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

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,105 @@
1
+ // The effect journal of the pi-durable adapter: an effectful action is journaled before it runs, and an entry an earlier process
2
+ // wrote and never settled is a cut, which the next call tells the model about once. These read and settle the journal; custody
3
+ // (durable.ts) writes it.
4
+ import { ToolResultEntry } from "@earendil-works/pi-durable";
5
+ export const journalOf = (state, plane) => [...state.sessions].reverse().find((r) => r.plane === plane && r.pendingEffect !== null)?.pendingEffect ?? null;
6
+ /** The entry with this call's id in a journal chain: the entry itself or one it carries as `prior`. */
7
+ export const inChain = (entry, callId) => {
8
+ for (let e = entry; e; e = e.prior)
9
+ if (e.callId === callId)
10
+ return e;
11
+ return undefined;
12
+ };
13
+ /** Settles one entry of a journal chain; the entries it carried stay. */
14
+ export const clearJournal = (c, scope, callId) => scope.commit(async (tx) => {
15
+ const state = await tx.doc(c.Sessions, scope.cid);
16
+ for (const record of state.sessions) {
17
+ if (record.plane !== scope.plane || !record.pendingEffect)
18
+ continue;
19
+ if (record.pendingEffect.callId === callId) {
20
+ record.pendingEffect = record.pendingEffect.prior ?? null;
21
+ continue;
22
+ }
23
+ for (let e = record.pendingEffect; e.prior; e = e.prior) {
24
+ if (e.prior.callId !== callId)
25
+ continue;
26
+ if (e.prior.prior)
27
+ e.prior = e.prior.prior;
28
+ else
29
+ delete e.prior;
30
+ break;
31
+ }
32
+ }
33
+ });
34
+ /** The entries of a journal chain whose warning is still owed, as a chain: each an earlier process wrote that is a cut (not
35
+ * finished with a saved answer) and has not been told by a saved answer. An entry of this process is never a cut, and a told
36
+ * one whose telling answer was saved was delivered. */
37
+ export async function owed(c, scope, entry) {
38
+ if (!entry)
39
+ return null;
40
+ const rest = await owed(c, scope, entry.prior);
41
+ const { prior: _carried, ...own } = entry;
42
+ const delivered = entry.incarnation === c.incarnation
43
+ || (entry.told === true && (await toldSaved(scope, entry)))
44
+ || (entry.finished === true && !entry.told && (await answered(scope, entry)));
45
+ return delivered ? rest : { ...own, ...(rest ? { prior: rest } : {}) };
46
+ }
47
+ /** A journaled action's own answer as pi committed it: true for a success, false for an error, null for none yet. */
48
+ export async function answerOf(scope, pending) {
49
+ const message = await savedAnswer(scope, pending.after, pending.callId);
50
+ return message === null ? null : message.isError !== true;
51
+ }
52
+ /** Whether the call that told a cut had its answer saved, carrying the cut's facts. One killed between the told mark and pi's
53
+ * commit told nobody, and the cut is told again. */
54
+ async function toldSaved(scope, pending) {
55
+ if (!pending.toldBy)
56
+ return false;
57
+ const message = await savedAnswer(scope, pending.after, pending.toldBy);
58
+ return message?.details?.pendingEffect?.callId === pending.callId;
59
+ }
60
+ /** A call's saved tool result, found by pi's typed tool-result entry. The scan covers only the cut's conversation from where
61
+ * it was journaled on, never the whole history. */
62
+ async function savedAnswer(scope, after, callId) {
63
+ if (after === undefined)
64
+ return null;
65
+ return scope.commit(async (tx) => {
66
+ let cursor;
67
+ do {
68
+ const page = await tx.scanEntries({ conversationId: scope.cid, minEntryId: after, order: "ascending" }, 100, cursor);
69
+ for (const entry of page.items) {
70
+ const message = ToolResultEntry.is(entry) ? entry.model?.[0] : undefined;
71
+ if (message?.role === "toolResult" && message.toolCallId === callId)
72
+ return message;
73
+ }
74
+ cursor = page.next;
75
+ } while (cursor !== undefined);
76
+ return null;
77
+ });
78
+ }
79
+ /** Whether a journaled action's own answer was committed as a success. */
80
+ const answered = async (scope, pending) => (await answerOf(scope, pending)) === true;
81
+ /** One journal entry as a cut. In this process an entry is in flight or answered, never cut; one an earlier process wrote is
82
+ * a cut unless its action finished and pi committed its answer, which only then is looked up. It counts as told only once
83
+ * the telling call's answer, carrying its facts, was saved. */
84
+ async function oneCut(c, scope, entry) {
85
+ if (entry.incarnation === c.incarnation)
86
+ return null;
87
+ const { prior: _carried, ...own } = entry;
88
+ const pending = own.told && !(await toldSaved(scope, own)) ? { ...own, told: false } : own;
89
+ if (!pending.finished || pending.told || !(await answered(scope, pending)))
90
+ return pending;
91
+ await clearJournal(c, scope, pending.callId);
92
+ return null;
93
+ }
94
+ /** Every cut in a journal chain, oldest first. An entry a later action replaced counts only while its warning is still owed:
95
+ * once a saved answer told it, the later action replaced it, as it would have with no chain. */
96
+ export async function cutsOf(c, scope, entry, newest = true) {
97
+ if (!entry)
98
+ return [];
99
+ const older = await cutsOf(c, scope, entry.prior, false);
100
+ const own = await oneCut(c, scope, entry);
101
+ return own && (newest || !own.told) ? [...older, own] : older;
102
+ }
103
+ /** The cut a call answers for: the oldest whose warning is still owed (an entry a later action replaced before the telling
104
+ * of it was saved comes first), else the newest. */
105
+ export const cutOf = (cuts) => cuts.find((cut) => !cut.told) ?? cuts.at(-1) ?? null;
@@ -1,4 +1,4 @@
1
- import type { ToolOutput } from "./core/custody.js";
1
+ import type { ToolOutput } from "../core/custody.js";
2
2
  /** pi-durable 1.0 and 1.1 read a tool result's `content`; 1.2 reads `output` and treats a result that lacks it as empty. The model's text goes under both keys. */
3
3
  export declare const forModel: (content: ToolOutput["content"]) => {
4
4
  content: ToolOutput["content"];
@@ -1,7 +1,7 @@
1
1
  import type { Context } from "@earendil-works/chord";
2
2
  import { type ConversationDocToken, type ConversationId, type DocumentReader, type Harness, type TaskId, type Tx } from "@earendil-works/pi-durable";
3
- import type { BrowserConfig, BrowserProvider, HandoffOutcome, HandoffPort, InventoryRow, ReconcileReport, ReleaseReason, SessionChange, SessionRecord, SessionsState } from "./core/host.js";
4
- import type { LeaseRef, LeaseState } from "./core/lease.js";
3
+ import type { BrowserConfig, BrowserProvider, HandoffOutcome, HandoffPort, InventoryRow, ReconcileReport, ReleaseReason, SessionChange, SessionRecord, SessionsState } from "../core/host.js";
4
+ import type { LeaseRef, LeaseState } from "../core/lease.js";
5
5
  export declare const now: () => string;
6
6
  /** Release attempts before custody is given up as `lost`, and status polls before a release is sent again. */
7
7
  export declare const RELEASE_ATTEMPTS = 6;
@@ -1,5 +1,5 @@
1
1
  import { defineDoc, defineTask } from "@earendil-works/pi-durable";
2
- import { backoffMs, moveRecord, notices } from "./core/custody.js";
2
+ import { backoffMs, moveRecord, notices } from "../core/custody.js";
3
3
  export const now = () => new Date().toISOString();
4
4
  const iso = (ms) => new Date(ms).toISOString();
5
5
  const cidOf = (row) => row.conversationId;
@@ -1,8 +1,8 @@
1
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 RenderedPage, type WebBackup, type WebToolsOptions } from "./core/web.js";
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 RenderedPage, type WebBackup, type WebToolsOptions } from "../core/web.js";
6
6
  export type WebExtensionOptions = {
7
7
  providers: {
8
8
  /** Names the source in `via` (`<name>_fetch`, `<name>_search`); default "provider". */
@@ -1,9 +1,9 @@
1
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 "./durable-result.js";
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
7
  export function createWebExtension(options) {
8
8
  const tools = createWebTools({
9
9
  name: options.providers.name ?? "provider",
package/dist/durable.d.ts CHANGED
@@ -93,6 +93,6 @@ export type BrowserExtensionHandle = {
93
93
  /** How many conversations the extension still holds in-memory state for: a repeat guard, an idle timer or a queued call. */
94
94
  retained(): number;
95
95
  };
96
- export { createWebExtension, type WebExtensionOptions } from "./web.js";
97
- export { CONFIRM_POLLS, RELEASE_ATTEMPTS } from "./store.js";
96
+ export { createWebExtension, type WebExtensionOptions } from "./durable/web.js";
97
+ export { CONFIRM_POLLS, RELEASE_ATTEMPTS } from "./durable/store.js";
98
98
  export declare function createBrowserExtension<D extends PageDriver>(options: BrowserExtensionOptions<D>): BrowserExtensionHandle;
package/dist/durable.js CHANGED
@@ -1,23 +1,24 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { configure, defineDoc, defineExtension, defineTool, ToolResultEntry } from "@earendil-works/pi-durable";
3
- import { BROWSER_TOOL_NAMES, BROWSER_TOOLS, browserSection, WEB_TOOL_NAMES } from "./core/contract.js";
4
- import { BrowserFailureError, closeDriver, currentRecord, loadedNoPage, custodyTools, FIXED_SESSION_RELAUNCH, fenced, HANDED_BACK, newSessionRecord, notices, NAVIGATION_CAP, NOTHING_TO_HOLD, profileRefusal, relaunchRefusal, SESSION_REPLACED, sessionSpec, waitingForHuman, NO_HANDOFF } from "./core/custody.js";
5
- import { forModel } from "./durable-result.js";
2
+ import { configure, defineDoc, defineExtension, defineTool } from "@earendil-works/pi-durable";
3
+ import { BROWSER_TOOL_NAMES, BROWSER_TOOLS, browserSection, listedFor, WEB_TOOL_NAMES } from "./core/contract.js";
4
+ import { BrowserFailureError, closeDriver, currentRecord, loadedNoPage, custodyTools, FIXED_SESSION_RELAUNCH, fenced, HANDED_BACK, newSessionRecord, notices, NAVIGATION_CAP, NOTHING_TO_HOLD, navigationRefusal, profileRefusal, relaunchRefusal, SESSION_REPLACED, sessionSpec, waitingForHuman, NO_HANDOFF } from "./core/custody.js";
5
+ import { forModel } from "./durable/result.js";
6
6
  import { EffectObserver, effectDecider, observerFailure } from "./core/effects.js";
7
7
  import { browserFailure, classifyBrowserError } from "./core/failures.js";
8
8
  import { workspaceFiles } from "./core/files.js";
9
9
  import { drivingGuarded } from "./core/driving-guard.js";
10
- import { drivingGates, keptFor, personOn, rearmWhenLeft } from "./core/driving.js";
10
+ import { drivingGates, keptReason, personOn, rearmWhenLeft } from "./core/driving.js";
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, hostLiveView, redactDeep, scrubPageUrl } from "./core/redact.js";
14
+ import { createRedactor, hostLiveView, redactContent, 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
- import { custodyStore, now } from "./store.js";
16
+ import { custodyStore, now } from "./durable/store.js";
17
+ import { answerOf, clearJournal, cutOf, cutsOf, inChain, journalOf, owed } from "./durable/journal.js";
17
18
  import { withinDeadline } from "./core/unanswered.js";
18
19
  import { resolvePrices, sessionCharge, withEstimate } from "./core/usage.js";
19
- export { createWebExtension } from "./web.js";
20
- export { CONFIRM_POLLS, RELEASE_ATTEMPTS } from "./store.js";
20
+ export { createWebExtension } from "./durable/web.js";
21
+ export { CONFIRM_POLLS, RELEASE_ATTEMPTS } from "./durable/store.js";
21
22
  const PLANE = "default";
22
23
  const UNCONFIGURED = { label: "", run: "", policy: DEFAULT_BROWSER_POLICY };
23
24
  const HANDOFF_ENDED = new BrowserFailureError(browserFailure("session_ended", "The browser session left the person's hands before their answer could be waited on. Your next browser call opens a fresh session; take a snapshot there before acting.", { retryable: true }));
@@ -97,6 +98,9 @@ async function configOf(c, read, cid, context) {
97
98
  async function providerOf(c, read, cid, plane, context) {
98
99
  return c.options.provider({ conversationId: cid, plane, config: await configOf(c, read, cid, context) });
99
100
  }
101
+ /** The two lookups for the conversation and plane a tool call runs in. */
102
+ const scopeConfig = (c, scope) => configOf(c, scope.read, scope.cid, scope.context);
103
+ const scopeProvider = (c, scope) => providerOf(c, scope.read, scope.cid, scope.plane, scope.context);
100
104
  const rowOf = (cid, record) => ({ tag: record.tag, conversationId: cid, plane: record.plane, provider: record.provider, resourceId: record.resourceId, state: record.state });
101
105
  async function emitObserver(c, row) {
102
106
  try {
@@ -136,13 +140,22 @@ const failure = (error, scope, redact) => error instanceof BrowserFailureError ?
136
140
  /** `bound`, when given, limits the attach beside the call's own signal (a reconnect's budget); the check for a session the
137
141
  * provider ended keeps the call's own. */
138
142
  async function attachLive(c, scope, record, bound) {
143
+ // A live session reused, resumed by another process or kept across a change of policy, meets the navigation check a new one
144
+ // meets at create: a policy its provider cannot enforce is refused, and so is an allow list the session was not started under,
145
+ // never browsed under because the session already existed.
146
+ const navigation = (await scopeConfig(c, scope)).policy.navigation;
147
+ if (navigation) {
148
+ const refusal = navigationRefusal({ navigation }, await scopeProvider(c, scope), { applied: record.settings.navigationAllow });
149
+ if (refusal)
150
+ throw new BrowserFailureError(refusal);
151
+ }
139
152
  const held = c.held.driver(record.tag);
140
153
  // An observer whose socket closed holds nothing: driver and observer are attached again together.
141
154
  if (held && !c.held.observer(record.tag)?.closed)
142
155
  return held;
143
156
  if (held)
144
157
  await c.held.detach(record.tag);
145
- const provider = await providerOf(c, scope.read, scope.cid, scope.plane, scope.context);
158
+ const provider = await scopeProvider(c, scope);
146
159
  const ref = { id: record.resourceId, tag: record.tag };
147
160
  try {
148
161
  return await connect(c, bound ? { ...scope, signal: AbortSignal.any([scope.signal, bound]) } : scope, provider, ref);
@@ -154,7 +167,7 @@ async function attachLive(c, scope, record, bound) {
154
167
  }
155
168
  }
156
169
  async function connect(c, scope, provider, ref) {
157
- const config = await configOf(c, scope.read, scope.cid, scope.context);
170
+ const config = await scopeConfig(c, scope);
158
171
  const { actions: policy, batchTimeoutMs } = config.policy;
159
172
  c.owned.set(ref.tag, { cid: scope.cid, provider, ref });
160
173
  const target = await provider.attach(ref, scope.signal);
@@ -184,11 +197,11 @@ async function markEnded(c, scope, record, provider) {
184
197
  return true;
185
198
  }
186
199
  async function refuseHeld(c, scope, record) {
187
- if (record?.state === "held" && !(await markEnded(c, scope, record, await providerOf(c, scope.read, scope.cid, scope.plane, scope.context))))
200
+ if (record?.state === "held" && !(await markEnded(c, scope, record, await scopeProvider(c, scope))))
188
201
  throw waiting(record);
189
202
  }
190
203
  async function settleCreating(c, scope, record) {
191
- const provider = await providerOf(c, scope.read, scope.cid, scope.plane, scope.context);
204
+ const provider = await scopeProvider(c, scope);
192
205
  try {
193
206
  await c.store.bindByTag(provider, rowOf(scope.cid, record), scope.commit, scope.signal);
194
207
  }
@@ -197,11 +210,11 @@ async function settleCreating(c, scope, record) {
197
210
  }
198
211
  }
199
212
  async function create(c, scope, overrides, presetTag) {
200
- const config = await configOf(c, scope.read, scope.cid, scope.context);
213
+ const config = await scopeConfig(c, scope);
201
214
  const provider = await c.options.provider({ conversationId: scope.cid, plane: scope.plane, config });
202
215
  const tag = presetTag ?? leaseTag("ar", config.run, scope.cid, (await stateOf(c, scope)).sessions.length + 1);
203
216
  const spec = sessionSpec(config, tag, overrides);
204
- const unsupported = profileRefusal(spec, provider.caps);
217
+ const unsupported = profileRefusal(spec, provider.caps) ?? navigationRefusal(spec, provider);
205
218
  if (unsupported)
206
219
  throw new BrowserFailureError(unsupported);
207
220
  const record = newSessionRecord({ plane: scope.plane, tag, provider: provider.name, spec, at: now(), honours: provider.caps.settings });
@@ -268,7 +281,7 @@ async function attached(c, scope, record, driver, note) {
268
281
  const fresh = state.sessions.find((r) => r.tag === record.tag) ?? record;
269
282
  const cuts = await cutsOf(c, scope, journalOf(state, scope.plane));
270
283
  const interrupted = cutOf(cuts);
271
- const provider = await providerOf(c, scope.read, scope.cid, scope.plane, scope.context);
284
+ const provider = await scopeProvider(c, scope);
272
285
  const fence = fresh.fence ?? 0;
273
286
  return { driver: fenced(driver, fence, () => c.fences.get(record.tag)), tag: record.tag, sessionId: fresh.resourceId, record: fresh, notice: notice || null, interrupted, cuts, recorded: Boolean(provider.recordings), effects: c.held.observer(record.tag) ?? null, fence, downloads: provider.downloads ?? null, replaced: replacedOf(state, scope.plane, fresh) };
274
287
  }
@@ -290,114 +303,14 @@ async function releaseRecord(c, scope, record, reason) {
290
303
  await c.held.detach(record.tag);
291
304
  }
292
305
  const editState = (c, scope, edit) => scope.commit(async (tx) => edit(await tx.doc(c.Sessions, scope.cid)));
293
- const journalOf = (state, plane) => [...state.sessions].reverse().find((r) => r.plane === plane && r.pendingEffect !== null)?.pendingEffect ?? null;
294
- /** The entry with this call's id in a journal chain: the entry itself or one it carries as `prior`. */
295
- const inChain = (entry, callId) => {
296
- for (let e = entry; e; e = e.prior)
297
- if (e.callId === callId)
298
- return e;
299
- return undefined;
300
- };
301
- /** Settles one entry of a journal chain; the entries it carried stay. */
302
- const clearJournal = (c, scope, callId) => editState(c, scope, (state) => {
303
- for (const record of state.sessions) {
304
- if (record.plane !== scope.plane || !record.pendingEffect)
305
- continue;
306
- if (record.pendingEffect.callId === callId) {
307
- record.pendingEffect = record.pendingEffect.prior ?? null;
308
- continue;
309
- }
310
- for (let e = record.pendingEffect; e.prior; e = e.prior) {
311
- if (e.prior.callId !== callId)
312
- continue;
313
- if (e.prior.prior)
314
- e.prior = e.prior.prior;
315
- else
316
- delete e.prior;
317
- break;
318
- }
319
- }
320
- });
321
- /** The entries of a journal chain whose warning is still owed, as a chain: each an earlier process wrote that is a cut (not
322
- * finished with a saved answer) and has not been told by a saved answer. An entry of this process is never a cut, and a told
323
- * one whose telling answer was saved was delivered. */
324
- async function owed(c, scope, entry) {
325
- if (!entry)
326
- return null;
327
- const rest = await owed(c, scope, entry.prior);
328
- const { prior: _carried, ...own } = entry;
329
- const delivered = entry.incarnation === c.incarnation
330
- || (entry.told === true && (await toldSaved(scope, entry)))
331
- || (entry.finished === true && !entry.told && (await answered(scope, entry)));
332
- return delivered ? rest : { ...own, ...(rest ? { prior: rest } : {}) };
333
- }
334
- /** A journaled action's own answer as pi committed it: true for a success, false for an error, null for none yet. */
335
- async function answerOf(scope, pending) {
336
- const message = await savedAnswer(scope, pending.after, pending.callId);
337
- return message === null ? null : message.isError !== true;
338
- }
339
- /** Whether the call that told a cut had its answer saved, carrying the cut's facts. One killed between the told mark and pi's
340
- * commit told nobody, and the cut is told again. */
341
- async function toldSaved(scope, pending) {
342
- if (!pending.toldBy)
343
- return false;
344
- const message = await savedAnswer(scope, pending.after, pending.toldBy);
345
- return message?.details?.pendingEffect?.callId === pending.callId;
346
- }
347
- /** A call's saved tool result, found by pi's typed tool-result entry. The scan covers only the cut's conversation from where
348
- * it was journaled on, never the whole history. */
349
- async function savedAnswer(scope, after, callId) {
350
- if (after === undefined)
351
- return null;
352
- return scope.commit(async (tx) => {
353
- let cursor;
354
- do {
355
- const page = await tx.scanEntries({ conversationId: scope.cid, minEntryId: after, order: "ascending" }, 100, cursor);
356
- for (const entry of page.items) {
357
- const message = ToolResultEntry.is(entry) ? entry.model?.[0] : undefined;
358
- if (message?.role === "toolResult" && message.toolCallId === callId)
359
- return message;
360
- }
361
- cursor = page.next;
362
- } while (cursor !== undefined);
363
- return null;
364
- });
365
- }
366
- /** Whether a journaled action's own answer was committed as a success. */
367
- const answered = async (scope, pending) => (await answerOf(scope, pending)) === true;
368
- /** One journal entry as a cut. In this process an entry is in flight or answered, never cut; one an earlier process wrote is
369
- * a cut unless its action finished and pi committed its answer, which only then is looked up. It counts as told only once
370
- * the telling call's answer, carrying its facts, was saved. */
371
- async function oneCut(c, scope, entry) {
372
- if (entry.incarnation === c.incarnation)
373
- return null;
374
- const { prior: _carried, ...own } = entry;
375
- const pending = own.told && !(await toldSaved(scope, own)) ? { ...own, told: false } : own;
376
- if (!pending.finished || pending.told || !(await answered(scope, pending)))
377
- return pending;
378
- await clearJournal(c, scope, pending.callId);
379
- return null;
380
- }
381
- /** Every cut in a journal chain, oldest first. An entry a later action replaced counts only while its warning is still owed:
382
- * once a saved answer told it, the later action replaced it, as it would have with no chain. */
383
- async function cutsOf(c, scope, entry, newest = true) {
384
- if (!entry)
385
- return [];
386
- const older = await cutsOf(c, scope, entry.prior, false);
387
- const own = await oneCut(c, scope, entry);
388
- return own && (newest || !own.told) ? [...older, own] : older;
389
- }
390
- /** The cut a call answers for: the oldest whose warning is still owed (an entry a later action replaced before the telling
391
- * of it was saved comes first), else the newest. */
392
- const cutOf = (cuts) => cuts.find((cut) => !cut.told) ?? cuts.at(-1) ?? null;
393
306
  async function relaunchOn(c, scope, api, slot, overrides) {
394
- const config = await configOf(c, scope.read, scope.cid, scope.context);
307
+ const config = await scopeConfig(c, scope);
395
308
  const refusal = relaunchRefusal(config.policy, overrides);
396
309
  if (refusal)
397
310
  throw new BrowserFailureError(refusal);
398
311
  await refuseHeld(c, scope, currentRecord(await stateOf(c, scope), scope.plane));
399
312
  // A session the host assigned is the only one: refused before anything is released.
400
- if ((await providerOf(c, scope.read, scope.cid, scope.plane, scope.context)).caps.fixedSession)
313
+ if ((await scopeProvider(c, scope)).caps.fixedSession)
401
314
  throw new BrowserFailureError(FIXED_SESSION_RELAUNCH);
402
315
  // The relaunch's session is chosen in a memo before its create commits: a rerun runs on it or says
403
316
  // session_replaced, never a second launch; a memo with no record yet is an uncommitted create and goes ahead.
@@ -526,18 +439,13 @@ function portFor(c, api, context) {
526
439
  });
527
440
  const record = currentRecord(await stateOf(c, scope), scope.plane);
528
441
  if (record)
529
- await emit(c, scope.cid, (await configOf(c, scope.read, scope.cid, scope.context)).label, record, "updated", await providerOf(c, scope.read, scope.cid, scope.plane, scope.context));
442
+ await emit(c, scope.cid, (await scopeConfig(c, scope)).label, record, "updated", await scopeProvider(c, scope));
530
443
  },
531
444
  unreachable: () => c.serial.run(key, async () => {
532
445
  const record = currentRecord(await stateOf(c, scope), scope.plane);
533
- // A session held for a person is theirs: custody never releases it on its own.
534
- if (record?.state === "held")
535
- return { released: false, lastUrl: record.lastUrl, kept: "held" };
536
- if (!record || !open(record))
446
+ if (!record || (record.state !== "held" && !open(record)))
537
447
  return { released: false, lastUrl: record?.lastUrl ?? null };
538
- // A session a person drives or watches through the live view is theirs: custody never releases it on its own.
539
- const person = personOn(c.options.gates ?? drivingGates, record.tag);
540
- const kept = person && keptFor(person);
448
+ const kept = keptReason(record, c.options.gates ?? drivingGates);
541
449
  if (kept)
542
450
  return { released: false, lastUrl: record.lastUrl, kept };
543
451
  await scope.commit(async (tx) => {
@@ -581,7 +489,7 @@ function portFor(c, api, context) {
581
489
  const record = currentRecord(await stateOf(c, scope), scope.plane);
582
490
  if (record?.state !== "live" && record?.state !== "held")
583
491
  return false;
584
- return markEnded(c, scope, record, await providerOf(c, scope.read, scope.cid, scope.plane, scope.context));
492
+ return markEnded(c, scope, record, await scopeProvider(c, scope));
585
493
  },
586
494
  handoff: async (ask) => {
587
495
  const person = c.options.handoff;
@@ -595,7 +503,7 @@ function portFor(c, api, context) {
595
503
  if (interactionId === undefined) {
596
504
  const { tag, sessionId } = await port.hold(ask.requestId);
597
505
  const asked = await (async () => {
598
- const provider = await providerOf(c, scope.read, scope.cid, scope.plane, scope.context);
506
+ const provider = await scopeProvider(c, scope);
599
507
  const view = provider.liveView ? await provider.liveView({ id: sessionId, tag }).catch(() => null) : null;
600
508
  const liveView = view && hostLiveView(view, c.redact);
601
509
  return person.request({ requestId: ask.requestId, sessionTag: tag, sessionId, liveView, instruction: ask.instruction, completionCondition: ask.completionCondition }, scope.signal);
@@ -750,7 +658,7 @@ const withSessionTime = (own, charged) => {
750
658
  };
751
659
  function toolsFor(c, impls) {
752
660
  return BROWSER_TOOLS
753
- .filter((contract) => impls[contract.name] && (contract.listedWhen !== "downloads" || c.options.workspace) && (contract.listedWhen !== "upload" || c.options.files || c.options.workspace) && (contract.listedWhen !== "handoff" || c.options.handoff))
661
+ .filter((contract) => impls[contract.name] && listedFor(contract, { downloads: !!c.options.workspace, upload: !!(c.options.files || c.options.workspace), handoff: !!c.options.handoff }))
754
662
  .map((contract) => defineTool({
755
663
  name: contract.name,
756
664
  description: contract.description,
@@ -773,7 +681,7 @@ function toolsFor(c, impls) {
773
681
  // A charge that cannot be committed now is carried by the next one.
774
682
  const usage = withSessionTime(out.usage, await chargeCall(c, api, context).catch(() => null));
775
683
  return {
776
- ...forModel(out.content.map((item) => item.type === "text" ? { ...item, text: c.redact(item.text) } : item)),
684
+ ...forModel(redactContent(out.content, c.redact)),
777
685
  ...(out.isError ? { isError: true } : {}),
778
686
  ...(out.details ? { details: redactDeep(out.details, c.redact) } : {}),
779
687
  ...(usage ? { usage: usage } : {}),
@@ -858,7 +766,7 @@ function siteTool(c, sites) {
858
766
  executionMode: contract.executionMode,
859
767
  execute: async (args, api, context) => {
860
768
  const out = await useWebsite(args, sites.port, sites.listing, { signal: context.abortSignal ?? new AbortController().signal, runChild: childConversation(c, api, context) });
861
- return { ...forModel(out.content.map((item) => item.type === "text" ? { ...item, text: c.redact(item.text) } : item)), ...(out.isError ? { isError: true } : {}) };
769
+ return { ...forModel(redactContent(out.content, c.redact)), ...(out.isError ? { isError: true } : {}) };
862
770
  },
863
771
  });
864
772
  }
@@ -4,9 +4,8 @@
4
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
5
  // conversation's. The host takes it back itself, once, when the task's browser closes; after that the session's own
6
6
  // failure() answers every create. A second create while another custody holds it is a refusal: the run has one browser.
7
- import { BrowserFailureError } from "../core/custody.js";
7
+ import { BrowserFailureError, refusedError } from "../core/custody.js";
8
8
  import { FAILURE_CODES } from "../core/failures.js";
9
- const refused = (message) => new BrowserFailureError({ ok: false, code: "refused", retryable: false, effect: "none", message });
10
9
  /** A host session types a failure the model should read as an error carrying `failure`; the tool loop takes it as is. */
11
10
  function typed(error) {
12
11
  const failure = error?.failure;
@@ -42,7 +41,7 @@ export function assignedSessionProvider(input) {
42
41
  if (ended)
43
42
  throw new BrowserFailureError(ended);
44
43
  if (assignedCustody.heldBy !== null && assignedCustody.heldBy !== spec.tag)
45
- throw refused("This task has one browser, the website session assigned to it, and it is already open; keep using it.");
44
+ throw refusedError("This task has one browser, the website session assigned to it, and it is already open; keep using it.");
46
45
  assignedCustody.heldBy = spec.tag;
47
46
  assignedCustody.letGo.delete(spec.tag);
48
47
  return { id: session.id, tag: spec.tag };
@@ -13,7 +13,9 @@ export const SEARCH_QUERY_MAX = 200;
13
13
  export const SEARCH_RESULTS_MAX = 25;
14
14
  /** Into `downloadPath` (default `downloads`, Browserbase's synced-downloads rule); the socket stays open. */
15
15
  export const setDownloadBehavior = (url, options = {}) => cdpCall(url, "Browser.setDownloadBehavior", { behavior: "allow", downloadPath: options.downloadPath ?? "downloads", eventsEnabled: true }, options.timeoutMs);
16
- const CAPS = { timeoutModel: "wall-clock", maxLifetimeS: 21_600, survivesDisconnect: true, releaseIsAsync: true, profiles: true, extension: "uploaded-per-launch", settings: { proxies: true, verified: true, geolocation: true, region: true, context: true } };
16
+ const CAPS = { timeoutModel: "wall-clock", maxLifetimeS: 21_600, survivesDisconnect: true, releaseIsAsync: true, profiles: true, extension: "uploaded-per-launch", settings: { proxies: true, verified: true, geolocation: true, region: true, context: true },
17
+ // A session is created with `allowedDomains` from the policy's allow list, which Browserbase enforces.
18
+ navigationAllow: true };
17
19
  const notFound = (e) => e?.status === 404;
18
20
  /** One signal for whichever of these there is (a store may call `make` without its limit). */
19
21
  const stopWhen = (...signals) => { const some = signals.filter((s) => s !== undefined); return some.length > 1 ? AbortSignal.any(some) : some[0]; };
@@ -79,8 +81,7 @@ export function browserbaseProvider(options = {}) {
79
81
  applyBrowserbaseNoProxy(env);
80
82
  const mod = await import(["@browserbasehq", "sdk"].join("/"));
81
83
  const Browserbase = mod.default ?? mod.Browserbase;
82
- const fetch = await directFetch();
83
- return new Browserbase({ apiKey, baseURL: baseUrl, ...(fetch ? { fetch } : {}) });
84
+ return new Browserbase({ apiKey, baseURL: baseUrl, fetch: await directFetch() });
84
85
  })());
85
86
  const extension = () => options.extensionId
86
87
  ? options.extensionId()
@@ -270,7 +271,7 @@ export function browserbaseProvider(options = {}) {
270
271
  const found = (await rec?.list(ref.id))?.downloads?.find((d) => String(d.pageId) === id && d.status === "COMPLETED" && d.downloadUrl);
271
272
  if (!found?.downloadUrl)
272
273
  throw new Error(`no rendered recording ${id} for session ${ref.id}`);
273
- const response = await ((await directFetch()) ?? fetch)(found.downloadUrl);
274
+ const response = await (await directFetch())(found.downloadUrl);
274
275
  if (!response.ok || !response.body)
275
276
  throw new Error(`recording download answered ${response.status}`);
276
277
  return response.body;
@@ -4,39 +4,12 @@ import { lstat, mkdir, mkdtemp, open, readdir, readFile, readlink, rm, stat, sym
4
4
  import os from "node:os";
5
5
  import { pipeline } from "node:stream/promises";
6
6
  import path from "node:path";
7
- import { BrowserFailureError, PROFILE_NAME } from "../core/custody.js";
7
+ import { BrowserFailureError, PROFILE_NAME, refusedError } from "../core/custody.js";
8
+ import { browserFailure } from "../core/failures.js";
8
9
  import { cdpCall } from "./cdp-call.js";
9
10
  import { chromeTail, openChromeStderr, watchChromeStderr } from "./chrome-stderr.js";
10
11
  import { claimWriter, freeWriter, noteWriter } from "./profiles.js";
11
- /** Stagehand 4.1.0's DEFAULT_CHROME_FLAGS (packages/sdk-ts/src/browser/localBrowser.ts, MIT, see NOTICE). 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
- "--remote-allow-origins=*",
38
- "--enable-features=WebMCPTesting,DevToolsWebMCPSupport",
39
- ];
12
+ import { chromeArgs } from "./chrome-args.js";
40
13
  const CAPS = { timeoutModel: "wall-clock", maxLifetimeS: 86_400, survivesDisconnect: true, releaseIsAsync: false, profiles: false, extension: "loaded-locally", settings: { proxies: false, verified: false, geolocation: false, region: false, context: false } };
41
14
  const downloadsDir = (profileRoot, tag) => path.join(profileDir(profileRoot, tag) + ".downloads");
42
15
  const READY_MS = 20_000;
@@ -134,7 +107,6 @@ const profileDir = (root, tag) => {
134
107
  return path.join(root, tag);
135
108
  };
136
109
  const savedDir = (root, name) => path.join(root, ".profiles", name);
137
- const refusal = (message) => new BrowserFailureError({ ok: false, code: "refused", retryable: false, effect: "none", message });
138
110
  /** A copy of a profile another Chrome is writing: that Chrome renames, truncates and deletes its journals and temp files
139
111
  * all the time. A file gone by the time it is reached is skipped. `fs.cp` fails the whole copy on it, and `fs.copyFile`
140
112
  * never returns for a file truncated while it copies (libuv's sendfile loop makes no progress and does not stop), so
@@ -172,7 +144,7 @@ export async function copyProfile(from, to, signal) {
172
144
  * it, so release removes the link and never the profile; not saving, it is a copy that leaves the profile as it was. */
173
145
  async function prepareProfile(root, dir, profile, tag, owner, signal, remove) {
174
146
  if (!PROFILE_NAME.test(profile.name))
175
- throw refusal("browser profile: a profile name is 1 to 64 characters of letters, digits, dot, underscore and dash, starting with a letter or digit. No session was started.");
147
+ throw refusedError("browser profile: a profile name is 1 to 64 characters of letters, digits, dot, underscore and dash, starting with a letter or digit. No session was started.");
176
148
  const saved = savedDir(root, profile.name);
177
149
  await rm(dir, { recursive: true, force: true });
178
150
  if (!profile.save) {
@@ -193,7 +165,7 @@ async function prepareProfile(root, dir, profile, tag, owner, signal, remove) {
193
165
  try {
194
166
  const lock = await readlink(path.join(saved, "SingletonLock")).then((value) => /^(.*)-(\d+)$/.exec(value), () => null);
195
167
  if (lock && lock[1] === os.hostname() && alive(Number(lock[2])))
196
- throw refusal(`browser profile "${profile.name}": a Chrome process (${lock[2]}) is using this profile. No session was started.`);
168
+ throw refusedError(`browser profile "${profile.name}": a Chrome process (${lock[2]}) is using this profile. No session was started.`);
197
169
  await mkdir(path.join(saved, "Default"), { recursive: true });
198
170
  await symlink(path.resolve(saved), dir, "dir");
199
171
  }
@@ -398,8 +370,7 @@ export function cdpProvider(options, internals = {}) {
398
370
  let child;
399
371
  try {
400
372
  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",
373
+ ...chromeArgs({ userDataDir: dir, viewport: spec.viewport, headless, sandbox }), ...args, "about:blank",
403
374
  ], { stdio: ["ignore", "ignore", stderrFd ?? "ignore"], detached: true, ...(tmp ? { env: { ...process.env, TMPDIR: tmp } } : {}) });
404
375
  }
405
376
  catch (error) {
@@ -424,7 +395,7 @@ export function cdpProvider(options, internals = {}) {
424
395
  const tail = chromeTail(tmp);
425
396
  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
397
  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}` })
398
+ ? new BrowserFailureError(browserFailure("browser_unavailable", `${message}\n${SANDBOX_HINT}`))
428
399
  : new Error(message);
429
400
  });
430
401
  if (child.pid === undefined) {
@@ -0,0 +1,18 @@
1
+ /** The directory Stagehand loads its extension from in a local Chrome (`Extensions.loadUnpacked`), resolved as Stagehand does. */
2
+ export declare function extensionDirectory(): string;
3
+ /** The Origin the extension's own DevTools socket carries. Chrome names an unpacked extension by the SHA-256 of its real path: the
4
+ * 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
5
+ * opened to every Origin instead. */
6
+ export declare function extensionOrigin(directory?: string): string;
7
+ /** Every argument a local Chrome is started with, but the page to open. The DevTools socket is the whole browser: Stagehand's own
8
+ * launcher allows every Origin (`*`), so a page the agent visits could drive the browser if it learned the socket's URL. Only the
9
+ * extension's socket carries an Origin (Node's clients send none), so only that Origin is allowed. */
10
+ export declare function chromeArgs(options: {
11
+ userDataDir: string;
12
+ viewport: {
13
+ width: number;
14
+ height: number;
15
+ };
16
+ headless?: boolean;
17
+ sandbox: boolean;
18
+ }): string[];