@tangle-network/agent-eval 0.145.22 → 0.147.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +34 -0
- package/dist/analyst/index.d.ts +13 -13
- package/dist/analyst/index.js +6 -6
- package/dist/{backend-integrity-HVmWyOaX.d.ts → backend-integrity-Bz8nSrRE.d.ts} +2 -2
- package/dist/{backend-integrity-HVmWyOaX.d.ts.map → backend-integrity-Bz8nSrRE.d.ts.map} +1 -1
- package/dist/{benchmark-DTQ1RApl.d.ts → benchmark-Cn7ZMFNW.d.ts} +3 -3
- package/dist/{benchmark-DTQ1RApl.d.ts.map → benchmark-Cn7ZMFNW.d.ts.map} +1 -1
- package/dist/{benchmark-command-CDB_yKqS.js → benchmark-command-BTiysiYU.js} +11 -11
- package/dist/{benchmark-command-CDB_yKqS.js.map → benchmark-command-BTiysiYU.js.map} +1 -1
- package/dist/benchmarks/index.d.ts +4 -4
- package/dist/benchmarks/index.js +3 -3
- package/dist/campaign/index.d.ts +8 -8
- package/dist/campaign/index.js +5 -5
- package/dist/{campaign-CbQXcARJ.js → campaign-DCDdhuv2.js} +7 -7
- package/dist/{campaign-CbQXcARJ.js.map → campaign-DCDdhuv2.js.map} +1 -1
- package/dist/{capture-fetch-BZiO2cEH.d.ts → capture-fetch-BAx3Gntt.d.ts} +2 -2
- package/dist/{capture-fetch-BZiO2cEH.d.ts.map → capture-fetch-BAx3Gntt.d.ts.map} +1 -1
- package/dist/{chat-client-BJmwfnjN.js → chat-client-BX8Wh3fn.js} +3 -3
- package/dist/{chat-client-BJmwfnjN.js.map → chat-client-BX8Wh3fn.js.map} +1 -1
- package/dist/cli.js +2 -2
- package/dist/{client-YDkU5QST.d.ts → client-BV7icIfy.d.ts} +2 -2
- package/dist/{client-YDkU5QST.d.ts.map → client-BV7icIfy.d.ts.map} +1 -1
- package/dist/contract/index.d.ts +10 -10
- package/dist/contract/index.js +9 -9
- package/dist/{cost-ledger-BSe92yAV.js → cost-ledger-B1qx30B4.js} +2 -2
- package/dist/{cost-ledger-BSe92yAV.js.map → cost-ledger-B1qx30B4.js.map} +1 -1
- package/dist/{default-registry-DONui3mA.d.ts → default-registry-BUtRMRKk.d.ts} +6 -6
- package/dist/{default-registry-DONui3mA.d.ts.map → default-registry-BUtRMRKk.d.ts.map} +1 -1
- package/dist/{define-agent-eval-BGxmy4W6.js → define-agent-eval-BqWFz3sK.js} +3 -3
- package/dist/{define-agent-eval-BGxmy4W6.js.map → define-agent-eval-BqWFz3sK.js.map} +1 -1
- package/dist/{define-agent-eval-DrpgTVPp.d.ts → define-agent-eval-D52ClbX2.d.ts} +5 -5
- package/dist/{define-agent-eval-DrpgTVPp.d.ts.map → define-agent-eval-D52ClbX2.d.ts.map} +1 -1
- package/dist/{dspy-rlm-engine-B2nst4NR.js → dspy-rlm-engine-BmtOl_kP.js} +4 -4
- package/dist/{dspy-rlm-engine-B2nst4NR.js.map → dspy-rlm-engine-BmtOl_kP.js.map} +1 -1
- package/dist/{engine-Bc3seRPe.d.ts → engine-CIy18RTX.d.ts} +4 -4
- package/dist/{engine-Bc3seRPe.d.ts.map → engine-CIy18RTX.d.ts.map} +1 -1
- package/dist/{eval-campaign-DeGLwACc.js → eval-campaign-bmZ6NIIP.js} +2 -2
- package/dist/{eval-campaign-DeGLwACc.js.map → eval-campaign-bmZ6NIIP.js.map} +1 -1
- package/dist/{exact-types-CYFbvA5U.d.ts → exact-types-rdKFzEnK.d.ts} +2 -2
- package/dist/{exact-types-CYFbvA5U.d.ts.map → exact-types-rdKFzEnK.d.ts.map} +1 -1
- package/dist/experiment/index.d.ts +5 -5
- package/dist/experiment/index.js +3 -3
- package/dist/{experiment-tracker-DWHZBAYL.d.ts → experiment-tracker-D9VHwRm-.d.ts} +6 -24
- package/dist/experiment-tracker-D9VHwRm-.d.ts.map +1 -0
- package/dist/{experiment-tracker-C29gXM4B.js → experiment-tracker-Ym6rEQT1.js} +15 -4
- package/dist/experiment-tracker-Ym6rEQT1.js.map +1 -0
- package/dist/{external-optimizer-contracts-CKEY98bK.d.ts → external-optimizer-contracts-CSjDLLmr.d.ts} +2 -2
- package/dist/{external-optimizer-contracts-CKEY98bK.d.ts.map → external-optimizer-contracts-CSjDLLmr.d.ts.map} +1 -1
- package/dist/{external-optimizer-process-DYNizz8W.js → external-optimizer-process-C4AyCcQd.js} +2 -2
- package/dist/{external-optimizer-process-DYNizz8W.js.map → external-optimizer-process-C4AyCcQd.js.map} +1 -1
- package/dist/{external-optimizer-subprocess-r6dP9DAj.js → external-optimizer-subprocess-DU1KM8yV.js} +3 -3
- package/dist/{external-optimizer-subprocess-r6dP9DAj.js.map → external-optimizer-subprocess-DU1KM8yV.js.map} +1 -1
- package/dist/{feedback-trajectory-Cg9EDxKB.d.ts → feedback-trajectory-niGeR6uJ.d.ts} +3 -3
- package/dist/{feedback-trajectory-Cg9EDxKB.d.ts.map → feedback-trajectory-niGeR6uJ.d.ts.map} +1 -1
- package/dist/fuzz.js +1 -1
- package/dist/hosted/index.d.ts +2 -2
- package/dist/{index-DGrcBMbC.d.ts → index-BjBjxiVv.d.ts} +9 -9
- package/dist/{index-DGrcBMbC.d.ts.map → index-BjBjxiVv.d.ts.map} +1 -1
- package/dist/index-CKblBxtr.d.ts +1 -0
- package/dist/{index-CevPFhDT.d.ts → index-gtjtfLEJ.d.ts} +7 -7
- package/dist/{index-CevPFhDT.d.ts.map → index-gtjtfLEJ.d.ts.map} +1 -1
- package/dist/index.d.ts +21 -51
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +16 -125
- package/dist/index.js.map +1 -1
- package/dist/{integrity-DDoeWibF.d.ts → integrity-CGfpTE5-.d.ts} +2 -2
- package/dist/{integrity-DDoeWibF.d.ts.map → integrity-CGfpTE5-.d.ts.map} +1 -1
- package/dist/{kind-factory-CPmSd58s.js → kind-factory-DmAa0h3K.js} +7 -7
- package/dist/kind-factory-DmAa0h3K.js.map +1 -0
- package/dist/{llm-client-_UE4fU7Z.js → llm-client-BMuxYoZy.js} +2 -2
- package/dist/{llm-client-_UE4fU7Z.js.map → llm-client-BMuxYoZy.js.map} +1 -1
- package/dist/{llm-judge-B7ffRF8w.js → llm-judge-DrzsVS5k.js} +4 -4
- package/dist/{llm-judge-B7ffRF8w.js.map → llm-judge-DrzsVS5k.js.map} +1 -1
- package/dist/matrix-C-2Qx1Zr.d.ts +383 -0
- package/dist/matrix-C-2Qx1Zr.d.ts.map +1 -0
- package/dist/meta-eval/index.d.ts +1 -1
- package/dist/{metrics-Cl0L1KUy.js → metrics-Qv-cpptD.js} +15 -8
- package/dist/metrics-Qv-cpptD.js.map +1 -0
- package/dist/multishot/golden/index.d.ts +230 -0
- package/dist/multishot/golden/index.d.ts.map +1 -0
- package/dist/multishot/golden/index.js +7686 -0
- package/dist/multishot/golden/index.js.map +1 -0
- package/dist/multishot/index.d.ts +2 -380
- package/dist/multishot/index.d.ts.map +1 -1
- package/dist/multishot/index.js +2 -106
- package/dist/multishot/index.js.map +1 -1
- package/dist/openapi.json +1 -1
- package/dist/{produced-state-D3k45S9a.js → produced-state-Dtx60bUQ.js} +4 -4
- package/dist/{produced-state-D3k45S9a.js.map → produced-state-Dtx60bUQ.js.map} +1 -1
- package/dist/{promotion-policy-BKi5OK5l.d.ts → promotion-policy-CewdjfCJ.d.ts} +2 -2
- package/dist/{promotion-policy-BKi5OK5l.d.ts.map → promotion-policy-CewdjfCJ.d.ts.map} +1 -1
- package/dist/{provenance-Bb7Zmyj2.d.ts → provenance-LrOEOHQb.d.ts} +6 -6
- package/dist/{provenance-Bb7Zmyj2.d.ts.map → provenance-LrOEOHQb.d.ts.map} +1 -1
- package/dist/{registry-CZgEmVXb.d.ts → registry-CaqJIDdN.d.ts} +4 -4
- package/dist/{registry-CZgEmVXb.d.ts.map → registry-CaqJIDdN.d.ts.map} +1 -1
- package/dist/reporting.d.ts +1 -1
- package/dist/reporting.js +1 -1
- package/dist/{researcher-CC305Ed-.d.ts → researcher-BySlpla_.d.ts} +3 -3
- package/dist/{researcher-CC305Ed-.d.ts.map → researcher-BySlpla_.d.ts.map} +1 -1
- package/dist/rl.d.ts +3 -3
- package/dist/rl.js +2 -2
- package/dist/{semantic-concept-judge-BsY2Q0Oq.js → semantic-concept-judge-BI7Rrl5-.js} +3 -3
- package/dist/{semantic-concept-judge-BsY2Q0Oq.js.map → semantic-concept-judge-BI7Rrl5-.js.map} +1 -1
- package/dist/{sequential-CYwq6Ff_.d.ts → sequential-BhsrMupG.d.ts} +31 -2
- package/dist/sequential-BhsrMupG.d.ts.map +1 -0
- package/dist/{sequential-Br0mAPHA.js → sequential-CzK5DarL.js} +48 -6
- package/dist/sequential-CzK5DarL.js.map +1 -0
- package/dist/series-convergence-CjO2QdRW.js.map +1 -1
- package/dist/{series-convergence-C9G-GNYK.d.ts → series-convergence-D2fsoJ2w.d.ts} +4 -7
- package/dist/{series-convergence-C9G-GNYK.d.ts.map → series-convergence-D2fsoJ2w.d.ts.map} +1 -1
- package/dist/{server-cQXve8i4.js → server-D9wQclzG.js} +3 -3
- package/dist/{server-cQXve8i4.js.map → server-D9wQclzG.js.map} +1 -1
- package/dist/{skillopt-optimization-method-C9MrMgW9.d.ts → skillopt-optimization-method-BoC1Qccx.d.ts} +5 -5
- package/dist/{skillopt-optimization-method-C9MrMgW9.d.ts.map → skillopt-optimization-method-BoC1Qccx.d.ts.map} +1 -1
- package/dist/{skillopt-optimization-method-Cv3K4DaS.js → skillopt-optimization-method-C_UrqZs2.js} +4 -4
- package/dist/{skillopt-optimization-method-Cv3K4DaS.js.map → skillopt-optimization-method-C_UrqZs2.js.map} +1 -1
- package/dist/{statistical-heldout-fvxtHnKQ.d.ts → statistical-heldout-uxSpFEjm.d.ts} +2 -2
- package/dist/{statistical-heldout-fvxtHnKQ.d.ts.map → statistical-heldout-uxSpFEjm.d.ts.map} +1 -1
- package/dist/{store-otlp-CsptLYpN.js → store-otlp-CDYWW_8N.js} +2 -2
- package/dist/{store-otlp-CsptLYpN.js.map → store-otlp-CDYWW_8N.js.map} +1 -1
- package/dist/{store-tool-spans-Cq9mFd-q.js → store-tool-spans-CykkbOlv.js} +3 -3
- package/dist/{store-tool-spans-Cq9mFd-q.js.map → store-tool-spans-CykkbOlv.js.map} +1 -1
- package/dist/{store-tool-spans-CV0hRsUp.d.ts → store-tool-spans-D5FhM0_A.d.ts} +4 -4
- package/dist/{store-tool-spans-CV0hRsUp.d.ts.map → store-tool-spans-D5FhM0_A.d.ts.map} +1 -1
- package/dist/{task-failure-attributes-CpQ4y5RD.js → task-failure-attributes--ZTP3tYO.js} +2 -2
- package/dist/{task-failure-attributes-CpQ4y5RD.js.map → task-failure-attributes--ZTP3tYO.js.map} +1 -1
- package/dist/{tool-groups-CDDXNKhd.d.ts → tool-groups-zpufabP8.d.ts} +3 -3
- package/dist/tool-groups-zpufabP8.d.ts.map +1 -0
- package/dist/trace-repair/index.d.ts +1 -1
- package/dist/traces.d.ts +7 -7
- package/dist/traces.js +4 -4
- package/dist/types-B3jzCp0p.js +108 -0
- package/dist/types-B3jzCp0p.js.map +1 -0
- package/dist/{types-oAsa-fs4.d.ts → types-BohHewKK.d.ts} +2 -2
- package/dist/{types-oAsa-fs4.d.ts.map → types-BohHewKK.d.ts.map} +1 -1
- package/dist/{types-DABZgDGV.d.ts → types-C1Bmeb8X.d.ts} +3 -3
- package/dist/{types-DABZgDGV.d.ts.map → types-C1Bmeb8X.d.ts.map} +1 -1
- package/dist/{types-CWcPguwd.d.ts → types-ColZlZtc.d.ts} +2 -2
- package/dist/{types-CWcPguwd.d.ts.map → types-ColZlZtc.d.ts.map} +1 -1
- package/dist/{types-XBRdmbj8.d.ts → types-DOhGq4S1.d.ts} +1 -7
- package/dist/{types-XBRdmbj8.d.ts.map → types-DOhGq4S1.d.ts.map} +1 -1
- package/dist/wire/index.d.ts +2 -2
- package/dist/wire/index.js +1 -1
- package/docs/multishot-golden-records.md +102 -0
- package/package.json +7 -2
- package/dist/experiment-tracker-C29gXM4B.js.map +0 -1
- package/dist/experiment-tracker-DWHZBAYL.d.ts.map +0 -1
- package/dist/index-BgHYx1QG.d.ts +0 -1
- package/dist/kind-factory-CPmSd58s.js.map +0 -1
- package/dist/metrics-Cl0L1KUy.js.map +0 -1
- package/dist/sequential-Br0mAPHA.js.map +0 -1
- package/dist/sequential-CYwq6Ff_.d.ts.map +0 -1
- package/dist/tool-groups-CDDXNKhd.d.ts.map +0 -1
package/dist/cli.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { o as runRolloutReleaseCli } from "./hf-dataset-XggBupCr.js";
|
|
3
|
-
import { n as runAnalystBenchmarkCommand } from "./benchmark-command-
|
|
4
|
-
import { a as runRpcBatch, o as runRpcOnce, p as handleVersion, r as startServerAsync, s as buildOpenApi } from "./server-
|
|
3
|
+
import { n as runAnalystBenchmarkCommand } from "./benchmark-command-BTiysiYU.js";
|
|
4
|
+
import { a as runRpcBatch, o as runRpcOnce, p as handleVersion, r as startServerAsync, s as buildOpenApi } from "./server-D9wQclzG.js";
|
|
5
5
|
import { writeFileSync } from "node:fs";
|
|
6
6
|
//#region src/cli-config.ts
|
|
7
7
|
function resolveCliLlmConfig(env = process.env) {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { l as RunTerminalOutcome } from "./run-record-DVV82Gwh.js";
|
|
2
|
-
import { _ as GateDecision, j as MutableSurface } from "./types-
|
|
2
|
+
import { _ as GateDecision, j as MutableSurface } from "./types-C1Bmeb8X.js";
|
|
3
3
|
import { o as InsightReport } from "./insight-report-BeT8KCgI.js";
|
|
4
4
|
//#region src/hosted/types.d.ts
|
|
5
5
|
declare const HOSTED_WIRE_VERSION: '2026-07-24.v1';
|
|
@@ -199,4 +199,4 @@ declare function hostedClientFromEnv(overrides?: Partial<HostedTenant> & {
|
|
|
199
199
|
}): HostedClient | undefined;
|
|
200
200
|
//#endregion
|
|
201
201
|
export { UnixNanoTimestamp as _, hostedTenantFromEnv as a, EvalRunGenerationSnapshot as c, HostedIngestHeaders as d, HostedWireVersion as f, TraceSpanEvent as g, IngestTracesRequest as h, hostedClientFromEnv as i, EvalRunStatus as l, IngestResponse as m, HostedTenant as n, EvalRunCellScore as o, IngestEvalRunsRequest as p, createHostedClient as r, EvalRunEvent as s, HostedClient as t, HOSTED_WIRE_VERSION as u };
|
|
202
|
-
//# sourceMappingURL=client-
|
|
202
|
+
//# sourceMappingURL=client-BV7icIfy.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client-
|
|
1
|
+
{"version":3,"file":"client-BV7icIfy.d.ts","names":[],"sources":["../src/hosted/types.ts","../src/hosted/client.ts"],"mappings":";;;;cAgCa;KACD,2BAA2B;;UAKtB;;EAEf;;EAEA;;EAEA,yBAAyB;;EAEzB;;;KAMU;UAQK;;EAEf;;EAEA;;EAEA;;EAEA,YAAY,eAAe;;EAE3B,iBAAiB;;EAEjB;;EAEA;;UAGe;;EAEf;;;EAGA;;;EAGA,UAAU;;EAEV,OAAO;;EAEP;;EAEA;;EAEA;;;;;;;UAQe;;EAEf;;EAEA;;EAEA;;EAEA,QAAQ;;EAER,QAAQ;;EAER,WAAW;;EAEX,aAAa;;EAEb,eAAe;;EAEf;;EAEA;;EAEA;;EAEA;;;;;;EAMA,gBAAgB;;;;;;KASN;;;;;;UAOK;EACf;EACA;EACA;EACA;EACA,mBAAmB;EACnB,iBAAiB;EACjB,YAAY;EACZ,SAAS;IACP,cAAc;IACd;IACA,aAAa;;EAEf;IAAW;IAAgC;;;EAE3C;;EAEA;;EAEA;;EAEA;;UAKe;EACf,aAAa;EACb,QAAQ;;UAGO;EACf,aAAa;EACb,OAAO;;UAGQ;;EAEf;;EAEA,UAAU;IAAQ;IAAe;;;;;UC1JlB;;EAEf;;EAEA;;EAEA;;EAEA,mBAAmB;;EAEnB;;EAEA;;UAGe;EACf,cAAc,OAAO,cAAc,0BAA0B,QAAQ;EACrE,eAAe,QAAQ,gBAAgB,0BAA0B,QAAQ;EACzE,aAAa,OAAO,kBAAkB,0BAA0B,QAAQ;WAC/D,QAAQ;WACR,aAAa;;iBAyGR,mBAAmB,QAAQ,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAsE1C,oBACd,YAAW,QAAQ;EAAkB,MAAM;IAC1C;iBAiBa,oBACd,YAAW,QAAQ;EAAkB,MAAM;IAC1C"}
|
package/dist/contract/index.d.ts
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
1
1
|
import { c as CostLedgerHandle } from "../cost-ledger-DbQdN3nO.js";
|
|
2
2
|
import { a as RunRecord, n as RunCostProvenance, s as RunSplitTag } from "../run-record-DVV82Gwh.js";
|
|
3
|
-
import { p as ChatClient, v as CreateChatClientOpts, w as createChatClient } from "../types-
|
|
4
|
-
import { _ as ProposalFinding, i as AnalystFinding, v as ProposalFindingOrigin, x as makeProposalFinding } from "../types-
|
|
5
|
-
import { n as buildDefaultAnalystRegistry, t as DefaultAnalystRegistryOptions } from "../default-registry-
|
|
6
|
-
import { C as JudgeDimension, H as SurfaceProposer, M as OptimizerConfig, R as Scenario, S as JudgeConfig, V as SessionScript, _ as GateDecision, a as CampaignResult, b as GenerationRecord, c as CampaignTraceWriter, d as DispatchContext, f as DispatchFn, g as GateContribution, h as GateContext, i as CampaignCostMeter, j as MutableSurface, l as CodeSurface, m as GateCheckStatus, n as CampaignArtifactWriter, p as Gate, r as CampaignCellResult, t as CampaignAggregates, v as GateResult, w as JudgeScore, y as GenerationCandidate } from "../types-
|
|
3
|
+
import { p as ChatClient, v as CreateChatClientOpts, w as createChatClient } from "../types-DOhGq4S1.js";
|
|
4
|
+
import { _ as ProposalFinding, i as AnalystFinding, v as ProposalFindingOrigin, x as makeProposalFinding } from "../types-BohHewKK.js";
|
|
5
|
+
import { n as buildDefaultAnalystRegistry, t as DefaultAnalystRegistryOptions } from "../default-registry-BUtRMRKk.js";
|
|
6
|
+
import { C as JudgeDimension, H as SurfaceProposer, M as OptimizerConfig, R as Scenario, S as JudgeConfig, V as SessionScript, _ as GateDecision, a as CampaignResult, b as GenerationRecord, c as CampaignTraceWriter, d as DispatchContext, f as DispatchFn, g as GateContribution, h as GateContext, i as CampaignCostMeter, j as MutableSurface, l as CodeSurface, m as GateCheckStatus, n as CampaignArtifactWriter, p as Gate, r as CampaignCellResult, t as CampaignAggregates, v as GateResult, w as JudgeScore, y as GenerationCandidate } from "../types-C1Bmeb8X.js";
|
|
7
7
|
import { a as FailureClusterInsight, c as JudgeInsight, d as Recommendation, f as ReleaseSummary, i as FailureClassTally, l as LiftInsight, m as TokenUsageInsight, n as ExecutionErrorOutcomeCell, o as InsightReport, p as ScalarDistribution, r as ExecutionInsight, s as InterRaterInsight, t as CostProvenanceSummary, u as OutcomeCorrelationInsight } from "../insight-report-BeT8KCgI.js";
|
|
8
|
-
import { C as analyzeRuns, S as SummarizeExecutionOptions, b as AnalyzeRunsOptions, w as summarizeExecution, x as ExecutionReport } from "../engine-
|
|
9
|
-
import { $ as OptimizationTokenUsage, D as runEval, Dt as fsCampaignStorage, E as RunEvalOptions, G as OptimizationMethodComparison, H as CompareOptimizationMethodsOptions, J as OptimizationMethodProvenance, K as OptimizationMethodInput, Mt as LlmJudgeDimension, Nt as LlmJudgeOptions, Ot as inMemoryCampaignStorage, Pt as llmJudge, Q as OptimizationPackageSource, Tt as CampaignStorage, U as ComparisonCost, W as OptimizationMethod, Y as OptimizationMethodResult, b as RunImprovementLoopResult, bt as runCampaign, tt as compareOptimizationMethods, vt as CampaignCellFailureReceipt, x as runImprovementLoop, y as RunImprovementLoopOptions, yt as RunCampaignOptions } from "../provenance-
|
|
10
|
-
import { B as runReferenceEquivalenceJudge, C as ExternalTextOptimizerContext, E as ExternalTextEvaluationResponse, F as ReferenceEquivalenceJudgeInput, I as ReferenceEquivalenceJudgeOptions, L as ReferenceEquivalenceJudgeResult, N as REFERENCE_EQUIVALENCE_INPUT_LIMITS, P as REFERENCE_EQUIVALENCE_JUDGE_VERSION, R as ReferenceEquivalenceScenario, S as ExternalTextOptimizationMethodConfig, T as ExternalOptimizationExample, _ as DefaultProductionGateOptions, a as GepaAdaptiveEngineRun, b as composeGate, c as GepaOptimizationMethodConfig, d as gepaOptimizationMethod, f as OpenAICompatibleOptimizerModel, g as DefaultProductionGateCheck, h as heldOutGate, i as skillOptOptimizationMethod, j as campaignSplitDigest, l as GepaOptimizationRecipe, m as HeldOutGateOptions, n as SkillOptRunnerCommand, o as GepaEngineOptions, p as OptimizerModelBudget, r as SkillOptTrainerConfig, s as GepaEngineRun, t as SkillOptOptimizationMethodConfig, u as GepaRunnerCommand, v as DefaultProductionRewardHackingOptions, w as ExternalTextOptimizerResult, x as externalTextOptimizationMethod, y as defaultProductionGate, z as createReferenceEquivalenceJudge } from "../skillopt-optimization-method-
|
|
11
|
-
import { a as ObjectiveSource, c as PromotionPolicy, d as paretoSignificanceGate, i as EvidenceVector, l as buildEvidenceVector, n as AxisVerdict, o as ParetoSignificanceGateOptions, r as BuildEvidenceVectorOptions, s as PromotionObjective, t as AxisEvidence, u as paretoPolicy } from "../promotion-policy-
|
|
12
|
-
import { c as EvalRunGenerationSnapshot, g as TraceSpanEvent, n as HostedTenant, o as EvalRunCellScore, s as EvalRunEvent } from "../client-
|
|
8
|
+
import { C as analyzeRuns, S as SummarizeExecutionOptions, b as AnalyzeRunsOptions, w as summarizeExecution, x as ExecutionReport } from "../engine-CIy18RTX.js";
|
|
9
|
+
import { $ as OptimizationTokenUsage, D as runEval, Dt as fsCampaignStorage, E as RunEvalOptions, G as OptimizationMethodComparison, H as CompareOptimizationMethodsOptions, J as OptimizationMethodProvenance, K as OptimizationMethodInput, Mt as LlmJudgeDimension, Nt as LlmJudgeOptions, Ot as inMemoryCampaignStorage, Pt as llmJudge, Q as OptimizationPackageSource, Tt as CampaignStorage, U as ComparisonCost, W as OptimizationMethod, Y as OptimizationMethodResult, b as RunImprovementLoopResult, bt as runCampaign, tt as compareOptimizationMethods, vt as CampaignCellFailureReceipt, x as runImprovementLoop, y as RunImprovementLoopOptions, yt as RunCampaignOptions } from "../provenance-LrOEOHQb.js";
|
|
10
|
+
import { B as runReferenceEquivalenceJudge, C as ExternalTextOptimizerContext, E as ExternalTextEvaluationResponse, F as ReferenceEquivalenceJudgeInput, I as ReferenceEquivalenceJudgeOptions, L as ReferenceEquivalenceJudgeResult, N as REFERENCE_EQUIVALENCE_INPUT_LIMITS, P as REFERENCE_EQUIVALENCE_JUDGE_VERSION, R as ReferenceEquivalenceScenario, S as ExternalTextOptimizationMethodConfig, T as ExternalOptimizationExample, _ as DefaultProductionGateOptions, a as GepaAdaptiveEngineRun, b as composeGate, c as GepaOptimizationMethodConfig, d as gepaOptimizationMethod, f as OpenAICompatibleOptimizerModel, g as DefaultProductionGateCheck, h as heldOutGate, i as skillOptOptimizationMethod, j as campaignSplitDigest, l as GepaOptimizationRecipe, m as HeldOutGateOptions, n as SkillOptRunnerCommand, o as GepaEngineOptions, p as OptimizerModelBudget, r as SkillOptTrainerConfig, s as GepaEngineRun, t as SkillOptOptimizationMethodConfig, u as GepaRunnerCommand, v as DefaultProductionRewardHackingOptions, w as ExternalTextOptimizerResult, x as externalTextOptimizationMethod, y as defaultProductionGate, z as createReferenceEquivalenceJudge } from "../skillopt-optimization-method-BoC1Qccx.js";
|
|
11
|
+
import { a as ObjectiveSource, c as PromotionPolicy, d as paretoSignificanceGate, i as EvidenceVector, l as buildEvidenceVector, n as AxisVerdict, o as ParetoSignificanceGateOptions, r as BuildEvidenceVectorOptions, s as PromotionObjective, t as AxisEvidence, u as paretoPolicy } from "../promotion-policy-CewdjfCJ.js";
|
|
12
|
+
import { c as EvalRunGenerationSnapshot, g as TraceSpanEvent, n as HostedTenant, o as EvalRunCellScore, s as EvalRunEvent } from "../client-BV7icIfy.js";
|
|
13
13
|
import { i as InMemoryOutcomeStore, n as FileSystemOutcomeStore, o as OutcomeStore, r as FileSystemOutcomeStoreOptions, t as DeploymentOutcome } from "../outcome-store-BYHIuO0e.js";
|
|
14
|
-
import { a as DefinedAgentEval, c as SelfImproveOptions, d as SelfImproveRunError, f as selfImprove, i as DefineAgentEvalOptions, l as SelfImproveProgressEvent, n as AgentEvalEvaluateOptions, o as defineAgentEval, r as AgentEvalImproveOptions, s as SelfImproveBudget, t as AgentEvalAgent, u as SelfImproveResult } from "../define-agent-eval-
|
|
14
|
+
import { a as DefinedAgentEval, c as SelfImproveOptions, d as SelfImproveRunError, f as selfImprove, i as DefineAgentEvalOptions, l as SelfImproveProgressEvent, n as AgentEvalEvaluateOptions, o as defineAgentEval, r as AgentEvalImproveOptions, s as SelfImproveBudget, t as AgentEvalAgent, u as SelfImproveResult } from "../define-agent-eval-D52ClbX2.js";
|
|
15
15
|
import { AgentCandidateBenchmarkCellRef, AgentCandidateBenchmarkSuiteInputs, AgentCandidateBenchmarkTask, AgentCandidateBenchmarkTaskMaterial, AgentCandidateBundle, AgentCandidateEvaluationPolicy, AgentCandidateExperiment, AgentCandidateExperimentMaterial, AgentCandidateExperimentMeasurement, AgentImprovementCost, AgentImprovementMeasuredComparison, AgentProfileImprovementExperiment, AgentProfileImprovementExperimentMaterial, AgentProfileImprovementMeasuredComparison, AgentProfileImprovementMeasurement, AgentProfileImprovementRunCell, AgentProfileImprovementRunReceipt, AgentProfileImprovementSuiteInputs, AgentProfileImprovementTask, AgentProfileImprovementTaskMaterial, CandidateExecutionEvidence, Sha256Digest } from "@tangle-network/agent-interface";
|
|
16
16
|
//#region src/contract/measured-comparison.d.ts
|
|
17
17
|
interface SealCandidateBenchmarkSuiteOptions {
|
package/dist/contract/index.js
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
1
|
import { s as ValidationError } from "../errors-Dngq5h35.js";
|
|
2
2
|
import { r as pairedBootstrap } from "../paired-tests-BHIhYVdu.js";
|
|
3
|
-
import { a as summarizeExecution, i as analyzeRuns, n as SelfImproveRunError, r as selfImprove, t as defineAgentEval } from "../define-agent-eval-
|
|
3
|
+
import { a as summarizeExecution, i as analyzeRuns, n as SelfImproveRunError, r as selfImprove, t as defineAgentEval } from "../define-agent-eval-BqWFz3sK.js";
|
|
4
4
|
import { a as parseRunRecordSafe } from "../run-record-D2lDdSAz.js";
|
|
5
|
-
import { G as runEval, K as runCampaign, f as runImprovementLoop, nt as campaignSplitDigest, t as llmJudge, x as compareOptimizationMethods, z as defaultProductionGate } from "../llm-judge-
|
|
6
|
-
import { i as isModelPriced, n as estimateCost } from "../metrics-
|
|
7
|
-
import { i as CostLedger } from "../cost-ledger-
|
|
5
|
+
import { G as runEval, K as runCampaign, f as runImprovementLoop, nt as campaignSplitDigest, t as llmJudge, x as compareOptimizationMethods, z as defaultProductionGate } from "../llm-judge-DrzsVS5k.js";
|
|
6
|
+
import { i as isModelPriced, n as estimateCost } from "../metrics-Qv-cpptD.js";
|
|
7
|
+
import { i as CostLedger } from "../cost-ledger-B1qx30B4.js";
|
|
8
8
|
import { d as mapConcurrentRange } from "../ledger-core-DTae9rv_.js";
|
|
9
|
-
import { S as inMemoryCampaignStorage, x as fsCampaignStorage } from "../external-optimizer-subprocess-
|
|
9
|
+
import { S as inMemoryCampaignStorage, x as fsCampaignStorage } from "../external-optimizer-subprocess-DU1KM8yV.js";
|
|
10
10
|
import { a as heldoutSignificance, s as decidePairedPromotion } from "../power-preflight-DEw-uC7q.js";
|
|
11
11
|
import { r as makeProposalFinding } from "../types-BI4fT3HN.js";
|
|
12
|
-
import { $ as classifyOtlpSpanRole, et as isOtlpModelCall } from "../kind-factory-
|
|
13
|
-
import { n as buildDefaultAnalystRegistry, t as createChatClient } from "../chat-client-
|
|
12
|
+
import { $ as classifyOtlpSpanRole, et as isOtlpModelCall } from "../kind-factory-DmAa0h3K.js";
|
|
13
|
+
import { n as buildDefaultAnalystRegistry, t as createChatClient } from "../chat-client-BX8Wh3fn.js";
|
|
14
14
|
import { LLM_MODEL_ATTR_KEYS, SPAN_KIND_ATTR_KEYS } from "../trace-attributes.js";
|
|
15
15
|
import { t as extractUsage } from "../extract-usage-BrQ8mCLX.js";
|
|
16
16
|
import { n as InMemoryOutcomeStore, t as FileSystemOutcomeStore } from "../outcome-store-ChBKlTd_.js";
|
|
17
|
-
import { i as summarizeTraceErrors, n as recordAggregateMeasurements, r as summarizeExecutionMeasurements, t as readTaskFailureLabels } from "../task-failure-attributes
|
|
18
|
-
import { a as externalTextOptimizationMethod, c as REFERENCE_EQUIVALENCE_INPUT_LIMITS, d as runReferenceEquivalenceJudge, i as composeGate, l as REFERENCE_EQUIVALENCE_JUDGE_VERSION, n as gepaOptimizationMethod, r as heldOutGate, t as skillOptOptimizationMethod, u as createReferenceEquivalenceJudge } from "../skillopt-optimization-method-
|
|
17
|
+
import { i as summarizeTraceErrors, n as recordAggregateMeasurements, r as summarizeExecutionMeasurements, t as readTaskFailureLabels } from "../task-failure-attributes--ZTP3tYO.js";
|
|
18
|
+
import { a as externalTextOptimizationMethod, c as REFERENCE_EQUIVALENCE_INPUT_LIMITS, d as runReferenceEquivalenceJudge, i as composeGate, l as REFERENCE_EQUIVALENCE_JUDGE_VERSION, n as gepaOptimizationMethod, r as heldOutGate, t as skillOptOptimizationMethod, u as createReferenceEquivalenceJudge } from "../skillopt-optimization-method-C_UrqZs2.js";
|
|
19
19
|
import { n as paretoPolicy, r as paretoSignificanceGate, t as buildEvidenceVector } from "../promotion-policy-xzA40Evo.js";
|
|
20
20
|
import { createHash } from "node:crypto";
|
|
21
21
|
import { agentCandidateBenchmarkSuiteSchema, agentCandidateBenchmarkTaskSchema, agentCandidateBundleSchema, agentCandidateEvaluationPolicySchema, agentCandidateExperimentSchema, agentImprovementMeasuredComparisonSchema, agentProfileImprovementExperimentSchema, agentProfileImprovementMeasuredComparisonSchema, agentProfileImprovementRunCellSchema, agentProfileImprovementRunReceiptSchema, agentProfileImprovementSuiteInputsSchema, agentProfileImprovementSuiteSchema, agentProfileImprovementTaskSchema, candidateExecutionEvidenceSchema, canonicalCandidateDigest, canonicalCandidateJson, numbersApproximatelyEqual, omitTopLevelDigest } from "@tangle-network/agent-interface";
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { s as ValidationError } from "./errors-Dngq5h35.js";
|
|
2
|
-
import { a as resolveModelPricing, i as isModelPriced, n as estimateCost } from "./metrics-
|
|
2
|
+
import { a as resolveModelPricing, i as isModelPriced, n as estimateCost } from "./metrics-Qv-cpptD.js";
|
|
3
3
|
import { z } from "zod";
|
|
4
4
|
//#region src/cost-ledger.ts
|
|
5
5
|
var CostCeilingReachedError = class extends ValidationError {
|
|
@@ -895,4 +895,4 @@ function assertString(value, name) {
|
|
|
895
895
|
//#endregion
|
|
896
896
|
export { CostLedgerPersistenceError as a, costForTokenPricing as c, CostLedger as i, costForUsage as l, CostCallConflictError as n, CostReceiptCaptureError as o, CostCeilingReachedError as r, CostReservationExceededError as s, CostAccountingIncompleteError as t, modelPriceKey as u };
|
|
897
897
|
|
|
898
|
-
//# sourceMappingURL=cost-ledger-
|
|
898
|
+
//# sourceMappingURL=cost-ledger-B1qx30B4.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cost-ledger-BSe92yAV.js","names":[],"sources":["../src/cost-ledger.ts"],"sourcesContent":["import { z } from 'zod'\nimport { ValidationError } from './errors'\nimport { estimateCost, isModelPriced, resolveModelPricing } from './metrics'\n\nexport type CostChannel = 'agent' | 'judge' | 'verifier' | 'analyst' | 'driver' | (string & {})\n\n/** How a USD amount was obtained. */\nexport type CostProvenance =\n | { kind: 'observed'; usd: number }\n | { kind: 'estimated'; usd: number }\n | { kind: 'uncaptured'; usd: null }\n\nexport interface CostUsage {\n inputTokens: number\n /** Includes reasoning tokens when the provider bills them as output. */\n outputTokens: number\n /** Reasoning-token subset of outputTokens, when reported. */\n reasoningTokens?: number\n /** Prompt tokens served from a provider cache. */\n cachedTokens?: number\n /** Prompt tokens written into a provider cache. */\n cacheWriteTokens?: number\n}\n\ninterface CostCallBase {\n callId: string\n channel: CostChannel\n phase: string\n actor: string\n model: string\n maximumCostUsd?: number\n tags?: Record<string, string>\n timestamp: number\n}\n\nexport interface PendingCostCall extends CostCallBase {\n status: 'pending'\n}\n\nexport interface PendingCostCallView extends PendingCostCall {\n state: 'active' | 'late' | 'interrupted'\n}\n\nexport interface CostReceipt extends CostCallBase, CostUsage {\n status: 'settled'\n costUsd: number\n costUnknown: boolean\n usageUnknown?: boolean\n /** Rates used to estimate cost locally. Absent when cost is provider-reported or unknown. */\n pricing?: {\n inputUsdPerThousand: number\n cachedInputUsdPerThousand?: number\n cacheWriteUsdPerThousand?: number\n outputUsdPerThousand: number\n }\n /** Cost reported by the provider, not a local token-price calculation. */\n actualCostUsd?: number\n /** Known non-provider amount supplied by an external executor. */\n estimatedCostUsd?: number\n /** Why the call failed. `'paid-call-failed'` is the ledger's own value for\n * recovery settles; a reconciling caller may record its own reason. */\n error?: string\n}\n\nexport type CostLedgerRecord = PendingCostCall | CostReceipt\n\nexport interface CostReceiptInput extends CostUsage {\n model: string\n /** Caller-supplied rates for a local estimate when the provider does not report billed cost. */\n customTokenPricing?: CustomTokenPricing\n actualCostUsd?: number\n /** A known estimate from an external executor that cannot provide token pricing. */\n estimatedCostUsd?: number\n costUnknown?: boolean\n usageUnknown?: boolean\n}\n\n/** Per-million token rates for a model or endpoint not covered by package pricing. */\nexport interface CustomTokenPricing {\n /** Non-cached input tokens. */\n inputUsdPerMillion: number\n /** Cache-read tokens. Falls back to the normal input rate when omitted. */\n cachedInputUsdPerMillion?: number\n /** Cache-creation or cache-write tokens. Falls back to the normal input rate when omitted. */\n cacheWriteUsdPerMillion?: number\n outputUsdPerMillion: number\n}\n\nexport type MaximumCharge =\n | { externallyEnforcedMaximumUsd: number }\n | ({\n customTokenPricing: CustomTokenPricing\n } & Pick<CostUsage, 'inputTokens' | 'outputTokens' | 'cachedTokens' | 'cacheWriteTokens'>)\n | ({ model: string } & CostUsage)\n\nexport interface RunPaidCallInput<T> {\n callId?: string\n channel: CostChannel\n phase: string\n actor: string\n /** Used before a provider receipt exists and on failures without one. */\n model?: string\n tags?: Record<string, string>\n signal?: AbortSignal\n /** Provider-enforced dollar maximum, or maximum token usage with known pricing. Required when capped. */\n maximumCharge?: MaximumCharge\n /** `callId` can be forwarded as the provider's idempotency key. */\n execute(signal: AbortSignal, callId: string): Promise<T>\n receipt(value: T): CostReceiptInput\n receiptFromError?(error: Error): CostReceiptInput | undefined\n}\n\nexport type PaidCallResult<T> =\n | { succeeded: true; callId: string; value: T; receipt: CostReceipt }\n | { succeeded: false; callId?: string; error: Error; receipt?: CostReceipt }\n\nexport interface ChannelRollup {\n channel: CostChannel\n calls: number\n inputTokens: number\n outputTokens: number\n reasoningTokens?: number\n cachedTokens: number\n cacheWriteTokens?: number\n costUsd: number\n unpricedCalls: number\n unknownUsageCalls: number\n}\n\nexport interface CostLedgerSummary {\n totalCalls: number\n pendingCalls: number\n unresolvedCalls: number\n reservedCostUsd: number\n inputTokens: number\n outputTokens: number\n reasoningTokens?: number\n cachedTokens: number\n cacheWriteTokens?: number\n totalCostUsd: number\n costProvenance: CostProvenance\n byChannel: ChannelRollup[]\n unpricedModels: string[]\n fullyPriced: boolean\n usageComplete: boolean\n accountingComplete: boolean\n incompleteReasons: string[]\n}\n\nexport interface CostLedgerFilter {\n channel?: CostChannel\n phase?: string\n tags?: Record<string, string>\n}\n\nexport interface CostLedgerWaitOptions {\n /** Maximum time to wait for active provider calls. Default 5 seconds. */\n timeoutMs?: number\n /** Wait only for calls matching this attribution filter. */\n filter?: CostLedgerFilter\n}\n\n/** Append-only storage. `append` must atomically reject stale revisions. */\nexport interface CostLedgerPersistence {\n read(): { revision: string; events: string }\n append(expectedRevision: string, event: string): string | undefined\n}\n\nexport interface CostLedgerOptions {\n costCeilingUsd?: number\n persistence?: CostLedgerPersistence\n /** Import already-settled receipts without admitting new paid work. */\n receipts?: readonly CostReceipt[]\n}\n\nexport class CostCeilingReachedError extends ValidationError {\n constructor(\n ceilingUsd: number,\n committedUsd: number,\n requestedUsd: number,\n phase: string,\n actor: string,\n ) {\n super(\n `CostLedger: reserving ${requestedUsd} for '${actor}' during '${phase}' would exceed ceiling ${ceilingUsd} with ${committedUsd} already committed`,\n )\n }\n}\n\nexport class CostAccountingIncompleteError extends ValidationError {}\n\nexport class CostReservationExceededError extends ValidationError {\n constructor(actor: string, actualUsd: number, maximumUsd: number) {\n super(\n `CostLedger: '${actor}' charged ${actualUsd}, exceeding its enforced maximum ${maximumUsd}`,\n )\n }\n}\n\nexport class CostCallConflictError extends ValidationError {\n readonly callId?: string\n readonly receipt?: CostReceipt\n\n constructor(\n message: string,\n options: { callId?: string; receipt?: CostReceipt; cause?: unknown } = {},\n ) {\n super(message, options.cause === undefined ? undefined : { cause: options.cause })\n this.callId = options.callId\n this.receipt = options.receipt ? cloneReceipt(options.receipt) : undefined\n }\n}\n\nexport class CostLedgerPersistenceError extends ValidationError {\n readonly callId?: string\n readonly receipt?: CostReceipt\n\n constructor(cause: unknown, callId?: string, receipt?: CostReceipt) {\n super(\n `CostLedger: failed to persist${callId ? ` call '${callId}'` : ''}: ${toError(cause).message}`,\n { cause },\n )\n this.callId = callId\n this.receipt = receipt ? cloneReceipt(receipt) : undefined\n }\n}\n\nexport class CostReceiptCaptureError extends ValidationError {\n readonly callId: string\n readonly receipt?: CostReceipt\n readonly receiptError: Error\n\n constructor(callId: string, cause: unknown, receiptError: unknown, receipt?: CostReceipt) {\n super(`CostLedger: could not capture the provider receipt for call '${callId}'`, { cause })\n this.callId = callId\n this.receipt = receipt ? cloneReceipt(receipt) : undefined\n this.receiptError = toError(receiptError)\n }\n}\n\ninterface PendingCostCallEvent {\n version: 1\n record: PendingCostCall\n}\n\ninterface SettledCostCallEvent {\n version: 2\n record: CostReceipt\n}\n\ninterface CompletedTasksEvent {\n version: 1\n completedTasks: number\n}\n\ninterface CostLimitEvent {\n version: 1\n costCeilingUsd: number\n}\n\ntype CostCallEvent = PendingCostCallEvent | SettledCostCallEvent\ntype CostLedgerEvent = CostCallEvent | CompletedTasksEvent | CostLimitEvent\n\n/** Run-wide paid-call admission, durable call state, receipts, and summaries. */\nexport class CostLedger {\n private readonly records = new Map<string, CostLedgerRecord>()\n private readonly activeCallIds = new Set<string>()\n private readonly lateCallIds = new Set<string>()\n private readonly idleWaiters = new Set<() => void>()\n private completedTasks = 0\n private revision = 'memory'\n private costLimitPersisted = false\n readonly costCeilingUsd?: number\n private readonly persistence?: CostLedgerPersistence\n\n constructor(input?: number | CostLedgerOptions) {\n const options = typeof input === 'number' ? { costCeilingUsd: input } : (input ?? {})\n this.persistence = options.persistence\n if (options.costCeilingUsd !== undefined) {\n assertNonNegative(options.costCeilingUsd, 'costCeilingUsd')\n }\n\n let persistedCostCeilingUsd: number | undefined\n if (this.persistence) {\n let stored: ReturnType<CostLedgerPersistence['read']>\n try {\n stored = this.persistence.read()\n } catch (cause) {\n throw new CostLedgerPersistenceError(cause)\n }\n assertString(stored.revision, 'persistence revision')\n this.revision = stored.revision\n const restored = parseEvents(stored.events)\n for (const record of restored.records) this.records.set(record.callId, record)\n this.completedTasks = restored.completedTasks\n persistedCostCeilingUsd = restored.costCeilingUsd\n }\n\n if (\n options.costCeilingUsd !== undefined &&\n persistedCostCeilingUsd !== undefined &&\n options.costCeilingUsd !== persistedCostCeilingUsd\n ) {\n throw new ValidationError(\n `CostLedger: requested cost ceiling ${options.costCeilingUsd} does not match persisted ceiling ${persistedCostCeilingUsd}`,\n )\n }\n this.costCeilingUsd = persistedCostCeilingUsd ?? options.costCeilingUsd\n this.costLimitPersisted =\n !this.persistence ||\n this.costCeilingUsd === undefined ||\n persistedCostCeilingUsd !== undefined\n\n if (\n this.costCeilingUsd !== undefined &&\n [...this.records.values()].some(\n (record) => record.status === 'pending' && record.maximumCostUsd === undefined,\n )\n ) {\n throw new ValidationError('CostLedger: capped event log contains an unbounded pending call')\n }\n\n if (options.receipts?.length) {\n const imported = options.receipts.map((receipt, index) =>\n parseImportedReceipt(receipt, `imported receipt ${index + 1}`),\n )\n this.ensureCostLimitPersisted()\n for (const receipt of imported) this.appendRecord(receipt)\n }\n }\n\n async runPaidCall<T>(input: RunPaidCallInput<T>): Promise<PaidCallResult<T>> {\n let callId: string | undefined\n let pending: PendingCostCall | undefined\n try {\n callId = resolveCallId(input.callId)\n validateAttribution(input)\n if (input.signal?.aborted) {\n return { succeeded: false, callId, error: abortError(input.signal) }\n }\n this.ensureCostLimitPersisted(callId)\n\n const maximumCostUsd = this.resolveMaximum(input.maximumCharge)\n const existing = this.records.get(callId)\n if (existing) {\n return {\n succeeded: false,\n callId,\n error: new CostCallConflictError(\n existing.status === 'pending'\n ? `CostLedger: callId '${callId}' is unresolved and must be reconciled before retry`\n : `CostLedger: callId '${callId}' already exists`,\n { callId },\n ),\n }\n }\n\n if (!pending) {\n while (true) {\n if (this.records.has(callId)) {\n return {\n succeeded: false,\n callId,\n error: new CostCallConflictError(`CostLedger: callId '${callId}' already exists`),\n }\n }\n const summary = this.summary()\n if (summary.unresolvedCalls > 0) {\n return {\n succeeded: false,\n callId,\n error: new CostAccountingIncompleteError(\n `CostLedger: ${summary.unresolvedCalls} unresolved call(s) must be reconciled before new paid work`,\n ),\n }\n }\n if (this.costCeilingUsd === undefined) break\n if (this.hasBudgetBreachingSettledCall()) {\n return {\n succeeded: false,\n callId,\n error: new CostAccountingIncompleteError(\n `CostLedger: a settled call exceeded its enforced maximum; refusing paid call '${input.actor}' during '${input.phase}'`,\n ),\n }\n }\n // A settled call whose cost the provider left unknown is charged its\n // reserved maximum here, so the ceiling is enforced against a real\n // upper bound and one under-reported response cannot let later calls\n // silently exceed the budget — while still permitting them.\n const committedCostUsd = this.conservativeSettledCostUsd()\n if (committedCostUsd + maximumCostUsd! > this.costCeilingUsd) {\n return {\n succeeded: false,\n callId,\n error: new CostCeilingReachedError(\n this.costCeilingUsd,\n committedCostUsd,\n maximumCostUsd!,\n input.phase,\n input.actor,\n ),\n }\n }\n if (committedCostUsd + summary.reservedCostUsd + maximumCostUsd! <= this.costCeilingUsd) {\n break\n }\n await this.waitForReservationRelease(input.signal)\n }\n\n pending = {\n status: 'pending',\n callId,\n channel: input.channel,\n phase: input.phase,\n actor: input.actor,\n model: pendingModel(input),\n ...(maximumCostUsd === undefined ? {} : { maximumCostUsd }),\n ...(input.tags ? { tags: { ...input.tags } } : {}),\n timestamp: Date.now(),\n }\n this.appendRecord(pending)\n this.activeCallIds.add(callId)\n }\n } catch (error) {\n return { succeeded: false, ...(callId ? { callId } : {}), error: toError(error) }\n }\n\n try {\n return await this.execute(input, pending)\n } catch (error) {\n return { succeeded: false, callId: pending.callId, error: toError(error) }\n } finally {\n if (!this.lateCallIds.has(pending.callId)) this.releaseActiveCall(pending.callId)\n }\n }\n\n /** Wait until every call started by this ledger has produced a durable outcome. */\n async waitForIdle(options: CostLedgerWaitOptions = {}): Promise<boolean> {\n const hasActiveMatch = (): boolean =>\n [...this.activeCallIds].some((callId) => {\n const record = this.records.get(callId)\n return record !== undefined && matches(record, options.filter)\n })\n if (!hasActiveMatch()) return true\n const timeoutMs = options.timeoutMs ?? 5_000\n assertTimeout(timeoutMs, 'waitForIdle.timeoutMs')\n return new Promise<boolean>((resolve) => {\n let timer: ReturnType<typeof setTimeout> | undefined\n const finish = (settled: boolean): void => {\n this.idleWaiters.delete(onIdle)\n if (timer !== undefined) clearTimeout(timer)\n resolve(settled)\n }\n const onIdle = (): void => {\n if (!hasActiveMatch()) finish(true)\n }\n this.idleWaiters.add(onIdle)\n timer = setTimeout(() => finish(false), timeoutMs)\n onIdle()\n })\n }\n\n /** Settle a call left pending by a crashed process after reconciling with the provider. */\n reconcile(\n callId: string,\n observed: CostReceiptInput,\n options: { failed?: boolean; error?: string } = {},\n ): CostReceipt {\n const pending = [...this.records.values()].find(\n (record): record is PendingCostCall =>\n record.callId === callId && record.status === 'pending',\n )\n if (!pending) throw new CostCallConflictError(`CostLedger: no pending call '${callId}'`)\n if (this.activeCallIds.has(callId)) {\n throw new CostCallConflictError(`CostLedger: call '${callId}' is still active`)\n }\n this.ensureCostLimitPersisted(callId)\n return this.commitReceipt(\n pending,\n observed,\n options.failed === true || options.error !== undefined,\n options.error,\n )\n }\n\n list(filter?: CostLedgerFilter): CostReceipt[] {\n return [...this.records.values()]\n .filter((record): record is CostReceipt => record.status === 'settled')\n .filter((receipt) => matches(receipt, filter))\n .map(cloneReceipt)\n }\n\n /** Read pending calls without exposing mutable ledger state. */\n listPending(filter?: CostLedgerFilter): PendingCostCallView[] {\n return [...this.records.values()]\n .filter((record): record is PendingCostCall => record.status === 'pending')\n .filter((record) => matches(record, filter))\n .map((record) => ({\n ...clonePendingCall(record),\n state: this.lateCallIds.has(record.callId)\n ? 'late'\n : this.activeCallIds.has(record.callId)\n ? 'active'\n : 'interrupted',\n }))\n }\n\n summary(filter?: CostLedgerFilter): CostLedgerSummary {\n const records = [...this.records.values()].filter((record) => matches(record, filter))\n const pending = records.filter(\n (record): record is PendingCostCall => record.status === 'pending',\n )\n const receipts = records.filter((record): record is CostReceipt => record.status === 'settled')\n const byChannel = new Map<string, ChannelRollup>()\n const unpriced = new Set<string>()\n const incompleteReasons: string[] = pending.map(\n (record) => `call '${record.callId}' for '${record.actor}' is pending`,\n )\n let inputTokens = 0\n let outputTokens = 0\n let reasoningTokens = 0\n let cachedTokens = 0\n let cacheWriteTokens = 0\n let totalCostUsd = 0\n\n for (const receipt of receipts) {\n inputTokens += receipt.inputTokens\n outputTokens += receipt.outputTokens\n reasoningTokens += receipt.reasoningTokens ?? 0\n cachedTokens += receipt.cachedTokens ?? 0\n cacheWriteTokens += receipt.cacheWriteTokens ?? 0\n totalCostUsd += receipt.costUsd\n if (receipt.costUnknown) {\n unpriced.add(receipt.model)\n incompleteReasons.push(\n receipt.error ?? `cost unknown for '${receipt.actor}' using '${receipt.model}'`,\n )\n }\n if (receipt.usageUnknown) {\n incompleteReasons.push(\n `token usage unknown for '${receipt.actor}' using '${receipt.model}'`,\n )\n }\n if (receipt.maximumCostUsd !== undefined && receipt.costUsd > receipt.maximumCostUsd) {\n incompleteReasons.push(\n `'${receipt.actor}' charged ${receipt.costUsd}, exceeding its enforced maximum ${receipt.maximumCostUsd}`,\n )\n }\n const rollup = byChannel.get(receipt.channel) ?? emptyRollup(receipt.channel)\n rollup.calls += 1\n rollup.inputTokens += receipt.inputTokens\n rollup.outputTokens += receipt.outputTokens\n rollup.reasoningTokens = (rollup.reasoningTokens ?? 0) + (receipt.reasoningTokens ?? 0)\n rollup.cachedTokens += receipt.cachedTokens ?? 0\n rollup.cacheWriteTokens = (rollup.cacheWriteTokens ?? 0) + (receipt.cacheWriteTokens ?? 0)\n rollup.costUsd += receipt.costUsd\n if (receipt.costUnknown) rollup.unpricedCalls += 1\n if (receipt.usageUnknown) rollup.unknownUsageCalls += 1\n byChannel.set(receipt.channel, rollup)\n }\n\n return {\n totalCalls: receipts.length,\n pendingCalls: pending.length,\n unresolvedCalls: pending.filter(\n (record) => !this.activeCallIds.has(record.callId) || this.lateCallIds.has(record.callId),\n ).length,\n reservedCostUsd: pending.reduce((sum, record) => sum + (record.maximumCostUsd ?? 0), 0),\n inputTokens,\n outputTokens,\n reasoningTokens,\n cachedTokens,\n cacheWriteTokens,\n totalCostUsd,\n costProvenance:\n pending.length > 0 || receipts.some((receipt) => receipt.costUnknown)\n ? { kind: 'uncaptured', usd: null }\n : receipts.every((receipt) => receipt.actualCostUsd !== undefined)\n ? { kind: 'observed', usd: totalCostUsd }\n : { kind: 'estimated', usd: totalCostUsd },\n byChannel: [...byChannel.values()].sort((a, b) => a.channel.localeCompare(b.channel)),\n unpricedModels: [...unpriced].sort(),\n fullyPriced: unpriced.size === 0,\n usageComplete: pending.length === 0 && receipts.every((receipt) => !receipt.usageUnknown),\n accountingComplete: incompleteReasons.length === 0,\n incompleteReasons: [...new Set(incompleteReasons)],\n }\n }\n\n markCompleted(count = 1): void {\n if (!Number.isInteger(count) || count < 0) {\n throw new ValidationError(\n `CostLedger.markCompleted: count must be a non-negative integer, got ${count}`,\n )\n }\n if (count === 0) return\n this.ensureCostLimitPersisted()\n this.appendEvent({ version: 1, completedTasks: count })\n this.completedTasks += count\n }\n\n costPerCompletedTask(): number | null {\n return this.completedTasks === 0 ? null : this.summary().totalCostUsd / this.completedTasks\n }\n\n private async execute<T>(\n input: RunPaidCallInput<T>,\n pending: PendingCostCall,\n ): Promise<PaidCallResult<T>> {\n const signal = input.signal ?? new AbortController().signal\n if (signal.aborted) {\n return this.commitOutcome(pending, abortError(signal), {\n model: pending.model,\n inputTokens: 0,\n outputTokens: 0,\n actualCostUsd: 0,\n })\n }\n\n const operation = Promise.resolve().then(() => input.execute(signal, pending.callId))\n const settled = await settle(operation, signal)\n if (settled.kind === 'aborted') {\n this.lateCallIds.add(pending.callId)\n this.captureLateOutcome(input, pending, operation)\n return paidFailure(pending.callId, abortError(signal))\n }\n if (settled.kind === 'error') {\n let observed: CostReceiptInput | undefined\n try {\n observed = input.receiptFromError?.(settled.error)\n } catch (receiptError) {\n return this.captureFailure(pending, settled.error, receiptError)\n }\n return this.commitOutcome(pending, settled.error, observed ?? unknownReceipt(pending.model))\n }\n\n try {\n const receipt = this.commitReceipt(pending, input.receipt(settled.value))\n if (receipt.maximumCostUsd !== undefined && receipt.costUsd > receipt.maximumCostUsd) {\n return paidFailure(\n pending.callId,\n new CostReservationExceededError(pending.actor, receipt.costUsd, receipt.maximumCostUsd),\n receipt,\n )\n }\n return { succeeded: true, callId: pending.callId, value: settled.value, receipt }\n } catch (receiptError) {\n if (\n receiptError instanceof CostLedgerPersistenceError ||\n receiptError instanceof CostCallConflictError\n ) {\n return paidFailure(pending.callId, receiptError)\n }\n return this.captureFailure(pending, receiptError, receiptError)\n }\n }\n\n private captureLateOutcome<T>(\n input: RunPaidCallInput<T>,\n pending: PendingCostCall,\n operation: Promise<T>,\n ): void {\n void operation\n .then(\n (value) => {\n if (this.records.get(pending.callId)?.status !== 'pending') return\n try {\n this.commitReceipt(pending, input.receipt(value))\n } catch {\n // A failed durable settlement leaves the reservation pending and blocks new paid work.\n }\n },\n (cause) => {\n if (this.records.get(pending.callId)?.status !== 'pending') return\n const error = toError(cause)\n try {\n const observed = input.receiptFromError?.(error)\n this.commitReceipt(pending, observed ?? unknownReceipt(pending.model), true)\n } catch (receiptError) {\n if (\n receiptError instanceof CostLedgerPersistenceError ||\n receiptError instanceof CostCallConflictError\n ) {\n return\n }\n this.captureFailure(pending, error, receiptError)\n }\n },\n )\n .finally(() => {\n this.lateCallIds.delete(pending.callId)\n this.releaseActiveCall(pending.callId)\n })\n }\n\n private releaseActiveCall(callId: string): void {\n this.activeCallIds.delete(callId)\n for (const resolve of [...this.idleWaiters]) resolve()\n }\n\n private async waitForReservationRelease(signal?: AbortSignal): Promise<void> {\n if (signal?.aborted) throw abortError(signal)\n await new Promise<void>((resolve, reject) => {\n let finished = false\n const finish = (error?: Error): void => {\n if (finished) return\n finished = true\n this.idleWaiters.delete(onRelease)\n signal?.removeEventListener('abort', onAbort)\n if (error) reject(error)\n else resolve()\n }\n const onRelease = (): void => finish()\n const onAbort = (): void => finish(abortError(signal!))\n this.idleWaiters.add(onRelease)\n signal?.addEventListener('abort', onAbort, { once: true })\n if (this.activeCallIds.size === 0) onRelease()\n })\n }\n\n private commitOutcome<T>(\n pending: PendingCostCall,\n error: Error,\n observed: CostReceiptInput,\n ): PaidCallResult<T> {\n try {\n const receipt = this.commitReceipt(pending, observed, true)\n return paidFailure(pending.callId, error, receipt)\n } catch (receiptError) {\n if (\n receiptError instanceof CostLedgerPersistenceError ||\n receiptError instanceof CostCallConflictError\n ) {\n return paidFailure(pending.callId, receiptError)\n }\n return this.captureFailure(pending, error, receiptError)\n }\n }\n\n private captureFailure<T>(\n pending: PendingCostCall,\n cause: unknown,\n receiptError: unknown,\n ): PaidCallResult<T> {\n try {\n const receipt = this.commitReceipt(pending, unknownReceipt(pending.model), true)\n return paidFailure(\n pending.callId,\n new CostReceiptCaptureError(pending.callId, cause, receiptError, receipt),\n receipt,\n )\n } catch (error) {\n const typed = error instanceof Error ? error : toError(error)\n return paidFailure(pending.callId, typed)\n }\n }\n\n private commitReceipt(\n pending: PendingCostCall,\n observed: CostReceiptInput,\n failed = false,\n error?: string,\n ): CostReceipt {\n const receipt = buildReceipt(pending, observed, failed, error)\n if (this.records.get(pending.callId)?.status !== 'pending') {\n throw new CostCallConflictError(`CostLedger: call '${pending.callId}' is not pending`)\n }\n this.appendRecord(receipt)\n return cloneReceipt(receipt)\n }\n\n private resolveMaximum(maximum: MaximumCharge | undefined): number | undefined {\n if (!maximum) {\n if (this.costCeilingUsd !== undefined) {\n throw new CostAccountingIncompleteError(\n 'CostLedger: capped paid calls require a hard maximumCharge before execution',\n )\n }\n return undefined\n }\n if ('externallyEnforcedMaximumUsd' in maximum) {\n assertNonNegative(\n maximum.externallyEnforcedMaximumUsd,\n 'maximumCharge.externallyEnforcedMaximumUsd',\n )\n return maximum.externallyEnforcedMaximumUsd\n }\n if ('customTokenPricing' in maximum) {\n return costForTokenPricing(maximum.customTokenPricing, maximum)\n }\n const priced = costForUsage(maximum.model, maximum)\n if (priced.costUnknown) {\n if (this.costCeilingUsd !== undefined) {\n throw new CostAccountingIncompleteError(\n `CostLedger: cannot reserve unpriced model '${maximum.model}' in a capped run`,\n )\n }\n return undefined\n }\n return priced.costUsd\n }\n\n private hasBudgetBreachingSettledCall(): boolean {\n return [...this.records.values()].some(\n (record) =>\n record.status === 'settled' &&\n record.maximumCostUsd !== undefined &&\n record.costUsd > record.maximumCostUsd,\n )\n }\n\n /**\n * Total settled cost with each unknown-cost call charged its reserved\n * maximum. A provider that omits a call's cost cannot make the ceiling check\n * under-count: the call is bounded by what it was allowed to spend.\n */\n private conservativeSettledCostUsd(): number {\n let total = 0\n for (const record of this.records.values()) {\n if (record.status !== 'settled') continue\n total += record.costUnknown ? (record.maximumCostUsd ?? record.costUsd) : record.costUsd\n }\n return total\n }\n\n private appendRecord(record: CostLedgerRecord): void {\n const callId = record.callId\n const receipt = record.status === 'settled' ? record : undefined\n validateTransition(this.records, record)\n const event: CostCallEvent =\n record.status === 'settled'\n ? { version: 2, record: cloneReceipt(record) }\n : { version: 1, record: clonePendingCall(record) }\n this.appendEvent(event, callId, receipt)\n this.records.set(callId, cloneRecord(record))\n }\n\n private ensureCostLimitPersisted(callId?: string): void {\n if (this.costLimitPersisted || this.costCeilingUsd === undefined) return\n this.appendEvent({ version: 1, costCeilingUsd: this.costCeilingUsd }, callId)\n this.costLimitPersisted = true\n }\n\n private appendEvent(event: CostLedgerEvent, callId?: string, receipt?: CostReceipt): void {\n try {\n if (this.persistence) {\n const nextRevision = this.persistence.append(this.revision, `${JSON.stringify(event)}\\n`)\n if (nextRevision === undefined) {\n throw new CostCallConflictError(\n `CostLedger: persisted revision changed while writing call '${callId}'`,\n { callId, receipt },\n )\n }\n assertString(nextRevision, 'persistence revision')\n this.revision = nextRevision\n }\n } catch (cause) {\n if (cause instanceof CostCallConflictError) throw cause\n throw new CostLedgerPersistenceError(cause, callId, receipt)\n }\n }\n}\n\n/** Public callback surface for a shared cost ledger.\n *\n * Declaration bundles may expose this type through multiple package subpaths.\n * Keeping callback contracts structural lets those subpaths compose while the\n * concrete {@link CostLedger} retains its private durable state.\n */\nexport type CostLedgerHandle = Pick<\n CostLedger,\n Exclude<keyof CostLedger, 'listPending' | 'waitForIdle'>\n> &\n Partial<Pick<CostLedger, 'listPending' | 'waitForIdle'>>\n\n/** Return the canonical pricing-table key, or null when the model is unpriced. */\nexport function modelPriceKey(model: string): string | null {\n return isModelPriced(model) ? model : null\n}\n\nexport interface CostResult {\n costUsd: number\n costUnknown: boolean\n}\n\nexport function costForUsage(model: string, usage: CostUsage): CostResult {\n assertUsage(usage)\n if (!resolveModelPricing(model)) return { costUsd: 0, costUnknown: true }\n return {\n costUsd: estimateCost(\n usage.inputTokens + (usage.cachedTokens ?? 0) + (usage.cacheWriteTokens ?? 0),\n usage.outputTokens,\n model,\n ),\n costUnknown: false,\n }\n}\n\n/** Price token counts with caller-supplied per-million rates. */\nexport function costForTokenPricing(\n pricing: CustomTokenPricing,\n usage: Pick<CostUsage, 'inputTokens' | 'outputTokens' | 'cachedTokens' | 'cacheWriteTokens'>,\n): number {\n assertTokenCount(usage.inputTokens, 'usage.inputTokens')\n assertTokenCount(usage.outputTokens, 'usage.outputTokens')\n if (usage.cachedTokens !== undefined) {\n assertTokenCount(usage.cachedTokens, 'usage.cachedTokens')\n }\n if (usage.cacheWriteTokens !== undefined) {\n assertTokenCount(usage.cacheWriteTokens, 'usage.cacheWriteTokens')\n }\n assertNonNegative(pricing.inputUsdPerMillion, 'pricing.inputUsdPerMillion')\n if (pricing.cachedInputUsdPerMillion !== undefined) {\n assertNonNegative(pricing.cachedInputUsdPerMillion, 'pricing.cachedInputUsdPerMillion')\n }\n if (pricing.cacheWriteUsdPerMillion !== undefined) {\n assertNonNegative(pricing.cacheWriteUsdPerMillion, 'pricing.cacheWriteUsdPerMillion')\n }\n assertNonNegative(pricing.outputUsdPerMillion, 'pricing.outputUsdPerMillion')\n const cachedInputRate = pricing.cachedInputUsdPerMillion ?? pricing.inputUsdPerMillion\n const cacheWriteRate = pricing.cacheWriteUsdPerMillion ?? pricing.inputUsdPerMillion\n return (\n (usage.inputTokens / 1_000_000) * pricing.inputUsdPerMillion +\n ((usage.cachedTokens ?? 0) / 1_000_000) * cachedInputRate +\n ((usage.cacheWriteTokens ?? 0) / 1_000_000) * cacheWriteRate +\n (usage.outputTokens / 1_000_000) * pricing.outputUsdPerMillion\n )\n}\n\ntype Settled<T> =\n | { kind: 'value'; value: T }\n | { kind: 'error'; error: Error }\n | { kind: 'aborted' }\n\nasync function settle<T>(promise: Promise<T>, signal: AbortSignal): Promise<Settled<T>> {\n return await new Promise((resolve) => {\n let done = false\n const finish = (value: Settled<T>): void => {\n if (done) return\n done = true\n signal.removeEventListener('abort', onAbort)\n resolve(value)\n }\n const onAbort = () => finish({ kind: 'aborted' })\n signal.addEventListener('abort', onAbort, { once: true })\n if (signal.aborted) onAbort()\n promise.then(\n (value) => finish({ kind: 'value', value }),\n (error) => finish({ kind: 'error', error: toError(error) }),\n )\n })\n}\n\nfunction buildReceipt(\n pending: PendingCostCall,\n observed: CostReceiptInput,\n failed = false,\n error?: string,\n): CostReceipt {\n assertUsage(observed)\n assertString(observed.model, 'receipt.model')\n const suppliedAmounts = [\n observed.actualCostUsd,\n observed.estimatedCostUsd,\n observed.customTokenPricing,\n ].filter((value) => value !== undefined)\n if (suppliedAmounts.length > 1) {\n throw new ValidationError(\n 'CostLedger: a receipt can have only one of actualCostUsd, estimatedCostUsd, or customTokenPricing',\n )\n }\n const customPricingSnapshot =\n observed.customTokenPricing === undefined\n ? undefined\n : pricingSnapshot(observed.customTokenPricing)\n const estimated = customPricingSnapshot\n ? {\n costUsd: costFromPricing(observed, customPricingSnapshot),\n costUnknown: false,\n }\n : costForUsage(observed.model, observed)\n const hasActual = observed.actualCostUsd !== undefined\n const hasExternalEstimate = observed.estimatedCostUsd !== undefined\n if (hasActual && observed.costUnknown === true) {\n throw new ValidationError(\n 'CostLedger: a receipt cannot have both actualCostUsd and costUnknown=true',\n )\n }\n if (hasActual) assertNonNegative(observed.actualCostUsd!, 'actualCostUsd')\n if (hasExternalEstimate) assertNonNegative(observed.estimatedCostUsd!, 'estimatedCostUsd')\n if (hasExternalEstimate && observed.costUnknown === true) {\n throw new ValidationError(\n 'CostLedger: a receipt cannot have both estimatedCostUsd and costUnknown=true',\n )\n }\n const usageUnknown = observed.usageUnknown === true\n const costUnknown =\n observed.costUnknown === true ||\n (!hasActual && !hasExternalEstimate && (usageUnknown || estimated.costUnknown))\n const resolvedModelPricing =\n !customPricingSnapshot && !hasActual && !hasExternalEstimate && !costUnknown\n ? resolveModelPricing(observed.model)\n : null\n const receiptPricing =\n !hasActual && !hasExternalEstimate && !costUnknown\n ? (customPricingSnapshot ??\n (resolvedModelPricing\n ? {\n inputUsdPerThousand: resolvedModelPricing.input,\n outputUsdPerThousand: resolvedModelPricing.output,\n }\n : undefined))\n : undefined\n return parseReceipt(\n {\n status: 'settled',\n callId: pending.callId,\n channel: pending.channel,\n phase: pending.phase,\n actor: pending.actor,\n model: observed.model,\n inputTokens: observed.inputTokens,\n outputTokens: observed.outputTokens,\n ...(observed.reasoningTokens === undefined\n ? {}\n : { reasoningTokens: observed.reasoningTokens }),\n ...(observed.cachedTokens === undefined ? {} : { cachedTokens: observed.cachedTokens }),\n ...(observed.cacheWriteTokens === undefined\n ? {}\n : { cacheWriteTokens: observed.cacheWriteTokens }),\n costUsd: costUnknown\n ? 0\n : hasActual\n ? observed.actualCostUsd!\n : hasExternalEstimate\n ? observed.estimatedCostUsd!\n : estimated.costUsd,\n costUnknown,\n usageUnknown,\n ...(receiptPricing ? { pricing: receiptPricing } : {}),\n ...(hasActual ? { actualCostUsd: observed.actualCostUsd } : {}),\n ...(hasExternalEstimate ? { estimatedCostUsd: observed.estimatedCostUsd } : {}),\n ...(pending.maximumCostUsd === undefined ? {} : { maximumCostUsd: pending.maximumCostUsd }),\n ...(failed ? { error: error ?? 'paid-call-failed' } : {}),\n ...(pending.tags ? { tags: { ...pending.tags } } : {}),\n timestamp: pending.timestamp,\n },\n 'provider receipt',\n )\n}\n\nconst NonEmptyString = z.string().refine((value) => value.trim().length > 0, 'must be non-empty')\nconst TokenCount = z.number().int().nonnegative().finite()\nconst NonNegative = z.number().nonnegative().finite()\nconst Tags = z.record(NonEmptyString, z.string())\nconst CostPricingSchema = z.strictObject({\n inputUsdPerThousand: NonNegative,\n cachedInputUsdPerThousand: NonNegative.optional(),\n cacheWriteUsdPerThousand: NonNegative.optional(),\n outputUsdPerThousand: NonNegative,\n})\nconst CostCallBaseShape = {\n callId: NonEmptyString,\n channel: NonEmptyString,\n phase: NonEmptyString,\n actor: NonEmptyString,\n model: NonEmptyString,\n maximumCostUsd: NonNegative.optional(),\n tags: Tags.optional(),\n timestamp: NonNegative,\n}\nconst PendingCostCallSchema = z.strictObject({\n status: z.literal('pending'),\n ...CostCallBaseShape,\n})\nconst CostReceiptBaseShape = {\n status: z.literal('settled'),\n ...CostCallBaseShape,\n inputTokens: TokenCount,\n outputTokens: TokenCount,\n cachedTokens: TokenCount.optional(),\n costUsd: NonNegative,\n costUnknown: z.boolean(),\n usageUnknown: z.boolean().default(false),\n pricing: CostPricingSchema.optional(),\n actualCostUsd: NonNegative.optional(),\n estimatedCostUsd: NonNegative.optional(),\n error: NonEmptyString.optional(),\n}\nconst CostReceiptSchema = z\n .strictObject({\n ...CostReceiptBaseShape,\n reasoningTokens: TokenCount.optional(),\n cacheWriteTokens: TokenCount.optional(),\n })\n .superRefine((receipt, ctx) => validateCostReceipt(receipt, ctx))\n\nfunction validateCostReceipt(\n receipt: CostUsage & {\n costUsd: number\n costUnknown: boolean\n usageUnknown: boolean\n pricing?: NonNullable<CostReceipt['pricing']>\n actualCostUsd?: number\n estimatedCostUsd?: number\n },\n ctx: z.RefinementCtx,\n): void {\n if (receipt.reasoningTokens !== undefined && receipt.reasoningTokens > receipt.outputTokens) {\n ctx.addIssue({ code: 'custom', message: 'reasoningTokens must not exceed outputTokens' })\n }\n\n if (receipt.actualCostUsd !== undefined && receipt.estimatedCostUsd !== undefined) {\n ctx.addIssue({\n code: 'custom',\n message: 'actual and external estimated costs cannot both be present',\n })\n }\n\n if (receipt.actualCostUsd !== undefined) {\n if (receipt.costUnknown || receipt.costUsd !== receipt.actualCostUsd) {\n ctx.addIssue({ code: 'custom', message: 'actual cost must be known and equal costUsd' })\n }\n if (receipt.pricing !== undefined) {\n ctx.addIssue({ code: 'custom', message: 'actual cost must not include estimated pricing' })\n }\n return\n }\n\n if (receipt.estimatedCostUsd !== undefined) {\n if (receipt.costUnknown || receipt.costUsd !== receipt.estimatedCostUsd) {\n ctx.addIssue({ code: 'custom', message: 'external estimate must be known and equal costUsd' })\n }\n if (receipt.pricing !== undefined) {\n ctx.addIssue({ code: 'custom', message: 'external estimate must not include token pricing' })\n }\n return\n }\n\n if (receipt.costUnknown) {\n if (receipt.costUsd !== 0) {\n ctx.addIssue({ code: 'custom', message: 'unknown cost must have costUsd 0' })\n }\n if (receipt.pricing !== undefined) {\n ctx.addIssue({ code: 'custom', message: 'unknown cost must not include estimated pricing' })\n }\n return\n }\n\n if (receipt.usageUnknown) {\n ctx.addIssue({ code: 'custom', message: 'known estimated cost requires known usage' })\n }\n if (!receipt.pricing) {\n ctx.addIssue({ code: 'custom', message: 'known estimated cost requires a pricing snapshot' })\n return\n }\n\n const expected = costFromPricing(receipt, receipt.pricing)\n if (!costAmountsMatch(receipt.costUsd, expected)) {\n ctx.addIssue({\n code: 'custom',\n message: `estimated cost ${receipt.costUsd} does not match pricing snapshot ${expected}`,\n })\n }\n}\n\nfunction costAmountsMatch(left: number, right: number): boolean {\n const scale = Math.max(1, Math.abs(left), Math.abs(right))\n return Math.abs(left - right) <= Number.EPSILON * scale * 8\n}\n\nconst CostLedgerEventSchema = z.union([\n z.strictObject({\n version: z.literal(1),\n record: PendingCostCallSchema,\n }),\n z.strictObject({\n version: z.literal(2),\n record: CostReceiptSchema,\n }),\n z.strictObject({\n version: z.literal(1),\n completedTasks: TokenCount,\n }),\n z.strictObject({\n version: z.literal(1),\n costCeilingUsd: NonNegative,\n }),\n])\n\nfunction parseEvents(serialized: string): {\n records: CostLedgerRecord[]\n completedTasks: number\n costCeilingUsd?: number\n} {\n const records = new Map<string, CostLedgerRecord>()\n let completedTasks = 0\n let costCeilingUsd: number | undefined\n let lineNumber = 0\n try {\n for (const line of completeJournalPrefix(serialized).split('\\n')) {\n if (!line.trim()) continue\n lineNumber += 1\n const event = CostLedgerEventSchema.parse(JSON.parse(line)) as CostLedgerEvent\n if ('record' in event) {\n const record = event.record\n validateTransition(records, record)\n records.set(record.callId, cloneRecord(record))\n } else if ('completedTasks' in event) {\n completedTasks += event.completedTasks\n if (!Number.isSafeInteger(completedTasks)) {\n throw new ValidationError('CostLedger: completed task count exceeds safe integer range')\n }\n } else {\n if (costCeilingUsd !== undefined) {\n throw new ValidationError('CostLedger: duplicate persisted cost ceiling')\n }\n costCeilingUsd = event.costCeilingUsd\n }\n }\n return {\n records: [...records.values()],\n completedTasks,\n ...(costCeilingUsd === undefined ? {} : { costCeilingUsd }),\n }\n } catch (cause) {\n throw new ValidationError(\n `CostLedger: invalid persisted event ${lineNumber || 1}: ${validationMessage(cause)}`,\n { cause },\n )\n }\n}\n\nfunction completeJournalPrefix(serialized: string): string {\n if (!serialized || serialized.endsWith('\\n')) return serialized\n const finalNewline = serialized.lastIndexOf('\\n')\n const tail = serialized.slice(finalNewline + 1)\n try {\n JSON.parse(tail)\n } catch {\n return finalNewline < 0 ? '' : serialized.slice(0, finalNewline + 1)\n }\n throw new ValidationError(\n 'CostLedger: complete final persisted event is missing its newline terminator',\n )\n}\n\nfunction validateTransition(\n records: ReadonlyMap<string, CostLedgerRecord>,\n record: CostLedgerRecord,\n): void {\n const current = records.get(record.callId)\n if (!current) return\n if (record.status === 'pending' || current.status === 'settled') {\n throw new CostCallConflictError(`CostLedger: duplicate callId '${record.callId}'`)\n }\n if (!sameAttribution(current, record)) {\n throw new ValidationError(`CostLedger: receipt attribution changed for call '${record.callId}'`)\n }\n}\n\nfunction sameAttribution(before: CostCallBase, after: CostCallBase): boolean {\n return (\n before.channel === after.channel &&\n before.phase === after.phase &&\n before.actor === after.actor &&\n before.maximumCostUsd === after.maximumCostUsd &&\n before.timestamp === after.timestamp &&\n sameTags(before.tags, after.tags)\n )\n}\n\nfunction sameTags(\n left: Readonly<Record<string, string>> | undefined,\n right: Readonly<Record<string, string>> | undefined,\n): boolean {\n const leftEntries = Object.entries(left ?? {}).sort(([a], [b]) => a.localeCompare(b))\n const rightEntries = Object.entries(right ?? {}).sort(([a], [b]) => a.localeCompare(b))\n return JSON.stringify(leftEntries) === JSON.stringify(rightEntries)\n}\n\nfunction parseReceipt(value: unknown, path: string): CostReceipt {\n try {\n return CostReceiptSchema.parse(value) as CostReceipt\n } catch (cause) {\n throw new ValidationError(`CostLedger: invalid ${path}: ${validationMessage(cause)}`, { cause })\n }\n}\n\nfunction parseImportedReceipt(value: unknown, path: string): CostReceipt {\n if (typeof value !== 'object' || value === null) return parseReceipt(value, path)\n const candidate = { ...value } as Record<string, unknown>\n if (\n candidate.status === 'settled' &&\n candidate.actualCostUsd === undefined &&\n candidate.estimatedCostUsd === undefined &&\n candidate.costUnknown === false &&\n candidate.pricing === undefined &&\n typeof candidate.model === 'string'\n ) {\n const pricing = resolveModelPricing(candidate.model)\n if (pricing) {\n candidate.pricing = {\n inputUsdPerThousand: pricing.input,\n outputUsdPerThousand: pricing.output,\n }\n }\n }\n return parseReceipt(candidate, path)\n}\n\nfunction validateAttribution(\n input: Pick<RunPaidCallInput<unknown>, 'channel' | 'phase' | 'actor' | 'model' | 'tags'>,\n): void {\n assertString(input.channel, 'channel')\n assertString(input.phase, 'phase')\n assertString(input.actor, 'actor')\n if (input.model !== undefined) assertString(input.model, 'model')\n if (input.tags !== undefined) {\n const parsed = Tags.safeParse(input.tags)\n if (!parsed.success)\n throw new ValidationError(`CostLedger: invalid tags: ${parsed.error.message}`)\n }\n}\n\nfunction matches(record: CostCallBase, filter: CostLedgerFilter | undefined): boolean {\n if (!filter) return true\n if (filter.channel !== undefined && record.channel !== filter.channel) return false\n if (filter.phase !== undefined && record.phase !== filter.phase) return false\n return Object.entries(filter.tags ?? {}).every(([key, value]) => record.tags?.[key] === value)\n}\n\nfunction cloneRecord(record: CostLedgerRecord): CostLedgerRecord {\n if (record.status === 'settled') return cloneReceipt(record)\n return clonePendingCall(record)\n}\n\nfunction clonePendingCall(record: PendingCostCall): PendingCostCall {\n const { tags, ...rest } = record\n return { ...rest, ...(tags ? { tags: { ...tags } } : {}) }\n}\n\nfunction cloneReceipt(receipt: CostReceipt): CostReceipt {\n const { pricing, tags, ...rest } = receipt\n return {\n ...rest,\n ...(tags ? { tags: { ...tags } } : {}),\n ...(pricing ? { pricing: { ...pricing } } : {}),\n }\n}\n\nfunction costFromPricing(usage: CostUsage, pricing: NonNullable<CostReceipt['pricing']>): number {\n const cachedInputRate = pricing.cachedInputUsdPerThousand ?? pricing.inputUsdPerThousand\n const cacheWriteRate = pricing.cacheWriteUsdPerThousand ?? pricing.inputUsdPerThousand\n return (\n (usage.inputTokens / 1000) * pricing.inputUsdPerThousand +\n ((usage.cachedTokens ?? 0) / 1000) * cachedInputRate +\n ((usage.cacheWriteTokens ?? 0) / 1000) * cacheWriteRate +\n (usage.outputTokens / 1000) * pricing.outputUsdPerThousand\n )\n}\n\nfunction pricingSnapshot(pricing: CustomTokenPricing): NonNullable<CostReceipt['pricing']> {\n costForTokenPricing(pricing, { inputTokens: 0, outputTokens: 0 })\n return {\n inputUsdPerThousand: pricing.inputUsdPerMillion / 1000,\n ...(pricing.cachedInputUsdPerMillion === undefined\n ? {}\n : { cachedInputUsdPerThousand: pricing.cachedInputUsdPerMillion / 1000 }),\n ...(pricing.cacheWriteUsdPerMillion === undefined\n ? {}\n : { cacheWriteUsdPerThousand: pricing.cacheWriteUsdPerMillion / 1000 }),\n outputUsdPerThousand: pricing.outputUsdPerMillion / 1000,\n }\n}\n\nfunction emptyRollup(channel: CostChannel): ChannelRollup {\n return {\n channel,\n calls: 0,\n inputTokens: 0,\n outputTokens: 0,\n reasoningTokens: 0,\n cachedTokens: 0,\n cacheWriteTokens: 0,\n costUsd: 0,\n unpricedCalls: 0,\n unknownUsageCalls: 0,\n }\n}\n\nfunction pendingModel(input: RunPaidCallInput<unknown>): string {\n if (input.model) return input.model\n if (input.maximumCharge && 'model' in input.maximumCharge) return input.maximumCharge.model\n return 'unknown'\n}\n\nfunction unknownReceipt(model: string): CostReceiptInput {\n return { model, inputTokens: 0, outputTokens: 0, costUnknown: true, usageUnknown: true }\n}\n\nfunction resolveCallId(input: string | undefined): string {\n if (input !== undefined) {\n assertString(input, 'callId')\n return input\n }\n if (typeof globalThis.crypto?.randomUUID !== 'function') {\n throw new ValidationError('CostLedger: crypto.randomUUID is required when callId is omitted')\n }\n return globalThis.crypto.randomUUID()\n}\n\nfunction abortError(signal: AbortSignal): Error {\n const reason = (signal as { reason?: unknown }).reason\n if (reason instanceof Error) return reason\n const error = new Error('CostLedger: paid call aborted')\n error.name = 'AbortError'\n return error\n}\n\nfunction toError(value: unknown): Error {\n return value instanceof Error ? value : new Error(String(value))\n}\n\nfunction paidFailure<T>(callId: string, error: Error, receipt?: CostReceipt): PaidCallResult<T> {\n return {\n succeeded: false,\n callId,\n error,\n ...(receipt ? { receipt: cloneReceipt(receipt) } : {}),\n }\n}\n\nfunction validationMessage(cause: unknown): string {\n return cause instanceof z.ZodError ? z.prettifyError(cause) : toError(cause).message\n}\n\nfunction assertUsage(usage: CostUsage): void {\n assertTokenCount(usage.inputTokens, 'inputTokens')\n assertTokenCount(usage.outputTokens, 'outputTokens')\n if (usage.reasoningTokens !== undefined) {\n assertTokenCount(usage.reasoningTokens, 'reasoningTokens')\n if (usage.reasoningTokens > usage.outputTokens) {\n throw new ValidationError('CostLedger: reasoningTokens must not exceed outputTokens')\n }\n }\n if (usage.cachedTokens !== undefined) assertTokenCount(usage.cachedTokens, 'cachedTokens')\n if (usage.cacheWriteTokens !== undefined) {\n assertTokenCount(usage.cacheWriteTokens, 'cacheWriteTokens')\n }\n}\n\nfunction assertTokenCount(value: unknown, name: string): asserts value is number {\n if (typeof value !== 'number' || !Number.isInteger(value) || value < 0) {\n throw new ValidationError(\n `CostLedger: ${name} must be a non-negative integer, got ${String(value)}`,\n )\n }\n}\n\nfunction assertNonNegative(value: unknown, name: string): asserts value is number {\n if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) {\n throw new ValidationError(\n `CostLedger: ${name} must be a non-negative finite number, got ${String(value)}`,\n )\n }\n}\n\nfunction assertTimeout(value: unknown, name: string): asserts value is number {\n if (\n typeof value !== 'number' ||\n !Number.isSafeInteger(value) ||\n value < 0 ||\n value > 2_147_483_647\n ) {\n throw new ValidationError(\n `CostLedger: ${name} must be a non-negative safe integer no greater than 2147483647, got ${String(value)}`,\n )\n }\n}\n\nfunction assertString(value: unknown, name: string): asserts value is string {\n if (typeof value !== 'string' || value.trim().length === 0) {\n throw new ValidationError(`CostLedger: ${name} must be a non-empty string`)\n }\n}\n"],"mappings":";;;;AA+KA,IAAa,0BAAb,cAA6C,gBAAgB;CAC3D,YACE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D,IAAI,MAAM,oBAAoB,KAAA,GAAW;EACvC,iBAAiB,MAAM,iBAAiB,iBAAiB;EACzD,IAAI,MAAM,kBAAkB,MAAM,cAChC,MAAM,IAAI,gBAAgB,0DAA0D;CAExF;CACA,IAAI,MAAM,iBAAiB,KAAA,GAAW,iBAAiB,MAAM,cAAc,cAAc;CACzF,IAAI,MAAM,qBAAqB,KAAA,GAC7B,iBAAiB,MAAM,kBAAkB,kBAAkB;AAE/D;AAEA,SAAS,iBAAiB,OAAgB,MAAuC;CAC/E,IAAI,OAAO,UAAU,YAAY,CAAC,OAAO,UAAU,KAAK,KAAK,QAAQ,GACnE,MAAM,IAAI,gBACR,eAAe,KAAK,uCAAuC,OAAO,KAAK,GACzE;AAEJ;AAEA,SAAS,kBAAkB,OAAgB,MAAuC;CAChF,IAAI,OAAO,UAAU,YAAY,CAAC,OAAO,SAAS,KAAK,KAAK,QAAQ,GAClE,MAAM,IAAI,gBACR,eAAe,KAAK,6CAA6C,OAAO,KAAK,GAC/E;AAEJ;AAEA,SAAS,cAAc,OAAgB,MAAuC;CAC5E,IACE,OAAO,UAAU,YACjB,CAAC,OAAO,cAAc,KAAK,KAC3B,QAAQ,KACR,QAAQ,YAER,MAAM,IAAI,gBACR,eAAe,KAAK,uEAAuE,OAAO,KAAK,GACzG;AAEJ;AAEA,SAAS,aAAa,OAAgB,MAAuC;CAC3E,IAAI,OAAO,UAAU,YAAY,MAAM,KAAK,CAAC,CAAC,WAAW,GACvD,MAAM,IAAI,gBAAgB,eAAe,KAAK,4BAA4B;AAE9E"}
|
|
1
|
+
{"version":3,"file":"cost-ledger-B1qx30B4.js","names":[],"sources":["../src/cost-ledger.ts"],"sourcesContent":["import { z } from 'zod'\nimport { ValidationError } from './errors'\nimport { estimateCost, isModelPriced, resolveModelPricing } from './metrics'\n\nexport type CostChannel = 'agent' | 'judge' | 'verifier' | 'analyst' | 'driver' | (string & {})\n\n/** How a USD amount was obtained. */\nexport type CostProvenance =\n | { kind: 'observed'; usd: number }\n | { kind: 'estimated'; usd: number }\n | { kind: 'uncaptured'; usd: null }\n\nexport interface CostUsage {\n inputTokens: number\n /** Includes reasoning tokens when the provider bills them as output. */\n outputTokens: number\n /** Reasoning-token subset of outputTokens, when reported. */\n reasoningTokens?: number\n /** Prompt tokens served from a provider cache. */\n cachedTokens?: number\n /** Prompt tokens written into a provider cache. */\n cacheWriteTokens?: number\n}\n\ninterface CostCallBase {\n callId: string\n channel: CostChannel\n phase: string\n actor: string\n model: string\n maximumCostUsd?: number\n tags?: Record<string, string>\n timestamp: number\n}\n\nexport interface PendingCostCall extends CostCallBase {\n status: 'pending'\n}\n\nexport interface PendingCostCallView extends PendingCostCall {\n state: 'active' | 'late' | 'interrupted'\n}\n\nexport interface CostReceipt extends CostCallBase, CostUsage {\n status: 'settled'\n costUsd: number\n costUnknown: boolean\n usageUnknown?: boolean\n /** Rates used to estimate cost locally. Absent when cost is provider-reported or unknown. */\n pricing?: {\n inputUsdPerThousand: number\n cachedInputUsdPerThousand?: number\n cacheWriteUsdPerThousand?: number\n outputUsdPerThousand: number\n }\n /** Cost reported by the provider, not a local token-price calculation. */\n actualCostUsd?: number\n /** Known non-provider amount supplied by an external executor. */\n estimatedCostUsd?: number\n /** Why the call failed. `'paid-call-failed'` is the ledger's own value for\n * recovery settles; a reconciling caller may record its own reason. */\n error?: string\n}\n\nexport type CostLedgerRecord = PendingCostCall | CostReceipt\n\nexport interface CostReceiptInput extends CostUsage {\n model: string\n /** Caller-supplied rates for a local estimate when the provider does not report billed cost. */\n customTokenPricing?: CustomTokenPricing\n actualCostUsd?: number\n /** A known estimate from an external executor that cannot provide token pricing. */\n estimatedCostUsd?: number\n costUnknown?: boolean\n usageUnknown?: boolean\n}\n\n/** Per-million token rates for a model or endpoint not covered by package pricing. */\nexport interface CustomTokenPricing {\n /** Non-cached input tokens. */\n inputUsdPerMillion: number\n /** Cache-read tokens. Falls back to the normal input rate when omitted. */\n cachedInputUsdPerMillion?: number\n /** Cache-creation or cache-write tokens. Falls back to the normal input rate when omitted. */\n cacheWriteUsdPerMillion?: number\n outputUsdPerMillion: number\n}\n\nexport type MaximumCharge =\n | { externallyEnforcedMaximumUsd: number }\n | ({\n customTokenPricing: CustomTokenPricing\n } & Pick<CostUsage, 'inputTokens' | 'outputTokens' | 'cachedTokens' | 'cacheWriteTokens'>)\n | ({ model: string } & CostUsage)\n\nexport interface RunPaidCallInput<T> {\n callId?: string\n channel: CostChannel\n phase: string\n actor: string\n /** Used before a provider receipt exists and on failures without one. */\n model?: string\n tags?: Record<string, string>\n signal?: AbortSignal\n /** Provider-enforced dollar maximum, or maximum token usage with known pricing. Required when capped. */\n maximumCharge?: MaximumCharge\n /** `callId` can be forwarded as the provider's idempotency key. */\n execute(signal: AbortSignal, callId: string): Promise<T>\n receipt(value: T): CostReceiptInput\n receiptFromError?(error: Error): CostReceiptInput | undefined\n}\n\nexport type PaidCallResult<T> =\n | { succeeded: true; callId: string; value: T; receipt: CostReceipt }\n | { succeeded: false; callId?: string; error: Error; receipt?: CostReceipt }\n\nexport interface ChannelRollup {\n channel: CostChannel\n calls: number\n inputTokens: number\n outputTokens: number\n reasoningTokens?: number\n cachedTokens: number\n cacheWriteTokens?: number\n costUsd: number\n unpricedCalls: number\n unknownUsageCalls: number\n}\n\nexport interface CostLedgerSummary {\n totalCalls: number\n pendingCalls: number\n unresolvedCalls: number\n reservedCostUsd: number\n inputTokens: number\n outputTokens: number\n reasoningTokens?: number\n cachedTokens: number\n cacheWriteTokens?: number\n totalCostUsd: number\n costProvenance: CostProvenance\n byChannel: ChannelRollup[]\n unpricedModels: string[]\n fullyPriced: boolean\n usageComplete: boolean\n accountingComplete: boolean\n incompleteReasons: string[]\n}\n\nexport interface CostLedgerFilter {\n channel?: CostChannel\n phase?: string\n tags?: Record<string, string>\n}\n\nexport interface CostLedgerWaitOptions {\n /** Maximum time to wait for active provider calls. Default 5 seconds. */\n timeoutMs?: number\n /** Wait only for calls matching this attribution filter. */\n filter?: CostLedgerFilter\n}\n\n/** Append-only storage. `append` must atomically reject stale revisions. */\nexport interface CostLedgerPersistence {\n read(): { revision: string; events: string }\n append(expectedRevision: string, event: string): string | undefined\n}\n\nexport interface CostLedgerOptions {\n costCeilingUsd?: number\n persistence?: CostLedgerPersistence\n /** Import already-settled receipts without admitting new paid work. */\n receipts?: readonly CostReceipt[]\n}\n\nexport class CostCeilingReachedError extends ValidationError {\n constructor(\n ceilingUsd: number,\n committedUsd: number,\n requestedUsd: number,\n phase: string,\n actor: string,\n ) {\n super(\n `CostLedger: reserving ${requestedUsd} for '${actor}' during '${phase}' would exceed ceiling ${ceilingUsd} with ${committedUsd} already committed`,\n )\n }\n}\n\nexport class CostAccountingIncompleteError extends ValidationError {}\n\nexport class CostReservationExceededError extends ValidationError {\n constructor(actor: string, actualUsd: number, maximumUsd: number) {\n super(\n `CostLedger: '${actor}' charged ${actualUsd}, exceeding its enforced maximum ${maximumUsd}`,\n )\n }\n}\n\nexport class CostCallConflictError extends ValidationError {\n readonly callId?: string\n readonly receipt?: CostReceipt\n\n constructor(\n message: string,\n options: { callId?: string; receipt?: CostReceipt; cause?: unknown } = {},\n ) {\n super(message, options.cause === undefined ? undefined : { cause: options.cause })\n this.callId = options.callId\n this.receipt = options.receipt ? cloneReceipt(options.receipt) : undefined\n }\n}\n\nexport class CostLedgerPersistenceError extends ValidationError {\n readonly callId?: string\n readonly receipt?: CostReceipt\n\n constructor(cause: unknown, callId?: string, receipt?: CostReceipt) {\n super(\n `CostLedger: failed to persist${callId ? ` call '${callId}'` : ''}: ${toError(cause).message}`,\n { cause },\n )\n this.callId = callId\n this.receipt = receipt ? cloneReceipt(receipt) : undefined\n }\n}\n\nexport class CostReceiptCaptureError extends ValidationError {\n readonly callId: string\n readonly receipt?: CostReceipt\n readonly receiptError: Error\n\n constructor(callId: string, cause: unknown, receiptError: unknown, receipt?: CostReceipt) {\n super(`CostLedger: could not capture the provider receipt for call '${callId}'`, { cause })\n this.callId = callId\n this.receipt = receipt ? cloneReceipt(receipt) : undefined\n this.receiptError = toError(receiptError)\n }\n}\n\ninterface PendingCostCallEvent {\n version: 1\n record: PendingCostCall\n}\n\ninterface SettledCostCallEvent {\n version: 2\n record: CostReceipt\n}\n\ninterface CompletedTasksEvent {\n version: 1\n completedTasks: number\n}\n\ninterface CostLimitEvent {\n version: 1\n costCeilingUsd: number\n}\n\ntype CostCallEvent = PendingCostCallEvent | SettledCostCallEvent\ntype CostLedgerEvent = CostCallEvent | CompletedTasksEvent | CostLimitEvent\n\n/** Run-wide paid-call admission, durable call state, receipts, and summaries. */\nexport class CostLedger {\n private readonly records = new Map<string, CostLedgerRecord>()\n private readonly activeCallIds = new Set<string>()\n private readonly lateCallIds = new Set<string>()\n private readonly idleWaiters = new Set<() => void>()\n private completedTasks = 0\n private revision = 'memory'\n private costLimitPersisted = false\n readonly costCeilingUsd?: number\n private readonly persistence?: CostLedgerPersistence\n\n constructor(input?: number | CostLedgerOptions) {\n const options = typeof input === 'number' ? { costCeilingUsd: input } : (input ?? {})\n this.persistence = options.persistence\n if (options.costCeilingUsd !== undefined) {\n assertNonNegative(options.costCeilingUsd, 'costCeilingUsd')\n }\n\n let persistedCostCeilingUsd: number | undefined\n if (this.persistence) {\n let stored: ReturnType<CostLedgerPersistence['read']>\n try {\n stored = this.persistence.read()\n } catch (cause) {\n throw new CostLedgerPersistenceError(cause)\n }\n assertString(stored.revision, 'persistence revision')\n this.revision = stored.revision\n const restored = parseEvents(stored.events)\n for (const record of restored.records) this.records.set(record.callId, record)\n this.completedTasks = restored.completedTasks\n persistedCostCeilingUsd = restored.costCeilingUsd\n }\n\n if (\n options.costCeilingUsd !== undefined &&\n persistedCostCeilingUsd !== undefined &&\n options.costCeilingUsd !== persistedCostCeilingUsd\n ) {\n throw new ValidationError(\n `CostLedger: requested cost ceiling ${options.costCeilingUsd} does not match persisted ceiling ${persistedCostCeilingUsd}`,\n )\n }\n this.costCeilingUsd = persistedCostCeilingUsd ?? options.costCeilingUsd\n this.costLimitPersisted =\n !this.persistence ||\n this.costCeilingUsd === undefined ||\n persistedCostCeilingUsd !== undefined\n\n if (\n this.costCeilingUsd !== undefined &&\n [...this.records.values()].some(\n (record) => record.status === 'pending' && record.maximumCostUsd === undefined,\n )\n ) {\n throw new ValidationError('CostLedger: capped event log contains an unbounded pending call')\n }\n\n if (options.receipts?.length) {\n const imported = options.receipts.map((receipt, index) =>\n parseImportedReceipt(receipt, `imported receipt ${index + 1}`),\n )\n this.ensureCostLimitPersisted()\n for (const receipt of imported) this.appendRecord(receipt)\n }\n }\n\n async runPaidCall<T>(input: RunPaidCallInput<T>): Promise<PaidCallResult<T>> {\n let callId: string | undefined\n let pending: PendingCostCall | undefined\n try {\n callId = resolveCallId(input.callId)\n validateAttribution(input)\n if (input.signal?.aborted) {\n return { succeeded: false, callId, error: abortError(input.signal) }\n }\n this.ensureCostLimitPersisted(callId)\n\n const maximumCostUsd = this.resolveMaximum(input.maximumCharge)\n const existing = this.records.get(callId)\n if (existing) {\n return {\n succeeded: false,\n callId,\n error: new CostCallConflictError(\n existing.status === 'pending'\n ? `CostLedger: callId '${callId}' is unresolved and must be reconciled before retry`\n : `CostLedger: callId '${callId}' already exists`,\n { callId },\n ),\n }\n }\n\n if (!pending) {\n while (true) {\n if (this.records.has(callId)) {\n return {\n succeeded: false,\n callId,\n error: new CostCallConflictError(`CostLedger: callId '${callId}' already exists`),\n }\n }\n const summary = this.summary()\n if (summary.unresolvedCalls > 0) {\n return {\n succeeded: false,\n callId,\n error: new CostAccountingIncompleteError(\n `CostLedger: ${summary.unresolvedCalls} unresolved call(s) must be reconciled before new paid work`,\n ),\n }\n }\n if (this.costCeilingUsd === undefined) break\n if (this.hasBudgetBreachingSettledCall()) {\n return {\n succeeded: false,\n callId,\n error: new CostAccountingIncompleteError(\n `CostLedger: a settled call exceeded its enforced maximum; refusing paid call '${input.actor}' during '${input.phase}'`,\n ),\n }\n }\n // A settled call whose cost the provider left unknown is charged its\n // reserved maximum here, so the ceiling is enforced against a real\n // upper bound and one under-reported response cannot let later calls\n // silently exceed the budget — while still permitting them.\n const committedCostUsd = this.conservativeSettledCostUsd()\n if (committedCostUsd + maximumCostUsd! > this.costCeilingUsd) {\n return {\n succeeded: false,\n callId,\n error: new CostCeilingReachedError(\n this.costCeilingUsd,\n committedCostUsd,\n maximumCostUsd!,\n input.phase,\n input.actor,\n ),\n }\n }\n if (committedCostUsd + summary.reservedCostUsd + maximumCostUsd! <= this.costCeilingUsd) {\n break\n }\n await this.waitForReservationRelease(input.signal)\n }\n\n pending = {\n status: 'pending',\n callId,\n channel: input.channel,\n phase: input.phase,\n actor: input.actor,\n model: pendingModel(input),\n ...(maximumCostUsd === undefined ? {} : { maximumCostUsd }),\n ...(input.tags ? { tags: { ...input.tags } } : {}),\n timestamp: Date.now(),\n }\n this.appendRecord(pending)\n this.activeCallIds.add(callId)\n }\n } catch (error) {\n return { succeeded: false, ...(callId ? { callId } : {}), error: toError(error) }\n }\n\n try {\n return await this.execute(input, pending)\n } catch (error) {\n return { succeeded: false, callId: pending.callId, error: toError(error) }\n } finally {\n if (!this.lateCallIds.has(pending.callId)) this.releaseActiveCall(pending.callId)\n }\n }\n\n /** Wait until every call started by this ledger has produced a durable outcome. */\n async waitForIdle(options: CostLedgerWaitOptions = {}): Promise<boolean> {\n const hasActiveMatch = (): boolean =>\n [...this.activeCallIds].some((callId) => {\n const record = this.records.get(callId)\n return record !== undefined && matches(record, options.filter)\n })\n if (!hasActiveMatch()) return true\n const timeoutMs = options.timeoutMs ?? 5_000\n assertTimeout(timeoutMs, 'waitForIdle.timeoutMs')\n return new Promise<boolean>((resolve) => {\n let timer: ReturnType<typeof setTimeout> | undefined\n const finish = (settled: boolean): void => {\n this.idleWaiters.delete(onIdle)\n if (timer !== undefined) clearTimeout(timer)\n resolve(settled)\n }\n const onIdle = (): void => {\n if (!hasActiveMatch()) finish(true)\n }\n this.idleWaiters.add(onIdle)\n timer = setTimeout(() => finish(false), timeoutMs)\n onIdle()\n })\n }\n\n /** Settle a call left pending by a crashed process after reconciling with the provider. */\n reconcile(\n callId: string,\n observed: CostReceiptInput,\n options: { failed?: boolean; error?: string } = {},\n ): CostReceipt {\n const pending = [...this.records.values()].find(\n (record): record is PendingCostCall =>\n record.callId === callId && record.status === 'pending',\n )\n if (!pending) throw new CostCallConflictError(`CostLedger: no pending call '${callId}'`)\n if (this.activeCallIds.has(callId)) {\n throw new CostCallConflictError(`CostLedger: call '${callId}' is still active`)\n }\n this.ensureCostLimitPersisted(callId)\n return this.commitReceipt(\n pending,\n observed,\n options.failed === true || options.error !== undefined,\n options.error,\n )\n }\n\n list(filter?: CostLedgerFilter): CostReceipt[] {\n return [...this.records.values()]\n .filter((record): record is CostReceipt => record.status === 'settled')\n .filter((receipt) => matches(receipt, filter))\n .map(cloneReceipt)\n }\n\n /** Read pending calls without exposing mutable ledger state. */\n listPending(filter?: CostLedgerFilter): PendingCostCallView[] {\n return [...this.records.values()]\n .filter((record): record is PendingCostCall => record.status === 'pending')\n .filter((record) => matches(record, filter))\n .map((record) => ({\n ...clonePendingCall(record),\n state: this.lateCallIds.has(record.callId)\n ? 'late'\n : this.activeCallIds.has(record.callId)\n ? 'active'\n : 'interrupted',\n }))\n }\n\n summary(filter?: CostLedgerFilter): CostLedgerSummary {\n const records = [...this.records.values()].filter((record) => matches(record, filter))\n const pending = records.filter(\n (record): record is PendingCostCall => record.status === 'pending',\n )\n const receipts = records.filter((record): record is CostReceipt => record.status === 'settled')\n const byChannel = new Map<string, ChannelRollup>()\n const unpriced = new Set<string>()\n const incompleteReasons: string[] = pending.map(\n (record) => `call '${record.callId}' for '${record.actor}' is pending`,\n )\n let inputTokens = 0\n let outputTokens = 0\n let reasoningTokens = 0\n let cachedTokens = 0\n let cacheWriteTokens = 0\n let totalCostUsd = 0\n\n for (const receipt of receipts) {\n inputTokens += receipt.inputTokens\n outputTokens += receipt.outputTokens\n reasoningTokens += receipt.reasoningTokens ?? 0\n cachedTokens += receipt.cachedTokens ?? 0\n cacheWriteTokens += receipt.cacheWriteTokens ?? 0\n totalCostUsd += receipt.costUsd\n if (receipt.costUnknown) {\n unpriced.add(receipt.model)\n incompleteReasons.push(\n receipt.error ?? `cost unknown for '${receipt.actor}' using '${receipt.model}'`,\n )\n }\n if (receipt.usageUnknown) {\n incompleteReasons.push(\n `token usage unknown for '${receipt.actor}' using '${receipt.model}'`,\n )\n }\n if (receipt.maximumCostUsd !== undefined && receipt.costUsd > receipt.maximumCostUsd) {\n incompleteReasons.push(\n `'${receipt.actor}' charged ${receipt.costUsd}, exceeding its enforced maximum ${receipt.maximumCostUsd}`,\n )\n }\n const rollup = byChannel.get(receipt.channel) ?? emptyRollup(receipt.channel)\n rollup.calls += 1\n rollup.inputTokens += receipt.inputTokens\n rollup.outputTokens += receipt.outputTokens\n rollup.reasoningTokens = (rollup.reasoningTokens ?? 0) + (receipt.reasoningTokens ?? 0)\n rollup.cachedTokens += receipt.cachedTokens ?? 0\n rollup.cacheWriteTokens = (rollup.cacheWriteTokens ?? 0) + (receipt.cacheWriteTokens ?? 0)\n rollup.costUsd += receipt.costUsd\n if (receipt.costUnknown) rollup.unpricedCalls += 1\n if (receipt.usageUnknown) rollup.unknownUsageCalls += 1\n byChannel.set(receipt.channel, rollup)\n }\n\n return {\n totalCalls: receipts.length,\n pendingCalls: pending.length,\n unresolvedCalls: pending.filter(\n (record) => !this.activeCallIds.has(record.callId) || this.lateCallIds.has(record.callId),\n ).length,\n reservedCostUsd: pending.reduce((sum, record) => sum + (record.maximumCostUsd ?? 0), 0),\n inputTokens,\n outputTokens,\n reasoningTokens,\n cachedTokens,\n cacheWriteTokens,\n totalCostUsd,\n costProvenance:\n pending.length > 0 || receipts.some((receipt) => receipt.costUnknown)\n ? { kind: 'uncaptured', usd: null }\n : receipts.every((receipt) => receipt.actualCostUsd !== undefined)\n ? { kind: 'observed', usd: totalCostUsd }\n : { kind: 'estimated', usd: totalCostUsd },\n byChannel: [...byChannel.values()].sort((a, b) => a.channel.localeCompare(b.channel)),\n unpricedModels: [...unpriced].sort(),\n fullyPriced: unpriced.size === 0,\n usageComplete: pending.length === 0 && receipts.every((receipt) => !receipt.usageUnknown),\n accountingComplete: incompleteReasons.length === 0,\n incompleteReasons: [...new Set(incompleteReasons)],\n }\n }\n\n markCompleted(count = 1): void {\n if (!Number.isInteger(count) || count < 0) {\n throw new ValidationError(\n `CostLedger.markCompleted: count must be a non-negative integer, got ${count}`,\n )\n }\n if (count === 0) return\n this.ensureCostLimitPersisted()\n this.appendEvent({ version: 1, completedTasks: count })\n this.completedTasks += count\n }\n\n costPerCompletedTask(): number | null {\n return this.completedTasks === 0 ? null : this.summary().totalCostUsd / this.completedTasks\n }\n\n private async execute<T>(\n input: RunPaidCallInput<T>,\n pending: PendingCostCall,\n ): Promise<PaidCallResult<T>> {\n const signal = input.signal ?? new AbortController().signal\n if (signal.aborted) {\n return this.commitOutcome(pending, abortError(signal), {\n model: pending.model,\n inputTokens: 0,\n outputTokens: 0,\n actualCostUsd: 0,\n })\n }\n\n const operation = Promise.resolve().then(() => input.execute(signal, pending.callId))\n const settled = await settle(operation, signal)\n if (settled.kind === 'aborted') {\n this.lateCallIds.add(pending.callId)\n this.captureLateOutcome(input, pending, operation)\n return paidFailure(pending.callId, abortError(signal))\n }\n if (settled.kind === 'error') {\n let observed: CostReceiptInput | undefined\n try {\n observed = input.receiptFromError?.(settled.error)\n } catch (receiptError) {\n return this.captureFailure(pending, settled.error, receiptError)\n }\n return this.commitOutcome(pending, settled.error, observed ?? unknownReceipt(pending.model))\n }\n\n try {\n const receipt = this.commitReceipt(pending, input.receipt(settled.value))\n if (receipt.maximumCostUsd !== undefined && receipt.costUsd > receipt.maximumCostUsd) {\n return paidFailure(\n pending.callId,\n new CostReservationExceededError(pending.actor, receipt.costUsd, receipt.maximumCostUsd),\n receipt,\n )\n }\n return { succeeded: true, callId: pending.callId, value: settled.value, receipt }\n } catch (receiptError) {\n if (\n receiptError instanceof CostLedgerPersistenceError ||\n receiptError instanceof CostCallConflictError\n ) {\n return paidFailure(pending.callId, receiptError)\n }\n return this.captureFailure(pending, receiptError, receiptError)\n }\n }\n\n private captureLateOutcome<T>(\n input: RunPaidCallInput<T>,\n pending: PendingCostCall,\n operation: Promise<T>,\n ): void {\n void operation\n .then(\n (value) => {\n if (this.records.get(pending.callId)?.status !== 'pending') return\n try {\n this.commitReceipt(pending, input.receipt(value))\n } catch {\n // A failed durable settlement leaves the reservation pending and blocks new paid work.\n }\n },\n (cause) => {\n if (this.records.get(pending.callId)?.status !== 'pending') return\n const error = toError(cause)\n try {\n const observed = input.receiptFromError?.(error)\n this.commitReceipt(pending, observed ?? unknownReceipt(pending.model), true)\n } catch (receiptError) {\n if (\n receiptError instanceof CostLedgerPersistenceError ||\n receiptError instanceof CostCallConflictError\n ) {\n return\n }\n this.captureFailure(pending, error, receiptError)\n }\n },\n )\n .finally(() => {\n this.lateCallIds.delete(pending.callId)\n this.releaseActiveCall(pending.callId)\n })\n }\n\n private releaseActiveCall(callId: string): void {\n this.activeCallIds.delete(callId)\n for (const resolve of [...this.idleWaiters]) resolve()\n }\n\n private async waitForReservationRelease(signal?: AbortSignal): Promise<void> {\n if (signal?.aborted) throw abortError(signal)\n await new Promise<void>((resolve, reject) => {\n let finished = false\n const finish = (error?: Error): void => {\n if (finished) return\n finished = true\n this.idleWaiters.delete(onRelease)\n signal?.removeEventListener('abort', onAbort)\n if (error) reject(error)\n else resolve()\n }\n const onRelease = (): void => finish()\n const onAbort = (): void => finish(abortError(signal!))\n this.idleWaiters.add(onRelease)\n signal?.addEventListener('abort', onAbort, { once: true })\n if (this.activeCallIds.size === 0) onRelease()\n })\n }\n\n private commitOutcome<T>(\n pending: PendingCostCall,\n error: Error,\n observed: CostReceiptInput,\n ): PaidCallResult<T> {\n try {\n const receipt = this.commitReceipt(pending, observed, true)\n return paidFailure(pending.callId, error, receipt)\n } catch (receiptError) {\n if (\n receiptError instanceof CostLedgerPersistenceError ||\n receiptError instanceof CostCallConflictError\n ) {\n return paidFailure(pending.callId, receiptError)\n }\n return this.captureFailure(pending, error, receiptError)\n }\n }\n\n private captureFailure<T>(\n pending: PendingCostCall,\n cause: unknown,\n receiptError: unknown,\n ): PaidCallResult<T> {\n try {\n const receipt = this.commitReceipt(pending, unknownReceipt(pending.model), true)\n return paidFailure(\n pending.callId,\n new CostReceiptCaptureError(pending.callId, cause, receiptError, receipt),\n receipt,\n )\n } catch (error) {\n const typed = error instanceof Error ? error : toError(error)\n return paidFailure(pending.callId, typed)\n }\n }\n\n private commitReceipt(\n pending: PendingCostCall,\n observed: CostReceiptInput,\n failed = false,\n error?: string,\n ): CostReceipt {\n const receipt = buildReceipt(pending, observed, failed, error)\n if (this.records.get(pending.callId)?.status !== 'pending') {\n throw new CostCallConflictError(`CostLedger: call '${pending.callId}' is not pending`)\n }\n this.appendRecord(receipt)\n return cloneReceipt(receipt)\n }\n\n private resolveMaximum(maximum: MaximumCharge | undefined): number | undefined {\n if (!maximum) {\n if (this.costCeilingUsd !== undefined) {\n throw new CostAccountingIncompleteError(\n 'CostLedger: capped paid calls require a hard maximumCharge before execution',\n )\n }\n return undefined\n }\n if ('externallyEnforcedMaximumUsd' in maximum) {\n assertNonNegative(\n maximum.externallyEnforcedMaximumUsd,\n 'maximumCharge.externallyEnforcedMaximumUsd',\n )\n return maximum.externallyEnforcedMaximumUsd\n }\n if ('customTokenPricing' in maximum) {\n return costForTokenPricing(maximum.customTokenPricing, maximum)\n }\n const priced = costForUsage(maximum.model, maximum)\n if (priced.costUnknown) {\n if (this.costCeilingUsd !== undefined) {\n throw new CostAccountingIncompleteError(\n `CostLedger: cannot reserve unpriced model '${maximum.model}' in a capped run`,\n )\n }\n return undefined\n }\n return priced.costUsd\n }\n\n private hasBudgetBreachingSettledCall(): boolean {\n return [...this.records.values()].some(\n (record) =>\n record.status === 'settled' &&\n record.maximumCostUsd !== undefined &&\n record.costUsd > record.maximumCostUsd,\n )\n }\n\n /**\n * Total settled cost with each unknown-cost call charged its reserved\n * maximum. A provider that omits a call's cost cannot make the ceiling check\n * under-count: the call is bounded by what it was allowed to spend.\n */\n private conservativeSettledCostUsd(): number {\n let total = 0\n for (const record of this.records.values()) {\n if (record.status !== 'settled') continue\n total += record.costUnknown ? (record.maximumCostUsd ?? record.costUsd) : record.costUsd\n }\n return total\n }\n\n private appendRecord(record: CostLedgerRecord): void {\n const callId = record.callId\n const receipt = record.status === 'settled' ? record : undefined\n validateTransition(this.records, record)\n const event: CostCallEvent =\n record.status === 'settled'\n ? { version: 2, record: cloneReceipt(record) }\n : { version: 1, record: clonePendingCall(record) }\n this.appendEvent(event, callId, receipt)\n this.records.set(callId, cloneRecord(record))\n }\n\n private ensureCostLimitPersisted(callId?: string): void {\n if (this.costLimitPersisted || this.costCeilingUsd === undefined) return\n this.appendEvent({ version: 1, costCeilingUsd: this.costCeilingUsd }, callId)\n this.costLimitPersisted = true\n }\n\n private appendEvent(event: CostLedgerEvent, callId?: string, receipt?: CostReceipt): void {\n try {\n if (this.persistence) {\n const nextRevision = this.persistence.append(this.revision, `${JSON.stringify(event)}\\n`)\n if (nextRevision === undefined) {\n throw new CostCallConflictError(\n `CostLedger: persisted revision changed while writing call '${callId}'`,\n { callId, receipt },\n )\n }\n assertString(nextRevision, 'persistence revision')\n this.revision = nextRevision\n }\n } catch (cause) {\n if (cause instanceof CostCallConflictError) throw cause\n throw new CostLedgerPersistenceError(cause, callId, receipt)\n }\n }\n}\n\n/** Public callback surface for a shared cost ledger.\n *\n * Declaration bundles may expose this type through multiple package subpaths.\n * Keeping callback contracts structural lets those subpaths compose while the\n * concrete {@link CostLedger} retains its private durable state.\n */\nexport type CostLedgerHandle = Pick<\n CostLedger,\n Exclude<keyof CostLedger, 'listPending' | 'waitForIdle'>\n> &\n Partial<Pick<CostLedger, 'listPending' | 'waitForIdle'>>\n\n/** Return the canonical pricing-table key, or null when the model is unpriced. */\nexport function modelPriceKey(model: string): string | null {\n return isModelPriced(model) ? model : null\n}\n\nexport interface CostResult {\n costUsd: number\n costUnknown: boolean\n}\n\nexport function costForUsage(model: string, usage: CostUsage): CostResult {\n assertUsage(usage)\n if (!resolveModelPricing(model)) return { costUsd: 0, costUnknown: true }\n return {\n costUsd: estimateCost(\n usage.inputTokens + (usage.cachedTokens ?? 0) + (usage.cacheWriteTokens ?? 0),\n usage.outputTokens,\n model,\n ),\n costUnknown: false,\n }\n}\n\n/** Price token counts with caller-supplied per-million rates. */\nexport function costForTokenPricing(\n pricing: CustomTokenPricing,\n usage: Pick<CostUsage, 'inputTokens' | 'outputTokens' | 'cachedTokens' | 'cacheWriteTokens'>,\n): number {\n assertTokenCount(usage.inputTokens, 'usage.inputTokens')\n assertTokenCount(usage.outputTokens, 'usage.outputTokens')\n if (usage.cachedTokens !== undefined) {\n assertTokenCount(usage.cachedTokens, 'usage.cachedTokens')\n }\n if (usage.cacheWriteTokens !== undefined) {\n assertTokenCount(usage.cacheWriteTokens, 'usage.cacheWriteTokens')\n }\n assertNonNegative(pricing.inputUsdPerMillion, 'pricing.inputUsdPerMillion')\n if (pricing.cachedInputUsdPerMillion !== undefined) {\n assertNonNegative(pricing.cachedInputUsdPerMillion, 'pricing.cachedInputUsdPerMillion')\n }\n if (pricing.cacheWriteUsdPerMillion !== undefined) {\n assertNonNegative(pricing.cacheWriteUsdPerMillion, 'pricing.cacheWriteUsdPerMillion')\n }\n assertNonNegative(pricing.outputUsdPerMillion, 'pricing.outputUsdPerMillion')\n const cachedInputRate = pricing.cachedInputUsdPerMillion ?? pricing.inputUsdPerMillion\n const cacheWriteRate = pricing.cacheWriteUsdPerMillion ?? pricing.inputUsdPerMillion\n return (\n (usage.inputTokens / 1_000_000) * pricing.inputUsdPerMillion +\n ((usage.cachedTokens ?? 0) / 1_000_000) * cachedInputRate +\n ((usage.cacheWriteTokens ?? 0) / 1_000_000) * cacheWriteRate +\n (usage.outputTokens / 1_000_000) * pricing.outputUsdPerMillion\n )\n}\n\ntype Settled<T> =\n | { kind: 'value'; value: T }\n | { kind: 'error'; error: Error }\n | { kind: 'aborted' }\n\nasync function settle<T>(promise: Promise<T>, signal: AbortSignal): Promise<Settled<T>> {\n return await new Promise((resolve) => {\n let done = false\n const finish = (value: Settled<T>): void => {\n if (done) return\n done = true\n signal.removeEventListener('abort', onAbort)\n resolve(value)\n }\n const onAbort = () => finish({ kind: 'aborted' })\n signal.addEventListener('abort', onAbort, { once: true })\n if (signal.aborted) onAbort()\n promise.then(\n (value) => finish({ kind: 'value', value }),\n (error) => finish({ kind: 'error', error: toError(error) }),\n )\n })\n}\n\nfunction buildReceipt(\n pending: PendingCostCall,\n observed: CostReceiptInput,\n failed = false,\n error?: string,\n): CostReceipt {\n assertUsage(observed)\n assertString(observed.model, 'receipt.model')\n const suppliedAmounts = [\n observed.actualCostUsd,\n observed.estimatedCostUsd,\n observed.customTokenPricing,\n ].filter((value) => value !== undefined)\n if (suppliedAmounts.length > 1) {\n throw new ValidationError(\n 'CostLedger: a receipt can have only one of actualCostUsd, estimatedCostUsd, or customTokenPricing',\n )\n }\n const customPricingSnapshot =\n observed.customTokenPricing === undefined\n ? undefined\n : pricingSnapshot(observed.customTokenPricing)\n const estimated = customPricingSnapshot\n ? {\n costUsd: costFromPricing(observed, customPricingSnapshot),\n costUnknown: false,\n }\n : costForUsage(observed.model, observed)\n const hasActual = observed.actualCostUsd !== undefined\n const hasExternalEstimate = observed.estimatedCostUsd !== undefined\n if (hasActual && observed.costUnknown === true) {\n throw new ValidationError(\n 'CostLedger: a receipt cannot have both actualCostUsd and costUnknown=true',\n )\n }\n if (hasActual) assertNonNegative(observed.actualCostUsd!, 'actualCostUsd')\n if (hasExternalEstimate) assertNonNegative(observed.estimatedCostUsd!, 'estimatedCostUsd')\n if (hasExternalEstimate && observed.costUnknown === true) {\n throw new ValidationError(\n 'CostLedger: a receipt cannot have both estimatedCostUsd and costUnknown=true',\n )\n }\n const usageUnknown = observed.usageUnknown === true\n const costUnknown =\n observed.costUnknown === true ||\n (!hasActual && !hasExternalEstimate && (usageUnknown || estimated.costUnknown))\n const resolvedModelPricing =\n !customPricingSnapshot && !hasActual && !hasExternalEstimate && !costUnknown\n ? resolveModelPricing(observed.model)\n : null\n const receiptPricing =\n !hasActual && !hasExternalEstimate && !costUnknown\n ? (customPricingSnapshot ??\n (resolvedModelPricing\n ? {\n inputUsdPerThousand: resolvedModelPricing.input,\n outputUsdPerThousand: resolvedModelPricing.output,\n }\n : undefined))\n : undefined\n return parseReceipt(\n {\n status: 'settled',\n callId: pending.callId,\n channel: pending.channel,\n phase: pending.phase,\n actor: pending.actor,\n model: observed.model,\n inputTokens: observed.inputTokens,\n outputTokens: observed.outputTokens,\n ...(observed.reasoningTokens === undefined\n ? {}\n : { reasoningTokens: observed.reasoningTokens }),\n ...(observed.cachedTokens === undefined ? {} : { cachedTokens: observed.cachedTokens }),\n ...(observed.cacheWriteTokens === undefined\n ? {}\n : { cacheWriteTokens: observed.cacheWriteTokens }),\n costUsd: costUnknown\n ? 0\n : hasActual\n ? observed.actualCostUsd!\n : hasExternalEstimate\n ? observed.estimatedCostUsd!\n : estimated.costUsd,\n costUnknown,\n usageUnknown,\n ...(receiptPricing ? { pricing: receiptPricing } : {}),\n ...(hasActual ? { actualCostUsd: observed.actualCostUsd } : {}),\n ...(hasExternalEstimate ? { estimatedCostUsd: observed.estimatedCostUsd } : {}),\n ...(pending.maximumCostUsd === undefined ? {} : { maximumCostUsd: pending.maximumCostUsd }),\n ...(failed ? { error: error ?? 'paid-call-failed' } : {}),\n ...(pending.tags ? { tags: { ...pending.tags } } : {}),\n timestamp: pending.timestamp,\n },\n 'provider receipt',\n )\n}\n\nconst NonEmptyString = z.string().refine((value) => value.trim().length > 0, 'must be non-empty')\nconst TokenCount = z.number().int().nonnegative().finite()\nconst NonNegative = z.number().nonnegative().finite()\nconst Tags = z.record(NonEmptyString, z.string())\nconst CostPricingSchema = z.strictObject({\n inputUsdPerThousand: NonNegative,\n cachedInputUsdPerThousand: NonNegative.optional(),\n cacheWriteUsdPerThousand: NonNegative.optional(),\n outputUsdPerThousand: NonNegative,\n})\nconst CostCallBaseShape = {\n callId: NonEmptyString,\n channel: NonEmptyString,\n phase: NonEmptyString,\n actor: NonEmptyString,\n model: NonEmptyString,\n maximumCostUsd: NonNegative.optional(),\n tags: Tags.optional(),\n timestamp: NonNegative,\n}\nconst PendingCostCallSchema = z.strictObject({\n status: z.literal('pending'),\n ...CostCallBaseShape,\n})\nconst CostReceiptBaseShape = {\n status: z.literal('settled'),\n ...CostCallBaseShape,\n inputTokens: TokenCount,\n outputTokens: TokenCount,\n cachedTokens: TokenCount.optional(),\n costUsd: NonNegative,\n costUnknown: z.boolean(),\n usageUnknown: z.boolean().default(false),\n pricing: CostPricingSchema.optional(),\n actualCostUsd: NonNegative.optional(),\n estimatedCostUsd: NonNegative.optional(),\n error: NonEmptyString.optional(),\n}\nconst CostReceiptSchema = z\n .strictObject({\n ...CostReceiptBaseShape,\n reasoningTokens: TokenCount.optional(),\n cacheWriteTokens: TokenCount.optional(),\n })\n .superRefine((receipt, ctx) => validateCostReceipt(receipt, ctx))\n\nfunction validateCostReceipt(\n receipt: CostUsage & {\n costUsd: number\n costUnknown: boolean\n usageUnknown: boolean\n pricing?: NonNullable<CostReceipt['pricing']>\n actualCostUsd?: number\n estimatedCostUsd?: number\n },\n ctx: z.RefinementCtx,\n): void {\n if (receipt.reasoningTokens !== undefined && receipt.reasoningTokens > receipt.outputTokens) {\n ctx.addIssue({ code: 'custom', message: 'reasoningTokens must not exceed outputTokens' })\n }\n\n if (receipt.actualCostUsd !== undefined && receipt.estimatedCostUsd !== undefined) {\n ctx.addIssue({\n code: 'custom',\n message: 'actual and external estimated costs cannot both be present',\n })\n }\n\n if (receipt.actualCostUsd !== undefined) {\n if (receipt.costUnknown || receipt.costUsd !== receipt.actualCostUsd) {\n ctx.addIssue({ code: 'custom', message: 'actual cost must be known and equal costUsd' })\n }\n if (receipt.pricing !== undefined) {\n ctx.addIssue({ code: 'custom', message: 'actual cost must not include estimated pricing' })\n }\n return\n }\n\n if (receipt.estimatedCostUsd !== undefined) {\n if (receipt.costUnknown || receipt.costUsd !== receipt.estimatedCostUsd) {\n ctx.addIssue({ code: 'custom', message: 'external estimate must be known and equal costUsd' })\n }\n if (receipt.pricing !== undefined) {\n ctx.addIssue({ code: 'custom', message: 'external estimate must not include token pricing' })\n }\n return\n }\n\n if (receipt.costUnknown) {\n if (receipt.costUsd !== 0) {\n ctx.addIssue({ code: 'custom', message: 'unknown cost must have costUsd 0' })\n }\n if (receipt.pricing !== undefined) {\n ctx.addIssue({ code: 'custom', message: 'unknown cost must not include estimated pricing' })\n }\n return\n }\n\n if (receipt.usageUnknown) {\n ctx.addIssue({ code: 'custom', message: 'known estimated cost requires known usage' })\n }\n if (!receipt.pricing) {\n ctx.addIssue({ code: 'custom', message: 'known estimated cost requires a pricing snapshot' })\n return\n }\n\n const expected = costFromPricing(receipt, receipt.pricing)\n if (!costAmountsMatch(receipt.costUsd, expected)) {\n ctx.addIssue({\n code: 'custom',\n message: `estimated cost ${receipt.costUsd} does not match pricing snapshot ${expected}`,\n })\n }\n}\n\nfunction costAmountsMatch(left: number, right: number): boolean {\n const scale = Math.max(1, Math.abs(left), Math.abs(right))\n return Math.abs(left - right) <= Number.EPSILON * scale * 8\n}\n\nconst CostLedgerEventSchema = z.union([\n z.strictObject({\n version: z.literal(1),\n record: PendingCostCallSchema,\n }),\n z.strictObject({\n version: z.literal(2),\n record: CostReceiptSchema,\n }),\n z.strictObject({\n version: z.literal(1),\n completedTasks: TokenCount,\n }),\n z.strictObject({\n version: z.literal(1),\n costCeilingUsd: NonNegative,\n }),\n])\n\nfunction parseEvents(serialized: string): {\n records: CostLedgerRecord[]\n completedTasks: number\n costCeilingUsd?: number\n} {\n const records = new Map<string, CostLedgerRecord>()\n let completedTasks = 0\n let costCeilingUsd: number | undefined\n let lineNumber = 0\n try {\n for (const line of completeJournalPrefix(serialized).split('\\n')) {\n if (!line.trim()) continue\n lineNumber += 1\n const event = CostLedgerEventSchema.parse(JSON.parse(line)) as CostLedgerEvent\n if ('record' in event) {\n const record = event.record\n validateTransition(records, record)\n records.set(record.callId, cloneRecord(record))\n } else if ('completedTasks' in event) {\n completedTasks += event.completedTasks\n if (!Number.isSafeInteger(completedTasks)) {\n throw new ValidationError('CostLedger: completed task count exceeds safe integer range')\n }\n } else {\n if (costCeilingUsd !== undefined) {\n throw new ValidationError('CostLedger: duplicate persisted cost ceiling')\n }\n costCeilingUsd = event.costCeilingUsd\n }\n }\n return {\n records: [...records.values()],\n completedTasks,\n ...(costCeilingUsd === undefined ? {} : { costCeilingUsd }),\n }\n } catch (cause) {\n throw new ValidationError(\n `CostLedger: invalid persisted event ${lineNumber || 1}: ${validationMessage(cause)}`,\n { cause },\n )\n }\n}\n\nfunction completeJournalPrefix(serialized: string): string {\n if (!serialized || serialized.endsWith('\\n')) return serialized\n const finalNewline = serialized.lastIndexOf('\\n')\n const tail = serialized.slice(finalNewline + 1)\n try {\n JSON.parse(tail)\n } catch {\n return finalNewline < 0 ? '' : serialized.slice(0, finalNewline + 1)\n }\n throw new ValidationError(\n 'CostLedger: complete final persisted event is missing its newline terminator',\n )\n}\n\nfunction validateTransition(\n records: ReadonlyMap<string, CostLedgerRecord>,\n record: CostLedgerRecord,\n): void {\n const current = records.get(record.callId)\n if (!current) return\n if (record.status === 'pending' || current.status === 'settled') {\n throw new CostCallConflictError(`CostLedger: duplicate callId '${record.callId}'`)\n }\n if (!sameAttribution(current, record)) {\n throw new ValidationError(`CostLedger: receipt attribution changed for call '${record.callId}'`)\n }\n}\n\nfunction sameAttribution(before: CostCallBase, after: CostCallBase): boolean {\n return (\n before.channel === after.channel &&\n before.phase === after.phase &&\n before.actor === after.actor &&\n before.maximumCostUsd === after.maximumCostUsd &&\n before.timestamp === after.timestamp &&\n sameTags(before.tags, after.tags)\n )\n}\n\nfunction sameTags(\n left: Readonly<Record<string, string>> | undefined,\n right: Readonly<Record<string, string>> | undefined,\n): boolean {\n const leftEntries = Object.entries(left ?? {}).sort(([a], [b]) => a.localeCompare(b))\n const rightEntries = Object.entries(right ?? {}).sort(([a], [b]) => a.localeCompare(b))\n return JSON.stringify(leftEntries) === JSON.stringify(rightEntries)\n}\n\nfunction parseReceipt(value: unknown, path: string): CostReceipt {\n try {\n return CostReceiptSchema.parse(value) as CostReceipt\n } catch (cause) {\n throw new ValidationError(`CostLedger: invalid ${path}: ${validationMessage(cause)}`, { cause })\n }\n}\n\nfunction parseImportedReceipt(value: unknown, path: string): CostReceipt {\n if (typeof value !== 'object' || value === null) return parseReceipt(value, path)\n const candidate = { ...value } as Record<string, unknown>\n if (\n candidate.status === 'settled' &&\n candidate.actualCostUsd === undefined &&\n candidate.estimatedCostUsd === undefined &&\n candidate.costUnknown === false &&\n candidate.pricing === undefined &&\n typeof candidate.model === 'string'\n ) {\n const pricing = resolveModelPricing(candidate.model)\n if (pricing) {\n candidate.pricing = {\n inputUsdPerThousand: pricing.input,\n outputUsdPerThousand: pricing.output,\n }\n }\n }\n return parseReceipt(candidate, path)\n}\n\nfunction validateAttribution(\n input: Pick<RunPaidCallInput<unknown>, 'channel' | 'phase' | 'actor' | 'model' | 'tags'>,\n): void {\n assertString(input.channel, 'channel')\n assertString(input.phase, 'phase')\n assertString(input.actor, 'actor')\n if (input.model !== undefined) assertString(input.model, 'model')\n if (input.tags !== undefined) {\n const parsed = Tags.safeParse(input.tags)\n if (!parsed.success)\n throw new ValidationError(`CostLedger: invalid tags: ${parsed.error.message}`)\n }\n}\n\nfunction matches(record: CostCallBase, filter: CostLedgerFilter | undefined): boolean {\n if (!filter) return true\n if (filter.channel !== undefined && record.channel !== filter.channel) return false\n if (filter.phase !== undefined && record.phase !== filter.phase) return false\n return Object.entries(filter.tags ?? {}).every(([key, value]) => record.tags?.[key] === value)\n}\n\nfunction cloneRecord(record: CostLedgerRecord): CostLedgerRecord {\n if (record.status === 'settled') return cloneReceipt(record)\n return clonePendingCall(record)\n}\n\nfunction clonePendingCall(record: PendingCostCall): PendingCostCall {\n const { tags, ...rest } = record\n return { ...rest, ...(tags ? { tags: { ...tags } } : {}) }\n}\n\nfunction cloneReceipt(receipt: CostReceipt): CostReceipt {\n const { pricing, tags, ...rest } = receipt\n return {\n ...rest,\n ...(tags ? { tags: { ...tags } } : {}),\n ...(pricing ? { pricing: { ...pricing } } : {}),\n }\n}\n\nfunction costFromPricing(usage: CostUsage, pricing: NonNullable<CostReceipt['pricing']>): number {\n const cachedInputRate = pricing.cachedInputUsdPerThousand ?? pricing.inputUsdPerThousand\n const cacheWriteRate = pricing.cacheWriteUsdPerThousand ?? pricing.inputUsdPerThousand\n return (\n (usage.inputTokens / 1000) * pricing.inputUsdPerThousand +\n ((usage.cachedTokens ?? 0) / 1000) * cachedInputRate +\n ((usage.cacheWriteTokens ?? 0) / 1000) * cacheWriteRate +\n (usage.outputTokens / 1000) * pricing.outputUsdPerThousand\n )\n}\n\nfunction pricingSnapshot(pricing: CustomTokenPricing): NonNullable<CostReceipt['pricing']> {\n costForTokenPricing(pricing, { inputTokens: 0, outputTokens: 0 })\n return {\n inputUsdPerThousand: pricing.inputUsdPerMillion / 1000,\n ...(pricing.cachedInputUsdPerMillion === undefined\n ? {}\n : { cachedInputUsdPerThousand: pricing.cachedInputUsdPerMillion / 1000 }),\n ...(pricing.cacheWriteUsdPerMillion === undefined\n ? {}\n : { cacheWriteUsdPerThousand: pricing.cacheWriteUsdPerMillion / 1000 }),\n outputUsdPerThousand: pricing.outputUsdPerMillion / 1000,\n }\n}\n\nfunction emptyRollup(channel: CostChannel): ChannelRollup {\n return {\n channel,\n calls: 0,\n inputTokens: 0,\n outputTokens: 0,\n reasoningTokens: 0,\n cachedTokens: 0,\n cacheWriteTokens: 0,\n costUsd: 0,\n unpricedCalls: 0,\n unknownUsageCalls: 0,\n }\n}\n\nfunction pendingModel(input: RunPaidCallInput<unknown>): string {\n if (input.model) return input.model\n if (input.maximumCharge && 'model' in input.maximumCharge) return input.maximumCharge.model\n return 'unknown'\n}\n\nfunction unknownReceipt(model: string): CostReceiptInput {\n return { model, inputTokens: 0, outputTokens: 0, costUnknown: true, usageUnknown: true }\n}\n\nfunction resolveCallId(input: string | undefined): string {\n if (input !== undefined) {\n assertString(input, 'callId')\n return input\n }\n if (typeof globalThis.crypto?.randomUUID !== 'function') {\n throw new ValidationError('CostLedger: crypto.randomUUID is required when callId is omitted')\n }\n return globalThis.crypto.randomUUID()\n}\n\nfunction abortError(signal: AbortSignal): Error {\n const reason = (signal as { reason?: unknown }).reason\n if (reason instanceof Error) return reason\n const error = new Error('CostLedger: paid call aborted')\n error.name = 'AbortError'\n return error\n}\n\nfunction toError(value: unknown): Error {\n return value instanceof Error ? value : new Error(String(value))\n}\n\nfunction paidFailure<T>(callId: string, error: Error, receipt?: CostReceipt): PaidCallResult<T> {\n return {\n succeeded: false,\n callId,\n error,\n ...(receipt ? { receipt: cloneReceipt(receipt) } : {}),\n }\n}\n\nfunction validationMessage(cause: unknown): string {\n return cause instanceof z.ZodError ? z.prettifyError(cause) : toError(cause).message\n}\n\nfunction assertUsage(usage: CostUsage): void {\n assertTokenCount(usage.inputTokens, 'inputTokens')\n assertTokenCount(usage.outputTokens, 'outputTokens')\n if (usage.reasoningTokens !== undefined) {\n assertTokenCount(usage.reasoningTokens, 'reasoningTokens')\n if (usage.reasoningTokens > usage.outputTokens) {\n throw new ValidationError('CostLedger: reasoningTokens must not exceed outputTokens')\n }\n }\n if (usage.cachedTokens !== undefined) assertTokenCount(usage.cachedTokens, 'cachedTokens')\n if (usage.cacheWriteTokens !== undefined) {\n assertTokenCount(usage.cacheWriteTokens, 'cacheWriteTokens')\n }\n}\n\nfunction assertTokenCount(value: unknown, name: string): asserts value is number {\n if (typeof value !== 'number' || !Number.isInteger(value) || value < 0) {\n throw new ValidationError(\n `CostLedger: ${name} must be a non-negative integer, got ${String(value)}`,\n )\n }\n}\n\nfunction assertNonNegative(value: unknown, name: string): asserts value is number {\n if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) {\n throw new ValidationError(\n `CostLedger: ${name} must be a non-negative finite number, got ${String(value)}`,\n )\n }\n}\n\nfunction assertTimeout(value: unknown, name: string): asserts value is number {\n if (\n typeof value !== 'number' ||\n !Number.isSafeInteger(value) ||\n value < 0 ||\n value > 2_147_483_647\n ) {\n throw new ValidationError(\n `CostLedger: ${name} must be a non-negative safe integer no greater than 2147483647, got ${String(value)}`,\n )\n }\n}\n\nfunction assertString(value: unknown, name: string): asserts value is string {\n if (typeof value !== 'string' || value.trim().length === 0) {\n throw new ValidationError(`CostLedger: ${name} must be a non-empty string`)\n }\n}\n"],"mappings":";;;;AA+KA,IAAa,0BAAb,cAA6C,gBAAgB;CAC3D,YACE,YACA,cACA,cACA,OACA,OACA;EACA,MACE,yBAAyB,aAAa,QAAQ,MAAM,YAAY,MAAM,yBAAyB,WAAW,QAAQ,aAAa,mBACjI;CACF;AACF;AAEA,IAAa,gCAAb,cAAmD,gBAAgB,CAAC;AAEpE,IAAa,+BAAb,cAAkD,gBAAgB;CAChE,YAAY,OAAe,WAAmB,YAAoB;EAChE,MACE,gBAAgB,MAAM,YAAY,UAAU,mCAAmC,YACjF;CACF;AACF;AAEA,IAAa,wBAAb,cAA2C,gBAAgB;CACzD;CACA;CAEA,YACE,SACA,UAAuE,CAAC,GACxE;EACA,MAAM,SAAS,QAAQ,UAAU,KAAA,IAAY,KAAA,IAAY,EAAE,OAAO,QAAQ,MAAM,CAAC;EACjF,KAAK,SAAS,QAAQ;EACtB,KAAK,UAAU,QAAQ,UAAU,aAAa,QAAQ,OAAO,IAAI,KAAA;CACnE;AACF;AAEA,IAAa,6BAAb,cAAgD,gBAAgB;CAC9D;CACA;CAEA,YAAY,OAAgB,QAAiB,SAAuB;EAClE,MACE,gCAAgC,SAAS,UAAU,OAAO,KAAK,GAAG,IAAI,QAAQ,KAAK,CAAC,CAAC,WACrF,EAAE,MAAM,CACV;EACA,KAAK,SAAS;EACd,KAAK,UAAU,UAAU,aAAa,OAAO,IAAI,KAAA;CACnD;AACF;AAEA,IAAa,0BAAb,cAA6C,gBAAgB;CAC3D;CACA;CACA;C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,UAAU,YAAY,MAAM,KAAK,CAAC,CAAC,WAAW,GACvD,MAAM,IAAI,gBAAgB,eAAe,KAAK,4BAA4B;AAE9E"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { i as AnalystFinding, n as AnalystContext, w as TraceAnalysisStore } from "./types-
|
|
2
|
-
import { l as ExactCapableAnalyst } from "./exact-types-
|
|
3
|
-
import { n as AnalystRegistry, r as AnalystRegistryOptions } from "./registry-
|
|
4
|
-
import { a as TraceAnalystLimits, d as RawAnalystFinding, i as TraceAnalysisEngineResult, n as TraceAnalysisEngine } from "./engine-
|
|
5
|
-
import { t as TraceToolGroupName } from "./tool-groups-
|
|
1
|
+
import { i as AnalystFinding, n as AnalystContext, w as TraceAnalysisStore } from "./types-BohHewKK.js";
|
|
2
|
+
import { l as ExactCapableAnalyst } from "./exact-types-rdKFzEnK.js";
|
|
3
|
+
import { n as AnalystRegistry, r as AnalystRegistryOptions } from "./registry-CaqJIDdN.js";
|
|
4
|
+
import { a as TraceAnalystLimits, d as RawAnalystFinding, i as TraceAnalysisEngineResult, n as TraceAnalysisEngine } from "./engine-CIy18RTX.js";
|
|
5
|
+
import { t as TraceToolGroupName } from "./tool-groups-zpufabP8.js";
|
|
6
6
|
//#region src/trace-analyst/behavioral-metrics.d.ts
|
|
7
7
|
type SuboptimalCode = 'monotonic-input-growth' | 'output-length-decay' | 'single-tool-dependency' | 'no-self-verification';
|
|
8
8
|
interface SuboptimalSignal {
|
|
@@ -111,4 +111,4 @@ interface DefaultAnalystRegistryOptions {
|
|
|
111
111
|
declare function buildDefaultAnalystRegistry(options?: DefaultAnalystRegistryOptions): AnalystRegistry;
|
|
112
112
|
//#endregion
|
|
113
113
|
export { createTraceAnalyst as a, runTraceAnalyst as c, deriveEfficiencyFindings as d, TraceAnalystDefinition as i, BehavioralAnalystOptions as l, buildDefaultAnalystRegistry as n, renderPriorFindings as o, CreateTraceAnalystOptions as r, renderUpstreamFindings as s, DefaultAnalystRegistryOptions as t, behavioralAnalyst as u };
|
|
114
|
-
//# sourceMappingURL=default-registry-
|
|
114
|
+
//# sourceMappingURL=default-registry-BUtRMRKk.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"default-registry-
|
|
1
|
+
{"version":3,"file":"default-registry-BUtRMRKk.d.ts","names":[],"sources":["../src/trace-analyst/behavioral-metrics.ts","../src/analyst/behavioral-analyst.ts","../src/analyst/kind-factory.ts","../src/analyst/default-registry.ts"],"mappings":";;;;;;KAoBY;UAMK;EACf,MAAM;EACN;;EAEA;;EAEA,UAAU;;UAGK;;EAEf;EACA;;EAEA,gBAAgB;;EAEhB;EACA;EACA,eAAe;EACf;EACA;;EAEA;EACA;EACA,SAAS;;UAGM;EACf;EACA;EACA,sBAAsB;EACtB,uBAAuB;;;;UC1BR;;EAEf;;EAEA;;;;;;iBA+Dc,yBACd,SAAS,mBACT;EAAQ;EAAoB;IAC3B;;iBAkCa,kBACd,UAAS,2BACR,oBAAoB;;;;UCrHN;EACf;EACA;EACA;EACA;;EAEA,sBAAsB,SAAS;;EAE/B;;EAEA,WAAW;;EAEX,kBACE,OAAO,oBACP,SAAS,wCACe;EAC1B,SAAS,QAAQ;EACjB,eAAe,KAAK,mBAAmB,SAAS,mBAAmB;EACnE;EACA;;UAGe;EACf,QAAQ;;EAER;EACA;;;iBAIoB,gBAAgB;EACpC,YAAY;EACZ,QAAQ;EACR,OAAO;EACP,SAAS;EACT;IACE,QAAQ;;iBAgFI,mBACd,YAAY,wBACZ,SAAS,4BACR,oBAAoB;iBA+QP,oBAAoB,OAAO;iBAe3B,uBAAuB,UAAU;;;UCnahC;;;;;;EAMf,SAAS;EACT,uBAAuB;;EAEvB;EACA,aAAa;EACb,WAAW;;iBAGG,4BACd,UAAS,gCACR"}
|
|
@@ -9,9 +9,9 @@ import { r as welchsTTest } from "./baseline-BhPRQBVn.js";
|
|
|
9
9
|
import { r as observedSplitScore } from "./reward-nw2xZGZG.js";
|
|
10
10
|
import { c as validateRunRecord, i as modelHasSnapshot } from "./run-record-D2lDdSAz.js";
|
|
11
11
|
import { r as paretoChart } from "./summary-report-Blysd6Z2.js";
|
|
12
|
-
import { A as surfaceHash, G as runEval, J as resolveRunDir, f as runImprovementLoop, k as surfaceContentHash, o as emitLoopProvenance, s as loopProvenanceArgsFromResult, y as assertOptimizationResult, z as defaultProductionGate } from "./llm-judge-
|
|
12
|
+
import { A as surfaceHash, G as runEval, J as resolveRunDir, f as runImprovementLoop, k as surfaceContentHash, o as emitLoopProvenance, s as loopProvenanceArgsFromResult, y as assertOptimizationResult, z as defaultProductionGate } from "./llm-judge-DrzsVS5k.js";
|
|
13
13
|
import { c as campaignCellTaskScore, l as campaignCellToRunRecord, o as campaignCellExecutionEvidence, s as campaignCellJudgeDimensions } from "./reward-hacking-DFo2FU5J.js";
|
|
14
|
-
import { S as inMemoryCampaignStorage, b as createRunCostLedger, x as fsCampaignStorage } from "./external-optimizer-subprocess-
|
|
14
|
+
import { S as inMemoryCampaignStorage, b as createRunCostLedger, x as fsCampaignStorage } from "./external-optimizer-subprocess-DU1KM8yV.js";
|
|
15
15
|
import { t as powerPreflight } from "./power-preflight-DEw-uC7q.js";
|
|
16
16
|
import { t as createHostedClient } from "./client-LIuo-KPv.js";
|
|
17
17
|
//#region src/contamination-guard.ts
|
|
@@ -1491,4 +1491,4 @@ function requirePositiveInteger(value, field) {
|
|
|
1491
1491
|
//#endregion
|
|
1492
1492
|
export { summarizeExecution as a, analyzeRuns as i, SelfImproveRunError as n, checkCanaries as o, selfImprove as r, defineAgentEval as t };
|
|
1493
1493
|
|
|
1494
|
-
//# sourceMappingURL=define-agent-eval-
|
|
1494
|
+
//# sourceMappingURL=define-agent-eval-BqWFz3sK.js.map
|