webfox 4.11.0 → 4.13.0

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 (95) hide show
  1. package/README.md +5 -2
  2. package/dist/adapter-2HWVV4H7.js +144 -0
  3. package/dist/{adapter-QQZFHUOP.js → adapter-2V73476L.js} +69 -131
  4. package/dist/{adapter-SZMVKAMC.js → adapter-3V4OZDZZ.js} +10 -14
  5. package/dist/adapter-64462GL3.js +247 -0
  6. package/dist/{adapter-WXEVTCM3.js → adapter-BCZ4UE7S.js} +38 -81
  7. package/dist/{adapter-YVZ4YBK5.js → adapter-BHDA6JOK.js} +40 -56
  8. package/dist/adapter-EQ3LZTZ4.js +152 -0
  9. package/dist/adapter-EQSFB26L.js +58 -0
  10. package/dist/{adapter-ODDFBGJG.js → adapter-EXDS6465.js} +36 -57
  11. package/dist/adapter-IWGMWJ5A.js +121 -0
  12. package/dist/{adapter-XSQX3GAI.js → adapter-JQNYUBYZ.js} +33 -23
  13. package/dist/{adapter-VXT4C6RZ.js → adapter-OTMS6OEU.js} +81 -102
  14. package/dist/{adapter-MZ7USB6Q.js → adapter-PW4UL2DR.js} +12 -32
  15. package/dist/adapter-RBSOVQCV.js +84 -0
  16. package/dist/{adapter-GFXYSHKP.js → adapter-RJ334ZU5.js} +28 -76
  17. package/dist/{adapter-XU2APKPC.js → adapter-T6UEERC7.js} +19 -24
  18. package/dist/{adapter-BZO5UEI6.js → adapter-VVWNAGWI.js} +118 -142
  19. package/dist/{adapter-GJOUFE2U.js → adapter-XMEXVEMQ.js} +7 -10
  20. package/dist/adapter-ZLS55DG2.js +341 -0
  21. package/dist/{chunk-NENL6L6N.js → chunk-46OIVYHW.js} +1 -0
  22. package/dist/{chunk-WCTOYZVB.js → chunk-6UC3ZBNK.js} +15 -5
  23. package/dist/{chunk-YILOS4E7.js → chunk-7NTO6AQX.js} +110 -72
  24. package/dist/{chunk-PVNWACMT.js → chunk-EBKQHHCO.js} +199 -20
  25. package/dist/chunk-HZVTFUBC.js +139 -0
  26. package/dist/{chunk-LDVDVA4Z.js → chunk-I4HLGP7F.js} +3 -7
  27. package/dist/chunk-U4I3X7IN.js +267 -0
  28. package/dist/chunk-V4SQCDI3.js +336 -0
  29. package/dist/chunk-VMIDLDYP.js +111 -0
  30. package/dist/cli.js +9 -9
  31. package/dist/config.schema.json +222 -1
  32. package/dist/document-schema.d.ts +4 -4
  33. package/dist/domain.d.ts +1 -1
  34. package/dist/durable.js +73 -65
  35. package/dist/index.js +8 -7
  36. package/dist/pi-render.d.ts +3 -2
  37. package/dist/pi-shared.d.ts +39 -0
  38. package/dist/pi.js +87 -191
  39. package/dist/providers/brave/adapter.d.ts +4 -5
  40. package/dist/providers/cloudflare/adapter.d.ts +3 -2
  41. package/dist/providers/contract.d.ts +20 -19
  42. package/dist/providers/custom/adapter.d.ts +2 -2
  43. package/dist/providers/exa/adapter.d.ts +6 -6
  44. package/dist/providers/firecrawl/adapter.d.ts +5 -5
  45. package/dist/providers/gemini/adapter.d.ts +5 -10
  46. package/dist/providers/keenable/adapter.d.ts +2 -3
  47. package/dist/providers/linkup/adapter.d.ts +5 -5
  48. package/dist/providers/ollama/adapter.d.ts +4 -4
  49. package/dist/providers/openai/adapter.d.ts +4 -4
  50. package/dist/providers/openai/types.d.ts +2 -4
  51. package/dist/providers/parallel/adapter.d.ts +4 -4
  52. package/dist/providers/perplexity/adapter.d.ts +4 -5
  53. package/dist/providers/registry.d.ts +1 -0
  54. package/dist/providers/serpbase/types.d.ts +2 -4
  55. package/dist/providers/serper/adapter.d.ts +2 -2
  56. package/dist/providers/serper/types.d.ts +2 -4
  57. package/dist/providers/shared.d.ts +50 -0
  58. package/dist/providers/sofya/adapter.d.ts +6 -6
  59. package/dist/providers/tapline/adapter.d.ts +4 -0
  60. package/dist/providers/tapline/definition.d.ts +1 -0
  61. package/dist/providers/tavily/adapter.d.ts +4 -4
  62. package/dist/providers/valyu/adapter.d.ts +6 -6
  63. package/dist/providers/youcom/adapter.d.ts +2 -3
  64. package/dist/runtime/duration.d.ts +2 -0
  65. package/dist/runtime/execute.d.ts +3 -1
  66. package/dist/runtime/lifecycle.d.ts +0 -1
  67. package/dist/runtime/outward.d.ts +6 -1
  68. package/dist/runtime/polling.d.ts +2 -3
  69. package/docs/provider.md +29 -0
  70. package/package.json +14 -20
  71. package/dist/adapter-44ZBIK47.js +0 -121
  72. package/dist/adapter-57MELLYI.js +0 -160
  73. package/dist/adapter-D4EXZEDL.js +0 -213
  74. package/dist/adapter-DJCTEEOA.js +0 -159
  75. package/dist/adapter-DLNMW34W.js +0 -214
  76. package/dist/adapter-RR55EZAW.js +0 -73
  77. package/dist/chunk-FSTCLBSF.js +0 -76
  78. package/dist/chunk-I2UIACY3.js +0 -12
  79. package/dist/chunk-KMUCUJVN.js +0 -251
  80. package/dist/chunk-TYJ6RHKB.js +0 -31
  81. package/dist/chunk-VVOQKYOP.js +0 -112
  82. package/dist/contents.d.ts +0 -24
  83. package/dist/providers/brave/types.d.ts +0 -4
  84. package/dist/providers/exa/types.d.ts +0 -4
  85. package/dist/providers/firecrawl/types.d.ts +0 -4
  86. package/dist/providers/gemini/types.d.ts +0 -3
  87. package/dist/providers/keenable/types.d.ts +0 -4
  88. package/dist/providers/linkup/types.d.ts +0 -4
  89. package/dist/providers/ollama/types.d.ts +0 -4
  90. package/dist/providers/parallel/types.d.ts +0 -4
  91. package/dist/providers/perplexity/types.d.ts +0 -4
  92. package/dist/providers/sofya/types.d.ts +0 -4
  93. package/dist/providers/tavily/types.d.ts +0 -4
  94. package/dist/providers/valyu/types.d.ts +0 -4
  95. package/dist/providers/youcom/types.d.ts +0 -4
@@ -0,0 +1,267 @@
1
+ import {
2
+ WebfoxError,
3
+ httpError
4
+ } from "./chunk-U4BLULLV.js";
5
+
6
+ // src/providers/shared.ts
7
+ function asRecord(value) {
8
+ return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
9
+ }
10
+ function readString(value) {
11
+ return typeof value === "string" ? value : void 0;
12
+ }
13
+ function readNonEmptyString(value) {
14
+ return typeof value === "string" && value.trim().length > 0 ? value : void 0;
15
+ }
16
+ function readInteger(value) {
17
+ return typeof value === "number" && Number.isInteger(value) ? value : void 0;
18
+ }
19
+ function readPositiveInteger(value) {
20
+ return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : void 0;
21
+ }
22
+ function readStringArray(value) {
23
+ if (!Array.isArray(value)) return void 0;
24
+ const strings = value.filter(
25
+ (item) => typeof item === "string" && item.trim() !== ""
26
+ );
27
+ return strings.length > 0 ? strings : void 0;
28
+ }
29
+ function readStringUnion(value, values) {
30
+ return typeof value === "string" && values.includes(value) ? value : void 0;
31
+ }
32
+ function requireApiKey(config, key = "api", label) {
33
+ const value = config.credentials?.[key];
34
+ if (!value) {
35
+ throw new Error(
36
+ label ? `${label} is missing an API key` : "is missing an API key"
37
+ );
38
+ }
39
+ return value;
40
+ }
41
+ function omittedContentsError() {
42
+ return new WebfoxError(
43
+ "PROVIDER_FAILURE",
44
+ "The provider omitted a result for this URL."
45
+ );
46
+ }
47
+ function ambiguousContentsError() {
48
+ return new WebfoxError(
49
+ "PROVIDER_FAILURE",
50
+ "The provider returned ambiguous results for this URL."
51
+ );
52
+ }
53
+ function pickSingleUrlOutcome(url, results, errors = []) {
54
+ const exactResult = results.find((entry) => entry.url === url);
55
+ if (exactResult) return { kind: "result", value: exactResult };
56
+ const exactError = errors.find((entry) => entry.url === url);
57
+ if (exactError) return { kind: "error", value: exactError };
58
+ if (results.length === 1 && errors.length === 0)
59
+ return { kind: "result", value: results[0] };
60
+ if (errors.length === 1 && results.length === 0)
61
+ return { kind: "error", value: errors[0] };
62
+ if (results.length === 0 && errors.length === 0) return { kind: "omitted" };
63
+ return { kind: "ambiguous" };
64
+ }
65
+ function trimSnippet(input, maxLength = 300) {
66
+ const text = (input ?? "").replace(/\s+/g, " ").trim();
67
+ return text.length <= maxLength ? text : `${text.slice(0, maxLength - 1)}\u2026`;
68
+ }
69
+ function normalizeContentText(input) {
70
+ return (input ?? "").replace(/\r/g, "").trim().split("\n").map((line) => line.replace(/[ \t]+$/g, "")).join("\n").replace(/\n{3,}/g, "\n\n");
71
+ }
72
+ function asJsonObject(value) {
73
+ return value ? { ...value } : {};
74
+ }
75
+ function formatJson(value) {
76
+ return JSON.stringify(value, null, 2);
77
+ }
78
+ function joinUrl(baseUrl, path) {
79
+ return `${baseUrl.replace(/\/+$/g, "")}/${path.replace(/^\/+/g, "")}`;
80
+ }
81
+ async function readResponseBody(response) {
82
+ const text = await response.text();
83
+ if (!text) return void 0;
84
+ try {
85
+ return JSON.parse(text);
86
+ } catch {
87
+ return text;
88
+ }
89
+ }
90
+ function expectJsonBody(payload, response) {
91
+ if (payload === void 0) {
92
+ throw new WebfoxError(
93
+ "PROVIDER_FAILURE",
94
+ `Expected a JSON response but received an empty body (status ${response.status}).`
95
+ );
96
+ }
97
+ if (typeof payload === "string") {
98
+ const snippet = payload.trim().replace(/\s+/g, " ").slice(0, 200);
99
+ throw new WebfoxError(
100
+ "PROVIDER_FAILURE",
101
+ `Expected a JSON response but received a non-JSON body (status ${response.status}): ${snippet}`
102
+ );
103
+ }
104
+ return payload;
105
+ }
106
+ function mergeHeaders(...layers) {
107
+ const keys = /* @__PURE__ */ new Map();
108
+ const values = /* @__PURE__ */ new Map();
109
+ for (const layer of layers) {
110
+ if (!layer) continue;
111
+ for (const [name, value] of Object.entries(layer)) {
112
+ const lower = name.toLowerCase();
113
+ keys.set(lower, name);
114
+ values.set(lower, value);
115
+ }
116
+ }
117
+ const merged = {};
118
+ for (const [lower, name] of keys) {
119
+ merged[name] = values.get(lower);
120
+ }
121
+ return merged;
122
+ }
123
+ async function readSseJson(response, onEvent) {
124
+ const reader = response.body?.getReader();
125
+ let eventName;
126
+ let dataLines = [];
127
+ let doneStream = false;
128
+ const dispatch = () => {
129
+ if (dataLines.length === 0) {
130
+ eventName = void 0;
131
+ return;
132
+ }
133
+ const raw = dataLines.join("\n").trim();
134
+ const currentEvent = eventName;
135
+ eventName = void 0;
136
+ dataLines = [];
137
+ if (!raw) return;
138
+ if (raw === "[DONE]") {
139
+ doneStream = true;
140
+ return;
141
+ }
142
+ let parsed;
143
+ try {
144
+ parsed = JSON.parse(raw);
145
+ } catch {
146
+ const snippet = raw.replace(/\s+/g, " ").slice(0, 200);
147
+ throw new WebfoxError(
148
+ "PROVIDER_FAILURE",
149
+ `Expected JSON in SSE event data but received: ${snippet}`
150
+ );
151
+ }
152
+ onEvent({ ...currentEvent ? { event: currentEvent } : {}, data: parsed });
153
+ };
154
+ const handleLine = (rawLine) => {
155
+ const line = rawLine.replace(/\r$/, "");
156
+ if (line === "") {
157
+ dispatch();
158
+ return;
159
+ }
160
+ if (line.startsWith(":")) return;
161
+ const colon = line.indexOf(":");
162
+ const field = colon === -1 ? line : line.slice(0, colon);
163
+ let value = colon === -1 ? "" : line.slice(colon + 1);
164
+ if (value.startsWith(" ")) value = value.slice(1);
165
+ if (field === "event") {
166
+ eventName = value || void 0;
167
+ } else if (field === "data") {
168
+ dataLines.push(value);
169
+ }
170
+ };
171
+ if (!reader) {
172
+ for (const line of (await response.text()).split("\n")) {
173
+ handleLine(line);
174
+ if (doneStream) return;
175
+ }
176
+ dispatch();
177
+ return;
178
+ }
179
+ const decoder = new TextDecoder();
180
+ let buffer = "";
181
+ try {
182
+ while (!doneStream) {
183
+ const { done, value } = await reader.read();
184
+ if (done) break;
185
+ buffer += decoder.decode(value, { stream: true });
186
+ const lines = buffer.split("\n");
187
+ buffer = lines.pop() ?? "";
188
+ for (const line of lines) {
189
+ handleLine(line);
190
+ if (doneStream) break;
191
+ }
192
+ }
193
+ if (!doneStream) {
194
+ buffer += decoder.decode();
195
+ if (buffer) {
196
+ for (const line of buffer.split("\n")) {
197
+ handleLine(line);
198
+ if (doneStream) break;
199
+ }
200
+ }
201
+ if (!doneStream) dispatch();
202
+ }
203
+ } finally {
204
+ if (doneStream) {
205
+ await reader.cancel().catch(() => {
206
+ });
207
+ }
208
+ }
209
+ }
210
+ function describeHttpError(label, payload, response) {
211
+ const record = asRecord(payload);
212
+ const errorObj = asRecord(record?.error);
213
+ const detailObj = asRecord(record?.detail);
214
+ const errors = Array.isArray(record?.errors) ? record.errors : [];
215
+ const firstArrayError = errors.map((item) => {
216
+ const entry = asRecord(item);
217
+ return readNonEmptyString(entry?.message) ?? readNonEmptyString(entry?.error) ?? readNonEmptyString(item);
218
+ }).filter((item) => Boolean(item)).join("; ");
219
+ const detail = readNonEmptyString(errorObj?.message) ?? readNonEmptyString(detailObj?.error) ?? readNonEmptyString(detailObj?.message) ?? readNonEmptyString(record?.error) ?? readNonEmptyString(record?.message) ?? readNonEmptyString(record?.detail) ?? (firstArrayError || void 0) ?? (typeof payload === "string" ? readNonEmptyString(payload) : void 0);
220
+ const trimmed = detail?.trim().slice(0, 500);
221
+ return trimmed ? `${label} request failed (HTTP ${response.status}): ${trimmed}` : `${label} request failed (HTTP ${response.status}).`;
222
+ }
223
+ async function requestJson(url, init, describeError) {
224
+ const method = init.method ?? (init.body === void 0 ? "GET" : "POST");
225
+ const response = await fetch(url, {
226
+ method,
227
+ headers: mergeHeaders(
228
+ {
229
+ Accept: "application/json",
230
+ ...init.body === void 0 ? {} : { "Content-Type": "application/json" }
231
+ },
232
+ init.headers
233
+ ),
234
+ ...init.body === void 0 ? {} : { body: JSON.stringify(init.body) },
235
+ signal: init.signal
236
+ });
237
+ const payload = await readResponseBody(response);
238
+ if (!response.ok) {
239
+ throw httpError(response, describeError(payload, response));
240
+ }
241
+ return expectJsonBody(payload, response);
242
+ }
243
+
244
+ export {
245
+ asRecord,
246
+ readString,
247
+ readNonEmptyString,
248
+ readInteger,
249
+ readPositiveInteger,
250
+ readStringArray,
251
+ readStringUnion,
252
+ requireApiKey,
253
+ omittedContentsError,
254
+ ambiguousContentsError,
255
+ pickSingleUrlOutcome,
256
+ trimSnippet,
257
+ normalizeContentText,
258
+ asJsonObject,
259
+ formatJson,
260
+ joinUrl,
261
+ readResponseBody,
262
+ expectJsonBody,
263
+ mergeHeaders,
264
+ readSseJson,
265
+ describeHttpError,
266
+ requestJson
267
+ };
@@ -0,0 +1,336 @@
1
+ import {
2
+ renderTextDocument
3
+ } from "./chunk-6RQGO727.js";
4
+ import {
5
+ createWebfox
6
+ } from "./chunk-7NTO6AQX.js";
7
+ import {
8
+ PROVIDER_IDS,
9
+ WEBFOX_ERROR_CODES
10
+ } from "./chunk-46OIVYHW.js";
11
+
12
+ // src/document-schema.ts
13
+ import { Type } from "typebox";
14
+ var closed = { additionalProperties: false };
15
+ var metadata = Type.Record(Type.String(), Type.Unknown(), {
16
+ description: "Provider-specific fields."
17
+ });
18
+ var searchResult = Type.Object(
19
+ {
20
+ title: Type.Optional(Type.String({ minLength: 1 })),
21
+ url: Type.String(),
22
+ snippet: Type.String(),
23
+ score: Type.Optional(Type.Number()),
24
+ metadata: Type.Optional(metadata)
25
+ },
26
+ closed
27
+ );
28
+ var contentsAnswer = Type.Object(
29
+ {
30
+ url: Type.String({ description: "Final URL after redirects." }),
31
+ content: Type.Optional(Type.String()),
32
+ summary: Type.Optional(Type.Unknown()),
33
+ metadata: Type.Optional(metadata)
34
+ },
35
+ closed
36
+ );
37
+ var textAnswer = Type.Object(
38
+ {
39
+ text: Type.String(),
40
+ sources: Type.Optional(
41
+ Type.Array(
42
+ Type.Union([
43
+ Type.Object(
44
+ {
45
+ url: Type.String({ minLength: 1 }),
46
+ title: Type.Optional(Type.String({ minLength: 1 }))
47
+ },
48
+ closed
49
+ ),
50
+ Type.Object({ title: Type.String({ minLength: 1 }) }, closed)
51
+ ])
52
+ )
53
+ ),
54
+ itemCount: Type.Optional(Type.Integer()),
55
+ metadata: Type.Optional(metadata)
56
+ },
57
+ closed
58
+ );
59
+ var serializedError = Type.Object(
60
+ {
61
+ code: Type.Enum(WEBFOX_ERROR_CODES),
62
+ message: Type.String(),
63
+ retryable: Type.Optional(Type.Boolean())
64
+ },
65
+ closed
66
+ );
67
+ function inputResult(value) {
68
+ const input = Type.String({
69
+ description: "The query, URL, or brief this entry answers."
70
+ });
71
+ return Type.Union([
72
+ Type.Object({ input, ok: Type.Literal(true), value }, closed),
73
+ Type.Object(
74
+ { input, ok: Type.Literal(false), error: serializedError },
75
+ closed
76
+ )
77
+ ]);
78
+ }
79
+ function document(capability, value) {
80
+ return Type.Object(
81
+ {
82
+ schemaVersion: Type.Literal(1),
83
+ capability: Type.Literal(capability),
84
+ provider: Type.Enum(PROVIDER_IDS),
85
+ status: Type.Enum(["ok", "partial"], {
86
+ description: "`partial` when at least one input failed."
87
+ }),
88
+ results: Type.Array(inputResult(value), {
89
+ description: "One entry per input, in input order."
90
+ })
91
+ },
92
+ closed
93
+ );
94
+ }
95
+ var DOCUMENT_SCHEMAS = {
96
+ search: document(
97
+ "search",
98
+ Type.Object({ results: Type.Array(searchResult) }, closed)
99
+ ),
100
+ contents: document("contents", contentsAnswer),
101
+ answer: document("answer", textAnswer),
102
+ research: document("research", textAnswer)
103
+ };
104
+
105
+ // src/pi-shared.ts
106
+ var WEB_NAMESPACE = {
107
+ name: "web",
108
+ description: "Search, extract pages, answer, and research the web."
109
+ };
110
+ var DEFAULT_TOOL_MAX_LINES = 2e3;
111
+ var DEFAULT_TOOL_MAX_BYTES = 50 * 1024;
112
+ function createClientCache(options = {}) {
113
+ const clients = /* @__PURE__ */ new Map();
114
+ return (cwd) => {
115
+ if (options.client) return options.client;
116
+ let client = clients.get(cwd);
117
+ if (!client) {
118
+ client = createWebfox({ ...options, cwd });
119
+ clients.set(cwd, client);
120
+ }
121
+ return client;
122
+ };
123
+ }
124
+ async function executeCapability(client, capability, provider, params, signal, onProgress) {
125
+ const request = {
126
+ provider,
127
+ signal,
128
+ options: params.options,
129
+ onProgress
130
+ };
131
+ switch (capability) {
132
+ case "search":
133
+ return await client.search({
134
+ ...request,
135
+ queries: params.queries,
136
+ maxResults: params.maxResults
137
+ });
138
+ case "contents":
139
+ return await client.contents({
140
+ ...request,
141
+ urls: params.urls
142
+ });
143
+ case "answer":
144
+ return await client.answer({
145
+ ...request,
146
+ queries: params.queries
147
+ });
148
+ case "research":
149
+ return await client.research({
150
+ ...request,
151
+ input: params.input
152
+ });
153
+ }
154
+ }
155
+ function truncateHeadOutput(content, {
156
+ maxLines = DEFAULT_TOOL_MAX_LINES,
157
+ maxBytes = DEFAULT_TOOL_MAX_BYTES
158
+ } = {}) {
159
+ const totalBytes = Buffer.byteLength(content, "utf-8");
160
+ const lines = splitLinesForCounting(content);
161
+ if (lines.length <= maxLines && totalBytes <= maxBytes) {
162
+ return { content, truncated: false };
163
+ }
164
+ if (lines.length > 0 && Buffer.byteLength(lines[0], "utf-8") > maxBytes) {
165
+ return { content: "", truncated: true };
166
+ }
167
+ const kept = [];
168
+ let bytes = 0;
169
+ for (let i = 0; i < lines.length && i < maxLines; i++) {
170
+ const line = lines[i];
171
+ const lineBytes = Buffer.byteLength(line, "utf-8") + (i > 0 ? 1 : 0);
172
+ if (bytes + lineBytes > maxBytes) break;
173
+ kept.push(line);
174
+ bytes += lineBytes;
175
+ }
176
+ return { content: kept.join("\n"), truncated: true };
177
+ }
178
+ function splitLinesForCounting(content) {
179
+ if (content.length === 0) return [];
180
+ const lines = content.split("\n");
181
+ if (content.endsWith("\n")) lines.pop();
182
+ return lines;
183
+ }
184
+ function sanitizeFooterValue(value) {
185
+ return /[\x00-\x1f\x7f]/.test(value) ? JSON.stringify(value).slice(1, -1) : value;
186
+ }
187
+ async function formatToolOutput(result, writeSpill) {
188
+ const json = JSON.stringify(result);
189
+ const rendered = renderTextDocument(result);
190
+ const initial = truncateHeadOutput(rendered);
191
+ if (!initial.truncated) {
192
+ return { body: initial.content, json };
193
+ }
194
+ const spilled = await writeSpill(json);
195
+ const fullOutputPath = "path" in spilled ? spilled.path : void 0;
196
+ let footer = "path" in spilled ? `
197
+
198
+ Full results: ${sanitizeFooterValue(spilled.path)}` : `
199
+
200
+ Full results could not be saved: ${sanitizeFooterValue(spilled.error)}`;
201
+ if (Buffer.byteLength(footer, "utf-8") > DEFAULT_TOOL_MAX_BYTES) {
202
+ footer = "path" in spilled ? "\n\nFull results saved (path omitted: exceeds output budget)." : "\n\nFull results could not be saved.";
203
+ }
204
+ const footerBytes = Buffer.byteLength(footer, "utf-8");
205
+ const footerLines = footer.split("\n").length - 1;
206
+ const maxBodyLines = DEFAULT_TOOL_MAX_LINES - footerLines;
207
+ const maxBodyBytes = DEFAULT_TOOL_MAX_BYTES - footerBytes;
208
+ const fitted = maxBodyLines > 0 && maxBodyBytes > 0 ? truncateHeadOutput(rendered, {
209
+ maxLines: maxBodyLines,
210
+ maxBytes: maxBodyBytes
211
+ }) : { content: "" };
212
+ const body = fitted.content ? `${fitted.content}${footer}` : footer.trimStart();
213
+ return {
214
+ body,
215
+ json,
216
+ ...fullOutputPath ? { fullOutputPath } : {}
217
+ };
218
+ }
219
+
220
+ // src/pi-validation.ts
221
+ import { stripVTControlCharacters } from "node:util";
222
+ import { Check, Errors } from "typebox/value";
223
+ function isSchema(value) {
224
+ return !!value && typeof value === "object" && !Array.isArray(value);
225
+ }
226
+ function alternatives(schema) {
227
+ return ["anyOf", "oneOf", "allOf"].flatMap(
228
+ (key) => Array.isArray(schema[key]) ? schema[key].filter(isSchema) : []
229
+ );
230
+ }
231
+ function acceptsPath(schema, path) {
232
+ if (schema === true) return true;
233
+ if (!isSchema(schema)) return false;
234
+ if (!path.length) return true;
235
+ if (alternatives(schema).some((branch) => acceptsPath(branch, path)))
236
+ return true;
237
+ const [key, ...rest] = path;
238
+ if (schema.type === "array") return acceptsPath(schema.items, rest);
239
+ if (schema.properties && Object.hasOwn(schema.properties, key))
240
+ return acceptsPath(schema.properties[key], rest);
241
+ if (isSchema(schema.patternProperties)) {
242
+ for (const [pattern, child] of Object.entries(schema.patternProperties))
243
+ if (new RegExp(pattern).test(key) && acceptsPath(child, rest))
244
+ return true;
245
+ }
246
+ if (schema.additionalProperties === false) return false;
247
+ if (schema.type && schema.type !== "object") return false;
248
+ if (alternatives(schema).length && !schema.properties && schema.additionalProperties === void 0)
249
+ return false;
250
+ return schema.additionalProperties === void 0 || acceptsPath(schema.additionalProperties, rest);
251
+ }
252
+ function displayPath(path) {
253
+ return path.map((part, index) => {
254
+ const safe = stripVTControlCharacters(part);
255
+ if (/^[a-zA-Z_][\w-]*$/.test(safe)) return `${index ? "." : ""}${safe}`;
256
+ if (/^\d+$/.test(safe)) return `[${safe}]`;
257
+ return `[${JSON.stringify(safe)}]`;
258
+ }).join("");
259
+ }
260
+ function locations(schema, name, path = []) {
261
+ if (!isSchema(schema)) return [];
262
+ const found = alternatives(schema).flatMap(
263
+ (branch) => locations(branch, name, path)
264
+ );
265
+ if (isSchema(schema.properties)) {
266
+ for (const [key, child] of Object.entries(schema.properties)) {
267
+ const next = [...path, key];
268
+ if (key === name) found.push(next);
269
+ found.push(...locations(child, name, next));
270
+ }
271
+ }
272
+ return found;
273
+ }
274
+ function prepareToolArguments(schema, args) {
275
+ if (Check(schema, args)) return args;
276
+ const messages = /* @__PURE__ */ new Set();
277
+ for (const error of Errors(schema, args)) {
278
+ if (error.keyword !== "additionalProperties") continue;
279
+ const names = error.params.additionalProperties;
280
+ if (!Array.isArray(names)) continue;
281
+ const parent = error.instancePath.split("/").slice(1).map((part) => part.replaceAll("~1", "/").replaceAll("~0", "~"));
282
+ for (const name of names) {
283
+ if (typeof name !== "string") continue;
284
+ const path = [...parent, name];
285
+ if (acceptsPath(schema, path)) continue;
286
+ const targets = [...new Set(locations(schema, name).map(displayPath))];
287
+ const suggestion = targets.length === 1 ? ` Use ${targets[0]} instead.` : " Check the tool's parameter schema.";
288
+ messages.add(`Invalid parameter: ${displayPath(path)}.${suggestion}`);
289
+ if (messages.size === 3) break;
290
+ }
291
+ if (messages.size === 3) break;
292
+ }
293
+ if (messages.size) throw new Error([...messages].join("\n"));
294
+ return args;
295
+ }
296
+
297
+ // src/tool-definition.ts
298
+ import { Type as Type2 } from "typebox";
299
+ function webToolParameters(inspection) {
300
+ const capability = inspection.capability;
301
+ const fields = capability === "contents" ? { urls: Type2.Array(Type2.String({ minLength: 1 }), { minItems: 1 }) } : capability === "research" ? { input: Type2.String({ minLength: 1 }) } : {
302
+ queries: Type2.Array(Type2.String({ minLength: 1 }), {
303
+ minItems: 1,
304
+ maxItems: 10
305
+ }),
306
+ ...capability === "search" ? { maxResults: Type2.Optional(Type2.Integer({ minimum: 1 })) } : {}
307
+ };
308
+ return Type2.Object(
309
+ {
310
+ ...fields,
311
+ ...inspection.optionSchema ? {
312
+ options: Type2.Optional(
313
+ inspection.optionSchema
314
+ )
315
+ } : {}
316
+ },
317
+ { additionalProperties: false }
318
+ );
319
+ }
320
+ var descriptions = {
321
+ search: "Search up to ten queries and return titles, URLs, and snippets in input order.",
322
+ contents: "Fetch and extract readable contents from web URLs.",
323
+ answer: "Answer up to ten questions using web-grounded evidence.",
324
+ research: "Run foreground multi-step web research and return the final report."
325
+ };
326
+
327
+ export {
328
+ DOCUMENT_SCHEMAS,
329
+ WEB_NAMESPACE,
330
+ createClientCache,
331
+ executeCapability,
332
+ formatToolOutput,
333
+ prepareToolArguments,
334
+ webToolParameters,
335
+ descriptions
336
+ };
@@ -0,0 +1,111 @@
1
+ import {
2
+ optionSchema,
3
+ providers
4
+ } from "./chunk-EBKQHHCO.js";
5
+ import {
6
+ CONFIG_SCHEMA_URL
7
+ } from "./chunk-HZVTFUBC.js";
8
+ import {
9
+ CAPABILITIES
10
+ } from "./chunk-46OIVYHW.js";
11
+
12
+ // src/configuration/schema.ts
13
+ var text = { type: "string", minLength: 1 };
14
+ var object = (properties) => ({
15
+ type: "object",
16
+ additionalProperties: false,
17
+ properties
18
+ });
19
+ var source = {
20
+ oneOf: ["env", "value", "command"].map((key) => ({
21
+ ...object({
22
+ [key]: key === "command" ? { type: "array", minItems: 1, items: text } : text
23
+ }),
24
+ required: [key]
25
+ }))
26
+ };
27
+ var sourceMap = { type: "object", additionalProperties: source };
28
+ var command = {
29
+ ...object({
30
+ argv: { type: "array", minItems: 1, items: text },
31
+ cwd: text,
32
+ env: sourceMap
33
+ }),
34
+ required: ["argv"]
35
+ };
36
+ var positive = { type: "integer", minimum: 1 };
37
+ var timeout = { ...positive, maximum: 2147483647 };
38
+ var fields = {
39
+ credentials: sourceMap,
40
+ baseUrl: text,
41
+ accountId: source,
42
+ commands: object(
43
+ Object.fromEntries(CAPABILITIES.map((capability) => [capability, command]))
44
+ )
45
+ };
46
+ var configurationSchema = {
47
+ $schema: "https://json-schema.org/draft/2020-12/schema",
48
+ $id: CONFIG_SCHEMA_URL,
49
+ title: "webfox configuration",
50
+ ...object({
51
+ $schema: text,
52
+ defaults: object(
53
+ Object.fromEntries(
54
+ CAPABILITIES.map((capability) => [
55
+ capability,
56
+ object({
57
+ provider: {
58
+ enum: Object.values(providers).filter((provider) => provider.capabilities[capability]).map((provider) => provider.id)
59
+ },
60
+ ...capability === "search" ? { maxResults: positive } : {}
61
+ })
62
+ ])
63
+ )
64
+ ),
65
+ execution: object({
66
+ timeoutMs: timeout,
67
+ researchTimeoutMs: timeout,
68
+ retries: { type: "integer", minimum: 0 },
69
+ retryDelayMs: { type: "integer", minimum: 0 },
70
+ concurrency: positive
71
+ }),
72
+ providers: object(
73
+ Object.fromEntries(
74
+ Object.values(providers).map((provider) => [
75
+ provider.id,
76
+ object(
77
+ Object.fromEntries(
78
+ provider.fields.map((field) => [
79
+ field,
80
+ field === "options" ? object(
81
+ Object.fromEntries(
82
+ CAPABILITIES.filter(
83
+ (capability) => provider.capabilities[capability]
84
+ ).map((capability) => [
85
+ capability,
86
+ optionSchema(provider, capability, "defaults") ?? {
87
+ type: "object",
88
+ additionalProperties: provider.id === "custom"
89
+ }
90
+ ])
91
+ )
92
+ ) : field === "credentials" ? object(
93
+ Object.fromEntries(
94
+ provider.credentials.map((credential) => [
95
+ credential.name,
96
+ source
97
+ ])
98
+ )
99
+ ) : fields[field]
100
+ ])
101
+ )
102
+ )
103
+ ])
104
+ )
105
+ )
106
+ })
107
+ };
108
+
109
+ export {
110
+ configurationSchema
111
+ };