@parcha/pi-browser 0.0.0-stage → 0.1.0-beta.14

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 (108) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +33 -0
  4. package/README.md +348 -2
  5. package/dist/coding-agent-local.d.ts +16 -0
  6. package/dist/coding-agent-local.js +138 -0
  7. package/dist/coding-agent.d.ts +79 -0
  8. package/dist/coding-agent.js +448 -0
  9. package/dist/core/contract.d.ts +26 -0
  10. package/dist/core/contract.js +154 -0
  11. package/dist/core/custody.d.ts +117 -0
  12. package/dist/core/custody.js +126 -0
  13. package/dist/core/decisions.d.ts +43 -0
  14. package/dist/core/decisions.js +4 -0
  15. package/dist/core/downloads.d.ts +35 -0
  16. package/dist/core/downloads.js +131 -0
  17. package/dist/core/effects.d.ts +63 -0
  18. package/dist/core/effects.js +256 -0
  19. package/dist/core/evidence.d.ts +43 -0
  20. package/dist/core/evidence.js +6 -0
  21. package/dist/core/failures.d.ts +36 -0
  22. package/dist/core/failures.js +68 -0
  23. package/dist/core/find.d.ts +32 -0
  24. package/dist/core/find.js +179 -0
  25. package/dist/core/guard.d.ts +6 -0
  26. package/dist/core/guard.js +25 -0
  27. package/dist/core/host.d.ts +328 -0
  28. package/dist/core/host.js +2 -0
  29. package/dist/core/images.d.ts +37 -0
  30. package/dist/core/images.js +60 -0
  31. package/dist/core/lease.d.ts +16 -0
  32. package/dist/core/lease.js +30 -0
  33. package/dist/core/receipts.d.ts +19 -0
  34. package/dist/core/receipts.js +22 -0
  35. package/dist/core/redact.d.ts +13 -0
  36. package/dist/core/redact.js +83 -0
  37. package/dist/core/session-control.d.ts +25 -0
  38. package/dist/core/session-control.js +75 -0
  39. package/dist/core/sites.d.ts +33 -0
  40. package/dist/core/sites.js +102 -0
  41. package/dist/core/tools.d.ts +72 -0
  42. package/dist/core/tools.js +200 -0
  43. package/dist/core/uri.d.ts +11 -0
  44. package/dist/core/uri.js +37 -0
  45. package/dist/core/usage.d.ts +19 -0
  46. package/dist/core/usage.js +44 -0
  47. package/dist/core/web.d.ts +98 -0
  48. package/dist/core/web.js +327 -0
  49. package/dist/driver/extension-worker.d.ts +6 -0
  50. package/dist/driver/extension-worker.js +121 -0
  51. package/dist/driver/stagehand.d.ts +25 -0
  52. package/dist/driver/stagehand.js +91 -0
  53. package/dist/durable-result.d.ts +6 -0
  54. package/dist/durable-result.js +2 -0
  55. package/dist/durable.d.ts +79 -0
  56. package/dist/durable.js +582 -0
  57. package/dist/index.d.ts +19 -0
  58. package/dist/index.js +20 -0
  59. package/dist/providers/browserbase-net.d.ts +13 -0
  60. package/dist/providers/browserbase-net.js +96 -0
  61. package/dist/providers/browserbase.d.ts +152 -0
  62. package/dist/providers/browserbase.js +262 -0
  63. package/dist/providers/cdp-call.d.ts +6 -0
  64. package/dist/providers/cdp-call.js +25 -0
  65. package/dist/providers/cdp.d.ts +55 -0
  66. package/dist/providers/cdp.js +423 -0
  67. package/dist/providers/http.d.ts +2 -0
  68. package/dist/providers/http.js +21 -0
  69. package/dist/providers/kernel.d.ts +49 -0
  70. package/dist/providers/kernel.js +246 -0
  71. package/dist/providers/shared.d.ts +47 -0
  72. package/dist/providers/shared.js +82 -0
  73. package/dist/recorder/credential.d.ts +9 -0
  74. package/dist/recorder/credential.js +49 -0
  75. package/dist/recorder/follow.d.ts +26 -0
  76. package/dist/recorder/follow.js +138 -0
  77. package/dist/recorder/frames.d.ts +80 -0
  78. package/dist/recorder/frames.js +309 -0
  79. package/dist/recorder/index.d.ts +4 -0
  80. package/dist/recorder/index.js +7 -0
  81. package/dist/recorder/jpeg.d.ts +8 -0
  82. package/dist/recorder/jpeg.js +70 -0
  83. package/dist/recorder/track.d.ts +107 -0
  84. package/dist/recorder/track.js +259 -0
  85. package/dist/store.d.ts +56 -0
  86. package/dist/store.js +196 -0
  87. package/dist/testing/backend.d.ts +231 -0
  88. package/dist/testing/backend.js +414 -0
  89. package/dist/testing/driver.d.ts +28 -0
  90. package/dist/testing/driver.js +32 -0
  91. package/dist/testing/index.d.ts +4 -0
  92. package/dist/testing/index.js +4 -0
  93. package/dist/testing/pages.d.ts +3 -0
  94. package/dist/testing/pages.js +10 -0
  95. package/dist/testing/sentinels.d.ts +29 -0
  96. package/dist/testing/sentinels.js +38 -0
  97. package/dist/vendor/stagehand-facade/contract.d.ts +348 -0
  98. package/dist/vendor/stagehand-facade/contract.js +155 -0
  99. package/dist/vendor/stagehand-facade/runtime.d.ts +90 -0
  100. package/dist/vendor/stagehand-facade/runtime.js +1640 -0
  101. package/dist/vendor/stagehand-facade/screenshot-transport.d.ts +15 -0
  102. package/dist/vendor/stagehand-facade/screenshot-transport.js +51 -0
  103. package/dist/vendor/stagehand-facade/tools.d.ts +31 -0
  104. package/dist/vendor/stagehand-facade/tools.js +139 -0
  105. package/dist/web.d.ts +41 -0
  106. package/dist/web.js +38 -0
  107. package/package.json +123 -4
  108. package/src/vendor/stagehand-facade/UPSTREAM.json +24 -0
@@ -0,0 +1,30 @@
1
+ import { createHash } from "node:crypto";
2
+ /** Each change is one commit, and a provider call sits between two commits, never inside one. `lost` ends custody of a
3
+ * resource the provider no longer answers for and that was never confirmed released. */
4
+ export const LEASE_TRANSITIONS = Object.freeze({
5
+ none: ["creating"],
6
+ creating: ["live", "released", "releasing"],
7
+ live: ["releasing", "released", "lost"],
8
+ releasing: ["released", "lost"],
9
+ released: [],
10
+ lost: [],
11
+ });
12
+ export function isLeaseTransition(from, to) {
13
+ return LEASE_TRANSITIONS[from].includes(to);
14
+ }
15
+ // Only the run part may keep a '-', the separator, so two different part lists never join into one tag.
16
+ const UNCLEAN = /[^A-Za-z0-9_.]+/g;
17
+ const UNCLEAN_RUN = /[^A-Za-z0-9_.-]+/g;
18
+ /** A cleaned or cut part keeps a hash of the original, after its head when it fits: distinct parts never collapse. */
19
+ function tagPart(part, max, unclean = UNCLEAN) {
20
+ const clean = part.replace(unclean, "_");
21
+ if (clean === part && clean.length <= max)
22
+ return clean;
23
+ const hash = createHash("sha256").update(part).digest("hex");
24
+ return max > 9 ? `${clean.slice(0, max - 9)}_${hash.slice(0, 8)}` : hash.slice(0, max);
25
+ }
26
+ /** At most 60 characters of `[A-Za-z0-9_.-]`: Browserbase holds metadata values to 60, and a tag query quotes it
27
+ * unescaped. */
28
+ export function leaseTag(prefix, run, conversation, seq) {
29
+ return `${tagPart(prefix, 4)}-${tagPart(run, 28, UNCLEAN_RUN)}-${tagPart(String(conversation), 12)}-${tagPart(String(seq), 10)}`;
30
+ }
@@ -0,0 +1,19 @@
1
+ import type { EvidenceRecord } from "./evidence.js";
2
+ import type { SessionRecord } from "./host.js";
3
+ type Facts = EvidenceRecord["facts"];
4
+ export type ReceiptFacts = Pick<Facts, "sha256" | "session" | "recording_at_s">;
5
+ export type ReadSession = Pick<SessionRecord, "resourceId" | "createdAt">;
6
+ export declare const sha256Hex: (bytes: string | Uint8Array) => string;
7
+ /** To a tenth; never negative; null for a bad date. A frame sits slightly before its offset. */
8
+ export declare function recordingOffsetS(createdAt: string, at: number | Date): number | null;
9
+ /** A fact that does not apply is absent, never null, so a receipt header has no line for it. */
10
+ export declare function receiptFacts(read: {
11
+ body: string | Uint8Array;
12
+ session?: ReadSession | null;
13
+ recorded: boolean;
14
+ at?: number | Date;
15
+ }): ReceiptFacts;
16
+ /** A key the order does not list follows the listed ones, so a fact added to the record never goes missing from a
17
+ * receipt. */
18
+ export declare function orderFacts(facts: Facts): Facts;
19
+ export {};
@@ -0,0 +1,22 @@
1
+ import { createHash } from "node:crypto";
2
+ export const sha256Hex = (bytes) => createHash("sha256").update(bytes).digest("hex");
3
+ /** To a tenth; never negative; null for a bad date. A frame sits slightly before its offset. */
4
+ export function recordingOffsetS(createdAt, at) {
5
+ const start = Date.parse(createdAt);
6
+ const end = typeof at === "number" ? at : at.getTime();
7
+ return Number.isFinite(start) && Number.isFinite(end) ? Math.max(0, Math.round((end - start) / 100) / 10) : null;
8
+ }
9
+ /** A fact that does not apply is absent, never null, so a receipt header has no line for it. */
10
+ export function receiptFacts(read) {
11
+ const id = read.session?.resourceId ?? null;
12
+ const offset = id && read.recorded && read.session ? recordingOffsetS(read.session.createdAt, read.at ?? Date.now()) : null;
13
+ return { sha256: sha256Hex(read.body), ...(id ? { session: id } : {}), ...(offset !== null ? { recording_at_s: offset } : {}) };
14
+ }
15
+ const FACT_ORDER = ["requested_url", "final_url", "title", "status_code", "content_type", "sha256", "extractor", "via", "session", "recording_at_s", "page_guard"];
16
+ /** A key the order does not list follows the listed ones, so a fact added to the record never goes missing from a
17
+ * receipt. */
18
+ export function orderFacts(facts) {
19
+ const listed = new Set(FACT_ORDER);
20
+ const keys = [...FACT_ORDER, ...Object.keys(facts).filter((key) => !listed.has(key))];
21
+ return Object.fromEntries(keys.flatMap((key) => (facts[key] === undefined ? [] : [[key, facts[key]]])));
22
+ }
@@ -0,0 +1,13 @@
1
+ export type Redact = (text: string) => string;
2
+ /** Scrubbing a shorter string everywhere would destroy the text around it, and no credential is that short. */
3
+ export declare const MIN_REDACTED_VALUE_LENGTH = 8;
4
+ /** `values()` is read at every call; each value is scrubbed raw, URL-encoded fully, and in every spelling web_fetch can
5
+ * send it in (fetchedSpellings), longest first. */
6
+ export declare function createRedactor(values?: () => readonly string[]): Redact;
7
+ /** A credential can sit in any query value, the fragment or the userinfo, so every query value is replaced (names stay)
8
+ * and the fragment and userinfo are dropped before `redact` runs. A non-http(s) URL is only redacted. */
9
+ export declare function scrubPageUrl(raw: string, redact: Redact): string;
10
+ /** A fetch's final URL for the model: a query value or fragment stays only where the requested URL has it; userinfo never does. */
11
+ export declare function scrubFetchedUrl(raw: string, requested: string, redact: Redact): string;
12
+ /** Every string inside `value`, object keys included, passed through `redact`. */
13
+ export declare function redactDeep<T>(value: T, redact: Redact): T;
@@ -0,0 +1,83 @@
1
+ import { fetchedSpellings } from "./uri.js";
2
+ const REDACTED = "[redacted]";
3
+ /** Scrubbing a shorter string everywhere would destroy the text around it, and no credential is that short. */
4
+ export const MIN_REDACTED_VALUE_LENGTH = 8;
5
+ const SHAPES = [
6
+ [/([?&](?:signingKey|api_?key|(?:access_)?token|key|jwt|signature)=)[^&#\s"'<>]+/gi, `$1${REDACTED}`],
7
+ // OpenAI-style secret keys, Browserbase live and test keys, Google API keys.
8
+ [/\b(sk-[A-Za-z0-9_-]{6})[A-Za-z0-9_-]+/g, `$1${REDACTED}`],
9
+ [/\b(bb_(?:live|test)_[A-Za-z0-9]{4})[A-Za-z0-9_-]+/g, `$1${REDACTED}`],
10
+ [/\bAIza[0-9A-Za-z_-]{30,}/g, `AIza${REDACTED}`],
11
+ [/\b(Bearer\s+)[A-Za-z0-9._~+/=-]{8,}/gi, `$1${REDACTED}`],
12
+ ];
13
+ /** `values()` is read at every call; each value is scrubbed raw, URL-encoded fully, and in every spelling web_fetch can
14
+ * send it in (fetchedSpellings), longest first. */
15
+ export function createRedactor(values = () => []) {
16
+ return (text) => {
17
+ const forms = new Set([...values()].filter((value) => typeof value === "string" && value.length >= MIN_REDACTED_VALUE_LENGTH).flatMap((value) => [value, encodeURIComponent(value), ...fetchedSpellings(value)]));
18
+ let out = text;
19
+ for (const form of [...forms].sort((a, b) => b.length - a.length))
20
+ out = out.split(form).join(REDACTED);
21
+ for (const [shape, replacement] of SHAPES)
22
+ out = out.replace(shape, replacement);
23
+ return out;
24
+ };
25
+ }
26
+ /** A credential can sit in any query value, the fragment or the userinfo, so every query value is replaced (names stay)
27
+ * and the fragment and userinfo are dropped before `redact` runs. A non-http(s) URL is only redacted. */
28
+ export function scrubPageUrl(raw, redact) {
29
+ let url;
30
+ try {
31
+ url = new URL(raw);
32
+ }
33
+ catch {
34
+ return redact(raw);
35
+ }
36
+ if (url.protocol !== "http:" && url.protocol !== "https:")
37
+ return redact(raw);
38
+ const names = [...new Set(url.searchParams.keys())];
39
+ return redact(`${url.origin}${url.pathname}${names.length ? `?${names.map((n) => `${encodeURIComponent(n)}=${REDACTED}`).join("&")}` : ""}`);
40
+ }
41
+ /** A fetch's final URL for the model: a query value or fragment stays only where the requested URL has it; userinfo never does. */
42
+ export function scrubFetchedUrl(raw, requested, redact) {
43
+ let url, asked;
44
+ try {
45
+ url = new URL(raw);
46
+ }
47
+ catch {
48
+ return redact(raw);
49
+ }
50
+ if (url.protocol !== "http:" && url.protocol !== "https:")
51
+ return redact(raw);
52
+ try {
53
+ asked = new URL(requested);
54
+ }
55
+ catch {
56
+ return scrubPageUrl(raw, redact);
57
+ }
58
+ const decoded = (text) => { try {
59
+ return decodeURIComponent(text.replace(/\+/g, " "));
60
+ }
61
+ catch {
62
+ return text;
63
+ } };
64
+ const pairsOf = (search) => search.slice(1).split("&").filter(Boolean).map((pair) => {
65
+ const at = pair.indexOf("=");
66
+ return at < 0 ? { pair, key: pair, value: "" } : { pair, key: pair.slice(0, at), value: pair.slice(at + 1) };
67
+ });
68
+ const sent = new Set(pairsOf(asked.search).map(({ key, value }) => `${decoded(key)}\0${decoded(value)}`));
69
+ const query = pairsOf(url.search).map(({ pair, key, value }) => (sent.has(`${decoded(key)}\0${decoded(value)}`) ? pair : `${key}=${REDACTED}`));
70
+ const fragment = url.hash && url.hash === asked.hash ? url.hash : "";
71
+ return redact(`${url.protocol}//${url.host}${url.pathname}${query.length ? `?${query.join("&")}` : ""}${fragment}`);
72
+ }
73
+ /** Every string inside `value`, object keys included, passed through `redact`. */
74
+ export function redactDeep(value, redact) {
75
+ if (typeof value === "string")
76
+ return redact(value);
77
+ if (Array.isArray(value))
78
+ return value.map((item) => redactDeep(item, redact));
79
+ if (value && typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype) {
80
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [redact(key), redactDeep(item, redact)]));
81
+ }
82
+ return value;
83
+ }
@@ -0,0 +1,25 @@
1
+ import type { BrowserPolicy } from "./host.js";
2
+ export declare const DEFAULT_BROWSER_POLICY: Readonly<BrowserPolicy>;
3
+ export declare const CREATE_DEADLINE_MS = 60000;
4
+ export type KeyedSerializer = {
5
+ run<T>(key: string, work: () => Promise<T>): Promise<T>;
6
+ keys(): string[];
7
+ };
8
+ export declare function keyedSerializer(): KeyedSerializer;
9
+ export type IdleTracker<K = string> = {
10
+ activity(key: K, delta: number, idleMs?: number): void;
11
+ /** True while `fired` is the key's current timer and nothing is in flight: only then may an idle release go ahead. */
12
+ isCurrent(key: K, fired: NodeJS.Timeout): boolean;
13
+ cancel(key: K): void;
14
+ /** Safe mid-call: a key with calls in flight goes when the last one ends, and no timer is armed after it. */
15
+ forget(key: K): void;
16
+ clear(): void;
17
+ keys(): K[];
18
+ };
19
+ export declare function idleTracker<K = string>(options: {
20
+ idleMs: number;
21
+ onIdle(key: K, fired: NodeJS.Timeout, idleMs: number): void;
22
+ }): IdleTracker<K>;
23
+ /** Every environment variable that holds a provider key: each redactor in either adapter scrubs their values. */
24
+ export declare const PROVIDER_KEY_ENV: readonly string[];
25
+ export declare const providerKeyValues: (env: NodeJS.ProcessEnv, host?: () => readonly string[]) => string[];
@@ -0,0 +1,75 @@
1
+ export const DEFAULT_BROWSER_POLICY = Object.freeze({
2
+ proxies: false, verified: false, captcha: false, geolocation: null, region: null, contextId: null, sessionTimeoutS: 1800, idleReleaseS: 180, batchTimeoutMs: 60_000,
3
+ });
4
+ export const CREATE_DEADLINE_MS = 60_000;
5
+ export function keyedSerializer() {
6
+ const tails = new Map();
7
+ return {
8
+ run(key, work) {
9
+ const turn = (tails.get(key) ?? Promise.resolve()).then(work, work);
10
+ const tail = turn.then(() => undefined, () => undefined);
11
+ tails.set(key, tail);
12
+ void tail.then(() => { if (tails.get(key) === tail)
13
+ tails.delete(key); });
14
+ return turn;
15
+ },
16
+ keys: () => [...tails.keys()],
17
+ };
18
+ }
19
+ export function idleTracker(options) {
20
+ const entries = new Map();
21
+ return {
22
+ activity(key, delta, idleMs) {
23
+ const entry = entries.get(key) ?? { inFlight: 0, idleMs: idleMs ?? options.idleMs };
24
+ if (entry.timer)
25
+ clearTimeout(entry.timer);
26
+ entry.timer = undefined;
27
+ entry.inFlight = Math.max(0, entry.inFlight + delta);
28
+ if (idleMs !== undefined)
29
+ entry.idleMs = idleMs;
30
+ if (entry.forgotten && entry.inFlight === 0) {
31
+ entries.delete(key);
32
+ return;
33
+ }
34
+ entries.set(key, entry);
35
+ if (entry.inFlight > 0 || !(entry.idleMs > 0))
36
+ return;
37
+ const timer = setTimeout(() => options.onIdle(key, timer, entry.idleMs), entry.idleMs);
38
+ entry.timer = timer;
39
+ timer.unref?.();
40
+ },
41
+ isCurrent(key, fired) {
42
+ const entry = entries.get(key);
43
+ return entry?.timer === fired && entry.inFlight === 0;
44
+ },
45
+ cancel(key) {
46
+ const entry = entries.get(key);
47
+ if (entry?.timer)
48
+ clearTimeout(entry.timer);
49
+ if (entry)
50
+ entry.timer = undefined;
51
+ },
52
+ forget(key) {
53
+ const entry = entries.get(key);
54
+ if (!entry)
55
+ return;
56
+ if (entry.timer)
57
+ clearTimeout(entry.timer);
58
+ entry.timer = undefined;
59
+ if (entry.inFlight === 0)
60
+ entries.delete(key);
61
+ else
62
+ entry.forgotten = true;
63
+ },
64
+ clear() {
65
+ for (const entry of entries.values())
66
+ if (entry.timer)
67
+ clearTimeout(entry.timer);
68
+ entries.clear();
69
+ },
70
+ keys: () => [...entries.keys()],
71
+ };
72
+ }
73
+ /** Every environment variable that holds a provider key: each redactor in either adapter scrubs their values. */
74
+ export const PROVIDER_KEY_ENV = Object.freeze(["BROWSERBASE_API_KEY", "BB_API_KEY", "KERNEL_API_KEY"]);
75
+ export const providerKeyValues = (env, host) => [...PROVIDER_KEY_ENV.map((name) => env[name] ?? "").filter(Boolean), ...(host?.() ?? [])];
@@ -0,0 +1,33 @@
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;
@@ -0,0 +1,102 @@
1
+ export const MAX_SITE_INSTRUCTIONS = 16_000;
2
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
3
+ const RUN_ID = /^[A-Za-z0-9_.:-]{1,200}$/;
4
+ const RUN_STATE = /^[a-z_]{1,40}$/;
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 function useWebsiteContract(sites) {
8
+ return {
9
+ name: "use_website",
10
+ label: "Use a website",
11
+ description: [
12
+ "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:",
13
+ ...sites.map((site) => `- ${site.site}: ${site.title}. ${site.description}`),
14
+ "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.",
15
+ ].join("\n"),
16
+ parameters: {
17
+ type: "object", additionalProperties: false, required: ["site", "request_id", "instructions"],
18
+ properties: {
19
+ site: { type: "string", enum: sites.map((site) => site.site), description: "The website to use." },
20
+ request_id: { type: "string", description: "A UUID you choose for this task." },
21
+ instructions: { type: "string", maxLength: MAX_SITE_INSTRUCTIONS, description: "What to do on the website and what to report back." },
22
+ },
23
+ },
24
+ effect: "effect", replay: "safe", executionMode: "sequential", evidence: "none", listedWhen: "sites",
25
+ };
26
+ }
27
+ /** Only the declared shape crosses back to the model: a port's extra fields, such as capabilities or URLs, are dropped
28
+ * here, and an answer with both shapes or neither is no answer. */
29
+ export function siteAnswer(raw) {
30
+ if (!raw || typeof raw !== "object")
31
+ return null;
32
+ const { run, report } = raw;
33
+ if ((run === undefined) === (report === undefined))
34
+ return null;
35
+ if (report !== undefined)
36
+ return typeof report === "string" ? { report } : null;
37
+ const { id, state } = (run ?? {});
38
+ return typeof id === "string" && RUN_ID.test(id) && typeof state === "string" && RUN_STATE.test(state) ? { run: { id, state } } : null;
39
+ }
40
+ const siteOutput = (body, isError = false) => ({ content: [{ type: "text", text: JSON.stringify(body) }], ...(isError ? { isError: true } : {}) });
41
+ const siteRefusal = (message) => siteOutput({ ok: false, code: "refused", retryable: false, effect: "none", message }, true);
42
+ export async function useWebsite(args, port, sites, ctx) {
43
+ const site = sites.find((known) => known.site === args.site);
44
+ if (!site)
45
+ return siteRefusal(`site is one of: ${sites.map((known) => known.site).join(", ")}`);
46
+ if (typeof args.request_id !== "string" || !UUID.test(args.request_id))
47
+ return siteRefusal("request_id is a UUID you choose for this task");
48
+ const instructions = typeof args.instructions === "string" ? args.instructions.trim() : "";
49
+ if (!instructions || instructions.length > MAX_SITE_INSTRUCTIONS)
50
+ return siteRefusal(`instructions say what to do on the site, in at most ${MAX_SITE_INSTRUCTIONS} characters`);
51
+ const head = { ok: true, site: site.site, request_id: args.request_id };
52
+ let raw;
53
+ try {
54
+ raw = await port.use({ site: site.site, requestId: args.request_id, instructions }, ctx);
55
+ }
56
+ catch {
57
+ // A port's error text can carry its grant or a URL: none of it is forwarded.
58
+ if (ctx.signal.aborted)
59
+ 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);
60
+ 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);
61
+ }
62
+ const parsed = siteAnswer(raw);
63
+ if (!parsed)
64
+ 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);
65
+ if ("report" in parsed)
66
+ return siteOutput({ ...head, report: parsed.report });
67
+ 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." });
68
+ }
69
+ const childPrompt = (site, entry, instructions) => [
70
+ `You are doing one task on ${entry.title} (${site}) for another agent, in your own browser.`,
71
+ `Start at ${entry.startUrl}.`,
72
+ `Task: ${instructions}`,
73
+ "Use the browser tools. Do not ask questions. Finish with a short report of what you found or did.",
74
+ ].join("\n");
75
+ /** `use_website` for a plain pi user: each task runs a child agent through the adapter's `runChild` and answers its
76
+ * report. A request_id runs once; a failed run may be asked again. */
77
+ export function localSites(sites) {
78
+ for (const [site, entry] of Object.entries(sites)) {
79
+ if (!/^https?:\/\//.test(entry.startUrl))
80
+ throw new Error(`site ${site}: startUrl must be an http or https URL`);
81
+ }
82
+ const runs = new Map();
83
+ return {
84
+ async list() {
85
+ return Object.entries(sites).map(([site, entry]) => ({ site, title: entry.title, description: entry.description }));
86
+ },
87
+ async use({ site, requestId, instructions }, { signal, runChild }) {
88
+ const entry = Object.hasOwn(sites, site) ? sites[site] : undefined;
89
+ if (!entry)
90
+ throw new Error(`no site named ${site}`);
91
+ const key = `${site}\u0000${requestId}`;
92
+ let run = runs.get(key);
93
+ if (!run) {
94
+ run = runChild({ site, requestId, prompt: childPrompt(site, entry, instructions) }, signal);
95
+ runs.set(key, run);
96
+ run.catch(() => { if (runs.get(key) === run)
97
+ runs.delete(key); });
98
+ }
99
+ return { report: await run };
100
+ },
101
+ };
102
+ }
@@ -0,0 +1,72 @@
1
+ import { type BrowserDriver, type CustodyPort, type ToolOutput } from "./custody.js";
2
+ import { type EvidenceSink } from "./evidence.js";
3
+ import type { Decisions } from "./decisions.js";
4
+ import { type RepeatGuard } from "./guard.js";
5
+ import { type ScreenshotOptions } from "./images.js";
6
+ import { type Redact } from "./redact.js";
7
+ import type { Geo } from "./host.js";
8
+ export type PageDriver = BrowserDriver & {
9
+ snapshot(options?: {
10
+ includeIframes?: boolean;
11
+ }): Promise<string>;
12
+ run(input: {
13
+ code?: string;
14
+ actions?: unknown[];
15
+ }): Promise<unknown>;
16
+ /** The page's URL, cheaply: no page content is read. */
17
+ url(): Promise<string>;
18
+ screenshot(options: ScreenshotOptions): Promise<{
19
+ data: string;
20
+ mimeType: string;
21
+ }>;
22
+ page(): Promise<{
23
+ url: string;
24
+ title: string;
25
+ text: string;
26
+ html: string;
27
+ }>;
28
+ };
29
+ export type ToolCall = {
30
+ callId: string;
31
+ conversationId: number;
32
+ signal: AbortSignal | undefined;
33
+ label: string;
34
+ redact: Redact;
35
+ evidence: EvidenceSink;
36
+ classifyPage?: Decisions["classifyPage"];
37
+ };
38
+ export type ToolImpl<D extends BrowserDriver = BrowserDriver, A = unknown> = (args: A, port: CustodyPort<D>, call: ToolCall) => Promise<ToolOutput>;
39
+ /** Each browser tool's arguments, as its contract's schema admits them. */
40
+ export type BrowserToolArgs = {
41
+ snapshot: {
42
+ includeIframes?: boolean;
43
+ };
44
+ run: {
45
+ code?: string;
46
+ actions?: unknown[];
47
+ };
48
+ screenshot: {
49
+ fullPage?: boolean;
50
+ type?: "png" | "jpeg";
51
+ quality?: number;
52
+ ask?: string;
53
+ };
54
+ browser_read: {
55
+ what?: (typeof WHATS)[number];
56
+ };
57
+ browser_release: Record<string, never>;
58
+ browser_relaunch: {
59
+ verified?: boolean;
60
+ geolocation?: Geo;
61
+ };
62
+ browser_downloads: Record<string, never>;
63
+ };
64
+ export type BrowserToolImpls<D extends BrowserDriver = BrowserDriver> = {
65
+ [K in keyof BrowserToolArgs]: ToolImpl<D, BrowserToolArgs[K]>;
66
+ };
67
+ declare const WHATS: readonly ["markdown", "text", "html", "url", "title"];
68
+ /** `guards` holds each conversation's repeat guard; a host that owns the conversation's lifecycle passes it to evict one. */
69
+ export declare function pageTools({ guards }?: {
70
+ guards?: Map<number, RepeatGuard>;
71
+ }): Pick<BrowserToolImpls<PageDriver>, "snapshot" | "run" | "screenshot" | "browser_read">;
72
+ export {};