@yanzc/claude-pro 0.9.0 → 0.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/README.md +342 -320
  2. package/package.json +1 -2
  3. package/src/agent.js +240 -62
  4. package/src/agents.js +3 -2
  5. package/src/api.js +83 -41
  6. package/src/browser/broker.js +367 -0
  7. package/src/browser/cdp.js +114 -0
  8. package/src/browser/render.js +242 -0
  9. package/src/browser/session.js +948 -0
  10. package/src/browser/snapshot.js +212 -0
  11. package/src/cache.js +1 -1
  12. package/src/checkpoints.js +1 -0
  13. package/src/commands.js +177 -71
  14. package/src/compaction.js +75 -0
  15. package/src/config.js +153 -153
  16. package/src/context.js +45 -18
  17. package/src/filestate.js +2 -1
  18. package/src/gateway.js +208 -164
  19. package/src/hooks.js +2 -2
  20. package/src/keepalive.js +1 -1
  21. package/src/main.js +52 -40
  22. package/src/mcp.js +2 -2
  23. package/src/peers.js +1 -10
  24. package/src/print.js +9 -3
  25. package/src/prompt-profiles.js +0 -6
  26. package/src/prompts.js +6 -62
  27. package/src/ratelimit.js +3 -5
  28. package/src/remote.js +26 -10
  29. package/src/restart.js +3 -0
  30. package/src/runtime.js +33 -10
  31. package/src/selfcheck.js +3 -3
  32. package/src/session.js +93 -3
  33. package/src/supervisor.js +10 -1
  34. package/src/tools/bash.js +19 -18
  35. package/src/tools/browser.js +365 -0
  36. package/src/tools/code.js +430 -0
  37. package/src/tools/effort.js +3 -4
  38. package/src/tools/files.js +92 -19
  39. package/src/tools/index.js +6 -0
  40. package/src/tools/notebook.js +11 -4
  41. package/src/tools/processes.js +274 -0
  42. package/src/tools/search.js +104 -21
  43. package/src/tools/web.js +316 -46
  44. package/src/trace.js +0 -4
  45. package/src/ui/ansi.js +92 -13
  46. package/src/ui/dialogs.js +16 -54
  47. package/src/ui/editor.js +231 -34
  48. package/src/ui/markdown.js +1 -2
  49. package/src/ui/render.js +1 -2
  50. package/src/ui/repl.js +246 -119
  51. package/src/ui/screen.js +139 -31
  52. package/src/updater.js +135 -165
  53. package/src/utils/clipboard.js +5 -3
  54. package/src/utils/paths.js +15 -17
  55. package/src/utils/shell.js +75 -21
  56. package/.env.example +0 -29
  57. package/src/verify.js +0 -57
package/src/tools/web.js CHANGED
@@ -1,9 +1,21 @@
1
- // WebFetch (fetch a page, convert to markdown-ish text, answer a prompt about it with the
2
- // currently selected model) and WebSearch (DuckDuckGo HTML endpoint with a Bing fallback).
1
+ // WebFetch (fetch a page, convert to markdown-ish text, answer a prompt about it with the currently selected model)
2
+ // and WebSearch (the models' own search through the gateway, see searchWithModel; scraping DuckDuckGo or Bing only
3
+ // as the last resort).
3
4
 
4
- import { quickQuery } from '../api.js';
5
+ import { quickQuery, streamMessage } from '../api.js';
6
+ import { localDate } from '../context.js';
7
+ import { renderPage, CHECK_TITLE } from '../browser/render.js';
8
+ import { safeUrl } from '../browser/session.js';
5
9
 
6
10
  const UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36';
11
+ const HEADERS = {
12
+ 'User-Agent': UA,
13
+ Accept: 'text/html,text/markdown,text/plain,application/json;q=0.9,*/*;q=0.8',
14
+ // the languages a browser says it reads: without them a site may pick one by the address (ai.google.dev sent its
15
+ // Portuguese page)
16
+ 'Accept-Language': 'en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7',
17
+ };
18
+ const MAX_REDIRECTS = 20; // as browsers
7
19
  const cache = new Map(); // url -> {at, text, status, bytes}; only successful responses
8
20
 
9
21
  // Limits, in one object so tests can shrink them.
@@ -79,8 +91,10 @@ export function htmlToMarkdown(html, baseUrl) {
79
91
  let s = html;
80
92
  const title = /<title[^>]*>([\s\S]*?)<\/title>/i.exec(s)?.[1];
81
93
  s = s.replace(/<!--[\s\S]*?-->/g, '')
82
- .replace(/<(script|style|noscript|svg|iframe|template|head)[\s\S]*?<\/\1>/gi, '')
83
- .replace(/<(nav|footer)[\s\S]*?<\/\1>/gi, '');
94
+ // the name ends where the tag's does: <header>, <navbar-menu>, <style-guide> are other elements (taken for <head>,
95
+ // <nav>, <style>, they ran on to a later closing tag and took the page's text with them)
96
+ .replace(/<(script|style|noscript|svg|iframe|template|head)(?=[\s>/])[\s\S]*?<\/\1\s*>/gi, '')
97
+ .replace(/<(nav|footer)(?=[\s>/])[\s\S]*?<\/\1\s*>/gi, '');
84
98
  const abs = (href) => { try { return new URL(decodeEntities(href), baseUrl).href; } catch { return href; } };
85
99
  s = s.replace(/<pre[^>]*>([\s\S]*?)<\/pre>/gi, (m, code) => `\n\`\`\`\n${decodeEntities(code.replace(/<[^>]+>/g, ''))}\n\`\`\`\n`)
86
100
  .replace(/<h([1-6])[^>]*>([\s\S]*?)<\/h\1>/gi, (m, n, t) => `\n\n${'#'.repeat(+n)} ${t.replace(/<[^>]+>/g, '').trim()}\n\n`)
@@ -104,9 +118,62 @@ export function htmlToMarkdown(html, baseUrl) {
104
118
  return (title ? `# ${decodeEntities(title.trim())}\n\n` : '') + s;
105
119
  }
106
120
 
107
- async function fetchText(url, signal) {
108
- const hit = cache.get(url);
109
- if (hit && Date.now() - hit.at < webLimits.cacheMs) return hit;
121
+ // The cookies of one fetch, kept across its redirects as a browser keeps them (for their host or domain, path,
122
+ // https only when secure, until they expire). Redirects followed without them can go round for good: ai.google.dev
123
+ // sends a visitor to a sign-in check that sets a cookie and sends it back, and without the cookie it starts again
124
+ // ("redirect count exceeded").
125
+ export class CookieJar {
126
+ constructor() { this.cookies = []; }
127
+
128
+ store(url, setCookies) {
129
+ const u = new URL(url);
130
+ const host = u.hostname.toLowerCase();
131
+ for (const line of setCookies) {
132
+ const [pair, ...attrs] = line.split(';');
133
+ const eq = pair.indexOf('=');
134
+ if (eq <= 0) continue;
135
+ const cookie = { name: pair.slice(0, eq).trim(), value: pair.slice(eq + 1).trim(), domain: host, hostOnly: true, path: null, secure: false, expires: null };
136
+ for (const attr of attrs) {
137
+ const i = attr.indexOf('=');
138
+ const key = (i < 0 ? attr : attr.slice(0, i)).trim().toLowerCase();
139
+ const val = i < 0 ? '' : attr.slice(i + 1).trim();
140
+ if (key === 'domain' && val) { cookie.domain = val.replace(/^\./, '').toLowerCase(); cookie.hostOnly = false; }
141
+ else if (key === 'path' && val.startsWith('/')) cookie.path = val;
142
+ else if (key === 'secure') cookie.secure = true;
143
+ else if (key === 'max-age' && /^-?\d+$/.test(val)) cookie.expires = Date.now() + Number(val) * 1000;
144
+ else if (key === 'expires' && cookie.expires === null && !Number.isNaN(Date.parse(val))) cookie.expires = Date.parse(val);
145
+ }
146
+ // not for another site, nor for a whole top-level domain (Domain=com)
147
+ if (!cookie.hostOnly && (!cookie.domain.includes('.') || (host !== cookie.domain && !host.endsWith(`.${cookie.domain}`)))) continue;
148
+ cookie.path ??= u.pathname.lastIndexOf('/') > 0 ? u.pathname.slice(0, u.pathname.lastIndexOf('/')) : '/';
149
+ this.cookies = this.cookies.filter((c) => !(c.name === cookie.name && c.domain === cookie.domain && c.path === cookie.path));
150
+ if (cookie.expires === null || cookie.expires > Date.now()) this.cookies.push(cookie);
151
+ }
152
+ }
153
+
154
+ header(url) {
155
+ const u = new URL(url);
156
+ const host = u.hostname.toLowerCase();
157
+ const now = Date.now();
158
+ return this.cookies
159
+ .filter((c) => (c.hostOnly ? host === c.domain : host === c.domain || host.endsWith(`.${c.domain}`))
160
+ && (u.pathname === c.path || u.pathname.startsWith(c.path.endsWith('/') ? c.path : `${c.path}/`))
161
+ && (!c.secure || u.protocol === 'https:')
162
+ && (c.expires === null || c.expires > now))
163
+ .sort((a, b) => b.path.length - a.path.length)
164
+ .map((c) => `${c.name}=${c.value}`)
165
+ .join('; ');
166
+ }
167
+ }
168
+
169
+ // The text of a page without its title line and blanks: how much it shows.
170
+ const shownChars = (text) => text.replace(/^# .*\n?/, '').replace(/\s+/g, '').length;
171
+ // A page that its scripts fill in: an empty element they mount the app into, or a note asking for JavaScript.
172
+ const APP_SHELL = /<(div|main|section)\b[^>]*\bid\s*=\s*["']?(?:root|app|__next|__nuxt|svelte|q-app)["']?[^>]*>\s*<\/\1>|<app-root\b[^>]*>\s*<\/app-root>|<noscript[^>]*>[\s\S]{0,500}?(?:enable|requires?|needs?|turn on)\b[\s\S]{0,60}?javascript|<noscript[^>]*>[\s\S]{0,300}?(?:启用|开启|需要)\s*javascript/i;
173
+
174
+ // A plain request, its redirects followed with their cookies: {status, statusText, text, html, scripts, check,
175
+ // binary, bytes, finalUrl, type}. `check`: a browser check page (Cloudflare's "Just a moment...").
176
+ async function fetchPlain(url, signal) {
110
177
  const ctrl = new AbortController();
111
178
  // A timeout must be reported as one, and must not look like the user's interrupt.
112
179
  let timedOut = false;
@@ -114,21 +181,38 @@ async function fetchText(url, signal) {
114
181
  const onAbort = () => ctrl.abort();
115
182
  if (signal?.aborted) ctrl.abort(); else signal?.addEventListener('abort', onAbort, { once: true });
116
183
  try {
117
- const res = await fetch(url, { headers: { 'User-Agent': UA, Accept: 'text/html,text/markdown,text/plain,application/json;q=0.9,*/*;q=0.8' }, redirect: 'follow', signal: ctrl.signal });
118
- const buf = await readCapped(res, webLimits.maxBodyBytes);
119
- const type = res.headers.get('content-type') || '';
120
- const base = { at: Date.now(), status: res.status, statusText: res.statusText, bytes: buf.length, finalUrl: res.url, type };
121
- // Binary content (a PDF, an image, an archive) is not shown as text.
122
- if (BINARY_TYPE.test(type) || buf.subarray(0, 8000).includes(0)) return { ...base, text: '', binary: true };
123
- let text = decodeBody(buf, type);
124
- if (/html/i.test(type) || /^\s*<(!doctype|html)/i.test(text)) text = htmlToMarkdown(text, res.url);
125
- const r = { ...base, text };
126
- // Only a successful page is remembered: a 503 or a 404 must not be served for the next 15 minutes
127
- // after the server has recovered.
128
- if (res.ok) remember(url, r);
129
- return r;
184
+ const jar = new CookieJar();
185
+ let current = url;
186
+ for (let hops = 0; ; hops++) {
187
+ const cookie = jar.header(current);
188
+ const res = await fetch(current, { headers: cookie ? { ...HEADERS, Cookie: cookie } : HEADERS, redirect: 'manual', signal: ctrl.signal });
189
+ jar.store(current, res.headers.getSetCookie?.() ?? []);
190
+ const location = res.status >= 300 && res.status < 400 ? res.headers.get('location') : null;
191
+ if (location) {
192
+ try { await res.body?.cancel(); } catch { /* done */ }
193
+ const next = new URL(location, current).href;
194
+ if (hops >= MAX_REDIRECTS) throw Object.assign(new Error(`too many redirects (more than ${MAX_REDIRECTS}; they go round between ${safeUrl(current)} and ${safeUrl(next)})`), { code: 'TOO_MANY_REDIRECTS' });
195
+ current = next;
196
+ continue;
197
+ }
198
+ const buf = await readCapped(res, webLimits.maxBodyBytes);
199
+ const type = res.headers.get('content-type') || '';
200
+ const base = { at: Date.now(), status: res.status, statusText: res.statusText, bytes: buf.length, finalUrl: current, type };
201
+ // Binary content (a PDF, an image, an archive) is not shown as text.
202
+ if (BINARY_TYPE.test(type) || buf.subarray(0, 8000).includes(0)) return { ...base, text: '', binary: true };
203
+ const body = decodeBody(buf, type);
204
+ const html = /html/i.test(type) || /^\s*<(!doctype|html)/i.test(body);
205
+ const title = html ? decodeEntities(/<title[^>]*>([\s\S]*?)<\/title>/i.exec(body)?.[1]?.trim() || '') : '';
206
+ return {
207
+ ...base, html, title,
208
+ text: html ? htmlToMarkdown(body, current) : body,
209
+ scripts: html && /<script\b/i.test(body),
210
+ shell: html && APP_SHELL.test(body),
211
+ check: res.headers.get('cf-mitigated') === 'challenge' || (html && CHECK_TITLE.test(title)),
212
+ };
213
+ }
130
214
  } catch (e) {
131
- if (timedOut && !signal?.aborted) throw new Error(`timed out after ${Number((webLimits.timeoutMs / 1000).toFixed(1))}s`);
215
+ if (timedOut && !signal?.aborted) throw Object.assign(new Error(`timed out after ${Number((webLimits.timeoutMs / 1000).toFixed(1))}s`), { code: 'TIMEOUT' });
132
216
  throw e;
133
217
  } finally {
134
218
  clearTimeout(timer);
@@ -136,6 +220,65 @@ async function fetchText(url, signal) {
136
220
  }
137
221
  }
138
222
 
223
+ // Why a page that a plain request got is opened in a headless browser too, or null: a browser check page, a server
224
+ // that refuses what is not a browser (403 "Access Denied", 429, 503), or a page whose text its scripts write (an
225
+ // app's empty shell, or next to no text at all with scripts; not a small page that has a script, as example.com).
226
+ function browserReason(page) {
227
+ if (page.binary) return null;
228
+ if (page.check) return 'check';
229
+ if ([403, 429, 503].includes(page.status)) return 'refused';
230
+ if (page.html && page.status < 300 && page.scripts) {
231
+ const shown = shownChars(page.text);
232
+ if (shown < 50 || (page.shell && shown < 1000)) return 'script';
233
+ }
234
+ return null;
235
+ }
236
+
237
+ // Whether a request that failed may work in a browser: redirects that go round, a connection reset or refused at
238
+ // its TLS handshake (servers that tell a browser by it), a name or route the browser's proxy settings reach. Not
239
+ // when nothing listens there, nor after the request took its whole time already.
240
+ const browserMayOpen = (err) => !['ECONNREFUSED', 'TIMEOUT'].includes(err?.code || err?.cause?.code);
241
+
242
+ // A page for WebFetch: a plain request first (fast and cheap), and the headless browser (browser/render.js) when
243
+ // that does not get the page (see browserReason). `rendered`: the browser's page; `blocked`: a page the browser did
244
+ // not get past either (a check that wants a person, or next to nothing shown after a refusal).
245
+ async function fetchPage(url, signal) {
246
+ const hit = cache.get(url);
247
+ if (hit && Date.now() - hit.at < webLimits.cacheMs) return hit;
248
+ let plain = null;
249
+ let failure = null;
250
+ try { plain = await fetchPlain(url, signal); } catch (e) {
251
+ if (signal?.aborted) throw e;
252
+ failure = e;
253
+ }
254
+ const web = /^https?:$/.test(new URL(url).protocol);
255
+ const why = !web ? null : plain ? browserReason(plain) : browserMayOpen(failure) ? 'failed' : null;
256
+ let page = plain;
257
+ if (why) {
258
+ let rendered = null;
259
+ try { rendered = await renderPage(url, { signal }); } catch (e) {
260
+ if (signal?.aborted) throw e;
261
+ if (!plain) throw Object.assign(new Error(`${failure.cause?.message || failure.message}; a headless browser could not open it either (${e.message})`), { code: failure.code });
262
+ }
263
+ if (rendered) {
264
+ const text = htmlToMarkdown(rendered.html, rendered.finalUrl);
265
+ const r = {
266
+ at: Date.now(), status: rendered.status, statusText: rendered.statusText, bytes: Buffer.byteLength(rendered.html),
267
+ finalUrl: rendered.finalUrl, type: 'text/html', html: true, title: rendered.title, text, rendered: true,
268
+ refusedStatus: plain && why !== 'script' ? plain.status : null,
269
+ };
270
+ if (rendered.challenge) page = { ...r, blocked: 'check' };
271
+ else if ((why === 'check' || why === 'refused') && r.status < 400 && shownChars(text) < 200) page = { ...r, blocked: 'empty' };
272
+ else if (why !== 'script' || shownChars(text) > shownChars(plain.text)) page = r;
273
+ }
274
+ }
275
+ if (!page) throw failure; // nothing listens there, or it took the whole time already
276
+ // Only a successful page is remembered: a 503 or a 404 must not be served for the next 15 minutes after the
277
+ // server has recovered.
278
+ if (page.status >= 200 && page.status < 300 && !page.binary && !page.blocked) remember(url, page);
279
+ return page;
280
+ }
281
+
139
282
  export function makeWebFetchTool(config) {
140
283
  return {
141
284
  name: 'WebFetch',
@@ -165,13 +308,24 @@ Usage notes:
165
308
  let url;
166
309
  try { url = new URL(input.url); } catch { return { isError: true, content: `Invalid URL: ${input.url}` }; }
167
310
  let page;
168
- try { page = await fetchText(url.href, ctx.signal); } catch (e) {
311
+ try { page = await fetchPage(url.href, ctx.signal); } catch (e) {
169
312
  if (ctx.signal?.aborted) throw e;
170
313
  return { isError: true, content: `Failed to fetch ${url.href}: ${e.cause?.message || e.message}` };
171
314
  }
172
315
  const size = page.bytes > 1024 ? `${(page.bytes / 1024).toFixed(1)}KB` : `${page.bytes}B`;
173
- const display = { summary: `Received ${size} (${page.status} ${page.statusText || ''})`.trim() };
174
- if (page.status >= 400) return { isError: true, content: `HTTP ${page.status} ${page.statusText} fetching ${url.href}\n\n${page.text.slice(0, 2000)}`, display };
316
+ const display = { summary: `Received ${size} (${`${page.status} ${page.statusText || ''}`.trim()}${page.rendered ? ', in a headless browser' : ''})` };
317
+ const useBrowser = 'Open it with the Browser tool: in the user\'s browser, which may be logged in or past the check already, or with browser: "own", where the user can pass the check if it asks.';
318
+ if (page.blocked === 'check') {
319
+ return { isError: true, content: `${url.href} shows a browser check ("${page.title || 'Just a moment...'}") that a headless browser does not get past: it wants a person. ${useBrowser}`, display };
320
+ }
321
+ if (page.blocked === 'empty') {
322
+ const ended = page.finalUrl && page.finalUrl !== url.href ? ` (it ended at ${safeUrl(page.finalUrl)})` : '';
323
+ return { isError: true, content: `${url.href} turned a plain request away (HTTP ${page.refusedStatus}) and showed next to nothing in a headless browser either${ended}: it may want a login or a check by a person. ${useBrowser}\n\n${page.text.slice(0, 1000)}`, display };
324
+ }
325
+ if (page.status >= 400) {
326
+ const hint = [401, 403, 429, 503].includes(page.status) ? `\n\n(${page.rendered ? 'A headless browser got this too. ' : ''}If the page opens in a browser for the user, with a login or a check, use the Browser tool.)` : '';
327
+ return { isError: true, content: `HTTP ${page.status} ${page.statusText} fetching ${url.href}${hint}\n\n${page.text.slice(0, 2000)}`, display };
328
+ }
175
329
  if (page.binary) {
176
330
  return { isError: true, content: `${page.finalUrl || url.href} is not text (${page.type || 'binary data'}, ${size}), so WebFetch cannot read it. If you need the file, download it with curl in Bash.`, display };
177
331
  }
@@ -184,18 +338,18 @@ Usage notes:
184
338
  const answer = await quickQuery(config, {
185
339
  model: config.model,
186
340
  system: 'You extract information from web pages. Answer only from the provided content. Be complete and precise: include every relevant detail, exact quotes, numbers and code. Keep code blocks intact.',
187
- prompt: `Web page content from ${page.finalUrl || url.href}:\n---\n${content}\n---\n\n${input.prompt || 'Summarize this page, keeping all important details, code and numbers.'}\n\nRespond based only on the content above.`,
188
- maxTokens: 16_000,
189
- signal: ctx.signal,
190
- // Nobody is told about a pause that happens inside a tool call, so the summary is skipped
191
- // instead (the page text below is returned as it is) and the main agent does the waiting.
192
- waitForRateLimit: false,
193
- });
194
- return { content: answer || content.slice(0, 50_000), display };
341
+ prompt: `Web page content from ${page.finalUrl || url.href}:\n---\n${content}\n---\n\n${input.prompt || 'Summarize this page, keeping all important details, code and numbers.'}\n\nRespond based only on the content above.`,
342
+ maxTokens: 16_000,
343
+ signal: ctx.signal,
344
+ // Nobody is told about a pause that happens inside a tool call, so the summary is skipped
345
+ // instead (the page text below is returned as it is) and the main agent does the waiting.
346
+ waitForRateLimit: false,
347
+ });
348
+ if (answer) return { content: answer, display };
195
349
  } catch (e) {
196
350
  if (ctx.signal?.aborted) throw e;
197
- return { content: content.slice(0, 100_000), display };
198
351
  }
352
+ return { content: content.slice(0, 100_000), display };
199
353
  },
200
354
  };
201
355
  }
@@ -247,14 +401,111 @@ async function searchBing(query, signal) {
247
401
  return results;
248
402
  }
249
403
 
404
+ // ---- WebSearch through the gateway
405
+ //
406
+ // The search runs where the selected model runs: a request with the server-side search tool (Anthropic's web_search;
407
+ // the gateway gives GPT models Codex's), which searches, reads the results and reports what they say, each statement
408
+ // marked with its source. Scraping search engines' pages from here, which this tool used to do, gets their bot pages
409
+ // (DuckDuckGo: 202), or Bing's results for the first word of the query only (2026-10-27: "run iOS simulator on
410
+ // Windows 2026 without Mac" gave ten dictionary entries for "run"): that is the last resort now.
411
+
412
+ export const searchLimits = { timeoutMs: 90_000, maxUses: 5, maxTextChars: 8000, maxResults: 40 };
413
+
414
+ const searchSystem = (today) => `You run web searches for another AI agent and report what they found. Search for the query (search again with other words when the first results miss it), then write what the results say that answers it: facts, versions, numbers, dates and names exactly as the pages give them. Do not answer from your own knowledge; when the results do not answer the query, say so plainly. Be brief: at most about 300 words, no preamble. Today's date is ${today}.`;
415
+
416
+ const hostOf = (u) => { try { return new URL(u).hostname; } catch { return ''; } };
417
+ const domainMatch = (host, d) => host === d || host.endsWith(`.${String(d).replace(/^\.+/, '')}`);
418
+
419
+ // Whether a result's URL passes the call's allowed_domains / blocked_domains.
420
+ function domainFilter(input) {
421
+ const allowed = (input.allowed_domains || []).map((d) => String(d).toLowerCase());
422
+ const blocked = (input.blocked_domains || []).map((d) => String(d).toLowerCase());
423
+ return (url) => {
424
+ const host = hostOf(url).toLowerCase();
425
+ if (!host) return false;
426
+ if (allowed.length && !allowed.some((d) => domainMatch(host, d))) return false;
427
+ return !blocked.some((d) => domainMatch(host, d));
428
+ };
429
+ }
430
+
431
+ // What a search request brought back: {results: [{url, title, age}], text, errors, queries}. Anthropic's search
432
+ // gives its results as web_search_tool_result blocks (their text is encrypted: what the pages say comes through the
433
+ // answer, whose statements carry citations, here marked [n] after the result they come from); Codex's, through the
434
+ // gateway, as links in the answer. `keep(url)`: whether a result may be shown.
435
+ export function readSearchReply(blocks, keep = () => true) {
436
+ const results = [];
437
+ const index = new Map();
438
+ const add = (url, title, age) => {
439
+ if (!/^https?:\/\//i.test(url || '') || !keep(url)) return -1;
440
+ if (!index.has(url)) {
441
+ results.push({ url, title: String(title || '').replace(/\s+/g, ' ').trim(), age: age || '' });
442
+ index.set(url, results.length - 1);
443
+ }
444
+ return index.get(url);
445
+ };
446
+ const errors = [];
447
+ const queries = [];
448
+ let text = '';
449
+ for (const b of blocks) {
450
+ if (b.type === 'server_tool_use' && b.input?.query) queries.push(String(b.input.query));
451
+ else if (b.type === 'web_search_tool_result') {
452
+ if (Array.isArray(b.content)) for (const r of b.content) add(r.url, r.title, r.page_age);
453
+ else if (b.content?.error_code) errors.push(b.content.error_code);
454
+ } else if (b.type === 'text') {
455
+ const cited = [...new Set((b.citations || []).map((c) => add(c.url, c.title)).filter((i) => i >= 0))];
456
+ text += b.text + cited.map((i) => `[${i + 1}]`).join('');
457
+ }
458
+ }
459
+ if (!blocks.some((b) => b.type === 'web_search_tool_result')) {
460
+ for (const m of text.matchAll(/\[([^\]\n]{1,200})\]\((https?:\/\/[^\s)]+)\)/g)) add(m[2], m[1]);
461
+ for (const m of text.matchAll(/https?:\/\/[^\s)\]>"'`]+/g)) add(m[0].replace(/[.,;:]+$/, ''), '');
462
+ }
463
+ return { results, text: text.trim(), errors, queries };
464
+ }
465
+
466
+ // One search request with `model`; throws when it fails (an error status, a timeout).
467
+ async function searchWithModel(config, model, input, signal) {
468
+ const tool = { type: 'web_search_20250305', name: 'web_search', max_uses: searchLimits.maxUses };
469
+ // Anthropic's search takes one of the two lists; the gateway passes neither to GPT. So the prompt says them as
470
+ // well, and the results are filtered here (readSearchReply).
471
+ if (input.allowed_domains?.length) tool.allowed_domains = input.allowed_domains;
472
+ else if (input.blocked_domains?.length) tool.blocked_domains = input.blocked_domains;
473
+ const scope = [
474
+ input.allowed_domains?.length ? `Only use results from: ${input.allowed_domains.join(', ')}.` : '',
475
+ input.blocked_domains?.length ? `Leave out results from: ${input.blocked_domains.join(', ')}.` : '',
476
+ ].filter(Boolean).join(' ');
477
+ const res = await streamMessage(config, {
478
+ model,
479
+ system: searchSystem(localDate()),
480
+ messages: [{ role: 'user', content: `Query: ${input.query}${scope ? `\n\n${scope}` : ''}` }],
481
+ tools: [tool],
482
+ maxTokens: 4000,
483
+ effort: /^gpt-/i.test(model.id) ? 'low' : null, // GPT's default effort thinks for long: a search does not need it
484
+ cacheBucket: 'other',
485
+ cacheMessages: false,
486
+ }, { signal, waitForRateLimit: false });
487
+ return readSearchReply(res.message.content, domainFilter(input));
488
+ }
489
+
490
+ function formatSearch(query, found, model) {
491
+ const { results, text, queries } = found;
492
+ const shown = results.slice(0, searchLimits.maxResults);
493
+ const list = shown.map((r, i) => `${i + 1}. [${(r.title || hostOf(r.url)).replace(/[[\]]/g, '')}](${r.url})${r.age ? ` · ${r.age}` : ''}`).join('\n');
494
+ const ran = queries.length > 1 || (queries.length === 1 && queries[0] !== query) ? ` (searched: ${queries.map((q) => `"${q}"`).join(', ')})` : '';
495
+ const said = text.length > searchLimits.maxTextChars ? `${text.slice(0, searchLimits.maxTextChars)}…` : text;
496
+ const parts = [`Web search results for query: "${query}"${ran}`];
497
+ if (list) parts.push(list);
498
+ if (said) parts.push(`What the results say (summarized by ${model.id}${list ? '; [n] is result n above' : ''}):\n${said}`);
499
+ return parts.join('\n\n');
500
+ }
501
+
250
502
  export const WebSearchTool = {
251
503
  name: 'WebSearch',
252
504
  readOnly: true,
253
- description: `- Allows searching the web and using the results to inform responses
254
- - Provides up-to-date information for current events and recent data
255
- - Returns search results (title, URL, snippet) for the query
256
- - Use this tool for accessing information beyond your knowledge cutoff
257
- - Use WebFetch afterwards to read a promising result in full
505
+ description: `- Searches the web and returns the results (title, URL, age) with a summary of what they say, each statement marked with the result it comes from
506
+ - Use it for current information, documentation, releases, error messages and anything beyond your knowledge cutoff
507
+ - Use WebFetch afterwards to read a result in full (it also reads a single post on X from its x.com URL)
508
+ - allowed_domains limits the search to some sites: ["x.com"] for posts on X (Twitter), ["github.com"] for repositories and issues (gh in Bash gives exact GitHub data when it is installed); blocked_domains leaves sites out
258
509
  - After answering from search results, include a "Sources:" section listing the relevant URLs as markdown links`,
259
510
  input_schema: {
260
511
  type: 'object',
@@ -265,8 +516,29 @@ export const WebSearchTool = {
265
516
  },
266
517
  required: ['query'],
267
518
  },
268
- summarize(input) { return `"${input.query}"`; },
519
+ summarize(input) { return `"${input.query}"${input.allowed_domains?.length ? ` on ${input.allowed_domains.join(', ')}` : ''}`; },
269
520
  async call(input, ctx) {
521
+ const failures = [];
522
+ if (ctx.config) {
523
+ const model = ctx.config.model;
524
+ const timeout = AbortSignal.timeout(searchLimits.timeoutMs);
525
+ try {
526
+ const found = await searchWithModel(ctx.config, model, input, AbortSignal.any([...(ctx.signal ? [ctx.signal] : []), timeout]));
527
+ if (found.results.length || (found.text && !found.errors.length)) {
528
+ return { content: formatSearch(input.query, found, model), display: { summary: `Found ${found.results.length} results` } };
529
+ }
530
+ if (!found.errors.length) {
531
+ // a search that worked and found nothing: so it is (another engine would not do better)
532
+ return { content: `No results found for "${input.query}"${input.allowed_domains?.length ? ` on ${input.allowed_domains.join(', ')}` : ''}.`, display: { summary: 'No results' } };
533
+ }
534
+ failures.push(`${model.id}: ${found.errors.join(', ')}`);
535
+ } catch (e) {
536
+ if (ctx.signal?.aborted) throw e;
537
+ failures.push(`${model.id}: ${timeout.aborted ? `timed out after ${searchLimits.timeoutMs / 1000}s` : (e.message || String(e)).slice(0, 200)}`);
538
+ }
539
+ }
540
+ // The last resort: a search engine's page, scraped.
541
+ const note = failures.length ? `(The search through the gateway failed: ${failures.join('; ')}. These results are scraped from a search engine's page instead and may be off-topic.)\n\n` : '';
270
542
  let results = [];
271
543
  const errors = [];
272
544
  for (const engine of [searchDuckDuckGo, searchBing]) {
@@ -278,14 +550,12 @@ export const WebSearchTool = {
278
550
  errors.push(e.cause?.message || e.message);
279
551
  }
280
552
  }
281
- const host = (u) => { try { return new URL(u).hostname; } catch { return ''; } };
282
- const match = (h, d) => h === d || h.endsWith('.' + d);
283
- if (input.allowed_domains?.length) results = results.filter((r) => input.allowed_domains.some((d) => match(host(r.url), d)));
284
- if (input.blocked_domains?.length) results = results.filter((r) => !input.blocked_domains.some((d) => match(host(r.url), d)));
553
+ const keep = domainFilter(input);
554
+ results = results.filter((r) => keep(r.url));
285
555
  if (!results.length) {
286
- return { isError: !!errors.length, content: errors.length ? `Web search failed: ${errors.join('; ')}` : `No results found for "${input.query}"`, display: { summary: 'No results' } };
556
+ return { isError: Boolean(errors.length || failures.length), content: errors.length || failures.length ? `Web search failed: ${[...failures, ...errors].join('; ')}` : `No results found for "${input.query}"`, display: { summary: 'No results' } };
287
557
  }
288
558
  const text = results.map((r, i) => `${i + 1}. [${r.title}](${r.url})\n ${r.snippet}`).join('\n\n');
289
- return { content: `Web search results for query: "${input.query}"\n\n${text}`, display: { summary: `Found ${results.length} results` } };
559
+ return { content: `${note}Web search results for query: "${input.query}"\n\n${text}`, display: { summary: `Found ${results.length} results` } };
290
560
  },
291
561
  };
package/src/trace.js CHANGED
@@ -470,8 +470,4 @@ export class RuntimeTrace {
470
470
  recent(limit = 20) {
471
471
  return this.recentEvents.slice(-Math.max(1, Math.min(200, Number(limit) || 20)));
472
472
  }
473
-
474
- close() {}
475
473
  }
476
-
477
- export const TRACE_DEFAULT_MAX_BYTES = DEFAULT_MAX_BYTES;
package/src/ui/ansi.js CHANGED
@@ -45,10 +45,8 @@ export const c = {
45
45
  cyan: hex('#56b6c2'),
46
46
  magenta: hex('#c678dd'),
47
47
  gray: hex('#8a8a8a'),
48
- white: hex('#ffffff'),
49
48
  claude: hex('#d77757'), // the orange brand accent
50
49
  permission: hex('#b1b9f9'),
51
- edits: hex('#af87ff'),
52
50
  code: hex('#b1b9f9'),
53
51
  userBg: hex('#373737', true), // the band behind the user's messages (see renderUserMessage)
54
52
  userText: hex('#e4e4e4'),
@@ -117,8 +115,8 @@ export function graphemeWidth(g) {
117
115
  if (g === '\t') return 4;
118
116
  const cp = g.codePointAt(0);
119
117
  let w = codePointWidth(cp);
120
- // Emoji presentation selector or ZWJ sequences render wide.
121
- if (g.length > 1 && /[️‍]/.test(g) && w === 1) w = 2;
118
+ // Emoji presentation selector or ZWJ sequences render wide, and so does a flag (two regional indicators).
119
+ if (g.length > 1 && w === 1 && (/[️‍]/.test(g) || (cp >= 0x1f1e6 && cp <= 0x1f1ff))) w = 2;
122
120
  return w;
123
121
  }
124
122
 
@@ -146,8 +144,47 @@ function tokenize(s) {
146
144
  return tokens;
147
145
  }
148
146
 
147
+ // The SGR state (colours and attributes) after `params` (what is between ESC[ and m), from `s`.
148
+ function sgrApply(s, params) {
149
+ const p = params === '' ? [0] : params.split(';').map(Number);
150
+ for (let i = 0; i < p.length; i++) {
151
+ const n = p[i];
152
+ if (n === 0) s = {};
153
+ else if (n === 1) s.bold = 1; else if (n === 2) s.dim = 2; else if (n === 22) { delete s.bold; delete s.dim; }
154
+ else if (n === 3) s.italic = 3; else if (n === 23) delete s.italic;
155
+ else if (n === 4) s.underline = 4; else if (n === 24) delete s.underline;
156
+ else if (n === 7) s.inverse = 7; else if (n === 27) delete s.inverse;
157
+ else if (n === 9) s.strike = 9; else if (n === 29) delete s.strike;
158
+ else if ((n >= 30 && n <= 37) || (n >= 90 && n <= 97)) s.fg = n; else if (n === 39) delete s.fg;
159
+ else if ((n >= 40 && n <= 47) || (n >= 100 && n <= 107)) s.bg = n; else if (n === 49) delete s.bg;
160
+ else if (n === 38 || n === 48) {
161
+ const key = n === 38 ? 'fg' : 'bg';
162
+ if (p[i + 1] === 5) { s[key] = `${n};5;${p[i + 2]}`; i += 2; }
163
+ else if (p[i + 1] === 2) { s[key] = `${n};2;${p[i + 2]};${p[i + 3]};${p[i + 4]}`; i += 4; }
164
+ }
165
+ }
166
+ return s;
167
+ }
168
+
169
+ // The rows a line was wrapped onto, each one after the first starting in the colours the row before it ended in: the
170
+ // screen resets them at the end of every row, so a bold or coloured span that was wrapped lost them on its next rows.
171
+ function carryStyles(rows) {
172
+ let s = {};
173
+ return rows.map((row, i) => {
174
+ const codes = Object.values(s);
175
+ const out = i && codes.length ? `\x1b[${codes.join(';')}m${row}` : row;
176
+ for (const m of row.matchAll(/\x1b\[([0-9;]*)m/g)) s = sgrApply(s, m[1]);
177
+ return out;
178
+ });
179
+ }
180
+
149
181
  // Hard-wrap a (possibly ANSI colored) single line to the given width. Returns array of lines.
150
182
  export function wrapLine(line, width) {
183
+ const rows = hardWrap(line, width);
184
+ return rows.length > 1 ? carryStyles(rows) : rows;
185
+ }
186
+
187
+ function hardWrap(line, width) {
151
188
  width = Math.max(1, width);
152
189
  if (stringWidth(line) <= width) return [line];
153
190
  const lines = [];
@@ -168,28 +205,73 @@ export function wrapLine(line, width) {
168
205
  return lines;
169
206
  }
170
207
 
171
- // Word-aware wrap for prose; falls back to hard wrap for long words.
208
+ // A run of text with CJK in it: such text has no spaces between its words (see wordWrap).
209
+ const CJK = /[\u1100-\u115f\u2e80-\u303e\u3041-\u33ff\u3400-\u4dbf\u4e00-\u9fff\ua960-\ua97f\uac00-\ud7a3\uf900-\ufaff\ufe10-\ufe19\ufe30-\ufe6f\uff00-\uff60\uffe0-\uffe6]/;
210
+ // What does not start a row (closing punctuation) and what does not end one (opening brackets), as CJK typesetting
211
+ // has it.
212
+ const NO_ROW_START = /^[,。、;:?!)」』】》〉’”…,.;:?!)\]}]$/;
213
+ const NO_ROW_END = /^[(「『【《〈‘“([{]$/;
214
+
215
+ // `word` cut where its first `room` columns end, or before: [head, rest], head '' when no place fits. It is cut only
216
+ // next to a wide character, never inside a run of narrow ones (an English word, a number, a path) nor before
217
+ // closing punctuation; colour codes in front of a character stay with it.
218
+ function cutNearWide(word, room) {
219
+ let at = 0, w = 0, cut = 0, prevEnd = 0, prevWide = false, prev = null;
220
+ for (const tok of tokenize(word)) {
221
+ if (tok.ansi) { at += tok.t.length; continue; }
222
+ const tw = tok.t === '\t' ? 4 : tok.w;
223
+ const wide = tw > 1;
224
+ if (prev !== null && (wide || prevWide) && !NO_ROW_START.test(tok.t) && !NO_ROW_END.test(prev)) cut = prevEnd;
225
+ if (w + tw > room) break;
226
+ w += tw;
227
+ at += tok.t.length;
228
+ prevEnd = at;
229
+ prevWide = wide;
230
+ prev = tok.t;
231
+ }
232
+ return cut ? [word.slice(0, cut), word.slice(cut)] : ['', word];
233
+ }
234
+
235
+ // Word-aware wrap for prose; falls back to hard wrap for long words. A run with CJK in it that does not fit goes on
236
+ // in the rest of the row (see cutNearWide): moved to a row of its own, as an English word is, it left a short ragged
237
+ // row before every such run ("先用 Node 24 " alone, the Chinese after it on the next rows).
172
238
  export function wordWrap(line, width) {
173
239
  width = Math.max(1, width);
174
240
  if (stringWidth(line) <= width) return [line];
175
241
  const words = line.split(/(\s+)/);
176
242
  const lines = [];
177
243
  let cur = '', curW = 0;
178
- for (const word of words) {
244
+ const flush = () => { lines.push(cur); cur = ''; curW = 0; };
245
+ for (let word of words) {
179
246
  if (!word) continue;
180
- const w = stringWidth(word);
247
+ let w = stringWidth(word);
181
248
  if (curW + w <= width) { cur += word; curW += w; continue; }
182
- if (/^\s+$/.test(word)) { lines.push(cur); cur = ''; curW = 0; continue; }
249
+ if (/^\s+$/.test(word)) { flush(); continue; }
250
+ if (CJK.test(word)) {
251
+ while (curW + w > width) {
252
+ const [head, rest] = cutNearWide(word, width - curW);
253
+ if (head) { cur += head; flush(); word = rest; w = stringWidth(word); continue; }
254
+ if (curW > 0) { flush(); continue; }
255
+ // no place to cut on a whole row either (a long run of narrow characters): anywhere
256
+ const parts = hardWrap(word, width);
257
+ lines.push(...parts.slice(0, -1));
258
+ word = parts[parts.length - 1];
259
+ w = stringWidth(word);
260
+ }
261
+ cur += word;
262
+ curW += w;
263
+ continue;
264
+ }
183
265
  if (curW > 0) { lines.push(cur); cur = ''; curW = 0; }
184
266
  if (w > width) {
185
- const parts = wrapLine(word, width);
267
+ const parts = hardWrap(word, width);
186
268
  lines.push(...parts.slice(0, -1));
187
269
  cur = parts[parts.length - 1];
188
270
  curW = stringWidth(cur);
189
271
  } else { cur = word; curW = w; }
190
272
  }
191
273
  lines.push(cur);
192
- return lines;
274
+ return lines.length > 1 ? carryStyles(lines) : lines;
193
275
  }
194
276
 
195
277
  // Cut a (possibly ANSI colored) string to `width` columns, ending in `ellipsis` when it was longer. It reads only as
@@ -233,11 +315,8 @@ export const ESC = {
233
315
  hideCursor: '\x1b[?25l',
234
316
  showCursor: '\x1b[?25h',
235
317
  clearDown: '\x1b[0J',
236
- clearLine: '\x1b[2K',
237
318
  up: (n) => (n > 0 ? `\x1b[${n}A` : ''),
238
- down: (n) => (n > 0 ? `\x1b[${n}B` : ''),
239
319
  right: (n) => (n > 0 ? `\x1b[${n}C` : ''),
240
- col0: '\r',
241
320
  bracketedPasteOn: '\x1b[?2004h',
242
321
  bracketedPasteOff: '\x1b[?2004l',
243
322
  clearScreen: '\x1b[2J\x1b[3J\x1b[H',