@parcha/pi-browser 0.1.0-beta.35 → 0.1.0-beta.351

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 (66) hide show
  1. package/CHANGELOG.md +162 -0
  2. package/NOTICE +6 -1
  3. package/README.md +65 -39
  4. package/dist/core/contract.js +4 -1
  5. package/dist/core/custody.d.ts +6 -0
  6. package/dist/core/custody.js +15 -3
  7. package/dist/core/downloads.d.ts +37 -3
  8. package/dist/core/downloads.js +81 -57
  9. package/dist/core/driving-guard.d.ts +1 -1
  10. package/dist/core/driving-guard.js +1 -1
  11. package/dist/core/files.d.ts +17 -2
  12. package/dist/core/files.js +157 -9
  13. package/dist/core/host.d.ts +20 -14
  14. package/dist/core/images.d.ts +32 -4
  15. package/dist/core/images.js +81 -16
  16. package/dist/core/lease.d.ts +2 -1
  17. package/dist/core/page-scan.d.ts +81 -2
  18. package/dist/core/page-scan.js +487 -13
  19. package/dist/core/public-fetch.d.ts +70 -9
  20. package/dist/core/public-fetch.js +348 -51
  21. package/dist/core/read-page-worker.js +5 -4
  22. package/dist/core/read-page.d.ts +23 -8
  23. package/dist/core/read-page.js +64 -20
  24. package/dist/core/tools.d.ts +23 -1
  25. package/dist/core/tools.js +46 -4
  26. package/dist/core/usage.d.ts +4 -1
  27. package/dist/core/usage.js +5 -2
  28. package/dist/core/vault.d.ts +0 -10
  29. package/dist/core/vault.js +0 -13
  30. package/dist/driver/cdp.js +3 -3
  31. package/dist/driver/page-driver.js +7 -3
  32. package/dist/driver/stagehand.d.ts +3 -1
  33. package/dist/driver/stagehand.js +4 -2
  34. package/dist/durable/store.d.ts +14 -3
  35. package/dist/durable/store.js +204 -51
  36. package/dist/durable.d.ts +31 -4
  37. package/dist/durable.js +61 -16
  38. package/dist/index.d.ts +3 -2
  39. package/dist/index.js +5 -2
  40. package/dist/live-view/index.d.ts +3 -1
  41. package/dist/live-view/index.js +4 -0
  42. package/dist/live-view/protocol.d.ts +1 -1
  43. package/dist/live-view/server.d.ts +30 -0
  44. package/dist/live-view/server.js +152 -25
  45. package/dist/providers/cdp.js +2 -2
  46. package/dist/providers/profiles.d.ts +1 -15
  47. package/dist/providers/profiles.js +1 -64
  48. package/dist/providers/shared.d.ts +1 -47
  49. package/dist/providers/shared.js +1 -82
  50. package/dist/providers/worker-extension.d.ts +14 -1
  51. package/dist/providers/worker-extension.js +69 -3
  52. package/dist/testing/backend.d.ts +4 -3
  53. package/dist/testing/backend.js +6 -5
  54. package/dist/vault-session.d.ts +4 -7
  55. package/dist/vault-session.js +26 -81
  56. package/dist/vendor/browser-use-pi/page.d.ts +3 -12
  57. package/dist/vendor/browser-use-pi/page.js +6 -19
  58. package/package.json +8 -21
  59. package/dist/providers/browserbase-net.d.ts +0 -12
  60. package/dist/providers/browserbase-net.js +0 -95
  61. package/dist/providers/browserbase.d.ts +0 -138
  62. package/dist/providers/browserbase.js +0 -294
  63. package/dist/providers/kernel.d.ts +0 -58
  64. package/dist/providers/kernel.js +0 -291
  65. /package/dist/{providers → core}/cdp-call.d.ts +0 -0
  66. /package/dist/{providers → core}/cdp-call.js +0 -0
@@ -3,19 +3,35 @@ import { backoffMs, HANDOFF_POLL_MS, moveRecord, notices } from "../core/custody
3
3
  export const now = () => new Date().toISOString();
4
4
  const iso = (ms) => new Date(ms).toISOString();
5
5
  const cidOf = (row) => row.conversationId;
6
+ /** Waits `ms`, or until `signal` aborts. */
7
+ const pause = (ms, signal) => new Promise((resolve) => {
8
+ const done = () => { clearTimeout(timer); signal?.removeEventListener("abort", done); resolve(); };
9
+ const timer = setTimeout(done, ms);
10
+ signal?.addEventListener("abort", done, { once: true });
11
+ });
6
12
  /** Release attempts before custody is given up as `lost`, and status polls before a release is sent again. */
7
13
  export const RELEASE_ATTEMPTS = 6;
8
14
  export const CONFIRM_POLLS = 5;
9
- export function custodyStore({ name, Config, Sessions, providerOf, emit, meter, bill, scrubbed, createDeadlineMs, handoff, handedBack, stopped: stoppedHook }) {
15
+ const madeOf = (refs) => Object.fromEntries(refs.flatMap((ref) => (ref.madeAt ? [[ref.id, ref.madeAt]] : [])));
16
+ /** `made` without the ids `told`; undefined when none is left. */
17
+ const madeLeft = (made, told = []) => {
18
+ const left = Object.entries(made ?? {}).filter(([id]) => !told.includes(id));
19
+ return left.length ? Object.fromEntries(left) : undefined;
20
+ };
21
+ export function custodyStore({ name, Config, Sessions, providerOf, emit, meter, bill, scrubbed, createDeadlineMs, handoff, handedBack, stopped: stoppedHook, raced }) {
10
22
  const Inventory = defineDoc({ kind: `${name}.inventory`, version: 1, scope: "session", initial: () => ({ rows: {} }), checkpointWhen: () => false });
11
23
  /** One state change: the record and the open-session inventory move in the same commit. */
12
24
  async function move(tx, row, next) {
13
25
  const inventory = await tx.doc(Inventory);
14
- // A lost one stays: custody gave up releasing it, not looking for it (reconcile releases it again at run open).
15
- if (next.state === "released")
26
+ const owed = union(inventory.rows[row.tag]?.owed, next.owed).filter((id) => !next.told?.includes(id));
27
+ const made = madeLeft(inventory.rows[row.tag]?.made, next.told);
28
+ const { owed: _stale, made: _staleMade, ...fields } = row;
29
+ // A lost one stays: custody gave up releasing it, not looking for it (reconcile releases it again at run open). So
30
+ // does a released one that still owes a raced call: the reconcile confirms those sessions' stop and tells them.
31
+ if (next.state === "released" && !owed.length)
16
32
  delete inventory.rows[row.tag];
17
33
  else
18
- inventory.rows[row.tag] = { ...row, state: next.state, resourceId: next.resourceId ?? row.resourceId };
34
+ inventory.rows[row.tag] = { ...fields, state: next.state === "released" ? "lost" : next.state, resourceId: next.resourceId ?? row.resourceId, ...(owed.length ? { owed } : {}), ...(made ? { made } : {}) };
19
35
  const state = await tx.doc(Sessions, cidOf(row));
20
36
  const record = state.sessions.find((r) => r.tag === row.tag);
21
37
  if (!record)
@@ -36,9 +52,33 @@ export function custodyStore({ name, Config, Sessions, providerOf, emit, meter,
36
52
  const addNotice = (state, text) => { if (!state.notice?.includes(text))
37
53
  state.notice = [state.notice, text].filter(Boolean).join(" "); };
38
54
  const begin = async (tx, row) => { (await tx.doc(Inventory)).rows[row.tag] = { ...row, state: "creating", resourceId: null }; };
55
+ /** Saves `ids` on the row as owed, and when the provider made each (`made`), before any stop is sent to them. */
56
+ const owe = async (tx, row, ids, made = {}) => {
57
+ const rows = (await tx.doc(Inventory)).rows;
58
+ const at = rows[row.tag] ?? row;
59
+ rows[row.tag] = { ...at, owed: union(at.owed, ids), ...madeOn(at, made) };
60
+ };
61
+ /** The row's `made` with `made` added, as fields to spread on it. */
62
+ const madeOn = (at, made) => {
63
+ const all = madeLeft({ ...at.made, ...made });
64
+ return all ? { made: all } : {};
65
+ };
66
+ /** Saves when the provider made the sessions a release found (`made`) on the row, before any stop is sent to them. */
67
+ const noteMade = async (tx, row, made) => {
68
+ const rows = (await tx.doc(Inventory)).rows;
69
+ const at = rows[row.tag];
70
+ if (at && Object.keys(made).length)
71
+ rows[row.tag] = { ...at, ...madeOn(at, made) };
72
+ };
73
+ /** When the provider made the row's sessions, as its row holds it now, with `seen` (this process's lookups) over it. */
74
+ const madeFor = async (read, row, context, seen = {}) => ({ ...(await read.snapshot(Inventory, context))?.rows?.[row.tag]?.made, ...seen });
75
+ /** The release confirms the row's owed sessions with its own and tells them (they go in as `found`). A row with no id
76
+ * yet leaves them to the reconcile: its release takes the first id it finds as its own. */
39
77
  async function requestRelease(tx, row, reason, at, notBefore) {
78
+ const owed = row.resourceId === null ? [] : (await tx.doc(Inventory)).rows[row.tag]?.owed ?? [];
40
79
  await move(tx, row, { state: "releasing", reason, at });
41
- await tx.createTask(ReleaseTask, { row: { ...row, state: "releasing" }, ...(notBefore ? { notBefore } : {}) }, { ownership: { kind: "conversation" }, conversationId: cidOf(row), background: true });
80
+ const { owed: _stale, made: _staleMade, ...fields } = row;
81
+ await tx.createTask(ReleaseTask, { row: { ...fields, state: "releasing" }, ...(notBefore ? { notBefore } : {}), ...(owed.length ? { found: owed } : {}) }, { ownership: { kind: "conversation" }, conversationId: cidOf(row), background: true });
42
82
  }
43
83
  /** A create no tag lookup finds may still land (a crashed or fenced holder's call in flight): the release task looks
44
84
  * again by tag after the create deadline and releases whatever landed. */
@@ -46,12 +86,28 @@ export function custodyStore({ name, Config, Sessions, providerOf, emit, meter,
46
86
  /** `found` hears the ids before any is released: a release that stops a session and then fails (its status check after
47
87
  * the stop) leaves the session known only to its caller, since the provider's tag lookup lists running sessions only. */
48
88
  async function releaseAll(row, provider, signal, found = () => { }) {
49
- const ids = [...new Set([row.resourceId, ...(await provider.findByTag(row.tag, signal)).map((ref) => ref.id)].filter((id) => id !== null))];
50
- await found(ids);
89
+ const refs = await provider.findByTag(row.tag, signal);
90
+ const ids = [...new Set([row.resourceId, ...refs.map((ref) => ref.id)].filter((id) => id !== null))];
91
+ await found(ids, madeOf(refs));
51
92
  for (const id of ids)
52
93
  await provider.release({ id, tag: row.tag }, signal);
53
94
  return ids;
54
95
  }
96
+ /** The sessions among `ids` besides `row`'s own. `ids` are what its release found, every attempt's, oldest first (the
97
+ * task's checkpoint keeps them): its own is its id, or for a create whose answer was lost the first its tag found
98
+ * (foundId), whose record bills it. */
99
+ const othersOf = (row, ids) => {
100
+ const own = row.resourceId ?? ids[0];
101
+ return ids.filter((id) => id !== own);
102
+ };
103
+ /** The host hears the sessions besides `row`'s own among `ids` (raced) once their stop is confirmed, `ids` every id the
104
+ * release found: one whose release stopped it and then failed (its status read) is found by no later lookup, so it is
105
+ * told from the ids its release kept, once, by the step that confirms the release. */
106
+ const tellRaced = async (row, ids, made) => {
107
+ const extras = othersOf(row, ids);
108
+ if (extras.length)
109
+ await raced?.(row, extras, await made());
110
+ };
55
111
  const anyRunning = async (provider, row, ids, signal) => {
56
112
  for (const id of ids)
57
113
  if (["pending", "running"].includes(await provider.status({ id, tag: row.tag }, signal)))
@@ -78,30 +134,72 @@ export function custodyStore({ name, Config, Sessions, providerOf, emit, meter,
78
134
  return fallback;
79
135
  }
80
136
  }
137
+ /** Releases `extras` and returns those a status read confirms stopped, read again (backoffMs) up to CONFIRM_POLLS times
138
+ * while a read fails or a stop that was sent is still under way; one still running after a release that failed is
139
+ * not read again. One not returned stays owed on the row. */
140
+ async function stopExtras(provider, row, extras, signal) {
141
+ const open = new Map();
142
+ for (const extra of extras)
143
+ open.set(extra.id, await provider.release(extra, signal).then(() => true, () => false));
144
+ const stopped = new Set();
145
+ for (let poll = 0; open.size && poll < CONFIRM_POLLS && !signal?.aborted; poll += 1) {
146
+ if (poll)
147
+ await pause(backoffMs(poll - 1), signal);
148
+ for (const [id, sent] of [...open]) {
149
+ const state = await provider.status({ id, tag: row.tag }, signal).catch(() => null);
150
+ if (state === null)
151
+ continue;
152
+ if (!["pending", "running"].includes(state))
153
+ (stopped.add(id), open.delete(id));
154
+ else if (!sent)
155
+ open.delete(id);
156
+ }
157
+ }
158
+ return extras.map((extra) => extra.id).filter((id) => stopped.has(id));
159
+ }
81
160
  /** A create whose answer never came, settled by its tag: the first session found is kept and committed `live`; extras
82
- * (a create retried behind the provider's API) are released. */
161
+ * (a create retried behind the provider's API) are saved on the row as owed, then released, and told as raced once
162
+ * their stop is confirmed. One no read confirms here stays owed, for the session's own release or the reconcile. */
83
163
  async function bindByTag(provider, row, commit, signal, found) {
84
164
  const refs = found ?? await provider.findByTag(row.tag, signal);
85
- for (const extra of refs.slice(1))
86
- await provider.release(extra, signal).catch(() => undefined);
165
+ const extras = refs.slice(1);
166
+ if (extras.length)
167
+ await commit((tx) => owe(tx, row, extras.map((ref) => ref.id), madeOf(extras)));
168
+ const stopped = await stopExtras(provider, row, extras, signal);
169
+ if (stopped.length)
170
+ await raced?.(row, stopped, madeOf(extras));
87
171
  const kept = refs[0] ?? null;
88
- await commit((tx) => kept ? move(tx, row, { state: "live", resourceId: kept.id, at: now() }) : unknownCreate(tx, row, now()));
172
+ await commit((tx) => kept ? move(tx, row, { state: "live", resourceId: kept.id, at: now(), told: stopped }) : unknownCreate(tx, row, now()));
89
173
  return kept;
90
174
  }
91
- async function emitReleased(cid, tag, read, context, at = now()) {
175
+ /** `found`: the id a release task's lookup found for a record that has none yet, which the commit after this one
176
+ * records; the host hears the session with it, and with the bill that commit makes. */
177
+ async function emitReleased(cid, tag, read, context, at = now(), found = {}) {
92
178
  const [state, config] = await Promise.all([read.snapshot(Sessions, cid, context), read.snapshot(Config, cid, context)]);
93
- const record = state?.sessions.find((r) => r.tag === tag);
179
+ const stored = state?.sessions.find((r) => r.tag === tag);
180
+ const record = stored && stored.resourceId === null && found.resourceId ? { ...stored, resourceId: found.resourceId } : stored;
94
181
  const spent = record && record.resourceId !== null ? meter(record.spent, at, true).spent : record?.spent;
95
182
  if (record && spent)
96
183
  await emit(cid, config?.label ?? "", { ...record, state: "released", endedAt: record.endedAt ?? at, spent }, "released");
97
184
  }
98
185
  const union = (...lists) => [...new Set(lists.flatMap((ids) => ids ?? []))];
99
186
  /** The row stays in the inventory until a run open's reconcile sees nothing under its tag running. `found` goes on to
100
- * the next attempt, and bills a lost one. */
187
+ * the next attempt, and bills a lost one; of a lost one's other sessions, each the provider says no longer runs is
188
+ * told (raced), and the rest stay owed on the row for the reconcile. */
101
189
  async function retry(runtime, row, attempt, context, found) {
102
190
  if (attempt + 1 >= RELEASE_ATTEMPTS) {
191
+ const ended = await step(runtime, async () => {
192
+ const provider = await providerOf(runtime, cidOf(row), row.plane, context);
193
+ const out = [];
194
+ for (const id of othersOf(row, found))
195
+ if (!(await anyRunning(provider, row, [id], runtime.signal)))
196
+ out.push(id);
197
+ return out;
198
+ }, []);
199
+ if (ended.length)
200
+ await raced?.(row, ended, await madeFor(runtime, row, context));
103
201
  await runtime.commit(async (tx) => {
104
- await move(tx, row, { state: "lost", reason: "lost", at: iso(runtime.now()), ...foundId(row, found) });
202
+ await move(tx, row, { state: "lost", reason: "lost", at: iso(runtime.now()), ...foundId(row, found), owed: othersOf(row, found), told: ended });
105
203
  return { status: "terminal", outcome: { status: "failed", error: { code: "release_failed", message: `${row.tag}: not released after ${RELEASE_ATTEMPTS} attempts` } } };
106
204
  }, context);
107
205
  return;
@@ -127,11 +225,15 @@ export function custodyStore({ name, Config, Sessions, providerOf, emit, meter,
127
225
  // Ids the lookup found that the task does not hold yet are committed before any stop is sent: an attempt cut
128
226
  // between its stop and its next commit (the task's abort) leaves them for the abort handler, whose own lookup
129
227
  // no longer lists a stopped session.
130
- const keep = async (ids) => {
228
+ const keep = async (ids, made) => {
131
229
  seen = ids;
132
230
  const known = union(found, ids);
133
- if (known.length > found.length)
134
- await runtime.commit(() => ({ status: "running", checkpoint: { phase: "release", attempt, found: known } }), context);
231
+ if (known.length > found.length) {
232
+ await runtime.commit(async (tx) => {
233
+ await noteMade(tx, row, made);
234
+ return { status: "running", checkpoint: { phase: "release", attempt, found: known } };
235
+ }, context);
236
+ }
135
237
  };
136
238
  const released = await step(runtime, async () => releaseAll(row, await providerOf(runtime, cidOf(row), row.plane, context), runtime.signal, keep), null);
137
239
  // What the lookup found goes on to the next attempt even when its release failed: the stop may have landed.
@@ -152,12 +254,13 @@ export function custodyStore({ name, Config, Sessions, providerOf, emit, meter,
152
254
  }
153
255
  if (running)
154
256
  return retry(runtime, row, attempt, context, ids);
155
- // The host hears the release before the task's last commit, so at least once, with the bill that commit
156
- // records.
257
+ // The host hears the release, and the other sessions it ended (tellRaced), before the task's last commit, so at
258
+ // least once, with the bill that commit records.
157
259
  const at = iso(runtime.now());
158
- await emitReleased(cidOf(row), row.tag, runtime, context, at);
260
+ await emitReleased(cidOf(row), row.tag, runtime, context, at, foundId(row, ids));
261
+ await tellRaced(row, ids, () => madeFor(runtime, row, context));
159
262
  await runtime.commit(async (tx) => {
160
- await move(tx, row, { state: "released", at, ...foundId(row, ids) });
263
+ await move(tx, row, { state: "released", at, ...foundId(row, ids), told: othersOf(row, ids) });
161
264
  return { status: "terminal", outcome: { status: "completed", result: { released: ids.length } } };
162
265
  }, context);
163
266
  },
@@ -169,14 +272,30 @@ export function custodyStore({ name, Config, Sessions, providerOf, emit, meter,
169
272
  const checkpoint = task.state.checkpoint;
170
273
  let found = union(task.input.found, checkpoint.phase === "confirm" ? checkpoint.ids : checkpoint.found);
171
274
  let stopped = null;
172
- // Before the create deadline nothing found is proof of nothing: the successor keeps the delayed lookup.
275
+ let confirmed = [];
276
+ let seen = {};
277
+ // Before the create deadline nothing found is proof of nothing: the successor keeps the delayed lookup. The ids
278
+ // earlier attempts found that no lookup lists now are read once each; one not confirmed stays owed on the row.
173
279
  if (!(notBefore && runtime.now() < notBefore))
174
- stopped = await providerOf(runtime, cidOf(row), row.plane, context).then((provider) => releasedIds(provider, row, context.abortSignal, (ids) => void (found = union(found, ids)))).catch(() => null);
280
+ stopped = await providerOf(runtime, cidOf(row), row.plane, context).then(async (provider) => {
281
+ const ids = await releasedIds(provider, row, context.abortSignal, (ids, made) => void ((found = union(found, ids)), (seen = { ...seen, ...made })));
282
+ if (ids)
283
+ for (const id of found)
284
+ if (ids.includes(id) || !(await anyRunning(provider, row, [id], context.abortSignal).catch(() => true)))
285
+ confirmed.push(id);
286
+ return ids;
287
+ }).catch(() => null);
288
+ const others = stopped ? othersOf(row, union(found, stopped)) : [];
289
+ const told = others.filter((id) => stopped?.includes(id) || confirmed.includes(id));
175
290
  if (stopped)
176
291
  stoppedHook?.(row.tag);
292
+ if (told.length)
293
+ await raced?.(row, told, await madeFor(runtime, row, context, seen));
177
294
  await runtime.commit(async (tx) => {
178
295
  if (stopped)
179
- await move(tx, row, { state: "released", at: iso(runtime.now()), ...foundId(row, union(found, stopped)) });
296
+ await noteMade(tx, row, seen);
297
+ if (stopped)
298
+ await move(tx, row, { state: "released", at: iso(runtime.now()), ...foundId(row, union(found, stopped)), owed: others, told });
180
299
  else
181
300
  await tx.createTask(ReleaseTask, { ...task.input, ...(found.length ? { found } : {}) }, { ownership: { kind: "conversation" }, conversationId: cidOf(row), background: true });
182
301
  return { status: "terminal", outcome: { status: "aborted", reason: stopped ? "released by the abort handler" : "release handed to a successor task" } };
@@ -262,6 +381,65 @@ export function custodyStore({ name, Config, Sessions, providerOf, emit, meter,
262
381
  } while (cursor);
263
382
  return undefined;
264
383
  }
384
+ /** A lost row at run open: the sessions besides its own that its tag lists are saved as owed, then its own and those
385
+ * are released, and its own and every owed one read once each. The others a read confirms stopped are told (raced) though another's release failed; the rest stay owed.
386
+ * The row goes, its record billed, once every release answered and every session is confirmed stopped; a release
387
+ * that failed leaves it for the next reconcile (unreachable). A session known only by its tag (no id on the row) is
388
+ * the first its tag lists, kept on the row and record before any stop is sent, as its tag lookup lists running
389
+ * sessions only. */
390
+ async function reconcileLost(provider, row, commit, outcome, at) {
391
+ const refs = await provider.findByTag(row.tag);
392
+ const listed = refs.map((ref) => ref.id);
393
+ const made = { ...row.made, ...madeOf(refs) };
394
+ const own = row.resourceId ?? listed[0] ?? null;
395
+ const others = union(listed, row.owed).filter((id) => id !== own);
396
+ if (others.some((id) => !row.owed?.includes(id)) || own !== row.resourceId) {
397
+ await commit(async (tx) => {
398
+ await owe(tx, row, others, made);
399
+ const rows = (await tx.doc(Inventory)).rows;
400
+ if (own !== null && rows[row.tag]?.resourceId === null)
401
+ rows[row.tag].resourceId = own;
402
+ const record = (await tx.doc(Sessions, cidOf(row))).sessions.find((r) => r.tag === row.tag);
403
+ if (own !== null && record && record.resourceId === null)
404
+ record.resourceId = own;
405
+ });
406
+ }
407
+ let answered = true;
408
+ for (const id of union(own === null ? [] : [own], listed))
409
+ if (!(await provider.release({ id, tag: row.tag }).then(() => true, () => false)))
410
+ answered = false;
411
+ const stopped = [];
412
+ for (const id of union(own === null ? [] : [own], others))
413
+ if (!(await anyRunning(provider, row, [id]).catch(() => true)))
414
+ stopped.push(id);
415
+ const told = others.filter((id) => stopped.includes(id));
416
+ if (told.length)
417
+ await raced?.(row, told, made);
418
+ const done = answered && (own === null || stopped.includes(own)) && told.length === others.length;
419
+ if (done) {
420
+ await outcome("released", async (tx) => {
421
+ delete (await tx.doc(Inventory)).rows[row.tag];
422
+ const record = (await tx.doc(Sessions, cidOf(row))).sessions.find((r) => r.tag === row.tag);
423
+ if (record && record.resourceId !== null)
424
+ await bill(tx, cidOf(row), record, at, true);
425
+ });
426
+ return;
427
+ }
428
+ if (told.length) {
429
+ await commit(async (tx) => {
430
+ const rows = (await tx.doc(Inventory)).rows;
431
+ const at = rows[row.tag];
432
+ if (!at)
433
+ return;
434
+ const { made: _told, ...fields } = at;
435
+ const left = madeLeft(at.made, told);
436
+ rows[row.tag] = { ...fields, owed: (at.owed ?? []).filter((id) => !told.includes(id)), ...(left ? { made: left } : {}) };
437
+ });
438
+ }
439
+ if (!answered)
440
+ throw new Error(`${row.tag}: a release failed`);
441
+ await outcome("lost");
442
+ }
265
443
  async function reconcileAll(harness, isActive, context) {
266
444
  const report = { released: [], kept: [], lost: [], unreachable: [] };
267
445
  for (const row of Object.values((await harness.snapshot(Inventory, context))?.rows ?? {})) {
@@ -274,32 +452,7 @@ export function custodyStore({ name, Config, Sessions, providerOf, emit, meter,
274
452
  try {
275
453
  const provider = await providerOf(harness, cidOf(row), row.plane, context);
276
454
  if (row.state === "lost") {
277
- let seen = [];
278
- const ids = await releasedIds(provider, row, undefined, (found) => void (seen = found)).catch(async (error) => {
279
- // The stop may have landed before the provider's answer was lost, and its tag lookup lists running sessions
280
- // only: a session known only by its tag keeps the id found on its row and record, for the next reconcile to
281
- // release and bill.
282
- const id = row.resourceId === null ? seen[0] : undefined;
283
- if (id !== undefined) {
284
- await commit(async (tx) => {
285
- const rows = (await tx.doc(Inventory)).rows;
286
- if (rows[row.tag])
287
- rows[row.tag] = { ...rows[row.tag], resourceId: id };
288
- const record = (await tx.doc(Sessions, cidOf(row))).sessions.find((r) => r.tag === row.tag);
289
- if (record && record.resourceId === null)
290
- record.resourceId = id;
291
- }).catch(() => undefined);
292
- }
293
- throw error;
294
- });
295
- await (ids ? outcome("released", async (tx) => {
296
- delete (await tx.doc(Inventory)).rows[row.tag];
297
- const record = (await tx.doc(Sessions, cidOf(row))).sessions.find((r) => r.tag === row.tag);
298
- if (record && record.resourceId === null && ids.length)
299
- record.resourceId = ids[0];
300
- if (record && record.resourceId !== null)
301
- await bill(tx, cidOf(row), record, at, true);
302
- }) : outcome("lost"));
455
+ await reconcileLost(provider, row, commit, outcome, at);
303
456
  continue;
304
457
  }
305
458
  let live = row;
package/dist/durable.d.ts CHANGED
@@ -1,9 +1,10 @@
1
- import type { Context } from "@earendil-works/chord";
1
+ import type { Context } from "@earendil-works/chord/context";
2
2
  import { type Conversation, type ConversationDocToken, type ConversationId, type Extension, type Harness, type SessionDocToken, type ToolRegistration, type Tx } from "@earendil-works/pi-durable";
3
3
  import { type DriverFactory } from "./core/custody.js";
4
4
  import type { Decisions } from "./core/decisions.js";
5
5
  import type { EvidenceSink } from "./core/evidence.js";
6
6
  import { EffectObserver } from "./core/effects.js";
7
+ import type { DownloadsWorkspace } from "./core/downloads.js";
7
8
  import { type VaultOptions } from "./vault-session.js";
8
9
  import type { DrivingGates } from "./live-view/protocol.js";
9
10
  import { type BrowserToolImpls, type PageDriver } from "./core/tools.js";
@@ -34,11 +35,12 @@ export type BrowserExtensionOptions<D extends PageDriver = PageDriver> = VaultOp
34
35
  /** Implementations by contract name, over the package's own; a contract tool with no implementation is not listed. */
35
36
  tools?: Partial<BrowserToolImpls<D>>;
36
37
  evidence: EvidenceSink;
37
- /** Where `browser_downloads` writes files and, without `files`, where `browser_upload` reads them; absent, neither is listed. */
38
- workspace?: (conversationId: ConversationId) => string;
38
+ /** The workspace `browser_downloads` writes files into, through the host's own file calls, which follow no link
39
+ * (DownloadsWorkspace); absent, it is not listed. */
40
+ workspace?: (conversationId: ConversationId) => DownloadsWorkspace;
39
41
  /** Reaches a person for `browser_request_handoff`; absent, the tool is not listed. */
40
42
  handoff?: HandoffPort;
41
- /** Resolves `browser_upload` paths; defaults to files under `workspace`. */
43
+ /** Resolves `browser_upload` paths (workspaceFiles over a folder is one); absent, it is not listed. */
42
44
  files?: WorkspaceFiles;
43
45
  /** Live view and session status; a throw here never fails a call. */
44
46
  onSession?: (row: SessionRow, change: SessionChange) => void | Promise<void>;
@@ -56,6 +58,20 @@ export type BrowserExtensionOptions<D extends PageDriver = PageDriver> = VaultOp
56
58
  onCharge?: (charge: SessionCharge, tx: Tx, call?: {
57
59
  callId: string;
58
60
  }) => void | Promise<void>;
61
+ /** A release by a session's tag ended sessions besides that session's own: a create retried behind the provider's API,
62
+ * or a create race of the session's tag, left them running, and no record bills their time. Their ids, so a host books
63
+ * what they ran, once a status read confirms each stopped, one whose release stopped it and then failed included. Each
64
+ * is saved on the session's inventory row (`owed`) before its stop is sent, until it is told: the session's own release
65
+ * confirms them, or a run open's reconcile for a row that ended lost or still owes one. Called again for an id only
66
+ * when a process ends between this call and the commit that takes it off the row. A throw here never fails the
67
+ * release. `madeAt`: when the provider made each of them (an ISO time, by id), where its tag lookup said
68
+ * (LeaseRef.madeAt), kept on the row with the id, so a later process hands it on too; absent when it said for none. */
69
+ onRaceReleased?: (released: {
70
+ conversationId: number;
71
+ tag: string;
72
+ ids: string[];
73
+ madeAt?: Record<string, string>;
74
+ }) => void | Promise<void>;
59
75
  /** Exact strings to scrub from every output besides the built-in shapes, read at each use. */
60
76
  redact?: {
61
77
  values: () => readonly string[];
@@ -107,6 +123,17 @@ export type BrowserExtensionHandle = {
107
123
  close(): Promise<void>;
108
124
  /** How many conversations the extension still holds in-memory state for: a repeat guard, an idle timer or a queued call. */
109
125
  retained(): number;
126
+ /** Keeps session `tag` from its idle release while the run waits for its person's answer (the host bounds that wait):
127
+ * an idle window that ends meanwhile releases nothing. The returned function lets it go, once; when the last keep on
128
+ * the tag goes, its idle window starts again from then. Releases for any other reason (the tool, a close, its end)
129
+ * are not held. */
130
+ keepForPerson(tag: string): () => void;
131
+ /** Bills each session of the conversation still open (live, held, or releasing: its release asked, not yet confirmed)
132
+ * through now, not final, in one commit that moves each one's `chargedThrough` with its charge (onCharge): what a host
133
+ * that stops waiting on a release books of the time known so far. The release's own charge, when it lands, bills only
134
+ * the time after it, and an `at` before it bills nothing and says so (SessionCharge.overbookedS). Resolves to the
135
+ * sessions charged. */
136
+ charge(conversation: Pick<Conversation, "id" | "commit">, context: Context): Promise<number>;
110
137
  };
111
138
  export { CONFIRM_POLLS, RELEASE_ATTEMPTS } from "./durable/store.js";
112
139
  export { HANDOFF_POLL_MS } from "./core/custody.js";
package/dist/durable.js CHANGED
@@ -1,11 +1,10 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { defineDoc, defineExtension, defineTool } from "@earendil-works/pi-durable";
3
3
  import { browserSection, browserToolsFor, listedFor } from "./core/contract.js";
4
- import { BrowserFailureError, closeDriver, currentRecord, loadedNoPage, custodyTools, FIXED_SESSION_RELAUNCH, fenced, HANDED_BACK, newSessionRecord, notices, NAVIGATION_CAP, NOTHING_TO_HOLD, navigationRefusal, profileRefusal, relaunchRefusal, SESSION_REPLACED, sessionSpec, waitingForHuman, NO_HANDOFF } from "./core/custody.js";
4
+ import { BrowserFailureError, closeDriver, DRIVER_ACK_BEFORE_KILL_MS, settledWithin, currentRecord, loadedNoPage, custodyTools, FIXED_SESSION_RELAUNCH, fenced, HANDED_BACK, newSessionRecord, notices, NAVIGATION_CAP, NOTHING_TO_HOLD, navigationRefusal, profileRefusal, relaunchRefusal, SESSION_REPLACED, sessionSpec, waitingForHuman, NO_HANDOFF } from "./core/custody.js";
5
5
  import { forModel } from "./durable/result.js";
6
6
  import { EffectObserver, effectDecider, observerFailure } from "./core/effects.js";
7
7
  import { browserFailure, classifyBrowserError, isRefusal } from "./core/failures.js";
8
- import { workspaceFiles } from "./core/files.js";
9
8
  import { drivingGuarded } from "./core/driving-guard.js";
10
9
  import { drivingGates, keptFor, keptReason, personOn, rearmWhenLeft } from "./core/driving.js";
11
10
  import { captureFor, planRestore, untilQuiet, vaultRuntime } from "./vault-session.js";
@@ -238,7 +237,6 @@ async function create(c, scope, overrides, presetTag) {
238
237
  const unsupported = profileRefusal(spec, provider.caps) ?? navigationRefusal(spec, provider);
239
238
  if (unsupported)
240
239
  throw new BrowserFailureError(unsupported);
241
- // The vault may name a context or profile for the provider; the record stored below is made from the spec WITHOUT it, so no context id reaches the store.
242
240
  const plan = await planRestore(c.vault, config.vault, provider, spec);
243
241
  const record = newSessionRecord({ plane: scope.plane, tag, provider: provider.name, spec, at: now(), honours: provider.caps.settings });
244
242
  const row = rowOf(scope.cid, record);
@@ -283,9 +281,6 @@ async function create(c, scope, overrides, presetTag) {
283
281
  const live = { ...record, state: "live", resourceId: ref.id };
284
282
  try {
285
283
  const driver = await connect(c, scope, provider, ref, plan.afterAttach, plan.vaulted, plan.holdBack);
286
- // A context made for this session is given to the vault now, so a restart that loses the provider's memory of it still finds it.
287
- if (plan.fresh)
288
- await c.held.capture(ref.tag);
289
284
  await emit(c, scope.cid, config.label, live, "launched", provider);
290
285
  return { record: live, driver };
291
286
  }
@@ -651,15 +646,19 @@ async function releasePlane(c, conversation, reason, context, still = () => true
651
646
  const mine = () => c.held.tags().filter((tag) => c.owned.get(tag)?.cid === conversation.id);
652
647
  // Kept before anything closes: the browser is still there, and a release that is cancelled (a call since) only made one capture more.
653
648
  await Promise.all(leasesOf(c, conversation.id).map((tag) => captureSession(c, tag)));
654
- // Closing a driver needs nothing from the store, so a release other than idle's starts closing the conversation's
655
- // drivers first and never waits for the commit to do it; the commit runs alongside, so the release task starts as
656
- // early as before. An idle release leaves it to the commit, which can find a call since or a person on the live view.
649
+ // Ack-then-kill, "close" only (a new reason gets the wait by decision, not by default): its drivers' close gets DRIVER_ACK_BEFORE_KILL_MS to answer before the commit that ends the session.
657
650
  const closing = reason === "idle" ? Promise.resolve() : Promise.all(mine().map((tag) => c.held.detach(tag)));
651
+ if (reason === "close")
652
+ await settledWithin(closing, DRIVER_ACK_BEFORE_KILL_MS);
658
653
  const tags = await conversation.commit(async (tx) => {
659
654
  const state = await tx.doc(c.Sessions, conversation.id);
660
655
  const record = still() ? currentRecord(state, PLANE) : null;
661
656
  if (!record || !releasable(record, reason))
662
657
  return [];
658
+ // A run waiting for its person's answer keeps the session from an idle release; letting the keep go starts the idle
659
+ // window again (keepForPerson).
660
+ if (reason === "idle" && c.waiting.has(record.tag))
661
+ return [];
663
662
  // A person driving or watching the session through the live view keeps it from an idle release (#1098); it is
664
663
  // released one idle window after they leave.
665
664
  kept.gate = reason === "idle" ? personOn(c.options.gates ?? drivingGates, record.tag) : null;
@@ -705,6 +704,26 @@ async function releasePlane(c, conversation, reason, context, still = () => true
705
704
  c.leaving.set(tag, rearmWhenLeft(kept.gate, () => c.idle.keys().includes(conversation.id), () => { c.leaving.delete(tag); c.idle.activity(conversation.id, 0); }, idleS * 1000));
706
705
  }
707
706
  }
707
+ /** The open sessions' time through now, not final, in one commit (BrowserExtensionHandle.charge): no lock is taken, so a
708
+ * release under way (its record `releasing`) never holds it back. A record with no session id (its create under way, or
709
+ * its answer lost and the session not yet found by its tag) has nothing at the provider to bill yet: its release's charge
710
+ * bills the whole session once it is found. One already charged through now has no time to charge, and gets no $0 one. */
711
+ async function chargeOpen(c, conversation, context) {
712
+ return conversation.commit(async (tx) => {
713
+ const state = await tx.doc(c.Sessions, conversation.id);
714
+ const at = now();
715
+ let charged = 0;
716
+ for (const record of state.sessions) {
717
+ if ((record.state !== "live" && record.state !== "held" && record.state !== "releasing") || record.resourceId === null || record.spent.final)
718
+ continue;
719
+ if (Date.parse(record.spent.chargedThrough) >= Date.parse(at))
720
+ continue;
721
+ if (await c.bill(tx, conversation.id, record, at, false))
722
+ charged += 1;
723
+ }
724
+ return charged;
725
+ }, context);
726
+ }
708
727
  async function chargeCall(c, api, context) {
709
728
  if (currentRecord(await api.snapshot(c.Sessions, api.conversationId, context), PLANE)?.state !== "live")
710
729
  return null;
@@ -723,7 +742,7 @@ const withSessionTime = (own, charged) => {
723
742
  };
724
743
  function toolsFor(c, impls) {
725
744
  return browserToolsFor(c.options.signIns ?? !!c.options.sessionVault)
726
- .filter((contract) => impls[contract.name] && listedFor(contract, { downloads: !!c.options.workspace, upload: !!(c.options.files || c.options.workspace), handoff: !!c.options.handoff }))
745
+ .filter((contract) => impls[contract.name] && listedFor(contract, { downloads: !!c.options.workspace, upload: !!c.options.files, handoff: !!c.options.handoff }))
727
746
  .map((contract) => defineTool({
728
747
  name: contract.name,
729
748
  description: contract.description,
@@ -735,8 +754,7 @@ function toolsFor(c, impls) {
735
754
  c.idle.activity(api.conversationId, +1, (config?.policy.idleReleaseS ?? 0) * 1000);
736
755
  try {
737
756
  const workspace = c.options.workspace?.(api.conversationId);
738
- const files = c.options.files ?? (workspace === undefined ? undefined : workspaceFiles(workspace));
739
- 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, workspace, files };
757
+ 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, workspace, files: c.options.files };
740
758
  // Inside an async function, so a host tool that throws before it returns a promise is caught too.
741
759
  const out = await (async () => impls[contract.name](args, portFor(c, api, context), call))().catch((error) => {
742
760
  // A throw would reach pi's diagnostic unscrubbed: every failure comes back as the typed envelope, redacted.
@@ -802,16 +820,16 @@ export function createBrowserExtension(options) {
802
820
  const listPriced = options.prices?.sessionUsdPerHour === undefined && prices.sessionUsdPerHour !== null;
803
821
  const meter = (spent, at, final = false) => {
804
822
  const charged = sessionCharge(spent, at, prices, priceState, final);
805
- return { spent: { ...withEstimate(spent, charged.spent, listPriced), state: charged.usage.state }, usage: charged.usage };
823
+ return { spent: { ...withEstimate(spent, charged.spent, listPriced), state: charged.usage.state }, usage: charged.usage, ...(charged.overbookedS === undefined ? {} : { overbookedS: charged.overbookedS }) };
806
824
  };
807
825
  const bill = async (tx, conversationId, record, at, final, call) => {
808
826
  const before = record.spent;
809
827
  if (before.final)
810
828
  return null;
811
- const { spent, usage } = meter(before, at, final);
829
+ const { spent, usage, overbookedS } = meter(before, at, final);
812
830
  record.spent = spent;
813
831
  const seconds = Math.round((spent.seconds - before.seconds) * 1000) / 1000;
814
- await options.onCharge?.({ conversationId, tag: record.tag, provider: record.provider, at, seconds, usd: usage.usage.cost.total, final, state: usage.state }, tx, call);
832
+ await options.onCharge?.({ conversationId, tag: record.tag, provider: record.provider, at, seconds, usd: usage.usage.cost.total, final, state: usage.state, ...(overbookedS === undefined ? {} : { overbookedS }) }, tx, call);
815
833
  return usage;
816
834
  };
817
835
  const leaving = new Map();
@@ -832,9 +850,16 @@ export function createBrowserExtension(options) {
832
850
  handoff: options.handoff,
833
851
  handedBack: (tag, fence) => c.fences.set(tag, { fence, failure: HANDED_BACK }),
834
852
  stopped: (tag) => { c.stops.get(tag)?.stop(); c.stops.delete(tag); },
853
+ raced: async (row, ids, made) => {
854
+ const madeAt = Object.fromEntries(ids.flatMap((id) => (made[id] ? [[id, made[id]]] : [])));
855
+ try {
856
+ await options.onRaceReleased?.({ conversationId: row.conversationId, tag: row.tag, ids, ...(Object.keys(madeAt).length ? { madeAt } : {}) });
857
+ }
858
+ catch { /* the host's booking never fails the release */ }
859
+ },
835
860
  });
836
861
  const c = {
837
- ...readers, name, Sessions, store, bill, held: new Attachments(), vault, fences: new Map(), leaving, serial: keyedSerializer(), guards: new Map(), owned, failed: false, stops: new Map(), ending: null, opened: null, incarnation: randomUUID(),
862
+ ...readers, name, Sessions, store, bill, held: new Attachments(), vault, fences: new Map(), leaving, waiting: new Map(), serial: keyedSerializer(), guards: new Map(), owned, failed: false, stops: new Map(), ending: null, opened: null, incarnation: randomUUID(),
838
863
  idle: idleTracker({ idleMs: DEFAULT_BROWSER_POLICY.idleReleaseS * 1000, onIdle: (cid, fired, idleMs) => void releaseIdle(c, cid, fired, idleMs).catch(() => undefined) }),
839
864
  };
840
865
  // Every browser tool is a model call on its session's driving gate: refused while a person drives the live view, and the viewer's input is held while it runs. The host's own
@@ -848,6 +873,7 @@ export function createBrowserExtension(options) {
848
873
  docs: { Config, Sessions, Inventory: store.Inventory },
849
874
  tools,
850
875
  release: (conversation, reason, context) => releasePlane(c, conversation, reason, context),
876
+ charge: (conversation, context) => chargeOpen(c, conversation, context),
851
877
  async reconcile(harness, isActive, context) {
852
878
  c.opened = { harness, context };
853
879
  c.ending = endingOf(harness);
@@ -884,5 +910,24 @@ export function createBrowserExtension(options) {
884
910
  c.owned.clear();
885
911
  },
886
912
  retained: () => new Set([...c.guards.keys(), ...c.idle.keys(), ...c.serial.keys().map((key) => Number(key.slice(0, key.indexOf(":"))))]).size,
913
+ keepForPerson(tag) {
914
+ c.waiting.set(tag, (c.waiting.get(tag) ?? 0) + 1);
915
+ let kept = true;
916
+ return () => {
917
+ if (!kept)
918
+ return;
919
+ kept = false;
920
+ const left = (c.waiting.get(tag) ?? 1) - 1;
921
+ if (left > 0) {
922
+ c.waiting.set(tag, left);
923
+ return;
924
+ }
925
+ c.waiting.delete(tag);
926
+ // The idle window starts again from now, for a session still owned here.
927
+ const cid = c.owned.get(tag)?.cid;
928
+ if (cid !== undefined && c.idle.keys().includes(cid))
929
+ c.idle.activity(cid, 0);
930
+ };
931
+ },
887
932
  };
888
933
  }
package/dist/index.d.ts CHANGED
@@ -13,8 +13,8 @@ export * from "./core/host.js";
13
13
  export * from "./core/images.js";
14
14
  export * from "./core/lease.js";
15
15
  export * from "./core/page-classifier.js";
16
- export { isPrivateAddress, pinnedLookup, PUBLIC_MAX_BYTES, publicFetch, type PublicAnswer, type PublicFetchOptions } from "./core/public-fetch.js";
17
- export { READ_DEADLINE_MS, READ_MAX_CHARS, readPage, type PageRead, type ReadPageOptions } from "./core/read-page.js";
16
+ export { isPrivateAddress, pinnedLookup, PUBLIC_MAX_BYTES, publicCheck, publicDownload, publicFetch, publicUpload, type PublicAnswer, type PublicFetchOptions, type PublicFile, type PublicUpload } from "./core/public-fetch.js";
17
+ export { PageReadOutOfMemory, READ_DEADLINE_MS, READ_LINKS_MAX, READ_LINKS_MAX_CHARS, READ_MAX_CHARS, READ_WORKER_HEAP_MB, readPage, type PageRead, type ReadPageOptions } from "./core/read-page.js";
18
18
  export * from "./core/receipts.js";
19
19
  export * from "./core/redact.js";
20
20
  export { DEFAULT_BROWSER_POLICY } from "./core/session-control.js";
@@ -22,3 +22,4 @@ export * from "./core/tools.js";
22
22
  export * from "./core/usage.js";
23
23
  export * from "./core/web.js";
24
24
  export * from "./core/vault.js";
25
+ export { cdpCall, type CdpSession } from "./core/cdp-call.js";
package/dist/index.js CHANGED
@@ -14,8 +14,8 @@ export * from "./core/host.js";
14
14
  export * from "./core/images.js";
15
15
  export * from "./core/lease.js";
16
16
  export * from "./core/page-classifier.js";
17
- export { isPrivateAddress, pinnedLookup, PUBLIC_MAX_BYTES, publicFetch } from "./core/public-fetch.js";
18
- export { READ_DEADLINE_MS, READ_MAX_CHARS, readPage } from "./core/read-page.js";
17
+ export { isPrivateAddress, pinnedLookup, PUBLIC_MAX_BYTES, publicCheck, publicDownload, publicFetch, publicUpload } from "./core/public-fetch.js";
18
+ export { PageReadOutOfMemory, READ_DEADLINE_MS, READ_LINKS_MAX, READ_LINKS_MAX_CHARS, READ_MAX_CHARS, READ_WORKER_HEAP_MB, readPage } from "./core/read-page.js";
19
19
  export * from "./core/receipts.js";
20
20
  export * from "./core/redact.js";
21
21
  export { DEFAULT_BROWSER_POLICY } from "./core/session-control.js";
@@ -23,3 +23,6 @@ export * from "./core/tools.js";
23
23
  export * from "./core/usage.js";
24
24
  export * from "./core/web.js";
25
25
  export * from "./core/vault.js";
26
+ // One CDP call over its own socket, kept open for a setting that lasts as long as it (Browser.setDownloadBehavior): what a
27
+ // host holding a vendor's browser for the tool needs beside the driver.
28
+ export { cdpCall } from "./core/cdp-call.js";