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,43 @@
1
+ import { defineSplice, createMockCaller } from 'toolsplice';
2
+
3
+ const handoff = defineSplice({
4
+ source: {
5
+ server: 'documents', tool: 'read',
6
+ inputSchema: { type: 'object' },
7
+ outputSchema: {
8
+ type: 'object',
9
+ properties: { tenant: { type: 'string' }, text: { type: 'string' } },
10
+ required: ['tenant', 'text'],
11
+ },
12
+ },
13
+ target: {
14
+ server: 'files', tool: 'save',
15
+ inputSchema: {
16
+ type: 'object', properties: { content: { type: 'string' } },
17
+ required: ['content'],
18
+ },
19
+ outputSchema: { type: 'boolean' },
20
+ },
21
+ bindings: [{ to: '/content', from: '/text' }],
22
+ contextSchema: {
23
+ type: 'object', properties: { tenant: { type: 'string' } }, required: ['tenant'],
24
+ },
25
+ rules: [{
26
+ id: 'same-tenant', left: { source: '/tenant' },
27
+ op: 'equals', right: { context: '/tenant' },
28
+ }],
29
+ });
30
+
31
+ const read = createMockCaller([{
32
+ name: 'read', result: { structuredContent: { tenant: 'acme', text: 'Hello' } },
33
+ }]);
34
+ const save = createMockCaller([{
35
+ name: 'save', arguments: { content: 'Hello' }, result: { structuredContent: true },
36
+ }]);
37
+
38
+ const result = await handoff.run(read, save, {}, {
39
+ context: { tenant: 'acme' }, allowReview: true,
40
+ });
41
+ read.assertDone();
42
+ save.assertDone();
43
+ console.log(result); // [true]
@@ -0,0 +1,67 @@
1
+ import { searchThenFetch } from "toolsplice";
2
+
3
+ // Replace these two reads with your application's read-only tools.
4
+ const pages = { a: "alpha alpha", b: "beta", c: "alpha", d: "beta beta" };
5
+ const origin = "https://pages.test";
6
+ const search = {
7
+ definition: {
8
+ name: "search",
9
+ inputSchema: {
10
+ type: "object",
11
+ properties: { id: { type: "string" } },
12
+ required: ["id"],
13
+ additionalProperties: false,
14
+ },
15
+ },
16
+ async execute({ id }) {
17
+ return { results: [{ contentUrl: origin + "/" + id }] };
18
+ },
19
+ };
20
+ const fetchPage = {
21
+ definition: {
22
+ name: "fetch",
23
+ inputSchema: {
24
+ type: "object",
25
+ properties: { url: { type: "string" } },
26
+ required: ["url"],
27
+ },
28
+ },
29
+ async execute({ url }) {
30
+ return pages[new URL(url).pathname.slice(1)];
31
+ },
32
+ };
33
+ const combined = searchThenFetch(search, fetchPage, {
34
+ origins: [origin],
35
+ pageView: "markdown",
36
+ });
37
+
38
+ export default {
39
+ context: "local-pages/v1",
40
+ routes: ["native", "configured"],
41
+ cases: Object.keys(pages).map((id, i) => ({
42
+ id,
43
+ workload: "page-count",
44
+ split: i < 2 ? "fit" : "holdout",
45
+ input: { id, literal: i % 2 ? "beta" : "alpha" },
46
+ expected: [2, 1, 1, 2][i],
47
+ })),
48
+ // For an agent, call your actual agent here and return its measured usage.
49
+ async run(route, { input }) {
50
+ let count;
51
+ if (route === "configured") {
52
+ const result = await combined.execute({
53
+ id: input.id,
54
+ countLiteral: input.literal,
55
+ });
56
+ count = result.count;
57
+ } else {
58
+ const { results } = await search.execute({ id: input.id });
59
+ const text = await fetchPage.execute({ url: results[0].contentUrl });
60
+ count = text.split(input.literal).length - 1;
61
+ }
62
+ return { answer: count, modelCalls: 0, costUsd: 0 };
63
+ },
64
+ grade(item, answer) {
65
+ return answer === item.expected;
66
+ },
67
+ };
@@ -0,0 +1,36 @@
1
+ import type { Tool } from "ai";
2
+ import type { RunDiagnostics, SpliceRunOptions } from "../dist/core.js";
3
+ import type { ExecutableTool } from "./types.mjs";
4
+
5
+ export declare function aiTools<Result>(
6
+ workflow: ExecutableTool<Result>,
7
+ options?: SpliceRunOptions,
8
+ ): Record<string, Tool<Record<string, unknown>, Result>>;
9
+
10
+ import type { ToolSet } from "ai";
11
+ import type { ResultTool } from "../dist/core.js";
12
+
13
+ /** Consume streaming results before the callback finishes. */
14
+ export declare function withAiTools<T extends ToolSet, R>(
15
+ existing: T,
16
+ question: string,
17
+ use: (tools: T & ToolSet, activeTools: () => string[]) => R,
18
+ options?: { enabled?: boolean; diagnostics?: RunDiagnostics },
19
+ ): Promise<Awaited<R>>;
20
+ export declare function withAiTools<R>(
21
+ existing: readonly ResultTool[],
22
+ question: string,
23
+ use: (tools: ToolSet, activeTools: () => string[]) => R,
24
+ options?: { enabled?: boolean; diagnostics?: RunDiagnostics },
25
+ ): Promise<Awaited<R>>;
26
+
27
+ /** Yield a stream from the callback and keep its tools live until consumption ends. */
28
+ export declare function streamAiTools<T>(
29
+ existing: ToolSet | readonly ResultTool[],
30
+ question: string,
31
+ use: (
32
+ tools: ToolSet,
33
+ activeTools: () => string[],
34
+ ) => AsyncIterable<T> | PromiseLike<AsyncIterable<T>>,
35
+ options?: { enabled?: boolean; diagnostics?: RunDiagnostics },
36
+ ): AsyncGenerator<T>;
@@ -0,0 +1,178 @@
1
+ import { createHash } from "node:crypto";
2
+ import { jsonSchema, tool } from "ai";
3
+ import {
4
+ managedTools,
5
+ activeTools,
6
+ checkNames,
7
+ visibleContent,
8
+ withRun,
9
+ streamRun,
10
+ } from "./managed.mjs";
11
+ import { callOptions } from "./call-options.mjs";
12
+
13
+ /** Register one checked workflow under its existing name in a Vercel AI SDK tool set. */
14
+ export function aiTools(workflow, options = {}) {
15
+ const { name, description, inputSchema } = workflow.definition;
16
+ return {
17
+ [name]: tool({
18
+ description,
19
+ inputSchema: jsonSchema(inputSchema),
20
+ execute: (input, { abortSignal }) =>
21
+ workflow.execute(input, callOptions(options, abortSignal)),
22
+ }),
23
+ };
24
+ }
25
+
26
+ /** Run a Vercel agent with its existing tool set and a private result scope. */
27
+ export async function withAiTools(
28
+ existing,
29
+ question,
30
+ use,
31
+ { enabled = true, diagnostics } = {},
32
+ ) {
33
+ if (diagnostics) return diagnostics.run(enabled ? "adaptive" : "native", () => withAiTools(existing, question, use, {enabled}));
34
+ if (!enabled) {
35
+ const native = nativeTools(existing);
36
+ return use(native, () => activeTools(native, true));
37
+ }
38
+ return withRun(question, buildTools(existing, question), use);
39
+ }
40
+
41
+ /** Stream a run and release retained results on completion, failure or early return. */
42
+ export async function* streamAiTools(
43
+ existing,
44
+ question,
45
+ use,
46
+ { enabled = true, diagnostics } = {},
47
+ ) {
48
+ if (diagnostics) {
49
+ yield* diagnostics.stream(enabled ? "adaptive" : "native", () => streamAiTools(existing, question, use, {enabled}));
50
+ return;
51
+ }
52
+ if (!enabled) {
53
+ const native = nativeTools(existing);
54
+ yield* await use(native, () => activeTools(native, true));
55
+ return;
56
+ }
57
+ yield* streamRun(question, buildTools(existing, question), use);
58
+ }
59
+
60
+ function nativeTools(existing) {
61
+ if (!Array.isArray(existing)) return existing;
62
+ checkNames(existing.map((t) => t.definition.name));
63
+ return Object.fromEntries(
64
+ existing.flatMap((t) => Object.entries(aiTools(t))),
65
+ );
66
+ }
67
+
68
+ function buildTools(existing, question) {
69
+ return (session, begin, cleanup) => {
70
+ const sources = Array.isArray(existing) ? existing : [];
71
+ const entries = [];
72
+ if (!Array.isArray(existing)) {
73
+ for (const [name, native] of Object.entries(existing)) {
74
+ entries.push([name, wrapNative(name, native, begin, cleanup)]);
75
+ }
76
+ }
77
+ for (const source of managedTools(session, sources, question)) {
78
+ entries.push(...Object.entries(aiTools(source)));
79
+ }
80
+ checkNames(entries.map(([name]) => name));
81
+ return Object.fromEntries(entries);
82
+ };
83
+ }
84
+
85
+ function defaultOutput(raw) {
86
+ if (typeof raw === "string") return { type: "text", value: raw };
87
+ const json = JSON.stringify(raw);
88
+ return { type: "json", value: json === undefined ? null : JSON.parse(json) };
89
+ }
90
+
91
+ function wrapNative(name, native, begin, cleanup) {
92
+ if (
93
+ native.type === "provider" ||
94
+ native.type === "provider-defined" ||
95
+ !native.execute
96
+ )
97
+ return native;
98
+ // Vercel can serialize the same tool result again when rebuilding message history.
99
+ // Keep the submitted URL and reuse a view only when the model-visible content agrees.
100
+ const calls = new Map();
101
+ let submittedInputs = new WeakMap();
102
+ cleanup.push(() => {
103
+ calls.clear();
104
+ submittedInputs = new WeakMap();
105
+ });
106
+ return {
107
+ ...native,
108
+ execute(input, options) {
109
+ const present = begin(name, input ?? {});
110
+ const id = options?.toolCallId;
111
+ if (id) {
112
+ if (calls.size === 32) calls.delete(calls.keys().next().value);
113
+ calls.set(id, { present });
114
+ if (input && typeof input === "object")
115
+ submittedInputs.set(input, { id, present });
116
+ }
117
+ return native.execute(input, options);
118
+ },
119
+ async toModelOutput(options) {
120
+ const call = calls.get(options.toolCallId);
121
+ const original = submittedInputs.get(options.input);
122
+ // A reconstructed input may already contain a redirect. Only attach a submitted
123
+ // URL to an identified call when we still have its dispatch snapshot.
124
+ const fallback = begin(
125
+ name,
126
+ options.toolCallId ? {} : (options.input ?? {}),
127
+ );
128
+ const present =
129
+ call?.present ??
130
+ (original && original.id === options.toolCallId
131
+ ? original.present
132
+ : fallback);
133
+ const output = native.toModelOutput
134
+ ? await native.toModelOutput(options)
135
+ : defaultOutput(options.output);
136
+ if (
137
+ options.output?.isError === true ||
138
+ (output.type === "json" && output.value?.isError === true) ||
139
+ !["text", "json", "content"].includes(output.type)
140
+ )
141
+ return output;
142
+ if (
143
+ output.type === "content" &&
144
+ output.value.some((p) => p.type !== "text")
145
+ )
146
+ return output;
147
+ const serialized = call && JSON.stringify(output.value);
148
+ const hash =
149
+ serialized?.length > 1024
150
+ ? createHash("sha256").update(serialized).digest("hex")
151
+ : undefined;
152
+ let value;
153
+ if (hash && call.hash === hash && call.type === output.type) {
154
+ value = structuredClone(call.view);
155
+ } else {
156
+ value =
157
+ output.type === "content"
158
+ ? visibleContent(output.value, present)
159
+ : present(output.value);
160
+ if (hash && JSON.stringify(value).length <= 8192) {
161
+ Object.assign(call, {
162
+ hash,
163
+ type: output.type,
164
+ view: structuredClone(value),
165
+ });
166
+ }
167
+ }
168
+ return {
169
+ ...output,
170
+ type:
171
+ output.type === "text" && typeof value !== "string"
172
+ ? "json"
173
+ : output.type,
174
+ value,
175
+ };
176
+ },
177
+ };
178
+ }
@@ -0,0 +1,9 @@
1
+ // Model arguments and application-owned run options use separate paths.
2
+ export function callOptions(options, frameworkSignal) {
3
+ if (!frameworkSignal) return options;
4
+ const signal =
5
+ options.signal && options.signal !== frameworkSignal
6
+ ? AbortSignal.any([options.signal, frameworkSignal])
7
+ : frameworkSignal;
8
+ return { ...options, signal };
9
+ }
@@ -0,0 +1,31 @@
1
+ import type { StructuredToolInterface } from "@langchain/core/tools";
2
+ import type { RunDiagnostics, SpliceRunOptions } from "../dist/core.js";
3
+ import type { ExecutableTool } from "./types.mjs";
4
+
5
+ export declare function asLangChainTool<Result>(
6
+ workflow: ExecutableTool<Result>,
7
+ options?: SpliceRunOptions & { returnDirect?: boolean },
8
+ ): StructuredToolInterface;
9
+
10
+ import type { ResultTool } from "../dist/core.js";
11
+
12
+ /** Consume streaming results before the callback finishes. */
13
+ export declare function withLangChainTools<R>(
14
+ existing: readonly (ResultTool | StructuredToolInterface)[],
15
+ question: string,
16
+ use: (
17
+ tools: StructuredToolInterface[],
18
+ activeTools: () => StructuredToolInterface[],
19
+ ) => R,
20
+ options?: { enabled?: boolean; diagnostics?: RunDiagnostics },
21
+ ): Promise<Awaited<R>>;
22
+
23
+ export declare function streamLangChainTools<T>(
24
+ existing: readonly (ResultTool | StructuredToolInterface)[],
25
+ question: string,
26
+ use: (
27
+ tools: StructuredToolInterface[],
28
+ activeTools: () => StructuredToolInterface[],
29
+ ) => AsyncIterable<T> | PromiseLike<AsyncIterable<T>>,
30
+ options?: { enabled?: boolean; diagnostics?: RunDiagnostics },
31
+ ): AsyncGenerator<T>;
@@ -0,0 +1,114 @@
1
+ import {
2
+ DynamicStructuredTool,
3
+ DynamicTool,
4
+ tool,
5
+ } from "@langchain/core/tools";
6
+ import {
7
+ managedTools,
8
+ activeTools,
9
+ checkNames,
10
+ visibleContent,
11
+ withRun,
12
+ streamRun,
13
+ } from "./managed.mjs";
14
+ import { callOptions } from "./call-options.mjs";
15
+
16
+ /** Register a workflow as one LangChain structured tool. */
17
+ export function asLangChainTool(workflow, options = {}) {
18
+ const { name, description, inputSchema } = workflow.definition;
19
+ const { returnDirect = false, ...runOptions } = options;
20
+ if (typeof returnDirect !== "boolean")
21
+ throw new TypeError("returnDirect must be boolean.");
22
+ return tool(
23
+ (input, config) =>
24
+ workflow.execute(input, callOptions(runOptions, config?.signal)),
25
+ {
26
+ name,
27
+ description: description ?? name,
28
+ schema: inputSchema,
29
+ returnDirect,
30
+ },
31
+ );
32
+ }
33
+
34
+ /** Run a LangChain agent with its existing tools and a private result scope. */
35
+ export async function withLangChainTools(
36
+ existing,
37
+ question,
38
+ use,
39
+ { enabled = true, diagnostics } = {},
40
+ ) {
41
+ if (diagnostics) return diagnostics.run(enabled ? "adaptive" : "native", () => withLangChainTools(existing, question, use, {enabled}));
42
+ if (!enabled) {
43
+ const native = nativeTools(existing);
44
+ return use(native, () => activeTools(native, true));
45
+ }
46
+ return withRun(question, buildTools(existing, question), use);
47
+ }
48
+
49
+ /** Stream a run and release retained results on completion, failure or early return. */
50
+ export async function* streamLangChainTools(
51
+ existing,
52
+ question,
53
+ use,
54
+ { enabled = true, diagnostics } = {},
55
+ ) {
56
+ if (diagnostics) {
57
+ yield* diagnostics.stream(enabled ? "adaptive" : "native", () => streamLangChainTools(existing, question, use, {enabled}));
58
+ return;
59
+ }
60
+ if (!enabled) {
61
+ const native = nativeTools(existing);
62
+ yield* await use(native, () => activeTools(native, true));
63
+ return;
64
+ }
65
+ yield* streamRun(question, buildTools(existing, question), use);
66
+ }
67
+
68
+ function nativeTools(existing) {
69
+ return existing.some((t) => t.definition && typeof t.execute === "function")
70
+ ? existing.map((t) =>
71
+ t.definition && typeof t.execute === "function"
72
+ ? asLangChainTool(t)
73
+ : t,
74
+ )
75
+ : existing;
76
+ }
77
+
78
+ function buildTools(existing, question) {
79
+ return (session, begin) => {
80
+ const sources = existing.filter(
81
+ (t) => t.definition && typeof t.execute === "function",
82
+ );
83
+ const registered = managedTools(session, sources, question);
84
+ const wrapped = new Map(
85
+ registered.map((t) => [t.definition.name, asLangChainTool(t)]),
86
+ );
87
+ const tools = existing.map((native) => {
88
+ if (native.definition && typeof native.execute === "function")
89
+ return wrapped.get(native.definition.name);
90
+ if (
91
+ native.returnDirect ||
92
+ ![DynamicTool, DynamicStructuredTool].includes(native.constructor)
93
+ )
94
+ return native;
95
+ return new native.constructor({
96
+ ...native,
97
+ async func(input, ...rest) {
98
+ const present = begin(native.name, input ?? {});
99
+ const output = await native.func(input, ...rest);
100
+ if (
101
+ native.responseFormat === "content_and_artifact" &&
102
+ Array.isArray(output) &&
103
+ output.length === 2
104
+ )
105
+ return [visibleContent(output[0], present), output[1]];
106
+ return visibleContent(output, present);
107
+ },
108
+ });
109
+ });
110
+ tools.push(wrapped.get("inspect_result"));
111
+ checkNames(tools.map((t) => t.name));
112
+ return tools;
113
+ };
114
+ }
@@ -0,0 +1,154 @@
1
+ import { ResultSession } from "../dist/core.js";
2
+
3
+ // Vercel expects names in prepareStep. LangChain middleware accepts tool objects.
4
+ export function activeTools(tools, showInspector) {
5
+ if (Array.isArray(tools))
6
+ return showInspector
7
+ ? [...tools]
8
+ : tools.filter((t) => t.name !== "inspect_result");
9
+ return Object.keys(tools).filter(
10
+ (name) => showInspector || name !== "inspect_result",
11
+ );
12
+ }
13
+
14
+ export async function withRun(question, build, use) {
15
+ const session = new ResultSession({ nativeOnCapacity: true });
16
+ const cleanup = [];
17
+ try {
18
+ const present = session.adaptivePresenter(question);
19
+ const tools = build(session, present, cleanup);
20
+ return await use(tools, () =>
21
+ activeTools(tools, session.hasRetainedResults),
22
+ );
23
+ } finally {
24
+ session.close();
25
+ for (const release of cleanup) release();
26
+ }
27
+ }
28
+
29
+ export async function* streamRun(question, build, use) {
30
+ const session = new ResultSession({ nativeOnCapacity: true });
31
+ const cleanup = [];
32
+ try {
33
+ const tools = build(session, session.adaptivePresenter(question), cleanup);
34
+ yield* await use(tools, () =>
35
+ activeTools(tools, session.hasRetainedResults),
36
+ );
37
+ } finally {
38
+ session.close();
39
+ for (const release of cleanup) release();
40
+ }
41
+ }
42
+
43
+ export function checkNames(names) {
44
+ if (new Set(names).size !== names.length)
45
+ throw new Error("Duplicate or reserved session tool name.");
46
+ }
47
+
48
+ // Native MCP adapters can carry media and framework-specific blocks alongside text.
49
+ // Preserve that representation and keep private artifacts outside retained values.
50
+ export function visibleContent(value, present) {
51
+ if (value?.isError === true) return value;
52
+ if (
53
+ Array.isArray(value) &&
54
+ value.some((part) => part && typeof part.type === "string")
55
+ ) {
56
+ if (!value.every((p) => p?.type === "text" && typeof p.text === "string"))
57
+ return value;
58
+ if (value.length > 1) {
59
+ if (
60
+ value.some((p) =>
61
+ Object.keys(p).some((k) => k !== "type" && k !== "text"),
62
+ )
63
+ )
64
+ return value;
65
+ const view = present(value);
66
+ return Array.isArray(view)
67
+ ? view
68
+ : [{ type: "text", text: JSON.stringify(view) }];
69
+ }
70
+ const text = present(value[0].text);
71
+ return [
72
+ {
73
+ ...value[0],
74
+ text: typeof text === "string" ? text : JSON.stringify(text),
75
+ },
76
+ ];
77
+ }
78
+ if (
79
+ value === undefined ||
80
+ (value !== null &&
81
+ typeof value === "object" &&
82
+ !Array.isArray(value) &&
83
+ ![Object.prototype, null].includes(Object.getPrototypeOf(value)))
84
+ )
85
+ return value;
86
+ return present(value);
87
+ }
88
+
89
+ /** Two required scalar arguments also work with hosts that enforce strict tool schemas. */
90
+ export function managedTools(session, sources, question) {
91
+ const tools = session.tools(sources, { adaptiveRead: question });
92
+ const index = tools.findIndex((t) => t.definition.name === "inspect_result");
93
+ const [inspect] = tools.splice(index, 1);
94
+ tools.push({
95
+ definition: {
96
+ name: "inspect_result",
97
+ description:
98
+ "Read missing evidence from this run without fetching again. If selection already contains the requested facts, answer directly. requestedUrl is the exact URL used; complete counts cover the entire selected text.",
99
+ inputSchema: {
100
+ type: "object",
101
+ properties: {
102
+ ref: {
103
+ type: "string",
104
+ description: "A ref returned by a tool in this run.",
105
+ },
106
+ query: {
107
+ type: "string",
108
+ maxLength: 4096,
109
+ description:
110
+ 'Use a JSON Pointer such as /items/0, an empty string for the root, or a JSON selector string such as {"contains":"needle","limit":120}, {"countMatches":"literal"}, or {"path":"/rows","fields":["id"]}.',
111
+ },
112
+ },
113
+ required: ["ref", "query"],
114
+ additionalProperties: false,
115
+ },
116
+ annotations: { readOnlyHint: true },
117
+ },
118
+ async execute({ ref, query }, options) {
119
+ if (typeof query !== "string" || query.length > 4096)
120
+ return {
121
+ error:
122
+ "Use a JSON Pointer or a JSON selector string of up to 4096 characters.",
123
+ };
124
+ let selector;
125
+ try {
126
+ selector =
127
+ query === "" || query.startsWith("/")
128
+ ? { path: query }
129
+ : JSON.parse(query);
130
+ } catch {
131
+ return {
132
+ error: "Invalid query. Use a JSON Pointer or a JSON selector string.",
133
+ };
134
+ }
135
+ if (
136
+ !selector ||
137
+ typeof selector !== "object" ||
138
+ Array.isArray(selector) ||
139
+ Object.hasOwn(selector, "ref")
140
+ )
141
+ return {
142
+ error:
143
+ "Pass ref separately and use a JSON Pointer or a selector object in query.",
144
+ };
145
+ try {
146
+ return await inspect.execute({ ...selector, ref }, options);
147
+ } catch (error) {
148
+ if (options?.signal?.aborted) throw error;
149
+ return { error: error.message };
150
+ }
151
+ },
152
+ });
153
+ return tools;
154
+ }
@@ -0,0 +1,13 @@
1
+ import type { SpliceRunOptions } from "../dist/core.js";
2
+
3
+ export interface ExecutableTool<Result> {
4
+ definition: {
5
+ name: string;
6
+ description?: string;
7
+ inputSchema: Record<string, unknown>;
8
+ };
9
+ execute(
10
+ args: Record<string, unknown>,
11
+ options?: SpliceRunOptions,
12
+ ): Promise<Result>;
13
+ }