The open-source app everyone uses to manage agents at work
TypeScript acpxagent-orchestrationagent-skillsagentic-aiai-agentsai-engineeringai-governanceai-toolsautonomous-agentsclaudeclaude-codeclaude-skillscodexhermesllmmcpmulti-agentopenclawproject-managementworkflow-automation
feat(runner): bind semantic tools to ACPX sessions (#12404)
Dotta3623a369aa15
diff --git a/packages/paperclip-runner/src/drivers/acpx/codex-runtime-adapter.test.ts b/packages/paperclip-runner/src/drivers/acpx/codex-runtime-adapter.test.tsindex b3e2478eb0..4bea8aad78 100644--- a/packages/paperclip-runner/src/drivers/acpx/codex-runtime-adapter.test.ts+++ b/packages/paperclip-runner/src/drivers/acpx/codex-runtime-adapter.test.ts@@ -267,7 +267,11 @@ describe("Codex ACPX runtime adapter", () => {const signal = new AbortController().signal;expect(- port.startTurn({ text: "Complete the task.", requestId: "turn-1", signal }),+ port.startTurn({+ text: "Complete the task.",+ requestId: "turn-1",+ signal,+ }),).toBe(turn);expect(runtime.startTurn).toHaveBeenCalledWith({handle: HANDLE,@@ -278,6 +282,91 @@ describe("Codex ACPX runtime adapter", () => {});});+ it("projects only ephemeral MCP bindings and applies fail-closed permissions", async () => {+ const runtime = fakeRuntime();+ let runtimeOptions: AcpRuntimeOptions | undefined;+ const port = await openCodexAcpxRuntime(+ {+ ...openOptions(fakeCommand()),+ permissionMode: "deny-all",+ mcpServers: [+ {+ name: "paperclip",+ url: "http://127.0.0.1:3210/mcp",+ bearerToken: "bridge-secret",+ runnerOwned: true,+ },+ ],+ },+ {+ createRegistry: () => registry(),+ createStore: () => store(),+ createRuntime: (options) => {+ runtimeOptions = options;+ return runtime;+ },+ },+ );++ expect(runtimeOptions?.mcpServers).toEqual([+ {+ type: "http",+ name: "paperclip",+ url: "http://127.0.0.1:3210/mcp",+ headers: [{ name: "Authorization", value: "Bearer bridge-secret" }],+ },+ ]);+ await expect(+ runtimeOptions?.onPermissionRequest?.(+ {+ sessionId: "session-1",+ inferredKind: "execute",+ raw: { _meta: { is_mcp_tool_approval: true } },+ },+ { signal: new AbortController().signal },+ ),+ ).resolves.toEqual({ outcome: "reject_once" });+ await expect(+ runtimeOptions?.onPermissionRequest?.(+ {+ sessionId: "session-1",+ inferredKind: "execute",+ raw: {},+ },+ { signal: new AbortController().signal },+ ),+ ).resolves.toEqual({ outcome: "reject_once" });+ expect(+ JSON.stringify(vi.mocked(runtime.ensureSession).mock.calls),+ ).not.toContain("bridge-secret");+ await port.close({ reason: "complete" });+ });++ it("delegates permissions that require an unavailable coordinator", async () => {+ const runtime = fakeRuntime();+ let runtimeOptions: AcpRuntimeOptions | undefined;+ const port = await openCodexAcpxRuntime(openOptions(fakeCommand()), {+ createRegistry: () => registry(),+ createStore: () => store(),+ createRuntime: (options) => {+ runtimeOptions = options;+ return runtime;+ },+ });++ await expect(+ runtimeOptions?.onPermissionRequest?.(+ {+ sessionId: "session-1",+ inferredKind: "write",+ raw: {},+ },+ { signal: new AbortController().signal },+ ),+ ).resolves.toBeUndefined();+ await port.close({ reason: "complete" });+ });+it("fails closed and closes the session when ACPX omits recovery identity", async () => {const runtime = fakeRuntime({ ...HANDLE, agentSessionId: undefined });await expect(@@ -1177,6 +1266,7 @@ function openOptions(OMITTED: undefined,},systemInstructions: "Use Paperclip tools.",+ mcpServers: [],};}diff --git a/packages/paperclip-runner/src/drivers/acpx/codex-runtime-adapter.ts b/packages/paperclip-runner/src/drivers/acpx/codex-runtime-adapter.tsindex e8737a4ec4..01a15540a8 100644--- a/packages/paperclip-runner/src/drivers/acpx/codex-runtime-adapter.ts+++ b/packages/paperclip-runner/src/drivers/acpx/codex-runtime-adapter.ts@@ -18,6 +18,7 @@ import type {AcpxRuntimePortIdentity,AcpxRuntimePortOpenOptions,} from "./runtime-host.js";+import { decideAcpxPermission } from "./permission-policy.js";const VERIFIED_COMMAND_SENTINEL = "paperclip-verified-acpx-command";const DEFAULT_RUNTIME_CLOSE_TIMEOUT_MS = 2_000;@@ -142,6 +143,11 @@ export async function openCodexAcpxRuntime(await baseStore.save(record);},};+ const runnerOwnedMcpServerNames = new Set(+ options.mcpServers+ .filter((server) => server.runnerOwned)+ .map((server) => server.name),+ );const runtime = createRuntime({cwd: options.cwd,sessionStore,@@ -159,6 +165,28 @@ export async function openCodexAcpxRuntime(? [...options.permissionPolicy.escalate]: undefined,},+ mcpServers: options.mcpServers.map((server) => ({+ type: "http" as const,+ name: server.name,+ url: server.url,+ headers: [+ { name: "Authorization", value: `Bearer ${server.bearerToken}` },+ ],+ })),+ onPermissionRequest: async (request) => {+ const disposition = decideAcpxPermission(+ options.profile.agent,+ options.permissionMode,+ request,+ {+ runnerOwnedMcpServerNames,+ allConfiguredMcpServersAreRunnerOwned:+ options.mcpServers.length > 0 &&+ options.mcpServers.every((server) => server.runnerOwned),+ },+ );+ return disposition === "delegate" ? undefined : { outcome: disposition };+ },spawnEnvironment: () => definedEnvironment(options.launchEnvironment),spawnCwd: options.cwd,spawnAgent: (input) => {diff --git a/packages/paperclip-runner/src/drivers/acpx/runtime-host.test.ts b/packages/paperclip-runner/src/drivers/acpx/runtime-host.test.tsindex b837f5fac7..5a35c44fa5 100644--- a/packages/paperclip-runner/src/drivers/acpx/runtime-host.test.ts+++ b/packages/paperclip-runner/src/drivers/acpx/runtime-host.test.ts@@ -111,6 +111,78 @@ describe("ACPX runtime host", () => {expect(fixture.commandClose).toHaveBeenCalledOnce();});+ it("owns an authenticated semantic bridge without persisting its secret", async () => {+ const fixture = await hostFixture();+ const handler = vi.fn(async ({ tool }) => ({ tool, ok: true }));+ let bridge:+ | { url: string; bearerToken: string; name: string; runnerOwned: boolean }+ | undefined;+ const host = await AcpxRuntimeHost.open(+ {+ ...fixture.options,+ agent: "codex",+ model: "gpt-5.6-sol",+ permissionMode: "deny-all",+ environment: { PAPERCLIP_ACPX_CODEX_AUTH_JSON_SECRET: "{}" },+ semanticTools: {+ tools: [+ {+ name: "documents.read",+ description: "Read one document.",+ inputSchema: {+ type: "object",+ properties: { id: { type: "string" } },+ required: ["id"],+ additionalProperties: false,+ },+ },+ ],+ handler,+ },+ },+ fixture.dependencies({+ openRuntime: async (options) => {+ bridge = options.mcpServers[0];+ return runtimePort();+ },+ }),+ );++ expect(bridge).toMatchObject({+ name: "paperclip",+ runnerOwned: true,+ });+ expect(new URL(bridge!.url).hostname).toBe("127.0.0.1");+ const response = await fetch(bridge!.url, {+ method: "POST",+ headers: {+ Authorization: `Bearer ${bridge!.bearerToken}`,+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ jsonrpc: "2.0",+ id: "call-1",+ method: "tools/call",+ params: { name: "documents.read", arguments: { id: "doc-1" } },+ }),+ });+ expect(await response.json()).toMatchObject({+ result: { content: [{ text: '{"tool":"documents.read","ok":true}' }] },+ });+ expect(handler).toHaveBeenCalledOnce();+ expect(JSON.stringify(host.persistedEnvironment())).not.toContain(+ bridge!.bearerToken,+ );++ await host.close({ reason: "complete" });+ await expect(+ fetch(bridge!.url, {+ method: "POST",+ headers: { Authorization: `Bearer ${bridge!.bearerToken}` },+ }),+ ).rejects.toThrow();+ });+it("selects and verifies Claude's qualified reported model", async () => {const fixture = await hostFixture();let selected = false;diff --git a/packages/paperclip-runner/src/drivers/acpx/runtime-host.ts b/packages/paperclip-runner/src/drivers/acpx/runtime-host.tsindex 9c8a2fa353..86c200744c 100644--- a/packages/paperclip-runner/src/drivers/acpx/runtime-host.ts+++ b/packages/paperclip-runner/src/drivers/acpx/runtime-host.ts@@ -1,6 +1,11 @@import type { AcpRuntimeEvent, AcpRuntimeTurnResult } from "acpx/runtime";import type { NativeAcpxPermissionMode } from "../../contracts/native-execution.js";+import {+ startRunnerToolBridge,+ type RunnerToolBridge,+ type RunnerToolBridgeOptions,+} from "../runner-tool-bridge.js";import {stageManagedCodexCredential,type ManagedCodexCredentialLease,@@ -77,14 +82,24 @@ export interface AcpxRuntimePortOpenOptions {systemInstructions: string;/** Abort provider admission and clean any runtime that resolves too late. */signal?: AbortSignal;+ mcpServers: readonly AcpxMcpServerBinding[];}export interface AcpxRetainedCleanupFailure {- resource: "credential" | "command" | "runtime";+ resource: "credential" | "command" | "runtime" | "tool_bridge";attempt: number;error: unknown;}+export interface AcpxMcpServerBinding {+ name: string;+ url: string;+ bearerToken: string;+ runnerOwned: boolean;+}++export type AcpxSemanticToolSession = Omit<RunnerToolBridgeOptions, "secret">;+export interface AcpxRuntimeHostDependencies {verifyInstallation?: (profile: QualifiedAcpxProfile,@@ -112,6 +127,7 @@ export interface OpenAcpxRuntimeHostOptions {expectedIdentity?: AcpxExpectedSessionIdentity;/** Abort admission without admitting resources that resolve afterward. */signal?: AbortSignal;+ semanticTools?: AcpxSemanticToolSession;}const activeRuntimeHostCleanupOwners = new Set<Promise<unknown>>();@@ -125,6 +141,7 @@ export class AcpxRuntimeHost {readonly #sandbox: AcpxRuntimeSandbox;readonly #credential: ManagedCodexCredentialLease | null;readonly #command: VerifiedAcpxCommandLease;+ readonly #toolBridge: RunnerToolBridge | null;#activeTurn: AcpxRuntimeTurn | null = null;#closingStarted = false;#closePromise: Promise<void> | null = null;@@ -137,6 +154,7 @@ export class AcpxRuntimeHost {sandbox: AcpxRuntimeSandbox;credential: ManagedCodexCredentialLease | null;command: VerifiedAcpxCommandLease;+ toolBridge: RunnerToolBridge | null;}) {this.#runtime = input.runtime;this.#binding = input.binding;@@ -144,6 +162,7 @@ export class AcpxRuntimeHost {this.#sandbox = input.sandbox;this.#credential = input.credential;this.#command = input.command;+ this.#toolBridge = input.toolBridge;}static async open(@@ -184,6 +203,7 @@ export class AcpxRuntimeHost {}let command: VerifiedAcpxCommandLease | null = null;let credential: ManagedCodexCredentialLease | null = null;+ let toolBridge: RunnerToolBridge | null = null;let runtime: AcpxRuntimePort | null = null;try {const sandbox = await runAbortableAdmissionStage(options.signal, () =>@@ -216,6 +236,16 @@ export class AcpxRuntimeHost {reportFailure: (failure) =>dependencies.reportRetainedCleanupFailure(failure),});+ toolBridge = options.semanticTools+ ? await acquireAbortableAdmissionResource({+ signal: options.signal,+ acquire: () => startRunnerToolBridge(options.semanticTools!),+ resource: "tool_bridge",+ releaseLate: (lateToolBridge) => lateToolBridge.close(),+ reportFailure: (failure) =>+ dependencies.reportRetainedCleanupFailure(failure),+ })+ : null;runtime = await acquireAbortableAdmissionResource({signal: options.signal,acquire: () =>@@ -232,6 +262,16 @@ export class AcpxRuntimeHost {launchEnvironment: sandbox.launchEnvironment,systemInstructions: boundedInstructions(options.systemInstructions),...(options.signal === undefined ? {} : { signal: options.signal }),+ mcpServers: toolBridge+ ? [+ {+ name: "paperclip",+ url: toolBridge.url,+ bearerToken: toolBridge.secret,+ runnerOwned: true,+ },+ ]+ : [],}),resource: "runtime",releaseLate: (lateRuntime) =>@@ -270,10 +310,12 @@ export class AcpxRuntimeHost {sandbox,credential,command,+ toolBridge,});} catch (error) {const cleanupError = await cleanupRuntimeResources(runtime,+ toolBridge,credential,command,"ACPX runtime initialization failed",@@ -361,6 +403,7 @@ export class AcpxRuntimeHost {}const cleanupError = await cleanupRuntimeResources(this.#runtime,+ this.#toolBridge,this.#credential,this.#command,reason,@@ -514,6 +557,7 @@ async function boundedCancellation(async function cleanupRuntimeResources(runtime: AcpxRuntimePort | null,+ toolBridge: RunnerToolBridge | null,credential: ManagedCodexCredentialLease | null,command: VerifiedAcpxCommandLease | null,reason: string,@@ -536,6 +580,12 @@ async function cleanupRuntimeResources(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 = command? settle(() => command.close()): Promise.resolve(null);@@ -546,6 +596,7 @@ async function cleanupRuntimeResources(})();const outcomes = await Promise.all([runtimeOutcome,+ toolBridgeOutcome,commandOutcome,credentialOutcome,]);