@foldrun/core 17.4.0 → 18.0.1

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/src/history.ts CHANGED
@@ -372,6 +372,12 @@ export function resolveRevisionLocal(
372
372
 
373
373
  /** The pick of resolveRevision over a newest-first list of restorable revisions. */
374
374
  function resolveIn(all: RevisionSummary[], to: string, now: number): { id: string; at: string; by: string; message: string } | null {
375
+ return pick(all, target(to, now));
376
+ }
377
+
378
+ /** What a restore's `to` names: a moment, or an id (or a commit). Throws 400
379
+ * on something that is neither. */
380
+ function target(to: string, now: number): { moment: number } | { id: string } {
375
381
  const t = to.trim();
376
382
  if (!t || t.startsWith("-")) throw Object.assign(new Error(`not a revision or a time: ${to}`), { status: 400 });
377
383
  const rel = /^(\d+)\s*(m|h|d|w)$/.exec(t);
@@ -380,12 +386,20 @@ function resolveIn(all: RevisionSummary[], to: string, now: number): { id: strin
380
386
  : /^\d{4}-\d{2}-\d{2}/.test(t)
381
387
  ? Date.parse(t)
382
388
  : null;
383
- let hit: RevisionSummary | undefined;
384
389
  if (moment !== null) {
385
390
  if (Number.isNaN(moment)) throw Object.assign(new Error(`not a date: ${to}`), { status: 400 });
386
- hit = all.find((r) => Date.parse(r.at) <= moment);
391
+ return { moment };
392
+ }
393
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,120}$/.test(t)) throw Object.assign(new Error(`not a revision or a time: ${to}`), { status: 400 });
394
+ return { id: t };
395
+ }
396
+
397
+ function pick(all: RevisionSummary[], want: { moment: number } | { id: string }): { id: string; at: string; by: string; message: string } | null {
398
+ let hit: RevisionSummary | undefined;
399
+ if ("moment" in want) {
400
+ hit = all.find((r) => Date.parse(r.at) <= want.moment);
387
401
  } else {
388
- if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,120}$/.test(t)) throw Object.assign(new Error(`not a revision or a time: ${to}`), { status: 400 });
402
+ const t = want.id;
389
403
  // An exact id first, then a commit: a commit deployed twice is recorded
390
404
  // once under its own id and again under a fresh one naming it (30 Oct
391
405
  // 2026, recordRevision), and newest-first with one predicate answered
@@ -532,29 +546,45 @@ export function latestRevisionIdLocal(tenant: string, scope: string): string | n
532
546
  // loses no history. The account shelf ("@library") is never in revisions.
533
547
 
534
548
  export interface RevisionView {
535
- /** Newest first, or null when revisions do not serve this scope. */
536
- list(tenant: string, scope: string, opts: { forPath?: string; limit?: number }): Promise<RevisionSummary[] | null>;
549
+ /** Newest first, or null when revisions do not serve this scope. Every page
550
+ * of the store up to `limit` (Infinity: all of it); `paths: false` leaves
551
+ * the changed paths out (rows say []), which is what makes "all" cheap. */
552
+ list(tenant: string, scope: string, opts: { forPath?: string; limit?: number; paths?: boolean }): Promise<RevisionSummary[] | null>;
537
553
  read(tenant: string, scope: string, id: string, forPath?: string): Promise<Revision | null>;
538
554
  snapshot(tenant: string, scope: string, id: string): Promise<{ path: string; content: string }[] | null>;
555
+ /** One revision by id, looked up rather than listed (paths []); null when
556
+ * the store has none. Optional: a view without it is asked through `list`. */
557
+ get?(tenant: string, scope: string, id: string): Promise<RevisionSummary | null>;
539
558
  }
540
559
  let view: RevisionView | null = null;
541
560
  export function registerRevisionView(v: RevisionView | null) {
542
561
  view = v;
543
562
  }
544
563
 
545
- /** Revisions first, then the local entries older than the oldest of them. */
546
- async function combined(tenant: string, scope: string, opts: { forPath?: string; limit?: number }, restorableOnly = false): Promise<RevisionSummary[]> {
564
+ /** Revisions first, then the local entries older than the oldest of them.
565
+ * `stored` is which rows came from the store (every one a restore point). */
566
+ async function combinedRows(
567
+ tenant: string,
568
+ scope: string,
569
+ opts: { forPath?: string; limit?: number; paths?: boolean },
570
+ restorableOnly = false,
571
+ ): Promise<{ rows: RevisionSummary[]; stored: Set<string> }> {
547
572
  const limit = opts.limit ?? 200;
548
- const mine = view && scope !== "@library" ? await view.list(tenant, scope, { ...opts, limit: Number.isFinite(limit) ? limit : 500 }) : null;
573
+ // The whole of `limit`, every page of it: the store's first page is not all
574
+ // of history (FOL-152).
575
+ const mine = view && scope !== "@library" ? await view.list(tenant, scope, { ...opts, limit }) : null;
549
576
  let local = listRevisionsLocal(tenant, scope, { forPath: opts.forPath, limit: Infinity });
550
577
  if (restorableOnly) {
551
578
  const have = snapshotIds(tenant, scope);
552
579
  local = local.filter((r) => have.has(r.id));
553
580
  }
554
- if (!mine || !mine.length) return local.slice(0, limit);
581
+ if (!mine || !mine.length) return { rows: local.slice(0, limit), stored: new Set() };
555
582
  const oldest = mine[mine.length - 1].at;
556
583
  const seen = new Set(mine.map((r) => r.id));
557
- return [...mine, ...local.filter((r) => !seen.has(r.id) && r.at < oldest)].slice(0, limit);
584
+ return { rows: [...mine, ...local.filter((r) => !seen.has(r.id) && r.at < oldest)].slice(0, limit), stored: seen };
585
+ }
586
+ async function combined(tenant: string, scope: string, opts: { forPath?: string; limit?: number; paths?: boolean }, restorableOnly = false): Promise<RevisionSummary[]> {
587
+ return (await combinedRows(tenant, scope, opts, restorableOnly)).rows;
558
588
  }
559
589
 
560
590
  export async function listRevisions(tenant: string, scope: string, opts: { forPath?: string; limit?: number } = {}): Promise<RevisionSummary[]> {
@@ -566,9 +596,8 @@ export async function listRevisions(tenant: string, scope: string, opts: { forPa
566
596
  * a local entry is when it has a snapshot — where asking per row would list
567
597
  * the store once per row. */
568
598
  export async function listRevisionsRestorable(tenant: string, scope: string, opts: { forPath?: string; limit?: number } = {}): Promise<(RevisionSummary & { restorable: boolean })[]> {
569
- const rows = await combined(tenant, scope, opts);
599
+ const { rows, stored } = await combinedRows(tenant, scope, opts);
570
600
  const have = snapshotIds(tenant, scope);
571
- const stored = view && scope !== "@library" ? new Set(((await view.list(tenant, scope, { limit: 500 })) ?? []).map((r) => r.id)) : new Set<string>();
572
601
  return rows.map((r) => ({ ...r, restorable: have.has(r.id) || stored.has(r.id) }));
573
602
  }
574
603
 
@@ -587,7 +616,11 @@ export async function snapshotAt(tenant: string, scope: string, id: string): Pro
587
616
  export async function hasSnapshot(tenant: string, scope: string, id: string): Promise<boolean> {
588
617
  assertSafeName(id, "revision id");
589
618
  if (hasSnapshotLocal(tenant, scope, id)) return true;
590
- return Boolean(view && scope !== "@library" && (await view.list(tenant, scope, { limit: 500 }))?.some((r) => r.id === id));
619
+ if (!view || scope === "@library") return false;
620
+ // Looked up by id: a listing stops at a page, and a revision older than it
621
+ // was "not restorable" until 9 Nov 2026 (FOL-152).
622
+ if (view.get) return (await view.get(tenant, scope, id)) !== null;
623
+ return Boolean((await view.list(tenant, scope, { limit: Infinity, paths: false }))?.some((r) => r.id === id));
591
624
  }
592
625
 
593
626
  export async function headRevision(tenant: string, scope: string): Promise<RevisionSummary | null> {
@@ -595,7 +628,15 @@ export async function headRevision(tenant: string, scope: string): Promise<Revis
595
628
  }
596
629
 
597
630
  export async function resolveRevision(tenant: string, scope: string, to: string, now = Date.now()): Promise<{ id: string; at: string; by: string; message: string } | null> {
598
- return resolveIn(await combined(tenant, scope, { limit: Infinity }, true), to, now);
631
+ const want = target(to, now);
632
+ // An id in the store is one lookup; anything else (a date, a local id, a
633
+ // commit) is answered from ALL of history — every page of the store, without
634
+ // the changed paths, then the local entries.
635
+ if ("id" in want && view?.get && scope !== "@library") {
636
+ const hit = await view.get(tenant, scope, want.id);
637
+ if (hit) return { id: hit.id, at: hit.at, by: hit.by, message: hit.message };
638
+ }
639
+ return pick(await combined(tenant, scope, { limit: Infinity, paths: false }, true), want);
599
640
  }
600
641
 
601
642
  export async function changedPathsBetween(tenant: string, scope: string, from: string | null, to: string | null): Promise<string[] | null> {
@@ -24,6 +24,7 @@
24
24
  // resumed (and swept by abortStaleUploads / a bucket lifecycle rule if no
25
25
  // one comes back).
26
26
 
27
+ import crypto from "node:crypto";
27
28
  import { s3Request, forgetS3Credentials, type S3Config, type S3StreamBody } from "./storage.ts";
28
29
  import {
29
30
  BlobNotFound,
@@ -47,6 +48,7 @@ const MiB = 1024 * 1024;
47
48
  export const MIN_PART_BYTES = 5 * MiB;
48
49
  /** S3's ceiling on the number of parts. */
49
50
  export const MAX_PARTS = 10_000;
51
+ const MAX_TIMER_MS = 2 ** 31 - 1;
50
52
 
51
53
  export interface S3BlobOptions {
52
54
  /** Objects at or above this many bytes go up as multipart. */
@@ -123,10 +125,22 @@ const isTimeout = (signal?: AbortSignal) => signal?.aborted === true && (signal.
123
125
  export function s3BlobStore(cfg: S3Config, given: Partial<S3BlobOptions> = {}): BlobStore & BlobSweeper & { checkBucket(signal?: AbortSignal): Promise<void> } {
124
126
  if (!cfg) throw new Error("the s3 blob store needs FOLDRUN_S3_ENDPOINT, FOLDRUN_S3_BUCKET and credentials");
125
127
  const o: S3BlobOptions = { ...s3OptionsFromEnv(), ...given };
126
- const requestDeadline = (bytes: number) => o.requestDeadlineMs + Math.ceil((bytes / o.minBytesPerSec) * 1000);
128
+ // Clamped to the longest timer Node keeps: past 2^31-1 ms it fires after
129
+ // 1 ms instead, which would cut off the complete of a multi-TiB object.
130
+ const requestDeadline = (bytes: number) => Math.min(MAX_TIMER_MS, o.requestDeadlineMs + Math.ceil((bytes / o.minBytesPerSec) * 1000));
127
131
 
128
132
  /** One signed request with the failures of the network turned into
129
- * BlobTransientError, so the retry wrapper above knows what to retry. */
133
+ * BlobTransientError, so the retry wrapper above knows what to retry.
134
+ *
135
+ * Every request carries this driver's own deadline (its floor plus its body
136
+ * at minBytesPerSec) on top of the caller's signal. bounded() leaves a
137
+ * streamed put to the driver, so without it a server that accepts the
138
+ * connection and never answers would hold the single PUT, or a multipart
139
+ * HEAD, list, create or complete, for as long as the caller's signal lets
140
+ * it — forever when there is none. `sizedBy` overrides the bytes the
141
+ * deadline is sized by (a complete, whose small body stands for a whole
142
+ * object the store has to assemble). A GET passes `false`: its signal also
143
+ * bounds reading the body, which is the caller's to bound. */
130
144
  const send = async (
131
145
  what: string,
132
146
  method: Parameters<typeof s3Request>[1],
@@ -136,15 +150,19 @@ export function s3BlobStore(cfg: S3Config, given: Partial<S3BlobOptions> = {}):
136
150
  signal?: AbortSignal,
137
151
  query?: Record<string, string>,
138
152
  mime?: string,
153
+ sizedBy?: number | false,
139
154
  ): Promise<Response> => {
155
+ const ms = requestDeadline(sizedBy === undefined || sizedBy === false ? (body?.length ?? 0) : sizedBy);
156
+ const bound = sizedBy === false ? signal : signal ? AbortSignal.any([signal, AbortSignal.timeout(ms)]) : AbortSignal.timeout(ms);
140
157
  try {
141
- return await s3Request(cfg, method, key, body, mime, extra, signal, query ? { query } : {});
158
+ return await s3Request(cfg, method, key, body, mime, extra, bound, query ? { query } : {});
142
159
  } catch (err) {
143
160
  // A source that fails while it is being sent surfaces from fetch as
144
161
  // "fetch failed" with the real error as its cause. It is not the
145
162
  // network's fault and a retry would read the same bytes.
146
163
  for (let e: unknown = err, i = 0; e && i < 4; e = (e as Error).cause, i++) if (e instanceof BlobSourceError) throw e;
147
164
  if (signal?.aborted && !isTimeout(signal)) throw err; // the caller cancelled
165
+ if (bound?.aborted && isTimeout(bound)) throw new BlobTransientError(`s3 ${what}: no answer within ${ms}ms`);
148
166
  const name = (err as Error)?.name;
149
167
  if (name === "AbortError" || name === "TimeoutError") throw new BlobTransientError(`s3 ${what}: timed out`);
150
168
  const cause = (err as { cause?: { code?: string; message?: string } }).cause;
@@ -162,6 +180,18 @@ export function s3BlobStore(cfg: S3Config, given: Partial<S3BlobOptions> = {}):
162
180
  return new BlobStoreError(msg, res.status, code);
163
181
  };
164
182
  const drain = (res: Response) => res.arrayBuffer().catch(() => {});
183
+ /** A reply's body. The request's deadline still runs while it is read, and
184
+ * a deadline or a dropped connection here is as transient as one before
185
+ * the headers came. */
186
+ const textOf = async (res: Response, what: string): Promise<string> => {
187
+ try {
188
+ return await res.text();
189
+ } catch (err) {
190
+ if ((err as Error)?.name === "TimeoutError") throw new BlobTransientError(`s3 ${what}: timed out reading the reply`);
191
+ if (err instanceof TypeError) throw new BlobTransientError(`s3 ${what}: the reply was cut off (${(err as { cause?: { code?: string } }).cause?.code ?? err.message})`);
192
+ throw err;
193
+ }
194
+ };
165
195
 
166
196
  const headObject = async (key: string, signal?: AbortSignal): Promise<HeadResult | null> => {
167
197
  const res = await send("head", "HEAD", key, undefined, {}, signal);
@@ -207,7 +237,7 @@ export function s3BlobStore(cfg: S3Config, given: Partial<S3BlobOptions> = {}):
207
237
  if (uploadMarker) q["upload-id-marker"] = uploadMarker;
208
238
  const res = await send("list uploads", "GET", "", undefined, {}, signal, q);
209
239
  if (!res.ok) throw await failure(res, "list uploads");
210
- const xml = await res.text();
240
+ const xml = await textOf(res, "list uploads");
211
241
  // The oldest open upload for the key: the one most likely to have parts.
212
242
  const mine = [...xml.matchAll(/<Upload>([\s\S]*?)<\/Upload>/g)]
213
243
  .map((m) => ({ key: unxml(/<Key>([^<]*)<\/Key>/.exec(m[1])?.[1] ?? ""), id: unxml(/<UploadId>([^<]*)<\/UploadId>/.exec(m[1])?.[1] ?? ""), at: Date.parse(/<Initiated>([^<]*)<\/Initiated>/.exec(m[1])?.[1] ?? "") || 0 }))
@@ -234,7 +264,7 @@ export function s3BlobStore(cfg: S3Config, given: Partial<S3BlobOptions> = {}):
234
264
  return null; // NoSuchUpload: it was completed or aborted under us
235
265
  }
236
266
  if (!res.ok) throw await failure(res, "list parts");
237
- const xml = await res.text();
267
+ const xml = await textOf(res, "list parts");
238
268
  for (const m of xml.matchAll(/<Part>([\s\S]*?)<\/Part>/g)) {
239
269
  const n = Number(/<PartNumber>(\d+)<\/PartNumber>/.exec(m[1])?.[1]);
240
270
  const size = Number(/<Size>(\d+)<\/Size>/.exec(m[1])?.[1]);
@@ -268,7 +298,7 @@ export function s3BlobStore(cfg: S3Config, given: Partial<S3BlobOptions> = {}):
268
298
  if (!uploadId || !have) {
269
299
  const res = await send("create upload", "POST", key, undefined, {}, signal, { uploads: "" }, opts.contentType);
270
300
  if (!res.ok) throw await failure(res, "create upload");
271
- uploadId = unxml(/<UploadId>([^<]*)<\/UploadId>/.exec(await res.text())?.[1] ?? "");
301
+ uploadId = unxml(/<UploadId>([^<]*)<\/UploadId>/.exec(await textOf(res, "create upload"))?.[1] ?? "");
272
302
  if (!uploadId) throw new BlobTransientError("s3 create upload: no upload id in the reply");
273
303
  have = new Map();
274
304
  }
@@ -281,6 +311,35 @@ export function s3BlobStore(cfg: S3Config, given: Partial<S3BlobOptions> = {}):
281
311
  // AbortError, which would hide a transient or final cause.
282
312
  let firstError: { err: unknown } | null = null;
283
313
  const both = signal ? AbortSignal.any([signal, inner.signal]) : inner.signal;
314
+
315
+ // Each part is checked against the bytes read for it (the sha256 signed
316
+ // into its PUT, or the md5 a part already in the store must match), but
317
+ // that alone says nothing about the object: a file that changed after the
318
+ // caller hashed it would go up whole and consistent under the OLD content
319
+ // address. So the same reads also feed one sha256 of the whole object,
320
+ // compared with opts.sha256 before the upload is completed. A sha256
321
+ // cannot be put together from the parts' own, so the reads have to reach
322
+ // it in order: each part's hash pass waits for the one before it.
323
+ // Workers take part numbers in order, so chaining their passes keeps it,
324
+ // and the uploads still overlap. A part reused from an earlier attempt is
325
+ // read and hashed like the others, so a resumed upload is covered too.
326
+ const whole = opts.sha256 ? crypto.createHash("sha256") : null;
327
+ let hashed: Promise<unknown> = Promise.resolve();
328
+ const hashPart = (start: number, end: number): Promise<{ sha256: string; md5: string }> => {
329
+ const pass = hashed.then(async () => {
330
+ const sha = crypto.createHash("sha256");
331
+ const md5 = crypto.createHash("md5");
332
+ for await (const chunk of source.read(start, end, both)) {
333
+ sha.update(chunk);
334
+ md5.update(chunk);
335
+ whole?.update(chunk);
336
+ }
337
+ return { sha256: sha.digest("hex"), md5: md5.digest("hex") };
338
+ });
339
+ hashed = pass; // a failed pass fails the ones after it: the upload is over anyway
340
+ return pass;
341
+ };
342
+
284
343
  let next = 1;
285
344
  const worker = async () => {
286
345
  while (!both.aborted) {
@@ -289,8 +348,10 @@ export function s3BlobStore(cfg: S3Config, given: Partial<S3BlobOptions> = {}):
289
348
  const [start, end] = range(n);
290
349
  const len = end - start;
291
350
  // Hash first: the sha256 is signed into the request, the md5 is what a
292
- // part already in the store must match to be trusted.
293
- const h = await hashRange(source, start, end, both);
351
+ // part already in the store must match to be trusted. (No await
352
+ // between taking `n` and queueing its pass: that is what keeps the
353
+ // whole-object hash in order.)
354
+ const h = await hashPart(start, end);
294
355
  const prior = have!.get(n);
295
356
  if (prior && prior.size === len && unquote(prior.etag) === h.md5) {
296
357
  done.set(n, prior.etag);
@@ -302,7 +363,7 @@ export function s3BlobStore(cfg: S3Config, given: Partial<S3BlobOptions> = {}):
302
363
  key,
303
364
  { stream: source.read(start, end, both), length: len, sha256: h.sha256 },
304
365
  {},
305
- AbortSignal.any([both, AbortSignal.timeout(requestDeadline(len))]),
366
+ both, // send() adds the part's deadline, sized by its length
306
367
  { partNumber: String(n), uploadId: id },
307
368
  );
308
369
  if (!res.ok) throw await failure(res, `part ${n}`);
@@ -324,6 +385,14 @@ export function s3BlobStore(cfg: S3Config, given: Partial<S3BlobOptions> = {}):
324
385
  await Promise.allSettled(pool);
325
386
  if (firstError) throw (firstError as { err: unknown }).err;
326
387
 
388
+ // Every part went through hashPart, in order: `whole` is the object the
389
+ // store would assemble. Not the bytes asked for means not this key —
390
+ // a final failure, so the catch below aborts the upload.
391
+ if (whole) {
392
+ const got = whole.digest("hex");
393
+ if (got !== opts.sha256) throw new BlobSourceError(`the bytes for ${key} do not hash to ${opts.sha256} (they hash to ${got}): the source changed after it was hashed`);
394
+ }
395
+
327
396
  const xml =
328
397
  `<CompleteMultipartUpload>` +
329
398
  [...done.entries()]
@@ -331,7 +400,9 @@ export function s3BlobStore(cfg: S3Config, given: Partial<S3BlobOptions> = {}):
331
400
  .map(([n, etag]) => `<Part><PartNumber>${n}</PartNumber><ETag>${etag.replace(/&/g, "&amp;").replace(/</g, "&lt;")}</ETag></Part>`)
332
401
  .join("") +
333
402
  `</CompleteMultipartUpload>`;
334
- const res = await send("complete upload", "POST", key, Buffer.from(xml), { "if-none-match": "*" }, signal, { uploadId: id }, "application/xml");
403
+ // Assembling the parts takes the store longer the bigger the object
404
+ // (AWS warns of minutes), so its deadline is sized by the object.
405
+ const res = await send("complete upload", "POST", key, Buffer.from(xml), { "if-none-match": "*" }, signal, { uploadId: id }, "application/xml", source.size);
335
406
  if (res.status === 412) {
336
407
  // Someone else's identical object won. Ours is not needed.
337
408
  await drain(res);
@@ -348,7 +419,7 @@ export function s3BlobStore(cfg: S3Config, given: Partial<S3BlobOptions> = {}):
348
419
  }
349
420
  if (!res.ok) throw await failure(res, "complete upload");
350
421
  // S3 can answer 200 and put the error in the body.
351
- const text = await res.text();
422
+ const text = await textOf(res, "complete upload");
352
423
  if (/<Error>/.test(text)) {
353
424
  const code = codeOf(text);
354
425
  const msg = `s3 complete upload failed: 200 ${code ?? "error in body"}`;
@@ -382,7 +453,7 @@ export function s3BlobStore(cfg: S3Config, given: Partial<S3BlobOptions> = {}):
382
453
  },
383
454
  async get(key, opts = {}) {
384
455
  assertKey(key);
385
- const res = await send("get", "GET", key, undefined, opts.range ? { range: `bytes=${opts.range.start}-${opts.range.end}` } : {}, opts.signal);
456
+ const res = await send("get", "GET", key, undefined, opts.range ? { range: `bytes=${opts.range.start}-${opts.range.end}` } : {}, opts.signal, undefined, undefined, false);
386
457
  if (res.status === 404) {
387
458
  const text = await res.text().catch(() => "");
388
459
  // A GET carries the reason a HEAD cannot: the bucket may be the thing that is missing.
@@ -425,7 +496,7 @@ export function s3BlobStore(cfg: S3Config, given: Partial<S3BlobOptions> = {}):
425
496
  if (uploadMarker) q["upload-id-marker"] = uploadMarker;
426
497
  const res = await send("list uploads", "GET", "", undefined, {}, signal, q);
427
498
  if (!res.ok) throw await failure(res, "list uploads");
428
- const xml = await res.text();
499
+ const xml = await textOf(res, "list uploads");
429
500
  for (const m of xml.matchAll(/<Upload>([\s\S]*?)<\/Upload>/g)) {
430
501
  const key = unxml(/<Key>([^<]*)<\/Key>/.exec(m[1])?.[1] ?? "");
431
502
  const id = unxml(/<UploadId>([^<]*)<\/UploadId>/.exec(m[1])?.[1] ?? "");
@@ -447,7 +518,7 @@ export function s3BlobStore(cfg: S3Config, given: Partial<S3BlobOptions> = {}):
447
518
  const q: Record<string, string> = { "list-type": "2", prefix: prefix.endsWith("/") ? prefix : `${prefix}/`, ...(token ? { "continuation-token": token } : {}) };
448
519
  const res = await send("list", "GET", "", undefined, {}, opts.signal, q);
449
520
  if (!res.ok) throw await failure(res, "list");
450
- const xml = await res.text();
521
+ const xml = await textOf(res, "list");
451
522
  for (const c of xml.matchAll(/<Contents>([\s\S]*?)<\/Contents>/g)) {
452
523
  const key = xmlText(c[1], "Key");
453
524
  const size = Number(xmlText(c[1], "Size"));
@@ -464,7 +535,7 @@ export function s3BlobStore(cfg: S3Config, given: Partial<S3BlobOptions> = {}):
464
535
  const q: Record<string, string> = { "list-type": "2", prefix: "t/", delimiter: "/", ...(token ? { "continuation-token": token } : {}) };
465
536
  const res = await send("list", "GET", "", undefined, {}, opts.signal, q);
466
537
  if (!res.ok) throw await failure(res, "list");
467
- const xml = await res.text();
538
+ const xml = await textOf(res, "list");
468
539
  for (const c of xml.matchAll(/<CommonPrefixes>\s*<Prefix>([^<]*)<\/Prefix>/g)) out.push(unxml(c[1]).replace(/^t\//, "").replace(/\/$/, ""));
469
540
  token = /<IsTruncated>true<\/IsTruncated>/.test(xml) ? (xmlText(xml, "NextContinuationToken") ?? undefined) : undefined;
470
541
  } while (token);
package/src/translator.ts CHANGED
@@ -615,6 +615,11 @@ export class ToolCallExtras {
615
615
  get size(): number {
616
616
  return this.byId.size;
617
617
  }
618
+ /** Every kept call's extras, oldest first — for a caller that keeps them
619
+ * between separate requests (the LLM gateway, per account). */
620
+ entries(): [string, Json][] {
621
+ return [...this.byId.entries()];
622
+ }
618
623
  }
619
624
 
620
625
  export class StreamTranslator {
@@ -824,6 +829,10 @@ export class ResponsesStreamTranslator {
824
829
  private incomplete: string | null = null;
825
830
  private sawTool = false;
826
831
  private sawRefusal = false;
832
+ /** The stream's last word: completed or incomplete (an answer), or the
833
+ * provider's error. None at all means it was cut off. */
834
+ private terminal: "done" | "failed" | null = null;
835
+ private failure: string | null = null;
827
836
  private id = `msg_${crypto.randomBytes(8).toString("hex")}`;
828
837
  private readonly model: string;
829
838
  constructor(model: string) {
@@ -925,6 +934,18 @@ export class ResponsesStreamTranslator {
925
934
  if (u) this.usage = anthropicUsage(u, "responses");
926
935
  const reason = (r.incomplete_details as Json | undefined)?.reason;
927
936
  if (typeof reason === "string") this.incomplete = reason;
937
+ if (type === "response.failed") {
938
+ // A failure is not an answer (Codex review, 10 Nov 2026): it was
939
+ // ended as a normal stop, so the caller read a failed reply as done.
940
+ this.terminal = "failed";
941
+ const err = (r.error as Json | undefined) ?? {};
942
+ this.failure = typeof err.message === "string" ? err.message : "the provider reported the response failed";
943
+ } else this.terminal = "done";
944
+ return out;
945
+ }
946
+ if (type === "error") {
947
+ this.terminal = "failed";
948
+ this.failure = typeof ev.message === "string" ? ev.message : "the provider sent an error mid-stream";
928
949
  return out;
929
950
  }
930
951
  return out;
@@ -939,6 +960,13 @@ export class ResponsesStreamTranslator {
939
960
  }
940
961
  out.push(this.event("content_block_stop", { type: "content_block_stop", index: entry.block }));
941
962
  }
963
+ // Failed, or cut off before any last word: an Anthropic error event, the
964
+ // shape a client reads as a failed request, never a normal stop.
965
+ if (this.terminal !== "done") {
966
+ const message = this.terminal === "failed" ? this.failure! : "the provider's stream ended before the response finished";
967
+ out.push(this.event("error", { type: "error", error: { type: "api_error", message } }));
968
+ return out;
969
+ }
942
970
  const reason = responsesStop(this.incomplete, this.sawTool, this.sawRefusal);
943
971
  out.push(
944
972
  this.event("message_delta", {