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

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 (104) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +33 -0
  4. package/README.md +329 -2
  5. package/dist/coding-agent-local.d.ts +16 -0
  6. package/dist/coding-agent-local.js +138 -0
  7. package/dist/coding-agent.d.ts +78 -0
  8. package/dist/coding-agent.js +446 -0
  9. package/dist/core/contract.d.ts +26 -0
  10. package/dist/core/contract.js +154 -0
  11. package/dist/core/custody.d.ts +111 -0
  12. package/dist/core/custody.js +122 -0
  13. package/dist/core/decisions.d.ts +43 -0
  14. package/dist/core/decisions.js +4 -0
  15. package/dist/core/downloads.d.ts +35 -0
  16. package/dist/core/downloads.js +131 -0
  17. package/dist/core/effects.d.ts +63 -0
  18. package/dist/core/effects.js +256 -0
  19. package/dist/core/evidence.d.ts +43 -0
  20. package/dist/core/evidence.js +6 -0
  21. package/dist/core/failures.d.ts +28 -0
  22. package/dist/core/failures.js +59 -0
  23. package/dist/core/find.d.ts +32 -0
  24. package/dist/core/find.js +179 -0
  25. package/dist/core/guard.d.ts +6 -0
  26. package/dist/core/guard.js +24 -0
  27. package/dist/core/host.d.ts +279 -0
  28. package/dist/core/host.js +2 -0
  29. package/dist/core/images.d.ts +37 -0
  30. package/dist/core/images.js +60 -0
  31. package/dist/core/lease.d.ts +16 -0
  32. package/dist/core/lease.js +30 -0
  33. package/dist/core/receipts.d.ts +19 -0
  34. package/dist/core/receipts.js +22 -0
  35. package/dist/core/redact.d.ts +13 -0
  36. package/dist/core/redact.js +83 -0
  37. package/dist/core/session-control.d.ts +25 -0
  38. package/dist/core/session-control.js +75 -0
  39. package/dist/core/sites.d.ts +33 -0
  40. package/dist/core/sites.js +102 -0
  41. package/dist/core/tools.d.ts +37 -0
  42. package/dist/core/tools.js +170 -0
  43. package/dist/core/uri.d.ts +11 -0
  44. package/dist/core/uri.js +37 -0
  45. package/dist/core/usage.d.ts +38 -0
  46. package/dist/core/usage.js +44 -0
  47. package/dist/core/web.d.ts +98 -0
  48. package/dist/core/web.js +327 -0
  49. package/dist/driver/stagehand.d.ts +25 -0
  50. package/dist/driver/stagehand.js +141 -0
  51. package/dist/durable-result.d.ts +6 -0
  52. package/dist/durable-result.js +2 -0
  53. package/dist/durable.d.ts +75 -0
  54. package/dist/durable.js +484 -0
  55. package/dist/index.d.ts +18 -0
  56. package/dist/index.js +19 -0
  57. package/dist/providers/browserbase-net.d.ts +13 -0
  58. package/dist/providers/browserbase-net.js +96 -0
  59. package/dist/providers/browserbase.d.ts +152 -0
  60. package/dist/providers/browserbase.js +262 -0
  61. package/dist/providers/cdp-call.d.ts +6 -0
  62. package/dist/providers/cdp-call.js +25 -0
  63. package/dist/providers/cdp.d.ts +48 -0
  64. package/dist/providers/cdp.js +353 -0
  65. package/dist/providers/http.d.ts +2 -0
  66. package/dist/providers/http.js +21 -0
  67. package/dist/providers/kernel.d.ts +49 -0
  68. package/dist/providers/kernel.js +246 -0
  69. package/dist/providers/shared.d.ts +47 -0
  70. package/dist/providers/shared.js +82 -0
  71. package/dist/recorder/credential.d.ts +9 -0
  72. package/dist/recorder/credential.js +49 -0
  73. package/dist/recorder/follow.d.ts +26 -0
  74. package/dist/recorder/follow.js +138 -0
  75. package/dist/recorder/frames.d.ts +80 -0
  76. package/dist/recorder/frames.js +309 -0
  77. package/dist/recorder/index.d.ts +3 -0
  78. package/dist/recorder/index.js +6 -0
  79. package/dist/recorder/jpeg.d.ts +5 -0
  80. package/dist/recorder/jpeg.js +34 -0
  81. package/dist/store.d.ts +56 -0
  82. package/dist/store.js +196 -0
  83. package/dist/testing/backend.d.ts +231 -0
  84. package/dist/testing/backend.js +414 -0
  85. package/dist/testing/driver.d.ts +28 -0
  86. package/dist/testing/driver.js +32 -0
  87. package/dist/testing/index.d.ts +4 -0
  88. package/dist/testing/index.js +4 -0
  89. package/dist/testing/pages.d.ts +3 -0
  90. package/dist/testing/pages.js +10 -0
  91. package/dist/testing/sentinels.d.ts +29 -0
  92. package/dist/testing/sentinels.js +38 -0
  93. package/dist/vendor/stagehand-facade/contract.d.ts +348 -0
  94. package/dist/vendor/stagehand-facade/contract.js +155 -0
  95. package/dist/vendor/stagehand-facade/runtime.d.ts +90 -0
  96. package/dist/vendor/stagehand-facade/runtime.js +1640 -0
  97. package/dist/vendor/stagehand-facade/screenshot-transport.d.ts +15 -0
  98. package/dist/vendor/stagehand-facade/screenshot-transport.js +51 -0
  99. package/dist/vendor/stagehand-facade/tools.d.ts +31 -0
  100. package/dist/vendor/stagehand-facade/tools.js +139 -0
  101. package/dist/web.d.ts +41 -0
  102. package/dist/web.js +38 -0
  103. package/package.json +123 -4
  104. package/src/vendor/stagehand-facade/UPSTREAM.json +24 -0
@@ -0,0 +1,484 @@
1
+ import { configure, defineDoc, defineExtension, defineTool } from "@earendil-works/pi-durable";
2
+ import { BROWSER_TOOL_NAMES, BROWSER_TOOLS, browserSection, WEB_TOOL_NAMES } from "./core/contract.js";
3
+ import { BrowserFailureError, closeDriver, currentRecord, custodyTools, newSessionRecord, notices, NAVIGATION_CAP, relaunchRefusal, SESSION_REPLACED, sessionSpec } from "./core/custody.js";
4
+ import { forModel } from "./durable-result.js";
5
+ import { EffectObserver, effectDecider, observerFailure } from "./core/effects.js";
6
+ import { classifyBrowserError } from "./core/failures.js";
7
+ import { pageTools } from "./core/tools.js";
8
+ import { useWebsite, useWebsiteContract } from "./core/sites.js";
9
+ import { leaseTag } from "./core/lease.js";
10
+ import { createRedactor, redactDeep, scrubPageUrl } from "./core/redact.js";
11
+ import { CREATE_DEADLINE_MS, DEFAULT_BROWSER_POLICY, idleTracker, keyedSerializer, providerKeyValues } from "./core/session-control.js";
12
+ import { custodyStore, now } from "./store.js";
13
+ import { resolvePrices, sessionCharge } from "./core/usage.js";
14
+ export { createWebExtension } from "./web.js";
15
+ export { CONFIRM_POLLS, RELEASE_ATTEMPTS } from "./store.js";
16
+ const PLANE = "default";
17
+ const UNCONFIGURED = { label: "", run: "", policy: DEFAULT_BROWSER_POLICY };
18
+ const NOT_CONFIGURED = new BrowserFailureError({ ok: false, code: "browser_unavailable", retryable: false, effect: "none", message: "This conversation has no browser configuration, so no browser can be launched here; use web_fetch or another source." });
19
+ const open = (record) => record?.state === "live" || record?.state === "creating";
20
+ // A child gets the browser and web tools only, never use_website, so it cannot start children of its own.
21
+ const CHILD_TOOLS = new Set([...BROWSER_TOOL_NAMES, ...WEB_TOOL_NAMES]);
22
+ export function createBrowserExtension(options) {
23
+ const name = options.name ?? "browser";
24
+ const redact = createRedactor(() => providerKeyValues(process.env, options.redact?.values));
25
+ const Config = defineDoc({ kind: `${name}.config`, version: 1, scope: "conversation", history: "latest", fork: "current", initial: () => structuredClone(UNCONFIGURED) });
26
+ // A fork starts with no sessions: it never shares a live browser.
27
+ const Children = defineDoc({ kind: `${name}.children`, version: 1, scope: "conversation", history: "latest", fork: "current", initial: () => ({ byRequest: {} }) });
28
+ const Sessions = defineDoc({ kind: `${name}.sessions`, version: 1, scope: "conversation", history: "latest", fork: "initial", initial: () => ({ current: {}, sessions: [], notice: null }) });
29
+ const attachments = new Map();
30
+ const observers = new Map();
31
+ const { run: serialize } = keyedSerializer();
32
+ const idle = idleTracker({ idleMs: DEFAULT_BROWSER_POLICY.idleReleaseS * 1000, onIdle: (cid, fired, idleMs) => void releaseIdle(cid, fired, idleMs).catch(() => undefined) });
33
+ let opened = null;
34
+ const configOf = async (read, cid, context) => {
35
+ const config = await read.snapshot(Config, cid, context);
36
+ if (!config?.run)
37
+ throw NOT_CONFIGURED;
38
+ return config;
39
+ };
40
+ const providerOf = async (read, cid, plane, context) => options.provider({ conversationId: cid, plane, config: await configOf(read, cid, context) });
41
+ const rowOf = (cid, record) => ({ tag: record.tag, conversationId: cid, plane: record.plane, provider: record.provider, resourceId: record.resourceId, state: record.state });
42
+ async function emitObserver(row) {
43
+ try {
44
+ await options.onObserver?.(row);
45
+ }
46
+ catch { }
47
+ }
48
+ async function emit(cid, label, record, change, provider) {
49
+ if (!options.onSession)
50
+ return;
51
+ try {
52
+ const ref = record.resourceId === null ? null : { id: record.resourceId, tag: record.tag };
53
+ const view = change !== "released" && ref && provider?.liveView ? await provider.liveView(ref) : null;
54
+ // 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
55
+ // scrubbed, since its query can carry a credential.
56
+ const liveView = view && { ...view, pages: view.pages.map((page) => ({ ...page, url: page.url === null ? null : scrubPageUrl(page.url, redact), title: page.title === null ? null : redact(page.title) })) };
57
+ await options.onSession({ conversationId: cid, label, session: record, liveView }, change);
58
+ }
59
+ catch { }
60
+ }
61
+ /** Class name and redacted message only: a vendor SDK's error text can repeat the request's credentials. */
62
+ const scrubbed = (error) => Object.assign(new Error(redact(error instanceof Error ? error.message : String(error))), { name: error instanceof Error ? error.name : "Error" });
63
+ const prices = resolvePrices(options.prices);
64
+ const priceState = prices.sessionUsdPerHour === null ? "unpriced" : "priced";
65
+ const meter = (spent, at, final = false) => {
66
+ const charged = sessionCharge(spent, at, prices, priceState, final);
67
+ return { spent: { ...charged.spent, state: charged.usage.state }, usage: charged.usage };
68
+ };
69
+ const { Inventory, move, addNotice, begin, requestRelease, bindByTag, emitReleased, ReleaseTask, reconcileAll } = custodyStore({ name, Config, Sessions, providerOf, emit, meter, scrubbed, createDeadlineMs: options.createDeadlineMs ?? CREATE_DEADLINE_MS });
70
+ const stateOf = async (scope) => (await scope.read.snapshot(Sessions, scope.cid, scope.context)) ?? { current: {}, sessions: [], notice: null };
71
+ const failure = (error, scope) => error instanceof BrowserFailureError ? error : new BrowserFailureError(classifyBrowserError(error, false, { aborted: scope.signal.aborted }));
72
+ async function detach(tag) {
73
+ const driver = attachments.get(tag);
74
+ attachments.delete(tag);
75
+ observers.get(tag)?.close();
76
+ observers.delete(tag);
77
+ if (driver)
78
+ await closeDriver(driver);
79
+ }
80
+ /** Let go of a dead driver connection and nothing else: a healthy observer stays attached, so a page that sends
81
+ * something before the next call is still held. When the observer is dead too, both go. */
82
+ async function detachDriver(tag) {
83
+ if (observers.get(tag)?.closed)
84
+ return detach(tag);
85
+ const driver = attachments.get(tag);
86
+ attachments.delete(tag);
87
+ if (driver)
88
+ await closeDriver(driver);
89
+ }
90
+ async function attachLive(scope, record) {
91
+ const held = attachments.get(record.tag);
92
+ // An observer whose socket closed holds nothing: driver and observer are attached again together.
93
+ if (held && !observers.get(record.tag)?.closed)
94
+ return held;
95
+ if (held)
96
+ await detach(record.tag);
97
+ const provider = await providerOf(scope.read, scope.cid, scope.plane, scope.context);
98
+ const ref = { id: record.resourceId, tag: record.tag };
99
+ try {
100
+ return await connect(scope, provider, ref);
101
+ }
102
+ catch (error) {
103
+ if (!(await markEnded(scope, record, provider)))
104
+ throw failure(error, scope);
105
+ return null;
106
+ }
107
+ }
108
+ async function connect(scope, provider, ref) {
109
+ const config = await configOf(scope.read, scope.cid, scope.context);
110
+ const { actions: policy, batchTimeoutMs } = config.policy;
111
+ const target = await provider.attach(ref, scope.signal);
112
+ const driver = await options.driver(target, scope.signal, { batchTimeoutMs });
113
+ let unattached = null;
114
+ // A healthy observer that outlived its driver's connection is kept, not opened a second time.
115
+ const kept = observers.get(ref.tag);
116
+ const open = options.openObserver ?? EffectObserver.open.bind(EffectObserver);
117
+ const observer = kept && !kept.closed ? kept : policy ? await open(target, policy === "allow" ? null : effectDecider(policy, options.decisions), batchTimeoutMs).catch((error) => { unattached = error; return null; }) : null;
118
+ // A policy that holds requests never degrades to browsing without the hold.
119
+ if (policy && policy !== "allow" && !observer) {
120
+ await closeDriver(driver);
121
+ throw new BrowserFailureError({ ok: false, code: "browser_unavailable", retryable: true, effect: "none", message: "The browser's request observer could not attach, and this run's action policy needs it to hold requests; the browser is not used without it." });
122
+ }
123
+ observers.set(ref.tag, observer);
124
+ attachments.set(ref.tag, driver);
125
+ if (policy === "allow" && !observer)
126
+ await emitObserver({ conversationId: scope.cid, label: config.label, tag: ref.tag, session_id: ref.id, policy, code: observerFailure(unattached) });
127
+ return driver;
128
+ }
129
+ async function markEnded(scope, record, provider) {
130
+ const status = await provider.status({ id: record.resourceId, tag: record.tag }, scope.signal).catch(() => "running");
131
+ if (status !== "gone" && status !== "stopped")
132
+ return false;
133
+ await scope.commit((tx) => move(tx, rowOf(scope.cid, record), { state: "released", reason: "ended", at: now() }));
134
+ await detach(record.tag);
135
+ await emitReleased(scope.cid, record.tag, scope.read, scope.context);
136
+ return true;
137
+ }
138
+ async function settleCreating(scope, record) {
139
+ const provider = await providerOf(scope.read, scope.cid, scope.plane, scope.context);
140
+ try {
141
+ await bindByTag(provider, rowOf(scope.cid, record), scope.commit, scope.signal);
142
+ }
143
+ catch (error) {
144
+ throw failure(error, scope);
145
+ }
146
+ }
147
+ async function create(scope, overrides, presetTag) {
148
+ const config = await configOf(scope.read, scope.cid, scope.context);
149
+ const provider = await options.provider({ conversationId: scope.cid, plane: scope.plane, config });
150
+ const tag = presetTag ?? leaseTag("ar", config.run, scope.cid, (await stateOf(scope)).sessions.length + 1);
151
+ const spec = sessionSpec(config, tag, overrides);
152
+ const record = newSessionRecord({ plane: scope.plane, tag, provider: provider.name, spec, at: now() });
153
+ const row = rowOf(scope.cid, record);
154
+ await scope.commit(async (tx) => {
155
+ const state = await tx.doc(Sessions, scope.cid);
156
+ state.sessions.push(record);
157
+ state.current[scope.plane] = state.sessions.length - 1;
158
+ await begin(tx, row);
159
+ });
160
+ // An answer lost on the way back is not a session that never started: it is settled by its tag.
161
+ const ref = await provider.create(spec, scope.signal).then(async (made) => { await scope.commit((tx) => move(tx, row, { state: "live", resourceId: made.id, at: now() })); return made; }, async (error) => (await bindByTag(provider, row, scope.commit, scope.signal, await provider.findByTag(tag, scope.signal).catch(() => []))) ?? Promise.reject(failure(error, scope)));
162
+ const live = { ...record, state: "live", resourceId: ref.id };
163
+ try {
164
+ const driver = await connect(scope, provider, ref);
165
+ await emit(scope.cid, config.label, live, "launched", provider);
166
+ return { record: live, driver };
167
+ }
168
+ catch (error) {
169
+ throw failure(error, scope);
170
+ }
171
+ }
172
+ async function acquire(scope) {
173
+ let note = null;
174
+ for (let turn = 0; turn < 4; turn += 1) {
175
+ const record = currentRecord(await stateOf(scope), scope.plane);
176
+ if (record?.state === "live") {
177
+ const driver = await attachLive(scope, record);
178
+ if (driver)
179
+ return { record, driver, note };
180
+ note = notices.ended(record.lastUrl);
181
+ }
182
+ else if (record?.state === "creating") {
183
+ await settleCreating(scope, record);
184
+ }
185
+ else {
186
+ return { ...(await create(scope, {})), note };
187
+ }
188
+ }
189
+ throw new Error(`browser custody for conversation ${scope.cid} did not settle`);
190
+ }
191
+ /** Custody's notice is kept in the call's memo before it is cleared, so a call rerun after a crash still tells it. */
192
+ async function attached(scope, record, driver, note) {
193
+ const state = await stateOf(scope);
194
+ const notice = await scope.keep("notice", [note, state.notice].filter(Boolean).join(" "));
195
+ if (state.notice !== null)
196
+ await scope.commit(async (tx) => { (await tx.doc(Sessions, scope.cid)).notice = null; });
197
+ const fresh = state.sessions.find((r) => r.tag === record.tag) ?? record;
198
+ const interrupted = [...state.sessions].reverse().find((r) => r.plane === scope.plane && r.pendingEffect !== null)?.pendingEffect ?? null;
199
+ const recorded = Boolean((await providerOf(scope.read, scope.cid, scope.plane, scope.context)).recordings);
200
+ return { driver, tag: record.tag, sessionId: fresh.resourceId, record: fresh, notice: notice || null, interrupted, recorded, effects: observers.get(record.tag) ?? null };
201
+ }
202
+ async function releaseRecord(scope, record, reason) {
203
+ await scope.commit((tx) => requestRelease(tx, rowOf(scope.cid, record), reason, now()));
204
+ await detach(record.tag);
205
+ }
206
+ const editRecords = (scope, edit) => scope.commit(async (tx) => { const state = await tx.doc(Sessions, scope.cid); edit(state.sessions.filter((r) => r.plane === scope.plane), state); });
207
+ function portFor(api, context) {
208
+ const memo = (slot) => `${name}:${slot}:${PLANE}`;
209
+ const scope = { cid: api.conversationId, plane: PLANE, context, read: api, signal: context.abortSignal ?? new AbortController().signal, commit: (change) => api.commit(change, context), keep: async (slot, value) => {
210
+ // An earlier attempt's text comes first; an empty one is never memoized, so it cannot shadow a later notice.
211
+ const prior = await api.memo(memo(slot), context);
212
+ if (prior !== undefined)
213
+ return [prior, value].filter(Boolean).join(" ");
214
+ return value ? api.memo(memo(slot), value, context) : "";
215
+ } };
216
+ const key = `${scope.cid}:${scope.plane}`;
217
+ return {
218
+ session: () => serialize(key, async () => {
219
+ const ran = await api.memo(memo("ran"), context);
220
+ if (ran !== undefined) {
221
+ const record = (await stateOf(scope)).sessions.find((r) => r.tag === ran);
222
+ const driver = record?.state === "live" ? await attachLive(scope, record) : null;
223
+ if (!record || !driver)
224
+ throw new BrowserFailureError(SESSION_REPLACED);
225
+ return attached(scope, record, driver, null);
226
+ }
227
+ const { record, driver, note } = await acquire(scope);
228
+ await api.memo(memo("ran"), record.tag, context);
229
+ return attached(scope, record, driver, note);
230
+ }),
231
+ relaunch: (overrides) => serialize(key, async () => {
232
+ const config = await configOf(scope.read, scope.cid, scope.context);
233
+ const refusal = relaunchRefusal(config.policy, overrides);
234
+ if (refusal)
235
+ throw new BrowserFailureError(refusal);
236
+ // The relaunch's session is chosen in a memo before its create commits: a rerun runs on it or says
237
+ // session_replaced, never a second launch; a memo with no record yet is an uncommitted create and goes ahead.
238
+ const find = async (tag) => (await stateOf(scope)).sessions.find((r) => r.tag === tag);
239
+ const launched = await api.memo(memo("relaunch"), context);
240
+ let mine = await find(launched);
241
+ if (mine) {
242
+ if (mine.state === "creating") {
243
+ await settleCreating(scope, mine);
244
+ mine = await find(launched);
245
+ }
246
+ const driver = mine?.state === "live" ? await attachLive(scope, mine) : null;
247
+ if (!mine || !driver)
248
+ throw new BrowserFailureError(SESSION_REPLACED);
249
+ return attached(scope, mine, driver, null);
250
+ }
251
+ const state = await stateOf(scope);
252
+ const tag = launched ?? await api.memo(memo("relaunch"), leaseTag("ar", config.run, scope.cid, state.sessions.length + 1), context);
253
+ const old = currentRecord(state, scope.plane);
254
+ if (old && open(old) && old.tag !== tag)
255
+ await releaseRecord(scope, old, "relaunch");
256
+ const made = await create(scope, overrides, tag);
257
+ return attached(scope, made.record, made.driver, null);
258
+ }),
259
+ release: () => serialize(key, async () => {
260
+ const record = currentRecord(await stateOf(scope), scope.plane);
261
+ if (!record || !open(record))
262
+ return { released: record?.state === "releasing", sessionId: record?.resourceId ?? null };
263
+ await releaseRecord(scope, record, "tool");
264
+ return { released: true, sessionId: record.resourceId };
265
+ }),
266
+ dispatching: (effect) => editRecords(scope, (records, state) => {
267
+ const record = currentRecord(state, scope.plane);
268
+ if (record)
269
+ record.pendingEffect = { ...effect, url: effect.url === null ? null : scrubPageUrl(effect.url, redact), at: now(), sent: [] };
270
+ }),
271
+ journal: (row) => editRecords(scope, (records, state) => {
272
+ const pending = currentRecord(state, scope.plane)?.pendingEffect;
273
+ if (!pending)
274
+ return;
275
+ const sent = pending.sent ?? (pending.sent = []);
276
+ const scrubbed = { ...row, origin: redact(row.origin), path: redact(row.path) };
277
+ const at = sent.findIndex((r) => r.requestId === row.requestId);
278
+ if (at === -1)
279
+ sent.push(scrubbed);
280
+ else
281
+ sent[at] = scrubbed;
282
+ }),
283
+ settle: async () => {
284
+ if (!(await stateOf(scope)).sessions.some((r) => r.plane === scope.plane && r.pendingEffect !== null))
285
+ return;
286
+ await editRecords(scope, (records) => { for (const record of records)
287
+ record.pendingEffect = null; });
288
+ },
289
+ navigated: async (page) => {
290
+ // A page URL can carry a credential in any query value, its fragment or its userinfo: scrubbed before it is
291
+ // committed or reported.
292
+ const url = scrubPageUrl(page, redact);
293
+ await editRecords(scope, (records, state) => {
294
+ const record = currentRecord(state, scope.plane);
295
+ if (!record)
296
+ return;
297
+ record.navigation.push({ at: now(), url });
298
+ if (record.navigation.length > NAVIGATION_CAP)
299
+ record.navigation.splice(0, record.navigation.length - NAVIGATION_CAP);
300
+ record.lastUrl = url;
301
+ });
302
+ const record = currentRecord(await stateOf(scope), scope.plane);
303
+ if (record)
304
+ await emit(scope.cid, (await configOf(scope.read, scope.cid, scope.context)).label, record, "updated", await providerOf(scope.read, scope.cid, scope.plane, scope.context));
305
+ },
306
+ dropped: () => serialize(key, async () => {
307
+ const record = currentRecord(await stateOf(scope), scope.plane);
308
+ if (record)
309
+ await detachDriver(record.tag);
310
+ }),
311
+ ended: async () => {
312
+ const record = currentRecord(await stateOf(scope), scope.plane);
313
+ if (record?.state !== "live")
314
+ return false;
315
+ return markEnded(scope, record, await providerOf(scope.read, scope.cid, scope.plane, scope.context));
316
+ },
317
+ };
318
+ }
319
+ /** A plane nobody calls for its idle window is released, never mid-call. A dead process's timers die with it, and the
320
+ * provider's own idle bound takes over. */
321
+ async function releaseIdle(cid, fired, idleMs) {
322
+ const conversation = opened && await opened.harness.conversation(cid, opened.context);
323
+ if (!conversation)
324
+ return;
325
+ // Only the still-current timer releases, checked inside the commit: a call since, even one that ran while the
326
+ // lookup above waited, replaced it.
327
+ await releasePlane(conversation, "idle", opened.context, () => idle.isCurrent(cid, fired), Math.round(idleMs / 1000));
328
+ }
329
+ /** A release the model did not ask for (idle, close) commits its notice with it, so whichever call next attaches a
330
+ * session tells it, even when the call that opened the replacement failed or died. */
331
+ async function releasePlane(conversation, reason, context, still = () => true, idleS = 0) {
332
+ const key = `${conversation.id}:${PLANE}`;
333
+ const released = await serialize(key, async () => {
334
+ const tags = await conversation.commit(async (tx) => {
335
+ const state = await tx.doc(Sessions, conversation.id);
336
+ const record = still() ? currentRecord(state, PLANE) : null;
337
+ if (!record || !open(record))
338
+ return [];
339
+ await requestRelease(tx, rowOf(conversation.id, record), reason, now());
340
+ if (reason === "idle" || reason === "close")
341
+ addNotice(state, notices.released(reason, record.lastUrl, idleS));
342
+ return [record.tag];
343
+ }, context);
344
+ for (const tag of tags)
345
+ await detach(tag);
346
+ return tags.length > 0;
347
+ });
348
+ if (released)
349
+ idle.cancel(conversation.id);
350
+ }
351
+ async function chargeCall(api, context) {
352
+ if (currentRecord(await api.snapshot(Sessions, api.conversationId, context), PLANE)?.state !== "live")
353
+ return null;
354
+ return api.commit(async (tx) => {
355
+ const record = currentRecord(await tx.doc(Sessions, api.conversationId), PLANE);
356
+ if (record?.state !== "live")
357
+ return null;
358
+ const { spent, usage } = meter(record.spent, now());
359
+ record.spent = spent;
360
+ return usage;
361
+ }, context);
362
+ }
363
+ const withSessionTime = (own, charged) => {
364
+ if (!charged)
365
+ return own;
366
+ const ownCost = (own?.cost ?? {});
367
+ return { ...charged.usage, ...own, cost: { ...charged.usage.cost, ...ownCost, total: charged.usage.cost.total + (ownCost.total ?? 0) } };
368
+ };
369
+ const impls = { ...custodyTools, ...pageTools(), ...options.tools };
370
+ const tools = BROWSER_TOOLS
371
+ .filter((contract) => impls[contract.name] && (contract.listedWhen !== "downloads" || options.workspace))
372
+ .map((contract) => defineTool({
373
+ name: contract.name,
374
+ description: contract.description,
375
+ parameters: contract.parameters,
376
+ replay: contract.replay,
377
+ executionMode: contract.executionMode,
378
+ execute: async (args, api, context) => {
379
+ const config = await api.snapshot(Config, api.conversationId, context);
380
+ idle.activity(api.conversationId, +1, (config?.policy.idleReleaseS ?? 0) * 1000);
381
+ try {
382
+ const call = { callId: api.callId, conversationId: api.conversationId, signal: context.abortSignal, label: config?.label ?? "", redact, evidence: options.evidence, classifyPage: options.decisions?.classifyPage };
383
+ // Inside an async function, so a host tool that throws before it returns a promise is caught too.
384
+ const out = await (async () => impls[contract.name](args, portFor(api, context), call))().catch((error) => {
385
+ // A throw would reach pi's diagnostic unscrubbed: every failure comes back as the typed envelope, redacted.
386
+ const typed = error instanceof BrowserFailureError ? error.failure : classifyBrowserError(error, contract.effect === "effect", { aborted: context.abortSignal?.aborted === true });
387
+ return { content: [{ type: "text", text: JSON.stringify(typed) }], isError: true };
388
+ });
389
+ // A charge that cannot be committed now is carried by the next one.
390
+ const usage = withSessionTime(out.usage, await chargeCall(api, context).catch(() => null));
391
+ return {
392
+ ...forModel(out.content.map((item) => item.type === "text" ? { ...item, text: redact(item.text) } : item)),
393
+ ...(out.isError ? { isError: true } : {}),
394
+ ...(out.details ? { details: redactDeep(out.details, redact) } : {}),
395
+ ...(usage ? { usage: usage } : {}),
396
+ };
397
+ }
398
+ finally {
399
+ idle.activity(api.conversationId, -1);
400
+ }
401
+ },
402
+ }));
403
+ const names = new Set(tools.map((tool) => tool.name));
404
+ const childConversation = (api, context) => async (task) => {
405
+ const config = await api.snapshot(Config, api.conversationId, context);
406
+ const childTools = (await api.agent(context)).tools.filter((tool) => CHILD_TOOLS.has(tool.name));
407
+ // One child per request, recorded in the commit that creates it: a replay or a repeated call finds it again, and
408
+ // its submission is deduplicated by request_id.
409
+ const id = await api.commit(async (tx) => {
410
+ const children = await tx.doc(Children, api.conversationId);
411
+ const key = `${task.site}:${task.requestId}`;
412
+ const known = children.byRequest[key];
413
+ if (known !== undefined)
414
+ return known;
415
+ const child = await tx.createConversation({ ownership: { kind: "task", taskId: api.taskId } });
416
+ await configure(tx, child.id, { tools: childTools, instructions: null });
417
+ Object.assign(await tx.doc(Config, child.id), config ?? UNCONFIGURED);
418
+ children.byRequest[key] = child.id;
419
+ return child.id;
420
+ }, context);
421
+ const child = await api.conversation(id, context);
422
+ if (!child)
423
+ throw new Error("the child conversation is gone");
424
+ try {
425
+ const settled = await (await child.submit({ type: "input", content: task.prompt, requestId: task.requestId }, context)).wait(context);
426
+ const report = await api.commit(async (tx) => {
427
+ for (const entry of (await tx.scanEntries({ conversationId: id, order: "descending" }, 50)).items) {
428
+ for (const message of [...(entry.model ?? [])].reverse()) {
429
+ if (message.role !== "assistant")
430
+ continue;
431
+ const text = message.content.filter((part) => part.type === "text").map((part) => part.text).join("").trim();
432
+ if (text)
433
+ return text;
434
+ }
435
+ }
436
+ return "";
437
+ }, context);
438
+ if (settled.status !== "done" || !report)
439
+ throw new Error("the child finished without a report");
440
+ return report;
441
+ }
442
+ finally {
443
+ await releasePlane({ id, commit: (change, ctx) => api.commit(change, ctx) }, "close", context).catch(() => undefined);
444
+ }
445
+ };
446
+ const siteTools = options.sites ? [((sites) => {
447
+ const contract = useWebsiteContract(sites.listing);
448
+ return defineTool({
449
+ name: contract.name,
450
+ description: contract.description,
451
+ parameters: contract.parameters,
452
+ replay: contract.replay,
453
+ executionMode: contract.executionMode,
454
+ execute: async (args, api, context) => {
455
+ const out = await useWebsite(args, sites.port, sites.listing, { signal: context.abortSignal ?? new AbortController().signal, runChild: childConversation(api, context) });
456
+ return { ...forModel(out.content.map((item) => item.type === "text" ? { ...item, text: redact(item.text) } : item)), ...(out.isError ? { isError: true } : {}) };
457
+ },
458
+ });
459
+ })(options.sites)] : [];
460
+ const section = {
461
+ key: name,
462
+ async render(input, context) {
463
+ if (!input.agent.tools.some((tool) => names.has(tool.name)))
464
+ return undefined;
465
+ const config = await input.read.snapshot(Config, input.conversationId, context);
466
+ return [browserSection({ idleReleaseS: config?.policy.idleReleaseS ?? UNCONFIGURED.policy.idleReleaseS }), options.section?.addendum].filter(Boolean).join("\n\n");
467
+ },
468
+ };
469
+ return {
470
+ extension: defineExtension({ name, tools: [...tools, ...siteTools], sections: [section], tasks: [ReleaseTask] }),
471
+ docs: { Config, Sessions, Inventory, Children },
472
+ tools: [...tools, ...siteTools],
473
+ release: (conversation, reason, context) => releasePlane(conversation, reason, context),
474
+ async reconcile(harness, isActive, context) {
475
+ opened = { harness, context };
476
+ return reconcileAll(harness, isActive, context);
477
+ },
478
+ async close() {
479
+ idle.clear();
480
+ // A session whose driver was let go and not yet replaced still has its observer attached: close both kinds.
481
+ await Promise.all([...new Set([...attachments.keys(), ...observers.keys()])].map(detach));
482
+ },
483
+ };
484
+ }
@@ -0,0 +1,18 @@
1
+ export * from "./core/contract.js";
2
+ export * from "./core/decisions.js";
3
+ export * from "./core/downloads.js";
4
+ export * from "./core/effects.js";
5
+ export * from "./core/evidence.js";
6
+ export * from "./core/failures.js";
7
+ export * from "./core/find.js";
8
+ export * from "./core/guard.js";
9
+ export * from "./core/host.js";
10
+ export * from "./core/images.js";
11
+ export * from "./core/lease.js";
12
+ export * from "./core/receipts.js";
13
+ export * from "./core/redact.js";
14
+ export * from "./core/sites.js";
15
+ export { DEFAULT_BROWSER_POLICY } from "./core/session-control.js";
16
+ export * from "./core/tools.js";
17
+ export * from "./core/usage.js";
18
+ export * from "./core/web.js";
package/dist/index.js ADDED
@@ -0,0 +1,19 @@
1
+ // The host-neutral core: it imports no pi package and no host, only Node's builtins and the package's own dependencies.
2
+ export * from "./core/contract.js";
3
+ export * from "./core/decisions.js";
4
+ export * from "./core/downloads.js";
5
+ export * from "./core/effects.js";
6
+ export * from "./core/evidence.js";
7
+ export * from "./core/failures.js";
8
+ export * from "./core/find.js";
9
+ export * from "./core/guard.js";
10
+ export * from "./core/host.js";
11
+ export * from "./core/images.js";
12
+ export * from "./core/lease.js";
13
+ export * from "./core/receipts.js";
14
+ export * from "./core/redact.js";
15
+ export * from "./core/sites.js";
16
+ export { DEFAULT_BROWSER_POLICY } from "./core/session-control.js";
17
+ export * from "./core/tools.js";
18
+ export * from "./core/usage.js";
19
+ export * from "./core/web.js";
@@ -0,0 +1,13 @@
1
+ export { directFetch, closeDirectFetch } from "./http.js";
2
+ /** Rewrite a Browserbase connect URL onto the credential proxy: only `*.browserbase.com` hosts, the signing query kept. */
3
+ export declare function rewriteConnectUrl(connectUrl: string, connectBaseUrl: string | undefined | null): string;
4
+ /** Direct, never through the HTTP(S) env proxy: it rejects CONNECT and the CDP WebSocket cannot ride it. Under `node
5
+ * --use-env-proxy` NO_PROXY is re-read per request, so listing these hosts bypasses it. */
6
+ export declare function browserbaseNoProxyHosts(env: NodeJS.ProcessEnv): string[];
7
+ export declare function applyBrowserbaseNoProxy(env?: NodeJS.ProcessEnv): string[];
8
+ /** A second provider binding the same URL to a different proxy is refused, never switched: the signed URL would go to
9
+ * it. */
10
+ export declare function bindConnectDial(connectUrl: string, connectBaseUrl: string | null): void;
11
+ export declare function unbindConnectDial(connectUrl: string): void;
12
+ export declare function connectDialUrl(url: string): string;
13
+ export declare function installWebSocketWrapper(): void;
@@ -0,0 +1,96 @@
1
+ import { browserbaseHoldings } from "./shared.js";
2
+ export { directFetch, closeDirectFetch } from "./http.js";
3
+ /** Rewrite a Browserbase connect URL onto the credential proxy: only `*.browserbase.com` hosts, the signing query kept. */
4
+ export function rewriteConnectUrl(connectUrl, connectBaseUrl) {
5
+ if (!connectUrl || !connectBaseUrl)
6
+ return connectUrl;
7
+ try {
8
+ const target = new URL(connectBaseUrl);
9
+ const u = new URL(connectUrl);
10
+ if (!/(?:^|\.)browserbase\.com$/i.test(u.hostname))
11
+ return connectUrl;
12
+ u.protocol = target.protocol;
13
+ u.host = target.host;
14
+ u.pathname = target.pathname.replace(/\/$/, "") + u.pathname;
15
+ return u.toString();
16
+ }
17
+ catch {
18
+ return connectUrl;
19
+ }
20
+ }
21
+ /** Direct, never through the HTTP(S) env proxy: it rejects CONNECT and the CDP WebSocket cannot ride it. Under `node
22
+ * --use-env-proxy` NO_PROXY is re-read per request, so listing these hosts bypasses it. */
23
+ export function browserbaseNoProxyHosts(env) {
24
+ const hosts = new Set();
25
+ for (const key of ["BROWSERBASE_BASE_URL", "BROWSERBASE_CONNECT_BASE_URL"]) {
26
+ const raw = String(env[key] || "").trim();
27
+ if (!raw)
28
+ continue;
29
+ try {
30
+ hosts.add(new URL(raw).hostname);
31
+ }
32
+ catch { }
33
+ }
34
+ if (!String(env.BROWSERBASE_CONNECT_BASE_URL || "").trim())
35
+ hosts.add(".browserbase.com");
36
+ return [...hosts];
37
+ }
38
+ export function applyBrowserbaseNoProxy(env = process.env) {
39
+ const hosts = browserbaseNoProxyHosts(env);
40
+ if (!hosts.length)
41
+ return hosts;
42
+ for (const target of env === process.env ? [env] : [env, process.env]) {
43
+ for (const key of ["NO_PROXY", "no_proxy"]) {
44
+ const merged = String(target[key] || "").split(",").map((h) => h.trim()).filter(Boolean);
45
+ for (const h of hosts)
46
+ if (!merged.includes(h))
47
+ merged.push(h);
48
+ target[key] = merged.join(",");
49
+ }
50
+ }
51
+ return hosts;
52
+ }
53
+ /** The driver keeps the raw connect URL (the extension in the cloud browser dials it back and reaches only
54
+ * Browserbase); this process's socket dials the proxy, so the rewrite happens at dial time, never in a record. */
55
+ /** Per-socket targets, so two providers with different proxies never send one's signed URL to the other's proxy. */
56
+ const { boundDials } = browserbaseHoldings;
57
+ /** A second provider binding the same URL to a different proxy is refused, never switched: the signed URL would go to
58
+ * it. */
59
+ export function bindConnectDial(connectUrl, connectBaseUrl) {
60
+ const target = connectBaseUrl?.trim() ?? "";
61
+ const bound = boundDials.get(connectUrl);
62
+ if (bound !== undefined && bound !== target)
63
+ throw new Error("this Browserbase session is already attached through another credential proxy");
64
+ boundDials.set(connectUrl, target);
65
+ }
66
+ export function unbindConnectDial(connectUrl) {
67
+ boundDials.delete(connectUrl);
68
+ if (![...boundDials.values()].some(Boolean))
69
+ restoreWebSocket();
70
+ }
71
+ export function connectDialUrl(url) {
72
+ const bound = boundDials.get(url);
73
+ if (bound !== undefined)
74
+ return bound ? rewriteConnectUrl(url, bound) : url;
75
+ return url;
76
+ }
77
+ /** Wraps the process WebSocket only while a session is bound to a proxy; the native one returns with the last binding. A wrapper
78
+ * installed on top cannot be removed, so ours stays under it and, with no bindings, passes every URL through. */
79
+ let wrapped = null;
80
+ export function installWebSocketWrapper() {
81
+ if (typeof globalThis.WebSocket !== "function" || (wrapped && globalThis.WebSocket === wrapped.wrapper))
82
+ return;
83
+ const original = globalThis.WebSocket;
84
+ const wrapper = function (url, protocols) { return new original(connectDialUrl(String(url)), protocols); };
85
+ wrapper.prototype = original.prototype;
86
+ for (const k of ["CONNECTING", "OPEN", "CLOSING", "CLOSED"])
87
+ wrapper[k] = original[k];
88
+ globalThis.WebSocket = wrapper;
89
+ wrapped = { original, wrapper };
90
+ }
91
+ function restoreWebSocket() {
92
+ if (!wrapped || globalThis.WebSocket !== wrapped.wrapper)
93
+ return;
94
+ globalThis.WebSocket = wrapped.original;
95
+ wrapped = null;
96
+ }