@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
+ * Bijective TOON / ONTO columnar encoder & decoder for uniform JSON payloads.
3
+ *
4
+ * Grounded in:
5
+ * - TOON (arXiv:2603.03306): tabular schema-once encoding cuts 30-50%+ tokens
6
+ * over minified JSON while matching/improving retrieval per token.
7
+ * - ONTO (arXiv:2604.17512): schema-once columnar rows with optional header
8
+ * metadata preserve structural fidelity across operational logs & arrays.
9
+ *
10
+ * 100% lossless (`decodeToon(encodeToon(x))` reconstructs `x`) and Workers-safe
11
+ * (zero `node:` imports). Only emitted when strictly token-profitable (>=20%
12
+ * fewer o200k tokens than minified JSON).
13
+ */
14
+ /**
15
+ * Losslessly encode a uniform array (or object dominated by a uniform array)
16
+ * into `@toon` pipe-delimited columnar format. Returns null if ineligible or
17
+ * if `@toon` does not save at least 20% tokens over minified JSON.
18
+ * Optional `minJsonBox` receives the computed `JSON.stringify(parsed)` string so
19
+ * callers don't serialize `parsed` twice.
20
+ */
21
+ export declare function encodeToon(parsed: unknown, minJsonBox?: {
22
+ json?: string;
23
+ }): string | null;
24
+ /**
25
+ * Bijectively decode a `@toon` payload back to the exact original JavaScript
26
+ * array or wrapper object. Throws on malformed input.
27
+ */
28
+ export declare function decodeToon(toon: string): unknown;
29
+ //# sourceMappingURL=toon.d.ts.map
@@ -0,0 +1,425 @@
1
+ /**
2
+ * Bijective TOON / ONTO columnar encoder & decoder for uniform JSON payloads.
3
+ *
4
+ * Grounded in:
5
+ * - TOON (arXiv:2603.03306): tabular schema-once encoding cuts 30-50%+ tokens
6
+ * over minified JSON while matching/improving retrieval per token.
7
+ * - ONTO (arXiv:2604.17512): schema-once columnar rows with optional header
8
+ * metadata preserve structural fidelity across operational logs & arrays.
9
+ *
10
+ * 100% lossless (`decodeToon(encodeToon(x))` reconstructs `x`) and Workers-safe
11
+ * (zero `node:` imports). Only emitted when strictly token-profitable (>=20%
12
+ * fewer o200k tokens than minified JSON).
13
+ */
14
+ import { gptTokenCount, hasLongUnbrokenBpeChunk } from './gpt-tokens.js';
15
+ const TOKEN_EXACT_CHAR_LIMIT = 32_000;
16
+ const NUMERIC_CELL_RE = /^-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?$/;
17
+ const ESCAPE_NEEDED_RE = /[\\|\n\r]/;
18
+ const EDGE_WS_RE = /^\s|\s$/;
19
+ function isPlainObject(v) {
20
+ if (!v || typeof v !== 'object' || Array.isArray(v))
21
+ return false;
22
+ const proto = Object.getPrototypeOf(v);
23
+ return proto === Object.prototype || proto === null;
24
+ }
25
+ function setOwnProp(target, key, value) {
26
+ Object.defineProperty(target, key, {
27
+ value,
28
+ writable: true,
29
+ enumerable: true,
30
+ configurable: true,
31
+ });
32
+ }
33
+ function escapeCellText(s) {
34
+ if (!ESCAPE_NEEDED_RE.test(s))
35
+ return s;
36
+ let out = '';
37
+ let start = 0;
38
+ for (let i = 0; i < s.length; i++) {
39
+ const ch = s.charCodeAt(i);
40
+ let rep;
41
+ if (ch === 92)
42
+ rep = '\\\\';
43
+ else if (ch === 124)
44
+ rep = '\\|';
45
+ else if (ch === 10)
46
+ rep = '\\n';
47
+ else if (ch === 13)
48
+ rep = '\\r';
49
+ if (rep !== undefined) {
50
+ if (i > start)
51
+ out += s.slice(start, i);
52
+ out += rep;
53
+ start = i + 1;
54
+ }
55
+ }
56
+ if (start < s.length)
57
+ out += s.slice(start);
58
+ return out;
59
+ }
60
+ function unescapeCellText(s) {
61
+ let out = '';
62
+ for (let i = 0; i < s.length; i++) {
63
+ const ch = s[i];
64
+ if (ch === '\\' && i + 1 < s.length) {
65
+ const next = s[++i];
66
+ if (next === '\\')
67
+ out += '\\';
68
+ else if (next === '|')
69
+ out += '|';
70
+ else if (next === 'n')
71
+ out += '\n';
72
+ else if (next === 'r')
73
+ out += '\r';
74
+ else
75
+ out += '\\' + next;
76
+ }
77
+ else {
78
+ out += ch;
79
+ }
80
+ }
81
+ return out;
82
+ }
83
+ function splitEscapedPipes(line) {
84
+ const cells = [];
85
+ let start = 0;
86
+ let escaped = false;
87
+ for (let i = 0; i < line.length; i++) {
88
+ const ch = line[i];
89
+ if (escaped) {
90
+ escaped = false;
91
+ continue;
92
+ }
93
+ if (ch === '\\') {
94
+ escaped = true;
95
+ continue;
96
+ }
97
+ if (ch === '|') {
98
+ cells.push(line.slice(start, i));
99
+ start = i + 1;
100
+ }
101
+ }
102
+ cells.push(line.slice(start));
103
+ return cells;
104
+ }
105
+ function encodeCell(v) {
106
+ if (v === undefined)
107
+ return '';
108
+ if (v === null)
109
+ return '~N';
110
+ if (typeof v === 'boolean')
111
+ return v ? 'true' : 'false';
112
+ if (typeof v === 'number') {
113
+ if (!Number.isFinite(v))
114
+ return null;
115
+ return Object.is(v, -0) ? '0' : String(v);
116
+ }
117
+ if (typeof v === 'string') {
118
+ if (v === '' ||
119
+ v === 'true' ||
120
+ v === 'false' ||
121
+ v.startsWith('~') ||
122
+ v.startsWith('@meta ') ||
123
+ v.startsWith('[') ||
124
+ v.startsWith('{') ||
125
+ EDGE_WS_RE.test(v) ||
126
+ NUMERIC_CELL_RE.test(v)) {
127
+ return '~S' + escapeCellText(v);
128
+ }
129
+ return escapeCellText(v);
130
+ }
131
+ if (typeof v === 'object') {
132
+ let serialized;
133
+ try {
134
+ serialized = JSON.stringify(v);
135
+ }
136
+ catch {
137
+ return null;
138
+ }
139
+ if (!serialized || (!serialized.startsWith('[') && !serialized.startsWith('{')))
140
+ return null;
141
+ return escapeCellText(serialized);
142
+ }
143
+ return null;
144
+ }
145
+ function decodeCell(raw) {
146
+ if (raw === '' || raw === '~U')
147
+ return undefined;
148
+ if (raw === '~N')
149
+ return null;
150
+ if (raw === 'true')
151
+ return true;
152
+ if (raw === 'false')
153
+ return false;
154
+ if (raw.startsWith('~S'))
155
+ return unescapeCellText(raw.slice(2));
156
+ if (raw.startsWith('[') || raw.startsWith('{')) {
157
+ return JSON.parse(unescapeCellText(raw));
158
+ }
159
+ if (NUMERIC_CELL_RE.test(raw)) {
160
+ const n = Number(raw);
161
+ if (Number.isFinite(n))
162
+ return n;
163
+ }
164
+ return unescapeCellText(raw);
165
+ }
166
+ function selectTableTarget(parsed) {
167
+ if (Array.isArray(parsed)) {
168
+ if (parsed.length < 5 || !parsed.every(isPlainObject))
169
+ return null;
170
+ return { rows: parsed };
171
+ }
172
+ if (!isPlainObject(parsed))
173
+ return null;
174
+ const entries = Object.entries(parsed);
175
+ let hasCandidate = false;
176
+ for (let i = 0; i < entries.length; i++) {
177
+ const v = entries[i][1];
178
+ if (Array.isArray(v) && v.length >= 5 && v.every(isPlainObject)) {
179
+ hasCandidate = true;
180
+ break;
181
+ }
182
+ }
183
+ if (!hasCandidate)
184
+ return null;
185
+ let bestKey;
186
+ let bestRows;
187
+ let bestLen = 0;
188
+ let totalApproxLen = 2;
189
+ const precomputedParts = [];
190
+ for (const [k, v] of entries) {
191
+ let serialized;
192
+ try {
193
+ serialized = JSON.stringify(v);
194
+ }
195
+ catch {
196
+ return null;
197
+ }
198
+ if (serialized !== undefined) {
199
+ precomputedParts.push({ key: k, json: serialized });
200
+ totalApproxLen += k.length + 4 + serialized.length;
201
+ }
202
+ const vLen = serialized?.length ?? 0;
203
+ if (Array.isArray(v) && v.length >= 5 && v.every(isPlainObject) && vLen > bestLen) {
204
+ bestKey = k;
205
+ bestRows = v;
206
+ bestLen = vLen;
207
+ }
208
+ }
209
+ if (!bestKey || !bestRows)
210
+ return null;
211
+ if (bestLen < totalApproxLen * 0.6)
212
+ return null;
213
+ const siblings = {};
214
+ let hasSiblings = false;
215
+ for (const [k, v] of entries) {
216
+ if (k !== bestKey && v !== undefined) {
217
+ setOwnProp(siblings, k, v);
218
+ hasSiblings = true;
219
+ }
220
+ }
221
+ return {
222
+ arrayKey: bestKey,
223
+ rows: bestRows,
224
+ siblings: hasSiblings ? siblings : undefined,
225
+ precomputedParts,
226
+ };
227
+ }
228
+ function estimateTokenPair(minJson, toon) {
229
+ // Always compare both payloads under the same regime (both exact BPE or both
230
+ // char-ratio) so long/unbroken JSON strings never compare heuristic JSON tokens
231
+ // against exact BPE TOON tokens.
232
+ if (minJson.length <= TOKEN_EXACT_CHAR_LIMIT &&
233
+ toon.length <= TOKEN_EXACT_CHAR_LIMIT &&
234
+ !hasLongUnbrokenBpeChunk(minJson) &&
235
+ !hasLongUnbrokenBpeChunk(toon)) {
236
+ return [gptTokenCount(minJson), gptTokenCount(toon)];
237
+ }
238
+ return [Math.ceil(minJson.length / 3.5), Math.ceil(toon.length / 3.5)];
239
+ }
240
+ /**
241
+ * Losslessly encode a uniform array (or object dominated by a uniform array)
242
+ * into `@toon` pipe-delimited columnar format. Returns null if ineligible or
243
+ * if `@toon` does not save at least 20% tokens over minified JSON.
244
+ * Optional `minJsonBox` receives the computed `JSON.stringify(parsed)` string so
245
+ * callers don't serialize `parsed` twice.
246
+ */
247
+ export function encodeToon(parsed, minJsonBox) {
248
+ const target = selectTableTarget(parsed);
249
+ if (!target)
250
+ return null;
251
+ const cols = [];
252
+ const colSet = new Set();
253
+ let totalFieldCount = 0;
254
+ for (const row of target.rows) {
255
+ for (const k of Object.keys(row)) {
256
+ if (row[k] === undefined)
257
+ continue;
258
+ totalFieldCount += 1;
259
+ if (!colSet.has(k)) {
260
+ colSet.add(k);
261
+ cols.push(k);
262
+ if (cols.length > 24)
263
+ return null;
264
+ }
265
+ }
266
+ }
267
+ if (cols.length < 2)
268
+ return null;
269
+ const density = totalFieldCount / (target.rows.length * cols.length);
270
+ if (density < 0.75)
271
+ return null;
272
+ let minJson;
273
+ const hasCustomToJson = !Array.isArray(parsed) &&
274
+ typeof parsed?.toJSON === 'function';
275
+ if (target.precomputedParts && !hasCustomToJson) {
276
+ try {
277
+ minJson = `{${target.precomputedParts.map((p) => `${JSON.stringify(p.key)}:${p.json}`).join(',')}}`;
278
+ }
279
+ catch {
280
+ return null;
281
+ }
282
+ }
283
+ else {
284
+ try {
285
+ minJson = JSON.stringify(parsed);
286
+ }
287
+ catch {
288
+ return null;
289
+ }
290
+ }
291
+ if (minJsonBox)
292
+ minJsonBox.json = minJson;
293
+ if (!minJson || minJson.length < 256)
294
+ return null;
295
+ const encodedCols = cols.map(escapeCellText).join('|');
296
+ const headerParts = ['@toon'];
297
+ if (target.arrayKey !== undefined) {
298
+ try {
299
+ headerParts.push(`key=${encodeURIComponent(target.arrayKey)}`);
300
+ }
301
+ catch {
302
+ // Lone UTF-16 surrogates throw URIError in encodeURIComponent; bail cleanly to JSON.
303
+ return null;
304
+ }
305
+ }
306
+ headerParts.push(`rows=${target.rows.length}`);
307
+ headerParts.push(`cols=${encodedCols}`);
308
+ const lines = [headerParts.join(' ')];
309
+ if (target.siblings !== undefined) {
310
+ if (target.precomputedParts && !hasCustomToJson) {
311
+ try {
312
+ const siblingParts = target.precomputedParts
313
+ .filter((p) => p.key !== target.arrayKey)
314
+ .map((p) => `${JSON.stringify(p.key)}:${p.json}`);
315
+ lines.push(`@meta {${siblingParts.join(',')}}`);
316
+ }
317
+ catch {
318
+ return null;
319
+ }
320
+ }
321
+ else {
322
+ try {
323
+ lines.push(`@meta ${JSON.stringify(target.siblings)}`);
324
+ }
325
+ catch {
326
+ return null;
327
+ }
328
+ }
329
+ }
330
+ for (const row of target.rows) {
331
+ const cells = [];
332
+ for (let c = 0; c < cols.length; c++) {
333
+ const col = cols[c];
334
+ const has = Object.prototype.hasOwnProperty.call(row, col);
335
+ const cell = encodeCell(has ? row[col] : undefined);
336
+ if (cell === null)
337
+ return null;
338
+ cells.push(cell);
339
+ }
340
+ lines.push(cells.join('|'));
341
+ }
342
+ const toon = lines.join('\n');
343
+ if (toon.length >= minJson.length)
344
+ return null;
345
+ const [jsonTokens, toonTokens] = estimateTokenPair(minJson, toon);
346
+ if (toonTokens > jsonTokens * 0.8)
347
+ return null;
348
+ return toon;
349
+ }
350
+ /**
351
+ * Bijectively decode a `@toon` payload back to the exact original JavaScript
352
+ * array or wrapper object. Throws on malformed input.
353
+ */
354
+ export function decodeToon(toon) {
355
+ const lines = toon.split('\n');
356
+ if (lines.length < 1)
357
+ throw new Error('Empty @toon payload');
358
+ const header = lines[0];
359
+ if (!header.startsWith('@toon '))
360
+ throw new Error('Missing @toon header');
361
+ const colsPrefix = ' cols=';
362
+ const rowsColsMatch = / rows=(\d+) cols=/.exec(header);
363
+ const colsIdx = rowsColsMatch
364
+ ? rowsColsMatch.index + rowsColsMatch[0].length - colsPrefix.length
365
+ : header.indexOf(colsPrefix);
366
+ if (colsIdx < 0)
367
+ throw new Error('Missing cols= in @toon header');
368
+ const metaHeader = header.slice(6, colsIdx).trim();
369
+ const colsRaw = header.slice(colsIdx + colsPrefix.length);
370
+ const cols = splitEscapedPipes(colsRaw).map(unescapeCellText);
371
+ let arrayKey;
372
+ let expectedRows = -1;
373
+ for (const token of metaHeader.split(/\s+/)) {
374
+ if (token.startsWith('key=')) {
375
+ const rawKey = token.slice(4);
376
+ try {
377
+ arrayKey = decodeURIComponent(rawKey);
378
+ }
379
+ catch {
380
+ arrayKey = unescapeCellText(rawKey);
381
+ }
382
+ }
383
+ else if (token.startsWith('rows=')) {
384
+ expectedRows = Number.parseInt(token.slice(5), 10);
385
+ }
386
+ }
387
+ let rowStartIdx = 1;
388
+ let siblings;
389
+ if (lines[1]?.startsWith('@meta ')) {
390
+ siblings = JSON.parse(lines[1].slice(6));
391
+ rowStartIdx = 2;
392
+ }
393
+ const rows = [];
394
+ for (let i = rowStartIdx; i < lines.length; i++) {
395
+ const line = lines[i];
396
+ if (line === '' && i === lines.length - 1 && expectedRows === rows.length)
397
+ break;
398
+ const rawCells = splitEscapedPipes(line);
399
+ if (rawCells.length !== cols.length) {
400
+ throw new Error(`Row ${i} has ${rawCells.length} cells, expected ${cols.length}`);
401
+ }
402
+ const obj = {};
403
+ for (let c = 0; c < cols.length; c++) {
404
+ const val = decodeCell(rawCells[c]);
405
+ if (val !== undefined) {
406
+ setOwnProp(obj, cols[c], val);
407
+ }
408
+ }
409
+ rows.push(obj);
410
+ }
411
+ if (expectedRows >= 0 && rows.length !== expectedRows) {
412
+ throw new Error(`Expected ${expectedRows} rows, got ${rows.length}`);
413
+ }
414
+ if (arrayKey === undefined)
415
+ return rows;
416
+ const out = {};
417
+ if (siblings) {
418
+ for (const [k, v] of Object.entries(siblings)) {
419
+ setOwnProp(out, k, v);
420
+ }
421
+ }
422
+ setOwnProp(out, arrayKey, rows);
423
+ return out;
424
+ }
425
+ //# sourceMappingURL=toon.js.map
@@ -0,0 +1,223 @@
1
+ /**
2
+ * Runtime-agnostic event sink for inkling.
3
+ * Per-request JSONL record — same shape on Node (file) and Workers (console.log).
4
+ * Never emits raw text; only sizes, counts, durations, env fields, and sha256 prefixes.
5
+ */
6
+ import type { ProxyEvent } from './proxy.js';
7
+ /** Flat record persisted per request. Adding a field is non-breaking for readers. */
8
+ export interface TrackEvent {
9
+ ts: string;
10
+ method: string;
11
+ path: string;
12
+ /** Top-level request model when present. */
13
+ model?: string;
14
+ accounting_provider?: 'anthropic' | 'openai' | 'google';
15
+ status: number;
16
+ duration_ms: number;
17
+ first_byte_ms?: number;
18
+ /** Local render+encode ms. `duration_ms - transform_ms` isolates upstream. */
19
+ transform_ms?: number;
20
+ compressed?: boolean;
21
+ reason?: string;
22
+ orig_chars?: number;
23
+ /** Text-chars replaced by image blocks (slab + reminders + tool_results).
24
+ * Compare with image_count: textTokens(n/4) vs imageTokens(n×2500). */
25
+ compressed_chars?: number;
26
+ image_count?: number;
27
+ /** Images the CLIENT already put on the wire (pasted screenshots, tool-returned
28
+ * pictures). They spend from the same provider cap as ours, so this is the
29
+ * number that explains an otherwise-surprising image_budget passthrough. */
30
+ native_images?: number;
31
+ /** Imaging paths that degraded to text because the wire cap was full. Nonzero
32
+ * here plus a fat request means the client's own images crowded us out — the
33
+ * request stayed valid, but the token win was skipped. */
34
+ image_budget_skips?: number;
35
+ /** Image blocks really on the wire. Present only when it differs from
36
+ * image_count + native_images — i.e. when the history collapse absorbed
37
+ * messages that already carried images, so we rendered more than we sent. */
38
+ wire_images?: number;
39
+ image_bytes?: number;
40
+ /** Total pixel area across all rendered images; pairs with cache_create_tokens for px/token regression. */
41
+ image_pixels?: number;
42
+ /** Provider-estimated vision tokens billed for rendered images. */
43
+ image_tokens?: number;
44
+ /** Chars/tokens removed by prefix-safe deterministic tool-output hygiene. */
45
+ text_hygiene_saved_chars?: number;
46
+ text_hygiene_saved_tokens?: number;
47
+ text_hygiene_blocks?: number;
48
+ text_hygiene_stages?: string[];
49
+ /** Set when compression pulled the prompt below a long-context pricing cliff. */
50
+ cliff_avoided_at?: number;
51
+ cliff_saved_usd?: number;
52
+ /** Provider-specific text-token estimate for imaged/stripped content. */
53
+ baseline_imaged_tokens?: number;
54
+ /** Provider-specific estimate of inkling-added native text. */
55
+ native_injected_tokens?: number;
56
+ /** Chars re-emitted as the pin footer on the last user message.
57
+ * These are MOVED, not copied: the source lines are stripped from the
58
+ * cacheable prefix and re-sent as plain text at the tail, so they are paid
59
+ * at full input price every turn instead of cache-read price once. Not part
60
+ * of orig_chars or compressed_chars, so any savings figure that ignores it
61
+ * overstates the win by this much per turn. */
62
+ pin_chars?: number;
63
+ /** TEXT chars in the outgoing body (all text blocks, incl. non-compressed tool_results).
64
+ * With image_pixels, a regression over cold-miss events solves chars_per_token (α) and pixels_per_token (β). */
65
+ outgoing_text_chars?: number;
66
+ /** Local o200k decomposition of the original OpenAI Responses request. */
67
+ responses_composition?: NonNullable<NonNullable<ProxyEvent['info']>['responsesComposition']>;
68
+ static_chars?: number;
69
+ dynamic_chars?: number;
70
+ dynamic_block_count?: number;
71
+ /** Images from compressing <system-reminder> blocks in the first user message. */
72
+ reminder_imgs?: number;
73
+ /** Images from compressing tool_result content. */
74
+ tool_result_imgs?: number;
75
+ /** Chars of tool docs moved to the system-text Tool Reference (not imaged). */
76
+ tool_docs_chars?: number;
77
+ /** tool_result blocks where text exceeded the per-result image budget and was truncated. */
78
+ truncated_tool_results?: number;
79
+ /** Chars elided by paging across all tool_results this request. */
80
+ omitted_chars?: number;
81
+ /** History-image: messages collapsed into the synthetic prepended user message. */
82
+ collapsed_turns?: number;
83
+ /** Total chars serialized into history image(s) before render. */
84
+ collapsed_chars?: number;
85
+ /** PNG blocks emitted for the history; also folded into image_count. */
86
+ collapsed_images?: number;
87
+ /** Why history collapse didn't run (or did). Diagnostic. */
88
+ history_reason?: string;
89
+ /** Messages packed per history image. Rises when the grid is re-cut coarser;
90
+ * never falls within a session, because a finer re-cut re-keys every chunk. */
91
+ history_freeze_step?: number;
92
+ /** Set when the grid was coarsened purely to fit the image budget — the turn
93
+ * paid legibility for a request that would otherwise have been rejected. */
94
+ history_budget_trimmed?: boolean;
95
+ /** Set when the session's upstream cache was provably dead and the collapse
96
+ * was therefore allowed to repack for density. Pair with cache_read_tokens:
97
+ * a repack that lands on a live cache would show as a cache_create spike. */
98
+ history_pack_fill?: boolean;
99
+ /** History collapse treated each closed tool call/result pair as its own round
100
+ * (Claude Code detection or FICHE_TRUST_ADJACENT_TOOL_ROUNDS=1). */
101
+ history_split_adjacent_pairs?: boolean;
102
+ /** Codepoints not in the glyph atlas. A spike means users type glyphs we don't ship — widen ATLAS_PROFILE. */
103
+ dropped_chars?: number;
104
+ /** Top-20 dropped codepoints (U+HHHH keys) by frequency. Only present when dropped_chars > 0. */
105
+ dropped_codepoints_top?: Record<string, number>;
106
+ /** Blocks that weren't image-compressed this request; only emitted when at least one counter > 0. */
107
+ passthrough_reasons?: {
108
+ below_threshold?: number;
109
+ not_profitable?: number;
110
+ };
111
+ /** Unrecognized tag names in the static slab — canary for Claude Code releases adding new dynamic tags. */
112
+ unknown_static_tags?: string[];
113
+ /** Slab tags whose content changed within a session — proven per-turn dynamics busting the image cache. */
114
+ churning_static_tags?: string[];
115
+ /** Per-bucket TEXT chars through each gate call site (static_slab, reminder, tool_result_*, history).
116
+ * Undefined on uncompressed requests; enables per-bucket cpt regression. */
117
+ bucket_chars?: Partial<Record<'static_slab' | 'reminder' | 'tool_result_structured' | 'tool_result_log' | 'tool_result_prose' | 'history', number>>;
118
+ /** TEXT chars that fed the history-image renderer; separate from bucket_chars because it credits a synthetic message. */
119
+ history_text_chars?: number;
120
+ /** sha8 of the collapsed history image. Unchanged across turns proves the prompt cache is hitting (cache_read).
121
+ * A drifting hash means the collapse boundary is unstable. Absent on no-collapse turns. */
122
+ history_image_sha8?: string;
123
+ /** sha8 of the exact cacheable prefix sent (tools+system+imaged prefix, live
124
+ * tail excluded). Changes turn-over-turn within a session ⇒ inkling-side cache
125
+ * bust; stable while cache_create spikes ⇒ upstream eviction. See #11. */
126
+ cache_prefix_sha8?: string;
127
+ /** Approx chars in that pinned prefix (growth vs pure-invalidation split). */
128
+ cache_prefix_bytes?: number;
129
+ /** Per-layer digests of the same pinned prefix. Whichever one moves between
130
+ * two turns of a session IS the cache-bust cause: tools (client loaded a
131
+ * deferred tool), system (volatile text inside the pinned span), head
132
+ * (collapse boundary / marker placement moved). */
133
+ cache_prefix_tools_sha8?: string;
134
+ cache_prefix_system_sha8?: string;
135
+ cache_prefix_head_sha8?: string;
136
+ /** The span Anthropic really caches (through the last cache_control marker),
137
+ * its size, and the marker's position. Unstable marked digest ⇒ inkling-side
138
+ * bust; stable digest with cache_read 0 ⇒ look upstream, not at the rewrite. */
139
+ cache_prefix_marked_sha8?: string;
140
+ cache_prefix_marked_bytes?: number;
141
+ cache_prefix_marker_pos?: string;
142
+ cwd?: string;
143
+ is_git_repo?: boolean;
144
+ git_branch?: string;
145
+ platform?: string;
146
+ os_version?: string;
147
+ today?: string;
148
+ system_sha8?: string;
149
+ first_user_sha8?: string;
150
+ session_key?: string;
151
+ session_key_source?: 'fiche-header' | 'claude-code-header' | 'anchor';
152
+ input_tokens?: number;
153
+ output_tokens?: number;
154
+ cache_create_tokens?: number;
155
+ cache_read_tokens?: number;
156
+ /** OpenAI prompt-cache hits (subset of input_tokens), from input/prompt_tokens_details.cached_tokens. */
157
+ cached_tokens?: number;
158
+ cache_write_tokens?: number;
159
+ /** Cache_create split by tier — 1.25x (5-min) and 2x (1-hour) input rates.
160
+ * Their sum equals `cache_create_tokens` when both fields are present. */
161
+ cache_create_5m_tokens?: number;
162
+ cache_create_1h_tokens?: number;
163
+ /** Server-side web search calls billed per-request (not per-token). */
164
+ web_search_requests?: number;
165
+ /** Model stop reason ("end_turn", "tool_use", "max_tokens", "refusal", …).
166
+ * OpenAI finish_reason ("stop", "length", "content_filter", …) lands in the same field. */
167
+ stop_reason?: string;
168
+ /** True when the stop reason indicates a safety classifier fired ("refusal" /
169
+ * "content_filter"). Refusal rows emit almost no output and would otherwise
170
+ * read as "cheap" — scorers MUST fail cost comparisons on these rows, and a
171
+ * cluster of them after a transform change means the imaged prompt itself is
172
+ * tripping the classifier (see transform.ts reasoning_extraction notes). */
173
+ safety_flagged?: boolean;
174
+ /** Ground-truth output chars measured by streaming the response body ourselves — independent of
175
+ * usage.output_tokens. redacted_block_count_measured counts opaque server-encrypted blocks;
176
+ * dashboard applies a low/mid/high estimate for those. Absent on non-scannable responses. */
177
+ text_chars_measured?: number;
178
+ thinking_chars_measured?: number;
179
+ tool_use_chars_measured?: number;
180
+ redacted_block_count_measured?: number;
181
+ /** count_tokens on the ORIGINAL body (free endpoint). Absent on probe failure; excluded from savings rollup. */
182
+ baseline_tokens?: number;
183
+ /** count_tokens on the original body truncated at the last cache_control marker — gives cacheable_prefix_tokens.
184
+ * With baseline_tokens, decomposes unproxied cost into (cacheable_prefix, cold_tail). Absent when no markers. */
185
+ baseline_cacheable_tokens?: number;
186
+ /** Probe outcome. Dashboards must only attribute "$ saved" to rows where status === 'ok'. */
187
+ baseline_probe_status?: 'ok' | 'partial' | 'failed';
188
+ /** Why the baseline probe failed (HTTP status + upstream error snippet). Present only on failure. */
189
+ baseline_probe_error?: string;
190
+ /** Server-side thread continuation: the body (and so baseline_tokens) is the delta only,
191
+ * while provider usage includes the server-held thread. Probe status is 'partial'. */
192
+ thread_continue?: boolean;
193
+ error?: string;
194
+ /** First ~2 KiB of the upstream 4xx response body. */
195
+ error_body?: string;
196
+ /** sha256[0..8] of the TRANSFORMED outgoing body — correlates payloads without persisting them. */
197
+ req_body_sha8?: string;
198
+ /** Gzipped+base64 TRANSFORMED body for 4xx, inlined when ≤ TRACK_BODY_INLINE_MAX. Node host writes sidecar for larger bodies. */
199
+ req_body_sample_b64?: string;
200
+ /** Node host only: path to gzipped sidecar when inline cap exceeded. Workers drop oversized samples. */
201
+ req_body_sample_path?: string;
202
+ }
203
+ /** Max inline base64 body per JSONL row (32 KiB). Larger goes to sidecar (Node) or is dropped (Workers). */
204
+ export declare const TRACK_BODY_INLINE_MAX: number;
205
+ /** Hosts implement this to persist events. */
206
+ export interface Tracker {
207
+ emit(ev: TrackEvent): void | Promise<void>;
208
+ /** Optional: flush any buffered writes (file rotation, etc.). */
209
+ flush?(): void | Promise<void>;
210
+ }
211
+ /** Redact Bearer and `sk-*` API tokens from error/telemetry snippets before persisting or logging. */
212
+ export declare function redactSecrets(text: string): string;
213
+ /** Convert a ProxyEvent to its flat persisted shape. Shared in core so Node/Worker hosts stay in sync. */
214
+ export declare function toTrackEvent(ev: ProxyEvent): TrackEvent;
215
+ /** Writes one JSON line per event. Worker host uses console.log; Node host uses a file-backed variant. */
216
+ export declare class JsonLogTracker implements Tracker {
217
+ private readonly sink;
218
+ constructor(sink?: (line: string) => void);
219
+ emit(ev: TrackEvent): void;
220
+ }
221
+ /** Tracker that drops everything. Used when INKLING_TRACK=0. */
222
+ export declare const noopTracker: Tracker;
223
+ //# sourceMappingURL=tracker.d.ts.map