@moss-dev/moss-web 1.8.0 → 1.10.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 +111 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/inference/error.d.ts +5 -0
- package/dist/inference/index.d.ts +66 -1
- package/dist/inference/index.js +222 -43
- package/dist/inference/stream.d.ts +4 -2
- package/dist/inference/stream.js +19 -12
- package/dist/inference/types.d.ts +152 -1
- package/package.json +1 -1
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.
|
|
21
|
+
Version 1.10.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,
|
|
@@ -433,6 +433,116 @@ and the SDK never retries. Nor does it retry any stream that fails after it
|
|
|
433
433
|
started. The tool may have changed data, and so may a call you abort or time out
|
|
434
434
|
after such an item, so do not replay such a call blindly.
|
|
435
435
|
|
|
436
|
+
### Browser tasks
|
|
437
|
+
|
|
438
|
+
`client.tasks` gives an agent a goal to reach in a browser that runs on Moss,
|
|
439
|
+
within time and dollar limits. `run` creates the task and resolves once it is
|
|
440
|
+
`completed`, `failed` or `cancelled`:
|
|
441
|
+
|
|
442
|
+
```typescript
|
|
443
|
+
interface Flight {
|
|
444
|
+
airline: string;
|
|
445
|
+
price: number;
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
const done = await client.tasks.run<Flight>(
|
|
449
|
+
{
|
|
450
|
+
goal: "Find the cheapest nonstop flight from SFO to JFK next Friday.",
|
|
451
|
+
environment: { type: "browser", start_url: "https://www.google.com/travel/flights" },
|
|
452
|
+
output_schema: {
|
|
453
|
+
type: "object",
|
|
454
|
+
properties: { airline: { type: "string" }, price: { type: "number" } },
|
|
455
|
+
required: ["airline", "price"],
|
|
456
|
+
},
|
|
457
|
+
limits: { max_runtime_seconds: 360, max_cost_usd: 0.25 },
|
|
458
|
+
},
|
|
459
|
+
{ timeout: 600_000 },
|
|
460
|
+
);
|
|
461
|
+
if (done.status === "completed") {
|
|
462
|
+
answer.textContent = `${done.result?.output?.airline}: $${done.result?.output?.price}`;
|
|
463
|
+
} else {
|
|
464
|
+
answer.textContent = `${done.status}: ${done.error?.message ?? ""}`;
|
|
465
|
+
}
|
|
466
|
+
```
|
|
467
|
+
|
|
468
|
+
A task runs for minutes. To keep its id first, `create` returns the `queued`
|
|
469
|
+
task at once, and `wait` polls it until it ends:
|
|
470
|
+
|
|
471
|
+
```typescript
|
|
472
|
+
const task = await client.tasks.create({
|
|
473
|
+
goal: "Find the library's opening hours.",
|
|
474
|
+
environment: { type: "browser" },
|
|
475
|
+
});
|
|
476
|
+
const finished = await client.tasks.wait(task.id);
|
|
477
|
+
```
|
|
478
|
+
|
|
479
|
+
Only the fields you pass are sent. The gateway picks the `model`, `effort` and
|
|
480
|
+
limits you leave out, and refuses a field it does not know. `model` is a name of
|
|
481
|
+
the Moss catalog, sent as is. With `output_schema` the gateway checks the
|
|
482
|
+
answer, and `verification.passed` is false, with `problems`, when it does not
|
|
483
|
+
match. `result` comes back either way. The type argument types
|
|
484
|
+
`result.output`, and the SDK does not check it. `usage` holds the model calls,
|
|
485
|
+
tokens and `cost_usd`, plus any other field the gateway sends, such as
|
|
486
|
+
`browser_minutes`.
|
|
487
|
+
|
|
488
|
+
`run` and `wait` resolve on a `failed` task too, so read `status` and `error`.
|
|
489
|
+
Their `timeout` limits the wait and is off by default. Past it, they throw a
|
|
490
|
+
`timeout` InferenceError and the task goes on, so wait again or cancel it. They
|
|
491
|
+
poll every `pollInterval`, 2000 ms by default. `signal` aborts them. Once the
|
|
492
|
+
task exists, every InferenceError they throw names it in `taskId`. `cancel`
|
|
493
|
+
stops a queued task at once. A running task comes back with
|
|
494
|
+
`cancel_requested: true` and ends `cancelled` soon after.
|
|
495
|
+
|
|
496
|
+
`trace` resolves to the agent's step-by-step record once `trace_available` is
|
|
497
|
+
true, and rejects with `not_found_error` before. `files.list` lists the
|
|
498
|
+
screenshots and output files once the task ends, and `files.content` resolves to
|
|
499
|
+
a file's bytes and `contentType`. The gateway removes the trace and files 7 days
|
|
500
|
+
after the task ends, at its `files_expire_at`. The SDK never opens or renders a
|
|
501
|
+
file. An `img` shows a screenshot safely. A blob URL of an HTML or SVG file,
|
|
502
|
+
though, opened in a tab or a frame, runs its scripts on your page's origin, so
|
|
503
|
+
offer other files as a download:
|
|
504
|
+
|
|
505
|
+
```typescript
|
|
506
|
+
for (const file of (await client.tasks.files.list(done.id)).data) {
|
|
507
|
+
if (!file.path.startsWith("screenshots/")) continue;
|
|
508
|
+
const { data, contentType } = await client.tasks.files.content(done.id, file.path);
|
|
509
|
+
const image = document.createElement("img");
|
|
510
|
+
image.src = URL.createObjectURL(new Blob([data], { type: contentType }));
|
|
511
|
+
image.alt = file.path;
|
|
512
|
+
document.querySelector("#screenshots")!.append(image);
|
|
513
|
+
}
|
|
514
|
+
```
|
|
515
|
+
|
|
516
|
+
Each call takes the options of `responses.create`, and retries as it does, but
|
|
517
|
+
never after a 409. `create` and `run` also take `apiKey`, and send only that
|
|
518
|
+
call's key as `X-Moss-Provider-Key`, for the task's model calls; see the pricing
|
|
519
|
+
docs. Tasks never use the client's `apiKey`, and the other calls never send a key. Each
|
|
520
|
+
create sends an `Idempotency-Key`, a new one per call or yours in its `headers`,
|
|
521
|
+
and the same one on every retry. The gateway answers a repeated key with the
|
|
522
|
+
same body, within 24 hours, with the task it created, so a retried create never
|
|
523
|
+
starts a second task. To retry a create yourself, pass your own key. Task calls
|
|
524
|
+
never send an `Idempotency-Key` from the client's `headers`.
|
|
525
|
+
|
|
526
|
+
With `baseURL`, task calls go to `/tasks` under that path, such as
|
|
527
|
+
`/moss/v1/tasks/{id}/files/{path}`. A route that serves them forwards `GET` and
|
|
528
|
+
`POST` under it with the `Accept`, `Content-Type` and `Idempotency-Key`
|
|
529
|
+
headers, and passes back the headers of [the proxy route](#the-proxy-route). A
|
|
530
|
+
task belongs to the project, not to the visitor, so the route also checks that
|
|
531
|
+
the visitor started the task they read or cancel.
|
|
532
|
+
|
|
533
|
+
| `status` | `type` | `errorCode` | When |
|
|
534
|
+
| --- | --- | --- | --- |
|
|
535
|
+
| 400 | `invalid_request_error` | `invalid_request_error` | A field or value the gateway refuses |
|
|
536
|
+
| 400 | `invalid_request_error` | `model_not_found` | A model the gateway does not serve |
|
|
537
|
+
| 403 | `permission_error` | `tasks_not_enabled` | Tasks are not enabled for the project |
|
|
538
|
+
| 404 | `not_found_error` | `not_found_error` | No such task in the project, no trace yet, or no such file |
|
|
539
|
+
| 409 | `invalid_request_error` | `task_not_finished` | The files of a task that is still queued or running |
|
|
540
|
+
| 410 | `invalid_request_error` | `files_expired` | The trace or files after the task's `files_expire_at` |
|
|
541
|
+
| 422 | `invalid_request_error` | `idempotency_key_reused` | An `Idempotency-Key` sent again with another body |
|
|
542
|
+
| 429 | `rate_limit_error` | `too_many_queued_tasks` | Too many queued tasks; retry after `retryAfter` |
|
|
543
|
+
| 503 | `server_error` | `server_error` | Tasks are not enabled on the gateway |
|
|
544
|
+
| 503 | `server_error` | `tasks_unavailable` | The gateway cannot take a task now; a create retries after `Retry-After` |
|
|
545
|
+
|
|
436
546
|
### The proxy route
|
|
437
547
|
|
|
438
548
|
With `null` credentials the client sends no `Authorization` header, and an
|
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 { Responses } from "./inference/index.js";
|
|
5
|
+
export type { Responses, TaskFiles, Tasks } from "./inference/index.js";
|
|
6
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 { EasyInputMessage, FunctionCallOutput, FunctionTool, InferenceRequestOptions, McpCall, McpServer, MossInferenceOptions, Response, ResponseCreateParams, ResponseCreateParamsBase, ResponseCreateParamsNonStreaming, ResponseCreateParamsStreaming, ResponseFunctionToolCall, ResponseInputItem, ResponseOutputItem, ResponseReasoningItem, ResponseOutputMessage, ResponseOutputText, ResponseStreamEvent, ResponseUsage, } 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, Task, TaskCreateOptions, TaskCreateParams, TaskEnvironment, TaskError, TaskFile, TaskFileContent, TaskFileList, TaskLimits, TaskRequestOptions, TaskResult, TaskRunOptions, TaskStatus, TaskUsage, TaskVerification, TaskWaitOptions, } 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
|
-
// Responses through the Moss inference gateway, in the shape of OpenAI's
|
|
3
|
+
// Responses and browser tasks through the Moss inference gateway, in the shape of OpenAI's APIs
|
|
4
4
|
export { MossInference } from "./inference/index.js";
|
|
5
5
|
export { ResponseStream } from "./inference/stream.js";
|
|
6
6
|
export { InferenceError } from "./inference/error.js";
|
|
@@ -26,6 +26,11 @@ export declare class InferenceError extends Error {
|
|
|
26
26
|
* A direct gateway call gets none, since the gateway's CORS headers do not expose `Retry-After`.
|
|
27
27
|
*/
|
|
28
28
|
readonly retryAfter?: number;
|
|
29
|
+
/**
|
|
30
|
+
* The task of a failed `tasks.wait`, or of a `tasks.run` that failed after its create,
|
|
31
|
+
* so you can still wait on, cancel or read it. Undefined for any other call.
|
|
32
|
+
*/
|
|
33
|
+
readonly taskId?: string;
|
|
29
34
|
constructor(message: string, init: {
|
|
30
35
|
type: InferenceErrorType;
|
|
31
36
|
status?: number;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { ResponseStream } from "./stream.js";
|
|
2
|
-
import type { InferenceRequestOptions, MossInferenceOptions, Response as MossResponse, ResponseCreateParams, ResponseCreateParamsNonStreaming, ResponseCreateParamsStreaming } from "./types.js";
|
|
2
|
+
import type { InferenceRequestOptions, MossInferenceOptions, Response as MossResponse, ResponseCreateParams, ResponseCreateParamsNonStreaming, ResponseCreateParamsStreaming, Task, TaskCreateOptions, TaskCreateParams, TaskFileContent, TaskFileList, TaskRequestOptions, TaskRunOptions, TaskWaitOptions } from "./types.js";
|
|
3
3
|
/** The `responses` namespace of a {@link MossInference} client, shaped like OpenAI's. */
|
|
4
4
|
export interface Responses {
|
|
5
5
|
/**
|
|
@@ -14,6 +14,69 @@ export interface Responses {
|
|
|
14
14
|
create(params: ResponseCreateParamsNonStreaming, options?: InferenceRequestOptions): Promise<MossResponse>;
|
|
15
15
|
create(params: ResponseCreateParams, options?: InferenceRequestOptions): Promise<ResponseStream | MossResponse>;
|
|
16
16
|
}
|
|
17
|
+
/**
|
|
18
|
+
* The files of a task, under `tasks.files`, ready once the task ends.
|
|
19
|
+
* While it is queued or running they reject with a 409 `task_not_finished`, never retried.
|
|
20
|
+
* The gateway removes them 7 days after the task ends, at its `files_expire_at`,
|
|
21
|
+
* and from then on they reject with a 410 `files_expired`.
|
|
22
|
+
*/
|
|
23
|
+
export interface TaskFiles {
|
|
24
|
+
/** Lists the screenshots and output files of a task. */
|
|
25
|
+
list(taskId: string, options?: TaskRequestOptions): Promise<TaskFileList>;
|
|
26
|
+
/**
|
|
27
|
+
* Downloads one file, by a `path` that `list` gave, such as `screenshots/step-1.png`.
|
|
28
|
+
* It resolves to the bytes and the media type, and never opens or renders the file.
|
|
29
|
+
*/
|
|
30
|
+
content(taskId: string, path: string, options?: TaskRequestOptions): Promise<TaskFileContent>;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* The `tasks` namespace of a {@link MossInference} client: an agent works toward
|
|
34
|
+
* a goal in a browser on Moss, within time and dollar limits, and you poll for the result.
|
|
35
|
+
* `Output` types `result.output`, which `output_schema` describes. The SDK does not check it.
|
|
36
|
+
* Failures reject with {@link InferenceError}.
|
|
37
|
+
*/
|
|
38
|
+
export interface Tasks {
|
|
39
|
+
/**
|
|
40
|
+
* Queues a task and resolves to it, `queued`.
|
|
41
|
+
*
|
|
42
|
+
* Each create sends an `Idempotency-Key`, a new one per call or the one in its `headers`,
|
|
43
|
+
* and the same one on every retry. The gateway answers a repeated key with the same body,
|
|
44
|
+
* within 24 hours, with the task it created, so a retried create never starts a second task.
|
|
45
|
+
* To retry a create yourself, pass your own key.
|
|
46
|
+
* Only the call's own `apiKey` goes as `X-Moss-Provider-Key`, for the task's model calls; see
|
|
47
|
+
* the pricing docs. The client's `apiKey` is never used, and no other task call sends a key.
|
|
48
|
+
*/
|
|
49
|
+
create<Output = unknown>(params: TaskCreateParams, options?: TaskCreateOptions): Promise<Task<Output>>;
|
|
50
|
+
/** Fetches a task by its id. */
|
|
51
|
+
retrieve<Output = unknown>(taskId: string, options?: TaskRequestOptions): Promise<Task<Output>>;
|
|
52
|
+
/**
|
|
53
|
+
* Stops a task. A queued task comes back `cancelled`.
|
|
54
|
+
* A running one comes back with `cancel_requested` and ends `cancelled` soon after.
|
|
55
|
+
*/
|
|
56
|
+
cancel<Output = unknown>(taskId: string, options?: TaskRequestOptions): Promise<Task<Output>>;
|
|
57
|
+
/**
|
|
58
|
+
* Polls a task every `pollInterval` until it is neither `queued` nor `running`, and resolves to it.
|
|
59
|
+
* A `failed` task resolves too, so read its `status` and `error`.
|
|
60
|
+
* Past `timeout` it rejects with a `timeout` InferenceError, and the task goes on.
|
|
61
|
+
* Every InferenceError it rejects with names the task in `taskId`.
|
|
62
|
+
*/
|
|
63
|
+
wait<Output = unknown>(taskId: string, options?: TaskWaitOptions): Promise<Task<Output>>;
|
|
64
|
+
/**
|
|
65
|
+
* Creates a task and waits for it, as `create` and then `wait` do.
|
|
66
|
+
* `timeout` and `pollInterval` apply to the wait, `apiKey` to the create, and the other options
|
|
67
|
+
* to every request.
|
|
68
|
+
* Once the task exists, every InferenceError it rejects with names the task in `taskId`.
|
|
69
|
+
*/
|
|
70
|
+
run<Output = unknown>(params: TaskCreateParams, options?: TaskRunOptions): Promise<Task<Output>>;
|
|
71
|
+
/**
|
|
72
|
+
* The agent's step-by-step record, as the gateway sent it.
|
|
73
|
+
* It rejects with `not_found_error` until `trace_available` is true.
|
|
74
|
+
* The gateway removes it 7 days after the task ends, at `files_expire_at`,
|
|
75
|
+
* and from then on it rejects with a 410 `files_expired`.
|
|
76
|
+
*/
|
|
77
|
+
trace(taskId: string, options?: TaskRequestOptions): Promise<unknown>;
|
|
78
|
+
readonly files: TaskFiles;
|
|
79
|
+
}
|
|
17
80
|
/**
|
|
18
81
|
* A drop-in for OpenAI's client that answers from your Moss indexes.
|
|
19
82
|
*
|
|
@@ -26,6 +89,8 @@ export declare class MossInference {
|
|
|
26
89
|
#private;
|
|
27
90
|
/** OpenAI's `responses`, answered by the Moss inference gateway. */
|
|
28
91
|
readonly responses: Responses;
|
|
92
|
+
/** Browser tasks with time and dollar limits, run by the Moss inference gateway. */
|
|
93
|
+
readonly tasks: Tasks;
|
|
29
94
|
constructor(projectId: string, projectKey: string, options?: MossInferenceOptions);
|
|
30
95
|
constructor(projectId: null, projectKey: null, options: MossInferenceOptions & {
|
|
31
96
|
baseURL: string;
|
package/dist/inference/index.js
CHANGED
|
@@ -9,9 +9,9 @@ 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,
|
|
12
|
+
var _MossInference_instances, _MossInference_path, _MossInference_headers, _MossInference_authorization, _MossInference_timeout, _MossInference_idleTimeout, _MossInference_maxRetries, _MossInference_apiKey, _MossInference_base, _MossInference_settings, _MossInference_merge, _MossInference_task, _MossInference_create, _MossInference_send;
|
|
13
13
|
import { InferenceError, errorFromResponse, responseFields, transportError, } from "./error.js";
|
|
14
|
-
import { ResponseStream, errorText, idleTimer } from "./stream.js";
|
|
14
|
+
import { ResponseStream, errorText, idleTimer, readBody } 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";
|
|
@@ -21,9 +21,39 @@ const DEFAULT_RETRIES = 2;
|
|
|
21
21
|
const MAX_DELAY = 2 ** 31 - 1;
|
|
22
22
|
/** The longest `Retry-After` a retry waits, in milliseconds. A longer one waits the backoff. */
|
|
23
23
|
const MAX_RETRY_AFTER = 60000;
|
|
24
|
+
/** The milliseconds between the polls of `tasks.wait`. */
|
|
25
|
+
const DEFAULT_POLL = 2000;
|
|
26
|
+
/** The 4xx statuses a `responses` call goes again after, as it does after a 5xx. */
|
|
27
|
+
const RESPONSE_RETRY = [408, 409, 429];
|
|
28
|
+
/** The 4xx statuses a task call goes again after. A 409 says the task has not finished. */
|
|
29
|
+
const TASK_RETRY = [408, 429];
|
|
24
30
|
function invalid(message) {
|
|
25
31
|
return new InferenceError(message, { type: "invalid_request_error" });
|
|
26
32
|
}
|
|
33
|
+
/** `value` as JSON text, or an `invalid_request_error` when it has no JSON form, as with `NaN`. */
|
|
34
|
+
function json(value) {
|
|
35
|
+
try {
|
|
36
|
+
return JSON.stringify(value, (_key, item) => {
|
|
37
|
+
if (typeof item === "number" && !Number.isFinite(item))
|
|
38
|
+
throw new TypeError("A number in the parameters is not finite.");
|
|
39
|
+
return item;
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
catch (cause) {
|
|
43
|
+
throw new InferenceError("The parameters cannot be sent as JSON.", {
|
|
44
|
+
type: "invalid_request_error",
|
|
45
|
+
cause,
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
/** A random version 4 UUID, which `crypto.randomUUID` gives only on https pages and localhost. */
|
|
50
|
+
function uuid() {
|
|
51
|
+
const bytes = crypto.getRandomValues(new Uint8Array(16));
|
|
52
|
+
bytes[6] = (bytes[6] & 0x0f) | 0x40;
|
|
53
|
+
bytes[8] = (bytes[8] & 0x3f) | 0x80;
|
|
54
|
+
const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
55
|
+
return hex.replace(/^(.{8})(.{4})(.{4})(.{4})/, "$1-$2-$3-$4-");
|
|
56
|
+
}
|
|
27
57
|
/**
|
|
28
58
|
* Printable Latin-1 with no space or tab at either end, which fetch would trim.
|
|
29
59
|
* It avoids a lookbehind, which Safari before 16.4 cannot parse.
|
|
@@ -68,13 +98,13 @@ function retries(value) {
|
|
|
68
98
|
}
|
|
69
99
|
/**
|
|
70
100
|
* True when a failed response may be sent again.
|
|
71
|
-
* Its `x-should-retry` decides when present, else a
|
|
101
|
+
* Its `x-should-retry` decides when present, else a 5xx or a status in `statuses` does.
|
|
72
102
|
*/
|
|
73
|
-
function retryable(response) {
|
|
103
|
+
function retryable(response, statuses) {
|
|
74
104
|
const header = response.headers.get("x-should-retry");
|
|
75
105
|
if (header === "true" || header === "false")
|
|
76
106
|
return header === "true";
|
|
77
|
-
return
|
|
107
|
+
return statuses.includes(response.status) || response.status >= 500;
|
|
78
108
|
}
|
|
79
109
|
/** Resolves after `ms`, or at once when `signal` aborts. */
|
|
80
110
|
function pause(ms, signal) {
|
|
@@ -104,7 +134,7 @@ function proxyPath(baseURL) {
|
|
|
104
134
|
throw invalid("baseURL must not hold a query or a fragment.");
|
|
105
135
|
return baseURL;
|
|
106
136
|
}
|
|
107
|
-
/** The
|
|
137
|
+
/** The URL of `path` on the origin of the current page, without a trailing slash. */
|
|
108
138
|
function onPage(path) {
|
|
109
139
|
let url;
|
|
110
140
|
try {
|
|
@@ -115,7 +145,102 @@ function onPage(path) {
|
|
|
115
145
|
}
|
|
116
146
|
if (!url || !["http:", "https:"].includes(url.protocol))
|
|
117
147
|
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(/\/+$/, "")}
|
|
148
|
+
return `${url.origin}${url.pathname.replace(/\/+$/, "")}`;
|
|
149
|
+
}
|
|
150
|
+
/** The URL path of a task, after its id is checked and encoded. */
|
|
151
|
+
function taskPath(taskId) {
|
|
152
|
+
if (typeof taskId !== "string" || taskId === "" || taskId === "." || taskId === "..")
|
|
153
|
+
throw invalid("taskId must be a task id, such as task_...");
|
|
154
|
+
return `/tasks/${encodeURIComponent(taskId)}`;
|
|
155
|
+
}
|
|
156
|
+
/** The URL path of a task's file, each part encoded. Empty, `.` and `..` parts are an error. */
|
|
157
|
+
function filePath(path) {
|
|
158
|
+
const parts = typeof path === "string" ? path.split("/") : [""];
|
|
159
|
+
if (parts.some((part) => part === "" || part === "." || part === ".."))
|
|
160
|
+
throw invalid("path must be a path that files.list gave, such as screenshots/step-1.png.");
|
|
161
|
+
return parts.map(encodeURIComponent).join("/");
|
|
162
|
+
}
|
|
163
|
+
/** The JSON of a reply, which must be an object when `object` is true. */
|
|
164
|
+
function decode(reply, object = true) {
|
|
165
|
+
let value;
|
|
166
|
+
try {
|
|
167
|
+
value = JSON.parse(new TextDecoder().decode(reply.data));
|
|
168
|
+
}
|
|
169
|
+
catch {
|
|
170
|
+
value = undefined;
|
|
171
|
+
}
|
|
172
|
+
const isObject = typeof value === "object" && value !== null && !Array.isArray(value);
|
|
173
|
+
if (value === undefined || (object && !isObject)) {
|
|
174
|
+
throw new InferenceError("The gateway sent a reply that is not a JSON object.", {
|
|
175
|
+
type: "server_error",
|
|
176
|
+
...reply.fields,
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
return value;
|
|
180
|
+
}
|
|
181
|
+
/** The wait limit, poll interval and per-request options of `wait` and `run`, checked. */
|
|
182
|
+
function waiting(options) {
|
|
183
|
+
const { timeout = null, pollInterval = DEFAULT_POLL, ...call } = options;
|
|
184
|
+
const limit = delay("timeout", timeout);
|
|
185
|
+
if (typeof pollInterval !== "number" || !(pollInterval > 0 && pollInterval < Infinity))
|
|
186
|
+
throw invalid("pollInterval must be a positive number of milliseconds.");
|
|
187
|
+
return { limit, pollInterval: Math.min(pollInterval, MAX_DELAY), call };
|
|
188
|
+
}
|
|
189
|
+
/** The `tasks` namespace over `send`, which makes one Tasks API request. */
|
|
190
|
+
function tasksOf(send) {
|
|
191
|
+
const task = async (call, options) => decode(await send(call, options));
|
|
192
|
+
const retrieve = async (taskId, options) => task({ method: "GET", path: taskPath(taskId) }, options);
|
|
193
|
+
const create = async (params, options) => task({ method: "POST", path: "/tasks", body: params }, options);
|
|
194
|
+
/** Polls a task until it ends, and names the task in each InferenceError. */
|
|
195
|
+
const poll = async (taskId, settings) => {
|
|
196
|
+
const path = taskPath(taskId);
|
|
197
|
+
const { limit, pollInterval, call } = settings;
|
|
198
|
+
const deadline = limit === null ? Infinity : Date.now() + limit;
|
|
199
|
+
const signal = call.signal ?? new AbortController().signal;
|
|
200
|
+
const late = (status, cause) => new InferenceError(`Task ${taskId} is still ${status} after ${limit} ms. It goes on: wait again or cancel it.`, { type: "timeout", cause });
|
|
201
|
+
let status = "unfinished";
|
|
202
|
+
try {
|
|
203
|
+
for (;;) {
|
|
204
|
+
const within = limit === null ? undefined : deadline - Date.now();
|
|
205
|
+
const found = await task({ method: "GET", path, within }, call).catch((error) => {
|
|
206
|
+
const expired = error instanceof InferenceError && error.type === "timeout";
|
|
207
|
+
throw expired && Date.now() >= deadline ? late(status, error) : error;
|
|
208
|
+
});
|
|
209
|
+
if (found.status !== "queued" && found.status !== "running")
|
|
210
|
+
return found;
|
|
211
|
+
status = found.status;
|
|
212
|
+
const left = deadline - Date.now();
|
|
213
|
+
if (left <= 0)
|
|
214
|
+
throw late(status);
|
|
215
|
+
await pause(Math.min(pollInterval, left), signal);
|
|
216
|
+
if (signal.aborted)
|
|
217
|
+
throw signal.reason;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
catch (error) {
|
|
221
|
+
throw error instanceof InferenceError ? Object.assign(error, { taskId }) : error;
|
|
222
|
+
}
|
|
223
|
+
};
|
|
224
|
+
return Object.freeze({
|
|
225
|
+
create,
|
|
226
|
+
retrieve,
|
|
227
|
+
cancel: async (taskId, options) => task({ method: "POST", path: `${taskPath(taskId)}/cancel` }, options),
|
|
228
|
+
wait: async (taskId, options = {}) => poll(taskId, waiting(options)),
|
|
229
|
+
run: async (params, { apiKey, ...options } = {}) => {
|
|
230
|
+
const settings = waiting(options);
|
|
231
|
+
const { id } = await create(params, { ...settings.call, apiKey });
|
|
232
|
+
return poll(id, settings);
|
|
233
|
+
},
|
|
234
|
+
trace: async (taskId, options) => decode(await send({ method: "GET", path: `${taskPath(taskId)}/trace` }, options), false),
|
|
235
|
+
files: Object.freeze({
|
|
236
|
+
list: async (taskId, options) => decode(await send({ method: "GET", path: `${taskPath(taskId)}/files` }, options)),
|
|
237
|
+
content: async (taskId, path, options) => {
|
|
238
|
+
const where = `${taskPath(taskId)}/files/${filePath(path)}`;
|
|
239
|
+
const { data, contentType } = await send({ method: "GET", path: where, accept: "*/*" }, options);
|
|
240
|
+
return { data, contentType };
|
|
241
|
+
},
|
|
242
|
+
}),
|
|
243
|
+
});
|
|
119
244
|
}
|
|
120
245
|
/**
|
|
121
246
|
* A drop-in for OpenAI's client that answers from your Moss indexes.
|
|
@@ -132,14 +257,13 @@ export class MossInference {
|
|
|
132
257
|
_MossInference_path.set(this, void 0);
|
|
133
258
|
/** The caller's headers for every call. */
|
|
134
259
|
_MossInference_headers.set(this, void 0);
|
|
135
|
-
/** The
|
|
136
|
-
|
|
260
|
+
/** The `Authorization` of every call, which wins over the caller's. None for null credentials. */
|
|
261
|
+
_MossInference_authorization.set(this, void 0);
|
|
137
262
|
_MossInference_timeout.set(this, void 0);
|
|
138
263
|
_MossInference_idleTimeout.set(this, void 0);
|
|
139
264
|
_MossInference_maxRetries.set(this, void 0);
|
|
140
|
-
/** The provider key for calls that do not pass their own. */
|
|
265
|
+
/** The provider key for `responses` calls that do not pass their own. Tasks never use it. */
|
|
141
266
|
_MossInference_apiKey.set(this, void 0);
|
|
142
|
-
__classPrivateFieldSet(this, _MossInference_own, new Headers({ "Content-Type": "application/json", Accept: "text/event-stream" }), "f");
|
|
143
267
|
if (projectId !== null || projectKey !== null) {
|
|
144
268
|
if (projectId === null || projectKey === null)
|
|
145
269
|
throw invalid("Pass both projectId and projectKey, or null for both.");
|
|
@@ -147,7 +271,7 @@ export class MossInference {
|
|
|
147
271
|
const key = credential("projectKey", projectKey);
|
|
148
272
|
if (id.includes(":"))
|
|
149
273
|
throw invalid("projectId must not contain a colon.");
|
|
150
|
-
|
|
274
|
+
__classPrivateFieldSet(this, _MossInference_authorization, `Bearer ${id}:${key}`, "f");
|
|
151
275
|
}
|
|
152
276
|
else if (options.baseURL == null) {
|
|
153
277
|
throw invalid("Null credentials need baseURL, the path of a route on your server that adds them.");
|
|
@@ -161,10 +285,71 @@ export class MossInference {
|
|
|
161
285
|
__classPrivateFieldSet(this, _MossInference_apiKey, options.apiKey == null ? undefined : credential("apiKey", options.apiKey), "f");
|
|
162
286
|
const create = (params, call) => __classPrivateFieldGet(this, _MossInference_instances, "m", _MossInference_create).call(this, params, call);
|
|
163
287
|
this.responses = Object.freeze({ create: create });
|
|
288
|
+
this.tasks = tasksOf((call, options) => __classPrivateFieldGet(this, _MossInference_instances, "m", _MossInference_task).call(this, call, options));
|
|
164
289
|
}
|
|
165
290
|
}
|
|
166
|
-
_MossInference_path = new WeakMap(), _MossInference_headers = new WeakMap(),
|
|
167
|
-
|
|
291
|
+
_MossInference_path = new WeakMap(), _MossInference_headers = new WeakMap(), _MossInference_authorization = new WeakMap(), _MossInference_timeout = new WeakMap(), _MossInference_idleTimeout = new WeakMap(), _MossInference_maxRetries = new WeakMap(), _MossInference_apiKey = new WeakMap(), _MossInference_instances = new WeakSet(), _MossInference_base = function _MossInference_base() {
|
|
292
|
+
return __classPrivateFieldGet(this, _MossInference_path, "f") === undefined ? DEFAULT_URL : onPage(__classPrivateFieldGet(this, _MossInference_path, "f"));
|
|
293
|
+
}, _MossInference_settings = function _MossInference_settings(options) {
|
|
294
|
+
return {
|
|
295
|
+
timeout: options.timeout === undefined ? __classPrivateFieldGet(this, _MossInference_timeout, "f") : delay("timeout", options.timeout),
|
|
296
|
+
idleTimeout: options.idleTimeout === undefined
|
|
297
|
+
? __classPrivateFieldGet(this, _MossInference_idleTimeout, "f")
|
|
298
|
+
: delay("idleTimeout", options.idleTimeout),
|
|
299
|
+
maxRetries: options.maxRetries === undefined ? __classPrivateFieldGet(this, _MossInference_maxRetries, "f") : retries(options.maxRetries),
|
|
300
|
+
signal: options.signal,
|
|
301
|
+
};
|
|
302
|
+
}, _MossInference_merge = function _MossInference_merge(call, own, skip) {
|
|
303
|
+
const headers = new Headers(__classPrivateFieldGet(this, _MossInference_headers, "f"));
|
|
304
|
+
if (skip !== undefined)
|
|
305
|
+
headers.delete(skip);
|
|
306
|
+
for (const [name, value] of headersOf(call))
|
|
307
|
+
headers.set(name, value);
|
|
308
|
+
for (const [name, value] of Object.entries(own))
|
|
309
|
+
headers.set(name, value);
|
|
310
|
+
if (__classPrivateFieldGet(this, _MossInference_authorization, "f") !== undefined)
|
|
311
|
+
headers.set("Authorization", __classPrivateFieldGet(this, _MossInference_authorization, "f"));
|
|
312
|
+
return headers;
|
|
313
|
+
}, _MossInference_task = async function _MossInference_task(call, options = {}) {
|
|
314
|
+
const url = __classPrivateFieldGet(this, _MossInference_instances, "m", _MossInference_base).call(this) + call.path;
|
|
315
|
+
const settings = __classPrivateFieldGet(this, _MossInference_instances, "m", _MossInference_settings).call(this, options);
|
|
316
|
+
if (call.within !== undefined)
|
|
317
|
+
settings.timeout = Math.max(Math.min(settings.timeout ?? MAX_DELAY, call.within), 1);
|
|
318
|
+
const own = {
|
|
319
|
+
Accept: call.accept ?? "application/json",
|
|
320
|
+
};
|
|
321
|
+
if (call.body) {
|
|
322
|
+
if ("apiKey" in call.body || "api_key" in call.body)
|
|
323
|
+
throw invalid("Pass the provider key as apiKey in the options of create, not in params.");
|
|
324
|
+
own["Content-Type"] = "application/json";
|
|
325
|
+
if (options.apiKey != null)
|
|
326
|
+
own["X-Moss-Provider-Key"] = credential("apiKey", options.apiKey);
|
|
327
|
+
}
|
|
328
|
+
const headers = __classPrivateFieldGet(this, _MossInference_instances, "m", _MossInference_merge).call(this, options.headers, own, "Idempotency-Key");
|
|
329
|
+
if (call.body && !headers.has("Idempotency-Key"))
|
|
330
|
+
headers.set("Idempotency-Key", uuid());
|
|
331
|
+
const init = {
|
|
332
|
+
method: call.method,
|
|
333
|
+
headers,
|
|
334
|
+
body: call.body && json(call.body),
|
|
335
|
+
};
|
|
336
|
+
const sent = await __classPrivateFieldGet(this, _MossInference_instances, "m", _MossInference_send).call(this, url, init, settings, TASK_RETRY);
|
|
337
|
+
const { response, controller, idle, settle, fields } = sent;
|
|
338
|
+
try {
|
|
339
|
+
const data = await readBody(response, idle);
|
|
340
|
+
const contentType = response.headers.get("Content-Type") ?? "application/octet-stream";
|
|
341
|
+
return { data, contentType, fields };
|
|
342
|
+
}
|
|
343
|
+
catch (error) {
|
|
344
|
+
if (controller.signal.aborted)
|
|
345
|
+
throw controller.signal.reason;
|
|
346
|
+
throw transportError(error, "The gateway's reply broke off", fields);
|
|
347
|
+
}
|
|
348
|
+
finally {
|
|
349
|
+
settle();
|
|
350
|
+
}
|
|
351
|
+
}, _MossInference_create = async function _MossInference_create(params, options = {}) {
|
|
352
|
+
const url = `${__classPrivateFieldGet(this, _MossInference_instances, "m", _MossInference_base).call(this)}/responses`;
|
|
168
353
|
const { indexes, retrieve, cache, model = DEFAULT_MODEL, ...body } = params;
|
|
169
354
|
if (body.apiKey !== undefined || body.api_key !== undefined)
|
|
170
355
|
throw invalid("Pass the provider key as apiKey in the options of create, not in params.");
|
|
@@ -177,16 +362,11 @@ _MossInference_path = new WeakMap(), _MossInference_headers = new WeakMap(), _Mo
|
|
|
177
362
|
headerSafe(`Index name ${JSON.stringify(name)}`, name);
|
|
178
363
|
}
|
|
179
364
|
const apiKey = options.apiKey == null ? __classPrivateFieldGet(this, _MossInference_apiKey, "f") : credential("apiKey", options.apiKey);
|
|
180
|
-
const
|
|
181
|
-
const
|
|
182
|
-
|
|
183
|
-
:
|
|
184
|
-
|
|
185
|
-
const headers = new Headers(__classPrivateFieldGet(this, _MossInference_headers, "f"));
|
|
186
|
-
for (const [name, value] of headersOf(options.headers))
|
|
187
|
-
headers.set(name, value);
|
|
188
|
-
for (const [name, value] of __classPrivateFieldGet(this, _MossInference_own, "f"))
|
|
189
|
-
headers.set(name, value);
|
|
365
|
+
const settings = __classPrivateFieldGet(this, _MossInference_instances, "m", _MossInference_settings).call(this, options);
|
|
366
|
+
const headers = __classPrivateFieldGet(this, _MossInference_instances, "m", _MossInference_merge).call(this, options.headers, {
|
|
367
|
+
"Content-Type": "application/json",
|
|
368
|
+
Accept: "text/event-stream",
|
|
369
|
+
});
|
|
190
370
|
if (indexes?.length)
|
|
191
371
|
headers.set("X-Moss-Indexes", indexes.join(","));
|
|
192
372
|
else if (indexes)
|
|
@@ -197,17 +377,19 @@ _MossInference_path = new WeakMap(), _MossInference_headers = new WeakMap(), _Mo
|
|
|
197
377
|
headers.set("X-Moss-Cache", "off");
|
|
198
378
|
if (apiKey !== undefined)
|
|
199
379
|
headers.set("X-Moss-Provider-Key", apiKey);
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
380
|
+
const payload = json({ model, ...body, stream: true });
|
|
381
|
+
const init = { method: "POST", headers, body: payload };
|
|
382
|
+
const sent = await __classPrivateFieldGet(this, _MossInference_instances, "m", _MossInference_send).call(this, url, init, settings, RESPONSE_RETRY);
|
|
383
|
+
const { response, controller, idle, settle, fields } = sent;
|
|
384
|
+
const stream = new ResponseStream(response, controller, idle, settle, fields);
|
|
385
|
+
return params.stream ? stream : stream.finalResponse();
|
|
386
|
+
}, _MossInference_send =
|
|
387
|
+
/**
|
|
388
|
+
* Sends a request and resolves to its OK response, with the call's timers still set.
|
|
389
|
+
* A failure before the response goes again within `maxRetries` and `timeout`:
|
|
390
|
+
* a failed connection, a 5xx, or a status in `statuses`.
|
|
391
|
+
*/
|
|
392
|
+
async function _MossInference_send(url, init, { timeout, idleTimeout, maxRetries, signal }, statuses) {
|
|
211
393
|
const controller = new AbortController();
|
|
212
394
|
let fields = {};
|
|
213
395
|
const expire = (message) => () => controller.abort(new InferenceError(message, { type: "timeout", ...fields }));
|
|
@@ -232,9 +414,7 @@ _MossInference_path = new WeakMap(), _MossInference_headers = new WeakMap(), _Mo
|
|
|
232
414
|
try {
|
|
233
415
|
idle.arm();
|
|
234
416
|
response = await fetch(url, {
|
|
235
|
-
|
|
236
|
-
headers,
|
|
237
|
-
body: payload,
|
|
417
|
+
...init,
|
|
238
418
|
signal: controller.signal,
|
|
239
419
|
redirect: "manual",
|
|
240
420
|
});
|
|
@@ -244,16 +424,16 @@ _MossInference_path = new WeakMap(), _MossInference_headers = new WeakMap(), _Mo
|
|
|
244
424
|
if (after <= MAX_RETRY_AFTER)
|
|
245
425
|
wait = after;
|
|
246
426
|
const last = attempt >= maxRetries || Date.now() + wait >= deadline;
|
|
247
|
-
if (response.ok || last || !retryable(response))
|
|
427
|
+
if (response.ok || last || !retryable(response, statuses))
|
|
248
428
|
break;
|
|
249
429
|
response.body?.cancel().catch(() => { });
|
|
250
430
|
}
|
|
251
431
|
catch (error) {
|
|
252
432
|
idle.clear();
|
|
253
433
|
const code = error?.cause?.code;
|
|
254
|
-
const
|
|
434
|
+
const again = code !== "UND_ERR_HEADERS_TIMEOUT";
|
|
255
435
|
const last = attempt >= maxRetries || Date.now() + wait >= deadline;
|
|
256
|
-
if (controller.signal.aborted ||
|
|
436
|
+
if (controller.signal.aborted || !again || last) {
|
|
257
437
|
settle();
|
|
258
438
|
if (controller.signal.aborted)
|
|
259
439
|
throw controller.signal.reason;
|
|
@@ -282,6 +462,5 @@ _MossInference_path = new WeakMap(), _MossInference_headers = new WeakMap(), _Mo
|
|
|
282
462
|
throw controller.signal.reason;
|
|
283
463
|
throw errorFromResponse(response, text);
|
|
284
464
|
}
|
|
285
|
-
|
|
286
|
-
return params.stream ? stream : stream.finalResponse();
|
|
465
|
+
return { response, controller, idle, settle, fields };
|
|
287
466
|
};
|
|
@@ -7,9 +7,11 @@ interface IdleTimer {
|
|
|
7
7
|
/** Calls `onIdle` when an armed timer runs `ms` milliseconds. Null `ms` never fires. */
|
|
8
8
|
export declare function idleTimer(ms: number | null, onIdle: () => void): IdleTimer;
|
|
9
9
|
/**
|
|
10
|
-
* Reads
|
|
11
|
-
* It stops
|
|
10
|
+
* Reads a body, arming `idle` while each read waits.
|
|
11
|
+
* It stops once `max` bytes are in and cancels the rest of the body.
|
|
12
12
|
*/
|
|
13
|
+
export declare function readBody(response: Response, idle: IdleTimer, max?: number): Promise<Uint8Array<ArrayBuffer>>;
|
|
14
|
+
/** Reads an error body, up to {@link MAX_ERROR_BODY} bytes, as text. */
|
|
13
15
|
export declare function errorText(response: Response, idle: IdleTimer): Promise<string>;
|
|
14
16
|
/**
|
|
15
17
|
* The streamed response of `responses.create` with `stream: true`.
|
package/dist/inference/stream.js
CHANGED
|
@@ -28,31 +28,38 @@ export function idleTimer(ms, onIdle) {
|
|
|
28
28
|
};
|
|
29
29
|
}
|
|
30
30
|
/**
|
|
31
|
-
* Reads
|
|
32
|
-
* It stops
|
|
31
|
+
* Reads a body, arming `idle` while each read waits.
|
|
32
|
+
* It stops once `max` bytes are in and cancels the rest of the body.
|
|
33
33
|
*/
|
|
34
|
-
export async function
|
|
35
|
-
|
|
36
|
-
return "";
|
|
37
|
-
const reader = response.body.getReader();
|
|
38
|
-
const decoder = new TextDecoder();
|
|
39
|
-
let text = "";
|
|
34
|
+
export async function readBody(response, idle, max = Infinity) {
|
|
35
|
+
const parts = [];
|
|
40
36
|
let size = 0;
|
|
37
|
+
const reader = response.body?.getReader();
|
|
41
38
|
try {
|
|
42
|
-
while (size <
|
|
39
|
+
while (reader && size < max) {
|
|
43
40
|
idle.arm();
|
|
44
41
|
const { value, done } = await reader.read();
|
|
45
42
|
idle.clear();
|
|
46
43
|
if (done)
|
|
47
44
|
break;
|
|
45
|
+
parts.push(value);
|
|
48
46
|
size += value.byteLength;
|
|
49
|
-
text += decoder.decode(value, { stream: true });
|
|
50
47
|
}
|
|
51
|
-
return text + decoder.decode();
|
|
52
48
|
}
|
|
53
49
|
finally {
|
|
54
|
-
reader
|
|
50
|
+
reader?.cancel().catch(() => { });
|
|
55
51
|
}
|
|
52
|
+
const body = new Uint8Array(size);
|
|
53
|
+
let offset = 0;
|
|
54
|
+
for (const part of parts) {
|
|
55
|
+
body.set(part, offset);
|
|
56
|
+
offset += part.byteLength;
|
|
57
|
+
}
|
|
58
|
+
return body;
|
|
59
|
+
}
|
|
60
|
+
/** Reads an error body, up to {@link MAX_ERROR_BODY} bytes, as text. */
|
|
61
|
+
export async function errorText(response, idle) {
|
|
62
|
+
return new TextDecoder().decode(await readBody(response, idle, MAX_ERROR_BODY));
|
|
56
63
|
}
|
|
57
64
|
/** True for the reason of a plain `abort()`, which ends a stream quietly. */
|
|
58
65
|
function isAbortError(reason) {
|
|
@@ -133,6 +133,7 @@ export interface MossInferenceOptions {
|
|
|
133
133
|
/**
|
|
134
134
|
* Your own OpenAI, Anthropic or Google key, for a vendor model such as `gpt-4o-mini`.
|
|
135
135
|
* `moss` ignores it, and a vendor model without one is refused. A call's `apiKey` wins.
|
|
136
|
+
* Used by `responses` only: tasks never send it.
|
|
136
137
|
*/
|
|
137
138
|
apiKey?: string;
|
|
138
139
|
/** The limit for each whole call, streaming included. None by default. */
|
|
@@ -144,7 +145,7 @@ export interface MossInferenceOptions {
|
|
|
144
145
|
* A failed connection or a 408, 409, 429 or 5xx response is retried.
|
|
145
146
|
*/
|
|
146
147
|
maxRetries?: number;
|
|
147
|
-
/** Headers sent on every call. */
|
|
148
|
+
/** Headers sent on every call. Task calls leave out an `Idempotency-Key` from here. */
|
|
148
149
|
headers?: Record<string, string>;
|
|
149
150
|
}
|
|
150
151
|
/** Per-call settings that never reach the request body. */
|
|
@@ -294,3 +295,153 @@ export interface ResponseStreamEvent {
|
|
|
294
295
|
arguments?: string;
|
|
295
296
|
[key: string]: any;
|
|
296
297
|
}
|
|
298
|
+
/** Where a task runs. A browser is the only environment for now. */
|
|
299
|
+
export interface TaskEnvironment {
|
|
300
|
+
type: "browser";
|
|
301
|
+
/** The page the browser opens first. */
|
|
302
|
+
start_url?: string;
|
|
303
|
+
/** True asks for `live_url`, a link to watch the browser while the task runs. */
|
|
304
|
+
live_view?: boolean;
|
|
305
|
+
}
|
|
306
|
+
/** The limits of a task. The gateway sets the ones a request leaves out. */
|
|
307
|
+
export interface TaskLimits {
|
|
308
|
+
/** The longest the task may run, in seconds. */
|
|
309
|
+
max_runtime_seconds?: number;
|
|
310
|
+
/** The most the task may spend, in US dollars. */
|
|
311
|
+
max_cost_usd?: number;
|
|
312
|
+
}
|
|
313
|
+
/**
|
|
314
|
+
* The parameters of `tasks.create`, sent as the JSON body unchanged.
|
|
315
|
+
* The gateway fills in what is left out, such as the model and the limits,
|
|
316
|
+
* and refuses a field it does not know with `invalid_request_error`.
|
|
317
|
+
*/
|
|
318
|
+
export interface TaskCreateParams {
|
|
319
|
+
/** What the agent should do, in plain words. */
|
|
320
|
+
goal: string;
|
|
321
|
+
environment: TaskEnvironment;
|
|
322
|
+
/** A JSON Schema for `result.output`. The gateway checks the answer against it. */
|
|
323
|
+
output_schema?: Record<string, unknown>;
|
|
324
|
+
limits?: TaskLimits;
|
|
325
|
+
/** A model name of the Moss catalog. The gateway picks one when it is left out. */
|
|
326
|
+
model?: string;
|
|
327
|
+
effort?: "low" | "medium" | "high";
|
|
328
|
+
/** Your own data, sent back with the task. */
|
|
329
|
+
metadata?: Record<string, unknown>;
|
|
330
|
+
}
|
|
331
|
+
/** The state of a task. It ends `completed`, `failed` or `cancelled`. */
|
|
332
|
+
export type TaskStatus = "queued" | "running" | "completed" | "failed" | "cancelled" | (string & {});
|
|
333
|
+
/** The agent's answer, where `output` is the JSON object that `output_schema` asked for. */
|
|
334
|
+
export interface TaskResult<Output = unknown> {
|
|
335
|
+
output_text: string;
|
|
336
|
+
output: Output | null;
|
|
337
|
+
[key: string]: any;
|
|
338
|
+
}
|
|
339
|
+
/** How the answer was checked: by the agent itself, or against `output_schema`. */
|
|
340
|
+
export interface TaskVerification {
|
|
341
|
+
method: "agent_reported" | "output_schema" | (string & {});
|
|
342
|
+
/** False when the answer does not match `output_schema`, null when only the agent checked it. */
|
|
343
|
+
passed: boolean | null;
|
|
344
|
+
/** What does not match, when `passed` is false. */
|
|
345
|
+
problems?: string[];
|
|
346
|
+
[key: string]: any;
|
|
347
|
+
}
|
|
348
|
+
/** What a task used, with every field the gateway sends, such as `browser_minutes`. */
|
|
349
|
+
export interface TaskUsage {
|
|
350
|
+
model_calls: number;
|
|
351
|
+
input_tokens: number;
|
|
352
|
+
cached_input_tokens: number;
|
|
353
|
+
output_tokens: number;
|
|
354
|
+
cost_usd: number;
|
|
355
|
+
[key: string]: any;
|
|
356
|
+
}
|
|
357
|
+
/** Why a task failed, such as `time_limit` or `budget_exceeded`. */
|
|
358
|
+
export interface TaskError {
|
|
359
|
+
code: string;
|
|
360
|
+
message: string;
|
|
361
|
+
[key: string]: any;
|
|
362
|
+
}
|
|
363
|
+
/**
|
|
364
|
+
* A task, the JSON the gateway sent. `Output` types `result.output`.
|
|
365
|
+
* The SDK does not check it: `verification` says whether it matched `output_schema`.
|
|
366
|
+
*/
|
|
367
|
+
export interface Task<Output = unknown> {
|
|
368
|
+
/** Such as `task_...`. */
|
|
369
|
+
id: string;
|
|
370
|
+
object: "task";
|
|
371
|
+
status: TaskStatus;
|
|
372
|
+
goal: string;
|
|
373
|
+
environment: TaskEnvironment;
|
|
374
|
+
output_schema: Record<string, unknown> | null;
|
|
375
|
+
/** The limits the task runs with, the gateway's own where the request left one out. */
|
|
376
|
+
limits: TaskLimits;
|
|
377
|
+
model: string;
|
|
378
|
+
effort: string | null;
|
|
379
|
+
metadata: Record<string, unknown> | null;
|
|
380
|
+
/** The answer once the task ends. A failed or cancelled task can have one too. */
|
|
381
|
+
result: TaskResult<Output> | null;
|
|
382
|
+
verification: TaskVerification | null;
|
|
383
|
+
usage: TaskUsage | null;
|
|
384
|
+
error: TaskError | null;
|
|
385
|
+
/** True once `tasks.trace` has the agent's record. */
|
|
386
|
+
trace_available: boolean;
|
|
387
|
+
/** A link to watch the browser while the task runs, with `live_view`. */
|
|
388
|
+
live_url?: string | null;
|
|
389
|
+
/** True while a cancel waits for a running task to stop. */
|
|
390
|
+
cancel_requested: boolean;
|
|
391
|
+
/** ISO 8601 times. */
|
|
392
|
+
created_at: string;
|
|
393
|
+
started_at: string | null;
|
|
394
|
+
finished_at: string | null;
|
|
395
|
+
/** When the gateway removes the trace and files, 7 days after the task ends. Null before. */
|
|
396
|
+
files_expire_at: string | null;
|
|
397
|
+
[key: string]: any;
|
|
398
|
+
}
|
|
399
|
+
/** A file of a task, such as a screenshot. */
|
|
400
|
+
export interface TaskFile {
|
|
401
|
+
/** The path for `tasks.files.content`, such as `screenshots/step-1.png`. */
|
|
402
|
+
path: string;
|
|
403
|
+
/** The size in bytes. */
|
|
404
|
+
bytes: number;
|
|
405
|
+
[key: string]: any;
|
|
406
|
+
}
|
|
407
|
+
/** The files of a task. */
|
|
408
|
+
export interface TaskFileList {
|
|
409
|
+
object: "list";
|
|
410
|
+
data: TaskFile[];
|
|
411
|
+
[key: string]: any;
|
|
412
|
+
}
|
|
413
|
+
/** The bytes of a task's file and their media type. The SDK never opens or renders a file. */
|
|
414
|
+
export interface TaskFileContent {
|
|
415
|
+
/** The bytes, ready for a `Blob`. */
|
|
416
|
+
data: Uint8Array<ArrayBuffer>;
|
|
417
|
+
/** The `Content-Type` the gateway sent, `application/octet-stream` when it sent none. */
|
|
418
|
+
contentType: string;
|
|
419
|
+
}
|
|
420
|
+
/** Per-call settings of a Tasks API call that is not a create, which sends no provider key. */
|
|
421
|
+
export type TaskRequestOptions = Omit<InferenceRequestOptions, "apiKey">;
|
|
422
|
+
/** Settings of `tasks.create`. Only its own `apiKey` goes as `X-Moss-Provider-Key`. */
|
|
423
|
+
export interface TaskCreateOptions extends TaskRequestOptions {
|
|
424
|
+
/**
|
|
425
|
+
* The provider key for the task's model calls. The client's `apiKey` is never used for tasks.
|
|
426
|
+
* An empty string is an error.
|
|
427
|
+
*/
|
|
428
|
+
apiKey?: string;
|
|
429
|
+
}
|
|
430
|
+
/**
|
|
431
|
+
* Settings of `tasks.wait` and `tasks.run`. Every request takes the others,
|
|
432
|
+
* with the client's `timeout` for each one.
|
|
433
|
+
*/
|
|
434
|
+
export interface TaskWaitOptions extends Omit<TaskRequestOptions, "timeout"> {
|
|
435
|
+
/** The longest the whole wait may take, in milliseconds. None by default. */
|
|
436
|
+
timeout?: number | null;
|
|
437
|
+
/** The pause between polls in milliseconds, 2000 by default. */
|
|
438
|
+
pollInterval?: number;
|
|
439
|
+
}
|
|
440
|
+
/** Settings of `tasks.run`: those of `wait`, and the `apiKey` of the create. */
|
|
441
|
+
export interface TaskRunOptions extends TaskWaitOptions {
|
|
442
|
+
/**
|
|
443
|
+
* The provider key for the task's model calls. The client's `apiKey` is never used for tasks.
|
|
444
|
+
* An empty string is an error.
|
|
445
|
+
*/
|
|
446
|
+
apiKey?: string;
|
|
447
|
+
}
|