toolsplice 0.0.0-stage → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (172) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +104 -2
  3. package/dist/abortable.d.ts +6 -0
  4. package/dist/abortable.js +50 -0
  5. package/dist/adaptive-read.d.ts +50 -0
  6. package/dist/adaptive-read.js +780 -0
  7. package/dist/answer-wait.d.ts +7 -0
  8. package/dist/answer-wait.js +45 -0
  9. package/dist/cache-reads.d.ts +18 -0
  10. package/dist/cache-reads.js +89 -0
  11. package/dist/calibration-ledger.d.ts +37 -0
  12. package/dist/calibration-ledger.js +148 -0
  13. package/dist/calibration-marker.d.ts +4 -0
  14. package/dist/calibration-marker.js +77 -0
  15. package/dist/catalog-setup.d.ts +33 -0
  16. package/dist/catalog-setup.js +89 -0
  17. package/dist/catalog.d.ts +10 -0
  18. package/dist/catalog.js +42 -0
  19. package/dist/checkpoint-files.d.ts +15 -0
  20. package/dist/checkpoint-files.js +99 -0
  21. package/dist/cli.d.ts +2 -0
  22. package/dist/cli.js +1454 -0
  23. package/dist/coalesce-reads.d.ts +6 -0
  24. package/dist/coalesce-reads.js +33 -0
  25. package/dist/codegen.d.ts +44 -0
  26. package/dist/codegen.js +479 -0
  27. package/dist/contract-caller.d.ts +23 -0
  28. package/dist/contract-caller.js +326 -0
  29. package/dist/contract-corrections.d.ts +35 -0
  30. package/dist/contract-corrections.js +159 -0
  31. package/dist/contract-schema.d.ts +7 -0
  32. package/dist/contract-schema.js +156 -0
  33. package/dist/contracts.d.ts +72 -0
  34. package/dist/contracts.js +370 -0
  35. package/dist/core.d.ts +44 -0
  36. package/dist/core.js +43 -0
  37. package/dist/db-final-answer.d.ts +9 -0
  38. package/dist/db-final-answer.js +62 -0
  39. package/dist/define.d.ts +78 -0
  40. package/dist/define.js +14 -0
  41. package/dist/doctor.d.ts +22 -0
  42. package/dist/doctor.js +91 -0
  43. package/dist/drift.d.ts +23 -0
  44. package/dist/drift.js +111 -0
  45. package/dist/execution.d.ts +38 -0
  46. package/dist/execution.js +66 -0
  47. package/dist/extract.d.ts +34 -0
  48. package/dist/extract.js +73 -0
  49. package/dist/final-answer-stores.d.ts +71 -0
  50. package/dist/final-answer-stores.js +72 -0
  51. package/dist/final-answer.d.ts +32 -0
  52. package/dist/final-answer.js +104 -0
  53. package/dist/impact.d.ts +48 -0
  54. package/dist/impact.js +71 -0
  55. package/dist/index.d.ts +51 -0
  56. package/dist/index.js +47 -0
  57. package/dist/local-tool.d.ts +18 -0
  58. package/dist/local-tool.js +32 -0
  59. package/dist/mcp-apps.d.ts +53 -0
  60. package/dist/mcp-apps.js +32 -0
  61. package/dist/mcp-event-delivery.d.ts +98 -0
  62. package/dist/mcp-event-delivery.js +211 -0
  63. package/dist/mcp-extensions.d.ts +46 -0
  64. package/dist/mcp-extensions.js +200 -0
  65. package/dist/mcp-peer.d.ts +45 -0
  66. package/dist/mcp-peer.js +207 -0
  67. package/dist/mcp-server-card.d.ts +21 -0
  68. package/dist/mcp-server-card.js +54 -0
  69. package/dist/ordered-transport.d.ts +12 -0
  70. package/dist/ordered-transport.js +106 -0
  71. package/dist/page-checkpoint.d.ts +71 -0
  72. package/dist/page-checkpoint.js +286 -0
  73. package/dist/page-read-gate.d.ts +15 -0
  74. package/dist/page-read-gate.js +48 -0
  75. package/dist/pattern.d.ts +3 -0
  76. package/dist/pattern.js +54 -0
  77. package/dist/postgres.d.ts +41 -0
  78. package/dist/postgres.js +264 -0
  79. package/dist/probe.d.ts +29 -0
  80. package/dist/probe.js +121 -0
  81. package/dist/proxy.d.ts +40 -0
  82. package/dist/proxy.js +436 -0
  83. package/dist/read-pages.d.ts +25 -0
  84. package/dist/read-pages.js +85 -0
  85. package/dist/read-policy.d.ts +6 -0
  86. package/dist/read-policy.js +16 -0
  87. package/dist/read-steps.d.ts +12 -0
  88. package/dist/read-steps.js +36 -0
  89. package/dist/result-session.d.ts +109 -0
  90. package/dist/result-session.js +620 -0
  91. package/dist/route-checkpoint.d.ts +3 -0
  92. package/dist/route-checkpoint.js +80 -0
  93. package/dist/route-driver-cli.d.ts +3 -0
  94. package/dist/route-driver-cli.js +43 -0
  95. package/dist/route-evaluation.d.ts +141 -0
  96. package/dist/route-evaluation.js +329 -0
  97. package/dist/row-groups.d.ts +17 -0
  98. package/dist/row-groups.js +79 -0
  99. package/dist/row-query.d.ts +62 -0
  100. package/dist/row-query.js +172 -0
  101. package/dist/rules.d.ts +30 -0
  102. package/dist/rules.js +72 -0
  103. package/dist/run-diagnostics.d.ts +75 -0
  104. package/dist/run-diagnostics.js +212 -0
  105. package/dist/runtime.d.ts +6 -0
  106. package/dist/runtime.js +26 -0
  107. package/dist/schema.d.ts +17 -0
  108. package/dist/schema.js +299 -0
  109. package/dist/search-fetch.d.ts +50 -0
  110. package/dist/search-fetch.js +264 -0
  111. package/dist/shape.d.ts +91 -0
  112. package/dist/shape.js +499 -0
  113. package/dist/skill-files.d.ts +9 -0
  114. package/dist/skill-files.js +49 -0
  115. package/dist/splice-diagnostics.d.ts +44 -0
  116. package/dist/splice-diagnostics.js +88 -0
  117. package/dist/splice-measure.d.ts +33 -0
  118. package/dist/splice-measure.js +55 -0
  119. package/dist/splice-project.d.ts +125 -0
  120. package/dist/splice-project.js +348 -0
  121. package/dist/splice-recording.d.ts +132 -0
  122. package/dist/splice-recording.js +481 -0
  123. package/dist/splice.d.ts +181 -0
  124. package/dist/splice.js +1263 -0
  125. package/dist/sqlite-checkpoint-store.d.ts +5 -0
  126. package/dist/sqlite-checkpoint-store.js +91 -0
  127. package/dist/sqlite-checkpoint-worker.d.ts +1 -0
  128. package/dist/sqlite-checkpoint-worker.js +115 -0
  129. package/dist/storage.d.ts +17 -0
  130. package/dist/storage.js +1 -0
  131. package/dist/store.d.ts +151 -0
  132. package/dist/store.js +735 -0
  133. package/dist/test-difference.d.ts +13 -0
  134. package/dist/test-difference.js +42 -0
  135. package/dist/testing.d.ts +122 -0
  136. package/dist/testing.js +261 -0
  137. package/dist/text-pages.d.ts +24 -0
  138. package/dist/text-pages.js +36 -0
  139. package/dist/tool-discovery.d.ts +59 -0
  140. package/dist/tool-discovery.js +136 -0
  141. package/dist/unevaluated.d.ts +7 -0
  142. package/dist/unevaluated.js +156 -0
  143. package/dist/v2.d.ts +49 -0
  144. package/dist/v2.js +413 -0
  145. package/dist/validate-output.d.ts +3 -0
  146. package/dist/validate-output.js +73 -0
  147. package/dist/version.d.ts +1 -0
  148. package/dist/version.js +1 -0
  149. package/dist/workflow-json.d.ts +8 -0
  150. package/dist/workflow-json.js +74 -0
  151. package/docs/AGENT-FRAMEWORKS.md +431 -0
  152. package/docs/BENCHMARKS.md +43 -0
  153. package/docs/INTEGRATION-QUICKSTART.md +859 -0
  154. package/docs/LEARNING-AND-STORAGE.md +393 -0
  155. package/docs/MCP.md +204 -0
  156. package/docs/PROJECTS-AND-UPGRADES.md +173 -0
  157. package/docs/PYTHON-REFERENCE.md +348 -0
  158. package/docs/PYTHON.md +120 -0
  159. package/docs/RECORDING-AND-CORRECTIONS.md +205 -0
  160. package/docs/TESTING.md +259 -0
  161. package/examples/mcp-app/build.mjs +11 -0
  162. package/examples/mcp-app/view.mjs +22 -0
  163. package/examples/quickstart.mjs +43 -0
  164. package/examples/route-driver.mjs +67 -0
  165. package/integrations/ai.d.mts +36 -0
  166. package/integrations/ai.mjs +178 -0
  167. package/integrations/call-options.mjs +9 -0
  168. package/integrations/langchain.d.mts +31 -0
  169. package/integrations/langchain.mjs +114 -0
  170. package/integrations/managed.mjs +154 -0
  171. package/integrations/types.d.mts +13 -0
  172. package/package.json +139 -4
@@ -0,0 +1,7 @@
1
+ import type { FinalAnswerStatus } from "./final-answer.js";
2
+ export declare class FinalAnswerWaitTimeout extends Error {
3
+ readonly state: "unknown" | "missing" | "incomplete";
4
+ constructor(state: "unknown" | "missing" | "incomplete");
5
+ }
6
+ export declare function validateWait(timeoutMs: number): void;
7
+ export declare function answerWaiter<T>(inspect: () => FinalAnswerStatus<T> | Promise<FinalAnswerStatus<T>>): (timeoutMs: number, signal?: AbortSignal) => Promise<T>;
@@ -0,0 +1,45 @@
1
+ import { setTimeout as sleep } from "node:timers/promises";
2
+ import { abortable } from "./abortable.js";
3
+ export class FinalAnswerWaitTimeout extends Error {
4
+ state;
5
+ constructor(state) {
6
+ super(`Timed out waiting for the final answer (last observed state: ${state}).`);
7
+ this.state = state;
8
+ this.name = "FinalAnswerWaitTimeout";
9
+ }
10
+ }
11
+ export function validateWait(timeoutMs) {
12
+ if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 2147483647)
13
+ throw new RangeError("Expected a positive integer wait timeout in milliseconds.");
14
+ }
15
+ export function answerWaiter(inspect) {
16
+ return async function waitForResult(timeoutMs, signal) {
17
+ validateWait(timeoutMs);
18
+ let state = "unknown";
19
+ const deadline = new AbortController();
20
+ const combined = signal
21
+ ? AbortSignal.any([signal, deadline.signal])
22
+ : deadline.signal;
23
+ const timer = setTimeout(() => deadline.abort(new FinalAnswerWaitTimeout(state)), timeoutMs);
24
+ try {
25
+ let interval = 10;
26
+ while (true) {
27
+ const observation = await abortable(inspect, combined);
28
+ if (observation.state === "saved")
29
+ return observation.answer;
30
+ state = observation.state;
31
+ try {
32
+ await sleep(interval, undefined, { signal: combined });
33
+ }
34
+ catch (error) {
35
+ combined.throwIfAborted();
36
+ throw error;
37
+ }
38
+ interval = Math.min(250, interval * 2);
39
+ }
40
+ }
41
+ finally {
42
+ clearTimeout(timer);
43
+ }
44
+ };
45
+ }
@@ -0,0 +1,18 @@
1
+ import type { ToolCaller } from "./execution.js";
2
+ export interface ReadCacheOptions {
3
+ tools: readonly string[];
4
+ /** Current authorization scope (tenant, grants and catalog version), after authorization. */
5
+ scope: () => string;
6
+ ttlMs: number;
7
+ maxEntries?: number;
8
+ maxBytes?: number;
9
+ }
10
+ export declare function cacheReads(caller: ToolCaller, { tools, scope, ttlMs, maxEntries, maxBytes, }: ReadCacheOptions): ToolCaller & {
11
+ clear(): void;
12
+ stats: () => {
13
+ entries: number;
14
+ bytes: number;
15
+ hits: number;
16
+ misses: number;
17
+ };
18
+ };
@@ -0,0 +1,89 @@
1
+ import { copyJson, jsonFingerprint } from "./workflow-json.js";
2
+ export function cacheReads(caller, { tools, scope, ttlMs, maxEntries = 128, maxBytes = 1024 * 1024, }) {
3
+ const positive = (n) => Number.isSafeInteger(n) && n > 0;
4
+ if (typeof caller !== "function" ||
5
+ typeof scope !== "function" ||
6
+ !Array.isArray(tools) ||
7
+ !tools.length ||
8
+ tools.some((t) => typeof t !== "string" || !t) ||
9
+ ![ttlMs, maxEntries, maxBytes].every(positive))
10
+ throw new TypeError("Expected a caller, read allowlist, scope, TTL and positive cache limits.");
11
+ const allowed = new Set(tools);
12
+ const entries = new Map();
13
+ let bytes = 0, hits = 0, misses = 0, generation = 0, sequence = 0;
14
+ function remove(key) {
15
+ const item = entries.get(key);
16
+ if (item) {
17
+ entries.delete(key);
18
+ bytes -= item.size;
19
+ }
20
+ }
21
+ const call = async (request, options) => {
22
+ if (!allowed.has(request.name) ||
23
+ Object.keys(request).some((k) => k !== "name" && k !== "arguments") ||
24
+ (options && Object.values(options).some((v) => v !== undefined)))
25
+ return caller(request, options);
26
+ const principal = scope();
27
+ if (typeof principal !== "string" || !principal.trim())
28
+ throw new TypeError("A nonempty authorization scope is required.");
29
+ const snapshot = copyJson(request);
30
+ const key = jsonFingerprint([principal, snapshot]);
31
+ const item = entries.get(key);
32
+ if (item && performance.now() < item.expires) {
33
+ hits++;
34
+ entries.delete(key);
35
+ entries.set(key, item);
36
+ return JSON.parse(item.json);
37
+ }
38
+ remove(key);
39
+ misses++;
40
+ const current = generation, seq = ++sequence;
41
+ const result = await caller(snapshot, options);
42
+ const newer = entries.get(key);
43
+ if (current !== generation || (newer && newer.seq > seq))
44
+ return result;
45
+ if (!result || typeof result !== "object")
46
+ return result;
47
+ const raw = result;
48
+ const duration = Object.hasOwn(raw, "ttlMs") ? raw.ttlMs : ttlMs;
49
+ if ((raw.resultType !== undefined && raw.resultType !== "complete") ||
50
+ (raw.isError !== undefined && raw.isError !== false) ||
51
+ (raw.cacheScope !== undefined &&
52
+ raw.cacheScope !== "private" &&
53
+ raw.cacheScope !== "public") ||
54
+ (!Object.hasOwn(raw, "structuredContent") &&
55
+ !Array.isArray(raw.content)) ||
56
+ typeof duration !== "number" ||
57
+ !positive(duration))
58
+ return result;
59
+ let json;
60
+ try {
61
+ json = JSON.stringify(copyJson(result, maxBytes));
62
+ }
63
+ catch {
64
+ return result;
65
+ }
66
+ const size = Buffer.byteLength(json) + key.length;
67
+ if (size > maxBytes)
68
+ return result;
69
+ remove(key);
70
+ while (entries.size >= maxEntries || bytes + size > maxBytes)
71
+ remove(entries.keys().next().value);
72
+ entries.set(key, {
73
+ json,
74
+ size,
75
+ expires: performance.now() + Math.min(ttlMs, duration),
76
+ seq,
77
+ });
78
+ bytes += size;
79
+ return result;
80
+ };
81
+ return Object.assign(call, {
82
+ clear() {
83
+ generation++;
84
+ entries.clear();
85
+ bytes = 0;
86
+ },
87
+ stats: () => ({ entries: entries.size, bytes, hits, misses }),
88
+ });
89
+ }
@@ -0,0 +1,37 @@
1
+ export interface CalibrationUsage {
2
+ costUsd: number;
3
+ inputTokens?: number;
4
+ outputTokens?: number;
5
+ }
6
+ export declare function runWithLedger<T>(dir: string, slot: string, key: string, run: () => Promise<T>): Promise<T>;
7
+ /** Call immediately before each provider request, then record its measured cost when usage arrives. */
8
+ export declare function startCalibrationCall(): (usage: CalibrationUsage) => void;
9
+ /** Read a snapshot of all attempts, including retries. This never runs a driver. */
10
+ export declare function readCalibrationLedger(directory: string): {
11
+ format: string;
12
+ version: number;
13
+ attempts: {
14
+ callIntents: number;
15
+ usageReceipts: number;
16
+ pendingCalls: number;
17
+ unmeteredIncompleteAttempts: number;
18
+ knownCostUsd: number;
19
+ trialNumber: number;
20
+ attemptNumber: number;
21
+ state: string;
22
+ calls: {
23
+ id: string;
24
+ startedAtMs: number;
25
+ receivedAtMs?: number;
26
+ usage?: CalibrationUsage;
27
+ }[];
28
+ }[];
29
+ totals: {
30
+ callIntents: number;
31
+ usageReceipts: number;
32
+ pendingCalls: number;
33
+ unmeteredIncompleteAttempts: number;
34
+ knownCostUsd: number;
35
+ };
36
+ usageStatus: string;
37
+ };
@@ -0,0 +1,148 @@
1
+ /** Local, provider-neutral request accounting for route calibration. */
2
+ import { AsyncLocalStorage } from "node:async_hooks";
3
+ import { randomUUID } from "node:crypto";
4
+ import { readdirSync } from "node:fs";
5
+ import { join, resolve } from "node:path";
6
+ import { CheckpointError, active, publish, read } from "./checkpoint-files.js";
7
+ import { canUseCallMarkers, createCallMarker, readCallMarker } from "./calibration-marker.js";
8
+ // Drivers may import the full SDK while the collector imports the core package.
9
+ const symbol = Symbol.for("toolsplice.calibration.attempt.v1");
10
+ const shared = globalThis;
11
+ const storage = shared[symbol] ??= new AsyncLocalStorage();
12
+ export async function runWithLedger(dir, slot, key, run) {
13
+ const scope = { dir, slot, key, open: true };
14
+ try {
15
+ return await storage.run(scope, run);
16
+ }
17
+ finally {
18
+ scope.open = false;
19
+ }
20
+ }
21
+ const money = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0;
22
+ const count = (v) => typeof v === "number" && Number.isSafeInteger(v) && v >= 0;
23
+ function usageOf(value) {
24
+ const { costUsd, inputTokens, outputTokens } = value;
25
+ if (!money(costUsd) || (inputTokens !== undefined && !count(inputTokens)) ||
26
+ (outputTokens !== undefined && !count(outputTokens)))
27
+ throw new CheckpointError(44);
28
+ return { costUsd, ...(inputTokens === undefined ? {} : { inputTokens }),
29
+ ...(outputTokens === undefined ? {} : { outputTokens }) };
30
+ }
31
+ /** Call immediately before each provider request, then record its measured cost when usage arrives. */
32
+ export function startCalibrationCall() {
33
+ const scope = storage.getStore();
34
+ if (!scope)
35
+ return () => { };
36
+ if (!scope.open)
37
+ throw new Error("Calibration attempt is closed.");
38
+ const id = randomUUID();
39
+ const path = join(scope.dir, scope.slot + ".call-" + id + ".json");
40
+ const key = scope.key + "/" + id;
41
+ const startedAtMs = Date.now();
42
+ const finishMarker = canUseCallMarkers(scope.dir) ? createCallMarker(scope.dir, scope.slot, id, key, startedAtMs) : undefined;
43
+ if (!finishMarker && !publish(path, { key, state: "started", startedAtMs }))
44
+ throw new CheckpointError(44);
45
+ return (usage) => {
46
+ if (!scope.open)
47
+ throw new Error("Calibration attempt is closed.");
48
+ const clean = usageOf(usage);
49
+ if (finishMarker)
50
+ return finishMarker(clean);
51
+ const saved = read(path);
52
+ if (saved?.key !== key)
53
+ throw new CheckpointError(44);
54
+ if (saved.state === "received" && JSON.stringify(usageOf(saved)) === JSON.stringify(clean))
55
+ return;
56
+ if (saved.state !== "started")
57
+ throw new CheckpointError(44);
58
+ publish(path, { key, state: "received", startedAtMs, receivedAtMs: Date.now(), ...clean }, true);
59
+ };
60
+ }
61
+ const slotPattern = /^(0|[1-9]\d*)-(0|[1-9]\d*)\.json$/;
62
+ const callPattern = /^((?:0|[1-9]\d*)-(?:0|[1-9]\d*))\.call-([0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12})(?:\.json|\.(\d{1,16})\.([0-9a-f]{64})\.intent)$/;
63
+ function counters() {
64
+ return { callIntents: 0, usageReceipts: 0, pendingCalls: 0, unmeteredIncompleteAttempts: 0, knownCostUsd: 0 };
65
+ }
66
+ /** Read a snapshot of all attempts, including retries. This never runs a driver. */
67
+ export function readCalibrationLedger(directory) {
68
+ const dir = resolve(directory);
69
+ const header = read(join(dir, "manifest.json"));
70
+ if (header?.format !== "toolsplice-calibration" || header.version !== 1 ||
71
+ typeof header.suite !== "string" || !/^[a-f0-9]{64}$/.test(header.suite))
72
+ throw new CheckpointError(44);
73
+ const names = readdirSync(dir).sort();
74
+ const callsBySlot = new Map();
75
+ for (const name of names) {
76
+ if (!name.includes(".call-"))
77
+ continue;
78
+ const match = callPattern.exec(name);
79
+ if (!match || match[0] !== name)
80
+ throw new CheckpointError(44);
81
+ const ids = callsBySlot.get(match[1]) ?? new Map();
82
+ if (ids.has(match[2]))
83
+ throw new CheckpointError(44);
84
+ ids.set(match[2], match);
85
+ callsBySlot.set(match[1], ids);
86
+ }
87
+ const totals = counters();
88
+ const attempts = [];
89
+ for (const name of names) {
90
+ const match = slotPattern.exec(name);
91
+ if (!match)
92
+ continue;
93
+ const slot = name.slice(0, -5);
94
+ const key = header.suite + "/" + slot;
95
+ const claim = read(join(dir, name));
96
+ if (claim?.key !== key || !["done", "active", "uncertain"].includes(String(claim.state)))
97
+ throw new CheckpointError(44);
98
+ const graded = claim.state === "done" ? claim : read(join(dir, slot + ".result.json"));
99
+ const row = counters();
100
+ const ids = Array.from(callsBySlot.get(slot)?.values() ?? []);
101
+ const calls = [];
102
+ row.callIntents = ids.length;
103
+ for (const [name, , id, stamp, tag] of ids) {
104
+ const path = join(dir, name);
105
+ const call = stamp ? readCallMarker(path, key + "/" + id, stamp, tag) : read(path);
106
+ if (call?.key !== key + "/" + id || !count(call.startedAtMs))
107
+ throw new CheckpointError(44);
108
+ if (call.state === "started") {
109
+ row.pendingCalls++;
110
+ calls.push({ id, startedAtMs: call.startedAtMs });
111
+ }
112
+ else if (call.state === "received") {
113
+ row.usageReceipts++;
114
+ if (!count(call.receivedAtMs))
115
+ throw new CheckpointError(44);
116
+ const usage = usageOf(call);
117
+ row.knownCostUsd += usage.costUsd;
118
+ calls.push({ id, startedAtMs: call.startedAtMs, receivedAtMs: call.receivedAtMs, usage });
119
+ }
120
+ else
121
+ throw new CheckpointError(44);
122
+ }
123
+ callsBySlot.delete(slot);
124
+ if (graded) {
125
+ const trial = graded.trial;
126
+ if (graded.key !== key || graded.state !== (claim.state === "done" ? "done" : "graded") ||
127
+ !trial || !money(trial.costUsd) || !count(trial.modelCalls))
128
+ throw new CheckpointError(44);
129
+ // Existing drivers may report aggregate usage only. Do not count the same calls twice.
130
+ row.knownCostUsd = Math.max(row.knownCostUsd, trial.costUsd);
131
+ }
132
+ else if (!ids.length)
133
+ row.unmeteredIncompleteAttempts++;
134
+ for (const k of Object.keys(totals))
135
+ totals[k] += row[k];
136
+ calls.sort((a, b) => a.startedAtMs - b.startedAtMs || (a.id < b.id ? -1 : 1));
137
+ const state = graded ? (claim.state === "done" ? "done" : "recoverable") :
138
+ (claim.state === "active" && active(claim) ? "active" : "interrupted");
139
+ attempts.push({ trialNumber: Number(match[1]) + 1, attemptNumber: Number(match[2]) + 1,
140
+ state, calls, ...row });
141
+ }
142
+ if (callsBySlot.size || !Number.isFinite(totals.knownCostUsd))
143
+ throw new CheckpointError(44);
144
+ attempts.sort((a, b) => a.trialNumber - b.trialNumber || a.attemptNumber - b.attemptNumber);
145
+ const usageStatus = totals.pendingCalls || totals.unmeteredIncompleteAttempts
146
+ ? (totals.usageReceipts || totals.knownCostUsd ? "partial" : "unknown") : "known";
147
+ return { format: "toolsplice-attempt-ledger", version: 1, attempts, totals, usageStatus };
148
+ }
@@ -0,0 +1,4 @@
1
+ import type { CalibrationUsage } from "./calibration-ledger.js";
2
+ export declare function canUseCallMarkers(folder: string): boolean;
3
+ export declare function createCallMarker(folder: string, slot: string, id: string, key: string, startedAtMs: number): (usage: CalibrationUsage) => void;
4
+ export declare function readCallMarker(path: string, key: string, stamp: string, identity: string): Record<string, unknown>;
@@ -0,0 +1,77 @@
1
+ import { createHash } from "node:crypto";
2
+ import { closeSync, lstatSync, mkdirSync, openSync, readdirSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { CheckpointError, syncDirectory } from "./checkpoint-files.js";
5
+ const digest = (key, data) => createHash("sha256").update(key + "/" + data).digest("hex");
6
+ const uint = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
7
+ function receipt(path, identity) {
8
+ if (!lstatSync(path).isDirectory())
9
+ throw new CheckpointError(44);
10
+ const entries = readdirSync(path, { withFileTypes: true });
11
+ if (!entries.length)
12
+ return undefined;
13
+ const [entry] = entries;
14
+ if (entries.length !== 1 || !entry.isFile())
15
+ throw new CheckpointError(44);
16
+ const [kind, checksum, data, extra] = entry.name.split("~");
17
+ if (kind !== "usage" || data === undefined || extra !== undefined ||
18
+ checksum !== digest(identity, data))
19
+ throw new CheckpointError(44);
20
+ let fields;
21
+ try {
22
+ fields = JSON.parse(data);
23
+ }
24
+ catch {
25
+ throw new CheckpointError(44);
26
+ }
27
+ if (!Array.isArray(fields) || fields.length !== 4)
28
+ throw new CheckpointError(44);
29
+ const [receivedAtMs, costUsd, inputTokens, outputTokens] = fields;
30
+ if (!uint(receivedAtMs) || typeof costUsd !== "number" || !Number.isFinite(costUsd) || costUsd < 0 ||
31
+ !(inputTokens === null || uint(inputTokens)) || !(outputTokens === null || uint(outputTokens))) {
32
+ throw new CheckpointError(44);
33
+ }
34
+ return { receivedAtMs, costUsd, ...(inputTokens === null ? {} : { inputTokens }),
35
+ ...(outputTokens === null ? {} : { outputTokens }) };
36
+ }
37
+ export function canUseCallMarkers(folder) {
38
+ // Darwin PATH_MAX includes the terminating NUL. Reserve two NAME_MAX components and their separators.
39
+ // Old JSON checkpoints support deeper paths; choose their one-level layout before any paid dispatch.
40
+ return process.platform === "darwin" && Buffer.byteLength(folder) + 2 * (1 + 255) < 1024;
41
+ }
42
+ // The stable directory name holds the entire intent. Its only child name holds the entire receipt.
43
+ // Each transition has one atomic namespace operation and one full parent-directory sync.
44
+ // No user data lives in a file body. Never rename/remove an intent or overwrite a receipt.
45
+ export function createCallMarker(folder, slot, id, key, startedAtMs) {
46
+ const stamp = String(startedAtMs);
47
+ const identity = digest(key, stamp);
48
+ const path = join(folder, slot + ".call-" + id + "." + stamp + "." + identity + ".intent");
49
+ mkdirSync(path, { mode: 0o700 });
50
+ syncDirectory(folder);
51
+ let synced = false;
52
+ return (usage) => {
53
+ const existing = receipt(path, identity);
54
+ if (existing) {
55
+ if (existing.costUsd !== usage.costUsd || existing.inputTokens !== usage.inputTokens ||
56
+ existing.outputTokens !== usage.outputTokens)
57
+ throw new CheckpointError(44);
58
+ if (synced)
59
+ return;
60
+ }
61
+ else {
62
+ const data = JSON.stringify([Date.now(), usage.costUsd, usage.inputTokens ?? null, usage.outputTokens ?? null]);
63
+ const name = "usage~" + digest(identity, data) + "~" + data;
64
+ closeSync(openSync(join(path, name), "wx", 0o600));
65
+ }
66
+ // A failed sync may have left the exact receipt visible. Retry the sync before acknowledging it.
67
+ syncDirectory(path);
68
+ synced = true;
69
+ };
70
+ }
71
+ export function readCallMarker(path, key, stamp, identity) {
72
+ const startedAtMs = Number(stamp);
73
+ if (!uint(startedAtMs) || String(startedAtMs) !== stamp || identity !== digest(key, stamp))
74
+ throw new CheckpointError(44);
75
+ const usage = receipt(path, identity);
76
+ return usage ? { key, state: "received", startedAtMs, ...usage } : { key, state: "started", startedAtMs };
77
+ }
@@ -0,0 +1,33 @@
1
+ import { createContractFromCatalog } from "./contracts.js";
2
+ import type { SpliceBinding, SpliceEndpoint, SpliceSpec } from "./splice.js";
3
+ export interface CatalogSetup {
4
+ source: SpliceEndpoint;
5
+ target: SpliceSpec["target"];
6
+ sourceCatalog: Parameters<typeof createContractFromCatalog>[1];
7
+ targetCatalog: Parameters<typeof createContractFromCatalog>[1];
8
+ fixture: unknown;
9
+ fixtureFormat?: "decoded" | "mcp";
10
+ input?: Record<string, unknown>;
11
+ /** Map each row selected by this RFC 6901 pointer. The empty string selects a root array. */
12
+ each?: string;
13
+ maxItems?: number;
14
+ bindings: SpliceBinding[];
15
+ }
16
+ export declare function catalogFixture(sample: unknown, format?: string): unknown;
17
+ export declare function catalogSelection(config: Pick<CatalogSetup, "source" | "each" | "maxItems">): Pick<SpliceSpec, "source" | "forEach" | "maxItems">;
18
+ export declare function inspectCatalogMapping(config: Omit<CatalogSetup, "bindings">): {
19
+ sourcePaths: string[];
20
+ batch?: {
21
+ pointer: string;
22
+ rowCount: number;
23
+ rowsInspected: number;
24
+ maxItems: number;
25
+ } | undefined;
26
+ pathsTruncated: boolean;
27
+ requiredTargetPaths: string[];
28
+ sourceTool: string;
29
+ targetTool: string;
30
+ };
31
+ export declare function parseCatalogBinding(text: string): SpliceBinding;
32
+ /** Names only, for choosing explicit endpoint identities before opening sample data. */
33
+ export declare function catalogToolNames(catalog: unknown): string[];
@@ -0,0 +1,89 @@
1
+ // Catalogs and sampled paths are suggestions. Only explicit bindings enter a plan.
2
+ import { createContractFromCatalog } from "./contracts.js";
3
+ import { decode } from "./execution.js";
4
+ import { escapePointer, jsonObject } from "./workflow-json.js";
5
+ import { readSplicePath } from "./splice.js";
6
+ export function catalogFixture(sample, format = "decoded") {
7
+ if (format === "decoded")
8
+ return sample;
9
+ if (format !== "mcp" || !jsonObject(sample) || sample.isError ||
10
+ (sample.resultType !== undefined && sample.resultType !== "complete"))
11
+ throw new Error("Expected a complete successful MCP source response.");
12
+ try {
13
+ return decode(sample);
14
+ }
15
+ catch {
16
+ throw new Error("Cannot decode the MCP source response.");
17
+ }
18
+ }
19
+ export function catalogSelection(config) {
20
+ if (config.maxItems !== undefined && (config.each === undefined || !Number.isSafeInteger(config.maxItems) ||
21
+ config.maxItems < 1 || config.maxItems > 1000))
22
+ throw new Error("maxItems requires a batch and must be between 1 and 1000.");
23
+ if (config.each === undefined)
24
+ return { source: config.source };
25
+ if (typeof config.each !== "string")
26
+ throw new Error("Expected a batch selection pointer.");
27
+ readSplicePath(null, config.each);
28
+ return { source: { ...config.source, path: config.each }, forEach: true, ...(config.maxItems === undefined ? {} : { maxItems: config.maxItems }) };
29
+ }
30
+ export function inspectCatalogMapping(config) {
31
+ const source = createContractFromCatalog({ name: config.source.server }, config.sourceCatalog, { tools: [config.source.tool] });
32
+ const target = createContractFromCatalog({ name: config.target.server }, config.targetCatalog, { tools: [config.target.tool] });
33
+ const fixture = catalogFixture(config.fixture, config.fixtureFormat);
34
+ const selection = catalogSelection(config);
35
+ const paths = new Set();
36
+ let truncated = false, visited = 0;
37
+ function visit(value, path, depth) {
38
+ if (++visited > 4096 || (!paths.has(path) && paths.size >= 128)) {
39
+ truncated = true;
40
+ return;
41
+ }
42
+ paths.add(path);
43
+ if (value === null || typeof value !== "object")
44
+ return;
45
+ for (const [key, child] of Object.entries(value)) {
46
+ if (visited >= 4096 || paths.size >= 128 || depth >= 8) {
47
+ truncated = true;
48
+ break;
49
+ }
50
+ visit(child, path + "/" + escapePointer(key), depth + 1);
51
+ }
52
+ }
53
+ let batch;
54
+ if (config.each === undefined)
55
+ visit(fixture, "", 0);
56
+ else {
57
+ const selected = readSplicePath(fixture, config.each);
58
+ if (!selected.found || !Array.isArray(selected.value))
59
+ throw new Error("Batch selection must point to a fixture array.");
60
+ const rows = selected.value;
61
+ let inspected = 0;
62
+ for (const row of rows) {
63
+ if (visited >= 4096 || paths.size >= 128) {
64
+ truncated = true;
65
+ break;
66
+ }
67
+ visit(row, "", 0);
68
+ inspected++;
69
+ }
70
+ batch = { pointer: config.each, rowCount: rows.length, rowsInspected: inspected, maxItems: selection.maxItems ?? 100 };
71
+ }
72
+ const schema = target.tools[0].input;
73
+ const required = jsonObject(schema) && Array.isArray(schema.required) ? schema.required : [];
74
+ return { sourcePaths: [...paths], ...(batch ? { batch } : {}), pathsTruncated: truncated, requiredTargetPaths: required.map(k => "/" + escapePointer(String(k))),
75
+ sourceTool: source.tools[0].name, targetTool: target.tools[0].name };
76
+ }
77
+ export function parseCatalogBinding(text) {
78
+ const index = text.indexOf("=");
79
+ if (index < 0)
80
+ throw new Error("Use --bind '/destination=/source' with JSON pointers.");
81
+ return { to: text.slice(0, index), from: text.slice(index + 1) };
82
+ }
83
+ /** Names only, for choosing explicit endpoint identities before opening sample data. */
84
+ export function catalogToolNames(catalog) {
85
+ if (!jsonObject(catalog) || !Array.isArray(catalog.tools) ||
86
+ catalog.tools.some(t => !jsonObject(t) || typeof t.name !== "string" || !t.name))
87
+ throw new Error("Expected a tools/list catalog with named tools.");
88
+ return catalog.tools.map(t => t.name);
89
+ }
@@ -0,0 +1,10 @@
1
+ import type { ToolListEntry } from "./store.js";
2
+ export interface ToolCatalogPage<T extends ToolListEntry = ToolListEntry> {
3
+ tools: readonly T[];
4
+ nextCursor?: string;
5
+ }
6
+ export declare function toolPages<T extends ToolListEntry>(listPage: (cursor?: string) => Promise<ToolCatalogPage<T>>): AsyncGenerator<readonly T[]>;
7
+ /** Collect an initialized client's tools/list pages. The callback owns the transport and deadlines. */
8
+ export declare function collectToolCatalog<T extends ToolListEntry>(listPage: (cursor?: string) => Promise<ToolCatalogPage<T>>): Promise<{
9
+ tools: T[];
10
+ }>;
@@ -0,0 +1,42 @@
1
+ import { createHash } from "node:crypto";
2
+ import { copyJson, JSON_LIMIT, jsonObject } from "./workflow-json.js";
3
+ export async function* toolPages(listPage) {
4
+ let cursor;
5
+ const seen = new Set();
6
+ for (let i = 0; i < 1000; i++) {
7
+ const page = await listPage(cursor);
8
+ if (!page || !Array.isArray(page.tools))
9
+ throw new Error("Expected a tools/list page.");
10
+ yield page.tools;
11
+ const next = page.nextCursor;
12
+ if (next === undefined)
13
+ return;
14
+ if (typeof next !== "string" || Buffer.byteLength(next) > JSON_LIMIT)
15
+ throw new Error("Invalid tools/list cursor.");
16
+ const digest = createHash("sha256").update(next).digest("hex");
17
+ if (seen.has(digest))
18
+ throw new Error("Upstream repeated a tools/list cursor.");
19
+ seen.add(digest);
20
+ cursor = next;
21
+ }
22
+ throw new Error("Upstream tools/list exceeded the discovery page limit.");
23
+ }
24
+ /** Collect an initialized client's tools/list pages. The callback owns the transport and deadlines. */
25
+ export async function collectToolCatalog(listPage) {
26
+ const tools = [], names = new Set();
27
+ let bytes = Buffer.byteLength('{"tools":[]}');
28
+ for await (const page of toolPages(listPage)) {
29
+ for (const entry of page) {
30
+ const tool = copyJson(entry);
31
+ if (!jsonObject(tool) || typeof tool.name !== "string" || !tool.name || names.has(tool.name) ||
32
+ !jsonObject(tool.inputSchema) || (tool.outputSchema !== undefined && !jsonObject(tool.outputSchema)))
33
+ throw new Error("Catalog tools need distinct names and JSON schemas.");
34
+ bytes += Buffer.byteLength(JSON.stringify(tool)) + (tools.length ? 1 : 0);
35
+ if (bytes > JSON_LIMIT)
36
+ throw new Error("Combined tool catalog exceeds 5 MiB.");
37
+ tools.push(tool);
38
+ names.add(tool.name);
39
+ }
40
+ }
41
+ return copyJson({ tools });
42
+ }
@@ -0,0 +1,15 @@
1
+ export declare const checkpointMessages: {
2
+ readonly 41: "Checkpoint belongs to a different evaluation suite or context.";
3
+ readonly 42: "Checkpoint trial is active on this or another host.";
4
+ readonly 43: "The trial was interrupted before its grade was saved. Check recorded usage with evaluate --ledger before using --retry-incomplete.";
5
+ readonly 44: "Invalid calibration checkpoint. Restore an intact copy before resuming.";
6
+ };
7
+ export declare class CheckpointError extends Error {
8
+ readonly code: keyof typeof checkpointMessages;
9
+ constructor(code: keyof typeof checkpointMessages);
10
+ }
11
+ export declare function hasCode(error: unknown, code: string): boolean;
12
+ export declare function syncDirectory(dir: string): void;
13
+ export declare function publish(path: string, value: unknown, replace?: boolean): boolean;
14
+ export declare function read(path: string, maxBytes?: number): Record<string, unknown> | undefined;
15
+ export declare function active(record: Record<string, unknown>): boolean;