@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,1696 @@
1
+ /**
2
+ * TSCG: Deterministic Tool-Schema & Static-Prompt Compiler.
3
+ *
4
+ * Grounded in:
5
+ * - TSCG (2026): lossless schema metadata compilation removes bloat ($schema,
6
+ * $comment, redundant titles, decorative whitespace, cross-tool repeated
7
+ * boilerplate) without altering tool names, parameter types, required fields,
8
+ * enums, constraints, or strictness.
9
+ * - CAPC (2026): strictly query-agnostic so compiled static prefixes produce
10
+ * identical bytes across every turn of a session (zero prefix-cache busts).
11
+ *
12
+ * Workers-safe: zero `node:` imports.
13
+ */
14
+ import { gptTokenCount, hasLongUnbrokenBpeChunk } from './gpt-tokens.js';
15
+ const TOKEN_EXACT_LIMIT = 32_000;
16
+ const DIVIDER_LINE_RE = /^[ \t]*[-=*_~─━═]{4,}[ \t]*$/;
17
+ const PROTECTED_SYS_LINE_RE = /^(?:You are Claude Code\b|You are a Claude agent, built on Anthropic's Claude Agent SDK\.|x-anthropic-billing-header:)/;
18
+ const COMPILER_CACHE_MAX_CHARS = 4 * 1024 * 1024;
19
+ const EMITTED_PREFIX_MAX = 512;
20
+ const emittedToolPrefixCache = new Map();
21
+ const emittedStaticPrefixCache = new Map();
22
+ function schemaHash64Hex(s) {
23
+ let h1 = 0x811c9dc5 >>> 0;
24
+ let h2 = 0x9e3779b1 >>> 0;
25
+ for (let i = 0; i < s.length; i++) {
26
+ const c = s.charCodeAt(i);
27
+ h1 = Math.imul((h1 ^ c) >>> 0, 0x01000193) >>> 0;
28
+ h2 = Math.imul((h2 ^ ((c + (i & 0xff)) >>> 0)) >>> 0, 0x85ebca6b) >>> 0;
29
+ }
30
+ return (h1 >>> 0).toString(16).padStart(8, '0') + (h2 >>> 0).toString(16).padStart(8, '0');
31
+ }
32
+ function lruGet(map, key) {
33
+ const hit = map.get(key);
34
+ if (hit !== undefined) {
35
+ map.delete(key);
36
+ map.set(key, hit);
37
+ }
38
+ return hit;
39
+ }
40
+ function recordEmittedPrefix(map, key, state) {
41
+ if (map.has(key))
42
+ map.delete(key);
43
+ while (map.size >= EMITTED_PREFIX_MAX) {
44
+ const oldest = map.keys().next().value;
45
+ if (oldest === undefined)
46
+ break;
47
+ map.delete(oldest);
48
+ }
49
+ map.set(key, state);
50
+ }
51
+ export function clearSchemaCompilerCachesForTests() {
52
+ toolSchemaCache.clear();
53
+ toolSchemaCacheChars = 0;
54
+ staticTextCache.clear();
55
+ staticTextCacheChars = 0;
56
+ segmentedStaticPatternCache.clear();
57
+ segmentedStaticPatternCacheChars = 0;
58
+ emittedToolPrefixCache.clear();
59
+ emittedStaticPrefixCache.clear();
60
+ }
61
+ const toolSchemaCache = new Map();
62
+ let toolSchemaCacheChars = 0;
63
+ const staticTextCache = new Map();
64
+ let staticTextCacheChars = 0;
65
+ const segmentedStaticPatternCache = new Map();
66
+ let segmentedStaticPatternCacheChars = 0;
67
+ const VOLATILE_XML_TAGS = new Set([
68
+ 'env',
69
+ 'context',
70
+ 'system-reminder',
71
+ 'fast_mode_info',
72
+ 'git_status',
73
+ 'additional_metadata',
74
+ ]);
75
+ const VOLATILE_ATTR_SCAN_LIMIT = 1024;
76
+ function estimateTokenPair(before, after) {
77
+ if (before.length <= TOKEN_EXACT_LIMIT &&
78
+ after.length <= TOKEN_EXACT_LIMIT &&
79
+ !hasLongUnbrokenBpeChunk(before) &&
80
+ !hasLongUnbrokenBpeChunk(after)) {
81
+ return [gptTokenCount(before), gptTokenCount(after)];
82
+ }
83
+ return [Math.ceil(before.length / 3.5), Math.ceil(after.length / 3.5)];
84
+ }
85
+ function normAlpha(s) {
86
+ return s.toLowerCase().replace(/[^a-z0-9]/g, '');
87
+ }
88
+ /** O(N) HTML comment stripper avoiding O(N^2) backtracking on unclosed `<!--`. */
89
+ function stripHtmlComments(s) {
90
+ const first = s.indexOf('<!--');
91
+ if (first < 0)
92
+ return s;
93
+ let out = '';
94
+ let pos = 0;
95
+ let open = first;
96
+ while (open >= 0) {
97
+ const close = s.indexOf('-->', open + 4);
98
+ if (close < 0)
99
+ break;
100
+ if (open > pos)
101
+ out += s.slice(pos, open);
102
+ pos = close + 3;
103
+ open = s.indexOf('<!--', pos);
104
+ }
105
+ if (pos === 0)
106
+ return s;
107
+ if (pos < s.length)
108
+ out += s.slice(pos);
109
+ return out;
110
+ }
111
+ /**
112
+ * Split text into unfenced prose vs fenced code blocks (``` or ~~~) using a strict
113
+ * CommonMark line scanner. Unclosed fences protect the remainder verbatim.
114
+ */
115
+ function splitCodeFences(raw) {
116
+ if (!raw.includes('```') && !raw.includes('~~~')) {
117
+ return [{ fence: false, text: raw }];
118
+ }
119
+ const lines = raw.split('\n');
120
+ const out = [];
121
+ let buf = [];
122
+ let openChar = '';
123
+ let openLen = 0;
124
+ const flush = (fence) => {
125
+ if (buf.length === 0)
126
+ return;
127
+ out.push({ fence, text: buf.join('\n') });
128
+ buf = [];
129
+ };
130
+ for (let i = 0; i < lines.length; i++) {
131
+ const line = lines[i];
132
+ const trimmedStart = line.replace(/^[ \t]{0,3}/, '');
133
+ const ch = trimmedStart[0];
134
+ let run = 0;
135
+ if (ch === '`' || ch === '~') {
136
+ while (trimmedStart[run] === ch)
137
+ run++;
138
+ }
139
+ const isBacktickInline = ch === '`' && trimmedStart.indexOf('`', run) >= 0;
140
+ if (!openChar && run >= 3 && !isBacktickInline) {
141
+ // Flush preceding prose lines with trailing newline delimiter preserved between segments.
142
+ flush(false);
143
+ openChar = ch;
144
+ openLen = run;
145
+ buf.push(line);
146
+ continue;
147
+ }
148
+ if (openChar &&
149
+ ch === openChar &&
150
+ run >= openLen &&
151
+ trimmedStart.slice(run).trim() === '') {
152
+ buf.push(line);
153
+ flush(true);
154
+ openChar = '';
155
+ openLen = 0;
156
+ continue;
157
+ }
158
+ buf.push(line);
159
+ }
160
+ flush(Boolean(openChar));
161
+ return out;
162
+ }
163
+ function isXmlWs(c) {
164
+ return c === 32 || c === 9 || c === 10 || c === 13;
165
+ }
166
+ function isXmlTagChar(c) {
167
+ return ((c >= 97 && c <= 122) ||
168
+ (c >= 65 && c <= 90) ||
169
+ (c >= 48 && c <= 57) ||
170
+ c === 45 ||
171
+ c === 95);
172
+ }
173
+ function asciiEqualsIgnoreCase(text, start, lowerTarget) {
174
+ if (text.length - start < lowerTarget.length)
175
+ return false;
176
+ for (let i = 0; i < lowerTarget.length; i++) {
177
+ let c = text.charCodeAt(start + i);
178
+ if (c >= 65 && c <= 90)
179
+ c += 32;
180
+ if (c !== lowerTarget.charCodeAt(i))
181
+ return false;
182
+ }
183
+ return true;
184
+ }
185
+ function buildNonProseSkipRanges(text) {
186
+ const ranges = [];
187
+ const len = text.length;
188
+ let pos = 0;
189
+ let fenceChar = '';
190
+ let fenceLen = 0;
191
+ let fenceStart = -1;
192
+ while (pos < len) {
193
+ const nl = text.indexOf('\n', pos);
194
+ const lineEnd = nl < 0 ? len : nl;
195
+ const line = text.slice(pos, lineEnd);
196
+ const trimmed = line.replace(/^[ \t]{0,3}/, '');
197
+ const ch = trimmed[0];
198
+ let run = 0;
199
+ if (ch === '`' || ch === '~') {
200
+ while (trimmed[run] === ch)
201
+ run++;
202
+ }
203
+ const isInlineFence = ch === '`' && trimmed.indexOf('`', run) >= 0;
204
+ if (!fenceChar && run >= 3 && !isInlineFence) {
205
+ fenceChar = ch;
206
+ fenceLen = run;
207
+ fenceStart = pos;
208
+ }
209
+ else if (fenceChar && ch === fenceChar && run >= fenceLen && trimmed.slice(run).trim() === '') {
210
+ ranges.push([fenceStart, nl < 0 ? len : nl + 1]);
211
+ fenceChar = '';
212
+ fenceLen = 0;
213
+ fenceStart = -1;
214
+ }
215
+ else if (!fenceChar && line.includes('`')) {
216
+ // Mask single-line inline backtick spans so prose mentions like `<system-reminder>` are skipped.
217
+ let bi = pos;
218
+ while (bi < lineEnd) {
219
+ if (text.charCodeAt(bi) === 96) {
220
+ let openRun = 0;
221
+ while (bi + openRun < lineEnd && text.charCodeAt(bi + openRun) === 96)
222
+ openRun++;
223
+ let closePos = -1;
224
+ let search = bi + openRun;
225
+ while (search < lineEnd) {
226
+ if (text.charCodeAt(search) === 96) {
227
+ let closeRun = 0;
228
+ while (search + closeRun < lineEnd && text.charCodeAt(search + closeRun) === 96)
229
+ closeRun++;
230
+ if (closeRun === openRun) {
231
+ closePos = search + closeRun;
232
+ break;
233
+ }
234
+ search += closeRun;
235
+ }
236
+ else {
237
+ search++;
238
+ }
239
+ }
240
+ if (closePos >= 0) {
241
+ ranges.push([bi, closePos]);
242
+ bi = closePos;
243
+ continue;
244
+ }
245
+ bi += openRun;
246
+ }
247
+ else {
248
+ bi++;
249
+ }
250
+ }
251
+ }
252
+ pos = nl < 0 ? len : nl + 1;
253
+ }
254
+ if (fenceChar && fenceStart >= 0) {
255
+ ranges.push([fenceStart, len]);
256
+ }
257
+ return ranges;
258
+ }
259
+ function advancePastSkipRange(ranges, idx, pos) {
260
+ let i = idx;
261
+ while (i < ranges.length && ranges[i][1] <= pos)
262
+ i++;
263
+ if (i < ranges.length && pos >= ranges[i][0] && pos < ranges[i][1]) {
264
+ return { idx: i + 1, skipEnd: ranges[i][1] };
265
+ }
266
+ return { idx: i, skipEnd: -1 };
267
+ }
268
+ function parseOpenTagHead(text, lt, targetLower) {
269
+ const len = text.length;
270
+ let nameEnd = lt + 1;
271
+ while (nameEnd < len && nameEnd - (lt + 1) <= 24 && isXmlTagChar(text.charCodeAt(nameEnd))) {
272
+ nameEnd++;
273
+ }
274
+ const nameLen = nameEnd - (lt + 1);
275
+ if (nameLen === 0 || nameLen > 24 || nameEnd >= len)
276
+ return undefined;
277
+ const tagLower = text.slice(lt + 1, nameEnd).toLowerCase();
278
+ if (targetLower !== undefined) {
279
+ if (tagLower !== targetLower)
280
+ return undefined;
281
+ }
282
+ else if (!VOLATILE_XML_TAGS.has(tagLower)) {
283
+ return undefined;
284
+ }
285
+ const delim = text.charCodeAt(nameEnd);
286
+ let openEnd = -1;
287
+ let selfClosing = false;
288
+ if (delim === 62) {
289
+ openEnd = nameEnd + 1;
290
+ }
291
+ else if (delim === 47) {
292
+ if (nameEnd + 1 < len && text.charCodeAt(nameEnd + 1) === 62) {
293
+ openEnd = nameEnd + 2;
294
+ selfClosing = true;
295
+ }
296
+ }
297
+ else if (isXmlWs(delim)) {
298
+ const limit = Math.min(len, nameEnd + VOLATILE_ATTR_SCAN_LIMIT);
299
+ let quote = 0;
300
+ for (let j = nameEnd; j < limit; j++) {
301
+ const ch = text.charCodeAt(j);
302
+ if (quote === 0) {
303
+ if (ch === 60)
304
+ break;
305
+ if (ch === 62) {
306
+ selfClosing = j > nameEnd && text.charCodeAt(j - 1) === 47;
307
+ openEnd = j + 1;
308
+ break;
309
+ }
310
+ if (ch === 34 || ch === 39)
311
+ quote = ch;
312
+ }
313
+ else if (ch === quote) {
314
+ quote = 0;
315
+ }
316
+ }
317
+ }
318
+ if (openEnd < 0)
319
+ return undefined;
320
+ return { tagLower, openEnd, selfClosing };
321
+ }
322
+ /**
323
+ * Linear O(N) scanner splitting dynamic/volatile XML prompt islands
324
+ * (`<env>`, `<context>`, `<system-reminder>`, `<fast_mode_info>`, `<git_status>`,
325
+ * `<ADDITIONAL_METADATA>`) from surrounding static prose.
326
+ * Skips fenced code blocks and inline backtick spans, tracks same-tag nesting
327
+ * depth, and fails open as volatile on unclosed tags.
328
+ */
329
+ export function splitVolatileXmlIslands(text) {
330
+ if (!text)
331
+ return [];
332
+ const out = [];
333
+ const len = text.length;
334
+ const skipRanges = buildNonProseSkipRanges(text);
335
+ let skipIdx = 0;
336
+ let lastEmit = 0;
337
+ let scanPos = 0;
338
+ while (scanPos < len) {
339
+ const lt = text.indexOf('<', scanPos);
340
+ if (lt < 0)
341
+ break;
342
+ const sk = advancePastSkipRange(skipRanges, skipIdx, lt);
343
+ skipIdx = sk.idx;
344
+ if (sk.skipEnd >= 0) {
345
+ scanPos = sk.skipEnd;
346
+ continue;
347
+ }
348
+ const head = parseOpenTagHead(text, lt);
349
+ if (!head) {
350
+ scanPos = lt + 1;
351
+ continue;
352
+ }
353
+ if (head.selfClosing) {
354
+ if (lt > lastEmit)
355
+ out.push({ volatile: false, text: text.slice(lastEmit, lt) });
356
+ out.push({ volatile: true, text: text.slice(lt, head.openEnd) });
357
+ lastEmit = head.openEnd;
358
+ scanPos = head.openEnd;
359
+ continue;
360
+ }
361
+ const tagLower = head.tagLower;
362
+ let closeSearch = head.openEnd;
363
+ let closeSkipIdx = skipIdx;
364
+ let depth = 1;
365
+ let closeEnd = -1;
366
+ while (closeSearch < len) {
367
+ const nextLt = text.indexOf('<', closeSearch);
368
+ if (nextLt < 0)
369
+ break;
370
+ const csk = advancePastSkipRange(skipRanges, closeSkipIdx, nextLt);
371
+ closeSkipIdx = csk.idx;
372
+ if (csk.skipEnd >= 0) {
373
+ closeSearch = csk.skipEnd;
374
+ continue;
375
+ }
376
+ if (nextLt + 1 < len && text.charCodeAt(nextLt + 1) === 47) {
377
+ const afterSlash = nextLt + 2;
378
+ if (asciiEqualsIgnoreCase(text, afterSlash, tagLower)) {
379
+ let k = afterSlash + tagLower.length;
380
+ while (k < len && isXmlWs(text.charCodeAt(k)))
381
+ k++;
382
+ if (k < len && text.charCodeAt(k) === 62) {
383
+ depth--;
384
+ if (depth === 0) {
385
+ closeEnd = k + 1;
386
+ skipIdx = closeSkipIdx;
387
+ break;
388
+ }
389
+ closeSearch = k + 1;
390
+ continue;
391
+ }
392
+ }
393
+ }
394
+ else {
395
+ const nested = parseOpenTagHead(text, nextLt, tagLower);
396
+ if (nested && !nested.selfClosing) {
397
+ depth++;
398
+ closeSearch = nested.openEnd;
399
+ continue;
400
+ }
401
+ }
402
+ closeSearch = nextLt + 1;
403
+ }
404
+ if (closeEnd < 0) {
405
+ if (lt > lastEmit)
406
+ out.push({ volatile: false, text: text.slice(lastEmit, lt) });
407
+ out.push({ volatile: true, text: text.slice(lt) });
408
+ lastEmit = len;
409
+ break;
410
+ }
411
+ if (lt > lastEmit)
412
+ out.push({ volatile: false, text: text.slice(lastEmit, lt) });
413
+ out.push({ volatile: true, text: text.slice(lt, closeEnd) });
414
+ lastEmit = closeEnd;
415
+ scanPos = closeEnd;
416
+ }
417
+ if (lastEmit < len) {
418
+ out.push({ volatile: false, text: text.slice(lastEmit) });
419
+ }
420
+ return out;
421
+ }
422
+ /** Compact one line of unfenced prose while leaving inline `` `...` `` spans verbatim. */
423
+ function compactInlineSafeLine(line) {
424
+ if (!line.includes('`')) {
425
+ const noTrail = line.replace(/[ \t]+$/g, '');
426
+ return noTrail.replace(/(\S)[ \t]{3,}/g, '$1 ');
427
+ }
428
+ let out = '';
429
+ let i = 0;
430
+ while (i < line.length) {
431
+ const tick = line.indexOf('`', i);
432
+ if (tick < 0) {
433
+ out += line.slice(i).replace(/(\S)[ \t]{3,}/g, '$1 ');
434
+ break;
435
+ }
436
+ if (tick > i) {
437
+ out += line.slice(i, tick).replace(/(\S)[ \t]{3,}/g, '$1 ');
438
+ }
439
+ let ticks = 1;
440
+ while (tick + ticks < line.length && line[tick + ticks] === '`')
441
+ ticks++;
442
+ const fence = '`'.repeat(ticks);
443
+ let close = line.indexOf(fence, tick + ticks);
444
+ // Require exact backtick run length for closing delimiter.
445
+ while (close >= 0) {
446
+ const beforeOk = close === 0 || line[close - 1] !== '`';
447
+ const afterOk = close + ticks >= line.length || line[close + ticks] !== '`';
448
+ if (beforeOk && afterOk)
449
+ break;
450
+ close = line.indexOf(fence, close + ticks);
451
+ }
452
+ if (close < 0) {
453
+ out += line.slice(tick);
454
+ break;
455
+ }
456
+ out += line.slice(tick, close + ticks);
457
+ i = close + ticks;
458
+ }
459
+ return out.replace(/[ \t]+$/g, '');
460
+ }
461
+ /** Split an unfenced chunk across inline backtick spans on the same line, running HTML comment removal only outside them. */
462
+ function stripHtmlCommentsOutsideInlineCode(seg) {
463
+ if (!seg.includes('<!--'))
464
+ return seg;
465
+ if (!seg.includes('`'))
466
+ return stripHtmlComments(seg);
467
+ // Mask single/multi-backtick inline spans per line with a collision-free marker.
468
+ const lines = seg.split('\n');
469
+ const saved = [];
470
+ let tokenPrefix = '\uE000__FC__';
471
+ while (seg.includes(tokenPrefix))
472
+ tokenPrefix += '_';
473
+ const maskedLines = lines.map((line) => {
474
+ if (!line.includes('`'))
475
+ return line;
476
+ let out = '';
477
+ let i = 0;
478
+ while (i < line.length) {
479
+ const tick = line.indexOf('`', i);
480
+ if (tick < 0) {
481
+ out += line.slice(i);
482
+ break;
483
+ }
484
+ out += line.slice(i, tick);
485
+ let ticks = 1;
486
+ while (tick + ticks < line.length && line[tick + ticks] === '`')
487
+ ticks++;
488
+ const fence = '`'.repeat(ticks);
489
+ let close = line.indexOf(fence, tick + ticks);
490
+ while (close >= 0) {
491
+ const beforeOk = close === 0 || line[close - 1] !== '`';
492
+ const afterOk = close + ticks >= line.length || line[close + ticks] !== '`';
493
+ if (beforeOk && afterOk)
494
+ break;
495
+ close = line.indexOf(fence, close + ticks);
496
+ }
497
+ if (close < 0) {
498
+ out += line.slice(tick);
499
+ break;
500
+ }
501
+ const id = saved.length;
502
+ saved.push(line.slice(tick, close + ticks));
503
+ out += `${tokenPrefix}${id}\uE001`;
504
+ i = close + ticks;
505
+ }
506
+ return out;
507
+ });
508
+ let stripped = stripHtmlComments(maskedLines.join('\n'));
509
+ if (saved.length > 0) {
510
+ const escPrefix = tokenPrefix.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
511
+ stripped = stripped.replace(new RegExp(`${escPrefix}(\\d+)\uE001`, 'g'), (_, rawId) => saved[Number(rawId)] ?? '');
512
+ }
513
+ return stripped;
514
+ }
515
+ function compactUnfencedSegment(segRaw, preserveProtectedLines) {
516
+ const withoutComments = stripHtmlCommentsOutsideInlineCode(segRaw);
517
+ const lines = withoutComments.split('\n');
518
+ const kept = [];
519
+ for (const line of lines) {
520
+ if (preserveProtectedLines && PROTECTED_SYS_LINE_RE.test(line)) {
521
+ kept.push(line);
522
+ continue;
523
+ }
524
+ const noTrail = line.replace(/[ \t]+$/g, '');
525
+ if (DIVIDER_LINE_RE.test(noTrail))
526
+ continue;
527
+ kept.push(compactInlineSafeLine(noTrail));
528
+ }
529
+ return kept.join('\n').replace(/\n{3,}/g, '\n\n');
530
+ }
531
+ /** Compact decorative prose whitespace outside fenced code blocks and inline backticks. */
532
+ function compactProseOutsideCode(raw) {
533
+ if (!raw || raw.length < 40)
534
+ return raw;
535
+ const segments = splitCodeFences(raw);
536
+ const out = segments
537
+ .map((seg) => (seg.fence ? seg.text : compactUnfencedSegment(seg.text, false)))
538
+ .join('\n');
539
+ return out.trim();
540
+ }
541
+ function cleanSchemaNode(node, propKey) {
542
+ if (!node || typeof node !== 'object')
543
+ return;
544
+ if (Array.isArray(node)) {
545
+ for (const item of node)
546
+ cleanSchemaNode(item);
547
+ return;
548
+ }
549
+ const obj = node;
550
+ // Preserve `$schema` so Draft-07 MCP tool schemas aren't re-evaluated as Draft 2020-12.
551
+ delete obj.$comment;
552
+ if (typeof obj.description === 'string') {
553
+ const compacted = compactProseOutsideCode(obj.description);
554
+ if (compacted === '') {
555
+ delete obj.description;
556
+ }
557
+ else if (compacted.length < obj.description.length) {
558
+ obj.description = compacted;
559
+ }
560
+ }
561
+ if (propKey !== undefined && typeof obj.title === 'string') {
562
+ const np = normAlpha(propKey);
563
+ if (np.length > 0 && normAlpha(obj.title) === np) {
564
+ delete obj.title;
565
+ }
566
+ }
567
+ if (obj.properties && typeof obj.properties === 'object' && !Array.isArray(obj.properties)) {
568
+ for (const [k, child] of Object.entries(obj.properties)) {
569
+ cleanSchemaNode(child, k);
570
+ }
571
+ }
572
+ if (obj.items !== undefined)
573
+ cleanSchemaNode(obj.items);
574
+ if (Array.isArray(obj.anyOf))
575
+ cleanSchemaNode(obj.anyOf);
576
+ if (Array.isArray(obj.oneOf))
577
+ cleanSchemaNode(obj.oneOf);
578
+ if (Array.isArray(obj.allOf))
579
+ cleanSchemaNode(obj.allOf);
580
+ if (obj.$defs && typeof obj.$defs === 'object') {
581
+ for (const child of Object.values(obj.$defs))
582
+ cleanSchemaNode(child);
583
+ }
584
+ if (obj.definitions && typeof obj.definitions === 'object') {
585
+ for (const child of Object.values(obj.definitions))
586
+ cleanSchemaNode(child);
587
+ }
588
+ }
589
+ const DEFAULT_SCHEMA_MIN_PARA_CHARS = 96;
590
+ function collectToolDescriptionSlots(node, out, minChars = DEFAULT_SCHEMA_MIN_PARA_CHARS) {
591
+ if (!node || typeof node !== 'object')
592
+ return;
593
+ if (Array.isArray(node)) {
594
+ for (const item of node)
595
+ collectToolDescriptionSlots(item, out, minChars);
596
+ return;
597
+ }
598
+ const obj = node;
599
+ if (typeof obj.description === 'string' && obj.description.length >= minChars) {
600
+ out.push({
601
+ get: () => obj.description,
602
+ set: (v) => {
603
+ obj.description = v;
604
+ },
605
+ });
606
+ }
607
+ if (obj.function && typeof obj.function === 'object' && !Array.isArray(obj.function)) {
608
+ collectToolDescriptionSlots(obj.function, out, minChars);
609
+ }
610
+ if (obj.input_schema && typeof obj.input_schema === 'object') {
611
+ collectSchemaDescSlots(obj.input_schema, out, minChars);
612
+ }
613
+ if (obj.parameters && typeof obj.parameters === 'object') {
614
+ collectSchemaDescSlots(obj.parameters, out, minChars);
615
+ }
616
+ if (Array.isArray(obj.functionDeclarations)) {
617
+ for (const fn of obj.functionDeclarations)
618
+ collectToolDescriptionSlots(fn, out, minChars);
619
+ }
620
+ }
621
+ function collectSchemaDescSlots(schema, out, minChars = DEFAULT_SCHEMA_MIN_PARA_CHARS) {
622
+ if (!schema || typeof schema !== 'object')
623
+ return;
624
+ if (Array.isArray(schema)) {
625
+ for (const s of schema)
626
+ collectSchemaDescSlots(s, out, minChars);
627
+ return;
628
+ }
629
+ const obj = schema;
630
+ if (typeof obj.description === 'string' && obj.description.length >= minChars) {
631
+ out.push({
632
+ get: () => obj.description,
633
+ set: (v) => {
634
+ obj.description = v;
635
+ },
636
+ });
637
+ }
638
+ if (obj.properties && typeof obj.properties === 'object' && !Array.isArray(obj.properties)) {
639
+ for (const child of Object.values(obj.properties)) {
640
+ collectSchemaDescSlots(child, out, minChars);
641
+ }
642
+ }
643
+ if (obj.items !== undefined)
644
+ collectSchemaDescSlots(obj.items, out, minChars);
645
+ if (Array.isArray(obj.anyOf))
646
+ collectSchemaDescSlots(obj.anyOf, out, minChars);
647
+ if (Array.isArray(obj.oneOf))
648
+ collectSchemaDescSlots(obj.oneOf, out, minChars);
649
+ if (Array.isArray(obj.allOf))
650
+ collectSchemaDescSlots(obj.allOf, out, minChars);
651
+ if (obj.$defs && typeof obj.$defs === 'object' && !Array.isArray(obj.$defs)) {
652
+ for (const child of Object.values(obj.$defs)) {
653
+ collectSchemaDescSlots(child, out, minChars);
654
+ }
655
+ }
656
+ if (obj.definitions && typeof obj.definitions === 'object' && !Array.isArray(obj.definitions)) {
657
+ for (const child of Object.values(obj.definitions)) {
658
+ collectSchemaDescSlots(child, out, minChars);
659
+ }
660
+ }
661
+ }
662
+ const UNTAGGED_REF_TEXT = 'See matching guidance in earlier tool above.';
663
+ function deduplicateSharedParagraphs(slots, tagPrefix, minParaChars, immutablePrefixSlots = 0, prefixState) {
664
+ const counts = new Map();
665
+ const splitSlots = slots.map((slot, slotIdx) => {
666
+ const raw = slot.get();
667
+ const isImmutable = slotIdx < immutablePrefixSlots;
668
+ const segments = splitCodeFences(raw).map((seg) => {
669
+ if (seg.fence) {
670
+ return { fence: true, text: seg.text, paras: [] };
671
+ }
672
+ const paras = seg.text.split(/\n\n+/);
673
+ for (const p of paras) {
674
+ if (p.length < minParaChars || PROTECTED_SYS_LINE_RE.test(p))
675
+ continue;
676
+ counts.set(p, (counts.get(p) ?? 0) + 1);
677
+ }
678
+ return { fence: false, text: seg.text, paras };
679
+ });
680
+ return { slot, raw, isImmutable, segments };
681
+ });
682
+ const profitableParas = new Set();
683
+ let estSeq = (prefixState?.maxTag ?? 0) + 1;
684
+ for (const [p, count] of counts.entries()) {
685
+ if (count < 2)
686
+ continue;
687
+ const preTagged = prefixState?.taggedParas.get(p);
688
+ const preUntagged = prefixState?.untaggedParas.has(p) ?? false;
689
+ if (preTagged !== undefined) {
690
+ profitableParas.add(p);
691
+ }
692
+ else if (preUntagged) {
693
+ if (p.length > UNTAGGED_REF_TEXT.length + 4)
694
+ profitableParas.add(p);
695
+ }
696
+ else {
697
+ const tagLen = 1 + String(estSeq).length + 1; // `#T1`
698
+ const netSaved = (count - 1) * (p.length - (12 + tagLen)) - (tagLen + 3);
699
+ if (netSaved > 0) {
700
+ profitableParas.add(p);
701
+ estSeq++;
702
+ }
703
+ }
704
+ }
705
+ const tagByPara = new Map(prefixState?.taggedParas ?? []);
706
+ const untaggedInPrefix = new Set(prefixState?.untaggedParas ?? []);
707
+ let seq = (prefixState?.maxTag ?? 0) + 1;
708
+ const compiledStrings = [];
709
+ for (let slotIdx = 0; slotIdx < splitSlots.length; slotIdx++) {
710
+ const item = splitSlots[slotIdx];
711
+ if (item.isImmutable) {
712
+ const frozen = prefixState?.compiledStrings[slotIdx] ?? item.raw;
713
+ if (frozen !== item.raw)
714
+ item.slot.set(frozen);
715
+ compiledStrings.push(frozen);
716
+ continue; // Never retroactively mutate already-emitted prefix tools.
717
+ }
718
+ if (profitableParas.size === 0) {
719
+ compiledStrings.push(item.raw);
720
+ continue;
721
+ }
722
+ let slotChanged = false;
723
+ const outSegs = item.segments.map((seg) => {
724
+ if (seg.fence)
725
+ return seg.text;
726
+ let segChanged = false;
727
+ const nextParas = seg.paras.map((p) => {
728
+ if (!profitableParas.has(p))
729
+ return p;
730
+ const existingTag = tagByPara.get(p);
731
+ if (existingTag) {
732
+ segChanged = true;
733
+ slotChanged = true;
734
+ return `See [${existingTag}] above.`;
735
+ }
736
+ if (untaggedInPrefix.has(p)) {
737
+ if (p.length <= UNTAGGED_REF_TEXT.length + 4)
738
+ return p;
739
+ segChanged = true;
740
+ slotChanged = true;
741
+ return UNTAGGED_REF_TEXT;
742
+ }
743
+ const tag = `#${tagPrefix}${seq++}`;
744
+ tagByPara.set(p, tag);
745
+ segChanged = true;
746
+ slotChanged = true;
747
+ return `[${tag}] ${p}`;
748
+ });
749
+ return segChanged ? nextParas.join('\n\n') : seg.text;
750
+ });
751
+ const finalText = slotChanged ? outSegs.join('\n') : item.raw;
752
+ if (slotChanged) {
753
+ item.slot.set(finalText);
754
+ }
755
+ compiledStrings.push(finalText);
756
+ }
757
+ const nextUntagged = new Set(untaggedInPrefix);
758
+ for (const [p] of counts.entries()) {
759
+ if (!tagByPara.has(p))
760
+ nextUntagged.add(p);
761
+ }
762
+ return { maxTag: seq - 1, taggedParas: tagByPara, untaggedParas: nextUntagged, compiledStrings };
763
+ }
764
+ const MIN_SUBTREE_JSON_CHARS = 220;
765
+ const MIN_TOOL_FACTOR_SAVED_CHARS = 120;
766
+ const SINGLE_SUBSCHEMA_KEYS = new Set([
767
+ 'additionalProperties',
768
+ 'unevaluatedProperties',
769
+ 'contains',
770
+ 'propertyNames',
771
+ 'not',
772
+ 'if',
773
+ 'then',
774
+ 'else',
775
+ 'contentSchema',
776
+ ]);
777
+ const ARRAY_SUBSCHEMA_KEYS = new Set(['anyOf', 'oneOf', 'allOf', 'prefixItems']);
778
+ const MAP_SUBSCHEMA_KEYS = new Set(['properties', 'patternProperties', 'dependentSchemas']);
779
+ const DEF_MAP_KEYS = new Set(['$defs', 'definitions']);
780
+ const SCOPE_ANCHOR_KEYS = new Set([
781
+ '$id',
782
+ '$anchor',
783
+ '$dynamicRef',
784
+ '$dynamicAnchor',
785
+ '$recursiveRef',
786
+ '$recursiveAnchor',
787
+ ]);
788
+ function isPlainRecord(v) {
789
+ return v !== null && typeof v === 'object' && !Array.isArray(v);
790
+ }
791
+ function mixHashPair(h1, h2, val) {
792
+ const n1 = Math.imul((h1 ^ val) >>> 0, 0x01000193) >>> 0;
793
+ const n2 = Math.imul((h2 ^ ((val + 0x9e3779b9) | 0)) >>> 0, 0x85ebca6b) >>> 0;
794
+ return [n1, n2];
795
+ }
796
+ function mixHashString(h1, h2, s) {
797
+ let a = h1 >>> 0;
798
+ let b = h2 >>> 0;
799
+ for (let i = 0; i < s.length; i++) {
800
+ const c = s.charCodeAt(i);
801
+ a = Math.imul((a ^ c) >>> 0, 0x01000193) >>> 0;
802
+ b = Math.imul((b ^ (c + i)) >>> 0, 0x85ebca6b) >>> 0;
803
+ }
804
+ return mixHashPair(a, b, s.length);
805
+ }
806
+ function hashJsonValue(val, depth = 0) {
807
+ if (depth > 64)
808
+ return [0xdeadbeef, 0xcafebabe];
809
+ if (val === null)
810
+ return [0x11111111, 0x22222222];
811
+ if (val === true)
812
+ return [0x33333333, 0x44444444];
813
+ if (val === false)
814
+ return [0x55555555, 0x66666666];
815
+ if (typeof val === 'number') {
816
+ const [a, b] = mixHashString(0x811c9dc5, 0x9e3779b1, String(val));
817
+ return mixHashPair(a, b, 1);
818
+ }
819
+ if (typeof val === 'string') {
820
+ const [a, b] = mixHashString(0x811c9dc5, 0x9e3779b1, val);
821
+ return mixHashPair(a, b, 2);
822
+ }
823
+ if (Array.isArray(val)) {
824
+ let a = 0x517cc1b7;
825
+ let b = 0x27d4eb2f;
826
+ for (let i = 0; i < val.length; i++) {
827
+ const [ca, cb] = hashJsonValue(val[i], depth + 1);
828
+ [a, b] = mixHashPair(a, b, ca ^ cb);
829
+ }
830
+ return mixHashPair(a, b, val.length);
831
+ }
832
+ if (typeof val === 'object') {
833
+ const obj = val;
834
+ const keys = Object.keys(obj).filter((k) => obj[k] !== undefined).sort();
835
+ let a = 0x811c9dc5;
836
+ let b = 0x9e3779b1;
837
+ for (const k of keys) {
838
+ [a, b] = mixHashString(a, b, k);
839
+ const [va, vb] = hashJsonValue(obj[k], depth + 1);
840
+ [a, b] = mixHashPair(a, b, va ^ vb);
841
+ }
842
+ return mixHashPair(a, b, keys.length);
843
+ }
844
+ return [0, 0];
845
+ }
846
+ function jsonValuesEqual(a, b, depth = 0) {
847
+ if (depth > 64)
848
+ return false;
849
+ if (a === b)
850
+ return true;
851
+ if (a === null || b === null || typeof a !== typeof b)
852
+ return false;
853
+ if (typeof a !== 'object')
854
+ return Number.isNaN(a) && Number.isNaN(b);
855
+ if (Array.isArray(a)) {
856
+ if (!Array.isArray(b) || a.length !== b.length)
857
+ return false;
858
+ for (let i = 0; i < a.length; i++) {
859
+ if (!jsonValuesEqual(a[i], b[i], depth + 1))
860
+ return false;
861
+ }
862
+ return true;
863
+ }
864
+ if (Array.isArray(b))
865
+ return false;
866
+ const ao = a;
867
+ const bo = b;
868
+ const ak = Object.keys(ao).filter((k) => ao[k] !== undefined);
869
+ const bk = Object.keys(bo).filter((k) => bo[k] !== undefined);
870
+ if (ak.length !== bk.length)
871
+ return false;
872
+ for (const k of ak) {
873
+ if (!Object.prototype.hasOwnProperty.call(bo, k))
874
+ return false;
875
+ if (!jsonValuesEqual(ao[k], bo[k], depth + 1))
876
+ return false;
877
+ }
878
+ return true;
879
+ }
880
+ function hasUnsafeInternalRef(root) {
881
+ const seen = new Set();
882
+ const stack = [root];
883
+ while (stack.length > 0) {
884
+ const cur = stack.pop();
885
+ if (!cur || typeof cur !== 'object')
886
+ continue;
887
+ if (seen.has(cur))
888
+ continue;
889
+ seen.add(cur);
890
+ if (Array.isArray(cur)) {
891
+ for (const item of cur)
892
+ stack.push(item);
893
+ continue;
894
+ }
895
+ const rec = cur;
896
+ if (typeof rec.$ref === 'string') {
897
+ const ref = rec.$ref;
898
+ if (ref.startsWith('#/') &&
899
+ !ref.startsWith('#/$defs/') &&
900
+ !ref.startsWith('#/definitions/')) {
901
+ return true;
902
+ }
903
+ }
904
+ for (const v of Object.values(rec))
905
+ stack.push(v);
906
+ }
907
+ return false;
908
+ }
909
+ function factorSingleSchema(schema) {
910
+ const useDraft07Definitions = typeof schema.$schema === 'string' &&
911
+ /draft-0[467]\b/i.test(schema.$schema) &&
912
+ schema.$defs === undefined;
913
+ const defsKey = useDraft07Definitions ? 'definitions' : '$defs';
914
+ const defsPtr = `#/${defsKey}/`;
915
+ if (!useDraft07Definitions && schema.$defs !== undefined && !isPlainRecord(schema.$defs)) {
916
+ return false;
917
+ }
918
+ if (useDraft07Definitions && schema.definitions !== undefined && !isPlainRecord(schema.definitions)) {
919
+ return false;
920
+ }
921
+ if (hasUnsafeInternalRef(schema))
922
+ return false;
923
+ const allNodes = [];
924
+ const recById = new Map();
925
+ let nextId = 1;
926
+ const activeStack = new Set();
927
+ const visit = (node, id, parentSchemaId, replaceable, applyReplace, depth, inEmbeddedResource) => {
928
+ if (depth > 48 || activeStack.has(node)) {
929
+ return { h1: 0, h2: 0, height: 0, hasScopeAnchor: true };
930
+ }
931
+ activeStack.add(node);
932
+ const isEmbedded = inEmbeddedResource || (depth > 0 && typeof node.$id === 'string');
933
+ const keys = Object.keys(node).filter((k) => node[k] !== undefined).sort();
934
+ let h1 = 0x811c9dc5;
935
+ let h2 = 0x9e3779b1;
936
+ let maxChildHeight = -1;
937
+ let hasScopeAnchor = isEmbedded;
938
+ for (const k of keys) {
939
+ if (SCOPE_ANCHOR_KEYS.has(k))
940
+ hasScopeAnchor = true;
941
+ const val = node[k];
942
+ [h1, h2] = mixHashString(h1, h2, k);
943
+ if (SINGLE_SUBSCHEMA_KEYS.has(k) && isPlainRecord(val)) {
944
+ const cid = nextId++;
945
+ const child = visit(val, cid, id, true, (refObj) => {
946
+ node[k] = refObj;
947
+ }, depth + 1, isEmbedded);
948
+ [h1, h2] = mixHashPair(h1, h2, child.h1 ^ child.h2);
949
+ if (child.height > maxChildHeight)
950
+ maxChildHeight = child.height;
951
+ if (child.hasScopeAnchor)
952
+ hasScopeAnchor = true;
953
+ continue;
954
+ }
955
+ if (k === 'items') {
956
+ if (isPlainRecord(val)) {
957
+ const cid = nextId++;
958
+ const child = visit(val, cid, id, true, (refObj) => {
959
+ node.items = refObj;
960
+ }, depth + 1, isEmbedded);
961
+ [h1, h2] = mixHashPair(h1, h2, child.h1 ^ child.h2);
962
+ if (child.height > maxChildHeight)
963
+ maxChildHeight = child.height;
964
+ if (child.hasScopeAnchor)
965
+ hasScopeAnchor = true;
966
+ continue;
967
+ }
968
+ if (Array.isArray(val)) {
969
+ let ah1 = 0x517cc1b7;
970
+ let ah2 = 0x27d4eb2f;
971
+ for (let idx = 0; idx < val.length; idx++) {
972
+ const elem = val[idx];
973
+ if (isPlainRecord(elem)) {
974
+ const cid = nextId++;
975
+ const child = visit(elem, cid, id, true, (refObj) => {
976
+ val[idx] = refObj;
977
+ }, depth + 1, isEmbedded);
978
+ [ah1, ah2] = mixHashPair(ah1, ah2, child.h1 ^ child.h2);
979
+ if (child.height > maxChildHeight)
980
+ maxChildHeight = child.height;
981
+ if (child.hasScopeAnchor)
982
+ hasScopeAnchor = true;
983
+ }
984
+ else {
985
+ const [eh1, eh2] = hashJsonValue(elem, depth + 1);
986
+ [ah1, ah2] = mixHashPair(ah1, ah2, eh1 ^ eh2);
987
+ }
988
+ }
989
+ [ah1, ah2] = mixHashPair(ah1, ah2, val.length);
990
+ [h1, h2] = mixHashPair(h1, h2, ah1 ^ ah2);
991
+ continue;
992
+ }
993
+ }
994
+ if (ARRAY_SUBSCHEMA_KEYS.has(k) && Array.isArray(val)) {
995
+ let ah1 = 0x517cc1b7;
996
+ let ah2 = 0x27d4eb2f;
997
+ for (let idx = 0; idx < val.length; idx++) {
998
+ const elem = val[idx];
999
+ if (isPlainRecord(elem)) {
1000
+ const cid = nextId++;
1001
+ const child = visit(elem, cid, id, true, (refObj) => {
1002
+ val[idx] = refObj;
1003
+ }, depth + 1, isEmbedded);
1004
+ [ah1, ah2] = mixHashPair(ah1, ah2, child.h1 ^ child.h2);
1005
+ if (child.height > maxChildHeight)
1006
+ maxChildHeight = child.height;
1007
+ if (child.hasScopeAnchor)
1008
+ hasScopeAnchor = true;
1009
+ }
1010
+ else {
1011
+ const [eh1, eh2] = hashJsonValue(elem, depth + 1);
1012
+ [ah1, ah2] = mixHashPair(ah1, ah2, eh1 ^ eh2);
1013
+ }
1014
+ }
1015
+ [ah1, ah2] = mixHashPair(ah1, ah2, val.length);
1016
+ [h1, h2] = mixHashPair(h1, h2, ah1 ^ ah2);
1017
+ continue;
1018
+ }
1019
+ if ((MAP_SUBSCHEMA_KEYS.has(k) || DEF_MAP_KEYS.has(k)) && isPlainRecord(val)) {
1020
+ const childReplaceable = !DEF_MAP_KEYS.has(k) && !isEmbedded;
1021
+ const mapKeys = Object.keys(val).filter((mk) => val[mk] !== undefined).sort();
1022
+ let mh1 = 0x811c9dc5;
1023
+ let mh2 = 0x9e3779b1;
1024
+ for (const mk of mapKeys) {
1025
+ [mh1, mh2] = mixHashString(mh1, mh2, mk);
1026
+ const sub = val[mk];
1027
+ if (isPlainRecord(sub)) {
1028
+ const cid = nextId++;
1029
+ const child = visit(sub, cid, id, childReplaceable, (refObj) => {
1030
+ val[mk] = refObj;
1031
+ }, depth + 1, isEmbedded);
1032
+ [mh1, mh2] = mixHashPair(mh1, mh2, child.h1 ^ child.h2);
1033
+ if (child.height > maxChildHeight)
1034
+ maxChildHeight = child.height;
1035
+ if (child.hasScopeAnchor)
1036
+ hasScopeAnchor = true;
1037
+ }
1038
+ else {
1039
+ const [vh1, vh2] = hashJsonValue(sub, depth + 1);
1040
+ [mh1, mh2] = mixHashPair(mh1, mh2, vh1 ^ vh2);
1041
+ }
1042
+ }
1043
+ [mh1, mh2] = mixHashPair(mh1, mh2, mapKeys.length);
1044
+ [h1, h2] = mixHashPair(h1, h2, mh1 ^ mh2);
1045
+ continue;
1046
+ }
1047
+ const [vh1, vh2] = hashJsonValue(val, depth + 1);
1048
+ [h1, h2] = mixHashPair(h1, h2, vh1 ^ vh2);
1049
+ }
1050
+ [h1, h2] = mixHashPair(h1, h2, keys.length);
1051
+ activeStack.delete(node);
1052
+ const height = maxChildHeight + 1;
1053
+ const isPureRef = typeof node.$ref === 'string' && keys.length === 1;
1054
+ if (replaceable && !isPureRef && !hasScopeAnchor && !isEmbedded) {
1055
+ const rec = {
1056
+ id,
1057
+ parentSchemaId,
1058
+ node,
1059
+ applyReplace,
1060
+ hashKey: `${h1.toString(16).padStart(8, '0')}${h2.toString(16).padStart(8, '0')}`,
1061
+ height,
1062
+ groupId: -1,
1063
+ };
1064
+ allNodes.push(rec);
1065
+ recById.set(id, rec);
1066
+ }
1067
+ return { h1, h2, height, hasScopeAnchor };
1068
+ };
1069
+ visit(schema, 0, -1, false, () => { }, 0, false);
1070
+ if (allNodes.length < 2)
1071
+ return false;
1072
+ const buckets = new Map();
1073
+ for (const rec of allNodes) {
1074
+ let list = buckets.get(rec.hashKey);
1075
+ if (!list) {
1076
+ list = [];
1077
+ buckets.set(rec.hashKey, list);
1078
+ }
1079
+ list.push(rec);
1080
+ }
1081
+ const groups = [];
1082
+ for (const bucket of buckets.values()) {
1083
+ if (bucket.length < 2)
1084
+ continue;
1085
+ const subGroups = [];
1086
+ for (const rec of bucket) {
1087
+ let matched = false;
1088
+ for (const sg of subGroups) {
1089
+ if (jsonValuesEqual(rec.node, sg[0].node)) {
1090
+ sg.push(rec);
1091
+ matched = true;
1092
+ break;
1093
+ }
1094
+ }
1095
+ if (!matched)
1096
+ subGroups.push([rec]);
1097
+ }
1098
+ for (const sg of subGroups) {
1099
+ if (sg.length < 2)
1100
+ continue;
1101
+ let serializedLen = 0;
1102
+ try {
1103
+ serializedLen = JSON.stringify(sg[0].node).length;
1104
+ }
1105
+ catch {
1106
+ continue;
1107
+ }
1108
+ if (serializedLen < MIN_SUBTREE_JSON_CHARS)
1109
+ continue;
1110
+ const gid = groups.length;
1111
+ for (const m of sg)
1112
+ m.groupId = gid;
1113
+ groups.push({ id: gid, height: sg[0].height, members: sg, dominated: false });
1114
+ }
1115
+ }
1116
+ if (groups.length === 0)
1117
+ return false;
1118
+ // Prune groups strictly dominated by an identical parent group of the exact same cardinality.
1119
+ for (const g of groups) {
1120
+ let commonParentGid = -1;
1121
+ let sameParentGroup = true;
1122
+ const distinctParents = new Set();
1123
+ for (const m of g.members) {
1124
+ const parentRec = recById.get(m.parentSchemaId);
1125
+ if (!parentRec || parentRec.groupId < 0) {
1126
+ sameParentGroup = false;
1127
+ break;
1128
+ }
1129
+ distinctParents.add(m.parentSchemaId);
1130
+ if (commonParentGid < 0)
1131
+ commonParentGid = parentRec.groupId;
1132
+ else if (parentRec.groupId !== commonParentGid) {
1133
+ sameParentGroup = false;
1134
+ break;
1135
+ }
1136
+ }
1137
+ if (sameParentGroup &&
1138
+ commonParentGid >= 0 &&
1139
+ distinctParents.size === g.members.length &&
1140
+ groups[commonParentGid].members.length === g.members.length) {
1141
+ g.dominated = true;
1142
+ }
1143
+ }
1144
+ const ordered = groups
1145
+ .filter((g) => !g.dominated)
1146
+ .sort((a, b) => a.height - b.height || a.id - b.id);
1147
+ if (ordered.length === 0)
1148
+ return false;
1149
+ const rawExistingDefs = useDraft07Definitions ? schema.definitions : schema.$defs;
1150
+ const existingDefs = isPlainRecord(rawExistingDefs) ? rawExistingDefs : undefined;
1151
+ const usedKeys = new Set(existingDefs ? Object.keys(existingDefs) : []);
1152
+ let defSeq = 1;
1153
+ const hoisted = [];
1154
+ for (const g of ordered) {
1155
+ const sample = g.members[0].node;
1156
+ let currentJson;
1157
+ try {
1158
+ currentJson = JSON.stringify(sample);
1159
+ }
1160
+ catch {
1161
+ continue;
1162
+ }
1163
+ if (currentJson.length < MIN_SUBTREE_JSON_CHARS)
1164
+ continue;
1165
+ while (usedKeys.has(`_f${defSeq}`))
1166
+ defSeq++;
1167
+ const defName = `_f${defSeq++}`;
1168
+ usedKeys.add(defName);
1169
+ const cloned = JSON.parse(currentJson);
1170
+ hoisted.push({ defName, value: cloned });
1171
+ const refTarget = `${defsPtr}${defName}`;
1172
+ for (const m of g.members) {
1173
+ m.applyReplace({ $ref: refTarget });
1174
+ }
1175
+ }
1176
+ if (hoisted.length === 0)
1177
+ return false;
1178
+ const defsObj = existingDefs ?? {};
1179
+ for (const h of hoisted) {
1180
+ defsObj[h.defName] = h.value;
1181
+ }
1182
+ schema[defsKey] = defsObj;
1183
+ return true;
1184
+ }
1185
+ /**
1186
+ * Bottom-up Merkle subtree factoring across non-Google tool schemas.
1187
+ * Hoists identical JSON Schema subtrees (`JSON.stringify(node).length >= 220`,
1188
+ * occurring `>= 2` times inside one tool's schema) into `schema.$defs._f1.._fN`
1189
+ * without colliding with existing `$defs` keys, replacing repeated occurrences
1190
+ * with `{ $ref: '#/$defs/_fN' }`. Keeps a tool's rewrite only when serialized
1191
+ * tool JSON shrinks by `>= 120` chars.
1192
+ */
1193
+ export function factorSharedSchemaSubtrees(candidate) {
1194
+ if (!candidate || typeof candidate !== 'object')
1195
+ return false;
1196
+ const tryFactorTool = (rawTool, applyWriteBack) => {
1197
+ if (!isPlainRecord(rawTool))
1198
+ return false;
1199
+ if (rawTool.strict === true || (isPlainRecord(rawTool.function) && rawTool.function.strict === true)) {
1200
+ return false;
1201
+ }
1202
+ let origToolJson;
1203
+ try {
1204
+ origToolJson = JSON.stringify(rawTool);
1205
+ }
1206
+ catch {
1207
+ return false;
1208
+ }
1209
+ if (origToolJson.length < MIN_SUBTREE_JSON_CHARS * 2)
1210
+ return false;
1211
+ const toolClone = JSON.parse(origToolJson);
1212
+ const fnTarget = isPlainRecord(toolClone.function) ? toolClone.function : toolClone;
1213
+ let touched = false;
1214
+ if (isPlainRecord(fnTarget.input_schema) && factorSingleSchema(fnTarget.input_schema)) {
1215
+ touched = true;
1216
+ }
1217
+ if (isPlainRecord(fnTarget.parameters) && factorSingleSchema(fnTarget.parameters)) {
1218
+ touched = true;
1219
+ }
1220
+ if (!touched)
1221
+ return false;
1222
+ const nextToolJson = JSON.stringify(toolClone);
1223
+ if (origToolJson.length - nextToolJson.length < MIN_TOOL_FACTOR_SAVED_CHARS) {
1224
+ return false;
1225
+ }
1226
+ applyWriteBack(toolClone);
1227
+ return true;
1228
+ };
1229
+ if (Array.isArray(candidate)) {
1230
+ let anyChanged = false;
1231
+ for (let i = 0; i < candidate.length; i++) {
1232
+ if (tryFactorTool(candidate[i], (next) => {
1233
+ candidate[i] = next;
1234
+ })) {
1235
+ anyChanged = true;
1236
+ }
1237
+ }
1238
+ return anyChanged;
1239
+ }
1240
+ const obj = candidate;
1241
+ if (isPlainRecord(obj.function) || isPlainRecord(obj.input_schema) || isPlainRecord(obj.parameters)) {
1242
+ return tryFactorTool(obj, (next) => {
1243
+ const nextObj = next;
1244
+ for (const k of Object.keys(obj))
1245
+ delete obj[k];
1246
+ Object.assign(obj, nextObj);
1247
+ });
1248
+ }
1249
+ let origJson;
1250
+ try {
1251
+ origJson = JSON.stringify(obj);
1252
+ }
1253
+ catch {
1254
+ return false;
1255
+ }
1256
+ if (origJson.length < MIN_SUBTREE_JSON_CHARS * 2)
1257
+ return false;
1258
+ const clone = JSON.parse(origJson);
1259
+ if (!factorSingleSchema(clone))
1260
+ return false;
1261
+ const nextJson = JSON.stringify(clone);
1262
+ if (origJson.length - nextJson.length < MIN_TOOL_FACTOR_SAVED_CHARS)
1263
+ return false;
1264
+ for (const k of Object.keys(obj))
1265
+ delete obj[k];
1266
+ Object.assign(obj, clone);
1267
+ return true;
1268
+ }
1269
+ /**
1270
+ * Compile tool definitions & JSON schemas deterministically in place.
1271
+ * Only writes back to `tools` when net savings are >=200 chars & >=40 tokens.
1272
+ */
1273
+ export function compileToolSchemas(tools, wire) {
1274
+ if (!Array.isArray(tools) || tools.length === 0) {
1275
+ return { changed: false, savedChars: 0, savedTokens: 0 };
1276
+ }
1277
+ let origJson;
1278
+ try {
1279
+ origJson = JSON.stringify(tools);
1280
+ }
1281
+ catch {
1282
+ return { changed: false, savedChars: 0, savedTokens: 0 };
1283
+ }
1284
+ if (!origJson || origJson.length < 512) {
1285
+ return { changed: false, savedChars: 0, savedTokens: 0 };
1286
+ }
1287
+ const cacheKey = `${wire}\0${origJson.length}:${schemaHash64Hex(origJson)}`;
1288
+ const cached = lruGet(toolSchemaCache, cacheKey);
1289
+ if (cached !== undefined) {
1290
+ if (cached.compiledJson !== undefined) {
1291
+ const cloned = JSON.parse(cached.compiledJson);
1292
+ for (let i = 0; i < tools.length && i < cloned.length; i++) {
1293
+ tools[i] = cloned[i];
1294
+ }
1295
+ }
1296
+ return cached.result;
1297
+ }
1298
+ const candidate = JSON.parse(origJson);
1299
+ const rawToolHashes = [];
1300
+ for (let i = 0; i < candidate.length; i++) {
1301
+ rawToolHashes.push(schemaHash64Hex(JSON.stringify(candidate[i]) ?? ''));
1302
+ }
1303
+ let immutablePrefixTools = 0;
1304
+ let matchedPrefixState;
1305
+ let runningPrefixKey = `${wire}`;
1306
+ const prefixKeys = [];
1307
+ for (let i = 0; i < rawToolHashes.length; i++) {
1308
+ runningPrefixKey = `${runningPrefixKey}\0${rawToolHashes[i]}`;
1309
+ prefixKeys.push(runningPrefixKey);
1310
+ }
1311
+ for (let k = prefixKeys.length - 2; k >= 0; k--) {
1312
+ const hit = lruGet(emittedToolPrefixCache, prefixKeys[k]);
1313
+ if (hit !== undefined) {
1314
+ immutablePrefixTools = k + 1;
1315
+ matchedPrefixState = hit;
1316
+ break;
1317
+ }
1318
+ }
1319
+ for (const rawTool of candidate) {
1320
+ if (!rawTool || typeof rawTool !== 'object')
1321
+ continue;
1322
+ const tool = rawTool;
1323
+ if (wire === 'google' && Array.isArray(tool.functionDeclarations)) {
1324
+ for (const rawFn of tool.functionDeclarations) {
1325
+ if (!rawFn || typeof rawFn !== 'object')
1326
+ continue;
1327
+ const fn = rawFn;
1328
+ if (typeof fn.description === 'string') {
1329
+ const c = compactProseOutsideCode(fn.description);
1330
+ if (c.length < fn.description.length && c.length > 0)
1331
+ fn.description = c;
1332
+ }
1333
+ if (fn.parameters !== undefined)
1334
+ cleanSchemaNode(fn.parameters);
1335
+ }
1336
+ continue;
1337
+ }
1338
+ const fnTarget = tool.function && typeof tool.function === 'object' && !Array.isArray(tool.function)
1339
+ ? tool.function
1340
+ : tool;
1341
+ if (typeof fnTarget.description === 'string') {
1342
+ const c = compactProseOutsideCode(fnTarget.description);
1343
+ if (c.length < fnTarget.description.length && c.length > 0)
1344
+ fnTarget.description = c;
1345
+ }
1346
+ if (fnTarget.input_schema !== undefined)
1347
+ cleanSchemaNode(fnTarget.input_schema);
1348
+ if (fnTarget.parameters !== undefined)
1349
+ cleanSchemaNode(fnTarget.parameters);
1350
+ }
1351
+ const schemaDagFactored = wire !== 'google' ? factorSharedSchemaSubtrees(candidate) : false;
1352
+ const slots = [];
1353
+ let immutablePrefixSlots = 0;
1354
+ for (let i = 0; i < candidate.length; i++) {
1355
+ collectToolDescriptionSlots(candidate[i], slots, DEFAULT_SCHEMA_MIN_PARA_CHARS);
1356
+ if (i + 1 === immutablePrefixTools)
1357
+ immutablePrefixSlots = slots.length;
1358
+ }
1359
+ const nextPrefixState = deduplicateSharedParagraphs(slots, 'T', DEFAULT_SCHEMA_MIN_PARA_CHARS, immutablePrefixSlots, matchedPrefixState);
1360
+ if (prefixKeys.length > 0) {
1361
+ recordEmittedPrefix(emittedToolPrefixCache, prefixKeys[prefixKeys.length - 1], nextPrefixState);
1362
+ }
1363
+ const nextJson = JSON.stringify(candidate);
1364
+ const savedChars = origJson.length - nextJson.length;
1365
+ const storeSchemaCache = (entry) => {
1366
+ const cost = cacheKey.length + (entry.compiledJson?.length ?? 0);
1367
+ if (cost <= COMPILER_CACHE_MAX_CHARS) {
1368
+ const prev = toolSchemaCache.get(cacheKey);
1369
+ if (prev) {
1370
+ toolSchemaCacheChars -= prev.cost;
1371
+ toolSchemaCache.delete(cacheKey);
1372
+ }
1373
+ while (toolSchemaCacheChars + cost > COMPILER_CACHE_MAX_CHARS && toolSchemaCache.size > 0) {
1374
+ const oldestKey = toolSchemaCache.keys().next().value;
1375
+ if (oldestKey === undefined)
1376
+ break;
1377
+ const oldest = toolSchemaCache.get(oldestKey);
1378
+ toolSchemaCache.delete(oldestKey);
1379
+ if (oldest)
1380
+ toolSchemaCacheChars -= oldest.cost;
1381
+ }
1382
+ toolSchemaCache.set(cacheKey, { ...entry, cost });
1383
+ toolSchemaCacheChars += cost;
1384
+ }
1385
+ };
1386
+ if (savedChars < 200) {
1387
+ const result = { changed: false, savedChars: 0, savedTokens: 0 };
1388
+ storeSchemaCache({ result });
1389
+ return result;
1390
+ }
1391
+ const [origTokens, nextTokens] = estimateTokenPair(origJson, nextJson);
1392
+ const savedTokens = Math.max(0, origTokens - nextTokens);
1393
+ if (savedTokens < 40) {
1394
+ const result = { changed: false, savedChars: 0, savedTokens: 0 };
1395
+ storeSchemaCache({ result });
1396
+ return result;
1397
+ }
1398
+ for (let i = 0; i < tools.length && i < candidate.length; i++) {
1399
+ tools[i] = candidate[i];
1400
+ }
1401
+ const result = {
1402
+ changed: true,
1403
+ savedChars,
1404
+ savedTokens,
1405
+ ...(schemaDagFactored ? { schemaDagFactored: true } : {}),
1406
+ };
1407
+ storeSchemaCache({ result, compiledJson: nextJson });
1408
+ return result;
1409
+ }
1410
+ /**
1411
+ * Compile multi-line static system/instruction prose deterministically.
1412
+ * Leaves single-line text, OAuth identity lines, billing headers, inline code
1413
+ * spans, and fenced code blocks verbatim untouched.
1414
+ */
1415
+ export function compileStaticText(text) {
1416
+ if (typeof text !== 'string' || text.length < 1200 || !text.includes('\n')) {
1417
+ return { text, changed: false, savedChars: 0, savedTokens: 0 };
1418
+ }
1419
+ const staticKey = `${text.length}:${schemaHash64Hex(text)}`;
1420
+ const hit = lruGet(staticTextCache, staticKey);
1421
+ if (hit !== undefined)
1422
+ return hit.result;
1423
+ const storeStaticCache = (res) => {
1424
+ const cost = staticKey.length + (res.changed ? res.text.length : 0);
1425
+ if (cost <= COMPILER_CACHE_MAX_CHARS) {
1426
+ const prev = staticTextCache.get(staticKey);
1427
+ if (prev) {
1428
+ staticTextCacheChars -= prev.cost;
1429
+ staticTextCache.delete(staticKey);
1430
+ }
1431
+ while (staticTextCacheChars + cost > COMPILER_CACHE_MAX_CHARS && staticTextCache.size > 0) {
1432
+ const oldestKey = staticTextCache.keys().next().value;
1433
+ if (oldestKey === undefined)
1434
+ break;
1435
+ const oldest = staticTextCache.get(oldestKey);
1436
+ staticTextCache.delete(oldestKey);
1437
+ if (oldest)
1438
+ staticTextCacheChars -= oldest.cost;
1439
+ }
1440
+ staticTextCache.set(staticKey, { result: res, cost });
1441
+ staticTextCacheChars += cost;
1442
+ }
1443
+ return res;
1444
+ };
1445
+ // Split by fenced code blocks (``` / ~~~) so anything inside code fences stays byte-identical.
1446
+ const segments = splitCodeFences(text);
1447
+ const outSegments = [];
1448
+ const paraCounts = new Map();
1449
+ for (const seg of segments) {
1450
+ if (seg.fence) {
1451
+ outSegments.push(seg);
1452
+ continue;
1453
+ }
1454
+ const cleaned = compactUnfencedSegment(seg.text, true);
1455
+ outSegments.push({ fence: false, text: cleaned });
1456
+ for (const para of cleaned.split(/\n\n+/)) {
1457
+ if (para.length >= 140 && !PROTECTED_SYS_LINE_RE.test(para)) {
1458
+ paraCounts.set(para, (paraCounts.get(para) ?? 0) + 1);
1459
+ }
1460
+ }
1461
+ }
1462
+ const tagByPara = new Map();
1463
+ let seq = 1;
1464
+ const outParts = outSegments.map((seg) => {
1465
+ if (seg.fence)
1466
+ return seg.text;
1467
+ const paras = seg.text.split(/\n\n+/);
1468
+ let any = false;
1469
+ const mapped = paras.map((p) => {
1470
+ if ((paraCounts.get(p) ?? 0) < 2)
1471
+ return p;
1472
+ const existing = tagByPara.get(p);
1473
+ if (existing) {
1474
+ any = true;
1475
+ return `See [${existing}] above.`;
1476
+ }
1477
+ const tag = `#S${seq++}`;
1478
+ tagByPara.set(p, tag);
1479
+ any = true;
1480
+ return `[${tag}] ${p}`;
1481
+ });
1482
+ return any ? mapped.join('\n\n') : seg.text;
1483
+ });
1484
+ const candidate = outParts.join('\n');
1485
+ const savedChars = text.length - candidate.length;
1486
+ if (savedChars < 200 || savedChars < text.length * 0.05) {
1487
+ return storeStaticCache({ text, changed: false, savedChars: 0, savedTokens: 0 });
1488
+ }
1489
+ const [origTokens, candTokens] = estimateTokenPair(text, candidate);
1490
+ const savedTokens = Math.max(0, origTokens - candTokens);
1491
+ if (savedTokens <= 0) {
1492
+ return storeStaticCache({ text, changed: false, savedChars: 0, savedTokens: 0 });
1493
+ }
1494
+ return storeStaticCache({ text: candidate, changed: true, savedChars, savedTokens });
1495
+ }
1496
+ function splitParaEdges(p) {
1497
+ const leadNl = p.startsWith('\n') ? '\n' : '';
1498
+ const trailNl = p.length > leadNl.length && p.endsWith('\n') ? '\n' : '';
1499
+ const core = p.slice(leadNl.length, p.length - trailNl.length);
1500
+ return { leadNl, core, trailNl };
1501
+ }
1502
+ /**
1503
+ * Compile multi-line static prompt prose while preserving volatile XML islands
1504
+ * (`<env>`, `<context>`, `<system-reminder>`, `<fast_mode_info>`, `<git_status>`,
1505
+ * `<ADDITIONAL_METADATA>`) and fenced code blocks byte-identical.
1506
+ * Deduplicates repeated paragraphs across non-volatile static islands (`#S1`, `#S2`, ...).
1507
+ */
1508
+ export function compileSegmentedStaticText(text) {
1509
+ if (typeof text !== 'string' || text.length < 300 || !text.includes('\n')) {
1510
+ return { text, changed: false, savedChars: 0, savedTokens: 0 };
1511
+ }
1512
+ const islands = splitVolatileXmlIslands(text);
1513
+ const staticIslands = [];
1514
+ let origStaticChars = 0;
1515
+ for (const island of islands) {
1516
+ if (!island.volatile) {
1517
+ staticIslands.push(island.text);
1518
+ origStaticChars += island.text.length;
1519
+ }
1520
+ }
1521
+ if (origStaticChars < 300) {
1522
+ return { text, changed: false, savedChars: 0, savedTokens: 0 };
1523
+ }
1524
+ // Key cache strictly by the invariant static islands so volatile <env>/<git_status>
1525
+ // updates hit the compiled static outputs immediately without re-scanning.
1526
+ const staticCacheKey = `${origStaticChars}:${schemaHash64Hex(staticIslands.join('\uE002'))}`;
1527
+ const cached = lruGet(segmentedStaticPatternCache, staticCacheKey);
1528
+ if (cached !== undefined) {
1529
+ if (cached.savedChars < 150 || cached.savedChars < cached.origStaticChars * 0.03 || cached.savedTokens <= 0) {
1530
+ return { text, changed: false, savedChars: 0, savedTokens: 0 };
1531
+ }
1532
+ let si = 0;
1533
+ const rebuilt = islands.map((isl) => (isl.volatile ? isl.text : cached.compiledStatic[si++])).join('');
1534
+ return { text: rebuilt, changed: true, savedChars: cached.savedChars, savedTokens: cached.savedTokens };
1535
+ }
1536
+ let immutableStaticCount = 0;
1537
+ let matchedStaticPrefix;
1538
+ let runningStaticKey = '';
1539
+ const staticPrefixKeys = [];
1540
+ for (let i = 0; i < staticIslands.length; i++) {
1541
+ const islHash = `${staticIslands[i].length}:${schemaHash64Hex(staticIslands[i])}`;
1542
+ runningStaticKey = i === 0 ? islHash : `${runningStaticKey}\0${islHash}`;
1543
+ staticPrefixKeys.push(runningStaticKey);
1544
+ }
1545
+ for (let k = staticPrefixKeys.length - 2; k >= 0; k--) {
1546
+ const hit = lruGet(emittedStaticPrefixCache, staticPrefixKeys[k]);
1547
+ if (hit !== undefined) {
1548
+ immutableStaticCount = k + 1;
1549
+ matchedStaticPrefix = hit;
1550
+ break;
1551
+ }
1552
+ }
1553
+ const storePatternCache = (compiledStatic, savedChars, savedTokens) => {
1554
+ const cost = staticCacheKey.length + compiledStatic.reduce((sum, s) => sum + s.length, 0);
1555
+ if (cost <= COMPILER_CACHE_MAX_CHARS) {
1556
+ const prev = segmentedStaticPatternCache.get(staticCacheKey);
1557
+ if (prev) {
1558
+ segmentedStaticPatternCacheChars -= prev.cost;
1559
+ segmentedStaticPatternCache.delete(staticCacheKey);
1560
+ }
1561
+ while (segmentedStaticPatternCacheChars + cost > COMPILER_CACHE_MAX_CHARS && segmentedStaticPatternCache.size > 0) {
1562
+ const oldestKey = segmentedStaticPatternCache.keys().next().value;
1563
+ if (oldestKey === undefined)
1564
+ break;
1565
+ const oldest = segmentedStaticPatternCache.get(oldestKey);
1566
+ segmentedStaticPatternCache.delete(oldestKey);
1567
+ if (oldest)
1568
+ segmentedStaticPatternCacheChars -= oldest.cost;
1569
+ }
1570
+ segmentedStaticPatternCache.set(staticCacheKey, { compiledStatic, origStaticChars, savedChars, savedTokens, cost });
1571
+ segmentedStaticPatternCacheChars += cost;
1572
+ }
1573
+ };
1574
+ const paraCounts = new Map();
1575
+ let staticCursor = 0;
1576
+ const compiledIslands = islands.map((island, idx) => {
1577
+ if (island.volatile) {
1578
+ return { volatile: true, text: island.text };
1579
+ }
1580
+ const staticIdx = staticCursor++;
1581
+ const trailingInlineSpace = idx < islands.length - 1 &&
1582
+ islands[idx + 1].volatile &&
1583
+ /[ \t]$/.test(island.text);
1584
+ const fenceSegs = splitCodeFences(island.text);
1585
+ const segments = fenceSegs.map((seg) => {
1586
+ if (seg.fence) {
1587
+ return { fence: true, text: seg.text, paras: [] };
1588
+ }
1589
+ const cleaned = compactUnfencedSegment(seg.text, true);
1590
+ const rawParas = cleaned.split(/\n\n+/);
1591
+ const paras = rawParas.map(splitParaEdges);
1592
+ for (const p of paras) {
1593
+ if (p.core.length >= 140 && !PROTECTED_SYS_LINE_RE.test(p.core)) {
1594
+ paraCounts.set(p.core, (paraCounts.get(p.core) ?? 0) + 1);
1595
+ }
1596
+ }
1597
+ return { fence: false, text: cleaned, paras };
1598
+ });
1599
+ return { volatile: false, staticIdx, trailingInlineSpace, segments };
1600
+ });
1601
+ const UNTAGGED_STATIC_REF = 'See matching guidance in earlier section above.';
1602
+ const profitableParas = new Set();
1603
+ let estSeq = (matchedStaticPrefix?.maxTag ?? 0) + 1;
1604
+ for (const [core, count] of paraCounts.entries()) {
1605
+ if (count < 2)
1606
+ continue;
1607
+ const preTagged = matchedStaticPrefix?.taggedParas.get(core);
1608
+ const preUntagged = matchedStaticPrefix?.untaggedParas.has(core) ?? false;
1609
+ if (preTagged !== undefined) {
1610
+ profitableParas.add(core);
1611
+ }
1612
+ else if (preUntagged) {
1613
+ if (core.length > UNTAGGED_STATIC_REF.length + 4)
1614
+ profitableParas.add(core);
1615
+ }
1616
+ else {
1617
+ const tagLen = 1 + String(estSeq).length + 1;
1618
+ const netSaved = (count - 1) * (core.length - (12 + tagLen)) - (tagLen + 3);
1619
+ if (netSaved > 0) {
1620
+ profitableParas.add(core);
1621
+ estSeq++;
1622
+ }
1623
+ }
1624
+ }
1625
+ const tagByPara = new Map(matchedStaticPrefix?.taggedParas ?? []);
1626
+ const untaggedStaticInPrefix = new Set(matchedStaticPrefix?.untaggedParas ?? []);
1627
+ let seq = (matchedStaticPrefix?.maxTag ?? 0) + 1;
1628
+ const compiledStaticOut = [];
1629
+ const outIslands = compiledIslands.map((island) => {
1630
+ if (island.volatile)
1631
+ return island.text;
1632
+ if (island.staticIdx < immutableStaticCount) {
1633
+ const frozen = matchedStaticPrefix?.compiledStrings[island.staticIdx] ?? staticIslands[island.staticIdx];
1634
+ compiledStaticOut.push(frozen);
1635
+ return frozen;
1636
+ }
1637
+ const outFenceParts = island.segments.map((seg) => {
1638
+ if (seg.fence)
1639
+ return seg.text;
1640
+ if (profitableParas.size === 0)
1641
+ return seg.text;
1642
+ let any = false;
1643
+ const mapped = seg.paras.map((p) => {
1644
+ if (!profitableParas.has(p.core)) {
1645
+ return `${p.leadNl}${p.core}${p.trailNl}`;
1646
+ }
1647
+ const existing = tagByPara.get(p.core);
1648
+ if (existing) {
1649
+ any = true;
1650
+ return `${p.leadNl}See [${existing}] above.${p.trailNl}`;
1651
+ }
1652
+ if (untaggedStaticInPrefix.has(p.core)) {
1653
+ if (p.core.length <= UNTAGGED_STATIC_REF.length + 4) {
1654
+ return `${p.leadNl}${p.core}${p.trailNl}`;
1655
+ }
1656
+ any = true;
1657
+ return `${p.leadNl}${UNTAGGED_STATIC_REF}${p.trailNl}`;
1658
+ }
1659
+ const tag = `#S${seq++}`;
1660
+ tagByPara.set(p.core, tag);
1661
+ any = true;
1662
+ return `${p.leadNl}[${tag}] ${p.core}${p.trailNl}`;
1663
+ });
1664
+ return any ? mapped.join('\n\n') : seg.text;
1665
+ });
1666
+ let compiledIslandText = outFenceParts.join('\n');
1667
+ if (island.trailingInlineSpace && !/[ \t\n]$/.test(compiledIslandText)) {
1668
+ compiledIslandText += ' ';
1669
+ }
1670
+ compiledStaticOut.push(compiledIslandText);
1671
+ return compiledIslandText;
1672
+ });
1673
+ if (staticPrefixKeys.length > 0) {
1674
+ const nextUntagged = new Set(untaggedStaticInPrefix);
1675
+ for (const [core] of paraCounts.entries()) {
1676
+ if (!tagByPara.has(core))
1677
+ nextUntagged.add(core);
1678
+ }
1679
+ recordEmittedPrefix(emittedStaticPrefixCache, staticPrefixKeys[staticPrefixKeys.length - 1], {
1680
+ maxTag: seq - 1,
1681
+ taggedParas: tagByPara,
1682
+ untaggedParas: nextUntagged,
1683
+ compiledStrings: compiledStaticOut,
1684
+ });
1685
+ }
1686
+ const candidate = outIslands.join('');
1687
+ const savedChars = text.length - candidate.length;
1688
+ const [origStaticTokens, candStaticTokens] = estimateTokenPair(staticIslands.join('\n'), compiledStaticOut.join('\n'));
1689
+ const savedTokens = Math.max(0, origStaticTokens - candStaticTokens);
1690
+ storePatternCache(compiledStaticOut, savedChars, savedTokens);
1691
+ if (savedChars < 150 || savedChars < origStaticChars * 0.03 || savedTokens <= 0) {
1692
+ return { text, changed: false, savedChars: 0, savedTokens: 0 };
1693
+ }
1694
+ return { text: candidate, changed: true, savedChars, savedTokens };
1695
+ }
1696
+ //# sourceMappingURL=schema-compiler.js.map