toolsplice 0.0.1 → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/README.md +62 -330
  2. package/dist/abortable.d.ts +6 -0
  3. package/dist/abortable.js +50 -0
  4. package/dist/adaptive-read.d.ts +50 -0
  5. package/dist/adaptive-read.js +780 -0
  6. package/dist/answer-wait.d.ts +7 -0
  7. package/dist/answer-wait.js +45 -0
  8. package/dist/cache-reads.d.ts +18 -0
  9. package/dist/cache-reads.js +89 -0
  10. package/dist/calibration-ledger.d.ts +37 -0
  11. package/dist/calibration-ledger.js +148 -0
  12. package/dist/calibration-marker.d.ts +4 -0
  13. package/dist/calibration-marker.js +77 -0
  14. package/dist/catalog-setup.d.ts +33 -0
  15. package/dist/catalog-setup.js +89 -0
  16. package/dist/catalog.d.ts +10 -0
  17. package/dist/catalog.js +42 -0
  18. package/dist/checkpoint-files.d.ts +15 -0
  19. package/dist/checkpoint-files.js +99 -0
  20. package/dist/cli.js +545 -14
  21. package/dist/coalesce-reads.d.ts +6 -0
  22. package/dist/coalesce-reads.js +33 -0
  23. package/dist/contract-caller.d.ts +2 -1
  24. package/dist/contract-caller.js +35 -16
  25. package/dist/contract-schema.d.ts +3 -1
  26. package/dist/contract-schema.js +34 -4
  27. package/dist/contracts.d.ts +1 -0
  28. package/dist/contracts.js +5 -1
  29. package/dist/core.d.ts +31 -1
  30. package/dist/core.js +27 -0
  31. package/dist/db-final-answer.d.ts +9 -0
  32. package/dist/db-final-answer.js +62 -0
  33. package/dist/define.d.ts +78 -0
  34. package/dist/define.js +14 -0
  35. package/dist/final-answer-stores.d.ts +71 -0
  36. package/dist/final-answer-stores.js +72 -0
  37. package/dist/final-answer.d.ts +32 -0
  38. package/dist/final-answer.js +104 -0
  39. package/dist/impact.d.ts +48 -0
  40. package/dist/impact.js +71 -0
  41. package/dist/index.d.ts +32 -1
  42. package/dist/index.js +28 -0
  43. package/dist/local-tool.d.ts +18 -0
  44. package/dist/local-tool.js +32 -0
  45. package/dist/mcp-apps.d.ts +53 -0
  46. package/dist/mcp-apps.js +32 -0
  47. package/dist/mcp-event-delivery.d.ts +98 -0
  48. package/dist/mcp-event-delivery.js +211 -0
  49. package/dist/mcp-extensions.d.ts +46 -0
  50. package/dist/mcp-extensions.js +200 -0
  51. package/dist/mcp-peer.d.ts +45 -0
  52. package/dist/mcp-peer.js +207 -0
  53. package/dist/mcp-server-card.d.ts +21 -0
  54. package/dist/mcp-server-card.js +54 -0
  55. package/dist/page-checkpoint.d.ts +71 -0
  56. package/dist/page-checkpoint.js +286 -0
  57. package/dist/page-read-gate.d.ts +15 -0
  58. package/dist/page-read-gate.js +48 -0
  59. package/dist/pattern.d.ts +1 -0
  60. package/dist/pattern.js +27 -5
  61. package/dist/probe.js +6 -19
  62. package/dist/read-pages.d.ts +25 -0
  63. package/dist/read-pages.js +85 -0
  64. package/dist/read-policy.d.ts +6 -0
  65. package/dist/read-policy.js +16 -0
  66. package/dist/read-steps.d.ts +12 -0
  67. package/dist/read-steps.js +36 -0
  68. package/dist/result-session.d.ts +109 -0
  69. package/dist/result-session.js +620 -0
  70. package/dist/route-checkpoint.d.ts +3 -0
  71. package/dist/route-checkpoint.js +80 -0
  72. package/dist/route-driver-cli.d.ts +3 -0
  73. package/dist/route-driver-cli.js +43 -0
  74. package/dist/route-evaluation.d.ts +141 -0
  75. package/dist/route-evaluation.js +329 -0
  76. package/dist/row-groups.d.ts +17 -0
  77. package/dist/row-groups.js +79 -0
  78. package/dist/row-query.d.ts +62 -0
  79. package/dist/row-query.js +172 -0
  80. package/dist/rules.d.ts +30 -0
  81. package/dist/rules.js +72 -0
  82. package/dist/run-diagnostics.d.ts +75 -0
  83. package/dist/run-diagnostics.js +212 -0
  84. package/dist/search-fetch.d.ts +50 -0
  85. package/dist/search-fetch.js +264 -0
  86. package/dist/skill-files.d.ts +9 -0
  87. package/dist/skill-files.js +49 -0
  88. package/dist/splice-diagnostics.d.ts +4 -0
  89. package/dist/splice-diagnostics.js +24 -16
  90. package/dist/splice-measure.d.ts +33 -0
  91. package/dist/splice-measure.js +55 -0
  92. package/dist/splice-project.d.ts +12 -6
  93. package/dist/splice-project.js +72 -20
  94. package/dist/splice-recording.d.ts +29 -2
  95. package/dist/splice-recording.js +22 -5
  96. package/dist/splice.d.ts +98 -1
  97. package/dist/splice.js +225 -27
  98. package/dist/sqlite-checkpoint-store.d.ts +5 -0
  99. package/dist/sqlite-checkpoint-store.js +91 -0
  100. package/dist/sqlite-checkpoint-worker.d.ts +1 -0
  101. package/dist/sqlite-checkpoint-worker.js +115 -0
  102. package/dist/test-difference.d.ts +13 -0
  103. package/dist/test-difference.js +42 -0
  104. package/dist/testing.d.ts +122 -0
  105. package/dist/testing.js +261 -0
  106. package/dist/text-pages.d.ts +24 -0
  107. package/dist/text-pages.js +36 -0
  108. package/dist/tool-discovery.d.ts +59 -0
  109. package/dist/tool-discovery.js +136 -0
  110. package/dist/unevaluated.d.ts +7 -0
  111. package/dist/unevaluated.js +156 -0
  112. package/dist/v2.js +25 -8
  113. package/dist/version.d.ts +1 -1
  114. package/dist/version.js +1 -1
  115. package/dist/workflow-json.js +1 -1
  116. package/docs/AGENT-FRAMEWORKS.md +431 -0
  117. package/docs/BENCHMARKS.md +43 -0
  118. package/docs/INTEGRATION-QUICKSTART.md +859 -0
  119. package/docs/LEARNING-AND-STORAGE.md +393 -0
  120. package/docs/MCP.md +204 -0
  121. package/docs/PROJECTS-AND-UPGRADES.md +67 -9
  122. package/docs/PYTHON-REFERENCE.md +348 -0
  123. package/docs/PYTHON.md +120 -0
  124. package/docs/RECORDING-AND-CORRECTIONS.md +30 -1
  125. package/docs/TESTING.md +259 -0
  126. package/examples/mcp-app/build.mjs +11 -0
  127. package/examples/mcp-app/view.mjs +22 -0
  128. package/examples/quickstart.mjs +43 -0
  129. package/examples/route-driver.mjs +67 -0
  130. package/integrations/ai.d.mts +36 -0
  131. package/integrations/ai.mjs +178 -0
  132. package/integrations/call-options.mjs +9 -0
  133. package/integrations/langchain.d.mts +31 -0
  134. package/integrations/langchain.mjs +114 -0
  135. package/integrations/managed.mjs +154 -0
  136. package/integrations/types.d.mts +13 -0
  137. package/package.json +47 -3
package/dist/cli.js CHANGED
@@ -1,7 +1,18 @@
1
1
  #!/usr/bin/env node
2
- import { readFileSync, writeFileSync } from "node:fs";
3
- import { delimiter, dirname, resolve } from "node:path";
2
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
3
+ import { ListToolsResultSchema } from "@modelcontextprotocol/sdk/types.js";
4
+ import { validMcpHeaderSchema } from "./contract-schema.js";
5
+ import { collectToolCatalog } from "./catalog.js";
6
+ import { randomUUID } from "node:crypto";
7
+ import { openSync, closeSync, linkSync, unlinkSync, readFileSync, writeFileSync, statSync, realpathSync } from "node:fs";
8
+ import { catalogToolNames, inspectCatalogMapping, parseCatalogBinding } from "./catalog-setup.js";
9
+ import { assessSpliceImpact } from "./impact.js";
10
+ import { runSpliceSuite, formatTestJUnit, suiteFromRecording } from "./testing.js";
11
+ import { delimiter, dirname, resolve, relative, isAbsolute, sep } from "node:path";
4
12
  import { fileURLToPath } from "node:url";
13
+ import { existsSync, createReadStream } from "node:fs";
14
+ import { evaluateRoutes, readCalibrationLedger } from "./route-evaluation.js";
15
+ import { executeRouteDriver } from "./route-driver-cli.js";
5
16
  import { parseArgs } from "node:util";
6
17
  import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
7
18
  import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
@@ -9,6 +20,7 @@ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
9
20
  import { parseSpliceSpec, prepareSplice, emitSpliceModule, SpliceError, } from "./splice.js";
10
21
  import { decode } from "./runtime.js";
11
22
  import { explainSpliceError } from "./splice-diagnostics.js";
23
+ import { measureSpliceRecording } from "./splice-measure.js";
12
24
  import { replaySpliceRecording } from "./splice-recording.js";
13
25
  import { applyContractCorrection, parseContractCorrection, } from "./contract-corrections.js";
14
26
  import { parseWorkflowJson, JSON_LIMIT } from "./workflow-json.js";
@@ -27,6 +39,14 @@ const USAGE = `toolsplice: check and generate MCP tool handoffs
27
39
  Usage:
28
40
  toolsplice splice <plan.json> [--fixture <file>] Check or dry-run an explicit tool-to-tool adapter; no tool calls
29
41
  toolsplice replay <recording.json> [--json] Replay a recorded run entirely offline; exit 2 on mismatch
42
+ toolsplice discover [--with-tools] --url <url> [--out discovery.json] Negotiate the protocol and list server capabilities (SDK 2.x)
43
+ toolsplice catalog [--modern] --url <url> [--out catalog.json] Capture all tools/list pages; accepts -- <command> [args...] for stdio
44
+ toolsplice impact <suite> --follow source|target --url <url> [--json] [--max-reports N]
45
+ Check the current catalog and recheck when the upstream signals a change.
46
+ toolsplice impact <suite.json|directory> [--source-contract file | --source-catalog file] [--target-contract file | --target-catalog file] [--candidate-result file] [--case name] [--json]
47
+ toolsplice test --from-recording <file> [--save-case <suite.json>] [--restorations <file>]
48
+ toolsplice evaluate --ledger <checkpoint-dir> Inspect all attempts and known spend\n toolsplice evaluate --init <new-suite.mjs> Create a runnable local evaluation driver\n toolsplice evaluate <trials.json> [--out policy.json] [--json]\n toolsplice evaluate --driver <trusted-suite.mjs> [--plan | --checkpoint dir [--retry-incomplete]] [--save-trials trials.json] [--out policy.json]\n toolsplice measure <recording.json> [--restorations <file>] [--json]
49
+ toolsplice init <dir> --source-catalog <file> --source server:tool --target-catalog <file> --target server:tool --fixture <file> [--fixture-format mcp] [--bind /destination=/source ...] [--set /destination=<json>] [--input <file>] [--each <array-pointer> [--max-items N]] [--result-path <pointer> | --result-fields <json-object>]
30
50
  toolsplice init <new-directory> Create and check an offline starter; optionally --from-recording <file>
31
51
  toolsplice project <directory> [--allow-review] Check project inputs/fixtures and mapped arguments offline
32
52
  toolsplice correct <baseline.json> --correction <file> Validate a pinned correction and its fixtures offline
@@ -105,6 +125,30 @@ const options = {
105
125
  context: { type: "string" },
106
126
  restorations: { type: "string" },
107
127
  "from-recording": { type: "string" },
128
+ junit: { type: "string" },
129
+ "candidate-result": { type: "string" },
130
+ "result-path": { type: "string" },
131
+ "result-fields": { type: "string" },
132
+ each: { type: "string" },
133
+ "max-items": { type: "string" },
134
+ modern: { type: "boolean" },
135
+ "with-tools": { type: "boolean" },
136
+ follow: { type: "string" },
137
+ "max-reports": { type: "string" },
138
+ case: { type: "string" },
139
+ "save-case": { type: "string" },
140
+ driver: { type: "string" },
141
+ checkpoint: { type: "string" },
142
+ ledger: { type: "string" },
143
+ "retry-incomplete": { type: "boolean" },
144
+ init: { type: "string" },
145
+ plan: { type: "boolean" },
146
+ "save-trials": { type: "string" },
147
+ source: { type: "string" },
148
+ target: { type: "string" },
149
+ input: { type: "string" },
150
+ bind: { type: "string", multiple: true },
151
+ set: { type: "string", multiple: true },
108
152
  correction: { type: "string" },
109
153
  baseline: { type: "string" },
110
154
  "fail-on": { type: "string" },
@@ -147,7 +191,7 @@ function integer(flags, name, fallback, min = 1) {
147
191
  throw new Error(`--${name} must be an integer >= ${min}`);
148
192
  return value;
149
193
  }
150
- function upstreamTransport(p) {
194
+ function upstreamConnection(p) {
151
195
  const url = str(p.flags.url);
152
196
  if (url) {
153
197
  if (p.upstream.length)
@@ -161,9 +205,8 @@ function upstreamTransport(p) {
161
205
  const token = tokenName ? process.env[tokenName] : undefined;
162
206
  if (tokenName && !token)
163
207
  throw new Error(`Environment variable ${tokenName} is empty or not set.`);
164
- return new StreamableHTTPClientTransport(parsed, token
165
- ? { requestInit: { headers: { Authorization: `Bearer ${token}` } } }
166
- : undefined);
208
+ return { kind: "http", url: parsed,
209
+ options: token ? { requestInit: { headers: { Authorization: `Bearer ${token}` } } } : undefined };
167
210
  }
168
211
  if (p.flags["bearer-env"])
169
212
  throw new Error("--bearer-env requires --url");
@@ -175,13 +218,18 @@ function upstreamTransport(p) {
175
218
  if (p.flags["database-env"])
176
219
  delete env[String(p.flags["database-env"])];
177
220
  env.PATH = `${dirname(process.execPath)}${delimiter}${env.PATH ?? ""}`;
178
- return new StdioClientTransport({
179
- command,
180
- args,
181
- cwd: str(p.flags["upstream-cwd"]),
182
- env,
183
- stderr: "inherit",
184
- });
221
+ return { kind: "stdio", params: {
222
+ command,
223
+ args,
224
+ cwd: str(p.flags["upstream-cwd"]),
225
+ env,
226
+ stderr: "inherit",
227
+ } };
228
+ }
229
+ function upstreamTransport(p) {
230
+ const connection = upstreamConnection(p);
231
+ return connection.kind === "http" ? new StreamableHTTPClientTransport(connection.url, connection.options)
232
+ : new StdioClientTransport(connection.params);
185
233
  }
186
234
  function config(p) {
187
235
  const name = str(p.flags.server) ?? str(p.flags.name);
@@ -557,6 +605,366 @@ async function runProject(p) {
557
605
  ? JSON.stringify(report, null, 2) + "\n"
558
606
  : `Created ${result.origin} starter in ${JSON.stringify(result.directory)}.\nCheck it with toolsplice project <directory> --allow-review --json. No tools were called.\n`);
559
607
  }
608
+ const ROUTE_FILE_LIMIT = 96 * 1024 * 1024;
609
+ function explainRoute(row) {
610
+ if (row.holdout && !row.holdout.reasons.length)
611
+ return "passed fit and holdout";
612
+ const phase = row.holdout ? "holdout" : "fit";
613
+ const candidates = row.holdout ? [row.holdout] : row.fit;
614
+ return candidates.length
615
+ ? phase + " " + candidates.map(c => c.route + " (" + c.reasons.join(", ") + ")").join(", ")
616
+ : "no candidate trials";
617
+ }
618
+ async function readRouteReceipt(file) {
619
+ if (!statSync(file).isFile())
620
+ throw new Error("Expected a local route-trial JSON file.");
621
+ const chunks = [];
622
+ let count = 0;
623
+ for await (const chunk of createReadStream(file)) {
624
+ count += chunk.length;
625
+ if (count > ROUTE_FILE_LIMIT)
626
+ throw new Error("Route receipt exceeds 96 MiB.");
627
+ chunks.push(chunk);
628
+ }
629
+ try {
630
+ return JSON.parse(Buffer.concat(chunks, count).toString("utf8"));
631
+ }
632
+ catch {
633
+ throw new Error("Invalid route-trial JSON.");
634
+ }
635
+ }
636
+ function readLocalJson(file) {
637
+ const stat = statSync(file);
638
+ if (!stat.isFile() || stat.size > JSON_LIMIT)
639
+ throw new Error("Expected a JSON file up to 5 MiB.");
640
+ return parseWorkflowJson(readFileSync(file, "utf8"));
641
+ }
642
+ function validateFlags(p, allowed) {
643
+ if (p.upstream.length || Object.keys(p.flags).some(key => !allowed.includes(key)))
644
+ throw new Error("Unsupported option for this offline command. See toolsplice --help.");
645
+ }
646
+ function endpoint(label, side) {
647
+ const split = label?.indexOf(":") ?? -1;
648
+ if (!label || split < 1 || split === label.length - 1)
649
+ throw new Error(`Choose the endpoint with --${side} server:tool.`);
650
+ return { server: label.slice(0, split), tool: label.slice(split + 1) };
651
+ }
652
+ async function initFromCatalogs(p) {
653
+ validateFlags(p, ["source", "target", "source-catalog", "target-catalog", "fixture", "fixture-format", "input", "bind", "set", "result-path", "result-fields", "each", "max-items", "json"]);
654
+ if (p.positional.length !== 1)
655
+ throw new Error("init requires one new project directory.");
656
+ const read = (flag) => {
657
+ const file = str(p.flags[flag]);
658
+ if (!file)
659
+ throw new Error(`Catalog setup requires --${flag} <file>.`);
660
+ return readLocalJson(file);
661
+ };
662
+ if (!p.flags.source && !p.flags.target && !p.flags.bind && !p.flags.set && p.flags["result-path"] === undefined && p.flags["result-fields"] === undefined && p.flags.each === undefined && p.flags["max-items"] === undefined) {
663
+ const sourceTools = catalogToolNames(read("source-catalog"));
664
+ const targetTools = catalogToolNames(read("target-catalog"));
665
+ process.stdout.write(JSON.stringify({ sourceTools, targetTools,
666
+ next: "Choose --source server:tool and --target server:tool, then supply --fixture <file>." }, null, 2) + "\n");
667
+ return;
668
+ }
669
+ const config = {
670
+ source: endpoint(str(p.flags.source), "source"), target: { ...endpoint(str(p.flags.target), "target"),
671
+ ...(p.flags["result-path"] !== undefined ? { resultPath: str(p.flags["result-path"]) } : {}),
672
+ ...(p.flags["result-fields"] !== undefined ? { resultFields: parseWorkflowJson(str(p.flags["result-fields"])) } : {}) },
673
+ sourceCatalog: read("source-catalog"),
674
+ targetCatalog: read("target-catalog"),
675
+ fixture: read("fixture"), fixtureFormat: (str(p.flags["fixture-format"]) ?? "decoded"),
676
+ ...(p.flags.each !== undefined ? { each: str(p.flags.each) } : {}),
677
+ ...(p.flags["max-items"] !== undefined ? { maxItems: integer(p.flags, "max-items", 100) } : {}),
678
+ bindings: [
679
+ ...(p.flags.bind ?? []).map(parseCatalogBinding),
680
+ ...(p.flags.set ?? []).map(text => {
681
+ const index = text.indexOf("=");
682
+ if (index < 0)
683
+ throw new Error("Use --set '/destination=<JSON literal>'.");
684
+ return { to: text.slice(0, index), value: parseWorkflowJson(text.slice(index + 1)) };
685
+ }),
686
+ ],
687
+ ...(p.flags.input ? { input: read("input") } : {}),
688
+ };
689
+ if (!config.bindings.length) {
690
+ const preview = inspectCatalogMapping(config);
691
+ process.stdout.write(JSON.stringify({ ...preview, next: "Repeat with --bind '/destination=/source' for each mapping." }, null, 2) + "\n");
692
+ return;
693
+ }
694
+ let result;
695
+ try {
696
+ result = await initializeSpliceProject(p.positional[0], { catalogs: config });
697
+ }
698
+ catch (error) {
699
+ if (error instanceof SpliceError) {
700
+ const issues = error.issues.map(issue => issue.code + " " + JSON.stringify(issue.path)).join(", ");
701
+ throw new Error(`Catalog mapping failed at ${error.stage}: ${issues}. Check the sample and bindings.`);
702
+ }
703
+ throw error;
704
+ }
705
+ process.stdout.write(p.flags.json ? JSON.stringify(result, null, 2) + "\n" :
706
+ `Created ${JSON.stringify(result.directory)}. Review tests.json, then run toolsplice test ${JSON.stringify(result.directory)}.\n`);
707
+ }
708
+ function readSuite(path) {
709
+ const read = readLocalJson;
710
+ const file = statSync(path).isDirectory() ? resolve(path, "tests.json") : path;
711
+ const suite = read(file);
712
+ if (!suite || typeof suite !== "object" || Array.isArray(suite))
713
+ throw new Error("Expected a test suite object.");
714
+ const base = realpathSync(dirname(file));
715
+ const readReference = (path) => {
716
+ const ref = realpathSync(resolve(base, path));
717
+ const name = relative(base, ref);
718
+ if (!name || name === ".." || name.startsWith(".." + sep) || isAbsolute(name))
719
+ throw new Error("Suite references must remain inside the suite directory.");
720
+ return read(ref);
721
+ };
722
+ for (const field of ["plan", "sourceContract", "targetContract"]) {
723
+ if (typeof suite[field] === "string")
724
+ suite[field] = readReference(suite[field]);
725
+ }
726
+ if (Array.isArray(suite.cases)) {
727
+ if (suite.cases.length > 100)
728
+ throw new Error("Suite exceeds 100 cases.");
729
+ let bytes = 0;
730
+ for (const c of suite.cases) {
731
+ if (!c || typeof c.sourceFixture !== "string")
732
+ continue;
733
+ if (c.mappingOnly !== true || Object.hasOwn(c, "sourceResult"))
734
+ throw new Error("Invalid mapping fixture reference.");
735
+ const fixture = readReference(c.sourceFixture);
736
+ bytes += Buffer.byteLength(JSON.stringify(fixture));
737
+ if (bytes > JSON_LIMIT)
738
+ throw new Error("Suite fixtures exceed 5 MiB.");
739
+ c.sourceResult = { structuredContent: fixture };
740
+ delete c.sourceFixture;
741
+ }
742
+ }
743
+ return suite;
744
+ }
745
+ function writeCatalog(path, text, limit = JSON_LIMIT) {
746
+ if (Buffer.byteLength(text) > limit)
747
+ throw new Error(limit === JSON_LIMIT ? "Catalog artifact exceeds 5 MiB." : "Route artifact exceeds 96 MiB.");
748
+ const temp = resolve(dirname(path), ".toolsplice-" + randomUUID() + ".tmp");
749
+ const fd = openSync(temp, "wx", 0o600);
750
+ try {
751
+ try {
752
+ writeFileSync(fd, text);
753
+ }
754
+ finally {
755
+ closeSync(fd);
756
+ }
757
+ linkSync(temp, path);
758
+ }
759
+ finally {
760
+ unlinkSync(temp);
761
+ }
762
+ }
763
+ async function modernConnection(p) {
764
+ const connection = upstreamConnection(p);
765
+ const sdk = await import("@modelcontextprotocol/client").catch(() => {
766
+ throw new Error("Install @modelcontextprotocol/client 2.x alongside toolsplice for modern discovery.");
767
+ });
768
+ const client = new sdk.Client({ name: "toolsplice", version: VERSION }, {
769
+ versionNegotiation: { mode: "auto" }, listMaxPages: 1000,
770
+ });
771
+ const transport = connection.kind === "http"
772
+ ? new sdk.StreamableHTTPClientTransport(connection.url, connection.options)
773
+ : new (await import("@modelcontextprotocol/client/stdio")).StdioClientTransport(connection.params);
774
+ return { client, transport };
775
+ }
776
+ async function readModernCatalog(client, signal, timeout) {
777
+ if (!client.getServerCapabilities()?.tools)
778
+ return { tools: [] };
779
+ // Explicit pages enforce cursor and size limits before acquiring the next page.
780
+ const deadline = AbortSignal.any([signal, AbortSignal.timeout(timeout)]);
781
+ const catalog = await collectToolCatalog(cursor => client.request({
782
+ method: "tools/list", ...(cursor === undefined ? {} : { params: { cursor } }),
783
+ }, { signal: deadline, timeout }));
784
+ if (client.getProtocolEra() === "modern")
785
+ catalog.tools = catalog.tools.filter(tool => validMcpHeaderSchema(tool.inputSchema));
786
+ return catalog;
787
+ }
788
+ async function modernDiscovery(p, signal, timeout) {
789
+ const { client, transport } = await modernConnection(p);
790
+ try {
791
+ await client.connect(transport, { signal, timeout });
792
+ const catalog = p.command === "catalog" || p.flags["with-tools"]
793
+ ? await readModernCatalog(client, signal, timeout) : undefined;
794
+ if (p.command === "catalog")
795
+ return catalog;
796
+ const discover = client.getDiscoverResult();
797
+ const version = client.getNegotiatedProtocolVersion();
798
+ return {
799
+ format: "toolsplice-discovery", formatVersion: 1,
800
+ method: discover ? "server/discover" : "initialize", negotiatedVersion: version,
801
+ supportedVersions: discover?.supportedVersions ?? [version],
802
+ serverInfo: client.getServerVersion() ?? null, capabilities: client.getServerCapabilities() ?? {},
803
+ ...catalog, ...(discover ? { ttlMs: discover.ttlMs, cacheScope: discover.cacheScope } : {}),
804
+ };
805
+ }
806
+ finally {
807
+ await client.close().catch(() => { });
808
+ }
809
+ }
810
+ /** One CLI-owned, acknowledged subscription. A changed list is a level trigger. */
811
+ async function followCatalogImpact(p) {
812
+ class SubscriptionError extends Error {
813
+ }
814
+ const allowed = new Set(["follow", "max-reports", "url", "bearer-env", "upstream-cwd", "timeout", "json"]);
815
+ const side = str(p.flags.follow);
816
+ if (p.positional.length !== 1 || (side !== "source" && side !== "target") ||
817
+ Object.keys(p.flags).some(key => !allowed.has(key)))
818
+ throw new Error("impact --follow needs a suite, source or target, and an upstream connection.");
819
+ const limit = integer(p.flags, "max-reports", Number.MAX_SAFE_INTEGER);
820
+ const timeout = integer(p.flags, "timeout", 30_000);
821
+ if (timeout > 2_147_483_647)
822
+ throw new Error("--timeout exceeds the supported timer range.");
823
+ const suite = readSuite(p.positional[0]);
824
+ const { client, transport } = await modernConnection(p);
825
+ const stop = new AbortController();
826
+ const cancel = () => stop.abort();
827
+ process.once("SIGINT", cancel);
828
+ process.once("SIGTERM", cancel);
829
+ let pending = false;
830
+ let ended = false;
831
+ let wake;
832
+ client.setNotificationHandler("notifications/tools/list_changed", () => { pending = true; wake?.(); });
833
+ try {
834
+ await client.connect(transport, { signal: stop.signal, timeout });
835
+ if (!client.getServerCapabilities()?.tools?.listChanged || client.getProtocolEra() !== "modern")
836
+ throw new SubscriptionError("This endpoint needs modern tools.listChanged support. Capture a catalog for a one-time impact check.");
837
+ const sub = await client.listen({ toolsListChanged: true }, { signal: stop.signal, timeout });
838
+ try {
839
+ if (!sub.honoredFilter.toolsListChanged)
840
+ throw new SubscriptionError("The server declined tools list changes.");
841
+ // Attach exactly once. A race with a fresh sub.closed.then() per report retains waiters indefinitely.
842
+ void sub.closed.then(() => { ended = true; wake?.(); });
843
+ for (let index = 0; index < limit; index++) {
844
+ if (index > 0 && !pending && !ended)
845
+ await new Promise(resolve => { wake = resolve; });
846
+ wake = undefined;
847
+ if (stop.signal.aborted)
848
+ return;
849
+ if (ended && !pending)
850
+ throw new SubscriptionError("Catalog subscription ended. Rerun to subscribe and check the current catalog.");
851
+ pending = false;
852
+ const candidate = await readModernCatalog(client, stop.signal, timeout);
853
+ const report = await assessSpliceImpact(suite, side === "source" ? { sourceCatalog: candidate } : { targetCatalog: candidate });
854
+ const reason = index === 0 ? "initial" : "changed";
855
+ if (p.flags.json)
856
+ console.log(JSON.stringify({ reason, side, report }));
857
+ else {
858
+ console.log(reason, side, report.status);
859
+ const evaluated = report.candidate ?? report.baseline;
860
+ for (const c of evaluated.cases.filter(c => !c.passed))
861
+ console.log(JSON.stringify(c.name), c.reason, JSON.stringify(c.actual.issues));
862
+ for (const issue of report.unavailable)
863
+ console.log(issue.side, issue.reason);
864
+ }
865
+ if (report.status !== "fixtures-pass") {
866
+ process.exitCode = 2;
867
+ return;
868
+ }
869
+ }
870
+ }
871
+ finally {
872
+ await sub.close().catch(() => { });
873
+ }
874
+ }
875
+ catch (error) {
876
+ if (!stop.signal.aborted) {
877
+ if (error instanceof SubscriptionError)
878
+ throw error;
879
+ throw new Error("Catalog subscription failed. Check the connection and rerun to check the current catalog.");
880
+ }
881
+ }
882
+ finally {
883
+ process.off("SIGINT", cancel);
884
+ process.off("SIGTERM", cancel);
885
+ await client.close().catch(() => { });
886
+ }
887
+ }
888
+ async function captureCatalog(p) {
889
+ const allowed = ["url", "upstream-cwd", "bearer-env", "timeout", "out", "modern"];
890
+ if (p.command === "discover")
891
+ allowed.push("with-tools");
892
+ if (p.positional.length || Object.keys(p.flags).some(key => !allowed.includes(key)))
893
+ throw new Error("catalog accepts a connection, --timeout and an optional --out file.");
894
+ const timeout = integer(p.flags, "timeout", 30_000);
895
+ if (timeout > 2_147_483_647)
896
+ throw new Error("--timeout exceeds the supported timer range.");
897
+ const client = new Client({ name: "toolsplice-catalog", version: VERSION });
898
+ const stop = new AbortController();
899
+ const signal = AbortSignal.any([stop.signal, AbortSignal.timeout(timeout)]);
900
+ const cancel = () => stop.abort();
901
+ process.once("SIGINT", cancel);
902
+ process.once("SIGTERM", cancel);
903
+ let catalog;
904
+ try {
905
+ if (p.command === "discover" || p.flags.modern) {
906
+ const result = await modernDiscovery(p, signal, timeout);
907
+ const output = JSON.stringify(result);
908
+ if (Buffer.byteLength(output) > JSON_LIMIT)
909
+ throw new Error("Discovery report exceeds 5 MiB.");
910
+ const file = str(p.flags.out);
911
+ if (file === undefined)
912
+ process.stdout.write(output + "\n");
913
+ else {
914
+ writeCatalog(file, output);
915
+ console.log(`Saved ${p.command} to ${JSON.stringify(file)}.`);
916
+ }
917
+ return;
918
+ }
919
+ await client.connect(upstreamTransport(p), { signal, timeout });
920
+ catalog = await collectToolCatalog(cursor => client.request({ method: "tools/list", params: cursor === undefined ? undefined : { cursor } }, ListToolsResultSchema, { signal, timeout }));
921
+ }
922
+ catch (error) {
923
+ if (p.command === "discover" || p.flags.modern) {
924
+ if (error instanceof Error && error.message.startsWith("Install @modelcontextprotocol/client"))
925
+ throw error;
926
+ throw new Error("Modern MCP discovery failed. Check the connection, credentials, output file and timeout.");
927
+ }
928
+ throw new Error("Could not capture a complete MCP tool catalog. Check the connection, credentials, pagination and timeout.");
929
+ }
930
+ finally {
931
+ process.off("SIGINT", cancel);
932
+ process.off("SIGTERM", cancel);
933
+ await client.close().catch(() => { });
934
+ }
935
+ const output = JSON.stringify(catalog);
936
+ const file = str(p.flags.out);
937
+ if (file === undefined)
938
+ process.stdout.write(output + "\n");
939
+ else {
940
+ writeCatalog(file, output);
941
+ console.log(`Saved ${catalog.tools.length} tools to ${JSON.stringify(file)}.`);
942
+ }
943
+ }
944
+ async function testRecording(p) {
945
+ validateFlags(p, ["from-recording", "save-case", "restorations", "json"]);
946
+ if (p.positional.length)
947
+ throw new Error("Choose a suite path or --from-recording.");
948
+ const recording = readLocalJson(String(p.flags["from-recording"]));
949
+ const options = p.flags.restorations ? { restorations: readLocalJson(String(p.flags.restorations)) } : {};
950
+ const suite = suiteFromRecording(recording, options);
951
+ const replay = await replaySpliceRecording(recording, options);
952
+ const report = await runSpliceSuite(suite);
953
+ const matched = replay.matched && report.failed === 0;
954
+ const actual = report.cases[0].actual;
955
+ if (matched && p.flags["save-case"]) {
956
+ const data = JSON.stringify(suite) + "\n";
957
+ if (Buffer.byteLength(data) > JSON_LIMIT)
958
+ throw new Error("Saved suite exceeds 5 MiB.");
959
+ writeFileSync(String(p.flags["save-case"]), data, { mode: 0o600, flag: "wx" });
960
+ }
961
+ const issue = actual.issues[0];
962
+ const detail = issue ? ` (${issue.code} at ${JSON.stringify(issue.path)})` : "";
963
+ const description = matched ? `Reproduced the original ${actual.status === "failed" ? "failure" : "success"}` : "Recording did not reproduce";
964
+ process.stdout.write(p.flags.json ? JSON.stringify({ ...report, recordingMatched: matched }, null, 2) + "\n" :
965
+ `${description}. ${actual.stage ?? actual.status}${detail}. Destination calls in replay: ${actual.targetCalls}.\n`);
966
+ process.exitCode = matched ? 0 : 2;
967
+ }
560
968
  async function main() {
561
969
  const p = parse(process.argv.slice(2));
562
970
  if (p.flags.version) {
@@ -564,7 +972,130 @@ async function main() {
564
972
  return;
565
973
  }
566
974
  if (p.flags.help || ["help", "--help"].includes(p.command)) {
567
- process.stdout.write(USAGE);
975
+ process.stdout.write(USAGE + "\n toolsplice test <suite.json|directory> [--json] [--junit results.xml]\n Run offline regression cases; optional --source-contract/--target-contract candidates.\n");
976
+ return;
977
+ }
978
+ if (p.command === "init" && ["source-catalog", "target-catalog", "source", "target", "bind", "set", "input", "fixture", "fixture-format", "result-path", "result-fields", "each", "max-items"].some(k => k in p.flags))
979
+ return initFromCatalogs(p);
980
+ if (p.command === "evaluate") {
981
+ if (p.flags.ledger !== undefined) {
982
+ validateFlags(p, ["ledger", "json"]);
983
+ const directory = str(p.flags.ledger);
984
+ if (!directory || p.positional.length)
985
+ throw new Error("--ledger needs a checkpoint directory.");
986
+ process.stdout.write(JSON.stringify(readCalibrationLedger(directory), null, 2) + "\n");
987
+ return;
988
+ }
989
+ if (p.flags.init !== undefined) {
990
+ validateFlags(p, ["init"]);
991
+ const target = str(p.flags.init);
992
+ if (!target?.endsWith(".mjs") || p.positional.length)
993
+ throw new Error("Choose a new .mjs driver path.");
994
+ writeCatalog(target, readFileSync(new URL("../examples/route-driver.mjs", import.meta.url), "utf8"));
995
+ process.stdout.write("Created the local evaluation driver.\n");
996
+ return;
997
+ }
998
+ if (p.flags.plan) {
999
+ validateFlags(p, ["driver", "plan", "json"]);
1000
+ const driver = str(p.flags.driver);
1001
+ if (p.positional.length || !driver?.endsWith(".mjs"))
1002
+ throw new Error("--plan needs a trusted --driver local.mjs.");
1003
+ const plan = await executeRouteDriver(driver, "plan");
1004
+ process.stdout.write(JSON.stringify(plan, null, 2) + "\n");
1005
+ return;
1006
+ }
1007
+ validateFlags(p, ["driver", "save-trials", "out", "json", "checkpoint", "retry-incomplete"]);
1008
+ const driver = str(p.flags.driver), saved = str(p.flags["save-trials"]), out = str(p.flags.out);
1009
+ if (driver ? p.positional.length || !driver.endsWith(".mjs") : p.positional.length !== 1 || saved)
1010
+ throw new Error("Pass a trial receipt or an explicit --driver local.mjs.");
1011
+ const checkpoint = str(p.flags.checkpoint), retry = Boolean(p.flags["retry-incomplete"]);
1012
+ if ((p.flags.checkpoint !== undefined && (!checkpoint || !driver)) || (retry && !checkpoint))
1013
+ throw new Error("--checkpoint needs --driver; --retry-incomplete needs --checkpoint.");
1014
+ const outputs = [saved, out].filter((x) => x !== undefined);
1015
+ const targets = outputs.map(x => resolve(realpathSync(dirname(x)), relative(dirname(x), x)));
1016
+ const journal = checkpoint ? (existsSync(checkpoint) ? realpathSync(checkpoint) : resolve(checkpoint)) : undefined;
1017
+ if (journal && targets.some(x => x === journal || x.startsWith(journal + sep)))
1018
+ throw new Error("Choose output paths outside the checkpoint directory.");
1019
+ if (new Set(targets).size !== targets.length || targets.some(x => existsSync(x)))
1020
+ throw new Error("Choose distinct, unused output paths.");
1021
+ const evidence = driver
1022
+ ? await executeRouteDriver(driver, "run", journal, retry)
1023
+ : await readRouteReceipt(p.positional[0]);
1024
+ const report = evaluateRoutes(evidence);
1025
+ if (saved)
1026
+ writeCatalog(saved, JSON.stringify(evidence) + "\n", ROUTE_FILE_LIMIT);
1027
+ if (out)
1028
+ writeCatalog(out, JSON.stringify(report.policy, null, 2) + "\n", ROUTE_FILE_LIMIT);
1029
+ process.stdout.write(p.flags.json ? JSON.stringify(report, null, 2) + "\n"
1030
+ : report.workloads.map(r => [r.workload, r.selected, explainRoute(r)].join(" ")).join("\n") + "\n");
1031
+ return;
1032
+ }
1033
+ if (p.command === "measure") {
1034
+ validateFlags(p, ["json", "restorations"]);
1035
+ if (p.positional.length !== 1)
1036
+ throw new Error("measure needs one successful payload recording.");
1037
+ const report = await measureSpliceRecording(readLocalJson(p.positional[0]), {
1038
+ ...(p.flags.restorations ? { restorations: readLocalJson(String(p.flags.restorations)) } : {}),
1039
+ });
1040
+ process.stdout.write(p.flags.json ? JSON.stringify(report, null, 2) + "\n" :
1041
+ `Direct: ${report.direct.modelToolCalls} model-facing tool calls, ${report.direct.toolResultBytes} result bytes. Composite: 1 model-facing tool call, ${report.composite.toolResultBytes} result bytes. Recorded upstream calls: ${report.recordedUpstreamCalls.source} source, ${report.recordedUpstreamCalls.target} target.\n`);
1042
+ return;
1043
+ }
1044
+ if (p.command === "catalog" || p.command === "discover")
1045
+ return captureCatalog(p);
1046
+ if (p.command === "impact" && p.flags.follow !== undefined)
1047
+ return followCatalogImpact(p);
1048
+ if (p.command === "impact") {
1049
+ validateFlags(p, ["source-contract", "target-contract", "source-catalog", "target-catalog", "candidate-result", "case", "json"]);
1050
+ if (p.positional.length !== 1)
1051
+ throw new Error("impact needs one suite file or project directory.");
1052
+ const suite = readSuite(p.positional[0]);
1053
+ let caseName = str(p.flags.case);
1054
+ const sample = str(p.flags["candidate-result"]);
1055
+ if (caseName !== undefined && !sample)
1056
+ throw new Error("--case requires --candidate-result.");
1057
+ if (sample && caseName === undefined) {
1058
+ if (!Array.isArray(suite.cases) || suite.cases.length !== 1 || typeof suite.cases[0]?.name !== "string")
1059
+ throw new Error("Use --case <name> to assign the candidate response to one suite case.");
1060
+ caseName = suite.cases[0].name;
1061
+ }
1062
+ const report = await assessSpliceImpact(suite, {
1063
+ ...(p.flags["source-catalog"] ? { sourceCatalog: readLocalJson(String(p.flags["source-catalog"])) } : {}),
1064
+ ...(p.flags["target-catalog"] ? { targetCatalog: readLocalJson(String(p.flags["target-catalog"])) } : {}),
1065
+ ...(p.flags["source-contract"] ? { sourceContract: parseContractSnapshot(readLocalJson(String(p.flags["source-contract"]))) } : {}),
1066
+ ...(p.flags["target-contract"] ? { targetContract: parseContractSnapshot(readLocalJson(String(p.flags["target-contract"]))) } : {}),
1067
+ ...(sample && caseName !== undefined ? { sourceResults: { [caseName]: readLocalJson(sample) } } : {}),
1068
+ });
1069
+ if (p.flags.json)
1070
+ process.stdout.write(JSON.stringify(report, null, 2) + "\n");
1071
+ else {
1072
+ const evaluated = report.candidate ?? report.baseline;
1073
+ console.log(`${report.status}. Baseline: ${report.baseline.passed}/${report.baseline.cases.length} passed. Candidate: ${report.candidate ? report.candidate.passed + "/" + report.candidate.cases.length + " passed" : "not run"}.`);
1074
+ for (const issue of report.unavailable)
1075
+ console.log(issue.side, issue.reason);
1076
+ for (const c of evaluated.cases.filter(c => !c.passed))
1077
+ console.log(JSON.stringify(c.name), c.reason, JSON.stringify(c.actual));
1078
+ }
1079
+ process.exitCode = report.status === "fixtures-pass" ? 0 : 2;
1080
+ return;
1081
+ }
1082
+ if (p.command === "test" && p.flags["from-recording"])
1083
+ return testRecording(p);
1084
+ if (p.command === "test") {
1085
+ const allowed = new Set(["json", "junit", "source-contract", "target-contract", "allow-review"]);
1086
+ if (p.positional.length !== 1 || p.upstream.length || Object.keys(p.flags).some(k => !allowed.has(k)))
1087
+ throw new Error("test needs one suite file/directory and only test/report/candidate options.");
1088
+ const suite = readSuite(p.positional[0]);
1089
+ const report = await runSpliceSuite(suite, {
1090
+ ...(p.flags["source-contract"] ? { sourceContract: parseContractSnapshot(readLocalJson(String(p.flags["source-contract"]))) } : {}),
1091
+ ...(p.flags["target-contract"] ? { targetContract: parseContractSnapshot(readLocalJson(String(p.flags["target-contract"]))) } : {}),
1092
+ ...(p.flags["allow-review"] ? { allowReview: true } : {}),
1093
+ });
1094
+ if (p.flags.junit)
1095
+ writeFileSync(String(p.flags.junit), formatTestJUnit(report), { flag: "wx", mode: 0o600 });
1096
+ process.stdout.write(p.flags.json ? JSON.stringify(report, null, 2) + "\n" :
1097
+ `${report.passed} passed, ${report.failed} failed; zero live tool/network calls.\n` + report.cases.filter(c => !c.passed).map(c => `${JSON.stringify(c.name)}: ${c.reason}; ${JSON.stringify(c.actual)}\n`).join(""));
1098
+ process.exitCode = report.failed ? 2 : 0;
568
1099
  return;
569
1100
  }
570
1101
  const examples = (str(p.flags.examples) ?? "none");
@@ -0,0 +1,6 @@
1
+ import type { ToolCaller } from "./execution.js";
2
+ /** Share identical concurrent reads on one authorized caller for a single run. */
3
+ export declare function coalesceReads(caller: ToolCaller, { tools, maxPending }: {
4
+ tools: readonly string[];
5
+ maxPending?: number;
6
+ }): ToolCaller;
@@ -0,0 +1,33 @@
1
+ import { copyJson, jsonFingerprint } from "./workflow-json.js";
2
+ /** Share identical concurrent reads on one authorized caller for a single run. */
3
+ export function coalesceReads(caller, { tools, maxPending = 64 }) {
4
+ if (typeof caller !== "function" ||
5
+ !Array.isArray(tools) ||
6
+ !tools.length ||
7
+ tools.some((n) => typeof n !== "string" || !n))
8
+ throw new TypeError("Specify a connected caller and its read-only tool names.");
9
+ if (!Number.isSafeInteger(maxPending) || maxPending < 1)
10
+ throw new RangeError("maxPending must be a positive integer.");
11
+ const allowed = new Set(tools);
12
+ const pending = new Map();
13
+ return async (request, options) => {
14
+ if (!allowed.has(request.name) ||
15
+ (options && Object.values(options).some((v) => v !== undefined)) ||
16
+ Object.keys(request).some((k) => k !== "arguments" && k !== "name"))
17
+ return caller(request, options);
18
+ const snapshot = copyJson(request);
19
+ const key = jsonFingerprint(snapshot);
20
+ let flight = pending.get(key);
21
+ if (!flight) {
22
+ if (pending.size >= maxPending)
23
+ return caller(snapshot, options);
24
+ flight = Promise.resolve().then(() => caller(snapshot, options));
25
+ pending.set(key, flight);
26
+ const finished = () => {
27
+ pending.delete(key);
28
+ };
29
+ void flight.then(finished, finished);
30
+ }
31
+ return structuredClone(await flight);
32
+ };
33
+ }