@parcha/pi-browser 0.1.0-beta.77 → 0.1.0-beta.79
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 +15 -0
- package/README.md +5 -4
- package/dist/core/downloads.d.ts +37 -3
- package/dist/core/downloads.js +80 -56
- package/dist/core/public-fetch.d.ts +3 -1
- package/dist/core/public-fetch.js +64 -3
- package/dist/core/tools.d.ts +2 -1
- package/dist/durable.d.ts +5 -3
- package/dist/durable.js +2 -4
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,21 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased
|
|
4
4
|
|
|
5
|
+
## 0.1.0-beta.79 (2026-12-01)
|
|
6
|
+
|
|
7
|
+
**Breaking:**
|
|
8
|
+
|
|
9
|
+
- `createBrowserExtension`'s `workspace` option now returns a `DownloadsWorkspace` (read, stat, mkdir, write, writeNew, remove, each relative to the workspace), not a folder's path, and `fetchDownloads` takes one as its `workspace`. A host passes its own guarded workspace; a test can wrap a folder. `browser_upload` is listed only when the host passes `files`, since `workspace` no longer gives a default: pass `files: workspaceFiles(folder)` to keep it. A `downloads/manifest.json` that is a link, even to a file in the workspace, is now refused: replace it with the file itself. <!-- changes/downloads-workspace-option.md -->
|
|
10
|
+
|
|
11
|
+
**Changes:**
|
|
12
|
+
|
|
13
|
+
- `isPrivateAddress` counts the hosting cluster's internal ranges as private: the ranges in `CLUSTER_INTERNAL_CIDRS` (a comma list of CIDRs, an address alone being one host), or GKE's default Service range `34.118.224.0/20` when it is unset or blank. That range is public address space on paper, so a name that resolves into it from inside a cluster (an in-cluster service, the Kubernetes API) passed every outbound guard before. Every guard built on the classifier refuses it now, at the check and at the dial it pins: `publicFetch`, `publicDownload` and `publicCheck` (web_fetch, web_save), the server's outbound webhook at its save and at each try, and the MCP server, calendar and feed checks, where no owner's private-hosts list allows it. A value replaces the default. A value holding an entry that is not a CIDR, a CIDR with bits set past its prefix, or no entry at all (separators alone) refuses every address until it is fixed. Each process holds to its own environment: set it on the server and on each runner, and restart them to change it. <!-- changes/cluster-internal-ranges.md -->
|
|
14
|
+
- On a Mode 1 server, `browser_downloads`, a run's checkout and the delete of a run or an agent write and remove in the run's folder only through the run's Workspace, which follows no link and never waits on a FIFO. A computer that shares the folder can no longer send a download, the manifest or the lock outside it by swapping `downloads/` for a link while the call runs. <!-- changes/downloads-no-follow.md -->
|
|
15
|
+
- `downloads/` that is a link or a file is refused before anything is written, and the call says why. So is a `downloads/manifest.json` that is not a regular file (a FIFO, a link, a folder): it is opened without blocking, checked, and refused at once, never read through.
|
|
16
|
+
- Each file is placed under a name no other file holds, with no temporary file beside it. A name taken by other bytes gains the file's digest, as before.
|
|
17
|
+
- A Mode 1 checkout (`checkout: pull_request` or `repository`) is made in a private folder of the server's, then copied into `repo/` through the run's Workspace. A computer kept from an earlier claim can no longer send the checkout outside the run's folder by swapping `repo/` for a link while it lands. A link in the repository's tree is checked out as a plain file holding its target, with `core.symlinks` false in `repo/.git/config`. A `repo/` that is itself a link is left as it is, and the run is told there is no checkout. A stop, or the checkout's time running out, during the copy ends it before the next file and removes the partial `repo/`. Every git call of a checkout, in either mode, runs with no fsmonitor, no attributes file and no transport but the remote's own scheme, and stops its search for a repository at the folder it started in: an fsmonitor named in a `.git/config` planted before the checkout never runs. Mode 2's checkout is otherwise unchanged.
|
|
18
|
+
- Deleting a run or an agent removes its folders on this machine through held folders and follows no link. A DELETE that a computer still sharing the run's folder changes mid-way is `503`, and the next DELETE finishes it.
|
|
19
|
+
|
|
5
20
|
## 0.1.0-beta.75 (2026-11-30)
|
|
6
21
|
|
|
7
22
|
- A page web_fetch can't read whole now gives the agent its start and a way to the rest. A page whose body is over 5 MiB, fetched directly, used to answer `refused: the page is over 5 MiB` with no text at all; it now answers its first 5 MiB as the page's start, `cut_bytes` on every part, and the last part's line says the rest wasn't read. A page's text past the first 1,000,000 characters is still out of paging's reach, and every part that shows it now says so. An answer to an `objective` for such a page says its chunks are from the page's start alone. Of each, on a run granted `web_save`, the line tells the agent to save the page whole as a file with it and read that file. `publicFetch` takes `cut: true` for this; without it, and in `publicDownload` (web_save's), a body over the cap is refused as before. `webFetchText` takes the save tool's name as an optional third argument. <!-- changes/web-fetch-big-page.md -->
|
package/README.md
CHANGED
|
@@ -206,7 +206,7 @@ One session at a time may save to a profile in one process. A second saver is re
|
|
|
206
206
|
| `run` | Act: code, or a batch of ref actions (`goto` takes a URL instead of an id). An AgentRun browser computer (raw CDP) takes actions only. | Never reruns. The model is told the call may have taken effect and where the page was, and the identical code is refused once (`effect_unknown`). |
|
|
207
207
|
| `browser_release`, `browser_relaunch` | End the session; end it and open another. | Idempotent. A create carries a tag, so a rerun finds its session. |
|
|
208
208
|
| `browser_request_handoff` | Hand the session to a person for a step only a human can do, and wait for the host's handoff port to say how it ended. While the person has it, every other call answers `waiting_for_human`. Listed only when the host gives a `handoff` port. | Reruns and waits on the same request; a request asked again carries the same `request_id`, which the port treats as one. |
|
|
209
|
-
| `browser_upload` | Choose one workspace file in a file input on the page, as a person picking it would. Nothing is submitted; `run` submits the form afterwards. The durable adapter lists it only when the host supplies `files
|
|
209
|
+
| `browser_upload` | Choose one workspace file in a file input on the page, as a person picking it would. Nothing is submitted; `run` submits the form afterwards. The durable adapter lists it only when the host supplies `files`. | Never reruns. An upload the page does not answer fails at 60 s as possibly applied, and the identical retry is refused until the agent has looked at the page. |
|
|
210
210
|
|
|
211
211
|
Session minutes are charged by the session meter (`core/usage.ts`, wired into custody): every session tool's result carries the
|
|
212
212
|
time since the last charge, and each released session's record carries its total. A host that books session time as spend
|
|
@@ -272,7 +272,8 @@ The pi peers are `@earendil-works/pi-durable` and `chord` `1.5.2` exactly. CI te
|
|
|
272
272
|
variant `publicDownload(url, { lookup?, fetchImpl?, signal?, maxBytes? })` (one file of any type, `{ url, status,
|
|
273
273
|
contentType, bytes }`, `bytes` null for a status that is not 2xx; the same hops, checks and pinned dial as
|
|
274
274
|
`publicFetch`, a declared length over `maxBytes` refused before the body is read and a body over it refused as it is
|
|
275
|
-
read), and `readPage(html, url, { deadlineMs?, signal? })`, with `isPrivateAddress`
|
|
275
|
+
read), and `readPage(html, url, { deadlineMs?, signal? })`, with `isPrivateAddress` (which also counts the ranges in `CLUSTER_INTERNAL_CIDRS` as private, GKE's Service range
|
|
276
|
+
`34.118.224.0/20` when it is unset or blank) and `pinnedLookup`. `readPage` never holds
|
|
276
277
|
the event loop: it drops a page's script, style, svg, noscript and template blocks, cuts what is left at
|
|
277
278
|
`READ_MAX_CHARS` (`truncated`, with the page's length in `html_chars`), and converts it to markdown in a worker thread
|
|
278
279
|
within `READ_DEADLINE_MS`, falling back to the page's plain text (`converted: "text"`). `browser_read`'s markdown goes
|
|
@@ -349,8 +350,8 @@ await browser.reconcile(harness, () => true, context); // settles what a dead
|
|
|
349
350
|
- `signIns`: `true` when the plane's sessions open on the agent's saved sign-ins (your kept profile or context). `run`'s
|
|
350
351
|
description then tells the model the browser keeps them, for a page behind a sign-in; without it, it says only that the
|
|
351
352
|
browser keeps cookies across pages. Absent, it is whether a `sessionVault` is given.
|
|
352
|
-
- `workspace`:
|
|
353
|
-
- `files`: a `WorkspaceFiles` that resolves `browser_upload` paths.
|
|
353
|
+
- `workspace`: per conversation, the `DownloadsWorkspace` that `browser_downloads` writes through: the host's own file calls on its workspace (read, stat, mkdir, write, writeNew, remove), each path relative to the workspace and none following a link on the way or at its end, a read refusing anything but a regular file without waiting on it. Absent, `browser_downloads` is not listed.
|
|
354
|
+
- `files`: a `WorkspaceFiles` that resolves `browser_upload` paths (`workspaceFiles(folder)` is one). Absent, `browser_upload` is not listed.
|
|
354
355
|
- `handoff`: a `HandoffPort` that reaches a person (`request`, then `outcome` polled until done, cancelled or expired;
|
|
355
356
|
when a request expires is the port's to decide). Absent, `browser_request_handoff` is not listed.
|
|
356
357
|
- `prices`: your session price (for example from `BROWSERBASE_USD_PER_MINUTE`). It prices the session meter, so each session
|
package/dist/core/downloads.d.ts
CHANGED
|
@@ -4,6 +4,36 @@ export declare const DOWNLOADS_DIR = "downloads";
|
|
|
4
4
|
export declare const DOWNLOADS_MANIFEST = "downloads/manifest.json";
|
|
5
5
|
export declare const MAX_DOWNLOAD_BYTES: number;
|
|
6
6
|
export declare const MAX_DOWNLOAD_FILES = 50;
|
|
7
|
+
/** The workspace browser_downloads copies into: the host's own file calls on it, never a path of this machine. Every path
|
|
8
|
+
* is relative to the workspace's root, folders separated by "/", and no call follows a link, on the way to its path or
|
|
9
|
+
* at its end: a link there is refused, so a folder that another process sharing the workspace swaps for a link (a
|
|
10
|
+
* computer that mounts it) leads no call outside it. agentrun-serve's Workspace is one (its local folder walks each
|
|
11
|
+
* path by handles opened with O_NOFOLLOW). */
|
|
12
|
+
export interface DownloadsWorkspace {
|
|
13
|
+
/** The bytes of regular file `path`, or `length` of them from `offset`. Anything else there (a link, a folder, a FIFO)
|
|
14
|
+
* is refused, without waiting on it; nothing there fails with `code` "NOT_FOUND". */
|
|
15
|
+
read(path: string, range?: {
|
|
16
|
+
readonly offset?: number;
|
|
17
|
+
readonly length?: number;
|
|
18
|
+
}): Promise<Uint8Array>;
|
|
19
|
+
/** What is at `path`, never following it, or undefined when nothing is. */
|
|
20
|
+
stat(path: string): Promise<{
|
|
21
|
+
readonly kind: "file" | "dir" | "link" | "other";
|
|
22
|
+
readonly size: number;
|
|
23
|
+
readonly mtimeMs: number;
|
|
24
|
+
} | undefined>;
|
|
25
|
+
/** Folder `path` made with its parents; one already there is fine, anything else there (a link, a file) is refused. */
|
|
26
|
+
mkdir(path: string): Promise<void>;
|
|
27
|
+
/** File `path` replaced by `data` in one step. */
|
|
28
|
+
write(path: string, data: Uint8Array | string): Promise<void>;
|
|
29
|
+
/** File `path` made with `data` only when nothing is at it, in one step: true when made, false when something is
|
|
30
|
+
* already there, which is kept. */
|
|
31
|
+
writeNew(path: string, data: Uint8Array | string): Promise<boolean>;
|
|
32
|
+
/** File `path` removed; nothing there is no failure with `force`. */
|
|
33
|
+
remove(path: string, options?: {
|
|
34
|
+
readonly force?: boolean;
|
|
35
|
+
}): Promise<void>;
|
|
36
|
+
}
|
|
7
37
|
/** What a skipped download the browser is still writing says: the next call files it. */
|
|
8
38
|
export declare const STILL_DOWNLOADING = "still downloading; call browser_downloads again";
|
|
9
39
|
/** A provider's read of a file the browser was still writing (its bytes or its name moved while it was read). */
|
|
@@ -30,13 +60,17 @@ export type DownloadsResult = {
|
|
|
30
60
|
};
|
|
31
61
|
/** A name that stays inside `downloads/`: the last path segment, no control characters, not hidden, not the manifest. */
|
|
32
62
|
export declare function safeDownloadName(remote: string): string;
|
|
33
|
-
|
|
34
|
-
|
|
63
|
+
/** `run` while this call holds lock file `file` of `workspace`, made only where nothing is at its name; one older than
|
|
64
|
+
* 30 s is a dead writer's, and is removed. */
|
|
65
|
+
export declare function withLock<T>(workspace: DownloadsWorkspace, file: string, run: () => Promise<T>, what?: string): Promise<T>;
|
|
66
|
+
/** Skips what the workspace already holds; one failing file is skipped with its reason. Every file call goes through
|
|
67
|
+
* `workspace`, which follows no link: a `downloads/` that is a link, or anything but a folder, is refused before any
|
|
68
|
+
* write, and so is a manifest that is not a regular file. */
|
|
35
69
|
export declare function fetchDownloads(options: {
|
|
36
70
|
provider: Pick<BrowserProvider, "downloads">;
|
|
37
71
|
ref: LeaseRef;
|
|
38
72
|
session: string;
|
|
39
|
-
workspace:
|
|
73
|
+
workspace: DownloadsWorkspace;
|
|
40
74
|
maxBytes?: number;
|
|
41
75
|
maxFiles?: number;
|
|
42
76
|
now?: () => Date;
|
package/dist/core/downloads.js
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import { createHash
|
|
2
|
-
import { lstat, mkdir, open, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
3
2
|
import path from "node:path";
|
|
4
3
|
import { refusedError } from "./custody.js";
|
|
5
4
|
export const DOWNLOADS_DIR = "downloads";
|
|
@@ -9,6 +8,8 @@ export const DOWNLOADS_MANIFEST = "downloads/manifest.json";
|
|
|
9
8
|
const LOCK_FILE = ".downloads.lock";
|
|
10
9
|
export const MAX_DOWNLOAD_BYTES = 100 * 1024 * 1024;
|
|
11
10
|
export const MAX_DOWNLOAD_FILES = 50;
|
|
11
|
+
/** How much of a file one read takes, when a name already taken is compared with a download's bytes. */
|
|
12
|
+
const COMPARE_READ_BYTES = 8 * 1024 * 1024;
|
|
12
13
|
/** What a skipped download the browser is still writing says: the next call files it. */
|
|
13
14
|
export const STILL_DOWNLOADING = "still downloading; call browser_downloads again";
|
|
14
15
|
/** A provider's read of a file the browser was still writing (its bytes or its name moved while it was read). */
|
|
@@ -24,41 +25,56 @@ export function safeDownloadName(remote) {
|
|
|
24
25
|
return !base || base === "manifest.json" ? "download" : base;
|
|
25
26
|
}
|
|
26
27
|
const sameRemote = (row, session, file) => row.session === session && row.remote.name === file.name && row.remote.sizeBytes === file.sizeBytes && row.remote.modifiedAt === file.modifiedAt;
|
|
27
|
-
const
|
|
28
|
-
|
|
28
|
+
const words = (error) => (error instanceof Error ? error.message : String(error));
|
|
29
|
+
/** A regular file is at `rel`: a path a manifest row names, which anything sharing the workspace can edit, so one the
|
|
30
|
+
* workspace refuses holds no file. */
|
|
31
|
+
const isFile = (workspace, rel) => workspace.stat(rel).then((at) => at?.kind === "file", () => false);
|
|
32
|
+
/** Whether `rel` is a regular file of `size` bytes whose SHA-256 is `sha256`, read in parts. */
|
|
33
|
+
async function holds(workspace, rel, size, sha256) {
|
|
34
|
+
const at = await workspace.stat(rel);
|
|
35
|
+
if (at?.kind !== "file" || at.size !== size)
|
|
36
|
+
return false;
|
|
37
|
+
const hash = createHash("sha256");
|
|
38
|
+
for (let read = 0; read < size;) {
|
|
39
|
+
const part = await workspace.read(rel, { offset: read, length: Math.min(COMPARE_READ_BYTES, size - read) });
|
|
40
|
+
if (part.byteLength === 0)
|
|
41
|
+
return false;
|
|
42
|
+
hash.update(part);
|
|
43
|
+
read += part.byteLength;
|
|
44
|
+
}
|
|
45
|
+
return hash.digest("hex") === sha256;
|
|
46
|
+
}
|
|
29
47
|
const withRow = (rows, row) => [...rows.filter((r) => r.path !== row.path || (r.sha256 === row.sha256 && !(r.session === row.session && r.remote.name === row.remote.name))), row];
|
|
30
|
-
|
|
48
|
+
/** `run` while this call holds lock file `file` of `workspace`, made only where nothing is at its name; one older than
|
|
49
|
+
* 30 s is a dead writer's, and is removed. */
|
|
50
|
+
export async function withLock(workspace, file, run, what = DOWNLOADS_MANIFEST) {
|
|
31
51
|
for (const deadline = Date.now() + 10_000;; await new Promise((r) => setTimeout(r, 25 + Math.random() * 50))) {
|
|
32
|
-
|
|
33
|
-
await (await open(file, "wx")).close();
|
|
52
|
+
if (await workspace.writeNew(file, ""))
|
|
34
53
|
break;
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
await rm(file, { force: true });
|
|
41
|
-
else if (Date.now() > deadline)
|
|
42
|
-
throw new Error(`${what} is locked by another writer`);
|
|
43
|
-
}
|
|
54
|
+
const at = await workspace.stat(file);
|
|
55
|
+
if (at !== undefined && Date.now() - at.mtimeMs > 30_000)
|
|
56
|
+
await workspace.remove(file, { force: true });
|
|
57
|
+
else if (Date.now() > deadline)
|
|
58
|
+
throw new Error(`${what} is locked by another writer`);
|
|
44
59
|
}
|
|
45
60
|
try {
|
|
46
61
|
return await run();
|
|
47
62
|
}
|
|
48
63
|
finally {
|
|
49
|
-
await
|
|
64
|
+
await workspace.remove(file, { force: true });
|
|
50
65
|
}
|
|
51
66
|
}
|
|
52
|
-
/** A manifest that is there but unreadable is refused, never replaced: its rows are the only record of earlier fetches.
|
|
53
|
-
|
|
67
|
+
/** A manifest that is there but unreadable is refused, never replaced: its rows are the only record of earlier fetches.
|
|
68
|
+
* Only a regular file is read: the workspace's read refuses a link, a folder or a FIFO, and never waits on one. */
|
|
69
|
+
async function readManifest(workspace) {
|
|
54
70
|
let raw;
|
|
55
71
|
try {
|
|
56
|
-
raw = await
|
|
72
|
+
raw = Buffer.from(await workspace.read(DOWNLOADS_MANIFEST)).toString("utf8");
|
|
57
73
|
}
|
|
58
74
|
catch (error) {
|
|
59
|
-
if (error
|
|
75
|
+
if (error?.code === "NOT_FOUND")
|
|
60
76
|
return { schema: "pi-browser.downloads.v1", files: [] };
|
|
61
|
-
throw error;
|
|
77
|
+
throw refusedError(`${DOWNLOADS_MANIFEST} cannot be read as a regular file (${words(error)}); move it, then call browser_downloads again.`);
|
|
62
78
|
}
|
|
63
79
|
let parsed = null;
|
|
64
80
|
try {
|
|
@@ -69,25 +85,28 @@ async function readManifest(file) {
|
|
|
69
85
|
return parsed;
|
|
70
86
|
throw refusedError(`${DOWNLOADS_MANIFEST} exists but is not a pi-browser downloads manifest; fix or move it, then call browser_downloads again.`);
|
|
71
87
|
}
|
|
72
|
-
/** Skips what the workspace already holds; one failing file is skipped with its reason.
|
|
88
|
+
/** Skips what the workspace already holds; one failing file is skipped with its reason. Every file call goes through
|
|
89
|
+
* `workspace`, which follows no link: a `downloads/` that is a link, or anything but a folder, is refused before any
|
|
90
|
+
* write, and so is a manifest that is not a regular file. */
|
|
73
91
|
export async function fetchDownloads(options) {
|
|
74
92
|
const { provider, ref, session, workspace } = options;
|
|
75
93
|
if (!provider.downloads)
|
|
76
94
|
throw new Error("this provider cannot list downloads");
|
|
77
95
|
const maxBytes = options.maxBytes ?? MAX_DOWNLOAD_BYTES;
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
96
|
+
try {
|
|
97
|
+
await workspace.mkdir(DOWNLOADS_DIR);
|
|
98
|
+
}
|
|
99
|
+
catch (error) {
|
|
100
|
+
throw refusedError(`${DOWNLOADS_DIR}/ in the workspace is not a directory the browser can copy into (${words(error)}); move it, then call browser_downloads again.`);
|
|
101
|
+
}
|
|
102
|
+
const manifest = await readManifest(workspace);
|
|
84
103
|
const result = { fetched: [], already_fetched: [], skipped: [], manifest: DOWNLOADS_MANIFEST };
|
|
85
104
|
const entry = (row) => ({ name: row.name, path: row.path, sizeBytes: row.sizeBytes, sha256: row.sha256 });
|
|
86
105
|
const remote = await provider.downloads.list(ref);
|
|
87
106
|
let attempted = 0;
|
|
88
107
|
for (const file of remote) {
|
|
89
108
|
const known = manifest.files.find((row) => sameRemote(row, session, file));
|
|
90
|
-
if (known && (await
|
|
109
|
+
if (known && (await isFile(workspace, known.path))) {
|
|
91
110
|
result.already_fetched.push(entry(known));
|
|
92
111
|
continue;
|
|
93
112
|
}
|
|
@@ -105,48 +124,53 @@ export async function fetchDownloads(options) {
|
|
|
105
124
|
result.skipped.push({ name: file.name, reason: `larger than the ${maxBytes}-byte limit` });
|
|
106
125
|
continue;
|
|
107
126
|
}
|
|
108
|
-
const part = path.join(dir, `.part-${randomBytes(6).toString("hex")}`);
|
|
109
127
|
try {
|
|
128
|
+
// The bytes are held here (at most maxBytes): nothing is written until the file is whole and its name chosen, as
|
|
129
|
+
// its name may be its digest's. Each chunk is copied into one buffer, sized by the provider's listed size, as it
|
|
130
|
+
// comes and then dropped, so the file is held once; a read longer than listed grows it (to maxBytes at most).
|
|
110
131
|
const hash = createHash("sha256");
|
|
132
|
+
let held = Buffer.allocUnsafe(Number.isSafeInteger(file.sizeBytes) && file.sizeBytes > 0 ? Math.min(file.sizeBytes, maxBytes) : 0);
|
|
111
133
|
let size = 0;
|
|
112
|
-
const
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
await out.write(chunk);
|
|
134
|
+
for await (const chunk of await provider.downloads.read(ref, file.name, maxBytes)) {
|
|
135
|
+
if (size + chunk.byteLength > maxBytes)
|
|
136
|
+
throw new Error(`larger than the ${maxBytes}-byte limit`);
|
|
137
|
+
if (size + chunk.byteLength > held.length) {
|
|
138
|
+
const grown = Buffer.allocUnsafe(Math.min(maxBytes, Math.max(held.length * 2, size + chunk.byteLength)));
|
|
139
|
+
held.copy(grown, 0, 0, size);
|
|
140
|
+
held = grown;
|
|
120
141
|
}
|
|
142
|
+
hash.update(chunk);
|
|
143
|
+
held.set(chunk, size);
|
|
144
|
+
size += chunk.byteLength;
|
|
121
145
|
}
|
|
122
|
-
|
|
123
|
-
await out.close();
|
|
124
|
-
}
|
|
146
|
+
const bytes = held.subarray(0, size);
|
|
125
147
|
const sha256 = hash.digest("hex");
|
|
126
|
-
// Naming, placing and recording are one step under the lock, so two writers never both find a name free
|
|
127
|
-
//
|
|
148
|
+
// Naming, placing and recording are one step under the lock, so two writers never both find a name free. A file is
|
|
149
|
+
// placed only where nothing is at its name (writeNew), so it never replaces other contents: a name that holds these
|
|
150
|
+
// very bytes is this file already, and one taken by other bytes gains this file's digest.
|
|
128
151
|
const wanted = safeDownloadName(file.name);
|
|
129
152
|
const ext = path.extname(wanted);
|
|
130
|
-
const row = await withLock(
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
153
|
+
const row = await withLock(workspace, LOCK_FILE, async () => {
|
|
154
|
+
const names = [wanted, ...[8, 16, 32, 64].map((digits) => `${path.basename(wanted, ext)}-${sha256.slice(0, digits)}${ext}`)];
|
|
155
|
+
let name;
|
|
156
|
+
for (const candidate of names) {
|
|
157
|
+
const rel = path.posix.join(DOWNLOADS_DIR, candidate);
|
|
158
|
+
if ((await workspace.writeNew(rel, bytes)) || (await holds(workspace, rel, size, sha256))) {
|
|
159
|
+
name = candidate;
|
|
134
160
|
break;
|
|
135
|
-
|
|
161
|
+
}
|
|
136
162
|
}
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
const
|
|
140
|
-
const
|
|
141
|
-
await
|
|
142
|
-
await rename(tmp, manifestPath);
|
|
163
|
+
if (name === undefined)
|
|
164
|
+
throw new Error(`every name for it in ${DOWNLOADS_DIR}/ holds other bytes`);
|
|
165
|
+
const placed = { name, path: path.posix.join(DOWNLOADS_DIR, name), sizeBytes: size, sha256, remote: { name: file.name, sizeBytes: file.sizeBytes, modifiedAt: file.modifiedAt }, session, fetchedAt: (options.now?.() ?? new Date()).toISOString() };
|
|
166
|
+
const latest = withRow((await readManifest(workspace)).files, placed);
|
|
167
|
+
await workspace.write(DOWNLOADS_MANIFEST, `${JSON.stringify({ schema: "pi-browser.downloads.v1", files: latest }, null, 2)}\n`);
|
|
143
168
|
return placed;
|
|
144
169
|
});
|
|
145
170
|
manifest.files = withRow(manifest.files, row);
|
|
146
171
|
result.fetched.push(entry(row));
|
|
147
172
|
}
|
|
148
173
|
catch (error) {
|
|
149
|
-
await rm(part, { force: true });
|
|
150
174
|
const reason = error instanceof DownloadNotSettled ? STILL_DOWNLOADING : error instanceof Error ? (options.redact ?? ((text) => text))(error.message).slice(0, 200) : "the read failed";
|
|
151
175
|
result.skipped.push({ name: file.name, reason });
|
|
152
176
|
}
|
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
/** Any address but a public unicast one, v4 and v6 (see V4_PRIVATE and V6_PRIVATE)
|
|
1
|
+
/** Any address but a public unicast one, v4 and v6 (see V4_PRIVATE and V6_PRIVATE), or one in the hosting cluster's
|
|
2
|
+
* internal ranges (CLUSTER_INTERNAL_CIDRS_ENV); what does not parse as one too. The one address judgment every
|
|
3
|
+
* outbound guard here uses: web_fetch, web_save, the webhook and the MCP, calendar and feed checks. */
|
|
2
4
|
export declare function isPrivateAddress(ip: string): boolean;
|
|
3
5
|
/** Answers `address` for any name: the address a request was checked against is the one it connects to. */
|
|
4
6
|
export declare const pinnedLookup: (address: string) => (_host: string, options: {
|
|
@@ -32,10 +32,71 @@ function v6Groups(ip) {
|
|
|
32
32
|
return [...head, ...new Array(8 - head.length - tail.length).fill(0), ...tail];
|
|
33
33
|
}
|
|
34
34
|
const inV6 = (groups, base, bits) => groups.every((group, i) => { const span = Math.max(0, Math.min(16, bits - 16 * i)); const mask = (0xffff << (16 - span)) & 0xffff; return (group & mask) === (base[i] & mask); });
|
|
35
|
-
/**
|
|
35
|
+
/** The environment variable listing the hosting cluster's own internal ranges: comma-separated CIDRs (an address alone is
|
|
36
|
+
* one host) that are public address space on paper but internal where the server runs, such as a
|
|
37
|
+
* managed Kubernetes cluster's Service range. Its value replaces the default; unset or blank, the default holds. */
|
|
38
|
+
const CLUSTER_INTERNAL_CIDRS_ENV = "CLUSTER_INTERNAL_CIDRS";
|
|
39
|
+
/** GKE's default Service range: Google-owned space that is never routed publicly, where in-cluster names resolve. */
|
|
40
|
+
const DEFAULT_CLUSTER_INTERNAL_CIDRS = "34.118.224.0/20";
|
|
41
|
+
let parsedClusterRanges;
|
|
42
|
+
/** One CIDR (or a lone address) as its base and prefix length; null when it is not one, or when it sets bits past its
|
|
43
|
+
* prefix (a typo such as `34.118.236.1/20` is refused, not read as a wider or narrower range). */
|
|
44
|
+
function clusterRange(entry) {
|
|
45
|
+
const [address, prefix, extra] = entry.split("/");
|
|
46
|
+
if (extra !== undefined || !address)
|
|
47
|
+
return null;
|
|
48
|
+
const family = net.isIPv4(address) ? 4 : net.isIPv6(address) ? 6 : 0;
|
|
49
|
+
if (!family)
|
|
50
|
+
return null;
|
|
51
|
+
const width = family === 4 ? 32 : 128;
|
|
52
|
+
const bits = prefix === undefined ? width : /^\d{1,3}$/.test(prefix) ? Number(prefix) : NaN;
|
|
53
|
+
if (!(bits >= 0 && bits <= width))
|
|
54
|
+
return null;
|
|
55
|
+
if (family === 4) {
|
|
56
|
+
const base = v4(address);
|
|
57
|
+
return base % 2 ** (32 - bits) === 0 ? { family, base, bits } : null;
|
|
58
|
+
}
|
|
59
|
+
const groups = v6Groups(address);
|
|
60
|
+
if (!groups)
|
|
61
|
+
return null;
|
|
62
|
+
const hostBits = groups.some((group, i) => { const span = Math.max(0, Math.min(16, bits - 16 * i)); return (group & ~(0xffff << (16 - span)) & 0xffff) !== 0; });
|
|
63
|
+
return hostBits ? null : { family, groups, bits };
|
|
64
|
+
}
|
|
65
|
+
/** The cluster's internal ranges, read from this process's environment at each use (CLUSTER_INTERNAL_CIDRS_ENV); null when
|
|
66
|
+
* the value holds an entry that is not a CIDR, or names none, so a bad setting refuses every address instead of opening
|
|
67
|
+
* one. */
|
|
68
|
+
function clusterInternalRanges() {
|
|
69
|
+
const value = process.env[CLUSTER_INTERNAL_CIDRS_ENV]?.trim() || DEFAULT_CLUSTER_INTERNAL_CIDRS;
|
|
70
|
+
if (parsedClusterRanges?.value === value)
|
|
71
|
+
return parsedClusterRanges.ranges;
|
|
72
|
+
let ranges = { v4: [], v6: [] };
|
|
73
|
+
for (const entry of value.split(",").map((part) => part.trim()).filter(Boolean)) {
|
|
74
|
+
const range = clusterRange(entry);
|
|
75
|
+
if (!range) {
|
|
76
|
+
ranges = null;
|
|
77
|
+
break;
|
|
78
|
+
}
|
|
79
|
+
if (range.family === 4)
|
|
80
|
+
ranges.v4.push([range.base, range.bits]);
|
|
81
|
+
else
|
|
82
|
+
ranges.v6.push([range.groups, range.bits]);
|
|
83
|
+
}
|
|
84
|
+
// A value of separators alone names no range: as malformed as a bad entry, never an empty list.
|
|
85
|
+
if (ranges && !ranges.v4.length && !ranges.v6.length)
|
|
86
|
+
ranges = null;
|
|
87
|
+
parsedClusterRanges = { value, ranges };
|
|
88
|
+
return ranges;
|
|
89
|
+
}
|
|
90
|
+
const inV4 = (ip, base, bits) => Math.floor(v4(ip) / 2 ** (32 - bits)) === Math.floor(base / 2 ** (32 - bits));
|
|
91
|
+
/** Any address but a public unicast one, v4 and v6 (see V4_PRIVATE and V6_PRIVATE), or one in the hosting cluster's
|
|
92
|
+
* internal ranges (CLUSTER_INTERNAL_CIDRS_ENV); what does not parse as one too. The one address judgment every
|
|
93
|
+
* outbound guard here uses: web_fetch, web_save, the webhook and the MCP, calendar and feed checks. */
|
|
36
94
|
export function isPrivateAddress(ip) {
|
|
95
|
+
const cluster = clusterInternalRanges();
|
|
96
|
+
if (!cluster)
|
|
97
|
+
return true;
|
|
37
98
|
if (net.isIPv4(ip))
|
|
38
|
-
return V4_PRIVATE.some(([base, bits]) =>
|
|
99
|
+
return V4_PRIVATE.some(([base, bits]) => inV4(ip, base, bits)) || cluster.v4.some(([base, bits]) => inV4(ip, base, bits));
|
|
39
100
|
const groups = net.isIPv6(ip) ? v6Groups(ip) : null;
|
|
40
101
|
if (!groups)
|
|
41
102
|
return true;
|
|
@@ -44,7 +105,7 @@ export function isPrivateAddress(ip) {
|
|
|
44
105
|
// 6to4 (2002::/16, RFC 3056) carries an IPv4 address in its next 32 bits, which a relay delivers to: judged as that one.
|
|
45
106
|
if (groups[0] === 0x2002)
|
|
46
107
|
return isPrivateAddress([groups[1] >> 8, groups[1] & 0xff, groups[2] >> 8, groups[2] & 0xff].join("."));
|
|
47
|
-
return V6_PRIVATE.some(([base, bits]) => inV6(groups, v6Groups(base), bits));
|
|
108
|
+
return V6_PRIVATE.some(([base, bits]) => inV6(groups, v6Groups(base), bits)) || cluster.v6.some(([base, bits]) => inV6(groups, base, bits));
|
|
48
109
|
}
|
|
49
110
|
/** Answers `address` for any name: the address a request was checked against is the one it connects to. */
|
|
50
111
|
export const pinnedLookup = (address) => (_host, options, callback) => {
|
package/dist/core/tools.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { type BrowserDriver, type CustodyPort, type ToolOutput } from "./custody.js";
|
|
2
2
|
import { type EvidenceSink } from "./evidence.js";
|
|
3
3
|
import type { Decisions } from "./decisions.js";
|
|
4
|
+
import { type DownloadsWorkspace } from "./downloads.js";
|
|
4
5
|
import type { WorkspaceFiles } from "./host.js";
|
|
5
6
|
import { type RepeatGuard } from "./guard.js";
|
|
6
7
|
import { type Locate } from "./clip.js";
|
|
@@ -92,7 +93,7 @@ export type ToolCall = {
|
|
|
92
93
|
redact: Redact;
|
|
93
94
|
evidence: EvidenceSink;
|
|
94
95
|
classifyPage?: Decisions["classifyPage"];
|
|
95
|
-
workspace?:
|
|
96
|
+
workspace?: DownloadsWorkspace;
|
|
96
97
|
files?: WorkspaceFiles;
|
|
97
98
|
};
|
|
98
99
|
export type ToolImpl<D extends BrowserDriver = BrowserDriver, A = unknown> = (args: A, port: CustodyPort<D>, call: ToolCall) => Promise<ToolOutput>;
|
package/dist/durable.d.ts
CHANGED
|
@@ -4,6 +4,7 @@ import { type DriverFactory } from "./core/custody.js";
|
|
|
4
4
|
import type { Decisions } from "./core/decisions.js";
|
|
5
5
|
import type { EvidenceSink } from "./core/evidence.js";
|
|
6
6
|
import { EffectObserver } from "./core/effects.js";
|
|
7
|
+
import type { DownloadsWorkspace } from "./core/downloads.js";
|
|
7
8
|
import { type VaultOptions } from "./vault-session.js";
|
|
8
9
|
import type { DrivingGates } from "./live-view/protocol.js";
|
|
9
10
|
import { type BrowserToolImpls, type PageDriver } from "./core/tools.js";
|
|
@@ -34,11 +35,12 @@ export type BrowserExtensionOptions<D extends PageDriver = PageDriver> = VaultOp
|
|
|
34
35
|
/** Implementations by contract name, over the package's own; a contract tool with no implementation is not listed. */
|
|
35
36
|
tools?: Partial<BrowserToolImpls<D>>;
|
|
36
37
|
evidence: EvidenceSink;
|
|
37
|
-
/**
|
|
38
|
-
|
|
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;
|
|
43
|
+
/** Resolves `browser_upload` paths (workspaceFiles over a folder is one); absent, it is not listed. */
|
|
42
44
|
files?: WorkspaceFiles;
|
|
43
45
|
/** Live view and session status; a throw here never fails a call. */
|
|
44
46
|
onSession?: (row: SessionRow, change: SessionChange) => void | Promise<void>;
|
package/dist/durable.js
CHANGED
|
@@ -5,7 +5,6 @@ import { BrowserFailureError, closeDriver, DRIVER_ACK_BEFORE_KILL_MS, settledWit
|
|
|
5
5
|
import { forModel } from "./durable/result.js";
|
|
6
6
|
import { EffectObserver, effectDecider, observerFailure } from "./core/effects.js";
|
|
7
7
|
import { browserFailure, classifyBrowserError, isRefusal } from "./core/failures.js";
|
|
8
|
-
import { workspaceFiles } from "./core/files.js";
|
|
9
8
|
import { drivingGuarded } from "./core/driving-guard.js";
|
|
10
9
|
import { drivingGates, keptFor, keptReason, personOn, rearmWhenLeft } from "./core/driving.js";
|
|
11
10
|
import { captureFor, planRestore, untilQuiet, vaultRuntime } from "./vault-session.js";
|
|
@@ -743,7 +742,7 @@ const withSessionTime = (own, charged) => {
|
|
|
743
742
|
};
|
|
744
743
|
function toolsFor(c, impls) {
|
|
745
744
|
return browserToolsFor(c.options.signIns ?? !!c.options.sessionVault)
|
|
746
|
-
.filter((contract) => impls[contract.name] && listedFor(contract, { downloads: !!c.options.workspace, upload: !!
|
|
745
|
+
.filter((contract) => impls[contract.name] && listedFor(contract, { downloads: !!c.options.workspace, upload: !!c.options.files, handoff: !!c.options.handoff }))
|
|
747
746
|
.map((contract) => defineTool({
|
|
748
747
|
name: contract.name,
|
|
749
748
|
description: contract.description,
|
|
@@ -755,8 +754,7 @@ function toolsFor(c, impls) {
|
|
|
755
754
|
c.idle.activity(api.conversationId, +1, (config?.policy.idleReleaseS ?? 0) * 1000);
|
|
756
755
|
try {
|
|
757
756
|
const workspace = c.options.workspace?.(api.conversationId);
|
|
758
|
-
const
|
|
759
|
-
const call = { callId: api.callId, conversationId: api.conversationId, signal: context.abortSignal, label: config?.label ?? "", redact: c.redact, evidence: c.options.evidence, classifyPage: c.options.decisions?.classifyPage, workspace, files };
|
|
757
|
+
const call = { callId: api.callId, conversationId: api.conversationId, signal: context.abortSignal, label: config?.label ?? "", redact: c.redact, evidence: c.options.evidence, classifyPage: c.options.decisions?.classifyPage, workspace, files: c.options.files };
|
|
760
758
|
// Inside an async function, so a host tool that throws before it returns a promise is caught too.
|
|
761
759
|
const out = await (async () => impls[contract.name](args, portFor(c, api, context), call))().catch((error) => {
|
|
762
760
|
// A throw would reach pi's diagnostic unscrubbed: every failure comes back as the typed envelope, redacted.
|