codex-browser-use 4.8.2 → 4.9.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.
package/src/server.js CHANGED
@@ -13,7 +13,6 @@ const tabGroupColorEnum = z.enum(["grey", "blue", "red", "yellow", "green", "pin
13
13
  const keepEntrySchema = z.object({
14
14
  tab_id: stringOrNumber,
15
15
  mode: z.enum(["handoff", "deliverable"]).optional(),
16
- focus: z.boolean().optional(),
17
16
  });
18
17
  const keepParamSchema = z.union([
19
18
  z.enum(["handoff", "deliverable"]),
@@ -22,17 +21,19 @@ const keepParamSchema = z.union([
22
21
 
23
22
  /**
24
23
  * Normalize inline `keep` parameter + script-tracked kept tabs into unique keep entries.
24
+ * Never activates or steals focus from the user's tab unless `BROWSER_USE_ALLOW_TAB_FOCUS=1`.
25
25
  * @param {"handoff"|"deliverable"|Array<{tab_id:unknown, mode?:string, focus?:boolean}>|undefined} keep
26
26
  * @param {unknown} fallbackTabId
27
27
  * @param {Array<{tab_id:unknown, mode?:string, focus?:boolean}>} [extraKept]
28
28
  */
29
29
  function resolveKeepEntries(keep, fallbackTabId, extraKept = []) {
30
+ const allowFocus = process.env.BROWSER_USE_ALLOW_TAB_FOCUS === "1";
30
31
  const merged = new Map();
31
32
  for (const entry of extraKept) {
32
33
  if (entry?.tab_id != null) {
33
34
  merged.set(String(entry.tab_id), {
34
35
  mode: entry.mode === "deliverable" ? "deliverable" : "handoff",
35
- ...(entry.focus === true ? { focus: true } : {}),
36
+ ...(allowFocus && entry.focus === true ? { focus: true } : {}),
36
37
  });
37
38
  }
38
39
  }
@@ -41,7 +42,7 @@ function resolveKeepEntries(keep, fallbackTabId, extraKept = []) {
41
42
  const prev = merged.get(String(fallbackTabId));
42
43
  merged.set(String(fallbackTabId), {
43
44
  mode: keep,
44
- ...(prev?.focus === true ? { focus: true } : {}),
45
+ ...(allowFocus && prev?.focus === true ? { focus: true } : {}),
45
46
  });
46
47
  }
47
48
  } else if (Array.isArray(keep)) {
@@ -50,7 +51,7 @@ function resolveKeepEntries(keep, fallbackTabId, extraKept = []) {
50
51
  const prev = merged.get(String(entry.tab_id));
51
52
  merged.set(String(entry.tab_id), {
52
53
  mode: entry.mode === "deliverable" ? "deliverable" : "handoff",
53
- ...(entry.focus === true || (entry.focus === undefined && prev?.focus === true) ? { focus: true } : {}),
54
+ ...(allowFocus && (entry.focus === true || (entry.focus === undefined && prev?.focus === true)) ? { focus: true } : {}),
54
55
  });
55
56
  }
56
57
  }
@@ -58,7 +59,7 @@ function resolveKeepEntries(keep, fallbackTabId, extraKept = []) {
58
59
  return [...merged.entries()].map(([tab_id, cfg]) => ({
59
60
  tab_id,
60
61
  mode: cfg.mode,
61
- ...(cfg.focus === true ? { focus: true } : {}),
62
+ ...(allowFocus && cfg.focus === true ? { focus: true } : {}),
62
63
  }));
63
64
  }
64
65
 
@@ -82,6 +83,7 @@ function shouldAttachErrorState(error, msg) {
82
83
  if (
83
84
  /^Browser evaluate (is read-only|could not parse|requires a JavaScript expression)/i.test(msg) ||
84
85
  /^(saveFile|readFile|saveScreenshot) (requires|payload exceeds)/i.test(msg) ||
86
+ /\b(ENOENT|EACCES|EISDIR)\b/u.test(msg) ||
85
87
  /^Maximum \d+ images per browser_run call exceeded/i.test(msg) ||
86
88
  /^No browser tab is active/i.test(msg)
87
89
  ) {
@@ -94,11 +96,22 @@ function shouldAttachErrorState(error, msg) {
94
96
  let browserPromise = null;
95
97
 
96
98
  /** @returns {Promise<BridgeBrowser>} */
97
- function defaultGetBrowser() {
98
- browserPromise ??= BridgeBrowser.connect({ bridgeFile }).catch((error) => {
99
- browserPromise = null;
100
- throw error;
101
- });
99
+ async function defaultGetBrowser() {
100
+ if (browserPromise) {
101
+ const pending = browserPromise;
102
+ const existing = await pending.catch(() => null);
103
+ if (!existing || existing.isClosed?.() || existing.closed) {
104
+ if (browserPromise === pending) browserPromise = null;
105
+ } else {
106
+ return existing;
107
+ }
108
+ }
109
+ if (!browserPromise) {
110
+ browserPromise = BridgeBrowser.connect({ bridgeFile }).catch((error) => {
111
+ browserPromise = null;
112
+ throw error;
113
+ });
114
+ }
102
115
  return browserPromise;
103
116
  }
104
117
 
@@ -165,6 +178,7 @@ async function withOptionalState(browser, tabId, actionResult, returnState = "no
165
178
  screenshot: returnState === "both",
166
179
  diff: returnState === "diff",
167
180
  full: returnState === "full" || returnState === "both",
181
+ mode: "compact",
168
182
  });
169
183
  return stateResponse(state, actionResult);
170
184
  }
@@ -374,6 +388,7 @@ export function registerTools(server, deps = {}) {
374
388
  full: effectiveReturnState === "full" || effectiveReturnState === "both",
375
389
  maxLines: max_lines ?? 1_500,
376
390
  mode: mode ?? "compact",
391
+ allowUnindexedBaseline: true,
377
392
  }).catch(() => null);
378
393
  if (state?.screenshotBase64) {
379
394
  images.push({ data: state.screenshotBase64, mimeType: state.screenshotMimeType || "image/jpeg" });
@@ -415,7 +430,8 @@ export function registerTools(server, deps = {}) {
415
430
  return { content };
416
431
  } catch (error) {
417
432
  const msg = error instanceof Error ? error.message : String(error);
418
- const fallbackTab = run?.activeTabId ?? tab_id ?? browser?.activeTabId;
433
+ const meta = /** @type {any} */ (error)?.browserRunMeta;
434
+ const fallbackTab = run?.activeTabId ?? meta?.activeTabId ?? tab_id ?? browser?.activeTabId;
419
435
  const errState = (browser && fallbackTab != null && shouldAttachErrorState(error, msg))
420
436
  ? await browser.getState(fallbackTab, {
421
437
  screenshot: false,
@@ -425,7 +441,19 @@ export function registerTools(server, deps = {}) {
425
441
  allowUnindexedBaseline: true,
426
442
  }).catch(() => null)
427
443
  : null;
428
- const parts = [msg];
444
+ const locStr = meta?.location ? `line ${meta.location.line}:${meta.location.column}` : null;
445
+ const headline = locStr ? `${msg} (at ${locStr})` : msg;
446
+ const parts = [headline];
447
+ const lastAction = meta?.last_action ?? meta?.lastAction;
448
+ const savedFiles = meta?.saved_files ?? meta?.savedFiles;
449
+ const partialLogs = meta?.partial_logs ?? meta?.logs;
450
+ if (meta && (partialLogs?.length || savedFiles?.length || lastAction)) {
451
+ parts.push(JSON.stringify({
452
+ ...(lastAction ? { last_action: lastAction } : {}),
453
+ ...(savedFiles?.length ? { saved_files: savedFiles } : {}),
454
+ ...(partialLogs?.length ? { partial_logs: partialLogs } : {}),
455
+ }, null, 2));
456
+ }
429
457
  if (errState?.notifications?.length) {
430
458
  parts.push(`<notifications>\n${errState.notifications.map((n) => `- ${n}`).join("\n")}\n</notifications>`);
431
459
  }
@@ -471,9 +499,19 @@ export function registerTools(server, deps = {}) {
471
499
  const fallbackTab = result.state?.tab_id ?? tab_id ?? browser.activeTabId;
472
500
  await browser.markTabs(resolveKeepEntries(keep, fallbackTab)).catch(() => {});
473
501
  }
502
+ const dataStepActions = new Set(["evaluate", "get_content", "read_tab", "new_tab", "get_state"]);
503
+ const stepResults = (result.completed_steps ?? [])
504
+ .filter((entry) => entry?.ok && dataStepActions.has(entry.action))
505
+ .map((entry) => {
506
+ if (entry.action === "get_state") {
507
+ return { step: entry.step, action: entry.action, tab_id: entry.result?.tab_id, elementCount: entry.result?.elementCount };
508
+ }
509
+ return { step: entry.step, action: entry.action, result: entry.result };
510
+ });
474
511
  const summary = {
475
512
  ok: result.ok,
476
513
  completed_steps: result.completed_steps.length,
514
+ ...(stepResults.length > 0 ? { step_results: stepResults } : {}),
477
515
  ...(result.ok ? {} : { failed_step: result.failed_step, error: result.error }),
478
516
  ...(endTurnResult ? { end_turn: endTurnResult } : {}),
479
517
  };
@@ -581,7 +619,7 @@ export function registerTools(server, deps = {}) {
581
619
  full_page: z.boolean().optional().describe("Full-page screenshot when screenshot=true"),
582
620
  format: z.enum(["jpeg", "png"]).optional().describe("Screenshot format (default jpeg)"),
583
621
  full: z.boolean().optional().describe("Return full AX tree instead of diff"),
584
- mode: axModeEnum.optional().describe("AX mode: full (default), compact, or interactive"),
622
+ mode: axModeEnum.optional().describe("AX mode: compact (default), full, or interactive"),
585
623
  max_lines: z.number().int().min(1).max(10_000).optional().describe("Max accessibility lines (default 2000)"),
586
624
  },
587
625
  guarded(async ({ tab_id, screenshot, full_page, format, full, mode, max_lines }) => stateResponse(
@@ -591,7 +629,7 @@ export function registerTools(server, deps = {}) {
591
629
  format: format ?? "jpeg",
592
630
  diff: full !== true,
593
631
  full: full === true,
594
- mode: mode ?? "full",
632
+ mode: mode ?? "compact",
595
633
  maxLines: max_lines ?? 2_000,
596
634
  }),
597
635
  )),
@@ -915,7 +953,12 @@ export function registerTools(server, deps = {}) {
915
953
  ? { ...(format ? { format } : {}), ...(max_chars !== undefined ? { maxChars: max_chars } : {}) }
916
954
  : undefined;
917
955
  const result = await (await getBrowser()).getContent(tab_id, opts);
918
- return text(format === "tables" || format === "links" ? result : (result.content ?? result.text));
956
+ if (format === "tables" || format === "links") {
957
+ const clean = { ...result };
958
+ if (clean.content === clean.text) delete clean.content;
959
+ return text(clean);
960
+ }
961
+ return text(result.content ?? result.text);
919
962
  }),
920
963
  );
921
964
 
@@ -924,7 +967,7 @@ export function registerTools(server, deps = {}) {
924
967
  "Return a compact visible DOM tree (default) or clean YAML ARIA snapshot (`format=\"aria\"`) for fast selector discovery or line filtering.",
925
968
  {
926
969
  format: z.enum(["dom", "aria"]).optional().describe('Snapshot format: "dom" (compact visible DOM) or "aria" (YAML ARIA tree). Defaults to "dom"'),
927
- mode: axModeEnum.optional().describe("ARIA compression mode when format='aria': full (default), compact, or interactive"),
970
+ mode: axModeEnum.optional().describe("ARIA compression mode when format='aria': compact (default), full, or interactive"),
928
971
  max_chars: z.number().int().min(1_000).max(100_000).optional().describe("Character limit for DOM format. Defaults to 24000"),
929
972
  max_lines: z.number().int().min(1).max(10_000).optional().describe("Line limit for ARIA format. Defaults to 2000"),
930
973
  tab_id: stringOrNumber.optional().describe("Optional tab_id"),
@@ -933,7 +976,7 @@ export function registerTools(server, deps = {}) {
933
976
  await (await getBrowser()).domSnapshot({
934
977
  tabId: tab_id,
935
978
  format: format ?? "dom",
936
- mode: mode ?? "full",
979
+ mode: mode ?? "compact",
937
980
  maxChars: max_chars ?? 24_000,
938
981
  maxLines: max_lines ?? 2_000,
939
982
  }),
@@ -1052,12 +1095,13 @@ export function registerTools(server, deps = {}) {
1052
1095
  "browser_end_turn",
1053
1096
  "End agent turn: keep handoff/deliverable tabs open and close unmarked tabs.",
1054
1097
  {
1055
- keep: z.array(keepEntrySchema).optional().describe("Kept tabs"),
1098
+ keep: keepParamSchema.optional().describe('Keep mode ("handoff"|"deliverable") or [{ tab_id, mode }]'),
1056
1099
  ungroup: z.boolean().optional().describe("Ungroup tabs on finish"),
1057
1100
  },
1058
1101
  guarded(async ({ keep, ungroup }) => {
1059
1102
  const browser = await getBrowser();
1060
- const res = await browser.endTurn({ keep: keep ?? [], ungroup: ungroup === true });
1103
+ const entries = keep !== undefined ? resolveKeepEntries(keep, browser.activeTabId) : [];
1104
+ const res = await browser.endTurn({ keep: entries, ungroup: ungroup === true });
1061
1105
  scriptSession.syncActiveTab(browser);
1062
1106
  return text(res);
1063
1107
  }),
@@ -1083,14 +1127,12 @@ export function registerTools(server, deps = {}) {
1083
1127
  export function createStandaloneServer(deps = {}) {
1084
1128
  const profile = deps.profile ?? resolveToolProfile();
1085
1129
  const server = new McpServer(
1086
- { name: "browser-use", version: "4.8.2" },
1130
+ { name: "browser-use", version: "4.9.0" },
1087
1131
  {
1088
1132
  instructions: [
1089
- "Browser use through a local Chrome bridge. Can create new session tabs or inspect and claim existing open user tabs in Chrome (via `browser_list_tabs` + `browser_select_tab` or `tab_id`, or `browser.tabs.list()` / `browser.user.openTabs()` + `browser.tabs.read()` / `browser.user.claimTab()` in `browser_run`). Claimed user tabs join the session Chrome Tab Group and are released (kept open & grouped) when a turn ends.",
1090
- "Tab & Group Hygiene: Use 1 concise task name via `browser.nameSession()` for an entire workflow so tabs across turns consolidate into 1 Chrome Tab Group (avoid spawning separate groups per turn). Before opening a new tab (`tabs.new(url)`), check `browser.user.openTabs()` / `tabs.list()` and reuse an existing tab for the same URL. Close ephemeral tabs with `keep: []` and pass `ungroup: true` when finishing if kept tabs no longer need a group label.",
1091
- "Speed & efficiency (Probe 1 -> Batch Loop All): When facing repetitive UI rows/modals/pages, inspect 1 sample item first, then pack the full loop (clicks, chunked reads, `saveFile()`, pagination) or known deterministic click sequence into ONE `browser_run` call (up to 300000ms) instead of repeating small calls. Includes persistent variables (`const`/`let`/`class`), bound tabs (`browser.tabs.new()` / `browser.tabs.get(id)` / parallel `browser.tabs.content(urls)` returning structured `.links`/`.tables`), `browser.nameSession()`, `browser.groups`, auto-waiting locators (including async CKEditor sync), `locator.screenshot()` / `saveScreenshot()`, `dev.enableNetwork({ captureBodies: true })` + `dev.responseBody(id)`, `markDeliverable`/`markHandoff`, and `browser.endTurn()`/`browser.end_turn()`.",
1092
- "Diff-first & inspect-first: Start with `ariaSnapshot({ mode: \"compact\" })` or `browser_get_state` / `ax.write()` before guessing selectors; narrow multi-matches with `.first()`/`.nth(i)` and use `reload()` rather than `goto(sameUrl)`. Request `screenshot: true` / `ax.write('screenshot')` / `saveScreenshot(..., { emit: true })` when visual inspection or Proof of Work is needed.",
1093
- "Pass end_turn/keep/ungroup to browser_run or browser_batch (or call `browser.endTurn()`/`markDeliverable()` inside `browser_run`), `browser_name_session` / `browser.nameSession()` to group tabs visually, and `browser_end_turn` at the end for tabs that must survive cleanup.",
1133
+ "Real Chrome automation via local bridge. Reuse existing open user tabs via `browser.user.openTabs()` + passive `tabs.read()` / `user.claimTab()` (or `browser_list_tabs`). All agent tabs stay in the background; never pass `focus: true` or steal active tab focus.",
1134
+ "Probe 1 -> Batch Loop All: Inspect 1 sample row/modal with `ariaSnapshot({ mode: \"compact\" })`, then pack full loops (`saveFile`, `pagination`, `dev.responseBody`, `saveScreenshot`) into ONE `browser_run` call (up to 300000ms) instead of small per-step tool turns.",
1135
+ "Gotchas: `await tab.url()` is async (returns a Promise); calling `markDeliverable()`/`markHandoff()` triggers `end_turn` unless `end_turn: false` is passed; `browser.evaluate()` is read-only; pass `ungroup: true` to dissolve temporary session tab groups on completion.",
1094
1136
  ].join("\n"),
1095
1137
  },
1096
1138
  );
@@ -1099,14 +1141,26 @@ export function createStandaloneServer(deps = {}) {
1099
1141
  }
1100
1142
 
1101
1143
  export async function main() {
1144
+ process.on("unhandledRejection", (reason) => {
1145
+ console.error(
1146
+ "Browser-use unhandled rejection (contained):",
1147
+ reason instanceof Error ? reason.stack || reason.message : String(reason),
1148
+ );
1149
+ });
1150
+
1102
1151
  const server = createStandaloneServer();
1103
1152
  await server.connect(new StdioServerTransport());
1104
1153
 
1105
- const shutdown = async () => {
1106
- const browser = browserPromise ? await browserPromise.catch(() => null) : null;
1107
- browserPromise = null;
1108
- await browser?.close().catch(() => {});
1109
- process.exit(0);
1154
+ let shutdownPromise = null;
1155
+ const shutdown = () => {
1156
+ if (shutdownPromise) return shutdownPromise;
1157
+ shutdownPromise = (async () => {
1158
+ const browser = browserPromise ? await browserPromise.catch(() => null) : null;
1159
+ browserPromise = null;
1160
+ await browser?.close().catch(() => {});
1161
+ process.exit(0);
1162
+ })();
1163
+ return shutdownPromise;
1110
1164
  };
1111
1165
  process.on("SIGINT", shutdown);
1112
1166
  process.on("SIGTERM", shutdown);