@parcha/pi-browser 0.1.0-beta.65 → 0.1.0-beta.67

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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,29 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 0.1.0-beta.66 (2026-11-27)
6
+
7
+ - The browser's `screenshot` tool takes an optional `save_as`: a path relative to the workspace, its folders separated by `/`, ending `.png`, `.jpg` or `.jpeg` (`shots/home.png`). The capture is filed as evidence as before, and the same bytes are also written to that path. Missing folders are created and an existing file is replaced. The answer gets a `saved: <path>` line, and its details get `save_as: { path, saved: true }`. A `.png` name captures a PNG. An absolute path, a `..` segment, a backslash, a name that is not an image, or a name whose format contradicts `type` is refused before the browser is called, so nothing is captured or filed. If the size budget retakes a PNG as a JPEG, the capture still comes back and is filed, but nothing is written under the `.png` name: the answer says `not saved: ...` and its details give `save_as: { path, saved: false, reason: "format_changed", message }`. Without `save_as`, the tool behaves as before. <!-- changes/browser-screenshot-save-as.md -->
8
+ - `WorkspaceFiles` (pi-browser's host port) gains an optional `write(rel, bytes)`. A host without one refuses `save_as`. pi-browser's own `workspaceFiles(root)` writes through no link, its parent folders and the file itself included, and replaces the file whole. It walks from the root one folder at a time, each opened through no link and held: on Linux every later name resolves inside a held folder, so a folder another process swaps for a link is never followed; elsewhere the held folders are checked (same folder, no link) before and after each step, and a swap seen is refused. serve writes through the run's Workspace, the same write the agent's write tool uses.
9
+ - On serve, the run's gate holds a browser screenshot that has `save_as` to `write`'s setting, as it already holds `computer_screenshot`'s. An agent not given `write` is refused, `write` set to deny refuses it, `write` set to ask asks a person, and a path inside a folder an MCP tool's file setting reserves is refused. A screenshot without `save_as` is held to the browser's setting alone.
10
+ - When serve lets a run's claim go (the run ends, is stopped, or parks), it now releases every cloud browser that carries the run's labels and the claim's epoch and that nothing the run holds names: not a session's browser by id, and not a browser whose session tag a held, not yet created session still owns. Before, a browser one create of a request made and then lost (its reply lost, its recovery keeping it because an older browser was answered) ran unheld until the vendor ended it, up to 6 hours on Browserbase and about 72 hours on Kernel: the janitor refuses vendor-lifetime providers, and a later claim's sweep releases only lower epochs. A browser another run made, or a later epoch's, is never touched. <!-- changes/browser-unheld-release.md -->
11
+
12
+ What the run holds is read after the vendor's list answers, and it counts every browser the run's custody held in that process, released or not: a browser the vendor still lists a moment after its own release is billed by its own record and never charged again. A browser whose create the process still has in flight is left to that create and named.
13
+
14
+ Each browser released this way is charged on the run from the time its vendor listing says it was made, through the same booking every other browser charge takes. The let-go records each browser on the run's root (its id, tag, when its vendor made it, and when its release went out) before its release is sent, and charges it, and says its release on the run's timeline, in one commit of its own once that release answers, before the next release is sent. A process that ends between a release and its charge, or a later release that does not answer within the let-go's bound, leaves each released browser charged and said, or recorded, and the next claim's open charges and says a recorded one: one that claim's own sweep of the run's older-epoch sessions released, to when that sweep answered (it ran until then); otherwise to when its release went out, or, where its vendor says it still runs, it releases it then and charges it to then. One whose status cannot be read stays recorded for the open after. The run's timeline and root record say so, one line per browser: `AgentRun: Released 1 browser a create race left running (<id>); this run did not hold it, and its time is booked on the run and absorbed, not billed.` A browser the release could not end is named too, as running to its vendor's lifetime. When a session's release by its tag ends such a browser beside the session's own, it is charged there under the same key (`unheld:<id>`), so it is charged once whichever release ends it, and a reopen books that charge once.
15
+
16
+ That time is booked and absorbed, never billed. The run's ledger books it, so its `cost.usd` and its usage's `total` hold it and the run's cost record is whole, but `GET /runs/{id}/usage` (`runusage/7`) puts it on a `browser_time` line of its own with `absorbed: "create_race"` and `billable: false`, and in `infra_usd`. A bill for the run's task is the billable lines, which leave it out; the run's own sessions' time stays billable. The run read leaves it out too, so no caller has to subtract it: `cost.tools_usd` (`toolsusd/4`) counts no absorbed line, and the new `cost.billable_usd` (`billable/1`) is `usd` less every absorbed line's cost, exactly `usd` for a run with none, and null only when `usd` is or an absorbed line's cost is unknown. While the run is at work, the absorbed cost it subtracts is read from the same journal records as `usd`, so a charge booked after the read is never subtracted from a `usd` that does not hold it.
17
+
18
+ `@parcha/agentrun-computer` adds `releaseUnheld(provider, run, epoch, held, { signal?, releasing?, released? })`, which lists the run's computers and releases each of that epoch the `held` predicate (sync or async, asked after the list) refuses, running `releasing(computer)` before each release is sent (one that throws holds that computer back, named in `failed`) and `released(computer)` once it answers, before the next is sent (`UnheldHooks`), and `ComputerInfo.createdAt`, which the Browserbase and Kernel listings now fill. Its README also names a gap it leaves: a create's lookup that answers a lost create's browser while a newer one runs, which that create's last read then releases; the lookup's holder loses one call and its page state, as its next call finds the browser ended and opens a fresh one. `@parcha/pi-browser` adds the `onRaceReleased` option, called with the ids a release by a session's tag ended besides that session's own, once a status read confirms each stopped: one whose release stopped it and then failed is kept with the release and told by the attempt, abort handler or reconcile that confirms it. A lost create's tag lookup tells the extra sessions it releases the same way. Each such id is saved on the session's inventory row (`InventoryRow.owed`, a new optional field) before its stop is sent, and stays there until a status read confirms its stop and it is told, across a restart: the session's own release confirms what its row owes, and a run open's reconcile what a lost row owes. A lost row's reconcile tells each session it confirms stopped even when another's release fails. A provider's `findByTag` may say when it made each session (`LeaseRef.madeAt`, a new optional field); that time is saved on the row beside the id (`InventoryRow.made`) and handed to `onRaceReleased` as `madeAt`, so a session told by a later process is charged from when it was made, not at an unknown amount. A browser a process charged and then was told again by a later one (its process ended before pi-browser's commit) is not charged again: serve reads the run's committed charges of such browsers once per process.
19
+ - A runner's graceful `close()` now resolves only after each live run's tool hosts have let go of what they hold, and their charges are booked under the claim the runner still holds. Before, the shutdown sealed the run's journal and aborted its ledger first, so a browser session's release charge was refused ("a tool host's beforeRelease failed: the loop stopped (shutdown)") and a priced computer's last stretch went unbooked. A shutdown's seal now lets the release hooks' commits through until they return; the claim's fence still refuses them once the claim is lost. On the run's cap, money already owed (a computer's time, a browser session's release) is booked after the run's stop, since nothing starts with it; every other step is still refused after a stop. <!-- changes/close-books-release.md -->
20
+
21
+ The wait is bounded, and the close's window now runs from its start:
22
+ - A run's release waits for its tool hosts up to a computer provider's cleanup bound (`cleanupMs`, 30 s by default) and a 5 s margin, never past the close's window. A host still going then is cut: each open browser session's time up to the cut is charged (pi-browser's `charge` handle), and the run's root records an `agentrun.release.cut` entry with the bound, the time taken and how many hosts finished. The session's release, when it lands (on this claim or the next one's), bills only the time after that charge. If the charge went past the release's own time, the release bills 0 s, and its `agentrun.browser_charged` entry carries `overbooked_s`. A reserve the cut claim left held is given back at the next claim's reopen. The cut reaches every conversation of the run, its subagents' included. pi-browser's `charge` now skips a session already charged through now, so a cut books no $0 charge under it.
23
+ - A lost create's recovery under way in the process (`recoveriesInFlight()`, new in `@parcha/agentrun-computer`, with `recoverCreate` now exported) is waited for at the close: each up to its own bound, or the drain, and the margin. A run's own process (`run-child`) waits for its own recoveries before it exits, and its runner gives that exit the release's bound.
24
+ - A person's stop gives a run's own process the release's bound and 5 s for the cut's booking on top of its 30 s stop, so a release that never answers is cut, charged and recorded before the process is ended. A release already under way when a shutdown arrives follows it: its cut is moved to the close's window, and the shutdown's seal lets the release's commits through. A run a person's stop already stops when the runner closes keeps that stop as its end, and its release is cut by the close's window too, in the runner's process or its own, so its cut is charged and recorded before the close ends.
25
+ - The close is now the drain plus the lease less its margin (31 s with the image's 6 s drain), or the cleanup bound and 10 s of margins from the close's start, whichever is longer: 40 s by default. Claims are renewed until the close returns. `startRunner` takes `cleanupMs` for a runner whose providers use a longer one.
26
+ - The deploy templates give a runner more time to stop: 45 s in `deploy/compose.yaml`, the Helm chart (`terminationGracePeriodSeconds`), Coolify and Dokploy, 45 s of Railway draining (`RAILWAY_DEPLOYMENT_DRAINING_SECONDS`), and 50 s on Fly (`kill_timeout`). A deployment of its own gives a runner at least 45 s, and at least `cleanupMs` + 15 s with a longer cleanup bound.
27
+
5
28
  ## 0.1.0-beta.63 (2026-11-26)
6
29
 
7
30
  - `BrowserExtensionHandle.charge(conversation, context)` bills each open session of a conversation through now, not final. A session counts as open when it is live, held, or releasing (its release asked and not yet confirmed). The charge and the session's `chargedThrough` move in one commit, and it resolves to the number of sessions charged. A host that stops waiting on a session's release uses it to book the time known so far. The release's own charge, when it lands, bills only the time after that, so a cut charge followed by the final charge books what one uninterrupted session books, the provider's minimum included. A charge through a time before the session's `chargedThrough` bills nothing, never a negative amount, and reports the difference in seconds as `SessionCharge.overbookedS`. That happens when the release was confirmed before an earlier charge that billed past it. A session billed final is never billed again. <!-- changes/pi-browser-cut-charge.md -->
package/README.md CHANGED
@@ -363,6 +363,16 @@ await browser.reconcile(harness, () => true, context); // settles what a dead
363
363
  earlier charge billed the session past this one's `at` (a `handle.charge` taken while its release was under way, the
364
364
  release confirmed before it), by that many seconds; this charge bills none of it again and never a negative. It must
365
365
  not throw: a throw fails the commit, and a call's charge is then carried by the session's next one.
366
+ - `onRaceReleased({ conversationId, tag, ids, madeAt })`: a release by a session's tag ended sessions besides that session's own
367
+ (a create retried behind the provider's API, or a create race of that tag, left them running), and no record bills
368
+ their time. Called with their ids once a status read confirms each stopped, including one whose release stopped it and
369
+ then failed. Each id is saved on the session's inventory row (`owed`) before its stop is sent, and stays there, across
370
+ a restart, until a read confirms its stop and it is told: the session's own release confirms the ones its row owes, and
371
+ a run open's reconcile those of a row that ended lost or that a release left owing. Called again for an id only when a
372
+ process ends between the call and the commit that takes it off the row, so a host books what they ran under one key
373
+ per id. `madeAt`, by id, is when the provider made each, where its tag lookup said (`LeaseRef.madeAt`): saved on the
374
+ row (`made`) with the id before its stop is sent, so a later process, whose lookups no longer list a stopped session,
375
+ hands it on too; absent when the lookup said for none. A throw here never fails the release.
366
376
 
367
377
  Per conversation, the host writes a `BrowserConfig` (`label`, `run`, and the policy: proxies, verified, captcha, geolocation,
368
378
  region, a raw context id, the session timeout, the idle release and the batch timeout; `DEFAULT_BROWSER_POLICY` holds the
@@ -373,7 +383,12 @@ as background tasks, which `waitForIdle` skips and closing the harness aborts: b
373
383
  releases gets them at the provider all the same: `handle.close()` waits, 30 s at most, for every one no drain since covered.
374
384
  A host that stops waiting on a release calls `handle.charge(conversation, ctx)` to book the time known so far: each session
375
385
  still open (live, held, or releasing) is billed through now, not final, its `chargedThrough` moved in the same commit, and
376
- the release's own charge, when it lands, bills only the time after it. A release the store cannot record (a storage error)
386
+ the release's own charge, when it lands, bills only the time after it. A record with no session id yet (its create under
387
+ way, or its answer lost and the session not yet found by its tag) is not charged: its release's charge bills the whole
388
+ session once it is found. A session already charged through now gets no $0 charge. The row `onSession` is told at a
389
+ release is the session as its release confirmed it: a `handle.charge` taken after that confirm and before its commit
390
+ bills past it, and is in the charges (`onCharge`, the bill) but not in that row, whose `spent` is then short of the
391
+ record's by that charge. A release the store cannot record (a storage error)
377
392
  is still made at the provider, and the record is left for the next run's reconcile; once the store has failed,
378
393
  `handle.close()` releases every session the process still holds, and over a healthy store it releases nothing. At run open,
379
394
  after the extensions are installed and
@@ -64,10 +64,12 @@ const run = {
64
64
  }),
65
65
  effect: "effect", replay: "unsafe", executionMode: "sequential", evidence: "none", listedWhen: "always",
66
66
  };
67
+ /** save_as's words, as the screenshot tool keeps them (tools.ts savePlanOf). */
68
+ const SAVE_AS = "Also save the capture as this file: a path relative to the workspace, folders separated by a forward slash, ending .png, .jpg or .jpeg (shots/home.png). A .png name captures a PNG; a .png name with type jpeg, or a .jpg name with type png, is refused. Missing folders are made and a file already there is replaced. The answer says where it was saved, or why it was not (a PNG over the size budget comes back as a JPEG, which is not saved under a .png name).";
67
69
  const screenshot = {
68
70
  name: "screenshot",
69
71
  label: "Browser: screenshot",
70
- description: 'Capture a screenshot of the active page. For size-constrained MCP clients, prefer a viewport JPEG: {"type":"jpeg","quality":40,"fullPage":false}.',
72
+ description: 'Capture a screenshot of the active page. For size-constrained MCP clients, prefer a viewport JPEG: {"type":"jpeg","quality":40,"fullPage":false}. With save_as, the capture is also saved as a file in the workspace.',
71
73
  parameters: object({
72
74
  fullPage: { type: "boolean" },
73
75
  type: { type: "string", enum: ["png", "jpeg"] },
@@ -76,6 +78,7 @@ const screenshot = {
76
78
  clip: { ...object({ x: { type: "number" }, y: { type: "number" }, width: { type: "number" }, height: { type: "number" } }, ["x", "y", "width", "height"]), description: "Capture only this region, in CSS pixels from the viewport's top-left corner (what the page shows now). Width and height 0 mean no clip: leave it out, or send zeros, to capture the whole viewport. A region that leaves the viewport is refused. Use one of clip, id or selector; an empty id or selector means none." },
77
79
  id: { type: "string", description: "Capture only this element: a bracketed ID from the latest snapshot, as a string. It is scrolled into view first. It must match one element." },
78
80
  selector: { type: "string", description: "Capture only the element this CSS selector matches (when there is no snapshot ID for it). It is scrolled into view first. It must match exactly one element." },
81
+ save_as: { type: "string", description: SAVE_AS },
79
82
  }),
80
83
  effect: "read", replay: "safe", executionMode: "sequential", evidence: "image", listedWhen: "always",
81
84
  };
@@ -3,9 +3,24 @@ export declare const MAX_UPLOAD_BYTES: number;
3
3
  /** The media type browser_upload gives a file named `name`, by its extension; application/octet-stream for one it does
4
4
  * not know. */
5
5
  export declare const uploadMime: (name: string) => string;
6
+ /** Why `rel` is no path of a file in a workspace, or null when it is one: a relative path with no `..` segment. Where it
7
+ * then leads (a link on the way) is the reader's or the writer's to check. */
8
+ export declare function workspacePathRefusal(rel: unknown): string | null;
6
9
  /** Files under `root` only: a relative path with no `..`, inside `root` once symlinks resolve, at most `maxBytes`, and
7
- * not one `refuse` names (a host's private files). */
8
- export declare function workspaceFiles(root: string, { maxBytes, refuse }?: {
10
+ * not one `refuse` names (a host's private files). A write takes folders separated by "/" alone and follows no link on
11
+ * the way, the file itself included: it walks from the root one folder at a time, each opened as a folder through no
12
+ * link and held, makes each missing one, and replaces the file whole (a temporary file made beside it, then renamed
13
+ * over the name; a reader sees the old file or the new one).
14
+ *
15
+ * On Linux (`procFd`, default there) every name after the root resolves inside a folder a handle holds, so a folder
16
+ * swapped for a link by another process changes nothing: what is made or written is made in the folders walked.
17
+ * Elsewhere node can only resolve a path again, so before and after each act the folders held are checked: each still
18
+ * there by its path, no link, the same folder (dev and inode); else the write is refused, and the temporary file
19
+ * removed. What remains there is the gap between the last check and the call itself: a folder swapped for a link in
20
+ * it, and put back before the next check, can have that one call (a folder made, an empty temporary file made, or the
21
+ * rename) land through the link; the bytes are written only once the temporary file is confirmed in the folder held. */
22
+ export declare function workspaceFiles(root: string, { maxBytes, refuse, procFd }?: {
9
23
  maxBytes?: number;
10
24
  refuse?: (real: string) => string | null;
25
+ procFd?: boolean;
11
26
  }): WorkspaceFiles;
@@ -1,5 +1,6 @@
1
1
  import { constants } from "node:fs";
2
- import { open, readlink, realpath, stat } from "node:fs/promises";
2
+ import { lstat, mkdir, open, readlink, realpath, rename, rm, stat } from "node:fs/promises";
3
+ import { randomBytes } from "node:crypto";
3
4
  import path from "node:path";
4
5
  export const MAX_UPLOAD_BYTES = 8 * 1024 * 1024;
5
6
  const MIME = {
@@ -19,17 +20,41 @@ async function openedPath(handle, checked) {
19
20
  const [opened, now] = await Promise.all([handle.stat(), stat(checked).catch(() => null)]);
20
21
  return now && opened.dev === now.dev && opened.ino === now.ino ? realpath(checked).catch(() => null) : null;
21
22
  }
23
+ /** Why `rel` is no path of a file in a workspace, or null when it is one: a relative path with no `..` segment. Where it
24
+ * then leads (a link on the way) is the reader's or the writer's to check. */
25
+ export function workspacePathRefusal(rel) {
26
+ if (typeof rel !== "string" || !rel.trim() || rel.includes("\0"))
27
+ return "path must name a file in the workspace";
28
+ if (path.isAbsolute(rel) || path.win32.isAbsolute(rel))
29
+ return `${rel} is absolute; give a path relative to the workspace`;
30
+ if (rel.split(/[\\/]/).includes(".."))
31
+ return `${rel} contains '..'; give a path inside the workspace`;
32
+ return null;
33
+ }
34
+ const DIR_FLAGS = constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW;
35
+ const errno = (error) => error?.code;
36
+ /** A write's refusal, carried out of the walk. */
37
+ class Refused extends Error {
38
+ }
22
39
  /** Files under `root` only: a relative path with no `..`, inside `root` once symlinks resolve, at most `maxBytes`, and
23
- * not one `refuse` names (a host's private files). */
24
- export function workspaceFiles(root, { maxBytes = MAX_UPLOAD_BYTES, refuse } = {}) {
40
+ * not one `refuse` names (a host's private files). A write takes folders separated by "/" alone and follows no link on
41
+ * the way, the file itself included: it walks from the root one folder at a time, each opened as a folder through no
42
+ * link and held, makes each missing one, and replaces the file whole (a temporary file made beside it, then renamed
43
+ * over the name; a reader sees the old file or the new one).
44
+ *
45
+ * On Linux (`procFd`, default there) every name after the root resolves inside a folder a handle holds, so a folder
46
+ * swapped for a link by another process changes nothing: what is made or written is made in the folders walked.
47
+ * Elsewhere node can only resolve a path again, so before and after each act the folders held are checked: each still
48
+ * there by its path, no link, the same folder (dev and inode); else the write is refused, and the temporary file
49
+ * removed. What remains there is the gap between the last check and the call itself: a folder swapped for a link in
50
+ * it, and put back before the next check, can have that one call (a folder made, an empty temporary file made, or the
51
+ * rename) land through the link; the bytes are written only once the temporary file is confirmed in the folder held. */
52
+ export function workspaceFiles(root, { maxBytes = MAX_UPLOAD_BYTES, refuse, procFd = process.platform === "linux" } = {}) {
25
53
  return {
26
54
  async resolve(rel) {
27
- if (typeof rel !== "string" || !rel.trim() || rel.includes("\0"))
28
- return { refused: "path must name a file in the workspace" };
29
- if (path.isAbsolute(rel) || path.win32.isAbsolute(rel))
30
- return { refused: `${rel} is absolute; give a path relative to the workspace` };
31
- if (rel.split(/[\\/]/).includes(".."))
32
- return { refused: `${rel} contains '..'; give a path inside the workspace` };
55
+ const bad = workspacePathRefusal(rel);
56
+ if (bad)
57
+ return { refused: bad };
33
58
  let base;
34
59
  try {
35
60
  base = await realpath(root);
@@ -73,5 +98,128 @@ export function workspaceFiles(root, { maxBytes = MAX_UPLOAD_BYTES, refuse } = {
73
98
  await handle.close();
74
99
  }
75
100
  },
101
+ async write(rel, bytes) {
102
+ const bad = workspacePathRefusal(rel);
103
+ if (bad)
104
+ return { refused: bad };
105
+ if (rel.includes("\\"))
106
+ return { refused: `${rel}: folders are separated by "/", never a backslash` };
107
+ const parts = rel.split("/").filter((part) => part !== "" && part !== ".");
108
+ const name = parts.pop();
109
+ if (!name)
110
+ return { refused: "path must name a file in the workspace" };
111
+ let base;
112
+ try {
113
+ base = await realpath(root);
114
+ }
115
+ catch {
116
+ return { refused: "the workspace does not exist" };
117
+ }
118
+ const held = [];
119
+ const at = (dir, child) => (procFd ? `/proc/self/fd/${dir.handle.fd}/${child}` : path.join(dir.abs, child));
120
+ const outside = () => new Refused(`${rel} resolves outside the workspace, or a link is on the way to it, and a write follows none`);
121
+ // Off /proc/self/fd: every folder held is still there by its path, through no link, the same folder.
122
+ const confirm = async () => {
123
+ if (procFd)
124
+ return;
125
+ for (const dir of held.slice(1)) {
126
+ const now = await lstat(dir.abs).catch(() => null);
127
+ if (!now?.isDirectory() || now.dev !== dir.dev || now.ino !== dir.ino)
128
+ throw outside();
129
+ }
130
+ };
131
+ const hold = async (handle, abs) => {
132
+ const info = await handle.stat().catch(async (error) => { await handle.close(); throw error; });
133
+ const dir = { handle, abs, dev: info.dev, ino: info.ino };
134
+ held.push(dir);
135
+ return dir;
136
+ };
137
+ const enter = async (dir, index) => {
138
+ const part = parts[index];
139
+ for (let made = false;;) {
140
+ try {
141
+ const handle = await open(at(dir, part), DIR_FLAGS);
142
+ const next = await hold(handle, path.join(dir.abs, part));
143
+ await confirm();
144
+ return next;
145
+ }
146
+ catch (error) {
147
+ if (error instanceof Refused)
148
+ throw error;
149
+ const code = errno(error);
150
+ if (code === "ENOENT" && !made) {
151
+ made = true;
152
+ await confirm();
153
+ await mkdir(at(dir, part)).catch((making) => { if (making.code !== "EEXIST")
154
+ throw making; });
155
+ await confirm();
156
+ continue;
157
+ }
158
+ const there = await lstat(at(dir, part)).catch(() => null);
159
+ if (code === "ELOOP" || there?.isSymbolicLink())
160
+ throw new Refused(`${rel}: a link is on the way to it, and a write follows none`);
161
+ if (code === "ENOTDIR" || there)
162
+ throw new Refused(`${rel}: ${parts.slice(0, index + 1).join("/")} is not a directory`);
163
+ throw error;
164
+ }
165
+ }
166
+ };
167
+ let temp = null;
168
+ let tempIn = null;
169
+ let placed = false;
170
+ try {
171
+ let dir = await hold(await open(base, DIR_FLAGS), base);
172
+ for (let index = 0; index < parts.length; index++)
173
+ dir = await enter(dir, index);
174
+ const target = path.join(dir.abs, name);
175
+ await confirm();
176
+ const there = await lstat(at(dir, name)).catch(() => null);
177
+ await confirm();
178
+ if (there?.isSymbolicLink())
179
+ return { refused: `${rel} is a link, and a write follows none` };
180
+ if (there && !there.isFile())
181
+ return { refused: `${rel} is not a regular file` };
182
+ const vetoed = refuse?.(target);
183
+ if (vetoed)
184
+ return { refused: `${rel}: ${vetoed}` };
185
+ // Not built from the name, as serve's workspace writes are not: a name the folder takes may leave no room for more.
186
+ const tempName = `.workspace-${randomBytes(8).toString("hex")}.tmp`;
187
+ const handle = await open(at(dir, tempName), constants.O_RDWR | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o666).catch(() => null);
188
+ if (!handle)
189
+ return { refused: `${rel} cannot be written` };
190
+ temp = tempName;
191
+ tempIn = dir;
192
+ try {
193
+ // The file just made is the one at its name in the folder held, before any byte is written to it.
194
+ await confirm();
195
+ const [made, named] = await Promise.all([handle.stat(), lstat(at(dir, tempName)).catch(() => null)]);
196
+ if (!named || named.dev !== made.dev || named.ino !== made.ino)
197
+ throw outside();
198
+ await confirm();
199
+ await handle.writeFile(bytes);
200
+ await handle.sync();
201
+ }
202
+ finally {
203
+ await handle.close();
204
+ }
205
+ await confirm();
206
+ // A rename replaces whatever is at the name, a link swapped in included, and never writes through it; one that
207
+ // resolves through a folder swapped since the check finds no temporary file there, and fails.
208
+ await rename(at(dir, tempName), at(dir, name));
209
+ placed = true;
210
+ await dir.handle.sync();
211
+ return { path: [...parts, name].join("/") };
212
+ }
213
+ catch (error) {
214
+ if (error instanceof Refused)
215
+ return { refused: error.message };
216
+ return { refused: `${rel} cannot be written` };
217
+ }
218
+ finally {
219
+ if (!placed && temp && tempIn)
220
+ await rm(at(tempIn, temp), { force: true }).catch(() => undefined);
221
+ await Promise.all(held.map((dir) => dir.handle.close().catch(() => undefined)));
222
+ }
223
+ },
76
224
  };
77
225
  }
@@ -162,7 +162,8 @@ export interface BrowserProvider {
162
162
  read(ref: LeaseRef, name: string, maxBytes: number): Promise<AsyncIterable<Uint8Array>>;
163
163
  };
164
164
  }
165
- /** The host owns the file boundary for `browser_upload`: a path the model names is resolved here or refused. */
165
+ /** The host owns the file boundary for `browser_upload` and a screenshot's `save_as`: a path the model names is resolved
166
+ * or written here, or refused. */
166
167
  export interface WorkspaceFiles {
167
168
  resolve(rel: string): Promise<{
168
169
  bytes: Uint8Array;
@@ -171,6 +172,13 @@ export interface WorkspaceFiles {
171
172
  } | {
172
173
  refused: string;
173
174
  }>;
175
+ /** File `rel` made or replaced with `bytes`, its parent directories made, as the host's own file-write tool writes one;
176
+ * `path` is where it went, relative to the workspace. Absent: the host saves no screenshot. */
177
+ write?(rel: string, bytes: Uint8Array): Promise<{
178
+ path: string;
179
+ } | {
180
+ refused: string;
181
+ }>;
174
182
  }
175
183
  export type HandoffOutcome = "done" | "cancelled" | "expired";
176
184
  /** Hands the live browser to a person and reports how it ended. Polled by id, so a restarted process resumes the wait;
@@ -297,6 +305,10 @@ export type SessionsState = {
297
305
  /** Told to the model on its next browser call, then cleared. */
298
306
  notice: string | null;
299
307
  };
308
+ /** `owed`: sessions besides the row's own that a release by its tag sent a stop to (or is about to), and that no raced
309
+ * call has told yet; each stays until a status read confirms its stop and it is told. `made`: when the provider made each
310
+ * session its tag lookup found (LeaseRef.madeAt), by id, saved before any stop is sent to it, until it is told: a stopped
311
+ * session is listed by no later lookup, and a raced call hands its host this time. */
300
312
  export type InventoryRow = {
301
313
  tag: string;
302
314
  conversationId: number;
@@ -304,6 +316,8 @@ export type InventoryRow = {
304
316
  provider: string;
305
317
  resourceId: string | null;
306
318
  state: SessionRecord["state"];
319
+ owed?: string[];
320
+ made?: Record<string, string>;
307
321
  };
308
322
  export type SessionRow = {
309
323
  conversationId: number;
@@ -5,7 +5,8 @@ export type ResourceStatus = "pending" | "running" | "stopped" | "gone";
5
5
  * `id`. */
6
6
  export type LeaseRef = {
7
7
  readonly id: string;
8
- readonly tag: string;
8
+ readonly tag: string; /** When the provider made the session (an ISO time), where its tag lookup (findByTag) says. */
9
+ readonly madeAt?: string;
9
10
  };
10
11
  /** Each change is one commit, and a provider call sits between two commits, never inside one. `lost` ends custody of a
11
12
  * resource the provider no longer answers for and that was never confirmed released. */
@@ -118,6 +118,7 @@ export type BrowserToolArgs = {
118
118
  };
119
119
  id?: string;
120
120
  selector?: string;
121
+ save_as?: string;
121
122
  };
122
123
  browser_read: {
123
124
  what?: (typeof WHATS)[number];
@@ -157,6 +158,26 @@ type Lost = {
157
158
  /** Told to a call whose page sent requests the browser lost before they left it (Chrome's network service restarted under
158
159
  * them): they were not sent, so the model may send them again. */
159
160
  export declare const lostRequests: (lost: readonly Lost[]) => string;
161
+ /** Where a screenshot's `save_as` saves it and in which format, or why it is refused: a path relative to the workspace
162
+ * (workspacePathRefusal), its folders separated by "/" alone (as computer_screenshot's save_as), naming a .png, .jpg
163
+ * or .jpeg file, whose format agrees with `type` when it is given. A .png name asks for a PNG; a .jpg name leaves the
164
+ * capture as it was asked (a JPEG unless type says png, which is refused). */
165
+ export declare function savePlanOf(given: unknown, type: "png" | "jpeg" | undefined): {
166
+ path: string;
167
+ format: "png" | "jpeg";
168
+ } | {
169
+ refused: string;
170
+ };
171
+ /** What became of a screenshot's save_as: saved at `path`, or not, with the reason in a word and in a sentence. */
172
+ export type SaveOutcome = {
173
+ path: string;
174
+ saved: true;
175
+ } | {
176
+ path: string;
177
+ saved: false;
178
+ reason: "format_changed" | "refused";
179
+ message: string;
180
+ };
160
181
  export declare function pageTools({ guards, reconnect: timings, readDeadlineMs }?: {
161
182
  /** Each conversation's repeat guard; a host that owns the conversation's lifecycle passes it to evict one. */
162
183
  guards?: Map<number, RepeatGuard>;
@@ -3,6 +3,7 @@ import { BrowserFailureError, FenceRefusal, refusedError, loadedNoPage, passedTh
3
3
  import { defaultInline } from "./evidence.js";
4
4
  import { fetchDownloads } from "./downloads.js";
5
5
  import { asPartial, browserFailure, classifyBrowserError, partialOf, transportFactOf } from "./failures.js";
6
+ import { workspacePathRefusal } from "./files.js";
6
7
  import { createRepeatGuard } from "./guard.js";
7
8
  import { regionOf } from "./clip.js";
8
9
  import { captureWithinBudget } from "./images.js";
@@ -69,6 +70,35 @@ const lostOf = (error) => (error !== null && typeof error === "object" ? (error[
69
70
  /** Told to a call whose page sent requests the browser lost before they left it (Chrome's network service restarted under
70
71
  * them): they were not sent, so the model may send them again. */
71
72
  export const lostRequests = (lost) => `The browser lost ${lost.length === 1 ? "a request" : `${lost.length} requests`} your page made before ${lost.length === 1 ? "the request" : "they"} left the browser: ${lost.map((r) => `${r.method} ${r.url}`).join(", ")}. Chrome's network service restarted while ${lost.length === 1 ? "it was" : "they were"} on ${lost.length === 1 ? "its" : "their"} way, so ${lost.length === 1 ? "the request was" : "the requests were"} not sent. Make ${lost.length === 1 ? "it" : "them"} again if you still need ${lost.length === 1 ? "it" : "them"}.`;
73
+ /** Where a screenshot's `save_as` saves it and in which format, or why it is refused: a path relative to the workspace
74
+ * (workspacePathRefusal), its folders separated by "/" alone (as computer_screenshot's save_as), naming a .png, .jpg
75
+ * or .jpeg file, whose format agrees with `type` when it is given. A .png name asks for a PNG; a .jpg name leaves the
76
+ * capture as it was asked (a JPEG unless type says png, which is refused). */
77
+ export function savePlanOf(given, type) {
78
+ const bad = workspacePathRefusal(given);
79
+ if (bad)
80
+ return { refused: `save_as: ${bad}` };
81
+ // One separator, so the path the run's gate reads is the path written: a backslash is refused, never read as a "/".
82
+ if (given.includes("\\"))
83
+ return { refused: `save_as separates folders with "/", never a backslash: not ${JSON.stringify(given)}` };
84
+ const path = given.split("/").filter((part) => part !== "" && part !== ".").join("/");
85
+ const format = /\.png$/i.test(path) ? "png" : /\.jpe?g$/i.test(path) ? "jpeg" : null;
86
+ if (!format || /(^|\/)\.(png|jpe?g)$/i.test(path))
87
+ return { refused: `save_as names a .png, .jpg or .jpeg file: not ${JSON.stringify(given)}` };
88
+ if (type !== undefined && type !== format)
89
+ return { refused: `save_as ${JSON.stringify(given)} names a ${format === "png" ? "PNG" : "JPEG"} file, and type asks for ${type === "png" ? "a PNG" : "a JPEG"}: give a name that matches type, or leave type out` };
90
+ return { path, format };
91
+ }
92
+ /** The capture's own bytes (the ones filed as evidence) written at the plan's path through the host's write, unless the
93
+ * capture came back in another format than the name says (a PNG over the size budget is retaken as a JPEG): a file
94
+ * whose bytes are not what its name says is never written. */
95
+ async function saveCapture(plan, taken, bytes, write) {
96
+ if (taken !== plan.format) {
97
+ return { path: plan.path, saved: false, reason: "format_changed", message: `the ${plan.format === "png" ? "PNG" : "JPEG"} was over the size budget and was taken as a ${taken === "png" ? "PNG" : "JPEG"}, so it was not saved as ${plan.path}; save a .${taken === "png" ? "png" : "jpg"} name, or capture a smaller region (clip, id or selector)` };
98
+ }
99
+ const out = await write(plan.path, bytes).catch((error) => ({ refused: `${plan.path} could not be written: ${error?.message ?? String(error)}` }));
100
+ return "refused" in out ? { path: plan.path, saved: false, reason: "refused", message: out.refused } : { path: out.path, saved: true };
101
+ }
72
102
  /** A read of a browser that has loaded no page yet: it is fresh, and the next step is to navigate, to the replaced
73
103
  * session's last page when there is one. */
74
104
  function freshBrowser(replaced) {
@@ -412,8 +442,16 @@ export function pageTools({ guards = new Map(), reconnect: timings = RECONNECT,
412
442
  });
413
443
  },
414
444
  screenshot: (args, port, call) => {
415
- const { ask: asked, clip: wantedClip, id: wantedId, selector: wantedSelector, ...requested } = args ?? {};
445
+ const { ask: asked, clip: wantedClip, id: wantedId, selector: wantedSelector, save_as: saveAs, ...asks } = args ?? {};
416
446
  const ask = typeof asked === "string" && asked.trim() ? asked.trim() : undefined;
447
+ // A save_as is checked before any browser call, so a refused one captures and files nothing.
448
+ const plan = saveAs === undefined ? undefined : savePlanOf(saveAs, asks.type);
449
+ if (plan && "refused" in plan)
450
+ return Promise.resolve(text(browserFailure("refused", plan.refused), true));
451
+ const write = call.files?.write?.bind(call.files);
452
+ if (plan && !write)
453
+ return Promise.resolve(text(browserFailure("refused", "This host gives the browser no workspace to save a screenshot into."), true));
454
+ const requested = plan?.format === "png" ? { ...asks, type: "png" } : asks;
417
455
  return perform("screenshot", args ?? {}, port, call, "read", async (s, news) => {
418
456
  // A region goes through the same capture as the whole page, so whatever guards a capture guards a clipped one.
419
457
  const region = await regionOf({ clip: wantedClip, id: wantedId, selector: wantedSelector, fullPage: requested.fullPage }, s.driver.locate?.bind(s.driver));
@@ -425,9 +463,10 @@ export function pageTools({ guards = new Map(), reconnect: timings = RECONNECT,
425
463
  const taken = shot.options.clip ? "the clip" : shot.options.fullPage ? "the full page" : "the viewport";
426
464
  const scaled = shot.options.scale !== undefined && shot.options.scale < 1 ? ", scaled down" : "";
427
465
  const adjusted = shot.adjusted && `adjusted: the first capture${first ? ` (${first.width}x${first.height})` : ""} ${over}; this is ${taken} at ${shot.size.width}x${shot.size.height}${scaled}`;
428
- const lines = [news, `url: ${url}`, `evidence: ${receipt.path ?? "(not filed)"}`, adjusted].filter(Boolean).join("\n");
466
+ const saved = plan && write ? await saveCapture(plan, shot.size.type, Buffer.from(shot.data, "base64"), write) : undefined;
467
+ const lines = [news, `url: ${url}`, `evidence: ${receipt.path ?? "(not filed)"}`, adjusted, saved && (saved.saved ? `saved: ${saved.path}` : `not saved: ${saved.message}`)].filter(Boolean).join("\n");
429
468
  const media = { kind: "screenshot", path: receipt.bodyPath, mime: shot.mimeType, bytes: Buffer.from(shot.data, "base64").byteLength, width: shot.size.width, height: shot.size.height, ...(region ? { clip: region.clip, ...region.of } : {}), ...(ask ? { ask } : {}) };
430
- return { content: [{ type: "text", text: lines }, { type: "image", data: shot.data, mimeType: shot.mimeType }], details: { evidence: receipt.path, sha256: receipt.sha256, media } };
469
+ return { content: [{ type: "text", text: lines }, { type: "image", data: shot.data, mimeType: shot.mimeType }], details: { evidence: receipt.path, sha256: receipt.sha256, media, ...(saved ? { save_as: saved } : {}) } };
431
470
  });
432
471
  },
433
472
  browser_read: (args, port, call) => {
@@ -6,6 +6,7 @@ export declare const now: () => string;
6
6
  /** Release attempts before custody is given up as `lost`, and status polls before a release is sent again. */
7
7
  export declare const RELEASE_ATTEMPTS = 6;
8
8
  export declare const CONFIRM_POLLS = 5;
9
+ /** `owed` adds to the row's owed ids, `told` takes those told off it (InventoryRow.owed). */
9
10
  type Move = {
10
11
  state: LeaseState;
11
12
  resourceId?: string;
@@ -13,6 +14,8 @@ type Move = {
13
14
  at: string;
14
15
  notice?: "kept" | "lost";
15
16
  handoff?: string;
17
+ owed?: string[];
18
+ told?: string[];
16
19
  };
17
20
  /** `found`: the ids an earlier attempt (or a task this one succeeds) released under the row's tag, kept until the release
18
21
  * is billed: a provider's tag lookup lists running sessions only, so a later attempt no longer finds one it stopped. */
@@ -41,6 +44,8 @@ type HandoffResult = {
41
44
  outcome: HandoffOutcome;
42
45
  reason?: string;
43
46
  };
47
+ /** When the provider made each session a tag lookup found, by id (InventoryRow.made). */
48
+ type Made = Record<string, string>;
44
49
  export type StoreDeps = {
45
50
  name: string;
46
51
  Config: ConversationDocToken<BrowserConfig>;
@@ -59,8 +64,12 @@ export type StoreDeps = {
59
64
  handedBack?(tag: string, fence: number): void;
60
65
  /** A release task (an attempt, or its abort handler) had the provider release `tag`'s session, and the provider answered. */
61
66
  stopped?(tag: string): void;
67
+ /** A release by `row`'s tag ended sessions besides the row's own (`ids`, each confirmed no longer running): a create
68
+ * retried behind the provider, or a create race, left them. Their time is on no record (durable.ts, onRaceReleased).
69
+ * `made`: when the provider made each, where a tag lookup said (InventoryRow.made). */
70
+ raced?(row: InventoryRow, ids: string[], made: Made): Promise<void>;
62
71
  };
63
- export declare function custodyStore({ name, Config, Sessions, providerOf, emit, meter, bill, scrubbed, createDeadlineMs, handoff, handedBack, stopped: stoppedHook }: StoreDeps): {
72
+ export declare function custodyStore({ name, Config, Sessions, providerOf, emit, meter, bill, scrubbed, createDeadlineMs, handoff, handedBack, stopped: stoppedHook, raced }: StoreDeps): {
64
73
  Inventory: import("@earendil-works/pi-durable").SessionDocToken<{
65
74
  rows: Record<string, InventoryRow>;
66
75
  }>;
@@ -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,14 +134,42 @@ 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
175
  /** `found`: the id a release task's lookup found for a record that has none yet, which the commit after this one
@@ -100,11 +184,22 @@ export function custodyStore({ name, Config, Sessions, providerOf, emit, meter,
100
184
  }
101
185
  const union = (...lists) => [...new Set(lists.flatMap((ids) => ids ?? []))];
102
186
  /** The row stays in the inventory until a run open's reconcile sees nothing under its tag running. `found` goes on to
103
- * 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. */
104
189
  async function retry(runtime, row, attempt, context, found) {
105
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));
106
201
  await runtime.commit(async (tx) => {
107
- 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 });
108
203
  return { status: "terminal", outcome: { status: "failed", error: { code: "release_failed", message: `${row.tag}: not released after ${RELEASE_ATTEMPTS} attempts` } } };
109
204
  }, context);
110
205
  return;
@@ -130,11 +225,15 @@ export function custodyStore({ name, Config, Sessions, providerOf, emit, meter,
130
225
  // Ids the lookup found that the task does not hold yet are committed before any stop is sent: an attempt cut
131
226
  // between its stop and its next commit (the task's abort) leaves them for the abort handler, whose own lookup
132
227
  // no longer lists a stopped session.
133
- const keep = async (ids) => {
228
+ const keep = async (ids, made) => {
134
229
  seen = ids;
135
230
  const known = union(found, ids);
136
- if (known.length > found.length)
137
- 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
+ }
138
237
  };
139
238
  const released = await step(runtime, async () => releaseAll(row, await providerOf(runtime, cidOf(row), row.plane, context), runtime.signal, keep), null);
140
239
  // What the lookup found goes on to the next attempt even when its release failed: the stop may have landed.
@@ -155,12 +254,13 @@ export function custodyStore({ name, Config, Sessions, providerOf, emit, meter,
155
254
  }
156
255
  if (running)
157
256
  return retry(runtime, row, attempt, context, ids);
158
- // The host hears the release before the task's last commit, so at least once, with the bill that commit
159
- // 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.
160
259
  const at = iso(runtime.now());
161
260
  await emitReleased(cidOf(row), row.tag, runtime, context, at, foundId(row, ids));
261
+ await tellRaced(row, ids, () => madeFor(runtime, row, context));
162
262
  await runtime.commit(async (tx) => {
163
- 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) });
164
264
  return { status: "terminal", outcome: { status: "completed", result: { released: ids.length } } };
165
265
  }, context);
166
266
  },
@@ -172,14 +272,30 @@ export function custodyStore({ name, Config, Sessions, providerOf, emit, meter,
172
272
  const checkpoint = task.state.checkpoint;
173
273
  let found = union(task.input.found, checkpoint.phase === "confirm" ? checkpoint.ids : checkpoint.found);
174
274
  let stopped = null;
175
- // 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.
176
279
  if (!(notBefore && runtime.now() < notBefore))
177
- 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));
178
290
  if (stopped)
179
291
  stoppedHook?.(row.tag);
292
+ if (told.length)
293
+ await raced?.(row, told, await madeFor(runtime, row, context, seen));
180
294
  await runtime.commit(async (tx) => {
181
295
  if (stopped)
182
- 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 });
183
299
  else
184
300
  await tx.createTask(ReleaseTask, { ...task.input, ...(found.length ? { found } : {}) }, { ownership: { kind: "conversation" }, conversationId: cidOf(row), background: true });
185
301
  return { status: "terminal", outcome: { status: "aborted", reason: stopped ? "released by the abort handler" : "release handed to a successor task" } };
@@ -265,6 +381,65 @@ export function custodyStore({ name, Config, Sessions, providerOf, emit, meter,
265
381
  } while (cursor);
266
382
  return undefined;
267
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
+ }
268
443
  async function reconcileAll(harness, isActive, context) {
269
444
  const report = { released: [], kept: [], lost: [], unreachable: [] };
270
445
  for (const row of Object.values((await harness.snapshot(Inventory, context))?.rows ?? {})) {
@@ -277,32 +452,7 @@ export function custodyStore({ name, Config, Sessions, providerOf, emit, meter,
277
452
  try {
278
453
  const provider = await providerOf(harness, cidOf(row), row.plane, context);
279
454
  if (row.state === "lost") {
280
- let seen = [];
281
- const ids = await releasedIds(provider, row, undefined, (found) => void (seen = found)).catch(async (error) => {
282
- // The stop may have landed before the provider's answer was lost, and its tag lookup lists running sessions
283
- // only: a session known only by its tag keeps the id found on its row and record, for the next reconcile to
284
- // release and bill.
285
- const id = row.resourceId === null ? seen[0] : undefined;
286
- if (id !== undefined) {
287
- await commit(async (tx) => {
288
- const rows = (await tx.doc(Inventory)).rows;
289
- if (rows[row.tag])
290
- rows[row.tag] = { ...rows[row.tag], resourceId: id };
291
- const record = (await tx.doc(Sessions, cidOf(row))).sessions.find((r) => r.tag === row.tag);
292
- if (record && record.resourceId === null)
293
- record.resourceId = id;
294
- }).catch(() => undefined);
295
- }
296
- throw error;
297
- });
298
- await (ids ? outcome("released", async (tx) => {
299
- delete (await tx.doc(Inventory)).rows[row.tag];
300
- const record = (await tx.doc(Sessions, cidOf(row))).sessions.find((r) => r.tag === row.tag);
301
- if (record && record.resourceId === null && ids.length)
302
- record.resourceId = ids[0];
303
- if (record && record.resourceId !== null)
304
- await bill(tx, cidOf(row), record, at, true);
305
- }) : outcome("lost"));
455
+ await reconcileLost(provider, row, commit, outcome, at);
306
456
  continue;
307
457
  }
308
458
  let live = row;
package/dist/durable.d.ts CHANGED
@@ -56,6 +56,20 @@ export type BrowserExtensionOptions<D extends PageDriver = PageDriver> = VaultOp
56
56
  onCharge?: (charge: SessionCharge, tx: Tx, call?: {
57
57
  callId: string;
58
58
  }) => void | Promise<void>;
59
+ /** A release by a session's tag ended sessions besides that session's own: a create retried behind the provider's API,
60
+ * or a create race of the session's tag, left them running, and no record bills their time. Their ids, so a host books
61
+ * what they ran, once a status read confirms each stopped, one whose release stopped it and then failed included. Each
62
+ * is saved on the session's inventory row (`owed`) before its stop is sent, until it is told: the session's own release
63
+ * confirms them, or a run open's reconcile for a row that ended lost or still owes one. Called again for an id only
64
+ * when a process ends between this call and the commit that takes it off the row. A throw here never fails the
65
+ * release. `madeAt`: when the provider made each of them (an ISO time, by id), where its tag lookup said
66
+ * (LeaseRef.madeAt), kept on the row with the id, so a later process hands it on too; absent when it said for none. */
67
+ onRaceReleased?: (released: {
68
+ conversationId: number;
69
+ tag: string;
70
+ ids: string[];
71
+ madeAt?: Record<string, string>;
72
+ }) => void | Promise<void>;
59
73
  /** Exact strings to scrub from every output besides the built-in shapes, read at each use. */
60
74
  redact?: {
61
75
  values: () => readonly string[];
package/dist/durable.js CHANGED
@@ -706,7 +706,9 @@ async function releasePlane(c, conversation, reason, context, still = () => true
706
706
  }
707
707
  }
708
708
  /** The open sessions' time through now, not final, in one commit (BrowserExtensionHandle.charge): no lock is taken, so a
709
- * release under way (its record `releasing`) never holds it back. */
709
+ * release under way (its record `releasing`) never holds it back. A record with no session id (its create under way, or
710
+ * its answer lost and the session not yet found by its tag) has nothing at the provider to bill yet: its release's charge
711
+ * bills the whole session once it is found. One already charged through now has no time to charge, and gets no $0 one. */
710
712
  async function chargeOpen(c, conversation, context) {
711
713
  return conversation.commit(async (tx) => {
712
714
  const state = await tx.doc(c.Sessions, conversation.id);
@@ -715,6 +717,8 @@ async function chargeOpen(c, conversation, context) {
715
717
  for (const record of state.sessions) {
716
718
  if ((record.state !== "live" && record.state !== "held" && record.state !== "releasing") || record.resourceId === null || record.spent.final)
717
719
  continue;
720
+ if (Date.parse(record.spent.chargedThrough) >= Date.parse(at))
721
+ continue;
718
722
  if (await c.bill(tx, conversation.id, record, at, false))
719
723
  charged += 1;
720
724
  }
@@ -848,6 +852,13 @@ export function createBrowserExtension(options) {
848
852
  handoff: options.handoff,
849
853
  handedBack: (tag, fence) => c.fences.set(tag, { fence, failure: HANDED_BACK }),
850
854
  stopped: (tag) => { c.stops.get(tag)?.stop(); c.stops.delete(tag); },
855
+ raced: async (row, ids, made) => {
856
+ const madeAt = Object.fromEntries(ids.flatMap((id) => (made[id] ? [[id, made[id]]] : [])));
857
+ try {
858
+ await options.onRaceReleased?.({ conversationId: row.conversationId, tag: row.tag, ids, ...(Object.keys(madeAt).length ? { madeAt } : {}) });
859
+ }
860
+ catch { /* the host's booking never fails the release */ }
861
+ },
851
862
  });
852
863
  const c = {
853
864
  ...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(),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@parcha/pi-browser",
3
- "version": "0.1.0-beta.65",
3
+ "version": "0.1.0-beta.67",
4
4
  "description": "Your agent gets its own browser, and you can take over and hand it back.",
5
5
  "keywords": [
6
6
  "pi-durable",