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.
- package/README.md +26 -17
- package/dist/abortable.d.ts +6 -0
- package/dist/abortable.js +50 -0
- package/dist/adaptive-read.d.ts +50 -0
- package/dist/adaptive-read.js +780 -0
- package/dist/answer-wait.d.ts +7 -0
- package/dist/answer-wait.js +45 -0
- package/dist/cache-reads.d.ts +18 -0
- package/dist/cache-reads.js +89 -0
- package/dist/calibration-ledger.d.ts +37 -0
- package/dist/calibration-ledger.js +148 -0
- package/dist/calibration-marker.d.ts +4 -0
- package/dist/calibration-marker.js +77 -0
- package/dist/catalog-setup.d.ts +33 -0
- package/dist/catalog-setup.js +89 -0
- package/dist/catalog.d.ts +10 -0
- package/dist/catalog.js +42 -0
- package/dist/checkpoint-files.d.ts +15 -0
- package/dist/checkpoint-files.js +99 -0
- package/dist/coalesce-reads.d.ts +6 -0
- package/dist/coalesce-reads.js +33 -0
- package/dist/contract-caller.d.ts +2 -1
- package/dist/contract-caller.js +35 -16
- package/dist/contract-schema.d.ts +3 -1
- package/dist/contract-schema.js +34 -4
- package/dist/contracts.d.ts +1 -0
- package/dist/contracts.js +5 -1
- package/dist/core.d.ts +31 -1
- package/dist/core.js +27 -0
- package/dist/db-final-answer.d.ts +9 -0
- package/dist/db-final-answer.js +62 -0
- package/dist/define.d.ts +78 -0
- package/dist/define.js +14 -0
- package/dist/final-answer-stores.d.ts +71 -0
- package/dist/final-answer-stores.js +72 -0
- package/dist/final-answer.d.ts +32 -0
- package/dist/final-answer.js +104 -0
- package/dist/impact.d.ts +48 -0
- package/dist/impact.js +71 -0
- package/dist/local-tool.d.ts +18 -0
- package/dist/local-tool.js +32 -0
- package/dist/mcp-apps.d.ts +53 -0
- package/dist/mcp-apps.js +32 -0
- package/dist/mcp-event-delivery.d.ts +98 -0
- package/dist/mcp-event-delivery.js +211 -0
- package/dist/mcp-extensions.d.ts +46 -0
- package/dist/mcp-extensions.js +200 -0
- package/dist/mcp-peer.d.ts +45 -0
- package/dist/mcp-peer.js +207 -0
- package/dist/mcp-server-card.d.ts +21 -0
- package/dist/mcp-server-card.js +54 -0
- package/dist/page-checkpoint.d.ts +71 -0
- package/dist/page-checkpoint.js +286 -0
- package/dist/page-read-gate.d.ts +15 -0
- package/dist/page-read-gate.js +48 -0
- package/dist/pattern.d.ts +1 -0
- package/dist/pattern.js +27 -5
- package/dist/read-pages.d.ts +25 -0
- package/dist/read-pages.js +85 -0
- package/dist/read-policy.d.ts +6 -0
- package/dist/read-policy.js +16 -0
- package/dist/read-steps.d.ts +12 -0
- package/dist/read-steps.js +36 -0
- package/dist/result-session.d.ts +109 -0
- package/dist/result-session.js +620 -0
- package/dist/route-checkpoint.d.ts +3 -0
- package/dist/route-checkpoint.js +80 -0
- package/dist/route-evaluation.d.ts +141 -0
- package/dist/route-evaluation.js +329 -0
- package/dist/row-groups.d.ts +17 -0
- package/dist/row-groups.js +79 -0
- package/dist/row-query.d.ts +62 -0
- package/dist/row-query.js +172 -0
- package/dist/rules.d.ts +30 -0
- package/dist/rules.js +72 -0
- package/dist/run-diagnostics.d.ts +75 -0
- package/dist/run-diagnostics.js +212 -0
- package/dist/search-fetch.d.ts +50 -0
- package/dist/search-fetch.js +264 -0
- package/dist/skill-files.d.ts +9 -0
- package/dist/skill-files.js +49 -0
- package/dist/splice-diagnostics.d.ts +4 -0
- package/dist/splice-diagnostics.js +24 -16
- package/dist/splice-recording.d.ts +29 -2
- package/dist/splice-recording.js +22 -5
- package/dist/splice.d.ts +98 -1
- package/dist/splice.js +225 -27
- package/dist/sqlite-checkpoint-store.d.ts +5 -0
- package/dist/sqlite-checkpoint-store.js +91 -0
- package/dist/sqlite-checkpoint-worker.js +115 -0
- package/dist/test-difference.d.ts +13 -0
- package/dist/test-difference.js +42 -0
- package/dist/testing.d.ts +122 -0
- package/dist/testing.js +261 -0
- package/dist/text-pages.d.ts +24 -0
- package/dist/text-pages.js +36 -0
- package/dist/tool-discovery.d.ts +59 -0
- package/dist/tool-discovery.js +136 -0
- package/dist/unevaluated.d.ts +7 -0
- package/dist/unevaluated.js +156 -0
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/workflow-json.js +1 -1
- package/integrations/ai.d.mts +36 -0
- package/integrations/ai.mjs +178 -0
- package/integrations/call-options.mjs +9 -0
- package/integrations/langchain.d.mts +31 -0
- package/integrations/langchain.mjs +114 -0
- package/integrations/managed.mjs +154 -0
- package/integrations/types.d.mts +13 -0
- package/package.json +30 -1
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { DatabaseSync } from "node:sqlite";
|
|
2
|
+
import { closeSync, openSync } from "node:fs";
|
|
3
|
+
import { parentPort, workerData } from "node:worker_threads";
|
|
4
|
+
import { setTimeout as wait } from "node:timers/promises";
|
|
5
|
+
const port = parentPort;
|
|
6
|
+
let db;
|
|
7
|
+
let read, claim, complete;
|
|
8
|
+
async function enableWal(db) {
|
|
9
|
+
const deadline = performance.now() + 5000;
|
|
10
|
+
for (let delay = 5;; delay = Math.min(delay * 2, 100)) {
|
|
11
|
+
try {
|
|
12
|
+
return db.prepare("PRAGMA journal_mode=WAL").get();
|
|
13
|
+
}
|
|
14
|
+
catch (error) {
|
|
15
|
+
const code = error.errcode ?? 0;
|
|
16
|
+
if ((code & 255) !== 5 || performance.now() >= deadline)
|
|
17
|
+
throw error;
|
|
18
|
+
// SQLite may skip its busy handler when concurrent openers upgrade journal mode.
|
|
19
|
+
await wait(Math.min(delay, Math.max(0, deadline - performance.now())));
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
async function open() {
|
|
24
|
+
const version = process.versions.sqlite;
|
|
25
|
+
if (!version)
|
|
26
|
+
throw new Error("A Node build with SQLite is required.");
|
|
27
|
+
const [major, minor, patch] = version.split(".").map(Number);
|
|
28
|
+
const fixed = major > 3 ||
|
|
29
|
+
(major === 3 &&
|
|
30
|
+
(minor > 51 ||
|
|
31
|
+
(minor === 51 && patch >= 3) ||
|
|
32
|
+
(minor === 50 && patch >= 7) ||
|
|
33
|
+
(minor === 44 && patch >= 6)));
|
|
34
|
+
if (!fixed)
|
|
35
|
+
throw new Error("SQLite " +
|
|
36
|
+
version +
|
|
37
|
+
" requires a WAL-reset fix. Use 3.51.3 or later, or a patched 3.50.7/3.44.6 release.");
|
|
38
|
+
// Only the creator sets the mode. Application-owned files keep their existing permissions.
|
|
39
|
+
try {
|
|
40
|
+
closeSync(openSync(workerData, "wx", 0o600));
|
|
41
|
+
}
|
|
42
|
+
catch (error) {
|
|
43
|
+
if (error.code !== "EEXIST")
|
|
44
|
+
throw error;
|
|
45
|
+
}
|
|
46
|
+
db = new DatabaseSync(workerData);
|
|
47
|
+
db.exec("PRAGMA busy_timeout=5000; PRAGMA fullfsync=ON; PRAGMA synchronous=FULL");
|
|
48
|
+
const mode = await enableWal(db);
|
|
49
|
+
if (mode?.journal_mode !== "wal" ||
|
|
50
|
+
db.prepare("PRAGMA fullfsync").get()?.fullfsync !== 1 ||
|
|
51
|
+
db.prepare("PRAGMA synchronous").get()?.synchronous !== 2)
|
|
52
|
+
throw new Error("Could not enable durable SQLite WAL mode.");
|
|
53
|
+
db.exec("CREATE TABLE IF NOT EXISTS toolsplice_checkpoints (job TEXT PRIMARY KEY, identity TEXT NOT NULL, payload TEXT) WITHOUT ROWID");
|
|
54
|
+
read = db.prepare("SELECT identity,payload FROM toolsplice_checkpoints WHERE job=?");
|
|
55
|
+
claim = db.prepare("INSERT INTO toolsplice_checkpoints(job,identity) VALUES(?,?) ON CONFLICT(job) DO NOTHING");
|
|
56
|
+
complete = db.prepare("UPDATE toolsplice_checkpoints SET payload=? WHERE job=? AND identity=? AND payload IS NULL");
|
|
57
|
+
}
|
|
58
|
+
function execute({ method, args: [job, identity, payload] }) {
|
|
59
|
+
switch (method) {
|
|
60
|
+
case "read":
|
|
61
|
+
return read.get(job) ?? null;
|
|
62
|
+
case "claim":
|
|
63
|
+
return claim.run(job, identity).changes === 1;
|
|
64
|
+
case "complete":
|
|
65
|
+
return complete.run(payload, job, identity).changes === 1;
|
|
66
|
+
default:
|
|
67
|
+
throw new Error("Unknown SQLite checkpoint operation.");
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
function dispatch(batch) {
|
|
71
|
+
const group = batch.length > 1 && batch.some((op) => op.method !== "read");
|
|
72
|
+
let inTransaction = false;
|
|
73
|
+
try {
|
|
74
|
+
if (group) {
|
|
75
|
+
db.exec("BEGIN IMMEDIATE");
|
|
76
|
+
inTransaction = true;
|
|
77
|
+
}
|
|
78
|
+
const replies = batch.map((op) => ({ id: op.id, value: execute(op) }));
|
|
79
|
+
if (group)
|
|
80
|
+
db.exec("COMMIT");
|
|
81
|
+
port.postMessage(replies);
|
|
82
|
+
}
|
|
83
|
+
catch (error) {
|
|
84
|
+
if (inTransaction && db.isTransaction)
|
|
85
|
+
db.exec("ROLLBACK");
|
|
86
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
87
|
+
port.postMessage(batch.map((op) => ({ id: op.id, error: reason })));
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
port.on("message", async (message) => {
|
|
91
|
+
if ("batch" in message) {
|
|
92
|
+
dispatch(message.batch);
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
const { id, method } = message;
|
|
96
|
+
try {
|
|
97
|
+
if (method === "open")
|
|
98
|
+
await open();
|
|
99
|
+
else if (method === "close") {
|
|
100
|
+
db?.close();
|
|
101
|
+
db = undefined;
|
|
102
|
+
}
|
|
103
|
+
else
|
|
104
|
+
throw new Error("Unknown SQLite connection operation.");
|
|
105
|
+
port.postMessage({ id });
|
|
106
|
+
}
|
|
107
|
+
catch (error) {
|
|
108
|
+
if (method === "open")
|
|
109
|
+
db?.close();
|
|
110
|
+
port.postMessage({
|
|
111
|
+
id,
|
|
112
|
+
error: error instanceof Error ? error.message : String(error),
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
});
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { type SpliceFieldOrigin } from "./splice-diagnostics.js";
|
|
2
|
+
import type { SpliceSpec } from "./splice.js";
|
|
3
|
+
export interface TestDifference {
|
|
4
|
+
path: string;
|
|
5
|
+
kind: "type" | "value" | "missing" | "extra" | "length";
|
|
6
|
+
expectedLength?: number;
|
|
7
|
+
actualLength?: number;
|
|
8
|
+
pathTruncated?: true;
|
|
9
|
+
fields?: SpliceFieldOrigin[];
|
|
10
|
+
}
|
|
11
|
+
/** Inputs are detached JSON from the suite and the completed mock run. */
|
|
12
|
+
export declare function firstDifference(expected: unknown, actual: unknown, path?: string): TestDifference | undefined;
|
|
13
|
+
export declare function attributeDifference(diff: TestDifference, plan: SpliceSpec): TestDifference;
|
|
@@ -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;
|
package/dist/testing.js
ADDED
|
@@ -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, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
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
|
+
}
|