diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/acpx_provider_backend.rs b/packages/paperclip-runner/runner/crates/runner-core/src/acpx_provider_backend.rs index fc08dabd803..dd76e5eca01 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/acpx_provider_backend.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/acpx_provider_backend.rs @@ -225,7 +225,7 @@ impl AcpxProviderDescriptor { "1.0.88", None, None, - "sha256:3ff08fbe76fe4549c9eb01e8794428d8909c65c151d775220f2ec111d9e6f7c1", + "sha256:5e5955c57917a7e7c25703b3ed9e420cd72105eab033b611508dc37fdba3858b", ), "grok" => ( "grok-4.7", @@ -1762,6 +1762,54 @@ impl AcpxCommandExecutor { }))) } + fn snapshot_live_requests(&mut self) -> Result { + let session = self.session.as_mut().ok_or_else(|| { + DurableRunnerError::invalid("ACPX request snapshot requires the surviving provider") + })?; + let live_requests = session.verify_live_request_snapshot().map_err(|error| { + DurableRunnerError::invalid(format!("ACPX live request snapshot failed: {error}")) + })?; + let state = self + .state + .as_ref() + .ok_or_else(|| DurableRunnerError::invalid("ACPX provider state is unavailable"))?; + if state.provider_exit_unconfirmed + || state.lifecycle == "closed" + || state.identity.as_ref() != Some(session.identity()) + || state.active_turn_id.as_deref() != session.state().active_turn_id() + { + return Err(DurableRunnerError::invalid( + "ACPX live request snapshot lost its provider binding", + )); + } + validate_pending_runtime_requests(&state.pending_runtime_requests)?; + let requests = state + .pending_runtime_requests + .values() + .filter(|request| { + let id = request["requestId"].as_str().unwrap_or(""); + request["turnId"].as_str() == state.active_turn_id.as_deref() + && if request["type"] == "input" { + session + .state() + .pending_provider_input_request_id(id) + .and_then(|provider_id| live_requests.get(provider_id)) + .is_some_and(|kind| kind == "input") + } else { + session.state().pending_permission(id).is_some() + && live_requests + .get(id) + .is_some_and(|kind| kind == "permission") + } + }) + .cloned() + .collect::>(); + let mut snapshot = self.snapshot()?; + snapshot.result["pendingRuntimeRequests"] = json!(requests); + snapshot.result["runtimeRequestsLive"] = json!(true); + Ok(snapshot) + } + fn close_session(&mut self, reason: &str) -> Result { if let Some(session) = self.session.as_mut() { session.shutdown(reason).map_err(|error| { @@ -2041,6 +2089,15 @@ impl CommandExecutor for AcpxCommandExecutor { "turn.stop" => self.stop_turn_for_suspension(&command.command_type), "request.resolve" => self.resolve_request(&command.payload), "semantic_tool.result" => self.deliver_tool_result(&command.payload), + "session.snapshot" + if command + .payload + .get("includePendingRuntimeRequests") + .and_then(Value::as_bool) + == Some(true) => + { + self.snapshot_live_requests() + } "session.snapshot" => self.snapshot(), "session.close" | "session.destroy" => self.close_session(&command.command_type), "runner.suspend" => self.suspend(), @@ -2831,7 +2888,7 @@ mod tests { "copilot", "@github/copilot", "1.0.88", - "sha256:3ff08fbe76fe4549c9eb01e8794428d8909c65c151d775220f2ec111d9e6f7c1", + "sha256:5e5955c57917a7e7c25703b3ed9e420cd72105eab033b611508dc37fdba3858b", None, None, "explicit-model", diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/acpx_provider_session.rs b/packages/paperclip-runner/runner/crates/runner-core/src/acpx_provider_session.rs index 929147ab908..342b2389d40 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/acpx_provider_session.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/acpx_provider_session.rs @@ -357,6 +357,35 @@ impl AcpxProviderSession { &self.state } + /// Read the same live sidecar before exposing its in-memory pending ledger. + /// A durable file alone cannot authorize a request after process loss. + pub fn verify_live_request_snapshot( + &mut self, + ) -> Result, LocalRunnerError> { + self.ensure_open()?; + if self.runtime_retired || self.transport_terminated { + return Err(LocalRunnerError::invalid( + "ACPX request snapshot requires a live provider", + )); + } + let snapshot = self + .transport + .request(GeneratedAcpxSidecarCommand::SessionSnapshot, json!({}))?; + let identity: AcpxProviderSessionIdentity = + serde_json::from_value(snapshot["identity"].clone()).map_err(|_| { + LocalRunnerError::invalid("ACPX request snapshot identity is invalid") + })?; + if identity != self.identity + || snapshot["runId"].as_str() != Some(self.config.run_id.as_str()) + || snapshot["turnId"].as_str() != self.state.active_turn_id() + { + return Err(LocalRunnerError::invalid( + "ACPX request snapshot changed session or turn", + )); + } + live_snapshot_requests(&snapshot, self.state.active_turn_id()) + } + pub fn catalog_revision(&self) -> u64 { self.catalog_revision } @@ -1441,6 +1470,45 @@ fn verify_suspend_response( Ok(()) } +fn live_snapshot_requests( + snapshot: &Value, + active_turn_id: Option<&str>, +) -> Result, LocalRunnerError> { + #[derive(Deserialize)] + #[serde(rename_all = "camelCase", deny_unknown_fields)] + struct LiveRequest { + request_id: String, + r#type: String, + turn_id: String, + } + let requests = snapshot["pendingRuntimeRequests"] + .as_array() + .ok_or_else(|| { + LocalRunnerError::invalid("ACPX live request snapshot omitted its pending callbacks") + })?; + if requests.len() > 1_024 { + return Err(LocalRunnerError::invalid( + "ACPX live request snapshot exceeds its request bound", + )); + } + let mut live = std::collections::BTreeMap::new(); + for value in requests { + let request: LiveRequest = serde_json::from_value(value.clone()).map_err(|_| { + LocalRunnerError::invalid("ACPX live request snapshot callback is invalid") + })?; + validate_text(&request.request_id, MAX_ID_CHARS, "live callback id")?; + if !matches!(request.r#type.as_str(), "input" | "permission") + || Some(request.turn_id.as_str()) != active_turn_id + || live.insert(request.request_id, request.r#type).is_some() + { + return Err(LocalRunnerError::invalid( + "ACPX live request snapshot callback binding is invalid", + )); + } + } + Ok(live) +} + fn validate_text(value: &str, max_chars: usize, label: &str) -> Result<(), LocalRunnerError> { if value.trim().is_empty() || value.chars().count() > max_chars @@ -1532,6 +1600,45 @@ fn with_cleanup_error( #[cfg(test)] mod tests { + #[test] + fn live_request_snapshot_requires_current_unique_typed_callbacks() { + use super::*; + let request = json!({"requestId":"input-1","type":"input","turnId":"turn-1"}); + let snapshot = json!({"pendingRuntimeRequests":[request.clone(), + {"requestId":"permission-1","type":"permission","turnId":"turn-1"}]}); + let live = live_snapshot_requests(&snapshot, Some("turn-1")).unwrap(); + assert_eq!(live.get("input-1").map(String::as_str), Some("input")); + assert_eq!( + live.get("permission-1").map(String::as_str), + Some("permission") + ); + for invalid in [ + json!({}), + json!({"pendingRuntimeRequests":null}), + json!({"pendingRuntimeRequests":[request.clone(),request.clone()]}), + json!({"pendingRuntimeRequests":[{"requestId":"","type":"input","turnId":"turn-1"}]}), + json!({"pendingRuntimeRequests":[{"requestId":"input-1","type":"tool","turnId":"turn-1"}]}), + json!({"pendingRuntimeRequests":[{"requestId":"input-1","type":"input","turnId":"turn-2"}]}), + json!({"pendingRuntimeRequests":[{"requestId":"input-1","type":"input","turnId":"turn-1","extra":true}]}), + ] { + assert!( + live_snapshot_requests(&invalid, Some("turn-1")).is_err(), + "{invalid}" + ); + } + assert!(live_snapshot_requests(&snapshot, None).is_err()); + assert!(live_snapshot_requests( + &json!({"pendingRuntimeRequests":vec![request;1_025]}), + Some("turn-1") + ) + .is_err()); + assert!( + live_snapshot_requests(&json!({"pendingRuntimeRequests":[]}), None) + .unwrap() + .is_empty() + ); + } + #[test] fn turn_controls_require_exact_live_pi_capability_fields() { use super::*; diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/bin/fake-acpx-sidecar.rs b/packages/paperclip-runner/runner/crates/runner-core/src/bin/fake-acpx-sidecar.rs index 6cbd0e9f093..fb7c0eb078f 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/bin/fake-acpx-sidecar.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/bin/fake-acpx-sidecar.rs @@ -287,6 +287,9 @@ fn run() -> Result<(), Box> { | "resolutions-error-redaction" | "resolutions-projected-id" | "resolutions-wrong-ack" + | "resolutions-snapshot-wrong-session" + | "resolutions-snapshot-wrong-turn" + | "resolutions-snapshot-missing-callbacks" | "suspend" | "suspend-wrong-ack" | "suspend-wrong-identity" @@ -679,15 +682,7 @@ fn run() -> Result<(), Box> { )?; next_sequence += 1; } - if command == "turn.start" - && matches!( - mode, - "resolutions" - | "resolutions-error-redaction" - | "resolutions-projected-id" - | "resolutions-wrong-ack" - ) - { + if command == "turn.start" && mode.starts_with("resolutions") { for (event_type, payload) in [ ( "runtime.tool_called", @@ -834,6 +829,22 @@ fn bootstrap_success( "turn.cancel" => { json!({"cancelled":mode != "turns-wrong-cancel", "sessionClosed":matches!(mode, "turns-retired" | "turns-retired-terminal-first")}) } + "session.snapshot" => json!({ + "identity": { + "kind":"acpx", "normalizedSessionId":"session-1", + "acpxRecordId":if mode == "resolutions-snapshot-wrong-session" {"other-record"} else {"record-1"}, + "backendSessionId":"backend-1", "agentSessionId":"agent-1", + "profileDigest":profile_digest, "workspaceDigest":format!("sha256:{}", "2".repeat(64)), + "requestedModel":"gpt-5.6-sol", "effectiveModel":"gpt-5.6-sol", + "permissionMode":"approve-reads", "providerLifetimeFenceCandidates":[60001,60002,60003] + }, + "runId":"run-1", + "turnId":if mode == "resolutions-snapshot-wrong-turn" {"other-turn"} else {"turn-1"}, + "pendingRuntimeRequests":if mode == "resolutions-snapshot-missing-callbacks" {Value::Null} else { + json!([{"requestId":if mode == "resolutions-projected-id" {PROJECTED_INPUT_PROVIDER_ID} else {"input-1"}, + "type":"input","turnId":"turn-1"}]) + } + }), "session.suspend" => json!({ "suspended":mode != "suspend-wrong-ack", "identity": if mode == "suspend-missing-identity" { Value::Null } else { json!({ diff --git a/packages/paperclip-runner/runner/crates/runner-core/tests/acpx_provider_resolutions.rs b/packages/paperclip-runner/runner/crates/runner-core/tests/acpx_provider_resolutions.rs index 0f361ac79fd..163da48eda5 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/tests/acpx_provider_resolutions.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/tests/acpx_provider_resolutions.rs @@ -107,6 +107,32 @@ fn commits_each_resolution_only_after_sidecar_acknowledgement() { session.shutdown("test complete").unwrap(); } +#[test] +fn live_callback_snapshot_checks_the_surviving_sidecar_and_upstream_input_id() { + for mode in ["resolutions", "resolutions-projected-id"] { + let mut session = started(mode); + let live = session.verify_live_request_snapshot().unwrap(); + let provider_id = if mode == "resolutions-projected-id" { + "input / réquest" + } else { + "input-1" + }; + assert_eq!(live.get(provider_id).map(String::as_str), Some("input")); + assert_eq!(live.len(), 1); + session.shutdown("test complete").unwrap(); + assert!(session.verify_live_request_snapshot().is_err()); + } + for mode in [ + "resolutions-snapshot-wrong-session", + "resolutions-snapshot-wrong-turn", + "resolutions-snapshot-missing-callbacks", + ] { + let mut session = started(mode); + assert!(session.verify_live_request_snapshot().is_err(), "{mode}"); + session.shutdown("test complete").unwrap(); + } +} + #[test] fn projected_request_id_resolves_the_exact_upstream_sidecar_request() { let mut session = AcpxProviderSession::start(&config("resolutions-projected-id")).unwrap(); diff --git a/packages/paperclip-runner/scripts/build-copilot-distribution.mjs b/packages/paperclip-runner/scripts/build-copilot-distribution.mjs index d6205bcbb44..19a2418a1ab 100644 --- a/packages/paperclip-runner/scripts/build-copilot-distribution.mjs +++ b/packages/paperclip-runner/scripts/build-copilot-distribution.mjs @@ -7,7 +7,7 @@ import { COPILOT_VERSION, materializePinnedCopilotBinary, resolveCopilotDistribu const MAX_ARCHIVE_BYTES = 128 * 1024 * 1024; const MAX_EXPANDED_BYTES = 384 * 1024 * 1024; -const PROFILE_DIGEST = "sha256:3ff08fbe76fe4549c9eb01e8794428d8909c65c151d775220f2ec111d9e6f7c1"; +const PROFILE_DIGEST = "sha256:5e5955c57917a7e7c25703b3ed9e420cd72105eab033b611508dc37fdba3858b"; /** Build-time only; outputRoot is the exact runner-owned platform asset directory. */ export async function buildPinnedCopilotDistribution({ outputRoot, platform = process.platform, architecture = process.arch }, { fetchImpl = fetch } = {}) { diff --git a/packages/paperclip-runner/src/cli/acpx-runtime-sidecar.test.ts b/packages/paperclip-runner/src/cli/acpx-runtime-sidecar.test.ts index 629b7768037..e985f3e2b62 100644 --- a/packages/paperclip-runner/src/cli/acpx-runtime-sidecar.test.ts +++ b/packages/paperclip-runner/src/cli/acpx-runtime-sidecar.test.ts @@ -11,6 +11,47 @@ import { fileURLToPath } from "node:url"; import { afterEach, describe, expect, it, vi } from "vitest"; +describe("live sidecar pending request snapshots", () => { + it("attests current callback identities after the live status barrier without exposing forms", async () => { + const source = readFileSync(new URL("./acpx-runtime-sidecar.ts", import.meta.url), "utf8"); + const start = source.indexOf(' if (request.command === "session.snapshot") {'); + const end = source.indexOf(' if (request.command === "session.goal.get") {', start); + expect(start).toBeGreaterThan(0); + const inputs = new Map([['input-1', { turnId: 'turn-1', questionSet: { private: 'hidden form' } }]]); + const permissions = new Map([['permission-1', { turnId: 'turn-1', normalized: { private: 'hidden permission' } }]]); + const host = { identity: () => 'identity', binding: () => 'binding' }; + const readStatus = vi.fn(async () => { + inputs.delete('input-1'); + inputs.set('input-2', { turnId: 'turn-1', questionSet: { private: 'new hidden form' } }); + return { live: true }; + }); + const run = new Function('requireHost', 'readSidecarHostStatusWithin', 'sanitizeRuntimeStatus', 'acpxProviderSessionIdentity', 'inputs', 'permissions', ` + const request={command:"session.snapshot"}, tools=new Map(), runId="run-1", turnId="turn-1", sequence=7; + ${stripTypeScriptTypes(`async function readSnapshot() { ${source.slice(start, end)} }`)} + return readSnapshot; + `)(() => host, readStatus, (value: unknown) => value, () => ({ kind: 'acpx' }), inputs, permissions); + const snapshot = await run(); + expect(readStatus).toHaveBeenCalledExactlyOnceWith(host); + expect(snapshot).toMatchObject({ runId: 'run-1', turnId: 'turn-1', pendingRuntimeRequests: [ + { requestId: 'input-2', type: 'input', turnId: 'turn-1' }, + { requestId: 'permission-1', type: 'permission', turnId: 'turn-1' }, + ] }); + expect(JSON.stringify(snapshot)).not.toContain('hidden'); + }); + + it("rejects the snapshot when its provider status cannot be verified", async () => { + const source = readFileSync(new URL("./acpx-runtime-sidecar.ts", import.meta.url), "utf8"); + const start = source.indexOf(' if (request.command === "session.snapshot") {'); + const end = source.indexOf(' if (request.command === "session.goal.get") {', start); + const run = new Function('requireHost', 'readSidecarHostStatusWithin', 'sanitizeRuntimeStatus', ` + const request={command:"session.snapshot"}; + ${stripTypeScriptTypes(`async function readSnapshot() { ${source.slice(start, end)} }`)} + return readSnapshot; + `)(() => ({}), async () => { throw new Error('provider process lost'); }, (value: unknown) => value); + await expect(run()).rejects.toThrow('provider process lost'); + }); +}); + import { deliverAcpxResponse } from "../drivers/acpx/response-delivery.js"; import { normalizeAcpxPermission } from "../drivers/acpx/acp-permission-adapter.js"; import { ACPX_CAPABILITY_PROFILES } from "../drivers/acpx/capability-profiles.js"; diff --git a/packages/paperclip-runner/src/cli/acpx-runtime-sidecar.ts b/packages/paperclip-runner/src/cli/acpx-runtime-sidecar.ts index a7439963f3e..783a69e2cb5 100644 --- a/packages/paperclip-runner/src/cli/acpx-runtime-sidecar.ts +++ b/packages/paperclip-runner/src/cli/acpx-runtime-sidecar.ts @@ -517,19 +517,22 @@ async function dispatch( } if (request.command === "session.snapshot") { const activeHost = requireHost(); + const status = sanitizeRuntimeStatus(await readSidecarHostStatusWithin(activeHost)); return { identity: acpxProviderSessionIdentity( activeHost.identity(), activeHost.binding(), ), - status: sanitizeRuntimeStatus( - await readSidecarHostStatusWithin(activeHost), - ), + status, runId, turnId, sequence, pendingToolCount: tools.size, pendingInputCount: inputs.size, + pendingRuntimeRequests: [ + ...Array.from(inputs, ([requestId, pending]) => ({ requestId, type: "input", turnId: pending.turnId })), + ...Array.from(permissions, ([requestId, pending]) => ({ requestId, type: "permission", turnId: pending.turnId })), + ], }; } if (request.command === "session.goal.get") { diff --git a/packages/paperclip-runner/src/contracts/native-execution.test.ts b/packages/paperclip-runner/src/contracts/native-execution.test.ts index 96db8b74a9d..e2c4edcd45b 100644 --- a/packages/paperclip-runner/src/contracts/native-execution.test.ts +++ b/packages/paperclip-runner/src/contracts/native-execution.test.ts @@ -344,7 +344,7 @@ describe("NativeExecutionInputV1", () => { profile: provider.profile, }); expect(parseNativeExecutionInput(parsed)).toEqual(parsed); - for (const unsupportedVersion of [0, 14, 1.5, "13", null]) { + for (const unsupportedVersion of [0, 15, 1.5, "14", null]) { expect(() => parseNativeExecutionInput({ ...input, session: { ...input.session, driverKind: "acpx_runtime" }, diff --git a/packages/paperclip-runner/src/contracts/native-execution.ts b/packages/paperclip-runner/src/contracts/native-execution.ts index 620141c2763..bc381f32e3c 100644 --- a/packages/paperclip-runner/src/contracts/native-execution.ts +++ b/packages/paperclip-runner/src/contracts/native-execution.ts @@ -91,7 +91,7 @@ export interface NativeAcpxProfileSnapshot { protocolVersion: 1; acpxVersion: "0.13.1"; agent: NativeAcpxAgent; - agentProfileVersion: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13; + agentProfileVersion: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14; agentServerPackage: string; agentServerVersion: string; agentRuntimePackage: string | null; @@ -616,7 +616,7 @@ export function parseNativeExecutionInput(value: unknown): NativeExecutionInput || profile.protocolVersion !== 1 || profile.acpxVersion !== "0.13.1" || profile.agent !== provider.agent - || (profile.agentProfileVersion !== 1 && profile.agentProfileVersion !== 2 && profile.agentProfileVersion !== 3 && profile.agentProfileVersion !== 4 && profile.agentProfileVersion !== 5 && profile.agentProfileVersion !== 6 && profile.agentProfileVersion !== 7 && profile.agentProfileVersion !== 8 && profile.agentProfileVersion !== 9 && profile.agentProfileVersion !== 10 && profile.agentProfileVersion !== 11 && profile.agentProfileVersion !== 12 && profile.agentProfileVersion !== 13) + || (profile.agentProfileVersion !== 1 && profile.agentProfileVersion !== 2 && profile.agentProfileVersion !== 3 && profile.agentProfileVersion !== 4 && profile.agentProfileVersion !== 5 && profile.agentProfileVersion !== 6 && profile.agentProfileVersion !== 7 && profile.agentProfileVersion !== 8 && profile.agentProfileVersion !== 9 && profile.agentProfileVersion !== 10 && profile.agentProfileVersion !== 11 && profile.agentProfileVersion !== 12 && profile.agentProfileVersion !== 13 && profile.agentProfileVersion !== 14) ) { throw new NativeExecutionInputError("input.provider.profile does not match the qualified ACPX v1 profile"); } diff --git a/packages/paperclip-runner/src/drivers/acpx/copilot-installation.test.ts b/packages/paperclip-runner/src/drivers/acpx/copilot-installation.test.ts index 37e1e4f7799..4637385a1c6 100644 --- a/packages/paperclip-runner/src/drivers/acpx/copilot-installation.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/copilot-installation.test.ts @@ -73,8 +73,15 @@ describe("Copilot build-owned installation", () => { expect(QUALIFIED_ACPX_PROFILES.copilot.qualificationStatus).toBe("pending"); }); - it("admits the current v13 declaration and binds its source policy, receipts and patch hashes", () => { - const identity = JSON.parse(readFileSync(new URL("../../../test/fixtures/copilot-profile-v13-identity.json", import.meta.url), "utf8")); + it("preserves v13 history while binding the shared live request snapshot", () => { + const prior = JSON.parse(readFileSync(new URL("../../../test/fixtures/copilot-profile-v13-identity.json", import.meta.url), "utf8")); + const current = JSON.parse(readFileSync(new URL("../../../test/fixtures/copilot-profile-v14-identity.json", import.meta.url), "utf8")); + expect(Object.keys(current.declaration).filter(key => current.declaration[key] !== prior.declaration[key]).sort()).toEqual(["agentProfileVersion", "semanticSidecarSourceSha256"]); + expect(QUALIFIED_ACPX_PROFILES.copilot.qualificationStatus).toBe("pending"); + }); + + it("admits the current v14 declaration and binds its source policy, receipts and patch hashes", () => { + const identity = JSON.parse(readFileSync(new URL("../../../test/fixtures/copilot-profile-v14-identity.json", import.meta.url), "utf8")); expect(identity.declaration.systemInstructionDelivery).toBe(COPILOT_SYSTEM_INSTRUCTION_DELIVERY); expect(identity.declaration.sharedRuntimeContract).toBe("paperclip.acpx-runtime-contract.v1"); expect(identity.declaration.permissionContextContract).toBe(COPILOT_PERMISSION_CONTEXT_CONTRACT); @@ -105,7 +112,7 @@ describe("Copilot build-owned installation", () => { expect([...closure].filter(path => !bound.has(path))).toEqual(["negative-control:unbound-policy"]); }); it.each([...PERMISSION_POLICY_SOURCES, ...SEMANTIC_RECEIPT_SOURCES])("changing %s changes the candidate identity", (_path, field) => { - const identity = JSON.parse(readFileSync(new URL("../../../test/fixtures/copilot-profile-v13-identity.json", import.meta.url), "utf8")); + const identity = JSON.parse(readFileSync(new URL("../../../test/fixtures/copilot-profile-v14-identity.json", import.meta.url), "utf8")); identity.declaration[field] = "0".repeat(64); const sorted = Object.fromEntries(Object.entries(identity.declaration).sort(([a], [b]) => a.localeCompare(b))); expect(`sha256:${createHash("sha256").update(JSON.stringify(sorted)).digest("hex")}`).not.toBe(identity.commandDigest); diff --git a/packages/paperclip-runner/src/drivers/acpx/qualified-profiles.ts b/packages/paperclip-runner/src/drivers/acpx/qualified-profiles.ts index aaf4aaef5c6..a4aa425d9ee 100644 --- a/packages/paperclip-runner/src/drivers/acpx/qualified-profiles.ts +++ b/packages/paperclip-runner/src/drivers/acpx/qualified-profiles.ts @@ -71,10 +71,10 @@ export const QUALIFIED_ACPX_PROFILES: Readonly< }, copilot: { driverKind: ACPX_DRIVER_KIND, protocolVersion: ACPX_DRIVER_PROTOCOL_VERSION, - acpxVersion: QUALIFIED_ACPX_VERSION, agent: "copilot", agentProfileVersion: 13, + acpxVersion: QUALIFIED_ACPX_VERSION, agent: "copilot", agentProfileVersion: 14, agentServerPackage: "@github/copilot", agentServerVersion: "1.0.88", agentRuntimePackage: null, agentRuntimeVersion: null, - commandDigest: "sha256:3ff08fbe76fe4549c9eb01e8794428d8909c65c151d775220f2ec111d9e6f7c1", + commandDigest: "sha256:5e5955c57917a7e7c25703b3ed9e420cd72105eab033b611508dc37fdba3858b", // Authenticated discovery has not established a qualification model. Never // turn this empty declaration into a default; callers must select an ID. qualificationModel: "", reportedModelId: "", permissionPolicy: "interactive", diff --git a/packages/paperclip-runner/src/drivers/codex/app-server-transport.ts b/packages/paperclip-runner/src/drivers/codex/app-server-transport.ts index 0b06817a53c..0a40bb8d1f3 100644 --- a/packages/paperclip-runner/src/drivers/codex/app-server-transport.ts +++ b/packages/paperclip-runner/src/drivers/codex/app-server-transport.ts @@ -40,6 +40,8 @@ export interface CodexAppServerTransport { notify(method: string, params?: Record): void; notifications(): AsyncIterable; setServerRequestHandler(handler: CodexServerRequestHandler): void; + /** One-shot requests authenticated by an adopted live provider, never a saved checkpoint alone. */ + takeRestoredRuntimeRequests?(): CodexRpcServerRequest[]; /** * Optional provider-neutral resolution path used when a transport has * already normalized a native server request behind another PRP boundary. diff --git a/packages/paperclip-runner/src/drivers/codex/codex-harness-session.ts b/packages/paperclip-runner/src/drivers/codex/codex-harness-session.ts index 2b22e9bbb2d..7d0bfc531f4 100644 --- a/packages/paperclip-runner/src/drivers/codex/codex-harness-session.ts +++ b/packages/paperclip-runner/src/drivers/codex/codex-harness-session.ts @@ -64,7 +64,17 @@ export class CodexHarnessSession this.transport.setServerRequestHandler((request) => handleServerRequest(this, request), ); - initializeCodexSessionEvents(this, input); + const restored = this.transport.takeRestoredRuntimeRequests?.() ?? []; + const restoredIds = new Set(restored.map(request => String(request.id))); + initializeCodexSessionEvents(this, { + ...input, + stalePendingRuntimeRequests: input.stalePendingRuntimeRequests?.filter(request => !restoredIds.has(request.requestId)), + }); + for (const request of restored) { + void handleServerRequest(this, request).catch(error => this.failProtocol( + "runtime_request_recovery_failed", error instanceof Error ? error.message : String(error), + )); + } if (this.terminal) { this.eventQueue.close(); } else { diff --git a/packages/paperclip-runner/src/live/acpx-request-recovery.test.ts b/packages/paperclip-runner/src/live/acpx-request-recovery.test.ts new file mode 100644 index 00000000000..ed84c5d0d73 --- /dev/null +++ b/packages/paperclip-runner/src/live/acpx-request-recovery.test.ts @@ -0,0 +1,98 @@ +import { describe, expect, it, vi } from "vitest"; +import { liveAcpxRuntimeRequests } from "./runnerd-codex-transport.js"; +import { FakeCodexTransport, makeDriver, WORKSPACE } from "../drivers/codex/codex-app-server-driver.test-support.js"; +import type { CodexRpcServerRequest } from "../drivers/codex/app-server-transport.js"; + +function snapshot() { + return { + provider: "acpx", runtimeRequestsLive: true, + driverSessionId: "thread-1", activeProviderTurnId: "turn-1", + pendingRuntimeRequests: [{ + schema: "paperclip.runtime_request.v2", requestId: "input-1", type: "input", + requestKind: "runtime", status: "pending", turnId: "turn-1", itemId: "question-1", + origin: { adapter: "acpx-runtime-sidecar", provider: "pi", method: "elicitation/create" }, + input: { schema: "paperclip.question_set.v1", questions: [ + { id: "answer", prompt: "Give the answer", required: true, answerMode: "text" }, + ] }, + }, { + schema: "paperclip.runtime_request.v2", requestId: "permission-1", type: "permission", + requestKind: "permission_approval", status: "pending", turnId: "turn-1", itemId: "write-1", + prompt: "Allow this write?", choices: [{ key: "deny", label: "Decline", outcome: "cancel" }], + details: { toolCallId: "write-1" }, + origin: { adapter: "acpx-runtime-sidecar", provider: "pi", method: "session/request_permission" }, + }], + }; +} + +describe("live ACP request recovery", () => { + it("retains original question, option and permission identities", () => { + const value = snapshot(); + const requests = liveAcpxRuntimeRequests(value, "thread-1", "turn-1"); + expect(requests.map(request => [request.id, request.method])).toEqual([ + ["input-1", "elicitation/create"], ["permission-1", "session/request_permission"], + ]); + expect(requests[0]!.params.questionSet).toEqual(value.pendingRuntimeRequests[0]!.input); + expect(requests[1]!.params).toMatchObject({ choices: value.pendingRuntimeRequests[1]!.choices, toolCallId: "write-1" }); + }); + + it.each([ + ["missing live attestation", { runtimeRequestsLive: false }], + ["wrong provider", { provider: "codex" }], + ["wrong session", { driverSessionId: "other" }], + ["wrong turn", { activeProviderTurnId: "other" }], + ["missing ledger", { pendingRuntimeRequests: null }], + ])("rejects %s", (_name, change) => { + expect(() => liveAcpxRuntimeRequests({ ...snapshot(), ...change }, "thread-1", "turn-1")).toThrow(); + }); + + it.each([ + { requestId: "" }, { status: "resolved" }, { turnId: "old-turn" }, + { schema: "paperclip.runtime_request.v1" }, { type: "permission" }, + { origin: { method: "item/tool/call" } }, { input: null }, + ])("rejects malformed or stale callback %j", change => { + const value = snapshot(); + expect(() => liveAcpxRuntimeRequests({ ...value, pendingRuntimeRequests: [{ ...value.pendingRuntimeRequests[0], ...change }] }, "thread-1", "turn-1")).toThrow(); + }); + + it("rejects duplicate or oversized callback ledgers", () => { + const value = snapshot(); + for (const count of [2, 1025]) { + expect(() => liveAcpxRuntimeRequests({ ...value, pendingRuntimeRequests: Array(count).fill(value.pendingRuntimeRequests[0]) }, "thread-1", "turn-1")).toThrow(); + } + }); + + it.each(["input-1", "permission-1"])("restores and delivers %s once after controller recovery", async requestId => { + const requests = liveAcpxRuntimeRequests(snapshot(), "thread-1", "turn-1"); + const originalTransport = new FakeCodexTransport(); + const original = await makeDriver([originalTransport]).openSession({ runId: "run-1", normalizedSessionId: "session-1", workingDirectory: WORKSPACE }); + let recovered: Awaited> | undefined; + try { + await original.startTurn({ message: { role: "user", text: "Wait for input" } }); + for (const request of requests) void originalTransport.invoke(request); + await Promise.resolve(); + recovered = await original.snapshot(); + expect(recovered.pendingRuntimeRequests).toHaveLength(2); + } finally { + await original.close(); + } + class AdoptedTransport extends FakeCodexTransport { + takeRestoredRuntimeRequests(): CodexRpcServerRequest[] { return requests; } + } + const transport = new AdoptedTransport(); + const deliver = vi.fn(async () => {}); + transport.runtimeRequestResolver = deliver; + const recovery = await makeDriver([transport]).recoverSession(recovered!); + expect(recovery.recovered).toBe(true); + const session = recovery.session!; + try { + expect(session.pendingRuntimeRequests?.().map(request => request.requestId)).toEqual(["input-1", "permission-1"]); + const resolution = requestId === "input-1" + ? { action: "submit" as const, content: { schema: "paperclip.question_response.v1", answers: { answer: { text: "undisclosed answer" } } } } + : { action: "decline" as const }; + await session.resolveRuntimeRequest?.({ requestId, turnId: "turn-1", resolution }); + expect(deliver).toHaveBeenCalledExactlyOnceWith({ requestId, turnId: "turn-1", resolution }); + await expect(session.resolveRuntimeRequest?.({ requestId, turnId: "turn-1", resolution })).rejects.toThrow("no longer pending"); + expect(deliver).toHaveBeenCalledTimes(1); + } finally { await session.close(); } + }); +}); diff --git a/packages/paperclip-runner/src/live/runnerd-codex-transport.ts b/packages/paperclip-runner/src/live/runnerd-codex-transport.ts index 5fc327a60b4..c884fad4c60 100644 --- a/packages/paperclip-runner/src/live/runnerd-codex-transport.ts +++ b/packages/paperclip-runner/src/live/runnerd-codex-transport.ts @@ -920,8 +920,12 @@ export function bridgedAcpxPermissionParams( turnId: string, ): Record | null { const request = record(record(record(event.envelope.payload).payload).request); - if (event.eventType !== "runtime_request.created" - || request.type !== "permission" || request.requestKind !== "permission_approval" + if (event.eventType !== "runtime_request.created") return null; + return acpxPermissionRequestParams(request, threadId, turnId); +} + +function acpxPermissionRequestParams(request: Record, threadId: string, turnId: string): Record | null { + if (request.type !== "permission" || request.requestKind !== "permission_approval" || record(request.origin).method !== "session/request_permission") return null; const toolCallId = record(request.details).toolCallId; // Match the permission adapter's 240-character bound. Never truncate, trim, @@ -940,6 +944,35 @@ export function bridgedAcpxPermissionParams( }; } +/** Rehydrate only the pending ledger attested by the same live ACP session. */ +export function liveAcpxRuntimeRequests(snapshot: Record, threadId: string, turnId: string): CodexRpcServerRequest[] { + if (snapshot.runtimeRequestsLive !== true || snapshot.provider !== "acpx" + || snapshot.driverSessionId !== threadId || snapshot.activeProviderTurnId !== turnId + || !turnId || !Array.isArray(snapshot.pendingRuntimeRequests) + || snapshot.pendingRuntimeRequests.length > 1024) { + throw new Error("ACPX pending request snapshot binding is invalid"); + } + const ids = new Set(); + return snapshot.pendingRuntimeRequests.map(value => { + const request = record(value), origin = record(request.origin); + const id = request.requestId, method = origin.method; + if (typeof id !== "string" || !id || id.length > 160 || ids.has(id) + || request.schema !== "paperclip.runtime_request.v2" || request.status !== "pending" + || request.turnId !== turnId || typeof method !== "string") { + throw new Error("ACPX pending request snapshot request is invalid"); + } + ids.add(id); + const permission = request.type === "permission" && request.requestKind === "permission_approval" + && method === "session/request_permission"; + const params = permission + ? acpxPermissionRequestParams(request, threadId, turnId) + : request.type === "input" && request.requestKind === "runtime" && isAcpxCanonicalInputMethod(method) + ? bridgedCodexQuestionParams(request, method, threadId, turnId) : null; + if (!params) throw new Error("ACPX pending request snapshot form is invalid"); + return { id, method, params }; + }); +} + export function bridgedCodexQuestionParams( request: Record, method: string, @@ -3511,6 +3544,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { readonly #traceFrameIndex = new RunnerdTraceFrameIndex(); #pendingTraceRehydrations: PendingTraceRehydration[] = []; #pendingDriverTraceInterpretations: PendingDriverTraceInterpretation[] = []; + #restoredRuntimeRequests: CodexRpcServerRequest[] = []; readonly #bridgedRuntimeInputs = new Map(); constructor(readonly options: CapabilityRunnerdCodexTransportOptions) { @@ -3701,7 +3735,10 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { // than reading its filesystem. This both supports remote process owners // and proves any identity restored after PRP event compaction before the // checkpoint-backed thread is exposed to the driver. - const snapshot = await this.#commandResult("session.snapshot", {}); + const restoreRuntimeRequests = this.#recoveryTurnBindingPending + && this.options.adoptExistingRunner !== undefined && this.options.provider === "acpx"; + const snapshot = await this.#commandResult("session.snapshot", restoreRuntimeRequests + ? { includePendingRuntimeRequests: true } : {}); this.#confirmCheckpointProviderIdentity( snapshot, "authenticated session.snapshot", @@ -3758,6 +3795,15 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { }); } } + if (restoreRuntimeRequests && activeProviderTurnId !== null) { + this.#restoredRuntimeRequests = liveAcpxRuntimeRequests(snapshot, this.#threadId, activeProviderTurnId); + for (const request of this.#restoredRuntimeRequests) { + this.#bridgedRuntimeInputs.set(String(request.id), { + durableTurnId: this.#durableTurnId, + permission: request.method === "session/request_permission", + }); + } + } this.#recoveryTurnBindingPending = false; this.#pumpEvents(); return { @@ -3837,6 +3883,14 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { return this.#queue; } + takeRestoredRuntimeRequests(): CodexRpcServerRequest[] { + this.#throwIfFailed(); + const requests = this.#restoredRuntimeRequests; + this.#restoredRuntimeRequests = []; + return requests.filter(request => this.#bridgedRuntimeInputs.has(String(request.id)) + && request.params.threadId === this.#threadId && request.params.turnId === this.#turnId); + } + setServerRequestHandler(handler: CodexServerRequestHandler): void { this.#handler = handler; } diff --git a/packages/paperclip-runner/test/fixtures/copilot-profile-v14-identity.json b/packages/paperclip-runner/test/fixtures/copilot-profile-v14-identity.json new file mode 100644 index 00000000000..74191266281 --- /dev/null +++ b/packages/paperclip-runner/test/fixtures/copilot-profile-v14-identity.json @@ -0,0 +1,43 @@ +{ + "commandDigest": "sha256:5e5955c57917a7e7c25703b3ed9e420cd72105eab033b611508dc37fdba3858b", + "declaration": { + "schema": "paperclip.acpx_profile_declaration.v1", + "agent": "copilot", + "agentProfileVersion": 14, + "acpxVersion": "0.13.1", + "agentServerVersion": "1.0.88", + "protocolPolicyRevision": "copilot-agent-manual-v1", + "acpxPatchSha256": "bd5393058a218040d217fa85449d59a6f30507de54cd645bf0ef21422823f85e", + "policySha256": "a4be69be43db84052560420a3ca546a665c9165573c24d543eb33d144ba138a3", + "distributionSourceSha256": "c0a65e247fc47b263bd369a3d5ab505c4b323d4e6493be8a9ecbeb0e9dbb9107", + "agentFilesBinding": "registered-runtime-context-v1", + "systemInstructionDelivery": "COPILOT_HOME/copilot-instructions.md:replace-under-lifetime-lease-before-launch:v1", + "sharedRuntimeContract": "paperclip.acpx-runtime-contract.v1", + "innerDistributionSourceSha256": "9bb08347eed01f1ab44e065c8b06ead9be3a25973d6e6329dc4c0a099096279a", + "upstreamAppSha256": "7b48282a19b5b0814a0c96ad5e3a125173d792cc55f9525b2effea962f6063c0", + "patchedAppSha256": "61f8eebe0c30cc03b311c6818b2acb158a6d16ca58c8bfac5ebd42db095c2679", + "messageIdentityContract": "copilot-native-message-id-v1", + "ownedDistributionDelivery": "COPILOT_CLI_DIST_DIR:lease-owned-guarded-inner-distribution:v1", + "permissionContextContract": "copilot-edit-permission-context-v1", + "permissionContextSourceSha256": "fe1bb611bea289d81b1c7c973fbb01b93de133a7caa8fe78b7ff4ee1f485b224", + "permissionAdapterSourceSha256": "49421a779c76e286ce65d75052026eab9630b1995af9ccf045a2d43d284633ce", + "permissionLocationsSourceSha256": "f39a81da395b6e23aa2a1a45572a28846e5e81bfd3d764d9a456f74a79c752e9", + "permissionRedactionSourceSha256": "687270d7bbe3dccce6c2fed8664e76cda724b43e545cb153b9f54b018de52927", + "permissionClassifierSourceSha256": "1161eabd82e26133e3b3db3ab567f65d52808b03f176e93497e02c8330349fb4", + "permissionIdentitySourceSha256": "770b47305e571a81f344883057d0e4a482a1cd59ac77d045836593a8e739deb1", + "semanticToolReceiptContract": "paperclip.semantic_tool_receipt.v2", + "semanticReceiptSourceSha256": "b2795726b2234a663fec1a6ca11f0551ae69882fe9e82aa39686e952d036e791", + "semanticBridgeSourceSha256": "8a43ebafb7a85dd1714ed6945670472666dcb63e8af32b4a74644163fa0e370d", + "toolEvidenceSourceSha256": "4b517eed447615b3cc820af348ccc360978175149caa0bbc838d1f78332abe75", + "semanticNormalizedInputContract": "validated-forwarded-input-commit-v1", + "semanticSidecarSourceSha256": "b83898b2453d0f425275d3bc58140675fc8f14505703103079094093f16be43f", + "semanticDirectDriverSourceSha256": "2db465e56ba41f06b406e039e566d9e3aea0a014fc6a47a6a54d5bc682dabcab", + "semanticValidationSourceSha256": "039fca52266fe21ba74ca64660d21228314d8ed737b19ba67941bfb25086e4d5", + "semanticNormalizationSourceSha256": "b1ce59251bf9c671f66e0e5173646190b9a2d1bfc5bdb7fb123824213986b92b", + "semanticCompletionContractSourceSha256": "00a684f9aea87f68eabf0974681c52461bc308631a1252a89c4ed087d7158b28", + "semanticValidatorsSourceSha256": "950b49b233d8dd62ff858398becfc55f0a181160cb8a434d9221b5c17816867c", + "semanticSchemaBundleSourceSha256": "2974c75590f816fbdbc7806f531698fdc8d62a99601a17625b81de0f074d6383", + "semanticSidecarProtocolSourceSha256": "72d9800603a652d6580084bb3b5dac4d4dd6d644324b0d15d293d7c198fd6b55", + "semanticSidecarReceiptCommitContract": "correlated-tool-resolve-v1" + } +}