diff --git a/packages/paperclip-runner/src/backends/runtime-context.test.ts b/packages/paperclip-runner/src/backends/runtime-context.test.ts index bfa1fa76be0..6e5fa9f1208 100644 --- a/packages/paperclip-runner/src/backends/runtime-context.test.ts +++ b/packages/paperclip-runner/src/backends/runtime-context.test.ts @@ -19,10 +19,12 @@ import { type NativeExecutionInput, } from "../contracts/native-execution.js"; import { + nativeRunAttachReservedBytes, nativeSystemInstructions, nativeTaskSkillInputs, nativeTaskConstraints, } from "./runtime-context.js"; +import { authorizedToolSetForProvider, runnerCodexDynamicToolsFit } from "../live/runnerd-codex-transport.js"; const temporaryRoots: string[] = []; @@ -420,3 +422,58 @@ describe("explicit task skill selection", () => { expect(nativeTaskSkillInputs("/first-task", null)).toEqual([]); }); }); + +describe("run attachment reserve", () => { + const roots: string[] = []; + afterEach(() => { + for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); + }); + + function reserveInput(instructions: string | null) { + const root = mkdtempSync(join(tmpdir(), "paperclip-run-attach-reserve-")); + roots.push(root); + if (instructions !== null) writeFileSync(join(root, "AGENTS.md"), instructions); + const criteria = Array.from({ length: 300 }, (_, index) => ({ id: `criterion-${index}-identifier`, requirement: "Done" })); + return { + provider: { kind: "codex" }, + completionContract: { contract: { revision: 1, criteria } }, + runtimeContext: { + prompt: { text: "Paperclip runtime." }, + instructions: { bundle: { rootPath: root }, entryPath: "AGENTS.md" }, + skills: Array.from({ length: 150 }, (_, index) => ({ runtimeName: `skill-${index}`, description: "Skill summary" })), + }, + } as unknown as NativeExecutionInput; + } + + it("keeps the whole run attachment within the command budget for any catalog it admits", () => { + const input = reserveInput("Agent instructions. ".repeat(8_000)); + const reserved = nativeRunAttachReservedBytes(input); + const instructions = nativeSystemInstructions(input); + const criterionIds = (input as { completionContract: { contract: { criteria: Array<{ id: string }> } } }) + .completionContract.contract.criteria.map(criterion => criterion.id); + expect(reserved).toBeGreaterThanOrEqual(Buffer.byteLength(JSON.stringify(instructions)) + Buffer.byteLength(JSON.stringify(criterionIds))); + const catalog = (count: number) => Array.from({ length: count }, (_, index) => ({ + name: `tool_${index}`, description: "Tool", inputSchema: { type: "object", properties: { value: { type: "string", enum: ["a", "b", "c", "d"] } } }, + })); + let count = 1; + while (count < 256 && runnerCodexDynamicToolsFit(catalog(count + 1), reserved)) count += 1; + const command = { + observeCredentials: true, + authorizedTools: authorizedToolSetForProvider("acpx", catalog(count)), + completionContract: { revision: 1, criterionIds }, + provider: { provider: "acpx", command: "provider", instructions, runtimeContext: (input as { runtimeContext: unknown }).runtimeContext }, + paperclipNextAuthority: { identity: { runId: "run", turnId: "turn", itemId: "item" }, connection: { mode: "connect", connectUrl: "ws://127.0.0.1:1" } }, + }; + expect(Buffer.byteLength(JSON.stringify(command))).toBeLessThanOrEqual(Math.floor((1024 * 1024 - 4 * 1024) / 2)); + }); + + it("reserves what it can measure when the instructions cannot be read", () => { + const input = reserveInput(null); + expect(() => nativeSystemInstructions(input)).toThrow(); + expect(nativeRunAttachReservedBytes(input)) + .toBe(Buffer.byteLength(JSON.stringify((input as { runtimeContext: unknown }).runtimeContext)) + + Buffer.byteLength(JSON.stringify((input as { completionContract: { contract: { criteria: Array<{ id: string }> } } }) + .completionContract.contract.criteria.map(criterion => criterion.id)))); + }); +}); + diff --git a/packages/paperclip-runner/src/backends/runtime-context.ts b/packages/paperclip-runner/src/backends/runtime-context.ts index 9518a8b3b16..6b63885431b 100644 --- a/packages/paperclip-runner/src/backends/runtime-context.ts +++ b/packages/paperclip-runner/src/backends/runtime-context.ts @@ -9,6 +9,17 @@ import { composeNativeSystemInstructions, } from "../contracts/runtime-context.js"; +export function nativeRunAttachReservedBytes(input: NativeExecutionInput): number { + const criterionIds = input.completionContract.contract.criteria.map((criterion) => criterion.id); + const runtimeContextBytes = Buffer.byteLength(JSON.stringify("runtimeContext" in input ? input.runtimeContext : null), "utf8") + + Buffer.byteLength(JSON.stringify(criterionIds), "utf8"); + try { + return runtimeContextBytes + Buffer.byteLength(JSON.stringify(nativeSystemInstructions(input)), "utf8"); + } catch { + return runtimeContextBytes; + } +} + export function nativeSystemInstructions(input: NativeExecutionInput): string { if (!("runtimeContext" in input)) return CODEX_SKILLLESS_BASE_INSTRUCTIONS; const configuredRoot = resolve( diff --git a/packages/paperclip-runner/src/control-plane/durable-prp-control-plane.test.ts b/packages/paperclip-runner/src/control-plane/durable-prp-control-plane.test.ts index c44db971979..c7f55071ee6 100644 --- a/packages/paperclip-runner/src/control-plane/durable-prp-control-plane.test.ts +++ b/packages/paperclip-runner/src/control-plane/durable-prp-control-plane.test.ts @@ -24,7 +24,7 @@ import { describe, expect, it, vi } from "vitest"; import { configuredEnvironmentProjection } from "../configured-environment.js"; import { NativeSessionProtocolIntegrityError } from "../contracts/native-session-backend.js"; -import { createCapabilityRunnerdCodexTransport, createCapabilityRunnerdProviderEnvironment, waitForRunnerCommand } from "../live/runnerd-codex-transport.js"; +import { authorizedToolSetForProvider, createCapabilityRunnerdCodexTransport, createCapabilityRunnerdProviderEnvironment, runnerCodexDynamicToolsFit, waitForRunnerCommand } from "../live/runnerd-codex-transport.js"; import { providerTurnStartBefore } from "../live/provider-turn-tool-order.js"; import { ACPX_CREDENTIAL_BINDING_ENV, createAcpxSidecarHostEnvironment } from "../drivers/acpx/environment.js"; import { validatePrpEvent } from "../protocol/replay-contract.js"; @@ -44,6 +44,7 @@ import { type DurablePrpControlPlaneStore, type RunnerProcessHandle, durableRecoveryInternals, + runAttachToolCatalogFits, SemanticToolNotDispatchedError, inspectWarmRunTransition, spawnRunner, @@ -405,6 +406,101 @@ it("persists an undispatched source-to-target attachment before bootstrap and pr } }); +function denseToolCatalog(toolCount: number, valuesPerTool: number): Record[] { + return Array.from({ length: toolCount }, (_, tool) => ({ + name: `connector_tool_${tool}`, + description: "Dense connector tool", + inputSchema: { + type: "object", + properties: Object.fromEntries(Array.from({ length: valuesPerTool / 10 }, (_, property) => [ + `p${property}`, { type: "string", enum: Array.from({ length: 10 }, (_, value) => String(value)) }, + ])), + }, + })); +} + +it("stages and restores a run attachment for every tool catalog the provider protocol admits", async () => { + let valuesPerTool = 10; + while (runnerCodexDynamicToolsFit(denseToolCatalog(250, valuesPerTool + 10))) valuesPerTool += 10; + const tools = denseToolCatalog(250, valuesPerTool); + expect(runnerCodexDynamicToolsFit(tools)).toBe(true); + const connectorCatalog = denseToolCatalog(180, 400); + expect(Buffer.byteLength(JSON.stringify(connectorCatalog))).toBeLessThan(768 * 1024); + expect(runnerCodexDynamicToolsFit(connectorCatalog)).toBe(false); + const root = mkdtempSync(resolve(tmpdir(), "runner-large-catalog-")); + const target = { ...identity, runId: "00000000-0000-4000-8000-000000000003", turnId: "catalog-turn", itemId: "catalog-item" }; + const template = { provider: { provider: "acpx", command: "fixture", instructions: "assigned" }, authorizedTools: authorizedToolSetForProvider("acpx", tools) }; + const core = new DurablePrpControlPlane({ stateDirectory: resolve(root, "first"), identity, expectedRunnerVersion, expectedRunnerDigest }); + let checkpoint!: DurablePrpCheckpoint; + core.setCheckpointPersistence(async value => { checkpoint = value; }); + try { + core.stageRunAttachment(target, template); + await core.flushCheckpoint(); + expect(() => decodeDurablePrpCheckpoint(checkpoint.records)).not.toThrow(); + checkpoint.restoreSessionDirectory(resolve(root, "replacement")); + const restored = new DurablePrpControlPlane({ stateDirectory: resolve(root, "replacement", "control-plane"), identity, expectedRunnerVersion, expectedRunnerDigest }); + try { + expect(inspectStagedRunAttachment(restored.store.state, target)).toMatchObject({ runAttachTemplate: template }); + } finally { + await restored.stop(); + } + } finally { + await core.stop(); rmSync(root, { recursive: true, force: true }); + } +}); + +it("refuses rather than throws for a tool schema nested past the canonical depth", () => { + let schema: Record = { type: "string" }; + for (let depth = 0; depth < 70; depth += 1) schema = { type: "object", properties: { child: schema } }; + expect(runnerCodexDynamicToolsFit([{ name: "deep_tool", description: "Deep", inputSchema: schema }])).toBe(false); +}); + +it("admits a tool catalog exactly up to the run attachment command budget", () => { + const catalog = authorizedToolSetForProvider("acpx", denseToolCatalog(40, 100)); + const catalogBytes = Buffer.byteLength(durableRecoveryInternals.controllerJson(catalog)); + const commandBudget = Math.floor((1024 * 1024 - 4 * 1024) / 2); + const reserveAtLimit = commandBudget - 32 * 1024 - catalogBytes; + expect(runAttachToolCatalogFits(catalog, reserveAtLimit)).toBe(true); + expect(runAttachToolCatalogFits(catalog, reserveAtLimit + 1)).toBe(false); +}); + +it("leaves room in the run attachment for the instructions it reserves", async () => { + const instructions = "Large agent instructions. ".repeat(6_000); + const runtimeContext = { skills: Array.from({ length: 200 }, (_, index) => ({ runtimeName: `skill-${index}`, description: "Skill summary ".repeat(6) })) }; + const criterionIds = Array.from({ length: 400 }, (_, index) => `criterion-${index}-with-a-longer-identifier`); + const reserved = Buffer.byteLength(JSON.stringify(instructions)) + Buffer.byteLength(JSON.stringify(runtimeContext)) + + Buffer.byteLength(JSON.stringify(criterionIds)); + let valuesPerTool = 10; + while (runnerCodexDynamicToolsFit(denseToolCatalog(100, valuesPerTool + 10))) valuesPerTool += 10; + const unreserved = denseToolCatalog(100, valuesPerTool); + expect(runnerCodexDynamicToolsFit(unreserved, reserved)).toBe(false); + let fitting = 10; + while (runnerCodexDynamicToolsFit(denseToolCatalog(100, fitting + 10), reserved)) fitting += 10; + const tools = denseToolCatalog(100, fitting); + const root = mkdtempSync(resolve(tmpdir(), "runner-reserved-catalog-")); + const target = { ...identity, runId: "00000000-0000-4000-8000-000000000004", turnId: "reserved-turn", itemId: "reserved-item" }; + const template = { observeCredentials: true, authorizedTools: authorizedToolSetForProvider("acpx", tools), + completionContract: { revision: 1, criterionIds }, + provider: { provider: "acpx", command: "fixture", instructions, runtimeContext } }; + const core = new DurablePrpControlPlane({ stateDirectory: resolve(root, "first"), identity, expectedRunnerVersion, expectedRunnerDigest }); + let checkpoint!: DurablePrpCheckpoint; + core.setCheckpointPersistence(async value => { checkpoint = value; }); + let client: AuthenticatedClient | null = null; + try { + expect(() => core.stageRunAttachment(target, template)).not.toThrow(); + await core.flushCheckpoint(); + await core.start(); client = await authenticate(core, core.issueBootstrapTicket()); + expect(client).not.toBeNull(); + expect(() => core.queueCommand("run.attach", { ...template, paperclipNextAuthority: { identity: target, + connection: { mode: "connect", connectUrl: core.connectUrl } } }, "reserved-next-attach")).not.toThrow(); + await core.flushCheckpoint(); + expect(() => decodeDurablePrpCheckpoint(checkpoint.records)).not.toThrow(); + } finally { + client?.socket.destroy(); + await core.stop(); rmSync(root, { recursive: true, force: true }); + } +}); + it("continues externally persisted commands after losing the local controller directory", async () => { const root = mkdtempSync(resolve(tmpdir(), "runner-external-store-")); const options = { stateDirectory: resolve(root, "control-plane"), identity, expectedRunnerVersion, expectedRunnerDigest }; @@ -5205,10 +5301,12 @@ describe("DurablePrpControlPlane", () => { core.persistPreparedLaunchConfiguration(identity, "prior-configuration"); core.persistPreparedLaunchConfiguration(nextIdentity, "next-configuration"); if (usesExternalPersistence) rmSync(resolve(root, "control-plane"), { recursive: true }); + const transitionCatalog = authorizedToolSetForProvider("acpx", denseToolCatalog(100, 200)); const command = core.queueCommand( "run.attach", { provider: { kind: "mock", run: "next" }, + authorizedTools: transitionCatalog, paperclipNextAuthority: { identity: nextIdentity, connection: { mode: "connect", connectUrl: core.connectUrl }, @@ -5558,7 +5656,7 @@ describe("DurablePrpControlPlane", () => { core.persistPreparedLaunchConfiguration({ ...nextIdentity, runId: "third-run" }, "third-configuration"); expect(core.preparedLaunchConfigurationId(identity)).toBeUndefined(); expect(core.store.state.preparedLaunchConfigurations).toHaveLength(2); - expect(core.store.state.runAttachTemplate).toEqual({ provider: { kind: "mock", run: "next" } }); + expect(core.store.state.runAttachTemplate).toEqual({ provider: { kind: "mock", run: "next" }, authorizedTools: transitionCatalog }); expect( (successor!.welcome.payload as Record) .pendingCommands, diff --git a/packages/paperclip-runner/src/control-plane/durable-prp-control-plane.ts b/packages/paperclip-runner/src/control-plane/durable-prp-control-plane.ts index e621888be18..772f1410a99 100644 --- a/packages/paperclip-runner/src/control-plane/durable-prp-control-plane.ts +++ b/packages/paperclip-runner/src/control-plane/durable-prp-control-plane.ts @@ -65,6 +65,7 @@ const transitionCoreStateSchema = const maxFrameBytes = 1024 * 1024; // Secure frames hex-encode ciphertext. Reserve envelope/tag space as well. const maxCommandBytes = Math.floor((maxFrameBytes - 4 * 1024) / 2); +const RUN_ATTACH_ENVELOPE_BYTES = 32 * 1024; const maxCommands = 500; const maxCommandsAtAttach = 32; const maxEventsPerAck = 64; @@ -658,7 +659,7 @@ function isUnclaimedBootstrapState(state: StoredCoreState, expected: DurableReco || state.commands.length !== 2 || state.commands[0]?.type !== "run.prepare" || state.commands[1]?.type !== "session.open" || state.commands.some(command => command.status !== "pending" || command.result !== null) - || !state.runAttachTemplate || canonicalJson(state.commands[0].payload) !== canonicalJson(state.runAttachTemplate)); + || !state.runAttachTemplate || controllerJson(state.commands[0].payload) !== controllerJson(state.runAttachTemplate)); } export function inspectUnclaimedBootstrapCheckpoint( @@ -796,18 +797,19 @@ function credentialMaterial(token: string): { } const MAX_CANONICAL_JSON_DEPTH = 64; -const MAX_CANONICAL_JSON_NODES = 10_000; +const MAX_RUNNER_INPUT_JSON_NODES = 10_000; +const MAX_CONTROLLER_JSON_NODES = maxCommandBytes; function canonicalJson( value: unknown, ancestors = new WeakSet(), - state = { nodes: 0 }, + state = { nodes: 0, maxNodes: MAX_RUNNER_INPUT_JSON_NODES }, depth = 0, ): string { state.nodes += 1; if ( depth > MAX_CANONICAL_JSON_DEPTH || - state.nodes > MAX_CANONICAL_JSON_NODES + state.nodes > state.maxNodes ) { throw new Error("durable_prp_canonical_json_too_large"); } @@ -861,6 +863,7 @@ function canonicalJson( export const durableRecoveryInternals = Object.freeze({ canonicalJson, + controllerJson: (value: unknown) => controllerJson(value), captureCheckpoint: (state: DurablePrpControlPlaneStore["state"], runnerVersion: string, runnerDigest: string, cache?: CheckpointRecordCache) => captureCheckpoint(state, runnerVersion, runnerDigest, cache), createCheckpointRecordCache: () => new CheckpointRecordCache(), @@ -870,6 +873,23 @@ function canonicalDigest(value: unknown): string { return createHash("sha256").update(canonicalJson(value)).digest("hex"); } +function controllerJson(value: unknown): string { + return canonicalJson(value, new WeakSet(), { nodes: 0, maxNodes: MAX_CONTROLLER_JSON_NODES }); +} + +function controllerDigest(value: unknown): string { + return createHash("sha256").update(controllerJson(value)).digest("hex"); +} + +export function runAttachToolCatalogFits(authorizedTools: Record, reservedBytes = 0): boolean { + try { + return Buffer.byteLength(controllerJson(authorizedTools), "utf8") + RUN_ATTACH_ENVELOPE_BYTES + Math.max(0, reservedBytes) + <= maxCommandBytes; + } catch { + return false; + } +} + function matchesSemanticInputDigest(input: unknown, digest: unknown): boolean { try { // Wire integrity covers the complete input, including protected fields. @@ -940,7 +960,7 @@ function warmTransitionReceipt( commandId: command.commandId, controllerSeq: command.controllerSeq, // Rust's closed Command representation serializes these optional fields. - commandFingerprint: canonicalDigest({ + commandFingerprint: controllerDigest({ ...wire, deadlineAt: null, precondition: null, @@ -999,11 +1019,11 @@ function validStoredWarmTransition(state: StoredCoreState): boolean { ) && (transition.phase === "activated" || (state.ackedSourceSeq === expected.oldAckedSourceSeq && - canonicalJson( + controllerJson( state.commands.find( (command) => command.commandId === expected.commandId, ), - ) === canonicalJson(transition.command))) + ) === controllerJson(transition.command))) ); } catch { return false; @@ -1088,8 +1108,8 @@ function stagedCommandMatches(staged: Pick | null { @@ -1125,7 +1145,7 @@ function validStagedRunAttachment(state: StoredCoreState, headerOnly = false): b && /^sha256:[0-9a-f]{64}$/.test(staged.templateDigest) && (headerOnly || staged.commandId !== null || (isRecord(staged.runAttachTemplate) && isRecord(staged.runAttachTemplate.provider) && staged.runAttachTemplate.paperclipNextAuthority === undefined - && `sha256:${canonicalDigest(staged.runAttachTemplate)}` === staged.templateDigest + && `sha256:${controllerDigest(staged.runAttachTemplate)}` === staged.templateDigest && Buffer.byteLength(JSON.stringify(staged.runAttachTemplate)) <= maxCommandBytes)) && (staged.commandId === null || (typeof staged.commandId === "string" && stableIdPattern.test(staged.commandId))))) return false; const sourceCurrent = canonicalJson(state.identity) === canonicalJson(staged.sourceIdentity); @@ -1481,8 +1501,8 @@ function warmTransitionRecoveryProof(input: WarmTransitionInspectionInput): { !Object.entries(requested).every( ([key, value]) => runner[key] === value, ) || - canonicalJson(pending.command) !== - canonicalJson({ ...wire, deadlineAt: null, precondition: null }) || + controllerJson(pending.command) !== + controllerJson({ ...wire, deadlineAt: null, precondition: null }) || canonicalJson(pending.result) !== canonicalJson(transition.expectedResult ?? transition.command.result) || runner.ackedSourceSeq !== @@ -2699,7 +2719,7 @@ export class DurablePrpControlPlane { completed.command.payload; if ( runAttachTemplate !== undefined && - canonicalJson(runAttachTemplate) !== canonicalJson(template) + controllerJson(runAttachTemplate) !== controllerJson(template) ) { throw new Error( "Completed warm transition template conflicts with its exact command.", @@ -2725,7 +2745,7 @@ export class DurablePrpControlPlane { const { paperclipNextAuthority: _boundary, ...expectedTemplate } = transition.command.payload; if ( - canonicalJson(runAttachTemplate) !== canonicalJson(expectedTemplate) + controllerJson(runAttachTemplate) !== controllerJson(expectedTemplate) ) { throw new Error( "Warm run transition template conflicts with its exact command.", @@ -2822,7 +2842,7 @@ export class DurablePrpControlPlane { if ( existing !== undefined && existing !== null && - canonicalJson(existing) !== canonicalJson(runAttachTemplate) + controllerJson(existing) !== controllerJson(runAttachTemplate) ) { throw new Error("Durable PRP run attachment template conflicts."); } @@ -2932,7 +2952,7 @@ export class DurablePrpControlPlane { if (!proof || proof.transition.receipt.transitionId !== input.transitionId || !this.#store.state.stagedRunAttachment) { throw new Error("Warm transition adoption snapshot proof is not authorized."); } - if (this.#store.state.warmTransition && canonicalJson(this.#store.state.warmTransition) === canonicalJson(proof.transition)) return; + if (this.#store.state.warmTransition && controllerJson(this.#store.state.warmTransition) === controllerJson(proof.transition)) return; const candidate = structuredClone(this.#store.state); candidate.schema = stagedCoreStateSchema; candidate.warmTransition = structuredClone(proof.transition); @@ -3016,7 +3036,7 @@ export class DurablePrpControlPlane { && targetIdentity.runId !== existing.targetIdentity.runId)) { if (!validStagedRunAttachment(this.#store.state) || canonicalJson(existing.targetIdentity) !== canonicalJson(targetIdentity) - || canonicalJson(stagedAttachmentTemplate(this.#store.state)) !== canonicalJson(runAttachTemplate)) { + || controllerJson(stagedAttachmentTemplate(this.#store.state)) !== controllerJson(runAttachTemplate)) { throw new Error("Staged run attachment conflicts with its durable intent."); } return; @@ -3025,7 +3045,7 @@ export class DurablePrpControlPlane { candidate.schema = stagedCoreStateSchema; candidate.stagedRunAttachment = { sourceIdentity: structuredClone(candidate.identity), targetIdentity: structuredClone(targetIdentity), runAttachTemplate: structuredClone(runAttachTemplate), - templateDigest: `sha256:${canonicalDigest(runAttachTemplate)}`, commandId: null }; + templateDigest: `sha256:${controllerDigest(runAttachTemplate)}`, commandId: null }; if (!validStagedRunAttachment(candidate)) throw new Error("Staged run attachment binding is invalid."); this.#store.commit(candidate); } @@ -3045,7 +3065,7 @@ export class DurablePrpControlPlane { && !(type === "run.attach" && isRecord(payload.paperclipNextAuthority) && isRecord(payload.paperclipNextAuthority.identity) && payload.paperclipNextAuthority.identity.runId === authorityRunId) - && !(prior && prior.status !== "pending" && prior.type === type && canonicalJson(prior.payload) === canonicalJson(payload))) { + && !(prior && prior.status !== "pending" && prior.type === type && controllerJson(prior.payload) === controllerJson(payload))) { throw new Error("native_runner_source_attachment_pending"); } const staged = this.#store.state.stagedRunAttachment; @@ -3057,7 +3077,7 @@ export class DurablePrpControlPlane { const { paperclipNextAuthority, ...template } = payload; if (!isRecord(paperclipNextAuthority) || canonicalJson(paperclipNextAuthority.identity) !== canonicalJson(staged.targetIdentity) - || `sha256:${canonicalDigest(template)}` !== staged.templateDigest + || `sha256:${controllerDigest(template)}` !== staged.templateDigest || (staged.commandId !== null && staged.commandId !== commandId)) throw new Error("Staged run attachment command conflicts."); } else if (!stagedTargetActivated(this.#store.state) && !["runner.drain", "session.open", "session.snapshot", "turn.stop", "runner.suspend", "session.close", "semantic_tool.result"].includes(type)) { throw new Error("Staged run attachment permits recovery maintenance only."); @@ -3068,7 +3088,7 @@ export class DurablePrpControlPlane { if ( commandId === transition.command.commandId && type === "run.attach" && - canonicalJson(payload) === canonicalJson(transition.command.payload) + controllerJson(payload) === controllerJson(transition.command.payload) ) return transition.command; throw new Error( @@ -3103,7 +3123,7 @@ export class DurablePrpControlPlane { if (existing !== undefined) { if ( existing.type !== type || - canonicalJson(existing.payload) !== canonicalJson(payload) + controllerJson(existing.payload) !== controllerJson(payload) ) { throw new Error( "Durable PRP command replay conflicts with persisted state.", diff --git a/packages/paperclip-runner/src/index.ts b/packages/paperclip-runner/src/index.ts index db819b7a6c4..d51046b4a6e 100644 --- a/packages/paperclip-runner/src/index.ts +++ b/packages/paperclip-runner/src/index.ts @@ -22,6 +22,7 @@ export * from "./contracts/types.js"; export * from "./backends/harness-driver-backend.js"; export * from "./drivers/dot/dot-harness-driver.js"; export { describeRunnerdNativeSessionBackend } from "./backends/codex-native-backend.js"; +export { nativeRunAttachReservedBytes } from "./backends/runtime-context.js"; export { createOpenCodeNativeSessionBackend } from "./backends/opencode-native-backend.js"; export { createNativeSessionBackend, diff --git a/packages/paperclip-runner/src/live/runnerd-codex-transport.ts b/packages/paperclip-runner/src/live/runnerd-codex-transport.ts index 87c38f45527..758f1f2d628 100644 --- a/packages/paperclip-runner/src/live/runnerd-codex-transport.ts +++ b/packages/paperclip-runner/src/live/runnerd-codex-transport.ts @@ -88,6 +88,7 @@ import { type RunnerProcessHandle, type RunnerProcessConnection, type DurablePrpControlPlaneOptions, + runAttachToolCatalogFits, } from "../control-plane/durable-prp-control-plane.js"; import { type QualifiedAcpxAgent, @@ -2610,6 +2611,10 @@ function commandDigest(value: unknown): string { return `sha256:${createHash("sha256").update(durableRecoveryInternals.canonicalJson(value)).digest("hex")}`; } +function controllerCommandDigest(value: unknown): string { + return `sha256:${createHash("sha256").update(durableRecoveryInternals.controllerJson(value)).digest("hex")}`; +} + function approvedRunnerArtifact(runnerBinaryPath: string): { version: string; digest: string; @@ -2823,7 +2828,7 @@ function completedMaintenanceTerminalReceipt( }; if ( record(state.runner.processedCommandFingerprints)[pending.commandId] !== - commandDigest(wire).slice("sha256:".length) + controllerCommandDigest(wire).slice("sha256:".length) ) return null; if (command.status === "pending") { @@ -2861,13 +2866,13 @@ function completedMaintenanceTerminalReplayMatches( after.runner.pendingTerminalDelivery == null && after.runner.pendingProviderCleanup == null && after.providerFingerprint === before.providerFingerprint && - commandDigest(after.runner.processedCommands) === - commandDigest(before.runner.processedCommands) && - commandDigest(after.runner.processedCommandFingerprints) === - commandDigest(before.runner.processedCommandFingerprints) && + controllerCommandDigest(after.runner.processedCommands) === + controllerCommandDigest(before.runner.processedCommands) && + controllerCommandDigest(after.runner.processedCommandFingerprints) === + controllerCommandDigest(before.runner.processedCommandFingerprints) && after.runner.lastControllerCommandSeq === before.runner.lastControllerCommandSeq && - commandDigest(after.control.commands) === commandDigest(expectedCommands) + controllerCommandDigest(after.control.commands) === controllerCommandDigest(expectedCommands) ); } @@ -3487,8 +3492,8 @@ async function settleRetainedRunnerdSessionOwned( settled.runner.pendingTerminalDelivery != null || commandDigest(settled.runner.pendingProviderCleanup) !== commandDigest(pendingTerminal) || - commandDigest(settled.control.commands) !== - commandDigest(before.control.commands) || + controllerCommandDigest(settled.control.commands) !== + controllerCommandDigest(before.control.commands) || epochProviderPids.size !== 0 || ![...pids].every(maintenanceProcessAbsent) ) @@ -3862,7 +3867,7 @@ function authorizedToolSet( return { schema: "paperclip.runner.authorized-tools.v1", schemaVersion: 1, - catalogDigest: commandDigest(operations), + catalogDigest: controllerCommandDigest(operations), operations, }; } @@ -3881,12 +3886,18 @@ export function authorizedToolSetForProvider( /** Include the completion tools that the Codex driver adds at session startup. */ export function runnerCodexDynamicToolsFit( tools: readonly Readonly>[], + reservedRunAttachBytes = 0, ): boolean { const supplied = [...tools, ...codexSemanticToolSpecs()]; // Keep these bounds aligned with runner-core/provider_bridge.rs. Project // large optional catalogs before run.prepare; never raise the protocol caps. - return supplied.length <= 256 && - Buffer.byteLength(JSON.stringify(authorizedToolSet(supplied)), "utf8") <= 768 * 1024; + if (supplied.length > 256) return false; + try { + const catalog = authorizedToolSet(supplied); + return Buffer.byteLength(JSON.stringify(catalog), "utf8") <= 768 * 1024 && runAttachToolCatalogFits(catalog, reservedRunAttachBytes); + } catch { + return false; + } } /** @@ -5171,7 +5182,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { const previous = record(this.#runAttachTemplate?.provider).runtimeContext; const current = input.currentRunGrant?.runtimeContext; return this.options.measureOperation ? this.options.measureOperation("runner.transport.attach", () => this.#attachRunWork(input, earlyClaim), - previous === undefined ? undefined : {contextReused:current === undefined || commandDigest(current) === commandDigest(previous)}) : this.#attachRunWork(input, earlyClaim); + previous === undefined ? undefined : {contextReused:current === undefined || controllerCommandDigest(current) === controllerCommandDigest(previous)}) : this.#attachRunWork(input, earlyClaim); } #assertRunAttachmentAdmission(): { core: DurablePrpControlPlane; retainingSource: boolean } { @@ -7264,7 +7275,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { ? core.getCommand(warmRecovery.commandId)?.payload.provider : exactAuthority ? record(controlPlaneState!.runAttachTemplate).provider : undefined; if ((exactAuthority || warmRecovery !== null) - && (recordedProvider === undefined || commandDigest(recordedProvider) !== commandDigest(saved.prepared.provider))) { + && (recordedProvider === undefined || controllerCommandDigest(recordedProvider) !== controllerCommandDigest(saved.prepared.provider))) { throw new Error("runner_prepared_launch_recovery_changed"); } template.provider = saved.prepared.provider; @@ -7330,7 +7341,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { this.#runAttachTemplate = structuredClone(runAttachTemplate); if (sourceAttachmentTarget) { await this.options.onStagedRunAttachment?.(core, { sourceIdentity: desiredIdentity, - targetIdentity: sourceAttachmentTarget, templateDigest: commandDigest(runAttachTemplate) }); + targetIdentity: sourceAttachmentTarget, templateDigest: controllerCommandDigest(runAttachTemplate) }); core.stageRunAttachment(sourceAttachmentTarget, runAttachTemplate); } else { core.persistRunAttachTemplate(runAttachTemplate); @@ -8268,8 +8279,8 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { if (existing) { if ( existing.type !== type || - durableRecoveryInternals.canonicalJson(existing.payload) !== - durableRecoveryInternals.canonicalJson(payload) + durableRecoveryInternals.controllerJson(existing.payload) !== + durableRecoveryInternals.controllerJson(payload) ) { throw new Error( `PRP steering correlation ${correlationId} was reused with different content`, diff --git a/server/src/services/native-runtime/assigned-mcp-tools.test.ts b/server/src/services/native-runtime/assigned-mcp-tools.test.ts index 5f4b653f4d9..67af5f7e069 100644 --- a/server/src/services/native-runtime/assigned-mcp-tools.test.ts +++ b/server/src/services/native-runtime/assigned-mcp-tools.test.ts @@ -10,7 +10,7 @@ import { ASSIGNED_SCHEMA_ADMISSION_CACHE_ENTRIES, ASSIGNED_SCHEMA_LISTING_BUDGET_BYTES, assignedSchemaAdmissionCacheSize, createAssignedMcpTools, getAssignedMcpGateway, registerAssignedMcpGateway, } from "./assigned-mcp-tools.js"; -import { admitToolInputSchema } from "../../vendor/paperclip-runner/index.js"; +import { admitToolInputSchema, runnerCodexDynamicToolsFit } from "../../vendor/paperclip-runner/index.js"; import { startOpenCodeMcpBridge } from "../../vendor/paperclip-runner/testing.js"; vi.mock("../../vendor/paperclip-runner/index.js", async importOriginal => { @@ -256,6 +256,22 @@ describe("assigned MCP runner tools", () => { } }); + it("moves a connector catalog the durable run attachment cannot carry to on-demand tools", async () => { + const properties = Object.fromEntries(Array.from({ length: 20 }, (_, index) => [`field_${index}`, { + type: "string", description: `Connector field ${index} with the provider's own documentation text.`, + enum: Array.from({ length: 6 }, (_, value) => `value_${value}`), + }])); + const descriptors = Array.from({ length: 180 }, (_, index) => ({ + ...descriptor(`connector.operation_${index}`), parametersSchema: { type: "object", properties }, + }) as ToolGatewayDescriptor); + const assigned = await createAssignedMcpTools(fixture(descriptors)); + const direct = assigned.definitions(); + expect(direct).toHaveLength(180); + expect(Buffer.byteLength(JSON.stringify(direct))).toBeLessThan(768 * 1024); + expect(runnerCodexDynamicToolsFit(direct)).toBe(false); + expect(assigned.definitions(runnerCodexDynamicToolsFit).map(tool => tool.name)).toEqual([searchName, callName]); + }); + it.each([1, 741])("uses bounded on-demand delivery for %i tools even when the direct catalog fits", async count => { const f = fixture(Array.from({ length: count }, (_, i) => descriptor(`app.operation_${i}`))); const direct = await createAssignedMcpTools(f); diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index 8ea78f0d81e..a6584779467 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -79,7 +79,7 @@ import { agentDirectoryBusyRetryDelayMs } from "../heartbeat/agent-directory-bus import { NativeExecutionContext } from "./native-execution-context.js"; import { NativeStartupCleanupPendingError, clearNativeStartupContext } from "./native-startup-cleanup.js"; import { readUnreadSteeredMessages } from "./unread-steered-messages.js"; -import { coldAdmissionTimeoutMs } from "../../vendor/paperclip-runner/index.js"; +import { coldAdmissionTimeoutMs, nativeRunAttachReservedBytes } from "../../vendor/paperclip-runner/index.js"; import { applyObservabilityEnvironment, type ProviderObservabilityLaunch } from "@paperclipai/adapter-utils/agent-observability"; import { museRunnerBroker } from "../muse-runner-broker.js"; import { nativeCaseHandoffResult } from "./native-case-handoff.js"; @@ -16794,6 +16794,7 @@ async function createRunnerdBackendWithinSessionClaim( input.executionContext?.signal.throwIfAborted(); const authority = new PaperclipRunnerToolAuthority(input.db, { apiUrl: resolveLocalRuntimeApiUrl(), + runAttachReservedBytes: nativeRunAttachReservedBytes(input.execution), casesEnabled: input.casesEnabled === true, responsibilitiesEnabled: input.responsibilitiesEnabled === true, ...(nativeReview ? { nativeReview } : {}), diff --git a/server/src/services/native-runtime/paperclip-runner-tool-authority.test.ts b/server/src/services/native-runtime/paperclip-runner-tool-authority.test.ts index f9f2de759be..f8c046e358f 100644 --- a/server/src/services/native-runtime/paperclip-runner-tool-authority.test.ts +++ b/server/src/services/native-runtime/paperclip-runner-tool-authority.test.ts @@ -1080,6 +1080,24 @@ describe("PaperclipRunnerToolAuthority", () => { } }); + it("moves assigned tools on demand when the run's reserved attachment bytes leave no room for them", async () => { + const listToolsForNamedGateway = vi.fn().mockResolvedValue(Array.from({ length: 40 }, (_, i) => ({ + name: `app.lookup_${i}`, displayName: `Lookup ${i}`, description: "Read a fixture", + parametersSchema: { type: "object", properties: { query: { type: "string", description: "Lookup field documentation. ".repeat(80) } } }, risk: "read", + }))); + const assignedMcpTools = await createAssignedMcpTools({ + gateway: { listToolsForNamedGateway } as unknown as ToolGatewayService, + gatewayPublicId: "fixture", bearerToken: "fixture-token", + }); + const binding = { companyId, agentId, issueId, runId, assignedMcpTools }; + const direct = new PaperclipRunnerToolAuthority(db, binding).definitions().map(tool => String(tool.name)); + expect(direct.filter(name => name.includes("lookup"))).toHaveLength(40); + const reserved = new PaperclipRunnerToolAuthority(db, { ...binding, runAttachReservedBytes: 340 * 1024 }) + .definitions().map(tool => String(tool.name)); + expect(reserved.filter(name => name.includes("lookup"))).toEqual([]); + expect(reserved).toEqual(expect.arrayContaining(["paperclip_search_assigned_tools", "paperclip_call_assigned_tool"])); + }); + it("fits large assigned catalogs alongside workspace and completion tools without dropping task tools", async () => { const listToolsForNamedGateway = vi.fn().mockResolvedValue(Array.from({ length: 224 }, (_, i) => ({ name: `app.action_${i}`, displayName: `Action ${i}`, description: "Read a fixture", diff --git a/server/src/services/native-runtime/paperclip-runner-tool-authority.ts b/server/src/services/native-runtime/paperclip-runner-tool-authority.ts index 368956da6e9..8330cac59a4 100644 --- a/server/src/services/native-runtime/paperclip-runner-tool-authority.ts +++ b/server/src/services/native-runtime/paperclip-runner-tool-authority.ts @@ -238,6 +238,7 @@ type Binding = { /** Server-owned suppression for baseline evals; true never overrides operator opt-in. */ connectorAssignments?: Pick[]; assignedMcpTools?: Awaited>; + runAttachReservedBytes?: number; apiToolsEnabled?: boolean; workMode?: "standard" | "planning" | "ask" | "skill_test"; casesEnabled?: boolean; @@ -481,7 +482,7 @@ export class PaperclipRunnerToolAuthority { ...(this.binding.connectorAssignments ?? []).flatMap((assignment) => assignment.tools)]; if (!this.binding.firstPartyOnly && this.binding.assignedMcpTools) definitions.push(READ_TOOL_RESULT_DEFINITION); const assignedTools = this.binding.firstPartyOnly ? [] : this.binding.assignedMcpTools?.definitions((tools) => - runnerCodexDynamicToolsFit([...connectionTools, ...tools, ...definitions])) ?? []; + runnerCodexDynamicToolsFit([...connectionTools, ...tools, ...definitions], this.binding.runAttachReservedBytes ?? 0)) ?? []; const all = [...connectionTools, ...assignedTools, ...definitions] .filter(tool => workMode !== "skill_test" || nativeSkillTestToolAllowed(String(tool.name))); return this.binding.museRuntime ? all.filter(definition => MUSE_NATIVE_OPERATIONS.has(String(definition.name))) : all; diff --git a/server/src/vendor/paperclip-runner/index.ts b/server/src/vendor/paperclip-runner/index.ts index 2f1b872597c..f12c6ca28c8 100644 --- a/server/src/vendor/paperclip-runner/index.ts +++ b/server/src/vendor/paperclip-runner/index.ts @@ -109,6 +109,7 @@ export const inspectUnclaimedBootstrapState = runner.inspectUnclaimedBootstrapSt export const RUNNER_PRP_PROTOCOL_MIN = runner.RUNNER_PRP_PROTOCOL_MIN; export const RUNNER_PRP_PROTOCOL_MAX = runner.RUNNER_PRP_PROTOCOL_MAX; export const runnerCodexDynamicToolsFit = runner.runnerCodexDynamicToolsFit; +export const nativeRunAttachReservedBytes = runner.nativeRunAttachReservedBytes; export const admitToolInputSchema = runner.admitToolInputSchema; export const TOOL_INPUT_SCHEMA_MAX_BYTES = runner.TOOL_INPUT_SCHEMA_MAX_BYTES; export const canonicalToolInputSchema = runner.canonicalToolInputSchema;