@0perator/operator 0.1.360-next.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +1 -1
  2. package/dist/autonomy/delegate-mode.js +159 -0
  3. package/dist/autonomy/delegate.js +1 -1
  4. package/dist/autonomy/session-factory.js +8 -2
  5. package/dist/background/index.js +26 -2
  6. package/dist/background/resume.js +125 -0
  7. package/dist/browser/engine.js +163 -0
  8. package/dist/browser/session.js +172 -134
  9. package/dist/cli.js +261 -70
  10. package/dist/config/settings.js +28 -7
  11. package/dist/config/skills-index.js +4 -0
  12. package/dist/engine/agent.js +1 -1
  13. package/dist/engine/aurora.js +22 -13
  14. package/dist/engine/compaction.js +1 -1
  15. package/dist/engine/moa.js +2 -1
  16. package/dist/engine/selfheal.js +1 -1
  17. package/dist/engine/speed-compaction.js +37 -0
  18. package/dist/engine/toolcalls.js +6 -6
  19. package/dist/gateway-cli.js +14 -5
  20. package/dist/index.js +3 -0
  21. package/dist/mcp/phone-server.js +30 -0
  22. package/dist/permissions/index.js +33 -17
  23. package/dist/permissions/signature.js +5 -0
  24. package/dist/phone-cli.js +65 -0
  25. package/dist/remote/host.js +31 -2
  26. package/dist/router/models.js +49 -25
  27. package/dist/selfimprove/index.js +1 -1
  28. package/dist/services/preflight.js +31 -8
  29. package/dist/session.js +96 -14
  30. package/dist/tools/deferred.js +1 -0
  31. package/dist/tools/device/android.js +227 -0
  32. package/dist/tools/device/classify.js +127 -0
  33. package/dist/tools/device/deps.js +69 -0
  34. package/dist/tools/device/desktop.js +82 -0
  35. package/dist/tools/device/harness.js +262 -0
  36. package/dist/tools/device/iphone.js +206 -0
  37. package/dist/tools/device/mirroring-jxa.js +146 -0
  38. package/dist/tools/device/setup.js +90 -0
  39. package/dist/tools/device/tools.js +70 -0
  40. package/dist/tools/device/types.js +19 -0
  41. package/dist/tools/registry.js +242 -48
  42. package/dist/tools/vision-media.js +162 -0
  43. package/dist/ui/App.js +4 -3
  44. package/dist/ui/ApprovalPrompt.js +10 -4
  45. package/dist/ui/BgPanel.js +2 -2
  46. package/dist/ui/UpdatePrompt.js +40 -0
  47. package/dist/ui/modelPicker.js +26 -8
  48. package/dist/ui/slashCommands.js +1 -0
  49. package/dist/update-check.js +134 -0
  50. package/dist/update.js +82 -13
  51. package/dist/util/slash.js +2 -2
  52. package/package.json +4 -2
  53. package/src/tools/device/NOTICE +37 -0
  54. package/dist/browser/cdp.js +0 -271
@@ -1,9 +1,13 @@
1
1
  // Persistent browser session + the two registry surfaces for HV3-02.
2
- // ONE headless Chrome per Operator session (mirrors src/tools/shell-session.ts): pages, cookies and
3
- // scroll state persist across tool calls; an idle browser decommissions on TTL; a dead Chrome
4
- // respawns transparently. Tools are split READ vs ACT so the registry-derived permission policy
5
- // (0.1.226) can let gated/plan mode READ pages freely while every page MUTATION stays gated.
6
- import { CdpConnection, launchChrome, checkNavigationUrl, evalResultToText, fillScript, BROWSER_CONSTANTS, } from "./cdp.js";
2
+ // ONE headless browser per Operator session (mirrors src/tools/shell-session.ts): pages and cookies persist across
3
+ // tool calls; an idle browser decommissions on TTL; a dead browser relaunches transparently. The engine is Playwright
4
+ // (./engine.ts) with a throwaway profile, so nothing outlives the session unless KODE_BROWSER_PROFILE=persistent.
5
+ // Tools are split READ vs ACT so the registry-derived permission policy (0.1.226) can let gated/plan mode READ pages
6
+ // freely while every page MUTATION stays gated.
7
+ import { launchBrowser, checkNavigationUrl, valueToText, shortError, BROWSER_CONSTANTS } from "./engine.js";
8
+ /** A full-page capture stops here (CSS px): past it Chrome's capture gets slow and the PNG heavy. */
9
+ export const MAX_PAGE_PX = 16_384;
10
+ const { ACTION_TIMEOUT_MS, NAV_TIMEOUT_MS, IDLE_TTL_MS } = BROWSER_CONSTANTS;
7
11
  async function nodeImport(id) {
8
12
  const g = globalThis;
9
13
  try {
@@ -14,177 +18,211 @@ async function nodeImport(id) {
14
18
  catch { /* dynamic */ }
15
19
  return import(id);
16
20
  }
21
+ /** `<cache>/browser/<kind>-<ms>` (no extension), or the OS temp dir when the Operator home is not writable. */
22
+ async function shotBase(kind) {
23
+ const { mkdirSync } = await nodeImport("node:fs");
24
+ try {
25
+ const { operatorPath } = await nodeImport("../config/home.js");
26
+ const dir = operatorPath("cache", "browser");
27
+ mkdirSync(dir, { recursive: true });
28
+ return `${dir}/${kind}-${Date.now()}`;
29
+ }
30
+ catch {
31
+ const os = await nodeImport("node:os");
32
+ return `${os.tmpdir()}/kode-${kind}-${Date.now()}`;
33
+ }
34
+ }
35
+ /** Chrome's network error for a failed load (net::ERR_NAME_NOT_RESOLVED, …), else Playwright's first line. */
36
+ function loadErrorOf(e) {
37
+ const msg = e?.message ?? String(e);
38
+ return /net::[A-Z_]+/.exec(msg)?.[0] ?? shortError(e);
39
+ }
17
40
  class BrowserSession {
18
- conn = null;
19
- proc = null;
41
+ launched = null;
20
42
  tabs = [];
21
43
  active = -1;
22
44
  lastUsed = 0;
23
45
  async ensure() {
24
46
  const now = Date.now();
25
- const alive = this.conn && this.proc && this.proc.exitCode == null &&
26
- now - this.lastUsed < BROWSER_CONSTANTS.IDLE_TTL_MS;
27
- if (alive) {
47
+ if (this.launched && now - this.lastUsed < IDLE_TTL_MS) {
28
48
  this.lastUsed = now;
29
- return this.conn;
49
+ return this.launched;
30
50
  }
31
- await this.dispose(); // TTL expiry or dead child: rebuild clean (cookies live in the $KODE_HOME/browser profile, so a relaunch is cheap for state)
32
- const { proc, wsUrl } = await launchChrome();
33
- const conn = new CdpConnection(wsUrl);
34
- await conn.connect();
35
- this.proc = proc;
36
- this.conn = conn;
51
+ await this.dispose(); // TTL expiry: rebuild clean
52
+ this.launched = await launchBrowser();
37
53
  this.tabs = [];
38
54
  this.active = -1;
39
55
  this.lastUsed = Date.now();
40
- return conn;
56
+ return this.launched;
41
57
  }
42
- /** Attach a fresh tab (target) and make it active. */
43
- async newTab(conn, url) {
44
- const created = await conn.send("Target.createTarget", { url: "about:blank" });
45
- const attached = await conn.send("Target.attachToTarget", { targetId: created.targetId, flatten: true });
46
- const tab = { targetId: created.targetId, sessionId: attached.sessionId, url: "about:blank" };
47
- this.tabs.push(tab);
58
+ /** Open a fresh tab and make it active. */
59
+ async newTab(url) {
60
+ const b = await this.ensure();
61
+ const page = await b.context.newPage();
62
+ this.tabs.push(page);
48
63
  this.active = this.tabs.length - 1;
49
- await conn.send("Page.enable", {}, tab.sessionId);
50
- await conn.send("Runtime.enable", {}, tab.sessionId);
51
64
  if (url !== "about:blank")
52
- await this.navigate(conn, tab, url);
53
- return tab;
65
+ await this.navigate(page, url);
66
+ return page;
54
67
  }
55
68
  tab() {
69
+ this.tabs = this.tabs.filter((t) => !t.isClosed());
70
+ if (this.active >= this.tabs.length)
71
+ this.active = this.tabs.length - 1;
56
72
  if (this.active < 0 || !this.tabs[this.active])
57
73
  throw new Error("browser: no active tab — call open first");
58
74
  return this.tabs[this.active];
59
75
  }
60
- async navigate(conn, tab, url) {
76
+ async navigate(page, url) {
61
77
  const blocked = checkNavigationUrl(url);
62
78
  if (blocked)
63
79
  throw new Error(blocked);
64
- const loadFired = conn.once("Page.loadEventFired"); // subscribe BEFORE navigate so we never miss it
65
- await conn.send("Page.navigate", { url }, tab.sessionId);
66
- const settled = await Promise.race([
67
- loadFired.then(() => "load"),
68
- new Promise((res) => setTimeout(() => res("timeout"), BROWSER_CONSTANTS.NAV_TIMEOUT_MS)),
69
- ]);
70
- // load fired (or timed out) — give SPAs a beat to paint, then confirm readyState
71
- await new Promise((r) => setTimeout(r, 300));
72
80
  try {
73
- const rs = await conn.send("Runtime.evaluate", { expression: "document.readyState", returnByValue: true }, tab.sessionId);
74
- tab.url = (await conn.send("Runtime.evaluate", { expression: "location.href", returnByValue: true }, tab.sessionId))?.result?.value ?? url;
75
- void settled;
76
- void rs;
81
+ const res = await page.goto(url, { waitUntil: "load", timeout: NAV_TIMEOUT_MS });
82
+ return { status: res?.status() || undefined };
77
83
  }
78
- catch {
79
- tab.url = url;
84
+ catch (e) {
85
+ if (/Timeout/i.test(e.message ?? ""))
86
+ return {}; // a page that never fires load is still readable
87
+ return { loadError: loadErrorOf(e) };
80
88
  }
81
89
  }
82
- async evaluate(expr, awaitPromise = false) {
83
- const conn = await this.ensure();
84
- const t = this.tab();
85
- const raw = await conn.send("Runtime.evaluate", { expression: expr, returnByValue: true, awaitPromise }, t.sessionId);
86
- return evalResultToText(raw);
90
+ /** Render `url` in a tab of its own, sized `width`×`height`, and save a PNG (the viewport, or the whole page up to
91
+ * MAX_PAGE_PX tall). A long page also yields up to `tiles` viewport-sized slices spread top to bottom, so vision
92
+ * sees readable pieces instead of one strip downscaled to nothing. The `browser` tool's tabs are left as they were. */
93
+ async capture(url, o) {
94
+ const b = await this.ensure();
95
+ const page = await b.context.newPage();
96
+ try {
97
+ await page.setViewportSize({ width: o.width, height: o.height });
98
+ const { status, loadError } = await this.navigate(page, url);
99
+ const value = async (expression) => (await page.evaluate(expression).catch(() => undefined));
100
+ const title = (await value("document.title")) ?? "";
101
+ const fullHeight = Math.max(o.height, Math.ceil((await value("Math.max(document.documentElement.scrollHeight, document.body ? document.body.scrollHeight : 0)")) ?? o.height));
102
+ const height = o.fullPage ? Math.min(fullHeight, MAX_PAGE_PX) : o.height;
103
+ const shoot = async (y, h, path) => {
104
+ await page.screenshot({ path, fullPage: o.fullPage, clip: { x: 0, y, width: o.width, height: h } });
105
+ return path;
106
+ };
107
+ const base = await shotBase("page");
108
+ const path = await shoot(0, height, `${base}.png`);
109
+ const tiles = [];
110
+ const n = o.fullPage && height > o.height * 1.5 ? Math.min(Math.max(1, o.tiles), Math.ceil(height / o.height)) : 0;
111
+ for (let i = 0; i < n; i++)
112
+ tiles.push(await shoot(n === 1 ? 0 : Math.round((i * (height - o.height)) / (n - 1)), o.height, `${base}-${i + 1}.png`));
113
+ const probe = o.probe ? await value(o.probe) : undefined;
114
+ return { path, tiles, title, finalUrl: page.url(), status, loadError, width: o.width, height, fullHeight, probe };
115
+ }
116
+ finally {
117
+ await page.close().catch(() => undefined);
118
+ }
119
+ }
120
+ async evaluate(expr) {
121
+ await this.ensure();
122
+ try {
123
+ return valueToText(await this.tab().evaluate(expr));
124
+ }
125
+ catch (e) {
126
+ throw new Error(`browser js error: ${shortError(e)}`);
127
+ }
87
128
  }
88
129
  async run(action, a) {
89
- const conn = await this.ensure();
130
+ await this.ensure();
131
+ const opts = { timeout: ACTION_TIMEOUT_MS };
90
132
  switch (action) {
91
133
  case "open": {
92
- const url = String(a.url ?? "about:blank");
93
- await this.newTab(conn, url);
94
- return this.infoInner(conn);
134
+ await this.newTab(String(a.url ?? "about:blank"));
135
+ return this.info();
95
136
  }
96
137
  case "navigate": {
97
- await this.navigate(conn, this.tab(), String(a.url));
98
- return this.infoInner(conn);
138
+ const { loadError } = await this.navigate(this.tab(), String(a.url));
139
+ return loadError ? `load failed: ${loadError}` : this.info();
99
140
  }
100
141
  case "reload": {
101
- await conn.send("Page.reload", { ignoreCache: !!a.cache_bust }, this.tab().sessionId);
102
- await new Promise((r) => setTimeout(r, 500));
103
- return this.infoInner(conn);
142
+ const t = this.tab();
143
+ if (a.cache_bust) { // Playwright's reload has no ignoreCache; Chromium's own Page.reload does
144
+ const cdp = await this.launched.context.newCDPSession(t);
145
+ try {
146
+ await cdp.send("Page.reload", { ignoreCache: true });
147
+ }
148
+ finally {
149
+ await cdp.detach().catch(() => undefined);
150
+ }
151
+ await t.waitForLoadState("load", { timeout: NAV_TIMEOUT_MS }).catch(() => undefined);
152
+ }
153
+ else
154
+ await t.reload({ waitUntil: "load", timeout: NAV_TIMEOUT_MS });
155
+ return this.info();
104
156
  }
105
157
  case "back":
106
158
  case "forward": {
107
- // history via JS (no CDP history domain): simplest reliable path
108
- await this.evaluate(action === "back" ? "history.back(); 'back'" : "history.forward(); 'forward'");
109
- await new Promise((r) => setTimeout(r, 400));
110
- return this.infoInner(conn);
159
+ const t = this.tab();
160
+ await (action === "back" ? t.goBack({ timeout: NAV_TIMEOUT_MS }) : t.goForward({ timeout: NAV_TIMEOUT_MS }));
161
+ return this.info();
111
162
  }
112
- case "info": return this.infoInner(conn);
163
+ case "info": return this.info();
113
164
  case "text": {
114
165
  const max = Math.max(500, Math.min(Number(a.max_chars ?? 20000), 100_000));
115
166
  const title = await this.evaluate("document.title");
116
- const url = await this.evaluate("location.href");
167
+ const url = this.tab().url();
117
168
  const body = await this.evaluate("(() => { const b = document.body; const t = b ? b.innerText : ''; return t.replace(/\\n{3,}/g, '\\n\\n').slice(0, " + max + "); })()");
118
169
  return `# ${title}\n${url}\n\n${body}`;
119
170
  }
120
- case "eval": {
121
- const out = await this.evaluate(String(a.js ?? "1"), true);
122
- return String(out);
123
- }
171
+ case "eval": return this.evaluate(String(a.js ?? "1"));
124
172
  case "click": {
125
173
  const sel = String(a.selector);
126
- const out = await this.evaluate(`(() => {
127
- const el = document.querySelector(${JSON.stringify(sel)});
128
- if (!el) throw new Error("element not found: " + ${JSON.stringify(sel)});
129
- el.scrollIntoView({ block: "center" });
130
- if (typeof el.click === "function") el.click(); else el.dispatchEvent(new MouseEvent("click", { bubbles: true }));
131
- return "clicked " + (el.tagName + (el.id ? "#" + el.id : "")).toLowerCase();
132
- })()`);
174
+ const t = this.tab();
175
+ const what = await t.$eval(sel, (el) => (el.tagName + (el.id ? "#" + el.id : "")).toLowerCase()).catch(() => sel);
176
+ await t.click(sel, opts);
133
177
  await new Promise((r) => setTimeout(r, Number(a.settle_ms ?? 250)));
134
- return String(out);
178
+ return `clicked ${what}`;
135
179
  }
136
180
  case "fill": {
137
- const out = await this.evaluate(fillScript(String(a.selector), String(a.text ?? "")));
138
- return `filled ${a.selector}: ${out}`;
181
+ const sel = String(a.selector);
182
+ const text = String(a.text ?? "");
183
+ const t = this.tab();
184
+ await t.fill(sel, text, opts);
185
+ return `filled ${sel}: ${await t.inputValue(sel, opts).catch(() => text)}`;
139
186
  }
140
187
  case "submit": {
141
- return String(await this.evaluate(`(() => {
142
- const el = document.querySelector(${JSON.stringify(String(a.selector))});
143
- const f = el && (el.form || (el.tagName === "FORM" ? el : null));
144
- if (!f) throw new Error("no form for selector: " + ${JSON.stringify(String(a.selector))});
145
- if (typeof f.requestSubmit === "function") f.requestSubmit(); else f.submit();
146
- return "submitted " + (f.action || "(inline)");
147
- })()`));
188
+ return valueToText(await this.tab().$eval(String(a.selector), (el) => {
189
+ const f = el.form || (el.tagName === "FORM" ? el : null);
190
+ if (!f)
191
+ throw new Error("no form for selector");
192
+ if (typeof f.requestSubmit === "function")
193
+ f.requestSubmit();
194
+ else
195
+ f.submit();
196
+ return "submitted " + (f.action || "(inline)");
197
+ }));
148
198
  }
149
199
  case "tab_list": {
150
- const list = await conn.send("Target.getTargets", {});
151
- const pages = list.targetInfos.filter((x) => x.type === "page");
152
- return pages.map((p, i) => `${i === this.active ? "*" : " "} ${i} ${p.title || "(untitled)"} — ${p.url.slice(0, 120)}`).join("\n") || "(no pages)";
200
+ this.tabs = this.tabs.filter((t) => !t.isClosed());
201
+ const rows = await Promise.all(this.tabs.map(async (p, i) => `${i === this.active ? "*" : " "} ${i} ${(await p.title().catch(() => "")) || "(untitled)"} — ${p.url().slice(0, 120)}`));
202
+ return rows.join("\n") || "(no pages)";
153
203
  }
154
204
  case "tab_select": {
155
205
  const i = Number(a.index);
156
206
  if (!this.tabs[i])
157
207
  throw new Error(`browser: no tab ${i} (have ${this.tabs.length})`);
158
208
  this.active = i;
159
- return this.infoInner(conn);
209
+ return this.info();
160
210
  }
161
211
  case "tab_close": {
162
212
  const i = Number.isFinite(Number(a.index)) ? Number(a.index) : this.active;
163
213
  const t = this.tabs[i];
164
214
  if (!t)
165
215
  throw new Error(`browser: no tab ${i}`);
166
- await conn.send("Target.closeTarget", { targetId: t.targetId }).catch(() => undefined);
216
+ await t.close().catch(() => undefined);
167
217
  this.tabs.splice(i, 1);
168
218
  this.active = Math.min(this.active, this.tabs.length - 1);
169
219
  return `closed tab ${i}; ${this.tabs.length} left`;
170
220
  }
171
221
  case "screenshot": {
172
- const shot = await conn.send("Page.captureScreenshot", { format: "png" }, this.tab().sessionId);
173
- const bytes = Math.round(shot.data.length * 3 / 4); // base64 → raw size
174
- const { mkdirSync, writeFileSync } = await nodeImport("node:fs");
175
- const { operatorPath } = await nodeImport("../config/home.js");
176
- let path;
177
- try {
178
- const dir = operatorPath("cache", "browser");
179
- mkdirSync(dir, { recursive: true });
180
- path = `${dir}/shot-${Date.now()}.png`;
181
- }
182
- catch {
183
- const os = await nodeImport("node:os");
184
- path = `${os.tmpdir()}/kode-shot-${Date.now()}.png`;
185
- }
186
- writeFileSync(path, shot.data, "base64");
187
- return `screenshot ${path} (${Math.round(bytes / 1024)} KB) — pass to image_analyze if you must see pixels; prefer text/eval`;
222
+ const path = `${await shotBase("shot")}.png`;
223
+ await this.tab().screenshot({ path });
224
+ const { statSync } = await nodeImport("node:fs");
225
+ return `screenshot ${path} (${Math.round(statSync(path).size / 1024)} KB) — pass to image_analyze if you must see pixels; prefer text/eval`;
188
226
  }
189
227
  case "close": {
190
228
  await this.dispose();
@@ -193,45 +231,40 @@ class BrowserSession {
193
231
  default: throw new Error(`browser: unknown action '${action}'`);
194
232
  }
195
233
  }
196
- async infoInner(conn) {
234
+ async info() {
197
235
  try {
198
- const title = await conn.send("Runtime.evaluate", { expression: "document.title", returnByValue: true }, this.tab().sessionId);
199
- const url = await conn.send("Runtime.evaluate", { expression: "location.href + ' | ' + document.readyState", returnByValue: true }, this.tab().sessionId);
200
- return `${title?.result?.value || "(untitled)"} — ${url?.result?.value ?? "?"}`;
236
+ const t = this.tab();
237
+ const title = await t.title();
238
+ const state = await t.evaluate("document.readyState").catch(() => "?");
239
+ return `${title || "(untitled)"} — ${t.url()} | ${state}`;
201
240
  }
202
241
  catch (e) {
203
- return `info failed: ${e.message}`;
242
+ return `info failed: ${shortError(e)}`;
204
243
  }
205
244
  }
206
245
  async dispose() {
207
- try {
208
- this.conn?.close();
209
- }
210
- catch { /* gone */ }
211
- this.conn = null;
212
- try {
213
- this.proc?.kill?.("SIGTERM");
214
- }
215
- catch { /* gone */ }
216
- this.proc = null;
246
+ const b = this.launched;
247
+ this.launched = null;
217
248
  this.tabs = [];
218
249
  this.active = -1;
250
+ if (b)
251
+ await b.close().catch(() => undefined);
219
252
  }
220
253
  /** href of the active tab (origin-bound vault checks). Throws cleanly when no page. */
221
254
  async href() {
222
- const conn = await this.ensure();
223
- const t = this.tab();
224
- const r = await conn.send("Runtime.evaluate", { expression: "location.href", returnByValue: true }, t.sessionId);
225
- const v = r?.result?.value;
255
+ await this.ensure();
256
+ const v = this.tab().url();
226
257
  if (!v)
227
258
  throw new Error("no active page href");
228
259
  return v;
229
260
  }
230
- /** Fill user+password fields atomically from the VAULT PATH — the secret value is a parameter to
231
- * this function only; callers above (tool glue) must never echo it back. */
261
+ /** Fill user+password fields from the VAULT PATH — the secret value is a parameter to this function only; callers
262
+ * above (tool glue) must never echo it back. */
232
263
  async fillPair(userSel, userVal, passSel, passVal) {
233
- await this.evaluate(fillScript(userSel, userVal));
234
- await this.evaluate(fillScript(passSel, passVal));
264
+ await this.ensure();
265
+ const t = this.tab();
266
+ await t.fill(userSel, userVal, { timeout: ACTION_TIMEOUT_MS });
267
+ await t.fill(passSel, passVal, { timeout: ACTION_TIMEOUT_MS });
235
268
  }
236
269
  }
237
270
  let singleton = null;
@@ -247,9 +280,8 @@ export async function disposeBrowser() {
247
280
  singleton = null;
248
281
  }
249
282
  }
250
- /** SYNC teardown for process-exit hooks — the same contract as disposeShellSession(): the SIGTERM
251
- * is delivered synchronously inside dispose(), so the Chrome child is signaled before
252
- * process.exit() can leave it orphaned. */
283
+ /** Teardown for process-exit hooks. Closing is async; Playwright's own exit handler kills any browser it launched
284
+ * that is still up when the process ends, so nothing is left behind either way. */
253
285
  export function disposeBrowserNow() {
254
286
  if (!singleton)
255
287
  return;
@@ -267,6 +299,10 @@ export const browserSessionHooks = {
267
299
  activeHref: () => session().href(),
268
300
  fillPair: (u, uv, p, pv) => session().fillPair(u, uv, p, pv),
269
301
  };
302
+ /** image_analyze `page` renders through the same browser as the `browser` tool; tests replace `capture`. */
303
+ export const pageCaptureHooks = {
304
+ capture: (url, o) => session().capture(url, o),
305
+ };
270
306
  /** run() for the `browser` tool (ACT side, plus reads for convenience in ungated modes). */
271
307
  export async function runBrowser(args) {
272
308
  const need = BROWSER_NEEDS[String(args.action)];
@@ -276,9 +312,11 @@ export async function runBrowser(args) {
276
312
  return await session().run(String(args.action ?? "info"), args);
277
313
  }
278
314
  catch (e) {
279
- const msg = e?.message ?? String(e);
280
- if (/devtools|spawn|ws |Chrome|chrome/.test(msg))
281
- return `browser: ${msg}`;
315
+ const msg = shortError(e);
316
+ if (/has been closed|Browser closed|crashed/i.test(msg))
317
+ await disposeBrowser(); // the next call relaunches
318
+ if (/^browser/.test(msg))
319
+ return msg;
282
320
  return `browser error: ${msg}`;
283
321
  }
284
322
  }