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,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,12 @@
1
+ import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
2
+ /**
3
+ * Wrap BEFORE connecting a client/server. Delivers inbound events in order,
4
+ * one per microtask, so SDK notification callbacks can run before a following
5
+ * response removes their progress handlers. No timers, pings or wire changes.
6
+ *
7
+ * Owns the underlying transport callbacks, just as Protocol.connect does.
8
+ * Methods/getters (including transport-specific extensions such as pid, stderr
9
+ * and terminateSession) retain their original receiver. Use a fresh wrapper for
10
+ * each connection; closing is idempotent and drains prior events before onclose.
11
+ */
12
+ export declare function orderedTransport<T extends Transport>(transport: T): T;
@@ -0,0 +1,106 @@
1
+ /**
2
+ * Wrap BEFORE connecting a client/server. Delivers inbound events in order,
3
+ * one per microtask, so SDK notification callbacks can run before a following
4
+ * response removes their progress handlers. No timers, pings or wire changes.
5
+ *
6
+ * Owns the underlying transport callbacks, just as Protocol.connect does.
7
+ * Methods/getters (including transport-specific extensions such as pid, stderr
8
+ * and terminateSession) retain their original receiver. Use a fresh wrapper for
9
+ * each connection; closing is idempotent and drains prior events before onclose.
10
+ */
11
+ export function orderedTransport(transport) {
12
+ const callbacks = {
13
+ onmessage: transport.onmessage, onerror: transport.onerror, onclose: transport.onclose,
14
+ };
15
+ const queue = [];
16
+ const idle = [];
17
+ let scheduled = false, closed = false, closeQueued = false, started = false;
18
+ let closing;
19
+ function schedule() {
20
+ if (scheduled || !queue.length)
21
+ return;
22
+ scheduled = true;
23
+ queueMicrotask(() => {
24
+ scheduled = false;
25
+ const delivery = queue.shift();
26
+ try {
27
+ if (delivery.kind === "close") {
28
+ closed = true;
29
+ callbacks.onclose?.();
30
+ }
31
+ else if (!closed && delivery.kind === "message")
32
+ callbacks.onmessage?.(delivery.message, delivery.extra);
33
+ else if (!closed && delivery.kind === "error")
34
+ callbacks.onerror?.(delivery.error);
35
+ }
36
+ catch (error) {
37
+ // Callback failure must not strand later responses or close waiters.
38
+ try {
39
+ callbacks.onerror?.(error instanceof Error ? error : new Error("Ordered transport callback failed."));
40
+ }
41
+ catch { }
42
+ }
43
+ finally {
44
+ schedule();
45
+ if (!queue.length && !scheduled)
46
+ for (const resolve of idle.splice(0))
47
+ resolve();
48
+ }
49
+ });
50
+ }
51
+ function enqueue(delivery) {
52
+ if (closed || closeQueued)
53
+ return;
54
+ if (delivery.kind === "close")
55
+ closeQueued = true;
56
+ queue.push(delivery);
57
+ schedule();
58
+ }
59
+ const start = async () => {
60
+ if (started)
61
+ throw new Error("Ordered transport already started; use a fresh wrapper per connection.");
62
+ if (closed || closeQueued)
63
+ throw new Error("Ordered transport is closed.");
64
+ started = true;
65
+ await transport.start();
66
+ };
67
+ const close = () => {
68
+ closing ??= (async () => {
69
+ await transport.close();
70
+ enqueue({ kind: "close" });
71
+ if (queue.length || scheduled)
72
+ await new Promise((resolve) => idle.push(resolve));
73
+ })();
74
+ return closing;
75
+ };
76
+ transport.onmessage = (message, extra) => enqueue({ kind: "message", message, extra });
77
+ transport.onerror = (error) => enqueue({ kind: "error", error });
78
+ transport.onclose = () => enqueue({ kind: "close" });
79
+ const bound = new Map();
80
+ return new Proxy(transport, {
81
+ get(target, key) {
82
+ if (key === "onmessage" || key === "onerror" || key === "onclose")
83
+ return callbacks[key];
84
+ if (key === "start")
85
+ return start;
86
+ if (key === "close")
87
+ return close;
88
+ const value = Reflect.get(target, key, target);
89
+ if (typeof value !== "function" || key === "constructor")
90
+ return value;
91
+ const existing = bound.get(key);
92
+ if (existing?.original === value)
93
+ return existing.value;
94
+ const fn = value.bind(target);
95
+ bound.set(key, { original: value, value: fn });
96
+ return fn;
97
+ },
98
+ set(target, key, value) {
99
+ if (key === "onmessage" || key === "onerror" || key === "onclose") {
100
+ Reflect.set(callbacks, key, value);
101
+ return true;
102
+ }
103
+ return Reflect.set(target, key, value, target);
104
+ },
105
+ });
106
+ }
@@ -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 {};