@wraith-ai/core 0.1.0 → 0.1.1

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 (153) hide show
  1. package/README.md +1 -1
  2. package/dist/{attempt-BeB7EltG.d.mts → attempt-HgararU3.d.mts} +2 -1
  3. package/dist/attempt-HgararU3.d.mts.map +1 -0
  4. package/dist/{capabilities-BPb5HSH6.d.mts → capabilities-CNsPrkB7.d.mts} +2 -1
  5. package/dist/capabilities-CNsPrkB7.d.mts.map +1 -0
  6. package/dist/index.d.mts +6 -5
  7. package/dist/index.d.mts.map +1 -0
  8. package/dist/index.mjs +11 -9
  9. package/dist/index.mjs.map +1 -0
  10. package/dist/{methods-CZp6XGn8.mjs → methods-7Ryz6zbd.mjs} +4 -2
  11. package/dist/methods-7Ryz6zbd.mjs.map +1 -0
  12. package/dist/{model-B6tJ9kX_.mjs → model-C16NUwXW.mjs} +2 -0
  13. package/dist/model-C16NUwXW.mjs.map +1 -0
  14. package/dist/{model-D6LQSveS.d.mts → model-_wqePNTL.d.mts} +4 -3
  15. package/dist/model-_wqePNTL.d.mts.map +1 -0
  16. package/dist/{models-dev-Y0ZikMBQ.d.mts → models-dev-DNgymZy3.d.mts} +3 -2
  17. package/dist/models-dev-DNgymZy3.d.mts.map +1 -0
  18. package/dist/{openai-codex-BhtZvNpm.mjs → openai-codex-Bz1EFPEi.mjs} +3 -1
  19. package/dist/openai-codex-Bz1EFPEi.mjs.map +1 -0
  20. package/dist/{openai-codex-Bk-iG7MZ.mjs → openai-codex-uvjhVoVy.mjs} +6 -4
  21. package/dist/openai-codex-uvjhVoVy.mjs.map +1 -0
  22. package/dist/{openai-compatible-hkXv-P74.mjs → openai-compatible-DBppnQ_N.mjs} +4 -2
  23. package/dist/openai-compatible-DBppnQ_N.mjs.map +1 -0
  24. package/dist/{openrouter-BflQBug2.mjs → openrouter-D8nTOAQo.mjs} +5 -3
  25. package/dist/openrouter-D8nTOAQo.mjs.map +1 -0
  26. package/dist/providers/openai-codex.d.mts +4 -3
  27. package/dist/providers/openai-codex.d.mts.map +1 -0
  28. package/dist/providers/openai-codex.mjs +1 -1
  29. package/dist/providers/openai-compatible.d.mts +3 -2
  30. package/dist/providers/openai-compatible.d.mts.map +1 -0
  31. package/dist/providers/openai-compatible.mjs +1 -1
  32. package/dist/providers/openrouter.d.mts +3 -2
  33. package/dist/providers/openrouter.d.mts.map +1 -0
  34. package/dist/providers/openrouter.mjs +1 -1
  35. package/dist/{shared-8d7RsyPH.mjs → shared-BIJaPhMm.mjs} +3 -1
  36. package/dist/shared-BIJaPhMm.mjs.map +1 -0
  37. package/dist/snapshot.d.mts +3 -2
  38. package/dist/snapshot.d.mts.map +1 -0
  39. package/dist/snapshot.mjs +4999 -4977
  40. package/dist/snapshot.mjs.map +1 -0
  41. package/dist/{turn-effort-DquDDwdE.mjs → turn-effort-C61L4JIt.mjs} +2 -0
  42. package/dist/turn-effort-C61L4JIt.mjs.map +1 -0
  43. package/package.json +3 -2
  44. package/src/agent/agent.ts +90 -0
  45. package/src/agent/attachments.ts +195 -0
  46. package/src/agent/classifier.ts +525 -0
  47. package/src/agent/compact.ts +384 -0
  48. package/src/agent/conversation.ts +300 -0
  49. package/src/agent/cost.ts +164 -0
  50. package/src/agent/inbox.ts +80 -0
  51. package/src/agent/instructions.ts +62 -0
  52. package/src/agent/loop.ts +675 -0
  53. package/src/agent/messages.ts +252 -0
  54. package/src/agent/on-demand.ts +58 -0
  55. package/src/agent/prompts.ts +35 -0
  56. package/src/agent/request-images.ts +94 -0
  57. package/src/agent/stop.ts +37 -0
  58. package/src/agent/title.ts +122 -0
  59. package/src/agent/tool-groups.ts +186 -0
  60. package/src/agent/tools.ts +106 -0
  61. package/src/app.ts +67 -0
  62. package/src/config/credential-file-store.ts +66 -0
  63. package/src/config/environment.ts +105 -0
  64. package/src/config/instructions.ts +157 -0
  65. package/src/config/load.ts +667 -0
  66. package/src/config/locked-file.ts +85 -0
  67. package/src/config/paths.ts +368 -0
  68. package/src/config/schema.ts +363 -0
  69. package/src/config/subagents.ts +156 -0
  70. package/src/config/trust.ts +53 -0
  71. package/src/config/write.ts +241 -0
  72. package/src/errors.ts +85 -0
  73. package/src/events/types.ts +258 -0
  74. package/src/glob.ts +161 -0
  75. package/src/index.ts +681 -0
  76. package/src/logger.ts +47 -0
  77. package/src/paths.ts +143 -0
  78. package/src/permissions/chain.ts +42 -0
  79. package/src/permissions/command.ts +233 -0
  80. package/src/permissions/layered.ts +77 -0
  81. package/src/permissions/match.ts +80 -0
  82. package/src/permissions/modes.ts +48 -0
  83. package/src/permissions/policy.ts +160 -0
  84. package/src/permissions/types.ts +159 -0
  85. package/src/providers/cache.ts +107 -0
  86. package/src/providers/capabilities.ts +77 -0
  87. package/src/providers/catalog-view.ts +91 -0
  88. package/src/providers/catalog.ts +65 -0
  89. package/src/providers/errors.ts +108 -0
  90. package/src/providers/factories/index.ts +15 -0
  91. package/src/providers/factories/openai-codex.ts +382 -0
  92. package/src/providers/factories/openai-compatible.ts +81 -0
  93. package/src/providers/factories/openrouter.ts +165 -0
  94. package/src/providers/factories/shared.ts +22 -0
  95. package/src/providers/model.ts +197 -0
  96. package/src/providers/models-dev.ts +355 -0
  97. package/src/providers/oauth/methods.ts +10 -0
  98. package/src/providers/oauth/openai-codex.ts +228 -0
  99. package/src/providers/oauth.ts +177 -0
  100. package/src/providers/openai-codex.ts +7 -0
  101. package/src/providers/openai-compatible.ts +2 -0
  102. package/src/providers/openrouter.ts +2 -0
  103. package/src/providers/registry.ts +464 -0
  104. package/src/providers/turn-effort.ts +156 -0
  105. package/src/providers/types.ts +83 -0
  106. package/src/session/backend.ts +44 -0
  107. package/src/session/file-store.ts +278 -0
  108. package/src/session/format.ts +1037 -0
  109. package/src/session/memory-store.ts +73 -0
  110. package/src/session/session.ts +153 -0
  111. package/src/session/store.ts +219 -0
  112. package/src/sign-in/attempt.ts +166 -0
  113. package/src/sign-in/loopback.ts +74 -0
  114. package/src/snapshot/data.json +8936 -0
  115. package/src/snapshot/index.ts +37 -0
  116. package/src/tools/bin.ts +364 -0
  117. package/src/tools/builtin.ts +48 -0
  118. package/src/tools/change.ts +88 -0
  119. package/src/tools/define.ts +267 -0
  120. package/src/tools/describe.ts +96 -0
  121. package/src/tools/fs/edit-file.ts +129 -0
  122. package/src/tools/fs/glob.ts +75 -0
  123. package/src/tools/fs/grep.ts +212 -0
  124. package/src/tools/fs/line-endings.ts +17 -0
  125. package/src/tools/fs/list-dir.ts +85 -0
  126. package/src/tools/fs/read-file.ts +230 -0
  127. package/src/tools/fs/ripgrep.ts +211 -0
  128. package/src/tools/fs/write-file.ts +97 -0
  129. package/src/tools/job.ts +252 -0
  130. package/src/tools/mcp/auth-store.ts +127 -0
  131. package/src/tools/mcp/command.ts +151 -0
  132. package/src/tools/mcp/config.ts +168 -0
  133. package/src/tools/mcp/servers.ts +463 -0
  134. package/src/tools/mcp/sign-in.ts +226 -0
  135. package/src/tools/mcp/stdio.ts +204 -0
  136. package/src/tools/mcp/tools.ts +173 -0
  137. package/src/tools/on-demand.ts +184 -0
  138. package/src/tools/registry.ts +935 -0
  139. package/src/tools/shell/bash.ts +217 -0
  140. package/src/tools/shell/find-bash.ts +162 -0
  141. package/src/tools/source.ts +35 -0
  142. package/src/tools/spill.ts +127 -0
  143. package/src/tools/subagents.ts +597 -0
  144. package/src/tools/tasks.ts +603 -0
  145. package/src/tools/to-model.ts +33 -0
  146. package/src/tools/web/address.ts +95 -0
  147. package/src/tools/web/exa.ts +163 -0
  148. package/src/tools/web/fetch.ts +373 -0
  149. package/src/tools/web/html.ts +173 -0
  150. package/src/tools/web/search.ts +111 -0
  151. package/src/tools/web/source.ts +51 -0
  152. package/src/units.ts +18 -0
  153. package/src/version.ts +23 -0
@@ -0,0 +1,95 @@
1
+ import { lookup as dnsLookup } from "node:dns/promises";
2
+ import { BlockList, isIP } from "node:net";
3
+ import { AgentError } from "../../errors";
4
+
5
+ /**
6
+ * Where `web_fetch` will not go: this machine and the networks behind it.
7
+ *
8
+ * Not a network boundary — while bash is allowed the model has curl, and a name
9
+ * can resolve differently a moment later. It stops the ordinary case: a page or
10
+ * a redirect pointing a fetch at a router or a metadata service.
11
+ */
12
+
13
+ /** Every address a host name has. Injected so tests never ask a resolver. */
14
+ export type HostLookup = (hostname: string) => Promise<readonly string[]>;
15
+
16
+ export const systemLookup: HostLookup = async (hostname) =>
17
+ (await dnsLookup(hostname, { all: true })).map((entry) => entry.address);
18
+
19
+ const local = new BlockList();
20
+ for (const [network, prefix] of [
21
+ ["0.0.0.0", 8],
22
+ ["10.0.0.0", 8],
23
+ ["100.64.0.0", 10],
24
+ ["127.0.0.0", 8],
25
+ ["169.254.0.0", 16],
26
+ ["172.16.0.0", 12],
27
+ ["192.0.0.0", 24],
28
+ ["192.168.0.0", 16],
29
+ ["198.18.0.0", 15],
30
+ ["224.0.0.0", 4],
31
+ ["240.0.0.0", 4],
32
+ ] as const) {
33
+ local.addSubnet(network, prefix, "ipv4");
34
+ }
35
+ for (const [network, prefix] of [
36
+ ["::", 127],
37
+ ["fc00::", 7],
38
+ ["fe80::", 10],
39
+ ["ff00::", 8],
40
+ // Both carry an IPv4 address inside, which may be any of the ones above.
41
+ ["64:ff9b::", 96],
42
+ ["2002::", 16],
43
+ ] as const) {
44
+ local.addSubnet(network, prefix, "ipv6");
45
+ }
46
+
47
+ /** Whether an address literal is this machine or a private network. */
48
+ export function isLocalAddress(address: string): boolean {
49
+ const family = isIP(address);
50
+ // The list answers for `::ffff:10.0.0.1` from its IPv4 rules.
51
+ return family === 0 ? false : local.check(address, family === 6 ? "ipv6" : "ipv4");
52
+ }
53
+
54
+ const HINT = "web_fetch only reaches public addresses — for a local server use bash with curl.";
55
+
56
+ function refuse(url: URL, why: string): AgentError {
57
+ return new AgentError("tool/failed", `${why} ${HINT}`, { details: { url: url.href } });
58
+ }
59
+
60
+ /** Throws unless every address the URL's host has is a public one. */
61
+ export async function assertPublicHost(url: URL, lookup: HostLookup = systemLookup): Promise<void> {
62
+ // The URL parser has already turned `0x7f.1` and `2130706433` into dotted form.
63
+ const host = url.hostname.replace(/^\[|\]$/g, "").toLowerCase();
64
+
65
+ if (isIP(host) !== 0) {
66
+ if (isLocalAddress(host)) throw refuse(url, `${host} is a local or private address.`);
67
+ return;
68
+ }
69
+
70
+ if (host === "localhost" || host.endsWith(".localhost") || !host.includes(".")) {
71
+ throw refuse(url, `"${host}" is a name on this machine or its network.`);
72
+ }
73
+
74
+ let addresses: readonly string[];
75
+ try {
76
+ addresses = await lookup(host);
77
+ } catch (cause) {
78
+ // Unresolved means unchecked, so it is refused rather than tried.
79
+ throw new AgentError("tool/failed", `"${host}" could not be resolved.`, {
80
+ cause,
81
+ details: { url: url.href },
82
+ });
83
+ }
84
+
85
+ if (addresses.length === 0) {
86
+ throw new AgentError("tool/failed", `"${host}" could not be resolved.`, {
87
+ details: { url: url.href },
88
+ });
89
+ }
90
+
91
+ const inside = addresses.find(isLocalAddress);
92
+ if (inside !== undefined) {
93
+ throw refuse(url, `"${host}" resolves to ${inside}, a local or private address.`);
94
+ }
95
+ }
@@ -0,0 +1,163 @@
1
+ import { z } from "zod";
2
+ import { AgentError } from "../../errors";
3
+ import type { WebSearch, WebSearchResult } from "./search";
4
+
5
+ /**
6
+ * Exa's hosted endpoint as a search backend.
7
+ *
8
+ * One POST carrying a JSON-RPC `tools/call`, with no MCP client around it. It
9
+ * works without a key, on a quota counted per address; a key lifts that.
10
+ */
11
+
12
+ export const EXA_ENDPOINT = "https://mcp.exa.ai/mcp";
13
+
14
+ export interface ExaSearchOptions {
15
+ /** Sent as a header, never in the address: addresses end up in logs. */
16
+ apiKey?: string;
17
+ /**
18
+ * What a user of this application does to store a key, added to the message
19
+ * about the free quota running out — the core does not know the command.
20
+ */
21
+ keyHint?: string;
22
+ /** Injected in tests, so nothing there leaves the machine. */
23
+ fetch?: typeof globalThis.fetch;
24
+ endpoint?: string;
25
+ }
26
+
27
+ const envelopeSchema = z.object({
28
+ result: z
29
+ .object({
30
+ content: z.array(z.object({ text: z.string().optional() })).default([]),
31
+ isError: z.boolean().optional(),
32
+ })
33
+ .optional(),
34
+ error: z.object({ message: z.string().optional() }).optional(),
35
+ });
36
+
37
+ type Envelope = z.infer<typeof envelopeSchema>;
38
+
39
+ /** The answer comes as an event stream from Exa and as bare JSON from others like it. */
40
+ function readEnvelope(body: string): Envelope | undefined {
41
+ const candidates = body.trimStart().startsWith("{")
42
+ ? [body]
43
+ : body
44
+ .split(/\r?\n/)
45
+ .filter((line) => line.startsWith("data:"))
46
+ .map((line) => line.slice("data:".length));
47
+
48
+ for (const candidate of candidates) {
49
+ try {
50
+ const parsed = envelopeSchema.safeParse(JSON.parse(candidate));
51
+ if (parsed.success && (parsed.data.result !== undefined || parsed.data.error !== undefined)) {
52
+ return parsed.data;
53
+ }
54
+ } catch {
55
+ // A keep-alive or a partial line; the next one may be the answer.
56
+ }
57
+ }
58
+ return undefined;
59
+ }
60
+
61
+ const BLOCK = /^Title: (.*)\nURL: (\S+)\n(?:Published: (.*)\n)?(?:Author: .*\n)?(?:Highlights:\n?)?([\s\S]*)$/;
62
+
63
+ /** Results arrive as one text: `Title:` / `URL:` / … blocks with `---` between them. */
64
+ export function parseExaResults(text: string): WebSearchResult[] {
65
+ return text
66
+ .split(/\n+---\n+(?=Title: )/)
67
+ .flatMap((block): WebSearchResult[] => {
68
+ const match = BLOCK.exec(block.trim());
69
+ if (match === null) return [];
70
+ const [, title = "", url = "", published, body = ""] = match;
71
+ return [
72
+ {
73
+ title: title.trim(),
74
+ url,
75
+ ...(published === undefined || published.trim() === "N/A" ? {} : { published: published.trim() }),
76
+ text: body.trim(),
77
+ },
78
+ ];
79
+ });
80
+ }
81
+
82
+ export function exaSearch(options: ExaSearchOptions = {}): WebSearch {
83
+ const fetchImpl = options.fetch ?? globalThis.fetch;
84
+ const endpoint = options.endpoint ?? EXA_ENDPOINT;
85
+ const hasKey = options.apiKey !== undefined && options.apiKey !== "";
86
+
87
+ /** Written for the model: it has to stop, and say what lifts the limit. */
88
+ const rateLimited = (retryAfter: string | null): AgentError => {
89
+ const wait = retryAfter === null ? "" : ` (the service says to wait ${retryAfter} s)`;
90
+ const hint = options.keyHint === undefined ? "" : ` — ${options.keyHint}`;
91
+ return new AgentError(
92
+ "tool/failed",
93
+ hasKey
94
+ ? `The search service is rate-limiting this key${wait}. Do not retry right away.`
95
+ : `The free search quota for this address is used up${wait}. Do not retry: tell the user ` +
96
+ `that an Exa API key lifts the limit${hint}.`,
97
+ { details: { status: 429 } },
98
+ );
99
+ };
100
+
101
+ return async (query, { limit, signal }) => {
102
+ const response = await fetchImpl(endpoint, {
103
+ method: "POST",
104
+ headers: {
105
+ "Content-Type": "application/json",
106
+ Accept: "application/json, text/event-stream",
107
+ ...(hasKey ? { Authorization: `Bearer ${options.apiKey ?? ""}` } : {}),
108
+ },
109
+ body: JSON.stringify({
110
+ jsonrpc: "2.0",
111
+ id: 1,
112
+ method: "tools/call",
113
+ params: {
114
+ name: "web_search_exa",
115
+ // Exa's schema requires `objective`; the query is the goal.
116
+ arguments: { query, objective: query, numResults: limit },
117
+ },
118
+ }),
119
+ signal,
120
+ });
121
+
122
+ if (response.status === 429) {
123
+ await response.body?.cancel();
124
+ throw rateLimited(response.headers.get("retry-after"));
125
+ }
126
+
127
+ if (!response.ok) {
128
+ await response.body?.cancel();
129
+ const rejected = hasKey && (response.status === 401 || response.status === 403);
130
+ throw new AgentError(
131
+ "tool/failed",
132
+ rejected
133
+ ? `The search service did not accept the Exa API key (${String(response.status)}).`
134
+ : `The search service answered ${String(response.status)}.`,
135
+ { details: { status: response.status } },
136
+ );
137
+ }
138
+
139
+ const envelope = readEnvelope(await response.text());
140
+ const text = (envelope?.result?.content ?? []).map((part) => part.text ?? "").join("\n");
141
+
142
+ if (envelope === undefined || envelope.error !== undefined || envelope.result?.isError === true) {
143
+ const said = envelope?.error?.message ?? (text === "" ? "an answer that could not be read" : text);
144
+ // Their second limit answers 200 with an error inside, and advice about
145
+ // an MCP address that means nothing here.
146
+ if (/rate limit/i.test(said)) throw rateLimited(null);
147
+ throw new AgentError("tool/failed", `The search service refused the search: ${said}`, {
148
+ details: { query },
149
+ });
150
+ }
151
+
152
+ const results = parseExaResults(text);
153
+ // Their format changing must be an error here, not a search that finds nothing.
154
+ if (results.length === 0 && text.trim() !== "" && !/^No (?:search )?results found/i.test(text.trim())) {
155
+ throw new AgentError(
156
+ "tool/failed",
157
+ "The search service answered in a format this version does not read.",
158
+ { details: { query } },
159
+ );
160
+ }
161
+ return results;
162
+ };
163
+ }
@@ -0,0 +1,373 @@
1
+ import { Buffer } from "node:buffer";
2
+ import { z } from "zod";
3
+ import { APP_NAME } from "../../app";
4
+ import { AgentError } from "../../errors";
5
+ import { CORE_VERSION } from "../../version";
6
+ import { defineTool } from "../define";
7
+ import { formatBytes, headOf, openSpill } from "../spill";
8
+ import { assertPublicHost, systemLookup, type HostLookup } from "./address";
9
+ import { htmlToMarkdown } from "./html";
10
+
11
+ /**
12
+ * One page, fetched here and handed to the model as markdown.
13
+ *
14
+ * No model sits in between: the HTML is cleaned, not summarized, so the
15
+ * signatures stay word for word.
16
+ */
17
+
18
+ const MAX_DOWNLOAD_BYTES = 5 * 1024 * 1024;
19
+ /** What comes back directly, the same as one `read_file` call returns. */
20
+ const RETURN_LIMIT_BYTES = 50 * 1024;
21
+ const DEFAULT_TIMEOUT_MS = 30_000;
22
+ const MAX_TIMEOUT_MS = 120_000;
23
+ const MAX_REDIRECTS = 5;
24
+ const REDIRECTS = new Set([301, 302, 303, 307, 308]);
25
+ const BINARY_PROBE_BYTES = 8_192;
26
+
27
+ /** Markdown first: servers that negotiate answer with it and nothing needs converting. */
28
+ const ACCEPT =
29
+ "text/markdown;q=1.0, text/x-markdown;q=0.9, text/plain;q=0.8, text/html;q=0.7, */*;q=0.1";
30
+
31
+ const BINARY_TYPES = /^(?:image|audio|video|font)\/|^application\/(?:pdf|zip|gzip|x-tar|wasm)$/;
32
+
33
+ export interface WebFetchOptions {
34
+ /** Injected in tests, so nothing there leaves the machine. */
35
+ fetch?: typeof globalThis.fetch;
36
+ /** Injected for the same reason. */
37
+ lookup?: HostLookup;
38
+ /** How the tool introduces itself. Its own name by default, never a browser's. */
39
+ userAgent?: string;
40
+ }
41
+
42
+ interface WebFetchOutput {
43
+ /** The address that answered, after redirects on the same host. */
44
+ url: string;
45
+ title?: string;
46
+ contentType: string;
47
+ content: string;
48
+ /** Size of the whole page as converted, of which `content` may be the start. */
49
+ bytes: number;
50
+ truncated: boolean;
51
+ /** The whole page, when it was too long to return and there was somewhere to keep it. */
52
+ outputPath?: string;
53
+ notice?: string;
54
+ /** Set instead of content when the address leads to another host. */
55
+ redirect?: string;
56
+ }
57
+
58
+ type Landing = { response: Response; url: URL } | { redirect: URL };
59
+
60
+ function parseAddress(raw: string): URL {
61
+ let url: URL;
62
+ try {
63
+ url = new URL(raw.trim());
64
+ } catch {
65
+ throw new AgentError(
66
+ "tool/invalid-input",
67
+ `"${raw}" is not a full address — it has to start with https://.`,
68
+ { details: { url: raw } },
69
+ );
70
+ }
71
+ if (url.protocol === "http:") url.protocol = "https:";
72
+ if (url.protocol !== "https:") {
73
+ throw new AgentError("tool/invalid-input", "Only http and https addresses can be fetched.", {
74
+ details: { url: raw },
75
+ });
76
+ }
77
+ // `https://docs.rs@evil.com/` reads as docs.rs and goes to evil.com.
78
+ if (url.username !== "" || url.password !== "") {
79
+ throw new AgentError(
80
+ "tool/invalid-input",
81
+ `That address goes to ${url.hostname}; the part before "@" is a user name. Give the address without it.`,
82
+ { details: { url: raw } },
83
+ );
84
+ }
85
+ url.hash = "";
86
+ return url;
87
+ }
88
+
89
+ /** `example.com` and `www.example.com` are one site; anything else is another. */
90
+ function sameSite(next: URL, start: URL): boolean {
91
+ const bare = (host: string): string => host.replace(/^www\./, "");
92
+ return (
93
+ next.protocol === "https:" &&
94
+ next.username === "" &&
95
+ next.port === start.port &&
96
+ bare(next.hostname) === bare(start.hostname)
97
+ );
98
+ }
99
+
100
+ async function readBody(response: Response, url: URL): Promise<Buffer> {
101
+ const tooLarge = (): AgentError =>
102
+ new AgentError(
103
+ "tool/too-large",
104
+ `${url.href} is larger than ${formatBytes(MAX_DOWNLOAD_BYTES)}, which is more than web_fetch downloads.`,
105
+ { details: { url: url.href } },
106
+ );
107
+
108
+ if (Number(response.headers.get("content-length") ?? "0") > MAX_DOWNLOAD_BYTES) {
109
+ await response.body?.cancel();
110
+ throw tooLarge();
111
+ }
112
+
113
+ const reader = response.body?.getReader();
114
+ if (reader === undefined) return Buffer.alloc(0);
115
+
116
+ const chunks: Uint8Array[] = [];
117
+ let total = 0;
118
+ for (;;) {
119
+ const { done, value } = await reader.read();
120
+ if (done) break;
121
+ total += value.length;
122
+ // The header is optional and can lie, so the count is kept here too.
123
+ if (total > MAX_DOWNLOAD_BYTES) {
124
+ await reader.cancel();
125
+ throw tooLarge();
126
+ }
127
+ chunks.push(value);
128
+ }
129
+ return Buffer.concat(chunks);
130
+ }
131
+
132
+ function decode(body: Buffer, contentType: string): string {
133
+ const declared =
134
+ /charset\s*=\s*"?([\w.:-]+)/i.exec(contentType)?.[1] ??
135
+ // An old page says it only in its own <meta>.
136
+ /<meta[^>]+charset\s*=\s*["']?([\w.:-]+)/i.exec(body.subarray(0, 2_048).toString("latin1"))?.[1];
137
+
138
+ if (declared !== undefined && !/^utf-?8$/i.test(declared)) {
139
+ try {
140
+ return new TextDecoder(declared).decode(body);
141
+ } catch {
142
+ // A label this runtime does not know reads as UTF-8, which is the likeliest truth.
143
+ }
144
+ }
145
+ return new TextDecoder().decode(body);
146
+ }
147
+
148
+ function formatJson(text: string): string {
149
+ try {
150
+ return JSON.stringify(JSON.parse(text), null, 2);
151
+ } catch {
152
+ return text;
153
+ }
154
+ }
155
+
156
+ function cutNotice(lines: number | undefined, bytes: number, path: string | undefined): string {
157
+ const shown = lines === undefined ? `the first ${formatBytes(RETURN_LIMIT_BYTES)}` : `the first ${String(lines)} lines`;
158
+ if (path === undefined) {
159
+ return `Only ${shown} of ${formatBytes(bytes)} are shown; the rest was not kept.`;
160
+ }
161
+ const next =
162
+ lines === undefined
163
+ ? "it is one long line, so use bash on it (head -c, tail -c, cut, jq)"
164
+ : `read on with read_file from offset=${String(lines + 1)}, or search it with grep`;
165
+ return `Only ${shown} are shown. The whole page (${formatBytes(bytes)}) is saved at ${path} — ${next}.`;
166
+ }
167
+
168
+ function reason(cause: unknown): string {
169
+ return cause instanceof Error ? cause.message : String(cause);
170
+ }
171
+
172
+ export function createWebFetchTool(options: WebFetchOptions = {}) {
173
+ const fetchImpl = options.fetch ?? globalThis.fetch;
174
+ const lookup = options.lookup ?? systemLookup;
175
+ const headers = {
176
+ Accept: ACCEPT,
177
+ "User-Agent": options.userAgent ?? `${APP_NAME}/${CORE_VERSION}`,
178
+ };
179
+
180
+ /** Goes as far as the first answer that is not a redirect on the same site. */
181
+ const follow = async (start: URL, signal: AbortSignal): Promise<Landing> => {
182
+ let url = start;
183
+
184
+ for (let hop = 0; hop <= MAX_REDIRECTS; hop += 1) {
185
+ // Every hop, not only the first: a redirect is how a public page points inward.
186
+ await assertPublicHost(url, lookup);
187
+ const response = await fetchImpl(url, { headers, redirect: "manual", signal });
188
+
189
+ const location = REDIRECTS.has(response.status) ? response.headers.get("location") : null;
190
+ if (location === null) return { response, url };
191
+ await response.body?.cancel();
192
+
193
+ let next: URL;
194
+ try {
195
+ next = new URL(location, url);
196
+ } catch {
197
+ throw new AgentError("tool/failed", `${url.href} redirects to "${location}", which is not an address.`, {
198
+ details: { url: url.href },
199
+ });
200
+ }
201
+ if (next.protocol === "http:") next.protocol = "https:";
202
+ next.hash = "";
203
+
204
+ // Another host is the caller's decision: it is returned, not followed.
205
+ if (!sameSite(next, start)) return { redirect: next };
206
+ url = next;
207
+ }
208
+
209
+ throw new AgentError(
210
+ "tool/failed",
211
+ `${start.href} redirects more than ${String(MAX_REDIRECTS)} times.`,
212
+ { details: { url: start.href } },
213
+ );
214
+ };
215
+
216
+ return defineTool({
217
+ name: "web_fetch",
218
+ description:
219
+ "Fetch one public web page and return it as markdown: HTML is cleaned and converted, " +
220
+ "JSON is formatted, markdown and plain text come back as they are. Use it for " +
221
+ "documentation and other pages whose address you know. It cannot reach localhost or " +
222
+ "private networks (use bash with curl there), runs no JavaScript, and does not read " +
223
+ `images or PDFs. Up to ${String(RETURN_LIMIT_BYTES / 1024)} KB comes back directly; a longer page is ` +
224
+ "saved to a file and `notice` says where, so read on with read_file or grep. If the " +
225
+ "address redirects to another host nothing is fetched and `redirect` holds the new " +
226
+ "address — fetch that one if it is what you want.",
227
+ danger: "network",
228
+ inputSchema: z.object({
229
+ url: z.string().min(1).describe("Full address of the page. http is upgraded to https."),
230
+ timeout_ms: z
231
+ .number()
232
+ .int()
233
+ .min(1_000)
234
+ .max(MAX_TIMEOUT_MS)
235
+ .optional()
236
+ .describe("How long to wait for the server, 30000 by default."),
237
+ }),
238
+ resources: (input) => ({ url: input.url }),
239
+ describe: (input) => input.url,
240
+ execute: async (input, context): Promise<WebFetchOutput> => {
241
+ const start = parseAddress(input.url);
242
+ const timeoutMs = input.timeout_ms ?? DEFAULT_TIMEOUT_MS;
243
+ const timeout = AbortSignal.timeout(timeoutMs);
244
+ const signal = AbortSignal.any([context.signal, timeout]);
245
+
246
+ let landing: Landing;
247
+ let body: Buffer;
248
+ try {
249
+ landing = await follow(start, signal);
250
+
251
+ if ("redirect" in landing) {
252
+ const to = landing.redirect.href;
253
+ return {
254
+ url: start.href,
255
+ contentType: "",
256
+ content: "",
257
+ bytes: 0,
258
+ truncated: false,
259
+ redirect: to,
260
+ notice: `${start.href} redirects to another host and was not followed. Fetch ${to} if that is the page you want.`,
261
+ };
262
+ }
263
+
264
+ const { response, url } = landing;
265
+ if (!response.ok) {
266
+ await response.body?.cancel();
267
+ const blocked =
268
+ response.headers.get("cf-mitigated") === "challenge"
269
+ ? " The site turns automated clients away; retrying will not help."
270
+ : response.status === 429
271
+ ? " The site is rate-limiting; do not retry right away."
272
+ : "";
273
+ // HTTP/2 has no reason phrase, so the number often stands alone.
274
+ const status = `${String(response.status)} ${response.statusText}`.trim();
275
+ throw new AgentError("tool/failed", `${url.href} answered ${status}.${blocked}`, {
276
+ details: { url: url.href, status: response.status },
277
+ });
278
+ }
279
+
280
+ body = await readBody(response, url);
281
+ } catch (error) {
282
+ if (error instanceof AgentError) throw error;
283
+ if (timeout.aborted) {
284
+ throw new AgentError(
285
+ "tool/timeout",
286
+ `${start.host} did not answer within ${String(timeoutMs)} ms.`,
287
+ { details: { url: start.href } },
288
+ );
289
+ }
290
+ // Cancelled by the user: the registry already answers for that.
291
+ if (context.signal.aborted) throw error;
292
+ throw new AgentError("tool/failed", `Could not fetch ${start.href}: ${reason(error)}`, {
293
+ cause: error,
294
+ details: { url: start.href },
295
+ });
296
+ }
297
+
298
+ const { response, url } = landing;
299
+ const contentType = response.headers.get("content-type") ?? "";
300
+ const mime = (contentType.split(";")[0] ?? "").trim().toLowerCase();
301
+
302
+ if (BINARY_TYPES.test(mime) || body.subarray(0, BINARY_PROBE_BYTES).includes(0)) {
303
+ throw new AgentError(
304
+ "tool/binary-file",
305
+ `${url.href} is ${mime === "" ? "binary data" : mime}, which web_fetch does not read.`,
306
+ { details: { url: url.href, contentType: mime } },
307
+ );
308
+ }
309
+
310
+ const text = decode(body, contentType);
311
+ let content = text;
312
+ let title: string | undefined;
313
+
314
+ const isHtml =
315
+ mime === "text/html" ||
316
+ mime === "application/xhtml+xml" ||
317
+ (mime === "" && /^\s*<(?:!doctype html|html)[\s>]/i.test(text.slice(0, 256)));
318
+
319
+ if (isHtml) {
320
+ const page = htmlToMarkdown(text, url.href);
321
+ content = page.markdown;
322
+ title = page.title;
323
+ } else if (
324
+ mime === "application/json" ||
325
+ mime.endsWith("+json") ||
326
+ // Asked for text first, a registry answers with JSON under `text/plain`.
327
+ ((mime === "text/plain" || mime === "") && /^\s*[[{]/.test(text))
328
+ ) {
329
+ content = formatJson(text);
330
+ }
331
+
332
+ const bytes = Buffer.byteLength(content, "utf8");
333
+ const output: WebFetchOutput = {
334
+ url: url.href,
335
+ ...(title === undefined ? {} : { title }),
336
+ contentType: mime,
337
+ content,
338
+ bytes,
339
+ truncated: false,
340
+ };
341
+
342
+ if (isHtml && content === "") {
343
+ // The usual reason, and one the model cannot see from an empty string.
344
+ output.notice =
345
+ "The page has no readable text — most likely it is drawn by JavaScript, which web_fetch does not run.";
346
+ return output;
347
+ }
348
+
349
+ if (bytes <= RETURN_LIMIT_BYTES) return output;
350
+
351
+ // The whole page goes to the file, so its line numbers carry on from the part shown.
352
+ const spill = openSpill(context, "web_fetch");
353
+ spill?.write(content);
354
+ const saved = spill?.close();
355
+ const { head, lines } = headOf(content, RETURN_LIMIT_BYTES);
356
+
357
+ output.content = head;
358
+ output.truncated = true;
359
+ if (saved !== undefined) output.outputPath = saved.path;
360
+ output.notice = cutNotice(lines, bytes, saved?.path);
361
+ return output;
362
+ },
363
+ describeResult: (output) => {
364
+ if (output.redirect !== undefined) return "redirects to another host";
365
+ const size = formatBytes(output.bytes);
366
+ if (!output.truncated) return size;
367
+ return `${size}, start shown${output.outputPath === undefined ? "" : ", saved to a file"}`;
368
+ },
369
+ });
370
+ }
371
+
372
+ /** The default instance, for listings and for describing stored calls. */
373
+ export const webFetchTool = createWebFetchTool();