@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
package/dist/tools/fetch.js
CHANGED
|
@@ -1,646 +1,2 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { z } from "zod";
|
|
3
|
-
//#region src/tools/fetch.ts
|
|
4
|
-
const DEFAULT_MAX_BYTES = 1e6;
|
|
5
|
-
const DEFAULT_MAX_MODEL_CHARS = 24e3;
|
|
6
|
-
const DEFAULT_TIMEOUT_MS = 1e4;
|
|
7
|
-
const DEFAULT_MODEL_HEADER_ALLOWLIST = [
|
|
8
|
-
"accept",
|
|
9
|
-
"accept-language",
|
|
10
|
-
"range"
|
|
11
|
-
];
|
|
12
|
-
const DEFAULT_ACCEPT = "text/markdown, text/plain;q=0.9, application/json;q=0.8, text/html;q=0.5, */*;q=0.1";
|
|
13
|
-
const MAX_REDIRECTS = 5;
|
|
14
|
-
/**
|
|
15
|
-
* Create the Think fetch tools.
|
|
16
|
-
*
|
|
17
|
-
* Returns a generic `fetch_url` tool (when a public `allowlist` is configured)
|
|
18
|
-
* plus one `fetch_<name>` tool per configured binding target. Throws when no
|
|
19
|
-
* allowlist and no bindings are configured, so a misconfiguration fails loudly
|
|
20
|
-
* instead of silently registering nothing.
|
|
21
|
-
*
|
|
22
|
-
* @example
|
|
23
|
-
* ```ts
|
|
24
|
-
* createFetchTools({
|
|
25
|
-
* allowlist: ["https://developers.cloudflare.com/**"],
|
|
26
|
-
* bindings: {
|
|
27
|
-
* docsApi: { binding: env.DOCS_API, allowlist: ["/v1/docs/**"] }
|
|
28
|
-
* }
|
|
29
|
-
* });
|
|
30
|
-
* ```
|
|
31
|
-
*/
|
|
32
|
-
function createFetchTools(options) {
|
|
33
|
-
const publicAllowlist = (options.allowlist ?? []).filter((entry) => entry.length > 0);
|
|
34
|
-
const bindings = options.bindings ?? {};
|
|
35
|
-
const bindingNames = Object.keys(bindings);
|
|
36
|
-
if (publicAllowlist.length === 0 && bindingNames.length === 0) throw new Error("createFetchTools requires a non-empty `allowlist` or at least one `bindings` target.");
|
|
37
|
-
const config = {
|
|
38
|
-
maxBytes: options.maxBytes ?? DEFAULT_MAX_BYTES,
|
|
39
|
-
maxModelChars: options.maxModelChars ?? DEFAULT_MAX_MODEL_CHARS,
|
|
40
|
-
spillToWorkspace: options.spillToWorkspace ?? false,
|
|
41
|
-
workspace: options.workspace,
|
|
42
|
-
timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS,
|
|
43
|
-
response: options.response ?? "auto",
|
|
44
|
-
followRedirects: options.followRedirects ?? "allowlisted",
|
|
45
|
-
modelHeaderAllowlist: new Set((options.modelHeaderAllowlist ?? DEFAULT_MODEL_HEADER_ALLOWLIST).map((name) => name.toLowerCase())),
|
|
46
|
-
defaultAccept: options.defaultAccept ?? DEFAULT_ACCEPT,
|
|
47
|
-
onEvent: options.onEvent
|
|
48
|
-
};
|
|
49
|
-
const tools = {};
|
|
50
|
-
if (publicAllowlist.length > 0) {
|
|
51
|
-
const target = {
|
|
52
|
-
kind: "public",
|
|
53
|
-
allowlist: publicAllowlist.map(compilePattern),
|
|
54
|
-
fixedHeaders: {},
|
|
55
|
-
baseUrl: ""
|
|
56
|
-
};
|
|
57
|
-
tools.fetch_url = tool({
|
|
58
|
-
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.",
|
|
59
|
-
inputSchema: z.object({
|
|
60
|
-
url: z.string().describe("Absolute http(s) URL to fetch. Must be allowlisted."),
|
|
61
|
-
response: responseModeSchema,
|
|
62
|
-
headers: headersSchema
|
|
63
|
-
}),
|
|
64
|
-
execute: (input, opts) => runFetch({
|
|
65
|
-
toolName: "fetch_url",
|
|
66
|
-
target,
|
|
67
|
-
config,
|
|
68
|
-
requested: input.url,
|
|
69
|
-
responseOverride: input.response,
|
|
70
|
-
modelHeaders: input.headers,
|
|
71
|
-
abortSignal: opts?.abortSignal
|
|
72
|
-
}),
|
|
73
|
-
toModelOutput: ({ output }) => toModelOutput(output)
|
|
74
|
-
});
|
|
75
|
-
}
|
|
76
|
-
for (const name of bindingNames) {
|
|
77
|
-
const def = bindings[name];
|
|
78
|
-
const toolName = `fetch_${sanitizeName(name)}`;
|
|
79
|
-
const target = {
|
|
80
|
-
kind: "binding",
|
|
81
|
-
binding: def.binding,
|
|
82
|
-
allowlist: def.allowlist.map(compilePattern),
|
|
83
|
-
fixedHeaders: def.headers ?? {},
|
|
84
|
-
baseUrl: def.baseUrl ?? "https://binding.local"
|
|
85
|
-
};
|
|
86
|
-
tools[toolName] = tool({
|
|
87
|
-
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.`,
|
|
88
|
-
inputSchema: z.object({
|
|
89
|
-
path: z.string().describe("Path (e.g. /v1/docs/search) or an allowlisted absolute URL."),
|
|
90
|
-
response: responseModeSchema,
|
|
91
|
-
headers: headersSchema
|
|
92
|
-
}),
|
|
93
|
-
execute: (input, opts) => runFetch({
|
|
94
|
-
toolName,
|
|
95
|
-
target,
|
|
96
|
-
config,
|
|
97
|
-
requested: input.path,
|
|
98
|
-
responseOverride: input.response,
|
|
99
|
-
modelHeaders: input.headers,
|
|
100
|
-
abortSignal: opts?.abortSignal
|
|
101
|
-
}),
|
|
102
|
-
toModelOutput: ({ output }) => toModelOutput(output)
|
|
103
|
-
});
|
|
104
|
-
}
|
|
105
|
-
return tools;
|
|
106
|
-
}
|
|
107
|
-
const responseModeSchema = z.enum([
|
|
108
|
-
"text",
|
|
109
|
-
"json",
|
|
110
|
-
"auto",
|
|
111
|
-
"workspace"
|
|
112
|
-
]).optional().describe("How to handle the response body. Defaults to the configured mode.");
|
|
113
|
-
const headersSchema = z.record(z.string(), z.string()).optional().describe("Optional request headers; only safe read headers are honored.");
|
|
114
|
-
async function runFetch(args) {
|
|
115
|
-
const { toolName, config, requested } = args;
|
|
116
|
-
const result = await runFetchInner(args);
|
|
117
|
-
if (config.onEvent) try {
|
|
118
|
-
config.onEvent(result.ok ? {
|
|
119
|
-
tool: toolName,
|
|
120
|
-
ok: true,
|
|
121
|
-
requestedUrl: requested,
|
|
122
|
-
finalUrl: result.finalUrl,
|
|
123
|
-
status: result.status,
|
|
124
|
-
bytes: result.bytes,
|
|
125
|
-
truncated: result.truncated,
|
|
126
|
-
response: result.response
|
|
127
|
-
} : {
|
|
128
|
-
tool: toolName,
|
|
129
|
-
ok: false,
|
|
130
|
-
requestedUrl: requested,
|
|
131
|
-
finalUrl: result.finalUrl,
|
|
132
|
-
status: result.status,
|
|
133
|
-
code: result.code
|
|
134
|
-
});
|
|
135
|
-
} catch {}
|
|
136
|
-
return result;
|
|
137
|
-
}
|
|
138
|
-
async function runFetchInner(args) {
|
|
139
|
-
const { target, config, requested, responseOverride, modelHeaders } = args;
|
|
140
|
-
const rawUrl = target.kind === "binding" && !/^https?:\/\//i.test(requested) ? resolveAgainstBase(requested, target.baseUrl) : requested;
|
|
141
|
-
if (rawUrl === null) return {
|
|
142
|
-
ok: false,
|
|
143
|
-
code: "disallowed_url",
|
|
144
|
-
message: "Invalid path."
|
|
145
|
-
};
|
|
146
|
-
const normalized = normalizeRequestUrl(rawUrl);
|
|
147
|
-
if ("error" in normalized) return {
|
|
148
|
-
ok: false,
|
|
149
|
-
code: "disallowed_url",
|
|
150
|
-
message: normalized.error
|
|
151
|
-
};
|
|
152
|
-
const url = normalized.url;
|
|
153
|
-
if (target.kind === "public" && isBlockedHost(url.hostname)) return {
|
|
154
|
-
ok: false,
|
|
155
|
-
code: "disallowed_url",
|
|
156
|
-
message: `Refusing to fetch a private or local address: ${url.hostname}`
|
|
157
|
-
};
|
|
158
|
-
if (!matchesAllowlist(url, target.allowlist)) return {
|
|
159
|
-
ok: false,
|
|
160
|
-
code: "disallowed_url",
|
|
161
|
-
message: `URL is not on the allowlist: ${url.toString()}`
|
|
162
|
-
};
|
|
163
|
-
const responseMode = responseOverride ?? config.response;
|
|
164
|
-
const safeModelHeaders = filterModelHeaders(modelHeaders, config.modelHeaderAllowlist);
|
|
165
|
-
return executeRequest({
|
|
166
|
-
target,
|
|
167
|
-
config,
|
|
168
|
-
initialUrl: url,
|
|
169
|
-
responseMode,
|
|
170
|
-
fixedHeaders: target.fixedHeaders,
|
|
171
|
-
modelHeaders: safeModelHeaders,
|
|
172
|
-
abortSignal: args.abortSignal
|
|
173
|
-
});
|
|
174
|
-
}
|
|
175
|
-
async function executeRequest(args) {
|
|
176
|
-
const { target, config, initialUrl, responseMode } = args;
|
|
177
|
-
const method = "GET";
|
|
178
|
-
const controller = new AbortController();
|
|
179
|
-
const onAbort = () => controller.abort();
|
|
180
|
-
if (args.abortSignal) if (args.abortSignal.aborted) controller.abort();
|
|
181
|
-
else args.abortSignal.addEventListener("abort", onAbort, { once: true });
|
|
182
|
-
const timer = setTimeout(() => controller.abort(), config.timeoutMs);
|
|
183
|
-
const initialOrigin = initialUrl.origin;
|
|
184
|
-
let currentUrl = initialUrl;
|
|
185
|
-
let headers = applyDefaultAccept(mergeHeaders(args.fixedHeaders, args.modelHeaders), config.defaultAccept);
|
|
186
|
-
try {
|
|
187
|
-
for (let hop = 0;; hop++) {
|
|
188
|
-
if (hop > MAX_REDIRECTS) return {
|
|
189
|
-
ok: false,
|
|
190
|
-
code: "request_failed",
|
|
191
|
-
finalUrl: currentUrl.toString(),
|
|
192
|
-
message: "Too many redirects."
|
|
193
|
-
};
|
|
194
|
-
const res = await doFetch(target, currentUrl, method, headers, controller.signal);
|
|
195
|
-
if (isRedirect(res.status)) {
|
|
196
|
-
const location = res.headers.get("location");
|
|
197
|
-
if (location) {
|
|
198
|
-
const redirectOutcome = resolveRedirect({
|
|
199
|
-
target,
|
|
200
|
-
config,
|
|
201
|
-
location,
|
|
202
|
-
currentUrl,
|
|
203
|
-
initialOrigin
|
|
204
|
-
});
|
|
205
|
-
if ("error" in redirectOutcome) {
|
|
206
|
-
discardBody(res);
|
|
207
|
-
return {
|
|
208
|
-
ok: false,
|
|
209
|
-
code: "disallowed_redirect",
|
|
210
|
-
status: res.status,
|
|
211
|
-
finalUrl: currentUrl.toString(),
|
|
212
|
-
message: redirectOutcome.error
|
|
213
|
-
};
|
|
214
|
-
}
|
|
215
|
-
discardBody(res);
|
|
216
|
-
if (redirectOutcome.url.origin !== currentUrl.origin) headers = applyDefaultAccept({}, config.defaultAccept);
|
|
217
|
-
currentUrl = redirectOutcome.url;
|
|
218
|
-
continue;
|
|
219
|
-
}
|
|
220
|
-
}
|
|
221
|
-
if (res.status < 200 || res.status >= 300) {
|
|
222
|
-
discardBody(res);
|
|
223
|
-
return {
|
|
224
|
-
ok: false,
|
|
225
|
-
code: "non_2xx",
|
|
226
|
-
status: res.status,
|
|
227
|
-
finalUrl: currentUrl.toString(),
|
|
228
|
-
message: `HTTP ${res.status}`
|
|
229
|
-
};
|
|
230
|
-
}
|
|
231
|
-
return finalizeResponse({
|
|
232
|
-
res,
|
|
233
|
-
config,
|
|
234
|
-
responseMode,
|
|
235
|
-
finalUrl: currentUrl.toString()
|
|
236
|
-
});
|
|
237
|
-
}
|
|
238
|
-
} catch (error) {
|
|
239
|
-
if (controller.signal.aborted) {
|
|
240
|
-
const aborted = args.abortSignal?.aborted ?? false;
|
|
241
|
-
return {
|
|
242
|
-
ok: false,
|
|
243
|
-
code: aborted ? "aborted" : "timeout",
|
|
244
|
-
finalUrl: currentUrl.toString(),
|
|
245
|
-
message: aborted ? "Request aborted." : "Request timed out."
|
|
246
|
-
};
|
|
247
|
-
}
|
|
248
|
-
return {
|
|
249
|
-
ok: false,
|
|
250
|
-
code: "request_failed",
|
|
251
|
-
finalUrl: currentUrl.toString(),
|
|
252
|
-
message: errorMessage(error)
|
|
253
|
-
};
|
|
254
|
-
} finally {
|
|
255
|
-
clearTimeout(timer);
|
|
256
|
-
args.abortSignal?.removeEventListener("abort", onAbort);
|
|
257
|
-
}
|
|
258
|
-
}
|
|
259
|
-
/**
|
|
260
|
-
* Cancel a response body we won't read (non-2xx, blocked/followed redirects)
|
|
261
|
-
* so the underlying connection isn't left dangling.
|
|
262
|
-
*/
|
|
263
|
-
function discardBody(res) {
|
|
264
|
-
res.body?.cancel().catch(() => {});
|
|
265
|
-
}
|
|
266
|
-
function doFetch(target, url, method, headers, signal) {
|
|
267
|
-
const init = {
|
|
268
|
-
method,
|
|
269
|
-
headers,
|
|
270
|
-
redirect: "manual",
|
|
271
|
-
signal
|
|
272
|
-
};
|
|
273
|
-
if (target.kind === "binding" && target.binding) return target.binding.fetch(url.toString(), init);
|
|
274
|
-
return fetch(url.toString(), init);
|
|
275
|
-
}
|
|
276
|
-
function resolveRedirect(args) {
|
|
277
|
-
const { target, config, location, currentUrl, initialOrigin } = args;
|
|
278
|
-
if (config.followRedirects === "none") return { error: "Redirects are disabled." };
|
|
279
|
-
let next;
|
|
280
|
-
try {
|
|
281
|
-
next = new URL(location, currentUrl);
|
|
282
|
-
} catch {
|
|
283
|
-
return { error: "Invalid redirect target." };
|
|
284
|
-
}
|
|
285
|
-
if (next.protocol !== "http:" && next.protocol !== "https:") return { error: "Redirect to a non-http(s) URL is not allowed." };
|
|
286
|
-
if (next.username || next.password) return { error: "Redirect to a URL with credentials is not allowed." };
|
|
287
|
-
if (target.kind === "binding" && next.origin !== currentUrl.origin) return { error: "Cross-origin redirects are not allowed for bindings." };
|
|
288
|
-
if (target.kind === "public" && isBlockedHost(next.hostname)) return { error: `Redirect to a private or local address: ${next.hostname}` };
|
|
289
|
-
if (config.followRedirects === "same-origin") {
|
|
290
|
-
if (next.origin !== initialOrigin) return { error: "Redirect escaped the original origin." };
|
|
291
|
-
} else if (config.followRedirects === "allowlisted") {
|
|
292
|
-
if (!matchesAllowlist(next, target.allowlist)) return { error: "Redirect target is not on the allowlist." };
|
|
293
|
-
}
|
|
294
|
-
return { url: next };
|
|
295
|
-
}
|
|
296
|
-
async function finalizeResponse(args) {
|
|
297
|
-
const { res, config, responseMode, finalUrl } = args;
|
|
298
|
-
const contentType = (res.headers.get("content-type") ?? "").split(";")[0].trim().toLowerCase();
|
|
299
|
-
const { bytes, capped } = await readCapped(res, config.maxBytes);
|
|
300
|
-
const mode = resolveResponseMode(responseMode, contentType, config);
|
|
301
|
-
if (bytes.byteLength === 0 && mode !== "workspace") return {
|
|
302
|
-
ok: true,
|
|
303
|
-
status: res.status,
|
|
304
|
-
finalUrl,
|
|
305
|
-
contentType,
|
|
306
|
-
bytes: 0,
|
|
307
|
-
truncated: false,
|
|
308
|
-
response: "text",
|
|
309
|
-
body: ""
|
|
310
|
-
};
|
|
311
|
-
if (mode === "unsupported") return {
|
|
312
|
-
ok: false,
|
|
313
|
-
code: "unsupported_content_type",
|
|
314
|
-
finalUrl,
|
|
315
|
-
message: `Unsupported content type: ${contentType || "unknown"}. Use response: "workspace" to store it.`
|
|
316
|
-
};
|
|
317
|
-
if (mode === "workspace") return spillToWorkspace({
|
|
318
|
-
bytes,
|
|
319
|
-
capped,
|
|
320
|
-
contentType,
|
|
321
|
-
finalUrl,
|
|
322
|
-
status: res.status,
|
|
323
|
-
config
|
|
324
|
-
});
|
|
325
|
-
const text = new TextDecoder().decode(bytes);
|
|
326
|
-
if (mode === "json") {
|
|
327
|
-
if (capped) return {
|
|
328
|
-
ok: false,
|
|
329
|
-
code: "too_large",
|
|
330
|
-
finalUrl,
|
|
331
|
-
message: `Response exceeded the ${config.maxBytes} byte cap and cannot be parsed as JSON. Use response: "workspace".`
|
|
332
|
-
};
|
|
333
|
-
try {
|
|
334
|
-
const json = JSON.parse(text);
|
|
335
|
-
return {
|
|
336
|
-
ok: true,
|
|
337
|
-
status: res.status,
|
|
338
|
-
finalUrl,
|
|
339
|
-
contentType,
|
|
340
|
-
bytes: bytes.byteLength,
|
|
341
|
-
truncated: false,
|
|
342
|
-
response: "json",
|
|
343
|
-
json
|
|
344
|
-
};
|
|
345
|
-
} catch {
|
|
346
|
-
return {
|
|
347
|
-
ok: false,
|
|
348
|
-
code: "invalid_json",
|
|
349
|
-
finalUrl,
|
|
350
|
-
message: "Response body is not valid JSON."
|
|
351
|
-
};
|
|
352
|
-
}
|
|
353
|
-
}
|
|
354
|
-
const { value, truncated: textTruncated } = truncateText(text, config.maxModelChars);
|
|
355
|
-
return {
|
|
356
|
-
ok: true,
|
|
357
|
-
status: res.status,
|
|
358
|
-
finalUrl,
|
|
359
|
-
contentType,
|
|
360
|
-
bytes: bytes.byteLength,
|
|
361
|
-
truncated: capped || textTruncated,
|
|
362
|
-
response: "text",
|
|
363
|
-
body: value
|
|
364
|
-
};
|
|
365
|
-
}
|
|
366
|
-
async function spillToWorkspace(args) {
|
|
367
|
-
const { bytes, capped, contentType, finalUrl, status, config } = args;
|
|
368
|
-
const ws = config.workspace;
|
|
369
|
-
if (!ws) return {
|
|
370
|
-
ok: false,
|
|
371
|
-
code: "unsupported_content_type",
|
|
372
|
-
finalUrl,
|
|
373
|
-
message: "response: \"workspace\" requires a workspace, but none is configured."
|
|
374
|
-
};
|
|
375
|
-
const isTextual = isTextualContentType(contentType);
|
|
376
|
-
const path = `/fetched/${Date.now()}-${randomToken()}.${extensionFor(contentType)}`;
|
|
377
|
-
try {
|
|
378
|
-
await ws.mkdir("/fetched", { recursive: true });
|
|
379
|
-
if (isTextual) await ws.writeFile(path, new TextDecoder().decode(bytes));
|
|
380
|
-
else if (ws.writeFileBytes) await ws.writeFileBytes(path, bytes);
|
|
381
|
-
else return {
|
|
382
|
-
ok: false,
|
|
383
|
-
code: "unsupported_content_type",
|
|
384
|
-
finalUrl,
|
|
385
|
-
message: "Binary response cannot be stored: workspace does not support writeFileBytes."
|
|
386
|
-
};
|
|
387
|
-
} catch (error) {
|
|
388
|
-
return {
|
|
389
|
-
ok: false,
|
|
390
|
-
code: "request_failed",
|
|
391
|
-
finalUrl,
|
|
392
|
-
message: `Failed to write workspace file: ${errorMessage(error)}`
|
|
393
|
-
};
|
|
394
|
-
}
|
|
395
|
-
return {
|
|
396
|
-
ok: true,
|
|
397
|
-
status,
|
|
398
|
-
finalUrl,
|
|
399
|
-
contentType,
|
|
400
|
-
bytes: bytes.byteLength,
|
|
401
|
-
truncated: capped,
|
|
402
|
-
response: "workspace",
|
|
403
|
-
path
|
|
404
|
-
};
|
|
405
|
-
}
|
|
406
|
-
async function readCapped(res, maxBytes) {
|
|
407
|
-
const body = res.body;
|
|
408
|
-
if (!body) return {
|
|
409
|
-
bytes: /* @__PURE__ */ new Uint8Array(0),
|
|
410
|
-
capped: false
|
|
411
|
-
};
|
|
412
|
-
const reader = body.getReader();
|
|
413
|
-
const chunks = [];
|
|
414
|
-
let total = 0;
|
|
415
|
-
let capped = false;
|
|
416
|
-
while (true) {
|
|
417
|
-
const { done, value } = await reader.read();
|
|
418
|
-
if (done) break;
|
|
419
|
-
if (!value) continue;
|
|
420
|
-
if (total + value.byteLength > maxBytes) {
|
|
421
|
-
const remaining = Math.max(0, maxBytes - total);
|
|
422
|
-
if (remaining > 0) chunks.push(value.slice(0, remaining));
|
|
423
|
-
total += remaining;
|
|
424
|
-
capped = true;
|
|
425
|
-
await reader.cancel().catch(() => {});
|
|
426
|
-
break;
|
|
427
|
-
}
|
|
428
|
-
chunks.push(value);
|
|
429
|
-
total += value.byteLength;
|
|
430
|
-
}
|
|
431
|
-
const out = new Uint8Array(total);
|
|
432
|
-
let offset = 0;
|
|
433
|
-
for (const chunk of chunks) {
|
|
434
|
-
out.set(chunk, offset);
|
|
435
|
-
offset += chunk.byteLength;
|
|
436
|
-
}
|
|
437
|
-
return {
|
|
438
|
-
bytes: out,
|
|
439
|
-
capped
|
|
440
|
-
};
|
|
441
|
-
}
|
|
442
|
-
function resolveResponseMode(mode, contentType, config) {
|
|
443
|
-
if (mode === "text") return "text";
|
|
444
|
-
if (mode === "json") return "json";
|
|
445
|
-
if (mode === "workspace") return "workspace";
|
|
446
|
-
if (isJsonContentType(contentType)) return "json";
|
|
447
|
-
if (isTextualContentType(contentType)) return "text";
|
|
448
|
-
if (config.spillToWorkspace && config.workspace) return "workspace";
|
|
449
|
-
return "unsupported";
|
|
450
|
-
}
|
|
451
|
-
function normalizeRequestUrl(raw) {
|
|
452
|
-
let url;
|
|
453
|
-
try {
|
|
454
|
-
url = new URL(raw);
|
|
455
|
-
} catch {
|
|
456
|
-
return { error: "Invalid URL." };
|
|
457
|
-
}
|
|
458
|
-
if (url.protocol !== "http:" && url.protocol !== "https:") return { error: "Only http(s) URLs are allowed." };
|
|
459
|
-
if (url.username || url.password) return { error: "URLs with embedded credentials are not allowed." };
|
|
460
|
-
return { url };
|
|
461
|
-
}
|
|
462
|
-
function resolveAgainstBase(pathOrUrl, baseUrl) {
|
|
463
|
-
try {
|
|
464
|
-
return new URL(pathOrUrl, baseUrl).toString();
|
|
465
|
-
} catch {
|
|
466
|
-
return null;
|
|
467
|
-
}
|
|
468
|
-
}
|
|
469
|
-
/**
|
|
470
|
-
* A bare origin (`https://example.com`, no path) is treated as the origin and
|
|
471
|
-
* everything under it, since the canonical URL always has at least a `/` path.
|
|
472
|
-
* Patterns with an explicit path are matched literally unless they include
|
|
473
|
-
* globs.
|
|
474
|
-
*/
|
|
475
|
-
function normalizeAllowlistPattern(pattern) {
|
|
476
|
-
if (/^https?:\/\/[^/]+$/i.test(pattern)) return `${pattern}/**`;
|
|
477
|
-
return pattern;
|
|
478
|
-
}
|
|
479
|
-
/**
|
|
480
|
-
* Compile an allowlist pattern once at config time so we don't rebuild a
|
|
481
|
-
* `RegExp` on every request. Path-only patterns (`/v1/**`) match against the
|
|
482
|
-
* URL pathname; everything else matches against the canonical origin+path.
|
|
483
|
-
*/
|
|
484
|
-
function compilePattern(pattern) {
|
|
485
|
-
const normalized = normalizeAllowlistPattern(pattern);
|
|
486
|
-
return {
|
|
487
|
-
scope: normalized.startsWith("/") ? "path" : "url",
|
|
488
|
-
re: globToRegExp(normalized)
|
|
489
|
-
};
|
|
490
|
-
}
|
|
491
|
-
function canonicalForMatch(url) {
|
|
492
|
-
const host = url.hostname.replace(/\.$/, "");
|
|
493
|
-
const port = url.port ? `:${url.port}` : "";
|
|
494
|
-
return `${url.protocol}//${host}${port}${url.pathname}`;
|
|
495
|
-
}
|
|
496
|
-
function matchesAllowlist(url, patterns) {
|
|
497
|
-
const canonical = canonicalForMatch(url);
|
|
498
|
-
for (const pattern of patterns) {
|
|
499
|
-
const subject = pattern.scope === "path" ? url.pathname : canonical;
|
|
500
|
-
if (pattern.re.test(subject)) return true;
|
|
501
|
-
}
|
|
502
|
-
return false;
|
|
503
|
-
}
|
|
504
|
-
function globToRegExp(glob) {
|
|
505
|
-
let re = "";
|
|
506
|
-
for (let i = 0; i < glob.length; i++) {
|
|
507
|
-
const c = glob[i];
|
|
508
|
-
if (c === "*") if (glob[i + 1] === "*") {
|
|
509
|
-
re += ".*";
|
|
510
|
-
i++;
|
|
511
|
-
} else re += "[^/]*";
|
|
512
|
-
else if ("\\^$.|?+()[]{}".includes(c)) re += `\\${c}`;
|
|
513
|
-
else re += c;
|
|
514
|
-
}
|
|
515
|
-
return new RegExp(`^${re}$`);
|
|
516
|
-
}
|
|
517
|
-
function isBlockedHost(hostname) {
|
|
518
|
-
const h = hostname.toLowerCase().replace(/\.$/, "");
|
|
519
|
-
if (h.length === 0) return true;
|
|
520
|
-
if (h === "localhost" || h.endsWith(".localhost")) return true;
|
|
521
|
-
if (h.endsWith(".internal")) return true;
|
|
522
|
-
if (h.startsWith("[") && h.endsWith("]")) return isBlockedIpv6(h.slice(1, -1));
|
|
523
|
-
if (/^\d{1,3}(\.\d{1,3}){3}$/.test(h)) return isBlockedIpv4(h);
|
|
524
|
-
if (/^\d+$/.test(h) || /^0x[0-9a-f]+$/.test(h)) return true;
|
|
525
|
-
return false;
|
|
526
|
-
}
|
|
527
|
-
function isBlockedIpv4(ip) {
|
|
528
|
-
const parts = ip.split(".").map((p) => Number.parseInt(p, 10));
|
|
529
|
-
if (parts.length !== 4 || parts.some((n) => Number.isNaN(n) || n < 0 || n > 255)) return true;
|
|
530
|
-
const [a, b] = parts;
|
|
531
|
-
if (a === 0) return true;
|
|
532
|
-
if (a === 10) return true;
|
|
533
|
-
if (a === 127) return true;
|
|
534
|
-
if (a === 169 && b === 254) return true;
|
|
535
|
-
if (a === 172 && b >= 16 && b <= 31) return true;
|
|
536
|
-
if (a === 192 && b === 168) return true;
|
|
537
|
-
if (a === 100 && b >= 64 && b <= 127) return true;
|
|
538
|
-
return false;
|
|
539
|
-
}
|
|
540
|
-
function isBlockedIpv6(ip) {
|
|
541
|
-
const lower = ip.toLowerCase();
|
|
542
|
-
if (lower === "::1" || lower === "::") return true;
|
|
543
|
-
if (lower.startsWith("fc") || lower.startsWith("fd")) return true;
|
|
544
|
-
if (/^fe[89ab]/.test(lower)) return true;
|
|
545
|
-
const dotted = lower.match(/^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/);
|
|
546
|
-
if (dotted) return isBlockedIpv4(dotted[1]);
|
|
547
|
-
const hex = lower.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);
|
|
548
|
-
if (hex) {
|
|
549
|
-
const high = Number.parseInt(hex[1], 16);
|
|
550
|
-
const low = Number.parseInt(hex[2], 16);
|
|
551
|
-
return isBlockedIpv4(`${high >> 8 & 255}.${high & 255}.${low >> 8 & 255}.${low & 255}`);
|
|
552
|
-
}
|
|
553
|
-
return false;
|
|
554
|
-
}
|
|
555
|
-
/**
|
|
556
|
-
* Merge fixed (server-side) and model headers into a lowercased-key map. Fixed
|
|
557
|
-
* headers win, so the model can never override a binding's configured header,
|
|
558
|
-
* and case-only duplicates (`Accept` vs `accept`) can't both be sent.
|
|
559
|
-
*/
|
|
560
|
-
function mergeHeaders(fixed, model) {
|
|
561
|
-
const out = {};
|
|
562
|
-
for (const [name, value] of Object.entries(model)) out[name.toLowerCase()] = value;
|
|
563
|
-
for (const [name, value] of Object.entries(fixed)) out[name.toLowerCase()] = value;
|
|
564
|
-
return out;
|
|
565
|
-
}
|
|
566
|
-
function applyDefaultAccept(headers, defaultAccept) {
|
|
567
|
-
if (!defaultAccept) return headers;
|
|
568
|
-
if (Object.keys(headers).some((name) => name.toLowerCase() === "accept")) return headers;
|
|
569
|
-
return {
|
|
570
|
-
...headers,
|
|
571
|
-
accept: defaultAccept
|
|
572
|
-
};
|
|
573
|
-
}
|
|
574
|
-
function filterModelHeaders(headers, allowlist) {
|
|
575
|
-
if (!headers) return {};
|
|
576
|
-
const out = {};
|
|
577
|
-
for (const [name, value] of Object.entries(headers)) if (allowlist.has(name.toLowerCase())) out[name] = value;
|
|
578
|
-
return out;
|
|
579
|
-
}
|
|
580
|
-
function isJsonContentType(contentType) {
|
|
581
|
-
return contentType === "application/json" || contentType.endsWith("+json") || contentType === "text/json";
|
|
582
|
-
}
|
|
583
|
-
function isTextualContentType(contentType) {
|
|
584
|
-
if (contentType.length === 0) return false;
|
|
585
|
-
if (contentType.startsWith("text/")) return true;
|
|
586
|
-
if (isJsonContentType(contentType)) return true;
|
|
587
|
-
return contentType === "application/xml" || contentType === "application/javascript" || contentType === "application/x-www-form-urlencoded";
|
|
588
|
-
}
|
|
589
|
-
function extensionFor(contentType) {
|
|
590
|
-
if (isJsonContentType(contentType)) return "json";
|
|
591
|
-
if (contentType === "text/html") return "html";
|
|
592
|
-
if (contentType.includes("xml")) return "xml";
|
|
593
|
-
if (contentType.startsWith("text/")) return "txt";
|
|
594
|
-
if (contentType === "application/pdf") return "pdf";
|
|
595
|
-
if (contentType.startsWith("image/")) return contentType.slice(6).split("+")[0] || "img";
|
|
596
|
-
return "bin";
|
|
597
|
-
}
|
|
598
|
-
function truncateText(value, maxChars) {
|
|
599
|
-
if (value.length <= maxChars) return {
|
|
600
|
-
value,
|
|
601
|
-
truncated: false
|
|
602
|
-
};
|
|
603
|
-
return {
|
|
604
|
-
value: `${value.slice(0, maxChars)}\n... (truncated ${value.length - maxChars} chars)`,
|
|
605
|
-
truncated: true
|
|
606
|
-
};
|
|
607
|
-
}
|
|
608
|
-
function isRedirect(status) {
|
|
609
|
-
return status === 301 || status === 302 || status === 303 || status === 307 || status === 308;
|
|
610
|
-
}
|
|
611
|
-
function sanitizeName(name) {
|
|
612
|
-
return name.replace(/[^a-zA-Z0-9_]/g, "_");
|
|
613
|
-
}
|
|
614
|
-
function randomToken() {
|
|
615
|
-
return Math.random().toString(36).slice(2, 10);
|
|
616
|
-
}
|
|
617
|
-
function errorMessage(error) {
|
|
618
|
-
return error instanceof Error ? error.message : String(error);
|
|
619
|
-
}
|
|
620
|
-
function toModelOutput(output) {
|
|
621
|
-
if (!output.ok) return {
|
|
622
|
-
type: "error-text",
|
|
623
|
-
value: output.message
|
|
624
|
-
};
|
|
625
|
-
if (output.response === "json") return {
|
|
626
|
-
type: "json",
|
|
627
|
-
value: {
|
|
628
|
-
status: output.status,
|
|
629
|
-
finalUrl: output.finalUrl,
|
|
630
|
-
contentType: output.contentType,
|
|
631
|
-
json: output.json ?? null
|
|
632
|
-
}
|
|
633
|
-
};
|
|
634
|
-
if (output.response === "workspace") return {
|
|
635
|
-
type: "text",
|
|
636
|
-
value: `Fetched ${output.finalUrl} (${output.contentType || "unknown"}, ${output.bytes} bytes${output.truncated ? ", truncated" : ""}) and saved to ${output.path}.`
|
|
637
|
-
};
|
|
638
|
-
return {
|
|
639
|
-
type: "text",
|
|
640
|
-
value: `Fetched ${output.finalUrl} (HTTP ${output.status}, ${output.contentType || "unknown"}${output.truncated ? ", truncated" : ""}):\n\n` + (output.body ?? "")
|
|
641
|
-
};
|
|
642
|
-
}
|
|
643
|
-
//#endregion
|
|
1
|
+
import { t as createFetchTools } from "../fetch-9f1p8UrI.js";
|
|
644
2
|
export { createFetchTools };
|
|
645
|
-
|
|
646
|
-
//# sourceMappingURL=fetch.js.map
|
package/dist/workflows.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { hn as Think, wn as ThinkSubmissionStatus } from "./index-
|
|
1
|
+
import { hn as Think, wn as ThinkSubmissionStatus } from "./index-Cjq_e9F2.js";
|
|
2
2
|
import { ZodObject, z } from "zod";
|
|
3
3
|
import { WorkflowEvent, WorkflowSleepDuration } from "cloudflare:workers";
|
|
4
4
|
import {
|
package/docs/getting-started.md
CHANGED
|
@@ -6,7 +6,7 @@ By the end of this tutorial you will have a Think agent that:
|
|
|
6
6
|
|
|
7
7
|
- Streams responses to a React chat UI
|
|
8
8
|
- Has persistent memory the model can read and write
|
|
9
|
-
- Includes workspace file tools (read,
|
|
9
|
+
- Includes workspace file tools (read, ls, find, grep, write, edit, delete)
|
|
10
10
|
- Supports custom server-side tools
|
|
11
11
|
|
|
12
12
|
## Prerequisites
|
|
@@ -25,7 +25,7 @@ npm init -y
|
|
|
25
25
|
Install dependencies:
|
|
26
26
|
|
|
27
27
|
```sh
|
|
28
|
-
npm install @cloudflare/think agents ai
|
|
28
|
+
npm install @cloudflare/think @cloudflare/computer agents ai zod react react-dom
|
|
29
29
|
npm install -D wrangler @cloudflare/vite-plugin @cloudflare/workers-types @vitejs/plugin-react @tailwindcss/vite tailwindcss typescript vite
|
|
30
30
|
```
|
|
31
31
|
|
|
@@ -110,7 +110,7 @@ This is a working agent. Think automatically provides:
|
|
|
110
110
|
- WebSocket chat protocol (compatible with `useAgentChat`)
|
|
111
111
|
- Message persistence in SQLite
|
|
112
112
|
- Resumable streaming (page refresh replays buffered chunks)
|
|
113
|
-
- Workspace file tools (read,
|
|
113
|
+
- Workspace file tools (read, ls, find, grep, write, edit, delete)
|
|
114
114
|
- Abort/cancel support
|
|
115
115
|
- Error handling with partial message persistence
|
|
116
116
|
|
|
@@ -272,7 +272,7 @@ export class MyAgent extends Think<Env> {
|
|
|
272
272
|
|
|
273
273
|
Think merges tools from multiple sources automatically. On every turn, the model has access to:
|
|
274
274
|
|
|
275
|
-
1. **Workspace tools** — read,
|
|
275
|
+
1. **Workspace tools** — read, ls, find, grep, write, edit, delete (built-in)
|
|
276
276
|
2. **Context tools** — set_context, search_context (from `configureContext`)
|
|
277
277
|
3. **Your tools** — from `getTools()`
|
|
278
278
|
4. **Skill tools** — activate_skill, read_skill_resource, and optional run_skill_script (from `getSkills()`)
|