Preserve scoped Pi prompt receipt provenance and cost through ACPX

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip committed 2026-09-28 11:26:11 -05:00
1 parent 7e2e7e1c35
commit 2de5c04c9a
2 files changed
+120 -21

No files matched your search

@@ -0,0 +1,57 @@
import assert from "node:assert/strict";
import { createRequire } from "node:module";
import { dirname, join } from "node:path";
import { pathToFileURL } from "node:url";
import test from "node:test";
const require = createRequire(import.meta.url);
const root = dirname(require.resolve("acpx/package.json"));
const {
_: createConversation, y: recordSubmission, n: runPromptTurn,
dt: serialize, ut: parse, tt: assertKeyPolicy,
} = await import(pathToFileURL(join(root, "dist/live-checkpoint-BSIrfgVo.js")));
async function recordReceipt(metadata, usage = { inputTokens: 12, outputTokens: 3 }) {
const conversation = createConversation();
const promptMessageId = recordSubmission(conversation, "Fixture prompt");
await runPromptTurn({
client: { prompt: async () => ({ stopReason: "end_turn", usage: { ...usage, _meta: { paperclipPi: metadata, secret: "DROP_ME" } } }) },
sessionId: "session-1", prompt: "Fixture prompt", conversation, promptMessageId,
});
return { conversation, promptMessageId };
}
test("Pi prompt receipts preserve exact per-request provenance and USD cost including zero", async () => {
for (const costUsd of [0, 0.0025]) {
const { conversation, promptMessageId } = await recordReceipt({ provenance: "assistant_message_receipts", costUsd, extra: "DROP_ME" });
assert.deepEqual(conversation.request_token_usage[promptMessageId].paperclip_pi, { provenance: "assistant_message_receipts", cost_usd: costUsd });
assert.equal(conversation.cumulative_token_usage.paperclip_pi, undefined);
assert.equal(conversation.cumulative_cost, undefined);
assert.equal(JSON.stringify(conversation).includes("DROP_ME"), false);
}
});
test("missing cost stays missing and untrusted provenance or invalid costs never become receipts", async () => {
const missing = await recordReceipt({ provenance: "assistant_message_receipts" }, {});
assert.deepEqual(missing.conversation.request_token_usage[missing.promptMessageId].paperclip_pi, { provenance: "assistant_message_receipts" });
for (const metadata of [{ provenance: "estimated", costUsd: 1 }, { provenance: "assistant_message_receipts", costUsd: -1 }, { provenance: "assistant_message_receipts", costUsd: Infinity }, { provenance: "assistant_message_receipts", costUsd: "0.01" }]) {
const { conversation, promptMessageId } = await recordReceipt(metadata);
assert.equal(conversation.request_token_usage[promptMessageId].paperclip_pi, undefined);
}
});
test("receipts survive canonical disk serialization/reload with a closed metadata shape", async () => {
const { conversation, promptMessageId } = await recordReceipt({ provenance: "assistant_message_receipts", costUsd: 0.01 });
const record = {
schema: "acpx.session.v1", acpxRecordId: "record-1", acpSessionId: "session-1", agentCommand: "verified-pi",
cwd: "/workspace", createdAt: "2026-09-28T00:00:00Z", lastUsedAt: "2026-09-28T00:00:00Z", lastSeq: 0,
...conversation,
};
const disk = serialize(record);
assertKeyPolicy(disk);
disk.request_token_usage[promptMessageId].paperclip_pi.extra = "DROP_ME";
const restored = parse(JSON.parse(JSON.stringify(disk)));
assert.ok(restored);
assert.deepEqual(restored.request_token_usage[promptMessageId].paperclip_pi, { provenance: "assistant_message_receipts", cost_usd: 0.01 });
assert.equal(JSON.stringify(restored).includes("DROP_ME"), false);
});
+63 -21
View File
@@ -20,7 +20,17 @@ diff --git a/dist/live-checkpoint-BSIrfgVo.js b/dist/live-checkpoint-BSIrfgVo.js
title: canonical.title,
messages: canonical.messages,
updated_at: canonical.updated_at,
@@ -1541,6 +1542,7 @@
@@ -1239,7 +1240,8 @@
for (const [key, value] of Object.entries(record)) {
const parsed = parseTokenUsage(value);
if (parsed == null) return null;
- usage[key] = parsed;
+ const receipt = parsePaperclipPiReceipt(asRecord$4(value)?.paperclip_pi);
+ usage[key] = receipt ? { ...parsed, paperclip_pi: receipt } : parsed;
}
return usage;
}
@@ -1541,6 +1543,7 @@
lastAgentDisconnectReason: optionals.lastAgentDisconnectReason,
protocolVersion: typeof record.protocol_version === "number" ? record.protocol_version : void 0,
agentCapabilities: asRecord$4(record.agent_capabilities),
@@ -28,7 +38,7 @@ diff --git a/dist/live-checkpoint-BSIrfgVo.js b/dist/live-checkpoint-BSIrfgVo.js
title: conversation.title,
messages: conversation.messages,
updated_at: conversation.updated_at,
@@ -1661,7 +1663,7 @@
@@ -1661,7 +1664,7 @@
"RedactedThinking",
"ToolUse"
]);
@@ -37,7 +47,7 @@ diff --git a/dist/live-checkpoint-BSIrfgVo.js b/dist/live-checkpoint-BSIrfgVo.js
const OPAQUE_VALUE_PATHS = /* @__PURE__ */ new Set([
"agent_capabilities",
"messages.Agent.content.ToolUse.input",
@@ -3135,8 +3137,18 @@
@@ -3135,8 +3138,18 @@
}
return protectedKeys;
}
@@ -58,7 +68,7 @@ diff --git a/dist/live-checkpoint-BSIrfgVo.js b/dist/live-checkpoint-BSIrfgVo.js
const protectedAuthEnvKeys = promotePrefixedAuthEnvironment(env);
if (authCredentials) for (const [methodId, credential] of Object.entries(authCredentials)) {
addAuthCredentialEnvKeys(protectedAuthEnvKeys, methodId, credential);
@@ -3178,10 +3190,10 @@
@@ -3178,10 +3191,10 @@
const configCredentials = authCredentials ?? {};
return configCredentials[methodId] ?? configCredentials[toEnvToken(methodId)];
}
@@ -71,7 +81,7 @@ diff --git a/dist/live-checkpoint-BSIrfgVo.js b/dist/live-checkpoint-BSIrfgVo.js
stdio: [
"pipe",
"pipe",
@@ -3961,10 +3973,13 @@
@@ -3961,10 +3974,13 @@
...params.elicitationModes.includes("url") ? { url: {} } : {}
} } : {}
};
@@ -87,7 +97,7 @@ diff --git a/dist/live-checkpoint-BSIrfgVo.js b/dist/live-checkpoint-BSIrfgVo.js
};
}
function hasResponseField(response, field) {
@@ -4067,6 +4082,27 @@
@@ -4067,6 +4083,27 @@
} })
};
}
@@ -115,7 +125,7 @@ diff --git a/dist/live-checkpoint-BSIrfgVo.js b/dist/live-checkpoint-BSIrfgVo.js
var AcpClient = class {
options;
connection;
@@ -4105,7 +4141,9 @@
@@ -4105,7 +4142,9 @@
cwd: asAbsoluteCwd(options.cwd),
authPolicy: options.authPolicy ?? "skip",
permissionPolicy: snapshotPermissionPolicy(options.permissionPolicy),
@@ -126,7 +136,7 @@ diff --git a/dist/live-checkpoint-BSIrfgVo.js b/dist/live-checkpoint-BSIrfgVo.js
};
this.eventHandlers = {
onAcpMessage: this.options.onAcpMessage,
@@ -4216,9 +4254,21 @@
@@ -4216,9 +4255,21 @@
this.lastAgentExit = void 0;
this.lastKnownPid = child.pid ?? void 0;
this.attachAgentLifecycleObservers(child);
@@ -148,7 +158,7 @@ diff --git a/dist/live-checkpoint-BSIrfgVo.js b/dist/live-checkpoint-BSIrfgVo.js
if (!this.options.verbose) return;
process.stderr.write(chunk);
});
@@ -4253,7 +4303,12 @@
@@ -4253,7 +4304,12 @@
geminiAcp: isGeminiAcpCommand(spawnCommand, args),
copilotAcp: isCopilotAcpCommand(spawnCommand, args),
claudeAcp: isClaudeAcpCommand(spawnCommand, args),
@@ -162,7 +172,7 @@ diff --git a/dist/live-checkpoint-BSIrfgVo.js b/dist/live-checkpoint-BSIrfgVo.js
};
}
logAgentLaunch(plan) {
@@ -4279,10 +4334,17 @@
@@ -4279,10 +4335,17 @@
}
async spawnAgentProcess(plan) {
const spawnCommand = buildAgentSpawnCommand(plan.spawnCommand, plan.args, process.platform, plan.spawnOptions.env);
@@ -182,7 +192,7 @@ diff --git a/dist/live-checkpoint-BSIrfgVo.js b/dist/live-checkpoint-BSIrfgVo.js
try {
await waitForSpawn$1(spawnedChild);
} catch (error) {
@@ -4312,6 +4374,11 @@
@@ -4312,6 +4375,11 @@
}).onRequest(methods.client.terminal.release, async ({ params }) => {
return await this.handleReleaseTerminal(params);
});
@@ -194,7 +204,7 @@ diff --git a/dist/live-checkpoint-BSIrfgVo.js b/dist/live-checkpoint-BSIrfgVo.js
if (launch.devinAcp) app.onRequest("_cognition.ai/request_diagnostics", (params) => {
return params && typeof params === "object" && !Array.isArray(params) ? params : {};
}, async () => ({}));
@@ -4333,12 +4400,12 @@
@@ -4333,12 +4401,12 @@
async initializeProtocolConnection(connection, launch) {
const initializePromise = connection.initialize({
protocolVersion: PROTOCOL_VERSION,
@@ -209,7 +219,7 @@ diff --git a/dist/live-checkpoint-BSIrfgVo.js b/dist/live-checkpoint-BSIrfgVo.js
clientInfo: resolveClientInfo(launch.devinAcp)
});
const initialized = launch.geminiAcp ? await withTimeout(initializePromise, resolveGeminiAcpStartupTimeoutMs()) : await initializePromise;
@@ -4367,8 +4434,9 @@
@@ -4367,8 +4435,9 @@
const shouldSuppressInboundReplaySessionUpdate = (message) => {
return this.suppressReplaySessionUpdateMessages && isSessionUpdateNotification(message);
};
@@ -220,7 +230,7 @@ diff --git a/dist/live-checkpoint-BSIrfgVo.js b/dist/live-checkpoint-BSIrfgVo.js
if (requestId !== void 0) {
elicitationRequestIds.add(requestId);
return;
@@ -4387,7 +4455,10 @@
@@ -4387,7 +4456,10 @@
if (done) break;
if (!value) continue;
observeInbound(value);
@@ -232,7 +242,7 @@ diff --git a/dist/live-checkpoint-BSIrfgVo.js b/dist/live-checkpoint-BSIrfgVo.js
controller.enqueue(value);
}
} finally {
@@ -4926,6 +4997,40 @@
@@ -4926,6 +4998,40 @@
}
return response;
}
@@ -273,7 +283,7 @@ diff --git a/dist/live-checkpoint-BSIrfgVo.js b/dist/live-checkpoint-BSIrfgVo.js
async handleElicitationRequest(request, requestId, requestSignal) {
const resolved = this.resolveElicitationOwner(request);
if ("response" in resolved) return resolved.response;
@@ -5028,6 +5133,12 @@
@@ -5028,6 +5134,12 @@
attachAgentLifecycleObservers(child) {
child.once("exit", (exitCode, signal) => {
this.recordAgentExit("process_exit", exitCode, signal);
@@ -286,7 +296,30 @@ diff --git a/dist/live-checkpoint-BSIrfgVo.js b/dist/live-checkpoint-BSIrfgVo.js
});
child.once("close", (exitCode, signal) => {
this.recordAgentExit("process_close", exitCode, signal);
@@ -6435,6 +6546,27 @@
@@ -5771,10 +5883,20 @@
trimConversationForRuntime(conversation);
return acpx;
}
+function parsePaperclipPiReceipt(raw, costField = "cost_usd") {
+ const receipt = asRecord$4(raw);
+ if (receipt?.provenance !== "assistant_message_receipts") return;
+ const cost = receipt[costField];
+ if (cost !== void 0 && !isNonNegativeFiniteNumber(cost)) return;
+ return { provenance: "assistant_message_receipts", ...cost !== void 0 ? { cost_usd: cost } : {} };
+}
function recordPromptResponseUsage(conversation, usage, promptMessageId, timestamp = isoNow()) {
const tokenUsage = sourceToTokenUsage(usage);
- if (!tokenUsage) return false;
- applyTokenUsage(conversation, tokenUsage, promptMessageId);
+ const receipt = parsePaperclipPiReceipt(asRecord$4(asRecord$4(usage)?._meta)?.paperclipPi, "costUsd");
+ if (!tokenUsage && !receipt) return false;
+ if (tokenUsage) applyTokenUsage(conversation, tokenUsage, promptMessageId);
+ const userId = promptMessageId ?? lastUserMessageId(conversation);
+ if (receipt && userId) conversation.request_token_usage[userId] = { ...conversation.request_token_usage[userId], paperclip_pi: receipt };
updateConversationTimestamp(conversation, timestamp);
trimConversationForRuntime(conversation);
return true;
@@ -6435,6 +6557,27 @@
//#region src/runtime/engine/prompt-turn.ts
const SESSION_REPLY_IDLE_MS = 1e3;
const SESSION_REPLY_DRAIN_TIMEOUT_MS = 5e3;
@@ -314,7 +347,7 @@ diff --git a/dist/live-checkpoint-BSIrfgVo.js b/dist/live-checkpoint-BSIrfgVo.js
async function runPromptTurn(params) {
try {
const promptPromise = params.client.prompt(params.sessionId, params.prompt, params.onPromptRequestStarted, params.onElicitation);
@@ -6444,6 +6576,19 @@
@@ -6444,6 +6587,19 @@
idleMs: SESSION_REPLY_IDLE_MS,
timeoutMs: SESSION_REPLY_DRAIN_TIMEOUT_MS
}).catch(() => {});
@@ -334,7 +367,7 @@ diff --git a/dist/live-checkpoint-BSIrfgVo.js b/dist/live-checkpoint-BSIrfgVo.js
recordPromptResponseUsage(params.conversation, response.usage, params.promptMessageId);
return {
stopReason: response.stopReason,
@@ -6518,4 +6663,4 @@
@@ -6518,4 +6674,4 @@
//#endregion
export { writeSessionRecord as $, PERMISSION_POLICY_ACTIONS as $t, REQUESTED_MODEL_UNSUPPORTED_ERROR_CODE as A, TimeoutError as At, getAcpxVersion as B, formatErrorMessage as Bt, mergeSessionOptions as C, PromptInputValidationError as Ct, applyLifecycleSnapshotToRecord as D, promptToDisplayText as Dt, applyConversation as E, parsePromptSource as Et, modelStateFromConfigOptions as F, normalizeAgentName$1 as Ft, findSession as G, toAcpErrorPayload as Gt, DEFAULT_HISTORY_LIMIT as H, normalizeOutputError as Ht, normalizeAgentCommandInput as I, resolveAgentArgv as It, listSessions as J, NON_INTERACTIVE_PERMISSION_POLICIES as Jt, findSessionByDirectoryWalk as K, AUTH_POLICIES as Kt, renderArgvIdentity as L, resolveAgentCommand as Lt, RequestedModelUnsupportedError as M, withTimeout as Mt, assertRequestedModelSupported as N, DEFAULT_AGENT_NAME as Nt, reconcileAgentSessionId as O, textPrompt as Ot, isRequestedModelUnsupportedError as P, listBuiltInAgents as Pt, resolveSessionRecord as Q, PERMISSION_MODES as Qt, runTimedExecFile as R, resolveCanonicalAgentName as Rt, advertisedModelState as S, parsePromptStopReason as St, sessionOptionsFromRecord as T, mergePromptSourceWithText as Tt, absolutePath as U, extractAcpError as Ut, permissionModeSatisfies as V, isRetryablePromptError as Vt, findGitRepositoryRoot as W, isAcpResourceNotFoundError as Wt, normalizeName as X, OUTPUT_ERROR_ORIGINS as Xt, listSessionsForAgent as Y, OUTPUT_ERROR_CODES as Yt, pruneSessions as Z, OUTPUT_FORMATS as Zt, createSessionConversation as _, sessionEventLockPath as _t, applyRequestedModelIfAdvertised as a, measurePerf as at, recordSessionUpdate as b, isAcpJsonRpcMessage as bt, setCurrentModelId as c, setPerfGauge as ct, setDesiredModelId as d, serializeSessionRecordForDisk as dt, SESSION_RECORD_SCHEMA as en, createAtomicWriteTempPath as et, syncAdvertisedModelState as f, normalizeRuntimeSessionId as ft, cloneSessionConversation as g, sessionEventActivePath as gt, cloneSessionAcpxState as h, sessionBaseDir$1 as ht, connectAndLoadSession as i, QueueProtocolError as in, incrementPerfCounter as it, REQUESTED_MODEL_UNSUPPORTED_REASONS as j, withInterrupt as jt, AcpClient as k, InterruptedError as kt, setDesiredConfigOption as l, startPerfTimer as lt, applyConfigOptionsToState as m, defaultSessionEventLog as mt, runPromptTurn as n, AgentSpawnError as nn, formatPerfMetric as nt, currentModelIdFromSetModelResponse as o, recordPerfDuration as ot, applyConfigOptionsToRecord as p, DEFAULT_EVENT_SEGMENT_MAX_BYTES as pt, isoNow$2 as q, EXIT_CODES as qt, withConnectedSession as r, QueueConnectionError as rn, getPerfMetricsSnapshot as rt, clearDesiredConfigOption as s, resetPerfMetrics as st, LiveSessionCheckpoint as t, AcpxOperationalError as tn, assertPersistedKeyPolicy as tt, setDesiredModeId as u, parseSessionRecord as ut, recordClientOperation as v, sessionEventSegmentPath as vt, persistSessionOptions as w, isPromptInput as wt, trimConversationForRuntime as x, parseJsonRpcErrorMessage as xt, recordPromptSubmission as y, extractSessionUpdateNotification as yt, splitCommandLine as z, exitCodeForOutputErrorCode as zt };
@@ -702,7 +735,7 @@ diff --git a/dist/session-options-DwRDODlr.d.ts b/dist/session-options-DwRDODlr.
onAcpMessage?: (direction: AcpMessageDirection, message: AcpJsonRpcMessage) => void;
onAcpOutputMessage?: (direction: AcpMessageDirection, message: AcpJsonRpcMessage) => void;
onSessionUpdate?: (notification: SessionNotification) => void;
@@ -263,6 +292,7 @@
@@ -263,12 +292,15 @@
lastAgentDisconnectReason?: string;
protocolVersion?: number;
agentCapabilities?: AgentCapabilities;
@@ -710,7 +743,16 @@ diff --git a/dist/session-options-DwRDODlr.d.ts b/dist/session-options-DwRDODlr.
title?: string | null;
messages: SessionMessage[];
updated_at: string;
@@ -295,4 +325,4 @@
cumulative_token_usage: SessionTokenUsage;
cumulative_cost?: SessionUsageCost;
- request_token_usage: Record<string, SessionTokenUsage>;
+ request_token_usage: Record<string, SessionTokenUsage & {
+ paperclip_pi?: { provenance: "assistant_message_receipts"; cost_usd?: number };
+ }>;
acpx?: SessionAcpxState;
importedFrom?: SessionImportedFrom;
};
@@ -295,4 +327,4 @@
};
//#endregion
export { SessionRecord as _, AcpElicitationHandler as a, AcpElicitationResponse as c, AuthPolicy as d, McpServer$1 as f, PermissionStats as g, PermissionPolicy as h, AcpElicitationContext as i, AcpPermissionDecision as l, PermissionMode as m, SystemPromptOption as n, AcpElicitationMode as o, NonInteractivePermissionPolicy as p, AcpClientOptions as r, AcpElicitationRequest as s, SessionAgentOptions as t, AcpPermissionRequest as u, PromptInput as v };