@keln.ai/sdk 0.0.0-stage → 0.1.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/CHANGELOG.md +14 -0
- package/LICENSE +202 -0
- package/NOTICE +6 -0
- package/README.md +598 -2
- package/dist/api-promise.d.ts +30 -0
- package/dist/api-promise.js +38 -0
- package/dist/api-promise.js.map +1 -0
- package/dist/api.d.ts +130 -0
- package/dist/api.js +321 -0
- package/dist/api.js.map +1 -0
- package/dist/client.d.ts +27 -0
- package/dist/client.js +42 -0
- package/dist/client.js.map +1 -0
- package/dist/commands.d.ts +78 -0
- package/dist/commands.js +269 -0
- package/dist/commands.js.map +1 -0
- package/dist/errors.d.ts +93 -0
- package/dist/errors.js +173 -0
- package/dist/errors.js.map +1 -0
- package/dist/files.d.ts +33 -0
- package/dist/files.js +130 -0
- package/dist/files.js.map +1 -0
- package/dist/images.d.ts +79 -0
- package/dist/images.js +150 -0
- package/dist/images.js.map +1 -0
- package/dist/index.d.ts +23 -0
- package/dist/index.js +14 -0
- package/dist/index.js.map +1 -0
- package/dist/inference.d.ts +672 -0
- package/dist/inference.js +244 -0
- package/dist/inference.js.map +1 -0
- package/dist/retry.d.ts +10 -0
- package/dist/retry.js +87 -0
- package/dist/retry.js.map +1 -0
- package/dist/sandbox.d.ts +132 -0
- package/dist/sandbox.js +216 -0
- package/dist/sandbox.js.map +1 -0
- package/dist/sse.d.ts +20 -0
- package/dist/sse.js +119 -0
- package/dist/sse.js.map +1 -0
- package/dist/streaming.d.ts +20 -0
- package/dist/streaming.js +77 -0
- package/dist/streaming.js.map +1 -0
- package/dist/terminals.d.ts +75 -0
- package/dist/terminals.js +239 -0
- package/dist/terminals.js.map +1 -0
- package/dist/types.d.ts +226 -0
- package/dist/types.js +6 -0
- package/dist/types.js.map +1 -0
- package/dist/uploads.d.ts +35 -0
- package/dist/uploads.js +154 -0
- package/dist/uploads.js.map +1 -0
- package/dist/util.d.ts +19 -0
- package/dist/util.js +69 -0
- package/dist/util.js.map +1 -0
- package/dist/web.d.ts +66 -0
- package/dist/web.js +44 -0
- package/dist/web.js.map +1 -0
- package/package.json +57 -4
- package/src/api-promise.ts +50 -0
- package/src/api.ts +415 -0
- package/src/client.ts +43 -0
- package/src/commands.ts +325 -0
- package/src/errors.ts +185 -0
- package/src/files.ts +149 -0
- package/src/images.ts +174 -0
- package/src/index.ts +114 -0
- package/src/inference.ts +737 -0
- package/src/retry.ts +77 -0
- package/src/sandbox.ts +281 -0
- package/src/sse.ts +124 -0
- package/src/streaming.ts +79 -0
- package/src/terminals.ts +269 -0
- package/src/types.ts +241 -0
- package/src/uploads.ts +177 -0
- package/src/util.ts +78 -0
- package/src/web.ts +94 -0
package/src/retry.ts
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
// Portions adapted from openai-node (Apache-2.0, Copyright 2026 OpenAI) and changed by Keln. See NOTICE.
|
|
2
|
+
/** api.keln.ai: how every inference and web call retries, and the platform headers every request carries. */
|
|
3
|
+
import { VERSION } from './util.js';
|
|
4
|
+
|
|
5
|
+
export const DEFAULT_API_MAX_RETRIES = 2;
|
|
6
|
+
|
|
7
|
+
/** Whether a non-2xx answer is tried again: 408, 409, 429 and every 5xx, unless `x-should-retry` says otherwise. */
|
|
8
|
+
export function shouldRetry(status: number, headers: Headers | undefined): boolean {
|
|
9
|
+
// `x-should-retry: true` or `false` from the API decides over the status.
|
|
10
|
+
const said = headers?.get('x-should-retry');
|
|
11
|
+
if (said === 'true') return true;
|
|
12
|
+
if (said === 'false') return false;
|
|
13
|
+
return status === 408 || status === 409 || status === 429 || status >= 500;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Milliseconds before the next try: what `retry-after-ms` or `retry-after` (seconds or a date) asks, when that is
|
|
18
|
+
* between 0 and 60 seconds, else 0.5 s doubling to 8 s, less up to 25%. `retriesTaken` is 0 before the first retry.
|
|
19
|
+
*/
|
|
20
|
+
export function retryDelayMs(retriesTaken: number, headers: Headers | undefined): number {
|
|
21
|
+
let asked: number | undefined;
|
|
22
|
+
// Milliseconds first, then `retry-after` as seconds or as a date.
|
|
23
|
+
const millis = headers?.get('retry-after-ms');
|
|
24
|
+
if (millis) {
|
|
25
|
+
const value = parseFloat(millis);
|
|
26
|
+
if (!Number.isNaN(value)) asked = value;
|
|
27
|
+
}
|
|
28
|
+
const after = headers?.get('retry-after');
|
|
29
|
+
if (after && asked === undefined) {
|
|
30
|
+
const seconds = parseFloat(after);
|
|
31
|
+
asked = Number.isNaN(seconds) ? Date.parse(after) - Date.now() : seconds * 1000;
|
|
32
|
+
}
|
|
33
|
+
if (asked === undefined || !Number.isFinite(asked) || asked < 0 || asked > 60 * 1000) return defaultRetryDelayMs(retriesTaken);
|
|
34
|
+
return asked;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** 0.5 s doubling to 8 s, less a random part of up to 25%. */
|
|
38
|
+
function defaultRetryDelayMs(retriesTaken: number): number {
|
|
39
|
+
const seconds = Math.min(0.5 * Math.pow(2, retriesTaken), 8);
|
|
40
|
+
return seconds * (1 - Math.random() * 0.25) * 1000;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const normalizeArch = (arch: string): string => {
|
|
44
|
+
if (arch === 'x32') return 'x32';
|
|
45
|
+
if (arch === 'x86_64' || arch === 'x64') return 'x64';
|
|
46
|
+
if (arch === 'arm') return 'arm';
|
|
47
|
+
if (arch === 'aarch64' || arch === 'arm64') return 'arm64';
|
|
48
|
+
if (arch) return `other:${arch}`;
|
|
49
|
+
return 'unknown';
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
const normalizePlatform = (platform: string): string => {
|
|
53
|
+
platform = platform.toLowerCase();
|
|
54
|
+
if (platform.includes('ios')) return 'iOS';
|
|
55
|
+
if (platform === 'android') return 'Android';
|
|
56
|
+
if (platform === 'darwin') return 'MacOS';
|
|
57
|
+
if (platform === 'win32') return 'Windows';
|
|
58
|
+
if (platform === 'freebsd') return 'FreeBSD';
|
|
59
|
+
if (platform === 'openbsd') return 'OpenBSD';
|
|
60
|
+
if (platform === 'linux') return 'Linux';
|
|
61
|
+
if (platform) return `Other:${platform}`;
|
|
62
|
+
return 'Unknown';
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
let platformHeadersCache: Record<string, string> | undefined;
|
|
66
|
+
|
|
67
|
+
/** What every request says about the SDK and where it runs. */
|
|
68
|
+
export function platformHeaders(): Record<string, string> {
|
|
69
|
+
return (platformHeadersCache ??= {
|
|
70
|
+
'x-keln-lang': 'js',
|
|
71
|
+
'x-keln-package-version': VERSION,
|
|
72
|
+
'x-keln-os': normalizePlatform(process.platform ?? 'unknown'),
|
|
73
|
+
'x-keln-arch': normalizeArch(process.arch ?? 'unknown'),
|
|
74
|
+
'x-keln-runtime': 'node',
|
|
75
|
+
'x-keln-runtime-version': process.version ?? 'unknown',
|
|
76
|
+
});
|
|
77
|
+
}
|
package/src/sandbox.ts
ADDED
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
import type { Api } from './api.js';
|
|
2
|
+
import { Commands } from './commands.js';
|
|
3
|
+
import { KelnError } from './errors.js';
|
|
4
|
+
import { Files } from './files.js';
|
|
5
|
+
import { type SandboxImage, type SandboxImageCreateOptions, SandboxImages } from './images.js';
|
|
6
|
+
import { Terminals } from './terminals.js';
|
|
7
|
+
import type {
|
|
8
|
+
CallOptions,
|
|
9
|
+
ListData,
|
|
10
|
+
Network,
|
|
11
|
+
Port,
|
|
12
|
+
SandboxData,
|
|
13
|
+
SandboxListData,
|
|
14
|
+
SandboxState,
|
|
15
|
+
SandboxTemplate,
|
|
16
|
+
SandboxTemplateData,
|
|
17
|
+
} from './types.js';
|
|
18
|
+
import { newIdempotencyKey, sandboxPath, sleep, untilAborted } from './util.js';
|
|
19
|
+
|
|
20
|
+
export type SandboxCreateOptions = CallOptions & {
|
|
21
|
+
/** A template from `keln.templates.list()`. The API's default is `base`. */
|
|
22
|
+
template?: string;
|
|
23
|
+
/**
|
|
24
|
+
* One of your images that is `ready`, instead of `template`. The sandbox starts with the image's files, at the image's
|
|
25
|
+
* size unless `cpu` or `memoryMb` are given.
|
|
26
|
+
*/
|
|
27
|
+
image?: string;
|
|
28
|
+
/** vCPUs. Defaults to the template's (or image's) size. */
|
|
29
|
+
cpu?: number;
|
|
30
|
+
/** Memory in MiB. Defaults to the template's (or image's) size. */
|
|
31
|
+
memoryMb?: number;
|
|
32
|
+
/** Seconds from creation until the sandbox stops. The API's default is 300. */
|
|
33
|
+
timeoutS?: number;
|
|
34
|
+
/** Environment variables every command gets; a command's own `env` wins. */
|
|
35
|
+
env?: Record<string, string>;
|
|
36
|
+
/** Your labels, returned as given and usable as a list filter. */
|
|
37
|
+
metadata?: Record<string, string>;
|
|
38
|
+
/** Outbound network access at start. Change it later with `sandbox.update()`. */
|
|
39
|
+
network?: Network;
|
|
40
|
+
/** `false` returns at once, with the sandbox maybe still `starting`. Default `true`: waits for it to run. */
|
|
41
|
+
wait?: boolean;
|
|
42
|
+
/** The `Idempotency-Key`. Defaults to a fresh one per call. A retry with it never starts a second sandbox. */
|
|
43
|
+
idempotencyKey?: string;
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
export type SandboxListOptions = CallOptions & {
|
|
47
|
+
/** Only sandboxes with all of these labels. */
|
|
48
|
+
metadata?: Record<string, string>;
|
|
49
|
+
/** Only sandboxes in these states. Without it, the API lists starting, running and paused ones. */
|
|
50
|
+
state?: SandboxState | SandboxState[];
|
|
51
|
+
/** Sandboxes per page, up to 100. The iteration goes through every page either way. */
|
|
52
|
+
limit?: number;
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
export type SandboxUpdateOptions = CallOptions & {
|
|
56
|
+
/** Replaces the network policy whole. */
|
|
57
|
+
network?: Network;
|
|
58
|
+
/** The complete list of ports reachable at their preview URLs; `[]` closes every port. */
|
|
59
|
+
ports?: { port: number; public?: boolean }[];
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
function notRunning(sandbox: Sandbox): KelnError {
|
|
63
|
+
const why = sandbox.endReason === null ? '' : ` (end_reason ${sandbox.endReason})`;
|
|
64
|
+
return new KelnError(`Sandbox ${sandbox.id} is ${sandbox.state}${why}, not running.`, { code: 'sandbox_not_running' });
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Polls until the sandbox leaves `starting`. No deadline; the caller can cancel. */
|
|
68
|
+
async function whileStarting(sandbox: Sandbox, signal: AbortSignal | undefined): Promise<void> {
|
|
69
|
+
let delay = 250;
|
|
70
|
+
while (sandbox.state === 'starting') {
|
|
71
|
+
await sleep(delay, signal);
|
|
72
|
+
delay = Math.min(delay * 2, 2000);
|
|
73
|
+
await sandbox.refresh({ signal });
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* One sandbox. Its fields are the API's, as of the last answer: `refresh()` reads them again, and every call that
|
|
79
|
+
* changes the sandbox updates them. `await using` deletes it on exit.
|
|
80
|
+
*/
|
|
81
|
+
export class Sandbox {
|
|
82
|
+
id!: string;
|
|
83
|
+
object!: string;
|
|
84
|
+
/** New states pass through as strings. */
|
|
85
|
+
state!: SandboxState;
|
|
86
|
+
/** The template it started from; for a sandbox started from an image, the image's template. */
|
|
87
|
+
template!: string;
|
|
88
|
+
/** The image it started from, or `null`. */
|
|
89
|
+
image!: string | null;
|
|
90
|
+
cpu!: number;
|
|
91
|
+
memoryMb!: number;
|
|
92
|
+
diskMb!: number;
|
|
93
|
+
createdAt!: number;
|
|
94
|
+
/** When it began running; billing starts here. */
|
|
95
|
+
startedAt!: number | null;
|
|
96
|
+
expiresAt!: number;
|
|
97
|
+
endedAt!: number | null;
|
|
98
|
+
/** When it was paused, while it is `paused`. */
|
|
99
|
+
pausedAt!: number | null;
|
|
100
|
+
/** Why a stopped sandbox stopped. */
|
|
101
|
+
endReason!: string | null;
|
|
102
|
+
metadata!: Record<string, string>;
|
|
103
|
+
network!: Network;
|
|
104
|
+
ports!: Port[];
|
|
105
|
+
/** The secret a private port's requests carry as `X-Keln-Port-Token`, once the sandbox has a port. */
|
|
106
|
+
portToken!: string | null;
|
|
107
|
+
/** The object as the API sent it. */
|
|
108
|
+
raw!: SandboxData;
|
|
109
|
+
readonly commands: Commands;
|
|
110
|
+
readonly files: Files;
|
|
111
|
+
readonly terminals: Terminals;
|
|
112
|
+
readonly #api: Api;
|
|
113
|
+
|
|
114
|
+
/** Made by `keln.sandboxes`. */
|
|
115
|
+
constructor(api: Api, data: SandboxData) {
|
|
116
|
+
this.#api = api;
|
|
117
|
+
this.#apply(data);
|
|
118
|
+
this.commands = new Commands(api, data.id);
|
|
119
|
+
this.files = new Files(api, data.id);
|
|
120
|
+
this.terminals = new Terminals(api, data.id);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
#apply(data: SandboxData): this {
|
|
124
|
+
this.raw = data;
|
|
125
|
+
this.id = data.id;
|
|
126
|
+
this.object = data.object;
|
|
127
|
+
this.state = data.state;
|
|
128
|
+
this.template = data.template;
|
|
129
|
+
this.image = data.image ?? null;
|
|
130
|
+
this.cpu = data.cpu;
|
|
131
|
+
this.memoryMb = data.memory_mb;
|
|
132
|
+
this.diskMb = data.disk_mb;
|
|
133
|
+
this.createdAt = data.created_at;
|
|
134
|
+
this.startedAt = data.started_at ?? null;
|
|
135
|
+
this.expiresAt = data.expires_at;
|
|
136
|
+
this.endedAt = data.ended_at ?? null;
|
|
137
|
+
this.pausedAt = data.paused_at ?? null;
|
|
138
|
+
this.endReason = data.end_reason ?? null;
|
|
139
|
+
this.metadata = data.metadata;
|
|
140
|
+
this.network = data.network;
|
|
141
|
+
this.ports = data.ports ?? [];
|
|
142
|
+
this.portToken = data.port_token ?? null;
|
|
143
|
+
return this;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
get #path(): string {
|
|
147
|
+
return sandboxPath(this.id);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** Reads the sandbox again and updates this object. */
|
|
151
|
+
async refresh(options: CallOptions = {}): Promise<this> {
|
|
152
|
+
return this.#apply(await this.#api.json<SandboxData>('GET', this.#path, options));
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** Replaces the sandbox's `network`, its `ports`, or both, while it runs. */
|
|
156
|
+
async update(options: SandboxUpdateOptions): Promise<this> {
|
|
157
|
+
const { signal, ...json } = options;
|
|
158
|
+
return this.#apply(await this.#api.json<SandboxData>('PATCH', this.#path, { json, signal }));
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** Sets the expiry to now plus `seconds`, shorter or longer than before. */
|
|
162
|
+
async setTimeout(seconds: number, options: CallOptions = {}): Promise<this> {
|
|
163
|
+
const path = `${this.#path}/timeout`;
|
|
164
|
+
return this.#apply(await this.#api.json<SandboxData>('POST', path, { ...options, json: { timeout_s: seconds } }));
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** Pauses the sandbox with its memory, processes and files kept. Billing stops until it is resumed. */
|
|
168
|
+
async pause(options: CallOptions = {}): Promise<this> {
|
|
169
|
+
return this.#apply(await this.#api.json<SandboxData>('POST', `${this.#path}/pause`, options));
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** Runs a paused sandbox again and waits for it to run, as a create does. */
|
|
173
|
+
async resume(options: CallOptions & { timeoutS?: number } = {}): Promise<this> {
|
|
174
|
+
const { timeoutS, signal } = options;
|
|
175
|
+
const json = timeoutS === undefined ? undefined : { timeout_s: timeoutS };
|
|
176
|
+
this.#apply(await this.#api.json<SandboxData>('POST', `${this.#path}/resume`, { json, signal }));
|
|
177
|
+
await whileStarting(this, signal);
|
|
178
|
+
if (this.state === 'stopped' || this.state === 'paused') throw notRunning(this);
|
|
179
|
+
return this;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* Saves the sandbox's files as an image and waits until it is `ready` or `failed`, as `keln.sandboxImages.create`
|
|
184
|
+
* does. The sandbox keeps running.
|
|
185
|
+
*/
|
|
186
|
+
async snapshot(options: SandboxImageCreateOptions = {}): Promise<SandboxImage> {
|
|
187
|
+
return await new SandboxImages(this.#api).create(this.id, options);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** Stops the sandbox and deletes its contents; billing ends now. Stopping a stopped sandbox changes nothing. */
|
|
191
|
+
async delete(options: CallOptions = {}): Promise<this> {
|
|
192
|
+
return this.#apply(await this.#api.json<SandboxData>('DELETE', this.#path, options));
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
async [Symbol.asyncDispose](): Promise<void> {
|
|
196
|
+
await this.delete();
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** `keln.sandboxes`. */
|
|
201
|
+
export class Sandboxes {
|
|
202
|
+
readonly #api: Api;
|
|
203
|
+
|
|
204
|
+
/** Made by `Keln`. */
|
|
205
|
+
constructor(api: Api) {
|
|
206
|
+
this.#api = api;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* Starts a sandbox and waits for it to run, with no deadline of ours. A sandbox that does not reach `running`
|
|
211
|
+
* throws `KelnError` with the code `sandbox_not_running`.
|
|
212
|
+
*
|
|
213
|
+
* An abort ends the call at once. The caller then has no way to reach the sandbox, so it is stopped in the
|
|
214
|
+
* background: the POST carries on without the signal and whatever it started is deleted, so nothing is left billing.
|
|
215
|
+
*/
|
|
216
|
+
async create(options: SandboxCreateOptions = {}): Promise<Sandbox> {
|
|
217
|
+
const { template, image, cpu, memoryMb, timeoutS, env, metadata, network, wait, idempotencyKey, signal } = options;
|
|
218
|
+
signal?.throwIfAborted();
|
|
219
|
+
const api = this.#api;
|
|
220
|
+
const pending = api.json<SandboxData>('POST', '/v1/sandboxes', {
|
|
221
|
+
json: { template, image, cpu, memory_mb: memoryMb, timeout_s: timeoutS, env, metadata, network },
|
|
222
|
+
headers: { 'idempotency-key': idempotencyKey ?? newIdempotencyKey() },
|
|
223
|
+
});
|
|
224
|
+
const data = await untilAborted(pending, signal, () => {
|
|
225
|
+
pending.then((started) => api.send('DELETE', sandboxPath(started.id))).catch(() => {});
|
|
226
|
+
});
|
|
227
|
+
const sandbox = new Sandbox(api, data);
|
|
228
|
+
if (wait === false) return sandbox;
|
|
229
|
+
try {
|
|
230
|
+
await whileStarting(sandbox, signal);
|
|
231
|
+
} catch (error) {
|
|
232
|
+
const stop = sandbox.delete().catch(() => {});
|
|
233
|
+
if (!signal?.aborted) await stop;
|
|
234
|
+
throw error;
|
|
235
|
+
}
|
|
236
|
+
if (sandbox.state === 'stopped') throw notRunning(sandbox);
|
|
237
|
+
return sandbox;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
async get(sandboxId: string, options: CallOptions = {}): Promise<Sandbox> {
|
|
241
|
+
return new Sandbox(this.#api, await this.#api.json<SandboxData>('GET', sandboxPath(sandboxId), options));
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/** Iterates the sandboxes, newest first, through every page. */
|
|
245
|
+
async *list(options: SandboxListOptions = {}): AsyncGenerator<Sandbox> {
|
|
246
|
+
const { metadata, state, limit, signal } = options;
|
|
247
|
+
const query = new URLSearchParams();
|
|
248
|
+
for (const [key, value] of Object.entries(metadata ?? {})) query.append(`metadata[${key}]`, value);
|
|
249
|
+
if (state !== undefined) query.append('state', [state].flat().join(','));
|
|
250
|
+
if (limit !== undefined) query.append('limit', String(limit));
|
|
251
|
+
while (true) {
|
|
252
|
+
const page = await this.#api.json<SandboxListData>('GET', '/v1/sandboxes', { query, signal });
|
|
253
|
+
for (const data of page.data) yield new Sandbox(this.#api, data);
|
|
254
|
+
if (!page.has_more || !page.next_cursor) return;
|
|
255
|
+
query.set('after', page.next_cursor);
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** `keln.templates`. */
|
|
261
|
+
export class Templates {
|
|
262
|
+
readonly #api: Api;
|
|
263
|
+
|
|
264
|
+
/** Made by `Keln`. */
|
|
265
|
+
constructor(api: Api) {
|
|
266
|
+
this.#api = api;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/** The templates a sandbox can start from, with their default sizes. */
|
|
270
|
+
async list(options: CallOptions = {}): Promise<SandboxTemplate[]> {
|
|
271
|
+
const page = await this.#api.json<ListData<SandboxTemplateData>>('GET', '/v1/sandbox-templates', options);
|
|
272
|
+
return page.data.map((raw) => ({
|
|
273
|
+
object: raw.object,
|
|
274
|
+
name: raw.name,
|
|
275
|
+
cpu: raw.cpu,
|
|
276
|
+
memoryMb: raw.memory_mb,
|
|
277
|
+
diskMb: raw.disk_mb,
|
|
278
|
+
raw,
|
|
279
|
+
}));
|
|
280
|
+
}
|
|
281
|
+
}
|
package/src/sse.ts
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
/** One Server-Sent Event: its `event` name, its joined `data` lines, and the last `id` seen on the stream. */
|
|
2
|
+
export type ServerSentEvent = {
|
|
3
|
+
event: string;
|
|
4
|
+
data: string;
|
|
5
|
+
id: string | undefined;
|
|
6
|
+
};
|
|
7
|
+
|
|
8
|
+
/** No byte arrived for `idleTimeoutMs`. The API sends a ping while a stream is idle: this is a dead connection. */
|
|
9
|
+
export class StreamIdleError extends Error {
|
|
10
|
+
constructor(idleTimeoutMs: number) {
|
|
11
|
+
super(`no byte arrived on the event stream for ${idleTimeoutMs} ms`);
|
|
12
|
+
this.name = 'StreamIdleError';
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function readWithIdleTimeout(
|
|
17
|
+
reader: ReadableStreamDefaultReader<Uint8Array>,
|
|
18
|
+
idleTimeoutMs: number,
|
|
19
|
+
): ReturnType<ReadableStreamDefaultReader<Uint8Array>['read']> {
|
|
20
|
+
if (!(idleTimeoutMs > 0)) return reader.read();
|
|
21
|
+
return new Promise((resolve, reject) => {
|
|
22
|
+
const timer = setTimeout(() => {
|
|
23
|
+
reject(new StreamIdleError(idleTimeoutMs));
|
|
24
|
+
reader.cancel().catch(() => {});
|
|
25
|
+
}, idleTimeoutMs);
|
|
26
|
+
reader.read().then(
|
|
27
|
+
(result) => {
|
|
28
|
+
clearTimeout(timer);
|
|
29
|
+
resolve(result);
|
|
30
|
+
},
|
|
31
|
+
(error: unknown) => {
|
|
32
|
+
clearTimeout(timer);
|
|
33
|
+
reject(error);
|
|
34
|
+
},
|
|
35
|
+
);
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Reads an event stream by the Server-Sent Events rules the API needs: `id`, `event`, multi-line `data`, comments
|
|
41
|
+
* (`: ping`), dispatch on a blank line, and CR, LF or CRLF line ends. An event cut off by the end of the stream is not
|
|
42
|
+
* dispatched, as the rules say; a reattach with `Last-Event-ID` delivers it again. `onBytes` runs on every chunk that
|
|
43
|
+
* arrives, a ping included, so a caller can tell a quiet stream from a dead one.
|
|
44
|
+
*
|
|
45
|
+
* Each chunk is scanned once, so a large event (a picture as base64) takes time in proportion to its size. A CR ends
|
|
46
|
+
* its line at once; an LF that opens the next chunk after it is the rest of that CRLF.
|
|
47
|
+
*/
|
|
48
|
+
export async function* readEventStream(
|
|
49
|
+
body: ReadableStream<Uint8Array>,
|
|
50
|
+
idleTimeoutMs: number,
|
|
51
|
+
onBytes?: () => void,
|
|
52
|
+
): AsyncGenerator<ServerSentEvent> {
|
|
53
|
+
const reader = body.getReader();
|
|
54
|
+
const decoder = new TextDecoder();
|
|
55
|
+
/** The start of a line that the chunks so far have not ended, in pieces, joined once when it ends. */
|
|
56
|
+
const pieces: string[] = [];
|
|
57
|
+
/** The last chunk ended with a CR, so an LF that opens the next one belongs to it. */
|
|
58
|
+
let afterCR = false;
|
|
59
|
+
let eventName = '';
|
|
60
|
+
let data: string[] = [];
|
|
61
|
+
let hasData = false;
|
|
62
|
+
let lastId: string | undefined;
|
|
63
|
+
let finished = false;
|
|
64
|
+
try {
|
|
65
|
+
while (true) {
|
|
66
|
+
const { done, value } = await readWithIdleTimeout(reader, idleTimeoutMs);
|
|
67
|
+
if (done) {
|
|
68
|
+
finished = true;
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
onBytes?.();
|
|
72
|
+
const text = decoder.decode(value, { stream: true });
|
|
73
|
+
if (text === '') continue; // the first bytes of a character that the next chunk completes
|
|
74
|
+
let start = afterCR && text.charCodeAt(0) === 10 ? 1 : 0;
|
|
75
|
+
afterCR = false;
|
|
76
|
+
for (let index = start; index < text.length; index++) {
|
|
77
|
+
const c = text.charCodeAt(index);
|
|
78
|
+
if (c !== 10 && c !== 13) continue;
|
|
79
|
+
const end = index;
|
|
80
|
+
if (c === 13) {
|
|
81
|
+
if (index + 1 === text.length) afterCR = true;
|
|
82
|
+
else if (text.charCodeAt(index + 1) === 10) index++;
|
|
83
|
+
}
|
|
84
|
+
let line = text.slice(start, end);
|
|
85
|
+
if (pieces.length > 0) {
|
|
86
|
+
pieces.push(line);
|
|
87
|
+
line = pieces.join('');
|
|
88
|
+
pieces.length = 0;
|
|
89
|
+
}
|
|
90
|
+
start = index + 1;
|
|
91
|
+
if (line === '') {
|
|
92
|
+
if (hasData) {
|
|
93
|
+
yield { event: eventName === '' ? 'message' : eventName, data: data.join('\n'), id: lastId };
|
|
94
|
+
}
|
|
95
|
+
eventName = '';
|
|
96
|
+
data = [];
|
|
97
|
+
hasData = false;
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
if (line.startsWith(':')) continue;
|
|
101
|
+
const colon = line.indexOf(':');
|
|
102
|
+
const field = colon === -1 ? line : line.slice(0, colon);
|
|
103
|
+
let fieldValue = colon === -1 ? '' : line.slice(colon + 1);
|
|
104
|
+
if (fieldValue.startsWith(' ')) fieldValue = fieldValue.slice(1);
|
|
105
|
+
if (field === 'event') {
|
|
106
|
+
eventName = fieldValue;
|
|
107
|
+
} else if (field === 'data') {
|
|
108
|
+
data.push(fieldValue);
|
|
109
|
+
hasData = true;
|
|
110
|
+
} else if (field === 'id' && !fieldValue.includes('\0')) {
|
|
111
|
+
lastId = fieldValue;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
if (start < text.length) pieces.push(text.slice(start));
|
|
115
|
+
}
|
|
116
|
+
} finally {
|
|
117
|
+
if (!finished) await reader.cancel().catch(() => {});
|
|
118
|
+
try {
|
|
119
|
+
reader.releaseLock();
|
|
120
|
+
} catch {
|
|
121
|
+
// A read the idle timer gave up on may still be pending; the cancel above already ended the stream.
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}
|
package/src/streaming.ts
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
// Portions adapted from openai-node (Apache-2.0, Copyright 2026 OpenAI) and changed by Keln. See NOTICE.
|
|
2
|
+
/**
|
|
3
|
+
* A streamed inference answer: its chunks or events, one at a time.
|
|
4
|
+
*
|
|
5
|
+
* The loop stops at `data: [DONE]`, throws on a chunk that carries `error` (Keln's `stream_interrupted` is one), and
|
|
6
|
+
* yields every other event's data. A transport failure throws `KelnConnectionError`, the call's `timeout`
|
|
7
|
+
* `KelnTimeoutError`, and an abort of the call's signal the signal's reason.
|
|
8
|
+
*
|
|
9
|
+
* A stream is not retried once its answer has started. The request that opens it is.
|
|
10
|
+
*/
|
|
11
|
+
import { KelnApiError, KelnConnectionError, KelnError, KelnTimeoutError, streamError } from './errors.js';
|
|
12
|
+
import { readEventStream } from './sse.js';
|
|
13
|
+
|
|
14
|
+
/** How a stream reads its answer. The inference calls set it. */
|
|
15
|
+
export type StreamOptions = {
|
|
16
|
+
/** The call's `timeout` as a signal: when it fires, the stream throws `KelnTimeoutError`. */
|
|
17
|
+
timeout?: AbortSignal | undefined;
|
|
18
|
+
/** The call's own signal: when it aborts, the stream throws its reason. */
|
|
19
|
+
signal?: AbortSignal | undefined;
|
|
20
|
+
/** Takes the API key out of text that goes into an exception. */
|
|
21
|
+
redact?: ((text: string) => string) | undefined;
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
export class Stream<T> implements AsyncIterable<T> {
|
|
25
|
+
/** The API's id for the request (`x-keln-request-id`). */
|
|
26
|
+
readonly requestId: string | undefined;
|
|
27
|
+
/** Aborting it closes the stream and its connection. */
|
|
28
|
+
readonly controller: AbortController;
|
|
29
|
+
readonly response: Response;
|
|
30
|
+
readonly #operation: string;
|
|
31
|
+
readonly #options: StreamOptions;
|
|
32
|
+
#consumed = false;
|
|
33
|
+
|
|
34
|
+
/** Made by the inference calls. */
|
|
35
|
+
constructor(response: Response, controller: AbortController, operation: string, options: StreamOptions = {}) {
|
|
36
|
+
this.response = response;
|
|
37
|
+
this.controller = controller;
|
|
38
|
+
this.requestId = response.headers.get('x-keln-request-id') ?? response.headers.get('x-request-id') ?? undefined;
|
|
39
|
+
this.#operation = operation;
|
|
40
|
+
this.#options = options;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
async *[Symbol.asyncIterator](): AsyncIterator<T> {
|
|
44
|
+
if (this.#consumed) throw new KelnError('A stream can be read once, and this one has been read.');
|
|
45
|
+
this.#consumed = true;
|
|
46
|
+
const { signal, timeout } = this.#options;
|
|
47
|
+
const redact = this.#options.redact ?? ((text: string): string => text);
|
|
48
|
+
const body = this.response.body;
|
|
49
|
+
if (body === null) return;
|
|
50
|
+
try {
|
|
51
|
+
for await (const sse of readEventStream(body, 0)) {
|
|
52
|
+
if (sse.data.startsWith('[DONE]')) return;
|
|
53
|
+
let data: unknown;
|
|
54
|
+
try {
|
|
55
|
+
data = JSON.parse(sse.data);
|
|
56
|
+
} catch {
|
|
57
|
+
throw new KelnApiError({
|
|
58
|
+
status: undefined,
|
|
59
|
+
message: `A ${this.#operation} stream event carries data that is not JSON.`,
|
|
60
|
+
body: redact(sse.data),
|
|
61
|
+
requestId: this.requestId,
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
if (data !== null && typeof data === 'object' && (data as { error?: unknown }).error) {
|
|
65
|
+
throw streamError(data as Record<string, unknown>, sse.data, this.requestId, redact);
|
|
66
|
+
}
|
|
67
|
+
yield data as T;
|
|
68
|
+
}
|
|
69
|
+
} catch (error) {
|
|
70
|
+
if (error instanceof KelnApiError) throw error;
|
|
71
|
+
if (signal?.aborted === true) throw signal.reason;
|
|
72
|
+
if (timeout?.aborted === true) throw new KelnTimeoutError(`Keln ${this.#operation} ran past its timeout.`);
|
|
73
|
+
if (this.controller.signal.aborted) throw this.controller.signal.reason;
|
|
74
|
+
throw new KelnConnectionError(`Keln ${this.#operation} failed: the connection closed before the stream finished`, { cause: error });
|
|
75
|
+
} finally {
|
|
76
|
+
this.controller.abort();
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|