@qlairoslabs/acp-client 0.5.0 → 0.7.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.
Files changed (62) hide show
  1. package/CHANGELOG-metering.md +288 -0
  2. package/CONSUMER_GUIDE.md +579 -292
  3. package/README.md +25 -0
  4. package/package.json +6 -3
  5. package/src/agent-session.ts +2589 -96
  6. package/src/cli/index.ts +33 -5
  7. package/src/cli/managed.ts +220 -0
  8. package/src/client.ts +57 -1
  9. package/src/controller.ts +43 -0
  10. package/src/index.ts +379 -3
  11. package/src/metering/catalog/build.ts +285 -0
  12. package/src/metering/catalog/index.ts +243 -0
  13. package/src/metering/catalog/live.ts +171 -0
  14. package/src/metering/catalog/models-dev.catalog.json +8797 -0
  15. package/src/metering/catalog/models-dev.meta.json +6 -0
  16. package/src/metering/categories.ts +129 -0
  17. package/src/metering/certification.ts +86 -0
  18. package/src/metering/context.ts +134 -0
  19. package/src/metering/delta.ts +108 -0
  20. package/src/metering/engine.ts +999 -0
  21. package/src/metering/money.ts +356 -0
  22. package/src/metering/opencode/channel.ts +389 -0
  23. package/src/metering/opencode/index.ts +159 -0
  24. package/src/metering/opencode/plugin.js +90 -0
  25. package/src/metering/opencode/profile.ts +159 -0
  26. package/src/metering/pricing.ts +285 -0
  27. package/src/metering/provider.ts +121 -0
  28. package/src/metering/rating.ts +349 -0
  29. package/src/metering/record.ts +275 -0
  30. package/src/metering/state.ts +421 -0
  31. package/src/metering/usage.ts +72 -0
  32. package/src/persistence/activity-projection.ts +71 -0
  33. package/src/persistence/audit-log-reader.ts +506 -0
  34. package/src/persistence/audit-runtime.ts +162 -0
  35. package/src/persistence/checkpoint.ts +304 -0
  36. package/src/persistence/config.ts +538 -0
  37. package/src/persistence/configuration-state.ts +191 -0
  38. package/src/persistence/deletion.ts +227 -0
  39. package/src/persistence/file-registry-store.ts +740 -0
  40. package/src/persistence/integrity.ts +147 -0
  41. package/src/persistence/legacy-registry-import.ts +240 -0
  42. package/src/persistence/managed-checkpoint.ts +81 -0
  43. package/src/persistence/managed-creation.ts +456 -0
  44. package/src/persistence/managed-load.ts +172 -0
  45. package/src/persistence/managed-registry.ts +57 -0
  46. package/src/persistence/migration.ts +298 -0
  47. package/src/persistence/paths.ts +172 -0
  48. package/src/persistence/projection.ts +373 -0
  49. package/src/persistence/reconfiguration.ts +453 -0
  50. package/src/persistence/records.ts +873 -0
  51. package/src/persistence/reducer.ts +498 -0
  52. package/src/persistence/registry.ts +446 -0
  53. package/src/persistence/restoration.ts +689 -0
  54. package/src/persistence/session-log-writer.ts +480 -0
  55. package/src/persistence/state-runtime.ts +176 -0
  56. package/src/persistence/transcript-reader.ts +980 -0
  57. package/src/persistence/transcript-runtime.ts +667 -0
  58. package/src/persistence/transcript-scanner.ts +385 -0
  59. package/src/persistence/truncation.ts +276 -0
  60. package/src/session-manager.ts +257 -7
  61. package/src/transcript.ts +3 -3
  62. package/src/types.ts +28 -5
package/src/index.ts CHANGED
@@ -33,18 +33,40 @@ export type {
33
33
  SetConfigFromStringResult,
34
34
  } from "./controller.ts";
35
35
 
36
- export { AgentSession } from "./agent-session.ts";
36
+ export {
37
+ AgentSession,
38
+ AgentSessionPromptBlockedError,
39
+ AdapterMismatchError,
40
+ ContinuationUnavailableError,
41
+ DirectAuditPersistenceUnsupportedError,
42
+ } from "./agent-session.ts";
37
43
  export type {
38
44
  AgentSessionConfig,
45
+ AgentSessionOpenConfig,
46
+ AgentSessionOpenResult,
47
+ AgentSessionPromptability,
39
48
  TranscriptActivityConfig,
40
49
  AgentSessionPhase,
41
50
  AgentSessionState,
42
51
  AgentSessionEvent,
43
52
  AgentSessionNotification,
44
53
  AgentSessionListener,
54
+ AgentSessionPromptResult,
45
55
  HandoffOptions,
46
56
  HandoffResult,
47
57
  ProviderSession,
58
+ ConfigurationRestoreStatus,
59
+ ConfigurationMismatchResolution,
60
+ ConfigurationMismatchResolutionResult,
61
+ AgentSessionRecoveryResolution,
62
+ AgentSessionRecoveryResolutionResult,
63
+ ContinuationAttempt,
64
+ ContinuationReport,
65
+ ContinuationStrategy,
66
+ OpenContinuationOptions,
67
+ TranscriptContinuationBuilder,
68
+ TranscriptContinuationBuilderContext,
69
+ PromptBlocker,
48
70
  } from "./agent-session.ts";
49
71
 
50
72
  export type {
@@ -103,8 +125,22 @@ export {
103
125
  defaultSessionsDir,
104
126
  } from "./session-store.ts";
105
127
  export type { SessionStore, SessionRecord } from "./session-store.ts";
106
- export { SessionManager, mergeSessions } from "./session-manager.ts";
107
- export type { MergedSession, SessionInput } from "./session-manager.ts";
128
+ export { SessionManager, SessionManagerModeError, mergeSessions } from "./session-manager.ts";
129
+ export type { MergedSession, SessionInput, SessionManagerConfig } from "./session-manager.ts";
130
+ export {
131
+ ManagedAgentSessionAuthorityConflictError,
132
+ ManagedAgentSessionDeletedError,
133
+ ManagedAgentSessionNotFoundError,
134
+ } from "./persistence/managed-load.ts";
135
+ export type { ManagedAgentSessionLoadConfig } from "./persistence/managed-load.ts";
136
+ export type {
137
+ GetAgentSessionCheckpointOptions,
138
+ ResolvedAgentSessionCheckpoint,
139
+ } from "./persistence/managed-checkpoint.ts";
140
+ export { AgentSessionPersistenceReconfigurationError } from "./persistence/reconfiguration.ts";
141
+ export type { ReconfigureAgentSessionPersistenceOptions } from "./persistence/reconfiguration.ts";
142
+ export { AgentSessionRestorationError } from "./persistence/restoration.ts";
143
+ export type { RestoreAgentSessionOptions } from "./persistence/restoration.ts";
108
144
 
109
145
  export {
110
146
  appendTranscriptLine,
@@ -126,6 +162,344 @@ export type {
126
162
  TranscriptRole,
127
163
  } from "./transcript.ts";
128
164
 
165
+ export {
166
+ PersistenceConfigurationError,
167
+ } from "./persistence/config.ts";
168
+ export type {
169
+ AgentSessionPersistenceOptions,
170
+ AuditLogCapturePolicy,
171
+ AuditLogConfig,
172
+ ManagedSessionPersistenceOptions,
173
+ PersistenceLimits,
174
+ SessionConfigurationPersistenceConfig,
175
+ SessionPersistenceConstraints,
176
+ TranscriptCapturePolicy,
177
+ TranscriptConfig,
178
+ TranscriptPreset,
179
+ } from "./persistence/config.ts";
180
+ export {
181
+ PersistenceSerializationError,
182
+ checkpointDigest,
183
+ checkpointDigestMatches,
184
+ } from "./persistence/integrity.ts";
185
+ export type { PersistedMachineCode } from "./persistence/integrity.ts";
186
+ export {
187
+ CheckpointValidationError,
188
+ createAgentSessionCheckpoint,
189
+ validateAgentSessionCheckpoint,
190
+ } from "./persistence/checkpoint.ts";
191
+ export type {
192
+ AgentSessionBoundary,
193
+ AgentSessionCheckpoint,
194
+ AgentSessionCheckpointInput,
195
+ CheckpointIdentityExpectation,
196
+ JsonObject,
197
+ JsonValue,
198
+ PersistedProtocol,
199
+ PersistedSessionConfigSelection,
200
+ SessionConfigurationCheckpoint,
201
+ TransitionKind,
202
+ } from "./persistence/checkpoint.ts";
203
+ export {
204
+ SessionLogRecordValidationError,
205
+ validateAuditLogRecord,
206
+ validateTranscriptRecord,
207
+ } from "./persistence/records.ts";
208
+ export type * from "./persistence/records.ts";
209
+ export {
210
+ AgentSessionRecordValidationError,
211
+ AgentSessionStoreConflictError,
212
+ MaintenanceAlreadyCompletedError,
213
+ SessionMaintenanceInProgressError,
214
+ internalSessionHistoryDigest,
215
+ validateAgentSessionRecord,
216
+ } from "./persistence/registry.ts";
217
+ export type * from "./persistence/registry.ts";
218
+ export {
219
+ AgentSessionRegistryCursorError,
220
+ AgentSessionRegistryError,
221
+ AgentSessionRegistryLockError,
222
+ FileAgentSessionStore,
223
+ MaintenanceOutcomeUnknownError,
224
+ } from "./persistence/file-registry-store.ts";
225
+ export type {
226
+ FileAgentSessionStoreOptions,
227
+ RegistryRecoveryNotice,
228
+ } from "./persistence/file-registry-store.ts";
229
+ export {
230
+ FileSessionLogWriter,
231
+ SessionLogAlreadyExistsError,
232
+ SessionLogInUseError,
233
+ SessionLogRecordTooLargeError,
234
+ SessionLogWriteError,
235
+ } from "./persistence/session-log-writer.ts";
236
+ export type {
237
+ FileSessionLogWriterOptions,
238
+ ResumedTranscriptWriter,
239
+ ResumeTranscriptWriterOptions,
240
+ SessionLogKind,
241
+ } from "./persistence/session-log-writer.ts";
242
+ export {
243
+ projectAuditEvent,
244
+ projectTranscriptEvent,
245
+ } from "./persistence/projection.ts";
246
+ export type {
247
+ AuditProjectionContext,
248
+ NormalizedActivityProjection,
249
+ NormalizedPersistenceEvent,
250
+ TranscriptProjectionContext,
251
+ } from "./persistence/projection.ts";
252
+ export {
253
+ SessionLogTruncationError,
254
+ truncateSessionLogRecord,
255
+ } from "./persistence/truncation.ts";
256
+ export type { SessionLogTruncationOptions } from "./persistence/truncation.ts";
257
+ export {
258
+ EMPTY_HISTORY_DIGEST,
259
+ TranscriptReductionError,
260
+ reduceTranscriptHistory,
261
+ reduceInternalSessionHistory,
262
+ reduceTranscriptState,
263
+ } from "./persistence/reducer.ts";
264
+ export {
265
+ TranscriptCorruptionError,
266
+ TranscriptIdentityError,
267
+ TranscriptNotFoundError,
268
+ TranscriptUnavailableError,
269
+ scanTranscriptContinuation,
270
+ } from "./persistence/transcript-scanner.ts";
271
+ export {
272
+ TranscriptPersistenceRuntime,
273
+ TranscriptRuntimeStateError,
274
+ } from "./persistence/transcript-runtime.ts";
275
+ export type {
276
+ CreateTranscriptRuntimeOptions,
277
+ TranscriptTerminalCheckpointChanges,
278
+ } from "./persistence/transcript-runtime.ts";
279
+ export { persistenceEventFromActivity } from "./persistence/activity-projection.ts";
280
+ export {
281
+ snapshotSessionConfiguration,
282
+ snapshotSessionConfigurationAfterSelection,
283
+ snapshotAcceptedEffectiveConfiguration,
284
+ } from "./persistence/configuration-state.ts";
285
+ export type {
286
+ SnapshotAcceptedEffectiveConfigurationOptions,
287
+ SnapshotSessionConfigurationAfterSelectionOptions,
288
+ SnapshotSessionConfigurationOptions,
289
+ } from "./persistence/configuration-state.ts";
290
+ export type {
291
+ TranscriptContinuationScan,
292
+ TranscriptScanExpectation,
293
+ } from "./persistence/transcript-scanner.ts";
294
+ export {
295
+ TranscriptCursorInvalidError,
296
+ TranscriptReader,
297
+ TranscriptReaderError,
298
+ } from "./persistence/transcript-reader.ts";
299
+ export {
300
+ AuditLogCursorInvalidError,
301
+ AuditLogReader,
302
+ AuditLogReaderError,
303
+ } from "./persistence/audit-log-reader.ts";
304
+ export type {
305
+ AuditLogCursor,
306
+ AuditLogSnapshotCursor,
307
+ ReadAuditLogPageOptions,
308
+ } from "./persistence/audit-log-reader.ts";
309
+ export {
310
+ LegacyTranscriptMigrationError,
311
+ migrateLegacyTranscript,
312
+ } from "./persistence/migration.ts";
313
+ export type {
314
+ LegacyTranscriptMigrationResult,
315
+ MigrateLegacyTranscriptOptions,
316
+ } from "./persistence/migration.ts";
317
+ export { importLegacySessionRegistry } from "./persistence/legacy-registry-import.ts";
318
+ export type {
319
+ LegacyRegistryImportEntry,
320
+ LegacyRegistryImportReason,
321
+ LegacyRegistryImportResult,
322
+ LegacyRegistryImportStatus,
323
+ } from "./persistence/legacy-registry-import.ts";
324
+ export {
325
+ AgentSessionDeletionError,
326
+ deleteManagedAgentSession,
327
+ } from "./persistence/deletion.ts";
328
+ export type { DeleteAgentSessionOptions } from "./persistence/deletion.ts";
329
+ export {
330
+ ManagedAgentSessionCreationError,
331
+ } from "./persistence/managed-creation.ts";
332
+ export type { ManagedAgentSessionCreateConfig } from "./persistence/managed-creation.ts";
333
+ export type {
334
+ ActivityExecutionState,
335
+ ListTranscriptActivitiesOptions,
336
+ PersistedActivityState,
337
+ PersistedActivityStatePage,
338
+ ReadTranscriptPageOptions,
339
+ TranscriptConversationItem,
340
+ TranscriptCursor,
341
+ TranscriptPage,
342
+ TranscriptSnapshotCursor,
343
+ TranscriptTimelineItem,
344
+ TranscriptReadableRecord,
345
+ TranscriptView,
346
+ } from "./persistence/transcript-reader.ts";
347
+ export type {
348
+ PersistenceRepair,
349
+ SessionRecoveryStatus,
350
+ TranscriptHistoryReduction,
351
+ TranscriptReductionResult,
352
+ TranscriptStructuralRecord,
353
+ } from "./persistence/reducer.ts";
354
+
355
+ export {
356
+ MAX_SCALE,
357
+ EMPTY_MONEY_TOTAL,
358
+ addMoney,
359
+ addToTotal,
360
+ canonicalizeMoney,
361
+ isTotalComplete,
362
+ mergeTotals,
363
+ soleAmount,
364
+ totalOf,
365
+ ratioOf,
366
+ subtractMoney,
367
+ decimalFromNumber,
368
+ isValidMoney,
369
+ rateTokens,
370
+ sumMoneyByCurrency,
371
+ } from "./metering/money.ts";
372
+ export type { Money, MoneyResult, MoneyTotal, TokenUnitPrice } from "./metering/money.ts";
373
+ export { normalizeTokenUsage } from "./metering/usage.ts";
374
+ export {
375
+ ACP_PROVENANCE,
376
+ acpProvenance,
377
+ AgentSessionHandoffError,
378
+ AgentSessionOperationError,
379
+ MeteringPreflightError,
380
+ UNAVAILABLE_PROVENANCE,
381
+ } from "./metering/record.ts";
382
+ export type {
383
+ AgentSessionMeteringSnapshot,
384
+ MeteredOperationKind,
385
+ MeteringConfig,
386
+ MeteringEnforcement,
387
+ MeteringPricingStatus,
388
+ MeteringProvenance,
389
+ MeteringReconciliation,
390
+ CostReconciliation,
391
+ MeteringUsageResult,
392
+ OperationMeteringRecord,
393
+ OperationOutcome,
394
+ ProviderIdentitySnapshot,
395
+ } from "./metering/record.ts";
396
+ export {
397
+ CERTIFIED_INTEGRATIONS,
398
+ OPENCODE_PLUGIN_CERTIFICATION,
399
+ billingRefusalReason,
400
+ certificationFor,
401
+ } from "./metering/certification.ts";
402
+ export {
403
+ OpencodeMeteringChannel,
404
+ createOpencodeMetering,
405
+ meteringPluginPath,
406
+ writeManagedProfile,
407
+ } from "./metering/opencode/index.ts";
408
+ export type {
409
+ ChannelHandshake,
410
+ ManagedProfile,
411
+ OpencodeMetering,
412
+ OpencodeMeteringOptions,
413
+ ProviderInference,
414
+ } from "./metering/opencode/index.ts";
415
+ export type { CertificationRequirements } from "./metering/certification.ts";
416
+ export { MeteringEngine, sumInferenceTokens } from "./metering/engine.ts";
417
+ export type { InferenceSource, MeteringEngineOptions, OpenOperation } from "./metering/engine.ts";
418
+ export {
419
+ activeModel,
420
+ counterInterpretationForAdapter,
421
+ providerIdForAdapter,
422
+ resolveModelReference,
423
+ } from "./metering/provider.ts";
424
+ export type { CounterInterpretation, ModelReference } from "./metering/provider.ts";
425
+ export { baselineMatches, calculateDelta } from "./metering/delta.ts";
426
+ export type { DeltaResult } from "./metering/delta.ts";
427
+ export { rateDelta, selectSchedule, unpricedUsage } from "./metering/rating.ts";
428
+ export type {
429
+ AttributableUsage,
430
+ BillingFacts,
431
+ PricedTokenAmount,
432
+ RatedLineItem,
433
+ RatingResult,
434
+ ScheduleSelection,
435
+ } from "./metering/rating.ts";
436
+ export {
437
+ METERING_STATE_VERSION,
438
+ accrueOperation,
439
+ accumulateByCurrency,
440
+ emptyMeteringState,
441
+ restoreMeteringState,
442
+ } from "./metering/state.ts";
443
+ export type {
444
+ AgentSessionMeteringState,
445
+ AggregateUsageTotal,
446
+ CategoryCoverage,
447
+ MeteringBaseline,
448
+ MeteringStateVersion,
449
+ OperationAccrual,
450
+ StateRestoration,
451
+ UnallocatedUsageAccrual,
452
+ UnallocatedUsageState,
453
+ UsageCategoryTotal,
454
+ UsageTotals,
455
+ } from "./metering/state.ts";
456
+ export {
457
+ contextWindowChanged,
458
+ parseContextWindow,
459
+ parseProviderCost,
460
+ providerCostChanged,
461
+ } from "./metering/context.ts";
462
+ export type {
463
+ ContextWindowStatus,
464
+ ProviderCostSnapshot,
465
+ ProviderCostUpdate,
466
+ } from "./metering/context.ts";
467
+ export {
468
+ TOKEN_CATEGORIES,
469
+ pricedCategories,
470
+ pricingCapturedAt,
471
+ unitPriceFor,
472
+ validatePricingPolicy,
473
+ } from "./metering/pricing.ts";
474
+ export type {
475
+ CacheInputConvention,
476
+ CategoryApplicability,
477
+ PolicyValidation,
478
+ PricingCondition,
479
+ PricingConfiguration,
480
+ PricingContext,
481
+ PricingPolicy,
482
+ PricingResolver,
483
+ PricingSchedule,
484
+ PricingSource,
485
+ TokenCategory,
486
+ } from "./metering/pricing.ts";
487
+ export { createLiveModelsDevResolver, fetchLiveCatalog } from "./metering/catalog/live.ts";
488
+ export type { LiveCatalogOptions } from "./metering/catalog/live.ts";
489
+ export {
490
+ MODELS_DEV_SOURCE,
491
+ catalogProviderIds,
492
+ createModelsDevResolver,
493
+ loadPinnedCatalog,
494
+ verifyCatalogIntegrity,
495
+ } from "./metering/catalog/index.ts";
496
+ export type {
497
+ CatalogEntry,
498
+ CatalogProviderInfo,
499
+ PricingCatalog,
500
+ } from "./metering/catalog/index.ts";
501
+ export type { UsageNormalization } from "./metering/usage.ts";
502
+
129
503
  export { ProcessCrashError, NotConnectedError, TimeoutError } from "./errors.ts";
130
504
 
131
505
  export { createWireLog } from "./wire-log.ts";
@@ -150,6 +524,8 @@ export type {
150
524
  PermissionRequest,
151
525
  PermissionOutcome,
152
526
  PermissionOptionKind,
527
+ TokenUsage,
528
+ /** @deprecated alias of TokenUsage */
153
529
  Usage,
154
530
  Attachment,
155
531
  SessionListEntry,
@@ -0,0 +1,285 @@
1
+ // The shared transform from raw models.dev data into the library's pricing shape.
2
+ //
3
+ // Lives in src/, not in the generator, because BOTH the pinned artifact and the optional
4
+ // live resolver must produce byte-identical policies. When these rules lived only in the
5
+ // build script there was no way to fetch fresh prices without reimplementing them, and a
6
+ // second implementation is a second set of conventions to drift.
7
+ //
8
+ // The cache and thought conventions are the part models.dev cannot supply: it publishes
9
+ // prices, not counter semantics. A provider is emitted ONLY when its convention is backed
10
+ // by evidence recorded below — guessing double-counts cached input or reasoning.
11
+
12
+ import { decimalFromNumber } from "../money.ts";
13
+
14
+ /** models.dev publishes every price per one million tokens. */
15
+ export const PER_TOKENS = 1_000_000;
16
+ /** models.dev does not carry a currency; its prices are USD. */
17
+ export const CURRENCY = "USD";
18
+
19
+ export type Applicability = "applicable" | "not_applicable" | "unknown";
20
+
21
+ export interface ProviderConvention {
22
+ readonly cacheInputConvention: {
23
+ readonly cachedRead: "included_in_input" | "excluded_from_input";
24
+ readonly cachedWrite: "included_in_input" | "excluded_from_input";
25
+ };
26
+ /** Why we believe the above. Copied into the artifact so it is auditable. */
27
+ readonly evidence: string;
28
+ /** Applicability for categories the price table cannot settle on its own. */
29
+ readonly thought: Applicability;
30
+ /**
31
+ * How reasoning tokens are charged when the catalog carries no separate price.
32
+ * Omit when it is genuinely unknown — an unpriced reported category then makes rating
33
+ * unavailable, which is the honest default.
34
+ */
35
+ readonly thoughtWithoutPrice?: "billed_as_output";
36
+ }
37
+
38
+ /**
39
+ * Documented counter conventions, keyed by models.dev provider id.
40
+ *
41
+ * These describe the PROVIDER's own reporting. §7 notes the convention can also vary by
42
+ * harness normalization path; the real-harness matrix validates that per adapter and may
43
+ * add adapter-level overrides on top of these defaults.
44
+ */
45
+ export const OPENCODE_CONVENTION: ProviderConvention = {
46
+ cacheInputConvention: {
47
+ cachedRead: "excluded_from_input",
48
+ cachedWrite: "excluded_from_input",
49
+ },
50
+ evidence:
51
+ "Measured on opencode ACP: totalTokens equals the exact sum of inputTokens, " +
52
+ "outputTokens, cachedReadTokens and thoughtTokens within each single report, across " +
53
+ "five underlying providers. Reasoning is billed at the output rate, reconciled " +
54
+ "exactly against OpenCode's own reported cost on opencode-go/kimi-k2.6.",
55
+ // Reasoning is reported separately but charged as output, so it is always priceable.
56
+ thought: "applicable",
57
+ thoughtWithoutPrice: "billed_as_output",
58
+ };
59
+
60
+ export const CONVENTIONS: Readonly<Record<string, ProviderConvention>> = {
61
+ anthropic: {
62
+ cacheInputConvention: {
63
+ cachedRead: "excluded_from_input",
64
+ cachedWrite: "excluded_from_input",
65
+ },
66
+ evidence:
67
+ "Anthropic Messages API reports cache_read_input_tokens and " +
68
+ "cache_creation_input_tokens as counters separate from input_tokens; total input " +
69
+ "is their sum.",
70
+ // Extended-thinking tokens are billed as output tokens and are not reported as a
71
+ // separate counter. Pricing a thought category would double-count them, so a harness
72
+ // that reports one against an Anthropic route is contradictory evidence (§7) and
73
+ // invalidates the record rather than silently inflating it.
74
+ thought: "not_applicable",
75
+ },
76
+ // OpenCode's gateways. They multiplex many upstream providers but NORMALIZE the
77
+ // counters themselves, so the convention is a property of OpenCode, not of the model
78
+ // behind it — which is what makes one entry legitimate for all of a gateway's models.
79
+ //
80
+ // Measured, not assumed. Across five underlying providers (big-pickle, Ling, MiMo,
81
+ // Nemotron via Zen; Kimi via Go), ten consecutive reports every one satisfied
82
+ // totalTokens === inputTokens + outputTokens + cachedReadTokens + thoughtTokens
83
+ // within a single report. Disjoint terms mean cache is excluded from input and thought
84
+ // is excluded from output.
85
+ //
86
+ // Reasoning is billed at the OUTPUT rate. Reconciled against OpenCode's own reported
87
+ // cumulative cost on opencode-go/kimi-k2.6, which prices no `reasoning` category:
88
+ // turn 1 in 2475, out 3, cache 6144, thought 35 -> computed 0.00348629
89
+ // reported 0.00348629
90
+ // turn 2 in 443, out 3, cache 8192, thought 26 -> computed 0.00184757
91
+ // reported delta 0.00184757
92
+ // The residual after pricing input/output/cache implied exactly 4.00 per 1M for
93
+ // thought, which is that model's output rate to the digit.
94
+ // See .res/somelogs.md/9-5+/9-6-harness-matrix-findings.md, Findings 5-8.
95
+ opencode: OPENCODE_CONVENTION,
96
+ "opencode-go": OPENCODE_CONVENTION,
97
+ openai: {
98
+ cacheInputConvention: {
99
+ cachedRead: "included_in_input",
100
+ cachedWrite: "included_in_input",
101
+ },
102
+ evidence:
103
+ "OpenAI usage.prompt_tokens includes cached input; cached tokens are itemized " +
104
+ "under prompt_tokens_details.cached_tokens rather than counted separately.",
105
+ thought: "unknown",
106
+ },
107
+ };
108
+
109
+ export interface RawCost {
110
+ input?: number;
111
+ output?: number;
112
+ cache_read?: number;
113
+ cache_write?: number;
114
+ reasoning?: number;
115
+ tiers?: ReadonlyArray<
116
+ RawCost & { tier?: { type?: string; size?: number } }
117
+ >;
118
+ }
119
+
120
+ export interface RawModel {
121
+ id?: string;
122
+ name?: string;
123
+ /** ISO date the upstream entry was last changed, e.g. "2026-03-13". */
124
+ last_updated?: string;
125
+ cost?: RawCost;
126
+ }
127
+
128
+ export interface RawProvider {
129
+ id?: string;
130
+ name?: string;
131
+ models?: Record<string, RawModel>;
132
+ }
133
+
134
+ export function toUnitPrice(value: number | undefined, label: string): { amount: string; currency: string; perTokens: number } | null {
135
+ if (value === undefined || value === null) return null;
136
+ const decimal = decimalFromNumber(value);
137
+ if (!decimal.ok) {
138
+ throw new Error(`${label}: ${decimal.reason}`);
139
+ }
140
+ return { amount: decimal.value, currency: CURRENCY, perTokens: PER_TOKENS };
141
+ }
142
+
143
+ /** Build one schedule from a cost block. Returns null when input/output are unpriced. */
144
+ export function buildSchedule(
145
+ cost: RawCost,
146
+ convention: ProviderConvention,
147
+ tier: string,
148
+ conditions: ReadonlyArray<Record<string, unknown>>,
149
+ label: string,
150
+ ) {
151
+ const input = toUnitPrice(cost.input, `${label}.input`);
152
+ const output = toUnitPrice(cost.output, `${label}.output`);
153
+ // Input and output are mandatory: a schedule that cannot price the two universal
154
+ // categories is not a usable schedule, and a missing price is never zero.
155
+ if (!input || !output) return null;
156
+
157
+ const cachedRead = toUnitPrice(cost.cache_read, `${label}.cache_read`);
158
+ const cachedWrite = toUnitPrice(cost.cache_write, `${label}.cache_write`);
159
+ const thought = toUnitPrice(cost.reasoning, `${label}.reasoning`);
160
+
161
+ // A model with its own reasoning price uses it; otherwise the provider convention says
162
+ // whether reasoning rides the output rate, and silence means we refuse to guess.
163
+ const thoughtConvention = thought
164
+ ? "separate_price"
165
+ : convention.thoughtWithoutPrice ?? undefined;
166
+
167
+ return {
168
+ tier,
169
+ conditions,
170
+ cacheInputConvention: convention.cacheInputConvention,
171
+ ...(thoughtConvention ? { thoughtConvention } : {}),
172
+ input,
173
+ output,
174
+ ...(cachedRead ? { cachedRead } : {}),
175
+ ...(cachedWrite ? { cachedWrite } : {}),
176
+ ...(thought ? { thought } : {}),
177
+ };
178
+ }
179
+
180
+ /**
181
+ * Applicability is a property of the provider/model, not of a pricing tier, so it sits on
182
+ * the policy beside the schedules.
183
+ *
184
+ * A missing price is NOT evidence of inapplicability (§7): it stays "unknown" so the
185
+ * resolver refuses rather than silently omitting a category from cost. Only the
186
+ * convention table may assert "not_applicable".
187
+ */
188
+ export function buildApplicability(
189
+ cost: RawCost,
190
+ convention: ProviderConvention,
191
+ ): Record<string, Applicability> {
192
+ return {
193
+ input: "applicable",
194
+ output: "applicable",
195
+ cached_read: cost.cache_read !== undefined ? "applicable" : "unknown",
196
+ cached_write: cost.cache_write !== undefined ? "applicable" : "unknown",
197
+ thought:
198
+ cost.reasoning !== undefined || convention.thoughtWithoutPrice
199
+ ? "applicable"
200
+ : convention.thought,
201
+ };
202
+ }
203
+
204
+
205
+ /**
206
+ * Build the catalog object from raw models.dev data.
207
+ *
208
+ * Deterministic and pure: the same input always produces the same object, which is what
209
+ * lets the artifact be identified by a digest of its serialization.
210
+ */
211
+ export function buildCatalog(raw: Record<string, RawProvider>): {
212
+ catalog: {
213
+ currency: string;
214
+ perTokens: number;
215
+ providers: Record<string, unknown>;
216
+ };
217
+ modelCount: number;
218
+ skippedCount: number;
219
+ } {
220
+ const providers: Record<string, unknown> = {};
221
+ let modelCount = 0;
222
+ let skippedCount = 0;
223
+
224
+ for (const [providerId, convention] of Object.entries(CONVENTIONS)) {
225
+ const source = raw[providerId];
226
+ if (!source) throw new Error(`provider ${providerId} is absent from models.dev`);
227
+
228
+ const models: Record<string, unknown> = {};
229
+ for (const [modelId, model] of Object.entries(source.models ?? {})) {
230
+ const cost = model.cost;
231
+ if (!cost) {
232
+ skippedCount += 1;
233
+ continue;
234
+ }
235
+ const label = `${providerId}/${modelId}`;
236
+ const schedules = [buildSchedule(cost, convention, "default", [{ kind: "default" }], label)];
237
+
238
+ // A context tier becomes a second schedule selected by an explicit condition, so
239
+ // long-context pricing is a recorded decision rather than a hidden multiplier.
240
+ for (const tier of cost.tiers ?? []) {
241
+ const size = tier.tier?.size;
242
+ if (tier.tier?.type !== "context" || !Number.isSafeInteger(size) || (size as number) <= 0) {
243
+ continue;
244
+ }
245
+ schedules.push(
246
+ buildSchedule(
247
+ tier,
248
+ convention,
249
+ `context_over_${size}`,
250
+ [{ kind: "context_tokens_at_least", tokens: size }],
251
+ `${label}#${size}`,
252
+ ),
253
+ );
254
+ }
255
+
256
+ const usable = schedules.filter((schedule) => schedule !== null);
257
+ if (usable.length === 0) {
258
+ skippedCount += 1;
259
+ continue;
260
+ }
261
+ models[modelId] = {
262
+ categoryApplicability: buildApplicability(cost, convention),
263
+ // How current the DATA is, as opposed to when we captured it.
264
+ ...(typeof model.last_updated === "string" && model.last_updated
265
+ ? { lastUpdated: model.last_updated }
266
+ : {}),
267
+ schedules: usable,
268
+ };
269
+ modelCount += 1;
270
+ }
271
+
272
+ providers[providerId] = {
273
+ cacheInputConvention: convention.cacheInputConvention,
274
+ conventionEvidence: convention.evidence,
275
+ models,
276
+ };
277
+ }
278
+
279
+ return { catalog: { currency: CURRENCY, perTokens: PER_TOKENS, providers }, modelCount, skippedCount };
280
+ }
281
+
282
+ /** Stable serialization: 2-space indent plus a trailing newline. The digest covers this. */
283
+ export function serializeCatalog(catalog: unknown): string {
284
+ return `${JSON.stringify(catalog, null, 2)}\n`;
285
+ }