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/splice.js ADDED
@@ -0,0 +1,1263 @@
1
+ // Tool-to-tool handoff analysis and adapters. No workflow code execution, model calls, or credential discovery,
2
+ // automatic field guessing, coercion, retries, or implicit array fanout.
3
+ import { stableHash } from "./drift.js";
4
+ import { assertContractJson } from "./contract-schema.js";
5
+ import { parseContractSnapshot, createContractSnapshot, selectContractTools, } from "./contracts.js";
6
+ import { createContractCaller, ContractValidationError, } from "./contract-caller.js";
7
+ import { invokeTool, } from "./execution.js";
8
+ import { parseJsonText } from "./extract.js";
9
+ import { emitModule } from "./codegen.js";
10
+ import { newServer, recordToolList } from "./store.js";
11
+ import { validateRules, ruleEvaluator } from "./rules.js";
12
+ import { toolUi } from "./mcp-apps.js";
13
+ class MappingFault extends Error {
14
+ code;
15
+ path;
16
+ constructor(code, path, message) {
17
+ super(message);
18
+ this.code = code;
19
+ this.path = path;
20
+ }
21
+ }
22
+ export class SpliceError extends Error {
23
+ stage;
24
+ completedTargets;
25
+ /** Rows submitted in read waves, possibly beyond the successful in-order prefix. */
26
+ scheduledTargets;
27
+ issues;
28
+ constructor(stage, completedTargets, cause, details) {
29
+ const issues = details ??
30
+ (cause instanceof ContractValidationError
31
+ ? cause.issues.map((i) => ({
32
+ severity: "error",
33
+ code: `validation-${i.keyword}`,
34
+ path: i.path,
35
+ message: `Contract ${cause.stage} check rejected this value.`,
36
+ }))
37
+ : cause instanceof MappingFault
38
+ ? [
39
+ {
40
+ severity: "error",
41
+ code: cause.code,
42
+ path: cause.path,
43
+ message: cause.message,
44
+ },
45
+ ]
46
+ : []);
47
+ super(`Toolsplice ${stage} failed; ${completedTargets} target call(s) acknowledged complete.${issues[0] ? ` ${issues[0].code} at ${JSON.stringify(issues[0].path)}.` : ""}`, { cause });
48
+ this.stage = stage;
49
+ this.completedTargets = completedTargets;
50
+ this.name = "SpliceError";
51
+ this.issues = issues;
52
+ }
53
+ }
54
+ const object = (v) => !!v && typeof v === "object" && !Array.isArray(v);
55
+ const ptr = (key) => key.replace(/~/g, "~0").replace(/\//g, "~1");
56
+ const schema = (v) => typeof v === "boolean" || object(v);
57
+ function segments(pointer) {
58
+ if (pointer === "")
59
+ return [];
60
+ if (pointer.length > 2048 ||
61
+ !pointer.startsWith("/") ||
62
+ /~(?:[^01]|$)/.test(pointer))
63
+ throw new Error("Splice paths must be bounded RFC 6901 JSON pointers.");
64
+ const result = pointer
65
+ .slice(1)
66
+ .split("/")
67
+ .map((k) => k.replace(/~1/g, "/").replace(/~0/g, "~"));
68
+ if (result.length > 32)
69
+ throw new Error("Splice paths may contain at most 32 segments.");
70
+ return result;
71
+ }
72
+ function ownPath(value, path) {
73
+ let current = value;
74
+ for (const key of path) {
75
+ if (!current ||
76
+ typeof current !== "object" ||
77
+ (Array.isArray(current) && !/^(0|[1-9]\d*)$/.test(key)) ||
78
+ !Object.hasOwn(current, key))
79
+ return { found: false, value: undefined };
80
+ current = current[key];
81
+ }
82
+ return { found: true, value: current };
83
+ }
84
+ function namedFields(fields) {
85
+ return Object.keys(fields).sort().map(name => [name, fields[name]]);
86
+ }
87
+ export function readSplicePath(value, pointer) {
88
+ return ownPath(value, segments(pointer));
89
+ }
90
+ const knownKeys = (v, keys) => Object.keys(v).every((k) => keys.includes(k));
91
+ export function parseSpliceSpec(source) {
92
+ if (typeof source === "string" && Buffer.byteLength(source) > 1024 * 1024)
93
+ throw new Error("Splice plan exceeds 1 MiB.");
94
+ let v;
95
+ try {
96
+ v = typeof source === "string" ? JSON.parse(source) : source;
97
+ }
98
+ catch {
99
+ throw new Error("Splice plan is not valid JSON.");
100
+ }
101
+ assertContractJson(v, 10000, 40);
102
+ if (Buffer.byteLength(JSON.stringify(v)) > 1024 * 1024)
103
+ throw new Error("Splice plan exceeds 1 MiB.");
104
+ const endpoint = (e, from) => object(e) &&
105
+ knownKeys(e, from
106
+ ? ["server", "tool", "path", "parseJson", "expect", "valueSchema", "matchOne"]
107
+ : ["server", "tool", "uniqueBy", "resultPath", "resultFields"]) &&
108
+ typeof e.server === "string" &&
109
+ e.server.length > 0 &&
110
+ typeof e.tool === "string" &&
111
+ e.tool.length > 0 &&
112
+ (!from ||
113
+ ((e.path === undefined || typeof e.path === "string") &&
114
+ (e.parseJson === undefined || typeof e.parseJson === "boolean") &&
115
+ (e.valueSchema === undefined || schema(e.valueSchema))));
116
+ if (!object(v) ||
117
+ !knownKeys(v, [
118
+ "format",
119
+ "formatVersion",
120
+ "source",
121
+ "target",
122
+ "forEach",
123
+ "maxItems",
124
+ "maxResultBytes",
125
+ "bindings",
126
+ "contextSchema",
127
+ "rules",
128
+ ]) ||
129
+ v.format !== "toolsplice-splice" ||
130
+ v.formatVersion !== 1 ||
131
+ !endpoint(v.source, true) ||
132
+ !endpoint(v.target, false) ||
133
+ (v.forEach !== undefined && typeof v.forEach !== "boolean") ||
134
+ (v.maxItems !== undefined &&
135
+ (!Number.isSafeInteger(v.maxItems) ||
136
+ Number(v.maxItems) < 1 ||
137
+ Number(v.maxItems) > 1000)) ||
138
+ (v.contextSchema !== undefined &&
139
+ (!object(v.contextSchema) || v.contextSchema.type !== "object")) ||
140
+ (v.maxResultBytes !== undefined &&
141
+ (!Number.isSafeInteger(v.maxResultBytes) ||
142
+ Number(v.maxResultBytes) < 2 ||
143
+ Number(v.maxResultBytes) > 64 * 1024 * 1024)) ||
144
+ !Array.isArray(v.bindings) ||
145
+ v.bindings.length === 0 ||
146
+ v.bindings.length > 64)
147
+ throw new Error("Invalid or unsupported Toolsplice plan.");
148
+ if (object(v.source) && typeof v.source.path === "string")
149
+ segments(v.source.path);
150
+ if (object(v.source) && v.source.matchOne !== undefined) {
151
+ const match = v.source.matchOne;
152
+ if (!object(match) || !knownKeys(match, ["path", "equals", "fromContext"]) ||
153
+ typeof match.path !== "string" || Object.hasOwn(match, "equals") === Object.hasOwn(match, "fromContext") ||
154
+ (match.equals !== null && typeof match.equals === "object") || v.forEach)
155
+ throw new Error("matchOne selects one array row by a scalar key and cannot be combined with forEach.");
156
+ segments(match.path);
157
+ if (Object.hasOwn(match, "fromContext")) {
158
+ if (typeof match.fromContext !== "string" || !v.contextSchema)
159
+ throw new Error("matchOne.fromContext requires a JSON pointer and a context schema.");
160
+ segments(match.fromContext);
161
+ }
162
+ }
163
+ if (object(v.source) && v.source.expect !== undefined) {
164
+ if (!Array.isArray(v.source.expect) ||
165
+ v.source.expect.length < 1 ||
166
+ v.source.expect.length > 16)
167
+ throw new Error("Source expect requires 1–16 conditions.");
168
+ for (const condition of v.source.expect) {
169
+ if (!object(condition) ||
170
+ !knownKeys(condition, ["path", "equals"]) ||
171
+ typeof condition.path !== "string" ||
172
+ !Object.hasOwn(condition, "equals"))
173
+ throw new Error("Every source expectation needs path and equals.");
174
+ segments(condition.path);
175
+ }
176
+ }
177
+ if (object(v.target) && v.target.resultFields !== undefined) {
178
+ const fields = v.target.resultFields;
179
+ if (!object(fields) || !Object.keys(fields).length || Object.keys(fields).length > 32 ||
180
+ v.target.resultPath !== undefined)
181
+ throw new Error("Choose resultPath or an object of 1–32 resultFields.");
182
+ for (const [name, pointer] of Object.entries(fields)) {
183
+ if (!name || typeof pointer !== "string")
184
+ throw new Error("Each result field needs a name and JSON pointer.");
185
+ segments(pointer);
186
+ }
187
+ }
188
+ if (object(v.target) && v.target.resultPath !== undefined) {
189
+ if (typeof v.target.resultPath !== "string")
190
+ throw new Error("Target resultPath must be a JSON pointer.");
191
+ segments(v.target.resultPath);
192
+ }
193
+ if (object(v.target) && v.target.uniqueBy !== undefined) {
194
+ if (!Array.isArray(v.target.uniqueBy) ||
195
+ v.target.uniqueBy.length < 1 ||
196
+ v.target.uniqueBy.length > 8)
197
+ throw new Error("Target uniqueBy requires 1–8 non-overlapping JSON pointers.");
198
+ const keys = [];
199
+ for (const pointer of v.target.uniqueBy) {
200
+ if (typeof pointer !== "string")
201
+ throw new Error("Target uniqueBy needs JSON pointers.");
202
+ const parts = segments(pointer);
203
+ if (keys.some((key) => key
204
+ .slice(0, Math.min(key.length, parts.length))
205
+ .every((part, i) => part === parts[i])))
206
+ throw new Error("Target uniqueBy paths must not duplicate or overlap.");
207
+ keys.push(parts);
208
+ }
209
+ }
210
+ if (v.rules !== undefined)
211
+ validateRules(v.rules, v.contextSchema !== undefined);
212
+ const paths = [];
213
+ for (const binding of v.bindings) {
214
+ if (!object(binding) ||
215
+ typeof binding.to !== "string" ||
216
+ !knownKeys(binding, Object.hasOwn(binding, "from")
217
+ ? ["to", "from"]
218
+ : Object.hasOwn(binding, "fromContext")
219
+ ? ["to", "fromContext"]
220
+ : ["to", "value"]) ||
221
+ ["from", "fromContext", "value"].filter((k) => Object.hasOwn(binding, k))
222
+ .length !== 1 ||
223
+ (Object.hasOwn(binding, "from") && typeof binding.from !== "string") ||
224
+ (Object.hasOwn(binding, "fromContext") &&
225
+ (typeof binding.fromContext !== "string" ||
226
+ v.contextSchema === undefined)))
227
+ throw new Error("Every splice binding needs to and one of from, fromContext (with contextSchema), or value.");
228
+ const to = segments(binding.to);
229
+ if (typeof binding.from === "string")
230
+ segments(binding.from);
231
+ if (typeof binding.fromContext === "string")
232
+ segments(binding.fromContext);
233
+ if (paths.some((p) => p.slice(0, Math.min(p.length, to.length)).every((s, i) => s === to[i])))
234
+ throw new Error("Splice destination paths must not duplicate or overlap.");
235
+ paths.push(to);
236
+ }
237
+ return JSON.parse(JSON.stringify(v));
238
+ }
239
+ function endpointTool(snapshot, endpoint) {
240
+ if (snapshot.server.name !== endpoint.server)
241
+ throw new Error("Splice endpoint does not match the supplied server identity.");
242
+ const tool = snapshot.tools.find((t) => t.name === endpoint.tool);
243
+ if (!tool)
244
+ throw new Error("Splice endpoint tool was not recorded.");
245
+ return tool;
246
+ }
247
+ function issue(a, severity, code, path, message) {
248
+ if (a.issues.length < 100)
249
+ a.issues.push({ severity, code, path, message });
250
+ else
251
+ a.limited = true;
252
+ }
253
+ const canonicalValue = (v) => Array.isArray(v)
254
+ ? v.map(canonicalValue)
255
+ : object(v)
256
+ ? Object.fromEntries(Object.keys(v)
257
+ .sort()
258
+ .map((k) => [k, canonicalValue(v[k])]))
259
+ : v;
260
+ const annotations = new Set([
261
+ "$schema",
262
+ "$id",
263
+ "$defs",
264
+ "definitions",
265
+ "description",
266
+ "title",
267
+ "default",
268
+ "examples",
269
+ "format",
270
+ "contentSchema",
271
+ "contentMediaType",
272
+ "contentEncoding",
273
+ ]);
274
+ function resolve(s, root, a, path) {
275
+ const seen = new Set();
276
+ while (object(s) && s.$ref !== undefined) {
277
+ if (seen.has(s) ||
278
+ seen.size >= 32 ||
279
+ typeof s.$ref !== "string" ||
280
+ !s.$ref.startsWith("#")) {
281
+ issue(a, "warning", "unresolved-reference", path, "Reference resolution needs review.");
282
+ return true;
283
+ }
284
+ seen.add(s);
285
+ let found;
286
+ try {
287
+ found = ownPath(root, segments(s.$ref.slice(1)));
288
+ }
289
+ catch {
290
+ found = { found: false, value: undefined };
291
+ }
292
+ if (!found.found || !schema(found.value)) {
293
+ issue(a, "warning", "unresolved-reference", path, "A local schema reference could not be resolved.");
294
+ return true;
295
+ }
296
+ if (Object.keys(s).some((k) => k !== "$ref" && !annotations.has(k) && !k.startsWith("x-"))) {
297
+ issue(a, "warning", "reference-siblings", path, "Combined reference constraints need runtime checking.");
298
+ return true;
299
+ }
300
+ s = found.value;
301
+ }
302
+ return s;
303
+ }
304
+ function budget(a, path) {
305
+ if (--a.remaining >= 0)
306
+ return true;
307
+ a.limited = true;
308
+ issue(a, "warning", "analysis-limit", path, "Static analysis budget reached; runtime checks are required.");
309
+ return false;
310
+ }
311
+ function project(s, keys, root, a, path) {
312
+ if (!budget(a, path))
313
+ return true;
314
+ s = resolve(s, root, a, path);
315
+ if (!keys.length)
316
+ return s;
317
+ if (s === false) {
318
+ issue(a, "error", "impossible-source", path, "The source schema permits no value.");
319
+ return false;
320
+ }
321
+ if (s === true) {
322
+ issue(a, "warning", "unknown-source-path", path, "This source path is not described by the available schema.");
323
+ return true;
324
+ }
325
+ const unions = Array.isArray(s.anyOf)
326
+ ? s.anyOf
327
+ : Array.isArray(s.oneOf)
328
+ ? s.oneOf
329
+ : Array.isArray(s.type)
330
+ ? s.type.map((type) => ({ ...s, type }))
331
+ : undefined;
332
+ if (unions) {
333
+ const branches = [];
334
+ let uncertain = false;
335
+ for (const branch of unions) {
336
+ const local = {
337
+ issues: [],
338
+ remaining: a.remaining,
339
+ limited: false,
340
+ };
341
+ const value = project(schema(branch) ? branch : true, keys, root, local, path);
342
+ a.remaining = local.remaining;
343
+ a.limited ||= local.limited;
344
+ if (local.issues.some((i) => i.severity === "error"))
345
+ uncertain = true;
346
+ else {
347
+ branches.push(value);
348
+ for (const i of local.issues)
349
+ issue(a, i.severity, i.code, i.path, i.message);
350
+ }
351
+ }
352
+ if (!branches.length) {
353
+ issue(a, "error", "source-path-unavailable", path, "No source branch provides this path.");
354
+ return false;
355
+ }
356
+ if (uncertain)
357
+ issue(a, "warning", "nullable-or-missing-source", path, "Some source branches do not provide this path.");
358
+ return branches.length === 1 ? branches[0] : { anyOf: branches };
359
+ }
360
+ if (s.allOf || s.if || s.not) {
361
+ issue(a, "warning", "complex-source", path, "Complex source constraints require runtime checking.");
362
+ return true;
363
+ }
364
+ const [key, ...rest] = keys;
365
+ if (s.type === "array") {
366
+ if (!/^(0|[1-9]\d*)$/.test(key)) {
367
+ issue(a, "error", "array-path", path, "An array needs an explicit forEach or numeric index.");
368
+ return false;
369
+ }
370
+ issue(a, "warning", "possibly-empty-array", path, "An indexed array element may be absent.");
371
+ const index = Number(key), item = Array.isArray(s.prefixItems)
372
+ ? s.prefixItems[index]
373
+ : Array.isArray(s.items)
374
+ ? s.items[index]
375
+ : s.items;
376
+ return project(schema(item) ? item : true, rest, root, a, path);
377
+ }
378
+ if (s.type !== undefined && s.type !== "object") {
379
+ issue(a, "error", "path-through-scalar", path, s.type === "string" && s.contentSchema
380
+ ? "Select the JSON string with source.path and opt into source.parseJson before traversing it."
381
+ : "This path traverses a scalar rather than an object.");
382
+ return false;
383
+ }
384
+ const properties = object(s.properties) ? s.properties : {};
385
+ if (!Object.hasOwn(properties, key)) {
386
+ if (s.additionalProperties === false) {
387
+ issue(a, "error", "source-path-missing", path, "A closed source object does not declare this field.");
388
+ return false;
389
+ }
390
+ issue(a, "warning", "unobserved-source-field", path, "The selected source field has not been declared or observed.");
391
+ return project(schema(s.additionalProperties) ? s.additionalProperties : true, rest, root, a, path);
392
+ }
393
+ if (!Array.isArray(s.required) || !s.required.includes(key))
394
+ issue(a, "warning", "optional-source-field", path, "The selected source field may be absent.");
395
+ return project(schema(properties[key]) ? properties[key] : true, rest, root, a, path);
396
+ }
397
+ function types(s) {
398
+ if (typeof s === "boolean")
399
+ return undefined;
400
+ if (typeof s.type === "string")
401
+ return [s.type];
402
+ if (Array.isArray(s.type))
403
+ return s.type.filter((t) => typeof t === "string");
404
+ if (Object.hasOwn(s, "const"))
405
+ return [valueType(s.const)];
406
+ return undefined;
407
+ }
408
+ function valueType(value) {
409
+ return value === null
410
+ ? "null"
411
+ : Array.isArray(value)
412
+ ? "array"
413
+ : typeof value === "number" && Number.isInteger(value)
414
+ ? "integer"
415
+ : typeof value;
416
+ }
417
+ function literalSchema(value) {
418
+ const result = {
419
+ type: valueType(value),
420
+ const: value,
421
+ };
422
+ if (object(value)) {
423
+ result.properties = Object.fromEntries(Object.entries(value).map(([k, v]) => [k, literalSchema(v)]));
424
+ result.required = Object.keys(value);
425
+ result.additionalProperties = false;
426
+ }
427
+ if (Array.isArray(value))
428
+ result.items = value.length ? { anyOf: value.map(literalSchema) } : {};
429
+ return result;
430
+ }
431
+ function fit(from, to, fromRoot, toRoot, a, path) {
432
+ if (!budget(a, path))
433
+ return;
434
+ from = resolve(from, fromRoot, a, path);
435
+ to = resolve(to, toRoot, a, path);
436
+ if (to === true ||
437
+ (object(to) &&
438
+ Object.keys(to).every((k) => annotations.has(k) || k.startsWith("x-"))))
439
+ return;
440
+ if (to === false) {
441
+ issue(a, "error", "target-impossible", path, "The target schema permits no value.");
442
+ return;
443
+ }
444
+ if (from === false)
445
+ return;
446
+ if (from === true) {
447
+ issue(a, "warning", "unknown-source-type", path, "Source type information is unavailable for this target argument.");
448
+ return;
449
+ }
450
+ const fromUnion = Array.isArray(from.anyOf)
451
+ ? from.anyOf
452
+ : Array.isArray(from.oneOf)
453
+ ? from.oneOf
454
+ : undefined;
455
+ if (fromUnion) {
456
+ const checks = fromUnion.map((branch) => {
457
+ const local = {
458
+ issues: [],
459
+ remaining: a.remaining,
460
+ limited: false,
461
+ };
462
+ fit(schema(branch) ? branch : true, to, fromRoot, toRoot, local, path);
463
+ a.remaining = local.remaining;
464
+ a.limited ||= local.limited;
465
+ return local;
466
+ });
467
+ const allBad = checks.every((c) => c.issues.some((i) => i.severity === "error"));
468
+ for (const c of checks)
469
+ for (const i of c.issues)
470
+ issue(a, !allBad && i.severity === "error" ? "warning" : i.severity, i.code, i.path, i.message);
471
+ return;
472
+ }
473
+ if (Array.isArray(to.anyOf)) {
474
+ const checks = to.anyOf.map((branch) => {
475
+ const local = {
476
+ issues: [],
477
+ remaining: a.remaining,
478
+ limited: false,
479
+ };
480
+ fit(from, schema(branch) ? branch : true, fromRoot, toRoot, local, path);
481
+ a.remaining = local.remaining;
482
+ a.limited ||= local.limited;
483
+ return local;
484
+ });
485
+ if (checks.some((c) => c.issues.length === 0)) {
486
+ if (Object.keys(to).some((k) => k !== "anyOf" && !annotations.has(k) && !k.startsWith("x-")))
487
+ issue(a, "warning", "target-union-siblings", path, "Constraints alongside a target union require runtime checking.");
488
+ return;
489
+ }
490
+ if (checks.every((c) => c.issues.some((i) => i.severity === "error")))
491
+ issue(a, "error", "target-union-mismatch", path, "No target union branch accepts this source type.");
492
+ else
493
+ issue(a, "warning", "target-union-uncertain", path, "Target union compatibility needs runtime checking.");
494
+ return;
495
+ }
496
+ if (from.allOf ||
497
+ from.if ||
498
+ from.not ||
499
+ to.allOf ||
500
+ to.oneOf ||
501
+ to.if ||
502
+ to.not) {
503
+ issue(a, "warning", "complex-compatibility", path, "Complex schema compatibility needs runtime checking.");
504
+ return;
505
+ }
506
+ const ft = types(from), tt = types(to), accepts = (f, t) => f === t || (f === "integer" && t === "number");
507
+ if (tt && ft) {
508
+ const valid = ft.filter((f) => tt.some((t) => accepts(f, t)));
509
+ if (!valid.length && !(ft.includes("number") && tt.includes("integer"))) {
510
+ issue(a, "error", "type-mismatch", path, "Source and target argument types do not overlap.");
511
+ return;
512
+ }
513
+ if (valid.length !== ft.length)
514
+ issue(a, "warning", "partial-type-match", path, "Only some source values fit the target type.");
515
+ }
516
+ else if (tt && !ft)
517
+ issue(a, "warning", "unknown-source-type", path, "Source type is not known precisely enough for this argument.");
518
+ if (to.enum !== undefined || Object.hasOwn(to, "const")) {
519
+ const allowed = Array.isArray(to.enum) ? to.enum : [to.const], values = Array.isArray(from.enum)
520
+ ? from.enum
521
+ : Object.hasOwn(from, "const")
522
+ ? [from.const]
523
+ : undefined;
524
+ if (!values)
525
+ issue(a, "warning", "unproven-enum", path, "Source values are not restricted to the target's allowed set.");
526
+ else {
527
+ const matches = values.filter((v) => allowed.some((w) => JSON.stringify(canonicalValue(v)) ===
528
+ JSON.stringify(canonicalValue(w))));
529
+ if (!matches.length)
530
+ issue(a, "error", "enum-mismatch", path, "No known source value is allowed by the target.");
531
+ else if (matches.length !== values.length)
532
+ issue(a, "warning", "partial-enum-match", path, "Some source values are not allowed by the target.");
533
+ }
534
+ }
535
+ const fp = object(from.properties) ? from.properties : {}, tp = object(to.properties) ? to.properties : {};
536
+ if (object(from.properties) ||
537
+ object(to.properties) ||
538
+ Array.isArray(to.required)) {
539
+ for (const required of Array.isArray(to.required) ? to.required : [])
540
+ if (typeof required === "string") {
541
+ if (!Object.hasOwn(fp, required))
542
+ issue(a, from.additionalProperties === false ? "error" : "warning", "required-input-unmapped", `${path}/${ptr(required)}`, "A required target argument is not established by the mapping.");
543
+ else if (!Array.isArray(from.required) ||
544
+ !from.required.includes(required))
545
+ issue(a, "warning", "optional-source-object-field", `${path}/${ptr(required)}`, "A required target field is optional in the selected source object.");
546
+ }
547
+ if (from.additionalProperties !== false &&
548
+ ((to.additionalProperties !== undefined &&
549
+ to.additionalProperties !== true) ||
550
+ Object.keys(tp).some((k) => !Object.hasOwn(fp, k))))
551
+ issue(a, "warning", "unproven-object-fields", path, "Unspecified source object fields may violate target constraints.");
552
+ for (const key of Object.keys(fp)) {
553
+ if (Object.hasOwn(tp, key))
554
+ fit(schema(fp[key]) ? fp[key] : true, schema(tp[key]) ? tp[key] : true, fromRoot, toRoot, a, `${path}/${ptr(key)}`);
555
+ else if (to.additionalProperties === false)
556
+ issue(a, "error", "target-field-forbidden", `${path}/${ptr(key)}`, "The mapping supplies a field rejected by the target schema.");
557
+ else {
558
+ issue(a, "warning", "target-field-undeclared", `${path}/${ptr(key)}`, "The target does not declare this mapped field; verify its meaning.");
559
+ if (schema(to.additionalProperties))
560
+ fit(schema(fp[key]) ? fp[key] : true, to.additionalProperties, fromRoot, toRoot, a, `${path}/${ptr(key)}`);
561
+ }
562
+ }
563
+ }
564
+ if (from.items === undefined && to.items !== undefined)
565
+ issue(a, "warning", "unknown-array-items", path, "Source array item types are not established.");
566
+ if (from.items !== undefined && to.items !== undefined)
567
+ fit(schema(from.items) ? from.items : true, schema(to.items) ? to.items : true, fromRoot, toRoot, a, `${path}/items`);
568
+ for (const key of [
569
+ "minimum",
570
+ "maximum",
571
+ "exclusiveMinimum",
572
+ "exclusiveMaximum",
573
+ "minLength",
574
+ "maxLength",
575
+ "minItems",
576
+ "maxItems",
577
+ "multipleOf",
578
+ ]) {
579
+ if (to[key] === undefined)
580
+ continue;
581
+ if (Object.hasOwn(from, "const") && typeof to[key] === "number") {
582
+ const v = from.const, n = typeof v === "number"
583
+ ? v
584
+ : typeof v === "string"
585
+ ? [...v].length
586
+ : Array.isArray(v)
587
+ ? v.length
588
+ : undefined;
589
+ const applicable = typeof v === "number"
590
+ ? [
591
+ "minimum",
592
+ "maximum",
593
+ "exclusiveMinimum",
594
+ "exclusiveMaximum",
595
+ "multipleOf",
596
+ ].includes(key)
597
+ : typeof v === "string"
598
+ ? ["minLength", "maxLength"].includes(key)
599
+ : Array.isArray(v)
600
+ ? ["minItems", "maxItems"].includes(key)
601
+ : false;
602
+ if (n !== undefined && applicable) {
603
+ const bound = to[key];
604
+ const valid = key === "multipleOf"
605
+ ? n / bound === Math.trunc(n / bound)
606
+ : key.startsWith("min")
607
+ ? n >= bound
608
+ : key.startsWith("max")
609
+ ? n <= bound
610
+ : key === "exclusiveMinimum"
611
+ ? n > bound
612
+ : n < bound;
613
+ if (!valid)
614
+ issue(a, "error", "literal-bound-mismatch", path, "A constant mapping violates a target bound.");
615
+ continue;
616
+ }
617
+ }
618
+ if (from[key] !== to[key])
619
+ issue(a, "warning", "unproven-bound", path, "A target bound is not established by the source contract.");
620
+ }
621
+ const handled = new Set([
622
+ "type",
623
+ "properties",
624
+ "required",
625
+ "additionalProperties",
626
+ "items",
627
+ "enum",
628
+ "const",
629
+ "minimum",
630
+ "maximum",
631
+ "exclusiveMinimum",
632
+ "exclusiveMaximum",
633
+ "minLength",
634
+ "maxLength",
635
+ "minItems",
636
+ "maxItems",
637
+ "multipleOf",
638
+ ]);
639
+ if (Object.keys(to).some((k) => !handled.has(k) && !annotations.has(k) && !k.startsWith("x-")))
640
+ issue(a, "warning", "additional-target-constraints", path, "Additional target constraints require runtime checking.");
641
+ }
642
+ function setSchema(root, path, value) {
643
+ if (!path.length)
644
+ return value;
645
+ let current = root;
646
+ for (const [i, key] of path.entries()) {
647
+ if (!object(current.properties))
648
+ current.properties = Object.create(null);
649
+ if (!Array.isArray(current.required))
650
+ current.required = [];
651
+ if (!current.required.includes(key))
652
+ current.required.push(key);
653
+ current.type = "object";
654
+ current.additionalProperties = false;
655
+ const props = current.properties;
656
+ if (i === path.length - 1)
657
+ Object.defineProperty(props, key, {
658
+ value,
659
+ enumerable: true,
660
+ writable: true,
661
+ configurable: true,
662
+ });
663
+ else {
664
+ if (!Object.hasOwn(props, key))
665
+ Object.defineProperty(props, key, {
666
+ value: {},
667
+ enumerable: true,
668
+ writable: true,
669
+ configurable: true,
670
+ });
671
+ current = props[key];
672
+ }
673
+ }
674
+ return root;
675
+ }
676
+ export function preflightSplice(plan, source, target) {
677
+ const spec = parseSpliceSpec(plan), s = parseContractSnapshot(source), t = parseContractSnapshot(target), st = endpointTool(s, spec.source), tt = endpointTool(t, spec.target);
678
+ const a = { issues: [], remaining: 2000, limited: false };
679
+ const sourceRoot = st.output ?? true;
680
+ for (const [i] of (spec.rules ?? []).entries())
681
+ issue(a, "warning", "application-rule", `/rules/${i}`, "An explicit application rule is enforced on every mapped row at runtime.");
682
+ for (const [i, condition] of (spec.source.expect ?? []).entries()) {
683
+ const path = `/source/expect/${i}`;
684
+ const field = project(sourceRoot, segments(condition.path), sourceRoot, a, path);
685
+ fit(literalSchema(condition.equals), field, sourceRoot, sourceRoot, a, path);
686
+ issue(a, "warning", "source-expectation", path, "This explicit source condition must pass at runtime before argument mapping.");
687
+ }
688
+ let selected = project(sourceRoot, segments(spec.source.path ?? ""), sourceRoot, a, "/source");
689
+ if (spec.source.parseJson) {
690
+ const selectedTypes = types(selected);
691
+ if (selectedTypes && !selectedTypes.includes("string"))
692
+ issue(a, "error", "json-source-not-string", "/source", "Explicit JSON parsing requires a string source.");
693
+ else if (selectedTypes && selectedTypes.some((t) => t !== "string"))
694
+ issue(a, "warning", "nullable-json-source", "/source", "Some source branches are not JSON strings.");
695
+ if (object(selected) && schema(selected.contentSchema))
696
+ selected = selected.contentSchema;
697
+ else {
698
+ issue(a, "warning", "unknown-json-shape", "/source", "The schema does not describe the JSON stored in this string.");
699
+ selected = true;
700
+ }
701
+ }
702
+ if (spec.source.valueSchema !== undefined) {
703
+ const declaredTypes = types(selected), requiredTypes = types(spec.source.valueSchema);
704
+ const impossible = spec.source.valueSchema === false ||
705
+ (declaredTypes &&
706
+ requiredTypes &&
707
+ !declaredTypes.some((x) => requiredTypes.includes(x) ||
708
+ (x === "integer" && requiredTypes.includes("number")) ||
709
+ (x === "number" && requiredTypes.includes("integer"))));
710
+ issue(a, impossible ? "error" : "warning", "source-value-requirement", "/source/valueSchema", impossible
711
+ ? "The selected source cannot meet this value requirement."
712
+ : "This consumer schema must pass on the selected value before fanout and argument mapping.");
713
+ }
714
+ const match = spec.source.matchOne;
715
+ if (spec.forEach || match) {
716
+ selected = resolve(selected, sourceRoot, a, "/source");
717
+ if (object(selected) && selected.type === "array")
718
+ selected = match && (Array.isArray(selected.items) || Array.isArray(selected.prefixItems))
719
+ ? true : schema(selected.items) ? selected.items : true;
720
+ else if (selected === true ||
721
+ !object(selected) ||
722
+ selected.type === undefined ||
723
+ (match && types(selected)?.includes("array"))) {
724
+ issue(a, "warning", "unknown-array-source", "/source", "An array of candidates is checked at runtime.");
725
+ selected = true;
726
+ }
727
+ else
728
+ issue(a, "error", match ? "match-one-requires-array" : "forEach-requires-array", "/source", "The selected source must be an array.");
729
+ }
730
+ if (match) {
731
+ const path = "/source/matchOne";
732
+ const field = project(selected, segments(match.path), sourceRoot, a, path);
733
+ const inputRoot = "fromContext" in match ? spec.contextSchema : sourceRoot;
734
+ const key = "fromContext" in match
735
+ ? project(inputRoot, segments(match.fromContext), inputRoot, a, path)
736
+ : literalSchema(match.equals);
737
+ fit(key, field, inputRoot, sourceRoot, a, path);
738
+ }
739
+ let argumentsSchema = {
740
+ type: "object",
741
+ properties: Object.create(null),
742
+ required: [],
743
+ additionalProperties: false,
744
+ };
745
+ for (const binding of spec.bindings) {
746
+ const path = `/bindings${binding.to}`;
747
+ let selectedSchema;
748
+ if ("fromContext" in binding) {
749
+ const contextRoot = spec.contextSchema;
750
+ const field = project(contextRoot, segments(binding.fromContext), contextRoot, a, path);
751
+ const destination = project(tt.input, segments(binding.to), tt.input, a, path);
752
+ fit(field, destination, contextRoot, tt.input, a, path);
753
+ // The full mapped object combines two schema roots. Do not reinterpret a
754
+ // nested context $ref as a reference into the source contract.
755
+ selectedSchema = true;
756
+ issue(a, "warning", "context-binding", path, "Application context is validated before the source call; mapped arguments are checked before destination dispatch.");
757
+ }
758
+ else
759
+ selectedSchema =
760
+ "from" in binding
761
+ ? project(selected, segments(binding.from), sourceRoot, a, path)
762
+ : literalSchema(binding.value);
763
+ argumentsSchema = setSchema(argumentsSchema, segments(binding.to), selectedSchema);
764
+ }
765
+ fit(argumentsSchema, tt.input, sourceRoot, tt.input, a, "/arguments");
766
+ if (spec.target.uniqueBy) {
767
+ for (const [i, key] of spec.target.uniqueBy.entries()) {
768
+ const parts = segments(key);
769
+ const mapped = spec.bindings.some((binding) => {
770
+ const to = segments(binding.to);
771
+ return to
772
+ .slice(0, Math.min(parts.length, to.length))
773
+ .every((part, j) => part === parts[j]);
774
+ });
775
+ if (!mapped)
776
+ issue(a, "error", "unique-key-unmapped", `/target/uniqueBy/${i}`, "This uniqueness key is outside all mapped destination fields.");
777
+ }
778
+ issue(a, "warning", "unique-target-keys", "/target/uniqueBy", "Destination-key tuples must be distinct within the mapped batch before any target call.");
779
+ }
780
+ const pathsToCheck = spec.target.resultFields
781
+ ? namedFields(spec.target.resultFields).map(([name, path]) => [`/target/resultFields/${ptr(name)}`, path])
782
+ : spec.target.resultPath ? [["/target/resultPath", spec.target.resultPath]] : [];
783
+ for (const [at, path] of pathsToCheck) {
784
+ const root = tt.output ?? true;
785
+ const check = { issues: [], remaining: a.remaining, limited: false };
786
+ const selected = project(root, segments(path), root, check, at);
787
+ a.remaining = check.remaining;
788
+ a.limited ||= check.limited;
789
+ if (selected === false || check.issues.some(i => i.severity === "error"))
790
+ issue(a, "error", "target-result-path-unavailable", at, "The destination contract rules out the selected result field.");
791
+ else if (check.issues.length || check.limited)
792
+ issue(a, "warning", "target-result-path-uncertain", at, "The destination may omit the selected result field.");
793
+ }
794
+ if (st.limited)
795
+ issue(a, "warning", "limited-source-evidence", "/source", "Source inference was limited; inspect the selected paths before enabling execution.");
796
+ if (a.limited)
797
+ issue(a, "warning", "analysis-limit", "/", "Static analysis was truncated; review is required.");
798
+ return {
799
+ status: a.issues.some((i) => i.severity === "error")
800
+ ? "blocked"
801
+ : a.issues.length || a.limited
802
+ ? "review"
803
+ : "ready",
804
+ source: { server: spec.source.server, tool: spec.source.tool },
805
+ target: { server: spec.target.server, tool: spec.target.tool },
806
+ issues: a.issues,
807
+ maxTargetCalls: spec.forEach ? (spec.maxItems ?? 100) : 1,
808
+ maxResultBytes: spec.maxResultBytes ?? 5 * 1024 * 1024,
809
+ fingerprints: {
810
+ source: s.fingerprint,
811
+ target: t.fingerprint,
812
+ plan: stableHash(canonicalValue(spec)),
813
+ },
814
+ note: "Structural fit does not prove that two IDs or fields mean the same thing. Observed schemas are provisional; runtime guards remain necessary.",
815
+ };
816
+ }
817
+ function setValue(root, path, value) {
818
+ if (!path.length)
819
+ return value;
820
+ let current = root;
821
+ for (const [i, key] of path.entries()) {
822
+ if (i === path.length - 1)
823
+ Object.defineProperty(current, key, {
824
+ value,
825
+ enumerable: true,
826
+ writable: true,
827
+ configurable: true,
828
+ });
829
+ else {
830
+ if (!Object.hasOwn(current, key))
831
+ Object.defineProperty(current, key, {
832
+ value: Object.create(null),
833
+ enumerable: true,
834
+ writable: true,
835
+ configurable: true,
836
+ });
837
+ current = current[key];
838
+ }
839
+ }
840
+ return root;
841
+ }
842
+ export function prepareSplice(plan, source, target) {
843
+ const spec = parseSpliceSpec(plan), s = selectContractTools(source, [spec.source.tool]), t = selectContractTools(target, [spec.target.tool]), report = preflightSplice(spec, s, t);
844
+ let validateArguments, validateSourceOutput, validateContext, validateSourceValue, setupError;
845
+ const sourceGuards = new WeakMap(), targetGuards = new WeakMap();
846
+ try {
847
+ if (spec.source.valueSchema !== undefined) {
848
+ const valueRecord = newServer("toolsplice-source-value");
849
+ const valueSchema = typeof spec.source.valueSchema === "boolean"
850
+ ? spec.source.valueSchema
851
+ ? {}
852
+ : { not: {} }
853
+ : spec.source.valueSchema;
854
+ recordToolList(valueRecord, [
855
+ {
856
+ name: "value",
857
+ inputSchema: { type: "object" },
858
+ outputSchema: valueSchema,
859
+ },
860
+ ]);
861
+ validateSourceValue = createContractCaller(async (request) => ({ structuredContent: request.arguments.value }), createContractSnapshot(valueRecord), { inputs: false });
862
+ }
863
+ if (spec.contextSchema) {
864
+ const contextRecord = newServer("toolsplice-context");
865
+ recordToolList(contextRecord, [
866
+ { name: "context", inputSchema: spec.contextSchema },
867
+ ]);
868
+ validateContext = createContractCaller(async () => ({ content: [] }), createContractSnapshot(contextRecord), { outputs: false });
869
+ }
870
+ validateArguments = createContractCaller(async () => ({ content: [] }), t, {
871
+ outputs: false,
872
+ });
873
+ validateSourceOutput = createContractCaller(async (request) => ({ structuredContent: request.arguments.value }), s, { inputs: false, outputs: s.tools[0].output !== null });
874
+ createContractCaller(async () => ({ content: [] }), s, {
875
+ outputs: s.tools[0].output !== null,
876
+ });
877
+ createContractCaller(async () => ({ content: [] }), t, {
878
+ outputs: t.tools[0].output !== null,
879
+ });
880
+ }
881
+ catch (error) {
882
+ setupError = error;
883
+ report.status = "blocked";
884
+ report.issues.push({
885
+ severity: "error",
886
+ code: "unsupported-runtime-validator",
887
+ path: "/contracts",
888
+ message: "An endpoint, context or selected-value schema cannot be guarded within the supported dialect and resource limits.",
889
+ });
890
+ }
891
+ const policyStatus = report.status;
892
+ for (const item of report.issues)
893
+ Object.freeze(item);
894
+ Object.freeze(report.issues);
895
+ Object.freeze(report.source);
896
+ Object.freeze(report.target);
897
+ Object.freeze(report.fingerprints);
898
+ Object.freeze(report);
899
+ const checkPolicy = (options = {}) => {
900
+ options.signal?.throwIfAborted();
901
+ if (policyStatus === "blocked" ||
902
+ (policyStatus === "review" && !options.allowReview))
903
+ throw new SpliceError("preflight", 0, setupError, report.issues);
904
+ };
905
+ const match = spec.source.matchOne;
906
+ const matchPath = match ? segments(match.path) : [];
907
+ const resolveContext = async (options) => {
908
+ if (!spec.contextSchema) {
909
+ if (options.context !== undefined)
910
+ throw new SpliceError("context", 0, new MappingFault("undeclared-context", "/context", "This plan does not declare contextSchema."));
911
+ return undefined;
912
+ }
913
+ try {
914
+ if (options.context === undefined)
915
+ throw new MappingFault("context-required", "/context", "This plan requires application context.");
916
+ assertContractJson(options.context);
917
+ const encoded = JSON.stringify(options.context);
918
+ if (Buffer.byteLength(encoded) > 5 * 1024 * 1024)
919
+ throw new MappingFault("context-byte-limit", "/context", "Application context exceeds 5 MiB.");
920
+ const context = JSON.parse(encoded);
921
+ await validateContext({
922
+ name: "context",
923
+ arguments: context,
924
+ });
925
+ if (match && "fromContext" in match) {
926
+ const key = readSplicePath(context, match.fromContext);
927
+ if (!key.found || (key.value !== null && typeof key.value === "object"))
928
+ throw new MappingFault("match-one-context-key", match.fromContext, "The match key must be a present JSON scalar.");
929
+ }
930
+ for (const binding of spec.bindings) {
931
+ if ("fromContext" in binding &&
932
+ !ownPath(context, segments(binding.fromContext)).found)
933
+ throw new MappingFault("context-field-missing", binding.fromContext, "A mapped context field is absent.");
934
+ }
935
+ return context;
936
+ }
937
+ catch (error) {
938
+ throw new SpliceError("context", 0, error);
939
+ }
940
+ };
941
+ const mapDecoded = async (output, context) => {
942
+ if (policyStatus === "blocked" || !validateArguments)
943
+ throw new SpliceError("preflight", 0, setupError, report.issues);
944
+ try {
945
+ assertContractJson(output);
946
+ output = JSON.parse(JSON.stringify(output));
947
+ for (const condition of spec.source.expect ?? []) {
948
+ const selected = ownPath(output, segments(condition.path));
949
+ if (!selected.found ||
950
+ JSON.stringify(canonicalValue(selected.value)) !==
951
+ JSON.stringify(canonicalValue(condition.equals)))
952
+ throw new MappingFault("source-expectation-failed", condition.path, "An explicit source expectation failed.");
953
+ }
954
+ const selected = readSplicePath(output, spec.source.path ?? "");
955
+ if (!selected.found)
956
+ throw new MappingFault("source-selection-missing", "/source", "The selected source path is absent.");
957
+ let value = selected.value;
958
+ if (spec.source.parseJson) {
959
+ if (typeof value !== "string")
960
+ throw new MappingFault("json-source-not-string", "/source", "The selected source is not a JSON string.");
961
+ const parsed = parseJsonText(value);
962
+ if (!parsed)
963
+ throw new MappingFault("invalid-json-string", "/source", "The selected string is not machine-readable JSON.");
964
+ value = parsed.value;
965
+ }
966
+ if (validateSourceValue) {
967
+ try {
968
+ await validateSourceValue({ name: "value", arguments: { value } });
969
+ }
970
+ catch (error) {
971
+ if (error instanceof ContractValidationError)
972
+ throw new SpliceError("mapping", 0, error, error.issues.map((i) => ({
973
+ severity: "error",
974
+ code: `source-value-${i.keyword}`,
975
+ path: `/source/valueSchema${i.path === "/" ? "" : i.path}`,
976
+ message: "The selected source value violates its explicit consumer schema.",
977
+ })));
978
+ throw error;
979
+ }
980
+ }
981
+ if (match) {
982
+ if (!Array.isArray(value))
983
+ throw new MappingFault("match-one-requires-array", "/source/matchOne", "Expected an array of candidates.");
984
+ if (value.length > (spec.maxItems ?? 100))
985
+ throw new MappingFault("match-one-limit", "/maxItems", "The source exceeds the candidate scan limit.");
986
+ const key = "fromContext" in match ? readSplicePath(context, match.fromContext).value : match.equals;
987
+ const candidates = value;
988
+ let found = false;
989
+ for (const row of candidates) {
990
+ const candidate = ownPath(row, matchPath);
991
+ if (!candidate.found || candidate.value !== key)
992
+ continue;
993
+ if (found)
994
+ throw new MappingFault("match-one-ambiguous", "/source/matchOne", "Multiple rows match the requested key.");
995
+ value = row;
996
+ found = true;
997
+ }
998
+ if (!found)
999
+ throw new MappingFault("match-one-missing", "/source/matchOne", "No row matches the requested key.");
1000
+ }
1001
+ const rows = spec.forEach ? value : [value];
1002
+ if (!Array.isArray(rows))
1003
+ throw new MappingFault("forEach-requires-array", "/forEach", "The selected source is not an array.");
1004
+ if (rows.length > (spec.forEach ? (spec.maxItems ?? 100) : 1))
1005
+ throw new MappingFault("fanout-limit", "/maxItems", "The source batch exceeds the explicit target-call limit.");
1006
+ const mapped = [];
1007
+ const uniqueKeys = new Set();
1008
+ let batchBytes = 0;
1009
+ const checkRules = ruleEvaluator(spec.rules);
1010
+ for (const [rowIndex, row] of rows.entries()) {
1011
+ let args = Object.create(null);
1012
+ for (const binding of spec.bindings) {
1013
+ const found = "from" in binding
1014
+ ? ownPath(row, segments(binding.from))
1015
+ : "fromContext" in binding
1016
+ ? ownPath(context, segments(binding.fromContext))
1017
+ : { found: true, value: binding.value };
1018
+ if (!found.found)
1019
+ throw new MappingFault("source-field-missing", `/rows/${rowIndex}${"from" in binding ? binding.from : ""}`, "A mapped source field is absent.");
1020
+ args = setValue(args, segments(binding.to), found.value);
1021
+ }
1022
+ assertContractJson(args);
1023
+ if (!object(args))
1024
+ throw new MappingFault("arguments-not-object", `/rows/${rowIndex}`, "Mapped tool arguments must be an object.");
1025
+ const encoded = JSON.stringify(args);
1026
+ batchBytes += Buffer.byteLength(encoded);
1027
+ if (batchBytes > 5 * 1024 * 1024)
1028
+ throw new MappingFault("mapped-batch-byte-limit", "/bindings", "Mapped arguments exceed the 5 MiB batch limit.");
1029
+ const detached = JSON.parse(encoded);
1030
+ try {
1031
+ await validateArguments({
1032
+ name: spec.target.tool,
1033
+ arguments: detached,
1034
+ });
1035
+ }
1036
+ catch (error) {
1037
+ if (error instanceof ContractValidationError)
1038
+ throw new SpliceError("mapping", 0, error, error.issues.map((i) => ({
1039
+ severity: "error",
1040
+ code: `validation-${i.keyword}`,
1041
+ path: `/rows/${rowIndex}${i.path === "/" ? "" : i.path}`,
1042
+ message: "A destination argument violates the target schema.",
1043
+ })));
1044
+ throw error;
1045
+ }
1046
+ if (spec.target.uniqueBy) {
1047
+ const values = spec.target.uniqueBy.map((key) => {
1048
+ const field = ownPath(detached, segments(key));
1049
+ if (!field.found)
1050
+ throw new MappingFault("unique-key-missing", `/rows/${rowIndex}${key}`, "A destination uniqueness key is absent.");
1051
+ return field.value;
1052
+ });
1053
+ const key = JSON.stringify(canonicalValue(values));
1054
+ if (uniqueKeys.has(key))
1055
+ throw new MappingFault("duplicate-target-key", `/rows/${rowIndex}`, "This destination-key tuple duplicates an earlier row; the whole batch was rejected.");
1056
+ uniqueKeys.add(key);
1057
+ }
1058
+ const violation = checkRules({ source: output, row, mapped: detached, context }, rowIndex);
1059
+ if (violation)
1060
+ throw new SpliceError("mapping", 0, undefined, [violation]);
1061
+ mapped.push(detached);
1062
+ }
1063
+ return mapped;
1064
+ }
1065
+ catch (error) {
1066
+ if (error instanceof SpliceError)
1067
+ throw error;
1068
+ throw new SpliceError("mapping", 0, error);
1069
+ }
1070
+ };
1071
+ const mapOutput = async (output, options = {}) => {
1072
+ if (policyStatus === "blocked" || !validateSourceOutput)
1073
+ throw new SpliceError("preflight", 0, setupError, report.issues);
1074
+ const context = await resolveContext(options);
1075
+ try {
1076
+ await validateSourceOutput({
1077
+ name: spec.source.tool,
1078
+ arguments: { value: output },
1079
+ });
1080
+ }
1081
+ catch (error) {
1082
+ throw new SpliceError("source", 0, error);
1083
+ }
1084
+ return mapDecoded(output, context);
1085
+ };
1086
+ const selections = namedFields(spec.target.resultFields ?? { "": spec.target.resultPath ?? "" })
1087
+ .map(([name, pointer]) => ({ name, pointer, keys: segments(pointer) }));
1088
+ const execute = async (sourceCaller, targetCaller, args, options, concurrency) => {
1089
+ checkPolicy(options);
1090
+ const context = await resolveContext(options);
1091
+ const callOptions = {
1092
+ signal: options.signal,
1093
+ timeoutMs: options.timeoutMs,
1094
+ onProgress: options.onProgress,
1095
+ };
1096
+ let result, sourceGuard = sourceGuards.get(sourceCaller), targetGuard = targetGuards.get(targetCaller);
1097
+ try {
1098
+ if (!sourceGuard) {
1099
+ sourceGuard = createContractCaller(sourceCaller, s, {
1100
+ outputs: s.tools[0].output !== null,
1101
+ });
1102
+ sourceGuards.set(sourceCaller, sourceGuard);
1103
+ }
1104
+ if (!targetGuard) {
1105
+ targetGuard = createContractCaller(targetCaller, t, {
1106
+ outputs: t.tools[0].output !== null,
1107
+ });
1108
+ targetGuards.set(targetCaller, targetGuard);
1109
+ }
1110
+ }
1111
+ catch (error) {
1112
+ throw new SpliceError("preflight", 0, error);
1113
+ }
1114
+ try {
1115
+ result = await invokeTool(sourceGuard, spec.source.tool, args, callOptions);
1116
+ }
1117
+ catch (error) {
1118
+ throw new SpliceError("source", 0, error);
1119
+ }
1120
+ const mapped = await mapDecoded(result, context), results = [];
1121
+ let resultBytes = 2; // The returned JSON array's brackets.
1122
+ const dispatch = (row) => invokeTool(targetGuard, spec.target.tool, row, callOptions);
1123
+ let scheduled = 0;
1124
+ try {
1125
+ for (let offset = 0; offset < mapped.length; offset += concurrency) {
1126
+ options.signal?.throwIfAborted();
1127
+ const wave = mapped.slice(offset, offset + concurrency);
1128
+ scheduled += wave.length;
1129
+ const replies = concurrency === 1
1130
+ ? [{ status: "fulfilled", value: await dispatch(wave[0]) }]
1131
+ : await Promise.allSettled(wave.map(dispatch));
1132
+ for (const reply of replies) {
1133
+ if (reply.status === "rejected")
1134
+ throw reply.reason;
1135
+ const value = reply.value;
1136
+ try {
1137
+ assertContractJson(value);
1138
+ }
1139
+ catch {
1140
+ throw new MappingFault("target-result-limits", `/results/${results.length}`, "Destination output must be finite, bounded JSON.");
1141
+ }
1142
+ const fields = Object.create(null);
1143
+ resultBytes += (results.length ? 1 : 0) + (spec.target.resultFields ? 2 : 0);
1144
+ for (const [i, field] of selections.entries()) {
1145
+ const selected = ownPath(value, field.keys);
1146
+ if (!selected.found)
1147
+ throw new MappingFault("target-result-field-missing", `/results/${results.length}${field.pointer}`, "The destination response omitted the selected result field.");
1148
+ const encoded = JSON.stringify(selected.value);
1149
+ if (spec.target.resultFields)
1150
+ resultBytes += Buffer.byteLength(JSON.stringify(field.name)) + 1 + (i ? 1 : 0);
1151
+ resultBytes += Buffer.byteLength(encoded);
1152
+ if (resultBytes > report.maxResultBytes)
1153
+ throw new MappingFault("result-batch-byte-limit", `/results/${results.length}`, "Collected destination output exceeds the configured byte budget.");
1154
+ fields[field.name] = JSON.parse(encoded);
1155
+ }
1156
+ results.push(spec.target.resultFields ? Object.fromEntries(Object.entries(fields)) : fields[""]);
1157
+ }
1158
+ }
1159
+ }
1160
+ catch (error) {
1161
+ const fault = new SpliceError("target", results.length, error);
1162
+ if (concurrency > 1)
1163
+ fault.scheduledTargets = scheduled;
1164
+ throw fault;
1165
+ }
1166
+ return results;
1167
+ };
1168
+ const run = (source, target, args, options = {}) => execute(source, target, args, options, 1);
1169
+ const readConcurrency = (concurrency, assumeReadOnly) => {
1170
+ if (!Number.isSafeInteger(concurrency) || concurrency < 1 || concurrency > 16)
1171
+ throw new RangeError("Read concurrency must be an integer from 1 through 16.");
1172
+ const hints = t.tools[0].annotations;
1173
+ if (hints.readOnlyHint === false || hints.destructiveHint === true ||
1174
+ (hints.readOnlyHint !== true && assumeReadOnly !== true))
1175
+ throw new Error("Concurrent reads need a read-only destination or an explicit application declaration.");
1176
+ return concurrency;
1177
+ };
1178
+ const runReads = async (source, target, args, options = {}) => execute(source, target, args, options, readConcurrency(options.concurrency ?? 4, options.assumeReadOnly));
1179
+ const asTool = ({ name, description, source, target, ui, readConcurrency: requested, assumeReadOnly }) => {
1180
+ const concurrency = requested === undefined ? 1 : readConcurrency(requested, assumeReadOnly);
1181
+ if (typeof name !== "string" || !name || (description !== undefined && typeof description !== "string") ||
1182
+ typeof source !== "function" || typeof target !== "function")
1183
+ throw new Error("A composite tool needs a name and source and destination callers.");
1184
+ const input = s.tools[0].input;
1185
+ if (input === false || (object(input) && input.type !== undefined &&
1186
+ input.type !== "object" && !(Array.isArray(input.type) && input.type.includes("object"))))
1187
+ throw new Error("An MCP tool must accept an object as its arguments.");
1188
+ const aliases = Object.keys(spec.target.resultFields ?? {});
1189
+ const items = aliases.length ? {
1190
+ type: "object", properties: Object.fromEntries(aliases.map(name => [name, {}])),
1191
+ required: aliases, additionalProperties: false,
1192
+ } : {};
1193
+ const definition = {
1194
+ name, ...(description === undefined ? {} : { description }),
1195
+ ...(ui === undefined ? {} : { _meta: { ui: toolUi(ui) } }),
1196
+ inputSchema: { ...(object(input) ? structuredClone(input) : {}), type: "object" },
1197
+ outputSchema: { type: "object", properties: { results: { type: "array", items } },
1198
+ required: ["results"], additionalProperties: false },
1199
+ };
1200
+ const text = (value) => [{ type: "text", text: JSON.stringify(value) }];
1201
+ const call = async (args, options = {}) => {
1202
+ options.signal?.throwIfAborted();
1203
+ try {
1204
+ const results = await execute(source, target, args, options, concurrency);
1205
+ const structuredContent = { results };
1206
+ return { resultType: "complete", structuredContent, content: text(structuredContent) };
1207
+ }
1208
+ catch (error) {
1209
+ options.signal?.throwIfAborted();
1210
+ const detail = error instanceof SpliceError ? {
1211
+ stage: error.stage, completedTargets: error.completedTargets,
1212
+ ...(error.scheduledTargets === undefined ? {} : { scheduledTargets: error.scheduledTargets }),
1213
+ issues: error.issues.map(({ code, path }) => ({ code, path })),
1214
+ destinationMayHaveRun: error.stage === "target",
1215
+ } : { stage: "unknown" };
1216
+ return { resultType: "complete", isError: true, content: text(detail) };
1217
+ }
1218
+ };
1219
+ const executeTool = async (args, options = {}) => {
1220
+ const result = await call(args, options);
1221
+ if (result.isError)
1222
+ throw new Error(result.content[0].text);
1223
+ return result.structuredContent;
1224
+ };
1225
+ return { definition, call, execute: executeTool };
1226
+ };
1227
+ return { report, mapOutput, run, runReads, asTool };
1228
+ }
1229
+ export function emitSpliceModule(plan, source, target, options = {}) {
1230
+ const spec = parseSpliceSpec(plan), s = selectContractTools(source, [spec.source.tool]), t = selectContractTools(target, [spec.target.tool]);
1231
+ const declaration = (snapshot, iface) => {
1232
+ const record = newServer(snapshot.server.name, snapshot.server.version);
1233
+ recordToolList(record, snapshot.tools.map((tool) => ({
1234
+ name: tool.name,
1235
+ inputSchema: tool.input,
1236
+ ...(tool.output === null ? {} : { outputSchema: tool.output }),
1237
+ })));
1238
+ return emitModule(record, { interfaceName: iface }).replaceAll("Declared by the server.", "Projected from a saved contract; observations are provisional.");
1239
+ };
1240
+ let contextTypes = "";
1241
+ let optionsParameter = "options?: toolsplice.SpliceRunOptions";
1242
+ if (spec.contextSchema) {
1243
+ const record = newServer("toolsplice-context");
1244
+ recordToolList(record, [
1245
+ { name: "context", inputSchema: spec.contextSchema },
1246
+ ]);
1247
+ contextTypes = `export declare namespace Context {\n${declaration(createContractSnapshot(record), "Tools")}\n}\n`;
1248
+ optionsParameter =
1249
+ 'options: toolsplice.SpliceRunOptions & { context: Parameters<Context.Tools["context"]>[0] }';
1250
+ }
1251
+ let resultType = `Awaited<ReturnType<Target.Tools[${JSON.stringify(spec.target.tool)}]>>`;
1252
+ let projectionTypes = "";
1253
+ if (spec.target.resultPath || spec.target.resultFields) {
1254
+ projectionTypes = 'type ResultField<T, K extends string> = T extends null | undefined ? never : K extends keyof T ? Exclude<T[K], undefined> : T extends ReadonlyArray<infer Item> ? Item : unknown;\n';
1255
+ const fieldType = (pointer) => segments(pointer).reduce((type, key) => `ResultField<${type}, ${JSON.stringify(key)}>`, resultType);
1256
+ resultType = spec.target.resultFields
1257
+ ? "{ " + namedFields(spec.target.resultFields).map(([key, path]) => JSON.stringify(key) + ": " + fieldType(path)).join("; ") + " }"
1258
+ : fieldType(spec.target.resultPath);
1259
+ projectionTypes += `export type SelectedResult = ${resultType};\n`;
1260
+ resultType = "SelectedResult";
1261
+ }
1262
+ return `// Generated by Toolsplice. Explicit mapping; no inferred semantic joins.\nimport * as toolsplice from ${JSON.stringify(options.runtimeImport ?? "toolsplice")};\n\nexport declare namespace Source {\n${declaration(s, "Tools")}\n}\nexport declare namespace Target {\n${declaration(t, "Tools")}\n}\n${contextTypes}${projectionTypes}const splice = toolsplice.prepareSplice(JSON.parse(${JSON.stringify(JSON.stringify(spec))}), JSON.parse(${JSON.stringify(JSON.stringify(s))}), JSON.parse(${JSON.stringify(JSON.stringify(t))}));\nexport const report = splice.report;\nexport function createSplice(source: toolsplice.ToolCaller, target: toolsplice.ToolCaller) {\n return (args: Parameters<Source.Tools[${JSON.stringify(spec.source.tool)}]>[0], ${optionsParameter}): Promise<${resultType}[]> =>\n splice.run(source, target, args, options) as Promise<${resultType}[]>;\n}\n`;
1263
+ }