@pal-code/core 0.0.19 → 0.0.21

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pal-code/core",
3
- "version": "0.0.19",
3
+ "version": "0.0.21",
4
4
  "description": "Core runtime for pal — agent loop, providers, tools, sessions",
5
5
  "license": "MIT",
6
6
  "publishConfig": {
package/src/agent/run.ts CHANGED
@@ -51,6 +51,12 @@ export interface RunAgentUsage {
51
51
  inputTokens: number;
52
52
  outputTokens: number;
53
53
  cachedTokens: number;
54
+ /**
55
+ * Billed cost in USD, summed from what providers reported. Zero when no
56
+ * provider in the turn reported a cost — callers then fall back to a local
57
+ * estimate rather than treating it as free.
58
+ */
59
+ reportedCost: number;
54
60
  }
55
61
 
56
62
  /**
@@ -522,6 +528,7 @@ async function* agentTurn(opts: RunAgentOptions): AsyncGenerator<AgentRunEvent>
522
528
  let totalInput = 0;
523
529
  let totalOutput = 0;
524
530
  let totalCached = 0;
531
+ let totalReportedCost = 0;
525
532
  let compactionNote = initialCompactionNote;
526
533
  // Leading-message *count* already folded into a checkpoint. Seeded from the
527
534
  // persisted high-water mark (a seq) via the conversion below, so a turn that
@@ -571,6 +578,7 @@ async function* agentTurn(opts: RunAgentOptions): AsyncGenerator<AgentRunEvent>
571
578
  inputTokens: totalInput,
572
579
  outputTokens: totalOutput,
573
580
  cachedTokens: totalCached,
581
+ reportedCost: totalReportedCost,
574
582
  });
575
583
 
576
584
  for (let round = 0; round < maxRounds; round++) {
@@ -656,6 +664,7 @@ async function* agentTurn(opts: RunAgentOptions): AsyncGenerator<AgentRunEvent>
656
664
  totalInput += event.usage.promptTokens ?? 0;
657
665
  totalOutput += event.usage.completionTokens ?? 0;
658
666
  totalCached += event.usage.cachedTokens ?? 0;
667
+ totalReportedCost += event.usage.cost ?? 0;
659
668
  }
660
669
  }
661
670
  } catch (err) {
@@ -848,6 +857,7 @@ async function* agentTurn(opts: RunAgentOptions): AsyncGenerator<AgentRunEvent>
848
857
  totalInput += event.usage.promptTokens ?? 0;
849
858
  totalOutput += event.usage.completionTokens ?? 0;
850
859
  totalCached += event.usage.cachedTokens ?? 0;
860
+ totalReportedCost += event.usage.cost ?? 0;
851
861
  }
852
862
  }
853
863
  } catch (err) {
package/src/agent/turn.ts CHANGED
@@ -33,6 +33,12 @@ export interface TurnResult {
33
33
  inputTokens: number;
34
34
  outputTokens: number;
35
35
  cachedTokens: number;
36
+ /**
37
+ * USD billed by the provider for this turn, when the provider reports it
38
+ * (OpenCode Zen does). `0` means "not reported" — callers must fall back to a
39
+ * local estimate, not treat the turn as free.
40
+ */
41
+ reportedCost: number;
36
42
  /** The model that actually served this turn (may differ from settings.model after a fallback). */
37
43
  model: string;
38
44
  /** Checkpoints this turn produced (auto-compaction can fire more than once). */
@@ -69,6 +75,13 @@ export interface AgentUi {
69
75
  extensions?(extensions: ExtensionStatus[]): void;
70
76
  mcpServers?(servers: McpServerStatus[]): void;
71
77
  primary?(name: string): void;
78
+ /**
79
+ * One-line startup advisories from extensions, delivered once after loading.
80
+ *
81
+ * Separate from `notice()` because that renders inside a run block: extension
82
+ * load happens before any turn, so a `notice()` call there would be dropped.
83
+ */
84
+ advisories?(lines: string[]): void;
72
85
  /** Called after extension loading finishes, so the frontend can repaint state. */
73
86
  ready?(): void;
74
87
  }
@@ -130,6 +143,10 @@ async function applyLoaded(
130
143
  }),
131
144
  );
132
145
 
146
+ if (result.notices.length > 0) {
147
+ ui.advisories?.(result.notices.map((n) => n.text));
148
+ }
149
+
133
150
  // Populate MCP server status live from the manager. Resolved through core
134
151
  // so `pal add` installs (under ~/.pal/extensions/node_modules) and compiled
135
152
  // binaries both resolve correctly.
@@ -327,7 +344,7 @@ export async function runTurn(
327
344
 
328
345
  ui.startRun(shortModel(settings.model));
329
346
 
330
- let usage = {inputTokens: 0, outputTokens: 0, cachedTokens: 0};
347
+ let usage = {inputTokens: 0, outputTokens: 0, cachedTokens: 0, reportedCost: 0};
331
348
  let activeModel = settings.model;
332
349
  const compactions: TurnResult['compactions'] = [];
333
350
 
@@ -381,6 +398,7 @@ export async function runTurn(
381
398
  inputTokens: usage.inputTokens,
382
399
  outputTokens: usage.outputTokens,
383
400
  cachedTokens: usage.cachedTokens,
401
+ reportedCost: usage.reportedCost,
384
402
  model: activeModel,
385
403
  compactions,
386
404
  };
package/src/extensions.ts CHANGED
@@ -107,6 +107,17 @@ export interface ToolExtension {
107
107
  * `@pal-code/agents` registers the role provider used by core's `delegate`.
108
108
  */
109
109
  setup?: () => void | Promise<void>;
110
+ /**
111
+ * Optional one-line advisory returned by `setup()` and surfaced to the user
112
+ * once at startup — for a condition that is not an error but that the user
113
+ * should fix, e.g. a directory the extension writes to that is not
114
+ * gitignored.
115
+ *
116
+ * Returned rather than printed: extensions load after the TUI has taken over
117
+ * the terminal, so any direct stdout write smears the frame. Core collects
118
+ * these and hands them to the frontend, which owns presentation.
119
+ */
120
+ setupNotice?: () => string | undefined;
110
121
  /**
111
122
  * Optional lifecycle handlers, called by the agent loop and tool executor
112
123
  * at the points the roadmap's Hooks section specifies (turn boundaries,
@@ -136,6 +147,13 @@ export interface LoadedExtensions {
136
147
  unavailable: Array<{pkg: string; reason?: string}>;
137
148
  /** Package names that failed, with the reason. */
138
149
  failed: Array<{pkg: string; reason: string}>;
150
+ /**
151
+ * One-line advisories from extensions that loaded fine but noticed something
152
+ * the user should fix. Distinct from `unavailable`/`failed`: nothing is
153
+ * broken and no tool is withheld — this is advice, e.g. a scratch directory
154
+ * that is not gitignored.
155
+ */
156
+ notices: Array<{pkg: string; text: string}>;
139
157
  }
140
158
 
141
159
  export interface LoadExtensionsOptions {
@@ -634,6 +652,7 @@ export async function loadExtensions(
634
652
  const loaded: string[] = [];
635
653
  const unavailable: Array<{pkg: string; reason?: string}> = [];
636
654
  const failed: Array<{pkg: string; reason: string}> = [];
655
+ const notices: Array<{pkg: string; text: string}> = [];
637
656
 
638
657
  // Clear any previously-registered role provider *before* (re)loading. If the
639
658
  // extension that provides it is gone or fails, its roles must not linger.
@@ -684,6 +703,18 @@ export async function loadExtensions(
684
703
  continue;
685
704
  }
686
705
 
706
+ // Advisory only: a throwing notice must never demote a working extension.
707
+ if (typeof ext.setupNotice === 'function') {
708
+ try {
709
+ const text = ext.setupNotice();
710
+ if (typeof text === 'string' && text.trim() !== '') {
711
+ notices.push({pkg, text: text.trim()});
712
+ }
713
+ } catch {
714
+ // Advice is best-effort — swallow rather than fail the load.
715
+ }
716
+ }
717
+
687
718
  allTools.push(...ext.tools);
688
719
  Object.assign(allHandlers, ext.handlers);
689
720
  // Kept per-extension (not merged key-wise like handlers) so one
@@ -708,5 +739,6 @@ export async function loadExtensions(
708
739
  loaded,
709
740
  unavailable,
710
741
  failed,
742
+ notices,
711
743
  };
712
744
  }
package/src/index.ts CHANGED
@@ -214,6 +214,17 @@ export {complete} from './provider/complete.js';
214
214
  export type {CompleteOptions, CompleteResult} from './provider/complete.js';
215
215
  export {pickCheapModel} from './provider/pick-model.js';
216
216
 
217
+ // Model pricing / cost resolution
218
+ export {
219
+ estimateCost,
220
+ isCostManifestLoaded,
221
+ isPricedModel,
222
+ loadCostManifest,
223
+ registerModelPricing,
224
+ resolveTurnCost,
225
+ } from './provider/pricing.js';
226
+ export type {Pricing, PricedModel} from './provider/pricing.js';
227
+
217
228
  // Debug logging
218
229
  export {log, isDebugEnabled} from './logger.js';
219
230
 
@@ -54,6 +54,35 @@ function extractCachedTokens(usage: Record<string, unknown>): number | undefined
54
54
  return typeof direct === 'number' ? direct : undefined;
55
55
  }
56
56
 
57
+ /**
58
+ * Pull the billed USD cost out of an OpenAI-compatible usage object.
59
+ *
60
+ * Two gateways, two shapes:
61
+ * - **Zen** (pay-as-you-go): `usage.cost` is the real charge.
62
+ * - **Go** (subscription): `usage.cost` is `0` — the subscription already
63
+ * paid, so the marginal charge is nothing — but `opencode.list_cost` holds
64
+ * what the usage *would* have cost, and `opencode.allowance` what it drew
65
+ * from the monthly allowance.
66
+ *
67
+ * Prefer a non-zero `cost`, then a non-zero `list_cost`. The later is the figure
68
+ * that makes cost tracking meaningful on a subscription, and it is also the
69
+ * only one that accounts for Go's weekday peak-hour multipliers (the server
70
+ * folds them in, a local price table cannot).
71
+ *
72
+ * Returns undefined when the provider reports nothing, so callers fall back to
73
+ * a local estimate.
74
+ */
75
+ function extractCost(usage: Record<string, unknown>): number | undefined {
76
+ const opencode = usage.opencode as Record<string, unknown> | undefined;
77
+ const num = (v: unknown): number | undefined =>
78
+ typeof v === 'number' && Number.isFinite(v) ? v : undefined;
79
+ const billed = num(usage.cost);
80
+ const list = num(opencode?.list_cost) ?? num(opencode?.cost);
81
+ if (billed !== undefined && billed > 0) return billed;
82
+ if (list !== undefined && list > 0) return list;
83
+ return billed ?? list;
84
+ }
85
+
57
86
  export async function* streamChat(opts: ChatStreamOptions): AsyncGenerator<StreamEvent> {
58
87
  const body: Record<string, unknown> = {
59
88
  model: opts.model,
@@ -151,6 +180,7 @@ export async function* streamChat(opts: ChatStreamOptions): AsyncGenerator<Strea
151
180
  completionTokens: parsed.usage.completion_tokens ?? 0,
152
181
  totalTokens: parsed.usage.total_tokens ?? 0,
153
182
  cachedTokens: extractCachedTokens(parsed.usage),
183
+ cost: extractCost(parsed.usage),
154
184
  };
155
185
  log('usage', lastUsage);
156
186
  }
@@ -4,4 +4,13 @@ export {resolveAuth} from './auth.js';
4
4
  export {complete} from './complete.js';
5
5
  export type {CompleteOptions, CompleteResult} from './complete.js';
6
6
  export {pickCheapModel} from './pick-model.js';
7
+ export {
8
+ estimateCost,
9
+ isCostManifestLoaded,
10
+ isPricedModel,
11
+ loadCostManifest,
12
+ registerModelPricing,
13
+ resolveTurnCost,
14
+ } from './pricing.js';
15
+ export type {Pricing, PricedModel} from './pricing.js';
7
16
  export {resolveRoute, mergeProviders} from './registry.js';
@@ -118,14 +118,54 @@ class OpenRouterProvider implements Provider {
118
118
  name?: string;
119
119
  pricing?: {prompt: string; completion: string};
120
120
  context_length?: number;
121
+ /** OpenCode Zen shape: per-1M USD prices. */
122
+ cost?: {
123
+ text?: {
124
+ input?: {price?: number; cache?: {read?: number; write?: number}};
125
+ output?: {price?: number};
126
+ };
127
+ };
128
+ limit?: {context?: number; output?: number};
121
129
  }>;
122
130
  };
123
- return (data.data ?? []).map((m) => ({
124
- id: m.id,
125
- name: m.name ?? m.id,
126
- contextWindow: m.context_length,
127
- free: m.pricing?.prompt === '0' && m.pricing?.completion === '0',
128
- }));
131
+ return (data.data ?? []).map((m) => {
132
+ // Two shapes in the wild: OpenRouter's `pricing` (USD per token as a
133
+ // string) and OpenCode's `cost.text` (USD per 1M tokens as a number).
134
+ // Normalise both to USD per 1M so callers never have to care which
135
+ // gateway answered.
136
+ //
137
+ // Go's catalogue additionally carries weekday peak-hour `multipliers`
138
+ // (e.g. x2). Those are deliberately NOT applied here: they depend on when
139
+ // the request ran, which a static price cannot express. Go's usage
140
+ // response accounts for them server-side in `opencode.list_cost`, and
141
+ // that figure is what `extractCost` prefers — so tracked cost stays
142
+ // correct while this table remains a rough fallback.
143
+ const zenIn = m.cost?.text?.input?.price;
144
+ const zenOut = m.cost?.text?.output?.price;
145
+ const orIn = m.pricing ? Number(m.pricing.prompt) * 1_000_000 : undefined;
146
+ const orOut = m.pricing ? Number(m.pricing.completion) * 1_000_000 : undefined;
147
+ const input = Number.isFinite(zenIn) ? zenIn : orIn;
148
+ const output = Number.isFinite(zenOut) ? zenOut : orOut;
149
+ const cacheRead = m.cost?.text?.input?.cache?.read;
150
+
151
+ const priced = typeof input === 'number' && typeof output === 'number';
152
+ return {
153
+ id: m.id,
154
+ name: m.name ?? m.id,
155
+ contextWindow: m.context_length ?? m.limit?.context,
156
+ maxOutput: m.limit?.output,
157
+ ...(priced
158
+ ? {
159
+ cost: {
160
+ input: input as number,
161
+ output: output as number,
162
+ ...(typeof cacheRead === 'number' ? {cacheRead} : {}),
163
+ },
164
+ }
165
+ : {}),
166
+ free: priced && input === 0 && output === 0,
167
+ };
168
+ });
129
169
  }
130
170
 
131
171
  async *stream(opts: {
@@ -0,0 +1,176 @@
1
+ /**
2
+ * Model pricing and cost resolution — shared by every frontend.
3
+ *
4
+ * Two sources, in order of authority:
5
+ *
6
+ * 1. **What the provider actually billed.** Gateways report a per-request
7
+ * `usage.cost` (OpenCode Zen does). That figure already accounts for cache
8
+ * discounts, per-account rates and discounts, so it always wins.
9
+ * 2. **A local table**, filled from the provider's own `/models` catalogue and
10
+ * from LiteLLM's public manifest.
11
+ *
12
+ * The table exists only because not every provider reports a cost. Its known
13
+ * failure mode is why `registerModelPricing` exists: the LiteLLM manifest keys
14
+ * models by *upstream vendor* (`azure_ai/deepseek-v4.1-flash`), so a gateway
15
+ * model id like `deepseek-v4.1-flash` matches nothing. Without registering the
16
+ * gateway's own catalogue, a paid model silently prices at $0.
17
+ */
18
+
19
+ /** USD per 1M tokens. `cacheRead` is present only when a source publishes it. */
20
+ export interface Pricing {
21
+ input: number;
22
+ output: number;
23
+ cacheRead?: number;
24
+ }
25
+
26
+ /** A model's published price, as returned by a provider's `/models` endpoint. */
27
+ export interface PricedModel {
28
+ id: string;
29
+ cost?: {input: number; output: number; cacheRead?: number};
30
+ }
31
+
32
+ const MODEL_PRICING: Record<string, Pricing> = {
33
+ 'anthropic/claude-sonnet-4': {input: 3, output: 15},
34
+ 'anthropic/claude-3.5-sonnet': {input: 3, output: 15},
35
+ 'openai/gpt-4o': {input: 2.5, output: 10},
36
+ 'openai/gpt-4o-mini': {input: 0.15, output: 0.6},
37
+ };
38
+
39
+ const COST_MANIFEST_URL =
40
+ 'https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json';
41
+
42
+ /** Mutable pricing — seeded from the table, upgraded by the two loaders below. */
43
+ let costManifest: Record<string, Pricing> = {...MODEL_PRICING};
44
+
45
+ let manifestLoaded = false;
46
+
47
+ export function isCostManifestLoaded(): boolean {
48
+ return manifestLoaded;
49
+ }
50
+
51
+ /**
52
+ * Fetch LiteLLM's public price manifest and merge it in as a fallback layer.
53
+ *
54
+ * Merged *under* whatever is already known, because anything registered from a
55
+ * live provider catalogue is more specific than a vendor-keyed manifest entry.
56
+ */
57
+ export async function loadCostManifest(): Promise<Record<string, Pricing>> {
58
+ try {
59
+ const res = await fetch(COST_MANIFEST_URL, {signal: AbortSignal.timeout(5000)});
60
+ if (!res.ok) return costManifest;
61
+ const data = (await res.json()) as Record<
62
+ string,
63
+ {
64
+ input_cost_per_token?: number;
65
+ output_cost_per_token?: number;
66
+ cache_read_input_token_cost?: number;
67
+ }
68
+ >;
69
+ const manifest: Record<string, Pricing> = {};
70
+ for (const [model, info] of Object.entries(data)) {
71
+ if (info && typeof info === 'object' && 'input_cost_per_token' in info) {
72
+ manifest[model] = {
73
+ input: (info.input_cost_per_token ?? 0) * 1_000_000,
74
+ output: (info.output_cost_per_token ?? 0) * 1_000_000,
75
+ ...(typeof info.cache_read_input_token_cost === 'number'
76
+ ? {cacheRead: info.cache_read_input_token_cost * 1_000_000}
77
+ : {}),
78
+ };
79
+ }
80
+ }
81
+ costManifest = {...MODEL_PRICING, ...manifest, ...costManifest};
82
+ manifestLoaded = true;
83
+ return costManifest;
84
+ } catch {
85
+ return costManifest; // offline / rate-limited — keep what we have
86
+ }
87
+ }
88
+
89
+ /**
90
+ * Merge pricing from a provider's live `/models` response.
91
+ *
92
+ * Registers both the bare id and the `provider/id` spec, so a model resolves
93
+ * whether or not the user spells the provider prefix.
94
+ */
95
+ export function registerModelPricing(models: readonly PricedModel[], providerId?: string): void {
96
+ for (const m of models) {
97
+ if (!m.cost) continue;
98
+ const entry: Pricing = {
99
+ input: m.cost.input,
100
+ output: m.cost.output,
101
+ ...(typeof m.cost.cacheRead === 'number' ? {cacheRead: m.cost.cacheRead} : {}),
102
+ };
103
+ costManifest[m.id] = entry;
104
+ if (providerId) costManifest[`${providerId}/${m.id}`] = entry;
105
+ }
106
+ }
107
+
108
+ /** True for model ids a provider marks free (e.g. `mimo-v2.6-flash-free`). */
109
+ function isFreeVariant(model: string): boolean {
110
+ return model.includes(':free') || model.includes('-free');
111
+ }
112
+
113
+ /** Look up a price by full `provider/model` spec, then by bare model name. */
114
+ function pricingFor(model: string): Pricing | undefined {
115
+ const bare = model.includes('/') ? model.split('/').slice(1).join('/') : model;
116
+ return costManifest[model] ?? costManifest[bare];
117
+ }
118
+
119
+ /**
120
+ * True when we know a price for this model. Unknown models price at $0, so the
121
+ * UI uses this to label the figure as an estimate rather than a real cost.
122
+ */
123
+ export function isPricedModel(model: string): boolean {
124
+ if (isFreeVariant(model)) return true;
125
+ return Boolean(pricingFor(model));
126
+ }
127
+
128
+ /** Cached input tokens are billed at roughly 10% when no explicit rate exists. */
129
+ const CACHE_DISCOUNT = 0.1;
130
+
131
+ /**
132
+ * Estimated cost in USD for one turn. Returns 0 for unknown models and for
133
+ * `*free*` variants — under-reporting beats inventing a number. Prefer
134
+ * `resolveTurnCost`, which honours a provider-reported figure first.
135
+ */
136
+ export function estimateCost(
137
+ model: string,
138
+ inputTokens: number,
139
+ outputTokens: number,
140
+ cachedTokens = 0,
141
+ ): number {
142
+ if (isFreeVariant(model)) return 0;
143
+ const pricing = pricingFor(model);
144
+ if (!pricing) return 0;
145
+ const uncachedInput = Math.max(0, inputTokens - cachedTokens);
146
+ // An explicit cache-read rate (gateways publish one, and it sits far below
147
+ // the blanket 10% heuristic) beats the discount guess.
148
+ const cacheRate = pricing.cacheRead ?? pricing.input * CACHE_DISCOUNT;
149
+ return (
150
+ (uncachedInput / 1_000_000) * pricing.input +
151
+ (cachedTokens / 1_000_000) * cacheRate +
152
+ (outputTokens / 1_000_000) * pricing.output
153
+ );
154
+ }
155
+
156
+ /**
157
+ * The cost to charge a turn for.
158
+ *
159
+ * `reportedCost` is what the provider says it billed; it is authoritative and
160
+ * used whenever present. Otherwise fall back to `estimateCost`.
161
+ *
162
+ * `reportedCost > 0` (not `!== undefined`) is deliberate: the adapters already
163
+ * resolve a subscription's `cost: 0` up to its `list_cost`, so a `0` reaching
164
+ * here means either a genuinely free model or a provider that reported nothing
165
+ * useful. In both cases an estimate is a safer answer than a confident `$0.00`.
166
+ */
167
+ export function resolveTurnCost(
168
+ reportedCost: number | undefined,
169
+ model: string,
170
+ inputTokens: number,
171
+ outputTokens: number,
172
+ cachedTokens = 0,
173
+ ): number {
174
+ if (typeof reportedCost === 'number' && reportedCost > 0) return reportedCost;
175
+ return estimateCost(model, inputTokens, outputTokens, cachedTokens);
176
+ }
@@ -118,6 +118,32 @@ const BUILTIN_PROVIDERS: ProviderDef[] = [
118
118
  // OpenAI-compatible Chat Completions.
119
119
  modelRoutes: [{pattern: '^(gpt-|codex|grok-|muse-spark)', protocol: 'responses'}],
120
120
  },
121
+ {
122
+ id: 'opencode-go',
123
+ name: 'OpenCode Go',
124
+ baseUrl: 'https://opencode.ai/zen/go/v1',
125
+ envVar: 'OPENCODE_API_KEY',
126
+ modelPrefixes: [],
127
+ keyPrefixes: [],
128
+ defaultModel: 'deepseek-v4.1-flash',
129
+ fallbackModels: [
130
+ 'deepseek-v4.1-flash',
131
+ 'glm-5.3',
132
+ 'glm-5.3-flash',
133
+ 'glm-5.2',
134
+ 'kimi-k3',
135
+ 'kimi-k2.7-code',
136
+ ],
137
+ headers: {
138
+ 'User-Agent': 'pal',
139
+ 'x-opencode-session': '__sesid__',
140
+ },
141
+ hint: 'opencode.ai/zen/go · subscription',
142
+ // Same OpenCode console key as Zen (OPENCODE_API_KEY); billing is the Go
143
+ // subscription's included monthly usage instead of per-token. GPT/Codex/
144
+ // Grok are served via the Responses API like on Zen.
145
+ modelRoutes: [{pattern: '^(gpt-|codex|grok-)', protocol: 'responses'}],
146
+ },
121
147
  {
122
148
  id: 'openai',
123
149
  name: 'OpenAI',
@@ -233,12 +233,27 @@ export async function* streamResponses(opts: ResponsesStreamOptions): AsyncGener
233
233
  const u = response?.usage as Record<string, unknown> | undefined;
234
234
  if (u) {
235
235
  const details = u.input_tokens_details as Record<string, unknown> | undefined;
236
+ // Same rule as the chat adapter: a non-zero `cost` is the real charge,
237
+ // but a subscription (Go) reports `cost: 0` and puts the
238
+ // equivalent-value figure in `opencode.list_cost`.
239
+ const oc = u.opencode as Record<string, unknown> | undefined;
240
+ const num = (v: unknown): number | undefined =>
241
+ typeof v === 'number' && Number.isFinite(v) ? v : undefined;
242
+ const billed = num(u.cost);
243
+ const list = num(oc?.list_cost) ?? num(oc?.cost);
244
+ const cost =
245
+ billed !== undefined && billed > 0
246
+ ? billed
247
+ : list !== undefined && list > 0
248
+ ? list
249
+ : (billed ?? list);
236
250
  lastUsage = {
237
251
  promptTokens: typeof u.input_tokens === 'number' ? u.input_tokens : 0,
238
252
  completionTokens: typeof u.output_tokens === 'number' ? u.output_tokens : 0,
239
253
  totalTokens: typeof u.total_tokens === 'number' ? u.total_tokens : 0,
240
254
  cachedTokens:
241
255
  typeof details?.cached_tokens === 'number' ? details.cached_tokens : undefined,
256
+ cost,
242
257
  };
243
258
  log('usage', lastUsage);
244
259
  }
@@ -34,7 +34,8 @@ export interface ProviderModel {
34
34
  name: string;
35
35
  contextWindow?: number;
36
36
  maxOutput?: number;
37
- cost?: {input: number; output: number};
37
+ /** USD per 1M tokens. Absent when the provider does not publish a price. */
38
+ cost?: {input: number; output: number; cacheRead?: number};
38
39
  free?: boolean;
39
40
  }
40
41
 
@@ -44,6 +45,13 @@ export interface Usage {
44
45
  totalTokens: number;
45
46
  /** Tokens served from the provider's prompt cache (DeepSeek/OpenAI/OpenRouter). */
46
47
  cachedTokens?: number;
48
+ /**
49
+ * Cost of this request in USD, as billed by the provider. Present only when
50
+ * the provider reports it (OpenCode Zen sends `usage.cost`). This is the
51
+ * authoritative figure — it already accounts for cache discounts and
52
+ * per-account pricing, so callers must prefer it over any estimate.
53
+ */
54
+ cost?: number;
47
55
  }
48
56
 
49
57
  export interface StreamEvent {