@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,2259 @@
1
+ /**
2
+ * Universal, prefix-cache-safe deterministic hygiene for tool/observation text.
3
+ *
4
+ * Grounded in multi-turn coding-agent caching findings:
5
+ * - CoACT (2026): action-preserving deterministic compression of tool outputs
6
+ * compounds quadratically across turns without breaking agent edits.
7
+ * - Prefix caching under 0.05x–0.1x reads ("Context Has a Price", 2026):
8
+ * removing or changing past observations mid-prefix busts caches, whereas a
9
+ * pure deterministic function `f(block)` applied consistently when each tool
10
+ * output enters the transcript produces byte-identical prefixes across turns
11
+ * while shrinking every cache write and subsequent cache read.
12
+ *
13
+ * Works across ALL providers and models — including text-only and weak-vision
14
+ * models (Claude 5.5, DeepSeek, Kimi, GLM, MiniMax, Qwen, Grok) where inkling
15
+ * refuses image rendering.
16
+ *
17
+ * Workers-safe: zero `node:` imports.
18
+ */
19
+ import { computeHorizonPaybackLimit, computeTailHydration, foldMarkovianEpisodes, getGlobalMmuStore, hasAnyStickyMarkovEpisode, isFileReadToolName, linkSessionSkills, pruneLowDensityBlob, } from './context-mmu.js';
20
+ import { getAllowedModelBases } from './applicability.js';
21
+ import { readBrandEnv } from './env.js';
22
+ import { createCasiIndex } from './casi-delta.js';
23
+ import { getGlobalPrefixTape, INITIAL_PREFIX_HASH, tapeHash64Hex } from './prefix-tape.js';
24
+ import { gptTokenCount, hasLongUnbrokenBpeChunk } from './gpt-tokens.js';
25
+ import { resolvePriceRates } from './pricing.js';
26
+ import { compileSegmentedStaticText, compileToolSchemas, splitVolatileXmlIslands, } from './schema-compiler.js';
27
+ import { getPinnedSessionSkills, hasStage2SealKey, isSessionCacheCold, recordStage2SealKey, setPinnedSessionSkills, } from './session-state.js';
28
+ import { planAndApplyTextEpochs, } from './text-history.js';
29
+ import { encodeToon } from './toon.js';
30
+ export { isFileReadToolName };
31
+ const MAX_HYGIENE_BLOCK_CHARS = 2 * 1024 * 1024;
32
+ const TOKEN_EXACT_LIMIT_CHARS = 16_000;
33
+ // ANSI / terminal control sequences (CSI, OSC, 2-byte ESC, BEL).
34
+ // eslint-disable-next-line no-control-regex
35
+ const OSC_RE = /\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g;
36
+ // eslint-disable-next-line no-control-regex
37
+ const CSI_RE = /\x1b\[[0-?]*[ -/]*[@-~]/g;
38
+ // eslint-disable-next-line no-control-regex
39
+ const ESC_2BYTE_RE = /\x1b[@-Z\\-_]/g;
40
+ // eslint-disable-next-line no-control-regex
41
+ const CONTROL_SCAN_RE = /[\x1b\x07\x08\r]/;
42
+ // Guards against mutating code files / diffs where whitespace or line structure
43
+ // is an Edit / apply_patch string-match anchor.
44
+ const LINE_NUMBER_RE = /^\s*\d{1,7}(?:\t|→|\s*[|\u2502](?:\s|$))/;
45
+ const ALT_LINE_NUMBER_RE = /^L\d{1,7}:\s/;
46
+ const DIFF_HEADER_RE = /^(?:diff --git |@@ -\d+(?:,\d+)? \+\d+(?:,\d+)? @@|\*\*\* (?:Begin Patch|Update File:|Add File:|Delete File:))/;
47
+ const DIFF_FILE_PAIR_RE = /^--- [^\n]+\n\+\+\+ [^\n]+/m;
48
+ const CODE_DECL_LINE_RE = /^\s*(?:(?:(?:export(?:\s+default)?|pub(?:\([^)]*\))?|public|private|protected|internal|static|final|abstract|override|readonly|sealed|open|suspend|async)\s+){0,4}(?:function\s+\w+|class\s+\w+|interface\s+\w+|record\s+\w+|protocol\s+\w+|actor\s+\w+|extension\s+\w+|namespace\s+[\w.]+|type\s+\w+\s*(?:=|struct\b|interface\b)|enum\s+\w+|struct\s+\w+|trait\s+\w+|impl\b|fn\s+\w+|func\s+(?:\([^)]*\)\s*)?\w+|def\s+\w+|(?:const|let|var|val)\s+\w+\s*(?::[^=\n]+)?=\s*(?:async\s+)?(?:\([^)]*\)\s*=>|function\b|class\b|\{|\[)|import\s+(?:\{|\*|"|\(|\w)|from\s+\S+\s+import\b|package\s+[\w.]+|using\s+[\w.]+\s*;|#include\s*[<"]|template\s*<)|(?:public|private|protected|internal)\s+(?:static\s+)?(?:final\s+)?(?:async\s+)?[A-Za-z_][\w.<>,[\]?]*\s+[A-Za-z_]\w*\s*\()/;
49
+ const STACK_PREFIX_RE = /^\s*(?:at\s+\S+\s*\(|Caused by:|File "|Traceback \(most recent call last\))/i;
50
+ const FILE_EXT_LOC_RE = /\.(?:ts|tsx|js|jsx|mjs|cjs|py|go|rs|java|c|cpp|cc|h|hpp|rb|php|cs|kt|swift):\d+\b/gi;
51
+ const TRAILING_WS_LINE_RE = /[ \t](?:\n|$)/;
52
+ const MULTI_BLANK_RE = /\n{4,}/g;
53
+ function stripAnsiSequences(raw) {
54
+ if (!raw.includes('\x1b') && !raw.includes('\x07'))
55
+ return raw;
56
+ return raw
57
+ .replace(OSC_RE, '')
58
+ .replace(CSI_RE, '')
59
+ .replace(ESC_2BYTE_RE, '')
60
+ // eslint-disable-next-line no-control-regex
61
+ .replace(/\x07/g, '');
62
+ }
63
+ function isAsciiWordChar(c) {
64
+ return (c >= 48 && c <= 57) || (c >= 65 && c <= 90) || (c >= 97 && c <= 122) || c === 95;
65
+ }
66
+ /**
67
+ * Strictly O(L) file:line matcher replacing `\b\w[\w.-]*\.ext:\d+\b` without
68
+ * catastrophic O(L^2) backtracking on long dotted/hyphenated lines.
69
+ */
70
+ function hasFileLineLocation(line) {
71
+ if (!line.includes(':'))
72
+ return false;
73
+ FILE_EXT_LOC_RE.lastIndex = 0;
74
+ let m;
75
+ while ((m = FILE_EXT_LOC_RE.exec(line)) !== null) {
76
+ let sawWord = false;
77
+ for (let i = m.index - 1; i >= 0; i--) {
78
+ const c = line.charCodeAt(i);
79
+ if (isAsciiWordChar(c)) {
80
+ sawWord = true;
81
+ }
82
+ else if (c !== 46 && c !== 45) {
83
+ break;
84
+ }
85
+ }
86
+ if (sawWord)
87
+ return true;
88
+ }
89
+ return false;
90
+ }
91
+ const CRITICAL_LOG_KEYWORD_RE = /\b(?:error|err|warn|warning|fail|failed|failure|fatal|panic|exception|traceback|assertion|assert|denied|forbidden|timeout|timed out|refused|oom|killed|segfault|abort|aborted|passed|skipped|summary|exit[_ ]?code(?:[=:\s]+[1-9]\d*)?|returned [1-9]\d*|[A-Za-z_]\w*(?:Error|Exception|Fault|Failure)|ECONNREFUSED|ENOENT|ETIMEDOUT|EACCES|EPERM|EADDRINUSE|EPIPE|EISDIR|ENOSPC)\b|\b(?:status[=:\s]+|HTTP\/\d(?:\.\d)?["'\s]+)[45]\d\d\b/i;
92
+ /**
93
+ * Resolve text-hygiene activation mode from call options and `INKLING_TEXT_HYGIENE`.
94
+ * - Explicit option/env `on`/`true` activates even when `INKLING_MODELS=off`.
95
+ * - Explicit option/env `off`/`false` disables completely.
96
+ * - `auto` (default) is active whenever `INKLING_MODELS` has any model enabled.
97
+ */
98
+ export function resolveTextHygieneMode(opt) {
99
+ if (opt === true || opt === 'on')
100
+ return 'on';
101
+ if (opt === false || opt === 'off')
102
+ return 'off';
103
+ const raw = readBrandEnv('TEXT_HYGIENE') ?? '';
104
+ const norm = raw.trim().toLowerCase();
105
+ if (/^(1|true|on|yes)$/i.test(norm))
106
+ return 'on';
107
+ if (/^(0|false|off|no|none)$/i.test(norm))
108
+ return 'off';
109
+ return 'auto';
110
+ }
111
+ export function isTextHygieneActive(opt) {
112
+ const mode = resolveTextHygieneMode(opt);
113
+ if (mode === 'off')
114
+ return false;
115
+ if (mode === 'on')
116
+ return true;
117
+ return getAllowedModelBases().length > 0;
118
+ }
119
+ function estimateTokensSaved(original, cleaned) {
120
+ const charDelta = original.length - cleaned.length;
121
+ if (charDelta <= 0)
122
+ return 0;
123
+ // Pure-JS BPE is quadratic on huge strings or long unbroken BPE chunks.
124
+ if (original.length <= TOKEN_EXACT_LIMIT_CHARS &&
125
+ !hasLongUnbrokenBpeChunk(original) &&
126
+ !hasLongUnbrokenBpeChunk(cleaned)) {
127
+ const before = gptTokenCount(original);
128
+ const after = gptTokenCount(cleaned);
129
+ if (before > 0 && after >= 0) {
130
+ return Math.max(0, before - after);
131
+ }
132
+ }
133
+ return Math.max(1, Math.round(charDelta / 3.5));
134
+ }
135
+ function isAsciiWs(c) {
136
+ return c === 32 || c === 9 || c === 10 || c === 11 || c === 12 || c === 13 || c === 160;
137
+ }
138
+ /**
139
+ * Edit/Action-Preservation Safety Guard:
140
+ * Protects source-code file reads, unified diffs, and code-fence-heavy outputs so
141
+ * Edit / apply_patch exact string matching never loses whitespace or repeated lines.
142
+ * Strips ANSI escapes first so colored git diffs, bat, and ripgrep stay protected.
143
+ */
144
+ export function isCodeOrDiffProtected(text) {
145
+ if (!text)
146
+ return false;
147
+ const scan = stripAnsiSequences(text);
148
+ if (scan.includes('\n+++ ') && DIFF_FILE_PAIR_RE.test(scan))
149
+ return true;
150
+ const hasBackticks = scan.includes('```');
151
+ let numberedLines = 0;
152
+ let codeDecls = 0;
153
+ let fencedLines = 0;
154
+ let inFence = false;
155
+ let diffHeaders = 0;
156
+ let lineIdx = 0;
157
+ let start = 0;
158
+ const len = scan.length;
159
+ while (start <= len) {
160
+ const nl = scan.indexOf('\n', start);
161
+ const end = nl < 0 ? len : nl;
162
+ const line = scan.slice(start, end);
163
+ if (lineIdx < 200) {
164
+ if (LINE_NUMBER_RE.test(line) || ALT_LINE_NUMBER_RE.test(line)) {
165
+ numberedLines++;
166
+ if (numberedLines >= 3)
167
+ return true;
168
+ }
169
+ if (DIFF_HEADER_RE.test(line)) {
170
+ if (line.startsWith('diff --git ') ||
171
+ line.startsWith('*** Begin Patch') ||
172
+ line.startsWith('*** Update File:')) {
173
+ return true;
174
+ }
175
+ diffHeaders++;
176
+ if (diffHeaders >= 2)
177
+ return true;
178
+ }
179
+ if (lineIdx < 100 && CODE_DECL_LINE_RE.test(line)) {
180
+ codeDecls++;
181
+ if (codeDecls >= 3)
182
+ return true;
183
+ }
184
+ }
185
+ else if (!hasBackticks) {
186
+ return false;
187
+ }
188
+ if (hasBackticks) {
189
+ let ws = 0;
190
+ while (ws < line.length && isAsciiWs(line.charCodeAt(ws)))
191
+ ws++;
192
+ if (ws + 2 < line.length &&
193
+ line.charCodeAt(ws) === 96 &&
194
+ line.charCodeAt(ws + 1) === 96 &&
195
+ line.charCodeAt(ws + 2) === 96) {
196
+ inFence = !inFence;
197
+ fencedLines++;
198
+ }
199
+ else if (inFence) {
200
+ fencedLines++;
201
+ }
202
+ }
203
+ lineIdx++;
204
+ if (nl < 0)
205
+ break;
206
+ start = nl + 1;
207
+ }
208
+ return hasBackticks && lineIdx > 0 && fencedLines / lineIdx >= 0.3;
209
+ }
210
+ /** Simulate carriage returns and backspaces within one terminal line cleanly. */
211
+ function resolveTerminalLine(line) {
212
+ let active = line;
213
+ if (active.includes('\r')) {
214
+ const segs = active.split('\r');
215
+ // Pick the final non-whitespace overwritten progress frame, falling back to last non-empty.
216
+ let chosen = '';
217
+ for (let i = segs.length - 1; i >= 0; i--) {
218
+ if (segs[i].trim().length > 0) {
219
+ chosen = segs[i];
220
+ break;
221
+ }
222
+ }
223
+ if (!chosen) {
224
+ for (let i = segs.length - 1; i >= 0; i--) {
225
+ if (segs[i].length > 0) {
226
+ chosen = segs[i];
227
+ break;
228
+ }
229
+ }
230
+ }
231
+ active = chosen;
232
+ }
233
+ if (!active.includes('\x08'))
234
+ return active;
235
+ const chars = [];
236
+ for (let i = 0; i < active.length; i++) {
237
+ const ch = active[i];
238
+ if (ch === '\x08') {
239
+ if (chars.length > 0)
240
+ chars.pop();
241
+ }
242
+ else {
243
+ chars.push(ch);
244
+ }
245
+ }
246
+ return chars.join('');
247
+ }
248
+ function stripTrailingLineWsLinear(text) {
249
+ const parts = [];
250
+ let segStart = 0;
251
+ let i = 0;
252
+ const len = text.length;
253
+ while (true) {
254
+ const nl = text.indexOf('\n', i);
255
+ const lineEnd = nl < 0 ? len : nl;
256
+ let trimEnd = lineEnd;
257
+ while (trimEnd > i) {
258
+ const c = text.charCodeAt(trimEnd - 1);
259
+ if (c === 32 || c === 9)
260
+ trimEnd--;
261
+ else
262
+ break;
263
+ }
264
+ if (trimEnd < lineEnd) {
265
+ parts.push(text.slice(segStart, trimEnd));
266
+ segStart = lineEnd;
267
+ }
268
+ if (nl < 0)
269
+ break;
270
+ i = nl + 1;
271
+ }
272
+ if (parts.length === 0)
273
+ return text;
274
+ parts.push(text.slice(segStart));
275
+ return parts.join('');
276
+ }
277
+ function emulateTerminal(ansiStripped, codeProtected, hasAnsi) {
278
+ const hasBareCrOrBs = ansiStripped.includes('\x08') ||
279
+ (() => {
280
+ let idx = ansiStripped.indexOf('\r');
281
+ while (idx >= 0) {
282
+ if (ansiStripped.charCodeAt(idx + 1) !== 10)
283
+ return true;
284
+ idx = ansiStripped.indexOf('\r', idx + 1);
285
+ }
286
+ return false;
287
+ })();
288
+ // On guarded code/diff reads, never touch CR/LF normalization or indentation/trailing spaces
289
+ // beyond literal ANSI escape codes so exact Edit anchors remain intact.
290
+ if (codeProtected) {
291
+ return {
292
+ text: ansiStripped,
293
+ changed: hasAnsi,
294
+ strippedAnsi: hasAnsi,
295
+ strippedCr: false,
296
+ };
297
+ }
298
+ const normalizedLf = ansiStripped.includes('\r\n') ? ansiStripped.replace(/\r\n/g, '\n') : ansiStripped;
299
+ let resolved = normalizedLf;
300
+ if (hasBareCrOrBs) {
301
+ const resolvedLines = normalizedLf.split('\n').map(resolveTerminalLine);
302
+ resolved = resolvedLines.join('\n');
303
+ }
304
+ // Trailing whitespace trim + 4+ blank line collapse (skip allocation entirely when clean).
305
+ const hasTrailingWs = TRAILING_WS_LINE_RE.test(resolved);
306
+ const hasMultiBlank = resolved.includes('\n\n\n\n');
307
+ let trimmedLines = resolved;
308
+ if (hasTrailingWs)
309
+ trimmedLines = stripTrailingLineWsLinear(trimmedLines);
310
+ if (hasMultiBlank)
311
+ trimmedLines = trimmedLines.replace(MULTI_BLANK_RE, '\n\n\n');
312
+ const pureWsSaved = resolved.length - trimmedLines.length;
313
+ const keepWsTrim = hasAnsi ||
314
+ hasBareCrOrBs ||
315
+ (pureWsSaved >= 128 && trimmedLines.length <= resolved.length * 0.95);
316
+ const out = keepWsTrim ? trimmedLines : resolved;
317
+ return {
318
+ text: out,
319
+ changed: hasAnsi || out !== ansiStripped,
320
+ strippedAnsi: hasAnsi,
321
+ strippedCr: hasBareCrOrBs && resolved !== normalizedLf,
322
+ };
323
+ }
324
+ /** Losslessly convert tabular JSON to `@toon` or minify pretty-printed JSON objects/arrays. */
325
+ function encodeStructuredJson(text, _aggressiveToon, enableToon = true) {
326
+ const hasNewline = text.includes('\n');
327
+ if (text.length < 256)
328
+ return null;
329
+ let start = 0;
330
+ let end = text.length;
331
+ while (start < end && isAsciiWs(text.charCodeAt(start)))
332
+ start++;
333
+ while (end > start && isAsciiWs(text.charCodeAt(end - 1)))
334
+ end--;
335
+ if (end - start < 2)
336
+ return null;
337
+ const first = text.charCodeAt(start);
338
+ const last = text.charCodeAt(end - 1);
339
+ if (!((first === 123 && last === 125) || (first === 91 && last === 93))) {
340
+ return null;
341
+ }
342
+ const trimmed = start === 0 && end === text.length ? text : text.slice(start, end);
343
+ try {
344
+ const parsed = JSON.parse(trimmed);
345
+ if (parsed === null || typeof parsed !== 'object')
346
+ return null;
347
+ const minJsonBox = {};
348
+ if (enableToon) {
349
+ const toon = encodeToon(parsed, minJsonBox);
350
+ if (toon !== null && toon.length < text.length) {
351
+ return { text: toon, stage: 'toon' };
352
+ }
353
+ }
354
+ if (!hasNewline)
355
+ return null;
356
+ const min = minJsonBox.json ?? JSON.stringify(parsed);
357
+ if (!min)
358
+ return null;
359
+ if (text.length - min.length < 120)
360
+ return null;
361
+ if (min.length > text.length * 0.85)
362
+ return null;
363
+ return { text: min, stage: 'json' };
364
+ }
365
+ catch {
366
+ return null;
367
+ }
368
+ }
369
+ const DIR_ENTRY_RE = /^((?:[MADRCU?!]{1,2}\s+)?)(?:\.\/)?((?:[A-Za-z0-9_@.~-]+\/)+)([A-Za-z0-9_@.~-]+\/?)$/;
370
+ const DIR_LEAF_RE = /^((?:[MADRCU?!]{1,2}\s+)?)[A-Za-z0-9_@.~-]+\.[A-Za-z0-9]{1,12}$/;
371
+ /**
372
+ * Losslessly group repetitive directory/file-tree listings (`>= 12` entries, `>= 600` chars)
373
+ * that share parent directories into `<dir>/: fileA, fileB, ...`. Preserves git status
374
+ * prefixes per group and never triggers on code, diffs, logs, or prose.
375
+ */
376
+ function compactDirectoryListing(text) {
377
+ if (text.length < 600 || text.length > MAX_HYGIENE_BLOCK_CHARS)
378
+ return null;
379
+ if (isJsonWrappedFast(text))
380
+ return null;
381
+ const lines = text.split('\n');
382
+ const nonEmpty = [];
383
+ for (const l of lines) {
384
+ const t = l.trim();
385
+ if (t)
386
+ nonEmpty.push(t);
387
+ }
388
+ if (nonEmpty.length < 12)
389
+ return null;
390
+ let pathHits = 0;
391
+ let slashHits = 0;
392
+ const parsed = [];
393
+ for (const entry of nonEmpty) {
394
+ if (/^(?:diff --git |@@ -\d|\*\*\* (?:Begin Patch|Update File|Add File))/.test(entry) ||
395
+ STACK_PREFIX_RE.test(entry) ||
396
+ entry.length > 260) {
397
+ return null;
398
+ }
399
+ const m = DIR_ENTRY_RE.exec(entry);
400
+ if (m) {
401
+ pathHits += 1;
402
+ slashHits += 1;
403
+ const prefix = m[1] ?? '';
404
+ const dir = m[2].replace(/\/+$/, '');
405
+ const leaf = m[3];
406
+ parsed.push({ kind: 'dir', key: `${prefix}\0${dir}`, prefix, dir, leaf, raw: entry });
407
+ continue;
408
+ }
409
+ if (DIR_LEAF_RE.test(entry)) {
410
+ pathHits += 1;
411
+ }
412
+ parsed.push({ kind: 'raw', raw: entry });
413
+ }
414
+ if (pathHits / nonEmpty.length < 0.8 || slashHits / nonEmpty.length < 0.6)
415
+ return null;
416
+ const groupLeaves = new Map();
417
+ for (const item of parsed) {
418
+ if (item.kind !== 'dir')
419
+ continue;
420
+ let g = groupLeaves.get(item.key);
421
+ if (!g) {
422
+ g = { prefix: item.prefix, dir: item.dir, leaves: [] };
423
+ groupLeaves.set(item.key, g);
424
+ }
425
+ g.leaves.push(item.leaf);
426
+ }
427
+ const emittedGroup = new Set();
428
+ const out = [];
429
+ let hasGrouped = false;
430
+ for (const item of parsed) {
431
+ if (item.kind === 'raw') {
432
+ out.push(item.raw);
433
+ continue;
434
+ }
435
+ const g = groupLeaves.get(item.key);
436
+ if (g.leaves.length < 2) {
437
+ out.push(item.raw);
438
+ continue;
439
+ }
440
+ if (emittedGroup.has(item.key))
441
+ continue;
442
+ emittedGroup.add(item.key);
443
+ hasGrouped = true;
444
+ out.push(`${g.prefix}${g.dir}/: ${g.leaves.join(', ')}`);
445
+ }
446
+ if (!hasGrouped)
447
+ return null;
448
+ const candidate = out.join('\n');
449
+ if (text.length - candidate.length < 150 || candidate.length > text.length * 0.82) {
450
+ return null;
451
+ }
452
+ return candidate;
453
+ }
454
+ /** Parameterize variable tokens into a Drain-style structural template for repetition detection. */
455
+ function drainTemplate(line) {
456
+ const s = line.trim();
457
+ if (!s)
458
+ return '<EMPTY>';
459
+ return s
460
+ // UUIDs
461
+ .replace(/\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi, '<UUID>')
462
+ // ISO timestamps & HH:MM:SS.sss
463
+ .replace(/\b\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})?\b/g, '<TS>')
464
+ .replace(/\b\d{2}:\d{2}:\d{2}(?:\.\d+)?\b/g, '<TIME>')
465
+ // IPv4 + optional port
466
+ .replace(/\b\d{1,3}(?:\.\d{1,3}){3}(?::\d+)?\b/g, '<IP>')
467
+ // Hex addresses / digests >= 8 hex chars
468
+ .replace(/\b0x[0-9a-f]+\b/gi, '<HEX>')
469
+ .replace(/\b[0-9a-f]{8,}\b/gi, '<HEX>')
470
+ // Durations & byte sizes
471
+ .replace(/\b\d+(?:\.\d+)?\s*(?:ns|us|µs|ms|s|m|h|B|KB|KiB|MB|MiB|GB|GiB)\b/gi, '<UNIT>')
472
+ // Remaining integers / decimals
473
+ .replace(/\b\d+(?:\.\d+)?\b/g, '<NUM>');
474
+ }
475
+ const LOG_ISO_TS_RE = /\b\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}/;
476
+ const LOG_CLOCK_TS_RE = /(?:^|[\s\[])\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:\]|[\s,:])/;
477
+ const LOG_LEVEL_RE = /\b(?:INFO|DEBUG|TRACE|VERBOSE|NOTICE|LOG)\b/;
478
+ const LOG_HTTP_RE = /\b(?:GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\s+\/\S*/;
479
+ const LOG_RUNNER_RE = /^\s*(?:[✓✔]\s|(?:PASS|OK|RUN|Compiling|Downloading|Fetching|Resolving|Checking|Installing|Building|Bundling|Built|Transformed|Rendered)\b|\[\d+\/\d+\]\s|·+$)|(?:\.\.\.\s*ok\s*(?:\([^)\n]+\))?$|\bok\s+\S+\s+\d+(?:\.\d+)?(?:ms|s)\s*$)/;
480
+ const PASSING_PROGRESS_RE = /^\s*(?:[✓✔]\s|(?:PASS|Compiling|Downloading|Fetching|Resolving|Checking|Installing|Building|Bundling)\b|\[\d+\/\d+\]\s|·+$)|(?:\.\.\.\s*ok\s*(?:\([^)\n]+\))?$|\bok\s+\S+\s+\d+(?:\.\d+)?(?:ms|s)\s*$)/;
481
+ const FAIL_OR_SUMMARY_RE = /\b(?:error|err|warn|warning|fail|failed|failure|fatal|panic|exception|traceback|assertion|assert|denied|forbidden|timeout|timed out|refused|oom|killed|segfault|abort|aborted|skipped|summary|Tests?\s+\d|Test Files\s+\d)\b/i;
482
+ function isLogShapedLine(line) {
483
+ return (LOG_ISO_TS_RE.test(line) ||
484
+ LOG_CLOCK_TS_RE.test(line) ||
485
+ LOG_LEVEL_RE.test(line) ||
486
+ LOG_HTTP_RE.test(line) ||
487
+ LOG_RUNNER_RE.test(line));
488
+ }
489
+ function isAnchorLine(line, index, total) {
490
+ if (index < 5 || index >= total - 15)
491
+ return true;
492
+ if (!line.trim())
493
+ return false;
494
+ if (CRITICAL_LOG_KEYWORD_RE.test(line))
495
+ return true;
496
+ if (STACK_PREFIX_RE.test(line) || hasFileLineLocation(line))
497
+ return true;
498
+ if (!isLogShapedLine(line))
499
+ return true;
500
+ return false;
501
+ }
502
+ function isJsonWrappedFast(text) {
503
+ let start = 0;
504
+ let end = text.length;
505
+ while (start < end && isAsciiWs(text.charCodeAt(start)))
506
+ start++;
507
+ while (end > start && isAsciiWs(text.charCodeAt(end - 1)))
508
+ end--;
509
+ if (end - start < 2)
510
+ return false;
511
+ const first = text.charCodeAt(start);
512
+ const last = text.charCodeAt(end - 1);
513
+ return (first === 123 && last === 125) || (first === 91 && last === 93);
514
+ }
515
+ /**
516
+ * Drain-inspired structural log-template folder:
517
+ * - Preserves first/last context lines, all error/warning/test summary/stack lines.
518
+ * - Collapses contiguous runs (>=4) and global high-frequency boilerplate (>=12) of
519
+ * structurally identical template lines with explicit `[... K similar lines folded ...]`.
520
+ */
521
+ function foldRepetitiveLogs(text) {
522
+ if (text.length < 1024 || isJsonWrappedFast(text)) {
523
+ // Do not mangle structured JSON blobs if minification declined them.
524
+ return null;
525
+ }
526
+ const lines = text.split('\n');
527
+ if (lines.length < 25)
528
+ return null;
529
+ const total = lines.length;
530
+ const anchored = new Uint8Array(total);
531
+ const templates = new Array(total);
532
+ const freq = new Map();
533
+ for (let i = 0; i < total; i++) {
534
+ const line = lines[i];
535
+ if (isAnchorLine(line, i, total)) {
536
+ anchored[i] = 1;
537
+ templates[i] = '';
538
+ }
539
+ else {
540
+ const tpl = drainTemplate(line);
541
+ templates[i] = tpl;
542
+ if (tpl !== '<EMPTY>') {
543
+ freq.set(tpl, (freq.get(tpl) ?? 0) + 1);
544
+ }
545
+ }
546
+ }
547
+ const keep = new Uint8Array(total);
548
+ keep.fill(1);
549
+ // Pass A: contiguous runs of >= 4 identical templates (bridging blank <EMPTY> separators; keep first 2, last 1).
550
+ let runStart = 0;
551
+ while (runStart < total) {
552
+ if (anchored[runStart] || templates[runStart] === '<EMPTY>') {
553
+ runStart++;
554
+ continue;
555
+ }
556
+ const tpl = templates[runStart];
557
+ const runIndices = [runStart];
558
+ let runEnd = runStart + 1;
559
+ while (runEnd < total &&
560
+ !anchored[runEnd] &&
561
+ (templates[runEnd] === tpl || templates[runEnd] === '<EMPTY>')) {
562
+ if (templates[runEnd] === tpl)
563
+ runIndices.push(runEnd);
564
+ runEnd++;
565
+ }
566
+ if (runIndices.length >= 4) {
567
+ const keepHeadEnd = runIndices[1];
568
+ const keepTailStart = runIndices[runIndices.length - 1];
569
+ for (let k = keepHeadEnd + 1; k < keepTailStart; k++) {
570
+ keep[k] = 0;
571
+ }
572
+ }
573
+ runStart = runIndices[runIndices.length - 1] + 1;
574
+ }
575
+ // Pass B: globally repetitive non-anchored templates (>= 12 times: keep first 3 + last 2).
576
+ const highFreqPositions = new Map();
577
+ for (let i = 0; i < total; i++) {
578
+ const tpl = templates[i];
579
+ if (!tpl || tpl === '<EMPTY>' || (freq.get(tpl) ?? 0) < 12)
580
+ continue;
581
+ let list = highFreqPositions.get(tpl);
582
+ if (!list) {
583
+ list = [];
584
+ highFreqPositions.set(tpl, list);
585
+ }
586
+ list.push(i);
587
+ }
588
+ for (const positions of highFreqPositions.values()) {
589
+ for (let j = 3; j < positions.length - 2; j++) {
590
+ keep[positions[j]] = 0;
591
+ }
592
+ }
593
+ // Pass B2: fold contiguous passing/progress runs (>= 8 lines: keep first 2 + last 2)
594
+ // even when individual test names vary, while preserving every error/warning/summary line.
595
+ const isPassingProgress = new Uint8Array(total);
596
+ for (let i = 0; i < total; i++) {
597
+ const line = lines[i];
598
+ if (PASSING_PROGRESS_RE.test(line) && !FAIL_OR_SUMMARY_RE.test(line)) {
599
+ isPassingProgress[i] = 1;
600
+ }
601
+ }
602
+ let pIdx = 0;
603
+ while (pIdx < total) {
604
+ if (!isPassingProgress[pIdx]) {
605
+ pIdx++;
606
+ continue;
607
+ }
608
+ const runIndices = [pIdx];
609
+ let pEnd = pIdx + 1;
610
+ while (pEnd < total && (isPassingProgress[pEnd] || templates[pEnd] === '<EMPTY>')) {
611
+ if (isPassingProgress[pEnd])
612
+ runIndices.push(pEnd);
613
+ pEnd++;
614
+ }
615
+ if (runIndices.length >= 8) {
616
+ const keepHeadEnd = runIndices[1];
617
+ const keepTailStart = runIndices[runIndices.length - 2];
618
+ for (let k = keepHeadEnd + 1; k < keepTailStart; k++) {
619
+ keep[k] = 0;
620
+ }
621
+ }
622
+ pIdx = runIndices[runIndices.length - 1] + 1;
623
+ }
624
+ // Pass C: collapse <EMPTY> blank lines sandwiched inside any folded span.
625
+ let prevNonEmptyKept = true;
626
+ for (let i = 0; i < total; i++) {
627
+ if (templates[i] !== '<EMPTY>') {
628
+ prevNonEmptyKept = keep[i] === 1;
629
+ continue;
630
+ }
631
+ if (keep[i] === 0 || prevNonEmptyKept)
632
+ continue;
633
+ let j = i + 1;
634
+ while (j < total && templates[j] === '<EMPTY>')
635
+ j++;
636
+ const nextNonEmptyKept = j < total ? keep[j] === 1 : true;
637
+ if (!nextNonEmptyKept) {
638
+ for (let k = i; k < j; k++)
639
+ keep[k] = 0;
640
+ }
641
+ i = j - 1;
642
+ }
643
+ const out = [];
644
+ let foldedCount = 0;
645
+ const flushFolded = () => {
646
+ if (foldedCount > 0) {
647
+ out.push(`[... ${foldedCount} similar lines folded ...]`);
648
+ foldedCount = 0;
649
+ }
650
+ };
651
+ for (let i = 0; i < total; i++) {
652
+ if (keep[i]) {
653
+ flushFolded();
654
+ out.push(lines[i]);
655
+ }
656
+ else {
657
+ // Collapse blank lines engulfed inside a folded region cleanly.
658
+ if (templates[i] !== '<EMPTY>') {
659
+ foldedCount++;
660
+ }
661
+ }
662
+ }
663
+ flushFolded();
664
+ const candidate = out.join('\n');
665
+ const saved = text.length - candidate.length;
666
+ if (saved < 256 || candidate.length > text.length * 0.75) {
667
+ return null;
668
+ }
669
+ return candidate;
670
+ }
671
+ const NESTED_JSON_FIELDS = [
672
+ 'output',
673
+ 'stdout',
674
+ 'stderr',
675
+ 'content',
676
+ 'result',
677
+ 'body',
678
+ 'text',
679
+ 'data',
680
+ ];
681
+ const MAX_SEED_STRING_CHARS = 512_000;
682
+ const MIN_SEED_STRING_CHARS = 400;
683
+ const MIN_USER_CLEAN_CHARS = 1500;
684
+ function estimateTokenPairSameRegime(before, after) {
685
+ if (before.length <= TOKEN_EXACT_LIMIT_CHARS &&
686
+ after.length <= TOKEN_EXACT_LIMIT_CHARS &&
687
+ !hasLongUnbrokenBpeChunk(before) &&
688
+ !hasLongUnbrokenBpeChunk(after)) {
689
+ return [gptTokenCount(before), gptTokenCount(after)];
690
+ }
691
+ return [Math.ceil(before.length / 3.5), Math.ceil(after.length / 3.5)];
692
+ }
693
+ function meetsUnwrapTokenGate(before, after) {
694
+ if (after.length >= before.length)
695
+ return false;
696
+ const [beforeTokens, afterTokens] = estimateTokenPairSameRegime(before, after);
697
+ const savedTokens = beforeTokens - afterTokens;
698
+ return savedTokens >= 40 && afterTokens <= beforeTokens * 0.85;
699
+ }
700
+ function countNewlinesAndQuotes(s) {
701
+ let count = 0;
702
+ for (let i = 0; i < s.length; i++) {
703
+ const c = s.charCodeAt(i);
704
+ if (c === 10 || c === 34)
705
+ count++;
706
+ }
707
+ return count;
708
+ }
709
+ /**
710
+ * Unwrap JSON tool envelopes that double-serialize inner JSON payloads or wrap
711
+ * 1-2 heavily escaped multi-line string fields into `@toon` / `@fiche-kv` / clean JSON.
712
+ * Keeps result only when net tokens drop by >=15% and >=40 tokens.
713
+ */
714
+ const SHELL_TOOL_RE = /^(?:bash|sh|zsh|shell|run_command|exec)$/i;
715
+ const CONFIG_JSON_KEYS = new Set([
716
+ 'compilerOptions',
717
+ 'dependencies',
718
+ 'devDependencies',
719
+ 'peerDependencies',
720
+ 'scripts',
721
+ 'workspaces',
722
+ ]);
723
+ function looksLikeConfigFixture(innerParsed, rawInner, toolName) {
724
+ if (!innerParsed || typeof innerParsed !== 'object' || Array.isArray(innerParsed))
725
+ return false;
726
+ const isShell = typeof toolName === 'string' && SHELL_TOOL_RE.test(toolName.trim());
727
+ const keys = Object.keys(innerParsed);
728
+ const hasConfigKey = keys.some((k) => CONFIG_JSON_KEYS.has(k));
729
+ if (!hasConfigKey)
730
+ return false;
731
+ return isShell || (rawInner.includes('\n') && rawInner.length >= 256);
732
+ }
733
+ export function unwrapNestedJsonStrings(text, opts) {
734
+ if (typeof text !== 'string' || text.length < 256 || text.length > MAX_HYGIENE_BLOCK_CHARS) {
735
+ return null;
736
+ }
737
+ let start = 0;
738
+ let end = text.length;
739
+ while (start < end && isAsciiWs(text.charCodeAt(start)))
740
+ start++;
741
+ while (end > start && isAsciiWs(text.charCodeAt(end - 1)))
742
+ end--;
743
+ if (end - start < 256)
744
+ return null;
745
+ if (text.charCodeAt(start) !== 123 || text.charCodeAt(end - 1) !== 125)
746
+ return null;
747
+ const trimmed = start === 0 && end === text.length ? text : text.slice(start, end);
748
+ if (!trimmed.includes('\\"') &&
749
+ !trimmed.includes('\\n') &&
750
+ !trimmed.includes('\\u') &&
751
+ !trimmed.includes('"[') &&
752
+ !trimmed.includes('"{')) {
753
+ return null;
754
+ }
755
+ let parsed;
756
+ try {
757
+ parsed = JSON.parse(trimmed);
758
+ }
759
+ catch {
760
+ return null;
761
+ }
762
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
763
+ return null;
764
+ const obj = parsed;
765
+ // Branch A: Long string field containing valid nested JSON object/array.
766
+ let unwrappedObj;
767
+ let unwrappedCount = 0;
768
+ let singleUnwrappedKey;
769
+ let singleInnerParsed;
770
+ const unwrappedFields = new Set();
771
+ const unwrappedEntries = [];
772
+ for (const field of NESTED_JSON_FIELDS) {
773
+ const val = obj[field];
774
+ if (typeof val !== 'string' || val.length < 256)
775
+ continue;
776
+ const innerTrim = val.trim();
777
+ const first = innerTrim.charCodeAt(0);
778
+ const last = innerTrim.charCodeAt(innerTrim.length - 1);
779
+ if (!((first === 123 && last === 125) || (first === 91 && last === 93)))
780
+ continue;
781
+ let innerParsed;
782
+ try {
783
+ innerParsed = JSON.parse(innerTrim);
784
+ }
785
+ catch {
786
+ continue;
787
+ }
788
+ if (!innerParsed || typeof innerParsed !== 'object')
789
+ continue;
790
+ if (looksLikeConfigFixture(innerParsed, val, opts?.toolName))
791
+ continue;
792
+ if (!unwrappedObj)
793
+ unwrappedObj = { ...obj };
794
+ unwrappedObj[field] = innerParsed;
795
+ unwrappedFields.add(field);
796
+ unwrappedEntries.push([field, innerParsed]);
797
+ unwrappedCount++;
798
+ if (unwrappedCount === 1) {
799
+ singleUnwrappedKey = field;
800
+ singleInnerParsed = innerParsed;
801
+ }
802
+ }
803
+ if (unwrappedObj && unwrappedCount > 0) {
804
+ if (opts?.enableToon !== false) {
805
+ const toonWhole = encodeToon(unwrappedObj);
806
+ if (toonWhole !== null && meetsUnwrapTokenGate(text, toonWhole)) {
807
+ return { text: toonWhole, stage: 'toon' };
808
+ }
809
+ if (unwrappedCount === 1 && singleUnwrappedKey && singleInnerParsed !== undefined) {
810
+ const toonInner = encodeToon(singleInnerParsed);
811
+ if (toonInner !== null) {
812
+ const kvLines = ['@fiche-kv'];
813
+ for (const k of Object.keys(obj)) {
814
+ if (k === singleUnwrappedKey || obj[k] === undefined)
815
+ continue;
816
+ kvLines.push(`${k}: ${JSON.stringify(obj[k])}`);
817
+ }
818
+ kvLines.push(`--- ${singleUnwrappedKey} (json-string) ---`);
819
+ kvLines.push(toonInner);
820
+ const framed = kvLines.join('\n');
821
+ if (meetsUnwrapTokenGate(text, framed)) {
822
+ return { text: framed, stage: 'toon' };
823
+ }
824
+ }
825
+ }
826
+ }
827
+ // Frame unwrapped string fields explicitly so the model never confuses string
828
+ // fields with native objects when downstream JSON consumers parse strings.
829
+ const kvLines = ['@fiche-kv'];
830
+ for (const k of Object.keys(obj)) {
831
+ if (unwrappedFields.has(k) || obj[k] === undefined)
832
+ continue;
833
+ kvLines.push(`${k}: ${JSON.stringify(obj[k])}`);
834
+ }
835
+ for (const [field, innerVal] of unwrappedEntries) {
836
+ kvLines.push(`--- ${field} (json-string) ---`);
837
+ try {
838
+ kvLines.push(JSON.stringify(innerVal));
839
+ }
840
+ catch {
841
+ kvLines.push(String(obj[field] ?? ''));
842
+ }
843
+ }
844
+ const framed = kvLines.join('\n');
845
+ if (meetsUnwrapTokenGate(text, framed)) {
846
+ return { text: framed, stage: 'json_unwrap' };
847
+ }
848
+ }
849
+ // Branch B: Small JSON envelope (<= 6 keys) wrapping 1-2 heavily escaped multi-line fields.
850
+ const keys = Object.keys(obj).filter((k) => obj[k] !== undefined);
851
+ if (keys.length >= 1 && keys.length <= 6) {
852
+ const heavyKeys = [];
853
+ let totalEscapeWaste = 0;
854
+ for (const k of keys) {
855
+ const v = obj[k];
856
+ if (typeof v !== 'string')
857
+ continue;
858
+ if (countNewlinesAndQuotes(v) < 4)
859
+ continue;
860
+ const escapeWaste = JSON.stringify(v).length - 2 - v.length;
861
+ heavyKeys.push(k);
862
+ totalEscapeWaste += escapeWaste;
863
+ }
864
+ if (heavyKeys.length >= 1 && heavyKeys.length <= 2 && totalEscapeWaste >= 128) {
865
+ const heavySet = new Set(heavyKeys);
866
+ const outLines = ['@fiche-kv'];
867
+ for (const k of keys) {
868
+ if (heavySet.has(k))
869
+ continue;
870
+ outLines.push(`${k}: ${JSON.stringify(obj[k])}`);
871
+ }
872
+ const foldLogs = opts?.foldLogs !== false;
873
+ for (const k of heavyKeys) {
874
+ const rawBody = obj[k];
875
+ const ansiStripped = stripAnsiSequences(rawBody);
876
+ const bodyProtected = isCodeOrDiffProtected(ansiStripped);
877
+ const term = emulateTerminal(ansiStripped, bodyProtected, ansiStripped !== rawBody);
878
+ let bodyOut = term.text;
879
+ if (!bodyProtected && foldLogs) {
880
+ const folded = foldRepetitiveLogs(bodyOut);
881
+ if (folded !== null)
882
+ bodyOut = folded;
883
+ }
884
+ outLines.push(`--- ${k} ---`);
885
+ outLines.push(bodyOut);
886
+ }
887
+ const candidate = outLines.join('\n');
888
+ if (meetsUnwrapTokenGate(text, candidate)) {
889
+ return { text: candidate, stage: 'json_unwrap' };
890
+ }
891
+ }
892
+ }
893
+ return null;
894
+ }
895
+ function cleanToolOutputCore(text, opts) {
896
+ if (typeof text !== 'string' || text.length === 0 || text.length > MAX_HYGIENE_BLOCK_CHARS) {
897
+ return { text, changed: false, stages: [] };
898
+ }
899
+ if (text.length < 256 && !CONTROL_SCAN_RE.test(text)) {
900
+ return { text, changed: false, stages: [] };
901
+ }
902
+ // Strip ANSI first so colored diffs, bat pipes, and ripgrep results stay code-protected.
903
+ const ansiStripped = stripAnsiSequences(text);
904
+ const strippedAnsi = ansiStripped !== text;
905
+ const codeProtected = isFileReadToolName(opts?.toolName) || isCodeOrDiffProtected(ansiStripped);
906
+ const foldLogs = opts?.foldLogs !== false;
907
+ const stages = [];
908
+ let current = ansiStripped;
909
+ const term = emulateTerminal(ansiStripped, codeProtected, strippedAnsi);
910
+ if (term.changed) {
911
+ current = term.text;
912
+ if (term.strippedAnsi)
913
+ stages.push('ansi');
914
+ if (term.strippedCr)
915
+ stages.push('cr');
916
+ if (!term.strippedAnsi && !term.strippedCr)
917
+ stages.push('ws');
918
+ }
919
+ if (!codeProtected) {
920
+ const unwrapped = opts?.enableJsonUnwrap !== false
921
+ ? unwrapNestedJsonStrings(current, {
922
+ enableToon: opts?.enableToon !== false,
923
+ foldLogs,
924
+ toolName: opts?.toolName,
925
+ })
926
+ : null;
927
+ if (unwrapped !== null) {
928
+ current = unwrapped.text;
929
+ stages.push(unwrapped.stage);
930
+ }
931
+ else {
932
+ const structured = encodeStructuredJson(current, opts?.aggressiveToon === true, opts?.enableToon !== false);
933
+ if (structured !== null) {
934
+ current = structured.text;
935
+ stages.push(structured.stage);
936
+ }
937
+ else {
938
+ const dirTree = compactDirectoryListing(current);
939
+ if (dirTree !== null) {
940
+ current = dirTree;
941
+ stages.push('dir_tree');
942
+ }
943
+ else {
944
+ const folded = foldLogs ? foldRepetitiveLogs(current) : null;
945
+ if (folded !== null) {
946
+ current = folded;
947
+ stages.push('log_fold');
948
+ }
949
+ else if (opts?.enableDensityPrune !== false &&
950
+ opts?.enableMmu !== false &&
951
+ (opts?.enableMmu === true || opts?.deepTextCompact === true) &&
952
+ current.length >= 2400) {
953
+ const pruned = pruneLowDensityBlob(current, {
954
+ store: getGlobalMmuStore(),
955
+ sessionKey: opts?.sessionKey,
956
+ refId: opts?.refId,
957
+ toolName: opts?.toolName,
958
+ minChars: 2400,
959
+ });
960
+ if (pruned.changed && pruned.text.length < current.length) {
961
+ current = pruned.text;
962
+ stages.push('density_prune');
963
+ }
964
+ }
965
+ }
966
+ }
967
+ }
968
+ }
969
+ if (current === text || current.length >= text.length) {
970
+ return { text, changed: false, stages: [] };
971
+ }
972
+ return { text: current, changed: true, stages };
973
+ }
974
+ /**
975
+ * Clean a single tool-output / observation string deterministically.
976
+ * Guaranteed pure function `f(text)` → identical output on every turn.
977
+ */
978
+ export function cleanToolOutput(text, opts) {
979
+ const core = cleanToolOutputCore(text, opts);
980
+ if (!core.changed) {
981
+ return { text: core.text, changed: false, savedChars: 0, savedTokens: 0, stages: [] };
982
+ }
983
+ return {
984
+ text: core.text,
985
+ changed: true,
986
+ savedChars: text.length - core.text.length,
987
+ savedTokens: estimateTokensSaved(text, core.text),
988
+ stages: core.stages,
989
+ };
990
+ }
991
+ function emptyWireStats() {
992
+ return { changed: false, savedChars: 0, savedTokens: 0, blocks: 0, stages: [] };
993
+ }
994
+ function collectSeedStrings(val, prefix, msgIndex, out, depth = 0) {
995
+ if (depth > 3 || val == null)
996
+ return;
997
+ if (typeof val === 'string') {
998
+ if (val.length >= MIN_SEED_STRING_CHARS && val.length <= MAX_SEED_STRING_CHARS) {
999
+ out.push({ refId: prefix, msgIndex, text: val });
1000
+ }
1001
+ return;
1002
+ }
1003
+ if (Array.isArray(val)) {
1004
+ const cap = Math.min(val.length, 32);
1005
+ for (let i = 0; i < cap; i++) {
1006
+ collectSeedStrings(val[i], `${prefix}[${i}]`, msgIndex, out, depth + 1);
1007
+ }
1008
+ return;
1009
+ }
1010
+ if (typeof val === 'object') {
1011
+ for (const [k, v] of Object.entries(val)) {
1012
+ collectSeedStrings(v, `${prefix}.${k}`, msgIndex, out, depth + 1);
1013
+ }
1014
+ }
1015
+ }
1016
+ function collectSeedStringsFromJsonArg(rawArgs, prefix, msgIndex, out) {
1017
+ if (rawArgs.length < MIN_SEED_STRING_CHARS || rawArgs.length > MAX_SEED_STRING_CHARS)
1018
+ return;
1019
+ const trimmed = rawArgs.trim();
1020
+ if (!((trimmed.startsWith('{') && trimmed.endsWith('}')) || (trimmed.startsWith('[') && trimmed.endsWith(']')))) {
1021
+ return;
1022
+ }
1023
+ try {
1024
+ const parsed = JSON.parse(trimmed);
1025
+ collectSeedStrings(parsed, prefix, msgIndex, out, 0);
1026
+ }
1027
+ catch {
1028
+ /* ignore malformed or partial tool-call arguments */
1029
+ }
1030
+ }
1031
+ function cleanUserBlockPreservingXml(raw, opts) {
1032
+ if (raw.length < MIN_USER_CLEAN_CHARS ||
1033
+ raw.includes('[End of rendered') ||
1034
+ isCodeOrDiffProtected(raw)) {
1035
+ return { text: raw, changed: false, stages: [] };
1036
+ }
1037
+ const islands = splitVolatileXmlIslands(raw);
1038
+ if (islands.length === 0)
1039
+ return { text: raw, changed: false, stages: [] };
1040
+ // Enforce threshold strictly on non-volatile user payload content (never
1041
+ // inflated by volatile <system-reminder>/<context> islands), and restrict user
1042
+ // payloads to lossless ANSI/whitespace/bijective-@toon (never density pruning!).
1043
+ let nonVolatileLen = 0;
1044
+ for (const isl of islands) {
1045
+ if (!isl.volatile)
1046
+ nonVolatileLen += isl.text.length;
1047
+ }
1048
+ if (nonVolatileLen < MIN_USER_CLEAN_CHARS) {
1049
+ return { text: raw, changed: false, stages: [] };
1050
+ }
1051
+ const userOpts = {
1052
+ ...opts,
1053
+ toolName: undefined,
1054
+ enableDensityPrune: false,
1055
+ enableJsonUnwrap: false,
1056
+ foldLogs: false,
1057
+ };
1058
+ if (islands.every((isl) => !isl.volatile)) {
1059
+ return cleanToolOutputCore(raw, userOpts);
1060
+ }
1061
+ let anyChanged = false;
1062
+ const stageSet = new Set();
1063
+ const outParts = islands.map((island) => {
1064
+ if (island.volatile || island.text.length < MIN_USER_CLEAN_CHARS || isCodeOrDiffProtected(island.text)) {
1065
+ return island.text;
1066
+ }
1067
+ const cleaned = cleanToolOutputCore(island.text, userOpts);
1068
+ if (!cleaned.changed)
1069
+ return island.text;
1070
+ const nextText = island.text.startsWith('\n') && !cleaned.text.startsWith('\n')
1071
+ ? `\n${cleaned.text}`
1072
+ : cleaned.text;
1073
+ if (nextText.length >= island.text.length)
1074
+ return island.text;
1075
+ anyChanged = true;
1076
+ for (const s of cleaned.stages)
1077
+ stageSet.add(s);
1078
+ return nextText;
1079
+ });
1080
+ if (!anyChanged)
1081
+ return { text: raw, changed: false, stages: [] };
1082
+ const joined = outParts.join('');
1083
+ if (joined.length >= raw.length)
1084
+ return { text: raw, changed: false, stages: [] };
1085
+ return { text: joined, changed: true, stages: [...stageSet] };
1086
+ }
1087
+ const SESSION_PINNED_SKILL_STORE = {
1088
+ get: (sessionKey, catalogHash) => getPinnedSessionSkills(sessionKey, catalogHash),
1089
+ set: (sessionKey, catalogHash, skills) => setPinnedSessionSkills(sessionKey, catalogHash, skills),
1090
+ };
1091
+ function estimateMessageBlockTokens(rawBlk) {
1092
+ if (!rawBlk || typeof rawBlk !== 'object')
1093
+ return 0;
1094
+ const blk = rawBlk;
1095
+ if (typeof blk.text === 'string')
1096
+ return Math.ceil(blk.text.length / 3.5);
1097
+ if (typeof blk.thinking === 'string')
1098
+ return Math.ceil(blk.thinking.length / 3.5);
1099
+ if (typeof blk.content === 'string')
1100
+ return Math.ceil(blk.content.length / 3.5);
1101
+ if (Array.isArray(blk.content)) {
1102
+ let sum = 0;
1103
+ for (const part of blk.content)
1104
+ sum += estimateMessageBlockTokens(part);
1105
+ return sum;
1106
+ }
1107
+ if (blk.type === 'tool_use' && blk.input !== undefined) {
1108
+ try {
1109
+ return Math.ceil((JSON.stringify(blk.input)?.length ?? 0) / 3.5);
1110
+ }
1111
+ catch {
1112
+ return 0;
1113
+ }
1114
+ }
1115
+ return 0;
1116
+ }
1117
+ export function estimateMessageTokens(rawMsg) {
1118
+ if (!rawMsg || typeof rawMsg !== 'object')
1119
+ return 0;
1120
+ const msg = rawMsg;
1121
+ if (typeof msg.content === 'string')
1122
+ return Math.ceil(msg.content.length / 3.5);
1123
+ if (!Array.isArray(msg.content))
1124
+ return 0;
1125
+ let sum = 0;
1126
+ for (const blk of msg.content)
1127
+ sum += estimateMessageBlockTokens(blk);
1128
+ return sum;
1129
+ }
1130
+ export function markerTtlSeconds(cc) {
1131
+ if (!cc || typeof cc !== 'object')
1132
+ return undefined;
1133
+ const ttl = cc.ttl;
1134
+ return ttl === '1h' ? 3600 : 300;
1135
+ }
1136
+ export function coveringBreakpointInfo(msgIndex, blockIndex, cacheBreakpoints, msgTotalTokens, totalMessages) {
1137
+ if (!cacheBreakpoints || cacheBreakpoints.length === 0) {
1138
+ return { coveringTtlSec: 0, downstreamTokens: 0 };
1139
+ }
1140
+ let coveringTtlSec = 0;
1141
+ let maxBpMsg = -1;
1142
+ for (const bp of cacheBreakpoints) {
1143
+ if (bp.msgIndex > msgIndex || (bp.msgIndex === msgIndex && bp.blockIndex >= blockIndex)) {
1144
+ if (bp.ttlSec > coveringTtlSec)
1145
+ coveringTtlSec = bp.ttlSec;
1146
+ if (bp.msgIndex > maxBpMsg)
1147
+ maxBpMsg = bp.msgIndex;
1148
+ }
1149
+ }
1150
+ if (coveringTtlSec === 0 || !msgTotalTokens || maxBpMsg < 0) {
1151
+ return { coveringTtlSec, downstreamTokens: 0 };
1152
+ }
1153
+ const limit = Math.min(msgTotalTokens.length - 1, Math.min(totalMessages - 1, maxBpMsg));
1154
+ let downstreamTokens = 0;
1155
+ for (let m = msgIndex + 1; m <= limit; m++) {
1156
+ downstreamTokens += msgTotalTokens[m] ?? 0;
1157
+ }
1158
+ return { coveringTtlSec, downstreamTokens };
1159
+ }
1160
+ function stage2RewritePaybackBlocked(orig, candidate, slot, opts, cacheBreakpoints, msgTotalTokens, totalMessages) {
1161
+ const { coveringTtlSec, downstreamTokens } = coveringBreakpointInfo(slot.msgIndex, slot.blockIndex ?? 0, cacheBreakpoints, msgTotalTokens, totalMessages);
1162
+ if (coveringTtlSec <= 0 || downstreamTokens <= 0)
1163
+ return false;
1164
+ const actualSavedTok = estimateTokensSaved(orig, candidate);
1165
+ if (!(actualSavedTok > 0))
1166
+ return true;
1167
+ const rawTok = Math.max(actualSavedTok + 1, Math.ceil(orig.length / 3.5));
1168
+ const keptTok = Math.max(1, rawTok - actualSavedTok);
1169
+ const rates = resolvePriceRates(opts?.model, { promptTokens: 0, ttlSec: coveringTtlSec });
1170
+ const savedPerRead = actualSavedTok * rates.read;
1171
+ if (!(savedPerRead > 0))
1172
+ return true;
1173
+ const transitionCost = keptTok * rates.write -
1174
+ rawTok * rates.read +
1175
+ downstreamTokens * (rates.write - rates.read);
1176
+ const paybackReads = Math.ceil(Math.max(0, transitionCost) / savedPerRead);
1177
+ const maxAllowed = computeHorizonPaybackLimit({
1178
+ turnsObserved: Math.max(1, Math.floor(totalMessages / 2)),
1179
+ baseMaxPayback: coveringTtlSec >= 3600 ? 8 : 12,
1180
+ downstreamCachedTokens: downstreamTokens,
1181
+ });
1182
+ return paybackReads > maxAllowed;
1183
+ }
1184
+ /** Deterministic session seal key protecting optically rendered Responses tool outputs from re-mutation. */
1185
+ export function buildOpticalToolSealKey(refId, rawText) {
1186
+ return `oai_opt_tr:${refId}\0${rawText.length}:${tapeHash64Hex(rawText)}`;
1187
+ }
1188
+ function runWireTextEngine(args) {
1189
+ const { tools, wire, staticSlots, toolSlots: rawToolSlots, userSlots, seedBlocks, totalMessages, msgTotalTokens, cacheBreakpoints, opts } = args;
1190
+ const effectiveOpts = opts?.aggressiveToon !== undefined
1191
+ ? opts
1192
+ : { ...opts, aggressiveToon: resolveTextHygieneMode(undefined) === 'on' };
1193
+ const initialSessionKey = effectiveOpts?.sessionKey;
1194
+ const toolSlots = initialSessionKey
1195
+ ? rawToolSlots.filter((s) => !hasStage2SealKey(initialSessionKey, buildOpticalToolSealKey(s.refId, s.getText())))
1196
+ : rawToolSlots;
1197
+ let staticSavedChars = 0;
1198
+ let staticSavedTokens = 0;
1199
+ let staticBlocks = 0;
1200
+ const stages = new Set();
1201
+ let cliffAvoided;
1202
+ const sessionKey = effectiveOpts?.sessionKey;
1203
+ const mmuActive = Boolean(effectiveOpts?.deepTextCompact && effectiveOpts?.enableMmu !== false);
1204
+ const mmuStore = mmuActive ? getGlobalMmuStore() : undefined;
1205
+ const sessionCold = effectiveOpts?.sessionCacheCold ??
1206
+ (sessionKey ? isSessionCacheCold(sessionKey, { model: effectiveOpts?.model }) : false);
1207
+ if (effectiveOpts?.deepTextCompact) {
1208
+ if (effectiveOpts.enableSkillLinker !== false && mmuStore && effectiveOpts.firstUserText) {
1209
+ for (const sSlot of staticSlots) {
1210
+ const raw = sSlot.get();
1211
+ const linked = linkSessionSkills({
1212
+ text: raw,
1213
+ firstUserText: effectiveOpts.firstUserText,
1214
+ sessionKey,
1215
+ store: mmuStore,
1216
+ pinnedStore: SESSION_PINNED_SKILL_STORE,
1217
+ });
1218
+ if (linked.changed && linked.text.length < raw.length && linked.savedTokens > 0) {
1219
+ sSlot.set(linked.text);
1220
+ staticSavedChars += linked.savedChars;
1221
+ staticSavedTokens += linked.savedTokens;
1222
+ staticBlocks += 1;
1223
+ stages.add('skill_linker');
1224
+ }
1225
+ }
1226
+ }
1227
+ if (effectiveOpts.enableTscg !== false) {
1228
+ const schemaRes = compileToolSchemas(tools, wire);
1229
+ if (schemaRes.changed) {
1230
+ staticSavedChars += schemaRes.savedChars;
1231
+ staticSavedTokens += schemaRes.savedTokens;
1232
+ staticBlocks += 1;
1233
+ stages.add('tscg');
1234
+ if (schemaRes.schemaDagFactored)
1235
+ stages.add('schema_dag');
1236
+ }
1237
+ for (const sSlot of staticSlots) {
1238
+ const raw = sSlot.get();
1239
+ const staticRes = compileSegmentedStaticText(raw);
1240
+ if (staticRes.changed) {
1241
+ sSlot.set(staticRes.text);
1242
+ staticSavedChars += staticRes.savedChars;
1243
+ staticSavedTokens += staticRes.savedTokens;
1244
+ staticBlocks += 1;
1245
+ stages.add('tscg');
1246
+ }
1247
+ }
1248
+ }
1249
+ }
1250
+ const tape = getGlobalPrefixTape();
1251
+ const stage2PolicyKey = [
1252
+ effectiveOpts?.enableToon !== false ? '1' : '0',
1253
+ effectiveOpts?.aggressiveToon === true ? '1' : '0',
1254
+ effectiveOpts?.foldLogs !== false ? '1' : '0',
1255
+ effectiveOpts?.enableJsonUnwrap !== false ? '1' : '0',
1256
+ effectiveOpts?.enableDensityPrune !== false ? '1' : '0',
1257
+ mmuActive ? '1' : '0',
1258
+ sessionKey ?? '',
1259
+ ].join('|');
1260
+ const origToolTexts = toolSlots.map((s) => s.getText());
1261
+ const slotStages = toolSlots.map(() => []);
1262
+ let stage2SavedChars = staticSavedChars;
1263
+ // Stage 2: per-block deterministic cleaning (ANSI / CR / WS / JSON-unwrap / TOON / JSON / dir_tree / log / density prune).
1264
+ // Frontier-first + monotonic: a block compressed at the frontier seals into session state so it
1265
+ // replays bit-identically behind later cache_control breakpoints (zero self-bust), while an
1266
+ // unsealed mid-prefix block covered by a live breakpoint only mutates if rewrite payback beats horizon.
1267
+ for (let i = 0; i < toolSlots.length; i++) {
1268
+ const tSlot = toolSlots[i];
1269
+ const cur = origToolTexts[i];
1270
+ const stage2SlotSig = `${tSlot.refId}\0${cur.length}:${tapeHash64Hex(cur)}`;
1271
+ const alreadySealedStage2 = Boolean(sessionKey && hasStage2SealKey(sessionKey, stage2SlotSig));
1272
+ const allowDensityPrune = effectiveOpts?.enableDensityPrune !== false;
1273
+ const memoKey = cur.length >= 64 && cur.length <= MAX_HYGIENE_BLOCK_CHARS
1274
+ ? `${stage2PolicyKey}:${allowDensityPrune ? '1' : '0'}\0${tSlot.refId}\0${tSlot.toolName ?? ''}\0${cur.length}:${tapeHash64Hex(cur)}`
1275
+ : undefined;
1276
+ let cleaned = memoKey ? tape.getStage2(memoKey) : undefined;
1277
+ if (!cleaned) {
1278
+ const slotOpts = {
1279
+ ...effectiveOpts,
1280
+ enableDensityPrune: allowDensityPrune,
1281
+ refId: tSlot.refId,
1282
+ ...(tSlot.toolName ? { toolName: tSlot.toolName } : {}),
1283
+ };
1284
+ const fresh = cleanToolOutputCore(cur, slotOpts);
1285
+ cleaned = { text: fresh.text, changed: fresh.changed, stages: fresh.stages };
1286
+ if (memoKey) {
1287
+ tape.setStage2(memoKey, cleaned);
1288
+ }
1289
+ }
1290
+ if (!cleaned.changed || cleaned.text.length >= cur.length)
1291
+ continue;
1292
+ if (!alreadySealedStage2 &&
1293
+ !sessionCold &&
1294
+ stage2RewritePaybackBlocked(cur, cleaned.text, tSlot, effectiveOpts, cacheBreakpoints, msgTotalTokens, totalMessages)) {
1295
+ continue;
1296
+ }
1297
+ tSlot.setText(cleaned.text);
1298
+ if (sessionKey)
1299
+ recordStage2SealKey(sessionKey, stage2SlotSig);
1300
+ stage2SavedChars += cur.length - cleaned.text.length;
1301
+ for (const s of cleaned.stages)
1302
+ slotStages[i].push(s);
1303
+ }
1304
+ // Opt-in Stage 2 cleaning on bulky user payloads (>= 1500 chars, non-code/diff, XML-safe).
1305
+ const activeUserSlots = effectiveOpts?.cleanUserPayloads === true && userSlots ? userSlots : [];
1306
+ const origUserTexts = activeUserSlots.map((s) => s.getText());
1307
+ const userSlotStages = activeUserSlots.map(() => []);
1308
+ for (let i = 0; i < activeUserSlots.length; i++) {
1309
+ const uSlot = activeUserSlots[i];
1310
+ const cur = origUserTexts[i];
1311
+ const cleaned = cleanUserBlockPreservingXml(cur, {
1312
+ ...effectiveOpts,
1313
+ refId: uSlot.refId,
1314
+ });
1315
+ if (cleaned.changed) {
1316
+ uSlot.setText(cleaned.text);
1317
+ stage2SavedChars += cur.length - cleaned.text.length;
1318
+ for (const s of cleaned.stages)
1319
+ userSlotStages[i].push(s);
1320
+ }
1321
+ }
1322
+ const estimateRemainingPromptTokens = () => {
1323
+ let remainingChars = 0;
1324
+ if (effectiveOpts?.rawBodyBytes && effectiveOpts.rawBodyBytes > 0) {
1325
+ remainingChars = Math.max(0, effectiveOpts.rawBodyBytes - (effectiveOpts.nativeImageBytes ?? 0) - stage2SavedChars);
1326
+ }
1327
+ else {
1328
+ for (const slot of toolSlots)
1329
+ remainingChars += slot.getText().length;
1330
+ }
1331
+ return Math.ceil(remainingChars / 3.5);
1332
+ };
1333
+ // Stage 3a/3b: Prefix-Monotonic Interval Seal Lattice (PMISL) + Context-MMU.
1334
+ // First replay already-sealed sticky Stage 3a epochs and Stage 3b Markov
1335
+ // episodes to a monotonic fixpoint BEFORE either stage evaluates new candidates,
1336
+ // so an advancing Stage 3a window never overwrites a previously folded Markov
1337
+ // episode or vice-versa on warm turns. Keeps `preCompactTexts` for CASI seeding.
1338
+ const preCompactTexts = toolSlots.map((s) => s.getText());
1339
+ const lsmActive = effectiveOpts?.enableLsm !== false;
1340
+ const lsmTail = effectiveOpts?.lsmEditTailMessages ?? 2;
1341
+ const minMsgsForEpochs = lsmActive ? lsmTail + 2 : 6;
1342
+ const canRunEpochs = Boolean(effectiveOpts?.deepTextCompact) &&
1343
+ effectiveOpts?.enableAcdc !== false &&
1344
+ toolSlots.length > 0 &&
1345
+ totalMessages > minMsgsForEpochs;
1346
+ const canRunMarkov = Boolean(effectiveOpts?.deepTextCompact) &&
1347
+ mmuActive &&
1348
+ effectiveOpts?.enableAcdc !== false &&
1349
+ toolSlots.length >= 4 &&
1350
+ totalMessages > 6;
1351
+ const epochPageOut = mmuStore
1352
+ ? (block, raw, digest) => {
1353
+ const page = mmuStore.storePage({
1354
+ sessionKey,
1355
+ refId: block.refId,
1356
+ toolName: block.toolName,
1357
+ rawText: raw,
1358
+ });
1359
+ return mmuStore.getPage(page.id, sessionKey)
1360
+ ? mmuStore.formatPageCard(page, digest)
1361
+ : digest;
1362
+ }
1363
+ : undefined;
1364
+ const runStage3a = (stickyOnly) => {
1365
+ if (!canRunEpochs || !effectiveOpts)
1366
+ return;
1367
+ const beforeEpochTexts = toolSlots.map((s) => s.getText());
1368
+ const epochRes = planAndApplyTextEpochs({
1369
+ blocks: toolSlots,
1370
+ totalMessages,
1371
+ model: effectiveOpts.model,
1372
+ totalPromptTokens: estimateRemainingPromptTokens(),
1373
+ expectedOutputTokens: effectiveOpts.expectedOutputTokens,
1374
+ ttlSec: effectiveOpts.ttlSec,
1375
+ msgTotalTokens,
1376
+ cacheBreakpoints,
1377
+ sessionKey,
1378
+ sessionCacheCold: sessionCold,
1379
+ enableLsm: lsmActive,
1380
+ lsmEditTailMessages: effectiveOpts.lsmEditTailMessages,
1381
+ stickyOnly,
1382
+ onPageOut: epochPageOut,
1383
+ });
1384
+ if (epochRes.changed) {
1385
+ for (let i = 0; i < toolSlots.length; i++) {
1386
+ const updated = toolSlots[i].getText();
1387
+ if (updated !== beforeEpochTexts[i]) {
1388
+ slotStages[i].push('acdc_epoch');
1389
+ if (lsmActive)
1390
+ slotStages[i].push(sessionCold ? 'lsm_l2_cold' : 'lsm_l1');
1391
+ if (mmuStore)
1392
+ slotStages[i].push('mmu_page');
1393
+ stage2SavedChars += Math.max(0, beforeEpochTexts[i].length - updated.length);
1394
+ }
1395
+ }
1396
+ if (epochRes.cliffAvoided)
1397
+ cliffAvoided = epochRes.cliffAvoided;
1398
+ }
1399
+ };
1400
+ const runStage3b = (stickyOnly) => {
1401
+ if (!canRunMarkov || !effectiveOpts)
1402
+ return false;
1403
+ const beforeMarkov = toolSlots.map((s) => s.getText());
1404
+ const markovRes = foldMarkovianEpisodes({
1405
+ blocks: toolSlots,
1406
+ totalMessages,
1407
+ keepTailMessages: effectiveOpts.lsmEditTailMessages !== undefined
1408
+ ? Math.max(effectiveOpts.lsmEditTailMessages, 4)
1409
+ : 4,
1410
+ sessionKey,
1411
+ model: effectiveOpts.model,
1412
+ sessionCacheCold: sessionCold,
1413
+ store: mmuStore,
1414
+ expectedOutputTokens: effectiveOpts.expectedOutputTokens,
1415
+ ttlSec: effectiveOpts.ttlSec,
1416
+ msgTotalTokens,
1417
+ cacheBreakpoints,
1418
+ totalPromptTokens: estimateRemainingPromptTokens(),
1419
+ stickyOnly,
1420
+ });
1421
+ if (markovRes.changed) {
1422
+ for (let i = 0; i < toolSlots.length; i++) {
1423
+ const updated = toolSlots[i].getText();
1424
+ if (updated !== beforeMarkov[i]) {
1425
+ slotStages[i].push('markov_fold');
1426
+ stage2SavedChars += beforeMarkov[i].length - updated.length;
1427
+ }
1428
+ }
1429
+ return true;
1430
+ }
1431
+ return false;
1432
+ };
1433
+ if ((canRunEpochs || canRunMarkov) && hasAnyStickyMarkovEpisode(sessionKey)) {
1434
+ for (let pass = 0; pass < 8; pass++) {
1435
+ const passBefore = toolSlots.map((s) => s.getText());
1436
+ runStage3a(true);
1437
+ runStage3b(true);
1438
+ let passChanged = false;
1439
+ for (let i = 0; i < toolSlots.length; i++) {
1440
+ if (toolSlots[i].getText() !== passBefore[i]) {
1441
+ passChanged = true;
1442
+ break;
1443
+ }
1444
+ }
1445
+ if (!passChanged)
1446
+ break;
1447
+ }
1448
+ }
1449
+ const sealSessionKey = sessionKey && sessionKey.length > 0 && (canRunEpochs || canRunMarkov) ? sessionKey : undefined;
1450
+ const sealSigs = sealSessionKey
1451
+ ? toolSlots.map((s, i) => `${s.refId}\0${s.msgIndex}\0${preCompactTexts[i].length}:${tapeHash64Hex(preCompactTexts[i])}`)
1452
+ : undefined;
1453
+ const replayedSeal = new Array(toolSlots.length).fill(false);
1454
+ // Unified Prefix Seal Table fast replay for already-sealed session slots before fixpoint scan.
1455
+ if (sealSessionKey && sealSigs && tape.hasAnySessionSeals(sealSessionKey)) {
1456
+ for (let i = 0; i < toolSlots.length; i++) {
1457
+ const seal = tape.getSeal(sealSessionKey, sealSigs[i]);
1458
+ if (!seal)
1459
+ continue;
1460
+ if (mmuStore) {
1461
+ const pgMatch = seal.text.match(/\[fiche vm-page (pg_[0-9a-f]+)/);
1462
+ if (pgMatch && !mmuStore.getPage(pgMatch[1], sealSessionKey)) {
1463
+ continue;
1464
+ }
1465
+ }
1466
+ const before = toolSlots[i].getText();
1467
+ if (before === seal.text) {
1468
+ replayedSeal[i] = true;
1469
+ continue;
1470
+ }
1471
+ toolSlots[i].setText(seal.text);
1472
+ for (const st of seal.stages)
1473
+ slotStages[i].push(st);
1474
+ stage2SavedChars += Math.max(0, before.length - seal.text.length);
1475
+ replayedSeal[i] = true;
1476
+ }
1477
+ }
1478
+ // Now seal newly eligible Stage 3a epochs and fold newly completed Stage 3b episodes.
1479
+ runStage3a(false);
1480
+ runStage3b(false);
1481
+ if (sealSessionKey && sealSigs) {
1482
+ for (let i = 0; i < toolSlots.length; i++) {
1483
+ if (replayedSeal[i])
1484
+ continue;
1485
+ const curAfter = toolSlots[i].getText();
1486
+ const pre = preCompactTexts[i];
1487
+ if (curAfter === pre || curAfter.length >= pre.length)
1488
+ continue;
1489
+ const isMarkov = curAfter.startsWith('[fiche causal-episode') || curAfter.startsWith('[folded into ');
1490
+ const isEpoch = curAfter.startsWith('[fiche epoch-digest') ||
1491
+ curAfter.startsWith('[inkling epoch-digest') ||
1492
+ curAfter.startsWith('[fiche vm-page');
1493
+ if (!isMarkov && !isEpoch)
1494
+ continue;
1495
+ const sealStages = slotStages[i].filter((s) => s === 'acdc_epoch' || s === 'lsm_l1' || s === 'lsm_l2_cold' || s === 'mmu_page' || s === 'markov_fold');
1496
+ tape.setSeal(sealSessionKey, sealSigs[i], {
1497
+ text: curAfter,
1498
+ stages: sealStages,
1499
+ kind: isMarkov ? 'markov' : 'epoch',
1500
+ rawLen: pre.length,
1501
+ });
1502
+ }
1503
+ }
1504
+ // Stage 4: CASI cross-turn deduplication / delta / FastCDC slice encoding.
1505
+ // Never seeds compacted preCompactTexts (whose bodies are gone from the prompt),
1506
+ // and replays warm indexed bases via replayIndexedBase (128-cap, independent of seedHashes).
1507
+ const casi = effectiveOpts?.enableCasi === false ? undefined : createCasiIndex();
1508
+ if (casi) {
1509
+ const sortedSeeds = seedBlocks && seedBlocks.length > 0
1510
+ ? [...seedBlocks].sort((a, b) => a.msgIndex - b.msgIndex)
1511
+ : [];
1512
+ let seedCursor = 0;
1513
+ let seedPrefixHash = INITIAL_PREFIX_HASH;
1514
+ let prefixHash = INITIAL_PREFIX_HASH;
1515
+ const deferredBases = [];
1516
+ const flushDeferredBases = () => {
1517
+ if (deferredBases.length === 0)
1518
+ return;
1519
+ for (const base of deferredBases) {
1520
+ if (base.kind === 'seed') {
1521
+ casi.seedBase(base.text, base.refId, base.msgIndex);
1522
+ }
1523
+ else {
1524
+ casi.replayIndexedBase(base.text, base.refId, base.msgIndex);
1525
+ }
1526
+ }
1527
+ deferredBases.length = 0;
1528
+ };
1529
+ for (let i = 0; i < toolSlots.length; i++) {
1530
+ const tSlot = toolSlots[i];
1531
+ while (seedCursor < sortedSeeds.length && sortedSeeds[seedCursor].msgIndex < tSlot.msgIndex) {
1532
+ const seed = sortedSeeds[seedCursor++];
1533
+ seedPrefixHash = tape.advancePrefixHash(seedPrefixHash, `${seed.refId}\0${seed.msgIndex}\0${seed.text.length}:${tapeHash64Hex(seed.text)}`);
1534
+ deferredBases.push({ kind: 'seed', text: seed.text, refId: seed.refId, msgIndex: seed.msgIndex });
1535
+ }
1536
+ const cur = tSlot.getText();
1537
+ if (cur.startsWith('[fiche epoch-digest') ||
1538
+ cur.startsWith('[inkling epoch-digest') ||
1539
+ cur.startsWith('[fiche vm-page') ||
1540
+ cur.startsWith('[fiche causal-episode') ||
1541
+ cur.startsWith('[folded into ') ||
1542
+ cur.startsWith('[fiche cas') ||
1543
+ cur.startsWith('[inkling cas')) {
1544
+ prefixHash = tape.advancePrefixHash(prefixHash, `compact\0${tSlot.refId}\0${tSlot.msgIndex}\0${cur.length}:${tapeHash64Hex(cur)}`);
1545
+ continue;
1546
+ }
1547
+ const curHash = tapeHash64Hex(cur);
1548
+ prefixHash = tape.advancePrefixHash(prefixHash, `${tSlot.refId}\0${tSlot.msgIndex}\0${cur.length}:${curHash}`);
1549
+ const casiKey = `${seedPrefixHash}\0${prefixHash}\0${tSlot.refId}\0${tSlot.msgIndex}\0${cur.length}:${curHash}`;
1550
+ let memo = tape.getCasiMemo(casiKey);
1551
+ if (!memo) {
1552
+ flushDeferredBases();
1553
+ const casiRes = casi.ingest(cur, tSlot.refId, tSlot.msgIndex);
1554
+ memo = {
1555
+ text: casiRes.text,
1556
+ changed: casiRes.changed,
1557
+ kind: casiRes.kind ?? 'none',
1558
+ };
1559
+ tape.setCasiMemo(casiKey, memo);
1560
+ }
1561
+ else if (!memo.changed && cur.length >= 400) {
1562
+ deferredBases.push({ kind: 'indexed', text: cur, refId: tSlot.refId, msgIndex: tSlot.msgIndex });
1563
+ }
1564
+ if (memo.changed) {
1565
+ tSlot.setText(memo.text);
1566
+ slotStages[i].push(memo.kind === 'exact_dup'
1567
+ ? 'casi_dup'
1568
+ : memo.kind === 'slice'
1569
+ ? 'casi_slice'
1570
+ : 'casi_delta');
1571
+ }
1572
+ }
1573
+ }
1574
+ let savedChars = staticSavedChars;
1575
+ let savedTokens = staticSavedTokens;
1576
+ let blocks = staticBlocks;
1577
+ let changed = staticBlocks > 0;
1578
+ for (let i = 0; i < toolSlots.length; i++) {
1579
+ const orig = origToolTexts[i];
1580
+ const final = toolSlots[i].getText();
1581
+ if (final !== orig && final.length < orig.length) {
1582
+ changed = true;
1583
+ savedChars += orig.length - final.length;
1584
+ savedTokens += estimateTokensSaved(orig, final);
1585
+ blocks += 1;
1586
+ for (const s of slotStages[i])
1587
+ stages.add(s);
1588
+ }
1589
+ else if (final !== orig) {
1590
+ // Revert if combined transforms somehow didn't shorten the block.
1591
+ toolSlots[i].setText(orig);
1592
+ }
1593
+ }
1594
+ // Enforce per-slot shrinkage BEFORE Stage 5 tail hydration so appending
1595
+ // `[fiche vm-hydrate]` onto string-content user messages is never reverted.
1596
+ for (let i = 0; i < activeUserSlots.length; i++) {
1597
+ const orig = origUserTexts[i];
1598
+ const final = activeUserSlots[i].getText();
1599
+ if (final !== orig && final.length < orig.length) {
1600
+ changed = true;
1601
+ savedChars += orig.length - final.length;
1602
+ savedTokens += estimateTokensSaved(orig, final);
1603
+ blocks += 1;
1604
+ for (const s of userSlotStages[i])
1605
+ stages.add(s);
1606
+ }
1607
+ else if (final !== orig) {
1608
+ activeUserSlots[i].setText(orig);
1609
+ }
1610
+ }
1611
+ // Stage 5: Speculative Live-Tail Hydration (read-only over prefix; appends ONLY to trailing live turn).
1612
+ let tailHydrated = false;
1613
+ if (mmuStore &&
1614
+ effectiveOpts?.appendTailHydration &&
1615
+ effectiveOpts.liveTailTexts &&
1616
+ effectiveOpts.liveTailTexts.length > 0) {
1617
+ const recentVerbatimTexts = [];
1618
+ for (const tSlot of toolSlots) {
1619
+ const t = tSlot.getText();
1620
+ if (!t.startsWith('[fiche ') &&
1621
+ !t.startsWith('[folded into ') &&
1622
+ !t.startsWith('[inkling ')) {
1623
+ recentVerbatimTexts.push(t);
1624
+ }
1625
+ }
1626
+ if (userSlots) {
1627
+ for (const uSlot of userSlots)
1628
+ recentVerbatimTexts.push(uSlot.getText());
1629
+ }
1630
+ const hyd = computeTailHydration({
1631
+ store: mmuStore,
1632
+ sessionKey,
1633
+ liveTailTexts: effectiveOpts.liveTailTexts,
1634
+ recentVerbatimTexts,
1635
+ });
1636
+ if (hyd.changed && hyd.text) {
1637
+ effectiveOpts.appendTailHydration(hyd.text);
1638
+ stages.add('mmu_hydrate');
1639
+ tailHydrated = true;
1640
+ }
1641
+ }
1642
+ if (!changed && !tailHydrated)
1643
+ return emptyWireStats();
1644
+ return {
1645
+ changed,
1646
+ ...(tailHydrated ? { tailHydrated: true } : {}),
1647
+ savedChars,
1648
+ savedTokens,
1649
+ blocks,
1650
+ stages: [...stages],
1651
+ ...(cliffAvoided ? { cliffAvoided } : {}),
1652
+ };
1653
+ }
1654
+ /** Clean Anthropic `messages[].content[].type==='tool_result'` (+ TSCG/CASI/ACDC when enabled) in place. */
1655
+ export function applyAnthropicTextHygiene(req, opts) {
1656
+ const staticSlots = [];
1657
+ if (typeof req.system === 'string') {
1658
+ staticSlots.push({
1659
+ get: () => req.system,
1660
+ set: (next) => {
1661
+ req.system = next;
1662
+ },
1663
+ });
1664
+ }
1665
+ else if (Array.isArray(req.system)) {
1666
+ for (const rawBlk of req.system) {
1667
+ if (!rawBlk || typeof rawBlk !== 'object')
1668
+ continue;
1669
+ const blk = rawBlk;
1670
+ if (blk.type === 'text' && typeof blk.text === 'string') {
1671
+ staticSlots.push({
1672
+ get: () => blk.text,
1673
+ set: (next) => {
1674
+ blk.text = next;
1675
+ },
1676
+ });
1677
+ }
1678
+ }
1679
+ }
1680
+ const toolSlots = [];
1681
+ const userSlots = [];
1682
+ const seedBlocks = [];
1683
+ const toolNameById = new Map();
1684
+ const cacheBreakpoints = [];
1685
+ if (Array.isArray(req.tools)) {
1686
+ for (const rawTool of req.tools) {
1687
+ if (!rawTool || typeof rawTool !== 'object')
1688
+ continue;
1689
+ const ttl = markerTtlSeconds(rawTool.cache_control);
1690
+ if (ttl !== undefined) {
1691
+ cacheBreakpoints.push({ msgIndex: -1, blockIndex: 0, ttlSec: ttl });
1692
+ }
1693
+ }
1694
+ }
1695
+ if (Array.isArray(req.system)) {
1696
+ for (const rawBlk of req.system) {
1697
+ if (!rawBlk || typeof rawBlk !== 'object')
1698
+ continue;
1699
+ const ttl = markerTtlSeconds(rawBlk.cache_control);
1700
+ if (ttl !== undefined) {
1701
+ cacheBreakpoints.push({ msgIndex: -1, blockIndex: 0, ttlSec: ttl });
1702
+ }
1703
+ }
1704
+ }
1705
+ const messages = Array.isArray(req.messages) ? req.messages : [];
1706
+ const msgTotalTokens = new Array(messages.length).fill(0);
1707
+ for (let mIdx = 0; mIdx < messages.length; mIdx++) {
1708
+ const rawMsg = messages[mIdx];
1709
+ if (!rawMsg || typeof rawMsg !== 'object')
1710
+ continue;
1711
+ msgTotalTokens[mIdx] = estimateMessageTokens(rawMsg);
1712
+ const msg = rawMsg;
1713
+ const msgTtl = markerTtlSeconds(msg.cache_control);
1714
+ if (msgTtl !== undefined) {
1715
+ cacheBreakpoints.push({ msgIndex: mIdx, blockIndex: Number.MAX_SAFE_INTEGER, ttlSec: msgTtl });
1716
+ }
1717
+ if (msg.role === 'user' && typeof msg.content === 'string') {
1718
+ userSlots.push({
1719
+ msgIndex: mIdx,
1720
+ blockIndex: 0,
1721
+ refId: `user_${mIdx}`,
1722
+ getText: () => msg.content,
1723
+ setText: (next) => {
1724
+ msg.content = next;
1725
+ },
1726
+ });
1727
+ continue;
1728
+ }
1729
+ if (!Array.isArray(msg.content))
1730
+ continue;
1731
+ for (let bIdx = 0; bIdx < msg.content.length; bIdx++) {
1732
+ const rawBlk = msg.content[bIdx];
1733
+ if (!rawBlk || typeof rawBlk !== 'object')
1734
+ continue;
1735
+ const blk = rawBlk;
1736
+ const blkTtl = markerTtlSeconds(blk.cache_control);
1737
+ if (blkTtl !== undefined) {
1738
+ cacheBreakpoints.push({ msgIndex: mIdx, blockIndex: bIdx, ttlSec: blkTtl });
1739
+ }
1740
+ if (blk.type === 'tool_use') {
1741
+ if (typeof blk.id === 'string' && typeof blk.name === 'string') {
1742
+ toolNameById.set(blk.id, blk.name);
1743
+ }
1744
+ const seedPrefix = typeof blk.id === 'string' && blk.id ? `${blk.id}:in` : `tu_${mIdx}_${bIdx}:in`;
1745
+ collectSeedStrings(blk.input, seedPrefix, mIdx, seedBlocks);
1746
+ continue;
1747
+ }
1748
+ if (msg.role === 'user' && blk.type === 'text' && typeof blk.text === 'string') {
1749
+ userSlots.push({
1750
+ msgIndex: mIdx,
1751
+ blockIndex: bIdx,
1752
+ refId: `user_${mIdx}_${bIdx}`,
1753
+ getText: () => blk.text,
1754
+ setText: (next) => {
1755
+ blk.text = next;
1756
+ },
1757
+ });
1758
+ continue;
1759
+ }
1760
+ if (blk.type !== 'tool_result')
1761
+ continue;
1762
+ const toolName = typeof blk.tool_use_id === 'string' ? toolNameById.get(blk.tool_use_id) : undefined;
1763
+ const baseRef = typeof blk.tool_use_id === 'string' && blk.tool_use_id ? blk.tool_use_id : `tr_${mIdx}_${bIdx}`;
1764
+ if (typeof blk.content === 'string') {
1765
+ toolSlots.push({
1766
+ msgIndex: mIdx,
1767
+ blockIndex: bIdx,
1768
+ refId: baseRef,
1769
+ toolName,
1770
+ getText: () => blk.content,
1771
+ setText: (next) => {
1772
+ blk.content = next;
1773
+ },
1774
+ });
1775
+ }
1776
+ else if (Array.isArray(blk.content)) {
1777
+ for (let pIdx = 0; pIdx < blk.content.length; pIdx++) {
1778
+ const rawPart = blk.content[pIdx];
1779
+ if (!rawPart || typeof rawPart !== 'object')
1780
+ continue;
1781
+ const part = rawPart;
1782
+ const partTtl = markerTtlSeconds(part.cache_control);
1783
+ if (partTtl !== undefined) {
1784
+ cacheBreakpoints.push({ msgIndex: mIdx, blockIndex: bIdx, ttlSec: partTtl });
1785
+ }
1786
+ if (part.type === 'text' && typeof part.text === 'string') {
1787
+ toolSlots.push({
1788
+ msgIndex: mIdx,
1789
+ blockIndex: bIdx,
1790
+ refId: `${baseRef}#${pIdx}`,
1791
+ toolName,
1792
+ getText: () => part.text,
1793
+ setText: (next) => {
1794
+ part.text = next;
1795
+ },
1796
+ });
1797
+ }
1798
+ }
1799
+ }
1800
+ }
1801
+ }
1802
+ if (toolSlots.length === 0 &&
1803
+ userSlots.length === 0 &&
1804
+ staticSlots.length === 0 &&
1805
+ !Array.isArray(req.tools)) {
1806
+ return emptyWireStats();
1807
+ }
1808
+ return runWireTextEngine({
1809
+ tools: Array.isArray(req.tools) ? req.tools : undefined,
1810
+ wire: 'anthropic',
1811
+ staticSlots,
1812
+ toolSlots,
1813
+ userSlots,
1814
+ seedBlocks,
1815
+ totalMessages: messages.length,
1816
+ msgTotalTokens,
1817
+ cacheBreakpoints,
1818
+ rawReq: req,
1819
+ opts,
1820
+ });
1821
+ }
1822
+ /** Clean OpenAI Chat Completions `role==='tool'` (+ TSCG/CASI/ACDC when enabled) in place. */
1823
+ export function applyOpenAIChatTextHygiene(req, opts) {
1824
+ const staticSlots = [];
1825
+ const toolSlots = [];
1826
+ const userSlots = [];
1827
+ const seedBlocks = [];
1828
+ const toolNameById = new Map();
1829
+ const messages = Array.isArray(req.messages) ? req.messages : [];
1830
+ for (let mIdx = 0; mIdx < messages.length; mIdx++) {
1831
+ const rawMsg = messages[mIdx];
1832
+ if (!rawMsg || typeof rawMsg !== 'object')
1833
+ continue;
1834
+ const msg = rawMsg;
1835
+ if (msg.role === 'assistant' && Array.isArray(msg.tool_calls)) {
1836
+ for (let tcIdx = 0; tcIdx < msg.tool_calls.length; tcIdx++) {
1837
+ const rawTc = msg.tool_calls[tcIdx];
1838
+ if (!rawTc || typeof rawTc !== 'object')
1839
+ continue;
1840
+ const tc = rawTc;
1841
+ if (typeof tc.id === 'string' && typeof tc.function?.name === 'string') {
1842
+ toolNameById.set(tc.id, tc.function.name);
1843
+ }
1844
+ const seedPrefix = typeof tc.id === 'string' && tc.id ? `${tc.id}:in` : `tc_${mIdx}_${tcIdx}:in`;
1845
+ const fnArgs = tc.function?.arguments;
1846
+ if (typeof fnArgs === 'string') {
1847
+ collectSeedStringsFromJsonArg(fnArgs, seedPrefix, mIdx, seedBlocks);
1848
+ }
1849
+ else if (fnArgs && typeof fnArgs === 'object') {
1850
+ collectSeedStrings(fnArgs, seedPrefix, mIdx, seedBlocks);
1851
+ }
1852
+ }
1853
+ continue;
1854
+ }
1855
+ if (msg.role === 'system' || msg.role === 'developer') {
1856
+ if (typeof msg.content === 'string') {
1857
+ staticSlots.push({
1858
+ get: () => msg.content,
1859
+ set: (next) => {
1860
+ msg.content = next;
1861
+ },
1862
+ });
1863
+ }
1864
+ else if (Array.isArray(msg.content)) {
1865
+ for (const rawPart of msg.content) {
1866
+ if (!rawPart || typeof rawPart !== 'object')
1867
+ continue;
1868
+ const part = rawPart;
1869
+ if (typeof part.text === 'string' && (part.type === 'text' || part.type === 'input_text')) {
1870
+ staticSlots.push({
1871
+ get: () => part.text,
1872
+ set: (next) => {
1873
+ part.text = next;
1874
+ },
1875
+ });
1876
+ }
1877
+ }
1878
+ }
1879
+ continue;
1880
+ }
1881
+ if (msg.role === 'user') {
1882
+ if (typeof msg.content === 'string') {
1883
+ userSlots.push({
1884
+ msgIndex: mIdx,
1885
+ refId: `user_${mIdx}`,
1886
+ getText: () => msg.content,
1887
+ setText: (next) => {
1888
+ msg.content = next;
1889
+ },
1890
+ });
1891
+ }
1892
+ else if (Array.isArray(msg.content)) {
1893
+ for (let pIdx = 0; pIdx < msg.content.length; pIdx++) {
1894
+ const rawPart = msg.content[pIdx];
1895
+ if (!rawPart || typeof rawPart !== 'object')
1896
+ continue;
1897
+ const part = rawPart;
1898
+ if (typeof part.text === 'string' && (part.type === 'text' || part.type === 'input_text')) {
1899
+ userSlots.push({
1900
+ msgIndex: mIdx,
1901
+ refId: `user_${mIdx}_${pIdx}`,
1902
+ getText: () => part.text,
1903
+ setText: (next) => {
1904
+ part.text = next;
1905
+ },
1906
+ });
1907
+ }
1908
+ }
1909
+ }
1910
+ continue;
1911
+ }
1912
+ if (msg.role !== 'tool')
1913
+ continue;
1914
+ const toolName = typeof msg.name === 'string' && msg.name
1915
+ ? msg.name
1916
+ : typeof msg.tool_call_id === 'string'
1917
+ ? toolNameById.get(msg.tool_call_id)
1918
+ : undefined;
1919
+ const baseRef = typeof msg.tool_call_id === 'string' && msg.tool_call_id ? msg.tool_call_id : `tool_${mIdx}`;
1920
+ if (typeof msg.content === 'string') {
1921
+ toolSlots.push({
1922
+ msgIndex: mIdx,
1923
+ refId: baseRef,
1924
+ toolName,
1925
+ getText: () => msg.content,
1926
+ setText: (next) => {
1927
+ msg.content = next;
1928
+ },
1929
+ });
1930
+ }
1931
+ else if (Array.isArray(msg.content)) {
1932
+ for (let pIdx = 0; pIdx < msg.content.length; pIdx++) {
1933
+ const rawPart = msg.content[pIdx];
1934
+ if (!rawPart || typeof rawPart !== 'object')
1935
+ continue;
1936
+ const part = rawPart;
1937
+ if (typeof part.text === 'string' && (part.type === 'text' || part.type === 'input_text')) {
1938
+ toolSlots.push({
1939
+ msgIndex: mIdx,
1940
+ refId: `${baseRef}#${pIdx}`,
1941
+ toolName,
1942
+ getText: () => part.text,
1943
+ setText: (next) => {
1944
+ part.text = next;
1945
+ },
1946
+ });
1947
+ }
1948
+ }
1949
+ }
1950
+ }
1951
+ if (toolSlots.length === 0 &&
1952
+ userSlots.length === 0 &&
1953
+ staticSlots.length === 0 &&
1954
+ !Array.isArray(req.tools)) {
1955
+ return emptyWireStats();
1956
+ }
1957
+ return runWireTextEngine({
1958
+ tools: Array.isArray(req.tools) ? req.tools : undefined,
1959
+ wire: 'openai_chat',
1960
+ staticSlots,
1961
+ toolSlots,
1962
+ userSlots,
1963
+ seedBlocks,
1964
+ totalMessages: messages.length,
1965
+ rawReq: req,
1966
+ opts,
1967
+ });
1968
+ }
1969
+ /** Clean OpenAI Responses `function_call_output` / `custom_tool_call_output` (+ TSCG/CASI/ACDC when enabled) in place. */
1970
+ export function applyOpenAIResponsesTextHygiene(req, opts) {
1971
+ const staticSlots = [];
1972
+ if (typeof req.instructions === 'string') {
1973
+ staticSlots.push({
1974
+ get: () => req.instructions,
1975
+ set: (next) => {
1976
+ req.instructions = next;
1977
+ },
1978
+ });
1979
+ }
1980
+ const toolSlots = [];
1981
+ const userSlots = [];
1982
+ const seedBlocks = [];
1983
+ const toolNameById = new Map();
1984
+ const items = Array.isArray(req.input) ? req.input : [];
1985
+ let leadingStatic = true;
1986
+ for (let iIdx = 0; iIdx < items.length; iIdx++) {
1987
+ const rawItem = items[iIdx];
1988
+ if (!rawItem || typeof rawItem !== 'object')
1989
+ continue;
1990
+ const item = rawItem;
1991
+ if (leadingStatic && (item.role === 'system' || item.role === 'developer')) {
1992
+ if (typeof item.content === 'string') {
1993
+ staticSlots.push({
1994
+ get: () => item.content,
1995
+ set: (next) => {
1996
+ item.content = next;
1997
+ },
1998
+ });
1999
+ }
2000
+ else if (Array.isArray(item.content)) {
2001
+ for (const rawPart of item.content) {
2002
+ if (!rawPart || typeof rawPart !== 'object')
2003
+ continue;
2004
+ const part = rawPart;
2005
+ if (typeof part.text === 'string' && (part.type === 'input_text' || part.type === 'text')) {
2006
+ staticSlots.push({
2007
+ get: () => part.text,
2008
+ set: (next) => {
2009
+ part.text = next;
2010
+ },
2011
+ });
2012
+ }
2013
+ }
2014
+ }
2015
+ continue;
2016
+ }
2017
+ leadingStatic = false;
2018
+ if (item.type === 'function_call' || item.type === 'custom_tool_call') {
2019
+ if (typeof item.name === 'string') {
2020
+ if (typeof item.call_id === 'string' && item.call_id)
2021
+ toolNameById.set(item.call_id, item.name);
2022
+ if (typeof item.id === 'string' && item.id)
2023
+ toolNameById.set(item.id, item.name);
2024
+ }
2025
+ const callRef = typeof item.call_id === 'string' && item.call_id
2026
+ ? item.call_id
2027
+ : typeof item.id === 'string' && item.id
2028
+ ? item.id
2029
+ : `fc_${iIdx}`;
2030
+ if (typeof item.arguments === 'string') {
2031
+ collectSeedStringsFromJsonArg(item.arguments, `${callRef}:in`, iIdx, seedBlocks);
2032
+ }
2033
+ else if (item.arguments && typeof item.arguments === 'object') {
2034
+ collectSeedStrings(item.arguments, `${callRef}:in`, iIdx, seedBlocks);
2035
+ }
2036
+ if (typeof item.input === 'string' && item.input.length >= MIN_SEED_STRING_CHARS) {
2037
+ const beforeLen = seedBlocks.length;
2038
+ collectSeedStringsFromJsonArg(item.input, `${callRef}:in`, iIdx, seedBlocks);
2039
+ if (seedBlocks.length === beforeLen && item.input.length <= MAX_SEED_STRING_CHARS) {
2040
+ seedBlocks.push({ refId: `${callRef}:in`, msgIndex: iIdx, text: item.input });
2041
+ }
2042
+ }
2043
+ else if (item.input && typeof item.input === 'object') {
2044
+ collectSeedStrings(item.input, `${callRef}:in`, iIdx, seedBlocks);
2045
+ }
2046
+ continue;
2047
+ }
2048
+ if (item.role === 'user') {
2049
+ if (typeof item.content === 'string') {
2050
+ userSlots.push({
2051
+ msgIndex: iIdx,
2052
+ refId: `user_${iIdx}`,
2053
+ getText: () => item.content,
2054
+ setText: (next) => {
2055
+ item.content = next;
2056
+ },
2057
+ });
2058
+ }
2059
+ else if (Array.isArray(item.content)) {
2060
+ for (let pIdx = 0; pIdx < item.content.length; pIdx++) {
2061
+ const rawPart = item.content[pIdx];
2062
+ if (!rawPart || typeof rawPart !== 'object')
2063
+ continue;
2064
+ const part = rawPart;
2065
+ if (typeof part.text === 'string' && (part.type === 'input_text' || part.type === 'text')) {
2066
+ userSlots.push({
2067
+ msgIndex: iIdx,
2068
+ refId: `user_${iIdx}_${pIdx}`,
2069
+ getText: () => part.text,
2070
+ setText: (next) => {
2071
+ part.text = next;
2072
+ },
2073
+ });
2074
+ }
2075
+ }
2076
+ }
2077
+ continue;
2078
+ }
2079
+ if (item.type !== 'function_call_output' && item.type !== 'custom_tool_call_output')
2080
+ continue;
2081
+ const toolName = typeof item.call_id === 'string' ? toolNameById.get(item.call_id) : undefined;
2082
+ const baseRef = typeof item.call_id === 'string' && item.call_id ? item.call_id : `out_${iIdx}`;
2083
+ if (typeof item.output === 'string') {
2084
+ toolSlots.push({
2085
+ msgIndex: iIdx,
2086
+ refId: baseRef,
2087
+ toolName,
2088
+ getText: () => item.output,
2089
+ setText: (next) => {
2090
+ item.output = next;
2091
+ },
2092
+ });
2093
+ }
2094
+ else if (Array.isArray(item.output)) {
2095
+ for (let pIdx = 0; pIdx < item.output.length; pIdx++) {
2096
+ const rawPart = item.output[pIdx];
2097
+ if (!rawPart || typeof rawPart !== 'object')
2098
+ continue;
2099
+ const part = rawPart;
2100
+ if (typeof part.text === 'string' && (part.type === 'input_text' || part.type === 'text' || part.type === 'output_text')) {
2101
+ toolSlots.push({
2102
+ msgIndex: iIdx,
2103
+ refId: `${baseRef}#${pIdx}`,
2104
+ toolName,
2105
+ getText: () => part.text,
2106
+ setText: (next) => {
2107
+ part.text = next;
2108
+ },
2109
+ });
2110
+ }
2111
+ }
2112
+ }
2113
+ }
2114
+ if (toolSlots.length === 0 &&
2115
+ userSlots.length === 0 &&
2116
+ staticSlots.length === 0 &&
2117
+ !Array.isArray(req.tools)) {
2118
+ return emptyWireStats();
2119
+ }
2120
+ return runWireTextEngine({
2121
+ tools: Array.isArray(req.tools) ? req.tools : undefined,
2122
+ wire: 'openai_responses',
2123
+ staticSlots,
2124
+ toolSlots,
2125
+ userSlots,
2126
+ seedBlocks,
2127
+ totalMessages: items.length,
2128
+ rawReq: req,
2129
+ opts,
2130
+ });
2131
+ }
2132
+ const GOOGLE_RESPONSE_TEXT_KEYS = [
2133
+ 'content',
2134
+ 'output',
2135
+ 'result',
2136
+ 'stdout',
2137
+ 'stderr',
2138
+ 'error',
2139
+ 'text',
2140
+ 'data',
2141
+ 'value',
2142
+ 'fileContent',
2143
+ 'body',
2144
+ ];
2145
+ /** Clean Google / Antigravity `functionResponse.response` & `.parts` (+ TSCG/CASI/ACDC when enabled) in place. */
2146
+ export function applyGoogleTextHygiene(req, opts) {
2147
+ const staticSlots = [];
2148
+ if (req.systemInstruction && Array.isArray(req.systemInstruction.parts)) {
2149
+ for (const rawPart of req.systemInstruction.parts) {
2150
+ if (!rawPart || typeof rawPart !== 'object')
2151
+ continue;
2152
+ const part = rawPart;
2153
+ if (typeof part.text === 'string') {
2154
+ staticSlots.push({
2155
+ get: () => part.text,
2156
+ set: (next) => {
2157
+ part.text = next;
2158
+ },
2159
+ });
2160
+ }
2161
+ }
2162
+ }
2163
+ const toolSlots = [];
2164
+ const userSlots = [];
2165
+ const seedBlocks = [];
2166
+ const contents = Array.isArray(req.contents) ? req.contents : [];
2167
+ for (let cIdx = 0; cIdx < contents.length; cIdx++) {
2168
+ const rawTurn = contents[cIdx];
2169
+ if (!rawTurn || typeof rawTurn !== 'object')
2170
+ continue;
2171
+ const turn = rawTurn;
2172
+ if (!Array.isArray(turn.parts))
2173
+ continue;
2174
+ for (let pIdx = 0; pIdx < turn.parts.length; pIdx++) {
2175
+ const rawPart = turn.parts[pIdx];
2176
+ if (!rawPart || typeof rawPart !== 'object')
2177
+ continue;
2178
+ const fc = rawPart.functionCall;
2179
+ if (fc && typeof fc === 'object') {
2180
+ const fcName = typeof fc.name === 'string' ? fc.name : 'fn';
2181
+ collectSeedStrings(fc.args, `${fcName}@${cIdx}.${pIdx}:in`, cIdx, seedBlocks);
2182
+ }
2183
+ const fr = rawPart.functionResponse;
2184
+ if (!fr || typeof fr !== 'object') {
2185
+ if (turn.role === 'user') {
2186
+ const partObj = rawPart;
2187
+ if (typeof partObj.text === 'string') {
2188
+ userSlots.push({
2189
+ msgIndex: cIdx,
2190
+ refId: `user_${cIdx}_${pIdx}`,
2191
+ getText: () => partObj.text,
2192
+ setText: (next) => {
2193
+ partObj.text = next;
2194
+ },
2195
+ });
2196
+ }
2197
+ }
2198
+ continue;
2199
+ }
2200
+ const rawFrName = typeof fr.name === 'string' ? fr.name : undefined;
2201
+ const frName = rawFrName ?? 'fn';
2202
+ const response = fr.response;
2203
+ if (response && typeof response === 'object' && !Array.isArray(response)) {
2204
+ const respObj = response;
2205
+ for (const k of GOOGLE_RESPONSE_TEXT_KEYS) {
2206
+ if (typeof respObj[k] === 'string') {
2207
+ toolSlots.push({
2208
+ msgIndex: cIdx,
2209
+ refId: `${frName}@${cIdx}.${pIdx}.${k}`,
2210
+ toolName: rawFrName,
2211
+ getText: () => respObj[k],
2212
+ setText: (next) => {
2213
+ respObj[k] = next;
2214
+ },
2215
+ });
2216
+ }
2217
+ }
2218
+ }
2219
+ const frParts = fr.parts;
2220
+ if (Array.isArray(frParts)) {
2221
+ for (let spIdx = 0; spIdx < frParts.length; spIdx++) {
2222
+ const rawSub = frParts[spIdx];
2223
+ if (!rawSub || typeof rawSub !== 'object')
2224
+ continue;
2225
+ const sub = rawSub;
2226
+ if (typeof sub.text === 'string') {
2227
+ toolSlots.push({
2228
+ msgIndex: cIdx,
2229
+ refId: `${frName}@${cIdx}.${pIdx}.p${spIdx}`,
2230
+ toolName: rawFrName,
2231
+ getText: () => sub.text,
2232
+ setText: (next) => {
2233
+ sub.text = next;
2234
+ },
2235
+ });
2236
+ }
2237
+ }
2238
+ }
2239
+ }
2240
+ }
2241
+ if (toolSlots.length === 0 &&
2242
+ userSlots.length === 0 &&
2243
+ staticSlots.length === 0 &&
2244
+ !Array.isArray(req.tools)) {
2245
+ return emptyWireStats();
2246
+ }
2247
+ return runWireTextEngine({
2248
+ tools: Array.isArray(req.tools) ? req.tools : undefined,
2249
+ wire: 'google',
2250
+ staticSlots,
2251
+ toolSlots,
2252
+ userSlots,
2253
+ seedBlocks,
2254
+ totalMessages: contents.length,
2255
+ rawReq: req,
2256
+ opts,
2257
+ });
2258
+ }
2259
+ //# sourceMappingURL=text-hygiene.js.map