@parcha/pi-browser 0.1.0-beta.13 → 0.1.0-beta.15

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 (43) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +29 -8
  3. package/dist/coding-agent.d.ts +7 -0
  4. package/dist/coding-agent.js +33 -16
  5. package/dist/core/contract.js +1 -1
  6. package/dist/core/custody.d.ts +16 -3
  7. package/dist/core/custody.js +28 -11
  8. package/dist/core/downloads.d.ts +1 -0
  9. package/dist/core/downloads.js +2 -2
  10. package/dist/core/failures.d.ts +8 -0
  11. package/dist/core/failures.js +18 -9
  12. package/dist/core/guard.d.ts +1 -1
  13. package/dist/core/guard.js +2 -1
  14. package/dist/core/host.d.ts +60 -2
  15. package/dist/core/sites.js +2 -1
  16. package/dist/core/tools.d.ts +37 -2
  17. package/dist/core/tools.js +84 -54
  18. package/dist/core/usage.d.ts +1 -20
  19. package/dist/driver/extension-worker.d.ts +7 -0
  20. package/dist/driver/extension-worker.js +148 -0
  21. package/dist/driver/new-document.d.ts +26 -0
  22. package/dist/driver/new-document.js +40 -0
  23. package/dist/driver/stagehand.js +9 -61
  24. package/dist/durable.d.ts +14 -3
  25. package/dist/durable.js +507 -369
  26. package/dist/index.d.ts +1 -0
  27. package/dist/index.js +1 -0
  28. package/dist/providers/browserbase.d.ts +17 -0
  29. package/dist/providers/browserbase.js +49 -8
  30. package/dist/providers/cdp.d.ts +14 -0
  31. package/dist/providers/cdp.js +270 -66
  32. package/dist/providers/kernel.js +40 -6
  33. package/dist/providers/profiles.d.ts +19 -0
  34. package/dist/providers/profiles.js +124 -0
  35. package/dist/providers/shared.d.ts +1 -1
  36. package/dist/recorder/index.d.ts +1 -0
  37. package/dist/recorder/index.js +1 -0
  38. package/dist/recorder/jpeg.d.ts +3 -0
  39. package/dist/recorder/jpeg.js +36 -0
  40. package/dist/recorder/track.d.ts +107 -0
  41. package/dist/recorder/track.js +280 -0
  42. package/dist/testing/backend.js +2 -2
  43. package/package.json +3 -3
package/dist/durable.js CHANGED
@@ -1,9 +1,10 @@
1
- import { configure, defineDoc, defineExtension, defineTool } from "@earendil-works/pi-durable";
1
+ import { randomUUID } from "node:crypto";
2
+ import { configure, defineDoc, defineExtension, defineTool, ToolResultEntry } from "@earendil-works/pi-durable";
2
3
  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 { BrowserFailureError, closeDriver, currentRecord, custodyTools, newSessionRecord, notices, NAVIGATION_CAP, profileRefusal, relaunchRefusal, SESSION_REPLACED, sessionSpec } from "./core/custody.js";
4
5
  import { forModel } from "./durable-result.js";
5
6
  import { EffectObserver, effectDecider, observerFailure } from "./core/effects.js";
6
- import { classifyBrowserError } from "./core/failures.js";
7
+ import { browserFailure, classifyBrowserError } from "./core/failures.js";
7
8
  import { pageTools } from "./core/tools.js";
8
9
  import { useWebsite, useWebsiteContract } from "./core/sites.js";
9
10
  import { leaseTag } from "./core/lease.js";
@@ -15,360 +16,461 @@ export { createWebExtension } from "./web.js";
15
16
  export { CONFIRM_POLLS, RELEASE_ATTEMPTS } from "./store.js";
16
17
  const PLANE = "default";
17
18
  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 NOT_CONFIGURED = new BrowserFailureError(browserFailure("browser_unavailable", "This conversation has no browser configuration, so no browser can be launched here; use web_fetch or another source."));
20
+ const emptySessions = () => ({ current: {}, sessions: [], notice: null });
21
+ async function drainReleases(name, harness, context, signal) {
22
+ signal?.throwIfAborted();
23
+ const drained = (async () => {
24
+ for (;;) {
25
+ const live = (await harness.inspect(context)).tasks.filter((task) => task.record.kind === `${name}.release`);
26
+ if (!live.length)
27
+ return;
28
+ await Promise.all(live.map((task) => harness.waitForTask(task.record.id, context)));
29
+ }
30
+ })();
31
+ if (!signal)
32
+ return drained;
33
+ const done = new AbortController();
34
+ try {
35
+ await Promise.race([drained, new Promise((_, reject) => signal.addEventListener("abort", () => reject(signal.reason), { once: true, signal: done.signal }))]);
36
+ }
37
+ finally {
38
+ done.abort();
39
+ }
40
+ }
19
41
  const open = (record) => record?.state === "live" || record?.state === "creating";
20
42
  // A child gets the browser and web tools only, never use_website, so it cannot start children of its own.
21
43
  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 { }
44
+ class Attachments {
45
+ drivers = new Map();
46
+ observers = new Map();
47
+ driver(tag) {
48
+ return this.drivers.get(tag);
47
49
  }
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 { }
50
+ observer(tag) {
51
+ return this.observers.get(tag);
60
52
  }
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);
53
+ attach(tag, driver, observer) {
54
+ this.observers.set(tag, observer);
55
+ this.drivers.set(tag, driver);
56
+ }
57
+ async detach(tag) {
58
+ const driver = this.drivers.get(tag);
59
+ this.drivers.delete(tag);
60
+ this.observers.get(tag)?.close();
61
+ this.observers.delete(tag);
77
62
  if (driver)
78
63
  await closeDriver(driver);
79
64
  }
80
65
  /** Let go of a dead driver connection and nothing else: a healthy observer stays attached, so a page that sends
81
66
  * 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);
67
+ async detachDriver(tag) {
68
+ if (this.observers.get(tag)?.closed)
69
+ return this.detach(tag);
70
+ const driver = this.drivers.get(tag);
71
+ this.drivers.delete(tag);
87
72
  if (driver)
88
73
  await closeDriver(driver);
89
74
  }
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
- }
75
+ tags() {
76
+ return [...new Set([...this.drivers.keys(), ...this.observers.keys()])];
107
77
  }
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;
78
+ }
79
+ async function configOf(c, read, cid, context) {
80
+ const config = await read.snapshot(c.Config, cid, context);
81
+ if (!config?.run)
82
+ throw NOT_CONFIGURED;
83
+ return config;
84
+ }
85
+ async function providerOf(c, read, cid, plane, context) {
86
+ return c.options.provider({ conversationId: cid, plane, config: await configOf(c, read, cid, context) });
87
+ }
88
+ const rowOf = (cid, record) => ({ tag: record.tag, conversationId: cid, plane: record.plane, provider: record.provider, resourceId: record.resourceId, state: record.state });
89
+ async function emitObserver(c, row) {
90
+ try {
91
+ await c.options.onObserver?.(row);
128
92
  }
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;
93
+ catch { }
94
+ }
95
+ /** The host's crossing: called synchronously; what it throws or rejects with is reported and never reaches the call. */
96
+ function cross(c, point) {
97
+ const crossing = c.options.crossing;
98
+ if (!crossing)
99
+ return;
100
+ const warn = (error) => process.emitWarning(`pi-browser: the host's crossing threw at ${point}; the call goes on: ${error instanceof Error ? error.message : String(error)}`, { code: "PI_BROWSER_CROSSING" });
101
+ // Promise.resolve, not instanceof: a promise from another realm (node:vm) is caught too.
102
+ try {
103
+ Promise.resolve(crossing(point)).catch(warn);
137
104
  }
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) {
105
+ catch (error) {
106
+ warn(error);
107
+ }
108
+ }
109
+ async function emit(c, cid, label, record, change, provider) {
110
+ if (!c.options.onSession)
111
+ return;
112
+ try {
113
+ const ref = record.resourceId === null ? null : { id: record.resourceId, tag: record.tag };
114
+ const view = change !== "released" && ref && provider?.liveView ? await provider.liveView(ref) : null;
115
+ // 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
116
+ // scrubbed, since its query can carry a credential.
117
+ 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) })) };
118
+ await c.options.onSession({ conversationId: cid, label, session: record, liveView }, change);
119
+ }
120
+ catch { }
121
+ }
122
+ async function stateOf(c, scope) {
123
+ return (await scope.read.snapshot(c.Sessions, scope.cid, scope.context)) ?? emptySessions();
124
+ }
125
+ const failure = (error, scope) => error instanceof BrowserFailureError ? error : new BrowserFailureError(classifyBrowserError(error, false, { aborted: scope.signal.aborted }));
126
+ async function attachLive(c, scope, record) {
127
+ const held = c.held.driver(record.tag);
128
+ // An observer whose socket closed holds nothing: driver and observer are attached again together.
129
+ if (held && !c.held.observer(record.tag)?.closed)
130
+ return held;
131
+ if (held)
132
+ await c.held.detach(record.tag);
133
+ const provider = await providerOf(c, scope.read, scope.cid, scope.plane, scope.context);
134
+ const ref = { id: record.resourceId, tag: record.tag };
135
+ try {
136
+ return await connect(c, scope, provider, ref);
137
+ }
138
+ catch (error) {
139
+ if (!(await markEnded(c, scope, record, provider)))
144
140
  throw failure(error, scope);
145
- }
141
+ return null;
146
142
  }
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 };
143
+ }
144
+ async function connect(c, scope, provider, ref) {
145
+ const config = await configOf(c, scope.read, scope.cid, scope.context);
146
+ const { actions: policy, batchTimeoutMs } = config.policy;
147
+ const target = await provider.attach(ref, scope.signal);
148
+ const driver = await c.options.driver(target, scope.signal, { batchTimeoutMs });
149
+ let unattached = null;
150
+ // A healthy observer that outlived its driver's connection is kept, not opened a second time.
151
+ const kept = c.held.observer(ref.tag);
152
+ const open = c.options.openObserver ?? EffectObserver.open.bind(EffectObserver);
153
+ const observer = kept && !kept.closed ? kept : policy ? await open(target, policy === "allow" ? null : effectDecider(policy, c.options.decisions), batchTimeoutMs).catch((error) => { unattached = error; return null; }) : null;
154
+ // A policy that holds requests never degrades to browsing without the hold.
155
+ if (policy && policy !== "allow" && !observer) {
156
+ await closeDriver(driver);
157
+ throw new BrowserFailureError(browserFailure("browser_unavailable", "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.", { retryable: true }));
158
+ }
159
+ c.held.attach(ref.tag, driver, observer);
160
+ if (policy === "allow" && !observer)
161
+ await emitObserver(c, { conversationId: scope.cid, label: config.label, tag: ref.tag, session_id: ref.id, policy, code: observerFailure(unattached) });
162
+ return driver;
163
+ }
164
+ async function markEnded(c, scope, record, provider) {
165
+ const status = await provider.status({ id: record.resourceId, tag: record.tag }, scope.signal).catch(() => "running");
166
+ if (status !== "gone" && status !== "stopped")
167
+ return false;
168
+ await scope.commit((tx) => c.store.move(tx, rowOf(scope.cid, record), { state: "released", reason: "ended", at: now() }));
169
+ await c.held.detach(record.tag);
170
+ await c.store.emitReleased(scope.cid, record.tag, scope.read, scope.context);
171
+ return true;
172
+ }
173
+ async function settleCreating(c, scope, record) {
174
+ const provider = await providerOf(c, scope.read, scope.cid, scope.plane, scope.context);
175
+ try {
176
+ await c.store.bindByTag(provider, rowOf(scope.cid, record), scope.commit, scope.signal);
177
+ }
178
+ catch (error) {
179
+ throw failure(error, scope);
180
+ }
181
+ }
182
+ async function create(c, scope, overrides, presetTag) {
183
+ const config = await configOf(c, scope.read, scope.cid, scope.context);
184
+ const provider = await c.options.provider({ conversationId: scope.cid, plane: scope.plane, config });
185
+ const tag = presetTag ?? leaseTag("ar", config.run, scope.cid, (await stateOf(c, scope)).sessions.length + 1);
186
+ const spec = sessionSpec(config, tag, overrides);
187
+ const unsupported = profileRefusal(spec, provider.caps);
188
+ if (unsupported)
189
+ throw new BrowserFailureError(unsupported);
190
+ const record = newSessionRecord({ plane: scope.plane, tag, provider: provider.name, spec, at: now(), honours: provider.caps.settings });
191
+ const row = rowOf(scope.cid, record);
192
+ await scope.commit(async (tx) => {
193
+ const state = await tx.doc(c.Sessions, scope.cid);
194
+ state.sessions.push(record);
195
+ state.current[scope.plane] = state.sessions.length - 1;
196
+ await c.store.begin(tx, row);
197
+ });
198
+ // An answer lost on the way back is not a session that never started: it is settled by its tag.
199
+ const ref = await provider.create(spec, scope.signal).then(async (made) => { await scope.commit((tx) => c.store.move(tx, row, { state: "live", resourceId: made.id, at: now() })); return made; }, async (error) => (await c.store.bindByTag(provider, row, scope.commit, scope.signal, await provider.findByTag(tag, scope.signal).catch(() => []))) ?? Promise.reject(failure(error, scope)));
200
+ const live = { ...record, state: "live", resourceId: ref.id };
201
+ try {
202
+ const driver = await connect(c, scope, provider, ref);
203
+ await emit(c, scope.cid, config.label, live, "launched", provider);
204
+ return { record: live, driver };
205
+ }
206
+ catch (error) {
207
+ throw failure(error, scope);
208
+ }
209
+ }
210
+ async function acquire(c, scope) {
211
+ let note = null;
212
+ for (let turn = 0; turn < 4; turn += 1) {
213
+ const record = currentRecord(await stateOf(c, scope), scope.plane);
214
+ if (record?.state === "live") {
215
+ const driver = await attachLive(c, scope, record);
216
+ if (driver)
217
+ return { record, driver, note };
218
+ note = notices.ended(record.lastUrl);
167
219
  }
168
- catch (error) {
169
- throw failure(error, scope);
220
+ else if (record?.state === "creating") {
221
+ await settleCreating(c, scope, record);
222
+ }
223
+ else {
224
+ return { ...(await create(c, scope, {})), note };
170
225
  }
171
226
  }
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 };
227
+ throw new Error(`browser custody for conversation ${scope.cid} did not settle`);
228
+ }
229
+ /** Custody's notice is kept in the call's memo before it is cleared, so a call rerun after a crash still tells it. */
230
+ async function attached(c, scope, record, driver, note) {
231
+ const state = await stateOf(c, scope);
232
+ const notice = await scope.keep("notice", [note, state.notice].filter(Boolean).join(" "));
233
+ if (state.notice !== null)
234
+ await scope.commit(async (tx) => { (await tx.doc(c.Sessions, scope.cid)).notice = null; });
235
+ const fresh = state.sessions.find((r) => r.tag === record.tag) ?? record;
236
+ const interrupted = await cutOf(c, scope, journalOf(state, scope.plane));
237
+ const recorded = Boolean((await providerOf(c, scope.read, scope.cid, scope.plane, scope.context)).recordings);
238
+ return { driver, tag: record.tag, sessionId: fresh.resourceId, record: fresh, notice: notice || null, interrupted, recorded, effects: c.held.observer(record.tag) ?? null };
239
+ }
240
+ async function releaseRecord(c, scope, record, reason) {
241
+ await scope.commit((tx) => c.store.requestRelease(tx, rowOf(scope.cid, record), reason, now()));
242
+ await c.held.detach(record.tag);
243
+ }
244
+ const editState = (c, scope, edit) => scope.commit(async (tx) => edit(await tx.doc(c.Sessions, scope.cid)));
245
+ const journalOf = (state, plane) => [...state.sessions].reverse().find((r) => r.plane === plane && r.pendingEffect !== null)?.pendingEffect ?? null;
246
+ const clearJournal = (c, scope, callId) => editState(c, scope, (state) => { for (const record of state.sessions)
247
+ if (record.plane === scope.plane && record.pendingEffect?.callId === callId)
248
+ record.pendingEffect = null; });
249
+ /** A journaled action's own answer as pi committed it, found by pi's typed tool-result entry: true for a success, false
250
+ * for an error, null for none yet. The scan covers only the entry's conversation from where it was journaled on, never
251
+ * the whole history. */
252
+ async function answerOf(scope, pending) {
253
+ const after = pending.after;
254
+ if (after === undefined)
255
+ return null;
256
+ return scope.commit(async (tx) => {
257
+ let cursor;
258
+ do {
259
+ const page = await tx.scanEntries({ conversationId: scope.cid, minEntryId: after, order: "ascending" }, 100, cursor);
260
+ for (const entry of page.items) {
261
+ const message = ToolResultEntry.is(entry) ? entry.model?.[0] : undefined;
262
+ if (message?.role === "toolResult" && message.toolCallId === pending.callId)
263
+ return message.isError !== true;
187
264
  }
265
+ cursor = page.next;
266
+ } while (cursor !== undefined);
267
+ return null;
268
+ });
269
+ }
270
+ /** Whether a journaled action's own answer was committed as a success. */
271
+ const answered = async (scope, pending) => (await answerOf(scope, pending)) === true;
272
+ /** The cut a call answers for. In this process an entry is in flight or answered, never cut; one an earlier process
273
+ * wrote is a cut unless its action finished and pi committed its answer, which only then is looked up. */
274
+ async function cutOf(c, scope, pending) {
275
+ if (!pending || pending.incarnation === c.incarnation)
276
+ return null;
277
+ if (!pending.finished || pending.told || !(await answered(scope, pending)))
278
+ return pending;
279
+ await clearJournal(c, scope, pending.callId);
280
+ return null;
281
+ }
282
+ async function relaunchOn(c, scope, api, slot, overrides) {
283
+ const config = await configOf(c, scope.read, scope.cid, scope.context);
284
+ const refusal = relaunchRefusal(config.policy, overrides);
285
+ if (refusal)
286
+ throw new BrowserFailureError(refusal);
287
+ // The relaunch's session is chosen in a memo before its create commits: a rerun runs on it or says
288
+ // session_replaced, never a second launch; a memo with no record yet is an uncommitted create and goes ahead.
289
+ const find = async (tag) => (await stateOf(c, scope)).sessions.find((r) => r.tag === tag);
290
+ const launched = await api.memo(slot, scope.context);
291
+ let mine = await find(launched);
292
+ if (mine) {
293
+ if (mine.state === "creating") {
294
+ await settleCreating(c, scope, mine);
295
+ mine = await find(launched);
188
296
  }
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);
297
+ const driver = mine?.state === "live" ? await attachLive(c, scope, mine) : null;
298
+ if (!mine || !driver)
299
+ throw new BrowserFailureError(SESSION_REPLACED);
300
+ return attached(c, scope, mine, driver, null);
205
301
  }
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);
302
+ const state = await stateOf(c, scope);
303
+ const tag = launched ?? await api.memo(slot, leaseTag("ar", config.run, scope.cid, state.sessions.length + 1), scope.context);
304
+ const old = currentRecord(state, scope.plane);
305
+ if (old && open(old) && old.tag !== tag)
306
+ await releaseRecord(c, scope, old, "relaunch");
307
+ const made = await create(c, scope, overrides, tag);
308
+ return attached(c, scope, made.record, made.driver, null);
309
+ }
310
+ function portFor(c, api, context) {
311
+ const memo = (slot) => `${c.name}:${slot}:${PLANE}`;
312
+ 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) => {
313
+ // An earlier attempt's text comes first; an empty one is never memoized, so it cannot shadow a later notice.
314
+ const prior = await api.memo(memo(slot), context);
315
+ if (prior !== undefined)
316
+ return [prior, value].filter(Boolean).join(" ");
317
+ return value ? api.memo(memo(slot), value, context) : "";
318
+ } };
319
+ const key = `${scope.cid}:${scope.plane}`;
320
+ return {
321
+ session: () => c.serial.run(key, async () => {
322
+ const ran = await api.memo(memo("ran"), context);
323
+ if (ran !== undefined) {
324
+ const record = (await stateOf(c, scope)).sessions.find((r) => r.tag === ran);
325
+ const driver = record?.state === "live" ? await attachLive(c, scope, record) : null;
326
+ if (!record || !driver)
327
+ throw new BrowserFailureError(SESSION_REPLACED);
328
+ return attached(c, scope, record, driver, null);
329
+ }
330
+ const { record, driver, note } = await acquire(c, scope);
331
+ await api.memo(memo("ran"), record.tag, context);
332
+ return attached(c, scope, record, driver, note);
333
+ }),
334
+ relaunch: (overrides) => c.serial.run(key, () => relaunchOn(c, scope, api, memo("relaunch"), overrides)),
335
+ release: () => c.serial.run(key, async () => {
336
+ const record = currentRecord(await stateOf(c, scope), scope.plane);
337
+ if (!record || !open(record)) {
338
+ // Only a release under way or done says so: a lost record is custody giving up, and its browser may still run.
339
+ const ended = (record?.state === "releasing" || record?.state === "released") && record.releaseReason ? { ended: { reason: record.releaseReason, at: record.endedAt } } : {};
340
+ return { released: record?.state === "releasing", sessionId: record?.resourceId ?? null, ...ended };
341
+ }
342
+ await releaseRecord(c, scope, record, "tool");
343
+ return { released: true, sessionId: record.resourceId };
344
+ }),
345
+ dispatching: async (effect) => {
346
+ // The host's mid-browse crossing: the page action before this one finished and pi committed its answer.
347
+ if (c.options.crossing) {
348
+ const previous = journalOf(await stateOf(c, scope), scope.plane);
349
+ if (previous?.finished && (await answerOf(scope, previous)) !== null)
350
+ cross(c, "browser.between-actions");
351
+ }
352
+ await scope.commit(async (tx) => {
353
+ const record = currentRecord(await tx.doc(c.Sessions, scope.cid), scope.plane);
354
+ if (!record)
355
+ return;
356
+ const newest = (await tx.scanEntries({ conversationId: scope.cid, order: "descending" }, 1)).items[0]?.id;
357
+ record.pendingEffect = { ...effect, url: effect.url === null ? null : scrubPageUrl(effect.url, c.redact), at: now(), sent: [], incarnation: c.incarnation, ...(newest === undefined ? {} : { after: newest }) };
358
+ });
359
+ },
360
+ journal: (row) => editState(c, scope, (state) => {
361
+ const pending = currentRecord(state, scope.plane)?.pendingEffect;
362
+ if (!pending)
363
+ return;
364
+ const sent = pending.sent ?? (pending.sent = []);
365
+ const scrubbed = { ...row, origin: c.redact(row.origin), path: c.redact(row.path) };
366
+ const at = sent.findIndex((r) => r.requestId === row.requestId);
367
+ if (at === -1)
368
+ sent.push(scrubbed);
369
+ else
370
+ sent[at] = scrubbed;
371
+ }),
372
+ mark: async (step, callId) => {
373
+ const found = { pending: false };
374
+ await editState(c, scope, (state) => {
375
+ const pending = state.sessions.find((r) => r.plane === scope.plane && r.pendingEffect?.callId === callId)?.pendingEffect;
376
+ if (pending) {
377
+ pending[step] = true;
378
+ found.pending = true;
250
379
  }
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) => {
380
+ });
381
+ // The host's double-run crossing: the action's driver call is over and its entry says so; pi has not committed
382
+ // the answer.
383
+ if (found.pending && step === "finished")
384
+ cross(c, "browser.action-returned");
385
+ },
386
+ settle: (callId) => clearJournal(c, scope, callId),
387
+ navigated: async (page) => {
388
+ // A page URL can carry a credential in any query value, its fragment or its userinfo: scrubbed before it is
389
+ // committed or reported.
390
+ const url = scrubPageUrl(page, c.redact);
391
+ await editState(c, scope, (state) => {
267
392
  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))
393
+ if (!record)
285
394
  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);
395
+ record.navigation.push({ at: now(), url });
396
+ if (record.navigation.length > NAVIGATION_CAP)
397
+ record.navigation.splice(0, record.navigation.length - NAVIGATION_CAP);
398
+ record.lastUrl = url;
399
+ });
400
+ const record = currentRecord(await stateOf(c, scope), scope.plane);
401
+ if (record)
402
+ 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));
403
+ },
404
+ dropped: () => c.serial.run(key, async () => {
405
+ const record = currentRecord(await stateOf(c, scope), scope.plane);
406
+ if (record)
407
+ await c.held.detachDriver(record.tag);
408
+ }),
409
+ ended: async () => {
410
+ const record = currentRecord(await stateOf(c, scope), scope.plane);
356
411
  if (record?.state !== "live")
357
- return null;
358
- const { spent, usage } = meter(record.spent, now());
359
- record.spent = spent;
360
- return usage;
412
+ return false;
413
+ return markEnded(c, scope, record, await providerOf(c, scope.read, scope.cid, scope.plane, scope.context));
414
+ },
415
+ };
416
+ }
417
+ /** A plane nobody calls for its idle window is released, never mid-call. A dead process's timers die with it, and the
418
+ * provider's own idle bound takes over. */
419
+ async function releaseIdle(c, cid, fired, idleMs) {
420
+ const conversation = c.opened && await c.opened.harness.conversation(cid, c.opened.context);
421
+ if (!conversation)
422
+ return;
423
+ // Only the still-current timer releases, checked inside the commit: a call since, even one that ran while the
424
+ // lookup above waited, replaced it.
425
+ await releasePlane(c, conversation, "idle", c.opened.context, () => c.idle.isCurrent(cid, fired), Math.round(idleMs / 1000));
426
+ }
427
+ /** A release the model did not ask for (idle, close) commits its notice with it, so whichever call next attaches a
428
+ * session tells it, even when the call that opened the replacement failed or died. */
429
+ async function releasePlane(c, conversation, reason, context, still = () => true, idleS = 0) {
430
+ const key = `${conversation.id}:${PLANE}`;
431
+ const released = await c.serial.run(key, async () => {
432
+ const tags = await conversation.commit(async (tx) => {
433
+ const state = await tx.doc(c.Sessions, conversation.id);
434
+ const record = still() ? currentRecord(state, PLANE) : null;
435
+ if (!record || !open(record))
436
+ return [];
437
+ await c.store.requestRelease(tx, rowOf(conversation.id, record), reason, now());
438
+ if (reason === "idle" || reason === "close")
439
+ c.store.addNotice(state, notices.released(reason, record.lastUrl, idleS));
440
+ return [record.tag];
361
441
  }, context);
442
+ for (const tag of tags)
443
+ await c.held.detach(tag);
444
+ return tags.length > 0;
445
+ });
446
+ if (reason === "close") {
447
+ c.idle.forget(conversation.id);
448
+ c.guards.delete(conversation.id);
362
449
  }
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))
450
+ else if (released)
451
+ c.idle.cancel(conversation.id);
452
+ }
453
+ async function chargeCall(c, api, context) {
454
+ if (currentRecord(await api.snapshot(c.Sessions, api.conversationId, context), PLANE)?.state !== "live")
455
+ return null;
456
+ return api.commit(async (tx) => {
457
+ const record = currentRecord(await tx.doc(c.Sessions, api.conversationId), PLANE);
458
+ if (record?.state !== "live")
459
+ return null;
460
+ const { spent, usage } = c.meter(record.spent, now());
461
+ record.spent = spent;
462
+ return usage;
463
+ }, context);
464
+ }
465
+ const withSessionTime = (own, charged) => {
466
+ if (!charged)
467
+ return own;
468
+ const ownCost = (own?.cost ?? {});
469
+ return { ...charged.usage, ...own, cost: { ...charged.usage.cost, ...ownCost, total: charged.usage.cost.total + (ownCost.total ?? 0) } };
470
+ };
471
+ function toolsFor(c, impls) {
472
+ return BROWSER_TOOLS
473
+ .filter((contract) => impls[contract.name] && (contract.listedWhen !== "downloads" || c.options.workspace))
372
474
  .map((contract) => defineTool({
373
475
  name: contract.name,
374
476
  description: contract.description,
@@ -376,45 +478,57 @@ export function createBrowserExtension(options) {
376
478
  replay: contract.replay,
377
479
  executionMode: contract.executionMode,
378
480
  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);
481
+ const config = await api.snapshot(c.Config, api.conversationId, context);
482
+ c.idle.activity(api.conversationId, +1, (config?.policy.idleReleaseS ?? 0) * 1000);
381
483
  try {
382
- const call = { callId: api.callId, conversationId: api.conversationId, signal: context.abortSignal, label: config?.label ?? "", redact, evidence: options.evidence, classifyPage: options.decisions?.classifyPage };
484
+ const call = { callId: api.callId, conversationId: api.conversationId, signal: context.abortSignal, label: config?.label ?? "", redact: c.redact, evidence: c.options.evidence, classifyPage: c.options.decisions?.classifyPage };
383
485
  // 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) => {
486
+ const out = await (async () => impls[contract.name](args, portFor(c, api, context), call))().catch((error) => {
385
487
  // A throw would reach pi's diagnostic unscrubbed: every failure comes back as the typed envelope, redacted.
386
488
  const typed = error instanceof BrowserFailureError ? error.failure : classifyBrowserError(error, contract.effect === "effect", { aborted: context.abortSignal?.aborted === true });
387
489
  return { content: [{ type: "text", text: JSON.stringify(typed) }], isError: true };
388
490
  });
389
491
  // 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));
492
+ const usage = withSessionTime(out.usage, await chargeCall(c, api, context).catch(() => null));
391
493
  return {
392
- ...forModel(out.content.map((item) => item.type === "text" ? { ...item, text: redact(item.text) } : item)),
494
+ ...forModel(out.content.map((item) => item.type === "text" ? { ...item, text: c.redact(item.text) } : item)),
393
495
  ...(out.isError ? { isError: true } : {}),
394
- ...(out.details ? { details: redactDeep(out.details, redact) } : {}),
496
+ ...(out.details ? { details: redactDeep(out.details, c.redact) } : {}),
395
497
  ...(usage ? { usage: usage } : {}),
396
498
  };
397
499
  }
398
500
  finally {
399
- idle.activity(api.conversationId, -1);
501
+ c.idle.activity(api.conversationId, -1);
400
502
  }
401
503
  },
402
504
  }));
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);
505
+ }
506
+ function sectionFor(c, names) {
507
+ return {
508
+ key: c.name,
509
+ async render(input, context) {
510
+ if (!input.agent.tools.some((tool) => names.has(tool.name)))
511
+ return undefined;
512
+ const config = await input.read.snapshot(c.Config, input.conversationId, context);
513
+ return [browserSection({ idleReleaseS: config?.policy.idleReleaseS ?? UNCONFIGURED.policy.idleReleaseS }), c.options.section?.addendum].filter(Boolean).join("\n\n");
514
+ },
515
+ };
516
+ }
517
+ function childConversation(c, api, context) {
518
+ return async (task) => {
519
+ const config = await api.snapshot(c.Config, api.conversationId, context);
406
520
  const childTools = (await api.agent(context)).tools.filter((tool) => CHILD_TOOLS.has(tool.name));
407
521
  // One child per request, recorded in the commit that creates it: a replay or a repeated call finds it again, and
408
522
  // its submission is deduplicated by request_id.
409
523
  const id = await api.commit(async (tx) => {
410
- const children = await tx.doc(Children, api.conversationId);
524
+ const children = await tx.doc(c.Children, api.conversationId);
411
525
  const key = `${task.site}:${task.requestId}`;
412
526
  const known = children.byRequest[key];
413
527
  if (known !== undefined)
414
528
  return known;
415
529
  const child = await tx.createConversation({ ownership: { kind: "task", taskId: api.taskId } });
416
530
  await configure(tx, child.id, { tools: childTools, instructions: null });
417
- Object.assign(await tx.doc(Config, child.id), config ?? UNCONFIGURED);
531
+ Object.assign(await tx.doc(c.Config, child.id), config ?? UNCONFIGURED);
418
532
  children.byRequest[key] = child.id;
419
533
  return child.id;
420
534
  }, context);
@@ -440,45 +554,69 @@ export function createBrowserExtension(options) {
440
554
  return report;
441
555
  }
442
556
  finally {
443
- await releasePlane({ id, commit: (change, ctx) => api.commit(change, ctx) }, "close", context).catch(() => undefined);
557
+ await releasePlane(c, { id, commit: (change, ctx) => api.commit(change, ctx) }, "close", context).catch(() => undefined);
444
558
  }
445
559
  };
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");
560
+ }
561
+ function siteTool(c, sites) {
562
+ const contract = useWebsiteContract(sites.listing);
563
+ return defineTool({
564
+ name: contract.name,
565
+ description: contract.description,
566
+ parameters: contract.parameters,
567
+ replay: contract.replay,
568
+ executionMode: contract.executionMode,
569
+ execute: async (args, api, context) => {
570
+ const out = await useWebsite(args, sites.port, sites.listing, { signal: context.abortSignal ?? new AbortController().signal, runChild: childConversation(c, api, context) });
571
+ return { ...forModel(out.content.map((item) => item.type === "text" ? { ...item, text: c.redact(item.text) } : item)), ...(out.isError ? { isError: true } : {}) };
467
572
  },
573
+ });
574
+ }
575
+ export function createBrowserExtension(options) {
576
+ const name = options.name ?? "browser";
577
+ const redact = createRedactor(() => providerKeyValues(process.env, options.redact?.values));
578
+ const Config = defineDoc({ kind: `${name}.config`, version: 1, scope: "conversation", history: "latest", fork: "current", initial: () => structuredClone(UNCONFIGURED) });
579
+ const Children = defineDoc({ kind: `${name}.children`, version: 1, scope: "conversation", history: "latest", fork: "current", initial: () => ({ byRequest: {} }) });
580
+ // A fork starts with no sessions: it never shares a live browser.
581
+ const Sessions = defineDoc({ kind: `${name}.sessions`, version: 1, scope: "conversation", history: "latest", fork: "initial", initial: emptySessions });
582
+ const readers = { options, redact, Config };
583
+ /** Class name and redacted message only: a vendor SDK's error text can repeat the request's credentials. */
584
+ const scrubbed = (error) => Object.assign(new Error(redact(error instanceof Error ? error.message : String(error))), { name: error instanceof Error ? error.name : "Error" });
585
+ const prices = resolvePrices(options.prices);
586
+ const priceState = prices.sessionUsdPerHour === null ? "unpriced" : "priced";
587
+ const meter = (spent, at, final = false) => {
588
+ const charged = sessionCharge(spent, at, prices, priceState, final);
589
+ return { spent: { ...charged.spent, state: charged.usage.state }, usage: charged.usage };
468
590
  };
591
+ const store = custodyStore({
592
+ name, Config, Sessions, meter, scrubbed, createDeadlineMs: options.createDeadlineMs ?? CREATE_DEADLINE_MS,
593
+ providerOf: (read, cid, plane, context) => providerOf(readers, read, cid, plane, context),
594
+ emit: (cid, label, record, change) => emit(readers, cid, label, record, change),
595
+ });
596
+ const c = {
597
+ ...readers, name, Sessions, Children, store, meter, held: new Attachments(), serial: keyedSerializer(), guards: new Map(), opened: null, incarnation: randomUUID(),
598
+ idle: idleTracker({ idleMs: DEFAULT_BROWSER_POLICY.idleReleaseS * 1000, onIdle: (cid, fired, idleMs) => void releaseIdle(c, cid, fired, idleMs).catch(() => undefined) }),
599
+ };
600
+ const own = { ...custodyTools, ...pageTools({ guards: c.guards }), ...options.tools };
601
+ // pi checks a call's arguments against the tool's schema before execute, so each implementation receives its own shape.
602
+ const tools = toolsFor(c, own);
603
+ const names = new Set(tools.map((tool) => tool.name));
604
+ const siteTools = options.sites ? [siteTool(c, options.sites)] : [];
469
605
  return {
470
- extension: defineExtension({ name, tools: [...tools, ...siteTools], sections: [section], tasks: [ReleaseTask] }),
471
- docs: { Config, Sessions, Inventory, Children },
606
+ extension: defineExtension({ name, tools: [...tools, ...siteTools], sections: [sectionFor(c, names)], tasks: [store.ReleaseTask] }),
607
+ docs: { Config, Sessions, Inventory: store.Inventory, Children },
472
608
  tools: [...tools, ...siteTools],
473
- release: (conversation, reason, context) => releasePlane(conversation, reason, context),
609
+ release: (conversation, reason, context) => releasePlane(c, conversation, reason, context),
474
610
  async reconcile(harness, isActive, context) {
475
- opened = { harness, context };
476
- return reconcileAll(harness, isActive, context);
611
+ c.opened = { harness, context };
612
+ return store.reconcileAll(harness, isActive, context);
477
613
  },
614
+ drain: (harness, context, signal) => drainReleases(name, harness, context, signal),
478
615
  async close() {
479
- idle.clear();
616
+ c.idle.clear();
480
617
  // 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));
618
+ await Promise.all(c.held.tags().map((tag) => c.held.detach(tag)));
482
619
  },
620
+ retained: () => new Set([...c.guards.keys(), ...c.idle.keys(), ...c.serial.keys().map((key) => Number(key.slice(0, key.indexOf(":"))))]).size,
483
621
  };
484
622
  }