Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .agents/repo.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 4 additions & 2 deletions services/platform/backend/core/connectors/hostcall_token.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@ const neverDispatches: Dispatch = () => {

const BASE = {
organizationId: 'org_1',
sessionId: 'session_1',
userId: 'user_1',
};

Expand Down Expand Up @@ -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] } });
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,6 @@ export type BridgeDispatch = (args: {
action: string;
input: unknown;
userId: string;
execSessionId: string;
}) => Promise<unknown>;

/** Whether the org has an ACTIVE credential for a connector (the status
Expand Down Expand Up @@ -175,7 +174,6 @@ export async function runBridgeConnectorImpl(
dispatch: BridgeDispatch,
args: {
organizationId: string;
sessionId: string;
userId: string;
slug: string;
operation: string;
Expand Down Expand Up @@ -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 =
Expand Down
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -11,27 +12,17 @@
* exec (`node -e <program>`, 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');
}
Expand Down Expand Up @@ -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 },
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down
54 changes: 52 additions & 2 deletions services/platform/backend/domains/connectors/bridge-routes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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);
Expand Down
76 changes: 55 additions & 21 deletions services/platform/backend/domains/connectors/bridge-routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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<string, number>();

export function createConnectorBridgeRoutes(deps: { sql: Sql }): Hono {
const app = new Hono();
app.use('/execute', sandboxDoorBodyLimit(toolResultTooLarge));
Expand Down Expand Up @@ -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<ReturnType<typeof runBridgeConnectorImpl>>;
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,
Expand Down
Loading