@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,121 @@
1
+ /**
2
+ * Cache-aware baseline math for the unproxied counterfactual.
3
+ * Workers-safe: no node:, no Buffer, no process.*. Pure number math.
4
+ * See docs/CACHING_AND_SAVINGS.md for the full derivation and audit history.
5
+ */
6
+ /** Documented Anthropic price ratios: cc_5m = 1.25×, cc_1h = 2×, cr = 0.1× base input. */
7
+ export declare const CACHE_CREATE_RATE = 1.25;
8
+ export declare const CACHE_READ_RATE = 0.1;
9
+ /** Anthropic prompt-cache TTL (seconds). A same-prefix prior that completed
10
+ * within this window makes the text counterfactual warm even when the actual
11
+ * request reports cr === 0 (see deriveBaselineWarmth). */
12
+ export declare const CACHE_TTL_SEC = 300;
13
+ /** The 1-hour cache tier's TTL (seconds). Claude Code writes its main thread,
14
+ * and with `subagentPromptCacheTtl: "1h"` its subagents too, at this tier. */
15
+ export declare const CACHE_TTL_1H_SEC = 3600;
16
+ /**
17
+ * TTL a session's cached prefix lives for, as last observed. Any 1-hour write
18
+ * proves the caller marks its prefix with `ttl: "1h"`, and that stays true for
19
+ * the session: later rows that only read, or only append 5-minute blocks after
20
+ * the 1h prefix, do not shorten the prefix's life. Sticky on purpose. Longer
21
+ * is the conservative side for savings, since it lets more self-busts count
22
+ * against inkling.
23
+ */
24
+ export declare function observedCacheTtlSec(cc1h: number | undefined, prevTtlSec: number | undefined): number;
25
+ /** This session's previous usage-bearing turn, used only for warm split sizing. */
26
+ export interface BaselineWarmthPrev {
27
+ /** Completion time of that turn, in wall-clock seconds. */
28
+ ts: number;
29
+ /** Cacheable-prefix tokens measured that turn (0 if the probe missed). */
30
+ cacheable: number;
31
+ /** Hash of the image-bound/static text prefix. If it changes, do not reuse the
32
+ * prior prefix size for this row's text reused/grown split. */
33
+ prefixSha?: string;
34
+ /** cache_prefix_tools_sha8 of that turn. A changed tool list busts the text
35
+ * prefix too; missing on either side is treated as unknown (don't care). */
36
+ toolsSha?: string;
37
+ /** cache_prefix_sha8 inkling actually sent (post-transform). */
38
+ pxPrefixSha?: string;
39
+ /** Model of that turn; prompt cache does not cross models. */
40
+ model?: string;
41
+ /** Cache TTL the session's prefix was observed at (see observedCacheTtlSec).
42
+ * When set, it replaces the caller's default `ttlSec`. */
43
+ ttlSec?: number;
44
+ }
45
+ /**
46
+ * Decide whether the TEXT counterfactual's prefix was warm this turn.
47
+ *
48
+ * The text path is warm when either:
49
+ * - this session has a prior row that completed less than `ttlSec` before
50
+ * this request started, with the same `system_sha8` (both known) and the
51
+ * same tools hash (or either unknown). The text request would have read
52
+ * that prefix from cache even if the image path missed — inkling busting its
53
+ * own cache is a real cost of inkling, not something text would have paid;
54
+ * - or the actual request reports `cr > 0`, which is server proof of a warm read.
55
+ *
56
+ * Otherwise the text baseline is priced cold. When warm, reused =
57
+ * min(prevCacheable, cacheable); without a usable prior, cr-only warmth assumes
58
+ * full reuse of this turn's cacheable prefix, which is conservative for savings.
59
+ *
60
+ * @param prev this session's previous usage-bearing turn, or undefined.
61
+ * @param nowSec request-start wall-clock seconds, used only to reject prior
62
+ * rows that had not completed before this request was sent.
63
+ * @param cacheable this turn's cacheable-prefix tokens (the full-reuse credit
64
+ * when warm only via cr, since cr proves a read but not the split).
65
+ * @param cr observed cache-read tokens this turn.
66
+ * @param ttlSec how recently a prior must have completed to count as fresh,
67
+ * when the prior carries no observed tier (`prev.ttlSec`).
68
+ * @param prefixSha system_sha8 of this row. Must match the prior's for a
69
+ * cr === 0 row to be warm.
70
+ * @param toolsSha cache_prefix_tools_sha8 of this row; a mismatch keeps the row cold.
71
+ */
72
+ export declare function deriveBaselineWarmth(prev: BaselineWarmthPrev | undefined, nowSec: number, cacheable: number, cr: number, ttlSec?: number, prefixSha?: string, toolsSha?: string, opts?: {
73
+ pxPrefixSha?: string;
74
+ model?: string;
75
+ }): {
76
+ warm: boolean;
77
+ prevCacheable: number;
78
+ };
79
+ /**
80
+ * Weighted input cost for the unproxied TEXT counterfactual (see docs/CACHING_AND_SAVINGS.md).
81
+ *
82
+ * Warmth matters: a TEXT prefix is only a cheap cache-read when a warm cache
83
+ * actually existed this turn. The previous warmth-FREE version always priced
84
+ * the cacheable prefix at CACHE_READ_RATE, which fabricated a "free read" on
85
+ * cold/TTL-expiry turns where text would in fact have paid a 1.25× create —
86
+ * that produced a phantom loss vs the imaged path (which DOES pay the create).
87
+ *
88
+ * cold turn (first turn / >5min since this session's last turn):
89
+ * text has no warm cache either ⇒ cacheable×CACHE_CREATE_RATE + coldTail×1.0
90
+ * warm turn (a prior turn cached the prefix within TTL):
91
+ * text append-caches ⇒ reused×CACHE_READ_RATE + grown×CACHE_CREATE_RATE + coldTail×1.0
92
+ * where reused = min(prevCacheable, cacheable), grown = cacheable − reused.
93
+ * This is what TEXT pays regardless of whether inkling's image busted its
94
+ * own cache on a growth turn — so the real growth loss is preserved.
95
+ *
96
+ * Saving = baseline_eff − actual_eff; can be negative (honestly reported, not floored).
97
+ *
98
+ * @param baselineCacheable tokens up to the last cache_control marker. ≤0 ⇒ credit nothing.
99
+ * @param warm was a warm cache available for this session this turn?
100
+ * @param prevCacheable cacheable prefix size on this session's previous turn (warm only).
101
+ */
102
+ export declare function computeBaselineInputEff(baseline: number, baselineCacheable: number, inputTokens: number, cc: number, cr: number, warm?: boolean, prevCacheable?: number): number;
103
+ /** Tier-aware variant for internal savings accounting. */
104
+ export declare function computeBaselineInputEffWithCacheTier(baseline: number, baselineCacheable: number, inputTokens: number, cc: number, cr: number, warm: boolean, prevCacheable: number, cacheCreate1hTokens: number, cacheCreate5mTokens?: number, readRate?: number): number;
105
+ /** Weighted input cost inkling actually paid this turn. */
106
+ export declare function computeActualInputEff(inputTokens: number, cc: number, cr: number): number;
107
+ /** Tier-aware variant for internal savings accounting. */
108
+ export declare function computeActualInputEffWithCacheTier(inputTokens: number, cc: number, cr: number, cacheCreate1hTokens: number, cacheCreate5mTokens?: number, readRate?: number): number;
109
+ /**
110
+ * Validate that an Anthropic `count_tokens` baseline probe represents a usable
111
+ * full-request baseline rather than a rejected/partial probe or a server-side
112
+ * `thread_continue` delta probe (which only probes the incremental delta while
113
+ * Anthropic expands the full cached thread in usage).
114
+ */
115
+ export declare function isUsableAnthropicBaselineProbe(args: {
116
+ baselineTokens: number | undefined;
117
+ probeStatus: string | undefined;
118
+ threadContinue?: boolean;
119
+ cacheReadTokens: number;
120
+ }): boolean;
121
+ //# sourceMappingURL=baseline.d.ts.map
@@ -0,0 +1,200 @@
1
+ /**
2
+ * Cache-aware baseline math for the unproxied counterfactual.
3
+ * Workers-safe: no node:, no Buffer, no process.*. Pure number math.
4
+ * See docs/CACHING_AND_SAVINGS.md for the full derivation and audit history.
5
+ */
6
+ /** Documented Anthropic price ratios: cc_5m = 1.25×, cc_1h = 2×, cr = 0.1× base input. */
7
+ export const CACHE_CREATE_RATE = 1.25;
8
+ const CACHE_CREATE_1H_RATE = 2.0;
9
+ export const CACHE_READ_RATE = 0.1;
10
+ /** Effective cache-write rate for this request. Older usage payloads do not
11
+ * expose the tier split; preserve the historical/conservative 5-minute rate
12
+ * in that case. The text counterfactual uses the same observed tier mix as
13
+ * the transformed request because inkling relocates, rather than invents, the
14
+ * caller's cache-control markers. */
15
+ function cacheCreateRate(cc, cc5m, cc1h) {
16
+ if (!(cc > 0))
17
+ return CACHE_CREATE_RATE;
18
+ const splitReported = cc5m !== undefined || cc1h !== undefined;
19
+ if (!splitReported)
20
+ return CACHE_CREATE_RATE;
21
+ const fiveMinute = Math.max(0, cc5m ?? 0);
22
+ const oneHour = Math.max(0, cc1h ?? 0);
23
+ const splitTotal = fiveMinute + oneHour;
24
+ if (!(splitTotal > 0))
25
+ return CACHE_CREATE_RATE;
26
+ // The API contract says splitTotal === cc. Normalize malformed/mismatched
27
+ // payloads to the aggregate so accounting never invents extra write tokens.
28
+ return (fiveMinute * CACHE_CREATE_RATE + oneHour * CACHE_CREATE_1H_RATE) / splitTotal;
29
+ }
30
+ /** Anthropic prompt-cache TTL (seconds). A same-prefix prior that completed
31
+ * within this window makes the text counterfactual warm even when the actual
32
+ * request reports cr === 0 (see deriveBaselineWarmth). */
33
+ export const CACHE_TTL_SEC = 300;
34
+ /** The 1-hour cache tier's TTL (seconds). Claude Code writes its main thread,
35
+ * and with `subagentPromptCacheTtl: "1h"` its subagents too, at this tier. */
36
+ export const CACHE_TTL_1H_SEC = 3600;
37
+ /**
38
+ * TTL a session's cached prefix lives for, as last observed. Any 1-hour write
39
+ * proves the caller marks its prefix with `ttl: "1h"`, and that stays true for
40
+ * the session: later rows that only read, or only append 5-minute blocks after
41
+ * the 1h prefix, do not shorten the prefix's life. Sticky on purpose. Longer
42
+ * is the conservative side for savings, since it lets more self-busts count
43
+ * against inkling.
44
+ */
45
+ export function observedCacheTtlSec(cc1h, prevTtlSec) {
46
+ if ((cc1h ?? 0) > 0)
47
+ return CACHE_TTL_1H_SEC;
48
+ return prevTtlSec ?? CACHE_TTL_SEC;
49
+ }
50
+ /**
51
+ * Decide whether the TEXT counterfactual's prefix was warm this turn.
52
+ *
53
+ * The text path is warm when either:
54
+ * - this session has a prior row that completed less than `ttlSec` before
55
+ * this request started, with the same `system_sha8` (both known) and the
56
+ * same tools hash (or either unknown). The text request would have read
57
+ * that prefix from cache even if the image path missed — inkling busting its
58
+ * own cache is a real cost of inkling, not something text would have paid;
59
+ * - or the actual request reports `cr > 0`, which is server proof of a warm read.
60
+ *
61
+ * Otherwise the text baseline is priced cold. When warm, reused =
62
+ * min(prevCacheable, cacheable); without a usable prior, cr-only warmth assumes
63
+ * full reuse of this turn's cacheable prefix, which is conservative for savings.
64
+ *
65
+ * @param prev this session's previous usage-bearing turn, or undefined.
66
+ * @param nowSec request-start wall-clock seconds, used only to reject prior
67
+ * rows that had not completed before this request was sent.
68
+ * @param cacheable this turn's cacheable-prefix tokens (the full-reuse credit
69
+ * when warm only via cr, since cr proves a read but not the split).
70
+ * @param cr observed cache-read tokens this turn.
71
+ * @param ttlSec how recently a prior must have completed to count as fresh,
72
+ * when the prior carries no observed tier (`prev.ttlSec`).
73
+ * @param prefixSha system_sha8 of this row. Must match the prior's for a
74
+ * cr === 0 row to be warm.
75
+ * @param toolsSha cache_prefix_tools_sha8 of this row; a mismatch keeps the row cold.
76
+ */
77
+ export function deriveBaselineWarmth(prev, nowSec, cacheable, cr, ttlSec = CACHE_TTL_SEC, prefixSha, toolsSha, opts) {
78
+ const age = prev !== undefined ? nowSec - prev.ts : Number.POSITIVE_INFINITY;
79
+ const samePrefix = prev === undefined
80
+ || prev.prefixSha === undefined
81
+ || prefixSha === undefined
82
+ || prev.prefixSha === prefixSha;
83
+ // cr is the only warm/cold signal. A prior only refines the warm split.
84
+ const window = prev?.ttlSec !== undefined && prev.ttlSec > 0 ? prev.ttlSec : ttlSec;
85
+ const fresh = prev !== undefined && age >= 0 && age < window;
86
+ const sameTools = prev === undefined
87
+ || prev.toolsSha === undefined
88
+ || toolsSha === undefined
89
+ || prev.toolsSha === toolsSha;
90
+ // A same-prefix prior that completed inside the TTL means the TEXT request
91
+ // would have found its own prefix cached, even when the image path missed
92
+ // (cr === 0 because inkling re-rendered and busted its own cache). Requires a
93
+ // positive system match — an unknown system hash can't vouch for the prefix.
94
+ const provenSystem = prev !== undefined
95
+ && prev.prefixSha !== undefined
96
+ && prefixSha !== undefined
97
+ && prev.prefixSha === prefixSha;
98
+ if (!(cr > 0)) {
99
+ // Self-bust exception: only when inkling PROVABLY changed what it sent.
100
+ // - prompt cache is per model: a model switch means text would miss too;
101
+ // - the outgoing cache_prefix_sha8 must differ from the prior's. If inkling
102
+ // sent the same prefix and still got cr === 0, the server evicted it and
103
+ // text would have missed as well — not inkling's fault, not text's gain.
104
+ const sameModel = prev?.model !== undefined
105
+ && opts?.model !== undefined
106
+ && prev.model === opts.model;
107
+ const inklingBusted = prev?.pxPrefixSha !== undefined
108
+ && opts?.pxPrefixSha !== undefined
109
+ && prev.pxPrefixSha !== opts.pxPrefixSha;
110
+ if (fresh && provenSystem && sameTools && sameModel && inklingBusted) {
111
+ return { warm: true, prevCacheable: prev.cacheable };
112
+ }
113
+ return { warm: false, prevCacheable: 0 };
114
+ }
115
+ // cr proves warmth. A fresh same-prefix prior gives the real reused/grown
116
+ // split; without one, assume full reuse (conservative for savings).
117
+ // (Unchanged from 0.15.0: tools hash does not gate the split.)
118
+ const freshPrior = fresh && samePrefix;
119
+ return { warm: true, prevCacheable: freshPrior ? prev.cacheable : cacheable };
120
+ }
121
+ /**
122
+ * Weighted input cost for the unproxied TEXT counterfactual (see docs/CACHING_AND_SAVINGS.md).
123
+ *
124
+ * Warmth matters: a TEXT prefix is only a cheap cache-read when a warm cache
125
+ * actually existed this turn. The previous warmth-FREE version always priced
126
+ * the cacheable prefix at CACHE_READ_RATE, which fabricated a "free read" on
127
+ * cold/TTL-expiry turns where text would in fact have paid a 1.25× create —
128
+ * that produced a phantom loss vs the imaged path (which DOES pay the create).
129
+ *
130
+ * cold turn (first turn / >5min since this session's last turn):
131
+ * text has no warm cache either ⇒ cacheable×CACHE_CREATE_RATE + coldTail×1.0
132
+ * warm turn (a prior turn cached the prefix within TTL):
133
+ * text append-caches ⇒ reused×CACHE_READ_RATE + grown×CACHE_CREATE_RATE + coldTail×1.0
134
+ * where reused = min(prevCacheable, cacheable), grown = cacheable − reused.
135
+ * This is what TEXT pays regardless of whether inkling's image busted its
136
+ * own cache on a growth turn — so the real growth loss is preserved.
137
+ *
138
+ * Saving = baseline_eff − actual_eff; can be negative (honestly reported, not floored).
139
+ *
140
+ * @param baselineCacheable tokens up to the last cache_control marker. ≤0 ⇒ credit nothing.
141
+ * @param warm was a warm cache available for this session this turn?
142
+ * @param prevCacheable cacheable prefix size on this session's previous turn (warm only).
143
+ */
144
+ export function computeBaselineInputEff(baseline, baselineCacheable, inputTokens, cc, cr, warm = false, prevCacheable = 0) {
145
+ return computeBaselineInputEffWithCacheTier(baseline, baselineCacheable, inputTokens, cc, cr, warm, prevCacheable, 0);
146
+ }
147
+ /** Tier-aware variant for internal savings accounting. */
148
+ export function computeBaselineInputEffWithCacheTier(baseline, baselineCacheable, inputTokens, cc, cr, warm, prevCacheable, cacheCreate1hTokens, cacheCreate5mTokens, readRate = CACHE_READ_RATE) {
149
+ if (baseline <= 0)
150
+ return 0;
151
+ // Probe miss: can't split prefix from tail, so credit nothing (same as actual).
152
+ if (baselineCacheable <= 0) {
153
+ return computeActualInputEffWithCacheTier(inputTokens, cc, cr, cacheCreate1hTokens, cacheCreate5mTokens, readRate);
154
+ }
155
+ const cacheable = Math.min(baselineCacheable, baseline);
156
+ const coldTail = baseline - cacheable;
157
+ const createRate = cacheCreateRate(cc, cacheCreate5mTokens, cacheCreate1hTokens);
158
+ if (warm) {
159
+ // Text reads the prefix it already had cached (0.10×) and creates only the
160
+ // growth since last turn (at the observed write-tier rate). Independent of
161
+ // the image path's cache.
162
+ const reused = Math.min(Math.max(prevCacheable, 0), cacheable);
163
+ const grown = cacheable - reused;
164
+ return reused * readRate + grown * createRate + coldTail * 1.0;
165
+ }
166
+ // Cold (first turn / TTL expiry): no warm cache for text either, so it
167
+ // re-creates the whole cacheable prefix at the create rate — same event the
168
+ // imaged path pays. Removes the phantom "free read" that fabricated a loss.
169
+ return cacheable * createRate + coldTail * 1.0;
170
+ }
171
+ /** Weighted input cost inkling actually paid this turn. */
172
+ export function computeActualInputEff(inputTokens, cc, cr) {
173
+ return computeActualInputEffWithCacheTier(inputTokens, cc, cr, 0);
174
+ }
175
+ /** Tier-aware variant for internal savings accounting. */
176
+ export function computeActualInputEffWithCacheTier(inputTokens, cc, cr, cacheCreate1hTokens, cacheCreate5mTokens, readRate = CACHE_READ_RATE) {
177
+ return inputTokens
178
+ + cc * cacheCreateRate(cc, cacheCreate5mTokens, cacheCreate1hTokens)
179
+ + cr * readRate;
180
+ }
181
+ /**
182
+ * Validate that an Anthropic `count_tokens` baseline probe represents a usable
183
+ * full-request baseline rather than a rejected/partial probe or a server-side
184
+ * `thread_continue` delta probe (which only probes the incremental delta while
185
+ * Anthropic expands the full cached thread in usage).
186
+ */
187
+ export function isUsableAnthropicBaselineProbe(args) {
188
+ const { baselineTokens, probeStatus, threadContinue, cacheReadTokens } = args;
189
+ if (baselineTokens === undefined || !Number.isFinite(baselineTokens) || !(baselineTokens > 0)) {
190
+ return false;
191
+ }
192
+ if (threadContinue === true)
193
+ return false;
194
+ if (probeStatus !== undefined && probeStatus !== 'ok')
195
+ return false;
196
+ if (cacheReadTokens > 2000 && baselineTokens < cacheReadTokens * 0.5)
197
+ return false;
198
+ return true;
199
+ }
200
+ //# sourceMappingURL=baseline.js.map
@@ -0,0 +1,86 @@
1
+ /**
2
+ * Model vision calibration probe generator, deterministic scorer, and
3
+ * normalized in-memory profile registry.
4
+ *
5
+ * Pure Core: ZERO `node:` imports, ZERO wall-clock or random calls in
6
+ * deterministic transforms.
7
+ */
8
+ import { type RenderedImage, type RenderFont } from './render.js';
9
+ import type { GptModelProfile } from './gpt-model-profiles.js';
10
+ export type CalibrationBand = 'spleen-5x8' | 'spleen-5x10' | 'jetbrains-mono-12' | 'jetbrains-mono-14' | 'text-only';
11
+ export type ImageCalibrationBand = Exclude<CalibrationBand, 'text-only'>;
12
+ export interface CalibrationScores {
13
+ hexScore: number;
14
+ codeScore: number;
15
+ numScore: number;
16
+ guardScore: number;
17
+ overallScore: number;
18
+ passed: boolean;
19
+ }
20
+ export interface CalibratedModelProfile {
21
+ model: string;
22
+ band: CalibrationBand;
23
+ cols: number;
24
+ maxHeightPx: number;
25
+ calibratedAtIso: string;
26
+ scores: CalibrationScores;
27
+ source: 'probe' | 'manual';
28
+ }
29
+ export interface CalibrationProbe {
30
+ band: CalibrationBand;
31
+ cols: number;
32
+ maxHeightPx: number;
33
+ prompt: string;
34
+ renderedText: string;
35
+ pngs: RenderedImage[];
36
+ expectedHex: string[];
37
+ expectedCode: string[];
38
+ expectedNums: string[];
39
+ forbiddenGuards: string[];
40
+ }
41
+ export interface CalibrationBandGeometry {
42
+ readonly band: ImageCalibrationBand;
43
+ readonly font: RenderFont;
44
+ readonly cols: number;
45
+ readonly cellWBonus: number;
46
+ readonly cellHBonus: number;
47
+ readonly maxHeightPx: number;
48
+ }
49
+ /** Candidate image bands ordered from densest (highest savings) to largest glyphs. */
50
+ export declare const CALIBRATION_BAND_ORDER: readonly ImageCalibrationBand[];
51
+ export declare function isImageCalibrationBand(band: unknown): band is ImageCalibrationBand;
52
+ export declare function isCalibrationBand(band: unknown): band is CalibrationBand;
53
+ export declare function getCalibrationBandGeometry(band: ImageCalibrationBand): CalibrationBandGeometry;
54
+ /**
55
+ * Derive a {@link GptModelProfile} configured for a calibrated {@link CalibrationBand}
56
+ * while preserving the base profile's provider billing/cache/history semantics.
57
+ */
58
+ export declare function calibratedBandToProfile(band: CalibrationBand, baseProfile: GptModelProfile, overrides?: {
59
+ cols?: number;
60
+ maxHeightPx?: number;
61
+ }): GptModelProfile;
62
+ export declare function buildCalibrationProbe(band: ImageCalibrationBand): Promise<CalibrationProbe>;
63
+ export declare function scoreCalibrationResponse(responseText: string, probe: CalibrationProbe): CalibrationScores;
64
+ /**
65
+ * Normalize a model id for calibration registry lookup:
66
+ * lowercase, strip `[1m]`-style bracketed variant tags, and strip gateway `vendor/` prefixes.
67
+ */
68
+ export declare function normalizeCalibratedModelId(model: string | null | undefined): string;
69
+ export declare function setCalibratedProfile(profile: CalibratedModelProfile): void;
70
+ export declare function removeCalibratedProfile(model: string): boolean;
71
+ export interface CalibratedProfileMatch {
72
+ readonly profile: CalibratedModelProfile;
73
+ readonly exact: boolean;
74
+ }
75
+ export declare function getCalibratedProfileMatch(model: string | null | undefined): CalibratedProfileMatch | undefined;
76
+ export declare function getCalibratedProfile(model: string | null | undefined): CalibratedModelProfile | undefined;
77
+ export declare function listCalibratedProfiles(): CalibratedModelProfile[];
78
+ export declare function clearCalibratedProfiles(): void;
79
+ export declare function serializeCalibratedProfiles(): string;
80
+ /**
81
+ * Restore calibrated profiles from serialized JSON using fail-closed validation.
82
+ * Corrupt JSON, mismatched format tags, or malformed profile entries are rejected/skipped.
83
+ * Returns the number of valid profiles restored.
84
+ */
85
+ export declare function restoreCalibratedProfiles(json: string): number;
86
+ //# sourceMappingURL=calibration.d.ts.map