@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.
@@ -1,4 +1,4 @@
1
- import type { ChatCompletion, ChatCompletionChunk } from "./types.js";
1
+ import type { Response as MossResponse, ResponseStreamEvent } from "./types.js";
2
2
  /** A timer that runs only while armed, so a slow reader never trips it. */
3
3
  interface IdleTimer {
4
4
  arm(): void;
@@ -12,20 +12,32 @@ export declare function idleTimer(ms: number | null, onIdle: () => void): IdleTi
12
12
  */
13
13
  export declare function errorText(response: Response, idle: IdleTimer): Promise<string>;
14
14
  /**
15
- * The streamed reply of `chat.completions.create` with `stream: true`.
15
+ * The streamed response of `responses.create` with `stream: true`.
16
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.
17
+ * Iterate it once with `for await`. It ends after `response.completed` or `response.incomplete`.
18
+ * Leaving the loop early, or calling `controller.abort()`, ends the loop quietly,
19
+ * closes the connection and stops the model. An abort with any other reason,
20
+ * such as the `TimeoutError` of `AbortSignal.timeout()`, throws that reason.
21
+ * A failure inside the stream, such as `response.failed`, throws an {@link InferenceError}
22
+ * after the events before it, with `errorCode` `failed_after_tool_call` once an event carried an `mcp_call` item.
21
23
  */
22
- export declare class ChatCompletionStream implements AsyncIterable<ChatCompletionChunk> {
24
+ export declare class ResponseStream implements AsyncIterable<ResponseStreamEvent> {
23
25
  #private;
24
26
  /** Aborts the request. */
25
27
  readonly controller: AbortController;
26
- /** Iterates the chunks once. Its `return()` closes the connection, even before the first chunk. */
27
- [Symbol.asyncIterator](): AsyncIterator<ChatCompletionChunk>;
28
+ /** The `X-Moss-Request-Id` of the response, undefined when it has none. */
29
+ readonly requestId: string | undefined;
30
+ /** Iterates the events once. Its `return()` closes the connection, even before the first event. */
31
+ [Symbol.asyncIterator](): AsyncIterator<ResponseStreamEvent>;
32
+ /**
33
+ * The `response` of the last event, as a call without `stream: true` returns.
34
+ *
35
+ * Every call returns the same response.
36
+ * Call it after the loop ends, or instead of one.
37
+ * It reads the events the loop has not read.
38
+ * It rejects with what the loop throws, or with the signal's reason
39
+ * after an abort that came before the last event.
40
+ */
41
+ finalResponse(): Promise<MossResponse>;
28
42
  }
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
43
  export {};
@@ -9,8 +9,8 @@ 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 _ChatCompletionStream_chunks;
13
- import { InferenceError, codeText, responseFields, transportError, } from "./error.js";
12
+ var _ResponseStream_instances, _ResponseStream_events, _ResponseStream_next, _ResponseStream_failure, _ResponseStream_response, _ResponseStream_final, _ResponseStream_drain;
13
+ import { InferenceError, codeText, transportError } from "./error.js";
14
14
  /** The most UTF-16 code units in one line or in the data of one event. */
15
15
  const MAX_EVENT = 1 << 20;
16
16
  /** The most bytes of an error body read for its message. */
@@ -115,21 +115,43 @@ async function* sseData(body, idle, fields) {
115
115
  }
116
116
  }
117
117
  /**
118
- * The streamed reply of `chat.completions.create` with `stream: true`.
118
+ * The streamed response of `responses.create` with `stream: true`.
119
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.
120
+ * Iterate it once with `for await`. It ends after `response.completed` or `response.incomplete`.
121
+ * Leaving the loop early, or calling `controller.abort()`, ends the loop quietly,
122
+ * closes the connection and stops the model. An abort with any other reason,
123
+ * such as the `TimeoutError` of `AbortSignal.timeout()`, throws that reason.
124
+ * A failure inside the stream, such as `response.failed`, throws an {@link InferenceError}
125
+ * after the events before it, with `errorCode` `failed_after_tool_call` once an event carried an `mcp_call` item.
124
126
  */
125
- export class ChatCompletionStream {
127
+ export class ResponseStream {
126
128
  /** @internal */
127
- constructor(response, controller, idle, onSettled) {
128
- _ChatCompletionStream_chunks.set(this, void 0);
129
+ constructor(response, controller, idle, onSettled, fields) {
130
+ _ResponseStream_instances.add(this);
131
+ _ResponseStream_events.set(this, void 0);
132
+ _ResponseStream_next.set(this, void 0);
133
+ /** What reading the events threw, which the final response throws again. */
134
+ _ResponseStream_failure.set(this, void 0);
135
+ /** The `response` of the last event, once it came. */
136
+ _ResponseStream_response.set(this, void 0);
137
+ _ResponseStream_final.set(this, void 0);
129
138
  this.controller = controller;
130
- const generator = chunks(response, controller, idle, onSettled);
131
- __classPrivateFieldSet(this, _ChatCompletionStream_chunks, {
132
- next: () => generator.next(),
139
+ this.requestId = fields.requestId;
140
+ const generator = events(response, controller, idle, onSettled, fields);
141
+ __classPrivateFieldSet(this, _ResponseStream_next, async () => {
142
+ try {
143
+ const result = await generator.next();
144
+ if (!result.done && isLast(result.value))
145
+ __classPrivateFieldSet(this, _ResponseStream_response, result.value.response, "f");
146
+ return result;
147
+ }
148
+ catch (error) {
149
+ __classPrivateFieldSet(this, _ResponseStream_failure, { error }, "f");
150
+ throw error;
151
+ }
152
+ }, "f");
153
+ __classPrivateFieldSet(this, _ResponseStream_events, {
154
+ next: __classPrivateFieldGet(this, _ResponseStream_next, "f"),
133
155
  return: (value) => {
134
156
  controller.abort();
135
157
  onSettled();
@@ -137,18 +159,42 @@ export class ChatCompletionStream {
137
159
  },
138
160
  }, "f");
139
161
  }
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");
162
+ /** Iterates the events once. Its `return()` closes the connection, even before the first event. */
163
+ [(_ResponseStream_events = new WeakMap(), _ResponseStream_next = new WeakMap(), _ResponseStream_failure = new WeakMap(), _ResponseStream_response = new WeakMap(), _ResponseStream_final = new WeakMap(), _ResponseStream_instances = new WeakSet(), Symbol.asyncIterator)]() {
164
+ const iterator = __classPrivateFieldGet(this, _ResponseStream_events, "f");
143
165
  if (!iterator)
144
- throw new Error("A ChatCompletionStream can be iterated only once.");
145
- __classPrivateFieldSet(this, _ChatCompletionStream_chunks, undefined, "f");
166
+ throw new Error("A ResponseStream can be iterated only once.");
167
+ __classPrivateFieldSet(this, _ResponseStream_events, undefined, "f");
146
168
  return iterator;
147
169
  }
170
+ /**
171
+ * The `response` of the last event, as a call without `stream: true` returns.
172
+ *
173
+ * Every call returns the same response.
174
+ * Call it after the loop ends, or instead of one.
175
+ * It reads the events the loop has not read.
176
+ * It rejects with what the loop throws, or with the signal's reason
177
+ * after an abort that came before the last event.
178
+ */
179
+ finalResponse() {
180
+ return (__classPrivateFieldSet(this, _ResponseStream_final, __classPrivateFieldGet(this, _ResponseStream_final, "f") ?? __classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_drain).call(this), "f"));
181
+ }
148
182
  }
149
- async function* chunks(response, controller, idle, onSettled) {
183
+ _ResponseStream_drain = async function _ResponseStream_drain() {
184
+ while (!(await __classPrivateFieldGet(this, _ResponseStream_next, "f").call(this)).done)
185
+ ;
186
+ if (__classPrivateFieldGet(this, _ResponseStream_failure, "f"))
187
+ throw __classPrivateFieldGet(this, _ResponseStream_failure, "f").error;
188
+ if (__classPrivateFieldGet(this, _ResponseStream_response, "f"))
189
+ return __classPrivateFieldGet(this, _ResponseStream_response, "f");
190
+ throw this.controller.signal.reason;
191
+ };
192
+ /** True for a JSON object, not null or an array. */
193
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
194
+ /** True for the last event of a stream, which holds the whole response. */
195
+ const isLast = (event) => ["response.completed", "response.incomplete"].includes(event.type) && isObject(event.response);
196
+ async function* events(response, controller, idle, onSettled, fields) {
150
197
  const notObject = "The gateway sent an event that is not a JSON object.";
151
- const fields = responseFields(response);
152
198
  let done = false;
153
199
  try {
154
200
  if (!response.body) {
@@ -158,10 +204,8 @@ async function* chunks(response, controller, idle, onSettled) {
158
204
  });
159
205
  }
160
206
  for await (const data of sseData(response.body, idle, fields)) {
161
- if (data === "[DONE]") {
162
- done = true;
163
- return;
164
- }
207
+ if (data === "[DONE]")
208
+ break;
165
209
  let event;
166
210
  try {
167
211
  event = JSON.parse(data);
@@ -169,20 +213,37 @@ async function* chunks(response, controller, idle, onSettled) {
169
213
  catch (cause) {
170
214
  throw new InferenceError(notObject, { type: "server_error", cause, ...fields });
171
215
  }
172
- if (typeof event !== "object" || event === null || Array.isArray(event)) {
216
+ if (!isObject(event)) {
173
217
  throw new InferenceError(notObject, { type: "server_error", ...fields });
174
218
  }
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),
219
+ if (event.type === "response.failed" || event.type === "error") {
220
+ const failed = event.type === "response.failed";
221
+ const error = failed
222
+ ? (event.response?.error ?? {})
223
+ : event;
224
+ throw new InferenceError(typeof error.message === "string" ? error.message : "The model failed during the stream.", {
225
+ type: failed && typeof error.type === "string" ? error.type : "model_error",
226
+ errorCode: codeText(error.code),
180
227
  ...fields,
181
228
  });
182
229
  }
230
+ if (event.item?.type === "mcp_call")
231
+ fields.errorCode = "failed_after_tool_call";
232
+ if (isObject(event.response)) {
233
+ const output = Array.isArray(event.response.output) ? event.response.output : [];
234
+ event.response.output_text = output
235
+ .flatMap((item) => item?.type === "message" && Array.isArray(item.content) ? item.content : [])
236
+ .filter((part) => part?.type === "output_text" && typeof part.text === "string")
237
+ .map((part) => part.text)
238
+ .join("");
239
+ Object.defineProperty(event.response, "requestId", { value: fields.requestId });
240
+ }
241
+ done = isLast(event);
183
242
  yield event;
243
+ if (done)
244
+ return;
184
245
  }
185
- throw new InferenceError("The stream ended before [DONE].", {
246
+ throw new InferenceError("The stream ended before response.completed.", {
186
247
  type: "incomplete_stream",
187
248
  ...fields,
188
249
  });
@@ -197,7 +258,7 @@ async function* chunks(response, controller, idle, onSettled) {
197
258
  throw reason;
198
259
  }
199
260
  if (socketEnded(error)) {
200
- throw new InferenceError("The connection closed before [DONE].", {
261
+ throw new InferenceError("The connection closed before response.completed.", {
201
262
  type: "incomplete_stream",
202
263
  cause: error,
203
264
  ...fields,
@@ -211,60 +272,3 @@ async function* chunks(response, controller, idle, onSettled) {
211
272
  onSettled();
212
273
  }
213
274
  }
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
- }