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,207 @@
1
+ import { setTimeout as delay } from "node:timers/promises";
2
+ import { collectToolCatalog } from "./catalog.js";
3
+ import { bindingOptions } from "./execution.js";
4
+ import { copyJson, jsonFingerprint, jsonObject } from "./workflow-json.js";
5
+ export const MCP_PROTOCOL_VERSION = "2026-07-28";
6
+ const taskExtension = "io.modelcontextprotocol/tasks";
7
+ const inputMethods = new Map([
8
+ ["elicitation/create", "elicitation"],
9
+ ["sampling/createMessage", "sampling"],
10
+ ["roots/list", "roots"],
11
+ ]);
12
+ /** Add the stateless request envelope to an application-owned, authenticated RPC transport.
13
+ * The exchange assigns a fresh JSON-RPC id per invocation and handles wire headers and streams. */
14
+ export function createMcpPeer(exchange, options) {
15
+ const info = copyJson(options.clientInfo), caps = copyJson(options.capabilities ?? {});
16
+ const rounds = options.maxInputRounds ?? 8, polls = options.maxPolls ?? 256;
17
+ if (typeof exchange !== "function" ||
18
+ !jsonObject(info) ||
19
+ !info.name ||
20
+ !info.version ||
21
+ typeof info.name !== "string" ||
22
+ typeof info.version !== "string" ||
23
+ !jsonObject(caps) ||
24
+ ![rounds, polls].every((n) => Number.isSafeInteger(n) && n >= 1))
25
+ throw new Error("Invalid MCP peer configuration.");
26
+ const onInput = options.onInputRequired, onTask = options.onTaskCreated;
27
+ const timeoutMs = bindingOptions({ timeoutMs: options.timeoutMs }).timeout;
28
+ const tasks = jsonObject(caps.extensions) && jsonObject(caps.extensions[taskExtension]);
29
+ async function timed(opts, work) {
30
+ const duration = bindingOptions(opts, { timeoutMs }).timeout;
31
+ const controller = new AbortController();
32
+ const signal = opts.signal
33
+ ? AbortSignal.any([opts.signal, controller.signal])
34
+ : controller.signal;
35
+ signal.throwIfAborted();
36
+ const timer = setTimeout(() => controller.abort(new Error("MCP request deadline exceeded.")), duration);
37
+ let rejectAbort = () => { };
38
+ const aborted = new Promise((_, reject) => {
39
+ rejectAbort = () => reject(signal.reason);
40
+ });
41
+ signal.addEventListener("abort", rejectAbort, { once: true });
42
+ try {
43
+ return await Promise.race([
44
+ aborted,
45
+ work({ ...opts, timeoutMs: duration, signal }),
46
+ ]);
47
+ }
48
+ finally {
49
+ clearTimeout(timer);
50
+ signal.removeEventListener("abort", rejectAbort);
51
+ }
52
+ }
53
+ async function send(method, params, opts) {
54
+ opts.signal?.throwIfAborted();
55
+ if (typeof method !== "string" ||
56
+ !method ||
57
+ !jsonObject(params) ||
58
+ (params._meta !== undefined && !jsonObject(params._meta)))
59
+ throw new Error("Invalid MCP request.");
60
+ const meta = {
61
+ ...params._meta,
62
+ "io.modelcontextprotocol/protocolVersion": MCP_PROTOCOL_VERSION,
63
+ "io.modelcontextprotocol/clientInfo": info,
64
+ "io.modelcontextprotocol/clientCapabilities": caps,
65
+ };
66
+ const raw = await exchange(method, copyJson({ ...params, _meta: meta }), opts);
67
+ opts.signal?.throwIfAborted();
68
+ const result = copyJson(raw, method === "resources/read" ? 97 * 1024 * 1024 : undefined);
69
+ if (!jsonObject(result))
70
+ throw new Error("Expected an MCP result object.");
71
+ return result;
72
+ }
73
+ async function inputResponses(requests, opts) {
74
+ if (!jsonObject(requests) || !onInput)
75
+ throw new Error("This request needs an application input handler.");
76
+ for (const r of Object.values(requests)) {
77
+ const capability = jsonObject(r) && inputMethods.get(String(r.method));
78
+ if (!capability || !jsonObject(caps[capability]))
79
+ throw new Error("Unadvertised input request.");
80
+ if (capability === "elicitation") {
81
+ const modes = caps[capability];
82
+ const mode = jsonObject(r.params) ? (r.params.mode ?? "form") : "form";
83
+ if ((mode !== "form" && mode !== "url") ||
84
+ (!(mode === "form" && !Object.keys(modes).length) &&
85
+ !jsonObject(modes[mode])))
86
+ throw new Error("Unadvertised elicitation mode.");
87
+ }
88
+ }
89
+ const responses = copyJson(await onInput(copyJson(requests), opts));
90
+ if (!jsonObject(responses) ||
91
+ Object.keys(responses).length !== Object.keys(requests).length ||
92
+ Object.keys(requests).some((k) => !Object.hasOwn(responses, k) || !jsonObject(responses[k])))
93
+ throw new Error("Provide one response object per requested input.");
94
+ return responses;
95
+ }
96
+ function complete(raw) {
97
+ if (!jsonObject(raw) ||
98
+ (Object.hasOwn(raw, "resultType") && raw.resultType !== "complete"))
99
+ throw new Error("Expected a completed MCP tool result.");
100
+ return { ...raw, resultType: "complete" };
101
+ }
102
+ async function pollTask(id, opts, firstDelay = 0) {
103
+ if (!tasks || typeof id !== "string" || !id)
104
+ throw new Error("Task polling needs an enabled extension and a task ID.");
105
+ let wait = firstDelay, inputs = 0;
106
+ const acknowledged = new Map();
107
+ for (let n = 0; n < polls; n++) {
108
+ if (!Number.isSafeInteger(wait) || wait < 0)
109
+ throw new Error("Invalid task poll interval.");
110
+ // A longer interval still respects the overall deadline and never wraps a Node timer.
111
+ if (wait)
112
+ await delay(Math.min(wait, opts.timeoutMs), undefined, {
113
+ signal: opts.signal,
114
+ });
115
+ const state = complete(await send("tasks/get", { taskId: id }, opts));
116
+ if (state.taskId !== id)
117
+ throw new Error("Unexpected task response.");
118
+ if (state.status === "completed")
119
+ return complete(state.result);
120
+ if (state.status === "failed" || state.status === "cancelled")
121
+ throw new Error("MCP task " + state.status + ".");
122
+ if (state.status === "input_required") {
123
+ if (!jsonObject(state.inputRequests))
124
+ throw new Error("Invalid task input requests.");
125
+ const pending = Object.entries(state.inputRequests).filter(([key, item]) => {
126
+ const prior = acknowledged.get(key);
127
+ if (prior !== undefined && prior !== jsonFingerprint(item))
128
+ throw new Error("Task reused an acknowledged input key for a different request.");
129
+ return prior === undefined;
130
+ });
131
+ if (pending.length) {
132
+ if (++inputs > rounds)
133
+ throw new Error("MCP input round limit exceeded.");
134
+ const responses = await inputResponses(Object.fromEntries(pending), opts);
135
+ const ack = await send("tasks/update", { taskId: id, inputResponses: responses }, opts);
136
+ complete(ack);
137
+ for (const [key, item] of pending)
138
+ acknowledged.set(key, jsonFingerprint(item));
139
+ }
140
+ }
141
+ else if (state.status !== "working")
142
+ throw new Error("Unexpected task status.");
143
+ wait = (state.pollIntervalMs ?? 1000);
144
+ }
145
+ throw new Error("MCP task poll limit exceeded.");
146
+ }
147
+ const request = (method, params = {}, opts = {}) => timed(opts, (o) => send(method, params, o));
148
+ const resolve = (method, args, opts = {}) => timed(opts, async (o) => {
149
+ if (!["tools/call", "prompts/get", "resources/read"].includes(method) ||
150
+ !jsonObject(args) ||
151
+ Object.hasOwn(args, "inputResponses") ||
152
+ Object.hasOwn(args, "requestState"))
153
+ throw new Error("Expected an initial MCP tool, prompt or resource request.");
154
+ const original = copyJson(args);
155
+ let params = original;
156
+ for (let n = 0;; n++) {
157
+ const result = await send(method, params, o);
158
+ if (result.resultType === "task") {
159
+ if (method !== "tools/call" ||
160
+ !tasks ||
161
+ typeof result.taskId !== "string" ||
162
+ !result.taskId)
163
+ throw new Error("Unexpected task handle.");
164
+ await onTask?.(result.taskId);
165
+ return pollTask(result.taskId, o, (result.pollIntervalMs ?? 1000));
166
+ }
167
+ if (result.resultType !== "input_required")
168
+ return complete(result);
169
+ if (n >= rounds)
170
+ throw new Error("MCP input round limit exceeded.");
171
+ if ((result.inputRequests === undefined &&
172
+ result.requestState === undefined) ||
173
+ (result.requestState !== undefined &&
174
+ typeof result.requestState !== "string"))
175
+ throw new Error("Invalid input_required result.");
176
+ params = { ...original };
177
+ if (result.requestState !== undefined)
178
+ params.requestState = result.requestState;
179
+ if (result.inputRequests !== undefined)
180
+ params.inputResponses = await inputResponses(result.inputRequests, o);
181
+ }
182
+ });
183
+ return {
184
+ request,
185
+ resolve,
186
+ async callTool(tool, opts = {}) {
187
+ if (!jsonObject(tool) ||
188
+ typeof tool.name !== "string" ||
189
+ !tool.name ||
190
+ !jsonObject(tool.arguments))
191
+ throw new Error("Expected a named MCP tool and argument object.");
192
+ return resolve("tools/call", tool, opts);
193
+ },
194
+ discover: (opts = {}) => request("server/discover", {}, opts),
195
+ catalog: (opts = {}) => timed(opts, (o) => collectToolCatalog(async (cursor) => {
196
+ const page = await send("tools/list", cursor === undefined ? {} : { cursor }, o);
197
+ complete(page);
198
+ return page;
199
+ })),
200
+ resumeTask: (id, opts = {}) => timed(opts, (o) => pollTask(id, o)),
201
+ cancelTask: (id, opts = {}) => {
202
+ if (!tasks || typeof id !== "string" || !id)
203
+ throw new Error("Task cancellation needs an enabled extension and a task ID.");
204
+ return request("tasks/cancel", { taskId: id }, opts).then(complete);
205
+ },
206
+ };
207
+ }
@@ -0,0 +1,21 @@
1
+ export interface McpServerCardOptions {
2
+ /** Reverse-DNS namespace and server name, such as com.example/search. */
3
+ name: string;
4
+ version: string;
5
+ description: string;
6
+ /** The concrete Streamable HTTP endpoint advertised by this card. */
7
+ url: string;
8
+ supportedProtocolVersions?: string[];
9
+ }
10
+ /** Build a public v1 Server Card for a concrete endpoint. Serving the document belongs to the application. */
11
+ export declare function createMcpServerCard(options: McpServerCardOptions): {
12
+ $schema: string;
13
+ name: string;
14
+ version: string;
15
+ description: string;
16
+ remotes: {
17
+ type: "streamable-http";
18
+ url: string;
19
+ supportedProtocolVersions?: string[] | undefined;
20
+ }[];
21
+ };
@@ -0,0 +1,54 @@
1
+ import { copyJson } from "./workflow-json.js";
2
+ /** Build a public v1 Server Card for a concrete endpoint. Serving the document belongs to the application. */
3
+ export function createMcpServerCard(options) {
4
+ const { name, version, description, url, supportedProtocolVersions } = copyJson(options);
5
+ if (typeof name !== "string" ||
6
+ name.length > 200 ||
7
+ !/^[a-zA-Z0-9.-]+\/[a-zA-Z0-9._-]+$/.test(name) ||
8
+ typeof version !== "string" ||
9
+ !version ||
10
+ [...version].length > 255 ||
11
+ /^[~^<>=]/.test(version) ||
12
+ /(?:^|\.)(?:\*|x)(?:\.|$)/i.test(version) ||
13
+ typeof description !== "string" ||
14
+ !description.length ||
15
+ [...description].length > 100)
16
+ throw new Error("Invalid MCP Server Card name, version or description.");
17
+ let endpoint;
18
+ try {
19
+ endpoint = new URL(url);
20
+ }
21
+ catch {
22
+ throw new Error("Expected a concrete HTTP(S) endpoint.");
23
+ }
24
+ if (typeof url !== "string" ||
25
+ !/^https?:\/\//.test(url) ||
26
+ !endpoint.hostname ||
27
+ endpoint.username ||
28
+ endpoint.password ||
29
+ endpoint.hash ||
30
+ /[\s{}\\]/u.test(url))
31
+ throw new Error("Expected a concrete HTTP(S) endpoint without embedded credentials or fragment.");
32
+ if (supportedProtocolVersions !== undefined &&
33
+ (!Array.isArray(supportedProtocolVersions) ||
34
+ !supportedProtocolVersions.length ||
35
+ supportedProtocolVersions.some((v) => typeof v !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(v)) ||
36
+ new Set(supportedProtocolVersions).size !==
37
+ supportedProtocolVersions.length))
38
+ throw new Error("Provide distinct MCP protocol version dates.");
39
+ return {
40
+ $schema: "https://static.modelcontextprotocol.io/schemas/v1/server-card.schema.json",
41
+ name,
42
+ version,
43
+ description,
44
+ remotes: [
45
+ {
46
+ type: "streamable-http",
47
+ url,
48
+ ...(supportedProtocolVersions === undefined
49
+ ? {}
50
+ : { supportedProtocolVersions }),
51
+ },
52
+ ],
53
+ };
54
+ }
@@ -0,0 +1,71 @@
1
+ import type { FinalAnswerStore } from "./final-answer-stores.js";
2
+ import { type PageReadOptions } from "./read-pages.js";
3
+ type Storage = {
4
+ directory: string;
5
+ store?: never;
6
+ } | {
7
+ store: FinalAnswerStore;
8
+ directory?: never;
9
+ };
10
+ export type PageCheckpoint = Storage & {
11
+ jobId: string;
12
+ context: Record<string, unknown>;
13
+ };
14
+ export type PageOutcome<T> = {
15
+ state: "complete";
16
+ result: T;
17
+ } | {
18
+ state: "deferred";
19
+ page: number;
20
+ retryAt: number;
21
+ } | {
22
+ state: "busy" | "expired";
23
+ page: number;
24
+ };
25
+ /** The source adapter can explicitly report that its saved snapshot cursor expired. */
26
+ export declare class ExpiredPageCursorError extends Error {
27
+ }
28
+ /** The dispatched source read may have completed. Keep its claim for reconciliation. */
29
+ export declare class UncertainPageReadError extends Error {
30
+ readonly name = "UncertainPageReadError";
31
+ }
32
+ export interface PageAttempt {
33
+ /** Stable key for this source attempt. Use it to retain or retrieve a source receipt. */
34
+ key: string;
35
+ page: number;
36
+ attempt: number;
37
+ cursor: string | null;
38
+ }
39
+ export type PageInspection = {
40
+ state: "complete";
41
+ acceptedPages: number;
42
+ } | (PageAttempt & {
43
+ state: "ready" | "outcome_unknown" | "expired" | "failed";
44
+ acceptedPages: number;
45
+ }) | (PageAttempt & {
46
+ state: "deferred";
47
+ acceptedPages: number;
48
+ retryAt: number;
49
+ });
50
+ type Reader<P> = (attempt: PageAttempt, signal?: AbortSignal) => P | PromiseLike<P>;
51
+ export interface PageJob<P, T> {
52
+ /** Replay saved pages, then dispatch the first available page through read. */
53
+ run(read: Reader<P>): Promise<PageOutcome<T>>;
54
+ /** Read durable progress without contacting the source or claiming work. */
55
+ inspect(): Promise<PageInspection>;
56
+ /** Save the source-confirmed response for this attempt. An identical confirmation is safe to repeat. */
57
+ confirm(key: string, page: P): Promise<void>;
58
+ }
59
+ type Projection<P, T> = {
60
+ project(page: P): {
61
+ part: unknown;
62
+ bytes: number;
63
+ };
64
+ append(part: unknown): void;
65
+ finish(): T;
66
+ };
67
+ /** Bound to one query and snapshot. Every invocation builds its own accumulator. */
68
+ export declare function createPageJob<P extends {
69
+ nextCursor?: string | null;
70
+ }, T>(checkpoint: PageCheckpoint, kind: string, query: unknown, options: PageReadOptions, projection: () => Projection<P, T>): PageJob<P, T>;
71
+ export {};
@@ -0,0 +1,286 @@
1
+ import { isDeepStrictEqual } from "node:util";
2
+ import { createHash } from "node:crypto";
3
+ import { mkdirSync } from "node:fs";
4
+ import { join, resolve } from "node:path";
5
+ import { publish, read as readRecord, syncDirectory, } from "./checkpoint-files.js";
6
+ import { abortable } from "./abortable.js";
7
+ import { pageLimits, RetryablePageError, utf8Bytes, } from "./read-pages.js";
8
+ import { jsonFingerprint, jsonObject } from "./workflow-json.js";
9
+ /** The source adapter can explicitly report that its saved snapshot cursor expired. */
10
+ export class ExpiredPageCursorError extends Error {
11
+ }
12
+ /** The dispatched source read may have completed. Keep its claim for reconciliation. */
13
+ export class UncertainPageReadError extends Error {
14
+ name = "UncertainPageReadError";
15
+ }
16
+ function fileStore(directory) {
17
+ let initialized = false;
18
+ const path = (job) => join(directory, "pages-" + job);
19
+ return {
20
+ async read(job) {
21
+ const saved = readRecord(path(job) + ".json", 96 * 1024 * 1024);
22
+ if (saved) {
23
+ if (typeof saved.identity !== "string" ||
24
+ typeof saved.payload !== "string")
25
+ throw new Error("Invalid page checkpoint.");
26
+ return { identity: saved.identity, payload: saved.payload };
27
+ }
28
+ const claim = readRecord(path(job) + ".claim");
29
+ return claim ? { identity: String(claim.identity), payload: null } : null;
30
+ },
31
+ async claim(job, identity) {
32
+ if (!initialized) {
33
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
34
+ initialized = true;
35
+ }
36
+ return publish(path(job) + ".claim", { identity });
37
+ },
38
+ async complete(job, identity, payload) {
39
+ const saved = publish(path(job) + ".json", { identity, payload });
40
+ if (!saved)
41
+ syncDirectory(directory);
42
+ return saved;
43
+ },
44
+ };
45
+ }
46
+ const digest = (body) => createHash("sha256").update(body).digest("hex");
47
+ function decode(encoded, normalizeZero = false) {
48
+ if (typeof encoded !== "string" ||
49
+ Buffer.byteLength(encoded) > 16 * 1024 * 1024)
50
+ throw new Error("Invalid page checkpoint.");
51
+ const body = encoded.slice(65);
52
+ if (encoded[64] !== "\n" || digest(body) !== encoded.slice(0, 64))
53
+ throw new Error("Invalid page checkpoint digest.");
54
+ const entry = normalizeZero
55
+ ? JSON.parse(body, (_key, value) => (value === 0 ? 0 : value))
56
+ : JSON.parse(body);
57
+ if (!jsonObject(entry) ||
58
+ !["page", "retry", "expired", "failed"].includes(String(entry.kind)))
59
+ throw new Error("Invalid page checkpoint entry.");
60
+ return entry;
61
+ }
62
+ function encode(entry) {
63
+ const body = JSON.stringify(entry);
64
+ if (Buffer.byteLength(body) > 12 * 1024 * 1024)
65
+ throw new Error("Page contribution exceeds the 12 MiB checkpoint limit.");
66
+ return digest(body) + "\n" + body;
67
+ }
68
+ function sameContribution(saved, candidate) {
69
+ if (saved === candidate)
70
+ return true;
71
+ // Older Python records may spell JSON zero as -0.0. Normalize it to the JS wire form.
72
+ return isDeepStrictEqual(decode(saved, true), decode(candidate));
73
+ }
74
+ // Another worker can confirm the same source contribution before the original writer returns.
75
+ async function save(backend, job, identity, payload) {
76
+ if (await backend.complete(job, identity, payload))
77
+ return;
78
+ const row = await backend.read(job);
79
+ if (row?.identity !== identity ||
80
+ row.payload === null ||
81
+ !sameContribution(row.payload, payload))
82
+ throw new Error("Conflicting or unacknowledged page checkpoint.");
83
+ }
84
+ /** Bound to one query and snapshot. Every invocation builds its own accumulator. */
85
+ export function createPageJob(checkpoint, kind, query, options, projection) {
86
+ const { maxPages, maxBytes } = pageLimits(options);
87
+ const { jobId, context, directory, store } = checkpoint;
88
+ const { maxReadAttempts = 3, maxRetryWaitMs = 60000, signal } = options;
89
+ if (typeof jobId !== "string" ||
90
+ !jobId ||
91
+ !jsonObject(context) ||
92
+ (store === undefined
93
+ ? typeof directory !== "string" || !directory
94
+ : !store || directory !== undefined))
95
+ throw new TypeError("Choose a page checkpoint directory or store, job ID and context.");
96
+ if (!Number.isInteger(maxReadAttempts) ||
97
+ maxReadAttempts < 1 ||
98
+ maxReadAttempts > 5 ||
99
+ !Number.isInteger(maxRetryWaitMs) ||
100
+ maxRetryWaitMs < 0 ||
101
+ maxRetryWaitMs > 60000)
102
+ throw new RangeError("Invalid page retry limits.");
103
+ const folder = directory === undefined ? undefined : resolve(directory);
104
+ const backend = store ?? fileStore(folder);
105
+ const format = "toolsplice-pages-v1";
106
+ const scope = jsonFingerprint({
107
+ format,
108
+ jobId,
109
+ context,
110
+ kind,
111
+ query,
112
+ maxPages,
113
+ maxBytes,
114
+ maxReadAttempts,
115
+ maxRetryWaitMs,
116
+ });
117
+ async function traverse(op) {
118
+ const { project, append, finish } = projection();
119
+ const missing = () => {
120
+ throw new Error("No matching claimed page attempt.");
121
+ };
122
+ const seen = new Set();
123
+ let cursor;
124
+ let claimNext = false;
125
+ let bytes = 0, remaining = maxRetryWaitMs;
126
+ function contribution(received, page) {
127
+ const next = received.nextCursor ?? null;
128
+ if (next !== null &&
129
+ (typeof next !== "string" ||
130
+ utf8Bytes(next) > 4096 ||
131
+ seen.has(next) ||
132
+ page === maxPages))
133
+ throw new Error("Invalid continuation or page limit exceeded.");
134
+ const data = project(received);
135
+ if (bytes + data.bytes > maxBytes)
136
+ throw new Error("Read exceeded the byte limit.");
137
+ return { kind: "page", next, ...data };
138
+ }
139
+ for (let page = 1; page <= maxPages; page++) {
140
+ for (let attempt = 1; attempt <= maxReadAttempts; attempt++) {
141
+ signal?.throwIfAborted();
142
+ const job = jsonFingerprint([format, jobId, page, attempt]);
143
+ const identity = jsonFingerprint([
144
+ scope,
145
+ page,
146
+ attempt,
147
+ cursor ?? null,
148
+ ]);
149
+ // After saving a fresh page, the next database key is usually absent.
150
+ // A lost claim still reads the winner's row and validates its identity.
151
+ const ownsClaim = claimNext && (await backend.claim(job, identity));
152
+ const row = ownsClaim ? null : await backend.read(job);
153
+ if (row && row.identity !== identity)
154
+ throw new Error("Page checkpoint identity mismatch.");
155
+ const receipt = {
156
+ key: identity,
157
+ page,
158
+ attempt,
159
+ cursor: cursor ?? null,
160
+ };
161
+ const position = { ...receipt, acceptedPages: page - 1 };
162
+ if (op.mode === "confirm" && op.key === identity) {
163
+ if (!row)
164
+ return missing();
165
+ const payload = encode(contribution(op.value, page));
166
+ if (row.payload === null)
167
+ await save(backend, job, identity, payload);
168
+ else {
169
+ if (!sameContribution(row.payload, payload))
170
+ throw new Error("Conflicting page confirmation.");
171
+ // A concurrent file publisher may still be syncing this visible directory entry.
172
+ if (folder)
173
+ syncDirectory(folder);
174
+ }
175
+ return;
176
+ }
177
+ let entry;
178
+ if (row?.payload != null) {
179
+ entry = decode(row.payload);
180
+ claimNext = false;
181
+ }
182
+ else {
183
+ if (op.mode === "inspect")
184
+ return { ...position, state: row ? "outcome_unknown" : "ready" };
185
+ if (op.mode === "confirm")
186
+ return missing();
187
+ if (!ownsClaim &&
188
+ (row || claimNext || !(await backend.claim(job, identity))))
189
+ return { state: "busy", page };
190
+ let cause;
191
+ let reading = true;
192
+ try {
193
+ const received = await abortable(() => op.read(receipt, signal), signal);
194
+ reading = false;
195
+ entry = contribution(received, page);
196
+ }
197
+ catch (error) {
198
+ signal?.throwIfAborted();
199
+ if (reading && error instanceof UncertainPageReadError)
200
+ throw error;
201
+ cause = error;
202
+ entry = {
203
+ kind: reading && error instanceof ExpiredPageCursorError
204
+ ? "expired"
205
+ : "failed",
206
+ };
207
+ if (reading &&
208
+ error instanceof RetryablePageError &&
209
+ attempt < maxReadAttempts) {
210
+ const delay = Math.max(error.retryAfterMs ?? 0, Math.floor(100 * 2 ** (attempt - 1) * (1 + Math.random())));
211
+ if (delay <= remaining)
212
+ entry = { kind: "retry", delay, at: Date.now() + delay };
213
+ }
214
+ }
215
+ let payload;
216
+ try {
217
+ payload = encode(entry);
218
+ }
219
+ catch (error) {
220
+ cause = error;
221
+ entry = { kind: "failed" };
222
+ payload = encode(entry);
223
+ }
224
+ await save(backend, job, identity, payload);
225
+ claimNext = store !== undefined;
226
+ if (entry.kind === "failed")
227
+ throw cause;
228
+ }
229
+ if (entry.kind === "expired" || entry.kind === "failed") {
230
+ if (op.mode === "inspect")
231
+ return { ...position, state: entry.kind };
232
+ if (op.mode === "confirm")
233
+ return missing();
234
+ }
235
+ if (entry.kind === "expired")
236
+ return { state: "expired", page };
237
+ if (entry.kind === "failed")
238
+ throw new Error("Page read previously failed for this job.");
239
+ if (entry.kind === "retry") {
240
+ if (!Number.isSafeInteger(entry.delay) ||
241
+ entry.delay < 0 ||
242
+ entry.delay > remaining ||
243
+ !Number.isSafeInteger(entry.at) ||
244
+ attempt >= maxReadAttempts)
245
+ throw new Error("Invalid saved page retry.");
246
+ remaining -= entry.delay;
247
+ if (Date.now() < entry.at) {
248
+ if (op.mode === "confirm")
249
+ return missing();
250
+ return op.mode === "inspect"
251
+ ? { ...position, state: "deferred", retryAt: entry.at }
252
+ : { state: "deferred", page, retryAt: entry.at };
253
+ }
254
+ continue;
255
+ }
256
+ if (entry.kind !== "page" ||
257
+ !Number.isSafeInteger(entry.bytes) ||
258
+ entry.bytes < 0 ||
259
+ (bytes += entry.bytes) > maxBytes)
260
+ throw new Error("Invalid saved page size.");
261
+ if (op.mode === "run")
262
+ append(entry.part);
263
+ if (entry.next === null) {
264
+ if (op.mode === "confirm")
265
+ return missing();
266
+ return op.mode === "inspect"
267
+ ? { state: "complete", acceptedPages: page }
268
+ : { state: "complete", result: finish() };
269
+ }
270
+ if (typeof entry.next !== "string" ||
271
+ utf8Bytes(entry.next) > 4096 ||
272
+ seen.has(entry.next))
273
+ throw new Error("Invalid saved continuation.");
274
+ cursor = entry.next;
275
+ seen.add(cursor);
276
+ break;
277
+ }
278
+ }
279
+ throw new Error("Read exceeded the page limit.");
280
+ }
281
+ return {
282
+ run: (read) => traverse({ mode: "run", read }),
283
+ inspect: () => traverse({ mode: "inspect" }),
284
+ confirm: (key, value) => traverse({ mode: "confirm", key, value }),
285
+ };
286
+ }
@@ -0,0 +1,15 @@
1
+ export interface PageReadGateOptions {
2
+ /** Minimum interval between starts, shared by reads using this gate. */
3
+ minIntervalMs: number;
4
+ /** Refuse a remaining source cooldown longer than this. Queueing is cancellable. Default 60 s. */
5
+ maxCooldownMs?: number;
6
+ }
7
+ /** One in-process upstream queue. Share the instance across idempotent readers. */
8
+ export declare class PageReadGate {
9
+ private tail;
10
+ private nextStart;
11
+ private readonly minIntervalMs;
12
+ private readonly maxCooldownMs;
13
+ constructor({ minIntervalMs, maxCooldownMs }: PageReadGateOptions);
14
+ read<T>(read: () => T | PromiseLike<T>, signal?: AbortSignal): Promise<T>;
15
+ }