@howaboua/pi-browser 0.0.7 → 0.0.9

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,17 @@
1
1
  # @howaboua/pi-browser
2
2
 
3
+ ## 0.0.9
4
+
5
+ - Use consistent tool discovery across native, Code and Notebook modes, with compact help in PCC GPT prompt mode.
6
+
7
+ ## 0.0.8
8
+
9
+ - ### Improvements
10
+ - Browser returns help when called without arguments, including an empty structured object. Explicit help remains supported.
11
+
12
+ ### Fixes
13
+ - Screenshots bring the target tab to the foreground, avoiding capture timeouts caused by background focus emulation.
14
+
3
15
  ## 0.0.7
4
16
 
5
17
  - Browser operations tolerate unused `response_length` hints. Page-length controls for `open` and `find` are unchanged.
package/README.md CHANGED
@@ -12,21 +12,21 @@ pi install npm:@howaboua/pi-browser
12
12
 
13
13
  Requires Pi 1.0.0 or newer, Node.js 22.19 or newer, and a Chrome-family browser with remote debugging enabled at `chrome://inspect/#remote-debugging`.
14
14
 
15
- Pi Codex 3.0.25 or newer is optional. Without it, Browser remains a normal top-level Pi tool. Do not load Pi Codex's example `browser.toml` custom tool alongside this extension.
15
+ Pi Codex 3.0.52 or newer is optional. Without it, Browser remains a normal top-level Pi tool. Do not load Pi Codex's example `browser.toml` custom tool alongside this extension.
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/biome.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "$schema": "https://biomejs.dev/schemas/2.5.10/schema.json",
2
+ "$schema": "https://biomejs.dev/schemas/2.5.15/schema.json",
3
3
  "vcs": {
4
4
  "enabled": true,
5
5
  "clientKind": "git",
package/dist/index.js CHANGED
@@ -16,9 +16,28 @@ export default async function browserExtension(pi) {
16
16
  configError = error instanceof Error ? error.message : String(error);
17
17
  }
18
18
  const runtime = new BrowserRuntime(routes);
19
- const tool = createBrowserTool(runtime);
19
+ let gpt = false;
20
+ const tool = createBrowserTool(runtime, () => gpt);
20
21
  registerBrowserCommand(pi);
21
22
  pi.registerTool(tool);
23
+ try {
24
+ const { registerGptPromptMode } = await import("@howaboua/pi-codex-conversion/prompt-mode");
25
+ registerGptPromptMode(pi, (active) => {
26
+ gpt = active;
27
+ return [tool];
28
+ });
29
+ }
30
+ catch (error) {
31
+ if (!(error instanceof Error) ||
32
+ !("code" in error) ||
33
+ ![
34
+ "ERR_MODULE_NOT_FOUND",
35
+ "MODULE_NOT_FOUND",
36
+ "ERR_PACKAGE_PATH_NOT_EXPORTED",
37
+ ].includes(String(error.code)) ||
38
+ !error.message.includes(CODE_MODE_PACKAGE))
39
+ throw error;
40
+ }
22
41
  const registration = await registerBrowserInCodeMode(pi, tool);
23
42
  pi.on("session_shutdown", async () => {
24
43
  registration?.unregister();
@@ -37,7 +56,7 @@ async function registerBrowserInCodeMode(pi, tool) {
37
56
  adaptToolForCodeMode(tool, {
38
57
  kind: "freeform",
39
58
  prepareInput: prepareBrowserInput,
40
- usage: 'await tools.browser("help") // Logged-in browser; help before other actions',
59
+ discovery: "help",
41
60
  }),
42
61
  ]);
43
62
  }
@@ -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
  }
@@ -1726,17 +1729,18 @@ async function discardCachedResult(handle) {
1726
1729
  }
1727
1730
 
1728
1731
  // src/browser/help.ts
1729
- function browserHelp(hosts = []) {
1732
+ function browserHelp(hosts = [], gpt = false) {
1730
1733
  const routed = hosts.length > 0;
1731
1734
  return {
1732
- input: "Request={action,...fields}; Pi: {command:JSON.stringify(request)}; Code/Notebook: JSON.stringify(request), JSON.parse(result)",
1735
+ input: gpt ? "Request={action,...fields}; Pi {command:JSON.stringify(request)}; Code/Notebook JSON.stringify(request), JSON.parse(result)" : "Request={action,...fields}; Pi: {command:JSON.stringify(request)}; Code/Notebook: JSON.stringify(request), JSON.parse(result)",
1733
1736
  ...routed ? {
1734
- host: `${hosts.join("|")} optional; keep a user-named host on every call and its refs/handles`
1737
+ host: `${hosts.join("|")}${gpt ? " optional; retain user-named host on every call + refs/handles" : " optional; keep a user-named host on every call and its refs/handles"}`
1735
1738
  } : {},
1736
1739
  refs: "tabs -> open; keep ref_id/id/cursors with their result",
1737
- safety: "Ask before unfamiliar low-trust navigation or consequential action unless authorized; never close shared browser",
1738
- batch: "{action_name:[{...fields}],...}; nonempty arrays; items omit action; host/response_length at request root; independent only",
1740
+ safety: gpt ? "Unless authorized, ask before unfamiliar low-trust navigation/consequential action; never close shared browser" : "Ask before unfamiliar low-trust navigation or consequential action unless authorized; never close shared browser",
1741
+ batch: gpt ? "{action_name:[{...fields}],...}; nonempty arrays, no item action; root host/response_length; independent only" : "{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);
@@ -1 +1 @@
1
- export declare function browserHelp(hosts?: readonly string[]): Record<string, unknown>;
1
+ export declare function browserHelp(hosts?: readonly string[], gpt?: boolean): Record<string, unknown>;
@@ -1,16 +1,23 @@
1
- export function browserHelp(hosts = []) {
1
+ export function browserHelp(hosts = [], gpt = false) {
2
2
  const routed = hosts.length > 0;
3
3
  return {
4
- input: "Request={action,...fields}; Pi: {command:JSON.stringify(request)}; Code/Notebook: JSON.stringify(request), JSON.parse(result)",
4
+ input: gpt
5
+ ? "Request={action,...fields}; Pi {command:JSON.stringify(request)}; Code/Notebook JSON.stringify(request), JSON.parse(result)"
6
+ : "Request={action,...fields}; Pi: {command:JSON.stringify(request)}; Code/Notebook: JSON.stringify(request), JSON.parse(result)",
5
7
  ...(routed
6
8
  ? {
7
- host: `${hosts.join("|")} optional; keep a user-named host on every call and its refs/handles`,
9
+ host: `${hosts.join("|")}${gpt ? " optional; retain user-named host on every call + refs/handles" : " optional; keep a user-named host on every call and its refs/handles"}`,
8
10
  }
9
11
  : {}),
10
12
  refs: "tabs -> open; keep ref_id/id/cursors with their result",
11
- safety: "Ask before unfamiliar low-trust navigation or consequential action unless authorized; never close shared browser",
12
- batch: "{action_name:[{...fields}],...}; nonempty arrays; items omit action; host/response_length at request root; independent only",
13
+ safety: gpt
14
+ ? "Unless authorized, ask before unfamiliar low-trust navigation/consequential action; never close shared browser"
15
+ : "Ask before unfamiliar low-trust navigation or consequential action unless authorized; never close shared browser",
16
+ batch: gpt
17
+ ? "{action_name:[{...fields}],...}; nonempty arrays, no item action; root host/response_length; independent only"
18
+ : "{action_name:[{...fields}],...}; nonempty arrays; items omit action; host/response_length at request root; independent only",
13
19
  actions: {
20
+ help: "",
14
21
  tabs: "query? offset? owned_only? -> ref_id title url owned",
15
22
  open: "ref_id lineno? | url; new tabs open in background",
16
23
  show: "ref_id; bring tab to foreground",
@@ -21,7 +28,7 @@ export function browserHelp(hosts = []) {
21
28
  fill: "ref_id id|selector value; replace/clear text, select option value/label, boolean checks/unchecks",
22
29
  press: "ref_id key; focused element, e.g. Enter or Control+a",
23
30
  wait: "ref_id selector|text|url_includes timeout_ms?; DOM presence or substring, default 10000ms",
24
- screenshot: "ref_id id?|selector? -> file",
31
+ screenshot: "ref_id id?|selector?; brings tab to foreground -> file",
25
32
  navigate: "ref_id url",
26
33
  html: "ref_id id?|selector?",
27
34
  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);
@@ -3,6 +3,6 @@ import { BrowserRuntime } from "./browser/runtime.js";
3
3
  export declare function prepareBrowserInput(input: unknown): {
4
4
  command: string;
5
5
  };
6
- export declare function createBrowserTool(runtime: BrowserRuntime): import("@earendil-works/pi-coding-agent").ToolDefinition<Type.TObject<{
7
- command: Type.TString;
6
+ export declare function createBrowserTool(runtime: BrowserRuntime, isGpt?: () => boolean): import("@earendil-works/pi-coding-agent").ToolDefinition<Type.TObject<{
7
+ command: Type.TOptional<Type.TString>;
8
8
  }>, unknown, any> & import("@earendil-works/pi-coding-agent").ToolDefinition<any, any, any>;
@@ -1,9 +1,12 @@
1
1
  import { defineTool } from "@earendil-works/pi-coding-agent";
2
2
  import { Type } from "typebox";
3
+ import { browserHelp } from "./browser/help.js";
3
4
  import { isRecordValue } from "./browser/parse-operation.js";
4
5
  import { parseBrowserRequest } from "./browser/request.js";
5
6
  import { BrowserRuntime } from "./browser/runtime.js";
6
7
  export function prepareBrowserInput(input) {
8
+ if (input === undefined)
9
+ return { command: "help" };
7
10
  if (typeof input === "string")
8
11
  return { command: input };
9
12
  if (!isRecordValue(input)) {
@@ -16,17 +19,21 @@ export function prepareBrowserInput(input) {
16
19
  return { ...input, command: input["command"] };
17
20
  }
18
21
  // Resume old object calls without changing their stored history representation.
22
+ parseBrowserRequest(input);
19
23
  return { command: JSON.stringify(input) };
20
24
  }
21
- export function createBrowserTool(runtime) {
25
+ export function createBrowserTool(runtime, isGpt = () => false) {
22
26
  return defineTool({
23
27
  name: "browser",
24
28
  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 }),
29
+ description: "Control logged-in browser",
30
+ parameters: Type.Object({
31
+ command: Type.Optional(Type.String({ description: "help or JSON request" })),
32
+ }, { additionalProperties: false }),
27
33
  prepareArguments: prepareBrowserInput,
28
34
  async execute(_toolCallId, input, signal, onUpdate, ctx) {
29
- const result = await runtime.execute(parseBrowserRequest(input.command), {
35
+ const request = parseBrowserRequest(input.command);
36
+ let result = await runtime.execute(request, {
30
37
  ownerId: ctx.sessionManager.getSessionId(),
31
38
  signal: signal ?? new AbortController().signal,
32
39
  onOperation(operation, index, total) {
@@ -48,6 +55,8 @@ export function createBrowserTool(runtime) {
48
55
  });
49
56
  },
50
57
  });
58
+ if (isGpt() && "help" in request)
59
+ result = browserHelp(runtime.hosts, true);
51
60
  return {
52
61
  content: [{ type: "text", text: JSON.stringify(result) }],
53
62
  details: result,
@@ -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
@@ -21,9 +21,32 @@ export default async function browserExtension(
21
21
  configError = error instanceof Error ? error.message : String(error);
22
22
  }
23
23
  const runtime = new BrowserRuntime(routes);
24
- const tool = createBrowserTool(runtime);
24
+ let gpt = false;
25
+ const tool = createBrowserTool(runtime, () => gpt);
25
26
  registerBrowserCommand(pi);
26
27
  pi.registerTool(tool);
28
+ try {
29
+ const { registerGptPromptMode } = await import(
30
+ "@howaboua/pi-codex-conversion/prompt-mode"
31
+ );
32
+ registerGptPromptMode(pi, (active) => {
33
+ gpt = active;
34
+ return [tool];
35
+ });
36
+ } catch (error) {
37
+ if (
38
+ !(error instanceof Error) ||
39
+ !("code" in error) ||
40
+ ![
41
+ "ERR_MODULE_NOT_FOUND",
42
+ "MODULE_NOT_FOUND",
43
+ "ERR_PACKAGE_PATH_NOT_EXPORTED",
44
+ ].includes(String(error.code)) ||
45
+ !error.message.includes(CODE_MODE_PACKAGE)
46
+ )
47
+ throw error;
48
+ }
49
+
27
50
  const registration = await registerBrowserInCodeMode(pi, tool);
28
51
  pi.on("session_shutdown", async () => {
29
52
  registration?.unregister();
@@ -47,8 +70,7 @@ async function registerBrowserInCodeMode(
47
70
  adaptToolForCodeMode(tool, {
48
71
  kind: "freeform",
49
72
  prepareInput: prepareBrowserInput,
50
- usage:
51
- 'await tools.browser("help") // Logged-in browser; help before other actions',
73
+ discovery: "help",
52
74
  }),
53
75
  ]);
54
76
  } 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.9",
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": ">=4.0.2",
50
49
  "@earendil-works/pi-ai": ">=1.0.0",
51
50
  "@earendil-works/pi-coding-agent": ">=1.0.0",
52
51
  "typebox": "*",
@@ -58,13 +57,12 @@
58
57
  }
59
58
  },
60
59
  "devDependencies": {
61
- "@howaboua/pi-codex-conversion": "3.0.46",
62
- "@biomejs/biome": "^2.5.10",
63
- "@earendil-works/pi-ai": "1.0.4",
64
- "@earendil-works/pi-coding-agent": "1.0.4",
65
- "@types/node": "^26.2.0",
66
- "tsx": "^4.23.12",
67
- "typebox": "1.3.18",
60
+ "@howaboua/pi-codex-conversion": "4.0.2",
61
+ "@biomejs/biome": "^2.5.15",
62
+ "@earendil-works/pi-ai": "1.3.0",
63
+ "@earendil-works/pi-coding-agent": "1.3.0",
64
+ "@types/node": "^26.6.5",
65
+ "typebox": "1.3.37",
68
66
  "typescript": "^7.0.2"
69
67
  },
70
68
  "pi": {
@@ -1,21 +1,26 @@
1
1
  export function browserHelp(
2
2
  hosts: readonly string[] = [],
3
+ gpt = false,
3
4
  ): Record<string, unknown> {
4
5
  const routed = hosts.length > 0;
5
6
  return {
6
- input:
7
- "Request={action,...fields}; Pi: {command:JSON.stringify(request)}; Code/Notebook: JSON.stringify(request), JSON.parse(result)",
7
+ input: gpt
8
+ ? "Request={action,...fields}; Pi {command:JSON.stringify(request)}; Code/Notebook JSON.stringify(request), JSON.parse(result)"
9
+ : "Request={action,...fields}; Pi: {command:JSON.stringify(request)}; Code/Notebook: JSON.stringify(request), JSON.parse(result)",
8
10
  ...(routed
9
11
  ? {
10
- host: `${hosts.join("|")} optional; keep a user-named host on every call and its refs/handles`,
12
+ host: `${hosts.join("|")}${gpt ? " optional; retain user-named host on every call + refs/handles" : " optional; keep a user-named host on every call and its refs/handles"}`,
11
13
  }
12
14
  : {}),
13
15
  refs: "tabs -> open; keep ref_id/id/cursors with their result",
14
- safety:
15
- "Ask before unfamiliar low-trust navigation or consequential action unless authorized; never close shared browser",
16
- batch:
17
- "{action_name:[{...fields}],...}; nonempty arrays; items omit action; host/response_length at request root; independent only",
16
+ safety: gpt
17
+ ? "Unless authorized, ask before unfamiliar low-trust navigation/consequential action; never close shared browser"
18
+ : "Ask before unfamiliar low-trust navigation or consequential action unless authorized; never close shared browser",
19
+ batch: gpt
20
+ ? "{action_name:[{...fields}],...}; nonempty arrays, no item action; root host/response_length; independent only"
21
+ : "{action_name:[{...fields}],...}; nonempty arrays; items omit action; host/response_length at request root; independent only",
18
22
  actions: {
23
+ help: "",
19
24
  tabs: "query? offset? owned_only? -> ref_id title url owned",
20
25
  open: "ref_id lineno? | url; new tabs open in background",
21
26
  show: "ref_id; bring tab to foreground",
@@ -26,7 +31,7 @@ export function browserHelp(
26
31
  fill: "ref_id id|selector value; replace/clear text, select option value/label, boolean checks/unchecks",
27
32
  press: "ref_id key; focused element, e.g. Enter or Control+a",
28
33
  wait: "ref_id selector|text|url_includes timeout_ms?; DOM presence or substring, default 10000ms",
29
- screenshot: "ref_id id?|selector? -> file",
34
+ screenshot: "ref_id id?|selector?; brings tab to foreground -> file",
30
35
  navigate: "ref_id url",
31
36
  html: "ref_id id?|selector?",
32
37
  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);
@@ -1,10 +1,12 @@
1
1
  import { defineTool } from "@earendil-works/pi-coding-agent";
2
2
  import { Type } from "typebox";
3
+ import { browserHelp } from "./browser/help.js";
3
4
  import { isRecordValue } from "./browser/parse-operation.js";
4
5
  import { parseBrowserRequest } from "./browser/request.js";
5
6
  import { BrowserRuntime } from "./browser/runtime.js";
6
7
 
7
8
  export function prepareBrowserInput(input: unknown): { command: string } {
9
+ if (input === undefined) return { command: "help" };
8
10
  if (typeof input === "string") return { command: input };
9
11
  if (!isRecordValue(input)) {
10
12
  throw new Error("browser input must be a command envelope or JSON request");
@@ -18,21 +20,30 @@ export function prepareBrowserInput(input: unknown): { command: string } {
18
20
  return { ...input, command: input["command"] };
19
21
  }
20
22
  // Resume old object calls without changing their stored history representation.
23
+ parseBrowserRequest(input);
21
24
  return { command: JSON.stringify(input) };
22
25
  }
23
26
 
24
- export function createBrowserTool(runtime: BrowserRuntime) {
27
+ export function createBrowserTool(
28
+ runtime: BrowserRuntime,
29
+ isGpt = () => false,
30
+ ) {
25
31
  return defineTool({
26
32
  name: "browser",
27
33
  label: "Browser",
28
- description: "Control logged-in browser; call help before other actions",
34
+ description: "Control logged-in browser",
29
35
  parameters: Type.Object(
30
- { command: Type.String({ description: "help or JSON request" }) },
36
+ {
37
+ command: Type.Optional(
38
+ Type.String({ description: "help or JSON request" }),
39
+ ),
40
+ },
31
41
  { additionalProperties: false },
32
42
  ),
33
43
  prepareArguments: prepareBrowserInput,
34
44
  async execute(_toolCallId, input, signal, onUpdate, ctx) {
35
- const result = await runtime.execute(parseBrowserRequest(input.command), {
45
+ const request = parseBrowserRequest(input.command);
46
+ let result = await runtime.execute(request, {
36
47
  ownerId: ctx.sessionManager.getSessionId(),
37
48
  signal: signal ?? new AbortController().signal,
38
49
  onOperation(operation, index, total) {
@@ -55,6 +66,8 @@ export function createBrowserTool(runtime: BrowserRuntime) {
55
66
  });
56
67
  },
57
68
  });
69
+ if (isGpt() && "help" in request)
70
+ result = browserHelp(runtime.hosts, true);
58
71
  return {
59
72
  content: [{ type: "text", text: JSON.stringify(result) }],
60
73
  details: result,
@@ -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
  }