@parcha/pi-browser 0.1.0-beta.49 → 0.1.0-beta.50

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,10 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 0.1.0-beta.50 (2026-11-20)
6
+
7
+ - `web_save {url, path}`, a new host tool, saves one public file (at most 200 MiB) into the run's `work/`, a bare name under `media/`. It downloads through `web_fetch`'s guard, never overwrites, and saves media only when the bytes, the declared type and the extension agree. An agent gets it by naming it. pi-browser adds `publicDownload`, the bytes version of `publicFetch`. A template eval's `web:` fixture takes an optional `save` section. <!-- changes/web-save-tool.md -->
8
+
5
9
  ## 0.1.0-beta.49 (2026-11-20)
6
10
 
7
11
  - A session whose create answer was lost, and which the release task found later by its tag, is now told to the host's `onSession` at its release with the id that lookup found and the bill its release records. Before, the host heard it with `resourceId` null and nothing spent, because the release is told before the commit that records them. <!-- changes/pi-browser-release-found-id.md -->
package/README.md CHANGED
@@ -268,8 +268,11 @@ The pi peers are `@earendil-works/pi-durable` and `chord` `1.5.2` exactly. CI te
268
268
  - `@parcha/pi-browser`: the host-neutral core. The model contract (tool names, descriptions, JSON schemas, effect and
269
269
  replay classes, the `browser` and `web` prompt sections), the typed failure envelope, the redactor, the screenshot
270
270
  budget, the repeat guard, evidence and decision-hook types, usage and prices, `find` (chunking and ranking a long page),
271
- `browser_downloads`, the opt-in request observer, and the provider interface. The public-host guard is here too: `publicFetch(url, { lookup?, fetchImpl?, signal?, maxBytes? })` and
272
- `readPage(html, url, { deadlineMs?, signal? })`, with `isPrivateAddress` and `pinnedLookup`. `readPage` never holds
271
+ `browser_downloads`, the opt-in request observer, and the provider interface. The public-host guard is here too: `publicFetch(url, { lookup?, fetchImpl?, signal?, maxBytes? })`, its bytes
272
+ variant `publicDownload(url, { lookup?, fetchImpl?, signal?, maxBytes? })` (one file of any type, `{ url, status,
273
+ contentType, bytes }`, `bytes` null for a status that is not 2xx; the same hops, checks and pinned dial as
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` and `pinnedLookup`. `readPage` never holds
273
276
  the event loop: it drops a page's script, style, svg, noscript and template blocks, cuts what is left at
274
277
  `READ_MAX_CHARS` (`truncated`, with the page's length in `html_chars`), and converts it to markdown in a worker thread
275
278
  within `READ_DEADLINE_MS`, falling back to the page's plain text (`converted: "text"`). `browser_read`'s markdown goes
@@ -21,6 +21,14 @@ export type PublicAnswer = {
21
21
  contentType: string;
22
22
  body: string | null;
23
23
  };
24
+ /** The answer that ended the redirects, as `publicDownload` gives it: its URL, status and type, and its bytes when it is a
25
+ * 2xx answer (an empty array for a 2xx with no body). */
26
+ export type PublicFile = {
27
+ url: string;
28
+ status: number;
29
+ contentType: string;
30
+ bytes: Uint8Array | null;
31
+ };
24
32
  /**
25
33
  * Fetches `url` from a public host, following at most 5 redirects, each hop resolved, checked and dialled at the
26
34
  * address checked. A 2xx answer of a text type is read whole, up to `maxBytes`; another status comes back without its
@@ -30,3 +38,13 @@ export type PublicAnswer = {
30
38
  * with the signal's reason), and an aborted hop is never dialled.
31
39
  */
32
40
  export declare function publicFetch(url: string, options?: PublicFetchOptions): Promise<PublicAnswer>;
41
+ /**
42
+ * Downloads `url` from a public host: publicFetch's hops and refusals (scheme, local or private host, port, redirects,
43
+ * the signal), with any content type accepted and the body kept as bytes, up to `maxBytes` (default 5 MiB). A 2xx answer
44
+ * is read whole; another status comes back with `bytes` null. A body over the cap is refused (`refused: the file is over
45
+ * <cap>`): before a byte is read when its content-length says so, else as soon as it passes it. A body whose length its
46
+ * host states (an unencoded reply's content-length) is read into one buffer of that length, so it is held once; one longer
47
+ * than stated is refused as it runs past it, one shorter at its end. With no stated length the chunks are joined at the
48
+ * end, about twice the file's size at the peak. `signal` ends the body's read too, with its reason.
49
+ */
50
+ export declare function publicDownload(url: string, options?: PublicFetchOptions): Promise<PublicFile>;
@@ -73,20 +73,23 @@ function untilAborted(work, signal) {
73
73
  * or application/<name>+json (atom, rss, xhtml, ld+json), so a site's feed reads like its pages. Anything else (a PDF,
74
74
  * a zip, octet-stream, an image/svg+xml) is refused. */
75
75
  const TEXT_TYPE = /^(text\/|application\/(json|xml|[\w.!#$&^-]+\+(xml|json)\b))/i;
76
+ const MIB = 1024 * 1024;
77
+ /** The options checked before any lookup: `maxBytes` (default 5 MiB) a whole number of bytes above 0. */
78
+ function capOf(options) {
79
+ const maxBytes = options.maxBytes ?? PUBLIC_MAX_BYTES;
80
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 1)
81
+ throw new RangeError(`maxBytes must be a whole number of bytes above 0, not ${maxBytes}`);
82
+ return maxBytes;
83
+ }
76
84
  /**
77
- * Fetches `url` from a public host, following at most 5 redirects, each hop resolved, checked and dialled at the
78
- * address checked. A 2xx answer of a text type is read whole, up to `maxBytes`; another status comes back without its
79
- * body. Refused (`BrowserFailureError` `refused`), on the first hop or a redirect: a scheme other than http(s); a host
80
- * that is local by name or resolves to any private address; a port other than 80 or 443; too many redirects; a 2xx body
81
- * that is not text or is over the cap. `signal` ends the fetch at any point, a hop's name lookup included (it rejects
82
- * with the signal's reason), and an aborted hop is never dialled.
85
+ * The hop loop both answers share: `url` fetched from a public host, following at most 5 redirects, each hop resolved,
86
+ * checked and dialled at the address checked, asking for `accept`. The answer that ends the redirects goes to `answer`,
87
+ * which reads what it needs of it; whatever it leaves unread is cancelled, and the hop's connection closed, once it
88
+ * returns or throws.
83
89
  */
84
- export async function publicFetch(url, options = {}) {
90
+ async function publicHops(url, options, accept, answer) {
85
91
  const lookup = options.lookup ?? (async (host) => (await dns.lookup(host, { all: true })).map((a) => a.address));
86
92
  const request = options.fetchImpl ?? ((target, init) => undiciFetch(target, init));
87
- const maxBytes = options.maxBytes ?? PUBLIC_MAX_BYTES;
88
- if (!Number.isSafeInteger(maxBytes) || maxBytes < 1)
89
- throw new RangeError(`maxBytes must be a whole number of bytes above 0, not ${maxBytes}`);
90
93
  let target = new URL(url);
91
94
  if (!/^https?:$/.test(target.protocol))
92
95
  throw refusedError(`refused: ${target.protocol} is not http(s)`);
@@ -103,7 +106,7 @@ export async function publicFetch(url, options = {}) {
103
106
  const dispatcher = new Agent({ connect: { lookup: pinnedLookup(addresses[0]) } });
104
107
  let res;
105
108
  try {
106
- res = await request(target, { redirect: "manual", signal: options.signal, dispatcher, headers: { accept: "text/html,text/plain;q=0.9,*/*;q=0.1", "user-agent": "pi-browser" } });
109
+ res = await request(target, { redirect: "manual", signal: options.signal, dispatcher, headers: { accept, "user-agent": "pi-browser" } });
107
110
  if (res.status >= 300 && res.status < 400 && res.headers.get("location")) {
108
111
  if (hop >= MAX_REDIRECTS)
109
112
  throw refusedError("refused: too many redirects");
@@ -112,27 +115,7 @@ export async function publicFetch(url, options = {}) {
112
115
  throw refusedError("refused: a redirect left http(s)");
113
116
  continue;
114
117
  }
115
- const contentType = res.headers.get("content-type") ?? "";
116
- if (!res.ok)
117
- return { url: target.href, status: res.status, contentType, body: null };
118
- // A 2xx with no body at all (204, 205) is an empty page, whatever type it names.
119
- if (!res.body)
120
- return { url: target.href, status: res.status, contentType, body: "" };
121
- if (!TEXT_TYPE.test(contentType))
122
- throw refusedError(`refused: ${contentType || "an unknown content type"} is not text`);
123
- const chunks = [];
124
- let size = 0;
125
- for (const reader = res.body.getReader();;) {
126
- const { done, value } = await reader.read();
127
- if (done)
128
- break;
129
- if ((size += value.length) > maxBytes) {
130
- await reader.cancel();
131
- throw refusedError(`refused: the page is over ${maxBytes === PUBLIC_MAX_BYTES ? "5 MiB" : `${maxBytes} bytes`}`);
132
- }
133
- chunks.push(value);
134
- }
135
- return { url: target.href, status: res.status, contentType, body: Buffer.concat(chunks).toString("utf8") };
118
+ return await answer(res, target);
136
119
  }
137
120
  finally {
138
121
  // A reply refused unread (not text, an error status, a redirect) still holds its connection: close() waits
@@ -142,3 +125,110 @@ export async function publicFetch(url, options = {}) {
142
125
  }
143
126
  }
144
127
  }
128
+ /** `reader`'s next chunk; with `signal`, ended at the signal's abort with its reason (the body cancelled), whatever the
129
+ * fetch does with the signal. */
130
+ const nextChunk = (reader, signal) => signal ? untilAborted(() => reader.read(), signal).catch(async (error) => { await reader.cancel(error).catch(() => undefined); throw error; }) : reader.read();
131
+ /** `body` read whole, refused (`over`'s words) once it passes `maxBytes`: cut off while it is read, not after. With
132
+ * `signal`, each read also ends at the signal's abort, with its reason. The chunks are kept and joined at the end, so a
133
+ * body peaks at about twice its size in memory: readStated is the path for a body whose length is stated. */
134
+ async function readCapped(body, maxBytes, over, signal) {
135
+ const chunks = [];
136
+ let size = 0;
137
+ for (const reader = body.getReader();;) {
138
+ const { done, value } = await nextChunk(reader, signal);
139
+ if (done)
140
+ break;
141
+ if ((size += value.length) > maxBytes) {
142
+ await reader.cancel();
143
+ throw refusedError(over);
144
+ }
145
+ chunks.push(value);
146
+ }
147
+ return Buffer.concat(chunks);
148
+ }
149
+ /** `body`, whose host stated it is `length` bytes, read into one buffer of that length, allocated before the first chunk:
150
+ * the file is held once, never joined into a second copy. A chunk that runs past `length` is refused as it comes, the
151
+ * body cancelled; a body that ends short of it is refused at its end. `signal` as readCapped's. */
152
+ async function readStated(body, length, signal) {
153
+ const bytes = new Uint8Array(length);
154
+ let at = 0;
155
+ for (const reader = body.getReader();;) {
156
+ const { done, value } = await nextChunk(reader, signal);
157
+ if (done)
158
+ break;
159
+ if (value.length > length - at) {
160
+ await reader.cancel();
161
+ throw refusedError(`refused: the file is longer than the ${length} bytes its host stated`);
162
+ }
163
+ bytes.set(value, at);
164
+ at += value.length;
165
+ }
166
+ if (at !== length)
167
+ throw refusedError(`refused: the file ended at ${at} of the ${length} bytes its host stated`);
168
+ return bytes;
169
+ }
170
+ /** The length a 2xx reply states for the body a fetch hands over: its content-length when that is a plain count and the
171
+ * body is not encoded (a gzip reply's length counts the bytes on the wire, not the decoded ones); else undefined. */
172
+ function statedLength(headers) {
173
+ const said = headers.get("content-length")?.trim();
174
+ if (said === undefined || !/^\d{1,16}$/.test(said))
175
+ return undefined;
176
+ const encoding = headers.get("content-encoding")?.trim().toLowerCase();
177
+ if (encoding && encoding !== "identity")
178
+ return undefined;
179
+ const length = Number(said);
180
+ return Number.isSafeInteger(length) ? length : undefined;
181
+ }
182
+ /**
183
+ * Fetches `url` from a public host, following at most 5 redirects, each hop resolved, checked and dialled at the
184
+ * address checked. A 2xx answer of a text type is read whole, up to `maxBytes`; another status comes back without its
185
+ * body. Refused (`BrowserFailureError` `refused`), on the first hop or a redirect: a scheme other than http(s); a host
186
+ * that is local by name or resolves to any private address; a port other than 80 or 443; too many redirects; a 2xx body
187
+ * that is not text or is over the cap. `signal` ends the fetch at any point, a hop's name lookup included (it rejects
188
+ * with the signal's reason), and an aborted hop is never dialled.
189
+ */
190
+ export async function publicFetch(url, options = {}) {
191
+ const maxBytes = capOf(options);
192
+ return publicHops(url, options, "text/html,text/plain;q=0.9,*/*;q=0.1", async (res, target) => {
193
+ const contentType = res.headers.get("content-type") ?? "";
194
+ if (!res.ok)
195
+ return { url: target.href, status: res.status, contentType, body: null };
196
+ // A 2xx with no body at all (204, 205) is an empty page, whatever type it names.
197
+ if (!res.body)
198
+ return { url: target.href, status: res.status, contentType, body: "" };
199
+ if (!TEXT_TYPE.test(contentType))
200
+ throw refusedError(`refused: ${contentType || "an unknown content type"} is not text`);
201
+ const body = await readCapped(res.body, maxBytes, `refused: the page is over ${maxBytes === PUBLIC_MAX_BYTES ? "5 MiB" : `${maxBytes} bytes`}`);
202
+ return { url: target.href, status: res.status, contentType, body: body.toString("utf8") };
203
+ });
204
+ }
205
+ /**
206
+ * Downloads `url` from a public host: publicFetch's hops and refusals (scheme, local or private host, port, redirects,
207
+ * the signal), with any content type accepted and the body kept as bytes, up to `maxBytes` (default 5 MiB). A 2xx answer
208
+ * is read whole; another status comes back with `bytes` null. A body over the cap is refused (`refused: the file is over
209
+ * <cap>`): before a byte is read when its content-length says so, else as soon as it passes it. A body whose length its
210
+ * host states (an unencoded reply's content-length) is read into one buffer of that length, so it is held once; one longer
211
+ * than stated is refused as it runs past it, one shorter at its end. With no stated length the chunks are joined at the
212
+ * end, about twice the file's size at the peak. `signal` ends the body's read too, with its reason.
213
+ */
214
+ export async function publicDownload(url, options = {}) {
215
+ const maxBytes = capOf(options);
216
+ const over = `refused: the file is over ${maxBytes % MIB === 0 ? `${maxBytes / MIB} MiB` : `${maxBytes} bytes`}`;
217
+ return publicHops(url, options, "*/*", async (res, target) => {
218
+ const contentType = res.headers.get("content-type") ?? "";
219
+ if (!res.ok)
220
+ return { url: target.href, status: res.status, contentType, bytes: null };
221
+ if (!res.body)
222
+ return { url: target.href, status: res.status, contentType, bytes: new Uint8Array(0) };
223
+ const declared = Number(res.headers.get("content-length") ?? Number.NaN);
224
+ if (Number.isFinite(declared) && declared > maxBytes)
225
+ throw refusedError(over);
226
+ // A stated length (at most the cap, checked above): the bytes read into one buffer of it. None: the chunks joined at
227
+ // the end, about twice the file's size at its peak.
228
+ const length = statedLength(res.headers);
229
+ if (length !== undefined)
230
+ return { url: target.href, status: res.status, contentType, bytes: await readStated(res.body, length, options.signal) };
231
+ const body = await readCapped(res.body, maxBytes, over, options.signal);
232
+ return { url: target.href, status: res.status, contentType, bytes: new Uint8Array(body.buffer, body.byteOffset, body.byteLength) };
233
+ });
234
+ }
package/dist/index.d.ts CHANGED
@@ -13,7 +13,7 @@ export * from "./core/host.js";
13
13
  export * from "./core/images.js";
14
14
  export * from "./core/lease.js";
15
15
  export * from "./core/page-classifier.js";
16
- export { isPrivateAddress, pinnedLookup, PUBLIC_MAX_BYTES, publicFetch, type PublicAnswer, type PublicFetchOptions } from "./core/public-fetch.js";
16
+ export { isPrivateAddress, pinnedLookup, PUBLIC_MAX_BYTES, publicDownload, publicFetch, type PublicAnswer, type PublicFetchOptions, type PublicFile } from "./core/public-fetch.js";
17
17
  export { READ_DEADLINE_MS, READ_MAX_CHARS, readPage, type PageRead, type ReadPageOptions } from "./core/read-page.js";
18
18
  export * from "./core/receipts.js";
19
19
  export * from "./core/redact.js";
package/dist/index.js CHANGED
@@ -14,7 +14,7 @@ export * from "./core/host.js";
14
14
  export * from "./core/images.js";
15
15
  export * from "./core/lease.js";
16
16
  export * from "./core/page-classifier.js";
17
- export { isPrivateAddress, pinnedLookup, PUBLIC_MAX_BYTES, publicFetch } from "./core/public-fetch.js";
17
+ export { isPrivateAddress, pinnedLookup, PUBLIC_MAX_BYTES, publicDownload, publicFetch } from "./core/public-fetch.js";
18
18
  export { READ_DEADLINE_MS, READ_MAX_CHARS, readPage } from "./core/read-page.js";
19
19
  export * from "./core/receipts.js";
20
20
  export * from "./core/redact.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@parcha/pi-browser",
3
- "version": "0.1.0-beta.49",
3
+ "version": "0.1.0-beta.50",
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",