@yanzc/claude-pro 0.8.0 → 0.9.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 (57) hide show
  1. package/README.md +342 -318
  2. package/package.json +1 -2
  3. package/src/agent.js +80 -14
  4. package/src/agents.js +3 -2
  5. package/src/api.js +39 -34
  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 +169 -67
  14. package/src/compaction.js +75 -0
  15. package/src/config.js +145 -144
  16. package/src/context.js +45 -18
  17. package/src/filestate.js +3 -2
  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 +7 -63
  27. package/src/ratelimit.js +2 -4
  28. package/src/remote.js +76 -14
  29. package/src/runtime.js +33 -10
  30. package/src/selfcheck.js +3 -3
  31. package/src/session.js +93 -3
  32. package/src/supervisor.js +10 -1
  33. package/src/tools/bash.js +18 -17
  34. package/src/tools/browser.js +365 -0
  35. package/src/tools/code.js +430 -0
  36. package/src/tools/effort.js +3 -4
  37. package/src/tools/files.js +368 -45
  38. package/src/tools/index.js +9 -1
  39. package/src/tools/notebook.js +11 -4
  40. package/src/tools/processes.js +274 -0
  41. package/src/tools/search.js +33 -8
  42. package/src/tools/web.js +316 -46
  43. package/src/trace.js +0 -4
  44. package/src/ui/ansi.js +92 -13
  45. package/src/ui/dialogs.js +16 -54
  46. package/src/ui/editor.js +231 -34
  47. package/src/ui/markdown.js +1 -2
  48. package/src/ui/render.js +1 -2
  49. package/src/ui/repl.js +335 -101
  50. package/src/ui/screen.js +139 -31
  51. package/src/updater.js +135 -165
  52. package/src/utils/clipboard.js +5 -3
  53. package/src/utils/dirs.js +136 -0
  54. package/src/utils/encoding.js +23 -2
  55. package/src/utils/paths.js +15 -17
  56. package/src/utils/shell.js +66 -11
  57. package/.env.example +0 -29
package/src/tools/bash.js CHANGED
@@ -3,7 +3,7 @@
3
3
  import fs from 'node:fs';
4
4
  import os from 'node:os';
5
5
  import path from 'node:path';
6
- import { findShell, killTree, killTreeSync, spawnShell, watchShell } from '../utils/shell.js';
6
+ import { childEnv, findShell, killTree, killTreeSync, spawnShell, watchShell } from '../utils/shell.js';
7
7
  import { stripAnsi } from '../ui/ansi.js';
8
8
  import { OutputDecoder } from '../utils/encoding.js';
9
9
  import { toolResultsDir } from '../session.js';
@@ -12,7 +12,7 @@ const background = new Map(); // id -> {child, command, output, readPos, status,
12
12
  let bgCounter = 0;
13
13
  const PROGRESS_CHARS = 8192; // the end of the output the live view gets while a command runs
14
14
 
15
- function truncateOutput(text, max) {
15
+ export function truncateOutput(text, max) {
16
16
  if (text.length <= max) return text;
17
17
  const head = text.slice(0, Math.floor(max * 0.4));
18
18
  const tail = text.slice(-Math.floor(max * 0.6));
@@ -21,7 +21,7 @@ function truncateOutput(text, max) {
21
21
  }
22
22
 
23
23
  // Keep the full text of truncated output so the model can still get at it.
24
- function saveFullOutput(root, text) {
24
+ export function saveFullOutput(root, text) {
25
25
  try {
26
26
  const dir = toolResultsDir(root);
27
27
  fs.mkdirSync(dir, { recursive: true });
@@ -44,18 +44,11 @@ export function appendOutput(bg, text, max = 5_000_000, keep = 2_000_000) {
44
44
  }
45
45
  }
46
46
 
47
- function childEnv() {
48
- const env = { ...process.env };
49
- // Keep child processes non-interactive and colour free.
50
- Object.assign(env, { GIT_EDITOR: 'true', GIT_PAGER: 'cat', PAGER: 'cat', NO_COLOR: '1', CLAUDE_PRO: '1' });
51
- delete env.FORCE_COLOR;
52
- // What commands run from here start must not believe they are a restartable session of this program.
53
- for (const key of ['CLAUDE_PRO_SUPERVISED', 'CLAUDE_PRO_RESTART_FILE', 'CLAUDE_PRO_RESTARTED']) delete env[key];
54
- return env;
55
- }
47
+ export { childEnv };
56
48
 
57
49
  export function shutdownBackgroundShells() {
58
- for (const bg of background.values()) if (bg.status === 'running') killTreeSync(bg.child); // the program is exiting
50
+ // the program is exiting; `orphans`: a shell that has ended but is still "running" left something holding its output
51
+ for (const bg of background.values()) if (bg.status === 'running') killTreeSync(bg.child, { orphans: true });
59
52
  }
60
53
 
61
54
  export function listBackgroundShells() {
@@ -108,6 +101,9 @@ When you commit (the system prompt says when): run git status, git diff and git
108
101
  const id = `bash_${++bgCounter}`;
109
102
  const bg = { child, command, description: String(input.description || ''), output: '', readPos: 0, status: 'running', exitCode: null, startedAt: Date.now() };
110
103
  background.set(id, bg);
104
+ // the shells that ended stay listed, with what was not read of their output: the oldest go past 50
105
+ const ended = [...background].filter(([, b]) => b.status !== 'running');
106
+ for (const [old] of ended.slice(0, Math.max(0, ended.length - 50))) background.delete(old);
111
107
  // Line by line, UTF-8 or the console code page (GBK here), never cutting a character (see OutputDecoder).
112
108
  for (const stream of [child.stdout, child.stderr]) {
113
109
  const decoder = new OutputDecoder();
@@ -161,15 +157,19 @@ When you commit (the system prompt says when): run git status, git diff and git
161
157
  resolve({ isError, content: text || '(no output)', display: { output: text, exitCode: code } });
162
158
  };
163
159
  // The live view shows the last lines: it gets the end of the output and the line count, not all of it
164
- // stripped again on every chunk (quadratic on a noisy build, with up to 10 MB re-split every frame).
160
+ // stripped again on every chunk (quadratic on a noisy build, with up to 10 MB re-split every frame). The end
161
+ // is kept apart: slicing `output` itself made V8 copy all of it into one string for every chunk, which froze
162
+ // the program for seconds on a 100 MB output.
165
163
  let lines = 0;
166
164
  let droppedHead = false;
165
+ let tail = '';
167
166
  watchShell(child, {
168
167
  onOutput: (text) => {
169
168
  output += text;
169
+ tail = (tail + text).slice(-PROGRESS_CHARS);
170
170
  for (let i = text.indexOf('\n'); i >= 0; i = text.indexOf('\n', i + 1)) lines++;
171
171
  if (output.length > 10_000_000) { output = output.slice(-5_000_000); droppedHead = true; }
172
- ctx.onProgress?.(stripAnsi(output.slice(-PROGRESS_CHARS)), { lines });
172
+ ctx.onProgress?.(stripAnsi(tail), { lines, all: () => stripAnsi(output) });
173
173
  },
174
174
  done: finish,
175
175
  });
@@ -198,7 +198,8 @@ export const BashOutputTool = {
198
198
  const bg = background.get(input.bash_id);
199
199
  if (!bg) return { isError: true, content: `No background shell with id ${input.bash_id}. Known: ${[...background.keys()].join(', ') || 'none'}` };
200
200
  let fresh = bg.output.slice(bg.readPos);
201
- bg.readPos = bg.output.length;
201
+ bg.output = ''; // what was read is not read again (up to 5 MB a shell, kept for good before)
202
+ bg.readPos = 0;
202
203
  if (input.filter) {
203
204
  try {
204
205
  const re = new RegExp(input.filter);
@@ -232,7 +233,7 @@ export const KillShellTool = {
232
233
  if (!bg) return { isError: true, content: `No background shell with id ${input.shell_id}` };
233
234
  if (bg.status !== 'running') return { content: `Shell ${input.shell_id} is not running (status: ${bg.status})` };
234
235
  bg.status = 'killed';
235
- await killTree(bg.child);
236
+ await killTree(bg.child, { orphans: true }); // still running: the shell, or what it left running after it ended
236
237
  return { content: `Successfully killed shell: ${input.shell_id} (${bg.command})` };
237
238
  },
238
239
  };
@@ -0,0 +1,365 @@
1
+ // Browser: drives a real browser through the DevTools protocol (see browser/session.js), with the page shown as
2
+ // its accessibility tree cut down to what can be acted on (browser/snapshot.js). After an action the model gets
3
+ // what changed, not the whole page again, and several actions can go in one call.
4
+
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import { browserSession, BrowserError, CdpError, refId, safeUrl } from '../browser/session.js';
8
+ import { snapshotLines, renderLines, diffLines, renderDiff, findLines } from '../browser/snapshot.js';
9
+ import { CONFIG_DIR } from '../config.js';
10
+ import { resolvePath } from '../utils/paths.js';
11
+
12
+ export const browserToolLimits = { snapshotChars: 10_000, diffLines: 60, diffChars: 5_000, textChars: 30_000, evalChars: 20_000, findMatches: 30 };
13
+
14
+ const ACTIONS = ['tabs', 'open', 'switch', 'navigate', 'back', 'forward', 'reload', 'close', 'snapshot', 'find', 'text', 'click', 'type', 'press', 'hover', 'scroll', 'select', 'upload', 'wait', 'eval', 'screenshot', 'dialog', 'disconnect'];
15
+ // After these the page is another one: it is shown whole. After these it is the same page: what changed is shown.
16
+ // After a step that reads the page (the model chose how to look at it), the page is not shown again at the end.
17
+ const READING = new Set(['find', 'text', 'eval', 'screenshot']);
18
+
19
+ const cut = (s, n) => (s.length > n ? `${s.slice(0, n - 1)}…` : s);
20
+
21
+ // The browser tool is left out when CLAUDE_PRO_BROWSER=off.
22
+ export const browserToolEnabled = (config) => String(config?.env?.CLAUDE_PRO_BROWSER ?? '').trim().toLowerCase() !== 'off';
23
+
24
+ const DESCRIPTION = `Drives a real browser (Edge, Chrome or another Chromium) through its DevTools protocol: the user's own browser, logged in as them, or claude-pro's own (browser: "own"). Use it for pages that need clicks, typing, a login or JavaScript; to read a public page, WebFetch is cheaper.
25
+
26
+ Actions, with their fields:
27
+ - tabs; open (url): a new tab; switch (tab: its id, or words of its title or address); navigate (url), back, forward, reload; close (tab)
28
+ - snapshot: the page's elements, one per line with a ref (e123) to act on; full: true adds the text and the links' addresses; ref: only that part. find (text): the lines that contain it (or /regex/). text (ref): the plain text
29
+ - click (ref, or x and y; double, button), type (text; ref, clear, submit: Enter after), press (key: Enter, Escape, Control+a…), hover (ref), scroll (dy in pixels, ref), select (ref, value) for a <select>, upload (ref, files)
30
+ - wait (text, gone; or ms), eval (script, ref): JavaScript in the page, its value comes back; screenshot (ref, full); dialog (accept, text): answer an alert, confirm or prompt; disconnect
31
+ - steps: [{action, …}, …] runs several actions in one call and stops at the first that fails
32
+ After actions you get what changed in the snapshot (+ added, ~ changed), or the new snapshot when the page changed a lot or is another page. A ref that is gone needs a new snapshot.
33
+
34
+ - The first call connects. The user's browser then asks them to allow remote debugging (once per session, the connection stays): tell them before. When no browser allows it, the error says how to turn it on; or offer browser: "own" (nothing to allow, but sites need a login there once).
35
+ - Work in tabs you opened or the one the user points to: do not read or change their other tabs.
36
+ - Before you publish, send, buy, delete or change settings, ask, unless the user asked for exactly that.`;
37
+
38
+ // The file of a tab's whole snapshot. Named by this process too: tab ids (t1, t2…) start again in every session, so
39
+ // two sessions wrote the same file and one of them read the other's page. Files a day old go.
40
+ let snapshotsSwept = false;
41
+ function snapshotFile(tab, text) {
42
+ const dir = path.join(CONFIG_DIR, 'browser-snapshots');
43
+ try {
44
+ fs.mkdirSync(dir, { recursive: true });
45
+ if (!snapshotsSwept) {
46
+ snapshotsSwept = true;
47
+ for (const name of fs.readdirSync(dir)) {
48
+ const old = path.join(dir, name);
49
+ try { if (Date.now() - fs.statSync(old).mtimeMs > 86_400_000) fs.rmSync(old, { force: true }); } catch { /* gone */ }
50
+ }
51
+ }
52
+ const file = path.join(dir, `${process.pid}-${tab.id}.txt`);
53
+ fs.writeFileSync(file, text);
54
+ return file;
55
+ } catch { return null; }
56
+ }
57
+
58
+ // A snapshot within the size limit; the whole of it in a file when it is longer.
59
+ function capped(tab, lines) {
60
+ const text = renderLines(lines);
61
+ if (!text) return '(nothing to show: the page is empty or still loading)';
62
+ if (text.length <= browserToolLimits.snapshotChars) return text;
63
+ const at = text.lastIndexOf('\n', browserToolLimits.snapshotChars);
64
+ const shown = text.slice(0, at > 0 ? at : browserToolLimits.snapshotChars);
65
+ const rest = text.slice(shown.length).split('\n').filter(Boolean).length;
66
+ const file = snapshotFile(tab, text);
67
+ return `${shown}\n… ${rest} more lines${file ? `: the whole snapshot is in ${file} (Grep it),` : ':'} or narrow it with find (text) or snapshot (ref)`;
68
+ }
69
+
70
+ function cappedText(text, max, what) {
71
+ if (text.length <= max) return text;
72
+ return `${text.slice(0, max)}\n… [${what} cut at ${max} of ${text.length} characters: narrow it with ref]`;
73
+ }
74
+
75
+ const header = (tab) => `${tab.id} ${cut(tab.url || '', 200)}${tab.title ? ` — ${cut(tab.title, 80)}` : ''}`;
76
+
77
+ // The page read once, in the two forms: `view`, what can be acted on (what a snapshot shows), and `all`, with the
78
+ // text and the links' addresses too (what find searches, and what the changes after an action are taken from, so
79
+ // that a message or a counter that changes shows up).
80
+ async function readPage(tab) {
81
+ const trees = await browserSession.trees(tab);
82
+ const title = trees.main?.find((n) => !n.parentId)?.name?.value; // the document's title, before the browser reports it
83
+ if (title) tab.title = title;
84
+ return {
85
+ trees,
86
+ view: snapshotLines(trees, { baseUrl: trees.baseUrl }),
87
+ all: snapshotLines(trees, { full: true, baseUrl: trees.baseUrl }),
88
+ };
89
+ }
90
+
91
+ function remember(tab, page) {
92
+ tab.lines = page.view;
93
+ tab.base = page.all;
94
+ tab.lastUrl = tab.url;
95
+ }
96
+
97
+ // "e14 button "Click me"": a ref with what it was in the last snapshot (without its value and states then, which
98
+ // the action may have changed).
99
+ function named(tab, ref) {
100
+ const line = tab?.lines?.find((l) => l.ref === `e${refId(ref)}`);
101
+ if (!line) return String(ref);
102
+ return `${line.ref} ${cut(line.text.replace(/^- /, '').replace(/ \[[^\]]+\]/g, '').replace(/: [^"\]]*$/, ''), 80)}`;
103
+ }
104
+
105
+ // A tab by id (t3f9a; see BrowserSession.relabel) or by words of its title or address.
106
+ function findTab(spec) {
107
+ const s = browserSession;
108
+ const want = String(spec ?? '').trim();
109
+ if (!want) throw new BrowserError('switch needs tab: an id from tabs, or words of its title or address');
110
+ if (/^t(?:\d+|[0-9a-f]{4,})$/i.test(want)) return s.tab(want);
111
+ const q = want.toLowerCase();
112
+ const hits = [...s.tabs.values()].filter((t) => `${t.title} ${t.url}`.toLowerCase().includes(q));
113
+ if (hits.length === 1) return hits[0];
114
+ if (!hits.length) throw new BrowserError(`no tab's title or address contains ${JSON.stringify(want)}: list them with tabs`);
115
+ throw new BrowserError(`${hits.length} tabs match ${JSON.stringify(want)}: ${hits.slice(0, 8).map((t) => `${t.id} ${cut(t.title || '', 40)} — ${safeUrl(t.url)}`).join('; ')}; pass the id`);
116
+ }
117
+
118
+ async function step(input, ctx) {
119
+ const s = browserSession;
120
+ const a = input.action;
121
+ const need = (field) => {
122
+ if (input[field] === undefined || input[field] === null || input[field] === '') throw new BrowserError(`${a} needs ${field}`);
123
+ return input[field];
124
+ };
125
+ // While an alert, confirm or prompt is open the page runs nothing else: every command would wait for it.
126
+ const current = s.current;
127
+ if (current?.dialog && !['dialog', 'tabs', 'switch', 'open', 'close', 'disconnect'].includes(a)) {
128
+ throw new BrowserError(`a ${current.dialog.type} dialog is open (${JSON.stringify(current.dialog.message)}): answer it first with dialog (accept: true or false${current.dialog.type === 'prompt' ? ', text' : ''})`);
129
+ }
130
+ switch (a) {
131
+ case 'tabs': {
132
+ const list = [...s.tabs.values()];
133
+ return { line: `Tabs in ${s.browser.label} (${list.length}):\n${list.map((t) => ` ${t.id}${t === s.current ? ' [current]' : ''}${t.ours ? ' [yours]' : ''} ${cut(t.title || '(no title)', 60)} — ${safeUrl(t.url)}`).join('\n')}` };
134
+ }
135
+ case 'open': {
136
+ const tab = await s.open(input.url);
137
+ return { line: `Opened ${tab.id}${input.url ? ` at ${cut(String(input.url), 100)}` : ''}.`, report: 'page' };
138
+ }
139
+ case 'switch': {
140
+ const tab = findTab(input.tab);
141
+ await s.select(tab);
142
+ return { line: `Switched to ${tab.id}.`, report: 'page' };
143
+ }
144
+ case 'navigate': await s.navigate(s.tab(), need('url')); return { line: `Went to ${cut(String(input.url), 100)}.`, report: 'page' };
145
+ case 'back': await s.history(s.tab(), -1); return { line: 'Went back.', report: 'page' };
146
+ case 'forward': await s.history(s.tab(), 1); return { line: 'Went forward.', report: 'page' };
147
+ case 'reload': {
148
+ const tab = s.tab();
149
+ tab.loading = true;
150
+ await s.send(tab, 'Page.reload', {});
151
+ return { line: 'Reloaded.', report: 'page' };
152
+ }
153
+ case 'close': {
154
+ const tab = input.tab ? findTab(input.tab) : s.tab();
155
+ await s.closeTab(tab, input.force);
156
+ return { line: `Closed ${tab.id}.` };
157
+ }
158
+ case 'snapshot': {
159
+ const tab = s.tab();
160
+ const page = await readPage(tab);
161
+ remember(tab, page);
162
+ const lines = input.ref || input.full ? snapshotLines(page.trees, { full: Boolean(input.full), root: input.ref ? refId(input.ref) : null, baseUrl: page.trees.baseUrl }) : page.view;
163
+ if (input.ref && !lines.length) throw new BrowserError(`${input.ref} is not on the page (any more): take a snapshot without ref`);
164
+ return { line: `${header(tab)}\n${capped(tab, lines)}`, report: 'shown' };
165
+ }
166
+ case 'find': {
167
+ const tab = s.tab();
168
+ const page = await readPage(tab);
169
+ const r = findLines(page.all, String(need('text')), browserToolLimits.findMatches);
170
+ if (!r.matches) return { line: `Nothing on the page matches ${JSON.stringify(input.text)} (try other words, or text for the page's plain text).` };
171
+ return { line: `${r.matches} line${r.matches === 1 ? '' : 's'} match ${JSON.stringify(input.text)}:\n${r.text}${r.matches > browserToolLimits.findMatches ? `\n… ${r.matches - browserToolLimits.findMatches} more: narrow the words` : ''}` };
172
+ }
173
+ case 'text': {
174
+ const text = await s.text(s.tab(), input.ref);
175
+ return { line: text.trim() ? cappedText(text.trim(), browserToolLimits.textChars, 'the text') : '(no text)' };
176
+ }
177
+ case 'click': {
178
+ const tab = s.tab();
179
+ await s.click(tab, input);
180
+ return { line: `Clicked ${input.ref ? named(tab, input.ref) : `at ${input.x},${input.y}`}${input.double ? ' twice' : ''}.`, report: 'changes' };
181
+ }
182
+ case 'type': {
183
+ const tab = s.tab();
184
+ if (!input.text && !input.clear) need('text');
185
+ await s.type(tab, input);
186
+ const what = input.text ? `Typed ${JSON.stringify(cut(String(input.text), 60))}` : 'Cleared';
187
+ return { line: `${what}${input.ref ? ` ${input.text ? 'into' : ''} ${named(tab, input.ref)}` : ''}${input.submit ? ' and pressed Enter' : ''}.`.replace(/ {2}/g, ' '), report: 'changes' };
188
+ }
189
+ case 'press': await s.press(s.tab(), need('key')); return { line: `Pressed ${input.key}.`, report: 'changes' };
190
+ case 'hover': { const tab = s.tab(); await s.hover(tab, need('ref')); return { line: `Hovering over ${named(tab, input.ref)}.`, report: 'changes' }; }
191
+ case 'scroll': {
192
+ const tab = s.tab();
193
+ await s.scroll(tab, input);
194
+ return { line: input.ref && input.dy === undefined ? `Scrolled ${named(tab, input.ref)} into view.` : `Scrolled ${input.dy ?? 'a screen'}${input.dy !== undefined ? ' px' : ''}${input.ref ? ` in ${named(tab, input.ref)}` : ''}.`, report: 'changes' };
195
+ }
196
+ case 'select': {
197
+ const tab = s.tab();
198
+ const label = await s.selectOption(tab, need('ref'), need('value'));
199
+ return { line: `Selected ${JSON.stringify(label)} in ${named(tab, input.ref)}.`, report: 'changes' };
200
+ }
201
+ case 'upload': {
202
+ const tab = s.tab();
203
+ const files = (Array.isArray(input.files) ? input.files : [need('files')]).map((f) => resolvePath(String(f), ctx.cwd));
204
+ const missing = files.filter((f) => !fs.existsSync(f));
205
+ if (missing.length) throw new BrowserError(`no such file: ${missing.join(', ')}`);
206
+ await s.upload(tab, need('ref'), files);
207
+ return { line: `Gave ${files.length} file${files.length === 1 ? '' : 's'} to ${named(tab, input.ref)}.`, report: 'changes' };
208
+ }
209
+ case 'wait': return { line: `${cut(await s.waitFor(s.tab(), input), 200)}.`, report: 'changes' };
210
+ case 'eval': {
211
+ const value = await s.evaluate(s.tab(), String(need('script')), input.ref);
212
+ return { line: `Result:\n${cappedText(String(value), browserToolLimits.evalChars, 'the result')}` };
213
+ }
214
+ case 'screenshot': {
215
+ const tab = s.tab();
216
+ const data = await s.screenshot(tab, input);
217
+ return { line: `Screenshot of ${tab.id}${input.ref ? ` ${named(tab, input.ref)}` : input.full ? ' (the whole page)' : ''}:`, images: [{ type: 'image', source: { type: 'base64', media_type: 'image/jpeg', data } }] };
218
+ }
219
+ case 'dialog': {
220
+ const tab = s.tab();
221
+ const d = tab.dialog;
222
+ await s.dialog(tab, input);
223
+ return { line: `Answered the ${d?.type || ''} dialog: ${input.accept === false ? 'dismissed' : 'accepted'}.`.replace(/ {2}/g, ' '), report: 'changes' };
224
+ }
225
+ case 'disconnect': {
226
+ const own = s.browser?.own;
227
+ s.close();
228
+ return { line: `Disconnected (the tabs stay as they are; the next call connects again${own ? '' : ', and the user is asked again to allow it'}).` };
229
+ }
230
+ default:
231
+ throw new BrowserError(`unknown action ${JSON.stringify(a)}: use one of ${ACTIONS.join(', ')}`);
232
+ }
233
+ }
234
+
235
+ // The page after what was done: what changed since the last snapshot, or the page itself.
236
+ async function pageState(tab, kind) {
237
+ const s = browserSession;
238
+ await s.settle(tab);
239
+ if (tab.dialog) return `A ${tab.dialog.type} dialog is open: ${JSON.stringify(tab.dialog.message)}. Answer it with dialog (accept: true or false${tab.dialog.type === 'prompt' ? ', text' : ''}).`;
240
+ const page = await readPage(tab);
241
+ let body = null;
242
+ if (kind === 'changes' && tab.base && tab.lastUrl === tab.url) {
243
+ const d = diffLines(tab.base, page.all);
244
+ if (!d.changed.length && !d.gone.length) body = 'Nothing changed on the page.';
245
+ else {
246
+ const text = renderDiff(d);
247
+ if (d.changed.length <= browserToolLimits.diffLines && text.length <= browserToolLimits.diffChars) body = `Changes:\n${text}`;
248
+ }
249
+ }
250
+ remember(tab, page);
251
+ return `${header(tab)}\n${body ?? capped(tab, page.view)}`;
252
+ }
253
+
254
+ // When the last step read the page (switch, then find): only where the tab is, the page not shown again. It is
255
+ // still recorded, so that the next action shows what it changed instead of the whole page.
256
+ async function quietState(tab, unsettled) {
257
+ if (unsettled) await browserSession.settle(tab);
258
+ if (!tab.dialog) remember(tab, await readPage(tab));
259
+ return header(tab);
260
+ }
261
+
262
+ async function run(input, ctx) {
263
+ const s = browserSession;
264
+ const steps = Array.isArray(input.steps) && input.steps.length ? input.steps : [input];
265
+ if (steps.some((x) => !x || typeof x !== 'object' || !x.action)) {
266
+ return { isError: true, content: 'Each call needs an action (or steps: a list of {action, …}).' };
267
+ }
268
+ if (steps.length === 1 && steps[0].action === 'disconnect' && !s.connected) return { content: 'Not connected to a browser.' };
269
+ const out = [];
270
+ try {
271
+ const target = await s.connect(input.browser || steps.find((x) => x.browser)?.browser, ctx.config?.env, (b) => {
272
+ ctx.onProgress?.(`Waiting for the user to allow remote debugging in ${b.label} ("Allow remote debugging?" → Allow)…`);
273
+ });
274
+ if (target) out.push(`Connected to ${target.label}${target.others?.length ? ` (${target.others.join(', ')} allow${target.others.length === 1 ? 's' : ''} it too: pass browser to use ${target.others.length === 1 ? 'it' : 'one of them'})` : ''}.`);
275
+ } catch (e) {
276
+ if (e?.name === 'AbortError') throw e;
277
+ return { isError: true, content: `Cannot use the browser: ${e.message}` };
278
+ }
279
+ let failed = false;
280
+ let pending = null; // what to show of the page at the end: 'page' | 'changes'
281
+ let unsettled = false; // a step changed the page, and it has not settled since
282
+ let lastRead = false;
283
+ const images = [];
284
+ for (const [i, x] of steps.entries()) {
285
+ const n = steps.length > 1 ? `${i + 1}. ` : '';
286
+ try {
287
+ // what a step started (a page loading, a menu opening) is done before the next step reads or acts on the page
288
+ if (unsettled && s.current) { await s.settle(s.current); unsettled = false; }
289
+ const r = await step(x, ctx);
290
+ out.push(`${n}${r.line}`);
291
+ if (r.images) images.push(...r.images);
292
+ if (r.report === 'page') pending = 'page';
293
+ else if (r.report === 'changes') pending = pending === 'page' ? 'page' : 'changes';
294
+ else if (r.report === 'shown') pending = null; // a snapshot shows the page already
295
+ if (r.report === 'page' || r.report === 'changes') unsettled = true;
296
+ lastRead = READING.has(x.action);
297
+ } catch (e) {
298
+ if (e?.name === 'AbortError') throw e;
299
+ failed = true;
300
+ out.push(`${n}${x.action} failed: ${e instanceof BrowserError || e instanceof CdpError ? e.message : `${e.message}`}`);
301
+ if (i < steps.length - 1) out.push(`(the ${steps.length - i - 1} step${steps.length - i - 1 === 1 ? '' : 's'} after it did not run)`);
302
+ break;
303
+ }
304
+ }
305
+ const tab = s.connected ? s.current : null;
306
+ if (pending && tab) {
307
+ try { out.push(lastRead && !failed ? await quietState(tab, unsettled) : await pageState(tab, pending)); } catch (e) {
308
+ if (e?.name === 'AbortError') throw e;
309
+ out.push(`(the page could not be read: ${e.message})`);
310
+ }
311
+ }
312
+ if (tab && !tab.dialog) await s.release(tab);
313
+ const text = [...s.takeNotes(), ...out].join('\n');
314
+ const last = out.find((l) => /failed:/.test(l)) || out[out.length - 1] || '';
315
+ return {
316
+ content: images.length ? [{ type: 'text', text }, ...images] : text,
317
+ isError: failed,
318
+ display: { summary: cut(last.split('\n')[0], 120) },
319
+ };
320
+ }
321
+
322
+ export function makeBrowserTool() {
323
+ return {
324
+ name: 'Browser',
325
+ description: DESCRIPTION,
326
+ input_schema: {
327
+ type: 'object',
328
+ properties: {
329
+ action: { type: 'string', enum: ACTIONS },
330
+ steps: { type: 'array', items: { type: 'object' }, description: 'Several actions in order, each {action, …its fields}' },
331
+ browser: { type: 'string', description: 'edge, chrome, brave, chromium, own, or a DevTools address' },
332
+ tab: { type: 'string', description: 'A tab id (t3), or words of its title or address' },
333
+ url: { type: 'string' },
334
+ ref: { type: 'string', description: 'An element ref from a snapshot (e123)' },
335
+ text: { type: 'string' },
336
+ key: { type: 'string' },
337
+ value: { type: 'string' },
338
+ script: { type: 'string' },
339
+ files: { type: 'array', items: { type: 'string' } },
340
+ full: { type: 'boolean' },
341
+ clear: { type: 'boolean' },
342
+ submit: { type: 'boolean' },
343
+ double: { type: 'boolean' },
344
+ gone: { type: 'boolean' },
345
+ force: { type: 'boolean' },
346
+ accept: { type: 'boolean' },
347
+ button: { type: 'string', enum: ['left', 'right', 'middle'] },
348
+ x: { type: 'number' },
349
+ y: { type: 'number' },
350
+ dx: { type: 'number' },
351
+ dy: { type: 'number' },
352
+ ms: { type: 'number' },
353
+ timeout: { type: 'number', description: 'For wait, in ms (default 10000)' },
354
+ },
355
+ },
356
+ summarize(input) {
357
+ const one = (x) => [x.action, x.tab, x.ref, x.url ? safeUrl(String(x.url)) : '', x.key, x.text !== undefined ? JSON.stringify(cut(String(x.text), 40)) : '', x.value !== undefined ? JSON.stringify(String(x.value)) : '', x.script ? cut(String(x.script).replace(/\s+/g, ' '), 40) : ''].filter(Boolean).join(' ');
358
+ if (Array.isArray(input.steps) && input.steps.length) return `${input.steps.length} steps: ${input.steps.map((x) => one(x || {})).join(', ')}`;
359
+ return one(input);
360
+ },
361
+ async call(input, ctx) {
362
+ return browserSession.run(ctx.signal, () => run(input, ctx));
363
+ },
364
+ };
365
+ }