@moss-dev/moss-web 1.5.1 → 1.6.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.5.1 resolves `@moss-dev/moss-wasm@0.18.1`. Text `query()` loads its
21
+ Version 1.6.0 resolves `@moss-dev/moss-wasm@0.18.2`. 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. Before 1.2.0 the only published npm versions were 1.0.0 and 1.0.1,
@@ -244,6 +244,150 @@ error.
244
244
  client.dispose();
245
245
  ```
246
246
 
247
+ ## Inference
248
+
249
+ `MossInference` answers OpenAI's `chat.completions.create`, with the same
250
+ arguments and return shapes as in `@moss-js/moss`, through the Moss inference
251
+ gateway. The gateway searches the `indexes` you pass and adds what it finds to
252
+ the prompt, so code written for OpenAI swaps its client for `MossInference` and
253
+ adds `indexes`.
254
+
255
+ A project key in page code is visible to every visitor of the page. So a page
256
+ passes `null` for both credentials and points `baseURL` at a route on its own
257
+ server that adds them, as [the proxy route](#the-proxy-route) shows:
258
+
259
+ ```typescript
260
+ import { MossInference } from "@moss-dev/moss-web";
261
+
262
+ const client = new MossInference(null, null, { baseURL: "/moss/v1" });
263
+ const answer = document.querySelector("#answer")!;
264
+ const messages = [{ role: "user" as const, content: "Do you ship to Canada?" }];
265
+
266
+ const stream = await client.chat.completions.create({
267
+ messages,
268
+ indexes: ["faq"],
269
+ stream: true,
270
+ });
271
+ document.querySelector("#stop")!.addEventListener("click", () => stream.controller.abort());
272
+ for await (const chunk of stream) {
273
+ answer.textContent += chunk.choices[0]?.delta.content ?? "";
274
+ }
275
+ ```
276
+
277
+ `model` is optional and defaults to `"moss"`, Moss's own model. Without
278
+ `stream: true` the call reads the whole stream and returns one completion:
279
+
280
+ ```typescript
281
+ const completion = await client.chat.completions.create(
282
+ { messages, indexes: ["faq"] },
283
+ { timeout: 30_000 },
284
+ );
285
+ answer.textContent = completion.choices[0].message.content;
286
+ ```
287
+
288
+ `baseURL` takes only a path on the page's origin, such as `/moss/v1`. An
289
+ absolute URL, or one that starts with `//`, throws `InferenceError`. Each call
290
+ resolves the path against the page's URL, so a module that builds the client
291
+ during server rendering, where there is no page, works once it runs in the
292
+ browser. A call made with no http or https page rejects with `InferenceError`.
293
+ Without `baseURL` the client calls the Moss inference gateway,
294
+ `https://inference.moss.dev`, which needs the project id and key.
295
+
296
+ `apiKey` is optional: your own OpenAI, Anthropic or Google key, for a vendor
297
+ model such as `gpt-4o-mini`. `moss` ignores it, and a vendor model without one
298
+ is refused. Set it on the client, or pass it with one call, where it wins over
299
+ the client's:
300
+
301
+ ```typescript
302
+ const keyed = new MossInference("your-project-id", "your-project-key", {
303
+ apiKey: "your-openai-key",
304
+ });
305
+ const reply = await keyed.chat.completions.create(
306
+ { model: "gpt-4o-mini", messages },
307
+ { apiKey: "your-other-openai-key" },
308
+ );
309
+ ```
310
+
311
+ Like a project key, a provider key in page code is visible to every visitor, so
312
+ a page that uses [the proxy route](#the-proxy-route) leaves it to the route.
313
+
314
+ The other client options are `timeout` for each whole call (no limit by
315
+ default), `idleTimeout` for the longest wait for response headers or for more of
316
+ the body (120 000 ms by default, `null` for none) and `headers`. Each call takes
317
+ `apiKey`, `signal`, `timeout`, `idleTimeout` and `headers`, which replace or add
318
+ to the client's for that call. `retrieve: false` skips the search.
319
+
320
+ Leaving the `for await` loop early, or calling `stream.controller.abort()`,
321
+ closes the connection, stops the model and ends the loop quietly. An abort with
322
+ any other reason, such as the `TimeoutError` of `AbortSignal.timeout()`, throws
323
+ that reason. Without `stream: true`, an abort rejects with the signal's reason,
324
+ an `AbortError` for a plain `abort()`. Every other failure throws
325
+ `InferenceError` with `status` and `type`, including an error the model reports
326
+ mid-stream, a stream that ends early (`incomplete_stream`), a broken connection
327
+ (`connection_error`) and a timeout (`timeout`). It also carries the gateway's
328
+ `errorCode`, the response's `requestId` and, for a `429` or another error that
329
+ sends `Retry-After`, `retryAfter` in milliseconds. A call straight to the
330
+ gateway gets `requestId` but no `retryAfter`, since the gateway's CORS headers
331
+ do not expose `Retry-After` to the page. [The proxy route](#the-proxy-route)
332
+ passes both headers back to the page. A browser may report a stream cut off
333
+ mid-reply as a network error, which is a `connection_error`. The client does
334
+ not follow redirects: a redirect throws `InferenceError`, with no `status` in a
335
+ browser, which hides it.
336
+
337
+ ### The proxy route
338
+
339
+ With `null` credentials the client sends no `Authorization` header, and an
340
+ `Authorization` header you pass in `headers`, such as the visitor's session
341
+ token, reaches your route unchanged. The route checks the visitor, decides which
342
+ indexes the call may search, adds the project credentials and forwards the call
343
+ to the gateway. In a server framework whose handlers take a `Request` and return
344
+ a `Response`, it can look like this:
345
+
346
+ ```typescript
347
+ // Serves POST /moss/v1/chat/completions. Check the visitor's session first,
348
+ // since every call through this route spends your project's quota.
349
+ const GATEWAY = "https://inference.moss.dev/v1/chat/completions";
350
+ const INDEXES = ["faq"];
351
+ const FORWARD = ["content-type", "accept"];
352
+ const REPLY = ["content-type", "retry-after", "x-moss-request-id"];
353
+
354
+ export async function POST(request: Request): Promise<Response> {
355
+ const { MOSS_PROJECT_ID, MOSS_PROJECT_KEY } = process.env;
356
+ const indexes = request.headers.get("x-moss-indexes")?.split(",") ?? INDEXES;
357
+ if (!indexes.every((name) => INDEXES.includes(name))) {
358
+ return Response.json({ detail: "This page cannot search that index." }, { status: 403 });
359
+ }
360
+ const headers = new Headers();
361
+ for (const name of FORWARD) {
362
+ const value = request.headers.get(name);
363
+ if (value !== null) headers.set(name, value);
364
+ }
365
+ headers.set("X-Moss-Indexes", indexes.join(","));
366
+ headers.set("Authorization", `Bearer ${MOSS_PROJECT_ID}:${MOSS_PROJECT_KEY}`);
367
+ const reply = await fetch(GATEWAY, {
368
+ method: "POST",
369
+ headers,
370
+ body: await request.text(),
371
+ signal: request.signal,
372
+ redirect: "manual",
373
+ });
374
+ const replyHeaders = [...reply.headers].filter(([name]) => REPLY.includes(name));
375
+ return new Response(reply.body, { status: reply.status, headers: replyHeaders });
376
+ }
377
+ ```
378
+
379
+ The page's headers reach the gateway only when the route forwards them by name,
380
+ since every visitor can set them. Back to the page it passes `Content-Type`,
381
+ `Retry-After` and `X-Moss-Request-Id`, so an `InferenceError` there carries
382
+ `retryAfter` and `requestId`. The route refuses an index that is not in its
383
+ list, and always sends `X-Moss-Indexes`, because a call without it searches
384
+ every index in the project. So `retrieve` and `apiKey` in page code do not
385
+ reach the gateway, and a route that wants them sets those headers itself, such
386
+ as `X-Moss-Provider-Key` for your own provider key.
387
+
388
+ Passing the project id and key instead of `null`, without `baseURL`, sends them
389
+ from the page straight to the gateway, which suits prototypes and internal tools.
390
+
247
391
  ## Telemetry
248
392
 
249
393
  The browser SDK always sends usage telemetry to the Moss cloud, and there is no
package/dist/index.d.ts CHANGED
@@ -1,4 +1,10 @@
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 { MossInference } from "./inference/index.js";
5
+ export type { ChatCompletions } from "./inference/index.js";
6
+ export { ChatCompletionStream } from "./inference/stream.js";
7
+ export { InferenceError } from "./inference/error.js";
8
+ export type { InferenceErrorType } from "./inference/error.js";
9
+ export type { ChatCompletion, ChatCompletionChoice, ChatCompletionChunk, ChatCompletionChunkChoice, ChatCompletionChunkDelta, ChatCompletionChunkToolCall, ChatCompletionContentPart, ChatCompletionCreateParams, ChatCompletionCreateParamsBase, ChatCompletionCreateParamsNonStreaming, ChatCompletionCreateParamsStreaming, ChatCompletionMessage, ChatCompletionMessageParam, ChatCompletionMessageToolCall, ChatCompletionTool, CompletionUsage, InferenceRequestOptions, MossInferenceOptions, } from "./inference/types.js";
4
10
  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,2 +1,6 @@
1
1
  export { MossClient } from "./client.js";
2
2
  export { ModelDeliveryError } from "./model-delivery.js";
3
+ // Chat completions through the Moss inference gateway, in OpenAI's shape
4
+ export { MossInference } from "./inference/index.js";
5
+ export { ChatCompletionStream } from "./inference/stream.js";
6
+ export { InferenceError } from "./inference/error.js";
@@ -0,0 +1,52 @@
1
+ /** The kind of failure an {@link InferenceError} reports. */
2
+ export type InferenceErrorType = "authentication_error" | "permission_error" | "not_found_error" | "invalid_request_error" | "rate_limit_error" | "model_error" | "server_error" | "connection_error" | "timeout" | "incomplete_stream" | (string & {});
3
+ /**
4
+ * The error every inference call throws, before or during the stream.
5
+ * Arguments the SDK rejects before sending carry `invalid_request_error` and no status.
6
+ * A caller's abort rejects with the signal's reason, or ends a stream quietly on an `AbortError`.
7
+ */
8
+ export declare class InferenceError extends Error {
9
+ /** The HTTP status of a rejected request. Undefined for transport and stream failures. */
10
+ readonly status: number | undefined;
11
+ /** The gateway's `error.type`, or one derived from the status or the failure. */
12
+ readonly type: InferenceErrorType;
13
+ /** The gateway's `error.code`, a string or a safe integer in decimal. Undefined otherwise. */
14
+ readonly errorCode?: string;
15
+ /** The `X-Moss-Request-Id` of the response. Undefined when the call failed before one arrived. */
16
+ readonly requestId?: string;
17
+ /**
18
+ * The `Retry-After` of an error response in milliseconds, when it gives whole seconds.
19
+ * A direct gateway call gets none, since the gateway's CORS headers do not expose `Retry-After`.
20
+ */
21
+ readonly retryAfter?: number;
22
+ constructor(message: string, init: {
23
+ type: InferenceErrorType;
24
+ status?: number;
25
+ errorCode?: string;
26
+ requestId?: string;
27
+ retryAfter?: number;
28
+ cause?: unknown;
29
+ });
30
+ }
31
+ /** What an {@link InferenceError} takes from the response headers. */
32
+ export interface ResponseFields {
33
+ requestId?: string;
34
+ retryAfter?: number;
35
+ }
36
+ /**
37
+ * The request id of any response, and for an error response
38
+ * the `Retry-After` in milliseconds when the header holds delta-seconds.
39
+ */
40
+ export declare function responseFields(response: Response): ResponseFields;
41
+ /**
42
+ * The gateway's `error.code` as text: a string as sent, a safe integer in decimal.
43
+ * A larger integer gives none, since `JSON.parse` can change its digits.
44
+ */
45
+ export declare function codeText(code: unknown): string | undefined;
46
+ /** The error for a fetch or body read that failed in transport, a `timeout` or a `connection_error`. */
47
+ export declare function transportError(error: unknown, message: string, fields?: ResponseFields): InferenceError;
48
+ /**
49
+ * Builds the error for a non-2xx response from its status and body text.
50
+ * A body that is not JSON gives the message, and an empty one the status line.
51
+ */
52
+ export declare function errorFromResponse(response: Response, text: string): InferenceError;
@@ -0,0 +1,103 @@
1
+ /**
2
+ * The error every inference call throws, before or during the stream.
3
+ * Arguments the SDK rejects before sending carry `invalid_request_error` and no status.
4
+ * A caller's abort rejects with the signal's reason, or ends a stream quietly on an `AbortError`.
5
+ */
6
+ export class InferenceError extends Error {
7
+ constructor(message, init) {
8
+ super(message);
9
+ this.name = "InferenceError";
10
+ this.type = init.type;
11
+ this.status = init.status;
12
+ this.errorCode = init.errorCode;
13
+ this.requestId = init.requestId;
14
+ this.retryAfter = init.retryAfter;
15
+ if (init.cause !== undefined) {
16
+ Object.defineProperty(this, "cause", {
17
+ value: init.cause,
18
+ writable: true,
19
+ configurable: true,
20
+ });
21
+ }
22
+ }
23
+ }
24
+ /**
25
+ * The request id of any response, and for an error response
26
+ * the `Retry-After` in milliseconds when the header holds delta-seconds.
27
+ */
28
+ export function responseFields(response) {
29
+ const retry = response.ok ? null : response.headers.get("Retry-After");
30
+ return {
31
+ requestId: response.headers.get("X-Moss-Request-Id") || undefined,
32
+ retryAfter: retry !== null && /^\d+$/.test(retry) ? Number(retry) * 1000 : undefined,
33
+ };
34
+ }
35
+ /**
36
+ * The gateway's `error.code` as text: a string as sent, a safe integer in decimal.
37
+ * A larger integer gives none, since `JSON.parse` can change its digits.
38
+ */
39
+ export function codeText(code) {
40
+ if (typeof code === "string")
41
+ return code;
42
+ return Number.isSafeInteger(code) ? String(code) : undefined;
43
+ }
44
+ const TYPE_BY_STATUS = {
45
+ 401: "authentication_error",
46
+ 403: "permission_error",
47
+ 404: "not_found_error",
48
+ 429: "rate_limit_error",
49
+ };
50
+ /** The longest message a body that is not JSON gives, in characters. */
51
+ const MAX_BODY_MESSAGE = 300;
52
+ /** The body with its whitespace collapsed, cut to {@link MAX_BODY_MESSAGE} characters. */
53
+ function bodyMessage(text) {
54
+ const chars = Array.from(text.replace(/\s+/g, " ").trim());
55
+ if (chars.length <= MAX_BODY_MESSAGE)
56
+ return chars.join("") || undefined;
57
+ return `${chars.slice(0, MAX_BODY_MESSAGE - 3).join("")}...`;
58
+ }
59
+ /** undici's codes for the time limits of Node's fetch, including its 300 s limits on silence. */
60
+ const TIMEOUT_CODES = new Set([
61
+ "UND_ERR_CONNECT_TIMEOUT",
62
+ "UND_ERR_HEADERS_TIMEOUT",
63
+ "UND_ERR_BODY_TIMEOUT",
64
+ ]);
65
+ /** The error for a fetch or body read that failed in transport, a `timeout` or a `connection_error`. */
66
+ export function transportError(error, message, fields = {}) {
67
+ const cause = error?.cause;
68
+ const detail = typeof cause?.message === "string" ? cause.message : String(error);
69
+ const type = TIMEOUT_CODES.has(cause?.code) ? "timeout" : "connection_error";
70
+ return new InferenceError(`${message}: ${detail}`, { type, cause: error, ...fields });
71
+ }
72
+ /**
73
+ * Builds the error for a non-2xx response from its status and body text.
74
+ * A body that is not JSON gives the message, and an empty one the status line.
75
+ */
76
+ export function errorFromResponse(response, text) {
77
+ let body;
78
+ let message = `HTTP ${response.status}${response.statusText ? ` ${response.statusText}` : ""}`;
79
+ try {
80
+ body = JSON.parse(text);
81
+ }
82
+ catch {
83
+ message = bodyMessage(text) ?? message;
84
+ }
85
+ const { error, detail } = (body ?? {});
86
+ if (typeof error?.message === "string")
87
+ message = error.message;
88
+ else if (typeof detail === "string")
89
+ message = detail;
90
+ else if (detail !== undefined)
91
+ message = JSON.stringify(detail);
92
+ return new InferenceError(message, {
93
+ type: typeof error?.type === "string"
94
+ ? error.type
95
+ : (TYPE_BY_STATUS[response.status] ??
96
+ (response.status >= 400 && response.status < 500
97
+ ? "invalid_request_error"
98
+ : "server_error")),
99
+ status: response.status,
100
+ errorCode: codeText(error?.code),
101
+ ...responseFields(response),
102
+ });
103
+ }
@@ -0,0 +1,35 @@
1
+ import { ChatCompletionStream } from "./stream.js";
2
+ import type { ChatCompletion, ChatCompletionCreateParams, ChatCompletionCreateParamsNonStreaming, ChatCompletionCreateParamsStreaming, InferenceRequestOptions, MossInferenceOptions } from "./types.js";
3
+ /** The `chat.completions` namespace of a {@link MossInference} client, shaped like OpenAI's. */
4
+ export interface ChatCompletions {
5
+ /**
6
+ * Sends a chat completion through the Moss inference gateway.
7
+ *
8
+ * The gateway searches `indexes` and adds what it finds to the prompt.
9
+ * Failures reject with {@link InferenceError}. With `stream: true` this
10
+ * resolves to a {@link ChatCompletionStream} once the gateway accepts the request,
11
+ * and otherwise to one {@link ChatCompletion} built from the whole stream.
12
+ */
13
+ create(params: ChatCompletionCreateParamsStreaming, options?: InferenceRequestOptions): Promise<ChatCompletionStream>;
14
+ create(params: ChatCompletionCreateParamsNonStreaming, options?: InferenceRequestOptions): Promise<ChatCompletion>;
15
+ create(params: ChatCompletionCreateParams, options?: InferenceRequestOptions): Promise<ChatCompletionStream | ChatCompletion>;
16
+ }
17
+ /**
18
+ * A drop-in for OpenAI's client that answers from your Moss indexes.
19
+ *
20
+ * The constructor throws {@link InferenceError} with `invalid_request_error`
21
+ * when the credentials, provider key, headers, timeouts or `baseURL` are wrong.
22
+ * A call through a `baseURL` path rejects the same way without an http or https page.
23
+ * Null credentials send no `Authorization` header, for a route on your server that adds it.
24
+ */
25
+ export declare class MossInference {
26
+ #private;
27
+ /** OpenAI's `chat.completions`, answered by the Moss inference gateway. */
28
+ readonly chat: {
29
+ readonly completions: ChatCompletions;
30
+ };
31
+ constructor(projectId: string, projectKey: string, options?: MossInferenceOptions);
32
+ constructor(projectId: null, projectKey: null, options: MossInferenceOptions & {
33
+ baseURL: string;
34
+ });
35
+ }
@@ -0,0 +1,228 @@
1
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
2
+ if (kind === "m") throw new TypeError("Private method is not writable");
3
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
4
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
5
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
6
+ };
7
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
8
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
9
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
+ };
12
+ var _MossInference_instances, _MossInference_path, _MossInference_headers, _MossInference_own, _MossInference_timeout, _MossInference_idleTimeout, _MossInference_apiKey, _MossInference_create;
13
+ import { InferenceError, errorFromResponse, responseFields, transportError, } from "./error.js";
14
+ import { ChatCompletionStream, aggregate, errorText, idleTimer } from "./stream.js";
15
+ /** The production gateway, up to and including `/v1`. */
16
+ const DEFAULT_URL = "https://inference.moss.dev/v1";
17
+ const DEFAULT_MODEL = "moss";
18
+ const DEFAULT_IDLE_TIMEOUT = 120000;
19
+ /** The longest delay `setTimeout` holds. */
20
+ const MAX_DELAY = 2 ** 31 - 1;
21
+ function invalid(message) {
22
+ return new InferenceError(message, { type: "invalid_request_error" });
23
+ }
24
+ /**
25
+ * Printable Latin-1 with no space or tab at either end, which fetch would trim.
26
+ * It avoids a lookbehind, which Safari before 16.4 cannot parse.
27
+ */
28
+ const HEADER_SAFE = /^(?:[\x21-\x7e\x80-\xff](?:[\t\x20-\x7e\x80-\xff]*[\x21-\x7e\x80-\xff])?)?$/;
29
+ /** Returns `value` when a header carries it unchanged. The error names `what`, never the value. */
30
+ function headerSafe(what, value) {
31
+ if (typeof value === "string" && HEADER_SAFE.test(value))
32
+ return value;
33
+ throw invalid(`${what} must be printable Latin-1 text without surrounding spaces.`);
34
+ }
35
+ function credential(what, value) {
36
+ if (value == null || value === "")
37
+ throw invalid(`${what} is missing or empty.`);
38
+ return headerSafe(what, value);
39
+ }
40
+ function headersOf(init) {
41
+ let headers;
42
+ try {
43
+ headers = new Headers(init);
44
+ }
45
+ catch {
46
+ throw invalid("The headers option holds a name or value a header cannot carry.");
47
+ }
48
+ for (const [name, value] of headers)
49
+ headerSafe(`The ${name} header`, value);
50
+ return headers;
51
+ }
52
+ /** Milliseconds for a timer, or null for no limit. */
53
+ function delay(what, value) {
54
+ if (value === null || value === Infinity)
55
+ return null;
56
+ if (typeof value === "number" && value > 0 && value < Infinity)
57
+ return Math.min(value, MAX_DELAY);
58
+ throw invalid(`${what} must be a positive number of milliseconds, or null for no limit.`);
59
+ }
60
+ /**
61
+ * A path with one leading slash, in printable ASCII without a space or backslash.
62
+ * Resolved against an http or https page, it always stays on the page's origin.
63
+ */
64
+ const PATH = /^\/(?!\/)[\x21-\x5b\x5d-\x7e]*$/;
65
+ /**
66
+ * Returns `baseURL` when it is such a path, with no query or fragment.
67
+ * The errors name `baseURL` but never quote the value the caller passed.
68
+ */
69
+ function proxyPath(baseURL) {
70
+ if (typeof baseURL !== "string" || !PATH.test(baseURL))
71
+ throw invalid("baseURL must be a path on the page's origin, such as /moss/v1.");
72
+ if (/[?#]/.test(baseURL))
73
+ throw invalid("baseURL must not hold a query or a fragment.");
74
+ return baseURL;
75
+ }
76
+ /** The chat completions URL under `path` on the origin of the current page. */
77
+ function onPage(path) {
78
+ let url;
79
+ try {
80
+ url = new URL(path, globalThis.location.href);
81
+ }
82
+ catch {
83
+ url = undefined;
84
+ }
85
+ if (!url || !["http:", "https:"].includes(url.protocol))
86
+ throw invalid("baseURL is a path on the page's origin, so it needs an http or https page.");
87
+ return `${url.origin}${url.pathname.replace(/\/+$/, "")}/chat/completions`;
88
+ }
89
+ /**
90
+ * A drop-in for OpenAI's client that answers from your Moss indexes.
91
+ *
92
+ * The constructor throws {@link InferenceError} with `invalid_request_error`
93
+ * when the credentials, provider key, headers, timeouts or `baseURL` are wrong.
94
+ * A call through a `baseURL` path rejects the same way without an http or https page.
95
+ * Null credentials send no `Authorization` header, for a route on your server that adds it.
96
+ */
97
+ export class MossInference {
98
+ constructor(projectId, projectKey, options = {}) {
99
+ _MossInference_instances.add(this);
100
+ /** The `baseURL` path each call resolves against the page, or undefined for the gateway. */
101
+ _MossInference_path.set(this, void 0);
102
+ /** The caller's headers for every call. */
103
+ _MossInference_headers.set(this, void 0);
104
+ /** The SDK's own headers, which win over the caller's. */
105
+ _MossInference_own.set(this, void 0);
106
+ _MossInference_timeout.set(this, void 0);
107
+ _MossInference_idleTimeout.set(this, void 0);
108
+ /** The provider key for calls that do not pass their own. */
109
+ _MossInference_apiKey.set(this, void 0);
110
+ __classPrivateFieldSet(this, _MossInference_own, new Headers({ "Content-Type": "application/json", Accept: "text/event-stream" }), "f");
111
+ if (projectId !== null || projectKey !== null) {
112
+ if (projectId === null || projectKey === null)
113
+ throw invalid("Pass both projectId and projectKey, or null for both.");
114
+ const id = credential("projectId", projectId);
115
+ const key = credential("projectKey", projectKey);
116
+ if (id.includes(":"))
117
+ throw invalid("projectId must not contain a colon.");
118
+ __classPrivateFieldGet(this, _MossInference_own, "f").set("Authorization", `Bearer ${id}:${key}`);
119
+ }
120
+ else if (options.baseURL == null) {
121
+ throw invalid("Null credentials need baseURL, the path of a route on your server that adds them.");
122
+ }
123
+ __classPrivateFieldSet(this, _MossInference_path, options.baseURL == null ? undefined : proxyPath(options.baseURL), "f");
124
+ __classPrivateFieldSet(this, _MossInference_timeout, delay("timeout", options.timeout ?? null), "f");
125
+ const { idleTimeout = DEFAULT_IDLE_TIMEOUT } = options;
126
+ __classPrivateFieldSet(this, _MossInference_idleTimeout, delay("idleTimeout", idleTimeout), "f");
127
+ __classPrivateFieldSet(this, _MossInference_headers, headersOf(options.headers), "f");
128
+ __classPrivateFieldSet(this, _MossInference_apiKey, options.apiKey == null ? undefined : credential("apiKey", options.apiKey), "f");
129
+ const create = (params, call) => __classPrivateFieldGet(this, _MossInference_instances, "m", _MossInference_create).call(this, params, call);
130
+ this.chat = Object.freeze({
131
+ completions: Object.freeze({ create: create }),
132
+ });
133
+ }
134
+ }
135
+ _MossInference_path = new WeakMap(), _MossInference_headers = new WeakMap(), _MossInference_own = new WeakMap(), _MossInference_timeout = new WeakMap(), _MossInference_idleTimeout = new WeakMap(), _MossInference_apiKey = new WeakMap(), _MossInference_instances = new WeakSet(), _MossInference_create = async function _MossInference_create(params, options = {}) {
136
+ const url = __classPrivateFieldGet(this, _MossInference_path, "f") === undefined ? `${DEFAULT_URL}/chat/completions` : onPage(__classPrivateFieldGet(this, _MossInference_path, "f"));
137
+ const { indexes, retrieve, model = DEFAULT_MODEL, ...body } = params;
138
+ if (body.apiKey !== undefined || body.api_key !== undefined)
139
+ throw invalid("Pass the provider key as apiKey in the options of create, not in params.");
140
+ if (indexes !== undefined && !Array.isArray(indexes))
141
+ throw invalid("indexes must be an array of index names.");
142
+ for (const name of indexes ?? []) {
143
+ if (typeof name !== "string" || name === "" || name.includes(",")) {
144
+ throw invalid(`Invalid index name ${JSON.stringify(name)}. Names must be non-empty and contain no comma.`);
145
+ }
146
+ headerSafe(`Index name ${JSON.stringify(name)}`, name);
147
+ }
148
+ const apiKey = options.apiKey == null ? __classPrivateFieldGet(this, _MossInference_apiKey, "f") : credential("apiKey", options.apiKey);
149
+ const timeout = options.timeout === undefined ? __classPrivateFieldGet(this, _MossInference_timeout, "f") : delay("timeout", options.timeout);
150
+ const idleTimeout = options.idleTimeout === undefined
151
+ ? __classPrivateFieldGet(this, _MossInference_idleTimeout, "f")
152
+ : delay("idleTimeout", options.idleTimeout);
153
+ const headers = new Headers(__classPrivateFieldGet(this, _MossInference_headers, "f"));
154
+ for (const [name, value] of headersOf(options.headers))
155
+ headers.set(name, value);
156
+ for (const [name, value] of __classPrivateFieldGet(this, _MossInference_own, "f"))
157
+ headers.set(name, value);
158
+ if (indexes?.length)
159
+ headers.set("X-Moss-Indexes", indexes.join(","));
160
+ if (retrieve === false)
161
+ headers.set("X-Moss-Retrieve", "off");
162
+ if (apiKey !== undefined)
163
+ headers.set("X-Moss-Provider-Key", apiKey);
164
+ let payload;
165
+ try {
166
+ payload = JSON.stringify({ model, ...body, stream: true });
167
+ }
168
+ catch (cause) {
169
+ throw new InferenceError(`The parameters cannot be sent as JSON: ${String(cause)}`, {
170
+ type: "invalid_request_error",
171
+ cause,
172
+ });
173
+ }
174
+ const { signal } = options;
175
+ const controller = new AbortController();
176
+ let fields = {};
177
+ const expire = (message) => () => controller.abort(new InferenceError(message, { type: "timeout", ...fields }));
178
+ const timer = timeout === null
179
+ ? undefined
180
+ : setTimeout(expire(`The request timed out after ${timeout} ms.`), timeout);
181
+ const idle = idleTimer(idleTimeout, expire(`The gateway sent nothing for ${idleTimeout} ms.`));
182
+ const onAbort = () => controller.abort(signal?.reason);
183
+ signal?.addEventListener("abort", onAbort, { once: true });
184
+ if (signal?.aborted)
185
+ onAbort();
186
+ const settle = () => {
187
+ clearTimeout(timer);
188
+ idle.clear();
189
+ signal?.removeEventListener("abort", onAbort);
190
+ };
191
+ let response;
192
+ try {
193
+ idle.arm();
194
+ response = await fetch(url, {
195
+ method: "POST",
196
+ headers,
197
+ body: payload,
198
+ signal: controller.signal,
199
+ redirect: "manual",
200
+ });
201
+ }
202
+ catch (error) {
203
+ settle();
204
+ if (controller.signal.aborted)
205
+ throw controller.signal.reason;
206
+ const failure = transportError(error, "The inference gateway did not answer");
207
+ if (failure.type === "connection_error") {
208
+ failure.message = `${failure.message.replace(/\.$/, "")}. Check the network, and that the gateway allows this page's origin (CORS).`;
209
+ }
210
+ throw failure;
211
+ }
212
+ idle.clear();
213
+ fields = responseFields(response);
214
+ if (response.type === "opaqueredirect") {
215
+ settle();
216
+ const message = "The gateway answered with a redirect, which the client does not follow.";
217
+ throw new InferenceError(message, { type: "server_error" });
218
+ }
219
+ if (!response.ok) {
220
+ const text = await errorText(response, idle).catch(() => "");
221
+ settle();
222
+ if (controller.signal.aborted)
223
+ throw controller.signal.reason;
224
+ throw errorFromResponse(response, text);
225
+ }
226
+ const stream = new ChatCompletionStream(response, controller, idle, settle);
227
+ return params.stream ? stream : aggregate(stream, model);
228
+ };
@@ -0,0 +1,31 @@
1
+ import type { ChatCompletion, ChatCompletionChunk } from "./types.js";
2
+ /** A timer that runs only while armed, so a slow reader never trips it. */
3
+ interface IdleTimer {
4
+ arm(): void;
5
+ clear(): void;
6
+ }
7
+ /** Calls `onIdle` when an armed timer runs `ms` milliseconds. Null `ms` never fires. */
8
+ export declare function idleTimer(ms: number | null, onIdle: () => void): IdleTimer;
9
+ /**
10
+ * Reads an error body, arming `idle` while each read waits.
11
+ * It stops after {@link MAX_ERROR_BODY} bytes and cancels the rest of the body.
12
+ */
13
+ export declare function errorText(response: Response, idle: IdleTimer): Promise<string>;
14
+ /**
15
+ * The streamed reply of `chat.completions.create` with `stream: true`.
16
+ *
17
+ * Iterate it once with `for await`. Leaving the loop early, or calling
18
+ * `controller.abort()`, ends the loop quietly, closes the connection and stops the model.
19
+ * An abort with any other reason, such as the `TimeoutError` of `AbortSignal.timeout()`, throws it.
20
+ * A failure inside the stream throws an {@link InferenceError} after the chunks that came before it.
21
+ */
22
+ export declare class ChatCompletionStream implements AsyncIterable<ChatCompletionChunk> {
23
+ #private;
24
+ /** Aborts the request. */
25
+ readonly controller: AbortController;
26
+ /** Iterates the chunks once. Its `return()` closes the connection, even before the first chunk. */
27
+ [Symbol.asyncIterator](): AsyncIterator<ChatCompletionChunk>;
28
+ }
29
+ /** Consumes every chunk and builds one completion, as a non-streaming call returns. */
30
+ export declare function aggregate(stream: ChatCompletionStream, model: string): Promise<ChatCompletion>;
31
+ export {};
@@ -0,0 +1,270 @@
1
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
2
+ if (kind === "m") throw new TypeError("Private method is not writable");
3
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
4
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
5
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
6
+ };
7
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
8
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
9
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
+ };
12
+ var _ChatCompletionStream_chunks;
13
+ import { InferenceError, codeText, responseFields, transportError, } from "./error.js";
14
+ /** The most UTF-16 code units in one line or in the data of one event. */
15
+ const MAX_EVENT = 1 << 20;
16
+ /** The most bytes of an error body read for its message. */
17
+ const MAX_ERROR_BODY = 1 << 20;
18
+ /** Calls `onIdle` when an armed timer runs `ms` milliseconds. Null `ms` never fires. */
19
+ export function idleTimer(ms, onIdle) {
20
+ let timer;
21
+ return {
22
+ arm() {
23
+ clearTimeout(timer);
24
+ if (ms !== null)
25
+ timer = setTimeout(onIdle, ms);
26
+ },
27
+ clear: () => clearTimeout(timer),
28
+ };
29
+ }
30
+ /**
31
+ * Reads an error body, arming `idle` while each read waits.
32
+ * It stops after {@link MAX_ERROR_BODY} bytes and cancels the rest of the body.
33
+ */
34
+ export async function errorText(response, idle) {
35
+ if (!response.body)
36
+ return "";
37
+ const reader = response.body.getReader();
38
+ const decoder = new TextDecoder();
39
+ let text = "";
40
+ let size = 0;
41
+ try {
42
+ while (size < MAX_ERROR_BODY) {
43
+ idle.arm();
44
+ const { value, done } = await reader.read();
45
+ idle.clear();
46
+ if (done)
47
+ break;
48
+ size += value.byteLength;
49
+ text += decoder.decode(value, { stream: true });
50
+ }
51
+ return text + decoder.decode();
52
+ }
53
+ finally {
54
+ reader.cancel().catch(() => { });
55
+ }
56
+ }
57
+ /** True for the reason of a plain `abort()`, which ends a stream quietly. */
58
+ function isAbortError(reason) {
59
+ return reason?.name === "AbortError";
60
+ }
61
+ /** True when the socket ended with no OS error, which undici reports as `UND_ERR_SOCKET`. */
62
+ function socketEnded(error) {
63
+ return error?.cause?.code === "UND_ERR_SOCKET";
64
+ }
65
+ /**
66
+ * Yields the data of each server-sent event, joining multi-line data with `\n`.
67
+ * Like any SSE parser, it drops an event that the body ends before its blank line.
68
+ * It splits only the newly read text, so a long line costs time in proportion to its length.
69
+ * A line or the data of one event over {@link MAX_EVENT} throws a `server_error` InferenceError.
70
+ */
71
+ async function* sseData(body, idle, fields) {
72
+ const reader = body.getReader();
73
+ const decoder = new TextDecoder();
74
+ const tooLarge = () => new InferenceError("The gateway sent an event over 1 MiB.", {
75
+ type: "server_error",
76
+ ...fields,
77
+ });
78
+ let pending = "";
79
+ let data = [];
80
+ let size = 0;
81
+ try {
82
+ for (;;) {
83
+ idle.arm();
84
+ const { value, done } = await reader.read();
85
+ idle.clear();
86
+ if (done)
87
+ return;
88
+ const lines = decoder.decode(value, { stream: true }).split("\n");
89
+ lines[0] = pending + lines[0];
90
+ pending = lines.pop() ?? "";
91
+ for (const raw of lines) {
92
+ if (raw.length > MAX_EVENT)
93
+ throw tooLarge();
94
+ const line = raw.endsWith("\r") ? raw.slice(0, -1) : raw;
95
+ if (line === "") {
96
+ if (data.length > 0)
97
+ yield data.join("\n");
98
+ data = [];
99
+ size = 0;
100
+ }
101
+ else if (line.startsWith("data:")) {
102
+ const part = line.slice(line.startsWith("data: ") ? 6 : 5);
103
+ size += part.length + (data.length > 0 ? 1 : 0);
104
+ if (size > MAX_EVENT)
105
+ throw tooLarge();
106
+ data.push(part);
107
+ }
108
+ }
109
+ if (pending.length > MAX_EVENT)
110
+ throw tooLarge();
111
+ }
112
+ }
113
+ finally {
114
+ reader.cancel().catch(() => { });
115
+ }
116
+ }
117
+ /**
118
+ * The streamed reply of `chat.completions.create` with `stream: true`.
119
+ *
120
+ * Iterate it once with `for await`. Leaving the loop early, or calling
121
+ * `controller.abort()`, ends the loop quietly, closes the connection and stops the model.
122
+ * An abort with any other reason, such as the `TimeoutError` of `AbortSignal.timeout()`, throws it.
123
+ * A failure inside the stream throws an {@link InferenceError} after the chunks that came before it.
124
+ */
125
+ export class ChatCompletionStream {
126
+ /** @internal */
127
+ constructor(response, controller, idle, onSettled) {
128
+ _ChatCompletionStream_chunks.set(this, void 0);
129
+ this.controller = controller;
130
+ const generator = chunks(response, controller, idle, onSettled);
131
+ __classPrivateFieldSet(this, _ChatCompletionStream_chunks, {
132
+ next: () => generator.next(),
133
+ return: (value) => {
134
+ controller.abort();
135
+ onSettled();
136
+ return generator.return(value);
137
+ },
138
+ }, "f");
139
+ }
140
+ /** Iterates the chunks once. Its `return()` closes the connection, even before the first chunk. */
141
+ [(_ChatCompletionStream_chunks = new WeakMap(), Symbol.asyncIterator)]() {
142
+ const iterator = __classPrivateFieldGet(this, _ChatCompletionStream_chunks, "f");
143
+ if (!iterator)
144
+ throw new Error("A ChatCompletionStream can be iterated only once.");
145
+ __classPrivateFieldSet(this, _ChatCompletionStream_chunks, undefined, "f");
146
+ return iterator;
147
+ }
148
+ }
149
+ async function* chunks(response, controller, idle, onSettled) {
150
+ const notObject = "The gateway sent an event that is not a JSON object.";
151
+ const fields = responseFields(response);
152
+ let done = false;
153
+ try {
154
+ if (!response.body) {
155
+ throw new InferenceError("The response has no body.", {
156
+ type: "incomplete_stream",
157
+ ...fields,
158
+ });
159
+ }
160
+ for await (const data of sseData(response.body, idle, fields)) {
161
+ if (data === "[DONE]") {
162
+ done = true;
163
+ return;
164
+ }
165
+ let event;
166
+ try {
167
+ event = JSON.parse(data);
168
+ }
169
+ catch (cause) {
170
+ throw new InferenceError(notObject, { type: "server_error", cause, ...fields });
171
+ }
172
+ if (typeof event !== "object" || event === null || Array.isArray(event)) {
173
+ throw new InferenceError(notObject, { type: "server_error", ...fields });
174
+ }
175
+ if (event.error) {
176
+ const { message, type, code } = event.error;
177
+ throw new InferenceError(typeof message === "string" ? message : "The model failed during the stream.", {
178
+ type: typeof type === "string" ? type : "model_error",
179
+ errorCode: codeText(code),
180
+ ...fields,
181
+ });
182
+ }
183
+ yield event;
184
+ }
185
+ throw new InferenceError("The stream ended before [DONE].", {
186
+ type: "incomplete_stream",
187
+ ...fields,
188
+ });
189
+ }
190
+ catch (error) {
191
+ if (error instanceof InferenceError)
192
+ throw error;
193
+ const { aborted, reason } = controller.signal;
194
+ if (aborted) {
195
+ if (isAbortError(reason))
196
+ return;
197
+ throw reason;
198
+ }
199
+ if (socketEnded(error)) {
200
+ throw new InferenceError("The connection closed before [DONE].", {
201
+ type: "incomplete_stream",
202
+ cause: error,
203
+ ...fields,
204
+ });
205
+ }
206
+ throw transportError(error, "The connection failed", fields);
207
+ }
208
+ finally {
209
+ if (!done)
210
+ controller.abort();
211
+ onSettled();
212
+ }
213
+ }
214
+ /** Consumes every chunk and builds one completion, as a non-streaming call returns. */
215
+ export async function aggregate(stream, model) {
216
+ var _a;
217
+ const choices = new Map();
218
+ let first;
219
+ let usage = null;
220
+ for await (const chunk of stream) {
221
+ first ?? (first = chunk);
222
+ if (chunk.usage)
223
+ usage = chunk.usage;
224
+ for (const choice of chunk.choices ?? []) {
225
+ const index = choice.index ?? 0;
226
+ let state = choices.get(index);
227
+ if (!state)
228
+ choices.set(index, (state = { content: null, finishReason: null, toolCalls: new Map() }));
229
+ const delta = choice.delta ?? {};
230
+ if (delta.content)
231
+ state.content = (state.content ?? "") + delta.content;
232
+ for (const part of delta.tool_calls ?? []) {
233
+ const call = state.toolCalls.get(part.index ?? 0) ?? {
234
+ id: "",
235
+ type: "function",
236
+ function: { name: "", arguments: "" },
237
+ };
238
+ call.id || (call.id = part.id ?? "");
239
+ (_a = call.function).name || (_a.name = part.function?.name ?? "");
240
+ call.function.arguments += part.function?.arguments ?? "";
241
+ state.toolCalls.set(part.index ?? 0, call);
242
+ }
243
+ if (choice.finish_reason != null)
244
+ state.finishReason = choice.finish_reason;
245
+ }
246
+ }
247
+ const byIndex = (map) => [...map].sort(([a], [b]) => a - b);
248
+ const completion = {
249
+ id: first?.id ?? "",
250
+ object: "chat.completion",
251
+ created: first?.created ?? 0,
252
+ model: first?.model ?? model,
253
+ choices: byIndex(choices).map(([index, state]) => ({
254
+ index,
255
+ message: {
256
+ role: "assistant",
257
+ content: state.content,
258
+ ...(state.toolCalls.size > 0 && {
259
+ tool_calls: byIndex(state.toolCalls).map(([, call]) => call),
260
+ }),
261
+ },
262
+ finish_reason: state.finishReason,
263
+ })),
264
+ usage,
265
+ };
266
+ const { signal } = stream.controller;
267
+ if (signal.aborted)
268
+ throw signal.reason;
269
+ return completion;
270
+ }
@@ -0,0 +1,188 @@
1
+ /** One part of a message's content, such as text or an image. */
2
+ export interface ChatCompletionContentPart {
3
+ type: string;
4
+ text?: string;
5
+ [key: string]: any;
6
+ }
7
+ /** A tool call the model made, as the API returns it. */
8
+ export interface ChatCompletionMessageToolCall {
9
+ id: string;
10
+ type: "function";
11
+ function: {
12
+ name: string;
13
+ arguments: string;
14
+ };
15
+ }
16
+ /** One message of the conversation, in OpenAI's shape. */
17
+ export interface ChatCompletionMessageParam {
18
+ role: "system" | "developer" | "user" | "assistant" | "tool" | "function";
19
+ content?: string | ChatCompletionContentPart[] | null;
20
+ name?: string;
21
+ tool_calls?: (ChatCompletionMessageToolCall | {
22
+ type: string;
23
+ [key: string]: any;
24
+ })[];
25
+ tool_call_id?: string;
26
+ [key: string]: any;
27
+ }
28
+ /** A function the model may call. */
29
+ export interface ChatCompletionTool {
30
+ type: "function";
31
+ function: {
32
+ name: string;
33
+ description?: string;
34
+ parameters?: Record<string, unknown>;
35
+ strict?: boolean | null;
36
+ };
37
+ }
38
+ /**
39
+ * OpenAI's chat completion parameters plus the Moss retrieval options.
40
+ * `indexes` and `retrieve` travel as headers, the rest in the body unchanged,
41
+ * including parameters this type does not name. The body always says `stream: true`.
42
+ */
43
+ export interface ChatCompletionCreateParamsBase {
44
+ /** `moss` by default, Moss's own model. A vendor model such as `gpt-4o-mini` needs `apiKey`. */
45
+ model?: string;
46
+ messages: ChatCompletionMessageParam[];
47
+ stream?: boolean | null;
48
+ /** Moss indexes the gateway searches. Names travel in a header, so they must be Latin-1. */
49
+ indexes?: string[];
50
+ /** False skips retrieval for this call. */
51
+ retrieve?: boolean;
52
+ temperature?: number | null;
53
+ top_p?: number | null;
54
+ max_tokens?: number | null;
55
+ max_completion_tokens?: number | null;
56
+ stop?: string | string[] | null;
57
+ seed?: number | null;
58
+ tools?: (ChatCompletionTool | {
59
+ type: string;
60
+ [key: string]: any;
61
+ })[];
62
+ tool_choice?: "none" | "auto" | "required" | {
63
+ type: string;
64
+ [key: string]: any;
65
+ };
66
+ response_format?: {
67
+ type: string;
68
+ [key: string]: any;
69
+ };
70
+ stream_options?: {
71
+ include_usage?: boolean;
72
+ } | null;
73
+ user?: string;
74
+ /** Any other OpenAI parameter. */
75
+ [param: string]: any;
76
+ }
77
+ /** Parameters that return a {@link ChatCompletionStream}. */
78
+ export interface ChatCompletionCreateParamsStreaming extends ChatCompletionCreateParamsBase {
79
+ stream: true;
80
+ }
81
+ /** Parameters that return one aggregated {@link ChatCompletion}. */
82
+ export interface ChatCompletionCreateParamsNonStreaming extends ChatCompletionCreateParamsBase {
83
+ stream?: false | null;
84
+ }
85
+ /** Parameters of `chat.completions.create`. */
86
+ export type ChatCompletionCreateParams = ChatCompletionCreateParamsStreaming | ChatCompletionCreateParamsNonStreaming;
87
+ /**
88
+ * Settings of a `MossInference` client.
89
+ * Timeouts are in milliseconds, and `null` or `Infinity` removes the limit.
90
+ */
91
+ export interface MossInferenceOptions {
92
+ /**
93
+ * A path on the page's origin, such as `/moss/v1`, for a route
94
+ * on your server that forwards calls to the gateway. Each call resolves
95
+ * it against the current page, so a client built in server rendering works
96
+ * in the browser. Without `baseURL`, the client calls the Moss inference gateway.
97
+ */
98
+ baseURL?: string;
99
+ /**
100
+ * Your own OpenAI, Anthropic or Google key, for a vendor model such as `gpt-4o-mini`.
101
+ * `moss` ignores it, and a vendor model without one is refused. A call's `apiKey` wins.
102
+ */
103
+ apiKey?: string;
104
+ /** The limit for each whole call, streaming included. None by default. */
105
+ timeout?: number | null;
106
+ /** The longest wait for response headers or for more of the body. 120 000 by default. */
107
+ idleTimeout?: number | null;
108
+ /** Headers sent on every call. */
109
+ headers?: Record<string, string>;
110
+ }
111
+ /** Per-call settings that never reach the request body. */
112
+ export interface InferenceRequestOptions {
113
+ /** Replaces the client's `apiKey` for this call. An empty string is an error. */
114
+ apiKey?: string;
115
+ /** Aborts the call. */
116
+ signal?: AbortSignal;
117
+ /** Replaces the client's `timeout` for this call. */
118
+ timeout?: number | null;
119
+ /** Replaces the client's `idleTimeout` for this call. */
120
+ idleTimeout?: number | null;
121
+ /** Headers for this call, over the client's. The SDK's own headers win over both. */
122
+ headers?: Record<string, string>;
123
+ }
124
+ /** Token counts for one call. */
125
+ export interface CompletionUsage {
126
+ prompt_tokens: number;
127
+ completion_tokens: number;
128
+ total_tokens: number;
129
+ }
130
+ /** A piece of a tool call inside a streamed delta. */
131
+ export interface ChatCompletionChunkToolCall {
132
+ index: number;
133
+ id?: string;
134
+ type?: "function";
135
+ function?: {
136
+ name?: string;
137
+ arguments?: string;
138
+ };
139
+ }
140
+ /** What one chunk adds to a choice. */
141
+ export interface ChatCompletionChunkDelta {
142
+ role?: string;
143
+ content?: string | null;
144
+ tool_calls?: ChatCompletionChunkToolCall[];
145
+ }
146
+ /** One choice inside a streamed chunk. */
147
+ export interface ChatCompletionChunkChoice {
148
+ index: number;
149
+ delta: ChatCompletionChunkDelta;
150
+ finish_reason: string | null;
151
+ }
152
+ /**
153
+ * One streamed event, in OpenAI's shape.
154
+ * Each chunk is the decoded JSON event,
155
+ * so fields this type does not name are still on the object.
156
+ * The last chunk may carry `usage` with an empty `choices` list.
157
+ */
158
+ export interface ChatCompletionChunk {
159
+ id: string;
160
+ object: "chat.completion.chunk";
161
+ created: number;
162
+ model: string;
163
+ choices: ChatCompletionChunkChoice[];
164
+ usage?: CompletionUsage | null;
165
+ }
166
+ /** The reply the model built for one choice. */
167
+ export interface ChatCompletionMessage {
168
+ role: "assistant";
169
+ /** All text joined, or null when the model sent none. */
170
+ content: string | null;
171
+ /** Present only when the model called tools. */
172
+ tool_calls?: ChatCompletionMessageToolCall[];
173
+ }
174
+ /** One choice of an aggregated completion. */
175
+ export interface ChatCompletionChoice {
176
+ index: number;
177
+ message: ChatCompletionMessage;
178
+ finish_reason: string | null;
179
+ }
180
+ /** A whole reply, built from every chunk of the stream. */
181
+ export interface ChatCompletion {
182
+ id: string;
183
+ object: "chat.completion";
184
+ created: number;
185
+ model: string;
186
+ choices: ChatCompletionChoice[];
187
+ usage: CompletionUsage | null;
188
+ }
@@ -0,0 +1,3 @@
1
+ // An `any` index signature, unlike `unknown`, also accepts values whose types are interfaces.
2
+ /* eslint-disable @typescript-eslint/no-explicit-any */
3
+ export {};
package/package.json CHANGED
@@ -1,11 +1,12 @@
1
1
  {
2
2
  "name": "@moss-dev/moss-web",
3
- "version": "1.5.1",
3
+ "version": "1.6.0",
4
4
  "type": "module",
5
5
  "description": "Moss browser SDK — in-browser semantic search powered by WASM",
6
6
  "main": "dist/index.js",
7
7
  "module": "dist/index.js",
8
8
  "types": "dist/index.d.ts",
9
+ "sideEffects": false,
9
10
  "exports": {
10
11
  ".": {
11
12
  "types": "./dist/index.d.ts",
@@ -31,7 +32,7 @@
31
32
  "test": "npm run build && node --test"
32
33
  },
33
34
  "dependencies": {
34
- "@moss-dev/moss-wasm": "0.18.1",
35
+ "@moss-dev/moss-wasm": "0.18.2",
35
36
  "onnxruntime-web": "1.30.0"
36
37
  },
37
38
  "devDependencies": {