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,212 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ function outcomeOf(error) {
3
+ return error instanceof Error && error.name === "AbortError"
4
+ ? "cancelled"
5
+ : error instanceof Error && error.name === "TimeoutError"
6
+ ? "timeout"
7
+ : "error";
8
+ }
9
+ const active = new AsyncLocalStorage();
10
+ /** One observer per agent run. Events contain bounded operation names, counts and timing only. */
11
+ export class RunDiagnostics {
12
+ #started;
13
+ #ended;
14
+ #route;
15
+ #outcome;
16
+ #events;
17
+ #counts = {
18
+ searches: 0,
19
+ fetches: 0,
20
+ retries: 0,
21
+ inspections: 0,
22
+ views: 0,
23
+ upstreamBytes: 0,
24
+ inputBytes: 0,
25
+ visibleBytes: 0,
26
+ deadlines: 0,
27
+ cancellations: 0,
28
+ handoffErrors: 0,
29
+ modelCalls: 0,
30
+ inputTokens: 0,
31
+ outputTokens: 0,
32
+ cachedInputTokens: 0,
33
+ knownCostUsd: 0,
34
+ unpricedCalls: 0,
35
+ };
36
+ constructor(options = {}) {
37
+ if (options.onEvent !== undefined && typeof options.onEvent !== "function")
38
+ throw new TypeError("onEvent must be callable.");
39
+ this.#events = options.onEvent;
40
+ }
41
+ #start(route) {
42
+ if (this.#started !== undefined ||
43
+ !["native", "adaptive", "configured"].includes(route))
44
+ throw new Error("Use a fresh diagnostic observer per run and a valid route.");
45
+ this.#started = performance.now();
46
+ this.#route = route;
47
+ this.record({ type: "route", route });
48
+ }
49
+ #finish(outcome) {
50
+ this.#outcome = outcome;
51
+ this.record({ type: "finish", outcome });
52
+ this.#ended = performance.now();
53
+ }
54
+ async run(route, work) {
55
+ if (active.getStore() === this && this.#ended === undefined)
56
+ return await work();
57
+ this.#start(route);
58
+ let outcome = "ok";
59
+ try {
60
+ return await active.run(this, work);
61
+ }
62
+ catch (error) {
63
+ outcome = outcomeOf(error);
64
+ throw error;
65
+ }
66
+ finally {
67
+ this.#finish(outcome);
68
+ }
69
+ }
70
+ async *stream(route, work) {
71
+ if (active.getStore() === this && this.#ended === undefined) {
72
+ yield* await work();
73
+ return;
74
+ }
75
+ this.#start(route);
76
+ let outcome = "closed";
77
+ try {
78
+ const iterator = await active.run(this, async () => (await work())[Symbol.asyncIterator]());
79
+ const scoped = {
80
+ next: (...args) => active.run(this, () => iterator.next(...args)),
81
+ ...(iterator.return && {
82
+ return: (value) => active.run(this, () => iterator.return(value)),
83
+ }),
84
+ ...(iterator.throw && {
85
+ throw: (error) => active.run(this, () => iterator.throw(error)),
86
+ }),
87
+ };
88
+ yield* { [Symbol.asyncIterator]: () => scoped };
89
+ outcome = "ok";
90
+ }
91
+ catch (error) {
92
+ outcome = outcomeOf(error);
93
+ throw error;
94
+ }
95
+ finally {
96
+ this.#finish(outcome);
97
+ }
98
+ }
99
+ /** Attach provider-reported usage. Omit cost when the host has no price. */
100
+ modelCall(usage) {
101
+ const { inputTokens, outputTokens, cachedInputTokens = 0, costUsd } = usage;
102
+ if (![inputTokens, outputTokens, cachedInputTokens].every((n) => Number.isSafeInteger(n) && n >= 0) ||
103
+ cachedInputTokens > inputTokens ||
104
+ (costUsd !== undefined && !(Number.isFinite(costUsd) && costUsd >= 0)))
105
+ throw new TypeError("Invalid model usage.");
106
+ this.record({
107
+ type: "model",
108
+ inputTokens,
109
+ outputTokens,
110
+ cachedInputTokens,
111
+ costUsd: costUsd ?? null,
112
+ });
113
+ }
114
+ snapshot() {
115
+ return {
116
+ route: this.#route ?? null,
117
+ status: this.#outcome ?? (this.#started === undefined ? "idle" : "running"),
118
+ elapsedMs: this.#started === undefined
119
+ ? 0
120
+ : (this.#ended ?? performance.now()) - this.#started,
121
+ ...this.#counts,
122
+ };
123
+ }
124
+ /** @internal Only SDK instrumentation supplies events. */
125
+ record(event) {
126
+ if (this.#started === undefined || this.#ended !== undefined)
127
+ return;
128
+ switch (event.type) {
129
+ case "read":
130
+ this.#counts[event.operation === "search" ? "searches" : "fetches"]++;
131
+ break;
132
+ case "model":
133
+ this.#counts.modelCalls++;
134
+ this.#counts.inputTokens += event.inputTokens;
135
+ this.#counts.outputTokens += event.outputTokens;
136
+ this.#counts.cachedInputTokens += event.cachedInputTokens;
137
+ if (event.costUsd === null)
138
+ this.#counts.unpricedCalls++;
139
+ else
140
+ this.#counts.knownCostUsd += event.costUsd;
141
+ break;
142
+ case "upstream-bytes":
143
+ this.#counts.upstreamBytes += event.bytes;
144
+ break;
145
+ case "view":
146
+ this.#counts.views++;
147
+ this.#counts.inputBytes += event.inputBytes;
148
+ this.#counts.visibleBytes += event.visibleBytes;
149
+ break;
150
+ case "inspect":
151
+ this.#counts.inspections++;
152
+ break;
153
+ case "retry":
154
+ this.#counts.retries++;
155
+ break;
156
+ case "deadline":
157
+ this.#counts.deadlines++;
158
+ break;
159
+ case "cancel":
160
+ this.#counts.cancellations++;
161
+ break;
162
+ case "handoff-error":
163
+ this.#counts.handoffErrors++;
164
+ break;
165
+ }
166
+ if (this.#events) {
167
+ try {
168
+ const result = this.#events({
169
+ ...event,
170
+ elapsedMs: performance.now() - this.#started,
171
+ });
172
+ if (result &&
173
+ typeof result.then === "function")
174
+ Promise.resolve(result).catch(() => { });
175
+ }
176
+ catch {
177
+ /* Exporter failures do not alter tool results. */
178
+ }
179
+ }
180
+ }
181
+ }
182
+ export function currentDiagnostics() {
183
+ return active.getStore();
184
+ }
185
+ const byteLength = (value) => Buffer.byteLength(typeof value === "string" ? value : JSON.stringify(value));
186
+ export function recordReadResult(value) {
187
+ const trace = active.getStore();
188
+ if (trace) {
189
+ try {
190
+ trace.record({ type: "upstream-bytes", bytes: byteLength(value) });
191
+ }
192
+ catch {
193
+ /* Optional measurement. */
194
+ }
195
+ }
196
+ return value;
197
+ }
198
+ export function recordView(input, visible) {
199
+ const trace = active.getStore();
200
+ if (!trace)
201
+ return;
202
+ try {
203
+ trace.record({
204
+ type: "view",
205
+ inputBytes: byteLength(input),
206
+ visibleBytes: byteLength(visible),
207
+ });
208
+ }
209
+ catch {
210
+ /* Framework values may use a non-JSON representation. */
211
+ }
212
+ }
@@ -0,0 +1,6 @@
1
+ import type { Client } from "@modelcontextprotocol/sdk/client/index.js";
2
+ import { type ToolCaller, type BindingCallOptions, type DecodeMode, type ToolFunction } from "./execution.js";
3
+ export * from "./execution.js";
4
+ /** SDK 1.x adapter. Uses request() to preserve raw results before decoding. */
5
+ export declare function createToolCaller(client: Pick<Client, "request">, defaults?: BindingCallOptions): ToolCaller;
6
+ export declare function toolFunctions(client: Client, names: string[], mode?: DecodeMode, timeoutMs?: number): Record<string, ToolFunction>;
@@ -0,0 +1,26 @@
1
+ import { CallToolResultSchema, } from "@modelcontextprotocol/sdk/types.js";
2
+ import { bindingOptions, decode, ToolError, } from "./execution.js";
3
+ export * from "./execution.js";
4
+ /** SDK 1.x adapter. Uses request() to preserve raw results before decoding. */
5
+ export function createToolCaller(client, defaults) {
6
+ bindingOptions(defaults);
7
+ return (request, options) => client.request({ method: "tools/call", params: request }, CallToolResultSchema, bindingOptions(options, defaults));
8
+ }
9
+ export function toolFunctions(client, names, mode = "decoded", timeoutMs = 120_000) {
10
+ // A tool name is a dictionary key, including names such as "__proto__".
11
+ const fns = Object.create(null);
12
+ for (const name of names) {
13
+ fns[name] = async (args = {}) => {
14
+ const result = (await client.request({ method: "tools/call", params: { name, arguments: args } }, CallToolResultSchema, {
15
+ timeout: timeoutMs,
16
+ }));
17
+ try {
18
+ return decode(result, mode);
19
+ }
20
+ catch (error) {
21
+ throw new ToolError(name, error instanceof Error ? error.message : String(error));
22
+ }
23
+ };
24
+ }
25
+ return fns;
26
+ }
@@ -0,0 +1,17 @@
1
+ import { type Shape } from "./shape.js";
2
+ export type JsonSchema = {
3
+ [key: string]: unknown;
4
+ };
5
+ export interface SchemaOptions {
6
+ mode: "docs" | "lenient";
7
+ }
8
+ export declare function toJsonSchema(shape: Shape, options?: SchemaOptions): JsonSchema;
9
+ /** Values that repeat often enough to look like a fixed set (status, kind, priority...). */
10
+ export declare function observedValues(shape: Shape): string[] | undefined;
11
+ /**
12
+ * The key whose array items look like the parent itself: every key of the items also appears on
13
+ * the parent, including the key itself (so the nesting continues at least one more level).
14
+ */
15
+ export declare function findRecursiveKey(shape: Shape): string | undefined;
16
+ /** Objects used as dictionaries (keyed by id or date) should be typed as maps, not as hundreds of fields. */
17
+ export declare function looksLikeMap(shape: Shape): boolean;
package/dist/schema.js ADDED
@@ -0,0 +1,299 @@
1
+ // Turns a learned Shape into JSON Schema (2020-12).
2
+ // "docs" mode includes observed hints; "lenient" relaxes presence, nullability and numeric
3
+ // constraints. Both preserve observed types, so future type changes can still fail validation.
4
+ import { DEFAULT_OPTIONS, emptyShape, mergeInto } from "./shape.js";
5
+ /** Minimum string observations before values that repeat are reported as likely enum members. */
6
+ const ENUM_MIN_COUNT = 4;
7
+ const ENUM_MAX_VALUES = 12;
8
+ const UNIX_SECONDS = [946_684_800, 4_102_444_800]; // 2000-01-01 .. 2100-01-01
9
+ const UNIX_MILLIS = [UNIX_SECONDS[0] * 1000, UNIX_SECONDS[1] * 1000];
10
+ export function toJsonSchema(shape, options = { mode: "docs" }) {
11
+ const ctx = { defs: {}, remaining: 10_000, depth: 0, active: new WeakSet() };
12
+ const schema = buildSchema(shape, options, ctx);
13
+ if (options.mode === "lenient")
14
+ return loosen(schema, true);
15
+ return Object.keys(ctx.defs).length ? { ...schema, $defs: ctx.defs } : schema;
16
+ }
17
+ /**
18
+ * Lenient schemas relax common variations: nested values may be null, integers may be
19
+ * fractional, and string formats are not enforced. They do not predict every future type.
20
+ */
21
+ function loosen(schema, root) {
22
+ const out = { ...schema };
23
+ delete out.format;
24
+ if (out.type === "integer")
25
+ out.type = "number";
26
+ if (Array.isArray(out.type))
27
+ out.type = [...new Set(out.type.map((t) => (t === "integer" ? "number" : t)))];
28
+ if (out.properties) {
29
+ out.properties = Object.fromEntries(Object.entries(out.properties).map(([k, v]) => [k, loosen(v, false)]));
30
+ }
31
+ if (out.items)
32
+ out.items = loosen(out.items, false);
33
+ if (out.additionalProperties && typeof out.additionalProperties === "object") {
34
+ out.additionalProperties = loosen(out.additionalProperties, false);
35
+ }
36
+ if (Array.isArray(out.anyOf))
37
+ out.anyOf = out.anyOf.map((v) => loosen(v, true));
38
+ return root ? out : nullable(out);
39
+ }
40
+ function nullable(schema) {
41
+ if (Object.keys(schema).length === 0)
42
+ return schema;
43
+ if (typeof schema.type === "string")
44
+ return schema.type === "null" ? schema : { ...schema, type: [schema.type, "null"] };
45
+ if (Array.isArray(schema.type))
46
+ return schema.type.includes("null") ? schema : { ...schema, type: [...schema.type, "null"] };
47
+ if (Array.isArray(schema.anyOf)) {
48
+ const anyOf = schema.anyOf;
49
+ return anyOf.some((v) => v.type === "null") ? schema : { ...schema, anyOf: [...anyOf, { type: "null" }] };
50
+ }
51
+ return schema;
52
+ }
53
+ function buildSchema(shape, options, ctx) {
54
+ if (ctx.remaining-- <= 0 || ctx.depth >= 64 || ctx.active.has(shape))
55
+ return {};
56
+ ctx.depth++;
57
+ ctx.active.add(shape);
58
+ try {
59
+ return buildSchemaBody(shape, options, ctx);
60
+ }
61
+ finally {
62
+ ctx.depth--;
63
+ ctx.active.delete(shape);
64
+ }
65
+ }
66
+ function buildSchemaBody(shape, options, ctx) {
67
+ if (shape.count === 0)
68
+ return {};
69
+ // Never seen with a value: saying "always null" would mislead the reader and reject real values.
70
+ if (shape.null === shape.count)
71
+ return options.mode === "docs" ? { "x-hint": "only seen as null" } : {};
72
+ const variants = [];
73
+ if (shape.null > 0)
74
+ variants.push({ type: "null" });
75
+ if (shape.boolean > 0)
76
+ variants.push({ type: "boolean" });
77
+ if (shape.number)
78
+ variants.push(numberSchema(shape, options));
79
+ if (shape.string)
80
+ variants.push(stringSchema(shape, options, ctx));
81
+ if (shape.array)
82
+ variants.push(arraySchema(shape, options, ctx));
83
+ if (shape.object)
84
+ variants.push(objectSchema(shape, options, ctx));
85
+ const accounted = shape.null + shape.boolean + (shape.number?.count ?? 0) + (shape.string?.count ?? 0) + (shape.array?.count ?? 0) + (shape.object?.count ?? 0);
86
+ // Depth limits and non-JSON values carry observations without a known type.
87
+ if (accounted < shape.count || variants.length === 0)
88
+ return {};
89
+ if (variants.length === 1)
90
+ return variants[0];
91
+ const simple = variants.every((v) => Object.keys(v).length === 1 && typeof v.type === "string");
92
+ if (simple)
93
+ return { type: variants.map((v) => v.type) };
94
+ return { anyOf: variants };
95
+ }
96
+ function numberSchema(shape, options) {
97
+ const n = shape.number;
98
+ const isInt = n.integers === n.count;
99
+ const schema = { type: isInt ? "integer" : "number" };
100
+ if (options.mode === "lenient")
101
+ return schema;
102
+ if (isInt && n.min >= UNIX_SECONDS[0] && n.max <= UNIX_SECONDS[1])
103
+ schema["x-hint"] = "unix-seconds";
104
+ else if (isInt && n.min >= UNIX_MILLIS[0] && n.max <= UNIX_MILLIS[1])
105
+ schema["x-hint"] = "unix-millis";
106
+ if (n.redacted)
107
+ schema["x-redacted"] = true;
108
+ else if (n.examples.length)
109
+ schema.examples = n.examples;
110
+ return schema;
111
+ }
112
+ function stringSchema(shape, options, ctx) {
113
+ const s = shape.string;
114
+ const schema = { type: "string" };
115
+ // JSON Schema's own way of saying "this string holds a JSON document shaped like X".
116
+ if (s.json && s.jsonCount === s.count) {
117
+ if (options.mode === "lenient")
118
+ return schema;
119
+ return { ...schema, contentMediaType: "application/json", contentSchema: buildSchema(s.json, options, ctx) };
120
+ }
121
+ const format = dominantFormat(s.formats, s.count);
122
+ if (format)
123
+ schema.format = format;
124
+ if (options.mode === "lenient")
125
+ return schema;
126
+ const observed = observedValues(shape);
127
+ if (observed)
128
+ schema["x-observed-values"] = observed;
129
+ else if (s.examples.length && !format)
130
+ schema.examples = s.examples;
131
+ if (s.redacted)
132
+ schema["x-redacted"] = true;
133
+ return schema;
134
+ }
135
+ /** Values that repeat often enough to look like a fixed set (status, kind, priority...). */
136
+ export function observedValues(shape) {
137
+ const s = shape.string;
138
+ if (!s || !s.values || s.count < ENUM_MIN_COUNT)
139
+ return undefined;
140
+ const values = Object.keys(s.values);
141
+ if (values.length === 0 || values.length > ENUM_MAX_VALUES)
142
+ return undefined;
143
+ // Require repetition: unique-per-row strings (names, titles) are not an enum.
144
+ if (values.length > s.count / 2)
145
+ return undefined;
146
+ return values.sort((a, b) => s.values[b] - s.values[a]);
147
+ }
148
+ function dominantFormat(formats, count) {
149
+ for (const [format, n] of Object.entries(formats)) {
150
+ if (n === count)
151
+ return format;
152
+ }
153
+ return undefined;
154
+ }
155
+ function arraySchema(shape, options, ctx) {
156
+ const a = shape.array;
157
+ if (a.redacted)
158
+ return options.mode === "docs" ? { type: "array", items: {}, "x-redacted": true } : { type: "array", items: {} };
159
+ const schema = { type: "array" };
160
+ if (a.truncated) {
161
+ schema.items = {};
162
+ if (options.mode === "docs") {
163
+ schema["x-sampled"] = true;
164
+ schema["x-hint"] = "items sampled; additional item types unknown";
165
+ if (a.items.count > 0)
166
+ schema["x-observed-items"] = buildSchema(a.items, options, ctx);
167
+ }
168
+ }
169
+ else if (a.items.count > 0)
170
+ schema.items = buildSchema(a.items, options, ctx);
171
+ else if (options.mode === "docs")
172
+ schema["x-hint"] = "always empty when observed";
173
+ return schema;
174
+ }
175
+ function objectSchema(shape, options, ctx) {
176
+ const obj = shape.object;
177
+ if (obj.redacted)
178
+ return options.mode === "docs" ? { type: "object", additionalProperties: {}, "x-redacted": true } : { type: "object", additionalProperties: {} };
179
+ const keys = Object.keys(obj.props);
180
+ if (obj.truncated || keys.length > 10_000) {
181
+ return options.mode === "docs" ? { type: "object", additionalProperties: {}, "x-hint": "keys sampled; additional value types unknown" } : { type: "object", additionalProperties: {} };
182
+ }
183
+ if (looksLikeMap(shape)) {
184
+ const merged = emptyShape();
185
+ for (const key of keys)
186
+ mergeInto(merged, obj.props[key], { ...DEFAULT_OPTIONS, examples: "all" });
187
+ const schema = { type: "object", additionalProperties: buildSchema(merged, options, ctx) };
188
+ if (options.mode === "docs")
189
+ schema["x-hint"] = `map keyed by ${describeKeys(keys)}`;
190
+ return schema;
191
+ }
192
+ // Trees (file trees, comment threads, nested categories) become one recursive type instead of
193
+ // a different type per observed depth. Only in docs mode: lenient schemas stay ref-free.
194
+ const recursiveKey = options.mode === "docs" ? findRecursiveKey(shape) : undefined;
195
+ if (recursiveKey !== undefined) {
196
+ const name = uniqueDefName(ctx, "Node");
197
+ const ref = { $ref: `#/$defs/${name}` };
198
+ ctx.defs[name] = {};
199
+ ctx.defs[name] = objectBody(foldTree(shape, recursiveKey), options, ctx, { key: recursiveKey, ref });
200
+ return ref;
201
+ }
202
+ return objectBody(shape, options, ctx);
203
+ }
204
+ function objectBody(shape, options, ctx, recursion) {
205
+ const obj = shape.object;
206
+ const keys = Object.keys(obj.props);
207
+ const properties = Object.create(null);
208
+ const required = [];
209
+ for (const key of keys) {
210
+ const prop = obj.props[key];
211
+ const child = recursion?.key === key ? recursiveProperty(prop, options, ctx, recursion.ref) : buildSchema(prop, options, ctx);
212
+ const presence = prop.count / obj.count;
213
+ if (presence >= 1)
214
+ required.push(key);
215
+ else if (options.mode === "docs")
216
+ child["x-presence"] = Math.round(presence * 100) / 100;
217
+ properties[key] = child;
218
+ }
219
+ const schema = { type: "object", properties };
220
+ if (options.mode === "docs" && required.length)
221
+ schema.required = required;
222
+ return schema;
223
+ }
224
+ /**
225
+ * The key whose array items look like the parent itself: every key of the items also appears on
226
+ * the parent, including the key itself (so the nesting continues at least one more level).
227
+ */
228
+ export function findRecursiveKey(shape) {
229
+ const obj = shape.object;
230
+ if (!obj)
231
+ return undefined;
232
+ for (const [key, prop] of Object.entries(obj.props)) {
233
+ const items = prop.array?.items.object;
234
+ if (!items || prop.object || prop.string)
235
+ continue;
236
+ const itemKeys = Object.keys(items.props);
237
+ if (itemKeys.length >= 2 && Object.hasOwn(items.props, key) && itemKeys.every((k) => Object.hasOwn(obj.props, k)))
238
+ return key;
239
+ }
240
+ return undefined;
241
+ }
242
+ /** Merges every level of a tree into one node shape, so the node's stats cover all depths. */
243
+ function foldTree(shape, key) {
244
+ const node = mergeInto(emptyShape(), shape, { ...DEFAULT_OPTIONS, examples: "all" });
245
+ let level = shape.object.props[key].array.items;
246
+ for (let depth = 0; level.object && depth < 64; depth++) {
247
+ mergeInto(node, level, { ...DEFAULT_OPTIONS, examples: "all" });
248
+ level = level.object.props[key]?.array?.items ?? emptyShape();
249
+ }
250
+ return node;
251
+ }
252
+ /** Preserve scalar/null alternatives on the edge and heterogeneous array items while folding. */
253
+ function recursiveProperty(prop, options, ctx, ref) {
254
+ const items = prop.array.items;
255
+ const restItems = { ...items, object: undefined, count: items.count - (items.object?.count ?? 0) };
256
+ const observedItems = restItems.count > 0
257
+ ? { anyOf: [ref, buildSchema(restItems, options, ctx)] }
258
+ : ref;
259
+ const array = { type: "array", items: prop.array.truncated ? {} : observedItems };
260
+ if (prop.array.truncated && options.mode === "docs") {
261
+ array["x-sampled"] = true;
262
+ array["x-observed-items"] = observedItems;
263
+ }
264
+ const rest = { ...prop, array: undefined, count: prop.count - prop.array.count };
265
+ return rest.count > 0 ? { anyOf: [buildSchema(rest, options, ctx), array] } : array;
266
+ }
267
+ function uniqueDefName(ctx, base) {
268
+ let name = base;
269
+ for (let i = 2; Object.hasOwn(ctx.defs, name); i++)
270
+ name = `${base}${i}`;
271
+ return name;
272
+ }
273
+ const ID_LIKE = /^(\d+|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|\d{4}-\d{2}-\d{2}.*|[0-9a-f]{24,})$/i;
274
+ /** Objects used as dictionaries (keyed by id or date) should be typed as maps, not as hundreds of fields. */
275
+ export function looksLikeMap(shape) {
276
+ const obj = shape.object;
277
+ if (!obj)
278
+ return false;
279
+ if (obj.truncated)
280
+ return true;
281
+ const keys = Object.keys(obj.props);
282
+ if (keys.length >= 3 && keys.every((k) => ID_LIKE.test(k)))
283
+ return true;
284
+ // Many keys that each show up in only a few objects: the keys are data, not field names.
285
+ if (keys.length >= 40) {
286
+ const rare = keys.filter((k) => obj.props[k].count / obj.count < 0.2).length;
287
+ return rare / keys.length > 0.8;
288
+ }
289
+ return false;
290
+ }
291
+ function describeKeys(keys) {
292
+ if (keys.every((k) => /^\d+$/.test(k)))
293
+ return "numeric id";
294
+ if (keys.every((k) => /^\d{4}-\d{2}-\d{2}/.test(k)))
295
+ return "date";
296
+ if (keys.every((k) => /^[0-9a-f]{8}-/i.test(k)))
297
+ return "uuid";
298
+ return "string";
299
+ }
@@ -0,0 +1,50 @@
1
+ import type { SpliceRunOptions } from "./splice.js";
2
+ import type { ResultTool } from "./result-session.js";
3
+ export interface SearchFetchOptions {
4
+ origins: readonly string[];
5
+ pageView?: "page" | "markdown";
6
+ /** Return the first ATX heading of this level in the Markdown view. Defaults to H1. */
7
+ headingLevel?: 1 | 2 | 3 | 4 | 5 | 6;
8
+ name?: string;
9
+ /** Opt in only for a repeatable read. Retry the same URL once when this predicate accepts the failure. */
10
+ retryFetchIf?: (error: unknown) => boolean | PromiseLike<boolean>;
11
+ /** One-based rank, or let the caller choose a rank in the tool input. */
12
+ rank?: number | "input";
13
+ resultsPath?: string;
14
+ urlPath?: string;
15
+ urlArgument?: string;
16
+ }
17
+ export declare class SearchFetchTool implements ResultTool {
18
+ #private;
19
+ private search;
20
+ private fetchPage;
21
+ readonly definition: {
22
+ name: string;
23
+ description: string;
24
+ inputSchema: Record<string, unknown>;
25
+ };
26
+ constructor(search: ResultTool, fetchPage: ResultTool, options: SearchFetchOptions);
27
+ execute(args: Record<string, unknown>, options?: SpliceRunOptions): Promise<{
28
+ status: "no_match";
29
+ rank: number;
30
+ totalResults: number;
31
+ requestedUrl?: undefined;
32
+ page?: undefined;
33
+ } | {
34
+ heading: string | null;
35
+ literal?: string | undefined;
36
+ count?: number | undefined;
37
+ status?: undefined;
38
+ rank?: undefined;
39
+ totalResults?: undefined;
40
+ requestedUrl: string;
41
+ page?: undefined;
42
+ } | {
43
+ status?: undefined;
44
+ rank?: undefined;
45
+ totalResults?: undefined;
46
+ requestedUrl: string;
47
+ page: unknown;
48
+ }>;
49
+ }
50
+ export declare function searchThenFetch(search: ResultTool, fetchPage: ResultTool, options: SearchFetchOptions): SearchFetchTool;