Skip to content

Commit 7d86bd3

Browse files
merge: staging into feat/table-views
2 parents d5a12f1 + 3d72ab3 commit 7d86bd3

45 files changed

Lines changed: 4261 additions & 265 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

apps/docs/content/docs/en/workflows/blocks/pi.mdx

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ description: The Pi Coding Agent block runs an autonomous coding agent on a real
44
pageType: reference
55
---
66

7+
import { Callout } from 'fumadocs-ui/components/callout'
78
import { BlockPreview } from '@/components/workflow-preview'
89
import { FAQ } from '@/components/ui/faq'
910

@@ -37,7 +38,7 @@ Review Code uses a disposable sandbox for the repository, but the Pi harness and
3738
- Requires sandbox execution. The provider key stays in Sim, so hosted keys and BYOK are both supported.
3839
- Needs a **GitHub token** that can clone the repo and submit reviews (see [Setup](#setup-cloud-code-review)).
3940
- Needs the **Pull Request Number** to review.
40-
- Does not load skills or memory, and never exposes shell, write, edit, or arbitrary network tools to the reviewer.
41+
- Does not load skills or memory, and never exposes shell, write, or edit tools to the reviewer. Its only network access is [Internet Search](#internet-search), and only when you select a provider.
4142
- Rechecks the PR immediately before submission and pins the review to the exact checked-out head commit.
4243
- The deliverable is a **submitted review** — read `reviewUrl` and `commentsPosted`.
4344

@@ -63,6 +64,22 @@ The model that drives the agent. Defaults to `claude-sonnet-4-6`. The dropdown c
6364

6465
Your key for the chosen provider. On hosted Sim it is optional for Local Dev and Review Code runs (a hosted key is used and metered to your workspace). **Create PR requires your own key** because its model client runs in the sandbox. When the provider supports workspace BYOK, you can store the key in **Settings → BYOK** instead of entering it on the block.
6566

67+
### Internet Search
68+
69+
Off by default. Pick a provider — **Exa**, **Serper**, **Parallel AI**, or **Firecrawl** — and the agent gains a single `web_search` tool that returns a handful of results, each with a title, URL, snippet, and (where the provider reports one) a publication date. It works the same way in all three modes, and it is the agent's only network access in Review Code. The tool accepts at most 20 calls **per block execution**, which bounds accidental tool loops. A Pi block inside a Loop or Parallel gets that allowance again on every iteration, so bound the iteration count too if you care about what a single workflow run can spend.
70+
71+
Search always uses **your own key** for the selected provider, entered in the block's **Search API Key** field. That field is the only source: there is no workspace BYOK fallback and Sim never supplies a hosted search key, so unlike the model key this field appears on every deployment. Leave it empty and the run fails with a setup error before any sandbox is created. Changing the provider in the editor clears the field, so re-enter the key that belongs to the provider you picked — a workflow you import, fork, or update through the API keeps whatever key was saved, so check it there.
72+
73+
<Callout type="warn">
74+
**Create PR exposes both keys to the agent.** Create PR runs the model client and the search client *inside* the sandbox, so the model key and the search key reach it as environment variables — and Pi copies its own environment into every shell command it runs. Your prompt, or instructions injected through the contents of the cloned repository, can therefore read either key and write it anywhere the agent can reach, including into the pull request itself. Sim strips verbatim key text out of run output, but that does not stop an agent that encodes the value first.
75+
76+
This is why the search key has no **Settings → BYOK** fallback. Workspace BYOK keys belong to the workspace rather than to you — Sim only ever displays them masked, and only workspace admins can add or remove them — so resolving one here would let anyone who can run a Pi block read a credential they cannot otherwise see. Requiring the key on the block keeps the exposure to a key its author already holds. Scope it to something you are willing to rotate.
77+
</Callout>
78+
79+
Results are third-party data. The agent is instructed to treat them as quoted evidence and never to follow instructions found inside them — the same posture Pi takes toward repository contents.
80+
81+
Traffic goes both ways: the agent writes its own queries after reading the repository, so leave search on **None** in Review Code when the pull request comes from an untrusted fork of a private repo. Injected instructions in a diff could otherwise put repository text into a query sent to the provider.
82+
6683
### Repository (Create PR / Review Code)
6784

6885
- **Repository Owner / Repository Name** — the GitHub repo (for example `your-org` / `your-repo`).
@@ -176,6 +193,7 @@ Enable sandbox execution as for Create PR. BYOK is optional because the model cr
176193
{ question: "Why does Local Dev need a public hostname?", answer: "Sim connects over raw SSH and blocks localhost, LAN, and private/reserved addresses for safety. Expose the machine with a TCP tunnel such as `ngrok tcp 22` and use the tunnel's host and port. Tailscale's private 100.x addresses won't work for the same reason." },
177194
{ question: "What GitHub permissions does Create PR need?", answer: "A token that can clone, push, and open a PR. With a fine-grained token: select the repo and grant Contents: Read and write plus Pull requests: Read and write. With a classic token: the repo scope. For organization repos, the token must be SSO-authorized." },
178195
{ question: "What GitHub permissions does Review Code need?", answer: "A token that can clone the repo and submit a review. With a fine-grained token: Contents: Read plus Pull requests: Read and write. Push permission is not required. With a classic token: the repo scope. For organization repos, the token must be SSO-authorized." },
196+
{ question: "Can the agent search the web?", answer: "Only if you pick a provider under Internet Search — Exa, Serper, Parallel AI, or Firecrawl. That adds one web_search tool in every mode, backed by your own key for that provider, entered on the block; there is no BYOK fallback and Sim never supplies a search key. Leave it on None and the agent has no search tool at all." },
179197
{ question: "Can I give it Gmail, Slack, or other integrations?", answer: "Yes, in Local Dev via the Tools field. Selected Sim tools run through Sim with your connected credentials, the same as the Agent block, so the agent can act beyond the repo while it codes. MCP and custom tools aren't supported yet." },
180198
{ question: "Where do the changes or feedback go?", answer: "In Create PR, to a new branch and a pull request (read prUrl and branch). In Review Code, to a submitted GitHub review on the existing PR (read reviewUrl and commentsPosted). In Local Dev, the files are edited in place on the target machine — review them with git there. Create PR and Local Dev also return changedFiles and a diff." },
181199
{ question: "What happens when memory or context gets large?", answer: "For Create PR and Local Dev, Sim trims memory before the run based on the memory type, and Pi compacts older turns as needed. Review Code does not load or save memory because a malicious PR could otherwise expose or poison prior context." },

apps/sim/app/api/knowledge/[id]/connectors/[connectorId]/route.ts

Lines changed: 26 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,6 @@
11
import { AuditAction, AuditResourceType, recordAudit } from '@sim/audit'
22
import { db } from '@sim/db'
3-
import {
4-
document,
5-
embedding,
6-
knowledgeBase,
7-
knowledgeConnector,
8-
knowledgeConnectorSyncLog,
9-
} from '@sim/db/schema'
3+
import { document, embedding, knowledgeConnector, knowledgeConnectorSyncLog } from '@sim/db/schema'
104
import { createLogger } from '@sim/logger'
115
import { and, desc, eq, inArray, isNull, sql } from 'drizzle-orm'
126
import { type NextRequest, NextResponse } from 'next/server'
@@ -17,6 +11,7 @@ import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid'
1711
import { hasWorkspaceLiveSyncAccess } from '@/lib/billing/core/subscription'
1812
import { generateRequestId } from '@/lib/core/utils/request'
1913
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
14+
import { resolveCredentialTokenIdentity } from '@/lib/credentials/access'
2015
import { deleteDocumentStorageFiles } from '@/lib/knowledge/documents/service'
2116
import { cleanupUnusedTagDefinitions } from '@/lib/knowledge/tags/service'
2217
import { captureServerEvent } from '@/lib/posthog/server'
@@ -157,16 +152,6 @@ export const PATCH = withRouteHandler(async (request: NextRequest, context: Rout
157152
)
158153
}
159154

160-
const kbRows = await db
161-
.select({ userId: knowledgeBase.userId })
162-
.from(knowledgeBase)
163-
.where(eq(knowledgeBase.id, knowledgeBaseId))
164-
.limit(1)
165-
166-
if (kbRows.length === 0) {
167-
return NextResponse.json({ error: 'Knowledge base not found' }, { status: 404 })
168-
}
169-
170155
let accessToken: string | null = null
171156
if (connectorConfig.auth.mode === 'apiKey') {
172157
if (!existing.encryptedApiKey) {
@@ -183,9 +168,32 @@ export const PATCH = withRouteHandler(async (request: NextRequest, context: Rout
183168
{ status: 400 }
184169
)
185170
}
171+
const connectorWorkspaceId = writeCheck.knowledgeBase.workspaceId
172+
if (!connectorWorkspaceId) {
173+
return NextResponse.json(
174+
{ error: 'Knowledge base is missing workspace context' },
175+
{ status: 409 }
176+
)
177+
}
178+
/**
179+
* Resolve the credential's own account owner, not the knowledge base owner:
180+
* workspace credentials are shared, and token reads are scoped to
181+
* `account.userId`.
182+
*/
183+
const identity = await resolveCredentialTokenIdentity(
184+
existing.credentialId,
185+
connectorWorkspaceId
186+
)
187+
if (!identity) {
188+
return NextResponse.json(
189+
{ error: 'Credential is no longer usable in this workspace. Please reconnect it.' },
190+
{ status: 400 }
191+
)
192+
}
186193
accessToken = await refreshAccessTokenIfNeeded(
187194
existing.credentialId,
188-
kbRows[0].userId,
195+
// Service accounts mint their own token and ignore the acting user.
196+
identity.kind === 'oauth' ? identity.userId : auth.userId,
189197
`patch-${connectorId}`
190198
)
191199
}

apps/sim/app/workspace/[workspaceId]/knowledge/[id]/components/add-connector-modal/add-connector-modal.tsx

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,14 +92,28 @@ export function AddConnectorModal({
9292
)
9393

9494
const {
95-
data: credentials = [],
95+
data: rawCredentials = [],
9696
isLoading: credentialsLoading,
9797
refetch: refetchCredentials,
9898
} = useOAuthCredentials(connectorProviderId ?? undefined, {
9999
enabled: Boolean(connectorConfig) && !isApiKeyMode,
100100
workspaceId,
101101
})
102102

103+
/**
104+
* The credential list also returns the provider's service accounts, but
105+
* `ConnectorAuthConfig` has no service-account mode: the sync engine resolves
106+
* connector tokens through `refreshAccessTokenIfNeeded`, which passes no scopes
107+
* and drops the `cloudId`/`domain`/`authStyle` a service account resolves with.
108+
* Offering them here would surface credentials no connector can authenticate
109+
* with, so — like a workflow picker that has not opted in via
110+
* `allowServiceAccounts` — list OAuth accounts only.
111+
*/
112+
const credentials = useMemo(
113+
() => rawCredentials.filter((cred) => cred.type !== 'service_account'),
114+
[rawCredentials]
115+
)
116+
103117
useCredentialRefreshTriggers(refetchCredentials, connectorProviderId ?? '', workspaceId)
104118

105119
const effectiveCredentialId =

apps/sim/blocks/blocks/pi.test.ts

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
/**
2+
* @vitest-environment node
3+
*/
4+
import { describe, expect, it, vi } from 'vitest'
5+
6+
// The registry lives server-side (`keys.ts` reaches BYOK, which reaches the database) and the block
7+
// deliberately does not import it — no block imports from `@/executor`. This test is what ties the
8+
// two copies together, so adding a provider to one and not the other fails here.
9+
vi.mock('@/lib/api-key/byok', () => ({ getBYOKKey: vi.fn(), getApiKeyWithBYOK: vi.fn() }))
10+
11+
import { evaluateSubBlockCondition } from '@/lib/workflows/subblocks/visibility'
12+
import { PiBlock } from '@/blocks/blocks/pi'
13+
import { PI_SEARCH_PROVIDERS } from '@/executor/handlers/pi/keys'
14+
15+
const searchProviderField = PiBlock.subBlocks.find((subBlock) => subBlock.id === 'searchProvider')
16+
const searchApiKeyField = PiBlock.subBlocks.find((subBlock) => subBlock.id === 'searchApiKey')
17+
18+
function searchKeyVisible(values: Record<string, unknown>): boolean {
19+
return evaluateSubBlockCondition(searchApiKeyField?.condition, values)
20+
}
21+
22+
describe('Pi block search fields', () => {
23+
it('offers None plus exactly the providers the resolver knows, defaulting to None', () => {
24+
expect(searchProviderField?.type).toBe('dropdown')
25+
expect(searchProviderField?.defaultValue).toBe('none')
26+
27+
const options = searchProviderField?.options as { id: string; label: string }[]
28+
expect(options.map(({ id }) => id)).toEqual(['none', ...Object.keys(PI_SEARCH_PROVIDERS)])
29+
// Labels too: a mismatch here means the dropdown names a provider differently from the setup
30+
// error the run fails with.
31+
expect(options.slice(1).map(({ label }) => label)).toEqual(
32+
Object.values(PI_SEARCH_PROVIDERS).map(({ label }) => label)
33+
)
34+
})
35+
36+
// The same handling this block already gives githubToken, password, and privateKey.
37+
it('keeps the search key out of connections, references, and plain text', () => {
38+
expect(searchApiKeyField?.password).toBe(true)
39+
expect(searchApiKeyField?.paramVisibility).toBe('user-only')
40+
expect(searchApiKeyField?.connectionDroppable).toBe(false)
41+
})
42+
43+
it('declares the key as dependent on the provider, which is what clears it in the editor', () => {
44+
expect(searchApiKeyField?.dependsOn).toEqual(['searchProvider'])
45+
})
46+
47+
it('shows the key field only once a provider is selected', () => {
48+
expect(searchKeyVisible({ searchProvider: 'exa' })).toBe(true)
49+
expect(searchKeyVisible({ searchProvider: 'firecrawl' })).toBe(true)
50+
expect(searchKeyVisible({ searchProvider: 'none' })).toBe(false)
51+
expect(searchKeyVisible({ searchProvider: '' })).toBe(false)
52+
})
53+
54+
// A Pi block saved before this field existed has no stored value, and the serializer does not
55+
// inject subBlock defaults — so `undefined` has to behave like None here too.
56+
it('hides the key field on blocks saved before the field existed', () => {
57+
expect(searchKeyVisible({})).toBe(false)
58+
expect(searchKeyVisible({ searchProvider: undefined })).toBe(false)
59+
})
60+
61+
// The field is the only source for the search key — no workspace BYOK fallback, no hosted key —
62+
// so it has to be required. Safe despite the condition: the serializer's required check returns
63+
// early for fields that are not visible, which is what keeps a Pi block with search off from
64+
// failing validation over a key it does not need.
65+
it('requires the key, which the hidden case must not enforce', () => {
66+
expect(searchApiKeyField?.required).toBe(true)
67+
expect(searchKeyVisible({ searchProvider: 'none' })).toBe(false)
68+
expect(searchKeyVisible({})).toBe(false)
69+
})
70+
71+
// `inputs` is the block's type map, not the delivery mechanism — the handler reads resolved
72+
// params — but an undeclared input is a convention break the next block author would copy.
73+
it('declares both fields in the block input map', () => {
74+
expect(PiBlock.inputs.searchProvider).toBeDefined()
75+
expect(PiBlock.inputs.searchApiKey).toBeDefined()
76+
})
77+
})

0 commit comments

Comments
 (0)