@0perator/operator 0.1.360-next.2 → 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 (49) 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 +2 -0
  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 +130 -140
  9. package/dist/cli.js +174 -12
  10. package/dist/config/settings.js +1 -1
  11. package/dist/engine/agent.js +1 -1
  12. package/dist/engine/aurora.js +4 -4
  13. package/dist/engine/compaction.js +1 -1
  14. package/dist/engine/moa.js +2 -1
  15. package/dist/engine/selfheal.js +1 -1
  16. package/dist/engine/toolcalls.js +6 -6
  17. package/dist/index.js +3 -0
  18. package/dist/mcp/phone-server.js +30 -0
  19. package/dist/permissions/index.js +33 -17
  20. package/dist/permissions/signature.js +5 -0
  21. package/dist/phone-cli.js +65 -0
  22. package/dist/remote/host.js +31 -2
  23. package/dist/router/models.js +5 -15
  24. package/dist/selfimprove/index.js +1 -1
  25. package/dist/session.js +48 -7
  26. package/dist/tools/deferred.js +1 -0
  27. package/dist/tools/device/android.js +227 -0
  28. package/dist/tools/device/classify.js +127 -0
  29. package/dist/tools/device/deps.js +69 -0
  30. package/dist/tools/device/desktop.js +82 -0
  31. package/dist/tools/device/harness.js +262 -0
  32. package/dist/tools/device/iphone.js +206 -0
  33. package/dist/tools/device/mirroring-jxa.js +146 -0
  34. package/dist/tools/device/setup.js +90 -0
  35. package/dist/tools/device/tools.js +70 -0
  36. package/dist/tools/device/types.js +19 -0
  37. package/dist/tools/registry.js +12 -3
  38. package/dist/ui/App.js +4 -3
  39. package/dist/ui/ApprovalPrompt.js +10 -4
  40. package/dist/ui/BgPanel.js +2 -2
  41. package/dist/ui/UpdatePrompt.js +40 -0
  42. package/dist/ui/modelPicker.js +1 -1
  43. package/dist/ui/slashCommands.js +1 -0
  44. package/dist/update-check.js +134 -0
  45. package/dist/update.js +59 -15
  46. package/dist/util/slash.js +2 -2
  47. package/package.json +4 -2
  48. package/src/tools/device/NOTICE +37 -0
  49. package/dist/browser/cdp.js +0 -271
@@ -1,11 +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";
7
8
  /** A full-page capture stops here (CSS px): past it Chrome's capture gets slow and the PNG heavy. */
8
9
  export const MAX_PAGE_PX = 16_384;
10
+ const { ACTION_TIMEOUT_MS, NAV_TIMEOUT_MS, IDLE_TTL_MS } = BROWSER_CONSTANTS;
9
11
  async function nodeImport(id) {
10
12
  const g = globalThis;
11
13
  try {
@@ -30,92 +32,76 @@ async function shotBase(kind) {
30
32
  return `${os.tmpdir()}/kode-${kind}-${Date.now()}`;
31
33
  }
32
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
+ }
33
40
  class BrowserSession {
34
- conn = null;
35
- proc = null;
41
+ launched = null;
36
42
  tabs = [];
37
43
  active = -1;
38
44
  lastUsed = 0;
39
45
  async ensure() {
40
46
  const now = Date.now();
41
- const alive = this.conn && this.proc && this.proc.exitCode == null &&
42
- now - this.lastUsed < BROWSER_CONSTANTS.IDLE_TTL_MS;
43
- if (alive) {
47
+ if (this.launched && now - this.lastUsed < IDLE_TTL_MS) {
44
48
  this.lastUsed = now;
45
- return this.conn;
49
+ return this.launched;
46
50
  }
47
- 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)
48
- const { proc, wsUrl } = await launchChrome();
49
- const conn = new CdpConnection(wsUrl);
50
- await conn.connect();
51
- this.proc = proc;
52
- this.conn = conn;
51
+ await this.dispose(); // TTL expiry: rebuild clean
52
+ this.launched = await launchBrowser();
53
53
  this.tabs = [];
54
54
  this.active = -1;
55
55
  this.lastUsed = Date.now();
56
- return conn;
56
+ return this.launched;
57
57
  }
58
- /** Attach a fresh tab (target) and make it active. */
59
- async newTab(conn, url) {
60
- const created = await conn.send("Target.createTarget", { url: "about:blank" });
61
- const attached = await conn.send("Target.attachToTarget", { targetId: created.targetId, flatten: true });
62
- const tab = { targetId: created.targetId, sessionId: attached.sessionId, url: "about:blank" };
63
- 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);
64
63
  this.active = this.tabs.length - 1;
65
- await conn.send("Page.enable", {}, tab.sessionId);
66
- await conn.send("Runtime.enable", {}, tab.sessionId);
67
64
  if (url !== "about:blank")
68
- await this.navigate(conn, tab, url);
69
- return tab;
65
+ await this.navigate(page, url);
66
+ return page;
70
67
  }
71
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;
72
72
  if (this.active < 0 || !this.tabs[this.active])
73
73
  throw new Error("browser: no active tab — call open first");
74
74
  return this.tabs[this.active];
75
75
  }
76
- /** Resolves to Chrome's network error for the load (net::ERR_NAME_NOT_RESOLVED, …), or undefined. */
77
- async navigate(conn, tab, url) {
76
+ async navigate(page, url) {
78
77
  const blocked = checkNavigationUrl(url);
79
78
  if (blocked)
80
79
  throw new Error(blocked);
81
- const loadFired = conn.once("Page.loadEventFired"); // subscribe BEFORE navigate so we never miss it
82
- const nav = await conn.send("Page.navigate", { url }, tab.sessionId);
83
- const settled = await Promise.race([
84
- loadFired.then(() => "load"),
85
- new Promise((res) => setTimeout(() => res("timeout"), BROWSER_CONSTANTS.NAV_TIMEOUT_MS)),
86
- ]);
87
- // load fired (or timed out) — give SPAs a beat to paint, then confirm readyState
88
- await new Promise((r) => setTimeout(r, 300));
89
80
  try {
90
- const rs = await conn.send("Runtime.evaluate", { expression: "document.readyState", returnByValue: true }, tab.sessionId);
91
- tab.url = (await conn.send("Runtime.evaluate", { expression: "location.href", returnByValue: true }, tab.sessionId))?.result?.value ?? url;
92
- void settled;
93
- void rs;
81
+ const res = await page.goto(url, { waitUntil: "load", timeout: NAV_TIMEOUT_MS });
82
+ return { status: res?.status() || undefined };
94
83
  }
95
- catch {
96
- 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) };
97
88
  }
98
- return nav?.errorText || undefined;
99
89
  }
100
90
  /** Render `url` in a tab of its own, sized `width`×`height`, and save a PNG (the viewport, or the whole page up to
101
91
  * MAX_PAGE_PX tall). A long page also yields up to `tiles` viewport-sized slices spread top to bottom, so vision
102
92
  * sees readable pieces instead of one strip downscaled to nothing. The `browser` tool's tabs are left as they were. */
103
93
  async capture(url, o) {
104
- const conn = await this.ensure();
105
- const before = this.active;
106
- const tab = await this.newTab(conn, "about:blank");
94
+ const b = await this.ensure();
95
+ const page = await b.context.newPage();
107
96
  try {
108
- await conn.send("Emulation.setDeviceMetricsOverride", { width: o.width, height: o.height, deviceScaleFactor: 1, mobile: false }, tab.sessionId);
109
- const loadError = await this.navigate(conn, tab, url);
110
- const value = async (expression) => (await conn.send("Runtime.evaluate", { expression, returnByValue: true }, tab.sessionId).catch(() => undefined))?.result?.value;
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));
111
100
  const title = (await value("document.title")) ?? "";
112
- const status = (await value("performance.getEntriesByType('navigation')[0]?.responseStatus || 0")) || undefined;
113
101
  const fullHeight = Math.max(o.height, Math.ceil((await value("Math.max(document.documentElement.scrollHeight, document.body ? document.body.scrollHeight : 0)")) ?? o.height));
114
102
  const height = o.fullPage ? Math.min(fullHeight, MAX_PAGE_PX) : o.height;
115
103
  const shoot = async (y, h, path) => {
116
- const shot = await conn.send("Page.captureScreenshot", { format: "png", captureBeyondViewport: o.fullPage, clip: { x: 0, y, width: o.width, height: h, scale: 1 } }, tab.sessionId);
117
- const { writeFileSync } = await nodeImport("node:fs");
118
- writeFileSync(path, shot.data, "base64");
104
+ await page.screenshot({ path, fullPage: o.fullPage, clip: { x: 0, y, width: o.width, height: h } });
119
105
  return path;
120
106
  };
121
107
  const base = await shotBase("page");
@@ -125,110 +111,118 @@ class BrowserSession {
125
111
  for (let i = 0; i < n; i++)
126
112
  tiles.push(await shoot(n === 1 ? 0 : Math.round((i * (height - o.height)) / (n - 1)), o.height, `${base}-${i + 1}.png`));
127
113
  const probe = o.probe ? await value(o.probe) : undefined;
128
- return { path, tiles, title, finalUrl: tab.url, status, loadError, width: o.width, height, fullHeight, probe };
114
+ return { path, tiles, title, finalUrl: page.url(), status, loadError, width: o.width, height, fullHeight, probe };
129
115
  }
130
116
  finally {
131
- await conn.send("Target.closeTarget", { targetId: tab.targetId }).catch(() => undefined);
132
- this.tabs = this.tabs.filter((t) => t !== tab);
133
- this.active = Math.min(before, this.tabs.length - 1);
117
+ await page.close().catch(() => undefined);
134
118
  }
135
119
  }
136
- async evaluate(expr, awaitPromise = false) {
137
- const conn = await this.ensure();
138
- const t = this.tab();
139
- const raw = await conn.send("Runtime.evaluate", { expression: expr, returnByValue: true, awaitPromise }, t.sessionId);
140
- return evalResultToText(raw);
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
+ }
141
128
  }
142
129
  async run(action, a) {
143
- const conn = await this.ensure();
130
+ await this.ensure();
131
+ const opts = { timeout: ACTION_TIMEOUT_MS };
144
132
  switch (action) {
145
133
  case "open": {
146
- const url = String(a.url ?? "about:blank");
147
- await this.newTab(conn, url);
148
- return this.infoInner(conn);
134
+ await this.newTab(String(a.url ?? "about:blank"));
135
+ return this.info();
149
136
  }
150
137
  case "navigate": {
151
- await this.navigate(conn, this.tab(), String(a.url));
152
- return this.infoInner(conn);
138
+ const { loadError } = await this.navigate(this.tab(), String(a.url));
139
+ return loadError ? `load failed: ${loadError}` : this.info();
153
140
  }
154
141
  case "reload": {
155
- await conn.send("Page.reload", { ignoreCache: !!a.cache_bust }, this.tab().sessionId);
156
- await new Promise((r) => setTimeout(r, 500));
157
- 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();
158
156
  }
159
157
  case "back":
160
158
  case "forward": {
161
- // history via JS (no CDP history domain): simplest reliable path
162
- await this.evaluate(action === "back" ? "history.back(); 'back'" : "history.forward(); 'forward'");
163
- await new Promise((r) => setTimeout(r, 400));
164
- 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();
165
162
  }
166
- case "info": return this.infoInner(conn);
163
+ case "info": return this.info();
167
164
  case "text": {
168
165
  const max = Math.max(500, Math.min(Number(a.max_chars ?? 20000), 100_000));
169
166
  const title = await this.evaluate("document.title");
170
- const url = await this.evaluate("location.href");
167
+ const url = this.tab().url();
171
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 + "); })()");
172
169
  return `# ${title}\n${url}\n\n${body}`;
173
170
  }
174
- case "eval": {
175
- const out = await this.evaluate(String(a.js ?? "1"), true);
176
- return String(out);
177
- }
171
+ case "eval": return this.evaluate(String(a.js ?? "1"));
178
172
  case "click": {
179
173
  const sel = String(a.selector);
180
- const out = await this.evaluate(`(() => {
181
- const el = document.querySelector(${JSON.stringify(sel)});
182
- if (!el) throw new Error("element not found: " + ${JSON.stringify(sel)});
183
- el.scrollIntoView({ block: "center" });
184
- if (typeof el.click === "function") el.click(); else el.dispatchEvent(new MouseEvent("click", { bubbles: true }));
185
- return "clicked " + (el.tagName + (el.id ? "#" + el.id : "")).toLowerCase();
186
- })()`);
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);
187
177
  await new Promise((r) => setTimeout(r, Number(a.settle_ms ?? 250)));
188
- return String(out);
178
+ return `clicked ${what}`;
189
179
  }
190
180
  case "fill": {
191
- const out = await this.evaluate(fillScript(String(a.selector), String(a.text ?? "")));
192
- 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)}`;
193
186
  }
194
187
  case "submit": {
195
- return String(await this.evaluate(`(() => {
196
- const el = document.querySelector(${JSON.stringify(String(a.selector))});
197
- const f = el && (el.form || (el.tagName === "FORM" ? el : null));
198
- if (!f) throw new Error("no form for selector: " + ${JSON.stringify(String(a.selector))});
199
- if (typeof f.requestSubmit === "function") f.requestSubmit(); else f.submit();
200
- return "submitted " + (f.action || "(inline)");
201
- })()`));
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
+ }));
202
198
  }
203
199
  case "tab_list": {
204
- const list = await conn.send("Target.getTargets", {});
205
- const pages = list.targetInfos.filter((x) => x.type === "page");
206
- 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)";
207
203
  }
208
204
  case "tab_select": {
209
205
  const i = Number(a.index);
210
206
  if (!this.tabs[i])
211
207
  throw new Error(`browser: no tab ${i} (have ${this.tabs.length})`);
212
208
  this.active = i;
213
- return this.infoInner(conn);
209
+ return this.info();
214
210
  }
215
211
  case "tab_close": {
216
212
  const i = Number.isFinite(Number(a.index)) ? Number(a.index) : this.active;
217
213
  const t = this.tabs[i];
218
214
  if (!t)
219
215
  throw new Error(`browser: no tab ${i}`);
220
- await conn.send("Target.closeTarget", { targetId: t.targetId }).catch(() => undefined);
216
+ await t.close().catch(() => undefined);
221
217
  this.tabs.splice(i, 1);
222
218
  this.active = Math.min(this.active, this.tabs.length - 1);
223
219
  return `closed tab ${i}; ${this.tabs.length} left`;
224
220
  }
225
221
  case "screenshot": {
226
- const shot = await conn.send("Page.captureScreenshot", { format: "png" }, this.tab().sessionId);
227
- const bytes = Math.round(shot.data.length * 3 / 4); // base64 → raw size
228
- const { writeFileSync } = await nodeImport("node:fs");
229
222
  const path = `${await shotBase("shot")}.png`;
230
- writeFileSync(path, shot.data, "base64");
231
- return `screenshot ${path} (${Math.round(bytes / 1024)} KB) — pass to image_analyze if you must see pixels; prefer text/eval`;
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`;
232
226
  }
233
227
  case "close": {
234
228
  await this.dispose();
@@ -237,45 +231,40 @@ class BrowserSession {
237
231
  default: throw new Error(`browser: unknown action '${action}'`);
238
232
  }
239
233
  }
240
- async infoInner(conn) {
234
+ async info() {
241
235
  try {
242
- const title = await conn.send("Runtime.evaluate", { expression: "document.title", returnByValue: true }, this.tab().sessionId);
243
- const url = await conn.send("Runtime.evaluate", { expression: "location.href + ' | ' + document.readyState", returnByValue: true }, this.tab().sessionId);
244
- 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}`;
245
240
  }
246
241
  catch (e) {
247
- return `info failed: ${e.message}`;
242
+ return `info failed: ${shortError(e)}`;
248
243
  }
249
244
  }
250
245
  async dispose() {
251
- try {
252
- this.conn?.close();
253
- }
254
- catch { /* gone */ }
255
- this.conn = null;
256
- try {
257
- this.proc?.kill?.("SIGTERM");
258
- }
259
- catch { /* gone */ }
260
- this.proc = null;
246
+ const b = this.launched;
247
+ this.launched = null;
261
248
  this.tabs = [];
262
249
  this.active = -1;
250
+ if (b)
251
+ await b.close().catch(() => undefined);
263
252
  }
264
253
  /** href of the active tab (origin-bound vault checks). Throws cleanly when no page. */
265
254
  async href() {
266
- const conn = await this.ensure();
267
- const t = this.tab();
268
- const r = await conn.send("Runtime.evaluate", { expression: "location.href", returnByValue: true }, t.sessionId);
269
- const v = r?.result?.value;
255
+ await this.ensure();
256
+ const v = this.tab().url();
270
257
  if (!v)
271
258
  throw new Error("no active page href");
272
259
  return v;
273
260
  }
274
- /** Fill user+password fields atomically from the VAULT PATH — the secret value is a parameter to
275
- * 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. */
276
263
  async fillPair(userSel, userVal, passSel, passVal) {
277
- await this.evaluate(fillScript(userSel, userVal));
278
- 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 });
279
268
  }
280
269
  }
281
270
  let singleton = null;
@@ -291,9 +280,8 @@ export async function disposeBrowser() {
291
280
  singleton = null;
292
281
  }
293
282
  }
294
- /** SYNC teardown for process-exit hooks — the same contract as disposeShellSession(): the SIGTERM
295
- * is delivered synchronously inside dispose(), so the Chrome child is signaled before
296
- * 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. */
297
285
  export function disposeBrowserNow() {
298
286
  if (!singleton)
299
287
  return;
@@ -311,7 +299,7 @@ export const browserSessionHooks = {
311
299
  activeHref: () => session().href(),
312
300
  fillPair: (u, uv, p, pv) => session().fillPair(u, uv, p, pv),
313
301
  };
314
- /** image_analyze `page` renders through the same Chrome as the `browser` tool; tests replace `capture`. */
302
+ /** image_analyze `page` renders through the same browser as the `browser` tool; tests replace `capture`. */
315
303
  export const pageCaptureHooks = {
316
304
  capture: (url, o) => session().capture(url, o),
317
305
  };
@@ -324,9 +312,11 @@ export async function runBrowser(args) {
324
312
  return await session().run(String(args.action ?? "info"), args);
325
313
  }
326
314
  catch (e) {
327
- const msg = e?.message ?? String(e);
328
- if (/devtools|spawn|ws |Chrome|chrome/.test(msg))
329
- 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;
330
320
  return `browser error: ${msg}`;
331
321
  }
332
322
  }