@howaboua/pi-browser 0.0.7 → 0.0.8

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/CHANGELOG.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # @howaboua/pi-browser
2
2
 
3
+ ## 0.0.8
4
+
5
+ - ### Improvements
6
+ - Browser returns help when called without arguments, including an empty structured object. Explicit help remains supported.
7
+
8
+ ### Fixes
9
+ - Screenshots bring the target tab to the foreground, avoiding capture timeouts caused by background focus emulation.
10
+
3
11
  ## 0.0.7
4
12
 
5
13
  - Browser operations tolerate unused `response_length` hints. Page-length controls for `open` and `find` are unchanged.
package/README.md CHANGED
@@ -16,17 +16,17 @@ Pi Codex 3.0.25 or newer is optional. Without it, Browser remains a normal top-l
16
16
 
17
17
  ## Use
18
18
 
19
- In normal Pi, call `browser` with `command: "help"` before first use, then send JSON request strings in `command`. Existing object requests remain accepted. In Code or Notebook Mode, start with:
19
+ In normal Pi, call `browser` with `{}` for help, then send JSON request strings in `command`. Explicit `command: "help"` and existing object requests remain accepted. In Code or Notebook Mode, start with:
20
20
 
21
21
  ```js
22
- await tools.browser("help")
22
+ await tools.browser()
23
23
  ```
24
24
 
25
25
  All modes accept single-action and batched requests described by help. A common route is `tabs`, then `open`, then `click` or `type` with the returned `ref_id` and element ID.
26
26
 
27
27
  Long Code and Notebook calls use the normal `exec` and `wait` lifecycle. Cancellation stops pending CDP work, though an already dispatched browser mutation may still take effect.
28
28
 
29
- New tabs open in the background and belong to the current Pi session. Owned tabs keep rendering during control without being brought forward. The agent can filter the tab list to its own tabs, show a tab when you want to see it, and close any tab by reference. Existing tabs remain accessible through their refs and are not silently claimed.
29
+ New tabs open in the background and belong to the current Pi session. Owned tabs keep rendering during control without being brought forward, except screenshots bring their target tab to the foreground for capture. The agent can filter the tab list to its own tabs, show a tab when you want to see it, and close any tab by reference. Existing tabs remain accessible through their refs and are not silently claimed.
30
30
 
31
31
  Ownership survives extension reloads and managed-worker restarts while the browser and local runtime state remain. Restarting the browser makes restored tabs shared again. Popups inherit ownership through Chrome's opener metadata, but can still take focus. This tool does not install a Chrome extension or create Chrome tab groups.
32
32
 
package/dist/index.js CHANGED
@@ -37,7 +37,7 @@ async function registerBrowserInCodeMode(pi, tool) {
37
37
  adaptToolForCodeMode(tool, {
38
38
  kind: "freeform",
39
39
  prepareInput: prepareBrowserInput,
40
- usage: 'await tools.browser("help") // Logged-in browser; help before other actions',
40
+ usage: "await tools.browser() // Logged-in browser help",
41
41
  }),
42
42
  ]);
43
43
  }
@@ -1445,7 +1445,7 @@ class BrowserCdpSession {
1445
1445
  bridge?.close(false);
1446
1446
  return closed.refId;
1447
1447
  }
1448
- async withTab(refId, signal, action) {
1448
+ async withTab(refId, signal, action, rendering = "background") {
1449
1449
  const pages = await this.pages(signal);
1450
1450
  const targetId = resolvePrefix(refId, pages.map((page) => page.targetId), "target", "Run tabs.");
1451
1451
  let bridge = this.tabs.get(targetId);
@@ -1482,7 +1482,10 @@ class BrowserCdpSession {
1482
1482
  const owned = pages.some((page) => page.targetId === targetId && page.owned === true);
1483
1483
  const current = bridge;
1484
1484
  return current.run(targetId.slice(0, prefixLength), signal, async (tab) => {
1485
- await current.setBackgroundRendering(owned, signal);
1485
+ await current.setBackgroundRendering(owned && rendering === "background", signal);
1486
+ if (rendering === "foreground") {
1487
+ await tab.cdp.send("Target.activateTarget", { targetId }, undefined, signal);
1488
+ }
1486
1489
  return action(tab);
1487
1490
  });
1488
1491
  }
@@ -1737,6 +1740,7 @@ function browserHelp(hosts = []) {
1737
1740
  safety: "Ask before unfamiliar low-trust navigation or consequential action unless authorized; never close shared browser",
1738
1741
  batch: "{action_name:[{...fields}],...}; nonempty arrays; items omit action; host/response_length at request root; independent only",
1739
1742
  actions: {
1743
+ help: "",
1740
1744
  tabs: "query? offset? owned_only? -> ref_id title url owned",
1741
1745
  open: "ref_id lineno? | url; new tabs open in background",
1742
1746
  show: "ref_id; bring tab to foreground",
@@ -1747,7 +1751,7 @@ function browserHelp(hosts = []) {
1747
1751
  fill: "ref_id id|selector value; replace/clear text, select option value/label, boolean checks/unchecks",
1748
1752
  press: "ref_id key; focused element, e.g. Enter or Control+a",
1749
1753
  wait: "ref_id selector|text|url_includes timeout_ms?; DOM presence or substring, default 10000ms",
1750
- screenshot: "ref_id id?|selector? -> file",
1754
+ screenshot: "ref_id id?|selector?; brings tab to foreground -> file",
1751
1755
  navigate: "ref_id url",
1752
1756
  html: "ref_id id?|selector?",
1753
1757
  evaluate: "ref_id expression",
@@ -3210,7 +3214,7 @@ class BrowserOperationExecutor {
3210
3214
  dpr: capture.dpr,
3211
3215
  coordinates: "CSS pixels; screenshot pixels / DPR"
3212
3216
  };
3213
- });
3217
+ }, "foreground");
3214
3218
  }
3215
3219
  async tabResult(refId, signal, action) {
3216
3220
  return this.cdp.withTab(refId, signal, async (tab) => ({
@@ -3494,11 +3498,11 @@ class BrowserRuntime {
3494
3498
  signal: options.signal ? AbortSignal.any([options.signal, this.lifetime.signal]) : this.lifetime.signal
3495
3499
  };
3496
3500
  options.signal?.throwIfAborted();
3501
+ if ("help" in request)
3502
+ return browserHelp(this.hosts);
3497
3503
  await waitForTurn(this.pruneLocalSessions(), options.signal);
3498
3504
  await pruneArtifacts();
3499
3505
  options.signal?.throwIfAborted();
3500
- if ("help" in request)
3501
- return browserHelp(this.hosts);
3502
3506
  const ownerId = options.ownerId ?? this.defaultOwnerId;
3503
3507
  if (request.host) {
3504
3508
  const route = this.routes.resolve(request.host);
@@ -11,6 +11,7 @@ export function browserHelp(hosts = []) {
11
11
  safety: "Ask before unfamiliar low-trust navigation or consequential action unless authorized; never close shared browser",
12
12
  batch: "{action_name:[{...fields}],...}; nonempty arrays; items omit action; host/response_length at request root; independent only",
13
13
  actions: {
14
+ help: "",
14
15
  tabs: "query? offset? owned_only? -> ref_id title url owned",
15
16
  open: "ref_id lineno? | url; new tabs open in background",
16
17
  show: "ref_id; bring tab to foreground",
@@ -21,7 +22,7 @@ export function browserHelp(hosts = []) {
21
22
  fill: "ref_id id|selector value; replace/clear text, select option value/label, boolean checks/unchecks",
22
23
  press: "ref_id key; focused element, e.g. Enter or Control+a",
23
24
  wait: "ref_id selector|text|url_includes timeout_ms?; DOM presence or substring, default 10000ms",
24
- screenshot: "ref_id id?|selector? -> file",
25
+ screenshot: "ref_id id?|selector?; brings tab to foreground -> file",
25
26
  navigate: "ref_id url",
26
27
  html: "ref_id id?|selector?",
27
28
  evaluate: "ref_id expression",
@@ -1,8 +1 @@
1
- interface ProcessResult {
2
- code: number;
3
- stdout: string;
4
- stderr: string;
5
- }
6
- export declare function runProcess(command: string, args: string[], signal?: AbortSignal): Promise<ProcessResult>;
7
1
  export declare function startBrowser(signal?: AbortSignal): Promise<string>;
8
- export {};
@@ -8,7 +8,7 @@ function abortReason(signal) {
8
8
  ? signal.reason
9
9
  : new Error("Browser launch aborted");
10
10
  }
11
- export function runProcess(command, args, signal) {
11
+ function runProcess(command, args, signal) {
12
12
  if (signal?.aborted)
13
13
  return Promise.reject(abortReason(signal));
14
14
  return new Promise((resolveValue, reject) => {
@@ -115,7 +115,7 @@ export class BrowserOperationExecutor {
115
115
  dpr: capture.dpr,
116
116
  coordinates: "CSS pixels; screenshot pixels / DPR",
117
117
  };
118
- });
118
+ }, "foreground");
119
119
  }
120
120
  async tabResult(refId, signal, action) {
121
121
  return this.cdp.withTab(refId, signal, async (tab) => ({
@@ -1,4 +1,3 @@
1
1
  import type { BrowserOperation } from "./operation.js";
2
2
  import type { BrowserRoute } from "./routes.js";
3
- export { remoteNodeCommand } from "./remote-helper.js";
4
3
  export declare function executeRemoteBrowser(route: BrowserRoute, operations: BrowserOperation[], ownerId: string, signal?: AbortSignal): Promise<Record<string, unknown>>;
@@ -4,7 +4,6 @@ import { artifactDirectory } from "./artifacts.js";
4
4
  import { ensureRemoteHelper, remoteNodeCommand } from "./remote-helper.js";
5
5
  import { runProgram } from "./remote-process.js";
6
6
  const SAFE_REMOTE_FILE = /^\/[A-Za-z0-9_./-]+$/;
7
- export { remoteNodeCommand } from "./remote-helper.js";
8
7
  function isRecord(value) {
9
8
  return value !== null && typeof value === "object" && !Array.isArray(value);
10
9
  }
@@ -10,6 +10,8 @@ function requestHost(value) {
10
10
  return value.trim();
11
11
  }
12
12
  export function parseBrowserRequest(input) {
13
+ if (input === undefined)
14
+ return { help: true };
13
15
  let value = input;
14
16
  if (typeof input === "string") {
15
17
  const text = input.trim();
@@ -25,6 +27,8 @@ export function parseBrowserRequest(input) {
25
27
  if (!isRecordValue(value)) {
26
28
  throw new Error("input must be a JSON object");
27
29
  }
30
+ if (Object.keys(value).length === 0)
31
+ return { help: true };
28
32
  if (Object.hasOwn(value, "action")) {
29
33
  const host = requestHost(value["host"]);
30
34
  const { host: _host, ...actionValue } = value;
@@ -12,5 +12,4 @@ export declare class BrowserRoutes {
12
12
  constructor(routes?: ReadonlyMap<string, BrowserRoute>);
13
13
  resolve(name: string): BrowserRoute;
14
14
  }
15
- export declare function parseBrowserRoutes(value: unknown, currentHostname?: string): BrowserRoutes;
16
15
  export declare function loadBrowserRoutes(path?: string, currentHostname?: string): BrowserRoutes;
@@ -1,5 +1,5 @@
1
1
  import { hostname } from "node:os";
2
- import { normalizeBrowserRouteConfig, readBrowserRouteConfig, } from "./config.js";
2
+ import { readBrowserRouteConfig } from "./config.js";
3
3
  export class BrowserRoutes {
4
4
  names;
5
5
  routes;
@@ -32,9 +32,6 @@ function routesFromConfig(config, currentHostname) {
32
32
  }
33
33
  return new BrowserRoutes(routes);
34
34
  }
35
- export function parseBrowserRoutes(value, currentHostname = hostname()) {
36
- return routesFromConfig(normalizeBrowserRouteConfig(value), currentHostname);
37
- }
38
35
  export function loadBrowserRoutes(path, currentHostname = hostname()) {
39
36
  return routesFromConfig(readBrowserRouteConfig(path), currentHostname);
40
37
  }
@@ -27,11 +27,11 @@ export class BrowserRuntime {
27
27
  : this.lifetime.signal,
28
28
  };
29
29
  options.signal?.throwIfAborted();
30
+ if ("help" in request)
31
+ return browserHelp(this.hosts);
30
32
  await waitForTurn(this.pruneLocalSessions(), options.signal);
31
33
  await pruneArtifacts();
32
34
  options.signal?.throwIfAborted();
33
- if ("help" in request)
34
- return browserHelp(this.hosts);
35
35
  const ownerId = options.ownerId ?? this.defaultOwnerId;
36
36
  if (request.host) {
37
37
  const route = this.routes.resolve(request.host);
@@ -4,5 +4,5 @@ export declare function prepareBrowserInput(input: unknown): {
4
4
  command: string;
5
5
  };
6
6
  export declare function createBrowserTool(runtime: BrowserRuntime): import("@earendil-works/pi-coding-agent").ToolDefinition<Type.TObject<{
7
- command: Type.TString;
7
+ command: Type.TOptional<Type.TString>;
8
8
  }>, unknown, any> & import("@earendil-works/pi-coding-agent").ToolDefinition<any, any, any>;
@@ -4,6 +4,8 @@ import { isRecordValue } from "./browser/parse-operation.js";
4
4
  import { parseBrowserRequest } from "./browser/request.js";
5
5
  import { BrowserRuntime } from "./browser/runtime.js";
6
6
  export function prepareBrowserInput(input) {
7
+ if (input === undefined)
8
+ return { command: "help" };
7
9
  if (typeof input === "string")
8
10
  return { command: input };
9
11
  if (!isRecordValue(input)) {
@@ -16,14 +18,17 @@ export function prepareBrowserInput(input) {
16
18
  return { ...input, command: input["command"] };
17
19
  }
18
20
  // Resume old object calls without changing their stored history representation.
21
+ parseBrowserRequest(input);
19
22
  return { command: JSON.stringify(input) };
20
23
  }
21
24
  export function createBrowserTool(runtime) {
22
25
  return defineTool({
23
26
  name: "browser",
24
27
  label: "Browser",
25
- description: "Control logged-in browser; call help before other actions",
26
- parameters: Type.Object({ command: Type.String({ description: "help or JSON request" }) }, { additionalProperties: false }),
28
+ description: "Control logged-in browser",
29
+ parameters: Type.Object({
30
+ command: Type.Optional(Type.String({ description: "help or JSON request" })),
31
+ }, { additionalProperties: false }),
27
32
  prepareArguments: prepareBrowserInput,
28
33
  async execute(_toolCallId, input, signal, onUpdate, ctx) {
29
34
  const result = await runtime.execute(parseBrowserRequest(input.command), {
@@ -21,7 +21,7 @@ export declare class BrowserCdpSession {
21
21
  }>;
22
22
  show(refId: string, signal?: AbortSignal): Promise<string>;
23
23
  closeTab(refId: string, signal?: AbortSignal): Promise<string>;
24
- withTab<T>(refId: string, signal: AbortSignal | undefined, action: (tab: ActiveTab) => Promise<T>): Promise<T>;
24
+ withTab<T>(refId: string, signal: AbortSignal | undefined, action: (tab: ActiveTab) => Promise<T>, rendering?: "background" | "foreground"): Promise<T>;
25
25
  stop(refId?: string): Promise<void>;
26
26
  close(): Promise<void>;
27
27
  private rootConnection;
@@ -140,7 +140,7 @@ export class BrowserCdpSession {
140
140
  bridge?.close(false);
141
141
  return closed.refId;
142
142
  }
143
- async withTab(refId, signal, action) {
143
+ async withTab(refId, signal, action, rendering = "background") {
144
144
  const pages = await this.pages(signal);
145
145
  const targetId = resolvePrefix(refId, pages.map((page) => page.targetId), "target", "Run tabs.");
146
146
  let bridge = this.tabs.get(targetId);
@@ -178,7 +178,12 @@ export class BrowserCdpSession {
178
178
  const owned = pages.some((page) => page.targetId === targetId && page.owned === true);
179
179
  const current = bridge;
180
180
  return current.run(targetId.slice(0, prefixLength), signal, async (tab) => {
181
- await current.setBackgroundRendering(owned, signal);
181
+ // Surface screenshots need a visible tab with real focus. Focus
182
+ // emulation alone can leave capture waiting indefinitely on Chrome.
183
+ await current.setBackgroundRendering(owned && rendering === "background", signal);
184
+ if (rendering === "foreground") {
185
+ await tab.cdp.send("Target.activateTarget", { targetId }, undefined, signal);
186
+ }
182
187
  return action(tab);
183
188
  });
184
189
  }
package/index.ts CHANGED
@@ -47,8 +47,7 @@ async function registerBrowserInCodeMode(
47
47
  adaptToolForCodeMode(tool, {
48
48
  kind: "freeform",
49
49
  prepareInput: prepareBrowserInput,
50
- usage:
51
- 'await tools.browser("help") // Logged-in browser; help before other actions',
50
+ usage: "await tools.browser() // Logged-in browser help",
52
51
  }),
53
52
  ]);
54
53
  } catch (error) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@howaboua/pi-browser",
3
- "version": "0.0.7",
3
+ "version": "0.0.8",
4
4
  "description": "Logged-in browser inspection and control for Pi, Code Mode and Notebook Mode.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -38,15 +38,14 @@
38
38
  ],
39
39
  "scripts": {
40
40
  "build": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.build.json && bun build remote-worker.ts --target=node --format=esm --outfile=dist/remote-worker.js --banner='// @howaboua/pi-browser managed worker'",
41
- "check": "bun run lint && bun run typecheck && bun run test",
41
+ "check": "bun run lint && bun run typecheck",
42
42
  "prepack": "bun run check && bun run build",
43
43
  "typecheck": "tsgo --noEmit",
44
44
  "lint": "biome check .",
45
- "test": "tsx --test tests/**/*.test.ts",
46
45
  "pack:dry": "npm pack --dry-run"
47
46
  },
48
47
  "peerDependencies": {
49
- "@howaboua/pi-codex-conversion": ">=3.0.46",
48
+ "@howaboua/pi-codex-conversion": ">=3.0.48",
50
49
  "@earendil-works/pi-ai": ">=1.0.0",
51
50
  "@earendil-works/pi-coding-agent": ">=1.0.0",
52
51
  "typebox": "*",
@@ -58,12 +57,11 @@
58
57
  }
59
58
  },
60
59
  "devDependencies": {
61
- "@howaboua/pi-codex-conversion": "3.0.46",
60
+ "@howaboua/pi-codex-conversion": "3.0.48",
62
61
  "@biomejs/biome": "^2.5.10",
63
- "@earendil-works/pi-ai": "1.0.4",
64
- "@earendil-works/pi-coding-agent": "1.0.4",
62
+ "@earendil-works/pi-ai": "1.1.0",
63
+ "@earendil-works/pi-coding-agent": "1.1.0",
65
64
  "@types/node": "^26.2.0",
66
- "tsx": "^4.23.12",
67
65
  "typebox": "1.3.18",
68
66
  "typescript": "^7.0.2"
69
67
  },
@@ -16,6 +16,7 @@ export function browserHelp(
16
16
  batch:
17
17
  "{action_name:[{...fields}],...}; nonempty arrays; items omit action; host/response_length at request root; independent only",
18
18
  actions: {
19
+ help: "",
19
20
  tabs: "query? offset? owned_only? -> ref_id title url owned",
20
21
  open: "ref_id lineno? | url; new tabs open in background",
21
22
  show: "ref_id; bring tab to foreground",
@@ -26,7 +27,7 @@ export function browserHelp(
26
27
  fill: "ref_id id|selector value; replace/clear text, select option value/label, boolean checks/unchecks",
27
28
  press: "ref_id key; focused element, e.g. Enter or Control+a",
28
29
  wait: "ref_id selector|text|url_includes timeout_ms?; DOM presence or substring, default 10000ms",
29
- screenshot: "ref_id id?|selector? -> file",
30
+ screenshot: "ref_id id?|selector?; brings tab to foreground -> file",
30
31
  navigate: "ref_id url",
31
32
  html: "ref_id id?|selector?",
32
33
  evaluate: "ref_id expression",
@@ -17,7 +17,7 @@ function abortReason(signal: AbortSignal): Error {
17
17
  : new Error("Browser launch aborted");
18
18
  }
19
19
 
20
- export function runProcess(
20
+ function runProcess(
21
21
  command: string,
22
22
  args: string[],
23
23
  signal?: AbortSignal,
@@ -241,35 +241,40 @@ export class BrowserOperationExecutor {
241
241
  signal?: AbortSignal,
242
242
  ): Promise<Record<string, unknown>> {
243
243
  const file = await screenshotPath(operation);
244
- return this.cdp.withTab(operation.ref_id, signal, async (tab) => {
245
- const capture =
246
- operation.id !== undefined
247
- ? await captureRef(
248
- tab.cdp,
249
- tab.sessionId,
250
- tab.elementRefs,
251
- operation.id,
252
- file,
253
- signal,
254
- )
255
- : operation.selector
256
- ? await captureSelector(
244
+ return this.cdp.withTab(
245
+ operation.ref_id,
246
+ signal,
247
+ async (tab) => {
248
+ const capture =
249
+ operation.id !== undefined
250
+ ? await captureRef(
257
251
  tab.cdp,
258
252
  tab.sessionId,
259
- operation.selector,
253
+ tab.elementRefs,
254
+ operation.id,
260
255
  file,
261
256
  signal,
262
257
  )
263
- : await captureViewport(tab.cdp, tab.sessionId, file, signal);
264
- return {
265
- ref_id: tab.refId,
266
- ...(operation.id === undefined ? {} : { id: operation.id }),
267
- ...(operation.selector ? { selector: operation.selector } : {}),
268
- file: capture.file,
269
- dpr: capture.dpr,
270
- coordinates: "CSS pixels; screenshot pixels / DPR",
271
- };
272
- });
258
+ : operation.selector
259
+ ? await captureSelector(
260
+ tab.cdp,
261
+ tab.sessionId,
262
+ operation.selector,
263
+ file,
264
+ signal,
265
+ )
266
+ : await captureViewport(tab.cdp, tab.sessionId, file, signal);
267
+ return {
268
+ ref_id: tab.refId,
269
+ ...(operation.id === undefined ? {} : { id: operation.id }),
270
+ ...(operation.selector ? { selector: operation.selector } : {}),
271
+ file: capture.file,
272
+ dpr: capture.dpr,
273
+ coordinates: "CSS pixels; screenshot pixels / DPR",
274
+ };
275
+ },
276
+ "foreground",
277
+ );
273
278
  }
274
279
 
275
280
  private async tabResult(
@@ -8,8 +8,6 @@ import type { BrowserRoute } from "./routes.js";
8
8
 
9
9
  const SAFE_REMOTE_FILE = /^\/[A-Za-z0-9_./-]+$/;
10
10
 
11
- export { remoteNodeCommand } from "./remote-helper.js";
12
-
13
11
  function isRecord(value: unknown): value is Record<string, unknown> {
14
12
  return value !== null && typeof value === "object" && !Array.isArray(value);
15
13
  }
@@ -16,6 +16,7 @@ function requestHost(value: unknown): string | undefined {
16
16
  }
17
17
 
18
18
  export function parseBrowserRequest(input: unknown): BrowserRequest {
19
+ if (input === undefined) return { help: true };
19
20
  let value = input;
20
21
  if (typeof input === "string") {
21
22
  const text = input.trim();
@@ -33,6 +34,7 @@ export function parseBrowserRequest(input: unknown): BrowserRequest {
33
34
  if (!isRecordValue(value)) {
34
35
  throw new Error("input must be a JSON object");
35
36
  }
37
+ if (Object.keys(value).length === 0) return { help: true };
36
38
  if (Object.hasOwn(value, "action")) {
37
39
  const host = requestHost(value["host"]);
38
40
  const { host: _host, ...actionValue } = value;
@@ -1,9 +1,5 @@
1
1
  import { hostname } from "node:os";
2
- import {
3
- type BrowserRouteConfig,
4
- normalizeBrowserRouteConfig,
5
- readBrowserRouteConfig,
6
- } from "./config.js";
2
+ import { type BrowserRouteConfig, readBrowserRouteConfig } from "./config.js";
7
3
 
8
4
  export interface BrowserRemoteCommand {
9
5
  nodePath: string;
@@ -54,13 +50,6 @@ function routesFromConfig(
54
50
  return new BrowserRoutes(routes);
55
51
  }
56
52
 
57
- export function parseBrowserRoutes(
58
- value: unknown,
59
- currentHostname = hostname(),
60
- ): BrowserRoutes {
61
- return routesFromConfig(normalizeBrowserRouteConfig(value), currentHostname);
62
- }
63
-
64
53
  export function loadBrowserRoutes(
65
54
  path?: string,
66
55
  currentHostname = hostname(),
@@ -50,10 +50,10 @@ export class BrowserRuntime {
50
50
  : this.lifetime.signal,
51
51
  };
52
52
  options.signal?.throwIfAborted();
53
+ if ("help" in request) return browserHelp(this.hosts);
53
54
  await waitForTurn(this.pruneLocalSessions(), options.signal);
54
55
  await pruneArtifacts();
55
56
  options.signal?.throwIfAborted();
56
- if ("help" in request) return browserHelp(this.hosts);
57
57
  const ownerId = options.ownerId ?? this.defaultOwnerId;
58
58
  if (request.host) {
59
59
  const route = this.routes.resolve(request.host);
@@ -5,6 +5,7 @@ import { parseBrowserRequest } from "./browser/request.js";
5
5
  import { BrowserRuntime } from "./browser/runtime.js";
6
6
 
7
7
  export function prepareBrowserInput(input: unknown): { command: string } {
8
+ if (input === undefined) return { command: "help" };
8
9
  if (typeof input === "string") return { command: input };
9
10
  if (!isRecordValue(input)) {
10
11
  throw new Error("browser input must be a command envelope or JSON request");
@@ -18,6 +19,7 @@ export function prepareBrowserInput(input: unknown): { command: string } {
18
19
  return { ...input, command: input["command"] };
19
20
  }
20
21
  // Resume old object calls without changing their stored history representation.
22
+ parseBrowserRequest(input);
21
23
  return { command: JSON.stringify(input) };
22
24
  }
23
25
 
@@ -25,9 +27,13 @@ export function createBrowserTool(runtime: BrowserRuntime) {
25
27
  return defineTool({
26
28
  name: "browser",
27
29
  label: "Browser",
28
- description: "Control logged-in browser; call help before other actions",
30
+ description: "Control logged-in browser",
29
31
  parameters: Type.Object(
30
- { command: Type.String({ description: "help or JSON request" }) },
32
+ {
33
+ command: Type.Optional(
34
+ Type.String({ description: "help or JSON request" }),
35
+ ),
36
+ },
31
37
  { additionalProperties: false },
32
38
  ),
33
39
  prepareArguments: prepareBrowserInput,
@@ -216,6 +216,7 @@ export class BrowserCdpSession {
216
216
  refId: string,
217
217
  signal: AbortSignal | undefined,
218
218
  action: (tab: ActiveTab) => Promise<T>,
219
+ rendering: "background" | "foreground" = "background",
219
220
  ): Promise<T> {
220
221
  const pages = await this.pages(signal);
221
222
  const targetId = resolvePrefix(
@@ -265,7 +266,20 @@ export class BrowserCdpSession {
265
266
  );
266
267
  const current = bridge;
267
268
  return current.run(targetId.slice(0, prefixLength), signal, async (tab) => {
268
- await current.setBackgroundRendering(owned, signal);
269
+ // Surface screenshots need a visible tab with real focus. Focus
270
+ // emulation alone can leave capture waiting indefinitely on Chrome.
271
+ await current.setBackgroundRendering(
272
+ owned && rendering === "background",
273
+ signal,
274
+ );
275
+ if (rendering === "foreground") {
276
+ await tab.cdp.send(
277
+ "Target.activateTarget",
278
+ { targetId },
279
+ undefined,
280
+ signal,
281
+ );
282
+ }
269
283
  return action(tab);
270
284
  });
271
285
  }
package/tsconfig.json CHANGED
@@ -3,5 +3,5 @@
3
3
  "compilerOptions": {
4
4
  "lib": ["ESNext", "DOM"]
5
5
  },
6
- "include": ["index.ts", "remote-worker.ts", "src/**/*.ts", "tests/**/*.ts"]
6
+ "include": ["index.ts", "remote-worker.ts", "src/**/*.ts"]
7
7
  }