fix(hermes): retain per-turn reported OpenRouter billing

Capture pinned SDK wire attempts, carry closed versioned receipts through ACPX and PRP, and bind reported subtotals to native turn accounting. Keep incomplete attempts unpriced and require settled cost plus budget health in the live OpenRouter oracle.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip committed 2026-10-08 12:28:12 -05:00
1 parent 01855199ad
commit e5afbd7107
38 files changed
+1286 -48

No files matched your search

@@ -323,6 +323,7 @@ import {
buildRemoteCodexLauncherCommand,
mayUsePreinstalledRunnerArtifact,
nativeUsageCostUsd,
createNativeTurnAccounting,
nativeUsageBiller,
normalizeNativeUsage,
resolveNativeBilling,
@@ -1001,6 +1002,45 @@ describe("native incomplete-bootstrap evidence", () => {
});
describe("native provider usage normalization", () => {
const hermes = { kind: "acpx", agent: "hermes", model: "fixture-model" } as NativeExecutionInput["provider"];
const billing = { schema: "paperclip.usage.billing/v1", source: "provider_reported", biller: "openrouter", currency: "USD",
complete: true, requestCount: 2, reportedRequestCount: 2, amountUsd: 0.25, amountUsdExact: "0.250000000" };
const priced = { runDelta: { inputTokens: 20, outputTokens: 5, providerCostUsd: 0.25 }, billing };
it("requires exact selected-account price authority for Hermes instead of a scalar or cumulative cost", () => {
expect(nativeUsageCostUsd(priced, hermes, "openrouter")).toBe(0.25);
for (const selectedBiller of [undefined, "unknown", "anthropic"]) expect(nativeUsageCostUsd(priced, hermes, selectedBiller)).toBeUndefined();
for (const candidate of [{ ...priced, billing: undefined }, { ...priced, billing: { ...billing, source: "rate_card" } },
{ ...priced, runDelta: { ...priced.runDelta, providerCostUsd: 1 } }]) {
expect(nativeUsageCostUsd(candidate, hermes, "openrouter")).toBeUndefined();
}
expect(nativeUsageCostUsd({ ...priced, billing: { ...billing, complete: false, reportedRequestCount: 1 } }, hermes, "openrouter")).toBe(0.25);
const zero = { ...priced, runDelta: { ...priced.runDelta, providerCostUsd: 0 }, billing: { ...billing, amountUsd: 0, amountUsdExact: "0.000000000" } };
expect(nativeUsageCostUsd(zero, hermes, "openrouter")).toBe(0);
expect(nativeUsageCostUsd({ ...zero, billing: { ...zero.billing, complete: false } }, hermes, "openrouter")).toBeUndefined();
});
it("rebuilds exact per-turn price totals across replay and preserves unknown earlier work", () => {
const accounting = createNativeTurnAccounting(hermes, "openrouter");
let sequence = 0;
const event = (eventType: string, turnId: string, payload: object = {}) => ({
eventType, turnId, payload, sourceSeq: ++sequence, sourceInstanceId: "provider",
}) as unknown as PrpEvent;
accounting.observe(event("turn.started", "first"));
const price = event("item.completed", "first", { kind: "usage", usage: priced });
accounting.observe(price); accounting.observe(price);
expect(accounting.snapshot().complete).toBe(false);
accounting.observe(event("turn.completed", "first"));
expect(accounting.snapshot().usage?.accountingCostUsdExact).toBe("0.250000000");
accounting.observe(event("turn.started", "second"));
accounting.observe(event("item.completed", "second", { kind: "usage", usage: {
runDelta: { inputTokens: 10, outputTokens: 2, providerCostUsd: 999 },
} }));
accounting.observe(event("turn.completed", "second"));
const snapshot = accounting.snapshot();
expect(snapshot.complete).toBe(true);
expect(snapshot.usage).toMatchObject({ accountingCostUsdExact: "0.250000000", accountingCostIncomplete: true,
billing: { complete: false, amountUsd: 0.25 } });
expect(nativeUsageCostUsd(snapshot.usage, hermes, "openrouter")).toBe(0.25);
});
it.each([
{}, { inputTokens: 1 }, { outputTokens: 1 },
{ inputTokens: 0, outputTokens: -1 }, { inputTokens: 0.5, outputTokens: 1 },
@@ -5515,6 +5555,46 @@ describe("native terminal-turn accounting", () => {
if (scenario === "late_update") expect(result.usage).toMatchObject({ inputTokens: 32, outputTokens: 8 });
});
it.each(["reported", "partial", "legacy", "wrong_account", "zero"] as const)("settles bound Hermes billing through the executor (%s)", async scenario => {
const previous = process.env.PAPERCLIP_RUNNER_ACPX_QUALIFICATION;
process.env.PAPERCLIP_RUNNER_ACPX_QUALIFICATION = JSON.stringify([{ agent: "hermes", model: "fixture-model" }]);
try {
const onUsage = vi.fn(async (_receipt: import("@paperclipai/adapter-utils").AdapterUsageCheckpoint) => {});
const amount = scenario === "zero" ? 0 : 0.25;
const billing = { schema: "paperclip.usage.billing/v1", source: "provider_reported", biller: "openrouter", currency: "USD",
complete: scenario !== "partial", requestCount: 2, reportedRequestCount: scenario === "partial" ? 1 : 2,
amountUsd: amount, amountUsdExact: amount.toFixed(9) };
const notification = (await import("@paperclipai/paperclip-runner/live")).rehydrateRunnerdUsageNotification({
runDeltaAvailable: true, runDelta: { inputTokens: 20, outputTokens: 5, cacheReadTokens: 3, cacheWriteTokens: 2, providerCostUsd: amount },
...(scenario === "legacy" ? {} : { billing }),
}, "session", "turn");
const event = (eventType: string, sourceSeq: number, payload: object = {}) => ({ eventType, turnId: "turn", payload,
sourceSeq, sourceInstanceId: "provider", emittedAt: new Date().toISOString() }) as unknown as PrpEvent;
state.execute.mockReset().mockImplementationOnce(async () => {
await accountingEvents.committed!(event("turn.started", 1));
const usage = event("item.completed", 2, { kind: "usage", usage: notification.tokenUsage });
await accountingEvents.committed!(usage);
expect(onUsage.mock.calls.at(-1)![0].complete).toBe(false);
await accountingEvents.committed!(event("turn.completed", 3));
await accountingEvents.duplicate!(usage);
return { result: { summary: "cancelled" }, terminal: { runTerminalState: "cancelled" }, turnId: "turn",
normalizedSessionId: "session", providerSessionId: null, driverKind: "test", driverVersion: "1", nativeEventCount: 3,
highestContiguousSourceSeq: 3, usage: null };
});
const known = !["legacy", "wrong_account"].includes(scenario);
const result = await executePaperclipNativeSession({ db: leaseDb(), runnerInstanceId: "runner", onUsage,
billingIdentity: { provider: "deepseek", biller: scenario === "wrong_account" ? "anthropic" : "openrouter", billingType: "metered_api" },
execution: { ...execution, provider: { kind: "acpx", agent: "hermes", model: "fixture-model", permissionMode: "approve-all", profile: QUALIFIED_ACPX_PROFILES.hermes } } as NativeExecutionInput });
expect(result).toMatchObject({ usageComplete: true, costUsd: known ? amount : null,
costStatus: known && scenario !== "partial" ? "reported" : "unpriced" });
expect(onUsage).toHaveBeenLastCalledWith(expect.objectContaining({ complete: true, costUsd: result.costUsd, costStatus: result.costStatus }));
if (known) expect(result.pricingProvenance).toMatchObject({ source: "provider_reported", version: "hermes-openrouter-wire/v1" });
} finally {
if (previous === undefined) delete process.env.PAPERCLIP_RUNNER_ACPX_QUALIFICATION;
else process.env.PAPERCLIP_RUNNER_ACPX_QUALIFICATION = previous;
}
});
it.each(["committed", "duplicate"] as const)("saves completed usage before returning to result commitment (%s)", async mode => {
const onUsage = vi.fn(async (_receipt: import("@paperclipai/adapter-utils").AdapterUsageCheckpoint) => {});
const failure = new Error("stopped after result commit, before executor returns");
@@ -4,6 +4,7 @@ import { dotRunnerBroker } from "../dot-runner-broker.js";
import { configuredEnvironment } from "../../vendor/paperclip-runner/index.js";
import { CURSOR_DISTRIBUTION_PINS, QUALIFIED_ACPX_PROFILES, QUALIFIED_ACPX_VERSION } from "../../vendor/paperclip-runner/index.js";
import { isProviderMode } from "../../vendor/paperclip-runner/index.js";
import { readProviderUsageBilling } from "../../vendor/paperclip-runner/index.js";
import { bundledRemoteProviderPackManifestPath, bundledRemoteRunnerBinary } from "../../vendor/paperclip-runner/index.js";
import { nativeRetryCancellationEligible, rethrowNativeCancellationLockConflict, assertCancellationRequest, cancellationIntentId as callerCancellationIntentId, cancellationRequestId } from "./native-cancellation-request.js";
import { readNativePlanWait } from "./native-plan-wait.js";
@@ -7977,7 +7978,8 @@ async function executePaperclipNativeSessionWithinScope(
let nativeAccountingComplete = false;
// OpenCode and ACPX report their current turn; Codex reports a cumulative run delta.
// Rebuild per-turn state from the durable event log when a controller resumes.
const turnAccounting = ["opencode", "acpx"].includes(input.execution.provider.kind) ? createNativeTurnAccounting(input.execution.provider) : null;
const selectedBiller = resolveNativeBilling(input.execution.provider, input.runnerEnvironment, input.billingIdentity).biller;
const turnAccounting = ["opencode", "acpx"].includes(input.execution.provider.kind) ? createNativeTurnAccounting(input.execution.provider, selectedBiller) : null;
if (turnAccounting) {
const history = await input.db.select({ payload: heartbeatRunEvents.payload }).from(heartbeatRunEvents).where(and(
eq(heartbeatRunEvents.companyId, input.execution.binding.companyId), eq(heartbeatRunEvents.runId, input.execution.binding.runId),
@@ -7988,20 +7990,22 @@ async function executePaperclipNativeSessionWithinScope(
}
const persistAccountingUsage = async (usage: Record<string, unknown> | null, complete: boolean) => {
const accountingUsage = normalizeNativeUsage(usage, { inputIncludesCacheReads: input.execution.provider.kind === "codex" });
const accountingCost = accountingUsage ? nativeUsageCostUsd(usage, input.execution.provider) : undefined;
const accountingCost = accountingUsage ? nativeUsageCostUsd(usage, input.execution.provider, selectedBiller) : undefined;
complete = complete && accountingUsage !== undefined;
const costStatus = complete && usage?.accountingCostIncomplete !== true
? input.execution.provider.kind === "aws_agentcore" ? "estimated" as const : undefined
? input.execution.provider.kind === "aws_agentcore" ? "estimated" as const : nativeHermesPriceEvidence(usage, input.execution.provider, selectedBiller) ? "reported" as const : undefined
: "unpriced" as const;
const billing = resolveNativeBilling(input.execution.provider, input.runnerEnvironment, input.billingIdentity);
const costUsdExact = typeof usage?.accountingCostUsdExact === "string" ? usage.accountingCostUsdExact : undefined;
await input.onUsage?.({ usage: accountingUsage, ...billing, complete, usageBasis: "per_run", costUsdExact,
model: input.execution.provider.model ?? "unknown", costUsd: accountingCost ?? null, costStatus });
model: input.execution.provider.model ?? "unknown", costUsd: accountingCost ?? null, costStatus,
...nativeHermesPriceEvidence(usage, input.execution.provider, selectedBiller) });
if (!input.onUsage) await input.db.update(heartbeatRuns).set({
costAccountingPending: true,
usageJson: sql`coalesce(${heartbeatRuns.usageJson}, '{}'::jsonb) || ${JSON.stringify({
...accountingUsage, ...billing, accountingReceiptReady: complete, model: input.execution.provider.model ?? "unknown",
costUsd: accountingCost ?? null, costUsdExact: costUsdExact ?? null, costStatus: costStatus ?? null, usageSource: "per_run",
...nativeHermesPriceEvidence(usage, input.execution.provider, selectedBiller),
})}::jsonb`,
}).where(and(eq(heartbeatRuns.id, input.execution.binding.runId), eq(heartbeatRuns.companyId, input.execution.binding.companyId), isNull(heartbeatRuns.costAccountedAt)));
};
@@ -9501,12 +9505,13 @@ async function executePaperclipNativeSessionWithinScope(
model: input.execution.provider.model,
usage: normalizeNativeUsage(native.usage, { inputIncludesCacheReads: input.execution.provider.kind === "codex" }),
costUsd: input.execution.provider.kind !== "openai_dot" && normalizeNativeUsage(native.usage, { inputIncludesCacheReads: input.execution.provider.kind === "codex" })
? nativeUsageCostUsd(native.usage, input.execution.provider) ?? null : null,
? nativeUsageCostUsd(native.usage, input.execution.provider, selectedBiller) ?? null : null,
costUsdExact: typeof native.usage?.accountingCostUsdExact === "string" ? native.usage.accountingCostUsdExact : undefined,
costStatus: nativeAccountingComplete && native.usage?.accountingCostIncomplete !== true
? input.execution.provider.kind === "aws_agentcore" ? "estimated" : undefined
? input.execution.provider.kind === "aws_agentcore" ? "estimated" : nativeHermesPriceEvidence(native.usage, input.execution.provider, selectedBiller) ? "reported" : undefined
: "unpriced",
usageComplete: nativeAccountingComplete,
...nativeHermesPriceEvidence(native.usage, input.execution.provider, selectedBiller),
usageBasis: "per_run",
nativeFinalization: finalization,
};
@@ -9575,7 +9580,7 @@ export function nativeUsageBiller(provider: NativeExecutionInput["provider"]): s
return "openai";
}
function createNativeTurnAccounting(provider: NativeExecutionInput["provider"]) {
export function createNativeTurnAccounting(provider: NativeExecutionInput["provider"], selectedBiller?: string | null) {
const turns = new Map<string, { usage: Record<string, unknown> | null; terminal: boolean }>();
const sequences = new Map<string, number>();
let currentTurn: string | undefined;
@@ -9584,6 +9589,7 @@ function createNativeTurnAccounting(provider: NativeExecutionInput["provider"])
if (turns.size === 0) return { usage: null, turnId: undefined, complete: false };
let inputTokens = 0, outputTokens = 0, cacheReadTokens = 0, cacheWriteTokens = 0;
let cost = 0n, costKnown = false, costIncomplete = false, complete = true;
let requestCount = 0, reportedRequestCount = 0;
for (const [turnId, turn] of turns) {
const normalized = normalizeNativeUsage(turn.usage);
complete &&= turnId !== "unattributed" && turn.terminal && normalized !== undefined;
@@ -9591,9 +9597,18 @@ function createNativeTurnAccounting(provider: NativeExecutionInput["provider"])
outputTokens += normalized?.outputTokens ?? 0;
cacheReadTokens += normalized?.cachedInputTokens ?? 0;
cacheWriteTokens += normalized?.cacheWriteTokens ?? 0;
const price = nativeUsageCostUsd(turn.usage, provider);
const price = nativeUsageCostUsd(turn.usage, provider, selectedBiller);
const billing = provider.kind === "acpx" && provider.agent === "hermes"
? readProviderUsageBilling(turn.usage?.billing) : null;
if (price === undefined) costIncomplete = true;
else { cost += usdToUnits(price); costKnown = true; }
else {
cost += usdToUnits(billing?.amountUsdExact ?? price); costKnown = true;
if (billing) {
costIncomplete ||= !billing.complete;
requestCount += billing.requestCount;
reportedRequestCount += billing.reportedRequestCount;
}
}
}
// A free empty attempt contributes no price evidence for later paid work.
// Keep an incomplete zero subtotal absent so complete aggregate tokens can
@@ -9602,8 +9617,14 @@ function createNativeTurnAccounting(provider: NativeExecutionInput["provider"])
const runDelta = { inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens,
...(retainCost ? { providerCostUsd: Number(cost) / 1_000_000_000 } : {}) };
const current = currentTurn ? turns.get(currentTurn) : undefined;
const costExact = `${cost / 1_000_000_000n}.${String(cost % 1_000_000_000n).padStart(9, "0")}`;
return { usage: { runDelta, accountingCostIncomplete: costIncomplete,
...(retainCost ? { accountingCostUsdExact: `${cost / 1_000_000_000n}.${String(cost % 1_000_000_000n).padStart(9, "0")}` } : {}) },
...(retainCost && provider.kind === "acpx" && provider.agent === "hermes" ? { billing: {
schema: "paperclip.usage.billing/v1", source: "provider_reported", biller: "openrouter", currency: "USD",
complete: !costIncomplete, requestCount, reportedRequestCount,
amountUsd: Number(costExact), amountUsdExact: costExact,
} } : {}),
...(retainCost ? { accountingCostUsdExact: costExact } : {}) },
turnId: current && normalizeNativeUsage(current.usage) ? currentTurn : undefined, complete };
};
return {
@@ -9628,7 +9649,8 @@ function createNativeTurnAccounting(provider: NativeExecutionInput["provider"])
if (payload.kind === "usage") {
const usage = record(payload.usage);
turn.usage = Object.hasOwn(usage, "runDelta")
? { runDelta: record(usage.runDelta), runDeltaComplete: usage.runDeltaComplete } : null;
? { runDelta: record(usage.runDelta), runDeltaComplete: usage.runDeltaComplete,
...(usage.billing === undefined ? {} : { billing: usage.billing }) } : null;
}
if (terminal) turn.terminal = true;
turns.set(key, turn);
@@ -9646,11 +9668,20 @@ function createNativeTurnAccounting(provider: NativeExecutionInput["provider"])
export function nativeUsageCostUsd(
usage: Record<string, unknown> | null,
provider?: NativeExecutionInput["provider"],
selectedBiller?: string | null,
) {
// The ACP normalization contract fills absent per-turn cost with zero and
// reports actual cost cumulatively. Until it carries an authoritative run
// delta with provenance, neither value is a candidate's billed USD receipt.
if (provider?.kind === "acpx" && ["cursor", "copilot", "pi", "hermes"].includes(provider.agent)) return undefined;
if (provider?.kind === "acpx" && provider.agent === "hermes") {
const billing = readProviderUsageBilling(usage?.billing);
if (!usage || !billing || selectedBiller !== billing.biller
|| nativeUsageMeasurement(usage).providerCostUsd !== billing.amountUsd) return undefined;
// Explicit provider-reported zero is authoritative only for a complete
// receipt. Positive observed subtotals survive an incomplete request set.
return billing.complete || billing.amountUsd > 0 ? billing.amountUsd : undefined;
}
if (provider?.kind === "acpx" && ["cursor", "copilot", "pi"].includes(provider.agent)) return undefined;
if (!usage) return undefined;
const measurement = nativeUsageMeasurement(usage);
const hasRunDelta = Object.hasOwn(usage, "runDelta") || Object.hasOwn(record(usage.usage), "runDelta");
@@ -9668,6 +9699,12 @@ export function nativeUsageCostUsd(
return numericUsageField(cost, ["amount", "total"]);
}
function nativeHermesPriceEvidence(usage: Record<string, unknown> | null, provider: NativeExecutionInput["provider"], selectedBiller?: string | null) {
if (provider.kind !== "acpx" || provider.agent !== "hermes" || nativeUsageCostUsd(usage, provider, selectedBiller) === undefined) return undefined;
return { pricingProvenance: { source: "provider_reported" as const, version: "hermes-openrouter-wire/v1",
evidence: "Selected-account OpenRouter response usage.cost; incomplete attempts remain unpriced." } };
}
/** Billing identity follows the selected runtime and resolved credentials.
* Unknown authentication remains unknown; a provider name does not prove billing mode. */
export function resolveNativeBilling(provider: NativeExecutionInput["provider"], env: NodeJS.ProcessEnv = {}, identity?: Pick<AdapterExecutionResult, "provider" | "biller" | "billingType">): Pick<AdapterExecutionResult, "provider" | "biller" | "billingType"> {
+1
View File
@@ -130,6 +130,7 @@ export const parseNativeRuntimeContext = runner.parseNativeRuntimeContext;
export const parsePaperclipQuestionSet = runner.parsePaperclipQuestionSet;
export const parsePaperclipQuestionResponse =
runner.parsePaperclipQuestionResponse;
export const readProviderUsageBilling = runner.readProviderUsageBilling;
export const resolveQualifiedAcpxProfile = runner.resolveQualifiedAcpxProfile;
export const QUALIFIED_ACPX_PROFILES = runner.QUALIFIED_ACPX_PROFILES;
export const QUALIFIED_ACPX_VERSION = runner.QUALIFIED_ACPX_VERSION;