@cloudflare/think 0.20.1 → 0.21.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.
- package/README.md +69 -39
- package/dist/classPrivateFieldSet2-DwGJfC3w.js +27 -0
- package/dist/extensions/index.js +2 -1
- package/dist/extensions/index.js.map +1 -1
- package/dist/fetch-9f1p8UrI.js +772 -0
- package/dist/fetch-9f1p8UrI.js.map +1 -0
- package/dist/{fetch-By3eIQ-a.d.ts → fetch-C7s1mpgg.d.ts} +70 -20
- package/dist/{index-CmhSKa6U.d.ts → index-Cjq_e9F2.d.ts} +55 -75
- package/dist/{manager-Cb3DNZgp.js → manager-BubfmA3q.js} +3 -28
- package/dist/{manager-Cb3DNZgp.js.map → manager-BubfmA3q.js.map} +1 -1
- package/dist/messengers/index.d.ts +1 -1
- package/dist/messengers/telegram.d.ts +1 -1
- package/dist/think.d.ts +3 -4
- package/dist/think.js +79 -97
- package/dist/think.js.map +1 -1
- package/dist/tools/execute.d.ts +19 -24
- package/dist/tools/execute.js +20 -40
- package/dist/tools/execute.js.map +1 -1
- package/dist/tools/extensions.d.ts +1 -1
- package/dist/tools/extensions.js +2 -2
- package/dist/tools/extensions.js.map +1 -1
- package/dist/tools/fetch.d.ts +2 -4
- package/dist/tools/fetch.js +1 -645
- package/dist/workflows.d.ts +1 -1
- package/docs/getting-started.md +4 -4
- package/docs/index.md +31 -16
- package/docs/multi-chat.md +22 -59
- package/docs/sub-agents.md +13 -13
- package/docs/tools.md +90 -109
- package/package.json +7 -11
- package/dist/tools/fetch.js.map +0 -1
- package/dist/tools/workspace.d.ts +0 -60
- package/dist/tools/workspace.js +0 -869
- package/dist/tools/workspace.js.map +0 -1
- package/dist/workspace-CNeXc2vl.d.ts +0 -201
|
@@ -0,0 +1,772 @@
|
|
|
1
|
+
import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldGet2, t as _classPrivateFieldSet2 } from "./classPrivateFieldSet2-DwGJfC3w.js";
|
|
2
|
+
import { tool } from "ai";
|
|
3
|
+
import { isPrivateOrLocalHost } from "agents/webfetch";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
//#region src/workspace-files.ts
|
|
6
|
+
/** Directory Computer's backends and tools treat as the working root. */
|
|
7
|
+
const WORKSPACE_ROOT = "/workspace";
|
|
8
|
+
/**
|
|
9
|
+
* Resolve a path against {@link WORKSPACE_ROOT}. Absolute paths pass
|
|
10
|
+
* through; relative ones, such as an extension's `notes/today.md`, land
|
|
11
|
+
* under `/workspace`.
|
|
12
|
+
*
|
|
13
|
+
* @param path - Absolute or root-relative path.
|
|
14
|
+
* @returns An absolute path.
|
|
15
|
+
*/
|
|
16
|
+
function resolveWorkspacePath(path) {
|
|
17
|
+
if (path.startsWith("/")) return path;
|
|
18
|
+
const relative = path.replace(/^\.\//, "");
|
|
19
|
+
return relative === "" || relative === "." ? WORKSPACE_ROOT : `${WORKSPACE_ROOT}/${relative}`;
|
|
20
|
+
}
|
|
21
|
+
const TEXT_ENCODER = new TextEncoder();
|
|
22
|
+
const TEXT_DECODER = new TextDecoder();
|
|
23
|
+
var _fs = /* @__PURE__ */ new WeakMap();
|
|
24
|
+
/**
|
|
25
|
+
* Think's file operations over a {@link ThinkWorkspace}.
|
|
26
|
+
*
|
|
27
|
+
* Translates the Workspace's node-style filesystem into the shape Think's
|
|
28
|
+
* internals use: missing files read as `null` instead of rejecting with
|
|
29
|
+
* `ENOENT`, writes create their parent directories, and listings return
|
|
30
|
+
* {@link WorkspaceEntry} values.
|
|
31
|
+
*
|
|
32
|
+
* @internal
|
|
33
|
+
*/
|
|
34
|
+
var WorkspaceFiles = class {
|
|
35
|
+
/**
|
|
36
|
+
* @param workspace - The Workspace to operate on.
|
|
37
|
+
*/
|
|
38
|
+
constructor(workspace) {
|
|
39
|
+
_classPrivateFieldInitSpec(this, _fs, void 0);
|
|
40
|
+
_classPrivateFieldSet2(_fs, this, workspace.fs);
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Read a file as UTF-8 text.
|
|
44
|
+
*
|
|
45
|
+
* @param path - Absolute file path.
|
|
46
|
+
* @returns The text, or `null` when the file does not exist.
|
|
47
|
+
*/
|
|
48
|
+
async readText(path) {
|
|
49
|
+
const bytes = await this.readBytes(path);
|
|
50
|
+
return bytes === null ? null : TEXT_DECODER.decode(bytes);
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Read a file's bytes.
|
|
54
|
+
*
|
|
55
|
+
* @param path - Absolute file path.
|
|
56
|
+
* @returns The bytes, or `null` when the file does not exist.
|
|
57
|
+
*/
|
|
58
|
+
async readBytes(path) {
|
|
59
|
+
try {
|
|
60
|
+
return await drain(await _classPrivateFieldGet2(_fs, this).readFile(path));
|
|
61
|
+
} catch (error) {
|
|
62
|
+
if (isNotFound(error)) return null;
|
|
63
|
+
throw error;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Write a file, creating missing parent directories.
|
|
68
|
+
*
|
|
69
|
+
* @param path - Absolute file path.
|
|
70
|
+
* @param content - Text, written as UTF-8, or bytes.
|
|
71
|
+
*/
|
|
72
|
+
async write(path, content) {
|
|
73
|
+
const parent = parentDirectory(path);
|
|
74
|
+
if (parent !== "/") await _classPrivateFieldGet2(_fs, this).mkdir(parent, { recursive: true });
|
|
75
|
+
await _classPrivateFieldGet2(_fs, this).writeFile(path, typeof content === "string" ? TEXT_ENCODER.encode(content) : content);
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Remove a file or directory.
|
|
79
|
+
*
|
|
80
|
+
* @param path - Absolute path.
|
|
81
|
+
* @param options - `recursive` removes a non-empty directory; `force`
|
|
82
|
+
* accepts a missing path.
|
|
83
|
+
*/
|
|
84
|
+
async remove(path, options) {
|
|
85
|
+
await _classPrivateFieldGet2(_fs, this).rm(path, options);
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* List a directory's entries in name order.
|
|
89
|
+
*
|
|
90
|
+
* @param path - Absolute directory path.
|
|
91
|
+
* @param options - Page size and start.
|
|
92
|
+
* @returns The entries on the requested page.
|
|
93
|
+
*/
|
|
94
|
+
async list(path, options) {
|
|
95
|
+
return (await _classPrivateFieldGet2(_fs, this).readdir(path, options)).map((entry) => ({
|
|
96
|
+
path: joinPath(path, entry.name),
|
|
97
|
+
name: entry.name,
|
|
98
|
+
type: entry.isDirectory ? "directory" : entry.isSymbolicLink ? "symlink" : "file",
|
|
99
|
+
size: entry.size,
|
|
100
|
+
updatedAt: entry.mtime
|
|
101
|
+
}));
|
|
102
|
+
}
|
|
103
|
+
};
|
|
104
|
+
async function drain(stream) {
|
|
105
|
+
const parts = [];
|
|
106
|
+
let total = 0;
|
|
107
|
+
for await (const part of stream) {
|
|
108
|
+
parts.push(part);
|
|
109
|
+
total += part.byteLength;
|
|
110
|
+
}
|
|
111
|
+
if (parts.length === 1 && parts[0]) return parts[0];
|
|
112
|
+
const bytes = new Uint8Array(total);
|
|
113
|
+
let offset = 0;
|
|
114
|
+
for (const part of parts) {
|
|
115
|
+
bytes.set(part, offset);
|
|
116
|
+
offset += part.byteLength;
|
|
117
|
+
}
|
|
118
|
+
return bytes;
|
|
119
|
+
}
|
|
120
|
+
function isNotFound(error) {
|
|
121
|
+
return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
|
|
122
|
+
}
|
|
123
|
+
function parentDirectory(path) {
|
|
124
|
+
const index = path.lastIndexOf("/");
|
|
125
|
+
return index <= 0 ? "/" : path.slice(0, index);
|
|
126
|
+
}
|
|
127
|
+
function joinPath(directory, name) {
|
|
128
|
+
return directory.endsWith("/") ? `${directory}${name}` : `${directory}/${name}`;
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* A {@link ThinkWorkspace} that resolves the real Workspace on first use.
|
|
132
|
+
*
|
|
133
|
+
* Use it for a Workspace another Durable Object owns, so the agent does not
|
|
134
|
+
* reach the owner until a turn actually touches a file:
|
|
135
|
+
*
|
|
136
|
+
* ```ts
|
|
137
|
+
* import { getWorkspace } from "@cloudflare/computer";
|
|
138
|
+
*
|
|
139
|
+
* override workspace = lazyWorkspace(async () =>
|
|
140
|
+
* getWorkspace(await this.parentAgent(Directory))
|
|
141
|
+
* );
|
|
142
|
+
* ```
|
|
143
|
+
*
|
|
144
|
+
* The resolved Workspace is kept and reused. A failed resolution is not
|
|
145
|
+
* kept, so the next operation tries again. To start over with a new client,
|
|
146
|
+
* for example after disposing the old one, assign a new `lazyWorkspace`.
|
|
147
|
+
*
|
|
148
|
+
* Only `fs` is forwarded, so the agent gets the file tools but no `exec`:
|
|
149
|
+
* the exec tool lists the Workspace's backends synchronously, before
|
|
150
|
+
* anything has been resolved.
|
|
151
|
+
*
|
|
152
|
+
* @param resolve - Produces the Workspace.
|
|
153
|
+
* @returns A Workspace whose `fs` forwards to the resolved one.
|
|
154
|
+
*/
|
|
155
|
+
function lazyWorkspace(resolve) {
|
|
156
|
+
let resolved;
|
|
157
|
+
const fs = async () => {
|
|
158
|
+
resolved ??= resolve().catch((error) => {
|
|
159
|
+
resolved = void 0;
|
|
160
|
+
throw error;
|
|
161
|
+
});
|
|
162
|
+
return (await resolved).fs;
|
|
163
|
+
};
|
|
164
|
+
return { fs: {
|
|
165
|
+
readFile: async (...args) => (await fs()).readFile(...args),
|
|
166
|
+
writeFile: async (...args) => (await fs()).writeFile(...args),
|
|
167
|
+
mkdir: async (...args) => (await fs()).mkdir(...args),
|
|
168
|
+
rm: async (...args) => (await fs()).rm(...args),
|
|
169
|
+
stat: async (...args) => (await fs()).stat(...args),
|
|
170
|
+
readdir: async (...args) => (await fs()).readdir(...args),
|
|
171
|
+
find: async (...args) => (await fs()).find(...args),
|
|
172
|
+
grep: async (...args) => (await fs()).grep(...args)
|
|
173
|
+
} };
|
|
174
|
+
}
|
|
175
|
+
//#endregion
|
|
176
|
+
//#region src/tools/fetch.ts
|
|
177
|
+
const DEFAULT_MAX_BYTES = 1e6;
|
|
178
|
+
const DEFAULT_MAX_MODEL_CHARS = 24e3;
|
|
179
|
+
const DEFAULT_TIMEOUT_MS = 1e4;
|
|
180
|
+
const DEFAULT_MODEL_HEADER_ALLOWLIST = [
|
|
181
|
+
"accept",
|
|
182
|
+
"accept-language",
|
|
183
|
+
"range"
|
|
184
|
+
];
|
|
185
|
+
const DEFAULT_ACCEPT = "text/markdown, text/plain;q=0.9, application/json;q=0.8, text/html;q=0.5, */*;q=0.1";
|
|
186
|
+
const MAX_REDIRECTS = 5;
|
|
187
|
+
/**
|
|
188
|
+
* Create the Think fetch tools.
|
|
189
|
+
*
|
|
190
|
+
* Returns a generic `fetch_url` tool (when a public `allowlist` is configured)
|
|
191
|
+
* plus one `fetch_<name>` tool per configured binding target. Throws when no
|
|
192
|
+
* allowlist and no bindings are configured, so a misconfiguration fails loudly
|
|
193
|
+
* instead of silently registering nothing.
|
|
194
|
+
*
|
|
195
|
+
* @example
|
|
196
|
+
* ```ts
|
|
197
|
+
* createFetchTools({
|
|
198
|
+
* allowlist: ["https://developers.cloudflare.com/**"],
|
|
199
|
+
* bindings: {
|
|
200
|
+
* docsApi: { binding: env.DOCS_API, allowlist: ["/v1/docs/**"] }
|
|
201
|
+
* }
|
|
202
|
+
* });
|
|
203
|
+
* ```
|
|
204
|
+
*/
|
|
205
|
+
function createFetchTools(options) {
|
|
206
|
+
const publicAllowlist = (options.allowlist ?? []).filter((entry) => entry.length > 0);
|
|
207
|
+
const bindings = options.bindings ?? {};
|
|
208
|
+
const bindingNames = Object.keys(bindings);
|
|
209
|
+
if (publicAllowlist.length === 0 && bindingNames.length === 0) throw new Error("createFetchTools requires a non-empty `allowlist` or at least one `bindings` target.");
|
|
210
|
+
const config = {
|
|
211
|
+
maxBytes: options.maxBytes ?? DEFAULT_MAX_BYTES,
|
|
212
|
+
maxModelChars: options.maxModelChars ?? DEFAULT_MAX_MODEL_CHARS,
|
|
213
|
+
spillToWorkspace: options.spillToWorkspace ?? false,
|
|
214
|
+
workspace: options.workspace,
|
|
215
|
+
timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS,
|
|
216
|
+
response: options.response ?? "auto",
|
|
217
|
+
followRedirects: options.followRedirects ?? "allowlisted",
|
|
218
|
+
modelHeaderAllowlist: new Set((options.modelHeaderAllowlist ?? DEFAULT_MODEL_HEADER_ALLOWLIST).map((name) => name.toLowerCase())),
|
|
219
|
+
defaultAccept: options.defaultAccept ?? DEFAULT_ACCEPT,
|
|
220
|
+
onEvent: options.onEvent
|
|
221
|
+
};
|
|
222
|
+
const tools = {};
|
|
223
|
+
if (publicAllowlist.length > 0) {
|
|
224
|
+
const target = {
|
|
225
|
+
kind: "public",
|
|
226
|
+
allowlist: publicAllowlist.map(compilePattern),
|
|
227
|
+
fixedHeaders: {},
|
|
228
|
+
baseUrl: ""
|
|
229
|
+
};
|
|
230
|
+
tools.fetch_url = tool({
|
|
231
|
+
description: "Fetch an allowlisted public URL over HTTP(S) (read-only GET). Returns the response body as text or JSON, or spills large/binary bodies to a workspace file. The URL must be on the configured allowlist; disallowed or private-network URLs are rejected.",
|
|
232
|
+
inputSchema: z.object({
|
|
233
|
+
url: z.string().describe("Absolute http(s) URL to fetch. Must be allowlisted."),
|
|
234
|
+
response: responseModeSchema,
|
|
235
|
+
headers: headersSchema
|
|
236
|
+
}),
|
|
237
|
+
execute: (input, opts) => runFetch({
|
|
238
|
+
toolName: "fetch_url",
|
|
239
|
+
target,
|
|
240
|
+
config,
|
|
241
|
+
requested: input.url,
|
|
242
|
+
responseOverride: input.response,
|
|
243
|
+
modelHeaders: input.headers,
|
|
244
|
+
abortSignal: opts?.abortSignal
|
|
245
|
+
}),
|
|
246
|
+
toModelOutput: ({ output }) => toModelOutput(output)
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
for (const name of bindingNames) {
|
|
250
|
+
const def = bindings[name];
|
|
251
|
+
const toolName = `fetch_${sanitizeName(name)}`;
|
|
252
|
+
const target = {
|
|
253
|
+
kind: "binding",
|
|
254
|
+
binding: def.binding,
|
|
255
|
+
allowlist: def.allowlist.map(compilePattern),
|
|
256
|
+
fixedHeaders: def.headers ?? {},
|
|
257
|
+
baseUrl: def.baseUrl ?? "https://binding.local"
|
|
258
|
+
};
|
|
259
|
+
tools[toolName] = tool({
|
|
260
|
+
description: `Fetch a read-only resource from the "${name}" service binding.${def.description ? ` ${def.description}` : ""} Provide a path (or an allowlisted absolute URL). Requests are routed through the configured binding with fixed server-side headers.`,
|
|
261
|
+
inputSchema: z.object({
|
|
262
|
+
path: z.string().describe("Path (e.g. /v1/docs/search) or an allowlisted absolute URL."),
|
|
263
|
+
response: responseModeSchema,
|
|
264
|
+
headers: headersSchema
|
|
265
|
+
}),
|
|
266
|
+
execute: (input, opts) => runFetch({
|
|
267
|
+
toolName,
|
|
268
|
+
target,
|
|
269
|
+
config,
|
|
270
|
+
requested: input.path,
|
|
271
|
+
responseOverride: input.response,
|
|
272
|
+
modelHeaders: input.headers,
|
|
273
|
+
abortSignal: opts?.abortSignal
|
|
274
|
+
}),
|
|
275
|
+
toModelOutput: ({ output }) => toModelOutput(output)
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
return tools;
|
|
279
|
+
}
|
|
280
|
+
const responseModeSchema = z.enum([
|
|
281
|
+
"text",
|
|
282
|
+
"json",
|
|
283
|
+
"auto",
|
|
284
|
+
"workspace"
|
|
285
|
+
]).optional().describe("How to handle the response body. Defaults to the configured mode.");
|
|
286
|
+
const headersSchema = z.record(z.string(), z.string()).optional().describe("Optional request headers; only safe read headers are honored.");
|
|
287
|
+
async function runFetch(args) {
|
|
288
|
+
const { toolName, config, requested } = args;
|
|
289
|
+
const result = await runFetchInner(args);
|
|
290
|
+
if (config.onEvent) try {
|
|
291
|
+
config.onEvent(result.ok ? {
|
|
292
|
+
tool: toolName,
|
|
293
|
+
ok: true,
|
|
294
|
+
requestedUrl: requested,
|
|
295
|
+
finalUrl: result.finalUrl,
|
|
296
|
+
status: result.status,
|
|
297
|
+
bytes: result.bytes,
|
|
298
|
+
truncated: result.truncated,
|
|
299
|
+
response: result.response
|
|
300
|
+
} : {
|
|
301
|
+
tool: toolName,
|
|
302
|
+
ok: false,
|
|
303
|
+
requestedUrl: requested,
|
|
304
|
+
finalUrl: result.finalUrl,
|
|
305
|
+
status: result.status,
|
|
306
|
+
code: result.code
|
|
307
|
+
});
|
|
308
|
+
} catch {}
|
|
309
|
+
return result;
|
|
310
|
+
}
|
|
311
|
+
async function runFetchInner(args) {
|
|
312
|
+
const { target, config, requested, responseOverride, modelHeaders } = args;
|
|
313
|
+
const rawUrl = target.kind === "binding" && !/^https?:\/\//i.test(requested) ? resolveAgainstBase(requested, target.baseUrl) : requested;
|
|
314
|
+
if (rawUrl === null) return {
|
|
315
|
+
ok: false,
|
|
316
|
+
code: "disallowed_url",
|
|
317
|
+
message: "Invalid path."
|
|
318
|
+
};
|
|
319
|
+
const normalized = normalizeRequestUrl(rawUrl);
|
|
320
|
+
if ("error" in normalized) return {
|
|
321
|
+
ok: false,
|
|
322
|
+
code: "disallowed_url",
|
|
323
|
+
message: normalized.error
|
|
324
|
+
};
|
|
325
|
+
const url = normalized.url;
|
|
326
|
+
if (target.kind === "public" && isPrivateOrLocalHost(url.hostname)) return {
|
|
327
|
+
ok: false,
|
|
328
|
+
code: "disallowed_url",
|
|
329
|
+
message: `Refusing to fetch a private or local address: ${url.hostname}`
|
|
330
|
+
};
|
|
331
|
+
if (!matchesAllowlist(url, target.allowlist)) return {
|
|
332
|
+
ok: false,
|
|
333
|
+
code: "disallowed_url",
|
|
334
|
+
message: `URL is not on the allowlist: ${url.toString()}`
|
|
335
|
+
};
|
|
336
|
+
const responseMode = responseOverride ?? config.response;
|
|
337
|
+
const safeModelHeaders = filterModelHeaders(modelHeaders, config.modelHeaderAllowlist);
|
|
338
|
+
return executeRequest({
|
|
339
|
+
target,
|
|
340
|
+
config,
|
|
341
|
+
initialUrl: url,
|
|
342
|
+
responseMode,
|
|
343
|
+
fixedHeaders: target.fixedHeaders,
|
|
344
|
+
modelHeaders: safeModelHeaders,
|
|
345
|
+
abortSignal: args.abortSignal
|
|
346
|
+
});
|
|
347
|
+
}
|
|
348
|
+
async function executeRequest(args) {
|
|
349
|
+
const { target, config, initialUrl, responseMode } = args;
|
|
350
|
+
const method = "GET";
|
|
351
|
+
const controller = new AbortController();
|
|
352
|
+
const onAbort = () => controller.abort();
|
|
353
|
+
if (args.abortSignal) if (args.abortSignal.aborted) controller.abort();
|
|
354
|
+
else args.abortSignal.addEventListener("abort", onAbort, { once: true });
|
|
355
|
+
const timer = setTimeout(() => controller.abort(), config.timeoutMs);
|
|
356
|
+
const initialOrigin = initialUrl.origin;
|
|
357
|
+
let currentUrl = initialUrl;
|
|
358
|
+
let headers = applyDefaultAccept(mergeHeaders(args.fixedHeaders, args.modelHeaders), config.defaultAccept);
|
|
359
|
+
try {
|
|
360
|
+
for (let hop = 0;; hop++) {
|
|
361
|
+
if (hop > MAX_REDIRECTS) return {
|
|
362
|
+
ok: false,
|
|
363
|
+
code: "request_failed",
|
|
364
|
+
finalUrl: currentUrl.toString(),
|
|
365
|
+
message: "Too many redirects."
|
|
366
|
+
};
|
|
367
|
+
const res = await doFetch(target, currentUrl, method, headers, controller.signal);
|
|
368
|
+
if (isRedirect(res.status)) {
|
|
369
|
+
const location = res.headers.get("location");
|
|
370
|
+
if (location) {
|
|
371
|
+
const redirectOutcome = resolveRedirect({
|
|
372
|
+
target,
|
|
373
|
+
config,
|
|
374
|
+
location,
|
|
375
|
+
currentUrl,
|
|
376
|
+
initialOrigin
|
|
377
|
+
});
|
|
378
|
+
if ("error" in redirectOutcome) {
|
|
379
|
+
discardBody(res);
|
|
380
|
+
return {
|
|
381
|
+
ok: false,
|
|
382
|
+
code: "disallowed_redirect",
|
|
383
|
+
status: res.status,
|
|
384
|
+
finalUrl: currentUrl.toString(),
|
|
385
|
+
message: redirectOutcome.error
|
|
386
|
+
};
|
|
387
|
+
}
|
|
388
|
+
discardBody(res);
|
|
389
|
+
if (redirectOutcome.url.origin !== currentUrl.origin) headers = applyDefaultAccept({}, config.defaultAccept);
|
|
390
|
+
currentUrl = redirectOutcome.url;
|
|
391
|
+
continue;
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
if (res.status < 200 || res.status >= 300) {
|
|
395
|
+
discardBody(res);
|
|
396
|
+
return {
|
|
397
|
+
ok: false,
|
|
398
|
+
code: "non_2xx",
|
|
399
|
+
status: res.status,
|
|
400
|
+
finalUrl: currentUrl.toString(),
|
|
401
|
+
message: `HTTP ${res.status}`
|
|
402
|
+
};
|
|
403
|
+
}
|
|
404
|
+
return finalizeResponse({
|
|
405
|
+
res,
|
|
406
|
+
config,
|
|
407
|
+
responseMode,
|
|
408
|
+
finalUrl: currentUrl.toString()
|
|
409
|
+
});
|
|
410
|
+
}
|
|
411
|
+
} catch (error) {
|
|
412
|
+
if (controller.signal.aborted) {
|
|
413
|
+
const aborted = args.abortSignal?.aborted ?? false;
|
|
414
|
+
return {
|
|
415
|
+
ok: false,
|
|
416
|
+
code: aborted ? "aborted" : "timeout",
|
|
417
|
+
finalUrl: currentUrl.toString(),
|
|
418
|
+
message: aborted ? "Request aborted." : "Request timed out."
|
|
419
|
+
};
|
|
420
|
+
}
|
|
421
|
+
return {
|
|
422
|
+
ok: false,
|
|
423
|
+
code: "request_failed",
|
|
424
|
+
finalUrl: currentUrl.toString(),
|
|
425
|
+
message: errorMessage(error)
|
|
426
|
+
};
|
|
427
|
+
} finally {
|
|
428
|
+
clearTimeout(timer);
|
|
429
|
+
args.abortSignal?.removeEventListener("abort", onAbort);
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
/**
|
|
433
|
+
* Cancel a response body we won't read (non-2xx, blocked/followed redirects)
|
|
434
|
+
* so the underlying connection isn't left dangling.
|
|
435
|
+
*/
|
|
436
|
+
function discardBody(res) {
|
|
437
|
+
res.body?.cancel().catch(() => {});
|
|
438
|
+
}
|
|
439
|
+
function doFetch(target, url, method, headers, signal) {
|
|
440
|
+
const init = {
|
|
441
|
+
method,
|
|
442
|
+
headers,
|
|
443
|
+
redirect: "manual",
|
|
444
|
+
signal
|
|
445
|
+
};
|
|
446
|
+
if (target.kind === "binding" && target.binding) return target.binding.fetch(url.toString(), init);
|
|
447
|
+
return fetch(url.toString(), init);
|
|
448
|
+
}
|
|
449
|
+
function resolveRedirect(args) {
|
|
450
|
+
const { target, config, location, currentUrl, initialOrigin } = args;
|
|
451
|
+
if (config.followRedirects === "none") return { error: "Redirects are disabled." };
|
|
452
|
+
let next;
|
|
453
|
+
try {
|
|
454
|
+
next = new URL(location, currentUrl);
|
|
455
|
+
} catch {
|
|
456
|
+
return { error: "Invalid redirect target." };
|
|
457
|
+
}
|
|
458
|
+
if (next.protocol !== "http:" && next.protocol !== "https:") return { error: "Redirect to a non-http(s) URL is not allowed." };
|
|
459
|
+
if (next.username || next.password) return { error: "Redirect to a URL with credentials is not allowed." };
|
|
460
|
+
if (target.kind === "binding" && next.origin !== currentUrl.origin) return { error: "Cross-origin redirects are not allowed for bindings." };
|
|
461
|
+
if (target.kind === "public" && isPrivateOrLocalHost(next.hostname)) return { error: `Redirect to a private or local address: ${next.hostname}` };
|
|
462
|
+
if (config.followRedirects === "same-origin") {
|
|
463
|
+
if (next.origin !== initialOrigin) return { error: "Redirect escaped the original origin." };
|
|
464
|
+
} else if (config.followRedirects === "allowlisted") {
|
|
465
|
+
if (!matchesAllowlist(next, target.allowlist)) return { error: "Redirect target is not on the allowlist." };
|
|
466
|
+
}
|
|
467
|
+
return { url: next };
|
|
468
|
+
}
|
|
469
|
+
async function finalizeResponse(args) {
|
|
470
|
+
const { res, config, responseMode, finalUrl } = args;
|
|
471
|
+
const contentType = (res.headers.get("content-type") ?? "").split(";")[0].trim().toLowerCase();
|
|
472
|
+
const { bytes, capped } = await readCapped(res, config.maxBytes);
|
|
473
|
+
const mode = resolveResponseMode(responseMode, contentType, config);
|
|
474
|
+
if (bytes.byteLength === 0 && mode !== "workspace") return {
|
|
475
|
+
ok: true,
|
|
476
|
+
status: res.status,
|
|
477
|
+
finalUrl,
|
|
478
|
+
contentType,
|
|
479
|
+
bytes: 0,
|
|
480
|
+
truncated: false,
|
|
481
|
+
response: "text",
|
|
482
|
+
body: ""
|
|
483
|
+
};
|
|
484
|
+
if (mode === "unsupported") return {
|
|
485
|
+
ok: false,
|
|
486
|
+
code: "unsupported_content_type",
|
|
487
|
+
finalUrl,
|
|
488
|
+
message: `Unsupported content type: ${contentType || "unknown"}. Use response: "workspace" to store it.`
|
|
489
|
+
};
|
|
490
|
+
if (mode === "workspace") return spillToWorkspace({
|
|
491
|
+
bytes,
|
|
492
|
+
capped,
|
|
493
|
+
contentType,
|
|
494
|
+
finalUrl,
|
|
495
|
+
status: res.status,
|
|
496
|
+
config
|
|
497
|
+
});
|
|
498
|
+
const text = new TextDecoder().decode(bytes);
|
|
499
|
+
if (mode === "json") {
|
|
500
|
+
if (capped) return {
|
|
501
|
+
ok: false,
|
|
502
|
+
code: "too_large",
|
|
503
|
+
finalUrl,
|
|
504
|
+
message: `Response exceeded the ${config.maxBytes} byte cap and cannot be parsed as JSON. Use response: "workspace".`
|
|
505
|
+
};
|
|
506
|
+
try {
|
|
507
|
+
const json = JSON.parse(text);
|
|
508
|
+
return {
|
|
509
|
+
ok: true,
|
|
510
|
+
status: res.status,
|
|
511
|
+
finalUrl,
|
|
512
|
+
contentType,
|
|
513
|
+
bytes: bytes.byteLength,
|
|
514
|
+
truncated: false,
|
|
515
|
+
response: "json",
|
|
516
|
+
json
|
|
517
|
+
};
|
|
518
|
+
} catch {
|
|
519
|
+
return {
|
|
520
|
+
ok: false,
|
|
521
|
+
code: "invalid_json",
|
|
522
|
+
finalUrl,
|
|
523
|
+
message: "Response body is not valid JSON."
|
|
524
|
+
};
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
const { value, truncated: textTruncated } = truncateText(text, config.maxModelChars);
|
|
528
|
+
return {
|
|
529
|
+
ok: true,
|
|
530
|
+
status: res.status,
|
|
531
|
+
finalUrl,
|
|
532
|
+
contentType,
|
|
533
|
+
bytes: bytes.byteLength,
|
|
534
|
+
truncated: capped || textTruncated,
|
|
535
|
+
response: "text",
|
|
536
|
+
body: value
|
|
537
|
+
};
|
|
538
|
+
}
|
|
539
|
+
async function spillToWorkspace(args) {
|
|
540
|
+
const { bytes, capped, contentType, finalUrl, status, config } = args;
|
|
541
|
+
const ws = config.workspace;
|
|
542
|
+
if (!ws) return {
|
|
543
|
+
ok: false,
|
|
544
|
+
code: "unsupported_content_type",
|
|
545
|
+
finalUrl,
|
|
546
|
+
message: "response: \"workspace\" requires a workspace, but none is configured."
|
|
547
|
+
};
|
|
548
|
+
const path = `/workspace/fetched/${Date.now()}-${randomToken()}.${extensionFor(contentType)}`;
|
|
549
|
+
try {
|
|
550
|
+
await new WorkspaceFiles(ws).write(path, bytes);
|
|
551
|
+
} catch (error) {
|
|
552
|
+
return {
|
|
553
|
+
ok: false,
|
|
554
|
+
code: "request_failed",
|
|
555
|
+
finalUrl,
|
|
556
|
+
message: `Failed to write workspace file: ${errorMessage(error)}`
|
|
557
|
+
};
|
|
558
|
+
}
|
|
559
|
+
return {
|
|
560
|
+
ok: true,
|
|
561
|
+
status,
|
|
562
|
+
finalUrl,
|
|
563
|
+
contentType,
|
|
564
|
+
bytes: bytes.byteLength,
|
|
565
|
+
truncated: capped,
|
|
566
|
+
response: "workspace",
|
|
567
|
+
path
|
|
568
|
+
};
|
|
569
|
+
}
|
|
570
|
+
async function readCapped(res, maxBytes) {
|
|
571
|
+
const body = res.body;
|
|
572
|
+
if (!body) return {
|
|
573
|
+
bytes: /* @__PURE__ */ new Uint8Array(0),
|
|
574
|
+
capped: false
|
|
575
|
+
};
|
|
576
|
+
const reader = body.getReader();
|
|
577
|
+
const chunks = [];
|
|
578
|
+
let total = 0;
|
|
579
|
+
let capped = false;
|
|
580
|
+
while (true) {
|
|
581
|
+
const { done, value } = await reader.read();
|
|
582
|
+
if (done) break;
|
|
583
|
+
if (!value) continue;
|
|
584
|
+
if (total + value.byteLength > maxBytes) {
|
|
585
|
+
const remaining = Math.max(0, maxBytes - total);
|
|
586
|
+
if (remaining > 0) chunks.push(value.slice(0, remaining));
|
|
587
|
+
total += remaining;
|
|
588
|
+
capped = true;
|
|
589
|
+
await reader.cancel().catch(() => {});
|
|
590
|
+
break;
|
|
591
|
+
}
|
|
592
|
+
chunks.push(value);
|
|
593
|
+
total += value.byteLength;
|
|
594
|
+
}
|
|
595
|
+
const out = new Uint8Array(total);
|
|
596
|
+
let offset = 0;
|
|
597
|
+
for (const chunk of chunks) {
|
|
598
|
+
out.set(chunk, offset);
|
|
599
|
+
offset += chunk.byteLength;
|
|
600
|
+
}
|
|
601
|
+
return {
|
|
602
|
+
bytes: out,
|
|
603
|
+
capped
|
|
604
|
+
};
|
|
605
|
+
}
|
|
606
|
+
function resolveResponseMode(mode, contentType, config) {
|
|
607
|
+
if (mode === "text") return "text";
|
|
608
|
+
if (mode === "json") return "json";
|
|
609
|
+
if (mode === "workspace") return "workspace";
|
|
610
|
+
if (isJsonContentType(contentType)) return "json";
|
|
611
|
+
if (isTextualContentType(contentType)) return "text";
|
|
612
|
+
if (config.spillToWorkspace && config.workspace) return "workspace";
|
|
613
|
+
return "unsupported";
|
|
614
|
+
}
|
|
615
|
+
function normalizeRequestUrl(raw) {
|
|
616
|
+
let url;
|
|
617
|
+
try {
|
|
618
|
+
url = new URL(raw);
|
|
619
|
+
} catch {
|
|
620
|
+
return { error: "Invalid URL." };
|
|
621
|
+
}
|
|
622
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") return { error: "Only http(s) URLs are allowed." };
|
|
623
|
+
if (url.username || url.password) return { error: "URLs with embedded credentials are not allowed." };
|
|
624
|
+
return { url };
|
|
625
|
+
}
|
|
626
|
+
function resolveAgainstBase(pathOrUrl, baseUrl) {
|
|
627
|
+
try {
|
|
628
|
+
return new URL(pathOrUrl, baseUrl).toString();
|
|
629
|
+
} catch {
|
|
630
|
+
return null;
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
/**
|
|
634
|
+
* A bare origin (`https://example.com`, no path) is treated as the origin and
|
|
635
|
+
* everything under it, since the canonical URL always has at least a `/` path.
|
|
636
|
+
* Patterns with an explicit path are matched literally unless they include
|
|
637
|
+
* globs.
|
|
638
|
+
*/
|
|
639
|
+
function normalizeAllowlistPattern(pattern) {
|
|
640
|
+
if (/^https?:\/\/[^/]+$/i.test(pattern)) return `${pattern}/**`;
|
|
641
|
+
return pattern;
|
|
642
|
+
}
|
|
643
|
+
/**
|
|
644
|
+
* Compile an allowlist pattern once at config time so we don't rebuild a
|
|
645
|
+
* `RegExp` on every request. Path-only patterns (`/v1/**`) match against the
|
|
646
|
+
* URL pathname; everything else matches against the canonical origin+path.
|
|
647
|
+
*/
|
|
648
|
+
function compilePattern(pattern) {
|
|
649
|
+
const normalized = normalizeAllowlistPattern(pattern);
|
|
650
|
+
return {
|
|
651
|
+
scope: normalized.startsWith("/") ? "path" : "url",
|
|
652
|
+
re: globToRegExp(normalized)
|
|
653
|
+
};
|
|
654
|
+
}
|
|
655
|
+
function canonicalForMatch(url) {
|
|
656
|
+
const host = url.hostname.replace(/\.$/, "");
|
|
657
|
+
const port = url.port ? `:${url.port}` : "";
|
|
658
|
+
return `${url.protocol}//${host}${port}${url.pathname}`;
|
|
659
|
+
}
|
|
660
|
+
function matchesAllowlist(url, patterns) {
|
|
661
|
+
const canonical = canonicalForMatch(url);
|
|
662
|
+
for (const pattern of patterns) {
|
|
663
|
+
const subject = pattern.scope === "path" ? url.pathname : canonical;
|
|
664
|
+
if (pattern.re.test(subject)) return true;
|
|
665
|
+
}
|
|
666
|
+
return false;
|
|
667
|
+
}
|
|
668
|
+
function globToRegExp(glob) {
|
|
669
|
+
let re = "";
|
|
670
|
+
for (let i = 0; i < glob.length; i++) {
|
|
671
|
+
const c = glob[i];
|
|
672
|
+
if (c === "*") if (glob[i + 1] === "*") {
|
|
673
|
+
re += ".*";
|
|
674
|
+
i++;
|
|
675
|
+
} else re += "[^/]*";
|
|
676
|
+
else if ("\\^$.|?+()[]{}".includes(c)) re += `\\${c}`;
|
|
677
|
+
else re += c;
|
|
678
|
+
}
|
|
679
|
+
return new RegExp(`^${re}$`);
|
|
680
|
+
}
|
|
681
|
+
/**
|
|
682
|
+
* Merge fixed (server-side) and model headers into a lowercased-key map. Fixed
|
|
683
|
+
* headers win, so the model can never override a binding's configured header,
|
|
684
|
+
* and case-only duplicates (`Accept` vs `accept`) can't both be sent.
|
|
685
|
+
*/
|
|
686
|
+
function mergeHeaders(fixed, model) {
|
|
687
|
+
const out = {};
|
|
688
|
+
for (const [name, value] of Object.entries(model)) out[name.toLowerCase()] = value;
|
|
689
|
+
for (const [name, value] of Object.entries(fixed)) out[name.toLowerCase()] = value;
|
|
690
|
+
return out;
|
|
691
|
+
}
|
|
692
|
+
function applyDefaultAccept(headers, defaultAccept) {
|
|
693
|
+
if (!defaultAccept) return headers;
|
|
694
|
+
if (Object.keys(headers).some((name) => name.toLowerCase() === "accept")) return headers;
|
|
695
|
+
return {
|
|
696
|
+
...headers,
|
|
697
|
+
accept: defaultAccept
|
|
698
|
+
};
|
|
699
|
+
}
|
|
700
|
+
function filterModelHeaders(headers, allowlist) {
|
|
701
|
+
if (!headers) return {};
|
|
702
|
+
const out = {};
|
|
703
|
+
for (const [name, value] of Object.entries(headers)) if (allowlist.has(name.toLowerCase())) out[name] = value;
|
|
704
|
+
return out;
|
|
705
|
+
}
|
|
706
|
+
function isJsonContentType(contentType) {
|
|
707
|
+
return contentType === "application/json" || contentType.endsWith("+json") || contentType === "text/json";
|
|
708
|
+
}
|
|
709
|
+
function isTextualContentType(contentType) {
|
|
710
|
+
if (contentType.length === 0) return false;
|
|
711
|
+
if (contentType.startsWith("text/")) return true;
|
|
712
|
+
if (isJsonContentType(contentType)) return true;
|
|
713
|
+
return contentType === "application/xml" || contentType === "application/javascript" || contentType === "application/x-www-form-urlencoded";
|
|
714
|
+
}
|
|
715
|
+
function extensionFor(contentType) {
|
|
716
|
+
if (isJsonContentType(contentType)) return "json";
|
|
717
|
+
if (contentType === "text/html") return "html";
|
|
718
|
+
if (contentType.includes("xml")) return "xml";
|
|
719
|
+
if (contentType.startsWith("text/")) return "txt";
|
|
720
|
+
if (contentType === "application/pdf") return "pdf";
|
|
721
|
+
if (contentType.startsWith("image/")) return contentType.slice(6).split("+")[0] || "img";
|
|
722
|
+
return "bin";
|
|
723
|
+
}
|
|
724
|
+
function truncateText(value, maxChars) {
|
|
725
|
+
if (value.length <= maxChars) return {
|
|
726
|
+
value,
|
|
727
|
+
truncated: false
|
|
728
|
+
};
|
|
729
|
+
return {
|
|
730
|
+
value: `${value.slice(0, maxChars)}\n... (truncated ${value.length - maxChars} chars)`,
|
|
731
|
+
truncated: true
|
|
732
|
+
};
|
|
733
|
+
}
|
|
734
|
+
function isRedirect(status) {
|
|
735
|
+
return status === 301 || status === 302 || status === 303 || status === 307 || status === 308;
|
|
736
|
+
}
|
|
737
|
+
function sanitizeName(name) {
|
|
738
|
+
return name.replace(/[^a-zA-Z0-9_]/g, "_");
|
|
739
|
+
}
|
|
740
|
+
function randomToken() {
|
|
741
|
+
return Math.random().toString(36).slice(2, 10);
|
|
742
|
+
}
|
|
743
|
+
function errorMessage(error) {
|
|
744
|
+
return error instanceof Error ? error.message : String(error);
|
|
745
|
+
}
|
|
746
|
+
function toModelOutput(output) {
|
|
747
|
+
if (!output.ok) return {
|
|
748
|
+
type: "error-text",
|
|
749
|
+
value: output.message
|
|
750
|
+
};
|
|
751
|
+
if (output.response === "json") return {
|
|
752
|
+
type: "json",
|
|
753
|
+
value: {
|
|
754
|
+
status: output.status,
|
|
755
|
+
finalUrl: output.finalUrl,
|
|
756
|
+
contentType: output.contentType,
|
|
757
|
+
json: output.json ?? null
|
|
758
|
+
}
|
|
759
|
+
};
|
|
760
|
+
if (output.response === "workspace") return {
|
|
761
|
+
type: "text",
|
|
762
|
+
value: `Fetched ${output.finalUrl} (${output.contentType || "unknown"}, ${output.bytes} bytes${output.truncated ? ", truncated" : ""}) and saved to ${output.path}.`
|
|
763
|
+
};
|
|
764
|
+
return {
|
|
765
|
+
type: "text",
|
|
766
|
+
value: `Fetched ${output.finalUrl} (HTTP ${output.status}, ${output.contentType || "unknown"}${output.truncated ? ", truncated" : ""}):\n\n` + (output.body ?? "")
|
|
767
|
+
};
|
|
768
|
+
}
|
|
769
|
+
//#endregion
|
|
770
|
+
export { resolveWorkspacePath as i, WorkspaceFiles as n, lazyWorkspace as r, createFetchTools as t };
|
|
771
|
+
|
|
772
|
+
//# sourceMappingURL=fetch-9f1p8UrI.js.map
|