diff --git a/.agents/repo.md b/.agents/repo.md index dd47826b14..9164b2f77c 100644 --- a/.agents/repo.md +++ b/.agents/repo.md @@ -435,6 +435,16 @@ default means deleting the override and fixing what surfaces: ## Contract debt ledger +- **The session-bound connector runner has no caller** — agent connector calls through the + sandbox bridge run on the in-process live runner (2026-10), so nothing starts a live + connector body as a `node -e` program in a session any more. The machinery for it stays: + `engine_exec_runner.ts` (`sandboxProgramRunnerForSession`), the sandbox-exec runner, `lib/connectors/portable-live.ts`, + `core/connectors/hostcall_token.ts`, the `/api/connectors/hostcall` route in + `domains/connectors/bridge-routes.ts` with its body limit in + `domains/sandbox/door-body-limit.ts`, the dispatcher's portable branch, the hostcall secret + in `backend/env.ts`, and the device relay's allowance for the route + (`services/sandbox/src/devices/relay-policy.ts`). Paying it down means deleting them together + with their tests; `runConnectorAction` no longer accepts a session to run in. - **Unbounded named-array lists on `/api/v1`** — `GET /automations`, `GET /projects/{id}/automations`, the two `…/versions` listings, `GET /projects/{id}/folders` (per level) and `GET /browser-sessions` answer the whole set with no `LIMIT`; declared diff --git a/services/platform/backend/core/connectors/hostcall_token.ts b/services/platform/backend/core/connectors/hostcall_token.ts index b493309c34..50a244fd0a 100644 --- a/services/platform/backend/core/connectors/hostcall_token.ts +++ b/services/platform/backend/core/connectors/hostcall_token.ts @@ -2,8 +2,10 @@ * Signed capability tokens for the connectors HOST-CALL endpoint — * the platform end of a live yaml-js body running out of process. * - * A live connector body executes inside the org's sandbox session - * (sandbox-exec runner), but its `ctx.http` stays PLATFORM-MEDIATED: the + * No caller runs a body this way today — every live body runs on the + * in-process live runner — and the path is listed as contract debt. When a + * live connector body executes inside the org's sandbox session + * (sandbox-exec runner), its `ctx.http` stays PLATFORM-MEDIATED: the * in-sandbox portable ctx round-trips every request to * `/api/connectors/hostcall`, where the real live host (allowlist, https, * response caps, Authorization injection) performs it. This token is what the diff --git a/services/platform/backend/core/node_only/sandbox/connectors_bridge.test.ts b/services/platform/backend/core/node_only/sandbox/connectors_bridge.test.ts index 6b3e77991a..9f35051535 100644 --- a/services/platform/backend/core/node_only/sandbox/connectors_bridge.test.ts +++ b/services/platform/backend/core/node_only/sandbox/connectors_bridge.test.ts @@ -47,7 +47,6 @@ const neverDispatches: Dispatch = () => { const BASE = { organizationId: 'org_1', - sessionId: 'session_1', userId: 'user_1', }; @@ -111,18 +110,15 @@ describe('dispatchBridgeConnectorImpl', () => { callArgs: { query: 'hello' }, }); - expect(runDispatch).toHaveBeenCalledWith( - expect.objectContaining({ - organizationId: 'org_1', - connector: 'tavily', - action: 'search', - input: { query: 'hello' }, - userId: 'user_1', - // The turn's own session doubles as the connector's out-of-process - // runner. - execSessionId: 'session_1', - }), - ); + // Exactly these: no session rides along, so the live body runs in the + // platform process and never in the calling turn's sandbox. + expect(runDispatch).toHaveBeenCalledWith({ + organizationId: 'org_1', + connector: 'tavily', + action: 'search', + input: { query: 'hello' }, + userId: 'user_1', + }); expect(result).toEqual({ status: 'ok', output: { results: [1] } }); }); diff --git a/services/platform/backend/core/node_only/sandbox/connectors_bridge.ts b/services/platform/backend/core/node_only/sandbox/connectors_bridge.ts index 7a5f8011ca..3c016de94e 100644 --- a/services/platform/backend/core/node_only/sandbox/connectors_bridge.ts +++ b/services/platform/backend/core/node_only/sandbox/connectors_bridge.ts @@ -121,7 +121,6 @@ export type BridgeDispatch = (args: { action: string; input: unknown; userId: string; - execSessionId: string; }) => Promise; /** Whether the org has an ACTIVE credential for a connector (the status @@ -175,7 +174,6 @@ export async function runBridgeConnectorImpl( dispatch: BridgeDispatch, args: { organizationId: string; - sessionId: string; userId: string; slug: string; operation: string; @@ -230,9 +228,10 @@ export async function runBridgeConnectorImpl( action: args.operation, input: args.callArgs ?? {}, userId: args.userId, - // The turn's own session doubles as the out-of-process runner for the - // connector's live body (the portable sandbox-exec convention). - execSessionId: args.sessionId, + // No session rides along: the connector's live body runs in the + // platform process, never in the calling turn's sandbox, where its + // program (credential secrets included) would sit on the process list + // of a session the agent itself runs in. }); if (isRecord(result) && result.status === 'approval-required') { const message = diff --git a/services/platform/backend/core/node_only/sandbox/engine_exec_runner.ts b/services/platform/backend/core/node_only/sandbox/engine_exec_runner.ts index a1a1c86d31..e117b235cb 100644 --- a/services/platform/backend/core/node_only/sandbox/engine_exec_runner.ts +++ b/services/platform/backend/core/node_only/sandbox/engine_exec_runner.ts @@ -1,7 +1,8 @@ 'use node'; /** - * The out-of-process CodeRunner, bound to ONE sandbox session. + * A sandbox session's one-shot program runner, the transport of the + * out-of-process CodeRunner. * * `lib/engine/runners/sandbox-exec.ts` owns the whole wire protocol (program * assembly, scope delivery, result extraction); the one thing it leaves to the @@ -11,27 +12,17 @@ * exec (`node -e `, output collected, runnerd enforcing the kill on * overrun — the spawner reports that as `errorCode: 'TIMEOUT'`). * - * PER-CALL, never global: the runner is handed to the dispatcher through its - * per-invocation context (`ctx.codeRunner`), so two concurrent invocations - * from different sessions/orgs can never share a transport — installing a - * session-bound runner into the process-global `setCodeRunner` slot would be - * a cross-tenant hazard. + * Nothing runs a connector body this way any more (every live body runs on + * the in-process runner, see the contract debt ledger); a runner built on it + * must stay per call, never installed in the process-global `setCodeRunner` + * slot two organizations share. */ import { randomUUID } from 'node:crypto'; -import type { CodeRunner } from '../../../../lib/engine/core/runner'; -import { - createSandboxExecRunner, - createSessionTransport, - type SandboxProgramRunner, -} from '../../../../lib/engine/runners/sandbox-exec'; +import type { SandboxProgramRunner } from '../../../../lib/engine/runners/sandbox-exec'; import { drainSessionExecResilient } from './helpers/session_client'; -/** An out-of-process boundary has a real payload ceiling; a connector body's - * input/secrets/config fit comfortably in a fraction of this. */ -const MAX_SCOPE_BYTES = 256 * 1024; - function fromBase64(b64: string): string { return Buffer.from(b64, 'base64').toString('utf8'); } @@ -62,12 +53,3 @@ export function sandboxProgramRunnerForSession( }; }; } - -/** The sandbox-exec CodeRunner for one session — hand it to the dispatcher - * via its per-invocation context. */ -export function codeRunnerForSession(sessionId: string): CodeRunner { - return createSandboxExecRunner( - createSessionTransport(sandboxProgramRunnerForSession(sessionId)), - { maxScopeBytes: MAX_SCOPE_BYTES }, - ); -} diff --git a/services/platform/backend/core/tasks/agent_run_host.connector_caller.test.ts b/services/platform/backend/core/tasks/agent_run_host.connector_caller.test.ts index a487bea193..5084d8c541 100644 --- a/services/platform/backend/core/tasks/agent_run_host.connector_caller.test.ts +++ b/services/platform/backend/core/tasks/agent_run_host.connector_caller.test.ts @@ -368,8 +368,12 @@ describe('a task run of an agent equipped with a connector', () => { input: { organizationSlug: 'tale' }, mode: 'live', caller: { kind: 'user', userId: 'user-starter' }, - execSessionId: 'pa-alice', }); + // Run in the platform process, never as a program in the agent's own + // session, whose process list would show the credential. + expect(runConnectorAction.mock.calls[0]?.[1]).not.toHaveProperty( + 'execSessionId', + ); // The forensic row names the member the call ran for. expect(io.toolCalls).toHaveLength(1); expect(io.toolCalls[0]).toContain('user-starter'); diff --git a/services/platform/backend/domains/connectors/bridge-routes.test.ts b/services/platform/backend/domains/connectors/bridge-routes.test.ts index 63eba07117..d7421198b5 100644 --- a/services/platform/backend/domains/connectors/bridge-routes.test.ts +++ b/services/platform/backend/domains/connectors/bridge-routes.test.ts @@ -11,7 +11,8 @@ * The second half pins WHOM a call acts for: the token's own user, or the * starter of the live task run on the exec the token names (`connectorCaller`), * read from the run on every call, and only while that person is still an - * active member. + * active member — and WHERE it runs: on the platform, never in the calling + * sandbox. */ import type { Sql } from 'postgres'; @@ -292,13 +293,62 @@ describe('POST /api/connectors/execute — whom a call acts for', () => { connector: 'glitchtip', action: 'list_import_issues', caller: { kind: 'user', userId: 'user_starter' }, - execSessionId: 'pa-agent_1', }); expect(toolCalls).toHaveLength(1); expect(toolCalls[0]).toContain('user_starter'); }, ); + it('runs the action’s live body on the platform, never in the calling sandbox [CONN-R13]', async () => { + tokenWith(TASK_TURN); + + await post('/execute', LIST_ISSUES); + + // No session for the body to run in: the door runs it in process, so + // the credential never reaches a program in the agent's own session. + expect(runConnectorAction.mock.calls[0]?.[1]).toMatchObject({ + mode: 'live', + }); + expect(runConnectorAction.mock.calls[0]?.[1]).not.toHaveProperty( + 'execSessionId', + ); + }); + + it('runs at most four of a session’s calls at once and stores no files [CONN-R14]', async () => { + tokenWith(TASK_TURN); + const pending: Array<() => void> = []; + runConnectorAction.mockImplementation( + () => + new Promise((resolve) => { + pending.push(() => resolve({ status: 'ok', output: [] })); + }), + ); + + const running = Array.from({ length: 4 }, () => + post('/execute', LIST_ISSUES), + ); + await vi.waitFor(() => expect(pending).toHaveLength(4)); + const refused = await post('/execute', LIST_ISSUES); + + expect(await refused.json()).toMatchObject({ + status: 'unavailable', + blockers: [{ code: 'busy' }], + }); + expect(runConnectorAction).toHaveBeenCalledTimes(4); + for (const call of runConnectorAction.mock.calls) { + expect(call[1]).toMatchObject({ storeFiles: false }); + } + + // A call that answered gives its place back. + pending.shift()?.(); + await running[0]; + const next = post('/execute', LIST_ISSUES); + await vi.waitFor(() => expect(pending).toHaveLength(4)); + for (const finish of pending) finish(); + await Promise.all([...running.slice(1), next]); + expect(runConnectorAction).toHaveBeenCalledTimes(5); + }); + it('acts for the member a REST start named (the api-key door) [CONN-R1]', async () => { runs.set('exec_1', { status: 'running', startedBy: 'api-key:user_1' }); tokenWith(TASK_TURN); diff --git a/services/platform/backend/domains/connectors/bridge-routes.ts b/services/platform/backend/domains/connectors/bridge-routes.ts index b607c7d517..6f20700919 100644 --- a/services/platform/backend/domains/connectors/bridge-routes.ts +++ b/services/platform/backend/domains/connectors/bridge-routes.ts @@ -44,10 +44,13 @@ import { runConnectorAction } from './service.ts'; * the task run on the exec the token names (`connectorCaller`), read * from the run on every call and only while that run is live; a call * runs only while that person is still an active member of the org. + * The action's live body runs here, in the platform process, like an + * automation's or chat's call — never in the calling sandbox. * - `hostcall` authenticates a one-run HMAC capability minted at dispatch, * bound to (org, connector, action, credential). It carries no secret: * the door re-resolves the credential itself, so a leaked token cannot - * become a credential. + * become a credential. No caller mints one today: every live body runs + * in process (the session-bound runner is listed as contract debt). * * The decision bodies are REUSED from the 0.4 bridge (one wording of every * refusal, for the model that relays it); only the dispatch and credential @@ -225,6 +228,14 @@ function isHostcallMethod(value: string): value is keyof typeof HTTP_VERBS { return value in HTTP_VERBS; } +/** Connector calls one sandbox session's agents may have running at once in + * this process: the four live execs a session had when each call ran inside + * it. A body now runs in the platform process, so the agent, which chooses + * how many calls it makes and how often it retries, gets a busy refusal + * past this instead of stacking bodies there. */ +const MAX_BRIDGE_CALLS_PER_SESSION = 4; +const bridgeCallsInFlight = new Map(); + export function createConnectorBridgeRoutes(deps: { sql: Sql }): Hono { const app = new Hono(); app.use('/execute', sandboxDoorBodyLimit(toolResultTooLarge)); @@ -277,26 +288,49 @@ export function createConnectorBridgeRoutes(deps: { sql: Sql }): Hono { if ('blocker' in caller) { return json(200, { status: 'unavailable', blockers: [caller.blocker] }); } - const result = await runBridgeConnectorImpl( - (dispatchArgs) => - runConnectorAction(deps.sql, { - organizationId: dispatchArgs.organizationId, - connector: dispatchArgs.connector, - action: dispatchArgs.action, - input: dispatchArgs.input, - mode: 'live', - caller: { kind: 'user', userId: dispatchArgs.userId }, - execSessionId: dispatchArgs.execSessionId, - }), - { - organizationId: auth.organizationId, - sessionId: auth.sessionId, - userId: caller.userId, - slug, - operation, - callArgs, - }, - ); + const running = bridgeCallsInFlight.get(auth.sessionId) ?? 0; + if (running >= MAX_BRIDGE_CALLS_PER_SESSION) { + return json(200, { + status: 'unavailable', + blockers: [ + { + code: 'busy', + guidance: + `This agent already has ${MAX_BRIDGE_CALLS_PER_SESSION} connector calls running. ` + + 'Wait for one of them to answer, then try this call again.', + }, + ], + }); + } + bridgeCallsInFlight.set(auth.sessionId, running + 1); + let result: Awaited>; + try { + result = await runBridgeConnectorImpl( + (dispatchArgs) => + runConnectorAction(deps.sql, { + organizationId: dispatchArgs.organizationId, + connector: dispatchArgs.connector, + action: dispatchArgs.action, + input: dispatchArgs.input, + mode: 'live', + caller: { kind: 'user', userId: dispatchArgs.userId }, + // An agent's read calls leave no files in the organization's + // store; an action that needs the store refuses instead. + storeFiles: false, + }), + { + organizationId: auth.organizationId, + userId: caller.userId, + slug, + operation, + callArgs, + }, + ); + } finally { + const left = (bridgeCallsInFlight.get(auth.sessionId) ?? 1) - 1; + if (left > 0) bridgeCallsInFlight.set(auth.sessionId, left); + else bridgeCallsInFlight.delete(auth.sessionId); + } await recordConnectorCall(deps.sql, { organizationId: auth.organizationId, sessionId: auth.sessionId, diff --git a/services/platform/backend/domains/connectors/service.runner.test.ts b/services/platform/backend/domains/connectors/service.runner.test.ts new file mode 100644 index 0000000000..c92075c18e --- /dev/null +++ b/services/platform/backend/domains/connectors/service.runner.test.ts @@ -0,0 +1,75 @@ +/** + * Which runner a live call gets, and what its host may touch: the connectors + * door decides both before the dispatcher runs. The dispatcher is replaced so + * the test reads exactly what the door hands it. + */ +import type { Sql } from 'postgres'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +const { executeConnectorAction } = vi.hoisted(() => ({ + executeConnectorAction: vi.fn(), +})); + +vi.mock('../../../lib/connectors/dispatcher.ts', async (importOriginal) => ({ + ...(await importOriginal< + typeof import('../../../lib/connectors/dispatcher.ts') + >()), + executeConnectorAction, +})); + +import { IN_PROCESS_LIVE_RUNNER_KIND } from '../../../lib/connectors/in-process-live.ts'; +import { runConnectorAction } from './service.ts'; + +// The host assembly only builds closures over the client; nothing queries. +// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- a stand-in no call reaches +const sql = {} as Sql; + +const handed = () => { + const args: unknown = executeConnectorAction.mock.calls[0]?.[0]; + if (typeof args !== 'object' || args === null || !('ctx' in args)) { + throw new Error('the door handed the dispatcher no context'); + } + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- shape checked above; the test reads its fields + return args.ctx as Record & { + codeRunner?: { kind(): string }; + }; +}; + +describe('runConnectorAction — the runner a live call gets', () => { + beforeEach(() => { + executeConnectorAction.mockReset(); + executeConnectorAction.mockResolvedValue({ status: 'ok', output: {} }); + }); + + it('runs a live body on the in-process runner with no sandbox in the path [CONN-R13]', async () => { + await runConnectorAction(sql, { + organizationId: 'org_1', + connector: 'tavily', + action: 'search', + input: { query: 'tale' }, + mode: 'live', + caller: { kind: 'user', userId: 'user_1' }, + }); + + const ctx = handed(); + expect(ctx.codeRunner?.kind()).toBe(IN_PROCESS_LIVE_RUNNER_KIND); + expect(ctx).not.toHaveProperty('portableHost'); + expect(ctx).toHaveProperty('blobs'); + }); + + it('gives an agent bridge call no file store [CONN-R14]', async () => { + await runConnectorAction(sql, { + organizationId: 'org_1', + connector: 'gmail', + action: 'get_attachments', + input: {}, + mode: 'live', + caller: { kind: 'user', userId: 'user_1' }, + storeFiles: false, + }); + + const ctx = handed(); + expect(ctx.codeRunner?.kind()).toBe(IN_PROCESS_LIVE_RUNNER_KIND); + expect(ctx).not.toHaveProperty('blobs'); + }); +}); diff --git a/services/platform/backend/domains/connectors/service.ts b/services/platform/backend/domains/connectors/service.ts index 5452329f14..dddeb2520f 100644 --- a/services/platform/backend/domains/connectors/service.ts +++ b/services/platform/backend/domains/connectors/service.ts @@ -17,14 +17,11 @@ import { type SandboxScriptRunner, type WorkflowConversationStore, } from '../../../lib/connectors/natives/index.ts'; -import type { PortableHostCall } from '../../../lib/connectors/portable-live.ts'; import { hasCodeRunner, setCodeRunner, - type CodeRunner, } from '../../../lib/engine/core/runner.ts'; import { nodeVmRunner } from '../../../lib/engine/runners/node-vm.ts'; -import { signHostcallToken } from '../../core/connectors/hostcall_token.ts'; import { ingestEmails, ingestSentEmails, @@ -32,7 +29,6 @@ import { querySyncCursor, syncMailbox, } from '../../core/conversations/sync_mailbox.ts'; -import { codeRunnerForSession } from '../../core/node_only/sandbox/engine_exec_runner.ts'; import { createCtxShim } from '../../lib/ctx-shim.ts'; import { evaluateApprovalGate } from '../approvals/gate.ts'; import { createAuditLog } from '../audit_logs/service.ts'; @@ -63,9 +59,9 @@ import { pgTaskStore } from './task-store.ts'; * run's own workflow session over the automations ctx shim — the same * session the run's agent nodes use. A live yaml-js body runs on the * host-capable in-process runner (the shipped catalog is trusted code, and - * `ctx.http` is the same policed live host either way) unless the caller - * owns a sandbox session, in which case the body runs out of process on the - * session-bound runner and phones its host calls home. + * `ctx.http` is the same policed live host either way) — the external-turn + * bridge included, so a sandboxed agent's call never runs its body, or + * carries its credential, inside the agent's own session. */ let mailTransportOverride: MailTransport | undefined; @@ -257,13 +253,12 @@ export interface RunConnectorArgs { caller: ConnectorCaller; idempotencyKey?: string; /** - * A live sandbox session to run a yaml-js body IN, out of process. Only - * the external-turn bridge owns one; every other live caller (automation - * runs, chat, the platform's own senders) runs the body on the in-process - * live runner. The runner is per-invocation ON PURPOSE — the - * process-global slot is shared by every concurrent org. + * Whether a live body may store files through `ctx.files` (default yes). + * The agent bridge says no: an agent's read calls should not leave blobs + * and file records in the organization's store, and an action that needs + * the store refuses instead, as it always did for agent calls. */ - execSessionId?: string; + storeFiles?: boolean; /** * The caller's own stop: an automation run's turn passes its signal so a * live call still running when the server is shutting down is cut @@ -283,33 +278,6 @@ export async function runConnectorAction( args: RunConnectorArgs, ): Promise { assembleConnectorHost(sql); - // Out-of-process live execution: the session-bound sandbox-exec runner - // plus the one-run capability its in-sandbox façade phones home with. No - // HMAC root ⇒ no token ⇒ the body runs in process instead, where its - // `ctx.http` is mediated by the live host directly. - let portableRunner: - | { codeRunner: CodeRunner; portableHost: PortableHostCall } - | undefined; - if (args.execSessionId !== undefined && args.mode === 'live') { - const token = await signHostcallToken({ - org: args.organizationId, - connector: args.connector, - action: args.action, - ...(args.credentialRef !== undefined - ? { credentialRef: args.credentialRef } - : {}), - }); - if (token === null) { - console.warn( - '[connectors] no HMAC root configured — live sandbox execution unavailable, running the body in process', - ); - } else { - portableRunner = { - codeRunner: codeRunnerForSession(args.execSessionId), - portableHost: { url: connectorsHostcallUrlForSessions(), token }, - }; - } - } return executeConnectorAction({ connector: args.connector, action: args.action, @@ -325,32 +293,25 @@ export async function runConnectorAction( approvals: approvalGate(sql), audit: auditSink(sql), // `ctx.files` for an in-process live body: the org's own blob store. - blobs: connectorBlobSink(sql, { - organizationId: args.organizationId, - connector: args.connector, - caller: args.caller, - }), + ...(args.storeFiles !== false + ? { + blobs: connectorBlobSink(sql, { + organizationId: args.organizationId, + connector: args.connector, + caller: args.caller, + }), + } + : {}), ...(args.idempotencyKey !== undefined ? { idempotencyKey: args.idempotencyKey } : {}), ...(args.signal !== undefined ? { signal: args.signal } : {}), - // A live yaml-js body needs a host-capable runner: the session-bound - // one when the caller owns a session, the in-process one otherwise. - // The process-global slot stays the data-only runner for mock bodies. - ...(portableRunner !== undefined - ? portableRunner - : args.mode === 'live' - ? { codeRunner: inProcessLive } - : {}), + // A live yaml-js body needs a host-capable runner: the in-process one, + // never a `node -e` program in a sandbox session, whose command line + // would carry the body's scope (credential secrets included) to every + // process of that session. The process-global slot stays the + // data-only runner for mock bodies. + ...(args.mode === 'live' ? { codeRunner: inProcessLive } : {}), }, }); } - -/** Where a session's CONTAINER reaches the host-call door (the same origin - * contract the staging callback and the tools bridge use). */ -function connectorsHostcallUrlForSessions(): string { - const origin = ( - process.env.SANDBOX_HTTP_API_BASE_URL ?? 'http://backend-api:3005' - ).replace(/\/$/, ''); - return `${origin}/api/connectors/hostcall`; -} diff --git a/services/platform/backend/domains/connectors/spec.md b/services/platform/backend/domains/connectors/spec.md index bb5f35fa40..5dd30f8872 100644 --- a/services/platform/backend/domains/connectors/spec.md +++ b/services/platform/backend/domains/connectors/spec.md @@ -4,9 +4,9 @@ A connector lets an agent or an automation act in an outside system: read a mailbox, file a ticket, fetch issues. These rules cover whom such a call acts for, when it is refused, how an -account is connected by signing in at the outside system, and what importing tasks through a -connector may write. The catalog of connectors and what each one can do are not covered; see -Not yet. +account is connected by signing in at the outside system, what importing tasks through a +connector may write, and where an agent's call runs. The catalog of connectors and what each +one can do are not covered; see Not yet. ## Whom a connector call acts for @@ -118,6 +118,29 @@ leaves the task's status and its description as they are in Tale. - **Example**: An issue was imported and Mia moved its task to Done. The import runs again → the task is still Done, and there is one task for the issue. +## Where a connector call runs + +### CONN-R13 · An agent's connector call runs on the platform, never inside the agent's sandbox + +The connector's code runs in the platform with the organization's credential, and the +sandbox gets back only the result. No process of the agent's sandbox is handed the +credential for the call. + +- **Example**: Mia's agent searches the web through the Tavily connector → the search runs + on the platform with the organization's Tavily key, and nothing in Mia's sandbox sees + the key. + +### CONN-R14 · An agent's connector calls are bounded on the platform + +One sandbox session's agents have at most four connector calls running at once; a further +call is refused as busy and can be tried again. A call that outlives its time limit can no +longer reach the outside system, and an agent's call stores no files in the organization's +file store. + +- **Example**: Mia's agent starts five Google Drive listings at once → four run and the + fifth is refused as busy; a listing still paging after its minute is cut off at its next + request, and a Gmail attachment the agent reads is not saved to the organization's files. + ## Not yet - **The catalog of connectors**, what each can do, and which need an approval before they diff --git a/services/platform/lib/connectors/dispatcher.test.ts b/services/platform/lib/connectors/dispatcher.test.ts index 8fc8703453..aa93619842 100644 --- a/services/platform/lib/connectors/dispatcher.test.ts +++ b/services/platform/lib/connectors/dispatcher.test.ts @@ -517,6 +517,79 @@ describe('live yaml-js under the sandbox-exec runner (portable convention)', () }); describe('live yaml-js backend', () => { + it("stops a live body's host calls at its time limit [CONN-R14]", async () => { + // A body that pages through a vendor without bound, like a recursive + // listing over a large account. In this process nothing can stop the body + // itself, so the host must refuse every request once the limit passed. + const PAGER = connectorSchema.parse({ + name: 'pager', + displayName: 'Pager', + description: 'Pages through a vendor without bound.', + endpointMode: 'fixed', + allowedHosts: ['api.demo.test'], + auth: [{ method: 'bearer' }], + actions: [ + { + name: 'list_all', + description: 'Read every page.', + effects: 'read', + input: { type: 'object', properties: {} }, + output: '{ pages: number }', + mock: 'return { pages: 0 };', + backend: { + kind: 'yaml-js', + live: [ + 'let pages = 0;', + 'while (true) {', + " await ctx.http.get('https://api.demo.test/page?n=' + pages);", + ' pages += 1;', + '}', + ].join('\n'), + }, + }, + ], + }); + installConnectorCatalog([...shipped, DEMO, PAGER]); + const issued: Array<{ atMs: number; aborted: boolean }> = []; + fetchStub.mockImplementation(async (_url: string, init: RequestInit) => { + issued.push({ atMs: Date.now(), aborted: init.signal?.aborted === true }); + if (init.signal?.aborted) throw new DOMException('aborted', 'AbortError'); + await new Promise((resolve) => setTimeout(resolve, 20)); + return new Response('{}', { + status: 200, + headers: { 'content-type': 'application/json' }, + }); + }); + + await expect( + executeConnectorAction({ + connector: 'pager', + action: 'list_all', + input: {}, + caller: { kind: 'user', userId: 'u1' }, + ctx: { + organizationId: ORG, + mode: 'live', + credentials: resolver(), + codeRunner: inProcessLiveRunner(), + timeoutMs: 150, + }, + }), + ).rejects.toMatchObject({ code: 'LIVE_BODY_FAILED' }); + expect(issued.length).toBeGreaterThan(0); + // The host refuses from 100 ms past the limit; give it that and a margin. + await new Promise((resolve) => setTimeout(resolve, 200)); + const settled = issued.length; + await new Promise((resolve) => setTimeout(resolve, 300)); + + // The body stopped calling, and whatever it tried after the host's + // grace was refused before reaching the vendor. + expect(issued.length).toBe(settled); + const lastLive = issued.findLastIndex((call) => !call.aborted); + expect(issued.slice(lastLive + 1).every((call) => call.aborted)).toBe(true); + expect(issued.filter((call) => call.aborted).length).toBeLessThanOrEqual(1); + }); + it('refuses live on the data-only node-vm runner, before any host work', async () => { // The bundled in-process runner cannot carry `ctx.secrets.get` or the // HTTP host across its JSON boundary — the dispatcher must say so up diff --git a/services/platform/lib/connectors/dispatcher.ts b/services/platform/lib/connectors/dispatcher.ts index 0eda1e427f..7dae340d23 100644 --- a/services/platform/lib/connectors/dispatcher.ts +++ b/services/platform/lib/connectors/dispatcher.ts @@ -61,6 +61,8 @@ const MOCK_TIMEOUT_MS = 2000; /** A live body may chain several vendor calls, each individually capped by the * host, so its own ceiling is generous. */ const DEFAULT_LIVE_TIMEOUT_MS = 60_000; +/** How long after a live body's time limit its host calls start refusing. */ +const HOST_ABORT_GRACE_MS = 100; // ------------------------------------------------------------------ catalog @@ -321,11 +323,10 @@ export interface ConnectorDispatchContext { */ signal?: AbortSignal; /** - * Per-invocation CodeRunner override for the LIVE yaml-js path. A caller - * with a sandbox session hands in the session-bound out-of-process runner - * here — never through the process-global `setCodeRunner` slot, which two - * concurrent orgs share. Mock bodies always run on the global runner (pure, - * data-only, no host). + * Per-invocation CodeRunner override for the LIVE yaml-js path: every + * live caller hands in the in-process live runner here — never through the + * process-global `setCodeRunner` slot, which two concurrent orgs share. + * Mock bodies always run on the global runner (pure, data-only, no host). */ codeRunner?: CodeRunner; /** @@ -470,6 +471,15 @@ function resolveAction(connector: Connector, name: string): ConnectorAction { return action; } +/** The caller's stop and `deadline` as one signal: aborted by whichever + * fires first. */ +function anySignal( + stop: AbortSignal | undefined, + deadline: AbortSignal, +): AbortSignal { + return stop === undefined ? deadline : AbortSignal.any([stop, deadline]); +} + /** * Run a live body unless the caller has stopped, and stop waiting for it the * moment the caller does: the rejection is `INTERRUPTED`, and the body's own @@ -699,7 +709,7 @@ export async function executeConnectorAction( `${nodeType} has a live body, but this deployment's code runner is the data-only node-vm one, which cannot reach credentials or the network`, { ...where, - hint: 'pass a host-capable runner as ctx.codeRunner: inProcessLiveRunner() for the shipped catalog, or the session-bound sandbox-exec runner (with ctx.portableHost) when the caller owns a sandbox session', + hint: 'pass a host-capable runner as ctx.codeRunner: inProcessLiveRunner() for the shipped catalog', }, ); } @@ -838,6 +848,23 @@ export async function executeConnectorAction( // host-capable in-process runner). Building the host is itself // policed — a credential pointing outside the connector's allowlist is // refused here — so it shares the block whose failures are recorded. + // + // Nothing in this process can stop a yaml-js body at its time limit, + // but its host calls can be stopped: shortly past the limit every + // ctx.http and ctx.files request rejects, so the body unwinds at its + // next host call instead of calling the vendor on after its caller was + // released. The grace lets the caller's own time-limit error land + // first, rather than the aborted request it causes. + const hostSignal = + nativeImpl === undefined && backend.kind === 'yaml-js' + ? anySignal( + ctx.signal, + AbortSignal.timeout( + (ctx.timeoutMs ?? DEFAULT_LIVE_TIMEOUT_MS) + + HOST_ABORT_GRACE_MS, + ), + ) + : ctx.signal; const host = createLiveHost({ connector, action: action.name, @@ -849,7 +876,7 @@ export async function executeConnectorAction( authHeader: credential.authHeader, }), ...(ctx.blobs !== undefined && { blobs: ctx.blobs }), - ...(ctx.signal !== undefined && { signal: ctx.signal }), + ...(hostSignal !== undefined && { signal: hostSignal }), }); const connectorCtx: ConnectorContext = { diff --git a/services/platform/lib/connectors/in-process-live.ts b/services/platform/lib/connectors/in-process-live.ts index 4d37eb407e..e550cb5621 100644 --- a/services/platform/lib/connectors/in-process-live.ts +++ b/services/platform/lib/connectors/in-process-live.ts @@ -5,11 +5,9 @@ * A live body needs the mediated host in hand — `ctx.http` (the allowlisted, * SSRF-policed fetch), `ctx.secrets.get`, `ctx.files` — and those are * functions. The bundled node-vm runner is data-only by contract (its scope - * crosses as JSON), so it can never carry them; the sandbox-exec runner - * carries them by round-tripping every call to the host-call endpoint, but - * only a caller that owns a sandbox session can use it. Automation runs and - * chat own none, which left every live yaml-js action refusing outside the - * bridge. + * crosses as JSON), so it can never carry them. Every live caller runs the + * catalog's bodies here: automation runs, chat, the platform's own senders + * and an agent's connector calls through the sandbox bridge. * * TRUST: this runner is NOT a security boundary and must only ever run the * catalog under `configs/platform/system/connectors/` — code that ships with @@ -21,16 +19,15 @@ * the sandbox; this module's `runBody` only accepts the async live shape and * hands everything else to the data-only backend. * - * TIME LIMIT: `limits.timeoutMs` bounds the CALLER's wait, not the body. In - * this realm there is no isolate to tear down, so a body whose await - * outlives the deadline keeps running in the backend process until that - * await settles, and its result is dropped. What it can still do is bounded - * by the host it holds — every `ctx.http` call goes through the policed live - * host with its own per-request timeout, `ctx.files` writes to the org's own - * store — so an overrun costs a request slot and some memory, never a policy. - * Cancelling the body itself (an AbortSignal threaded into the live host's - * fetch) is not wired; a catalog body is expected to make one or a few - * bounded vendor calls. + * TIME LIMIT: `limits.timeoutMs` bounds the CALLER's wait here. In this + * realm there is no isolate to tear down, so a body whose await outlives the + * deadline keeps running in the backend process until that await settles, + * and its result is dropped. The dispatcher hands the body's host a signal + * that aborts at the same limit, so from then on every `ctx.http` and + * `ctx.files` request rejects and the body unwinds at its next host call; + * only work between host calls runs on. An overrun therefore costs a request + * slot and some memory, never a policy, and an agent retrying a slow call + * cannot pile up bodies that keep calling the vendor. */ import vm from 'node:vm'; diff --git a/services/platform/tests/manual/reference/automation.md b/services/platform/tests/manual/reference/automation.md index f4495ca203..b752691bc8 100644 --- a/services/platform/tests/manual/reference/automation.md +++ b/services/platform/tests/manual/reference/automation.md @@ -1093,4 +1093,5 @@ Scroll-responsive navigation is covered by `packages/ui/src/hooks/use-scroll-com | [automations](../suites/automations.md) / [tasks](../suites/tasks.md) | Protocol cutover holds unfinished legacy runs without inventing effect outcomes. The real boot transaction and its schema-bound ledger fence stale snapshots; old claim/progress writes, held-task starts and destructive evidence changes refuse. An exact-identity acknowledged stop request records one operator decision while retaining the hold, task exclusion and original asks. | ✅ unit + real PostgreSQL | `backend/domains/automations/legacy-protocol.integration.ts`, `backend/domains/automations/legacy-quarantine.test.ts`, `backend/domains/automations/routes.project-scope.test.ts`, `backend/domains/tasks/retire.test.ts`, `tests/guards/automation-legacy-fixture.test.ts`, `backend/domains/automations/legacy-agent-flow.integration.ts`, `tests/guards/automation-legacy-agent-flow.test.ts` (complete released start/resume bodies and actual old run/ask SQL; external ports record requested effects only); already-admitted effects are not asserted undone, and requested token expiry does not prove gateway-key retirement | | [automations](../suites/automations.md) | Five logical execution jobs use one protocol-to-physical queue mapping. Independent old/new workers cannot consume each other's execution jobs; enqueue, get/cancel, handover, recovery and drain keep their existing budgets and truthful legacy census. | ✅ unit + real PostgreSQL | `backend/jobs/automation-protocol.test.ts`, `backend/jobs/automation-protocol.integration.ts`, `backend/domains/control/service.test.ts`, `backend/domains/sandbox/recovery.test.ts`; the native helpers run before ordinary workers | | [automations](../suites/automations.md) | Public run API projects safe legacy hold facts in organization and project scopes; stop requests require the exact hold identity and acknowledgement, authenticated actor and existing write authority; stale and wrong-scope requests refuse without releasing the hold | 🔶 REST contract and OpenAPI tests; native stop and migration outcomes remain separate integration proofs | `backend/rest/v1-automations.contract.test.ts`, `backend/rest/v1-automations.project-scope.test.ts`, `scripts/openapi/spec.test.ts` | +| [connectors](../suites/connectors.md) | An agent's connector call through the in-sandbox bridge runs the action's live body in the platform process, like an automation's or chat's call, never as a `node -e` program in the agent's own session (whose command line carried the credential's secrets, readable by every process of that session, and which took one of its live-exec places); the bridge's dispatch carries no session. The bridge runs at most four of a session's calls at once (a further one is refused as busy), gives agent calls no file store, and a body past its time limit can no longer reach the outside system | ✅ backend | `backend/domains/connectors/service.runner.test.ts` (the door hands a live call the in-process runner, and a bridge call no file store), `backend/domains/connectors/bridge-routes.test.ts` (live mode, no session, the four-call cap), `lib/connectors/dispatcher.test.ts` (no host request after the time limit), `backend/core/node_only/sandbox/connectors_bridge.test.ts` (the dispatch's exact arguments), `backend/core/tasks/agent_run_host.connector_caller.test.ts` (a task run's call routed through the real hosts with the door mocked) | | [chat](../suites/chat.md) | Attachment permissions are checked before parking and before rebuilding history or regenerating a turn; preflight failures retain text only, metadata uses the current organization and reader, and denied document reads do not queue indexing. Real PostgreSQL probes cover same-organization and cross-organization audio denial through captured model requests, with an allowed own-audio control. | ✅ unit + real PostgreSQL | `backend/domains/chat/attachment-privacy.test.ts`, `deferred-sends.test.ts` and the `checkChatDeferredAuto` lane in `backend/integration-check.ts`; existing REST and arena suites cover surrounding caller contracts; door-level privacy execution remains separate |