@howaboua/pi-browser 0.0.10 → 0.0.12

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 (39) hide show
  1. package/CHANGELOG.md +11 -4
  2. package/README.md +11 -1
  3. package/biome.json +1 -1
  4. package/dist/extension.d.ts +3 -0
  5. package/dist/extension.js +29 -0
  6. package/dist/index.d.ts +1 -2
  7. package/dist/index.js +1 -100
  8. package/dist/remote-worker.js +137 -116
  9. package/dist/src/browser/config.d.ts +2 -0
  10. package/dist/src/browser/config.js +38 -5
  11. package/dist/src/browser/help.js +7 -7
  12. package/dist/src/browser/voice-start.d.ts +16 -0
  13. package/dist/src/browser/voice-start.js +110 -0
  14. package/dist/src/browser-registration.d.ts +6 -0
  15. package/dist/src/browser-registration.js +103 -0
  16. package/dist/src/browser-tool-definition.d.ts +12 -0
  17. package/dist/src/browser-tool-definition.js +63 -0
  18. package/dist/src/browser-tool.d.ts +1 -4
  19. package/dist/src/browser-tool.js +2 -62
  20. package/dist/src/cdp/session.d.ts +3 -8
  21. package/dist/src/cdp/session.js +1 -104
  22. package/dist/src/cdp/snapshot-tree.d.ts +8 -0
  23. package/dist/src/cdp/snapshot-tree.js +238 -0
  24. package/dist/src/cdp/snapshot.js +2 -234
  25. package/dist/src/cdp/tab-bridge.d.ts +25 -0
  26. package/dist/src/cdp/tab-bridge.js +107 -0
  27. package/index.ts +1 -127
  28. package/package.json +12 -8
  29. package/src/browser/config.ts +48 -7
  30. package/src/browser/help.ts +7 -7
  31. package/src/browser/voice-start.ts +154 -0
  32. package/src/browser-registration.ts +138 -0
  33. package/src/browser-tool-definition.ts +81 -0
  34. package/src/browser-tool.ts +3 -69
  35. package/src/cdp/session.ts +3 -145
  36. package/src/cdp/snapshot-tree.ts +291 -0
  37. package/src/cdp/snapshot.ts +5 -282
  38. package/src/cdp/tab-bridge.ts +149 -0
  39. package/tsconfig.json +1 -1
package/index.ts CHANGED
@@ -1,128 +1,2 @@
1
- import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
- import { BrowserRoutes, loadBrowserRoutes } from "./src/browser/routes.js";
3
- import { BrowserRuntime } from "./src/browser/runtime.js";
4
- import { registerBrowserCommand } from "./src/browser/settings.js";
5
- import { createBrowserTool, prepareBrowserInput } from "./src/browser-tool.js";
6
-
1
+ export { default } from "./extension.js";
7
2
  export { createBrowserTool } from "./src/browser-tool.js";
8
-
9
- const CODE_MODE_PACKAGE = "@howaboua/pi-codex-conversion";
10
- const CODE_MODE_MODULE = `${CODE_MODE_PACKAGE}/code-mode`;
11
-
12
- export default async function browserExtension(
13
- pi: ExtensionAPI,
14
- ): Promise<void> {
15
- let configError: string | undefined;
16
- let routes: BrowserRoutes;
17
- try {
18
- routes = loadBrowserRoutes();
19
- } catch (error) {
20
- routes = new BrowserRoutes();
21
- configError = error instanceof Error ? error.message : String(error);
22
- }
23
- const runtime = new BrowserRuntime(routes);
24
- let gpt = false;
25
- const tool = createBrowserTool(runtime, () => gpt);
26
- registerBrowserCommand(pi);
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
-
50
- const registration = await registerBrowserInCodeMode(pi, tool);
51
- pi.on("session_shutdown", async () => {
52
- registration?.unregister();
53
- await runtime.close();
54
- });
55
- if (configError) {
56
- pi.on("session_start", (_event, ctx) => {
57
- ctx.ui.notify(`${configError}. Run /browser to repair it.`, "warning");
58
- });
59
- }
60
- }
61
-
62
- async function registerBrowserInCodeMode(
63
- pi: ExtensionAPI,
64
- tool: ReturnType<typeof createBrowserTool>,
65
- ) {
66
- try {
67
- const { adaptToolForCodeMode, registerCodeModeExtensionTools } =
68
- await import("@howaboua/pi-codex-conversion/code-mode");
69
- return registerCodeModeExtensionTools(pi, () => [
70
- adaptToolForCodeMode(tool, {
71
- kind: "freeform",
72
- prepareInput: prepareBrowserInput,
73
- discovery: "help",
74
- }),
75
- ]);
76
- } catch (error) {
77
- if (isMissingCodeModeExtension(error)) return undefined;
78
- if (isOutdatedCodeModeExtension(error)) {
79
- throw new Error(
80
- "Update " +
81
- CODE_MODE_PACKAGE +
82
- " to 3.0.24 or newer to use Pi Browser with it",
83
- { cause: error },
84
- );
85
- }
86
- throw error;
87
- }
88
- }
89
-
90
- function isMissingCodeModeExtension(error: unknown): boolean {
91
- if (
92
- !error ||
93
- typeof error !== "object" ||
94
- !("code" in error) ||
95
- !("message" in error) ||
96
- typeof error.message !== "string"
97
- ) {
98
- return false;
99
- }
100
- if (
101
- error.code !== "ERR_MODULE_NOT_FOUND" &&
102
- error.code !== "MODULE_NOT_FOUND"
103
- ) {
104
- return false;
105
- }
106
- const missing = error.message.match(
107
- /Cannot find (?:package|module) ['"]([^'"]+)['"]/,
108
- )?.[1];
109
- return missing === CODE_MODE_PACKAGE || missing === CODE_MODE_MODULE;
110
- }
111
-
112
- function isOutdatedCodeModeExtension(error: unknown): boolean {
113
- if (
114
- !error ||
115
- typeof error !== "object" ||
116
- !("code" in error) ||
117
- !("message" in error) ||
118
- typeof error.message !== "string"
119
- )
120
- return false;
121
- return (
122
- (error.code === "ERR_PACKAGE_PATH_NOT_EXPORTED" ||
123
- error.code === "ERR_UNSUPPORTED_DIR_IMPORT") &&
124
- (error.message.includes(CODE_MODE_MODULE) ||
125
- (error.message.includes("Package subpath './code-mode'") &&
126
- error.message.includes(CODE_MODE_PACKAGE)))
127
- );
128
- }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@howaboua/pi-browser",
3
- "version": "0.0.10",
3
+ "version": "0.0.12",
4
4
  "description": "Logged-in browser inspection and control for Pi, Code Mode and Notebook Mode.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -45,7 +45,7 @@
45
45
  "pack:dry": "npm pack --dry-run"
46
46
  },
47
47
  "peerDependencies": {
48
- "@howaboua/pi-codex-conversion": ">=4.0.3",
48
+ "@howaboua/pi-codex-conversion": ">=4.0.6",
49
49
  "@earendil-works/pi-ai": ">=1.0.0",
50
50
  "@earendil-works/pi-coding-agent": ">=1.0.0",
51
51
  "typebox": "*",
@@ -57,18 +57,18 @@
57
57
  }
58
58
  },
59
59
  "devDependencies": {
60
- "@howaboua/pi-codex-conversion": "4.0.3",
61
- "@biomejs/biome": "^2.5.15",
62
- "@earendil-works/pi-ai": "1.3.0",
63
- "@earendil-works/pi-coding-agent": "1.3.0",
60
+ "@howaboua/pi-codex-conversion": "4.0.6",
61
+ "@biomejs/biome": "^2.6.3",
62
+ "@earendil-works/pi-ai": "1.4.0",
63
+ "@earendil-works/pi-coding-agent": "1.4.0",
64
64
  "@types/node": "^26.6.5",
65
- "typebox": "1.3.37",
65
+ "typebox": "1.4.3",
66
66
  "typescript": "^7.0.2"
67
67
  },
68
68
  "pi": {
69
69
  "extensions": [
70
70
  "./changelog.ts",
71
- "./dist/index.js"
71
+ "./dist/extension.js"
72
72
  ]
73
73
  },
74
74
  "engines": {
@@ -80,6 +80,10 @@
80
80
  "main": "./dist/index.js",
81
81
  "types": "./dist/index.d.ts",
82
82
  "exports": {
83
+ "./voice-start": {
84
+ "types": "./dist/src/browser/voice-start.d.ts",
85
+ "import": "./dist/src/browser/voice-start.js"
86
+ },
83
87
  ".": {
84
88
  "types": "./dist/index.d.ts",
85
89
  "import": "./dist/index.js"
@@ -15,12 +15,14 @@ export interface BrowserRouteConfig {
15
15
  aliases: Record<string, string>;
16
16
  hosts: string[];
17
17
  remoteNodePath: string;
18
+ voiceOnly?: boolean;
18
19
  }
19
20
 
20
21
  interface BrowserRouteConfigInput {
21
22
  aliases?: Record<string, string>;
22
23
  hosts?: string[];
23
24
  remoteNodePath?: string;
25
+ voiceOnly?: unknown;
24
26
  }
25
27
 
26
28
  const ROUTE_NAME = /^[A-Za-z0-9_.-]+$/;
@@ -70,6 +72,9 @@ export function normalizeBrowserRouteConfig(
70
72
  throw new Error("pi-browser config must be an object");
71
73
  }
72
74
  const input = value as BrowserRouteConfigInput;
75
+ if (input.voiceOnly !== undefined && typeof input.voiceOnly !== "boolean") {
76
+ throw new Error("pi-browser voiceOnly must be a boolean");
77
+ }
73
78
  const rawHosts = input.hosts ?? [];
74
79
  if (!Array.isArray(rawHosts)) {
75
80
  throw new Error("pi-browser config hosts must be an array");
@@ -101,6 +106,7 @@ export function normalizeBrowserRouteConfig(
101
106
  return {
102
107
  aliases,
103
108
  hosts,
109
+ ...(input.voiceOnly === true ? { voiceOnly: true } : {}),
104
110
  remoteNodePath: remoteWord(
105
111
  input.remoteNodePath ?? DEFAULT_REMOTE_NODE_PATH,
106
112
  "pi-browser remoteNodePath",
@@ -108,9 +114,7 @@ export function normalizeBrowserRouteConfig(
108
114
  };
109
115
  }
110
116
 
111
- export function readBrowserRouteConfig(
112
- path = browserConfigPath(),
113
- ): BrowserRouteConfig {
117
+ function readBrowserConfig(path: string): unknown {
114
118
  let source: string;
115
119
  try {
116
120
  source = readFileSync(path, "utf8");
@@ -121,12 +125,43 @@ export function readBrowserRouteConfig(
121
125
  "code" in error &&
122
126
  error.code === "ENOENT"
123
127
  ) {
124
- return defaultBrowserRouteConfig();
128
+ return undefined;
125
129
  }
126
130
  throw error;
127
131
  }
128
132
  try {
129
- return normalizeBrowserRouteConfig(JSON.parse(source));
133
+ return JSON.parse(source);
134
+ } catch (error) {
135
+ throw new Error(
136
+ `Invalid pi-browser config at ${path}: ${error instanceof Error ? error.message : String(error)}`,
137
+ );
138
+ }
139
+ }
140
+
141
+ export function readBrowserVoiceOnly(path = browserConfigPath()): boolean {
142
+ const value = readBrowserConfig(path);
143
+ if (value === undefined) return false;
144
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
145
+ throw new Error(
146
+ `Invalid pi-browser config at ${path}: pi-browser config must be an object`,
147
+ );
148
+ }
149
+ const voiceOnly = (value as BrowserRouteConfigInput).voiceOnly;
150
+ if (voiceOnly !== undefined && typeof voiceOnly !== "boolean") {
151
+ throw new Error(
152
+ `Invalid pi-browser config at ${path}: pi-browser voiceOnly must be a boolean`,
153
+ );
154
+ }
155
+ return voiceOnly === true;
156
+ }
157
+
158
+ export function readBrowserRouteConfig(
159
+ path = browserConfigPath(),
160
+ ): BrowserRouteConfig {
161
+ const value = readBrowserConfig(path);
162
+ if (value === undefined) return defaultBrowserRouteConfig();
163
+ try {
164
+ return normalizeBrowserRouteConfig(value);
130
165
  } catch (error) {
131
166
  throw new Error(
132
167
  `Invalid pi-browser config at ${path}: ${error instanceof Error ? error.message : String(error)}`,
@@ -139,7 +174,7 @@ export function writeBrowserRouteConfig(
139
174
  path = browserConfigPath(),
140
175
  ): void {
141
176
  const normalized = normalizeBrowserRouteConfig(config);
142
- if (normalized.hosts.length === 0) {
177
+ if (normalized.hosts.length === 0 && !normalized.voiceOnly) {
143
178
  rmSync(path, { force: true });
144
179
  return;
145
180
  }
@@ -149,8 +184,14 @@ export function writeBrowserRouteConfig(
149
184
  directory,
150
185
  `.${basename(path)}.${process.pid}.${randomUUID()}.tmp`,
151
186
  );
187
+ const stored =
188
+ normalized.voiceOnly &&
189
+ normalized.hosts.length === 0 &&
190
+ normalized.remoteNodePath === DEFAULT_REMOTE_NODE_PATH
191
+ ? { voiceOnly: true }
192
+ : normalized;
152
193
  try {
153
- writeFileSync(temporary, `${JSON.stringify(normalized, null, 2)}\n`, {
194
+ writeFileSync(temporary, `${JSON.stringify(stored, null, 2)}\n`, {
154
195
  encoding: "utf8",
155
196
  flag: "wx",
156
197
  mode: 0o600,
@@ -4,20 +4,20 @@ export function browserHelp(
4
4
  ): Record<string, unknown> {
5
5
  const routed = hosts.length > 0;
6
6
  return {
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)",
7
+ input: "{action,...fields}",
10
8
  ...(routed
11
9
  ? {
12
- host: `${hosts.join("|")}${gpt ? " optional; user-named host→retain every call+its refs/handles" : " optional; keep a user-named host on every call and its refs/handles"}`,
10
+ host: `${hosts.join("|")}${gpt ? " optional; user-named host→retain EVERY call+refs/handles" : " optional; keep a user-named host on every call and its refs/handles"}`,
13
11
  }
14
12
  : {}),
15
- refs: "tabs -> open; keep ref_id/id/cursors with their result",
13
+ refs: gpt
14
+ ? "tabs→open; ref_id/id/cursors stay with result"
15
+ : "tabs -> open; keep ref_id/id/cursors with their result",
16
16
  safety: gpt
17
- ? "Unfamiliar low-trust navigation/consequential action→ask first unless authorized; never close shared browser"
17
+ ? "Unfamiliar low-trust navigation/consequential action→ask UNLESS authorised; NEVER close shared browser"
18
18
  : "Ask before unfamiliar low-trust navigation or consequential action unless authorized; never close shared browser",
19
19
  batch: gpt
20
- ? "{action_name:[{...fields}],...}; arrays nonempty; items omit action; host/response_length at root; independent only"
20
+ ? "{action_name:[{...fields}],...}; nonempty arrays; omit item action; root host/response_length; independent ONLY"
21
21
  : "{action_name:[{...fields}],...}; nonempty arrays; items omit action; host/response_length at request root; independent only",
22
22
  actions: {
23
23
  help: "",
@@ -0,0 +1,154 @@
1
+ import { sleep } from "../cdp/discovery.js";
2
+ import { asRecord, errorMessage } from "../cdp/types.js";
3
+ import { assertHttpUrl } from "../cdp/url.js";
4
+ import type { BrowserOperation } from "./operation.js";
5
+ import { BrowserRuntime } from "./runtime.js";
6
+
7
+ export interface BrowserVoiceStartOptions {
8
+ url: string;
9
+ host?: string;
10
+ provider: "codex" | "gippity" | "grok";
11
+ signal?: AbortSignal;
12
+ timeoutMs?: number;
13
+ }
14
+
15
+ export interface BrowserVoiceStartResult {
16
+ state: "listening" | "error" | "timeout";
17
+ url: string;
18
+ refId?: string;
19
+ status: string;
20
+ detail: string;
21
+ }
22
+
23
+ // Read the bundled frontends' acknowledged audio state, not socket connectivity
24
+ // or the fact that a click was dispatched. No permissions or trust are changed.
25
+ const CONVERSATION_STATE = String.raw`(() => {
26
+ const button = document.querySelector('#voice');
27
+ const status = document.querySelector('#audio-state')?.textContent?.trim() || '';
28
+ const detail = document.querySelector('#audio-detail')?.textContent?.trim() || '';
29
+ const listening = button?.dataset.mode === 'conversation' && button?.getAttribute('aria-pressed') === 'true' && status === 'Listening';
30
+ const failed = ['Could not start', 'Voice disconnected', 'Could not reconnect', 'Moved to another device', 'Transferred session ended', 'Microphone muted'].includes(status);
31
+ return {state: listening ? 'listening' : failed ? 'error' : button && !button.disabled && button.getAttribute('aria-busy') !== 'true' && button.getAttribute('aria-pressed') !== 'true' && button.dataset.mode === 'conversation' ? 'ready' : 'waiting', status, detail};
32
+ })()`;
33
+
34
+ const GROK_STATE = String.raw`(() => {
35
+ const button = document.querySelector('#start');
36
+ const status = document.querySelector('#status')?.textContent?.trim() || '';
37
+ const detail = document.querySelector('#error')?.textContent?.trim() || '';
38
+ const mode = document.querySelector('#mode')?.value;
39
+ const muted = document.querySelector('#mute')?.getAttribute('aria-pressed') === 'true';
40
+ const listening = !muted && mode === 'voice' && /^listening(?: ·|$)/.test(status) && status.includes(' · browser microphone connected');
41
+ return {state: detail || muted ? 'error' : listening ? 'listening' : button && !button.disabled && mode === 'voice' ? 'ready' : 'waiting', status, detail: muted ? 'Microphone is muted. Unmute it in the voice page.' : detail};
42
+ })()`;
43
+
44
+ interface PageState {
45
+ state: "listening" | "ready" | "waiting" | "error";
46
+ status: string;
47
+ detail: string;
48
+ }
49
+
50
+ function pageState(result: Record<string, unknown>): PageState {
51
+ if (typeof result["value"] !== "string")
52
+ throw new Error("Voice page did not return its audio status");
53
+ const value = asRecord(JSON.parse(result["value"]), "Voice page status");
54
+ const state = value["state"];
55
+ if (
56
+ (state !== "listening" &&
57
+ state !== "ready" &&
58
+ state !== "waiting" &&
59
+ state !== "error") ||
60
+ typeof value["status"] !== "string" ||
61
+ typeof value["detail"] !== "string"
62
+ )
63
+ throw new Error("Voice page returned an invalid audio status");
64
+ return { state, status: value["status"], detail: value["detail"] };
65
+ }
66
+
67
+ /** Start once in a new tab; disconnect automation without closing the tab. */
68
+ export async function startBrowserVoice(
69
+ options: BrowserVoiceStartOptions,
70
+ ): Promise<BrowserVoiceStartResult> {
71
+ const timeoutMs = options.timeoutMs ?? 30_000;
72
+ if (
73
+ !Number.isInteger(timeoutMs) ||
74
+ timeoutMs <= 0 ||
75
+ timeoutMs > 2_147_483_647
76
+ )
77
+ throw new Error(
78
+ "Voice browser timeout must fit a positive signed 32-bit millisecond timer",
79
+ );
80
+ assertHttpUrl(options.url);
81
+ if (!["codex", "gippity", "grok"].includes(options.provider))
82
+ throw new Error("Unsupported voice page provider");
83
+ const timeout = AbortSignal.timeout(timeoutMs);
84
+ const signal = options.signal
85
+ ? AbortSignal.any([options.signal, timeout])
86
+ : timeout;
87
+ let runtime: BrowserRuntime | undefined;
88
+ let refId: string | undefined;
89
+ let observed: PageState = { state: "waiting", status: "", detail: "" };
90
+ let clicked = false;
91
+ const result = (
92
+ state: BrowserVoiceStartResult["state"],
93
+ detail = observed.detail,
94
+ ): BrowserVoiceStartResult => ({
95
+ state,
96
+ url: options.url,
97
+ ...(refId ? { refId } : {}),
98
+ status: observed.status,
99
+ detail,
100
+ });
101
+ try {
102
+ const browser = new BrowserRuntime();
103
+ runtime = browser;
104
+ const execute = (operation: BrowserOperation) =>
105
+ browser.execute(
106
+ {
107
+ operations: [operation],
108
+ ...(options.host ? { host: options.host } : {}),
109
+ },
110
+ { signal },
111
+ );
112
+ const opened = await execute({ action: "open", url: options.url });
113
+ if (opened["owned"] !== true || typeof opened["ref_id"] !== "string")
114
+ throw new Error("Browser did not confirm ownership of the new voice tab");
115
+ refId = opened["ref_id"];
116
+ await execute({
117
+ action: "wait",
118
+ ref_id: refId,
119
+ selector: options.provider === "grok" ? "#start" : "#voice",
120
+ timeout_ms: timeoutMs,
121
+ });
122
+ while (true) {
123
+ signal.throwIfAborted();
124
+ observed = pageState(
125
+ await execute({
126
+ action: "evaluate",
127
+ ref_id: refId,
128
+ expression:
129
+ options.provider === "grok" ? GROK_STATE : CONVERSATION_STATE,
130
+ }),
131
+ );
132
+ if (observed.state === "listening") return result("listening");
133
+ if (observed.state === "error") return result("error");
134
+ if (!clicked && observed.state === "ready") {
135
+ // Never retry a possibly dispatched start: it may toggle an active call.
136
+ clicked = true;
137
+ await execute({
138
+ action: "click",
139
+ ref_id: refId,
140
+ selector: options.provider === "grok" ? "#start" : "#voice",
141
+ });
142
+ }
143
+ await sleep(200, signal);
144
+ }
145
+ } catch (error) {
146
+ return result(
147
+ timeout.aborted && !options.signal?.aborted ? "timeout" : "error",
148
+ `${errorMessage(error)}${observed.detail ? ` · ${observed.detail}` : ""}`,
149
+ );
150
+ } finally {
151
+ // Disconnect automation only; the page owns the continuing microphone.
152
+ await runtime?.close();
153
+ }
154
+ }
@@ -0,0 +1,138 @@
1
+ import type { defineTool, ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import type { Type } from "typebox";
3
+ import { BrowserRoutes, loadBrowserRoutes } from "./browser/routes.js";
4
+ import { BrowserRuntime } from "./browser/runtime.js";
5
+ import { registerBrowserCommand } from "./browser/settings.js";
6
+ import {
7
+ createBrowserTool,
8
+ prepareBrowserInput,
9
+ } from "./browser-tool-definition.js";
10
+
11
+ const CODE_MODE_PACKAGE = "@howaboua/pi-codex-conversion";
12
+ const CODE_MODE_MODULE = `${CODE_MODE_PACKAGE}/code-mode`;
13
+
14
+ export default async function browserExtension(
15
+ pi: ExtensionAPI,
16
+ sdk: { defineTool: typeof defineTool; Type: typeof Type },
17
+ ): Promise<void> {
18
+ let configError: string | undefined;
19
+ let routes: BrowserRoutes;
20
+ try {
21
+ routes = loadBrowserRoutes();
22
+ } catch (error) {
23
+ routes = new BrowserRoutes();
24
+ configError = error instanceof Error ? error.message : String(error);
25
+ }
26
+ const runtime = new BrowserRuntime(routes);
27
+ let gpt = false;
28
+ const tool = createBrowserTool(sdk, runtime, () => gpt);
29
+ registerBrowserCommand(pi);
30
+ pi.registerTool(tool);
31
+ try {
32
+ const { registerGptPromptMode } = await import(
33
+ "@howaboua/pi-codex-conversion/prompt-mode"
34
+ );
35
+ registerGptPromptMode(pi, (active) => {
36
+ gpt = active;
37
+ return [tool];
38
+ });
39
+ } catch (error) {
40
+ if (
41
+ !(error instanceof Error) ||
42
+ !("code" in error) ||
43
+ ![
44
+ "ERR_MODULE_NOT_FOUND",
45
+ "MODULE_NOT_FOUND",
46
+ "ERR_PACKAGE_PATH_NOT_EXPORTED",
47
+ ].includes(String(error.code)) ||
48
+ !error.message.includes(CODE_MODE_PACKAGE)
49
+ )
50
+ throw error;
51
+ }
52
+
53
+ const registration = await registerBrowserInCodeMode(pi, tool, sdk);
54
+ pi.on("session_shutdown", async () => {
55
+ registration?.unregister();
56
+ await runtime.close();
57
+ });
58
+ if (configError) {
59
+ pi.on("session_start", (_event, ctx) => {
60
+ ctx.ui.notify(`${configError}. Run /browser to repair it.`, "warning");
61
+ });
62
+ }
63
+ }
64
+
65
+ async function registerBrowserInCodeMode(
66
+ pi: ExtensionAPI,
67
+ tool: ReturnType<typeof createBrowserTool>,
68
+ sdk: { Type: typeof Type },
69
+ ) {
70
+ try {
71
+ const { adaptToolForCodeMode, registerCodeModeExtensionTools } =
72
+ await import("@howaboua/pi-codex-conversion/code-mode");
73
+ return registerCodeModeExtensionTools(pi, () => [
74
+ adaptToolForCodeMode(
75
+ {
76
+ ...tool,
77
+ parameters: sdk.Type.Object({}, { additionalProperties: true }),
78
+ },
79
+ {
80
+ prepareInput: prepareBrowserInput,
81
+ discovery: "help",
82
+ resultValue: (result) => result.details,
83
+ },
84
+ ),
85
+ ]);
86
+ } catch (error) {
87
+ if (isMissingCodeModeExtension(error)) return undefined;
88
+ if (isOutdatedCodeModeExtension(error)) {
89
+ throw new Error(
90
+ "Update " +
91
+ CODE_MODE_PACKAGE +
92
+ " to 3.0.24 or newer to use Pi Browser with it",
93
+ { cause: error },
94
+ );
95
+ }
96
+ throw error;
97
+ }
98
+ }
99
+
100
+ function isMissingCodeModeExtension(error: unknown): boolean {
101
+ if (
102
+ !error ||
103
+ typeof error !== "object" ||
104
+ !("code" in error) ||
105
+ !("message" in error) ||
106
+ typeof error.message !== "string"
107
+ ) {
108
+ return false;
109
+ }
110
+ if (
111
+ error.code !== "ERR_MODULE_NOT_FOUND" &&
112
+ error.code !== "MODULE_NOT_FOUND"
113
+ ) {
114
+ return false;
115
+ }
116
+ const missing = error.message.match(
117
+ /Cannot find (?:package|module) ['"]([^'"]+)['"]/,
118
+ )?.[1];
119
+ return missing === CODE_MODE_PACKAGE || missing === CODE_MODE_MODULE;
120
+ }
121
+
122
+ function isOutdatedCodeModeExtension(error: unknown): boolean {
123
+ if (
124
+ !error ||
125
+ typeof error !== "object" ||
126
+ !("code" in error) ||
127
+ !("message" in error) ||
128
+ typeof error.message !== "string"
129
+ )
130
+ return false;
131
+ return (
132
+ (error.code === "ERR_PACKAGE_PATH_NOT_EXPORTED" ||
133
+ error.code === "ERR_UNSUPPORTED_DIR_IMPORT") &&
134
+ (error.message.includes(CODE_MODE_MODULE) ||
135
+ (error.message.includes("Package subpath './code-mode'") &&
136
+ error.message.includes(CODE_MODE_PACKAGE)))
137
+ );
138
+ }
@@ -0,0 +1,81 @@
1
+ import type { defineTool as definePiTool } from "@earendil-works/pi-coding-agent";
2
+ import type { Type as SchemaType } from "typebox";
3
+ import { browserHelp } from "./browser/help.js";
4
+ import { isRecordValue } from "./browser/parse-operation.js";
5
+ import { parseBrowserRequest } from "./browser/request.js";
6
+ import type { BrowserRuntime } from "./browser/runtime.js";
7
+
8
+ export function prepareBrowserInput(input: unknown): { command: string } {
9
+ if (input === undefined) return { command: "help" };
10
+ if (typeof input === "string") return { command: input };
11
+ if (!isRecordValue(input)) {
12
+ throw new Error("browser input must be a command envelope or JSON request");
13
+ }
14
+ if (Object.hasOwn(input, "command")) {
15
+ if (typeof input["command"] !== "string") {
16
+ throw new Error(
17
+ 'browser command must be "help" or a JSON request string',
18
+ );
19
+ }
20
+ return { ...input, command: input["command"] };
21
+ }
22
+ // Resume old object calls without changing their stored history representation.
23
+ parseBrowserRequest(input);
24
+ return { command: JSON.stringify(input) };
25
+ }
26
+
27
+ export function createBrowserTool(
28
+ {
29
+ defineTool,
30
+ Type,
31
+ }: { defineTool: typeof definePiTool; Type: typeof SchemaType },
32
+ runtime: BrowserRuntime,
33
+ isGpt = () => false,
34
+ ) {
35
+ return defineTool({
36
+ name: "browser",
37
+ label: "Browser",
38
+ description: "Control logged-in browser",
39
+ parameters: Type.Object(
40
+ {
41
+ command: Type.Optional(
42
+ Type.String({ description: "help or JSON request" }),
43
+ ),
44
+ },
45
+ { additionalProperties: false },
46
+ ),
47
+ prepareArguments: prepareBrowserInput,
48
+ async execute(_toolCallId, input, signal, onUpdate, ctx) {
49
+ const request = parseBrowserRequest(input.command);
50
+ let result = await runtime.execute(request, {
51
+ ownerId: ctx.sessionManager.getSessionId(),
52
+ signal: signal ?? new AbortController().signal,
53
+ onOperation(operation, index, total) {
54
+ onUpdate?.({
55
+ content: [
56
+ {
57
+ type: "text",
58
+ text:
59
+ total === 1
60
+ ? `Browser ${operation.action}`
61
+ : `Browser ${operation.action} ${index + 1}/${total}`,
62
+ },
63
+ ],
64
+ details: {
65
+ action: operation.action,
66
+ index: index + 1,
67
+ total,
68
+ status: "running",
69
+ },
70
+ });
71
+ },
72
+ });
73
+ if (isGpt() && "help" in request)
74
+ result = browserHelp(runtime.hosts, true);
75
+ return {
76
+ content: [{ type: "text", text: JSON.stringify(result) }],
77
+ details: result,
78
+ };
79
+ },
80
+ });
81
+ }