@moss-dev/moss-web 1.2.0 → 1.4.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.
@@ -1,10 +1,45 @@
1
1
  import type { ModelContentKeys, ModelKeyExchange, SealedModel, Tokenizer } from "@moss-dev/moss-wasm";
2
- import type { ModelArtifactIdentity } from "./types.js";
2
+ import type { ModelArtifactIdentity, ModelDownloadProgress } from "./types.js";
3
3
  export declare const DEFAULT_INDEX_BASE_URL = "https://service.usemoss.dev/index";
4
4
  export declare const DEFAULT_MODEL_ARTIFACT_ORIGIN = "https://models.moss.link";
5
5
  export interface SealedModelRuntime {
6
6
  newKeyExchange(): ModelKeyExchange;
7
7
  openSealedModel(bytes: Uint8Array, keys: ModelContentKeys, sku: string): SealedModel;
8
+ /**
9
+ * Opens bytes whose raw SHA-256 already matched the release entry, without
10
+ * hashing them again. Absent on @moss-dev/moss-wasm releases that predate it.
11
+ */
12
+ openMatchedSealedModel?(bytes: Uint8Array, keys: ModelContentKeys, sku: string): SealedModel;
13
+ /**
14
+ * Lets Web Crypto decrypt the model instead of wasm. Absent on
15
+ * @moss-dev/moss-wasm releases that predate the exports it needs.
16
+ */
17
+ webCrypto?: WebCryptoSealedModelRuntime;
18
+ }
19
+ /** What Web Crypto needs to decrypt the payload of a sealed model. */
20
+ export interface SealedModelDecryptParams {
21
+ iv: Uint8Array;
22
+ tag: Uint8Array;
23
+ additionalData: Uint8Array;
24
+ payloadOffset: number;
25
+ payloadLength: number;
26
+ }
27
+ /** Where the tokenizer and graph lie in a decrypted sealed model payload. */
28
+ export interface SealedModelSections {
29
+ tokenizerOffset: number;
30
+ tokenizerLength: number;
31
+ graphOffset: number;
32
+ graphLength: number;
33
+ }
34
+ /**
35
+ * The runtime exports that check a sealed model on each side of a Web Crypto
36
+ * decrypt. The content keys import themselves through `importWebCryptoKey`,
37
+ * so the raw key crosses only into `importKey`, from a buffer zeroed right after.
38
+ */
39
+ export interface WebCryptoSealedModelRuntime {
40
+ sealedModelDecryptParams(bytes: Uint8Array, keys: ModelContentKeys, sku: string): SealedModelDecryptParams;
41
+ sealedModelSections(plaintext: Uint8Array, sku: string): SealedModelSections;
42
+ sealedModelTokenizer(tokenizerJson: Uint8Array): Tokenizer;
8
43
  }
9
44
  export interface ModelDeliveryAuth {
10
45
  getAuthHeader(): Promise<string>;
@@ -17,6 +52,11 @@ export interface ModelDeliveryOptions {
17
52
  baseUrl?: string;
18
53
  artifactOrigin?: string;
19
54
  fetch?: typeof fetch;
55
+ onProgress?: (progress: ModelDownloadProgress) => void;
56
+ /** Cache API storage for the verified model file. `null` turns caching off; unset uses `globalThis.caches`. */
57
+ caches?: CacheStorage | null;
58
+ /** How long the grant request, or an artifact response or its next chunk, may take before it is aborted. */
59
+ requestTimeoutMs?: number;
20
60
  }
21
61
  export interface GrantedObject {
22
62
  url: string;
@@ -44,6 +84,8 @@ export declare class ModelDeliveryError extends Error {
44
84
  interface ArtifactOrigin {
45
85
  protocol: string;
46
86
  host: string;
87
+ hostname: string;
88
+ port: string;
47
89
  }
48
90
  interface ReleaseFile {
49
91
  relativePath: string;
@@ -54,7 +96,22 @@ export declare function parseArtifactOrigin(value: string): ArtifactOrigin;
54
96
  export declare function parseModelDeliveryGrant(json: string, sku: string, artifactOrigin?: string): ModelDeliveryGrant;
55
97
  export declare function grantAcceptsStamp(grant: ModelDeliveryGrant, stamped: ModelArtifactIdentity): boolean;
56
98
  export declare function requestModelDeliveryGrant(options: ModelDeliveryOptions, sku: string, capabilityQuery: string): Promise<ModelDeliveryGrant>;
57
- export declare function fetchGrantedBytes(fetchFn: typeof fetch, object: GrantedObject, maxBytes?: number): Promise<Uint8Array>;
99
+ export interface ArtifactTransfer {
100
+ /** The transfer aborts as soon as more bytes than this arrive. */
101
+ maxBytes: number;
102
+ /** Writes the body into one buffer of exactly `maxBytes` bytes. A shorter body is retried. */
103
+ preallocate?: boolean;
104
+ /** Receives the running byte count of the current attempt after each chunk. */
105
+ onBytes?: (loadedBytes: number) => void;
106
+ timeoutMs?: number;
107
+ }
108
+ /**
109
+ * Streams one granted artifact into memory.
110
+ *
111
+ * Each attempt aborts when the response or the next chunk takes longer than
112
+ * the deadline. A stall, a network error, a 408, a 429 or a 5xx is retried once.
113
+ */
114
+ export declare function fetchGrantedBytes(fetchFn: typeof fetch, object: GrantedObject, transfer: ArtifactTransfer): Promise<Uint8Array>;
58
115
  export declare function verifyReleaseManifest(releaseBytes: Uint8Array, grant: ModelDeliveryGrant): Promise<ReleaseFile>;
59
116
  export declare function verifyModelBytes(bytes: Uint8Array, record: ReleaseFile): Promise<void>;
60
117
  export declare function loadSealedModel(options: ModelDeliveryOptions, stamped: ModelArtifactIdentity): Promise<SealedModelBundle>;
@@ -7,6 +7,10 @@ const RELEASE_FILE = "release.json";
7
7
  const MODEL_FILE = "model.mossml";
8
8
  const SUPPORTED_RELEASE_SCHEMA_VERSIONS = [1, 2];
9
9
  const MAX_RELEASE_MANIFEST_BYTES = 1024 * 1024;
10
+ const DEFAULT_REQUEST_TIMEOUT_MS = 30000;
11
+ const ARTIFACT_REQUEST_ATTEMPTS = 2;
12
+ const ARTIFACT_CACHE_NAME = "moss-model-artifacts-v1";
13
+ const ARTIFACT_CACHE_PATH = "/.moss-artifact-cache";
10
14
  export class ModelDeliveryError extends Error {
11
15
  constructor(message, status, code) {
12
16
  super(message);
@@ -15,6 +19,9 @@ export class ModelDeliveryError extends Error {
15
19
  this.code = code;
16
20
  }
17
21
  }
22
+ /** A transport failure worth one more attempt: a stall, a dropped connection, a short body, a 408, a 429 or a 5xx. */
23
+ class ArtifactTransferError extends ModelDeliveryError {
24
+ }
18
25
  function isCanonicalSha256(value) {
19
26
  return /^[0-9a-f]{64}$/.test(value);
20
27
  }
@@ -39,7 +46,12 @@ export function parseArtifactOrigin(value) {
39
46
  if (url.pathname !== "/" || url.search || url.hash || url.username || url.password) {
40
47
  throw new ModelDeliveryError("Model artifact origin must be scheme://host[:port] only");
41
48
  }
42
- return { protocol: url.protocol, host: url.host.toLowerCase() };
49
+ return {
50
+ protocol: url.protocol,
51
+ host: url.host.toLowerCase(),
52
+ hostname: url.hostname.toLowerCase(),
53
+ port: url.port,
54
+ };
43
55
  }
44
56
  function validateGrantedUrl(url, origin, sku, version, object) {
45
57
  let parsed;
@@ -50,15 +62,22 @@ function validateGrantedUrl(url, origin, sku, version, object) {
50
62
  throw new ModelDeliveryError(`${object} url is not valid: ${String(error)}`);
51
63
  }
52
64
  const expectedPath = `${ARTIFACTS_PREFIX}/${sku}/${version}/${object}`;
53
- if (parsed.protocol !== origin.protocol
54
- || parsed.host.toLowerCase() !== origin.host
55
- || parsed.pathname !== expectedPath
56
- || parsed.search
57
- || parsed.hash
58
- || parsed.username
59
- || parsed.password) {
60
- throw new ModelDeliveryError(`${object} url on ${parsed.host} is outside ${origin.protocol}//${origin.host}${expectedPath}`);
61
- }
65
+ let mismatch;
66
+ if (parsed.protocol !== origin.protocol)
67
+ mismatch = "scheme";
68
+ else if (parsed.hostname.toLowerCase() !== origin.hostname)
69
+ mismatch = "host";
70
+ else if (parsed.port !== origin.port)
71
+ mismatch = "port";
72
+ else if (parsed.pathname !== expectedPath)
73
+ mismatch = "path";
74
+ else if (parsed.search || parsed.hash)
75
+ mismatch = "query or fragment";
76
+ else if (parsed.username || parsed.password)
77
+ mismatch = "userinfo";
78
+ else
79
+ return;
80
+ throw new ModelDeliveryError(`${object} url ${mismatch} does not match the artifact location on ${origin.hostname}`);
62
81
  }
63
82
  function grantedObject(value, name) {
64
83
  if (!value || typeof value !== "object") {
@@ -129,40 +148,242 @@ export async function requestModelDeliveryGrant(options, sku, capabilityQuery) {
129
148
  const fetchFn = options.fetch ?? fetch;
130
149
  const baseUrl = (options.baseUrl ?? DEFAULT_INDEX_BASE_URL).replace(/\/+$/, "");
131
150
  const url = `${baseUrl}/model-artifacts/download?${capabilityQuery}`;
132
- const send = async (authHeader) => fetchFn(url, {
133
- method: "GET",
134
- headers: { Authorization: authHeader, "x-project-id": options.projectId },
135
- credentials: "omit",
136
- });
137
- let response = await send(await options.auth.getAuthHeader());
138
- if (response.status === 401) {
139
- await options.auth.invalidate();
151
+ const timeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
152
+ let deadline;
153
+ let timer;
154
+ const send = (authHeader) => {
155
+ clearTimeout(timer);
156
+ const controller = new AbortController();
157
+ deadline = controller;
158
+ timer = setTimeout(() => controller.abort(), timeoutMs);
159
+ return fetchFn(url, {
160
+ method: "GET",
161
+ headers: { Authorization: authHeader, "x-project-id": options.projectId },
162
+ credentials: "omit",
163
+ signal: controller.signal,
164
+ });
165
+ };
166
+ let response;
167
+ let body;
168
+ try {
140
169
  response = await send(await options.auth.getAuthHeader());
170
+ if (response.status === 401) {
171
+ response.body?.cancel().catch(() => undefined);
172
+ await options.auth.invalidate();
173
+ response = await send(await options.auth.getAuthHeader());
174
+ }
175
+ body = response.ok
176
+ ? await response.text()
177
+ : await response.text().catch((error) => {
178
+ if (deadline?.signal.aborted)
179
+ throw error;
180
+ return "";
181
+ });
182
+ }
183
+ catch (error) {
184
+ if (!deadline?.signal.aborted)
185
+ throw error;
186
+ throw new ModelDeliveryError(`Model grant request for '${sku}' got no answer within ${timeoutMs} ms`);
187
+ }
188
+ finally {
189
+ clearTimeout(timer);
141
190
  }
142
191
  if (!response.ok) {
143
- const body = await response.text().catch(() => "");
144
192
  const code = issuerErrorCode(body);
145
193
  const hint = code === "MODEL_ARTIFACT_UNAVAILABLE" || code === "MODEL_ARTIFACT_ENCRYPTED_UNAVAILABLE"
146
194
  ? "; no sealed model artifact is published for this model yet"
147
195
  : "";
148
196
  throw new ModelDeliveryError(`Issuer refused the sealed model grant for '${sku}' (HTTP ${response.status} ${code})${hint}; no plaintext fallback`, response.status, code);
149
197
  }
150
- return parseModelDeliveryGrant(await response.text(), sku, options.artifactOrigin);
198
+ return parseModelDeliveryGrant(body, sku, options.artifactOrigin);
199
+ }
200
+ /**
201
+ * Streams one granted artifact into memory.
202
+ *
203
+ * Each attempt aborts when the response or the next chunk takes longer than
204
+ * the deadline. A stall, a network error, a 408, a 429 or a 5xx is retried once.
205
+ */
206
+ export async function fetchGrantedBytes(fetchFn, object, transfer) {
207
+ for (let attempt = 1;; attempt += 1) {
208
+ try {
209
+ return await fetchGrantedBytesOnce(fetchFn, object, transfer);
210
+ }
211
+ catch (error) {
212
+ if (!(error instanceof ArtifactTransferError) || attempt >= ARTIFACT_REQUEST_ATTEMPTS) {
213
+ throw error;
214
+ }
215
+ }
216
+ }
151
217
  }
152
- export async function fetchGrantedBytes(fetchFn, object, maxBytes) {
153
- const response = await fetchFn(object.url, {
218
+ async function fetchGrantedBytesOnce(fetchFn, object, transfer) {
219
+ const timeoutMs = transfer.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
220
+ const artifact = artifactLabel(object.url);
221
+ const controller = new AbortController();
222
+ const network = async (step, failure) => {
223
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
224
+ try {
225
+ return await step();
226
+ }
227
+ catch (error) {
228
+ throw new ArtifactTransferError(controller.signal.aborted
229
+ ? `Fetching ${artifact} stalled: nothing arrived for ${timeoutMs} ms`
230
+ : `${failure}: ${String(error)}`);
231
+ }
232
+ finally {
233
+ clearTimeout(timer);
234
+ }
235
+ };
236
+ const response = await network(() => fetchFn(object.url, {
154
237
  method: "GET",
155
238
  headers: { Authorization: `Bearer ${object.capability}` },
156
239
  credentials: "omit",
157
- });
240
+ signal: controller.signal,
241
+ }), `Failed to fetch ${artifact}`);
158
242
  if (!response.ok) {
159
- throw new ModelDeliveryError(`Failed to fetch '${object.url}': ${response.status}`, response.status);
243
+ response.body?.cancel().catch(() => undefined);
244
+ const message = `Failed to fetch ${artifact}: ${response.status}`;
245
+ const transient = response.status >= 500 || response.status === 408 || response.status === 429;
246
+ throw transient
247
+ ? new ArtifactTransferError(message, response.status)
248
+ : new ModelDeliveryError(message, response.status);
249
+ }
250
+ return await readArtifactBody(response, artifact, transfer, network);
251
+ }
252
+ async function readArtifactBody(response, artifact, transfer, network) {
253
+ const target = transfer.preallocate ? new Uint8Array(transfer.maxBytes) : null;
254
+ const chunks = [];
255
+ let loaded = 0;
256
+ const finish = () => {
257
+ if (target && loaded < transfer.maxBytes) {
258
+ throw new ArtifactTransferError(`${artifact} has an unexpected size: the transfer ended after ${loaded} of ${transfer.maxBytes} bytes`);
259
+ }
260
+ return target ?? joinChunks(chunks, loaded);
261
+ };
262
+ if (!response.body)
263
+ return finish();
264
+ const reader = response.body.getReader();
265
+ try {
266
+ for (;;) {
267
+ const next = await network(() => reader.read(), `Transfer of ${artifact} failed`);
268
+ if (next.done)
269
+ break;
270
+ const chunk = next.value;
271
+ if (loaded + chunk.byteLength > transfer.maxBytes) {
272
+ throw new ModelDeliveryError(`${artifact} exceeds ${transfer.maxBytes} bytes`);
273
+ }
274
+ if (target)
275
+ target.set(chunk, loaded);
276
+ else
277
+ chunks.push(chunk);
278
+ loaded += chunk.byteLength;
279
+ transfer.onBytes?.(loaded);
280
+ }
160
281
  }
161
- const bytes = new Uint8Array(await response.arrayBuffer());
162
- if (maxBytes !== undefined && bytes.byteLength > maxBytes) {
163
- throw new ModelDeliveryError(`'${object.url}' exceeds ${maxBytes} bytes`);
282
+ catch (error) {
283
+ reader.cancel().catch(() => undefined);
284
+ throw error;
285
+ }
286
+ return finish();
287
+ }
288
+ /** The file name and host of a granted artifact URL, the only parts of it kept in error text. */
289
+ function artifactLabel(url) {
290
+ try {
291
+ const parsed = new URL(url);
292
+ const file = parsed.pathname.slice(parsed.pathname.lastIndexOf("/") + 1);
293
+ return `'${file}' from ${parsed.host}`;
294
+ }
295
+ catch {
296
+ return "the model artifact";
297
+ }
298
+ }
299
+ function joinChunks(chunks, length) {
300
+ if (chunks.length === 1)
301
+ return chunks[0];
302
+ const joined = new Uint8Array(length);
303
+ let offset = 0;
304
+ for (const chunk of chunks) {
305
+ joined.set(chunk, offset);
306
+ offset += chunk.byteLength;
307
+ }
308
+ return joined;
309
+ }
310
+ /**
311
+ * Verified model files in the Cache API, keyed by the release manifest digest.
312
+ *
313
+ * Every read is verified again by the caller. Caching is best effort: storage that
314
+ * is missing, as in Node or an insecure context, or that fails, turns into a miss.
315
+ */
316
+ class ArtifactCache {
317
+ constructor(storage, origin) {
318
+ this.cache = null;
319
+ this.storage = storage;
320
+ this.prefix = `${origin.protocol}//${origin.host}${ARTIFACT_CACHE_PATH}/`;
321
+ }
322
+ key(sku, manifestSha256) {
323
+ return `${this.prefix}${sku}/${manifestSha256}/${MODEL_FILE}`;
324
+ }
325
+ async read(key) {
326
+ try {
327
+ const response = await (await this.open())?.match(key);
328
+ return response ? new Uint8Array(await response.arrayBuffer()) : null;
329
+ }
330
+ catch {
331
+ return null;
332
+ }
333
+ }
334
+ async write(key, bytes) {
335
+ if (!this.storage)
336
+ return;
337
+ try {
338
+ const response = new Response(bytes, {
339
+ headers: { "content-type": "application/octet-stream" },
340
+ });
341
+ await (await this.open())?.put(key, response);
342
+ }
343
+ catch {
344
+ // A full or unavailable cache only costs a download on the next page load.
345
+ }
346
+ }
347
+ async remove(key) {
348
+ try {
349
+ await (await this.open())?.delete(key);
350
+ }
351
+ catch {
352
+ // A stale entry that cannot be removed fails verification again on the next read.
353
+ }
354
+ }
355
+ /** Drops the artifacts of every other release of this model. */
356
+ async pruneOtherReleases(sku, manifestSha256) {
357
+ try {
358
+ const cache = await this.open();
359
+ if (!cache)
360
+ return;
361
+ const modelPrefix = `${this.prefix}${sku}/`;
362
+ const keep = `${modelPrefix}${manifestSha256}/`;
363
+ for (const request of await cache.keys()) {
364
+ if (request.url.startsWith(modelPrefix) && !request.url.startsWith(keep)) {
365
+ await cache.delete(request);
366
+ }
367
+ }
368
+ }
369
+ catch {
370
+ // Leftover releases are only a storage cost.
371
+ }
372
+ }
373
+ open() {
374
+ if (!this.storage)
375
+ return Promise.resolve(null);
376
+ this.cache ?? (this.cache = this.storage.open(ARTIFACT_CACHE_NAME).catch(() => null));
377
+ return this.cache;
378
+ }
379
+ }
380
+ function defaultCacheStorage() {
381
+ try {
382
+ return globalThis.caches ?? undefined;
383
+ }
384
+ catch {
385
+ return undefined;
164
386
  }
165
- return bytes;
166
387
  }
167
388
  function parseReleaseFiles(value) {
168
389
  if (!Array.isArray(value)) {
@@ -259,21 +480,124 @@ export async function loadSealedModel(options, stamped) {
259
480
  exchange.free();
260
481
  }
261
482
  try {
262
- const releaseBytes = await fetchGrantedBytes(fetchFn, grant.release, MAX_RELEASE_MANIFEST_BYTES);
483
+ const cache = new ArtifactCache(options.caches === undefined ? defaultCacheStorage() : options.caches ?? undefined, parseArtifactOrigin(options.artifactOrigin ?? DEFAULT_MODEL_ARTIFACT_ORIGIN));
484
+ const releaseBytes = await fetchGrantedBytes(fetchFn, grant.release, {
485
+ maxBytes: MAX_RELEASE_MANIFEST_BYTES,
486
+ timeoutMs: options.requestTimeoutMs,
487
+ });
263
488
  const record = await verifyReleaseManifest(releaseBytes, grant);
264
- const modelBytes = await fetchGrantedBytes(fetchFn, grant.model);
265
- await verifyModelBytes(modelBytes, record);
266
- const sealed = options.runtime.openSealedModel(modelBytes, keys, sku);
267
- try {
268
- const graph = sealed.takeGraph();
269
- const tokenizer = sealed.takeTokenizer();
270
- return { grant, graph, tokenizer };
271
- }
272
- finally {
273
- sealed.free();
274
- }
489
+ const model = await loadModelFile(options, fetchFn, cache, grant, record);
490
+ const opened = await openWithWebCrypto(options.runtime, model.bytes, keys, sku)
491
+ ?? openInWasm(options.runtime, model.bytes, keys, sku);
492
+ model.persist?.();
493
+ return { grant, ...opened };
275
494
  }
276
495
  finally {
277
496
  keys.free();
278
497
  }
279
498
  }
499
+ /** The message the wasm runtime gives when the AES-GCM tag does not match. */
500
+ const DECRYPT_FAILED = "mossml payload decryption failed";
501
+ /**
502
+ * Opens a sealed model with the AES-GCM of Web Crypto, which runs in native code.
503
+ *
504
+ * Returns null, and the wasm runtime opens the model, when the runtime, the keys
505
+ * or the context lack what this path needs, or when Web Crypto cannot import the
506
+ * key or run the decrypt. A tag that does not match fails the load, as in wasm.
507
+ * The graph is a view of the plaintext, and every byte before it is zeroed first.
508
+ */
509
+ async function openWithWebCrypto(runtime, bytes, keys, sku) {
510
+ const webCrypto = runtime.webCrypto;
511
+ const subtle = globalThis.crypto?.subtle;
512
+ const contentKeys = keys;
513
+ if (!webCrypto || !subtle || typeof contentKeys.importWebCryptoKey !== "function") {
514
+ return null;
515
+ }
516
+ const params = webCrypto.sealedModelDecryptParams(bytes, keys, sku);
517
+ const importing = contentKeys.importWebCryptoKey().catch(() => null);
518
+ const { payloadOffset, payloadLength, tag } = params;
519
+ const sealed = new Uint8Array(payloadLength + tag.byteLength);
520
+ sealed.set(bytes.subarray(payloadOffset, payloadOffset + payloadLength));
521
+ sealed.set(tag, payloadLength);
522
+ const key = await importing;
523
+ if (!key)
524
+ return null;
525
+ let plaintext;
526
+ try {
527
+ plaintext = new Uint8Array(await subtle.decrypt({
528
+ name: "AES-GCM",
529
+ iv: params.iv,
530
+ additionalData: params.additionalData,
531
+ tagLength: 128,
532
+ }, key, sealed));
533
+ }
534
+ catch (error) {
535
+ if (error?.name === "OperationError") {
536
+ throw new ModelDeliveryError(DECRYPT_FAILED);
537
+ }
538
+ return null;
539
+ }
540
+ try {
541
+ const sections = webCrypto.sealedModelSections(plaintext, sku);
542
+ const { tokenizerOffset, tokenizerLength, graphOffset, graphLength } = sections;
543
+ const tokenizer = webCrypto.sealedModelTokenizer(plaintext.subarray(tokenizerOffset, tokenizerOffset + tokenizerLength));
544
+ plaintext.fill(0, 0, graphOffset);
545
+ return { graph: plaintext.subarray(graphOffset, graphOffset + graphLength), tokenizer };
546
+ }
547
+ catch (error) {
548
+ plaintext.fill(0);
549
+ throw error;
550
+ }
551
+ }
552
+ function openInWasm(runtime, bytes, keys, sku) {
553
+ const sealed = runtime.openMatchedSealedModel
554
+ ? runtime.openMatchedSealedModel(bytes, keys, sku)
555
+ : runtime.openSealedModel(bytes, keys, sku);
556
+ try {
557
+ const graph = sealed.takeGraph();
558
+ const tokenizer = sealed.takeTokenizer();
559
+ return { graph, tokenizer };
560
+ }
561
+ finally {
562
+ sealed.free();
563
+ }
564
+ }
565
+ async function loadModelFile(options, fetchFn, cache, grant, record) {
566
+ const report = (loadedBytes, fromCache) => {
567
+ try {
568
+ options.onProgress?.({
569
+ modelId: grant.modelId,
570
+ loadedBytes,
571
+ totalBytes: record.sizeBytes,
572
+ fromCache,
573
+ });
574
+ }
575
+ catch {
576
+ // A failing progress callback must not fail the model load.
577
+ }
578
+ };
579
+ const manifestSha256 = grant.identity.manifestSha256;
580
+ const key = cache.key(grant.modelId, manifestSha256);
581
+ const cached = await cache.read(key);
582
+ if (cached) {
583
+ try {
584
+ await verifyModelBytes(cached, record);
585
+ report(cached.byteLength, true);
586
+ return { bytes: cached };
587
+ }
588
+ catch {
589
+ await cache.remove(key);
590
+ }
591
+ }
592
+ const bytes = await fetchGrantedBytes(fetchFn, grant.model, {
593
+ maxBytes: record.sizeBytes,
594
+ preallocate: true,
595
+ timeoutMs: options.requestTimeoutMs,
596
+ onBytes: (loaded) => report(loaded, false),
597
+ });
598
+ await verifyModelBytes(bytes, record);
599
+ const persist = () => {
600
+ void cache.write(key, bytes).then(() => cache.pruneOtherReleases(grant.modelId, manifestSha256));
601
+ };
602
+ return { bytes, persist };
603
+ }
package/dist/types.d.ts CHANGED
@@ -5,6 +5,21 @@ export interface MossClientOptions {
5
5
  wasmUrl?: string;
6
6
  onnxWasmPath?: string;
7
7
  modelArtifactOrigin?: string;
8
+ /**
9
+ * Called while the embedding model that text queries need is loaded, as bytes arrive.
10
+ * An error thrown here is ignored and does not stop the load.
11
+ */
12
+ onProgress?: (progress: ModelDownloadProgress) => void;
13
+ }
14
+ /** Progress of the embedding model file that the first text query waits on. */
15
+ export interface ModelDownloadProgress {
16
+ modelId: MossModel;
17
+ /** Bytes of the model file received so far. Starts again from 0 when a stalled request is retried. */
18
+ loadedBytes: number;
19
+ /** Size of the model file in bytes, as the verified release manifest records it. */
20
+ totalBytes: number;
21
+ /** True when the verified file came from the browser Cache API and no transfer took place. */
22
+ fromCache: boolean;
8
23
  }
9
24
  export interface ModelRef {
10
25
  id: string;
@@ -31,6 +46,13 @@ export interface QueryResultDocumentInfo {
31
46
  id: string;
32
47
  text: string;
33
48
  metadata?: Record<string, string>;
49
+ /**
50
+ * Relevance to the query from 0 to 1. It comes from vector similarity
51
+ * alone, so `alpha` and rank never change it. Results are ordered by hybrid
52
+ * relevance, so a lower result can show a higher score. A keyword-only query
53
+ * (`alpha` 0, or an index without vectors) scores every hit 0. Scores
54
+ * depend on the embedding model.
55
+ */
34
56
  score: number;
35
57
  /** Source index. Set on multi-index results; absent for single-index. */
36
58
  indexName?: string;
@@ -45,7 +67,22 @@ export interface QueryOptions {
45
67
  topK?: number;
46
68
  alpha?: number;
47
69
  filter?: MetadataFilter;
48
- }
70
+ /**
71
+ * How many hits a hybrid query (`alpha` between 0 and 1) ranks on each
72
+ * signal before fusion. A hit outside both lists is never returned, so a
73
+ * deeper list raises recall and query time. Defaults to `2 * topK`. A set
74
+ * value must be at least 1 and is raised to `topK` when below it.
75
+ * Keyword-only and vector-only queries (`alpha` 0 or 1) ignore it.
76
+ */
77
+ candidateDepth?: number;
78
+ }
79
+ /**
80
+ * A metadata filter: one field condition, or an `$and` / `$or` of filters.
81
+ *
82
+ * A field condition never matches a document that lacks the field, whatever
83
+ * its operator, `$ne` and `$nin` included. A misspelled field name therefore
84
+ * matches nothing rather than raising an error.
85
+ */
49
86
  export type MetadataFilter = {
50
87
  field: string;
51
88
  condition: FilterCondition;
@@ -54,6 +91,15 @@ export type MetadataFilter = {
54
91
  } | {
55
92
  $or: MetadataFilter[];
56
93
  };
94
+ /**
95
+ * A condition on one metadata field. Metadata values are strings.
96
+ *
97
+ * `$gt`, `$gte`, `$lt` and `$lte` compare two plain decimals (`"42"`, `"-3.5"`)
98
+ * as numbers and two other values character by character as text. They never
99
+ * match a plain decimal against any other value, such as `"007"`, `"1e3"` or `"NaN"`.
100
+ * `$near` takes `"lat,lng,maxDistanceMeters"`, such as `"40.7580,-73.9855,5000"`, and
101
+ * matches a `"lat,lng"` field value. Any other `$near` value makes the query fail.
102
+ */
57
103
  export type FilterCondition = {
58
104
  $eq: string | number;
59
105
  } | {
@@ -71,12 +117,13 @@ export type FilterCondition = {
71
117
  } | {
72
118
  $nin: (string | number)[];
73
119
  } | {
74
- $near: string | number;
120
+ $near: string;
75
121
  };
76
122
  export interface RefreshResult {
77
123
  indexName: string;
78
124
  previousUpdatedAt: string;
79
125
  newUpdatedAt: string;
126
+ /** False when the cloud snapshot was no newer than the loaded one and nothing was downloaded. */
80
127
  wasUpdated: boolean;
81
128
  modelId?: string;
82
129
  modelArtifactVersion?: string;
@@ -95,10 +142,22 @@ export interface MutationResult {
95
142
  }
96
143
  export interface CreateIndexOptions {
97
144
  modelId?: MossModel | "custom";
145
+ /**
146
+ * Called with each job status the client polls until the build finishes.
147
+ * An exception it throws, or a rejection of a promise it returns, is ignored.
148
+ */
98
149
  onProgress?: (progress: JobProgress) => void;
99
150
  }
100
151
  export interface MutationOptions {
152
+ /**
153
+ * Whether a document replaces a stored one with the same ID.
154
+ * `addDocs` sends it only when set, `deleteDocs` ignores it, and the cloud service decides how to apply it.
155
+ */
101
156
  upsert?: boolean;
157
+ /**
158
+ * Called with each job status the client polls until the job finishes.
159
+ * An exception it throws, or a rejection of a promise it returns, is ignored.
160
+ */
102
161
  onProgress?: (progress: JobProgress) => void;
103
162
  }
104
163
  export interface ParseFileInput {
@@ -128,12 +187,23 @@ export interface GetDocumentsOptions {
128
187
  docIds?: string[];
129
188
  }
130
189
  export interface LoadIndexOptions {
190
+ /**
191
+ * Refresh the index from the cloud on a timer until it is unloaded.
192
+ * Off, with one warning, on a `@moss-dev/moss-wasm` that downloads the whole index on every refresh.
193
+ */
131
194
  autoRefresh?: boolean;
195
+ /**
196
+ * Seconds between auto refreshes, 600 when unset or 0.
197
+ * A negative or non-finite value is rejected. Other values below 1 use 1,
198
+ * and values above 2147483 (the longest browser timer, about 24 days) use 2147483.
199
+ */
132
200
  pollingIntervalInSeconds?: number;
133
201
  }
134
202
  /** Outcome of a bulk load. Indexes that succeed are kept even if others fail. */
135
203
  export interface LoadIndexesResult {
136
204
  loaded: string[];
137
205
  failed: Record<string, string>;
206
+ /** Stable error code per failed index, such as `NOT_FOUND` or `NETWORK`, when the failure carries one. */
207
+ failedCodes?: Record<string, string>;
138
208
  }
139
209
  export type ISODate = string;