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,11 @@
1
+ export declare class Sha256 {
2
+ private readonly h;
3
+ private readonly block;
4
+ private readonly w;
5
+ private used;
6
+ private bytes;
7
+ private done;
8
+ private compress;
9
+ update(input: Uint8Array): void;
10
+ hex(): string;
11
+ }
@@ -0,0 +1,97 @@
1
+ // Incremental SHA-256: retains at most one input chunk and a 64-byte block.
2
+ // Input is bytes; callers must not mutate a chunk during update().
3
+ // Moved from the candidate's src/Next/Assets/sha256.mjs (classic a42829b) without behaviour change (fm-eulc).
4
+ const K = new Uint32Array([
5
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
6
+ 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
7
+ 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
8
+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
9
+ 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
10
+ 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
11
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
12
+ 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
13
+ ]);
14
+ const rotr = (x, n) => (x >>> n) | (x << (32 - n));
15
+ export class Sha256 {
16
+ h = new Uint32Array([
17
+ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
18
+ ]);
19
+ block = new Uint8Array(64);
20
+ w = new Uint32Array(64);
21
+ used = 0;
22
+ bytes = 0;
23
+ done = false;
24
+ compress(block) {
25
+ const w = this.w;
26
+ const view = new DataView(block.buffer, block.byteOffset, 64);
27
+ for (let i = 0; i < 16; i++)
28
+ w[i] = view.getUint32(i * 4);
29
+ for (let i = 16; i < 64; i++) {
30
+ const x = w[i - 15];
31
+ const y = w[i - 2];
32
+ w[i] =
33
+ w[i - 16] +
34
+ (rotr(x, 7) ^ rotr(x, 18) ^ (x >>> 3)) +
35
+ w[i - 7] +
36
+ (rotr(y, 17) ^ rotr(y, 19) ^ (y >>> 10));
37
+ }
38
+ const s = this.h;
39
+ let a = s[0], b = s[1], c = s[2], d = s[3], e = s[4], f = s[5], g = s[6], h = s[7];
40
+ for (let i = 0; i < 64; i++) {
41
+ const t1 = (h + (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) + ((e & f) ^ (~e & g)) + K[i] + w[i]) >>> 0;
42
+ const t2 = ((rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + ((a & b) ^ (a & c) ^ (b & c))) >>> 0;
43
+ h = g;
44
+ g = f;
45
+ f = e;
46
+ e = (d + t1) >>> 0;
47
+ d = c;
48
+ c = b;
49
+ b = a;
50
+ a = (t1 + t2) >>> 0;
51
+ }
52
+ s[0] += a;
53
+ s[1] += b;
54
+ s[2] += c;
55
+ s[3] += d;
56
+ s[4] += e;
57
+ s[5] += f;
58
+ s[6] += g;
59
+ s[7] += h;
60
+ }
61
+ update(input) {
62
+ if (this.done)
63
+ throw new Error('Hash already finalized');
64
+ this.bytes += input.length;
65
+ for (let offset = 0; offset < input.length;) {
66
+ if (this.used === 0 && input.length - offset >= 64) {
67
+ this.compress(input.subarray(offset, offset + 64));
68
+ offset += 64;
69
+ }
70
+ else {
71
+ const n = Math.min(64 - this.used, input.length - offset);
72
+ this.block.set(input.subarray(offset, offset + n), this.used);
73
+ this.used += n;
74
+ offset += n;
75
+ if (this.used === 64) {
76
+ this.compress(this.block);
77
+ this.used = 0;
78
+ }
79
+ }
80
+ }
81
+ }
82
+ hex() {
83
+ if (this.done)
84
+ throw new Error('Hash already finalized');
85
+ const bytes = this.bytes;
86
+ this.update(new Uint8Array([128]));
87
+ while (this.used !== 56)
88
+ this.update(new Uint8Array([0]));
89
+ const length = new Uint8Array(8);
90
+ const view = new DataView(length.buffer);
91
+ view.setUint32(0, Math.floor(bytes / 0x20000000));
92
+ view.setUint32(4, (bytes * 8) >>> 0);
93
+ this.update(length);
94
+ this.done = true;
95
+ return [...this.h].map((x) => x.toString(16).padStart(8, '0')).join('');
96
+ }
97
+ }
@@ -0,0 +1,89 @@
1
+ export declare const SHARD_DIRECTORY = "checkface-model-shards-v1";
2
+ export declare const TRAILER_BYTES = 48;
3
+ export declare function trailer(sha256: string, size: number): Uint8Array;
4
+ export declare function trailerMatches(tail: Uint8Array, sha256: string, size: number): boolean;
5
+ /** One pinned unit per file: read the payload or undefined, answer presence from size, commit, remove. */
6
+ export interface ShardStore {
7
+ read(sha256: string, size: number): Promise<Uint8Array<ArrayBuffer> | undefined>;
8
+ has(sha256: string, size: number): Promise<boolean>;
9
+ write(sha256: string, bytes: Uint8Array): Promise<void>;
10
+ remove(sha256: string): Promise<void>;
11
+ }
12
+ /** The parts of a FileSystemFileHandle the store uses (Safari's sync handles exist only in workers). */
13
+ interface FileHandleLike {
14
+ getFile(): Promise<File>;
15
+ createWritable?(options: {
16
+ keepExistingData: boolean;
17
+ }): Promise<{
18
+ write(data: Uint8Array): Promise<void>;
19
+ close(): Promise<void>;
20
+ abort?(): Promise<void>;
21
+ }>;
22
+ createSyncAccessHandle?(): Promise<{
23
+ truncate(size: number): void;
24
+ write(data: Uint8Array, options: {
25
+ at: number;
26
+ }): number;
27
+ flush(): void;
28
+ close(): void;
29
+ }>;
30
+ }
31
+ export interface DirectoryLike {
32
+ getFileHandle(name: string, options?: {
33
+ create?: boolean;
34
+ }): Promise<FileHandleLike>;
35
+ removeEntry(name: string): Promise<void>;
36
+ }
37
+ /**
38
+ * Store over any directory handle with the OPFS shape. `read` returns the payload or undefined
39
+ * (absent, short, uncommitted, or a trailer for different bytes); `has` answers from the file
40
+ * size alone, without reading; `write` commits payload then trailer; `remove` drops one unit.
41
+ */
42
+ export declare function createShardStore(dir: DirectoryLike): ShardStore;
43
+ /** The browser globals the cache reads, typed here so the package also compiles without DOM types. */
44
+ export interface BrowserGlobals {
45
+ readonly caches?: {
46
+ open(name: string): Promise<{
47
+ match(key: string): Promise<Response | undefined>;
48
+ put(key: string, response: Response): Promise<void>;
49
+ delete(key: string): Promise<boolean>;
50
+ }>;
51
+ };
52
+ readonly location?: {
53
+ readonly origin: string;
54
+ readonly hostname: string;
55
+ };
56
+ readonly navigator?: {
57
+ readonly storage?: StorageLike;
58
+ readonly locks?: unknown;
59
+ };
60
+ }
61
+ export declare const browserGlobals: BrowserGlobals;
62
+ export interface StorageLike {
63
+ persist?(): Promise<boolean>;
64
+ persisted?(): Promise<boolean>;
65
+ estimate?(): Promise<{
66
+ usage?: number;
67
+ quota?: number;
68
+ }>;
69
+ getDirectory?(): Promise<{
70
+ getDirectoryHandle(name: string, options?: {
71
+ create?: boolean;
72
+ }): Promise<DirectoryLike>;
73
+ }>;
74
+ }
75
+ /**
76
+ * Gives back at least `bytes` of model storage, newest units first, and returns what it freed (fm-jzuq). For the
77
+ * visitor's own records (their faces) when the origin is full: model units download again, faces do not. A small
78
+ * origin quota (a private window, whose quota is a fraction of RAM) fills with the photo encoder, which then cannot
79
+ * be kept anyway; its newest units are the ones that did not fit, so the face model written before them stays. A
80
+ * removed unit reads as evicted, which the cache already handles.
81
+ */
82
+ export declare function releaseShardSpace(bytes: number, { storage }?: {
83
+ storage?: StorageLike | undefined;
84
+ }): Promise<number>;
85
+ export declare function openShardStore({ storage, readOnly, }?: {
86
+ storage?: StorageLike | undefined;
87
+ readOnly?: boolean;
88
+ }): Promise<ShardStore | null>;
89
+ export {};
@@ -0,0 +1,204 @@
1
+ /**
2
+ * Model bytes as one file per pinned unit (a manifest chunk, or a small unchunked asset) in the
3
+ * Origin Private File System. Each file is the payload followed by a 48-byte trailer: magic,
4
+ * payload length and the unit's raw SHA-256. The trailer is written last, so a write that is cut
5
+ * short leaves no valid trailer and reads as missing, never as bytes.
6
+ *
7
+ * The trailer is a commit record, not a verdict. Nothing here vouches for the payload: the cache
8
+ * digests every unit with the platform SHA-256 on every read (model-cache.ts). That is the rule
9
+ * the durable "verified" marker broke on 19 September, when a record stored apart from the bytes
10
+ * kept vouching for bytes that had changed underneath it (iOS 27 Safari, Android Chrome 124).
11
+ *
12
+ * Returns null wherever the platform cannot give us a working directory (Firefox private
13
+ * windows, old engines, Tauri origins, denied storage); the cache then keeps Cache Storage.
14
+ *
15
+ * Moved from the candidate's src/Next/Assets/shard-store.mjs (classic a42829b) without behaviour change (fm-eulc).
16
+ */
17
+ import { acquisitionPhase } from '../acquisition/phases.js';
18
+ export const SHARD_DIRECTORY = 'checkface-model-shards-v1'; // Never app-versioned or age-purged.
19
+ const MAGIC = [0x43, 0x46, 0x53, 0x48, 0x41, 0x52, 0x44, 0x31]; // "CFSHARD1"
20
+ export const TRAILER_BYTES = 48;
21
+ const fromHex = (sha256) => Uint8Array.from(sha256.match(/../g) ?? [], (byte) => parseInt(byte, 16));
22
+ export function trailer(sha256, size) {
23
+ const out = new Uint8Array(TRAILER_BYTES);
24
+ const view = new DataView(out.buffer);
25
+ out.set(MAGIC, 0);
26
+ view.setBigUint64(8, BigInt(size), true);
27
+ out.set(fromHex(sha256), 16);
28
+ return out;
29
+ }
30
+ export function trailerMatches(tail, sha256, size) {
31
+ if (tail.byteLength !== TRAILER_BYTES)
32
+ return false;
33
+ for (let i = 0; i < 8; i++)
34
+ if (tail[i] !== MAGIC[i])
35
+ return false;
36
+ if (new DataView(tail.buffer, tail.byteOffset, TRAILER_BYTES).getBigUint64(8, true) !== BigInt(size))
37
+ return false;
38
+ const expected = fromHex(sha256);
39
+ for (let i = 0; i < 32; i++)
40
+ if (tail[16 + i] !== expected[i])
41
+ return false;
42
+ return true;
43
+ }
44
+ const named = (error) => error?.name;
45
+ /**
46
+ * Store over any directory handle with the OPFS shape. `read` returns the payload or undefined
47
+ * (absent, short, uncommitted, or a trailer for different bytes); `has` answers from the file
48
+ * size alone, without reading; `write` commits payload then trailer; `remove` drops one unit.
49
+ */
50
+ export function createShardStore(dir) {
51
+ const file = async (name) => {
52
+ try {
53
+ return await (await dir.getFileHandle(name)).getFile();
54
+ }
55
+ catch (error) {
56
+ if (named(error) === 'NotFoundError' || named(error) === 'TypeMismatchError')
57
+ return undefined;
58
+ throw error;
59
+ }
60
+ };
61
+ async function read(sha256, size) {
62
+ const stored = await file(sha256);
63
+ if (!stored || stored.size !== size + TRAILER_BYTES)
64
+ return undefined;
65
+ // Payload and trailer are read separately so the payload is an exact-length buffer: consumers
66
+ // build typed arrays over `.buffer`, and trailing bytes there corrupted the first canary.
67
+ // A File whose backing bytes can no longer be read (NotReadableError, seen on Android Chrome) is
68
+ // an absent unit: the caller removes it and fetches it again, instead of failing every read.
69
+ try {
70
+ if (!trailerMatches(new Uint8Array(await stored.slice(size).arrayBuffer()), sha256, size))
71
+ return undefined;
72
+ const payload = new Uint8Array(await stored.slice(0, size).arrayBuffer());
73
+ return payload.byteLength === size ? payload : undefined;
74
+ }
75
+ catch (error) {
76
+ if (named(error) === 'NotReadableError' || named(error) === 'NotFoundError')
77
+ return undefined;
78
+ throw error;
79
+ }
80
+ }
81
+ async function has(sha256, size) {
82
+ try {
83
+ return (await file(sha256))?.size === size + TRAILER_BYTES;
84
+ }
85
+ catch {
86
+ return false;
87
+ }
88
+ }
89
+ async function write(sha256, bytes) {
90
+ const handle = await dir.getFileHandle(sha256, { create: true });
91
+ if (typeof handle.createWritable === 'function') {
92
+ // Chrome and Firefox write to a swap file and replace the original on close(): the commit
93
+ // is atomic already, and the trailer still marks a complete payload.
94
+ const writable = await handle.createWritable({ keepExistingData: false });
95
+ try {
96
+ await writable.write(bytes);
97
+ await writable.write(trailer(sha256, bytes.byteLength));
98
+ await writable.close();
99
+ }
100
+ catch (error) {
101
+ await writable.abort?.().catch(() => { });
102
+ throw error;
103
+ }
104
+ return;
105
+ }
106
+ // Safari before createWritable: synchronous handles, workers only. The trailer goes last and
107
+ // the file is flushed before it is closed, so a crash part-way leaves no valid trailer.
108
+ if (typeof handle.createSyncAccessHandle !== 'function')
109
+ throw new Error('No OPFS write method');
110
+ const access = await handle.createSyncAccessHandle();
111
+ try {
112
+ access.truncate(0);
113
+ if (access.write(bytes, { at: 0 }) !== bytes.byteLength)
114
+ throw new Error('Short OPFS write');
115
+ access.flush();
116
+ if (access.write(trailer(sha256, bytes.byteLength), { at: bytes.byteLength }) !== TRAILER_BYTES)
117
+ throw new Error('Short OPFS write');
118
+ access.flush();
119
+ }
120
+ finally {
121
+ access.close();
122
+ }
123
+ }
124
+ async function remove(sha256) {
125
+ try {
126
+ await dir.removeEntry(sha256);
127
+ }
128
+ catch (error) {
129
+ if (named(error) !== 'NotFoundError')
130
+ throw error;
131
+ }
132
+ }
133
+ return { read, has, write, remove };
134
+ }
135
+ export const browserGlobals = globalThis;
136
+ /**
137
+ * Gives back at least `bytes` of model storage, newest units first, and returns what it freed (fm-jzuq). For the
138
+ * visitor's own records (their faces) when the origin is full: model units download again, faces do not. A small
139
+ * origin quota (a private window, whose quota is a fraction of RAM) fills with the photo encoder, which then cannot
140
+ * be kept anyway; its newest units are the ones that did not fit, so the face model written before them stays. A
141
+ * removed unit reads as evicted, which the cache already handles.
142
+ */
143
+ export async function releaseShardSpace(bytes, { storage = browserGlobals.navigator?.storage } = {}) {
144
+ if (typeof storage?.getDirectory !== 'function' || !(bytes > 0))
145
+ return 0;
146
+ let dir;
147
+ try {
148
+ dir = (await (await storage.getDirectory()).getDirectoryHandle(SHARD_DIRECTORY));
149
+ }
150
+ catch {
151
+ return 0; // no model storage on this origin
152
+ }
153
+ if (typeof dir.values !== 'function')
154
+ return 0;
155
+ const units = [];
156
+ for await (const entry of dir.values()) {
157
+ if (entry.kind !== 'file')
158
+ continue;
159
+ try {
160
+ const file = await (await dir.getFileHandle(entry.name)).getFile();
161
+ units.push({ name: entry.name, size: file.size, at: file.lastModified });
162
+ }
163
+ catch {
164
+ /* removed meanwhile */
165
+ }
166
+ }
167
+ units.sort((a, b) => b.at - a.at || (a.name < b.name ? -1 : 1));
168
+ let freed = 0;
169
+ for (const unit of units) {
170
+ if (freed >= bytes)
171
+ break;
172
+ try {
173
+ await dir.removeEntry(unit.name);
174
+ freed += unit.size;
175
+ }
176
+ catch {
177
+ /* in use by a write in progress, or already gone */
178
+ }
179
+ }
180
+ return freed;
181
+ }
182
+ export async function openShardStore({ storage = browserGlobals.navigator?.storage, readOnly = false, } = {}) {
183
+ if (typeof storage?.getDirectory !== 'function' || !globalThis.crypto?.subtle)
184
+ return null;
185
+ try {
186
+ const dir = await (await storage.getDirectory()).getDirectoryHandle(SHARD_DIRECTORY, { create: !readOnly });
187
+ const store = createShardStore(dir);
188
+ // Inventory on the main thread must see worker-written shards even on Safari, where
189
+ // only workers can obtain synchronous write handles. It never acquires or repairs bytes.
190
+ if (readOnly)
191
+ return store;
192
+ // Prove a round trip before relying on it: some engines expose getDirectory and then refuse
193
+ // writes (private modes, a main thread with only synchronous handles).
194
+ const probe = new Uint8Array([1, 2, 3, 4]);
195
+ const name = Array.from(crypto.getRandomValues(new Uint8Array(32)), (x) => x.toString(16).padStart(2, '0')).join('');
196
+ await acquisitionPhase('write', () => store.write(name, probe));
197
+ const back = await store.read(name, probe.byteLength);
198
+ await store.remove(name);
199
+ return back && back.every((value, i) => value === probe[i]) ? store : null;
200
+ }
201
+ catch {
202
+ return null;
203
+ }
204
+ }
@@ -0,0 +1,41 @@
1
+ export interface AcquisitionBudget {
2
+ /** Bytes this owner may transfer in total (its advertised remaining scope). */
3
+ readonly transferBytes: number;
4
+ /** Bytes fetched ahead of the writer, aggregate across workers. */
5
+ readonly readAheadBytes: number;
6
+ /** Bytes held while hashing. */
7
+ readonly hashBytes: number;
8
+ /** Bytes buffered before a storage write commits. */
9
+ readonly writeBufferBytes: number;
10
+ }
11
+ export interface LiveResidencyLimit {
12
+ /** Model bytes resident at once (encoder and synthesis never overlap; see ResidencyTransition). */
13
+ readonly maxResidentBytes: number;
14
+ readonly maxLiveSessions: number;
15
+ }
16
+ /** Largest manifest chunk (Assets/model-cache.mjs refuses a chunk part over 16 MiB). */
17
+ export declare const ACQUISITION_CHUNK_MAX_BYTES: number;
18
+ /** How much memory the device reports; unknown is treated as constrained. */
19
+ export type AcquisitionMemoryClass = 'constrained-or-unknown' | 'ample';
20
+ /**
21
+ * The fixed parts of an AcquisitionBudget per memory class. browser/ort-worker.mjs reads ahead 4 chunks
22
+ * when `navigator.deviceMemory >= 8`, else 2; model-cache.mjs hashes one chunk at a time (sha256.mjs keeps
23
+ * one chunk and a 64-byte block) and commits one unit per shard write.
24
+ */
25
+ export declare const ACQUISITION_BUDGETS: {
26
+ readonly [M in AcquisitionMemoryClass]: Omit<AcquisitionBudget, 'transferBytes'>;
27
+ };
28
+ /** The memory class from `navigator.deviceMemory` (GiB), as the candidate decides it. */
29
+ export declare function acquisitionMemoryClass(deviceMemoryGiB: number | undefined): AcquisitionMemoryClass;
30
+ /**
31
+ * One owner's budget: the transfer is the bytes its consent grant still allows (never a constant), the
32
+ * rest is the memory class's fixed figure.
33
+ */
34
+ export declare function acquisitionBudget(memory: AcquisitionMemoryClass, grantRemainingBytes: number): AcquisitionBudget;
35
+ /**
36
+ * Aggregate live residency. Encoder and generator never overlap, so the bound is the larger of the two:
37
+ * the qualified streamed encoder's 256 MiB unshared heap (maxWasmBytes), which also covers the
38
+ * generator's mapping + synthesis bundle. Live sessions: mapping and synthesis (ort-worker.mjs) are the
39
+ * most held at once; the encoder holds one of its 108 sessions at a time.
40
+ */
41
+ export declare const LIVE_RESIDENCY_LIMIT: LiveResidencyLimit;
@@ -0,0 +1,48 @@
1
+ // Acquisition budgets and live residency, as named fields with their values (contracts milestone 2,
2
+ // fm-2o8q). The candidate's two-chunk phone read-ahead is per worker and does not bound overlapping
3
+ // workers, so these budgets are aggregate across workers: the per-worker candidate figure becomes the
4
+ // whole tab's figure. Values are carried from the candidate (classic a42829b); revising one is a
5
+ // contract revision, cited by the app's ceilings file.
6
+ import { E4E_MAX_WASM_BYTES } from './manifest.js';
7
+ /** Largest manifest chunk (Assets/model-cache.mjs refuses a chunk part over 16 MiB). */
8
+ export const ACQUISITION_CHUNK_MAX_BYTES = 16 * 1024 * 1024;
9
+ /**
10
+ * The fixed parts of an AcquisitionBudget per memory class. browser/ort-worker.mjs reads ahead 4 chunks
11
+ * when `navigator.deviceMemory >= 8`, else 2; model-cache.mjs hashes one chunk at a time (sha256.mjs keeps
12
+ * one chunk and a 64-byte block) and commits one unit per shard write.
13
+ */
14
+ export const ACQUISITION_BUDGETS = Object.freeze({
15
+ 'constrained-or-unknown': Object.freeze({
16
+ readAheadBytes: 2 * ACQUISITION_CHUNK_MAX_BYTES,
17
+ hashBytes: ACQUISITION_CHUNK_MAX_BYTES + 64,
18
+ writeBufferBytes: ACQUISITION_CHUNK_MAX_BYTES,
19
+ }),
20
+ ample: Object.freeze({
21
+ readAheadBytes: 4 * ACQUISITION_CHUNK_MAX_BYTES,
22
+ hashBytes: ACQUISITION_CHUNK_MAX_BYTES + 64,
23
+ writeBufferBytes: ACQUISITION_CHUNK_MAX_BYTES,
24
+ }),
25
+ });
26
+ /** The memory class from `navigator.deviceMemory` (GiB), as the candidate decides it. */
27
+ export function acquisitionMemoryClass(deviceMemoryGiB) {
28
+ return deviceMemoryGiB !== undefined && deviceMemoryGiB >= 8 ? 'ample' : 'constrained-or-unknown';
29
+ }
30
+ /**
31
+ * One owner's budget: the transfer is the bytes its consent grant still allows (never a constant), the
32
+ * rest is the memory class's fixed figure.
33
+ */
34
+ export function acquisitionBudget(memory, grantRemainingBytes) {
35
+ if (!Number.isSafeInteger(grantRemainingBytes) || grantRemainingBytes < 0)
36
+ throw new RangeError('grantRemainingBytes must be a non-negative integer byte count');
37
+ return { transferBytes: grantRemainingBytes, ...ACQUISITION_BUDGETS[memory] };
38
+ }
39
+ /**
40
+ * Aggregate live residency. Encoder and generator never overlap, so the bound is the larger of the two:
41
+ * the qualified streamed encoder's 256 MiB unshared heap (maxWasmBytes), which also covers the
42
+ * generator's mapping + synthesis bundle. Live sessions: mapping and synthesis (ort-worker.mjs) are the
43
+ * most held at once; the encoder holds one of its 108 sessions at a time.
44
+ */
45
+ export const LIVE_RESIDENCY_LIMIT = Object.freeze({
46
+ maxResidentBytes: E4E_MAX_WASM_BYTES,
47
+ maxLiveSessions: 2,
48
+ });
@@ -0,0 +1,43 @@
1
+ export type ManagerErrorCode = 'cache-miss' | 'corrupt' | 'evicted' | 'invalidated' | 'quota' | 'manifest-rejected' | 'unknown-status' | 'network';
2
+ export type ManagerError = {
3
+ readonly code: 'cache-miss';
4
+ readonly sha256: string;
5
+ readonly message: string;
6
+ } | {
7
+ readonly code: 'corrupt';
8
+ readonly sha256: string;
9
+ readonly message: string;
10
+ } | {
11
+ readonly code: 'evicted';
12
+ readonly sha256: string;
13
+ readonly message: string;
14
+ } | {
15
+ readonly code: 'invalidated';
16
+ readonly cause: import('./leases.ts').LeaseInvalidationCause;
17
+ readonly message: string;
18
+ } | {
19
+ readonly code: 'quota';
20
+ readonly requiredBytes: number;
21
+ readonly message: string;
22
+ } | {
23
+ readonly code: 'manifest-rejected';
24
+ readonly reason: import('./manifest.ts').ManifestErrorCode;
25
+ readonly message: string;
26
+ }
27
+ /** Cache or manifest state could not be read: bounded inspection or retry, never permission to fetch. */
28
+ | {
29
+ readonly code: 'unknown-status';
30
+ readonly retryable: true;
31
+ readonly message: string;
32
+ } | {
33
+ readonly code: 'network';
34
+ readonly retryable: boolean;
35
+ readonly message: string;
36
+ };
37
+ export type Result<T, E> = {
38
+ readonly ok: true;
39
+ readonly value: T;
40
+ } | {
41
+ readonly ok: false;
42
+ readonly error: E;
43
+ };
@@ -0,0 +1,2 @@
1
+ // Manager errors: one discriminated union, structured-clone safe (no Error instances cross a worker).
2
+ export {};
@@ -0,0 +1,47 @@
1
+ import type { ComputeRoute } from 'stylegan-js';
2
+ import type { AssetInventory } from './lifecycle.ts';
3
+ export type GrantPurpose = 'generate' | 'generate-and-encode' | 'prepare-encoder';
4
+ /** Who holds a share of an acquisition: a face slot, a photo crop, or speculative warming. */
5
+ export type GrantOwnerId = `${'face' | 'photo' | 'warming' | 'export'}:${string}`;
6
+ export type GrantDecision = 'approved' | 'declined' | 'cancelled' | 'revision-required';
7
+ export type AcquisitionPriority = 'foreground-required' | 'synthesis-prerequisite' | 'detector-prerequisite' | 'optional' | 'speculative-warming';
8
+ export interface GrantAsset {
9
+ readonly sha256: string;
10
+ readonly bytes: number;
11
+ readonly priority: AcquisitionPriority;
12
+ }
13
+ export interface AcquisitionGrant {
14
+ readonly manifestSha256: string;
15
+ readonly route: ComputeRoute;
16
+ readonly purpose: GrantPurpose;
17
+ readonly assets: readonly GrantAsset[];
18
+ /** Bytes still to transfer that the person was shown; the grant never covers more. */
19
+ readonly remainingBytes: number;
20
+ readonly owners: readonly GrantOwnerId[];
21
+ }
22
+ /** Speculative warming yields to every foreground priority and is cancelled first under pressure. */
23
+ export interface WarmingOwnership {
24
+ readonly owner: `warming:${string}`;
25
+ readonly priority: 'speculative-warming';
26
+ readonly yieldsTo: readonly Exclude<AcquisitionPriority, 'speculative-warming'>[];
27
+ }
28
+ /** A request is covered only by the same manifest, route and digests within the advertised bytes. */
29
+ export declare function scopeCovers(grant: AcquisitionGrant, request: {
30
+ readonly manifestSha256: string;
31
+ readonly route: ComputeRoute;
32
+ readonly assets: readonly {
33
+ readonly sha256: string;
34
+ readonly bytes: number;
35
+ }[];
36
+ }): 'covered' | 'revision-required';
37
+ export interface SharedFetch {
38
+ readonly sha256: string;
39
+ readonly owners: readonly GrantOwnerId[];
40
+ }
41
+ /** Removes `owner` from every fetch; a fetch with no owner left stops (its verified chunks are kept). */
42
+ export declare function cancelOwner(fetches: readonly SharedFetch[], owner: GrantOwnerId): {
43
+ readonly continuing: readonly SharedFetch[];
44
+ readonly stopped: readonly string[];
45
+ };
46
+ /** What may happen to an asset given its inventory and the grant decision. */
47
+ export declare function inventoryAction(inventory: AssetInventory, decision: GrantDecision): 'none' | 'fetch' | 'inspect' | 'wait-for-decision';
@@ -0,0 +1,44 @@
1
+ // Acquisition grants: what a person approved the device to download, for which purpose and owners.
2
+ //
3
+ // Approval covers deferred stages and retries within the unchanged scope only; extra or replacement
4
+ // scope needs a revised decision, and cache revalidation cannot silently inflate it. Cancelling
5
+ // releases that owner; a shared fetch stops when its last approved owner leaves; verified chunks are
6
+ // kept and cancelled transfers are never revived. Requests deduplicate by digest, and acquisition
7
+ // holds no compute permit while it waits. Unknown cache or manifest status gives bounded inspection
8
+ // or a retryable error, never permission to fetch (the candidate's unknown inventory bypassed
9
+ // gateScope). The manager supplies these primitives; the policy that uses them lives in the app.
10
+ /** A request is covered only by the same manifest, route and digests within the advertised bytes. */
11
+ export function scopeCovers(grant, request) {
12
+ if (request.manifestSha256 !== grant.manifestSha256 || request.route !== grant.route)
13
+ return 'revision-required';
14
+ const granted = new Map(grant.assets.map((a) => [a.sha256, a.bytes]));
15
+ const unique = new Map(request.assets.map((a) => [a.sha256, a.bytes]));
16
+ let bytes = 0;
17
+ for (const [sha256, size] of unique) {
18
+ if (granted.get(sha256) !== size)
19
+ return 'revision-required';
20
+ bytes += size;
21
+ }
22
+ return bytes <= grant.remainingBytes ? 'covered' : 'revision-required';
23
+ }
24
+ /** Removes `owner` from every fetch; a fetch with no owner left stops (its verified chunks are kept). */
25
+ export function cancelOwner(fetches, owner) {
26
+ const continuing = [];
27
+ const stopped = [];
28
+ for (const f of fetches) {
29
+ const owners = f.owners.filter((o) => o !== owner);
30
+ if (owners.length)
31
+ continuing.push({ sha256: f.sha256, owners });
32
+ else
33
+ stopped.push(f.sha256);
34
+ }
35
+ return { continuing, stopped };
36
+ }
37
+ /** What may happen to an asset given its inventory and the grant decision. */
38
+ export function inventoryAction(inventory, decision) {
39
+ if (inventory === 'verified-local')
40
+ return 'none';
41
+ if (inventory === 'unknown')
42
+ return 'inspect';
43
+ return decision === 'approved' ? 'fetch' : 'wait-for-decision';
44
+ }
@@ -0,0 +1,6 @@
1
+ export * from './errors.ts';
2
+ export * from './leases.ts';
3
+ export * from './lifecycle.ts';
4
+ export * from './grant.ts';
5
+ export * from './budgets.ts';
6
+ export * from './manifest.ts';
@@ -0,0 +1,7 @@
1
+ // browser-model-manager contracts (fm-hwh): lifecycle, leases, grants, budgets, manifests.
2
+ export * from './errors.js';
3
+ export * from './leases.js';
4
+ export * from './lifecycle.js';
5
+ export * from './grant.js';
6
+ export * from './budgets.js';
7
+ export * from './manifest.js';
@@ -0,0 +1,20 @@
1
+ import type { ManagerErrorCode } from './errors.ts';
2
+ export type LeaseInvalidationCause = 'browser-eviction' | 'corruption' | 'cross-tab-deletion' | 'device-loss' | 'worker-loss';
3
+ /** How the operations holding an invalidated lease end. */
4
+ export type SettlementRule =
5
+ /** Pending operations settle as failed with the mapped error; resources are released. */
6
+ 'fail-pending-and-release'
7
+ /** The handle is gone (device or worker): pending operations settle as failed and the handle is unusable. */
8
+ | 'fail-pending-and-dispose-handle';
9
+ export interface AssetLease {
10
+ readonly sha256: string;
11
+ readonly bytes: number;
12
+ /** Holders of this asset; manager eviction skips any asset whose count is above zero. */
13
+ readonly refCount: number;
14
+ release(): void;
15
+ }
16
+ /** Every cause maps to exactly one manager error and settlement rule (exhaustive by its type). */
17
+ export declare const LEASE_INVALIDATION: Readonly<Record<LeaseInvalidationCause, {
18
+ readonly error: ManagerErrorCode;
19
+ readonly settlement: SettlementRule;
20
+ }>>;