toolsplice 0.0.1 → 0.0.2

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 (137) hide show
  1. package/README.md +62 -330
  2. package/dist/abortable.d.ts +6 -0
  3. package/dist/abortable.js +50 -0
  4. package/dist/adaptive-read.d.ts +50 -0
  5. package/dist/adaptive-read.js +780 -0
  6. package/dist/answer-wait.d.ts +7 -0
  7. package/dist/answer-wait.js +45 -0
  8. package/dist/cache-reads.d.ts +18 -0
  9. package/dist/cache-reads.js +89 -0
  10. package/dist/calibration-ledger.d.ts +37 -0
  11. package/dist/calibration-ledger.js +148 -0
  12. package/dist/calibration-marker.d.ts +4 -0
  13. package/dist/calibration-marker.js +77 -0
  14. package/dist/catalog-setup.d.ts +33 -0
  15. package/dist/catalog-setup.js +89 -0
  16. package/dist/catalog.d.ts +10 -0
  17. package/dist/catalog.js +42 -0
  18. package/dist/checkpoint-files.d.ts +15 -0
  19. package/dist/checkpoint-files.js +99 -0
  20. package/dist/cli.js +545 -14
  21. package/dist/coalesce-reads.d.ts +6 -0
  22. package/dist/coalesce-reads.js +33 -0
  23. package/dist/contract-caller.d.ts +2 -1
  24. package/dist/contract-caller.js +35 -16
  25. package/dist/contract-schema.d.ts +3 -1
  26. package/dist/contract-schema.js +34 -4
  27. package/dist/contracts.d.ts +1 -0
  28. package/dist/contracts.js +5 -1
  29. package/dist/core.d.ts +31 -1
  30. package/dist/core.js +27 -0
  31. package/dist/db-final-answer.d.ts +9 -0
  32. package/dist/db-final-answer.js +62 -0
  33. package/dist/define.d.ts +78 -0
  34. package/dist/define.js +14 -0
  35. package/dist/final-answer-stores.d.ts +71 -0
  36. package/dist/final-answer-stores.js +72 -0
  37. package/dist/final-answer.d.ts +32 -0
  38. package/dist/final-answer.js +104 -0
  39. package/dist/impact.d.ts +48 -0
  40. package/dist/impact.js +71 -0
  41. package/dist/index.d.ts +32 -1
  42. package/dist/index.js +28 -0
  43. package/dist/local-tool.d.ts +18 -0
  44. package/dist/local-tool.js +32 -0
  45. package/dist/mcp-apps.d.ts +53 -0
  46. package/dist/mcp-apps.js +32 -0
  47. package/dist/mcp-event-delivery.d.ts +98 -0
  48. package/dist/mcp-event-delivery.js +211 -0
  49. package/dist/mcp-extensions.d.ts +46 -0
  50. package/dist/mcp-extensions.js +200 -0
  51. package/dist/mcp-peer.d.ts +45 -0
  52. package/dist/mcp-peer.js +207 -0
  53. package/dist/mcp-server-card.d.ts +21 -0
  54. package/dist/mcp-server-card.js +54 -0
  55. package/dist/page-checkpoint.d.ts +71 -0
  56. package/dist/page-checkpoint.js +286 -0
  57. package/dist/page-read-gate.d.ts +15 -0
  58. package/dist/page-read-gate.js +48 -0
  59. package/dist/pattern.d.ts +1 -0
  60. package/dist/pattern.js +27 -5
  61. package/dist/probe.js +6 -19
  62. package/dist/read-pages.d.ts +25 -0
  63. package/dist/read-pages.js +85 -0
  64. package/dist/read-policy.d.ts +6 -0
  65. package/dist/read-policy.js +16 -0
  66. package/dist/read-steps.d.ts +12 -0
  67. package/dist/read-steps.js +36 -0
  68. package/dist/result-session.d.ts +109 -0
  69. package/dist/result-session.js +620 -0
  70. package/dist/route-checkpoint.d.ts +3 -0
  71. package/dist/route-checkpoint.js +80 -0
  72. package/dist/route-driver-cli.d.ts +3 -0
  73. package/dist/route-driver-cli.js +43 -0
  74. package/dist/route-evaluation.d.ts +141 -0
  75. package/dist/route-evaluation.js +329 -0
  76. package/dist/row-groups.d.ts +17 -0
  77. package/dist/row-groups.js +79 -0
  78. package/dist/row-query.d.ts +62 -0
  79. package/dist/row-query.js +172 -0
  80. package/dist/rules.d.ts +30 -0
  81. package/dist/rules.js +72 -0
  82. package/dist/run-diagnostics.d.ts +75 -0
  83. package/dist/run-diagnostics.js +212 -0
  84. package/dist/search-fetch.d.ts +50 -0
  85. package/dist/search-fetch.js +264 -0
  86. package/dist/skill-files.d.ts +9 -0
  87. package/dist/skill-files.js +49 -0
  88. package/dist/splice-diagnostics.d.ts +4 -0
  89. package/dist/splice-diagnostics.js +24 -16
  90. package/dist/splice-measure.d.ts +33 -0
  91. package/dist/splice-measure.js +55 -0
  92. package/dist/splice-project.d.ts +12 -6
  93. package/dist/splice-project.js +72 -20
  94. package/dist/splice-recording.d.ts +29 -2
  95. package/dist/splice-recording.js +22 -5
  96. package/dist/splice.d.ts +98 -1
  97. package/dist/splice.js +225 -27
  98. package/dist/sqlite-checkpoint-store.d.ts +5 -0
  99. package/dist/sqlite-checkpoint-store.js +91 -0
  100. package/dist/sqlite-checkpoint-worker.d.ts +1 -0
  101. package/dist/sqlite-checkpoint-worker.js +115 -0
  102. package/dist/test-difference.d.ts +13 -0
  103. package/dist/test-difference.js +42 -0
  104. package/dist/testing.d.ts +122 -0
  105. package/dist/testing.js +261 -0
  106. package/dist/text-pages.d.ts +24 -0
  107. package/dist/text-pages.js +36 -0
  108. package/dist/tool-discovery.d.ts +59 -0
  109. package/dist/tool-discovery.js +136 -0
  110. package/dist/unevaluated.d.ts +7 -0
  111. package/dist/unevaluated.js +156 -0
  112. package/dist/v2.js +25 -8
  113. package/dist/version.d.ts +1 -1
  114. package/dist/version.js +1 -1
  115. package/dist/workflow-json.js +1 -1
  116. package/docs/AGENT-FRAMEWORKS.md +431 -0
  117. package/docs/BENCHMARKS.md +43 -0
  118. package/docs/INTEGRATION-QUICKSTART.md +859 -0
  119. package/docs/LEARNING-AND-STORAGE.md +393 -0
  120. package/docs/MCP.md +204 -0
  121. package/docs/PROJECTS-AND-UPGRADES.md +67 -9
  122. package/docs/PYTHON-REFERENCE.md +348 -0
  123. package/docs/PYTHON.md +120 -0
  124. package/docs/RECORDING-AND-CORRECTIONS.md +30 -1
  125. package/docs/TESTING.md +259 -0
  126. package/examples/mcp-app/build.mjs +11 -0
  127. package/examples/mcp-app/view.mjs +22 -0
  128. package/examples/quickstart.mjs +43 -0
  129. package/examples/route-driver.mjs +67 -0
  130. package/integrations/ai.d.mts +36 -0
  131. package/integrations/ai.mjs +178 -0
  132. package/integrations/call-options.mjs +9 -0
  133. package/integrations/langchain.d.mts +31 -0
  134. package/integrations/langchain.mjs +114 -0
  135. package/integrations/managed.mjs +154 -0
  136. package/integrations/types.d.mts +13 -0
  137. package/package.json +47 -3
@@ -0,0 +1,780 @@
1
+ import { jsonObject, copyJson } from "./workflow-json.js";
2
+ const budget = 4096;
3
+ const size = (value) => Buffer.byteLength(JSON.stringify(value));
4
+ const short = (value) => value === null ||
5
+ typeof value === "boolean" ||
6
+ typeof value === "number" ||
7
+ (typeof value === "string" && value.length <= 96);
8
+ // An explicit "names containing 'X'" asks about a particular column, not every text cell.
9
+ function fieldFilter(question) {
10
+ const clauses = [
11
+ ...question.matchAll(/\b([a-z_][a-z0-9_]{0,63})\s+(?:contains?|containing|includes?)\s+(["'`])([^"'`\n]{1,128})\2/gi),
12
+ ];
13
+ if (clauses.length !== 1)
14
+ return;
15
+ const [, name, , literal] = clauses[0];
16
+ return {
17
+ name: name.toLowerCase(),
18
+ literal: literal,
19
+ caseSensitive: !/\bcase[- ]insensitive\b/i.test(question),
20
+ };
21
+ }
22
+ function fieldEvidence(rows, filter) {
23
+ if (!rows.length || rows.length > 2048 || !jsonObject(rows[0]))
24
+ return;
25
+ const candidates = Object.keys(rows[0]).filter((k) => k.toLowerCase() === filter.name || k.toLowerCase() + "s" === filter.name);
26
+ if (candidates.length !== 1)
27
+ return;
28
+ const field = candidates[0], needle = filter.caseSensitive
29
+ ? filter.literal
30
+ : filter.literal.toLowerCase();
31
+ const values = [];
32
+ let count = 0, inspected = 0, matchedBytes = 2;
33
+ for (const row of rows) {
34
+ if (!jsonObject(row) ||
35
+ !Object.hasOwn(row, field) ||
36
+ typeof row[field] !== "string")
37
+ return;
38
+ const value = row[field];
39
+ inspected += Buffer.byteLength(value);
40
+ if (inspected > 128 * 1024)
41
+ return;
42
+ if (!(filter.caseSensitive ? value : value.toLowerCase()).includes(needle))
43
+ continue;
44
+ count++;
45
+ matchedBytes += size(value) + 1;
46
+ if (count <= 32 && matchedBytes <= 1536)
47
+ values.push(value);
48
+ }
49
+ return {
50
+ rowsScanned: rows.length,
51
+ field,
52
+ contains: filter.literal,
53
+ caseSensitive: filter.caseSensitive,
54
+ count,
55
+ ...(count === values.length ? { allMatchingValues: values } : {}),
56
+ };
57
+ }
58
+ // A column view is complete only when every source row contains the requested scalar.
59
+ function requestedColumn(question) {
60
+ if (/\b(?:where|except|excluding|distinct|unique|filtered|matching)\b/i.test(question))
61
+ return;
62
+ const match = /\b(?:return|list|give|show|extract)\s+(?:(?:the|me)\s+){0,2}[`"']?([a-z][\w-]*)[`"']?(?:\s+(?:field|column|values?))?\s+(?:for|from|of)\s+(?:all|every|each)\b/i.exec(question) ??
63
+ /\b(?:all|every|each)\s+(?:[a-z][\w-]*\s+)?[`"']?((?!(?:fields?|columns?|values?|in|as|from|for|of)\b)[a-z][\w-]*)[`"']?(?=\s*(?:[.,?!;:]|$)|\s+(?:in|from|including|as|of|for|values?)\b)/i.exec(question);
64
+ return match?.[1]?.toLowerCase();
65
+ }
66
+ function columnValues(rows, term) {
67
+ if (!rows.length || !jsonObject(rows[0]))
68
+ return;
69
+ const keys = Object.keys(rows[0]).filter((k) => k.toLowerCase() === term || k.toLowerCase() + "s" === term);
70
+ if (keys.length !== 1)
71
+ return;
72
+ const field = keys[0], values = [];
73
+ let used = 128 + size(field);
74
+ for (const row of rows) {
75
+ if (!jsonObject(row) || !Object.hasOwn(row, field))
76
+ return;
77
+ const v = row[field];
78
+ if (v !== null && typeof v === "object")
79
+ return;
80
+ if (used <= budget - 256) {
81
+ used += size(v) + 1;
82
+ if (used <= budget - 256)
83
+ values.push(v);
84
+ }
85
+ }
86
+ return values.length === rows.length
87
+ ? { field, complete: true, totalRows: rows.length, values }
88
+ : {
89
+ field,
90
+ complete: false,
91
+ totalRows: rows.length,
92
+ hint: "Inspect the retained rows with fields, offset and limit.",
93
+ };
94
+ }
95
+ // Every numerical statistic is scoped to the returned array.
96
+ function numericRequest(question) {
97
+ if (/\b(?:where|excluding|except|whose|among those|filtered|subject to)\b/i.test(question))
98
+ return;
99
+ const extrema = [
100
+ ...question.matchAll(/\b(greatest|largest|highest|maximum|smallest|lowest|minimum)\s+([a-z_][a-z0-9_]{0,63})\b/gi),
101
+ ];
102
+ const bounds = [
103
+ ...question.matchAll(/\b([a-z_][a-z0-9_]{0,63})\s*(?:>=|<=|>|<)\s*(-?(?:0|[1-9]\d{0,14})(?:\.\d{1,14})?)(?=$|\s|[;,.)](?!\d))/gi),
104
+ ];
105
+ if (bounds.length !== (question.match(/>=|<=|>|</g) ?? []).length ||
106
+ bounds.some((m) => m[2].replace(/\D/g, "").length > 15))
107
+ return;
108
+ if (extrema.length === 1 && !bounds.length) {
109
+ const [, kind, field] = extrema[0];
110
+ return {
111
+ field: field.toLowerCase(),
112
+ kind: /^(smallest|lowest|minimum)$/i.test(kind) ? "min" : "max",
113
+ };
114
+ }
115
+ if (!extrema.length &&
116
+ bounds.length &&
117
+ /\b(count|how many)\b/i.test(question)) {
118
+ const field = bounds[0][1].toLowerCase(), threshold = Number(bounds[0][2]);
119
+ if (Number.isFinite(threshold) &&
120
+ Math.abs(threshold) <= Number.MAX_SAFE_INTEGER &&
121
+ bounds.every((m) => m[1].toLowerCase() === field && Number(m[2]) === threshold))
122
+ return { field, kind: "split", threshold };
123
+ }
124
+ }
125
+ function numericEvidence(rows, spec, words) {
126
+ if (!rows.length || rows.length > 2048 || !jsonObject(rows[0]))
127
+ return;
128
+ const fields = Object.keys(rows[0]).filter((k) => k.toLowerCase() === spec.field);
129
+ if (fields.length !== 1)
130
+ return;
131
+ const field = fields[0];
132
+ let extreme = 0, winner, ties = 0;
133
+ let below = 0, equal = 0;
134
+ for (const row of rows) {
135
+ if (!jsonObject(row) || !Object.hasOwn(row, field))
136
+ return;
137
+ const v = row[field];
138
+ if (typeof v !== "number" ||
139
+ !Number.isFinite(v) ||
140
+ Math.abs(v) > Number.MAX_SAFE_INTEGER)
141
+ return;
142
+ if (spec.kind === "split") {
143
+ if (v < spec.threshold)
144
+ below++;
145
+ else if (v === spec.threshold)
146
+ equal++;
147
+ }
148
+ else if (!winner || (spec.kind === "max" ? v > extreme : v < extreme)) {
149
+ extreme = v;
150
+ winner = row;
151
+ ties = 1;
152
+ }
153
+ else if (v === extreme)
154
+ ties++;
155
+ }
156
+ const coverage = {
157
+ field,
158
+ rowsScanned: rows.length,
159
+ coverage: "Computed from every row in this returned array.",
160
+ };
161
+ if (spec.kind === "split")
162
+ return {
163
+ ...coverage,
164
+ threshold: spec.threshold,
165
+ below,
166
+ equal,
167
+ above: rows.length - below - equal,
168
+ };
169
+ const selected = ties === 1 && winner
170
+ ? Object.fromEntries(Object.entries(winner)
171
+ .filter(([k, v]) => words.has(k.toLowerCase()) && short(v))
172
+ .slice(0, 16))
173
+ : undefined;
174
+ return {
175
+ ...coverage,
176
+ [spec.kind]: extreme,
177
+ ties,
178
+ ...(selected && size(selected) <= 1024 ? { row: selected } : {}),
179
+ };
180
+ }
181
+ // Counts cover every string cell, including text omitted from the displayed columns.
182
+ function countRowText(rows, terms) {
183
+ if (!terms.length || rows.length > 2048)
184
+ return;
185
+ let inspected = 0;
186
+ const counts = terms.map(() => 0);
187
+ for (const row of rows) {
188
+ if (!jsonObject(row))
189
+ return;
190
+ const strings = [];
191
+ for (const v of Object.values(row)) {
192
+ if (v !== null && typeof v === "object")
193
+ return;
194
+ if (typeof v !== "string")
195
+ continue;
196
+ inspected += Buffer.byteLength(v);
197
+ if (inspected > 128 * 1024)
198
+ return;
199
+ strings.push(v.toLowerCase());
200
+ }
201
+ terms.forEach((term, i) => {
202
+ if (strings.some((s) => s.includes(term)))
203
+ counts[i]++;
204
+ });
205
+ }
206
+ return Object.fromEntries(terms.map((term, i) => [term, counts[i]]));
207
+ }
208
+ function rowTable(rows, terms) {
209
+ if (rows.length < 3 || !jsonObject(rows[0]))
210
+ return;
211
+ const columns = Object.keys(rows[0])
212
+ .filter((k) => k.length <= 96 && short(rows[0][k]))
213
+ .slice(0, 16);
214
+ // Envelopes with mostly nested data lose the payload in a scalar table.
215
+ if (!columns.length ||
216
+ (columns.length < 3 &&
217
+ Object.values(rows[0]).some((v) => v !== null && typeof v === "object")))
218
+ return;
219
+ const table = [];
220
+ let used = size(columns) + 96;
221
+ for (const row of rows.slice(0, 100)) {
222
+ if (!jsonObject(row) ||
223
+ !columns.every((k) => Object.hasOwn(row, k) && short(row[k])))
224
+ break;
225
+ const cells = columns.map((k) => row[k]);
226
+ used += size(cells) + 1;
227
+ if (used > budget - 512)
228
+ break;
229
+ table.push(cells);
230
+ }
231
+ if (!table.length)
232
+ return;
233
+ const allRows = table.length === rows.length;
234
+ const distinct = [];
235
+ if (rows.length <= 2048) {
236
+ for (const column of columns) {
237
+ const seen = new Set();
238
+ for (const row of rows) {
239
+ if (!jsonObject(row) ||
240
+ !Object.hasOwn(row, column) ||
241
+ !short(row[column])) {
242
+ seen.clear();
243
+ break;
244
+ }
245
+ seen.add(row[column]);
246
+ if (seen.size > 8)
247
+ break;
248
+ }
249
+ const values = [...seen];
250
+ if (values.length &&
251
+ values.length <= 8 &&
252
+ values.length < rows.length &&
253
+ size([column, values]) <= 96)
254
+ distinct.push([column, values]);
255
+ if (distinct.length === 4)
256
+ break;
257
+ }
258
+ }
259
+ const counts = countRowText(rows, terms);
260
+ return {
261
+ totalRows: rows.length,
262
+ allRows,
263
+ ...(distinct.length
264
+ ? { allDistinctValues: Object.fromEntries(distinct) }
265
+ : {}),
266
+ ...(counts ? { rowsContainingText: counts } : {}),
267
+ columns,
268
+ rows: table,
269
+ };
270
+ }
271
+ /** Only declare a complete table when every original field of every row is represented. */
272
+ function completeRows(rows, summary, inputBytes) {
273
+ if (rows.length > 2048 || !jsonObject(rows[0]))
274
+ return;
275
+ const columns = Object.keys(rows[0]);
276
+ if (!columns.length || columns.length > 16)
277
+ return;
278
+ const cells = [];
279
+ for (const row of rows) {
280
+ if (!jsonObject(row) ||
281
+ Object.keys(row).length !== columns.length ||
282
+ !columns.every((k) => Object.hasOwn(row, k) &&
283
+ (row[k] === null || typeof row[k] !== "object")))
284
+ return;
285
+ cells.push(columns.map((k) => row[k]));
286
+ }
287
+ const full = {
288
+ coverage: {
289
+ rowsScanned: rows.length,
290
+ scope: "Every record in this tool result",
291
+ ...(summary.allDistinctValues
292
+ ? { allDistinctValues: summary.allDistinctValues }
293
+ : {}),
294
+ ...(summary.rowsContainingText
295
+ ? { rowsContainingText: summary.rowsContainingText }
296
+ : {}),
297
+ },
298
+ complete: true,
299
+ columns,
300
+ rows: cells,
301
+ };
302
+ return size(full) <= inputBytes ? full : undefined;
303
+ }
304
+ const writtenLevels = ["one", "two", "three", "four", "five", "six"];
305
+ function outlineLevel(question) {
306
+ if (!/\b(headings?|h[1-6]|atx)\b/i.test(question))
307
+ return;
308
+ const firstSubheading = /\bfirst\s+(?:markdown\s+)?(?:h[2-6]\b|level[- ]+(?:two|three|four|five|six|[2-6])\s+(?:markdown\s+)?heading\b)/i.test(question);
309
+ if (!firstSubheading &&
310
+ !/\b(count|how many|list|all|last|number|outline)\b/i.test(question))
311
+ return;
312
+ const levels = new Set();
313
+ for (const match of question
314
+ .toLowerCase()
315
+ .matchAll(/\bh([1-6])\b|\blevel[ -]+(one|two|three|four|five|six|[1-6])\b/g)) {
316
+ const level = match[1] ?? match[2];
317
+ levels.add(Number(level) || writtenLevels.indexOf(level) + 1);
318
+ }
319
+ return levels.size === 1 ? [...levels][0] : undefined;
320
+ }
321
+ function* atxHeadings(text) {
322
+ let fence = "";
323
+ for (const [line] of text.matchAll(/[^\r\n]+/g)) {
324
+ const marker = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(line);
325
+ if (marker) {
326
+ const run = marker[1], rest = marker[2];
327
+ if (!fence && (run[0] === "~" || !rest.includes("`")))
328
+ fence = run;
329
+ else if (fence &&
330
+ run[0] === fence[0] &&
331
+ run.length >= fence.length &&
332
+ !rest.trim())
333
+ fence = "";
334
+ continue;
335
+ }
336
+ if (fence)
337
+ continue;
338
+ const heading = /^ {0,3}(#{1,6})(?:[ \t]+(.*)|$)/.exec(line);
339
+ if (heading)
340
+ yield {
341
+ line,
342
+ level: heading[1].length,
343
+ title: (heading[2] ?? "").replace(/(?:^|[ \t]+)#+[ \t]*$/, "").trim(),
344
+ };
345
+ }
346
+ }
347
+ export function literalCount(text, literal) {
348
+ if (!literal.length)
349
+ throw new TypeError("Expected a nonempty literal.");
350
+ let count = 0, start = 0;
351
+ for (let i = text.indexOf(literal); i >= 0; i = text.indexOf(literal, start)) {
352
+ count++;
353
+ start = i + literal.length;
354
+ }
355
+ return { literal, count, complete: true, caseSensitive: true };
356
+ }
357
+ /** A declared Markdown projection scans the complete document, including fenced text for literal counts. */
358
+ export function markdownPageFacts(raw, literal, headingLevel = 1) {
359
+ const text = documentText(raw);
360
+ if (text === undefined)
361
+ throw new Error("Markdown facts require a text page of at most 256 KiB.");
362
+ let heading = null;
363
+ for (const entry of atxHeadings(text))
364
+ if (entry.level === headingLevel) {
365
+ heading = entry.title;
366
+ break;
367
+ }
368
+ return {
369
+ heading,
370
+ ...(literal === undefined
371
+ ? {}
372
+ : { literal, count: literalCount(text, literal).count }),
373
+ };
374
+ }
375
+ // The first-read result can claim completeness only for a fully scanned document.
376
+ function documentText(raw) {
377
+ const value = typeof raw === "string"
378
+ ? raw
379
+ : jsonObject(raw)
380
+ ? (raw.markdown ?? raw.text ?? raw.content)
381
+ : undefined;
382
+ if (typeof value === "string" &&
383
+ value.length <= 262144 &&
384
+ Buffer.byteLength(value) <= 262144)
385
+ return value;
386
+ }
387
+ function headingSummary(text, level, exactStart) {
388
+ let count = 0, first = "", last = "";
389
+ for (const heading of atxHeadings(text)) {
390
+ if (heading.level !== level ||
391
+ (exactStart && !heading.line.startsWith("#")))
392
+ continue;
393
+ if (!count)
394
+ first = heading.title;
395
+ last = heading.title;
396
+ count++;
397
+ }
398
+ return {
399
+ syntax: "ATX",
400
+ ...(size(last) <= 512
401
+ ? {
402
+ coverage: "Computed from the entire page. The count and last heading are final, including zero and null.",
403
+ }
404
+ : {}),
405
+ level,
406
+ count,
407
+ complete: true,
408
+ ...(!count ? { first: null, last: null } : {}),
409
+ ...(count && size(first) <= 512 ? { first } : {}),
410
+ ...(count && size(last) <= 512 ? { last } : {}),
411
+ };
412
+ }
413
+ function firstHeading(text) {
414
+ const bytes = Buffer.from(text.slice(0, 65537));
415
+ let prefix = bytes.subarray(0, 65536).toString("utf8");
416
+ if (bytes.length > 65536)
417
+ prefix = prefix.slice(0, Math.max(0, prefix.lastIndexOf("\n"), prefix.lastIndexOf("\r")));
418
+ for (const heading of atxHeadings(prefix)) {
419
+ if (heading.level === 1)
420
+ return heading.line.length <= 512 ? heading : undefined;
421
+ }
422
+ }
423
+ /** Bind only a submitted document URL. Never substitute a provider-reported redirect. */
424
+ export function requestedPageUrl(args) {
425
+ const candidates = ["url", "sourceUrl", "source_url", "uri"]
426
+ .filter((k) => Object.hasOwn(args, k))
427
+ .map((k) => args[k]);
428
+ const url = candidates[0];
429
+ if (typeof url !== "string" ||
430
+ !candidates.every((v) => v === url) ||
431
+ /[\s\x00-\x1f\x7f]/u.test(url))
432
+ return;
433
+ return /^https?:\/\/[^/?#]+(?:[/?#].*)?$/i.test(url) ? url : undefined;
434
+ }
435
+ export function isPageResult(raw) {
436
+ return (typeof raw === "string" ||
437
+ (jsonObject(raw) &&
438
+ ["markdown", "html", "text", "content"].some((k) => typeof raw[k] === "string")));
439
+ }
440
+ function requestedFetchRank(question) {
441
+ if (!/\b(?:url|contenturl|sourceurl|href|uri)\b/i.test(question))
442
+ return;
443
+ const matches = [
444
+ ...question.matchAll(/\b(?:fetch|open|read|visit|retrieve)\s+(?:the\s+)?(?:(?:search\s+)?(?:result|hit)\s+(?:number\s+|#\s*)?([1-9]\d{0,5})\b(?!\.\d)|(?:(first|second|third)\s+)(?:(?:search\s+)?(?:result|hit)|(?:exact\s+)?(?:url|contenturl|href))\b)/gi),
445
+ ];
446
+ if (matches.length !== 1)
447
+ return;
448
+ const [match] = matches;
449
+ if (/^\s*(?:[-–,/]|\b(?:and|or|to|through)\b)\s*(?:#?\d|first|second|third)/i.test(question.slice(match.index + match[0].length)))
450
+ return;
451
+ return match[1]
452
+ ? Number(match[1])
453
+ : ["first", "second", "third"].indexOf(match[2].toLowerCase()) + 1;
454
+ }
455
+ function searchRecords(raw) {
456
+ let value = raw;
457
+ if (typeof raw === "string" &&
458
+ raw.trimStart().startsWith("{") &&
459
+ Buffer.byteLength(raw) <= 128 * 1024) {
460
+ try {
461
+ value = copyJson(JSON.parse(raw));
462
+ }
463
+ catch {
464
+ return;
465
+ }
466
+ }
467
+ if (!jsonObject(value))
468
+ return;
469
+ const lists = [value.results, value.hits].filter(Array.isArray);
470
+ return lists.length === 1 ? lists[0] : undefined;
471
+ }
472
+ function rankedUrl(rows, rank, words) {
473
+ if (rank > rows.length)
474
+ return { rank, totalResults: rows.length, status: "no_match" };
475
+ const hit = rows[rank - 1];
476
+ if (!jsonObject(hit))
477
+ return;
478
+ const fields = Object.keys(hit).filter((k) => /^(?:url|uri|href|contentUrl|sourceUrl|source_url)$/i.test(k));
479
+ const named = fields.filter((k) => /^(?:contentUrl|sourceUrl|source_url)$/i.test(k) &&
480
+ words.has(k.toLowerCase()));
481
+ const urls = new Set((named.length ? named : fields).map((k) => requestedPageUrl({ url: hit[k] })));
482
+ if (urls.size !== 1)
483
+ return;
484
+ const [url] = urls;
485
+ if (url && size(url) <= budget / 2)
486
+ return { rank, totalResults: rows.length, url };
487
+ }
488
+ /** Build a bounded, explicitly partial view. All routing inputs stay in the host. */
489
+ export function prepareAdaptiveRead(question) {
490
+ if (typeof question !== "string" ||
491
+ !question.trim() ||
492
+ Buffer.byteLength(question) > 32768)
493
+ throw new TypeError("adaptiveRead requires a question of 1 to 32768 UTF-8 bytes.");
494
+ const words = new Set(question.toLowerCase().match(/[\p{L}\p{N}_]+/gu) ?? []);
495
+ for (const compound of question
496
+ .toLowerCase()
497
+ .match(/[\p{L}\p{N}_]+(?:[./-][\p{L}\p{N}_]+)+/gu) ?? [])
498
+ words.add(compound);
499
+ const literals = [];
500
+ for (const match of question.matchAll(/(["'`])([^"'\n`]{1,128})\1/g)) {
501
+ const literal = match[2];
502
+ words.add(literal.toLowerCase());
503
+ if (/[\p{L}\p{N}]/u.test(literal) &&
504
+ !/^\s*:/.test(question.slice(match.index + match[0].length)) &&
505
+ !literals.includes(literal))
506
+ literals.push(literal);
507
+ if (literals.length === 4)
508
+ break;
509
+ }
510
+ const fetchRank = requestedFetchRank(question);
511
+ const ranked = new Set([
512
+ ...question
513
+ .toLowerCase()
514
+ .matchAll(/\b(first|last)\s+(?:search\s+)?(?:result|hit)\b/g),
515
+ ].map((m) => m[1]));
516
+ const filter = fieldFilter(question);
517
+ const numeric = numericRequest(question);
518
+ const column = requestedColumn(question);
519
+ const level = outlineLevel(question);
520
+ const exactStart = /lines? starting with exactly/i.test(question);
521
+ const named = [
522
+ ...question.matchAll(/\bliteral\s+(["'`])([^"'\x60\r\n]{1,128})\1/gi),
523
+ ];
524
+ const countTerm = named.length === 1 &&
525
+ /\b(?:how many times|occurrences?)\b/i.test(question) &&
526
+ /\b(?:case-sensitive|exact)\b/i.test(question) &&
527
+ !/\b(?:insensitive|overlapping|excluding|ignore)\b/i.test(question)
528
+ ? named[0][2]
529
+ : undefined;
530
+ // A literal count and a first-title request describe two different facts.
531
+ const onlyFirstTitle = countTerm &&
532
+ level === 1 &&
533
+ /\bfirst (?:markdown )?(?:h1|level[- ]one heading)\b/i.test(question) &&
534
+ !/\b(?:all|last|count|number of|how many)\s+(?:the\s+)?(?:markdown\s+)?(?:h1s?|headings?)\b/i.test(question);
535
+ const wantsHeading = ["heading", "h1", "headings"].some((k) => words.has(k));
536
+ const terms = [...words]
537
+ .filter((t) => t.length >= 4 && t.length <= 48)
538
+ .sort((a, b) => b.length - a.length)
539
+ .slice(0, 8);
540
+ const wantsSource = /\b(?:exact|requested|source|original|result|search hit)\s+(?:(?:result|source)\s+)?url\b|\bcit(?:e|ation)s?\b/i.test(question);
541
+ const metadataKeys = [
542
+ ...new Set([...question.matchAll(/\bmetadata\.([a-zA-Z_][a-zA-Z0-9_]{0,95})/g)].map((m) => m[1])),
543
+ ].slice(0, 16);
544
+ return (raw, fallbackSize, requestedUrl) => {
545
+ const rows = fetchRank && !requestedUrl ? searchRecords(raw) : undefined;
546
+ if (rows && fetchRank) {
547
+ const link = rankedUrl(rows, fetchRank, words);
548
+ if (link)
549
+ return { native: false, selection: { rankedResult: link } };
550
+ }
551
+ const document = !rows && (level || countTerm) ? documentText(raw) : undefined;
552
+ const markdown = document !== undefined &&
553
+ ((jsonObject(raw) && typeof raw.markdown === "string") ||
554
+ !/^\s*[<{\[]/.test(document));
555
+ const outline = level && !onlyFirstTitle && markdown
556
+ ? headingSummary(document, level, exactStart)
557
+ : undefined;
558
+ const occurrences = countTerm && document !== undefined
559
+ ? literalCount(document, countTerm)
560
+ : undefined;
561
+ if (requestedUrl &&
562
+ wantsSource &&
563
+ isPageResult(raw) &&
564
+ (wantsHeading || metadataKeys.length)) {
565
+ const markdown = typeof raw === "string"
566
+ ? raw
567
+ : (raw.markdown ?? raw.text ?? raw.content);
568
+ const heading = wantsHeading && typeof markdown === "string"
569
+ ? firstHeading(markdown)
570
+ : undefined;
571
+ const meta = typeof raw === "string" ? undefined : raw.metadata;
572
+ const selected = jsonObject(meta)
573
+ ? Object.fromEntries(metadataKeys
574
+ .filter((k) => Object.hasOwn(meta, k) && short(meta[k]))
575
+ .map((k) => [k, meta[k]]))
576
+ : {};
577
+ const evidence = {
578
+ ...(outline ? { headings: outline } : {}),
579
+ ...(occurrences ? { occurrences } : {}),
580
+ ...(heading === undefined ? {} : { heading: heading.title }),
581
+ ...(Object.keys(selected).length ? { metadata: selected } : {}),
582
+ };
583
+ if (Object.keys(evidence).length && size(evidence) <= budget)
584
+ return {
585
+ native: false,
586
+ selection: evidence,
587
+ ...(heading
588
+ ? {
589
+ headingEvidence: "heading is the first Markdown H1 in source order. requestedUrl is the exact URL passed to this read.",
590
+ }
591
+ : {}),
592
+ };
593
+ }
594
+ if (outline || occurrences)
595
+ return {
596
+ native: false,
597
+ selection: {
598
+ ...(outline ? { headings: outline } : {}),
599
+ ...(occurrences ? { occurrences } : {}),
600
+ },
601
+ };
602
+ let anchors = 0;
603
+ let complete;
604
+ let remaining = 240, decodeBytes = 128 * 1024;
605
+ function visit(value, depth, field = "") {
606
+ if (depth > 7 || --remaining < 0)
607
+ return { omitted: true };
608
+ if (typeof value === "string") {
609
+ if (decodeBytes && /^\s*(?:\[|\{)/.test(value)) {
610
+ const length = Buffer.byteLength(value);
611
+ if (length <= decodeBytes) {
612
+ decodeBytes -= length;
613
+ try {
614
+ const json = JSON.parse(value, (_k, v) => {
615
+ if (typeof v === "number" &&
616
+ (!Number.isFinite(v) ||
617
+ (Number.isInteger(v) && !Number.isSafeInteger(v))))
618
+ throw new Error("Inexact JSON number.");
619
+ return v;
620
+ });
621
+ return { json: visit(copyJson(json), depth + 1) };
622
+ }
623
+ catch {
624
+ /* A malformed or unsupported document remains text. */
625
+ }
626
+ }
627
+ }
628
+ if (value.length <= 240)
629
+ return value;
630
+ const heading = wantsHeading && (field.toLowerCase() === "markdown" || depth === 0)
631
+ ? firstHeading(value)?.line
632
+ : undefined;
633
+ if (heading !== undefined)
634
+ anchors++;
635
+ const passages = literals.map((literal) => {
636
+ const i = value.indexOf(literal);
637
+ if (i < 0)
638
+ return { literal, found: false };
639
+ anchors++;
640
+ return {
641
+ literal,
642
+ text: Array.from(value.slice(i, i + 480))
643
+ .slice(0, 240)
644
+ .join(""),
645
+ };
646
+ });
647
+ return {
648
+ ...(heading !== undefined ? { firstHeadingLine: heading } : {}),
649
+ ...(!passages.length ||
650
+ (!heading && passages.every((p) => p.found === false))
651
+ ? { prefix: Array.from(value.slice(0, 480)).slice(0, 240).join("") }
652
+ : {}),
653
+ ...(passages.length ? { passages } : {}),
654
+ };
655
+ }
656
+ if (Array.isArray(value)) {
657
+ if (value.length && ranked.size && /^(results|hits)$/i.test(field)) {
658
+ anchors++;
659
+ const hit = (item) => {
660
+ if (wantsSource && jsonObject(item)) {
661
+ const named = Object.keys(item).filter((k) => words.has(k.toLowerCase()));
662
+ if (named.some((k) => /(?:url|href)$/i.test(k) && typeof item[k] === "string") &&
663
+ named.every((k) => typeof item[k] === "string" || short(item[k]))) {
664
+ const picked = Object.fromEntries(named.map((k) => [k, item[k]]));
665
+ if (size(picked) <= budget / 2)
666
+ return picked;
667
+ }
668
+ }
669
+ return visit(item, depth + 1);
670
+ };
671
+ return {
672
+ totalItems: value.length,
673
+ ...(ranked.has("first") ? { first: hit(value[0]) } : {}),
674
+ ...(ranked.has("last")
675
+ ? { last: hit(value[value.length - 1]) }
676
+ : {}),
677
+ };
678
+ }
679
+ if (filter &&
680
+ jsonObject(value[0]) &&
681
+ !Object.keys(value[0]).some((key) => {
682
+ const k = key.toLowerCase();
683
+ return words.has(k) && k !== filter.name && k + "s" !== filter.name;
684
+ })) {
685
+ const evidence = fieldEvidence(value, filter);
686
+ if (evidence) {
687
+ anchors++;
688
+ return { fieldTextMatches: evidence };
689
+ }
690
+ }
691
+ if (column) {
692
+ const projected = columnValues(value, column);
693
+ if (projected) {
694
+ anchors++;
695
+ return { column: projected };
696
+ }
697
+ }
698
+ if (numeric) {
699
+ const facts = numericEvidence(value, numeric, words);
700
+ if (facts) {
701
+ anchors++;
702
+ return { numeric: facts };
703
+ }
704
+ }
705
+ const table = rowTable(value, terms);
706
+ if (table) {
707
+ if (fallbackSize !== undefined) {
708
+ const hasCell = value.some((row) => jsonObject(row) &&
709
+ Object.values(row).some((cell) => typeof cell === "string" &&
710
+ cell.length >= 3 &&
711
+ words.has(cell.toLowerCase())));
712
+ if (hasCell)
713
+ anchors++;
714
+ if (depth === 0 && (!hasCell || !table.allRows))
715
+ complete = completeRows(value, table, fallbackSize);
716
+ }
717
+ return table;
718
+ }
719
+ const items = [];
720
+ let used = 64;
721
+ for (const item of value.slice(0, 8)) {
722
+ const out = visit(item, depth + 1);
723
+ used += size(out) + 1;
724
+ if (used > budget)
725
+ break;
726
+ items.push(out);
727
+ }
728
+ return items.length === value.length
729
+ ? items
730
+ : { items, totalItems: value.length };
731
+ }
732
+ if (!jsonObject(value))
733
+ return value;
734
+ const keys = Object.keys(value);
735
+ const mentioned = keys.filter((k) => words.has(k.toLowerCase()));
736
+ const entries = [];
737
+ let used = 4;
738
+ const nearby = keys.filter((k) => !words.has(k.toLowerCase()) &&
739
+ (short(value[k]) ||
740
+ (Array.isArray(value[k]) &&
741
+ value[k].length <= 4 &&
742
+ value[k].every(short))));
743
+ const direct = new Set([...mentioned, ...nearby]);
744
+ const other = keys.filter((k) => !direct.has(k));
745
+ for (const k of [...direct, ...other].slice(0, 24)) {
746
+ if (k.length > 128 || remaining <= 0)
747
+ continue;
748
+ const previous = anchors;
749
+ const out = visit(value[k], depth + 1, k);
750
+ if (mentioned.length && !direct.has(k) && previous === anchors)
751
+ continue;
752
+ const cost = size(k) + size(out) + 2;
753
+ if (used + cost > budget) {
754
+ anchors = previous;
755
+ continue;
756
+ }
757
+ used += cost;
758
+ entries.push([k, out]);
759
+ if (words.has(k.toLowerCase()))
760
+ anchors++;
761
+ }
762
+ return Object.fromEntries(entries);
763
+ }
764
+ const view = visit(raw, 0);
765
+ if (complete)
766
+ return { native: true, value: complete };
767
+ if (fallbackSize !== undefined &&
768
+ (!anchors ||
769
+ size({
770
+ ref: "result_" + "0".repeat(22),
771
+ partial: true,
772
+ selection: view,
773
+ }) >= fallbackSize))
774
+ return { native: true, value: raw };
775
+ return {
776
+ native: false,
777
+ selection: size(view) <= budget ? view : { omitted: true },
778
+ };
779
+ };
780
+ }