browser-model-manager 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/LICENSE +21 -0
  3. package/PROVENANCE.json +16 -0
  4. package/README.md +607 -2
  5. package/THIRD_PARTY_NOTICES +4 -0
  6. package/dist/acquisition/grants.d.ts +31 -0
  7. package/dist/acquisition/grants.js +75 -0
  8. package/dist/acquisition/index.d.ts +4 -0
  9. package/dist/acquisition/index.js +6 -0
  10. package/dist/acquisition/output.d.ts +12 -0
  11. package/dist/acquisition/output.js +19 -0
  12. package/dist/acquisition/phases.d.ts +3 -0
  13. package/dist/acquisition/phases.js +64 -0
  14. package/dist/acquisition/progress.d.ts +29 -0
  15. package/dist/acquisition/progress.js +124 -0
  16. package/dist/acquisition/slots.d.ts +35 -0
  17. package/dist/acquisition/slots.js +296 -0
  18. package/dist/cache/index.d.ts +3 -0
  19. package/dist/cache/index.js +4 -0
  20. package/dist/cache/model-cache.d.ts +152 -0
  21. package/dist/cache/model-cache.js +1585 -0
  22. package/dist/cache/sha256.d.ts +11 -0
  23. package/dist/cache/sha256.js +97 -0
  24. package/dist/cache/shard-store.d.ts +89 -0
  25. package/dist/cache/shard-store.js +204 -0
  26. package/dist/contracts/budgets.d.ts +41 -0
  27. package/dist/contracts/budgets.js +48 -0
  28. package/dist/contracts/errors.d.ts +43 -0
  29. package/dist/contracts/errors.js +2 -0
  30. package/dist/contracts/grant.d.ts +47 -0
  31. package/dist/contracts/grant.js +44 -0
  32. package/dist/contracts/index.d.ts +6 -0
  33. package/dist/contracts/index.js +7 -0
  34. package/dist/contracts/leases.d.ts +20 -0
  35. package/dist/contracts/leases.js +14 -0
  36. package/dist/contracts/lifecycle.d.ts +88 -0
  37. package/dist/contracts/lifecycle.js +12 -0
  38. package/dist/contracts/manifest.d.ts +95 -0
  39. package/dist/contracts/manifest.js +174 -0
  40. package/dist/handles/cross-tab.d.ts +16 -0
  41. package/dist/handles/cross-tab.js +29 -0
  42. package/dist/handles/handle.d.ts +24 -0
  43. package/dist/handles/handle.js +93 -0
  44. package/dist/handles/index.d.ts +3 -0
  45. package/dist/handles/index.js +4 -0
  46. package/dist/handles/leases.d.ts +45 -0
  47. package/dist/handles/leases.js +103 -0
  48. package/dist/index.d.ts +5 -0
  49. package/dist/index.js +7 -0
  50. package/package.json +43 -4
  51. package/schema/model-manifest.v1.schema.json +215 -0
@@ -0,0 +1,1585 @@
1
+ // The model cache: acquisition, verification and storage of pinned model assets in Cache Storage and OPFS shards.
2
+ // Moved from the candidate's src/Next/Assets/model-cache.mjs (classic a42829b) without behaviour change (fm-eulc);
3
+ // the comments are the candidate's. Acquisition primitives (fm-fr9s): every transfer is under an app-supplied grant
4
+ // and inside the shared aggregate slot budget, retries alternate with configured origins, a silent connection is
5
+ // abandoned, and the asset deadline counts silence, not size (the candidate's 942c807).
6
+ import { chargeGrant, grantAsset, GrantRefused } from '../acquisition/grants.js';
7
+ import { createAcquisitionSlots, PRIORITY_ORDER, slotCount, } from '../acquisition/slots.js';
8
+ import { acquisitionPhase } from '../acquisition/phases.js';
9
+ import { ACQUISITION_CHUNK_MAX_BYTES, acquisitionMemoryClass } from '../contracts/budgets.js';
10
+ import { Sha256 } from './sha256.js';
11
+ import { browserGlobals, openShardStore, } from './shard-store.js';
12
+ export const MODEL_CACHE_NAME = 'checkface-model-blobs-v1'; // Never app-versioned or age-purged.
13
+ /** A real storage-quota refusal, separate from execution/provider capability.
14
+ * The DOM name and cause remain available to existing browser-storage callers;
15
+ * `error` is the structured-clone-safe manager result for app/worker boundaries.
16
+ */
17
+ export class CacheQuotaExceeded extends Error {
18
+ error;
19
+ constructor(requiredBytes, cause) {
20
+ const message = 'Not enough browser storage to save this model. Free some storage and try again.';
21
+ super(message, { cause });
22
+ this.name = 'QuotaExceededError';
23
+ this.error = { code: 'quota', requiredBytes, message };
24
+ }
25
+ }
26
+ const aborted = () => new DOMException('Asset acquisition cancelled', 'AbortError');
27
+ const localError = (message, local) => Object.assign(new Error(message), { local });
28
+ const check = (signal) => {
29
+ if (signal?.aborted)
30
+ throw signal.reason || aborted();
31
+ };
32
+ export function validateAsset(asset) {
33
+ if (!asset ||
34
+ !/^[a-f0-9]{64}$/.test(asset.sha256) ||
35
+ !Number.isSafeInteger(asset.size) ||
36
+ asset.size < 0)
37
+ throw new TypeError('Asset requires lowercase SHA-256 and exact nonnegative byte size');
38
+ const url = new URL(asset.url);
39
+ if (url.protocol !== 'https:' || url.username || url.password)
40
+ throw new TypeError('Asset acquisition requires an HTTPS URL without embedded credentials');
41
+ let chunks;
42
+ if (asset.chunks !== undefined) {
43
+ if (!Array.isArray(asset.chunks) || !asset.chunks.length || asset.chunks.length > 256)
44
+ throw new TypeError('Invalid asset chunks');
45
+ chunks = asset.chunks.map((part) => {
46
+ if (part.chunks !== undefined || part.size <= 0 || part.size > 16 * 1024 * 1024)
47
+ throw new TypeError('Invalid asset chunk');
48
+ return validateAsset(part);
49
+ });
50
+ if (chunks.reduce((sum, part) => sum + part.size, 0) !== asset.size)
51
+ throw new TypeError('Asset chunk sizes do not match');
52
+ Object.freeze(chunks);
53
+ }
54
+ return Object.freeze({
55
+ sha256: asset.sha256,
56
+ size: asset.size,
57
+ url: url.href,
58
+ ...(chunks ? { chunks } : {}),
59
+ });
60
+ }
61
+ const PIECE_BYTES = 256 * 1024;
62
+ const SHARD_UNIT_LIMIT = ACQUISITION_CHUNK_MAX_BYTES; // larger unchunked assets stream through Cache Storage
63
+ const hex = (buffer) => Array.from(new Uint8Array(buffer), (x) => x.toString(16).padStart(2, '0')).join('');
64
+ /** Incremental inputs also share the hash phase; never hand it an oversized view. */
65
+ async function updateHash(hash, bytes, signal) {
66
+ for (let at = 0; at < bytes.byteLength; at += ACQUISITION_CHUNK_MAX_BYTES) {
67
+ const piece = bytes.subarray(at, at + ACQUISITION_CHUNK_MAX_BYTES);
68
+ await acquisitionPhase('hash', () => hash.update(piece), signal);
69
+ }
70
+ }
71
+ const finishHash = (hash, signal) => acquisitionPhase('hash', () => hash.hex(), signal);
72
+ /** Platform SHA-256 copies its input. Larger unchunked assets keep the existing incremental
73
+ * whole-asset digest instead of creating a native workspace larger than the frozen ceiling. */
74
+ async function digestHex(bytes, signal) {
75
+ if (bytes.byteLength <= ACQUISITION_CHUNK_MAX_BYTES && globalThis.crypto?.subtle)
76
+ return acquisitionPhase('hash', async () => hex(await globalThis.crypto.subtle.digest('SHA-256', bytes)), signal);
77
+ const hash = new Sha256();
78
+ await updateHash(hash, bytes, signal);
79
+ return finishHash(hash, signal);
80
+ }
81
+ /** A non-200 answer; `transient` marks the statuses worth asking again (server faults, rate limits).
82
+ * The message is shown to the visitor as it is, so it says what happened and what to do. Model files are immutable
83
+ * and named by digest, so one that is gone (404, 410) belongs to a version the site no longer serves: an open tab
84
+ * that loaded before an update asks for it. That is not retried and no other digest is tried in its place; `reload`
85
+ * tells the page the remedy is a reload, which loads the current version (fm-fy2.14). */
86
+ function downloadRefused(response) {
87
+ void response.body?.cancel().catch(() => { });
88
+ const status = response.type === 'opaque' ? 'opaque response' : `HTTP ${response.status}`;
89
+ const transient = response.status >= 500 || response.status === 429 || response.status === 408;
90
+ const reload = response.status === 404 || response.status === 410;
91
+ const error = new Error(transient
92
+ ? `The model download server had a temporary fault (${status}). Parts already downloaded are kept: try again in a few minutes.`
93
+ : reload
94
+ ? `A model file could not be downloaded (${status}): this page is older than the site, which has been updated since it loaded. Reload the page to continue.`
95
+ : `A model file could not be downloaded (${status}).`);
96
+ return Object.assign(error, { status: response.status, transient, reload });
97
+ }
98
+ // 20 October: one Cloudflare edge answered HTTP 500 for a single 9 MB encoder chunk for twenty-five
99
+ // minutes (part-033, then part-091; the same files were 200 everywhere else), and every attempt
100
+ // failed the whole photo on that one chunk out of a hundred. A server fault or a dropped connection
101
+ // is asked again after a pause, under a fresh query string so neither the browser nor the edge
102
+ // replays the bad answer. When a mirror is known (models.facemorph.me, R2: separate storage), every
103
+ // other retry goes there instead, and any failure of the mirror just moves on to the next attempt.
104
+ // Bytes are checked against the pin wherever they come from, so a retry cannot admit wrong ones.
105
+ export const CHUNK_RETRY_DELAYS_MS = Object.freeze([1000, 4000, 10000, 20000]);
106
+ const retryable = (error) => error?.transient === true || error instanceof TypeError; // fetch reports a dropped connection as TypeError
107
+ const pauseFor = (ms, signal) => new Promise((resolve, reject) => {
108
+ const done = () => {
109
+ clearTimeout(timer);
110
+ reject(signal.reason || aborted());
111
+ };
112
+ const timer = setTimeout(() => {
113
+ signal?.removeEventListener('abort', done);
114
+ resolve();
115
+ }, ms);
116
+ signal?.addEventListener('abort', done, { once: true });
117
+ });
118
+ /** Time only pending network operations, never hashing, storage backpressure or aggregate-slot waits.
119
+ * A separate controller keeps the timeout attached to the actual fetch, including handle repairs.
120
+ * Zero read-ahead here leaves local consumers in charge of when the next network read begins.
121
+ */
122
+ function networkDeadline(download, timeoutMs) {
123
+ return async (part, signal) => {
124
+ const controller = new AbortController();
125
+ const relay = () => controller.abort(signal.reason || aborted());
126
+ signal.addEventListener('abort', relay, { once: true });
127
+ if (signal.aborted)
128
+ relay();
129
+ let reader;
130
+ let cancellation;
131
+ const cancelReader = (reason) => {
132
+ if (!reader)
133
+ return Promise.resolve();
134
+ return (cancellation ??= reader
135
+ .cancel(reason)
136
+ .catch(() => { })
137
+ .finally(() => reader.releaseLock()));
138
+ };
139
+ const cancel = () => {
140
+ void cancelReader(controller.signal.reason || aborted());
141
+ };
142
+ controller.signal.addEventListener('abort', cancel, { once: true });
143
+ const cleanup = () => {
144
+ signal.removeEventListener('abort', relay);
145
+ controller.signal.removeEventListener('abort', cancel);
146
+ };
147
+ const wait = async (operation) => {
148
+ check(controller.signal);
149
+ let interrupt;
150
+ const cancelled = new Promise((_resolve, reject) => {
151
+ interrupt = () => reject(controller.signal.reason || aborted());
152
+ controller.signal.addEventListener('abort', interrupt, { once: true });
153
+ });
154
+ const timer = setTimeout(() => controller.abort(new DOMException('Asset acquisition timed out', 'TimeoutError')), timeoutMs);
155
+ try {
156
+ return await Promise.race([operation(), cancelled]);
157
+ }
158
+ catch (error) {
159
+ check(controller.signal); // Native fetch cancellation can substitute its own generic AbortError.
160
+ throw error;
161
+ }
162
+ finally {
163
+ clearTimeout(timer);
164
+ controller.signal.removeEventListener('abort', interrupt);
165
+ }
166
+ };
167
+ try {
168
+ const body = await wait(() => download(part, controller.signal));
169
+ if (!body) {
170
+ cleanup();
171
+ return null;
172
+ }
173
+ reader = body.getReader();
174
+ return new ReadableStream({
175
+ async pull(output) {
176
+ try {
177
+ const result = await wait(() => reader.read());
178
+ check(controller.signal);
179
+ if (result.done) {
180
+ cleanup();
181
+ reader.releaseLock();
182
+ output.close();
183
+ }
184
+ else
185
+ output.enqueue(result.value);
186
+ }
187
+ catch (error) {
188
+ cleanup();
189
+ output.error(error);
190
+ await cancelReader(error);
191
+ }
192
+ },
193
+ cancel(reason) {
194
+ cleanup();
195
+ controller.abort(reason || aborted());
196
+ return cancelReader(reason);
197
+ },
198
+ }, { highWaterMark: 0 });
199
+ }
200
+ catch (error) {
201
+ cleanup();
202
+ controller.abort(error);
203
+ throw error;
204
+ }
205
+ };
206
+ }
207
+ /** The same path on another origin. */
208
+ const onOrigin = (url, origin) => new URL(new URL(url).pathname, origin).href;
209
+ async function fetchVerifiedChunk(part, download, signal, transfer, delays = CHUNK_RETRY_DELAYS_MS, alternates = [], stallMs = CHUNK_STALL_MS) {
210
+ let first;
211
+ for (let attempt = 0;; attempt++) {
212
+ const fromMirror = alternates.length > 0 && attempt % 2 === 1;
213
+ try {
214
+ const url = fromMirror
215
+ ? onOrigin(part.url, alternates[((attempt - 1) / 2) % alternates.length])
216
+ : attempt
217
+ ? Object.assign(new URL(part.url), { search: `retry=${attempt}` }).href
218
+ : part.url;
219
+ return await fetchChunkOnce(attempt ? { ...part, url } : part, download, signal, transfer, stallMs);
220
+ }
221
+ catch (error) {
222
+ check(signal);
223
+ if (error instanceof GrantRefused)
224
+ throw error; // more attempts would need more than was approved
225
+ first ??= error; // the site's own answer is the one worth reporting
226
+ if (attempt >= delays.length || !(fromMirror || retryable(error)))
227
+ throw fromMirror ? first : error;
228
+ await pauseFor(delays[attempt], signal);
229
+ }
230
+ }
231
+ }
232
+ // 24 October (fm-vf9l, device lab): a connection that goes silent without a reset (a laptop waking from sleep, a
233
+ // changed network, a dead NAT mapping) never fails a fetch. An encoder shard sat 106 s without a byte and nothing on
234
+ // the page noticed; only the asset deadline would have ended it, and that fails the whole download. An attempt that
235
+ // receives nothing for `stallMs` is abandoned and asked again like a dropped connection, so the next try opens a
236
+ // fresh request (and every other try goes to the mirror).
237
+ export const CHUNK_STALL_MS = 30000;
238
+ const stalledError = () => Object.assign(new Error('The model download stopped receiving data. Parts already downloaded are kept: try again in a few minutes.'), { transient: true, stalled: true });
239
+ /** One pinned chunk, fully read into a buffer of exactly its declared size and checked by the platform digest. */
240
+ async function fetchChunkOnce(part, download, signal, transfer, stallMs) {
241
+ // Every byte of every attempt counts against the grant; the attempt reserves its chunk before asking.
242
+ const charge = chargeGrant(transfer.payer(), part.sha256, part.size);
243
+ const attempt = new AbortController();
244
+ const stall = stalledError();
245
+ const relay = () => attempt.abort(signal.reason || aborted());
246
+ if (signal.aborted)
247
+ relay();
248
+ else
249
+ signal.addEventListener('abort', relay, { once: true });
250
+ let timer;
251
+ const quiet = () => {
252
+ clearTimeout(timer);
253
+ timer = setTimeout(() => attempt.abort(stall), stallMs);
254
+ };
255
+ const out = new Uint8Array(part.size);
256
+ let at = 0;
257
+ try {
258
+ quiet();
259
+ const body = await download(part, attempt.signal);
260
+ if (!body)
261
+ throw new Error('Asset response has no readable body');
262
+ const reader = body.getReader();
263
+ try {
264
+ for (;;) {
265
+ const { value, done } = await reader.read();
266
+ check(attempt.signal);
267
+ quiet();
268
+ if (done)
269
+ break;
270
+ charge.received(value.byteLength);
271
+ if (at + value.byteLength > part.size)
272
+ throw new Error('Asset exceeds declared size');
273
+ out.set(value, at);
274
+ at += value.byteLength;
275
+ }
276
+ }
277
+ catch (error) {
278
+ void reader.cancel(error).catch(() => { });
279
+ throw error;
280
+ }
281
+ finally {
282
+ reader.releaseLock();
283
+ }
284
+ }
285
+ catch (error) {
286
+ attempt.abort(error); // stop unfinished I/O on failure, not a fully consumed response
287
+ check(signal); // the caller's own cancellation wins over anything below
288
+ throw attempt.signal.reason === stall ? stall : error;
289
+ }
290
+ finally {
291
+ clearTimeout(timer);
292
+ signal.removeEventListener('abort', relay);
293
+ charge.settle();
294
+ }
295
+ if (at !== part.size)
296
+ throw new Error('Asset integrity mismatch');
297
+ const digest = await digestHex(out, signal);
298
+ check(signal);
299
+ if (digest !== part.sha256)
300
+ throw new Error('Asset integrity mismatch');
301
+ return out;
302
+ }
303
+ /** Validates configured alternate origins: each an HTTPS origin, exactly. */
304
+ function validateOrigins(origins) {
305
+ for (const origin of origins) {
306
+ const url = new URL(origin);
307
+ if (url.protocol !== 'https:' || url.origin !== origin)
308
+ throw new TypeError('alternateOrigins must be HTTPS origins (scheme, host and port only)');
309
+ }
310
+ return Object.freeze([...origins]);
311
+ }
312
+ // Opaque origins cannot use Web Locks. Serialize the bounded chunk workspace in this realm
313
+ // when the browser cannot provide cross-realm coordination, rather than admitting every caller.
314
+ const localUncachedSlots = (() => {
315
+ let busy = false;
316
+ const waiting = [];
317
+ const pump = () => {
318
+ if (busy)
319
+ return;
320
+ const next = waiting.shift();
321
+ if (!next)
322
+ return;
323
+ next.signal.removeEventListener('abort', next.cancel);
324
+ if (next.signal.aborted) {
325
+ next.reject(next.signal.reason || aborted());
326
+ pump();
327
+ return;
328
+ }
329
+ busy = true;
330
+ let released = false;
331
+ next.resolve(() => {
332
+ if (released)
333
+ return;
334
+ released = true;
335
+ busy = false;
336
+ pump();
337
+ });
338
+ };
339
+ return {
340
+ count: 1,
341
+ take(_priority, signal) {
342
+ check(signal);
343
+ return new Promise((resolve, reject) => {
344
+ const next = {
345
+ signal,
346
+ resolve,
347
+ reject,
348
+ cancel() {
349
+ const at = waiting.indexOf(next);
350
+ if (at >= 0)
351
+ waiting.splice(at, 1);
352
+ reject(signal.reason || aborted());
353
+ },
354
+ };
355
+ signal.addEventListener('abort', next.cancel, { once: true });
356
+ waiting.push(next);
357
+ pump();
358
+ });
359
+ },
360
+ };
361
+ })();
362
+ function uncachedBrowserSlots() {
363
+ try {
364
+ const locks = browserGlobals.navigator?.locks;
365
+ if (!locks)
366
+ return localUncachedSlots;
367
+ const native = createAcquisitionSlots({
368
+ locks,
369
+ count: slotCount(acquisitionMemoryClass(browserGlobals.navigator?.deviceMemory)),
370
+ });
371
+ return {
372
+ count: native.count,
373
+ async take(priority, signal) {
374
+ try {
375
+ return await native.take(priority, signal);
376
+ }
377
+ catch (error) {
378
+ check(signal);
379
+ if (error?.name !== 'SecurityError')
380
+ throw error;
381
+ return localUncachedSlots.take(priority, signal);
382
+ }
383
+ },
384
+ };
385
+ }
386
+ catch (error) {
387
+ if (error?.name !== 'SecurityError')
388
+ throw error;
389
+ return localUncachedSlots;
390
+ }
391
+ }
392
+ /** Returns one verified asset without reading or writing any persistent storage.
393
+ * The caller owns its lifetime. Explicit JS model buffers are one final buffer plus one
394
+ * sequential verified chunk, never an asset map or the encoder's complete shard set. Platform
395
+ * SHA-256 may additionally use native workspace for its input (a whole unchunked asset).
396
+ * All bytes, including
397
+ * failed attempts, spend the supplied grant; a cache failure does not replenish that grant.
398
+ */
399
+ export async function acquireUncachedBytes(input, options, { fetcher = globalThis.fetch, timeoutMs = 300000, stallMs = CHUNK_STALL_MS, retryDelaysMs = CHUNK_RETRY_DELAYS_MS, alternateOrigins = [], slots = uncachedBrowserSlots(), report = () => { }, } = {}) {
400
+ const asset = validateAsset(input);
401
+ const { grant, owner, signal } = options ?? {};
402
+ const permission = grantAsset(grant, owner, asset.sha256, asset.size);
403
+ check(signal);
404
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0 || !Number.isFinite(stallMs) || stallMs <= 0)
405
+ throw new TypeError('Invalid uncached acquisition settings');
406
+ const alternates = validateOrigins(alternateOrigins);
407
+ const controller = new AbortController();
408
+ const relay = () => controller.abort(signal?.reason || aborted());
409
+ signal?.addEventListener('abort', relay, { once: true });
410
+ const emit = (event) => {
411
+ try {
412
+ report(event);
413
+ }
414
+ catch {
415
+ /* observers cannot break acquisition */
416
+ }
417
+ };
418
+ const transfer = { payer: () => grant, priority: () => permission.priority };
419
+ let completed = 0;
420
+ const download = networkDeadline(async (part, attemptSignal) => {
421
+ const response = await fetcher(part.url, {
422
+ signal: attemptSignal,
423
+ credentials: 'omit',
424
+ cache: 'default',
425
+ mode: 'cors',
426
+ });
427
+ check(attemptSignal);
428
+ if (!response.ok || response.status !== 200 || response.type === 'opaque')
429
+ throw downloadRefused(response);
430
+ return response.body
431
+ ? counted(response.body, part, (event) => emit({
432
+ ...event,
433
+ sha256: asset.sha256,
434
+ loaded: completed + Number(event['loaded']),
435
+ bytes: asset.size,
436
+ }))
437
+ : null;
438
+ }, timeoutMs);
439
+ try {
440
+ emit({ status: 'downloading', sha256: asset.sha256 });
441
+ const out = asset.chunks ? new Uint8Array(asset.size) : null;
442
+ const parentHash = asset.chunks ? new Sha256() : null;
443
+ for (const part of asset.chunks ?? [asset]) {
444
+ const release = slots ? await slots.take(permission.priority, controller.signal) : () => { };
445
+ try {
446
+ check(controller.signal);
447
+ const bytes = await fetchVerifiedChunk(part, download, controller.signal, transfer, retryDelaysMs, alternates, stallMs);
448
+ if (!out) {
449
+ emit({ status: 'verified', sha256: asset.sha256, bytes: asset.size });
450
+ return bytes;
451
+ }
452
+ out.set(bytes, completed);
453
+ await updateHash(parentHash, bytes, controller.signal);
454
+ completed += bytes.byteLength;
455
+ emit({ status: 'progress', sha256: asset.sha256, loaded: completed, bytes: asset.size });
456
+ }
457
+ finally {
458
+ release();
459
+ }
460
+ }
461
+ check(controller.signal);
462
+ if (!out ||
463
+ completed !== asset.size ||
464
+ (await finishHash(parentHash, controller.signal)) !== asset.sha256)
465
+ throw new Error('Asset integrity mismatch');
466
+ check(controller.signal);
467
+ emit({ status: 'verified', sha256: asset.sha256, bytes: asset.size });
468
+ return out;
469
+ }
470
+ finally {
471
+ signal?.removeEventListener('abort', relay);
472
+ }
473
+ }
474
+ // Runs with backpressure; errors before EOF prevent Cache.put from committing.
475
+ function verifiedStream(body, asset, signal, onFailure) {
476
+ if (!body)
477
+ throw new Error('Asset response has no readable body');
478
+ const reader = body.getReader();
479
+ const hash = new Sha256();
480
+ let size = 0;
481
+ let terminal = false;
482
+ let streamController;
483
+ const cleanup = () => {
484
+ terminal = true;
485
+ signal.removeEventListener('abort', onAbort);
486
+ };
487
+ const onAbort = () => {
488
+ if (terminal)
489
+ return;
490
+ const reason = signal.reason || aborted();
491
+ cleanup();
492
+ onFailure?.(reason);
493
+ streamController.error(reason);
494
+ void reader.cancel(reason).catch(() => { });
495
+ };
496
+ return new ReadableStream({
497
+ start(controller) {
498
+ streamController = controller;
499
+ signal.addEventListener('abort', onAbort, { once: true });
500
+ if (signal.aborted)
501
+ onAbort();
502
+ },
503
+ async pull(controller) {
504
+ try {
505
+ check(signal);
506
+ const { value, done } = await reader.read();
507
+ check(signal);
508
+ if (done) {
509
+ if (size !== asset.size || (await finishHash(hash, signal)) !== asset.sha256)
510
+ throw new Error('Asset integrity mismatch');
511
+ cleanup();
512
+ controller.close();
513
+ return;
514
+ }
515
+ size += value.byteLength;
516
+ if (size > asset.size)
517
+ throw new Error('Asset exceeds declared size');
518
+ await updateHash(hash, value, signal);
519
+ controller.enqueue(value);
520
+ }
521
+ catch (error) {
522
+ if (!terminal) {
523
+ cleanup();
524
+ onFailure?.(error);
525
+ controller.error(error);
526
+ }
527
+ void reader.cancel(error).catch(() => { });
528
+ }
529
+ },
530
+ cancel(reason) {
531
+ cleanup();
532
+ return reader.cancel(reason);
533
+ },
534
+ });
535
+ }
536
+ /**
537
+ * Counts bytes on their way past so an observer can drive a real progress bar. The 158 MB
538
+ * asset used to report {loaded:0} and then {loaded:size}: the bar sat at zero for minutes and
539
+ * then jumped. Ticks are coalesced so a large download costs a bounded number of events.
540
+ */
541
+ export const PROGRESS_INTERVAL_BYTES = 1024 * 1024;
542
+ function counted(body, asset, emit) {
543
+ const reader = body.getReader();
544
+ let seen = 0;
545
+ let announced = 0;
546
+ return new ReadableStream({
547
+ async pull(controller) {
548
+ const { value, done } = await reader.read();
549
+ if (done) {
550
+ controller.close();
551
+ return;
552
+ }
553
+ seen += value.byteLength;
554
+ if (seen - announced >= PROGRESS_INTERVAL_BYTES) {
555
+ announced = seen;
556
+ emit({
557
+ status: 'progress',
558
+ sha256: asset.sha256,
559
+ loaded: Math.min(seen, asset.size),
560
+ bytes: asset.size,
561
+ });
562
+ }
563
+ controller.enqueue(value);
564
+ },
565
+ cancel(reason) {
566
+ return reader.cancel(reason);
567
+ },
568
+ });
569
+ }
570
+ /** Counts a body's bytes against an attempt's grant charge as they pass. */
571
+ function charged(body, charge) {
572
+ if (!body)
573
+ return body;
574
+ const reader = body.getReader();
575
+ return new ReadableStream({
576
+ async pull(controller) {
577
+ try {
578
+ const { value, done } = await reader.read();
579
+ if (done)
580
+ return controller.close();
581
+ charge.received(value.byteLength);
582
+ controller.enqueue(value);
583
+ }
584
+ catch (error) {
585
+ controller.error(error);
586
+ void reader.cancel(error).catch(() => { });
587
+ }
588
+ },
589
+ cancel(reason) {
590
+ return reader.cancel(reason);
591
+ },
592
+ });
593
+ }
594
+ /**
595
+ * Small JSON records sharing the asset store's namespace but keyed by their own identity rather
596
+ * than asset bytes: verified-asset markers (C-05) and canary qualification records (C-03). A
597
+ * record that fails to parse or read is dropped, never fatal — the caller re-proves instead.
598
+ */
599
+ export function createRecordAccess(store) {
600
+ return {
601
+ async get(key) {
602
+ try {
603
+ const response = await store.get(key);
604
+ if (!response)
605
+ return undefined;
606
+ const record = await response.json();
607
+ return record && typeof record === 'object'
608
+ ? record
609
+ : undefined;
610
+ }
611
+ catch {
612
+ return undefined;
613
+ }
614
+ },
615
+ async put(key, record) {
616
+ await store.put(key, new Response(JSON.stringify(record), { headers: { 'Content-Type': 'application/json' } }));
617
+ },
618
+ async remove(key) {
619
+ await store.remove(key);
620
+ },
621
+ };
622
+ }
623
+ /** Store contract: get(hash) -> fresh Response|undefined; put(hash, Response)
624
+ * MUST consume the stream and commit atomically only after successful EOF;
625
+ * remove(hash) removes only that corrupt identity. Never expose partial writes.
626
+ * Observers receive hashes/status only (no URLs or authentication material).
627
+ */
628
+ export function createModelCache({ store, shards = null, fetcher = globalThis.fetch, locks, timeoutMs = 300000, stallMs = CHUNK_STALL_MS, maxConcurrent = 2, readAhead = 2, retryDelaysMs = CHUNK_RETRY_DELAYS_MS, alternateOrigins = [], slots = null, report = () => { }, }) {
629
+ if (!store ||
630
+ !Number.isFinite(timeoutMs) ||
631
+ timeoutMs <= 0 ||
632
+ !Number.isFinite(stallMs) ||
633
+ stallMs <= 0 ||
634
+ !Number.isInteger(maxConcurrent) ||
635
+ maxConcurrent < 1 ||
636
+ !Number.isInteger(readAhead) ||
637
+ readAhead < 1 ||
638
+ readAhead > 8)
639
+ throw new TypeError('Invalid cache settings');
640
+ const alternates = validateOrigins(alternateOrigins);
641
+ /** Holds one aggregate slot for `run`; no slots configured admits at once. */
642
+ const inSlot = async (transfer, signal, run) => {
643
+ const release = slots ? await slots.take(transfer.priority(), signal) : () => { };
644
+ try {
645
+ return await run();
646
+ }
647
+ finally {
648
+ release();
649
+ }
650
+ };
651
+ const chunk = (unit, signal, transfer) => fetchVerifiedChunk(unit, fetchBody, signal, transfer, retryDelaysMs, alternates, stallMs);
652
+ const pending = new Map();
653
+ const queue = [];
654
+ let active = 0;
655
+ // Identities this cache has seen stored (saved, retained, or read locally): an absent one is then evicted.
656
+ const stored = new Set();
657
+ const emit = (event) => {
658
+ if (event.status === 'saved' || event.status === 'retained')
659
+ stored.add(event.sha256);
660
+ try {
661
+ report(event);
662
+ }
663
+ catch {
664
+ /* observers cannot break storage */
665
+ }
666
+ };
667
+ const records = createRecordAccess(store);
668
+ const fetchBody = networkDeadline(async (part, signal) => {
669
+ const response = await fetcher(part.url, {
670
+ signal,
671
+ credentials: 'omit',
672
+ cache: 'default',
673
+ mode: 'cors',
674
+ });
675
+ check(signal);
676
+ if (!response.ok || response.status !== 200 || response.type === 'opaque')
677
+ throw downloadRefused(response);
678
+ return response.body;
679
+ }, timeoutMs);
680
+ // ---- Shard store (OPFS) -------------------------------------------------------------------
681
+ // Each pinned unit (a manifest chunk, or a small unchunked asset) is its own file, and every
682
+ // read digests every unit with the platform SHA-256 against the manifest's pin. There is no
683
+ // verified marker of any kind: what vouches for bytes is a hash of those bytes, taken when they
684
+ // are handed out. Measured on eris (autoresearch/candidates/opfs-shard-cache-v1) this replaces
685
+ // a JS hash of the whole asset plus a second full read; a bad unit costs one unit's re-fetch.
686
+ // The whole-asset digest is not recomputed: the chunk list comes from the same pinned manifest
687
+ // as the whole digest, so every byte is already bound to it through its chunk.
688
+ // Older caches admitted unchunked OPFS units up to 64 MiB. Keep reading those verified
689
+ // bytes offline, but never create/repair another oversized shard under the 16 MiB write ceiling.
690
+ const legacyLargeShards = new Set();
691
+ const usesShards = (asset) => Boolean(shards) &&
692
+ Boolean(asset.chunks || asset.size <= SHARD_UNIT_LIMIT || legacyLargeShards.has(asset.sha256));
693
+ const discoverLegacyShard = async (asset) => {
694
+ if (shards &&
695
+ !asset.chunks &&
696
+ asset.size > SHARD_UNIT_LIMIT &&
697
+ asset.size <= 64 * 1024 * 1024) {
698
+ if (await shards.has(asset.sha256, asset.size).catch(() => false))
699
+ legacyLargeShards.add(asset.sha256);
700
+ else
701
+ legacyLargeShards.delete(asset.sha256);
702
+ }
703
+ };
704
+ const unitsOf = (asset) => asset.chunks || [asset];
705
+ const platformHex = digestHex;
706
+ const underLock = (name, run) => locks?.request ? locks.request(`${MODEL_CACHE_NAME}:${name}`, run) : run();
707
+ async function commitUnit(asset, unit, bytes, signal) {
708
+ try {
709
+ await acquisitionPhase('write', () => shards.write(unit.sha256, bytes), signal);
710
+ }
711
+ catch (error) {
712
+ const quota = error?.name === 'QuotaExceededError';
713
+ emit({
714
+ status: quota ? 'quota-exceeded' : 'save-failed',
715
+ sha256: asset.sha256,
716
+ });
717
+ throw quota ? new CacheQuotaExceeded(asset.size, error) : error;
718
+ }
719
+ }
720
+ // Bounded-concurrency map over units, in order of index; the first failure stops new work.
721
+ async function eachUnit(list, limit, run) {
722
+ let next = 0;
723
+ let failure;
724
+ const lane = async () => {
725
+ while (next < list.length && !failure) {
726
+ const i = next++;
727
+ try {
728
+ await run(list[i], i);
729
+ }
730
+ catch (error) {
731
+ failure ??= error;
732
+ }
733
+ }
734
+ };
735
+ await Promise.all(Array.from({ length: Math.min(limit, list.length) }, lane));
736
+ if (failure)
737
+ throw failure;
738
+ }
739
+ // Bytes saved by the Cache Storage backend move across without a download: each unit is
740
+ // checked against its pin on the way, and the old entry is dropped once every unit is in place
741
+ // (keeping both would double the quota the model takes, which iOS does not have to spare).
742
+ async function migrateLegacy(asset, missing, signal) {
743
+ let response;
744
+ try {
745
+ response = await store.get(asset.sha256);
746
+ }
747
+ catch {
748
+ return;
749
+ }
750
+ if (!response?.body)
751
+ return;
752
+ const wanted = new Set(missing.map((unit) => unit.sha256));
753
+ const reader = response.body.getReader();
754
+ let index = 0;
755
+ let unit = unitsOf(asset)[0];
756
+ let buffer = new Uint8Array(unit.size);
757
+ let at = 0;
758
+ let moved = 0;
759
+ try {
760
+ for (;;) {
761
+ const { value, done } = await reader.read();
762
+ check(signal);
763
+ if (done)
764
+ break;
765
+ let offset = 0;
766
+ while (offset < value.byteLength && unit) {
767
+ const take = Math.min(unit.size - at, value.byteLength - offset);
768
+ buffer.set(value.subarray(offset, offset + take), at);
769
+ at += take;
770
+ offset += take;
771
+ if (at === unit.size) {
772
+ if (wanted.has(unit.sha256) && (await platformHex(buffer, signal)) === unit.sha256) {
773
+ await commitUnit(asset, unit, buffer, signal);
774
+ moved++;
775
+ }
776
+ unit = unitsOf(asset)[++index];
777
+ at = 0;
778
+ buffer = unit ? new Uint8Array(unit.size) : null;
779
+ }
780
+ }
781
+ if (!unit)
782
+ break;
783
+ }
784
+ }
785
+ catch (error) {
786
+ if (signal.aborted)
787
+ throw error;
788
+ }
789
+ finally {
790
+ // a broken old entry is not fatal: download what is left
791
+ void reader.cancel().catch(() => { });
792
+ }
793
+ if (moved)
794
+ emit({ status: 'migrated', sha256: asset.sha256, units: moved });
795
+ return moved;
796
+ }
797
+ async function missingUnits(asset) {
798
+ const out = [];
799
+ for (const unit of unitsOf(asset))
800
+ if (!(await shards.has(unit.sha256, unit.size)))
801
+ out.push(unit);
802
+ return out;
803
+ }
804
+ async function ensureShards(asset, signal, transfer) {
805
+ let missing = await missingUnits(asset);
806
+ check(signal);
807
+ if (!asset.chunks && asset.size > SHARD_UNIT_LIMIT && missing.length) {
808
+ legacyLargeShards.delete(asset.sha256);
809
+ return ensure(asset, signal, transfer);
810
+ }
811
+ if (!missing.length) {
812
+ emit({ status: 'retained', sha256: asset.sha256, bytes: asset.size });
813
+ return;
814
+ }
815
+ // Migration is local: it announces nothing until it is known that the network is needed.
816
+ if (await migrateLegacy(asset, missing, signal)) {
817
+ missing = await missingUnits(asset);
818
+ if (!missing.length) {
819
+ void Promise.resolve(store.remove(asset.sha256)).catch(() => { });
820
+ emit({ status: 'saved', sha256: asset.sha256, bytes: asset.size });
821
+ return;
822
+ }
823
+ }
824
+ check(signal);
825
+ emit({ status: 'missing', sha256: asset.sha256 });
826
+ emit({ status: 'downloading', sha256: asset.sha256 });
827
+ let loaded = asset.size - missing.reduce((sum, unit) => sum + unit.size, 0);
828
+ const stop = new AbortController();
829
+ const relay = () => stop.abort(signal.reason || aborted());
830
+ signal.addEventListener('abort', relay, { once: true });
831
+ try {
832
+ await eachUnit(missing, readAhead, async (unit) => {
833
+ try {
834
+ // The slot spans fetch, digest and write: the chunk's bytes are in memory for all three.
835
+ await inSlot(transfer, stop.signal, async () => commitUnit(asset, unit, await chunk(unit, stop.signal, transfer), stop.signal));
836
+ }
837
+ catch (error) {
838
+ stop.abort(error);
839
+ throw error;
840
+ }
841
+ loaded += unit.size;
842
+ emit({ status: 'progress', sha256: asset.sha256, loaded, bytes: asset.size });
843
+ });
844
+ }
845
+ finally {
846
+ signal.removeEventListener('abort', relay);
847
+ }
848
+ check(signal);
849
+ void Promise.resolve(store.remove(asset.sha256)).catch(() => { }); // a partly migrated old entry is no longer needed
850
+ emit({ status: 'saved', sha256: asset.sha256, bytes: asset.size });
851
+ }
852
+ // Every unit read is digested against its pin, every time. A unit that is absent, uncommitted or
853
+ // wrong is removed and fetched again on its own, under the same lock that guards its writes.
854
+ async function readShards(asset, { allowRepair, transfer }) {
855
+ if (!asset.chunks && asset.size > SHARD_UNIT_LIMIT) {
856
+ const bytes = await shards.read(asset.sha256, asset.size);
857
+ if (bytes && (await platformHex(bytes)) === asset.sha256)
858
+ return bytes;
859
+ emit({ status: bytes ? 'corrupt-removed' : 'missing-after-acquire', sha256: asset.sha256 });
860
+ if (!allowRepair || !transfer)
861
+ throw bytes
862
+ ? localError('Asset integrity mismatch', 'corrupt')
863
+ : localError('Stored asset disappeared; acquire again', 'absent');
864
+ emit({ status: 'repairing', sha256: asset.sha256 });
865
+ return underLock(asset.sha256, async () => {
866
+ const again = await shards.read(asset.sha256, asset.size);
867
+ if (again && (await platformHex(again)) === asset.sha256)
868
+ return again;
869
+ await shards.remove(asset.sha256);
870
+ legacyLargeShards.delete(asset.sha256);
871
+ await ensure(asset, new AbortController().signal, transfer);
872
+ return readVerified(asset, transfer);
873
+ });
874
+ }
875
+ const units = unitsOf(asset);
876
+ const out = units.length === 1 ? null : new Uint8Array(asset.size);
877
+ const offsets = [];
878
+ units.reduce((at, unit) => {
879
+ offsets.push(at);
880
+ return at + unit.size;
881
+ }, 0);
882
+ let single;
883
+ await eachUnit(units, 4, async (unit, i) => {
884
+ let bytes = await shards.read(unit.sha256, unit.size);
885
+ if (!bytes || (await platformHex(bytes)) !== unit.sha256) {
886
+ emit({ status: bytes ? 'corrupt-removed' : 'missing-after-acquire', sha256: asset.sha256 });
887
+ if (!allowRepair || !transfer)
888
+ throw bytes
889
+ ? localError('Asset integrity mismatch', 'corrupt')
890
+ : localError('Stored asset disappeared; acquire again', 'absent');
891
+ emit({ status: 'repairing', sha256: asset.sha256 });
892
+ bytes = await underLock(unit.sha256, async () => {
893
+ const again = await shards.read(unit.sha256, unit.size); // another tab may have repaired it
894
+ if (again && (await platformHex(again)) === unit.sha256)
895
+ return again;
896
+ await shards.remove(unit.sha256);
897
+ // The refetch is under the grant that acquired the asset, inside the shared budget.
898
+ const repair = new AbortController().signal;
899
+ return inSlot(transfer, repair, async () => {
900
+ const fresh = await chunk(unit, repair, transfer);
901
+ await commitUnit(asset, unit, fresh).catch(() => { }); // the verified bytes are served even if saving fails
902
+ return fresh;
903
+ });
904
+ });
905
+ }
906
+ if (out)
907
+ out.set(bytes, offsets[i]);
908
+ else
909
+ single = bytes;
910
+ });
911
+ return out || single;
912
+ }
913
+ // C-05, amended 19 September: the digest of an asset is computed at most once per session.
914
+ // Bytes verified on download (or on first open of bytes stored earlier) carry the in-memory
915
+ // mark; the marker is deliberately NOT durable any more — a durable marker vouches for bytes
916
+ // it cannot see change underneath, and a stale marker served corrupt bytes on iOS 27 Safari
917
+ // and Android Chrome 124. Cost of the fix: one hash per asset per session instead of one per
918
+ // bundle version; correctness outranks the saving. Old durable markers are deleted whenever
919
+ // the identity is touched (openVerified cleanup).
920
+ const VERIFIED_MARKER = 'verified:';
921
+ const verifiedAssets = new Set();
922
+ const markVerified = (sha256) => {
923
+ verifiedAssets.add(sha256);
924
+ };
925
+ const pump = () => {
926
+ while (active < maxConcurrent && queue.length) {
927
+ const task = queue.shift();
928
+ if (task.signal.aborted) {
929
+ task.reject(task.signal.reason || aborted());
930
+ continue;
931
+ }
932
+ task.signal.removeEventListener('abort', task.cancel);
933
+ active++;
934
+ Promise.resolve()
935
+ .then(task.run)
936
+ .then(task.resolve, task.reject)
937
+ .finally(() => {
938
+ active--;
939
+ pump();
940
+ });
941
+ }
942
+ };
943
+ const schedule = (run, signal) => new Promise((resolve, reject) => {
944
+ const task = {
945
+ run,
946
+ signal,
947
+ resolve,
948
+ reject,
949
+ cancel: () => {
950
+ const index = queue.indexOf(task);
951
+ if (index >= 0)
952
+ queue.splice(index, 1);
953
+ reject(signal.reason || aborted());
954
+ },
955
+ };
956
+ check(signal);
957
+ queue.push(task);
958
+ signal.addEventListener('abort', task.cancel, { once: true });
959
+ pump();
960
+ });
961
+ async function ensure(asset, signal, transfer) {
962
+ check(signal);
963
+ await discoverLegacyShard(asset);
964
+ check(signal);
965
+ if (usesShards(asset))
966
+ return ensureShards(asset, signal, transfer);
967
+ let cached;
968
+ try {
969
+ cached = await store.get(asset.sha256);
970
+ }
971
+ catch (error) {
972
+ emit({ status: 'storage-unavailable', sha256: asset.sha256 });
973
+ throw error;
974
+ }
975
+ check(signal);
976
+ if (cached) {
977
+ // C-05: a retained asset is not re-hashed here — that streamed every byte through JS
978
+ // hashing on every session for files already verified when written. Integrity is
979
+ // enforced where it is consumed: open() verifies once per asset identity (see below).
980
+ emit({ status: 'retained', sha256: asset.sha256, bytes: asset.size });
981
+ return;
982
+ }
983
+ else
984
+ emit({ status: 'missing', sha256: asset.sha256 }); // Missing alone does not prove eviction.
985
+ check(signal);
986
+ emit({ status: 'downloading', sha256: asset.sha256 });
987
+ /** Slots held by this asset's chunks still in memory; all are let go when the asset settles. */
988
+ const held = new Set();
989
+ const letGo = (release) => {
990
+ held.delete(release);
991
+ release();
992
+ };
993
+ let body;
994
+ let settlePlain;
995
+ const chunks = asset.chunks;
996
+ if (chunks && globalThis.crypto?.subtle) {
997
+ // Read-ahead (measured on eris, 150 MiB model prefix): chunks fetched one at a time and hashed in
998
+ // JS twice cost 6.8 s of a cold first face, against a link ceiling of 2.7 s with four in flight.
999
+ // Up to `readAhead` 16 MiB chunks are fetched into memory concurrently; each is checked against
1000
+ // its pinned digest by the platform's SHA-256 (8x the speed of sha256.mjs, off this thread) and
1001
+ // handed on strictly in order. Memory is bounded by readAhead chunks. The whole-asset digest
1002
+ // below is unchanged, and nothing commits until it matches at EOF.
1003
+ // Each chunk also holds an aggregate slot from before its first byte until the store has taken all of it: the
1004
+ // next pull only comes once the consumer has read every piece enqueued before it (fm-fr9s).
1005
+ const ahead = [];
1006
+ const stop = new AbortController();
1007
+ const relay = () => stop.abort(signal.reason || aborted());
1008
+ signal.addEventListener('abort', relay, { once: true });
1009
+ const release = (reason) => {
1010
+ signal.removeEventListener('abort', relay);
1011
+ if (reason !== undefined)
1012
+ stop.abort(reason);
1013
+ };
1014
+ let started = 0;
1015
+ let handedOn;
1016
+ const fill = () => {
1017
+ while (ahead.length < readAhead && started < chunks.length) {
1018
+ const part = chunks[started++];
1019
+ const task = (async () => {
1020
+ const slot = slots ? await slots.take(transfer.priority(), stop.signal) : () => { };
1021
+ held.add(slot);
1022
+ try {
1023
+ return { bytes: await chunk(part, stop.signal, transfer), release: slot };
1024
+ }
1025
+ catch (error) {
1026
+ letGo(slot);
1027
+ throw error;
1028
+ }
1029
+ })();
1030
+ task.catch(() => { }); // surfaced where it is awaited; a later chunk must not become an unhandled rejection
1031
+ ahead.push(task);
1032
+ }
1033
+ };
1034
+ body = new ReadableStream({
1035
+ async pull(controller) {
1036
+ try {
1037
+ if (handedOn)
1038
+ letGo(handedOn);
1039
+ handedOn = undefined;
1040
+ check(signal);
1041
+ fill();
1042
+ if (!ahead.length) {
1043
+ release();
1044
+ controller.close();
1045
+ return;
1046
+ }
1047
+ const next = await ahead.shift();
1048
+ handedOn = next.release;
1049
+ const piece = next.bytes;
1050
+ check(signal);
1051
+ fill();
1052
+ // Network-sized views, not the whole 16 MiB buffer: Firefox failed the first read-ahead build with a
1053
+ // NetworkError (caught by the pre-deploy engine matrix), and the progress bar would move in 16 MiB
1054
+ // steps. Views share the buffer, so this copies nothing.
1055
+ for (let at = 0; at < piece.byteLength; at += PIECE_BYTES)
1056
+ controller.enqueue(piece.subarray(at, Math.min(at + PIECE_BYTES, piece.byteLength)));
1057
+ }
1058
+ catch (error) {
1059
+ release(error);
1060
+ controller.error(error);
1061
+ }
1062
+ },
1063
+ cancel(reason) {
1064
+ release(reason ?? aborted());
1065
+ },
1066
+ });
1067
+ }
1068
+ else if (chunks) {
1069
+ // No platform digest (very old engines): one chunk at a time, hashed incrementally as before.
1070
+ let index = 0;
1071
+ let reader;
1072
+ let charge;
1073
+ let slot;
1074
+ const endChunk = () => {
1075
+ charge?.settle();
1076
+ charge = undefined;
1077
+ if (slot)
1078
+ letGo(slot);
1079
+ slot = undefined;
1080
+ };
1081
+ body = new ReadableStream({
1082
+ async pull(controller) {
1083
+ try {
1084
+ check(signal);
1085
+ while (true) {
1086
+ if (!reader) {
1087
+ if (index === chunks.length) {
1088
+ controller.close();
1089
+ return;
1090
+ }
1091
+ const part = chunks[index++];
1092
+ slot = slots ? await slots.take(transfer.priority(), signal) : () => { };
1093
+ held.add(slot);
1094
+ charge = chargeGrant(transfer.payer(), part.sha256, part.size);
1095
+ reader = verifiedStream(await fetchBody(part, signal), part, signal).getReader();
1096
+ }
1097
+ const result = await reader.read();
1098
+ if (result.done) {
1099
+ reader.releaseLock();
1100
+ reader = undefined;
1101
+ endChunk();
1102
+ continue;
1103
+ }
1104
+ charge.received(result.value.byteLength);
1105
+ controller.enqueue(result.value);
1106
+ return;
1107
+ }
1108
+ }
1109
+ catch (error) {
1110
+ endChunk();
1111
+ controller.error(error);
1112
+ await reader?.cancel(error).catch(() => { });
1113
+ }
1114
+ },
1115
+ cancel(reason) {
1116
+ endChunk();
1117
+ return reader?.cancel(reason);
1118
+ },
1119
+ });
1120
+ }
1121
+ else {
1122
+ // One unchunked asset streams into the store under one slot and one charge for its whole size.
1123
+ const slot = slots ? await slots.take(transfer.priority(), signal) : () => { };
1124
+ held.add(slot);
1125
+ let charge;
1126
+ try {
1127
+ charge = chargeGrant(transfer.payer(), asset.sha256, asset.size);
1128
+ body = charged(await fetchBody(asset, signal), charge);
1129
+ }
1130
+ catch (error) {
1131
+ charge?.settle();
1132
+ letGo(slot); // a refused grant gives its slot back at once
1133
+ throw error;
1134
+ }
1135
+ const settle = charge;
1136
+ settlePlain = () => settle.settle();
1137
+ }
1138
+ let streamFailure;
1139
+ const verified = new Response(verifiedStream(counted(body, asset, emit), asset, signal, (error) => {
1140
+ streamFailure = error;
1141
+ }), {
1142
+ headers: {
1143
+ 'Content-Type': 'application/octet-stream',
1144
+ 'Content-Length': String(asset.size),
1145
+ 'X-CheckFace-SHA256': asset.sha256,
1146
+ },
1147
+ });
1148
+ try {
1149
+ await store.put(asset.sha256, verified);
1150
+ }
1151
+ catch (error) {
1152
+ // Native Cache.put may replace a rejected body's reason with a generic NetworkError.
1153
+ // Preserve the verified stream's actual failure; storage-only refusals retain their own error.
1154
+ const failure = streamFailure ?? error;
1155
+ // A backend can reject before consuming (e.g. quota); cancel the unconsumed network stream.
1156
+ if (verified.body && !verified.body.locked)
1157
+ await verified.body.cancel(failure).catch(() => { });
1158
+ const quota = failure?.name === 'QuotaExceededError';
1159
+ emit({
1160
+ status: quota ? 'quota-exceeded' : 'save-failed',
1161
+ sha256: asset.sha256,
1162
+ });
1163
+ throw quota ? new CacheQuotaExceeded(asset.size, failure) : failure;
1164
+ }
1165
+ finally {
1166
+ for (const release of held)
1167
+ letGo(release); // deleting the visited entry is safe
1168
+ settlePlain?.();
1169
+ }
1170
+ // A cancellation at commit may leave a fully verified blob: retain it for a later request.
1171
+ emit({ status: 'saved', sha256: asset.sha256, bytes: asset.size });
1172
+ check(signal);
1173
+ // The bytes just committed were verified stream-incrementally; record that once (C-05).
1174
+ markVerified(asset.sha256);
1175
+ }
1176
+ // open(): bytes stored by THIS session were verified at write time and are returned as-is.
1177
+ // Anything else is hashed on first open of the session — the durable verified marker was
1178
+ // removed 19 September because it vouched for bytes it could not see change underneath
1179
+ // (a stale marker served corrupt bytes on iOS 27 Safari and Android Chrome 124; see the
1180
+ // mobile suite's corrupt-cache-repair check). A first-open mismatch, or a vanished entry,
1181
+ // is repaired once: the bad identity is removed and re-acquired before bytes are handed
1182
+ // back. open() stays streaming: pass 1 hashes the stored stream, pass 2 returns a fresh
1183
+ // store read. bytes() instead verifies while filling its one required execution buffer.
1184
+ async function digestFailure(body, asset) {
1185
+ if (!body)
1186
+ return new Error('Asset response has no readable body');
1187
+ const reader = body.getReader();
1188
+ const hash = new Sha256();
1189
+ let size = 0;
1190
+ for (;;) {
1191
+ const { value, done } = await reader.read();
1192
+ if (done)
1193
+ break;
1194
+ size += value.byteLength;
1195
+ if (size > asset.size) {
1196
+ void reader.cancel(new Error('Asset exceeds declared size')).catch(() => { });
1197
+ return new Error('Asset exceeds declared size');
1198
+ }
1199
+ await updateHash(hash, value);
1200
+ }
1201
+ if (size !== asset.size || (await finishHash(hash)) !== asset.sha256)
1202
+ return new Error('Asset integrity mismatch');
1203
+ return null;
1204
+ }
1205
+ async function openVerified(asset, { allowRepair, transfer }) {
1206
+ let response;
1207
+ try {
1208
+ response = await store.get(asset.sha256);
1209
+ }
1210
+ catch (error) {
1211
+ emit({ status: 'storage-unavailable', sha256: asset.sha256 });
1212
+ throw error;
1213
+ }
1214
+ if (!response) {
1215
+ emit({ status: 'missing-after-acquire', sha256: asset.sha256 });
1216
+ if (!allowRepair || !transfer)
1217
+ throw localError('Stored asset disappeared; acquire again', 'absent');
1218
+ emit({ status: 'repairing', sha256: asset.sha256 });
1219
+ await ensure(asset, new AbortController().signal, transfer);
1220
+ return openVerified(asset, { allowRepair: false });
1221
+ }
1222
+ if (verifiedAssets.has(asset.sha256))
1223
+ return response;
1224
+ // A stored body that cannot be read (NotReadableError: Android Chrome loses the file behind a
1225
+ // Cache Storage entry) is corrupt like a wrong digest, and is repaired the same way.
1226
+ const failure = await digestFailure(response.body, asset).catch((error) => error);
1227
+ if (!failure) {
1228
+ markVerified(asset.sha256);
1229
+ emit({ status: 'verified', sha256: asset.sha256, bytes: asset.size });
1230
+ return (await store.get(asset.sha256));
1231
+ }
1232
+ // Corrupt: drop the identity and its record, then repair once.
1233
+ verifiedAssets.delete(asset.sha256);
1234
+ await Promise.resolve(store.remove(asset.sha256)).catch(() => { });
1235
+ await records.remove(VERIFIED_MARKER + asset.sha256).catch(() => { });
1236
+ emit({ status: 'corrupt-removed', sha256: asset.sha256 });
1237
+ if (!allowRepair || !transfer)
1238
+ throw Object.assign(failure, { local: 'corrupt' });
1239
+ emit({ status: 'repairing', sha256: asset.sha256 });
1240
+ await ensure(asset, new AbortController().signal, transfer);
1241
+ return openVerified(asset, { allowRepair: false });
1242
+ }
1243
+ // Return the same bytes we verified, rather than hashing one stored stream then reopening
1244
+ // another. The output is the execution buffer bytes() already requires; incoming pieces use
1245
+ // the unchanged bounded hash phase. Never allocate from the untrusted response's length.
1246
+ // A file that becomes unreadable after verification is still dropped and repaired once.
1247
+ async function readVerified(asset, transfer) {
1248
+ for (const allowRepair of [true, false]) {
1249
+ let response;
1250
+ try {
1251
+ response = await store.get(asset.sha256);
1252
+ }
1253
+ catch (error) {
1254
+ emit({ status: 'storage-unavailable', sha256: asset.sha256 });
1255
+ throw error;
1256
+ }
1257
+ let failure;
1258
+ if (response) {
1259
+ // Allocation failure is memory pressure, not evidence that the stored model is corrupt.
1260
+ // Keep it outside the repair catch so it cannot evict good bytes or spend another grant.
1261
+ let output;
1262
+ try {
1263
+ output = new Uint8Array(asset.size);
1264
+ }
1265
+ catch (error) {
1266
+ void response.body?.cancel(error).catch(() => { });
1267
+ throw error;
1268
+ }
1269
+ let reader;
1270
+ try {
1271
+ const needsVerification = !verifiedAssets.has(asset.sha256);
1272
+ const body = needsVerification
1273
+ ? verifiedStream(response.body, asset, new AbortController().signal)
1274
+ : response.body;
1275
+ if (!body)
1276
+ throw new Error('Asset response has no readable body');
1277
+ reader = body.getReader();
1278
+ let size = 0;
1279
+ for (;;) {
1280
+ const { value, done } = await reader.read();
1281
+ if (done)
1282
+ break;
1283
+ if (value.byteLength > output.byteLength - size)
1284
+ throw new Error('Asset exceeds declared size');
1285
+ output.set(value, size);
1286
+ size += value.byteLength;
1287
+ }
1288
+ if (size !== asset.size)
1289
+ throw new Error('Asset integrity mismatch');
1290
+ if (needsVerification) {
1291
+ markVerified(asset.sha256);
1292
+ emit({ status: 'verified', sha256: asset.sha256, bytes: asset.size });
1293
+ }
1294
+ return output;
1295
+ }
1296
+ catch (error) {
1297
+ failure = error;
1298
+ await reader?.cancel(error).catch(() => { });
1299
+ }
1300
+ finally {
1301
+ reader?.releaseLock();
1302
+ }
1303
+ await Promise.resolve(store.remove(asset.sha256)).catch(() => { });
1304
+ await records.remove(VERIFIED_MARKER + asset.sha256).catch(() => { });
1305
+ emit({ status: 'corrupt-removed', sha256: asset.sha256 });
1306
+ }
1307
+ else {
1308
+ failure = localError('Stored asset disappeared; acquire again', 'absent');
1309
+ emit({ status: 'missing-after-acquire', sha256: asset.sha256 });
1310
+ }
1311
+ verifiedAssets.delete(asset.sha256);
1312
+ if (!allowRepair)
1313
+ throw failure;
1314
+ emit({ status: 'repairing', sha256: asset.sha256 });
1315
+ await ensure(asset, new AbortController().signal, transfer);
1316
+ }
1317
+ throw new Error('Stored asset could not be read');
1318
+ }
1319
+ function acquire(input, options) {
1320
+ const { grant, owner, signal } = options ?? {};
1321
+ let asset;
1322
+ try {
1323
+ asset = validateAsset(input);
1324
+ // No grant, an owner it does not name, or a digest outside it: refused before any request.
1325
+ grantAsset(grant, owner, asset.sha256, asset.size);
1326
+ check(signal);
1327
+ }
1328
+ catch (error) {
1329
+ return Promise.reject(error);
1330
+ }
1331
+ const ownerId = owner;
1332
+ let task = pending.get(asset.sha256);
1333
+ if (task && task.asset.size !== asset.size)
1334
+ return Promise.reject(new Error('Conflicting size for identical hash'));
1335
+ if (!task) {
1336
+ const controller = new AbortController();
1337
+ const owners = new Map();
1338
+ // Bytes are charged to the first owner still attached; when it leaves, the next one carries the fetch on
1339
+ // under its own grant (ownership transfer). Priority is the highest any owner's grant gives this asset.
1340
+ const transfer = {
1341
+ payer() {
1342
+ const first = owners.values().next();
1343
+ if (first.done)
1344
+ throw new GrantRefused('no-owner', asset.sha256);
1345
+ return first.value.grant;
1346
+ },
1347
+ priority() {
1348
+ let best = 'speculative-warming';
1349
+ for (const { grant: g } of owners.values()) {
1350
+ const p = g.assets.find((a) => a.sha256 === asset.sha256)?.priority ?? best;
1351
+ if (PRIORITY_ORDER.indexOf(p) < PRIORITY_ORDER.indexOf(best))
1352
+ best = p;
1353
+ }
1354
+ return best;
1355
+ },
1356
+ };
1357
+ const current = {
1358
+ asset,
1359
+ controller,
1360
+ waiters: 0,
1361
+ owners,
1362
+ transfer,
1363
+ promise: Promise.resolve(),
1364
+ };
1365
+ task = current;
1366
+ const run = () => ensure(asset, controller.signal, transfer);
1367
+ current.promise = schedule(() => locks?.request
1368
+ ? locks.request(`${MODEL_CACHE_NAME}:${asset.sha256}`, { signal: controller.signal }, run)
1369
+ : run(), controller.signal).finally(() => {
1370
+ if (pending.get(asset.sha256) === current)
1371
+ pending.delete(asset.sha256);
1372
+ });
1373
+ pending.set(asset.sha256, current);
1374
+ }
1375
+ const shared = task;
1376
+ shared.waiters++;
1377
+ // A revised grant from the same owner (a new decision) pays from now on; the owner keeps its place in line.
1378
+ shared.owners.set(ownerId, {
1379
+ grant: grant,
1380
+ count: (shared.owners.get(ownerId)?.count ?? 0) + 1,
1381
+ });
1382
+ // The handle repairs only under this caller's own grant: a later refetch is charged to it.
1383
+ const own = {
1384
+ payer: () => grant,
1385
+ priority: () => grant.assets.find((a) => a.sha256 === asset.sha256).priority,
1386
+ };
1387
+ return new Promise((resolve, reject) => {
1388
+ let settled = false;
1389
+ const leave = () => {
1390
+ const entry = shared.owners.get(ownerId);
1391
+ if (entry && --entry.count === 0)
1392
+ shared.owners.delete(ownerId);
1393
+ };
1394
+ const finish = (error) => {
1395
+ if (settled)
1396
+ return;
1397
+ settled = true;
1398
+ signal?.removeEventListener('abort', cancel);
1399
+ shared.waiters--;
1400
+ leave();
1401
+ if (error)
1402
+ reject(error);
1403
+ else if (usesShards(asset))
1404
+ resolve(Object.freeze({
1405
+ sha256: asset.sha256,
1406
+ size: asset.size,
1407
+ bytes: () => readShards(asset, { allowRepair: true, transfer: own }),
1408
+ open: async () => new Response(await readShards(asset, { allowRepair: true, transfer: own })),
1409
+ }));
1410
+ else
1411
+ resolve(Object.freeze({
1412
+ sha256: asset.sha256,
1413
+ size: asset.size,
1414
+ bytes: () => readVerified(asset, own),
1415
+ open: async () => openVerified(asset, { allowRepair: true, transfer: own }),
1416
+ }));
1417
+ };
1418
+ const cancel = () => {
1419
+ finish(signal.reason || aborted());
1420
+ // The last owner to leave stops the fetch; verified chunks already stored are kept.
1421
+ if (shared.waiters === 0) {
1422
+ shared.controller.abort(aborted());
1423
+ if (pending.get(asset.sha256) === shared)
1424
+ pending.delete(asset.sha256);
1425
+ }
1426
+ };
1427
+ signal?.addEventListener('abort', cancel, { once: true });
1428
+ shared.promise.then(() => finish(), finish);
1429
+ if (signal?.aborted)
1430
+ cancel();
1431
+ });
1432
+ }
1433
+ // Both take an asset descriptor (or, for Cache Storage only, a bare hash). Bytes still in the
1434
+ // old Cache Storage entry count as present: the next acquisition moves them without a download.
1435
+ async function has(input) {
1436
+ const asset = typeof input === 'string' ? null : input;
1437
+ const sha256 = asset ? asset.sha256 : input;
1438
+ if (asset)
1439
+ await discoverLegacyShard(asset);
1440
+ if (asset && usesShards(asset) && !(await missingUnits(asset).catch(() => [asset])).length)
1441
+ return true;
1442
+ try {
1443
+ return Boolean(await store.get(sha256));
1444
+ }
1445
+ catch {
1446
+ return false;
1447
+ }
1448
+ }
1449
+ async function heldBytes(input) {
1450
+ const asset = input;
1451
+ if (await has(asset))
1452
+ return asset.size;
1453
+ if (!usesShards(asset))
1454
+ return 0;
1455
+ let held = 0;
1456
+ for (const unit of unitsOf(asset))
1457
+ if (await shards.has(unit.sha256, unit.size).catch(() => false))
1458
+ held += unit.size;
1459
+ return held;
1460
+ }
1461
+ async function peek(input) {
1462
+ const asset = typeof input === 'string' ? null : input;
1463
+ const sha256 = asset ? asset.sha256 : input;
1464
+ if (asset)
1465
+ await discoverLegacyShard(asset);
1466
+ if (asset && usesShards(asset)) {
1467
+ try {
1468
+ return new Response(await readShards(asset, { allowRepair: false }));
1469
+ }
1470
+ catch {
1471
+ /* fall through */
1472
+ }
1473
+ }
1474
+ try {
1475
+ return (await store.get(sha256)) || null;
1476
+ }
1477
+ catch {
1478
+ return null;
1479
+ }
1480
+ }
1481
+ // ---- Verified local reads (fm-eulc) ------------------------------------------------------
1482
+ // No network, ever: readShards and openVerified run with allowRepair false, and nothing here reaches the
1483
+ // fetcher. Every read digests what it returns: each OPFS unit by readShards, and Cache Storage bytes once
1484
+ // more here, because open() trusts bytes it verified earlier in the session and a local read must not.
1485
+ // Presence alone (has(), a committed trailer) never vouches for bytes. An absent asset is `evicted` when
1486
+ // it was stored before as far as this cache can tell (some of its units remain, or this cache saw it
1487
+ // stored this session) and `cache-miss` otherwise: after a whole-origin eviction a new session cannot
1488
+ // tell the two apart.
1489
+ const unitsPresent = async (asset) => (await Promise.all(unitsOf(asset).map((u) => shards.has(u.sha256, u.size).catch(() => false)))).filter(Boolean).length;
1490
+ async function readLocal(input) {
1491
+ const asset = validateAsset(input);
1492
+ const fail = (error) => ({ ok: false, error });
1493
+ try {
1494
+ await discoverLegacyShard(asset);
1495
+ let bytes;
1496
+ const legacy = async () => {
1497
+ const body = new Uint8Array(await (await openVerified(asset, { allowRepair: false })).arrayBuffer());
1498
+ if (body.byteLength !== asset.size || (await platformHex(body)) !== asset.sha256) {
1499
+ await Promise.resolve(store.remove(asset.sha256)).catch(() => { });
1500
+ throw localError('Asset integrity mismatch', 'corrupt');
1501
+ }
1502
+ return body;
1503
+ };
1504
+ if (usesShards(asset)) {
1505
+ // Bytes still in the old Cache Storage entry (not yet migrated) are read from there, verified.
1506
+ const fromLegacy = !(await unitsPresent(asset)) &&
1507
+ Boolean(await store.get(asset.sha256).catch(() => undefined));
1508
+ bytes = fromLegacy ? await legacy() : await readShards(asset, { allowRepair: false });
1509
+ }
1510
+ else
1511
+ bytes = await legacy();
1512
+ stored.add(asset.sha256);
1513
+ return { ok: true, value: bytes };
1514
+ }
1515
+ catch (error) {
1516
+ const e = error;
1517
+ if (e?.local === 'corrupt' || e?.name === 'NotReadableError') {
1518
+ stored.delete(asset.sha256); // a removed identity is not an eviction
1519
+ return fail({ code: 'corrupt', sha256: asset.sha256, message: e.message });
1520
+ }
1521
+ if (e?.local === 'absent') {
1522
+ const partial = usesShards(asset) && (await unitsPresent(asset)) > 0;
1523
+ return fail({
1524
+ code: partial || stored.has(asset.sha256) ? 'evicted' : 'cache-miss',
1525
+ sha256: asset.sha256,
1526
+ message: e.message,
1527
+ });
1528
+ }
1529
+ return fail({
1530
+ code: 'unknown-status',
1531
+ retryable: true,
1532
+ message: String(e?.message ?? error),
1533
+ });
1534
+ }
1535
+ }
1536
+ const local = Object.freeze({ allowRepair: false, read: readLocal });
1537
+ return { acquire, records, has, heldBytes, peek, local };
1538
+ }
1539
+ export async function createBrowserModelCache(options = {}) {
1540
+ const { caches, location } = browserGlobals;
1541
+ if (!caches || !location?.origin)
1542
+ throw new Error('Persistent Cache Storage unavailable');
1543
+ const cache = await caches.open(MODEL_CACHE_NAME);
1544
+ // Native WebViews use tauri:// origins, which Cache Storage rejects as keys.
1545
+ // This HTTPS namespace is a local storage key only; no request is sent here.
1546
+ const origin = /^https?:\/\//.test(location.origin)
1547
+ ? location.origin
1548
+ : 'https://next.facemorph.me';
1549
+ const key = (hash) => new URL(`/__checkface_model_blobs__/sha256/${hash}`, origin).href;
1550
+ const shards = options.shards !== undefined
1551
+ ? options.shards
1552
+ : await openShardStore({ readOnly: options.readOnly === true });
1553
+ const locks = browserGlobals.navigator?.locks;
1554
+ // One aggregate budget for every worker and tab of this origin, sized by the device's memory class.
1555
+ const memory = acquisitionMemoryClass(browserGlobals.navigator?.deviceMemory);
1556
+ return createModelCache({
1557
+ slots: locks ? createAcquisitionSlots({ locks, count: slotCount(memory) }) : null,
1558
+ ...options,
1559
+ shards,
1560
+ locks,
1561
+ store: {
1562
+ get: (hash) => cache.match(key(hash)),
1563
+ put: (hash, response) => cache.put(key(hash), response),
1564
+ remove: (hash) => cache.delete(key(hash)),
1565
+ },
1566
+ });
1567
+ }
1568
+ // Request explicitly from the host UI; no persistence prompt at module import/startup.
1569
+ export async function storageStatus({ requestPersistence = false, storage = browserGlobals.navigator?.storage, } = {}) {
1570
+ if (!storage)
1571
+ return { persistence: 'unavailable', eviction: 'unknown' };
1572
+ try {
1573
+ const granted = requestPersistence && storage.persist ? await storage.persist() : await storage.persisted?.();
1574
+ const estimate = await storage.estimate?.();
1575
+ return {
1576
+ persistence: granted === true ? 'granted' : granted === false ? 'not-granted' : 'unavailable',
1577
+ usage: estimate?.usage,
1578
+ quota: estimate?.quota,
1579
+ eviction: 'unknown',
1580
+ };
1581
+ }
1582
+ catch {
1583
+ return { persistence: 'unavailable', eviction: 'unknown' };
1584
+ }
1585
+ }