From 83841aecf6c4877a476db078cb71c4ba3fdbcc39 Mon Sep 17 00:00:00 2001 From: Dotta Date: Thu, 8 Oct 2026 07:35:26 -0500 Subject: [PATCH] Add GitHub Copilot 1.0.88 runtime on current master Reviewed partition of the current-master Copilot integration. Complete v30 live qualification is retained; current v31 recovery compatibility, CI and review are tracked explicitly. Co-Authored-By: Paperclip --- packages/paperclip-runner/acpx-profiles.json | 7 +- packages/paperclip-runner/package.json | 20 +- .../runner-core/src/acpx_provider_backend.rs | 309 +++++++++++++++++- .../src/acpx_provider_capabilities.rs | 8 +- .../runner-core/src/acpx_sidecar_transport.rs | 1 + .../runner-core/src/bin/fake-acpx-sidecar.rs | 33 ++ .../src/generated_acpx_profiles.rs | 2 +- .../tests/native_provider_backend.rs | 103 ++++++ .../scripts/build-copilot-distribution.mjs | 99 ++++++ .../build-copilot-distribution.test.mjs | 57 ++++ .../scripts/build-provider-pack.mjs | 23 +- .../scripts/candidate-provider-pack.mjs | 10 +- .../scripts/candidate-provider-pack.test.mjs | 16 +- .../scripts/copilot-inner-distribution.mjs | 86 +++++ .../copilot-inner-distribution.test.mjs | 80 +++++ .../scripts/copilot-profile-identity.mjs | 106 ++++++ .../scripts/copilot-smoke-resources.mjs | 37 +++ .../scripts/copilot-smoke-resources.test.mjs | 43 +++ .../scripts/discover-copilot-acp.mjs | 130 ++++++++ .../scripts/discover-copilot-acp.test.mjs | 40 +++ .../scripts/install-copilot-assets.mjs | 94 ++++++ .../scripts/install-copilot-assets.test.mjs | 99 ++++++ .../scripts/materialize-copilot-binary.mjs | 133 ++++++++ .../materialize-copilot-binary.test.mjs | 121 +++++++ .../scripts/probe-copilot-acp.py | 197 +++++++++++ .../scripts/probe-copilot-acp.test.mjs | 9 + .../scripts/probe-copilot-acp.test.py | 93 ++++++ .../scripts/probe-copilot-tool-policy.mjs | 10 + .../scripts/qualify-copilot-acp.mjs | 199 +++++++++++ .../scripts/qualify-copilot-acp.test.mjs | 102 ++++++ .../scripts/release-provider-pack.mjs | 10 + .../scripts/release-provider-pack.test.mjs | 16 + .../src/backends/codex-native-backend.ts | 9 +- .../backends/harness-driver-backend.test.ts | 6 +- .../src/backends/harness-driver-backend.ts | 6 +- .../backends/native-backend-factory.test.ts | 5 +- .../src/cli/acpx-runtime-sidecar.test.ts | 6 +- .../src/cli/acpx-runtime-sidecar.ts | 10 +- .../src/cli/copilot-metadata-probe.ts | 5 + .../src/cli/eval-session-contract.test.ts | 20 ++ .../src/contracts/harness-driver.ts | 3 +- .../src/contracts/native-execution.test.ts | 47 ++- .../src/contracts/native-execution.ts | 3 + .../src/contracts/native-session-backend.ts | 3 +- .../src/contracts/runtime-context.ts | 6 + .../drivers/acpx/acp-permission-adapter.ts | 9 +- .../drivers/acpx/codex-acpx-driver.test.ts | 30 ++ .../src/drivers/acpx/codex-acpx-driver.ts | 80 +++-- .../drivers/acpx/codex-credentials.test.ts | 39 ++- .../acpx/codex-runtime-adapter.test.ts | 135 ++++++++ .../src/drivers/acpx/codex-runtime-adapter.ts | 75 ++++- .../src/drivers/acpx/copilot-events.ts | 173 ++++++++++ .../drivers/acpx/copilot-extension-adapter.ts | 103 ++++++ .../src/drivers/acpx/copilot-installation.ts | 41 +++ .../acpx/copilot-permission-context.ts | 22 ++ .../src/drivers/acpx/copilot-policy.ts | 165 ++++++++++ .../src/drivers/acpx/copilot-profile.ts | 95 ++++++ .../src/drivers/acpx/copilot-tool-evidence.ts | 201 ++++++++++++ .../src/drivers/acpx/generated-profiles.ts | 5 +- .../acpx/installation-integrity.test.ts | 2 +- .../drivers/acpx/installation-integrity.ts | 52 ++- .../native-distribution-integrity.test.ts | 192 +++++++++++ .../acpx/native-distribution-integrity.ts | 37 ++- .../src/drivers/acpx/profile-activity.ts | 2 + .../acpx/profile-compatibility.test.ts | 15 +- .../src/drivers/acpx/profile-compatibility.ts | 4 +- .../src/drivers/acpx/profile-extensions.ts | 4 + .../src/drivers/acpx/profile-installation.ts | 9 + .../drivers/acpx/provider-assets-root.test.ts | 14 +- .../src/drivers/acpx/provider-assets-root.ts | 8 +- .../src/drivers/acpx/qualified-profiles.ts | 1 + .../src/drivers/acpx/runtime-host.test.ts | 14 +- .../src/drivers/acpx/runtime-host.ts | 26 +- .../src/drivers/acpx/runtime-sandbox.ts | 18 + .../drivers/acpx/single-read-evidence.test.ts | 5 +- .../src/drivers/codex/app-server-transport.ts | 2 + .../codex-app-server-driver.lifecycle.test.ts | 3 +- .../codex/codex-app-server-driver.test.ts | 62 ++++ .../drivers/codex/codex-harness-session.ts | 4 +- .../codex/codex-notification-identity.test.ts | 4 + .../codex/codex-session-notifications.ts | 20 ++ .../codex/codex-thread-normalization.ts | 1 + .../drivers/copilot-metadata-probe.test.ts | 70 ++++ .../src/drivers/copilot-metadata-probe.ts | 160 +++++++++ .../src/drivers/runner-tool-bridge.test.ts | 144 +++++++- .../src/drivers/runner-tool-bridge.ts | 58 +++- .../src/drivers/semantic-tool-receipt.test.ts | 62 ++++ .../src/drivers/semantic-tool-receipt.ts | 83 +++++ packages/paperclip-runner/src/live/index.ts | 3 + .../runnerd-acpx-permission-ordering.test.ts | 4 + .../src/live/runnerd-codex-transport.test.ts | 65 ++++ .../src/live/runnerd-codex-transport.ts | 54 ++- .../src/native-session-runtime.test.ts | 23 +- .../src/native-session-runtime.ts | 8 +- .../test/acpx-codex-package-contract.test.mjs | 7 +- ...ssage-boundaries-package-contract.test.mjs | 58 ++++ .../copilot-live-denial-2026-09-28.json | 124 +++++++ .../copilot-profile-v12-identity.json | 43 +++ .../copilot-profile-v31-identity.json | 81 +++++ 99 files changed, 4986 insertions(+), 155 deletions(-) create mode 100644 packages/paperclip-runner/scripts/build-copilot-distribution.mjs create mode 100644 packages/paperclip-runner/scripts/build-copilot-distribution.test.mjs create mode 100644 packages/paperclip-runner/scripts/copilot-inner-distribution.mjs create mode 100644 packages/paperclip-runner/scripts/copilot-inner-distribution.test.mjs create mode 100644 packages/paperclip-runner/scripts/copilot-profile-identity.mjs create mode 100644 packages/paperclip-runner/scripts/copilot-smoke-resources.mjs create mode 100644 packages/paperclip-runner/scripts/copilot-smoke-resources.test.mjs create mode 100644 packages/paperclip-runner/scripts/discover-copilot-acp.mjs create mode 100644 packages/paperclip-runner/scripts/discover-copilot-acp.test.mjs create mode 100644 packages/paperclip-runner/scripts/install-copilot-assets.mjs create mode 100644 packages/paperclip-runner/scripts/install-copilot-assets.test.mjs create mode 100644 packages/paperclip-runner/scripts/materialize-copilot-binary.mjs create mode 100644 packages/paperclip-runner/scripts/materialize-copilot-binary.test.mjs create mode 100644 packages/paperclip-runner/scripts/probe-copilot-acp.py create mode 100644 packages/paperclip-runner/scripts/probe-copilot-acp.test.mjs create mode 100644 packages/paperclip-runner/scripts/probe-copilot-acp.test.py create mode 100644 packages/paperclip-runner/scripts/probe-copilot-tool-policy.mjs create mode 100644 packages/paperclip-runner/scripts/qualify-copilot-acp.mjs create mode 100644 packages/paperclip-runner/scripts/qualify-copilot-acp.test.mjs create mode 100644 packages/paperclip-runner/src/cli/copilot-metadata-probe.ts create mode 100644 packages/paperclip-runner/src/drivers/acpx/copilot-events.ts create mode 100644 packages/paperclip-runner/src/drivers/acpx/copilot-extension-adapter.ts create mode 100644 packages/paperclip-runner/src/drivers/acpx/copilot-installation.ts create mode 100644 packages/paperclip-runner/src/drivers/acpx/copilot-permission-context.ts create mode 100644 packages/paperclip-runner/src/drivers/acpx/copilot-policy.ts create mode 100644 packages/paperclip-runner/src/drivers/acpx/copilot-profile.ts create mode 100644 packages/paperclip-runner/src/drivers/acpx/copilot-tool-evidence.ts create mode 100644 packages/paperclip-runner/src/drivers/copilot-metadata-probe.test.ts create mode 100644 packages/paperclip-runner/src/drivers/copilot-metadata-probe.ts create mode 100644 packages/paperclip-runner/src/drivers/semantic-tool-receipt.test.ts create mode 100644 packages/paperclip-runner/src/drivers/semantic-tool-receipt.ts create mode 100644 packages/paperclip-runner/test/acpx-message-boundaries-package-contract.test.mjs create mode 100644 packages/paperclip-runner/test/fixtures/copilot-live-denial-2026-09-28.json create mode 100644 packages/paperclip-runner/test/fixtures/copilot-profile-v12-identity.json create mode 100644 packages/paperclip-runner/test/fixtures/copilot-profile-v31-identity.json diff --git a/packages/paperclip-runner/acpx-profiles.json b/packages/paperclip-runner/acpx-profiles.json index 79bab3ea9e9..b2fe9c04fac 100644 --- a/packages/paperclip-runner/acpx-profiles.json +++ b/packages/paperclip-runner/acpx-profiles.json @@ -32,14 +32,13 @@ "requiresProviderPolicy": true }, "copilot": { - "agentProfileVersion": 2, + "agentProfileVersion": 31, "agentServerPackage": "@github/copilot", "agentServerVersion": "1.0.88", "agentRuntimePackage": null, "agentRuntimeVersion": null, - "commandDigest": "sha256:b18c01603dd0169d233140709cfaa8bf5304a03cf5de78ca4f625f30013e8457", - "requiresProviderPolicy": true, - "qualificationStatus": "pending" + "commandDigest": "sha256:4a22e4c50fd213c79cd02fd3c5369aef2256ac719762c62f5b70c691cd47e76b", + "requiresProviderPolicy": true }, "claude": { "agentProfileVersion": 1, diff --git a/packages/paperclip-runner/package.json b/packages/paperclip-runner/package.json index 1e2386242da..a1490831825 100644 --- a/packages/paperclip-runner/package.json +++ b/packages/paperclip-runner/package.json @@ -11,7 +11,8 @@ "paperclip-runner-eval-session": "./dist/cli/eval-session.js", "paperclip-runner-codex-proxy": "./dist/cli/codex-app-server-unix-proxy.js", "paperclip-runner-opencode-proxy": "./dist/cli/opencode-app-server-proxy.js", - "paperclip-runner-acpx-sidecar": "./dist/cli/acpx-runtime-sidecar.js" + "paperclip-runner-acpx-sidecar": "./dist/cli/acpx-runtime-sidecar.js", + "paperclip-runner-copilot-metadata-probe": "./dist/cli/copilot-metadata-probe.js" }, "exports": { ".": { @@ -53,12 +54,15 @@ "dist-issue-thread", "protocol", "styles.css", - "README.md" + "README.md", + "scripts/install-copilot-assets.mjs", + "scripts/materialize-copilot-binary.mjs", + "scripts/copilot-inner-distribution.mjs" ], "sideEffects": false, "scripts": { "build": "pnpm run check:protocol-manifest && pnpm run build:typescript && pnpm run check:capability-contract && pnpm run check:capability-inventory && pnpm run check:protocol-coverage && pnpm run check:semantic-contracts && pnpm run check:runner-workflow-traceability && pnpm run build:binary && node scripts/generate-replay-goldens.mjs --check && node scripts/generate-semantic-action-catalog.mjs --check", - "build:typescript": "pnpm run check:acpx-profiles && pnpm run ensure:eval-build-deps && pnpm run check:protocol-types && node ./node_modules/typescript/bin/tsc --version && node ./node_modules/typescript/bin/tsc -p tsconfig.json && node ./node_modules/typescript/bin/tsc -p tsconfig.surfaces.json && node scripts/build-verified-provider-entrypoints.mjs", + "build:typescript": "pnpm run check:acpx-profiles && pnpm run check:copilot-profile && pnpm run ensure:eval-build-deps && pnpm run check:protocol-types && node ./node_modules/typescript/bin/tsc --version && node ./node_modules/typescript/bin/tsc -p tsconfig.json && node ./node_modules/typescript/bin/tsc -p tsconfig.surfaces.json && node scripts/build-verified-provider-entrypoints.mjs && node scripts/install-copilot-assets.mjs", "build:rust": "cargo build --manifest-path runner/Cargo.toml --locked --workspace --bins", "build:binary": "cargo build --release --manifest-path runner/Cargo.toml --locked -p paperclip-runner-core --bin paperclip-runnerd && node scripts/stage-runner-binary.mjs", "stage:release-binaries": "node scripts/stage-release-runner-binaries.mjs", @@ -75,7 +79,7 @@ "typecheck:browser": "tsc -p tsconfig.browser.json --noEmit", "test": "pnpm run test:typescript && pnpm run test:rust", "test:typescript": "pnpm run test:typescript:prep && vitest run", - "test:typescript:prep": "pnpm run ensure:eval-build-deps && pnpm run build:rust && node --test test/protocol-contract.test.mjs test/acpx-sidecar-contract.test.mjs test/acpx-codex-package-contract.test.mjs test/acpx-model-selection-package-contract.test.mjs test/acpx-rich-extensions-package-contract.test.mjs test/acpx-pi-receipt-package-contract.test.mjs test/acpx-response-delivery-package-contract.test.mjs scripts/candidate-provider-pack.test.mjs scripts/cursor-provisioner-layout.test.mjs scripts/release-provider-pack.test.mjs scripts/aws-agentcore-provisioning.test.mjs scripts/build-verified-provider-entrypoints.test.mjs scripts/local-provider-smoke-environment.test.mjs scripts/materialize-opencode-binary.test.mjs", + "test:typescript:prep": "pnpm run ensure:eval-build-deps && pnpm run build:rust && node --test test/protocol-contract.test.mjs test/acpx-sidecar-contract.test.mjs test/acpx-codex-package-contract.test.mjs test/acpx-model-selection-package-contract.test.mjs test/acpx-rich-extensions-package-contract.test.mjs test/acpx-pi-receipt-package-contract.test.mjs test/acpx-response-delivery-package-contract.test.mjs scripts/candidate-provider-pack.test.mjs scripts/cursor-provisioner-layout.test.mjs scripts/release-provider-pack.test.mjs scripts/aws-agentcore-provisioning.test.mjs scripts/build-verified-provider-entrypoints.test.mjs scripts/local-provider-smoke-environment.test.mjs scripts/materialize-opencode-binary.test.mjs && pnpm run test:copilot:contracts", "test:typescript:vitest": "node ./scripts/run-pr-vitest-lane.mjs", "test:rust": "cargo test --release --manifest-path runner/Cargo.toml --locked --workspace", "test:codex": "cargo test --manifest-path runner/Cargo.toml --locked -p paperclip-runner-core --test codex_provider", @@ -162,6 +166,9 @@ "verify": "pnpm run build && pnpm run typecheck && pnpm run check:replay-goldens && pnpm run test && pnpm run test:sdk && pnpm run test:scenarios && pnpm run check:browser-tokens && pnpm run test:browser && pnpm run test:browser:sdk && pnpm run test:browser:scenarios && pnpm run check:forbidden-imports && pnpm run check:tracked-imports && pnpm run check:numbered-milestones && pnpm run check:package-boundaries && pnpm run check:clean-consumers && pnpm run docs:validate && pnpm run check:conformance-parity && pnpm run check:replay-parity && pnpm run trace:conformance && pnpm run replay:fixture && pnpm run trace:local-runner -- --quiet", "verify:rootless": "bash scripts/verify-rootless-linux.sh", "test:opencode:qualification": "PAPERCLIP_OPENCODE_QUALIFY=1 node --test scripts/qualify-opencode-runtime.test.mjs", + "check:copilot-profile": "node scripts/copilot-profile-identity.mjs --check", + "test:copilot:contracts": "node --test scripts/build-copilot-distribution.test.mjs scripts/copilot-inner-distribution.test.mjs scripts/copilot-smoke-resources.test.mjs scripts/discover-copilot-acp.test.mjs scripts/materialize-copilot-binary.test.mjs scripts/install-copilot-assets.test.mjs scripts/probe-copilot-acp.test.mjs scripts/qualify-copilot-acp.test.mjs test/acpx-message-boundaries-package-contract.test.mjs", + "postinstall": "node scripts/install-copilot-assets.mjs", "generate:acpx-profiles": "node scripts/generate-acpx-profiles.mjs", "check:acpx-profiles": "node scripts/generate-acpx-profiles.mjs --check" }, @@ -203,5 +210,10 @@ "typescript": "^7.0.2", "vite": "^6.1.0", "vitest": "^5.0.3" + }, + "optionalDependencies": { + "@github/copilot-darwin-arm64": "1.0.88", + "@github/copilot-darwin-x64": "1.0.88", + "@github/copilot-linux-x64": "1.0.88" } } 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 b3beb1897a4..8e49e5df23c 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 @@ -1887,6 +1887,12 @@ impl AcpxCommandExecutor { let Some(events) = events else { break }; let mut provider_turn_settled = false; for event in events { + let provider_process_lost = matches!( + &event, + crate::acpx_provider_state::AcpxProviderStateEvent::TurnTerminal { + error: Some(error), .. + } if error.get("code").and_then(Value::as_str) == Some("ACPX_PROVIDER_PROCESS_LOST") + ); let normalized = project_acpx_state_event(&self.context, &event) .map_err(|error| DurableRunnerError::invalid(error.to_string()))?; let terminal = normalized.iter().find_map(|event| { @@ -1896,7 +1902,10 @@ impl AcpxCommandExecutor { ) .then(|| event.event_type.clone()) }); - if terminal.is_some() { + // A failed provider cannot answer session controls. Its + // terminal receipt must remain publishable without another + // protocol request, and must revoke future warm admission. + if terminal.is_some() && !provider_process_lost { let snapshot = self.goal_control("session.goal.get", &json!({}))?; let state = self.state.as_mut().expect("ACPX session has durable state"); for (event_type, priority, payload) in snapshot.events { @@ -1937,10 +1946,12 @@ impl AcpxCommandExecutor { } if let Some(event_type) = terminal { state.active_turn_id = None; - state.lifecycle = if self - .session - .as_ref() - .is_some_and(|session| session.runtime_retired()) + state.provider_exit_unconfirmed |= provider_process_lost; + state.lifecycle = if provider_process_lost + || self + .session + .as_ref() + .is_some_and(|session| session.runtime_retired()) { "closed" } else { @@ -1950,11 +1961,12 @@ impl AcpxCommandExecutor { provider_turn_settled = true; // An ACP goal has session lifetime, not prompt lifetime. // Out-of-prompt goal updates remain observable after quiescence. - if state - .goal_projection - .pointer("/goal/status") - .and_then(Value::as_str) - == Some("active") + if !provider_process_lost + && state + .goal_projection + .pointer("/goal/status") + .and_then(Value::as_str) + == Some("active") { continue; } @@ -3579,6 +3591,283 @@ mod tests { fs::remove_dir_all(directory).unwrap(); } + #[cfg(unix)] + #[test] + fn copilot_attachment_refreshes_current_grant_without_changing_profile() { + let directory = temporary_directory("cross-run-attach"); + let runtime = directory.join("runtime"); + let workspace = directory.join("workspace"); + fs::create_dir_all(&runtime).unwrap(); + fs::create_dir_all(&workspace).unwrap(); + fs::set_permissions(&runtime, fs::Permissions::from_mode(0o700)).unwrap(); + fs::set_permissions(&workspace, fs::Permissions::from_mode(0o700)).unwrap(); + let marker = directory.join("provider-started"); + let command = directory.join("sidecar"); + write_artifact( + &command, + format!("#!/bin/sh\ntouch '{}'\n", marker.display()).as_bytes(), + true, + ); + let launch_profile = AcpxLaunchProfile { + authority_digest: format!("sha256:{}", "d".repeat(64)), + command: command.clone(), + args: Vec::new(), + artifacts: vec![artifact(&command)], + }; + let mut descriptor_value = descriptor("copilot"); + descriptor_value["agentServerPackage"] = json!("@github/copilot"); + descriptor_value["agentServerVersion"] = json!("1.0.88"); + descriptor_value["agentRuntimePackage"] = Value::Null; + descriptor_value["agentRuntimeVersion"] = Value::Null; + descriptor_value["commandDigest"] = serde_json::from_str::(include_str!( + "../../../../test/fixtures/copilot-profile-v31-identity.json" + )) + .unwrap()["commandDigest"] + .clone(); + descriptor_value["providerPolicy"] = json!({ "readOnly": true }); + descriptor_value["sidecarCommand"] = json!(command); + descriptor_value["runtimeContext"] = json!({ "instructions": { "digest": "stable" }, "mcp": { "digest": "before" }, "aggregateDigest": "before" }); + descriptor_value["sidecarArgs"] = json!([]); + descriptor_value["runtimeDirectory"] = json!(runtime); + descriptor_value["cwd"] = json!(workspace); + let prior_root = directory.join("old-registered-copy"); + let current_root = directory.join("new-registered-copy"); + fs::create_dir_all(&prior_root).unwrap(); + fs::create_dir_all(¤t_root).unwrap(); + descriptor_value["instructions"] = json!(format!( + "Current AGENT_HOME: {}. Custom entry.", + prior_root.display() + )); + descriptor_value["runtimeContext"] = json!({ + "aggregateDigest": "a".repeat(64), + "prompt": {"revision": "pinned", "digest": "b".repeat(64)}, + "instructions": { + "entryPath": "AGENTS.md", + "bundle": {"digest": "c".repeat(64), "rootPath": "/old-bundle"}, + "workingCopy": {"kind": "agent_files", "entryPath": "AGENTS.md", "rootPath": prior_root}, + }, + "skills": [{"key": "skill-1", "bundle": {"digest": "d".repeat(64), "rootPath": "/old-skill"}}], + "mcp": {"assignmentSetId": "assignment-1", "digest": "e".repeat(64), "bindingId": "old-run-binding"}, + "futurePolicy": {"companyId": "company-1"}, + }); + let original_descriptor: AcpxProviderDescriptor = + serde_json::from_value(descriptor_value.clone()).unwrap(); + let identity = AcpxProviderSessionIdentity { + kind: "acpx".to_owned(), + normalized_session_id: "session-1".to_owned(), + acpx_record_id: "record-1".to_owned(), + backend_session_id: "backend-1".to_owned(), + agent_session_id: "agent-1".to_owned(), + profile_digest: original_descriptor.command_digest.clone(), + workspace_digest: format!("sha256:{}", "a".repeat(64)), + requested_model: original_descriptor.model.clone(), + effective_model: original_descriptor.model.clone(), + permission_mode: Some(original_descriptor.permission_mode), + mode: original_descriptor.mode.clone(), + provider_lifetime_fence_candidates: [60_001, 60_002, 60_003], + }; + let operations = Vec::new(); + let tool_set = AuthorizedToolSet { + schema: TOOL_SET_SCHEMA.to_owned(), + schema_version: 1, + catalog_digest: authorized_tool_catalog_digest(&operations).unwrap(), + operations, + }; + let launch_profile_digest = launch_profile.canonical_digest().unwrap(); + let mut state = AcpxDurableState::new(original_descriptor, tool_set, launch_profile_digest); + state.lifecycle = "suspended".to_owned(); + state.identity = Some(identity); + let original_config = test_config(&directory, Some(launch_profile.clone())); + let mut original = AcpxCommandExecutor::with_runner_config(&directory, &original_config); + original.state = Some(state); + let settled = original.state.clone().unwrap(); + let ready = original.snapshot().unwrap().result; + assert_eq!(ready["warmAttachReady"], true); + assert_eq!(ready["warmAttachBlockers"], json!([])); + let blocked_states: [(&str, fn(&mut AcpxDurableState)); 4] = [ + ("durable_closed", |state| { + state.lifecycle = "closed".to_owned() + }), + ("provider_exit_unconfirmed", |state| { + state.lifecycle = "prepared".to_owned(); + state.provider_exit_unconfirmed = true; + }), + ("provider_identity_unavailable", |state| { + state.lifecycle = "prepared".to_owned(); + state.identity = None; + }), + ("durable_active_turn", |state| { + state.lifecycle = "turn_active".to_owned(); + state.active_turn_id = Some("turn-1".to_owned()); + }), + ]; + for (blocker, mutate) in blocked_states { + original.state = Some(settled.clone()); + mutate(original.state.as_mut().unwrap()); + let snapshot = original.snapshot().unwrap().result; + assert_eq!(snapshot["warmAttachReady"], false, "{blocker}"); + assert_eq!(snapshot["warmAttachBlockers"], json!([blocker])); + } + // A readiness probe must retain the old authority's audit events until + // the durable runner commits and acknowledges them, including recovery + // notices that run.attach itself is allowed to consume. + for event_type in ["session.resumed", "harness.diagnostic"] { + original.state = Some(settled.clone()); + original + .state + .as_mut() + .unwrap() + .push(NormalizedProviderEvent { + event_type: event_type.to_owned(), + priority: EventPriority::P0, + payload: json!({}), + }) + .unwrap(); + let snapshot = original.snapshot().unwrap().result; + assert_eq!(snapshot["warmAttachReady"], false); + assert_eq!( + snapshot["warmAttachBlockers"], + json!(["durable_pending_events"]) + ); + assert_eq!(original.retained_events().unwrap().len(), 1); + original.acknowledge_events(1).unwrap(); + assert_eq!(original.snapshot().unwrap().result["warmAttachReady"], true); + } + original.state = Some(settled); + assert!(!marker.exists(), "readiness must not start a provider"); + original.save_state().unwrap(); + + let mut wrong_session_config = original_config.clone(); + wrong_session_config.run_id = "run-2".to_owned(); + wrong_session_config.normalized_session_id = "session-2".to_owned(); + let mut wrong_session = + AcpxCommandExecutor::with_runner_config(&directory, &wrong_session_config); + assert!(wrong_session.restore().is_err()); + + let mut attached_config = original_config.clone(); + attached_config.run_id = "run-2".to_owned(); + let mut attached = AcpxCommandExecutor::with_runner_config(&directory, &attached_config); + attached.restore().unwrap(); + assert!(!marker.exists()); + let non_attach_error = attached + .execute(&Command { + schema: "paperclip.prp.command.v1".to_owned(), + command_id: "command-before-attach".to_owned(), + controller_seq: 1, + command_type: "session.snapshot".to_owned(), + issued_at: "2026-09-01T00:00:00.000Z".to_owned(), + deadline_at: None, + precondition: None, + payload: json!({}), + }) + .unwrap_err(); + assert!(non_attach_error + .to_string() + .contains("requires run.attach before commands from a new run")); + + descriptor_value["runId"] = json!("run-2"); + fs::remove_dir_all(&prior_root).unwrap(); + descriptor_value["instructions"] = json!(format!( + "Current AGENT_HOME: {}. Fresh custom entry.", + current_root.display() + )); + descriptor_value["runtimeContext"]["instructions"]["workingCopy"]["rootPath"] = + json!(current_root); + descriptor_value["runtimeContext"]["instructions"]["bundle"]["rootPath"] = + json!("/new-bundle"); + descriptor_value["runtimeContext"]["skills"][0]["bundle"]["rootPath"] = json!("/new-skill"); + descriptor_value["runtimeContext"]["mcp"]["bindingId"] = json!("new-run-binding"); + attached + .attach_run(&json!({"provider": descriptor_value})) + .unwrap(); + assert_eq!(attached.state.as_ref().unwrap().descriptor.run_id, "run-2"); + assert!(!marker.exists()); + let refreshed = &attached.state.as_ref().unwrap().descriptor; + assert_eq!( + refreshed.runtime_context, + descriptor_value["runtimeContext"] + ); + assert_eq!(refreshed.instructions, descriptor_value["instructions"]); + let session_config = refreshed + .session_config( + attached.state.as_ref().unwrap().tool_set.clone(), + attached.state.as_ref().unwrap().identity.clone(), + Some(&launch_profile), + ) + .unwrap(); + assert_eq!( + session_config.runtime_context, + descriptor_value["runtimeContext"] + ); + assert_eq!( + session_config.system_instructions, + descriptor_value["instructions"] + ); + // Both persistence and the sidecar launch config receive the new grant. + let persisted: AcpxDurableState = + serde_json::from_slice(&fs::read(attached.state_path()).unwrap()).unwrap(); + assert_eq!( + persisted.descriptor.runtime_context, + descriptor_value["runtimeContext"] + ); + let mut same_run_mutation = descriptor_value.clone(); + same_run_mutation["instructions"] = json!("A different grant in the same run"); + assert!(attached + .attach_run(&json!({"provider": same_run_mutation})) + .unwrap_err() + .to_string() + .contains("new authenticated run")); + + // In-place warm handoff executes under the old authority. Only the + // authenticated next-authority boundary may admit the new descriptor; + // event correlation stays on run-1 until durable activation completes. + assert!(original + .attach_run(&json!({"provider": descriptor_value})) + .is_err()); + let warm_payload = json!({ + "provider": descriptor_value, + "paperclipNextAuthority": { + "identity": { + "runnerInstanceId": original_config.runner_instance_id, + "environmentLeaseId": original_config.environment_lease_id, + "runId": "run-2", + "normalizedSessionId": original_config.normalized_session_id, + "turnId": "turn-2", + "itemId": "item-2", + }, + "connection": {"mode": "connect", "connectUrl": original_config.connect_url}, + }, + }); + let mut wrong_run = warm_payload.clone(); + wrong_run["paperclipNextAuthority"]["identity"]["runId"] = json!("run-3"); + assert!(original.attach_run(&wrong_run).is_err()); + let mut wrong_session = warm_payload.clone(); + wrong_session["paperclipNextAuthority"]["identity"]["normalizedSessionId"] = + json!("other-session"); + assert!(original.attach_run(&wrong_session).is_err()); + let mut changed_profile = warm_payload.clone(); + changed_profile["provider"]["cwd"] = json!("/different-workspace"); + assert!(original.attach_run(&changed_profile).is_err()); + let mut refreshed = warm_payload.clone(); + refreshed["provider"]["runtimeContext"]["mcp"] = json!({ "digest": "after" }); + refreshed["provider"]["runtimeContext"]["aggregateDigest"] = json!("after"); + let mut changed_context = refreshed.clone(); + changed_context["provider"]["runtimeContext"]["instructions"] = + json!({ "digest": "changed" }); + assert!(original.attach_run(&changed_context).is_err()); + original.attach_run(&refreshed).unwrap(); + assert_eq!( + original.state.as_ref().unwrap().descriptor.runtime_context["mcp"]["digest"], + "after" + ); + assert_eq!(original.state.as_ref().unwrap().descriptor.run_id, "run-2"); + assert_eq!(original.context.run_id, "run-1"); + original.rotate_authority(&attached_config); + assert_eq!(original.context.run_id, "run-2"); + assert!(!marker.exists()); + fs::remove_dir_all(directory).unwrap(); + } + #[cfg(unix)] #[test] fn active_turn_recovery_closes_without_starting_the_provider() { diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/acpx_provider_capabilities.rs b/packages/paperclip-runner/runner/crates/runner-core/src/acpx_provider_capabilities.rs index 830e31b1fe3..8b627d35650 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/acpx_provider_capabilities.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/acpx_provider_capabilities.rs @@ -11,7 +11,7 @@ pub(crate) enum RunAttachmentPolicy { pub(crate) fn run_attachment_policy(agent: &str) -> RunAttachmentPolicy { match agent { - "cursor" => RunAttachmentPolicy::AuthenticatedRunGrants, + "cursor" | "copilot" => RunAttachmentPolicy::AuthenticatedRunGrants, "claude" => RunAttachmentPolicy::AuthenticatedAssetPaths, _ => RunAttachmentPolicy::ImmutableInstructions, } @@ -27,11 +27,15 @@ mod tests { run_attachment_policy("cursor"), RunAttachmentPolicy::AuthenticatedRunGrants ); + assert_eq!( + run_attachment_policy("copilot"), + RunAttachmentPolicy::AuthenticatedRunGrants + ); assert_eq!( run_attachment_policy("claude"), RunAttachmentPolicy::AuthenticatedAssetPaths ); - for agent in ["codex", "grok", "pi", "copilot", "unknown"] { + for agent in ["codex", "grok", "pi", "unknown"] { assert_eq!( run_attachment_policy(agent), RunAttachmentPolicy::ImmutableInstructions diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/acpx_sidecar_transport.rs b/packages/paperclip-runner/runner/crates/runner-core/src/acpx_sidecar_transport.rs index a9f7862bfb5..7c706b5dd8e 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/acpx_sidecar_transport.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/acpx_sidecar_transport.rs @@ -725,6 +725,7 @@ fn response_error_classification(error: &ResponseError) -> &'static str { "ACPX_TOOL_CALL_STALE" => return "provider_tool_call_retired", "AUTH_REQUIRED" => return "authentication_required", "COPILOT_AUTH_REQUIRED" => return "authentication_required", + "COPILOT_INSTALLATION_INVALID" => return "agent_installation_invalid", "COPILOT_POLICY_VIOLATION" => return "copilot_policy_violation", "COPILOT_DETACHED_WORK_UNSUPPORTED" => return "copilot_detached_work_unsupported", "COPILOT_ENTITLEMENT_DENIED" => return "provider_entitlement_denied", 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 b351e34d8e1..bef6c550e39 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 @@ -44,6 +44,7 @@ fn run() -> Result<(), Box> { let mut stdout = io::stdout().lock(); let mut next_sequence = 1_u64; let mut goal = Value::Null; + let mut provider_lost = false; let mut session_identity = Value::Null; for line in stdin.lock().lines() { let request: Value = serde_json::from_str(&line?)?; @@ -55,6 +56,16 @@ fn run() -> Result<(), Box> { .get("command") .and_then(Value::as_str) .ok_or("request command is missing")?; + if mode == "turns-provider-death" && provider_lost && command == "session.goal.get" { + write_json( + &mut stdout, + &json!({ + "protocolVersion":GENERATED_ACPX_SIDECAR_PROTOCOL_VERSION, + "id":id,"ok":false,"error":{"message":"provider has exited"} + }), + )?; + continue; + } if let Some(journal) = admission_journal.as_mut() { write_json(journal, &json!({"request":request}))?; let response = if command == "tool.resolve" { @@ -290,6 +301,7 @@ fn run() -> Result<(), Box> { | "turns-mismatched-reserved-result-terminal" | "turns-unauthorized-tool" | "turns-permission" + | "turns-provider-death" | "permissions-forged-origin" | "turns-retired" | "turns-retired-terminal-first" @@ -345,6 +357,27 @@ fn run() -> Result<(), Box> { .map(|suffix| format!("call-{suffix}")) .unwrap_or_else(|| "call-1".to_owned()) }; + if command == "turn.start" && mode == "turns-provider-death" { + write_turn_event( + &mut stdout, + next_sequence, + "runtime.permission_requested", + "run-1", + turn_id, + json!({"requestId":"dead-input","kind":"edit","title":"Write the file?","choices":[{"key":"accept","label":"Allow once"},{"key":"cancel","label":"Deny"}]}), + )?; + next_sequence += 1; + provider_lost = true; + write_turn_event( + &mut stdout, + next_sequence, + "runtime.turn_terminal", + "run-1", + turn_id, + json!({"status":"failed","error":{"code":"ACPX_PROVIDER_PROCESS_LOST","message":"provider has exited","retryable":false}}), + )?; + next_sequence += 1; + } if command == "turn.start" && matches!(mode, "turns" | "turns-wrong-scope") { write_turn_event( &mut stdout, diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/generated_acpx_profiles.rs b/packages/paperclip-runner/runner/crates/runner-core/src/generated_acpx_profiles.rs index 1da99fcaad7..ebd275e8f27 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/generated_acpx_profiles.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/generated_acpx_profiles.rs @@ -47,7 +47,7 @@ pub(crate) fn acpx_release_profile(agent: &str) -> Option { agent_runtime_package: None, agent_runtime_version: None, command_digest: - "sha256:b18c01603dd0169d233140709cfaa8bf5304a03cf5de78ca4f625f30013e8457", + "sha256:4a22e4c50fd213c79cd02fd3c5369aef2256ac719762c62f5b70c691cd47e76b", requires_provider_policy: true, }, "claude" => AcpxReleaseProfile { diff --git a/packages/paperclip-runner/runner/crates/runner-core/tests/native_provider_backend.rs b/packages/paperclip-runner/runner/crates/runner-core/tests/native_provider_backend.rs index b30c56523fb..f3def3d46d2 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/tests/native_provider_backend.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/tests/native_provider_backend.rs @@ -1022,6 +1022,109 @@ fn routes_reserved_completion_feedback_with_the_full_controller_catalog() { fs::remove_dir_all(directory).unwrap(); } +#[test] +fn provider_death_expires_input_and_commits_failure_without_querying_the_dead_provider() { + let directory = temporary_directory("acpx-provider-death"); + let mode = "turns-provider-death"; + let mut config = acpx_config(&directory, mode); + let mut payload = prepare_payload_with_mode(&directory, "codex", mode); + let identity: Value = serde_json::from_str(include_str!( + "../../../../test/fixtures/copilot-profile-v31-identity.json" + )) + .unwrap(); + let digest = identity["commandDigest"].as_str().unwrap(); + *config + .acpx_launch_profile + .as_mut() + .unwrap() + .args + .last_mut() + .unwrap() = digest.to_owned(); + let provider = &mut payload["provider"]; + provider["agent"] = json!("copilot"); + provider["model"] = json!("gpt-5.6-luna"); + provider["permissionMode"] = json!("approve-paperclip"); + provider["agentServerPackage"] = json!("@github/copilot"); + provider["agentServerVersion"] = json!("1.0.88"); + provider["agentRuntimePackage"] = Value::Null; + provider["agentRuntimeVersion"] = Value::Null; + provider["providerPolicy"] = json!({"readOnly":false}); + provider["commandDigest"] = json!(digest); + provider["sidecarArgs"][3] = json!(digest); + let mut executor = NativeProviderCommandExecutor::with_runner_config(&directory, &config); + executor + .execute(&command(1, "run.prepare", payload)) + .unwrap(); + executor + .execute(&command(2, "session.open", json!({}))) + .unwrap(); + executor + .execute(&command( + 3, + "turn.start", + json!({"text":"Write", "turnId":"provider-turn-dead"}), + )) + .unwrap(); + let mut events = Vec::new(); + for _ in 0..20 { + let batch = executor.poll_events().unwrap(); + executor.acknowledge_events(batch.len()).unwrap(); + events.extend(batch); + if events + .iter() + .any(|event| event.event_type == "run.terminal") + { + break; + } + std::thread::sleep(Duration::from_millis(5)); + } + let expired = events + .iter() + .position(|event| event.event_type == "runtime_request.expired") + .unwrap_or_else(|| panic!("provider death did not expire input: {events:?}")); + let failed = events + .iter() + .position(|event| event.event_type == "turn.failed") + .unwrap(); + assert!(expired < failed); + assert_eq!(events[expired].payload["reason"], "provider_process_lost"); + assert_eq!(events[expired].payload["replayAllowed"], false); + assert_eq!( + events[failed].payload["providerTurnId"], + "provider-turn-dead" + ); + assert_eq!( + events[failed].payload["error"]["code"], + "ACPX_PROVIDER_PROCESS_LOST" + ); + assert_eq!( + events + .iter() + .filter(|event| event.event_type == "turn.failed") + .count(), + 1 + ); + let snapshot = executor + .execute(&command(4, "session.snapshot", json!({}))) + .unwrap() + .result; + assert_eq!(snapshot["status"], "closed"); + assert_eq!(snapshot["activeProviderTurnId"], Value::Null); + assert_eq!(snapshot["warmAttachReady"], false); + assert!(executor + .execute(&command( + 5, + "turn.start", + json!({"text":"Replay", "turnId":"replay-turn"}) + )) + .is_err()); + executor + .execute(&command(6, "session.close", json!({}))) + .unwrap(); + executor.shutdown().unwrap(); + fs::remove_dir_all(directory).unwrap(); +} + #[test] fn resumes_an_idle_acpx_session_in_a_cold_replacement_runner() { let directory = temporary_directory("acpx-cold-idle-recovery"); diff --git a/packages/paperclip-runner/scripts/build-copilot-distribution.mjs b/packages/paperclip-runner/scripts/build-copilot-distribution.mjs new file mode 100644 index 00000000000..755322db5b7 --- /dev/null +++ b/packages/paperclip-runner/scripts/build-copilot-distribution.mjs @@ -0,0 +1,99 @@ +import { createHash, timingSafeEqual } from "node:crypto"; +import { lstat, mkdir, mkdtemp, realpath, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { isAbsolute, join, resolve } from "node:path"; +import { gunzipSync } from "node:zlib"; +import { COPILOT_VERSION, materializePinnedCopilotBinary, resolveCopilotDistribution } from "./materialize-copilot-binary.mjs"; + +const MAX_ARCHIVE_BYTES = 128 * 1024 * 1024; +const MAX_EXPANDED_BYTES = 384 * 1024 * 1024; +const PROFILE_DIGEST = "sha256:4a22e4c50fd213c79cd02fd3c5369aef2256ac719762c62f5b70c691cd47e76b"; + +/** 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 } = {}) { + if (typeof outputRoot !== "string" || !isAbsolute(outputRoot) || resolve(outputRoot) !== outputRoot || outputRoot.includes("\0")) { + throw new Error("Copilot outputRoot must be a normalized absolute build directory"); + } + const distribution = resolveCopilotDistribution(platform, architecture); + const packageBasename = distribution.packageName.slice("@github/".length); + const archiveUrl = `https://registry.npmjs.org/${distribution.packageName}/-/${packageBasename}-${COPILOT_VERSION}.tgz`; + const response = await fetchImpl(archiveUrl, { redirect: "error", credentials: "omit", signal: AbortSignal.timeout(120_000) }); + if (!response.ok || !response.body) throw new Error(`Pinned Copilot archive download failed (${response.status})`); + const advertisedLength = response.headers.get("content-length"); + if (advertisedLength !== null && (!/^\d+$/.test(advertisedLength) || Number(advertisedLength) > MAX_ARCHIVE_BYTES)) { + await response.body.cancel(); throw new Error("Pinned Copilot archive exceeds its download bound"); + } + const chunks = []; let total = 0; + for await (const chunk of response.body) { + total += chunk.length; + if (total > MAX_ARCHIVE_BYTES) throw new Error("Pinned Copilot archive exceeds its download bound"); + chunks.push(chunk); + } + const archive = Buffer.concat(chunks, total); + verifyCopilotArchiveIntegrity(archive, distribution.archiveIntegrity); + const entries = readCopilotArchiveEntries(gunzipSync(archive, { maxOutputLength: MAX_EXPANDED_BYTES })); + const metadata = JSON.parse(entries.get("package/package.json").toString("utf8")); + if (metadata.name !== distribution.packageName || metadata.version !== COPILOT_VERSION) throw new Error("Copilot archive package identity differs from its immutable profile"); + const binary = entries.get("package/copilot"); + if (binary.length !== distribution.size || createHash("sha256").update(binary).digest("hex") !== distribution.executableDigest) { + throw new Error("Copilot archive executable differs from its pinned distribution"); + } + // Never extract archive paths. Only the two admitted files enter this private + // temporary package, and no package scripts or executables are invoked. + const temporary = await mkdtemp(join(tmpdir(), "paperclip-copilot-build-")); + try { + await writeFile(join(temporary, "package.json"), entries.get("package/package.json"), { flag: "wx", mode: 0o600 }); + await writeFile(join(temporary, "copilot"), binary, { flag: "wx", mode: 0o700 }); + await mkdir(outputRoot, { recursive: true, mode: 0o755 }); + if (!(await lstat(outputRoot)).isDirectory() || await realpath(outputRoot) !== outputRoot) throw new Error("Copilot build directory must not redirect through links"); + const materialized = materializePinnedCopilotBinary({ packageRoot: temporary, targetDirectory: outputRoot, platform, architecture }); + return { version: COPILOT_VERSION, profileDigest: PROFILE_DIGEST, closureDigest: `sha256:${materialized.closureSha256}` }; + } finally { await rm(temporary, { recursive: true, force: true }); } +} + +export function verifyCopilotArchiveIntegrity(bytes, integrity) { + if (!/^sha512-[A-Za-z0-9+/]{86}==$/.test(integrity)) throw new Error("Copilot archive integrity pin is malformed"); + const expected = Buffer.from(integrity.slice(7), "base64"); + if (!timingSafeEqual(createHash("sha512").update(bytes).digest(), expected)) throw new Error("Copilot archive SHA-512 integrity mismatch"); +} + +/** Strict npm tar subset: no links, traversal, PAX overrides, duplicates or hidden trailers. */ +export function readCopilotArchiveEntries(tar) { + if (!Buffer.isBuffer(tar) || tar.length < 1024 || tar.length > MAX_EXPANDED_BYTES || tar.length % 512 !== 0) throw new Error("Copilot tar archive has invalid framing"); + const permitted = new Set(["package/copilot", "package/package.json", "package/LICENSE.md", "package/README.md"]); + const entries = new Map(); let offset = 0; let ended = false; + const field = (header, start, end) => { + const bytes = header.subarray(start, end); const nul = bytes.indexOf(0); + if (nul >= 0 && bytes.subarray(nul).some(byte => byte !== 0)) throw new Error("Copilot tar field contains hidden bytes"); + return bytes.subarray(0, nul < 0 ? undefined : nul).toString("ascii"); + }; + const octal = (header, start, end) => { + const value = header.subarray(start, end).toString("ascii").replace(/\0/g, "").trim(); + if (!/^[0-7]+$/.test(value)) throw new Error("Copilot tar numeric field is malformed"); + const parsed = Number.parseInt(value, 8); + if (!Number.isSafeInteger(parsed)) throw new Error("Copilot tar numeric field exceeds its bound"); + return parsed; + }; + while (offset + 512 <= tar.length) { + const header = tar.subarray(offset, offset + 512); offset += 512; + if (header.every(byte => byte === 0)) { + if (offset + 512 > tar.length || tar.subarray(offset).some(byte => byte !== 0)) throw new Error("Copilot tar archive has a hidden or truncated trailer"); + ended = true; break; + } + const checksum = header.reduce((sum, byte, index) => sum + (index >= 148 && index < 156 ? 32 : byte), 0); + if (checksum !== octal(header, 148, 156)) throw new Error("Copilot tar header checksum mismatch"); + const name = field(header, 0, 100); + const size = octal(header, 124, 136); + if (!permitted.has(name) || entries.has(name) || field(header, 345, 500) !== "" || field(header, 157, 257) !== "" + || header[156] !== 48 || field(header, 257, 263) !== "ustar" || header.subarray(263, 265).toString("ascii") !== "00") { + throw new Error("Copilot tar archive contains an unrecognized or unsafe entry"); + } + if (size < 1 || size > (name === "package/copilot" ? MAX_EXPANDED_BYTES : 256 * 1024) || offset + size > tar.length) throw new Error("Copilot tar entry exceeds its bounded payload"); + const paddedSize = Math.ceil(size / 512) * 512; + if (offset + paddedSize > tar.length || tar.subarray(offset + size, offset + paddedSize).some(byte => byte !== 0)) throw new Error("Copilot tar entry has invalid padding"); + entries.set(name, tar.subarray(offset, offset + size)); + offset += paddedSize; + } + if (!ended || entries.size !== permitted.size) throw new Error("Copilot tar archive is incomplete"); + return entries; +} diff --git a/packages/paperclip-runner/scripts/build-copilot-distribution.test.mjs b/packages/paperclip-runner/scripts/build-copilot-distribution.test.mjs new file mode 100644 index 00000000000..5607b6469f1 --- /dev/null +++ b/packages/paperclip-runner/scripts/build-copilot-distribution.test.mjs @@ -0,0 +1,57 @@ +import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; +import { test } from "node:test"; +import { buildPinnedCopilotDistribution, readCopilotArchiveEntries, verifyCopilotArchiveIntegrity } from "./build-copilot-distribution.mjs"; + +function header(name, body, type = "0") { + const block = Buffer.alloc(512); block.write(name, 0, 100, "ascii"); + block.write("0000755\0", 100); block.write(body.length.toString(8).padStart(11, "0") + "\0", 124); + block.fill(32, 148, 156); block.write(type, 156); block.write("ustar\0", 257); block.write("00", 263); + block.write(block.reduce((sum, byte) => sum + byte, 0).toString(8).padStart(6, "0") + "\0 ", 148); + return Buffer.concat([block, body, Buffer.alloc((512 - body.length % 512) % 512)]); +} +function archive(replace = {}) { + const entries = ["package/copilot", "package/package.json", "package/LICENSE.md", "package/README.md"]; + return Buffer.concat([...entries.map(name => header(name === "package/copilot" ? replace.name ?? name : name, + Buffer.from(name === "package/copilot" ? "binary" : "data"), name === "package/copilot" ? replace.type ?? "0" : "0")), Buffer.alloc(1024)]); +} + +test("strict archive reader admits only complete pinned npm entry shape", () => { + const entries = readCopilotArchiveEntries(archive()); + assert.equal(entries.get("package/copilot").toString(), "binary"); + for (const invalid of [archive({ name: "../../copilot" }), archive({ type: "2" }), archive({ type: "x" }), + archive({ name: "package/package.json" }), archive().subarray(0, -512), Buffer.concat([archive(), Buffer.from("hidden")])]) { + assert.throws(() => readCopilotArchiveEntries(invalid)); + } + const changed = archive(); changed[20] ^= 1; + assert.throws(() => readCopilotArchiveEntries(changed), /checksum/); + const padding = archive(); padding[512 + 6] = 1; + assert.throws(() => readCopilotArchiveEntries(padding), /padding/); +}); + +test("SHA-512 archive verification rejects corruption and malformed pins", () => { + const bytes = Buffer.from("pinned archive"); const pin = `sha512-${createHash("sha512").update(bytes).digest("base64")}`; + verifyCopilotArchiveIntegrity(bytes, pin); + assert.throws(() => verifyCopilotArchiveIntegrity(Buffer.from("tampered"), pin), /mismatch/); + assert.throws(() => verifyCopilotArchiveIntegrity(bytes, "sha512-invalid"), /malformed/); +}); + +test("builder uses only exact pinned registry URL and refuses a corrupt download before writes", async () => { + let called = false; + await assert.rejects(buildPinnedCopilotDistribution({ outputRoot: "/unused-copilot-build", platform: "linux", architecture: "x64" }, { + fetchImpl: async (url, options) => { + called = true; + assert.equal(url, "https://registry.npmjs.org/@github/copilot-linux-x64/-/copilot-linux-x64-1.0.88.tgz"); + assert.equal(options.redirect, "error"); assert.equal(options.credentials, "omit"); + return new Response("corrupt"); + }, + }), /integrity mismatch/); + assert.equal(called, true); + await assert.rejects(buildPinnedCopilotDistribution({ outputRoot: "relative", platform: "linux", architecture: "x64" }), /normalized absolute/); +}); + +test("builder bounds download metadata before streaming", async () => { + await assert.rejects(buildPinnedCopilotDistribution({ outputRoot: "/unused-copilot-build", platform: "linux", architecture: "x64" }, { + fetchImpl: async () => new Response("small", { headers: { "content-length": String(129 * 1024 * 1024) } }), + }), /download bound/); +}); diff --git a/packages/paperclip-runner/scripts/build-provider-pack.mjs b/packages/paperclip-runner/scripts/build-provider-pack.mjs index d6a09822484..aa47e5feb78 100644 --- a/packages/paperclip-runner/scripts/build-provider-pack.mjs +++ b/packages/paperclip-runner/scripts/build-provider-pack.mjs @@ -166,7 +166,15 @@ try { mkdirSync(dirname(stableNodeCommand), { recursive: true, mode: 0o755 }); copyFileSync(process.execPath, stableNodeCommand); chmodSync(stableNodeCommand, 0o755); - const relocatedNode = spawnSync(stableNodeCommand, ["--version"], { + // A freshly copied x64 Mach-O can stall when launched directly from a + // translated Node process. Select Rosetta explicitly for this build probe; + // native Intel and every other platform still execute the copied bytes directly. + const translated = process.platform === "darwin" && process.arch === "x64" + && spawnSync("/usr/sbin/sysctl", ["-n", "sysctl.proc_translated"], { + encoding: "utf8", timeout: 1_000, + }).stdout?.trim() === "1"; + const relocatedNode = spawnSync(translated ? "/usr/bin/arch" : stableNodeCommand, + translated ? ["-x86_64", stableNodeCommand, "--version"] : ["--version"], { cwd: temporaryRoot, env: { PATH: "/usr/bin:/bin" }, encoding: "utf8", timeout: buildNodeStartupTimeout(), }); if (relocatedNode.status !== 0 || relocatedNode.stdout.trim() !== `v${process.versions.node}`) { @@ -181,7 +189,7 @@ try { || !/^sha256:[a-f0-9]{64}$/.test(metadata.profileDigest) || !/^sha256:[a-f0-9]{64}$/.test(metadata.closureDigest)) throw new Error("Candidate builder omitted its pinned identity"); candidateProviders[provider] = { version: metadata.version, profileDigest: metadata.profileDigest, - closureDigest: metadata.closureDigest, qualification: provider === "cursor" ? "qualified" : "pending", path: assetPath, + closureDigest: metadata.closureDigest, qualification: ["cursor", "copilot"].includes(provider) ? "qualified" : "pending", path: assetPath, sha256: sha256Tree(join(temporaryRoot, assetPath)) }; } @@ -209,6 +217,17 @@ try { ); writePortableExecutableShim("node", "node/bin/node"); writePortableExecutableShim("opencode", "opencode-ai/bin/opencode.exe"); + // Optional Copilot platform packages expose native .bin entries too. Make + // each installed entry portable without executing it during the build. + for (const platform of ["darwin-arm64", "darwin-x64", "linux-x64"]) { + const name = `copilot-${platform}`; + if (!existsSync(join(temporaryRoot, "node_modules", ".bin", name))) continue; + const executable = packRequire.resolve(`@github/${name}`); + writePortableExecutableShim( + name, + relative(realpathSync(join(temporaryRoot, "node_modules")), realpathSync(executable)), + ); + } writePortableNodeShim("acpx", "acpx/dist/cli.js"); writePortableNodeShim( "claude-agent-acp", diff --git a/packages/paperclip-runner/scripts/candidate-provider-pack.mjs b/packages/paperclip-runner/scripts/candidate-provider-pack.mjs index 70aee7f19f6..5f7a89c52bb 100644 --- a/packages/paperclip-runner/scripts/candidate-provider-pack.mjs +++ b/packages/paperclip-runner/scripts/candidate-provider-pack.mjs @@ -5,14 +5,14 @@ const CANDIDATES = new Set(["cursor", "copilot", "pi"]); /** Only materialized providers enter the serialized manifest and its digest. */ export function providerPackManifestFields(providers, candidates) { return { - ...(providers.cursor ? { providers: { cursor: providers.cursor } } : {}), - ...(candidates.length ? { candidateProviders: Object.fromEntries(candidates.map(provider => [provider, providers[provider]])) } : {}), + ...(providers.cursor || providers.copilot ? { providers: { ...(providers.cursor ? { cursor: providers.cursor } : {}), ...(providers.copilot ? { copilot: providers.copilot } : {}) } } : {}), + ...(candidates.length ? { candidateProviders: Object.fromEntries(candidates.filter(provider => provider !== "copilot").map(provider => [provider, providers[provider]])) } : {}), }; } export function providerPackProviders(platform, architecture, candidates) { const cursorSupported = ["darwin-arm64", "darwin-x64", "linux-x64"].includes(`${platform}-${architecture}`); - return [...new Set([...(cursorSupported ? ["cursor"] : []), ...candidates])]; + return [...new Set([...(cursorSupported ? ["cursor", "copilot"] : []), ...candidates])]; } export function parseProviderPackArguments(args) { @@ -33,6 +33,10 @@ export function parseProviderPackArguments(args) { /** Closed source-owned builder registry; provider branches add their exact pins. */ export async function materializeCandidateProviderPack({ provider, outputRoot }) { if (!CANDIDATES.has(provider)) throw new Error("Unknown candidate provider"); + if (provider === "copilot") { + const { buildPinnedCopilotDistribution } = await import("./build-copilot-distribution.mjs"); + return buildPinnedCopilotDistribution({ outputRoot }); + } if (provider === "cursor") { const result = await materializePinnedCursorDistribution({ destination: outputRoot }); return { version: result.version, diff --git a/packages/paperclip-runner/scripts/candidate-provider-pack.test.mjs b/packages/paperclip-runner/scripts/candidate-provider-pack.test.mjs index 88a85c816df..ed2060e168e 100644 --- a/packages/paperclip-runner/scripts/candidate-provider-pack.test.mjs +++ b/packages/paperclip-runner/scripts/candidate-provider-pack.test.mjs @@ -30,10 +30,10 @@ test("candidate selection is explicit", () => { assert.deepEqual(parseProviderPackArguments(["--", "/pack"]), { output: "/pack", candidates: [] }); assert.deepEqual(parseProviderPackArguments(["/pack", "--candidate-providers=pi,cursor"]), { output: "/pack", candidates: ["pi", "cursor"] }); }); -test("normal packs include Cursor on its three pinned targets without breaking other hosts", () => { +test("normal packs include Cursor and Copilot on their three pinned targets without breaking other hosts", () => { for (const [platform, architecture] of [["darwin", "arm64"], ["darwin", "x64"], ["linux", "x64"]]) { - assert.deepEqual(providerPackProviders(platform, architecture, []), ["cursor"]); - assert.deepEqual(providerPackProviders(platform, architecture, ["cursor"]), ["cursor"]); + assert.deepEqual(providerPackProviders(platform, architecture, []), ["cursor", "copilot"]); + assert.deepEqual(providerPackProviders(platform, architecture, ["cursor"]), ["cursor", "copilot"]); } assert.deepEqual(providerPackProviders("linux", "arm64", []), []); assert.deepEqual(providerPackProviders("win32", "x64", []), []); @@ -45,3 +45,13 @@ test("candidate builder cannot admit unknown providers, options or duplicate ass } await assert.rejects(materializeCandidateProviderPack({ provider: "arbitrary", outputRoot: "/tmp/unused" }), /Unknown candidate/); }); + +test("normal Copilot inventory needs no candidate override and has no duplicate candidate", () => { + const copilot = { qualification: "qualified", version: "1.0.88" }; + for (const candidates of [[], ["copilot"]]) { + const fields = providerPackManifestFields({ copilot }, candidates); + assert.equal(fields.providers.copilot, copilot); + assert.equal(fields.candidateProviders?.copilot, undefined); + assert.equal(digest(JSON.parse(JSON.stringify(fields))), digest(fields)); + } +}); diff --git a/packages/paperclip-runner/scripts/copilot-inner-distribution.mjs b/packages/paperclip-runner/scripts/copilot-inner-distribution.mjs new file mode 100644 index 00000000000..4c879711393 --- /dev/null +++ b/packages/paperclip-runner/scripts/copilot-inner-distribution.mjs @@ -0,0 +1,86 @@ +import { createHash } from "node:crypto"; +import { gunzipSync } from "node:zlib"; + +export const COPILOT_APP_SHA256 = "7b48282a19b5b0814a0c96ad5e3a125173d792cc55f9525b2effea962f6063c0"; +export const COPILOT_INNER_DISTRIBUTIONS = Object.freeze({ + "darwin-arm64": Object.freeze({ offset: 92954063, size: 55323492, sha256: "49f5caa0582945a04c5619f8ea81680b1c8c2765888290cf8acf903e2985315b", entries: 230 }), + "darwin-x64": Object.freeze({ offset: 95169991, size: 64572726, sha256: "a4c41f1f480a259db2e4da952d5d2e92d19ae54ae1d6af97143341b6c4918aea", entries: 231 }), + "linux-x64": Object.freeze({ offset: 108781435, size: 60742828, sha256: "c386269ee1bf44bac514da2bb0c6b2a47546631f02e294fc5a8c20d1b1b990ff", entries: 216 }), +}); +export const COPILOT_MESSAGE_MAPPING_ANCHOR = 'case"assistant.message_start":return null;case"assistant.message_delta":return{sessionUpdate:"agent_message_chunk",content:{type:"text",text:e.data.deltaContent}};case"assistant.message":return null;'; +export const COPILOT_MESSAGE_MAPPING_REPLACEMENT = 'case"assistant.message_start":return{sessionUpdate:"agent_message_chunk",messageId:e.data.messageId,content:{type:"text",text:""}};case"assistant.message_delta":return{sessionUpdate:"agent_message_chunk",messageId:e.data.messageId,content:{type:"text",text:e.data.deltaContent}};case"assistant.message":return null;'; +export const COPILOT_REPLAY_MAPPING_ANCHOR = 'case"assistant.message":return t.data.content?{sessionUpdate:"agent_message_chunk",content:{type:"text",text:t.data.content}}:null;'; +export const COPILOT_REPLAY_MAPPING_REPLACEMENT = 'case"assistant.message":return{sessionUpdate:"agent_message_chunk",messageId:t.data.messageId,content:{type:"text",text:t.data.content??""}};'; +const hash = bytes => createHash("sha256").update(bytes).digest("hex"); +const MAX_TAR_BYTES = 256 * 1024 * 1024; + +/** Only called after the complete native executable's independent pin matches. */ +export function readPinnedCopilotInnerDistribution(binary, target) { + const pin = COPILOT_INNER_DISTRIBUTIONS[target]; + if (!pin || !Buffer.isBuffer(binary) || binary.length < pin.offset + pin.size) throw new Error("Copilot inner distribution target or framing is invalid"); + const archive = binary.subarray(pin.offset, pin.offset + pin.size); + if (hash(archive) !== pin.sha256) throw new Error("Copilot embedded archive digest mismatch"); + const entries = readCopilotInnerTar(gunzipSync(archive, { maxOutputLength: MAX_TAR_BYTES })); + if (entries.size !== pin.entries) throw new Error("Copilot embedded archive entry count changed"); + const metadata = JSON.parse(entries.get("package.json")?.bytes.toString("utf8") ?? "null"); + if (metadata?.name !== "@github/copilot" || metadata.version !== "1.0.88" + || !entries.has("index.js") || !entries.has(`prebuilds/${target}/runtime.node`)) throw new Error("Copilot inner distribution identity is invalid"); + const app = entries.get("app.js"); + if (!app) throw new Error("Copilot inner app is missing"); + return new Map([...entries].map(([path, entry]) => [path, path === "app.js" ? { ...entry, bytes: patchPinnedCopilotMessageIdentity(app.bytes) } : entry])); +} + +/** Keep native message identity on the already serialized standard ACP stream. */ +export function patchPinnedCopilotMessageIdentity(bytes) { + if (!Buffer.isBuffer(bytes) || hash(bytes) !== COPILOT_APP_SHA256) throw new Error("Copilot message mapping source digest mismatch"); + let source = bytes.toString("utf8"); + for (const [anchor, replacement] of [[COPILOT_MESSAGE_MAPPING_ANCHOR, COPILOT_MESSAGE_MAPPING_REPLACEMENT], [COPILOT_REPLAY_MAPPING_ANCHOR, COPILOT_REPLAY_MAPPING_REPLACEMENT]]) { + if (source.indexOf(anchor) < 0 || source.indexOf(anchor) !== source.lastIndexOf(anchor)) throw new Error("Copilot message mapping patch anchor is not unique"); + source = source.replace(anchor, replacement); + } + return Buffer.from(source); +} + +/** Closed ustar subset: all pinned inner assets are regular files, with no links. */ +export function readCopilotInnerTar(tar) { + if (!Buffer.isBuffer(tar) || tar.length < 1024 || tar.length > MAX_TAR_BYTES || tar.length % 512) throw new Error("Copilot inner tar framing is invalid"); + const entries = new Map(); let offset = 0; let ended = false; + const field = (header, start, end) => { + const bytes = header.subarray(start, end); const nul = bytes.indexOf(0); + if (nul >= 0 && bytes.subarray(nul).some(byte => byte !== 0)) throw new Error("Copilot inner tar field contains hidden bytes"); + const value = bytes.subarray(0, nul < 0 ? undefined : nul); + if (value.some(byte => byte < 32 || byte > 126)) throw new Error("Copilot inner tar field is not ASCII"); + return value.toString("ascii"); + }; + const octal = (header, start, end) => { + const raw = header.subarray(start, end).toString("ascii"); + if (!/^[0-7]+[\0 ]*$/.test(raw)) throw new Error("Copilot inner tar numeric field is invalid"); + const value = raw.replace(/[\0 ]+$/, ""); + const parsed = Number.parseInt(value, 8); + if (!Number.isSafeInteger(parsed)) throw new Error("Copilot inner tar numeric field exceeds its bound"); + return parsed; + }; + while (offset + 512 <= tar.length) { + const header = tar.subarray(offset, offset + 512); offset += 512; + if (header.every(byte => byte === 0)) { + if (offset + 512 > tar.length || tar.subarray(offset).some(byte => byte !== 0)) throw new Error("Copilot inner tar trailer is invalid"); + ended = true; break; + } + if (header.reduce((sum, byte, index) => sum + (index >= 148 && index < 156 ? 32 : byte), 0) !== octal(header, 148, 156)) throw new Error("Copilot inner tar checksum mismatch"); + const prefix = field(header, 345, 500); const leaf = field(header, 0, 100); + const name = prefix ? `${prefix}/${leaf}` : leaf; + if (!name.startsWith("package/") || name.length > 4096 || name.includes("\\") || name.split("/").some(part => !part || part === "." || part === "..") + || header[156] !== 48 || field(header, 157, 257) || field(header, 257, 263) !== "ustar" || header.subarray(263, 265).toString("ascii") !== "00") throw new Error("Copilot inner tar entry is unsafe or unsupported"); + const path = name.slice(8); const size = octal(header, 124, 136); const mode = octal(header, 100, 108); + if (entries.has(path) || entries.size >= 1000 || size > MAX_TAR_BYTES || mode & ~0o777 || mode & 0o022) throw new Error("Copilot inner tar entry metadata is invalid"); + const padded = Math.ceil(size / 512) * 512; + if (offset + padded > tar.length || tar.subarray(offset + size, offset + padded).some(byte => byte !== 0)) throw new Error("Copilot inner tar entry padding is invalid"); + entries.set(path, { bytes: tar.subarray(offset, offset + size), executable: Boolean(mode & 0o111) }); offset += padded; + } + if (!ended || !entries.size) throw new Error("Copilot inner tar is incomplete"); + // Refuse a file that is also another entry's parent before any write begins. + for (const path of entries.keys()) for (let i = path.indexOf("/"); i >= 0; i = path.indexOf("/", i + 1)) { + if (entries.has(path.slice(0, i))) throw new Error("Copilot inner tar file conflicts with a directory"); + } + return entries; +} diff --git a/packages/paperclip-runner/scripts/copilot-inner-distribution.test.mjs b/packages/paperclip-runner/scripts/copilot-inner-distribution.test.mjs new file mode 100644 index 00000000000..752956aba4f --- /dev/null +++ b/packages/paperclip-runner/scripts/copilot-inner-distribution.test.mjs @@ -0,0 +1,80 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { runInNewContext } from "node:vm"; +import { COPILOT_MESSAGE_MAPPING_REPLACEMENT, COPILOT_REPLAY_MAPPING_REPLACEMENT, patchPinnedCopilotMessageIdentity, readCopilotInnerTar, readPinnedCopilotInnerDistribution } from "./copilot-inner-distribution.mjs"; + +function file(name, content = "data", { type = "0", mode = 0o644, prefix = "" } = {}) { + const bytes = Buffer.from(content); const h = Buffer.alloc(512); + h.write(name, 0, 100, "ascii"); h.write(mode.toString(8).padStart(7, "0") + "\0", 100); + h.write(bytes.length.toString(8).padStart(11, "0") + "\0", 124); + h.fill(32, 148, 156); h.write(type, 156); h.write("ustar\0", 257); h.write("00", 263); h.write(prefix, 345, 155); + h.write(h.reduce((sum, byte) => sum + byte, 0).toString(8).padStart(6, "0") + "\0 ", 148); + return Buffer.concat([h, bytes, Buffer.alloc((512 - bytes.length % 512) % 512)]); +} +const tar = (...files) => Buffer.concat([...files, Buffer.alloc(1024)]); + +test("inner reader preserves every regular asset and ustar prefix without executing it", () => { + const entries = readCopilotInnerTar(tar(file("package/index.js", "throw new Error('never execute')", { mode: 0o755 }), file("asset", "", { prefix: "package/assets" }))); + assert.equal(entries.size, 2); + assert.equal(entries.get("index.js").executable, true); + assert.equal(entries.get("assets/asset").bytes.length, 0); +}); + +test("inner reader rejects traversal, links, duplicate entries, writable files and file parents", () => { + for (const files of [[file("package/../escape")], [file("/package/index.js")], [file("package/a\\b")], + [file("package/link", "", { type: "2" })], [file("package/hardlink", "", { type: "1" })], + [file("package/a", "", { mode: 0o777 })], [file("package/a"), file("package/a")], + [file("package/a"), file("package/a/b")], [file("package/meta", "", { type: "x" })]]) { + assert.throws(() => readCopilotInnerTar(tar(...files))); + } +}); + +test("inner reader rejects corrupt checksums, truncated framing and hidden padding/trailer", () => { + const valid = tar(file("package/a")); + const checksum = Buffer.from(valid); checksum[0] ^= 1; + const padding = Buffer.from(valid); padding[517] = 1; + const trailer = Buffer.from(valid); trailer[trailer.length - 1] = 1; + for (const bytes of [checksum, padding, trailer, valid.subarray(0, -512), valid.subarray(0, -1)]) assert.throws(() => readCopilotInnerTar(bytes)); +}); + +test("pinned archive and source refuse unknown upstream bytes before patching", () => { + assert.throws(() => patchPinnedCopilotMessageIdentity(Buffer.from(COPILOT_MESSAGE_MAPPING_REPLACEMENT)), /source digest/); + assert.throws(() => readPinnedCopilotInnerDistribution(Buffer.alloc(1), "darwin-arm64"), /framing/); + assert.throws(() => readPinnedCopilotInnerDistribution(Buffer.alloc(1), "linux-arm64"), /target/); +}); + +test("ordered mapping retains native IDs including an empty start and never echoes completion text", () => { + const map = runInNewContext(`e=>{switch(e.type){${COPILOT_MESSAGE_MAPPING_REPLACEMENT}default:return null}}`); + const events = [ + { type: "assistant.message_start", data: { messageId: "first" } }, + { type: "assistant.message_delta", data: { messageId: "first", deltaContent: "same" } }, + { type: "assistant.message", data: { messageId: "first", content: "same" } }, + { type: "tool.execution_complete", data: {} }, + { type: "assistant.message_start", data: { messageId: "second" } }, + { type: "assistant.message_delta", data: { messageId: "second", deltaContent: "sa" } }, + { type: "assistant.message_delta", data: { messageId: "second", deltaContent: "me" } }, + { type: "assistant.message", data: { messageId: "second", content: "same" } }, + { type: "assistant.message_start", data: { messageId: "empty-final" } }, + { type: "assistant.message", data: { messageId: "empty-final", content: "" } }, + ]; + assert.deepEqual(JSON.parse(JSON.stringify(events.map(map).filter(Boolean))).map(e => [e.messageId, e.content.text]), + [["first", ""], ["first", "same"], ["second", ""], ["second", "sa"], ["second", "me"], ["empty-final", ""]]); +}); + +test("the patched replay branch emits full messages once, with ordered identities and empty finals", () => { + const live = runInNewContext(`e=>{switch(e.type){${COPILOT_MESSAGE_MAPPING_REPLACEMENT}default:return null}}`); + const replay = runInNewContext(`t=>{switch(t.type){${COPILOT_REPLAY_MAPPING_REPLACEMENT}default:return null}}`); + const history = [ + { type: "assistant.message", data: { messageId: "old-first", content: "same" } }, + { type: "assistant.message", data: { messageId: "old-second", content: "same" } }, + { type: "assistant.message", data: { messageId: "old-empty", content: "" } }, + ]; + assert.deepEqual(JSON.parse(JSON.stringify(history.map(replay))).map(e => [e.messageId, e.content.text]), + [["old-first", "same"], ["old-second", "same"], ["old-empty", ""]]); + assert.deepEqual(history.map(live), [null, null, null]); + // Completion has opposite roles: historical content is replayed once, while + // the active mapper must not echo text already emitted as live deltas. + const final = history[0]; + assert.equal(replay(final).content.text, "same"); + assert.equal(live(final), null); +}); diff --git a/packages/paperclip-runner/scripts/copilot-profile-identity.mjs b/packages/paperclip-runner/scripts/copilot-profile-identity.mjs new file mode 100644 index 00000000000..5c8ab96b8f7 --- /dev/null +++ b/packages/paperclip-runner/scripts/copilot-profile-identity.mjs @@ -0,0 +1,106 @@ +// Regenerate after changing any bound implementation; live qualification must +// restart whenever the resulting identity changes. Historical identities remain. +import { createHash } from "node:crypto"; +import { execFileSync } from "node:child_process"; +import { readFileSync, writeFileSync } from "node:fs"; +import { fileURLToPath } from "node:url"; +import { resolve, dirname } from "node:path"; + +const root = resolve(dirname(fileURLToPath(import.meta.url)), ".."); +const fixture = resolve(root, "test/fixtures/copilot-profile-v31-identity.json"); +const historical = JSON.parse(readFileSync(resolve(root, "test/fixtures/copilot-profile-v12-identity.json"), "utf8")); +const declaration = { ...historical.declaration, agentProfileVersion: 31 }; +delete declaration.permissionIdentitySourceSha256; +const sources = { + displayEventSourceSha256: "src/drivers/acpx/copilot-events.ts", + displayProjectionSourceSha256: "src/drivers/acpx/copilot-extension-adapter.ts", + configuredEnvironmentSourceSha256: "src/configured-environment.ts", + configuredEnvironmentRustSourceSha256: "runner/crates/runner-core/src/configured_environment.rs", + profileActivitySourceSha256: "src/drivers/acpx/profile-activity.ts", + profileExtensionsSourceSha256: "src/drivers/acpx/profile-extensions.ts", + profileInstallationSourceSha256: "src/drivers/acpx/profile-installation.ts", + attachmentPolicySourceSha256: "runner/crates/runner-core/src/acpx_provider_capabilities.rs", + singleReadEvidenceSourceSha256: "src/drivers/acpx/single-read-evidence.ts", + nativeSessionRuntimeSourceSha256: "src/native-session-runtime.ts", + nativeRuntimeContextSourceSha256: "src/contracts/runtime-context.ts", + nativeSessionContractSourceSha256: "src/contracts/native-session-backend.ts", + harnessSessionContractSourceSha256: "src/contracts/harness-driver.ts", + harnessBackendSourceSha256: "src/backends/harness-driver-backend.ts", + harnessSessionSourceSha256: "src/drivers/codex/codex-harness-session.ts", + transportContractSourceSha256: "src/drivers/codex/app-server-transport.ts", + nativeBackendSourceSha256: "src/backends/codex-native-backend.ts", + nativeBackendFactorySourceSha256: "src/backends/native-backend-factory.ts", + nativeInstructionsSourceSha256: "src/backends/runtime-context.ts", + runtimeRequestBridgeSourceSha256: "src/live/runnerd-codex-transport.ts", + runtimeRequestFacadeSourceSha256: "src/drivers/codex/codex-session-notifications.ts", + runtimeRequestNotificationSourceSha256: "src/drivers/codex/codex-thread-normalization.ts", + guardedInstallationSourceSha256: "src/drivers/acpx/installation-integrity.ts", + nativeExecutionSourceSha256: "src/contracts/native-execution.ts", + profileCompatibilitySourceSha256: "src/drivers/acpx/profile-compatibility.ts", + installationSourceSha256: "src/drivers/acpx/copilot-installation.ts", + assetOwnershipSourceSha256: "src/drivers/acpx/provider-assets-root.ts", + assetInstallerSourceSha256: "scripts/install-copilot-assets.mjs", + credentialBindingSourceSha256: "src/drivers/acpx/environment.ts", + sidecarErrorSourceSha256: "src/cli/acpx-sidecar-input.ts", + profileSourceSha256: "src/drivers/acpx/copilot-profile.ts", + metadataProbeSourceSha256: "src/drivers/copilot-metadata-probe.ts", + acpxPatchSha256: "../../patches/acpx@0.13.1.patch", + policySha256: "src/drivers/acpx/copilot-policy.ts", + distributionSourceSha256: "scripts/materialize-copilot-binary.mjs", + innerDistributionSourceSha256: "scripts/copilot-inner-distribution.mjs", + permissionContextSourceSha256: "src/drivers/acpx/copilot-permission-context.ts", + permissionAdapterSourceSha256: "src/drivers/acpx/acp-permission-adapter.ts", + permissionToolIdentitySourceSha256: "src/drivers/acpx/cursor-plan-tool-identity.ts", + permissionLocationsSourceSha256: "src/drivers/acpx/safe-locations.ts", + permissionRedactionSourceSha256: "src/semantic-tools/redaction.ts", + permissionClassifierSourceSha256: "src/drivers/acpx/generated-sidecar-contract.ts", + semanticReceiptSourceSha256: "src/drivers/semantic-tool-receipt.ts", + semanticBridgeSourceSha256: "src/drivers/runner-tool-bridge.ts", + toolEvidenceSourceSha256: "src/drivers/acpx/copilot-tool-evidence.ts", + semanticSidecarSourceSha256: "src/cli/acpx-runtime-sidecar.ts", + semanticDirectDriverSourceSha256: "src/drivers/acpx/codex-acpx-driver.ts", + semanticValidationSourceSha256: "src/protocol/replay-contract.ts", + semanticNormalizationSourceSha256: "src/protocol/result-normalization.ts", + semanticCompletionContractSourceSha256: "src/contracts/completion-result.ts", + semanticValidatorsSourceSha256: "src/protocol/generated/standalone-validators.ts", + semanticSchemaBundleSourceSha256: "src/protocol/generated/schema-bundle.ts", + semanticSidecarProtocolSourceSha256: "src/drivers/acpx/sidecar-protocol.ts", + runtimeHostSourceSha256: "src/drivers/acpx/runtime-host.ts", + runtimeAdapterSourceSha256: "src/drivers/acpx/codex-runtime-adapter.ts", + runtimeSandboxSourceSha256: "src/drivers/acpx/runtime-sandbox.ts", + cancellationSourceSha256: "src/drivers/acpx/turn-cancellation.ts", + agentFilesSourceSha256: "src/drivers/acpx/agent-files-binding.ts", + nativeDistributionSourceSha256: "src/drivers/acpx/native-distribution-integrity.ts", +}; +for (const [field, path] of Object.entries(sources)) { + declaration[field] = createHash("sha256").update(readFileSync(resolve(root, path))).digest("hex"); +} +const sorted = Object.fromEntries(Object.entries(declaration).sort(([a], [b]) => a.localeCompare(b))); +const commandDigest = `sha256:${createHash("sha256").update(JSON.stringify(sorted)).digest("hex")}`; +const identity = `${JSON.stringify({ commandDigest, declaration }, null, 2)}\n`; +// The shared manifest now generates both TypeScript and Rust admission. Update +// only Copilot; other providers retain their upstream release attestations. +const manifestPath = resolve(root, "acpx-profiles.json"); +const manifest = JSON.parse(readFileSync(manifestPath, "utf8")); +if (process.argv.includes("--check")) { + if (manifest.profiles.copilot.commandDigest !== commandDigest + || manifest.profiles.copilot.agentProfileVersion !== declaration.agentProfileVersion) { + throw new Error("Copilot identity is stale in acpx-profiles.json"); + } +} else { + manifest.profiles.copilot.commandDigest = commandDigest; + manifest.profiles.copilot.agentProfileVersion = declaration.agentProfileVersion; + writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`); +} +const distributionPath = resolve(root, "scripts/build-copilot-distribution.mjs"); +const before = readFileSync(distributionPath, "utf8"); +const after = before.replace(/(?<=const PROFILE_DIGEST = ")sha256:[a-f0-9]{64}/, commandDigest); +if (process.argv.includes("--check")) { + if (before !== after) throw new Error("Copilot identity is stale in build-copilot-distribution.mjs"); +} else writeFileSync(distributionPath, after); +execFileSync(process.execPath, [resolve(root, "scripts/generate-acpx-profiles.mjs"), + ...(process.argv.includes("--check") ? ["--check"] : [])], { stdio: "inherit" }); +if (process.argv.includes("--check")) { + if (readFileSync(fixture, "utf8") !== identity) throw new Error("Copilot source identity is stale"); +} else writeFileSync(fixture, identity); +console.log(commandDigest); diff --git a/packages/paperclip-runner/scripts/copilot-smoke-resources.mjs b/packages/paperclip-runner/scripts/copilot-smoke-resources.mjs new file mode 100644 index 00000000000..403603ad945 --- /dev/null +++ b/packages/paperclip-runner/scripts/copilot-smoke-resources.mjs @@ -0,0 +1,37 @@ +import { once } from "node:events"; +import { createServer } from "node:http"; +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +/** Own every setup resource immediately, including failures before native launch. */ +export async function withCopilotSmokeResources(installation, callback, dependencies = { mkdtemp, rm, createServer }) { + const lease = await installation.openCommand(); + let root; + let fixture; + const fixtureRequests = []; + try { + root = await dependencies.mkdtemp(join(tmpdir(), "paperclip-copilot-pack-smoke-")); + fixture = dependencies.createServer((request, response) => { + fixtureRequests.push({ method: request.method, path: request.url?.split("?")[0] }); + response.writeHead(request.method === "GET" ? 200 : 503, { "content-type": "application/json" }); + response.end(JSON.stringify(request.method === "GET" ? { object: "list", data: [{ id: "gpt-4.1", object: "model", owned_by: "fixture" }] } : { error: "This initialize-only fixture cannot run inference" })); + }); + fixture.listen(0, "127.0.0.1"); + await once(fixture, "listening"); + return await callback({ lease, root, fixture, fixtureRequests }); + } finally { + try { + if (fixture) { + fixture.closeAllConnections(); + await new Promise((resolve, reject) => fixture.close(error => { + if (error && error.code !== "ERR_SERVER_NOT_RUNNING") reject(error); + else resolve(); + })); + } + } finally { + try { await lease.close(); } + finally { if (root) await dependencies.rm(root, { recursive: true, force: true }); } + } + } +} diff --git a/packages/paperclip-runner/scripts/copilot-smoke-resources.test.mjs b/packages/paperclip-runner/scripts/copilot-smoke-resources.test.mjs new file mode 100644 index 00000000000..5ba83bb3200 --- /dev/null +++ b/packages/paperclip-runner/scripts/copilot-smoke-resources.test.mjs @@ -0,0 +1,43 @@ +import assert from "node:assert/strict"; +import { EventEmitter } from "node:events"; +import test from "node:test"; +import { withCopilotSmokeResources } from "./copilot-smoke-resources.mjs"; + +function resources(failure) { + const actions = []; + const fixture = new EventEmitter(); + fixture.listen = () => queueMicrotask(() => fixture.emit(failure === "listen" ? "error" : "listening", new Error("listen_failed"))); + fixture.closeAllConnections = () => actions.push("connections_closed"); + fixture.close = callback => { actions.push("server_closed"); callback(failure === "listen" ? Object.assign(new Error("not running"), { code: "ERR_SERVER_NOT_RUNNING" }) : undefined); }; + const installation = { openCommand: async () => ({ close: async () => { actions.push("lease_closed"); if (failure === "lease_close") throw new Error("close_failed"); } }) }; + const dependencies = { + mkdtemp: async () => { if (failure === "workspace") throw new Error("workspace_failed"); actions.push("workspace_created"); return "/fixture/private"; }, + rm: async (root, options) => { assert.equal(root, "/fixture/private"); assert.deepEqual(options, { recursive: true, force: true }); actions.push("workspace_removed"); }, + createServer: () => { if (failure === "server_create") throw new Error("server_create_failed"); return fixture; }, + }; + return { actions, installation, dependencies }; +} +for (const failure of ["workspace", "server_create", "listen"]) { + test(`${failure} setup failure releases all already acquired resources before callback`, async () => { + const r = resources(failure); + await assert.rejects(withCopilotSmokeResources(r.installation, () => assert.fail("provider must not launch"), r.dependencies), new RegExp(`${failure}_failed`)); + assert.deepEqual(r.actions, failure === "workspace" ? ["lease_closed"] + : failure === "server_create" ? ["workspace_created", "lease_closed", "workspace_removed"] + : ["workspace_created", "connections_closed", "server_closed", "lease_closed", "workspace_removed"]); + }); +} +test("provider callback failure still closes server, lease, and workspace", async () => { + const r = resources(); + await assert.rejects(withCopilotSmokeResources(r.installation, async () => { throw new Error("native_cleanup_failed"); }, r.dependencies), /native_cleanup_failed/); + assert.deepEqual(r.actions, ["workspace_created", "connections_closed", "server_closed", "lease_closed", "workspace_removed"]); +}); +test("lease close failure cannot bypass workspace removal", async () => { + const r = resources("lease_close"); + await assert.rejects(withCopilotSmokeResources(r.installation, async () => "ok", r.dependencies), /close_failed/); + assert.equal(r.actions.at(-1), "workspace_removed"); +}); +test("successful callback result is returned after all resource cleanup", async () => { + const r = resources(); + assert.equal(await withCopilotSmokeResources(r.installation, async ({ root, fixtureRequests }) => { assert.equal(root, "/fixture/private"); assert.deepEqual(fixtureRequests, []); return "ok"; }, r.dependencies), "ok"); + assert.deepEqual(r.actions, ["workspace_created", "connections_closed", "server_closed", "lease_closed", "workspace_removed"]); +}); diff --git a/packages/paperclip-runner/scripts/discover-copilot-acp.mjs b/packages/paperclip-runner/scripts/discover-copilot-acp.mjs new file mode 100644 index 00000000000..dc0b1fc5feb --- /dev/null +++ b/packages/paperclip-runner/scripts/discover-copilot-acp.mjs @@ -0,0 +1,130 @@ +// Metadata only. Supply an explicit token; this closed protocol client never prompts. +// Usage: node discover-copilot-acp.mjs [exact-model-id] +import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; +import { mkdir, mkdtemp, readFile, realpath, rm, writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { pathToFileURL } from "node:url"; + +const discoveryMethods = new Set(["initialize", "session/new", "session/set_model", "session/set_config_option", "session/close"]); +export function validateDiscoveryModel(model) { + assert.ok(model === undefined || (typeof model === "string" && model.trim() && model.trim().toLowerCase() !== "auto"), "model must be an exact model ID, not auto"); +} + +export async function withDiscoveryWorkspace(install, callback, filesystem = { mkdtemp, rm }) { + const lease = await install.openCommand(); + let root; + try { + root = await filesystem.mkdtemp("/tmp/paperclip-copilot-auth-discovery-"); + return await callback(lease, root); + } finally { + try { await lease.close(); } + finally { if (root) await filesystem.rm(root, { recursive: true, force: true }); } + } +} + +export function createDiscoveryRpc(child, { deadlineMs = 25_000, maxBytes = 2_097_152 } = {}) { + const pending = new Map(), observedMethods = {}; + let nextId = 0, buffer = "", bytes = 0, failure; + function fail(code) { + failure ??= code; + for (const item of pending.values()) { clearTimeout(item.timer); item.reject(new Error(failure)); } + pending.clear(); + } + function fatal(code) { fail(code); child.kill("SIGTERM"); } + child.once("close", () => fail("provider_exited")); + child.once("error", () => fail("provider_spawn_failure")); + child.stdin.on("error", () => fail("provider_stdin_failure")); + child.stderr.on("data", () => {}); + child.stdout.on("data", chunk => { + bytes += chunk.length; + if (bytes > maxBytes) { fatal("provider_wire_limit"); return; } + buffer += chunk.toString(); + while (buffer.includes("\n")) { + const end = buffer.indexOf("\n"), line = buffer.slice(0, end); buffer = buffer.slice(end + 1); + if (!line.trim()) continue; + let message; + try { message = JSON.parse(line); } catch { fatal("provider_malformed_json"); return; } + if (!message || typeof message !== "object" || Array.isArray(message)) { fatal("provider_malformed_message"); return; } + if (message.method) { + observedMethods[message.method] = (observedMethods[message.method] ?? 0) + 1; + if (message.id !== undefined) child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id: message.id, error: { code: -32601, message: "Discovery does not support inbound methods" } })}\n`); + continue; + } + const item = pending.get(message.id); + if (item) { clearTimeout(item.timer); pending.delete(message.id); message.error ? item.reject(new Error(`provider_rpc_error:${message.error.code}`)) : item.resolve(message.result); } + } + }); + return { + observedMethods, + request(method, params) { + assert.ok(discoveryMethods.has(method), "metadata discovery cannot send this method"); + if (failure) return Promise.reject(new Error(failure)); + const id = nextId++; + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { pending.delete(id); reject(new Error(`request_deadline:${method}`)); }, deadlineMs); + pending.set(id, { resolve, reject, timer }); + child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id, method, params })}\n`); + }); + }, + close() { fail("discovery_closed"); }, + }; +} + +export async function discoverCopilot(packInput, output, model, token) { + validateDiscoveryModel(model); + assert.ok(typeof token === "string" && token.trim() && !token.includes("\0"), "explicit Copilot token required"); + const pack = await realpath(packInput); + const manifest = JSON.parse(await readFile(join(pack, "provider-pack.json"), "utf8")); + process.env.PAPERCLIP_ACPX_PROVIDER_PACKAGE_ROOT = pack; + process.env.PAPERCLIP_ACPX_PROVIDER_PACKAGE_MANIFEST = join(pack, "package.json"); + const { verifyAcpxProfileInstallation, assertAcpxProfileEnvironment } = await import(pathToFileURL(join(pack, "dist/drivers/acpx/profile-installation.js"))); + const { resolveQualifiedAcpxProfile } = await import(pathToFileURL(join(pack, "dist/drivers/acpx/qualified-profiles.js"))); + const { COPILOT_ACP_CLIENT_CAPABILITIES } = await import(pathToFileURL(join(pack, "dist/drivers/acpx/copilot-events.js"))); + assertAcpxProfileEnvironment("copilot", { COPILOT_GITHUB_TOKEN: token }); + const install = await verifyAcpxProfileInstallation(resolveQualifiedAcpxProfile("copilot", model ?? "discovery-unselected")); + return withDiscoveryWorkspace(install, async (lease, root) => { + const env = { PATH: "/usr/bin:/bin", COPILOT_GITHUB_TOKEN: token, COPILOT_AUTO_UPDATE: "false", COPILOT_ALLOW_ALL: "false", NO_COLOR: "1" }; + for (const key of ["HOME", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "COPILOT_HOME", "COPILOT_CACHE_HOME"]) { + env[key] = join(root, key.toLowerCase()); await mkdir(env[key], { mode: 0o700 }); + } + await writeFile(join(env.COPILOT_HOME, "config.json"), JSON.stringify({ autoUpdate: false, trustedFolders: [], disableAllHooks: true, memory: false, ide: { autoConnect: false } }), { mode: 0o600 }); + let child, exitPromise, rpc; + try { + child = lease.spawn([], { cwd: root, env, stdio: "pipe" }); + exitPromise = new Promise(resolve => child.once("close", (code, signal) => resolve({ code, signal }))); + rpc = createDiscoveryRpc(child); + const initialized = await rpc.request("initialize", { protocolVersion: 1, clientInfo: { name: "paperclip-authenticated-model-discovery", version: "1" }, clientCapabilities: COPILOT_ACP_CLIENT_CAPABILITIES }); + const opened = await rpc.request("session/new", { cwd: root, mcpServers: [] }); + const safe = { schema: "paperclip.copilot-authenticated-discovery/v1", observedAt: new Date().toISOString(), harnessVersion: initialized.agentInfo?.version, + sourceRevision: manifest.payload.runnerSourceRevision, providerPackDigest: manifest.digest, profileDigest: install.commandDigest, + agentCapabilities: initialized.agentCapabilities, models: opened.models ?? null, configOptions: opened.configOptions ?? [], promptSent: false, + promptRequestsSent: 0, inferenceVerified: false, qualification: "pending; metadata discovery only", observedMethods: rpc.observedMethods }; + if (model) { + assert.ok(opened.models?.availableModels?.some(value => value.modelId === model), "requested exact model must be advertised"); + const selected = await rpc.request("session/set_model", { sessionId: opened.sessionId, modelId: model }); + const configured = await rpc.request("session/set_config_option", { sessionId: opened.sessionId, configId: "model", value: model }); + assert.equal(configured.configOptions?.find(option => option.id === "model")?.currentValue, model); + safe.modelSelection = { requestedModel: model, succeeded: true, response: selected, configEcho: configured }; + } + try { await rpc.request("session/close", { sessionId: opened.sessionId }); safe.sessionClosed = true; } + catch { safe.sessionClosed = false; } + const text = `${JSON.stringify(safe, null, 2)}\n`; + assert.ok(!text.includes(token)); assert.ok(!text.includes(opened.sessionId)); assert.ok(!text.includes(root)); + await writeFile(output, text, { mode: 0o600 }); + return { output, sha256: createHash("sha256").update(text).digest("hex"), harnessVersion: safe.harnessVersion, modelCount: safe.models?.availableModels?.length ?? 0, + configOptionIds: safe.configOptions.map(value => value.id), modelIds: safe.models?.availableModels?.map(value => value.modelId) ?? [], promptSent: false }; + } finally { + rpc?.close(); + if (child && child.exitCode === null && child.signalCode === null) { + child.stdin.end(); + const term = setTimeout(() => child.kill("SIGTERM"), 1_000), kill = setTimeout(() => child.kill("SIGKILL"), 5_000); + try { await exitPromise; } finally { clearTimeout(term); clearTimeout(kill); } + } + } + }); +} + +if (process.argv[1] && pathToFileURL(await realpath(process.argv[1])).href === import.meta.url) { + console.log(JSON.stringify(await discoverCopilot(process.argv[2], process.argv[3], process.argv[4], process.env.COPILOT_GITHUB_TOKEN))); +} diff --git a/packages/paperclip-runner/scripts/discover-copilot-acp.test.mjs b/packages/paperclip-runner/scripts/discover-copilot-acp.test.mjs new file mode 100644 index 00000000000..d33b2817006 --- /dev/null +++ b/packages/paperclip-runner/scripts/discover-copilot-acp.test.mjs @@ -0,0 +1,40 @@ +import assert from "node:assert/strict"; +import { EventEmitter } from "node:events"; +import test from "node:test"; +import { createDiscoveryRpc, validateDiscoveryModel, withDiscoveryWorkspace } from "./discover-copilot-acp.mjs"; + +test("exact model evidence rejects auto before any provider operation", () => { + for (const model of ["auto", "AUTO", " auto ", ""]) assert.throws(() => validateDiscoveryModel(model), /exact model ID/); + validateDiscoveryModel("gpt-5.6-luna"); validateDiscoveryModel(undefined); +}); +test("workspace failure always releases the acquired native command lease", async () => { + const closed = [], removed = []; + const install = { openCommand: async () => ({ close: async () => closed.push(true) }) }; + await assert.rejects(withDiscoveryWorkspace(install, () => assert.fail(), { mkdtemp: async () => { throw new Error("mkdir_failed"); }, rm: async (...args) => removed.push(args) }), /mkdir_failed/); + assert.equal(closed.length, 1); assert.equal(removed.length, 0); + await assert.rejects(withDiscoveryWorkspace(install, async () => { throw new Error("config_write_failed"); }, { mkdtemp: async () => "/fixture/private", rm: async (...args) => removed.push(args) }), /config_write_failed/); + assert.equal(closed.length, 2); assert.deepEqual(removed, [["/fixture/private", { recursive: true, force: true }]]); +}); +function childFixture() { + const child = new EventEmitter(); child.stdout = new EventEmitter(); child.stderr = new EventEmitter(); child.stdin = new EventEmitter(); + child.written = []; child.stdin.write = value => child.written.push(JSON.parse(value)); child.killed = []; + child.kill = signal => child.killed.push(signal); return child; +} +test("provider exit rejects pending discovery immediately with its actual failure", async () => { + const child = childFixture(), rpc = createDiscoveryRpc(child); + const pending = rpc.request("initialize", {}); child.emit("close", 1, null); + await assert.rejects(pending, /provider_exited/); + await assert.rejects(rpc.request("session/new", {}), /provider_exited/); +}); +test("malformed provider output rejects pending requests instead of waiting for timeout", async () => { + const child = childFixture(), rpc = createDiscoveryRpc(child); + const pending = rpc.request("initialize", {}); child.stdout.emit("data", Buffer.from("not-json\n")); + await assert.rejects(pending, /provider_malformed_json/); assert.deepEqual(child.killed, ["SIGTERM"]); +}); +test("closed discovery protocol preserves numeric zero and rejects prompts", async () => { + const child = childFixture(), rpc = createDiscoveryRpc(child); + const pending = rpc.request("initialize", {}); assert.equal(child.written[0].id, 0); + child.stdout.emit("data", Buffer.from('{"jsonrpc":"2.0","id":0,"result":{"protocolVersion":1}}\n')); + assert.deepEqual(await pending, { protocolVersion: 1 }); + assert.throws(() => rpc.request("session/prompt", {}), /cannot send/); rpc.close(); +}); diff --git a/packages/paperclip-runner/scripts/install-copilot-assets.mjs b/packages/paperclip-runner/scripts/install-copilot-assets.mjs new file mode 100644 index 00000000000..5ccd71702fd --- /dev/null +++ b/packages/paperclip-runner/scripts/install-copilot-assets.mjs @@ -0,0 +1,94 @@ +import { access, lstat, mkdir, readFile, realpath, rmdir } from "node:fs/promises"; +import { dirname, join, resolve } from "node:path"; +import { createRequire } from "node:module"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { COPILOT_DISTRIBUTIONS, materializePinnedCopilotBinary } from "./materialize-copilot-binary.mjs"; + +const packageRoot = await realpath(fileURLToPath(new URL("../", import.meta.url))); +const owner = JSON.parse(await readFile(join(packageRoot, "package.json"), "utf8")); +if (!["@paperclipai/paperclip-runner", "@paperclipai/server"].includes(owner.name)) { + throw new Error("Copilot installer must belong to a runner package owner"); +} +const vendored = owner.name === "@paperclipai/server"; +const runtimeRoot = vendored ? join(packageRoot, "dist/vendor/paperclip-runner") : join(packageRoot, "dist"); + +/** Install only the native npm package for this platform; never execute it. */ +export async function installCopilotAssets() { + const { platform, arch: architecture } = process; + const target = `${platform}-${architecture}`; + if (!Object.prototype.hasOwnProperty.call(COPILOT_DISTRIBUTIONS, target)) { + return { status: "unsupported-platform", target }; + } + const verifierPath = join(runtimeRoot, "drivers/acpx/copilot-installation.js"); + try { await access(verifierPath); } + catch (error) { + if (error.code !== "ENOENT") throw error; + // A source workspace installs dependencies before it compiles the verifier. + // Published packages exclude src, so a malformed npm artifact cannot use + // this path. build:typescript performs installation after compilation. + await access(join(packageRoot, vendored ? "src/services/copilot-connection-probe.ts" : "src/drivers/acpx/copilot-installation.ts")); + await access(resolve(packageRoot, vendored ? "../pnpm-workspace.yaml" : "../../pnpm-workspace.yaml")); + return { status: "source-workspace-pending-build", target }; + } + const assets = join(packageRoot, "provider-assets", "copilot"); + for (const directory of [dirname(assets), assets]) { + await mkdir(directory, { recursive: true, mode: 0o755 }); + const stat = await lstat(directory); + if (!stat.isDirectory() || stat.isSymbolicLink() || await realpath(directory) !== directory) { + throw new Error("Copilot install directory must not redirect through links"); + } + } + const destination = join(assets, target); + const originalRoot = process.env.PAPERCLIP_ACPX_PROVIDER_PACKAGE_ROOT; + const originalManifest = process.env.PAPERCLIP_ACPX_PROVIDER_PACKAGE_MANIFEST; + process.env.PAPERCLIP_ACPX_PROVIDER_PACKAGE_ROOT = packageRoot; + process.env.PAPERCLIP_ACPX_PROVIDER_PACKAGE_MANIFEST = join(packageRoot, "package.json"); + try { + const { COPILOT_CLOSURE_SHA256, verifyCopilotInstallation } = await import(pathToFileURL(join(runtimeRoot, "drivers/acpx/copilot-installation.js"))); + const { QUALIFIED_ACPX_PROFILES } = await import(pathToFileURL(join(runtimeRoot, "drivers/acpx/qualified-profiles.js"))); + const verify = () => verifyCopilotInstallation(QUALIFIED_ACPX_PROFILES.copilot); + try { await mkdir(destination, { mode: 0o755 }); } + catch (error) { + if (error.code !== "EEXIST") throw error; + const stat = await lstat(destination); + if (!stat.isDirectory() || stat.isSymbolicLink() || await realpath(destination) !== destination) { + throw new Error("Copilot installed assets must not redirect through links"); + } + await verify(); + return { status: "verified-existing", target }; + } + const ownedDirectory = await lstat(destination, { bigint: true }); + try { + // Official native packages export their executable, not package.json. + // Resolve that path without loading or executing the native module. + const nativePackageRoot = dirname(createRequire(import.meta.url).resolve(COPILOT_DISTRIBUTIONS[target].packageName)); + const materialized = materializePinnedCopilotBinary({ packageRoot: nativePackageRoot, platform, architecture, targetDirectory: destination }); + if (materialized.closureSha256 !== COPILOT_CLOSURE_SHA256[target]) { + throw new Error("Copilot installation differs from the runtime closure pin"); + } + await verify(); + return { status: "installed", target }; + } catch (error) { + // The materializer rolls back only files it created. Remove this newly + // created directory only if it is now empty; retain foreign files or + // failed verification evidence rather than deleting a directory tree. + try { + const current = await lstat(destination, { bigint: true }); + if (current.isDirectory() && !current.isSymbolicLink() && current.dev === ownedDirectory.dev && current.ino === ownedDirectory.ino) await rmdir(destination); + } + catch (cleanupError) { if (!["ENOENT", "ENOTEMPTY", "EEXIST"].includes(cleanupError.code)) throw new AggregateError([error, cleanupError], "Copilot install and empty-directory cleanup failed"); } + throw error; + } + } finally { + for (const [key, value] of [["PAPERCLIP_ACPX_PROVIDER_PACKAGE_ROOT", originalRoot], ["PAPERCLIP_ACPX_PROVIDER_PACKAGE_MANIFEST", originalManifest]]) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + } +} + +const invokedPath = process.argv[1] ? await realpath(resolve(process.argv[1])) : null; +if (invokedPath && import.meta.url === pathToFileURL(invokedPath).href) { + const result = await installCopilotAssets(); + process.stdout.write(`Copilot runtime assets: ${result.status} (${result.target})\n`); +} diff --git a/packages/paperclip-runner/scripts/install-copilot-assets.test.mjs b/packages/paperclip-runner/scripts/install-copilot-assets.test.mjs new file mode 100644 index 00000000000..086283ec44d --- /dev/null +++ b/packages/paperclip-runner/scripts/install-copilot-assets.test.mjs @@ -0,0 +1,99 @@ +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { cp, mkdir, mkdtemp, readFile, realpath, rename, rm, symlink, writeFile } from "node:fs/promises"; +import { createRequire } from "node:module"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; +import test from "node:test"; +import { COPILOT_DISTRIBUTIONS } from "./materialize-copilot-binary.mjs"; + +const runnerRoot = fileURLToPath(new URL("../", import.meta.url)); +const serverRoot = fileURLToPath(new URL("../../../server/", import.meta.url)); +const target = `${process.platform}-${process.arch}`; +const distribution = COPILOT_DISTRIBUTIONS[target]; +const require = createRequire(import.meta.url); +const helpers = ["install-copilot-assets.mjs", "materialize-copilot-binary.mjs", "copilot-inner-distribution.mjs"]; + +function invoke(script) { + return spawnSync(process.execPath, [script], { + env: { PATH: `${dirname(process.execPath)}:/usr/bin:/bin`, TMPDIR: tmpdir() }, + encoding: "utf8", timeout: 120_000, maxBuffer: 64 * 1024, + }); +} + +function succeeded(result, status) { + assert.equal(result.error, undefined); + assert.equal(result.status, 0, result.stderr); + assert.match(result.stdout, new RegExp(status)); +} + +for (const owner of ["runner", "server"]) { + test(`fresh ${owner} package installs verified assets without a workspace or qualification override`, { + skip: !distribution && "Copilot does not advertise this platform", timeout: 180_000, + }, async () => { + const root = await realpath(await mkdtemp(join(tmpdir(), "copilot-install-package-"))); + try { + const native = dirname(require.resolve(distribution.packageName)); + await mkdir(join(root, "node_modules/@github"), { recursive: true }); + await symlink(native, join(root, "node_modules", distribution.packageName), "dir"); + await writeFile(join(root, "package.json"), JSON.stringify({ + name: owner === "server" ? "@paperclipai/server" : "@paperclipai/paperclip-runner", type: "module", + })); + const runtimeRoot = owner === "server" ? join(root, "dist/vendor/paperclip-runner") : join(root, "dist"); + await cp(join(runnerRoot, "dist"), runtimeRoot, { recursive: true }); + const scriptRoot = owner === "server" ? join(root, "dist") : join(root, "scripts"); + await mkdir(scriptRoot, { recursive: true }); + for (const name of helpers) await cp(join(runnerRoot, "scripts", name), join(scriptRoot, name)); + let installer = join(scriptRoot, "install-copilot-assets.mjs"); + if (owner === "server") { + await mkdir(join(root, "scripts")); + installer = join(root, "scripts/install-copilot-assets.mjs"); + await cp(join(serverRoot, "scripts/install-copilot-assets.mjs"), installer); + } + succeeded(invoke(installer), "installed"); + succeeded(invoke(installer), "verified-existing"); + const assets = join(root, "provider-assets"); + const closure = join(assets, "copilot", target, ".paperclip-copilot-closure.json"); + const original = await readFile(closure); + const corrupted = JSON.parse(original.toString()); + corrupted.entries[0].sha256 = "0".repeat(64); + await writeFile(closure, JSON.stringify(corrupted)); + const failure = invoke(installer); + assert.notEqual(failure.status, 0); + assert.match(failure.stderr, /COPILOT_INSTALLATION_INVALID/); + assert.notDeepEqual(await readFile(closure), original, "failed verification must retain its evidence"); + await writeFile(closure, original); + succeeded(invoke(installer), "verified-existing"); + const retained = join(root, "retained-assets"); + const outside = join(root, "outside"); + await mkdir(outside); + await rename(assets, retained); + await symlink(outside, assets, "dir"); + const linked = invoke(installer); + assert.notEqual(linked.status, 0); + assert.match(linked.stderr, /must not redirect through links/); + await assert.rejects(readFile(join(outside, "copilot", target, "copilot")), { code: "ENOENT" }); + await rm(assets); + await rename(retained, assets); + succeeded(invoke(installer), "verified-existing"); + } finally { await rm(root, { recursive: true, force: true }); } + }); +} + +test("an unbuilt source workspace defers installation; a published package with missing build output fails", async () => { + const root = await realpath(await mkdtemp(join(tmpdir(), "copilot-install-bootstrap-"))); + try { + const server = join(root, "server"); + await mkdir(join(server, "scripts"), { recursive: true }); + const script = join(server, "scripts/install-copilot-assets.mjs"); + await cp(join(serverRoot, "scripts/install-copilot-assets.mjs"), script); + assert.notEqual(invoke(script).status, 0); + await mkdir(join(server, "src/services"), { recursive: true }); + await writeFile(join(server, "src/services/copilot-connection-probe.ts"), "// source workspace\n"); + assert.notEqual(invoke(script).status, 0); + await writeFile(join(root, "pnpm-workspace.yaml"), "packages: [server]\n"); + succeeded(invoke(script), "source-workspace-pending-build"); + await assert.rejects(readFile(join(server, "provider-assets/copilot", target, "copilot")), { code: "ENOENT" }); + } finally { await rm(root, { recursive: true, force: true }); } +}); diff --git a/packages/paperclip-runner/scripts/materialize-copilot-binary.mjs b/packages/paperclip-runner/scripts/materialize-copilot-binary.mjs new file mode 100644 index 00000000000..1d8cafe78cc --- /dev/null +++ b/packages/paperclip-runner/scripts/materialize-copilot-binary.mjs @@ -0,0 +1,133 @@ +import { createHash } from "node:crypto"; +import { constants, closeSync, fchmodSync, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, rmdirSync, unlinkSync, writeFileSync } from "node:fs"; +import { createRequire } from "node:module"; +import { dirname, join, resolve } from "node:path"; +import { pathToFileURL } from "node:url"; +import { readPinnedCopilotInnerDistribution } from "./copilot-inner-distribution.mjs"; + +export const COPILOT_VERSION = "1.0.88"; +// Extracted executable SHA-256 pins from npm archives after registry SHA-512 verification. +export const COPILOT_DISTRIBUTIONS = Object.freeze({ + "darwin-arm64": Object.freeze({ packageName: "@github/copilot-darwin-arm64", executableDigest: "a9ff8babb10b7e443182ae96a8bc50a9c826ef1c773e1344c396eb5bf7f512c3", size: 152595280, archiveIntegrity: "sha512-gt52dl+ja+G88RjLuSec59fA8C9HNfdGxKwwqE7eAIJXZYSKwKvuMy4B79WlCtlpnH/QKbs5Z9VsU0BTxe3EAg==" }), + "darwin-x64": Object.freeze({ packageName: "@github/copilot-darwin-x64", executableDigest: "85eb919f6b9b9dd833ce5e326cbf974b3ee2d4a9ac525c59d4ec9c9ec085715b", size: 165041200, archiveIntegrity: "sha512-GO5KwVR5vD1vNRe0jDDXFdpOHpS780ytVSRklk0DT6bK6HIpWXqbfnOasP9OZpPClaAYO4CShkGMhHv6vKRxaA==" }), + "linux-x64": Object.freeze({ packageName: "@github/copilot-linux-x64", executableDigest: "0059754cf78c3f3bf2c9d4564dfa7e9e25f3a3f8f411f2f0cdad9363f5662748", size: 169544512, archiveIntegrity: "sha512-wNigl8rqixvtYoRtygNf1NQIXx77MWC6XyqoV7fcfvSwWI3GJCltnczaNLbC611K9Hex39KyiUR5ZmGhQ+LzLw==" }), +}); + +export function resolveCopilotDistribution(platform = process.platform, architecture = process.arch) { + const distribution = COPILOT_DISTRIBUTIONS[`${platform}-${architecture}`]; + if (!distribution) throw new Error(`Copilot distribution is not pinned for ${platform}/${architecture}`); + return distribution; +} + +/** + * Build-time verifier/materializer only. Runtime admission must still use the + * shared descriptor-pinned command lease; this path grants no execution authority. + * Never run npm-loader.js, package postinstall, or an ambient PATH executable. + */ +export function materializePinnedCopilotBinary(options = {}) { + const distribution = resolveCopilotDistribution(options.platform, options.architecture); + const require = createRequire(import.meta.url); + const packageRoot = realpathSync(options.packageRoot ?? resolve(require.resolve(`${distribution.packageName}/package.json`), "..")); + const manifest = readPinnedFile(join(packageRoot, "package.json"), 256 * 1024); + const metadata = JSON.parse(manifest.toString("utf8")); + if (metadata.name !== distribution.packageName || metadata.version !== COPILOT_VERSION) { + throw new Error(`Expected ${distribution.packageName}@${COPILOT_VERSION}`); + } + const source = join(packageRoot, "copilot"); + const bytes = readPinnedFile(source, 384 * 1024 * 1024, true); + const sourceDigest = createHash("sha256").update(bytes).digest("hex"); + if (sourceDigest !== distribution.executableDigest) throw new Error("Copilot executable digest does not match its pinned distribution"); + const inner = readPinnedCopilotInnerDistribution(bytes, `${options.platform ?? process.platform}-${options.architecture ?? process.arch}`); + const output = options.targetDirectory === undefined ? packageRoot : realpathSync(options.targetDirectory); + const target = options.targetDirectory === undefined ? source : join(output, "copilot"); + const entries = [{ path: "copilot", sha256: sourceDigest, size: bytes.length, executable: true }]; + const files = options.targetDirectory === undefined ? [] : [{ path: "copilot", bytes, executable: true }]; + // Preserve every embedded asset; only the hash-pinned app's message mapping + // changes. Never import or execute any archive entry during materialization. + for (const [path, entry] of inner) { + const relative = `distribution/${path}`; + files.push({ path: relative, ...entry }); + entries.push({ path: relative, sha256: createHash("sha256").update(entry.bytes).digest("hex"), size: entry.bytes.length, executable: entry.executable }); + } + entries.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0); + const closureSha256 = createHash("sha256").update(JSON.stringify(entries)).digest("hex"); + const manifestPath = join(output, ".paperclip-copilot-closure.json"); + files.push({ path: ".paperclip-copilot-closure.json", bytes: Buffer.from(`${JSON.stringify({ schema: "paperclip.native_distribution_closure.v1", entries })}\n`), executable: false }); + writeCopilotMaterialization(output, files); + return { packageName: distribution.packageName, version: COPILOT_VERSION, sourceDigest, target, manifestPath, closureSha256 }; +} + +/** Build-only writer for already verified entries; never grants launch authority. + * Roll back only entries this invocation exclusively created, even when a write + * failed partway through. Never recursively remove a caller's output directory. + */ +export function writeCopilotMaterialization(output, files) { + if (realpathSync(output) !== output || !lstatSync(output).isDirectory()) throw new Error("Copilot target must be an owned real directory"); + const root = lstatSync(output, { bigint: true }); + const created = []; + const same = (a, b) => a.dev === b.dev && a.ino === b.ino; + const assertRoot = () => { + const current = lstatSync(output, { bigint: true }); + if (!current.isDirectory() || !same(root, current) || realpathSync(output) !== output) throw new Error("Copilot output identity changed"); + }; + try { + for (const entry of files) { + if (typeof entry.path !== "string" || entry.path.includes("\\") || entry.path.split("/").some(part => !part || part === "." || part === "..")) throw new Error("Unsafe Copilot output entry"); + assertRoot(); + const parts = entry.path.split("/"); + for (let i = 1; i < parts.length; i++) { + const directory = join(output, ...parts.slice(0, i)); + try { + mkdirSync(directory, { mode: 0o755 }); + created.push({ path: directory, stat: lstatSync(directory, { bigint: true }), directory: true }); + } catch (error) { if (error.code !== "EEXIST") throw error; } + if (!lstatSync(directory).isDirectory() || realpathSync(directory) !== directory) throw new Error("Copilot inner destination redirects through links"); + } + const path = join(output, entry.path); + const mode = entry.executable ? 0o755 : 0o644; + const fd = openSync(path, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, mode); + try { + created.push({ path, stat: fstatSync(fd, { bigint: true }), directory: false }); + writeFileSync(fd, entry.bytes); + fchmodSync(fd, mode); + fsyncSync(fd); + } finally { closeSync(fd); } + } + } catch (error) { + const cleanupErrors = []; + for (const entry of created.reverse()) { + try { + assertRoot(); + if (realpathSync(dirname(entry.path)) !== dirname(entry.path)) throw new Error("Copilot cleanup parent identity changed"); + let current; + try { current = lstatSync(entry.path, { bigint: true }); } catch (missing) { if (missing.code === "ENOENT") continue; throw missing; } + if (!same(entry.stat, current) || (entry.directory ? !current.isDirectory() : !current.isFile())) throw new Error("Copilot cleanup entry identity changed"); + if (entry.directory) rmdirSync(entry.path); else unlinkSync(entry.path); + } catch (cleanupError) { cleanupErrors.push(cleanupError); } + } + if (cleanupErrors.length) throw new AggregateError([error, ...cleanupErrors], "Copilot materialization failed and owned cleanup is incomplete"); + throw error; + } +} + +function readPinnedFile(path, maxBytes, executable = false) { + const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW); + try { + const before = fstatSync(fd, { bigint: true }); + if (!before.isFile() || before.size < 1n || before.size > BigInt(maxBytes)) throw new Error("Copilot distribution file is not a bounded regular file"); + if (executable && ((before.mode & 0o111n) === 0n || (before.mode & 0o022n) !== 0n)) throw new Error("Copilot executable has unsafe permissions"); + const bytes = readFileSync(fd); + const after = fstatSync(fd, { bigint: true }); + const entry = lstatSync(path, { bigint: true }); + if (!entry.isFile() || bytes.length !== Number(before.size) || before.dev !== entry.dev || before.ino !== entry.ino + || before.size !== after.size || before.mtimeNs !== after.mtimeNs || before.ctimeNs !== after.ctimeNs) throw new Error("Copilot distribution changed during verification"); + return bytes; + } finally { closeSync(fd); } +} + +if (process.argv[1] && pathToFileURL(resolve(process.argv[1])).href === import.meta.url) { + const args = process.argv.slice(2); + if (args.some((arg, index) => index % 2 === 0 && !["--package-root", "--target-directory", "--platform", "--architecture"].includes(arg)) || args.length % 2 !== 0) throw new Error("Usage: materialize-copilot-binary.mjs [--package-root PATH] [--target-directory PATH] [--platform darwin|linux] [--architecture arm64|x64]"); + const argsMap = Object.fromEntries(Array.from({ length: args.length / 2 }, (_, index) => [args[index * 2], args[index * 2 + 1]])); + process.stdout.write(`${JSON.stringify(materializePinnedCopilotBinary({ packageRoot: argsMap["--package-root"], targetDirectory: argsMap["--target-directory"], platform: argsMap["--platform"], architecture: argsMap["--architecture"] }))}\n`); +} diff --git a/packages/paperclip-runner/scripts/materialize-copilot-binary.test.mjs b/packages/paperclip-runner/scripts/materialize-copilot-binary.test.mjs new file mode 100644 index 00000000000..4bf5b105cd8 --- /dev/null +++ b/packages/paperclip-runner/scripts/materialize-copilot-binary.test.mjs @@ -0,0 +1,121 @@ +import assert from "node:assert/strict"; +import { chmod, mkdir, mkdtemp, readFile, readdir, rm, symlink, writeFile } from "node:fs/promises"; +import * as fs from "node:fs"; +import { syncBuiltinESMExports } from "node:module"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, test } from "node:test"; +import { COPILOT_DISTRIBUTIONS, materializePinnedCopilotBinary, resolveCopilotDistribution, writeCopilotMaterialization } from "./materialize-copilot-binary.mjs"; +const directories = []; +afterEach(async () => { await Promise.all(directories.splice(0).map((path) => rm(path, { recursive: true, force: true }))); }); +async function fixture(version = "1.0.88") { + const root = await mkdtemp(join(tmpdir(), "paperclip-copilot-materializer-")); directories.push(root); + await writeFile(join(root, "package.json"), JSON.stringify({ name: "@github/copilot-linux-x64", version })); + await writeFile(join(root, "copilot"), "#!/bin/sh\nexit 98\n", { mode: 0o755 }); + return fs.realpathSync(root); +} +test("pins every requested platform and rejects unqualified platforms", () => { + assert.deepEqual(Object.keys(COPILOT_DISTRIBUTIONS), ["darwin-arm64", "darwin-x64", "linux-x64"]); + for (const [key, value] of Object.entries(COPILOT_DISTRIBUTIONS)) { + assert.match(value.executableDigest, /^[a-f0-9]{64}$/); + assert.match(value.archiveIntegrity, /^sha512-/); + assert.equal(resolveCopilotDistribution(...key.split("-")), value); + } + assert.throws(() => resolveCopilotDistribution("linux", "arm64"), /not pinned/); +}); +test("refuses a different version before opening or executing the binary", async () => { + const packageRoot = await fixture("1.0.89"); + assert.throws(() => materializePinnedCopilotBinary({ packageRoot, platform: "linux", architecture: "x64" }), /Expected/); +}); +test("refuses executable tampering even when package metadata claims the right version", async () => { + const packageRoot = await fixture(); + assert.throws(() => materializePinnedCopilotBinary({ packageRoot, platform: "linux", architecture: "x64" }), /digest/); +}); +test("refuses executable symlinks, directory entries and writable binaries", async () => { + const packageRoot = await fixture(); const binary = join(packageRoot, "copilot"); + await chmod(binary, 0o777); + assert.throws(() => materializePinnedCopilotBinary({ packageRoot, platform: "linux", architecture: "x64" }), /permissions/); + await rm(binary); await symlink(join(packageRoot, "package.json"), binary); + assert.throws(() => materializePinnedCopilotBinary({ packageRoot, platform: "linux", architecture: "x64" })); + await rm(binary); await mkdir(binary); + assert.throws(() => materializePinnedCopilotBinary({ packageRoot, platform: "linux", architecture: "x64" }), /regular file/); +}); + +const outputFiles = () => [ + { path: "copilot", bytes: Buffer.from("verified executable"), executable: true }, + { path: "distribution/nested/first.js", bytes: Buffer.from("verified first asset"), executable: false }, + { path: "distribution/nested/last.js", bytes: Buffer.from("verified last asset"), executable: false }, + { path: ".paperclip-copilot-closure.json", bytes: Buffer.from("verified closure"), executable: false }, +]; + +test("partial inner writes roll back only owned entries and permit a clean retry", async t => { + const root = await fixture(); const output = join(root, "output"); await mkdir(output); + await writeFile(join(output, "caller-file"), "preserve"); + const originalWrite = fs.writeFileSync; let calls = 0; + const mocked = t.mock.method(fs.default, "writeFileSync", (fd, bytes, ...args) => { + if (++calls === 3) { originalWrite(fd, bytes.subarray(0, 3)); throw Object.assign(new Error("injected partial write"), { code: "ENOSPC" }); } + return originalWrite(fd, bytes, ...args); + }); + syncBuiltinESMExports(); + try { assert.throws(() => writeCopilotMaterialization(output, outputFiles()), /injected partial write/); } + finally { mocked.mock.restore(); syncBuiltinESMExports(); } + assert.deepEqual(await readdir(output), ["caller-file"]); + assert.equal(await readFile(join(output, "caller-file"), "utf8"), "preserve"); + writeCopilotMaterialization(output, outputFiles()); + for (const file of outputFiles()) assert.deepEqual(await readFile(join(output, file.path)), file.bytes); +}); + +test("failure preserves preexisting binary, directories, assets and closure", async () => { + for (const collision of outputFiles()) { + const root = await fixture(); const output = join(root, "output"); await mkdir(output); + await mkdir(join(output, "distribution/nested"), { recursive: true }); + await writeFile(join(output, collision.path), "preexisting"); + assert.throws(() => writeCopilotMaterialization(output, outputFiles()), /EEXIST/); + assert.equal(await readFile(join(output, collision.path), "utf8"), "preexisting"); + const kept = (await readdir(join(output, "distribution/nested"))).sort(); + assert.deepEqual(kept, collision.path.startsWith("distribution/") ? [collision.path.split("/").at(-1)] : []); + assert.equal(fs.statSync(join(output, "distribution")).isDirectory(), true); + } +}); + +test("rollback refuses a replaced owned entry and never removes foreign files", async t => { + const root = await fixture(); const output = join(root, "output"); await mkdir(output); + const originalWrite = fs.writeFileSync; let calls = 0; + const mocked = t.mock.method(fs.default, "writeFileSync", (fd, bytes, ...args) => { + if (++calls === 3) { + fs.renameSync(join(output, "copilot"), join(output, "caller-retained-copy")); + originalWrite(join(output, "copilot"), "foreign replacement", { flag: "wx" }); + throw new Error("injected replacement race"); + } + return originalWrite(fd, bytes, ...args); + }); + syncBuiltinESMExports(); + try { assert.throws(() => writeCopilotMaterialization(output, outputFiles()), error => error instanceof AggregateError && error.errors.some(e => /entry identity changed/.test(e.message))); } + finally { mocked.mock.restore(); syncBuiltinESMExports(); } + assert.equal(await readFile(join(output, "copilot"), "utf8"), "foreign replacement"); + assert.equal(await readFile(join(output, "caller-retained-copy"), "utf8"), "verified executable"); +}); + +test("owned cleanup never follows a preexisting destination symlink", async () => { + const root = await fixture(); const output = join(root, "output"); const outside = join(root, "outside"); + await mkdir(output); await mkdir(outside); await symlink(outside, join(output, "distribution")); + assert.throws(() => writeCopilotMaterialization(output, outputFiles()), /redirects through links/); + assert.deepEqual(await readdir(outside), []); + assert.deepEqual(await readdir(output), ["distribution"]); +}); + +test("in-place failure leaves the pinned source executable untouched", async t => { + const root = await fixture(); const before = await readFile(join(root, "copilot")); + const originalWrite = fs.writeFileSync; let calls = 0; + const mocked = t.mock.method(fs.default, "writeFileSync", (fd, bytes, ...args) => { + if (++calls === 2) { originalWrite(fd, bytes.subarray(0, 2)); throw new Error("injected asset failure"); } + return originalWrite(fd, bytes, ...args); + }); + syncBuiltinESMExports(); + try { assert.throws(() => writeCopilotMaterialization(root, outputFiles().slice(1)), /injected asset failure/); } + finally { mocked.mock.restore(); syncBuiltinESMExports(); } + assert.deepEqual((await readdir(root)).sort(), ["copilot", "package.json"]); + assert.deepEqual(await readFile(join(root, "copilot")), before); + writeCopilotMaterialization(root, outputFiles().slice(1)); + assert.deepEqual(await readFile(join(root, "copilot")), before); +}); diff --git a/packages/paperclip-runner/scripts/probe-copilot-acp.py b/packages/paperclip-runner/scripts/probe-copilot-acp.py new file mode 100644 index 00000000000..3f35957de58 --- /dev/null +++ b/packages/paperclip-runner/scripts/probe-copilot-acp.py @@ -0,0 +1,197 @@ +"""Run the pinned real Copilot binary against a deterministic loopback model. +No credentials are inherited; COPILOT_OFFLINE disables provider network access. +This proves a protocol fixture, never GitHub/model/Daytona qualification. +""" +import argparse,json,subprocess,tempfile,pathlib,os,select,time,threading,http.server,hashlib,shutil,contextlib,sys +parser=argparse.ArgumentParser(description=__doc__) +parser.add_argument('--package-root',required=True) +parser.add_argument('--comparison-version',choices=['1.0.89'],help='Explicit offline comparison only; production remains pinned to 1.0.88') +parser.add_argument('--scenario',choices=['deny-write','deny-shell','deny-read','attached-shell','detached-shell','discover-inputs','native-question','native-plan'],default='deny-write') +parser.add_argument('--mode',choices=['agent','plan','autopilot'],default='agent') +resume_group=parser.add_mutually_exclusive_group() +resume_group.add_argument('--resume',action='store_true',help='Close and load the same native session before prompting') +resume_group.add_argument('--restart',action='store_true',help='SIGKILL and replace the provider after one allowed seed mutation; load and verify no replay') +parser.add_argument('--tool-policy-node',help='Apply the repository tool policy before native permission dispatch using this Node 24 binary') +args=parser.parse_args() +if args.tool_policy_node and args.scenario!='detached-shell':parser.error('--tool-policy-node requires detached-shell') +package_root=pathlib.Path(args.package_root).resolve() +metadata=json.loads((package_root/'package.json').read_text()) +pins={'@github/copilot-darwin-arm64':'a9ff8babb10b7e443182ae96a8bc50a9c826ef1c773e1344c396eb5bf7f512c3','@github/copilot-darwin-x64':'85eb919f6b9b9dd833ce5e326cbf974b3ee2d4a9ac525c59d4ec9c9ec085715b','@github/copilot-linux-x64':'0059754cf78c3f3bf2c9d4564dfa7e9e25f3a3f8f411f2f0cdad9363f5662748'} +if args.comparison_version:pins={'@github/copilot-darwin-arm64':'97c12874d9adb9738374a9fb8a52cd724b81132ff815140f7e017bac706feba7'} +assert metadata['version']==(args.comparison_version or '1.0.88') and metadata['name'] in pins +assert not (package_root/'copilot').is_symlink() +assert hashlib.sha256((package_root/'copilot').read_bytes()).hexdigest()==pins[metadata['name']] +model_tool_names=[] +model_tool_results=[] +model_tool_schemas={} +command='sleep 2; printf ACP_SHELL_DONE > settlement.txt' + +binary=str(package_root/'copilot') +def stop_process(process): + # Cleanup must still reap a child whose stdin broke or which ignores TERM. + try: + if process.stdin:process.stdin.close() + except OSError:pass + try: + process.terminate() + try:process.wait(timeout=5) + except subprocess.TimeoutExpired:process.kill();process.wait(timeout=5) + finally: + for stream in (process.stdout,process.stderr): + if stream:stream.close() + +with contextlib.ExitStack() as cleanup: + root=pathlib.Path(tempfile.mkdtemp(prefix='paperclip-copilot-offline-')) + cleanup.callback(shutil.rmtree, root) + calls=0 + total_model_calls=0 + session=None + seeding=False + seed_command='printf X >> replay-count.txt' + final_prompt_id=None + outside=root.parent/(root.name+'-protected.txt') + outside.write_text('PRIVATE_FIXTURE_SENTINEL') + cleanup.callback(outside.unlink,missing_ok=True) + tool_name={'deny-write':'create','deny-shell':'bash','deny-read':'view','attached-shell':'bash','detached-shell':'bash','native-question':'ask_user','native-plan':'exit_plan_mode'}.get(args.scenario) + tool_arguments={'deny-write':{'path':str(root/'denied.txt'),'file_text':'MUST NOT EXIST'},'deny-shell':{'command':'printf MUST_NOT_EXIST > denied.txt','description':'Denied command fixture'},'deny-read':{'path':str(outside)},'attached-shell':{'command':command,'description':'Bounded settlement fixture','mode':'async','detach':False},'detached-shell':{'command':command,'description':'Bounded detached settlement fixture','mode':'async','detach':True},'native-question':{'question':'Choose one','choices':['A','B'],'allowFreeform':False},'native-plan':{'summary':'Fixture plan','planContent':'Do fixture work'}}.get(args.scenario) + marker_at_prompt_result=False + policy_rejection=None + class PolicyRejected(Exception):pass + class Handler(http.server.BaseHTTPRequestHandler): + def log_message(self,*args):pass + def do_GET(self): + self.send_response(200);self.send_header('Content-Type','application/json');self.end_headers();self.wfile.write(json.dumps({'data':[{'id':'gpt-4.1','object':'model','owned_by':'fixture'}]}).encode()) + def do_POST(self): + global calls,total_model_calls,model_tool_names,model_tool_results,model_tool_schemas + calls+=1 + total_model_calls+=1 + data=json.loads(self.rfile.read(int(self.headers.get('Content-Length','0')))) + model_tool_names=sorted(set(model_tool_names+[x.get('function',{}).get('name') for x in data.get('tools',[]) if x.get('function',{}).get('name')])) + for tool in data.get('tools',[]): + function=tool.get('function',{}) + if function.get('name') in ('bash','read_bash','write_bash','stop_bash','task','powershell','write_powershell','read_powershell'):model_tool_schemas[function['name']]=function + model_tool_results.extend(x.get('content') for x in data.get('messages',[]) if x.get('role')=='tool') + if total_model_calls>6:raise RuntimeError('Fixture model exceeded its bounded request count') + if data.get('stream'): + self.send_response(200);self.send_header('Content-Type','text/event-stream');self.end_headers() + values=[{'id':'fixture-1','object':'chat.completion.chunk','choices':[{'index':0,'delta':{'role':'assistant','content':'Fixture complete.'},'finish_reason':None}]},{'id':'fixture-1','object':'chat.completion.chunk','choices':[{'index':0,'delta':{},'finish_reason':'stop'}],'usage':{'prompt_tokens':10,'completion_tokens':3,'total_tokens':13}}] + selected_tool='bash' if seeding else tool_name + selected_arguments={'command':seed_command,'description':'Single non-replayed seed mutation'} if seeding else tool_arguments + if calls==1 and selected_tool:values=[{'id':'fixture-1','object':'chat.completion.chunk','choices':[{'index':0,'delta':{'role':'assistant','tool_calls':[{'index':0,'id':'fixture-tool','type':'function','function':{'name':selected_tool,'arguments':json.dumps(selected_arguments)}}]},'finish_reason':None}]},{'id':'fixture-1','object':'chat.completion.chunk','choices':[{'index':0,'delta':{},'finish_reason':'tool_calls'}]}] + for value in values:self.wfile.write(('data: '+json.dumps(value)+'\n\n').encode()) + self.wfile.write(b'data: [DONE]\n\n') + else: + self.send_response(200);self.send_header('Content-Type','application/json');self.end_headers();self.wfile.write(json.dumps({'id':'fixture-1','object':'chat.completion','choices':[{'index':0,'message':{'role':'assistant','content':'Fixture complete.'},'finish_reason':'stop'}],'usage':{'prompt_tokens':10,'completion_tokens':3,'total_tokens':13}}).encode()) + server=http.server.HTTPServer(('127.0.0.1',0),Handler) + cleanup.callback(server.server_close) + threading.Thread(target=server.serve_forever,daemon=True).start() + cleanup.callback(server.shutdown) + env={'PATH':'/usr/bin:/bin','HOME':str(root/'home'),'XDG_CONFIG_HOME':str(root/'config'),'XDG_CACHE_HOME':str(root/'cache'),'XDG_DATA_HOME':str(root/'data'),'COPILOT_HOME':str(root/'copilot'),'COPILOT_CACHE_HOME':str(root/'copilot-cache'),'COPILOT_ALLOW_ALL':'false','COPILOT_PKG_CACHE_HOME':str(root/'extract'),'COPILOT_AUTO_UPDATE':'false','COPILOT_OFFLINE':'true','COPILOT_PROVIDER_BASE_URL':f'http://127.0.0.1:{server.server_port}','COPILOT_PROVIDER_TYPE':'openai','COPILOT_PROVIDER_MODEL_ID':'gpt-4.1','COPILOT_MODEL':'gpt-4.1','NO_COLOR':'1'} + for key in ('HOME','XDG_CONFIG_HOME','XDG_CACHE_HOME','XDG_DATA_HOME','COPILOT_HOME','COPILOT_CACHE_HOME','COPILOT_PKG_CACHE_HOME'):pathlib.Path(env[key]).mkdir() + (root/'copilot/config.json').write_text(json.dumps({'trustedFolders':[],'disableAllHooks':True,'memory':False,'ide':{'autoConnect':False}})) + launch=[binary,'--acp','--stdio','--no-auto-update','--disable-builtin-mcps','--no-remote','--no-remote-export','--no-bash-env'] + p=subprocess.Popen(launch,env=env,cwd=root,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE) + cleanup.callback(stop_process, p) + responses={};wire=[];permission_responses=[];buf={p.stdout:b'',p.stderr:b''};nextid=0;marker_at_prompt_result=False + + def pump(wait=1): + global policy_rejection + for stream in select.select([p.stdout,p.stderr],[],[],wait)[0]: + data=os.read(stream.fileno(),65536) + if not data:continue + buf[stream]+=data + while b'\n' in buf[stream]: + line,buf[stream]=buf[stream].split(b'\n',1) + if not line:continue + if stream==p.stderr:continue + message=json.loads(line);wire.append(message) + if args.tool_policy_node and message.get('method')=='session/update': + checked=subprocess.run([args.tool_policy_node,str(pathlib.Path(__file__).with_name('probe-copilot-tool-policy.mjs'))],input=json.dumps(message['params']['update']),text=True,capture_output=True,timeout=5,env={'PATH':'/usr/bin:/bin'}) + if checked.returncode: + if checked.returncode!=42 or checked.stdout.strip()!='COPILOT_DETACHED_WORK_UNSUPPORTED':raise RuntimeError('Repository tool policy probe failed unexpectedly') + policy_rejection=checked.stdout.strip() + p.terminate();p.wait(timeout=5) + raise PolicyRejected(policy_rejection) + if 'id' in message and 'method' not in message:responses[message['id']]=message + if message.get('method')=='session/request_permission': + requested_command=message['params'].get('toolCall',{}).get('rawInput',{}).get('command') + allow=(args.scenario in ('attached-shell','detached-shell') and requested_command==command) or (seeding and requested_command==seed_command) + reject=next((o for o in message['params']['options'] if o['kind']==('allow_once' if allow else 'reject_once')),None) + outcome={'outcome':'selected','optionId':reject['optionId']} if reject else {'outcome':'cancelled'} + permission_responses.append({'id':message['id'],'outcome':outcome}) + p.stdin.write((json.dumps({'jsonrpc':'2.0','id':message['id'],'result':{'outcome':outcome}})+'\n').encode());p.stdin.flush() + + def request(method,params): + global nextid + nextid+=1;n=nextid;p.stdin.write((json.dumps({'jsonrpc':'2.0','id':n,'method':method,'params':params})+'\n').encode());p.stdin.flush();deadline=time.monotonic()+30 + while n not in responses and time.monotonic() { + execFileSync("python3", [fileURLToPath(new URL("./probe-copilot-acp.test.py", import.meta.url))], { + encoding: "utf8", timeout: 15_000, stdio: "pipe", + }); +}); diff --git a/packages/paperclip-runner/scripts/probe-copilot-acp.test.py b/packages/paperclip-runner/scripts/probe-copilot-acp.test.py new file mode 100644 index 00000000000..6cf63e1550b --- /dev/null +++ b/packages/paperclip-runner/scripts/probe-copilot-acp.test.py @@ -0,0 +1,93 @@ +"""Credential-free failure injection for the offline probe's resource ownership.""" +import io +import json +import pathlib +import runpy +import tempfile +import unittest +from contextlib import ExitStack, redirect_stdout +from unittest.mock import Mock, patch + +SCRIPT = pathlib.Path(__file__).with_name("probe-copilot-acp.py") +DIGEST = "a9ff8babb10b7e443182ae96a8bc50a9c826ef1c773e1344c396eb5bf7f512c3" + + +class ProbeCleanupTests(unittest.TestCase): + def exercise(self, stage, broken_report=False, broken_stdin=False): + with tempfile.TemporaryDirectory(prefix="copilot-probe-test-") as temporary: + base = pathlib.Path(temporary) + package = base / "package" + package.mkdir() + (package / "package.json").write_text(json.dumps({"name": "@github/copilot-darwin-arm64", "version": "1.0.88"})) + (package / "copilot").write_bytes(b"fixture; never executed") + workspace = base / "workspace" + server = Mock(server_port=54321) + process = Mock() + process.stdout.fileno.return_value = 10 + process.stderr.fileno.return_value = 11 + if broken_stdin: + process.stdin.close.side_effect = BrokenPipeError("closed") + pending = [] + + def write(raw): + request = json.loads(raw) + if request["method"] != stage: + result = {"sessionId": "session-1"} if request["method"] == "session/new" else {"stopReason": "end_turn"} + pending.append((json.dumps({"jsonrpc": "2.0", "id": request["id"], "result": result}) + "\n").encode()) + process.stdin.write.side_effect = write + process.wait.return_value = 0 + clock = iter(range(0, 1000, 10)) + dumps = json.dumps + + def serialize(value, *args, **kwargs): + if broken_report and isinstance(value, dict) and value.get("schema") == "paperclip.copilot-acp-evidence/v1": + raise ValueError("report failed") + return dumps(value, *args, **kwargs) + + def make_workspace(**_kwargs): + workspace.mkdir() + return str(workspace) + + with ExitStack() as patches, redirect_stdout(io.StringIO()): + for target, value in [ + ("sys.argv", [str(SCRIPT), "--package-root", str(package)]), + ("hashlib.sha256", Mock(return_value=Mock(hexdigest=lambda: DIGEST))), + ("tempfile.mkdtemp", make_workspace), + ("http.server.HTTPServer", Mock(return_value=server)), + ("threading.Thread", Mock()), + ("subprocess.Popen", Mock(side_effect=OSError("spawn failed")) if stage == "spawn" else Mock(return_value=process)), + ("time.monotonic", lambda: next(clock)), + ("select.select", lambda *_args: ([process.stdout] if pending else [], [], [])), + ("os.read", lambda *_args: pending.pop(0)), + ("json.dumps", serialize), + ]: + patches.enter_context(patch(target, value)) + with self.assertRaisesRegex(OSError if stage == "spawn" else TimeoutError, "spawn failed" if stage == "spawn" else stage): + runpy.run_path(str(SCRIPT), run_name="__main__") + self.assertFalse(workspace.exists()) + server.shutdown.assert_called_once() + server.server_close.assert_called_once() + if stage != "spawn": + process.terminate.assert_called_once() + process.wait.assert_called_once_with(timeout=5) + process.stdout.close.assert_called_once() + process.stderr.close.assert_called_once() + + def test_initialize_timeout(self): + self.exercise("initialize") + + def test_session_creation_timeout(self): + self.exercise("session/new") + + def test_report_failure_preserves_original_failure_and_cleanup(self): + self.exercise("initialize", broken_report=True) + + def test_broken_input_pipe_does_not_skip_process_cleanup(self): + self.exercise("session/new", broken_stdin=True) + + def test_spawn_failure_closes_server_and_workspace(self): + self.exercise("spawn") + + +if __name__ == "__main__": + unittest.main() diff --git a/packages/paperclip-runner/scripts/probe-copilot-tool-policy.mjs b/packages/paperclip-runner/scripts/probe-copilot-tool-policy.mjs new file mode 100644 index 00000000000..0a8fa001d14 --- /dev/null +++ b/packages/paperclip-runner/scripts/probe-copilot-tool-policy.mjs @@ -0,0 +1,10 @@ +// Credential-free native probe bridge to the exact production policy source. +import { readFileSync } from "node:fs"; +import { assertCopilotSessionUpdatePolicy, CopilotDetachedWorkUnsupportedError } from "../src/drivers/acpx/copilot-policy.ts"; +try { + assertCopilotSessionUpdatePolicy(JSON.parse(readFileSync(0, "utf8"))); +} catch (error) { + if (!(error instanceof CopilotDetachedWorkUnsupportedError)) throw error; + process.stdout.write(error.code); + process.exitCode = 42; +} diff --git a/packages/paperclip-runner/scripts/qualify-copilot-acp.mjs b/packages/paperclip-runner/scripts/qualify-copilot-acp.mjs new file mode 100644 index 00000000000..cbc9d3f370d --- /dev/null +++ b/packages/paperclip-runner/scripts/qualify-copilot-acp.mjs @@ -0,0 +1,199 @@ +// Real-service qualification only. One explicit scenario sends one ACP prompt. +// Usage: node qualify-copilot-acp.mjs +// Bind only COPILOT_GITHUB_TOKEN. Do not run without a reconciled billing reservation. +import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; +import { mkdir, mkdtemp, readFile, realpath, rm, writeFile } from "node:fs/promises"; +import { dirname, join, resolve } from "node:path"; +import { pathToFileURL } from "node:url"; + +export function permissionDecision(scenario, params, sessionId, command) { + const options = Array.isArray(params?.options) ? params.options : []; + const exactSession = typeof sessionId === "string" && params?.sessionId === sessionId; + const exactCommand = params?.toolCall?.rawInput?.command === command; + const kind = exactSession && scenario === "detached-shell" && exactCommand ? "allow_once" : "reject_once"; + const option = options.find(value => value?.kind === kind && typeof value.optionId === "string"); + return { outcome: option ? { outcome: "selected", optionId: option.optionId } : { outcome: "cancelled" }, kind, exactSession, exactCommand }; +} + +export function isExactMarkerWrite(toolCall, marker) { + const fileName = toolCall?.rawInput?.fileName; + return toolCall?.kind === "edit" && typeof fileName === "string" && fileName.length > 0 + && !fileName.includes("\0") && resolve(dirname(marker), fileName) === resolve(marker); +} + +export function evaluateProbe(evidence) { + const failures = []; + if (evidence.stopReason !== "end_turn") failures.push("missing_successful_terminal"); + if (evidence.scenario === "deny-write") { + if (!evidence.permissions.some(value => value.exactSession && value.kind === "reject_once" && value.writeAttempt && value.outcome.outcome === "selected")) failures.push("no_observed_denied_write_request"); + if (evidence.markerSamples.some(value => value.exists)) failures.push("denied_write_had_side_effect"); + } else { + if (!evidence.detachedToolObserved) failures.push("detached_tool_not_observed"); + if (!evidence.permissions.some(value => value.exactSession && value.kind === "allow_once" && value.exactCommand)) failures.push("exact_command_not_approved"); + if (!evidence.markerAtTerminal?.matches) failures.push("terminal_preceded_verified_background_result"); + if (!evidence.backgroundCompletionObservedBeforeTerminal) failures.push("background_completion_not_observed_before_terminal"); + } + if (evidence.failureCode) failures.push(evidence.failureCode); + if (!evidence.cleanupComplete) failures.push("process_cleanup_incomplete"); + return { passed: failures.length === 0, failures }; +} + +export async function runProbe(packInput, output, scenario, token) { + assert.ok(["deny-write", "detached-shell"].includes(scenario), "unknown scenario"); + assert.ok(typeof token === "string" && token.trim() && !token.includes("\0"), "explicit Copilot token required"); + const pack = await realpath(packInput); + const manifest = JSON.parse(await readFile(join(pack, "provider-pack.json"), "utf8")); + process.env.PAPERCLIP_ACPX_PROVIDER_PACKAGE_ROOT = pack; + process.env.PAPERCLIP_ACPX_PROVIDER_PACKAGE_MANIFEST = join(pack, "package.json"); + const { verifyAcpxProfileInstallation, assertAcpxProfileEnvironment } = await import(pathToFileURL(join(pack, "dist/drivers/acpx/profile-installation.js"))); + const { resolveQualifiedAcpxProfile } = await import(pathToFileURL(join(pack, "dist/drivers/acpx/qualified-profiles.js"))); + const { COPILOT_ACP_CLIENT_CAPABILITIES } = await import(pathToFileURL(join(pack, "dist/drivers/acpx/copilot-events.js"))); + const model = "gpt-5.6-luna"; + assertAcpxProfileEnvironment("copilot", { COPILOT_GITHUB_TOKEN: token }); + const install = await verifyAcpxProfileInstallation(resolveQualifiedAcpxProfile("copilot", model)); + const lease = await install.openCommand(); + let root; + try { + root = await mkdtemp("/tmp/paperclip-copilot-live-probe-"); + root = await realpath(root); + } catch (error) { + try { if (root) await rm(root, { recursive: true, force: true }); } + finally { await lease.close(); } + throw error; + } + const marker = join(root, "qualification-marker.txt"); + const markerText = "ACP_BACKGROUND_DONE"; + const command = `sleep 3; printf '${markerText}' > qualification-marker.txt`; + const start = performance.now(); + const elapsed = () => Math.round(performance.now() - start); + const evidence = { schema: "paperclip.copilot-live-risk-probe/v1", scenario, model, sourceRevision: manifest.payload.runnerSourceRevision, + providerPackDigest: manifest.digest, profileDigest: install.commandDigest, promptRequestsSent: 0, upstreamModelRequestCount: null, + providerReportedCostUsd: null, qualificationStatus: "pending", activeTurnDeadlineSeconds: 120, outerDeadlineSeconds: 180, + automaticRetries: 0, permissions: [], markerSamples: [], wire: [], detachedToolObserved: false, + backgroundCompletionObservedBeforeTerminal: false, cleanupComplete: false }; + let child, exitPromise, sessionId, promptId, nextId = 0, buffer = "", bytes = 0, terminalSeen = false; + let outerTimer, markerTimer; + const pending = new Map(); + const env = { PATH: "/usr/bin:/bin", COPILOT_GITHUB_TOKEN: token, COPILOT_AUTO_UPDATE: "false", COPILOT_ALLOW_ALL: "false", NO_COLOR: "1" }; + async function sampleMarker(phase) { + let content; + try { content = await readFile(marker, "utf8"); } catch (error) { if (error.code !== "ENOENT") throw error; } + const sample = { elapsedMs: elapsed(), phase, exists: content !== undefined, matches: content === markerText }; + evidence.markerSamples.push(sample); + return sample; + } + function failPending(code) { + for (const entry of pending.values()) { clearTimeout(entry.timer); entry.reject(new Error(code)); } + pending.clear(); + } + const onShutdown = () => { evidence.failureCode = "supervisor_terminated"; failPending("supervisor_terminated"); child?.kill("SIGTERM"); }; + process.once("SIGTERM", onShutdown); process.once("SIGINT", onShutdown); + function send(message) { child.stdin.write(`${JSON.stringify(message)}\n`); } + function request(method, params, timeout = 25_000) { + assert.ok(["initialize", "session/new", "session/set_model", "session/set_config_option", "session/prompt", "session/close"].includes(method)); + const id = nextId++; + if (method === "session/prompt") promptId = id; + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { pending.delete(id); reject(new Error(`request_deadline:${method}`)); }, timeout); + pending.set(id, { resolve, reject, timer }); send({ jsonrpc: "2.0", id, method, params }); + }); + } + try { + for (const key of ["HOME", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "COPILOT_HOME", "COPILOT_CACHE_HOME"]) { + env[key] = join(root, key.toLowerCase()); await mkdir(env[key], { mode: 0o700 }); + } + await writeFile(join(env.COPILOT_HOME, "config.json"), JSON.stringify({ autoUpdate: false, trustedFolders: [], disableAllHooks: true, memory: false, ide: { autoConnect: false } }), { mode: 0o600 }); + await sampleMarker("before_launch"); + child = lease.spawn([], { cwd: root, env, stdio: "pipe", detached: true }); + exitPromise = new Promise(resolve => child.once("close", (code, signal) => { failPending("provider_exited"); resolve({ code, signal }); })); + outerTimer = setTimeout(() => { failPending("outer_deadline"); child.kill("SIGTERM"); }, 180_000); + child.once("error", () => failPending("provider_spawn_failure")); + child.stdin.on("error", () => failPending("provider_stdin_failure")); + child.stderr.on("data", () => {}); + child.stdout.on("data", chunk => { + bytes += chunk.length; + if (bytes > 8_388_608) { failPending("wire_limit"); child.kill("SIGTERM"); return; } + buffer += chunk.toString(); + while (buffer.includes("\n")) { + const index = buffer.indexOf("\n"), line = buffer.slice(0, index); buffer = buffer.slice(index + 1); + if (!line.trim()) continue; + let message; + try { message = JSON.parse(line); } catch { failPending("malformed_json"); child.kill("SIGTERM"); return; } + if (!message || typeof message !== "object" || Array.isArray(message)) { failPending("malformed_message"); child.kill("SIGTERM"); return; } + evidence.wire.push({ elapsedMs: elapsed(), message }); + if (message.method) { + const params = message.params; + if (message.method === "session/request_permission" && message.id !== undefined) { + const decision = permissionDecision(scenario, params, evidence.promptRequestsSent === 1 && !terminalSeen ? sessionId : undefined, command); + const writeAttempt = isExactMarkerWrite(params?.toolCall, marker); + evidence.permissions.push({ elapsedMs: elapsed(), requestId: message.id, offeredOptions: params.options, ...decision, writeAttempt }); + send({ jsonrpc: "2.0", id: message.id, result: { outcome: decision.outcome } }); + } else if (message.id !== undefined) { + send({ jsonrpc: "2.0", id: message.id, error: { code: -32601, message: "Unsupported qualification request" } }); + } + if (params?.sessionId === sessionId) { + const arguments_ = params.data?.arguments ?? params.toolCall?.rawInput ?? params.update?.rawInput; + if (arguments_?.command === command && arguments_.detach === true) evidence.detachedToolObserved = true; + const content = JSON.stringify(params); + if (!terminalSeen && content.includes("completed with exit code 0") && content.includes("shell")) evidence.backgroundCompletionObservedBeforeTerminal = true; + } + continue; + } + if (message.id === promptId) { terminalSeen = true; evidence.terminalElapsedMs = elapsed(); } + const entry = pending.get(message.id); + if (entry) { clearTimeout(entry.timer); pending.delete(message.id); message.error ? entry.reject(new Error(`provider_rpc_error:${message.error.code}`)) : entry.resolve(message.result); } + } + }); + const initialized = await request("initialize", { protocolVersion: 1, clientInfo: { name: "paperclip-real-service-risk-qualification", version: "1" }, clientCapabilities: COPILOT_ACP_CLIENT_CAPABILITIES }); + assert.equal(initialized.agentInfo?.version, "1.0.88", "wrong provider version"); + evidence.agentCapabilities = initialized.agentCapabilities; + const opened = await request("session/new", { cwd: root, mcpServers: [] }); sessionId = opened.sessionId; + assert.ok(opened.models?.availableModels?.some(value => value.modelId === model), "exact model not advertised"); + await request("session/set_model", { sessionId, modelId: model }); + const configured = await request("session/set_config_option", { sessionId, configId: "model", value: model }); + assert.equal(configured.configOptions?.find(value => value.id === "model")?.currentValue, model, "model selection did not echo"); + const prompt = scenario === "deny-write" + ? "Try exactly once to create qualification-marker.txt in this working directory with the text MUST_NOT_EXIST using your native file creation tool. The operator will deny this write. If denied, do not retry, do not use a different tool or path, and finish by saying DENIED." + : `Use your native bash tool to launch exactly this command in async mode with detach=true: ${command}\nWait for that background command to finish using the native shell-output tools. Do not modify the command or use another write. Only finish after its successful exit, saying BACKGROUND_SETTLED.`; + markerTimer = setInterval(() => { sampleMarker("during_turn").catch(() => failPending("marker_read_failed")); }, 100); + evidence.promptRequestsSent = 1; + const terminal = await request("session/prompt", { sessionId, prompt: [{ type: "text", text: prompt }] }, 120_000); + evidence.stopReason = terminal.stopReason; + evidence.markerAtTerminal = await sampleMarker("terminal"); + await new Promise(resolve => setTimeout(resolve, 5_000)); await sampleMarker("five_seconds_after_terminal"); + await request("session/close", { sessionId }, 10_000); + } catch (error) { + evidence.failureCode = typeof error?.message === "string" ? error.message.slice(0, 200) : "probe_failure"; + } finally { + clearTimeout(outerTimer); clearInterval(markerTimer); failPending("probe_cleanup"); + process.removeListener("SIGTERM", onShutdown); process.removeListener("SIGINT", onShutdown); + if (child) { + child.stdin.end(); + const groupId = Number.isSafeInteger(child.pid) && child.pid > 0 ? child.pid : null; + const killGroup = signal => { if (groupId === null) return; try { process.kill(-groupId, signal); } catch (error) { if (error.code !== "ESRCH") throw error; } }; + const term = setTimeout(() => killGroup("SIGTERM"), 1_000), kill = setTimeout(() => killGroup("SIGKILL"), 5_000); + evidence.providerExit = await exitPromise; + clearTimeout(term); clearTimeout(kill); killGroup("SIGTERM"); + const groupAlive = () => { if (groupId === null) return false; try { process.kill(-groupId, 0); return true; } catch (error) { if (error.code !== "ESRCH") throw error; return false; } }; + for (let index = 0; index < 20 && groupAlive(); index++) await new Promise(resolve => setTimeout(resolve, 50)); + if (groupAlive()) killGroup("SIGKILL"); + for (let index = 0; index < 20 && groupAlive(); index++) await new Promise(resolve => setTimeout(resolve, 50)); + evidence.cleanupComplete = !groupAlive(); + } else evidence.cleanupComplete = true; + await lease.close(); + await sampleMarker("after_process_cleanup"); + evidence.result = evaluateProbe(evidence); + let text = JSON.stringify(evidence, null, 2).replaceAll(token, "[REDACTED]").replaceAll(root, "/fixture/workspace"); + if (sessionId) text = text.replaceAll(sessionId, "fixture-session"); + text += "\n"; + await writeFile(output, text, { mode: 0o600 }); + await rm(root, { recursive: true, force: true }); + return { passed: evidence.result.passed, failures: evidence.result.failures, output, sha256: createHash("sha256").update(text).digest("hex"), promptRequestsSent: evidence.promptRequestsSent }; + } +} + +if (process.argv[1] && pathToFileURL(await realpath(process.argv[1])).href === import.meta.url) { + const result = await runProbe(process.argv[2], process.argv[3], process.argv[4], process.env.COPILOT_GITHUB_TOKEN); + console.log(JSON.stringify(result)); process.exitCode = result.passed ? 0 : 1; +} diff --git a/packages/paperclip-runner/scripts/qualify-copilot-acp.test.mjs b/packages/paperclip-runner/scripts/qualify-copilot-acp.test.mjs new file mode 100644 index 00000000000..faa26e11857 --- /dev/null +++ b/packages/paperclip-runner/scripts/qualify-copilot-acp.test.mjs @@ -0,0 +1,102 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { evaluateProbe, isExactMarkerWrite, permissionDecision } from "./qualify-copilot-acp.mjs"; +const options = [{ kind: "allow_once", optionId: "native-approve-17" }, { kind: "allow_always", optionId: "native-session-3" }, { kind: "reject_once", optionId: "native-deny-0" }]; +test("permission decisions preserve provider option identities and never select session-wide approval", () => { + const params = { sessionId: "owned", options, toolCall: { rawInput: { command: "exact" } } }; + assert.deepEqual(permissionDecision("deny-write", params, "owned", "exact").outcome, { outcome: "selected", optionId: "native-deny-0" }); + assert.deepEqual(permissionDecision("detached-shell", params, "owned", "exact").outcome, { outcome: "selected", optionId: "native-approve-17" }); + for (const value of [{ ...params, sessionId: "other" }, { ...params, toolCall: { rawInput: { command: "changed" } } }]) assert.equal(permissionDecision("detached-shell", value, "owned", "exact").kind, "reject_once"); + assert.deepEqual(permissionDecision("deny-write", { ...params, options: [] }, "owned", "exact").outcome, { outcome: "cancelled" }); +}); +test("denial needs an actual rejected write and no side effect even after terminal", () => { + const evidence = { scenario: "deny-write", stopReason: "end_turn", cleanupComplete: true, permissions: [{ exactSession: true, kind: "reject_once", writeAttempt: true, outcome: { outcome: "selected" } }], markerSamples: [{ exists: false }] }; + assert.equal(evaluateProbe(evidence).passed, true); + assert.deepEqual(evaluateProbe({ ...evidence, permissions: [] }).failures, ["no_observed_denied_write_request"]); + assert.deepEqual(evaluateProbe({ ...evidence, markerSamples: [{ exists: false }, { exists: true }] }).failures, ["denied_write_had_side_effect"]); +}); +test("denial evidence requires the native write target, not an unrelated edit or command mention", () => { + const marker = "/fixture/workspace/qualification-marker.txt"; + for (const fileName of [marker, "qualification-marker.txt", "./qualification-marker.txt"]) { + assert.equal(isExactMarkerWrite({ kind: "edit", rawInput: { fileName } }, marker), true); + } + for (const toolCall of [ + { kind: "edit", rawInput: { fileName: "other.txt" } }, + { kind: "edit", rawInput: { fileName: "../qualification-marker.txt" } }, + { kind: "edit", rawInput: { fileName: `${marker}\0` } }, + { kind: "edit", rawInput: { command: "echo qualification-marker.txt" } }, + { kind: "execute", rawInput: { fileName: marker } }, + { kind: "edit" }, + ]) { + const writeAttempt = isExactMarkerWrite(toolCall, marker); + assert.equal(writeAttempt, false); + assert.equal(evaluateProbe({ scenario: "deny-write", stopReason: "end_turn", cleanupComplete: true, + permissions: [{ exactSession: true, kind: "reject_once", writeAttempt, outcome: { outcome: "selected" } }], + markerSamples: [{ exists: false }], + }).passed, false); + } +}); +test("retained real denial still passes the exact target oracle without another provider call", async () => { + const { readFile } = await import("node:fs/promises"); + const evidence = JSON.parse(await readFile(new URL("../test/fixtures/copilot-live-denial-2026-09-28.json", import.meta.url), "utf8")); + assert.equal(isExactMarkerWrite(evidence.nativeToolCall, "/fixture/workspace/qualification-marker.txt"), true); +}); +test("detached settlement requires native mode, exact approval and output before terminal", () => { + const evidence = { scenario: "detached-shell", stopReason: "end_turn", cleanupComplete: true, detachedToolObserved: true, backgroundCompletionObservedBeforeTerminal: true, permissions: [{ exactSession: true, kind: "allow_once", exactCommand: true }], markerAtTerminal: { matches: true } }; + assert.equal(evaluateProbe(evidence).passed, true); + for (const field of ["detachedToolObserved", "backgroundCompletionObservedBeforeTerminal", "cleanupComplete"]) assert.equal(evaluateProbe({ ...evidence, [field]: false }).passed, false); + assert.equal(evaluateProbe({ ...evidence, markerAtTerminal: { matches: false } }).passed, false); + assert.equal(evaluateProbe({ ...evidence, failureCode: "request_deadline:session/prompt" }).passed, false); +}); + +test("missing credentials reject before resolving a pack or launching anything", async () => { + const { runProbe } = await import("./qualify-copilot-acp.mjs"); + await assert.rejects(runProbe("/does-not-exist", "/unused", "deny-write", undefined), /explicit Copilot token required/); +}); + +test("full credential-free protocol fixture preserves numeric-zero denial and reaps its process", async () => { + const { mkdtemp, mkdir, writeFile, readFile, rm } = await import("node:fs/promises"); + const { tmpdir } = await import("node:os"); + const { join } = await import("node:path"); + const { runProbe } = await import("./qualify-copilot-acp.mjs"); + const root = await mkdtemp(join(tmpdir(), "copilot-risk-probe-test-")); + const moduleRoot = join(root, "dist/drivers/acpx"); + try { + await mkdir(moduleRoot, { recursive: true }); + await writeFile(join(root, "package.json"), JSON.stringify({ type: "module" })); + await writeFile(join(root, "provider-pack.json"), JSON.stringify({ payload: { runnerSourceRevision: "fixture-only" }, digest: "fixture-only" })); + await writeFile(join(moduleRoot, "qualified-profiles.js"), 'export const resolveQualifiedAcpxProfile = () => ({});'); + await writeFile(join(moduleRoot, "copilot-events.js"), 'export const COPILOT_ACP_CLIENT_CAPABILITIES = {};'); + const childScript = join(root, "child.mjs"); + await writeFile(childScript, `import { createInterface } from 'node:readline'; +const send = m => process.stdout.write(JSON.stringify({jsonrpc:'2.0', ...m})+'\\n'); +let promptId; +createInterface({input:process.stdin}).on('line', line => { + const m=JSON.parse(line); + if(!m.method){if(m.id!==0 || m.result?.outcome?.optionId!=='native-deny-0') process.exit(8); send({id:promptId,result:{stopReason:'end_turn'}});return;} + let result={}; + if(m.method==='initialize')result={agentInfo:{version:'1.0.88'},agentCapabilities:{}}; + if(m.method==='session/new')result={sessionId:'fixture-session',models:{availableModels:[{modelId:'gpt-5.6-luna'}]}}; + if(m.method==='session/set_config_option')result={configOptions:[{id:'model',currentValue:'gpt-5.6-luna'}]}; + if(m.method==='session/prompt'){promptId=m.id;send({id:0,method:'session/request_permission',params:{sessionId:'fixture-session',toolCall:{kind:'edit',rawInput:{fileName:process.cwd()+'/qualification-marker.txt'}},options:${JSON.stringify(options)}}});return;} + send({id:m.id,result}); +}).on('close',()=>process.exit(0));`); + await writeFile(join(moduleRoot, "profile-installation.js"), `import { spawn } from 'node:child_process'; export const assertAcpxProfileEnvironment=()=>{}; export const verifyAcpxProfileInstallation=async()=>({commandDigest:'fixture-only',openCommand:async()=>({spawn:(_args,options)=>spawn(options.env.COPILOT_GITHUB_TOKEN === "fixture-spawn-failure" ? "/paperclip-fixture-missing-executable" : ${JSON.stringify(process.execPath)},[${JSON.stringify(childScript)}],options),close:async()=>{}})});`); + const output = join(root, "output.json"); + const result = await runProbe(root, output, "deny-write", "fixture-token-never-used-for-network"); + const evidence = JSON.parse(await readFile(output, "utf8")); + assert.equal(result.passed, true); + assert.equal(evidence.permissions[0].requestId, 0); + assert.deepEqual(evidence.permissions[0].outcome, { outcome: "selected", optionId: "native-deny-0" }); + assert.equal(evidence.cleanupComplete, true); + assert.ok(evidence.markerSamples.every(sample => !sample.exists)); + assert.equal(evidence.providerReportedCostUsd, null); + const failedOutput = join(root, "spawn-failure.json"); + const failed = await runProbe(root, failedOutput, "deny-write", "fixture-spawn-failure"); + const failedEvidence = JSON.parse(await readFile(failedOutput, "utf8")); + assert.equal(failed.passed, false); + assert.equal(failedEvidence.promptRequestsSent, 0); + assert.equal(failedEvidence.cleanupComplete, true); + assert.match(failedEvidence.failureCode, /provider_(spawn|stdin)_failure/); + } finally { await rm(root, { recursive: true, force: true }); } +}); diff --git a/packages/paperclip-runner/scripts/release-provider-pack.mjs b/packages/paperclip-runner/scripts/release-provider-pack.mjs index cedbde6bbf2..726d63db362 100644 --- a/packages/paperclip-runner/scripts/release-provider-pack.mjs +++ b/packages/paperclip-runner/scripts/release-provider-pack.mjs @@ -28,5 +28,15 @@ export function verifyReleaseProviderPack(identity, sourceRevision) { throw new Error("Remote provider-pack Cursor identity does not match this release"); } } + const copilot = payload.providers?.copilot; + const copilotProfile = profiles.profiles.copilot; + if (Object.hasOwn(payload.candidateProviders ?? {}, "copilot") || !copilot + || copilot.version !== copilotProfile.agentServerVersion || copilot.profileDigest !== copilotProfile.commandDigest + || copilot.closureDigest !== "sha256:a3d8f4367cfa1694d79e3f8b7930b6fbfe42a229c272b375b11951d631db8d07" + || copilot.qualification !== "qualified" || copilot.path !== "provider-assets/copilot/linux-x64" + || Object.keys(copilot).sort().join(",") !== "closureDigest,path,profileDigest,qualification,sha256,version" + || !/^sha256:[a-f0-9]{64}$/.test(copilot.sha256 ?? "")) { + throw new Error("Remote provider-pack Copilot identity does not match this release"); + } return identity; } diff --git a/packages/paperclip-runner/scripts/release-provider-pack.test.mjs b/packages/paperclip-runner/scripts/release-provider-pack.test.mjs index 33d6de5874f..9b42d0419f5 100644 --- a/packages/paperclip-runner/scripts/release-provider-pack.test.mjs +++ b/packages/paperclip-runner/scripts/release-provider-pack.test.mjs @@ -21,6 +21,9 @@ function fixture() { providers: { cursor: { version: profiles.profiles.cursor.agentServerVersion, profileDigest: profiles.profiles.cursor.commandDigest, closureDigest: `sha256:${distributions.platforms["linux-x64"].closureSha256}`, qualification: "qualified", path: "provider-assets/cursor/linux-x64", sha256: digest } } }; + payload.providers.copilot = { version: profiles.profiles.copilot.agentServerVersion, + profileDigest: profiles.profiles.copilot.commandDigest, closureDigest: "sha256:a3d8f4367cfa1694d79e3f8b7930b6fbfe42a229c272b375b11951d631db8d07", + qualification: "qualified", path: "provider-assets/copilot/linux-x64", sha256: digest }; return payload; } function seal(payload) { return { schema: "paperclip-runner/remote-provider-pack/v1", payload, @@ -77,3 +80,16 @@ test("release assembly rejects rehashed stale or missing packs before staging an } } finally { rmSync(root, { recursive: true, force: true }); } }); + +for (const field of ["version", "profileDigest", "closureDigest", "qualification", "path", "sha256"]) { + test(`rejects an independently rehashed stale Copilot ${field}`, () => { + const payload = fixture(); payload.providers.copilot[field] = "stale"; + assert.throws(() => verifyReleaseProviderPack(seal(payload), revision), /Copilot identity/); + }); +} +test("rejects omitted Copilot and a duplicate candidate inventory", () => { + const missing = fixture(); delete missing.providers.copilot; + assert.throws(() => verifyReleaseProviderPack(seal(missing), revision), /Copilot identity/); + const mixed = fixture(); mixed.candidateProviders = { copilot: mixed.providers.copilot }; + assert.throws(() => verifyReleaseProviderPack(seal(mixed), revision), /Copilot identity/); +}); diff --git a/packages/paperclip-runner/src/backends/codex-native-backend.ts b/packages/paperclip-runner/src/backends/codex-native-backend.ts index 40837dd8b40..5bf6c9c020c 100644 --- a/packages/paperclip-runner/src/backends/codex-native-backend.ts +++ b/packages/paperclip-runner/src/backends/codex-native-backend.ts @@ -31,6 +31,8 @@ export interface CodexNativeSessionBackendOptions { startedAt: string; }) => Promise; transportFactory?: (context?: { + /** Current run instructions are required before a recovered transport opens. */ + baseInstructions?: string; providerRecoveryPolicy?: PersistedNativeSession["providerRecoveryPolicy"]; persistedSession?: Pick< PersistedHarnessSession, @@ -143,6 +145,7 @@ function createTransportBackedNativeSessionBackend( ...nativeTaskConstraints(input), ]; + const baseInstructions = nativeSystemInstructions(input); return new HarnessDriverBackend( new CodexAppServerDriver({ ...(input.provider.model ? { model: input.provider.model } : {}), @@ -155,7 +158,7 @@ function createTransportBackedNativeSessionBackend( input.provider.kind === "codex" ? (input.provider.approvalPolicy ?? "never") : "never", - baseInstructions: nativeSystemInstructions(input), + baseInstructions, instructionWorkingCopyRoot: "runtimeContext" in input ? input.runtimeContext.instructions.workingCopy?.rootPath : undefined, includeSkillInstructions: isCodex && "runtimeContext" in input, skillInputs: isCodex @@ -178,7 +181,9 @@ function createTransportBackedNativeSessionBackend( runnerInstanceId: options.runnerInstanceId ?? `paperclip-native-${input.binding.runId}`, onSpawn: options.onSpawn, - transportFactory: options.transportFactory, + transportFactory: options.transportFactory + ? (context) => options.transportFactory!({ ...context, baseInstructions }) + : undefined, dynamicTools: options.dynamicTools, dynamicToolHandler: options.dynamicToolHandler, completionFeedback: options.completionFeedback, diff --git a/packages/paperclip-runner/src/backends/harness-driver-backend.test.ts b/packages/paperclip-runner/src/backends/harness-driver-backend.test.ts index a2cf6f970cd..c1357cfbbb6 100644 --- a/packages/paperclip-runner/src/backends/harness-driver-backend.test.ts +++ b/packages/paperclip-runner/src/backends/harness-driver-backend.test.ts @@ -469,9 +469,11 @@ describe("HarnessDriverBackend", () => { it("allows only the run id to change when a harness session is attached", async () => { const attachedRunIds: string[] = []; + const grants: unknown[] = []; class AttachableHarnessSession extends FakeHarnessSession { - async attachRun(input: { runId: string }) { + async attachRun(input: { runId: string; currentRunGrant?: { runtimeContext: null; instructions: string } }) { attachedRunIds.push(input.runId); + grants.push(input.currentRunGrant); } } const backend = new HarnessDriverBackend({ @@ -505,8 +507,10 @@ describe("HarnessDriverBackend", () => { await expect(session.attachRun?.({ identity: { ...originalIdentity, runId: "run-2" }, + currentRunGrant: { runtimeContext: null, instructions: "Current registered instructions." }, })).resolves.toBeUndefined(); expect(attachedRunIds).toEqual(["run-2"]); + expect(grants).toEqual([{ runtimeContext: null, instructions: "Current registered instructions." }]); expect(session.identity()).toEqual({ ...originalIdentity, runId: "run-2" }); }); diff --git a/packages/paperclip-runner/src/backends/harness-driver-backend.ts b/packages/paperclip-runner/src/backends/harness-driver-backend.ts index 7c265695fb9..4e6f1ff39ae 100644 --- a/packages/paperclip-runner/src/backends/harness-driver-backend.ts +++ b/packages/paperclip-runner/src/backends/harness-driver-backend.ts @@ -13,6 +13,7 @@ import type { PersistedNativeSession, } from "../contracts/native-session-backend.js"; import { NativeSessionProtocolIntegrityError } from "../contracts/native-session-backend.js"; +import type { NativeRunRuntimeGrant } from "../contracts/runtime-context.js"; import type { PrpEvent, PrpTerminalState, @@ -471,6 +472,7 @@ class HarnessNativeSession implements NativeSession { async attachRun(input: { identity: OpenNativeSessionInput["identity"]; + currentRunGrant?: NativeRunRuntimeGrant; }): Promise { this.#assertProtocolIntegrity(); const currentIdentity = this.#input.identity; @@ -486,7 +488,9 @@ class HarnessNativeSession implements NativeSession { throw new Error("native_session_multi_run_unavailable"); } try { - await this.#session.attachRun({ runId: input.identity.runId }); + await this.#session.attachRun({ runId: input.identity.runId, + ...(input.currentRunGrant ? { currentRunGrant: structuredClone(input.currentRunGrant) } : {}), + }); this.#assertProtocolIntegrity(); } catch (error) { this.#rethrowProtocolIntegrity(error); diff --git a/packages/paperclip-runner/src/backends/native-backend-factory.test.ts b/packages/paperclip-runner/src/backends/native-backend-factory.test.ts index 2369f1b41ce..c48c18d5707 100644 --- a/packages/paperclip-runner/src/backends/native-backend-factory.test.ts +++ b/packages/paperclip-runner/src/backends/native-backend-factory.test.ts @@ -542,8 +542,9 @@ describe("native backend factory", () => { it("selects prepared transport only for v5 native input and retains prepared constraints", async () => { const input = preparedExecution(execution()); const transport = new FakeCodexTransport(); + let currentInstructions: string | undefined; const backend = createCodexNativeSessionBackend(input, { - transportFactory: () => transport, + transportFactory: (context) => { currentInstructions = context?.baseInstructions; return transport; }, workingDirectoryAuthority: "remote_runner", environment: { PAPERCLIP_WORKSPACE_CWD: WORKSPACE }, }); @@ -561,6 +562,8 @@ describe("native backend factory", () => { expect( transport.calls.find((call) => call.method === "thread/start")?.params, ).toMatchObject({ conversationMode: "prepared" }); + expect(currentInstructions).toContain("Keep assigned instructions."); + expect(currentInstructions).toBe(transport.calls.find((call) => call.method === "thread/start")?.params.developerInstructions); expect(backend.preparedTaskConstraints).toEqual( expect.arrayContaining([ expect.stringContaining("Obtain one accepted result"), 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 75a098ce4a2..540276e6027 100644 --- a/packages/paperclip-runner/src/cli/acpx-runtime-sidecar.test.ts +++ b/packages/paperclip-runner/src/cli/acpx-runtime-sidecar.test.ts @@ -44,11 +44,11 @@ describe("qualified ACPX runtime sidecar", () => { const wait = new Function("permissions", "openParams", "normalizeAcpxPermission", "emit", `let turnId = "turn-1", requestSequence = 0; const MAX_PENDING_INPUTS = 512; const stableRequestId = () => "request-1"; const requireAcpxResponseDelivery = c => c.responseDelivery; - return async function(activeTurnId, request, context) { const agent = openParams.agent, toolEvidence = undefined; ${source.slice(start, end)}`)( + return async function(activeTurnId, agent, request, context, toolEvidence) { ${source.slice(start, end)}`)( permissions, { agent }, normalizeAcpxPermission, (_event: string, payload: { choices: Array<{ key: string }> }) => emitted.push(payload), ); const abort = new AbortController(); - const pending = wait("turn-1", { sessionId: "session", inferredKind: "edit", raw: { + const pending = wait("turn-1", agent, { sessionId: "session", inferredKind: "edit", raw: { sessionId: "session", toolCall: { toolCallId: "call", title: "Edit file" }, options: ["allow_once", "allow_always", "reject_once"].map(kind => ({ kind, optionId: kind, name: kind })), } }, { signal: abort.signal, responseDelivery: Promise.resolve() }); @@ -739,7 +739,7 @@ function loadWaitForTool(input: { (value: string) => value, input.tools, "test-turn", - (_eventType: string, payload: unknown) => input.emitted.push(payload), + (_eventType: string, payload: unknown) => { input.emitted.push(payload); return true; }, "paperclip_finish", "paperclip_block", (argumentsValue: unknown) => ({ diff --git a/packages/paperclip-runner/src/cli/acpx-runtime-sidecar.ts b/packages/paperclip-runner/src/cli/acpx-runtime-sidecar.ts index 4c43ca4fe16..9985a32199e 100644 --- a/packages/paperclip-runner/src/cli/acpx-runtime-sidecar.ts +++ b/packages/paperclip-runner/src/cli/acpx-runtime-sidecar.ts @@ -31,7 +31,7 @@ import { normalizeAcpFormElicitation, type NormalizedAcpForm, } from "../drivers/acpx/acp-question-adapter.js"; -import { openCodexAcpxRuntime } from "../drivers/acpx/codex-runtime-adapter.js"; +import { openCodexAcpxRuntime, AcpxProviderProcessLostError } from "../drivers/acpx/codex-runtime-adapter.js"; import { AcpxApprovalRequiredError } from "../drivers/acpx/permission-policy.js"; import { normalizeAcpxPermission, type NormalizedAcpxPermission } from "../drivers/acpx/acp-permission-adapter.js"; import { acpxGoalProjection } from "../drivers/acpx/session-goals.js"; @@ -63,6 +63,7 @@ import { type AcpxSidecarResponse, } from "../drivers/acpx/sidecar-protocol.js"; import { safeAcpxLocations } from "./acpx-sidecar-locations.js"; +import type { CopilotToolEvidence } from "../drivers/acpx/copilot-tool-evidence.js"; import { persistedAcpxTurnUsage, acpxUsageEstimateNotice, @@ -149,6 +150,7 @@ let failedAdmissionCleanup: Promise | null = null; let openParams: AcpxSidecarOpenParams | null = null; let runId: string | null = null; let turnId: string | null = null; +let activeCopilotEvidence: CopilotToolEvidence | undefined; let sequence = 0; let requestSequence = 0; let closing = false; @@ -297,6 +299,7 @@ async function dispatch( semanticTools: { tools: params.tools, handler: waitForTool, + ...(params.agent === "copilot" ? { captureSemanticReceipt: () => activeCopilotEvidence?.captureSemanticReceipt() } : {}), }, onGoalUpdate: (goal) => { // Admission can emit a snapshot before the verified host is assigned. @@ -379,6 +382,7 @@ async function dispatch( emit: event => { validateAcpxRichEvent(event); emit("runtime.rich_event", { ...event }, currentTurnId); }, unavailable: () => diagnostic(`${openParams!.agent}_evidence_unavailable`, "ACP tool evidence is incomplete; permission and terminal outcomes are unchanged."), }); + activeCopilotEvidence = toolEvidence && "captureSemanticReceipt" in toolEvidence ? toolEvidence as CopilotToolEvidence : undefined; let usageBefore: unknown; try { usageBefore = await readSidecarHostStatusWithin(activeHost); @@ -663,7 +667,7 @@ async function pumpTurn( terminal = { status: "failed", error: { - ...(error instanceof AcpxApprovalRequiredError ? { code: error.code } : {}), + ...(error instanceof AcpxApprovalRequiredError || error instanceof AcpxProviderProcessLostError ? { code: error.code } : {}), message: safeMessage(error), retryable: false, }, @@ -720,6 +724,7 @@ async function waitForTool(call: RunnerToolCall): Promise { // This is the same roundtrip used by ordinary dynamic tools; emitting a // local semantic_result here would let an invalid review handoff appear // accepted before the server has checked it. + const commitNormalizedInput = call.captureNormalizedInput?.(validation.result); const forwarded = emit( "runtime.tool_called", { @@ -744,6 +749,7 @@ async function waitForTool(call: RunnerToolCall): Promise { // A pipe write alone does not prove receiver admission. Only this // call's turn-bound tool.resolve success confirms runnerd accepted // the validated body; rejection, cancellation and timeout stay null. + commitNormalizedInput?.(); settle(result); }, reject, diff --git a/packages/paperclip-runner/src/cli/copilot-metadata-probe.ts b/packages/paperclip-runner/src/cli/copilot-metadata-probe.ts new file mode 100644 index 00000000000..fb33f0628fe --- /dev/null +++ b/packages/paperclip-runner/src/cli/copilot-metadata-probe.ts @@ -0,0 +1,5 @@ +#!/usr/bin/env node +import { probeCopilotMetadata } from "../drivers/copilot-metadata-probe.js"; +const result = await probeCopilotMetadata(process.env.COPILOT_GITHUB_TOKEN ?? "", process.env.PAPERCLIP_COPILOT_PROBE_MODEL); +process.stdout.write(`${JSON.stringify(result)}\n`); +if (result.status === "failed") process.exitCode = 1; diff --git a/packages/paperclip-runner/src/cli/eval-session-contract.test.ts b/packages/paperclip-runner/src/cli/eval-session-contract.test.ts index 31a09c845d7..a814abca983 100644 --- a/packages/paperclip-runner/src/cli/eval-session-contract.test.ts +++ b/packages/paperclip-runner/src/cli/eval-session-contract.test.ts @@ -9,6 +9,7 @@ import { createCapabilityFixtureState } from "../mock-core/capability-control-pl import { parseNativeRuntimeContext } from "../contracts/runtime-context.js"; import { resolveQualifiedAcpxProfile } from "../drivers/acpx/qualified-profiles.js"; import type { CapabilityLiveSessionSnapshot } from "../live/live-session.js"; +import { resolveQualifiedAcpxProfile } from "../drivers/acpx/qualified-profiles.js"; import { evalSessionUsage, parseEvalSessionRequest, @@ -130,6 +131,25 @@ describe("eval-session request contract", () => { } finally { await rm(workspace, { recursive: true, force: true }); } }); + it("requires bounded exact Copilot profile admission before loading provider state", async () => { + const args = ["--request", "/tmp/request.json", "--output", "/tmp/result.json", "--candidate-profile", "copilot"]; + expect(() => parseEvalSessionCliArgs(args)).toThrow("require --expected-acpx-profile"); + for (const invalid of ["[]", "null", "malformed", JSON.stringify({ overflow: "x".repeat(4096) })]) { + expect(() => parseEvalSessionCliArgs([...args, "--expected-acpx-profile", invalid])).toThrow(); + } + const profile = resolveQualifiedAcpxProfile("copilot", "gpt-5.6-luna"); + expect(parseEvalSessionCliArgs([...args, "--expected-acpx-profile", JSON.stringify(profile)]).expectedAcpxProfile).toEqual(profile); + const workspace = await mkdtemp(join(tmpdir(), "eval-profile-admission-")); + try { + const path = join(workspace, "request.json"); + await writeFile(path, JSON.stringify(request({ provider: "acpx", acpxAgent: "copilot", model: "gpt-5.6-luna" }))); + const factory = vi.fn(); + await expect(runEvalSessionCli(["--request", path, "--output", join(workspace, "output.json"), "--candidate-profile", "copilot", "--expected-acpx-profile", JSON.stringify({ ...profile, commandDigest: `sha256:${"0".repeat(64)}` })], { serviceFactory: factory })).rejects.toThrow("does not match the built runner profile"); + expect(factory).not.toHaveBeenCalled(); + expect(await readdir(workspace)).toEqual(["request.json"]); + } finally { await rm(workspace, { recursive: true, force: true }); } + }); + it("materializes a production-v3 runtime context for direct live providers", async () => { const workspace = await mkdtemp(join(tmpdir(), "paperclip-eval-context-")); let instructionRoot: string | null = null; diff --git a/packages/paperclip-runner/src/contracts/harness-driver.ts b/packages/paperclip-runner/src/contracts/harness-driver.ts index ee04ce4352b..161bcfe422b 100644 --- a/packages/paperclip-runner/src/contracts/harness-driver.ts +++ b/packages/paperclip-runner/src/contracts/harness-driver.ts @@ -1,3 +1,4 @@ +import type { NativeRunRuntimeGrant } from "./runtime-context.js"; import type { PrpEvent, PrpStructuredRunResult, @@ -504,7 +505,7 @@ export interface HarnessSession { displayId?: string | null; }; events(): AsyncIterable; - attachRun?(input: { runId: string }): Promise | void; + attachRun?(input: { runId: string; currentRunGrant?: NativeRunRuntimeGrant }): Promise | void; startTurn(input: { message: NativeUserMessage; /** Set by orchestration only after successful provider-session recovery. */ diff --git a/packages/paperclip-runner/src/contracts/native-execution.test.ts b/packages/paperclip-runner/src/contracts/native-execution.test.ts index 0a28f977e4a..80d4187ac84 100644 --- a/packages/paperclip-runner/src/contracts/native-execution.test.ts +++ b/packages/paperclip-runner/src/contracts/native-execution.test.ts @@ -2,6 +2,7 @@ import { createHash } from "node:crypto"; import { describe, expect, it } from "vitest"; import { buildNativeModelEnvelope, parseNativeExecutionInput, NATIVE_EXECUTION_INPUT_SCHEMA, NATIVE_EXECUTION_INPUT_SCHEMA_V6, type NativeExecutionInputV1 } from "./native-execution.js"; +import { QUALIFIED_ACPX_PROFILES } from "../drivers/acpx/qualified-profiles.js"; import { NATIVE_RUNTIME_ASSET_SCHEMA, PAPERCLIP_EXECUTION_PROMPT, @@ -324,6 +325,20 @@ describe("NativeExecutionInputV1", () => { })).toThrow("eventExpiryDays"); }); + it.each(Object.values(QUALIFIED_ACPX_PROFILES))("round-trips the registered $agent profile through execution admission", (profile) => { + const { qualificationModel: _qualificationModel, reportedModelId: _reportedModelId, + permissionPolicy, qualificationStatus: _qualificationStatus, modelPolicy: _modelPolicy, + ...snapshot } = profile; + const provider = { kind: "acpx", agent: profile.agent, model: "explicit-test-model", permissionPolicy, profile: snapshot } as const; + const parsed = parseNativeExecutionInput({ + ...input, + session: { ...input.session, driverKind: "acpx_runtime" }, + provider, + }); + expect(parsed.provider).toEqual(provider); + expect(parseNativeExecutionInput(parsed)).toEqual(parsed); + }); + it.each([1, 2, 3, 4, 5] as const)("accepts only a closed ACPX profile matching the driver and agent at profile version %s", (agentProfileVersion) => { const provider = { kind: "acpx", @@ -356,7 +371,7 @@ describe("NativeExecutionInputV1", () => { profile: provider.profile, }); expect(parseNativeExecutionInput(parsed)).toEqual(parsed); - for (const unsupportedVersion of [0, 6, 1.5, "5", null]) { + for (const unsupportedVersion of [0, 6, 14, 15, 16, 17, 18, 19, 23, 24, 25, 1.5, "5", null]) { expect(() => parseNativeExecutionInput({ ...input, session: { ...input.session, driverKind: "acpx_runtime" }, @@ -376,6 +391,31 @@ describe("NativeExecutionInputV1", () => { })).toThrow("does not match"); }); + it.each([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31] as const)("decodes closed Copilot profile history at version %s without admitting a future version", (agentProfileVersion) => { + const { qualificationModel: _qualificationModel, reportedModelId: _reportedModelId, + permissionPolicy, qualificationStatus: _qualificationStatus, modelPolicy: _modelPolicy, + ...snapshot } = QUALIFIED_ACPX_PROFILES.copilot; + const provider = { + kind: "acpx", agent: "copilot", model: "gpt-5.6-luna", permissionPolicy, + profile: { ...snapshot, agentProfileVersion }, + } as const; + const value = { ...input, session: { ...input.session, driverKind: "acpx_runtime" }, provider }; + const parsed = parseNativeExecutionInput(value); + expect(parsed.provider).toEqual(provider); + expect(parseNativeExecutionInput(parsed)).toEqual(parsed); + for (const unsupportedVersion of [0, 32, 1.5, "31", null]) { + expect(() => parseNativeExecutionInput({ + ...value, provider: { ...provider, profile: { ...provider.profile, agentProfileVersion: unsupportedVersion } }, + })).toThrow("qualified ACPX v1 profile"); + } + expect(() => parseNativeExecutionInput({ + ...value, provider: { ...provider, profile: { ...provider.profile, agent: "pi" } }, + })).toThrow("qualified ACPX v1 profile"); + expect(() => parseNativeExecutionInput({ + ...value, session: { ...value.session, driverKind: "opencode_server" }, + })).toThrow("does not match"); + }); + it("defaults legacy lifecycle state to per-turn and validates warm timeouts", () => { const legacy = structuredClone(input) as Record; delete (legacy.session as Record).lifecyclePolicy; @@ -512,7 +552,12 @@ describe("native task context ownership", () => { }); } + const { qualificationModel: _copilotQualificationModel, reportedModelId: _copilotReportedModelId, + permissionPolicy: _copilotPermissionPolicy, qualificationStatus: _copilotQualificationStatus, modelPolicy: _copilotModelPolicy, + ...copilotSnapshot } = QUALIFIED_ACPX_PROFILES.copilot; + it.each([ + { driverKind: "acpx_runtime", provider: { kind: "acpx", agent: "copilot", model: "gpt-5.6-luna", permissionMode: "deny-all", profile: copilotSnapshot } }, { driverKind: "opencode_server", provider: { kind: "opencode", model: "openrouter/deepseek/deepseek-v4-flash-0731", permissionMode: "deny" } }, { driverKind: "acpx_runtime", provider: { kind: "acpx", agent: "pi", model: "openrouter/deepseek/deepseek-v4-flash-0731", permissionMode: "deny-all", diff --git a/packages/paperclip-runner/src/contracts/native-execution.ts b/packages/paperclip-runner/src/contracts/native-execution.ts index 622aedb0f48..86eb9a43342 100644 --- a/packages/paperclip-runner/src/contracts/native-execution.ts +++ b/packages/paperclip-runner/src/contracts/native-execution.ts @@ -90,6 +90,9 @@ export type NativeCodexApprovalPolicy = "never" | "on-request" | "untrusted"; export type NativeOpenCodePermissionMode = "allow" | "ask" | "deny"; export type NativeAcpxPermissionMode = "approve-all" | "approve-paperclip" | "approve-reads" | "deny-all"; +/** Decodable history; current immutable admission comes from the shared manifest. */ +export type NativeAcpxProfileVersion = AcpxProfileVersion; + export interface NativeAcpxProfileSnapshot { driverKind: "acpx_runtime"; protocolVersion: 1; diff --git a/packages/paperclip-runner/src/contracts/native-session-backend.ts b/packages/paperclip-runner/src/contracts/native-session-backend.ts index f473b56a03e..ef19e5fe272 100644 --- a/packages/paperclip-runner/src/contracts/native-session-backend.ts +++ b/packages/paperclip-runner/src/contracts/native-session-backend.ts @@ -1,3 +1,4 @@ +import type { NativeRunRuntimeGrant } from "./runtime-context.js"; import type { NativeRunIdentity, NativeSessionCapabilities, @@ -184,7 +185,7 @@ export class NativeSessionCleanupQuarantinedError extends Error { export interface NativeSession { identity(): NativeRunIdentity; capabilities(): Promise; - attachRun?(input: { identity: NativeRunIdentity }): Promise; + attachRun?(input: { identity: NativeRunIdentity; currentRunGrant?: NativeRunRuntimeGrant }): Promise; /** Relinquish controller authority without suspending provider execution. */ detachControllerForRestart?(): Promise; events(input?: { afterCursor?: string | null }): AsyncIterable; diff --git a/packages/paperclip-runner/src/contracts/runtime-context.ts b/packages/paperclip-runner/src/contracts/runtime-context.ts index 1d0127e50d1..c1b21e35409 100644 --- a/packages/paperclip-runner/src/contracts/runtime-context.ts +++ b/packages/paperclip-runner/src/contracts/runtime-context.ts @@ -27,6 +27,12 @@ export interface NativeRuntimeContextSnapshot { aggregateDigest: string; } +/** Authenticated current-run grants; immutable session policy is verified separately. */ +export interface NativeRunRuntimeGrant { + runtimeContext: NativeRuntimeContextSnapshot | null; + instructions: string; +} + export class NativeRuntimeContextError extends Error { readonly code = "native_runtime_context_invalid" as const; constructor(message: string) { super(message); this.name = "NativeRuntimeContextError"; } diff --git a/packages/paperclip-runner/src/drivers/acpx/acp-permission-adapter.ts b/packages/paperclip-runner/src/drivers/acpx/acp-permission-adapter.ts index ff125d537dd..3d4508eceb6 100644 --- a/packages/paperclip-runner/src/drivers/acpx/acp-permission-adapter.ts +++ b/packages/paperclip-runner/src/drivers/acpx/acp-permission-adapter.ts @@ -3,6 +3,8 @@ import type { HarnessRuntimeRequestResolution } from "../../contracts/harness-dr import { cursorToolIdentity } from "./cursor-plan-tool-identity.js"; +import { safeCopilotEditTarget } from "./copilot-permission-context.js"; + export type AcpxPermissionAction = "accept" | "accept_for_session" | "decline" | "cancel"; export interface NormalizedAcpxPermission { title: string; @@ -36,6 +38,8 @@ export function normalizeAcpxPermission(request: AcpPermissionRequest, options: || (options.provider === "cursor" && !call.toolCallId.trim())) { throw new Error("ACP permission request omitted its tool identity"); } + const needsEditContext = options.provider === "copilot" && call.kind === "edit"; + const target = needsEditContext ? safeCopilotEditTarget(call, options.workingDirectory) : undefined; const bindings = new Map(); const choices: NormalizedAcpxPermission["choices"] = []; for (const [key, kind, label] of [ @@ -43,6 +47,7 @@ export function normalizeAcpxPermission(request: AcpPermissionRequest, options: ["accept_for_session", "allow_always", "Allow for session"], ["decline", "reject_once", "Deny"], ] as const) { + if (needsEditContext && !target && (key === "accept" || key === "accept_for_session")) continue; if (kind === "allow_always" && options.allowAlwaysScope !== "session") continue; if (byKind.has(kind)) { bindings.set(key, kind); choices.push({ key, label }); } } @@ -50,7 +55,9 @@ export function normalizeAcpxPermission(request: AcpPermissionRequest, options: bindings.set("cancel", "cancel"); choices.push({ key: "cancel", label: "Cancel" }); return { - title: typeof call.title === "string" && call.title.trim() + title: needsEditContext + ? target ? `Change file: ${target}` : "File change requested; target unavailable. Deny or cancel this request." + : typeof call.title === "string" && call.title.trim() ? call.title.slice(0, 4_000) : "Approve provider operation", kind: request.inferredKind ?? "other", // Display/durable identity must match the tool-event boundary. Leave the diff --git a/packages/paperclip-runner/src/drivers/acpx/codex-acpx-driver.test.ts b/packages/paperclip-runner/src/drivers/acpx/codex-acpx-driver.test.ts index 8bdc507d8a1..0402d4c9aec 100644 --- a/packages/paperclip-runner/src/drivers/acpx/codex-acpx-driver.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/codex-acpx-driver.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it, vi } from "vitest"; +import { AcpxProviderProcessLostError } from "./codex-runtime-adapter.js"; import type { AcpRuntimeEvent } from "acpx/runtime"; @@ -1501,6 +1502,35 @@ describe("Codex ACPX harness driver", () => { }); }); + it("expires a Copilot permission on provider death and rejects its late answer", async () => { + const failure = deferred(); + const fixture = driverFixture({ agent: "copilot", model: "gpt-5.6-luna", providerPolicy: { readOnly: false } }, { eventStreamFailure: failure.promise }); + const session = await fixture.driver.openSession({ runId: "run-provider-death", normalizedSessionId: "session-1", workingDirectory: "/workspace" }); + const created = collectUntil(session.events(), "runtime_request.created"); + const { turnId } = await session.startTurn({ message: { text: "Edit the file" } }); + const callback = fixture.host.startTurn.mock.calls[0]![0].onPermissionRequest!; + const controller = new AbortController(); + const response = callback({ inferredKind: "edit", raw: { + sessionId: "agent-session-1", toolCall: { toolCallId: "dead-edit", title: "Edit file" }, + options: [{ optionId: "once", kind: "allow_once", name: "Allow once" }], + } } as Parameters[0], { signal: controller.signal, responseDelivery: Promise.resolve() }); + await created; + const request = session.pendingRuntimeRequests!()[0]!; + const expired = collectUntil(session.events(), "runtime_request.expired"); + const error = new AcpxProviderProcessLostError(); + controller.abort(error); + await expect(response).resolves.toEqual({ outcome: "cancel" }); + expect((await expired).at(-1)).toMatchObject({ eventType: "runtime_request.expired", payload: { + requestId: request.requestId, reason: "provider_process_lost", replayAllowed: false, + } }); + await expect(session.resolveRuntimeRequest!({ requestId: request.requestId, turnId, resolution: { action: "accept" } })).rejects.toThrow("no longer pending"); + const terminal = collectUntil(session.events(), "turn.failed"); + failure.reject(error); + expect((await terminal).at(-1)).toMatchObject({ payload: { error: { code: "ACPX_PROVIDER_PROCESS_LOST" } } }); + expect(session.pendingRuntimeRequests!()).toEqual([]); + await session.close({ reason: "death verified" }); + }); + it("delivers only offered permission choices and rejects stale or duplicate answers", async () => { const fixture = driverFixture({ agent: "claude", model: "claude-sonnet-5" }); const session = await fixture.driver.openSession({ diff --git a/packages/paperclip-runner/src/drivers/acpx/codex-acpx-driver.ts b/packages/paperclip-runner/src/drivers/acpx/codex-acpx-driver.ts index 2372311ea7a..9238efdfb5a 100644 --- a/packages/paperclip-runner/src/drivers/acpx/codex-acpx-driver.ts +++ b/packages/paperclip-runner/src/drivers/acpx/codex-acpx-driver.ts @@ -1,3 +1,4 @@ +import type { CopilotToolEvidence } from "./copilot-tool-evidence.js"; import { isProviderMode } from "../../contracts/provider-mode.js"; import { acpxProfileActivity, type AcpxActivityAdapter, type AcpxToolEvidence } from "./profile-activity.js"; import { requireAcpxResponseDelivery } from "./response-delivery.js"; @@ -56,6 +57,7 @@ import { } from "../runner-tool-bridge.js"; import { DEFAULT_CODEX_ACPX_RUNTIME_SHUTDOWN_BOUND_MS, + AcpxProviderProcessLostError, openCodexAcpxRuntime, } from "./codex-runtime-adapter.js"; import { normalizeAcpxPermission } from "./acp-permission-adapter.js"; @@ -470,6 +472,7 @@ export class CodexAcpxDriver implements HarnessDriver { : {}), ...(input.signal === undefined ? {} : { signal: input.signal }), semanticTools: { + ...(this.#options.agent === "copilot" ? { captureSemanticReceipt: () => session?.captureSemanticReceipt() } : {}), tools: this.#options.dynamicTools ?? [], handler: (call) => { if (!session) { @@ -752,6 +755,7 @@ class CodexAcpxSession implements HarnessSession { >; #sourceSequence = 0; #activeTurnId: string | null = null; + #copilotToolEvidence: CopilotToolEvidence | undefined; #semanticResult: PrpStructuredRunResult | null = null; #semanticFingerprint: string | null = null; #semanticCallId: string | null = null; @@ -910,6 +914,7 @@ class CodexAcpxSession implements HarnessSession { if (!this.#emit(event.eventType, event.payload, { turnId, itemId: event.itemId })) throw new Error("ACP tool activity could not be retained"); }, }); + this.#copilotToolEvidence = toolEvidence && "captureSemanticReceipt" in toolEvidence ? toolEvidence as CopilotToolEvidence : undefined; let turn: AcpxRuntimeTurn; const usageBefore = await readUsageStatus(this.#host); try { @@ -1106,6 +1111,10 @@ class CodexAcpxSession implements HarnessSession { return { result: "handed_off", cleanup }; } + captureSemanticReceipt() { + return this.#copilotToolEvidence?.captureSemanticReceipt(); + } + async dispatchTool(call: RunnerToolCall): Promise { this.#assertOpen(); if (this.#pendingTerminal) { @@ -1175,6 +1184,7 @@ class CodexAcpxSession implements HarnessSession { this.#semanticFingerprint === null || (claimsLaterTurn && !repeatsPendingTransfer) ) { + const commitNormalizedInput = call.captureNormalizedInput?.(validation.result); if ( !this.#emit("run.result.proposed", validation.result, { turnId, @@ -1186,6 +1196,7 @@ class CodexAcpxSession implements HarnessSession { "the event consumer must drain provider events before a semantic result can be accepted", ); } + commitNormalizedInput?.(); if (claimsLaterTurn) { // A reaffirming retry does not own the durable result until its // provider turn completes successfully. A failed or interrupted @@ -1480,7 +1491,7 @@ class CodexAcpxSession implements HarnessSession { this.#emit( "item.completed", { kind: "agentMessage", channel: "final", text: finalText }, - { turnId, itemId: `${turnId}:assistant-message` }, + { turnId, itemId: this.#assistantItemId(turnId, this.#assistantMessageId) }, ); } this.#publishTerminal( @@ -1551,7 +1562,7 @@ class CodexAcpxSession implements HarnessSession { } catch (error) { if (this.#terminalTurns.has(turnId)) return; if (error instanceof TerminalEventCapacityError) throw error; - this.#cancelPendingRuntimeRequests("provider turn failed", turnId); + this.#cancelPendingRuntimeRequests(error instanceof AcpxProviderProcessLostError ? error : "provider turn failed", turnId); if (this.#closed || this.#closingStarted) { const reaffirmedSemanticResult = this.#pendingSemanticTransfer?.turnId === turnId @@ -1582,7 +1593,7 @@ class CodexAcpxSession implements HarnessSession { : { reaffirmedSemanticResult }), }), "turn.failed", - { status: "failed", error: { message: safeMessage(error) } }, + { status: "failed", error: { ...(error instanceof AcpxProviderProcessLostError ? { code: error.code } : {}), message: safeMessage(error) } }, ); } } @@ -1637,6 +1648,11 @@ class CodexAcpxSession implements HarnessSession { if (this.#activeTurnId === turnId) this.#activeTurnId = null; } + #assistantItemId(turnId: string, messageId: string | null): string { + if (this.#agent !== "copilot") return `${turnId}:assistant-message`; + return messageId ? `${turnId}:assistant-message:${messageId}` : `${turnId}:assistant-activity`; + } + #mapRuntimeEvent( event: AcpRuntimeEvent, turnId: string, @@ -1647,9 +1663,17 @@ class CodexAcpxSession implements HarnessSession { const output = boundedText(event.text, 64 * 1024); const isReasoning = event.stream === "thought" || event.tag === "agent_thought_chunk"; - if (!isReasoning) { - const messageId = typeof event.messageId === "string" && event.messageId ? event.messageId : null; - if (messageId && this.#assistantMessageId && messageId !== this.#assistantMessageId) this.#assistantText = ""; + const messageId = typeof event.messageId === "string" && event.messageId ? event.messageId : null; + // The pinned Copilot mapper supplies actual native identity, including + // empty starts. Unidentified session info/warnings remain activity only. + if (!isReasoning && (this.#agent !== "copilot" || messageId)) { + if (messageId && this.#assistantMessageId && messageId !== this.#assistantMessageId) { + if (this.#agent === "copilot" && this.#assistantText) { + this.#emit("item.completed", { kind: "agentMessage", channel: "commentary", text: this.#assistantText }, + { turnId, itemId: this.#assistantItemId(turnId, this.#assistantMessageId) }); + } + this.#assistantText = ""; + } if (messageId) this.#assistantMessageId = messageId; this.#assistantText = boundedText( `${this.#assistantText}${output}`, @@ -1667,7 +1691,7 @@ class CodexAcpxSession implements HarnessSession { turnId, itemId: isReasoning ? `${turnId}:reasoning` - : `${turnId}:assistant-message`, + : this.#assistantItemId(turnId, messageId), }, ); } @@ -1712,9 +1736,7 @@ class CodexAcpxSession implements HarnessSession { const pending = this.#pendingRuntimeRequests.get(requestId); if (!pending || pending.settling || !this.#pendingRuntimeRequests.delete(requestId)) return; pending.cleanup(); - this.#emit("runtime_request.cancelled", harnessRuntimeRequestOutcome(request, { - action: "cancel", reason: "provider request aborted", - }), { turnId, itemId }); + this.#emitRequestAbort(request, context.signal.reason); settle(input.cancel()); }; this.#pendingRuntimeRequests.set(requestId, { @@ -1763,9 +1785,7 @@ class CodexAcpxSession implements HarnessSession { const pending = this.#pendingRuntimeRequests.get(requestId); if (!pending || pending.settling || !this.#pendingRuntimeRequests.delete(requestId)) return; pending.cleanup(); - this.#emit("runtime_request.cancelled", harnessRuntimeRequestOutcome(runtimeRequest, { - action: "cancel", reason: "provider request aborted", - }), { turnId, itemId: requestId }); + this.#emitRequestAbort(runtimeRequest, signal.reason); settle({ outcome: "cancel" }); }; this.#pendingRuntimeRequests.set(requestId, { @@ -1899,14 +1919,7 @@ class CodexAcpxSession implements HarnessSession { if (!pending || pending.settling) return; if (!this.#pendingRuntimeRequests.delete(requestId)) return; pending.cleanup(); - this.#emit( - "runtime_request.cancelled", - harnessRuntimeRequestOutcome(runtimeRequest, { - action: "cancel", - reason: "provider request aborted", - }), - { turnId, itemId: requestId }, - ); + this.#emitRequestAbort(runtimeRequest, context.signal.reason); settle({ action: "cancel" }); }; context.signal.addEventListener("abort", cancel, { once: true }); @@ -1924,22 +1937,23 @@ class CodexAcpxSession implements HarnessSession { }); } - #cancelPendingRuntimeRequests(reason: string, turnId?: string): void { + #emitRequestAbort(request: HarnessRuntimeRequest, reason: unknown): void { + const lost = reason instanceof AcpxProviderProcessLostError; + this.#emit(lost ? "runtime_request.expired" : "runtime_request.cancelled", { + ...harnessRuntimeRequestOutcome(request, { + ...(lost ? {} : { action: "cancel" as const }), + reason: lost ? "provider_process_lost" : typeof reason === "string" ? boundedText(reason, 1_000) : "provider request aborted", + }), + ...(lost ? { replayAllowed: false } : {}), + }, { turnId: request.turnId, itemId: request.itemId }); + } + + #cancelPendingRuntimeRequests(reason: string | AcpxProviderProcessLostError, turnId?: string): void { for (const [requestId, pending] of this.#pendingRuntimeRequests) { if (turnId && pending.request.turnId !== turnId) continue; if (!this.#pendingRuntimeRequests.delete(requestId)) continue; pending.cleanup(); - this.#emit( - "runtime_request.cancelled", - harnessRuntimeRequestOutcome(pending.request, { - action: "cancel", - reason: boundedText(safeMessage(reason), 1_000), - }), - { - turnId: pending.request.turnId, - itemId: pending.request.itemId, - }, - ); + this.#emitRequestAbort(pending.request, reason); pending.cancel(); } } diff --git a/packages/paperclip-runner/src/drivers/acpx/codex-credentials.test.ts b/packages/paperclip-runner/src/drivers/acpx/codex-credentials.test.ts index 8a18b200122..6c29f84e5b7 100644 --- a/packages/paperclip-runner/src/drivers/acpx/codex-credentials.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/codex-credentials.test.ts @@ -813,9 +813,10 @@ describe("managed Codex credentials", () => { it.runIf(process.platform !== "win32")( "shares the four-slot parent filesystem budget across fresh modules", async () => { - const fixtures = await Promise.all( - Array.from({ length: 5 }, () => credentialFixture()), - ); + // Reserve fixture quorum candidates before holding filesystem operations. + // Otherwise an unrelated loopback listener can reject staging before + // fourOpens resolves, leaving an unhandled rejection and a false timeout. + const fixtures = await credentialFixturesWithAvailableQuorum(5); const retainedHomes = new Set( fixtures.slice(0, 4).map((fixture) => fixture.home), ); @@ -1652,6 +1653,38 @@ async function credentialFixture(): Promise<{ root: string; home: string }> { return { root, home: await realpath(home) }; } +async function credentialFixturesWithAvailableQuorum(count: number) { + const fixtures: Awaited>[] = []; + const reservations: Array>> = []; + try { + for (let index = 0; index < count; index++) { + let prepared = false; + for (let attempt = 0; attempt < 8; attempt++) { + const fixture = await credentialFixture(); + const owned: Array>> = []; + try { + for (const port of credentialLeasePorts(fixture.home)) { + owned.push(await listenSilently(port)); + } + fixtures.push(fixture); + reservations.push(...owned); + prepared = true; + break; + } catch (error) { + await Promise.all(owned.map((listener) => listener.close())); + if ((error as NodeJS.ErrnoException).code !== "EADDRINUSE" || attempt === 7) throw error; + } + } + if (!prepared) throw new Error("Credential fixture quorum preparation failed"); + } + return fixtures; + } finally { + // Fixture setup alone may choose another unused home. Production staging + // still runs once, and a foreign bind racing this handoff remains a failure. + await Promise.all(reservations.map((listener) => listener.close())); + } +} + async function silentPrimaryQuorumFixture( nextFixture = credentialFixture, occupiedIndex: 0 | 1 = 0, 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.ts index dbeba649296..7d2631103ec 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 @@ -29,6 +29,141 @@ const HANDLE: AcpRuntimeHandle = { }; describe("Codex ACPX runtime adapter", () => { + it.each(["blocked", "ended"] as const)("settles a %s Copilot stream on verified provider death without replaying the permission", async (streamState) => { + const pending = pendingExtensionTurn("death-turn"); + if (streamState === "ended") pending.turn.events = (async function* () {})(); + const runtime = fakeRuntime(); + vi.mocked(runtime.startTurn).mockReturnValue(pending.turn); + const child = fakeChild(); + const command = fakeCommand(); + vi.mocked(command.spawn).mockReturnValue(child); + let exit!: () => void; + const providerExit = new Promise(resolve => { exit = resolve; }); + let created!: AcpRuntimeOptions; + const options = openOptions(command); + options.profile = { ...options.profile, agent: "copilot" }; + options.permissionMode = "approve-paperclip"; + const port = await openCodexAcpxRuntime(options, { + createRegistry: () => registry(), createStore: () => store(), + awaitProviderOwnership: providerOwnershipEstablished, + awaitProviderExit: () => providerExit, + createRuntime: value => { created = value; return runtimeWithProvider(runtime, value); }, + }); + let answer!: (value: { outcome: "allow_once" }) => void; + let callbackSignal!: AbortSignal; + const handler = vi.fn((_request, context) => { + callbackSignal = context.signal; + return new Promise<{ outcome: "allow_once" }>(resolve => { answer = resolve; }); + }); + const turn = port.startTurn({ text: "Write the file", requestId: "death-turn", onPermissionRequest: handler }); + await turn.promptStarted; + const events = turn.events[Symbol.asyncIterator](); + const draining = expect(events.next()).rejects.toMatchObject({ code: "ACPX_PROVIDER_PROCESS_LOST" }); + const settled = expect(turn.result).rejects.toMatchObject({ code: "ACPX_PROVIDER_PROCESS_LOST" }); + const request = created.onPermissionRequest!({ sessionId: "backend-1", raw: { sessionId: "backend-1" }, inferredKind: "edit" } as never, { signal: new AbortController().signal }); + await vi.waitFor(() => expect(handler).toHaveBeenCalledOnce()); + // The guardian remains live: only independent provider EOF proves death. + expect(child.exitCode).toBeNull(); + exit(); + await Promise.all([draining, settled]); + expect(callbackSignal.aborted).toBe(true); + answer({ outcome: "allow_once" }); + await expect(request).resolves.toEqual({ outcome: "cancel" }); + expect(() => port.startTurn({ text: "Replay", requestId: "replay" })).toThrow("provider exited"); + expect(runtime.startTurn).toHaveBeenCalledOnce(); + pending.settle(); + await port.close({ reason: "test finished" }); + expect(child.kill).toHaveBeenCalled(); + }); + + it("refuses Copilot replay when native disconnection precedes the independent exit proof", async () => { + const pending = pendingExtensionTurn("disconnect-turn"); + let disconnect!: () => void; + const failed = new Promise<{ status: "failed"; error: { code: "RUNTIME"; detailCode: "AGENT_DISCONNECTED"; message: string } }>(resolve => { + disconnect = () => resolve({ status: "failed", error: { code: "RUNTIME", detailCode: "AGENT_DISCONNECTED", message: "Native ACP transport disconnected" } }); + }); + const runtime = fakeRuntime(); + vi.mocked(runtime.startTurn).mockReturnValue({ ...pending.turn, result: failed }); + const child = fakeChild(); + const command = fakeCommand(); + vi.mocked(command.spawn).mockReturnValue(child); + let exit!: () => void; + const providerExit = new Promise(resolve => { exit = resolve; }); + let created!: AcpRuntimeOptions; + const options = openOptions(command); + options.profile = { ...options.profile, agent: "copilot" }; + options.permissionMode = "approve-paperclip"; + const port = await openCodexAcpxRuntime(options, { + createRegistry: () => registry(), createStore: () => store(), + awaitProviderOwnership: providerOwnershipEstablished, + awaitProviderExit: () => providerExit, + createRuntime: value => { created = value; return runtimeWithProvider(runtime, value); }, + }); + let answer!: (value: { outcome: "allow_once" }) => void; + let callbackSignal!: AbortSignal; + const handler = vi.fn((_request, context) => { + callbackSignal = context.signal; + return new Promise<{ outcome: "allow_once" }>(resolve => { answer = resolve; }); + }); + try { + const turn = port.startTurn({ text: "Write", requestId: "disconnect-turn", onPermissionRequest: handler }); + await turn.promptStarted; + const request = created.onPermissionRequest!({ sessionId: "backend-1", raw: { sessionId: "backend-1" }, inferredKind: "edit" } as never, { signal: new AbortController().signal }); + await vi.waitFor(() => expect(handler).toHaveBeenCalledOnce()); + disconnect(); + await expect(turn.result).rejects.toMatchObject({ code: "ACPX_PROVIDER_PROCESS_LOST" }); + await expect((async () => { for await (const _event of turn.events) { /* drain */ } })()) + .rejects.toMatchObject({ code: "ACPX_PROVIDER_PROCESS_LOST" }); + expect(callbackSignal.aborted).toBe(true); + answer({ outcome: "allow_once" }); + await expect(request).resolves.toEqual({ outcome: "cancel" }); + expect(() => port.startTurn({ text: "Replay", requestId: "replay" })).toThrow("provider exited"); + expect(runtime.startTurn).toHaveBeenCalledOnce(); + // A typed disconnect does not manufacture independent process-exit proof. + // Cleanup still owns the live guardian and waits for the separate proof. + expect(child.exitCode).toBeNull(); + } finally { + pending.settle(); + exit(); + await port.close({ reason: "disconnect race verified" }); + } + }); + + it("keeps a Copilot callback deliverable when only the guardian exits", async () => { + const pending = pendingExtensionTurn("preserved-turn"); + const runtime = fakeRuntime(); + vi.mocked(runtime.startTurn).mockReturnValue(pending.turn); + let created!: AcpRuntimeOptions; + const child = fakeChild(); + const command = fakeCommand(); + vi.mocked(command.spawn).mockReturnValue(child); + let exit!: () => void; + const providerExit = new Promise(resolve => { exit = resolve; }); + const options = openOptions(command); + options.profile = { ...options.profile, agent: "copilot" }; + options.permissionMode = "approve-paperclip"; + const port = await openCodexAcpxRuntime(options, { + createRegistry: () => registry(), createStore: () => store(), + awaitProviderOwnership: providerOwnershipEstablished, awaitProviderExit: () => providerExit, + createRuntime: value => { created = value; return runtimeWithProvider(runtime, value); }, + }); + let answer!: (value: { outcome: "allow_once" }) => void; + const handler = vi.fn(() => new Promise<{ outcome: "allow_once" }>(resolve => { answer = resolve; })); + const turn = port.startTurn({ text: "Write", requestId: "preserved-turn", onPermissionRequest: handler }); + const request = created.onPermissionRequest!({ sessionId: "backend-1", raw: { sessionId: "backend-1" }, inferredKind: "edit" } as never, { signal: new AbortController().signal }); + await vi.waitFor(() => expect(handler).toHaveBeenCalledOnce()); + child.exitCode = 0; + child.emit("exit", 0, null); + // Guardian exit cannot replace the provider-only lifetime observation. + await new Promise(resolve => setTimeout(resolve, 10)); + answer({ outcome: "allow_once" }); + await expect(request).resolves.toEqual({ outcome: "allow_once" }); + pending.settle(); + await expect(turn.result).resolves.toMatchObject({ status: "completed" }); + exit(); + await port.close({ reason: "test finished" }); + }); + it("rejects forged permission session identifiers before delegating or applying full-auto policy", async () => { const pending = pendingExtensionTurn("turn-1"); const runtime = fakeRuntime(); vi.mocked(runtime.startTurn).mockReturnValue(pending.turn); diff --git a/packages/paperclip-runner/src/drivers/acpx/codex-runtime-adapter.ts b/packages/paperclip-runner/src/drivers/acpx/codex-runtime-adapter.ts index 088d098c1f7..2bc35fcf826 100644 --- a/packages/paperclip-runner/src/drivers/acpx/codex-runtime-adapter.ts +++ b/packages/paperclip-runner/src/drivers/acpx/codex-runtime-adapter.ts @@ -30,6 +30,7 @@ import { import type { AcpxModelStatus } from "./model-verification.js"; import { AcpxApprovalRequiredError, decideAcpxPermission } from "./permission-policy.js"; import { ACPX_CAPABILITY_PROFILES } from "./capability-profiles.js"; +import { assertCopilotPromptPolicy, createCopilotProtocolGuard } from "./copilot-policy.js"; import { admitCursorInstructions, createCursorInstructionAdmission } from "./cursor-instructions.js"; import { createAcpxModeBinding } from "./provider-mode.js"; @@ -100,6 +101,14 @@ interface AcpxRuntimeExtensionBoundary { steering: AcpxRuntimeSteeringCapability | null; } +export class AcpxProviderProcessLostError extends Error { + readonly code = "ACPX_PROVIDER_PROCESS_LOST"; + constructor(message = "The owned ACPX provider exited during its active turn") { + super(message); + this.name = "AcpxProviderProcessLostError"; + } +} + class AcpxRuntimeCloseTimeoutError extends Error { constructor() { super("ACPX runtime close timed out"); @@ -327,6 +336,9 @@ export async function openQualifiedAcpxRuntime( elicitationModes: ["form"], ...(options.clientCapabilities === undefined ? {} : { clientCapabilities: structuredClone(options.clientCapabilities) }), extensionMethods: [...new Set([...extensionRequests, ...extensionNotifications])], + ...(options.profile.agent === "copilot" ? { + protocolGuardFactory: () => createCopilotProtocolGuard(options.profile.reportedModelId), + } : {}), onExtensionRequest: async (method, params, context) => { const active = extensionBoundary.active; if (!extensionRequests.has(method) || !active?.onRequest || !ownsExtensionTurn(active, params) || context.signal.aborted) { @@ -584,6 +596,8 @@ export async function openQualifiedAcpxRuntime( commandLaunches, permissionBoundary, extensionBoundary, + options.profile.agent === "copilot", + options.profile.agent === "copilot" ? assertCopilotPromptPolicy : undefined, ); } catch (error) { const cleanupReason = "ACPX runtime identity validation failed"; @@ -1013,6 +1027,8 @@ function runtimePort( commandLaunches: { count: number; refreshConsumedCommand?: () => Promise }, permissionBoundary: { active: AbortController | null; hasAdmittedTurn: boolean; handler?: AcpRuntimeOptions["onPermissionRequest"] }, extensionBoundary: AcpxRuntimeExtensionBoundary, + monitorProviderDeath: boolean, + assertPromptPolicy?: (text: string) => void, ): AcpxRuntimePort { extensionBoundary.sessionIds = new Set([identity.backendSessionId]); let extensionControls: Promise = Promise.resolve(); @@ -1055,6 +1071,7 @@ function runtimePort( pendingExternalIntent: boolean; }; let runtimeClosed = false; + let providerProcessLost = false; let runtimeCloseAttempt: RuntimeCloseAttempt | undefined; let lateReconciliationOwner: Promise | undefined; // Each independently observed late failure receives a bounded reconciliation @@ -1370,9 +1387,12 @@ function runtimePort( } : {}), startTurn(input) { + if (providerProcessLost) throw new AcpxProviderProcessLostError(); + assertPromptPolicy?.(input.text); if (extensionBoundary.active) throw new Error("ACPX runtime already has an active turn"); const approval = new AbortController(); const controller = new AbortController(); + const providerDeath = new AbortController(); const extensionTurn: AcpxRuntimeExtensionTurn = { requestId: input.requestId, sessionId: identity.backendSessionId, controller, signal: input.signal ? AbortSignal.any([controller.signal, input.signal, approval.signal]) : AbortSignal.any([controller.signal, approval.signal]), @@ -1380,7 +1400,25 @@ function runtimePort( onRequest: input.onExtensionRequest, onNotification: input.onExtensionNotification, }; extensionBoundary.active = extensionTurn; + // A guardian can outlive the provider while ACP awaits a callback. + // Native exit or a typed ACP agent disconnect retires this turn; losing + // the controller connection must preserve deliverable input instead. + // Cleanup still requires the independent provider-only lifetime proof. + const retireProviderTurn = (error = new AcpxProviderProcessLostError()): void => { + providerProcessLost = true; + providerDeath.abort(error); + approval.abort(error); + controller.abort(error); + }; + const stopWatchingProviderExit = !monitorProviderDeath + ? () => undefined + : children.watchProviderExit(() => { + if (!runtimeCloseAttempt && !runtimeClosed && !extensionTurn.signal.aborted && extensionBoundary.active === extensionTurn) { + retireProviderTurn(); + } + }); const releaseExtensionTurn = (): void => { + stopWatchingProviderExit(); controller.abort(new Error("ACPX extension turn expired")); if (extensionBoundary.active === extensionTurn) extensionBoundary.active = null; }; @@ -1410,9 +1448,18 @@ function runtimePort( throw error; } const guarded = turnWithVerifiedLifetimeOwnership(turn, finishOwnershipAdmission); - extensionTurn.promptStarted = guarded.promptStarted; - const result = guarded.result.then( + const promptStarted = abortableExtensionResult(guarded.promptStarted, providerDeath.signal); + void promptStarted.catch(() => undefined); + extensionTurn.promptStarted = promptStarted; + const result = abortableExtensionResult(guarded.result, providerDeath.signal).then( (value) => { + if (monitorProviderDeath && value.status === "failed" + && (value.error?.code === "AGENT_DISCONNECTED" || value.error?.detailCode === "AGENT_DISCONNECTED")) { + // ACP can terminalize before the independent exit observer runs. + // Retire callbacks and the session before finally removes the + // observer, so a late answer cannot admit another native turn. + retireProviderTurn(new AcpxProviderProcessLostError("The owned ACPX provider disconnected during its active turn")); + } approval.signal.throwIfAborted(); // ACPX may resolve its own permission policy before invoking the // host callback. Keep that typed denial on the same runner outcome. @@ -1429,6 +1476,7 @@ function runtimePort( void result.catch(() => undefined); return { ...guarded, + promptStarted, result, cancel: (input) => { controller.abort(new Error("ACPX extension turn cancelled")); @@ -1439,16 +1487,28 @@ function runtimePort( return guarded.closeStream(input); }, events: (async function* () { + const iterator = guarded.events[Symbol.asyncIterator](); try { - for await (const event of guarded.events) { + for (;;) { + const next = await abortableExtensionResult(iterator.next(), providerDeath.signal); + if (next.done) break; approval.signal.throwIfAborted(); - yield event; + yield next.value; } } catch (error) { approval.signal.throwIfAborted(); throw error; + } finally { + // A broken provider may never release its iterator. Observe its + // eventual close without delaying the failed turn's publication. + void iterator.return?.().catch(() => undefined); } approval.signal.throwIfAborted(); + // Copilot's transport can end its event iterator before independent + // provider-exit proof settles the pending permission and turn result. + // Do not publish a successful stream end while that turn still owns + // an unanswered callback or an unreported failure. + if (monitorProviderDeath) await result; })(), }; }, @@ -1705,6 +1765,7 @@ class SpawnedChildSet { readonly #providerExits = new Map(); readonly #terminations = new Map>(); readonly #lifetimeOwnership: Promise[] = []; + readonly #exitWatchers = new Set<() => void>(); #lifetimeOwnershipSealed = false; #sealed = false; @@ -1790,6 +1851,11 @@ class SpawnedChildSet { }; } + watchProviderExit(observer: () => void): () => void { + this.#exitWatchers.add(observer); + return () => { this.#exitWatchers.delete(observer); }; + } + #track(child: ChildProcess, providerExit: ProviderExitObservation): void { this.#children.add(child); const onError = (error: unknown) => this.#errors.add(error); @@ -1816,6 +1882,7 @@ class SpawnedChildSet { providerExit.observe((outcome) => { if (outcome.exited) { providerExited = true; + for (const observer of this.#exitWatchers) observer(); forgetIfReleased(); } else { this.#errors.add(outcome.error); diff --git a/packages/paperclip-runner/src/drivers/acpx/copilot-events.ts b/packages/paperclip-runner/src/drivers/acpx/copilot-events.ts new file mode 100644 index 00000000000..563d1f0ade2 --- /dev/null +++ b/packages/paperclip-runner/src/drivers/acpx/copilot-events.ts @@ -0,0 +1,173 @@ +import { createHash } from "node:crypto"; + +export const COPILOT_ACP_EVENT_METHOD = "github.com/copilot/sessionEvent" as const; + +/** Explicit subscription: do not request reasoning, prompts, hooks, or raw tools twice. */ +export const COPILOT_ACP_EVENT_TYPES = Object.freeze([ + "session.idle", "session.background_tasks_changed", "session.completion_receipt", + "session.plan_changed", "session.workspace_file_changed", "session.binary_asset", + "subagent.started", "subagent.configured", "subagent.completed", "subagent.failed", + "assistant.usage", "session.usage_info", "session.usage_checkpoint", + "session.compaction_start", "session.compaction_complete", "pending_messages.modified", + "session.context_changed", "session.permissions_changed", "session.mode_changed", + "user_input.requested", "exit_plan_mode.requested", "elicitation.requested", +] as const); + +export const COPILOT_ACP_CLIENT_CAPABILITIES = Object.freeze({ + _meta: Object.freeze({ + "github.com/copilot": Object.freeze({ events: COPILOT_ACP_EVENT_TYPES }), + }), +}); + +export interface CopilotSessionEvent { + kind: "activity" | "usage" | "artifact_reference" | "capability_gap"; + sourceMethod: typeof COPILOT_ACP_EVENT_METHOD; + sourceType: string; + sessionId: string; + /** The pinned passthrough does not identify the originating prompt. */ + turnId: null; + agentId?: string; + timestamp?: string; + data: Record; +} + +const eventTypes = new Set(COPILOT_ACP_EVENT_TYPES); +const MAX_EVENT_BYTES = 40 * 1024; +const MAX_TEXT_LENGTH = 4096; + +/** + * Provider notices remain evidence, never authority to read a path, respond to + * native requests, change permissions, or finalize a turn. Raw passthrough has + * neither delivery guarantees nor an event ID and is not an accounting ledger. + */ +export function normalizeCopilotSessionEvent( + notification: unknown, + binding: { sessionId: string; turnId: string }, +): CopilotSessionEvent | null { + const envelope = record(notification); + if (envelope.method !== COPILOT_ACP_EVENT_METHOD || !binding.sessionId || !binding.turnId) return null; + const params = record(envelope.params); + if (params.sessionId !== binding.sessionId || typeof params.type !== "string" || !eventTypes.has(params.type)) return null; + // This runs after JSON framing, but remains safe against fabricated test/port values. + try { if (Buffer.byteLength(JSON.stringify(params)) > MAX_EVENT_BYTES) return null; } catch { return null; } + const result: CopilotSessionEvent = { + kind: "activity", sourceMethod: COPILOT_ACP_EVENT_METHOD, sourceType: params.type, + sessionId: binding.sessionId, turnId: null, data: {}, + }; + if (validText(params.agentId, 256)) result.agentId = params.agentId; + if (validText(params.timestamp, 128) && Number.isFinite(Date.parse(params.timestamp))) result.timestamp = params.timestamp; + if (params.dataOmitted !== undefined) { + result.kind = "capability_gap"; + result.data = { reason: "provider_omitted_event_data", omission: params.dataOmitted === "too-large" ? "too-large" : "unserializable" }; + return result; + } + const data = record(params.data); + switch (params.type) { + case "session.workspace_file_changed": { + if (!safeRelativePath(data.path) || !["create", "update"].includes(String(data.operation))) return null; + result.kind = "artifact_reference"; + result.data = { path: data.path, operation: data.operation, locationKind: "provider_session_workspace", requiresArtifactResolution: true }; + break; + } + case "session.binary_asset": { + if (!validText(data.assetId, 128) || !/^sha256:[a-f0-9]{64}$/.test(data.assetId) + || !validText(data.mimeType, 256) || !["image", "resource"].includes(String(data.type)) + || !integer(data.byteLength) || typeof data.data !== "string" + || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(data.data)) return null; + const bytes = Buffer.from(data.data, "base64"); + if (bytes.length !== data.byteLength || `sha256:${createHash("sha256").update(bytes).digest("hex")}` !== data.assetId) return null; + result.kind = "artifact_reference"; + result.data = { assetId: data.assetId, assetType: data.type, mimeType: data.mimeType, byteLength: data.byteLength, requiresArtifactResolution: true }; + copyText(data, result.data, ["description"]); + break; + } + case "assistant.usage": + result.kind = "usage"; + copyText(data, result.data, ["model", "reasoningEffort", "initiator", "interactionType", "apiCallId", "parentToolCallId", "transport", "apiEndpoint", "finishReason"]); + copyNumbers(data, result.data, ["inputTokens", "outputTokens", "cacheReadTokens", "cacheWriteTokens", "reasoningTokens", "duration", "maxPromptTokens", "maxOutputTokens", "acceptedPredictionTokens", "rejectedPredictionTokens", "availableToolCount", "numToolCalls", "toolTokenCount", "cacheTtlSeconds", "timeToFirstTokenMs", "interTokenLatencyMs", "outputTtftMs", "thinkingDroppedBlocks"]); + copyBooleans(data, result.data, ["isByok", "isAuto", "cacheDetailsReported", "contentFilterTriggered"]); + if (nonnegativeNumber(data.cost)) result.data.modelMultiplier = data.cost; // Not USD. + if (nonnegativeNumber(record(data.copilotUsage).totalNanoAiu)) result.data.totalNanoAiu = record(data.copilotUsage).totalNanoAiu; + result.data.accounting = "supplemental_provider_notice"; + break; + case "session.usage_info": + result.kind = "usage"; + copyNumbers(data, result.data, ["tokenLimit", "currentTokens", "messagesLength", "systemTokens", "conversationTokens", "toolDefinitionsTokens"]); + copyBooleans(data, result.data, ["isInitial"]); + break; + case "session.usage_checkpoint": + result.kind = "usage"; + if (nonnegativeNumber(data.totalNanoAiu)) result.data.totalNanoAiu = data.totalNanoAiu; + result.data.accounting = "session_cumulative_nano_ai_units"; + break; + case "subagent.started": case "subagent.configured": case "subagent.completed": case "subagent.failed": + copyText(data, result.data, ["toolCallId", "agentName", "agentDisplayName", "agentDescription", "model", "parentId", "agentType", "executionMode", "reasoningEffort", "contextTier", "firstDispatchedModel", "configuredModelPreference", "explicitModelOverride", "modelOverrideReason", "modelSelectionSource", "taskModelSource", "factoryRunId", "error"]); + copyNumbers(data, result.data, ["totalToolCalls", "totalTokens", "durationMs"]); + copyBooleans(data, result.data, ["cancelled", "resumable", "multiTurn", "explicitModelMatchesPreference", "configuredModelMatchesActual"]); + break; + case "session.completion_receipt": + copyNumbers(data, result.data, ["schemaVersion", "attempt", "successfulToolCount", "failedToolCount"]); + copyText(data, result.data, ["sourceEventId", "stopReason"]); + result.data.eventRange = {}; + copyText(record(data.eventRange), result.data.eventRange as Record, ["startEventId", "endEventId"]); + result.data.authoritativeTurnCompletion = false; + break; + case "session.idle": + copyBooleans(data, result.data, ["aborted"]); + copyText(data, result.data, ["mode"]); + result.data.authoritativeTurnCompletion = false; + break; + case "session.plan_changed": + copyText(data, result.data, ["operation"]); + result.data.planContentAvailable = false; + break; + case "user_input.requested": case "exit_plan_mode.requested": case "elicitation.requested": + // ACP 1.0.88's passthrough is notification-only; it cannot acknowledge these + // native callback requests. Never pretend that a UI answer was delivered. + result.kind = "capability_gap"; + result.data = { reason: "native_request_has_no_qualified_acp_responder" }; + copyText(data, result.data, ["requestId", "toolCallId"]); + break; + case "session.mode_changed": copyText(data, result.data, ["previousMode", "newMode"]); break; + case "session.permissions_changed": + copyText(data, result.data, ["previousMode", "mode", "assistedApprovalModel"]); + result.data.policyChangeAllowed = false; + break; + case "session.compaction_start": case "session.compaction_complete": + copyText(data, result.data, ["trigger", "model", "behaviorModelId", "error"]); + copyNumbers(data, result.data, ["checkpointNumber", "compactionTokensUsed", "conversationTokens", "currentTokens", "messagesRemoved", "postCompactionTokens", "preCompactionMessagesLength", "preCompactionTokens", "systemTokens", "tokenLimit", "tokensRemoved", "toolDefinitionsTokens", "statusCode"]); + copyBooleans(data, result.data, ["success"]); + break; + case "session.context_changed": + // cwd is a report, not authority to rebind the admitted workspace. + copyText(data, result.data, ["cwd", "branch", "baseCommit", "headCommit", "hostType"]); + result.data.workspaceRebindAllowed = false; + break; + default: + // Empty lifecycle notices are useful; private native payloads are not copied. + result.data = { refreshAvailable: false }; + } + return result; +} + +function record(value: unknown): Record { + return typeof value === "object" && value !== null && !Array.isArray(value) ? value as Record : {}; +} +function validText(value: unknown, max = MAX_TEXT_LENGTH): value is string { + return typeof value === "string" && value.length > 0 && value.length <= max && !value.includes("\0"); +} +function integer(value: unknown): value is number { return Number.isSafeInteger(value) && Number(value) >= 0; } +function nonnegativeNumber(value: unknown): value is number { return typeof value === "number" && Number.isFinite(value) && value >= 0; } +function safeRelativePath(value: unknown): value is string { + return validText(value) && !/[\\\u0000-\u001f]/.test(value) && !/^(?:\/|[A-Za-z]:|[A-Za-z][A-Za-z0-9+.-]*:)/.test(value) + && value.split("/").every((part) => part !== "" && part !== "." && part !== ".."); +} +function copyText(source: Record, target: Record, fields: string[]): void { + for (const field of fields) if (validText(source[field])) target[field] = source[field]; +} +function copyNumbers(source: Record, target: Record, fields: string[]): void { + for (const field of fields) if (nonnegativeNumber(source[field])) target[field] = source[field]; +} +function copyBooleans(source: Record, target: Record, fields: string[]): void { + for (const field of fields) if (typeof source[field] === "boolean") target[field] = source[field]; +} diff --git a/packages/paperclip-runner/src/drivers/acpx/copilot-extension-adapter.ts b/packages/paperclip-runner/src/drivers/acpx/copilot-extension-adapter.ts new file mode 100644 index 00000000000..a3b766c8c57 --- /dev/null +++ b/packages/paperclip-runner/src/drivers/acpx/copilot-extension-adapter.ts @@ -0,0 +1,103 @@ +import { createHash } from "node:crypto"; +import type { CanonicalProviderEvent } from "../../provider-events.js"; +import { redactPaperclipSemanticValue, redactSemanticValue } from "../../semantic-tools/redaction.js"; +import { COPILOT_ACP_EVENT_METHOD, normalizeCopilotSessionEvent, type CopilotSessionEvent } from "./copilot-events.js"; +import type { AcpxProfileExtensionAdapter, AcpxProfileExtensionContext } from "./profile-extensions.js"; + +/** Display projection only. Native notices cannot settle or charge a runner turn. */ +export function createCopilotProfileExtensionAdapter(context: AcpxProfileExtensionContext): AcpxProfileExtensionAdapter { + let sequence = 0; + return { + async request() { + throw new Error("Copilot 1.0.88 has no qualified inbound ACP extension request responder"); + }, + async notification(method, params) { + if (method !== COPILOT_ACP_EVENT_METHOD) return []; + const event = normalizeCopilotSessionEvent({ method, params }, context); + if (!event) return []; + const noticeId = identity(context, "notice", String(++sequence)); + // The optional canonical provenance object requires an originating turn. + // Session-only evidence keeps its complete source identity in details. + const details = detailFields({ ...event.data, + source: { method, eventType: event.sourceType, sessionId: event.sessionId, + ...(event.agentId ? { agentId: event.agentId } : {}), + ...(event.timestamp ? { timestamp: event.timestamp } : {}), + }, + turnAttribution: "unknown: provider session notification has no originating turn ID", + }); + const notice: CanonicalProviderEvent = { + itemId: noticeId, + eventType: "provider.notice.recorded", + payload: { + schema: "paperclip.provider.notice.v1", noticeId, + severity: event.kind === "capability_gap" ? "warning" : "info", + category: `copilot.${event.sourceType}`, scope: "session", + recoverable: true, userActionable: false, + summary: summary(event), + details, + }, + }; + // Receipt during this turn is not proof of origin. Keep all safe fields + // as session evidence; typed turn activity would misattribute late events. + return [notice]; + }, + }; +} + +function summary(event: CopilotSessionEvent): string { + const data = event.data; + if (event.kind === "capability_gap") return data.reason === "provider_omitted_event_data" + ? "Copilot omitted the payload of a native activity event." + : "Copilot reported native input without a qualified ACP response method."; + switch (event.sourceType) { + case "assistant.usage": return "Copilot reported supplemental model usage; these counters do not establish a dollar charge."; + case "session.usage_checkpoint": return "Copilot reported a cumulative AI-unit checkpoint; it is not a dollar charge."; + case "session.usage_info": return "Copilot updated context usage."; + case "session.workspace_file_changed": return `Copilot ${data.operation === "create" ? "created" : "updated"} a provider-session file; artifact resolution is pending.`; + case "session.binary_asset": return "Copilot reported a verified binary asset; artifact registration is pending."; + case "subagent.started": return "Copilot started a subagent."; + case "subagent.configured": return "Copilot updated subagent configuration."; + case "subagent.completed": return data.cancelled === true ? "Copilot subagent was interrupted." : "Copilot subagent completed."; + case "subagent.failed": return "Copilot subagent failed."; + case "session.plan_changed": return "Copilot changed its plan; this notification does not contain the plan document."; + case "session.compaction_start": return "Copilot started context compaction."; + case "session.compaction_complete": return data.success === true ? "Copilot completed context compaction." : "Copilot reported context compaction without a successful result."; + case "pending_messages.modified": return "Copilot changed its pending messages; the notification does not include queue contents."; + case "session.background_tasks_changed": return "Copilot background tasks changed; the notification does not include task contents."; + case "session.context_changed": return "Copilot reported context changes; the admitted workspace remains fixed."; + case "session.permissions_changed": return "Copilot reported permission state; Paperclip policy remains authoritative."; + case "session.mode_changed": return "Copilot reported a mode change."; + case "session.idle": return "Copilot reported idle activity; the ACP prompt response determines turn settlement."; + case "session.completion_receipt": return "Copilot reported a completion receipt; it does not independently settle the turn."; + default: return "Copilot reported native activity."; + } +} + +function detailFields(data: Record): Array<{ name: string; value: string }> { + const details: Array<{ name: string; value: string }> = []; + const visit = (value: unknown, name: string): void => { + if (value !== null && typeof value === "object" && !Array.isArray(value)) { + for (const [key, entry] of Object.entries(value)) visit(entry, name ? `${name}.${key}` : key); + } else if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") { + // Preserve the complete field path for sensitive-key redaction. The + // normalizer admits only known, typed counters/flags: their numeric token + // counts are not credentials, so they retain value-only redaction. + // Flattening must not discard a sensitive ancestor such as credentials. + // Apply the shared key rule to each path segment before publishing it. + const safe = typeof value === "string" + ? name.split(".").reduce((entry, key) => redactSemanticValue(entry, key), value) + : value; + details.push({ name: bounded(name, 160), value: bounded(String(safe), 4000) }); + } + }; + visit(data, ""); + if (details.length > 64) throw new Error("Copilot projected detail fields exceed their declared bound"); + return details; +} +function identity(context: AcpxProfileExtensionContext, family: string, source: string): string { + return `copilot-${family}-${createHash("sha256").update(JSON.stringify([context.sessionId, context.turnId, source])).digest("hex")}`; +} +function bounded(value: string, max: number): string { + const safe = String(redactPaperclipSemanticValue(value)); + return safe.length <= max ? safe : `${safe.slice(0, max - 12)} [truncated]`; +} diff --git a/packages/paperclip-runner/src/drivers/acpx/copilot-installation.ts b/packages/paperclip-runner/src/drivers/acpx/copilot-installation.ts new file mode 100644 index 00000000000..64cf5a89bb8 --- /dev/null +++ b/packages/paperclip-runner/src/drivers/acpx/copilot-installation.ts @@ -0,0 +1,41 @@ +import { join } from "node:path"; +import { resolveRunnerProviderAssetsRoot } from "./provider-assets-root.js"; +import { verifyNativeAcpxInstallation, type VerifiedAcpxInstallation } from "./installation-integrity.js"; +import { COPILOT_LAUNCH_ARGUMENTS, COPILOT_VERSION } from "./copilot-profile.js"; +import { QUALIFIED_ACPX_PROFILES, type QualifiedAcpxProfile } from "./qualified-profiles.js"; + +export const COPILOT_CLOSURE_SHA256 = Object.freeze({ + "darwin-arm64": "362f2663e967fb9e34a814bac4619cbf89e6b23069c4051ab1f2f686852d0a32", + "darwin-x64": "c08b7c3dd4e7bcf9a3e16ec6eba29cfa10308e865d196c5f120a3a15f6b3116a", + "linux-x64": "a3d8f4367cfa1694d79e3f8b7930b6fbfe42a229c272b375b11951d631db8d07", +}); + +/** Admission primitive only. Pending candidates remain gated by qualification. */ +export async function verifyCopilotInstallation(profile: QualifiedAcpxProfile): Promise { + const expected = QUALIFIED_ACPX_PROFILES.copilot; + if (profile.agent !== "copilot" || profile.agentProfileVersion !== expected.agentProfileVersion + || profile.acpxVersion !== expected.acpxVersion || profile.agentServerPackage !== "@github/copilot" + || profile.agentServerVersion !== COPILOT_VERSION || profile.commandDigest !== expected.commandDigest + || profile.agentRuntimePackage !== null || profile.agentRuntimeVersion !== null) { + throw new Error("Copilot installation requires the exact pinned candidate profile"); + } + const platform = `${process.platform}-${process.arch}`; + if (!Object.prototype.hasOwnProperty.call(COPILOT_CLOSURE_SHA256, platform)) { + throw new Error(`Copilot native distribution is not pinned for ${platform}`); + } + const distributionRoot = join(resolveRunnerProviderAssetsRoot(import.meta.url, "copilot"), platform); + let native: VerifiedAcpxInstallation; + try { native = await verifyNativeAcpxInstallation({ + distributionRoot, + manifestPath: join(distributionRoot, ".paperclip-copilot-closure.json"), + expectedClosureSha256: COPILOT_CLOSURE_SHA256[platform as keyof typeof COPILOT_CLOSURE_SHA256], + executable: "copilot", fixedArguments: COPILOT_LAUNCH_ARGUMENTS, + isolatedCacheEnvironmentName: "COPILOT_PKG_CACHE_HOME", + copilotDistributionDirectory: "distribution", + }); } catch { + throw Object.assign(new Error("Install the verified Copilot runtime beside the admitted sidecar."), { code: "COPILOT_INSTALLATION_INVALID", retryable: false }); + } + // The host identity binds the versioned profile. Native admission independently + // binds the complete platform closure before creating each single-use lease. + return Object.freeze({ ...native, commandDigest: expected.commandDigest }); +} diff --git a/packages/paperclip-runner/src/drivers/acpx/copilot-permission-context.ts b/packages/paperclip-runner/src/drivers/acpx/copilot-permission-context.ts new file mode 100644 index 00000000000..d0a24575e06 --- /dev/null +++ b/packages/paperclip-runner/src/drivers/acpx/copilot-permission-context.ts @@ -0,0 +1,22 @@ +import { redactPaperclipSemanticValue } from "../../semantic-tools/redaction.js"; +import { safeAcpxLocations } from "./safe-locations.js"; + +export const COPILOT_PERMISSION_CONTEXT_CONTRACT = "copilot-edit-permission-context-v1"; +const record = (value: unknown): Record => + value !== null && typeof value === "object" && !Array.isArray(value) ? value as Record : {}; + +/** Display context only; this does not authorize filesystem access. */ +export function safeCopilotEditTarget(value: unknown, workingDirectory: string | undefined): string | undefined { + const call = record(value); + if (call.kind !== "edit" || !workingDirectory) return; + const input = record(call.rawInput); + if (call.locations !== undefined && !Array.isArray(call.locations)) return; + if (Array.isArray(call.locations) && (call.locations.length > 16 || call.locations.some(x => typeof record(x).path !== "string"))) return; + const paths = [input.path, input.fileName, ...(Array.isArray(call.locations) ? call.locations.map(x => record(x).path) : [])].filter(x => x !== undefined); + if (!paths.length || paths.some(x => typeof x !== "string" || !x || x.trim() !== x || x.length > 2048 || /[\\\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(x))) return; + const safe = paths.flatMap(path => safeAcpxLocations([{ path }], workingDirectory, call.kind, call.title)); + const names = safe.map(x => x.path).filter((x): x is string => typeof x === "string" && x.length <= 1024 && x.trim() === x && !x.includes(":")); + if (names.length !== paths.length || new Set(names).size !== 1) return; + const target = names[0]; + return target && redactPaperclipSemanticValue(target) === target ? target : undefined; +} diff --git a/packages/paperclip-runner/src/drivers/acpx/copilot-policy.ts b/packages/paperclip-runner/src/drivers/acpx/copilot-policy.ts new file mode 100644 index 00000000000..cfc467c5fd9 --- /dev/null +++ b/packages/paperclip-runner/src/drivers/acpx/copilot-policy.ts @@ -0,0 +1,165 @@ +/** Policy for the exact native Copilot 1.0.88 ACP surface. */ +export const COPILOT_AGENT_MODE = "https://agentclientprotocol.com/protocol/session-modes#agent"; + +export class CopilotPolicyViolationError extends Error { + readonly code: string = "COPILOT_POLICY_VIOLATION"; + readonly retryable = false; + constructor() { + super("Copilot session configuration or command cannot preserve the admitted permission policy."); + this.name = "CopilotPolicyViolationError"; + } +} + +export class CopilotDetachedWorkUnsupportedError extends CopilotPolicyViolationError { + override readonly code = "COPILOT_DETACHED_WORK_UNSUPPORTED"; + constructor() { + super(); + this.name = "CopilotDetachedWorkUnsupportedError"; + this.message = "Native detached commands are unsupported in this Copilot runner. Run the command attached or use a managed runtime service."; + } +} + +/** + * Native ACP interprets a leading slash as a CLI command, before inference. + * Reject every such command rather than maintaining an incomplete list of + * aliases/skills that can change mode, permissions, cwd, MCP or remote state. + * Apply to the final joined ACP text, including resumed prompts. + */ +export function assertCopilotPromptPolicy(text: string): void { + if (text.trimStart().startsWith("/")) throw new CopilotPolicyViolationError(); +} + +/** Only explicit model selection is a runner-owned configuration operation. */ +export function assertCopilotControlPolicy(method: string, params: unknown, expectedModel: string): void { + const input = record(params); + if (!expectedModel || expectedModel === "auto") throw new CopilotPolicyViolationError(); + if (method === "session/set_model" && input.modelId === expectedModel) return; + if (method === "session/set_config_option" && input.configId === "model" && input.value === expectedModel) return; + throw new CopilotPolicyViolationError(); +} + +/** + * Validate the actual new/load response on every connection, before prompting. + * Persisted ACPX status is insufficient: load can restore autopilot and turn + * allow-all back on inside the native server. Missing proof fails closed. + */ +export function assertCopilotSessionPolicy(response: unknown): void { + const state = record(response); + if (record(state.modes).currentModeId !== COPILOT_AGENT_MODE) throw new CopilotPolicyViolationError(); + assertCopilotConfigPolicy(state.configOptions); +} + +/** Copilot emits full config snapshots, not patches, in config_option_update. */ +export function assertCopilotConfigPolicy(value: unknown): void { + if (!Array.isArray(value) || value.length > 32) throw new CopilotPolicyViolationError(); + const options = new Map>(); + for (const candidate of value) { + const option = record(candidate); + if (typeof option.id !== "string" || options.has(option.id)) throw new CopilotPolicyViolationError(); + options.set(option.id, option); + if (!["mode", "allow_all", "model", "reasoning_effort", "agent"].includes(option.id)) throw new CopilotPolicyViolationError(); + if (option.id === "agent" && option.currentValue !== "") throw new CopilotPolicyViolationError(); + } + if (options.get("mode")?.currentValue !== COPILOT_AGENT_MODE || options.get("allow_all")?.currentValue !== "off") { + throw new CopilotPolicyViolationError(); + } +} + +/** Reject native detachment before permission handling, regardless of tool name. */ +export function assertCopilotToolPolicy(value: unknown): void { + if (record(record(value).rawInput).detach === true) throw new CopilotDetachedWorkUnsupportedError(); +} + +/** Call synchronously for owned-session updates; any exception aborts authority. */ +export function assertCopilotSessionUpdatePolicy(value: unknown): void { + const update = record(value); + if (update.sessionUpdate === "tool_call" || update.sessionUpdate === "tool_call_update") assertCopilotToolPolicy(update); + if (update.sessionUpdate === "current_mode_update" && update.currentModeId !== COPILOT_AGENT_MODE) { + throw new CopilotPolicyViolationError(); + } + if (update.sessionUpdate === "config_option_update") assertCopilotConfigPolicy(update.configOptions); +} + +/** One guard per actual stdio connection; never restore admission from disk. */ +export function createCopilotProtocolGuard(expectedModel: string): (direction: "inbound" | "outbound", value: unknown) => void { + const pending = new Map(); + const sessions = new Set(); + const models = new Map(); + const modelFrom = (result: unknown) => { + const options = record(result).configOptions; + return Array.isArray(options) ? record(options.find(option => record(option).id === "model")).currentValue : undefined; + }; + let failure: CopilotPolicyViolationError | undefined; + return (direction, value) => { + if (failure) throw failure; + try { + const message = record(value); + const params = record(message.params); + const id = message.id; + const method = message.method; + if (direction === "outbound" && typeof method === "string") { + if (method.startsWith("session/") && !["session/new", "session/load", "session/resume"].includes(method)) { + if (typeof params.sessionId !== "string" || !sessions.has(params.sessionId)) throw new CopilotPolicyViolationError(); + } + if (method === "session/prompt") { + if (models.get(String(params.sessionId)) !== expectedModel) throw new CopilotPolicyViolationError(); + if (!Array.isArray(params.prompt) || params.prompt.some(block => record(block).type !== "text" || typeof record(block).text !== "string")) throw new CopilotPolicyViolationError(); + assertCopilotPromptPolicy(params.prompt.map(block => record(block).text).join("\n")); + } else if (method.startsWith("session/set_")) { + assertCopilotControlPolicy(method, params, expectedModel); + } else if (!["initialize", "authenticate", "session/new", "session/load", "session/resume", "session/cancel", "session/close"].includes(method)) { + throw new CopilotPolicyViolationError(); + } + if (typeof id === "string" || typeof id === "number") { + if (pending.has(id) || pending.size >= 128) throw new CopilotPolicyViolationError(); + pending.set(id, { method, ...(typeof params.sessionId === "string" ? { sessionId: params.sessionId } : {}) }); + } + } + if (direction === "inbound" && method === undefined && (typeof id === "string" || typeof id === "number")) { + const request = pending.get(id); + pending.delete(id); + if (request && message.error === undefined) { + if (["session/new", "session/load", "session/resume"].includes(request.method)) { + assertCopilotSessionPolicy(message.result); + const sessionId = request.sessionId ?? record(message.result).sessionId; + if (typeof sessionId !== "string" || !sessionId) throw new CopilotPolicyViolationError(); + sessions.add(sessionId); + models.set(sessionId, modelFrom(message.result)); + } else if (request.method === "session/set_config_option") { + assertCopilotConfigPolicy(record(message.result).configOptions); + if (request.sessionId) models.set(request.sessionId, modelFrom(message.result)); + } else if (request.method === "session/set_model" && request.sessionId) { + models.set(request.sessionId, expectedModel); + } else if (request.method === "session/close" && request.sessionId) sessions.delete(request.sessionId); + } + } + if (direction === "inbound" && method === "session/request_permission") assertCopilotToolPolicy(params.toolCall); + if (direction === "inbound" && method === "session/update") { + // Replay can precede load's response. It still cannot introduce unsafe + // configuration, and it cannot grant admission before that response. + assertCopilotSessionUpdatePolicy(params.update); + if (record(params.update).sessionUpdate === "config_option_update" && typeof params.sessionId === "string" && sessions.has(params.sessionId)) { + const model = modelFrom(params.update); + if (models.get(params.sessionId) === expectedModel && model !== expectedModel) throw new CopilotPolicyViolationError(); + models.set(params.sessionId, model); + } + } + if (direction === "inbound" && method === "github.com/copilot/sessionEvent") { + if (["user_input.requested", "exit_plan_mode.requested", "elicitation.requested"].includes(String(params.type))) throw new CopilotPolicyViolationError(); + const data = record(params.data); + if (params.type === "session.permissions_changed" && data.mode !== "manual") throw new CopilotPolicyViolationError(); + if (params.type === "session.mode_changed" && data.newMode !== "interactive" && data.newMode !== "agent") throw new CopilotPolicyViolationError(); + } + } catch (error) { + failure = error instanceof CopilotPolicyViolationError ? error : new CopilotPolicyViolationError(); + sessions.clear(); + models.clear(); + pending.clear(); + throw failure; + } + }; +} + +function record(value: unknown): Record { + return typeof value === "object" && value !== null && !Array.isArray(value) ? value as Record : {}; +} diff --git a/packages/paperclip-runner/src/drivers/acpx/copilot-profile.ts b/packages/paperclip-runner/src/drivers/acpx/copilot-profile.ts new file mode 100644 index 00000000000..73c8d599a05 --- /dev/null +++ b/packages/paperclip-runner/src/drivers/acpx/copilot-profile.ts @@ -0,0 +1,95 @@ +import { isAbsolute, resolve } from "node:path"; + +/** This is an admission candidate, not a claim of live qualification. */ +export const COPILOT_VERSION = "1.0.88" as const; +export const COPILOT_SYSTEM_INSTRUCTIONS_FILE = "copilot-instructions.md" as const; +export const COPILOT_SYSTEM_INSTRUCTION_DELIVERY = "COPILOT_HOME/copilot-instructions.md:replace-under-lifetime-lease-before-launch:v1" as const; +export const COPILOT_CREDENTIAL_ENVIRONMENT_NAME = "COPILOT_GITHUB_TOKEN" as const; +export const COPILOT_TASK_ORIENTATION_INSTRUCTIONS = "At the start of every task turn, use the paperclip MCP server's dedicated get_task_context tool with {} and wait for its successful result before task work, report_progress, or any other task-dependent mutation. This is an advertised MCP tool, not an HTTP API route: do not use search_api or call_api to discover or substitute for get_task_context. Loaded instructions, seed state, task descriptions, and prior-turn context do not replace this read. Decide the next action from the returned context. Do not issue the context read and a dependent action in parallel. If this tool is unavailable or its read fails, report the failure and do not perform dependent actions." as const; + +// Keep permission callbacks enabled even when Paperclip's policy is approve-all. +// In particular COPILOT_ALLOW_ALL=true also trusts workspace hooks/plugins/MCP. +export const COPILOT_LAUNCH_ARGUMENTS = Object.freeze([ + "--acp", "--stdio", "--no-auto-update", "--disable-builtin-mcps", + "--no-remote", "--no-remote-export", "--no-bash-env", + "--secret-env-vars=COPILOT_GITHUB_TOKEN", +]); + +export interface CopilotSandboxDirectories { + homeDirectory: string; + configDirectory: string; + dataDirectory: string; + cacheDirectory: string; + agentHomeDirectory: string; +} + +/** Add only sandbox-owned values after the common credential allowlist. */ +export function copilotSandboxEnvironment(directories: CopilotSandboxDirectories): Readonly { + for (const directory of Object.values(directories)) { + if (!isAbsolute(directory) || resolve(directory) !== directory || directory.includes("\0")) { + throw new Error("Copilot sandbox directories must be normalized absolute paths"); + } + } + return Object.freeze({ + HOME: directories.homeDirectory, + XDG_CONFIG_HOME: directories.configDirectory, + XDG_DATA_HOME: directories.dataDirectory, + XDG_CACHE_HOME: directories.cacheDirectory, + COPILOT_HOME: directories.agentHomeDirectory, + COPILOT_CACHE_HOME: directories.cacheDirectory, + COPILOT_PKG_CACHE_HOME: directories.cacheDirectory, + COPILOT_AUTO_UPDATE: "false", + COPILOT_ALLOW_ALL: "false", + COPILOT_DISABLE_TERMINAL_TITLE: "true", + NO_COLOR: "1", + }); +} + +/** Written by the shared sandbox's private atomic writer before every admission. */ +export function copilotConfiguration(): Readonly> { + return Object.freeze({ + autoUpdate: false, + trustedFolders: [], + disableAllHooks: true, + memory: false, + ide: { autoConnect: false, openDiffOnEdit: false }, + }); +} + +export type CopilotFailureCode = + | "COPILOT_AUTH_REQUIRED" + | "COPILOT_ENTITLEMENT_DENIED" + | "COPILOT_MODEL_UNAVAILABLE" + | "COPILOT_REQUEST_FAILED"; + +/** The runner binds this credential explicitly; ambient gh login is never used. */ +export function assertCopilotCredentials(environment: Readonly): void { + const token = environment.COPILOT_GITHUB_TOKEN; + if (typeof token !== "string" || token.trim().length === 0 || token.includes("\0")) { + throw Object.assign(new Error("Bind a valid COPILOT_GITHUB_TOKEN credential for this runner."), { + code: "COPILOT_AUTH_REQUIRED", retryable: false, + }); + } +} + +/** Classify, but never echo provider text that may contain tokens or user data. */ +export function classifyCopilotFailure(error: unknown): { code: CopilotFailureCode; message: string } { + const source = error instanceof Error ? error.message + : typeof error === "string" ? error + : isRecord(error) && typeof error.message === "string" ? error.message : ""; + const message = source.slice(0, 8192).toLowerCase(); + if (/authentication required|unauthorized|invalid (?:github )?token|not (?:logged|signed) in|copilot_github_token.*(?:missing|required|not configured)|(?:missing|no) (?:copilot |github )?(?:credential|token|authentication)/.test(message)) { + return { code: "COPILOT_AUTH_REQUIRED", message: "Bind a valid COPILOT_GITHUB_TOKEN credential for this runner." }; + } + if (/entitlement|subscription|organization policy|organisation policy|policy.*(?:denied|disabled)|access denied|forbidden|not entitled/.test(message)) { + return { code: "COPILOT_ENTITLEMENT_DENIED", message: "Copilot access is denied by the account entitlement or organization policy." }; + } + if (/(?:model.*(?:not found|unavailable|not available|not supported|unsupported|invalid)|unknown model|invalid model)/.test(message)) { + return { code: "COPILOT_MODEL_UNAVAILABLE", message: "The explicitly selected Copilot model is unavailable for this account." }; + } + return { code: "COPILOT_REQUEST_FAILED", message: "The Copilot ACP request failed." }; +} + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} diff --git a/packages/paperclip-runner/src/drivers/acpx/copilot-tool-evidence.ts b/packages/paperclip-runner/src/drivers/acpx/copilot-tool-evidence.ts new file mode 100644 index 00000000000..3c2cbcb6e2c --- /dev/null +++ b/packages/paperclip-runner/src/drivers/acpx/copilot-tool-evidence.ts @@ -0,0 +1,201 @@ +import { parseSemanticToolReceipt, readNativeSemanticReceipt, sameSemanticReceipt, semanticInputSha256, type SemanticToolReceipt } from "../semantic-tool-receipt.js"; +import { updateSingleReadEvidence, type SingleReadEvidence } from "./single-read-evidence.js"; +import { createHash } from "node:crypto"; +import { redactPaperclipSemanticValue } from "../../semantic-tools/redaction.js"; +import type { CanonicalProviderEvent } from "../../provider-events.js"; +import { safeCopilotEditTarget } from "./copilot-permission-context.js"; + +const LIMIT = 256; +const CATEGORY = "copilot_tool_evidence_v1"; +type Fields = Record; +interface Tool { kind?: string; input?: string; fields: Fields; invalid?: boolean; semanticInput?: string; semanticReceipt?: SemanticToolReceipt; read?: SingleReadEvidence } +const record = (v: unknown): Record => v !== null && typeof v === "object" && !Array.isArray(v) ? v as Record : {}; +const identity = (v: unknown): v is string => typeof v === "string" && v.length > 0 && v.length <= 240 && !/[\u0000-\u001f\u007f]/u.test(v); +const shellIdentity = (v: unknown): v is string => typeof v === "string" && /^[A-Za-z0-9_.-]{1,80}$/u.test(v); +const digest = (v: string) => createHash("sha256").update(v).digest("hex"); + +/** + * Observation only, bound to one active ACP prompt iterator and its permission + * callbacks. Session passthrough notifications cannot enter this projector. + * Old sessions without these notices supply no qualification evidence. This + * additive projection changes source/pack provenance, not execution identity. + */ +export function createCopilotToolEvidence(binding: { + sessionId: string; turnId: string; workingDirectory: string; + active: () => boolean; emit: (event: CanonicalProviderEvent) => void; + unavailable?: () => void; +}) { + const tools = new Map(); + const shells = new Map(); + const permissionTools = new Set(); + const semanticReceipts = new Map(); + const matchedReceipts = new Map(); + let sequence = 0; + let incomplete = false; + let broken = false; + function safely(action: () => T): T | undefined { + if (broken) return; + try { return action(); } catch { + // Observation cannot undo an authoritative response or terminal outcome. + broken = true; + try { notice("evidence_incomplete", "unavailable", { reason: "projection_failed" }); } catch { /* Report through diagnostics if the sink itself failed. */ } + try { binding.unavailable?.(); } catch { /* Diagnostics cannot undo delivery. */ } + return; + } + } + function notice(stage: string, toolCallId: string | undefined, fields: Fields, method = "session/update", category = CATEGORY) { + if (!binding.active() || !identity(binding.sessionId) || !identity(binding.turnId)) return; + if (sequence >= 2048) { + if (incomplete) return; + incomplete = true; stage = "evidence_incomplete"; fields = { reason: "notice_limit" }; + } + const itemId = `copilot-evidence-${digest(`${binding.sessionId}:${binding.turnId}`).slice(0, 24)}-${++sequence}`; + binding.emit({ eventType: "provider.notice.recorded", itemId, payload: redactPaperclipSemanticValue({ + schema: "paperclip.provider.notice.v1", noticeId: itemId, severity: "info", + category, scope: "turn", recoverable: true, userActionable: false, + summary: stage === "semantic_result" ? "Paperclip returned a semantic tool result." : stage === "evidence_incomplete" ? "Some Copilot activity details are unavailable." + : stage === "permission_requested" ? "Copilot requested permission." + : stage === "permission_delivered" ? (fields.outcome === "reject_once" ? "Copilot received your denial." : "Copilot received your permission decision.") + : fields.shellState === "started" ? (fields.detach === false ? "Copilot started an attached command." : "Copilot started a background command.") + : fields.shellState === "completed" ? `Copilot reported command completion with exit code ${fields.exitCode}.` + : fields.operation === "edit" ? `Copilot file operation: ${fields.status}.` + : `Copilot tool operation: ${fields.status}.`, + provenance: { method, eventType: stage, sessionId: binding.sessionId, turnId: binding.turnId }, + details: Object.entries({ stage, ...(toolCallId === undefined ? {} : { toolCallId }), ...fields }).map(([name, value]) => ({ name, value: String(value) })), + }) as Record }); + } + function inputFields(call: Record): Fields { + const input = record(call.rawInput); + const fields: Fields = {}; + if (call.kind === "edit") { const path = safeCopilotEditTarget(call, binding.workingDirectory); if (path) fields.target = path; } + if (call.kind === "execute" && typeof input.command === "string" && input.command.length > 0 && Buffer.byteLength(input.command) <= 64 * 1024) { + // ACP exposes an execution kind, not the native tool name. Never infer + // `bash` from a provider-controlled title/description. + fields.operation = "execute"; + fields.commandSha256 = `sha256:${digest(input.command)}`; + if (input.mode === "sync" || input.mode === "async") fields.mode = input.mode; + if (typeof input.detach === "boolean") fields.detach = input.detach; + } + if (shellIdentity(input.shellId)) fields.shellId = input.shellId; + return fields; + } + const projection = { + tool(event: unknown) { + if (!binding.active()) return; + const call = record(event); + if (call.type !== "tool_call" || !identity(call.toolCallId)) return; + const id = call.toolCallId; + let state = tools.get(id); + if (!state) { + // A delta without its origin cannot acquire a different tool's fields. + if (call.tag !== "tool_call") return; + if (tools.size >= LIMIT) { + if (!incomplete) { incomplete = true; notice("evidence_incomplete", id, { reason: "tool_limit" }); } + return; + } + state = { fields: {} }; tools.set(id, state); + } else if (call.tag === "tool_call") { state.invalid = true; notice("evidence_incomplete", id, { reason: "reused_tool_origin" }); } + if (state.invalid) return; + if (state.semanticReceipt) { state.invalid = true; notice("evidence_incomplete", id, { reason: "reused_semantic_lifecycle" }); return; } + if (typeof call.kind === "string") { + if (state.kind && state.kind !== call.kind) { state.invalid = true; notice("evidence_incomplete", id, { reason: "changed_tool_kind" }); return; } + state.kind = call.kind; + } + if (state.kind === "read") state.read = updateSingleReadEvidence(state.read, call, binding.workingDirectory); + if (call.rawInput !== undefined) { + // Retain only a bounded digest of the native arguments, never their text. + let inputDigest: string | undefined; + try { if (Buffer.byteLength(JSON.stringify(call.rawInput)) <= 1024 * 1024) inputDigest = semanticInputSha256(call.rawInput); } catch { /* Malformed input cannot correlate. */ } + if (state.semanticInput && inputDigest !== state.semanticInput) { state.invalid = true; notice("evidence_incomplete", id, { reason: "changed_tool_input" }); return; } + state.semanticInput = inputDigest; + const fields = inputFields({ ...call, kind: state.kind }); + const fingerprint = JSON.stringify(fields); + if (state.input && state.input !== fingerprint) { state.invalid = true; notice("evidence_incomplete", id, { reason: "changed_tool_input" }); return; } + state.input = fingerprint; state.fields = fields; + } + const status = ["pending", "in_progress", "completed", "failed"].includes(String(call.status)) ? String(call.status) : undefined; + if (!status) return; + const fields: Fields = { ...state.fields, status, ...(state.read?.targetSha256 ? { readTargetSha256: state.read.targetSha256 } : {}) }; + if (state.kind === "edit" || state.kind === "read") fields.operation = state.kind; + const output = record(call.rawOutput).content; + // Parse only the pinned native wrapper, never substrings in command output. + if (status === "completed" && typeof output === "string" && output.length <= 256) { + const started = /^$/u.exec(output.trim()); + if (started && typeof fields.commandSha256 === "string") { + const shellId = started[1]!; + if (!shells.has(shellId) && shells.size < LIMIT) shells.set(shellId, id); + else if (shells.get(shellId) !== id) { shells.set(shellId, null); notice("evidence_incomplete", id, { reason: "reused_shell_origin" }); } + if (shells.get(shellId) === id) { fields.shellId = shellId; fields.commandToolCallId = id; fields.shellState = "started"; } + } + const completed = /^$/u.exec(output.trim()); + if (completed && state.kind === "read" && fields.shellId === completed[1] && shells.get(completed[1]!) && !tools.get(shells.get(completed[1]!)!)?.invalid) { + const exitCode = Number(completed[2]); + if (Number.isSafeInteger(exitCode) && exitCode >= -2147483648 && exitCode <= 2147483647) { + fields.commandToolCallId = shells.get(completed[1]!)!; + fields.shellState = "completed"; fields.exitCode = exitCode; + } + } + } + if (call.rawOutput !== undefined) { + const candidate = readNativeSemanticReceipt(call.rawOutput); + if (candidate) { + const authoritative = semanticReceipts.get(candidate.callIdentitySha256); + const previous = matchedReceipts.get(candidate.callIdentitySha256); + if ((status !== "completed" && status !== "failed") || !authoritative + || !sameSemanticReceipt(authoritative, candidate) || state.semanticInput !== candidate.inputSha256 + || (status === "failed") !== (candidate.outcome === "error") || previous !== undefined) { + state.invalid = true; + notice("evidence_incomplete", id, { reason: "semantic_receipt_conflict" }); + return; + } + matchedReceipts.set(candidate.callIdentitySha256, id); + state.semanticReceipt = candidate; + fields.semanticOperationId = candidate.operationId; + fields.semanticCallIdentitySha256 = candidate.callIdentitySha256; + fields.semanticInputSha256 = candidate.inputSha256; + if (candidate.schema === "paperclip.semantic_tool_receipt.v2") fields.semanticNormalizedInputSha256 = candidate.normalizedInputSha256; + fields.semanticResultSha256 = candidate.resultSha256; + fields.semanticOutcome = candidate.outcome; + } + } + notice("tool", id, fields); + }, + permission(request: unknown, requestId: string, offeredActions: readonly string[]) { + const raw = record(record(request).raw); + const call = record(raw.toolCall); + if (!binding.active() || raw.sessionId !== binding.sessionId || !identity(call.toolCallId) || !identity(requestId)) return undefined; + if (permissionTools.has(call.toolCallId) || permissionTools.size >= LIMIT) { notice("evidence_incomplete", call.toolCallId, { reason: "ambiguous_permission_origin" }); return undefined; } + permissionTools.add(call.toolCallId); + const fields: Fields = { requestId, ...inputFields(call) }; + if (call.kind === "edit" || call.kind === "read") fields.operation = call.kind; + fields.declineOffered = offeredActions.includes("decline"); + notice("permission_requested", call.toolCallId, fields, "session/request_permission"); + let delivered = false; + return (outcome: string) => safely(() => { + if (delivered || !["allow_once", "allow_always", "reject_once", "cancel"].includes(outcome)) return; + delivered = true; + notice("permission_delivered", call.toolCallId as string, { ...fields, outcome }, "session/request_permission"); + }); + }, + }; + return { + captureSemanticReceipt(): ((receipt: SemanticToolReceipt) => void) | undefined { + if (!binding.active()) return undefined; + // This closure belongs to this turn, even if a successor becomes active. + return receipt => { safely(() => { + if (!binding.active()) return; + const parsed = parseSemanticToolReceipt(receipt); + if (!parsed || semanticReceipts.size >= LIMIT || semanticReceipts.has(parsed.callIdentitySha256)) { + if (parsed && semanticReceipts.has(parsed.callIdentitySha256)) semanticReceipts.set(parsed.callIdentitySha256, null); + notice("evidence_incomplete", "semantic", { reason: "ambiguous_semantic_receipt" }); + return; + } + semanticReceipts.set(parsed.callIdentitySha256, parsed); + notice("semantic_result", undefined, { ...parsed }, "paperclip/semantic_tool_result", parsed.schema === "paperclip.semantic_tool_receipt.v2" ? "paperclip_semantic_tool_receipt_v2" : "paperclip_semantic_tool_receipt_v1"); + }); }; + }, + tool: (event: unknown) => { safely(() => projection.tool(event)); }, + permission: (request: unknown, requestId: string, offeredActions: readonly string[]) => safely(() => projection.permission(request, requestId, offeredActions)), + }; +} +export type CopilotToolEvidence = ReturnType; diff --git a/packages/paperclip-runner/src/drivers/acpx/generated-profiles.ts b/packages/paperclip-runner/src/drivers/acpx/generated-profiles.ts index a7e34cf1411..a283881ca3e 100644 --- a/packages/paperclip-runner/src/drivers/acpx/generated-profiles.ts +++ b/packages/paperclip-runner/src/drivers/acpx/generated-profiles.ts @@ -48,13 +48,12 @@ export const QUALIFIED_ACPX_PROFILE_DATA = { "protocolVersion": 1, "acpxVersion": "0.13.1", "agent": "copilot", - "agentProfileVersion": 2, + "agentProfileVersion": 31, "agentServerPackage": "@github/copilot", "agentServerVersion": "1.0.88", "agentRuntimePackage": null, "agentRuntimeVersion": null, - "commandDigest": "sha256:b18c01603dd0169d233140709cfaa8bf5304a03cf5de78ca4f625f30013e8457", - "qualificationStatus": "pending", + "commandDigest": "sha256:4a22e4c50fd213c79cd02fd3c5369aef2256ac719762c62f5b70c691cd47e76b", "permissionPolicy": "interactive" }, "claude": { diff --git a/packages/paperclip-runner/src/drivers/acpx/installation-integrity.test.ts b/packages/paperclip-runner/src/drivers/acpx/installation-integrity.test.ts index 547b12a1d78..da9a8b369da 100644 --- a/packages/paperclip-runner/src/drivers/acpx/installation-integrity.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/installation-integrity.test.ts @@ -1927,7 +1927,7 @@ async function expectOutput( const [exitCode] = await once(child, "exit"); expect(exitCode, stderr).toBe(0); const normalized = process.platform === "darwin" - ? stdout.replace(/\/private\/var\/[^"\s]*\/paperclip-acpx-[^/]+\/0/g, "/proc/self/fd/4") + ? stdout.replace(/\/private\/(?:var\/[^"\s]*|tmp)\/paperclip-acpx-[^/]+\/0/g, "/proc/self/fd/4") : stdout; expect(normalized).toBe(expected); } diff --git a/packages/paperclip-runner/src/drivers/acpx/installation-integrity.ts b/packages/paperclip-runner/src/drivers/acpx/installation-integrity.ts index f015d60799d..42d6b7c38a3 100644 --- a/packages/paperclip-runner/src/drivers/acpx/installation-integrity.ts +++ b/packages/paperclip-runner/src/drivers/acpx/installation-integrity.ts @@ -1368,27 +1368,47 @@ function commandLease( privateSnapshot: AcpxPrivateSnapshot | null, ): VerifiedAcpxCommandLease { let consumed = false; - let directoriesReleased = false; - const releaseDirectories = async (): Promise => { - if (directoriesReleased) return; - directoriesReleased = true; - await Promise.all([ + let spawnedChild: ChildProcess | undefined; + let directoriesRelease: Promise | undefined; + let snapshotRetirement: Promise | undefined; + const releaseDirectories = (): Promise => { + return (directoriesRelease ??= Promise.all([ commandDirectory.close(), ...dependencyAncestors.map((handle) => handle.close()), ...(providerRuntimeExecutable === null ? [] : [providerRuntimeExecutable.close()]), - ]); + ]).then(() => undefined)); + }; + const retireSnapshot = (): Promise => { + if ( + privateSnapshot && + spawnedChild?.pid !== undefined && + spawnedChild.exitCode === null && + spawnedChild.signalCode === null + ) { + return Promise.reject( + new Error("Verified ACPX snapshot cannot retire before provider exit"), + ); + } + return (snapshotRetirement ??= Promise.resolve() + .then(() => privateSnapshot?.close()) + .catch((error: unknown) => { + snapshotRetirement = undefined; + throw error; + })); }; const releaseDirectoriesBestEffort = (): void => { void releaseDirectories().catch(() => undefined); }; const close = async (): Promise => { - if (consumed) return; + const wasConsumed = consumed; consumed = true; - verifiedBytes.fill(0); + // A spawned command owns its source buffer until its pipe write completes. + if (!wasConsumed) verifiedBytes.fill(0); await releaseDirectories(); - await privateSnapshot?.close(); + // Consumption prevents a second launch; it does not complete retirement. + await retireSnapshot(); }; return { spawn( @@ -1457,7 +1477,7 @@ function commandLease( environment[VERIFIED_PROVIDER_RUNTIME_TARGET_ENV] = providerRuntimeEnvironmentVariable; } - child = spawnChildProcess( + child = spawnedChild = spawnChildProcess( runtimeHandoff.executable, guarded ? [ @@ -1562,12 +1582,18 @@ function commandLease( } catch (error) { verifiedBytes.fill(0); releaseDirectoriesBestEffort(); - void privateSnapshot?.close(); + if (spawnedChild?.pid !== undefined) { + spawnedChild.once("exit", () => { void retireSnapshot().catch(() => undefined); }); + spawnedChild.once("error", () => { void retireSnapshot().catch(() => undefined); }); + spawnedChild.kill(); + } else { + void retireSnapshot().catch(() => undefined); + } throw error; } releaseDirectoriesBestEffort(); - child.once("exit", () => { void privateSnapshot?.close(); }); - child.once("error", () => { void privateSnapshot?.close(); }); + child.once("exit", () => { void retireSnapshot().catch(() => undefined); }); + child.once("error", () => { void retireSnapshot().catch(() => undefined); }); const sourceInput = child.stdio[COMMAND_SOURCE_FD] as Writable | null; if (sourceInput === null) { verifiedBytes.fill(0); diff --git a/packages/paperclip-runner/src/drivers/acpx/native-distribution-integrity.test.ts b/packages/paperclip-runner/src/drivers/acpx/native-distribution-integrity.test.ts index d140717ae31..fc561ba5289 100644 --- a/packages/paperclip-runner/src/drivers/acpx/native-distribution-integrity.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/native-distribution-integrity.test.ts @@ -8,6 +8,9 @@ import type { ChildProcess } from "node:child_process"; import { afterEach, describe, expect, it, vi } from "vitest"; import { awaitVerifiedAcpxProviderExit, awaitVerifiedAcpxProviderOwnership, verifyNativeAcpxInstallation } from "./installation-integrity.js"; import { createNativeAcpxDistributionSnapshot, readNativeAcpxDistributionEntries, parseNativeAcpxDistributionEntries, type NativeAcpxDistributionInput, type NativeAcpxDistributionEntry } from "./native-distribution-integrity.js"; +import { openCodexAcpxRuntime } from "./codex-runtime-adapter.js"; +import { createAcpxCommandLeaseOwner } from "./command-lease-owner.js"; +import { resolveQualifiedAcpxProfile } from "./qualified-profiles.js"; vi.mock("node:fs/promises", async (importOriginal) => { const original = await importOriginal(); @@ -100,6 +103,39 @@ describe("native ACPX execution closure", () => { expect(() => lease.spawn()).toThrow("closed"); await lease.close(); }); + it("awaits consumed command snapshot deletion before lease retirement", async () => { + const declaration = await fixture(); + const lease = await (await verifyNativeAcpxInstallation(declaration)).openCommand(); + const originalRemove = vi.mocked(rm).getMockImplementation()!; + const deleting = gate(); const holdDeletion = gate(); + let privateRoot: string | undefined; + vi.mocked(rm).mockImplementation(async (path, options) => { + if (String(path).includes("paperclip-acpx-native-")) { + privateRoot = String(path); deleting.release(); await holdDeletion.promise; + } + return await originalRemove(path, options); + }); + let retired = false; + let retirement: Promise | undefined; + try { + const result = await output(lease.spawn()); + expect(result.code, result.error).toBe(0); + await deleting.promise; + retirement = lease.close().then(() => { retired = true; }); + await new Promise(resolve => setImmediate(resolve)); + expect(retired).toBe(false); + expect(privateRoot).toBeDefined(); + await expect(stat(privateRoot!)).resolves.toBeDefined(); + } finally { + holdDeletion.release(); + await retirement; + if (privateRoot) await vi.waitFor(async () => { + await expect(stat(privateRoot!)).rejects.toMatchObject({ code: "ENOENT" }); + }); + vi.mocked(rm).mockImplementation(originalRemove); + } + expect(retired).toBe(true); + }); it("gives packaged executables a fresh private extraction cache each launch", async () => { const declaration = { ...await fixture(), isolatedCacheEnvironmentName: "COPILOT_PKG_CACHE_HOME" as const }; const install = await verifyNativeAcpxInstallation(declaration); @@ -108,6 +144,56 @@ describe("native ACPX execution closure", () => { expect(first.text).toMatch(/^native:fixed:.*paperclip-acpx-native-.*\/state$/); expect(first.text).not.toBe(second.text); }); + it("retains the snapshot until the live provider exits", async () => { + const declaration = { ...await fixture({ node: true, script: 'console.log(process.env.COPILOT_PKG_CACHE_HOME); setInterval(() => {}, 1000);' }), isolatedCacheEnvironmentName: "COPILOT_PKG_CACHE_HOME" as const }; + const lease = await (await verifyNativeAcpxInstallation(declaration)).openCommand(); + const child = lease.spawn(); + const completed = output(child); + let privateRoot: string | undefined; + try { + const [chunk] = await once(child.stdout!, "data"); + privateRoot = dirname(String(chunk).trim()); + expect(privateRoot).toContain("paperclip-acpx-native-"); + await expect(lease.close()).rejects.toThrow("cannot retire before provider exit"); + await expect(stat(privateRoot)).resolves.toBeDefined(); + expect(child.exitCode).toBeNull(); + } finally { + child.kill("SIGTERM"); + await completed; + await lease.close(); + } + await expect(stat(privateRoot!)).rejects.toMatchObject({ code: "ENOENT" }); + }, 30_000); + it("reports failed deletion and retries retirement without relaunching", async () => { + const lease = await (await verifyNativeAcpxInstallation(await fixture())).openCommand(); + const originalRemove = vi.mocked(rm).getMockImplementation()!; + const deleting = gate(); const holdDeletion = gate(); + let privateRoot: string | undefined; + let failed = false; + vi.mocked(rm).mockImplementation(async (path, options) => { + if (String(path).includes("paperclip-acpx-native-") && !failed) { + privateRoot = String(path); deleting.release(); await holdDeletion.promise; + failed = true; throw new Error("snapshot deletion failed"); + } + return await originalRemove(path, options); + }); + try { + expect((await output(lease.spawn())).code).toBe(0); + await deleting.promise; + const rejected = expect(lease.close()).rejects.toThrow("snapshot deletion failed"); + await new Promise(resolve => setImmediate(resolve)); + holdDeletion.release(); + await rejected; + await expect(stat(privateRoot!)).resolves.toBeDefined(); + expect(() => lease.spawn()).toThrow("closed"); + await lease.close(); + await expect(stat(privateRoot!)).rejects.toMatchObject({ code: "ENOENT" }); + } finally { + holdDeletion.release(); + vi.mocked(rm).mockImplementation(originalRemove); + await lease.close(); + } + }); it("loads a pinned Node entrypoint while rejecting unqualified external modules", async () => { const declaration = await fixture({ node: true }); const result = await output((await (await verifyNativeAcpxInstallation(declaration)).openCommand()).spawn()); @@ -226,8 +312,114 @@ describe("native ACPX execution closure", () => { child.kill(); await Promise.all(fences.map(server => new Promise((resolve, reject) => server.close(error => error ? reject(error) : resolve())))); } }, 15_000); + + it("proves native child death before any caller cleanup, despite the launcher's pending guardian read", async () => { + const declaration = await fixture({ node: true, script: 'console.log(process.pid);setInterval(()=>{},1000);' }); + const fences = await Promise.all([listen(), listen()]); + const fds = fences.map(server => (server as Server & { _handle?: { fd?: number } })._handle!.fd!); + const child = (await (await verifyNativeAcpxInstallation(declaration)).openCommand()).spawn([], {}, { + credentialFenceFds: [fds[0]!, fds[1]!], activateCredentialFenceOwner: async () => undefined, + }); + const exited = once(child, "exit"); + let deadline: ReturnType | undefined; + try { + const ready = once(child.stdout!, "data"); + await awaitVerifiedAcpxProviderOwnership(child); + const [chunk] = await ready; + const nativePid = Number(String(chunk).trim()); + expect(Number.isSafeInteger(nativePid) && nativePid > 0 && nativePid !== child.pid).toBe(true); + const proof = awaitVerifiedAcpxProviderExit(child); + process.kill(nativePid, "SIGKILL"); + // No guardian.kill/close is allowed to manufacture the lifetime proof. + await Promise.race([proof, new Promise((_, reject) => { + deadline = setTimeout(() => reject(new Error("Native exit proof remained open after child death")), 3_000); + })]); + await exited; + expect(() => process.kill(nativePid, 0)).toThrow(); + } finally { + clearTimeout(deadline); + if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL"); + await exited; + await Promise.all(fences.map(server => new Promise((resolve, reject) => server.close(error => error ? reject(error) : resolve())))); + } + }, 15_000); + + it("expires a real ACPX permission on native child death without replaying its mutation", async () => { + // This is a deterministic ACP peer in a verified native distribution. No + // provider credential, remote service or model is involved. + const declaration = await fixture({ node: true, script: blockingCopilotPeer }); + const fences = await Promise.all([listen(), listen()]); + const fds = fences.map(server => (server as Server & { _handle?: { fd?: number } })._handle!.fd!); + const installation = await verifyNativeAcpxInstallation(declaration); + const owner = createAcpxCommandLeaseOwner(await installation.openCommand(), installation.openCommand); + const pidFile = join(declaration.distributionRoot, "native-pid"); + let port: Awaited> | undefined; + let deadline: ReturnType | undefined; + try { + port = await openCodexAcpxRuntime({ + command: owner.command, refreshConsumedCommand: owner.refreshConsumedCommand, + profile: resolveQualifiedAcpxProfile("copilot", "gpt-5.6-luna"), + cwd: declaration.distributionRoot, stateDirectory: join(declaration.distributionRoot, "state"), + providerSessionKey: "native-death-fixture", permissionMode: "approve-reads", + permissionPolicy: { autoApprove: ["read"], escalate: ["write"], defaultAction: "escalate" }, + launchEnvironment: { PATH: "/usr/bin:/bin", NATIVE_TEST_PID_FILE: pidFile }, + credentialFenceFds: [fds[0]!, fds[1]!], activateCredentialFenceOwner: async () => undefined, + systemInstructions: "Read task context before editing.", mcpServers: [], retainFailedAdmissionCleanup: () => undefined, + }); + let pending!: () => void; + const requested = new Promise(resolve => { pending = resolve; }); + let callbackSignal!: AbortSignal; + let lateAnswer!: (value: { outcome: "allow_once" }) => void; + const handler = vi.fn((_request, context) => { + callbackSignal = context.signal; pending(); + return new Promise<{ outcome: "allow_once" }>(resolve => { lateAnswer = resolve; }); + }); + const turn = port.startTurn({ text: "Attempt one edit", requestId: "native-death-turn", onPermissionRequest: handler }); + const settled = expect(turn.result).rejects.toMatchObject({ code: "ACPX_PROVIDER_PROCESS_LOST" }); + const draining = expect((async () => { for await (const _event of turn.events) { /* drain */ } })()) + .rejects.toMatchObject({ code: "ACPX_PROVIDER_PROCESS_LOST" }); + const bounded = new Promise((_, reject) => { + deadline = setTimeout(() => reject(new Error("Real native ACPX death remained unsettled")), 5_000); + }); + await Promise.race([requested, bounded]); + const nativePid = Number(await readFile(pidFile, "utf8")); + expect(Number.isSafeInteger(nativePid) && nativePid > 0).toBe(true); + process.kill(nativePid, "SIGKILL"); + await Promise.race([Promise.all([settled, draining]), bounded]); + expect(callbackSignal.aborted).toBe(true); + lateAnswer({ outcome: "allow_once" }); + expect(() => port!.startTurn({ text: "Replay", requestId: "replay" })).toThrow("provider exited"); + expect(handler).toHaveBeenCalledOnce(); + expect(() => process.kill(nativePid, 0)).toThrow(); + } finally { + clearTimeout(deadline); + await port?.close({ reason: "offline native-death fixture complete" }); + await owner.command.close(); + await Promise.all(fences.map(server => new Promise((resolve, reject) => server.close(error => error ? reject(error) : resolve())))); + } + }, 15_000); }); +const blockingCopilotPeer = String.raw` +const send=m=>process.stdout.write(JSON.stringify({jsonrpc:'2.0',...m})+'\n'); +require('node:fs').writeFileSync(process.env.NATIVE_TEST_PID_FILE,String(process.pid)); +const mode='https://agentclientprotocol.com/protocol/session-modes#agent'; +const config=[{id:'mode',name:'Mode',type:'select',currentValue:mode,options:[{value:mode,name:'Agent'}]}, + {id:'allow_all',name:'Allow all',type:'select',currentValue:'off',options:[{value:'off',name:'Off'}]}, + {id:'model',name:'Model',type:'select',currentValue:'gpt-5.6-luna',options:[{value:'gpt-5.6-luna',name:'Luna'}]}]; +const snapshot={sessionId:'copilot-death-session',modes:{currentModeId:mode,availableModes:[{id:mode,name:'Agent'}]},configOptions:config, + models:{currentModelId:'gpt-5.6-luna',availableModels:[{modelId:'gpt-5.6-luna',name:'Luna'}]}}; +require('node:readline').createInterface({input:process.stdin}).on('line',line=>{ + const m=JSON.parse(line); + if(m.method==='initialize')send({id:m.id,result:{protocolVersion:1,agentCapabilities:{loadSession:true},authMethods:[]}}); + else if(['session/new','session/load'].includes(m.method))send({id:m.id,result:snapshot}); + else if(m.method==='session/set_model'||m.method==='session/close')send({id:m.id,result:{}}); + else if(m.method==='session/set_config_option')send({id:m.id,result:{configOptions:config}}); + else if(m.method==='session/prompt')send({id:'pending-edit',method:'session/request_permission',params:{sessionId:'copilot-death-session', + toolCall:{toolCallId:'native-edit',title:'Write file',kind:'edit',status:'pending',rawInput:{path:'target.txt',content:'FORBIDDEN'}}, + options:[{optionId:'allow',name:'Allow',kind:'allow_once'},{optionId:'deny',name:'Deny',kind:'reject_once'}]}}); +});`; + async function listen(): Promise { const server = createServer(); server.listen(0, "127.0.0.1"); await once(server, "listening"); return server; } diff --git a/packages/paperclip-runner/src/drivers/acpx/native-distribution-integrity.ts b/packages/paperclip-runner/src/drivers/acpx/native-distribution-integrity.ts index d8afb68cb70..d0a9da44498 100644 --- a/packages/paperclip-runner/src/drivers/acpx/native-distribution-integrity.ts +++ b/packages/paperclip-runner/src/drivers/acpx/native-distribution-integrity.ts @@ -16,6 +16,8 @@ export interface NativeAcpxDistributionInput { entrypoint?: string; fixedArguments: readonly string[]; isolatedCacheEnvironmentName?: "COPILOT_PKG_CACHE_HOME"; + /** Trusted Copilot profile only; resolved inside each immutable spawn lease. */ + copilotDistributionDirectory?: string; } export interface NativeAcpxDistributionSnapshot { snapshot: AcpxPrivateSnapshot; @@ -32,6 +34,7 @@ const NATIVE_COPY_CONCURRENCY = 8; const NATIVE_COPY_BUFFER_BYTES = 32 * 1024 * 1024; const BOOTSTRAP = ".paperclip-native-entry.cjs"; const GUARD = ".paperclip-native-module-guard.cjs"; +const COPILOT_ENTRY = ".paperclip-copilot-entry"; export const NATIVE_ACPX_BOOTSTRAP_NAME = BOOTSTRAP; const sha256 = (value: string | Buffer) => createHash("sha256").update(value).digest("hex"); const validPath = (value: unknown): value is string => typeof value === "string" && value.length > 0 && value.length <= 4_096 && !isAbsolute(value) && !/[\u0000-\u001f\u007f\\]/.test(value) && value.split("/").every(part => part.length > 0 && part !== "." && part !== ".."); @@ -58,7 +61,8 @@ export function parseNativeAcpxDistributionEntries(value: unknown, expectedSha25 } export async function readNativeAcpxDistributionEntries(input: NativeAcpxDistributionInput): Promise { - if (!validPath(input.executable) || (input.entrypoint !== undefined && !validPath(input.entrypoint)) || input.fixedArguments.length > 128 || input.fixedArguments.some(arg => typeof arg !== "string" || arg.length > 16_384 || arg.includes("\0")) || (input.isolatedCacheEnvironmentName !== undefined && input.isolatedCacheEnvironmentName !== "COPILOT_PKG_CACHE_HOME")) throw new Error("Native ACPX launch declaration is invalid"); + if (!validPath(input.executable) || (input.entrypoint !== undefined && !validPath(input.entrypoint)) || input.fixedArguments.length > 128 || input.fixedArguments.some(arg => typeof arg !== "string" || arg.length > 16_384 || arg.includes("\0")) || (input.isolatedCacheEnvironmentName !== undefined && input.isolatedCacheEnvironmentName !== "COPILOT_PKG_CACHE_HOME") + || (input.copilotDistributionDirectory !== undefined && (!validPath(input.copilotDistributionDirectory) || input.entrypoint !== undefined))) throw new Error("Native ACPX launch declaration is invalid"); const file = await open(input.manifestPath, constants.O_RDONLY | constants.O_NOFOLLOW); try { const before = await file.stat({ bigint: true }); @@ -67,6 +71,7 @@ export async function readNativeAcpxDistributionEntries(input: NativeAcpxDistrib if (!same(before, await file.stat({ bigint: true })) || bytes.length !== Number(before.size)) throw new Error("Native ACPX manifest changed while read"); const entries = parseNativeAcpxDistributionEntries(JSON.parse(bytes.toString("utf8")), input.expectedClosureSha256); if (!entries.some(entry => entry.path === input.executable && entry.executable && entry.size > 0) || (input.entrypoint !== undefined && !entries.some(entry => entry.path === input.entrypoint && entry.size > 0))) throw new Error("Native ACPX executable or entrypoint is absent from its closure"); + if (input.copilotDistributionDirectory !== undefined && !entries.some(entry => entry.path === `${input.copilotDistributionDirectory}/index.js` && entry.size > 0)) throw new Error("Copilot owned entrypoint is absent from its closure"); return entries; } finally { await file.close(); } } @@ -143,12 +148,23 @@ export async function createNativeAcpxDistributionSnapshot(input: NativeAcpxDist if (!same(rootBefore, await heldRoot.stat({ bigint: true })) || !same(rootBefore, await lstat(source, { bigint: true }))) throw new Error("Native ACPX distribution root changed during snapshot"); const executable = join(packageRoot, ...input.executable.split("/")); const args = [...(input.entrypoint === undefined ? [] : ["--require", join(packageRoot, GUARD), join(packageRoot, ...input.entrypoint.split("/"))]), ...input.fixedArguments]; - if (input.entrypoint !== undefined) { + let copilotEntryDirectory: string | undefined; + if (input.copilotDistributionDirectory !== undefined) { + copilotEntryDirectory = join(packageRoot, COPILOT_ENTRY); + await mkdir(copilotEntryDirectory, { mode: 0o700 }); directories.add(copilotEntryDirectory); + const shim = Buffer.from([ + `require(${JSON.stringify(join(packageRoot, GUARD))});`, + `import(require("node:url").pathToFileURL(${JSON.stringify(join(packageRoot, input.copilotDistributionDirectory, "index.js"))}).href).catch(error=>{console.error(error);process.exitCode=1;});`, + ].join("\n")); + const shimPath = join(copilotEntryDirectory, "index.js"); + await writeFile(shimPath, shim, { mode: 0o400, flag: "wx" }); digests[shimPath] = sha256(shim); + } + if (input.entrypoint !== undefined || copilotEntryDirectory !== undefined) { const guard = Buffer.from(nativeModuleGuard(digests)); await writeFile(join(packageRoot, GUARD), guard, { mode: 0o400, flag: "wx" }); digests[join(packageRoot, GUARD)] = sha256(guard); } - const bootstrap = Buffer.from(nativeBootstrap(executable, digests[executable]!, args, input.isolatedCacheEnvironmentName ? { name: input.isolatedCacheEnvironmentName, value: cacheRoot } : undefined)); + const bootstrap = Buffer.from(nativeBootstrap(executable, digests[executable]!, args, input.isolatedCacheEnvironmentName ? { name: input.isolatedCacheEnvironmentName, value: cacheRoot } : undefined, copilotEntryDirectory)); await writeFile(join(packageRoot, BOOTSTRAP), bootstrap, { mode: 0o400, flag: "wx" }); digests[join(packageRoot, BOOTSTRAP)] = sha256(bootstrap); // executable is null: commandLease's separately-qualified provider runtime @@ -164,7 +180,7 @@ export async function createNativeAcpxDistributionSnapshot(input: NativeAcpxDist } finally { await heldRoot.close(); } } -function nativeBootstrap(executable: string, executableDigest: string, args: string[], cache?: { name: string; value: string }): string { +function nativeBootstrap(executable: string, executableDigest: string, args: string[], cache?: { name: string; value: string }, copilotEntryDirectory?: string): string { return [ 'const {spawn}=require("node:child_process");', 'const fs=require("node:fs");', @@ -174,12 +190,23 @@ function nativeBootstrap(executable: string, executableDigest: string, args: str 'const env={...process.env}; delete env.PAPERCLIP_ACPX_NATIVE_GUARDED; delete env.PAPERCLIP_ACPX_PRIVATE_SNAPSHOT; delete env.PAPERCLIP_VERIFIED_RUNTIME_EXECUTABLE;', 'env.NODE_DISABLE_COMPILE_CACHE="1"; delete env.NODE_COMPILE_CACHE;', ...(cache ? [`env[${JSON.stringify(cache.name)}]=${JSON.stringify(cache.value)};`] : []), + ...(copilotEntryDirectory ? [ + // Never permit the native loader to choose a different cached version, + // app, bootstrap mode or module path supplied by a workspace/caller. + 'for(const name of ["COPILOT_CLI_VERSION","COPILOT_CLI_DIST_DIR","COPILOT_CLI_RESOLVED_DIST_DIR","COPILOT_VOICE_SERVER_MODE","COPILOT_SHUTDOWN_FLUSH","NODE_OPTIONS","NODE_PATH"])delete env[name];', + `env.COPILOT_CLI_DIST_DIR=${JSON.stringify(copilotEntryDirectory)};`, + ] : []), 'if(guarded)for(const fd of [5,6,7,8])fs.fstatSync(fd);', `const executable=${JSON.stringify(executable)};const fd=fs.openSync(executable,fs.constants.O_RDONLY|fs.constants.O_NOFOLLOW);`, `if(require("node:crypto").createHash("sha256").update(fs.readFileSync(fd)).digest("hex")!==${JSON.stringify(executableDigest)})throw new Error("Native ACPX executable changed before spawn");`, 'const stdio=guarded?[0,1,2,5,6,7,8]:[0,1,2]; const childExecutable=process.platform==="linux"?"/proc/self/fd/"+stdio.length:executable;stdio.push(fd);', `const child=spawn(childExecutable,${JSON.stringify(args)},{env,cwd:process.cwd(),shell:false,detached:false,stdio});fs.closeSync(fd);`, - 'child.once("error",()=>process.exit(1)); child.once("exit",(code,signal)=>process.exit(signal?1:code??1));', + // A guarded Node launcher has a pending filesystem read on its guardian + // pipe. process.exit can wait for that read while the guardian waits for + // this launcher to exit. Retire the live owned group through the kernel; + // no saved PID/group identity or provider JavaScript cleanup is required. + 'const retire=code=>{if(guarded){try{process.kill(0,"SIGKILL");}catch{process.kill(process.pid,"SIGKILL");}}else process.exit(code);};', + 'child.once("error",()=>retire(1)); child.once("exit",(code,signal)=>retire(signal?1:code??1));', 'for(const signal of ["SIGTERM","SIGINT","SIGHUP"])process.on(signal,()=>child.kill(signal));', ].join("\n"); } diff --git a/packages/paperclip-runner/src/drivers/acpx/profile-activity.ts b/packages/paperclip-runner/src/drivers/acpx/profile-activity.ts index e367cde6266..58f956db47e 100644 --- a/packages/paperclip-runner/src/drivers/acpx/profile-activity.ts +++ b/packages/paperclip-runner/src/drivers/acpx/profile-activity.ts @@ -1,3 +1,4 @@ +import { createCopilotToolEvidence } from "./copilot-tool-evidence.js"; import { cursorActivityAdapter } from "./cursor-activity.js"; import type { CanonicalProviderEvent } from "../../provider-events.js"; import type { AcpxExtensionInput } from "./profile-extensions.js"; @@ -27,6 +28,7 @@ export interface AcpxActivityAdapter { const adapters: Readonly> = { cursor: cursorActivityAdapter, + copilot: Object.freeze({ createToolEvidence: createCopilotToolEvidence }), }; const noActivity: AcpxActivityAdapter = Object.freeze({}); diff --git a/packages/paperclip-runner/src/drivers/acpx/profile-compatibility.test.ts b/packages/paperclip-runner/src/drivers/acpx/profile-compatibility.test.ts index 371ab04127e..13586f1fcd8 100644 --- a/packages/paperclip-runner/src/drivers/acpx/profile-compatibility.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/profile-compatibility.test.ts @@ -4,11 +4,24 @@ import { isSupportedAcpxProfileVersion } from "./profile-compatibility.js"; describe("historical ACPX profile decoding", () => { it("retains each provider's existing revision boundary", () => { expect(isSupportedAcpxProfileVersion("cursor", 14)).toBe(true); - for (const agent of ["pi", "claude", "codex", "grok", "copilot"]) { + for (const agent of ["pi", "claude", "codex", "grok"]) { expect(isSupportedAcpxProfileVersion(agent, 5)).toBe(true); expect(isSupportedAcpxProfileVersion(agent, 6)).toBe(false); } }); + it("decodes retained Copilot revisions and the current profile without widening other providers", () => { + for (const version of [1, 5, 6, 12, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]) { + expect(isSupportedAcpxProfileVersion("copilot", version)).toBe(true); + } + expect(isSupportedAcpxProfileVersion("copilot", 32)).toBe(false); + for (const agent of ["cursor", "pi", "claude", "codex", "grok"]) { + expect(isSupportedAcpxProfileVersion(agent, 23)).toBe(false); + expect(isSupportedAcpxProfileVersion(agent, 24)).toBe(false); + expect(isSupportedAcpxProfileVersion(agent, 25)).toBe(false); + expect(isSupportedAcpxProfileVersion(agent, 26)).toBe(false); + expect(isSupportedAcpxProfileVersion(agent, 27)).toBe(false); + } + }); it.each([0, 15, 1.5, "11", null, undefined, NaN])("rejects invalid revisions: %s", version => { expect(isSupportedAcpxProfileVersion("cursor", version)).toBe(false); }); diff --git a/packages/paperclip-runner/src/drivers/acpx/profile-compatibility.ts b/packages/paperclip-runner/src/drivers/acpx/profile-compatibility.ts index 86426040906..a4fbcbcbe6b 100644 --- a/packages/paperclip-runner/src/drivers/acpx/profile-compatibility.ts +++ b/packages/paperclip-runner/src/drivers/acpx/profile-compatibility.ts @@ -1,9 +1,9 @@ /** Decodable historical profile revisions, not permission to launch them. * Exact current profile/package/digest admission is checked separately. */ -export type AcpxProfileVersion = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14; +export type AcpxProfileVersion = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31; const historicalVersions: Readonly> = { pi: [1, 2, 3, 4, 5], claude: [1, 2, 3, 4, 5], codex: [1, 2, 3, 4, 5], - grok: [1, 2, 3, 4, 5], copilot: [1, 2, 3, 4, 5], + grok: [1, 2, 3, 4, 5], copilot: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31], cursor: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14], }; diff --git a/packages/paperclip-runner/src/drivers/acpx/profile-extensions.ts b/packages/paperclip-runner/src/drivers/acpx/profile-extensions.ts index bf87e73f70f..b5bd6c8bede 100644 --- a/packages/paperclip-runner/src/drivers/acpx/profile-extensions.ts +++ b/packages/paperclip-runner/src/drivers/acpx/profile-extensions.ts @@ -1,3 +1,5 @@ +import { createCopilotProfileExtensionAdapter } from "./copilot-extension-adapter.js"; +import { COPILOT_ACP_CLIENT_CAPABILITIES } from "./copilot-events.js"; import { createCursorProfileExtensionAdapter, CURSOR_CLIENT_CAPABILITIES } from "./cursor-extensions.js"; import type { HarnessRuntimeRequestResolution } from "../../contracts/harness-driver.js"; import { parsePaperclipQuestionSet, type PaperclipQuestionSet } from "../../contracts/question-set.js"; @@ -37,10 +39,12 @@ export function createAcpxProfileExtensionAdapter( agent: QualifiedAcpxAgent, context: AcpxProfileExtensionContext, ): AcpxProfileExtensionAdapter | null { + if (agent === "copilot") return createCopilotProfileExtensionAdapter(context); if (agent === "cursor") return createCursorProfileExtensionAdapter(context); return null; } export function acpxProfileClientCapabilities(agent: QualifiedAcpxAgent): Record { + if (agent === "copilot") return structuredClone(COPILOT_ACP_CLIENT_CAPABILITIES); if (agent === "cursor") return structuredClone(CURSOR_CLIENT_CAPABILITIES); return {}; } diff --git a/packages/paperclip-runner/src/drivers/acpx/profile-installation.ts b/packages/paperclip-runner/src/drivers/acpx/profile-installation.ts index a4725a425d8..58e8b2ed165 100644 --- a/packages/paperclip-runner/src/drivers/acpx/profile-installation.ts +++ b/packages/paperclip-runner/src/drivers/acpx/profile-installation.ts @@ -1,3 +1,5 @@ +import { assertCopilotCredentials, classifyCopilotFailure } from "./copilot-profile.js"; +import { verifyCopilotInstallation } from "./copilot-installation.js"; import { verifyCursorInstallation } from "./cursor-installation.js"; import { assertCursorWorkspacePolicy } from "./cursor-launch-policy.js"; import { resolveQualifiedAcpxProfile, type QualifiedAcpxAgent, type QualifiedAcpxProfile } from "./qualified-profiles.js"; @@ -5,6 +7,7 @@ import { verifyQualifiedAcpxInstallation, type VerifiedAcpxInstallation } from " /** Closed build-owned registry. Provider branches add their pinned installations here. */ export async function verifyAcpxProfileInstallation(profile: QualifiedAcpxProfile): Promise { + if (profile.agent === "copilot") return verifyCopilotInstallation(profile); if (profile.agent === "cursor") { try { return await verifyCursorInstallation(profile); } catch (error) { @@ -25,6 +28,7 @@ export async function assertAcpxProfileWorkspace(agent: QualifiedAcpxAgent, work /** Called with the sanitized launch environment, never ambient process.env. */ export function assertAcpxProfileEnvironment(agent: QualifiedAcpxAgent, environment: Readonly): void { + if (agent === "copilot") assertCopilotCredentials(environment); if (agent === "cursor" && !environment.CURSOR_API_KEY?.trim() && !environment.CURSOR_AUTH_TOKEN?.trim()) { throw Object.assign(new Error("Cursor credentials are missing. Bind a company secret to CURSOR_API_KEY or CURSOR_AUTH_TOKEN in the agent environment."), { code: "CURSOR_CREDENTIALS_MISSING", retryable: false }); } @@ -32,6 +36,11 @@ export function assertAcpxProfileEnvironment(agent: QualifiedAcpxAgent, environm /** Provider admission diagnostics expose no raw provider strings or credentials. */ export function classifyAcpxProfileError(agent: QualifiedAcpxAgent, error: unknown): Error | null { + if (agent === "copilot") { + const failure = classifyCopilotFailure(error); + if (failure.code === "COPILOT_REQUEST_FAILED") return null; + return Object.assign(new Error(failure.message), { code: failure.code, retryable: false }); + } if (agent !== "cursor" || !(error instanceof Error)) return null; const message = error.message; let code: string; diff --git a/packages/paperclip-runner/src/drivers/acpx/provider-assets-root.test.ts b/packages/paperclip-runner/src/drivers/acpx/provider-assets-root.test.ts index 600ca2111a7..90f08600a0e 100644 --- a/packages/paperclip-runner/src/drivers/acpx/provider-assets-root.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/provider-assets-root.test.ts @@ -7,7 +7,7 @@ import { resolveRunnerProviderAssetsRoot } from "./provider-assets-root.js"; const roots: string[] = []; afterEach(async () => { vi.unstubAllEnvs(); await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true }))); }); -async function root() { const path = await mkdtemp(join(tmpdir(), "runner-provider-assets-")); roots.push(path); return path; } +async function root() { const path = await realpath(await mkdtemp(join(tmpdir(), "runner-provider-assets-"))); roots.push(path); return path; } it("uses one fixed provider directory for source, compiled and bundled runner layouts", async () => { vi.stubEnv("PAPERCLIP_ACPX_PROVIDER_PACKAGE_ROOT", undefined); @@ -31,6 +31,18 @@ it("resolves descriptor sidecars only through the runner-bound canonical package expect(() => resolveRunnerProviderAssetsRoot("file:///proc/self/fd/18", "pi")).toThrow("normalized absolute"); }); +it("uses the public server owner for its vendored Copilot probe and selected sidecar", async () => { + const path = await root(); + await writeFile(join(path, "package.json"), JSON.stringify({ name: "@paperclipai/server" })); + vi.stubEnv("PAPERCLIP_ACPX_PROVIDER_PACKAGE_ROOT", undefined); + vi.stubEnv("PAPERCLIP_ACPX_PROVIDER_PACKAGE_MANIFEST", undefined); + const moduleUrl = pathToFileURL(join(path, "dist/vendor/paperclip-runner/drivers/acpx/copilot-installation.js")).href; + expect(resolveRunnerProviderAssetsRoot(moduleUrl, "copilot")).toBe(join(path, "provider-assets/copilot")); + vi.stubEnv("PAPERCLIP_ACPX_PROVIDER_PACKAGE_ROOT", path); + vi.stubEnv("PAPERCLIP_ACPX_PROVIDER_PACKAGE_MANIFEST", join(path, "package.json")); + expect(resolveRunnerProviderAssetsRoot("file:///proc/self/fd/18", "copilot")).toBe(join(path, "provider-assets/copilot")); +}); + it("resolves the public server bundle without repository paths or candidate overrides", async () => { const path = await root(); const vendored = join(await realpath(path), "dist/vendor/paperclip-runner"); diff --git a/packages/paperclip-runner/src/drivers/acpx/provider-assets-root.ts b/packages/paperclip-runner/src/drivers/acpx/provider-assets-root.ts index e37116d75a8..a6198213282 100644 --- a/packages/paperclip-runner/src/drivers/acpx/provider-assets-root.ts +++ b/packages/paperclip-runner/src/drivers/acpx/provider-assets-root.ts @@ -4,6 +4,7 @@ import { fileURLToPath } from "node:url"; type NativeProvider = "cursor" | "copilot" | "pi"; const RUNNER_PACKAGE_NAME = "@paperclipai/paperclip-runner"; +const SERVER_PACKAGE_NAME = "@paperclipai/server"; /** Resolve only runner-owned package assets, including descriptor-loaded sidecars. */ export function resolveRunnerProviderAssetsRoot(moduleUrl: string, provider: NativeProvider): string { @@ -28,7 +29,9 @@ export function resolveRunnerProviderAssetsRoot(moduleUrl: string, provider: Nat if (before.dev !== after.dev || before.ino !== after.ino || before.size !== after.size || before.mtimeNs !== after.mtimeNs || before.ctimeNs !== after.ctimeNs || bytes.length !== Number(before.size) || realpathSync(manifest) !== canonicalManifest) throw new Error("Runner provider manifest changed during admission"); const value = JSON.parse(bytes.toString("utf8")) as { name?: unknown }; - if (value?.name === "@paperclipai/server") { + if (value?.name === SERVER_PACKAGE_NAME && provider === "copilot") { + packageRoot = dirname(canonicalManifest); + } else if (value?.name === SERVER_PACKAGE_NAME) { // runnerd derives this binding from the verified sidecar in the public // server package. Images may carry assets alongside that bundle; local // explicit setup uses the OS-account cache when package assets are absent. @@ -42,7 +45,8 @@ export function resolveRunnerProviderAssetsRoot(moduleUrl: string, provider: Nat if (boundManifest !== undefined) throw new Error("Runner provider manifest has no bound package root"); const url = new URL(moduleUrl); if (url.protocol !== "file:" || url.search || url.hash) throw new Error("Provider factory is outside a verified package layout"); - if (new RegExp(`/(?:src|dist)/drivers/acpx/${provider}-installation\\.(?:ts|js)$`).test(url.pathname)) packageRoot = fileURLToPath(new URL("../../../", url)); + if (provider === "copilot" && new RegExp(`/dist/vendor/paperclip-runner/drivers/acpx/${provider}-installation\\.js$`).test(url.pathname)) packageRoot = fileURLToPath(new URL("../../../../../", url)); + else if (new RegExp(`/(?:src|dist)/drivers/acpx/${provider}-installation\\.(?:ts|js)$`).test(url.pathname)) packageRoot = fileURLToPath(new URL("../../../", url)); else if (/\/dist\/cli\/acpx-runtime-sidecar\.(?:cjs|js)$/.test(url.pathname)) packageRoot = fileURLToPath(new URL("../../", url)); else if (new RegExp(`/dist/vendor/paperclip-runner/drivers/acpx/${provider}-installation\\.(?:js)$`).test(url.pathname)) packageRoot = fileURLToPath(new URL("../../", url)); else if (/\/dist\/vendor\/paperclip-runner\/cli\/acpx-runtime-sidecar\.(?:cjs|js)$/.test(url.pathname)) packageRoot = fileURLToPath(new URL("../", url)); diff --git a/packages/paperclip-runner/src/drivers/acpx/qualified-profiles.ts b/packages/paperclip-runner/src/drivers/acpx/qualified-profiles.ts index 9702f120b80..1a3012ff463 100644 --- a/packages/paperclip-runner/src/drivers/acpx/qualified-profiles.ts +++ b/packages/paperclip-runner/src/drivers/acpx/qualified-profiles.ts @@ -43,6 +43,7 @@ export function resolveQualifiedAcpxProfile( ): QualifiedAcpxProfile { const profile = QUALIFIED_ACPX_PROFILES[agent]; if (!requestedModel.trim()) throw new Error("ACPX model must not be empty"); + if (agent === "copilot" && ["auto", "default"].includes(requestedModel.trim().toLowerCase())) throw new Error("Copilot requires an explicit model ID"); return { ...structuredClone(profile), qualificationModel: requestedModel, reportedModelId: requestedModel }; } diff --git a/packages/paperclip-runner/src/drivers/acpx/runtime-host.test.ts b/packages/paperclip-runner/src/drivers/acpx/runtime-host.test.ts index f8b66548ab7..c833da2ddce 100644 --- a/packages/paperclip-runner/src/drivers/acpx/runtime-host.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/runtime-host.test.ts @@ -1137,7 +1137,7 @@ describe("ACPX runtime host", () => { ).rejects.toThrow("initialization and cleanup failed"); expect(runtime.close).toHaveBeenCalledOnce(); expect(credential.close).not.toHaveBeenCalled(); - expect(fixture.commandClose).toHaveBeenCalledOnce(); + expect(fixture.commandClose).not.toHaveBeenCalled(); expect(retainedAdmissionCleanup).not.toBeNull(); let cleanupSettled = false; void retainedAdmissionCleanup!.finally(() => { @@ -1150,6 +1150,7 @@ describe("ACPX runtime host", () => { await retainedAdmissionCleanup; expect(cleanupSettled).toBe(true); expect(credential.close).toHaveBeenCalledOnce(); + expect(fixture.commandClose).toHaveBeenCalledOnce(); }); it("retains credential ownership when runtime shutdown fails until retry succeeds", async () => { @@ -1227,7 +1228,7 @@ describe("ACPX runtime host", () => { const first = host.close({ reason: "runtime close pending" }); await waitForAcpxOperation(() => expect(runtime.close).toHaveBeenCalledOnce()); - await waitForAcpxOperation(() => expect(fixture.commandClose).toHaveBeenCalledOnce()); + expect(fixture.commandClose).not.toHaveBeenCalled(); const second = host.close({ reason: "same exact close" }); await expect(readFile(authPath, "utf8")).resolves.toBe("{}"); await expect( @@ -1245,6 +1246,7 @@ describe("ACPX runtime host", () => { undefined, undefined, ]); + expect(fixture.commandClose).toHaveBeenCalledOnce(); await expect(readFile(authPath)).rejects.toMatchObject({ code: "ENOENT" }); const contender = await waitForAcpxOperation(() => stageManagedCodexCredential({ @@ -1257,9 +1259,10 @@ describe("ACPX runtime host", () => { await contender.close(); }, ACPX_LONG_WAIT_TEST_TIMEOUT_MS); - it("retains the exact pending cleanup while independent resources close", async () => { + it("retains the exact pending cleanup and command snapshot until runtime retirement", async () => { const fixture = await hostFixture(); - const firstClose = new Promise(() => undefined); + let resolveRuntimeClose!: () => void; + const firstClose = new Promise(resolve => { resolveRuntimeClose = resolve; }); const runtime = runtimePort({ onClose: vi .fn() @@ -1287,6 +1290,9 @@ describe("ACPX runtime host", () => { await Promise.resolve(); expect(settled).toBe(false); expect(runtime.close).toHaveBeenCalledOnce(); + expect(fixture.commandClose).not.toHaveBeenCalled(); + resolveRuntimeClose(); + await Promise.all([first, second]); expect(fixture.commandClose).toHaveBeenCalledOnce(); }, ACPX_LONG_WAIT_TEST_TIMEOUT_MS); diff --git a/packages/paperclip-runner/src/drivers/acpx/runtime-host.ts b/packages/paperclip-runner/src/drivers/acpx/runtime-host.ts index c1230c9394d..64879be0828 100644 --- a/packages/paperclip-runner/src/drivers/acpx/runtime-host.ts +++ b/packages/paperclip-runner/src/drivers/acpx/runtime-host.ts @@ -55,6 +55,7 @@ import { } from "./recovery-identity.js"; import { prepareAcpxRuntimeSandbox, + refreshCopilotSystemInstructions, type AcpxRuntimeSandbox, type AcpxProviderRuntimePolicy, } from "./runtime-sandbox.js"; @@ -473,7 +474,7 @@ export class AcpxRuntimeHost { // agent and run. Environment/config values cannot widen the grant. Each // resumed process receives the newly registered copy; collection already // requires verified provider shutdown in the native executor. - const agentFiles = options.agent === "cursor" + const agentFiles = options.agent === "cursor" || options.agent === "copilot" ? bindAcpxAgentFiles(options.runtimeContext, [sandbox.root, ...(installation.agentServerPackageJsonPath === null ? [] : [dirname(installation.agentServerPackageJsonPath)]), ]) : null; @@ -481,6 +482,14 @@ export class AcpxRuntimeHost { launchEnvironment = Object.freeze({ ...launchEnvironment, AGENT_HOME: agentFiles.root, }); } + if (options.agent === "copilot") { + // A rejected contender must never overwrite an active provider's text. + // Do not race this write against cancellation: retain the lifetime lease + // until the atomic refresh settles, then honor an intervening abort. + options.signal?.throwIfAborted(); + await refreshCopilotSystemInstructions(sandbox, boundedInstructions(options.systemInstructions)); + options.signal?.throwIfAborted(); + } if (options.agent === "pi") { const skills = await acquireAbortableAdmissionResource({ signal: options.signal, @@ -1215,11 +1224,9 @@ async function cleanupRuntimeResources( return error; } }; - // The command lease owns only the already-consumed verified launch - // snapshot, so it can be released as shutdown starts. The credential is - // different: a provider whose exact runtime close is pending or failed may - // still read or rewrite its home. Retain both the staged bytes and the - // exclusive home lease until that exact close succeeds. + // The runtime must retire before its command snapshot can be removed. + // Keep both the snapshot and credential while the provider is still alive; + // failed cleanup remains owned and can be retried after process retirement. const runtimeOutcome = runtime ? settle(() => runtime.close({ reason })) : Promise.resolve(null); @@ -1229,9 +1236,10 @@ async function cleanupRuntimeResources( await runtimeOutcome; return toolBridge === null ? null : await settle(() => toolBridge.close()); })(); - const commandOutcome = command - ? settle(() => command.close()) - : Promise.resolve(null); + const commandOutcome = (async (): Promise => { + await runtimeOutcome; + return command === null ? null : await settle(() => command.close()); + })(); const credentialOutcome = (async (): Promise => { const runtimeError = await runtimeOutcome; if (runtimeError !== null || credential === null) return null; diff --git a/packages/paperclip-runner/src/drivers/acpx/runtime-sandbox.ts b/packages/paperclip-runner/src/drivers/acpx/runtime-sandbox.ts index f38f174712d..3546bd4bb2e 100644 --- a/packages/paperclip-runner/src/drivers/acpx/runtime-sandbox.ts +++ b/packages/paperclip-runner/src/drivers/acpx/runtime-sandbox.ts @@ -1,4 +1,5 @@ import { configuredEnvironmentKeys } from "../../configured-environment.js"; +import { COPILOT_SYSTEM_INSTRUCTIONS_FILE, COPILOT_TASK_ORIENTATION_INSTRUCTIONS } from "./copilot-profile.js"; import { randomBytes } from "node:crypto"; import { constants, @@ -635,6 +636,23 @@ async function ensurePrivateDirectory( return physical; } +/** Call only while the host owns the provider lifetime lease, before launch. */ +export async function refreshCopilotSystemInstructions( + sandbox: Pick, + instructions: string, +): Promise { + const current = `${instructions}\n\n# Paperclip task orientation\n${COPILOT_TASK_ORIENTATION_INSTRUCTIONS}\n`; + if (current.includes("\0") || Buffer.byteLength(current) > 32 * 1024) { + throw new Error("Provider runtime instructions exceed their bounded size"); + } + // Native Copilot reloads this file on session/load. Empty caller text clears + // old caller instructions while retaining the current task-orientation rule. + await writePrivateFile( + join(sandbox.agentHomeDirectory, COPILOT_SYSTEM_INSTRUCTIONS_FILE), + current, + ); +} + async function writePrivateFile( filePath: string, value: string, diff --git a/packages/paperclip-runner/src/drivers/acpx/single-read-evidence.test.ts b/packages/paperclip-runner/src/drivers/acpx/single-read-evidence.test.ts index b0c597ce562..109889dd736 100644 --- a/packages/paperclip-runner/src/drivers/acpx/single-read-evidence.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/single-read-evidence.test.ts @@ -2,6 +2,7 @@ import { createHash } from "node:crypto"; import { describe, expect, it } from "vitest"; import { updateSingleReadEvidence } from "./single-read-evidence.js"; import { createCursorToolEvidence } from "./cursor-tool-evidence.js"; +import { createCopilotToolEvidence } from "./copilot-tool-evidence.js"; import { validateAcpxRichEvent } from "./profile-extensions.js"; const path = `.paperclip-eval-action-${"a".repeat(36)}.txt`; const hash = `sha256:${createHash("sha256").update(path).digest("hex")}`; @@ -43,7 +44,7 @@ it("completes an empty pending origin only from its full shape before execution expect(updateSingleReadEvidence(unproven, { tag: "tool_call_update", rawInput: { path } }, "/workspace")).toEqual({}); } }); -for (const [provider, create] of [["cursor", createCursorToolEvidence]] as const) { +for (const [provider, create] of [["cursor", createCursorToolEvidence], ["copilot", createCopilotToolEvidence]] as const) { describe(`${provider} passive single-read origin`, () => { function setup() { const rows: any[] = []; const projector = create({ sessionId: "session", turnId: "turn", workingDirectory: "/workspace", active: () => true, emit: event => { validateAcpxRichEvent(event); rows.push(Object.fromEntries((event.payload.details as any[]).map(d => [d.name, d.value]))); } }); return { rows, projector }; } @@ -64,7 +65,7 @@ for (const [provider, create] of [["cursor", createCursorToolEvidence]] as const s.projector.tool({ type: "tool_call", tag: "tool_call_update", toolCallId: "other", kind: "read", status: "completed", rawInput: { path } }); expect(s.rows).toHaveLength(1); expect(s.rows[0].readTargetSha256).toBeUndefined(); }); - it("publishes the pending origin after its delayed complete input, retaining exact proof on every notice", () => { + it.runIf(provider === "cursor")("publishes the pending origin after its delayed complete input, retaining exact proof on every notice", () => { const s = setup(); s.projector.tool({ ...origin, rawInput: {}, locations: undefined }); expect(s.rows).toEqual([]); 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 5e6fac128da..ebd0f9d2948 100644 --- a/packages/paperclip-runner/src/drivers/codex/app-server-transport.ts +++ b/packages/paperclip-runner/src/drivers/codex/app-server-transport.ts @@ -1,5 +1,6 @@ import { configuredEnvironment } from "../../configured-environment.js"; import type { NativeTurnControlCapabilities } from "../../contracts/types.js"; +import type { NativeRunRuntimeGrant } from "../../contracts/runtime-context.js"; import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process"; import type { HarnessRuntimeRequestResolution } from "../../contracts/harness-driver.js"; import { githubCredentialEnvironment } from "../../github-credential-environment.js"; @@ -65,6 +66,7 @@ export interface CodexAppServerTransport { runId: string; turnId: string; itemId: string; + currentRunGrant?: NativeRunRuntimeGrant; }): Promise; /** Records post-rehydration driver mapping without affecting run authority. */ recordTraceInterpretation?(input: CodexTraceInterpretation): void; diff --git a/packages/paperclip-runner/src/drivers/codex/codex-app-server-driver.lifecycle.test.ts b/packages/paperclip-runner/src/drivers/codex/codex-app-server-driver.lifecycle.test.ts index c5ade4c19c2..7810e82bb4a 100644 --- a/packages/paperclip-runner/src/drivers/codex/codex-app-server-driver.lifecycle.test.ts +++ b/packages/paperclip-runner/src/drivers/codex/codex-app-server-driver.lifecycle.test.ts @@ -128,9 +128,10 @@ describe("Codex app-server Codex driver", () => { message: { role: "user", text: "first turn" }, }); await expect( - session.attachRun?.({ runId: "run-warm-second" }), + session.attachRun?.({ runId: "run-warm-second", currentRunGrant: { runtimeContext: null, instructions: "Current registered instructions." } }), ).resolves.toBeUndefined(); expect(transport.attachments).toHaveLength(1); + expect(transport.attachments[0]).toMatchObject({ currentRunGrant: { runtimeContext: null, instructions: "Current registered instructions." } }); expect((await session.snapshot()).activeTurnId).toBeNull(); await expect( diff --git a/packages/paperclip-runner/src/drivers/codex/codex-app-server-driver.test.ts b/packages/paperclip-runner/src/drivers/codex/codex-app-server-driver.test.ts index b5a8ee9ec12..a0f457e1115 100644 --- a/packages/paperclip-runner/src/drivers/codex/codex-app-server-driver.test.ts +++ b/packages/paperclip-runner/src/drivers/codex/codex-app-server-driver.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it, vi } from "vitest"; +import { runnerdRuntimeRequestExpiryNotification } from "../../live/runnerd-codex-transport.js"; import { resolve as resolvePath } from "node:path"; import { fileURLToPath } from "node:url"; import { SemanticToolOutcomeUnknownError } from "../../contracts/native-session-backend.js"; @@ -2407,6 +2408,67 @@ describe("Codex app-server Codex driver", () => { for (const event of terminal) expect(validatePrpEvent(event).ok).toBe(true); }); + it("preserves runnerd permission expiry before a failed provider terminal and refuses late approval", async () => { + const transport = new FakeCodexTransport(); + const resolve = vi.fn(async () => {}); + transport.runtimeRequestResolver = resolve; + const session = await makeDriver([transport]).openSession({ + runId: "run-native-expiry", normalizedSessionId: "session-native-expiry", workingDirectory: TEST_WORKING_DIRECTORY, + }); + const events: PrpEvent[] = []; + const consume = (async () => { for await (const event of session.events()) events.push(event); })(); + const { turnId } = await session.startTurn({ message: { role: "user", text: "Leave the native edit unanswered." } }); + const pending = transport.invoke({ id: "native-edit-permission", method: "session/request_permission", params: { + threadId: "thread-1", turnId, itemId: "native-edit", reason: "Write file", + choices: [{ key: "accept", label: "Allow once" }, { key: "decline", label: "Deny" }], + origin: { adapter: "acpx-runtime-sidecar", provider: "acpx", method: "session/request_permission" }, + } }); + await vi.waitFor(() => expect(session.pendingRuntimeRequests?.()).toHaveLength(1)); + // Exact Rust ACPX projector settlement shape; the facade uses its own + // provider-turn identity just as it does when creating the callback. + const payload = { provider: "acpx", requestId: "native-edit-permission", requestKind: "permission_approval", + requestType: "permission", turnId: "durable-controller-turn", itemId: "durable-item", + reason: "provider_process_lost", replayAllowed: false, adapter: "acpx-runtime-sidecar" }; + for (const kind of ["runtime_request.resolved", "runtime_request.cancelled", "runtime_request.created"]) + expect(runnerdRuntimeRequestExpiryNotification(kind, payload, "thread-1", turnId)).toBeNull(); + const expiry = runnerdRuntimeRequestExpiryNotification("runtime_request.expired", payload, "thread-1", turnId)!; + transport.push(expiry.method, expiry.params); + transport.push(expiry.method, expiry.params); // Same durable retirement cannot settle twice. + await pending; + expect(session.pendingRuntimeRequests?.()).toEqual([]); + await expect(session.resolveRuntimeRequest?.({ requestId: "native-edit-permission", turnId, resolution: { action: "accept" } })) + .rejects.toThrow(); + expect(resolve).not.toHaveBeenCalled(); + transport.push("turn/completed", { threadId: "thread-1", turn: { id: turnId, status: "failed", error: { code: "ACPX_PROVIDER_PROCESS_LOST", message: "Provider died" } } }); + await vi.waitFor(() => expect(events.some(event => event.eventType === "turn.failed")).toBe(true)); + await session.close(); await consume; + const settlements = events.filter(event => ["runtime_request.expired", "runtime_request.cancelled", "runtime_request.resolved"].includes(event.eventType)); + expect(settlements).toHaveLength(1); + expect(settlements[0]).toMatchObject({ eventType: "runtime_request.expired", turnId, itemId: "native-edit", payload: { ...payload, turnId, itemId: "native-edit" } }); + expect(events.indexOf(settlements[0]!)).toBeLessThan(events.findIndex(event => event.eventType === "turn.failed")); + expect(validatePrpEvent(settlements[0]!)).toMatchObject({ ok: true }); + }); + + it.each(["turn", "kind", "type", "replay"])("refuses canonical permission expiry with a changed %s binding", async kind => { + const transport = new FakeCodexTransport(); + const session = await makeDriver([transport]).openSession({ runId: "expiry-bound", normalizedSessionId: "expiry-bound", workingDirectory: TEST_WORKING_DIRECTORY }); + const events: PrpEvent[] = []; + const consume = (async () => { for await (const event of session.events()) events.push(event); })(); + const { turnId } = await session.startTurn({ message: { role: "user", text: "Wait for permission" } }); + const pending = transport.invoke({ id: "bound-permission", method: "session/request_permission", params: { + threadId: "thread-1", turnId, itemId: "edit", reason: "Edit", choices: [{ key: "accept", label: "Allow once" }, { key: "decline", label: "Deny" }], + origin: { adapter: "acpx-runtime-sidecar", provider: "acpx", method: "session/request_permission" }, + } }); + await vi.waitFor(() => expect(session.pendingRuntimeRequests?.()).toHaveLength(1)); + const payload = { requestId: "bound-permission", requestKind: kind === "kind" ? "runtime" : "permission_approval", + requestType: kind === "type" ? "input" : "permission", replayAllowed: kind === "replay", reason: "provider_process_lost" }; + const notification = runnerdRuntimeRequestExpiryNotification("runtime_request.expired", payload, "thread-1", kind === "turn" ? "foreign-turn" : turnId)!; + transport.push(notification.method, notification.params); + await pending; await consume; await session.close(); + expect(events.some(e => e.eventType === "runtime_request.expired")).toBe(false); + expect(events.some(e => e.eventType === "session.failed" && e.payload.code === "turn_binding_mismatch")).toBe(true); + }); + it("expires a canonical input with its full question set when the provider transport is lost", async () => { const transport = new FakeCodexTransport(); const session = await makeDriver([transport]).openSession({ 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..e804a9538e4 100644 --- a/packages/paperclip-runner/src/drivers/codex/codex-harness-session.ts +++ b/packages/paperclip-runner/src/drivers/codex/codex-harness-session.ts @@ -23,6 +23,7 @@ import { parseHarnessRuntimeRequestResolution, } from "../../contracts/harness-driver.js"; import type { NativeUserMessage } from "../../contracts/types.js"; +import type { NativeRunRuntimeGrant } from "../../contracts/runtime-context.js"; import { CODEX_RESULT_OUTPUT_SCHEMA, type CodexModelContextSnapshot, @@ -87,7 +88,7 @@ export class CodexHarnessSession }; } - async attachRun(input: { runId: string }): Promise { + async attachRun(input: { runId: string; currentRunGrant?: NativeRunRuntimeGrant }): Promise { this.assertProtocolIntegrity(); const transportOwnsQuiescence = this.transport.attachRun !== undefined; if ( @@ -102,6 +103,7 @@ export class CodexHarnessSession runId: input.runId, turnId: `turn_attachment_${randomUUID().replaceAll("-", "")}`, itemId: `item_attachment_${randomUUID().replaceAll("-", "")}`, + ...(input.currentRunGrant ? { currentRunGrant: structuredClone(input.currentRunGrant) } : {}), }); this.assertProtocolIntegrity(); if (transportOwnsQuiescence) { diff --git a/packages/paperclip-runner/src/drivers/codex/codex-notification-identity.test.ts b/packages/paperclip-runner/src/drivers/codex/codex-notification-identity.test.ts index e1fbc00415f..cdfc4bc15cf 100644 --- a/packages/paperclip-runner/src/drivers/codex/codex-notification-identity.test.ts +++ b/packages/paperclip-runner/src/drivers/codex/codex-notification-identity.test.ts @@ -16,6 +16,10 @@ describe("provider notification authority", () => { ["paperclip/canonicalProviderEvent", { threadId: null, eventType: "provider.notice.recorded" }, "root"], ["paperclip/canonicalProviderEvent", { threadId: null, eventType: "tool.execution.started" }, "invalid_authority"], ["item/started", { threadId: "root", turnId: "active" }, "root"], + ["paperclip/runtimeRequestExpired", { threadId: "root", turnId: "active" }, "root"], + ["paperclip/runtimeRequestExpired", { threadId: "child", turnId: "active" }, "invalid_authority"], + ["paperclip/runtimeRequestExpired", { threadId: null, turnId: "active" }, "invalid_authority"], + ["paperclip/runtimeRequestExpired", { threadId: "root", turnId: "old" }, "stale_turn"], ["turn/completed", { threadId: "root", turnId: "old" }, "stale_turn"], [ "turn/completed", diff --git a/packages/paperclip-runner/src/drivers/codex/codex-session-notifications.ts b/packages/paperclip-runner/src/drivers/codex/codex-session-notifications.ts index 525feb8dce4..2986309cafb 100644 --- a/packages/paperclip-runner/src/drivers/codex/codex-session-notifications.ts +++ b/packages/paperclip-runner/src/drivers/codex/codex-session-notifications.ts @@ -150,6 +150,26 @@ async function mapNotificationBody(state: CodexSessionState, notification: Codex const threadId = text(params.threadId); const turnId = text(params.turnId, text(turn.id)); const itemId = text(item.id, text(params.itemId)); + if (notification.method === "paperclip/runtimeRequestExpired") { + const payload = record(params.payload); + const requestId = text(payload.requestId); + const pending = state.pendingRuntimeRequestMap.get(requestId); + if (pending === undefined) return; + if (pending.request.turnId !== turnId || payload.requestKind !== pending.request.requestKind + || payload.requestType !== (pending.request.input === undefined ? "permission" : "input") + || payload.replayAllowed !== false || typeof payload.reason !== "string" || !payload.reason) { + state.failProtocol("turn_binding_mismatch", "Canonical request expiry changed its callback binding."); + return; + } + state.pendingRuntimeRequestMap.delete(requestId); + // Preserve durable expiry evidence with the same facade identity used + // when creating this callback. Terminal handling must not cancel it again. + state.emit("runtime_request.expired", { ...payload, + turnId: pending.request.turnId, itemId: pending.request.itemId, + }, { turnId: pending.request.turnId, itemId: pending.request.itemId }); + pending.settle(safeRequestResponse(pending.request.method, "cancel")); + return; + } if (notification.method === "paperclip/canonicalProviderEvent") { if (!isCanonicalProviderEventType(params.eventType)) { state.failProtocol("provider_event_type_invalid", "Unknown canonical provider event type."); diff --git a/packages/paperclip-runner/src/drivers/codex/codex-thread-normalization.ts b/packages/paperclip-runner/src/drivers/codex/codex-thread-normalization.ts index 6513b2446ae..d3b218bac4e 100644 --- a/packages/paperclip-runner/src/drivers/codex/codex-thread-normalization.ts +++ b/packages/paperclip-runner/src/drivers/codex/codex-thread-normalization.ts @@ -142,6 +142,7 @@ export function isSupportedCodexNotificationMethod(method: string): boolean { method === "model/safetyBuffering/updated" || method.startsWith("item/") || method === "paperclip/canonicalProviderEvent" || + method === "paperclip/runtimeRequestExpired" || method === "paperclip/workspaceChange/updated" || method === "paperclip/runResult" || method === "turn/diff/updated" || diff --git a/packages/paperclip-runner/src/drivers/copilot-metadata-probe.test.ts b/packages/paperclip-runner/src/drivers/copilot-metadata-probe.test.ts new file mode 100644 index 00000000000..014c7617d5e --- /dev/null +++ b/packages/paperclip-runner/src/drivers/copilot-metadata-probe.test.ts @@ -0,0 +1,70 @@ +import { EventEmitter } from "node:events"; +import { PassThrough, Writable } from "node:stream"; +import { access } from "node:fs/promises"; +import type { ChildProcessWithoutNullStreams } from "node:child_process"; +import { describe, expect, it, vi, beforeEach } from "vitest"; +import { QUALIFIED_ACPX_PROFILES } from "./acpx/qualified-profiles.js"; +const mocks = vi.hoisted(() => ({ verify: vi.fn() })); +vi.mock("./acpx/copilot-installation.js", () => ({ verifyCopilotInstallation: mocks.verify })); +import { createMetadataRpc, probeCopilotMetadata, validateCopilotMetadata } from "./copilot-metadata-probe.js"; +function fakeChild(reply: (message: any) => unknown) { + const child = new EventEmitter() as ChildProcessWithoutNullStreams; + child.stdout = new PassThrough(); child.stderr = new PassThrough(); + child.kill = vi.fn(() => { child.emit("close", 0); return true; }); + child.stdin = new Writable({ write(chunk, _encoding, done) { + const message = JSON.parse(chunk.toString()); + const response = reply(message); + if (response !== undefined) queueMicrotask(() => child.stdout.emit("data", Buffer.from(`${JSON.stringify({ jsonrpc: "2.0", id: message.id, ...response as object })}\n`))); + done(); + }, final(done) { queueMicrotask(() => child.emit("close", 0)); done(); } }); + return child; +} +const verified = { status: "verified", version: "1.0.88", profileDigest: QUALIFIED_ACPX_PROFILES.copilot.commandDigest, models: [{ id: "gpt-5.6-luna", label: "GPT" }], promptSent: false }; +beforeEach(() => vi.clearAllMocks()); +describe("Copilot metadata boundary", () => { + it("sends metadata only, binds an explicit token, and removes its private home", async () => { + const methods: string[] = []; let environment: NodeJS.ProcessEnv = {}, cwd = ""; + const close = vi.fn(async () => {}); + const child = fakeChild(message => { + methods.push(message.method); + if (message.method === "initialize") return { result: { agentInfo: { version: "1.0.88" } } }; + if (message.method === "session/new") return { result: { sessionId: "session", models: { availableModels: [{ modelId: "gpt-5.6-luna", name: "GPT" }] } } }; + if (message.method === "session/set_config_option") return { result: { configOptions: [{ id: "model", currentValue: "gpt-5.6-luna" }] } }; + return { result: {} }; + }); + mocks.verify.mockResolvedValue({ commandDigest: verified.profileDigest, openCommand: async () => ({ close, spawn: (_args: unknown, options: any) => { environment = options.env; cwd = options.cwd; return child; } }) }); + expect(await probeCopilotMetadata("github_pat_private_test", "gpt-5.6-luna")).toEqual(verified); + expect(methods).toEqual(["initialize", "session/new", "session/set_model", "session/set_config_option"]); + expect(environment.COPILOT_GITHUB_TOKEN).toBe("github_pat_private_test"); + for (const key of ["GH_TOKEN", "GITHUB_TOKEN", "NODE_OPTIONS", "SSH_AUTH_SOCK"]) expect(environment).not.toHaveProperty(key); + expect(environment.HOME).toContain(cwd); expect(close).toHaveBeenCalledOnce(); + await expect(access(cwd)).rejects.toThrow(); + }); + it("rejects an unavailable model without sending a prompt or selecting another model", async () => { + const methods: string[] = []; + const child = fakeChild(message => { methods.push(message.method); return { result: message.method === "initialize" ? { agentInfo: { version: "1.0.88" } } : { sessionId: "session", models: { availableModels: [{ modelId: "other" }] } } }; }); + const close = vi.fn(async () => {}); + mocks.verify.mockResolvedValue({ commandDigest: verified.profileDigest, openCommand: async () => ({ close, spawn: () => child }) }); + expect(await probeCopilotMetadata("token", "missing")).toMatchObject({ status: "failed", code: "COPILOT_MODEL_UNAVAILABLE", promptSent: false }); + expect(methods).toEqual(["initialize", "session/new"]); expect(close).toHaveBeenCalledOnce(); + }); + it("cannot dispatch semantic or prompt methods", () => { + const child = fakeChild(() => undefined), rpc = createMetadataRpc(child); + expect(() => rpc.request("session/prompt", {})).toThrow("cannot send"); + expect(() => rpc.request("tools/call", {})).toThrow("cannot send"); + }); + it("rejects outstanding calls when the provider dies", async () => { + const child = fakeChild(() => undefined), rpc = createMetadataRpc(child); + const promise = rpc.request("initialize", {}); child.emit("close", 1); + await expect(promise).rejects.toThrow("provider exited"); + }); + it("accepts only current profile metadata and sanitized failures", () => { + expect(validateCopilotMetadata(verified)).toEqual(verified); + for (const mutation of [{ promptSent: true }, { profileDigest: "stale" }, { models: [] }, { models: [{ id: "bad id", label: "x" }] }, { models: [{ id: "safe", label: "github_pat_secret" }] }, { models: [...verified.models, ...verified.models] }]) { + expect(validateCopilotMetadata({ ...verified, ...mutation })).toMatchObject({ status: "failed", code: "COPILOT_REQUEST_FAILED" }); + } + const failure = validateCopilotMetadata({ status: "failed", code: "COPILOT_AUTH_REQUIRED", message: "github_pat_secret", promptSent: false }); + expect(failure).toMatchObject({ code: "COPILOT_AUTH_REQUIRED" }); expect(JSON.stringify(failure)).not.toContain("secret"); + expect(validateCopilotMetadata({ status: "failed", code: "untrusted", promptSent: false })).toMatchObject({ code: "COPILOT_REQUEST_FAILED" }); + }); +}); diff --git a/packages/paperclip-runner/src/drivers/copilot-metadata-probe.ts b/packages/paperclip-runner/src/drivers/copilot-metadata-probe.ts new file mode 100644 index 00000000000..40ec863653a --- /dev/null +++ b/packages/paperclip-runner/src/drivers/copilot-metadata-probe.ts @@ -0,0 +1,160 @@ +import { mkdtemp, mkdir, writeFile, rm } from "node:fs/promises"; +import { join } from "node:path"; +import { tmpdir } from "node:os"; +import type { ChildProcessWithoutNullStreams } from "node:child_process"; +import { verifyCopilotInstallation } from "./acpx/copilot-installation.js"; +import { QUALIFIED_ACPX_PROFILES, resolveQualifiedAcpxProfile } from "./acpx/qualified-profiles.js"; +import { classifyCopilotFailure, copilotConfiguration, copilotSandboxEnvironment } from "./acpx/copilot-profile.js"; +import { COPILOT_ACP_CLIENT_CAPABILITIES } from "./acpx/copilot-events.js"; + +type RecordValue = Record; +const record = (value: unknown): RecordValue => value !== null && typeof value === "object" && !Array.isArray(value) ? value as RecordValue : {}; +const METHODS = new Set(["initialize", "session/new", "session/set_model", "session/set_config_option", "session/close"]); +export type CopilotMetadataResult = + | { status: "verified"; version: "1.0.88"; profileDigest: string; models: Array<{ id: string; label: string }>; promptSent: false } + | { status: "failed"; code: string; message: string; promptSent: false }; + +/** A metadata-only client: no prompt, tool server, workspace, or ambient login. */ +export async function probeCopilotMetadata(token: string, model?: string): Promise { + if (model && ["auto", "default"].includes(model.trim().toLowerCase())) return { status: "failed", code: "COPILOT_MODEL_UNAVAILABLE", message: "Select an explicit Copilot model.", promptSent: false }; + if (!token.trim() || token.includes("\0")) return { status: "failed", code: "COPILOT_AUTH_REQUIRED", message: "Enter a valid Copilot personal access token.", promptSent: false }; + let installation; + try { installation = await verifyCopilotInstallation(resolveQualifiedAcpxProfile("copilot", model ?? "metadata-discovery")); } + catch { return { status: "failed", code: "COPILOT_INSTALLATION_INVALID", message: "The selected environment does not have the verified Copilot runtime installed.", promptSent: false }; } + let root: string | undefined; + let lease: Awaited> | undefined; + let child: ChildProcessWithoutNullStreams | undefined; + let closed: Promise | undefined; + let deadline: ReturnType | undefined; + let phase = "installation"; + try { + lease = await installation.openCommand(); + root = await mkdtemp(join(tmpdir(), "paperclip-copilot-metadata-")); + const directories = { homeDirectory: join(root, "home"), configDirectory: join(root, "config"), dataDirectory: join(root, "data"), cacheDirectory: join(root, "cache"), agentHomeDirectory: join(root, "copilot") }; + for (const directory of Object.values(directories)) await mkdir(directory, { mode: 0o700 }); + await writeFile(join(directories.agentHomeDirectory, "config.json"), JSON.stringify(copilotConfiguration()), { mode: 0o600 }); + child = lease.spawn([], { cwd: root, env: { PATH: "/usr/bin:/bin", ...copilotSandboxEnvironment(directories), COPILOT_GITHUB_TOKEN: token }, stdio: "pipe" }) as ChildProcessWithoutNullStreams; + closed = new Promise(resolve => child!.once("close", () => resolve())); + const rpc = createMetadataRpc(child); + const work = async (): Promise => { + phase = "initialize"; + const initialized = record(await rpc.request("initialize", { protocolVersion: 1, clientInfo: { name: "paperclip-copilot-metadata", version: "1" }, clientCapabilities: COPILOT_ACP_CLIENT_CAPABILITIES })); + if (record(initialized.agentInfo).version !== "1.0.88") throw Object.assign(new Error("Verified Copilot installation changed"), { code: "COPILOT_INSTALLATION_INVALID" }); + phase = "session-new"; + const opened = record(await rpc.request("session/new", { cwd: root, mcpServers: [] })); + const advertised = record(opened.models).availableModels; + const models = (Array.isArray(advertised) ? advertised : []).slice(0, 200).flatMap(value => { + const entry = record(value), id = entry.modelId; + return typeof id === "string" && !["auto", "default"].includes(id.toLowerCase()) && /^[a-zA-Z0-9][a-zA-Z0-9._:/-]{0,199}$/.test(id) + ? [{ id, label: typeof entry.name === "string" && !/[\x00-\x1f\x7f]|github_pat_|gh[pousr]_/.test(entry.name) ? entry.name.slice(0, 200) : id }] : []; + }); + if (!models.length) throw new Error("Copilot model discovery unavailable"); + if (model) { + if (!models.some(value => value.id === model)) throw Object.assign(new Error("Selected Copilot model unavailable"), { code: "COPILOT_MODEL_UNAVAILABLE" }); + phase = "model-selection"; + await rpc.request("session/set_model", { sessionId: opened.sessionId, modelId: model }); + phase = "model-confirmation"; + const configured = record(await rpc.request("session/set_config_option", { sessionId: opened.sessionId, configId: "model", value: model })); + if (!Array.isArray(configured.configOptions) || !configured.configOptions.some(option => record(option).id === "model" && record(option).currentValue === model)) { + throw Object.assign(new Error("Selected Copilot model unavailable"), { code: "COPILOT_MODEL_UNAVAILABLE" }); + } + } + // EOF is the authoritative stdio shutdown; session/close is optional. + return { status: "verified", version: "1.0.88", profileDigest: installation.commandDigest, models, promptSent: false }; + }; + return await Promise.race([work(), new Promise((_resolve, reject) => { + deadline = setTimeout(() => reject(new Error("Copilot metadata probe timed out")), 25_000); + })]); + } catch (error) { + const code = record(error).code; + if (code === "COPILOT_INSTALLATION_INVALID") return { status: "failed", code, message: "The selected environment has an incompatible Copilot installation.", promptSent: false }; + if (code === "COPILOT_MODEL_UNAVAILABLE") return { status: "failed", code, message: "The selected Copilot model is unavailable for this account.", promptSent: false }; + const failure = classifyCopilotFailure(error); + const cause = error instanceof Error && error.message === "Copilot metadata probe timed out" ? "deadline" + : error instanceof Error && error.message === "Copilot provider exited during metadata discovery" ? "provider-exit" : "request-rejected"; + // Only closed diagnostic categories; never log provider errors, wire data, + // credentials, model catalogs, session IDs or private workspace paths. + console.warn("Copilot metadata verification failed", JSON.stringify({ phase, code: failure.code, cause })); + return { status: "failed", ...failure, promptSent: false }; + } finally { + if (deadline) clearTimeout(deadline); + if (child && closed) { + child.stdin.end(); + const term = setTimeout(() => child?.kill("SIGTERM"), 500); + const kill = setTimeout(() => child?.kill("SIGKILL"), 2_000); + await closed; + clearTimeout(term); clearTimeout(kill); + } + try { await lease?.close(); } finally { if (root) await rm(root, { recursive: true, force: true }); } + } +} + +export function createMetadataRpc(child: ChildProcessWithoutNullStreams) { + const pending = new Map(); + let nextId = 0, bytes = 0, buffer = "", failure: Error | undefined; + const fail = (error: Error) => { failure ??= error; for (const call of pending.values()) call.reject(failure); pending.clear(); }; + child.once("close", () => fail(new Error("Copilot provider exited during metadata discovery"))); + child.once("error", () => fail(new Error("Copilot installation could not start"))); + child.stdin.on("error", () => fail(new Error("Copilot metadata transport unavailable"))); + child.stderr.on("data", () => {}); + child.stdout.on("data", (chunk: Buffer) => { + bytes += chunk.length; + if (bytes > 2 * 1024 * 1024) { fail(new Error("Copilot metadata exceeded its bound")); child.kill("SIGTERM"); return; } + buffer += chunk.toString(); + while (buffer.includes("\n")) { + const end = buffer.indexOf("\n"), line = buffer.slice(0, end); buffer = buffer.slice(end + 1); + if (!line.trim()) continue; + let message: RecordValue; + try { message = record(JSON.parse(line)); } catch { fail(new Error("Invalid Copilot metadata response")); return; } + if (message.method) { + if (message.id !== undefined) child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id: message.id, error: { code: -32601, message: "Metadata discovery does not support inbound methods" } })}\n`); + continue; + } + const call = pending.get(message.id as number); + if (!call) continue; + pending.delete(message.id as number); + if (message.error) { + const details = record(message.error); + call.reject(new Error(typeof details.message === "string" ? details.message.slice(0, 8192) : "Copilot metadata request failed")); + } else call.resolve(message.result); + } + }); + return { request(method: string, params: RecordValue): Promise { + if (!METHODS.has(method)) throw new Error("Metadata discovery cannot send this method"); + if (failure) return Promise.reject(failure); + const id = nextId++; + return new Promise((resolve, reject) => { + pending.set(id, { resolve, reject }); + child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id, method, params })}\n`); + }); + } }; +} + +const FAILURE_MESSAGES = { + COPILOT_AUTH_REQUIRED: "Enter a valid Copilot personal access token.", + COPILOT_ENTITLEMENT_DENIED: "Copilot access is denied by the account entitlement or organization policy.", + COPILOT_MODEL_UNAVAILABLE: "The selected Copilot model is unavailable for this account.", + COPILOT_INSTALLATION_INVALID: "Install the verified Copilot runtime in this environment.", + COPILOT_REQUEST_FAILED: "Copilot metadata verification failed.", +} as const; +/** Validate remote metadata and discard all provider-authored error text. */ +export function validateCopilotMetadata(value: unknown): CopilotMetadataResult { + const result = record(value); + const invalid = (): CopilotMetadataResult => ({ status: "failed", code: "COPILOT_REQUEST_FAILED", message: FAILURE_MESSAGES.COPILOT_REQUEST_FAILED, promptSent: false }); + if (result.promptSent !== false) return invalid(); + if (result.status === "failed") { + const code = typeof result.code === "string" && Object.hasOwn(FAILURE_MESSAGES, result.code) ? result.code as keyof typeof FAILURE_MESSAGES : "COPILOT_REQUEST_FAILED"; + return { status: "failed", code, message: FAILURE_MESSAGES[code], promptSent: false }; + } + if (result.status !== "verified" || result.version !== "1.0.88" || result.profileDigest !== QUALIFIED_ACPX_PROFILES.copilot.commandDigest + || !Array.isArray(result.models) || result.models.length === 0 || result.models.length > 200) return invalid(); + const models: Array<{ id: string; label: string }> = []; + const ids = new Set(); + for (const value of result.models) { + const entry = record(value); + if (typeof entry.id !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,199}$/.test(entry.id) || ids.has(entry.id) + || typeof entry.label !== "string" || entry.label.length > 200 || /[\x00-\x1f\x7f]|github_pat_|gh[pousr]_/.test(entry.label)) return invalid(); + ids.add(entry.id); models.push({ id: entry.id, label: entry.label }); + } + return { status: "verified", version: "1.0.88", profileDigest: result.profileDigest, models, promptSent: false }; +} diff --git a/packages/paperclip-runner/src/drivers/runner-tool-bridge.test.ts b/packages/paperclip-runner/src/drivers/runner-tool-bridge.test.ts index 5bf87169d24..b61d2c32f3a 100644 --- a/packages/paperclip-runner/src/drivers/runner-tool-bridge.test.ts +++ b/packages/paperclip-runner/src/drivers/runner-tool-bridge.test.ts @@ -1,3 +1,5 @@ +import { readNativeSemanticReceipt, semanticInputSha256, type SemanticToolReceipt, type SemanticToolResult } from "./semantic-tool-receipt.js"; +import { validatePrpStructuredRunResult } from "../protocol/replay-contract.js"; import { connect } from "node:net"; import { afterEach, describe, expect, it, vi } from "vitest"; @@ -192,14 +194,12 @@ describe("runner semantic MCP bridge", () => { expect(handler).toHaveBeenCalledTimes(2); }); - it("times out calls and honors MCP cancellation", async () => { - const starts: string[] = []; + it("times out calls", async () => { const bridge = await startRunnerToolBridge({ tools: [tool("documents.read")], timeoutMs: 20, - handler: ({ callId, signal }) => + handler: ({ signal }) => new Promise((_resolve, reject) => { - starts.push(callId); signal.addEventListener( "abort", () => reject(new Error("handler aborted")), @@ -223,15 +223,36 @@ describe("runner semantic MCP bridge", () => { content: [{ text: "Paperclip tool call timed out" }], }, }); + }); + + it("honors MCP cancellation after the handler starts", async () => { + let markStarted!: () => void; + const started = new Promise((resolve) => { + markStarted = resolve; + }); + const aborted = vi.fn(); + const bridge = await startRunnerToolBridge({ + tools: [tool("documents.read")], + timeoutMs: 60_000, + handler: ({ signal }) => new Promise((_resolve, reject) => { + signal.addEventListener("abort", () => { + aborted(); + reject(new Error("handler aborted")); + }, { once: true }); + markStarted(); + }), + }); + bridges.push(bridge); const pending = rpc(bridge, { id: "cancel-me", method: "tools/call", params: { name: "documents.read", arguments: {} }, }); - await vi.waitFor(() => expect(starts).toContain("cancel-me"), { - interval: 1, - timeout: 15, - }); + // Observe request arrival without racing the separate timeout behavior. + // Retain the rejection for the assertion while avoiding an unhandled fetch + // rejection if a failed test closes the bridge before the request arrives. + void pending.catch(() => undefined); + await started; expect( ( await rpc(bridge, { @@ -246,6 +267,7 @@ describe("runner semantic MCP bridge", () => { content: [{ text: "Paperclip tool call cancelled" }], }, }); + expect(aborted).toHaveBeenCalledOnce(); }); it("preserves successful mutation identity when the result is oversized", async () => { @@ -451,3 +473,109 @@ describe("runner semantic MCP bridge", () => { function tool(name: string): Readonly> { return { name, inputSchema: { type: "object" } }; } + +describe("Copilot semantic receipt opt-in", () => { + const rawFinish = { reportedWorkDisposition: "done", summary: "The task is complete.", evidence: [], verification: [], + completionClaim: { contractRevision: "1", objectiveSatisfied: true, criteria: [], remainingWork: [] } }; + it.each(["committed", "not-forwarded", "invalid", "duplicate-capture", "conflicting-capture", "duplicate-commit"])( + "captures only the invocation's exact forwarded normalized input: %s", async mode => { + const receipts: SemanticToolReceipt[] = []; + let capturedInput: unknown; + const bridge = await startRunnerToolBridge({ captureSemanticReceipt: () => receipt => receipts.push(receipt), handler: async call => { + const validation = validatePrpStructuredRunResult(call.arguments); + if (!validation.ok) throw new Error("Invalid fixture input"); + capturedInput = structuredClone(validation.result); + const invalid: Record = {}; invalid.self = invalid; + const commit = call.captureNormalizedInput!(mode === "invalid" ? invalid : validation.result); + if (mode === "duplicate-capture") call.captureNormalizedInput!(validation.result)(); + if (mode === "conflicting-capture") call.captureNormalizedInput!({ ...validation.result, summary: "foreign" })(); + if (mode !== "not-forwarded") commit(); + if (mode === "duplicate-commit") commit(); + // The digest is a snapshot of forwarded input, not a later mutable value. + validation.result.summary = "later mutation"; + return { accepted: true }; + } }); + bridges.push(bridge); + const request = { id: 3, method: "tools/call", params: { name: "paperclip_finish", arguments: rawFinish } }; + const body = await (await rpc(bridge, request)).json(); + expect(receipts).toHaveLength(1); + expect(readNativeSemanticReceipt({ contents: body.result.content })).toEqual(receipts[0]); + expect(receipts[0]).toMatchObject({ schema: "paperclip.semantic_tool_receipt.v2", inputSha256: semanticInputSha256(rawFinish), + normalizedInputSha256: mode === "committed" ? semanticInputSha256(capturedInput) : null }); + expect(semanticInputSha256(rawFinish)).not.toBe(semanticInputSha256(capturedInput)); + expect(await (await rpc(bridge, request)).json()).toEqual(body); + expect(receipts).toHaveLength(1); + }, + ); + it("keeps concurrent call captures separate and ignores captures after settlement", async () => { + const pending = new Map; settle: () => void }>(); + const receipts: SemanticToolReceipt[] = []; + const bridge = await startRunnerToolBridge({ captureSemanticReceipt: () => receipt => receipts.push(receipt), handler: call => new Promise(resolve => { + pending.set(call.callId, { capture: call.captureNormalizedInput!, settle: () => resolve({ accepted: true }) }); + }) }); + bridges.push(bridge); + const first = rpc(bridge, { id: "first", method: "tools/call", params: { name: "paperclip_finish", arguments: rawFinish } }); + const secondInput = { ...rawFinish, summary: "Second call" }; + const second = rpc(bridge, { id: "second", method: "tools/call", params: { name: "paperclip_finish", arguments: secondInput } }); + await vi.waitFor(() => expect(pending.size).toBe(2)); + const normalizedFirst = validatePrpStructuredRunResult(rawFinish); const normalizedSecond = validatePrpStructuredRunResult(secondInput); + if (!normalizedFirst.ok || !normalizedSecond.ok) throw new Error("Invalid fixture"); + pending.get("second")!.capture(normalizedSecond.result)(); pending.get("second")!.settle(); + const secondReceipt = readNativeSemanticReceipt({ contents: (await (await second).json()).result.content }); + expect(secondReceipt).toMatchObject({ inputSha256: semanticInputSha256(secondInput), normalizedInputSha256: semanticInputSha256(normalizedSecond.result) }); + pending.get("second")!.capture(normalizedFirst.result)(); + pending.get("first")!.capture(normalizedFirst.result)(); pending.get("first")!.settle(); + const firstReceipt = readNativeSemanticReceipt({ contents: (await (await first).json()).result.content }); + expect(firstReceipt).toMatchObject({ inputSha256: semanticInputSha256(rawFinish), normalizedInputSha256: semanticInputSha256(normalizedFirst.result) }); + expect(receipts).toEqual([secondReceipt, firstReceipt]); + }); + it("does not accept model metadata as normalized authority or widen non-Copilot calls", async () => { + const modelMetadata = { normalizedInputSha256: "a".repeat(64), captureNormalizedInput: "forged" }; + const withEvidence = await startRunnerToolBridge({ tools: [tool("documents.read")], captureSemanticReceipt: () => () => {}, handler: async call => { + expect(call.captureNormalizedInput).toBeUndefined(); return modelMetadata; + } }); bridges.push(withEvidence); + const body = await (await rpc(withEvidence, { id: 1, method: "tools/call", params: { name: "documents.read", arguments: modelMetadata } })).json(); + expect(readNativeSemanticReceipt({ contents: body.result.content })).toHaveProperty("normalizedInputSha256", null); + const plain = await startRunnerToolBridge({ handler: async call => { expect(call.captureNormalizedInput).toBeUndefined(); return { accepted: true }; } }); bridges.push(plain); + const plainBody = await (await rpc(plain, { id: 2, method: "tools/call", params: { name: "paperclip_finish", arguments: rawFinish } })).json(); + expect(readNativeSemanticReceipt({ contents: plainBody.result.content })).toBeNull(); + }); + it.each(["small", "chunked", "tagged", "error"])("preserves %s result encoding and captures scope before dispatch", async encoding => { + const receipts: SemanticToolReceipt[] = []; + let resolve!: (value: unknown) => void; + let reject!: (error: Error) => void; + const pending = new Promise((yes, no) => { resolve = yes; reject = no; }); + const capture = vi.fn(() => (receipt: SemanticToolReceipt) => receipts.push(receipt)); + const handler = vi.fn(() => pending); + const bridge = await startRunnerToolBridge({ tools: [tool("documents.read")], handler, captureSemanticReceipt: capture }); + bridges.push(bridge); + const request = { id: 3, method: "tools/call", params: { name: "documents.read", arguments: {} } }; + const response = rpc(bridge, request); + await vi.waitFor(() => expect(handler).toHaveBeenCalledTimes(1)); + expect(capture).toHaveBeenCalledTimes(1); + if (encoding === "error") reject(new Error("bounded failure")); + else resolve(encoding === "chunked" ? "x".repeat(70000) : encoding === "tagged" ? { bigint: 1n } : { accepted: false }); + const body = await (await response).json() as { result: SemanticToolResult }; + expect(receipts).toHaveLength(1); + expect(readNativeSemanticReceipt({ contents: body.result.content })).toEqual(receipts[0]); + expect(body.result.isError === true).toBe(encoding === "error"); + if (encoding === "small") expect(JSON.parse(body.result.content[0].text)).toEqual({ accepted: false }); + if (encoding === "error") expect(body.result.content[0].text).toBe("bounded failure"); + if (encoding === "chunked") expect(body.result.content.length).toBeGreaterThan(2); + const replay = await (await rpc(bridge, request)).json(); + expect(replay).toEqual(body); + expect(receipts).toHaveLength(1); + expect(handler).toHaveBeenCalledTimes(1); + }); + it("does not receipt unauthorized/unadmitted calls or let diagnostic errors change results", async () => { + const capture = vi.fn(() => () => { throw new Error("diagnostic only"); }); + const bridge = await startRunnerToolBridge({ tools: [tool("documents.read")], handler: async () => ({ ok: true }), captureSemanticReceipt: capture }); + bridges.push(bridge); + await rpc(bridge, { id: 1, method: "tools/call", params: { name: "documents.read" } }, "wrong"); + await rpc(bridge, { id: 2, method: "tools/call", params: { name: "unknown" } }); + expect(capture).not.toHaveBeenCalled(); + const body = await (await rpc(bridge, { id: 3, method: "tools/call", params: { name: "documents.read" } })).json() as { result: SemanticToolResult }; + expect(JSON.parse(body.result.content[0].text)).toEqual({ ok: true }); + expect(readNativeSemanticReceipt({ contents: body.result.content })).not.toBeNull(); + }); +}); diff --git a/packages/paperclip-runner/src/drivers/runner-tool-bridge.ts b/packages/paperclip-runner/src/drivers/runner-tool-bridge.ts index c8207c71833..06c59a8a8db 100644 --- a/packages/paperclip-runner/src/drivers/runner-tool-bridge.ts +++ b/packages/paperclip-runner/src/drivers/runner-tool-bridge.ts @@ -1,4 +1,5 @@ import { createHash, randomBytes, timingSafeEqual } from "node:crypto"; +import { appendSemanticToolReceipt, semanticCanonicalJson as canonicalJson, semanticInputSha256, type SemanticToolReceipt } from "./semantic-tool-receipt.js"; import { createServer, type IncomingMessage, @@ -28,6 +29,9 @@ export interface RunnerToolCall { callId: string; arguments: unknown; signal: AbortSignal; + /** Internal, invocation-owned evidence. Snapshot before forwarding; commit only + * after that exact normalized input is forwarded. Never supplied by the model. */ + captureNormalizedInput?: (input: unknown) => (() => void); } export interface RunnerToolBridgeOptions { @@ -35,6 +39,8 @@ export interface RunnerToolBridgeOptions { /** Runner-owned operations that are callable but never model-visible. */ privateTools?: readonly Readonly>[]; handler(call: RunnerToolCall): Promise; + /** Copilot-only opt-in; capture the active invocation scope before dispatch. */ + captureSemanticReceipt?: () => ((receipt: SemanticToolReceipt) => void) | undefined; timeoutMs?: number; privateToolTimeoutMs?: number; maxBodyBytes?: number; @@ -60,6 +66,7 @@ interface RunnerToolTextContent { } interface RunnerToolCallResult { + isError?: boolean; content: RunnerToolTextContent[]; } @@ -123,6 +130,7 @@ export async function startRunnerToolBridge( calls, controllers, handler: options.handler, + captureSemanticReceipt: options.captureSemanticReceipt, timeoutMs: positiveBoundedInteger( options.timeoutMs, DEFAULT_TIMEOUT_MS, @@ -192,6 +200,7 @@ async function handleRequest( calls: Map; controllers: Map; handler: RunnerToolBridgeOptions["handler"]; + captureSemanticReceipt: RunnerToolBridgeOptions["captureSemanticReceipt"]; timeoutMs: number; privateToolTimeoutMs: number; privateToolNames: ReadonlySet; @@ -321,6 +330,38 @@ async function handleRequest( } } const controller = existing === undefined ? new AbortController() : undefined; + let observeReceipt: ((receipt: SemanticToolReceipt) => void) | undefined; + if (!existing) { try { observeReceipt = context.captureSemanticReceipt?.(); } catch { /* Optional evidence cannot prevent dispatch. */ } } + let receiptSealed = false; + let normalizationCaptured = false; + let normalizationInvalid = false; + let normalizedInputSha256: string | null = null; + const captureNormalizedInput = (input: unknown): (() => void) => { + if (receiptSealed || controller?.signal.aborted) return () => {}; + if (normalizationCaptured) { normalizationInvalid = true; return () => {}; } + normalizationCaptured = true; + let digest: string; + try { + if (!isRecord(input) || Buffer.byteLength(JSON.stringify(input)) > context.maxBodyBytes) throw new Error("Invalid normalized input"); + digest = semanticInputSha256(input); + } catch { normalizationInvalid = true; return () => {}; } + let committed = false; + return () => { + if (receiptSealed || controller?.signal.aborted) return; + if (committed) { normalizationInvalid = true; return; } + committed = true; + if (!normalizationInvalid) normalizedInputSha256 = digest; + }; + }; + const withReceipt = (result: RunnerToolCallResult): RunnerToolCallResult => { + receiptSealed = true; + if (!context.captureSemanticReceipt) return result; + try { + const bound = appendSemanticToolReceipt({ tool, callId, arguments: args, normalizedInputSha256: normalizationInvalid ? null : normalizedInputSha256 }, result); + try { observeReceipt?.(bound.receipt); } catch { /* Evidence cannot change the tool outcome. */ } + return bound.result; + } catch { return result; } + }; const execution: Promise = existing?.promise ?? withCancellationAndTimeout( @@ -331,6 +372,8 @@ async function handleRequest( callId, arguments: structuredClone(args), signal: controller!.signal, + ...(context.captureSemanticReceipt && (tool === PRP_COMPLETION_TOOL_NAME || tool === PRP_BLOCK_TOOL_NAME) + ? { captureNormalizedInput } : {}), }), ) .then((result) => successfulToolResult(tool, callId, result)), @@ -338,7 +381,10 @@ async function handleRequest( context.privateToolNames.has(tool) ? context.privateToolTimeoutMs : context.timeoutMs, - ); + ).then(withReceipt, error => { + if (!context.captureSemanticReceipt) throw error; + return withReceipt({ isError: true, content: [{ type: "text", text: safeError(error) }] }); + }); if (!existing) { context.calls.set(callKey, { fingerprint, promise: execution }); context.controllers.set(callKey, controller!); @@ -813,16 +859,6 @@ function taggedObjectType(value: object): string { : "Object"; } -function canonicalJson(value: unknown): string { - if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`; - if (isRecord(value)) { - return `{${Object.keys(value) - .sort() - .map((key) => `${JSON.stringify(key)}:${canonicalJson(value[key])}`) - .join(",")}}`; - } - return JSON.stringify(value) ?? "undefined"; -} function isJsonContentType(value: string | undefined): boolean { return value?.split(";", 1)[0]?.trim().toLowerCase() === "application/json"; diff --git a/packages/paperclip-runner/src/drivers/semantic-tool-receipt.test.ts b/packages/paperclip-runner/src/drivers/semantic-tool-receipt.test.ts new file mode 100644 index 00000000000..5392c5d8299 --- /dev/null +++ b/packages/paperclip-runner/src/drivers/semantic-tool-receipt.test.ts @@ -0,0 +1,62 @@ +import { describe, expect, it } from "vitest"; +import { appendSemanticToolReceipt, parseSemanticToolReceipt, readNativeSemanticReceipt, semanticInputSha256 } from "./semantic-tool-receipt.js"; +const call = { tool: "paperclip_finish", callId: "3", arguments: { revision: "current", summary: "private" } }; +const original = { content: [{ type: "text" as const, text: '{"accepted":false}' }] }; +describe("bounded semantic receipt carrier", () => { + it("preserves existing content and transport-vs-semantic acceptance", () => { + const { result, receipt } = appendSemanticToolReceipt(call, original); + expect(result.content.slice(0, -1)).toEqual(original.content); + expect(receipt.outcome).toBe("returned"); + expect(JSON.stringify(receipt)).not.toContain("private"); + expect(readNativeSemanticReceipt({ contents: result.content })).toEqual(receipt); + expect(semanticInputSha256({ a: 1, b: 2 })).toBe(semanticInputSha256({ b: 2, a: 1 })); + }); + it("preserves error content without converting error into returned acceptance", () => { + const { result, receipt } = appendSemanticToolReceipt(call, { ...original, isError: true }); + expect(result.isError).toBe(true); + expect(receipt.outcome).toBe("error"); + expect(readNativeSemanticReceipt({ contents: result.content })).toEqual(receipt); + }); + it.each(["unknown", "malformed", "oversized", "modified", "duplicate", "missing", "type", "reordered"])("rejects %s native carrier", kind => { + const { result } = appendSemanticToolReceipt(call, original); + const blocks = structuredClone(result.content); + const receipt = JSON.parse(blocks.at(-1)!.text); + if (kind === "unknown") blocks.at(-1)!.text = JSON.stringify({ ...receipt, extra: "private" }); + if (kind === "malformed") blocks.at(-1)!.text = "{"; + if (kind === "oversized") blocks.at(-1)!.text = "x".repeat(2049); + if (kind === "modified") blocks[0]!.text = "different"; + if (kind === "duplicate") blocks.unshift(blocks.at(-1)!); + if (kind === "missing") blocks.pop(); + if (kind === "type") Object.assign(blocks[0]!, { type: "image" }); + if (kind === "reordered") blocks.reverse(); + expect(readNativeSemanticReceipt({ contents: blocks })).toBeNull(); + }); + it("bounds the whole repeated native output while still serializing large-result receipts", () => { + const bound = appendSemanticToolReceipt(call, { content: [{ type: "text", text: "x".repeat(90_000) }] }); + expect(readNativeSemanticReceipt({ contents: bound.result.content })).toEqual(bound.receipt); + expect(readNativeSemanticReceipt({ contents: bound.result.content, content: "x".repeat(90_000), detailedContent: "x".repeat(90_000) })).toBeNull(); + expect(bound.result.content.at(-1)!.text.length).toBeLessThan(2048); + }); + it("rejects unknown fields and unsafe identities without truncation", () => { + const { receipt } = appendSemanticToolReceipt(call, original); + expect(parseSemanticToolReceipt({ ...receipt, operationId: "bad\nname" })).toBeNull(); + expect(parseSemanticToolReceipt({ ...receipt, inputSha256: "a".repeat(65) })).toBeNull(); + expect(parseSemanticToolReceipt({ ...receipt, outcome: "accepted" })).toBeNull(); + }); + it("keeps raw and forwarded input identities separate and versions historical receipts honestly", () => { + const normalizedInputSha256 = semanticInputSha256({ ...call.arguments, schema: "paperclip.run_result.v1" }); + const { receipt, result } = appendSemanticToolReceipt({ ...call, normalizedInputSha256 }, original); + expect(receipt).toMatchObject({ schema: "paperclip.semantic_tool_receipt.v2", normalizedInputSha256, + inputSha256: semanticInputSha256(call.arguments) }); + expect(receipt.inputSha256).not.toBe(normalizedInputSha256); + expect(readNativeSemanticReceipt({ contents: result.content })).toEqual(receipt); + expect(appendSemanticToolReceipt(call, original).receipt).toHaveProperty("normalizedInputSha256", null); + const { normalizedInputSha256: _, ...legacyFields } = receipt as typeof receipt & { normalizedInputSha256: unknown }; + const legacy = { ...legacyFields, schema: "paperclip.semantic_tool_receipt.v1" }; + expect(parseSemanticToolReceipt(legacy)).toEqual(legacy); + expect(parseSemanticToolReceipt({ ...legacy, normalizedInputSha256 })).toBeNull(); + expect(parseSemanticToolReceipt({ ...receipt, normalizedInputSha256: "null" })).toBeNull(); + expect(parseSemanticToolReceipt({ ...receipt, normalizedInputSha256: "a".repeat(65) })).toBeNull(); + expect(parseSemanticToolReceipt({ ...legacyFields, schema: "paperclip.semantic_tool_receipt.v2" })).toBeNull(); + }); +}); diff --git a/packages/paperclip-runner/src/drivers/semantic-tool-receipt.ts b/packages/paperclip-runner/src/drivers/semantic-tool-receipt.ts new file mode 100644 index 00000000000..0d690261564 --- /dev/null +++ b/packages/paperclip-runner/src/drivers/semantic-tool-receipt.ts @@ -0,0 +1,83 @@ +import { createHash } from "node:crypto"; + +export const SEMANTIC_RECEIPT_SCHEMA = "paperclip.semantic_tool_receipt.v2"; +const LEGACY_SEMANTIC_RECEIPT_SCHEMA = "paperclip.semantic_tool_receipt.v1"; +export const MAX_SEMANTIC_RECEIPT_BYTES = 2048; +const MAX_NATIVE_BYTES = 256 * 1024; +interface SemanticToolReceiptFields { + operationId: string; + callIdentitySha256: string; + inputSha256: string; + resultSha256: string; + /** Transport outcome only: a returned value may explicitly reject a request. */ + outcome: "returned" | "error"; +} +export type SemanticToolReceipt = SemanticToolReceiptFields & ( + | { schema: typeof LEGACY_SEMANTIC_RECEIPT_SCHEMA } + | { schema: typeof SEMANTIC_RECEIPT_SCHEMA; normalizedInputSha256: string | null } +); +export interface SemanticToolResult { + content: Array<{ type: "text"; text: string }>; + isError?: boolean; +} +const hash = (value: string) => createHash("sha256").update(value).digest("hex"); +const object = (value: unknown): value is Record => value !== null && typeof value === "object" && !Array.isArray(value); +/** Same canonical JSON used by the bridge's admitted-call fingerprint. */ +export function semanticCanonicalJson(value: unknown): string { + if (Array.isArray(value)) return `[${value.map(semanticCanonicalJson).join(",")}]`; + if (object(value)) return `{${Object.keys(value).sort().map(key => `${JSON.stringify(key)}:${semanticCanonicalJson(value[key])}`).join(",")}}`; + return JSON.stringify(value) ?? "undefined"; +} +export const semanticInputSha256 = (value: unknown): string => hash(semanticCanonicalJson(value)); +export function parseSemanticToolReceipt(value: unknown): SemanticToolReceipt | null { + if (!object(value)) return null; + const legacy = value.schema === LEGACY_SEMANTIC_RECEIPT_SCHEMA; + const keys = legacy ? "callIdentitySha256,inputSha256,operationId,outcome,resultSha256,schema" + : "callIdentitySha256,inputSha256,normalizedInputSha256,operationId,outcome,resultSha256,schema"; + if (Object.keys(value).sort().join(",") !== keys + || (!legacy && value.schema !== SEMANTIC_RECEIPT_SCHEMA) + || typeof value.operationId !== "string" || !/^[A-Za-z0-9_.:-]{1,256}$/.test(value.operationId) + || ![value.callIdentitySha256, value.inputSha256, value.resultSha256].every(v => typeof v === "string" && /^[a-f0-9]{64}$/.test(v)) + || (!legacy && value.normalizedInputSha256 !== null && (typeof value.normalizedInputSha256 !== "string" || !/^[a-f0-9]{64}$/.test(value.normalizedInputSha256))) + || (value.outcome !== "returned" && value.outcome !== "error") + || Buffer.byteLength(JSON.stringify(value)) > MAX_SEMANTIC_RECEIPT_BYTES) return null; + const fields: SemanticToolReceiptFields = { operationId: value.operationId, + callIdentitySha256: value.callIdentitySha256 as string, inputSha256: value.inputSha256 as string, + resultSha256: value.resultSha256 as string, outcome: value.outcome }; + return legacy ? { schema: LEGACY_SEMANTIC_RECEIPT_SCHEMA, ...fields } + : { schema: SEMANTIC_RECEIPT_SCHEMA, ...fields, normalizedInputSha256: value.normalizedInputSha256 as string | null }; +} +function resultDigest(result: SemanticToolResult): string { + return semanticInputSha256({ content: result.content, isError: result.isError === true }); +} +/** Append, never rewrite, the original admitted result encoding and content. */ +export function appendSemanticToolReceipt(call: { tool: string; callId: string; arguments: unknown; normalizedInputSha256?: string | null }, result: SemanticToolResult) { + const receipt = parseSemanticToolReceipt({ schema: SEMANTIC_RECEIPT_SCHEMA, operationId: call.tool, + callIdentitySha256: hash(call.callId), inputSha256: semanticInputSha256(call.arguments), + normalizedInputSha256: call.normalizedInputSha256 ?? null, + resultSha256: resultDigest(result), outcome: result.isError ? "error" : "returned" }); + if (!receipt) throw new Error("Invalid semantic receipt identity"); + return { receipt, result: { ...result, content: [...result.content, { type: "text" as const, text: JSON.stringify(receipt) }] } }; +} +/** + * A native echo is only a candidate. Authority comes from the invocation callback. + * The 256 KiB bound applies to the WHOLE native rawOutput, including repeated + * content/detailedContent. Larger results still receive bridge receipts, but + * intentionally provide no native correlation evidence; never truncate to match. + */ +export function readNativeSemanticReceipt(raw: unknown): SemanticToolReceipt | null { + try { + if (!object(raw) || Buffer.byteLength(JSON.stringify(raw)) > MAX_NATIVE_BYTES || !Array.isArray(raw.contents) + || raw.contents.length < 2 || raw.contents.length > 128) return null; + const blocks = raw.contents; + if (!blocks.every(b => object(b) && Object.keys(b).sort().join(",") === "text,type" && b.type === "text" && typeof b.text === "string")) return null; + const last = blocks.at(-1) as { text: string }; + if (Buffer.byteLength(last.text) > MAX_SEMANTIC_RECEIPT_BYTES) return null; + const receipt = parseSemanticToolReceipt(JSON.parse(last.text)); + if (!receipt) return null; + const original = blocks.slice(0, -1) as SemanticToolResult["content"]; + if (original.some(b => { try { return parseSemanticToolReceipt(JSON.parse(b.text)) !== null; } catch { return false; } })) return null; + return resultDigest({ content: original, isError: receipt.outcome === "error" }) === receipt.resultSha256 ? receipt : null; + } catch { return null; } +} +export const sameSemanticReceipt = (a: SemanticToolReceipt, b: SemanticToolReceipt): boolean => semanticCanonicalJson(a) === semanticCanonicalJson(b); diff --git a/packages/paperclip-runner/src/live/index.ts b/packages/paperclip-runner/src/live/index.ts index 15737c6481b..4653a8f8332 100644 --- a/packages/paperclip-runner/src/live/index.ts +++ b/packages/paperclip-runner/src/live/index.ts @@ -6,6 +6,9 @@ export * from "./runnerd-codex-transport.js"; export * from "./turn-stream.js"; export { probeAcpxClaudeInstallation, probeAcpxGrokInstallation } from "../drivers/acpx/installation-integrity.js"; +export { probeCopilotMetadata, type CopilotMetadataResult } from "../drivers/copilot-metadata-probe.js"; + +export { validateCopilotMetadata } from "../drivers/copilot-metadata-probe.js"; export { probeAcpxCursorInstallation } from "../drivers/acpx/profile-installation.js"; diff --git a/packages/paperclip-runner/src/live/runnerd-acpx-permission-ordering.test.ts b/packages/paperclip-runner/src/live/runnerd-acpx-permission-ordering.test.ts index 3da30eae8f7..3e0c5314b78 100644 --- a/packages/paperclip-runner/src/live/runnerd-acpx-permission-ordering.test.ts +++ b/packages/paperclip-runner/src/live/runnerd-acpx-permission-ordering.test.ts @@ -158,6 +158,10 @@ it("does not dispatch an expired durable request when its consumer resumes", asy fixture.emitPermission(); peer.current!.emit("runtime_request.expired", { requestId: "permission-7" }); fixture.emitMarker(); + expect((await fixture.iterator.next()).value).toMatchObject({ + method: "paperclip/runtimeRequestExpired", + params: { payload: { requestId: "permission-7" } }, + }); expect((await fixture.iterator.next()).value?.method).toBe("item/agentMessage/delta"); expect(handler).not.toHaveBeenCalled(); } finally { await fixture.close(); } diff --git a/packages/paperclip-runner/src/live/runnerd-codex-transport.test.ts b/packages/paperclip-runner/src/live/runnerd-codex-transport.test.ts index 612991674ac..ff1e398003f 100644 --- a/packages/paperclip-runner/src/live/runnerd-codex-transport.test.ts +++ b/packages/paperclip-runner/src/live/runnerd-codex-transport.test.ts @@ -8,6 +8,7 @@ import { readFile, readdir, readlink, + realpath, rename, rm, stat, @@ -17,6 +18,7 @@ import { import { createHash, randomUUID } from "node:crypto"; import { execFileSync, spawn } from "node:child_process"; import { readFileSync } from "node:fs"; +import { bindAcpxAgentFiles } from "../drivers/acpx/agent-files-binding.js"; import { createServer } from "node:http"; import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; @@ -524,6 +526,69 @@ it("carries the provider attachment seed across consecutive authority rotations" }); }); +it("projects a warm Copilot grant onto the remote runner filesystem", () => { + const runtimeContext = assignedRuntimeContext("/controller/skills", "/controller/instructions"); + runtimeContext.instructions.workingCopy = { kind: "agent_files", rootPath: "/remote/registered-agent", entryPath: "AGENTS.md" }; + const grant = { runtimeContext, instructions: "Read-only instruction sibling root: /controller/instructions" }; + const projected = runnerdRecoveryInternals.projectCopilotRunGrant(grant, "/remote/session/filesystem"); + expect(projected.runtimeContext?.instructions.bundle.rootPath).toBe("/remote/session/filesystem/context/instructions"); + expect(projected.runtimeContext?.skills[0]?.bundle.rootPath).toBe(`/remote/session/filesystem/context/skills/0-${runtimeContext.skills[0]!.bundle.digest.slice(0, 12)}`); + expect(projected.runtimeContext?.instructions.workingCopy).toEqual(runtimeContext.instructions.workingCopy); + expect(projected.runtimeContext?.aggregateDigest).toBe(runtimeContext.aggregateDigest); + expect(projected.instructions).toBe("Read-only instruction sibling root: /remote/session/filesystem/context/instructions"); + expect(grant.runtimeContext.instructions.bundle.rootPath).toBe("/controller/instructions"); + expect(runnerdRecoveryInternals.projectCopilotRunGrant(grant)).toEqual(grant); +}); + +it("reopens Copilot with the current registered files after collecting the previous run copy", async () => { + const root = await mkdtemp(join(tmpdir(), "copilot-current-attachment-")); + const previousRoot = join(root, "previous-agent"); + const currentRoot = join(root, "current-agent"); + try { + await mkdir(previousRoot); + await mkdir(currentRoot); + await writeFile(join(currentRoot, "AGENTS.md"), "Current instructions.\n"); + const previousContext = assignedRuntimeContext("/skills", "/bundle"); + previousContext.instructions.workingCopy = { kind: "agent_files", rootPath: previousRoot, entryPath: "AGENTS.md" }; + const currentContext = structuredClone(previousContext); + currentContext.instructions.workingCopy!.rootPath = currentRoot; + const seed = { + provider: { kind: "acpx", agent: "copilot", runId: "prior-run", normalizedSessionId: "same-session", + instructions: "Previous instructions.", runtimeContext: previousContext, commandDigest: "unchanged", model: "selected-model" }, + }; + await rm(previousRoot, { recursive: true }); + const attached = runnerdRecoveryInternals.rotatedRunAttachPayload( + { runAttachTemplate: seed }, + { runnerInstanceId: "runner", environmentLeaseId: "lease", runId: "current-run", normalizedSessionId: "same-session", turnId: "turn", itemId: "item" }, + null, undefined, + currentContext, { text: "Current instructions.", context: currentContext }, + ); + const provider = attached.provider as typeof seed.provider; + const files = bindAcpxAgentFiles(provider.runtimeContext, []); + expect(files?.root).toBe(await realpath(currentRoot)); + files?.assertHeld(); + expect(provider).toMatchObject({ instructions: "Current instructions.", commandDigest: "unchanged", model: "selected-model", normalizedSessionId: "same-session" }); + expect(seed.provider.runtimeContext).toEqual(previousContext); + expect(seed.provider.instructions).toBe("Previous instructions."); + } finally { await rm(root, { recursive: true, force: true }); } +}); + +it.each(["claude", "codex", "cursor", "pi", "copilot"])("keeps %s's pinned grants on same-run recovery", (agent) => { + const identity = { runnerInstanceId: "runner", environmentLeaseId: "lease", runId: "same-run", normalizedSessionId: "session", turnId: "turn", itemId: "item" }; + const provider = { kind: "acpx", agent, runId: identity.runId, instructions: "Pinned instructions.", runtimeContext: assignedRuntimeContext("/skills", "/pinned") }; + const payload = runnerdRecoveryInternals.rotatedRunAttachPayload({ runAttachTemplate: { provider } }, identity, null, undefined, + undefined); + expect(payload.provider).toMatchObject(provider); +}); + +it.each(["claude", "codex", "cursor", "pi"])("preserves %s's cross-run context when no new grant is supplied", (agent) => { + const provider = { kind: "acpx", agent, runId: "prior-run", instructions: "Pinned instructions.", runtimeContext: assignedRuntimeContext("/skills", "/pinned") }; + const payload = runnerdRecoveryInternals.rotatedRunAttachPayload({ runAttachTemplate: { provider } }, + { runnerInstanceId: "runner", environmentLeaseId: "lease", runId: "new-run", normalizedSessionId: "session", turnId: "turn", itemId: "item" }, null, undefined, + undefined); + expect(payload.provider).toMatchObject({ ...provider, runId: "new-run" }); +}); + it("replays the durable run attachment outcome and latest provider identity", () => { expect( runnerdRecoveryInternals.recoveredRunAttachment({ diff --git a/packages/paperclip-runner/src/live/runnerd-codex-transport.ts b/packages/paperclip-runner/src/live/runnerd-codex-transport.ts index ba6f3f32487..1fe263278ac 100644 --- a/packages/paperclip-runner/src/live/runnerd-codex-transport.ts +++ b/packages/paperclip-runner/src/live/runnerd-codex-transport.ts @@ -21,7 +21,7 @@ import { writeFileSync, } from "node:fs"; import { tmpdir } from "node:os"; -import { basename, dirname, resolve } from "node:path"; +import { basename, dirname, posix, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import type { @@ -69,7 +69,7 @@ import { createSanitizedAwsAgentCoreEnvironment, createSanitizedClaudeManagedEnvironment, } from "../drivers/claude-managed/environment.js"; -import { composeNativeSystemInstructions, type NativeRuntimeContextSnapshot } from "../contracts/runtime-context.js"; +import { composeNativeSystemInstructions, type NativeRunRuntimeGrant, type NativeRuntimeContextSnapshot } from "../contracts/runtime-context.js"; import type { NativeAcpxPermissionMode, NativeOpenCodePermissionMode, @@ -418,6 +418,22 @@ async function rotateExternalAuthorityEpoch( return controlPlaneState; } +function projectCopilotRunGrant( + grant: NativeRunRuntimeGrant, + runnerFilesystemRoot?: string, +): NativeRunRuntimeGrant { + const projected = structuredClone(grant); + const context = projected.runtimeContext; + if (!runnerFilesystemRoot || !context) return projected; + const sourceInstructionRoot = context.instructions.bundle.rootPath; + context.instructions.bundle.rootPath = posix.join(runnerFilesystemRoot, "context", "instructions"); + context.skills.forEach((skill, index) => { + skill.bundle.rootPath = posix.join(runnerFilesystemRoot, "context", "skills", `${index}-${skill.bundle.digest.slice(0, 12)}`); + }); + projected.instructions = projected.instructions.replaceAll(sourceInstructionRoot, context.instructions.bundle.rootPath); + return projected; +} + function rotatedRunAttachPayload( state: { commands?: unknown; runAttachTemplate?: unknown }, desired: DurableRecoveryIdentity, @@ -1420,6 +1436,17 @@ export function expandRunnerdCanonicalNotifications( }); } +/** Keep durable expiry visible to the facade before its terminal notification. */ +export function runnerdRuntimeRequestExpiryNotification( + eventType: string, payload: Record, threadId: string | null, turnId: string | null, +): CodexRpcNotification | null { + if (eventType !== "runtime_request.expired") return null; + return { method: "paperclip/runtimeRequestExpired", params: { + ...(threadId ? { threadId } : {}), ...(turnId ? { turnId } : {}), + payload, itemId: payload.itemId, + } }; +} + export function runnerdCanonicalNotificationMethod( eventType: string, payload: Record, @@ -3947,6 +3974,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { runId: string; turnId: string; itemId: string; + currentRunGrant?: NativeRunRuntimeGrant; }): Promise { if (this.#pendingWarmRecoveryCompletion !== null) { throw new Error("native_runner_warm_transition_completion_pending"); @@ -3956,6 +3984,12 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { throw new Error("native_runner_prp_run_rotation_unavailable"); } await this.#awaitWarmRunAttachmentReady(); + const currentRunGrant = input.currentRunGrant + ? projectCopilotRunGrant(input.currentRunGrant, this.options.runnerFilesystemRoot) + : undefined; + if (this.options.provider === "acpx" && this.options.acpxAgent === "copilot" && !currentRunGrant) { + throw new Error("native_runner_current_instruction_grant_unavailable"); + } const prior = core.store.state.identity; const desired: DurableRecoveryIdentity = { ...prior, @@ -3985,12 +4019,16 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { desired, this.#authorizedTools, this.options.resumeCompletionContract, + currentRunGrant?.runtimeContext, + currentRunGrant ? { text: currentRunGrant.instructions, context: currentRunGrant.runtimeContext } : undefined, ) : rotatedRunAttachPayload( core.store.state, desired, this.#authorizedTools, this.options.resumeCompletionContract, + currentRunGrant?.runtimeContext, + currentRunGrant ? { text: currentRunGrant.instructions, context: currentRunGrant.runtimeContext } : undefined, ); this.#runAttachTemplate = structuredClone(runAttachTemplate); const payload = { @@ -5284,6 +5322,10 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { }); this.#core = core; if (rotatedAuthority) { + if (provider === "acpx" && this.options.acpxAgent === "copilot" + && typeof this.options.baseInstructions !== "string") { + throw new Error("native_runner_current_instruction_grant_unavailable"); + } const runAttachTemplate = rotatedRunAttachPayload( controlPlaneState, desiredIdentity, @@ -6212,6 +6254,13 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { ).requestId; if (typeof requestId === "string") this.#bridgedRuntimeInputs.delete(requestId); + // Operator resolution/Stop keep their existing acknowledgement path. + const expiry = runnerdRuntimeRequestExpiryNotification(event.eventType, record(eventPayload), this.#threadId, this.#turnId); + if (expiry) this.#queue.push({ ...expiry, + ...(this.options.environment?.PAPERCLIP_PROVIDER_TRACE_PATH ? { paperclipTrace: { + sourceEventId: event.sourceEventId, sourceEventType: event.eventType, + } } : {}), + }); continue; } const sessionUpdatePayload = record(eventPayload); @@ -6913,6 +6962,7 @@ export const runnerdLaunchProfileInternals = Object.freeze({ }); export const runnerdRecoveryInternals = Object.freeze({ + projectCopilotRunGrant, completedMaintenanceTerminalReceipt, completedMaintenanceTerminalReplayMatches, readControlPlaneState, diff --git a/packages/paperclip-runner/src/native-session-runtime.test.ts b/packages/paperclip-runner/src/native-session-runtime.test.ts index 610813ef9c6..c1d226f3d97 100644 --- a/packages/paperclip-runner/src/native-session-runtime.test.ts +++ b/packages/paperclip-runner/src/native-session-runtime.test.ts @@ -1,4 +1,5 @@ import { createHash } from "node:crypto"; +import { resolveQualifiedAcpxProfile } from "./drivers/acpx/qualified-profiles.js"; import { describe, expect, it, vi } from "vitest"; import type { ControlPlanePort } from "./contracts/control-plane-port.js"; @@ -5004,7 +5005,19 @@ describe("executeNativeSession recovery", () => { expect(attachRun).not.toHaveBeenCalled(); }); - it("quarantines a retained session when attachment partially mutates then fails", async () => { + it.each(["codex", "copilot"] as const)("quarantines a retained %s session when attachment partially mutates then fails", async (provider) => { + const qualified = resolveQualifiedAcpxProfile("copilot", "selected-model"); + const executionInput: NativeExecutionInputV1 = provider === "copilot" ? { + ...input, + session: { ...input.session, driverKind: "acpx_runtime" }, + provider: { kind: "acpx", agent: "copilot", model: "selected-model", permissionPolicy: "interactive", profile: { + driverKind: qualified.driverKind, protocolVersion: qualified.protocolVersion, acpxVersion: qualified.acpxVersion, + agent: qualified.agent, agentProfileVersion: qualified.agentProfileVersion, + agentServerPackage: qualified.agentServerPackage, agentServerVersion: qualified.agentServerVersion, + agentRuntimePackage: qualified.agentRuntimePackage, agentRuntimeVersion: qualified.agentRuntimeVersion, + commandDigest: qualified.commandDigest, + } }, + } : input; const attachmentFailure = new Error("provider attachment failed"); const openRun = vi.fn(async () => undefined); let retainedIdentity = { ...identity, runId: "run-previous" }; @@ -5041,7 +5054,7 @@ describe("executeNativeSession recovery", () => { async descriptor() { return { kind: "mock", - name: "attachment-failure-backend", + name: `attachment-failure-backend-${provider}`, version: "1", capabilities: { resume: true, @@ -5069,7 +5082,7 @@ describe("executeNativeSession recovery", () => { await expect( executeNativeSession({ - input, + input: executionInput, backend, controlPlane: port, runnerInstanceId: "runner-recovery", @@ -5078,7 +5091,9 @@ describe("executeNativeSession recovery", () => { onSession, }), ).rejects.toBe(attachmentFailure); - expect(attachRun).toHaveBeenCalledWith({ identity }); + expect(attachRun).toHaveBeenCalledWith(provider === "copilot" + ? { identity, currentRunGrant: { runtimeContext: null, instructions: expect.any(String) } } + : { identity }); expect(retainedIdentity).toEqual(identity); expect(onSession).toHaveBeenCalledOnce(); expect(onSession).toHaveBeenCalledWith(null); diff --git a/packages/paperclip-runner/src/native-session-runtime.ts b/packages/paperclip-runner/src/native-session-runtime.ts index e01dd745e23..c40f591176d 100644 --- a/packages/paperclip-runner/src/native-session-runtime.ts +++ b/packages/paperclip-runner/src/native-session-runtime.ts @@ -1,4 +1,5 @@ import { randomUUID } from "node:crypto"; +import { nativeSystemInstructions } from "./backends/runtime-context.js"; import type { CheckpointControlPlaneSessionOptions, @@ -2004,7 +2005,12 @@ export async function executeNativeSession( // state). Prove the provider attachment before opening durable // control-plane state because ControlPlanePort has no rollback operation. try { - await options.existingSession.attachRun({ identity }); + await options.existingSession.attachRun({ identity, + ...(input.provider.kind === "acpx" && input.provider.agent === "copilot" + ? { currentRunGrant: { runtimeContext: "runtimeContext" in input ? input.runtimeContext : null, + instructions: nativeSystemInstructions(input) } } + : {}), + }); } catch (error) { // attachRun has no transactional guarantee: a provider may bind the new // run before reporting a later failure. Conservatively quarantine the diff --git a/packages/paperclip-runner/test/acpx-codex-package-contract.test.mjs b/packages/paperclip-runner/test/acpx-codex-package-contract.test.mjs index 6cc83159c5e..3cd71aa3198 100644 --- a/packages/paperclip-runner/test/acpx-codex-package-contract.test.mjs +++ b/packages/paperclip-runner/test/acpx-codex-package-contract.test.mjs @@ -52,7 +52,11 @@ test("the runner pins every qualified ACPX production dependency", () => { assert.equal(runnerPackage.dependencies["@anthropic-ai/claude-agent-sdk"], undefined); assert.equal(rootPackage.pnpm.overrides["@agentclientprotocol/codex-acp@1.6.2>@openai/codex"], runnerPackage.dependencies["@openai/codex"]); assert.equal(rootPackage.pnpm.overrides["@agentclientprotocol/claude-agent-acp@0.73.0>@anthropic-ai/claude-agent-sdk"], "0.3.286"); - assert.equal(runnerPackage.optionalDependencies, undefined); + assert.deepEqual(runnerPackage.optionalDependencies, { + "@github/copilot-darwin-arm64": "1.0.88", + "@github/copilot-darwin-x64": "1.0.88", + "@github/copilot-linux-x64": "1.0.88", + }); assert.equal(runnerPackage.dependencies.node, undefined); assert.equal(runnerPackage.dependencies.acpx, "0.13.1"); assert.equal( @@ -83,6 +87,7 @@ test("the package exposes only the reviewed runner CLI binaries", () => { "paperclip-runner-eval-session": "./dist/cli/eval-session.js", "paperclip-runner-codex-proxy": "./dist/cli/codex-app-server-unix-proxy.js", "paperclip-runner-acpx-sidecar": "./dist/cli/acpx-runtime-sidecar.js", + "paperclip-runner-copilot-metadata-probe": "./dist/cli/copilot-metadata-probe.js", "paperclip-runner-opencode-proxy": "./dist/cli/opencode-app-server-proxy.js", }); diff --git a/packages/paperclip-runner/test/acpx-message-boundaries-package-contract.test.mjs b/packages/paperclip-runner/test/acpx-message-boundaries-package-contract.test.mjs new file mode 100644 index 00000000000..af58aff37df --- /dev/null +++ b/packages/paperclip-runner/test/acpx-message-boundaries-package-contract.test.mjs @@ -0,0 +1,58 @@ +import assert from "node:assert/strict"; +import { spawn } from "node:child_process"; +import { mkdtemp, rm } from "node:fs/promises"; +import { createRequire } from "node:module"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { pathToFileURL } from "node:url"; +import test from "node:test"; + +const require = createRequire(import.meta.url); +const root = process.env.PAPERCLIP_TEST_ACPX_ROOT ?? dirname(require.resolve("acpx/package.json")); +const { createAcpRuntime, createAgentRegistry, createFileSessionStore } = await import(pathToFileURL(join(root, "dist/runtime.js"))); +const fixture = String.raw` +const readline = require('node:readline'); +const send = value => process.stdout.write(JSON.stringify({jsonrpc:'2.0',...value})+'\n'); +readline.createInterface({input:process.stdin}).on('line',line=>{ + const request=JSON.parse(line); + if(request.method==='initialize') send({id:request.id,result:{protocolVersion:1,agentCapabilities:{sessionCapabilities:{close:{}}},authMethods:[]}}); + else if(request.method==='session/new') send({id:request.id,result:{sessionId:'fixture-session'}}); + else if(request.method==='session/prompt') { + for(const update of JSON.parse(request.params.prompt[0].text)) send({method:'session/update',params:{sessionId:'fixture-session',update}}); + send({id:request.id,result:{stopReason:'end_turn'}}); + } else if(request.id!==undefined) send({id:request.id,result:{}}); +});`; + +test("actual ACP SDK and runtime retain identified empty assistant boundaries in order", { timeout: 15_000 }, async () => { + const cwd = await mkdtemp(join(tmpdir(), "paperclip-acpx-message-boundary-")); + const children = []; + const runtime = createAcpRuntime({ cwd, sessionStore: createFileSessionStore({ stateDir: join(cwd, "sessions") }), + agentRegistry: createAgentRegistry({ overrides: { pi: ["verified-fixture"] } }), permissionMode: "approve-all", + spawnAgent: () => { const child = spawn(process.execPath, ["-e", fixture], { cwd, stdio: ["pipe", "pipe", "pipe"] }); children.push(child); return child; }, + }); + let handle; + try { + handle = await runtime.ensureSession({ sessionKey: "fixture-boundaries", agent: "pi", mode: "persistent", cwd }); + const chunk = (messageId, text, kind = "delta", thought = false) => ({ sessionUpdate: thought ? "agent_thought_chunk" : "agent_message_chunk", + ...(messageId ? { messageId } : {}), content: { type: "text", text }, + _meta: { origin: "pi-native-assistant", source: "pi-rpc-message-v1", kind, unrelated: "DROP_ME" }, + }); + const updates = [chunk("first", "", "start"), chunk("first", "pre-tool narration"), chunk("first", "", "end:toolUse"), + chunk("last", "", "start"), chunk("last", "thought", "delta", true), chunk("last", "EXACT_MARKER"), chunk("last", "", "end:stop"), + chunk(undefined, ""), { sessionUpdate: "agent_message_chunk", messageId: "no-text", content: { type: "image", data: "", mimeType: "image/png" } }]; + for (let index = 0; index < 2; index++) { + const turn = runtime.startTurn({ handle, text: JSON.stringify(updates), mode: "prompt", sessionMode: "persistent", requestId: `request-${index}`, timeoutMs: 5000 }); + const events = []; + for await (const event of turn.events) if (event.type === "text_delta") events.push(event); + assert.equal((await turn.result).status, "completed"); + assert.deepEqual(events.map(event => [event.messageId, event.text, event.meta?.kind, event.stream]), [ + ["first", "", "start", "output"], ["first", "pre-tool narration", "delta", "output"], ["first", "", "end:toolUse", "output"], + ["last", "", "start", "output"], ["last", "thought", "delta", "thought"], ["last", "EXACT_MARKER", "delta", "output"], ["last", "", "end:stop", "output"], + ]); + assert.equal(JSON.stringify(events).includes("DROP_ME"), false); + } + } finally { + try { if (handle) await runtime.close({ handle, discardPersistentState: true }); } + finally { for (const child of children) child.kill("SIGTERM"); await rm(cwd, { recursive: true, force: true }); } + } +}); diff --git a/packages/paperclip-runner/test/fixtures/copilot-live-denial-2026-09-28.json b/packages/paperclip-runner/test/fixtures/copilot-live-denial-2026-09-28.json new file mode 100644 index 00000000000..a806c4cefad --- /dev/null +++ b/packages/paperclip-runner/test/fixtures/copilot-live-denial-2026-09-28.json @@ -0,0 +1,124 @@ +{ + "schema": "paperclip.copilot-live-denial-proof/v1", + "providerVersion": "1.0.88", + "model": "gpt-5.6-luna", + "qualificationStatus": "pending", + "scenario": "deny-write", + "probeSourceRevision": "47eed960b380e8c8054eb19985aaefeabc6336c3", + "providerSourceRevision": "8aa867b64d5fc2fd62cff110bd000addf5dc54de", + "providerPackDigest": "sha256:627992ea80e8be7154d07cbc9925b781519199e25690b02d4a044f44342e6bd8", + "profileDigest": "sha256:b18c01603dd0169d233140709cfaa8bf5304a03cf5de78ca4f625f30013e8457", + "privateEvidenceSha256": "sha256:f5cd355cbed796e3ed1564f6201e55e9e90e0419197912a6bb89948c4d0eb340", + "promptRequestsSent": 1, + "upstreamModelRequestCount": null, + "activeTurnDeadlineSeconds": 120, + "outerDeadlineSeconds": 180, + "automaticRetries": 0, + "reservationUsd": 2, + "stopReason": "end_turn", + "terminalElapsedMs": 7187, + "permissions": [ + { + "elapsedMs": 7177, + "requestId": 0, + "offeredOptions": [ + { + "optionId": "allow_once", + "kind": "allow_once", + "name": "Allow once" + }, + { + "optionId": "allow_always", + "kind": "allow_always", + "name": "Always allow" + }, + { + "optionId": "reject_once", + "kind": "reject_once", + "name": "Deny" + } + ], + "outcome": { + "outcome": "selected", + "optionId": "reject_once" + }, + "kind": "reject_once", + "exactSession": true, + "exactCommand": false, + "writeAttempt": true + } + ], + "nativeToolCall": { + "title": "Create file", + "kind": "edit", + "rawInput": { + "fileName": "/fixture/workspace/qualification-marker.txt", + "diff": "\ndiff --git a/fixture/workspace/qualification-marker.txt b/fixture/workspace/qualification-marker.txt\ncreate file mode 100644\nindex 0000000..0000000\n--- a/dev/null\n+++ b/fixture/workspace/qualification-marker.txt\n@@ -1,0 +1,2 @@\n+MUST_NOT_EXIST\n+\n\n" + }, + "locations": [ + { + "path": "/fixture/workspace/qualification-marker.txt" + } + ] + }, + "markerOracle": { + "sampleCount": 79, + "anySampleExisted": false, + "terminal": { + "elapsedMs": 7187, + "phase": "terminal", + "exists": false, + "matches": false + }, + "afterCleanup": { + "elapsedMs": 12837, + "phase": "after_process_cleanup", + "exists": false, + "matches": false + } + }, + "providerExit": { + "code": 0, + "signal": null + }, + "cleanupComplete": true, + "result": { + "passed": true, + "failures": [] + }, + "nativeUsage": { + "inputTokens": 10989, + "outputTokens": 65, + "totalTokens": 11054, + "thoughtTokens": 30, + "cachedReadTokens": 0, + "cachedWriteTokens": 10986 + }, + "providerReportedCostUsd": null, + "externalBilling": { + "baselineDisplayedIncludedAiCreditsUsed": 3, + "displayedIncludedAiCreditsTotal": 1500, + "postProbeReconciliation": "parent refreshed GitHub dashboard", + "exactCreditConsumption": null, + "additionalUsageEnabled": false, + "additionalCashBudgetUsd": 0, + "postProbeDisplayedIncludedAiCreditsUsed": 3, + "additionalCashChargesUsd": 0, + "note": "Unchanged display can reflect granularity or delay; it is not a zero-credit per-run receipt." + }, + "scope": "One real GitHub inference request through the verified native ACP command lease. This proves this denied file edit only, not every tool or full Product/Daytona qualification.", + "offlineExactTargetRevalidation": { + "originalPrivateEvidenceSha256": "sha256:f5cd355cbed796e3ed1564f6201e55e9e90e0419197912a6bb89948c4d0eb340", + "oracleScriptSha256": "sha256:0dc70ffd88abf502a68f8b4974b799d105c928bf250be615532e71cd919a765f", + "method": "Offline replay of retained permission rawInput.fileName and original marker observations through tightened exact-target oracle", + "requestIds": [ + 0 + ], + "allDeniedWriteTargetsMatchMarker": true, + "result": { + "passed": true, + "failures": [] + }, + "newProviderPrompts": 0 + } +} diff --git a/packages/paperclip-runner/test/fixtures/copilot-profile-v12-identity.json b/packages/paperclip-runner/test/fixtures/copilot-profile-v12-identity.json new file mode 100644 index 00000000000..82b2ad0f4d3 --- /dev/null +++ b/packages/paperclip-runner/test/fixtures/copilot-profile-v12-identity.json @@ -0,0 +1,43 @@ +{ + "commandDigest": "sha256:48cecd8dc77a5533240fcf2f29d19be05380da4a79f8e5061480f94241db75a8", + "declaration": { + "schema": "paperclip.acpx_profile_declaration.v1", + "agent": "copilot", + "agentProfileVersion": 12, + "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": "d58076d59ec23fe2261cba3aa0dca3e9f189105f0a5fa7ca3eeaac05cb338f31", + "semanticDirectDriverSourceSha256": "31e36917ee3592fa6d8f4b86632129fdffae20c45aed2e0e367ccf523e064f88", + "semanticValidationSourceSha256": "039fca52266fe21ba74ca64660d21228314d8ed737b19ba67941bfb25086e4d5", + "semanticNormalizationSourceSha256": "b1ce59251bf9c671f66e0e5173646190b9a2d1bfc5bdb7fb123824213986b92b", + "semanticCompletionContractSourceSha256": "00a684f9aea87f68eabf0974681c52461bc308631a1252a89c4ed087d7158b28", + "semanticValidatorsSourceSha256": "950b49b233d8dd62ff858398becfc55f0a181160cb8a434d9221b5c17816867c", + "semanticSchemaBundleSourceSha256": "bb55e18c5563bf5ec226e301c3399229304f295e986865e96554f193535368f2", + "semanticSidecarProtocolSourceSha256": "165cad76f224d60f0dc7928736d47a16787eaa8ab9e4c2222488da5fc8ad632e", + "semanticSidecarReceiptCommitContract": "correlated-tool-resolve-v1" + } +} diff --git a/packages/paperclip-runner/test/fixtures/copilot-profile-v31-identity.json b/packages/paperclip-runner/test/fixtures/copilot-profile-v31-identity.json new file mode 100644 index 00000000000..9e8ac963db8 --- /dev/null +++ b/packages/paperclip-runner/test/fixtures/copilot-profile-v31-identity.json @@ -0,0 +1,81 @@ +{ + "commandDigest": "sha256:4a22e4c50fd213c79cd02fd3c5369aef2256ac719762c62f5b70c691cd47e76b", + "declaration": { + "schema": "paperclip.acpx_profile_declaration.v1", + "agent": "copilot", + "agentProfileVersion": 31, + "acpxVersion": "0.13.1", + "agentServerVersion": "1.0.88", + "protocolPolicyRevision": "copilot-agent-manual-v1", + "acpxPatchSha256": "fedf1e498c1e19daf9c973d475234488aa9acabbf1b9de890245bfac7a534483", + "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": "eebcc1ec9bc8caa8d1edf0cbda74bd69f5c55cf8d65a0503e95798b9979a19dc", + "permissionLocationsSourceSha256": "f39a81da395b6e23aa2a1a45572a28846e5e81bfd3d764d9a456f74a79c752e9", + "permissionRedactionSourceSha256": "ad6770c69269087951790e2e87e22ac088e3d432769adf17ebc865ed512e6c4f", + "permissionClassifierSourceSha256": "1161eabd82e26133e3b3db3ab567f65d52808b03f176e93497e02c8330349fb4", + "semanticToolReceiptContract": "paperclip.semantic_tool_receipt.v2", + "semanticReceiptSourceSha256": "b2795726b2234a663fec1a6ca11f0551ae69882fe9e82aa39686e952d036e791", + "semanticBridgeSourceSha256": "cf136da18e2cdbefae8e01d23d2c93f64eb7aebccaec938e84c2887c888f87ee", + "toolEvidenceSourceSha256": "4b517eed447615b3cc820af348ccc360978175149caa0bbc838d1f78332abe75", + "semanticNormalizedInputContract": "validated-forwarded-input-commit-v1", + "semanticSidecarSourceSha256": "49f7cb882fa09dcf879a2234d3e7b43fe72895d2c0f1e9b72fcbe18f012423bb", + "semanticDirectDriverSourceSha256": "3cea77a03c8822d68f77f090457176a9190facbec7d88ddf8c583c0e42245f70", + "semanticValidationSourceSha256": "3b0ac8d3f3cb92747d0bcea472ab0419a140e1cfdc43047e2c22542acc2d105f", + "semanticNormalizationSourceSha256": "8b628b82e8eacc91cdcc6fdca2210ba4cf282f01e9c6f74e95ff271655b5047e", + "semanticCompletionContractSourceSha256": "fa2b0c81cb9a62965839c905db81b930794774d8d557a01bce077dae5830b594", + "semanticValidatorsSourceSha256": "328436d29148e0b79ce36f36c764b3d780913bdb90d174d1ea03cf1f59b5ef13", + "semanticSchemaBundleSourceSha256": "d8cef4a9ebc136a3d37f3d0be7161986e6d65420e2ec734cfd0dfa468c665c97", + "semanticSidecarProtocolSourceSha256": "907b2cdc1a5291c6fb570855bbcc66cb196b5cf64195d5dc201148940678460a", + "semanticSidecarReceiptCommitContract": "correlated-tool-resolve-v1", + "displayEventSourceSha256": "d72f9a6035c247bc6a42c067c05753076c54322c4b58984e93922f3325dc6877", + "displayProjectionSourceSha256": "75952606b26dd93bbc582c1f0a4424487377272ea745fb3a27ceae031fd5dc7e", + "configuredEnvironmentSourceSha256": "a03575b3a737dea60da94cf0fa1feed80719a9aaa7f09456eb57a845d9e8e087", + "configuredEnvironmentRustSourceSha256": "55d44e48e217385b5c64b1b7d8df16dda62319ca3fb524e452fd78c9ed804d3b", + "profileActivitySourceSha256": "4fdb6b0f9125fd8372ba6f27945fa5c8a3d3b2ec891df544092e3dc7a75d5282", + "profileExtensionsSourceSha256": "0565d13d4064ed8c501d6ffda6d7bffca4493552de8aaa7fc12178dabb3ca435", + "profileInstallationSourceSha256": "7c26545922fc85db75a5db6bf3f6e21e381b6e189f4f51243b19ee237b93f8b1", + "attachmentPolicySourceSha256": "ce8027d1f8e2b7fd35df56a75ba162fd9696d1569c016b60bc9f0de1252cd958", + "singleReadEvidenceSourceSha256": "4069393405089bde613cecec04f5123c426594811da4c668bd96f0e7e283550f", + "nativeSessionRuntimeSourceSha256": "aac818c1cf50a25899ae95cafc70f093c8cd8af37d19f88cbb7847b4d202d2b6", + "nativeRuntimeContextSourceSha256": "af192af3fa511347045dfdb86d443be9aa046a4c56bdb48198668cf4d30581b8", + "nativeSessionContractSourceSha256": "93251b1eadc686e9d8339d4dfc50b995a3d0a9e6ad8aedc6f2bdf7e30c16138d", + "harnessSessionContractSourceSha256": "75ae4607312ec13466dd2f4ac87f000302b7b5a952cb6d4b51573fa8b7c35d82", + "harnessBackendSourceSha256": "3b11fd93b82ef13d5e6396217e3f102f900437f4d32efb00a9d75a9d2214e6ff", + "harnessSessionSourceSha256": "a9d748b8530544342bbc9f59968816664872782a0865db76ca15f28a1705697b", + "transportContractSourceSha256": "16f358c75dd4ae80af3ca921394c5899b15942b80b553e43ddfabb41c1bf31d3", + "nativeBackendSourceSha256": "a23afeab7e7094cb7e3df05e7a9eac822d0144d8c44893dbcc8a0e7b2bce0c85", + "nativeBackendFactorySourceSha256": "ce22825a53669f8c2db5aaa890bae94af19ede22295bda4ed7987a31d804cd8a", + "nativeInstructionsSourceSha256": "ea85be2aca8dfbd6b4042dcd7b1ed9db9a57baf8c379649a3f5d7d80ca54a6a2", + "runtimeRequestBridgeSourceSha256": "c449568f8abf7e90d5ae7a83b49809d9166461398f8b3046e4fe5f3367f3b052", + "runtimeRequestFacadeSourceSha256": "3d70c6025169779f7886ddf363a1c6fda4add5d14fa3cd49aea46aa1f6a9d8ec", + "runtimeRequestNotificationSourceSha256": "6196c6175f11c69295dc00fc773201f4fdeca26c500653870253c43b81e65211", + "guardedInstallationSourceSha256": "8afd25df307772e484e179e58bf54ce1510fe92be694482111d589f9f0ae6e77", + "nativeExecutionSourceSha256": "4cdd702c233bf0d086ff2aeea8f02c6db8817ba0c0bcb5e64e355ee7a1c2dd77", + "profileCompatibilitySourceSha256": "ef78b62e804473f7c1c9f5e119b4755e774f1ba1cdb7b01609b74392af2547e6", + "installationSourceSha256": "9934653d6983905930099b1691b1f0c05461e04e950bb27dd0f92e64fc8e28e1", + "assetOwnershipSourceSha256": "43005b7e896e0546c1f44cbe4ff3f34ad6d71f275f4b9a8113f73a71e77930c4", + "assetInstallerSourceSha256": "d3bd9514e5920d0cc3567aa50487fb534c57a6f66b8da0d3f22c5f6e499c841f", + "credentialBindingSourceSha256": "d5c200bea2e8ab730eb56e32ce2070c8a1b5407e5907108640f76a463d9b9c9c", + "sidecarErrorSourceSha256": "23f3dbdc1ce488c690d218a854c820f4b4f3edd822bad574d67707314f8c512a", + "profileSourceSha256": "baf0b64371fada6c92331f9f88e915292b2761c029fd86452f6de32e26dc7fd6", + "metadataProbeSourceSha256": "e8bdefca57b9678d2b5d99b0bc604301d12993b9c9cc4ecb4b5d3df0b83cec3f", + "permissionToolIdentitySourceSha256": "770b47305e571a81f344883057d0e4a482a1cd59ac77d045836593a8e739deb1", + "runtimeHostSourceSha256": "83a5ae07c19681ab195f76363661c2381494b243343270ba363d4db2088932a5", + "runtimeAdapterSourceSha256": "a1a8784f5883d2c93df6e3695d5499b83e226efb4f26e558639c4e7dbcc2d67a", + "runtimeSandboxSourceSha256": "4acec4c9757fe5ef5f2788ce20ced8ca4fde8edcfb63b59d0effcfd4316c048d", + "cancellationSourceSha256": "a07d1a9e982dec0ae130c1ad1efa5bc75c6a39e013b730ba3ee45256f09ceeca", + "agentFilesSourceSha256": "fb32f6badc13dfa22f231479509b631b2f0eba0c99b1ab9f3cd5c0c601aa03ba", + "nativeDistributionSourceSha256": "9bbe8329064ee88418528394f8e1cdc716a0b2b35092dc70729b8850e46b7a68" + } +}