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
@@ -1,4 +1,4 @@
1
- import { type ContractSnapshot } from "./contracts.js";
1
+ import { type ContractSnapshot, type ContractSchema } from "./contracts.js";
2
2
  import { type ToolCaller } from "./execution.js";
3
3
  export interface ContractIssue {
4
4
  path: string;
@@ -10,6 +10,7 @@ export declare class ContractValidationError extends Error {
10
10
  readonly issues: ContractIssue[];
11
11
  constructor(tool: string, stage: "input" | "output" | "contract", issues: ContractIssue[]);
12
12
  }
13
+ export declare function createGuardCompiler(): (schema: ContractSchema | null, tool: string, stage: string) => import("ajv/dist/core.js").AnyValidateFunction<unknown>;
13
14
  export interface ContractCallerOptions {
14
15
  /** Both default true. Disabling one stage is explicit; unknown tools always fail before dispatch. */
15
16
  inputs?: boolean;
@@ -1,7 +1,7 @@
1
1
  // Opt-in guards for reviewed tool contracts. The default proxy/bindings stay pass-through.
2
2
  import { Ajv } from "ajv";
3
- import { RE2JS } from "re2js";
4
- import { compilePattern } from "./pattern.js";
3
+ import { compileUnevaluated } from "./unevaluated.js";
4
+ import { compileEnginePattern, compilePattern } from "./pattern.js";
5
5
  import { Ajv2020 } from "ajv/dist/2020.js";
6
6
  import { assertContractJson } from "./contract-schema.js";
7
7
  import { parseContractSnapshot, } from "./contracts.js";
@@ -119,7 +119,7 @@ const MODERN = new Set([
119
119
  "unevaluatedProperties",
120
120
  "unevaluatedItems",
121
121
  ]);
122
- function guardedSchema(schema, tool, path = "", draft7 = false, budget = { patterns: 0 }) {
122
+ function guardedSchema(schema, tool, path = "", draft7 = false, budget = { patterns: 0, unevaluated: false }) {
123
123
  if (typeof schema === "boolean")
124
124
  return schema;
125
125
  if (!isObject(schema))
@@ -151,6 +151,8 @@ function guardedSchema(schema, tool, path = "", draft7 = false, budget = { patte
151
151
  throw new ContractValidationError(tool, "contract", [
152
152
  { path: `${path}/uniqueItems`, keyword: "requires-bounded-maxItems" },
153
153
  ]);
154
+ if (schema.unevaluatedItems !== undefined || schema.unevaluatedProperties !== undefined)
155
+ budget.unevaluated = true;
154
156
  if (schema.pattern !== undefined) {
155
157
  if (typeof schema.pattern !== "string" ||
156
158
  schema.pattern.length > 1024 ||
@@ -167,7 +169,7 @@ function guardedSchema(schema, tool, path = "", draft7 = false, budget = { patte
167
169
  ]);
168
170
  }
169
171
  }
170
- return Object.fromEntries(Object.entries(schema)
172
+ const guarded = Object.fromEntries(Object.entries(schema)
171
173
  .filter(([key]) => !IGNORE.has(key) && !key.startsWith("x-"))
172
174
  .map(([key, value]) => {
173
175
  const p = `${path}/${pointer(key)}`;
@@ -211,28 +213,31 @@ function guardedSchema(schema, tool, path = "", draft7 = false, budget = { patte
211
213
  ];
212
214
  return [key, value];
213
215
  }));
216
+ // Draft 2020-12 permits an empty enum. It matches no instance. Preserve all
217
+ // other schema locations, including definitions addressed by local refs.
218
+ if (!draft7 && Array.isArray(guarded.enum) && !guarded.enum.length &&
219
+ (guarded.allOf === undefined || Array.isArray(guarded.allOf))) {
220
+ delete guarded.enum;
221
+ guarded.allOf = [...(guarded.allOf ?? []), false];
222
+ }
223
+ return guarded;
214
224
  }
215
- /** Compile once, then enforce a detached snapshot before inputs and after decoded outputs.
216
- * Raw successful results are returned unchanged for generated bindings or SDK consumers.
217
- * MCP error and unfinished results pass through for normal SDK/binding error handling.
218
- * Reviewed schemas are trusted configuration, not an arbitrary-schema execution sandbox. */
219
- export function createContractCaller(caller, source, options = {}) {
220
- const snapshot = parseContractSnapshot(source);
221
- const inputs = options.inputs ?? true, outputs = options.outputs ?? true;
225
+ export function createGuardCompiler() {
222
226
  const validatorOptions = {
223
227
  strict: false,
224
228
  validateFormats: false,
225
229
  allErrors: false,
226
230
  addUsedSchema: false,
227
231
  ownProperties: true,
232
+ // The loop tests property existence directly, including the empty JSON key.
233
+ loopRequired: 1,
228
234
  logger: false,
229
235
  code: {
230
- regExp: Object.assign((pattern, _flags) => RE2JS.compile(pattern), { code: "toolspliceRE2" }),
236
+ regExp: Object.assign((pattern, _flags) => compileEnginePattern(pattern), { code: "toolspliceRE2" }),
231
237
  },
232
238
  };
233
239
  const ajv = new Ajv2020(validatorOptions), ajv7 = new Ajv(validatorOptions);
234
- const validators = new Map();
235
- const compile = (schema, tool, stage) => {
240
+ return (schema, tool, stage) => {
236
241
  if (schema === null)
237
242
  throw new ContractValidationError(tool, "contract", [
238
243
  { path: `/${stage}`, keyword: "unobserved-output" },
@@ -246,8 +251,11 @@ export function createContractCaller(caller, source, options = {}) {
246
251
  ]);
247
252
  }
248
253
  const draft7 = isObject(schema) && DRAFT7.has(String(schema.$schema));
249
- const safe = guardedSchema(schema, tool, `/${stage}`, draft7);
254
+ const budget = { patterns: 0, unevaluated: false };
255
+ const safe = guardedSchema(schema, tool, `/${stage}`, draft7, budget);
250
256
  try {
257
+ if (budget.unevaluated)
258
+ return compileUnevaluated(safe, validatorOptions);
251
259
  return (draft7 ? ajv7 : ajv).compile(safe);
252
260
  }
253
261
  catch {
@@ -256,6 +264,16 @@ export function createContractCaller(caller, source, options = {}) {
256
264
  ]);
257
265
  }
258
266
  };
267
+ }
268
+ /** Compile once, then enforce a detached snapshot before inputs and after decoded outputs.
269
+ * Raw successful results are returned unchanged for generated bindings or SDK consumers.
270
+ * MCP error and unfinished results pass through for normal SDK/binding error handling.
271
+ * Reviewed schemas are trusted configuration, not an arbitrary-schema execution sandbox. */
272
+ export function createContractCaller(caller, source, options = {}) {
273
+ const snapshot = parseContractSnapshot(source);
274
+ const inputs = options.inputs ?? true, outputs = options.outputs ?? true;
275
+ const compile = createGuardCompiler();
276
+ const validators = new Map();
259
277
  for (const tool of snapshot.tools)
260
278
  validators.set(tool.name, {
261
279
  input: inputs ? compile(tool.input, tool.name, "input") : undefined,
@@ -301,7 +319,8 @@ export function createContractCaller(caller, source, options = {}) {
301
319
  raw.resultType !== undefined &&
302
320
  raw.resultType !== "complete"))
303
321
  return raw;
304
- check(validator.output, decode(raw), request.name, "output");
322
+ if (validator.output)
323
+ check(validator.output, decode(raw), request.name, "output");
305
324
  return raw;
306
325
  };
307
326
  }
@@ -1,5 +1,7 @@
1
1
  /** Reject cycles, excessive work, and non-JSON library inputs before hashing or compiling. */
2
- export declare function assertContractJson(value: unknown, maxNodes?: number, maxDepth?: number): void;
2
+ export declare function assertContractJson(value: unknown, maxNodes?: number, maxDepth?: number, maxStringBytes?: number): void;
3
+ /** Check routing annotations in schema positions. Call on a bounded tools/list schema. */
4
+ export declare function validMcpHeaderSchema(root: unknown): boolean;
3
5
  /** Declared constraints matter even when inference deliberately omits observed numeric ranges.
4
6
  * Annotation keywords are removed only at schema positions, never from literal values/field names. */
5
7
  export declare function definitionContract(schema: unknown): unknown;
@@ -35,16 +35,16 @@ const SET_ARRAYS = new Set(["required", "type", "enum"]);
35
35
  const cmp = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
36
36
  const isObject = (v) => !!v && typeof v === "object" && !Array.isArray(v);
37
37
  /** Reject cycles, excessive work, and non-JSON library inputs before hashing or compiling. */
38
- export function assertContractJson(value, maxNodes = 50_000, maxDepth = 64) {
38
+ export function assertContractJson(value, maxNodes = 50_000, maxDepth = 64, maxStringBytes = 5 * 1024 * 1024) {
39
39
  const active = new WeakSet();
40
- let remaining = maxNodes, bytes = 5 * 1024 * 1024;
40
+ let remaining = maxNodes, bytes = maxStringBytes;
41
41
  const walk = (v, depth) => {
42
42
  if (--remaining < 0 || depth > maxDepth)
43
43
  throw new Error("Contract data exceeds size or depth limits.");
44
44
  if (typeof v === "string") {
45
45
  bytes -= Buffer.byteLength(v);
46
46
  if (bytes < 0)
47
- throw new Error("Contract data exceeds the 5 MiB string budget.");
47
+ throw new Error(`Contract data exceeds the ${maxStringBytes / (1024 * 1024)} MiB string budget.`);
48
48
  return;
49
49
  }
50
50
  if (v === null ||
@@ -65,13 +65,43 @@ export function assertContractJson(value, maxNodes = 50_000, maxDepth = 64) {
65
65
  for (const [key, x] of Object.entries(v)) {
66
66
  bytes -= Buffer.byteLength(key);
67
67
  if (bytes < 0)
68
- throw new Error("Contract data exceeds the 5 MiB string budget.");
68
+ throw new Error(`Contract data exceeds the ${maxStringBytes / (1024 * 1024)} MiB string budget.`);
69
69
  walk(x, depth + 1);
70
70
  }
71
71
  active.delete(v);
72
72
  };
73
73
  walk(value, 0);
74
74
  }
75
+ /** Check routing annotations in schema positions. Call on a bounded tools/list schema. */
76
+ export function validMcpHeaderSchema(root) {
77
+ const names = new Set();
78
+ function visit(schema, throughProperties, rootNode = false) {
79
+ if (!isObject(schema))
80
+ return true;
81
+ if (Object.hasOwn(schema, "x-mcp-header")) {
82
+ const name = schema["x-mcp-header"];
83
+ if (rootNode || !throughProperties || typeof name !== "string" ||
84
+ !/^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/.test(name) ||
85
+ typeof schema.type !== "string" || !["string", "integer", "boolean"].includes(schema.type) ||
86
+ names.has(name.toLowerCase()))
87
+ return false;
88
+ names.add(name.toLowerCase());
89
+ }
90
+ for (const [key, value] of Object.entries(schema)) {
91
+ if (SCHEMA_MAPS.has(key) && isObject(value)) {
92
+ if (!Object.values(value).every(child => visit(child, throughProperties && key === "properties")))
93
+ return false;
94
+ }
95
+ else if (SCHEMA_ARRAYS.has(key) || SCHEMA_VALUES.has(key)) {
96
+ const children = Array.isArray(value) ? value : [value];
97
+ if (!children.every(child => visit(child, false)))
98
+ return false;
99
+ }
100
+ }
101
+ return true;
102
+ }
103
+ return visit(root, true, true);
104
+ }
75
105
  function canonicalLiteral(v) {
76
106
  if (Array.isArray(v))
77
107
  return v.map(canonicalLiteral);
@@ -58,6 +58,7 @@ export declare function createContractFromCatalog(server: {
58
58
  version?: string;
59
59
  }, catalog: {
60
60
  tools: readonly ToolListEntry[];
61
+ nextCursor?: string;
61
62
  }, options?: {
62
63
  tools?: string[];
63
64
  }): ContractSnapshot;
package/dist/contracts.js CHANGED
@@ -112,10 +112,14 @@ export function createContractFromCatalog(server, catalog, options = {}) {
112
112
  throw new Error("Catalog tools need distinct names and JSON schemas.");
113
113
  names.add(tool.name);
114
114
  }
115
+ if (catalog.nextCursor !== undefined && typeof catalog.nextCursor !== "string")
116
+ throw new Error("Catalog nextCursor must be a string when present.");
115
117
  const record = newServer(server.name, server.version);
116
118
  recordToolList(record, [...catalog.tools]);
117
119
  // Parsing also detaches the result from the caller's catalog and checks limits.
118
- return parseContractSnapshot(createContractSnapshot(record, options));
120
+ const selection = catalog.nextCursor !== undefined && options.tools === undefined
121
+ ? { tools: [...names] } : options;
122
+ return parseContractSnapshot(createContractSnapshot(record, selection));
119
123
  }
120
124
  /** Parse without executing schemas, fetching refs, connecting to servers, or changing learning. */
121
125
  export function parseContractSnapshot(source) {
package/dist/core.d.ts CHANGED
@@ -2,7 +2,7 @@ export { extract, parseJsonText, type Extracted, type ToolResultLike, } from "./
2
2
  export { decode, invokeTool, ToolError, type ToolCaller, type BindingCallOptions, type DecodeMode, } from "./execution.js";
3
3
  export { createContractFromCatalog, createContractSnapshot, parseContractSnapshot, selectContractTools, compareContractSnapshots, contractCheckFailed, type ContractSnapshot, type ContractTool, type ContractSchema, } from "./contracts.js";
4
4
  export { createContractCaller, ContractValidationError, type ContractIssue, type ContractCallerOptions, } from "./contract-caller.js";
5
- export { parseSpliceSpec, preflightSplice, prepareSplice, SpliceError, type SpliceSpec, type SpliceBinding, type SpliceReport, type SpliceIssue, type SpliceRunOptions, type SpliceMappingOptions, } from "./splice.js";
5
+ export { parseSpliceSpec, preflightSplice, prepareSplice, SpliceError, type SpliceSpec, type SpliceToolOptions, type SpliceBinding, type SpliceReport, type SpliceIssue, type SpliceRunOptions, type SpliceReadOptions, type SpliceMappingOptions, } from "./splice.js";
6
6
  export { explainSpliceError, type SpliceExplanation, type SpliceFieldOrigin, } from "./splice-diagnostics.js";
7
7
  export { createSpliceRecorder, parseSpliceRecording, replaySpliceRecording, type SpliceRecording, type SpliceRecordingOptions, type SpliceReplayOptions, } from "./splice-recording.js";
8
8
  export { parseContractCorrection, applyContractCorrection, type ContractCorrection, type CorrectionFixtureResult, } from "./contract-corrections.js";
@@ -12,3 +12,33 @@ import type { ContractSnapshot } from "./contracts.js";
12
12
  export declare function emitSpliceModule(plan: SpliceSpec, source: ContractSnapshot, target: ContractSnapshot, options?: {
13
13
  runtimeImport?: string;
14
14
  }): string;
15
+ export { type SpliceRule, type RuleOperand } from "./rules.js";
16
+ export { createMockCaller, mockRecordedCalls, MockCallError, parseSpliceSuite, runSpliceSuite, suiteFromRecording, formatTestJUnit, type MockStep, type SpliceTestCase, type SpliceSuite, type SpliceTestReport } from "./testing.js";
17
+ export { defineSplice, type SpliceDefinition } from "./define.js";
18
+ export { defineLocalTool, type LocalToolDefinition } from "./local-tool.js";
19
+ export { inspectCatalogMapping, type CatalogSetup } from "./catalog-setup.js";
20
+ export { assessSpliceImpact, type SpliceImpactOptions, type SpliceImpactReport } from "./impact.js";
21
+ export { collectToolCatalog, type ToolCatalogPage } from "./catalog.js";
22
+ export { createMcpAppResource, MCP_APP_MIME_TYPE, type McpToolUi, type McpAppResourceOptions } from "./mcp-apps.js";
23
+ export { createMcpPeer, MCP_PROTOCOL_VERSION, type McpExchange, type McpPeerOptions } from "./mcp-peer.js";
24
+ export type { McpWebhookOptions, McpEventOccurrence } from "./mcp-event-delivery.js";
25
+ export { openMcpSkills, openMcpEvents, type McpRequestPeer, type McpPollOptions, type McpEventBatch } from "./mcp-extensions.js";
26
+ export { createMcpServerCard, type McpServerCardOptions } from "./mcp-server-card.js";
27
+ export { PageReadGate, type PageReadGateOptions } from "./page-read-gate.js";
28
+ export { RetryablePageError } from "./read-pages.js";
29
+ export { collectTextPages, textPageJob, type TextPage, type TextPageOptions } from "./text-pages.js";
30
+ export { ResultSession, resultToolsFromMcp, projectTool, type ResultTool, type ResultSelection, type ResultSessionOptions, type ResultForwardRequest, type ResultToolOptions } from "./result-session.js";
31
+ export type { RowGrouping, RowGroup } from "./row-groups.js";
32
+ export { ExpiredPageCursorError, UncertainPageReadError, type PageCheckpoint, type PageOutcome, type PageJob, type PageInspection, type PageAttempt } from "./page-checkpoint.js";
33
+ export { queryRows, queryRowPages, rowPageJob, type RowPage, type RowPageOptions, type RowPredicate, type RowQuery, type RowQueryResult } from "./row-query.js";
34
+ export { cacheReads, type ReadCacheOptions } from "./cache-reads.js";
35
+ export { coalesceReads } from "./coalesce-reads.js";
36
+ export { searchThenFetch, type SearchFetchOptions } from "./search-fetch.js";
37
+ export { discoverTools } from "./tool-discovery.js";
38
+ export * from "./route-evaluation.js";
39
+ export { RunDiagnostics, type DiagnosticEvent, type DiagnosticModelUsage, type TimedDiagnosticEvent } from "./run-diagnostics.js";
40
+ export { readSteps } from "./read-steps.js";
41
+ export { FinalAnswerWaitTimeout } from "./answer-wait.js";
42
+ export { finalAnswerCheckpoint, type FinalAnswerOptions, type DatabaseFinalAnswerOptions, type FinalAnswerStatus } from "./final-answer.js";
43
+ export { postgresFinalAnswerStore, mongoFinalAnswerStore, type FinalAnswerStore, type FinalAnswerRow } from "./final-answer-stores.js";
44
+ export { openSqliteCheckpointStore } from "./sqlite-checkpoint-store.js";
package/dist/core.js CHANGED
@@ -14,3 +14,30 @@ export function emitSpliceModule(plan, source, target, options = {}) {
14
14
  runtimeImport: options.runtimeImport ?? "toolsplice-core",
15
15
  });
16
16
  }
17
+ export { createMockCaller, mockRecordedCalls, MockCallError, parseSpliceSuite, runSpliceSuite, suiteFromRecording, formatTestJUnit } from "./testing.js";
18
+ export { defineSplice } from "./define.js";
19
+ export { defineLocalTool } from "./local-tool.js";
20
+ export { inspectCatalogMapping } from "./catalog-setup.js";
21
+ export { assessSpliceImpact } from "./impact.js";
22
+ export { collectToolCatalog } from "./catalog.js";
23
+ export { createMcpAppResource, MCP_APP_MIME_TYPE } from "./mcp-apps.js";
24
+ export { createMcpPeer, MCP_PROTOCOL_VERSION } from "./mcp-peer.js";
25
+ export { openMcpSkills, openMcpEvents } from "./mcp-extensions.js";
26
+ export { createMcpServerCard } from "./mcp-server-card.js";
27
+ export { PageReadGate } from "./page-read-gate.js";
28
+ export { RetryablePageError } from "./read-pages.js";
29
+ export { collectTextPages, textPageJob } from "./text-pages.js";
30
+ export { ResultSession, resultToolsFromMcp, projectTool } from "./result-session.js";
31
+ export { ExpiredPageCursorError, UncertainPageReadError } from "./page-checkpoint.js";
32
+ export { queryRows, queryRowPages, rowPageJob } from "./row-query.js";
33
+ export { cacheReads } from "./cache-reads.js";
34
+ export { coalesceReads } from "./coalesce-reads.js";
35
+ export { searchThenFetch } from "./search-fetch.js";
36
+ export { discoverTools } from "./tool-discovery.js";
37
+ export * from "./route-evaluation.js";
38
+ export { RunDiagnostics } from "./run-diagnostics.js";
39
+ export { readSteps } from "./read-steps.js";
40
+ export { FinalAnswerWaitTimeout } from "./answer-wait.js";
41
+ export { finalAnswerCheckpoint } from "./final-answer.js";
42
+ export { postgresFinalAnswerStore, mongoFinalAnswerStore } from "./final-answer-stores.js";
43
+ export { openSqliteCheckpointStore } from "./sqlite-checkpoint-store.js";
@@ -0,0 +1,9 @@
1
+ import type { FinalAnswerStore } from "./final-answer-stores.js";
2
+ import type { FinalAnswerStatus } from "./final-answer.js";
3
+ export declare function databaseCheckpoint<T>(store: FinalAnswerStore, job: string, identity: string, check: (value: unknown) => T): {
4
+ inspect: () => Promise<FinalAnswerStatus<T>>;
5
+ run: (work: (save: (value: T) => Promise<T>) => unknown, options?: {
6
+ waitMs?: number;
7
+ }) => Promise<T>;
8
+ waitForResult: (timeoutMs: number, signal?: AbortSignal) => Promise<T>;
9
+ };
@@ -0,0 +1,62 @@
1
+ import { answerWaiter, validateWait } from "./answer-wait.js";
2
+ import { jsonFingerprint } from "./workflow-json.js";
3
+ export function databaseCheckpoint(store, job, identity, check) {
4
+ async function inspect() {
5
+ const row = await store.read(job);
6
+ if (row === null)
7
+ return { state: "missing" };
8
+ if (row.identity !== identity)
9
+ throw new Error("Final answer checkpoint identity or format mismatch.");
10
+ if (row.payload === null)
11
+ return { state: "incomplete" };
12
+ if (typeof row.payload !== "string" ||
13
+ Buffer.byteLength(row.payload) > 512 * 1024)
14
+ throw new Error("Invalid final answer checkpoint.");
15
+ const record = JSON.parse(row.payload);
16
+ const answer = check(record.answer);
17
+ if (record.digest !== jsonFingerprint(answer))
18
+ throw new Error("Invalid final answer digest.");
19
+ return { state: "saved", answer };
20
+ }
21
+ const waitForResult = answerWaiter(inspect);
22
+ async function run(work, options) {
23
+ if (options?.waitMs !== undefined)
24
+ validateWait(options.waitMs);
25
+ const cached = await inspect();
26
+ if (cached.state === "saved")
27
+ return cached.answer;
28
+ if (!(await store.claim(job, identity))) {
29
+ if (options?.waitMs !== undefined)
30
+ return waitForResult(options.waitMs);
31
+ const latest = await inspect();
32
+ if (latest.state === "saved")
33
+ return latest.answer;
34
+ throw new Error("Final answer job is claimed without a saved answer. Reconcile before retrying.");
35
+ }
36
+ let open = true;
37
+ async function save(value) {
38
+ if (!open)
39
+ throw new Error("Final answer run has ended.");
40
+ const answer = check(value);
41
+ const digest = jsonFingerprint(answer);
42
+ if (!(await store.complete(job, identity, JSON.stringify({ answer, digest })))) {
43
+ const latest = await inspect();
44
+ if (latest.state !== "saved" ||
45
+ jsonFingerprint(latest.answer) !== digest)
46
+ throw new Error("A different final answer is already saved.");
47
+ }
48
+ return answer;
49
+ }
50
+ try {
51
+ await work(save);
52
+ }
53
+ finally {
54
+ open = false;
55
+ }
56
+ const result = await inspect();
57
+ if (result.state !== "saved")
58
+ throw new Error("The workflow ended without saving a final answer.");
59
+ return result.answer;
60
+ }
61
+ return { inspect, run, waitForResult };
62
+ }
@@ -0,0 +1,78 @@
1
+ import { type SpliceSpec } from "./splice.js";
2
+ /** Inline definitions for applications that already know their tools' schemas. */
3
+ export type SpliceDefinition = Omit<SpliceSpec, "format" | "formatVersion" | "source" | "target"> & {
4
+ source: SpliceSpec["source"] & {
5
+ inputSchema: Record<string, unknown>;
6
+ outputSchema?: Record<string, unknown>;
7
+ };
8
+ target: SpliceSpec["target"] & {
9
+ inputSchema: Record<string, unknown>;
10
+ outputSchema?: Record<string, unknown>;
11
+ };
12
+ };
13
+ export declare function defineSplice(definition: SpliceDefinition): {
14
+ report: import("./splice.js").SpliceReport;
15
+ mapOutput: (output: unknown, options?: import("./splice.js").SpliceMappingOptions) => Promise<Record<string, unknown>[]>;
16
+ run: (source: import("./execution.js").ToolCaller, target: import("./execution.js").ToolCaller, args: unknown, options?: import("./splice.js").SpliceRunOptions) => Promise<unknown[]>;
17
+ runReads: (source: import("./execution.js").ToolCaller, target: import("./execution.js").ToolCaller, args: unknown, options?: import("./splice.js").SpliceReadOptions) => Promise<unknown[]>;
18
+ asTool: ({ name, description, source, target, ui, readConcurrency: requested, assumeReadOnly }: import("./splice.js").SpliceToolOptions) => {
19
+ definition: {
20
+ name: string;
21
+ description?: string | undefined;
22
+ _meta?: {
23
+ ui: import("./mcp-apps.js").McpToolUi;
24
+ } | undefined;
25
+ inputSchema: {
26
+ type: "object";
27
+ };
28
+ outputSchema: {
29
+ type: "object";
30
+ properties: {
31
+ results: {
32
+ type: string;
33
+ items: {
34
+ type: string;
35
+ properties: {
36
+ [k: string]: {};
37
+ };
38
+ required: string[];
39
+ additionalProperties: boolean;
40
+ } | {
41
+ type?: undefined;
42
+ properties?: undefined;
43
+ required?: undefined;
44
+ additionalProperties?: undefined;
45
+ };
46
+ };
47
+ };
48
+ required: string[];
49
+ additionalProperties: boolean;
50
+ };
51
+ };
52
+ call: (args: Record<string, unknown>, options?: import("./splice.js").SpliceRunOptions) => Promise<{
53
+ resultType: "complete";
54
+ structuredContent: {
55
+ results: unknown[];
56
+ };
57
+ content: {
58
+ type: "text";
59
+ text: string;
60
+ }[];
61
+ isError?: undefined;
62
+ } | {
63
+ structuredContent?: undefined;
64
+ resultType: "complete";
65
+ isError: true;
66
+ content: {
67
+ type: "text";
68
+ text: string;
69
+ }[];
70
+ }>;
71
+ execute: (args: Record<string, unknown>, options?: import("./splice.js").SpliceRunOptions) => Promise<{
72
+ results: unknown[];
73
+ }>;
74
+ };
75
+ plan: SpliceSpec;
76
+ sourceContract: import("./contracts.js").ContractSnapshot;
77
+ targetContract: import("./contracts.js").ContractSnapshot;
78
+ };
package/dist/define.js ADDED
@@ -0,0 +1,14 @@
1
+ import { createContractFromCatalog } from "./contracts.js";
2
+ import { parseSpliceSpec, prepareSplice } from "./splice.js";
3
+ import { copyJson, jsonObject } from "./workflow-json.js";
4
+ export function defineSplice(definition) {
5
+ const config = copyJson(definition);
6
+ const { inputSchema: si, outputSchema: so, ...source } = config.source;
7
+ const { inputSchema: ti, outputSchema: to, ...target } = config.target;
8
+ if (!jsonObject(si) || !jsonObject(ti) || (so !== undefined && !jsonObject(so)) || (to !== undefined && !jsonObject(to)))
9
+ throw new Error("Inline tool schemas must be JSON Schema objects.");
10
+ const plan = parseSpliceSpec({ format: "toolsplice-splice", formatVersion: 1, ...config, source, target });
11
+ const sourceContract = createContractFromCatalog({ name: source.server }, { tools: [{ name: source.tool, inputSchema: si, ...(so === undefined ? {} : { outputSchema: so }) }] });
12
+ const targetContract = createContractFromCatalog({ name: target.server }, { tools: [{ name: target.tool, inputSchema: ti, ...(to === undefined ? {} : { outputSchema: to }) }] });
13
+ return { ...prepareSplice(plan, sourceContract, targetContract), plan, sourceContract, targetContract };
14
+ }
@@ -0,0 +1,71 @@
1
+ /** Database adapters use an application-owned pool or database. Both SDKs store the
2
+ * same bounded JSON text to preserve JSON keys and numbers across SQL and BSON. */
3
+ export interface FinalAnswerRow {
4
+ identity: string;
5
+ payload: string | null;
6
+ }
7
+ export interface FinalAnswerStore {
8
+ read(job: string): Promise<FinalAnswerRow | null>;
9
+ claim(job: string, identity: string): Promise<boolean>;
10
+ complete(job: string, identity: string, payload: string): Promise<boolean>;
11
+ }
12
+ interface PgResult {
13
+ rowCount: number | null;
14
+ rows: Record<string, unknown>[];
15
+ }
16
+ interface PgQuery {
17
+ query(sql: string, values?: string[]): Promise<PgResult>;
18
+ }
19
+ interface PgPool extends PgQuery {
20
+ connect(): Promise<PgQuery & {
21
+ release(discard?: boolean): void;
22
+ }>;
23
+ }
24
+ export declare function postgresFinalAnswerStore(pool: PgPool): {
25
+ /** Run once in a migration; application workers need only SELECT, INSERT and UPDATE. */
26
+ initialize(): Promise<void>;
27
+ read(job: string): Promise<FinalAnswerRow>;
28
+ claim(job: string, identity: string): Promise<boolean>;
29
+ complete(job: string, identity: string, payload: string): Promise<boolean>;
30
+ };
31
+ interface MongoCollection {
32
+ findOne(filter: {
33
+ _id: string;
34
+ }, options: {
35
+ readPreference: "primary";
36
+ readConcern: {
37
+ level: "majority";
38
+ };
39
+ }): Promise<(FinalAnswerRow & {
40
+ _id: string;
41
+ }) | null>;
42
+ insertOne(row: FinalAnswerRow & {
43
+ _id: string;
44
+ }, options: MongoWrite): Promise<{
45
+ acknowledged: boolean;
46
+ }>;
47
+ updateOne(filter: {
48
+ _id: string;
49
+ identity: string;
50
+ payload: null;
51
+ }, update: {
52
+ $set: {
53
+ payload: string;
54
+ };
55
+ }, options: MongoWrite): Promise<{
56
+ acknowledged: boolean;
57
+ modifiedCount: number;
58
+ }>;
59
+ }
60
+ interface MongoWrite {
61
+ writeConcern: {
62
+ w: "majority";
63
+ j: true;
64
+ };
65
+ }
66
+ interface MongoDatabase {
67
+ databaseName: string;
68
+ collection(name: string): MongoCollection;
69
+ }
70
+ export declare function mongoFinalAnswerStore(database: MongoDatabase): FinalAnswerStore;
71
+ export {};
@@ -0,0 +1,72 @@
1
+ export function postgresFinalAnswerStore(pool) {
2
+ async function write(operation) {
3
+ const client = await pool.connect();
4
+ let discard = false;
5
+ try {
6
+ await client.query("BEGIN");
7
+ await client.query("SET LOCAL synchronous_commit = on");
8
+ const result = await operation(client);
9
+ await client.query("COMMIT");
10
+ return result;
11
+ }
12
+ catch (error) {
13
+ try {
14
+ await client.query("ROLLBACK");
15
+ }
16
+ catch {
17
+ discard = true;
18
+ }
19
+ throw error;
20
+ }
21
+ finally {
22
+ client.release(discard);
23
+ }
24
+ }
25
+ return {
26
+ /** Run once in a migration; application workers need only SELECT, INSERT and UPDATE. */
27
+ async initialize() {
28
+ await write(async (client) => {
29
+ await client.query("SELECT pg_advisory_xact_lock(1970037089, 1)");
30
+ await client.query("CREATE TABLE IF NOT EXISTS toolsplice_final_answers (job text PRIMARY KEY, identity text NOT NULL, payload text)");
31
+ });
32
+ },
33
+ async read(job) {
34
+ const { rows } = await pool.query("SELECT identity, payload FROM toolsplice_final_answers WHERE job = $1", [job]);
35
+ return rows[0] ?? null;
36
+ },
37
+ claim(job, identity) {
38
+ return write(async (client) => (await client.query("INSERT INTO toolsplice_final_answers (job, identity) VALUES ($1, $2) ON CONFLICT (job) DO NOTHING", [job, identity])).rowCount === 1);
39
+ },
40
+ complete(job, identity, payload) {
41
+ return write(async (client) => (await client.query("UPDATE toolsplice_final_answers SET payload = $3 WHERE job = $1 AND identity = $2 AND payload IS NULL", [job, identity, payload])).rowCount === 1);
42
+ },
43
+ };
44
+ }
45
+ export function mongoFinalAnswerStore(database) {
46
+ if (database.databaseName === "local")
47
+ throw new Error("Choose an application database with durable write concern.");
48
+ const collection = database.collection("toolsplice_final_answers");
49
+ const write = { writeConcern: { w: "majority", j: true } };
50
+ return {
51
+ read: (job) => collection.findOne({ _id: job }, { readPreference: "primary", readConcern: { level: "majority" } }),
52
+ async claim(job, identity) {
53
+ try {
54
+ const result = await collection.insertOne({ _id: job, identity, payload: null }, write);
55
+ if (!result.acknowledged)
56
+ throw new Error("Checkpoint claim was not acknowledged.");
57
+ return true;
58
+ }
59
+ catch (error) {
60
+ if (error?.code === 11000)
61
+ return false;
62
+ throw error;
63
+ }
64
+ },
65
+ async complete(job, identity, payload) {
66
+ const result = await collection.updateOne({ _id: job, identity, payload: null }, { $set: { payload } }, write);
67
+ if (!result.acknowledged)
68
+ throw new Error("Checkpoint save was not acknowledged.");
69
+ return result.modifiedCount === 1;
70
+ },
71
+ };
72
+ }
@@ -0,0 +1,32 @@
1
+ import type { FinalAnswerStore } from "./final-answer-stores.js";
2
+ import { databaseCheckpoint } from "./db-final-answer.js";
3
+ interface AnswerIdentity {
4
+ jobId: string;
5
+ /** Include the principal, inputs and version of the workflow. Only its fingerprint is stored. */
6
+ context: Record<string, unknown>;
7
+ schema: Record<string, unknown>;
8
+ }
9
+ export interface FinalAnswerOptions extends AnswerIdentity {
10
+ directory: string;
11
+ store?: never;
12
+ }
13
+ export interface DatabaseFinalAnswerOptions extends AnswerIdentity {
14
+ store: FinalAnswerStore;
15
+ directory?: never;
16
+ }
17
+ export type FinalAnswerStatus<T> = {
18
+ state: "missing" | "incomplete";
19
+ } | {
20
+ state: "saved";
21
+ answer: T;
22
+ };
23
+ /** One app-owned final answer. A durable claim precedes work and a validated save ends replay. */
24
+ export declare function finalAnswerCheckpoint<T = unknown>(options: FinalAnswerOptions): {
25
+ inspect(): FinalAnswerStatus<T>;
26
+ run(work: (save: (value: T) => T) => unknown, options?: {
27
+ waitMs?: number;
28
+ }): Promise<T>;
29
+ waitForResult(timeoutMs: number, signal?: AbortSignal): Promise<T>;
30
+ };
31
+ export declare function finalAnswerCheckpoint<T = unknown>(options: DatabaseFinalAnswerOptions): ReturnType<typeof databaseCheckpoint<T>>;
32
+ export {};