@sriinnu/fiche 0.18.0-bootstrap.0 → 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 +289 -0
  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 +115 -3
  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,29 @@
1
+ /**
2
+ * Shared JSON-Schema annotation stripper for BOTH transformer paths
3
+ * (Anthropic/Claude in transform.ts and OpenAI/GPT in openai.ts).
4
+ *
5
+ * The whole point of this module is that the strip is *structure-aware*: the
6
+ * literal key `description` (also `title`, `default`, `examples`) is a schema
7
+ * ANNOTATION in one place and a user-defined PROPERTY NAME in another. The
8
+ * `task` tool, for example, has a required parameter literally named
9
+ * `description`. A naive "drop every key called description" walk deletes that
10
+ * property, leaving `required: ["description"]` pointing at nothing — the model
11
+ * then can't emit it and the host rejects the tool call ("Missing key at
12
+ * [\"description\"]"). So we only strip annotation keywords at the schema-node
13
+ * level and recurse into the *values* of `properties`/`$defs`/etc., never
14
+ * treating their keys as annotations.
15
+ */
16
+ /** Strip long-form metadata from a JSON Schema node, preserving the structural
17
+ * keys a tool-use validator needs. Strips: description, title, examples,
18
+ * default, $id, $comment, long format. Recurses into
19
+ * properties/oneOf/anyOf/allOf/items etc. Returns a fresh object — never
20
+ * mutates the input. Property *names* (the keys inside `properties` and
21
+ * friends) are preserved even when they collide with annotation keywords. */
22
+ export declare function stripSchemaDescriptions(node: unknown, depth?: number): unknown;
23
+ /** JSON Schema keys that carry a parameter *contract* (shape/values), as opposed
24
+ * to pure annotations. Used to decide whether a stripped schema still tells the
25
+ * validator anything — if none survive, the strip is not worth shipping. */
26
+ export declare const SCHEMA_STRUCTURAL_KEYS: readonly ['properties', 'patternProperties', 'oneOf', 'anyOf', 'allOf', 'items', '$ref', 'enum', 'const'];
27
+ /** True when the schema node retains at least one structural (contract) key. */
28
+ export declare function schemaHasStructure(schema: Record<string, unknown>): boolean;
29
+ //# sourceMappingURL=schema-strip.d.ts.map
@@ -0,0 +1,173 @@
1
+ /**
2
+ * Shared JSON-Schema annotation stripper for BOTH transformer paths
3
+ * (Anthropic/Claude in transform.ts and OpenAI/GPT in openai.ts).
4
+ *
5
+ * The whole point of this module is that the strip is *structure-aware*: the
6
+ * literal key `description` (also `title`, `default`, `examples`) is a schema
7
+ * ANNOTATION in one place and a user-defined PROPERTY NAME in another. The
8
+ * `task` tool, for example, has a required parameter literally named
9
+ * `description`. A naive "drop every key called description" walk deletes that
10
+ * property, leaving `required: ["description"]` pointing at nothing — the model
11
+ * then can't emit it and the host rejects the tool call ("Missing key at
12
+ * [\"description\"]"). So we only strip annotation keywords at the schema-node
13
+ * level and recurse into the *values* of `properties`/`$defs`/etc., never
14
+ * treating their keys as annotations.
15
+ */
16
+ /** Max recursion depth for schema stripping. 20 handles realistic DSL/query schemas;
17
+ * deeper nodes are left untouched rather than corrupted. */
18
+ const SCHEMA_STRIP_MAX_DEPTH = 20;
19
+ /** Metadata keys that add tokens but no validation; the image carries them for the model.
20
+ * `$schema` is deliberately NOT here: it is the dialect declaration, not an annotation.
21
+ * Stripping it re-dialects the schema to the validator's default (JSON Schema 2020-12),
22
+ * which 400s draft-07 constructs the original legally used — e.g. tuple-form
23
+ * `items: [...]` in Voiceflow MCP tools ("tools.N.custom.input_schema: JSON schema
24
+ * is invalid. It must match JSON Schema draft 2020-12"). */
25
+ const SCHEMA_STRIP_KEYS = new Set([
26
+ 'description',
27
+ 'title',
28
+ 'examples',
29
+ 'default',
30
+ '$id',
31
+ '$comment',
32
+ ]);
33
+ /** JSON Schema composition keys (values are arrays of subschemas). */
34
+ const SCHEMA_COMPOSITION_KEYS = new Set(['oneOf', 'anyOf', 'allOf']);
35
+ /** JSON Schema keys whose values are named-subschema objects.
36
+ * IMPORTANT: the *keys* inside these objects are user property names, not
37
+ * annotation keywords — we recurse into the values only.
38
+ * Every container whose keys are property names MUST be listed here, or the
39
+ * fallback at the bottom of the walk reads its property keys as annotations. */
40
+ const SCHEMA_NAMED_SUBSCHEMA_KEYS = new Set([
41
+ 'properties',
42
+ 'patternProperties',
43
+ 'definitions',
44
+ '$defs',
45
+ 'dependentSchemas', // JSON Schema 2019-09+
46
+ 'dependencies', // draft-07 (subschema OR string[])
47
+ 'dependentRequired', // JSON Schema 2019-09+ (string[])
48
+ ]);
49
+ /** JSON Schema keys whose value is a single subschema. */
50
+ const SCHEMA_SINGLE_SUBSCHEMA_KEYS = new Set([
51
+ 'items',
52
+ 'additionalProperties',
53
+ 'not',
54
+ 'contains',
55
+ 'propertyNames',
56
+ 'unevaluatedItems',
57
+ 'unevaluatedProperties',
58
+ 'if',
59
+ 'then',
60
+ 'else',
61
+ ]);
62
+ /** JSON Schema keys that are primitives or opaque arrays — pass through verbatim.
63
+ * `required`/`enum`/`const` MUST survive untouched: stripping a property while
64
+ * leaving its name in `required` is exactly the bug this module prevents. */
65
+ const SCHEMA_VERBATIM_KEYS = new Set([
66
+ '$schema', // dialect declaration; stripping it can invalidate the schema
67
+ 'required',
68
+ 'enum',
69
+ 'const',
70
+ 'type', // string or array of strings
71
+ '$ref', // we don't resolve refs but we mustn't drop them
72
+ 'minimum',
73
+ 'maximum',
74
+ 'exclusiveMinimum',
75
+ 'exclusiveMaximum',
76
+ 'minLength',
77
+ 'maxLength',
78
+ 'minItems',
79
+ 'maxItems',
80
+ 'minProperties',
81
+ 'maxProperties',
82
+ 'multipleOf',
83
+ 'uniqueItems',
84
+ 'pattern',
85
+ ]);
86
+ /** Real `format` tokens (date-time, uri, email…) are short; anything longer is a description. */
87
+ const FORMAT_MAX_LEN = 32;
88
+ /** Strip long-form metadata from a JSON Schema node, preserving the structural
89
+ * keys a tool-use validator needs. Strips: description, title, examples,
90
+ * default, $id, $comment, long format. Recurses into
91
+ * properties/oneOf/anyOf/allOf/items etc. Returns a fresh object — never
92
+ * mutates the input. Property *names* (the keys inside `properties` and
93
+ * friends) are preserved even when they collide with annotation keywords. */
94
+ export function stripSchemaDescriptions(node, depth = 0) {
95
+ if (depth > SCHEMA_STRIP_MAX_DEPTH)
96
+ return node; // leave pathological depth untouched
97
+ if (Array.isArray(node))
98
+ return node; // subschema arrays handled by parent
99
+ if (!node || typeof node !== 'object')
100
+ return node;
101
+ const obj = node;
102
+ const out = {};
103
+ for (const [k, v] of Object.entries(obj)) {
104
+ if (SCHEMA_STRIP_KEYS.has(k))
105
+ continue;
106
+ if (k === 'format' && typeof v === 'string' && v.length > FORMAT_MAX_LEN) {
107
+ continue; // long format = description in disguise
108
+ }
109
+ if (SCHEMA_VERBATIM_KEYS.has(k)) {
110
+ out[k] = v;
111
+ continue;
112
+ }
113
+ if (SCHEMA_NAMED_SUBSCHEMA_KEYS.has(k) &&
114
+ v &&
115
+ typeof v === 'object' &&
116
+ !Array.isArray(v)) {
117
+ const nested = {};
118
+ for (const [pk, pv] of Object.entries(v)) {
119
+ nested[pk] = stripSchemaDescriptions(pv, depth + 1);
120
+ }
121
+ out[k] = nested;
122
+ continue;
123
+ }
124
+ if (SCHEMA_COMPOSITION_KEYS.has(k) && Array.isArray(v)) {
125
+ out[k] = v.map((sub) => stripSchemaDescriptions(sub, depth + 1));
126
+ continue;
127
+ }
128
+ if (SCHEMA_SINGLE_SUBSCHEMA_KEYS.has(k)) {
129
+ // additionalProperties may be a boolean — pass through untouched.
130
+ if (typeof v === 'boolean') {
131
+ out[k] = v;
132
+ }
133
+ else if (Array.isArray(v)) {
134
+ out[k] = v.map((sub) => stripSchemaDescriptions(sub, depth + 1));
135
+ }
136
+ else {
137
+ out[k] = stripSchemaDescriptions(v, depth + 1);
138
+ }
139
+ continue;
140
+ }
141
+ // Unknown key — recurse into nested objects so vendor-extension descriptions get stripped.
142
+ if (v && typeof v === 'object') {
143
+ out[k] = stripSchemaDescriptions(v, depth + 1);
144
+ }
145
+ else {
146
+ out[k] = v;
147
+ }
148
+ }
149
+ return out;
150
+ }
151
+ /** JSON Schema keys that carry a parameter *contract* (shape/values), as opposed
152
+ * to pure annotations. Used to decide whether a stripped schema still tells the
153
+ * validator anything — if none survive, the strip is not worth shipping. */
154
+ export const SCHEMA_STRUCTURAL_KEYS = [
155
+ 'properties',
156
+ 'patternProperties',
157
+ 'oneOf',
158
+ 'anyOf',
159
+ 'allOf',
160
+ 'items',
161
+ '$ref',
162
+ 'enum',
163
+ 'const',
164
+ ];
165
+ /** True when the schema node retains at least one structural (contract) key. */
166
+ export function schemaHasStructure(schema) {
167
+ for (const k of SCHEMA_STRUCTURAL_KEYS) {
168
+ if (k in schema)
169
+ return true;
170
+ }
171
+ return false;
172
+ }
173
+ //# sourceMappingURL=schema-strip.js.map
@@ -0,0 +1,219 @@
1
+ /**
2
+ * Per-session cache-liveness state for the history collapse.
3
+ *
4
+ * ## Why this exists
5
+ *
6
+ * The history grid is append-only: chunk N's pixels are a pure function of its
7
+ * message range, so old chunks stay byte-identical as the conversation grows and
8
+ * ride Anthropic's prompt cache as `cache_read` forever. That freeze is worth a
9
+ * lot — but only while a cache actually exists. Where there is none, the freeze
10
+ * protects nothing and the grid is free to be re-cut for *density* instead:
11
+ * {@link HistoryCollapseOptions.packFill} raises the freeze step until the pages
12
+ * are nearly full, which roughly halves image tokens on long sessions of short
13
+ * turns (#161: 317 images at 43% fill).
14
+ *
15
+ * ## How we know whether a cache exists
16
+ *
17
+ * The provider tells us, and that beats inferring it. {@link noteCacheOutcome}
18
+ * feeds each response's accounting back in: a `cache_read` proves the prefix was
19
+ * live, a `cache_create` proves one was just written. Only when both are zero is
20
+ * there nothing to lose by re-cutting.
21
+ *
22
+ * This module used to decide from the wall clock alone, treating any gap past the
23
+ * ephemeral 5-minute TTL as cold. That was wrong most of the times it fired —
24
+ * measured over 143 gaps on a production host, the cache was still warm in 66% of
25
+ * gaps past 5.5 minutes, 40% past 15 minutes, 13% past an hour. Claude Code marks
26
+ * some blocks with the 1-hour TTL, so the short constant never described this
27
+ * traffic. The worst case was a session repacked three times in one hour on
28
+ * ~10-minute gaps, each repack re-keying the whole prefix — and each preceded by a
29
+ * turn that had just *written* a cache, which the clock could not see.
30
+ *
31
+ * The clock survives only as a backstop for responses whose accounting never
32
+ * arrived: {@link COLD_HORIZON_MS}. And a rejected request still marks the session
33
+ * dead outright ({@link markCacheDead}) — but only a 413 or a too-long 400, not
34
+ * a transient 5xx: see {@link responseLeftNoCache}.
35
+ *
36
+ * ## Why the step is sticky
37
+ *
38
+ * Once a session has been repacked coarse, every later turn must keep at least
39
+ * that step. Falling back to the fine grid would re-cut the same messages into
40
+ * different chunks — every chunk's bytes change, and the whole history re-keys as
41
+ * `cache_create`. {@link recordFreezeStep} pins the floor; the collapse only ever
42
+ * doubles it.
43
+ *
44
+ * ## Why the state survives a restart
45
+ *
46
+ * The map lives in this process. A restart used to lose it, and the module
47
+ * called that an accepted failure mode: an unknown session is treated as WARM
48
+ * (no repack), so at worst we keep paying the old image count. That covers
49
+ * `cold`, but not the floor. {@link recordFreezeStep} exists because a render at
50
+ * a finer grid than the session was last frozen at re-keys every chunk (see
51
+ * above), and after a restart the floor is 0 again: the next collapse is free to
52
+ * pick a finer step than the one the cache was built on, and whether it does
53
+ * depends on that request's image budget — exactly what the pin was added to
54
+ * stop mattering.
55
+ *
56
+ * So the host may attach a {@link SessionStateStore}. Every mutation schedules a
57
+ * debounced save ({@link PERSIST_DEBOUNCE_MS}); the record shape on disk is the
58
+ * in-memory record plus its key. On configure the file is read back and records
59
+ * idle for more than {@link PERSIST_MAX_IDLE_MS} are dropped — past the cold
60
+ * horizon the clock already declares them cold, so nothing they pin is protecting
61
+ * a live cache. Records already in memory win over the file. The core never
62
+ * touches a filesystem: without a store the module behaves exactly as before.
63
+ */
64
+ export type OpticalHistoryPolicy = 'hybrid' | 'full';
65
+ export interface SessionLivenessScopeOpts {
66
+ readonly nowMs?: number;
67
+ readonly model?: string;
68
+ readonly modelFamily?: string;
69
+ readonly systemSha8?: string;
70
+ readonly scope?: string;
71
+ }
72
+ /**
73
+ * Configure the maximum tracked sessions kept in RAM (clamped to `[64, 8192]`),
74
+ * evicting oldest entries immediately if capacity shrinks.
75
+ */
76
+ export declare function configureMaxSessions(limit?: number): number;
77
+ /** Current maximum tracked session count. */
78
+ export declare function getMaxSessions(): number;
79
+ /**
80
+ * Host-supplied storage for the session map. The core stays filesystem-free;
81
+ * `node.ts` backs this with `~/.inkling/session-state.json`, tests with a string.
82
+ * `load` returns the last saved text or `undefined` when nothing was saved yet.
83
+ * `save` must be atomic from the reader's point of view (write-then-rename).
84
+ */
85
+ export interface SessionStateStore {
86
+ load(): string | undefined;
87
+ save(text: string): void;
88
+ }
89
+ /**
90
+ * Attach (or with `undefined`, detach) the store and restore what it holds.
91
+ * Flushes pending changes to the previous store first. Returns how many
92
+ * sessions were restored. Never throws: a store that cannot be read leaves the
93
+ * map as it was — the pre-persistence behaviour, which is safe (unknown = warm).
94
+ */
95
+ export declare function configureSessionStateStore(next: SessionStateStore | undefined, nowMs?: number): number;
96
+ /**
97
+ * Merge a serialized snapshot into the map. Records already in memory win (they
98
+ * are newer by construction); records idle past {@link PERSIST_MAX_IDLE_MS} or
99
+ * malformed in any field are skipped. Returns the number restored.
100
+ */
101
+ export declare function restoreSessionState(text: string | undefined, nowMs?: number): number;
102
+ /** The map as JSON, oldest session first (LRU order), stale records omitted. */
103
+ export declare function serializeSessionState(nowMs?: number): string;
104
+ /**
105
+ * Write pending changes now. Returns true when a save happened. Called by the
106
+ * debounce timer, on store change, and by the host on shutdown. A failing store
107
+ * is swallowed: persistence is an optimisation and must never fail a request.
108
+ */
109
+ export declare function flushSessionState(): boolean;
110
+ export interface HistorySessionState {
111
+ /** The upstream prefix cache is provably gone — re-cutting the grid is free. */
112
+ cold: boolean;
113
+ /** Floor for the freeze step, in messages. 0 = no constraint. */
114
+ minFreezeStep: number;
115
+ }
116
+ /** Normalize a model ID to its liveness family so auxiliary Haiku calls never clobber main-thread liveness. */
117
+ export declare function normalizeSessionModelFamily(model: string | undefined): string;
118
+ /**
119
+ * Record a request for `sessionKey` and report what the history collapse may
120
+ * assume about the upstream cache. Call once per transformed request, BEFORE the
121
+ * collapse runs; it advances the session's last-seen clock.
122
+ *
123
+ * A session we have never seen counts as warm (see module docs) — unknown must
124
+ * never authorize a repack.
125
+ */
126
+ export declare function noteHistoryRequest(sessionKey: string | undefined, nowMsOrOpts?: number | SessionLivenessScopeOpts): HistorySessionState;
127
+ /**
128
+ * Non-mutating read checking whether `sessionKey`'s upstream cache is currently cold.
129
+ * Unknown/unseen sessions return `false` (warm by default).
130
+ */
131
+ export declare function isSessionCacheCold(sessionKey: string | undefined, nowMsOrOpts?: number | SessionLivenessScopeOpts): boolean;
132
+ export declare function getPinnedOpticalHistoryPolicy(sessionKey: string | undefined, opts?: SessionLivenessScopeOpts): OpticalHistoryPolicy | undefined;
133
+ export declare function setPinnedOpticalHistoryPolicy(sessionKey: string | undefined, policy: OpticalHistoryPolicy, opts?: SessionLivenessScopeOpts): void;
134
+ export declare function recordSealedEpochKey(sessionKey: string | undefined, epochKey: string): void;
135
+ export declare function hasSealedEpochKey(sessionKey: string | undefined, epochKey: string): boolean;
136
+ /**
137
+ * Record a Stage-2 text-hygiene or hybrid optical slot seal key (head-retaining
138
+ * cap 512) so any compression performed at the uncached frontier replays
139
+ * bit-identically once downstream cache_control breakpoints cover that slot.
140
+ */
141
+ export declare function recordStage2SealKey(sessionKey: string | undefined, slotKey: string): void;
142
+ export declare function hasStage2SealKey(sessionKey: string | undefined, slotKey: string): boolean;
143
+ export declare function recordFoldedEpisodeId(sessionKey: string | undefined, episodeId: string, certificate?: string): void;
144
+ export declare function getFoldedEpisodeCertificate(sessionKey: string | undefined, episodeId: string): string | undefined;
145
+ export declare function hasFoldedEpisodeId(sessionKey: string | undefined, episodeId: string): boolean;
146
+ export declare function hasAnyFoldedEpisodeId(sessionKey: string | undefined): boolean;
147
+ export declare function getPinnedSessionSkills(sessionKey: string | undefined, catalogHash: string): readonly string[] | undefined;
148
+ export declare function setPinnedSessionSkills(sessionKey: string | undefined, catalogHash: string, skills: readonly string[]): void;
149
+ export declare function noteCacheOutcome(sessionKey: string | undefined, cacheReadTokens: number | undefined, cacheCreateTokens: number | undefined, opts?: SessionLivenessScopeOpts): void;
150
+ /**
151
+ * Pin the grid this session was last rendered at. Monotonic: the floor only ever
152
+ * rises, because a later, finer render would re-key every chunk it re-cuts.
153
+ */
154
+ export declare function recordFreezeStep(sessionKey: string | undefined, step: number | undefined, opts?: SessionLivenessScopeOpts): void;
155
+ /**
156
+ * Mark this session's upstream cache as gone: the last request was rejected, so
157
+ * nothing was cached and the next one may re-cut the grid for density. Call on
158
+ * the failure paths that leave no cache entry (oversized request → opaque 500).
159
+ */
160
+ export declare function markCacheDead(sessionKey: string | undefined, opts?: SessionLivenessScopeOpts): void;
161
+ /**
162
+ * Did this response leave the upstream prefix cache unpopulated?
163
+ *
164
+ * A cache entry is written by a request the provider actually *accepted*. Three
165
+ * outcomes mean it never got that far, so the frozen grid we were protecting
166
+ * protects nothing and the next turn may re-cut for density:
167
+ *
168
+ * - `413` — the payload was rejected outright;
169
+ * - `400` whose body says the prompt is too long (Anthropic's wording varies:
170
+ * `prompt is too long`, `prompt_too_long`, `request_too_large`).
171
+ *
172
+ * NOT any 5xx, which is what this used to say. Production disagreed: of 20871
173
+ * requests on one host the 5xx population was 177 × `529 overloaded`, 2 × `500`
174
+ * and 1 × `503` — and 129 of 250 repacks fired directly after one of them. A 529
175
+ * means the provider declined to process the request; the prefix cache it never
176
+ * touched is still there, and re-cutting the grid threw it away for nothing.
177
+ *
178
+ * Nor any other 4xx. A bad key or a rate limit says nothing about the cache.
179
+ *
180
+ * A cache that genuinely died needs no error to be noticed: {@link
181
+ * noteCacheOutcome} sees the next response report neither a read nor a write, and
182
+ * that is both accurate and free.
183
+ */
184
+ export declare function responseLeftNoCache(status: number, errorBody?: string): boolean;
185
+ /** Test seam: drop all session state and any pending save. The store stays attached. */
186
+ export declare function resetSessionState(): void;
187
+ /** Test/inspection seam: inspect a session without mutating its clock. */
188
+ export declare function peekSessionState(sessionKey: string): {
189
+ lastSeenMs: number;
190
+ freezeStep: number;
191
+ cacheDead: boolean;
192
+ repackInFlightCount?: number;
193
+ justRepacked: boolean;
194
+ lastCacheAlive?: boolean;
195
+ everCacheAlive?: boolean;
196
+ opticalHistoryPolicy?: OpticalHistoryPolicy;
197
+ sealedEpochKeys?: string[];
198
+ sealedStage2SlotKeys?: string[];
199
+ pinnedSkills?: string[];
200
+ pinnedSkillCatalogHash?: string;
201
+ } | undefined;
202
+ export declare function isBoilerplateText(text: string): boolean;
203
+ /**
204
+ * Pick the text that identifies a conversation, from the text blocks of its
205
+ * opening user turn(s) in order (everything before the first assistant message).
206
+ *
207
+ * Blocks that are wholly a harness envelope are skipped: they are boilerplate
208
+ * the client injects into every session (omp opens each one with the same
209
+ * `<system-notice>` device inventory; Claude Code with the project's CLAUDE.md
210
+ * `<system-reminder>` and local slash-command output), so keying on them merges
211
+ * every concurrent session into one record, and each session's cache outcomes
212
+ * then re-cut the others' history grids. The first non-envelope block is the
213
+ * user's own prompt. When every block is an envelope, the first one is still
214
+ * better than no key. Capped at 4 KiB.
215
+ */
216
+ export declare function sessionAnchorText(texts: readonly string[]): string;
217
+ /** Inspection seam: how many sessions are currently tracked. */
218
+ export declare function sessionStateSize(): number;
219
+ //# sourceMappingURL=session-state.d.ts.map