mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-01 09:39:53 +01:00
feat(runner): retain bounded Copilot tool evidence
Project active-turn native tool and permission observations through canonical notices. Redact values, reject ambiguous correlation, and preserve authoritative outcomes if observation fails. Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
76672efbeb
commit
f939d369e6
5 files changed
+556
-4
No files matched your search
@@ -4,6 +4,7 @@ import { fileURLToPath } from "node:url";
|
||||
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { deliverAcpxResponse } from "../drivers/acpx/response-delivery.js";
|
||||
import { normalizeAcpxPermission } from "../drivers/acpx/acp-permission-adapter.js";
|
||||
import { ACPX_CAPABILITY_PROFILES } from "../drivers/acpx/capability-profiles.js";
|
||||
import { resolveQualifiedAcpxProfile } from "../drivers/acpx/qualified-profiles.js";
|
||||
@@ -44,7 +45,7 @@ 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) { ${source.slice(start, end)}`)(
|
||||
return async function(activeTurnId, request, context, toolEvidence) { ${source.slice(start, end)}`)(
|
||||
permissions, { agent }, normalizeAcpxPermission, (_event: string, payload: { choices: Array<{ key: string }> }) => emitted.push(payload),
|
||||
);
|
||||
const abort = new AbortController();
|
||||
@@ -57,6 +58,26 @@ describe("qualified ACPX runtime sidecar", () => {
|
||||
await expect(pending).resolves.toEqual({ outcome: "cancel" });
|
||||
expect(permissions.size).toBe(0);
|
||||
});
|
||||
it("emits permission delivery evidence only after the actual response write settles", async () => {
|
||||
const source = readFileSync(new URL("./acpx-runtime-sidecar.ts", import.meta.url), "utf8");
|
||||
const start = source.indexOf(' const requestId = boundedIdentity', source.indexOf('if (request.command === "permission.resolve")'));
|
||||
const end = source.indexOf('\n if (request.command === "input.resolve")', start);
|
||||
const execute = new Function("permissions", "deliverAcpxResponse", "parseHarnessRuntimeRequestResolution", `
|
||||
const turnId = "turn"; const boundedIdentity = x => x;
|
||||
return async function(request) { ${source.slice(start, end)}
|
||||
`);
|
||||
for (const reject of [false, true]) {
|
||||
let resolve!: () => void, fail!: (error: Error) => void;
|
||||
const delivery = new Promise<void>((r, j) => { resolve = r; fail = j; });
|
||||
const deliveredEvidence = vi.fn(), settle = vi.fn();
|
||||
const permissions = new Map([["request", { turnId: "turn", normalized: { resolve: () => ({ outcome: "reject_once" }) }, cleanup() {}, settle, responseDelivery: delivery, deliveredEvidence }]]);
|
||||
const run = execute(permissions, deliverAcpxResponse, () => ({ action: "decline" }))({ params: { requestId: "request", turnId: "turn" } });
|
||||
expect(settle).toHaveBeenCalledWith({ outcome: "reject_once" });
|
||||
expect(deliveredEvidence).not.toHaveBeenCalled();
|
||||
if (reject) { fail(new Error("write failed")); await expect(run).rejects.toThrow("write failed"); expect(deliveredEvidence).not.toHaveBeenCalled(); }
|
||||
else { resolve(); await expect(run).resolves.toEqual({ resolved: true }); expect(deliveredEvidence).toHaveBeenCalledExactlyOnceWith("reject_once"); }
|
||||
}
|
||||
});
|
||||
it("preserves ACP input presence through the bounded sidecar handoff", () => {
|
||||
const source = readFileSync(
|
||||
fileURLToPath(new URL("./acpx-runtime-sidecar.ts", import.meta.url)),
|
||||
|
||||
@@ -61,6 +61,7 @@ import {
|
||||
type AcpxSidecarResponse,
|
||||
} from "../drivers/acpx/sidecar-protocol.js";
|
||||
import { safeAcpxLocations } from "./acpx-sidecar-locations.js";
|
||||
import { createCopilotToolEvidence, type CopilotToolEvidence } from "./copilot-tool-evidence.js";
|
||||
import {
|
||||
persistedAcpxTurnUsage,
|
||||
acpxUsageEstimateNotice,
|
||||
@@ -136,6 +137,7 @@ interface PendingPermission {
|
||||
turnId: string;
|
||||
responseDelivery: Promise<void>;
|
||||
normalized: NormalizedAcpxPermission;
|
||||
deliveredEvidence?: (outcome: string) => void;
|
||||
settle(response: AcpPermissionDecision): void;
|
||||
cleanup(): void;
|
||||
}
|
||||
@@ -366,6 +368,13 @@ async function dispatch(
|
||||
waitForInput: (input, context) => waitForExtensionInput(currentTurnId, input, context),
|
||||
emit: event => emit("runtime.rich_event", { ...event }, currentTurnId),
|
||||
});
|
||||
const toolEvidence = openParams!.agent === "copilot" ? createCopilotToolEvidence({
|
||||
sessionId: activeHost.identity().backendSessionId, turnId: currentTurnId,
|
||||
workingDirectory: openParams!.workingDirectory,
|
||||
active: () => turnId === currentTurnId && host === activeHost,
|
||||
emit: event => { validateAcpxRichEvent(event); emit("runtime.rich_event", { ...event }, currentTurnId); },
|
||||
unavailable: () => diagnostic("copilot_evidence_unavailable", "Copilot tool evidence is incomplete; permission and terminal outcomes are unchanged."),
|
||||
}) : undefined;
|
||||
let usageBefore: unknown;
|
||||
try {
|
||||
usageBefore = await readSidecarHostStatusWithin(activeHost);
|
||||
@@ -377,13 +386,13 @@ async function dispatch(
|
||||
onElicitation: (providerRequest, context) =>
|
||||
waitForInput(currentTurnId, providerRequest, context),
|
||||
onPermissionRequest: (providerRequest, context) =>
|
||||
waitForPermission(currentTurnId, providerRequest, context),
|
||||
waitForPermission(currentTurnId, providerRequest, context, toolEvidence),
|
||||
});
|
||||
} catch (error) {
|
||||
turnId = null;
|
||||
throw error;
|
||||
}
|
||||
void pumpTurn(currentTurnId, runtimeTurn, activeHost, usageBefore, extensions.drain);
|
||||
void pumpTurn(currentTurnId, runtimeTurn, activeHost, usageBefore, extensions.drain, toolEvidence);
|
||||
// Warm sessions may defer initialize until their first prompt. Publish only
|
||||
// the capabilities of that live initialized connection, never old disk state.
|
||||
await runtimeTurn.promptStarted;
|
||||
@@ -427,7 +436,9 @@ async function dispatch(
|
||||
const decision = pending.normalized.resolve(resolution);
|
||||
if (!permissions.delete(requestId)) throw new Error("permission request lost its settlement race");
|
||||
pending.cleanup();
|
||||
return await deliverAcpxResponse(pending.responseDelivery, () => pending.settle(decision));
|
||||
const receipt = await deliverAcpxResponse(pending.responseDelivery, () => pending.settle(decision));
|
||||
pending.deliveredEvidence?.(decision.outcome);
|
||||
return receipt;
|
||||
}
|
||||
if (request.command === "input.resolve") {
|
||||
const requestId = boundedIdentity(request.params.requestId, "requestId");
|
||||
@@ -589,6 +600,7 @@ async function pumpTurn(
|
||||
activeHost: AcpxRuntimeHost,
|
||||
usageBefore: unknown,
|
||||
drainExtensions: () => Promise<void>,
|
||||
toolEvidence?: CopilotToolEvidence,
|
||||
): Promise<void> {
|
||||
let terminal: Record<string, unknown>;
|
||||
try {
|
||||
@@ -599,6 +611,7 @@ async function pumpTurn(
|
||||
const normalizeMessage = initializedAgent === "grok"
|
||||
? createGrokMessageNormalizer<AcpRuntimeEvent>() : (event: AcpRuntimeEvent) => event;
|
||||
for await (const event of runtimeTurn.events) {
|
||||
toolEvidence?.tool(event);
|
||||
emit(
|
||||
"runtime.event",
|
||||
sanitizeRuntimeEvent(
|
||||
@@ -740,6 +753,7 @@ async function waitForPermission(
|
||||
activeTurnId: string,
|
||||
request: AcpPermissionRequest,
|
||||
context: { signal: AbortSignal; responseDelivery?: Promise<void> },
|
||||
toolEvidence?: CopilotToolEvidence,
|
||||
): Promise<AcpPermissionDecision> {
|
||||
const { signal } = context;
|
||||
if (turnId !== activeTurnId || signal.aborted || permissions.size >= MAX_PENDING_INPUTS) {
|
||||
@@ -756,6 +770,7 @@ async function waitForPermission(
|
||||
};
|
||||
permissions.set(requestId, {
|
||||
turnId: activeTurnId, normalized, settle, responseDelivery,
|
||||
deliveredEvidence: toolEvidence?.permission(request, requestId, normalized.choices.map(choice => choice.key)),
|
||||
cleanup: () => signal.removeEventListener("abort", abort),
|
||||
});
|
||||
signal.addEventListener("abort", abort, { once: true });
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { validateAcpxRichEvent } from "../drivers/acpx/profile-extensions.js";
|
||||
import type { CanonicalProviderEvent } from "../provider-events.js";
|
||||
import { createCopilotToolEvidence } from "./copilot-tool-evidence.js";
|
||||
const fixture = JSON.parse(readFileSync(new URL("./fixtures/copilot-tool-evidence.json", import.meta.url), "utf8"));
|
||||
const details = (e: CanonicalProviderEvent) => Object.fromEntries((e.payload.details as Array<{ name: string; value: string }>).map(d => [d.name, d.value]));
|
||||
function harness(sessionId = "session") {
|
||||
const events: CanonicalProviderEvent[] = []; let active = true;
|
||||
const projector = createCopilotToolEvidence({ sessionId, turnId: "turn", workingDirectory: "/fixture/workspace", active: () => active,
|
||||
emit: event => { validateAcpxRichEvent(event); events.push(event); } });
|
||||
return { projector, events, stop: () => { active = false; } };
|
||||
}
|
||||
const tool = (id: string, rawInput: unknown, kind = "execute") => ({ type: "tool_call", tag: "tool_call", toolCallId: id, kind, status: "pending", rawInput });
|
||||
const update = (id: string, content: string) => ({ type: "tool_call", tag: "tool_call_update", toolCallId: id, status: "completed", rawOutput: { content } });
|
||||
function replay(name: string) {
|
||||
const frames = fixture[name]; const h = harness(frames[0].params.sessionId);
|
||||
for (const frame of frames) {
|
||||
if (frame.method === "session/update") { const u = frame.params.update; h.projector.tool({ ...u, type: "tool_call", tag: u.sessionUpdate }); }
|
||||
else h.projector.permission({ raw: frame.params }, "request-0", ["accept", "decline", "cancel"])?.(name === "deny-write" ? "reject_once" : "allow_once");
|
||||
}
|
||||
return h;
|
||||
}
|
||||
describe("Copilot active-turn tool evidence", () => {
|
||||
it("projects actual denied-create wire into canonical notices without file contents/diff", () => {
|
||||
const { events } = replay("deny-write");
|
||||
expect(events.map(details)).toEqual([
|
||||
{ stage: "tool", toolCallId: "fixture-tool", target: "copilot-denied-nonce.txt", operation: "edit", status: "pending" },
|
||||
{ stage: "permission_requested", toolCallId: "fixture-tool", requestId: "request-0", target: "copilot-denied-nonce.txt", operation: "edit", declineOffered: "true" },
|
||||
{ stage: "permission_delivered", toolCallId: "fixture-tool", requestId: "request-0", target: "copilot-denied-nonce.txt", operation: "edit", declineOffered: "true", outcome: "reject_once" },
|
||||
{ stage: "tool", toolCallId: "fixture-tool", target: "copilot-denied-nonce.txt", operation: "edit", status: "failed" },
|
||||
]);
|
||||
expect(JSON.stringify(events)).not.toMatch(/MUST NOT EXIST|diff --git|file_text/);
|
||||
expect(events.every(e => e.payload.scope === "turn" && (e.payload.provenance as { turnId: string }).turnId === "turn")).toBe(true);
|
||||
});
|
||||
it("links actual attached command and separate read-shell completion, not initial completed tool", () => {
|
||||
const ds = replay("attached-shell").events.map(details);
|
||||
const started = ds.find(d => d.shellState === "started")!; const completed = ds.find(d => d.shellState === "completed")!;
|
||||
expect(started).toMatchObject({ operation: "execute", mode: "async", detach: "false", shellId: "0", commandToolCallId: "fixture-tool", status: "completed" });
|
||||
expect(started).not.toHaveProperty("exitCode");
|
||||
expect(completed).toMatchObject({ commandToolCallId: "fixture-tool", shellId: "0", exitCode: "0", status: "completed" });
|
||||
expect(completed.toolCallId).not.toBe(started.toolCallId);
|
||||
expect(started.commandSha256).toBe(`sha256:${createHash("sha256").update("sleep 2; printf ACP_SHELL_DONE > settlement.txt").digest("hex")}`);
|
||||
expect(JSON.stringify(ds)).not.toContain("sleep 2");
|
||||
});
|
||||
it.each(["../outside", "/outside", "bad\u0000path", "C:\\private", "https://secret.invalid/path"])("omits unsafe target %j", path => {
|
||||
const h = harness(); h.projector.tool(tool("edit", { path, file_text: "SECRET" }, "edit"));
|
||||
expect(details(h.events[0]!)).not.toHaveProperty("target"); expect(JSON.stringify(h.events)).not.toContain("SECRET");
|
||||
});
|
||||
it("omits conflicting locations instead of selecting one", () => {
|
||||
const h = harness(); h.projector.tool({ ...tool("edit", { path: "a" }, "edit"), locations: [{ path: "b" }] });
|
||||
expect(details(h.events[0]!)).not.toHaveProperty("target");
|
||||
});
|
||||
it("rejects session notifications, stale binding, foreign permission session and originless deltas", () => {
|
||||
const h = harness(); h.projector.tool({ method: "github.com/copilot/sessionEvent", params: { type: "session.background_tasks_changed" } });
|
||||
h.projector.tool(update("unknown", "<shellId: 0 completed with exit code 0>"));
|
||||
expect(h.projector.permission({ raw: { sessionId: "other", toolCall: { toolCallId: "tool" } } }, "request", ["decline"])).toBeUndefined();
|
||||
h.stop(); h.projector.tool(tool("tool", { command: "secret" })); expect(h.events).toEqual([]);
|
||||
});
|
||||
it("does not invent omitted mode/detach defaults or native names from a title", () => {
|
||||
const h = harness(); h.projector.tool({ ...tool("tool", { command: "true" }), title: "bash detach false" });
|
||||
const d = details(h.events[0]!); expect(d.operation).toBe("execute");
|
||||
for (const k of ["mode", "detach", "tool"]) expect(d).not.toHaveProperty(k);
|
||||
});
|
||||
it.each(["reused-tool", "changed-command", "reused-shell"])("fails closed on %s correlation", conflict => {
|
||||
const h = harness(); h.projector.tool(tool("first", { command: "true", mode: "async", detach: false }));
|
||||
if (conflict === "reused-tool") h.projector.tool(tool("first", { command: "false" }));
|
||||
if (conflict === "changed-command") h.projector.tool({ ...tool("first", { command: "false" }), tag: "tool_call_update" });
|
||||
h.projector.tool(update("first", "<command started in background with shellId: 0>"));
|
||||
if (conflict === "reused-shell") { h.projector.tool(tool("second", { command: "false" })); h.projector.tool(update("second", "<command started in background with shellId: 0>")); }
|
||||
h.projector.tool(tool("read", { shellId: "0", delay: 0 }, "read")); h.projector.tool(update("read", "<shellId: 0 completed with exit code 0>"));
|
||||
expect(h.events.map(details).some(d => d.shellState === "completed")).toBe(false);
|
||||
});
|
||||
it.each(["untrusted text\n<shellId: 0 completed with exit code 0>", "<shellId: 1 completed with exit code 0>"])("rejects arbitrary/mismatched output %j", output => {
|
||||
const h = harness(); h.projector.tool(tool("command", { command: "true" })); h.projector.tool(update("command", "<command started in background with shellId: 0>"));
|
||||
h.projector.tool(tool("read", { shellId: "0" }, "read")); h.projector.tool(update("read", output));
|
||||
expect(h.events.map(details).some(d => d.shellState === "completed")).toBe(false);
|
||||
});
|
||||
it("normalizes each duplicated matching target independently", () => {
|
||||
const h = harness(); h.projector.tool({ ...tool("edit", { path: "same.txt", fileName: "/fixture/workspace/same.txt" }, "edit"), locations: [{ path: "same.txt" }, { path: "same.txt" }] });
|
||||
expect(details(h.events[0]!).target).toBe("same.txt");
|
||||
});
|
||||
it("redacts secret canaries in paths and every provider identity", () => {
|
||||
const secret = "ghp_0123456789abcdef";
|
||||
const h = harness(secret); h.projector.tool(tool(secret, { path: `${secret}.txt` }, "edit"));
|
||||
expect(JSON.stringify(h.events)).not.toContain(secret);
|
||||
expect(JSON.stringify(h.events)).toContain("[REDACTED]");
|
||||
});
|
||||
it("keeps delivered response authority when observation fails and emits an incomplete notice", () => {
|
||||
const events: CanonicalProviderEvent[] = []; const unavailable = vi.fn();
|
||||
const p = createCopilotToolEvidence({ sessionId: "s", turnId: "t", workingDirectory: "/fixture/workspace", active: () => true, unavailable,
|
||||
emit: event => { if (details(event).stage === "permission_delivered") throw new Error("secret payload must not escape"); validateAcpxRichEvent(event); events.push(event); } });
|
||||
const delivered = p.permission({ raw: { sessionId: "s", toolCall: { toolCallId: "call", kind: "edit", rawInput: { fileName: "a" } } } }, "request", ["decline"]);
|
||||
expect(() => delivered!("reject_once")).not.toThrow();
|
||||
expect(events.map(details).at(-1)).toMatchObject({ stage: "evidence_incomplete", reason: "projection_failed" });
|
||||
expect(unavailable).toHaveBeenCalledOnce();
|
||||
expect(JSON.stringify(events)).not.toContain("secret payload");
|
||||
p.tool(tool("later", { command: "true" })); expect(events).toHaveLength(2);
|
||||
});
|
||||
it("handles malformed bounded input without leaking arbitrary data", () => {
|
||||
const h = harness();
|
||||
for (const rawInput of [null, [], { command: "x".repeat(65537) }, { mode: {}, detach: "false", shellId: {} }]) h.projector.tool(tool(String(h.events.length), rawInput));
|
||||
expect(h.events).toHaveLength(4);
|
||||
expect(h.events.map(details).every(d => !d.commandSha256 && !d.mode && !d.detach && !d.shellId)).toBe(true);
|
||||
});
|
||||
it("bounds retained tools and emitted notices", () => {
|
||||
const h = harness(); for (let n = 0; n < 300; n++) h.projector.tool(tool(`t${n}`, { command: "true" })); expect(h.events).toHaveLength(257);
|
||||
expect(details(h.events.at(-1)!)).toMatchObject({ stage: "evidence_incomplete", reason: "tool_limit" });
|
||||
for (let n = 0; n < 2200; n++) h.projector.tool(update("t0", "")); expect(h.events).toHaveLength(2048);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,163 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { redactPaperclipSemanticValue } from "../semantic-tools/redaction.js";
|
||||
import type { CanonicalProviderEvent } from "../provider-events.js";
|
||||
import { safeAcpxLocations } from "./acpx-sidecar-locations.js";
|
||||
|
||||
const LIMIT = 256;
|
||||
const CATEGORY = "copilot_tool_evidence_v1";
|
||||
type Fields = Record<string, string | number | boolean>;
|
||||
interface Tool { kind?: string; input?: string; fields: Fields; invalid?: boolean }
|
||||
const record = (v: unknown): Record<string, unknown> => v !== null && typeof v === "object" && !Array.isArray(v) ? v as Record<string, unknown> : {};
|
||||
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<string, Tool>();
|
||||
const shells = new Map<string, string | null>();
|
||||
const permissionTools = new Set<string>();
|
||||
let sequence = 0;
|
||||
let incomplete = false;
|
||||
let broken = false;
|
||||
function safely<T>(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, fields: Fields, method = "session/update") {
|
||||
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: CATEGORY, scope: "turn", recoverable: true, userActionable: false,
|
||||
summary: 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, ...fields }).map(([name, value]) => ({ name, value: String(value) })),
|
||||
}) as Record<string, unknown> });
|
||||
}
|
||||
function target(call: Record<string, unknown>): string | undefined {
|
||||
const input = record(call.rawInput);
|
||||
if (Array.isArray(call.locations) && call.locations.length > 16) return;
|
||||
const paths = [input.path, input.fileName, ...(Array.isArray(call.locations) ? call.locations.slice(0, 16).map(x => record(x).path) : [])].filter(x => x !== undefined);
|
||||
if (!paths.length || paths.some(x => typeof x !== "string" || x.length > 2048 || /[\u0000-\u001f\u007f\\]/u.test(x))) return;
|
||||
const safe = paths.flatMap(path => safeAcpxLocations([{ path }], binding.workingDirectory, call.kind, call.title));
|
||||
const names = safe.map(x => x.path).filter((x): x is string => typeof x === "string" && x.length <= 1024 && !x.includes(":"));
|
||||
if (names.length !== paths.length || new Set(names).size !== 1) return;
|
||||
return names[0];
|
||||
}
|
||||
function inputFields(call: Record<string, unknown>): Fields {
|
||||
const input = record(call.rawInput);
|
||||
const fields: Fields = {};
|
||||
if (call.kind === "edit") { const path = target(call); 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 (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 (call.rawInput !== undefined) {
|
||||
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 };
|
||||
if (state.kind === "edit") fields.operation = "edit";
|
||||
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 = /^<command started in background with shellId: ([A-Za-z0-9_.-]{1,80})>$/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 = /^<shellId: ([A-Za-z0-9_.-]{1,80}) completed with exit code (-?\d{1,10})>$/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;
|
||||
}
|
||||
}
|
||||
}
|
||||
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") fields.operation = "edit";
|
||||
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 {
|
||||
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<typeof createCopilotToolEvidence>;
|
||||
@@ -0,0 +1,241 @@
|
||||
{
|
||||
"provider": "@github/copilot@1.0.88",
|
||||
"executableSha256": "a9ff8babb10b7e443182ae96a8bc50a9c826ef1c773e1344c396eb5bf7f512c3",
|
||||
"source": "Credential-free native binary with loopback synthetic model; no provider inference. Workspace paths normalized by probe.",
|
||||
"deny-write": [
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "session/update",
|
||||
"params": {
|
||||
"sessionId": "21c800ed-2229-48f8-b13a-68e711944863",
|
||||
"update": {
|
||||
"sessionUpdate": "tool_call",
|
||||
"toolCallId": "fixture-tool",
|
||||
"title": "Creating ...pilot-offline-2khr_xkr/copilot-denied-nonce.txt",
|
||||
"kind": "edit",
|
||||
"status": "pending",
|
||||
"rawInput": {
|
||||
"path": "/fixture/workspace/copilot-denied-nonce.txt",
|
||||
"file_text": "MUST NOT EXIST"
|
||||
},
|
||||
"locations": [
|
||||
{
|
||||
"path": "/fixture/workspace/copilot-denied-nonce.txt"
|
||||
}
|
||||
],
|
||||
"content": [
|
||||
{
|
||||
"type": "diff",
|
||||
"path": "/fixture/workspace/copilot-denied-nonce.txt",
|
||||
"oldText": "",
|
||||
"newText": "MUST NOT EXIST"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"id": 0,
|
||||
"method": "session/request_permission",
|
||||
"params": {
|
||||
"sessionId": "21c800ed-2229-48f8-b13a-68e711944863",
|
||||
"toolCall": {
|
||||
"toolCallId": "fixture-tool",
|
||||
"title": "Create file",
|
||||
"kind": "edit",
|
||||
"status": "pending",
|
||||
"rawInput": {
|
||||
"fileName": "/fixture/workspace/copilot-denied-nonce.txt",
|
||||
"diff": "\ndiff --git a/fixture/workspace/copilot-denied-nonce.txt b/fixture/workspace/copilot-denied-nonce.txt\ncreate file mode 100644\nindex 0000000..0000000\n--- a/dev/null\n+++ b/fixture/workspace/copilot-denied-nonce.txt\n@@ -1,0 +1,1 @@\n+MUST NOT EXIST\n"
|
||||
},
|
||||
"locations": [
|
||||
{
|
||||
"path": "/fixture/workspace/copilot-denied-nonce.txt"
|
||||
}
|
||||
]
|
||||
},
|
||||
"options": [
|
||||
{
|
||||
"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"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "session/update",
|
||||
"params": {
|
||||
"sessionId": "21c800ed-2229-48f8-b13a-68e711944863",
|
||||
"update": {
|
||||
"sessionUpdate": "tool_call_update",
|
||||
"toolCallId": "fixture-tool",
|
||||
"status": "failed",
|
||||
"rawOutput": {
|
||||
"message": "The user rejected this tool call.",
|
||||
"code": "rejected"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"attached-shell": [
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "session/update",
|
||||
"params": {
|
||||
"sessionId": "8426a268-fe73-4b5c-addd-26de5f670c38",
|
||||
"update": {
|
||||
"sessionUpdate": "tool_call",
|
||||
"toolCallId": "fixture-tool",
|
||||
"title": "Bounded settlement fixture",
|
||||
"kind": "execute",
|
||||
"status": "pending",
|
||||
"rawInput": {
|
||||
"command": "sleep 2; printf ACP_SHELL_DONE > settlement.txt",
|
||||
"description": "Bounded settlement fixture",
|
||||
"mode": "async",
|
||||
"detach": false
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"id": 0,
|
||||
"method": "session/request_permission",
|
||||
"params": {
|
||||
"sessionId": "8426a268-fe73-4b5c-addd-26de5f670c38",
|
||||
"toolCall": {
|
||||
"toolCallId": "fixture-tool",
|
||||
"title": "Bounded settlement fixture",
|
||||
"kind": "execute",
|
||||
"status": "pending",
|
||||
"rawInput": {
|
||||
"command": "sleep 2; printf ACP_SHELL_DONE > settlement.txt",
|
||||
"commands": [
|
||||
"sleep 2; printf ACP_SHELL_DONE > settlement.txt"
|
||||
]
|
||||
}
|
||||
},
|
||||
"options": [
|
||||
{
|
||||
"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"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "session/update",
|
||||
"params": {
|
||||
"sessionId": "8426a268-fe73-4b5c-addd-26de5f670c38",
|
||||
"update": {
|
||||
"sessionUpdate": "tool_call_update",
|
||||
"toolCallId": "fixture-tool",
|
||||
"status": "completed",
|
||||
"content": [
|
||||
{
|
||||
"type": "content",
|
||||
"content": {
|
||||
"type": "text",
|
||||
"text": "<command started in background with shellId: 0>"
|
||||
}
|
||||
}
|
||||
],
|
||||
"rawOutput": {
|
||||
"content": "<command started in background with shellId: 0>",
|
||||
"detailedContent": "<command started in background with shellId: 0>"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "session/update",
|
||||
"params": {
|
||||
"sessionId": "8426a268-fe73-4b5c-addd-26de5f670c38",
|
||||
"update": {
|
||||
"sessionUpdate": "tool_call_update",
|
||||
"toolCallId": "fixture-tool",
|
||||
"content": [
|
||||
{
|
||||
"type": "content",
|
||||
"content": {
|
||||
"type": "text",
|
||||
"text": ""
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "session/update",
|
||||
"params": {
|
||||
"sessionId": "8426a268-fe73-4b5c-addd-26de5f670c38",
|
||||
"update": {
|
||||
"sessionUpdate": "tool_call",
|
||||
"toolCallId": "7da35af6-2aab-469f-8964-40f0605dcb6c",
|
||||
"title": "Reading shell output",
|
||||
"kind": "read",
|
||||
"status": "pending",
|
||||
"rawInput": {
|
||||
"shellId": "0",
|
||||
"delay": 0
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "session/update",
|
||||
"params": {
|
||||
"sessionId": "8426a268-fe73-4b5c-addd-26de5f670c38",
|
||||
"update": {
|
||||
"sessionUpdate": "tool_call_update",
|
||||
"toolCallId": "7da35af6-2aab-469f-8964-40f0605dcb6c",
|
||||
"status": "completed",
|
||||
"content": [
|
||||
{
|
||||
"type": "content",
|
||||
"content": {
|
||||
"type": "text",
|
||||
"text": "\n<shellId: 0 completed with exit code 0>"
|
||||
}
|
||||
}
|
||||
],
|
||||
"rawOutput": {
|
||||
"content": "\n<shellId: 0 completed with exit code 0>",
|
||||
"detailedContent": "\n<shellId: 0 completed with exit code 0>"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
Reference in new issue
Block a user