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

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 CHANGED
@@ -2,6 +2,12 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 0.1.0-beta.23 (2026-10-22)
6
+
7
+ - `@parcha/pi-browser`: a Chrome that exits before it opens its debugging port now fails the create with the last ten lines it wrote to stderr (a partial first line dropped, each whole line redacted for the common key shapes and then shortened, control characters dropped). When the sandbox is on and Chrome aborted or named the sandbox, the failure is the typed `browser_unavailable` and says to set `sandbox: false` or `PI_BROWSER_NO_SANDBOX=1`; before, only a SIGABRT said so, and Debian's Chromium in a container exited 1 and gave only its exit code. Chrome's stderr is a file in the lease's private directory, emptied once the port is open and whenever it passes 256 KB. A tail window with no newline in it shows nothing, a Chrome a restarted host recovers through `attach` has its file bounded the same way, and a launch whose `spawn` throws closes the file and removes the lease's private directory instead of leaking both. The README's Quick start names the container setting and `--init`, documents the local Chrome's options including `sandbox`, and creates its session inside the `try`, so a failed create leaves no profile root; its pi range now reads 1.1 to 1.3. The pi coding agent's untyped tool errors reach the model redacted: a failure that was not a typed browser failure (a workspace read that fails before `browser_upload`'s own handling, for one) used to be rethrown with its raw message, so a registered key in it reached the model and the session file; every failure now comes back typed and redacted. A handoff gives the host the browsed page's URL with its query and fragment scrubbed and its title redacted, as `onSession` always did; the viewer's own URL stays whole there, since the host needs its token.
8
+ - `@parcha/pi-browser`: the README's Quick start names the container setting (`PI_BROWSER_NO_SANDBOX=1`, or `sandbox: false`, and `--init` so a killed Chrome is reaped), documents the local Chrome's options including `sandbox`, and creates its session inside the `try`, so a failed create leaves no profile root. The entries list names `/providers/assigned` and `/recorder`, and says the core loads the two HTML packages on demand. Doc comments in the source sit on the declaration they describe, and the live view's docs name both host channels that receive the viewer URL.
9
+ - `@parcha/pi-browser`: the README's Install block has a line for a pi-durable host that pins `@earendil-works/pi-durable`, `chord` and `pi-ai` to 1.3.0, and says pi 1.4 is not supported yet. pi 1.4.0 is npm's latest and the peer range stops below it, so the same names unpinned stop `npm install` with ERESOLVE. The first screen's pi range reads 1.1 to 1.3, the range of the peers.
10
+
5
11
  ## 0.1.0-beta.19 (2026-10-20)
6
12
 
7
13
  - `@parcha/pi-browser`: a live view for the cdp provider, from the new `@parcha/pi-browser/live-view` export. `createLiveView` serves a viewer page and a loopback WebSocket for one person at a time: the first message must be the hello with the session's token, a wrong or missing token, a bad Origin or a second viewer is refused, the screencast frames are never written anywhere, the viewer says it is connecting and refuses input out loud until it is ready, and the view ends when the session is released. `liveViewProvider` wraps the cdp provider and reports the viewer's URL to `onSession` and nowhere else. While a person drives the viewer, every browser tool call (and `browser_release` and `browser_relaunch`) is refused with a typed, retryable `person_driving` before it does anything, the person's input is discarded while the agent acts (one shared gate per session, `drivingGates`), and an idle window never releases a session a person drives or watches. Custody can hold a session for a person behind a per-session fence: `CustodyPort` gains `current()`, a page action the fence stopped before any driver call got through is settled as not sent, and a held session the provider ended no longer holds up the conversation. `FrameRecorderOptions.hold` keeps a person-driven session out of the recording (one `frame.gap` marks the span), and when a hold lifts one frame is captured on demand so the replay does not end at the hold. `RunAction` types the actions of `run` per op. `browser_upload` runs behind a `WorkspaceFiles` port (it refuses swapped parents, pipes and host-private files, and is journaled like a run), `browser_downloads` works, and a `use_website` child is offered neither. A site child's browser can be the session the host reserved for it: the new `@parcha/pi-browser/providers/assigned` export never creates or ends a browser, takes its assigned session as the run's only browser, and is never relaunched or idled away. A screenshot's result carries the captured image's own facts in `details.media` (`kind`, `path`, `mime`, `bytes`, `width`, `height`, `ask`), and a screenshot can capture one region, by clip, snapshot id or CSS selector. The index exports custody's vocabulary, and a session's record and `relaunch`'s answer say the settings the provider applied. `browser_request_handoff` hands the browser to a person for a step only a human can do, such as a 2FA or a captcha, and waits durably for the host's answer. It is listed only when the host gives a `HandoffPort`, a rerun never asks again once the answer is kept, `done`, `cancelled` or `expired` give the session back under a new fence, and every other call answers `waiting_for_human` meanwhile. A refusal from the port, or a failure before it answers, gives the session straight back.
package/README.md CHANGED
@@ -10,8 +10,8 @@ Your agent gets its own browser, and you can take over and hand it back.
10
10
 
11
11
  If the process dies, a pi-durable host recovers the session and does not repeat an action. See [For hosts](#for-hosts).
12
12
 
13
- Part of [AgentRun](https://github.com/Parcha-ai/agentrun). Node `>=22.19.0`, pi 1.1 and 1.2 (the
14
- coding-agent entry also runs on pi 1.0.4). ESM only: the
13
+ Part of [AgentRun](https://github.com/Parcha-ai/agentrun). Node `>=22.19.0`, pi 1.1 to 1.3 (the range of its
14
+ pi-durable and chord peers; the coding-agent entry also runs on pi 1.0.4). ESM only: the
15
15
  package has `import` entries and no `require` entry.
16
16
 
17
17
  ## Install
@@ -19,13 +19,14 @@ package has `import` entries and no `require` entry.
19
19
  ```sh
20
20
  pi install npm:@parcha/pi-browser@beta # the pi coding agent's extension
21
21
  npm install @parcha/pi-browser@beta # the library: providers, driver, durable adapter
22
+ npm install @parcha/pi-browser@beta @earendil-works/pi-durable@1.3.0 @earendil-works/chord@1.3.0 @earendil-works/pi-ai@1.3.0 # a pi-durable host: its peers, pinned to 1.3.0 (unpinned, npm takes 1.4.0 and stops with ERESOLVE)
22
23
  ```
23
24
 
24
- `pi install` loads the extension. A Chrome starts on the model's first browser call, and not before.
25
+ `pi install` loads the extension. A Chrome starts on the model's first browser call, and not before. pi 1.4 is not supported yet; a later release widens the range.
25
26
 
26
27
  ## Quick start
27
28
 
28
- A local Chrome, one page, one snapshot. It needs Chrome or Chromium; `CHROME_PATH` names it.
29
+ A local Chrome, one page, one snapshot. It needs Chrome or Chromium; `CHROME_PATH` names it. As root or in a container, Chrome cannot start its sandbox: set `PI_BROWSER_NO_SANDBOX=1`, or pass `sandbox: false` beside `executablePath`, and run the container with `--init`, or a Chrome killed on cleanup stays a zombie.
29
30
 
30
31
  ```js
31
32
  import { mkdtemp, rm } from "node:fs/promises";
@@ -37,14 +38,15 @@ import { stagehandDriver } from "@parcha/pi-browser/driver/stagehand";
37
38
  const profileRoot = await mkdtemp(join(tmpdir(), "pi-browser-"));
38
39
  const provider = cdpProvider({ chrome: { executablePath: process.env.CHROME_PATH ?? "/usr/bin/google-chrome", profileRoot } });
39
40
  const signal = AbortSignal.timeout(60_000);
40
- const session = await provider.create({ tag: "quick-start", maxLifetimeS: 600, idleTimeoutS: 60, proxies: false, verified: false, captcha: false, viewport: { width: 1000, height: 700 }, metadata: {} }, signal);
41
+ let session;
41
42
  try {
43
+ session = await provider.create({ tag: "quick-start", maxLifetimeS: 600, idleTimeoutS: 60, proxies: false, verified: false, captcha: false, viewport: { width: 1000, height: 700 }, metadata: {} }, signal);
42
44
  const driver = await stagehandDriver()(await provider.attach(session), signal);
43
45
  await driver.run({ code: `await page.goto(${JSON.stringify(process.argv[2] ?? "https://example.com")})` });
44
46
  console.log(await driver.snapshot());
45
47
  await driver.close();
46
48
  } finally {
47
- await provider.release(session);
49
+ if (session) await provider.release(session);
48
50
  await rm(profileRoot, { recursive: true, force: true });
49
51
  }
50
52
  ```
@@ -96,6 +98,15 @@ The same tools run on three kinds of browser. You pick one when you set up the p
96
98
  | Browserbase (`/providers/browserbase`) | A Browserbase session, through its SDK. | `BROWSERBASE_API_KEY` and the `@browserbasehq/sdk` peer. |
97
99
  | Kernel (`/providers/kernel`) | A Kernel browser, through its REST API. | `KERNEL_API_KEY`. No SDK. |
98
100
 
101
+ The local Chrome's options, in `cdpProvider({ chrome: { ... } })`:
102
+
103
+ | Option | Meaning |
104
+ |---|---|
105
+ | `executablePath`, `profileRoot` | The Chrome to start, and the directory its profiles live under. Both are required. |
106
+ | `headless` | `true` by default; `false` shows the window. |
107
+ | `args` | Extra Chrome flags, added after the package's own. |
108
+ | `sandbox` | Chrome's own sandbox, on unless `false`. When absent, `PI_BROWSER_NO_SANDBOX=1` turns it off. Turn it off only where Chrome cannot start its sandbox (root, a container, restricted user namespaces), and only for pages you trust. A Chrome that exits before it opens its debugging port fails the create with its last lines of stderr, and with this hint when it aborted or named the sandbox. |
109
+
99
110
  The pi extension picks one from a flag or an environment variable; see [For pi users](#for-pi-users). A host that wires the package itself passes the provider it wants; see [For hosts](#for-hosts). `examples/one-script-three-providers.mjs` runs one script on all three.
100
111
 
101
112
  ## Take over and hand back
@@ -243,7 +254,8 @@ pi 1.0.4 or 1.1.x users: pin `@earendil-works/pi-codemode` to the same version a
243
254
  - `@parcha/pi-browser`: the host-neutral core. The model contract (tool names, descriptions, JSON schemas, effect and
244
255
  replay classes, the `browser` and `web` prompt sections), the typed failure envelope, the redactor, the screenshot
245
256
  budget, the repeat guard, evidence and decision-hook types, usage and prices, `find` (chunking and ranking a long page),
246
- `browser_downloads`, the opt-in request observer, and the provider interface. It imports nothing outside Node's builtins.
257
+ `browser_downloads`, the opt-in request observer, and the provider interface. Outside Node's builtins it loads only
258
+ node-html-parser and node-html-markdown, on demand, for `browser_read`'s page text and frame scan.
247
259
  - `/durable`: the pi-durable adapter. `createBrowserExtension` is session custody in the run's own store (a create is
248
260
  committed before the provider is called, release is a durable task, reconcile runs at run open). `createWebExtension` is
249
261
  `web_fetch` and `web_search`.
@@ -255,8 +267,12 @@ pi 1.0.4 or 1.1.x users: pin `@earendil-works/pi-codemode` to the same version a
255
267
  - `/providers/browserbase`, `/providers/kernel`, `/providers/cdp`: where browsers come from. Browserbase through its SDK,
256
268
  with the credential-proxy dial and the connect-URL rewrite. Kernel through its REST API on the package's own HTTP agent.
257
269
  Any CDP endpoint, or a local Chrome the provider starts and kills by exact pid.
270
+ - `/providers/assigned`: `assignedSessionProvider()`, over the one session a host assigned to the run. It never creates or
271
+ ends a browser: it hands that session to one custody at a time, and the host takes it back itself.
258
272
  - `/live-view`: a person sees and drives the local Chrome (the cdp provider) from your page, with nothing leaving the machine but the model. See
259
273
  [The live view of your own Chrome](#the-live-view-of-your-own-chrome).
274
+ - `/recorder`: `frameRecorder()` screencasts each session over DevTools into a sink you pass, and `exportFrameTracks()`
275
+ makes a WebM per session from the recorded frames. See [Recording what the browsers show](#recording-what-the-browsers-show).
260
276
  - `/testing`: the shared test fake. A provider backend with a ledger of every call, a credential broker, an HTTP face so the
261
277
  ledger outlives a killed child process, a driver over in-memory pages, and sentinel credentials. A host's composition
262
278
  test and this package's crash matrix use the same one.
@@ -9,7 +9,7 @@ import { BrowserFailureError, closeDriver, custodyTools, FIXED_SESSION_RELAUNCH,
9
9
  import { browserFailure, classifyBrowserError } from "./core/failures.js";
10
10
  import { workspaceFiles } from "./core/files.js";
11
11
  import { leaseTag } from "./core/lease.js";
12
- import { createRedactor, redactDeep, scrubPageUrl } from "./core/redact.js";
12
+ import { createRedactor, hostLiveView, redactDeep, scrubPageUrl } from "./core/redact.js";
13
13
  import { useWebsite, useWebsiteContract } from "./core/sites.js";
14
14
  import { drivingGuarded } from "./core/driving-guard.js";
15
15
  import { drivingGates, keptFor, personOn, rearmWhenLeft } from "./core/driving.js";
@@ -332,7 +332,8 @@ export class LocalCustody {
332
332
  const stop = signal ? AbortSignal.any([this.d.signal, signal]) : this.d.signal;
333
333
  try {
334
334
  const provider = await this.d.provider();
335
- const liveView = provider.liveView ? await provider.liveView({ id: sessionId, tag }).catch(() => null) : null;
335
+ const view = provider.liveView ? await provider.liveView({ id: sessionId, tag }).catch(() => null) : null;
336
+ const liveView = view && hostLiveView(view, this.d.redact);
336
337
  const asked = await port.request({ requestId: ask.requestId, sessionTag: tag, sessionId, liveView, instruction: ask.instruction, completionCondition: ask.completionCondition }, stop);
337
338
  if ("refused" in asked)
338
339
  return asked;
@@ -439,11 +440,11 @@ async function openRuntime(pi, settings, ctx, reason, listSites) {
439
440
  return await impl(args, custody, call);
440
441
  }
441
442
  catch (error) {
442
- // A typed failure thrown before the tool's own handling (the driving guard refuses a release or relaunch for a person who is driving before the tool runs) comes
443
- // back as the envelope the durable adapter gives, so the model reads its code and `retryable`; other errors keep their path.
444
- if (error instanceof BrowserFailureError)
445
- return { content: [{ type: "text", text: JSON.stringify(error.failure) }], isError: true };
446
- throw error;
443
+ // A throw would reach the model as its raw message, unredacted (pi shows a tool's error text): every failure comes back as the typed envelope the durable
444
+ // adapter gives, redacted, so the model reads its code and `retryable`. A typed one is thrown before the tool's own handling (the driving guard refuses a
445
+ // release or relaunch for a person who is driving before the tool runs); any other is classified here.
446
+ const typed = error instanceof BrowserFailureError ? error.failure : classifyBrowserError(error, [...BROWSER_TOOLS, ...WEB_TOOLS].find((contract) => contract.name === tool)?.effect === "effect", { aborted: signal?.aborted === true, redact });
447
+ return { content: [{ type: "text", text: JSON.stringify(typed) }], isError: true };
447
448
  }
448
449
  finally {
449
450
  custody.activity(-1);
@@ -51,8 +51,8 @@ export interface CustodyPort<D extends BrowserDriver = BrowserDriver> {
51
51
  session(signal?: AbortSignal): Promise<AttachedSession<D>>;
52
52
  /** A rerun finds the session it launched. */
53
53
  relaunch(overrides: Overrides): Promise<AttachedSession<D>>;
54
- /** No session, or one already released, is not an error. */
55
- /** `ended`: the session was released, or is being released, before this call: by what and when (null while in flight). */
54
+ /** No session, or one already released, is not an error.
55
+ * `ended`: the session was released, or is being released, before this call: by what and when (null while in flight). */
56
56
  release(): Promise<{
57
57
  released: boolean;
58
58
  sessionId: string | null;
@@ -175,10 +175,10 @@ export declare function moveRecord(record: SessionRecord, next: {
175
175
  export declare const PROFILE_NAME: RegExp;
176
176
  export declare function sessionSpec(config: BrowserConfig, tag: string, overrides?: Overrides): SessionSpec;
177
177
  export declare function profileRefusal(spec: SessionSpec, caps: ProviderCaps): BrowserFailure | null;
178
- /** With proxies off a geolocation is refused up front: the session would browse from the provider's default place,
179
- * silently. */
180
178
  /** browser_relaunch on a provider whose session the host assigned: nothing to relaunch onto, and nothing released. */
181
179
  export declare const FIXED_SESSION_RELAUNCH: BrowserFailure;
180
+ /** With proxies off a geolocation is refused up front: the session would browse from the provider's default place,
181
+ * silently. */
182
182
  export declare function relaunchRefusal(policy: BrowserConfig["policy"], overrides: Overrides): BrowserFailure | null;
183
183
  /** An ISO alpha-2 country, a US state abbreviation, a city in capitals; null when the country is not two letters. */
184
184
  export declare function normalizeGeolocation(raw: unknown): Geo | null;
@@ -123,10 +123,10 @@ export function sessionSpec(config, tag, overrides = {}) {
123
123
  export function profileRefusal(spec, caps) {
124
124
  return spec.profile && !caps.profiles ? refused(`browser profile: this browser provider cannot keep a saved sign-in, so profile "${spec.profile.name}" cannot be used. No session was started.`) : null;
125
125
  }
126
- /** With proxies off a geolocation is refused up front: the session would browse from the provider's default place,
127
- * silently. */
128
126
  /** browser_relaunch on a provider whose session the host assigned: nothing to relaunch onto, and nothing released. */
129
127
  export const FIXED_SESSION_RELAUNCH = Object.freeze({ ok: false, code: "refused", retryable: false, effect: "none", message: "browser_relaunch: this task's browser is the one session its host assigned it, and there is no other to relaunch onto. Nothing was relaunched and your session is unchanged; keep using it." });
128
+ /** With proxies off a geolocation is refused up front: the session would browse from the provider's default place,
129
+ * silently. */
130
130
  export function relaunchRefusal(policy, overrides) {
131
131
  if (!overrides.geolocation || policy.proxies)
132
132
  return null;
@@ -14,14 +14,14 @@ export declare const browserFailure: (code: FailureCode, message: string, option
14
14
  effect?: BrowserFailure["effect"];
15
15
  detail?: string;
16
16
  }) => BrowserFailure;
17
- /** `timedOut`: the call ran to the driver's batch deadline, which Stagehand reports as a plain Error. */
18
- /** `action`: what an effectful call ran, named when it threw; "Your browser code" when unset. */
19
- /** `redact` removes the run's registered values from the error text; it runs over the whole text before any cut below, so no fragment of a value survives a cut point. */
20
17
  export type FailureFacts = {
21
18
  sessionEnded?: boolean;
22
19
  aborted?: boolean;
20
+ /** The call ran to the driver's batch deadline, which Stagehand reports as a plain Error. */
23
21
  timedOut?: boolean;
22
+ /** What an effectful call ran, named when it threw; "Your browser code" when unset. */
24
23
  action?: string;
24
+ /** Removes the run's registered values from the error text; it runs over the whole text before any cut below, so no fragment of a value survives a cut point. */
25
25
  redact?: (text: string) => string;
26
26
  };
27
27
  export declare const NO_HYDRATED_SNAPSHOT_ERROR = "No hydrated snapshot exists for the active page; call snapshot first.";
@@ -1,3 +1,4 @@
1
+ import type { LiveView } from "./host.js";
1
2
  export type Redact = (text: string) => string;
2
3
  /** Scrubbing a shorter string everywhere would destroy the text around it, and no credential is that short. */
3
4
  export declare const MIN_REDACTED_VALUE_LENGTH = 8;
@@ -7,6 +8,9 @@ export declare function createRedactor(values?: () => readonly string[]): Redact
7
8
  /** A credential can sit in any query value, the fragment or the userinfo, so every query value is replaced (names stay)
8
9
  * and the fragment and userinfo are dropped before `redact` runs. A non-http(s) URL is only redacted. */
9
10
  export declare function scrubPageUrl(raw: string, redact: Redact): string;
11
+ /** A live view as the host receives it, on every channel (`onSession`, a handoff's `request`): the viewer's own URLs stay
12
+ * whole, since the host needs their token; a browsed page's URL and title are scrubbed, since its query can carry a credential. */
13
+ export declare function hostLiveView(view: LiveView, redact: Redact): LiveView;
10
14
  /** 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
15
  export declare function scrubFetchedUrl(raw: string, requested: string, redact: Redact): string;
12
16
  /** Every string inside `value`, object keys included, passed through `redact`. */
@@ -38,6 +38,11 @@ export function scrubPageUrl(raw, redact) {
38
38
  const names = [...new Set(url.searchParams.keys())];
39
39
  return redact(`${url.origin}${url.pathname}${names.length ? `?${names.map((n) => `${encodeURIComponent(n)}=${REDACTED}`).join("&")}` : ""}`);
40
40
  }
41
+ /** A live view as the host receives it, on every channel (`onSession`, a handoff's `request`): the viewer's own URLs stay
42
+ * whole, since the host needs their token; a browsed page's URL and title are scrubbed, since its query can carry a credential. */
43
+ export function hostLiveView(view, redact) {
44
+ return { ...view, pages: view.pages.map((page) => ({ ...page, url: page.url === null ? null : scrubPageUrl(page.url, redact), title: page.title === null ? null : redact(page.title) })) };
45
+ }
41
46
  /** 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
47
  export function scrubFetchedUrl(raw, requested, redact) {
43
48
  let url, asked;
@@ -129,10 +129,10 @@ type ReconnectTimings = {
129
129
  tryMs: number;
130
130
  backoffMs: readonly number[];
131
131
  };
132
- /** `guards` holds each conversation's repeat guard; a host that owns the conversation's lifecycle passes it to evict one. */
133
- /** `reconnect`: the reconnect timings, for tests; hosts keep the defaults. */
134
132
  export declare function pageTools({ guards, reconnect: timings }?: {
133
+ /** Each conversation's repeat guard; a host that owns the conversation's lifecycle passes it to evict one. */
135
134
  guards?: Map<number, RepeatGuard>;
135
+ /** The reconnect timings, for tests; hosts keep the defaults. */
136
136
  reconnect?: ReconnectTimings;
137
137
  }): Pick<BrowserToolImpls<PageDriver>, "snapshot" | "run" | "screenshot" | "browser_read" | "browser_upload" | "browser_downloads">;
138
138
  export {};
@@ -140,8 +140,6 @@ async function markdown(html, fallback) {
140
140
  catch { }
141
141
  return { body: fallback, extractor: "inner-text", ext: "txt" };
142
142
  }
143
- /** `guards` holds each conversation's repeat guard; a host that owns the conversation's lifecycle passes it to evict one. */
144
- /** `reconnect`: the reconnect timings, for tests; hosts keep the defaults. */
145
143
  export function pageTools({ guards = new Map(), reconnect: timings = RECONNECT } = {}) {
146
144
  const guardOf = (conversationId, redact) => guards.get(conversationId) ?? guards.set(conversationId, createRepeatGuard(redact)).get(conversationId);
147
145
  async function failureOf(error, effectful, port, call, action) {
@@ -1,6 +1,7 @@
1
+ import type { Stagehand } from "@browserbasehq/stagehand";
1
2
  import type { PageDriver } from "../core/tools.js";
2
3
  /** `batchMs` bounds every run batch; the page calls' own deadlines are fixed but for tests. */
3
- export declare function pageDriver(stagehand: any, deadlines: {
4
+ export declare function pageDriver(stagehand: Stagehand, deadlines: {
4
5
  batchMs: number;
5
6
  snapshotMs?: number;
6
7
  screenshotMs?: number;
package/dist/durable.js CHANGED
@@ -11,7 +11,7 @@ import { drivingGates, keptFor, personOn, rearmWhenLeft } from "./core/driving.j
11
11
  import { pageTools } from "./core/tools.js";
12
12
  import { useWebsite, useWebsiteContract } from "./core/sites.js";
13
13
  import { leaseTag } from "./core/lease.js";
14
- import { createRedactor, redactDeep, scrubPageUrl } from "./core/redact.js";
14
+ import { createRedactor, hostLiveView, redactDeep, scrubPageUrl } from "./core/redact.js";
15
15
  import { CREATE_DEADLINE_MS, DEFAULT_BROWSER_POLICY, idleTracker, keyedSerializer, oneAtATime, providerKeyValues } from "./core/session-control.js";
16
16
  import { custodyStore, now } from "./store.js";
17
17
  import { withinDeadline } from "./core/unanswered.js";
@@ -124,9 +124,7 @@ async function emit(c, cid, label, record, change, provider) {
124
124
  try {
125
125
  const ref = record.resourceId === null ? null : { id: record.resourceId, tag: record.tag };
126
126
  const view = change !== "released" && ref && provider?.liveView ? await provider.liveView(ref) : null;
127
- // The live view's own URLs go to the host as they are (it needs their token); a browsed page's URL and title are
128
- // scrubbed, since its query can carry a credential.
129
- const liveView = view && { ...view, pages: view.pages.map((page) => ({ ...page, url: page.url === null ? null : scrubPageUrl(page.url, c.redact), title: page.title === null ? null : c.redact(page.title) })) };
127
+ const liveView = view && hostLiveView(view, c.redact);
130
128
  await c.options.onSession({ conversationId: cid, label, session: record, liveView }, change);
131
129
  }
132
130
  catch { }
@@ -598,7 +596,8 @@ function portFor(c, api, context) {
598
596
  const { tag, sessionId } = await port.hold(ask.requestId);
599
597
  const asked = await (async () => {
600
598
  const provider = await providerOf(c, scope.read, scope.cid, scope.plane, scope.context);
601
- const liveView = provider.liveView ? await provider.liveView({ id: sessionId, tag }).catch(() => null) : null;
599
+ const view = provider.liveView ? await provider.liveView({ id: sessionId, tag }).catch(() => null) : null;
600
+ const liveView = view && hostLiveView(view, c.redact);
602
601
  return person.request({ requestId: ask.requestId, sessionTag: tag, sessionId, liveView, instruction: ask.instruction, completionCondition: ask.completionCondition }, scope.signal);
603
602
  })().catch(async (error) => { await port.resume(null); throw failure(error, scope, c.redact); });
604
603
  if ("refused" in asked) {
@@ -1,6 +1,6 @@
1
1
  import type { BrowserProvider } from "../core/host.js";
2
2
  import type { LiveViewHost } from "./server.js";
3
- /** The provider with a live view: `liveView(ref)` reports the viewer's URL (to the host's `onSession`, the one place it goes), and a release kills the
3
+ /** The provider with a live view: `liveView(ref)` reports the viewer's URL (to the host only: its `onSession` and a handoff's `request`), and a release kills the
4
4
  * token before the provider's own release runs, so a session that is going away cannot be driven. Wrap the cdp provider with it, as the frame recorder
5
5
  * wraps a provider with `watch`; the provider's own methods are untouched. */
6
6
  export declare function liveViewProvider(provider: BrowserProvider, host: LiveViewHost): BrowserProvider;
@@ -1,4 +1,4 @@
1
- /** The provider with a live view: `liveView(ref)` reports the viewer's URL (to the host's `onSession`, the one place it goes), and a release kills the
1
+ /** The provider with a live view: `liveView(ref)` reports the viewer's URL (to the host only: its `onSession` and a handoff's `request`), and a release kills the
2
2
  * token before the provider's own release runs, so a session that is going away cannot be driven. Wrap the cdp provider with it, as the frame recorder
3
3
  * wraps a provider with `watch`; the provider's own methods are untouched. */
4
4
  export function liveViewProvider(provider, host) {
@@ -30,8 +30,8 @@ export type LiveViewHost = {
30
30
  handle(req: IncomingMessage, res: ServerResponse): boolean;
31
31
  /** Takes a WebSocket upgrade for a viewer; true when the request was this host's. A bad Origin or an unknown path id is refused here. */
32
32
  upgrade(req: IncomingMessage, socket: Duplex, head: Buffer): boolean;
33
- /** The viewer's URL for one session, with its token in the fragment. Idempotent per tag: the same URL until `release`. Only the host's `onSession`
34
- * ever receives it. Nothing starts until a viewer authenticates. */
33
+ /** The viewer's URL for one session, with its token in the fragment. Idempotent per tag: the same URL until `release`. Only the host receives it (its
34
+ * `onSession`, and a handoff's `request`), never the model. Nothing starts until a viewer authenticates. */
35
35
  open(tag: string, cdpUrl: string): Promise<LiveView>;
36
36
  /** The view `open` gave for a tag, or null: for a caller that must not start anything (`liveViewProvider` asks before it attaches). */
37
37
  known(tag: string): LiveView | null;
@@ -10,11 +10,11 @@ const ID = /^[A-Za-z0-9_-]{22}$/;
10
10
  const SLOW_VIEWER_BYTES = 512 * 1024;
11
11
  /** Input messages are tiny: a whole message, fragments included, over this ends the connection (1009). */
12
12
  const MAX_MESSAGE_BYTES = 64 * 1024;
13
- /** A viewer whose messages the protocol does not know: one is dropped with a notice, and past this many within the window the connection is closed. */
14
13
  /** While a person's command runs, their driving turn is renewed this often (the gate's window is 3 s by default). */
15
14
  const KEEP_DRIVING_MS = 1_000;
16
15
  /** Messages a viewer may have waiting behind the browser command that is running; the rest are dropped with `held busy`, and a viewer that keeps doing it is closed. */
17
16
  const MAX_QUEUED_INPUT = 32;
17
+ /** A viewer whose messages the protocol does not know: one is dropped with a notice, and past this many within the window the connection is closed. */
18
18
  const MAX_BAD_MESSAGES = 20;
19
19
  const BAD_WINDOW_MS = 10_000;
20
20
  export function createLiveView(options) {
@@ -31,8 +31,6 @@ export function createLiveView(options) {
31
31
  /** The opens waiting for the server, by tag: a `release` or a `close` that comes meanwhile marks them cancelled, and each open takes its own mark off when it ends, so
32
32
  * nothing is kept for a tag that has no open in flight. */
33
33
  const opening = new Map();
34
- const need = (value, what) => { if (value === undefined)
35
- throw new Error(`the live view has no ${what}`); return value; };
36
34
  const send = (conn, message) => { conn.send(JSON.stringify(message)); };
37
35
  const refuse = (conn, reason) => { send(conn, { type: "refused", reason }); conn.close(CLOSE_CODES[reason], reason); };
38
36
  /** The request's path, or null when its target cannot be read as one (`//[`): such a request is nobody's, so it is not this host's and nothing is thrown into the
@@ -1,4 +1,3 @@
1
- export { directFetch, closeDirectFetch } from "./http.js";
2
1
  /** Rewrite a Browserbase connect URL onto the credential proxy: only `*.browserbase.com` hosts, the signing query kept. */
3
2
  export declare function rewriteConnectUrl(connectUrl: string, connectBaseUrl: string | undefined | null): string;
4
3
  /** Direct, never through the HTTP(S) env proxy: it rejects CONNECT and the CDP WebSocket cannot ride it. Under `node
@@ -1,5 +1,4 @@
1
1
  import { browserbaseHoldings } from "./shared.js";
2
- export { directFetch, closeDirectFetch } from "./http.js";
3
2
  /** Rewrite a Browserbase connect URL onto the credential proxy: only `*.browserbase.com` hosts, the signing query kept. */
4
3
  export function rewriteConnectUrl(connectUrl, connectBaseUrl) {
5
4
  if (!connectUrl || !connectBaseUrl)
@@ -1,11 +1,12 @@
1
1
  import { execFile, spawn } from "node:child_process";
2
- import { createReadStream, createWriteStream, readFileSync } from "node:fs";
2
+ import { closeSync, createReadStream, createWriteStream, readFileSync } from "node:fs";
3
3
  import { lstat, mkdir, mkdtemp, open, readdir, readFile, readlink, rm, stat, symlink, writeFile } from "node:fs/promises";
4
4
  import os from "node:os";
5
5
  import { pipeline } from "node:stream/promises";
6
6
  import path from "node:path";
7
7
  import { BrowserFailureError, PROFILE_NAME } from "../core/custody.js";
8
8
  import { cdpCall } from "./cdp-call.js";
9
+ import { chromeTail, openChromeStderr, watchChromeStderr } from "./chrome-stderr.js";
9
10
  import { claimWriter, freeWriter, noteWriter } from "./profiles.js";
10
11
  /** Stagehand 4.1.0's DEFAULT_CHROME_FLAGS (packages/sdk-ts/src/browser/localBrowser.ts, MIT, see NOTICE). Without them
11
12
  * Stagehand.create takes about 24 s on a local Chrome instead of under 100 ms. */
@@ -253,6 +254,7 @@ async function ownedBy(named, tag) {
253
254
  return null;
254
255
  return (await readFile(path.join(named, TMP_OWNER), "utf8").catch(() => null)) === tag ? named : null;
255
256
  }
257
+ const SANDBOX_HINT = "On a system that cannot start Chrome's sandbox (root, a container, restricted user namespaces), set sandbox: false or PI_BROWSER_NO_SANDBOX=1.";
256
258
  /** Signal 0 only asks; EPERM means the process exists under another user. */
257
259
  const alive = (pid) => { try {
258
260
  process.kill(pid, 0);
@@ -392,19 +394,38 @@ export function cdpProvider(options, internals = {}) {
392
394
  const tmp = await makePrivateTmp(spec.tag, dir, spec.profile?.save ? leaseRecord(profileRoot, spec.tag) : null, remove);
393
395
  if (tmp)
394
396
  privateTmps.set(spec.tag, tmp);
395
- const child = spawn(executablePath, [
396
- ...CHROME_FLAGS, ...(sandbox ? [] : ["--no-sandbox"]), ...(headless ? ["--headless=new"] : []), "--remote-debugging-port=0", "--remote-debugging-address=127.0.0.1", `--user-data-dir=${dir}`,
397
- `--window-size=${spec.viewport.width},${spec.viewport.height}`, ...args, "about:blank",
398
- ], { stdio: "ignore", detached: true, ...(tmp ? { env: { ...process.env, TMPDIR: tmp } } : {}) });
397
+ const stderrFd = openChromeStderr(tmp);
398
+ let child;
399
+ try {
400
+ child = spawn(executablePath, [
401
+ ...CHROME_FLAGS, ...(sandbox ? [] : ["--no-sandbox"]), ...(headless ? ["--headless=new"] : []), "--remote-debugging-port=0", "--remote-debugging-address=127.0.0.1", `--user-data-dir=${dir}`,
402
+ `--window-size=${spec.viewport.width},${spec.viewport.height}`, ...args, "about:blank",
403
+ ], { stdio: ["ignore", "ignore", stderrFd ?? "ignore"], detached: true, ...(tmp ? { env: { ...process.env, TMPDIR: tmp } } : {}) });
404
+ }
405
+ catch (error) {
406
+ // A spawn that throws (an argument with a null byte) starts no child, so nothing else will remove what this start made.
407
+ const left = await removeAll([dir, downloadsDir(profileRoot, spec.tag), ...(tmp ? [tmp] : [])], remove);
408
+ await forgetTmp(profileRoot, spec.tag);
409
+ throw left ? new ProfileNotRemovedError(left.dirs, left.error, error) : error;
410
+ }
411
+ finally {
412
+ // The parent's copy is closed whether or not spawn threw.
413
+ if (stderrFd !== null)
414
+ closeSync(stderrFd);
415
+ }
399
416
  // A Chrome that cannot start emits `error`, which unhandled would end the host: it rejects create instead.
400
417
  let failed = null;
401
418
  child.once("error", (error) => { failed = error; });
402
419
  child.once("exit", (code, signal) => {
403
- // A Chrome that cannot start its sandbox aborts (SIGABRT) before it opens a port: the signal is the fact, never
404
- // Chrome's words.
405
- failed ??= sandbox && signal === "SIGABRT"
406
- ? new BrowserFailureError({ ok: false, code: "browser_unavailable", retryable: false, effect: "none", message: `Chrome exited before it opened its debugging port (SIGABRT); on a system that cannot start Chrome's sandbox (root, a container, restricted user namespaces) start it with sandbox: false or PI_BROWSER_NO_SANDBOX=1` })
407
- : new Error(`Chrome exited before it opened its debugging port (${signal ?? code})`);
420
+ // Whatever Chrome said goes into the failure. The sandbox hint goes with it when the sandbox is on and either Chrome
421
+ // aborted before it opened a port (SIGABRT, how some builds fail it) or its own words name the sandbox (others exit 1).
422
+ if (failed)
423
+ return;
424
+ const tail = chromeTail(tmp);
425
+ const message = `Chrome exited before it opened its debugging port (${signal ?? code})${tail ? `\nChrome said:\n${tail.split("\n").map((line) => ` ${line}`).join("\n")}` : ""}`;
426
+ failed = sandbox && (signal === "SIGABRT" || /sandbox/i.test(tail))
427
+ ? new BrowserFailureError({ ok: false, code: "browser_unavailable", retryable: false, effect: "none", message: `${message}\n${SANDBOX_HINT}` })
428
+ : new Error(message);
408
429
  });
409
430
  if (child.pid === undefined) {
410
431
  await sleep(0);
@@ -425,6 +446,7 @@ export function cdpProvider(options, internals = {}) {
425
446
  if (own && (await answeringPath(own.port)) === own.path) {
426
447
  const pid = child.pid;
427
448
  noteWriter(spec.tag, () => isOurs({ pid, port: own.port }));
449
+ watchChromeStderr(tmp, pid);
428
450
  return { id: `local:${pid}:${own.port}:${spec.tag}`, tag: spec.tag };
429
451
  }
430
452
  if (Date.now() > deadline)
@@ -471,6 +493,8 @@ export function cdpProvider(options, internals = {}) {
471
493
  const url = await debuggerUrl(`http://127.0.0.1:${local.port}`);
472
494
  if (new URL(url).pathname !== own.path)
473
495
  throw new Error(`the browser on port ${local.port} is not the browser this lease's profile records`);
496
+ // A Chrome this host did not start outlived the host that did: its stderr file is bounded here too.
497
+ watchChromeStderr(privateTmps.get(local.tag) ?? await recordedTmp(options.chrome.profileRoot, local.tag) ?? await ownedTmp(profileDir(options.chrome.profileRoot, local.tag), local.tag), local.pid);
474
498
  return { sdkCdpUrl: url };
475
499
  },
476
500
  async release(ref) {
@@ -0,0 +1,21 @@
1
+ /** What a Chrome that exits before its port opens said on stderr. Chrome writes to a file in the lease's private
2
+ * directory, not a pipe: a pipe would end Chrome's writes when this host dies, and the host's death is a case this
3
+ * package survives. The failure carries the last lines only, with control characters dropped and the common key shapes
4
+ * redacted: a model reads it. */
5
+ export declare const CHROME_STDERR = "chrome-stderr.log";
6
+ /** Once the port is open the start-up lines have done their work: the file is emptied then, and again whenever it passes
7
+ * this size, so a Chrome that logs heavily through `args` cannot fill the disk. */
8
+ export declare const KEEP_BYTES: number;
9
+ /** The file Chrome's stderr goes to, open for append; null when there is no private directory or it cannot be opened. */
10
+ export declare function openChromeStderr(dir: string | null): number | null;
11
+ /** The last lines Chrome wrote. A read that starts inside a line drops that partial line, and each whole line is redacted
12
+ * before it is shortened: a key cut by either would no longer match its shape. */
13
+ export declare function chromeTail(dir: string | null): string;
14
+ /** Empties the file when it is over `limit`. Chrome holds it open for append, so what it writes next lands at the new end. */
15
+ export declare function trimChromeStderr(dir: string | null, limit?: number): boolean;
16
+ /** From the moment the port is open (or a host recovers that Chrome) until that process or its file is gone, once per
17
+ * directory. A timer never keeps this host alive, and it is by pid, not by child: a recovered Chrome is no child of this host. */
18
+ export declare function watchChromeStderr(dir: string | null, pid: number, everyMs?: number): void;
19
+ /** For tests: how many directories are watched, and a way to stop them all. */
20
+ export declare const watchedChromeStderr: () => number;
21
+ export declare function stopWatchingChromeStderr(): void;
@@ -0,0 +1,108 @@
1
+ import { closeSync, fstatSync, openSync, readSync, statSync, truncateSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { createRedactor } from "../core/redact.js";
4
+ /** What a Chrome that exits before its port opens said on stderr. Chrome writes to a file in the lease's private
5
+ * directory, not a pipe: a pipe would end Chrome's writes when this host dies, and the host's death is a case this
6
+ * package survives. The failure carries the last lines only, with control characters dropped and the common key shapes
7
+ * redacted: a model reads it. */
8
+ export const CHROME_STDERR = "chrome-stderr.log";
9
+ const TAIL_BYTES = 4096;
10
+ const TAIL_LINES = 10;
11
+ const LINE_CHARS = 300;
12
+ /** Once the port is open the start-up lines have done their work: the file is emptied then, and again whenever it passes
13
+ * this size, so a Chrome that logs heavily through `args` cannot fill the disk. */
14
+ export const KEEP_BYTES = 256 * 1024;
15
+ const TRIM_EVERY_MS = 60_000;
16
+ const redact = createRedactor();
17
+ /** The file Chrome's stderr goes to, open for append; null when there is no private directory or it cannot be opened. */
18
+ export function openChromeStderr(dir) {
19
+ if (!dir)
20
+ return null;
21
+ try {
22
+ return openSync(path.join(dir, CHROME_STDERR), "a", 0o600);
23
+ }
24
+ catch {
25
+ return null;
26
+ }
27
+ }
28
+ /** The last lines Chrome wrote. A read that starts inside a line drops that partial line, and each whole line is redacted
29
+ * before it is shortened: a key cut by either would no longer match its shape. */
30
+ export function chromeTail(dir) {
31
+ if (!dir)
32
+ return "";
33
+ let fd = null;
34
+ try {
35
+ fd = openSync(path.join(dir, CHROME_STDERR), "r");
36
+ const size = fstatSync(fd).size, from = Math.max(0, size - TAIL_BYTES), buf = Buffer.alloc(size - from);
37
+ readSync(fd, buf, 0, buf.length, from);
38
+ let text = buf.toString("utf8");
39
+ if (from > 0) {
40
+ // The read began inside a line. With no newline in the whole window it is one partial line, and none of it can be trusted to redact.
41
+ const newline = text.indexOf("\n");
42
+ if (newline === -1)
43
+ return "";
44
+ text = text.slice(newline + 1);
45
+ }
46
+ return text.replace(/[^\S\n]+/g, " ").replace(/[\u0000-\u0009\u000b-\u001f\u007f]/g, "").split("\n")
47
+ .map((line) => redact(line.trim())).filter(Boolean).slice(-TAIL_LINES)
48
+ .map((line) => (line.length > LINE_CHARS ? `${line.slice(0, LINE_CHARS)}...` : line)).join("\n");
49
+ }
50
+ catch {
51
+ return "";
52
+ }
53
+ finally {
54
+ if (fd !== null)
55
+ closeSync(fd);
56
+ }
57
+ }
58
+ /** Empties the file when it is over `limit`. Chrome holds it open for append, so what it writes next lands at the new end. */
59
+ export function trimChromeStderr(dir, limit = KEEP_BYTES) {
60
+ if (!dir)
61
+ return false;
62
+ const file = path.join(dir, CHROME_STDERR);
63
+ try {
64
+ if (statSync(file).size <= limit)
65
+ return false;
66
+ truncateSync(file, 0);
67
+ return true;
68
+ }
69
+ catch {
70
+ return false;
71
+ }
72
+ }
73
+ const watching = new Map();
74
+ const alive = (pid) => { try {
75
+ process.kill(pid, 0);
76
+ return true;
77
+ }
78
+ catch (error) {
79
+ return error.code === "EPERM";
80
+ } };
81
+ /** From the moment the port is open (or a host recovers that Chrome) until that process or its file is gone, once per
82
+ * directory. A timer never keeps this host alive, and it is by pid, not by child: a recovered Chrome is no child of this host. */
83
+ export function watchChromeStderr(dir, pid, everyMs = TRIM_EVERY_MS) {
84
+ if (!dir || watching.has(dir))
85
+ return;
86
+ trimChromeStderr(dir, 0);
87
+ const timer = setInterval(() => {
88
+ if (!alive(pid) || !statSyncOk(path.join(dir, CHROME_STDERR))) {
89
+ clearInterval(timer);
90
+ watching.delete(dir);
91
+ return;
92
+ }
93
+ trimChromeStderr(dir);
94
+ }, everyMs);
95
+ timer.unref();
96
+ watching.set(dir, timer);
97
+ }
98
+ const statSyncOk = (file) => { try {
99
+ statSync(file);
100
+ return true;
101
+ }
102
+ catch {
103
+ return false;
104
+ } };
105
+ /** For tests: how many directories are watched, and a way to stop them all. */
106
+ export const watchedChromeStderr = () => watching.size;
107
+ export function stopWatchingChromeStderr() { for (const timer of watching.values())
108
+ clearInterval(timer); watching.clear(); }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@parcha/pi-browser",
3
- "version": "0.1.0-beta.21",
3
+ "version": "0.1.0-beta.23",
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",