mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-03 03:36:57 +01:00
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:
1 parent
77216f7a7f
commit
a978fd5b4a
38 files changed
+1286
-48
No files matched your search
@@ -303,6 +303,10 @@ definition includes the account/runner harness source digest. Its API-only scope
|
||||
does not substitute for subscription or lifecycle qualification.
|
||||
The task permits one attempt. Both public 200-cent budgets must match the fixture
|
||||
scope before task creation; unlimited or foreign budget records fail admission.
|
||||
OpenRouter also requires a settled provider-reported price with an exact USD
|
||||
amount and healthy company/agent budget state before fixture teardown. The
|
||||
oracle reads scoped public run, company and agent records; it never derives
|
||||
billing or health from the model's answer or the cleanup pause.
|
||||
|
||||
## Persistent agent files
|
||||
|
||||
|
||||
@@ -1542,6 +1542,11 @@ the ordinary completion, screenshot, token/cost and cleanup evidence.
|
||||
Each cell admits one attempt and configures 200-cent company and agent budgets.
|
||||
Public budget readback must pass before task creation. Unpriced model usage
|
||||
remains unknown; this configured limit is not an exact billing receipt.
|
||||
The OpenRouter cell additionally waits for its public run's reported wire cost
|
||||
to settle and checks that the company remains active and the agent idle with
|
||||
no pause reason before cleanup. Its separate settlement snapshot rejects missing
|
||||
price evidence, estimates and an unpriced budget pause even when the answer is
|
||||
correct. Other providers retain completion-only coverage.
|
||||
Before creating the task, public account readback must identify the selected
|
||||
connected personal account, its company and owner, and the authenticated caller.
|
||||
Both run attribution fields must match that independently recorded owner.
|
||||
|
||||
@@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest";
|
||||
import { runnerMatrix, runnerSuites, suiteDefinitionHash } from "./catalog.js";
|
||||
import { buildMatrixJobs, parseRunnerSelectors, selectRunnerExecutions } from "./selectors.js";
|
||||
import { buildRunnerE2EProcessEnvironment } from "./harness-env.js";
|
||||
import { captureHermesApiAccountOwner, captureHermesApiBudgets, gradeHermesApiConnection } from "./hermes-api-connections.js";
|
||||
import { captureHermesApiAccountOwner, captureHermesApiBudgets, captureHermesOpenRouterSettlement, gradeHermesApiConnection } from "./hermes-api-connections.js";
|
||||
|
||||
describe("Hermes managed API connection qualification", () => {
|
||||
const suite = runnerSuites.find(s => s.id === "hermes-api-connections")!;
|
||||
@@ -41,6 +41,39 @@ describe("Hermes managed API connection qualification", () => {
|
||||
it("accepts independently observed account/model metadata", () => {
|
||||
expect(gradeHermesApiConnection(valid).every(check => check.passed)).toBe(true);
|
||||
});
|
||||
it.each(["valid", "reported-zero", "company-scope", "agent-scope", "run-scope", "task-scope", "paused-agent", "paused-company", "pause-reason", "budget-changed",
|
||||
"pending", "missing-settlement", "missing-price", "estimated", "partial", "wrong-biller", "wrong-provenance", "mismatched-exact", "unknown-tokens"])("calibrates public OpenRouter settlement: %s", async fault => {
|
||||
const company: Record<string, unknown> = { id: "company", status: "active", pauseReason: null, budgetMonthlyCents: 200 };
|
||||
const agent: Record<string, unknown> = { id: "agent", companyId: "company", status: "idle", pauseReason: null, budgetMonthlyCents: 200 };
|
||||
const usage: Record<string, unknown> = { biller: "openrouter", billingType: "metered_api", costStatus: "reported", costUsd: 0.0042, costUsdExact: "0.004200000",
|
||||
inputTokens: 40, outputTokens: 10, accountingReceiptReady: true, pricingProvenance: { source: "provider_reported", version: "hermes-openrouter-wire/v1" } };
|
||||
const run: Record<string, unknown> = { id: "run", companyId: "company", agentId: "agent", issueId: "task", status: "succeeded", usageJson: usage,
|
||||
costAccountingPending: false, costAccountedAt: "2026-10-08T03:00:00Z" };
|
||||
if (fault === "reported-zero") { usage.costUsd = 0; usage.costUsdExact = "0.000000000"; }
|
||||
if (fault === "company-scope") company.id = "foreign";
|
||||
if (fault === "agent-scope") agent.companyId = "foreign";
|
||||
if (fault === "run-scope") run.agentId = "foreign";
|
||||
if (fault === "task-scope") run.issueId = "foreign";
|
||||
if (fault === "paused-agent") agent.status = "paused";
|
||||
if (fault === "paused-company") company.status = "paused";
|
||||
if (fault === "pause-reason") agent.pauseReason = "budget_unpriced";
|
||||
if (fault === "budget-changed") agent.budgetMonthlyCents = 0;
|
||||
if (fault === "pending") run.costAccountingPending = true;
|
||||
if (fault === "missing-settlement") delete run.costAccountedAt;
|
||||
if (fault === "missing-price") { usage.costUsd = null; usage.costUsdExact = null; }
|
||||
if (fault === "estimated") usage.costStatus = "estimated";
|
||||
if (fault === "partial") usage.costStatus = "unpriced";
|
||||
if (fault === "wrong-biller") usage.biller = "openai";
|
||||
if (fault === "wrong-provenance") usage.pricingProvenance = { source: "model_prices" };
|
||||
if (fault === "mismatched-exact") usage.costUsdExact = "0.040000000";
|
||||
if (fault === "unknown-tokens") delete usage.inputTokens;
|
||||
const paths: string[] = [];
|
||||
const receipt = await captureHermesOpenRouterSettlement({ companyId: "company", agentId: "agent", issueId: "task", runId: "run", api: {
|
||||
async get<T>(url: string) { paths.push(url); return (url === "/api/companies/company" ? company : url === "/api/agents/agent" ? agent : run) as T; },
|
||||
} });
|
||||
expect(new Set(paths)).toEqual(new Set(["/api/companies/company", "/api/agents/agent", "/api/heartbeat-runs/run"]));
|
||||
expect(receipt.checks.every(check => check.passed)).toBe(["valid", "reported-zero"].includes(fault));
|
||||
});
|
||||
it.each(["valid", "missing", "duplicate", "company", "provider", "method", "ownership", "status", "owner", "caller"])("establishes the expected user from public account readback: %s", async fault => {
|
||||
const account = { id: "account", companyId: "company", provider: "xai", method: "api_key", ownership: "personal", ownerUserId: "user", status: "connected" };
|
||||
if (fault === "company") account.companyId = "foreign";
|
||||
|
||||
@@ -53,6 +53,37 @@ export async function captureHermesApiBudgets(input: {
|
||||
] };
|
||||
}
|
||||
|
||||
/** Observe settled billing and budget health before fixture cleanup pauses the agent. */
|
||||
export async function captureHermesOpenRouterSettlement(input: {
|
||||
api: { get<T>(path: string): Promise<T> }; companyId: string; agentId: string; issueId: string; runId: string;
|
||||
}) {
|
||||
const [company, agent, run] = await Promise.all([
|
||||
input.api.get<Record<string, unknown>>(`/api/companies/${input.companyId}`),
|
||||
input.api.get<Record<string, unknown>>(`/api/agents/${input.agentId}`),
|
||||
input.api.get<Record<string, unknown>>(`/api/heartbeat-runs/${input.runId}`),
|
||||
]);
|
||||
const usage = record(run.usageJson), provenance = record(usage.pricingProvenance);
|
||||
const cost = usage.costUsd, exact = usage.costUsdExact;
|
||||
return { observation: {
|
||||
company: { id: company.id, status: company.status, pauseReason: company.pauseReason, budgetMonthlyCents: company.budgetMonthlyCents },
|
||||
agent: { id: agent.id, companyId: agent.companyId, status: agent.status, pauseReason: agent.pauseReason, budgetMonthlyCents: agent.budgetMonthlyCents },
|
||||
run: { id: run.id, companyId: run.companyId, agentId: run.agentId, issueId: run.issueId, status: run.status,
|
||||
costAccountingPending: run.costAccountingPending, costAccountedAt: run.costAccountedAt,
|
||||
usage: Object.fromEntries(["provider", "biller", "billingType", "costStatus", "costUsd", "costUsdExact", "inputTokens", "outputTokens", "accountingReceiptReady", "pricingProvenance"].map(key => [key, usage[key]])) },
|
||||
}, checks: [
|
||||
{ id: "billing-observation-scope", passed: company.id === input.companyId && agent.id === input.agentId && agent.companyId === input.companyId
|
||||
&& run.id === input.runId && run.companyId === input.companyId && run.agentId === input.agentId && run.issueId === input.issueId },
|
||||
{ id: "settled-openrouter-reported-cost", passed: run.status === "succeeded" && run.costAccountingPending === false && present(run.costAccountedAt)
|
||||
&& usage.accountingReceiptReady === true && usage.biller === "openrouter" && usage.billingType === "metered_api" && usage.costStatus === "reported"
|
||||
&& provenance.source === "provider_reported" && provenance.version === "hermes-openrouter-wire/v1"
|
||||
&& typeof cost === "number" && Number.isFinite(cost) && cost >= 0 && typeof exact === "string" && /^(0|[1-9][0-9]{0,6})\.[0-9]{9}$/.test(exact) && Number(exact) === cost
|
||||
&& typeof usage.inputTokens === "number" && Number.isSafeInteger(usage.inputTokens) && usage.inputTokens >= 0
|
||||
&& typeof usage.outputTokens === "number" && Number.isSafeInteger(usage.outputTokens) && usage.outputTokens >= 0 && usage.inputTokens + usage.outputTokens > 0 },
|
||||
{ id: "budget-health-after-settlement", passed: company.status === "active" && company.pauseReason === null && agent.status === "idle" && agent.pauseReason === null
|
||||
&& company.budgetMonthlyCents === HERMES_API_CONNECTION_BUDGET_CENTS && agent.budgetMonthlyCents === HERMES_API_CONNECTION_BUDGET_CENTS },
|
||||
] };
|
||||
}
|
||||
|
||||
/** Grade public run/account/model metadata; a model's completion claim cannot supply it. */
|
||||
export function gradeHermesApiConnection(input: {
|
||||
companyId: string; agentId: string; issueId: string; connectionId: string; provider: string; model: string; expectedResponsibleUserId: string;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { runPlanTaskFlow } from "./plan-task-flow.js";
|
||||
import { captureHermesApiAccountOwner, captureHermesApiBudgets, gradeHermesApiConnection, isHermesConnectionSuite } from "./hermes-api-connections.js";
|
||||
import { captureHermesApiAccountOwner, captureHermesApiBudgets, captureHermesOpenRouterSettlement, gradeHermesApiConnection, isHermesConnectionSuite } from "./hermes-api-connections.js";
|
||||
import { assertNativeCompletionSelection, NATIVE_COMPLETION_PREFLIGHT_ENV, verifyNativeCompletionPreflight } from "./native-completion-admission.js";
|
||||
import { assertNativeInstructionSelection, verifyNativeInstructionPreflight, NATIVE_INSTRUCTION_PREFLIGHT_ENV, NATIVE_INSTRUCTION_SUITE, NATIVE_INSTRUCTION_DEFAULT_SHA256 } from "./native-instruction-consolidation.js";
|
||||
import { captureNativeDefault, gradeNativeDefault, nativeCompletionWorkspaceDigest } from "./native-completion-defaults.js";
|
||||
@@ -2895,6 +2895,23 @@ for (const execution of executions) {
|
||||
{ id: "account-owner-preserved", passed: after.expectedResponsibleUserId === hermesApiAccountOwner.expectedResponsibleUserId });
|
||||
await writeSanitizedJson(snapshotsDir, "hermes-api-owner-after-execution.json", after, secrets);
|
||||
}
|
||||
if (fixtures.aiConnection.binding.provider === "openrouter") {
|
||||
const settlementScope = { companyId: fixtures.company.id, agentId: fixtures.agent.id, issueId: issue.id,
|
||||
runId: selectedRuns[0]?.id ?? "missing" };
|
||||
let receipt: Awaited<ReturnType<typeof captureHermesOpenRouterSettlement>> | undefined;
|
||||
try {
|
||||
await expect.poll(async () => {
|
||||
receipt = await captureHermesOpenRouterSettlement({ api, ...settlementScope });
|
||||
return receipt.checks.every(check => check.passed);
|
||||
}, { timeout: 30_000, message: "OpenRouter billing must settle without pausing the agent before cleanup" }).toBe(true);
|
||||
} finally {
|
||||
if (receipt) {
|
||||
await writeSanitizedJson(snapshotsDir, "hermes-openrouter-settlement.json", receipt, secrets);
|
||||
matcherResults.push(...receipt.checks.map(check => ({ matcher: { kind: "json_path" as const, path: `hermesBilling.${check.id}`, expected: true },
|
||||
passed: check.passed, detail: "Public reported cost and company/agent budget health must pass before teardown." })));
|
||||
}
|
||||
}
|
||||
}
|
||||
matcherResults.push(...checks.map(check => ({ matcher: { kind: "json_path" as const, path: `hermesConnection.${check.id}`, expected: true }, passed: check.passed, detail: "Public native run metadata must match the selected managed API account and exact model." })));
|
||||
await writeSanitizedJson(snapshotsDir, "hermes-api-connection.json", { checks }, secrets);
|
||||
expect(checks.every(check => check.passed), "Hermes managed account and native model attribution").toBe(true);
|
||||
|
||||
Reference in new issue
Block a user