aegiscode 7.0.26 → 7.0.28

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 (118) hide show
  1. package/SOURCE-OFFER.txt +9 -0
  2. package/package.json +4 -7
  3. package/scripts/check.mjs +1 -52
  4. package/scripts/demo.mjs +1 -94
  5. package/scripts/predist.mjs +1 -75
  6. package/scripts/runtests.mjs +1 -56
  7. package/scripts/seal-gate.mjs +1 -74
  8. package/src/agents.js +1 -139
  9. package/src/app.js +1 -2957
  10. package/src/art.js +1 -289
  11. package/src/chatflow.js +1 -3023
  12. package/src/checkpoint.js +1 -90
  13. package/src/clipboard.js +1 -424
  14. package/src/cloudsync.js +1 -528
  15. package/src/commands.js +1 -4089
  16. package/src/config.js +1 -581
  17. package/src/connect.js +1 -349
  18. package/src/credentials.js +1 -33
  19. package/src/deps.js +1 -232
  20. package/src/devrun.js +1 -187
  21. package/src/diff.js +1 -333
  22. package/src/diffview.js +1 -296
  23. package/src/engine.js +1 -297
  24. package/src/entitlement.js +1 -355
  25. package/src/events.js +1 -707
  26. package/src/export.js +1 -67
  27. package/src/filepreview.js +1 -153
  28. package/src/fingerprint.js +1 -592
  29. package/src/format.js +1 -259
  30. package/src/fuzzy.js +1 -119
  31. package/src/history.js +1 -423
  32. package/src/init.js +1 -175
  33. package/src/input.js +1 -139
  34. package/src/keys.js +1 -183
  35. package/src/markdown.js +1 -306
  36. package/src/models.js +1 -507
  37. package/src/naming.js +1 -57
  38. package/src/overlays.js +1 -462
  39. package/src/panels.js +1 -1418
  40. package/src/ping.js +1 -226
  41. package/src/presence.js +1 -238
  42. package/src/render.js +1 -516
  43. package/src/screen.js +1 -518
  44. package/src/screens.js +1 -896
  45. package/src/secret.js +1 -59
  46. package/src/securefs.js +1 -359
  47. package/src/settings.js +1 -155
  48. package/src/shared.js +1 -52
  49. package/src/sharedpaths.js +1 -53
  50. package/src/signup.js +1 -156
  51. package/src/summarize.js +1 -95
  52. package/src/sysdiag.js +1 -585
  53. package/src/system.js +1 -40
  54. package/src/theme.js +1 -570
  55. package/src/title.js +1 -220
  56. package/src/todos.js +1 -115
  57. package/src/tokens.js +1 -263
  58. package/src/topup.js +1 -210
  59. package/src/update.js +1 -191
  60. package/vendor/client/aegis.js +1 -2441
  61. package/vendor/client/attest.js +1 -518
  62. package/vendor/client/authorship-key.js +1 -410
  63. package/vendor/client/auto-provision.js +1 -134
  64. package/vendor/client/brain-catalog.js +1 -268
  65. package/vendor/client/byok-catalog.js +1 -199
  66. package/vendor/client/catalog-client.js +1 -487
  67. package/vendor/client/conversation-export.js +1 -177
  68. package/vendor/client/credentials.js +1 -494
  69. package/vendor/client/device-fingerprint.js +1 -141
  70. package/vendor/client/drive-connect.js +1 -110
  71. package/vendor/client/drive-upload.js +1 -234
  72. package/vendor/client/env-file.js +1 -1273
  73. package/vendor/client/fingerprint.js +1 -1064
  74. package/vendor/client/foreign-memory.js +1 -669
  75. package/vendor/client/google-signin.js +1 -133
  76. package/vendor/client/hooks.js +1 -430
  77. package/vendor/client/model-discovery.js +1 -373
  78. package/vendor/client/naming.js +1 -283
  79. package/vendor/client/platform.js +1 -937
  80. package/vendor/client/prefs.js +1 -351
  81. package/vendor/client/presence-constants.js +1 -107
  82. package/vendor/client/presence.js +1 -438
  83. package/vendor/client/record-vault.js +3 -1055
  84. package/vendor/client/session-store.js +1 -575
  85. package/vendor/client/topup.js +1 -297
  86. package/vendor/client/touch.js +1 -458
  87. package/vendor/client/update.js +1 -763
  88. package/vendor/client/user-models.js +1 -381
  89. package/vendor/desktop/lib/local/agents.js +1 -105
  90. package/vendor/desktop/lib/local/attachments.js +1 -276
  91. package/vendor/desktop/lib/local/autonomous.js +1 -1045
  92. package/vendor/desktop/lib/local/claude-pro.js +1 -1028
  93. package/vendor/desktop/lib/local/context.js +1 -125
  94. package/vendor/desktop/lib/local/engine.js +1 -3666
  95. package/vendor/desktop/lib/local/entitlement.js +1 -660
  96. package/vendor/desktop/lib/local/exec-plan.js +1 -269
  97. package/vendor/desktop/lib/local/git-scope.js +1 -228
  98. package/vendor/desktop/lib/local/integrity.js +1 -163
  99. package/vendor/desktop/lib/local/local.js +1 -2145
  100. package/vendor/desktop/lib/local/prompt.js +1 -280
  101. package/vendor/desktop/lib/local/queue.js +1 -560
  102. package/vendor/desktop/lib/local/session-rounds.js +1 -238
  103. package/vendor/desktop/lib/local/shell.js +1 -712
  104. package/vendor/desktop/lib/local/spill.js +1 -75
  105. package/vendor/desktop/lib/local/tools.js +1 -1328
  106. package/vendor/desktop/lib/local/turn-guard.js +1 -300
  107. package/vendor/desktop/lib/local/worktree-lock.js +1 -235
  108. package/vendor/desktop/lib/settings.js +1 -890
  109. package/vendor/desktop/main.js +1 -4890
  110. package/vendor/desktop/renderer/usage.js +1 -1239
  111. package/vendor/hosts/install.js +1 -638
  112. package/vendor/hosts/openai-shim.js +1 -515
  113. package/vendor/hosts/spec.js +1 -164
  114. package/vendor/hosts/targets.js +1 -346
  115. package/vendor/mcp/server.js +1 -221
  116. package/vendor/mcp/tools.js +1 -408
  117. package/vendor/one/src/child.js +1 -285
  118. package/vendor/one/src/permissions.js +1 -383
@@ -1,1241 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- // AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
4
- // Conveying a modified copy, or running one as a network service, owes the
5
- // corresponding source under this licence (§5/§13) — see LICENSING.md.
6
- 'use strict';
7
-
8
- /**
9
- * Pure token-usage → display-number mapping, and the cost half of it.
10
- *
11
- * Standalone from app.js (same reason as budget.js/stream-policy.js): it is
12
- * requireable from a plain Node test without window.aegis. app.js only calls
13
- * into it.
14
- *
15
- * Why this exists at all: the two wire formats spell the same quantity
16
- * differently, and the renderer used to read exactly one of the spellings.
17
- *
18
- * OpenAI-compatible { prompt_tokens, completion_tokens, total_tokens }
19
- * Anthropic-compatible { input_tokens, output_tokens } ← no total
20
- *
21
- * Reading only `total_tokens` — the field OpenAI happens to provide — meant
22
- * every Anthropic-compatible model rendered with no token count at all, while
23
- * the call was silently being billed. Accepting both spellings, and deriving
24
- * the total when the provider doesn't state one, is what makes the spend
25
- * visible regardless of which endpoint answered.
26
- *
27
- * ── The cost half, on the CLI's principle ──────────────────────────────────
28
- *
29
- * The renderer printed a token count and nothing else, so the desktop had no
30
- * meter to compare against `aegiscodex` on the same engine and the same
31
- * prompt — the comparison that started this whole line of work. The CLI's
32
- * rule (cli/src/tokens.js, ported here) has three parts, and all three matter:
33
- *
34
- * 1. A pooled turn's bill is settled SERVER-side and carries a margin and a
35
- * prompt-cache discount the client cannot see. When the response states
36
- * `costUsd`, that figure wins verbatim — it is the truth about the
37
- * charge, not an estimate of it.
38
- * 2. Only in the absence of a settled charge does the local rate table
39
- * apply, and the result is labeled an estimate so nobody reads a guess as
40
- * a bill.
41
- * 3. The rate table is resolved by exact id, then longest prefix. The
42
- * DeepSeek row is load-bearing: without it every direct DeepSeek turn
43
- * fell through to Sonnet's $3.00/$15.00 per M against a real
44
- * $0.14/$0.28 — 21x the input rate and 54x the output rate — which made
45
- * the *meter* the largest single contributor to the apparent cost gap
46
- * between two surfaces running identical code.
47
- */
48
-
49
- /**
50
- * Number of tokens to show for a completed turn, or `null` when the provider
51
- * reported none (an unknown count must render as nothing, never as `0`).
52
- *
53
- * @param {{total_tokens?: number, prompt_tokens?: number, completion_tokens?: number,
54
- * input_tokens?: number, output_tokens?: number,
55
- * input?: number, output?: number}|null|undefined} usage
56
- * @returns {number|null}
57
- */
58
- function usageTokens(usage) {
59
- if (!usage || typeof usage !== 'object') return null;
60
- if (typeof usage.total_tokens === 'number') return usage.total_tokens;
61
- // Three spellings of the same quantity: OpenAI's, Anthropic's, and this
62
- // file's own bucket shape — which is also the shape a LEDGER row carries
63
- // (cli/src/history.js writes `{input, output, cacheRead, cacheWrite}` into
64
- // sessions.json, and the CLI's demo path writes `{input, output}`). Reading
65
- // only the two wire spellings left every stored row uncountable, so a
66
- // resumed session's rolling total started at zero even though its ledger
67
- // said otherwise.
68
- const input = usage.input_tokens ?? usage.prompt_tokens ?? usage.input;
69
- const output = usage.output_tokens ?? usage.completion_tokens ?? usage.output;
70
- if (typeof input !== 'number' && typeof output !== 'number') return null;
71
- return (input || 0) + (output || 0);
72
- }
73
-
74
- /**
75
- * Rough token count for text the wire never measured — a direct port of the
76
- * CLI's own estimator (the upstream engine's estimateTokens), and the
77
- * reason its session total is MONOTONIC.
78
- *
79
- * This is the whole difference being fixed. The CLI's `appendHistory`
80
- * (the upstream engine's history module) writes a `tokens` object for EVERY finished
81
- * exchange: `{input, output, cacheRead, cacheWrite, real: true}` when the wire
82
- * reported usage, and `{input: estimateTokens(prompt), output:
83
- * estimateTokens(reply), real: false}` when it did not. `real` is a FLAG, not a
84
- * gate — `aggregateSessionUsage` adds `t.input || 0` for every row regardless,
85
- * so a turn without usage still moves the total and only marks it as partly
86
- * estimated.
87
- *
88
- * The desktop rolled only reported usage and dropped everything else, so its
89
- * total was flat across any turn the pool did not report on — the meter looked
90
- * dead while the conversation was being billed. ~4 characters per token, the
91
- * CLI's heuristic, kept identical so the two surfaces estimate the same turn
92
- * the same way. Empty text is 0, never the `Math.max(1, …)` floor.
93
- */
94
- function estimateTokens(text) {
95
- if (!text) return 0;
96
- return Math.max(1, Math.ceil([...String(text)].length / 4));
97
- }
98
-
99
- /**
100
- * The bucket shape an exchange gets when the wire reported no usage: the CLI's
101
- * `{input: estimateTokens(prompt), output: estimateTokens(reply)}`.
102
- *
103
- * `null` when there is no text at all to estimate from, so a dispatch that
104
- * genuinely reported nothing (no usage, no prompt, no reply) still lands in
105
- * `unknown` instead of being handed a fabricated zero.
106
- *
107
- * `reasoning` is the extended-thinking trace, and it is OUTPUT: a reasoning
108
- * model bills its chain of thought as output tokens, which is why the wire's
109
- * own `output_tokens` already includes it. The desktop renders that trace in
110
- * its own element (app.js `reasoningText`) rather than in the reply body, so
111
- * the two streams had to be added back together here — an estimate measured off
112
- * the visible answer alone sat still for the entire think phase, which on a
113
- * reasoning model is both the longest and the most expensive part of the turn.
114
- *
115
- * @param {string} [prompt]
116
- * @param {string} [reply]
117
- * @param {string} [reasoning]
118
- * @returns {{input: number, output: number, cacheRead: number, cacheWrite: number}|null}
119
- */
120
- function estimatedBuckets(prompt, reply, reasoning) {
121
- const hasPrompt = typeof prompt === 'string' && prompt.length > 0;
122
- const out =
123
- (typeof reply === 'string' ? reply : '') +
124
- (typeof reasoning === 'string' ? reasoning : '');
125
- const hasReply = out.length > 0;
126
- if (!hasPrompt && !hasReply) return null;
127
- return {
128
- input: estimateTokens(prompt),
129
- output: estimateTokens(out),
130
- cacheRead: 0,
131
- cacheWrite: 0,
132
- real: false,
133
- };
134
- }
135
-
136
- // Per-million-token USD rates. Cache-read/write matter for long sessions.
137
- //
138
- // These are the PROVIDER's rates, for the fallback path where a turn has no
139
- // server-settled charge (a byok relay turn reports the provider rate it
140
- // relays against). A pooled turn reports the ledger figure instead — see
141
- // turnAccounting's `costUsd` — because the pool's bill carries a margin and a
142
- // prompt-cache discount this table cannot see.
143
- //
144
- // Keys are matched by exact id first, then by prefix (ratesFor below), so a
145
- // family row covers every dated variant of it.
146
- const RATES = {
147
- // Sonnet, Opus, Fable, Haiku — the four FAMILY rows, matched by prefix, and
148
- // deliberately NOT re-pointed at any one generation's price.
149
- //
150
- // The tempting change is to price this row as Claude Sonnet 5's published
151
- // $2.00/$10.00, on the theory that `sonnet` names Sonnet 5. It does not: this
152
- // repo's own alias tables carry no such id. `cli/src/models.js` lists pooled
153
- // seats by name and `cli/src/config.js` records that the platform "does not
154
- // advertise" `sonnet` at all — a pin on it was a phantom that made the pool
155
- // answer from its own default with no error. So a bare `sonnet` is a LABEL,
156
- // not a route: `cli/src/tokens.js` uses it as the default stand-in when no
157
- // model is named, and the family row here is what a non-`claude-`-prefixed
158
- // spelling resolves to by prefix.
159
- //
160
- // $3.00/$15.00 is therefore the honest figure for it, and it is the SAME
161
- // figure as `RATES.default` below — which is the point: an id that names no
162
- // real vendored route prices exactly like an unpriced one, never like a
163
- // current-generation model. Every id that DOES name a real model has an exact
164
- // row in the Claude 5 block below, and an exact id out-ranks a prefix match,
165
- // so correcting those is what fixes the money — re-pointing this family row
166
- // only moves the number an admitted placeholder reports, and silently
167
- // re-prices every dated spelling that resolves here by prefix
168
- // (`sonnet-4-5-20250929` is pinned at $3.00 in test/turn-accounting.test.mjs
169
- // for exactly that reason).
170
- sonnet: { input: 3.00, output: 15.00, cacheRead: 0.30, cacheWrite: 3.75 },
171
- default: { input: 3.00, output: 15.00, cacheRead: 0.30, cacheWrite: 3.75 },
172
- // Fable — the alias for **claude-fable-5**, at Fable's published
173
- // $10.00/$50.00. The $5.00/$25.00 this row used to carry is the Opus-class
174
- // figure; Fable has never been priced there, and the error ran in the
175
- // under-reporting direction on the most expensive model in the lineup.
176
- fable: { input: 10.00, output: 50.00, cacheRead: 1.00, cacheWrite: 12.50 },
177
- opus: { input: 5.00, output: 25.00, cacheRead: 0.50, cacheWrite: 6.25 },
178
- // Haiku — the same class of hole as the DeepSeek row below, on the provider
179
- // whose prices we already thought we knew. The three rows above price Sonnet,
180
- // Opus and Fable; a Haiku turn matched no exact key, no prefix
181
- // ("claude-haiku-4-5" starts with none of them) and no family name, so it
182
- // fell to the Sonnet-class default at 3x its real input and output rate.
183
- //
184
- // $1.00/$5.00 per M (Anthropic's published rate). cacheRead/cacheWrite
185
- // follow the convention the three rows above already encode — 0.1x and 1.25x
186
- // input — rather than being quoted independently, so the Anthropic rows
187
- // cannot drift apart from each other.
188
- haiku: { input: 1.00, output: 5.00, cacheRead: 0.10, cacheWrite: 1.25 },
189
- // `claude-haiku-4-5` names its family after the vendor prefix, so the
190
- // family-scan fallback (raw.includes(key)) would find it — but only after the
191
- // prefix loop, and the prefix `claude` is not a key. Listed explicitly so the
192
- // match is EXACT and cannot be reordered away.
193
- 'claude-haiku': { input: 1.00, output: 5.00, cacheRead: 0.10, cacheWrite: 1.25 },
194
-
195
- // ── the Claude 5 line, one row per ID ────────────────────────────────────
196
- //
197
- // Every figure here is Anthropic's own published rate (docs.claude.com
198
- // pricing table, fetched 2026-10-11), not a fraction derived from a sibling
199
- // row. They are EXACT rows because the family fallback prices this
200
- // generation wrong in both directions: `claude-sonnet-5-5` family-matched
201
- // `sonnet` and `claude-fable-5-1` family-matched `fable`, so the very ids
202
- // the picker offers and the BYOK relay forwards were billed at rates the
203
- // vendor does not charge for them.
204
- //
205
- // cacheRead is NOT the 0.1x-input convention the 4.x rows above use.
206
- // Anthropic changed the cache-hit multiplier on this generation and quotes
207
- // it per model — 5% of input on Opus 5.5 and Sonnet 5.5 ($0.20 / $0.10),
208
- // 2.5% on Fable 5.1 ($0.25), 10% on Fable 5 and Haiku 5.5 ($1.00 / $0.01)
209
- // — so each row carries the published number rather than a multiplier this
210
- // file computed. cacheWrite stays 1.25x input, which the same table
211
- // confirms for all of them.
212
- //
213
- // Haiku 5.5 is priced by PROMPT LENGTH: the vendor charges 5x input and 5x
214
- // output once a request's prompt passes 100k tokens ($0.50/$2.50). This
215
- // schema has no prompt-size field — the only tiering it models is
216
- // DeepSeek's time-of-day peak/offPeak — so the row carries the up-to-100k
217
- // tier and a long-context Haiku turn UNDER-reports. Said out loud rather
218
- // than left implicit: the alternative is 5x-ing every ordinary Haiku turn,
219
- // which is the louder error.
220
- 'claude-opus-5': { input: 5.00, output: 25.00, cacheRead: 0.50, cacheWrite: 6.25 },
221
- 'claude-opus-5-5': { input: 4.00, output: 20.00, cacheRead: 0.20, cacheWrite: 5.00 },
222
- 'claude-sonnet-5': { input: 2.00, output: 10.00, cacheRead: 0.20, cacheWrite: 2.50 },
223
- 'claude-sonnet-5-5': { input: 2.00, output: 10.00, cacheRead: 0.10, cacheWrite: 2.50 },
224
- 'claude-haiku-5-5': { input: 0.10, output: 0.50, cacheRead: 0.01, cacheWrite: 0.125 },
225
- 'claude-fable-5': { input: 10.00, output: 50.00, cacheRead: 1.00, cacheWrite: 12.50 },
226
- 'claude-fable-5-1': { input: 10.00, output: 50.00, cacheRead: 0.25, cacheWrite: 12.50 },
227
- // The Sonnet 4.x spellings keep their own line items now that `sonnet`
228
- // above carries the 5-line price: without these, a Claude Sonnet 4.x turn —
229
- // the id a config saved before this change still holds, and the wire model
230
- // the dated form names — would family-match the alias row and be billed
231
- // $2.00/$10.00 against the vendor's $3.00/$15.00.
232
- 'claude-sonnet-4-6': { input: 3.00, output: 15.00, cacheRead: 0.30, cacheWrite: 3.75 },
233
- 'claude-sonnet-4-5': { input: 3.00, output: 15.00, cacheRead: 0.30, cacheWrite: 3.75 },
234
-
235
- // DeepSeek — read off the vendor's own pricing table
236
- // (api-docs.deepseek.com/quick_start/pricing), not from a secondary blog and
237
- // not from a mirror of our own catalog.
238
- //
239
- // The row this replaces said $0.14/$0.28, sourced from aegis1's
240
- // catalog.py (cost_per_1k_input=0.00014) and referenced in pricing.py. That
241
- // figure is the retired **V4-Flash** tier, and the vendor's own footnote (1)
242
- // retires it explicitly: "The legacy names deepseek-v4-flash and
243
- // deepseek-v4-flash-vision-exp are still accepted, but the corresponding
244
- // models have been retired, their requests are served by the
245
- // DeepSeek-V4.1-Flash model and billed at the Flash price." So every legacy
246
- // id — which is what the picker advertises and what a user pins — bills at
247
- // the V4.1 figures below, ~2.1x the old row.
248
- //
249
- // The rate is TIME-DEPENDENT (peak 01:00-04:00 and 06:00-10:00 UTC Mon-Fri),
250
- // so one flat row cannot state the price — it can only state one of the two.
251
- // `offPeak` carries the other and ratesFor() picks by the wall clock.
252
- //
253
- // cacheRead is the CACHE HIT price the vendor quotes directly ($0.006 peak),
254
- // not a fraction of input: it is 50x cheaper than input, which is what makes
255
- // the cache-hit rate worth measuring at all. Deriving it as 0.1x input — the
256
- // convention aegis1/pricing.py used — overstated it 2.3x.
257
- // cacheWrite is the input rate: DeepSeek bills a cache write as ordinary
258
- // input tokens with no write premium, unlike Anthropic's 1.25x.
259
- deepseek: {
260
- input: 0.30, output: 1.20, cacheRead: 0.006, cacheWrite: 0.30,
261
- offPeak: { input: 0.15, output: 0.60, cacheRead: 0.003, cacheWrite: 0.15 },
262
- },
263
- // DeepSeek-V4-Pro-0813 — a different, pricier model. Longest-prefix matching
264
- // keeps it from being shadowed by the `deepseek` family row above.
265
- 'deepseek-v4-pro': {
266
- input: 1.32, output: 3.96, cacheRead: 0.044, cacheWrite: 1.32,
267
- offPeak: { input: 0.66, output: 1.98, cacheRead: 0.022, cacheWrite: 0.66 },
268
- },
269
- // `deepseek-v4.1-pro` is a spelling the plugin's OWN regex accepts
270
- // (DEEPSEEK_REASONING_MODEL_RE: `v4(\.\d+)?-(flash|pro)`), so a config can
271
- // carry it and the picker can advertise it. It is listed explicitly because
272
- // the prefix loop cannot reach the row above — "deepseek-v4.1-pro" does not
273
- // start with "deepseek-v4-pro" — so it matched the `deepseek` KEY by PREFIX
274
- // (the prefix branch, not the family scan, though that key is also the row
275
- // the family scan lands on) and a Pro-tier turn was billed at Flash rates.
276
- //
277
- // Figures are the Pro tier's ($1.32/$3.96 per M), the same tier the tail of
278
- // the id names. This is deliberately the DEARER reading: an id that names
279
- // "pro" and prices at Flash under-reports spend, which is the direction that
280
- // cannot be recovered after the fact. Sources disagree on V4 Pro's current
281
- // rate (one registry still carries an August 12 check at $0.435/$0.87), so
282
- // treat this row as the one figure here most worth confirming against an
283
- // invoice.
284
- 'deepseek-v4.1-pro': {
285
- input: 1.32, output: 3.96, cacheRead: 0.044, cacheWrite: 1.32,
286
- offPeak: { input: 0.66, output: 1.98, cacheRead: 0.022, cacheWrite: 0.66 },
287
- },
288
-
289
- // The three rows below back the BYOK additions in client/byok-catalog.js —
290
- // without a row here each would resolve to RATE_BASIS.DEFAULT, the same
291
- // "priced at Sonnet's $3/$15 and nobody can tell" hole this file exists to
292
- // close for DeepSeek and Haiku. None of the three publish a cache-WRITE
293
- // premium (unlike Anthropic's 1.25x): all three bill a cache write as
294
- // ordinary input, so cacheWrite repeats the input rate, the same convention
295
- // the DeepSeek rows above use for the same reason.
296
-
297
- // Grok 4.7 (api.x.ai/v1, flagship since 2026-09-21): $2.00/$6.00 per M,
298
- // $0.50 cached input, standard (<200k token) tier. xAI doubles every rate
299
- // above a 200k-token prompt, a prompt-SIZE threshold this table has no field
300
- // for (the only tiering this schema models is DeepSeek's time-of-day
301
- // peak/offPeak) — left at the standard tier rather than inventing one, so a
302
- // long-context Grok turn under-reports rather than carrying a fabricated
303
- // split.
304
- 'grok-4.7': { input: 2.00, output: 6.00, cacheRead: 0.50, cacheWrite: 2.00 },
305
-
306
- // Gemini 3.8 Flash (ai.google.dev, GA 2026-09-02): $0.75/$3.75 per M,
307
- // $0.075 cached input — the introductory rate published through
308
- // 2026-12-31 (scheduled to rise to $1.50/$7.50 on 2027-01-01, not modeled
309
- // here for the same reason the Grok long-context tier above is not: no
310
- // field in this table carries a future-dated rate change).
311
- 'gemini-3.8-flash': { input: 0.75, output: 3.75, cacheRead: 0.075, cacheWrite: 0.75 },
312
-
313
- // GPT-5.5 (api.openai.com/v1, released 2026-04-23): $5.00/$30.00 per M,
314
- // $0.50 cached input, standard (<272k token) tier. Like Grok above, OpenAI
315
- // doubles input and 1.5x's output past that prompt size; left at the
316
- // standard tier for the same reason.
317
- 'gpt-5.5': { input: 5.00, output: 30.00, cacheRead: 0.50, cacheWrite: 5.00 },
318
- };
319
-
320
- /**
321
- * Is `at` inside DeepSeek's peak window? 01:00-04:00 and 06:00-10:00 UTC,
322
- * Monday-Friday. Everything else, weekends included, is off-peak at half rate.
323
- *
324
- * The vendor also excludes Chinese public holidays, which we do NOT model: the
325
- * published table lists them by date, so honouring them would mean shipping a
326
- * calendar that goes stale. The consequence is bounded and one-directional —
327
- * on a holiday we price at peak (the dearer reading) instead of off-peak — and
328
- * over-reporting a spend is recoverable where under-reporting is not.
329
- */
330
- function isPeak(provider, at = new Date()) {
331
- if (String(provider || '').toLowerCase().indexOf('deepseek') !== 0) return true;
332
- const day = at.getUTCDay();
333
- if (day === 0 || day === 6) return false;
334
- const hour = at.getUTCHours();
335
- return (hour >= 1 && hour < 4) || (hour >= 6 && hour < 10);
336
- }
337
-
338
- /** How a model id was matched to a rate row — see ratesFor. */
339
- const RATE_BASIS = Object.freeze({
340
- EXACT: 'exact',
341
- PREFIX: 'prefix',
342
- FAMILY: 'family',
343
- DEFAULT: 'default',
344
- });
345
-
346
- /**
347
- * The rate rows a model id may name as a whole word rather than as a prefix.
348
- * Anthropic spells its family *inside* the id — "claude-opus-4" matches no
349
- * prefix — so prefix matching alone cannot see it.
350
- */
351
- const RATE_FAMILIES = Object.keys(RATES).filter((k) => k !== 'default');
352
-
353
- /**
354
- * Ids this module can be handed that deliberately have NO row, with the reason.
355
- *
356
- * `test/rate-coverage.test.mjs` fails the build when an id the plugin's own
357
- * source routes to resolves to RATE_BASIS.DEFAULT without appearing here. That
358
- * is the mechanism that was missing on the day the picker started advertising
359
- * DeepSeek: nothing compared "ids we route to" against "ids we have priced", so
360
- * the gap had no surface on which to show up as a failure.
361
- *
362
- * Two honest reasons to be in this list, and no others:
363
- *
364
- * - POOLED: aegis1 bills the pool call and reports the settled figure, which
365
- * `turnAccounting` already prefers over anything computed here (its
366
- * `costUsd` branch). A local guess would be a second, worse number printed
367
- * beside the real charge — and for the brain tiers it would also miss the
368
- * fan-out factor (see ID_NOTES in cli/src/models.js: four billed provider
369
- * calls per turn at effort=high, sized by the ask).
370
- * - PROVIDER: a bare provider (`anthropic`, `groq`) is a ROUTING choice — "let
371
- * the pool pick" — not a model. It names no rate because it names no model.
372
- *
373
- * Anything else belongs in RATES. An entry here is a claim that we have no
374
- * business pricing it, not a parking space for a rate we have not looked up.
375
- */
376
- const UNPRICED_BY_DESIGN = Object.freeze({
377
- // Pooled seats — the ledger carries the charge.
378
- 'nexus-brain': 'pooled: multi-call fan-out, aegis1 settles the charge',
379
- 'aegis-brain': 'pooled alias of nexus-brain',
380
- 'nexus-brain-smart': 'pooled alias of nexus-brain',
381
- 'nexus-brain-neo': 'pooled alias of nexus-brain',
382
- 'aegis-brain-smart': 'pooled alias of nexus-brain',
383
- 'aegis-brain-neo': 'pooled alias of nexus-brain',
384
- 'openai-gpt4o-mini': 'pooled seat, aegis1 settles the charge',
385
- // Bare provider names — a routing choice, not a model.
386
- anthropic: 'provider name, not a model id',
387
- openai: 'provider name, not a model id',
388
- groq: 'provider name, not a model id',
389
- google: 'provider name, not a model id',
390
- xai: 'provider name, not a model id',
391
- });
392
-
393
- /**
394
- * The rate row for a model id, plus HOW it was matched.
395
- *
396
- * `basis` is the whole point of the return shape. This used to be
397
- * `return family || RATES.default` — a bare row — so an id nobody had priced
398
- * (DeepSeek, until this change; Haiku too) was silently priced at Sonnet's
399
- * $3/$15 and rendered as though it were a measurement. A wrong number that
400
- * announces itself is a bug report; a wrong number that looks like every other
401
- * number is a fabrication, and it survived because nothing downstream could
402
- * tell the two apart.
403
- *
404
- * So the fallback still exists — a caller needs *a* number to render — but it
405
- * is now labeled: `basis: 'default'` means "we do not know this model's price
406
- * and this figure is a Sonnet-class placeholder". Callers that display money
407
- * are expected to say so, and test/rate-coverage.test.mjs fails the build when
408
- * a model the plugin can actually route to lands here.
409
- *
410
- * @param {string} model a model id, provider name, alias, or "provider:model"
411
- * @param {{at?: Date}} [opts] the instant to price against, for peak/off-peak
412
- * @returns {object} the row ({input,output,cacheRead,cacheWrite}) plus `basis`,
413
- * `peak`, and the `model` it resolved from.
414
- */
415
- function ratesFor(model, { at } = {}) {
416
- const raw = String(model || '').toLowerCase();
417
- const finish = (row, basis) => {
418
- const provider = raw.indexOf('deepseek') === 0 || raw.indexOf(':deepseek') > -1
419
- ? 'deepseek'
420
- : raw;
421
- const peak = isPeak(provider, at || new Date());
422
- // Off-peak rows are half of peak by construction, but read them from the
423
- // table rather than dividing, so a future discount that is NOT exactly half
424
- // is expressed where the numbers live instead of in arithmetic here.
425
- const use = !peak && row.offPeak ? { ...row, ...row.offPeak } : row;
426
- return { ...use, basis, peak, model: raw };
427
- };
428
- if (!raw) return finish(RATES.default, RATE_BASIS.DEFAULT);
429
-
430
- // A byok model id carries its provider as a routing label:
431
- // "anthropic:claude-opus-4", "deepseek:deepseek-v4-flash". The label is not
432
- // a rate, and rating it as written fell through every prefix to
433
- // RATES.default — so an Opus BYOK turn was priced at Sonnet's $3/$15 against
434
- // the vendor's real $5/$25. 15x, on the one class whose figure can only ever
435
- // be an estimate, because there the vendor bills the caller and AEGIS only
436
- // relays.
437
- //
438
- // Precedence is by MATCH QUALITY first and candidate second, not
439
- // candidate-first: matching candidate-by-candidate let the label `deepseek`
440
- // prefix-match the family row before the tail was ever considered, so a
441
- // `deepseek:deepseek-v4-pro` turn was priced at Flash rates — the routing
442
- // label beating the model it labels. So: try every candidate as an exact id,
443
- // then every candidate as a prefix.
444
- const ids = [raw];
445
- // The routing label is separated by ':' in a byok id ("anthropic:claude-opus-4")
446
- // and by '/' in the ids the PLATFORM advertises ("deepseek/deepseek-v4-flash"
447
- // — see test/cli-tools.test.mjs, test/mcp-balance.test.mjs). Splitting only on
448
- // ':' left the slash form resolving its whole string as one id, so
449
- // "deepseek/deepseek-v4-pro" never reached the tail and prefix-matched the
450
- // `deepseek` FAMILY row — the pro model priced at Flash rates, the same
451
- // label-shadowing bug the ':' form had, in the spelling that is actually
452
- // shipped.
453
- const sep = Math.max(raw.lastIndexOf(':'), raw.lastIndexOf('/'));
454
- const tail = raw.slice(sep + 1);
455
- if (tail && tail !== raw) ids.push(tail);
456
- for (const id of ids) {
457
- if (RATES[id]) return finish(RATES[id], RATE_BASIS.EXACT);
458
- }
459
- let best = null;
460
- let bestLen = 0;
461
- for (const id of ids) {
462
- for (const [prefix, rates] of Object.entries(RATES)) {
463
- if (prefix !== 'default' && id.startsWith(prefix) && prefix.length > bestLen) {
464
- best = rates;
465
- bestLen = prefix.length;
466
- }
467
- }
468
- }
469
- if (best) return finish(best, RATE_BASIS.PREFIX);
470
- // Longest family-key hit wins, so an overlapping pair resolves the same way
471
- // twice running rather than by object key order.
472
- let family = null;
473
- let familyLen = 0;
474
- for (const key of RATE_FAMILIES) {
475
- if (raw.includes(key) && key.length > familyLen) {
476
- family = RATES[key];
477
- familyLen = key.length;
478
- }
479
- }
480
- return finish(family || RATES.default, family ? RATE_BASIS.FAMILY : RATE_BASIS.DEFAULT);
481
- }
482
-
483
- /**
484
- * The four billable buckets from a wire usage object, accepting every
485
- * provider's spelling of them.
486
- *
487
- * ── The one thing the providers genuinely disagree about ───────────────────
488
- *
489
- * Cache fields are not merely spelled differently, they are MEASURED
490
- * differently, and the difference is silent:
491
- *
492
- * Anthropic `input_tokens` EXCLUDES `cache_read_input_tokens` and
493
- * `cache_creation_input_tokens` — the buckets are DISJOINT.
494
- * OpenAI `prompt_tokens` INCLUDES
495
- * `prompt_tokens_details.cached_tokens`.
496
- * DeepSeek `prompt_tokens` INCLUDES `prompt_cache_hit_tokens` — the
497
- * cached count is a SUBSET of the prompt count.
498
- *
499
- * Reading a subset pair as though it were disjoint double-bills every cached
500
- * token: once at the input rate and again at the cache rate. That is the exact
501
- * inverse of the saving caching exists to produce, and it is invisible in the
502
- * output — the figure simply comes out larger, and never looks wrong. So the
503
- * convention is detected from which field supplied the prompt count, and only
504
- * the subset spellings subtract.
505
- *
506
- * Earlier revisions deferred this to `desktop/lib/local/providers.js`, a file
507
- * that does not exist — so nothing normalised these fields and every DeepSeek
508
- * turn reported `cacheRead: 0`, pricing its whole prompt at the miss rate.
509
- * That is why the convention is resolved here, in the one module both hosts
510
- * resolve (cli/src/deps.js), rather than in a transport either could drop.
511
- *
512
- * @param {object|null|undefined} usage
513
- * @returns {{input: number, output: number, cacheRead: number, cacheWrite: number}}
514
- */
515
- function usageBuckets(usage) {
516
- const u = usage && typeof usage === 'object' ? usage : {};
517
- const num = (...candidates) => {
518
- for (const c of candidates) if (typeof c === 'number') return c;
519
- return 0;
520
- };
521
- const opt = (v) => (typeof v === 'number' ? v : undefined);
522
-
523
- const anthropicIn = opt(u.input_tokens);
524
- const openaiIn = opt(u.prompt_tokens);
525
- const details = u.prompt_tokens_details;
526
- const nested = details && typeof details === 'object' ? opt(details.cached_tokens) : undefined;
527
- // DeepSeek's `prompt_cache_hit_tokens`, OpenAI's nested `cached_tokens`, and
528
- // the bare `cached_tokens` some OpenAI-compatible gateways emit. All three
529
- // are SUBSETS of the prompt count they arrive beside.
530
- const subsetHit = num(u.prompt_cache_hit_tokens, nested, u.cached_tokens);
531
-
532
- // Only the OpenAI/DeepSeek spelling names the cache INSIDE the prompt stat.
533
- // The Anthropic spelling, and this file's own already-bucketed `{input,...}`
534
- // shape (which a ledger row carries), are disjoint — subtracting there would
535
- // understate the bill.
536
- const subset = anthropicIn === undefined && openaiIn !== undefined;
537
- const promptCount = subset ? openaiIn : num(anthropicIn, openaiIn, u.input);
538
-
539
- const cacheReadRaw = num(u.cache_read_input_tokens, u.cacheRead, subsetHit);
540
- // Clamp to the prompt it belongs to: a provider over-reporting its hit count
541
- // must not be able to produce negative input tokens.
542
- const cacheRead = subset ? Math.min(Math.max(0, promptCount), cacheReadRaw) : cacheReadRaw;
543
- const cacheWrite = num(u.cache_creation_input_tokens, u.cacheWrite);
544
- const output = num(u.output_tokens, u.completion_tokens, u.output);
545
- const input = subset ? Math.max(0, promptCount - cacheRead) : promptCount;
546
-
547
- // A stated total larger than the split means the provider counted tokens the
548
- // split does not name (thinking, cached reads). Attribute the remainder to
549
- // input rather than dropping it: dropping it would understate the bill.
550
- const total = num(u.total_tokens);
551
- const accounted = input + output + cacheRead + cacheWrite;
552
- // ── Did the source report a cache at all? ─────────────────────────────────
553
- //
554
- // Every `num(...)` above coerces an absent field to 0, which is right for
555
- // arithmetic and WRONG for a claim. A provider that reports only
556
- // `prompt_tokens` and no cache field of any spelling is not reporting a cold
557
- // cache — it is not reporting a cache — and the two must not render the same.
558
- // Aider does exactly this (it prints "Tokens: N sent" and no hit count), and
559
- // reading its silence as a 0 made its prompt total the lowest of five
560
- // harnesses when it was really a partial number. See `cacheHitRate`.
561
- const cacheReported =
562
- typeof u.cache_read_input_tokens === 'number'
563
- || typeof u.cacheRead === 'number'
564
- || typeof u.cache_creation_input_tokens === 'number'
565
- || typeof u.cacheWrite === 'number'
566
- || typeof u.prompt_cache_hit_tokens === 'number'
567
- || typeof u.cached_tokens === 'number'
568
- || typeof nested === 'number';
569
- return {
570
- input: total > accounted ? input + (total - accounted) : input,
571
- output,
572
- cacheRead,
573
- cacheWrite,
574
- cacheReported,
575
- };
576
- }
577
-
578
- /**
579
- * Cache hit rate for a usage record: the share of prompt tokens the provider
580
- * actually served from its cache rather than billing at miss price.
581
- *
582
- * Ported from the upstream engine reference. It reads through `usageBuckets`
583
- * rather than off the raw object, which is the one deliberate difference: the
584
- * engine's copy is handed an already-normalised record, while this module is
585
- * also handed WIRE usage (a provider's raw response body) and ledger rows. A
586
- * raw DeepSeek body spells the hit count `prompt_cache_hit_tokens` inside
587
- * `prompt_tokens`; reading `usage.cacheRead` off that shape finds nothing and
588
- * reports `pct: null` — "no cache activity" — for a turn that was almost
589
- * entirely cached. Going through the normaliser is what makes the number the
590
- * same on both spellings.
591
- *
592
- * The denominator is `input + cacheRead`, and `input` means the MISS half
593
- * everywhere in this codebase — `usageBuckets` derives it as
594
- * `prompt_tokens - prompt_cache_hit_tokens`, and the Anthropic spelling
595
- * `input_tokens` already excludes cached reads by definition. Adding
596
- * `cacheWrite` to the denominator would be wrong twice over: on Anthropic a
597
- * written block is read back on the next turn (the same tokens counted again),
598
- * and on DeepSeek there is no write field at all.
599
- *
600
- * `pct` is null — not 0 — when nothing has been billed yet, so a caller can
601
- * tell "no cache activity recorded" apart from "everything missed". A
602
- * hardcoded 0 in a parser once made the benchmark's "0 cache reads" column a
603
- * measurement of our own code rather than of the cache.
604
- *
605
- * `reported` closes the other half of that hole, which this module shares with
606
- * the engine and had to fix in the same commit or the two hosts would disagree.
607
- * `usageBuckets` coerces every absent field to 0 for arithmetic, so a provider
608
- * that reports prompt tokens and NO cache spelling of any kind came out
609
- * `pct: 0` — "everything missed" — when the honest reading is "never said".
610
- * Aider is that shape: it prints a sent-token count and no hit count, and its
611
- * silence priced it as the most cache-efficient harness in the benchmark. So
612
- * `pct` is null unless a cache field was actually present, and a caller that
613
- * prints the rate renders an unreported one as "—".
614
- *
615
- * @returns {{read: number, miss: number, prompt: number, pct: number|null,
616
- * reported: boolean}} `pct` is 0-100, or null when the source reported no
617
- * cache field, or when no prompt tokens have been accounted.
618
- */
619
- function cacheHitRate(usage) {
620
- const u = usageBuckets(usage);
621
- const read = Math.max(0, u.cacheRead || 0);
622
- const miss = Math.max(0, u.input || 0);
623
- const prompt = read + miss;
624
- return {
625
- read,
626
- miss,
627
- prompt,
628
- pct: u.cacheReported && prompt > 0 ? (read / prompt) * 100 : null,
629
- reported: u.cacheReported,
630
- };
631
- }
632
-
633
- /**
634
- * Dollar cost of a usage record at the given model's rates, with the
635
- * provenance attached.
636
- *
637
- * `basis === 'default'` means the model was not priced and `cost` is a
638
- * Sonnet-class placeholder — the one state the old code could not express.
639
- *
640
- * `model` deliberately has NO `= 'sonnet'` default parameter, which is a
641
- * behaviour change worth stating: the old signature was `model = 'sonnet'`, so
642
- * `costBreakdown(u, undefined)` substituted the alias and reported
643
- * `basis: 'exact'` — "this model's real rate" — while `costBreakdown(u, '')`
644
- * (and `ratesFor(undefined)`) reported `basis: 'default'` — "we do not know
645
- * this model". The two spellings produced the SAME money, because
646
- * RATES.default and RATES.sonnet are numerically identical, but two different
647
- * labels for the same number is the exact ambiguity this return shape exists to
648
- * remove. So an unspecified model now flows to the default row and says so.
649
- * The money is unchanged; only the claim about it is.
650
- *
651
- * @param {object} usage a wire usage object or a stored bucket row
652
- * @param {string} model the model id that answered
653
- * @param {{at?: Date}} [opts] the instant to price against (peak/off-peak)
654
- * @returns {{cost: number, basis: string, peak: boolean, model: string, priced: boolean}}
655
- */
656
- function costBreakdown(usage, model, opts = {}) {
657
- const r = ratesFor(model, opts);
658
- const u = usageBuckets(usage);
659
- const toD = (n, rate) => (Math.max(0, Number(n) || 0) / 1_000_000) * rate;
660
- const cost = toD(u.input, r.input)
661
- + toD(u.output, r.output)
662
- + toD(u.cacheRead, r.cacheRead)
663
- + toD(u.cacheWrite, r.cacheWrite);
664
- return { cost, basis: r.basis, peak: r.peak, model: r.model, priced: r.basis !== RATE_BASIS.DEFAULT };
665
- }
666
-
667
- /**
668
- * Dollar cost of a usage record at the given model's rates (USD, estimate).
669
- * See `costBreakdown` for why an unnamed model reports `default` rather than
670
- * silently claiming Sonnet's row as an exact match.
671
- */
672
- function usageCost(usage, model, opts = {}) {
673
- return costBreakdown(usage, model, opts).cost;
674
- }
675
-
676
- /**
677
- * What one turn cost, as the CLI reports it: the server's settled charge when
678
- * the response carries one, otherwise the rate table's estimate, always with
679
- * the distinction preserved so it can be labeled.
680
- *
681
- * @param {object|null|undefined} usage the response's `usage` object
682
- * @param {string} model the model id that answered
683
- * @param {{costUsd?: number}} [opts] the server-settled charge, if any
684
- * @returns {{tokens: number|null, output: number|null, cost: number|null,
685
- * real: boolean, estimated: boolean}}
686
- * `real` is true only when `cost` is the settled charge. `cost` is
687
- * `null` when nothing was reported and no model was named — an
688
- * unpriced turn must render as nothing, never as $0.0000.
689
- * `tokens` is the wire's TOTAL (input + output) and is what the ledger
690
- * and the rolling fold need; `output` is the half a person reads, and
691
- * it is what every per-turn surface shows (see `displayTokens`).
692
- */
693
- function turnAccounting(usage, model, opts = {}) {
694
- const tokens = usageTokens(usage);
695
- const u = usage && typeof usage === 'object' ? usage : {};
696
- // The half the turn PRODUCED. Kept beside the total rather than replacing it:
697
- // `tokens` still has to fold the ledger, and a rebuild from stored buckets
698
- // must agree with the live fold to the unit.
699
- const output =
700
- usage && typeof usage === 'object' ? usageBuckets(usage).output : null;
701
- // The settled charge can arrive either on the response or folded into the
702
- // usage object — the upstream engine does the latter
703
- // (`{ ...result.usage, costUsd: result.costUsd }`), so both are accepted.
704
- const settled = typeof opts.costUsd === 'number'
705
- ? opts.costUsd
706
- : (typeof u.costUsd === 'number' ? u.costUsd : undefined);
707
- if (typeof settled === 'number') {
708
- // The ledger's own figure. `basis: 'settled'` rather than a table match,
709
- // because a settled charge is a fact and a table match is a guess — and the
710
- // pool's bill carries a margin and a prompt-cache discount this table
711
- // cannot see, so the two must never be averaged or confused.
712
- return {
713
- tokens, output, cost: settled, real: true, estimated: false, basis: 'settled', priced: true,
714
- };
715
- }
716
- if (tokens == null) {
717
- return {
718
- tokens, output, cost: null, real: false, estimated: false, basis: null, priced: false,
719
- };
720
- }
721
- const b = costBreakdown(u, model, opts);
722
- // A model the table cannot place still yields a number (ratesFor never
723
- // returns nothing), so this is always an estimate — but `priced: false` says
724
- // the figure is a placeholder rather than this model's rate, so the caller
725
- // can label it instead of printing it as though it had been measured.
726
- return {
727
- tokens, output, cost: b.cost, real: false, estimated: true, basis: b.basis, priced: b.priced,
728
- };
729
- }
730
-
731
- /**
732
- * ── The rolling session tallies, on the CLI's rule ─────────────────────────
733
- *
734
- * The two surfaces did not merely print different numbers — they counted
735
- * differently. The CLI never shows a turn's tokens in isolation: `recordTurn`
736
- * (cli/src/app.js) folds each finished turn's usage into one `session` object
737
- * — `tokens`, `inputTokens`, `outputTokens`, `calls` — and what the user reads
738
- * back is that RUNNING TOTAL. The status bar prints `state.tokens`
739
- * (renderStatus), and `ctrl+t` prints the tallies in one line
740
- * (`tokenSummary`: `12,400 tokens (10,100 in / 2,300 out) · 4 calls · €0.03`).
741
- * The tallies are reproduced; that one abbreviation is not — `fmtRoll` explains
742
- * why it drops the parenthetical rather than carrying the CLI's line verbatim.
743
- *
744
- * The desktop counted per turn only. Every meta row was a fresh count that
745
- * reset at the next call, so "what has this session spent" was answerable only
746
- * by adding the rows up by eye across a scrollback — which is most of why the
747
- * desktop looked like it accounted differently from the CLI on identical
748
- * engine code and an identical prompt.
749
- *
750
- * Three properties of the CLI's fold are load-bearing and are reproduced here
751
- * exactly, because dropping any one of them reintroduces a specific lie:
752
- *
753
- * 1. `turns` and `calls` are incremented BEFORE the "did usage come back?"
754
- * gate (recordTurn counts first, then tests `tokens != null`). A turn
755
- * that reported nothing still happened; a tally that skipped it would
756
- * report the session as shorter and cheaper than it was.
757
- * 2. `tokens`, `input` and `output` accumulate — never reset. A rolling
758
- * total that resets per turn is the per-turn count it replaced.
759
- * 3. A `null` count contributes nothing and is counted in `unknown`, so
760
- * `tokens: 0` is only ever read as a real zero. Nothing is ever added as
761
- * a fabricated 0 to make the arithmetic look complete.
762
- *
763
- * The money split is the CLI's too: a settled charge (the pool's ledger
764
- * figure) rolls into `cost`, and a locally priced turn rolls into `estimate`.
765
- * They are kept apart rather than summed so a `~`-estimate can never be read
766
- * as part of the bill — the distinction `fmtCost` marks on a single turn, held
767
- * across the session.
768
- */
769
-
770
- /** A session with nothing accounted for yet. */
771
- function emptyRoll() {
772
- return {
773
- turns: 0,
774
- calls: 0,
775
- tokens: 0,
776
- input: 0,
777
- output: 0,
778
- cacheRead: 0,
779
- cacheWrite: 0,
780
- /** Dispatches that reported no usage at all — the honest gap in `tokens`. */
781
- unknown: 0,
782
- /**
783
- * Exchanges folded from TEXT rather than reported usage, on the CLI's
784
- * `real: false` rule. They are counted in `tokens` — that is the point —
785
- * and named here so an estimated figure is never read as a measured one.
786
- */
787
- estimated: 0,
788
- /** Settled charges (server-settled `costUsd`), rolled. */
789
- cost: 0,
790
- /** Locally priced turns, rolled. Never mixed into `cost`. */
791
- estimate: 0,
792
- };
793
- }
794
-
795
- /**
796
- * Fold one completed dispatch into a session's rolling tallies. Pure: it
797
- * returns a NEW roll and never mutates the one it was handed, so a half-applied
798
- * fold cannot exist.
799
- *
800
- * @param {object} [roll] the roll so far (emptyRoll() when omitted)
801
- * @param {object} [usage] the response's `usage` object
802
- * @param {{model?: string, costUsd?: number, calls?: number, turns?: number,
803
- * prompt?: string, reply?: string, estimated?: boolean}} [opts]
804
- * `calls` defaults to 1; a pooled turn may report how many provider
805
- * calls it actually made. `turns: 0` folds a dispatch that is not a
806
- * turn of its own — the discovery-lane card, which bills like any other
807
- * call but is not something the user asked for. `prompt`/`reply` are the
808
- * turn's text, used ONLY when the wire reported no usage, so the turn is
809
- * estimated rather than dropped (the CLI's `appendHistory` rule).
810
- * @returns {object} the new roll
811
- */
812
- function rollTurn(roll, usage, opts = {}) {
813
- const next = Object.assign(emptyRoll(), roll || {});
814
- next.turns += opts.turns === undefined ? 1 : Number(opts.turns) || 0;
815
- next.calls += opts.calls === undefined ? 1 : Number(opts.calls) || 0;
816
- const turn = turnAccounting(usage, opts.model, { costUsd: opts.costUsd });
817
- // A row folded from text rather than from the wire: either this turn's own
818
- // fallback below, or a stored ledger row carrying `real: false` — the shape
819
- // the CLI's `appendHistory` writes for an exchange the provider did not
820
- // report on.
821
- const estimated = opts.estimated === true || (usage && usage.real === false);
822
- if (turn.tokens == null) {
823
- // No reported usage. The CLI does not let such a turn vanish from the
824
- // total: `appendHistory` estimates it from the text and marks it
825
- // `real: false` (the upstream engine's history module), and
826
- // `aggregateSessionUsage` then adds it like any other row. Folding the same
827
- // estimate here is what makes the live roll and the rebuilt roll the same
828
- // number, and what stops the total standing still on exactly the turns the
829
- // pool declined to report on — the symptom this fallback exists to remove.
830
- const est = estimatedBuckets(opts.prompt, opts.reply, opts.reasoning);
831
- // Thinking tokens the provider MEASURED, not estimated. On a subscription
832
- // turn the deliberation text is withheld entirely (every real
833
- // `thinking_delta` carries `thinking: ""`), so `estimatedBuckets` above
834
- // cannot see the longest, priciest part of the turn and the live preview
835
- // read 0 for the whole thinking phase. Added verbatim — it is already a
836
- // token count, and it is billed output exactly as the reply is.
837
- const measured =
838
- typeof opts.measuredReasoningTokens === 'number' && opts.measuredReasoningTokens > 0
839
- ? opts.measuredReasoningTokens
840
- : 0;
841
- if (!est) {
842
- // A subscription turn with nothing written yet but thinking under way is
843
- // NOT the `unknown` case: the provider measured it, so a zero would be a
844
- // fabricated reading rather than an absent one.
845
- if (!measured) {
846
- // Nothing reported AND no text to estimate from. The single case that
847
- // stays uncounted: `unknown` names the gap, where a fabricated zero
848
- // would read as a measurement.
849
- next.unknown += 1;
850
- return next;
851
- }
852
- next.tokens += measured;
853
- next.output += measured;
854
- next.estimated += 1;
855
- return next;
856
- }
857
- next.tokens += est.input + est.output + measured;
858
- next.input += est.input;
859
- next.output += est.output + measured;
860
- next.estimated += 1;
861
- return next;
862
- }
863
- const b = usageBuckets(usage);
864
- next.tokens += turn.tokens;
865
- next.input += b.input;
866
- next.output += b.output;
867
- next.cacheRead += b.cacheRead;
868
- next.cacheWrite += b.cacheWrite;
869
- if (estimated) {
870
- // Money stays out of an estimated exchange, deliberately and in both
871
- // directions: the CLI writes no `costUsd` for one, so pricing it here would
872
- // make the live roll drift from the rebuilt one — and pricing tokens that
873
- // were themselves guessed would stack one guess on another.
874
- next.estimated += 1;
875
- return next;
876
- }
877
- if (turn.real) next.cost += turn.cost;
878
- else if (turn.cost != null) next.estimate += turn.cost;
879
- return next;
880
- }
881
-
882
- /**
883
- * Rebuild a session's rolling total from stored exchanges — the desktop's
884
- * counterpart of the CLI's `aggregateSessionUsage`, which sums history.jsonl so
885
- * a resumed session (and a compacted one) still reports everything it spent.
886
- *
887
- * Reads the shapes the shared store writes: an assistant message carrying
888
- * `tokens: {input, output, cacheRead, cacheWrite}` and, when the pool settled
889
- * the turn, `costUsd` (cli/src/history.js → session-store.recordExchange).
890
- * Messages the desktop itself appended carry no `tokens` and fold as `unknown`
891
- * — a resumed thread states what is known and does not invent the rest.
892
- *
893
- * @param {Array<{role?: string, tokens?: object, costUsd?: number, model?: string}>} [messages]
894
- * @returns {object} the roll
895
- */
896
- function rollMessages(messages) {
897
- let roll = emptyRoll();
898
- for (const m of Array.isArray(messages) ? messages : []) {
899
- if (!m || m.role !== 'assistant') continue;
900
- roll = rollTurn(roll, m.tokens, {
901
- model: m.model,
902
- costUsd: typeof m.costUsd === 'number' ? m.costUsd : undefined,
903
- calls: m.calls,
904
- });
905
- }
906
- return roll;
907
- }
908
-
909
- /**
910
- * The ledger row one finished dispatch must carry into the shared session
911
- * store, so the rolling total can be REBUILT when the thread is reopened —
912
- * the desktop's counterpart of the CLI's `appendHistory`
913
- * (the upstream engine's history module).
914
- *
915
- * One authority for the row, on purpose. The CLI writes a `tokens` object for
916
- * EVERY exchange and skips none:
917
- *
918
- * tokens: usage
919
- * ? { input, output, cacheRead, cacheWrite, real: true }
920
- * : { input: estimateTokens(prompt), output: estimateTokens(reply), real: false }
921
- *
922
- * …and `aggregateSessionUsage` then sums `t.input || 0` over every entry with
923
- * `real` as a FLAG, not a gate. Mirroring that shape here is what makes the
924
- * live roll and the rebuilt roll the same number: `rollTurn` is handed this
925
- * exact object on reopen, so an estimated exchange adds the same buckets it
926
- * added live and is counted under `estimated` in both.
927
- *
928
- * Returns `null` when there is neither reported usage nor text to estimate
929
- * from — the one case that must stay unrecorded, because a fabricated
930
- * `{input: 0, output: 0}` row would read as a measured zero forever after.
931
- *
932
- * @param {object} [usage] the response's `usage` object
933
- * @param {object} [turn] its accounting (turnAccounting), when already done
934
- * @param {{model?: string, costUsd?: number, calls?: number, prompt?: string,
935
- * reply?: string}} [opts]
936
- * @returns {object|null} the row's ledger fields
937
- */
938
- function ledgerRow(usage, turn, opts = {}) {
939
- const t = turn || turnAccounting(usage, opts.model, { costUsd: opts.costUsd });
940
- const calls = Number.isFinite(opts.calls) && opts.calls > 0 ? opts.calls : undefined;
941
- if (t.tokens != null) {
942
- const row = { tokens: usageBuckets(usage) };
943
- // Only a SETTLED charge is persisted. The CLI writes `costUsd` for a real
944
- // charge only, and the rebuild prices an unpriced row from the same rate
945
- // table this window used — persisting a local guess would let a stale
946
- // table outlive the change that wrote it.
947
- if (t.real && t.cost != null) row.costUsd = t.cost;
948
- if (calls !== undefined) row.calls = calls;
949
- return row;
950
- }
951
- // `reasoning` is part of the billed output, so it is estimated with the
952
- // reply — a stored row for a thinking-heavy turn must not persist a count
953
- // that excludes the longest thing the model wrote.
954
- const est = estimatedBuckets(opts.prompt, opts.reply, opts.reasoning);
955
- if (!est) return null;
956
- const row = { tokens: est };
957
- if (calls !== undefined) row.calls = calls;
958
- return row;
959
- }
960
-
961
- /**
962
- * The CLI's rendering of a session tally — `cli/src/format.js fmtTokens`, which
963
- * is the one `tokenSummary` actually imports (`cli/src/app.js:50`). NOT the
964
- * `1.5k`/`12.3k` form in `cli/src/tokens.js`: that one belongs to the /cost
965
- * panels, and using it here would print `12.4k` on the very total the CLI
966
- * prints as `12,400` — a rendering difference stacked on top of the accounting
967
- * difference this change exists to remove.
968
- *
969
- * Comma-grouped integer. Anything not finite and positive renders `0`, which is
970
- * the CLI's rule and keeps a stray NaN from reaching the topbar.
971
- */
972
- function fmtTokens(n) {
973
- const v = Number(n);
974
- if (!Number.isFinite(v) || v <= 0) return '0';
975
- return Math.round(v)
976
- .toString()
977
- .replace(/\B(?=(\d{3})+(?!\d))/g, ',');
978
- }
979
-
980
- /**
981
- * The token figure a person is SHOWN for a finished turn or a session roll.
982
- *
983
- * One authority, because there are two shapes that reach it and they had
984
- * drifted apart: `turnAccounting` (a single dispatch, `{tokens, output}`) and
985
- * `emptyRoll`/`rollTurn` (a session tally, same two fields). Every per-turn row
986
- * and the topbar both route through here, so no surface can print a different
987
- * quantity than another.
988
- *
989
- * What it returns is the OUTPUT — what the turn produced. The wire's total is
990
- * input + output, and on any cached or long-context turn the input half
991
- * dominates it: a 3,145-token call whose prompt was 3,000 tokens is a turn that
992
- * wrote 145. Showing 3,145 beside a `session:` line that also reads 3,145 told
993
- * the reader the model had emitted ten times what it did, and there is no way
994
- * to tell from the row which of the two numbers is the prompt restated. The
995
- * CLI settled this the same way (`fmtUsageSplit`, cli/src/format.js): the figure
996
- * is the output, and the input half is not shown unlabelled beside it.
997
- *
998
- * It does NOT fall back to the total. Fall back to `tokens` and the input half
999
- * is back on the screen with no label: a wire that priced a turn but did not
1000
- * itemise it would print `3,145` for a turn that wrote 145. Returns `null`
1001
- * rather than `0` in that case — `0 tokens` is a figure no provider sent,
1002
- * and this file refuses that fabrication everywhere else (`fmtRoll`).
1003
- *
1004
- * @param {{tokens?: number|null, output?: number|null}} [source]
1005
- * @returns {number|null}
1006
- */
1007
- function displayTokens(source) {
1008
- if (!source || typeof source !== 'object') return null;
1009
- // The half the turn PRODUCED, from either shape this file is handed: an
1010
- // accounting or roll record (`output`), or a stored token bucket
1011
- // (`tokens: {output}` — what `rollMessages` reads back out of the shared
1012
- // store, and what a rebuilt session presents).
1013
- const nested = source.tokens;
1014
- const candidates = [source.output];
1015
- if (nested && typeof nested === 'object') {
1016
- candidates.push(nested.output, nested.output_tokens, nested.completion_tokens);
1017
- } else {
1018
- candidates.push(source.output_tokens, source.completion_tokens);
1019
- }
1020
- for (const c of candidates) {
1021
- if (typeof c === 'number' && isFinite(c) && c > 0) return c;
1022
- }
1023
- // The wire's TOTAL is deliberately NOT a fallback here. `tokens` is
1024
- // input + output, and on a cached turn the input half is the larger one, so
1025
- // falling back to it put back the exact reading this rule exists to remove:
1026
- // `tokens: 3,145` on a turn that wrote 145. This was the last surviving
1027
- // place the input half reached the screen — the split had been dropped, and
1028
- // the total it fell back to still carried it.
1029
- //
1030
- // Stated once more, because it is the whole point: a turn the wire priced but
1031
- // did not itemise has NO output figure, and inventing one from the total
1032
- // would be a number no provider sent. That turn's row states its own text
1033
- // estimate instead (`~N tokens`), which is at least a figure about what was
1034
- // written.
1035
- return null;
1036
- }
1037
-
1038
- /**
1039
- * The rolling session total as one line — the desktop's counterpart of the
1040
- * CLI's `tokenSummary`. Empty string when nothing has been accounted for, so
1041
- * an untouched session adds no noise to a turn's meta line.
1042
- *
1043
- * @param {object} [roll]
1044
- * @returns {string} e.g. `2,300 tokens · 4 calls · $0.0310` — the CLI's fields in
1045
- * the CLI's order, minus the input/output parenthetical (see below). The
1046
- * figure is the OUTPUT (see `displayTokens`).
1047
- */
1048
- function fmtRoll(roll, opts = {}) {
1049
- const r = roll || emptyRoll();
1050
- if (!r.turns && !r.calls) return '';
1051
- // The fields are `tokenSummary`'s (cli/src/app.js:1413) in its order — tokens,
1052
- // calls, money — with one dropped: the `(10,100 in / 2,300 out)` split. `in`
1053
- // and `out` are a terminal status-line shorthand, legible to someone already
1054
- // reading that status line and to nobody else, which is what an unlabelled
1055
- // abbreviation in a GUI topbar turns into.
1056
- //
1057
- // …and the figure that remains is the OUTPUT, not the wire's total. This line
1058
- // used to print `r.tokens`, which is input + output: on a cached turn the
1059
- // prompt restated is the larger half, so a session that wrote 2,300 tokens on
1060
- // a 10,100-token prompt read `12,400 tokens` and looked like a model emitting
1061
- // five times what it did. The parenthetical was not the only place the input
1062
- // half showed up — it was in the total too, and dropping the split alone left
1063
- // the reader comparing two numbers that were both mostly their own prompt.
1064
- // `displayTokens` holds the rule, the same one the CLI's `fmtUsageSplit` uses.
1065
- // `r.input` is still folded onto the roll (see `rollTurn`) for any surface
1066
- // that wants to show the split with real labels.
1067
- const bits = [];
1068
- // The token half only when something was actually counted. `rollTurn` counts
1069
- // turns and calls BEFORE it looks at the token count, so a dispatch that
1070
- // reported nothing still reaches here — and printing an empty tally would put
1071
- // `0 tokens` on the topbar, a figure the meter never took, which reads as a
1072
- // counter that does not move. `displayTokens` returns null rather than 0 for
1073
- // exactly that case, and falls back to the total only when no split arrived.
1074
- // The turn count is still stated, because that much is true.
1075
- const produced = displayTokens(r);
1076
- if (produced != null) {
1077
- bits.push(`${fmtTokens(produced)} tokens`);
1078
- }
1079
- bits.push(`${r.calls} call${r.calls === 1 ? '' : 's'}`);
1080
- // Money is where this line departs from `tokenSummary`, deliberately: that
1081
- // one sums a single `session.cost` in EUR via fmtEur, while this surface keeps
1082
- // a settled charge and a local estimate apart so a `~`-estimate can never be
1083
- // read as part of the bill. Desktop's pre-existing fmtCost renders both, and
1084
- // its `$` convention is left exactly as it was.
1085
- // Money is omitted entirely on a tier AEGIS does not bill a fee to
1086
- // (`opts.omitMoney` — see `feeWaived`). Not zeroed, not marked `~`: a `$0.0000`
1087
- // states a price, and this account has no price on this turn.
1088
- if (!opts.omitMoney && (r.cost > 0 || r.estimate > 0)) {
1089
- const money = [];
1090
- if (r.cost > 0) money.push(fmtCost(r.cost, true));
1091
- if (r.estimate > 0) money.push(fmtCost(r.estimate, false));
1092
- bits.push(money.join(' + '));
1093
- }
1094
- // No counterpart in `tokenSummary`, which folds a usage-less turn silently and
1095
- // so reports a total short of the truth without saying so. Named here instead:
1096
- // the count appears only when something went unreported, and it never changes
1097
- // a number — it only says the number is not the whole story.
1098
- if (r.unknown) bits.push(`${r.unknown} unrpt`);
1099
- // The other half of the same honesty: a total that includes estimated
1100
- // exchanges says so, because the CLI marks the same rows `real: false` and a
1101
- // reader is entitled to know which figure they are looking at. It changes no
1102
- // number — it says the number is partly inferred.
1103
- if (r.estimated) bits.push(`${r.estimated} est`);
1104
- return bits.join(' · ');
1105
- }
1106
-
1107
- /**
1108
- * A cost for display. Estimates are marked with `~` so an estimate is never
1109
- * mistaken for a settled charge.
1110
- *
1111
- * @param {number} cost
1112
- * @param {boolean} [real]
1113
- * @returns {string}
1114
- */
1115
- function fmtCost(cost, real) {
1116
- if (typeof cost !== 'number' || !isFinite(cost)) return '';
1117
- // The `$` is not decoration: its loss was a regression, not a decision.
1118
- // `4d5d1e9` introduced this function with it (`~$18.0000`); `6d48470` — a
1119
- // commit about the token TOTAL, unrelated to money — dropped it as a stray
1120
- // hunk. Every desktop turn row then painted a bare `18.0000`, a number with no
1121
- // currency on it, where the CLI paints `€0.03` for the same figure.
1122
- return `${real ? '' : '~'}$${cost.toFixed(4)}`;
1123
- }
1124
-
1125
- /**
1126
- * True when this account's tier means AEGIS bills no per-turn fee, so no money
1127
- * figure belongs on a turn row or a session roll.
1128
- *
1129
- * The fee in question is the BYOK handling fee — the only charge AEGIS adds on
1130
- * top of a caller's own provider bill — and aegis1 waives it on Unlimited:
1131
- * `lib/local/entitlement.js` states the rule in as many words ("the throughput
1132
- * allowance and the BYOK fee waiver are `is_unlimited()`-gated"), and the tier
1133
- * a welcome trial grants IS Unlimited (a 30-day `unlimited` row in
1134
- * `subscriptions`, which `register_device` writes in the same request that mints
1135
- * the key). So a trial account resolves here exactly like a paying one, which is
1136
- * what "trial unlimited" means — the trial is not a separate tier with its own
1137
- * money rule, it is Unlimited for 30 days.
1138
- *
1139
- * Matching is on the resolved tier rather than `pro`: `pro` is "the PLAN is paid
1140
- * for" and is also true of the €9 tier's aliases, while the waiver is gated on
1141
- * `unlimited` specifically. A funded bank on a free plan is not a tier at all
1142
- * (`entitlement.js` refuses to name one) and is therefore NOT waived — that
1143
- * account pays the fee from the bank, and hiding the number would leave it with
1144
- * no meter for the only money it spends.
1145
- *
1146
- * @param {{tier?: string|null, plan?: string|null, planRaw?: string|null}} [entitlement]
1147
- * @returns {boolean}
1148
- */
1149
- function feeWaived(entitlement) {
1150
- if (!entitlement || typeof entitlement !== 'object') return false;
1151
- const named = [
1152
- entitlement.tier,
1153
- entitlement.plan,
1154
- entitlement.planRaw,
1155
- entitlement.subscription,
1156
- entitlement.subscriptionTier,
1157
- entitlement.product,
1158
- // The server's own two fields, as `register_device` writes them: a welcome
1159
- // trial is a 30-day `unlimited` row in `subscriptions`, and `item`/`sku` is
1160
- // that row's product name. Naming them here is what keeps a trial account
1161
- // from resolving to "no tier" and being billed a fee it does not owe.
1162
- entitlement.item,
1163
- entitlement.sku,
1164
- ]
1165
- .filter((v) => typeof v === 'string')
1166
- .map((v) => v.trim().toLowerCase());
1167
- // An explicit boolean outranks every spelling below: aegis1's `is_unlimited()`
1168
- // verdict is the fact, and the strings are only what it is written as on the
1169
- // wire. A probe that answers with the bit and not the tier is still an answer.
1170
- if (entitlement.unlimited === true) return true;
1171
- if (named.some((v) => v === 'unlimited' || v === 'trial')) return true;
1172
- // A tier string that merely CONTAINS the word — `unlimited_trial`,
1173
- // `plan.unlimited`, `Unlimited (trial)` — so a server that decorates the name
1174
- // cannot put the fee back on an account whose tier is Unlimited.
1175
- return named.some((v) => /(^|[^a-z])unlimited([^a-z]|$)/.test(v));
1176
- }
1177
-
1178
- /**
1179
- * Whether a money figure belongs on this account's turn row or session roll.
1180
- *
1181
- * The CLI's exact rule (`cli/src/format.js` → `feeBillable`), and it is the same
1182
- * rule on purpose — the two hosts render the same turn from the same engine, so
1183
- * a row that shows a fee on one and waives it on the other is a disagreement
1184
- * about what the user owes.
1185
- *
1186
- * A price is printed UNLESS AEGIS either waives it or has not proven it owed:
1187
- *
1188
- * - a tier AEGIS waives (`feeWaived`) → no price. Unlimited, paid or on the
1189
- * 30-day welcome trial, has no per-turn charge and no bank draw;
1190
- * - a snapshot asserting a plan it cannot prove (`degraded`) → no price. The
1191
- * entitlement module STARTS at exactly that: `makeFreeSnapshot()` reads
1192
- * `plan: 'free'`, `tier: null`, `source: 'unresolved'`, `degraded: true`,
1193
- * which says "no verdict yet", not "this account is free". Reading the
1194
- * placeholder as a verdict is what put `~$0.0005` and an "AEGIS handling fee"
1195
- * line on the turns of trial accounts whose probe had not answered — a fee
1196
- * charged in writing to the one account that does not pay it;
1197
- * - everything else → the price stands, including when no snapshot exists at
1198
- * all. A cost figure is a measurement of the turn, and dropping a real number
1199
- * because no tier was published would leave a self-hosted or BYO-key run with
1200
- * no meter for money it actually spent.
1201
- *
1202
- * The token figure is never gated by this, on any branch: what a turn produced
1203
- * is not a price, and hiding it would leave an Unlimited account with no meter.
1204
- *
1205
- * @param {{tier?: string|null, plan?: string|null, planRaw?: string|null,
1206
- * degraded?: boolean, source?: string|null, unlimited?: boolean}} [entitlement]
1207
- * @returns {boolean}
1208
- */
1209
- function feeBillable(entitlement) {
1210
- if (!entitlement || typeof entitlement !== 'object') return true;
1211
- if (feeWaived(entitlement)) return false;
1212
- return entitlement.degraded !== true;
1213
- }
1214
-
1215
- if (typeof module !== 'undefined' && module.exports) {
1216
- module.exports = {
1217
- feeWaived,
1218
- feeBillable,
1219
- RATES,
1220
- RATE_BASIS,
1221
- UNPRICED_BY_DESIGN,
1222
- isPeak,
1223
- usageTokens,
1224
- ratesFor,
1225
- usageBuckets,
1226
- cacheHitRate,
1227
- usageCost,
1228
- costBreakdown,
1229
- turnAccounting,
1230
- displayTokens,
1231
- estimateTokens,
1232
- estimatedBuckets,
1233
- emptyRoll,
1234
- rollTurn,
1235
- rollMessages,
1236
- ledgerRow,
1237
- fmtTokens,
1238
- fmtRoll,
1239
- fmtCost,
1240
- };
1241
- }
3
+ "use strict";function usageTokens(e){if(!e||"object"!=typeof e)return null;if("number"==typeof e.total_tokens)return e.total_tokens;const t=e.input_tokens??e.prompt_tokens??e.input,o=e.output_tokens??e.completion_tokens??e.output;return"number"!=typeof t&&"number"!=typeof o?null:(t||0)+(o||0)}function estimateTokens(e){return e?Math.max(1,Math.ceil([...String(e)].length/4)):0}function estimatedBuckets(e,t,o){const n=("string"==typeof t?t:"")+("string"==typeof o?o:"");return"string"==typeof e&&e.length>0||n.length>0?{input:estimateTokens(e),output:estimateTokens(n),cacheRead:0,cacheWrite:0,real:!1}:null}const RATES={sonnet:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},default:{input:3,output:15,cacheRead:.3,cacheWrite:3.75},fable:{input:10,output:50,cacheRead:1,cacheWrite:12.5},opus:{input:5,output:25,cacheRead:.5,cacheWrite:6.25},haiku:{input:1,output:5,cacheRead:.1,cacheWrite:1.25},"claude-haiku":{input:1,output:5,cacheRead:.1,cacheWrite:1.25},"claude-opus-5":{input:5,output:25,cacheRead:.5,cacheWrite:6.25},"claude-opus-5-5":{input:4,output:20,cacheRead:.2,cacheWrite:5},"claude-sonnet-5":{input:2,output:10,cacheRead:.2,cacheWrite:2.5},"claude-sonnet-5-5":{input:2,output:10,cacheRead:.1,cacheWrite:2.5},"claude-haiku-5-5":{input:.1,output:.5,cacheRead:.01,cacheWrite:.125},"claude-fable-5":{input:10,output:50,cacheRead:1,cacheWrite:12.5},"claude-fable-5-1":{input:10,output:50,cacheRead:.25,cacheWrite:12.5},"claude-sonnet-4-6":{input:3,output:15,cacheRead:.3,cacheWrite:3.75},"claude-sonnet-4-5":{input:3,output:15,cacheRead:.3,cacheWrite:3.75},deepseek:{input:.3,output:1.2,cacheRead:.006,cacheWrite:.3,offPeak:{input:.15,output:.6,cacheRead:.003,cacheWrite:.15}},"deepseek-v4-pro":{input:1.32,output:3.96,cacheRead:.044,cacheWrite:1.32,offPeak:{input:.66,output:1.98,cacheRead:.022,cacheWrite:.66}},"deepseek-v4.1-pro":{input:1.32,output:3.96,cacheRead:.044,cacheWrite:1.32,offPeak:{input:.66,output:1.98,cacheRead:.022,cacheWrite:.66}},"grok-4.7":{input:2,output:6,cacheRead:.5,cacheWrite:2},"gemini-3.8-flash":{input:.75,output:3.75,cacheRead:.075,cacheWrite:.75},"gpt-5.5":{input:5,output:30,cacheRead:.5,cacheWrite:5}};function isPeak(e,t=new Date){if(0!==String(e||"").toLowerCase().indexOf("deepseek"))return!0;const o=t.getUTCDay();if(0===o||6===o)return!1;const n=t.getUTCHours();return n>=1&&n<4||n>=6&&n<10}const RATE_BASIS=Object.freeze({EXACT:"exact",PREFIX:"prefix",FAMILY:"family",DEFAULT:"default"}),RATE_FAMILIES=Object.keys(RATES).filter((e=>"default"!==e)),UNPRICED_BY_DESIGN=Object.freeze({"nexus-brain":"pooled: multi-call fan-out, aegis1 settles the charge","aegis-brain":"pooled alias of nexus-brain","nexus-brain-smart":"pooled alias of nexus-brain","nexus-brain-neo":"pooled alias of nexus-brain","aegis-brain-smart":"pooled alias of nexus-brain","aegis-brain-neo":"pooled alias of nexus-brain","openai-gpt4o-mini":"pooled seat, aegis1 settles the charge",anthropic:"provider name, not a model id",openai:"provider name, not a model id",groq:"provider name, not a model id",google:"provider name, not a model id",xai:"provider name, not a model id"});function ratesFor(e,{at:t}={}){const o=String(e||"").toLowerCase(),n=(e,n)=>{const s=isPeak(0===o.indexOf("deepseek")||o.indexOf(":deepseek")>-1?"deepseek":o,t||new Date);return{...!s&&e.offPeak?{...e,...e.offPeak}:e,basis:n,peak:s,model:o}};if(!o)return n(RATES.default,RATE_BASIS.DEFAULT);const s=[o],a=Math.max(o.lastIndexOf(":"),o.lastIndexOf("/")),u=o.slice(a+1);u&&u!==o&&s.push(u);for(const e of s)if(RATES[e])return n(RATES[e],RATE_BASIS.EXACT);let c=null,i=0;for(const e of s)for(const[t,o]of Object.entries(RATES))"default"!==t&&e.startsWith(t)&&t.length>i&&(c=o,i=t.length);if(c)return n(c,RATE_BASIS.PREFIX);let r=null,p=0;for(const e of RATE_FAMILIES)o.includes(e)&&e.length>p&&(r=RATES[e],p=e.length);return n(r||RATES.default,r?RATE_BASIS.FAMILY:RATE_BASIS.DEFAULT)}function usageBuckets(e){const t=e&&"object"==typeof e?e:{},o=(...e)=>{for(const t of e)if("number"==typeof t)return t;return 0},n=e=>"number"==typeof e?e:void 0,s=n(t.input_tokens),a=n(t.prompt_tokens),u=t.prompt_tokens_details,c=u&&"object"==typeof u?n(u.cached_tokens):void 0,i=o(t.prompt_cache_hit_tokens,c,t.cached_tokens),r=void 0===s&&void 0!==a,p=r?a:o(s,a,t.input),l=o(t.cache_read_input_tokens,t.cacheRead,i),d=r?Math.min(Math.max(0,p),l):l,f=o(t.cache_creation_input_tokens,t.cacheWrite),m=o(t.output_tokens,t.completion_tokens,t.output),h=r?Math.max(0,p-d):p,k=o(t.total_tokens),R=h+m+d+f;return{input:k>R?h+(k-R):h,output:m,cacheRead:d,cacheWrite:f,cacheReported:"number"==typeof t.cache_read_input_tokens||"number"==typeof t.cacheRead||"number"==typeof t.cache_creation_input_tokens||"number"==typeof t.cacheWrite||"number"==typeof t.prompt_cache_hit_tokens||"number"==typeof t.cached_tokens||"number"==typeof c}}function cacheHitRate(e){const t=usageBuckets(e),o=Math.max(0,t.cacheRead||0),n=Math.max(0,t.input||0),s=o+n;return{read:o,miss:n,prompt:s,pct:t.cacheReported&&s>0?o/s*100:null,reported:t.cacheReported}}function costBreakdown(e,t,o={}){const n=ratesFor(t,o),s=usageBuckets(e),a=(e,t)=>Math.max(0,Number(e)||0)/1e6*t;return{cost:a(s.input,n.input)+a(s.output,n.output)+a(s.cacheRead,n.cacheRead)+a(s.cacheWrite,n.cacheWrite),basis:n.basis,peak:n.peak,model:n.model,priced:n.basis!==RATE_BASIS.DEFAULT}}function usageCost(e,t,o={}){return costBreakdown(e,t,o).cost}function turnAccounting(e,t,o={}){const n=usageTokens(e),s=e&&"object"==typeof e?e:{},a=e&&"object"==typeof e?usageBuckets(e).output:null,u="number"==typeof o.costUsd?o.costUsd:"number"==typeof s.costUsd?s.costUsd:void 0;if("number"==typeof u)return{tokens:n,output:a,cost:u,real:!0,estimated:!1,basis:"settled",priced:!0};if(null==n)return{tokens:n,output:a,cost:null,real:!1,estimated:!1,basis:null,priced:!1};const c=costBreakdown(s,t,o);return{tokens:n,output:a,cost:c.cost,real:!1,estimated:!0,basis:c.basis,priced:c.priced}}function emptyRoll(){return{turns:0,calls:0,tokens:0,input:0,output:0,cacheRead:0,cacheWrite:0,unknown:0,estimated:0,cost:0,estimate:0}}function rollTurn(e,t,o={}){const n=Object.assign(emptyRoll(),e||{});n.turns+=void 0===o.turns?1:Number(o.turns)||0,n.calls+=void 0===o.calls?1:Number(o.calls)||0;const s=turnAccounting(t,o.model,{costUsd:o.costUsd}),a=!0===o.estimated||t&&!1===t.real;if(null==s.tokens){const e=estimatedBuckets(o.prompt,o.reply,o.reasoning),t="number"==typeof o.measuredReasoningTokens&&o.measuredReasoningTokens>0?o.measuredReasoningTokens:0;return e?(n.tokens+=e.input+e.output+t,n.input+=e.input,n.output+=e.output+t,n.estimated+=1,n):t?(n.tokens+=t,n.output+=t,n.estimated+=1,n):(n.unknown+=1,n)}const u=usageBuckets(t);return n.tokens+=s.tokens,n.input+=u.input,n.output+=u.output,n.cacheRead+=u.cacheRead,n.cacheWrite+=u.cacheWrite,a?(n.estimated+=1,n):(s.real?n.cost+=s.cost:null!=s.cost&&(n.estimate+=s.cost),n)}function rollMessages(e){let t=emptyRoll();for(const o of Array.isArray(e)?e:[])o&&"assistant"===o.role&&(t=rollTurn(t,o.tokens,{model:o.model,costUsd:"number"==typeof o.costUsd?o.costUsd:void 0,calls:o.calls}));return t}function ledgerRow(e,t,o={}){const n=t||turnAccounting(e,o.model,{costUsd:o.costUsd}),s=Number.isFinite(o.calls)&&o.calls>0?o.calls:void 0;if(null!=n.tokens){const t={tokens:usageBuckets(e)};return n.real&&null!=n.cost&&(t.costUsd=n.cost),void 0!==s&&(t.calls=s),t}const a=estimatedBuckets(o.prompt,o.reply,o.reasoning);if(!a)return null;const u={tokens:a};return void 0!==s&&(u.calls=s),u}function fmtTokens(e){const t=Number(e);return!Number.isFinite(t)||t<=0?"0":Math.round(t).toString().replace(/\B(?=(\d{3})+(?!\d))/g,",")}function displayTokens(e){if(!e||"object"!=typeof e)return null;const t=e.tokens,o=[e.output];t&&"object"==typeof t?o.push(t.output,t.output_tokens,t.completion_tokens):o.push(e.output_tokens,e.completion_tokens);for(const e of o)if("number"==typeof e&&isFinite(e)&&e>0)return e;return null}function fmtRoll(e,t={}){const o=e||emptyRoll();if(!o.turns&&!o.calls)return"";const n=[],s=displayTokens(o);if(null!=s&&n.push(`${fmtTokens(s)} tokens`),n.push(`${o.calls} call${1===o.calls?"":"s"}`),!t.omitMoney&&(o.cost>0||o.estimate>0)){const e=[];o.cost>0&&e.push(fmtCost(o.cost,!0)),o.estimate>0&&e.push(fmtCost(o.estimate,!1)),n.push(e.join(" + "))}return o.unknown&&n.push(`${o.unknown} unrpt`),o.estimated&&n.push(`${o.estimated} est`),n.join(" · ")}function fmtCost(e,t){return"number"==typeof e&&isFinite(e)?`${t?"":"~"}$${e.toFixed(4)}`:""}function feeWaived(e){if(!e||"object"!=typeof e)return!1;const t=[e.tier,e.plan,e.planRaw,e.subscription,e.subscriptionTier,e.product,e.item,e.sku].filter((e=>"string"==typeof e)).map((e=>e.trim().toLowerCase()));return!0===e.unlimited||!!t.some((e=>"unlimited"===e||"trial"===e))||t.some((e=>/(^|[^a-z])unlimited([^a-z]|$)/.test(e)))}function feeBillable(e){return!e||"object"!=typeof e||!feeWaived(e)&&!0!==e.degraded}"undefined"!=typeof module&&module.exports&&(module.exports={feeWaived:feeWaived,feeBillable:feeBillable,RATES:RATES,RATE_BASIS:RATE_BASIS,UNPRICED_BY_DESIGN:UNPRICED_BY_DESIGN,isPeak:isPeak,usageTokens:usageTokens,ratesFor:ratesFor,usageBuckets:usageBuckets,cacheHitRate:cacheHitRate,usageCost:usageCost,costBreakdown:costBreakdown,turnAccounting:turnAccounting,displayTokens:displayTokens,estimateTokens:estimateTokens,estimatedBuckets:estimatedBuckets,emptyRoll:emptyRoll,rollTurn:rollTurn,rollMessages:rollMessages,ledgerRow:ledgerRow,fmtTokens:fmtTokens,fmtRoll:fmtRoll,fmtCost:fmtCost});