@qlairoslabs/acp-client 0.5.0 → 0.6.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-metering.md +288 -0
- package/package.json +6 -3
- package/src/agent-session.ts +416 -15
- package/src/client.ts +57 -1
- package/src/controller.ts +30 -0
- package/src/index.ts +151 -0
- package/src/metering/catalog/build.ts +285 -0
- package/src/metering/catalog/index.ts +243 -0
- package/src/metering/catalog/live.ts +171 -0
- package/src/metering/catalog/models-dev.catalog.json +8797 -0
- package/src/metering/catalog/models-dev.meta.json +6 -0
- package/src/metering/categories.ts +129 -0
- package/src/metering/certification.ts +86 -0
- package/src/metering/context.ts +134 -0
- package/src/metering/delta.ts +108 -0
- package/src/metering/engine.ts +991 -0
- package/src/metering/money.ts +356 -0
- package/src/metering/opencode/channel.ts +389 -0
- package/src/metering/opencode/index.ts +159 -0
- package/src/metering/opencode/plugin.js +90 -0
- package/src/metering/opencode/profile.ts +159 -0
- package/src/metering/pricing.ts +285 -0
- package/src/metering/provider.ts +121 -0
- package/src/metering/rating.ts +349 -0
- package/src/metering/record.ts +274 -0
- package/src/metering/state.ts +421 -0
- package/src/metering/usage.ts +72 -0
- package/src/types.ts +28 -5
package/src/client.ts
CHANGED
|
@@ -19,6 +19,7 @@ import {
|
|
|
19
19
|
import { parseConfigOptions, type ConfigOptions } from "./config-options.ts";
|
|
20
20
|
import { extractResponseChunk, toActivityEvent, toAvailableCommands } from "./updates.ts";
|
|
21
21
|
import { ResponseAccumulator } from "./response.ts";
|
|
22
|
+
import { normalizeTokenUsage } from "./metering/usage.ts";
|
|
22
23
|
import { TerminalRegistry } from "./terminals.ts";
|
|
23
24
|
import { readTextFile, writeTextFile } from "./fs-access.ts";
|
|
24
25
|
import { NotConnectedError } from "./errors.ts";
|
|
@@ -169,6 +170,15 @@ interface QueueItem {
|
|
|
169
170
|
|
|
170
171
|
export type AvailableCommandsListener = (commands: readonly InternalSessionCommand[]) => void;
|
|
171
172
|
|
|
173
|
+
/**
|
|
174
|
+
* A raw ACP `usage_update`, with the session it named.
|
|
175
|
+
*
|
|
176
|
+
* Delivered raw rather than as an ActivityEvent because metering needs two things the
|
|
177
|
+
* folded event discards: ACP's absent-versus-null `cost`, and un-coerced counters (the
|
|
178
|
+
* activity projection defaults them to zero).
|
|
179
|
+
*/
|
|
180
|
+
export type UsageUpdateListener = (update: unknown, sessionId: string | null) => void;
|
|
181
|
+
|
|
172
182
|
interface CommandTransition {
|
|
173
183
|
previous: readonly InternalSessionCommand[];
|
|
174
184
|
bySession: Map<string, readonly InternalSessionCommand[]>;
|
|
@@ -180,6 +190,15 @@ export class AcpClient implements AgentClient {
|
|
|
180
190
|
private _configOptions: ConfigOptions = new Map();
|
|
181
191
|
private _availableCommands: readonly InternalSessionCommand[] = Object.freeze([]);
|
|
182
192
|
private readonly availableCommandListeners = new Set<AvailableCommandsListener>();
|
|
193
|
+
private readonly usageUpdateListeners = new Set<UsageUpdateListener>();
|
|
194
|
+
/**
|
|
195
|
+
* Latest usage_update seen, replayed to a late subscriber.
|
|
196
|
+
*
|
|
197
|
+
* Listeners are attached after connect + session/new, so a harness that notifies during
|
|
198
|
+
* startup would otherwise be unobserved. Mirrors how `availableCommands` is cached and
|
|
199
|
+
* re-emitted on attach.
|
|
200
|
+
*/
|
|
201
|
+
private lastUsageUpdate: { update: unknown; sessionId: string | null } | null = null;
|
|
183
202
|
private commandTransition: CommandTransition | null = null;
|
|
184
203
|
private _sessionId: string | null = null;
|
|
185
204
|
|
|
@@ -245,6 +264,26 @@ export class AcpClient implements AgentClient {
|
|
|
245
264
|
this.availableCommandListeners.add(listener);
|
|
246
265
|
return () => this.availableCommandListeners.delete(listener);
|
|
247
266
|
}
|
|
267
|
+
/**
|
|
268
|
+
* Observe `usage_update` notifications — context window and provider cost.
|
|
269
|
+
*
|
|
270
|
+
* Session-scoped rather than per-turn: ACP gives no ordering guarantee between a
|
|
271
|
+
* prompt response and the usage update describing it, so an update can arrive well
|
|
272
|
+
* after the turn's handlers are gone. Routing these only through PromptHandlers would
|
|
273
|
+
* drop exactly the observations metering needs.
|
|
274
|
+
*/
|
|
275
|
+
subscribeUsageUpdate(listener: UsageUpdateListener): () => void {
|
|
276
|
+
this.usageUpdateListeners.add(listener);
|
|
277
|
+
const buffered = this.lastUsageUpdate;
|
|
278
|
+
if (buffered) {
|
|
279
|
+
try {
|
|
280
|
+
listener(buffered.update, buffered.sessionId);
|
|
281
|
+
} catch (err) {
|
|
282
|
+
this.log.warn("usage_update_listener_failed", { error: String(err) });
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
return () => this.usageUpdateListeners.delete(listener);
|
|
286
|
+
}
|
|
248
287
|
get currentSessionId(): string | null {
|
|
249
288
|
return this._sessionId;
|
|
250
289
|
}
|
|
@@ -684,6 +723,10 @@ export class AcpClient implements AgentClient {
|
|
|
684
723
|
const cancelled = this.active.cancelled;
|
|
685
724
|
const text = this.active.response.text;
|
|
686
725
|
const messages = this.active.response.snapshot();
|
|
726
|
+
// ACP usage is optional and experimental: validate rather than cast. An
|
|
727
|
+
// unavailable report is logged and surfaced as null — never zero-filled.
|
|
728
|
+
const usage = normalizeTokenUsage(res.usage);
|
|
729
|
+
if (!usage.ok) this.log.debug("prompt_usage_unavailable", { reason: usage.reason });
|
|
687
730
|
this.log[text.length === 0 && !cancelled ? "warn" : "info"]("prompt_end", {
|
|
688
731
|
stopReason: res.stopReason,
|
|
689
732
|
status: cancelled ? "cancelled" : "completed",
|
|
@@ -695,7 +738,7 @@ export class AcpClient implements AgentClient {
|
|
|
695
738
|
messages,
|
|
696
739
|
stopReason: res.stopReason,
|
|
697
740
|
status: cancelled ? "cancelled" : "completed",
|
|
698
|
-
usage:
|
|
741
|
+
usage: usage.ok ? usage.usage : null,
|
|
699
742
|
};
|
|
700
743
|
} finally {
|
|
701
744
|
this.active = null;
|
|
@@ -763,6 +806,19 @@ export class AcpClient implements AgentClient {
|
|
|
763
806
|
}
|
|
764
807
|
}
|
|
765
808
|
|
|
809
|
+
if (kind === "usage_update") {
|
|
810
|
+
// Fired before the active-turn gate: a usage update is session state, and dropping
|
|
811
|
+
// it between turns would lose the context/cost observation entirely.
|
|
812
|
+
this.lastUsageUpdate = { update, sessionId: notification.sessionId ?? null };
|
|
813
|
+
for (const listener of [...this.usageUpdateListeners]) {
|
|
814
|
+
try {
|
|
815
|
+
listener(update, notification.sessionId ?? null);
|
|
816
|
+
} catch (err) {
|
|
817
|
+
this.log.warn("usage_update_listener_failed", { error: String(err) });
|
|
818
|
+
}
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
|
|
766
822
|
if (!this.active) {
|
|
767
823
|
if (this.replay && (!notification.sessionId || notification.sessionId === this.replay.sessionId)) {
|
|
768
824
|
this.replay.onUpdate?.(notification);
|
package/src/controller.ts
CHANGED
|
@@ -111,6 +111,10 @@ export class AgentController implements AgentClient {
|
|
|
111
111
|
(commands: readonly InternalSessionCommand[]) => void
|
|
112
112
|
>();
|
|
113
113
|
private detachAvailableCommands: (() => void) | null = null;
|
|
114
|
+
private readonly usageUpdateListeners = new Set<
|
|
115
|
+
(update: unknown, sessionId: string | null) => void
|
|
116
|
+
>();
|
|
117
|
+
private detachUsageUpdates: (() => void) | null = null;
|
|
114
118
|
|
|
115
119
|
constructor(private readonly config: AgentControllerConfig) {
|
|
116
120
|
this.mode = config.mode ?? "normal";
|
|
@@ -165,6 +169,16 @@ export class AgentController implements AgentClient {
|
|
|
165
169
|
return () => this.availableCommandListeners.delete(listener);
|
|
166
170
|
}
|
|
167
171
|
|
|
172
|
+
/**
|
|
173
|
+
* Observe raw ACP `usage_update` notifications (context window, provider cost).
|
|
174
|
+
*
|
|
175
|
+
* Degraded (pty) mode has no ACP notifications, so this simply never fires there.
|
|
176
|
+
*/
|
|
177
|
+
subscribeUsageUpdate(listener: (update: unknown, sessionId: string | null) => void): () => void {
|
|
178
|
+
this.usageUpdateListeners.add(listener);
|
|
179
|
+
return () => this.usageUpdateListeners.delete(listener);
|
|
180
|
+
}
|
|
181
|
+
|
|
168
182
|
async start(): Promise<ConnectResult> {
|
|
169
183
|
if (this.current) {
|
|
170
184
|
return { sessionId: this.currentSessionId ?? "", resumed: this.acp?.hasSession ?? false };
|
|
@@ -223,6 +237,8 @@ export class AgentController implements AgentClient {
|
|
|
223
237
|
this.acp = null;
|
|
224
238
|
this.detachAvailableCommands?.();
|
|
225
239
|
this.detachAvailableCommands = null;
|
|
240
|
+
this.detachUsageUpdates?.();
|
|
241
|
+
this.detachUsageUpdates = null;
|
|
226
242
|
this.emitAvailableCommands(NO_AVAILABLE_COMMANDS);
|
|
227
243
|
if (client) await client.stop();
|
|
228
244
|
}
|
|
@@ -461,6 +477,20 @@ export class AgentController implements AgentClient {
|
|
|
461
477
|
this.detachAvailableCommands = this.acp?.subscribeAvailableCommands((commands) =>
|
|
462
478
|
this.emitAvailableCommands(commands)) ?? null;
|
|
463
479
|
this.emitAvailableCommands(this.acp?.availableCommands ?? NO_AVAILABLE_COMMANDS);
|
|
480
|
+
|
|
481
|
+
this.detachUsageUpdates?.();
|
|
482
|
+
this.detachUsageUpdates =
|
|
483
|
+
this.acp?.subscribeUsageUpdate((update, sessionId) => {
|
|
484
|
+
for (const listener of [...this.usageUpdateListeners]) {
|
|
485
|
+
try {
|
|
486
|
+
listener(update, sessionId);
|
|
487
|
+
} catch (err) {
|
|
488
|
+
this.config.logger?.warn("controller_usage_update_listener_failed", {
|
|
489
|
+
error: String(err),
|
|
490
|
+
});
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
}) ?? null;
|
|
464
494
|
}
|
|
465
495
|
|
|
466
496
|
private emitAvailableCommands(commands: readonly InternalSessionCommand[]): void {
|
package/src/index.ts
CHANGED
|
@@ -42,6 +42,7 @@ export type {
|
|
|
42
42
|
AgentSessionEvent,
|
|
43
43
|
AgentSessionNotification,
|
|
44
44
|
AgentSessionListener,
|
|
45
|
+
AgentSessionPromptResult,
|
|
45
46
|
HandoffOptions,
|
|
46
47
|
HandoffResult,
|
|
47
48
|
ProviderSession,
|
|
@@ -126,6 +127,154 @@ export type {
|
|
|
126
127
|
TranscriptRole,
|
|
127
128
|
} from "./transcript.ts";
|
|
128
129
|
|
|
130
|
+
export {
|
|
131
|
+
MAX_SCALE,
|
|
132
|
+
EMPTY_MONEY_TOTAL,
|
|
133
|
+
addMoney,
|
|
134
|
+
addToTotal,
|
|
135
|
+
canonicalizeMoney,
|
|
136
|
+
isTotalComplete,
|
|
137
|
+
mergeTotals,
|
|
138
|
+
soleAmount,
|
|
139
|
+
totalOf,
|
|
140
|
+
ratioOf,
|
|
141
|
+
subtractMoney,
|
|
142
|
+
decimalFromNumber,
|
|
143
|
+
isValidMoney,
|
|
144
|
+
rateTokens,
|
|
145
|
+
sumMoneyByCurrency,
|
|
146
|
+
} from "./metering/money.ts";
|
|
147
|
+
export type { Money, MoneyResult, MoneyTotal, TokenUnitPrice } from "./metering/money.ts";
|
|
148
|
+
export { normalizeTokenUsage } from "./metering/usage.ts";
|
|
149
|
+
export {
|
|
150
|
+
ACP_PROVENANCE,
|
|
151
|
+
acpProvenance,
|
|
152
|
+
AgentSessionHandoffError,
|
|
153
|
+
AgentSessionOperationError,
|
|
154
|
+
MeteringPreflightError,
|
|
155
|
+
UNAVAILABLE_PROVENANCE,
|
|
156
|
+
} from "./metering/record.ts";
|
|
157
|
+
export type {
|
|
158
|
+
AgentSessionMeteringSnapshot,
|
|
159
|
+
MeteredOperationKind,
|
|
160
|
+
MeteringConfig,
|
|
161
|
+
MeteringEnforcement,
|
|
162
|
+
MeteringPricingStatus,
|
|
163
|
+
MeteringProvenance,
|
|
164
|
+
MeteringReconciliation,
|
|
165
|
+
CostReconciliation,
|
|
166
|
+
MeteringUsageResult,
|
|
167
|
+
OperationMeteringRecord,
|
|
168
|
+
OperationOutcome,
|
|
169
|
+
ProviderIdentitySnapshot,
|
|
170
|
+
} from "./metering/record.ts";
|
|
171
|
+
export {
|
|
172
|
+
CERTIFIED_INTEGRATIONS,
|
|
173
|
+
OPENCODE_PLUGIN_CERTIFICATION,
|
|
174
|
+
billingRefusalReason,
|
|
175
|
+
certificationFor,
|
|
176
|
+
} from "./metering/certification.ts";
|
|
177
|
+
export {
|
|
178
|
+
OpencodeMeteringChannel,
|
|
179
|
+
createOpencodeMetering,
|
|
180
|
+
meteringPluginPath,
|
|
181
|
+
writeManagedProfile,
|
|
182
|
+
} from "./metering/opencode/index.ts";
|
|
183
|
+
export type {
|
|
184
|
+
ChannelHandshake,
|
|
185
|
+
ManagedProfile,
|
|
186
|
+
OpencodeMetering,
|
|
187
|
+
OpencodeMeteringOptions,
|
|
188
|
+
ProviderInference,
|
|
189
|
+
} from "./metering/opencode/index.ts";
|
|
190
|
+
export type { CertificationRequirements } from "./metering/certification.ts";
|
|
191
|
+
export { MeteringEngine, sumInferenceTokens } from "./metering/engine.ts";
|
|
192
|
+
export type { InferenceSource, MeteringEngineOptions, OpenOperation } from "./metering/engine.ts";
|
|
193
|
+
export {
|
|
194
|
+
activeModel,
|
|
195
|
+
counterInterpretationForAdapter,
|
|
196
|
+
providerIdForAdapter,
|
|
197
|
+
resolveModelReference,
|
|
198
|
+
} from "./metering/provider.ts";
|
|
199
|
+
export type { CounterInterpretation, ModelReference } from "./metering/provider.ts";
|
|
200
|
+
export { baselineMatches, calculateDelta } from "./metering/delta.ts";
|
|
201
|
+
export type { DeltaResult } from "./metering/delta.ts";
|
|
202
|
+
export { rateDelta, selectSchedule, unpricedUsage } from "./metering/rating.ts";
|
|
203
|
+
export type {
|
|
204
|
+
AttributableUsage,
|
|
205
|
+
BillingFacts,
|
|
206
|
+
PricedTokenAmount,
|
|
207
|
+
RatedLineItem,
|
|
208
|
+
RatingResult,
|
|
209
|
+
ScheduleSelection,
|
|
210
|
+
} from "./metering/rating.ts";
|
|
211
|
+
export {
|
|
212
|
+
METERING_STATE_VERSION,
|
|
213
|
+
accrueOperation,
|
|
214
|
+
accumulateByCurrency,
|
|
215
|
+
emptyMeteringState,
|
|
216
|
+
restoreMeteringState,
|
|
217
|
+
} from "./metering/state.ts";
|
|
218
|
+
export type {
|
|
219
|
+
AgentSessionMeteringState,
|
|
220
|
+
AggregateUsageTotal,
|
|
221
|
+
CategoryCoverage,
|
|
222
|
+
MeteringBaseline,
|
|
223
|
+
MeteringStateVersion,
|
|
224
|
+
OperationAccrual,
|
|
225
|
+
StateRestoration,
|
|
226
|
+
UnallocatedUsageAccrual,
|
|
227
|
+
UnallocatedUsageState,
|
|
228
|
+
UsageCategoryTotal,
|
|
229
|
+
UsageTotals,
|
|
230
|
+
} from "./metering/state.ts";
|
|
231
|
+
export {
|
|
232
|
+
contextWindowChanged,
|
|
233
|
+
parseContextWindow,
|
|
234
|
+
parseProviderCost,
|
|
235
|
+
providerCostChanged,
|
|
236
|
+
} from "./metering/context.ts";
|
|
237
|
+
export type {
|
|
238
|
+
ContextWindowStatus,
|
|
239
|
+
ProviderCostSnapshot,
|
|
240
|
+
ProviderCostUpdate,
|
|
241
|
+
} from "./metering/context.ts";
|
|
242
|
+
export {
|
|
243
|
+
TOKEN_CATEGORIES,
|
|
244
|
+
pricedCategories,
|
|
245
|
+
pricingCapturedAt,
|
|
246
|
+
unitPriceFor,
|
|
247
|
+
validatePricingPolicy,
|
|
248
|
+
} from "./metering/pricing.ts";
|
|
249
|
+
export type {
|
|
250
|
+
CacheInputConvention,
|
|
251
|
+
CategoryApplicability,
|
|
252
|
+
PolicyValidation,
|
|
253
|
+
PricingCondition,
|
|
254
|
+
PricingConfiguration,
|
|
255
|
+
PricingContext,
|
|
256
|
+
PricingPolicy,
|
|
257
|
+
PricingResolver,
|
|
258
|
+
PricingSchedule,
|
|
259
|
+
PricingSource,
|
|
260
|
+
TokenCategory,
|
|
261
|
+
} from "./metering/pricing.ts";
|
|
262
|
+
export { createLiveModelsDevResolver, fetchLiveCatalog } from "./metering/catalog/live.ts";
|
|
263
|
+
export type { LiveCatalogOptions } from "./metering/catalog/live.ts";
|
|
264
|
+
export {
|
|
265
|
+
MODELS_DEV_SOURCE,
|
|
266
|
+
catalogProviderIds,
|
|
267
|
+
createModelsDevResolver,
|
|
268
|
+
loadPinnedCatalog,
|
|
269
|
+
verifyCatalogIntegrity,
|
|
270
|
+
} from "./metering/catalog/index.ts";
|
|
271
|
+
export type {
|
|
272
|
+
CatalogEntry,
|
|
273
|
+
CatalogProviderInfo,
|
|
274
|
+
PricingCatalog,
|
|
275
|
+
} from "./metering/catalog/index.ts";
|
|
276
|
+
export type { UsageNormalization } from "./metering/usage.ts";
|
|
277
|
+
|
|
129
278
|
export { ProcessCrashError, NotConnectedError, TimeoutError } from "./errors.ts";
|
|
130
279
|
|
|
131
280
|
export { createWireLog } from "./wire-log.ts";
|
|
@@ -150,6 +299,8 @@ export type {
|
|
|
150
299
|
PermissionRequest,
|
|
151
300
|
PermissionOutcome,
|
|
152
301
|
PermissionOptionKind,
|
|
302
|
+
TokenUsage,
|
|
303
|
+
/** @deprecated alias of TokenUsage */
|
|
153
304
|
Usage,
|
|
154
305
|
Attachment,
|
|
155
306
|
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
|
+
}
|