@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.
Files changed (77) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +6 -0
  4. package/README.md +598 -2
  5. package/dist/api-promise.d.ts +30 -0
  6. package/dist/api-promise.js +38 -0
  7. package/dist/api-promise.js.map +1 -0
  8. package/dist/api.d.ts +130 -0
  9. package/dist/api.js +321 -0
  10. package/dist/api.js.map +1 -0
  11. package/dist/client.d.ts +27 -0
  12. package/dist/client.js +42 -0
  13. package/dist/client.js.map +1 -0
  14. package/dist/commands.d.ts +78 -0
  15. package/dist/commands.js +269 -0
  16. package/dist/commands.js.map +1 -0
  17. package/dist/errors.d.ts +93 -0
  18. package/dist/errors.js +173 -0
  19. package/dist/errors.js.map +1 -0
  20. package/dist/files.d.ts +33 -0
  21. package/dist/files.js +130 -0
  22. package/dist/files.js.map +1 -0
  23. package/dist/images.d.ts +79 -0
  24. package/dist/images.js +150 -0
  25. package/dist/images.js.map +1 -0
  26. package/dist/index.d.ts +23 -0
  27. package/dist/index.js +14 -0
  28. package/dist/index.js.map +1 -0
  29. package/dist/inference.d.ts +672 -0
  30. package/dist/inference.js +244 -0
  31. package/dist/inference.js.map +1 -0
  32. package/dist/retry.d.ts +10 -0
  33. package/dist/retry.js +87 -0
  34. package/dist/retry.js.map +1 -0
  35. package/dist/sandbox.d.ts +132 -0
  36. package/dist/sandbox.js +216 -0
  37. package/dist/sandbox.js.map +1 -0
  38. package/dist/sse.d.ts +20 -0
  39. package/dist/sse.js +119 -0
  40. package/dist/sse.js.map +1 -0
  41. package/dist/streaming.d.ts +20 -0
  42. package/dist/streaming.js +77 -0
  43. package/dist/streaming.js.map +1 -0
  44. package/dist/terminals.d.ts +75 -0
  45. package/dist/terminals.js +239 -0
  46. package/dist/terminals.js.map +1 -0
  47. package/dist/types.d.ts +226 -0
  48. package/dist/types.js +6 -0
  49. package/dist/types.js.map +1 -0
  50. package/dist/uploads.d.ts +35 -0
  51. package/dist/uploads.js +154 -0
  52. package/dist/uploads.js.map +1 -0
  53. package/dist/util.d.ts +19 -0
  54. package/dist/util.js +69 -0
  55. package/dist/util.js.map +1 -0
  56. package/dist/web.d.ts +66 -0
  57. package/dist/web.js +44 -0
  58. package/dist/web.js.map +1 -0
  59. package/package.json +57 -4
  60. package/src/api-promise.ts +50 -0
  61. package/src/api.ts +415 -0
  62. package/src/client.ts +43 -0
  63. package/src/commands.ts +325 -0
  64. package/src/errors.ts +185 -0
  65. package/src/files.ts +149 -0
  66. package/src/images.ts +174 -0
  67. package/src/index.ts +114 -0
  68. package/src/inference.ts +737 -0
  69. package/src/retry.ts +77 -0
  70. package/src/sandbox.ts +281 -0
  71. package/src/sse.ts +124 -0
  72. package/src/streaming.ts +79 -0
  73. package/src/terminals.ts +269 -0
  74. package/src/types.ts +241 -0
  75. package/src/uploads.ts +177 -0
  76. package/src/util.ts +78 -0
  77. package/src/web.ts +94 -0
@@ -0,0 +1,325 @@
1
+ import type { Api } from './api.js';
2
+ import { KelnApiError, KelnError, apiError } from './errors.js';
3
+ import { readEventStream, type ServerSentEvent } from './sse.js';
4
+ import type {
5
+ CallOptions,
6
+ CommandData,
7
+ CommandEvent,
8
+ CommandResult,
9
+ CommandState,
10
+ ListData,
11
+ } from './types.js';
12
+ import { backoffMs, newIdempotencyKey, sandboxPath, sleep, utf8Decoder } from './util.js';
13
+
14
+ /** What to run: a shell line, through `bash -lc`, or a program and its arguments, run directly. */
15
+ export type CommandLine = string | string[];
16
+
17
+ export type CommandOptions = CallOptions & {
18
+ /** Working directory (absolute). Defaults to the user's home. */
19
+ cwd?: string;
20
+ /** Environment variables, over the sandbox's own. */
21
+ env?: Record<string, string>;
22
+ /** `user` (the API's default) or `root`. */
23
+ user?: 'user' | 'root';
24
+ /** The API's timeout: it kills the command after this many seconds of running. Unset, the command runs on. */
25
+ timeoutS?: number;
26
+ /** Keep stdin open for `command.write()`. */
27
+ stdin?: boolean;
28
+ /** The `Idempotency-Key`. Defaults to a fresh one per call. A retry with it never runs the command twice. */
29
+ idempotencyKey?: string;
30
+ };
31
+
32
+ export type OutputOptions = {
33
+ /** Sees stdout as it arrives. A multi-byte character split across two events arrives whole. */
34
+ onStdout?: (text: string) => void;
35
+ /** Sees stderr as it arrives. */
36
+ onStderr?: (text: string) => void;
37
+ };
38
+
39
+ export type RunOptions = CommandOptions & OutputOptions;
40
+
41
+ function commandBody(cmd: CommandLine, options: CommandOptions): Record<string, unknown> {
42
+ return {
43
+ ...(typeof cmd === 'string' ? { command: cmd } : { argv: cmd }),
44
+ cwd: options.cwd,
45
+ env: options.env,
46
+ user: options.user,
47
+ timeout_s: options.timeoutS,
48
+ stdin: options.stdin,
49
+ };
50
+ }
51
+
52
+ function parsed(data: string): unknown {
53
+ try {
54
+ return JSON.parse(data);
55
+ } catch {
56
+ return data;
57
+ }
58
+ }
59
+
60
+ /** The data of an event this SDK names. */
61
+ function objectOf(api: Api, sse: ServerSentEvent): Record<string, unknown> {
62
+ const value = parsed(sse.data);
63
+ if (value !== null && typeof value === 'object') return value as Record<string, unknown>;
64
+ throw new KelnApiError({
65
+ status: undefined,
66
+ message: `A \`${sse.event}\` event carries data that is not a JSON object.`,
67
+ body: api.redact(sse.data),
68
+ });
69
+ }
70
+
71
+ function eventOf(api: Api, sse: ServerSentEvent): CommandEvent {
72
+ const id = sse.id as string;
73
+ switch (sse.event) {
74
+ case 'error':
75
+ throw apiError(undefined, api.redact(sse.data));
76
+ case 'started': {
77
+ const raw = objectOf(api, sse);
78
+ return { type: 'started', id, commandId: raw.command_id as string, pid: raw.pid as number, raw };
79
+ }
80
+ case 'stdout':
81
+ case 'stderr': {
82
+ const raw = objectOf(api, sse);
83
+ // `new Uint8Array` copies: small Buffers share one pooled ArrayBuffer, which a reader of `.buffer` must not see.
84
+ const data = new Uint8Array(Buffer.from(typeof raw.data === 'string' ? raw.data : '', 'base64'));
85
+ return { type: sse.event, id, data, ts: raw.ts as number | undefined, raw };
86
+ }
87
+ case 'exit': {
88
+ const raw = objectOf(api, sse);
89
+ const exitCode = (raw.exit_code as number | null | undefined) ?? null;
90
+ const signal = (raw.signal as number | null | undefined) ?? null;
91
+ return { type: 'exit', id, exitCode, signal, oomKilled: raw.oom_killed === true, raw };
92
+ }
93
+ default:
94
+ return { type: sse.event, id: sse.id, raw: parsed(sse.data) } as unknown as CommandEvent; // new types pass through
95
+ }
96
+ }
97
+
98
+ /**
99
+ * A command's events, to its `exit` event. `from` starts the command (`POST …/commands`, streamed) or attaches to one
100
+ * that already runs. When the stream drops (it ends early, breaks, or stays silent past `streamIdleTimeoutMs`) this
101
+ * reattaches with `GET …/events` and `Last-Event-ID`, so no event is lost or repeated. It reattaches by the
102
+ * `Keln-Command-Id` header when the stream dropped before `started`. A command the API has not named yet is sent again
103
+ * with the same `Idempotency-Key`, which replays it and never runs it twice.
104
+ *
105
+ * Only a stream that delivers nothing counts against `maxReattachAttempts`. A ping is a delivery, so a long silent
106
+ * command survives any number of drops. `request` retries the attach itself, and a failure it gives up on is final.
107
+ * Every `KelnError` it throws carries `commandId` once the API has named the command, which may still be running.
108
+ */
109
+ async function* follow(
110
+ api: Api,
111
+ commandsPath: string,
112
+ from: { body?: unknown; idempotencyKey?: string; commandId?: string; lastEventId?: string },
113
+ signal: AbortSignal | undefined,
114
+ ): AsyncGenerator<CommandEvent> {
115
+ let { commandId, lastEventId } = from;
116
+ let failures = 0;
117
+ try {
118
+ while (true) {
119
+ const response =
120
+ commandId === undefined
121
+ ? await api.request('POST', commandsPath, {
122
+ json: from.body,
123
+ headers: { accept: 'text/event-stream', 'idempotency-key': from.idempotencyKey as string },
124
+ signal,
125
+ })
126
+ : await api.request('GET', `${commandsPath}/${encodeURIComponent(commandId)}/events`, {
127
+ headers: {
128
+ accept: 'text/event-stream',
129
+ ...(lastEventId !== undefined ? { 'last-event-id': lastEventId } : {}),
130
+ },
131
+ signal,
132
+ });
133
+ commandId ??= response.headers.get('keln-command-id') ?? undefined;
134
+ let failure: unknown = "the event stream ended before it reported the command's exit";
135
+ try {
136
+ if (response.body !== null) {
137
+ const streamed = readEventStream(response.body, api.streamIdleTimeoutMs, () => {
138
+ failures = 0;
139
+ });
140
+ for await (const sse of streamed) {
141
+ const event = eventOf(api, sse);
142
+ if (event.type === 'started') commandId ??= event.commandId;
143
+ lastEventId = event.id ?? lastEventId;
144
+ yield event;
145
+ if (event.type === 'exit') return;
146
+ }
147
+ }
148
+ } catch (error) {
149
+ if (signal?.aborted) throw signal.reason;
150
+ if (error instanceof KelnApiError) throw error; // an `error` event: it ends the stream, the API said why
151
+ failure = error;
152
+ }
153
+ failures += 1;
154
+ if (failures > api.maxReattachAttempts) {
155
+ const which = commandId ? `command ${commandId}` : 'a command that had no id yet';
156
+ throw api.connectionError(failure, `The event stream of ${which} closed and could not be reattached`);
157
+ }
158
+ await sleep(backoffMs(failures, undefined), signal);
159
+ }
160
+ } catch (error) {
161
+ if (error instanceof KelnError) error.commandId ??= commandId;
162
+ throw error;
163
+ }
164
+ }
165
+
166
+ /** Reads a command's events from its first one to its exit. */
167
+ async function collect(
168
+ events: AsyncIterable<CommandEvent>,
169
+ commandId: string | undefined,
170
+ options: OutputOptions,
171
+ ): Promise<CommandResult> {
172
+ const decoders = { stdout: utf8Decoder(), stderr: utf8Decoder() };
173
+ const output = { stdout: '', stderr: '' };
174
+ const notify = { stdout: options.onStdout, stderr: options.onStderr };
175
+ const add = (stream: 'stdout' | 'stderr', text: string): void => {
176
+ if (text === '') return;
177
+ output[stream] += text;
178
+ notify[stream]?.(text);
179
+ };
180
+ let id = commandId;
181
+ let exit: Extract<CommandEvent, { type: 'exit' }> | undefined;
182
+ for await (const event of events) {
183
+ if (event.type === 'started') id = event.commandId;
184
+ else if (event.type === 'stdout' || event.type === 'stderr') {
185
+ add(event.type, decoders[event.type].decode(event.data, { stream: true }));
186
+ } else if (event.type === 'exit') exit = event;
187
+ }
188
+ add('stdout', decoders.stdout.decode());
189
+ add('stderr', decoders.stderr.decode());
190
+ const { exitCode, signal: exitSignal, oomKilled } = exit as NonNullable<typeof exit>; // `follow` ends on `exit` or throws
191
+ return { id: id as string, exitCode, stdout: output.stdout, stderr: output.stderr, exitSignal, oomKilled };
192
+ }
193
+
194
+ /** One command, started in the background or found by id. Its fields are the API's, as of the last answer. */
195
+ export class Command {
196
+ id!: string;
197
+ object!: string;
198
+ sandboxId!: string;
199
+ state!: CommandState;
200
+ /** What ran (`["bash", "-lc", "<command>"]` for a shell line). */
201
+ argv!: string[];
202
+ exitCode!: number | null;
203
+ /** The API's `signal`, the signal that ended the command. `signal()` is the call that sends one. */
204
+ exitSignal!: number | null;
205
+ oomKilled!: boolean;
206
+ /** Whether stdin is open for writing. */
207
+ stdin!: boolean;
208
+ startedAt!: number;
209
+ endedAt!: number | null;
210
+ /** The object as the API sent it. */
211
+ raw!: CommandData;
212
+ readonly #api: Api;
213
+ readonly #commandsPath: string;
214
+
215
+ /** Made by `sandbox.commands`. */
216
+ constructor(api: Api, data: CommandData) {
217
+ this.#api = api;
218
+ this.#commandsPath = `${sandboxPath(data.sandbox_id)}/commands`;
219
+ this.#apply(data);
220
+ }
221
+
222
+ #apply(data: CommandData): this {
223
+ this.raw = data;
224
+ this.id = data.id;
225
+ this.object = data.object;
226
+ this.sandboxId = data.sandbox_id;
227
+ this.state = data.state;
228
+ this.argv = data.argv;
229
+ this.exitCode = data.exit_code ?? null;
230
+ this.exitSignal = data.signal ?? null;
231
+ this.oomKilled = data.oom_killed ?? false;
232
+ this.stdin = data.stdin;
233
+ this.startedAt = data.started_at;
234
+ this.endedAt = data.ended_at ?? null;
235
+ return this;
236
+ }
237
+
238
+ get #path(): string {
239
+ return `${this.#commandsPath}/${encodeURIComponent(this.id)}`;
240
+ }
241
+
242
+ /** Waits for the exit and returns the command's whole output, from its first event. Aborting leaves it running. */
243
+ async wait(options: CallOptions & OutputOptions = {}): Promise<CommandResult> {
244
+ return await collect(this.events({ signal: options.signal }), this.id, options);
245
+ }
246
+
247
+ /** The command's events, from the start or after `lastEventId`, to its `exit` event. It reattaches by itself. */
248
+ events(options: CallOptions & { lastEventId?: string } = {}): AsyncGenerator<CommandEvent> {
249
+ return follow(this.#api, this.#commandsPath, { commandId: this.id, lastEventId: options.lastEventId }, options.signal);
250
+ }
251
+
252
+ /** Reads the command again and updates this object. */
253
+ async refresh(options: CallOptions = {}): Promise<this> {
254
+ return this.#apply(await this.#api.json<CommandData>('GET', this.#path, options));
255
+ }
256
+
257
+ /** Sends SIGKILL. Killing an exited command changes nothing. */
258
+ async kill(options: CallOptions = {}): Promise<this> {
259
+ return this.#apply(await this.#api.json<CommandData>('DELETE', this.#path, options));
260
+ }
261
+
262
+ /** Sends a signal, by name (`SIGTERM`, `TERM`) or number (15). */
263
+ async signal(signal: string | number, options: CallOptions = {}): Promise<this> {
264
+ const path = `${this.#path}/signal`;
265
+ return this.#apply(await this.#api.json<CommandData>('POST', path, { ...options, json: { signal } }));
266
+ }
267
+
268
+ /** Writes to the command's stdin, which needs `stdin: true` at the start. */
269
+ async write(data: Uint8Array | string, options: CallOptions = {}): Promise<void> {
270
+ await this.#api.send('POST', `${this.#path}/stdin`, {
271
+ ...options,
272
+ body: typeof data === 'string' ? new TextEncoder().encode(data) : data,
273
+ headers: { 'content-type': 'application/octet-stream' },
274
+ });
275
+ }
276
+
277
+ /** Sends end-of-file. Closing a closed stdin changes nothing. */
278
+ async closeStdin(options: CallOptions = {}): Promise<void> {
279
+ await this.#api.send('POST', `${this.#path}/stdin/close`, options);
280
+ }
281
+ }
282
+
283
+ /** The commands of one sandbox: `sandbox.commands`. */
284
+ export class Commands {
285
+ readonly #api: Api;
286
+ readonly #path: string;
287
+
288
+ /** Made by `Sandbox`. */
289
+ constructor(api: Api, sandboxId: string) {
290
+ this.#api = api;
291
+ this.#path = `${sandboxPath(sandboxId)}/commands`;
292
+ }
293
+
294
+ /** Runs a command, waits for its exit and returns its result. Aborting stops the waiting, not the command. */
295
+ async run(cmd: CommandLine, options: RunOptions = {}): Promise<CommandResult> {
296
+ return await collect(this.stream(cmd, options), undefined, options);
297
+ }
298
+
299
+ /** Runs a command and iterates its events: `started`, `stdout`, `stderr`, `exit`. It reattaches by itself. */
300
+ stream(cmd: CommandLine, options: CommandOptions = {}): AsyncGenerator<CommandEvent> {
301
+ const idempotencyKey = options.idempotencyKey ?? newIdempotencyKey();
302
+ return follow(this.#api, this.#path, { body: commandBody(cmd, options), idempotencyKey }, options.signal);
303
+ }
304
+
305
+ /** Starts a command in the background and returns it at once. */
306
+ async start(cmd: CommandLine, options: CommandOptions = {}): Promise<Command> {
307
+ const data = await this.#api.json<CommandData>('POST', this.#path, {
308
+ json: { ...commandBody(cmd, options), background: true },
309
+ headers: { 'idempotency-key': options.idempotencyKey ?? newIdempotencyKey() },
310
+ signal: options.signal,
311
+ });
312
+ return new Command(this.#api, data);
313
+ }
314
+
315
+ async get(commandId: string, options: CallOptions = {}): Promise<Command> {
316
+ const path = `${this.#path}/${encodeURIComponent(commandId)}`;
317
+ return new Command(this.#api, await this.#api.json<CommandData>('GET', path, options));
318
+ }
319
+
320
+ /** The sandbox's commands, running and exited, newest first. */
321
+ async list(options: CallOptions = {}): Promise<Command[]> {
322
+ const page = await this.#api.json<ListData<CommandData>>('GET', this.#path, options);
323
+ return page.data.map((data) => new Command(this.#api, data));
324
+ }
325
+ }
package/src/errors.ts ADDED
@@ -0,0 +1,185 @@
1
+ // Portions adapted from openai-node (Apache-2.0, Copyright 2026 OpenAI) and changed by Keln. See NOTICE.
2
+ /** Everything this SDK raises, except the reason of an aborted `AbortSignal`. */
3
+ export class KelnError extends Error {
4
+ /** The specific cause. `code` is the field to branch on; messages are for people. */
5
+ readonly code: string | undefined;
6
+ /**
7
+ * The command a failure happened to, once the API has named it. That command may still be running:
8
+ * `sandbox.commands.get(commandId)` reaches it again. `undefined` for a failure that is not a command's.
9
+ */
10
+ commandId: string | undefined;
11
+
12
+ constructor(message: string, options: { code?: string | undefined; cause?: unknown; commandId?: string | undefined } = {}) {
13
+ super(message, options.cause === undefined ? undefined : { cause: options.cause });
14
+ this.name = new.target.name;
15
+ this.code = options.code;
16
+ this.commandId = options.commandId;
17
+ }
18
+ }
19
+
20
+ /**
21
+ * The API answered with an error: a non-2xx status, or an error inside a stream (an `error` event on a command's
22
+ * stream, or a chunk carrying `error`, such as Keln's `stream_interrupted`). A non-2xx answer throws the subclass named
23
+ * for its status (`RateLimitError` for a 429).
24
+ */
25
+ export class KelnApiError extends KelnError {
26
+ /** The HTTP status; `undefined` for an error inside a stream. */
27
+ readonly status: number | undefined;
28
+ /** The API's `error.type`, the class, such as `not_found_error`. */
29
+ readonly type: string | undefined;
30
+ /** The request field at fault, when the API names one. */
31
+ readonly param: string | undefined;
32
+ /** Seconds from `Retry-After`, when the API sent it. */
33
+ readonly retryAfter: number | undefined;
34
+ /** The complete response body (or the event's data), as received. */
35
+ readonly body: string;
36
+ /** The API's id for the request (`x-keln-request-id`), when it sent one: quote it to support. */
37
+ readonly requestId: string | undefined;
38
+ /** The answer's headers, for an HTTP error. */
39
+ readonly headers: Headers | undefined;
40
+
41
+ constructor(fields: {
42
+ status: number | undefined;
43
+ code?: string | undefined;
44
+ type?: string | undefined;
45
+ param?: string | undefined;
46
+ message: string;
47
+ retryAfter?: number | undefined;
48
+ body: string;
49
+ requestId?: string | undefined;
50
+ headers?: Headers | undefined;
51
+ }) {
52
+ super(fields.message, { code: fields.code });
53
+ this.status = fields.status;
54
+ this.type = fields.type;
55
+ this.param = fields.param;
56
+ this.retryAfter = fields.retryAfter;
57
+ this.body = fields.body;
58
+ this.requestId = fields.requestId;
59
+ this.headers = fields.headers;
60
+ }
61
+ }
62
+
63
+ // One class per status, so a caller can branch on `instanceof RateLimitError`.
64
+ /** 400. */
65
+ export class BadRequestError extends KelnApiError {}
66
+ /** 401. */
67
+ export class AuthenticationError extends KelnApiError {}
68
+ /** 403. */
69
+ export class PermissionDeniedError extends KelnApiError {}
70
+ /** 404. */
71
+ export class NotFoundError extends KelnApiError {}
72
+ /** 409. */
73
+ export class ConflictError extends KelnApiError {}
74
+ /** 422. */
75
+ export class UnprocessableEntityError extends KelnApiError {}
76
+ /** 429. */
77
+ export class RateLimitError extends KelnApiError {}
78
+ /** Any 5xx. */
79
+ export class InternalServerError extends KelnApiError {}
80
+
81
+ function errorClass(status: number | undefined): typeof KelnApiError {
82
+ if (status === undefined) return KelnApiError;
83
+ if (status === 400) return BadRequestError;
84
+ if (status === 401) return AuthenticationError;
85
+ if (status === 403) return PermissionDeniedError;
86
+ if (status === 404) return NotFoundError;
87
+ if (status === 409) return ConflictError;
88
+ if (status === 422) return UnprocessableEntityError;
89
+ if (status === 429) return RateLimitError;
90
+ if (status >= 500) return InternalServerError;
91
+ return KelnApiError;
92
+ }
93
+
94
+ /** The API could not be reached, or its answer could not be read to the end. */
95
+ export class KelnConnectionError extends KelnError {}
96
+
97
+ /** A call ran past its `timeout`. */
98
+ export class KelnTimeoutError extends KelnError {}
99
+
100
+ function field(error: Record<string, unknown> | undefined, name: string): string | undefined {
101
+ const value = error?.[name];
102
+ return typeof value === 'string' ? value : undefined;
103
+ }
104
+
105
+ /** The `error` object of a body, or `undefined` when it does not have the API's error shape. */
106
+ function errorObject(text: string): Record<string, unknown> | undefined {
107
+ try {
108
+ const error = (JSON.parse(text) as { error?: unknown } | null)?.error;
109
+ return error !== null && typeof error === 'object' ? (error as Record<string, unknown>) : undefined;
110
+ } catch {
111
+ return undefined;
112
+ }
113
+ }
114
+
115
+ /** The API's id for a request, from its answer's headers: `x-keln-request-id`, else `x-request-id`. */
116
+ export function requestIdOf(headers: Headers | undefined): string | undefined {
117
+ return headers?.get('x-keln-request-id') ?? headers?.get('x-request-id') ?? undefined;
118
+ }
119
+
120
+ /**
121
+ * The error for an HTTP answer (`status`), or for an `error` event, which has no status. A body without the API's
122
+ * error shape (a proxy in between, say) gives the message its start and `body` all of it.
123
+ */
124
+ export function apiError(
125
+ status: number | undefined,
126
+ text: string,
127
+ retryAfterHeader?: string | null,
128
+ headers?: Headers,
129
+ ): KelnApiError {
130
+ const error = errorObject(text);
131
+ const seconds = retryAfterHeader ? Number(retryAfterHeader) : Number.NaN;
132
+ const ErrorClass = errorClass(status);
133
+ return new ErrorClass({
134
+ status,
135
+ code: field(error, 'code'),
136
+ type: field(error, 'type'),
137
+ param: field(error, 'param'),
138
+ message:
139
+ field(error, 'message') ??
140
+ (text.trim().slice(0, 2000) ||
141
+ (typeof status === 'number' ? `The response (${status}) has an empty body.` : 'The error event has an empty body.')),
142
+ retryAfter: Number.isFinite(seconds) ? seconds : undefined,
143
+ body: text,
144
+ requestId: requestIdOf(headers),
145
+ headers,
146
+ });
147
+ }
148
+
149
+ /**
150
+ * The error a streamed answer ends with after its 200: a chunk carrying `error`, such as Keln's `stream_interrupted`.
151
+ * `redact` takes the API key out of every text the error keeps.
152
+ */
153
+ export function streamError(
154
+ data: Record<string, unknown>,
155
+ raw: string,
156
+ requestId: string | undefined,
157
+ redact: (text: string) => string,
158
+ ): KelnApiError {
159
+ const error = data.error !== null && typeof data.error === 'object' ? (data.error as Record<string, unknown>) : undefined;
160
+ const text = (name: string): string | undefined => {
161
+ const value = field(error, name);
162
+ return value === undefined ? undefined : redact(value);
163
+ };
164
+ return new KelnApiError({
165
+ status: undefined,
166
+ code: text('code'),
167
+ type: text('type'),
168
+ param: text('param'),
169
+ message: text('message') || 'The stream ended with an error.',
170
+ body: redact(raw),
171
+ requestId,
172
+ });
173
+ }
174
+
175
+ /** Whether an error is a `409 idempotency_key_in_use`: the first request with that key has not finished yet. */
176
+ export function isKeyInUse(error: unknown): boolean {
177
+ return error instanceof KelnApiError && error.status === 409 && error.code === 'idempotency_key_in_use';
178
+ }
179
+
180
+ /** What a safe call may try again: transport failures, 429, 502, 503, and a key still in use. */
181
+ export function isRetryable(error: unknown): boolean {
182
+ if (error instanceof KelnConnectionError) return true;
183
+ if (!(error instanceof KelnApiError)) return false;
184
+ return error.status === 429 || error.status === 502 || error.status === 503 || isKeyInUse(error);
185
+ }
package/src/files.ts ADDED
@@ -0,0 +1,149 @@
1
+ import type { Api } from './api.js';
2
+ import type {
3
+ CallOptions,
4
+ FileEntry,
5
+ FileEntryData,
6
+ FileStat,
7
+ FileStatData,
8
+ FileWritten,
9
+ FileWrittenData,
10
+ ListData,
11
+ } from './types.js';
12
+ import { sandboxPath, utf8Decoder } from './util.js';
13
+
14
+ /** What `files.write` takes: bytes, text (sent as UTF-8), or a stream of any size, which a Node stream also is. */
15
+ export type FileData = Uint8Array | string | ReadableStream<Uint8Array> | AsyncIterable<Uint8Array>;
16
+
17
+ function fileStat(raw: FileStatData): FileStat {
18
+ const { object, path, type } = raw;
19
+ return { object, path, type, size: raw.size ?? null, modifiedAt: raw.modified_at ?? null, raw };
20
+ }
21
+
22
+ function fileEntry(raw: FileEntryData): FileEntry {
23
+ const { name, path, type } = raw;
24
+ return { name, path, type, size: raw.size ?? null, modifiedAt: raw.modified_at ?? null, raw };
25
+ }
26
+
27
+ /** An upload's body, and `stop`, which ends the caller's stream when the write fails. */
28
+ type Upload = { body: Uint8Array | ReadableStream<Uint8Array>; stop: (reason: unknown) => void };
29
+
30
+ /**
31
+ * `data` as the body of a write. A stream goes through a reader the SDK holds, so a failed write can cancel it even
32
+ * while `fetch` still holds the body: the caller's stream then ends, and a file it reads from closes.
33
+ */
34
+ function uploadBody(data: FileData): Upload {
35
+ if (typeof data === 'string') return { body: new TextEncoder().encode(data), stop: () => {} };
36
+ if (data instanceof Uint8Array) return { body: data, stop: () => {} };
37
+ const reader = (data instanceof ReadableStream ? data : ReadableStream.from(data)).getReader();
38
+ // A Node stream closes its file only when destroyed, and one that never delivered a chunk is not ended by a cancel.
39
+ const node = data as { destroy?: unknown };
40
+ const destroy = typeof node.destroy === 'function' ? (node.destroy as () => void).bind(data) : undefined;
41
+ const body = new ReadableStream<Uint8Array>({
42
+ async pull(controller) {
43
+ const next = await reader.read();
44
+ try {
45
+ if (next.done) controller.close();
46
+ else controller.enqueue(next.value);
47
+ } catch {
48
+ // The body was cancelled meanwhile: nothing more goes out.
49
+ }
50
+ },
51
+ async cancel(reason) {
52
+ await reader.cancel(reason);
53
+ },
54
+ });
55
+ const stop = (reason: unknown): void => {
56
+ reader.cancel(reason).catch(() => {});
57
+ try {
58
+ destroy?.();
59
+ } catch {
60
+ // Already ended.
61
+ }
62
+ };
63
+ return { body, stop };
64
+ }
65
+
66
+ /** The files of one sandbox: `sandbox.files`. Paths are absolute. */
67
+ export class Files {
68
+ readonly #api: Api;
69
+ readonly #path: string;
70
+
71
+ /** Made by `Sandbox`. */
72
+ constructor(api: Api, sandboxId: string) {
73
+ this.#api = api;
74
+ this.#path = `${sandboxPath(sandboxId)}/files`;
75
+ }
76
+
77
+ /** The file's bytes. */
78
+ async read(path: string, options: CallOptions = {}): Promise<Uint8Array> {
79
+ return await this.#api.request('GET', this.#path, { ...options, query: { path } }, async (response) => {
80
+ return new Uint8Array(await response.arrayBuffer());
81
+ });
82
+ }
83
+
84
+ /** The file, decoded as UTF-8. */
85
+ async readText(path: string, options: CallOptions = {}): Promise<string> {
86
+ return utf8Decoder().decode(await this.read(path, options));
87
+ }
88
+
89
+ /** Iterates the chunks of a large file as they arrive. */
90
+ async *stream(path: string, options: CallOptions = {}): AsyncGenerator<Uint8Array> {
91
+ const response = await this.#api.request('GET', this.#path, { ...options, query: { path } });
92
+ if (response.body === null) return;
93
+ try {
94
+ for await (const chunk of response.body) yield chunk;
95
+ } catch (error) {
96
+ if (options.signal?.aborted) throw options.signal.reason;
97
+ throw this.#api.connectionError(error);
98
+ }
99
+ }
100
+
101
+ /**
102
+ * Writes a file, replacing one that exists. `data` is sent as it comes, with no limit on its size. A write that
103
+ * fails, before or during the upload, cancels a stream `data`, so a file it reads from closes.
104
+ */
105
+ async write(path: string, data: FileData, options: CallOptions = {}): Promise<FileWritten> {
106
+ const upload = uploadBody(data);
107
+ try {
108
+ const raw = await this.#api.json<FileWrittenData>('PUT', this.#path, {
109
+ ...options,
110
+ query: { path },
111
+ body: upload.body,
112
+ headers: { 'content-type': 'application/octet-stream' },
113
+ });
114
+ return { object: raw.object, path: raw.path, size: raw.size, raw };
115
+ } catch (error) {
116
+ upload.stop(error);
117
+ throw error;
118
+ }
119
+ }
120
+
121
+ /** A directory's entries. */
122
+ async list(path: string, options: CallOptions = {}): Promise<FileEntry[]> {
123
+ const url = `${this.#path}/list`;
124
+ const page = await this.#api.json<ListData<FileEntryData>>('GET', url, { ...options, query: { path } });
125
+ return page.data.map(fileEntry);
126
+ }
127
+
128
+ /** What is at `path`, following symbolic links. */
129
+ async stat(path: string, options: CallOptions = {}): Promise<FileStat> {
130
+ return fileStat(await this.#api.json<FileStatData>('GET', `${this.#path}/stat`, { ...options, query: { path } }));
131
+ }
132
+
133
+ /** Deletes a file or a symbolic link. A directory is a `409 is_a_directory`: delete it with a command. */
134
+ async delete(path: string, options: CallOptions = {}): Promise<void> {
135
+ await this.#api.send('DELETE', this.#path, { ...options, query: { path } });
136
+ }
137
+
138
+ /** Makes a directory and any missing parents. An existing directory is answered as it is. */
139
+ async mkdir(path: string, options: CallOptions = {}): Promise<FileStat> {
140
+ return fileStat(await this.#api.json<FileStatData>('POST', `${this.#path}/mkdir`, { ...options, json: { path } }));
141
+ }
142
+
143
+ /** Moves or renames `from` to `to`, the new path itself. An existing `to` is a `409 path_exists` unless `overwrite`. */
144
+ async move(from: string, to: string, options: CallOptions & { overwrite?: boolean } = {}): Promise<FileStat> {
145
+ const { overwrite, signal } = options;
146
+ const json = { from, to, overwrite };
147
+ return fileStat(await this.#api.json<FileStatData>('POST', `${this.#path}/move`, { json, signal }));
148
+ }
149
+ }