@parcha/pi-browser 0.1.0-beta.23 → 0.1.0-beta.26

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 (48) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/README.md +15 -0
  3. package/dist/coding-agent-local.js +7 -6
  4. package/dist/coding-agent.js +25 -22
  5. package/dist/core/clip.js +2 -2
  6. package/dist/core/contract.d.ts +7 -0
  7. package/dist/core/contract.js +3 -0
  8. package/dist/core/custody.d.ts +9 -0
  9. package/dist/core/custody.js +22 -5
  10. package/dist/core/downloads.js +2 -2
  11. package/dist/core/driving.d.ts +6 -0
  12. package/dist/core/driving.js +8 -0
  13. package/dist/core/failures.d.ts +10 -0
  14. package/dist/core/failures.js +22 -15
  15. package/dist/core/host.d.ts +6 -0
  16. package/dist/core/redact.d.ts +5 -0
  17. package/dist/core/redact.js +4 -0
  18. package/dist/core/sites.js +2 -1
  19. package/dist/core/tools.js +7 -8
  20. package/dist/core/web.d.ts +1 -6
  21. package/dist/core/web.js +8 -4
  22. package/dist/driver/extension-worker.js +149 -118
  23. package/dist/driver/sealed.d.ts +16 -0
  24. package/dist/driver/sealed.js +47 -0
  25. package/dist/driver/stagehand.js +7 -43
  26. package/dist/durable/journal.d.ts +31 -0
  27. package/dist/durable/journal.js +105 -0
  28. package/dist/{durable-result.d.ts → durable/result.d.ts} +1 -1
  29. package/dist/{store.d.ts → durable/store.d.ts} +2 -2
  30. package/dist/{store.js → durable/store.js} +1 -1
  31. package/dist/{web.d.ts → durable/web.d.ts} +4 -4
  32. package/dist/{web.js → durable/web.js} +5 -5
  33. package/dist/durable.d.ts +2 -2
  34. package/dist/durable.js +39 -131
  35. package/dist/providers/assigned.js +2 -3
  36. package/dist/providers/browserbase.js +5 -4
  37. package/dist/providers/cdp.js +7 -36
  38. package/dist/providers/chrome-args.d.ts +18 -0
  39. package/dist/providers/chrome-args.js +66 -0
  40. package/dist/providers/http.d.ts +4 -1
  41. package/dist/providers/http.js +5 -8
  42. package/dist/providers/kernel.d.ts +10 -1
  43. package/dist/providers/kernel.js +1 -1
  44. package/dist/providers/profiles.js +6 -6
  45. package/dist/providers/shared.d.ts +9 -0
  46. package/dist/providers/shared.js +5 -1
  47. package/package.json +7 -3
  48. /package/dist/{durable-result.js → durable/result.js} +0 -0
@@ -0,0 +1,66 @@
1
+ // The arguments the cdp provider starts a local Chrome with, in one place, so a host that starts its own Chrome for Stagehand can
2
+ // take the same list rather than copy it.
3
+ import { createHash } from "node:crypto";
4
+ import { realpathSync } from "node:fs";
5
+ import path from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import { BrowserFailureError } from "../core/custody.js";
8
+ import { browserFailure } from "../core/failures.js";
9
+ import { nonEmpty } from "./shared.js";
10
+ /** Stagehand 4.1.0's DEFAULT_CHROME_FLAGS (packages/sdk-ts/src/browser/localBrowser.ts, MIT, see NOTICE), less its
11
+ * `--remote-allow-origins=*`, which the launch below narrows to the extension's own Origin. Without them
12
+ * Stagehand.create takes about 24 s on a local Chrome instead of under 100 ms. */
13
+ const CHROME_FLAGS = [
14
+ "--disable-features=Translate,OptimizationHints,MediaRouter,DialMediaRouteProvider,CalculateNativeWinOcclusion,InterestFeedContentSuggestions,CertificateTransparencyComponentUpdater,AutofillServerCommunication,PrivacySandboxSettings4,RenderDocument",
15
+ "--disable-component-extensions-with-background-pages",
16
+ "--disable-background-networking",
17
+ "--disable-component-update",
18
+ "--disable-client-side-phishing-detection",
19
+ "--disable-sync",
20
+ "--metrics-recording-only",
21
+ "--disable-default-apps",
22
+ "--mute-audio",
23
+ "--no-default-browser-check",
24
+ "--no-first-run",
25
+ "--disable-backgrounding-occluded-windows",
26
+ "--disable-renderer-backgrounding",
27
+ "--disable-background-timer-throttling",
28
+ "--disable-ipc-flooding-protection",
29
+ "--password-store=basic",
30
+ "--use-mock-keychain",
31
+ "--force-fieldtrials=*BackgroundTracing/default/",
32
+ "--disable-hang-monitor",
33
+ "--disable-prompt-on-repost",
34
+ "--disable-domain-reliability",
35
+ "--propagate-iph-for-testing",
36
+ "--enable-unsafe-extension-debugging",
37
+ "--enable-features=WebMCPTesting,DevToolsWebMCPSupport",
38
+ ];
39
+ /** The directory Stagehand loads its extension from in a local Chrome (`Extensions.loadUnpacked`), resolved as Stagehand does. */
40
+ export function extensionDirectory() {
41
+ return nonEmpty(process.env.STAGEHAND_EXTENSION_DIRECTORY_PATH) || path.join(path.dirname(fileURLToPath(import.meta.resolve("@browserbasehq/stagehand"))), "extension");
42
+ }
43
+ /** The Origin the extension's own DevTools socket carries. Chrome names an unpacked extension by the SHA-256 of its real path: the
44
+ * first 32 hex digits, each written as a letter a to p. A directory that cannot be resolved refuses the launch: the socket is never
45
+ * opened to every Origin instead. */
46
+ export function extensionOrigin(directory = extensionDirectory()) {
47
+ let real;
48
+ try {
49
+ real = realpathSync(directory);
50
+ }
51
+ catch (error) {
52
+ throw new BrowserFailureError(browserFailure("browser_unavailable", `Stagehand's extension directory ${directory} cannot be resolved (${error.code ?? "unreadable"}), so the browser's DevTools socket cannot be limited to the extension's Origin; no browser was started.`));
53
+ }
54
+ const hex = createHash("sha256").update(real).digest("hex").slice(0, 32);
55
+ return `chrome-extension://${[...hex].map((digit) => String.fromCharCode(97 + parseInt(digit, 16))).join("")}`;
56
+ }
57
+ /** Every argument a local Chrome is started with, but the page to open. The DevTools socket is the whole browser: Stagehand's own
58
+ * launcher allows every Origin (`*`), so a page the agent visits could drive the browser if it learned the socket's URL. Only the
59
+ * extension's socket carries an Origin (Node's clients send none), so only that Origin is allowed. */
60
+ export function chromeArgs(options) {
61
+ return [
62
+ ...CHROME_FLAGS, ...(options.sandbox ? [] : ["--no-sandbox"]), ...(options.headless ? ["--headless=new"] : []),
63
+ "--remote-debugging-port=0", "--remote-debugging-address=127.0.0.1", `--remote-allow-origins=${extensionOrigin()}`,
64
+ `--user-data-dir=${options.userDataDir}`, `--window-size=${options.viewport.width},${options.viewport.height}`,
65
+ ];
66
+ }
@@ -1,2 +1,5 @@
1
- export declare function directFetch(): Promise<((input: any, init?: any) => Promise<any>) | undefined>;
1
+ import type * as Undici from "undici";
2
+ /** fetch over the package's own undici agent: direct, never through the HTTP(S) env proxy. undici is a dependency, so a load that
3
+ * fails is a broken install and throws; there is no fallback to the global fetch, which would follow the proxy. */
4
+ export declare function directFetch(): Promise<typeof Undici.fetch>;
2
5
  export declare function closeDirectFetch(): Promise<void>;
@@ -4,15 +4,12 @@ let undiciModule;
4
4
  /** Loaded on first use, so a process that never reaches a provider never loads undici. */
5
5
  const undiciDoor = () => (undiciModule ??= require("undici"));
6
6
  let directAgent;
7
+ /** fetch over the package's own undici agent: direct, never through the HTTP(S) env proxy. undici is a dependency, so a load that
8
+ * fails is a broken install and throws; there is no fallback to the global fetch, which would follow the proxy. */
7
9
  export async function directFetch() {
8
- try {
9
- const undici = undiciDoor();
10
- // Userland undici refuses a request body it must stream (the extension upload's multipart file) without `duplex`.
11
- return (input, init = {}) => undici.fetch(input, { ...init, dispatcher: (directAgent ??= new undici.Agent()), ...(init.body ? { duplex: "half" } : {}) });
12
- }
13
- catch {
14
- return undefined;
15
- }
10
+ const undici = undiciDoor();
11
+ // Userland undici refuses a request body it must stream (the extension upload's multipart file) without `duplex`.
12
+ return (input, init = {}) => undici.fetch(input, { ...init, dispatcher: (directAgent ??= new undici.Agent()), ...(init.body ? { duplex: "half" } : {}) });
16
13
  }
17
14
  export async function closeDirectFetch() {
18
15
  const agent = directAgent;
@@ -2,12 +2,21 @@ import type { BrowserProvider, SessionSpec } from "../core/host.js";
2
2
  export declare const KERNEL_BASE_URL = "https://api.onkernel.com";
3
3
  export declare const KERNEL_IDLE_MIN_S = 10;
4
4
  export declare const KERNEL_IDLE_MAX_S = 259200;
5
+ /** What the provider reads of a reply: the global fetch's Response and undici's both have it. */
6
+ type HttpReply = {
7
+ ok: boolean;
8
+ status: number;
9
+ headers: {
10
+ get(name: string): string | null;
11
+ };
12
+ text(): Promise<string>;
13
+ };
5
14
  type HttpFetch = (input: string, init: {
6
15
  method: string;
7
16
  headers: Record<string, string>;
8
17
  body?: Uint8Array | string;
9
18
  signal?: AbortSignal;
10
- }) => Promise<Response>;
19
+ }) => Promise<HttpReply>;
11
20
  export type KernelOptions = {
12
21
  /** KERNEL_API_KEY and KERNEL_BASE_URL (default https://api.onkernel.com). Default: process.env. */
13
22
  env?: NodeJS.ProcessEnv;
@@ -46,7 +46,7 @@ export function kernelProvider(options = {}) {
46
46
  const sleep = options.sleep ?? defaultSleep;
47
47
  const confirm = options.confirm ?? DEFAULT_CONFIRM;
48
48
  let client = null;
49
- const http = () => (client ??= options.fetch ? Promise.resolve(options.fetch) : directFetch().then((f) => (f ?? fetch)));
49
+ const http = () => (client ??= options.fetch ? Promise.resolve(options.fetch) : directFetch());
50
50
  /** One request, never retried: a create served twice would be a second paid browser. On failure only Kernel's `code`
51
51
  * survives; a transport failure keeps its cause chain under a message that names the call alone. */
52
52
  async function call(method, route, init = {}) {
@@ -2,12 +2,12 @@ import { randomBytes } from "node:crypto";
2
2
  import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
3
3
  import os from "node:os";
4
4
  import path from "node:path";
5
- import { BrowserFailureError } from "../core/custody.js";
5
+ import { refusedError } from "../core/custody.js";
6
6
  import { withLock } from "../core/downloads.js";
7
- const writers = new Map();
7
+ import { profileHoldings } from "./shared.js";
8
+ const writers = profileHoldings.writers;
8
9
  const WAIT_MS = 20_000;
9
10
  const PROBE_MS = 2_000;
10
- const refusal = (message) => new BrowserFailureError({ ok: false, code: "refused", retryable: false, effect: "none", message });
11
11
  /** True when `work` finishes within `ms`; false at the deadline; rejects when `signal` aborts, leaving `work` to finish alone. */
12
12
  async function waitFor(work, signal, ms) {
13
13
  let timer;
@@ -43,15 +43,15 @@ export async function claimWriter(key, name, tag, owner, signal) {
43
43
  }
44
44
  if (held.running && !(await held.running(AbortSignal.any([...(signal ? [signal] : []), AbortSignal.timeout(PROBE_MS)])).catch(() => true))) {
45
45
  if (held.settle && !(await waitFor(held.settle(), signal, end - Date.now())))
46
- throw refusal(`browser profile "${name}": the session that was saving to it is still ending. Try again in a moment. No session was started.`);
46
+ throw refusedError(`browser profile "${name}": the session that was saving to it is still ending. Try again in a moment. No session was started.`);
47
47
  if (writers.get(key) === held)
48
48
  writers.delete(key);
49
49
  continue;
50
50
  }
51
51
  if (held.owner !== owner)
52
- throw refusal(`browser profile "${name}": one session at a time may save to a profile, and another session is saving to it now. Wait for it to end, or start without saving. No session was started.`);
52
+ throw refusedError(`browser profile "${name}": one session at a time may save to a profile, and another session is saving to it now. Wait for it to end, or start without saving. No session was started.`);
53
53
  if (Date.now() > end)
54
- throw refusal(`browser profile "${name}": the session that was saving to it is still ending. Try again in a moment. No session was started.`);
54
+ throw refusedError(`browser profile "${name}": the session that was saving to it is still ending. Try again in a moment. No session was started.`);
55
55
  signal?.throwIfAborted();
56
56
  await new Promise((resolve) => setTimeout(resolve, 100));
57
57
  }
@@ -44,4 +44,13 @@ export declare const kernelHoldings: {
44
44
  name: string;
45
45
  }>>;
46
46
  };
47
+ /** Which session may save to a named profile now, by profile: claimed by both cloud providers (providers/profiles.ts). */
48
+ export declare const profileHoldings: {
49
+ writers: Map<string, {
50
+ tag: string;
51
+ owner: string;
52
+ running?: (signal: AbortSignal) => Promise<boolean>;
53
+ settle?: () => Promise<void>;
54
+ }>;
55
+ };
47
56
  export declare function resetProviderHoldings(): void;
@@ -75,8 +75,12 @@ export const kernelHoldings = {
75
75
  liveUrls: new Map(),
76
76
  uploads: new Map(),
77
77
  };
78
+ /** Which session may save to a named profile now, by profile: claimed by both cloud providers (providers/profiles.ts). */
79
+ export const profileHoldings = {
80
+ writers: new Map(),
81
+ };
78
82
  export function resetProviderHoldings() {
79
- for (const holdings of [browserbaseHoldings, kernelHoldings])
83
+ for (const holdings of [browserbaseHoldings, kernelHoldings, profileHoldings])
80
84
  for (const map of Object.values(holdings))
81
85
  map.clear();
82
86
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@parcha/pi-browser",
3
- "version": "0.1.0-beta.23",
3
+ "version": "0.1.0-beta.26",
4
4
  "description": "Your agent gets its own browser, and you can take over and hand it back.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -40,6 +40,10 @@
40
40
  "types": "./dist/providers/cdp.d.ts",
41
41
  "import": "./dist/providers/cdp.js"
42
42
  },
43
+ "./providers/chrome-args": {
44
+ "types": "./dist/providers/chrome-args.d.ts",
45
+ "import": "./dist/providers/chrome-args.js"
46
+ },
43
47
  "./providers/assigned": {
44
48
  "types": "./dist/providers/assigned.d.ts",
45
49
  "import": "./dist/providers/assigned.js"
@@ -87,8 +91,8 @@
87
91
  "@browserbasehq/stagehand": "~4.1.0",
88
92
  "node-html-markdown": "^2.0.0",
89
93
  "node-html-parser": "^6.1.13",
90
- "undici": "^6.28.0",
91
- "zod": "~4.4.3"
94
+ "undici": "^6.29.1",
95
+ "zod": "~4.6.6"
92
96
  },
93
97
  "peerDependencies": {
94
98
  "@browserbasehq/sdk": ">=2.20.0 <3",
File without changes