From e5a5cb2f3ea3939e33c8c0b4b363cf5598f9c7f8 Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Thu, 8 Oct 2026 13:24:15 +0200 Subject: [PATCH 1/5] fix(platform): run agent connector calls in process, not in the sandbox The in-sandbox connectors bridge passed the turn's own session as execSessionId, so each live yaml-js body ran as `node -e ` in the agent's session. The program embeds the body's scope as a string literal, credential.secrets included: while the call ran, the org's raw connector key sat on a command line any process of that session (the agent, same uid) could read through /proc//cmdline or ps. Each call also paid a Node cold start (~40 ms, ~48 MB), took one of the session's four live-exec places (parallel tool calls then failed with "sandbox produced no result"), and added ~150-250 ms. The bridge now dispatches without a session, so the body runs on the in-process live runner that automation runs and chat already use: the shipped catalog is the only code it runs (organizations cannot upload connector bodies), ctx.http is the same policed live host, and the credential stays in the platform process. The connectors spec states it as CONN-R13, held by the bridge route test. No caller passes execSessionId any more. The session-bound path it reaches (the sandbox-exec runner, engine_exec_runner, portable-live, the hostcall token and route, and the device relay's allowance for that route in the sandbox service) is left in place: removing it spans the platform's engine, routes and env and the sandbox service, which is not a self-contained change. --- .../sandbox/connectors_bridge.test.ts | 22 ++++++++----------- .../node_only/sandbox/connectors_bridge.ts | 9 ++++---- .../agent_run_host.connector_caller.test.ts | 6 ++++- .../domains/connectors/bridge-routes.test.ts | 19 ++++++++++++++-- .../domains/connectors/bridge-routes.ts | 4 ++-- .../backend/domains/connectors/service.ts | 20 ++++++++++------- .../backend/domains/connectors/spec.md | 18 ++++++++++++--- .../tests/manual/reference/automation.md | 1 + 8 files changed, 65 insertions(+), 34 deletions(-) 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/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..77be4ba43d 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,27 @@ 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('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..f38ae0dc6c 100644 --- a/services/platform/backend/domains/connectors/bridge-routes.ts +++ b/services/platform/backend/domains/connectors/bridge-routes.ts @@ -44,6 +44,8 @@ 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 @@ -286,11 +288,9 @@ export function createConnectorBridgeRoutes(deps: { sql: Sql }): Hono { 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, diff --git a/services/platform/backend/domains/connectors/service.ts b/services/platform/backend/domains/connectors/service.ts index 5452329f14..8150b2615e 100644 --- a/services/platform/backend/domains/connectors/service.ts +++ b/services/platform/backend/domains/connectors/service.ts @@ -63,9 +63,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,11 +257,15 @@ 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. + * A live sandbox session to run a yaml-js body IN, out of process. No + * caller passes one: every live caller — automation runs, chat, the + * platform's own senders and the external-turn bridge — runs the body on + * the in-process live runner. The bridge must not: the session-bound + * runner starts the body as a `node -e` program in the agent's own + * session, with its scope (credential secrets included) on the command + * line every process of that session can read. The runner is + * per-invocation ON PURPOSE — the process-global slot is shared by every + * concurrent org. */ execSessionId?: string; /** diff --git a/services/platform/backend/domains/connectors/spec.md b/services/platform/backend/domains/connectors/spec.md index bb5f35fa40..751f0c352a 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,18 @@ 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 reads GlitchTip issues through the connector → the call runs on + the platform with the organization's GlitchTip token, and nothing in Mia's sandbox sees + the token. + ## Not yet - **The catalog of connectors**, what each can do, and which need an approval before they diff --git a/services/platform/tests/manual/reference/automation.md b/services/platform/tests/manual/reference/automation.md index 0501535a5f..4c003ead2e 100644 --- a/services/platform/tests/manual/reference/automation.md +++ b/services/platform/tests/manual/reference/automation.md @@ -1091,3 +1091,4 @@ 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 | ✅ backend | `backend/domains/connectors/bridge-routes.test.ts` (the connectors spec's rule on where a call runs: live mode, no session), `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 end to end) | From 075f021bceaef3b12315b12bcc06e4b93834fee7 Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Thu, 8 Oct 2026 14:16:10 +0200 Subject: [PATCH 2/5] fix(platform): bound agent connector calls that run in process Moving agent bridge calls onto the in-process live runner lost two bounds the sandbox gave them: four live execs per session, and a kill when a body overran its deadline. In the shared backend process the deadline only released the caller; the body went on calling its vendor, and an agent retrying a slow call (a recursive Drive listing on a large account) started another body each time. Bridge calls also gained ctx.files, so an agent's read of an attachment stored blobs and file records in the organization's store, which the sandbox path never did. - A yaml-js body's host gets a signal that aborts at the body's time limit, so every ctx.http and ctx.files request after it rejects and the body unwinds at its next host call (a test shows 9 vendor requests after the limit without it, none with it). - The bridge runs at most four of a session's calls at once per backend process; a further call gets a busy refusal the agent can retry. - Bridge calls run without a file store, as they always did. - runConnectorAction no longer accepts a session to run a body in; the now unused session-bound machinery is recorded in the contract debt ledger, and comments that described it as live are corrected. CONN-R14 states the bounds; a service-level test holds the runner choice (CONN-R13) with a yaml-js example instead of a native connector. --- .agents/repo.md | 10 +++ .../backend/core/connectors/hostcall_token.ts | 6 +- .../domains/connectors/bridge-routes.test.ts | 35 ++++++++ .../domains/connectors/bridge-routes.ts | 72 +++++++++++----- .../domains/connectors/service.runner.test.ts | 75 +++++++++++++++++ .../backend/domains/connectors/service.ts | 83 +++++-------------- .../backend/domains/connectors/spec.md | 17 +++- .../lib/connectors/dispatcher.test.ts | 71 ++++++++++++++++ .../platform/lib/connectors/dispatcher.ts | 34 ++++++-- .../lib/connectors/in-process-live.ts | 27 +++--- .../tests/manual/reference/automation.md | 1 + 11 files changed, 322 insertions(+), 109 deletions(-) create mode 100644 services/platform/backend/domains/connectors/service.runner.test.ts diff --git a/.agents/repo.md b/.agents/repo.md index 65caaf63dc..893ef562ec 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` (`codeRunnerForSession`), `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/domains/connectors/bridge-routes.test.ts b/services/platform/backend/domains/connectors/bridge-routes.test.ts index 77be4ba43d..d7421198b5 100644 --- a/services/platform/backend/domains/connectors/bridge-routes.test.ts +++ b/services/platform/backend/domains/connectors/bridge-routes.test.ts @@ -314,6 +314,41 @@ describe('POST /api/connectors/execute — whom a call acts for', () => { ); }); + 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 f38ae0dc6c..6f20700919 100644 --- a/services/platform/backend/domains/connectors/bridge-routes.ts +++ b/services/platform/backend/domains/connectors/bridge-routes.ts @@ -49,7 +49,8 @@ import { runConnectorAction } from './service.ts'; * - `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 @@ -227,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)); @@ -279,24 +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 }, - }), - { - organizationId: auth.organizationId, - 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 8150b2615e..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'; @@ -257,17 +253,12 @@ export interface RunConnectorArgs { caller: ConnectorCaller; idempotencyKey?: string; /** - * A live sandbox session to run a yaml-js body IN, out of process. No - * caller passes one: every live caller — automation runs, chat, the - * platform's own senders and the external-turn bridge — runs the body on - * the in-process live runner. The bridge must not: the session-bound - * runner starts the body as a `node -e` program in the agent's own - * session, with its scope (credential secrets included) on the command - * line every process of that session can read. 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 @@ -287,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, @@ -329,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 751f0c352a..5dd30f8872 100644 --- a/services/platform/backend/domains/connectors/spec.md +++ b/services/platform/backend/domains/connectors/spec.md @@ -126,9 +126,20 @@ The connector's code runs in the platform with the organization's credential, an sandbox gets back only the result. No process of the agent's sandbox is handed the credential for the call. -- **Example**: Mia's agent reads GlitchTip issues through the connector → the call runs on - the platform with the organization's GlitchTip token, and nothing in Mia's sandbox sees - the token. +- **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 diff --git a/services/platform/lib/connectors/dispatcher.test.ts b/services/platform/lib/connectors/dispatcher.test.ts index 8fc8703453..cf36559e6d 100644 --- a/services/platform/lib/connectors/dispatcher.test.ts +++ b/services/platform/lib/connectors/dispatcher.test.ts @@ -517,6 +517,77 @@ 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' }); + const releasedAtMs = Date.now(); + const issuedByRelease = issued.length; + expect(issuedByRelease).toBeGreaterThan(0); + await new Promise((resolve) => setTimeout(resolve, 200)); + + // At most the one request in flight at the limit went out after it, and + // the host refused it; nothing reached the vendor afterwards. + const late = issued.filter((call) => call.atMs >= releasedAtMs); + expect(late.length).toBeLessThanOrEqual(1); + expect(late.every((call) => call.aborted)).toBe(true); + }); + 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..7dbe8a2337 100644 --- a/services/platform/lib/connectors/dispatcher.ts +++ b/services/platform/lib/connectors/dispatcher.ts @@ -321,11 +321,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 +469,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 +707,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 +846,18 @@ 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: 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. + const hostSignal = + nativeImpl === undefined && backend.kind === 'yaml-js' + ? anySignal( + ctx.signal, + AbortSignal.timeout(ctx.timeoutMs ?? DEFAULT_LIVE_TIMEOUT_MS), + ) + : ctx.signal; const host = createLiveHost({ connector, action: action.name, @@ -849,7 +869,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 4c003ead2e..f74ef99942 100644 --- a/services/platform/tests/manual/reference/automation.md +++ b/services/platform/tests/manual/reference/automation.md @@ -1092,3 +1092,4 @@ Scroll-responsive navigation is covered by `packages/ui/src/hooks/use-scroll-com | [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 | ✅ backend | `backend/domains/connectors/bridge-routes.test.ts` (the connectors spec's rule on where a call runs: live mode, no session), `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 end to end) | +| [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) | From 0964095c183121efc31c527d23237382963d416a Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Thu, 8 Oct 2026 14:45:14 +0200 Subject: [PATCH 3/5] fix(platform): let a live body's time-limit error land before its host refuses The host signal and the caller's deadline fired on the same tick, so a caller could be told 'request aborted' by the body's next host call instead of the body's time-limit error. Host calls now start refusing 100 ms past the limit. --- .../platform/lib/connectors/dispatcher.test.ts | 18 ++++++++++-------- services/platform/lib/connectors/dispatcher.ts | 15 +++++++++++---- 2 files changed, 21 insertions(+), 12 deletions(-) diff --git a/services/platform/lib/connectors/dispatcher.test.ts b/services/platform/lib/connectors/dispatcher.test.ts index cf36559e6d..aa93619842 100644 --- a/services/platform/lib/connectors/dispatcher.test.ts +++ b/services/platform/lib/connectors/dispatcher.test.ts @@ -576,16 +576,18 @@ describe('live yaml-js backend', () => { }, }), ).rejects.toMatchObject({ code: 'LIVE_BODY_FAILED' }); - const releasedAtMs = Date.now(); - const issuedByRelease = issued.length; - expect(issuedByRelease).toBeGreaterThan(0); + 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)); - // At most the one request in flight at the limit went out after it, and - // the host refused it; nothing reached the vendor afterwards. - const late = issued.filter((call) => call.atMs >= releasedAtMs); - expect(late.length).toBeLessThanOrEqual(1); - expect(late.every((call) => call.aborted)).toBe(true); + // 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 () => { diff --git a/services/platform/lib/connectors/dispatcher.ts b/services/platform/lib/connectors/dispatcher.ts index 7dbe8a2337..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 @@ -848,14 +850,19 @@ export async function executeConnectorAction( // 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: 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. + // 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), + AbortSignal.timeout( + (ctx.timeoutMs ?? DEFAULT_LIVE_TIMEOUT_MS) + + HOST_ABORT_GRACE_MS, + ), ) : ctx.signal; const host = createLiveHost({ From c46b99fb1a7f081ff5668b23279251fcd82bf0af Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Thu, 8 Oct 2026 15:05:48 +0200 Subject: [PATCH 4/5] refactor(platform): drop the session-bound connector runner factory codeRunnerForSession lost its last caller when connector bodies moved in process; the program runner beneath it stays with the rest of the session-bound path listed in the contract debt ledger. --- .agents/repo.md | 2 +- .../node_only/sandbox/engine_exec_runner.ts | 32 ++++--------------- 2 files changed, 8 insertions(+), 26 deletions(-) diff --git a/.agents/repo.md b/.agents/repo.md index 893ef562ec..5a7566b81e 100644 --- a/.agents/repo.md +++ b/.agents/repo.md @@ -438,7 +438,7 @@ default means deleting the override and fixing what surfaces: - **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` (`codeRunnerForSession`), `lib/connectors/portable-live.ts`, + `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 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 }, - ); -} From 335313f401eaec7dcea99ee4f3eb8660a150dbe8 Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Thu, 8 Oct 2026 19:22:46 +0200 Subject: [PATCH 5/5] test(platform): drop the superseded connector bridge automation row --- services/platform/tests/manual/reference/automation.md | 1 - 1 file changed, 1 deletion(-) diff --git a/services/platform/tests/manual/reference/automation.md b/services/platform/tests/manual/reference/automation.md index 862a3757fb..e4f37098a6 100644 --- a/services/platform/tests/manual/reference/automation.md +++ b/services/platform/tests/manual/reference/automation.md @@ -1093,5 +1093,4 @@ 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 | ✅ backend | `backend/domains/connectors/bridge-routes.test.ts` (the connectors spec's rule on where a call runs: live mode, no session), `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 end to end) | | [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) |