toolsplice 0.0.1 → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/README.md +62 -330
  2. package/dist/abortable.d.ts +6 -0
  3. package/dist/abortable.js +50 -0
  4. package/dist/adaptive-read.d.ts +50 -0
  5. package/dist/adaptive-read.js +780 -0
  6. package/dist/answer-wait.d.ts +7 -0
  7. package/dist/answer-wait.js +45 -0
  8. package/dist/cache-reads.d.ts +18 -0
  9. package/dist/cache-reads.js +89 -0
  10. package/dist/calibration-ledger.d.ts +37 -0
  11. package/dist/calibration-ledger.js +148 -0
  12. package/dist/calibration-marker.d.ts +4 -0
  13. package/dist/calibration-marker.js +77 -0
  14. package/dist/catalog-setup.d.ts +33 -0
  15. package/dist/catalog-setup.js +89 -0
  16. package/dist/catalog.d.ts +10 -0
  17. package/dist/catalog.js +42 -0
  18. package/dist/checkpoint-files.d.ts +15 -0
  19. package/dist/checkpoint-files.js +99 -0
  20. package/dist/cli.js +545 -14
  21. package/dist/coalesce-reads.d.ts +6 -0
  22. package/dist/coalesce-reads.js +33 -0
  23. package/dist/contract-caller.d.ts +2 -1
  24. package/dist/contract-caller.js +35 -16
  25. package/dist/contract-schema.d.ts +3 -1
  26. package/dist/contract-schema.js +34 -4
  27. package/dist/contracts.d.ts +1 -0
  28. package/dist/contracts.js +5 -1
  29. package/dist/core.d.ts +31 -1
  30. package/dist/core.js +27 -0
  31. package/dist/db-final-answer.d.ts +9 -0
  32. package/dist/db-final-answer.js +62 -0
  33. package/dist/define.d.ts +78 -0
  34. package/dist/define.js +14 -0
  35. package/dist/final-answer-stores.d.ts +71 -0
  36. package/dist/final-answer-stores.js +72 -0
  37. package/dist/final-answer.d.ts +32 -0
  38. package/dist/final-answer.js +104 -0
  39. package/dist/impact.d.ts +48 -0
  40. package/dist/impact.js +71 -0
  41. package/dist/index.d.ts +32 -1
  42. package/dist/index.js +28 -0
  43. package/dist/local-tool.d.ts +18 -0
  44. package/dist/local-tool.js +32 -0
  45. package/dist/mcp-apps.d.ts +53 -0
  46. package/dist/mcp-apps.js +32 -0
  47. package/dist/mcp-event-delivery.d.ts +98 -0
  48. package/dist/mcp-event-delivery.js +211 -0
  49. package/dist/mcp-extensions.d.ts +46 -0
  50. package/dist/mcp-extensions.js +200 -0
  51. package/dist/mcp-peer.d.ts +45 -0
  52. package/dist/mcp-peer.js +207 -0
  53. package/dist/mcp-server-card.d.ts +21 -0
  54. package/dist/mcp-server-card.js +54 -0
  55. package/dist/page-checkpoint.d.ts +71 -0
  56. package/dist/page-checkpoint.js +286 -0
  57. package/dist/page-read-gate.d.ts +15 -0
  58. package/dist/page-read-gate.js +48 -0
  59. package/dist/pattern.d.ts +1 -0
  60. package/dist/pattern.js +27 -5
  61. package/dist/probe.js +6 -19
  62. package/dist/read-pages.d.ts +25 -0
  63. package/dist/read-pages.js +85 -0
  64. package/dist/read-policy.d.ts +6 -0
  65. package/dist/read-policy.js +16 -0
  66. package/dist/read-steps.d.ts +12 -0
  67. package/dist/read-steps.js +36 -0
  68. package/dist/result-session.d.ts +109 -0
  69. package/dist/result-session.js +620 -0
  70. package/dist/route-checkpoint.d.ts +3 -0
  71. package/dist/route-checkpoint.js +80 -0
  72. package/dist/route-driver-cli.d.ts +3 -0
  73. package/dist/route-driver-cli.js +43 -0
  74. package/dist/route-evaluation.d.ts +141 -0
  75. package/dist/route-evaluation.js +329 -0
  76. package/dist/row-groups.d.ts +17 -0
  77. package/dist/row-groups.js +79 -0
  78. package/dist/row-query.d.ts +62 -0
  79. package/dist/row-query.js +172 -0
  80. package/dist/rules.d.ts +30 -0
  81. package/dist/rules.js +72 -0
  82. package/dist/run-diagnostics.d.ts +75 -0
  83. package/dist/run-diagnostics.js +212 -0
  84. package/dist/search-fetch.d.ts +50 -0
  85. package/dist/search-fetch.js +264 -0
  86. package/dist/skill-files.d.ts +9 -0
  87. package/dist/skill-files.js +49 -0
  88. package/dist/splice-diagnostics.d.ts +4 -0
  89. package/dist/splice-diagnostics.js +24 -16
  90. package/dist/splice-measure.d.ts +33 -0
  91. package/dist/splice-measure.js +55 -0
  92. package/dist/splice-project.d.ts +12 -6
  93. package/dist/splice-project.js +72 -20
  94. package/dist/splice-recording.d.ts +29 -2
  95. package/dist/splice-recording.js +22 -5
  96. package/dist/splice.d.ts +98 -1
  97. package/dist/splice.js +225 -27
  98. package/dist/sqlite-checkpoint-store.d.ts +5 -0
  99. package/dist/sqlite-checkpoint-store.js +91 -0
  100. package/dist/sqlite-checkpoint-worker.d.ts +1 -0
  101. package/dist/sqlite-checkpoint-worker.js +115 -0
  102. package/dist/test-difference.d.ts +13 -0
  103. package/dist/test-difference.js +42 -0
  104. package/dist/testing.d.ts +122 -0
  105. package/dist/testing.js +261 -0
  106. package/dist/text-pages.d.ts +24 -0
  107. package/dist/text-pages.js +36 -0
  108. package/dist/tool-discovery.d.ts +59 -0
  109. package/dist/tool-discovery.js +136 -0
  110. package/dist/unevaluated.d.ts +7 -0
  111. package/dist/unevaluated.js +156 -0
  112. package/dist/v2.js +25 -8
  113. package/dist/version.d.ts +1 -1
  114. package/dist/version.js +1 -1
  115. package/dist/workflow-json.js +1 -1
  116. package/docs/AGENT-FRAMEWORKS.md +431 -0
  117. package/docs/BENCHMARKS.md +43 -0
  118. package/docs/INTEGRATION-QUICKSTART.md +859 -0
  119. package/docs/LEARNING-AND-STORAGE.md +393 -0
  120. package/docs/MCP.md +204 -0
  121. package/docs/PROJECTS-AND-UPGRADES.md +67 -9
  122. package/docs/PYTHON-REFERENCE.md +348 -0
  123. package/docs/PYTHON.md +120 -0
  124. package/docs/RECORDING-AND-CORRECTIONS.md +30 -1
  125. package/docs/TESTING.md +259 -0
  126. package/examples/mcp-app/build.mjs +11 -0
  127. package/examples/mcp-app/view.mjs +22 -0
  128. package/examples/quickstart.mjs +43 -0
  129. package/examples/route-driver.mjs +67 -0
  130. package/integrations/ai.d.mts +36 -0
  131. package/integrations/ai.mjs +178 -0
  132. package/integrations/call-options.mjs +9 -0
  133. package/integrations/langchain.d.mts +31 -0
  134. package/integrations/langchain.mjs +114 -0
  135. package/integrations/managed.mjs +154 -0
  136. package/integrations/types.d.mts +13 -0
  137. package/package.json +47 -3
@@ -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,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;
@@ -0,0 +1,264 @@
1
+ import { currentDiagnostics, recordReadResult } from "./run-diagnostics.js";
2
+ import { markdownPageFacts } from "./adaptive-read.js";
3
+ import { abortable, withCallDeadline, isReadDeadline } from "./abortable.js";
4
+ import { readSplicePath } from "./splice.js";
5
+ import { copyJson, jsonObject, pointerParts } from "./workflow-json.js";
6
+ function positiveRank(rank) {
7
+ return typeof rank === "number" && Number.isSafeInteger(rank) && rank >= 1;
8
+ }
9
+ function canonicalOrigin(authority) {
10
+ const match = /^(https?):\/\/(\[[a-f0-9:.]+\]|[a-z0-9.-]+)(?::\d{1,5})?$/i.exec(authority);
11
+ if (!match)
12
+ return;
13
+ try {
14
+ const url = new URL(authority);
15
+ // Reject ambiguous legacy IPv4 spellings in a source-provided location.
16
+ if (!match[2].startsWith("[") && url.hostname !== match[2].toLowerCase())
17
+ return;
18
+ return url.origin;
19
+ }
20
+ catch {
21
+ return;
22
+ }
23
+ }
24
+ function trustedOrigins(origins) {
25
+ if (!Array.isArray(origins) || !origins.length)
26
+ throw new TypeError("Specify allowed HTTP(S) origins.");
27
+ return new Set(origins.map((s) => {
28
+ const origin = typeof s === "string" && canonicalOrigin(s.replace(/\/$/, ""));
29
+ if (!origin)
30
+ throw new TypeError("Expected an HTTP(S) origin without credentials or a path.");
31
+ return origin;
32
+ }));
33
+ }
34
+ // Local JSON Pointer references keep pointing into the search schema after nesting.
35
+ // Visit only schema positions so example payloads and const values stay literal.
36
+ function nestSearchSchema(root) {
37
+ function visit(value, top = false) {
38
+ if (!jsonObject(value) || (!top && Object.hasOwn(value, "$id")))
39
+ return;
40
+ if (typeof value.$ref === "string" &&
41
+ (value.$ref === "#" || value.$ref.startsWith("#/")))
42
+ value.$ref = "#/properties/search" + value.$ref.slice(1);
43
+ for (const key of [
44
+ "properties",
45
+ "patternProperties",
46
+ "$defs",
47
+ "definitions",
48
+ "dependentSchemas",
49
+ "dependencies",
50
+ ]) {
51
+ const schemas = value[key];
52
+ if (jsonObject(schemas))
53
+ Object.values(schemas).forEach((s) => visit(s));
54
+ }
55
+ for (const key of [
56
+ "items",
57
+ "prefixItems",
58
+ "allOf",
59
+ "anyOf",
60
+ "oneOf",
61
+ "not",
62
+ "if",
63
+ "then",
64
+ "else",
65
+ "contains",
66
+ "additionalItems",
67
+ "additionalProperties",
68
+ "propertyNames",
69
+ "unevaluatedProperties",
70
+ "unevaluatedItems",
71
+ "contentSchema",
72
+ ]) {
73
+ const sub = value[key];
74
+ if (Array.isArray(sub))
75
+ sub.forEach((s) => visit(s));
76
+ else
77
+ visit(sub);
78
+ }
79
+ }
80
+ const metadata = {};
81
+ for (const k of ["$schema", "$id"])
82
+ if (Object.hasOwn(root, k)) {
83
+ metadata[k] = root[k];
84
+ delete root[k];
85
+ }
86
+ visit(root, true);
87
+ return metadata;
88
+ }
89
+ export class SearchFetchTool {
90
+ search;
91
+ fetchPage;
92
+ definition;
93
+ #origins;
94
+ #rank;
95
+ #flat;
96
+ #extras;
97
+ #markdown;
98
+ #headingLevel;
99
+ #results;
100
+ #url;
101
+ #argument;
102
+ #retryFetchIf;
103
+ constructor(search, fetchPage, options) {
104
+ this.search = search;
105
+ this.fetchPage = fetchPage;
106
+ this.#origins = trustedOrigins(options.origins);
107
+ if (options.retryFetchIf !== undefined &&
108
+ typeof options.retryFetchIf !== "function")
109
+ throw new TypeError("retryFetchIf must be a function.");
110
+ this.#retryFetchIf = options.retryFetchIf;
111
+ this.#rank = options.rank ?? 1;
112
+ if (this.#rank !== "input" && !positiveRank(this.#rank))
113
+ throw new RangeError("Expected a positive result rank.");
114
+ this.#results = options.resultsPath ?? "/results";
115
+ this.#url = options.urlPath ?? "/contentUrl";
116
+ this.#argument = options.urlArgument ?? "url";
117
+ if ([this.#results, this.#url].some((p) => pointerParts(p).length > 32))
118
+ throw new Error("Handoff paths allow at most 32 segments.");
119
+ const input = copyJson(search.definition.inputSchema);
120
+ const dynamic = this.#rank === "input";
121
+ const properties = input.properties ?? {};
122
+ this.#markdown = options.pageView === "markdown";
123
+ if (options.headingLevel !== undefined && (!this.#markdown || !Number.isInteger(options.headingLevel) || options.headingLevel < 1 || options.headingLevel > 6))
124
+ throw new RangeError("headingLevel requires a Markdown view and an integer from 1 to 6.");
125
+ this.#headingLevel = options.headingLevel ?? 1;
126
+ if (options.pageView !== undefined &&
127
+ !["page", "markdown"].includes(options.pageView))
128
+ throw new TypeError("Unknown page view.");
129
+ const extras = {};
130
+ if (dynamic)
131
+ extras.rank = {
132
+ type: "integer",
133
+ minimum: 1,
134
+ description: "One-based result position. Use 1 for first, 2 for second.",
135
+ };
136
+ if (this.#markdown)
137
+ extras.countLiteral = {
138
+ type: "string",
139
+ minLength: 1,
140
+ maxLength: 256,
141
+ description: "To count exact case-sensitive occurrences in the full Markdown page, supply the requested literal.",
142
+ };
143
+ this.#extras = new Set(Object.keys(extras));
144
+ this.#flat =
145
+ input.type === "object" &&
146
+ !JSON.stringify(input).includes('"$ref":') &&
147
+ jsonObject(properties) &&
148
+ Object.keys(extras).every((k) => !Object.hasOwn(properties, k)) &&
149
+ Object.keys(input).every((k) => [
150
+ "type",
151
+ "properties",
152
+ "required",
153
+ "additionalProperties",
154
+ "title",
155
+ "description",
156
+ "$comment",
157
+ "$schema",
158
+ "$defs",
159
+ "definitions",
160
+ ].includes(k));
161
+ const flat = this.#flat && jsonObject(properties);
162
+ const wrapped = flat
163
+ ? { ...input }
164
+ : {
165
+ ...(this.#extras.size ? nestSearchSchema(input) : {}),
166
+ type: "object",
167
+ additionalProperties: false,
168
+ };
169
+ wrapped.properties = {
170
+ ...(flat ? properties : { search: input }),
171
+ ...extras,
172
+ };
173
+ wrapped.required = [
174
+ ...(flat
175
+ ? Array.isArray(input.required)
176
+ ? input.required
177
+ : []
178
+ : ["search"]),
179
+ ...(dynamic ? ["rank"] : []),
180
+ ];
181
+ const result = this.#markdown
182
+ ? `Returns the exact requestedUrl and first Markdown H${this.#headingLevel} heading. Supply countLiteral when the request asks for a literal count. The returned count covers the full page.`
183
+ : "A successful call has already fetched the page. Use the returned page evidence to answer.";
184
+ this.definition = {
185
+ name: options.name ?? "search_then_fetch",
186
+ description: `Search and fetch ${dynamic ? "the selected result (one-based rank)" : "result number " + this.#rank} in one call. Preserve the supplied search arguments exactly. ${result} If the rank is absent it returns no_match.`,
187
+ inputSchema: this.#extras.size ? wrapped : input,
188
+ };
189
+ }
190
+ execute(args, options) {
191
+ const trace = currentDiagnostics();
192
+ const result = withCallDeadline(options, "Search-to-fetch handoff timed out.", (bounded) => this.#run(args, bounded));
193
+ return trace ? result.catch(error => {
194
+ const type = options?.signal?.aborted ? "cancel" : isReadDeadline(error) ? "deadline" : error?.name === "AbortError" ? "cancel" : "handoff-error";
195
+ trace.record({ type });
196
+ throw error;
197
+ }) : result;
198
+ }
199
+ async #run(args, options) {
200
+ options?.signal?.throwIfAborted();
201
+ const dynamic = this.#rank === "input";
202
+ const rank = dynamic ? args.rank : this.#rank;
203
+ const nested = this.#extras.size > 0 && !this.#flat;
204
+ const searchArgs = nested
205
+ ? args.search
206
+ : this.#extras.size
207
+ ? Object.fromEntries(Object.entries(args).filter(([k]) => !this.#extras.has(k)))
208
+ : args;
209
+ const literal = this.#markdown ? args.countLiteral : undefined;
210
+ if (literal !== undefined &&
211
+ (typeof literal !== "string" ||
212
+ !literal.length ||
213
+ Array.from(literal).length > 256))
214
+ throw new TypeError("countLiteral must contain 1 to 256 characters.");
215
+ if (!positiveRank(rank) ||
216
+ !jsonObject(searchArgs) ||
217
+ (nested &&
218
+ Object.keys(args).some((k) => k !== "search" && !this.#extras.has(k))))
219
+ throw new TypeError("Invalid search arguments or result rank.");
220
+ const trace = currentDiagnostics();
221
+ trace?.record({ type: "read", operation: "search" });
222
+ const hits = readSplicePath(recordReadResult(await this.search.execute(copyJson(searchArgs), options)), this.#results).value;
223
+ options?.signal?.throwIfAborted();
224
+ if (!Array.isArray(hits))
225
+ throw new Error("The search result collection must be an array.");
226
+ if (rank > hits.length)
227
+ return { status: "no_match", rank, totalResults: hits.length };
228
+ const url = readSplicePath(hits[rank - 1], this.#url).value;
229
+ const authority = typeof url === "string" &&
230
+ !/[\s\\\x00-\x1f\x7f]/u.test(url) &&
231
+ /^(https?:\/\/[^/?#]+)(?:[/?#]|$)/i.exec(url)?.[1];
232
+ const origin = authority && canonicalOrigin(authority);
233
+ if (!origin || !this.#origins.has(origin))
234
+ throw new Error("The selected result has no permitted fetch URL.");
235
+ options?.signal?.throwIfAborted();
236
+ const fetch = () => {
237
+ trace?.record({ type: "read", operation: "fetch" });
238
+ return this.fetchPage.execute({ [this.#argument]: url }, options);
239
+ };
240
+ let page;
241
+ try {
242
+ page = await fetch();
243
+ }
244
+ catch (error) {
245
+ options?.signal?.throwIfAborted();
246
+ const decide = this.#retryFetchIf;
247
+ if (!decide || (error instanceof Error && error.name === "AbortError"))
248
+ throw error;
249
+ if ((await abortable(() => decide(error), options?.signal)) !== true)
250
+ throw error;
251
+ options?.signal?.throwIfAborted();
252
+ trace?.record({ type: "retry" });
253
+ page = await fetch();
254
+ }
255
+ options?.signal?.throwIfAborted();
256
+ recordReadResult(page);
257
+ return this.#markdown
258
+ ? { requestedUrl: url, ...markdownPageFacts(page, literal, this.#headingLevel) }
259
+ : { requestedUrl: url, page };
260
+ }
261
+ }
262
+ export function searchThenFetch(search, fetchPage, options) {
263
+ return new SearchFetchTool(search, fetchPage, options);
264
+ }
@@ -0,0 +1,9 @@
1
+ /** Identify manifest resources without translating them to host filesystem paths. */
2
+ export declare function skillFile(uri: string, base?: string): {
3
+ path: string[];
4
+ origin: string;
5
+ key: string;
6
+ name: string;
7
+ };
8
+ /** Optional YAML parser is loaded only for an entry file, after verifying its bytes. */
9
+ export declare function defaultSkillFrontmatter(markdown: string): Promise<any>;
@@ -0,0 +1,49 @@
1
+ /** Identify manifest resources without translating them to host filesystem paths. */
2
+ export function skillFile(uri, base) {
3
+ let url;
4
+ try {
5
+ url = new URL(uri, base);
6
+ }
7
+ catch {
8
+ throw new Error("Invalid MCP skill resource URI.");
9
+ }
10
+ const path = url.pathname.split("/").map((segment) => {
11
+ const value = decodeURIComponent(segment);
12
+ if (/[\/\\\x00-\x1f\x7f]/u.test(value))
13
+ throw new Error("Invalid MCP skill resource path.");
14
+ return value;
15
+ });
16
+ if (!url.href.includes("://") || !path.at(-1))
17
+ throw new Error("Expected a skill file URI.");
18
+ const origin = url.protocol +
19
+ "//" +
20
+ (url.username || url.password
21
+ ? url.username + ":" + url.password + "@"
22
+ : "") +
23
+ url.host;
24
+ return {
25
+ path,
26
+ origin,
27
+ key: JSON.stringify([origin, path, url.search]),
28
+ name: path.at(-2) || decodeURIComponent(url.host),
29
+ };
30
+ }
31
+ /** Optional YAML parser is loaded only for an entry file, after verifying its bytes. */
32
+ export async function defaultSkillFrontmatter(markdown) {
33
+ const normalized = markdown.replace(/^\uFEFF/, "").replace(/\r\n/g, "\n");
34
+ const match = /^---[ \t]*\n([\s\S]*?)^---[ \t]*(?:\n|$)/m.exec(normalized);
35
+ if (!match || match.index !== 0)
36
+ throw new Error("Expected YAML frontmatter at the start of SKILL.md.");
37
+ const packageName = "yaml";
38
+ const yaml = await import(packageName).catch(() => {
39
+ throw new Error("Install yaml or pass a Markdown frontmatter parser to skills.open().");
40
+ });
41
+ const document = yaml.parseDocument(match[1], {
42
+ version: "1.2",
43
+ schema: "core",
44
+ uniqueKeys: true,
45
+ });
46
+ if (document.errors.length || document.warnings.length)
47
+ throw new Error("Invalid YAML skill frontmatter.");
48
+ return document.toJS({ maxAliasCount: 64 });
49
+ }
@@ -5,6 +5,7 @@ export interface SpliceFieldOrigin {
5
5
  origin: "source" | "context" | "literal";
6
6
  pointer?: string;
7
7
  selectionPointer?: string;
8
+ matchPointer?: string;
8
9
  parsedJson?: boolean;
9
10
  rowIndex?: number;
10
11
  }
@@ -27,14 +28,17 @@ export interface SpliceExplanation {
27
28
  pointer: string;
28
29
  parsedJson: boolean;
29
30
  forEach: boolean;
31
+ matchPointer?: string;
30
32
  };
31
33
  summary: string;
32
34
  issues: {
33
35
  code: string;
34
36
  path: string;
35
37
  fields: SpliceFieldOrigin[];
38
+ ruleId?: string;
36
39
  }[];
37
40
  sideEffects: "no-destination-calls" | "destination-effects-may-have-occurred";
38
41
  }
42
+ export declare function describeBinding(spec: SpliceSpec, bindingIndex: number, rowIndex?: number): SpliceFieldOrigin;
39
43
  /** Path-only explanation. Never traverses causes or includes inputs, results or literal values. */
40
44
  export declare function explainSpliceError(plan: SpliceSpec, error: SpliceError): SpliceExplanation;
@@ -4,6 +4,25 @@ const overlaps = (a, b) => {
4
4
  const x = pointerParts(a), y = pointerParts(b);
5
5
  return x.slice(0, Math.min(x.length, y.length)).every((p, i) => p === y[i]);
6
6
  };
7
+ export function describeBinding(spec, bindingIndex, rowIndex) {
8
+ const binding = spec.bindings[bindingIndex];
9
+ return {
10
+ bindingIndex,
11
+ targetPointer: binding.to,
12
+ ...("from" in binding
13
+ ? {
14
+ origin: "source",
15
+ pointer: binding.from,
16
+ selectionPointer: spec.source.path ?? "",
17
+ ...(spec.source.matchOne ? { matchPointer: spec.source.matchOne.path } : {}),
18
+ parsedJson: spec.source.parseJson ?? false,
19
+ }
20
+ : "fromContext" in binding
21
+ ? { origin: "context", pointer: binding.fromContext }
22
+ : { origin: "literal" }),
23
+ ...(rowIndex === undefined ? {} : { rowIndex }),
24
+ };
25
+ }
7
26
  /** Path-only explanation. Never traverses causes or includes inputs, results or literal values. */
8
27
  export function explainSpliceError(plan, error) {
9
28
  const spec = parseSpliceSpec(plan);
@@ -40,23 +59,11 @@ export function explainSpliceError(plan, error) {
40
59
  overlaps(issue.path.slice(10), binding.to))));
41
60
  if (!relevant)
42
61
  continue;
43
- fields.push({
44
- bindingIndex,
45
- targetPointer: binding.to,
46
- ...("from" in binding
47
- ? {
48
- origin: "source",
49
- pointer: binding.from,
50
- selectionPointer: spec.source.path ?? "",
51
- parsedJson: spec.source.parseJson ?? false,
52
- }
53
- : "fromContext" in binding
54
- ? { origin: "context", pointer: binding.fromContext }
55
- : { origin: "literal" }),
56
- ...(rowIndex === undefined ? {} : { rowIndex }),
57
- });
62
+ fields.push(describeBinding(spec, bindingIndex, rowIndex));
58
63
  }
59
- return { code: issue.code, path: issue.path, fields };
64
+ const ruleIndex = /^\/rules\/(\d+)$/.exec(path);
65
+ const rule = ruleIndex ? spec.rules?.[Number(ruleIndex[1])] : undefined;
66
+ return { code: issue.code, path: issue.path, fields, ...(rule ? { ruleId: rule.id } : {}) };
60
67
  });
61
68
  return {
62
69
  stage: error.stage,
@@ -70,6 +77,7 @@ export function explainSpliceError(plan, error) {
70
77
  pointer: spec.source.path ?? "",
71
78
  parsedJson: spec.source.parseJson ?? false,
72
79
  forEach: spec.forEach ?? false,
80
+ ...(spec.source.matchOne ? { matchPointer: spec.source.matchOne.path } : {}),
73
81
  },
74
82
  summary: `${error.stage} validation or execution failed; ${error.completedTargets} destination result(s) were acknowledged and collected.`,
75
83
  issues,