codex-browser-use 4.8.3 → 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
@@ -83,6 +83,7 @@ function shouldAttachErrorState(error, msg) {
83
83
  if (
84
84
  /^Browser evaluate (is read-only|could not parse|requires a JavaScript expression)/i.test(msg) ||
85
85
  /^(saveFile|readFile|saveScreenshot) (requires|payload exceeds)/i.test(msg) ||
86
+ /\b(ENOENT|EACCES|EISDIR)\b/u.test(msg) ||
86
87
  /^Maximum \d+ images per browser_run call exceeded/i.test(msg) ||
87
88
  /^No browser tab is active/i.test(msg)
88
89
  ) {
@@ -97,17 +98,20 @@ let browserPromise = null;
97
98
  /** @returns {Promise<BridgeBrowser>} */
98
99
  async function defaultGetBrowser() {
99
100
  if (browserPromise) {
100
- const existing = await browserPromise.catch(() => null);
101
+ const pending = browserPromise;
102
+ const existing = await pending.catch(() => null);
101
103
  if (!existing || existing.isClosed?.() || existing.closed) {
102
- browserPromise = null;
104
+ if (browserPromise === pending) browserPromise = null;
103
105
  } else {
104
106
  return existing;
105
107
  }
106
108
  }
107
- browserPromise = BridgeBrowser.connect({ bridgeFile }).catch((error) => {
108
- browserPromise = null;
109
- throw error;
110
- });
109
+ if (!browserPromise) {
110
+ browserPromise = BridgeBrowser.connect({ bridgeFile }).catch((error) => {
111
+ browserPromise = null;
112
+ throw error;
113
+ });
114
+ }
111
115
  return browserPromise;
112
116
  }
113
117
 
@@ -174,6 +178,7 @@ async function withOptionalState(browser, tabId, actionResult, returnState = "no
174
178
  screenshot: returnState === "both",
175
179
  diff: returnState === "diff",
176
180
  full: returnState === "full" || returnState === "both",
181
+ mode: "compact",
177
182
  });
178
183
  return stateResponse(state, actionResult);
179
184
  }
@@ -383,6 +388,7 @@ export function registerTools(server, deps = {}) {
383
388
  full: effectiveReturnState === "full" || effectiveReturnState === "both",
384
389
  maxLines: max_lines ?? 1_500,
385
390
  mode: mode ?? "compact",
391
+ allowUnindexedBaseline: true,
386
392
  }).catch(() => null);
387
393
  if (state?.screenshotBase64) {
388
394
  images.push({ data: state.screenshotBase64, mimeType: state.screenshotMimeType || "image/jpeg" });
@@ -424,7 +430,8 @@ export function registerTools(server, deps = {}) {
424
430
  return { content };
425
431
  } catch (error) {
426
432
  const msg = error instanceof Error ? error.message : String(error);
427
- 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;
428
435
  const errState = (browser && fallbackTab != null && shouldAttachErrorState(error, msg))
429
436
  ? await browser.getState(fallbackTab, {
430
437
  screenshot: false,
@@ -434,7 +441,19 @@ export function registerTools(server, deps = {}) {
434
441
  allowUnindexedBaseline: true,
435
442
  }).catch(() => null)
436
443
  : null;
437
- 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
+ }
438
457
  if (errState?.notifications?.length) {
439
458
  parts.push(`<notifications>\n${errState.notifications.map((n) => `- ${n}`).join("\n")}\n</notifications>`);
440
459
  }
@@ -480,9 +499,19 @@ export function registerTools(server, deps = {}) {
480
499
  const fallbackTab = result.state?.tab_id ?? tab_id ?? browser.activeTabId;
481
500
  await browser.markTabs(resolveKeepEntries(keep, fallbackTab)).catch(() => {});
482
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
+ });
483
511
  const summary = {
484
512
  ok: result.ok,
485
513
  completed_steps: result.completed_steps.length,
514
+ ...(stepResults.length > 0 ? { step_results: stepResults } : {}),
486
515
  ...(result.ok ? {} : { failed_step: result.failed_step, error: result.error }),
487
516
  ...(endTurnResult ? { end_turn: endTurnResult } : {}),
488
517
  };
@@ -590,7 +619,7 @@ export function registerTools(server, deps = {}) {
590
619
  full_page: z.boolean().optional().describe("Full-page screenshot when screenshot=true"),
591
620
  format: z.enum(["jpeg", "png"]).optional().describe("Screenshot format (default jpeg)"),
592
621
  full: z.boolean().optional().describe("Return full AX tree instead of diff"),
593
- mode: axModeEnum.optional().describe("AX mode: full (default), compact, or interactive"),
622
+ mode: axModeEnum.optional().describe("AX mode: compact (default), full, or interactive"),
594
623
  max_lines: z.number().int().min(1).max(10_000).optional().describe("Max accessibility lines (default 2000)"),
595
624
  },
596
625
  guarded(async ({ tab_id, screenshot, full_page, format, full, mode, max_lines }) => stateResponse(
@@ -600,7 +629,7 @@ export function registerTools(server, deps = {}) {
600
629
  format: format ?? "jpeg",
601
630
  diff: full !== true,
602
631
  full: full === true,
603
- mode: mode ?? "full",
632
+ mode: mode ?? "compact",
604
633
  maxLines: max_lines ?? 2_000,
605
634
  }),
606
635
  )),
@@ -924,7 +953,12 @@ export function registerTools(server, deps = {}) {
924
953
  ? { ...(format ? { format } : {}), ...(max_chars !== undefined ? { maxChars: max_chars } : {}) }
925
954
  : undefined;
926
955
  const result = await (await getBrowser()).getContent(tab_id, opts);
927
- 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);
928
962
  }),
929
963
  );
930
964
 
@@ -933,7 +967,7 @@ export function registerTools(server, deps = {}) {
933
967
  "Return a compact visible DOM tree (default) or clean YAML ARIA snapshot (`format=\"aria\"`) for fast selector discovery or line filtering.",
934
968
  {
935
969
  format: z.enum(["dom", "aria"]).optional().describe('Snapshot format: "dom" (compact visible DOM) or "aria" (YAML ARIA tree). Defaults to "dom"'),
936
- 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"),
937
971
  max_chars: z.number().int().min(1_000).max(100_000).optional().describe("Character limit for DOM format. Defaults to 24000"),
938
972
  max_lines: z.number().int().min(1).max(10_000).optional().describe("Line limit for ARIA format. Defaults to 2000"),
939
973
  tab_id: stringOrNumber.optional().describe("Optional tab_id"),
@@ -942,7 +976,7 @@ export function registerTools(server, deps = {}) {
942
976
  await (await getBrowser()).domSnapshot({
943
977
  tabId: tab_id,
944
978
  format: format ?? "dom",
945
- mode: mode ?? "full",
979
+ mode: mode ?? "compact",
946
980
  maxChars: max_chars ?? 24_000,
947
981
  maxLines: max_lines ?? 2_000,
948
982
  }),
@@ -1061,12 +1095,13 @@ export function registerTools(server, deps = {}) {
1061
1095
  "browser_end_turn",
1062
1096
  "End agent turn: keep handoff/deliverable tabs open and close unmarked tabs.",
1063
1097
  {
1064
- keep: z.array(keepEntrySchema).optional().describe("Kept tabs"),
1098
+ keep: keepParamSchema.optional().describe('Keep mode ("handoff"|"deliverable") or [{ tab_id, mode }]'),
1065
1099
  ungroup: z.boolean().optional().describe("Ungroup tabs on finish"),
1066
1100
  },
1067
1101
  guarded(async ({ keep, ungroup }) => {
1068
1102
  const browser = await getBrowser();
1069
- 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 });
1070
1105
  scriptSession.syncActiveTab(browser);
1071
1106
  return text(res);
1072
1107
  }),
@@ -1092,14 +1127,12 @@ export function registerTools(server, deps = {}) {
1092
1127
  export function createStandaloneServer(deps = {}) {
1093
1128
  const profile = deps.profile ?? resolveToolProfile();
1094
1129
  const server = new McpServer(
1095
- { name: "browser-use", version: "4.8.3" },
1130
+ { name: "browser-use", version: "4.9.0" },
1096
1131
  {
1097
1132
  instructions: [
1098
- "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.",
1099
- "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. Keep all agent tabs in the background and never pass `focus: true` or steal focus from the user's active tab. Close ephemeral tabs with `keep: []` and pass `ungroup: true` when finishing if kept tabs no longer need a group label.",
1100
- "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()`.",
1101
- "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.",
1102
- "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.",
1103
1136
  ].join("\n"),
1104
1137
  },
1105
1138
  );
@@ -1118,11 +1151,16 @@ export async function main() {
1118
1151
  const server = createStandaloneServer();
1119
1152
  await server.connect(new StdioServerTransport());
1120
1153
 
1121
- const shutdown = async () => {
1122
- const browser = browserPromise ? await browserPromise.catch(() => null) : null;
1123
- browserPromise = null;
1124
- await browser?.close().catch(() => {});
1125
- 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;
1126
1164
  };
1127
1165
  process.on("SIGINT", shutdown);
1128
1166
  process.on("SIGTERM", shutdown);