Skip to content

The open-source app everyone uses to manage agents at work

fix(adapter-utils): bound the ACP startup handshake and fence the abandoned session promise (#12454)

Nicky Leache127faa14cc1
diff --git a/doc/execution-semantics.md b/doc/execution-semantics.md
index 9f707d6280..6e798bfe33 100644
--- a/doc/execution-semantics.md
+++ b/doc/execution-semantics.md
@@ -376,6 +376,12 @@ Workspace incoherence feeds into the same non-terminal liveness and stranded ass
For runtime-created `git_worktree` execution workspaces, branch coherence is part of workspace coherence. The persisted execution workspace branch is the recorded branch for future dispatch. Reusing that workspace must verify that the worktree is still registered and that `HEAD` is on the recorded branch. Successful run finalization must perform the same check before recording `workspace_finalize=succeeded`. If the run switched to a publishing/PR branch without updating the execution workspace record, finalization may auto-restore the recorded branch only when the worktree is clean, still registered, and the recorded branch points at the current `HEAD`; the repair is recorded as a workspace operation before the successful finalize row. If that safe repair cannot be proven, finalization records a failed workspace finalize and the run fails with bounded evidence for the expected and actual branch. A branch change is sanctioned when a control-plane path updates the execution workspace record before finalization, when publishing work happens in a separate worktree and the managed issue worktree remains on its recorded branch, or when the finalizer performs this clean same-commit restoration.
+### ACP startup handshake bound
+
+An adapter-backed live path also requires that the ACP startup handshake itself cannot hang forever. The engine bounds the handshake with a fixed startup deadline and a poll of the duplex control-channel disposition. Either condition ends the handshake and reports a closed, typed code, so the issue can reach a settled disposition instead of staying `in_progress` with no observable next action.
+
+The handshake failure code is distinct from a session-identity mismatch. A timeout or a duplex-channel loss during startup must not be reported as the same code as a failed session resume, because the two need different operator responses.
+
### Explicit recovery actions
An explicit recovery action is a typed liveness repair path for a source issue. It is the recovery primitive; the action can be rendered directly on the source issue or backed by a separate recovery issue when the repair needs its own work item.
diff --git a/packages/adapter-utils/src/acpx-engine/constants.ts b/packages/adapter-utils/src/acpx-engine/constants.ts
index 11f3aa2249..bb515b21b7 100644
--- a/packages/adapter-utils/src/acpx-engine/constants.ts
+++ b/packages/adapter-utils/src/acpx-engine/constants.ts
@@ -5,6 +5,19 @@ export const DEFAULT_ACP_ENGINE_NON_INTERACTIVE_PERMISSIONS = "deny";
export const DEFAULT_ACP_ENGINE_TIMEOUT_SEC = 0;
export const DEFAULT_ACP_ENGINE_WARM_HANDLE_IDLE_MS = 0;
+// The bound on the ACP startup handshake (`runtime.ensureSession()`). This
+// deadline is separate from, and much smaller than, the whole-adapter
+// execution timeout: it bounds only the handshake, not the agent turn. A real
+// handshake completes in a few seconds; this value gives it generous room
+// before the host gives up and reports a closed timeout code.
+export const ACPX_HANDSHAKE_TIMEOUT_MS = 60_000;
+
+// How often the host polls the duplex control-channel disposition while the
+// handshake is in flight. The read is a cheap, non-mutating getter, so a
+// short interval costs nothing while giving the host near-immediate notice
+// of a channel loss.
+export const ACPX_HANDSHAKE_TRANSPORT_POLL_MS = 250;
+
export const ACPX_ADAPTER_AGENT_IDS = {
claude_local: "claude",
codex_local: "codex",
diff --git a/packages/adapter-utils/src/acpx-engine/execute.test.ts b/packages/adapter-utils/src/acpx-engine/execute.test.ts
index c47d057e3e..1681155270 100644
--- a/packages/adapter-utils/src/acpx-engine/execute.test.ts
+++ b/packages/adapter-utils/src/acpx-engine/execute.test.ts
@@ -36,6 +36,7 @@ import {
summarizeAcpxTurnUsage,
type AcpxEngineExecutorOptions,
} from "./execute.js";
+import { ACPX_HANDSHAKE_TIMEOUT_MS } from "./constants.js";
import { runChildProcess } from "../server-utils.js";
import { setExpensiveWorkspaceGitExecutor } from "../git-workspace-sync.js";
import { resolveReferencedSourceIgnore } from "../sandbox-managed-runtime.js";
@@ -216,6 +217,20 @@ async function runExecutor(
return { logs, meta, events, runtimeOptions, configOptions, sessionInputs, result };
}
+// Under `vi.useFakeTimers()`, the setup work before a run reaches its
+// `ensureSession` call (staging, warm-handle lookups, real `fs` calls) still
+// runs through ordinary promise chains, not timers. `advanceTimersByTimeAsync`
+// only drains microtasks in the windows between the timer ticks it processes;
+// with no timer due yet, a single call can return before that setup chain
+// finishes unwinding. Flushing a few zero-length advances first lets it fully
+// unwind before the real, deadline-length advance below.
+async function flushSetupThenAdvanceTimersByTimeAsync(ms: number): Promise<void> {
+ for (let i = 0; i < 50; i++) {
+ await vi.advanceTimersByTimeAsync(0);
+ }
+ await vi.advanceTimersByTimeAsync(ms);
+}
+
// A recording span, used only in tests. It captures the span name, the parent
// span (resolved from the explicit parent-context token), the attribute map,
// the terminal status, and whether the span ended. The engine treats it purely
@@ -6168,4 +6183,587 @@ describe("ACPX engine sandbox bridge run-disposition seam (fail-closed)", () =>
// released the runtime locally and placed no remote close call.
expect(closeCalls).toBe(0);
});
+
+ it("ends a pending handshake with a closed transport-lost code when the duplex channel is lost before ensureSession settles", async () => {
+ const sandbox = await setupRemoteSandbox();
+ const fake = createFakeBridgeHandle();
+ // `ensureSession` never settles on its own; only the guard can end it.
+ const runtime = {
+ ensureSession: () => new Promise(() => {}),
+ startTurn: () => ({
+ events: (async function* () {
+ yield { type: "done", stopReason: "end_turn" };
+ })(),
+ result: Promise.resolve({ status: "completed" as const, stopReason: "end_turn" }),
+ cancel: async () => {},
+ }),
+ setConfigOption: async () => {},
+ close: async () => {},
+ };
+
+ // Real timers: the sandbox lane spawns a real staging subprocess, whose
+ // completion callbacks run on the real event loop, not through fake
+ // timers. The poll interval is short (a fixed host constant well under a
+ // second), so this converges quickly without needing the deadline to
+ // fire — the loss is ordered up front, before `ensureSession` ever runs.
+ const resultPromise = runRemote(fake.handle, runtime, sandbox);
+ fake.emitLoss("provider_exit");
+ const result = await resultPromise;
+
+ expect(result.exitCode).not.toBe(0);
+ expect(result.errorCode).toBe("acpx_handshake_transport_lost");
+ expect(result.resultJson).toMatchObject({ phase: "ensure_session" });
+ // Distinct from a session-identity failure and from the deadline code.
+ expect(result.errorCode).not.toBe("acpx_session_init_failed");
+ expect(result.errorCode).not.toBe("acpx_handshake_timeout");
+ }, 10000);
+});
+
+describe("ACPX startup handshake guard and late-completion fence", () => {
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it("ends a handshake that stays pending past the startup deadline with a closed timeout code", async () => {
+ const root = await makeTempRoot();
+ const execute = createAcpxEngineExecutor({
+ createRuntime: () =>
+ ({
+ // Never settles on its own; only the guard's deadline can end it.
+ ensureSession: () => new Promise(() => {}),
+ startTurn: () => ({
+ events: (async function* () {})(),
+ result: Promise.resolve({ status: "completed", stopReason: "end_turn" }),
+ cancel: async () => {},
+ }),
+ close: async () => {},
+ }) as never,
+ });
+
+ try {
+ vi.useFakeTimers();
+ const resultPromise = execute({
+ runId: "run-handshake-timeout",
+ agent: { id: "agent-1", companyId: "company-1" },
+ runtime: {},
+ config: { agent: "custom", agentCommand: "node ./fake-acp.js", stateDir: path.join(root, "state") },
+ context: {},
+ onLog: async () => {},
+ onMeta: async () => {},
+ } as never);
+ await flushSetupThenAdvanceTimersByTimeAsync(ACPX_HANDSHAKE_TIMEOUT_MS + 50);
+ const result = await resultPromise;
+
+ // The run terminalizes promptly on its own; no server restart needed.
+ expect(result.exitCode).not.toBe(0);
+ expect(result.errorCode).toBe("acpx_handshake_timeout");
+ expect(result.resultJson).toMatchObject({ phase: "ensure_session" });
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("never promotes a late ensureSession resolution into the live handle after a guard rejection", async () => {
+ const root = await makeTempRoot();
+ let resolveEnsure!: (handle: unknown) => void;
+ const ensureSessionPromise = new Promise((resolve) => {
+ resolveEnsure = resolve;
+ });
+ const startTurn = vi.fn(() => ({
+ events: (async function* () {
+ yield { type: "done", stopReason: "end_turn" };
+ })(),
+ result: Promise.resolve({ status: "completed" as const, stopReason: "end_turn" }),
+ cancel: async () => {},
+ }));
+ const execute = createAcpxEngineExecutor({
+ createRuntime: () =>
+ ({
+ ensureSession: () => ensureSessionPromise,
+ startTurn,
+ close: async () => {},
+ }) as never,
+ });
+
+ try {
+ vi.useFakeTimers();
+ const resultPromise = execute({
+ runId: "run-no-promotion",
+ agent: { id: "agent-1", companyId: "company-1" },
+ runtime: {},
+ config: { agent: "custom", agentCommand: "node ./fake-acp.js", stateDir: path.join(root, "state") },
+ context: {},
+ onLog: async () => {},
+ onMeta: async () => {},
+ } as never);
+ await flushSetupThenAdvanceTimersByTimeAsync(ACPX_HANDSHAKE_TIMEOUT_MS + 50);
+ const result = await resultPromise;
+
+ expect(result.errorCode).toBe("acpx_handshake_timeout");
+ // The run settled as a pre-turn handshake failure; the turn never ran,
+ // which it could only do with a promoted, live session handle.
+ expect(result.resultJson).toMatchObject({ phase: "ensure_session" });
+ expect(startTurn).not.toHaveBeenCalled();
+
+ // The abandoned promise now resolves. It must still never start a turn.
+ resolveEnsure({
+ backendSessionId: "backend-session",
+ agentSessionId: "agent-session",
+ runtimeSessionName: "runtime-session",
+ });
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(startTurn).not.toHaveBeenCalled();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("closes a late-resolving real handle exactly once, whether it arrives before or after settlement seals", async () => {
+ const lateHandle = {
+ backendSessionId: "backend-session",
+ agentSessionId: "agent-session",
+ runtimeSessionName: "runtime-session",
+ };
+
+ async function runAbandonedHandshake(): Promise<{
+ closeSpy: ReturnType<typeof vi.fn>;
+ resolveEnsure: (handle: unknown) => void;
+ resultPromise: Promise<unknown>;
+ }> {
+ const root = await makeTempRoot();
+ let resolveEnsure!: (handle: unknown) => void;
+ const ensureSessionPromise = new Promise((resolve) => {
+ resolveEnsure = resolve;
+ });
+ const closeSpy = vi.fn(async () => {});
+ const execute = createAcpxEngineExecutor({
+ createRuntime: () =>
+ ({
+ ensureSession: () => ensureSessionPromise,
+ startTurn: () => ({
+ events: (async function* () {})(),
+ result: Promise.resolve({ status: "completed", stopReason: "end_turn" }),
+ cancel: async () => {},
+ }),
+ close: closeSpy,
+ }) as never,
+ });
+ const resultPromise = execute({
+ runId: "run-fence-close",
+ agent: { id: "agent-1", companyId: "company-1" },
+ runtime: {},
+ config: { agent: "custom", agentCommand: "node ./fake-acp.js", stateDir: path.join(root, "state") },
+ context: {},
+ onLog: async () => {},
+ onMeta: async () => {},
+ } as never);
+ await flushSetupThenAdvanceTimersByTimeAsync(ACPX_HANDSHAKE_TIMEOUT_MS + 1);
+ return { closeSpy, resolveEnsure, resultPromise };
+ }
+
+ try {
+ vi.useFakeTimers();
+
+ // Order A: the late resolution lands as soon as possible after the
+ // guard rejects, ahead of the settlement steps that follow it.
+ {
+ const { closeSpy, resolveEnsure, resultPromise } = await runAbandonedHandshake();
+ resolveEnsure(lateHandle);
+ await resultPromise;
+ expect(closeSpy).toHaveBeenCalledTimes(1);
+ expect(closeSpy).toHaveBeenCalledWith(expect.objectContaining({ handle: lateHandle }));
+ }
+
+ // Order B: the run fully settles first (so settlement has already
+ // sealed the fence), and only then does the late resolution land.
+ {
+ const { closeSpy, resolveEnsure, resultPromise } = await runAbandonedHandshake();
+ await resultPromise;
+ expect(closeSpy).not.toHaveBeenCalled();
+ resolveEnsure(lateHandle);
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(closeSpy).toHaveBeenCalledTimes(1);
+ expect(closeSpy).toHaveBeenCalledWith(expect.objectContaining({ handle: lateHandle }));
+ }
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("discards the reuse decision and leaves no warm entry after a guard rejection", async () => {
+ const root = await makeTempRoot();
+ const warmHandles = new Map();
+ const execute = createAcpxEngineExecutor({
+ warmHandles,
+ createRuntime: () =>
+ ({
+ ensureSession: () => new Promise(() => {}),
+ startTurn: () => ({
+ events: (async function* () {})(),
+ result: Promise.resolve({ status: "completed", stopReason: "end_turn" }),
+ cancel: async () => {},
+ }),
+ close: async () => {},
+ }) as never,
+ });
+
+ try {
+ vi.useFakeTimers();
+ const resultPromise = execute({
+ runId: "run-discard-reuse",
+ agent: { id: "agent-1", companyId: "company-1" },
+ runtime: {},
+ config: {
+ agent: "custom",
+ agentCommand: "node ./fake-acp.js",
+ stateDir: path.join(root, "state"),
+ mode: "persistent",
+ warmHandleIdleMs: 60_000,
+ },
+ context: {},
+ onLog: async () => {},
+ onMeta: async () => {},
+ } as never);
+ await flushSetupThenAdvanceTimersByTimeAsync(ACPX_HANDSHAKE_TIMEOUT_MS + 50);
+ const result = await resultPromise;
+
+ expect(result.errorCode).toBe("acpx_handshake_timeout");
+ expect(warmHandles.size).toBe(0);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("keeps the session-identity mismatch code unchanged and distinct from both new handshake-guard codes", async () => {
+ class FakeAcpRuntimeError extends Error {
+ readonly code = "ACP_SESSION_INIT_FAILED";
+ constructor(message: string) {
+ super(message);
+ this.name = "AcpRuntimeError";
+ }
+ }
+ const root = await makeTempRoot();
+ const execute = createAcpxEngineExecutor({
+ createRuntime: () =>
+ ({
+ ensureSession: async () => {
+ throw new FakeAcpRuntimeError("session/new failed: backend rejected initialize");
+ },
+ startTurn: () => ({
+ events: (async function* () {})(),
+ result: Promise.resolve({ status: "completed", stopReason: "end_turn" }),
+ cancel: async () => {},
+ }),
+ close: async () => {},
+ }) as never,
+ });
+
+ const result = await execute({
+ runId: "run-session-mismatch",
+ agent: { id: "agent-1", companyId: "company-1" },
+ runtime: {},
+ config: { agent: "custom", agentCommand: "node ./fake-acp.js", stateDir: path.join(root, "state") },
+ context: {},
+ onLog: async () => {},
+ onMeta: async () => {},
+ } as never);
+
+ expect(result.errorCode).toBe("acpx_session_init_failed");
+ expect(result.errorCode).not.toBe("acpx_handshake_timeout");
+ expect(result.errorCode).not.toBe("acpx_handshake_transport_lost");
+
+ // A normal cold start and session establishment stay unaffected.
+ const { result: coldStartResult } = await runExecutor({
+ agent: "custom",
+ agentCommand: "node ./fake-acp.js",
+ stateDir: path.join(root, "state-cold"),
+ });
+ expect(coldStartResult.exitCode).toBe(0);
+ expect(coldStartResult.errorCode ?? null).toBeNull();
+ });
+
+ it("never leaks a sandbox-provided value from a late ensureSession rejection into logs, the result, or a classification", async () => {
+ const secretMarker = "sandbox-secret-marker-9f3c1a";
+ const root = await makeTempRoot();
+ let rejectEnsure!: (err: unknown) => void;
+ const ensureSessionPromise = new Promise((_resolve, reject) => {
+ rejectEnsure = reject;
+ });
+ const logs: Array<{ stream: string; text: string }> = [];
+ const unhandledRejections: unknown[] = [];
+ const onUnhandledRejection = (err: unknown) => unhandledRejections.push(err);
+ process.on("unhandledRejection", onUnhandledRejection);
+
+ try {
+ vi.useFakeTimers();
+ const execute = createAcpxEngineExecutor({
+ createRuntime: () =>
+ ({
+ ensureSession: () => ensureSessionPromise,
+ startTurn: () => ({
+ events: (async function* () {})(),
+ result: Promise.resolve({ status: "completed", stopReason: "end_turn" }),
+ cancel: async () => {},
+ }),
+ close: async () => {},
+ }) as never,
+ });
+ const resultPromise = execute({
+ runId: "run-late-rejection",
+ agent: { id: "agent-1", companyId: "company-1" },
+ runtime: {},
+ config: { agent: "custom", agentCommand: "node ./fake-acp.js", stateDir: path.join(root, "state") },
+ context: {},
+ onLog: async (stream: "stdout" | "stderr", text: string) => {
+ logs.push({ stream, text });
+ },
+ onMeta: async () => {},
+ } as never);
+ await flushSetupThenAdvanceTimersByTimeAsync(ACPX_HANDSHAKE_TIMEOUT_MS + 1);
+ const result = await resultPromise;
+ expect(result.errorCode).toBe("acpx_handshake_timeout");
+
+ // The abandoned promise now rejects with a value carrying a secret-like
+ // marker, as if a compromised sandbox child placed it there.
+ rejectEnsure(new Error(`leaked credential: ${secretMarker}`));
+ await Promise.resolve();
+ await Promise.resolve();
+
+ for (const entry of logs) {
+ expect(entry.text).not.toContain(secretMarker);
+ }
+ expect(JSON.stringify(result)).not.toContain(secretMarker);
+ const lateRejectionLog = logs.find((entry) => entry.text.includes("acpx_handshake_late_rejection"));
+ expect(lateRejectionLog).toBeTruthy();
+ expect(unhandledRejections).toHaveLength(0);
+ } finally {
+ process.off("unhandledRejection", onUnhandledRejection);
+ vi.useRealTimers();
+ }
+ });
+
+ it("never leaks the child stderr tail into logs or the acpx.error payload after a startup-timeout guard trip", async () => {
+ const secretMarker = "sandbox-secret-marker-timeout-7d2e";
+ const root = await makeTempRoot();
+ const stateDir = path.join(root, "state");
+ const runStderrDir = path.join(stateDir, "run-stderr");
+ await fs.mkdir(runStderrDir, { recursive: true });
+ await fs.writeFile(
+ path.join(runStderrDir, "run-guard-timeout.log"),
+ `leaked credential: ${secretMarker}\n`,
+ "utf8",
+ );
+
+ const logs: Array<{ stream: string; text: string }> = [];
+ const execute = createAcpxEngineExecutor({
+ createRuntime: () =>
+ ({
+ // Never settles on its own; only the guard's deadline can end it.
+ ensureSession: () => new Promise(() => {}),
+ startTurn: () => ({
+ events: (async function* () {})(),
+ result: Promise.resolve({ status: "completed", stopReason: "end_turn" }),
+ cancel: async () => {},
+ }),
+ close: async () => {},
+ }) as never,
+ });
+
+ try {
+ vi.useFakeTimers();
+ const resultPromise = execute({
+ runId: "run-guard-timeout",
+ agent: { id: "agent-1", companyId: "company-1" },
+ runtime: {},
+ config: { agent: "custom", agentCommand: "node ./fake-acp.js", stateDir },
+ context: {},
+ onLog: async (stream: "stdout" | "stderr", text: string) => {
+ logs.push({ stream, text });
+ },
+ onMeta: async () => {},
+ } as never);
+ await flushSetupThenAdvanceTimersByTimeAsync(ACPX_HANDSHAKE_TIMEOUT_MS + 50);
+ const result = await resultPromise;
+
+ expect(result.errorCode).toBe("acpx_handshake_timeout");
+ for (const entry of logs) {
+ expect(entry.text).not.toContain(secretMarker);
+ }
+ expect(JSON.stringify(result)).not.toContain(secretMarker);
+ const errorLogLine = logs.find((entry) => entry.text.includes("\"type\":\"acpx.error\""));
+ expect(errorLogLine).toBeTruthy();
+ const errorPayload = JSON.parse(errorLogLine!.text.trim());
+ expect(errorPayload.childStderrTail).toBeUndefined();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("never leaks the child stderr tail into logs or the acpx.error payload after a transport-lost guard trip", async () => {
+ const secretMarker = "sandbox-secret-marker-transport-4b91";
+ const root = await makeTempRoot();
+ const stateDir = path.join(root, "state");
+ const localCwd = path.join(root, "worktree");
+ const remoteCwd = path.join(root, "remote-workspace");
+ await fs.mkdir(localCwd, { recursive: true });
+ await fs.mkdir(remoteCwd, { recursive: true });
+ await fs.writeFile(path.join(localCwd, "hello.txt"), "hi", "utf8");
+ const runStderrDir = path.join(stateDir, "run-stderr");
+ await fs.mkdir(runStderrDir, { recursive: true });
+ await fs.writeFile(
+ path.join(runStderrDir, "run-guard-transport-lost.log"),
+ `leaked credential: ${secretMarker}\n`,
+ "utf8",
+ );
+
+ const runner = createLocalSandboxRunner();
+ const executionTarget = {
+ kind: "remote",
+ transport: "sandbox",
+ providerKey: "fake-plugin",
+ remoteCwd,
+ runner,
+ };
+
+ // A minimal run-disposition latch, matching the real bridge transport: once
+ // the loss is ordered, every later read still reports it.
+ let lossOrdered = false;
+ const readDisposition = () => ({ failed: lossOrdered, lossReason: lossOrdered ? "provider_exit" : null });
+ const bridgeHandle = {
+ env: {
+ PAPERCLIP_API_URL: "http://127.0.0.1:1",
+ PAPERCLIP_API_KEY: "bridge-token",
+ PAPERCLIP_API_BRIDGE_MODE: "http2_v1",
+ },
+ readRunDisposition: () => readDisposition(),
+ settleRunDisposition: () => readDisposition(),
+ markOrderlyCompletion: () => {},
+ stop: async () => {},
+ };
+ vi.mocked(startAdapterExecutionTargetPaperclipBridge).mockImplementationOnce(
+ async () => bridgeHandle as never,
+ );
+ vi.mocked(startAdapterExecutionTargetProcessSessionBridge).mockImplementationOnce(
+ async () => ({ agentCommand: null, stop: async () => {} }) as never,
+ );
+
+ const logs: Array<{ stream: string; text: string }> = [];
+ const execute = createAcpxEngineExecutor({
+ createRuntime: () =>
+ ({
+ // Never settles on its own; only the guard's transport-loss poll can
+ // end it.
+ ensureSession: () => new Promise(() => {}),
+ startTurn: () => ({
+ events: (async function* () {})(),
+ result: Promise.resolve({ status: "completed", stopReason: "end_turn" }),
+ cancel: async () => {},
+ }),
+ setConfigOption: async () => {},
+ close: async () => {},
+ }) as never,
+ });
+
+ // Real timers: the sandbox lane spawns a real staging subprocess, whose
+ // completion callbacks run on the real event loop, not through fake
+ // timers. The loss is ordered up front, before `ensureSession` ever runs.
+ const resultPromise = execute({
+ runId: "run-guard-transport-lost",
+ agent: { id: "agent-1", companyId: "company-1" },
+ runtime: {},
+ config: { agent: "custom", agentCommand: "node ./fake-acp.js", stateDir, cwd: localCwd },
+ context: {},
+ authToken: "real-run-jwt",
+ executionTarget,
+ onLog: async (stream: "stdout" | "stderr", text: string) => {
+ logs.push({ stream, text });
+ },
+ onMeta: async () => {},
+ onEvent: async () => {},
+ } as never);
+ lossOrdered = true;
+ const result = await resultPromise;
+
+ expect(result.errorCode).toBe("acpx_handshake_transport_lost");
+ for (const entry of logs) {
+ expect(entry.text).not.toContain(secretMarker);
+ }
+ expect(JSON.stringify(result)).not.toContain(secretMarker);
+ const errorLogLine = logs.find((entry) => entry.text.includes("\"type\":\"acpx.error\""));
+ expect(errorLogLine).toBeTruthy();
+ const errorPayload = JSON.parse(errorLogLine!.text.trim());
+ expect(errorPayload.childStderrTail).toBeUndefined();
+ }, 10000);
+
+ it("never leaks a sandbox-provided value from a late close rejection into logs or the result", async () => {
+ const secretMarker = "sandbox-secret-marker-late-close-2a7f";
+ const root = await makeTempRoot();
+ const lateHandle = {
+ backendSessionId: "backend-session",
+ agentSessionId: "agent-session",
+ runtimeSessionName: "runtime-session",
+ };
+ let resolveEnsure!: (handle: unknown) => void;
+ const ensureSessionPromise = new Promise((resolve) => {
+ resolveEnsure = resolve;
+ });
+ const logs: Array<{ stream: string; text: string }> = [];
+ const unhandledRejections: unknown[] = [];
+ const onUnhandledRejection = (err: unknown) => unhandledRejections.push(err);
+ process.on("unhandledRejection", onUnhandledRejection);
+
+ try {
+ vi.useFakeTimers();
+ const execute = createAcpxEngineExecutor({
+ createRuntime: () =>
+ ({
+ ensureSession: () => ensureSessionPromise,
+ startTurn: () => ({
+ events: (async function* () {})(),
+ result: Promise.resolve({ status: "completed", stopReason: "end_turn" }),
+ cancel: async () => {},
+ }),
+ close: async () => {
+ throw new Error(`leaked credential: ${secretMarker}`);
+ },
+ }) as never,
+ });
+ const resultPromise = execute({
+ runId: "run-late-close-rejection",
+ agent: { id: "agent-1", companyId: "company-1" },
+ runtime: {},
+ config: { agent: "custom", agentCommand: "node ./fake-acp.js", stateDir: path.join(root, "state") },
+ context: {},
+ onLog: async (stream: "stdout" | "stderr", text: string) => {
+ logs.push({ stream, text });
+ },
+ onMeta: async () => {},
+ } as never);
+ await flushSetupThenAdvanceTimersByTimeAsync(ACPX_HANDSHAKE_TIMEOUT_MS + 1);
+ const result = await resultPromise;
+ expect(result.errorCode).toBe("acpx_handshake_timeout");
+
+ // The run has already settled (the fence is sealed), and only now does the
+ // abandoned promise resolve into a real handle, as if a compromised
+ // sandbox child forged a late handle. The engine's own close attempt on
+ // that handle then rejects with a value carrying a secret-like marker.
+ resolveEnsure(lateHandle);
+ await Promise.resolve();
+ await Promise.resolve();
+ await Promise.resolve();
+
+ for (const entry of logs) {
+ expect(entry.text).not.toContain(secretMarker);
+ }
+ expect(JSON.stringify(result)).not.toContain(secretMarker);
+ const lateCloseLog = logs.find((entry) => entry.text.includes("acpx_handshake_late_close_failed"));
+ expect(lateCloseLog).toBeTruthy();
+ expect(unhandledRejections).toHaveLength(0);
+ } finally {
+ process.off("unhandledRejection", onUnhandledRejection);
+ vi.useRealTimers();
+ }
+ });
});
diff --git a/packages/adapter-utils/src/acpx-engine/execute.ts b/packages/adapter-utils/src/acpx-engine/execute.ts
index 65a77de060..110ca0a30a 100644
--- a/packages/adapter-utils/src/acpx-engine/execute.ts
+++ b/packages/adapter-utils/src/acpx-engine/execute.ts
@@ -89,6 +89,8 @@ import {
type AcpRuntimeUsageCost,
} from "acpx/runtime";
import {
+ ACPX_HANDSHAKE_TIMEOUT_MS,
+ ACPX_HANDSHAKE_TRANSPORT_POLL_MS,
DEFAULT_ACP_ENGINE_AGENT,
DEFAULT_ACP_ENGINE_MODE,
DEFAULT_ACP_ENGINE_NON_INTERACTIVE_PERMISSIONS,
@@ -2411,6 +2413,163 @@ interface RuntimeSettlementPlan {
readonly skipRemoteClose: boolean;
}
+// ACP startup handshake guard and late-completion fence.
+//
+// `runtime.ensureSession()` comes from the external `acpx/runtime` package. It
+// takes no `AbortSignal`, so the engine cannot cancel it; it can only walk
+// away from the promise. `guardEnsureSession` races the call against a fixed
+// deadline and a poll of the duplex control-channel disposition, and rejects
+// with one of these two host-generated, typed errors the moment either
+// condition trips. The error type — not its message — is what
+// `classifyError` reads, so a startup timeout can never collapse into the
+// session-identity failure code.
+//
+// A guard rejection does not stop the external call. `HandshakeAbandonmentFence`
+// gives that abandoned promise one owner: a resolution that arrives after the
+// engine walked away can never become the live session handle, the promise
+// stays observed so it can never raise an unhandled rejection, and the real
+// handle is closed exactly once, whichever side — the settlement step or the
+// fence itself — ends up seeing it first.
+
+class AcpxHandshakeTimeoutError extends Error {
+ readonly acpxHandshakeGuardKind = "timeout" as const;
+ constructor() {
+ super("The ACP startup handshake did not finish before the startup deadline.");
+ this.name = "AcpxHandshakeTimeoutError";
+ }
+}
+
+class AcpxHandshakeTransportLostError extends Error {
+ readonly acpxHandshakeGuardKind = "transport_lost" as const;
+ constructor() {
+ super("The sandbox duplex control channel was lost during the ACP startup handshake.");
+ this.name = "AcpxHandshakeTransportLostError";
+ }
+}
+
+function isAcpxHandshakeTimeoutError(err: unknown): err is AcpxHandshakeTimeoutError {
+ return err instanceof AcpxHandshakeTimeoutError;
+}
+
+function isAcpxHandshakeTransportLostError(err: unknown): err is AcpxHandshakeTransportLostError {
+ return err instanceof AcpxHandshakeTransportLostError;
+}
+
+/**
+ * Gives one abandoned `ensureSession` promise one owner. Construct one fence
+ * per run and reuse it across both `ensureSession` call sites (the first
+ * attempt and the fresh-session retry): only one of those two calls can ever
+ * be the one a guard rejection abandons, because the retry only runs after
+ * the first call already settled on its own.
+ *
+ * `seal()` is the idempotent boundary: only its first call can flip the
+ * state and hand back a handle that arrived before it ran. A later call is a
+ * no-op, so `endSession` can call it unconditionally as its first operation
+ * on every settlement path, not only a handshake-guard one.
+ */
+class HandshakeAbandonmentFence {
+ private sealedFlag = false;
+ private lateHandle: AcpRuntimeHandle | null = null;
+
+ get isSealed(): boolean {
+ return this.sealedFlag;
+ }
+
+ /** Record a late resolution that arrived before `seal()` ran. */
+ storeLateHandle(handle: AcpRuntimeHandle): void {
+ if (this.sealedFlag) return;
+ this.lateHandle = handle;
+ }
+
+ /** Idempotent. Only the first call can return a handle that beat it here. */
+ seal(): AcpRuntimeHandle | null {
+ if (this.sealedFlag) return null;
+ this.sealedFlag = true;
+ const handle = this.lateHandle;
+ this.lateHandle = null;
+ return handle;
+ }
+}
+
+/**
+ * Race one `ensureSession()` call against the startup guard. Whichever
+ * settles first wins; `outcome` records which one, so the promise's own
+ * `.then` (attached synchronously, right here, before this function returns)
+ * can tell a genuinely late settlement apart from the one the race already
+ * delivered through its normal return value.
+ *
+ * The deadline and the transport-loss poll both start now, at the call site,
+ * not earlier. The bridge disposition this polls is a latch: once a loss
+ * orders, every later read still reports it, so a loss that happened before
+ * this call started polling is still caught on the first tick.
+ */
+function guardEnsureSession(params: {
+ call: () => Promise<AcpRuntimeHandle>;
+ fence: HandshakeAbandonmentFence;
+ isTransportLost: () => boolean;
+ onLateHandleAfterSeal: (handle: AcpRuntimeHandle) => void;
+ onLateRejection: () => void;
+}): Promise<AcpRuntimeHandle> {
+ const sessionPromise = params.call();
+ let outcome: "pending" | "session" | "guard" = "pending";
+
+ // Attached the moment the promise exists. A guard-won race still leaves
+ // this promise observed for as long as it takes to settle, so it can never
+ // raise an unhandled rejection.
+ sessionPromise.then(
+ (handle) => {
+ if (outcome !== "guard") return;
+ if (params.fence.isSealed) {
+ params.onLateHandleAfterSeal(handle);
+ } else {
+ params.fence.storeLateHandle(handle);
+ }
+ },
+ () => {
+ if (outcome !== "guard") return;
+ params.onLateRejection();
+ },
+ );
+
+ return new Promise<AcpRuntimeHandle>((resolve, reject) => {
+ let settled = false;
+ const timer = setTimeout(() => {
+ if (settled) return;
+ settled = true;
+ outcome = "guard";
+ clearInterval(poll);
+ reject(new AcpxHandshakeTimeoutError());
+ }, ACPX_HANDSHAKE_TIMEOUT_MS);
+ const poll = setInterval(() => {
+ if (settled) return;
+ if (!params.isTransportLost()) return;
+ settled = true;
+ outcome = "guard";
+ clearTimeout(timer);
+ clearInterval(poll);
+ reject(new AcpxHandshakeTransportLostError());
+ }, ACPX_HANDSHAKE_TRANSPORT_POLL_MS);
+ sessionPromise.then(
+ (handle) => {
+ if (settled) return;
+ settled = true;
+ outcome = "session";
+ clearTimeout(timer);
+ clearInterval(poll);
+ resolve(handle);
+ },
+ (err) => {
+ if (settled) return;
+ settled = true;
+ outcome = "session";
+ clearTimeout(timer);
+ clearInterval(poll);
+ reject(err);
+ },
+ );
+ });
+}
+
function renderPaperclipEnvNote(env: Record<string, string>): string {
const paperclipKeys = Object.keys(env)
.filter((key) => key.startsWith("PAPERCLIP_"))
@@ -2821,6 +2980,23 @@ function classifyError(
...(stackPreview ? { stackPreview } : {}),
...(phase ? { phase } : {}),
};
+ // A host-generated handshake-guard error is classified by its type, never
+ // by message text, and runs before the message-driven heuristics below. A
+ // startup timeout or a duplex control-channel loss must report its own
+ // closed code, not the generic session-identity failure `phase ===
+ // "ensure_session"` would otherwise produce a few lines down.
+ if (isAcpxHandshakeTimeoutError(err)) {
+ return {
+ errorCode: "acpx_handshake_timeout",
+ errorMeta: { category: "runtime", ...baseMeta },
+ };
+ }
+ if (isAcpxHandshakeTransportLostError(err)) {
+ return {
+ errorCode: "acpx_handshake_transport_lost",
+ errorMeta: { category: "runtime", ...baseMeta },
+ };
+ }
const lower = message.toLowerCase();
const authLike = lower.includes("auth") || lower.includes("login") || lower.includes("credential");
if (authLike) {
@@ -2889,16 +3065,25 @@ async function emitAcpxFailure(input: {
// acpx.error payload. Used by the turn path to surface the self-describing
// adapter execution timeout message instead of the raw underlying error.
messageOverride?: string;
+ // Skip the child stderr tail entirely: do not read the child stderr log, do
+ // not write the `onLog` line, and do not add `childStderrTail` to the
+ // `acpx.error` payload. Used by the handshake-guard failure route: the
+ // child can hold `ensureSession()` open until the guard fires and write
+ // chosen bytes to its own stderr first, so this route must never let those
+ // sandbox-provided bytes become durable host run-log content.
+ suppressChildStderrTail?: boolean;
}): Promise<{
classified: Pick<AdapterExecutionResult, "errorCode" | "errorMeta">;
message: string;
childStderrTail: string | null;
}> {
- const { ctx, prepared, err, phase, messageOverride } = input;
+ const { ctx, prepared, err, phase, messageOverride, suppressChildStderrTail } = input;
const rawMessage = err instanceof Error ? err.message : String(err);
const message = messageOverride ?? rawMessage;
const classified = classifyError(err, phase);
- const childStderrTail = await readChildStderrTail({ logPath: prepared.childStderrLogPath });
+ const childStderrTail = suppressChildStderrTail
+ ? null
+ : await readChildStderrTail({ logPath: prepared.childStderrLogPath });
if (childStderrTail) {
await ctx.onLog(
"stderr",
@@ -3514,6 +3699,15 @@ export function createAcpxEngineExecutor(deps: AcpxEngineExecutorOptions = {}) {
// returns; a build or create-runtime failure never registers the runtime, so
// the step no-ops on the empty slot and this stays null.
let runtimeSettlement: RuntimeSettlementPlan | null = null;
+ // True only when a handshake-guard rejection (a startup timeout or a
+ // duplex transport loss) abandoned an `ensureSession` call. It tells the
+ // settlement `endSession` step to defer the close to `handshakeFence`
+ // when no late handle has arrived yet, instead of closing the synthetic
+ // placeholder itself — closing both would close the same session twice.
+ let handshakeAbandoned = false;
+ // The one owner of an abandoned `ensureSession` promise for this run. See
+ // `HandshakeAbandonmentFence` above for the state machine.
+ const handshakeFence = new HandshakeAbandonmentFence();
// A synthetic close handle from the prepared identity, for a close that has no
// established session handle (a cold `ensureSession` throw or a missing
// handle). `runtime.close` reads the session key and the runtime session name.
@@ -3709,6 +3903,44 @@ export function createAcpxEngineExecutor(deps: AcpxEngineExecutorOptions = {}) {
// resume) up to the established handle.
const ensureSessionPhaseStart = now();
resumedSession = Boolean(handle ?? resumeSessionId);
+ const isHandshakeTransportLost = (): boolean =>
+ prepared.paperclipBridge?.readRunDisposition?.().failed ?? false;
+ // The fence's own close, for a real handle that resolves after
+ // `endSession` already sealed. `endSession` closed the synthetic
+ // placeholder by then (or skipped closing because the channel was
+ // already known lost), so this is the one close for this real handle,
+ // not a second one.
+ // A rejected close comes from inside the sandbox (a forged late handle
+ // can make `runtime.close` reject with chosen bytes). It crosses the
+ // sandbox-to-host trust boundary, so it must never reach the run log,
+ // the result, or a classification: log the fixed closed code only.
+ // The catch stays attached so the promise stays observed and no
+ // unhandled rejection can occur.
+ const closeLateHandshakeHandle = (lateHandle: AcpRuntimeHandle): void => {
+ if (isHandshakeTransportLost()) return;
+ void runtime
+ .close({
+ handle: lateHandle,
+ reason: "paperclip late handshake cleanup",
+ discardPersistentState: false,
+ })
+ .catch(() =>
+ ctx
+ .onLog(
+ "stderr",
+ "[paperclip] ACPX handshake late close failed: acpx_handshake_late_close_failed\n",
+ )
+ .catch(() => {}),
+ );
+ };
+ // The late rejection comes from inside the sandbox. It crosses the
+ // sandbox-to-host trust boundary, so it must never reach the run log,
+ // the result, or a classification: log the fixed closed code only.
+ const recordLateHandshakeRejection = (): void => {
+ void ctx
+ .onLog("stderr", "[paperclip] ACPX handshake late rejection: acpx_handshake_late_rejection\n")
+ .catch(() => {});
+ };
try {
if (!handle) {
@@ -3720,13 +3952,20 @@ export function createAcpxEngineExecutor(deps: AcpxEngineExecutorOptions = {}) {
let ensureSessionMs: number | undefined;
handle = await measureStartupStep(ctx, now, "acp.handshake", async () => {
const ensureSessionStart = now();
- const established = await runtime.ensureSession({
- sessionKey: prepared.sessionKey,
- agent: prepared.acpxAgent,
- mode: prepared.mode,
- cwd: prepared.cwd,
- resumeSessionId,
- sessionOptions: { env: prepared.env },
+ const established = await guardEnsureSession({
+ call: () =>
+ runtime.ensureSession({
+ sessionKey: prepared.sessionKey,
+ agent: prepared.acpxAgent,
+ mode: prepared.mode,
+ cwd: prepared.cwd,
+ resumeSessionId,
+ sessionOptions: { env: prepared.env },
+ }),
+ fence: handshakeFence,
+ isTransportLost: isHandshakeTransportLost,
+ onLateHandleAfterSeal: closeLateHandshakeHandle,
+ onLateRejection: recordLateHandshakeRejection,
});
ensureSessionMs = now() - ensureSessionStart;
return established;
@@ -3752,12 +3991,19 @@ export function createAcpxEngineExecutor(deps: AcpxEngineExecutorOptions = {}) {
let retryEnsureSessionMs: number | undefined;
handle = await measureStartupStep(ctx, now, "acp.handshake", async () => {
const ensureSessionStart = now();
- const established = await runtime.ensureSession({
- sessionKey: prepared.sessionKey,
- agent: prepared.acpxAgent,
- mode: prepared.mode,
- cwd: prepared.cwd,
- sessionOptions: { env: prepared.env },
+ const established = await guardEnsureSession({
+ call: () =>
+ runtime.ensureSession({
+ sessionKey: prepared.sessionKey,
+ agent: prepared.acpxAgent,
+ mode: prepared.mode,
+ cwd: prepared.cwd,
+ sessionOptions: { env: prepared.env },
+ }),
+ fence: handshakeFence,
+ isTransportLost: isHandshakeTransportLost,
+ onLateHandleAfterSeal: closeLateHandshakeHandle,
+ onLateRejection: recordLateHandshakeRejection,
});
retryEnsureSessionMs = now() - ensureSessionStart;
return established;
@@ -3799,6 +4045,15 @@ export function createAcpxEngineExecutor(deps: AcpxEngineExecutorOptions = {}) {
// ledger now holds the runtime, so `endSession` closes it and the former
// cold-handshake leak is gone. The settlement stops the bridges, releases
// the staging lease, and flushes the child stderr on every exit path.
+ //
+ // A handshake-guard rejection is the one exception: `handle` stays
+ // null, but the abandoned `ensureSession` call can still resolve
+ // into a real handle later. `handshakeAbandoned` tells `endSession`
+ // to defer that placeholder close to `handshakeFence` when no late
+ // handle has arrived yet, instead of closing it here and possibly
+ // again later.
+ const guardTripped = isAcpxHandshakeTimeoutError(err) || isAcpxHandshakeTransportLostError(err);
+ handshakeAbandoned = guardTripped;
runtimeSettlement = {
mode: "direct",
handle: handle ?? syntheticCloseHandle(),
@@ -3815,6 +4070,16 @@ export function createAcpxEngineExecutor(deps: AcpxEngineExecutorOptions = {}) {
prepared,
err,
phase: "ensure_session",
+ // The guard's own message is already generic and host-authored, so
+ // this replaces the underlying error text with the same closed
+ // message `classifyError` classified — the ensure_session phase
+ // never gets a chance to summarize it differently.
+ ...(guardTripped && err instanceof Error ? { messageOverride: err.message } : {}),
+ // A compromised child can hold ensureSession open until the guard
+ // fires, then write chosen bytes to its own stderr. Suppress the
+ // child stderr tail on this route only, so those sandbox-provided
+ // bytes never reach the run log or the acpx.error payload.
+ ...(guardTripped ? { suppressChildStderrTail: true } : {}),
});
capturedResult = {
exitCode: 1,
@@ -4419,9 +4684,14 @@ export function createAcpxEngineExecutor(deps: AcpxEngineExecutorOptions = {}) {
// Close every runtime the decision did not transfer, and drop the warm entry
// on close.
endSession: (slots, decision) => timedPhase("end_session", async () => {
+ // The fence is the one idempotent owner of the abandoned promise's
+ // eventual handle. Seal it first, before every other decision
+ // below, including the empty-slot and save early returns: a late
+ // handle that already arrived must never race this step.
+ const lateHandle = handshakeFence.seal();
if (!slots.has("acp_runtime")) return;
if (decision.kind === "save" && decision.savedId === "acp_runtime") return;
- const settlement: RuntimeSettlementPlan = runtimeSettlement ?? {
+ const baseSettlement: RuntimeSettlementPlan = runtimeSettlement ?? {
mode: "direct",
handle: syntheticCloseHandle(),
reason: "paperclip cleanup",
@@ -4431,6 +4701,12 @@ export function createAcpxEngineExecutor(deps: AcpxEngineExecutorOptions = {}) {
cancelTurnReason: null,
skipRemoteClose: false,
};
+ // A late handle that arrived before this seal replaces the synthetic
+ // placeholder, so the one close call below uses the real identity
+ // `ensureSession` eventually returned.
+ const settlement: RuntimeSettlementPlan = lateHandle
+ ? { ...baseSettlement, handle: lateHandle }
+ : baseSettlement;
// Cancel a running turn before the close (the turn-error path).
if (settlement.cancelTurnReason && activeTurn) {
await activeTurn.cancel({ reason: settlement.cancelTurnReason }).catch(() => {});
@@ -4457,6 +4733,14 @@ export function createAcpxEngineExecutor(deps: AcpxEngineExecutorOptions = {}) {
}
return;
}
+ // The handshake guard abandoned this `ensureSession` call and no late
+ // handle has arrived yet. Do not close the synthetic placeholder now:
+ // the real handle can still resolve later, and closing it too would
+ // close the same session twice. `handshakeFence`'s own late-arrival
+ // hook (armed at the `ensureSession` call site) closes it once,
+ // whenever it shows up. A guarded call only ever runs on a cold
+ // start, so there is no matching warm entry here to drop.
+ if (handshakeAbandoned && !lateHandle) return;
if (
settlement.mode === "warm_or_close" &&
warmHandleMatches(existing, runtime, settlement.handle) &&