@moss-dev/moss-web 1.0.1 → 1.3.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.
package/dist/client.js CHANGED
@@ -1,28 +1,52 @@
1
- import wasmInit, { IndexManager, ManageClient, Tokenizer as WasmTokenizer, poolAndNormalize, } from "@moss-dev/moss-wasm";
2
- import { Embedder } from "./embedder";
3
- import { resolveQueryModel } from "./query-model";
1
+ import wasmInit, { IndexManager, ManageClient, ModelKeyExchange, ProjectKeyAuthenticator, openSealedModel, poolAndNormalize, } from "@moss-dev/moss-wasm";
2
+ import { CachingAuthenticator } from "./auth/caching.authenticator.js";
3
+ import { Embedder } from "./embedder.js";
4
+ import { ModelArtifactOwnership } from "./model-artifact-ownership.js";
5
+ import { exactModelArtifactIdentity, provenanceAwareIndexManager, queryWithResolvedModelIdentity, requireMultiIndexIndexManager, requireProvenanceAwareIndexManager, runtimeQueryTuning, } from "./wasm-runtime-capability.js";
4
6
  const DEFAULT_MODEL = "moss-minilm";
7
+ function sameModelArtifactIdentity(left, right) {
8
+ if (left === null || right === null)
9
+ return left === right;
10
+ return left.modelId === right.modelId
11
+ && left.version === right.version
12
+ && left.manifestSha256 === right.manifestSha256;
13
+ }
14
+ /** True for a query with no text to match: empty or only whitespace. */
15
+ function isBlankQuery(query) {
16
+ return query.trim().length === 0;
17
+ }
5
18
  export class MossClient {
6
- constructor(projectId, projectKey, options) {
19
+ constructor(projectId, auth, options) {
7
20
  this.initialized = false;
8
21
  this.indexManager = null;
9
22
  this.manageClient = null;
10
- this.defaultModel = DEFAULT_MODEL;
11
- this.embedders = new Map();
12
- // Model id each loaded index was built with, so queries embed with the matching model
13
- this.indexModels = new Map();
23
+ this.embedder = null;
24
+ this.projectKeyAuthenticator = null;
14
25
  this.initPromise = null;
26
+ this.modelArtifacts = new ModelArtifactOwnership((identities) => {
27
+ this.embedder?.retainModelArtifacts(identities);
28
+ });
15
29
  this.projectId = projectId;
16
- this.projectKey = projectKey;
30
+ if (typeof auth === "string") {
31
+ this.projectKey = auth;
32
+ this.authenticator = null;
33
+ }
34
+ else {
35
+ this.projectKey = null;
36
+ this.authenticator = new CachingAuthenticator(auth);
37
+ }
17
38
  this.options = options ?? {};
18
39
  }
19
- /**
20
- * Create and initialize a new MossClient instance.
21
- * This is the recommended way to create a client as it ensures
22
- * the WASM modules are loaded before returning.
23
- */
24
- static async create(projectId, projectKey, options) {
25
- const client = new MossClient(projectId, projectKey, options);
40
+ async getAuthToken() {
41
+ if (!this.authenticator) {
42
+ throw new Error("getAuthToken() requires a custom IAuthenticator; the projectKey path exchanges tokens inside the WASM runtime");
43
+ }
44
+ return this.authenticator.getAuthToken();
45
+ }
46
+ static async create(projectId, auth, options) {
47
+ const client = typeof auth === "string"
48
+ ? new MossClient(projectId, auth, options)
49
+ : new MossClient(projectId, auth, options);
26
50
  await client.ensureInitialized();
27
51
  return client;
28
52
  }
@@ -36,51 +60,42 @@ export class MossClient {
36
60
  }
37
61
  async doInit() {
38
62
  await wasmInit(this.options.wasmUrl);
39
- if (this.options.baseUrl) {
40
- this.indexManager = IndexManager.withBaseUrl(this.projectId, this.projectKey, this.options.baseUrl);
41
- this.manageClient = ManageClient.withBaseUrl(this.projectId, this.projectKey, this.options.baseUrl);
63
+ let deliveryAuth;
64
+ if (this.authenticator) {
65
+ const auth = this.authenticator;
66
+ const getAuthHeader = () => auth.getAuthHeader();
67
+ const invalidate = () => auth.invalidate();
68
+ deliveryAuth = { getAuthHeader, invalidate };
69
+ this.indexManager = IndexManager.withAuthenticator(this.projectId, getAuthHeader, invalidate, this.options.baseUrl);
70
+ this.manageClient = ManageClient.withAuthenticator(this.projectId, getAuthHeader, invalidate, this.options.baseUrl);
42
71
  }
43
72
  else {
44
- this.indexManager = new IndexManager(this.projectId, this.projectKey);
45
- this.manageClient = new ManageClient(this.projectId, this.projectKey);
46
- }
47
- this.defaultModel = this.options.model ?? DEFAULT_MODEL;
48
- await this.getEmbedder(this.defaultModel);
49
- this.initialized = true;
50
- }
51
- async getEmbedder(model) {
52
- let embedder = this.embedders.get(model);
53
- if (!embedder) {
54
- embedder = new Embedder(model, WasmTokenizer, poolAndNormalize);
55
- this.embedders.set(model, embedder);
56
- try {
57
- await embedder.init(this.options.onnxWasmPath);
73
+ const projectKeyAuth = new ProjectKeyAuthenticator(this.projectId, this.projectKey);
74
+ this.projectKeyAuthenticator = projectKeyAuth;
75
+ deliveryAuth = {
76
+ getAuthHeader: () => projectKeyAuth.getAuthHeader(),
77
+ invalidate: () => projectKeyAuth.invalidate(),
78
+ };
79
+ if (this.options.baseUrl) {
80
+ this.indexManager = IndexManager.withBaseUrl(this.projectId, this.projectKey, this.options.baseUrl);
81
+ this.manageClient = ManageClient.withBaseUrl(this.projectId, this.projectKey, this.options.baseUrl);
58
82
  }
59
- catch (err) {
60
- this.embedders.delete(model);
61
- embedder.dispose();
62
- throw err;
83
+ else {
84
+ this.indexManager = new IndexManager(this.projectId, this.projectKey);
85
+ this.manageClient = new ManageClient(this.projectId, this.projectKey);
63
86
  }
64
87
  }
65
- else {
66
- await embedder.init(this.options.onnxWasmPath);
67
- }
68
- return embedder;
69
- }
70
- async resolveIndexModel(indexName) {
71
- const cached = this.indexModels.get(indexName);
72
- if (cached !== undefined)
73
- return cached;
74
- try {
75
- const info = (await this.indexManager.getIndexInfo(indexName));
76
- const modelId = info?.model?.id ?? null;
77
- this.indexModels.set(indexName, modelId);
78
- return modelId;
79
- }
80
- catch {
81
- // Index not loaded or info unavailable; fall back to the configured model
82
- return null;
83
- }
88
+ const model = this.options.model ?? DEFAULT_MODEL;
89
+ this.embedder = new Embedder(model, poolAndNormalize, {
90
+ projectId: this.projectId,
91
+ auth: deliveryAuth,
92
+ runtime: { newKeyExchange: () => new ModelKeyExchange(), openSealedModel },
93
+ baseUrl: this.options.baseUrl,
94
+ artifactOrigin: this.options.modelArtifactOrigin,
95
+ onProgress: this.options.onProgress,
96
+ });
97
+ await this.embedder.init(this.options.onnxWasmPath);
98
+ this.initialized = true;
84
99
  }
85
100
  async getIndexManager() {
86
101
  await this.ensureInitialized();
@@ -94,12 +109,13 @@ export class MossClient {
94
109
  async createIndex(indexName, docs, options) {
95
110
  const manage = await this.getManageClient();
96
111
  const hasEmbeddings = docs.some((d) => Array.isArray(d.embedding) && d.embedding.length > 0);
97
- const modelId = options?.modelId ?? (hasEmbeddings ? "custom" : DEFAULT_MODEL);
112
+ const modelId = options?.modelId
113
+ ?? (hasEmbeddings ? "custom" : (this.options.model ?? DEFAULT_MODEL));
98
114
  return manage.createIndex(indexName, docs, modelId);
99
115
  }
100
116
  async createIndexFromFiles(indexName, files, options) {
101
117
  const manage = await this.getManageClient();
102
- const modelId = options?.modelId ?? DEFAULT_MODEL;
118
+ const modelId = options?.modelId ?? (this.options.model ?? DEFAULT_MODEL);
103
119
  return manage.createIndexFromFiles(indexName, files, modelId);
104
120
  }
105
121
  async addDocs(indexName, docs, options) {
@@ -133,15 +149,43 @@ export class MossClient {
133
149
  // ── Local index operations ─────────────────────────────────
134
150
  async loadIndex(indexName, _options) {
135
151
  const im = await this.getIndexManager();
136
- await im.loadIndex(indexName);
137
- this.indexModels.delete(indexName);
138
- await this.resolveIndexModel(indexName);
152
+ await this.modelArtifacts.replaceAfter(indexName, () => im.loadIndex(indexName), (info) => provenanceAwareIndexManager(im)
153
+ ? this.modelIdentityFromInfo(info)
154
+ : null, async () => {
155
+ await im.unloadIndex(indexName);
156
+ });
139
157
  return indexName;
140
158
  }
141
159
  async unloadIndex(indexName) {
142
160
  const im = await this.getIndexManager();
143
- this.indexModels.delete(indexName);
144
- return im.unloadIndex(indexName);
161
+ await this.modelArtifacts.removeAfter(indexName, () => im.unloadIndex(indexName));
162
+ }
163
+ /**
164
+ * Best-effort bulk load. Loads one index at a time so each keeps its own
165
+ * model artifact identity; failures are reported in `failed` and never roll
166
+ * back the indexes that did load.
167
+ */
168
+ async loadIndexes(indexNames, options) {
169
+ const result = { loaded: [], failed: {} };
170
+ for (const name of indexNames) {
171
+ try {
172
+ await this.loadIndex(name, options);
173
+ result.loaded.push(name);
174
+ }
175
+ catch (error) {
176
+ result.failed[name] = error instanceof Error ? error.message : String(error);
177
+ }
178
+ }
179
+ return result;
180
+ }
181
+ /** Best-effort bulk unload; names that are not loaded are ignored. */
182
+ async unloadIndexes(indexNames) {
183
+ for (const name of indexNames) {
184
+ try {
185
+ await this.unloadIndex(name);
186
+ }
187
+ catch { }
188
+ }
145
189
  }
146
190
  async hasIndex(indexName) {
147
191
  const im = await this.getIndexManager();
@@ -149,31 +193,142 @@ export class MossClient {
149
193
  }
150
194
  async getIndexInfo(indexName) {
151
195
  const im = await this.getIndexManager();
152
- return im.getIndexInfo(indexName);
196
+ return this.modelArtifacts.replaceAfter(indexName, () => im.getIndexInfo(indexName), (info) => provenanceAwareIndexManager(im)
197
+ ? this.modelIdentityFromInfo(info)
198
+ : null);
153
199
  }
154
200
  async refreshIndex(indexName) {
155
201
  const im = await this.getIndexManager();
156
- this.indexModels.delete(indexName);
157
- return im.refreshIndex(indexName);
202
+ return this.modelArtifacts.replaceAfter(indexName, () => im.refreshIndex(indexName), (result) => provenanceAwareIndexManager(im)
203
+ ? this.modelIdentityFromRefresh(result)
204
+ : null);
158
205
  }
206
+ /**
207
+ * Embeds `query` locally and searches one loaded index.
208
+ *
209
+ * A blank `query` (empty or only whitespace) returns no results at every
210
+ * `alpha`, without running the embedding model. `topK` 0 returns no results.
211
+ */
159
212
  async query(indexName, query, options) {
160
213
  await this.ensureInitialized();
161
- const model = resolveQueryModel(await this.resolveIndexModel(indexName), this.defaultModel);
162
- const embedder = await this.getEmbedder(model);
163
- const embedding = await embedder.embed(query);
164
- return this.indexManager.query(indexName, query, embedding, options?.topK, options?.alpha, options?.filter);
214
+ const manager = requireProvenanceAwareIndexManager(this.indexManager);
215
+ const identity = await this.modelIdentityForIndex(indexName);
216
+ if (!identity) {
217
+ throw new Error(`Index '${indexName}' has no foundation model artifact identity; use queryWithEmbedding`);
218
+ }
219
+ if (isBlankQuery(query)) {
220
+ return { docs: [], query, indexName, timeTakenMs: 0 };
221
+ }
222
+ const embedding = await this.embedder.embed(query, identity);
223
+ return manager.queryWithModelIdentity(indexName, query, embedding, identity.modelId, identity.version, identity.manifestSha256, options?.topK, options?.alpha, options?.filter, runtimeQueryTuning(options));
165
224
  }
166
- dispose() {
167
- for (const embedder of this.embedders.values()) {
168
- embedder.dispose();
225
+ async queryWithEmbedding(indexName, query, embedding, options) {
226
+ const im = await this.getIndexManager();
227
+ const identity = await this.modelIdentityForIndex(indexName);
228
+ const queryEmbedding = embedding instanceof Float32Array
229
+ ? embedding
230
+ : new Float32Array(embedding);
231
+ return queryWithResolvedModelIdentity(im, identity, indexName, query, queryEmbedding, options?.topK, options?.alpha, options?.filter, runtimeQueryTuning(options));
232
+ }
233
+ /**
234
+ * Search several loaded indexes in one call and return the global top-k,
235
+ * each result tagged with its source `indexName`. Local-only: every name
236
+ * must already be loaded, and all must share one embedding model artifact.
237
+ *
238
+ * `alpha` matches the single-index `query`: `1.0` is embedding-only, `0.0`
239
+ * is keyword-only, and values between fuse both rankings. `topK` is the
240
+ * global cap across the union, not a per-index cap, and 0 returns no results.
241
+ * A blank `query` returns no results without running the embedding model.
242
+ */
243
+ async queryMultiIndex(indexNames, query, options) {
244
+ if (indexNames.length === 0) {
245
+ throw new Error("queryMultiIndex requires at least one index name");
246
+ }
247
+ await this.ensureInitialized();
248
+ const manager = requireMultiIndexIndexManager(this.indexManager);
249
+ const identity = await this.sharedModelIdentity(indexNames);
250
+ if (isBlankQuery(query)) {
251
+ return { docs: [], query, timeTakenMs: 0 };
252
+ }
253
+ const embedding = await this.embedder.embed(query, identity);
254
+ return manager.queryMultiIndexWithModelIdentity(indexNames, query, embedding, identity.modelId, identity.version, identity.manifestSha256, options?.topK, options?.alpha, options?.filter, runtimeQueryTuning(options));
255
+ }
256
+ /** As `queryMultiIndex`, with a caller-supplied query vector. */
257
+ async queryMultiIndexWithEmbedding(indexNames, query, embedding, options) {
258
+ if (indexNames.length === 0) {
259
+ throw new Error("queryMultiIndexWithEmbedding requires at least one index name");
260
+ }
261
+ await this.ensureInitialized();
262
+ const manager = requireMultiIndexIndexManager(this.indexManager);
263
+ const identity = await this.resolveSharedModelIdentity(indexNames);
264
+ const queryEmbedding = embedding instanceof Float32Array
265
+ ? embedding
266
+ : new Float32Array(embedding);
267
+ if (identity) {
268
+ return manager.queryMultiIndexWithModelIdentity(indexNames, query, queryEmbedding, identity.modelId, identity.version, identity.manifestSha256, options?.topK, options?.alpha, options?.filter, runtimeQueryTuning(options));
269
+ }
270
+ return manager.queryMultiIndex(indexNames, query, queryEmbedding, options?.topK, options?.alpha, options?.filter, runtimeQueryTuning(options));
271
+ }
272
+ /**
273
+ * The one model artifact identity every named index shares, or `null` when
274
+ * none of them has one (custom or legacy embeddings). Throws when they
275
+ * disagree, because a single query vector cannot serve two models.
276
+ */
277
+ async resolveSharedModelIdentity(indexNames) {
278
+ let shared = null;
279
+ let resolved = false;
280
+ for (const name of indexNames) {
281
+ const identity = await this.modelIdentityForIndex(name);
282
+ if (!resolved) {
283
+ shared = identity;
284
+ resolved = true;
285
+ continue;
286
+ }
287
+ if (!sameModelArtifactIdentity(shared, identity)) {
288
+ throw new Error(`all indexes must share one embedding model artifact identity; '${name}' differs from '${indexNames[0]}'`);
289
+ }
290
+ }
291
+ return shared;
292
+ }
293
+ /** As `resolveSharedModelIdentity`, for the text path, which cannot embed
294
+ * without an exact identity to bind the vector to. */
295
+ async sharedModelIdentity(indexNames) {
296
+ const identity = await this.resolveSharedModelIdentity(indexNames);
297
+ if (!identity) {
298
+ throw new Error(`Indexes ${JSON.stringify(indexNames)} have no shared foundation model artifact identity; use queryMultiIndexWithEmbedding`);
169
299
  }
170
- this.embedders.clear();
171
- this.indexModels.clear();
300
+ return identity;
301
+ }
302
+ async modelIdentityForIndex(indexName) {
303
+ if (this.modelArtifacts.has(indexName)) {
304
+ return this.modelArtifacts.get(indexName) ?? null;
305
+ }
306
+ await this.getIndexInfo(indexName);
307
+ return this.modelArtifacts.get(indexName) ?? null;
308
+ }
309
+ modelIdentityFromInfo(info) {
310
+ return this.exactModelIdentity(info.model.id, info.modelArtifactVersion, info.manifestSha256);
311
+ }
312
+ modelIdentityFromRefresh(result) {
313
+ if (!result.modelId) {
314
+ throw new Error(`Refresh for '${result.indexName}' omitted its model identity`);
315
+ }
316
+ return this.exactModelIdentity(result.modelId, result.modelArtifactVersion, result.manifestSha256);
317
+ }
318
+ exactModelIdentity(modelId, version, manifestSha256) {
319
+ return exactModelArtifactIdentity(modelId, version, manifestSha256);
320
+ }
321
+ dispose() {
322
+ this.modelArtifacts.clearAll();
323
+ this.embedder?.dispose();
172
324
  this.indexManager?.free();
173
325
  this.manageClient?.free();
326
+ this.projectKeyAuthenticator?.free();
174
327
  this.initialized = false;
175
328
  this.indexManager = null;
176
329
  this.manageClient = null;
330
+ this.embedder = null;
331
+ this.projectKeyAuthenticator = null;
177
332
  this.initPromise = null;
178
333
  }
179
334
  }
@@ -1,17 +1,19 @@
1
- import type { Tokenizer, poolAndNormalize as PoolAndNormalizeFn } from "@moss-dev/moss-wasm";
2
- import type { MossModel } from "./types";
1
+ import type { poolAndNormalize as PoolAndNormalizeFn } from "@moss-dev/moss-wasm";
2
+ import { type ModelDeliveryOptions } from "./model-delivery.js";
3
+ import type { ModelArtifactIdentity, MossModel } from "./types.js";
3
4
  export declare class Embedder {
4
- private session;
5
- private tokenizer;
6
5
  private readonly modelId;
7
- private readonly hiddenDim;
8
- private initPromise;
9
- private readonly wasmTokenizerCtor;
6
+ private readonly runtimes;
7
+ private retainedKeys;
10
8
  private readonly poolAndNormalize;
11
- constructor(modelId: MossModel, wasmTokenizerCtor: typeof Tokenizer, poolAndNormalize: typeof PoolAndNormalizeFn);
9
+ private readonly delivery;
10
+ constructor(modelId: MossModel, poolAndNormalize: typeof PoolAndNormalizeFn, delivery: ModelDeliveryOptions);
12
11
  init(onnxWasmPath?: string): Promise<void>;
13
- private _init;
14
- embed(text: string): Promise<Float32Array>;
15
- private poolResult;
12
+ embed(text: string, identity: ModelArtifactIdentity): Promise<Float32Array>;
13
+ retainModelArtifacts(identities: ModelArtifactIdentity[]): void;
14
+ private runtimeFor;
15
+ private identityKey;
16
+ private retireRuntime;
17
+ private loadRuntime;
16
18
  dispose(): void;
17
19
  }
package/dist/embedder.js CHANGED
@@ -1,85 +1,105 @@
1
1
  import * as ort from "onnxruntime-web";
2
- const CDN_BASE = "https://models.moss.link/";
3
- const MODEL_CONFIGS = {
4
- "moss-minilm": { hiddenDim: 384 },
5
- "moss-mediumlm": { hiddenDim: 512 },
6
- };
2
+ import { modelHiddenDim } from "./model-config.js";
3
+ import { loadSealedModel } from "./model-delivery.js";
7
4
  export class Embedder {
8
- constructor(modelId, wasmTokenizerCtor, poolAndNormalize) {
9
- this.session = null;
10
- this.tokenizer = null;
11
- this.initPromise = null;
5
+ constructor(modelId, poolAndNormalize, delivery) {
6
+ this.runtimes = new Map();
7
+ this.retainedKeys = new Set();
12
8
  this.modelId = modelId;
13
- this.hiddenDim = MODEL_CONFIGS[modelId].hiddenDim;
14
- this.wasmTokenizerCtor = wasmTokenizerCtor;
15
9
  this.poolAndNormalize = poolAndNormalize;
10
+ this.delivery = delivery;
16
11
  }
17
12
  async init(onnxWasmPath) {
18
- if (this.initPromise)
19
- return this.initPromise;
20
- this.initPromise = this._init(onnxWasmPath);
21
- return this.initPromise;
22
- }
23
- async _init(onnxWasmPath) {
24
13
  if (onnxWasmPath) {
25
14
  ort.env.wasm.wasmPaths = onnxWasmPath;
26
15
  }
27
- const modelUrl = `${CDN_BASE}${this.modelId}/`;
28
- const [tokenizerBytes, onnxModel] = await Promise.all([
29
- fetch(`${modelUrl}tokenizer.json`).then((r) => {
30
- if (!r.ok)
31
- throw new Error(`Failed to fetch tokenizer.json: ${r.status}`);
32
- return r.arrayBuffer();
33
- }),
34
- fetch(`${modelUrl}onnx/model.onnx`).then((r) => {
35
- if (!r.ok)
36
- throw new Error(`Failed to fetch model.onnx: ${r.status}`);
37
- return r.arrayBuffer();
38
- }),
39
- ]);
40
- this.tokenizer = new this.wasmTokenizerCtor(new Uint8Array(tokenizerBytes));
41
- this.session = await ort.InferenceSession.create(onnxModel, {
42
- executionProviders: ["wasm"],
43
- graphOptimizationLevel: "all",
44
- });
45
16
  }
46
- async embed(text) {
47
- if (!this.tokenizer || !this.session) {
48
- throw new Error("Embedder not initialized — call init() first");
17
+ async embed(text, identity) {
18
+ if (identity.modelId !== this.modelId) {
19
+ throw new Error(`Loaded index requires model '${identity.modelId}', but this client is configured for '${this.modelId}'`);
49
20
  }
50
- const tokens = this.tokenizer.tokenize(text);
51
- const seqLen = tokens.inputIds.length;
52
- const inputIdsTensor = new ort.Tensor("int64", BigInt64Array.from(tokens.inputIds.map(BigInt)), [1, seqLen]);
53
- const attentionMaskTensor = new ort.Tensor("int64", BigInt64Array.from(tokens.attentionMask.map(BigInt)), [1, seqLen]);
54
- const tokenTypeIdsTensor = new ort.Tensor("int64", BigInt64Array.from(tokens.tokenTypeIds.map(BigInt)), [1, seqLen]);
55
- const feeds = {
56
- input_ids: inputIdsTensor,
57
- attention_mask: attentionMaskTensor,
58
- token_type_ids: tokenTypeIdsTensor,
59
- };
60
- const output = await this.session.run(feeds);
61
- const lastHiddenState = output["last_hidden_state"];
62
- if (!lastHiddenState) {
63
- const firstKey = Object.keys(output)[0];
64
- if (!firstKey)
21
+ const [key, entry] = this.runtimeFor(identity);
22
+ entry.users += 1;
23
+ try {
24
+ const runtime = await entry.promise;
25
+ const tokens = runtime.tokenizer.tokenize(text);
26
+ const seqLen = tokens.inputIds.length;
27
+ const feeds = {
28
+ input_ids: new ort.Tensor("int64", BigInt64Array.from(tokens.inputIds.map(BigInt)), [1, seqLen]),
29
+ attention_mask: new ort.Tensor("int64", BigInt64Array.from(tokens.attentionMask.map(BigInt)), [1, seqLen]),
30
+ token_type_ids: new ort.Tensor("int64", BigInt64Array.from(tokens.tokenTypeIds.map(BigInt)), [1, seqLen]),
31
+ };
32
+ const output = await runtime.session.run(feeds);
33
+ const tensor = output.last_hidden_state ?? output[Object.keys(output)[0] ?? ""];
34
+ if (!tensor)
65
35
  throw new Error("ONNX model returned no outputs");
66
- const fallback = output[firstKey];
67
- return this.poolResult(fallback.data, tokens.attentionMask);
36
+ return this.poolAndNormalize(tensor.data, new Int32Array(tokens.attentionMask), runtime.hiddenDim);
37
+ }
38
+ finally {
39
+ entry.users -= 1;
40
+ if (!entry.retained && entry.users === 0)
41
+ this.retireRuntime(key, entry);
68
42
  }
69
- return this.poolResult(lastHiddenState.data, tokens.attentionMask);
70
43
  }
71
- poolResult(tokenEmbeddings, attentionMask) {
72
- return this.poolAndNormalize(tokenEmbeddings, new Int32Array(attentionMask), this.hiddenDim);
44
+ retainModelArtifacts(identities) {
45
+ this.retainedKeys = new Set(identities.map((identity) => this.identityKey(identity)));
46
+ for (const [key, entry] of this.runtimes) {
47
+ entry.retained = this.retainedKeys.has(key);
48
+ if (!entry.retained && entry.users === 0)
49
+ this.retireRuntime(key, entry);
50
+ }
73
51
  }
74
- dispose() {
75
- if (this.tokenizer) {
76
- this.tokenizer.free();
77
- this.tokenizer = null;
52
+ runtimeFor(identity) {
53
+ const key = this.identityKey(identity);
54
+ const existing = this.runtimes.get(key);
55
+ if (existing)
56
+ return [key, existing];
57
+ let entry;
58
+ const promise = this.loadRuntime(identity).catch((error) => {
59
+ if (this.runtimes.get(key) === entry)
60
+ this.runtimes.delete(key);
61
+ throw error;
62
+ });
63
+ entry = { promise, users: 0, retained: this.retainedKeys.has(key) };
64
+ this.runtimes.set(key, entry);
65
+ return [key, entry];
66
+ }
67
+ identityKey(identity) {
68
+ return `${identity.modelId}\0${identity.version}\0${identity.manifestSha256}`;
69
+ }
70
+ retireRuntime(key, entry) {
71
+ if (this.runtimes.get(key) !== entry)
72
+ return;
73
+ this.runtimes.delete(key);
74
+ void entry.promise.then(({ tokenizer, session }) => {
75
+ tokenizer.free();
76
+ session.release();
77
+ }).catch(() => undefined);
78
+ }
79
+ async loadRuntime(identity) {
80
+ const { graph, tokenizer } = await loadSealedModel(this.delivery, identity);
81
+ try {
82
+ const session = await ort.InferenceSession.create(graph, {
83
+ executionProviders: ["wasm"],
84
+ graphOptimizationLevel: "all",
85
+ });
86
+ return {
87
+ tokenizer,
88
+ session,
89
+ hiddenDim: modelHiddenDim(identity.modelId),
90
+ };
78
91
  }
79
- if (this.session) {
80
- this.session.release();
81
- this.session = null;
92
+ catch (error) {
93
+ tokenizer.free();
94
+ throw error;
95
+ }
96
+ }
97
+ dispose() {
98
+ this.retainedKeys.clear();
99
+ for (const [key, entry] of this.runtimes) {
100
+ entry.retained = false;
101
+ if (entry.users === 0)
102
+ this.retireRuntime(key, entry);
82
103
  }
83
- this.initPromise = null;
84
104
  }
85
105
  }
package/dist/index.d.ts CHANGED
@@ -1,2 +1,4 @@
1
- export { MossClient } from "./client";
2
- export type { MossClientOptions, MossModel, IndexInfo, SearchResult, QueryResultDocumentInfo, QueryOptions, MetadataFilter, FilterCondition, RefreshResult, ModelRef, DocumentInfo, MutationResult, CreateIndexOptions, MutationOptions, ParseFileInput, JobStatus, JobPhase, JobProgress, JobStatusResponse, GetDocumentsOptions, LoadIndexOptions, ISODate, } from "./types";
1
+ export { MossClient } from "./client.js";
2
+ export type { IAuthenticator, AuthToken } from "./auth/authenticator.interface.js";
3
+ export { ModelDeliveryError } from "./model-delivery.js";
4
+ export type { MossClientOptions, MossModel, IndexInfo, SearchResult, QueryResultDocumentInfo, QueryOptions, MetadataFilter, FilterCondition, RefreshResult, ModelRef, ModelArtifactIdentity, ModelDownloadProgress, DocumentInfo, MutationResult, CreateIndexOptions, MutationOptions, ParseFileInput, JobStatus, JobPhase, JobProgress, JobStatusResponse, GetDocumentsOptions, LoadIndexOptions, LoadIndexesResult, ISODate, } from "./types.js";
package/dist/index.js CHANGED
@@ -1 +1,2 @@
1
- export { MossClient } from "./client";
1
+ export { MossClient } from "./client.js";
2
+ export { ModelDeliveryError } from "./model-delivery.js";
@@ -0,0 +1,18 @@
1
+ import type { ModelArtifactIdentity } from "./types.js";
2
+ export declare class ModelArtifactOwnership {
3
+ private readonly identities;
4
+ private readonly retain;
5
+ constructor(retain: (identities: ModelArtifactIdentity[]) => void);
6
+ has(indexName: string): boolean;
7
+ get(indexName: string): ModelArtifactIdentity | null | undefined;
8
+ synchronize(indexName: string, identity: ModelArtifactIdentity | null): void;
9
+ clear(indexName: string): void;
10
+ clearAll(): void;
11
+ replaceAfter<T>(indexName: string, transition: () => Promise<T>, identityFromResult: (result: T) => ModelArtifactIdentity | null, rollbackSynchronizedTransition?: (result: T) => Promise<void>): Promise<T>;
12
+ removeAfter<T>(indexName: string, transition: () => Promise<T>): Promise<T>;
13
+ /** Clear an index's identity while an error is already propagating: the
14
+ * map entry is always removed, but a failure releasing runtimes is
15
+ * swallowed so it cannot mask the primary error. */
16
+ private clearWithoutMasking;
17
+ private retainCurrentArtifacts;
18
+ }