@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.
package/README.md CHANGED
@@ -18,7 +18,7 @@ Built on WebAssembly for near-native performance in any modern browser.
18
18
  npm install @moss-dev/moss-web
19
19
  ```
20
20
 
21
- Version 1.2.0 resolves `@moss-dev/moss-wasm@0.15.0`. Text `query()` loads its
21
+ Version 1.4.0 resolves `@moss-dev/moss-wasm@0.17.0`. Text `query()` loads its
22
22
  model through the Moss service using the client's credentials, so the service
23
23
  must be reachable the first time a model is loaded; there is no offline
24
24
  fallback. The only published npm versions before this are 1.0.0 and 1.0.1,
@@ -75,22 +75,31 @@ class MyBackendAuthenticator implements IAuthenticator {
75
75
  const res = await fetch("/api/moss-token", { method: "POST" });
76
76
  return res.json(); // { token, expiresIn }
77
77
  }
78
- async getAuthHeader(): Promise<string> {
79
- const { token } = await this.getAuthToken();
80
- return `Bearer ${token}`;
81
- }
82
78
  }
83
79
 
84
80
  const client = new MossClient(projectId, new MyBackendAuthenticator());
85
81
  await client.getAuthToken(); // cached AuthToken
86
82
  ```
87
83
 
88
- Tokens are cached until 60 seconds before expiry and refetched after a 401.
84
+ The client calls `getAuthToken()` only and sends the token as `Authorization: Bearer <token>`. `getAuthHeader()` on an `IAuthenticator` is optional and deprecated, since the client never calls it.
85
+
86
+ A token is cached until 60 seconds before it expires, or for 90% of its life when that is later, and refetched after a 401. A token whose `expiresIn` is not a positive finite number of seconds is not cached, so each request fetches a new one.
89
87
 
90
88
  **Options:**
91
89
 
92
90
  - `model` — `"moss-minilm"` (default, fast, for most use-cases) or `"moss-mediumlm"`
93
91
  - `baseUrl` — Custom API base URL (for self-hosted Moss instances)
92
+ - `onProgress` — Called with `{ modelId, loadedBytes, totalBytes, fromCache }` while the embedding model downloads
93
+
94
+ The first text query waits for the embedding model. The model grant request fails after 30 seconds without an answer. Each model file request aborts after 30 seconds without data and is retried once. The verified model is kept in the browser Cache API and checked against its SHA-256 before each use, so later page loads skip the download. On pages without the Cache API, such as plain HTTP, it downloads on each page load.
95
+
96
+ ```typescript
97
+ const client = new MossClient(projectId, projectKey, {
98
+ onProgress: ({ loadedBytes, totalBytes }) => {
99
+ progressBar.value = loadedBytes / totalBytes;
100
+ },
101
+ });
102
+ ```
94
103
 
95
104
  ### Index Management
96
105
 
@@ -160,9 +169,45 @@ await client.unloadIndex(name);
160
169
  await client.unloadIndexes(names);
161
170
  ```
162
171
 
163
- `loadIndex` and `loadIndexes` accept `LoadIndexOptions` (`autoRefresh`,
164
- `pollingIntervalInSeconds`) for parity with the Node SDK, but the browser SDK
165
- does not honor them yet; use `refreshIndex` to pull server updates.
172
+ `refreshIndex` downloads the index only when the cloud has a newer version.
173
+ When the loaded version is current it downloads nothing and returns
174
+ `wasUpdated: false`.
175
+
176
+ `loadIndex` and `loadIndexes` accept `autoRefresh` and `pollingIntervalInSeconds`.
177
+ With `autoRefresh: true` the client refreshes that index every
178
+ `pollingIntervalInSeconds` (600 when unset or 0, at least 1) until the index is
179
+ unloaded, loaded again without `autoRefresh`, or the client is disposed. Loading
180
+ the same name again replaces the timer, and a failed refresh logs a warning and
181
+ retries on the next tick.
182
+ A `@moss-dev/moss-wasm` older than the release that skips unchanged snapshots
183
+ would download the whole index on every tick, so with one `autoRefresh` is off:
184
+ the index loads, the client logs one warning, and no timer starts.
185
+
186
+ ```typescript
187
+ await client.loadIndex("docs", { autoRefresh: true, pollingIntervalInSeconds: 300 });
188
+ ```
189
+
190
+ #### Job progress
191
+
192
+ `createIndex`, `createIndexFromFiles`, `addDocs` and `deleteDocs` wait for the
193
+ server job to finish. Pass `onProgress` to see each status the client polls.
194
+ An exception thrown by the callback, or a rejected promise it returns, is ignored.
195
+
196
+ ```typescript
197
+ await client.addDocs("docs", docs, {
198
+ onProgress: (p) => console.log(p.status, p.progress, p.currentPhase),
199
+ });
200
+ ```
201
+
202
+ `onProgress` needs a `@moss-dev/moss-wasm` whose job methods take the callback.
203
+ With an older package these calls throw an upgrade error before the job starts.
204
+
205
+ #### Metadata filters
206
+
207
+ `$gt`, `$gte`, `$lt` and `$lte` compare two plain decimals (`"42"`, `"-3.5"`) as numbers
208
+ and two other values as text. They never match a plain decimal against any other value, such as `"01234"`, `"1e3"` or `"NaN"`.
209
+ `$near` takes `"lat,lng,maxDistanceMeters"` and matches a `"lat,lng"` field value; any other `$near` value is an error.
210
+ A condition never matches a document that lacks the field, `$ne` and `$nin` included.
166
211
 
167
212
  #### Multi-index search
168
213
 
@@ -199,6 +244,70 @@ error.
199
244
  client.dispose();
200
245
  ```
201
246
 
247
+ ## Telemetry
248
+
249
+ The browser SDK always sends usage events, as the native Moss SDKs do. They
250
+ carry the query counts that Moss bills, so there is no option to turn them off.
251
+
252
+ Each client posts them to `<baseUrl>/telemetry`
253
+ (`https://service.usemoss.dev/index/telemetry` by default) with the same
254
+ credentials as its other requests. A query adds one to a count and sends
255
+ nothing. Every 3 seconds while there are new queries, the client gets a token
256
+ and sends the count, and `dispose()` sends what is left. While there are none,
257
+ it gets a token every 30 seconds, so a page that is closing can send without
258
+ waiting for one. It gets these tokens the way other requests do, so a cached
259
+ token costs no request, and with an authenticator whose tokens are not cached,
260
+ each one is a `getAuthToken()` call. Counts wait until the first token request
261
+ succeeds. A failed send is dropped. It never fails a query or raises an
262
+ unhandled promise rejection.
263
+
264
+ Each send is one usage body and the query events in JSON arrays of up to 500,
265
+ the bodies the native SDKs send. One send carries at most 10,000 query events,
266
+ and later queries wait for the next send. A send uses `keepalive`, so a
267
+ navigation does not cancel it, when it fits in about 60 KB that every client on
268
+ the page shares, since browsers allow 64 KiB of keepalive requests in flight per
269
+ page. On `pagehide` and `dispose()` the client starts at once the sends that fit.
270
+ After `pagehide` the rest stay counted for a page restored from the back/forward
271
+ cache, and are lost when the page unloads.
272
+
273
+ ### Device id
274
+
275
+ `deviceId` is the billable device key. A page reads it once, when its first
276
+ client initializes, from `localStorage` under `moss-device-id`. When there is
277
+ none, the SDK creates a random UUID and stores it there, so page reloads and
278
+ every client on the origin reuse it. Later clients on the same page reuse the id
279
+ in memory and do not touch `localStorage`, so after the site's data is cleared,
280
+ the next page load stores a new id. Where `localStorage` is missing or throws,
281
+ each page, worker or process gets a new id that lasts until it ends. That
282
+ happens in some private windows and sandboxed frames, in Web Workers, and under
283
+ Node or server rendering, so each of those counts as a new device. Browsers also
284
+ scope the stored id: a third-party iframe gets one id per top-level site, and
285
+ Safari deletes it after 7 days of use without a visit to the site.
286
+
287
+ ### Fields on every event
288
+
289
+ | Field | Value |
290
+ |---|---|
291
+ | `action` | Always `"telemetry"`. |
292
+ | `eventType` | The event type, from the table below. |
293
+ | `projectId` | Your project id. |
294
+ | `clientId`, `sessionId` | The same random id, one per client. |
295
+ | `sdkVersion`, `sdkPackageVersion` | Version of `@moss-dev/moss-wasm`. |
296
+ | `nativeCoreVersion` | Version of the Rust core. |
297
+ | `deviceId`, `mossDeviceId` | The device id, the same value in both. |
298
+
299
+ ### Event types
300
+
301
+ | Event | Sent when | Extra fields |
302
+ |---|---|---|
303
+ | `index.usage.periodic_flush` | Every 3 seconds while there are new queries | `queryCount`, and `docsEmbedded` and `tokensEstimated`, always 0 |
304
+ | `index.usage.final_flush` | On `dispose()` and `pagehide`, when queries are left | The same as `index.usage.periodic_flush` |
305
+ | `index.query` | Once per single index query, in a batch | None |
306
+ | `index.query_multi` | Once per multi-index query, in a batch | None |
307
+
308
+ Query events carry no index name, latency or model, because a query only adds
309
+ to a count. No document text, query text, metadata or embedding is ever sent.
310
+
202
311
  ## License
203
312
 
204
313
  See [LICENSE](./LICENSE.txt).
@@ -1,8 +1,14 @@
1
1
  export interface AuthToken {
2
2
  token: string;
3
+ /** Seconds until the token expires. A token without a positive finite value is not cached. */
3
4
  expiresIn: number;
4
5
  }
6
+ /**
7
+ * Supplies short-lived tokens to `MossClient`.
8
+ * The client calls `getAuthToken` only and sends `Authorization: Bearer <token>`.
9
+ */
5
10
  export interface IAuthenticator {
6
11
  getAuthToken(): Promise<AuthToken>;
7
- getAuthHeader(): Promise<string>;
12
+ /** @deprecated The client never calls this. It builds the header from `getAuthToken`. */
13
+ getAuthHeader?(): Promise<string>;
8
14
  }
@@ -5,6 +5,7 @@ export declare class CachingAuthenticator implements IAuthenticator {
5
5
  private inflight;
6
6
  constructor(inner: IAuthenticator);
7
7
  getAuthToken(): Promise<AuthToken>;
8
+ /** The header the client sends, built from `getAuthToken`. */
8
9
  getAuthHeader(): Promise<string>;
9
10
  invalidate(): void;
10
11
  private fetchAndCache;
@@ -19,6 +19,7 @@ export class CachingAuthenticator {
19
19
  this.inflight = null;
20
20
  }
21
21
  }
22
+ /** The header the client sends, built from `getAuthToken`. */
22
23
  async getAuthHeader() {
23
24
  const { token } = await this.getAuthToken();
24
25
  return `Bearer ${token}`;
@@ -28,8 +29,21 @@ export class CachingAuthenticator {
28
29
  }
29
30
  async fetchAndCache() {
30
31
  const { token, expiresIn } = await this.inner.getAuthToken();
31
- const expiresAt = Date.now() + (expiresIn - 60) * 1000;
32
- this.cache = { token, expiresIn, expiresAt };
32
+ const lifetime = cacheLifetimeSeconds(expiresIn);
33
+ this.cache = lifetime > 0
34
+ ? { token, expiresIn, expiresAt: Date.now() + lifetime * 1000 }
35
+ : null;
33
36
  return { token, expiresIn };
34
37
  }
35
38
  }
39
+ /**
40
+ * Seconds to serve a token from the cache: until 60 seconds
41
+ * before it expires, or for 90% of its life when that is later.
42
+ * Returns 0, meaning uncached, unless `expiresIn` is a positive finite number.
43
+ */
44
+ function cacheLifetimeSeconds(expiresIn) {
45
+ if (!Number.isFinite(expiresIn) || expiresIn <= 0) {
46
+ return 0;
47
+ }
48
+ return Math.max(expiresIn * 0.9, expiresIn - 60);
49
+ }
package/dist/client.d.ts CHANGED
@@ -12,6 +12,8 @@ export declare class MossClient {
12
12
  private projectKeyAuthenticator;
13
13
  private initPromise;
14
14
  private readonly modelArtifacts;
15
+ private readonly autoRefreshLoops;
16
+ private autoRefreshUnsupportedWarned;
15
17
  constructor(projectId: string, projectKey: string, options?: MossClientOptions);
16
18
  constructor(projectId: string, authenticator: IAuthenticator, options?: MossClientOptions);
17
19
  getAuthToken(): Promise<AuthToken>;
@@ -35,19 +37,38 @@ export declare class MossClient {
35
37
  deleteIndex(indexName: string): Promise<boolean>;
36
38
  getDocs(indexName: string, options?: GetDocumentsOptions): Promise<DocumentInfo[]>;
37
39
  getJobStatus(jobId: string): Promise<JobStatusResponse>;
38
- loadIndex(indexName: string, _options?: LoadIndexOptions): Promise<string>;
40
+ /**
41
+ * Load an index into browser memory.
42
+ *
43
+ * With `autoRefresh`, the index is refreshed from the cloud
44
+ * every `pollingIntervalInSeconds` (600 when unset or 0, minimum 1)
45
+ * until it is unloaded, loaded again without `autoRefresh`, or the client is disposed.
46
+ * A failed load keeps the running loop, and a failed refresh keeps the model of the loaded index.
47
+ * A `@moss-dev/moss-wasm` that would download the whole index on every tick gets a warning and no loop.
48
+ */
49
+ loadIndex(indexName: string, options?: LoadIndexOptions): Promise<string>;
39
50
  unloadIndex(indexName: string): Promise<void>;
40
51
  /**
41
52
  * Best-effort bulk load. Loads one index at a time so each keeps its own
42
- * model artifact identity; failures are reported in `failed` and never roll
43
- * back the indexes that did load.
53
+ * model artifact identity; failures are reported in `failed`, with their
54
+ * codes in `failedCodes`, and never roll back the indexes that did load.
44
55
  */
45
56
  loadIndexes(indexNames: string[], options?: LoadIndexOptions): Promise<LoadIndexesResult>;
46
57
  /** Best-effort bulk unload; names that are not loaded are ignored. */
47
58
  unloadIndexes(indexNames: string[]): Promise<void>;
48
59
  hasIndex(indexName: string): Promise<boolean>;
49
60
  getIndexInfo(indexName: string): Promise<IndexInfo>;
61
+ /**
62
+ * Install the cloud's snapshot of a loaded index when it is newer. A snapshot no newer
63
+ * than the loaded one, with the same model, downloads nothing and returns `wasUpdated` false.
64
+ */
50
65
  refreshIndex(indexName: string): Promise<RefreshResult>;
66
+ /**
67
+ * Embeds `query` locally and searches one loaded index.
68
+ *
69
+ * A blank `query` (empty or only whitespace) returns no results at every
70
+ * `alpha`, without running the embedding model. `topK` 0 returns no results.
71
+ */
51
72
  query(indexName: string, query: string, options?: QueryOptions): Promise<SearchResult>;
52
73
  queryWithEmbedding(indexName: string, query: string, embedding: Float32Array | number[], options?: QueryOptions): Promise<SearchResult>;
53
74
  /**
@@ -57,7 +78,8 @@ export declare class MossClient {
57
78
  *
58
79
  * `alpha` matches the single-index `query`: `1.0` is embedding-only, `0.0`
59
80
  * is keyword-only, and values between fuse both rankings. `topK` is the
60
- * global cap across the union, not a per-index cap.
81
+ * global cap across the union, not a per-index cap, and 0 returns no results.
82
+ * A blank `query` returns no results without running the embedding model.
61
83
  */
62
84
  queryMultiIndex(indexNames: string[], query: string, options?: QueryOptions): Promise<SearchResult>;
63
85
  /** As `queryMultiIndex`, with a caller-supplied query vector. */
@@ -75,5 +97,8 @@ export declare class MossClient {
75
97
  private modelIdentityFromInfo;
76
98
  private modelIdentityFromRefresh;
77
99
  private exactModelIdentity;
100
+ /** Refreshes `indexName` on `im` until the loop is replaced or stopped, or `im` is disposed. */
101
+ private startAutoRefresh;
102
+ private stopAutoRefresh;
78
103
  dispose(): void;
79
104
  }
package/dist/client.js CHANGED
@@ -1,9 +1,31 @@
1
1
  import wasmInit, { IndexManager, ManageClient, ModelKeyExchange, ProjectKeyAuthenticator, openSealedModel, poolAndNormalize, } from "@moss-dev/moss-wasm";
2
+ import * as mossWasm from "@moss-dev/moss-wasm";
2
3
  import { CachingAuthenticator } from "./auth/caching.authenticator.js";
3
4
  import { Embedder } from "./embedder.js";
4
5
  import { ModelArtifactOwnership } from "./model-artifact-ownership.js";
5
- import { exactModelArtifactIdentity, provenanceAwareIndexManager, queryWithResolvedModelIdentity, requireMultiIndexIndexManager, requireProvenanceAwareIndexManager, } from "./wasm-runtime-capability.js";
6
+ import { callWithProgress, exactModelArtifactIdentity, matchedSealedModelOpener, provenanceAwareIndexManager, queryWithResolvedModelIdentity, refreshSkipsUnchanged, requireMultiIndexIndexManager, requireProvenanceAwareIndexManager, runtimeQueryTuning, webCryptoSealedModelRuntime, } from "./wasm-runtime-capability.js";
6
7
  const DEFAULT_MODEL = "moss-minilm";
8
+ /** Auto refresh interval when `pollingIntervalInSeconds` is unset or 0, as in the native SDKs. */
9
+ const DEFAULT_POLLING_INTERVAL_SECONDS = 600;
10
+ /** Shortest auto refresh interval. Smaller values use it. */
11
+ const MIN_POLLING_INTERVAL_SECONDS = 1;
12
+ /** Longest interval `setTimeout` honors. It fires at once for anything longer. */
13
+ const MAX_POLLING_INTERVAL_SECONDS = Math.floor(2147483647 / 1000);
14
+ /**
15
+ * The auto refresh delay in milliseconds for `options`, or `null` when auto
16
+ * refresh is off. Throws on an interval that is not a finite number of zero or more.
17
+ */
18
+ function autoRefreshDelayMs(options) {
19
+ if (!options?.autoRefresh)
20
+ return null;
21
+ const requested = options.pollingIntervalInSeconds ?? DEFAULT_POLLING_INTERVAL_SECONDS;
22
+ if (typeof requested !== "number" || !Number.isFinite(requested) || requested < 0) {
23
+ throw new RangeError(`pollingIntervalInSeconds must be a finite number of zero or more, got ${String(requested)}`);
24
+ }
25
+ const seconds = requested === 0 ? DEFAULT_POLLING_INTERVAL_SECONDS : requested;
26
+ const clamped = Math.min(Math.max(seconds, MIN_POLLING_INTERVAL_SECONDS), MAX_POLLING_INTERVAL_SECONDS);
27
+ return Math.round(clamped * 1000);
28
+ }
7
29
  function sameModelArtifactIdentity(left, right) {
8
30
  if (left === null || right === null)
9
31
  return left === right;
@@ -11,6 +33,10 @@ function sameModelArtifactIdentity(left, right) {
11
33
  && left.version === right.version
12
34
  && left.manifestSha256 === right.manifestSha256;
13
35
  }
36
+ /** True for a query with no text to match: empty or only whitespace. */
37
+ function isBlankQuery(query) {
38
+ return query.trim().length === 0;
39
+ }
14
40
  export class MossClient {
15
41
  constructor(projectId, auth, options) {
16
42
  this.initialized = false;
@@ -22,6 +48,8 @@ export class MossClient {
22
48
  this.modelArtifacts = new ModelArtifactOwnership((identities) => {
23
49
  this.embedder?.retainModelArtifacts(identities);
24
50
  });
51
+ this.autoRefreshLoops = new Map();
52
+ this.autoRefreshUnsupportedWarned = false;
25
53
  this.projectId = projectId;
26
54
  if (typeof auth === "string") {
27
55
  this.projectKey = auth;
@@ -85,9 +113,15 @@ export class MossClient {
85
113
  this.embedder = new Embedder(model, poolAndNormalize, {
86
114
  projectId: this.projectId,
87
115
  auth: deliveryAuth,
88
- runtime: { newKeyExchange: () => new ModelKeyExchange(), openSealedModel },
116
+ runtime: {
117
+ newKeyExchange: () => new ModelKeyExchange(),
118
+ openSealedModel,
119
+ openMatchedSealedModel: matchedSealedModelOpener(mossWasm),
120
+ webCrypto: webCryptoSealedModelRuntime(mossWasm),
121
+ },
89
122
  baseUrl: this.options.baseUrl,
90
123
  artifactOrigin: this.options.modelArtifactOrigin,
124
+ onProgress: this.options.onProgress,
91
125
  });
92
126
  await this.embedder.init(this.options.onnxWasmPath);
93
127
  this.initialized = true;
@@ -106,20 +140,20 @@ export class MossClient {
106
140
  const hasEmbeddings = docs.some((d) => Array.isArray(d.embedding) && d.embedding.length > 0);
107
141
  const modelId = options?.modelId
108
142
  ?? (hasEmbeddings ? "custom" : (this.options.model ?? DEFAULT_MODEL));
109
- return manage.createIndex(indexName, docs, modelId);
143
+ return callWithProgress(manage, "createIndex", [indexName, docs, modelId], options?.onProgress);
110
144
  }
111
145
  async createIndexFromFiles(indexName, files, options) {
112
146
  const manage = await this.getManageClient();
113
147
  const modelId = options?.modelId ?? (this.options.model ?? DEFAULT_MODEL);
114
- return manage.createIndexFromFiles(indexName, files, modelId);
148
+ return callWithProgress(manage, "createIndexFromFiles", [indexName, files, modelId], options?.onProgress);
115
149
  }
116
150
  async addDocs(indexName, docs, options) {
117
151
  const manage = await this.getManageClient();
118
- return manage.addDocs(indexName, docs, options?.upsert);
152
+ return callWithProgress(manage, "addDocs", [indexName, docs, options?.upsert], options?.onProgress);
119
153
  }
120
154
  async deleteDocs(indexName, docIds, options) {
121
155
  const manage = await this.getManageClient();
122
- return manage.deleteDocs(indexName, docIds);
156
+ return callWithProgress(manage, "deleteDocs", [indexName, docIds], options?.onProgress);
123
157
  }
124
158
  async getIndex(indexName) {
125
159
  const manage = await this.getManageClient();
@@ -142,26 +176,52 @@ export class MossClient {
142
176
  return manage.getJobStatus(jobId);
143
177
  }
144
178
  // ── Local index operations ─────────────────────────────────
145
- async loadIndex(indexName, _options) {
179
+ /**
180
+ * Load an index into browser memory.
181
+ *
182
+ * With `autoRefresh`, the index is refreshed from the cloud
183
+ * every `pollingIntervalInSeconds` (600 when unset or 0, minimum 1)
184
+ * until it is unloaded, loaded again without `autoRefresh`, or the client is disposed.
185
+ * A failed load keeps the running loop, and a failed refresh keeps the model of the loaded index.
186
+ * A `@moss-dev/moss-wasm` that would download the whole index on every tick gets a warning and no loop.
187
+ */
188
+ async loadIndex(indexName, options) {
189
+ let refreshDelayMs = autoRefreshDelayMs(options);
146
190
  const im = await this.getIndexManager();
191
+ if (refreshDelayMs !== null && !refreshSkipsUnchanged(im)) {
192
+ refreshDelayMs = null;
193
+ if (!this.autoRefreshUnsupportedWarned) {
194
+ this.autoRefreshUnsupportedWarned = true;
195
+ console.warn("The installed @moss-dev/moss-wasm downloads the whole index on every refresh, so autoRefresh is off. Upgrade @moss-dev/moss-wasm to enable it.");
196
+ }
197
+ }
147
198
  await this.modelArtifacts.replaceAfter(indexName, () => im.loadIndex(indexName), (info) => provenanceAwareIndexManager(im)
148
199
  ? this.modelIdentityFromInfo(info)
149
200
  : null, async () => {
150
201
  await im.unloadIndex(indexName);
151
202
  });
203
+ // dispose() ran while the load was pending, so the index belongs to a freed manager.
204
+ if (this.indexManager !== im)
205
+ return indexName;
206
+ this.stopAutoRefresh(indexName);
207
+ if (refreshDelayMs !== null) {
208
+ this.startAutoRefresh(indexName, refreshDelayMs, im);
209
+ }
152
210
  return indexName;
153
211
  }
154
212
  async unloadIndex(indexName) {
213
+ this.stopAutoRefresh(indexName);
155
214
  const im = await this.getIndexManager();
156
215
  await this.modelArtifacts.removeAfter(indexName, () => im.unloadIndex(indexName));
157
216
  }
158
217
  /**
159
218
  * Best-effort bulk load. Loads one index at a time so each keeps its own
160
- * model artifact identity; failures are reported in `failed` and never roll
161
- * back the indexes that did load.
219
+ * model artifact identity; failures are reported in `failed`, with their
220
+ * codes in `failedCodes`, and never roll back the indexes that did load.
162
221
  */
163
222
  async loadIndexes(indexNames, options) {
164
- const result = { loaded: [], failed: {} };
223
+ const failedCodes = {};
224
+ const result = { loaded: [], failed: {}, failedCodes };
165
225
  for (const name of indexNames) {
166
226
  try {
167
227
  await this.loadIndex(name, options);
@@ -169,6 +229,9 @@ export class MossClient {
169
229
  }
170
230
  catch (error) {
171
231
  result.failed[name] = error instanceof Error ? error.message : String(error);
232
+ const code = error?.code;
233
+ if (typeof code === "string")
234
+ failedCodes[name] = code;
172
235
  }
173
236
  }
174
237
  return result;
@@ -192,12 +255,22 @@ export class MossClient {
192
255
  ? this.modelIdentityFromInfo(info)
193
256
  : null);
194
257
  }
258
+ /**
259
+ * Install the cloud's snapshot of a loaded index when it is newer. A snapshot no newer
260
+ * than the loaded one, with the same model, downloads nothing and returns `wasUpdated` false.
261
+ */
195
262
  async refreshIndex(indexName) {
196
263
  const im = await this.getIndexManager();
197
264
  return this.modelArtifacts.replaceAfter(indexName, () => im.refreshIndex(indexName), (result) => provenanceAwareIndexManager(im)
198
265
  ? this.modelIdentityFromRefresh(result)
199
266
  : null);
200
267
  }
268
+ /**
269
+ * Embeds `query` locally and searches one loaded index.
270
+ *
271
+ * A blank `query` (empty or only whitespace) returns no results at every
272
+ * `alpha`, without running the embedding model. `topK` 0 returns no results.
273
+ */
201
274
  async query(indexName, query, options) {
202
275
  await this.ensureInitialized();
203
276
  const manager = requireProvenanceAwareIndexManager(this.indexManager);
@@ -205,8 +278,11 @@ export class MossClient {
205
278
  if (!identity) {
206
279
  throw new Error(`Index '${indexName}' has no foundation model artifact identity; use queryWithEmbedding`);
207
280
  }
281
+ if (isBlankQuery(query)) {
282
+ return { docs: [], query, indexName, timeTakenMs: 0 };
283
+ }
208
284
  const embedding = await this.embedder.embed(query, identity);
209
- return manager.queryWithModelIdentity(indexName, query, embedding, identity.modelId, identity.version, identity.manifestSha256, options?.topK, options?.alpha, options?.filter);
285
+ return manager.queryWithModelIdentity(indexName, query, embedding, identity.modelId, identity.version, identity.manifestSha256, options?.topK, options?.alpha, options?.filter, runtimeQueryTuning(options));
210
286
  }
211
287
  async queryWithEmbedding(indexName, query, embedding, options) {
212
288
  const im = await this.getIndexManager();
@@ -214,7 +290,7 @@ export class MossClient {
214
290
  const queryEmbedding = embedding instanceof Float32Array
215
291
  ? embedding
216
292
  : new Float32Array(embedding);
217
- return queryWithResolvedModelIdentity(im, identity, indexName, query, queryEmbedding, options?.topK, options?.alpha, options?.filter);
293
+ return queryWithResolvedModelIdentity(im, identity, indexName, query, queryEmbedding, options?.topK, options?.alpha, options?.filter, runtimeQueryTuning(options));
218
294
  }
219
295
  /**
220
296
  * Search several loaded indexes in one call and return the global top-k,
@@ -223,7 +299,8 @@ export class MossClient {
223
299
  *
224
300
  * `alpha` matches the single-index `query`: `1.0` is embedding-only, `0.0`
225
301
  * is keyword-only, and values between fuse both rankings. `topK` is the
226
- * global cap across the union, not a per-index cap.
302
+ * global cap across the union, not a per-index cap, and 0 returns no results.
303
+ * A blank `query` returns no results without running the embedding model.
227
304
  */
228
305
  async queryMultiIndex(indexNames, query, options) {
229
306
  if (indexNames.length === 0) {
@@ -232,8 +309,11 @@ export class MossClient {
232
309
  await this.ensureInitialized();
233
310
  const manager = requireMultiIndexIndexManager(this.indexManager);
234
311
  const identity = await this.sharedModelIdentity(indexNames);
312
+ if (isBlankQuery(query)) {
313
+ return { docs: [], query, timeTakenMs: 0 };
314
+ }
235
315
  const embedding = await this.embedder.embed(query, identity);
236
- return manager.queryMultiIndexWithModelIdentity(indexNames, query, embedding, identity.modelId, identity.version, identity.manifestSha256, options?.topK, options?.alpha, options?.filter);
316
+ return manager.queryMultiIndexWithModelIdentity(indexNames, query, embedding, identity.modelId, identity.version, identity.manifestSha256, options?.topK, options?.alpha, options?.filter, runtimeQueryTuning(options));
237
317
  }
238
318
  /** As `queryMultiIndex`, with a caller-supplied query vector. */
239
319
  async queryMultiIndexWithEmbedding(indexNames, query, embedding, options) {
@@ -247,9 +327,9 @@ export class MossClient {
247
327
  ? embedding
248
328
  : new Float32Array(embedding);
249
329
  if (identity) {
250
- return manager.queryMultiIndexWithModelIdentity(indexNames, query, queryEmbedding, identity.modelId, identity.version, identity.manifestSha256, options?.topK, options?.alpha, options?.filter);
330
+ return manager.queryMultiIndexWithModelIdentity(indexNames, query, queryEmbedding, identity.modelId, identity.version, identity.manifestSha256, options?.topK, options?.alpha, options?.filter, runtimeQueryTuning(options));
251
331
  }
252
- return manager.queryMultiIndex(indexNames, query, queryEmbedding, options?.topK, options?.alpha, options?.filter);
332
+ return manager.queryMultiIndex(indexNames, query, queryEmbedding, options?.topK, options?.alpha, options?.filter, runtimeQueryTuning(options));
253
333
  }
254
334
  /**
255
335
  * The one model artifact identity every named index shares, or `null` when
@@ -300,7 +380,59 @@ export class MossClient {
300
380
  exactModelIdentity(modelId, version, manifestSha256) {
301
381
  return exactModelArtifactIdentity(modelId, version, manifestSha256);
302
382
  }
383
+ /** Refreshes `indexName` on `im` until the loop is replaced or stopped, or `im` is disposed. */
384
+ startAutoRefresh(indexName, delayMs, im) {
385
+ const loop = { timer: undefined };
386
+ const current = () => this.autoRefreshLoops.get(indexName) === loop && this.indexManager === im;
387
+ const schedule = () => {
388
+ loop.timer = setTimeout(tick, delayMs);
389
+ // Under Node, an idle refresh timer must not keep the process alive.
390
+ loop.timer.unref?.();
391
+ };
392
+ // Unlike `refreshIndex`, a failed tick keeps the index's model identity:
393
+ // the loaded index is unchanged, and dropping it would release the model.
394
+ const tick = async () => {
395
+ if (!current())
396
+ return;
397
+ try {
398
+ const result = await im.refreshIndex(indexName);
399
+ if (current()) {
400
+ this.modelArtifacts.synchronize(indexName, provenanceAwareIndexManager(im) ? this.modelIdentityFromRefresh(result) : null);
401
+ }
402
+ }
403
+ catch (error) {
404
+ if (!current())
405
+ return;
406
+ const loaded = await im.hasIndex(indexName).catch(() => true);
407
+ if (!current())
408
+ return;
409
+ if (!loaded) {
410
+ this.stopAutoRefresh(indexName);
411
+ try {
412
+ this.modelArtifacts.clear(indexName);
413
+ }
414
+ catch { }
415
+ return;
416
+ }
417
+ console.warn(`Moss auto refresh of '${indexName}' failed: ${error instanceof Error ? error.message : String(error)}`);
418
+ }
419
+ if (current())
420
+ schedule();
421
+ };
422
+ this.autoRefreshLoops.set(indexName, loop);
423
+ schedule();
424
+ }
425
+ stopAutoRefresh(indexName) {
426
+ const loop = this.autoRefreshLoops.get(indexName);
427
+ if (!loop)
428
+ return;
429
+ clearTimeout(loop.timer);
430
+ this.autoRefreshLoops.delete(indexName);
431
+ }
303
432
  dispose() {
433
+ for (const indexName of Array.from(this.autoRefreshLoops.keys())) {
434
+ this.stopAutoRefresh(indexName);
435
+ }
304
436
  this.modelArtifacts.clearAll();
305
437
  this.embedder?.dispose();
306
438
  this.indexManager?.free();
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  export { MossClient } from "./client.js";
2
2
  export type { IAuthenticator, AuthToken } from "./auth/authenticator.interface.js";
3
3
  export { ModelDeliveryError } from "./model-delivery.js";
4
- export type { MossClientOptions, MossModel, IndexInfo, SearchResult, QueryResultDocumentInfo, QueryOptions, MetadataFilter, FilterCondition, RefreshResult, ModelRef, ModelArtifactIdentity, DocumentInfo, MutationResult, CreateIndexOptions, MutationOptions, ParseFileInput, JobStatus, JobPhase, JobProgress, JobStatusResponse, GetDocumentsOptions, LoadIndexOptions, LoadIndexesResult, ISODate, } from "./types.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";