toolsplice 0.0.0-stage → 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 (172) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +104 -2
  3. package/dist/abortable.d.ts +6 -0
  4. package/dist/abortable.js +50 -0
  5. package/dist/adaptive-read.d.ts +50 -0
  6. package/dist/adaptive-read.js +780 -0
  7. package/dist/answer-wait.d.ts +7 -0
  8. package/dist/answer-wait.js +45 -0
  9. package/dist/cache-reads.d.ts +18 -0
  10. package/dist/cache-reads.js +89 -0
  11. package/dist/calibration-ledger.d.ts +37 -0
  12. package/dist/calibration-ledger.js +148 -0
  13. package/dist/calibration-marker.d.ts +4 -0
  14. package/dist/calibration-marker.js +77 -0
  15. package/dist/catalog-setup.d.ts +33 -0
  16. package/dist/catalog-setup.js +89 -0
  17. package/dist/catalog.d.ts +10 -0
  18. package/dist/catalog.js +42 -0
  19. package/dist/checkpoint-files.d.ts +15 -0
  20. package/dist/checkpoint-files.js +99 -0
  21. package/dist/cli.d.ts +2 -0
  22. package/dist/cli.js +1454 -0
  23. package/dist/coalesce-reads.d.ts +6 -0
  24. package/dist/coalesce-reads.js +33 -0
  25. package/dist/codegen.d.ts +44 -0
  26. package/dist/codegen.js +479 -0
  27. package/dist/contract-caller.d.ts +23 -0
  28. package/dist/contract-caller.js +326 -0
  29. package/dist/contract-corrections.d.ts +35 -0
  30. package/dist/contract-corrections.js +159 -0
  31. package/dist/contract-schema.d.ts +7 -0
  32. package/dist/contract-schema.js +156 -0
  33. package/dist/contracts.d.ts +72 -0
  34. package/dist/contracts.js +370 -0
  35. package/dist/core.d.ts +44 -0
  36. package/dist/core.js +43 -0
  37. package/dist/db-final-answer.d.ts +9 -0
  38. package/dist/db-final-answer.js +62 -0
  39. package/dist/define.d.ts +78 -0
  40. package/dist/define.js +14 -0
  41. package/dist/doctor.d.ts +22 -0
  42. package/dist/doctor.js +91 -0
  43. package/dist/drift.d.ts +23 -0
  44. package/dist/drift.js +111 -0
  45. package/dist/execution.d.ts +38 -0
  46. package/dist/execution.js +66 -0
  47. package/dist/extract.d.ts +34 -0
  48. package/dist/extract.js +73 -0
  49. package/dist/final-answer-stores.d.ts +71 -0
  50. package/dist/final-answer-stores.js +72 -0
  51. package/dist/final-answer.d.ts +32 -0
  52. package/dist/final-answer.js +104 -0
  53. package/dist/impact.d.ts +48 -0
  54. package/dist/impact.js +71 -0
  55. package/dist/index.d.ts +51 -0
  56. package/dist/index.js +47 -0
  57. package/dist/local-tool.d.ts +18 -0
  58. package/dist/local-tool.js +32 -0
  59. package/dist/mcp-apps.d.ts +53 -0
  60. package/dist/mcp-apps.js +32 -0
  61. package/dist/mcp-event-delivery.d.ts +98 -0
  62. package/dist/mcp-event-delivery.js +211 -0
  63. package/dist/mcp-extensions.d.ts +46 -0
  64. package/dist/mcp-extensions.js +200 -0
  65. package/dist/mcp-peer.d.ts +45 -0
  66. package/dist/mcp-peer.js +207 -0
  67. package/dist/mcp-server-card.d.ts +21 -0
  68. package/dist/mcp-server-card.js +54 -0
  69. package/dist/ordered-transport.d.ts +12 -0
  70. package/dist/ordered-transport.js +106 -0
  71. package/dist/page-checkpoint.d.ts +71 -0
  72. package/dist/page-checkpoint.js +286 -0
  73. package/dist/page-read-gate.d.ts +15 -0
  74. package/dist/page-read-gate.js +48 -0
  75. package/dist/pattern.d.ts +3 -0
  76. package/dist/pattern.js +54 -0
  77. package/dist/postgres.d.ts +41 -0
  78. package/dist/postgres.js +264 -0
  79. package/dist/probe.d.ts +29 -0
  80. package/dist/probe.js +121 -0
  81. package/dist/proxy.d.ts +40 -0
  82. package/dist/proxy.js +436 -0
  83. package/dist/read-pages.d.ts +25 -0
  84. package/dist/read-pages.js +85 -0
  85. package/dist/read-policy.d.ts +6 -0
  86. package/dist/read-policy.js +16 -0
  87. package/dist/read-steps.d.ts +12 -0
  88. package/dist/read-steps.js +36 -0
  89. package/dist/result-session.d.ts +109 -0
  90. package/dist/result-session.js +620 -0
  91. package/dist/route-checkpoint.d.ts +3 -0
  92. package/dist/route-checkpoint.js +80 -0
  93. package/dist/route-driver-cli.d.ts +3 -0
  94. package/dist/route-driver-cli.js +43 -0
  95. package/dist/route-evaluation.d.ts +141 -0
  96. package/dist/route-evaluation.js +329 -0
  97. package/dist/row-groups.d.ts +17 -0
  98. package/dist/row-groups.js +79 -0
  99. package/dist/row-query.d.ts +62 -0
  100. package/dist/row-query.js +172 -0
  101. package/dist/rules.d.ts +30 -0
  102. package/dist/rules.js +72 -0
  103. package/dist/run-diagnostics.d.ts +75 -0
  104. package/dist/run-diagnostics.js +212 -0
  105. package/dist/runtime.d.ts +6 -0
  106. package/dist/runtime.js +26 -0
  107. package/dist/schema.d.ts +17 -0
  108. package/dist/schema.js +299 -0
  109. package/dist/search-fetch.d.ts +50 -0
  110. package/dist/search-fetch.js +264 -0
  111. package/dist/shape.d.ts +91 -0
  112. package/dist/shape.js +499 -0
  113. package/dist/skill-files.d.ts +9 -0
  114. package/dist/skill-files.js +49 -0
  115. package/dist/splice-diagnostics.d.ts +44 -0
  116. package/dist/splice-diagnostics.js +88 -0
  117. package/dist/splice-measure.d.ts +33 -0
  118. package/dist/splice-measure.js +55 -0
  119. package/dist/splice-project.d.ts +125 -0
  120. package/dist/splice-project.js +348 -0
  121. package/dist/splice-recording.d.ts +132 -0
  122. package/dist/splice-recording.js +481 -0
  123. package/dist/splice.d.ts +181 -0
  124. package/dist/splice.js +1263 -0
  125. package/dist/sqlite-checkpoint-store.d.ts +5 -0
  126. package/dist/sqlite-checkpoint-store.js +91 -0
  127. package/dist/sqlite-checkpoint-worker.d.ts +1 -0
  128. package/dist/sqlite-checkpoint-worker.js +115 -0
  129. package/dist/storage.d.ts +17 -0
  130. package/dist/storage.js +1 -0
  131. package/dist/store.d.ts +151 -0
  132. package/dist/store.js +735 -0
  133. package/dist/test-difference.d.ts +13 -0
  134. package/dist/test-difference.js +42 -0
  135. package/dist/testing.d.ts +122 -0
  136. package/dist/testing.js +261 -0
  137. package/dist/text-pages.d.ts +24 -0
  138. package/dist/text-pages.js +36 -0
  139. package/dist/tool-discovery.d.ts +59 -0
  140. package/dist/tool-discovery.js +136 -0
  141. package/dist/unevaluated.d.ts +7 -0
  142. package/dist/unevaluated.js +156 -0
  143. package/dist/v2.d.ts +49 -0
  144. package/dist/v2.js +413 -0
  145. package/dist/validate-output.d.ts +3 -0
  146. package/dist/validate-output.js +73 -0
  147. package/dist/version.d.ts +1 -0
  148. package/dist/version.js +1 -0
  149. package/dist/workflow-json.d.ts +8 -0
  150. package/dist/workflow-json.js +74 -0
  151. package/docs/AGENT-FRAMEWORKS.md +431 -0
  152. package/docs/BENCHMARKS.md +43 -0
  153. package/docs/INTEGRATION-QUICKSTART.md +859 -0
  154. package/docs/LEARNING-AND-STORAGE.md +393 -0
  155. package/docs/MCP.md +204 -0
  156. package/docs/PROJECTS-AND-UPGRADES.md +173 -0
  157. package/docs/PYTHON-REFERENCE.md +348 -0
  158. package/docs/PYTHON.md +120 -0
  159. package/docs/RECORDING-AND-CORRECTIONS.md +205 -0
  160. package/docs/TESTING.md +259 -0
  161. package/examples/mcp-app/build.mjs +11 -0
  162. package/examples/mcp-app/view.mjs +22 -0
  163. package/examples/quickstart.mjs +43 -0
  164. package/examples/route-driver.mjs +67 -0
  165. package/integrations/ai.d.mts +36 -0
  166. package/integrations/ai.mjs +178 -0
  167. package/integrations/call-options.mjs +9 -0
  168. package/integrations/langchain.d.mts +31 -0
  169. package/integrations/langchain.mjs +114 -0
  170. package/integrations/managed.mjs +154 -0
  171. package/integrations/types.d.mts +13 -0
  172. package/package.json +139 -4
package/dist/v2.js ADDED
@@ -0,0 +1,413 @@
1
+ import { bindingOptions } from "./runtime.js";
2
+ import { describeOutput } from "./codegen.js";
3
+ import { definitionFingerprint, learnedContract, recordDrift, resetLearning, stableHash } from "./drift.js";
4
+ import { extract } from "./extract.js";
5
+ import { DEFAULT_OPTIONS, hasEmbeddedJson } from "./shape.js";
6
+ import { applyExamplePolicy, newServer, recordCall, recordToolList } from "./store.js";
7
+ /** Structural SDK 2.x adapter; no SDK 2.x runtime dependency. */
8
+ export function createV2ToolCaller(client, defaults) {
9
+ bindingOptions(defaults);
10
+ return (request, options) => client.callTool(request, bindingOptions(options, defaults));
11
+ }
12
+ // Node 24's Undici clone finalizer can cancel the original tee branch if the
13
+ // clone wrapper is collected while learning waits in a writer queue. Retain
14
+ // that wrapper for the original Response's lifetime, without retaining either
15
+ // response after its consumer releases it.
16
+ const observedResponses = new WeakMap();
17
+ function object(value) {
18
+ return value !== null && typeof value === "object" && !Array.isArray(value);
19
+ }
20
+ export function createV2Adapter(options) {
21
+ const { store, serverName, enrich = "description", minSamples = 1, maxDescriptionLength = 2000, maxResponseBytes = 2 * 1024 * 1024, observationTimeoutMs = 1000, notificationDebounceMs = 50 } = options;
22
+ if (!serverName)
23
+ throw new Error("v2 adapter requires an explicit serverName.");
24
+ if (!["none", "description"].includes(enrich))
25
+ throw new Error("v2 adapter supports none or description enrichment only.");
26
+ if (options.examples !== undefined && !["none", "safe", "all"].includes(options.examples))
27
+ throw new Error("Invalid example policy.");
28
+ for (const [name, value, min] of [["minSamples", minSamples, 1], ["maxDescriptionLength", maxDescriptionLength, 80], ["maxResponseBytes", maxResponseBytes, 256], ["observationTimeoutMs", observationTimeoutMs, 1], ["notificationDebounceMs", notificationDebounceMs, 0]]) {
29
+ if (!Number.isSafeInteger(value) || value < min)
30
+ throw new Error(`${name} must be an integer >= ${min}.`);
31
+ }
32
+ const observeOptions = { ...DEFAULT_OPTIONS, examples: options.examples ?? "none" };
33
+ const log = (message) => { try {
34
+ options.log?.(message);
35
+ }
36
+ catch { } };
37
+ let record = newServer(serverName), version = options.serverVersion, disposed = false;
38
+ const advertised = new Map();
39
+ let scan;
40
+ const pending = new Set();
41
+ let timer;
42
+ function changed(name) {
43
+ if (!options.onChanged || disposed)
44
+ return;
45
+ pending.add(name);
46
+ if (timer)
47
+ return;
48
+ timer = setTimeout(() => {
49
+ timer = undefined;
50
+ const tools = [...pending].sort();
51
+ pending.clear();
52
+ if (!tools.length)
53
+ return;
54
+ try {
55
+ Promise.resolve(options.onChanged({ serverName, tools })).catch(() => log("v2 change callback failed."));
56
+ }
57
+ catch {
58
+ log("v2 change callback failed.");
59
+ }
60
+ }, notificationDebounceMs);
61
+ timer.unref();
62
+ }
63
+ let learningQueue = Promise.resolve();
64
+ function learn(mutate) {
65
+ // Serialize this adapter's fan-out before contending with other processes.
66
+ // A failed operation must not poison the queue for later observations.
67
+ const operation = learningQueue.then(() => doLearn(mutate));
68
+ learningQueue = operation.catch(() => { });
69
+ return operation;
70
+ }
71
+ async function doLearn(mutate) {
72
+ let entered = false;
73
+ const deadline = Date.now() + 500;
74
+ for (let attempt = 0;; attempt++) {
75
+ try {
76
+ await store.transact(serverName, (latest) => {
77
+ entered = true;
78
+ record = latest;
79
+ if (version && latest.version && latest.version !== version)
80
+ for (const t of Object.values(latest.tools))
81
+ resetLearning(t, "server-version");
82
+ if (version)
83
+ latest.version = version;
84
+ applyExamplePolicy(latest, observeOptions);
85
+ mutate(latest);
86
+ });
87
+ // The lock is released. Yield before this queue's next transaction so
88
+ // another process can acquire it during sustained code-mode fan-out.
89
+ await new Promise((r) => setTimeout(r, 1));
90
+ return;
91
+ }
92
+ catch (error) {
93
+ const code = object(error) ? error.code : undefined;
94
+ if (!entered && (code === "LOCKED" || code === "CONFLICT") && Date.now() < deadline) {
95
+ const delay = Math.min(30, 3 * (attempt + 1)) + Math.floor(Math.random() * 5);
96
+ await new Promise((r) => setTimeout(r, delay));
97
+ continue;
98
+ }
99
+ if (!entered) {
100
+ try {
101
+ applyExamplePolicy(record, observeOptions);
102
+ mutate(record);
103
+ }
104
+ catch { }
105
+ }
106
+ log("v2 learning could not be persisted; response remains available.");
107
+ return;
108
+ }
109
+ }
110
+ }
111
+ function enrichTool(tool, rec) {
112
+ if (enrich === "none" || !rec || rec.shape.count + rec.kinds.text < minSamples)
113
+ return tool;
114
+ if (tool.outputSchema && rec.kinds.structured > 0 && !hasEmbeddedJson(rec.shape))
115
+ return tool;
116
+ let summary = describeOutput(rec)?.replace(/\(learned from \d+ responses?\)/, "(observed; may vary)");
117
+ if (!summary)
118
+ return tool;
119
+ if (summary.length > maxDescriptionLength)
120
+ summary = summary.slice(0, maxDescriptionLength - 35) + "… [inspect full types with emit-ts]";
121
+ return { ...tool, description: [typeof tool.description === "string" ? tool.description.trim() : "", summary].filter(Boolean).join("\n\n") };
122
+ }
123
+ function fingerprint(tool) {
124
+ return stableHash({ description: tool.description, outputSchema: tool.outputSchema });
125
+ }
126
+ async function mapMessage(raw, request) {
127
+ if (disposed || !object(raw) || raw.id !== request.id || !object(raw.result) || raw.error !== undefined)
128
+ return raw;
129
+ const result = raw.result;
130
+ // Multi-round-trip challenges and future result types must pass unchanged,
131
+ // without being counted as completed tool observations.
132
+ if (result.resultType !== undefined && result.resultType !== "complete")
133
+ return raw;
134
+ const metaInfo = object(result._meta) ? result._meta["io.modelcontextprotocol/serverInfo"] : undefined;
135
+ const info = object(result.serverInfo) ? result.serverInfo : object(metaInfo) ? metaInfo : undefined;
136
+ if (!options.serverVersion && typeof info?.version === "string")
137
+ version = info.version;
138
+ if (request.method === "tools/list" && Array.isArray(result.tools) && result.tools.every((t) => object(t) && typeof t.name === "string")) {
139
+ const tools = result.tools;
140
+ await learn((current) => {
141
+ for (const t of tools) {
142
+ const previous = Object.hasOwn(current.tools, t.name) ? current.tools[t.name] : undefined;
143
+ if (previous?.inputSchema && definitionFingerprint(previous) !== definitionFingerprint({ inputSchema: t.inputSchema, outputSchema: t.outputSchema }))
144
+ resetLearning(previous, "tool-definition");
145
+ }
146
+ recordToolList(current, tools);
147
+ const cursor = object(request.params) ? request.params.cursor : undefined;
148
+ if (cursor === undefined)
149
+ scan = { expectedCursor: undefined, names: new Set(), seen: new Set() };
150
+ // Native v2 listTools aggregates pages above fetch. Only a complete,
151
+ // contiguous head-to-tail chain is authoritative for removals.
152
+ if (scan && scan.expectedCursor === cursor && (cursor === undefined || (typeof cursor === "string" && !scan.seen.has(cursor))) &&
153
+ (result.nextCursor === undefined || typeof result.nextCursor === "string")) {
154
+ if (typeof cursor === "string")
155
+ scan.seen.add(cursor);
156
+ for (const tool of tools)
157
+ scan.names.add(tool.name);
158
+ scan.expectedCursor = typeof result.nextCursor === "string" && result.nextCursor ? result.nextCursor : undefined;
159
+ }
160
+ else
161
+ scan = undefined;
162
+ if (scan && !scan.expectedCursor) {
163
+ for (const name of Object.keys(current.tools))
164
+ if (!scan.names.has(name)) {
165
+ delete current.tools[name];
166
+ advertised.delete(name);
167
+ pending.delete(name);
168
+ }
169
+ scan = undefined;
170
+ }
171
+ });
172
+ let modified = false;
173
+ const enriched = tools.map((tool) => {
174
+ const next = enrichTool(tool, Object.hasOwn(record.tools, tool.name) ? record.tools[tool.name] : undefined);
175
+ advertised.set(tool.name, fingerprint(next));
176
+ if (next !== tool)
177
+ modified = true;
178
+ return next;
179
+ });
180
+ return modified ? { ...raw, result: { ...result, tools: enriched } } : raw;
181
+ }
182
+ if (request.method === "tools/call" && object(request.params) && typeof request.params.name === "string" && Array.isArray(result.content)) {
183
+ const name = request.params.name;
184
+ const extracted = extract(result);
185
+ await learn((current) => {
186
+ const before = Object.hasOwn(current.tools, name) ? current.tools[name] : undefined;
187
+ const contract = before ? learnedContract(before) : undefined;
188
+ const count = before ? before.shape.count + before.kinds.text + before.kinds.empty : 0;
189
+ const rec = recordCall(current, name, extracted, observeOptions);
190
+ recordDrift(rec, contract, count, extracted.kind);
191
+ });
192
+ const rec = Object.hasOwn(record.tools, name) ? record.tools[name] : undefined;
193
+ if (rec && advertised.has(name)) {
194
+ const next = enrichTool({ name, description: rec.description, outputSchema: rec.outputSchema }, rec);
195
+ const hash = fingerprint(next);
196
+ if (hash !== advertised.get(name)) {
197
+ advertised.set(name, hash);
198
+ changed(name);
199
+ }
200
+ }
201
+ }
202
+ return raw;
203
+ }
204
+ async function transformJson(text, request) {
205
+ try {
206
+ const raw = JSON.parse(text);
207
+ const mapped = await mapMessage(raw, request);
208
+ return raw === mapped ? text : JSON.stringify(mapped);
209
+ }
210
+ catch {
211
+ log("v2 response observation skipped; payload preserved.");
212
+ return text;
213
+ }
214
+ }
215
+ function responseWith(response, body) {
216
+ const headers = new Headers(response.headers);
217
+ // fetch has already decoded the body, and an enriched response has a new entity.
218
+ for (const h of ["content-length", "content-encoding", "etag", "content-md5", "digest", "content-digest"])
219
+ headers.delete(h);
220
+ return new Response(body, { status: response.status, statusText: response.statusText, headers });
221
+ }
222
+ const middleware = (next) => async (input, init) => {
223
+ // SDK 2.3.1 serializes JSON-RPC POSTs into init.body strings. Other body
224
+ // forms, batches, and long-lived subscription requests are untouched.
225
+ let request;
226
+ if (!disposed && typeof init?.body === "string") {
227
+ try {
228
+ const body = JSON.parse(init.body);
229
+ if (object(body) && ["tools/list", "tools/call"].includes(String(body.method)) && (typeof body.id === "string" || typeof body.id === "number"))
230
+ request = body;
231
+ }
232
+ catch { }
233
+ }
234
+ const response = await next(input, init);
235
+ if (!request || !response.ok || !response.body)
236
+ return response;
237
+ const contentType = response.headers.get("content-type")?.split(";")[0].trim().toLowerCase();
238
+ if (contentType === "application/json") {
239
+ const observed = response.clone();
240
+ observedResponses.set(response, observed);
241
+ const reader = observed.body.getReader();
242
+ const decoder = new TextDecoder();
243
+ let text = "", bytes = 0;
244
+ let deadlineTimer;
245
+ const deadline = new Promise((_, reject) => {
246
+ deadlineTimer = setTimeout(() => reject(new Error("Observation deadline reached.")), observationTimeoutMs);
247
+ });
248
+ try {
249
+ while (true) {
250
+ const item = await Promise.race([reader.read(), deadline]);
251
+ if (item.done)
252
+ break;
253
+ bytes += item.value.byteLength;
254
+ if (bytes > maxResponseBytes) {
255
+ void reader.cancel().catch(() => { });
256
+ log("v2 oversized response left unobserved.");
257
+ return response;
258
+ }
259
+ text += decoder.decode(item.value, { stream: true });
260
+ }
261
+ text += decoder.decode();
262
+ const mapped = await transformJson(text, request);
263
+ if (mapped === text)
264
+ return response;
265
+ void response.body.cancel().catch(() => { });
266
+ return responseWith(response, mapped);
267
+ }
268
+ catch {
269
+ // Awaiting a tee branch's cancel can itself wait for the SDK to consume
270
+ // the original branch. Fire it and return the original immediately.
271
+ void reader.cancel().catch(() => { });
272
+ log("v2 response observation skipped; payload preserved.");
273
+ return response;
274
+ }
275
+ finally {
276
+ clearTimeout(deadlineTimer);
277
+ }
278
+ }
279
+ if (contentType !== "text/event-stream")
280
+ return response;
281
+ const context = request, decoder = new TextDecoder(), encoder = new TextEncoder();
282
+ // Keep byte slices, not a repeatedly concatenated/rescanned partial frame.
283
+ // CR ends a line immediately; skipLF remembers a possible following LF,
284
+ // including when the CRLF pair straddles chunks. Mixed endings are legal.
285
+ let parts = [], frameBytes = 0, lineHasData = false, skipLF = false, bypass = false;
286
+ let workDeadline = performance.now() + 8;
287
+ function workBudget() {
288
+ if (performance.now() < workDeadline)
289
+ return;
290
+ // Awaited microtasks alone can starve fetch aborts and request timers when
291
+ // a source has thousands of already-queued tiny chunks.
292
+ return new Promise((resolve) => setTimeout(resolve, 0)).then(() => { workDeadline = performance.now() + 8; });
293
+ }
294
+ async function frame(bytes) {
295
+ const text = decoder.decode(bytes);
296
+ const lines = [];
297
+ const line = /([^\r\n]*)(\r\n|\r|\n|$)/g;
298
+ let match;
299
+ while ((match = line.exec(text)) && match[0])
300
+ lines.push({ value: match[1], ending: match[2] });
301
+ const data = lines.filter((line) => line.value.startsWith("data:")).map((line) => line.value.slice(5).replace(/^ /, ""));
302
+ if (!data.length)
303
+ return bytes;
304
+ const original = data.join("\n"), mapped = await transformJson(original, context);
305
+ if (mapped === original)
306
+ return bytes;
307
+ let emitted = false;
308
+ return encoder.encode(lines.map((line) => {
309
+ if (!line.value.startsWith("data:"))
310
+ return line.value + line.ending;
311
+ if (emitted)
312
+ return "";
313
+ emitted = true;
314
+ return `data: ${mapped}${line.ending}`;
315
+ }).join(""));
316
+ }
317
+ async function emitFrame(controller) {
318
+ // Flatten once, only after a complete event. Incomplete frames are never
319
+ // rescanned or flattened as more chunks arrive.
320
+ const bytes = new Uint8Array(frameBytes);
321
+ let offset = 0;
322
+ for (const part of parts) {
323
+ bytes.set(part, offset);
324
+ offset += part.byteLength;
325
+ }
326
+ parts = [];
327
+ frameBytes = 0;
328
+ controller.enqueue(await frame(bytes));
329
+ }
330
+ // A long incomplete event can contain thousands of tiny upstream fragments.
331
+ // Forward bounded blocks so a single flush cannot queue one task per fragment.
332
+ async function forwardBuffered(controller) {
333
+ let first = 0;
334
+ while (first < parts.length) {
335
+ let end = first + 1, size = parts[first].byteLength;
336
+ while (end < parts.length && size + parts[end].byteLength <= 64 * 1024) {
337
+ size += parts[end++].byteLength;
338
+ }
339
+ if (end === first + 1)
340
+ controller.enqueue(parts[first]);
341
+ else
342
+ controller.enqueue(Buffer.concat(parts.slice(first, end), size));
343
+ first = end;
344
+ const pause = workBudget();
345
+ if (pause)
346
+ await pause;
347
+ }
348
+ parts = [];
349
+ frameBytes = 0;
350
+ }
351
+ const stream = response.body.pipeThrough(new TransformStream({
352
+ async transform(chunk, controller) {
353
+ const yieldChunk = workBudget();
354
+ if (yieldChunk)
355
+ await yieldChunk;
356
+ if (bypass) {
357
+ controller.enqueue(chunk);
358
+ return;
359
+ }
360
+ let start = 0;
361
+ for (let i = 0; i < chunk.byteLength; i++) {
362
+ if (i > 0 && (i & 0xffff) === 0) {
363
+ const yieldBlock = workBudget();
364
+ if (yieldBlock)
365
+ await yieldBlock;
366
+ }
367
+ if (frameBytes + i - start + 1 > maxResponseBytes) {
368
+ await forwardBuffered(controller);
369
+ controller.enqueue(start ? chunk.subarray(start) : chunk);
370
+ bypass = true;
371
+ log("v2 oversized SSE stream left unobserved.");
372
+ return;
373
+ }
374
+ const byte = chunk[i];
375
+ if (skipLF) {
376
+ skipLF = false;
377
+ if (byte === 10) {
378
+ // A blank CR may already have emitted the event. Forward its LF
379
+ // immediately: downstream parsers can wait for it to finish CRLF.
380
+ if (!frameBytes && start === i) {
381
+ controller.enqueue(chunk.subarray(i, i + 1));
382
+ start = i + 1;
383
+ }
384
+ continue;
385
+ }
386
+ }
387
+ if (byte !== 10 && byte !== 13) {
388
+ lineHasData = true;
389
+ continue;
390
+ }
391
+ skipLF = byte === 13;
392
+ const complete = !lineHasData;
393
+ lineHasData = false;
394
+ if (!complete)
395
+ continue;
396
+ const part = chunk.subarray(start, i + 1);
397
+ parts.push(part);
398
+ frameBytes += part.byteLength;
399
+ start = i + 1;
400
+ await emitFrame(controller);
401
+ }
402
+ if (start < chunk.byteLength) {
403
+ const part = start ? chunk.subarray(start) : chunk;
404
+ parts.push(part);
405
+ frameBytes += part.byteLength;
406
+ }
407
+ },
408
+ flush: forwardBuffered,
409
+ }));
410
+ return responseWith(response, stream);
411
+ };
412
+ return { middleware, dispose() { disposed = true; clearTimeout(timer); pending.clear(); } };
413
+ }
@@ -0,0 +1,3 @@
1
+ import type { ToolRecord } from "./store.js";
2
+ import type { ToolResultLike } from "./extract.js";
3
+ export declare function validateOutput(tool: ToolRecord, result: ToolResultLike): void;
@@ -0,0 +1,73 @@
1
+ // Diagnostics only. The upstream result is never rewritten or rejected by this validator.
2
+ import { Ajv2020 } from "ajv/dist/2020.js";
3
+ import { contract, stableHash } from "./drift.js";
4
+ const ajv = new Ajv2020({ strict: false, validateFormats: false, allErrors: false, addUsedSchema: false });
5
+ const cache = new Map();
6
+ const MAX_CACHE = 128;
7
+ export function validateOutput(tool, result) {
8
+ if (!tool.outputSchema || result.isError)
9
+ return;
10
+ const state = (tool.schemaValidation ??= { checked: 0, mismatches: 0, latest: "unverified", paths: [] });
11
+ if (result.structuredContent === undefined) {
12
+ state.checked++;
13
+ state.mismatches++;
14
+ state.latest = "mismatch";
15
+ state.paths = ["/structuredContent (missing)"];
16
+ return;
17
+ }
18
+ let raw;
19
+ try {
20
+ raw = JSON.stringify(tool.outputSchema);
21
+ }
22
+ catch {
23
+ state.latest = "unverified";
24
+ return;
25
+ }
26
+ if (raw.length > 50_000 || !withinDepth(tool.outputSchema, 32)) {
27
+ state.latest = "unverified";
28
+ return;
29
+ }
30
+ // Evaluate structural constraints only. Running arbitrary regexes from an upstream schema
31
+ // on tool data would add a new way to stall a pass-through proxy.
32
+ const schema = contract(tool.outputSchema);
33
+ if (!withinDepth(result.structuredContent, 32)) {
34
+ state.latest = "unverified";
35
+ return;
36
+ }
37
+ const key = stableHash(schema);
38
+ if (!cache.has(key)) {
39
+ if (cache.size >= MAX_CACHE)
40
+ cache.delete(cache.keys().next().value);
41
+ try {
42
+ cache.set(key, ajv.compile(schema));
43
+ }
44
+ catch {
45
+ cache.set(key, undefined);
46
+ }
47
+ }
48
+ const validate = cache.get(key);
49
+ if (!validate) {
50
+ state.latest = "unverified";
51
+ return;
52
+ }
53
+ state.checked++;
54
+ if (validate(result.structuredContent)) {
55
+ state.latest = "valid";
56
+ state.paths = [];
57
+ }
58
+ else {
59
+ state.mismatches++;
60
+ state.latest = "mismatch";
61
+ // Paths and schema keywords explain the fault without persisting actual returned values.
62
+ state.paths = (validate.errors ?? []).slice(0, 4).map((e) => `${e.instancePath || "/"} (${e.keyword})`);
63
+ }
64
+ }
65
+ function withinDepth(v, remaining, budget = { remaining: 5000 }) {
66
+ if (--budget.remaining < 0)
67
+ return false;
68
+ if (!v || typeof v !== "object")
69
+ return true;
70
+ if (remaining <= 0)
71
+ return false;
72
+ return Object.values(v).every((x) => withinDepth(x, remaining - 1, budget));
73
+ }
@@ -0,0 +1 @@
1
+ export declare const VERSION = "0.0.2";
@@ -0,0 +1 @@
1
+ export const VERSION = "0.0.2";
@@ -0,0 +1,8 @@
1
+ export declare const JSON_LIMIT: number;
2
+ export declare const jsonObject: (value: unknown) => value is Record<string, unknown>;
3
+ export declare function copyJson<T>(value: T, maxBytes?: number): T;
4
+ export declare function parseWorkflowJson(value: unknown): unknown;
5
+ export declare function jsonFingerprint(value: unknown): string;
6
+ export declare const escapePointer: (key: string) => string;
7
+ export declare function pointerParts(pointer: string): string[];
8
+ export declare function replaceOwnPointer(root: unknown, pointer: string, value: unknown): unknown;
@@ -0,0 +1,74 @@
1
+ // Shared bounded JSON helpers. No schema execution or filesystem access.
2
+ import { assertContractJson } from "./contract-schema.js";
3
+ import { stableHash } from "./drift.js";
4
+ export const JSON_LIMIT = 5 * 1024 * 1024;
5
+ export const jsonObject = (value) => !!value && typeof value === "object" && !Array.isArray(value);
6
+ export function copyJson(value, maxBytes = JSON_LIMIT) {
7
+ assertContractJson(value, undefined, undefined, maxBytes);
8
+ const encoded = JSON.stringify(value);
9
+ if (Buffer.byteLength(encoded) > maxBytes)
10
+ throw new Error("Workflow JSON exceeds its byte limit.");
11
+ return JSON.parse(encoded);
12
+ }
13
+ export function parseWorkflowJson(value) {
14
+ if (typeof value !== "string")
15
+ return copyJson(value);
16
+ if (Buffer.byteLength(value) > JSON_LIMIT)
17
+ throw new Error("Workflow JSON exceeds its byte limit.");
18
+ try {
19
+ return copyJson(JSON.parse(value));
20
+ }
21
+ catch {
22
+ throw new Error("Workflow artifact must contain bounded JSON.");
23
+ }
24
+ }
25
+ function canonical(value) {
26
+ if (Array.isArray(value))
27
+ return value.map(canonical);
28
+ if (!jsonObject(value))
29
+ return value;
30
+ return Object.fromEntries(Object.keys(value)
31
+ .sort()
32
+ .map((key) => [key, canonical(value[key])]));
33
+ }
34
+ export function jsonFingerprint(value) {
35
+ return stableHash(canonical(copyJson(value)));
36
+ }
37
+ export const escapePointer = (key) => key.replace(/~/g, "~0").replace(/\//g, "~1");
38
+ export function pointerParts(pointer) {
39
+ if (typeof pointer !== "string" ||
40
+ pointer.length > 2048 ||
41
+ (pointer !== "" && !pointer.startsWith("/")) ||
42
+ /~(?:[^01]|$)/.test(pointer))
43
+ throw new Error("Expected a bounded RFC 6901 JSON pointer.");
44
+ const parts = pointer === ""
45
+ ? []
46
+ : pointer
47
+ .slice(1)
48
+ .split("/")
49
+ .map((p) => p.replace(/~1/g, "/").replace(/~0/g, "~"));
50
+ if (parts.length > 64)
51
+ throw new Error("JSON pointer exceeds its depth limit.");
52
+ return parts;
53
+ }
54
+ export function replaceOwnPointer(root, pointer, value) {
55
+ const parts = pointerParts(pointer);
56
+ if (!parts.length)
57
+ return value;
58
+ let parent = root;
59
+ for (const key of parts.slice(0, -1)) {
60
+ if (!parent || typeof parent !== "object" || !Object.hasOwn(parent, key))
61
+ throw new Error("Restoration path is absent.");
62
+ parent = parent[key];
63
+ }
64
+ const key = parts.at(-1);
65
+ if (!parent || typeof parent !== "object" || !Object.hasOwn(parent, key))
66
+ throw new Error("Restoration path is absent.");
67
+ Object.defineProperty(parent, key, {
68
+ value,
69
+ enumerable: true,
70
+ writable: true,
71
+ configurable: true,
72
+ });
73
+ return root;
74
+ }