@parcha/pi-browser 0.1.0-beta.31 → 0.1.0-beta.310

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 (125) hide show
  1. package/CHANGELOG.md +232 -0
  2. package/NOTICE +39 -4
  3. package/README.md +122 -236
  4. package/dist/core/contract.d.ts +9 -6
  5. package/dist/core/contract.js +27 -36
  6. package/dist/core/custody.d.ts +19 -2
  7. package/dist/core/custody.js +28 -6
  8. package/dist/core/downloads.d.ts +44 -3
  9. package/dist/core/downloads.js +94 -58
  10. package/dist/core/driving-guard.d.ts +20 -0
  11. package/dist/core/driving-guard.js +190 -23
  12. package/dist/core/driving.d.ts +56 -2
  13. package/dist/core/driving.js +189 -10
  14. package/dist/core/effects.d.ts +80 -6
  15. package/dist/core/effects.js +374 -41
  16. package/dist/core/evidence.d.ts +1 -1
  17. package/dist/core/failures.d.ts +15 -1
  18. package/dist/core/failures.js +7 -0
  19. package/dist/core/files.d.ts +20 -2
  20. package/dist/core/files.js +161 -10
  21. package/dist/core/host.d.ts +29 -77
  22. package/dist/core/images.d.ts +32 -4
  23. package/dist/core/images.js +81 -16
  24. package/dist/core/lease.d.ts +2 -1
  25. package/dist/core/page-scan.d.ts +81 -2
  26. package/dist/core/page-scan.js +487 -13
  27. package/dist/core/public-fetch.d.ts +70 -9
  28. package/dist/core/public-fetch.js +348 -51
  29. package/dist/core/read-page-worker.js +5 -4
  30. package/dist/core/read-page.d.ts +23 -8
  31. package/dist/core/read-page.js +64 -20
  32. package/dist/core/redact.d.ts +0 -2
  33. package/dist/core/redact.js +0 -32
  34. package/dist/core/session-control.d.ts +0 -2
  35. package/dist/core/session-control.js +0 -5
  36. package/dist/core/tools.d.ts +46 -1
  37. package/dist/core/tools.js +88 -12
  38. package/dist/core/usage.d.ts +4 -3
  39. package/dist/core/usage.js +5 -4
  40. package/dist/core/vault.d.ts +0 -10
  41. package/dist/core/vault.js +0 -13
  42. package/dist/core/web.d.ts +2 -111
  43. package/dist/core/web.js +0 -443
  44. package/dist/driver/cdp.d.ts +6 -0
  45. package/dist/driver/cdp.js +245 -0
  46. package/dist/driver/page-driver.js +110 -7
  47. package/dist/driver/sealed.d.ts +4 -12
  48. package/dist/driver/sealed.js +23 -37
  49. package/dist/driver/stagehand.d.ts +12 -15
  50. package/dist/driver/stagehand.js +21 -17
  51. package/dist/durable/result.d.ts +1 -2
  52. package/dist/durable/result.js +2 -2
  53. package/dist/durable/store.d.ts +17 -3
  54. package/dist/durable/store.js +231 -64
  55. package/dist/durable.d.ts +47 -17
  56. package/dist/durable.js +106 -105
  57. package/dist/index.d.ts +3 -3
  58. package/dist/index.js +5 -3
  59. package/dist/live-view/index.d.ts +4 -1
  60. package/dist/live-view/index.js +5 -0
  61. package/dist/live-view/protocol.d.ts +39 -7
  62. package/dist/live-view/protocol.js +2 -0
  63. package/dist/live-view/provider.d.ts +2 -2
  64. package/dist/live-view/provider.js +2 -2
  65. package/dist/live-view/server.d.ts +55 -2
  66. package/dist/live-view/server.js +282 -35
  67. package/dist/live-view/stream.js +16 -3
  68. package/dist/live-view/viewer.js +106 -13
  69. package/dist/providers/cdp.d.ts +0 -1
  70. package/dist/providers/cdp.js +35 -13
  71. package/dist/providers/chrome-args.d.ts +3 -0
  72. package/dist/providers/chrome-args.js +13 -2
  73. package/dist/providers/profiles.d.ts +1 -15
  74. package/dist/providers/profiles.js +1 -64
  75. package/dist/providers/shared.d.ts +1 -47
  76. package/dist/providers/shared.js +1 -82
  77. package/dist/providers/worker-extension.d.ts +20 -1
  78. package/dist/providers/worker-extension.js +86 -7
  79. package/dist/testing/backend.d.ts +6 -24
  80. package/dist/testing/backend.js +7 -30
  81. package/dist/vault-session.d.ts +4 -7
  82. package/dist/vault-session.js +26 -81
  83. package/dist/vendor/browser-use-pi/ax.d.ts +106 -0
  84. package/dist/vendor/browser-use-pi/ax.js +642 -0
  85. package/dist/vendor/browser-use-pi/cdp.d.ts +19 -0
  86. package/dist/vendor/browser-use-pi/cdp.js +106 -0
  87. package/dist/vendor/browser-use-pi/page.d.ts +29 -0
  88. package/dist/vendor/browser-use-pi/page.js +99 -0
  89. package/package.json +15 -46
  90. package/src/vendor/browser-use-pi/UPSTREAM.json +25 -0
  91. package/src/vendor/stagehand-facade/UPSTREAM.json +0 -4
  92. package/dist/coding-agent-local.d.ts +0 -12
  93. package/dist/coding-agent-local.js +0 -72
  94. package/dist/coding-agent.d.ts +0 -134
  95. package/dist/coding-agent.js +0 -641
  96. package/dist/core/sites.d.ts +0 -33
  97. package/dist/core/sites.js +0 -104
  98. package/dist/driver/extension-worker.d.ts +0 -9
  99. package/dist/driver/extension-worker.js +0 -185
  100. package/dist/durable/web.d.ts +0 -47
  101. package/dist/durable/web.js +0 -41
  102. package/dist/providers/assigned.d.ts +0 -18
  103. package/dist/providers/assigned.js +0 -75
  104. package/dist/providers/browserbase-net.d.ts +0 -12
  105. package/dist/providers/browserbase-net.js +0 -95
  106. package/dist/providers/browserbase.d.ts +0 -169
  107. package/dist/providers/browserbase.js +0 -319
  108. package/dist/providers/kernel.d.ts +0 -58
  109. package/dist/providers/kernel.js +0 -291
  110. package/dist/recorder/credential.d.ts +0 -9
  111. package/dist/recorder/credential.js +0 -49
  112. package/dist/recorder/follow.d.ts +0 -36
  113. package/dist/recorder/follow.js +0 -163
  114. package/dist/recorder/frames.d.ts +0 -87
  115. package/dist/recorder/frames.js +0 -377
  116. package/dist/recorder/index.d.ts +0 -4
  117. package/dist/recorder/index.js +0 -7
  118. package/dist/recorder/jpeg.d.ts +0 -8
  119. package/dist/recorder/jpeg.js +0 -70
  120. package/dist/recorder/track.d.ts +0 -107
  121. package/dist/recorder/track.js +0 -280
  122. package/dist/vendor/stagehand-facade/screenshot-transport.d.ts +0 -15
  123. package/dist/vendor/stagehand-facade/screenshot-transport.js +0 -51
  124. /package/dist/{providers → core}/cdp-call.d.ts +0 -0
  125. /package/dist/{providers → core}/cdp-call.js +0 -0
@@ -1,33 +0,0 @@
1
- import type { ToolContract } from "./contract.js";
2
- import type { ToolOutput } from "./custody.js";
3
- import type { ChildRunner, SiteInfo, SiteRunPort } from "./host.js";
4
- export declare const MAX_SITE_INSTRUCTIONS = 16000;
5
- /** The site enum and the description render from the listing, which is configuration: every request sends the same
6
- * text and keeps the prompt cache. */
7
- export declare function useWebsiteContract(sites: readonly SiteInfo[]): ToolContract;
8
- /** Only the declared shape crosses back to the model: a port's extra fields, such as capabilities or URLs, are dropped
9
- * here, and an answer with both shapes or neither is no answer. */
10
- export declare function siteAnswer(raw: unknown): {
11
- run: {
12
- id: string;
13
- state: string;
14
- };
15
- } | {
16
- report: string;
17
- } | null;
18
- export declare function useWebsite(args: {
19
- site?: unknown;
20
- request_id?: unknown;
21
- instructions?: unknown;
22
- }, port: SiteRunPort, sites: readonly SiteInfo[], ctx: {
23
- signal: AbortSignal;
24
- runChild: ChildRunner;
25
- }): Promise<ToolOutput>;
26
- export type LocalSite = {
27
- title: string;
28
- description: string;
29
- startUrl: string;
30
- };
31
- /** `use_website` for a plain pi user: each task runs a child agent through the adapter's `runChild` and answers its
32
- * report. A request_id runs once; a failed run may be asked again. */
33
- export declare function localSites(sites: Record<string, LocalSite>): SiteRunPort;
@@ -1,104 +0,0 @@
1
- import { browserFailure } from "./failures.js";
2
- export const MAX_SITE_INSTRUCTIONS = 16_000;
3
- const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
4
- const RUN_ID = /^[A-Za-z0-9_.:-]{1,200}$/;
5
- const RUN_STATE = /^[a-z_]{1,40}$/;
6
- /** The site enum and the description render from the listing, which is configuration: every request sends the same
7
- * text and keeps the prompt cache. */
8
- export function useWebsiteContract(sites) {
9
- return {
10
- name: "use_website",
11
- label: "Use a website",
12
- description: [
13
- "Hand a task to an agent that works on one of these websites in its own browser, and get back what it found or did:",
14
- ...sites.map((site) => `- ${site.site}: ${site.title}. ${site.description}`),
15
- "Give a new request_id (a UUID) for each new task. Calling again with the request_id of a finished task answers its result without running it again; a task that failed runs again, and may repeat what it already did on the site.",
16
- "Several calls in one turn run at once, each agent in its own browser.",
17
- ].join("\n"),
18
- parameters: {
19
- type: "object", additionalProperties: false, required: ["site", "request_id", "instructions"],
20
- properties: {
21
- site: { type: "string", enum: sites.map((site) => site.site), description: "The website to use." },
22
- request_id: { type: "string", description: "A UUID you choose for this task." },
23
- instructions: { type: "string", maxLength: MAX_SITE_INSTRUCTIONS, description: "What to do on the website and what to report back." },
24
- },
25
- },
26
- effect: "effect", replay: "safe", executionMode: "parallel", evidence: "none", listedWhen: "sites",
27
- };
28
- }
29
- /** Only the declared shape crosses back to the model: a port's extra fields, such as capabilities or URLs, are dropped
30
- * here, and an answer with both shapes or neither is no answer. */
31
- export function siteAnswer(raw) {
32
- if (!raw || typeof raw !== "object")
33
- return null;
34
- const { run, report } = raw;
35
- if ((run === undefined) === (report === undefined))
36
- return null;
37
- if (report !== undefined)
38
- return typeof report === "string" ? { report } : null;
39
- const { id, state } = (run ?? {});
40
- return typeof id === "string" && RUN_ID.test(id) && typeof state === "string" && RUN_STATE.test(state) ? { run: { id, state } } : null;
41
- }
42
- const siteOutput = (body, isError = false) => ({ content: [{ type: "text", text: JSON.stringify(body) }], ...(isError ? { isError: true } : {}) });
43
- const siteRefusal = (message) => siteOutput(browserFailure("refused", message), true);
44
- export async function useWebsite(args, port, sites, ctx) {
45
- const site = sites.find((known) => known.site === args.site);
46
- if (!site)
47
- return siteRefusal(`site is one of: ${sites.map((known) => known.site).join(", ")}`);
48
- if (typeof args.request_id !== "string" || !UUID.test(args.request_id))
49
- return siteRefusal("request_id is a UUID you choose for this task");
50
- const instructions = typeof args.instructions === "string" ? args.instructions.trim() : "";
51
- if (!instructions || instructions.length > MAX_SITE_INSTRUCTIONS)
52
- return siteRefusal(`instructions say what to do on the site, in at most ${MAX_SITE_INSTRUCTIONS} characters`);
53
- const head = { ok: true, site: site.site, request_id: args.request_id };
54
- let raw;
55
- try {
56
- raw = await port.use({ site: site.site, requestId: args.request_id, instructions }, ctx);
57
- }
58
- catch {
59
- // A port's error text can carry its grant or a URL: none of it is forwarded.
60
- if (ctx.signal.aborted)
61
- return siteOutput({ ok: false, code: "aborted", retryable: true, effect: "possibly_effected", message: "The call was cancelled, and the site's task may already have changed the site. Calling again with the same request_id runs an unfinished task again, and it may repeat what it did." }, true);
62
- return siteOutput({ ok: false, code: "command_failed", retryable: true, effect: "possibly_effected", message: `The ${site.site} task failed, and may already have changed the site. Calling use_website again with the same request_id runs it again, and it may repeat what it did.` }, true);
63
- }
64
- const parsed = siteAnswer(raw);
65
- if (!parsed)
66
- return siteOutput({ ok: false, code: "command_failed", retryable: false, effect: "possibly_effected", message: `The ${site.site} runner answered neither a started task nor a report.` }, true);
67
- if ("report" in parsed)
68
- return siteOutput({ ...head, report: parsed.report });
69
- return siteOutput({ ...head, run: parsed.run, next: "The site's task was started; its result arrives through your host. Do not call use_website again for this request." });
70
- }
71
- const childPrompt = (site, entry, instructions) => [
72
- `You are doing one task on ${entry.title} (${site}) for another agent, in your own browser.`,
73
- `Start at ${entry.startUrl}.`,
74
- `Task: ${instructions}`,
75
- "Use the browser tools. Do not ask questions. Finish with a short report of what you found or did.",
76
- ].join("\n");
77
- /** `use_website` for a plain pi user: each task runs a child agent through the adapter's `runChild` and answers its
78
- * report. A request_id runs once; a failed run may be asked again. */
79
- export function localSites(sites) {
80
- for (const [site, entry] of Object.entries(sites)) {
81
- if (!/^https?:\/\//.test(entry.startUrl))
82
- throw new Error(`site ${site}: startUrl must be an http or https URL`);
83
- }
84
- const runs = new Map();
85
- return {
86
- async list() {
87
- return Object.entries(sites).map(([site, entry]) => ({ site, title: entry.title, description: entry.description }));
88
- },
89
- async use({ site, requestId, instructions }, { signal, runChild }) {
90
- const entry = Object.hasOwn(sites, site) ? sites[site] : undefined;
91
- if (!entry)
92
- throw new Error(`no site named ${site}`);
93
- const key = `${site}\u0000${requestId}`;
94
- let run = runs.get(key);
95
- if (!run) {
96
- run = runChild({ site, requestId, prompt: childPrompt(site, entry, instructions) }, signal);
97
- runs.set(key, run);
98
- run.catch(() => { if (runs.get(key) === run)
99
- runs.delete(key); });
100
- }
101
- return { report: await run };
102
- },
103
- };
104
- }
@@ -1,9 +0,0 @@
1
- export declare const STAGEHAND_EXTENSION = "Stagehand Runtime";
2
- /** A held extension runtime keeps one Stagehand instance until that instance's close, which a dead process never sent,
3
- * so a new attach would be refused. The close is sent here through the worker's own RPC, and the worker keeps running:
4
- * a worker closed under load is sometimes never restarted, and its attach waits out Stagehand's 60 s init deadline.
5
- * With no worker running nothing is held, and the worker is woken until it is listed. A target list the browser does
6
- * not give by DISCOVERY_MS is not a list without a worker: the attach fails. `replyMs`: how long the close waits for the
7
- * runtime's reply. An init still running in the extension answers it only once that init ends, since the runtime runs
8
- * both one after the other; the socket outlives the deadline by that much more. */
9
- export declare function installedExtension(cdpUrl: string, signal?: AbortSignal, known?: string, replyMs?: number): Promise<string | null>;
@@ -1,185 +0,0 @@
1
- export const STAGEHAND_EXTENSION = "Stagehand Runtime";
2
- const DISCOVERY_MS = 10_000;
3
- /** Kept past the deadline so the last wake page is closed on the same socket. */
4
- const CLEANUP_MS = 1_000;
5
- const WAKE_TRIES = 60;
6
- const CLOSE_REPLY_MS = 3_000;
7
- const SEND_TO_HOST = "__stagehandSendToHost";
8
- const RESET_ID = 2_147_000_000;
9
- /** The browser did not list its targets by the deadline, so a runtime it may hold could not be freed. */
10
- class TargetsUnlistedError extends Error {
11
- constructor() { super(`the browser did not list its targets within ${DISCOVERY_MS} ms, so a Stagehand runtime it may hold could not be freed`); }
12
- }
13
- /** One attach's CDP socket, open for `lifeMs` at most and closed at once on an abort. A call settles empty when the
14
- * browser does not answer within `ms` (the deadline, unless shorter), and every call settles empty once the socket
15
- * closes (an abort, the browser, the end of its life). */
16
- class Cdp {
17
- deadline;
18
- signal;
19
- /** Settles when the socket opens; rejects when it fails to open or closes first. */
20
- opened;
21
- socket;
22
- timer;
23
- stop = () => this.socket.close();
24
- pending = new Map();
25
- listeners = new Set();
26
- next = 0;
27
- isClosed = false;
28
- constructor(cdpUrl, deadline, lifeMs, signal) {
29
- this.deadline = deadline;
30
- this.signal = signal;
31
- this.socket = new WebSocket(cdpUrl);
32
- this.timer = setTimeout(() => this.socket.close(), lifeMs);
33
- signal?.addEventListener("abort", this.stop, { once: true });
34
- this.opened = new Promise((resolve, reject) => {
35
- this.socket.onopen = () => resolve();
36
- // A refused connection raises `error` and, on Node 22, never `close`: waiting for `close` alone would hang the attach.
37
- this.socket.onerror = () => reject(new Error("Failed to open CDP WebSocket"));
38
- this.socket.onclose = () => { this.onClose(); reject(new Error("the CDP socket closed")); };
39
- this.socket.onmessage = (event) => this.onMessage(event.data);
40
- });
41
- }
42
- /** A send on a closed socket neither throws nor is ever answered (Node 24): once closed, every call settles empty. */
43
- call(method, params = {}, sessionId, ms = this.deadline - Date.now()) {
44
- return new Promise((resolve) => {
45
- if (this.isClosed || this.socket.readyState !== WebSocket.OPEN || ms <= 0)
46
- return resolve(undefined);
47
- const id = ++this.next;
48
- const settle = (result) => { clearTimeout(wait); this.pending.delete(id); resolve(result); };
49
- const wait = setTimeout(() => settle(undefined), ms);
50
- this.pending.set(id, settle);
51
- this.socket.send(JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) }));
52
- });
53
- }
54
- listen(listener) { this.listeners.add(listener); }
55
- closed() { return this.isClosed; }
56
- end() { clearTimeout(this.timer); this.signal?.removeEventListener("abort", this.stop); this.socket.close(); }
57
- onClose() {
58
- this.isClosed = true;
59
- for (const settle of [...this.pending.values()])
60
- settle(undefined);
61
- for (const listener of this.listeners)
62
- listener({ method: "closed" });
63
- }
64
- /** A throw in a socket listener ends the process: a frame that is not JSON is dropped. */
65
- onMessage(data) {
66
- try {
67
- const message = JSON.parse(String(data));
68
- if (message?.id !== undefined)
69
- this.pending.get(message.id)?.(message.result);
70
- else if (message)
71
- for (const listener of this.listeners)
72
- listener(message);
73
- }
74
- catch { }
75
- }
76
- }
77
- /** The one enabled Stagehand extension's id; null when there is none, or more than one. */
78
- async function stagehandExtensionId(cdp) {
79
- const extensions = (await cdp.call("Extensions.getExtensions"))?.extensions ?? [];
80
- const enabled = extensions.filter((extension) => extension.name === STAGEHAND_EXTENSION && extension.enabled);
81
- return enabled.length === 1 ? enabled[0].id : null;
82
- }
83
- /** The extension's workers; null when the browser gave no list, which is not a list without one. */
84
- async function extensionWorkers(cdp, id) {
85
- const infos = (await cdp.call("Target.getTargets"))?.targetInfos;
86
- return infos?.filter((target) => target.type === "service_worker" && target.url.startsWith(`chrome-extension://${id}/`)).map((target) => target.targetId) ?? null;
87
- }
88
- /** With no worker running nothing is held, and the worker is woken until it is listed. Every wake page opened stays
89
- * listed here until a close of it is answered. None is opened within CLEANUP_MS of the deadline, an opening's reply is
90
- * awaited into the first half of that second, and the socket outlives the deadline by CLEANUP_MS, so the last pages are
91
- * closed on it. */
92
- async function wakeWorker(cdp, id, deadline) {
93
- const wakes = new Set();
94
- const closeWakes = async (ms) => { for (const page of [...wakes])
95
- if ((await cdp.call("Target.closeTarget", { targetId: page }, undefined, ms)) !== undefined)
96
- wakes.delete(page); };
97
- for (let tries = 0; !cdp.closed() && Date.now() < deadline && tries < WAKE_TRIES && ((await extensionWorkers(cdp, id))?.length ?? 0) === 0; tries += 1) {
98
- if (tries % 10 === 0 && deadline - Date.now() > CLEANUP_MS) {
99
- await closeWakes();
100
- const page = (await cdp.call("Target.createTarget", { url: `chrome-extension://${id}/wake-service-worker.html` }, undefined, deadline + CLEANUP_MS / 2 - Date.now()))?.targetId;
101
- if (page)
102
- wakes.add(page);
103
- }
104
- await new Promise((r) => setTimeout(r, 100));
105
- }
106
- await closeWakes(deadline + CLEANUP_MS - Date.now());
107
- }
108
- /** A binding call on `sessionId` that carries the reply to the close (its id is RESET_ID). */
109
- function isResetReply(event, sessionId) {
110
- if (event.method !== "Runtime.bindingCalled" || event.sessionId !== sessionId || event.params?.name !== SEND_TO_HOST)
111
- return false;
112
- try {
113
- return JSON.parse(event.params.payload ?? "")?.id === RESET_ID;
114
- }
115
- catch {
116
- return false;
117
- }
118
- }
119
- /** Settles on the runtime's reply to the close, at once when the socket closes, and after `replyMs` at most. */
120
- function resetReplied(cdp, sessionId, replyMs) {
121
- return new Promise((resolve) => {
122
- const wait = setTimeout(resolve, replyMs);
123
- cdp.listen((event) => {
124
- if (event.method === "closed" || isResetReply(event, sessionId)) {
125
- clearTimeout(wait);
126
- resolve();
127
- }
128
- });
129
- });
130
- }
131
- /** The held runtime's close, sent through the worker's own RPC, and its reply awaited for up to `replyMs`; the worker
132
- * keeps running. */
133
- async function closeHeldRuntime(cdp, worker, replyMs) {
134
- const sessionId = (await cdp.call("Target.attachToTarget", { targetId: worker, flatten: true }))?.sessionId;
135
- if (!sessionId)
136
- return;
137
- try {
138
- await cdp.call("Runtime.enable", {}, sessionId);
139
- await cdp.call("Runtime.addBinding", { name: SEND_TO_HOST }, sessionId);
140
- const replied = resetReplied(cdp, sessionId, replyMs);
141
- const close = JSON.stringify({ jsonrpc: "2.0", id: RESET_ID, method: "stagehand.close", params: {} });
142
- const sent = await cdp.call("Runtime.evaluate", { expression: `void globalThis.__stagehandReceiveFromHost(${JSON.stringify(close)}); true`, returnByValue: true }, sessionId);
143
- if (sent && !sent.exceptionDetails)
144
- await replied;
145
- }
146
- finally {
147
- await cdp.call("Target.detachFromTarget", { sessionId });
148
- }
149
- }
150
- /** A held extension runtime keeps one Stagehand instance until that instance's close, which a dead process never sent,
151
- * so a new attach would be refused. The close is sent here through the worker's own RPC, and the worker keeps running:
152
- * a worker closed under load is sometimes never restarted, and its attach waits out Stagehand's 60 s init deadline.
153
- * With no worker running nothing is held, and the worker is woken until it is listed. A target list the browser does
154
- * not give by DISCOVERY_MS is not a list without a worker: the attach fails. `replyMs`: how long the close waits for the
155
- * runtime's reply. An init still running in the extension answers it only once that init ends, since the runtime runs
156
- * both one after the other; the socket outlives the deadline by that much more. */
157
- export async function installedExtension(cdpUrl, signal, known, replyMs = CLOSE_REPLY_MS) {
158
- const deadline = Date.now() + DISCOVERY_MS;
159
- const cdp = new Cdp(cdpUrl, deadline, DISCOVERY_MS + CLEANUP_MS - CLOSE_REPLY_MS + replyMs, signal);
160
- try {
161
- await cdp.opened;
162
- const id = known || (await stagehandExtensionId(cdp));
163
- if (!id)
164
- return null;
165
- const running = await extensionWorkers(cdp, id);
166
- if (running === null) {
167
- if (signal?.aborted || cdp.closed())
168
- return id;
169
- throw new TargetsUnlistedError();
170
- }
171
- if (running.length === 0)
172
- await wakeWorker(cdp, id, deadline);
173
- else
174
- await closeHeldRuntime(cdp, running[0], replyMs);
175
- return id;
176
- }
177
- catch (error) {
178
- if (error instanceof TargetsUnlistedError)
179
- throw error;
180
- return known ?? null;
181
- }
182
- finally {
183
- cdp.end();
184
- }
185
- }
@@ -1,47 +0,0 @@
1
- import { defineExtension, type ConversationId, type ToolRegistration } from "@earendil-works/pi-durable";
2
- import type { Decisions } from "../core/decisions.js";
3
- import type { EvidenceSink } from "../core/evidence.js";
4
- import type { FetchRequest, FetchResult, PriceTable, SearchRequest, SearchResult } from "../core/host.js";
5
- import { type FetchSource, type RenderedPage, type SearchSource, type WebBackup, type WebToolsOptions } from "../core/web.js";
6
- export type WebExtensionOptions = {
7
- providers: {
8
- /** Names the source in `via` (`<name>_fetch`, `<name>_search`); default "provider". */
9
- name?: string;
10
- fetch?: (request: FetchRequest, signal?: AbortSignal) => Promise<FetchResult>;
11
- search?: (request: SearchRequest, signal?: AbortSignal) => Promise<SearchResult>;
12
- };
13
- /** Searches tried before `providers.search`, in order (see `SearchSource`). */
14
- searchSources?: readonly SearchSource[];
15
- /** Readers tried before `providers.fetch` for a markdown read, in order (see `FetchSource`). */
16
- fetchSources?: readonly FetchSource[];
17
- evidence: EvidenceSink;
18
- /** Per use: evidence label and proxies. Default: label "web", proxies on. */
19
- scope?: (conversationId: ConversationId) => {
20
- label: string;
21
- proxies: boolean;
22
- } | Promise<{
23
- label: string;
24
- proxies: boolean;
25
- }>;
26
- prices?: Partial<PriceTable>;
27
- redact?: {
28
- values: () => readonly string[];
29
- };
30
- /** The host's fallback fetchers, tried in order when the provider cannot fetch a page. */
31
- backups?: ReadonlyArray<WebBackup>;
32
- decisions?: Pick<Decisions, "classifyPage">;
33
- render?: {
34
- enabled: boolean;
35
- read(url: string, signal?: AbortSignal): Promise<RenderedPage>;
36
- };
37
- pdf?: WebToolsOptions["pdf"];
38
- /** How long the screening of a search answer's snippets may take in all (see `WebToolsOptions`). */
39
- snippetScreenMs?: number;
40
- section?: {
41
- addendum?: string;
42
- };
43
- };
44
- export declare function createWebExtension(options: WebExtensionOptions): {
45
- extension: ReturnType<typeof defineExtension>;
46
- tools: readonly ToolRegistration[];
47
- };
@@ -1,41 +0,0 @@
1
- import { defineExtension, defineTool } from "@earendil-works/pi-durable";
2
- import { WEB_TOOLS } from "../core/contract.js";
3
- import { providerKeyValues } from "../core/session-control.js";
4
- import { toolUsage } from "../core/usage.js";
5
- import { createWebTools } from "../core/web.js";
6
- import { forModel } from "./result.js";
7
- export function createWebExtension(options) {
8
- const tools = createWebTools({
9
- name: options.providers.name ?? "provider",
10
- fetch: options.providers.fetch,
11
- search: options.providers.search,
12
- searchSources: options.searchSources,
13
- fetchSources: options.fetchSources,
14
- evidence: options.evidence,
15
- scope: options.scope ?? (() => ({ label: "web", proxies: true })),
16
- prices: options.prices,
17
- redact: { values: () => providerKeyValues(process.env, options.redact?.values) },
18
- backups: options.backups,
19
- classifyPage: options.decisions?.classifyPage,
20
- render: options.render,
21
- pdf: options.pdf,
22
- snippetScreenMs: options.snippetScreenMs,
23
- });
24
- const run = { web_fetch: tools.fetch, web_search: tools.search };
25
- const result = ({ text, isError, details, usd }) => ({ ...forModel([{ type: "text", text }]), isError, details: details, usage: toolUsage(usd).usage });
26
- const registrations = WEB_TOOLS
27
- .filter((tool) => (tool.listedWhen === "fetch" ? options.providers.fetch || options.render?.enabled || options.backups?.length || options.fetchSources?.length : options.providers.search || options.searchSources?.length))
28
- .map((tool) => defineTool({
29
- name: tool.name,
30
- description: tool.description,
31
- parameters: tool.parameters,
32
- replay: tool.replay,
33
- executionMode: tool.executionMode,
34
- execute: async (args, api, context) => result(await run[tool.name](api.conversationId, args, context.abortSignal)),
35
- }));
36
- // Matched by name: another extension's tool registered under the same name would carry the text too.
37
- const names = new Set(registrations.map((tool) => tool.name));
38
- const addendum = options.section?.addendum;
39
- const sections = addendum ? [{ key: "web", render: async (input) => (input.agent.tools.some((tool) => names.has(tool.name)) ? addendum : undefined) }] : [];
40
- return { extension: defineExtension({ name: "web", tools: registrations, sections }), tools: registrations };
41
- }
@@ -1,18 +0,0 @@
1
- import { type BrowserFailure } from "../core/failures.js";
2
- import type { AttachTarget, BrowserProvider } from "../core/host.js";
3
- import type { ResourceStatus } from "../core/lease.js";
4
- export type AssignedSession = {
5
- /** The session's id: the same for every attach. */
6
- readonly id: string;
7
- /** A fresh target for the driver; it names no secret in `sdkCdpUrl` (a relay or a signed URL goes in `dial`). A failure
8
- * the model should read is thrown as an error carrying `failure`. */
9
- attach(signal?: AbortSignal): Promise<AttachTarget>;
10
- status(signal?: AbortSignal): Promise<ResourceStatus>;
11
- /** Why the session can no longer be used (the host fenced it, took it back, it ended), or null while it can. */
12
- failure?(): BrowserFailure | null;
13
- };
14
- export declare function assignedSessionProvider(input: {
15
- name: string;
16
- session: AssignedSession;
17
- maxLifetimeS?: number;
18
- }): BrowserProvider;
@@ -1,75 +0,0 @@
1
- // A provider over the one session a host assigned to the run (Parcha's site child: the session it reserved for this task).
2
- // It never creates or ends a browser. create hands that session to one custody at a time, every attach asks the host for a
3
- // fresh target (a relay's capability rotates), and release lets go of that custody's hold without asking the host: a
4
- // custody releases at a failed launch, an orphan sweep or a conversation's end, and the session is the task's, not the
5
- // conversation's. The host takes it back itself, once, when the task's browser closes; after that the session's own
6
- // failure() answers every create. A second create while another custody holds it is a refusal: the run has one browser.
7
- import { BrowserFailureError, refusedError } from "../core/custody.js";
8
- import { FAILURE_CODES } from "../core/failures.js";
9
- /** A host session types a failure the model should read as an error carrying `failure`; the tool loop takes it as is. */
10
- function typed(error) {
11
- const failure = error?.failure;
12
- if (error instanceof BrowserFailureError || !failure || failure.ok !== false || !FAILURE_CODES.includes(failure.code))
13
- return error;
14
- return new BrowserFailureError(failure);
15
- }
16
- let assignedHolds;
17
- const assignedHoldOf = (session) => {
18
- assignedHolds ??= new WeakMap();
19
- let assignedCustody = assignedHolds.get(session);
20
- if (!assignedCustody) {
21
- assignedCustody = { heldBy: null, letGo: new Set() };
22
- assignedHolds.set(session, assignedCustody);
23
- }
24
- return assignedCustody;
25
- };
26
- export function assignedSessionProvider(input) {
27
- const { session } = input;
28
- const caps = { timeoutModel: "wall-clock", maxLifetimeS: input.maxLifetimeS ?? 21_600, survivesDisconnect: true, releaseIsAsync: false, extension: "preinstalled", fixedSession: true,
29
- // The host made the session and owns its sign-in: none of the run's session settings is applied, and no saved profile
30
- // can be loaded into it.
31
- settings: { proxies: false, verified: false, geolocation: false, region: false, context: false }, profiles: false };
32
- // A hold its custody let go of is over for that custody; the session goes on for the next one.
33
- const assignedCustody = assignedHoldOf(session);
34
- const ours = (ref) => ref.id === session.id;
35
- return {
36
- name: input.name,
37
- caps,
38
- async create(spec) {
39
- // A session that can no longer be used says why (a sign-in it needs, the host took it back), never that it is open elsewhere.
40
- const ended = session.failure?.();
41
- if (ended)
42
- throw new BrowserFailureError(ended);
43
- if (assignedCustody.heldBy !== null && assignedCustody.heldBy !== spec.tag)
44
- throw refusedError("This task has one browser, the website session assigned to it, and it is already open; keep using it.");
45
- assignedCustody.heldBy = spec.tag;
46
- assignedCustody.letGo.delete(spec.tag);
47
- return { id: session.id, tag: spec.tag };
48
- },
49
- findByTag: async (tag) => (assignedCustody.heldBy === tag ? [{ id: session.id, tag }] : []),
50
- async status(ref, signal) {
51
- if (!ours(ref))
52
- return "gone";
53
- if (assignedCustody.letGo.has(ref.tag))
54
- return "stopped";
55
- return session.status(signal);
56
- },
57
- async attach(ref, signal) {
58
- if (!ours(ref))
59
- throw new Error("this session is not the one the host assigned to the run");
60
- try {
61
- return await session.attach(signal);
62
- }
63
- catch (error) {
64
- throw typed(error);
65
- }
66
- },
67
- async release(ref) {
68
- if (!ours(ref))
69
- return;
70
- if (assignedCustody.heldBy === ref.tag)
71
- assignedCustody.heldBy = null;
72
- assignedCustody.letGo.add(ref.tag);
73
- },
74
- };
75
- }
@@ -1,12 +0,0 @@
1
- /** Rewrite a Browserbase connect URL onto the credential proxy: only `*.browserbase.com` hosts, the signing query kept. */
2
- export declare function rewriteConnectUrl(connectUrl: string, connectBaseUrl: string | undefined | null): string;
3
- /** Direct, never through the HTTP(S) env proxy: it rejects CONNECT and the CDP WebSocket cannot ride it. Under `node
4
- * --use-env-proxy` NO_PROXY is re-read per request, so listing these hosts bypasses it. */
5
- export declare function browserbaseNoProxyHosts(env: NodeJS.ProcessEnv): string[];
6
- export declare function applyBrowserbaseNoProxy(env?: NodeJS.ProcessEnv): string[];
7
- /** A second provider binding the same URL to a different proxy is refused, never switched: the signed URL would go to
8
- * it. */
9
- export declare function bindConnectDial(connectUrl: string, connectBaseUrl: string | null): void;
10
- export declare function unbindConnectDial(connectUrl: string): void;
11
- export declare function connectDialUrl(url: string): string;
12
- export declare function installWebSocketWrapper(): void;
@@ -1,95 +0,0 @@
1
- import { browserbaseHoldings } from "./shared.js";
2
- /** Rewrite a Browserbase connect URL onto the credential proxy: only `*.browserbase.com` hosts, the signing query kept. */
3
- export function rewriteConnectUrl(connectUrl, connectBaseUrl) {
4
- if (!connectUrl || !connectBaseUrl)
5
- return connectUrl;
6
- try {
7
- const target = new URL(connectBaseUrl);
8
- const u = new URL(connectUrl);
9
- if (!/(?:^|\.)browserbase\.com$/i.test(u.hostname))
10
- return connectUrl;
11
- u.protocol = target.protocol;
12
- u.host = target.host;
13
- u.pathname = target.pathname.replace(/\/$/, "") + u.pathname;
14
- return u.toString();
15
- }
16
- catch {
17
- return connectUrl;
18
- }
19
- }
20
- /** Direct, never through the HTTP(S) env proxy: it rejects CONNECT and the CDP WebSocket cannot ride it. Under `node
21
- * --use-env-proxy` NO_PROXY is re-read per request, so listing these hosts bypasses it. */
22
- export function browserbaseNoProxyHosts(env) {
23
- const hosts = new Set();
24
- for (const key of ["BROWSERBASE_BASE_URL", "BROWSERBASE_CONNECT_BASE_URL"]) {
25
- const raw = String(env[key] || "").trim();
26
- if (!raw)
27
- continue;
28
- try {
29
- hosts.add(new URL(raw).hostname);
30
- }
31
- catch { }
32
- }
33
- if (!String(env.BROWSERBASE_CONNECT_BASE_URL || "").trim())
34
- hosts.add(".browserbase.com");
35
- return [...hosts];
36
- }
37
- export function applyBrowserbaseNoProxy(env = process.env) {
38
- const hosts = browserbaseNoProxyHosts(env);
39
- if (!hosts.length)
40
- return hosts;
41
- for (const target of env === process.env ? [env] : [env, process.env]) {
42
- for (const key of ["NO_PROXY", "no_proxy"]) {
43
- const merged = String(target[key] || "").split(",").map((h) => h.trim()).filter(Boolean);
44
- for (const h of hosts)
45
- if (!merged.includes(h))
46
- merged.push(h);
47
- target[key] = merged.join(",");
48
- }
49
- }
50
- return hosts;
51
- }
52
- /** The driver keeps the raw connect URL (the extension in the cloud browser dials it back and reaches only
53
- * Browserbase); this process's socket dials the proxy, so the rewrite happens at dial time, never in a record. */
54
- /** Per-socket targets, so two providers with different proxies never send one's signed URL to the other's proxy. */
55
- const { boundDials } = browserbaseHoldings;
56
- /** A second provider binding the same URL to a different proxy is refused, never switched: the signed URL would go to
57
- * it. */
58
- export function bindConnectDial(connectUrl, connectBaseUrl) {
59
- const target = connectBaseUrl?.trim() ?? "";
60
- const bound = boundDials.get(connectUrl);
61
- if (bound !== undefined && bound !== target)
62
- throw new Error("this Browserbase session is already attached through another credential proxy");
63
- boundDials.set(connectUrl, target);
64
- }
65
- export function unbindConnectDial(connectUrl) {
66
- boundDials.delete(connectUrl);
67
- if (![...boundDials.values()].some(Boolean))
68
- restoreWebSocket();
69
- }
70
- export function connectDialUrl(url) {
71
- const bound = boundDials.get(url);
72
- if (bound !== undefined)
73
- return bound ? rewriteConnectUrl(url, bound) : url;
74
- return url;
75
- }
76
- /** Wraps the process WebSocket only while a session is bound to a proxy; the native one returns with the last binding. A wrapper
77
- * installed on top cannot be removed, so ours stays under it and, with no bindings, passes every URL through. */
78
- let wrapped = null;
79
- export function installWebSocketWrapper() {
80
- if (typeof globalThis.WebSocket !== "function" || (wrapped && globalThis.WebSocket === wrapped.wrapper))
81
- return;
82
- const original = globalThis.WebSocket;
83
- const wrapper = function (url, protocols) { return new original(connectDialUrl(String(url)), protocols); };
84
- wrapper.prototype = original.prototype;
85
- for (const k of ["CONNECTING", "OPEN", "CLOSING", "CLOSED"])
86
- wrapper[k] = original[k];
87
- globalThis.WebSocket = wrapper;
88
- wrapped = { original, wrapper };
89
- }
90
- function restoreWebSocket() {
91
- if (!wrapped || globalThis.WebSocket !== wrapped.wrapper)
92
- return;
93
- globalThis.WebSocket = wrapped.original;
94
- wrapped = null;
95
- }