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.
- package/LICENSE +21 -0
- package/README.md +104 -2
- package/dist/abortable.d.ts +6 -0
- package/dist/abortable.js +50 -0
- package/dist/adaptive-read.d.ts +50 -0
- package/dist/adaptive-read.js +780 -0
- package/dist/answer-wait.d.ts +7 -0
- package/dist/answer-wait.js +45 -0
- package/dist/cache-reads.d.ts +18 -0
- package/dist/cache-reads.js +89 -0
- package/dist/calibration-ledger.d.ts +37 -0
- package/dist/calibration-ledger.js +148 -0
- package/dist/calibration-marker.d.ts +4 -0
- package/dist/calibration-marker.js +77 -0
- package/dist/catalog-setup.d.ts +33 -0
- package/dist/catalog-setup.js +89 -0
- package/dist/catalog.d.ts +10 -0
- package/dist/catalog.js +42 -0
- package/dist/checkpoint-files.d.ts +15 -0
- package/dist/checkpoint-files.js +99 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +1454 -0
- package/dist/coalesce-reads.d.ts +6 -0
- package/dist/coalesce-reads.js +33 -0
- package/dist/codegen.d.ts +44 -0
- package/dist/codegen.js +479 -0
- package/dist/contract-caller.d.ts +23 -0
- package/dist/contract-caller.js +326 -0
- package/dist/contract-corrections.d.ts +35 -0
- package/dist/contract-corrections.js +159 -0
- package/dist/contract-schema.d.ts +7 -0
- package/dist/contract-schema.js +156 -0
- package/dist/contracts.d.ts +72 -0
- package/dist/contracts.js +370 -0
- package/dist/core.d.ts +44 -0
- package/dist/core.js +43 -0
- package/dist/db-final-answer.d.ts +9 -0
- package/dist/db-final-answer.js +62 -0
- package/dist/define.d.ts +78 -0
- package/dist/define.js +14 -0
- package/dist/doctor.d.ts +22 -0
- package/dist/doctor.js +91 -0
- package/dist/drift.d.ts +23 -0
- package/dist/drift.js +111 -0
- package/dist/execution.d.ts +38 -0
- package/dist/execution.js +66 -0
- package/dist/extract.d.ts +34 -0
- package/dist/extract.js +73 -0
- package/dist/final-answer-stores.d.ts +71 -0
- package/dist/final-answer-stores.js +72 -0
- package/dist/final-answer.d.ts +32 -0
- package/dist/final-answer.js +104 -0
- package/dist/impact.d.ts +48 -0
- package/dist/impact.js +71 -0
- package/dist/index.d.ts +51 -0
- package/dist/index.js +47 -0
- package/dist/local-tool.d.ts +18 -0
- package/dist/local-tool.js +32 -0
- package/dist/mcp-apps.d.ts +53 -0
- package/dist/mcp-apps.js +32 -0
- package/dist/mcp-event-delivery.d.ts +98 -0
- package/dist/mcp-event-delivery.js +211 -0
- package/dist/mcp-extensions.d.ts +46 -0
- package/dist/mcp-extensions.js +200 -0
- package/dist/mcp-peer.d.ts +45 -0
- package/dist/mcp-peer.js +207 -0
- package/dist/mcp-server-card.d.ts +21 -0
- package/dist/mcp-server-card.js +54 -0
- package/dist/ordered-transport.d.ts +12 -0
- package/dist/ordered-transport.js +106 -0
- package/dist/page-checkpoint.d.ts +71 -0
- package/dist/page-checkpoint.js +286 -0
- package/dist/page-read-gate.d.ts +15 -0
- package/dist/page-read-gate.js +48 -0
- package/dist/pattern.d.ts +3 -0
- package/dist/pattern.js +54 -0
- package/dist/postgres.d.ts +41 -0
- package/dist/postgres.js +264 -0
- package/dist/probe.d.ts +29 -0
- package/dist/probe.js +121 -0
- package/dist/proxy.d.ts +40 -0
- package/dist/proxy.js +436 -0
- package/dist/read-pages.d.ts +25 -0
- package/dist/read-pages.js +85 -0
- package/dist/read-policy.d.ts +6 -0
- package/dist/read-policy.js +16 -0
- package/dist/read-steps.d.ts +12 -0
- package/dist/read-steps.js +36 -0
- package/dist/result-session.d.ts +109 -0
- package/dist/result-session.js +620 -0
- package/dist/route-checkpoint.d.ts +3 -0
- package/dist/route-checkpoint.js +80 -0
- package/dist/route-driver-cli.d.ts +3 -0
- package/dist/route-driver-cli.js +43 -0
- package/dist/route-evaluation.d.ts +141 -0
- package/dist/route-evaluation.js +329 -0
- package/dist/row-groups.d.ts +17 -0
- package/dist/row-groups.js +79 -0
- package/dist/row-query.d.ts +62 -0
- package/dist/row-query.js +172 -0
- package/dist/rules.d.ts +30 -0
- package/dist/rules.js +72 -0
- package/dist/run-diagnostics.d.ts +75 -0
- package/dist/run-diagnostics.js +212 -0
- package/dist/runtime.d.ts +6 -0
- package/dist/runtime.js +26 -0
- package/dist/schema.d.ts +17 -0
- package/dist/schema.js +299 -0
- package/dist/search-fetch.d.ts +50 -0
- package/dist/search-fetch.js +264 -0
- package/dist/shape.d.ts +91 -0
- package/dist/shape.js +499 -0
- package/dist/skill-files.d.ts +9 -0
- package/dist/skill-files.js +49 -0
- package/dist/splice-diagnostics.d.ts +44 -0
- package/dist/splice-diagnostics.js +88 -0
- package/dist/splice-measure.d.ts +33 -0
- package/dist/splice-measure.js +55 -0
- package/dist/splice-project.d.ts +125 -0
- package/dist/splice-project.js +348 -0
- package/dist/splice-recording.d.ts +132 -0
- package/dist/splice-recording.js +481 -0
- package/dist/splice.d.ts +181 -0
- package/dist/splice.js +1263 -0
- package/dist/sqlite-checkpoint-store.d.ts +5 -0
- package/dist/sqlite-checkpoint-store.js +91 -0
- package/dist/sqlite-checkpoint-worker.d.ts +1 -0
- package/dist/sqlite-checkpoint-worker.js +115 -0
- package/dist/storage.d.ts +17 -0
- package/dist/storage.js +1 -0
- package/dist/store.d.ts +151 -0
- package/dist/store.js +735 -0
- package/dist/test-difference.d.ts +13 -0
- package/dist/test-difference.js +42 -0
- package/dist/testing.d.ts +122 -0
- package/dist/testing.js +261 -0
- package/dist/text-pages.d.ts +24 -0
- package/dist/text-pages.js +36 -0
- package/dist/tool-discovery.d.ts +59 -0
- package/dist/tool-discovery.js +136 -0
- package/dist/unevaluated.d.ts +7 -0
- package/dist/unevaluated.js +156 -0
- package/dist/v2.d.ts +49 -0
- package/dist/v2.js +413 -0
- package/dist/validate-output.d.ts +3 -0
- package/dist/validate-output.js +73 -0
- package/dist/version.d.ts +1 -0
- package/dist/version.js +1 -0
- package/dist/workflow-json.d.ts +8 -0
- package/dist/workflow-json.js +74 -0
- package/docs/AGENT-FRAMEWORKS.md +431 -0
- package/docs/BENCHMARKS.md +43 -0
- package/docs/INTEGRATION-QUICKSTART.md +859 -0
- package/docs/LEARNING-AND-STORAGE.md +393 -0
- package/docs/MCP.md +204 -0
- package/docs/PROJECTS-AND-UPGRADES.md +173 -0
- package/docs/PYTHON-REFERENCE.md +348 -0
- package/docs/PYTHON.md +120 -0
- package/docs/RECORDING-AND-CORRECTIONS.md +205 -0
- package/docs/TESTING.md +259 -0
- package/examples/mcp-app/build.mjs +11 -0
- package/examples/mcp-app/view.mjs +22 -0
- package/examples/quickstart.mjs +43 -0
- package/examples/route-driver.mjs +67 -0
- package/integrations/ai.d.mts +36 -0
- package/integrations/ai.mjs +178 -0
- package/integrations/call-options.mjs +9 -0
- package/integrations/langchain.d.mts +31 -0
- package/integrations/langchain.mjs +114 -0
- package/integrations/managed.mjs +154 -0
- package/integrations/types.d.mts +13 -0
- package/package.json +139 -4
|
@@ -0,0 +1,620 @@
|
|
|
1
|
+
import { prepareAdaptiveRead, requestedPageUrl, isPageResult, literalCount, } from "./adaptive-read.js";
|
|
2
|
+
import { SearchFetchTool } from "./search-fetch.js";
|
|
3
|
+
import { CatalogCall, CatalogSearch } from "./tool-discovery.js";
|
|
4
|
+
import { abortable, withCallDeadline } from "./abortable.js";
|
|
5
|
+
import { currentDiagnostics, recordView } from "./run-diagnostics.js";
|
|
6
|
+
import { randomBytes } from "node:crypto";
|
|
7
|
+
import { createGuardCompiler } from "./contract-caller.js";
|
|
8
|
+
import { defineLocalTool } from "./local-tool.js";
|
|
9
|
+
import { invokeTool } from "./execution.js";
|
|
10
|
+
import { copyJson, JSON_LIMIT, jsonObject, pointerParts, } from "./workflow-json.js";
|
|
11
|
+
/** Adapt already-authorized MCP definitions and their connected caller once. */
|
|
12
|
+
export function resultToolsFromMcp(catalog, caller) {
|
|
13
|
+
return catalog.tools.map((definition) => {
|
|
14
|
+
const name = definition.name;
|
|
15
|
+
return defineLocalTool(definition, (args, options) => invokeTool(caller, name, args, options));
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
/** Present a successful tool read using application-defined fields and its actual arguments. */
|
|
19
|
+
export function projectTool(source, project, options = {}) {
|
|
20
|
+
if (typeof project !== "function")
|
|
21
|
+
throw new TypeError("A result projector must be callable.");
|
|
22
|
+
const definition = copyJson(source.definition);
|
|
23
|
+
delete definition.outputSchema;
|
|
24
|
+
if (options.description !== undefined) {
|
|
25
|
+
if (typeof options.description !== "string")
|
|
26
|
+
throw new TypeError("Expected a tool description.");
|
|
27
|
+
definition.description = options.description;
|
|
28
|
+
}
|
|
29
|
+
let guard;
|
|
30
|
+
if (options.outputSchema !== undefined) {
|
|
31
|
+
if (!jsonObject(options.outputSchema))
|
|
32
|
+
throw new TypeError("Expected a projected output schema object.");
|
|
33
|
+
definition.outputSchema = copyJson(options.outputSchema);
|
|
34
|
+
guard = createGuardCompiler()(definition.outputSchema, definition.name, "output");
|
|
35
|
+
}
|
|
36
|
+
return {
|
|
37
|
+
definition,
|
|
38
|
+
async execute(args, runOptions) {
|
|
39
|
+
runOptions?.signal?.throwIfAborted();
|
|
40
|
+
if (!jsonObject(args))
|
|
41
|
+
throw new TypeError("Expected tool arguments to be an object.");
|
|
42
|
+
const requested = copyJson(args);
|
|
43
|
+
const value = await source.execute(copyJson(requested), runOptions);
|
|
44
|
+
try {
|
|
45
|
+
const output = copyJson(await abortable(() => project(value, requested), runOptions?.signal));
|
|
46
|
+
if (guard && !guard(output))
|
|
47
|
+
throw new Error("Projected output does not match its schema.");
|
|
48
|
+
return output;
|
|
49
|
+
}
|
|
50
|
+
catch (cause) {
|
|
51
|
+
runOptions?.signal?.throwIfAborted();
|
|
52
|
+
throw new Error("Tool completed but its result could not be projected.", { cause });
|
|
53
|
+
}
|
|
54
|
+
},
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
const viewBytes = 8192;
|
|
58
|
+
const bytes = (value) => Buffer.byteLength(JSON.stringify(value));
|
|
59
|
+
const objectSchema = (properties, required) => ({ type: "object", properties, required, additionalProperties: false });
|
|
60
|
+
const text = { type: "string", maxLength: 2048 };
|
|
61
|
+
const inspectSchema = objectSchema({
|
|
62
|
+
ref: {
|
|
63
|
+
...text,
|
|
64
|
+
description: "Toolsplice result handle from this run. Use it only with inspect_result or call_with_result.",
|
|
65
|
+
},
|
|
66
|
+
path: {
|
|
67
|
+
...text,
|
|
68
|
+
description: "JSON Pointer into the returned value, e.g. /report/narrative. Escape a slash inside a key as ~1 and a tilde as ~0. Omit for the root.",
|
|
69
|
+
},
|
|
70
|
+
keys: { type: "boolean" },
|
|
71
|
+
contains: { type: "string", minLength: 1, maxLength: 256 },
|
|
72
|
+
countMatches: { type: "string", minLength: 1, maxLength: 256,
|
|
73
|
+
description: "Count every non-overlapping, case-sensitive occurrence of this literal in the entire text at path, including zero. Use alone with ref and optional path." },
|
|
74
|
+
offset: { type: "integer", minimum: 0, maximum: 2147483647 },
|
|
75
|
+
limit: { type: "integer", minimum: 1, maximum: 2048 },
|
|
76
|
+
fields: { type: "array", minItems: 1, maxItems: 16, items: text },
|
|
77
|
+
where: objectSchema({
|
|
78
|
+
field: text,
|
|
79
|
+
equals: { type: ["string", "number", "boolean", "null"] },
|
|
80
|
+
}, ["field", "equals"]),
|
|
81
|
+
}, ["ref"]);
|
|
82
|
+
const selectSchema = {
|
|
83
|
+
...objectSchema(Object.fromEntries(Object.entries(inspectSchema.properties).filter(([key]) => key !== "ref")), []),
|
|
84
|
+
description: "Select from the value AFTER all native arguments are applied. Omit path when the provider already returns the text or array itself. For a literal marker use contains; limit counts characters starting at the marker. For object rows use fields and where. A page without nextOffset is complete, including an empty rows array.",
|
|
85
|
+
};
|
|
86
|
+
const extensibleKeys = new Set([
|
|
87
|
+
"type",
|
|
88
|
+
"properties",
|
|
89
|
+
"required",
|
|
90
|
+
"additionalProperties",
|
|
91
|
+
"$schema",
|
|
92
|
+
"$id",
|
|
93
|
+
"$defs",
|
|
94
|
+
"definitions",
|
|
95
|
+
"title",
|
|
96
|
+
"description",
|
|
97
|
+
"examples",
|
|
98
|
+
"default",
|
|
99
|
+
"$comment",
|
|
100
|
+
]);
|
|
101
|
+
function withSelect(schema) {
|
|
102
|
+
const properties = schema.properties ?? {};
|
|
103
|
+
if (schema.type !== "object" ||
|
|
104
|
+
!jsonObject(properties) ||
|
|
105
|
+
Object.hasOwn(properties, "select") ||
|
|
106
|
+
Object.keys(schema).some((k) => !extensibleKeys.has(k)))
|
|
107
|
+
throw new Error("Cannot extend this input schema with select. Use readAndSelect with separate arguments.");
|
|
108
|
+
return copyJson({
|
|
109
|
+
...schema,
|
|
110
|
+
properties: { ...properties, select: selectSchema },
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
let selectGuard;
|
|
114
|
+
let inspectGuard;
|
|
115
|
+
const measure = (v) => Array.isArray(v) ? "array" : v === null ? "null" : typeof v;
|
|
116
|
+
function positive(value, name, minimum = 1) {
|
|
117
|
+
if (!Number.isSafeInteger(value) || value < minimum)
|
|
118
|
+
throw new RangeError(`Invalid ${name}.`);
|
|
119
|
+
return value;
|
|
120
|
+
}
|
|
121
|
+
// Preview is a sample. Only resolve() and non-preview inspection fields carry exact values.
|
|
122
|
+
function preview(value, depth = 0) {
|
|
123
|
+
if (typeof value === "string") {
|
|
124
|
+
let prefix = "", length = 0;
|
|
125
|
+
for (const char of value) {
|
|
126
|
+
if (length++ === 64)
|
|
127
|
+
return prefix + "…";
|
|
128
|
+
prefix += char;
|
|
129
|
+
}
|
|
130
|
+
return prefix;
|
|
131
|
+
}
|
|
132
|
+
if (Array.isArray(value))
|
|
133
|
+
return depth >= 2
|
|
134
|
+
? { items: value.length }
|
|
135
|
+
: value.slice(0, 2).map((v) => preview(v, depth + 1));
|
|
136
|
+
if (jsonObject(value)) {
|
|
137
|
+
const keys = Object.keys(value);
|
|
138
|
+
if (depth >= 2)
|
|
139
|
+
return { properties: keys.length };
|
|
140
|
+
return Object.fromEntries(keys
|
|
141
|
+
.filter((key) => Buffer.byteLength(key) <= 64)
|
|
142
|
+
.slice(0, 4)
|
|
143
|
+
.map((key) => [key, preview(value[key], depth + 1)]));
|
|
144
|
+
}
|
|
145
|
+
return value;
|
|
146
|
+
}
|
|
147
|
+
function boundedPreview(value) {
|
|
148
|
+
const sample = preview(value);
|
|
149
|
+
if (bytes(sample) <= 1024)
|
|
150
|
+
return sample;
|
|
151
|
+
return {
|
|
152
|
+
type: measure(value),
|
|
153
|
+
...(jsonObject(value) ? { properties: Object.keys(value).length } : {}),
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
function selectFields(row, fields) {
|
|
157
|
+
if (!fields)
|
|
158
|
+
return row;
|
|
159
|
+
if (!jsonObject(row))
|
|
160
|
+
throw new SelectionMismatch("fields requires an object or object rows.");
|
|
161
|
+
return Object.fromEntries(fields.filter((k) => Object.hasOwn(row, k)).map((k) => [k, row[k]]));
|
|
162
|
+
}
|
|
163
|
+
class SelectionMismatch extends Error {
|
|
164
|
+
}
|
|
165
|
+
function pathValue(value, path) {
|
|
166
|
+
const parts = pointerParts(path);
|
|
167
|
+
if (parts.length > 32)
|
|
168
|
+
throw new Error("Result path exceeds 32 levels.");
|
|
169
|
+
for (const key of parts) {
|
|
170
|
+
if (Array.isArray(value) &&
|
|
171
|
+
/^(0|[1-9][0-9]*)$/.test(key) &&
|
|
172
|
+
Number(key) < value.length)
|
|
173
|
+
value = value[Number(key)];
|
|
174
|
+
else if (jsonObject(value) && Object.hasOwn(value, key))
|
|
175
|
+
value = value[key];
|
|
176
|
+
else
|
|
177
|
+
throw new SelectionMismatch("Result path does not exist.");
|
|
178
|
+
}
|
|
179
|
+
return value;
|
|
180
|
+
}
|
|
181
|
+
/** One instance per agent run. Retain large captures and values requested by first-read selection. */
|
|
182
|
+
export class ResultSession {
|
|
183
|
+
#values = new Map();
|
|
184
|
+
#inline;
|
|
185
|
+
#fallback;
|
|
186
|
+
#nativeOnCapacity;
|
|
187
|
+
#capacity;
|
|
188
|
+
#entries;
|
|
189
|
+
#used = 0;
|
|
190
|
+
#reservedReads = 0;
|
|
191
|
+
#closed = false;
|
|
192
|
+
constructor(options = {}) {
|
|
193
|
+
const { inlineBytes = 2048, maxBytes = 8 * 1024 * 1024, maxEntries = 32, adaptiveFallbackBytes = options.inlineBytes === undefined ? 32768 : 0, } = options;
|
|
194
|
+
if (options.nativeOnCapacity !== undefined &&
|
|
195
|
+
typeof options.nativeOnCapacity !== "boolean")
|
|
196
|
+
throw new TypeError("nativeOnCapacity must be boolean.");
|
|
197
|
+
this.#nativeOnCapacity = options.nativeOnCapacity === true;
|
|
198
|
+
this.#fallback = positive(adaptiveFallbackBytes, "adaptiveFallbackBytes", 0);
|
|
199
|
+
this.#inline = positive(inlineBytes, "inlineBytes", 0);
|
|
200
|
+
this.#capacity = positive(maxBytes, "maxBytes");
|
|
201
|
+
this.#entries = positive(maxEntries, "maxEntries");
|
|
202
|
+
}
|
|
203
|
+
#open() {
|
|
204
|
+
if (this.#closed)
|
|
205
|
+
throw new Error("Result session is closed.");
|
|
206
|
+
}
|
|
207
|
+
get hasRetainedResults() {
|
|
208
|
+
this.#open();
|
|
209
|
+
return this.#values.size > 0;
|
|
210
|
+
}
|
|
211
|
+
#lookup(ref, path) {
|
|
212
|
+
this.#open();
|
|
213
|
+
if (!this.#values.has(ref))
|
|
214
|
+
throw new Error("Unknown result reference in this run.");
|
|
215
|
+
return pathValue(this.#values.get(ref).value, path);
|
|
216
|
+
}
|
|
217
|
+
capture(input) {
|
|
218
|
+
return this.#store(input, null);
|
|
219
|
+
}
|
|
220
|
+
#store(input, sourceTool, mode = "preview", select, requestedUrl) {
|
|
221
|
+
this.#open();
|
|
222
|
+
const value = copyJson(input), size = bytes(value);
|
|
223
|
+
if (mode !== "reference" && size <= this.#inline)
|
|
224
|
+
return { value };
|
|
225
|
+
const adaptive = select?.(value, size <= this.#fallback ? size : undefined, requestedUrl);
|
|
226
|
+
if (adaptive?.native)
|
|
227
|
+
return { value: adaptive.value };
|
|
228
|
+
if (this.#values.size + this.#reservedReads >= this.#entries ||
|
|
229
|
+
size > this.#capacity - this.#used - this.#reservedReads) {
|
|
230
|
+
if (mode === "adaptive" && this.#nativeOnCapacity)
|
|
231
|
+
return { value };
|
|
232
|
+
throw new Error("Result session capacity exceeded.");
|
|
233
|
+
}
|
|
234
|
+
const ref = "result_" + randomBytes(16).toString("base64url");
|
|
235
|
+
this.#values.set(ref, { value, sourceTool });
|
|
236
|
+
this.#used += size;
|
|
237
|
+
if (adaptive) {
|
|
238
|
+
return {
|
|
239
|
+
ref,
|
|
240
|
+
partial: true,
|
|
241
|
+
selection: adaptive.selection,
|
|
242
|
+
...("headingEvidence" in adaptive && adaptive.headingEvidence
|
|
243
|
+
? { headingEvidence: adaptive.headingEvidence }
|
|
244
|
+
: {}),
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
if (mode !== "preview")
|
|
248
|
+
return { ref };
|
|
249
|
+
return {
|
|
250
|
+
ref,
|
|
251
|
+
bytes: size,
|
|
252
|
+
type: measure(value),
|
|
253
|
+
preview: boundedPreview(value),
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
#completed(value, name, mode = "preview", select, requestedUrl) {
|
|
257
|
+
try {
|
|
258
|
+
return this.#store(value, name, mode, select, requestedUrl);
|
|
259
|
+
}
|
|
260
|
+
catch (cause) {
|
|
261
|
+
throw new Error("Tool completed but its result could not be retained.", {
|
|
262
|
+
cause,
|
|
263
|
+
});
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
/** Capture the model-visible output of a native framework tool in this run. */
|
|
267
|
+
adaptivePresenter(question) {
|
|
268
|
+
this.#open();
|
|
269
|
+
const select = prepareAdaptiveRead(question);
|
|
270
|
+
return (name, args) => {
|
|
271
|
+
this.#open();
|
|
272
|
+
const submitted = requestedPageUrl(args);
|
|
273
|
+
return (value) => this.#adaptiveValue(value, name, submitted, select);
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
#adaptiveValue(value, name, submitted, select, measureView = true) {
|
|
277
|
+
const url = submitted && isPageResult(value) ? submitted : undefined;
|
|
278
|
+
const saved = this.#completed(value, name, "adaptive", select, url);
|
|
279
|
+
const visible = url ? { requestedUrl: url, ...saved } : saved.ref === undefined ? saved.value : saved;
|
|
280
|
+
if (measureView)
|
|
281
|
+
recordView(value, visible);
|
|
282
|
+
return visible;
|
|
283
|
+
}
|
|
284
|
+
/** Read once, retain the original and return only the requested view. */
|
|
285
|
+
async readAndSelect(tool, args, selection, options) {
|
|
286
|
+
this.#open();
|
|
287
|
+
options?.signal?.throwIfAborted();
|
|
288
|
+
const q = copyJson(selection);
|
|
289
|
+
selectGuard ??= createGuardCompiler()(selectSchema, "select", "input");
|
|
290
|
+
if (!selectGuard(q))
|
|
291
|
+
throw new Error("Invalid result selection.");
|
|
292
|
+
if (pointerParts(q.path ?? "").length > 32)
|
|
293
|
+
throw new Error("Result path exceeds 32 levels.");
|
|
294
|
+
if (this.#values.size + this.#reservedReads >= this.#entries ||
|
|
295
|
+
this.#used + this.#reservedReads >= this.#capacity)
|
|
296
|
+
throw new Error("Result session capacity exceeded.");
|
|
297
|
+
// Each selected read promises a reference, even if its result is small.
|
|
298
|
+
this.#reservedReads++;
|
|
299
|
+
let value;
|
|
300
|
+
try {
|
|
301
|
+
const input = copyJson(args);
|
|
302
|
+
value = await withCallDeadline(options, "Selected read timed out.", bounded => tool.execute(input, bounded));
|
|
303
|
+
}
|
|
304
|
+
finally {
|
|
305
|
+
this.#reservedReads--;
|
|
306
|
+
}
|
|
307
|
+
const ref = this.#completed(value, tool.definition.name, "reference").ref;
|
|
308
|
+
try {
|
|
309
|
+
return { ref, ...this.inspect({ ...q, ref }) };
|
|
310
|
+
}
|
|
311
|
+
catch (error) {
|
|
312
|
+
if (!(error instanceof SelectionMismatch))
|
|
313
|
+
throw error;
|
|
314
|
+
return {
|
|
315
|
+
ref,
|
|
316
|
+
selectionError: error.message + " Use inspect_result with this ref.",
|
|
317
|
+
};
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
resolve(ref, path = "") {
|
|
321
|
+
return copyJson(this.#lookup(ref, path));
|
|
322
|
+
}
|
|
323
|
+
close() {
|
|
324
|
+
this.#closed = true;
|
|
325
|
+
this.#values.clear();
|
|
326
|
+
this.#used = 0;
|
|
327
|
+
}
|
|
328
|
+
inspect(selection) {
|
|
329
|
+
currentDiagnostics()?.record({ type: "inspect" });
|
|
330
|
+
const q = copyJson(selection);
|
|
331
|
+
inspectGuard ??= createGuardCompiler()(inspectSchema, "inspect_result", "input");
|
|
332
|
+
if (!inspectGuard(q))
|
|
333
|
+
throw new Error("Invalid result selection.");
|
|
334
|
+
const value = this.#lookup(q.ref, q.path ?? ""), offset = q.offset ?? 0;
|
|
335
|
+
if (q.countMatches !== undefined) {
|
|
336
|
+
if (typeof value !== "string" || Object.keys(q).some(k => !["ref", "path", "countMatches"].includes(k)))
|
|
337
|
+
throw new SelectionMismatch("countMatches requires a text path without other selectors.");
|
|
338
|
+
return literalCount(value, q.countMatches);
|
|
339
|
+
}
|
|
340
|
+
if (q.contains !== undefined && typeof value !== "string")
|
|
341
|
+
throw new SelectionMismatch("contains requires text.");
|
|
342
|
+
if (q.keys) {
|
|
343
|
+
if (!jsonObject(value) || q.fields || q.where)
|
|
344
|
+
throw new SelectionMismatch("keys requires an object without fields or where.");
|
|
345
|
+
const all = Object.keys(value), keys = [];
|
|
346
|
+
let i = offset, used = 128;
|
|
347
|
+
for (; i < all.length && keys.length < Math.min(q.limit ?? 20, 100); i++) {
|
|
348
|
+
const size = bytes(all[i]) + 1;
|
|
349
|
+
if (size > viewBytes - 128)
|
|
350
|
+
throw new SelectionMismatch("Object key exceeds the inspection byte limit.");
|
|
351
|
+
if (used + size > viewBytes)
|
|
352
|
+
break;
|
|
353
|
+
used += size;
|
|
354
|
+
keys.push(all[i]);
|
|
355
|
+
}
|
|
356
|
+
return { keys, ...(i < all.length ? { nextOffset: i } : {}) };
|
|
357
|
+
}
|
|
358
|
+
if (q.where && !Array.isArray(value))
|
|
359
|
+
throw new SelectionMismatch("where requires an array.");
|
|
360
|
+
if (Array.isArray(value)) {
|
|
361
|
+
const rows = [];
|
|
362
|
+
let used = 128, i = offset;
|
|
363
|
+
for (; i < value.length && rows.length < Math.min(100, q.limit ?? 20); i++) {
|
|
364
|
+
const row = value[i];
|
|
365
|
+
if (q.where &&
|
|
366
|
+
(!jsonObject(row) ||
|
|
367
|
+
!Object.hasOwn(row, q.where.field) ||
|
|
368
|
+
row[q.where.field] !== q.where.equals))
|
|
369
|
+
continue;
|
|
370
|
+
const selected = selectFields(row, q.fields);
|
|
371
|
+
let entry = { index: i, value: selected };
|
|
372
|
+
if (bytes(entry) > viewBytes - 128)
|
|
373
|
+
entry = { index: i, preview: boundedPreview(selected) };
|
|
374
|
+
const size = bytes(entry) + 1;
|
|
375
|
+
if (used + size > viewBytes)
|
|
376
|
+
break;
|
|
377
|
+
rows.push(entry);
|
|
378
|
+
used += size;
|
|
379
|
+
}
|
|
380
|
+
return {
|
|
381
|
+
rows: copyJson(rows),
|
|
382
|
+
...(i < value.length ? { nextOffset: i } : {}),
|
|
383
|
+
};
|
|
384
|
+
}
|
|
385
|
+
if (typeof value === "string") {
|
|
386
|
+
if (q.fields)
|
|
387
|
+
throw new SelectionMismatch("fields requires an object or object rows.");
|
|
388
|
+
// Work in Unicode code points without expanding the entire stored string.
|
|
389
|
+
let index = 0, position = 0;
|
|
390
|
+
while (position < offset && index < value.length) {
|
|
391
|
+
index += value.codePointAt(index) > 0xffff ? 2 : 1;
|
|
392
|
+
position++;
|
|
393
|
+
}
|
|
394
|
+
if (q.contains !== undefined) {
|
|
395
|
+
const match = value.indexOf(q.contains, index);
|
|
396
|
+
if (match < 0)
|
|
397
|
+
return { found: false };
|
|
398
|
+
while (index < match) {
|
|
399
|
+
index += value.codePointAt(index) > 0xffff ? 2 : 1;
|
|
400
|
+
position++;
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
const start = position, from = index, limit = q.limit ?? 512;
|
|
404
|
+
let used = 128;
|
|
405
|
+
while (index < value.length && position - start < limit) {
|
|
406
|
+
const length = value.codePointAt(index) > 0xffff ? 2 : 1;
|
|
407
|
+
const cost = bytes(value.slice(index, index + length)) - 2;
|
|
408
|
+
if (used + cost > viewBytes)
|
|
409
|
+
break;
|
|
410
|
+
used += cost;
|
|
411
|
+
index += length;
|
|
412
|
+
position++;
|
|
413
|
+
}
|
|
414
|
+
return {
|
|
415
|
+
text: value.slice(from, index),
|
|
416
|
+
...(q.contains !== undefined ? { offset: start } : {}),
|
|
417
|
+
...(index < value.length ? { nextOffset: position } : {}),
|
|
418
|
+
};
|
|
419
|
+
}
|
|
420
|
+
if (q.offset !== undefined || q.limit !== undefined)
|
|
421
|
+
throw new SelectionMismatch("Paging requires text or an array.");
|
|
422
|
+
const selected = selectFields(value, q.fields);
|
|
423
|
+
return bytes(selected) <= viewBytes - 128
|
|
424
|
+
? { value: copyJson(selected) }
|
|
425
|
+
: { preview: boundedPreview(selected), partial: true };
|
|
426
|
+
}
|
|
427
|
+
/** Select the tools to advertise on the next model turn in hosts with dynamic catalogs. */
|
|
428
|
+
availableTools(tools, { remainingTurns } = {}) {
|
|
429
|
+
this.#open();
|
|
430
|
+
if (remainingTurns !== undefined) {
|
|
431
|
+
if (!Number.isSafeInteger(remainingTurns) || remainingTurns < 0)
|
|
432
|
+
throw new RangeError("remainingTurns must be a nonnegative integer.");
|
|
433
|
+
if (remainingTurns <= 1)
|
|
434
|
+
return [];
|
|
435
|
+
}
|
|
436
|
+
return tools.filter((t) => this.#values.size > 0 ||
|
|
437
|
+
!["inspect_result", "call_with_result"].includes(t.definition.name));
|
|
438
|
+
}
|
|
439
|
+
/** Register input tools for capture. Only forwardTo destinations accept reference handoffs. */
|
|
440
|
+
tools(input, { forwardTo = {}, authorizeForward, selectOnRead = [], adaptiveRead, } = {}) {
|
|
441
|
+
this.#open();
|
|
442
|
+
if (authorizeForward !== undefined &&
|
|
443
|
+
typeof authorizeForward !== "function")
|
|
444
|
+
throw new TypeError("Expected an authorization callback.");
|
|
445
|
+
if (!Array.isArray(selectOnRead) ||
|
|
446
|
+
selectOnRead.some((name) => !input.some((t) => t.definition.name === name)))
|
|
447
|
+
throw new Error("selectOnRead must list registered tool names.");
|
|
448
|
+
const selectLarge = adaptiveRead === undefined
|
|
449
|
+
? undefined
|
|
450
|
+
: prepareAdaptiveRead(adaptiveRead);
|
|
451
|
+
const selected = new Set(selectOnRead);
|
|
452
|
+
const destinations = new Map();
|
|
453
|
+
const result = [];
|
|
454
|
+
for (const tool of input) {
|
|
455
|
+
const { name, inputSchema, annotations } = tool.definition;
|
|
456
|
+
const description = selectLarge &&
|
|
457
|
+
/\b(?:each|multiple|in order|in this order)\b/i.test(adaptiveRead)
|
|
458
|
+
? [
|
|
459
|
+
tool.definition.description,
|
|
460
|
+
"Issue independent reads together in one turn. When the requested fields are available, answer directly.",
|
|
461
|
+
]
|
|
462
|
+
.filter(Boolean)
|
|
463
|
+
.join(" ")
|
|
464
|
+
: tool.definition.description;
|
|
465
|
+
if (destinations.has(name) ||
|
|
466
|
+
["inspect_result", "call_with_result"].includes(name))
|
|
467
|
+
throw new Error("Duplicate or reserved session tool name.");
|
|
468
|
+
destinations.set(name, tool);
|
|
469
|
+
result.push({
|
|
470
|
+
definition: {
|
|
471
|
+
name,
|
|
472
|
+
inputSchema: selected.has(name)
|
|
473
|
+
? withSelect(inputSchema)
|
|
474
|
+
: copyJson(inputSchema),
|
|
475
|
+
...(selected.has(name)
|
|
476
|
+
? {
|
|
477
|
+
description: [
|
|
478
|
+
description,
|
|
479
|
+
"For a passage in long text, pass select.contains on this read. Use native filters for small lookups. A result ref can be inspected or handed off whole within this run.",
|
|
480
|
+
]
|
|
481
|
+
.filter(Boolean)
|
|
482
|
+
.join(" "),
|
|
483
|
+
}
|
|
484
|
+
: description === undefined
|
|
485
|
+
? {}
|
|
486
|
+
: { description }),
|
|
487
|
+
...(annotations ? { annotations: copyJson(annotations) } : {}),
|
|
488
|
+
},
|
|
489
|
+
execute: async (args, options) => {
|
|
490
|
+
this.#open();
|
|
491
|
+
options?.signal?.throwIfAborted();
|
|
492
|
+
const submitted = selectLarge ? requestedPageUrl(args) : undefined;
|
|
493
|
+
if (selected.has(name) && Object.hasOwn(args, "select")) {
|
|
494
|
+
const { select, ...providerArgs } = copyJson(args);
|
|
495
|
+
const view = await this.readAndSelect(tool, providerArgs, select, options);
|
|
496
|
+
return submitted && isPageResult(this.#lookup(view.ref, ""))
|
|
497
|
+
? { requestedUrl: submitted, ...view }
|
|
498
|
+
: view;
|
|
499
|
+
}
|
|
500
|
+
if (tool instanceof CatalogSearch)
|
|
501
|
+
return tool.execute(args);
|
|
502
|
+
const resolved = tool instanceof CatalogCall
|
|
503
|
+
? tool.resolve(args)
|
|
504
|
+
: { tool, input: args };
|
|
505
|
+
const source = resolved.tool;
|
|
506
|
+
const sourceUrl = selectLarge && tool instanceof CatalogCall
|
|
507
|
+
? requestedPageUrl(resolved.input)
|
|
508
|
+
: submitted;
|
|
509
|
+
const value = await withCallDeadline(options, "Tool read timed out.", bounded => source.execute(resolved.input, bounded));
|
|
510
|
+
if (!selectLarge)
|
|
511
|
+
return this.#completed(value, source.definition.name);
|
|
512
|
+
if (source instanceof SearchFetchTool &&
|
|
513
|
+
jsonObject(value) &&
|
|
514
|
+
typeof value.requestedUrl === "string" &&
|
|
515
|
+
isPageResult(value.page)) {
|
|
516
|
+
const page = this.#adaptiveValue(value.page, source.definition.name, value.requestedUrl, selectLarge, false);
|
|
517
|
+
if (jsonObject(page) &&
|
|
518
|
+
jsonObject(page.selection) &&
|
|
519
|
+
(Object.hasOwn(page.selection, "heading") ||
|
|
520
|
+
Object.hasOwn(page.selection, "headings") ||
|
|
521
|
+
Object.hasOwn(page.selection, "occurrences"))) {
|
|
522
|
+
const visible = { requestedUrl: value.requestedUrl, pageEvidence: page.selection, fullPageRef: page.ref };
|
|
523
|
+
recordView(value, visible);
|
|
524
|
+
return visible;
|
|
525
|
+
}
|
|
526
|
+
recordView(value, page);
|
|
527
|
+
return page;
|
|
528
|
+
}
|
|
529
|
+
return this.#adaptiveValue(value, source.definition.name, sourceUrl, selectLarge);
|
|
530
|
+
},
|
|
531
|
+
});
|
|
532
|
+
}
|
|
533
|
+
result.push({
|
|
534
|
+
definition: {
|
|
535
|
+
name: "inspect_result",
|
|
536
|
+
description: "Read a stored result by ref and JSON Pointer path without fetching again. Set keys=true to list object keys, or contains to find a literal text passage. Page text or rows with offset and limit. For rows, fields selects named keys and where matches one field exactly. Row indices refer to the original array.",
|
|
537
|
+
inputSchema: copyJson(inspectSchema),
|
|
538
|
+
annotations: { readOnlyHint: true },
|
|
539
|
+
},
|
|
540
|
+
execute: async (args) => this.inspect(args),
|
|
541
|
+
});
|
|
542
|
+
if (!jsonObject(forwardTo))
|
|
543
|
+
throw new Error("forwardTo must map each destination to allowed arguments.");
|
|
544
|
+
const routes = new Map();
|
|
545
|
+
const validators = new Map();
|
|
546
|
+
const names = Object.keys(forwardTo);
|
|
547
|
+
if (!names.length)
|
|
548
|
+
return result;
|
|
549
|
+
const compile = createGuardCompiler();
|
|
550
|
+
for (const name of names) {
|
|
551
|
+
const target = destinations.get(name), fields = forwardTo[name];
|
|
552
|
+
if (!target ||
|
|
553
|
+
!Array.isArray(fields) ||
|
|
554
|
+
!fields.length ||
|
|
555
|
+
fields.some((k) => typeof k !== "string" || !k))
|
|
556
|
+
throw new Error("Invalid forwarding destination or argument list.");
|
|
557
|
+
routes.set(name, new Set(fields));
|
|
558
|
+
validators.set(name, compile(copyJson(target.definition.inputSchema), name, "input"));
|
|
559
|
+
}
|
|
560
|
+
const schema = objectSchema({
|
|
561
|
+
tool: { type: "string", enum: names },
|
|
562
|
+
argument: {
|
|
563
|
+
type: "string",
|
|
564
|
+
enum: [...new Set([...routes.values()].flatMap((keys) => [...keys]))],
|
|
565
|
+
},
|
|
566
|
+
ref: text,
|
|
567
|
+
path: text,
|
|
568
|
+
arguments: {
|
|
569
|
+
type: "object",
|
|
570
|
+
description: "Other literal arguments for the destination.",
|
|
571
|
+
},
|
|
572
|
+
}, ["tool", "argument", "ref"]);
|
|
573
|
+
const check = createGuardCompiler()(schema, "call_with_result", "input");
|
|
574
|
+
result.push({
|
|
575
|
+
definition: {
|
|
576
|
+
name: "call_with_result",
|
|
577
|
+
description: "Call an allowed tool once with an exact stored value in one named argument. Optionally select it by JSON Pointer path. Supply other arguments literally.",
|
|
578
|
+
inputSchema: copyJson(schema),
|
|
579
|
+
},
|
|
580
|
+
execute: async (input, options) => {
|
|
581
|
+
const q = copyJson(input);
|
|
582
|
+
if (!check(q))
|
|
583
|
+
throw new Error("Invalid result handoff.");
|
|
584
|
+
const args = (q.arguments ?? {}), key = q.argument;
|
|
585
|
+
const name = q.tool;
|
|
586
|
+
if (!routes.get(name)?.has(key))
|
|
587
|
+
throw new Error("Destination argument is not allowed.");
|
|
588
|
+
if (Object.hasOwn(args, key))
|
|
589
|
+
throw new Error("Handoff argument also supplied literally.");
|
|
590
|
+
const value = this.#lookup(q.ref, q.path ?? "");
|
|
591
|
+
const bound = copyJson({ ...args, [key]: value }, JSON_LIMIT);
|
|
592
|
+
if (!validators.get(name)(bound))
|
|
593
|
+
throw new Error("Destination arguments do not match its input schema.");
|
|
594
|
+
options?.signal?.throwIfAborted();
|
|
595
|
+
if (authorizeForward) {
|
|
596
|
+
let allowed;
|
|
597
|
+
try {
|
|
598
|
+
allowed = await authorizeForward({
|
|
599
|
+
sourceTool: this.#values.get(q.ref).sourceTool,
|
|
600
|
+
tool: name,
|
|
601
|
+
argument: key,
|
|
602
|
+
path: q.path ?? "",
|
|
603
|
+
arguments: copyJson(bound),
|
|
604
|
+
});
|
|
605
|
+
}
|
|
606
|
+
catch {
|
|
607
|
+
options?.signal?.throwIfAborted();
|
|
608
|
+
throw new Error("Result handoff authorization failed.");
|
|
609
|
+
}
|
|
610
|
+
if (allowed !== true)
|
|
611
|
+
throw new Error("Result handoff denied.");
|
|
612
|
+
}
|
|
613
|
+
this.#open();
|
|
614
|
+
options?.signal?.throwIfAborted();
|
|
615
|
+
return this.#completed(await destinations.get(name).execute(bound, options), name);
|
|
616
|
+
},
|
|
617
|
+
});
|
|
618
|
+
return result;
|
|
619
|
+
}
|
|
620
|
+
}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import type { RouteTrial } from "./route-evaluation.js";
|
|
2
|
+
export { CheckpointError, checkpointMessages } from "./checkpoint-files.js";
|
|
3
|
+
export declare function openRouteCheckpoint(directory: string, descriptor: object, cases: readonly unknown[], retry: boolean): (index: number, run: () => Promise<RouteTrial>, validate: (row: unknown) => row is RouteTrial) => Promise<RouteTrial>;
|