pi-browser-use 0.9.5 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,916 +1,29 @@
1
- import { mkdirSync, writeFileSync } from 'node:fs';
2
- import { dirname } from 'node:path';
3
- import { Type } from 'typebox';
4
- import { DevToolsClient } from './client.js';
5
- import { DEFAULT_PROFILE_DIR, resolveConfig, resolveModeTarget, } from './config.js';
1
+ import { createBrowserRuntime } from './runtime.js';
6
2
  import { isProjectTrusted, loadConfig } from './settings.js';
7
- import { augmentToolDescription, classifyPageState, extractTextContent, looksLikeLoginWall, looksOverlayBlocked, OVERLAY_RECOVERABLE, postProcessToolResult, } from './tool-augment.js';
8
- import { pickImageData, resolveArtifactTarget } from './artifacts.js';
9
- import { CLEANUP_ANNOTATIONS, formatAnnotatedMap, INJECT_ANNOTATIONS, parseAnnotatedElements, } from './annotate.js';
10
- import { diagnose, formatDoctorReport } from './doctor.js';
11
- import { checkExistingCloseAllowed, normalizeTabUrl, openExistingPage, parseMcpPageList, } from './existing-flow.js';
12
- import { checkSharedCloseAllowed, claimPage, livePeerSessions, newSessionId, releasePages, } from './shared-backend.js';
13
- import { applyNewPageDefaults, applySelectPageDefaults } from './focus-policy.js';
14
- import { frontProcessByPid } from './chrome-launcher.js';
15
- import { PersistentBackend, shouldSelfLaunch } from './persistent-backend.js';
16
- import { loadPersistentMetadata, loadSitePreferences, markAutomationResult, saveSitePreferences, } from './persistent-store.js';
17
- import { prepareBrowserProfile } from './profile.js';
18
- import { runBootstrap, runReauth } from './setup-flow.js';
19
- import { normalizeOrigin, rememberExecutionPreference, resolveExecutionForOrigin, } from './session-manager.js';
20
- import { DEFAULT_BRIDGE_PORT, TabBridge } from './tab-bridge.js';
21
- import { createRegistryVisionCaller, handleAnalyzeScreenshot, } from './vision.js';
3
+ import { createRegistryVisionCaller } from './vision.js';
22
4
  export { configToArgs, resolveConfig } from './config.js';
23
- // All upstream tools are re-exported with this prefix to avoid name collisions.
24
- const TOOL_PREFIX = 'browser_';
25
- async function callUpstream(client, name, params, signal) {
26
- return (await client.callTool(name, params, signal));
27
- }
28
- // Noisy, slow, or privileged upstream tools; skipped during registration.
29
- const EXCLUDED_TOOLS = new Set([
30
- 'lighthouse_audit',
31
- 'performance_analyze_insight',
32
- 'performance_start_trace',
33
- 'performance_stop_trace',
34
- 'screencast_start',
35
- 'screencast_stop',
36
- 'install_extension',
37
- 'list_extensions',
38
- 'reload_extension',
39
- 'trigger_extension_action',
40
- 'uninstall_extension',
41
- ]);
42
- function toToolContent(result, originalName) {
43
- const textContent = extractTextContent(result.content);
44
- const processed = postProcessToolResult(originalName, textContent);
45
- const content = [];
46
- if (processed !== textContent) {
47
- content.push({ type: 'text', text: processed });
48
- }
49
- else if (result.content) {
50
- for (const item of result.content) {
51
- if (item.type === 'text' && item.text)
52
- content.push({ type: 'text', text: item.text });
53
- }
54
- }
55
- if (result.content) {
56
- for (const item of result.content) {
57
- if (item.type === 'image' && item.data) {
58
- content.push({ type: 'image', data: item.data, mimeType: item.mimeType ?? 'image/png' });
59
- }
60
- }
61
- }
62
- if (content.length === 0)
63
- content.push({ type: 'text', text: '' });
64
- return result.isError ? { content, isError: true } : { content };
65
- }
66
- /**
67
- * Pi extension entry point. On session_start spawns chrome-devtools-mcp,
68
- * discovers upstream tools, and registers each as browser_*. On
69
- * session_shutdown tears the subprocess down. Nothing runs persistently.
70
- *
71
- * Defaults are persistent headless (Pi-owned profile, no window, no consent
72
- * popups). Set mode "fresh" for an isolated clean room, or "existing" with
73
- * autoConnect/browserUrl to drive an already-running Chrome.
74
- */
5
+ /** Native Pi owns settings/trust and model credentials, not browser behavior. */
75
6
  export default function browserUseExtension(pi) {
76
- let config;
77
- let client;
78
- // Pi-owned persistent Chrome (self-launched, MCP attached via browserUrl).
79
- // Set only for persistent mode when the legacy MCP-launch path is off.
80
- let ownBackend;
81
- // Existing-mode tab broker bridge. Lazy; lives for the whole session.
82
- let bridge;
83
- // Last navigated origin: drives the per-origin headed-background fallback.
84
- let lastOrigin;
85
- // URLs Pi opened or navigated to in Existing mode (raw + normalized): the
86
- // only close_page targets allowed there without explicit force:true.
87
- const piOwnedUrls = new Set();
88
- // This extension load's agent-session identity for the shared registry.
89
- const sessionId = newSessionId();
90
- const myOwner = { sessionId, pid: process.pid };
91
- const shortSession = sessionId.slice(0, 8);
92
- /** Registry home: the persistent profile, or the default home for existing. */
93
- function registryDir() {
94
- return currentMode === 'persistent' ? persistentProfileDir(config ?? {}) : DEFAULT_PROFILE_DIR;
95
- }
96
- function trackPiUrl(url) {
97
- piOwnedUrls.add(url);
98
- piOwnedUrls.add(normalizeTabUrl(url));
99
- }
100
- // Tracks which identity the live backend holds, so results can suggest
101
- // escalation. 'custom' covers user-configured attach setups we did not pick.
102
- let currentMode = 'fresh';
103
- function describeMode() {
104
- if (config?.sessionMode === 'isolated')
105
- return 'fresh';
106
- if (config?.sessionMode === 'persistent')
107
- return 'persistent';
108
- if (config?.sessionMode === 'existing')
109
- return 'existing';
110
- return 'custom';
111
- }
112
- function persistentProfileDir(cfg) {
113
- return cfg.userDataDir ?? DEFAULT_PROFILE_DIR;
114
- }
115
- /** Close the MCP transport and any Pi-owned Chrome. The bridge survives. */
116
- async function teardownBackend() {
117
- if (client) {
118
- try {
119
- await client.close();
120
- }
121
- catch {
122
- // A half-dead transport must not block the switch.
123
- }
124
- client = undefined;
125
- }
126
- if (ownBackend) {
127
- try {
128
- await ownBackend.stop();
129
- }
130
- catch {
131
- // Shutdown is best-effort; the profile lock release inside never
132
- // throws fatally, so a new backend can still start.
133
- }
134
- ownBackend = undefined;
135
- }
136
- }
137
- function pinCurrentSite(profileDir, headed) {
138
- if (!lastOrigin)
139
- return false;
140
- const prefs = rememberExecutionPreference(loadSitePreferences(profileDir), lastOrigin, headed ? 'headed-background' : 'headless');
141
- saveSitePreferences(profileDir, prefs);
142
- return true;
143
- }
144
- /**
145
- * Rebuild the backend for a mode switch. Shared by the switch tool and
146
- * automatic escalation so both paths behave identically. Persistent
147
- * self-launches Pi-owned Chrome (MCP attaches via browserUrl) unless
148
- * PI_BROWSER_USE_LEGACY_PERSISTENT=1. A per-origin headed-background pin
149
- * wins over a headless request so one headless-hostile site never
150
- * downgrades every site.
151
- */
152
- async function switchBackend(mode, headed, signal, opts) {
153
- const next = resolveConfig(resolveModeTarget(config ?? {}, mode, headed));
154
- await teardownBackend();
155
- let effectiveHeaded = headed;
156
- let backendNote = '';
157
- if (mode === 'persistent' && shouldSelfLaunch(next)) {
158
- const profileDir = persistentProfileDir(next);
159
- if (opts?.rememberSite === true)
160
- pinCurrentSite(profileDir, headed);
161
- if (!headed && lastOrigin) {
162
- const pinned = resolveExecutionForOrigin(loadSitePreferences(profileDir), lastOrigin, 'headless');
163
- if (pinned === 'headed-background') {
164
- effectiveHeaded = true;
165
- backendNote = ` (${normalizeOrigin(lastOrigin)} prefers the visible fallback)`;
166
- }
167
- }
168
- ownBackend = new PersistentBackend({ config: next, headed: effectiveHeaded, sessionId });
169
- const attach = await ownBackend.start(signal);
170
- client = new DevToolsClient(attach);
171
- markAutomationResult(profileDir, effectiveHeaded ? 'headed' : 'headless');
172
- }
173
- else {
174
- if (mode === 'persistent' && opts?.rememberSite === true) {
175
- pinCurrentSite(persistentProfileDir(next), headed);
176
- }
177
- prepareBrowserProfile(next);
178
- client = new DevToolsClient(next);
179
- }
180
- await client.ensureReady(signal);
181
- // Record what actually launched (a per-origin pin may have upgraded
182
- // headless to headed-background) so status/doctor tell the truth.
183
- next.headless = !effectiveHeaded;
184
- config = next;
185
- currentMode = mode;
186
- return { next, effectiveHeaded, backendNote };
187
- }
188
- /** Start the Existing-mode tab broker bridge on demand. */
189
- async function ensureBridge() {
190
- if (bridge)
191
- return bridge;
192
- const port = config?.tabBridgePort ?? DEFAULT_BRIDGE_PORT;
193
- if (port === 0)
194
- throw new Error('The tab bridge is disabled (tabBridgePort: 0).');
195
- bridge = new TabBridge({ port });
196
- await bridge.start();
197
- return bridge;
198
- }
199
- function loginWallHint(url, text) {
200
- if (currentMode !== 'fresh')
201
- return '';
202
- if (!looksLikeLoginWall(url, text))
203
- return '';
204
- return '\n\nHint: this looks like a login wall in a fresh (logged-out) session. If the page needs your identity, call browser_switch_mode({"mode": "persistent"}) — a human must complete any SSO, 2FA, or passkey step, ideally headed.';
205
- }
206
- function sameOrigin(a, b) {
207
- try {
208
- if (!a || !b)
209
- return false;
210
- return new URL(a).origin === new URL(b).origin;
211
- }
212
- catch {
213
- return false;
214
- }
215
- }
216
- /**
217
- * Automatic escalation for hard blocks the agent cannot clear alone.
218
- * Returns prompt text for the agent to relay, or empty when nothing
219
- * applies. Escalates at most once per call; never loops, never retries
220
- * a challenge page, and never switches away from an attached session.
221
- *
222
- * Challenges only escalate with navigation context: a stale "Just a
223
- * moment..." shortcut tile on a New Tab snapshot must not rebuild the
224
- * backend, and a challenge on another origin than requested means the
225
- * navigation never landed there.
226
- */
227
- async function escalateBlockedPage(url, text, signal, context) {
228
- const state = classifyPageState(url, text);
229
- if (state === 'ok')
230
- return '';
231
- if (state === 'challenge') {
232
- if (context?.tool !== 'navigate_page')
233
- return '';
234
- if (context.requestedUrl && url && !sameOrigin(context.requestedUrl, url)) {
235
- // Challenge-provider handoffs (dedicated challenge domains) still
236
- // count; anything else means the navigation never landed there.
237
- const host = (() => {
238
- try {
239
- return new URL(url).hostname;
240
- }
241
- catch {
242
- return '';
243
- }
244
- })();
245
- if (!/challenge|turnstile|captcha|cf-chl|kasada|perimeterx|datadome/i.test(host))
246
- return '';
247
- }
248
- }
249
- if (state === 'login-wall') {
250
- if (currentMode === 'fresh')
251
- return loginWallHint(url, text);
252
- if (currentMode === 'custom' || currentMode === 'existing') {
253
- return '\n\nThis page needs an identity this session does not have. Sign in is required — complete it in the visible browser, then retry.';
254
- }
255
- if (config?.headless === false) {
256
- return '\n\nThis page needs a login and the browser is already visible. Sign in in that window, then retry — no relaunch, nothing closed.';
257
- }
258
- return await escalateToHeaded(url ?? 'this page');
259
- }
260
- // Challenge (bot check): identity never helps; only a human-gated
261
- // headed window can clear it. Stay in the same mode.
262
- if (config?.headless === false) {
263
- return '\n\nA bot challenge is blocking this page and the browser is already visible. Complete the challenge in the window, then retry.';
264
- }
265
- if (currentMode === 'custom' || currentMode === 'existing') {
266
- return '\n\nA bot challenge is blocking this page. Complete it in the visible browser, then retry — do not loop against the challenge.';
267
- }
268
- return await escalateToHeaded(url ?? 'this page');
269
- }
270
- /**
271
- * Rebuild the current backend headed so a human can act (log in, clear
272
- * a challenge), then tell the agent exactly what to relay. Attach
273
- * sessions are already visible and owned by the user: prompt only. The
274
- * headed window is navigated to the blocked page and fronted: auth
275
- * handoff is the one case where taking foreground is the job, not a bug.
276
- */
277
- async function escalateToHeaded(url, signal) {
278
- const mode = currentMode === 'persistent' ? 'persistent' : 'fresh';
279
- try {
280
- await switchBackend(mode, true, signal);
281
- }
282
- catch (error) {
283
- return `\n\nBlocked on ${url} and the headed browser failed to launch (${error instanceof Error ? error.message : String(error)}). Ask the user to proceed manually.`;
284
- }
285
- if (/^https?:\/\//.test(url)) {
286
- // Best effort: the window is already open for manual navigation.
287
- try {
288
- await callUpstream(client, 'new_page', { url, background: false }, signal);
289
- }
290
- catch {
291
- // Manual navigation in the opened window covers this.
292
- }
293
- }
294
- // Front Pi-owned Chrome so the handoff window is actually visible.
295
- // Fresh MCP-launched Chrome fronts itself; only Pi-owned needs help.
296
- if (ownBackend)
297
- frontProcessByPid(ownBackend.pid());
298
- return `\n\nBlocked on ${url}: a browser window just opened on that page (same ${mode} session — previous tabs are gone, re-list pages after). Please complete the login or challenge in that window, then tell the agent to continue. Do not close the window until done.`;
299
- }
300
- function pageUrlFromSnapshot(text) {
301
- return text.match(/\burl="([^"]+)"/)?.[1];
302
- }
303
- /** Best-effort MCP page list → entries (shared parser, never throws). */
304
- function mcpPageEntries(result) {
305
- return parseMcpPageList(result);
306
- }
307
- async function ensureConnected(signal) {
308
- if (!client)
309
- throw new Error('browser-use: session not started');
310
- await client.ensureReady(signal);
311
- }
312
- async function registerUpstreamTools() {
313
- await ensureConnected();
314
- const upstreamTools = await client.listAllTools();
315
- for (const tool of upstreamTools) {
316
- if (EXCLUDED_TOOLS.has(tool.name))
317
- continue;
318
- const prefixedName = `${TOOL_PREFIX}${tool.name}`;
319
- const originalName = tool.name;
320
- const description = augmentToolDescription(prefixedName, tool.description ?? '');
321
- // close_page carries an extra force gate so Existing mode can refuse
322
- // to close tabs Pi did not open (spec 19); stripped before upstream.
323
- const parameters = originalName === 'close_page'
324
- ? Type.Object({
325
- pageId: Type.Number({
326
- description: 'The ID of the page to close. Call browser_list_pages first; IDs shift when tabs close.',
327
- }),
328
- force: Type.Optional(Type.Boolean({
329
- description: 'Existing mode only: Pi refuses to close tabs it did not open unless force is true and the user explicitly asked for that exact tab.',
330
- })),
331
- })
332
- : Type.Unsafe(tool.inputSchema);
7
+ let runtime;
8
+ pi.on('session_start', async (_event, context) => {
9
+ await runtime?.stop();
10
+ const config = loadConfig({ cwd: context.cwd, projectTrusted: isProjectTrusted(context) });
11
+ runtime = createBrowserRuntime({ config, visionEnabled: !!config.visionModel });
12
+ for (const tool of await runtime.start()) {
333
13
  pi.registerTool({
334
- name: prefixedName,
335
- label: prefixedName,
336
- description,
337
- parameters,
338
- async execute(_toolCallId, params, signal) {
339
- await ensureConnected(signal);
340
- const browser = client;
341
- // Focus policy (headed-background / existing): Pi-created pages
342
- // open in the background and selections never take foreground
343
- // unless the caller explicitly asked. Explicit values always win.
344
- const effectiveParams = originalName === 'new_page'
345
- ? applyNewPageDefaults(params)
346
- : originalName === 'select_page'
347
- ? applySelectPageDefaults(params)
348
- : params;
349
- if ((originalName === 'navigate_page' || originalName === 'new_page') &&
350
- typeof effectiveParams.url === 'string') {
351
- // Remember the origin for the per-origin headed-background
352
- // fallback; normalizeOrigin never throws (falls back to raw).
353
- lastOrigin = normalizeOrigin(effectiveParams.url);
354
- // In Existing mode a Pi-driven navigation marks the destination
355
- // as Pi-touched for the close guard below.
356
- if (currentMode === 'existing')
357
- trackPiUrl(effectiveParams.url);
358
- // Claim navigated pages for this session so peer agents in a
359
- // shared browser can tell ours apart (best effort, never fatal).
360
- if (originalName === 'navigate_page' &&
361
- (currentMode === 'persistent' || currentMode === 'existing') &&
362
- typeof effectiveParams.pageId === 'number') {
363
- try {
364
- claimPage(registryDir(), { pageId: effectiveParams.pageId, url: effectiveParams.url }, myOwner);
365
- }
366
- catch {
367
- // Ownership is coordination metadata, not the task itself.
368
- }
369
- }
370
- }
371
- // Never close another session's tabs: Existing mode checks Pi URL
372
- // ownership (spec 19); a shared persistent backend checks the page
373
- // registry instead. Both yield to explicit force:true.
374
- if (originalName === 'close_page') {
375
- const { force: _force, ...closeArgs } = effectiveParams;
376
- void _force;
377
- const wantsForce = effectiveParams.force === true;
378
- const sharedPersistent = currentMode === 'persistent' && !!ownBackend && !ownBackend.owned;
379
- if ((currentMode === 'existing' || sharedPersistent) && !wantsForce) {
380
- if (typeof effectiveParams.pageId !== 'number') {
381
- return {
382
- content: [{ type: 'text', text: 'close_page needs a numeric pageId.' }],
383
- isError: true,
384
- details: undefined,
385
- };
386
- }
387
- const entries = parseMcpPageList(await callUpstream(browser, 'list_pages', {}, signal));
388
- const verdict = currentMode === 'existing'
389
- ? checkExistingCloseAllowed(entries, effectiveParams.pageId, piOwnedUrls)
390
- : checkSharedCloseAllowed(entries, effectiveParams.pageId, registryDir(), myOwner, piOwnedUrls);
391
- if (!verdict.ok) {
392
- return {
393
- content: [{ type: 'text', text: verdict.reason }],
394
- isError: true,
395
- details: undefined,
396
- };
397
- }
398
- }
399
- const result = await callUpstream(browser, originalName, closeArgs, signal);
400
- if (!result.isError && typeof effectiveParams.pageId === 'number') {
401
- try {
402
- releasePages(registryDir(), { pageId: effectiveParams.pageId });
403
- }
404
- catch {
405
- // Registry hygiene never fails the close itself.
406
- }
407
- }
408
- return { ...toToolContent(result, originalName), details: undefined };
409
- }
410
- let result = await callUpstream(browser, originalName, effectiveParams, signal);
411
- if (result.isError &&
412
- OVERLAY_RECOVERABLE.has(originalName) &&
413
- looksOverlayBlocked(extractTextContent(result.content))) {
414
- // One recovery attempt: dismiss the overlay, then retry the
415
- // original call. Any failure here falls through to the
416
- // original error, which already carries a hint.
417
- try {
418
- const escapeArgs = typeof effectiveParams.pageId === 'number'
419
- ? { pageId: effectiveParams.pageId, key: 'Escape' }
420
- : { key: 'Escape' };
421
- await callUpstream(browser, 'press_key', escapeArgs, signal);
422
- result = await callUpstream(browser, originalName, effectiveParams, signal);
423
- }
424
- catch {
425
- // Fall through to the original result below.
426
- }
427
- }
428
- const toolContent = toToolContent(result, originalName);
429
- if (!toolContent.isError &&
430
- (originalName === 'navigate_page' || originalName === 'take_snapshot')) {
431
- // Prefer the page's real URL from the snapshot; fall back to the
432
- // requested URL only when the snapshot carries none.
433
- const snapshotUrl = pageUrlFromSnapshot(extractTextContent(result.content));
434
- const requestedUrl = originalName === 'navigate_page' && typeof effectiveParams.url === 'string'
435
- ? effectiveParams.url
436
- : undefined;
437
- const url = snapshotUrl ?? requestedUrl;
438
- const escalation = await escalateBlockedPage(url, extractTextContent(result.content), signal, { tool: originalName, requestedUrl });
439
- const first = toolContent.content[0];
440
- if (escalation && first && first.text !== undefined) {
441
- first.text += escalation;
442
- }
443
- }
444
- return { ...toolContent, details: undefined };
14
+ ...tool,
15
+ execute: async (_id, params, signal, _onUpdate, ctx) => {
16
+ const callVision = config.visionModel && ctx?.modelRegistry
17
+ ? createRegistryVisionCaller(config.visionModel, ctx.modelRegistry)
18
+ : undefined;
19
+ return { ...(await tool.execute(params, signal, { callVision })), details: undefined };
445
20
  },
446
21
  });
447
22
  }
448
- }
449
- function registerSaveArtifactTool() {
450
- const properties = {
451
- kind: Type.Union([Type.Literal('screenshot'), Type.Literal('html')], {
452
- description: 'Capture a viewport screenshot (PNG) or the full rendered HTML.',
453
- }),
454
- path: Type.Optional(Type.String({
455
- description: 'Absolute destination path. Defaults to ~/.pi/browser-artifacts/<timestamp>.<png|html>.',
456
- })),
457
- annotate: Type.Optional(Type.Boolean({
458
- description: 'Screenshots only: overlay numbered badges on interactive elements and return their coordinate map for coordinate click tools. Badges are removed after capture.',
459
- })),
460
- };
461
- if (config?.experimentalPageIdRouting === true) {
462
- properties.pageId = Type.Number({
463
- description: 'Numeric page ID returned by browser_list_pages.',
464
- });
465
- }
466
- pi.registerTool({
467
- name: `${TOOL_PREFIX}save_artifact`,
468
- label: `${TOOL_PREFIX}save_artifact`,
469
- description: 'Save a screenshot or the rendered HTML of the current page to disk and return its path. Prefer this over pulling image bytes into context when the capture is evidence (bug reports, visual QA, artifact sharing) rather than something you need to look at right now.',
470
- parameters: Type.Object(properties),
471
- async execute(_toolCallId, params, signal) {
472
- await ensureConnected(signal);
473
- const browser = client;
474
- const kind = params.kind === 'html' ? 'html' : 'screenshot';
475
- const pageId = typeof params.pageId === 'number' ? params.pageId : undefined;
476
- const target = resolveArtifactTarget(kind, params.path);
477
- if (kind === 'html') {
478
- const pageArgs = pageId === undefined ? {} : { pageId };
479
- const evaluated = (await browser.callTool('evaluate_script', {
480
- ...pageArgs,
481
- function: '() => document.documentElement.outerHTML',
482
- }, signal));
483
- const html = extractTextContent(evaluated.content);
484
- if (!html)
485
- throw new Error('Page HTML came back empty.');
486
- mkdirSync(dirname(target), { recursive: true });
487
- writeFileSync(target, html, 'utf8');
488
- return {
489
- content: [
490
- { type: 'text', text: `Saved page HTML (${html.length} chars) to ${target}` },
491
- ],
492
- details: undefined,
493
- };
494
- }
495
- const shotArgs = pageId === undefined ? {} : { pageId };
496
- const evalArgs = pageId === undefined ? {} : { pageId };
497
- const wantAnnotations = params.annotate === true && kind === 'screenshot';
498
- let annotatedMap = '';
499
- try {
500
- if (wantAnnotations) {
501
- const injected = (await browser.callTool('evaluate_script', {
502
- ...evalArgs,
503
- function: INJECT_ANNOTATIONS,
504
- }, signal));
505
- annotatedMap = formatAnnotatedMap(parseAnnotatedElements(extractTextContent(injected.content)));
506
- }
507
- const shot = (await browser.callTool('take_screenshot', shotArgs, signal));
508
- const image = pickImageData(shot.content);
509
- if (!image)
510
- throw new Error('Screenshot came back without image data.');
511
- mkdirSync(dirname(target), { recursive: true });
512
- writeFileSync(target, Buffer.from(image.data, 'base64'));
513
- }
514
- finally {
515
- if (wantAnnotations) {
516
- try {
517
- await browser.callTool('evaluate_script', {
518
- ...evalArgs,
519
- function: CLEANUP_ANNOTATIONS,
520
- }, signal);
521
- }
522
- catch {
523
- // Badges are pointer-events:none and harmless if cleanup fails.
524
- }
525
- }
526
- }
527
- const suffix = annotatedMap ? `\nAnnotated elements:\n${annotatedMap}` : '';
528
- return {
529
- content: [{ type: 'text', text: `Saved screenshot to ${target}${suffix}` }],
530
- details: undefined,
531
- };
532
- },
533
- });
534
- }
535
- function registerSwitchModeTool() {
536
- pi.registerTool({
537
- name: `${TOOL_PREFIX}switch_mode`,
538
- label: `${TOOL_PREFIX}switch_mode`,
539
- description: 'Switch the browser backend without restarting: "persistent" is Pi\'s own browser (saved profile with your logins, default), "fresh" is an isolated clean room for anonymous checks, "existing" attaches to your running Chrome (tabs go to the collapsed pi-browser-use group via browser_open_background_tab, consent popup each session). Fresh and persistent default to headless; pass headed true to watch. Tabs do not transfer; call browser_list_pages after switching. Prefer persistent; drop to fresh for clean-room checks.',
540
- parameters: Type.Object({
541
- mode: Type.Union([
542
- Type.Literal('fresh'),
543
- Type.Literal('persistent'),
544
- Type.Literal('existing'),
545
- ]),
546
- headed: Type.Optional(Type.Boolean({
547
- description: 'Show the browser window. Default is headless — everything works with no popups.',
548
- })),
549
- rememberSite: Type.Optional(Type.Boolean({
550
- description: "Persistent only: remember the last-visited site's visibility (headless or headed-background) for next time.",
551
- })),
552
- }),
553
- async execute(_toolCallId, params, signal) {
554
- const mode = params.mode === 'persistent'
555
- ? 'persistent'
556
- : params.mode === 'existing'
557
- ? 'existing'
558
- : 'fresh';
559
- const { next, effectiveHeaded, backendNote } = await switchBackend(mode, params.headed === true, signal, { rememberSite: params.rememberSite === true });
560
- const visibility = mode === 'existing' ? 'headed (your Chrome)' : effectiveHeaded ? 'headed' : 'headless';
561
- const what = mode === 'fresh'
562
- ? 'a fresh isolated browser'
563
- : mode === 'persistent'
564
- ? 'the persistent Pi profile'
565
- : 'your running Chrome';
566
- const extra = mode === 'existing'
567
- ? ' Open Pi tabs with browser_open_background_tab so they land in the collapsed pi-browser-use group.'
568
- : '';
569
- void next;
570
- return {
571
- content: [
572
- {
573
- type: 'text',
574
- text: `Switched to ${what} (${visibility})${backendNote}. Previous tabs are gone; call browser_list_pages to start.${extra}`,
575
- },
576
- ],
577
- details: undefined,
578
- };
579
- },
580
- });
581
- }
582
- function registerSetupTool() {
583
- pi.registerTool({
584
- name: `${TOOL_PREFIX}setup`,
585
- label: `${TOOL_PREFIX}setup`,
586
- description: 'First-run setup for the persistent Pi browser profile: opens a plain headed Chrome window (no automation attached) for a human to sign into Google and any sites. Completes when the window is closed. Run once; afterwards Pi automates headless.',
587
- parameters: Type.Object({}),
588
- async execute() {
589
- const profileDir = persistentProfileDir(config ?? {});
590
- const meta = loadPersistentMetadata(profileDir);
591
- if (meta.initialized) {
592
- return {
593
- content: [
594
- {
595
- type: 'text',
596
- text: `Pi browser profile is already initialized (${profileDir}). If a login expired, use browser_reauth instead.`,
597
- },
598
- ],
599
- details: undefined,
600
- };
601
- }
602
- // No Chrome may hold the profile while the setup window runs.
603
- await teardownBackend();
604
- await runBootstrap({
605
- profileDir,
606
- executablePath: config?.executablePath,
607
- chromeArgs: config?.chromeArgs,
608
- });
609
- return {
610
- content: [
611
- {
612
- type: 'text',
613
- text: 'Pi browser profile initialized. Pi now works in the background — no Chrome window will appear during normal automation.',
614
- },
615
- ],
616
- details: undefined,
617
- };
618
- },
619
- });
620
- }
621
- function registerStatusTool() {
622
- pi.registerTool({
623
- name: `${TOOL_PREFIX}status`,
624
- label: `${TOOL_PREFIX}status`,
625
- description: 'Plain-language Pi browser status: profile readiness, execution mode, and what to do next. No page is touched.',
626
- parameters: Type.Object({}),
627
- async execute() {
628
- const mode = currentMode;
629
- const profileDir = persistentProfileDir(config ?? {});
630
- const meta = loadPersistentMetadata(profileDir);
631
- const sitePins = loadSitePreferences(profileDir).length;
632
- const lines = ['Pi Browser', '──────────', `Session: ${shortSession}`];
633
- if (mode === 'fresh') {
634
- lines.push('Profile: Ephemeral (nothing persists)');
635
- lines.push('Execution: Headless');
636
- }
637
- else if (mode === 'persistent') {
638
- lines.push(`Profile: ${meta.initialized ? 'Ready' : 'Setup required'}`);
639
- if (!meta.initialized) {
640
- lines.push('Next step: run browser_setup and sign in, then close the window.');
641
- }
642
- else {
643
- const headed = config?.headless === false;
644
- lines.push(`Execution: ${headed ? 'Visible fallback (background)' : 'Headless'}${ownBackend?.running() ? '' : ' (backend stopped)'}`);
645
- if (meta.lastSuccessfulMode)
646
- lines.push(`Last working mode: ${meta.lastSuccessfulMode}`);
647
- if (sitePins > 0)
648
- lines.push(`Sites pinned to visible fallback: ${sitePins}`);
649
- }
650
- }
651
- else if (mode === 'existing') {
652
- lines.push('Profile: Your browser');
653
- lines.push('Execution: Background tabs in the collapsed pi-browser-use group');
654
- lines.push(`Tab bridge: ${bridge ? bridge.baseUrl() : 'not running'}`);
655
- }
656
- else {
657
- lines.push('Profile: Externally attached browser');
658
- lines.push('Execution: Visible (owned by its launcher)');
659
- }
660
- return { content: [{ type: 'text', text: lines.join('\n') }], details: undefined };
661
- },
662
- });
663
- }
664
- function registerReauthTool() {
665
- pi.registerTool({
666
- name: `${TOOL_PREFIX}reauth`,
667
- label: `${TOOL_PREFIX}reauth`,
668
- description: 'Reauthenticate the persistent Pi profile after a login/challenge wall: shuts the headless browser down cleanly, opens a headed window for the human to verify, then resumes headless. The plain variant (no automation attached) is for providers that reject instrumented browsers.',
669
- parameters: Type.Object({
670
- url: Type.Optional(Type.String({ description: 'Page that needs authentication. Defaults to last origin.' })),
671
- variant: Type.Optional(Type.Union([Type.Literal('instrumented'), Type.Literal('plain')], {
672
- description: 'Headed variant: instrumented (Pi navigates first) or plain (maximum compatibility).',
673
- })),
674
- }),
675
- async execute(_toolCallId, params, signal) {
676
- if (currentMode !== 'persistent') {
677
- return {
678
- content: [
679
- {
680
- type: 'text',
681
- text: 'Reauth applies to the persistent Pi profile. Switch to it first with browser_switch_mode({"mode": "persistent"}).',
682
- },
683
- ],
684
- details: undefined,
685
- };
686
- }
687
- const url = typeof params.url === 'string' && params.url.length > 0
688
- ? params.url
689
- : (lastOrigin ?? 'this page');
690
- const variant = params.variant === 'plain' ? 'plain' : 'instrumented';
691
- if (ownBackend && !ownBackend.owned) {
692
- return {
693
- content: [
694
- {
695
- type: 'text',
696
- text: 'Another live agent session owns the persistent browser (shared mode). Reauth must happen there — ask that session to run browser_reauth, or wait for it to exit and retry.',
697
- },
698
- ],
699
- details: undefined,
700
- };
701
- }
702
- if (!ownBackend) {
703
- // Legacy MCP-launched persistent: headed switch is the reauth path.
704
- await switchBackend('persistent', true, signal);
705
- return {
706
- content: [
707
- {
708
- type: 'text',
709
- text: `A browser window just opened (legacy persistent backend). ${url}: please complete the login there, then tell the agent to continue.`,
710
- },
711
- ],
712
- details: undefined,
713
- };
714
- }
715
- // Spec §7: close headless Chrome cleanly before any headed reauth.
716
- await teardownBackend();
717
- const backend = new PersistentBackend({
718
- config: config ?? {},
719
- headed: variant === 'instrumented',
720
- sessionId,
721
- });
722
- ownBackend = backend;
723
- const message = await runReauth({
724
- backend,
725
- url,
726
- variant,
727
- restartBackend: (headed) => backend.restart(headed),
728
- });
729
- if (variant === 'plain') {
730
- // Plain window closed by the human: resume headless automation.
731
- const attach = await backend.restart(false);
732
- client = new DevToolsClient(attach);
733
- await client.ensureReady(signal);
734
- return {
735
- content: [
736
- { type: 'text', text: `${message}\n\nVerification recorded — Pi resumed headless.` },
737
- ],
738
- details: undefined,
739
- };
740
- }
741
- client = new DevToolsClient(backend.attachConfig());
742
- await client.ensureReady(signal);
743
- return {
744
- content: [
745
- {
746
- type: 'text',
747
- text: `${message}\n\nAfter verifying, tell the agent to continue; it resumes with browser_switch_mode({"mode": "persistent"}) back to headless.`,
748
- },
749
- ],
750
- details: undefined,
751
- };
752
- },
753
- });
754
- }
755
- function registerOpenBackgroundTabTool() {
756
- pi.registerTool({
757
- name: `${TOOL_PREFIX}open_background_tab`,
758
- label: `${TOOL_PREFIX}open_background_tab`,
759
- description: 'Existing mode only: open a URL as an inactive tab in the collapsed pi-browser-use group via the Pi extension — never a foreground tab. Fails clearly when the extension bridge is unavailable.',
760
- parameters: Type.Object({
761
- url: Type.String({ description: 'URL to open in a background Pi tab.' }),
762
- timeoutMs: Type.Optional(Type.Number({
763
- description: 'How long to wait for the extension (default 90000: a suspended worker wakes on the ~1min alarm cadence).',
764
- })),
765
- }),
766
- async execute(_toolCallId, params, signal) {
767
- if (currentMode !== 'existing') {
768
- return {
769
- content: [
770
- {
771
- type: 'text',
772
- text: 'Background Pi tabs need Existing mode (your Chrome). Switch first with browser_switch_mode({"mode": "existing"}).',
773
- isError: true,
774
- },
775
- ],
776
- details: undefined,
777
- isError: true,
778
- };
779
- }
780
- if (typeof params.url !== 'string' || params.url.length === 0) {
781
- throw new Error('A URL is required.');
782
- }
783
- const activeBridge = await ensureBridge();
784
- const timeoutMs = typeof params.timeoutMs === 'number' && params.timeoutMs > 0 ? params.timeoutMs : 90_000;
785
- const result = await openExistingPage(params.url, {
786
- bridge: activeBridge,
787
- listPages: async () => {
788
- await ensureConnected(signal);
789
- const pages = await client.callTool('list_pages', {}, signal);
790
- return mcpPageEntries(pages);
791
- },
792
- }, { timeoutMs, signal });
793
- trackPiUrl(params.url);
794
- if (result.pageId !== undefined) {
795
- try {
796
- claimPage(registryDir(), { pageId: result.pageId, url: params.url }, myOwner);
797
- }
798
- catch {
799
- // Ownership is coordination metadata, not the task itself.
800
- }
801
- }
802
- const selectHint = result.pageId !== undefined
803
- ? ` Select it with browser_select_page (it stays in the background).`
804
- : ' Call browser_list_pages to find it (it stays in the background).';
805
- return {
806
- content: [
807
- {
808
- type: 'text',
809
- text: `Opened ${params.url} as an inactive tab in the collapsed pi-browser-use group.${selectHint}`,
810
- },
811
- ],
812
- details: undefined,
813
- };
814
- },
815
- });
816
- }
817
- function registerDoctorTool() {
818
- pi.registerTool({
819
- name: `${TOOL_PREFIX}doctor`,
820
- label: `${TOOL_PREFIX}doctor`,
821
- description: 'Diagnose the browser setup: effective mode, whether this session launches its own Chrome, profile health, and upstream tool availability. Run this first when browser tools misbehave. Touches no pages.',
822
- parameters: Type.Object({}),
823
- async execute() {
824
- await ensureConnected();
825
- let peers = 0;
826
- try {
827
- peers = livePeerSessions(registryDir()).length;
828
- }
829
- catch {
830
- peers = 0;
831
- }
832
- const report = await diagnose(config ?? {}, async () => (await client.listAllTools()).map((tool) => tool.name), {
833
- backend: ownBackend ? (ownBackend.owned ? 'pi-owned' : 'shared') : undefined,
834
- bridgeUrl: bridge?.baseUrl() ?? null,
835
- peers,
836
- });
837
- return { content: [{ type: 'text', text: formatDoctorReport(report) }], details: undefined };
838
- },
839
- });
840
- }
841
- async function registerVisionTool(visionConfig) {
842
- const properties = {
843
- instruction: Type.Optional(Type.String({
844
- description: 'What to identify or analyze visually (e.g. "Find the coordinates of the blue submit button").',
845
- })),
846
- };
847
- if (config?.experimentalPageIdRouting === true) {
848
- properties.pageId = Type.Number({
849
- description: 'Numeric page ID returned by browser_list_pages.',
850
- });
851
- }
852
- pi.registerTool({
853
- name: `${TOOL_PREFIX}analyze_screenshot`,
854
- label: `${TOOL_PREFIX}analyze_screenshot`,
855
- description: 'Analyze the current page visually using a screenshot. Use when you need to identify elements by visual attributes (color, layout, position) not available in the accessibility tree, or when you need precise pixel coordinates for coordinate click tools.',
856
- parameters: Type.Object(properties),
857
- async execute(_toolCallId, params, signal, _onUpdate, ctx) {
858
- await ensureConnected(signal);
859
- if (!ctx?.modelRegistry)
860
- throw new Error('Vision model registry is unavailable in this session.');
861
- const callVision = createRegistryVisionCaller(visionConfig, ctx.modelRegistry);
862
- const pageId = typeof params.pageId === 'number' ? params.pageId : undefined;
863
- const result = await handleAnalyzeScreenshot({
864
- callTool: (name, args, sig) => client.callTool(name, args, sig),
865
- }, callVision, { instruction: typeof params.instruction === 'string' ? params.instruction : '', pageId }, signal);
866
- return { ...result, details: undefined };
867
- },
868
- });
869
- }
870
- pi.on('session_start', async (_event, ctx) => {
871
- config = resolveConfig(loadConfig({ cwd: ctx.cwd, projectTrusted: isProjectTrusted(ctx) }));
872
- currentMode = describeMode();
873
- if (currentMode === 'persistent' && shouldSelfLaunch(config)) {
874
- // Phase 2: Pi owns the persistent Chrome process; MCP attaches.
875
- ownBackend = new PersistentBackend({ config, headed: config.headless === false, sessionId });
876
- client = new DevToolsClient(await ownBackend.start());
877
- }
878
- else {
879
- prepareBrowserProfile(config);
880
- client = new DevToolsClient(config);
881
- }
882
- await registerUpstreamTools();
883
- registerSaveArtifactTool();
884
- registerDoctorTool();
885
- registerSwitchModeTool();
886
- registerSetupTool();
887
- registerStatusTool();
888
- registerReauthTool();
889
- registerOpenBackgroundTabTool();
890
- if (config.visionModel) {
891
- await registerVisionTool(config.visionModel);
892
- }
893
23
  });
894
24
  pi.on('session_shutdown', async () => {
895
- await teardownBackend();
896
- // Release this session's page claims in every scope it may have used.
897
- for (const scope of new Set([persistentProfileDir(config ?? {}), DEFAULT_PROFILE_DIR])) {
898
- try {
899
- releasePages(scope, { sessionId });
900
- }
901
- catch {
902
- // Best effort.
903
- }
904
- }
905
- if (bridge) {
906
- try {
907
- await bridge.stop();
908
- }
909
- catch {
910
- // Session teardown is best-effort.
911
- }
912
- bridge = undefined;
913
- }
25
+ await runtime?.stop();
26
+ runtime = undefined;
914
27
  });
915
28
  }
916
29
  //# sourceMappingURL=index.js.map