@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.
- package/README.md +234 -1
- package/dist/index.d.ts +6 -0
- package/dist/index.js +4 -0
- package/dist/inference/error.d.ts +61 -0
- package/dist/inference/error.js +103 -0
- package/dist/inference/index.d.ts +35 -0
- package/dist/inference/index.js +289 -0
- package/dist/inference/stream.d.ts +41 -0
- package/dist/inference/stream.js +375 -0
- package/dist/inference/types.d.ts +284 -0
- package/dist/inference/types.js +3 -0
- package/package.json +3 -2
|
@@ -0,0 +1,289 @@
|
|
|
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_maxRetries, _MossInference_apiKey, _MossInference_create;
|
|
13
|
+
import { InferenceError, errorFromResponse, responseFields, transportError, } from "./error.js";
|
|
14
|
+
import { ChatCompletionStream, 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
|
+
const DEFAULT_RETRIES = 2;
|
|
20
|
+
/** The longest delay `setTimeout` holds. */
|
|
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;
|
|
24
|
+
function invalid(message) {
|
|
25
|
+
return new InferenceError(message, { type: "invalid_request_error" });
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Printable Latin-1 with no space or tab at either end, which fetch would trim.
|
|
29
|
+
* It avoids a lookbehind, which Safari before 16.4 cannot parse.
|
|
30
|
+
*/
|
|
31
|
+
const HEADER_SAFE = /^(?:[\x21-\x7e\x80-\xff](?:[\t\x20-\x7e\x80-\xff]*[\x21-\x7e\x80-\xff])?)?$/;
|
|
32
|
+
/** Returns `value` when a header carries it unchanged. The error names `what`, never the value. */
|
|
33
|
+
function headerSafe(what, value) {
|
|
34
|
+
if (typeof value === "string" && HEADER_SAFE.test(value))
|
|
35
|
+
return value;
|
|
36
|
+
throw invalid(`${what} must be printable Latin-1 text without surrounding spaces.`);
|
|
37
|
+
}
|
|
38
|
+
function credential(what, value) {
|
|
39
|
+
if (value == null || value === "")
|
|
40
|
+
throw invalid(`${what} is missing or empty.`);
|
|
41
|
+
return headerSafe(what, value);
|
|
42
|
+
}
|
|
43
|
+
function headersOf(init) {
|
|
44
|
+
let headers;
|
|
45
|
+
try {
|
|
46
|
+
headers = new Headers(init);
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
throw invalid("The headers option holds a name or value a header cannot carry.");
|
|
50
|
+
}
|
|
51
|
+
for (const [name, value] of headers)
|
|
52
|
+
headerSafe(`The ${name} header`, value);
|
|
53
|
+
return headers;
|
|
54
|
+
}
|
|
55
|
+
/** Milliseconds for a timer, or null for no limit. */
|
|
56
|
+
function delay(what, value) {
|
|
57
|
+
if (value === null || value === Infinity)
|
|
58
|
+
return null;
|
|
59
|
+
if (typeof value === "number" && value > 0 && value < Infinity)
|
|
60
|
+
return Math.min(value, MAX_DELAY);
|
|
61
|
+
throw invalid(`${what} must be a positive number of milliseconds, or null for no limit.`);
|
|
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
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* A path with one leading slash, in printable ASCII without a space or backslash.
|
|
93
|
+
* Resolved against an http or https page, it always stays on the page's origin.
|
|
94
|
+
*/
|
|
95
|
+
const PATH = /^\/(?!\/)[\x21-\x5b\x5d-\x7e]*$/;
|
|
96
|
+
/**
|
|
97
|
+
* Returns `baseURL` when it is such a path, with no query or fragment.
|
|
98
|
+
* The errors name `baseURL` but never quote the value the caller passed.
|
|
99
|
+
*/
|
|
100
|
+
function proxyPath(baseURL) {
|
|
101
|
+
if (typeof baseURL !== "string" || !PATH.test(baseURL))
|
|
102
|
+
throw invalid("baseURL must be a path on the page's origin, such as /moss/v1.");
|
|
103
|
+
if (/[?#]/.test(baseURL))
|
|
104
|
+
throw invalid("baseURL must not hold a query or a fragment.");
|
|
105
|
+
return baseURL;
|
|
106
|
+
}
|
|
107
|
+
/** The chat completions URL under `path` on the origin of the current page. */
|
|
108
|
+
function onPage(path) {
|
|
109
|
+
let url;
|
|
110
|
+
try {
|
|
111
|
+
url = new URL(path, globalThis.location.href);
|
|
112
|
+
}
|
|
113
|
+
catch {
|
|
114
|
+
url = undefined;
|
|
115
|
+
}
|
|
116
|
+
if (!url || !["http:", "https:"].includes(url.protocol))
|
|
117
|
+
throw invalid("baseURL is a path on the page's origin, so it needs an http or https page.");
|
|
118
|
+
return `${url.origin}${url.pathname.replace(/\/+$/, "")}/chat/completions`;
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* A drop-in for OpenAI's client that answers from your Moss indexes.
|
|
122
|
+
*
|
|
123
|
+
* The constructor throws {@link InferenceError} with `invalid_request_error`
|
|
124
|
+
* when the credentials, provider key, headers, timeouts or `baseURL` are wrong.
|
|
125
|
+
* A call through a `baseURL` path rejects the same way without an http or https page.
|
|
126
|
+
* Null credentials send no `Authorization` header, for a route on your server that adds it.
|
|
127
|
+
*/
|
|
128
|
+
export class MossInference {
|
|
129
|
+
constructor(projectId, projectKey, options = {}) {
|
|
130
|
+
_MossInference_instances.add(this);
|
|
131
|
+
/** The `baseURL` path each call resolves against the page, or undefined for the gateway. */
|
|
132
|
+
_MossInference_path.set(this, void 0);
|
|
133
|
+
/** The caller's headers for every call. */
|
|
134
|
+
_MossInference_headers.set(this, void 0);
|
|
135
|
+
/** The SDK's own headers, which win over the caller's. */
|
|
136
|
+
_MossInference_own.set(this, void 0);
|
|
137
|
+
_MossInference_timeout.set(this, void 0);
|
|
138
|
+
_MossInference_idleTimeout.set(this, void 0);
|
|
139
|
+
_MossInference_maxRetries.set(this, void 0);
|
|
140
|
+
/** The provider key for calls that do not pass their own. */
|
|
141
|
+
_MossInference_apiKey.set(this, void 0);
|
|
142
|
+
__classPrivateFieldSet(this, _MossInference_own, new Headers({ "Content-Type": "application/json", Accept: "text/event-stream" }), "f");
|
|
143
|
+
if (projectId !== null || projectKey !== null) {
|
|
144
|
+
if (projectId === null || projectKey === null)
|
|
145
|
+
throw invalid("Pass both projectId and projectKey, or null for both.");
|
|
146
|
+
const id = credential("projectId", projectId);
|
|
147
|
+
const key = credential("projectKey", projectKey);
|
|
148
|
+
if (id.includes(":"))
|
|
149
|
+
throw invalid("projectId must not contain a colon.");
|
|
150
|
+
__classPrivateFieldGet(this, _MossInference_own, "f").set("Authorization", `Bearer ${id}:${key}`);
|
|
151
|
+
}
|
|
152
|
+
else if (options.baseURL == null) {
|
|
153
|
+
throw invalid("Null credentials need baseURL, the path of a route on your server that adds them.");
|
|
154
|
+
}
|
|
155
|
+
__classPrivateFieldSet(this, _MossInference_path, options.baseURL == null ? undefined : proxyPath(options.baseURL), "f");
|
|
156
|
+
__classPrivateFieldSet(this, _MossInference_timeout, delay("timeout", options.timeout ?? null), "f");
|
|
157
|
+
const { idleTimeout = DEFAULT_IDLE_TIMEOUT, maxRetries = DEFAULT_RETRIES } = options;
|
|
158
|
+
__classPrivateFieldSet(this, _MossInference_idleTimeout, delay("idleTimeout", idleTimeout), "f");
|
|
159
|
+
__classPrivateFieldSet(this, _MossInference_maxRetries, retries(maxRetries), "f");
|
|
160
|
+
__classPrivateFieldSet(this, _MossInference_headers, headersOf(options.headers), "f");
|
|
161
|
+
__classPrivateFieldSet(this, _MossInference_apiKey, options.apiKey == null ? undefined : credential("apiKey", options.apiKey), "f");
|
|
162
|
+
const create = (params, call) => __classPrivateFieldGet(this, _MossInference_instances, "m", _MossInference_create).call(this, params, call);
|
|
163
|
+
this.chat = Object.freeze({
|
|
164
|
+
completions: Object.freeze({ create: create }),
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
_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 = {}) {
|
|
169
|
+
const url = __classPrivateFieldGet(this, _MossInference_path, "f") === undefined ? `${DEFAULT_URL}/chat/completions` : onPage(__classPrivateFieldGet(this, _MossInference_path, "f"));
|
|
170
|
+
const { indexes, retrieve, cache, model = DEFAULT_MODEL, ...body } = params;
|
|
171
|
+
if (body.apiKey !== undefined || body.api_key !== undefined)
|
|
172
|
+
throw invalid("Pass the provider key as apiKey in the options of create, not in params.");
|
|
173
|
+
if (indexes !== undefined && !Array.isArray(indexes))
|
|
174
|
+
throw invalid("indexes must be an array of index names.");
|
|
175
|
+
for (const name of indexes ?? []) {
|
|
176
|
+
if (typeof name !== "string" || name === "" || name.includes(",")) {
|
|
177
|
+
throw invalid(`Invalid index name ${JSON.stringify(name)}. Names must be non-empty and contain no comma.`);
|
|
178
|
+
}
|
|
179
|
+
headerSafe(`Index name ${JSON.stringify(name)}`, name);
|
|
180
|
+
}
|
|
181
|
+
const apiKey = options.apiKey == null ? __classPrivateFieldGet(this, _MossInference_apiKey, "f") : credential("apiKey", options.apiKey);
|
|
182
|
+
const timeout = options.timeout === undefined ? __classPrivateFieldGet(this, _MossInference_timeout, "f") : delay("timeout", options.timeout);
|
|
183
|
+
const idleTimeout = options.idleTimeout === undefined
|
|
184
|
+
? __classPrivateFieldGet(this, _MossInference_idleTimeout, "f")
|
|
185
|
+
: delay("idleTimeout", options.idleTimeout);
|
|
186
|
+
const maxRetries = options.maxRetries === undefined ? __classPrivateFieldGet(this, _MossInference_maxRetries, "f") : retries(options.maxRetries);
|
|
187
|
+
const headers = new Headers(__classPrivateFieldGet(this, _MossInference_headers, "f"));
|
|
188
|
+
for (const [name, value] of headersOf(options.headers))
|
|
189
|
+
headers.set(name, value);
|
|
190
|
+
for (const [name, value] of __classPrivateFieldGet(this, _MossInference_own, "f"))
|
|
191
|
+
headers.set(name, value);
|
|
192
|
+
if (indexes?.length)
|
|
193
|
+
headers.set("X-Moss-Indexes", indexes.join(","));
|
|
194
|
+
else if (indexes)
|
|
195
|
+
headers.delete("X-Moss-Indexes");
|
|
196
|
+
if (retrieve === false || indexes?.length === 0)
|
|
197
|
+
headers.set("X-Moss-Retrieve", "off");
|
|
198
|
+
if (cache === false)
|
|
199
|
+
headers.set("X-Moss-Cache", "off");
|
|
200
|
+
if (apiKey !== undefined)
|
|
201
|
+
headers.set("X-Moss-Provider-Key", apiKey);
|
|
202
|
+
let payload;
|
|
203
|
+
try {
|
|
204
|
+
payload = JSON.stringify({ model, ...body, stream: true });
|
|
205
|
+
}
|
|
206
|
+
catch (cause) {
|
|
207
|
+
throw new InferenceError("The parameters cannot be sent as JSON.", {
|
|
208
|
+
type: "invalid_request_error",
|
|
209
|
+
cause,
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
const { signal } = options;
|
|
213
|
+
const controller = new AbortController();
|
|
214
|
+
let fields = {};
|
|
215
|
+
const expire = (message) => () => controller.abort(new InferenceError(message, { type: "timeout", ...fields }));
|
|
216
|
+
const timer = timeout === null
|
|
217
|
+
? undefined
|
|
218
|
+
: setTimeout(expire(`The request timed out after ${timeout} ms.`), timeout);
|
|
219
|
+
const deadline = timeout === null ? Infinity : Date.now() + timeout;
|
|
220
|
+
const idle = idleTimer(idleTimeout, expire(`The gateway sent nothing for ${idleTimeout} ms.`));
|
|
221
|
+
const onAbort = () => controller.abort(signal?.reason);
|
|
222
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
223
|
+
if (signal?.aborted)
|
|
224
|
+
onAbort();
|
|
225
|
+
const settle = () => {
|
|
226
|
+
clearTimeout(timer);
|
|
227
|
+
idle.clear();
|
|
228
|
+
signal?.removeEventListener("abort", onAbort);
|
|
229
|
+
};
|
|
230
|
+
let response;
|
|
231
|
+
for (let attempt = 0;; attempt++) {
|
|
232
|
+
fields = {};
|
|
233
|
+
let wait = Math.min(500 * 2 ** attempt, 8000) * (1 - Math.random() / 4);
|
|
234
|
+
try {
|
|
235
|
+
idle.arm();
|
|
236
|
+
response = await fetch(url, {
|
|
237
|
+
method: "POST",
|
|
238
|
+
headers,
|
|
239
|
+
body: payload,
|
|
240
|
+
signal: controller.signal,
|
|
241
|
+
redirect: "manual",
|
|
242
|
+
});
|
|
243
|
+
idle.clear();
|
|
244
|
+
fields = responseFields(response);
|
|
245
|
+
const after = fields.retryAfter ?? Infinity;
|
|
246
|
+
if (after <= MAX_RETRY_AFTER)
|
|
247
|
+
wait = after;
|
|
248
|
+
const last = attempt >= maxRetries || Date.now() + wait >= deadline;
|
|
249
|
+
if (response.ok || last || !retryable(response))
|
|
250
|
+
break;
|
|
251
|
+
response.body?.cancel().catch(() => { });
|
|
252
|
+
}
|
|
253
|
+
catch (error) {
|
|
254
|
+
idle.clear();
|
|
255
|
+
const code = error?.cause?.code;
|
|
256
|
+
const headersTimeout = code === "UND_ERR_HEADERS_TIMEOUT";
|
|
257
|
+
const last = attempt >= maxRetries || Date.now() + wait >= deadline;
|
|
258
|
+
if (controller.signal.aborted || headersTimeout || last) {
|
|
259
|
+
settle();
|
|
260
|
+
if (controller.signal.aborted)
|
|
261
|
+
throw controller.signal.reason;
|
|
262
|
+
const failure = transportError(error, "The inference gateway did not answer");
|
|
263
|
+
if (failure.type === "connection_error") {
|
|
264
|
+
failure.message = `${failure.message.replace(/\.$/, "")}. Check the network, and that the gateway allows this page's origin (CORS).`;
|
|
265
|
+
}
|
|
266
|
+
throw failure;
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
await pause(wait, controller.signal);
|
|
270
|
+
if (controller.signal.aborted) {
|
|
271
|
+
settle();
|
|
272
|
+
throw controller.signal.reason;
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
if (response.type === "opaqueredirect") {
|
|
276
|
+
settle();
|
|
277
|
+
const message = "The gateway answered with a redirect, which the client does not follow.";
|
|
278
|
+
throw new InferenceError(message, { type: "server_error" });
|
|
279
|
+
}
|
|
280
|
+
if (!response.ok) {
|
|
281
|
+
const text = await errorText(response, idle).catch(() => "");
|
|
282
|
+
settle();
|
|
283
|
+
if (controller.signal.aborted)
|
|
284
|
+
throw controller.signal.reason;
|
|
285
|
+
throw errorFromResponse(response, text);
|
|
286
|
+
}
|
|
287
|
+
const stream = new ChatCompletionStream(response, controller, idle, settle, fields, model);
|
|
288
|
+
return params.stream ? stream : stream.finalChatCompletion();
|
|
289
|
+
};
|
|
@@ -0,0 +1,41 @@
|
|
|
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
|
+
* with `errorCode` `failed_after_tool_call` once a chunk carried a `moss_tool_step`.
|
|
22
|
+
*/
|
|
23
|
+
export declare class ChatCompletionStream implements AsyncIterable<ChatCompletionChunk> {
|
|
24
|
+
#private;
|
|
25
|
+
/** Aborts the request. */
|
|
26
|
+
readonly controller: AbortController;
|
|
27
|
+
/** The `X-Moss-Request-Id` of the response, undefined when it has none. */
|
|
28
|
+
readonly requestId: string | undefined;
|
|
29
|
+
/** Iterates the chunks once. Its `return()` closes the connection, even before the first chunk. */
|
|
30
|
+
[Symbol.asyncIterator](): AsyncIterator<ChatCompletionChunk>;
|
|
31
|
+
/**
|
|
32
|
+
* The whole stream joined into one completion, as a call without `stream: true` returns.
|
|
33
|
+
*
|
|
34
|
+
* Every call returns the same completion.
|
|
35
|
+
* Call it after the loop ends, or instead of one.
|
|
36
|
+
* It reads the chunks the loop has not read, then joins them with the ones it has.
|
|
37
|
+
* It rejects with what the loop throws, or with the signal's reason after an abort.
|
|
38
|
+
*/
|
|
39
|
+
finalChatCompletion(): Promise<ChatCompletion>;
|
|
40
|
+
}
|
|
41
|
+
export {};
|