@moss-dev/moss-web 1.5.1 → 1.7.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.
@@ -0,0 +1,375 @@
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_instances, _ChatCompletionStream_chunks, _ChatCompletionStream_next, _ChatCompletionStream_join, _ChatCompletionStream_failure, _ChatCompletionStream_final, _ChatCompletionStream_drain;
13
+ import { InferenceError, codeText, 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
+ * with `errorCode` `failed_after_tool_call` once a chunk carried a `moss_tool_step`.
125
+ */
126
+ export class ChatCompletionStream {
127
+ /** @internal */
128
+ constructor(response, controller, idle, onSettled, fields, model) {
129
+ _ChatCompletionStream_instances.add(this);
130
+ _ChatCompletionStream_chunks.set(this, void 0);
131
+ _ChatCompletionStream_next.set(this, void 0);
132
+ _ChatCompletionStream_join.set(this, void 0);
133
+ /** What reading the chunks threw, which the completion throws again. */
134
+ _ChatCompletionStream_failure.set(this, void 0);
135
+ _ChatCompletionStream_final.set(this, void 0);
136
+ this.controller = controller;
137
+ this.requestId = fields.requestId;
138
+ __classPrivateFieldSet(this, _ChatCompletionStream_join, new Join(model), "f");
139
+ const generator = chunks(response, controller, idle, onSettled, fields);
140
+ __classPrivateFieldSet(this, _ChatCompletionStream_next, async () => {
141
+ try {
142
+ const result = await generator.next();
143
+ if (!result.done)
144
+ __classPrivateFieldGet(this, _ChatCompletionStream_join, "f").add(result.value);
145
+ return result;
146
+ }
147
+ catch (error) {
148
+ __classPrivateFieldSet(this, _ChatCompletionStream_failure, { error }, "f");
149
+ throw error;
150
+ }
151
+ }, "f");
152
+ __classPrivateFieldSet(this, _ChatCompletionStream_chunks, {
153
+ next: __classPrivateFieldGet(this, _ChatCompletionStream_next, "f"),
154
+ return: (value) => {
155
+ controller.abort();
156
+ onSettled();
157
+ return generator.return(value);
158
+ },
159
+ }, "f");
160
+ }
161
+ /** Iterates the chunks once. Its `return()` closes the connection, even before the first chunk. */
162
+ [(_ChatCompletionStream_chunks = new WeakMap(), _ChatCompletionStream_next = new WeakMap(), _ChatCompletionStream_join = new WeakMap(), _ChatCompletionStream_failure = new WeakMap(), _ChatCompletionStream_final = new WeakMap(), _ChatCompletionStream_instances = new WeakSet(), Symbol.asyncIterator)]() {
163
+ const iterator = __classPrivateFieldGet(this, _ChatCompletionStream_chunks, "f");
164
+ if (!iterator)
165
+ throw new Error("A ChatCompletionStream can be iterated only once.");
166
+ __classPrivateFieldSet(this, _ChatCompletionStream_chunks, undefined, "f");
167
+ return iterator;
168
+ }
169
+ /**
170
+ * The whole stream joined into one completion, as a call without `stream: true` returns.
171
+ *
172
+ * Every call returns the same completion.
173
+ * Call it after the loop ends, or instead of one.
174
+ * It reads the chunks the loop has not read, then joins them with the ones it has.
175
+ * It rejects with what the loop throws, or with the signal's reason after an abort.
176
+ */
177
+ finalChatCompletion() {
178
+ return (__classPrivateFieldSet(this, _ChatCompletionStream_final, __classPrivateFieldGet(this, _ChatCompletionStream_final, "f") ?? __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_drain).call(this), "f"));
179
+ }
180
+ }
181
+ _ChatCompletionStream_drain = async function _ChatCompletionStream_drain() {
182
+ while (!(await __classPrivateFieldGet(this, _ChatCompletionStream_next, "f").call(this)).done)
183
+ ;
184
+ if (__classPrivateFieldGet(this, _ChatCompletionStream_failure, "f"))
185
+ throw __classPrivateFieldGet(this, _ChatCompletionStream_failure, "f").error;
186
+ const { signal } = this.controller;
187
+ if (signal.aborted)
188
+ throw signal.reason;
189
+ return Object.defineProperty(__classPrivateFieldGet(this, _ChatCompletionStream_join, "f").build(), "requestId", { value: this.requestId });
190
+ };
191
+ async function* chunks(response, controller, idle, onSettled, fields) {
192
+ const notObject = "The gateway sent an event that is not a JSON object.";
193
+ let done = false;
194
+ try {
195
+ if (!response.body) {
196
+ throw new InferenceError("The response has no body.", {
197
+ type: "incomplete_stream",
198
+ ...fields,
199
+ });
200
+ }
201
+ for await (const data of sseData(response.body, idle, fields)) {
202
+ if (data === "[DONE]") {
203
+ done = true;
204
+ return;
205
+ }
206
+ let event;
207
+ try {
208
+ event = JSON.parse(data);
209
+ }
210
+ catch (cause) {
211
+ throw new InferenceError(notObject, { type: "server_error", cause, ...fields });
212
+ }
213
+ if (typeof event !== "object" || event === null || Array.isArray(event)) {
214
+ throw new InferenceError(notObject, { type: "server_error", ...fields });
215
+ }
216
+ if (event.error) {
217
+ const { message, type, code } = event.error;
218
+ throw new InferenceError(typeof message === "string" ? message : "The model failed during the stream.", {
219
+ type: typeof type === "string" ? type : "model_error",
220
+ errorCode: codeText(code),
221
+ ...fields,
222
+ });
223
+ }
224
+ if (event.moss_tool_step)
225
+ fields.errorCode = "failed_after_tool_call";
226
+ yield event;
227
+ }
228
+ throw new InferenceError("The stream ended before [DONE].", {
229
+ type: "incomplete_stream",
230
+ ...fields,
231
+ });
232
+ }
233
+ catch (error) {
234
+ if (error instanceof InferenceError)
235
+ throw error;
236
+ const { aborted, reason } = controller.signal;
237
+ if (aborted) {
238
+ if (isAbortError(reason))
239
+ return;
240
+ throw reason;
241
+ }
242
+ if (socketEnded(error)) {
243
+ throw new InferenceError("The connection closed before [DONE].", {
244
+ type: "incomplete_stream",
245
+ cause: error,
246
+ ...fields,
247
+ });
248
+ }
249
+ throw transportError(error, "The connection failed", fields);
250
+ }
251
+ finally {
252
+ if (!done)
253
+ controller.abort();
254
+ onSettled();
255
+ }
256
+ }
257
+ /** True for a JSON object, not null or an array. */
258
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
259
+ /**
260
+ * Joins chunks as they pass into one completion, as a non-streaming call returns.
261
+ *
262
+ * It joins tool call pieces as the gateway does, keeping fields beyond OpenAI's.
263
+ * A piece with no integer `index` joins the call that has its `id`, else the latest call.
264
+ * A new `id` starts the next call instead, unless the latest call has no id yet and takes it.
265
+ */
266
+ class Join {
267
+ constructor(model) {
268
+ this.model = model;
269
+ this.choices = new Map();
270
+ this.steps = [];
271
+ this.usage = null;
272
+ }
273
+ add(chunk) {
274
+ var _a;
275
+ this.first ?? (this.first = chunk);
276
+ if (chunk.usage)
277
+ this.usage = chunk.usage;
278
+ if (chunk.moss_tool_step)
279
+ this.steps.push(chunk.moss_tool_step);
280
+ for (const choice of Array.isArray(chunk.choices) ? chunk.choices : []) {
281
+ if (!isObject(choice))
282
+ continue;
283
+ const index = choice.index ?? 0;
284
+ let state = this.choices.get(index);
285
+ if (!state) {
286
+ state = {
287
+ content: null,
288
+ logprobs: null,
289
+ finishReason: null,
290
+ toolCalls: new Map(),
291
+ last: -1,
292
+ };
293
+ this.choices.set(index, state);
294
+ }
295
+ const delta = choice.delta ?? {};
296
+ if (delta.content)
297
+ state.content = (state.content ?? "") + delta.content;
298
+ if (isObject(choice.logprobs)) {
299
+ state.logprobs ?? (state.logprobs = { content: null, refusal: null });
300
+ for (const key of ["content", "refusal"]) {
301
+ const tokens = choice.logprobs[key];
302
+ if (Array.isArray(tokens))
303
+ ((_a = state.logprobs)[key] ?? (_a[key] = [])).push(...tokens);
304
+ }
305
+ }
306
+ const parts = Array.isArray(delta.tool_calls) ? delta.tool_calls : [];
307
+ for (const part of parts) {
308
+ if (!isObject(part))
309
+ continue;
310
+ let slot = part.index;
311
+ if (!Number.isInteger(slot)) {
312
+ const known = [...state.toolCalls].find(([, joined]) => part.id && joined.id === part.id);
313
+ const latest = state.toolCalls.get(state.last);
314
+ if (known)
315
+ slot = known[0];
316
+ else if (latest && !(part.id && latest.id))
317
+ slot = state.last;
318
+ else
319
+ slot = Math.max(-1, ...state.toolCalls.keys()) + 1;
320
+ }
321
+ state.last = slot;
322
+ const call = state.toolCalls.get(slot) ?? {
323
+ id: "",
324
+ type: "function",
325
+ function: { name: "", arguments: "" },
326
+ };
327
+ if (part.id)
328
+ call.id = part.id;
329
+ if (part.type)
330
+ call.type = part.type;
331
+ if (part.function?.name)
332
+ call.function.name = part.function.name;
333
+ if (typeof part.function?.arguments === "string")
334
+ call.function.arguments += part.function.arguments;
335
+ for (const [key, value] of Object.entries(part)) {
336
+ if (value == null || ["index", "id", "type", "function"].includes(key))
337
+ continue;
338
+ const merged = isObject(value) && isObject(call[key]) ? { ...call[key], ...value } : value;
339
+ Object.defineProperty(call, key, {
340
+ value: merged,
341
+ enumerable: true,
342
+ writable: true,
343
+ configurable: true,
344
+ });
345
+ }
346
+ state.toolCalls.set(slot, call);
347
+ }
348
+ if (choice.finish_reason != null)
349
+ state.finishReason = choice.finish_reason;
350
+ }
351
+ }
352
+ build() {
353
+ const byIndex = (map) => [...map].sort(([a], [b]) => a - b);
354
+ return {
355
+ id: this.first?.id ?? "",
356
+ object: "chat.completion",
357
+ created: this.first?.created ?? 0,
358
+ model: this.first?.model ?? this.model,
359
+ choices: byIndex(this.choices).map(([index, state]) => ({
360
+ index,
361
+ message: {
362
+ role: "assistant",
363
+ content: state.content ?? (state.toolCalls.size > 0 ? null : ""),
364
+ ...(state.toolCalls.size > 0 && {
365
+ tool_calls: byIndex(state.toolCalls).map(([, call]) => call),
366
+ }),
367
+ },
368
+ logprobs: state.logprobs,
369
+ finish_reason: state.finishReason,
370
+ })),
371
+ usage: this.usage,
372
+ ...(this.steps.length > 0 && { moss_tool_steps: this.steps }),
373
+ };
374
+ }
375
+ }
@@ -0,0 +1,284 @@
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
+ /**
8
+ * A tool call the model made, as the API returns it.
9
+ * Fields the model adds, such as Gemini's `extra_content`, stay on the object.
10
+ */
11
+ export interface ChatCompletionMessageToolCall {
12
+ id: string;
13
+ type: "function";
14
+ function: {
15
+ name: string;
16
+ arguments: string;
17
+ };
18
+ [key: string]: any;
19
+ }
20
+ /** One message of the conversation, in OpenAI's shape. */
21
+ export interface ChatCompletionMessageParam {
22
+ role: "system" | "developer" | "user" | "assistant" | "tool" | "function";
23
+ content?: string | ChatCompletionContentPart[] | null;
24
+ name?: string;
25
+ tool_calls?: (ChatCompletionMessageToolCall | {
26
+ type: string;
27
+ [key: string]: any;
28
+ })[];
29
+ tool_call_id?: string;
30
+ [key: string]: any;
31
+ }
32
+ /** A function the model may call. Your code runs it and sends back the result. */
33
+ export interface ChatCompletionTool {
34
+ type: "function";
35
+ function: {
36
+ name: string;
37
+ description?: string;
38
+ parameters?: Record<string, unknown>;
39
+ strict?: boolean | null;
40
+ };
41
+ }
42
+ /** An MCP server the gateway calls for the model during the turn. */
43
+ export interface McpServer {
44
+ /** Marks this `tools` entry as an MCP server. */
45
+ type: "mcp";
46
+ /** The server's label, unique in the request. */
47
+ server_label: string;
48
+ /** The server's https URL. */
49
+ server_url: string;
50
+ /**
51
+ * Headers for this server only.
52
+ * In page code every visitor can read them, `Authorization` included.
53
+ */
54
+ headers?: Record<string, string>;
55
+ /** The only tools of the server the model may call. */
56
+ allowed_tools?: string[];
57
+ /** `streamable_http` by default, or `sse` for an older server. */
58
+ transport?: "streamable_http" | "sse";
59
+ }
60
+ /**
61
+ * One MCP tool call the gateway runs, streamed once before the call (`call`)
62
+ * and once after it (`result`). Fields this type does not name stay on the object.
63
+ */
64
+ export interface ToolStep {
65
+ /** `call` before the tool runs, `result` after. */
66
+ type: "call" | "result";
67
+ /** The same on the `call` and the `result` of one tool call. */
68
+ id: string;
69
+ /** The label of the MCP server, as sent in `tools`. */
70
+ server_label: string;
71
+ /** The tool's name on its server. */
72
+ name: string;
73
+ /** The arguments as JSON text, on `call` only. */
74
+ arguments?: string;
75
+ /** True when the tool failed, on `result` only. */
76
+ is_error?: boolean;
77
+ /** How long the call took in milliseconds, on `result` only. */
78
+ duration_ms?: number;
79
+ /** The tool's result, cut when long, on `result` only. */
80
+ output?: string;
81
+ [key: string]: any;
82
+ }
83
+ /**
84
+ * OpenAI's chat completion parameters plus the Moss options.
85
+ * `indexes`, `retrieve` and `cache` travel as headers, the rest in the body
86
+ * unchanged, including parameters this type does not name. The body always says `stream: true`.
87
+ */
88
+ export interface ChatCompletionCreateParamsBase {
89
+ /** `moss` by default, Moss's own model. A vendor model such as `gpt-4o-mini` needs `apiKey`. */
90
+ model?: string;
91
+ messages: ChatCompletionMessageParam[];
92
+ stream?: boolean | null;
93
+ /**
94
+ * Moss indexes to search, every index when left out and none when empty.
95
+ * Names travel in a single header, so each must be Latin-1 text with no comma.
96
+ */
97
+ indexes?: string[];
98
+ /** False skips retrieval for this call. */
99
+ retrieve?: boolean;
100
+ /** False always asks the model instead of the gateway's reply cache. */
101
+ cache?: boolean;
102
+ temperature?: number | null;
103
+ top_p?: number | null;
104
+ max_tokens?: number | null;
105
+ max_completion_tokens?: number | null;
106
+ stop?: string | string[] | null;
107
+ seed?: number | null;
108
+ /** Functions your code runs, MCP servers the gateway calls, or any other tool object. */
109
+ tools?: (ChatCompletionTool | McpServer | {
110
+ type: string;
111
+ [key: string]: any;
112
+ })[];
113
+ /** Whether and which tool the model calls, such as `{ type: "function", function: { name } }`. */
114
+ tool_choice?: "none" | "auto" | "required" | {
115
+ type: string;
116
+ [key: string]: any;
117
+ };
118
+ /** False asks the model for at most one tool call per reply. */
119
+ parallel_tool_calls?: boolean | null;
120
+ response_format?: {
121
+ type: string;
122
+ [key: string]: any;
123
+ };
124
+ stream_options?: {
125
+ include_usage?: boolean;
126
+ } | null;
127
+ user?: string;
128
+ /** Any other OpenAI parameter. */
129
+ [param: string]: any;
130
+ }
131
+ /** Parameters that return a {@link ChatCompletionStream}. */
132
+ export interface ChatCompletionCreateParamsStreaming extends ChatCompletionCreateParamsBase {
133
+ stream: true;
134
+ }
135
+ /** Parameters that return one aggregated {@link ChatCompletion}. */
136
+ export interface ChatCompletionCreateParamsNonStreaming extends ChatCompletionCreateParamsBase {
137
+ stream?: false | null;
138
+ }
139
+ /** Parameters of `chat.completions.create`. */
140
+ export type ChatCompletionCreateParams = ChatCompletionCreateParamsStreaming | ChatCompletionCreateParamsNonStreaming;
141
+ /**
142
+ * Settings of a `MossInference` client.
143
+ * Timeouts are in milliseconds, and `null` or `Infinity` removes the limit.
144
+ */
145
+ export interface MossInferenceOptions {
146
+ /**
147
+ * A path on the page's origin, such as `/moss/v1`, for a route
148
+ * on your server that forwards calls to the gateway. Each call resolves
149
+ * it against the current page, so a client built in server rendering works
150
+ * in the browser. Without `baseURL`, the client calls the Moss inference gateway.
151
+ */
152
+ baseURL?: string;
153
+ /**
154
+ * Your own OpenAI, Anthropic or Google key, for a vendor model such as `gpt-4o-mini`.
155
+ * `moss` ignores it, and a vendor model without one is refused. A call's `apiKey` wins.
156
+ */
157
+ apiKey?: string;
158
+ /** The limit for each whole call, streaming included. None by default. */
159
+ timeout?: number | null;
160
+ /** The longest wait for response headers or for more of the body. 120 000 by default. */
161
+ idleTimeout?: number | null;
162
+ /**
163
+ * Retries before the stream starts, 2 by default and 0 for none.
164
+ * A failed connection or a 408, 409, 429 or 5xx response is retried.
165
+ */
166
+ maxRetries?: number;
167
+ /** Headers sent on every call. */
168
+ headers?: Record<string, string>;
169
+ }
170
+ /** Per-call settings that never reach the request body. */
171
+ export interface InferenceRequestOptions {
172
+ /** Replaces the client's `apiKey` for this call. An empty string is an error. */
173
+ apiKey?: string;
174
+ /** Aborts the call. */
175
+ signal?: AbortSignal;
176
+ /** Replaces the client's `timeout` for this call. */
177
+ timeout?: number | null;
178
+ /** Replaces the client's `idleTimeout` for this call. */
179
+ idleTimeout?: number | null;
180
+ /** Replaces the client's `maxRetries` for this call. */
181
+ maxRetries?: number;
182
+ /** Headers for this call, over the client's. The SDK's own headers win over both. */
183
+ headers?: Record<string, string>;
184
+ }
185
+ /** Token counts for one call, with every field the gateway sent. */
186
+ export interface CompletionUsage {
187
+ prompt_tokens: number;
188
+ completion_tokens: number;
189
+ total_tokens: number;
190
+ /** Such as `reasoning_tokens`. */
191
+ completion_tokens_details?: Record<string, any>;
192
+ /** Such as `cached_tokens`. */
193
+ prompt_tokens_details?: Record<string, any>;
194
+ [key: string]: any;
195
+ }
196
+ /** The log probability of one token, with the likeliest tokens in its place when asked for. */
197
+ export interface ChatCompletionTokenLogprob {
198
+ token: string;
199
+ logprob: number;
200
+ bytes: number[] | null;
201
+ top_logprobs: {
202
+ token: string;
203
+ logprob: number;
204
+ bytes: number[] | null;
205
+ }[];
206
+ [key: string]: any;
207
+ }
208
+ /** The log probabilities of a choice's tokens, for its text and for a refusal. */
209
+ export interface ChatCompletionLogprobs {
210
+ content: ChatCompletionTokenLogprob[] | null;
211
+ refusal: ChatCompletionTokenLogprob[] | null;
212
+ }
213
+ /** A piece of a tool call inside a streamed delta, with any fields beyond OpenAI's. */
214
+ export interface ChatCompletionChunkToolCall {
215
+ index: number;
216
+ id?: string;
217
+ type?: "function";
218
+ function?: {
219
+ name?: string;
220
+ arguments?: string;
221
+ };
222
+ [key: string]: any;
223
+ }
224
+ /** What one chunk adds to a choice. */
225
+ export interface ChatCompletionChunkDelta {
226
+ role?: string;
227
+ content?: string | null;
228
+ tool_calls?: ChatCompletionChunkToolCall[];
229
+ }
230
+ /** One choice inside a streamed chunk. */
231
+ export interface ChatCompletionChunkChoice {
232
+ index: number;
233
+ delta: ChatCompletionChunkDelta;
234
+ logprobs?: ChatCompletionLogprobs | null;
235
+ finish_reason: string | null;
236
+ }
237
+ /**
238
+ * One streamed event, in OpenAI's shape.
239
+ * Each chunk is the decoded JSON event,
240
+ * so fields this type does not name are still on the object.
241
+ * The last chunk may carry `usage` with an empty `choices` list.
242
+ */
243
+ export interface ChatCompletionChunk {
244
+ id: string;
245
+ object: "chat.completion.chunk";
246
+ created: number;
247
+ model: string;
248
+ choices: ChatCompletionChunkChoice[];
249
+ usage?: CompletionUsage | null;
250
+ /** An MCP tool call the gateway runs, on a chunk whose one choice has an empty delta. */
251
+ moss_tool_step?: ToolStep;
252
+ }
253
+ /**
254
+ * The reply the model built for one choice.
255
+ * Push it onto `messages` unchanged, then one `tool` message per tool call.
256
+ */
257
+ export interface ChatCompletionMessage {
258
+ role: "assistant";
259
+ /** All text joined. Without text, null when the model called tools and empty otherwise. */
260
+ content: string | null;
261
+ /** Present only when the model called tools. */
262
+ tool_calls?: ChatCompletionMessageToolCall[];
263
+ }
264
+ /** One choice of an aggregated completion. */
265
+ export interface ChatCompletionChoice {
266
+ index: number;
267
+ message: ChatCompletionMessage;
268
+ /** The tokens of every chunk joined in order, or null when no chunk had any. */
269
+ logprobs: ChatCompletionLogprobs | null;
270
+ finish_reason: string | null;
271
+ }
272
+ /** A whole reply, built from every chunk of the stream. */
273
+ export interface ChatCompletion {
274
+ id: string;
275
+ object: "chat.completion";
276
+ created: number;
277
+ model: string;
278
+ choices: ChatCompletionChoice[];
279
+ usage: CompletionUsage | null;
280
+ /** Every MCP tool step of the stream in order, present only when there is one. */
281
+ moss_tool_steps?: ToolStep[];
282
+ /** The `X-Moss-Request-Id` of the response. `JSON.stringify` leaves it out. */
283
+ readonly requestId?: string;
284
+ }
@@ -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.7.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": {