toolsplice-core 0.0.1 → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/README.md +26 -17
  2. package/dist/abortable.d.ts +6 -0
  3. package/dist/abortable.js +50 -0
  4. package/dist/adaptive-read.d.ts +50 -0
  5. package/dist/adaptive-read.js +780 -0
  6. package/dist/answer-wait.d.ts +7 -0
  7. package/dist/answer-wait.js +45 -0
  8. package/dist/cache-reads.d.ts +18 -0
  9. package/dist/cache-reads.js +89 -0
  10. package/dist/calibration-ledger.d.ts +37 -0
  11. package/dist/calibration-ledger.js +148 -0
  12. package/dist/calibration-marker.d.ts +4 -0
  13. package/dist/calibration-marker.js +77 -0
  14. package/dist/catalog-setup.d.ts +33 -0
  15. package/dist/catalog-setup.js +89 -0
  16. package/dist/catalog.d.ts +10 -0
  17. package/dist/catalog.js +42 -0
  18. package/dist/checkpoint-files.d.ts +15 -0
  19. package/dist/checkpoint-files.js +99 -0
  20. package/dist/coalesce-reads.d.ts +6 -0
  21. package/dist/coalesce-reads.js +33 -0
  22. package/dist/contract-caller.d.ts +2 -1
  23. package/dist/contract-caller.js +35 -16
  24. package/dist/contract-schema.d.ts +3 -1
  25. package/dist/contract-schema.js +34 -4
  26. package/dist/contracts.d.ts +1 -0
  27. package/dist/contracts.js +5 -1
  28. package/dist/core.d.ts +31 -1
  29. package/dist/core.js +27 -0
  30. package/dist/db-final-answer.d.ts +9 -0
  31. package/dist/db-final-answer.js +62 -0
  32. package/dist/define.d.ts +78 -0
  33. package/dist/define.js +14 -0
  34. package/dist/final-answer-stores.d.ts +71 -0
  35. package/dist/final-answer-stores.js +72 -0
  36. package/dist/final-answer.d.ts +32 -0
  37. package/dist/final-answer.js +104 -0
  38. package/dist/impact.d.ts +48 -0
  39. package/dist/impact.js +71 -0
  40. package/dist/local-tool.d.ts +18 -0
  41. package/dist/local-tool.js +32 -0
  42. package/dist/mcp-apps.d.ts +53 -0
  43. package/dist/mcp-apps.js +32 -0
  44. package/dist/mcp-event-delivery.d.ts +98 -0
  45. package/dist/mcp-event-delivery.js +211 -0
  46. package/dist/mcp-extensions.d.ts +46 -0
  47. package/dist/mcp-extensions.js +200 -0
  48. package/dist/mcp-peer.d.ts +45 -0
  49. package/dist/mcp-peer.js +207 -0
  50. package/dist/mcp-server-card.d.ts +21 -0
  51. package/dist/mcp-server-card.js +54 -0
  52. package/dist/page-checkpoint.d.ts +71 -0
  53. package/dist/page-checkpoint.js +286 -0
  54. package/dist/page-read-gate.d.ts +15 -0
  55. package/dist/page-read-gate.js +48 -0
  56. package/dist/pattern.d.ts +1 -0
  57. package/dist/pattern.js +27 -5
  58. package/dist/read-pages.d.ts +25 -0
  59. package/dist/read-pages.js +85 -0
  60. package/dist/read-policy.d.ts +6 -0
  61. package/dist/read-policy.js +16 -0
  62. package/dist/read-steps.d.ts +12 -0
  63. package/dist/read-steps.js +36 -0
  64. package/dist/result-session.d.ts +109 -0
  65. package/dist/result-session.js +620 -0
  66. package/dist/route-checkpoint.d.ts +3 -0
  67. package/dist/route-checkpoint.js +80 -0
  68. package/dist/route-evaluation.d.ts +141 -0
  69. package/dist/route-evaluation.js +329 -0
  70. package/dist/row-groups.d.ts +17 -0
  71. package/dist/row-groups.js +79 -0
  72. package/dist/row-query.d.ts +62 -0
  73. package/dist/row-query.js +172 -0
  74. package/dist/rules.d.ts +30 -0
  75. package/dist/rules.js +72 -0
  76. package/dist/run-diagnostics.d.ts +75 -0
  77. package/dist/run-diagnostics.js +212 -0
  78. package/dist/search-fetch.d.ts +50 -0
  79. package/dist/search-fetch.js +264 -0
  80. package/dist/skill-files.d.ts +9 -0
  81. package/dist/skill-files.js +49 -0
  82. package/dist/splice-diagnostics.d.ts +4 -0
  83. package/dist/splice-diagnostics.js +24 -16
  84. package/dist/splice-recording.d.ts +29 -2
  85. package/dist/splice-recording.js +22 -5
  86. package/dist/splice.d.ts +98 -1
  87. package/dist/splice.js +225 -27
  88. package/dist/sqlite-checkpoint-store.d.ts +5 -0
  89. package/dist/sqlite-checkpoint-store.js +91 -0
  90. package/dist/sqlite-checkpoint-worker.js +115 -0
  91. package/dist/test-difference.d.ts +13 -0
  92. package/dist/test-difference.js +42 -0
  93. package/dist/testing.d.ts +122 -0
  94. package/dist/testing.js +261 -0
  95. package/dist/text-pages.d.ts +24 -0
  96. package/dist/text-pages.js +36 -0
  97. package/dist/tool-discovery.d.ts +59 -0
  98. package/dist/tool-discovery.js +136 -0
  99. package/dist/unevaluated.d.ts +7 -0
  100. package/dist/unevaluated.js +156 -0
  101. package/dist/version.d.ts +1 -1
  102. package/dist/version.js +1 -1
  103. package/dist/workflow-json.js +1 -1
  104. package/integrations/ai.d.mts +36 -0
  105. package/integrations/ai.mjs +178 -0
  106. package/integrations/call-options.mjs +9 -0
  107. package/integrations/langchain.d.mts +31 -0
  108. package/integrations/langchain.mjs +114 -0
  109. package/integrations/managed.mjs +154 -0
  110. package/integrations/types.d.mts +13 -0
  111. package/package.json +30 -1
package/dist/splice.d.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  import { type ContractSchema, type ContractSnapshot } from "./contracts.js";
2
2
  import { type BindingCallOptions, type ToolCaller } from "./execution.js";
3
+ import { type SpliceRule } from "./rules.js";
4
+ import { type McpToolUi } from "./mcp-apps.js";
3
5
  export interface SpliceEndpoint {
4
6
  server: string;
5
7
  tool: string;
@@ -26,19 +28,44 @@ export interface SpliceSpec {
26
28
  path: string;
27
29
  equals: unknown;
28
30
  }[];
31
+ /** Select exactly one candidate by a scalar key after source value validation. */
32
+ matchOne?: {
33
+ path: string;
34
+ } & ({
35
+ equals: string | number | boolean | null;
36
+ } | {
37
+ fromContext: string;
38
+ });
29
39
  };
30
40
  target: SpliceEndpoint & {
31
41
  /** Reject duplicate destination-key tuples within this batch, before any target call. */
32
42
  uniqueBy?: string[];
43
+ /** Return this field from each validated destination response. Empty selects the full result. */
44
+ resultPath?: string;
45
+ /** Build an object from named JSON pointers into the validated destination response. */
46
+ resultFields?: Record<string, string>;
33
47
  };
34
48
  forEach?: boolean;
35
49
  maxItems?: number;
36
50
  /** UTF-8 JSON bytes of the final result array; default 5 MiB, maximum 64 MiB. */
37
51
  maxResultBytes?: number;
38
52
  bindings: SpliceBinding[];
53
+ /** Per-row application rules checked before any destination call. */
54
+ rules?: SpliceRule[];
39
55
  /** Application-supplied values, validated before any source call. */
40
56
  contextSchema?: Record<string, unknown>;
41
57
  }
58
+ export interface SpliceToolOptions {
59
+ /** Enable ordered read waves with an application-owned concurrency bound. */
60
+ readConcurrency?: number;
61
+ assumeReadOnly?: boolean;
62
+ /** Link an explicitly registered MCP Apps resource to the outer tool. */
63
+ ui?: McpToolUi;
64
+ name: string;
65
+ description?: string;
66
+ source: ToolCaller;
67
+ target: ToolCaller;
68
+ }
42
69
  export interface SpliceIssue {
43
70
  severity: "error" | "warning";
44
71
  code: string;
@@ -66,18 +93,88 @@ export interface SpliceRunOptions extends BindingCallOptions, SpliceMappingOptio
66
93
  /** Explicitly allow uncertain static checks; runtime validation still applies to every row. */
67
94
  allowReview?: boolean;
68
95
  }
96
+ export interface SpliceReadOptions extends SpliceRunOptions {
97
+ /** Maximum independent destination calls in each ordered wave. Default 4. */
98
+ concurrency?: number;
99
+ /** Application confirmation for read-only tools that omit the MCP readOnlyHint. */
100
+ assumeReadOnly?: boolean;
101
+ }
69
102
  export declare class SpliceError extends Error {
70
103
  readonly stage: "preflight" | "context" | "source" | "mapping" | "target";
71
104
  readonly completedTargets: number;
105
+ /** Rows submitted in read waves, possibly beyond the successful in-order prefix. */
106
+ scheduledTargets?: number;
72
107
  readonly issues: SpliceIssue[];
73
108
  constructor(stage: "preflight" | "context" | "source" | "mapping" | "target", completedTargets: number, cause?: unknown, details?: SpliceIssue[]);
74
109
  }
110
+ export declare function readSplicePath(value: unknown, pointer: string): {
111
+ found: boolean;
112
+ value: unknown;
113
+ };
75
114
  export declare function parseSpliceSpec(source: string | unknown): SpliceSpec;
76
115
  export declare function preflightSplice(plan: SpliceSpec, source: ContractSnapshot, target: ContractSnapshot): SpliceReport;
77
116
  export declare function prepareSplice(plan: SpliceSpec, source: ContractSnapshot, target: ContractSnapshot): {
78
117
  report: SpliceReport;
79
118
  mapOutput: (output: unknown, options?: SpliceMappingOptions) => Promise<Record<string, unknown>[]>;
80
- run: (sourceCaller: ToolCaller, targetCaller: ToolCaller, args: unknown, options?: SpliceRunOptions) => Promise<unknown[]>;
119
+ run: (source: ToolCaller, target: ToolCaller, args: unknown, options?: SpliceRunOptions) => Promise<unknown[]>;
120
+ runReads: (source: ToolCaller, target: ToolCaller, args: unknown, options?: SpliceReadOptions) => Promise<unknown[]>;
121
+ asTool: ({ name, description, source, target, ui, readConcurrency: requested, assumeReadOnly }: SpliceToolOptions) => {
122
+ definition: {
123
+ name: string;
124
+ description?: string | undefined;
125
+ _meta?: {
126
+ ui: McpToolUi;
127
+ } | undefined;
128
+ inputSchema: {
129
+ type: "object";
130
+ };
131
+ outputSchema: {
132
+ type: "object";
133
+ properties: {
134
+ results: {
135
+ type: string;
136
+ items: {
137
+ type: string;
138
+ properties: {
139
+ [k: string]: {};
140
+ };
141
+ required: string[];
142
+ additionalProperties: boolean;
143
+ } | {
144
+ type?: undefined;
145
+ properties?: undefined;
146
+ required?: undefined;
147
+ additionalProperties?: undefined;
148
+ };
149
+ };
150
+ };
151
+ required: string[];
152
+ additionalProperties: boolean;
153
+ };
154
+ };
155
+ call: (args: Record<string, unknown>, options?: SpliceRunOptions) => Promise<{
156
+ resultType: "complete";
157
+ structuredContent: {
158
+ results: unknown[];
159
+ };
160
+ content: {
161
+ type: "text";
162
+ text: string;
163
+ }[];
164
+ isError?: undefined;
165
+ } | {
166
+ structuredContent?: undefined;
167
+ resultType: "complete";
168
+ isError: true;
169
+ content: {
170
+ type: "text";
171
+ text: string;
172
+ }[];
173
+ }>;
174
+ execute: (args: Record<string, unknown>, options?: SpliceRunOptions) => Promise<{
175
+ results: unknown[];
176
+ }>;
177
+ };
81
178
  };
82
179
  export declare function emitSpliceModule(plan: SpliceSpec, source: ContractSnapshot, target: ContractSnapshot, options?: {
83
180
  runtimeImport?: string;
package/dist/splice.js CHANGED
@@ -8,6 +8,8 @@ import { invokeTool, } from "./execution.js";
8
8
  import { parseJsonText } from "./extract.js";
9
9
  import { emitModule } from "./codegen.js";
10
10
  import { newServer, recordToolList } from "./store.js";
11
+ import { validateRules, ruleEvaluator } from "./rules.js";
12
+ import { toolUi } from "./mcp-apps.js";
11
13
  class MappingFault extends Error {
12
14
  code;
13
15
  path;
@@ -20,6 +22,8 @@ class MappingFault extends Error {
20
22
  export class SpliceError extends Error {
21
23
  stage;
22
24
  completedTargets;
25
+ /** Rows submitted in read waves, possibly beyond the successful in-order prefix. */
26
+ scheduledTargets;
23
27
  issues;
24
28
  constructor(stage, completedTargets, cause, details) {
25
29
  const issues = details ??
@@ -77,6 +81,12 @@ function ownPath(value, path) {
77
81
  }
78
82
  return { found: true, value: current };
79
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
+ }
80
90
  const knownKeys = (v, keys) => Object.keys(v).every((k) => keys.includes(k));
81
91
  export function parseSpliceSpec(source) {
82
92
  if (typeof source === "string" && Buffer.byteLength(source) > 1024 * 1024)
@@ -93,8 +103,8 @@ export function parseSpliceSpec(source) {
93
103
  throw new Error("Splice plan exceeds 1 MiB.");
94
104
  const endpoint = (e, from) => object(e) &&
95
105
  knownKeys(e, from
96
- ? ["server", "tool", "path", "parseJson", "expect", "valueSchema"]
97
- : ["server", "tool", "uniqueBy"]) &&
106
+ ? ["server", "tool", "path", "parseJson", "expect", "valueSchema", "matchOne"]
107
+ : ["server", "tool", "uniqueBy", "resultPath", "resultFields"]) &&
98
108
  typeof e.server === "string" &&
99
109
  e.server.length > 0 &&
100
110
  typeof e.tool === "string" &&
@@ -114,6 +124,7 @@ export function parseSpliceSpec(source) {
114
124
  "maxResultBytes",
115
125
  "bindings",
116
126
  "contextSchema",
127
+ "rules",
117
128
  ]) ||
118
129
  v.format !== "toolsplice-splice" ||
119
130
  v.formatVersion !== 1 ||
@@ -136,6 +147,19 @@ export function parseSpliceSpec(source) {
136
147
  throw new Error("Invalid or unsupported Toolsplice plan.");
137
148
  if (object(v.source) && typeof v.source.path === "string")
138
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
+ }
139
163
  if (object(v.source) && v.source.expect !== undefined) {
140
164
  if (!Array.isArray(v.source.expect) ||
141
165
  v.source.expect.length < 1 ||
@@ -150,6 +174,22 @@ export function parseSpliceSpec(source) {
150
174
  segments(condition.path);
151
175
  }
152
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
+ }
153
193
  if (object(v.target) && v.target.uniqueBy !== undefined) {
154
194
  if (!Array.isArray(v.target.uniqueBy) ||
155
195
  v.target.uniqueBy.length < 1 ||
@@ -167,6 +207,8 @@ export function parseSpliceSpec(source) {
167
207
  keys.push(parts);
168
208
  }
169
209
  }
210
+ if (v.rules !== undefined)
211
+ validateRules(v.rules, v.contextSchema !== undefined);
170
212
  const paths = [];
171
213
  for (const binding of v.bindings) {
172
214
  if (!object(binding) ||
@@ -635,6 +677,8 @@ export function preflightSplice(plan, source, target) {
635
677
  const spec = parseSpliceSpec(plan), s = parseContractSnapshot(source), t = parseContractSnapshot(target), st = endpointTool(s, spec.source), tt = endpointTool(t, spec.target);
636
678
  const a = { issues: [], remaining: 2000, limited: false };
637
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.");
638
682
  for (const [i, condition] of (spec.source.expect ?? []).entries()) {
639
683
  const path = `/source/expect/${i}`;
640
684
  const field = project(sourceRoot, segments(condition.path), sourceRoot, a, path);
@@ -667,18 +711,30 @@ export function preflightSplice(plan, source, target) {
667
711
  ? "The selected source cannot meet this value requirement."
668
712
  : "This consumer schema must pass on the selected value before fanout and argument mapping.");
669
713
  }
670
- if (spec.forEach) {
714
+ const match = spec.source.matchOne;
715
+ if (spec.forEach || match) {
671
716
  selected = resolve(selected, sourceRoot, a, "/source");
672
717
  if (object(selected) && selected.type === "array")
673
- selected = schema(selected.items) ? selected.items : true;
718
+ selected = match && (Array.isArray(selected.items) || Array.isArray(selected.prefixItems))
719
+ ? true : schema(selected.items) ? selected.items : true;
674
720
  else if (selected === true ||
675
721
  !object(selected) ||
676
- selected.type === undefined) {
677
- issue(a, "warning", "unknown-array-source", "/source", "The available schema does not establish an array for forEach.");
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.");
678
725
  selected = true;
679
726
  }
680
727
  else
681
- issue(a, "error", "forEach-requires-array", "/source", "Explicit forEach needs an array source.");
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);
682
738
  }
683
739
  let argumentsSchema = {
684
740
  type: "object",
@@ -721,6 +777,20 @@ export function preflightSplice(plan, source, target) {
721
777
  }
722
778
  issue(a, "warning", "unique-target-keys", "/target/uniqueBy", "Destination-key tuples must be distinct within the mapped batch before any target call.");
723
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
+ }
724
794
  if (st.limited)
725
795
  issue(a, "warning", "limited-source-evidence", "/source", "Source inference was limited; inspect the selected paths before enabling execution.");
726
796
  if (a.limited)
@@ -832,6 +902,8 @@ export function prepareSplice(plan, source, target) {
832
902
  (policyStatus === "review" && !options.allowReview))
833
903
  throw new SpliceError("preflight", 0, setupError, report.issues);
834
904
  };
905
+ const match = spec.source.matchOne;
906
+ const matchPath = match ? segments(match.path) : [];
835
907
  const resolveContext = async (options) => {
836
908
  if (!spec.contextSchema) {
837
909
  if (options.context !== undefined)
@@ -850,6 +922,11 @@ export function prepareSplice(plan, source, target) {
850
922
  name: "context",
851
923
  arguments: context,
852
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
+ }
853
930
  for (const binding of spec.bindings) {
854
931
  if ("fromContext" in binding &&
855
932
  !ownPath(context, segments(binding.fromContext)).found)
@@ -866,6 +943,7 @@ export function prepareSplice(plan, source, target) {
866
943
  throw new SpliceError("preflight", 0, setupError, report.issues);
867
944
  try {
868
945
  assertContractJson(output);
946
+ output = JSON.parse(JSON.stringify(output));
869
947
  for (const condition of spec.source.expect ?? []) {
870
948
  const selected = ownPath(output, segments(condition.path));
871
949
  if (!selected.found ||
@@ -873,7 +951,7 @@ export function prepareSplice(plan, source, target) {
873
951
  JSON.stringify(canonicalValue(condition.equals)))
874
952
  throw new MappingFault("source-expectation-failed", condition.path, "An explicit source expectation failed.");
875
953
  }
876
- const selected = ownPath(output, segments(spec.source.path ?? ""));
954
+ const selected = readSplicePath(output, spec.source.path ?? "");
877
955
  if (!selected.found)
878
956
  throw new MappingFault("source-selection-missing", "/source", "The selected source path is absent.");
879
957
  let value = selected.value;
@@ -900,6 +978,26 @@ export function prepareSplice(plan, source, target) {
900
978
  throw error;
901
979
  }
902
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
+ }
903
1001
  const rows = spec.forEach ? value : [value];
904
1002
  if (!Array.isArray(rows))
905
1003
  throw new MappingFault("forEach-requires-array", "/forEach", "The selected source is not an array.");
@@ -908,6 +1006,7 @@ export function prepareSplice(plan, source, target) {
908
1006
  const mapped = [];
909
1007
  const uniqueKeys = new Set();
910
1008
  let batchBytes = 0;
1009
+ const checkRules = ruleEvaluator(spec.rules);
911
1010
  for (const [rowIndex, row] of rows.entries()) {
912
1011
  let args = Object.create(null);
913
1012
  for (const binding of spec.bindings) {
@@ -956,6 +1055,9 @@ export function prepareSplice(plan, source, target) {
956
1055
  throw new MappingFault("duplicate-target-key", `/rows/${rowIndex}`, "This destination-key tuple duplicates an earlier row; the whole batch was rejected.");
957
1056
  uniqueKeys.add(key);
958
1057
  }
1058
+ const violation = checkRules({ source: output, row, mapped: detached, context }, rowIndex);
1059
+ if (violation)
1060
+ throw new SpliceError("mapping", 0, undefined, [violation]);
959
1061
  mapped.push(detached);
960
1062
  }
961
1063
  return mapped;
@@ -981,7 +1083,9 @@ export function prepareSplice(plan, source, target) {
981
1083
  }
982
1084
  return mapDecoded(output, context);
983
1085
  };
984
- const run = async (sourceCaller, targetCaller, args, options = {}) => {
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) => {
985
1089
  checkPolicy(options);
986
1090
  const context = await resolveContext(options);
987
1091
  const callOptions = {
@@ -1015,29 +1119,112 @@ export function prepareSplice(plan, source, target) {
1015
1119
  }
1016
1120
  const mapped = await mapDecoded(result, context), results = [];
1017
1121
  let resultBytes = 2; // The returned JSON array's brackets.
1018
- for (const next of mapped) {
1019
- try {
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) {
1020
1126
  options.signal?.throwIfAborted();
1021
- const value = await invokeTool(targetGuard, spec.target.tool, next, callOptions);
1022
- try {
1023
- assertContractJson(value);
1024
- }
1025
- catch {
1026
- throw new MappingFault("target-result-limits", `/results/${results.length}`, "Destination output must be finite, bounded JSON.");
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[""]);
1027
1157
  }
1028
- const encoded = JSON.stringify(value);
1029
- resultBytes += Buffer.byteLength(encoded) + (results.length ? 1 : 0);
1030
- if (resultBytes > report.maxResultBytes)
1031
- throw new MappingFault("result-batch-byte-limit", `/results/${results.length}`, "Collected destination output exceeds the configured byte budget; no truncation was applied.");
1032
- results.push(JSON.parse(encoded));
1033
- }
1034
- catch (error) {
1035
- throw new SpliceError("target", results.length, error);
1036
1158
  }
1037
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
+ }
1038
1166
  return results;
1039
1167
  };
1040
- return { report, mapOutput, run };
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 };
1041
1228
  }
1042
1229
  export function emitSpliceModule(plan, source, target, options = {}) {
1043
1230
  const spec = parseSpliceSpec(plan), s = selectContractTools(source, [spec.source.tool]), t = selectContractTools(target, [spec.target.tool]);
@@ -1061,5 +1248,16 @@ export function emitSpliceModule(plan, source, target, options = {}) {
1061
1248
  optionsParameter =
1062
1249
  'options: toolsplice.SpliceRunOptions & { context: Parameters<Context.Tools["context"]>[0] }';
1063
1250
  }
1064
- 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}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<Awaited<ReturnType<Target.Tools[${JSON.stringify(spec.target.tool)}]>>[]> =>\n splice.run(source, target, args, options) as Promise<Awaited<ReturnType<Target.Tools[${JSON.stringify(spec.target.tool)}]>>[]>;\n}\n`;
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`;
1065
1263
  }
@@ -0,0 +1,5 @@
1
+ import type { FinalAnswerStore } from "./final-answer-stores.js";
2
+ /** A local, cross-process checkpoint store. Own one connection per worker and close it at shutdown. */
3
+ export declare function openSqliteCheckpointStore(filename: string): Promise<FinalAnswerStore & {
4
+ close(): Promise<void>;
5
+ }>;
@@ -0,0 +1,91 @@
1
+ import { Worker } from "node:worker_threads";
2
+ import { resolve } from "node:path";
3
+ /** A local, cross-process checkpoint store. Own one connection per worker and close it at shutdown. */
4
+ export async function openSqliteCheckpointStore(filename) {
5
+ if (typeof filename !== "string" || !filename || filename === ":memory:")
6
+ throw new TypeError("Provide a local SQLite database file.");
7
+ const worker = new Worker(new URL(new URL(import.meta.url).pathname.endsWith(".ts")
8
+ ? "./sqlite-checkpoint-worker.ts"
9
+ : "./sqlite-checkpoint-worker.js", import.meta.url), {
10
+ workerData: resolve(filename),
11
+ execArgv: [],
12
+ });
13
+ const batchSize = 64;
14
+ let sequence = 0;
15
+ let stopped;
16
+ let closing;
17
+ const pending = new Map();
18
+ const queue = [];
19
+ let scheduled;
20
+ function flush() {
21
+ if (scheduled)
22
+ clearImmediate(scheduled);
23
+ scheduled = undefined;
24
+ for (let start = 0; start < queue.length; start += batchSize)
25
+ worker.postMessage({ batch: queue.slice(start, start + batchSize) });
26
+ queue.length = 0;
27
+ }
28
+ function stop(error) {
29
+ stopped ??= error;
30
+ if (scheduled)
31
+ clearImmediate(scheduled);
32
+ queue.length = 0;
33
+ for (const request of pending.values())
34
+ request.reject(error);
35
+ pending.clear();
36
+ }
37
+ worker.on("error", stop);
38
+ worker.on("exit", () => stop(new Error("SQLite checkpoint connection closed.")));
39
+ worker.on("message", (message) => {
40
+ for (const reply of Array.isArray(message) ? message : [message]) {
41
+ const item = pending.get(reply.id);
42
+ if (!item)
43
+ continue;
44
+ pending.delete(reply.id);
45
+ if (reply.error !== undefined)
46
+ item.reject(new Error(reply.error));
47
+ else
48
+ item.resolve(reply.value);
49
+ }
50
+ if (!pending.size)
51
+ worker.unref();
52
+ });
53
+ function request(method, ...args) {
54
+ // A malformed binding must never roll back another job in the same commit.
55
+ // SQLite UTF-8 bindings would silently replace an unpaired JS surrogate.
56
+ if (args.some((value) => typeof value !== "string" || /[\uD800-\uDFFF]/u.test(value)))
57
+ return Promise.reject(new TypeError("SQLite checkpoint arguments must be valid Unicode strings."));
58
+ if (closing || stopped)
59
+ return Promise.reject(stopped ?? new Error("SQLite checkpoint connection is closing."));
60
+ const id = ++sequence;
61
+ return new Promise((resolve, reject) => {
62
+ pending.set(id, { resolve: (value) => resolve(value), reject });
63
+ worker.ref();
64
+ if (method === "open" || method === "close") {
65
+ flush();
66
+ worker.postMessage({ id, method, args });
67
+ }
68
+ else {
69
+ queue.push({ id, method, args });
70
+ scheduled ??= setImmediate(flush);
71
+ }
72
+ });
73
+ }
74
+ try {
75
+ await request("open");
76
+ }
77
+ catch (error) {
78
+ await worker.terminate();
79
+ throw error;
80
+ }
81
+ return {
82
+ read: (job) => request("read", job),
83
+ claim: (job, identity) => request("claim", job, identity),
84
+ complete: (job, identity, payload) => request("complete", job, identity, payload),
85
+ close() {
86
+ return (closing ??= request("close").finally(async () => {
87
+ await worker.terminate();
88
+ }));
89
+ },
90
+ };
91
+ }