@jackwener/browsermcp 0.0.34-embedded.1 → 0.0.34

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 (115) hide show
  1. package/CHANGELOG.md +2 -12
  2. package/README.md +1 -93
  3. package/dist/docs/api-reference.md +15 -6
  4. package/dist/docs/errors.md +24 -0
  5. package/dist/docs/js-tool.md +12 -2
  6. package/dist/docs/tab-lifecycle.md +3 -3
  7. package/dist/src/api/api.js +2 -1
  8. package/dist/src/api/api.js.map +1 -1
  9. package/dist/src/api/browser.js +23 -4
  10. package/dist/src/api/browser.js.map +1 -1
  11. package/dist/src/api/tab.js +23 -7
  12. package/dist/src/api/tab.js.map +1 -1
  13. package/dist/src/backends/extension-page.js +8 -1
  14. package/dist/src/backends/extension-page.js.map +1 -1
  15. package/dist/src/docs/manifest.js +3 -6
  16. package/dist/src/docs/manifest.js.map +1 -1
  17. package/dist/src/mcp/js-session.js +29 -18
  18. package/dist/src/mcp/js-session.js.map +1 -1
  19. package/dist/src/mcp/js-worker.mjs +51 -15
  20. package/dist/src/mcp/server.js +2 -2
  21. package/dist/src/mcp/server.js.map +1 -1
  22. package/dist/src/protocol.js +1 -1
  23. package/dist/src/protocol.js.map +1 -1
  24. package/dist/src/runtime/runtime.js +2 -2
  25. package/dist/src/runtime/runtime.js.map +1 -1
  26. package/dist/src/shared/api-contract.js +117 -0
  27. package/dist/src/shared/api-contract.js.map +1 -0
  28. package/docs/api-reference.md +15 -6
  29. package/docs/errors.md +24 -0
  30. package/docs/js-tool.md +12 -2
  31. package/docs/releasing.md +14 -3
  32. package/docs/tab-lifecycle.md +3 -3
  33. package/extension/dist/background.js +20046 -278
  34. package/package.json +4 -13
  35. package/dist/src/api/action-input.d.ts +0 -47
  36. package/dist/src/api/agent.d.ts +0 -10
  37. package/dist/src/api/api.d.ts +0 -50
  38. package/dist/src/api/browser.d.ts +0 -89
  39. package/dist/src/api/context.d.ts +0 -7
  40. package/dist/src/api/diff.d.ts +0 -8
  41. package/dist/src/api/errors.d.ts +0 -12
  42. package/dist/src/api/network.d.ts +0 -10
  43. package/dist/src/api/observation.d.ts +0 -4
  44. package/dist/src/api/streams.d.ts +0 -13
  45. package/dist/src/api/tab.d.ts +0 -308
  46. package/dist/src/api/webmcp.d.ts +0 -19
  47. package/dist/src/backends/backend.d.ts +0 -14
  48. package/dist/src/backends/browser-helpers.d.ts +0 -17
  49. package/dist/src/backends/extension-page.d.ts +0 -5
  50. package/dist/src/backends/managed-page.d.ts +0 -57
  51. package/dist/src/backends/page-transport.d.ts +0 -10
  52. package/dist/src/backends/page-types.d.ts +0 -82
  53. package/dist/src/docs/embedded.d.ts +0 -2
  54. package/dist/src/docs/embedded.js +0 -35
  55. package/dist/src/docs/embedded.js.map +0 -1
  56. package/dist/src/docs/manifest.d.ts +0 -23
  57. package/dist/src/docs/surface.d.ts +0 -12
  58. package/dist/src/electron/backend.d.ts +0 -48
  59. package/dist/src/electron/backend.js +0 -360
  60. package/dist/src/electron/backend.js.map +0 -1
  61. package/dist/src/electron/chrome.d.ts +0 -24
  62. package/dist/src/electron/chrome.js +0 -133
  63. package/dist/src/electron/chrome.js.map +0 -1
  64. package/dist/src/electron/driver.d.ts +0 -42
  65. package/dist/src/electron/driver.js +0 -238
  66. package/dist/src/electron/driver.js.map +0 -1
  67. package/dist/src/electron/event-buffer.d.ts +0 -16
  68. package/dist/src/electron/event-buffer.js +0 -59
  69. package/dist/src/electron/event-buffer.js.map +0 -1
  70. package/dist/src/electron/page.js +0 -834
  71. package/dist/src/electron/registry.d.ts +0 -93
  72. package/dist/src/electron/registry.js +0 -259
  73. package/dist/src/electron/registry.js.map +0 -1
  74. package/dist/src/electron/streams.d.ts +0 -16
  75. package/dist/src/electron/streams.js +0 -48
  76. package/dist/src/electron/streams.js.map +0 -1
  77. package/dist/src/embedded/index.d.ts +0 -41
  78. package/dist/src/embedded/index.js +0 -69
  79. package/dist/src/embedded/index.js.map +0 -1
  80. package/dist/src/host/bridge.d.ts +0 -50
  81. package/dist/src/host/doctor.d.ts +0 -34
  82. package/dist/src/host/extension.d.ts +0 -3
  83. package/dist/src/host/host.d.ts +0 -3
  84. package/dist/src/host/ipc.d.ts +0 -14
  85. package/dist/src/host/jsonc-config.d.ts +0 -1
  86. package/dist/src/host/launch.d.ts +0 -11
  87. package/dist/src/host/native-messaging.d.ts +0 -28
  88. package/dist/src/host/opencode.d.ts +0 -6
  89. package/dist/src/host/pi.d.ts +0 -6
  90. package/dist/src/host/registration.d.ts +0 -24
  91. package/dist/src/host/setup.d.ts +0 -7
  92. package/dist/src/host/socket.d.ts +0 -25
  93. package/dist/src/host/state.d.ts +0 -39
  94. package/dist/src/launcher/stdio.d.ts +0 -3
  95. package/dist/src/lib/paths.d.ts +0 -1
  96. package/dist/src/lib/sources.d.ts +0 -5
  97. package/dist/src/main.d.ts +0 -2
  98. package/dist/src/mcp/catalog.d.ts +0 -202
  99. package/dist/src/mcp/js-session.d.ts +0 -63
  100. package/dist/src/mcp/server.d.ts +0 -15
  101. package/dist/src/protocol.d.ts +0 -318
  102. package/dist/src/recon/analyzer.d.ts +0 -43
  103. package/dist/src/recon/discover.d.ts +0 -48
  104. package/dist/src/runtime/runtime.d.ts +0 -148
  105. package/dist/src/shared/aria-tree.d.ts +0 -2
  106. package/dist/src/shared/element-ref.d.ts +0 -4
  107. package/dist/src/shared/engine.d.ts +0 -50
  108. package/dist/src/shared/injected-source.d.ts +0 -2
  109. package/dist/src/shared/page-contract.d.ts +0 -256
  110. package/dist/src/sites/define.d.ts +0 -28
  111. package/dist/src/sites/drafts.d.ts +0 -39
  112. package/dist/src/sites/executor.d.ts +0 -34
  113. package/dist/src/sites/loader.d.ts +0 -84
  114. package/dist/src/sites/schema.d.ts +0 -11
  115. package/dist/src/version.d.ts +0 -2
package/CHANGELOG.md CHANGED
@@ -1,18 +1,8 @@
1
1
  # Changelog
2
2
 
3
- ## 0.0.34-embedded.1 — 2026-10-21
3
+ ## 0.0.34 — 2026-10-22
4
4
 
5
- - Model host tabs independently of WebContents, with stable logical IDs, explicit active selection, metadata updates and lazy loading.
6
- - Expose typed host events and snapshots with public MCP session IDs; reserve ownership during loading and roll back or cancel failed/revoked claims.
7
- - Unify tab state across MCP and Chrome APIs, and default MCP version to the installed package version.
8
- - Migration: use registerPage handles and reported tabId values; tabId no longer equals webContents.id. Synchronize host selection with setActivePage(scope, handle).
9
- - Share runtime isolation, storage injection, package version resolution and release infrastructure with main.
10
-
11
- ## 0.0.34-embedded.0 — 2026-10-21
12
-
13
- - Add the embedded Electron SDK with host-owned storage, profiles and page lifecycle.
14
- - Support MCP sessions, adapter creation and updates, Chrome API compatibility and CDP in embedded Chromium.
15
- - Import @jackwener/browsermcp/embedded without CLI setup or a Chrome extension.
5
+ Enforce strict evaluate options and lossless REPL call transport. Separate user data from internal RPC references. Return explicit tab discovery scope, counts and pagination using shared backend contracts. Reject malformed backend responses. Protocol revision 4 requires updating host and extension together; read openTabs results from items.
16
6
 
17
7
  ## 0.0.33 — 2026-10-20
18
8
 
package/README.md CHANGED
@@ -98,7 +98,7 @@ await tab.observe();
98
98
 
99
99
  Variables, functions, classes and Tab handles persist across calls. After inspecting the result, use `await tab.act(...)` and `await tab.expect(...)` or observe again. Keep working data in variables and return only relevant evidence. `docs_get {}` provides a compact quickstart; `{name:"api-reference",member:"Tab.act"}` provides exact types. No repository documentation access is required.
100
100
 
101
- Use `browser.user.openTabs({query,limit})` and `browser.user.claimTab(...)` for user tabs. The lookup returns up to 20 recent matches by default. `tab.release()` leaves a tab open; `tab.close()` closes it. `session_finalize` closes agent tabs not kept and releases borrowed tabs. `js_reset` stops JavaScript and clears bindings while leaving tabs open; already dispatched operations may still complete. All API methods are awaited.
101
+ Use `browser.user.openTabs({query,limit})` and `browser.user.claimTab(...)` for user tabs. The lookup returns a discovery envelope: read `items`, `matched`, `totalInScope`, `excluded` and `hasMore`. It returns up to 20 recent matches by default; continue with `offset: nextOffset`. `tab.release()` leaves a tab open; `tab.close()` closes it. `session_finalize` closes agent tabs not kept and releases borrowed tabs. `js_reset` stops JavaScript and clears bindings while leaving tabs open; already dispatched operations may still complete. All API methods are awaited.
102
102
 
103
103
  Inside the `js` tool, you can also call site commands directly:
104
104
 
@@ -143,98 +143,6 @@ Site commands execute directly without additional approval prompts. The read/wri
143
143
  | [Tab lifecycle](docs/tab-lifecycle.md) | Claiming tabs, grouping, and cleanup |
144
144
  | [Errors](docs/errors.md) | Error codes and recovery |
145
145
 
146
- ## Embedded Electron applications
147
-
148
- Import `@jackwener/browsermcp/embedded` from Electron's main process. This entry does not run setup, register Native Messaging, discover Chrome, read global CLI configuration, or install an extension. The application supplies its writable directory, profile sessions, and page lifecycle callbacks. Adapters can still be created, verified, activated, updated, and removed through `tools`.
149
-
150
- ```ts
151
- import { app, BrowserWindow, session } from 'electron';
152
- import path from 'node:path';
153
- import { createEmbeddedBrowser } from '@jackwener/browsermcp/embedded';
154
-
155
- await app.whenReady();
156
- const windows = new Map<number, BrowserWindow>();
157
- const profile = ({ profileId }) => session.fromPartition(`persist:${profileId}`);
158
- const browser = await createEmbeddedBrowser({
159
- dataDir: path.join(app.getPath('userData'), 'browsermcp'),
160
- execution: 'trusted-node',
161
- browser: {
162
- profile,
163
- async createPage(scope) {
164
- const window = new BrowserWindow({
165
- webPreferences: {
166
- session: profile(scope), contextIsolation: true,
167
- sandbox: true, nodeIntegration: false,
168
- },
169
- });
170
- const id = window.webContents.id;
171
- windows.set(id, window);
172
- window.once('closed', () => windows.delete(id));
173
- return window.webContents;
174
- },
175
- async closePage(contents) { windows.get(contents.id)?.destroy(); },
176
- async activatePage(contents) { windows.get(contents.id)?.show(); },
177
- },
178
- });
179
-
180
- // Scope comes from the application, not from agent-provided MCP arguments.
181
- const connection = browser.createSession({ workspaceId: 'project-a', profileId: 'personal' });
182
- await connection.server.connect(transport); // Any host-provided MCP SDK transport.
183
- // On disconnect, cleanup is automatic. Explicit close and application shutdown:
184
- await connection.close();
185
- await browser.dispose();
186
- ```
187
-
188
- The host owns logical tabs; a tab does not need a `WebContents` until it is claimed. Register restored tabs immediately, and synchronize selection from the host UI:
189
-
190
- ```ts
191
- const scope = { workspaceId: 'workspace', profileId: 'personal' };
192
- const handle = browser.registerPage({
193
- scope,
194
- url: restoredTab.url,
195
- title: restoredTab.title,
196
- load: async (signal) => {
197
- // Resolve only once the restored tab has loaded; honor cancellation.
198
- return hostTabs.ensureLoaded(restoredTab.id, { signal });
199
- },
200
- close: async () => { await hostTabs.close(restoredTab.id); },
201
- });
202
- browser.setActivePage(scope, handle); // Call on each host selection change.
203
- browser.updatePage(handle, { url: restoredTab.url, title: restoredTab.title });
204
- const unsubscribe = browser.subscribe((event) => {
205
- // event.sessionId matches createSession().id, with no internal prefix.
206
- // event.page.sessionId is the current owner; undefined after release.
207
- hostTabs.setAgentOwner(event.page.handle, event.page.sessionId);
208
- });
209
- const snapshot = browser.getPages(scope); // Initialize/reconcile host UI.
210
- ```
211
-
212
- `registerPage(contents, scope)` remains supported for already loaded pages. For restored tabs, pass metadata and `load(signal)` (optionally existing contents); enumeration and matching do not trigger loading. A claim reserves exclusive ownership before loading, validates the resolved Electron profile, and returns only after loading succeeds. Failed loads return an unowned tab to the pool. Loading is cancelled on release, unregister, or session cleanup, and is bounded to 30 seconds. A host must honor the signal to prevent its own late side effects; BrowserMCP never attaches a result after access is revoked. A destroyed lazy page returns to dormant state and can be restored again; its logical identity remains stable. `close()` closes a dormant host tab without loading it.
213
-
214
- **Identity contract:** the returned handle and the numeric `tabId` in `getPages()` / agent tab lists belong to BrowserMCP. `tabId` is not `webContents.id`. Use the handle to map to your host tab and use the reported `tabId` for Chrome-shaped calls. Both stay stable across loading. This changes the implicit `webContents.id` behavior in `0.0.34-embedded.0` and the original vendored branch.
215
-
216
- `setActivePage(scope, handle | null)` is authoritative; keyboard focus is never used to infer the selected tab. Each workspace/profile has at most one active tab. `openTabs`, `claimTab({ active: true })`, owned-tab lists and `chrome.tabs.query` read the same registry state. `activatePage(contents)` implements agent-requested activation, after which the registry selection is updated. A zero-match claim reports `tab_not_found`; multiple matches report `ambiguous_tab`.
217
-
218
- Host `subscribe()` emits typed snapshots for registration, metadata/lifecycle changes, activation, acquisition, release, navigation, closure and unregister. Acquisition is idempotent for the same session. Listener exceptions cannot break ownership transitions. Subscribe before taking `getPages(scope)` when initializing UI, and unsubscribe when disposing it. MCP version defaults to the installed BrowserMCP package version; explicit `version` remains available for bundled hosts.
219
-
220
- The callbacks can manage `WebContentsView` instead of `BrowserWindow`; layout is entirely application-owned. Use `browser.registerPage(contents, scope)` to make an existing user page available for claiming. Register only intended browser content, not application settings or privileged UI. `unregisterPage(handle)` revokes access without closing the page. User pages are released during cleanup; unkept agent pages are closed. Profile IDs must map to the intended Electron `Session`, and the backend checks this identity when registering/creating pages.
221
-
222
- The current evaluator explicitly requires **trusted Node execution**. REPL and adapter modules can access Node capabilities; neither `vm`, a Worker, nor page registration is a sandbox against malicious host code. The REPL runs in a Worker; adapter modules execute in the runtime process. This main-process entry is for applications that trust the connected agent and loaded adapter code. Browser pages should retain `sandbox: true`, `contextIsolation: true`, and `nodeIntegration: false`.
223
-
224
- Storage is confined by configuration: generated adapters are in `<dataDir>/adapters`, inactive candidates in `<dataDir>/drafts`, and a small standalone adapter SDK in `<dataDir>/node_modules`. No implicit `~/.browsermcp` or `~/.opencli-mcp` source is loaded. Optional `sources` are explicit; generated adapters override them. Adapter code is shared within the service, while execution uses the caller's authorized profile and pages. No login credentials are copied between profiles.
225
-
226
- `browser.chrome.call/describe/watch` remain available. Electron implements `tabs.query/get/create/update/remove/reload` and `cookies.getAll/get/set/remove`, plus session-scoped `tabs.onCreated/onUpdated/onRemoved/onActivated` events. Call `describe` for method availability and differences. Only registered, accessible tabs are returned; `windowId` is `-1` because window organization belongs to the host. Unsupported methods/options return `capability_unavailable`. Page-scoped CDP is available through `tab.cdp.send`; browser-wide `Target.*` and `Browser.*` commands are rejected. This is an explicit compatibility surface, not an emulation of every extension API.
227
-
228
- Package the generated `dist`, `docs`, and `adapter-sdk` resources with the npm package. When using ASAR, unpack `**/js-*.mjs` so the REPL worker and evaluator remain loadable. Keep Electron as an application dependency; it is only a development dependency here. Call `dispose()` before quitting, await it, and handle cleanup failures; it is safe to retry. The SDK does not install process exit handlers or call `process.exit()`.
229
-
230
- Validation:
231
-
232
- ```bash
233
- npm run build:embedded # SDK and page resources; no extension build required
234
- npm run smoke:embedded # real Electron + MCP, two profiles, adapter editing, cleanup
235
- npm run smoke:embedded:package # installed npm package inside app.asar
236
- ```
237
-
238
146
  ## Development
239
147
 
240
148
  ```bash
@@ -34,13 +34,13 @@ class Browser {
34
34
  };
35
35
  tabs: {
36
36
  new(url?: string): Promise<Tab>;
37
- list(): Promise<Array<{ id?: string; tabId: number; pending?: true; url?: string; title?: string; active: boolean; selected: boolean; origin: "agent" | "user"; state: "active" | "handoff"; }>>;
37
+ list(): Promise<Array<{ id?: string; tabId: number; pending?: true; url?: string; title?: string; active: boolean; selected: boolean; lifecycle?: "dormant" | "loading" | "ready"; origin: "agent" | "user"; state: "active" | "handoff"; }>>;
38
38
  get(tab: string | { tab?: string; tabId: number; }, opts?: { timeoutMs?: number; }): Promise<Tab>;
39
39
  selected(): Promise<Tab | undefined>;
40
40
  finalize(opts?: { keep?: Array<{ tab: string | Tab; status: "handoff" | "deliverable"; }>; }): Promise<{ closed: Array<string>; kept: Array<string>; failed: Array<{ page: string; reason: string; }>; }>;
41
41
  };
42
42
  user: {
43
- openTabs(options?: { query?: string; limit?: number; }): Promise<Array<UserTabInfo>>;
43
+ openTabs(...args: [options?: { query?: string | undefined; limit?: number | undefined; offset?: number | undefined; }]): Promise<{ scope: "unclaimed"; query: string; matching: "case-insensitive-substring"; totalVisible: number; totalInScope: number; excluded: { owned: number; unsupported: number; }; matched: number; offset: number; limit: number; hasMore: boolean; items: Array<{ tabId: number; windowId: number; active: boolean; title?: string | undefined; url?: string | undefined; groupId?: number | undefined; lastAccessed?: number | undefined; lifecycle?: "dormant" | "loading" | "ready" | undefined; availability?: "ready" | "load_required" | "host_attachment_required" | undefined; }>; nextOffset?: number | undefined; }>; // Unclaimed supported tabs in the visible scope. Query is trimmed, case-insensitive literal substring of URL OR title (no token splitting). Inspect items, matched, totalInScope, excluded and hasMore; continue with nextOffset. Each call takes a fresh snapshot.
44
44
  claimTab(tab: { tabId?: number; active?: boolean; title?: string; url?: string; expectedUrl?: string; expectedTitle?: string; }): Promise<Tab>; // Claim by foreground, id, or unique url/title lookup; expected fields verify the tab's current identity.
45
45
  closeTabs(tabIds: Array<number>): Promise<CloseUserTabsResult>; // Close user tabs by Chrome id without claiming or loading their pages.
46
46
  };
@@ -53,9 +53,12 @@ class Browser {
53
53
  }
54
54
 
55
55
  class Tab {
56
- tabId?: number; // `id` is the Chrome tab id as a string; `tabId` is the numeric id when claimed from a user tab.
56
+ tabId?: number; // `id` is the stable backend page handle; `tabId` is the numeric backend id when claimed from a user tab.
57
57
  id: string;
58
58
  goto(url: string, opts?: { waitUntil?: "load" | "none"; settleMs?: number; }): Promise<{ url: string | null; title: string | null; }>;
59
+ markDeliverable(): Promise<void>; // Preserve this tab for the user when the session is finalized.
60
+ markHandoff(): Promise<void>; // Preserve this tab for a subsequent turn; it must be claimed again after finalization.
61
+ clearRetention(): Promise<void>; // Restore default cleanup: close agent tabs, release borrowed user tabs.
59
62
  url(): Promise<string | null>;
60
63
  title(): Promise<string | null>;
61
64
  back(): Promise<void>;
@@ -74,7 +77,7 @@ class Tab {
74
77
  call(name: string, input?: Record<string, unknown>, options?: { frame?: FrameStep | Array<FrameStep>; }): Promise<unknown>;
75
78
  };
76
79
  expect(what: Expectation, opts?: { timeoutMs?: number; }): Promise<CheckResult>; // Assert what the page must show now (polled up to timeoutMs).
77
- evaluate(script: string | ((arg: any) => any), opts?: { arg?: unknown; frame?: FrameStep | Array<FrameStep>; timeoutMs?: number; }): Promise<unknown>; // Main World page code; functions receive only opts.arg, never host closures. Dispatched scripts are never replayed.
80
+ evaluate(script: string | ((arg: any) => any), opts?: { arg?: unknown; frame?: string | number | Array<string | number> | undefined; timeoutMs?: number | undefined; }): Promise<unknown>; // Main World page code; functions receive only opts.arg, never host closures. Dispatched scripts are never replayed.
78
81
  cdp: { // Native CDP on this Tab's shared debugger attachment. Parameters are not rewritten.
79
82
  send(method: string, params?: Record<string, unknown>, target?: { frameId: string; }): Promise<unknown>;
80
83
  watch(event: string, options?: StreamOptions): Promise<EventStream>;
@@ -164,8 +167,6 @@ interface DialogInfo { type: 'alert' | 'confirm' | 'prompt' | 'beforeunload'; me
164
167
 
165
168
  interface ConsoleEntry { seq: number; level: 'debug' | 'info' | 'log' | 'warn' | 'error'; message: string; timestamp: string; url?: string; line?: number }
166
169
 
167
- interface UserTabInfo { tabId: number; title?: string; url?: string; windowId: number; active: boolean; groupId?: number; lastAccessed?: number }
168
-
169
170
  interface CloseUserTabsResult {
170
171
  complete: boolean;
171
172
  closed: number[];
@@ -190,6 +191,14 @@ interface DownloadWaitResult {
190
191
  elapsedMs: number;
191
192
  }
192
193
 
194
+ type EvaluateOptions = { arg?: unknown; frame?: string | number | Array<string | number> | undefined; timeoutMs?: number | undefined; };
195
+
196
+ type TabDiscoveryOptions = { query?: string | undefined; limit?: number | undefined; offset?: number | undefined; };
197
+
198
+ type UserTabInfo = { tabId: number; windowId: number; active: boolean; title?: string | undefined; url?: string | undefined; groupId?: number | undefined; lastAccessed?: number | undefined; lifecycle?: "dormant" | "loading" | "ready" | undefined; availability?: "ready" | "load_required" | "host_attachment_required" | undefined; };
199
+
200
+ type TabDiscoveryResult = { scope: "unclaimed"; query: string; matching: "case-insensitive-substring"; totalVisible: number; totalInScope: number; excluded: { owned: number; unsupported: number; }; matched: number; offset: number; limit: number; hasMore: boolean; items: Array<{ tabId: number; windowId: number; active: boolean; title?: string | undefined; url?: string | undefined; groupId?: number | undefined; lastAccessed?: number | undefined; lifecycle?: "dormant" | "loading" | "ready" | undefined; availability?: "ready" | "load_required" | "host_attachment_required" | undefined; }>; nextOffset?: number | undefined; };
201
+
193
202
  interface PageTool { name: string; description?: string; inputSchema?: unknown }
194
203
 
195
204
  interface PageToolsUpdate { status: 'ready' | 'unavailable'; frame: FrameStep[]; tools: Array<{ name: string; description?: string }>; truncated?: boolean }
@@ -26,3 +26,27 @@ Every error has `code`, `message`, optional `hint`, and any structured data spre
26
26
  | JavaScript | `js_error`, `js_timeout`, `js_cancelled`, `js_reset`, `js_busy`, `js_worker_failed`, `js_worker_exited` | ordinary exceptions preserve bindings; timeout, cancellation, reset and worker failure clear them. `js_busy`: wait for `doctor` javascript.pendingCalls to reach zero. See `repl-session` for execution and recovery semantics |
27
27
 
28
28
  Native browser APIs report `chrome_api_unavailable`, `chrome_api_error`, `unsupported_call_shape`, and `runtime_state_conflict`. Inspect `browser.chrome.describe(member)` for context/signatures. Streams report loss/reset in their results; `stream_closed` requires a new watch. `command_outcome_unknown` means dispatched page code may have run: inspect before retrying. `result_not_serializable` requires returning plain data.
29
+
30
+ ## Trustworthy API boundaries
31
+
32
+ `invalid_args` with `dispatched:false` rejects an invocation before browser effects; fix the indicated field and retry that call. Evaluation does not guess positional arguments or discard unknown options. REPL call transport rejects lossy values rather than applying display formatting to them.
33
+
34
+ `invalid_response` from tab discovery means a backend response violated the protocol, not that the browser has no tabs. Check `doctor` for host/backend versions. Protocol revision 4 requires the discovery envelope; update host and extension together.
35
+
36
+ For discovery, `totalInScope:0` means no eligible unclaimed tabs in the visible scope; `totalInScope>0, matched:0` means no literal query match. `excluded` explains ownership and unsupported-page exclusions. `hasMore` distinguishes a partial result from a complete match set. Search emptiness is not an exception.
37
+
38
+ Issues #18 and #19 exposed different evidence: #18's silent argument loss is reproducible. #19's literal `x.com/home` query matches `https://x.com/home` in the reported version's implementation; its reported live discrepancy is not established by that example alone. The discovery envelope and strict response validation address the confirmed ambiguity without asserting an unverified incident cause.
39
+
40
+ The design borrows explicit tool contracts from OpenAI's public function-calling guidance (https://developers.openai.com/api/docs/guides/function-calling) and observe/action feedback from the publicly described ChatGPT agent (https://openai.com/index/introducing-chatgpt-agent/). These sources do not disclose ChatGPT's internal tab-search implementation. In this REPL, an MCP schema for the outer `code` string cannot validate nested JavaScript API calls; runtime contracts remain necessary.
41
+
42
+ ### Local client implementation evidence
43
+
44
+ A read-only inspection of the locally installed ChatGPT.app ASAR on 2026-10-22 found package `openai-codex-electron` version `26.1007.30912`. In `.vite/build/main-CqEoQDOU.js` (SHA-256 `09d19386e1f23cf4ccbc950fc40d85a1e8a064a08be588b2a4be6a89f6ada9e6`), these named methods remain visible in the bundled JavaScript:
45
+
46
+ - `getTabsForBrowserUse` and `serializeTab`: build inventory from host metadata and optional live runtime, expose stable provider identity and session-control status, and choose an active tab. This layer has no query argument; it does not establish how a separate search API works.
47
+ - `requireLiveTab`: recover a missing execution resource only when a concrete tab is needed. Inventory survives WebContents destruction.
48
+ - `requireBrowserUseTab`: enforce the session route before access.
49
+ - `assertTabMatchesCurrentBrowserUsePage`: check page identity and WebContents identity/liveness before dispatch, including after asynchronous waits.
50
+ - `runLoggedRequest`: attach session/request/turn context to failures and rethrow them.
51
+
52
+ These are observations of the installed desktop bundle, not claims about ChatGPT's server implementation or original source. We independently implement shared discovery contracts and retain host-owned logical tabs. We do not adopt its fallback to the first tab as an indication of the user's foreground intent. No vendor code is included in this repository.
@@ -13,9 +13,11 @@ await tab.observe();
13
13
  Or borrow a user tab:
14
14
  ```js
15
15
  let matches = await browser.user.openTabs({query: 'example.com', limit: 20});
16
- matches;
16
+ matches.items;
17
17
  ```
18
- Copy its numeric `tabId` into `await browser.user.claimTab({tabId: ...})`. Store the returned Tab handle, then observe it. Session handles come from `await browser.tabs.list()` and `await browser.tabs.get(id)`.
18
+ The result reports `totalVisible`, `totalInScope`, `excluded`, `matched`, and `hasMore`. `scope:"unclaimed"` excludes actively owned and unsupported tabs. Query is a trimmed case-insensitive literal substring of URL OR title, without whitespace token splitting. For more results, pass `offset: matches.nextOffset` with the same query and limit; each call is a fresh snapshot. Zero matches is a valid result; invalid transport responses are errors.
19
+
20
+ Copy an item’s numeric `tabId` into `await browser.user.claimTab({tabId: ...})`. Store the returned Tab handle, then observe it. Session handles come from `await browser.tabs.list()` and `await browser.tabs.get(id)`.
19
21
 
20
22
  After reading the observation, call `await tab.act({action:'click', target:{ref: '...'}})` using a returned ref, then `await tab.observe()` or `await tab.expect({text:'...'})` with the expected result. `await tab.read()` reads document text. Batch determined steps; return at new decision points.
21
23
 
@@ -34,3 +36,11 @@ Refs are opaque Element identities shared by ARIA, DOM and find. Copy them uncha
34
36
  Finish with `session_finalize`. Use `doctor` for connection/execution status and `js_reset` to stop JavaScript, clear bindings and close explicit subscriptions; tabs stay open. Read `repl-session` for Node declaration semantics, errors, timeout/reset and images. Request `api-reference` with `member:"Tab.act"`, `"Tab.network"`, `"Browser"` or another class/member for exact signatures; omit member for the full reference.
35
37
 
36
38
  Reuse the same target for verification: `await tab.expect({target, value:"42"})`. Continue captured output with `tab.observe(result.next)` or `tab.read(result.next)`. Pass an `openedTabs` entry directly to `browser.tabs.get`, and the returned download object to `tab.download(result.download)`.
39
+
40
+ Tab handles expose async methods: use `await tab.url()` and `await tab.title()`. Entries returned by `browser.tabs.list()` are snapshots with string `url` and `title` fields. Inspecting or converting a remote method to a string describes the method locally; it never reads the page.
41
+
42
+ ### Page evaluation contract
43
+
44
+ Use `await tab.evaluate(value => value, {arg: data})`. The second argument is a strict options object with only `arg`, `frame`, and `timeoutMs`; extra positional arguments and unknown fields fail before dispatch. Source strings do not accept `arg`. Functions run in the page and cannot capture REPL variables.
45
+
46
+ Arguments are plain JSON data: null, booleans, strings, finite numbers (excluding negative zero), dense arrays and plain objects. Root `arg: undefined` is allowed. Nested undefined, non-finite numbers, BigInt, functions, special objects, accessors, symbol keys and cycles are rejected, never silently rewritten. Convert special values explicitly. API handles can be passed to APIs that accept them; they are not page data. Errors with `dispatched:false` mean the rejected invocation had no page effects. This does not undo earlier calls in the same cell.
@@ -2,13 +2,13 @@
2
2
 
3
3
  Use these methods in `js`, awaiting every call. Start with `await browser.nameSession('🔎 Research')`, then `let tab = await browser.tabs.new(url)`. Agent-created tabs open in a named Chrome group, in the background, muted until the user looks at them.
4
4
 
5
- To use an existing tab, call `await browser.user.openTabs({query:'…',limit:20})`, then `let tab = await browser.user.claimTab({tabId})`. Discovery is recency-sorted, defaults to 20 matches and is capped at 100; it is not a complete browser inventory. To claim the foreground tab, use `{active:true}`. Unique URL/title lookup is also supported; `expectedUrl` and `expectedTitle` check exact identity when necessary. Claiming alone does not observe the page. Claimed user tabs stay outside the agent group and are never closed by finalize.
5
+ To use an existing tab, call `await browser.user.openTabs({query:'…',limit:20})`, then `let tab = await browser.user.claimTab({tabId})`. Read the returned `items` array. Discovery reports its `scope:"unclaimed"`, visible/in-scope totals, excluded owned/unsupported counts, and match count. Matching is a trimmed, case-insensitive literal substring of URL OR title (no token splitting). Results are recency-sorted with tabId as a tie-breaker, default to 20 and allow up to 100 per page. Continue with `offset: nextOffset` while `hasMore`; each request is a fresh snapshot, so tab changes can shift pagination. Discovery never claims or loads a tab. To claim the foreground tab, use `{active:true}`. Unique URL/title lookup is also supported; `expectedUrl` and `expectedTitle` check exact identity when necessary. Claiming alone does not observe the page. Claimed user tabs stay outside the agent group and are never closed by finalize.
6
6
 
7
- `await browser.tabs.list()` returns controlled tabs with string `id`, numeric Chrome `tabId`, `origin` and `state`. Obtain a handle with `await browser.tabs.get(id)`. The page id is stable across navigation and becomes stale after closure. An older extension may return `pending:true` without an id; match its numeric `tabId` on a later list call. Unknown ids are rejected rather than adopted.
7
+ `await browser.tabs.list()` returns controlled tabs with string `id`, numeric backend `tabId`, `origin` and `state`. Obtain a handle with `await browser.tabs.get(id)`. The page id is stable across navigation and becomes stale after logical closure. In Electron it also survives WebContents replacement; `lifecycle` reports dormant, loading or ready. A newly attaching extension tab may return `pending:true` without an id; match its numeric `tabId` on a later list call. Unknown ids are rejected rather than adopted.
8
8
 
9
9
  `await tab.release()` keeps the tab open and gives up control; an agent-created tab leaves only its temporary session group and is unmuted unless its mute state is native (a raw-created tab or an explicit `tabs.update({muted})` call). User-arranged groups are preserved. `await tab.close()` closes a controlled tab. For bulk user-tab cleanup, use `await browser.user.closeTabs([tabId1,tabId2])` without claiming; its result reports `closed` and `failed` ids. Keep discovery and planning in REPL variables, and return a summary before the next decision. Do not move every row into the conversation.
10
10
 
11
- Finish with the MCP tool `session_finalize`, or `await browser.tabs.finalize({keep:[{tab,status:'deliverable'}]})` in `js`. `deliverable` tabs leave temporary session groups and stay open; explicitly arranged groups are preserved; `handoff` tabs stay grouped for a later turn; other agent tabs close. Failed tabs retain their lease for retry. After successful finalize, old handles are released; obtain fresh handles in a later turn. Let running JavaScript finish before calling the separate finalize tool.
11
+ Prefer `await tab.markDeliverable()` to preserve a result, `await tab.markHandoff()` to retain control for a later turn, and `await tab.clearRetention()` to remove a mark. Marks belong to the logical tab and do not require a loaded page. Finish with the MCP tool `session_finalize`, or `await browser.tabs.finalize({keep:[{tab,status:'deliverable'}]})` in `js`. Explicit keep entries override stored marks and require the complete `tab.id` or a Tab handle in JavaScript, never a variable name or numeric `tabId`. Invalid keep entries abort before any cleanup. `deliverable` tabs leave temporary session groups and stay open; explicitly arranged groups are preserved; `handoff` tabs stay grouped for a later turn; other agent tabs close. Failed tabs retain their lease for retry. After successful finalize, old handles are released; obtain fresh handles in a later turn. Let running JavaScript finish before calling the separate finalize tool.
12
12
 
13
13
  Resetting JavaScript leaves browser tabs open. Closing the MCP client closes its local IPC connection and finalizes only that connection’s session. A host restart creates a new session; `session_restarted` means rebuild REPL bindings and inspect the browser before continuing. An idle browser session is finalized after an hour.
14
14
 
@@ -1,3 +1,4 @@
1
+ import { PageFunction } from '../shared/api-contract.js';
1
2
  import { ActionError } from './errors.js';
2
3
  import { argSpec } from '../sites/schema.js';
3
4
  import { discoverEndpoints } from '../recon/discover.js';
@@ -55,7 +56,7 @@ export function createAgentApi(rt, sessionId) {
55
56
  recon: { discover: async (tab, opts) => { const log = await tab.network.read({ limit: 2000 }); return tab.use((page) => discoverEndpoints(page, { ...opts, network: log.entries })); } },
56
57
  tools: {
57
58
  // In js, an explicit function can be passed directly; its source is saved as the adapter.
58
- define: (def) => rt.defineTool({ ...def, func: typeof def.func === 'function' ? def.func.toString() : def.func }),
59
+ define: (def) => rt.defineTool({ ...def, func: typeof def.func === 'function' ? def.func.toString() : def.func instanceof PageFunction ? def.func.source : def.func }),
59
60
  try: (draftId, args, expect) => rt.tryToolDraft(draftId, args, expect, sessionId),
60
61
  activate: (draftId) => rt.activateToolDraft(draftId),
61
62
  discard: async (draftId) => rt.discardToolDraft(draftId),
@@ -1 +1 @@
1
- {"version":3,"file":"api.js","sourceRoot":"","sources":["../../../src/api/api.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,OAAO,EAAE,MAAM,oBAAoB,CAAC;AAC7C,OAAO,EAAE,iBAAiB,EAAuB,MAAM,sBAAsB,CAAC;AAG9E,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAExD,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAWvC,MAAM,UAAU,cAAc,CAAC,EAAW,EAAE,SAAiB;IAC3D,MAAM,KAAK,GAAG,EAAE,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;IACpC,MAAM,GAAG,GAAmB,EAAE,EAAE,EAAE,SAAS,EAAE,KAAK,EAAE,CAAC;IACrD,sGAAsG;IACtG,MAAM,UAAU,GAAG,KAAK,IAAsB,EAAE;QAC9C,IAAI,CAAC,EAAE,CAAC,gBAAgB,EAAE;YAAE,MAAM,IAAI,WAAW,CAAC,qBAAqB,EAAE,iCAAiC,EAAE,iDAAiD,CAAC,CAAC;QAC/J,OAAO,IAAI,OAAO,CAAC,EAAE,CAAC,OAAO,EAAE,KAAK,UAAU,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,OAAO,EAAE,KAAK,UAAU,CAAC,CAAC,CAAC,UA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AE,EAAE,CAAC,EAAE,CAAC,iBAAiB,CAAC,OAAO,CAAC;YACpD,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE,CAAC,EAAE,CAAC,gBAAgB,CAAC,OAAO,CAAC;YACxD,IAAI,EAAE,KAAK,IAAI,EAAE,CAAC,EAAE,CAAC,SAAS,EAAE;YAChC,MAAM,EAAE,CAAC,IAAY,EAAE,IAAY,EAAE,EAAE,CAAC,EAAE,CAAC,UAAU,CAAC,IAAI,EAAE,IAAI,CAAC;SAClE;QACD,OAAO,EAAE,EAAE,EAAE,EAAE,SAAS,EAAE;KAC3B,CAAC;AACJ,CAAC"}
@@ -1,3 +1,4 @@
1
+ import { checkArity, parseInput, discoveryOptions } from '../shared/api-contract.js';
1
2
  import { browserCommand, watch } from './streams.js';
2
3
  import { ActionError } from './errors.js';
3
4
  import { buildInstructions, readDocForContext } from '../docs/manifest.js';
@@ -53,7 +54,7 @@ export class Browser {
53
54
  list: async () => {
54
55
  const page = await this.page();
55
56
  const tabs = await page.tabs();
56
- return tabs.map((t) => ({ ...(t.page && { id: t.page }), tabId: t.tabId, ...(!t.page && { pending: true }), url: t.url, title: t.title, active: t.active, selected: t.selected, origin: t.origin, state: t.state }));
57
+ return tabs.map((t) => ({ ...(t.page && { id: t.page }), tabId: t.tabId, ...(!t.page && { pending: true }), url: t.url, title: t.title, active: t.active, selected: t.selected, ...(t.lifecycle && { lifecycle: t.lifecycle }), origin: t.origin, state: t.state }));
57
58
  },
58
59
  get: async (tab, opts = {}) => {
59
60
  if (opts.timeoutMs !== undefined && (!Number.isFinite(opts.timeoutMs) || opts.timeoutMs < 0))
@@ -77,12 +78,25 @@ export class Browser {
77
78
  },
78
79
  selected: async () => {
79
80
  const tabs = (await this.tabs.list()).filter((tab) => tab.state === 'active' && tab.id);
80
- const current = tabs.find((tab) => tab.selected) ?? tabs.find((tab) => tab.active) ?? tabs[0];
81
+ const current = tabs.find((tab) => tab.selected) ?? tabs.find((tab) => tab.active);
81
82
  return current?.id ? new Tab(current.id, this.ctx) : undefined;
82
83
  },
83
84
  finalize: async (opts = {}) => {
84
85
  const page = await this.page();
85
- const keep = (opts.keep ?? []).map((k) => ({ page: typeof k.tab === 'string' ? k.tab : k.tab.id, status: k.status }));
86
+ const keep = (opts.keep ?? []).map((k) => ({ page: typeof k.tab === 'string' ? k.tab : k.tab?.id, status: k.status }));
87
+ if (keep.length) {
88
+ const owned = await this.tabs.list();
89
+ for (const item of keep) {
90
+ if (!['deliverable', 'handoff'].includes(item.status))
91
+ throw new ActionError('invalid_args', 'Unknown retention status');
92
+ if (!owned.some(tab => tab.id === item.page)) {
93
+ const valid = typeof item.page === 'string' && (this.type === 'electron'
94
+ ? /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(item.page)
95
+ : /^(0|[1-9]\d*)$/.test(item.page));
96
+ throw new ActionError(valid ? 'page_unavailable' : 'invalid_tab_id', `Cannot retain tab ${JSON.stringify(item.page)}`, 'Use await tab.markDeliverable(), or pass the full tab.id (not a variable name or numeric tabId). No tabs were cleaned up.', { tab: item.page, phase: 'finalize_validation', tabs: owned });
97
+ }
98
+ }
99
+ }
86
100
  const result = this.ctx.rt.isManagedPage(page) ? await page.finalize(keep) : (await page.closeWindow(), { closed: [], kept: keep.map((k) => k.page), failed: [] });
87
101
  for (const id of [...result.closed, ...result.kept])
88
102
  this.ctx.rt.forgetPage(this.ctx.sessionId, id);
@@ -95,7 +109,12 @@ export class Browser {
95
109
  },
96
110
  };
97
111
  user = {
98
- openTabs: async (options = {}) => this.ext(await this.page()).userTabs(options),
112
+ /** Unclaimed supported tabs in the visible scope. Query is trimmed, case-insensitive literal substring of URL OR title (no token splitting). Inspect items, matched, totalInScope, excluded and hasMore; continue with nextOffset. Each call takes a fresh snapshot. */
113
+ openTabs: async (...args) => {
114
+ checkArity('Browser.user.openTabs', args.length, 0, 1);
115
+ const options = parseInput('Browser.user.openTabs', discoveryOptions, args[0] === undefined ? {} : args[0]);
116
+ return this.ext(await this.page()).userTabs(options);
117
+ },
99
118
  /** Claim by foreground, id, or unique url/title lookup; expected fields verify the tab's current identity. */
100
119
  claimTab: async (tab) => {
101
120
  const page = this.ext(await this.page());
@@ -1 +1 @@
1
- {"version":3,"file":"browser.js","sourceRoot":"","sources":["../../../src/api/browser.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,cAAc,EAAE,KAAK,EAAE,MAAM,cAAc,CAAC;AAIrD,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,iBAAiB,EAAE,iBAAiB,EAAmB,MAAM,qBAAqB,CAAC;AAC5F,OAAO,EAAE,oBAAoB,EAAE,MAAM,oBAAoB,CAAC;AAC1D,OAAO,EAAE,GAAG,EAAE,MAAM,UAAU,CAAC;AAG/B,MAAM,OAAO,OAAO;IACG;IAAqB;IAAiD;IAA3F,YAAqB,EAAU,EAAW,IAA8B,EAAmB,GAAmB;QAAzF,OAAE,GAAF,EAAE,CAAQ;QAAW,SAAI,GAAJ,IAAI,CAA0B;QAAmB,QAAG,GAAH,GAAG,CAAgB;IAAG,CAAC;IAClH,MAAM,KAAuD,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,EAAE,EAAE,IAAI,CAAC,EAAE,EAAE,OAAO,EAAE,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC;IACnH,IAAI,KAA2B,OAAO,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,cAAc,CAAC,IAAI,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;IACvF,GAAG,CAAC,IAAiB;QAC3B,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,aAAa,CAAC,IAAI,CAAC;YAAE,MAAM,IAAI,WAAW,CAAC,qBAAqB,EAAE,gDAAgD,EAAE,wEAAwE,CAAC,CAAC;QAC/M,OAAO,IAAI,CAAC;IACd,CAAC;IAED,qGAAqG;IAC5F,MAAM,GAAG;QAChB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AAC,GAAG,CAAC,EAAE,CAAC,QAAQ,EAAE,EAAE,CAAC,EAAE,CAAC;YAAC,CAAC;YACte,MAAM,IAAI,WAAW,CAAC,oBAAoB,EAAE,kBAAkB,EAAE,GAAG,EAAE,6DAA6D,CAAC,CAAC;QACtI,CAAC;KACF,CAAC;IAEF,KAAK,CAAC,aAAa;QACjB,MAAM,GAAG,GAAe,EAAE,OAAO,EAAE,IAAI,CAAC,IAAI,EAAE,YAAY,EAAE,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,QAAQ,EAAE,EAAE,CAAC;QACrF,OAAO,GAAG,iBAAiB,CAAC,GAAG,CAAC,OAAO,iBAAiB,CAAC,SAAS,EAAE,GAAG,CAAC,IAAI,EAAE,OAAO,iBAAiB,CAAC,eAAe,EAAE,GAAG,CAAC,IAAI,EAAE,EAAE,CAAC;IACvI,CAAC;CACF"}
@@ -1,3 +1,4 @@
1
+ import { PageFunction, checkArity, parseInput, evaluateOptions, pageArgument } from '../shared/api-contract.js';
1
2
  import { pageTools, pageToolsUpdate } from './webmcp.js';
2
3
  import { watch } from './streams.js';
3
4
  import { ActionError } from './errors.js';
@@ -13,7 +14,7 @@ export class Tab {
13
14
  ctx;
14
15
  bound;
15
16
  /** A Tab owns the page object bound to its identity; `bound` lets an adapter pass an existing page. */
16
- /** `id` is the Chrome tab id as a string; `tabId` is the numeric id when claimed from a user tab. */
17
+ /** `id` is the stable backend page handle; `tabId` is the numeric backend id when claimed from a user tab. */
17
18
  tabId;
18
19
  constructor(initialId, ctx, bound, tabId) {
19
20
  this.initialId = initialId;
@@ -121,6 +122,19 @@ export class Tab {
121
122
  const title = await page.evaluate('document.title').catch(() => null);
122
123
  return { url, title };
123
124
  }
125
+ /** Preserve this tab for the user when the session is finalized. */
126
+ async markDeliverable() { await this.setRetention('deliverable'); }
127
+ /** Preserve this tab for a subsequent turn; it must be claimed again after finalization. */
128
+ async markHandoff() { await this.setRetention('handoff'); }
129
+ /** Restore default cleanup: close agent tabs, release borrowed user tabs. */
130
+ async clearRetention() { await this.setRetention(null); }
131
+ async setRetention(status) {
132
+ await this.use(async (page) => {
133
+ if (!this.ctx.rt.isManagedPage(page))
134
+ throw new ActionError('capability_unavailable', 'This backend does not support tab retention');
135
+ await page.mark(this.id, status);
136
+ });
137
+ }
124
138
  async url() { return this.use((p) => p.getCurrentUrl()); }
125
139
  async title() { return this.use((p) => p.evaluate('document.title')); }
126
140
  async back() { await this.use((p) => p.history('back')); }
@@ -395,13 +409,15 @@ export class Tab {
395
409
  }
396
410
  /** Main World page code; functions receive only opts.arg, never host closures. Dispatched scripts are never replayed. */
397
411
  async evaluate(script, opts = {}) {
398
- if (opts.timeoutMs !== undefined && (!Number.isFinite(opts.timeoutMs) || opts.timeoutMs < 1 || opts.timeoutMs > 300_000))
399
- throw new ActionError('invalid_args', 'timeoutMs must be from 1 to 300000');
400
- const source = typeof script === 'function' ? script.toString() : script?.$function;
401
- const expression = source ? `(${source})(${JSON.stringify(opts.arg) ?? 'undefined'})` : script;
412
+ checkArity('Tab.evaluate', arguments.length, 1, 2);
413
+ const options = parseInput('Tab.evaluate', evaluateOptions, opts);
414
+ const source = typeof script === 'function' ? script.toString() : (script instanceof PageFunction ? script.source : undefined);
415
+ if (!source && Object.hasOwn(options, 'arg'))
416
+ throw new ActionError('invalid_args', 'Tab.evaluate: arg requires a function, not a source string.', 'Use tab.evaluate(value => ..., {arg: value}).', { dispatched: false });
417
+ const expression = source ? `(${source})(${pageArgument(options.arg)})` : script;
402
418
  if (typeof expression !== 'string')
403
- throw new ActionError('invalid_args', 'evaluate expects page source or a function');
404
- return this.use(page => opts.frame !== undefined ? page.evaluateInFrame(expression, opts.frame, opts.timeoutMs) : page.evaluate(expression, { timeoutMs: opts.timeoutMs }));
419
+ throw new ActionError('invalid_args', 'evaluate expects page source or a function', undefined, { dispatched: false });
420
+ return this.use(page => options.frame !== undefined ? page.evaluateInFrame(expression, options.frame, options.timeoutMs) : page.evaluate(expression, { timeoutMs: options.timeoutMs }));
405
421
  }
406
422
  /** Native CDP on this Tab's shared debugger attachment. Parameters are not rewritten. */
407
423
  cdp = {