Files
PaperClipAI/packages/paperclip-runner/src/drivers/acpx/runtime-host.ts
T
Nicky LeachandClaude Opus 5.5 c603f591dc fix(runner): bound ACPX instructions only where the sandbox delivers them (#21646)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The Runner prepares a private sandbox for each ACPX agent before it
opens the provider session
> - `validateProviderPolicy` in that sandbox stage refuses system
instructions over 32 KiB for every ACPX agent
> - Only Pi gets the text from the sandbox stage. Claude, Codex, Grok
and Antigravity do not use it there. The host accepts 256 KiB
> - An agent with a large instruction bundle fails every run at
`session.open`. The error says only `classification=admission_sandbox`,
so the operator cannot see the cause
> - This pull request applies the 32 KiB sandbox bound only to Pi, and
gives every instructions rejection its own closed admission code
> - The benefit is that Claude and Codex agents with large instructions
can start, and an over-bound rejection names its real cause

## Linked Issues or Issue Description

Fixes: #20814

Refs #14430 (this pull request added the 32 KiB check, with no stated
reason for the other providers)

Related: #21644 (also fixes #20814, but only for Claude, and does not
change the classification)

**What happened?**
Every run of a Claude ACPX agent failed with
`provider_session_open_rejected`. The message was `ACPX sidecar command
session.open was rejected (retryable=false,
classification=admission_sandbox)`. A reproduction in a sandbox from the
same image showed that all the filesystem steps of
`prepareAcpxRuntimeSandbox` succeed. The real cause: the agent's
instructions entry file was 54,734 bytes. That is more than the 32 KiB
check in `validateProviderPolicy`. The host bound (`boundedInstructions`
in `runtime-host.ts`) is 256 KiB. Agents with smaller instructions (12.7
KB) work.

**Expected behavior**
The sandbox stage must refuse only the text that it delivers. #14430
added the check when only Pi consumed `systemInstructions` in the
sandbox (as the `PAPERCLIP_PI_SYSTEM_INSTRUCTIONS` env var). The check
runs before any per-provider branch, so it also refuses Claude, Codex,
Grok and Antigravity. Those providers get the text in the session
request. When a bound refuses the text, the error must name the
instructions, not the sandbox.

**Steps to reproduce**
1. Create a Claude ACPX agent whose composed instructions are more than
32 KiB (for example, an `AGENTS.md` of 54 KB).
2. Start a run of the agent on the Paperclip Runner.
3. See that `session.open` fails with
`classification=admission_sandbox`.

**Paperclip version/commit**
`master` at 163d9f323c.

**Deployment mode**
Paperclip Runner with ACPX providers (any deployment).

Where each provider consumes `systemInstructions` today:

| Provider | Delivery | Bound |
| --- | --- | --- |
| Pi | `PAPERCLIP_PI_SYSTEM_INSTRUCTIONS` env var (sandbox) | 32 KiB in
`validateProviderPolicy` (kept) |
| Cursor | `PAPERCLIP_CURSOR_INSTRUCTIONS` env var (sandbox) | 32 KiB in
`cursorInstructionBinding` |
| Kimi | `PAPERCLIP_KIMI_INSTRUCTIONS` env var (sandbox) | 32 KiB in
`kimiInstructionBinding` |
| Copilot | `copilot-instructions.md` (host, after the sandbox stage) |
32 KiB in `composeCopilotSystemInstructions` and
`refreshCopilotSystemInstructions` |
| Claude, Codex, Grok, Antigravity | session request
(`systemPrompt.append` or the provider's own session admission) | host
bound, 256 KiB |

## What Changed

- `runtime-sandbox.ts`: `validateProviderPolicy` gets the agent. It
applies the 32 KiB bound only to Pi. The type and NUL checks stay for
all agents. Cursor, Kimi and Copilot keep their own 32 KiB checks.
- `admission-diagnostics.ts`: new closed admission code
`ACPX_ADMISSION_INSTRUCTIONS`, and `acpxInstructionsAdmissionError`,
which tags the error with that code. The tag wins over the stage code
that the host records later.
- The instructions bound and NUL rejections in `runtime-sandbox.ts`,
`runtime-host.ts` (`boundedInstructions`), `cursor-instructions.ts`,
`kimi-instructions.ts` and `copilot-profile.ts` use the new tagged
error. The messages contain no instruction text and no provider output.
- `acpx_sidecar_transport.rs`: `ACPX_ADMISSION_INSTRUCTIONS` maps to
`classification=admission_instructions`. The classification set stays
closed.
- `antigravity-connection-probe.ts`: the closed classification pattern
accepts `admission_instructions`.
- `copilot-installation.test.ts`: the v70 identity test compared two
historical source hashes with the live files. Since #18325, Runner
source changes do not advance profile identities. The test now pins the
hashes that the v70 record holds.

## Verification

- Red-green: the new tests failed on `master` (11 failed) and pass with
the fix.
- `cd packages/paperclip-runner && npx vitest run
src/drivers/acpx/runtime-sandbox.test.ts
src/drivers/acpx/runtime-host.test.ts
src/drivers/acpx/kimi-instructions.test.ts
src/drivers/acpx/cursor-instructions.test.ts
src/drivers/acpx/copilot-profile.test.ts
src/drivers/acpx/copilot-runtime-host.test.ts
src/drivers/acpx/pi-acp-runtime.test.ts src/cli`: 29 files, 489 tests
pass.
- New tests:
- The sandbox admits 54,734-byte instructions for Claude, Codex, Grok
and Antigravity, and does not put them in the launch environment.
- The host opens a Claude runtime with 54,734-byte instructions and
passes the full text to the provider.
- Pi and Cursor sandboxes refuse more than 32 KiB with
`ACPX_ADMISSION_INSTRUCTIONS`. NUL also gives that code.
- Through the host and the sidecar error mapping
(`acpxSidecarErrorCode`), oversized Pi (32 KiB + 1), Copilot (32 KiB +
1) and Claude (256 KiB + 1) instructions give
`ACPX_ADMISSION_INSTRUCTIONS` before the provider launches.
- The Rust classification test maps `ACPX_ADMISSION_INSTRUCTIONS` to
`admission_instructions`.
- The Antigravity probe logs `admission_instructions` as a closed
classification.
- `cargo test -p paperclip-runner-core --lib
classifies_only_allowlisted_internal_sidecar_failures` passes. `cargo
fmt --check` passes.
- `tsc -p packages/paperclip-runner/tsconfig.json --noEmit` passes.
- `cd server && npx vitest run
src/__tests__/antigravity-connection-probe.test.ts`: 11 tests pass.
- I did not do a live provider run. I did not run the full local suite.
CI supplies that coverage.

## Risks

- Low risk. The bound gets less strict only for providers that do not
get the text from the sandbox stage. Those providers stay under the host
bound (256 KiB). Pi, Cursor, Kimi and Copilot keep 32 KiB.
- An over-bound rejection now reports `admission_instructions` and not
`admission_sandbox` (or `admission_configuration` for Copilot). A
dashboard or alert that matches the old classification for this case
must also match the new one. Server code that checks a specific
classification does not check these values, except the Antigravity
probe, which this pull request updates.
- The NUL rejection message in `validateProviderPolicy` changes from
"exceed their bounded size" to "are invalid".

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use and
code execution.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 13:40:20 -08:00

1449 lines
57 KiB
TypeScript

import { retainAcpxCredentialRefresh } from "./credential-refresh.js";
import type { AcpxTurnDispatchJournal } from "./turn-dispatch-journal.js";
import { assertAcpxExecutionAdmission, parseAcpxCandidateStartupAdmission, type AcpxCandidateStartupAdmission } from "./candidate-admission.js";
import { resolveGrokDisableWebSearch } from "./grok-web-search.js";
import { acpxInstructionsAdmissionError, recordAcpxAdmissionFailure, type ACPX_ADMISSION_CODES } from "./admission-diagnostics.js";
import { composeCopilotSystemInstructions } from "./copilot-profile.js";
import { resolveClaudeEffort } from "./claude-effort.js";
import { resolveGrokEffort } from "./grok-effort.js";
import { piProviderConfiguration } from "./pi-provider-config.js";
import { withAcpxTurnCancellation } from "./turn-cancellation.js";
import type { AcpxTerminalSessionFailure } from "./provider-failure.js";
import type { ClaudeBackgroundTaskState } from "./claude-background-tasks.js";
import type { ClaudeProviderCycleItem } from "./claude-provider-turns.js";
import { resolveAcpxProviderMode } from "./provider-mode.js";
import { resolvePiThinkingLevel, type PiThinkingLevel } from "./pi-thinking.js";
import { preparedHarnessHome, preconfiguredHomeEnvironment, usesPreconfiguredHome } from "../preconfigured-home.js";
import { dirname, join } from "node:path";
import { bindAcpxAgentFiles } from "./agent-files-binding.js";
import { assertAcpxProfileEnvironment, assertAcpxProfileWorkspace, classifyAcpxProfileError, verifyAcpxProfileInstallation } from "./profile-installation.js";
import { createAcpxRuntimeSkillLease } from "./runtime-skill-lease.js";
import { stageManagedGrokCredential } from "./grok-credentials.js";
import { stageManagedAntigravityCredential } from "./antigravity-credentials.js";
import { claudeNativeSkillPrompt } from "./native-skill-prompt.js";
import { prepareStdioMcpBindings } from "../stdio-mcp.js";
import type {
AcpRuntimeOptions,
AcpRuntimeEvent,
AcpRuntimeTurnResult,
} from "acpx/runtime";
import type { NativeAcpxPermissionMode } from "../../contracts/native-execution.js";
import type { NativeRuntimeContextSnapshot } from "../../contracts/runtime-context.js";
import {
materializeNativeRuntimeSkills,
releaseMaterializedNativeRuntimeSkills,
} from "../runtime-context-materializer.js";
import {
startRunnerToolBridge,
type RunnerToolBridge,
type RunnerToolBridgeOptions,
} from "../runner-tool-bridge.js";
import {
acquireAcpxProviderLifetimeLease,
stageManagedCodexCredential,
type AcpxProviderLifetimeLease,
} from "./codex-credentials.js";
import {
type VerifiedAcpxCommandLease,
type VerifiedAcpxInstallation,
} from "./installation-integrity.js";
import { createAcpxCommandLeaseOwner } from "./command-lease-owner.js";
import type { AcpxHostElicitationHandler, AcpxHostExtensionRequestHandler, AcpxHostPermissionHandler } from "./interaction-delivery.js";
import {
requireVerifiedAcpxModel,
type AcpxModelStatus,
} from "./model-verification.js";
import { acpxRuntimePermissionPolicy } from "./permission-policy.js";
import {
resolveQualifiedAcpxProfile,
type QualifiedAcpxAgent,
type QualifiedAcpxProfile,
} from "./qualified-profiles.js";
import {
createAcpxIdentityRecord,
createAcpxRecoveryBinding,
verifyExpectedAcpxIdentity,
type AcpxIdentityRecord,
type AcpxRecoveryBinding,
} from "./recovery-identity.js";
import {
prepareAcpxRuntimeSandbox,
refreshCopilotSystemInstructions,
type AcpxRuntimeSandbox,
type AcpxProviderRuntimePolicy,
} from "./runtime-sandbox.js";
import type { AcpxExpectedSessionIdentity } from "./sidecar-protocol.js";
export const ACPX_TURN_CANCELLATION_SHUTDOWN_BOUND_MS = 2_000;
const RUNTIME_ADMISSION_VERIFICATION_TIMEOUT_MS = 8_000;
const activeRuntimeHostCleanupOwners = new Set<Promise<unknown>>();
class AcpxRuntimeAdmissionTimeoutError extends Error {
readonly code = "ACPX_RUNTIME_ADMISSION_VERIFICATION_TIMEOUT";
constructor() {
super("ACPX runtime admission verification exceeded its deadline");
this.name = "AcpxRuntimeAdmissionTimeoutError";
}
}
const ACPX_ADMISSION_CLEANUP_BATCH_ATTEMPTS = 8;
const ACPX_ADMISSION_CLEANUP_RETRY_DELAY_MS = 10;
const ACPX_ADMISSION_CLEANUP_RESCHEDULE_MS = 1_000;
export interface AcpxRuntimePortIdentity {
mode?: string;
piThinkingLevel?: PiThinkingLevel;
claudeEffort?: "low" | "medium" | "high" | "xhigh" | "max";
grokEffort?: "minimal" | "low" | "medium" | "high" | "xhigh";
grokDisableWebSearch?: boolean;
acpxRecordId: string;
backendSessionId: string;
agentSessionId: string;
}
export interface AcpxRuntimeGoalCapability {
version: number;
controlMethod: string;
actions: Array<"set" | "pause" | "resume" | "clear">;
}
export interface AcpxRuntimeSteeringCapability {
steering: boolean;
queuedFollowUp: boolean;
}
export interface AcpxRuntimeGoalSnapshot {
objective: string;
status: "active" | "paused" | "blocked" | "limited" | "complete";
tokenBudget?: number | null;
tokensUsed?: number;
timeUsedSeconds?: number;
iterations?: number;
lastReason?: string | null;
createdAt?: number | string | null;
updatedAt?: number | string | null;
}
/** A harness-native proposed plan captured for Paperclip's approval gate. */
export interface AcpxPlanProposal {
toolCallId: string;
markdown: string;
}
export interface AcpxRuntimeTurnInput {
text: string;
requestId: string;
signal?: AbortSignal;
onElicitation?: AcpxHostElicitationHandler;
onPermissionRequest?: AcpxHostPermissionHandler;
onExtensionRequest?: AcpxHostExtensionRequestHandler;
onExtensionNotification?: AcpRuntimeOptions["onExtensionNotification"];
/** Receives a harness-native proposed plan that Paperclip, not the harness, approves. */
onPlanProposal?: (proposal: AcpxPlanProposal) => void;
/** Receives the typed AIR failure behind ACPX's generic terminal error. */
onTerminalSessionFailure?: (failure: AcpxTerminalSessionFailure) => void;
/** Records the turn start and the prompt dispatch durably (turn-dispatch-journal.ts). */
dispatchJournal?: AcpxTurnDispatchJournal;
}
export interface AcpxRuntimeTurn {
readonly requestId: string;
readonly promptStarted: Promise<void>;
readonly events: AsyncIterable<AcpRuntimeEvent>;
readonly result: Promise<AcpRuntimeTurnResult>;
cancel(input?: { reason?: string }): Promise<void>;
closeStream(input?: { reason?: string }): Promise<void>;
}
/** Minimal third-party ACP runtime surface admitted by the host boundary. */
export type AcpxProviderTurnBinding = {
onPermissionRequest: AcpxHostPermissionHandler;
onPlanProposal?: (proposal: AcpxPlanProposal) => void;
busy(): boolean;
};
export interface AcpxProviderCycleStream {
next(): Promise<ClaudeProviderCycleItem | null>;
adopt(binding: AcpxProviderTurnBinding): boolean;
drop(): void;
cancel(): boolean;
decisionFor(toolCallId: unknown): Promise<boolean> | null;
}
export interface AcpxRuntimePort {
identity(): Promise<AcpxRuntimePortIdentity>;
getStatus(): Promise<AcpxModelStatus>;
setModel?(model: string): Promise<void>;
steeringCapability?(): AcpxRuntimeSteeringCapability | null;
steerActiveTurn?(text: string, requestId: string): Promise<void>;
queueFollowUp?(text: string, requestId: string): Promise<void>;
goalCapability?(): AcpxRuntimeGoalCapability | null;
goalSnapshot?(): AcpxRuntimeGoalSnapshot | null;
backgroundTaskState?(): ClaudeBackgroundTaskState | null;
providerCycles?(): AcpxProviderCycleStream | null;
providerTurnsAvailable?(): boolean;
controlGoal?(
action: "set" | "pause" | "resume" | "clear",
objective?: string,
): Promise<AcpxRuntimeGoalSnapshot | null>;
startTurn(input: AcpxRuntimeTurnInput): AcpxRuntimeTurn;
close(input: { reason: string }): Promise<void>;
}
export interface AcpxRuntimePortOpenOptions {
/** A durable identity was admitted; restored native mode must already match. */
restoringSession?: boolean;
/** Ephemeral provider extension metadata; mandatory ACP caps remain host-owned. */
clientCapabilities?: Record<string, unknown>;
command: VerifiedAcpxCommandLease;
/** Replace a consumed launch snapshot after an ephemeral control session. */
refreshConsumedCommand?: () => Promise<void>;
profile: QualifiedAcpxProfile;
cwd: string;
stateDirectory: string;
providerSessionKey: string;
permissionMode: NativeAcpxPermissionMode;
readOnly?: boolean;
mode?: string;
piThinkingLevel?: PiThinkingLevel;
claudeEffort?: "low" | "medium" | "high" | "xhigh" | "max";
grokEffort?: "minimal" | "low" | "medium" | "high" | "xhigh";
grokDisableWebSearch?: boolean;
permissionPolicy: ReturnType<typeof acpxRuntimePermissionPolicy>;
launchEnvironment: Readonly<NodeJS.ProcessEnv>;
/** Kernel credential-home quorum inherited by the provider sentinel. */
credentialFenceFds: readonly [number, number] | null;
/** Validate the guardian while the credential-home quorum is held. */
activateCredentialFenceOwner: ((pid: number) => Promise<void>) | null;
systemInstructions: string;
/** Revalidate a pinned recovery workspace at the provider spawn boundary. */
assertWorkspaceHeld?: () => void;
/** Abort provider admission and clean any runtime that resolves too late. */
signal?: AbortSignal;
mcpServers: readonly AcpxMcpServerBinding[];
onGoalUpdate?: (goal: AcpxRuntimeGoalSnapshot | null) => void;
/**
* Transfer the provider cleanup proof before a failed open settles. The host
* keeps credentials fenced until this exact cleanup succeeds.
*/
retainFailedAdmissionCleanup(cleanup: Promise<void>): void;
}
export type AcpxMcpServerBinding = {
name: string; url: string; bearerToken: string; runnerOwned: boolean;
} | {
name: string; command: string; args: string[]; env: Record<string, string>; runnerOwned: false;
};
export type AcpxSemanticToolSession = Omit<RunnerToolBridgeOptions, "secret" | "preloadClaudeTaskTools">;
export interface AcpxRetainedCleanupFailure {
resource:
"credential" | "provider_lifetime" | "command" | "runtime" | "tool_bridge" | "skills";
attempt: number;
error: unknown;
}
export interface AcpxRuntimeHostDependencies {
verifyInstallation?: (
profile: QualifiedAcpxProfile,
) => Promise<VerifiedAcpxInstallation>;
/** Internal test seam for aborting credential acquisition. */
stageCredential?: typeof stageManagedCodexCredential;
openRuntime(options: AcpxRuntimePortOpenOptions): Promise<AcpxRuntimePort>;
/** Internal test seam for deterministic sandbox-admission scheduling. */
prepareSandbox?: typeof prepareAcpxRuntimeSandbox;
/** Internal test seam for the post-handshake admission deadline. */
admissionVerificationTimeoutMs?: number;
/** Internal test seam for failed-admission cleanup. */
admissionCleanupTimeoutMs?: number;
/**
* Transfers failed-admission cleanup ownership to the embedding lifecycle.
* The callback receives the exact aggregate cleanup attempt before the
* bounded admission wait can return.
*/
retainAdmissionCleanup?: (cleanup: Promise<void>) => void;
/**
* Required observability channel for resources acquired after admission was
* aborted. Implementations must not throw from this callback.
*/
reportRetainedCleanupFailure(failure: AcpxRetainedCleanupFailure): void;
}
export interface OpenAcpxRuntimeHostOptions {
/** Trusted startup authority from runnerd; never provider session data. */
candidateAdmission?: AcpxCandidateStartupAdmission;
/** Explicit task execution policy; never inferred from auto-approval. Required for Pi. */
providerPolicy?: AcpxProviderRuntimePolicy;
/** Never persisted as session options or recovery identity. */
clientCapabilities?: Record<string, unknown>;
runtimeDirectory: string;
normalizedSessionId: string;
workingDirectory: string;
agent: QualifiedAcpxAgent;
model: string;
permissionMode: NativeAcpxPermissionMode;
mode?: string;
piThinkingLevel?: PiThinkingLevel;
claudeEffort?: "low" | "medium" | "high" | "xhigh" | "max";
grokEffort?: "minimal" | "low" | "medium" | "high" | "xhigh";
grokDisableWebSearch?: boolean;
systemInstructions?: string;
runtimeContext?: NativeRuntimeContextSnapshot | null;
environment?: NodeJS.ProcessEnv;
managedCodexCredentialSourcePath?: string;
expectedIdentity?: AcpxExpectedSessionIdentity;
/** Revalidate a pinned recovery workspace through provider admission. */
assertWorkspaceHeld?: () => void;
/** Abort admission without admitting resources that resolve afterward. */
signal?: AbortSignal;
semanticTools?: AcpxSemanticToolSession;
assignedMcpTransport?: "prp";
onGoalUpdate?: (goal: AcpxRuntimeGoalSnapshot | null) => void;
}
const RETAINED_CLEANUP_RETRY_INITIAL_DELAY_MS = 10;
const RETAINED_CLEANUP_RETRY_MAX_DELAY_MS = 1_000;
interface RetainedRejectedRuntimeAdmission {
readonly credential: AcpxProviderLifetimeLease;
cleanup: Promise<void>;
}
// A rejected provider open is not itself proof that provider processes are
// gone. Retain the credential with the adapter's exact cleanup proof and scrub
// it only after that proof succeeds. Terminal cleanup failure stays inert and
// fenced instead of exposing the credential to a replacement admission.
const retainedRejectedRuntimeAdmissions =
new Set<RetainedRejectedRuntimeAdmission>();
interface RetainedAcpxAdmissionCleanup {
readonly runtime: AcpxRuntimePort | null;
readonly toolBridge: RunnerToolBridge | null;
readonly credential: AcpxProviderLifetimeLease | null;
readonly command: VerifiedAcpxCommandLease | null;
readonly reason: string;
recovery: Promise<void> | null;
timer: ReturnType<typeof setTimeout> | null;
}
// An admission failure has no AcpxRuntimeHost instance for a caller to close.
// Retain those resources here until provider shutdown succeeds and the staged
// credential can consequently be scrubbed. Each recovery batch is finite and
// sequential; an unref'd timer rate-limits later autonomous attempts without
// allowing the failed admission's ownership to become unreachable.
const retainedAcpxAdmissionCleanups = new Set<RetainedAcpxAdmissionCleanup>();
export class AcpxRuntimeHost {
readonly #runtime: AcpxRuntimePort;
readonly #binding: AcpxRecoveryBinding;
readonly #identity: AcpxIdentityRecord;
readonly #sandbox: AcpxRuntimeSandbox;
readonly #credential: AcpxProviderLifetimeLease | null;
readonly #command: VerifiedAcpxCommandLease;
readonly #toolBridge: RunnerToolBridge | null;
readonly #claudeSkillNames: readonly string[];
readonly #assertAgentFilesHeld: (() => void) | undefined;
readonly #candidateAdmission: AcpxCandidateStartupAdmission | undefined;
#activeTurn: AcpxRuntimeTurn | null = null;
#activeTurnInterruption: AcpxRuntimeTurn["cancel"] | null = null;
#closingStarted = false;
#closePromise: Promise<void> | null = null;
#closed = false;
private constructor(input: {
runtime: AcpxRuntimePort;
binding: AcpxRecoveryBinding;
identity: AcpxIdentityRecord;
sandbox: AcpxRuntimeSandbox;
credential: AcpxProviderLifetimeLease | null;
command: VerifiedAcpxCommandLease;
toolBridge: RunnerToolBridge | null;
claudeSkillNames: readonly string[];
assertAgentFilesHeld?: () => void;
candidateAdmission?: AcpxCandidateStartupAdmission;
}) {
this.#runtime = input.runtime;
this.#binding = input.binding;
this.#identity = input.identity;
this.#sandbox = input.sandbox;
this.#credential = input.credential;
this.#command = input.command;
this.#toolBridge = input.toolBridge;
this.#claudeSkillNames = [...input.claudeSkillNames];
this.#assertAgentFilesHeld = input.assertAgentFilesHeld;
this.#candidateAdmission = input.candidateAdmission ? structuredClone(input.candidateAdmission) : undefined;
}
static async open(
options: OpenAcpxRuntimeHostOptions,
dependencies: AcpxRuntimeHostDependencies,
): Promise<AcpxRuntimeHost> {
options.signal?.throwIfAborted();
if (options.agent === "pi" && typeof options.providerPolicy?.readOnly !== "boolean") {
throw new Error("Pi admission requires an explicit task execution policy");
}
const preconfigured = usesPreconfiguredHome(options.environment);
const preparedHome = preparedHarnessHome(options.environment, options.agent);
if (preconfigured && options.permissionMode !== "approve-all") {
throw new Error("preconfigured home currently requires ACPX approve-all; local permission rules still apply");
}
// shortcut: qualify a read-only provider launch before enabling preconfigured ACPX planning.
if (preconfigured && options.providerPolicy?.readOnly) {
throw new Error("preconfigured ACPX read-only execution is not supported; use isolated mode or native Codex");
}
// shortcut: qualify session permissions that deny Runner state before enabling this provider.
if (preconfigured && options.agent === "codex") throw new Error("preconfigured ACPX Codex cannot protect Runner state; use native Codex or isolated mode");
if (!preconfigured && options.runtimeContext?.mcp.bindingId
&& !(options.assignedMcpTransport === "prp" && options.semanticTools)) {
throw new Error("assigned native MCP launch binding is unavailable");
}
const profile = resolveQualifiedAcpxProfile(options.agent, options.model);
if (options.candidateAdmission) {
assertAcpxExecutionAdmission(profile, options.candidateAdmission);
options = { ...options, candidateAdmission: parseAcpxCandidateStartupAdmission(options.candidateAdmission, { agent: options.agent, model: options.model, normalizedSessionId: options.normalizedSessionId }) };
if (preconfigured || typeof options.providerPolicy?.readOnly !== "boolean") throw new Error("ACPX candidate requires a fresh isolated session and explicit task policy");
}
const binding = await runAbortableAdmissionStage(
options.signal,
() =>
createAcpxRecoveryBinding({
runtimeDirectory: options.runtimeDirectory,
normalizedSessionId: options.normalizedSessionId,
workingDirectory: options.workingDirectory,
profile,
requestedModel: options.model,
...(options.agent === "pi" ? { providerConfigurationDigest: piProviderConfiguration(options.environment)?.digest } : {}),
permissionMode: options.permissionMode,
mode: resolveAcpxProviderMode(options.agent, options.mode),
piThinkingLevel: resolvePiThinkingLevel(options.agent, options.piThinkingLevel),
claudeEffort: resolveClaudeEffort(options.agent, options.claudeEffort),
grokEffort: resolveGrokEffort(options.agent, options.grokEffort),
grokDisableWebSearch: resolveGrokDisableWebSearch(options.agent, options.grokDisableWebSearch),
...(preconfigured || preparedHome ? { homeBinding: preconfiguredHomeEnvironment(options.environment) } : {}),
...(["cursor", "copilot", "pi", "kimi"].includes(options.agent) && options.providerPolicy !== undefined
? { providerPolicy: options.providerPolicy } : {}),
}),
dependencies.retainAdmissionCleanup,
).catch(error => { throw recordAcpxAdmissionFailure(error, "binding"); });
if (options.expectedIdentity) {
verifyExpectedAcpxIdentity(options.expectedIdentity, binding, null);
}
options.assertWorkspaceHeld?.();
if (
options.agent !== "codex" &&
options.managedCodexCredentialSourcePath !== undefined
) {
throw new Error(
"Managed Codex credentials require the Codex ACPX profile",
);
}
const installation = await runAbortableAdmissionStage(
options.signal,
() =>
dependencies.verifyInstallation
? dependencies.verifyInstallation(profile)
: verifyAcpxProfileInstallation(profile, options.candidateAdmission),
dependencies.retainAdmissionCleanup,
).catch(error => { throw recordAcpxAdmissionFailure(error, "installation"); });
if (installation.commandDigest !== profile.commandDigest) {
throw new Error("Verified ACPX installation does not match its profile");
}
let admissionSucceeded = false;
let command: VerifiedAcpxCommandLease | null = null;
let credential: AcpxProviderLifetimeLease | null = null;
let toolBridge: RunnerToolBridge | null = null;
let runtime: AcpxRuntimePort | null = null;
let pendingRuntimeOwnsCredential = false;
const admissionVerificationTimeoutMs =
dependencies.admissionVerificationTimeoutMs ??
RUNTIME_ADMISSION_VERIFICATION_TIMEOUT_MS;
const admissionCleanupTimeoutMs =
dependencies.admissionCleanupTimeoutMs ??
RUNTIME_ADMISSION_VERIFICATION_TIMEOUT_MS;
let failedAdmissionCleanupTransferred = false;
let resolveFailedAdmissionCleanupTransfer!: () => void;
const failedAdmissionCleanupTransfer = new Promise<void>((resolve) => {
resolveFailedAdmissionCleanupTransfer = resolve;
});
const retainFailedAdmissionCleanup = (cleanup: Promise<void>): void => {
if (failedAdmissionCleanupTransferred) return;
failedAdmissionCleanupTransferred = true;
pendingRuntimeOwnsCredential = credential !== null;
resolveFailedAdmissionCleanupTransfer();
if (credential === null) {
retainRuntimeHostCleanup(cleanup);
return;
}
const retained: RetainedRejectedRuntimeAdmission = {
credential,
cleanup: Promise.resolve(),
};
const ownedCleanup = cleanup.then(async () => {
await cleanupAbortedRuntimeAdmission(
null,
retained.credential,
"ACPX rejected runtime admission cleanup confirmed",
);
retainedRejectedRuntimeAdmissions.delete(retained);
});
retained.cleanup = ownedCleanup;
retainedRejectedRuntimeAdmissions.add(retained);
retainRuntimeHostCleanup(ownedCleanup);
};
let admissionStage: keyof typeof ACPX_ADMISSION_CODES = "sandbox";
try {
const sandbox = await runAbortableAdmissionStage(
options.signal,
() =>
(dependencies.prepareSandbox ?? prepareAcpxRuntimeSandbox)({
binding,
agent: options.agent,
environment: options.environment,
tools: options.semanticTools?.tools,
...(options.providerPolicy === undefined ? {} : { providerPolicy: {
...options.providerPolicy,
systemInstructions: boundedInstructions(options.systemInstructions),
protectedPaths: [
...(options.providerPolicy.protectedPaths ?? []),
...(installation.agentServerPackageJsonPath === null
? []
: [dirname(installation.agentServerPackageJsonPath)]),
],
} }),
}),
dependencies.retainAdmissionCleanup,
);
admissionStage = "credential";
if (options.agent === "antigravity") assertAcpxProfileEnvironment(options.agent, options.environment ?? {});
if (options.agent === "codex" && !preconfigured) {
credential = await acquireAbortableAdmissionResource({
signal: options.signal,
acquire: async () => {
const lease = await (dependencies.stageCredential ?? stageManagedCodexCredential)({
agentHomeDirectory: sandbox.agentHomeDirectory,
environment: options.environment,
sourcePath: options.managedCodexCredentialSourcePath,
});
return retainAcpxCredentialRefresh({
lease, agentHomeDirectory: sandbox.agentHomeDirectory,
retainRefresh: () => admissionSucceeded && lease.mode !== "api_key",
});
},
resource: "credential",
releaseLate: (lateCredential) => lateCredential.close(),
reportFailure: (failure) =>
dependencies.reportRetainedCleanupFailure(failure),
});
} else if (options.agent === "antigravity") {
credential = await acquireAbortableAdmissionResource({
signal: options.signal,
acquire: () => stageManagedAntigravityCredential({ agentHomeDirectory: sandbox.agentHomeDirectory,
environment: options.environment, retainRefresh: () => admissionSucceeded }),
resource: "credential", releaseLate: late => late.close(),
reportFailure: failure => dependencies.reportRetainedCleanupFailure(failure),
});
} else if (options.agent === "grok") {
credential = await acquireAbortableAdmissionResource({
signal: options.signal,
acquire: () => stageManagedGrokCredential({ agentHomeDirectory: sandbox.agentHomeDirectory, environment: options.environment, retainRefresh: () => admissionSucceeded }),
resource: "credential", releaseLate: (lease) => lease.close(),
reportFailure: (failure) => dependencies.reportRetainedCleanupFailure(failure),
});
} else {
credential = await acquireAbortableAdmissionResource({
signal: options.signal,
acquire: () =>
acquireAcpxProviderLifetimeLease({
agentHomeDirectory: preconfigured ? sandbox.root : sandbox.agentHomeDirectory,
}),
resource: "provider_lifetime",
releaseLate: (lateLifetime) => lateLifetime.close(),
reportFailure: (failure) =>
dependencies.reportRetainedCleanupFailure(failure),
});
}
options.signal?.throwIfAborted();
admissionStage = "configuration";
const configurationLifetime = credential;
await runAbortableAdmissionStage(
options.signal,
async () => { await sandbox.initializeOwnedConfiguration?.(); },
cleanup => {
pendingRuntimeOwnsCredential = true;
const retained = cleanup.then(() => cleanupAbortedRuntimeAdmission(
null, configurationLifetime, "ACPX owned configuration cancelled",
));
retainRuntimeHostCleanup(retained);
dependencies.retainAdmissionCleanup?.(retained);
},
);
options.signal?.throwIfAborted();
admissionStage = "credential";
// Antigravity's selected OAuth document has already been validated and
// staged; it is intentionally absent from the native launch environment.
if (options.agent !== "antigravity") assertAcpxProfileEnvironment(options.agent, sandbox.launchEnvironment);
admissionStage = "configuration";
let launchEnvironment = sandbox.launchEnvironment;
// This copy is registered by the authenticated controller for its company,
// agent and run. Environment/config values cannot widen the grant. Each
// resumed process receives the newly registered copy; collection already
// requires verified provider shutdown in the native executor.
const agentFiles = ["cursor", "copilot", "pi", "kimi"].includes(options.agent)
? bindAcpxAgentFiles(options.runtimeContext, [sandbox.root,
...(installation.agentServerPackageJsonPath === null ? [] : [dirname(installation.agentServerPackageJsonPath)]),
]) : null;
if (agentFiles) {
launchEnvironment = Object.freeze({ ...launchEnvironment, AGENT_HOME: agentFiles.root,
...(options.agent === "pi" ? { PAPERCLIP_PI_AGENT_HOME: agentFiles.root } : {}),
});
}
if (options.agent === "copilot") {
// A rejected contender must never overwrite an active provider's text.
// Do not race this write against cancellation: retain the lifetime lease
// until the atomic refresh settles, then honor an intervening abort.
options.signal?.throwIfAborted();
await refreshCopilotSystemInstructions(
sandbox,
composeCopilotSystemInstructions(boundedInstructions(options.systemInstructions)),
);
options.signal?.throwIfAborted();
}
admissionStage = "skills";
if (options.agent === "pi") {
const skills = await acquireAbortableAdmissionResource({
signal: options.signal,
acquire: () => createAcpxRuntimeSkillLease(options.runtimeContext ?? null),
resource: "skills", releaseLate: value => value.close(),
reportFailure: dependencies.reportRetainedCleanupFailure,
});
const providerLifetime = credential;
credential = {
lifetimeFenceCandidates: providerLifetime.lifetimeFenceCandidates,
lifetimeFenceFds: providerLifetime.lifetimeFenceFds,
activateLifetimeOwner: pid => providerLifetime.activateLifetimeOwner(pid),
async close() {
// Only release assigned files after the provider lifetime quorum closes.
await providerLifetime.close();
await skills.close();
},
};
launchEnvironment = Object.freeze({ ...launchEnvironment,
PAPERCLIP_PI_READ_ROOTS: JSON.stringify([...(options.providerPolicy?.readRoots ?? []), ...skills.readRoots]),
});
}
if (!preconfigured && !preparedHome && (options.agent === "claude" || options.agent === "grok" || options.agent === "kimi")) {
// The lifetime lease proves the previous provider has stopped. Refresh
// the assigned snapshot before every launch, including durable resume;
// Claude discovers user skills beneath its isolated CLAUDE_CONFIG_DIR.
const skillsHome = join(sandbox.agentHomeDirectory, "skills");
await releaseMaterializedNativeRuntimeSkills(skillsHome);
await materializeNativeRuntimeSkills(
options.runtimeContext ?? null,
skillsHome,
);
options.signal?.throwIfAborted();
}
admissionStage = "command";
command = await acquireAbortableAdmissionResource({
signal: options.signal,
acquire: () => installation.openCommand({ signal: options.signal }),
resource: "command",
releaseLate: (lateCommand) => lateCommand.close(),
reportFailure: (failure) =>
dependencies.reportRetainedCleanupFailure(failure),
});
const commandOwner = createAcpxCommandLeaseOwner(
command,
signal => installation.openCommand({ signal }),
);
command = commandOwner.command;
admissionStage = "tool_bridge";
toolBridge = options.semanticTools
? await acquireAbortableAdmissionResource({
signal: options.signal,
acquire: () => startRunnerToolBridge({
...options.semanticTools!,
preserveToolNames: options.assignedMcpTransport === "prp",
preloadClaudeTaskTools: options.agent === "claude",
}),
resource: "tool_bridge",
releaseLate: (lateToolBridge) => lateToolBridge.close(),
reportFailure: (failure) =>
dependencies.reportRetainedCleanupFailure(failure),
})
: null;
const admittedLifetime = credential;
if (admittedLifetime === null) {
throw new Error("ACPX provider lifetime lease is unavailable");
}
admissionStage = "runtime";
runtime = await acquireAbortableAdmissionResource({
signal: options.signal,
acquire: async () => {
options.assertWorkspaceHeld?.();
agentFiles?.assertHeld();
await assertAcpxProfileWorkspace(options.agent, binding.workspacePath);
if (options.candidateAdmission) assertAcpxExecutionAdmission(profile, options.candidateAdmission);
return dependencies.openRuntime({
...(options.clientCapabilities === undefined ? {} : {
clientCapabilities: structuredClone(options.clientCapabilities),
}),
command: command!,
refreshConsumedCommand: commandOwner.refreshConsumedCommand,
profile,
cwd: binding.workspacePath,
stateDirectory: sandbox.stateDirectory,
providerSessionKey: binding.profileSessionKey,
restoringSession: options.expectedIdentity !== undefined,
permissionMode: binding.permissionMode,
readOnly: options.providerPolicy?.readOnly,
mode: binding.mode,
piThinkingLevel: binding.piThinkingLevel,
claudeEffort: binding.claudeEffort,
grokEffort: binding.grokEffort, grokDisableWebSearch: binding.grokDisableWebSearch,
permissionPolicy: acpxRuntimePermissionPolicy(
binding.permissionMode,
),
launchEnvironment,
credentialFenceFds: admittedLifetime.lifetimeFenceFds,
activateCredentialFenceOwner:
admittedLifetime.activateLifetimeOwner.bind(admittedLifetime),
systemInstructions: boundedInstructions(options.systemInstructions),
...(options.assertWorkspaceHeld === undefined && !agentFiles
? {}
: { assertWorkspaceHeld: () => { options.assertWorkspaceHeld?.(); agentFiles?.assertHeld(); } }),
...(options.signal === undefined ? {} : { signal: options.signal }),
mcpServers: [
...(options.providerPolicy?.readOnly ? [] : prepareStdioMcpBindings(options.environment ?? {}, sandbox.root)),
...(toolBridge ? [{ name: preconfigured ? `paperclip_runner_${binding.profileSessionKey.slice(-16)}` : "paperclip", url: toolBridge.url,
bearerToken: toolBridge.secret, runnerOwned: true }] : []),
],
...(options.onGoalUpdate === undefined
? {}
: { onGoalUpdate: options.onGoalUpdate }),
retainFailedAdmissionCleanup,
});
},
resource: "runtime",
releaseLate: (lateRuntime) =>
lateRuntime.close({
reason: "ACPX runtime admission aborted",
}),
reportFailure: (failure) =>
dependencies.reportRetainedCleanupFailure(failure),
onAbortedPending: (pendingRuntime) => {
// A provider may already be running even though openRuntime has not
// returned its port. Keep its credential lease with that exact
// admission while the ordinary catch path revokes tools and releases
// the consumed command snapshot without delaying cancellation.
pendingRuntimeOwnsCredential = credential !== null;
retainAbortedRuntimeAdmissionCleanup({
pendingRuntime,
credential,
reason: "ACPX runtime admission aborted",
failedAdmissionCleanupTransfer,
});
},
});
admissionStage = "identity";
const runtimeIdentity = await runAbortableAdmissionStage(
options.signal,
() =>
boundedRuntimeAdmissionVerification(
runtime!,
profile,
admissionVerificationTimeoutMs,
),
dependencies.retainAdmissionCleanup,
);
if (runtimeIdentity.mode !== binding.mode) {
throw new Error("ACPX runtime Provider mode does not match the admitted session configuration");
}
if (runtimeIdentity.piThinkingLevel !== binding.piThinkingLevel) {
throw new Error("ACPX runtime Pi thinking level conflicts with session binding");
}
if (runtimeIdentity.claudeEffort !== binding.claudeEffort) throw new Error("ACPX runtime Claude effort conflicts with session binding");
if (runtimeIdentity.grokEffort !== binding.grokEffort || runtimeIdentity.grokDisableWebSearch !== binding.grokDisableWebSearch) throw new Error("ACPX runtime Grok effort conflicts with session binding");
const observedIdentity: AcpxExpectedSessionIdentity = {
kind: "acpx",
normalizedSessionId: binding.normalizedSessionId,
...runtimeIdentity,
profileDigest: binding.commandDigest,
workspaceDigest: binding.workspaceDigest,
requestedModel: binding.requestedModel,
effectiveModel: binding.effectiveModel,
permissionMode: binding.permissionMode,
providerLifetimeFenceCandidates:
admittedLifetime.lifetimeFenceCandidates,
};
const identity = createAcpxIdentityRecord(observedIdentity, binding);
if (options.expectedIdentity) {
verifyExpectedAcpxIdentity(options.expectedIdentity, binding, identity);
}
options.signal?.throwIfAborted();
admissionSucceeded = true;
return new AcpxRuntimeHost({
runtime,
binding,
identity,
sandbox,
credential,
command,
toolBridge,
assertAgentFilesHeld: agentFiles?.assertHeld,
candidateAdmission: options.candidateAdmission,
claudeSkillNames: options.agent === "claude"
? (options.runtimeContext?.skills.map((skill) => skill.runtimeName) ?? [])
: [],
});
} catch (error) {
error = classifyAcpxProfileError(options.agent, error) ?? error;
recordAcpxAdmissionFailure(error, admissionStage);
const cleanup = cleanupRuntimeResources(
runtime,
toolBridge,
pendingRuntimeOwnsCredential ? null : credential,
command,
"ACPX runtime initialization failed",
);
retainRuntimeHostCleanup(cleanup);
void cleanup.then((cleanupError) => {
if (!cleanupError) return;
retainFailedAcpxAdmissionCleanup({
runtime,
toolBridge,
credential: pendingRuntimeOwnsCredential ? null : credential,
command,
reason: "ACPX runtime initialization failed",
});
});
dependencies.retainAdmissionCleanup?.(
cleanup.then((cleanupError) => {
if (cleanupError) throw cleanupError;
}),
);
const cleanupOutcome = await awaitRuntimeHostCleanupWithin(
cleanup,
admissionCleanupTimeoutMs,
);
if (cleanupOutcome === "deferred") {
throw new AggregateError(
[
error,
new Error(
"ACPX runtime initialization cleanup exceeded its shutdown timeout",
),
],
"ACPX runtime initialization and cleanup failed",
);
}
if (cleanupOutcome) {
throw new AggregateError(
[error, ...cleanupOutcome.errors],
"ACPX runtime initialization and cleanup failed",
);
}
throw error;
}
}
identity(): AcpxIdentityRecord {
return structuredClone(this.#identity);
}
binding(): AcpxRecoveryBinding {
return structuredClone(this.#binding);
}
runtimeRoot(): string {
return this.#sandbox.root;
}
persistedEnvironment(): Readonly<NodeJS.ProcessEnv> {
return Object.freeze({ ...this.#sandbox.persistedEnvironment });
}
async status(): Promise<AcpxModelStatus> {
return structuredClone(await this.#runtime.getStatus());
}
goalCapability(): AcpxRuntimeGoalCapability | null {
return this.#runtime.goalCapability?.() ?? null;
}
steeringCapability(): AcpxRuntimeSteeringCapability | null {
return this.#runtime.steeringCapability?.() ?? null;
}
async steerActiveTurn(text: string, turnId?: string): Promise<void> {
const turn = this.#activeTurn;
if (this.#closed || this.#closingStarted || !turn || (turnId !== undefined && turn.requestId !== turnId)) {
throw new Error("ACPX steering does not own an active turn");
}
if (!this.steeringCapability()?.steering || !this.#runtime.steerActiveTurn) {
throw new Error("ACPX active steering is unavailable");
}
await turn.promptStarted;
if (this.#activeTurn !== turn || this.#closingStarted) throw new Error("ACPX steering turn expired");
await this.#runtime.steerActiveTurn(boundedTurnText(text), turn.requestId);
}
async queueFollowUp(text: string, turnId?: string): Promise<void> {
const turn = this.#activeTurn;
if (this.#closed || this.#closingStarted || !turn || (turnId !== undefined && turn.requestId !== turnId)) {
throw new Error("ACPX follow-up does not own an active turn");
}
if (!this.steeringCapability()?.queuedFollowUp || !this.#runtime.queueFollowUp) {
throw new Error("ACPX queued follow-up is unavailable");
}
await turn.promptStarted;
if (this.#activeTurn !== turn || this.#closingStarted) throw new Error("ACPX follow-up turn expired");
await this.#runtime.queueFollowUp(boundedTurnText(text), turn.requestId);
}
goalSnapshot(): AcpxRuntimeGoalSnapshot | null {
return this.#runtime.goalSnapshot?.() ?? null;
}
backgroundTaskState(): ClaudeBackgroundTaskState | null {
return this.#runtime.backgroundTaskState?.() ?? null;
}
providerCycles(): AcpxProviderCycleStream | null {
return this.#runtime.providerCycles?.() ?? null;
}
providerTurnsAvailable(): boolean {
return this.#runtime.providerTurnsAvailable?.() ?? false;
}
async controlGoal(
action: "set" | "pause" | "resume" | "clear",
objective?: string,
): Promise<AcpxRuntimeGoalSnapshot | null> {
if (!this.#runtime.controlGoal) {
throw new Error("ACPX runtime does not expose session goal controls");
}
return await this.#runtime.controlGoal(action, objective);
}
startTurn(input: AcpxRuntimeTurnInput): AcpxRuntimeTurn {
if (this.#candidateAdmission) parseAcpxCandidateStartupAdmission(this.#candidateAdmission, { agent: this.#candidateAdmission.agent, model: this.#binding.requestedModel, normalizedSessionId: this.#binding.normalizedSessionId });
this.#assertAgentFilesHeld?.();
if (this.#closed || this.#closingStarted) {
throw new Error("ACPX runtime host is closing");
}
if (this.#activeTurn) {
throw new Error("ACPX runtime host already has an active turn");
}
const requestId = boundedRequestId(input.requestId);
// Bound caller input before adding the provider's assigned-skill command.
// The command is internal framing; it must not consume the envelope's
// allowance or cause an otherwise valid envelope to be truncated/rejected.
const text = claudeNativeSkillPrompt(
boundedTurnText(input.text), this.#claudeSkillNames,
);
const turn = this.#runtime.startTurn({
text,
requestId,
...(input.signal ? { signal: input.signal } : {}),
...(input.onElicitation ? { onElicitation: input.onElicitation } : {}),
...(input.onPermissionRequest ? { onPermissionRequest: input.onPermissionRequest } : {}),
...(input.onExtensionRequest ? { onExtensionRequest: input.onExtensionRequest } : {}),
...(input.onExtensionNotification ? { onExtensionNotification: input.onExtensionNotification } : {}),
...(input.onPlanProposal ? { onPlanProposal: input.onPlanProposal } : {}),
...(input.onTerminalSessionFailure ? { onTerminalSessionFailure: input.onTerminalSessionFailure } : {}),
...(input.dispatchJournal ? { dispatchJournal: input.dispatchJournal } : {}),
});
this.#activeTurn = turn;
const managed = withAcpxTurnCancellation(turn, reason => this.close({ reason }), ACPX_TURN_CANCELLATION_SHUTDOWN_BOUND_MS);
this.#activeTurnInterruption = managed.cancel;
void managed.result
.finally(() => {
// Once shutdown owns this turn, retain its cancellation handle until
// runtime cleanup succeeds. The result may settle while cleanup is
// failing, and a later close must still be able to retry cancellation.
if (this.#activeTurn === turn && !this.#closingStarted) {
this.#activeTurn = null;
this.#activeTurnInterruption = null;
}
})
.catch(() => undefined);
return managed;
}
isClosed(): boolean {
return this.#closed;
}
async interruptActiveTurn(reason: string): Promise<void> {
const turn = this.#activeTurn;
if (!turn) throw new Error("ACPX runtime host has no active turn");
await this.#activeTurnInterruption!({ reason: boundedReason(reason) });
}
async close(input: { reason: string }): Promise<void> {
if (this.#closed) return;
if (this.#closePromise) {
return await this.#closePromise;
}
this.#closingStarted = true;
const closePromise = this.#close(boundedReason(input.reason));
this.#closePromise = closePromise;
try {
await closePromise;
this.#closed = true;
} finally {
if (this.#closePromise === closePromise) this.#closePromise = null;
}
}
async #close(reason: string): Promise<void> {
const errors: unknown[] = [];
const activeTurn = this.#activeTurn;
if (activeTurn) {
try {
const cancellationError = await boundedCancellation(
activeTurn.cancel({ reason }),
);
if (cancellationError !== null) errors.push(cancellationError);
} catch (error) {
errors.push(error);
}
}
const cleanupError = await cleanupRuntimeResources(
this.#runtime,
this.#toolBridge,
this.#credential,
this.#command,
reason,
);
if (cleanupError) errors.push(...cleanupError.errors);
if (!cleanupError) {
// Runtime, credential, and command ownership has been relinquished even
// when the provider never acknowledged turn cancellation. Preserve that
// cancellation error for this caller, but make later close calls
// idempotently observe the successfully closed host.
if (this.#activeTurn === activeTurn) this.#activeTurn = null;
this.#closed = true;
}
if (errors.length > 0) {
throw new AggregateError(errors, "ACPX runtime cleanup failed");
}
}
}
async function runAbortableAdmissionStage<T>(
signal: AbortSignal | undefined,
operation: () => Promise<T>,
retainCleanup: ((cleanup: Promise<void>) => void) | undefined,
): Promise<T> {
if (signal === undefined) return await operation();
signal.throwIfAborted();
const pending = Promise.resolve().then(operation);
try {
return await raceAdmissionWithAbort(pending, signal);
} catch (error) {
if (signal.aborted) {
// Abort may win while sandbox preparation or another non-resource stage
// still owns asynchronous work. Keep that exact operation observed and
// expose it to the embedding lifecycle so filesystem teardown cannot
// remove its session root while it is still making durable writes.
// The aborted opening is already authoritative, and this stage owns no
// provider resource. Its retained promise represents settlement only;
// a late stage rejection must not masquerade as failed resource cleanup.
const cleanup = pending.then(
() => undefined,
() => undefined,
);
retainRuntimeHostCleanup(cleanup);
retainCleanup?.(cleanup);
}
throw error;
}
}
async function acquireAbortableAdmissionResource<T>(input: {
signal: AbortSignal | undefined;
acquire: () => Promise<T>;
resource: AcpxRetainedCleanupFailure["resource"];
releaseLate: (resource: T) => Promise<void>;
onAbortedPending?: (pending: Promise<T>) => void;
reportFailure: (failure: AcpxRetainedCleanupFailure) => void;
}): Promise<T> {
if (input.signal === undefined) return await input.acquire();
input.signal.throwIfAborted();
const pending = Promise.resolve().then(input.acquire);
try {
return await raceAdmissionWithAbort(pending, input.signal);
} catch (error) {
if (input.signal.aborted) {
if (input.onAbortedPending) {
input.onAbortedPending(pending);
} else {
retainRuntimeHostCleanup(
pending.then((resource) =>
releaseRetainedAdmissionResource({
resource,
resourceKind: input.resource,
release: input.releaseLate,
reportFailure: input.reportFailure,
}),
),
);
}
}
throw error;
}
}
function raceAdmissionWithAbort<T>(
pending: Promise<T>,
signal: AbortSignal,
): Promise<T> {
return new Promise<T>((resolve, reject) => {
let settled = false;
const settle = (operation: () => void): void => {
if (settled) return;
settled = true;
signal.removeEventListener("abort", onAbort);
operation();
};
const onAbort = (): void => settle(() => reject(signal.reason));
signal.addEventListener("abort", onAbort, { once: true });
if (signal.aborted) {
onAbort();
return;
}
void pending.then(
(value) => settle(() => resolve(value)),
(error: unknown) => settle(() => reject(error)),
);
});
}
function retainAbortedRuntimeAdmissionCleanup(input: {
pendingRuntime: Promise<AcpxRuntimePort>;
credential: AcpxProviderLifetimeLease | null;
reason: string;
failedAdmissionCleanupTransfer: Promise<void>;
}): void {
const cleanup = input.pendingRuntime.then(
(runtime) =>
cleanupAbortedRuntimeAdmission(runtime, input.credential, input.reason),
() => input.failedAdmissionCleanupTransfer,
);
retainRuntimeHostCleanup(cleanup);
}
async function cleanupAbortedRuntimeAdmission(
runtime: AcpxRuntimePort | null,
credential: AcpxProviderLifetimeLease | null,
reason: string,
): Promise<void> {
const cleanupError = await cleanupRuntimeResources(
runtime,
null,
credential,
null,
reason,
);
if (!cleanupError) return;
retainFailedAcpxAdmissionCleanup({
runtime,
toolBridge: null,
credential,
command: null,
reason,
});
}
function retainFailedAcpxAdmissionCleanup(input: {
runtime: AcpxRuntimePort | null;
toolBridge: RunnerToolBridge | null;
credential: AcpxProviderLifetimeLease | null;
command: VerifiedAcpxCommandLease | null;
reason: string;
}): void {
const cleanup: RetainedAcpxAdmissionCleanup = {
...input,
recovery: null,
timer: null,
};
retainedAcpxAdmissionCleanups.add(cleanup);
startRetainedAcpxAdmissionCleanup(cleanup);
}
function startRetainedAcpxAdmissionCleanup(
cleanup: RetainedAcpxAdmissionCleanup,
): Promise<void> {
if (cleanup.recovery) return cleanup.recovery;
const recovery = (async () => {
let retryDelayMs = ACPX_ADMISSION_CLEANUP_RETRY_DELAY_MS;
for (
let attempt = 1;
attempt <= ACPX_ADMISSION_CLEANUP_BATCH_ATTEMPTS;
attempt += 1
) {
const cleanupError = await cleanupRuntimeResources(
cleanup.runtime,
cleanup.toolBridge,
cleanup.credential,
cleanup.command,
`${cleanup.reason} (automatic cleanup recovery ${attempt})`,
);
if (!cleanupError) {
retainedAcpxAdmissionCleanups.delete(cleanup);
if (cleanup.timer) clearTimeout(cleanup.timer);
cleanup.timer = null;
return;
}
if (attempt < ACPX_ADMISSION_CLEANUP_BATCH_ATTEMPTS) {
await waitForAdmissionCleanupRetry(retryDelayMs);
retryDelayMs = Math.min(retryDelayMs * 2, 1_000);
}
}
})();
cleanup.recovery = recovery;
void recovery
.finally(() => {
if (cleanup.recovery === recovery) cleanup.recovery = null;
scheduleRetainedAcpxAdmissionCleanup(cleanup);
})
.catch(() => undefined);
return recovery;
}
function scheduleRetainedAcpxAdmissionCleanup(
cleanup: RetainedAcpxAdmissionCleanup,
): void {
if (
!retainedAcpxAdmissionCleanups.has(cleanup) ||
cleanup.recovery ||
cleanup.timer
) {
return;
}
cleanup.timer = setTimeout(() => {
cleanup.timer = null;
if (!retainedAcpxAdmissionCleanups.has(cleanup)) return;
startRetainedAcpxAdmissionCleanup(cleanup);
}, ACPX_ADMISSION_CLEANUP_RESCHEDULE_MS);
cleanup.timer.unref?.();
}
async function waitForAdmissionCleanupRetry(delayMs: number): Promise<void> {
await new Promise<void>((resolve) => {
const timer = setTimeout(resolve, delayMs);
timer.unref?.();
});
}
async function releaseRetainedAdmissionResource<T>(input: {
resource: T;
resourceKind: AcpxRetainedCleanupFailure["resource"];
release: (resource: T) => Promise<void>;
reportFailure: (failure: AcpxRetainedCleanupFailure) => void;
}): Promise<void> {
let attempt = 0;
let retryDelayMs = RETAINED_CLEANUP_RETRY_INITIAL_DELAY_MS;
for (;;) {
attempt += 1;
try {
await input.release(input.resource);
return;
} catch (error) {
try {
input.reportFailure({
resource: input.resourceKind,
attempt,
error,
});
} catch {
// The required reporter is observational. A broken reporter must not
// relinquish ownership of the resource that still needs cleanup.
}
await waitForRetainedCleanupRetry(retryDelayMs);
retryDelayMs = Math.min(
retryDelayMs * 2,
RETAINED_CLEANUP_RETRY_MAX_DELAY_MS,
);
}
}
}
async function waitForRetainedCleanupRetry(delayMs: number): Promise<void> {
await new Promise<void>((resolve) => {
const timer = setTimeout(resolve, delayMs);
timer.unref?.();
});
}
function retainRuntimeHostCleanup(cleanup: Promise<unknown>): void {
activeRuntimeHostCleanupOwners.add(cleanup);
void cleanup.then(
() => activeRuntimeHostCleanupOwners.delete(cleanup),
() => activeRuntimeHostCleanupOwners.delete(cleanup),
);
}
async function awaitRuntimeHostCleanupWithin(
cleanup: Promise<AggregateError | null>,
timeoutMs: number,
): Promise<AggregateError | null | "deferred"> {
let timer: ReturnType<typeof setTimeout> | undefined;
try {
return await Promise.race([
cleanup,
new Promise<"deferred">((resolve) => {
timer = setTimeout(
() => resolve("deferred"),
Math.max(1, Math.floor(timeoutMs)),
);
timer.unref();
}),
]);
} finally {
if (timer) clearTimeout(timer);
}
}
async function boundedRuntimeAdmissionVerification(
runtime: AcpxRuntimePort,
profile: QualifiedAcpxProfile,
timeoutMs: number,
): Promise<AcpxRuntimePortIdentity> {
const verification = Promise.resolve().then(async () => {
await requireVerifiedAcpxModel(runtime, profile);
return await runtime.identity();
});
let timer: ReturnType<typeof setTimeout> | undefined;
try {
return await Promise.race([
verification,
new Promise<never>((_resolve, reject) => {
timer = setTimeout(
() => reject(new AcpxRuntimeAdmissionTimeoutError()),
timeoutMs,
);
timer.unref();
}),
]);
} finally {
if (timer) clearTimeout(timer);
}
}
async function boundedCancellation(
cancellation: Promise<void>,
): Promise<unknown | null> {
let timer: ReturnType<typeof setTimeout> | undefined;
const outcome = await Promise.race([
cancellation.then(
() => ({ error: null }),
(error: unknown) => ({ error }),
),
new Promise<{ error: unknown }>((resolve) => {
timer = setTimeout(
() =>
resolve({
error: new Error(
"ACPX turn cancellation exceeded its shutdown timeout",
),
}),
ACPX_TURN_CANCELLATION_SHUTDOWN_BOUND_MS,
);
timer.unref();
}),
]);
if (timer) clearTimeout(timer);
return outcome.error;
}
async function cleanupRuntimeResources(
runtime: AcpxRuntimePort | null,
toolBridge: RunnerToolBridge | null,
credential: AcpxProviderLifetimeLease | null,
command: VerifiedAcpxCommandLease | null,
reason: string,
): Promise<AggregateError | null> {
const settle = async (
close: () => Promise<void>,
): Promise<unknown | null> => {
try {
await close();
return null;
} catch (error) {
return error;
}
};
// The runtime must retire before its command snapshot can be removed.
// Keep both the snapshot and credential while the provider is still alive;
// failed cleanup remains owned and can be retried after process retirement.
const runtimeOutcome = runtime
? settle(() => runtime.close({ reason }))
: Promise.resolve(null);
const toolBridgeOutcome = (async (): Promise<unknown | null> => {
// Preserve the semantic-session cleanup order: the bridge is revoked once
// the runtime close attempt settles, even when that attempt fails.
await runtimeOutcome;
return toolBridge === null ? null : await settle(() => toolBridge.close());
})();
const commandOutcome = (async (): Promise<unknown | null> => {
await runtimeOutcome;
return command === null ? null : await settle(() => command.close());
})();
const credentialOutcome = (async (): Promise<unknown | null> => {
const runtimeError = await runtimeOutcome;
if (runtimeError !== null || credential === null) return null;
return await settle(() => credential.close());
})();
const outcomes = await Promise.all([
runtimeOutcome,
toolBridgeOutcome,
commandOutcome,
credentialOutcome,
]);
const errors = outcomes.filter((error): error is unknown => error !== null);
return errors.length > 0
? new AggregateError(errors, "ACPX runtime cleanup failed")
: null;
}
function boundedInstructions(value: string | undefined): string {
const instructions = value ?? "";
if (Buffer.byteLength(instructions) > 256 * 1024) {
throw acpxInstructionsAdmissionError("ACPX system instructions exceed their bounded size");
}
return instructions;
}
function boundedReason(value: string): string {
const reason = value.trim().slice(0, 1_000);
return reason || "ACPX runtime closed";
}
function boundedRequestId(value: string): string {
const requestId = value.trim();
if (
requestId.length === 0 ||
requestId !== value ||
Buffer.byteLength(requestId) > 1_024
) {
throw new Error("ACPX turn request id is outside its bounded size");
}
return requestId;
}
function boundedTurnText(value: string): string {
if (Buffer.byteLength(value) > 1024 * 1024) {
throw new Error("ACPX turn text exceeds its bounded size");
}
return value;
}