@parcha/pi-browser 0.1.0-beta.34 → 0.1.0-beta.340

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 (78) hide show
  1. package/CHANGELOG.md +170 -0
  2. package/NOTICE +6 -1
  3. package/README.md +70 -60
  4. package/dist/core/contract.d.ts +9 -6
  5. package/dist/core/contract.js +12 -30
  6. package/dist/core/custody.d.ts +6 -0
  7. package/dist/core/custody.js +15 -3
  8. package/dist/core/downloads.d.ts +37 -3
  9. package/dist/core/downloads.js +81 -57
  10. package/dist/core/driving-guard.d.ts +1 -1
  11. package/dist/core/driving-guard.js +1 -1
  12. package/dist/core/evidence.d.ts +1 -1
  13. package/dist/core/files.d.ts +20 -2
  14. package/dist/core/files.js +161 -10
  15. package/dist/core/host.d.ts +18 -75
  16. package/dist/core/images.d.ts +32 -4
  17. package/dist/core/images.js +81 -16
  18. package/dist/core/lease.d.ts +2 -1
  19. package/dist/core/page-scan.d.ts +81 -2
  20. package/dist/core/page-scan.js +487 -13
  21. package/dist/core/public-fetch.d.ts +70 -9
  22. package/dist/core/public-fetch.js +348 -51
  23. package/dist/core/read-page-worker.js +5 -4
  24. package/dist/core/read-page.d.ts +23 -8
  25. package/dist/core/read-page.js +64 -20
  26. package/dist/core/redact.d.ts +0 -2
  27. package/dist/core/redact.js +0 -32
  28. package/dist/core/session-control.d.ts +0 -2
  29. package/dist/core/session-control.js +0 -5
  30. package/dist/core/tools.d.ts +23 -1
  31. package/dist/core/tools.js +46 -4
  32. package/dist/core/usage.d.ts +4 -3
  33. package/dist/core/usage.js +5 -4
  34. package/dist/core/vault.d.ts +0 -10
  35. package/dist/core/vault.js +0 -13
  36. package/dist/core/web.d.ts +2 -111
  37. package/dist/core/web.js +0 -443
  38. package/dist/driver/cdp.js +3 -3
  39. package/dist/driver/page-driver.js +7 -3
  40. package/dist/driver/stagehand.d.ts +3 -1
  41. package/dist/driver/stagehand.js +4 -2
  42. package/dist/durable/store.d.ts +14 -3
  43. package/dist/durable/store.js +204 -51
  44. package/dist/durable.d.ts +32 -16
  45. package/dist/durable.js +68 -95
  46. package/dist/index.d.ts +3 -3
  47. package/dist/index.js +5 -3
  48. package/dist/live-view/index.d.ts +3 -1
  49. package/dist/live-view/index.js +4 -0
  50. package/dist/live-view/protocol.d.ts +1 -1
  51. package/dist/live-view/server.d.ts +30 -0
  52. package/dist/live-view/server.js +152 -25
  53. package/dist/providers/cdp.js +2 -2
  54. package/dist/providers/profiles.d.ts +1 -15
  55. package/dist/providers/profiles.js +1 -64
  56. package/dist/providers/shared.d.ts +1 -47
  57. package/dist/providers/shared.js +1 -82
  58. package/dist/providers/worker-extension.d.ts +14 -1
  59. package/dist/providers/worker-extension.js +69 -3
  60. package/dist/testing/backend.d.ts +6 -24
  61. package/dist/testing/backend.js +7 -30
  62. package/dist/vault-session.d.ts +4 -7
  63. package/dist/vault-session.js +26 -81
  64. package/dist/vendor/browser-use-pi/page.d.ts +3 -12
  65. package/dist/vendor/browser-use-pi/page.js +6 -19
  66. package/package.json +9 -22
  67. package/dist/core/sites.d.ts +0 -33
  68. package/dist/core/sites.js +0 -104
  69. package/dist/durable/web.d.ts +0 -47
  70. package/dist/durable/web.js +0 -41
  71. package/dist/providers/browserbase-net.d.ts +0 -12
  72. package/dist/providers/browserbase-net.js +0 -95
  73. package/dist/providers/browserbase.d.ts +0 -169
  74. package/dist/providers/browserbase.js +0 -319
  75. package/dist/providers/kernel.d.ts +0 -58
  76. package/dist/providers/kernel.js +0 -291
  77. /package/dist/{providers → core}/cdp-call.d.ts +0 -0
  78. /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,13 +1,14 @@
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";
10
- import type { BrowserConfig, BrowserProvider, InventoryRow, ObserverRow, PriceTable, ReconcileReport, ReleaseReason, SessionChange, SessionCharge, SessionRow, SessionsState, SiteInfo, SiteRunPort, HandoffPort, WorkspaceFiles } from "./core/host.js";
11
+ import type { BrowserConfig, BrowserProvider, InventoryRow, ObserverRow, PriceTable, ReconcileReport, ReleaseReason, SessionChange, SessionCharge, SessionRow, SessionsState, HandoffPort, WorkspaceFiles } from "./core/host.js";
11
12
  export type { BrowserToolArgs, BrowserToolImpls, PageDriver, ToolCall, ToolImpl } from "./core/tools.js";
12
13
  export type { DriverFactory, DriverOptions } from "./core/custody.js";
13
14
  /** A host's step before a session is created at its provider (`BrowserExtensionOptions.beforeCreate`): the session's
@@ -34,18 +35,13 @@ 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
- /** `use_website`'s sites; absent, the tool is not listed. `listing` is the port's `list()`, read once at host setup:
44
- * the tool's description renders from it. Each local child runs in a conversation this call owns. */
45
- sites?: {
46
- port: SiteRunPort;
47
- listing: readonly SiteInfo[];
48
- };
49
45
  /** Live view and session status; a throw here never fails a call. */
50
46
  onSession?: (row: SessionRow, change: SessionChange) => void | Promise<void>;
51
47
  /** The person/model mutex shared with the live view (`createLiveView`'s `gates`); the default, the package's process-wide `drivingGates`, is the one the live view
@@ -62,6 +58,20 @@ export type BrowserExtensionOptions<D extends PageDriver = PageDriver> = VaultOp
62
58
  onCharge?: (charge: SessionCharge, tx: Tx, call?: {
63
59
  callId: string;
64
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>;
65
75
  /** Exact strings to scrub from every output besides the built-in shapes, read at each use. */
66
76
  redact?: {
67
77
  values: () => readonly string[];
@@ -90,16 +100,12 @@ type Crossing = "browser.between-actions" | "browser.action-returned";
90
100
  export type BrowserExtensionHandle = {
91
101
  /** Install once per Harness, before `resume()`; select per conversation. */
92
102
  extension: Extension;
93
- /** `Children`: the conversation each `use_website` request ran its child in, by `<site>:<request_id>`. */
94
103
  docs: {
95
104
  Config: ConversationDocToken<BrowserConfig>;
96
105
  Sessions: ConversationDocToken<SessionsState>;
97
106
  Inventory: SessionDocToken<{
98
107
  rows: Record<string, InventoryRow>;
99
108
  }>;
100
- Children: ConversationDocToken<{
101
- byRequest: Record<string, number>;
102
- }>;
103
109
  };
104
110
  tools: readonly ToolRegistration[];
105
111
  /** Shutdown path (pi has no conversation-end event): closes the conversation's drivers and commits `releasing` and a
@@ -117,8 +123,18 @@ export type BrowserExtensionHandle = {
117
123
  close(): Promise<void>;
118
124
  /** How many conversations the extension still holds in-memory state for: a repeat guard, an idle timer or a queued call. */
119
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>;
120
137
  };
121
- export { createWebExtension, type WebExtensionOptions } from "./durable/web.js";
122
138
  export { CONFIRM_POLLS, RELEASE_ATTEMPTS } from "./durable/store.js";
123
139
  export { HANDOFF_POLL_MS } from "./core/custody.js";
124
140
  export declare function createBrowserExtension<D extends PageDriver>(options: BrowserExtensionOptions<D>): BrowserExtensionHandle;