diff --git a/doc/architecture/runner-copilot-capabilities.md b/doc/architecture/runner-copilot-capabilities.md index 987b05c97ae..651d80d734a 100644 --- a/doc/architecture/runner-copilot-capabilities.md +++ b/doc/architecture/runner-copilot-capabilities.md @@ -278,16 +278,22 @@ backpressure can drop events. There is no event ID or reliable replay contract. even when subscribed. These are provider restrictions, not missing runner parsing. `copilot-events.ts` requests 22 event types and projects only bounded declared -fields after matching the active session and turn. It records source method/type, +fields after matching the admitted session and an active receiver. The pinned +notification has no originating turn ID; arrival during a later turn cannot +establish attribution. It records source method/type, provider timestamp and subagent identity. Payloads cannot authorize filesystem reads, workspace rebinding, permission changes, native-input replies or terminal settlement. Inline binary assets are content-address verified; only metadata is forwarded until a provider-session artifact resolver can upload them safely. -`copilot-extension-adapter.ts` converts the normalized events into canonical -delegation, compaction and unregistered artifact activity. Every safe projected -field is retained in bounded provider-notice details with method/event/session/ -turn provenance. Notices have readable summaries; secret-shaped string values +`copilot-extension-adapter.ts` retains every safe projected field in bounded, +session-scoped provider notices with method/event/session provenance and an +explicit unknown originating-turn attribution. Typed delegation, compaction and +artifact projections are withheld because they would falsely attribute delayed +session notifications to the receiving turn. Native correlated ACP turn events +remain separate. Follow-up: a versioned provider correlation contract is required +before promoting these notices into typed turn activity. Notices have readable +summaries; secret-shaped string values are scrubbed without erasing numeric token counters. These display events never create a usage charge, input-resolution acknowledgment, registered artifact, or turn terminal event. The provider registry installs this factory and initialize @@ -316,6 +322,7 @@ Daytona claims require the separate live product qualification. | Plan approval | Native `exit_plan_mode` callback; notification contains plan content/actions but lacks qualified ACP responder. | Capability-gap notice only; never synthesize plan acceptance. | Agent-mode tool list omits exit_plan_mode. Paperclip semantic plan/revision approval passes through the UI; Native plan-mode input is confirmed unavailable offline; production mode controls remain disabled. | | Plan progress | Standard plan from todos SQL; native `session.plan_changed` has operation only. | Existing ACP plan/activity; native operation preserved, `planContentAvailable:false`. | Source; plan document reads require native interface. P1. | | Models / reasoning / config | Source `session/set_model`, config options for model, reasoning, mode, custom agents, allow_all. | Explicit model admission. Mode/governance changes must remain policy-gated. | Authenticated catalog, exact set_model/config echo and real inference verified for gpt-5.6-luna. Other models and config-mode changes remain unqualified. | +| Native notification attribution | Copilot passthrough identifies the session, optional subagent and timestamp, but no originating turn. | Bounded redacted session notices retain all admitted details; typed delegation/artifact/compaction projection is withheld. | Delayed same-session regression; P1 require a provider-origin turn correlation contract. Arrival time and optional payload IDs cannot establish it. | | Usage | Standard prompt usage and context usage; native assistant usage, AI-unit checkpoint. | Token/counter metadata with source; multiplier and nano-AI-units distinct from USD. | Real token counters retain GitHub provenance; authoritative per-turn USD is unavailable. External included-credit snapshots are separate, with additional cash billing disabled. CLI requested-cost coverage fails closed when unknown. Never double-count passthrough. | | Subagent activity | Native started/configured/completed/failed, model and tool IDs, token/call/duration stats. | Bounded structured activity retaining attribution and model-selection details. | Source and unit fixtures; live UI attribution pending. | | Task file changes / diffs | Standard tools carry locations/diff content for create/edit/str_replace/apply_patch. | Shared ACP tool activity retains bounded `rawOutput`, `inputUpdated` and the first validated relative location. Structured tool `content` diffs/images, `rawInput` and secondary locations are dropped; no complete diff presentation is claimed. | Real denied-create wire contains a diff, but wire presence is not runner/UI preservation. P1 add typed, bounded diff/image content and all validated locations with tool/session provenance; Product file-edit/validation and downloadable-file presentation pass; rich diff rendering remains unqualified. | diff --git a/packages/paperclip-runner/scripts/copilot-provider-pack-smoke.mjs b/packages/paperclip-runner/scripts/copilot-provider-pack-smoke.mjs index 774cda0b9dc..3eeb6cac834 100644 --- a/packages/paperclip-runner/scripts/copilot-provider-pack-smoke.mjs +++ b/packages/paperclip-runner/scripts/copilot-provider-pack-smoke.mjs @@ -1,11 +1,10 @@ import assert from "node:assert/strict"; import { createHash } from "node:crypto"; import { once } from "node:events"; -import { createServer } from "node:http"; -import { mkdir, mkdtemp, readFile, realpath, rm, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; +import { mkdir, readFile, realpath, writeFile } from "node:fs/promises"; import { join, resolve } from "node:path"; import { pathToFileURL } from "node:url"; +import { withCopilotSmokeResources } from "./copilot-smoke-resources.mjs"; // Build verification only. No prompt, credential, model request, or runtime // installation occurs; the provider runs offline with isolated state. @@ -26,91 +25,79 @@ const profile = resolveQualifiedAcpxProfile("copilot", "gpt-4.1"); assert.throws(() => assertAcpxProfileEnvironment("copilot", {}), { code: "COPILOT_AUTH_REQUIRED" }); const installation = await verifyAcpxProfileInstallation(profile); assert.equal(installation.commandDigest, candidate.profileDigest); -const lease = await installation.openCommand(); -const root = await mkdtemp(join(tmpdir(), "paperclip-copilot-pack-smoke-")); -let child; -let exited; -const fixtureRequests = []; -const fixture = 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"); -try { - const environment = { PATH: "/usr/bin:/bin", COPILOT_OFFLINE: "true", COPILOT_AUTO_UPDATE: "false", NO_COLOR: "1", - COPILOT_PROVIDER_BASE_URL: `http://127.0.0.1:${fixture.address().port}`, COPILOT_PROVIDER_TYPE: "openai", - COPILOT_PROVIDER_MODEL_ID: "gpt-4.1", COPILOT_MODEL: "gpt-4.1", - }; - for (const name of ["HOME", "XDG_CONFIG_HOME", "XDG_CACHE_HOME", "XDG_DATA_HOME", "COPILOT_HOME", "COPILOT_CACHE_HOME"]) { - environment[name] = join(root, name.toLowerCase()); - await mkdir(environment[name], { mode: 0o700 }); - } - await writeFile(join(environment.COPILOT_HOME, "config.json"), JSON.stringify({ autoUpdate: false, trustedFolders: [], disableAllHooks: true, memory: false, ide: { autoConnect: false } }), { mode: 0o600 }); - child = lease.spawn([], { cwd: root, env: environment, stdio: "pipe" }); - exited = once(child, "exit"); - const initialized = new Promise((done, reject) => { - let buffer = ""; - let stderr = ""; - let total = 0; - const timeout = setTimeout(() => reject(new Error(`Copilot ACP initialize timed out: ${stderr.replaceAll(root, "/fixture/workspace").replaceAll(pack, "/fixture/provider-pack").slice(0, 4000)}`)), 20_000); - timeout.unref(); - child.once("error", reject); - child.once("exit", () => reject(new Error(`Copilot exited before initialize: ${stderr.replaceAll(root, "/fixture/workspace").replaceAll(pack, "/fixture/provider-pack").slice(0, 4000)}`))); - child.stdout.on("data", chunk => { - total += chunk.length; - if (total > 1024 * 1024) { reject(new Error("Copilot ACP output exceeded bound")); return; } - buffer += chunk.toString("utf8"); - while (buffer.includes("\n")) { - const newline = buffer.indexOf("\n"); - const line = buffer.slice(0, newline); buffer = buffer.slice(newline + 1); - if (!line.trim()) continue; - let response; - try { response = JSON.parse(line); } catch { reject(new Error("Copilot emitted malformed ACP JSON")); return; } - if (response.id === 0 && response.method === undefined) { - clearTimeout(timeout); - if (response.error || !response.result) reject(new Error("Copilot rejected ACP initialize")); - else done(response.result); +await withCopilotSmokeResources(installation, async ({ lease, root, fixture, fixtureRequests }) => { + let child; + let exited; + try { + const environment = { PATH: "/usr/bin:/bin", COPILOT_OFFLINE: "true", COPILOT_AUTO_UPDATE: "false", NO_COLOR: "1", + COPILOT_PROVIDER_BASE_URL: `http://127.0.0.1:${fixture.address().port}`, COPILOT_PROVIDER_TYPE: "openai", + COPILOT_PROVIDER_MODEL_ID: "gpt-4.1", COPILOT_MODEL: "gpt-4.1", + }; + for (const name of ["HOME", "XDG_CONFIG_HOME", "XDG_CACHE_HOME", "XDG_DATA_HOME", "COPILOT_HOME", "COPILOT_CACHE_HOME"]) { + environment[name] = join(root, name.toLowerCase()); + await mkdir(environment[name], { mode: 0o700 }); + } + await writeFile(join(environment.COPILOT_HOME, "config.json"), JSON.stringify({ autoUpdate: false, trustedFolders: [], disableAllHooks: true, memory: false, ide: { autoConnect: false } }), { mode: 0o600 }); + child = lease.spawn([], { cwd: root, env: environment, stdio: "pipe" }); + exited = once(child, "exit"); + const initialized = new Promise((done, reject) => { + let buffer = ""; + let stderr = ""; + let total = 0; + const timeout = setTimeout(() => reject(new Error(`Copilot ACP initialize timed out: ${stderr.replaceAll(root, "/fixture/workspace").replaceAll(pack, "/fixture/provider-pack").slice(0, 4000)}`)), 20_000); + timeout.unref(); + child.once("error", reject); + child.once("exit", () => reject(new Error(`Copilot exited before initialize: ${stderr.replaceAll(root, "/fixture/workspace").replaceAll(pack, "/fixture/provider-pack").slice(0, 4000)}`))); + child.stdout.on("data", chunk => { + total += chunk.length; + if (total > 1024 * 1024) { reject(new Error("Copilot ACP output exceeded bound")); return; } + buffer += chunk.toString("utf8"); + while (buffer.includes("\n")) { + const newline = buffer.indexOf("\n"); + const line = buffer.slice(0, newline); buffer = buffer.slice(newline + 1); + if (!line.trim()) continue; + let response; + try { response = JSON.parse(line); } catch { reject(new Error("Copilot emitted malformed ACP JSON")); return; } + if (response.id === 0 && response.method === undefined) { + clearTimeout(timeout); + if (response.error || !response.result) reject(new Error("Copilot rejected ACP initialize")); + else done(response.result); + } } - } + }); + child.stderr.on("data", chunk => { stderr = (stderr + chunk.toString("utf8")).slice(-16_384); }); }); - child.stderr.on("data", chunk => { stderr = (stderr + chunk.toString("utf8")).slice(-16_384); }); - }); - child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id: 0, method: "initialize", params: { protocolVersion: 1, clientInfo: { name: "paperclip-pack-offline-smoke", version: "1" }, clientCapabilities: COPILOT_ACP_CLIENT_CAPABILITIES } })}\n`); - const result = await initialized; - assert.equal(result.protocolVersion, 1); - assert.equal(result.agentInfo?.version, "1.0.88"); - child.stdin.end(); - const timer = setTimeout(() => child.kill("SIGTERM"), 1_000); - const [exitCode, signal] = await within(exited, 10_000); - clearTimeout(timer); - assert.equal(exitCode, 0, "Copilot did not exit cleanly after stdin EOF"); - assert.equal(signal, null); - assert.equal(fixtureRequests.some(request => request.method !== "GET"), false, "Unexpected model inference request"); - const safeInitialize = JSON.parse(JSON.stringify(result, (key, value) => - key === "command" && typeof value === "string" && value.endsWith("/distribution/copilot") ? "/fixture/verified/copilot" : value)); - const executable = await readFile(join(pack, candidate.path, "copilot")); - process.stdout.write(`${JSON.stringify({ - schema: "paperclip.copilot-provider-pack-smoke/v1", sourceRevision: manifest.payload.runnerSourceRevision, - providerPackDigest: manifest.digest, platform: process.platform, architecture: process.arch, - candidate, executableSha256: `sha256:${createHash("sha256").update(executable).digest("hex")}`, - registryLaunch: "verifyAcpxProfileInstallation/openCommand/spawn", initializeRequestId: 0, - initialize: safeInitialize, missingCredentialPreflight: "COPILOT_AUTH_REQUIRED", cleanExit: true, inheritedCredentials: false, promptSent: false, - networkMode: "COPILOT_OFFLINE=true; loopback metadata-only provider", fixtureRequests, protocolFixtureModel: "gpt-4.1 (not a qualified GitHub model)", costUsd: 0, - qualification: "pending: no credential, entitlement, model execution or Daytona", - }, null, 2)}\n`); -} finally { - if (child && child.exitCode === null && child.signalCode === null) { + child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id: 0, method: "initialize", params: { protocolVersion: 1, clientInfo: { name: "paperclip-pack-offline-smoke", version: "1" }, clientCapabilities: COPILOT_ACP_CLIENT_CAPABILITIES } })}\n`); + const result = await initialized; + assert.equal(result.protocolVersion, 1); + assert.equal(result.agentInfo?.version, "1.0.88"); child.stdin.end(); - child.kill("SIGTERM"); - await within(exited, 5_000); + const timer = setTimeout(() => child.kill("SIGTERM"), 1_000); + const [exitCode, signal] = await within(exited, 10_000); + clearTimeout(timer); + assert.equal(exitCode, 0, "Copilot did not exit cleanly after stdin EOF"); + assert.equal(signal, null); + assert.equal(fixtureRequests.some(request => request.method !== "GET"), false, "Unexpected model inference request"); + const safeInitialize = JSON.parse(JSON.stringify(result, (key, value) => + key === "command" && typeof value === "string" && value.endsWith("/distribution/copilot") ? "/fixture/verified/copilot" : value)); + const executable = await readFile(join(pack, candidate.path, "copilot")); + process.stdout.write(`${JSON.stringify({ + schema: "paperclip.copilot-provider-pack-smoke/v1", sourceRevision: manifest.payload.runnerSourceRevision, + providerPackDigest: manifest.digest, platform: process.platform, architecture: process.arch, + candidate, executableSha256: `sha256:${createHash("sha256").update(executable).digest("hex")}`, + registryLaunch: "verifyAcpxProfileInstallation/openCommand/spawn", initializeRequestId: 0, + initialize: safeInitialize, missingCredentialPreflight: "COPILOT_AUTH_REQUIRED", cleanExit: true, inheritedCredentials: false, promptSent: false, + networkMode: "COPILOT_OFFLINE=true; loopback metadata-only provider", fixtureRequests, protocolFixtureModel: "gpt-4.1 (not a qualified GitHub model)", costUsd: 0, + qualification: "pending: no credential, entitlement, model execution or Daytona", + }, null, 2)}\n`); + } finally { + if (child && child.exitCode === null && child.signalCode === null) { + child.stdin.end(); + child.kill("SIGTERM"); + await within(exited, 5_000); + } } - fixture.closeAllConnections(); - await new Promise(resolve => fixture.close(resolve)); - await lease.close(); - await rm(root, { recursive: true, force: true }); -} +}); async function within(promise, timeoutMs) { 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/src/drivers/acpx/copilot-events.test.ts b/packages/paperclip-runner/src/drivers/acpx/copilot-events.test.ts index 5501bb394c3..96c04dc0a6a 100644 --- a/packages/paperclip-runner/src/drivers/acpx/copilot-events.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/copilot-events.test.ts @@ -6,7 +6,7 @@ const binding = { sessionId: "session-1", turnId: "turn-1" }; const event = (type: string, data: unknown, extra = {}) => ({ method: COPILOT_ACP_EVENT_METHOD, params: { sessionId: "session-1", type, data, ...extra } }); describe("Copilot native event projection", () => { - it("subscribes explicitly and fences events to the active session and turn", () => { + it("subscribes explicitly and requires an active receiver without inventing originating turn", () => { const events = COPILOT_ACP_CLIENT_CAPABILITIES._meta["github.com/copilot"].events; expect(events).toContain("session.workspace_file_changed"); expect(events).not.toContain("assistant.reasoning"); @@ -14,6 +14,13 @@ describe("Copilot native event projection", () => { expect(normalizeCopilotSessionEvent(event("session.idle", {}), { ...binding, turnId: "" })).toBeNull(); expect(normalizeCopilotSessionEvent(event("assistant.reasoning", { text: "private" }), binding)).toBeNull(); }); + it("retains session evidence without treating receipt or provider payload as originating turn", () => { + const delayed = event("assistant.usage", { inputTokens: 10 }, { turnId: "unqualified-provider-field" }); + const earlier = normalizeCopilotSessionEvent(delayed, binding); + const later = normalizeCopilotSessionEvent(delayed, { ...binding, turnId: "next-turn" }); + expect(earlier).toEqual(later); + expect(later).toMatchObject({ sessionId: "session-1", turnId: null, data: { inputTokens: 10 } }); + }); it("preserves subagent attribution and useful metrics while dropping undeclared fields", () => { expect(normalizeCopilotSessionEvent(event("subagent.completed", { toolCallId: "t", agentName: "review", agentDisplayName: "Reviewer", model: "m", totalTokens: 42, cancelled: true, private: "secret" }, { agentId: "child" }), binding)).toMatchObject({ kind: "activity", agentId: "child", data: { model: "m", totalTokens: 42, cancelled: true } }); expect(normalizeCopilotSessionEvent(event("subagent.completed", { private: "secret" }), binding)?.data).not.toHaveProperty("private"); diff --git a/packages/paperclip-runner/src/drivers/acpx/copilot-events.ts b/packages/paperclip-runner/src/drivers/acpx/copilot-events.ts index 044981d5576..563d1f0ade2 100644 --- a/packages/paperclip-runner/src/drivers/acpx/copilot-events.ts +++ b/packages/paperclip-runner/src/drivers/acpx/copilot-events.ts @@ -24,7 +24,8 @@ export interface CopilotSessionEvent { sourceMethod: typeof COPILOT_ACP_EVENT_METHOD; sourceType: string; sessionId: string; - turnId: string; + /** The pinned passthrough does not identify the originating prompt. */ + turnId: null; agentId?: string; timestamp?: string; data: Record; @@ -51,7 +52,7 @@ export function normalizeCopilotSessionEvent( 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: binding.turnId, data: {}, + 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; diff --git a/packages/paperclip-runner/src/drivers/acpx/copilot-extension-adapter.test.ts b/packages/paperclip-runner/src/drivers/acpx/copilot-extension-adapter.test.ts index 9618bfd93f8..df319244fc3 100644 --- a/packages/paperclip-runner/src/drivers/acpx/copilot-extension-adapter.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/copilot-extension-adapter.test.ts @@ -9,31 +9,51 @@ const context = { workspacePath: "/workspace", sessionId: "session-1", turnId: " const params = (type: string, data: unknown, extra = {}) => ({ sessionId: context.sessionId, type, data, ...extra }); describe("Copilot display extension adapter", () => { - it("preserves subagent lifecycle identity and all safe details with canonical provenance", async () => { + it("preserves subagent lifecycle details as session notices without invented turn provenance", async () => { const adapter = createCopilotProfileExtensionAdapter(context); const started = await adapter.notification(COPILOT_ACP_EVENT_METHOD, params("subagent.started", { agentName: "review", agentDisplayName: "Reviewer", toolCallId: "tool-1", agentDescription: "Review the change", model: "exact-model", resumable: true }, { agentId: "agent-2" })); const completed = await adapter.notification(COPILOT_ACP_EVENT_METHOD, params("subagent.completed", { agentName: "review", toolCallId: "tool-1", model: "exact-model", totalToolCalls: 3, durationMs: 12.5, totalTokens: 40, modelSelectionSource: "agent" }, { agentId: "agent-2", timestamp: "2026-09-28T00:00:00Z" })); [...started, ...completed].forEach(validateAcpxRichEvent); - expect(started[0].eventType).toBe("delegation.started"); - expect(completed[0].eventType).toBe("delegation.completed"); - expect(started[0].itemId).toBe(completed[0].itemId); - expect(completed[1].payload).toMatchObject({ - provenance: { method: COPILOT_ACP_EVENT_METHOD, eventType: "subagent.completed", agentId: "agent-2", sessionId: "session-1", turnId: "turn-1", timestamp: "2026-09-28T00:00:00Z" }, - details: expect.arrayContaining([{ name: "totalTokens", value: "40" }, { name: "durationMs", value: "12.5" }, { name: "modelSelectionSource", value: "agent" }]), + expect(started.map(event => event.eventType)).toEqual(["provider.notice.recorded"]); + expect(completed.map(event => event.eventType)).toEqual(["provider.notice.recorded"]); + expect(started[0].itemId).not.toBe(completed[0].itemId); + expect(completed[0].payload).toMatchObject({ + scope: "session", + details: expect.arrayContaining([{ name: "totalTokens", value: "40" }, { name: "durationMs", value: "12.5" }, { name: "modelSelectionSource", value: "agent" }, { name: "source.agentId", value: "agent-2" }, { name: "source.timestamp", value: "2026-09-28T00:00:00Z" }]), }); }); + it("does not assign delayed usage, delegation, or artifact activity to the next receiving turn", async () => { + const next = createCopilotProfileExtensionAdapter({ ...context, turnId: "turn-2" }); + for (const [type, data] of [ + ["assistant.usage", { inputTokens: 42 }], + ["subagent.completed", { toolCallId: "previous-tool", totalTokens: 42 }], + ["session.workspace_file_changed", { path: "previous.md", operation: "create" }], + ["session.compaction_complete", { success: true, preCompactionTokens: 42 }], + ] as const) { + const events = await next.notification(COPILOT_ACP_EVENT_METHOD, params(type, data, { timestamp: "2026-09-28T00:00:00Z" })); + events.forEach(validateAcpxRichEvent); + expect(events.map(event => event.eventType)).toEqual(["provider.notice.recorded"]); + expect(events[0].payload.scope).toBe("session"); + expect(events[0].payload).not.toHaveProperty("provenance"); + expect(events[0].payload.details).toContainEqual({ name: "source.sessionId", value: "session-1" }); + expect(events[0].payload.details).toContainEqual({ name: "turnAttribution", value: "unknown: provider session notification has no originating turn ID" }); + expect(JSON.stringify(events)).not.toContain("turn-2"); + } + }); + it("does not register provider-session paths or binary assets as task artifacts", async () => { const adapter = createCopilotProfileExtensionAdapter(context); const file = await adapter.notification(COPILOT_ACP_EVENT_METHOD, params("session.workspace_file_changed", { operation: "create", path: "reports/result.md" })); file.forEach(validateAcpxRichEvent); - expect(file[0].payload).toMatchObject({ registered: false, reference: null }); - expect(file[1].payload.details).toEqual(expect.arrayContaining([{ name: "path", value: "reports/result.md" }, { name: "locationKind", value: "provider_session_workspace" }])); + expect(file.map(event => event.eventType)).toEqual(["provider.notice.recorded"]); + expect(file[0].payload).toMatchObject({ scope: "session" }); + expect(file[0].payload.details).toEqual(expect.arrayContaining([{ name: "path", value: "reports/result.md" }, { name: "locationKind", value: "provider_session_workspace" }])); expect(await adapter.notification(COPILOT_ACP_EVENT_METHOD, params("session.workspace_file_changed", { operation: "create", path: "../../secret" }))).toEqual([]); const bytes = Buffer.from("image fixture"); const asset = await adapter.notification(COPILOT_ACP_EVENT_METHOD, params("session.binary_asset", { assetId: `sha256:${createHash("sha256").update(bytes).digest("hex")}`, type: "image", mimeType: "image/png", byteLength: bytes.length, data: bytes.toString("base64") })); asset.forEach(validateAcpxRichEvent); - expect(asset[0].payload).toMatchObject({ mediaType: "image/png", reference: null, registered: false }); + expect(asset[0].payload.details).toContainEqual({ name: "mimeType", value: "image/png" }); expect(JSON.stringify(asset)).not.toContain(bytes.toString("base64")); }); @@ -50,7 +70,7 @@ describe("Copilot display extension adapter", () => { const events = await createCopilotProfileExtensionAdapter(context).notification(COPILOT_ACP_EVENT_METHOD, params("subagent.failed", { agentName: "review", totalTokens: 42, error: "Authorization: Bearer secretsecretsecret", model: "ghp_abcdefghijklmnopqrstuvwxyz" })); events.forEach(validateAcpxRichEvent); expect(JSON.stringify(events)).not.toMatch(/secretsecretsecret|ghp_abcdefghijklmnopqrstuvwxyz/); - expect(events[1].payload.details).toContainEqual({ name: "totalTokens", value: "42" }); + expect(events[0].payload.details).toContainEqual({ name: "totalTokens", value: "42" }); }); it("reports native unsupported input honestly and ignores unrelated or cross-session notifications", async () => { @@ -69,7 +89,7 @@ describe("Copilot display extension adapter", () => { // field list, so a future projected field cannot bypass keyed redaction. const normalize = vi.spyOn(copilotEvents, "normalizeCopilotSessionEvent").mockReturnValueOnce({ kind: "usage", sourceMethod: COPILOT_ACP_EVENT_METHOD, sourceType: "assistant.usage", - sessionId: context.sessionId, turnId: context.turnId, + sessionId: context.sessionId, turnId: null, data: { connectionString: "plain-credential-value", credentials: { endpoint: "opaque-value" }, inputTokens: 42 }, }); try { @@ -84,11 +104,12 @@ describe("Copilot display extension adapter", () => { } finally { normalize.mockRestore(); } }); - it("emits compaction completion only after provider-reported success and keeps settlement notices nonterminal", async () => { + it("preserves compaction success and failure as session notices and keeps settlement nonterminal", async () => { const adapter = createCopilotProfileExtensionAdapter(context); const success = await adapter.notification(COPILOT_ACP_EVENT_METHOD, params("session.compaction_complete", { success: true, preCompactionTokens: 100, postCompactionTokens: 40, checkpointNumber: 1 })); success.forEach(validateAcpxRichEvent); - expect(success[0]).toMatchObject({ eventType: "context.compacted", payload: { preTokens: 100, postTokens: 40, sameSession: true } }); + expect(success.map(event => event.eventType)).toEqual(["provider.notice.recorded"]); + expect(success[0].payload.details).toEqual(expect.arrayContaining([{ name: "preCompactionTokens", value: "100" }, { name: "postCompactionTokens", value: "40" }, { name: "success", value: "true" }])); const failure = await adapter.notification(COPILOT_ACP_EVENT_METHOD, params("session.compaction_complete", { success: false })); expect(failure.map(event => event.eventType)).toEqual(["provider.notice.recorded"]); const idle = await adapter.notification(COPILOT_ACP_EVENT_METHOD, params("session.idle", {})); diff --git a/packages/paperclip-runner/src/drivers/acpx/copilot-extension-adapter.ts b/packages/paperclip-runner/src/drivers/acpx/copilot-extension-adapter.ts index 35019e00468..88c9cca1f27 100644 --- a/packages/paperclip-runner/src/drivers/acpx/copilot-extension-adapter.ts +++ b/packages/paperclip-runner/src/drivers/acpx/copilot-extension-adapter.ts @@ -16,71 +16,34 @@ export function createCopilotProfileExtensionAdapter(context: AcpxProfileExtensi const event = normalizeCopilotSessionEvent({ method, params }, context); if (!event) return []; const noticeId = identity(context, "notice", String(++sequence)); - const details = detailFields(event.data); + // 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: "turn", + category: `copilot.${event.sourceType}`, scope: "session", recoverable: true, userActionable: false, summary: summary(event), - provenance: { - method, eventType: event.sourceType, sessionId: bounded(context.sessionId, 240), turnId: bounded(context.turnId, 240), - ...(event.agentId ? { agentId: bounded(event.agentId, 240) } : {}), - ...(event.timestamp ? { timestamp: bounded(event.timestamp, 80) } : {}), - }, details, }, }; - const typed = typedProjection(event, context, noticeId); - return typed ? [typed, notice] : [notice]; + // 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 typedProjection(event: CopilotSessionEvent, context: AcpxProfileExtensionContext, fallbackId: string): CanonicalProviderEvent | null { - const data = event.data; - if (event.kind === "capability_gap") return null; - if (event.sourceType.startsWith("subagent.")) { - const correlation = event.agentId ?? string(data.toolCallId); - const itemId = correlation ? identity(context, "delegation", correlation) : fallbackId; - const status = data.cancelled === true ? "interrupted" - : event.sourceType === "subagent.completed" ? "completed" - : event.sourceType === "subagent.failed" ? "failed" : "running"; - return { - itemId, - eventType: status === "running" ? (event.sourceType === "subagent.started" ? "delegation.started" : "delegation.updated") : "delegation.completed", - payload: { - schema: "paperclip.delegation.v1", delegationId: itemId, action: "spawn", status, - children: [{ - childId: itemId, role: optional(data.agentDisplayName ?? data.agentName ?? data.agentType, 160), - model: optional(data.model, 240), status, - summary: optional(data.agentDescription ?? data.error, 4000), - activitySummary: summary(event), - }], - }, - }; - } - if (event.sourceType === "session.compaction_complete" && data.success === true) { - const itemId = identity(context, "compaction", String(data.checkpointNumber ?? fallbackId)); - return { itemId, eventType: "context.compacted", payload: { - schema: "paperclip.context.compacted.v1", compactionId: itemId, reason: "provider", - preTokens: nonnegativeInteger(data.preCompactionTokens), postTokens: nonnegativeInteger(data.postCompactionTokens), sameSession: true, - } }; - } - if (event.kind === "artifact_reference") { - const itemId = identity(context, "artifact", string(data.assetId) || string(data.path) || fallbackId); - return { itemId, eventType: "artifact.generated", payload: { - schema: "paperclip.artifact.generated.v1", artifactId: itemId, status: "completed", - // Provider-session paths are not task-workspace paths or registered URLs. - reference: null, mediaType: optional(data.mimeType, 160), registered: false, failure: null, - } }; - } - return null; -} - function summary(event: CopilotSessionEvent): string { const data = event.data; if (event.kind === "capability_gap") return data.reason === "provider_omitted_event_data" @@ -134,6 +97,3 @@ function bounded(value: string, max: number): string { const safe = String(redactPaperclipSemanticValue(value)); return safe.length <= max ? safe : `${safe.slice(0, max - 12)} [truncated]`; } -function optional(value: unknown, max: number): string | null { return typeof value === "string" && value ? bounded(value, max) : null; } -function string(value: unknown): string { return typeof value === "string" ? value : ""; } -function nonnegativeInteger(value: unknown): number | null { return Number.isSafeInteger(value) && Number(value) >= 0 ? Number(value) : null; } diff --git a/packages/paperclip-runner/src/drivers/acpx/copilot-registry.test.ts b/packages/paperclip-runner/src/drivers/acpx/copilot-registry.test.ts index b1cbd6e4f16..a2fb584f5c2 100644 --- a/packages/paperclip-runner/src/drivers/acpx/copilot-registry.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/copilot-registry.test.ts @@ -50,14 +50,17 @@ describe("Copilot provider registry conformance", () => { binder.onExtensionNotification(COPILOT_ACP_EVENT_METHOD, { sessionId: context.sessionId, type: "subagent.completed", data, agentId: "agent-2", timestamp: "2026-09-28T00:00:00Z" }); await binder.drain(); - expect(emitted.map(event => event.eventType)).toEqual(["delegation.completed", "provider.notice.recorded"]); - expect(emitted[0]!.payload).toMatchObject({ schema: "paperclip.delegation.v1", action: "spawn", status: "completed", - children: [{ role: "Reviewer", model: "exact-model", status: "completed", summary: "Review the change" }] }); - expect(emitted[1]!.payload).toMatchObject({ summary: "Copilot subagent completed.", provenance: { - method: COPILOT_ACP_EVENT_METHOD, eventType: "subagent.completed", agentId: "agent-2", - sessionId: "backend-1", turnId: "turn-1", timestamp: "2026-09-28T00:00:00Z", - } }); - expect(emitted[1]!.payload.details).toEqual(Object.entries(data).map(([name, value]) => ({ name, value: String(value) }))); + expect(emitted.map(event => event.eventType)).toEqual(["provider.notice.recorded"]); + expect(emitted[0]!.payload).toMatchObject({ summary: "Copilot subagent completed.", details: expect.arrayContaining([ + { name: "source.method", value: COPILOT_ACP_EVENT_METHOD }, + { name: "source.eventType", value: "subagent.completed" }, + { name: "source.agentId", value: "agent-2" }, + { name: "source.sessionId", value: "backend-1" }, + { name: "source.timestamp", value: "2026-09-28T00:00:00Z" }, + ]) }); + expect(emitted[0]!.payload.scope).toBe("session"); + expect(emitted[0]!.payload).not.toHaveProperty("provenance"); + expect(emitted[0]!.payload.details).toEqual(expect.arrayContaining(Object.entries(data).map(([name, value]) => ({ name, value: String(value) })))); }); it.each(["wrong_session", "stale_turn"])("rejects %s events at the shared boundary before presentation", async scenario => { diff --git a/packages/paperclip-runner/src/drivers/acpx/cursor-extensions.test.ts b/packages/paperclip-runner/src/drivers/acpx/cursor-extensions.test.ts index 3aae9725bc4..b5b3560ae55 100644 --- a/packages/paperclip-runner/src/drivers/acpx/cursor-extensions.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/cursor-extensions.test.ts @@ -2,6 +2,7 @@ import { mkdtemp, mkdir, rm, symlink, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, describe, expect, it } from "vitest"; +import { validateAcpxRichEvent } from "./profile-extensions.js"; import { PAPERCLIP_QUESTION_RESPONSE_SCHEMA } from "../../contracts/question-set.js"; import { createCursorNotificationNormalizer, createCursorProfileExtensionAdapter, createCursorSubagentNormalizer, cursorWorkspaceArtifactReference, @@ -144,6 +145,20 @@ describe("Cursor active-turn extension adapter", () => { await expect(createCursorProfileExtensionAdapter({ ...context, turnId: "next" }).notification("cursor/subagent_update", { sessionId: "parent", update: state })).rejects.toThrow("no spawn"); }); + it.each(["😀".repeat(2_500), "😀".repeat(5_000), "漢😀".repeat(2_000)])("bounds Unicode child activity for UTF-16 consumers without splitting code points (%#)", async message => { + const adapter = createCursorProfileExtensionAdapter({ workspacePath: await workspace(), sessionId: "parent", turnId: "turn" }); + await adapter.notification("cursor/subagent_update", { sessionId: "parent", update: { sessionUpdate: "subagent_spawned", subagentSessionId: "child", name: "Explore", task: "", _meta: { cursor: { toolCallId: "task", agentId: "agent" } } } }); + const events = await adapter.notification("cursor/subagent_update", { sessionId: "parent", childSessionId: "child", update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text: message } } }); + const event = events[0]!; + expect(() => validateAcpxRichEvent(event)).not.toThrow(); + const summary = (event.payload.children as { activitySummary: string }[])[0]!.activitySummary; + expect(summary.length).toBeLessThanOrEqual(4_000); + expect(summary.isWellFormed()).toBe(true); + expect(summary).toMatch(/^\[Earlier child activity omitted\]\n/); + const tail = summary.slice("[Earlier child activity omitted]\n".length); + expect(message.endsWith(tail)).toBe(true); + }); + it("attributes nested child transcripts, reports partial tool detail, and settles disconnected children honestly", async () => { const adapter = createCursorProfileExtensionAdapter({ workspacePath: await workspace(), sessionId: "parent", turnId: "turn" }); const child = { sessionUpdate: "subagent_spawned", subagentSessionId: "child", name: "Explore", task: "", _meta: { cursor: { toolCallId: "task", agentId: "agent" } } }; diff --git a/packages/paperclip-runner/src/drivers/acpx/cursor-extensions.ts b/packages/paperclip-runner/src/drivers/acpx/cursor-extensions.ts index d28ad4168f2..8516cb28b66 100644 --- a/packages/paperclip-runner/src/drivers/acpx/cursor-extensions.ts +++ b/packages/paperclip-runner/src/drivers/acpx/cursor-extensions.ts @@ -369,8 +369,20 @@ function cursorChildActivitySummary(update: Record): { text: st } function boundedChildActivity(text: string): string { + if (text.length <= 4_000) return text; + const prefix = "[Earlier child activity omitted]\n"; const points = Array.from(text); - return points.length <= 4_000 ? text : `[Earlier child activity omitted]\n${points.slice(-3_960).join("")}`; + const tail: string[] = []; + let length = prefix.length; + // Bound both UTF-16 consumers and the schema's Unicode code-point count. + // Keep each complete code point when retaining the most recent activity. + for (let index = points.length - 1; index >= 0; index -= 1) { + const point = points[index]!; + if (length + point.length > 4_000) break; + tail.push(point); + length += point.length; + } + return prefix + tail.reverse().join(""); } /** Preserve identity across delta state updates; use a fresh reducer per turn. */