@parcha/pi-browser 0.0.0-bootstrap.0 → 0.1.0-beta.13
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 +16 -0
- package/LICENSE +202 -0
- package/NOTICE +33 -0
- package/README.md +328 -1
- package/dist/coding-agent-local.d.ts +16 -0
- package/dist/coding-agent-local.js +138 -0
- package/dist/coding-agent.d.ts +78 -0
- package/dist/coding-agent.js +446 -0
- package/dist/core/contract.d.ts +26 -0
- package/dist/core/contract.js +154 -0
- package/dist/core/custody.d.ts +111 -0
- package/dist/core/custody.js +122 -0
- package/dist/core/decisions.d.ts +43 -0
- package/dist/core/decisions.js +4 -0
- package/dist/core/downloads.d.ts +35 -0
- package/dist/core/downloads.js +131 -0
- package/dist/core/effects.d.ts +63 -0
- package/dist/core/effects.js +256 -0
- package/dist/core/evidence.d.ts +43 -0
- package/dist/core/evidence.js +6 -0
- package/dist/core/failures.d.ts +28 -0
- package/dist/core/failures.js +59 -0
- package/dist/core/find.d.ts +32 -0
- package/dist/core/find.js +179 -0
- package/dist/core/guard.d.ts +6 -0
- package/dist/core/guard.js +24 -0
- package/dist/core/host.d.ts +279 -0
- package/dist/core/host.js +2 -0
- package/dist/core/images.d.ts +37 -0
- package/dist/core/images.js +60 -0
- package/dist/core/lease.d.ts +16 -0
- package/dist/core/lease.js +30 -0
- package/dist/core/receipts.d.ts +19 -0
- package/dist/core/receipts.js +22 -0
- package/dist/core/redact.d.ts +13 -0
- package/dist/core/redact.js +83 -0
- package/dist/core/session-control.d.ts +25 -0
- package/dist/core/session-control.js +75 -0
- package/dist/core/sites.d.ts +33 -0
- package/dist/core/sites.js +102 -0
- package/dist/core/tools.d.ts +37 -0
- package/dist/core/tools.js +170 -0
- package/dist/core/uri.d.ts +11 -0
- package/dist/core/uri.js +37 -0
- package/dist/core/usage.d.ts +38 -0
- package/dist/core/usage.js +44 -0
- package/dist/core/web.d.ts +98 -0
- package/dist/core/web.js +327 -0
- package/dist/driver/stagehand.d.ts +25 -0
- package/dist/driver/stagehand.js +141 -0
- package/dist/durable-result.d.ts +6 -0
- package/dist/durable-result.js +2 -0
- package/dist/durable.d.ts +75 -0
- package/dist/durable.js +484 -0
- package/dist/index.d.ts +18 -0
- package/dist/index.js +19 -0
- package/dist/providers/browserbase-net.d.ts +13 -0
- package/dist/providers/browserbase-net.js +96 -0
- package/dist/providers/browserbase.d.ts +152 -0
- package/dist/providers/browserbase.js +262 -0
- package/dist/providers/cdp-call.d.ts +6 -0
- package/dist/providers/cdp-call.js +25 -0
- package/dist/providers/cdp.d.ts +48 -0
- package/dist/providers/cdp.js +353 -0
- package/dist/providers/http.d.ts +2 -0
- package/dist/providers/http.js +21 -0
- package/dist/providers/kernel.d.ts +49 -0
- package/dist/providers/kernel.js +246 -0
- package/dist/providers/shared.d.ts +47 -0
- package/dist/providers/shared.js +82 -0
- package/dist/recorder/credential.d.ts +9 -0
- package/dist/recorder/credential.js +49 -0
- package/dist/recorder/follow.d.ts +26 -0
- package/dist/recorder/follow.js +138 -0
- package/dist/recorder/frames.d.ts +80 -0
- package/dist/recorder/frames.js +309 -0
- package/dist/recorder/index.d.ts +3 -0
- package/dist/recorder/index.js +6 -0
- package/dist/recorder/jpeg.d.ts +5 -0
- package/dist/recorder/jpeg.js +34 -0
- package/dist/store.d.ts +56 -0
- package/dist/store.js +196 -0
- package/dist/testing/backend.d.ts +231 -0
- package/dist/testing/backend.js +414 -0
- package/dist/testing/driver.d.ts +28 -0
- package/dist/testing/driver.js +32 -0
- package/dist/testing/index.d.ts +4 -0
- package/dist/testing/index.js +4 -0
- package/dist/testing/pages.d.ts +3 -0
- package/dist/testing/pages.js +10 -0
- package/dist/testing/sentinels.d.ts +29 -0
- package/dist/testing/sentinels.js +38 -0
- package/dist/vendor/stagehand-facade/contract.d.ts +348 -0
- package/dist/vendor/stagehand-facade/contract.js +155 -0
- package/dist/vendor/stagehand-facade/runtime.d.ts +90 -0
- package/dist/vendor/stagehand-facade/runtime.js +1640 -0
- package/dist/vendor/stagehand-facade/screenshot-transport.d.ts +15 -0
- package/dist/vendor/stagehand-facade/screenshot-transport.js +51 -0
- package/dist/vendor/stagehand-facade/tools.d.ts +31 -0
- package/dist/vendor/stagehand-facade/tools.js +139 -0
- package/dist/web.d.ts +41 -0
- package/dist/web.js +38 -0
- package/package.json +125 -1
- package/src/vendor/stagehand-facade/UPSTREAM.json +24 -0
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { mkdir, writeFile } from "node:fs/promises";
|
|
3
|
+
import { Agent, fetch as undiciFetch } from "undici";
|
|
4
|
+
import dns from "node:dns/promises";
|
|
5
|
+
import net from "node:net";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
const LINUX_NAMES = ["google-chrome", "google-chrome-stable", "chromium", "chromium-browser"];
|
|
8
|
+
export function findChrome(env = process.env, exists = existsSync) {
|
|
9
|
+
for (const named of [env.PI_BROWSER_CHROME, env.CHROME_PATH])
|
|
10
|
+
if (named && exists(named))
|
|
11
|
+
return named;
|
|
12
|
+
const onPath = (env.PATH ?? "").split(path.delimiter).filter(Boolean).flatMap((dir) => LINUX_NAMES.map((name) => path.join(dir, name)));
|
|
13
|
+
const fixed = ["/opt/google/chrome/chrome", "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe"];
|
|
14
|
+
return [...onPath, ...fixed].find((file) => exists(file)) ?? null;
|
|
15
|
+
}
|
|
16
|
+
/** One path segment of `[A-Za-z0-9._-]`; a label of only dots (`.`, `..`) is never a directory name. */
|
|
17
|
+
const safe = (part) => {
|
|
18
|
+
const cleaned = part.replace(/[^A-Za-z0-9._-]+/g, "_").slice(0, 60);
|
|
19
|
+
return !cleaned ? "browser" : /^\.+$/.test(cleaned) ? `_${cleaned}` : cleaned;
|
|
20
|
+
};
|
|
21
|
+
export function fileEvidenceSink(root, relativeTo) {
|
|
22
|
+
let seq = 0;
|
|
23
|
+
return {
|
|
24
|
+
async file(label, record) {
|
|
25
|
+
try {
|
|
26
|
+
const dir = path.join(root, safe(label));
|
|
27
|
+
await mkdir(dir, { recursive: true });
|
|
28
|
+
const text = typeof record.body === "string";
|
|
29
|
+
const header = ["tool: " + record.tool, "args: " + JSON.stringify(record.args), "status: " + record.status,
|
|
30
|
+
...Object.entries(record.facts).filter(([, value]) => value !== undefined).map(([key, value]) => `${key}: ${value}`), "---"];
|
|
31
|
+
// A name is reserved with an exclusive create, so a later session (or a fork) never overwrites an earlier
|
|
32
|
+
// receipt.
|
|
33
|
+
for (;;) {
|
|
34
|
+
const stem = `${String(++seq).padStart(4, "0")}-${record.tool}`;
|
|
35
|
+
const [receipt, capture] = [path.join(dir, `${stem}.md`), path.join(dir, `${stem}.${record.ext ?? "bin"}`)];
|
|
36
|
+
try {
|
|
37
|
+
await writeFile(text ? receipt : capture, text ? `${header.join("\n")}\n${record.body}` : record.body, { flag: "wx" });
|
|
38
|
+
}
|
|
39
|
+
catch (error) {
|
|
40
|
+
if (error.code === "EEXIST")
|
|
41
|
+
continue;
|
|
42
|
+
throw error;
|
|
43
|
+
}
|
|
44
|
+
if (!text)
|
|
45
|
+
await writeFile(receipt, `${header.join("\n")}\n(the capture is ${path.basename(capture)})\n`);
|
|
46
|
+
return { path: path.relative(relativeTo, receipt).split(path.sep).join("/"), bodyLine: text ? header.length + 1 : undefined };
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
52
|
+
},
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
const V4_PRIVATE = [[0x0a000000, 8], [0x64400000, 10], [0x7f000000, 8], [0xa9fe0000, 16], [0xac100000, 12], [0xc0a80000, 16], [0x00000000, 8], [0xe0000000, 4]];
|
|
56
|
+
const v4 = (ip) => ip.split(".").reduce((n, octet) => n * 256 + Number(octet), 0);
|
|
57
|
+
/** Loopback, private, link-local, carrier-grade and multicast addresses, v4 and v6, v4-mapped included. */
|
|
58
|
+
export function isPrivateAddress(ip) {
|
|
59
|
+
const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/i.exec(ip)?.[1];
|
|
60
|
+
if (mapped)
|
|
61
|
+
return isPrivateAddress(mapped);
|
|
62
|
+
if (net.isIPv4(ip))
|
|
63
|
+
return V4_PRIVATE.some(([base, bits]) => Math.floor(v4(ip) / 2 ** (32 - bits)) === Math.floor(base / 2 ** (32 - bits)));
|
|
64
|
+
if (net.isIPv6(ip))
|
|
65
|
+
return /^(::1?|f[cd][0-9a-f]{2}:|fe[89ab][0-9a-f]:|ff[0-9a-f]{2}:)/i.test(ip) || ip === "::";
|
|
66
|
+
return true;
|
|
67
|
+
}
|
|
68
|
+
const MAX_BYTES = 5 * 1024 * 1024;
|
|
69
|
+
const MAX_REDIRECTS = 5;
|
|
70
|
+
/** Answers `address` for any name: the address a request was checked against is the one it connects to. */
|
|
71
|
+
export const pinnedLookup = (address) => (_host, options, callback) => {
|
|
72
|
+
const family = net.isIPv6(address) ? 6 : 4;
|
|
73
|
+
if (options?.all)
|
|
74
|
+
callback(null, [{ address, family }]);
|
|
75
|
+
else
|
|
76
|
+
callback(null, address, family);
|
|
77
|
+
};
|
|
78
|
+
/** Public hosts only, so a page-steered agent never reaches the owner's private network: each redirect hop is resolved
|
|
79
|
+
* once, checked and dialled at that address. No cookies or credentials; at most 5 MiB. */
|
|
80
|
+
export function httpBackup(options = {}) {
|
|
81
|
+
const lookup = options.lookup ?? (async (host) => (await dns.lookup(host, { all: true })).map((a) => a.address));
|
|
82
|
+
const request = options.fetchImpl ?? ((url, init) => undiciFetch(url, init));
|
|
83
|
+
return {
|
|
84
|
+
name: "http",
|
|
85
|
+
async fetch(url, signal) {
|
|
86
|
+
let target = new URL(url);
|
|
87
|
+
for (let hop = 0;; hop += 1) {
|
|
88
|
+
const host = target.hostname.replace(/^\[|\]$/g, "");
|
|
89
|
+
if (host === "localhost" || host.endsWith(".localhost") || host.endsWith(".local") || host.endsWith(".internal"))
|
|
90
|
+
throw new Error(`refused: ${host} is not a public host`);
|
|
91
|
+
const addresses = net.isIP(host) ? [host] : await lookup(host);
|
|
92
|
+
if (!addresses.length || addresses.some(isPrivateAddress))
|
|
93
|
+
throw new Error(`refused: ${host} is not a public host`);
|
|
94
|
+
const dispatcher = new Agent({ connect: { lookup: pinnedLookup(addresses[0]) } });
|
|
95
|
+
let res;
|
|
96
|
+
try {
|
|
97
|
+
res = await request(target, { redirect: "manual", signal, dispatcher, headers: { accept: "text/html,text/plain;q=0.9,*/*;q=0.1", "user-agent": "pi-browser" } });
|
|
98
|
+
if (res.status >= 300 && res.status < 400 && res.headers.get("location")) {
|
|
99
|
+
if (hop >= MAX_REDIRECTS)
|
|
100
|
+
throw new Error("refused: too many redirects");
|
|
101
|
+
target = new URL(res.headers.get("location"), target);
|
|
102
|
+
if (!/^https?:$/.test(target.protocol))
|
|
103
|
+
throw new Error("refused: a redirect left http(s)");
|
|
104
|
+
continue;
|
|
105
|
+
}
|
|
106
|
+
if (!res.ok)
|
|
107
|
+
throw Object.assign(new Error(`the page answered ${res.status}`), { status: res.status });
|
|
108
|
+
const type = res.headers.get("content-type") ?? "";
|
|
109
|
+
if (!/^(text\/|application\/(xhtml\+xml|json|xml))/i.test(type))
|
|
110
|
+
throw new Error(`refused: ${type || "an unknown content type"} is not text`);
|
|
111
|
+
const chunks = [];
|
|
112
|
+
let size = 0;
|
|
113
|
+
for (const reader = res.body.getReader();;) {
|
|
114
|
+
const { done, value } = await reader.read();
|
|
115
|
+
if (done)
|
|
116
|
+
break;
|
|
117
|
+
if ((size += value.length) > MAX_BYTES) {
|
|
118
|
+
await reader.cancel();
|
|
119
|
+
throw new Error("refused: the page is over 5 MiB");
|
|
120
|
+
}
|
|
121
|
+
chunks.push(value);
|
|
122
|
+
}
|
|
123
|
+
const text = Buffer.concat(chunks).toString("utf8");
|
|
124
|
+
if (!/html/i.test(type))
|
|
125
|
+
return text;
|
|
126
|
+
const { NodeHtmlMarkdown } = await import("node-html-markdown");
|
|
127
|
+
return NodeHtmlMarkdown.translate(text, { keepDataImages: false });
|
|
128
|
+
}
|
|
129
|
+
finally {
|
|
130
|
+
// A reply refused unread (not text, an error status, a redirect) still holds its connection: close() waits
|
|
131
|
+
// for it.
|
|
132
|
+
await res?.body?.cancel().catch(() => undefined);
|
|
133
|
+
await dispatcher.close().catch(() => undefined);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
},
|
|
137
|
+
};
|
|
138
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { type AttachedSession, type CustodyPort, type DriverFactory, type Overrides } from "./core/custody.js";
|
|
3
|
+
import type { BrowserConfig, BrowserPolicy, BrowserProvider, ReleaseReason, SiteRunPort } from "./core/host.js";
|
|
4
|
+
import { type Redact } from "./core/redact.js";
|
|
5
|
+
import { type PageDriver } from "./core/tools.js";
|
|
6
|
+
import { type WebBackup } from "./core/web.js";
|
|
7
|
+
export { findChrome } from "./coding-agent-local.js";
|
|
8
|
+
export declare const SESSION_ENTRY = "browser.session";
|
|
9
|
+
export type CodingAgentOptions = {
|
|
10
|
+
/** Default: chosen by the `--browser-*` flags and `PI_BROWSER_*` when the session starts. */
|
|
11
|
+
provider?: BrowserProvider | (() => BrowserProvider | Promise<BrowserProvider>);
|
|
12
|
+
/** Default: the Stagehand driver. */
|
|
13
|
+
driver?: DriverFactory<PageDriver>;
|
|
14
|
+
policy?: Partial<BrowserPolicy>;
|
|
15
|
+
/** Fetchers tried when the provider cannot fetch a page. Default: a plain HTTP read of public hosts. */
|
|
16
|
+
backups?: ReadonlyArray<WebBackup>;
|
|
17
|
+
env?: NodeJS.ProcessEnv;
|
|
18
|
+
/** `use_website`'s sites; absent, the tool is not listed. Each child is a pi session with this extension and no
|
|
19
|
+
* use_website, started through pi's SDK and disposed, so its browser released, when it reports. */
|
|
20
|
+
sites?: SiteRunPort;
|
|
21
|
+
};
|
|
22
|
+
type Deps = {
|
|
23
|
+
config: BrowserConfig;
|
|
24
|
+
provider: () => Promise<BrowserProvider>;
|
|
25
|
+
driver: DriverFactory<PageDriver>;
|
|
26
|
+
keep: (customType: string, data: unknown) => void;
|
|
27
|
+
redact: Redact;
|
|
28
|
+
signal: AbortSignal;
|
|
29
|
+
};
|
|
30
|
+
export declare class LocalCustody implements CustodyPort<PageDriver> {
|
|
31
|
+
private readonly d;
|
|
32
|
+
private live;
|
|
33
|
+
/** Browsers that are gone whose directories are not: each is released again as cleanup, never kept as the live session. */
|
|
34
|
+
private leftovers;
|
|
35
|
+
private seq;
|
|
36
|
+
private notice;
|
|
37
|
+
private readonly queue;
|
|
38
|
+
private readonly idle;
|
|
39
|
+
constructor(d: Deps);
|
|
40
|
+
private serial;
|
|
41
|
+
private save;
|
|
42
|
+
private failure;
|
|
43
|
+
/** Release every session the branch's entries leave open (a browser a crashed process left running); never adopted. */
|
|
44
|
+
releaseOrphans(entries: ReadonlyArray<{
|
|
45
|
+
type: string;
|
|
46
|
+
customType?: string;
|
|
47
|
+
data?: any;
|
|
48
|
+
}>): Promise<void>;
|
|
49
|
+
private attached;
|
|
50
|
+
private launch;
|
|
51
|
+
/** A release the provider fails leaves the session held, so a later release, the shutdown or the next start can retry it. The exception is a
|
|
52
|
+
* release that says the browser is gone and only a directory is left (`profile_not_removed`): that session is over (it is never the live
|
|
53
|
+
* one again), its record stays open for the directory, which is released again by the next release, the shutdown or the next start; the
|
|
54
|
+
* caller is still told what is left. */
|
|
55
|
+
private finish;
|
|
56
|
+
/** Releases again each browser that is gone and whose directory was left; one that still cannot be removed stays for the next time, and the
|
|
57
|
+
* last such failure is returned for a caller that was asked to release. */
|
|
58
|
+
private sweepLeftovers;
|
|
59
|
+
private retireEnded;
|
|
60
|
+
session(): Promise<AttachedSession<PageDriver>>;
|
|
61
|
+
relaunch(overrides: Overrides): Promise<AttachedSession<PageDriver>>;
|
|
62
|
+
release(): Promise<{
|
|
63
|
+
released: boolean;
|
|
64
|
+
sessionId: string | null;
|
|
65
|
+
}>;
|
|
66
|
+
/** Releases without failing the caller; idempotent. */
|
|
67
|
+
close(reason: ReleaseReason): Promise<void>;
|
|
68
|
+
dispatching(): Promise<void>;
|
|
69
|
+
journal(): Promise<void>;
|
|
70
|
+
settle(): Promise<void>;
|
|
71
|
+
navigated(url: string): Promise<void>;
|
|
72
|
+
ended(): Promise<boolean>;
|
|
73
|
+
dropped(): Promise<void>;
|
|
74
|
+
/** A session left idle is released after the policy's idle spell. */
|
|
75
|
+
activity(delta: 1 | -1): void;
|
|
76
|
+
}
|
|
77
|
+
export declare function createBrowserExtension(options?: CodingAgentOptions): (pi: ExtensionAPI) => void;
|
|
78
|
+
export default function piBrowser(pi: ExtensionAPI): void;
|
|
@@ -0,0 +1,446 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { existsSync } from "node:fs";
|
|
3
|
+
import { mkdtemp, rm } from "node:fs/promises";
|
|
4
|
+
import os from "node:os";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { BROWSER_TOOLS, WEB_TOOLS, browserSection } from "./core/contract.js";
|
|
7
|
+
import { BrowserFailureError, closeDriver, custodyTools, newSessionRecord, notices, sessionSpec, } from "./core/custody.js";
|
|
8
|
+
import { classifyBrowserError } from "./core/failures.js";
|
|
9
|
+
import { leaseTag } from "./core/lease.js";
|
|
10
|
+
import { createRedactor, redactDeep, scrubPageUrl } from "./core/redact.js";
|
|
11
|
+
import { useWebsite, useWebsiteContract } from "./core/sites.js";
|
|
12
|
+
import { pageTools } from "./core/tools.js";
|
|
13
|
+
import { CREATE_DEADLINE_MS, DEFAULT_BROWSER_POLICY, idleTracker, keyedSerializer, providerKeyValues } from "./core/session-control.js";
|
|
14
|
+
import { createWebTools } from "./core/web.js";
|
|
15
|
+
import { fileEvidenceSink, findChrome, httpBackup } from "./coding-agent-local.js";
|
|
16
|
+
export { findChrome } from "./coding-agent-local.js";
|
|
17
|
+
export const SESSION_ENTRY = "browser.session";
|
|
18
|
+
const CONVERSATION = 1;
|
|
19
|
+
const BROWSER_FLAGS = ["browser-provider", "browser-endpoint", "browser-chrome", "browser-headed", "browser-no-sandbox"];
|
|
20
|
+
const refused = (message, code = "browser_unavailable") => new BrowserFailureError({ ok: false, code, retryable: false, effect: "none", message });
|
|
21
|
+
const now = () => new Date().toISOString();
|
|
22
|
+
/** The provider released the browser and could not remove a directory it left (`ProfileNotRemovedError`'s code, read without importing the provider). */
|
|
23
|
+
const directoryLeft = (error) => error?.code === "profile_not_removed";
|
|
24
|
+
export class LocalCustody {
|
|
25
|
+
d;
|
|
26
|
+
live = null;
|
|
27
|
+
/** Browsers that are gone whose directories are not: each is released again as cleanup, never kept as the live session. */
|
|
28
|
+
leftovers = [];
|
|
29
|
+
seq = 0;
|
|
30
|
+
notice = null;
|
|
31
|
+
queue = keyedSerializer();
|
|
32
|
+
idle;
|
|
33
|
+
constructor(d) {
|
|
34
|
+
this.d = d;
|
|
35
|
+
this.idle = idleTracker({ idleMs: d.config.policy.idleReleaseS * 1000, onIdle: (key, fired) => void this.serial(async () => {
|
|
36
|
+
if (this.idle.isCurrent(key, fired) && this.live)
|
|
37
|
+
await this.finish(this.live, "idle").catch(() => undefined);
|
|
38
|
+
}) });
|
|
39
|
+
}
|
|
40
|
+
serial(run) {
|
|
41
|
+
return this.queue.run(this.d.config.label, run);
|
|
42
|
+
}
|
|
43
|
+
save(record) {
|
|
44
|
+
this.d.keep(SESSION_ENTRY, { tag: record.tag, resourceId: record.resourceId, state: record.state, reason: record.releaseReason });
|
|
45
|
+
}
|
|
46
|
+
failure(error, signal) {
|
|
47
|
+
return error instanceof BrowserFailureError ? error : new BrowserFailureError(classifyBrowserError(error, false, { aborted: signal?.aborted === true }));
|
|
48
|
+
}
|
|
49
|
+
/** Release every session the branch's entries leave open (a browser a crashed process left running); never adopted. */
|
|
50
|
+
async releaseOrphans(entries) {
|
|
51
|
+
const last = new Map();
|
|
52
|
+
for (const e of entries)
|
|
53
|
+
if (e.type === "custom" && e.customType === SESSION_ENTRY && e.data?.tag)
|
|
54
|
+
last.set(e.data.tag, e.data);
|
|
55
|
+
const open = [...last.values()].filter((entry) => entry.state !== "released");
|
|
56
|
+
if (!open.length)
|
|
57
|
+
return;
|
|
58
|
+
const provider = await this.d.provider();
|
|
59
|
+
for (const { tag, resourceId } of open) {
|
|
60
|
+
const refs = resourceId ? [{ id: resourceId, tag }] : await provider.findByTag(tag).catch(() => null);
|
|
61
|
+
if (!refs)
|
|
62
|
+
continue;
|
|
63
|
+
let released = true;
|
|
64
|
+
for (const ref of refs)
|
|
65
|
+
await provider.release(ref).catch(() => { released = false; });
|
|
66
|
+
if (released)
|
|
67
|
+
this.d.keep(SESSION_ENTRY, { tag, resourceId, state: "released", reason: "lost" });
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
async attached(live) {
|
|
71
|
+
const provider = await this.d.provider();
|
|
72
|
+
const signal = AbortSignal.any([this.d.signal, AbortSignal.timeout(CREATE_DEADLINE_MS)]);
|
|
73
|
+
try {
|
|
74
|
+
live.driver ??= await this.d.driver(await provider.attach(live.ref, signal), signal, { batchTimeoutMs: this.d.config.policy.batchTimeoutMs });
|
|
75
|
+
}
|
|
76
|
+
catch (error) {
|
|
77
|
+
throw this.failure(error, signal);
|
|
78
|
+
}
|
|
79
|
+
const notice = this.notice;
|
|
80
|
+
this.notice = null;
|
|
81
|
+
return { driver: live.driver, tag: live.record.tag, sessionId: live.ref.id, record: live.record, notice, interrupted: null, recorded: !!provider.recordings, effects: null };
|
|
82
|
+
}
|
|
83
|
+
async launch(overrides) {
|
|
84
|
+
const provider = await this.d.provider();
|
|
85
|
+
const tag = leaseTag("pib", this.d.config.run, randomUUID().slice(0, 8), ++this.seq);
|
|
86
|
+
const spec = sessionSpec(this.d.config, tag, overrides);
|
|
87
|
+
const record = newSessionRecord({ plane: "browser", tag, provider: provider.name, spec, at: now() });
|
|
88
|
+
this.save(record);
|
|
89
|
+
const signal = AbortSignal.any([this.d.signal, AbortSignal.timeout(CREATE_DEADLINE_MS)]);
|
|
90
|
+
let live = null;
|
|
91
|
+
try {
|
|
92
|
+
const ref = await provider.create(spec, signal);
|
|
93
|
+
Object.assign(record, { state: "live", resourceId: ref.id });
|
|
94
|
+
this.save(record);
|
|
95
|
+
live = { record, ref, driver: null };
|
|
96
|
+
const attached = await this.attached(live);
|
|
97
|
+
this.live = live;
|
|
98
|
+
return attached;
|
|
99
|
+
}
|
|
100
|
+
catch (error) {
|
|
101
|
+
// A create that threw may still have made a browser: with no ref, look it up by its tag. The record ends released
|
|
102
|
+
// only when every release is confirmed; otherwise it stays open for the next start to retry.
|
|
103
|
+
const refs = live ? [live.ref] : await provider.findByTag(tag).catch(() => null);
|
|
104
|
+
let released = refs !== null;
|
|
105
|
+
for (const ref of refs ?? [])
|
|
106
|
+
if (!(await provider.release(ref).then(() => true, () => false)))
|
|
107
|
+
released = false;
|
|
108
|
+
if (released) {
|
|
109
|
+
Object.assign(record, { state: "released", releaseReason: "create_failed" });
|
|
110
|
+
this.save(record);
|
|
111
|
+
}
|
|
112
|
+
throw this.failure(error, signal);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
/** A release the provider fails leaves the session held, so a later release, the shutdown or the next start can retry it. The exception is a
|
|
116
|
+
* release that says the browser is gone and only a directory is left (`profile_not_removed`): that session is over (it is never the live
|
|
117
|
+
* one again), its record stays open for the directory, which is released again by the next release, the shutdown or the next start; the
|
|
118
|
+
* caller is still told what is left. */
|
|
119
|
+
async finish(live, reason) {
|
|
120
|
+
await this.sweepLeftovers();
|
|
121
|
+
// A close that never comes back (Stagehand after a reconnect) never holds up the provider's release.
|
|
122
|
+
if (live.driver)
|
|
123
|
+
await closeDriver(live.driver);
|
|
124
|
+
try {
|
|
125
|
+
await (await this.d.provider()).release(live.ref);
|
|
126
|
+
}
|
|
127
|
+
catch (error) {
|
|
128
|
+
if (!directoryLeft(error))
|
|
129
|
+
throw this.failure(error);
|
|
130
|
+
if (this.live === live)
|
|
131
|
+
this.live = null;
|
|
132
|
+
live.driver = null;
|
|
133
|
+
Object.assign(live.record, { state: "releasing", releaseReason: reason });
|
|
134
|
+
this.save(live.record);
|
|
135
|
+
this.leftovers.push(live);
|
|
136
|
+
throw this.failure(error);
|
|
137
|
+
}
|
|
138
|
+
if (this.live === live)
|
|
139
|
+
this.live = null;
|
|
140
|
+
Object.assign(live.record, { state: "released", releaseReason: reason });
|
|
141
|
+
this.save(live.record);
|
|
142
|
+
}
|
|
143
|
+
/** Releases again each browser that is gone and whose directory was left; one that still cannot be removed stays for the next time, and the
|
|
144
|
+
* last such failure is returned for a caller that was asked to release. */
|
|
145
|
+
async sweepLeftovers() {
|
|
146
|
+
let stillLeft = null;
|
|
147
|
+
const pending = this.leftovers.splice(0);
|
|
148
|
+
for (const live of pending) {
|
|
149
|
+
try {
|
|
150
|
+
await (await this.d.provider()).release(live.ref);
|
|
151
|
+
}
|
|
152
|
+
catch (error) {
|
|
153
|
+
this.leftovers.push(live);
|
|
154
|
+
stillLeft = error;
|
|
155
|
+
continue;
|
|
156
|
+
}
|
|
157
|
+
Object.assign(live.record, { state: "released" });
|
|
158
|
+
this.save(live.record);
|
|
159
|
+
}
|
|
160
|
+
return stillLeft;
|
|
161
|
+
}
|
|
162
|
+
async retireEnded() {
|
|
163
|
+
const live = this.live;
|
|
164
|
+
if (!live || !["gone", "stopped"].includes(await (await this.d.provider()).status(live.ref).catch(() => "running")))
|
|
165
|
+
return false;
|
|
166
|
+
this.notice = notices.ended(live.record.lastUrl);
|
|
167
|
+
await this.finish(live, "ended").catch(() => undefined);
|
|
168
|
+
return true;
|
|
169
|
+
}
|
|
170
|
+
session() {
|
|
171
|
+
return this.serial(async () => {
|
|
172
|
+
await this.retireEnded();
|
|
173
|
+
return this.live ? this.attached(this.live) : this.launch({});
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
relaunch(overrides) {
|
|
177
|
+
return this.serial(async () => {
|
|
178
|
+
// A browser that is gone with only its directory left is over: the new one opens, and the directory is retried later.
|
|
179
|
+
if (this.live)
|
|
180
|
+
await this.finish(this.live, "relaunch").catch((error) => { if (this.live)
|
|
181
|
+
throw error; });
|
|
182
|
+
return this.launch(overrides);
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
release() {
|
|
186
|
+
return this.serial(async () => {
|
|
187
|
+
const live = this.live;
|
|
188
|
+
if (live)
|
|
189
|
+
await this.finish(live, "tool");
|
|
190
|
+
else {
|
|
191
|
+
const stillLeft = await this.sweepLeftovers();
|
|
192
|
+
if (stillLeft)
|
|
193
|
+
throw this.failure(stillLeft);
|
|
194
|
+
} // no browser, but a directory an earlier release left
|
|
195
|
+
return { released: !!live, sessionId: live?.ref.id ?? null };
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
/** Releases without failing the caller; idempotent. */
|
|
199
|
+
close(reason) {
|
|
200
|
+
return this.serial(async () => {
|
|
201
|
+
this.idle.cancel(this.d.config.label);
|
|
202
|
+
if (this.live)
|
|
203
|
+
await this.finish(this.live, reason).catch(() => undefined);
|
|
204
|
+
await this.sweepLeftovers();
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
async dispatching() { }
|
|
208
|
+
async journal() { }
|
|
209
|
+
async settle() { }
|
|
210
|
+
async navigated(url) { if (this.live)
|
|
211
|
+
this.live.record.lastUrl = scrubPageUrl(url, this.d.redact); }
|
|
212
|
+
ended() {
|
|
213
|
+
return this.serial(() => this.retireEnded());
|
|
214
|
+
}
|
|
215
|
+
dropped() {
|
|
216
|
+
return this.serial(async () => {
|
|
217
|
+
const driver = this.live?.driver;
|
|
218
|
+
if (!driver || !this.live)
|
|
219
|
+
return;
|
|
220
|
+
this.live.driver = null;
|
|
221
|
+
await closeDriver(driver);
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
/** A session left idle is released after the policy's idle spell. */
|
|
225
|
+
activity(delta) {
|
|
226
|
+
this.idle.activity(this.d.config.label, delta);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
const flagOf = (pi, name, fallback) => {
|
|
230
|
+
const value = pi.getFlag(name);
|
|
231
|
+
return typeof value === "string" && value ? value : fallback;
|
|
232
|
+
};
|
|
233
|
+
async function chooseProvider(pi, { options, env }, profiles) {
|
|
234
|
+
if (options.provider)
|
|
235
|
+
return typeof options.provider === "function" ? options.provider() : options.provider;
|
|
236
|
+
const kind = flagOf(pi, "browser-provider", env.PI_BROWSER_PROVIDER ?? "cdp");
|
|
237
|
+
if (kind === "browserbase") {
|
|
238
|
+
if (!(env.BROWSERBASE_API_KEY || env.BB_API_KEY))
|
|
239
|
+
throw refused("The browserbase provider needs BROWSERBASE_API_KEY in the environment; none is set. Use the default local browser, or ask the person to set the key.", "auth");
|
|
240
|
+
return (await import("./providers/browserbase.js")).browserbaseProvider({ env });
|
|
241
|
+
}
|
|
242
|
+
if (kind === "kernel") {
|
|
243
|
+
if (!env.KERNEL_API_KEY)
|
|
244
|
+
throw refused("The kernel provider needs KERNEL_API_KEY in the environment; none is set. Use the default local browser, or ask the person to set the key.", "auth");
|
|
245
|
+
return (await import("./providers/kernel.js")).kernelProvider({ env, stealth: env.PI_BROWSER_STEALTH === "1" });
|
|
246
|
+
}
|
|
247
|
+
if (kind !== "cdp")
|
|
248
|
+
throw refused(`--browser-provider is "${kind}"; it is cdp, browserbase or kernel.`, "refused");
|
|
249
|
+
const { cdpProvider } = await import("./providers/cdp.js");
|
|
250
|
+
const endpoint = flagOf(pi, "browser-endpoint", env.PI_BROWSER_ENDPOINT);
|
|
251
|
+
if (endpoint)
|
|
252
|
+
return cdpProvider({ endpoint });
|
|
253
|
+
// A Chrome the person named is used or refused by name, never swapped; only when none is named are the usual
|
|
254
|
+
// places searched.
|
|
255
|
+
const named = flagOf(pi, "browser-chrome") ?? (env.PI_BROWSER_CHROME || undefined);
|
|
256
|
+
if (named && !existsSync(named))
|
|
257
|
+
throw refused(`The Chrome named by --browser-chrome or PI_BROWSER_CHROME, ${named}, does not exist. Ask the person for the right path.`);
|
|
258
|
+
const executablePath = named ?? findChrome(env);
|
|
259
|
+
if (!executablePath)
|
|
260
|
+
throw refused("No Chrome or Chromium was found on this machine. Ask the person to install one, or to set PI_BROWSER_CHROME (or pass --browser-chrome) to its path, or --browser-endpoint to a running one.");
|
|
261
|
+
const headed = pi.getFlag("browser-headed") === true || env.PI_BROWSER_HEADED === "1";
|
|
262
|
+
// Absent the flag, the provider reads PI_BROWSER_NO_SANDBOX itself.
|
|
263
|
+
return cdpProvider({ chrome: { executablePath, profileRoot: await profiles.root(), headless: !headed, ...(pi.getFlag("browser-no-sandbox") === true ? { sandbox: false } : {}) } });
|
|
264
|
+
}
|
|
265
|
+
async function openRuntime(pi, settings, ctx, reason, listSites) {
|
|
266
|
+
const { options, env, policy, impls } = settings;
|
|
267
|
+
const closing = new AbortController();
|
|
268
|
+
const keyValues = () => providerKeyValues(env);
|
|
269
|
+
const redact = createRedactor(keyValues);
|
|
270
|
+
let root = null;
|
|
271
|
+
const profiles = { root: () => (root ??= mkdtemp(path.join(os.tmpdir(), "pi-browser-"))) };
|
|
272
|
+
let chosen = null;
|
|
273
|
+
const provider = () => (chosen ??= chooseProvider(pi, settings, profiles));
|
|
274
|
+
const evidence = fileEvidenceSink(path.join(ctx.cwd, ".pi", "browser", "evidence"), ctx.cwd);
|
|
275
|
+
const sessionId = ctx.sessionManager.getSessionId?.() ?? randomUUID();
|
|
276
|
+
const config = { label: "browser", run: sessionId, policy };
|
|
277
|
+
const driver = options.driver ?? (async (target, signal, driverOptions) => (await import("./driver/stagehand.js")).stagehandDriver()(target, signal, driverOptions));
|
|
278
|
+
const custody = new LocalCustody({ config, provider, driver, redact, signal: closing.signal, keep: (type, data) => pi.appendEntry(type, data) });
|
|
279
|
+
// A fork's branch holds its parent's entries: the parent released its own browser when it ended.
|
|
280
|
+
if (reason !== "fork")
|
|
281
|
+
await custody.releaseOrphans(ctx.sessionManager.getBranch()).catch(() => undefined);
|
|
282
|
+
// With no provider (no Chrome) the web tools still run on the host's fetchers.
|
|
283
|
+
const chosenProvider = await provider().catch(() => null);
|
|
284
|
+
const web = createWebTools({
|
|
285
|
+
name: "provider", evidence, redact: { values: keyValues },
|
|
286
|
+
scope: () => ({ label: "web", proxies: policy.proxies }), backups: options.backups ?? [httpBackup()],
|
|
287
|
+
...(chosenProvider?.fetch ? { fetch: (request, signal) => chosenProvider.fetch(request, signal) } : {}),
|
|
288
|
+
...(chosenProvider?.search ? { search: (request, signal) => chosenProvider.search(request, signal) } : {}),
|
|
289
|
+
});
|
|
290
|
+
// A listing that fails is asked again at the next session start.
|
|
291
|
+
const sites = options.sites && listSites ? await options.sites.list(closing.signal).catch(() => []) : [];
|
|
292
|
+
let closed = null;
|
|
293
|
+
return {
|
|
294
|
+
redact, web, searches: !!chosenProvider?.search, sites,
|
|
295
|
+
async call(tool, args, callId, signal) {
|
|
296
|
+
const impl = impls[tool];
|
|
297
|
+
custody.activity(1);
|
|
298
|
+
try {
|
|
299
|
+
const call = { callId, conversationId: CONVERSATION, signal, label: config.label, redact, evidence };
|
|
300
|
+
return await impl(args, custody, call);
|
|
301
|
+
}
|
|
302
|
+
finally {
|
|
303
|
+
custody.activity(-1);
|
|
304
|
+
}
|
|
305
|
+
},
|
|
306
|
+
close: () => (closed ??= (async () => {
|
|
307
|
+
closing.abort();
|
|
308
|
+
await custody.close("close");
|
|
309
|
+
if (root)
|
|
310
|
+
await root.then((dir) => rm(dir, { recursive: true, force: true })).catch(() => undefined);
|
|
311
|
+
})()),
|
|
312
|
+
};
|
|
313
|
+
}
|
|
314
|
+
function registerTool(pi, contract, runtimeOf) {
|
|
315
|
+
pi.registerTool({
|
|
316
|
+
name: contract.name,
|
|
317
|
+
label: contract.label,
|
|
318
|
+
description: contract.description,
|
|
319
|
+
promptSnippet: contract.label,
|
|
320
|
+
parameters: contract.parameters,
|
|
321
|
+
executionMode: contract.executionMode,
|
|
322
|
+
annotations: contract.effect === "read" ? { readOnlyHint: true, openWorldHint: true } : { readOnlyHint: false, openWorldHint: true },
|
|
323
|
+
async execute(callId, params, signal, _onUpdate, ctx) {
|
|
324
|
+
const rt = await runtimeOf(ctx);
|
|
325
|
+
const web = contract.name === "web_fetch" ? await rt.web.fetch(CONVERSATION, params, signal) : contract.name === "web_search" ? await rt.web.search(CONVERSATION, params, signal) : null;
|
|
326
|
+
const out = web ? { content: [{ type: "text", text: web.text }], details: web.details, isError: web.isError } : await rt.call(contract.name, params, callId, signal);
|
|
327
|
+
// Every text the model is shown passes the redactor, as the durable adapter does: a snapshot or a run's return value is
|
|
328
|
+
// where a registered key on a page would otherwise appear.
|
|
329
|
+
const content = out.content.map((item) => item.type === "text" ? { ...item, text: rt.redact(item.text) } : item);
|
|
330
|
+
return { content, details: out.details ? redactDeep(out.details, rt.redact) : undefined, ...(out.isError ? { isError: true } : {}) };
|
|
331
|
+
},
|
|
332
|
+
});
|
|
333
|
+
}
|
|
334
|
+
export function createBrowserExtension(options = {}) {
|
|
335
|
+
const env = options.env ?? process.env;
|
|
336
|
+
const policy = { ...DEFAULT_BROWSER_POLICY, ...(env.PI_BROWSER_PROXIES === "1" ? { proxies: true } : {}), ...options.policy };
|
|
337
|
+
const impls = { ...custodyTools, ...pageTools() };
|
|
338
|
+
return function piBrowser(pi) {
|
|
339
|
+
let runtime = null;
|
|
340
|
+
let opening = null;
|
|
341
|
+
let webSearchRegistered = false;
|
|
342
|
+
let sitesRegistered = false;
|
|
343
|
+
pi.registerFlag("browser-provider", { type: "string", description: "Browser provider: cdp (a local Chrome, the default), browserbase (needs BROWSERBASE_API_KEY) or kernel (needs KERNEL_API_KEY)" });
|
|
344
|
+
pi.registerFlag("browser-endpoint", { type: "string", description: "Attach to a Chrome DevTools endpoint (http://host:port or ws://...) instead of starting Chrome" });
|
|
345
|
+
pi.registerFlag("browser-chrome", { type: "string", description: "Path to the Chrome or Chromium to start" });
|
|
346
|
+
pi.registerFlag("browser-headed", { type: "boolean", description: "Show the browser window instead of running headless" });
|
|
347
|
+
pi.registerFlag("browser-no-sandbox", { type: "boolean", description: "Start Chrome without its sandbox (needed as root or in a container; only for pages you trust)" });
|
|
348
|
+
const runtimeOf = (ctx, reason = "startup") => runtime ? Promise.resolve(runtime) : (opening ??= openRuntime(pi, { options, env, policy, impls }, ctx, reason, !sitesRegistered).then((r) => {
|
|
349
|
+
if (r.searches && !webSearchRegistered) {
|
|
350
|
+
registerTool(pi, WEB_TOOLS.find((tool) => tool.name === "web_search"), runtimeOf);
|
|
351
|
+
webSearchRegistered = true;
|
|
352
|
+
}
|
|
353
|
+
if (options.sites && r.sites.length && !sitesRegistered) {
|
|
354
|
+
registerSites(options.sites, r.sites);
|
|
355
|
+
sitesRegistered = true;
|
|
356
|
+
}
|
|
357
|
+
return (runtime = r);
|
|
358
|
+
}));
|
|
359
|
+
const end = async () => {
|
|
360
|
+
const current = runtime ?? (await opening?.catch(() => null)) ?? null;
|
|
361
|
+
runtime = null;
|
|
362
|
+
opening = null;
|
|
363
|
+
await current?.close();
|
|
364
|
+
};
|
|
365
|
+
pi.on("session_start", async (event, ctx) => { await end(); await runtimeOf(ctx, event.reason); });
|
|
366
|
+
pi.on("session_shutdown", end);
|
|
367
|
+
pi.on("before_agent_start", (event) => { event.systemPromptOptions.sections.browser = browserSection(policy); });
|
|
368
|
+
async function childSession(ctx, prompt, signal) {
|
|
369
|
+
const sdk = await import("@earendil-works/pi-coding-agent");
|
|
370
|
+
const model = ctx.model;
|
|
371
|
+
if (!model)
|
|
372
|
+
throw new Error("this session has no model to give a child");
|
|
373
|
+
const cancelled = () => { if (signal.aborted)
|
|
374
|
+
throw new Error("the use_website call was cancelled before its child started"); };
|
|
375
|
+
const agentDir = sdk.getAgentDir();
|
|
376
|
+
const modelRuntime = await sdk.ModelRuntime.create();
|
|
377
|
+
// A provider registered at run time (by an extension, or a test) is not in the files a fresh runtime reads.
|
|
378
|
+
const registered = ctx.modelRegistry.getRegisteredProviderConfig(model.provider);
|
|
379
|
+
if (registered)
|
|
380
|
+
modelRuntime.registerProvider(model.provider, registered);
|
|
381
|
+
const flags = new Map();
|
|
382
|
+
for (const flag of BROWSER_FLAGS) {
|
|
383
|
+
const value = pi.getFlag(flag);
|
|
384
|
+
if (typeof value === "string" || typeof value === "boolean")
|
|
385
|
+
flags.set(flag, value);
|
|
386
|
+
}
|
|
387
|
+
const extension = createBrowserExtension({ ...options, sites: undefined });
|
|
388
|
+
const runtime = await sdk.createAgentSessionRuntime(async ({ cwd, sessionManager, sessionStartEvent }) => {
|
|
389
|
+
const services = await sdk.createAgentSessionServices({
|
|
390
|
+
cwd, agentDir, modelRuntime, extensionFlagValues: flags,
|
|
391
|
+
resourceLoaderOptions: { extensionFactories: [extension], noExtensions: true, noSkills: true, noPromptTemplates: true, noThemes: true, noContextFiles: true },
|
|
392
|
+
});
|
|
393
|
+
return { ...(await sdk.createAgentSessionFromServices({ services, sessionManager, sessionStartEvent, model, thinkingLevel: ctx.thinkingLevel, noTools: "builtin" })), services, diagnostics: services.diagnostics };
|
|
394
|
+
}, { cwd: ctx.cwd, agentDir, sessionManager: sdk.SessionManager.inMemory(ctx.cwd) });
|
|
395
|
+
let report = "";
|
|
396
|
+
const stop = runtime.session.subscribe((event) => {
|
|
397
|
+
if (event.type !== "message_end" || event.message.role !== "assistant")
|
|
398
|
+
return;
|
|
399
|
+
const text = event.message.content.filter((part) => part.type === "text").map((part) => part.text ?? "").join("").trim();
|
|
400
|
+
if (text)
|
|
401
|
+
report = text;
|
|
402
|
+
});
|
|
403
|
+
const abort = () => { runtime.session.abort().catch(() => undefined); };
|
|
404
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
405
|
+
try {
|
|
406
|
+
// A cancel during the setup above has already fired, so the listener never hears it: check before each step.
|
|
407
|
+
cancelled();
|
|
408
|
+
await runtime.session.bindExtensions({});
|
|
409
|
+
cancelled();
|
|
410
|
+
await runtime.session.prompt(prompt);
|
|
411
|
+
}
|
|
412
|
+
finally {
|
|
413
|
+
signal.removeEventListener("abort", abort);
|
|
414
|
+
stop();
|
|
415
|
+
await runtime.dispose();
|
|
416
|
+
}
|
|
417
|
+
if (!report)
|
|
418
|
+
throw new Error("the child finished without a report");
|
|
419
|
+
return report;
|
|
420
|
+
}
|
|
421
|
+
function registerSites(port, listing) {
|
|
422
|
+
const contract = useWebsiteContract(listing);
|
|
423
|
+
pi.registerTool({
|
|
424
|
+
name: contract.name,
|
|
425
|
+
label: contract.label,
|
|
426
|
+
description: contract.description,
|
|
427
|
+
promptSnippet: contract.label,
|
|
428
|
+
parameters: contract.parameters,
|
|
429
|
+
executionMode: contract.executionMode,
|
|
430
|
+
annotations: { readOnlyHint: false, openWorldHint: true },
|
|
431
|
+
async execute(_callId, params, signal, _onUpdate, ctx) {
|
|
432
|
+
const rt = await runtimeOf(ctx);
|
|
433
|
+
const out = await useWebsite(params, port, listing, { signal: signal ?? new AbortController().signal, runChild: (task, childSignal) => childSession(ctx, task.prompt, childSignal) });
|
|
434
|
+
return { content: out.content.map((item) => item.type === "text" ? { ...item, text: rt.redact(item.text) } : item), details: undefined, ...(out.isError ? { isError: true } : {}) };
|
|
435
|
+
},
|
|
436
|
+
});
|
|
437
|
+
}
|
|
438
|
+
for (const contract of BROWSER_TOOLS)
|
|
439
|
+
if (contract.listedWhen === "always")
|
|
440
|
+
registerTool(pi, contract, runtimeOf);
|
|
441
|
+
registerTool(pi, WEB_TOOLS.find((tool) => tool.name === "web_fetch"), runtimeOf);
|
|
442
|
+
};
|
|
443
|
+
}
|
|
444
|
+
export default function piBrowser(pi) {
|
|
445
|
+
createBrowserExtension()(pi);
|
|
446
|
+
}
|