@sriinnu/fiche 0.0.0-stage → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (196) hide show
  1. package/CHANGELOG.md +134 -0
  2. package/LICENSE +22 -0
  3. package/NOTICE +13 -0
  4. package/PRIVACY.md +41 -0
  5. package/README.md +288 -2
  6. package/SECURITY.md +53 -0
  7. package/assets/JETBRAINS_MONO_LICENSE.txt +89 -0
  8. package/assets/SPLEEN_LICENSE.txt +24 -0
  9. package/assets/UNIFONT_LICENSE.txt +476 -0
  10. package/assets/fiche-logo-dark.svg +61 -0
  11. package/assets/fiche-logo-light.svg +61 -0
  12. package/assets/fiche-logo.svg +71 -0
  13. package/assets/fiche-mark.svg +48 -0
  14. package/bin/cli.js +7 -0
  15. package/bin/mcp.js +8 -0
  16. package/dist/calibrate.d.ts +30 -0
  17. package/dist/calibrate.js +588 -0
  18. package/dist/core/anthropic-vision.d.ts +28 -0
  19. package/dist/core/anthropic-vision.js +34 -0
  20. package/dist/core/applicability.d.ts +63 -0
  21. package/dist/core/applicability.js +151 -0
  22. package/dist/core/atlas-gray-jbmono10.d.ts +26 -0
  23. package/dist/core/atlas-gray-jbmono10.js +64 -0
  24. package/dist/core/atlas-gray-jbmono12.d.ts +26 -0
  25. package/dist/core/atlas-gray-jbmono12.js +64 -0
  26. package/dist/core/atlas-gray-jbmono14.d.ts +26 -0
  27. package/dist/core/atlas-gray-jbmono14.js +64 -0
  28. package/dist/core/atlas-gray.d.ts +26 -0
  29. package/dist/core/atlas-gray.js +64 -0
  30. package/dist/core/atlas-jbmono10.d.ts +34 -0
  31. package/dist/core/atlas-jbmono10.js +71 -0
  32. package/dist/core/atlas-jbmono12.d.ts +34 -0
  33. package/dist/core/atlas-jbmono12.js +71 -0
  34. package/dist/core/atlas-jbmono14.d.ts +34 -0
  35. package/dist/core/atlas-jbmono14.js +71 -0
  36. package/dist/core/atlas.d.ts +34 -0
  37. package/dist/core/atlas.js +71 -0
  38. package/dist/core/baseline.d.ts +121 -0
  39. package/dist/core/baseline.js +200 -0
  40. package/dist/core/calibration.d.ts +86 -0
  41. package/dist/core/calibration.js +547 -0
  42. package/dist/core/casi-delta.d.ts +63 -0
  43. package/dist/core/casi-delta.js +1271 -0
  44. package/dist/core/claude-model-profiles.d.ts +53 -0
  45. package/dist/core/claude-model-profiles.js +160 -0
  46. package/dist/core/client-tool-round.d.ts +31 -0
  47. package/dist/core/client-tool-round.js +58 -0
  48. package/dist/core/codex-cache.d.ts +20 -0
  49. package/dist/core/codex-cache.js +59 -0
  50. package/dist/core/context-mmu.d.ts +350 -0
  51. package/dist/core/context-mmu.js +3028 -0
  52. package/dist/core/cpt-fit.d.ts +70 -0
  53. package/dist/core/cpt-fit.js +197 -0
  54. package/dist/core/env.d.ts +8 -0
  55. package/dist/core/env.js +15 -0
  56. package/dist/core/export.d.ts +127 -0
  57. package/dist/core/export.js +385 -0
  58. package/dist/core/factsheet.d.ts +77 -0
  59. package/dist/core/factsheet.js +494 -0
  60. package/dist/core/gemini-model-profiles.d.ts +20 -0
  61. package/dist/core/gemini-model-profiles.js +134 -0
  62. package/dist/core/google.d.ts +76 -0
  63. package/dist/core/google.js +1380 -0
  64. package/dist/core/gpt-model-profiles.d.ts +218 -0
  65. package/dist/core/gpt-model-profiles.js +570 -0
  66. package/dist/core/gpt-tokens.d.ts +14 -0
  67. package/dist/core/gpt-tokens.js +165 -0
  68. package/dist/core/history.d.ts +197 -0
  69. package/dist/core/history.js +1003 -0
  70. package/dist/core/index.d.ts +16 -0
  71. package/dist/core/index.js +16 -0
  72. package/dist/core/library.d.ts +80 -0
  73. package/dist/core/library.js +131 -0
  74. package/dist/core/measurement.d.ts +34 -0
  75. package/dist/core/measurement.js +280 -0
  76. package/dist/core/messages-chat-bridge.d.ts +23 -0
  77. package/dist/core/messages-chat-bridge.js +747 -0
  78. package/dist/core/messages-responses-bridge.d.ts +11 -0
  79. package/dist/core/messages-responses-bridge.js +893 -0
  80. package/dist/core/openai-history.d.ts +184 -0
  81. package/dist/core/openai-history.js +1279 -0
  82. package/dist/core/openai-savings.d.ts +57 -0
  83. package/dist/core/openai-savings.js +116 -0
  84. package/dist/core/openai.d.ts +68 -0
  85. package/dist/core/openai.js +2523 -0
  86. package/dist/core/pin.d.ts +199 -0
  87. package/dist/core/pin.js +1353 -0
  88. package/dist/core/png.d.ts +14 -0
  89. package/dist/core/png.js +188 -0
  90. package/dist/core/prefix-tape.d.ts +102 -0
  91. package/dist/core/prefix-tape.js +315 -0
  92. package/dist/core/price-id.d.ts +10 -0
  93. package/dist/core/price-id.js +26 -0
  94. package/dist/core/prices.generated.d.ts +36 -0
  95. package/dist/core/prices.generated.js +369 -0
  96. package/dist/core/pricing.d.ts +134 -0
  97. package/dist/core/pricing.js +335 -0
  98. package/dist/core/profile-base.d.ts +30 -0
  99. package/dist/core/profile-base.js +67 -0
  100. package/dist/core/provider-router.d.ts +51 -0
  101. package/dist/core/provider-router.js +121 -0
  102. package/dist/core/proxy.d.ts +252 -0
  103. package/dist/core/proxy.js +2929 -0
  104. package/dist/core/reader-tier.d.ts +24 -0
  105. package/dist/core/reader-tier.js +118 -0
  106. package/dist/core/render.d.ts +280 -0
  107. package/dist/core/render.js +1302 -0
  108. package/dist/core/request-guard.d.ts +31 -0
  109. package/dist/core/request-guard.js +126 -0
  110. package/dist/core/request-transform.d.ts +43 -0
  111. package/dist/core/request-transform.js +173 -0
  112. package/dist/core/schema-compiler.d.ts +64 -0
  113. package/dist/core/schema-compiler.js +1696 -0
  114. package/dist/core/schema-strip.d.ts +29 -0
  115. package/dist/core/schema-strip.js +173 -0
  116. package/dist/core/session-state.d.ts +219 -0
  117. package/dist/core/session-state.js +929 -0
  118. package/dist/core/stage-plugins.d.ts +45 -0
  119. package/dist/core/stage-plugins.js +205 -0
  120. package/dist/core/text-history.d.ts +74 -0
  121. package/dist/core/text-history.js +612 -0
  122. package/dist/core/text-hygiene.d.ts +160 -0
  123. package/dist/core/text-hygiene.js +2259 -0
  124. package/dist/core/toon.d.ts +29 -0
  125. package/dist/core/toon.js +425 -0
  126. package/dist/core/tracker.d.ts +223 -0
  127. package/dist/core/tracker.js +290 -0
  128. package/dist/core/transform.d.ts +589 -0
  129. package/dist/core/transform.js +3153 -0
  130. package/dist/core/types.d.ts +87 -0
  131. package/dist/core/types.js +8 -0
  132. package/dist/core/upstream-hosts.d.ts +127 -0
  133. package/dist/core/upstream-hosts.js +398 -0
  134. package/dist/core/vision-cost.d.ts +63 -0
  135. package/dist/core/vision-cost.js +137 -0
  136. package/dist/dashboard/fragments.d.ts +87 -0
  137. package/dist/dashboard/fragments.js +1515 -0
  138. package/dist/dashboard/types.d.ts +217 -0
  139. package/dist/dashboard/types.js +3 -0
  140. package/dist/dashboard/vendor.d.ts +3 -0
  141. package/dist/dashboard/vendor.js +6 -0
  142. package/dist/dashboard.d.ts +372 -0
  143. package/dist/dashboard.js +2731 -0
  144. package/dist/export-collect.d.ts +36 -0
  145. package/dist/export-collect.js +59 -0
  146. package/dist/file-tracker.d.ts +42 -0
  147. package/dist/file-tracker.js +234 -0
  148. package/dist/kosha-sync.d.ts +74 -0
  149. package/dist/kosha-sync.js +272 -0
  150. package/dist/launchd-socket.d.ts +22 -0
  151. package/dist/launchd-socket.js +210 -0
  152. package/dist/mcp/cli.d.ts +2 -0
  153. package/dist/mcp/cli.js +55 -0
  154. package/dist/mcp/server.d.ts +48 -0
  155. package/dist/mcp/server.js +987 -0
  156. package/dist/mmu-store.d.ts +31 -0
  157. package/dist/mmu-store.js +179 -0
  158. package/dist/node-fetch.d.ts +22 -0
  159. package/dist/node-fetch.js +489 -0
  160. package/dist/node.d.ts +9 -0
  161. package/dist/node.js +244396 -0
  162. package/dist/request-decoding.d.ts +30 -0
  163. package/dist/request-decoding.js +85 -0
  164. package/dist/sessions.d.ts +179 -0
  165. package/dist/sessions.js +837 -0
  166. package/dist/stats.d.ts +114 -0
  167. package/dist/stats.js +439 -0
  168. package/dist/turn-report.d.ts +65 -0
  169. package/dist/turn-report.js +724 -0
  170. package/dist/warp/app-launch.d.ts +26 -0
  171. package/dist/warp/app-launch.js +155 -0
  172. package/dist/warp/ca.d.ts +74 -0
  173. package/dist/warp/ca.js +416 -0
  174. package/dist/warp/connect.d.ts +42 -0
  175. package/dist/warp/connect.js +686 -0
  176. package/dist/warp/der.d.ts +57 -0
  177. package/dist/warp/der.js +151 -0
  178. package/dist/warp/index.d.ts +79 -0
  179. package/dist/warp/index.js +650 -0
  180. package/dist/warp/resolve.d.ts +12 -0
  181. package/dist/warp/resolve.js +49 -0
  182. package/dist/warp/route.d.ts +71 -0
  183. package/dist/warp/route.js +134 -0
  184. package/dist/worker.d.ts +71 -0
  185. package/dist/worker.js +174 -0
  186. package/docs/SECURITY_MODEL.md +84 -0
  187. package/package.json +122 -4
  188. package/plugins/fiche-companion/README.md +42 -0
  189. package/plugins/fiche-companion/assets/logo.svg +48 -0
  190. package/plugins/fiche-companion/hooks.json +11 -0
  191. package/plugins/fiche-companion/mcp_config.json +8 -0
  192. package/plugins/fiche-companion/plugin.json +18 -0
  193. package/plugins/fiche-companion/scripts/claude-statusline.mjs +35 -0
  194. package/plugins/fiche-companion/scripts/post-invocation.mjs +122 -0
  195. package/plugins/fiche-companion/scripts/resolve-turn-report.mjs +132 -0
  196. package/plugins/fiche-companion/skills/fiche/SKILL.md +61 -0
@@ -0,0 +1,335 @@
1
+ /**
2
+ * One place every price ratio comes from.
3
+ *
4
+ * inkling compares token counts weighted by price ratios (cached input,
5
+ * cache write and output, each divided by the uncached input price). The
6
+ * compression gate and the savings math must use the same ratios for the same
7
+ * model, so both ask here.
8
+ *
9
+ * Two sources, chosen by `INKLING_PRICES`:
10
+ * - `legacy` (default): the values inkling has always used. Profile fields
11
+ * for the savings math; Anthropic's 5-minute-tier ratios (1.25x write,
12
+ * 0.1x read) for the gate, whatever the model. These are NOT the official
13
+ * per-model prices (Opus 5.5 reads at 0.05x).
14
+ * - `kosha`: the build-time table in prices.generated.ts (first-party rows
15
+ * of a kosha snapshot; `pnpm prices:gen`). An explicit pricing field in
16
+ * INKLING_GPT_PROFILES still wins. A model with no sane row is UNPRICED:
17
+ * the gate passes it through untouched, the savings math falls back to the
18
+ * profile and reports the source as unpriced.
19
+ *
20
+ * Kosha mode also reads the snapshot's TTL write tiers, long-context bands and
21
+ * dated changes through a {@link PriceContext}: the cache TTL the request
22
+ * writes, its prompt size (cached tokens included) and the time. Bands keep
23
+ * the ratios nearly flat (OpenAI, xAI and Haiku 5.5 double input, read and
24
+ * write together); they matter for absolute dollars. The TTL tier matters for
25
+ * the gate: an Anthropic 1h write costs 2x input, not 1.25x.
26
+ *
27
+ * Workers-safe: no node:, no fs. Reads process.env only behind a typeof guard,
28
+ * like gpt-model-profiles.ts.
29
+ */
30
+ import { CACHE_CREATE_RATE, CACHE_READ_RATE } from './baseline.js';
31
+ import { readBrandEnv } from './env.js';
32
+ import { envPricingOverride, resolveGptProfile } from './gpt-model-profiles.js';
33
+ import { normalizeModelId } from './price-id.js';
34
+ import { PRICES, PRICE_ALIASES, PRICE_SNAPSHOT } from './prices.generated.js';
35
+ export { PRICE_SNAPSHOT };
36
+ /** The ratios the Anthropic gate has always priced with: 5-minute write tier,
37
+ * 0.1x read, for every Claude model. */
38
+ export const ANTHROPIC_GATE_RATES = Object.freeze({
39
+ read: CACHE_READ_RATE,
40
+ write: CACHE_CREATE_RATE,
41
+ output: 5,
42
+ });
43
+ /** Which source is active. Anything other than `kosha` is legacy. */
44
+ export function priceMode() {
45
+ const raw = readBrandEnv('PRICES') || '';
46
+ return raw.trim().toLowerCase() === 'kosha' ? 'kosha' : 'legacy';
47
+ }
48
+ const PRICE_ROW_CACHE = new Map();
49
+ /** The snapshot row for a model: exact normalised id, then a kosha alias, then
50
+ * the longest snapshot id that prefixes it at a `-` boundary (a `-codex` or
51
+ * `-latest` variant prices as its base). */
52
+ export function priceRowFor(model) {
53
+ const id = normalizeModelId(model);
54
+ if (!id)
55
+ return undefined;
56
+ const cached = PRICE_ROW_CACHE.get(id);
57
+ if (cached !== undefined)
58
+ return cached ?? undefined;
59
+ const exact = PRICES[id] ?? (PRICE_ALIASES[id] ? PRICES[PRICE_ALIASES[id]] : undefined);
60
+ let resolved = exact;
61
+ if (!resolved) {
62
+ let best;
63
+ for (const key of Object.keys(PRICES)) {
64
+ if (id.startsWith(key + '-') && (best === undefined || key.length > best.length))
65
+ best = key;
66
+ }
67
+ resolved = best ? PRICES[best] : undefined;
68
+ }
69
+ if (PRICE_ROW_CACHE.size < 512) {
70
+ PRICE_ROW_CACHE.set(id, resolved ?? null);
71
+ }
72
+ return resolved;
73
+ }
74
+ /** The row as billed under `ctx`: due dated changes applied, then the band the
75
+ * prompt falls in (above `at`, or from `at` when `incl`) replacing the base
76
+ * rates. A band without its own read or write tiers scales the base ones by
77
+ * its input ratio. */
78
+ export function effectiveRow(row, ctx = {}) {
79
+ if (!row)
80
+ return undefined;
81
+ let r = { ...row };
82
+ const at = ctx.at ?? Date.now();
83
+ for (const c of row.chg ?? []) {
84
+ if (c.at > at)
85
+ continue;
86
+ const { at: _at, ...rates } = c;
87
+ r = { ...r, ...rates };
88
+ // A dated write price supersedes the tier list it was cut from.
89
+ if (rates.cw !== undefined || rates.cw1h !== undefined)
90
+ delete r.cwt;
91
+ }
92
+ const n = ctx.promptTokens;
93
+ if (typeof n === 'number' && Number.isFinite(n)) {
94
+ let band;
95
+ for (const b of r.bands ?? [])
96
+ if (n > b.at || (b.incl === true && n >= b.at))
97
+ band = b;
98
+ if (band && r.in > 0) {
99
+ const k = band.in / r.in;
100
+ const bandCw1h = band.cwt?.find(([ttl]) => ttl === 3600)?.[1];
101
+ r = {
102
+ ...r,
103
+ in: band.in,
104
+ out: band.out ?? (r.out !== undefined ? r.out * k : undefined),
105
+ cr: band.cr ?? (r.cr !== undefined ? r.cr * k : undefined),
106
+ cw: band.cwt?.[0]?.[1] ?? (r.cw !== undefined ? r.cw * k : undefined),
107
+ cw1h: bandCw1h ?? (r.cw1h !== undefined ? r.cw1h * k : undefined),
108
+ cwt: band.cwt ?? r.cwt?.map(([ttl, per]) => [ttl, per * k]),
109
+ };
110
+ }
111
+ }
112
+ return r;
113
+ }
114
+ /** Write price for a TTL: explicit 3600s tier in `cwt` (e.g. band override) or `cw1h` first when ttlSec === 3600, else the shortest tier that lasts at least `ttlSec`, else `cw`. */
115
+ function writePriceFor(row, ttlSec) {
116
+ if (ttlSec === 3600) {
117
+ const tier3600 = row.cwt?.find(([ttl]) => ttl === 3600)?.[1];
118
+ if (typeof tier3600 === 'number')
119
+ return tier3600;
120
+ if (typeof row.cw1h === 'number')
121
+ return row.cw1h;
122
+ }
123
+ const tiers = row.cwt;
124
+ if (!ttlSec || !tiers || tiers.length === 0)
125
+ return row.cw;
126
+ const sorted = [...tiers].sort((a, b) => a[0] - b[0]);
127
+ return (sorted.find(([ttl]) => ttl >= ttlSec) ?? sorted[sorted.length - 1])[1];
128
+ }
129
+ /** Ratios from a snapshot row, or undefined when the row can't be trusted for
130
+ * ratios: no positive input or output, no cache read, a read at or above
131
+ * input, or a write outside [input, 3x input]. A write of 0 or none means no
132
+ * write premium (DeepSeek, z.ai, xAI bill the write as ordinary input). */
133
+ export function ratesFromRow(row, ttlSec) {
134
+ if (!row || !(row.in > 0) || !(typeof row.out === 'number' && row.out > 0))
135
+ return undefined;
136
+ if (typeof row.cr !== 'number')
137
+ return undefined;
138
+ const read = row.cr / row.in;
139
+ if (!(read > 0 && read < 1))
140
+ return undefined;
141
+ // `as-input`: the write bills as plain input (DeepSeek, xAI, z.ai, Google).
142
+ const cw = writePriceFor(row, ttlSec);
143
+ const write = row.cwb === 'as-input' ? 1
144
+ : typeof cw === 'number' && cw > 0 ? cw / row.in : 1;
145
+ if (!(write >= 1 && write <= 3))
146
+ return undefined;
147
+ return { read, write, output: row.out / row.in };
148
+ }
149
+ function legacyTtlWriteRate(profileWrite, ttlSec) {
150
+ const baseWrite = profileWrite ?? 1;
151
+ if (ttlSec === undefined)
152
+ return baseWrite;
153
+ if (ttlSec === 3600 || ttlSec > 300)
154
+ return 2;
155
+ if (ttlSec > 0)
156
+ return Math.max(baseWrite, CACHE_CREATE_RATE);
157
+ return baseWrite;
158
+ }
159
+ function profileRates(model, ttlSec) {
160
+ const profile = resolveGptProfile(model);
161
+ return {
162
+ read: profile.cacheReadRate,
163
+ write: legacyTtlWriteRate(profile.cacheWriteRate, ttlSec),
164
+ output: profile.outputRate,
165
+ };
166
+ }
167
+ let cachedEnvProfilesRaw = '';
168
+ const cachedEnvPricingMap = new Map();
169
+ function memoizedEnvPricingOverride(model) {
170
+ const raw = readBrandEnv('GPT_PROFILES') || '';
171
+ if (!raw)
172
+ return undefined;
173
+ if (raw !== cachedEnvProfilesRaw) {
174
+ cachedEnvProfilesRaw = raw;
175
+ cachedEnvPricingMap.clear();
176
+ }
177
+ const key = model ?? '';
178
+ if (cachedEnvPricingMap.has(key))
179
+ return cachedEnvPricingMap.get(key);
180
+ const resolved = envPricingOverride(model);
181
+ if (cachedEnvPricingMap.size >= 256)
182
+ cachedEnvPricingMap.clear();
183
+ cachedEnvPricingMap.set(key, resolved);
184
+ return resolved;
185
+ }
186
+ /** Kosha-mode ratios with their source; env fields override field by field. */
187
+ function koshaRates(model, ctx = {}) {
188
+ const env = memoizedEnvPricingOverride(model);
189
+ const fromRow = ratesFromRow(effectiveRow(priceRowFor(model), ctx), ctx.ttlSec);
190
+ if (!env)
191
+ return fromRow ? { rates: fromRow, source: 'kosha' } : undefined;
192
+ const base = fromRow ?? profileRates(model);
193
+ return {
194
+ rates: {
195
+ read: env.cacheReadRate ?? base.read,
196
+ write: env.cacheWriteRate ?? base.write,
197
+ output: env.outputRate ?? base.output,
198
+ },
199
+ source: 'env',
200
+ };
201
+ }
202
+ /** Where this model's savings ratios come from under the active mode. */
203
+ export function priceSourceFor(model) {
204
+ if (priceMode() === 'legacy')
205
+ return 'legacy';
206
+ return koshaRates(model)?.source ?? 'unpriced';
207
+ }
208
+ /** Ratios for a model as the savings math prices it. In kosha mode an
209
+ * unpriced model falls back to its profile; check {@link priceSourceFor}
210
+ * before presenting that number as a measured saving. */
211
+ export function resolvePriceRates(model, ctx) {
212
+ if (priceMode() === 'kosha') {
213
+ const k = koshaRates(model, ctx);
214
+ if (k)
215
+ return k.rates;
216
+ }
217
+ return profileRates(model, ctx?.ttlSec);
218
+ }
219
+ /** Ratios the image/text gate in transform.ts prices with, or null when the
220
+ * model is unpriced in kosha mode (the gate then passes the text through).
221
+ * Legacy mode keeps the historical Anthropic ratios for every model. */
222
+ export function gateRatesFor(model, ctx) {
223
+ if (priceMode() === 'legacy')
224
+ return ANTHROPIC_GATE_RATES;
225
+ return koshaRates(model, ctx)?.rates ?? null;
226
+ }
227
+ /** Cache-read ratio for the Anthropic savings math (baseline.ts). Legacy and
228
+ * unpriced models keep the historical 0.1x. Writes stay at Anthropic's
229
+ * published 1.25x (5m) / 2x (1h), which hold for every Claude model. */
230
+ export function anthropicReadRate(model, ctx) {
231
+ if (priceMode() === 'legacy')
232
+ return CACHE_READ_RATE;
233
+ return gateRatesFor(model, ctx)?.read ?? CACHE_READ_RATE;
234
+ }
235
+ /** USD per 1M uncached input tokens for converting saved token-equivalents to
236
+ * dollars, at the band and date in `ctx`, or undefined when legacy mode or
237
+ * the model is unpriced. */
238
+ export function inputUsdPerMtok(model, ctx) {
239
+ if (priceMode() === 'legacy' || !koshaRates(model, ctx))
240
+ return undefined;
241
+ const row = effectiveRow(priceRowFor(model), ctx);
242
+ return row && row.in > 0 ? row.in : undefined;
243
+ }
244
+ /** True for OpenAI GPT/o-series models whose standard prompt cache bills uncached writes at 1.0x. */
245
+ export function isAutoCacheOpenAIModel(model) {
246
+ if (!model)
247
+ return false;
248
+ return /^(?:(?:[^/]+\/)?(?:gpt-|o[134](?=[-.0-9]|$)))/i.test(model.trim());
249
+ }
250
+ function bandWriteUsdPerMtok(row, ttlSec) {
251
+ if (row.cwb === 'as-input')
252
+ return row.in;
253
+ const cw = writePriceFor(row, ttlSec);
254
+ return typeof cw === 'number' && cw > 0 ? cw : row.in;
255
+ }
256
+ /**
257
+ * Evaluate whether shrinking a prompt from `promptTokensBefore` to
258
+ * `promptTokensAfter` drops the entire request below a long-context pricing
259
+ * cliff (e.g. OpenAI 272K, Gemini/Grok 200K, Haiku 5.5 100K, MiniMax M3 512K),
260
+ * turning an amortized multi-turn trade-off into an immediate turn-1 win.
261
+ *
262
+ * Returns null in legacy mode, on unpriced models, or if no cliff is crossed.
263
+ */
264
+ export function evaluateCliffAvoidance(model, args) {
265
+ if (priceMode() === 'legacy')
266
+ return null;
267
+ const baseRow = priceRowFor(model);
268
+ if (!baseRow)
269
+ return null;
270
+ const { promptTokensBefore: beforeTok, promptTokensAfter: afterTok } = args;
271
+ if (!(beforeTok > afterTok) || afterTok < 0)
272
+ return null;
273
+ const rowBefore = effectiveRow(baseRow, { promptTokens: beforeTok, at: args.at });
274
+ const rowAfter = effectiveRow(baseRow, { promptTokens: afterTok, at: args.at });
275
+ if (!rowBefore || !rowAfter || !(rowAfter.in > 0) || !(rowBefore.in > rowAfter.in))
276
+ return null;
277
+ if (typeof rowBefore.cr !== 'number' || typeof rowAfter.cr !== 'number')
278
+ return null;
279
+ const baseDated = effectiveRow(baseRow, { at: args.at });
280
+ let cliffAt = 0;
281
+ for (const b of baseDated?.bands ?? []) {
282
+ const inBefore = beforeTok > b.at || (b.incl === true && beforeTok >= b.at);
283
+ const inAfter = afterTok > b.at || (b.incl === true && afterTok >= b.at);
284
+ if (inBefore && !inAfter && b.at > cliffAt)
285
+ cliffAt = b.at;
286
+ }
287
+ const collapsedBase = Math.max(0, args.collapsedBaselineTokens ?? (beforeTok - afterTok));
288
+ const collapsedActual = Math.max(0, args.collapsedActualTokens ?? Math.max(0, afterTok - (beforeTok - collapsedBase)));
289
+ const downstreamCached = Math.max(0, Math.min(args.downstreamCachedTokens ?? 0, Math.max(0, beforeTok - collapsedBase)));
290
+ const keptPrefix = Math.max(0, beforeTok - collapsedBase - downstreamCached);
291
+ const outTok = Math.max(0, args.expectedOutputTokens ?? 0);
292
+ // Conservative comparison: unproxied path reads 100% of prompt at the upper
293
+ // tier's cache-read rate, while compressed path pays write rate on the
294
+ // newly imaged/emitted section plus any invalidated downstream suffix, and
295
+ // lower-tier cache-read on kept prefix tokens.
296
+ const unproxiedUsd = (beforeTok * rowBefore.cr + outTok * (rowBefore.out ?? 0)) / 1e6;
297
+ const writeUsd = bandWriteUsdPerMtok(rowAfter, args.ttlSec);
298
+ const compressedUsd = (keptPrefix * rowAfter.cr + (collapsedActual + downstreamCached) * writeUsd + outTok * (rowAfter.out ?? 0)) / 1e6;
299
+ const netSingleTurnUsd = unproxiedUsd - compressedUsd;
300
+ const cliffSavedUsd = (keptPrefix * (rowBefore.cr - rowAfter.cr) + outTok * Math.max(0, (rowBefore.out ?? 0) - (rowAfter.out ?? 0))) / 1e6;
301
+ return {
302
+ crossesCliff: true,
303
+ cliffAt,
304
+ multiplier: rowBefore.in / rowAfter.in,
305
+ inputUsdBefore: rowBefore.in,
306
+ inputUsdAfter: rowAfter.in,
307
+ netSingleTurnUsd,
308
+ cliffSavedUsd,
309
+ };
310
+ }
311
+ /**
312
+ * Exact kosha USD bill for one request's token buckets at its billed prompt band,
313
+ * or undefined in legacy mode or when the model lacks input/output/read rates.
314
+ */
315
+ export function estimateBillUsd(model, args) {
316
+ if (priceMode() === 'legacy')
317
+ return undefined;
318
+ const base = priceRowFor(model);
319
+ if (!base || memoizedEnvPricingOverride(model ?? undefined))
320
+ return undefined;
321
+ const totalPrompt = args.promptTokens ??
322
+ Math.max(0, (args.uncachedTokens || 0) + (args.cachedTokens || 0) + (args.cacheWriteTokens || 0));
323
+ const row = effectiveRow(base, { promptTokens: totalPrompt, at: args.at });
324
+ if (!row || !(row.in > 0))
325
+ return undefined;
326
+ const uncached = Math.max(0, args.uncachedTokens || 0);
327
+ const cached = Math.max(0, args.cachedTokens || 0);
328
+ const write = Math.max(0, args.cacheWriteTokens || 0);
329
+ const output = Math.max(0, args.outputTokens || 0);
330
+ const crRate = typeof row.cr === 'number' ? row.cr : row.in;
331
+ const cwRate = bandWriteUsdPerMtok(row, args.ttlSec);
332
+ const outRate = typeof row.out === 'number' ? row.out : 0;
333
+ return (uncached * row.in + cached * crRate + write * cwRate + output * outRate) / 1e6;
334
+ }
335
+ //# sourceMappingURL=pricing.js.map
@@ -0,0 +1,30 @@
1
+ import type { GptHistoryProfile, GptRenderStyle } from './gpt-model-profiles.js';
2
+ /**
3
+ * Shared defaults for the built-in profile tables.
4
+ *
5
+ * These live outside gpt-model-profiles.ts so per-provider profile files
6
+ * (claude-model-profiles.ts, gemini-model-profiles.ts) can reuse them: those
7
+ * files are imported BY gpt-model-profiles.ts, so importing the constants back
8
+ * out of it would be a cycle, and the profiles are top-level consts, so the
9
+ * cycle would be a load-time TDZ crash rather than a lint warning.
10
+ */
11
+ /**
12
+ * Conservative list-price ratios for families inkling has not priced explicitly.
13
+ * Deliberately mid-range: an unknown model must not be reported at the most
14
+ * favourable (gpt-5) cache discount, and must not be priced at Anthropic's.
15
+ */
16
+ export declare const BASE_PRICING: {
17
+ /** cached input ÷ uncached input */
18
+ cacheReadRate: number;
19
+ /** output ÷ uncached input */
20
+ outputRate: number;
21
+ };
22
+ export declare const BASE_STYLE: GptRenderStyle;
23
+ export declare const BASE_HISTORY: GptHistoryProfile;
24
+ /** Shared history policy for every native-14px profile (Sol, Grok, Qwen).
25
+ * 14px packs ~3× fewer chars/page than 5×8, so a 6-turn tail + 1000-token
26
+ * floor + pairs planner leaves most of a completions chat as text (~0.3%
27
+ * saved on grok-4.6). Mixed + 1-turn tail + no token floor is what actually
28
+ * images that bulk. Sol keeps a higher maxImages because its pages are taller. */
29
+ export declare const NATIVE_14PX_HISTORY: GptHistoryProfile;
30
+ //# sourceMappingURL=profile-base.d.ts.map
@@ -0,0 +1,67 @@
1
+ import { DEFAULT_RENDER_FONT } from './render.js';
2
+ /**
3
+ * Shared defaults for the built-in profile tables.
4
+ *
5
+ * These live outside gpt-model-profiles.ts so per-provider profile files
6
+ * (claude-model-profiles.ts, gemini-model-profiles.ts) can reuse them: those
7
+ * files are imported BY gpt-model-profiles.ts, so importing the constants back
8
+ * out of it would be a cycle, and the profiles are top-level consts, so the
9
+ * cycle would be a load-time TDZ crash rather than a lint warning.
10
+ */
11
+ /**
12
+ * Conservative list-price ratios for families inkling has not priced explicitly.
13
+ * Deliberately mid-range: an unknown model must not be reported at the most
14
+ * favourable (gpt-5) cache discount, and must not be priced at Anthropic's.
15
+ */
16
+ export const BASE_PRICING = {
17
+ /** cached input ÷ uncached input */
18
+ cacheReadRate: 0.5,
19
+ /** output ÷ uncached input */
20
+ outputRate: 4,
21
+ };
22
+ export const BASE_STYLE = {
23
+ font: DEFAULT_RENDER_FONT,
24
+ cellWBonus: 0,
25
+ cellHBonus: 0,
26
+ aa: true,
27
+ grid: false,
28
+ gridCols: 0,
29
+ colorCycle: false,
30
+ markerScale: 1,
31
+ markerRed: false,
32
+ inkDilate: 0,
33
+ };
34
+ export const BASE_HISTORY = {
35
+ // Not a provider limit — no vendor documents a per-request image count we come
36
+ // near. This is our own latency budget: vision latency grows with physical image
37
+ // count/bytes, not just billed tokens, and long OpenCode sessions can turn old
38
+ // history into 80+ images — token-cheap but slow enough that the model times out
39
+ // before first token. When the cap trips, callers leave the old history as text
40
+ // rather than dropping or de-prioritizing it, so tripping it is never lossy.
41
+ maxImages: 32,
42
+ keepTail: 6,
43
+ keepRecentPairs: 6,
44
+ minCollapseTokens: 2000,
45
+ responsesMode: 'pairs',
46
+ framing: 'full',
47
+ factSheetScope: 'per-segment',
48
+ };
49
+ /** Shared history policy for every native-14px profile (Sol, Grok, Qwen).
50
+ * 14px packs ~3× fewer chars/page than 5×8, so a 6-turn tail + 1000-token
51
+ * floor + pairs planner leaves most of a completions chat as text (~0.3%
52
+ * saved on grok-4.6). Mixed + 1-turn tail + no token floor is what actually
53
+ * images that bulk. Sol keeps a higher maxImages because its pages are taller. */
54
+ export const NATIVE_14PX_HISTORY = {
55
+ ...BASE_HISTORY,
56
+ maxImages: 32,
57
+ keepTail: 1,
58
+ keepRecentPairs: 1,
59
+ minCollapseTokens: 0,
60
+ minCollapsePrefix: 1,
61
+ collapseChunk: 1,
62
+ freezeChunk: 1,
63
+ responsesMode: 'mixed',
64
+ framing: 'compact',
65
+ factSheetScope: 'combined',
66
+ };
67
+ //# sourceMappingURL=profile-base.js.map
@@ -0,0 +1,51 @@
1
+ import { type ProxyConfig, type ProxyEvent } from './proxy.js';
2
+ export type ProviderProtocol = 'anthropic' | 'openai' | 'google';
3
+ export interface ProviderRouteDefinition {
4
+ /** Stable route id used in `/providers/<id>/...`. */
5
+ id: string;
6
+ /** Wire protocol accepted by the configured upstream. */
7
+ protocol: ProviderProtocol;
8
+ /** Existing proxy configuration for this provider. Kept in memory only. */
9
+ proxy: ProxyConfig;
10
+ }
11
+ export interface ProviderRouterConfig {
12
+ /** Handles legacy unprefixed routes such as `/v1/messages`. */
13
+ defaultProxy: ProxyConfig;
14
+ /** Explicitly addressable providers. */
15
+ providers: readonly ProviderRouteDefinition[];
16
+ /** Optional observer invoked after the provider-specific observer. */
17
+ onRequest?: (providerId: string, event: ProxyEvent) => void | Promise<void>;
18
+ }
19
+ export interface ParsedProviderRoute {
20
+ providerId: string;
21
+ upstreamPath: string;
22
+ }
23
+ export interface ProviderRouterInspection {
24
+ defaultRoute: 'legacy';
25
+ providers: Array<{
26
+ id: string;
27
+ protocol: ProviderProtocol;
28
+ prefix: string;
29
+ }>;
30
+ }
31
+ export declare function assertProviderId(id: string): void;
32
+ /**
33
+ * Parse an explicit provider-prefixed request path.
34
+ *
35
+ * The provider id is never accepted from a header, query string or body. This
36
+ * keeps routing metadata outside the model payload and prevents an untrusted
37
+ * client from overriding upstream selection through a forwarded header.
38
+ */
39
+ export declare function parseProviderRoute(pathname: string): ParsedProviderRoute | null;
40
+ /**
41
+ * Create one request handler that multiplexes several provider-specific
42
+ * `createProxy` instances behind one Web-standard request handler.
43
+ *
44
+ * Legacy paths continue through `defaultProxy`. Explicit provider paths use:
45
+ *
46
+ * /providers/<provider-id>/<upstream-path>
47
+ */
48
+ export declare function createProviderRouter(config: ProviderRouterConfig): ((request: Request) => Promise<Response>) & {
49
+ inspect(): ProviderRouterInspection;
50
+ };
51
+ //# sourceMappingURL=provider-router.d.ts.map
@@ -0,0 +1,121 @@
1
+ import { createProxy } from './proxy.js';
2
+ const PROVIDER_ID = /^[a-z][a-z0-9-]{0,62}$/;
3
+ const PROVIDER_ROOT = '/providers';
4
+ const PREFIX = `${PROVIDER_ROOT}/`;
5
+ export function assertProviderId(id) {
6
+ if (!PROVIDER_ID.test(id)) {
7
+ throw new Error(`invalid provider id ${JSON.stringify(id)}; expected lowercase letters, digits and dashes`);
8
+ }
9
+ }
10
+ /**
11
+ * Parse an explicit provider-prefixed request path.
12
+ *
13
+ * The provider id is never accepted from a header, query string or body. This
14
+ * keeps routing metadata outside the model payload and prevents an untrusted
15
+ * client from overriding upstream selection through a forwarded header.
16
+ */
17
+ export function parseProviderRoute(pathname) {
18
+ if (!pathname.startsWith(PREFIX))
19
+ return null;
20
+ const remainder = pathname.slice(PREFIX.length);
21
+ const slash = remainder.indexOf('/');
22
+ if (slash <= 0)
23
+ return null;
24
+ const providerId = remainder.slice(0, slash);
25
+ if (!PROVIDER_ID.test(providerId))
26
+ return null;
27
+ const upstreamPath = remainder.slice(slash);
28
+ if (!upstreamPath.startsWith('/') || upstreamPath.startsWith('//'))
29
+ return null;
30
+ return { providerId, upstreamPath };
31
+ }
32
+ function isProviderNamespace(pathname) {
33
+ return pathname === PROVIDER_ROOT || pathname.startsWith(PREFIX);
34
+ }
35
+ function wrapProviderObserver(definition, routerObserver) {
36
+ const providerObserver = definition.proxy.onRequest;
37
+ return {
38
+ ...definition.proxy,
39
+ onRequest: async (event) => {
40
+ await providerObserver?.(event);
41
+ await routerObserver?.(definition.id, event);
42
+ },
43
+ };
44
+ }
45
+ function rewriteProviderRequest(request, route) {
46
+ const sourceUrl = new URL(request.url);
47
+ sourceUrl.pathname = route.upstreamPath;
48
+ const bodyAllowed = request.method !== 'GET' && request.method !== 'HEAD';
49
+ const init = {
50
+ method: request.method,
51
+ headers: new Headers(request.headers),
52
+ body: bodyAllowed ? request.body : undefined,
53
+ redirect: request.redirect,
54
+ signal: request.signal,
55
+ };
56
+ if (request.body)
57
+ init.duplex = 'half';
58
+ // The body stream is forwarded without decoding or re-encoding it. Tool
59
+ // schemas, prompts, binary parts and structured-output contracts remain
60
+ // untouched until the selected provider's normal transform pipeline runs.
61
+ return new Request(sourceUrl, init);
62
+ }
63
+ function invalidProviderRoute() {
64
+ return new Response(JSON.stringify({ error: 'invalid_provider_route' }), {
65
+ status: 400,
66
+ headers: { 'content-type': 'application/json' },
67
+ });
68
+ }
69
+ /**
70
+ * Create one request handler that multiplexes several provider-specific
71
+ * `createProxy` instances behind one Web-standard request handler.
72
+ *
73
+ * Legacy paths continue through `defaultProxy`. Explicit provider paths use:
74
+ *
75
+ * /providers/<provider-id>/<upstream-path>
76
+ */
77
+ export function createProviderRouter(config) {
78
+ const defaultHandler = createProxy(config.defaultProxy);
79
+ const handlers = new Map();
80
+ const definitions = new Map();
81
+ for (const definition of config.providers) {
82
+ assertProviderId(definition.id);
83
+ if (definitions.has(definition.id)) {
84
+ throw new Error(`duplicate provider id: ${definition.id}`);
85
+ }
86
+ definitions.set(definition.id, definition);
87
+ handlers.set(definition.id, createProxy(wrapProviderObserver(definition, config.onRequest)));
88
+ }
89
+ const route = async (request) => {
90
+ const pathname = new URL(request.url).pathname;
91
+ const parsed = parseProviderRoute(pathname);
92
+ // `/providers` is a reserved internal namespace. Malformed explicit routes
93
+ // must never fall through to the legacy/default upstream.
94
+ if (!parsed)
95
+ return isProviderNamespace(pathname) ? invalidProviderRoute() : defaultHandler(request);
96
+ const handler = handlers.get(parsed.providerId);
97
+ if (!handler) {
98
+ return new Response(JSON.stringify({
99
+ error: 'unknown_provider',
100
+ provider: parsed.providerId,
101
+ }), {
102
+ status: 404,
103
+ headers: { 'content-type': 'application/json' },
104
+ });
105
+ }
106
+ return handler(rewriteProviderRequest(request, parsed));
107
+ };
108
+ return Object.assign(route, {
109
+ inspect() {
110
+ return {
111
+ defaultRoute: 'legacy',
112
+ providers: [...definitions.values()].map((definition) => ({
113
+ id: definition.id,
114
+ protocol: definition.protocol,
115
+ prefix: `${PREFIX}${definition.id}`,
116
+ })),
117
+ };
118
+ },
119
+ });
120
+ }
121
+ //# sourceMappingURL=provider-router.js.map