toolsplice 0.0.1 → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/README.md +62 -330
  2. package/dist/abortable.d.ts +6 -0
  3. package/dist/abortable.js +50 -0
  4. package/dist/adaptive-read.d.ts +50 -0
  5. package/dist/adaptive-read.js +780 -0
  6. package/dist/answer-wait.d.ts +7 -0
  7. package/dist/answer-wait.js +45 -0
  8. package/dist/cache-reads.d.ts +18 -0
  9. package/dist/cache-reads.js +89 -0
  10. package/dist/calibration-ledger.d.ts +37 -0
  11. package/dist/calibration-ledger.js +148 -0
  12. package/dist/calibration-marker.d.ts +4 -0
  13. package/dist/calibration-marker.js +77 -0
  14. package/dist/catalog-setup.d.ts +33 -0
  15. package/dist/catalog-setup.js +89 -0
  16. package/dist/catalog.d.ts +10 -0
  17. package/dist/catalog.js +42 -0
  18. package/dist/checkpoint-files.d.ts +15 -0
  19. package/dist/checkpoint-files.js +99 -0
  20. package/dist/cli.js +545 -14
  21. package/dist/coalesce-reads.d.ts +6 -0
  22. package/dist/coalesce-reads.js +33 -0
  23. package/dist/contract-caller.d.ts +2 -1
  24. package/dist/contract-caller.js +35 -16
  25. package/dist/contract-schema.d.ts +3 -1
  26. package/dist/contract-schema.js +34 -4
  27. package/dist/contracts.d.ts +1 -0
  28. package/dist/contracts.js +5 -1
  29. package/dist/core.d.ts +31 -1
  30. package/dist/core.js +27 -0
  31. package/dist/db-final-answer.d.ts +9 -0
  32. package/dist/db-final-answer.js +62 -0
  33. package/dist/define.d.ts +78 -0
  34. package/dist/define.js +14 -0
  35. package/dist/final-answer-stores.d.ts +71 -0
  36. package/dist/final-answer-stores.js +72 -0
  37. package/dist/final-answer.d.ts +32 -0
  38. package/dist/final-answer.js +104 -0
  39. package/dist/impact.d.ts +48 -0
  40. package/dist/impact.js +71 -0
  41. package/dist/index.d.ts +32 -1
  42. package/dist/index.js +28 -0
  43. package/dist/local-tool.d.ts +18 -0
  44. package/dist/local-tool.js +32 -0
  45. package/dist/mcp-apps.d.ts +53 -0
  46. package/dist/mcp-apps.js +32 -0
  47. package/dist/mcp-event-delivery.d.ts +98 -0
  48. package/dist/mcp-event-delivery.js +211 -0
  49. package/dist/mcp-extensions.d.ts +46 -0
  50. package/dist/mcp-extensions.js +200 -0
  51. package/dist/mcp-peer.d.ts +45 -0
  52. package/dist/mcp-peer.js +207 -0
  53. package/dist/mcp-server-card.d.ts +21 -0
  54. package/dist/mcp-server-card.js +54 -0
  55. package/dist/page-checkpoint.d.ts +71 -0
  56. package/dist/page-checkpoint.js +286 -0
  57. package/dist/page-read-gate.d.ts +15 -0
  58. package/dist/page-read-gate.js +48 -0
  59. package/dist/pattern.d.ts +1 -0
  60. package/dist/pattern.js +27 -5
  61. package/dist/probe.js +6 -19
  62. package/dist/read-pages.d.ts +25 -0
  63. package/dist/read-pages.js +85 -0
  64. package/dist/read-policy.d.ts +6 -0
  65. package/dist/read-policy.js +16 -0
  66. package/dist/read-steps.d.ts +12 -0
  67. package/dist/read-steps.js +36 -0
  68. package/dist/result-session.d.ts +109 -0
  69. package/dist/result-session.js +620 -0
  70. package/dist/route-checkpoint.d.ts +3 -0
  71. package/dist/route-checkpoint.js +80 -0
  72. package/dist/route-driver-cli.d.ts +3 -0
  73. package/dist/route-driver-cli.js +43 -0
  74. package/dist/route-evaluation.d.ts +141 -0
  75. package/dist/route-evaluation.js +329 -0
  76. package/dist/row-groups.d.ts +17 -0
  77. package/dist/row-groups.js +79 -0
  78. package/dist/row-query.d.ts +62 -0
  79. package/dist/row-query.js +172 -0
  80. package/dist/rules.d.ts +30 -0
  81. package/dist/rules.js +72 -0
  82. package/dist/run-diagnostics.d.ts +75 -0
  83. package/dist/run-diagnostics.js +212 -0
  84. package/dist/search-fetch.d.ts +50 -0
  85. package/dist/search-fetch.js +264 -0
  86. package/dist/skill-files.d.ts +9 -0
  87. package/dist/skill-files.js +49 -0
  88. package/dist/splice-diagnostics.d.ts +4 -0
  89. package/dist/splice-diagnostics.js +24 -16
  90. package/dist/splice-measure.d.ts +33 -0
  91. package/dist/splice-measure.js +55 -0
  92. package/dist/splice-project.d.ts +12 -6
  93. package/dist/splice-project.js +72 -20
  94. package/dist/splice-recording.d.ts +29 -2
  95. package/dist/splice-recording.js +22 -5
  96. package/dist/splice.d.ts +98 -1
  97. package/dist/splice.js +225 -27
  98. package/dist/sqlite-checkpoint-store.d.ts +5 -0
  99. package/dist/sqlite-checkpoint-store.js +91 -0
  100. package/dist/sqlite-checkpoint-worker.d.ts +1 -0
  101. package/dist/sqlite-checkpoint-worker.js +115 -0
  102. package/dist/test-difference.d.ts +13 -0
  103. package/dist/test-difference.js +42 -0
  104. package/dist/testing.d.ts +122 -0
  105. package/dist/testing.js +261 -0
  106. package/dist/text-pages.d.ts +24 -0
  107. package/dist/text-pages.js +36 -0
  108. package/dist/tool-discovery.d.ts +59 -0
  109. package/dist/tool-discovery.js +136 -0
  110. package/dist/unevaluated.d.ts +7 -0
  111. package/dist/unevaluated.js +156 -0
  112. package/dist/v2.js +25 -8
  113. package/dist/version.d.ts +1 -1
  114. package/dist/version.js +1 -1
  115. package/dist/workflow-json.js +1 -1
  116. package/docs/AGENT-FRAMEWORKS.md +431 -0
  117. package/docs/BENCHMARKS.md +43 -0
  118. package/docs/INTEGRATION-QUICKSTART.md +859 -0
  119. package/docs/LEARNING-AND-STORAGE.md +393 -0
  120. package/docs/MCP.md +204 -0
  121. package/docs/PROJECTS-AND-UPGRADES.md +67 -9
  122. package/docs/PYTHON-REFERENCE.md +348 -0
  123. package/docs/PYTHON.md +120 -0
  124. package/docs/RECORDING-AND-CORRECTIONS.md +30 -1
  125. package/docs/TESTING.md +259 -0
  126. package/examples/mcp-app/build.mjs +11 -0
  127. package/examples/mcp-app/view.mjs +22 -0
  128. package/examples/quickstart.mjs +43 -0
  129. package/examples/route-driver.mjs +67 -0
  130. package/integrations/ai.d.mts +36 -0
  131. package/integrations/ai.mjs +178 -0
  132. package/integrations/call-options.mjs +9 -0
  133. package/integrations/langchain.d.mts +31 -0
  134. package/integrations/langchain.mjs +114 -0
  135. package/integrations/managed.mjs +154 -0
  136. package/integrations/types.d.mts +13 -0
  137. package/package.json +47 -3
@@ -0,0 +1,42 @@
1
+ import { describeBinding } from "./splice-diagnostics.js";
2
+ import { escapePointer, jsonObject } from "./workflow-json.js";
3
+ /** Inputs are detached JSON from the suite and the completed mock run. */
4
+ export function firstDifference(expected, actual, path = "") {
5
+ if (expected === actual)
6
+ return;
7
+ if (actual === undefined)
8
+ return { path, kind: "missing" };
9
+ if (expected === undefined)
10
+ return { path, kind: "extra" };
11
+ if (Array.isArray(expected) && Array.isArray(actual)) {
12
+ if (expected.length !== actual.length)
13
+ return { path, kind: "length", expectedLength: expected.length, actualLength: actual.length };
14
+ for (let i = 0; i < expected.length; i++) {
15
+ const diff = firstDifference(expected[i], actual[i], path + "/" + i);
16
+ if (diff)
17
+ return diff;
18
+ }
19
+ return;
20
+ }
21
+ if (jsonObject(expected) && jsonObject(actual)) {
22
+ const keys = new Set([...Object.keys(expected), ...Object.keys(actual)]);
23
+ for (const key of [...keys].sort()) {
24
+ const child = path + "/" + escapePointer(key);
25
+ const diff = firstDifference(Object.hasOwn(expected, key) ? expected[key] : undefined, Object.hasOwn(actual, key) ? actual[key] : undefined, child);
26
+ if (diff)
27
+ return child.length > 2048 ? { ...diff, path, pathTruncated: true } : diff;
28
+ }
29
+ return;
30
+ }
31
+ const kind = (v) => v === null ? "null" : Array.isArray(v) ? "array" : typeof v;
32
+ return { path, kind: kind(expected) === kind(actual) ? "value" : "type" };
33
+ }
34
+ export function attributeDifference(diff, plan) {
35
+ const row = /^\/(\d+)(\/.*)?$/s.exec(diff.path);
36
+ if (!row)
37
+ return diff;
38
+ const path = row[2] ?? "";
39
+ const fields = plan.bindings.flatMap((binding, index) => path === binding.to || path.startsWith(binding.to + "/") || binding.to.startsWith(path + "/")
40
+ ? [describeBinding(plan, index, Number(row[1]))] : []);
41
+ return { ...diff, fields };
42
+ }
@@ -0,0 +1,122 @@
1
+ import { type ReadPolicy } from "./read-policy.js";
2
+ import { type TestDifference } from "./test-difference.js";
3
+ import type { ToolCaller } from "./execution.js";
4
+ import type { ToolResultLike } from "./extract.js";
5
+ import { SpliceError, type SpliceSpec } from "./splice.js";
6
+ import { type ContractSnapshot } from "./contracts.js";
7
+ import { type SpliceRecording } from "./splice-recording.js";
8
+ export interface MockStep {
9
+ name: string;
10
+ /** Omit to accept any JSON object. Supplied arguments must match exactly. */
11
+ arguments?: Record<string, unknown>;
12
+ result?: ToolResultLike;
13
+ throws?: true;
14
+ delayMs?: number;
15
+ }
16
+ export declare class MockCallError extends Error {
17
+ constructor();
18
+ }
19
+ export declare function createMockCaller(input: MockStep[]): ToolCaller & {
20
+ getCalls: () => {
21
+ name: string;
22
+ arguments: Record<string, unknown>;
23
+ }[];
24
+ stats: () => {
25
+ attempts: number;
26
+ consumed: number;
27
+ remaining: number;
28
+ mismatch: boolean;
29
+ };
30
+ assertDone: () => void;
31
+ };
32
+ /** Feed an application's own workflow with captured results, preserving cross-endpoint order. */
33
+ export declare function mockRecordedCalls(input: SpliceRecording | string, options?: {
34
+ restorations?: Record<string, unknown>;
35
+ }): {
36
+ source: ToolCaller;
37
+ target: ToolCaller;
38
+ assertDone: () => void;
39
+ stats: () => {
40
+ attempts: number;
41
+ consumed: number;
42
+ remaining: number;
43
+ mismatch: boolean;
44
+ };
45
+ };
46
+ export interface SpliceTestCase {
47
+ /** Dry-run the saved source output and compare mapped arguments without target fixtures. */
48
+ mappingOnly?: true;
49
+ readPolicy?: ReadPolicy;
50
+ /** Zero-based target attempts throwing during a recorded read wave. */
51
+ targetFailures?: number[];
52
+ /** Simulate a generic exception from the source or the last target attempt. */
53
+ transportFailure?: "source" | "target";
54
+ name: string;
55
+ input: Record<string, unknown>;
56
+ context?: unknown;
57
+ /** Raw MCP result, including structuredContent/content/isError. */
58
+ sourceResult: ToolResultLike;
59
+ targetResults?: ToolResultLike[];
60
+ expect: {
61
+ status: "succeeded" | "failed";
62
+ targetCalls: number;
63
+ sourceCalls?: number;
64
+ completedTargets?: number;
65
+ stage?: SpliceError["stage"];
66
+ code?: string;
67
+ path?: string;
68
+ arguments?: Record<string, unknown>[];
69
+ results?: unknown[];
70
+ resultFingerprint?: string;
71
+ };
72
+ }
73
+ export interface SpliceSuite {
74
+ format: "toolsplice-suite";
75
+ formatVersion: 1;
76
+ plan: SpliceSpec;
77
+ sourceContract: ContractSnapshot;
78
+ targetContract: ContractSnapshot;
79
+ allowReview?: boolean;
80
+ cases: SpliceTestCase[];
81
+ }
82
+ export declare function parseSpliceSuite(input: unknown): SpliceSuite;
83
+ export declare function runSpliceSuite(input: unknown, options?: {
84
+ sourceContract?: ContractSnapshot;
85
+ targetContract?: ContractSnapshot;
86
+ allowReview?: boolean;
87
+ }): Promise<{
88
+ format: "toolsplice-test-report";
89
+ formatVersion: number;
90
+ passed: number;
91
+ failed: number;
92
+ cases: {
93
+ name: string;
94
+ passed: boolean;
95
+ reason?: string | undefined;
96
+ actual: {
97
+ difference?: TestDifference;
98
+ completedTargets?: number;
99
+ status: string;
100
+ stage?: string;
101
+ issues: {
102
+ code: string;
103
+ path: string;
104
+ }[];
105
+ targetCalls: number;
106
+ sourceCalls: number;
107
+ };
108
+ }[];
109
+ fingerprints: {
110
+ source: string;
111
+ target: string;
112
+ plan: string;
113
+ };
114
+ networkCalls: number;
115
+ liveToolCalls: number;
116
+ }>;
117
+ export type SpliceTestReport = Awaited<ReturnType<typeof runSpliceSuite>>;
118
+ export declare function suiteFromRecording(input: SpliceRecording | string, options?: {
119
+ name?: string;
120
+ restorations?: Record<string, unknown>;
121
+ }): SpliceSuite;
122
+ export declare function formatTestJUnit(report: SpliceTestReport): string;
@@ -0,0 +1,261 @@
1
+ // Framework-independent test helpers. No provider connections or process execution.
2
+ import { parseReadPolicy } from "./read-policy.js";
3
+ import { firstDifference, attributeDifference } from "./test-difference.js";
4
+ import { catalogFixture } from "./catalog-setup.js";
5
+ import { copyJson, jsonObject, jsonFingerprint, parseWorkflowJson } from "./workflow-json.js";
6
+ import { prepareSplice, parseSpliceSpec, SpliceError } from "./splice.js";
7
+ import { parseContractSnapshot } from "./contracts.js";
8
+ import { loadReplayFixture } from "./splice-recording.js";
9
+ export class MockCallError extends Error {
10
+ constructor() { super("Mock call did not match the fixture or fixture simulates failure."); this.name = "MockCallError"; }
11
+ }
12
+ export function createMockCaller(input) {
13
+ const steps = copyJson(input);
14
+ if (!Array.isArray(steps) || steps.length > 1000 || steps.some(s => !jsonObject(s) ||
15
+ Object.keys(s).some(k => !["name", "arguments", "result", "throws", "delayMs"].includes(k)) ||
16
+ typeof s.name !== "string" || !s.name ||
17
+ (s.arguments !== undefined && !jsonObject(s.arguments)) ||
18
+ Number(Object.hasOwn(s, "result")) + Number(s.throws === true) !== 1 ||
19
+ (Object.hasOwn(s, "throws") && s.throws !== true) ||
20
+ (s.result !== undefined && !jsonObject(s.result)) ||
21
+ (s.delayMs !== undefined && (!Number.isSafeInteger(s.delayMs) || s.delayMs < 0 || s.delayMs > 1000))))
22
+ throw new Error("Invalid mock steps (maximum 1000 calls, delays 0–1000 ms).");
23
+ let consumed = 0, mismatch = false, attempts = 0, callBytes = 2;
24
+ const calls = [];
25
+ const call = async (request, options) => {
26
+ options?.signal?.throwIfAborted();
27
+ attempts++;
28
+ // Unexpected calls fail even if the application catches the exception.
29
+ const expected = steps[consumed];
30
+ try {
31
+ const saved = copyJson(request);
32
+ if (!jsonObject(saved) || typeof saved.name !== "string" || !jsonObject(saved.arguments))
33
+ throw new MockCallError();
34
+ const bytes = Buffer.byteLength(JSON.stringify(saved)) + (calls.length ? 1 : 0);
35
+ if (calls.length >= 1001 || callBytes + bytes > 5 * 1024 * 1024)
36
+ throw new MockCallError();
37
+ calls.push(saved);
38
+ callBytes += bytes;
39
+ }
40
+ catch {
41
+ mismatch = true;
42
+ throw new MockCallError();
43
+ }
44
+ if (!expected || expected.name !== request.name || !jsonObject(request.arguments) ||
45
+ (expected.arguments !== undefined && jsonFingerprint(request.arguments) !== jsonFingerprint(expected.arguments))) {
46
+ mismatch = true;
47
+ throw new MockCallError();
48
+ }
49
+ consumed++;
50
+ if (expected.delayMs) {
51
+ const { setTimeout } = await import("node:timers/promises");
52
+ await setTimeout(expected.delayMs, undefined, { signal: options?.signal });
53
+ }
54
+ if (expected.throws)
55
+ throw new MockCallError();
56
+ return copyJson(expected.result);
57
+ };
58
+ return Object.assign(call, {
59
+ getCalls: () => copyJson(calls),
60
+ stats: () => ({ attempts, consumed, remaining: steps.length - consumed, mismatch }),
61
+ assertDone: () => { if (mismatch || consumed !== steps.length)
62
+ throw new MockCallError(); },
63
+ });
64
+ }
65
+ /** Feed an application's own workflow with captured results, preserving cross-endpoint order. */
66
+ export function mockRecordedCalls(input, options = {}) {
67
+ const { recording } = loadReplayFixture(input, options);
68
+ if (recording.cancellationObserved)
69
+ throw new Error("Recorded cancellation timing cannot be simulated.");
70
+ const mock = createMockCaller(recording.calls.map(c => {
71
+ if (!c.arguments || (c.outcome === "returned" && !c.result))
72
+ throw new Error("Recording lacks captured call payloads.");
73
+ return { name: `${c.side}:${c.name}`, arguments: c.arguments,
74
+ ...(c.outcome === "threw" ? { throws: true } : { result: c.result }) };
75
+ }));
76
+ const caller = (side) => (request, options) => mock({ ...request, name: `${side}:${request.name}` }, options);
77
+ return { source: caller("source"), target: caller("target"), assertDone: mock.assertDone, stats: mock.stats };
78
+ }
79
+ export function parseSpliceSuite(input) {
80
+ const s = parseWorkflowJson(input);
81
+ if (!jsonObject(s) || Object.keys(s).some(k => !["format", "formatVersion", "plan", "sourceContract", "targetContract", "allowReview", "cases"].includes(k)) ||
82
+ s.format !== "toolsplice-suite" || s.formatVersion !== 1 || (s.allowReview !== undefined && typeof s.allowReview !== "boolean") ||
83
+ !Array.isArray(s.cases) || !s.cases.length || s.cases.length > 100)
84
+ throw new Error("Expected a toolsplice-suite v1 with 1–100 cases.");
85
+ parseSpliceSpec(s.plan);
86
+ parseContractSnapshot(s.sourceContract);
87
+ parseContractSnapshot(s.targetContract);
88
+ const names = new Set();
89
+ let totalCalls = 0;
90
+ for (const c of s.cases) {
91
+ if (!jsonObject(c) || Object.keys(c).some(k => !["name", "mappingOnly", "transportFailure", "readPolicy", "targetFailures", "input", "context", "sourceResult", "targetResults", "expect"].includes(k)) ||
92
+ typeof c.name !== "string" || !c.name || c.name.length > 160 || names.has(c.name) || !jsonObject(c.input) ||
93
+ (!jsonObject(c.sourceResult) && !(c.sourceResult === undefined && c.transportFailure === "source")) ||
94
+ (c.targetResults !== undefined && (!Array.isArray(c.targetResults) || c.targetResults.some(r => !jsonObject(r)))) || !jsonObject(c.expect))
95
+ throw new Error("Invalid test case or duplicate case name.");
96
+ names.add(c.name);
97
+ const e = c.expect;
98
+ if (c.readPolicy !== undefined) {
99
+ parseReadPolicy(c.readPolicy);
100
+ if (c.mappingOnly)
101
+ throw new Error("A mapping-only case cannot schedule reads.");
102
+ }
103
+ if (c.targetFailures !== undefined) {
104
+ const indices = c.targetFailures;
105
+ if (!c.readPolicy || c.transportFailure !== undefined || e.status !== "failed" || e.stage !== "target" ||
106
+ !Array.isArray(indices) || !indices.length || indices.length > 1000 ||
107
+ indices.some((v, i) => !Number.isSafeInteger(v) || v < 0 || v >= Number(e.targetCalls) || (i > 0 && v <= indices[i - 1])))
108
+ throw new Error("Read failures must name ordered distinct target attempt indices.");
109
+ }
110
+ if (c.transportFailure !== undefined) {
111
+ if (!(c.transportFailure === "source" || c.transportFailure === "target") || c.mappingOnly ||
112
+ e.status !== "failed" || e.stage !== c.transportFailure ||
113
+ (c.transportFailure === "source" && (e.targetCalls !== 0 || Object.keys(c.sourceResult ?? {}).length)) ||
114
+ (c.transportFailure === "target" && Number(e.targetCalls) < 1))
115
+ throw new Error("A scripted transport exception needs a matching failure stage and attempt count.");
116
+ if (c.transportFailure === "source")
117
+ c.sourceResult = {};
118
+ }
119
+ if (Object.hasOwn(c, "mappingOnly") && (c.mappingOnly !== true || e.status !== "succeeded" ||
120
+ e.targetCalls !== 0 || !Array.isArray(e.arguments) || e.arguments.length > 1000 ||
121
+ Object.keys(c.input).length || c.targetResults !== undefined || e.results !== undefined || e.resultFingerprint !== undefined))
122
+ throw new Error("A mapping-only case needs exact arguments and no tool calls or input.");
123
+ if (Object.keys(e).some(k => !["status", "targetCalls", "sourceCalls", "completedTargets", "stage", "code", "path", "arguments", "results", "resultFingerprint"].includes(k)) ||
124
+ !["succeeded", "failed"].includes(String(e.status)) || !Number.isSafeInteger(e.targetCalls) || Number(e.targetCalls) < 0 || Number(e.targetCalls) > 1000 ||
125
+ (e.sourceCalls !== undefined && !(e.sourceCalls === 0 || e.sourceCalls === 1)) ||
126
+ (e.completedTargets !== undefined && (e.status !== "failed" || !Number.isSafeInteger(e.completedTargets) || Number(e.completedTargets) < 0 || Number(e.completedTargets) > Number(e.targetCalls))) ||
127
+ (e.status === "failed" && !["preflight", "context", "source", "mapping", "target"].includes(String(e.stage))) ||
128
+ (e.status === "succeeded" && ["stage", "code", "path"].some(k => k in e)) ||
129
+ (e.code !== undefined && typeof e.code !== "string") || (e.path !== undefined && typeof e.path !== "string") ||
130
+ (e.arguments !== undefined && (!Array.isArray(e.arguments) || (!c.mappingOnly && e.arguments.length !== e.targetCalls) || e.arguments.some(a => !jsonObject(a)))) ||
131
+ (e.resultFingerprint !== undefined && (typeof e.resultFingerprint !== "string" || !/^[a-f0-9]{64}$/.test(e.resultFingerprint) ||
132
+ e.status !== "succeeded" || e.results !== undefined)) ||
133
+ (e.results !== undefined && (!Array.isArray(e.results) || e.status !== "succeeded")))
134
+ throw new Error("Invalid expected outcome; failures require a stage and all cases require targetCalls.");
135
+ const returned = Number(e.targetCalls) - (c.transportFailure === "target" ? 1 : (c.targetFailures?.length ?? 0));
136
+ if ((c.targetResults?.length ?? 0) !== returned)
137
+ throw new Error("Provide one target result per returning target call.");
138
+ totalCalls += Number(e.targetCalls);
139
+ }
140
+ if (totalCalls > 1000)
141
+ throw new Error("Suite exceeds 1000 target calls.");
142
+ return s;
143
+ }
144
+ export async function runSpliceSuite(input, options = {}) {
145
+ const suite = parseSpliceSuite(input);
146
+ if (options.allowReview !== undefined && typeof options.allowReview !== "boolean")
147
+ throw new Error("allowReview must be boolean.");
148
+ const prepared = prepareSplice(suite.plan, options.sourceContract ?? suite.sourceContract, options.targetContract ?? suite.targetContract);
149
+ const cases = [];
150
+ for (const c of suite.cases) {
151
+ const source = createMockCaller([{ name: suite.plan.source.tool, arguments: c.input,
152
+ ...(c.transportFailure === "source" ? { throws: true } : { result: c.sourceResult }) }]);
153
+ const failures = new Set(c.targetFailures ?? (c.transportFailure === "target" ? [c.expect.targetCalls - 1] : []));
154
+ let returned = 0;
155
+ const steps = Array.from({ length: c.expect.targetCalls }, (_, index) => ({
156
+ name: suite.plan.target.tool,
157
+ ...(failures.has(index) ? { throws: true } : { result: c.targetResults[returned++] }),
158
+ }));
159
+ const target = createMockCaller(steps);
160
+ const actual = { status: "succeeded", issues: [], targetCalls: 0, sourceCalls: 0 };
161
+ let result;
162
+ let mapped;
163
+ try {
164
+ if (c.mappingOnly) {
165
+ const decoded = catalogFixture(c.sourceResult, "mcp");
166
+ mapped = await prepared.mapOutput(decoded, Object.hasOwn(c, "context") ? { context: c.context } : {});
167
+ }
168
+ else {
169
+ const execute = c.readPolicy ? prepared.runReads : prepared.run;
170
+ result = await execute(source, target, c.input, { ...c.readPolicy, allowReview: options.allowReview ?? suite.allowReview ?? false,
171
+ ...(Object.hasOwn(c, "context") ? { context: c.context } : {}) });
172
+ }
173
+ }
174
+ catch (error) {
175
+ actual.status = "failed";
176
+ actual.stage = error instanceof SpliceError ? error.stage : "unknown";
177
+ if (error instanceof SpliceError && c.expect.completedTargets !== undefined)
178
+ actual.completedTargets = error.completedTargets;
179
+ actual.issues = error instanceof SpliceError ? error.issues.map(({ code, path }) => ({ code, path })) : [];
180
+ }
181
+ actual.sourceCalls = source.stats().attempts;
182
+ actual.targetCalls = target.stats().attempts;
183
+ const expected = c.expect;
184
+ let reason = actual.status !== expected.status || (expected.stage !== undefined && actual.stage !== expected.stage) ? "unexpected-outcome"
185
+ : expected.sourceCalls !== undefined && actual.sourceCalls !== expected.sourceCalls ? "unexpected-source-calls"
186
+ : expected.completedTargets !== undefined && actual.completedTargets !== expected.completedTargets ? "unexpected-completed-targets"
187
+ : actual.targetCalls !== expected.targetCalls ? "unexpected-target-calls"
188
+ : source.stats().mismatch || target.stats().mismatch ? "mock-mismatch"
189
+ : (c.transportFailure === "source" && source.stats().consumed !== 1) ||
190
+ (c.transportFailure === "target" && target.stats().remaining !== 0) ? "transport-failure-not-reached"
191
+ : expected.code !== undefined && !actual.issues.some(i => i.code === expected.code && (expected.path === undefined || i.path === expected.path)) ? "unexpected-issue"
192
+ : expected.path !== undefined && !actual.issues.some(i => i.path === expected.path) ? "unexpected-issue"
193
+ : undefined;
194
+ if (!reason && expected.arguments !== undefined) {
195
+ const diff = firstDifference(expected.arguments, mapped ?? target.getCalls().map(call => call.arguments));
196
+ if (diff) {
197
+ reason = "unexpected-arguments";
198
+ actual.difference = attributeDifference(diff, suite.plan);
199
+ }
200
+ }
201
+ if (!reason && expected.results !== undefined) {
202
+ const diff = firstDifference(expected.results, result);
203
+ if (diff) {
204
+ reason = "unexpected-results";
205
+ actual.difference = diff;
206
+ }
207
+ }
208
+ if (!reason && expected.resultFingerprint !== undefined && jsonFingerprint(result) !== expected.resultFingerprint)
209
+ reason = "unexpected-results";
210
+ cases.push({ name: c.name, passed: reason === undefined, ...(reason ? { reason } : {}), actual });
211
+ }
212
+ const failed = cases.filter(c => !c.passed).length;
213
+ return { format: "toolsplice-test-report", formatVersion: 1, passed: cases.length - failed, failed, cases,
214
+ fingerprints: prepared.report.fingerprints, networkCalls: 0, liveToolCalls: 0 };
215
+ }
216
+ export function suiteFromRecording(input, options = {}) {
217
+ const { recording: r, spec, source, target } = loadReplayFixture(input, options);
218
+ const thrown = r.calls.find(c => c.outcome === "threw");
219
+ if (r.cancellationObserved || r.calls.some((c, i) => !c.arguments || (c.outcome === "returned" && !c.result) ||
220
+ c.name !== spec[c.side].tool || c.side !== (i === 0 ? "source" : "target")) ||
221
+ (r.outcome.status === "failed" && r.outcome.stage === "unknown") ||
222
+ (thrown && ((thrown !== r.calls.at(-1) && !(r.readPolicy && thrown.side === "target")) || r.outcome.status !== "failed" || r.outcome.stage !== thrown.side)))
223
+ throw new Error("Suite conversion needs complete ordered calls and a reproducible outcome without cancellation.");
224
+ const sourceCall = r.calls[0];
225
+ const targets = r.calls.slice(1);
226
+ const expected = {
227
+ status: r.outcome.status,
228
+ sourceCalls: sourceCall ? 1 : 0,
229
+ targetCalls: targets.length,
230
+ arguments: targets.map(c => c.arguments),
231
+ };
232
+ if (r.outcome.status === "succeeded" && r.outcome.resultFingerprint)
233
+ expected.resultFingerprint = r.outcome.resultFingerprint;
234
+ if (r.outcome.status === "failed") {
235
+ expected.stage = r.outcome.stage;
236
+ expected.completedTargets = r.outcome.completedTargets;
237
+ const issue = r.outcome.issues[0];
238
+ if (issue)
239
+ Object.assign(expected, { code: issue.code, path: issue.path });
240
+ }
241
+ return parseSpliceSuite({
242
+ format: "toolsplice-suite", formatVersion: 1, plan: spec,
243
+ sourceContract: source, targetContract: target, allowReview: r.allowReview,
244
+ cases: [{
245
+ name: options.name ?? "recorded handoff",
246
+ input: r.input,
247
+ ...(Object.hasOwn(r, "context") ? { context: r.context } : {}),
248
+ sourceResult: sourceCall ? sourceCall.result ?? {} : { content: [] },
249
+ ...(r.readPolicy ? { readPolicy: r.readPolicy } : {}),
250
+ ...(thrown && r.readPolicy && thrown.side === "target"
251
+ ? { targetFailures: targets.flatMap((c, i) => c.outcome === "threw" ? [i] : []) }
252
+ : thrown ? { transportFailure: thrown.side } : {}),
253
+ targetResults: targets.filter(c => c.outcome === "returned").map(c => c.result),
254
+ expect: expected,
255
+ }],
256
+ });
257
+ }
258
+ export function formatTestJUnit(report) {
259
+ const xml = (v) => v.replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\ufffe\uffff]/g, "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
260
+ return `<?xml version="1.0" encoding="UTF-8"?>\n<testsuites><testsuite name="toolsplice" tests="${report.cases.length}" failures="${report.failed}">${report.cases.map(c => `<testcase name="${xml(c.name)}">${c.passed ? "" : `<failure message="${xml(c.reason ?? "failed")}">${xml(JSON.stringify(c.actual))}</failure>`}</testcase>`).join("")}</testsuite></testsuites>\n`;
261
+ }
@@ -0,0 +1,24 @@
1
+ import { type PageJob, type PageCheckpoint, type PageOutcome } from "./page-checkpoint.js";
2
+ import { type PageReadOptions } from "./read-pages.js";
3
+ export interface TextPage {
4
+ text: string;
5
+ /** Omit the cursor, or return null, when this page completes the text. */
6
+ nextCursor?: string | null;
7
+ }
8
+ export type TextPageOptions<C extends PageCheckpoint | undefined = undefined> = PageReadOptions & {
9
+ checkpoint?: C;
10
+ };
11
+ type Reader = (cursor: string | undefined, signal?: AbortSignal) => TextPage | PromiseLike<TextPage>;
12
+ /** Collect ordered chunks from an application-owned reader. Cursors are opaque. */
13
+ export declare function collectTextPages(read: Reader, options?: PageReadOptions & {
14
+ checkpoint?: undefined;
15
+ }): Promise<string>;
16
+ export declare function collectTextPages(read: Reader, options: TextPageOptions<PageCheckpoint> & {
17
+ checkpoint: PageCheckpoint;
18
+ }): Promise<PageOutcome<string>>;
19
+ export declare function collectTextPages(read: Reader, options: TextPageOptions<PageCheckpoint | undefined>): Promise<string | PageOutcome<string>>;
20
+ /** Open a resumable collection of text chunks in source order. */
21
+ export declare function textPageJob(options: PageReadOptions & {
22
+ checkpoint: PageCheckpoint;
23
+ }): PageJob<TextPage, string>;
24
+ export {};
@@ -0,0 +1,36 @@
1
+ import { createPageJob, } from "./page-checkpoint.js";
2
+ import { pageLimits, readPages, utf8Bytes, } from "./read-pages.js";
3
+ export async function collectTextPages(read, options = {}) {
4
+ const { maxPages, maxBytes } = pageLimits(options);
5
+ const chunks = [];
6
+ if (options.checkpoint !== undefined) {
7
+ return textPageJob({ ...options, checkpoint: options.checkpoint }).run(({ cursor }, signal) => read(cursor ?? undefined, signal));
8
+ }
9
+ let bytes = 0;
10
+ for await (const page of readPages(read, maxPages, options)) {
11
+ if (!page || typeof page.text !== "string")
12
+ throw new TypeError("Expected a text page.");
13
+ bytes += utf8Bytes(page.text);
14
+ if (bytes > maxBytes)
15
+ throw new RangeError("Collected text exceeded the byte limit.");
16
+ chunks.push(page.text);
17
+ }
18
+ return chunks.join("");
19
+ }
20
+ /** Open a resumable collection of text chunks in source order. */
21
+ export function textPageJob(options) {
22
+ return createPageJob(options.checkpoint, "text", null, options, () => {
23
+ const chunks = [];
24
+ return {
25
+ project(page) {
26
+ if (typeof page?.text !== "string")
27
+ throw new TypeError("Expected a text page.");
28
+ return { part: page.text, bytes: utf8Bytes(page.text) };
29
+ },
30
+ append(part) {
31
+ chunks.push(part);
32
+ },
33
+ finish: () => chunks.join(""),
34
+ };
35
+ });
36
+ }
@@ -0,0 +1,59 @@
1
+ import type { ResultTool } from "./result-session.js";
2
+ import type { SpliceRunOptions } from "./splice.js";
3
+ export declare class CatalogSearch {
4
+ #private;
5
+ private limit;
6
+ readonly definition: {
7
+ name: string;
8
+ description: string;
9
+ inputSchema: {
10
+ type: string;
11
+ properties: Record<string, unknown>;
12
+ required: string[];
13
+ additionalProperties: boolean;
14
+ };
15
+ };
16
+ constructor(tools: readonly ResultTool[], limit: number);
17
+ matches(q: string): {
18
+ entry: {
19
+ tool: ResultTool;
20
+ definition: import("./local-tool.js").LocalToolDefinition;
21
+ name: Set<string>;
22
+ body: Set<string>;
23
+ };
24
+ score: number;
25
+ }[];
26
+ initial(question: string): ResultTool[];
27
+ execute(args: Record<string, unknown>): Promise<{
28
+ tools: {
29
+ name: string;
30
+ description: string;
31
+ inputSchema: Record<string, unknown>;
32
+ }[];
33
+ }>;
34
+ }
35
+ export declare class CatalogCall {
36
+ #private;
37
+ readonly definition: {
38
+ name: string;
39
+ description: string;
40
+ inputSchema: {
41
+ type: string;
42
+ properties: Record<string, unknown>;
43
+ required: string[];
44
+ additionalProperties: boolean;
45
+ };
46
+ };
47
+ constructor(tools: readonly ResultTool[]);
48
+ resolve(args: Record<string, unknown>): {
49
+ tool: ResultTool;
50
+ input: Record<string, unknown>;
51
+ };
52
+ execute(args: Record<string, unknown>, options?: SpliceRunOptions): Promise<unknown>;
53
+ }
54
+ /** Limit model-visible schemas to requested matches. Pass only executables authorized for this run. */
55
+ export declare function discoverTools(tools: readonly ResultTool[], { threshold, limit, question, }?: {
56
+ threshold?: number;
57
+ limit?: number;
58
+ question?: string;
59
+ }): ResultTool[];