@parcha/pi-browser 0.1.0-beta.32 → 0.1.0-beta.321
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 +187 -0
- package/NOTICE +36 -1
- package/README.md +91 -231
- package/dist/core/contract.d.ts +9 -6
- package/dist/core/contract.js +26 -35
- package/dist/core/custody.d.ts +12 -0
- package/dist/core/custody.js +21 -3
- package/dist/core/downloads.d.ts +37 -3
- package/dist/core/downloads.js +81 -57
- package/dist/core/driving-guard.d.ts +1 -1
- package/dist/core/driving-guard.js +18 -3
- package/dist/core/evidence.d.ts +1 -1
- package/dist/core/files.d.ts +20 -2
- package/dist/core/files.js +161 -10
- package/dist/core/host.d.ts +18 -75
- package/dist/core/images.d.ts +32 -4
- package/dist/core/images.js +81 -16
- package/dist/core/lease.d.ts +2 -1
- package/dist/core/page-scan.d.ts +81 -2
- package/dist/core/page-scan.js +487 -13
- package/dist/core/public-fetch.d.ts +70 -9
- package/dist/core/public-fetch.js +348 -51
- package/dist/core/read-page-worker.js +5 -4
- package/dist/core/read-page.d.ts +23 -8
- package/dist/core/read-page.js +64 -20
- package/dist/core/redact.d.ts +0 -2
- package/dist/core/redact.js +0 -32
- package/dist/core/session-control.d.ts +0 -2
- package/dist/core/session-control.js +0 -5
- package/dist/core/tools.d.ts +32 -1
- package/dist/core/tools.js +46 -4
- package/dist/core/usage.d.ts +4 -3
- package/dist/core/usage.js +5 -4
- package/dist/core/vault.d.ts +0 -10
- package/dist/core/vault.js +0 -13
- package/dist/core/web.d.ts +2 -111
- package/dist/core/web.js +0 -443
- package/dist/driver/cdp.d.ts +6 -0
- package/dist/driver/cdp.js +245 -0
- package/dist/driver/page-driver.js +36 -6
- package/dist/driver/stagehand.d.ts +3 -1
- package/dist/driver/stagehand.js +4 -2
- package/dist/durable/store.d.ts +14 -3
- package/dist/durable/store.js +217 -55
- package/dist/durable.d.ts +33 -16
- package/dist/durable.js +69 -95
- package/dist/index.d.ts +3 -3
- package/dist/index.js +5 -3
- package/dist/live-view/index.d.ts +3 -1
- package/dist/live-view/index.js +4 -0
- package/dist/live-view/protocol.d.ts +1 -1
- package/dist/live-view/provider.d.ts +2 -2
- package/dist/live-view/provider.js +2 -2
- package/dist/live-view/server.d.ts +31 -1
- package/dist/live-view/server.js +152 -25
- package/dist/providers/cdp.js +2 -2
- package/dist/providers/chrome-args.d.ts +3 -0
- package/dist/providers/chrome-args.js +13 -2
- package/dist/providers/profiles.d.ts +1 -15
- package/dist/providers/profiles.js +1 -64
- package/dist/providers/shared.d.ts +1 -47
- package/dist/providers/shared.js +1 -82
- package/dist/providers/worker-extension.d.ts +14 -1
- package/dist/providers/worker-extension.js +69 -3
- package/dist/testing/backend.d.ts +6 -24
- package/dist/testing/backend.js +7 -30
- package/dist/vault-session.d.ts +4 -7
- package/dist/vault-session.js +26 -81
- package/dist/vendor/browser-use-pi/ax.d.ts +106 -0
- package/dist/vendor/browser-use-pi/ax.js +642 -0
- package/dist/vendor/browser-use-pi/cdp.d.ts +19 -0
- package/dist/vendor/browser-use-pi/cdp.js +106 -0
- package/dist/vendor/browser-use-pi/page.d.ts +29 -0
- package/dist/vendor/browser-use-pi/page.js +99 -0
- package/package.json +14 -45
- package/src/vendor/browser-use-pi/UPSTREAM.json +25 -0
- package/src/vendor/stagehand-facade/UPSTREAM.json +0 -4
- package/dist/coding-agent-local.d.ts +0 -12
- package/dist/coding-agent-local.js +0 -72
- package/dist/coding-agent.d.ts +0 -135
- package/dist/coding-agent.js +0 -641
- package/dist/core/sites.d.ts +0 -33
- package/dist/core/sites.js +0 -104
- package/dist/durable/web.d.ts +0 -47
- package/dist/durable/web.js +0 -41
- package/dist/providers/assigned.d.ts +0 -18
- package/dist/providers/assigned.js +0 -75
- package/dist/providers/browserbase-net.d.ts +0 -12
- package/dist/providers/browserbase-net.js +0 -95
- package/dist/providers/browserbase.d.ts +0 -169
- package/dist/providers/browserbase.js +0 -319
- package/dist/providers/kernel.d.ts +0 -58
- package/dist/providers/kernel.js +0 -291
- package/dist/recorder/credential.d.ts +0 -9
- package/dist/recorder/credential.js +0 -49
- package/dist/recorder/follow.d.ts +0 -36
- package/dist/recorder/follow.js +0 -163
- package/dist/recorder/frames.d.ts +0 -87
- package/dist/recorder/frames.js +0 -377
- package/dist/recorder/index.d.ts +0 -4
- package/dist/recorder/index.js +0 -7
- package/dist/recorder/jpeg.d.ts +0 -8
- package/dist/recorder/jpeg.js +0 -70
- package/dist/recorder/track.d.ts +0 -107
- package/dist/recorder/track.js +0 -280
- package/dist/vendor/stagehand-facade/screenshot-transport.d.ts +0 -15
- package/dist/vendor/stagehand-facade/screenshot-transport.js +0 -51
- /package/dist/{providers → core}/cdp-call.d.ts +0 -0
- /package/dist/{providers → core}/cdp-call.js +0 -0
package/dist/core/sites.d.ts
DELETED
|
@@ -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;
|
package/dist/core/sites.js
DELETED
|
@@ -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
|
-
}
|
package/dist/durable/web.d.ts
DELETED
|
@@ -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
|
-
};
|
package/dist/durable/web.js
DELETED
|
@@ -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
|
-
}
|
|
@@ -1,169 +0,0 @@
|
|
|
1
|
-
import type { BrowserProvider, Geo, PriceTable, SessionSpec } from "../core/host.js";
|
|
2
|
-
import { type CdpSession } from "./cdp-call.js";
|
|
3
|
-
import { type ProfileStore } from "./profiles.js";
|
|
4
|
-
export { rewriteConnectUrl, browserbaseNoProxyHosts, applyBrowserbaseNoProxy } from "./browserbase-net.js";
|
|
5
|
-
export { fileProfileStore, memoryProfileStore, type ProfileStore } from "./profiles.js";
|
|
6
|
-
export declare const SEARCH_QUERY_MAX = 200;
|
|
7
|
-
export declare const SEARCH_RESULTS_MAX = 25;
|
|
8
|
-
export type BrowserbaseSdk = {
|
|
9
|
-
sessions: {
|
|
10
|
-
create(body: BrowserbaseSessionBody, options?: RequestOptions): Promise<{
|
|
11
|
-
id: string;
|
|
12
|
-
connectUrl: string;
|
|
13
|
-
}>;
|
|
14
|
-
list(query: {
|
|
15
|
-
q?: string;
|
|
16
|
-
status?: string;
|
|
17
|
-
}, options?: RequestOptions): Promise<Array<{
|
|
18
|
-
id: string;
|
|
19
|
-
status?: string;
|
|
20
|
-
userMetadata?: Record<string, unknown>;
|
|
21
|
-
}>>;
|
|
22
|
-
retrieve(id: string, options?: RequestOptions): Promise<{
|
|
23
|
-
id: string;
|
|
24
|
-
status?: string;
|
|
25
|
-
connectUrl?: string;
|
|
26
|
-
}>;
|
|
27
|
-
update(id: string, body: {
|
|
28
|
-
status: "REQUEST_RELEASE";
|
|
29
|
-
}, options?: RequestOptions): Promise<unknown>;
|
|
30
|
-
debug(id: string, options?: RequestOptions): Promise<{
|
|
31
|
-
debuggerFullscreenUrl?: string;
|
|
32
|
-
debuggerUrl?: string;
|
|
33
|
-
pages?: Array<{
|
|
34
|
-
id?: string;
|
|
35
|
-
url?: string;
|
|
36
|
-
title?: string;
|
|
37
|
-
debuggerFullscreenUrl?: string;
|
|
38
|
-
}>;
|
|
39
|
-
}>;
|
|
40
|
-
recording?: {
|
|
41
|
-
downloads: {
|
|
42
|
-
create(id: string): Promise<{
|
|
43
|
-
downloads?: RecordingDownload[];
|
|
44
|
-
}>;
|
|
45
|
-
list(id: string): Promise<{
|
|
46
|
-
downloads?: RecordingDownload[];
|
|
47
|
-
}>;
|
|
48
|
-
};
|
|
49
|
-
};
|
|
50
|
-
};
|
|
51
|
-
extensions: {
|
|
52
|
-
create(body: {
|
|
53
|
-
file: unknown;
|
|
54
|
-
}, options?: RequestOptions): Promise<{
|
|
55
|
-
id: string;
|
|
56
|
-
}>;
|
|
57
|
-
};
|
|
58
|
-
contexts: {
|
|
59
|
-
create(body: {
|
|
60
|
-
projectId?: string;
|
|
61
|
-
}, options?: RequestOptions): Promise<{
|
|
62
|
-
id: string;
|
|
63
|
-
}>;
|
|
64
|
-
};
|
|
65
|
-
fetchAPI: {
|
|
66
|
-
create(body: {
|
|
67
|
-
url: string;
|
|
68
|
-
allowRedirects?: boolean;
|
|
69
|
-
proxies?: boolean;
|
|
70
|
-
format?: string;
|
|
71
|
-
}, options?: RequestOptions): Promise<FetchApiResult>;
|
|
72
|
-
};
|
|
73
|
-
search: {
|
|
74
|
-
web(body: {
|
|
75
|
-
query: string;
|
|
76
|
-
numResults?: number;
|
|
77
|
-
}, options?: RequestOptions): Promise<SearchApiResult>;
|
|
78
|
-
};
|
|
79
|
-
get<T = unknown>(path: string, options?: RequestOptions & {
|
|
80
|
-
query?: Record<string, unknown>;
|
|
81
|
-
headers?: Record<string, string>;
|
|
82
|
-
__binaryResponse?: boolean;
|
|
83
|
-
}): Promise<T>;
|
|
84
|
-
};
|
|
85
|
-
type FetchApiResult = {
|
|
86
|
-
statusCode?: unknown;
|
|
87
|
-
contentType?: unknown;
|
|
88
|
-
content?: unknown;
|
|
89
|
-
} | null | undefined;
|
|
90
|
-
type SearchRow = {
|
|
91
|
-
url?: unknown;
|
|
92
|
-
title?: string | null;
|
|
93
|
-
author?: string | null;
|
|
94
|
-
publishedDate?: string | null;
|
|
95
|
-
published?: string | null;
|
|
96
|
-
};
|
|
97
|
-
type SearchApiResult = {
|
|
98
|
-
results?: SearchRow[];
|
|
99
|
-
} | null | undefined;
|
|
100
|
-
type BrowserbaseSessionBody = {
|
|
101
|
-
proxies: boolean | Array<Record<string, unknown>>;
|
|
102
|
-
timeout: number;
|
|
103
|
-
keepAlive: boolean;
|
|
104
|
-
browserSettings: {
|
|
105
|
-
solveCaptchas: boolean;
|
|
106
|
-
viewport: SessionSpec["viewport"];
|
|
107
|
-
verified?: boolean;
|
|
108
|
-
context?: {
|
|
109
|
-
id: string;
|
|
110
|
-
persist: boolean;
|
|
111
|
-
};
|
|
112
|
-
allowedDomains?: string[];
|
|
113
|
-
};
|
|
114
|
-
userMetadata: Record<string, string>;
|
|
115
|
-
region?: string;
|
|
116
|
-
extensionId?: string;
|
|
117
|
-
projectId?: string;
|
|
118
|
-
};
|
|
119
|
-
type RequestOptions = {
|
|
120
|
-
maxRetries?: number;
|
|
121
|
-
timeout?: number;
|
|
122
|
-
signal?: AbortSignal;
|
|
123
|
-
};
|
|
124
|
-
type RecordingDownload = {
|
|
125
|
-
pageId?: string;
|
|
126
|
-
status?: string;
|
|
127
|
-
downloadUrl?: string;
|
|
128
|
-
};
|
|
129
|
-
export type BrowserbaseOptions = {
|
|
130
|
-
/** Reads BROWSERBASE_API_KEY (or BB_API_KEY), _BASE_URL, _CONNECT_BASE_URL, _PROJECT_ID. Default: process.env. */
|
|
131
|
-
env?: NodeJS.ProcessEnv;
|
|
132
|
-
client?: BrowserbaseSdk;
|
|
133
|
-
/** The Stagehand extension's Browserbase id. Default: uploaded once per process. */
|
|
134
|
-
extensionId?: () => Promise<string>;
|
|
135
|
-
prices?: Partial<PriceTable>;
|
|
136
|
-
downloadBehavior?: (dialUrl: string) => Promise<DownloadSetting | void>;
|
|
137
|
-
confirm?: {
|
|
138
|
-
polls: number;
|
|
139
|
-
intervalMs: number;
|
|
140
|
-
};
|
|
141
|
-
sleep?: (ms: number) => Promise<void>;
|
|
142
|
-
/** Where profile names find their Browserbase contexts. Default: a file under the user's config directory. */
|
|
143
|
-
profiles?: ProfileStore;
|
|
144
|
-
/** How long a release that saved a profile waits for Browserbase to write the context back. */
|
|
145
|
-
profileSettleMs?: number;
|
|
146
|
-
};
|
|
147
|
-
/** `Browser.setDownloadBehavior` lasts only as long as the socket that sent it, so the socket stays open until
|
|
148
|
-
* `close()`. */
|
|
149
|
-
export type DownloadSetting = Pick<CdpSession, "close" | "open">;
|
|
150
|
-
/** Into `downloadPath` (default `downloads`, Browserbase's synced-downloads rule); the socket stays open. */
|
|
151
|
-
export declare const setDownloadBehavior: (url: string, options?: {
|
|
152
|
-
downloadPath?: string;
|
|
153
|
-
timeoutMs?: number;
|
|
154
|
-
}) => Promise<DownloadSetting>;
|
|
155
|
-
export type BrowserbaseProvider = BrowserProvider & {
|
|
156
|
-
readonly name: "browserbase";
|
|
157
|
-
};
|
|
158
|
-
/** ISO alpha-2 country, US state abbreviation, upper-case city; no two-letter country, no geolocation. */
|
|
159
|
-
export declare function browserbaseGeolocation(raw: Partial<Geo> | null | undefined): Geo | null;
|
|
160
|
-
export declare function proxiesField(proxies: SessionSpec["proxies"]): boolean | Array<Record<string, unknown>>;
|
|
161
|
-
export declare function sessionCreateBody(spec: SessionSpec, extra?: {
|
|
162
|
-
extensionId?: string;
|
|
163
|
-
projectId?: string;
|
|
164
|
-
context?: {
|
|
165
|
-
id: string;
|
|
166
|
-
persist: boolean;
|
|
167
|
-
};
|
|
168
|
-
}): BrowserbaseSessionBody;
|
|
169
|
-
export declare function browserbaseProvider(options?: BrowserbaseOptions): BrowserbaseProvider;
|