@moss-dev/moss-web 1.6.0 → 1.8.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.6.0 resolves `@moss-dev/moss-wasm@0.18.2`. Text `query()` loads its
21
+ Version 1.8.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,
@@ -246,11 +246,11 @@ client.dispose();
246
246
 
247
247
  ## Inference
248
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`.
249
+ `MossInference` answers OpenAI's `responses.create`, with the arguments and
250
+ return shapes of OpenAI's Responses API, as in `@moss-js/moss`, through the
251
+ Moss inference gateway. The gateway searches the `indexes` you pass and adds
252
+ what it finds to the prompt, so code written for OpenAI swaps its client for
253
+ `MossInference` and adds `indexes`.
254
254
 
255
255
  A project key in page code is visible to every visitor of the page. So a page
256
256
  passes `null` for both credentials and points `baseURL` at a route on its own
@@ -261,30 +261,39 @@ import { MossInference } from "@moss-dev/moss-web";
261
261
 
262
262
  const client = new MossInference(null, null, { baseURL: "/moss/v1" });
263
263
  const answer = document.querySelector("#answer")!;
264
- const messages = [{ role: "user" as const, content: "Do you ship to Canada?" }];
265
264
 
266
- const stream = await client.chat.completions.create({
267
- messages,
265
+ const stream = await client.responses.create({
266
+ input: "Do you ship to Canada?",
268
267
  indexes: ["faq"],
269
268
  stream: true,
270
269
  });
271
270
  document.querySelector("#stop")!.addEventListener("click", () => stream.controller.abort());
272
- for await (const chunk of stream) {
273
- answer.textContent += chunk.choices[0]?.delta.content ?? "";
271
+ for await (const event of stream) {
272
+ if (event.type === "response.output_text.delta") answer.textContent += event.delta ?? "";
274
273
  }
275
274
  ```
276
275
 
277
276
  `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:
277
+ `stream: true` the call reads the whole stream and returns the `Response` of its
278
+ last event, whose `output_text` joins the text of its messages:
279
279
 
280
280
  ```typescript
281
- const completion = await client.chat.completions.create(
282
- { messages, indexes: ["faq"] },
281
+ const response = await client.responses.create(
282
+ { instructions: "Answer in one sentence.", input: "Do you ship to Canada?", indexes: ["faq"] },
283
283
  { timeout: 30_000 },
284
284
  );
285
- answer.textContent = completion.choices[0].message.content;
285
+ answer.textContent = response.output_text;
286
286
  ```
287
287
 
288
+ `input` is a string, or the conversation so far as a list of items: messages
289
+ such as `{ role: "user", content: "Hi" }`, and the `output` items of earlier
290
+ responses. Moss stores nothing, so send the whole conversation each time.
291
+ `store` is ignored, and `previous_response_id`, `background`, `include` and
292
+ OpenAI's built-in tools, such as `web_search`, are refused with
293
+ `invalid_request_error` and the `errorCode` `unsupported_parameter`. Other
294
+ OpenAI parameters, such as `temperature`, `text: { format }` for structured
295
+ output or `reasoning: { effort: "low" }`, reach the gateway unchanged.
296
+
288
297
  `baseURL` takes only a path on the page's origin, such as `/moss/v1`. An
289
298
  absolute URL, or one that starts with `//`, throws `InferenceError`. Each call
290
299
  resolves the path against the page's URL, so a module that builds the client
@@ -302,8 +311,8 @@ the client's:
302
311
  const keyed = new MossInference("your-project-id", "your-project-key", {
303
312
  apiKey: "your-openai-key",
304
313
  });
305
- const reply = await keyed.chat.completions.create(
306
- { model: "gpt-4o-mini", messages },
314
+ const reply = await keyed.responses.create(
315
+ { model: "gpt-4o-mini", input: "Hi" },
307
316
  { apiKey: "your-other-openai-key" },
308
317
  );
309
318
  ```
@@ -313,26 +322,116 @@ a page that uses [the proxy route](#the-proxy-route) leaves it to the route.
313
322
 
314
323
  The other client options are `timeout` for each whole call (no limit by
315
324
  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.
325
+ the body (120 000 ms by default, `null` for none), `maxRetries` and `headers`.
326
+ Each call takes `apiKey`, `signal`, `timeout`, `idleTimeout`, `maxRetries` and
327
+ `headers`, which replace or add to the client's for that call.
328
+
329
+ `maxRetries` (2 by default, `0` for none) sends a call again when the connection
330
+ fails, or when the gateway answers 408, 409, 429 or 5xx before the stream
331
+ starts, after a `Retry-After` of up to 60 s, else a backoff of 0.5 s doubling
332
+ up to 8 s, within `timeout`. `retrieve: false` or `indexes: []` skips the
333
+ search, and leaving `indexes` out searches every index. Moss can answer an
334
+ identical request from its reply cache; `cache: false` always asks the model.
335
+ `stream.requestId` and a response's `requestId`, which `JSON.stringify` leaves
336
+ out, hold the response's `X-Moss-Request-Id`.
337
+
338
+ A stream ends after `response.completed`, or after `response.incomplete` for a
339
+ response cut by `max_output_tokens`, whose `status` is then `incomplete`, with
340
+ the reason in `incomplete_details`. Leaving the `for await` loop early, or
341
+ calling `stream.controller.abort()`, closes the connection, stops the model and
342
+ ends the loop quietly. An abort with any other reason, such as the
343
+ `TimeoutError` of `AbortSignal.timeout()`, throws that reason. Without
344
+ `stream: true`, an abort rejects with the signal's reason, an `AbortError` for a
345
+ plain `abort()`. Every other failure throws `InferenceError` with `status` and
346
+ `type`, including a `response.failed` event, a stream that ends before its last
347
+ event (`incomplete_stream`), a broken connection (`connection_error`) and a
348
+ timeout (`timeout`). It also carries the gateway's `errorCode`, the response's
349
+ `requestId` and, for a `429` or another error that sends `Retry-After`,
350
+ `retryAfter` in milliseconds. A call straight to the gateway gets `requestId`
351
+ but no `retryAfter`, since the gateway's CORS headers do not expose
352
+ `Retry-After` to the page. [The proxy route](#the-proxy-route) passes both
353
+ headers back to the page. A browser may report a stream cut off mid-response as
354
+ a network error, which is a `connection_error`. The client does not follow
355
+ redirects: a redirect throws `InferenceError`, with no `status` in a browser,
356
+ which hides it.
357
+
358
+ ### Tool calls
359
+
360
+ `tools`, `tool_choice` and `parallel_tool_calls` take the shapes of OpenAI's
361
+ Responses API, where a function tool is flat, and your code runs each call. Each
362
+ call comes as a `function_call` item of `output`, which keeps fields beyond
363
+ OpenAI's, such as Gemini's `extra_content`, which the model needs back. After
364
+ streaming the text, `finalResponse()` gives the whole response. Push its
365
+ `output` items onto `input` as they are, add one `function_call_output` item
366
+ per call, and ask again:
367
+
368
+ ```typescript
369
+ import type { FunctionTool, ResponseInputItem } from "@moss-dev/moss-web";
370
+
371
+ const tools: FunctionTool[] = [
372
+ {
373
+ type: "function",
374
+ name: "order_status",
375
+ parameters: { type: "object", properties: { id: { type: "string" } }, required: ["id"] },
376
+ },
377
+ ];
378
+ const input: ResponseInputItem[] = [{ role: "user", content: "Where is order A1?" }];
379
+ for (;;) {
380
+ const stream = await client.responses.create({ input, tools, stream: true });
381
+ for await (const event of stream) {
382
+ if (event.type === "response.output_text.delta") answer.textContent += event.delta ?? "";
383
+ }
384
+ const { output } = await stream.finalResponse();
385
+ input.push(...output);
386
+ const calls = output.filter((item) => item.type === "function_call");
387
+ if (calls.length === 0) break;
388
+ for (const call of calls) {
389
+ const status = await orderStatus(JSON.parse(call.arguments).id);
390
+ input.push({ type: "function_call_output", call_id: call.call_id, output: status });
391
+ }
392
+ }
393
+ ```
394
+
395
+ `finalResponse()` reads what the loop has not read. If the stream was closed
396
+ before its last event, it rejects, so it never returns part of a response.
397
+
398
+ ### MCP servers
399
+
400
+ A `tools` entry of type `mcp`, typed `McpServer`, asks the gateway to call that
401
+ MCP server for the model during the response. The server's `headers` hold its
402
+ credentials, and like a project key they are visible to every visitor in page
403
+ code, so [the proxy route](#the-proxy-route) adds the entry and the page sends
404
+ none. Each call comes as an `mcp_call` item, in `response.output_item.added`
405
+ when it starts and `response.output_item.done` when it ends:
406
+
407
+ ```typescript
408
+ const stream = await client.responses.create({ input: "Where is order A1?", stream: true });
409
+ for await (const event of stream) {
410
+ if (event.type === "response.output_item.done" && event.item?.type === "mcp_call") {
411
+ console.log(event.item.name, event.item.status, event.item.duration_ms);
412
+ } else if (event.type === "response.output_text.delta") {
413
+ answer.textContent += event.delta ?? "";
414
+ }
415
+ }
416
+ ```
417
+
418
+ An `mcp_call` item has the `server_label`, `name` and `arguments` of the call,
419
+ and once it ended its `status`, `output` or `error`, and `duration_ms`. Without
420
+ `stream: true`, the same items are in the response's `output`, in order.
421
+ Sending the `output` items back in `input`, `mcp_call` items included, gives the
422
+ model the earlier tool results. A response with tools can run for a few minutes.
423
+
424
+ | `status` | `type` | `errorCode` | When |
425
+ | --- | --- | --- | --- |
426
+ | 403 | `permission_error` | `mcp_not_enabled` | MCP is switched off on the gateway |
427
+ | 429 | `capacity` | `mcp_loops_busy` | The gateway is busy; retry after `retryAfter` |
428
+ | 400, 424 | `mcp_error` | `mcp_server_error` | The URL was refused, or the server failed |
429
+ | 400 | `invalid_request_error` | (none) | A bad `tools` entry, or a label or tool name used twice |
430
+
431
+ After an `mcp_call` item every failure has `errorCode` `failed_after_tool_call`,
432
+ and the SDK never retries. Nor does it retry any stream that fails after it
433
+ started. The tool may have changed data, and so may a call you abort or time out
434
+ after such an item, so do not replay such a call blindly.
336
435
 
337
436
  ### The proxy route
338
437
 
@@ -344,15 +443,23 @@ to the gateway. In a server framework whose handlers take a `Request` and return
344
443
  a `Response`, it can look like this:
345
444
 
346
445
  ```typescript
347
- // Serves POST /moss/v1/chat/completions. Check the visitor's session first,
446
+ // Serves POST /moss/v1/responses. Check the visitor's session first,
348
447
  // since every call through this route spends your project's quota.
349
- const GATEWAY = "https://inference.moss.dev/v1/chat/completions";
448
+ import type { McpServer } from "@moss-dev/moss-web";
449
+
450
+ const GATEWAY = "https://inference.moss.dev/v1/responses";
350
451
  const INDEXES = ["faq"];
452
+ const CRM: McpServer = {
453
+ type: "mcp",
454
+ server_label: "crm",
455
+ server_url: "https://mcp.example.com/mcp",
456
+ allowed_tools: ["lookup_order"],
457
+ };
351
458
  const FORWARD = ["content-type", "accept"];
352
459
  const REPLY = ["content-type", "retry-after", "x-moss-request-id"];
353
460
 
354
461
  export async function POST(request: Request): Promise<Response> {
355
- const { MOSS_PROJECT_ID, MOSS_PROJECT_KEY } = process.env;
462
+ const { MOSS_PROJECT_ID, MOSS_PROJECT_KEY, CRM_TOKEN } = process.env;
356
463
  const indexes = request.headers.get("x-moss-indexes")?.split(",") ?? INDEXES;
357
464
  if (!indexes.every((name) => INDEXES.includes(name))) {
358
465
  return Response.json({ detail: "This page cannot search that index." }, { status: 403 });
@@ -364,10 +471,14 @@ export async function POST(request: Request): Promise<Response> {
364
471
  }
365
472
  headers.set("X-Moss-Indexes", indexes.join(","));
366
473
  headers.set("Authorization", `Bearer ${MOSS_PROJECT_ID}:${MOSS_PROJECT_KEY}`);
474
+ const body = await request.json();
475
+ const tools = Array.isArray(body.tools) ? body.tools : [];
476
+ const crm = { ...CRM, headers: { Authorization: `Bearer ${CRM_TOKEN}` } };
477
+ body.tools = [...tools.filter((tool) => tool?.type !== "mcp"), crm];
367
478
  const reply = await fetch(GATEWAY, {
368
479
  method: "POST",
369
480
  headers,
370
- body: await request.text(),
481
+ body: JSON.stringify(body),
371
482
  signal: request.signal,
372
483
  redirect: "manual",
373
484
  });
@@ -381,9 +492,11 @@ since every visitor can set them. Back to the page it passes `Content-Type`,
381
492
  `Retry-After` and `X-Moss-Request-Id`, so an `InferenceError` there carries
382
493
  `retryAfter` and `requestId`. The route refuses an index that is not in its
383
494
  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.
495
+ every index in the project. So `retrieve`, `indexes: []`, `cache` and `apiKey`
496
+ in page code do not reach the gateway, and a route that wants them sets those
497
+ headers itself, such as `X-Moss-Provider-Key` for your own provider key. The
498
+ route also drops any MCP entry the page sends and adds its own server, so the
499
+ page never holds MCP credentials.
387
500
 
388
501
  Passing the project id and key instead of `null`, without `baseURL`, sends them
389
502
  from the page straight to the gateway, which suits prototypes and internal tools.
package/dist/index.d.ts CHANGED
@@ -2,9 +2,9 @@ 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
4
  export { MossInference } from "./inference/index.js";
5
- export type { ChatCompletions } from "./inference/index.js";
6
- export { ChatCompletionStream } from "./inference/stream.js";
5
+ export type { Responses } from "./inference/index.js";
6
+ export { ResponseStream } from "./inference/stream.js";
7
7
  export { InferenceError } from "./inference/error.js";
8
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";
9
+ export type { EasyInputMessage, FunctionCallOutput, FunctionTool, InferenceRequestOptions, McpCall, McpServer, MossInferenceOptions, Response, ResponseCreateParams, ResponseCreateParamsBase, ResponseCreateParamsNonStreaming, ResponseCreateParamsStreaming, ResponseFunctionToolCall, ResponseInputItem, ResponseOutputItem, ResponseReasoningItem, ResponseOutputMessage, ResponseOutputText, ResponseStreamEvent, ResponseUsage, } from "./inference/types.js";
10
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,6 +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
3
+ // Responses through the Moss inference gateway, in the shape of OpenAI's Responses API
4
4
  export { MossInference } from "./inference/index.js";
5
- export { ChatCompletionStream } from "./inference/stream.js";
5
+ export { ResponseStream } from "./inference/stream.js";
6
6
  export { InferenceError } from "./inference/error.js";
@@ -1,5 +1,5 @@
1
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 & {});
2
+ export type InferenceErrorType = "authentication_error" | "permission_error" | "not_found_error" | "invalid_request_error" | "rate_limit_error" | "capacity" | "mcp_error" | "model_error" | "server_error" | "connection_error" | "timeout" | "incomplete_stream" | (string & {});
3
3
  /**
4
4
  * The error every inference call throws, before or during the stream.
5
5
  * Arguments the SDK rejects before sending carry `invalid_request_error` and no status.
@@ -10,7 +10,14 @@ export declare class InferenceError extends Error {
10
10
  readonly status: number | undefined;
11
11
  /** The gateway's `error.type`, or one derived from the status or the failure. */
12
12
  readonly type: InferenceErrorType;
13
- /** The gateway's `error.code`, a string or a safe integer in decimal. Undefined otherwise. */
13
+ /**
14
+ * The gateway's `error.code`, a string or a safe integer in decimal. Undefined otherwise.
15
+ *
16
+ * `failed_after_tool_call` once the stream carried an `mcp_call` item.
17
+ * The tool may have changed data, so do not replay the call blindly.
18
+ * The same holds for a call you abort after such an item, which has no such code,
19
+ * as with `stream.controller.abort()` or a signal such as `AbortSignal.timeout()`.
20
+ */
14
21
  readonly errorCode?: string;
15
22
  /** The `X-Moss-Request-Id` of the response. Undefined when the call failed before one arrived. */
16
23
  readonly requestId?: string;
@@ -28,10 +35,12 @@ export declare class InferenceError extends Error {
28
35
  cause?: unknown;
29
36
  });
30
37
  }
31
- /** What an {@link InferenceError} takes from the response headers. */
38
+ /** What every {@link InferenceError} of a call takes from its response. */
32
39
  export interface ResponseFields {
33
40
  requestId?: string;
34
41
  retryAfter?: number;
42
+ /** Set once the stream carries an `mcp_call` item. */
43
+ errorCode?: "failed_after_tool_call";
35
44
  }
36
45
  /**
37
46
  * The request id of any response, and for an error response
@@ -1,18 +1,18 @@
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 {
1
+ import { ResponseStream } from "./stream.js";
2
+ import type { InferenceRequestOptions, MossInferenceOptions, Response as MossResponse, ResponseCreateParams, ResponseCreateParamsNonStreaming, ResponseCreateParamsStreaming } from "./types.js";
3
+ /** The `responses` namespace of a {@link MossInference} client, shaped like OpenAI's. */
4
+ export interface Responses {
5
5
  /**
6
- * Sends a chat completion through the Moss inference gateway.
6
+ * Creates a response through the Moss inference gateway.
7
7
  *
8
8
  * The gateway searches `indexes` and adds what it finds to the prompt.
9
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.
10
+ * resolves to a {@link ResponseStream} once the gateway accepts the request,
11
+ * and otherwise to the `Response` of the stream's last event.
12
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>;
13
+ create(params: ResponseCreateParamsStreaming, options?: InferenceRequestOptions): Promise<ResponseStream>;
14
+ create(params: ResponseCreateParamsNonStreaming, options?: InferenceRequestOptions): Promise<MossResponse>;
15
+ create(params: ResponseCreateParams, options?: InferenceRequestOptions): Promise<ResponseStream | MossResponse>;
16
16
  }
17
17
  /**
18
18
  * A drop-in for OpenAI's client that answers from your Moss indexes.
@@ -24,10 +24,8 @@ export interface ChatCompletions {
24
24
  */
25
25
  export declare class MossInference {
26
26
  #private;
27
- /** OpenAI's `chat.completions`, answered by the Moss inference gateway. */
28
- readonly chat: {
29
- readonly completions: ChatCompletions;
30
- };
27
+ /** OpenAI's `responses`, answered by the Moss inference gateway. */
28
+ readonly responses: Responses;
31
29
  constructor(projectId: string, projectKey: string, options?: MossInferenceOptions);
32
30
  constructor(projectId: null, projectKey: null, options: MossInferenceOptions & {
33
31
  baseURL: string;
@@ -9,15 +9,18 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
9
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
10
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
11
  };
12
- var _MossInference_instances, _MossInference_path, _MossInference_headers, _MossInference_own, _MossInference_timeout, _MossInference_idleTimeout, _MossInference_apiKey, _MossInference_create;
12
+ var _MossInference_instances, _MossInference_path, _MossInference_headers, _MossInference_own, _MossInference_timeout, _MossInference_idleTimeout, _MossInference_maxRetries, _MossInference_apiKey, _MossInference_create;
13
13
  import { InferenceError, errorFromResponse, responseFields, transportError, } from "./error.js";
14
- import { ChatCompletionStream, aggregate, errorText, idleTimer } from "./stream.js";
14
+ import { ResponseStream, errorText, idleTimer } from "./stream.js";
15
15
  /** The production gateway, up to and including `/v1`. */
16
16
  const DEFAULT_URL = "https://inference.moss.dev/v1";
17
17
  const DEFAULT_MODEL = "moss";
18
18
  const DEFAULT_IDLE_TIMEOUT = 120000;
19
+ const DEFAULT_RETRIES = 2;
19
20
  /** The longest delay `setTimeout` holds. */
20
21
  const MAX_DELAY = 2 ** 31 - 1;
22
+ /** The longest `Retry-After` a retry waits, in milliseconds. A longer one waits the backoff. */
23
+ const MAX_RETRY_AFTER = 60000;
21
24
  function invalid(message) {
22
25
  return new InferenceError(message, { type: "invalid_request_error" });
23
26
  }
@@ -57,6 +60,34 @@ function delay(what, value) {
57
60
  return Math.min(value, MAX_DELAY);
58
61
  throw invalid(`${what} must be a positive number of milliseconds, or null for no limit.`);
59
62
  }
63
+ /** A retry count, a whole number of 0 or more. */
64
+ function retries(value) {
65
+ if (typeof value === "number" && Number.isSafeInteger(value) && value >= 0)
66
+ return value;
67
+ throw invalid("maxRetries must be a whole number of 0 or more.");
68
+ }
69
+ /**
70
+ * True when a failed response may be sent again.
71
+ * Its `x-should-retry` decides when present, else a 408, 409, 429 or 5xx does.
72
+ */
73
+ function retryable(response) {
74
+ const header = response.headers.get("x-should-retry");
75
+ if (header === "true" || header === "false")
76
+ return header === "true";
77
+ return [408, 409, 429].includes(response.status) || response.status >= 500;
78
+ }
79
+ /** Resolves after `ms`, or at once when `signal` aborts. */
80
+ function pause(ms, signal) {
81
+ return new Promise((resolve) => {
82
+ const done = () => {
83
+ clearTimeout(timer);
84
+ signal.removeEventListener("abort", done);
85
+ resolve();
86
+ };
87
+ const timer = setTimeout(done, ms);
88
+ signal.addEventListener("abort", done, { once: true });
89
+ });
90
+ }
60
91
  /**
61
92
  * A path with one leading slash, in printable ASCII without a space or backslash.
62
93
  * Resolved against an http or https page, it always stays on the page's origin.
@@ -73,7 +104,7 @@ function proxyPath(baseURL) {
73
104
  throw invalid("baseURL must not hold a query or a fragment.");
74
105
  return baseURL;
75
106
  }
76
- /** The chat completions URL under `path` on the origin of the current page. */
107
+ /** The Responses URL under `path` on the origin of the current page. */
77
108
  function onPage(path) {
78
109
  let url;
79
110
  try {
@@ -84,7 +115,7 @@ function onPage(path) {
84
115
  }
85
116
  if (!url || !["http:", "https:"].includes(url.protocol))
86
117
  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`;
118
+ return `${url.origin}${url.pathname.replace(/\/+$/, "")}/responses`;
88
119
  }
89
120
  /**
90
121
  * A drop-in for OpenAI's client that answers from your Moss indexes.
@@ -105,6 +136,7 @@ export class MossInference {
105
136
  _MossInference_own.set(this, void 0);
106
137
  _MossInference_timeout.set(this, void 0);
107
138
  _MossInference_idleTimeout.set(this, void 0);
139
+ _MossInference_maxRetries.set(this, void 0);
108
140
  /** The provider key for calls that do not pass their own. */
109
141
  _MossInference_apiKey.set(this, void 0);
110
142
  __classPrivateFieldSet(this, _MossInference_own, new Headers({ "Content-Type": "application/json", Accept: "text/event-stream" }), "f");
@@ -122,19 +154,18 @@ export class MossInference {
122
154
  }
123
155
  __classPrivateFieldSet(this, _MossInference_path, options.baseURL == null ? undefined : proxyPath(options.baseURL), "f");
124
156
  __classPrivateFieldSet(this, _MossInference_timeout, delay("timeout", options.timeout ?? null), "f");
125
- const { idleTimeout = DEFAULT_IDLE_TIMEOUT } = options;
157
+ const { idleTimeout = DEFAULT_IDLE_TIMEOUT, maxRetries = DEFAULT_RETRIES } = options;
126
158
  __classPrivateFieldSet(this, _MossInference_idleTimeout, delay("idleTimeout", idleTimeout), "f");
159
+ __classPrivateFieldSet(this, _MossInference_maxRetries, retries(maxRetries), "f");
127
160
  __classPrivateFieldSet(this, _MossInference_headers, headersOf(options.headers), "f");
128
161
  __classPrivateFieldSet(this, _MossInference_apiKey, options.apiKey == null ? undefined : credential("apiKey", options.apiKey), "f");
129
162
  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
- });
163
+ this.responses = Object.freeze({ create: create });
133
164
  }
134
165
  }
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;
166
+ _MossInference_path = new WeakMap(), _MossInference_headers = new WeakMap(), _MossInference_own = new WeakMap(), _MossInference_timeout = new WeakMap(), _MossInference_idleTimeout = new WeakMap(), _MossInference_maxRetries = new WeakMap(), _MossInference_apiKey = new WeakMap(), _MossInference_instances = new WeakSet(), _MossInference_create = async function _MossInference_create(params, options = {}) {
167
+ const url = __classPrivateFieldGet(this, _MossInference_path, "f") === undefined ? `${DEFAULT_URL}/responses` : onPage(__classPrivateFieldGet(this, _MossInference_path, "f"));
168
+ const { indexes, retrieve, cache, model = DEFAULT_MODEL, ...body } = params;
138
169
  if (body.apiKey !== undefined || body.api_key !== undefined)
139
170
  throw invalid("Pass the provider key as apiKey in the options of create, not in params.");
140
171
  if (indexes !== undefined && !Array.isArray(indexes))
@@ -150,6 +181,7 @@ _MossInference_path = new WeakMap(), _MossInference_headers = new WeakMap(), _Mo
150
181
  const idleTimeout = options.idleTimeout === undefined
151
182
  ? __classPrivateFieldGet(this, _MossInference_idleTimeout, "f")
152
183
  : delay("idleTimeout", options.idleTimeout);
184
+ const maxRetries = options.maxRetries === undefined ? __classPrivateFieldGet(this, _MossInference_maxRetries, "f") : retries(options.maxRetries);
153
185
  const headers = new Headers(__classPrivateFieldGet(this, _MossInference_headers, "f"));
154
186
  for (const [name, value] of headersOf(options.headers))
155
187
  headers.set(name, value);
@@ -157,8 +189,12 @@ _MossInference_path = new WeakMap(), _MossInference_headers = new WeakMap(), _Mo
157
189
  headers.set(name, value);
158
190
  if (indexes?.length)
159
191
  headers.set("X-Moss-Indexes", indexes.join(","));
160
- if (retrieve === false)
192
+ else if (indexes)
193
+ headers.delete("X-Moss-Indexes");
194
+ if (retrieve === false || indexes?.length === 0)
161
195
  headers.set("X-Moss-Retrieve", "off");
196
+ if (cache === false)
197
+ headers.set("X-Moss-Cache", "off");
162
198
  if (apiKey !== undefined)
163
199
  headers.set("X-Moss-Provider-Key", apiKey);
164
200
  let payload;
@@ -166,7 +202,7 @@ _MossInference_path = new WeakMap(), _MossInference_headers = new WeakMap(), _Mo
166
202
  payload = JSON.stringify({ model, ...body, stream: true });
167
203
  }
168
204
  catch (cause) {
169
- throw new InferenceError(`The parameters cannot be sent as JSON: ${String(cause)}`, {
205
+ throw new InferenceError("The parameters cannot be sent as JSON.", {
170
206
  type: "invalid_request_error",
171
207
  cause,
172
208
  });
@@ -178,6 +214,7 @@ _MossInference_path = new WeakMap(), _MossInference_headers = new WeakMap(), _Mo
178
214
  const timer = timeout === null
179
215
  ? undefined
180
216
  : setTimeout(expire(`The request timed out after ${timeout} ms.`), timeout);
217
+ const deadline = timeout === null ? Infinity : Date.now() + timeout;
181
218
  const idle = idleTimer(idleTimeout, expire(`The gateway sent nothing for ${idleTimeout} ms.`));
182
219
  const onAbort = () => controller.abort(signal?.reason);
183
220
  signal?.addEventListener("abort", onAbort, { once: true });
@@ -189,28 +226,50 @@ _MossInference_path = new WeakMap(), _MossInference_headers = new WeakMap(), _Mo
189
226
  signal?.removeEventListener("abort", onAbort);
190
227
  };
191
228
  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)
229
+ for (let attempt = 0;; attempt++) {
230
+ fields = {};
231
+ let wait = Math.min(500 * 2 ** attempt, 8000) * (1 - Math.random() / 4);
232
+ try {
233
+ idle.arm();
234
+ response = await fetch(url, {
235
+ method: "POST",
236
+ headers,
237
+ body: payload,
238
+ signal: controller.signal,
239
+ redirect: "manual",
240
+ });
241
+ idle.clear();
242
+ fields = responseFields(response);
243
+ const after = fields.retryAfter ?? Infinity;
244
+ if (after <= MAX_RETRY_AFTER)
245
+ wait = after;
246
+ const last = attempt >= maxRetries || Date.now() + wait >= deadline;
247
+ if (response.ok || last || !retryable(response))
248
+ break;
249
+ response.body?.cancel().catch(() => { });
250
+ }
251
+ catch (error) {
252
+ idle.clear();
253
+ const code = error?.cause?.code;
254
+ const headersTimeout = code === "UND_ERR_HEADERS_TIMEOUT";
255
+ const last = attempt >= maxRetries || Date.now() + wait >= deadline;
256
+ if (controller.signal.aborted || headersTimeout || last) {
257
+ settle();
258
+ if (controller.signal.aborted)
259
+ throw controller.signal.reason;
260
+ const failure = transportError(error, "The inference gateway did not answer");
261
+ if (failure.type === "connection_error") {
262
+ failure.message = `${failure.message.replace(/\.$/, "")}. Check the network, and that the gateway allows this page's origin (CORS).`;
263
+ }
264
+ throw failure;
265
+ }
266
+ }
267
+ await pause(wait, controller.signal);
268
+ if (controller.signal.aborted) {
269
+ settle();
205
270
  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
271
  }
210
- throw failure;
211
272
  }
212
- idle.clear();
213
- fields = responseFields(response);
214
273
  if (response.type === "opaqueredirect") {
215
274
  settle();
216
275
  const message = "The gateway answered with a redirect, which the client does not follow.";
@@ -223,6 +282,6 @@ _MossInference_path = new WeakMap(), _MossInference_headers = new WeakMap(), _Mo
223
282
  throw controller.signal.reason;
224
283
  throw errorFromResponse(response, text);
225
284
  }
226
- const stream = new ChatCompletionStream(response, controller, idle, settle);
227
- return params.stream ? stream : aggregate(stream, model);
285
+ const stream = new ResponseStream(response, controller, idle, settle, fields);
286
+ return params.stream ? stream : stream.finalResponse();
228
287
  };