@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,269 @@
1
+ import { KelnApiError, KelnError, apiError } from './errors.js';
2
+ import { readEventStream } from './sse.js';
3
+ import { backoffMs, newIdempotencyKey, sandboxPath, sleep, utf8Decoder } from './util.js';
4
+ function commandBody(cmd, options) {
5
+ return {
6
+ ...(typeof cmd === 'string' ? { command: cmd } : { argv: cmd }),
7
+ cwd: options.cwd,
8
+ env: options.env,
9
+ user: options.user,
10
+ timeout_s: options.timeoutS,
11
+ stdin: options.stdin,
12
+ };
13
+ }
14
+ function parsed(data) {
15
+ try {
16
+ return JSON.parse(data);
17
+ }
18
+ catch {
19
+ return data;
20
+ }
21
+ }
22
+ /** The data of an event this SDK names. */
23
+ function objectOf(api, sse) {
24
+ const value = parsed(sse.data);
25
+ if (value !== null && typeof value === 'object')
26
+ return value;
27
+ throw new KelnApiError({
28
+ status: undefined,
29
+ message: `A \`${sse.event}\` event carries data that is not a JSON object.`,
30
+ body: api.redact(sse.data),
31
+ });
32
+ }
33
+ function eventOf(api, sse) {
34
+ const id = sse.id;
35
+ switch (sse.event) {
36
+ case 'error':
37
+ throw apiError(undefined, api.redact(sse.data));
38
+ case 'started': {
39
+ const raw = objectOf(api, sse);
40
+ return { type: 'started', id, commandId: raw.command_id, pid: raw.pid, raw };
41
+ }
42
+ case 'stdout':
43
+ case 'stderr': {
44
+ const raw = objectOf(api, sse);
45
+ // `new Uint8Array` copies: small Buffers share one pooled ArrayBuffer, which a reader of `.buffer` must not see.
46
+ const data = new Uint8Array(Buffer.from(typeof raw.data === 'string' ? raw.data : '', 'base64'));
47
+ return { type: sse.event, id, data, ts: raw.ts, raw };
48
+ }
49
+ case 'exit': {
50
+ const raw = objectOf(api, sse);
51
+ const exitCode = raw.exit_code ?? null;
52
+ const signal = raw.signal ?? null;
53
+ return { type: 'exit', id, exitCode, signal, oomKilled: raw.oom_killed === true, raw };
54
+ }
55
+ default:
56
+ return { type: sse.event, id: sse.id, raw: parsed(sse.data) }; // new types pass through
57
+ }
58
+ }
59
+ /**
60
+ * A command's events, to its `exit` event. `from` starts the command (`POST …/commands`, streamed) or attaches to one
61
+ * that already runs. When the stream drops (it ends early, breaks, or stays silent past `streamIdleTimeoutMs`) this
62
+ * reattaches with `GET …/events` and `Last-Event-ID`, so no event is lost or repeated. It reattaches by the
63
+ * `Keln-Command-Id` header when the stream dropped before `started`. A command the API has not named yet is sent again
64
+ * with the same `Idempotency-Key`, which replays it and never runs it twice.
65
+ *
66
+ * Only a stream that delivers nothing counts against `maxReattachAttempts`. A ping is a delivery, so a long silent
67
+ * command survives any number of drops. `request` retries the attach itself, and a failure it gives up on is final.
68
+ * Every `KelnError` it throws carries `commandId` once the API has named the command, which may still be running.
69
+ */
70
+ async function* follow(api, commandsPath, from, signal) {
71
+ let { commandId, lastEventId } = from;
72
+ let failures = 0;
73
+ try {
74
+ while (true) {
75
+ const response = commandId === undefined
76
+ ? await api.request('POST', commandsPath, {
77
+ json: from.body,
78
+ headers: { accept: 'text/event-stream', 'idempotency-key': from.idempotencyKey },
79
+ signal,
80
+ })
81
+ : await api.request('GET', `${commandsPath}/${encodeURIComponent(commandId)}/events`, {
82
+ headers: {
83
+ accept: 'text/event-stream',
84
+ ...(lastEventId !== undefined ? { 'last-event-id': lastEventId } : {}),
85
+ },
86
+ signal,
87
+ });
88
+ commandId ??= response.headers.get('keln-command-id') ?? undefined;
89
+ let failure = "the event stream ended before it reported the command's exit";
90
+ try {
91
+ if (response.body !== null) {
92
+ const streamed = readEventStream(response.body, api.streamIdleTimeoutMs, () => {
93
+ failures = 0;
94
+ });
95
+ for await (const sse of streamed) {
96
+ const event = eventOf(api, sse);
97
+ if (event.type === 'started')
98
+ commandId ??= event.commandId;
99
+ lastEventId = event.id ?? lastEventId;
100
+ yield event;
101
+ if (event.type === 'exit')
102
+ return;
103
+ }
104
+ }
105
+ }
106
+ catch (error) {
107
+ if (signal?.aborted)
108
+ throw signal.reason;
109
+ if (error instanceof KelnApiError)
110
+ throw error; // an `error` event: it ends the stream, the API said why
111
+ failure = error;
112
+ }
113
+ failures += 1;
114
+ if (failures > api.maxReattachAttempts) {
115
+ const which = commandId ? `command ${commandId}` : 'a command that had no id yet';
116
+ throw api.connectionError(failure, `The event stream of ${which} closed and could not be reattached`);
117
+ }
118
+ await sleep(backoffMs(failures, undefined), signal);
119
+ }
120
+ }
121
+ catch (error) {
122
+ if (error instanceof KelnError)
123
+ error.commandId ??= commandId;
124
+ throw error;
125
+ }
126
+ }
127
+ /** Reads a command's events from its first one to its exit. */
128
+ async function collect(events, commandId, options) {
129
+ const decoders = { stdout: utf8Decoder(), stderr: utf8Decoder() };
130
+ const output = { stdout: '', stderr: '' };
131
+ const notify = { stdout: options.onStdout, stderr: options.onStderr };
132
+ const add = (stream, text) => {
133
+ if (text === '')
134
+ return;
135
+ output[stream] += text;
136
+ notify[stream]?.(text);
137
+ };
138
+ let id = commandId;
139
+ let exit;
140
+ for await (const event of events) {
141
+ if (event.type === 'started')
142
+ id = event.commandId;
143
+ else if (event.type === 'stdout' || event.type === 'stderr') {
144
+ add(event.type, decoders[event.type].decode(event.data, { stream: true }));
145
+ }
146
+ else if (event.type === 'exit')
147
+ exit = event;
148
+ }
149
+ add('stdout', decoders.stdout.decode());
150
+ add('stderr', decoders.stderr.decode());
151
+ const { exitCode, signal: exitSignal, oomKilled } = exit; // `follow` ends on `exit` or throws
152
+ return { id: id, exitCode, stdout: output.stdout, stderr: output.stderr, exitSignal, oomKilled };
153
+ }
154
+ /** One command, started in the background or found by id. Its fields are the API's, as of the last answer. */
155
+ export class Command {
156
+ id;
157
+ object;
158
+ sandboxId;
159
+ state;
160
+ /** What ran (`["bash", "-lc", "<command>"]` for a shell line). */
161
+ argv;
162
+ exitCode;
163
+ /** The API's `signal`, the signal that ended the command. `signal()` is the call that sends one. */
164
+ exitSignal;
165
+ oomKilled;
166
+ /** Whether stdin is open for writing. */
167
+ stdin;
168
+ startedAt;
169
+ endedAt;
170
+ /** The object as the API sent it. */
171
+ raw;
172
+ #api;
173
+ #commandsPath;
174
+ /** Made by `sandbox.commands`. */
175
+ constructor(api, data) {
176
+ this.#api = api;
177
+ this.#commandsPath = `${sandboxPath(data.sandbox_id)}/commands`;
178
+ this.#apply(data);
179
+ }
180
+ #apply(data) {
181
+ this.raw = data;
182
+ this.id = data.id;
183
+ this.object = data.object;
184
+ this.sandboxId = data.sandbox_id;
185
+ this.state = data.state;
186
+ this.argv = data.argv;
187
+ this.exitCode = data.exit_code ?? null;
188
+ this.exitSignal = data.signal ?? null;
189
+ this.oomKilled = data.oom_killed ?? false;
190
+ this.stdin = data.stdin;
191
+ this.startedAt = data.started_at;
192
+ this.endedAt = data.ended_at ?? null;
193
+ return this;
194
+ }
195
+ get #path() {
196
+ return `${this.#commandsPath}/${encodeURIComponent(this.id)}`;
197
+ }
198
+ /** Waits for the exit and returns the command's whole output, from its first event. Aborting leaves it running. */
199
+ async wait(options = {}) {
200
+ return await collect(this.events({ signal: options.signal }), this.id, options);
201
+ }
202
+ /** The command's events, from the start or after `lastEventId`, to its `exit` event. It reattaches by itself. */
203
+ events(options = {}) {
204
+ return follow(this.#api, this.#commandsPath, { commandId: this.id, lastEventId: options.lastEventId }, options.signal);
205
+ }
206
+ /** Reads the command again and updates this object. */
207
+ async refresh(options = {}) {
208
+ return this.#apply(await this.#api.json('GET', this.#path, options));
209
+ }
210
+ /** Sends SIGKILL. Killing an exited command changes nothing. */
211
+ async kill(options = {}) {
212
+ return this.#apply(await this.#api.json('DELETE', this.#path, options));
213
+ }
214
+ /** Sends a signal, by name (`SIGTERM`, `TERM`) or number (15). */
215
+ async signal(signal, options = {}) {
216
+ const path = `${this.#path}/signal`;
217
+ return this.#apply(await this.#api.json('POST', path, { ...options, json: { signal } }));
218
+ }
219
+ /** Writes to the command's stdin, which needs `stdin: true` at the start. */
220
+ async write(data, options = {}) {
221
+ await this.#api.send('POST', `${this.#path}/stdin`, {
222
+ ...options,
223
+ body: typeof data === 'string' ? new TextEncoder().encode(data) : data,
224
+ headers: { 'content-type': 'application/octet-stream' },
225
+ });
226
+ }
227
+ /** Sends end-of-file. Closing a closed stdin changes nothing. */
228
+ async closeStdin(options = {}) {
229
+ await this.#api.send('POST', `${this.#path}/stdin/close`, options);
230
+ }
231
+ }
232
+ /** The commands of one sandbox: `sandbox.commands`. */
233
+ export class Commands {
234
+ #api;
235
+ #path;
236
+ /** Made by `Sandbox`. */
237
+ constructor(api, sandboxId) {
238
+ this.#api = api;
239
+ this.#path = `${sandboxPath(sandboxId)}/commands`;
240
+ }
241
+ /** Runs a command, waits for its exit and returns its result. Aborting stops the waiting, not the command. */
242
+ async run(cmd, options = {}) {
243
+ return await collect(this.stream(cmd, options), undefined, options);
244
+ }
245
+ /** Runs a command and iterates its events: `started`, `stdout`, `stderr`, `exit`. It reattaches by itself. */
246
+ stream(cmd, options = {}) {
247
+ const idempotencyKey = options.idempotencyKey ?? newIdempotencyKey();
248
+ return follow(this.#api, this.#path, { body: commandBody(cmd, options), idempotencyKey }, options.signal);
249
+ }
250
+ /** Starts a command in the background and returns it at once. */
251
+ async start(cmd, options = {}) {
252
+ const data = await this.#api.json('POST', this.#path, {
253
+ json: { ...commandBody(cmd, options), background: true },
254
+ headers: { 'idempotency-key': options.idempotencyKey ?? newIdempotencyKey() },
255
+ signal: options.signal,
256
+ });
257
+ return new Command(this.#api, data);
258
+ }
259
+ async get(commandId, options = {}) {
260
+ const path = `${this.#path}/${encodeURIComponent(commandId)}`;
261
+ return new Command(this.#api, await this.#api.json('GET', path, options));
262
+ }
263
+ /** The sandbox's commands, running and exited, newest first. */
264
+ async list(options = {}) {
265
+ const page = await this.#api.json('GET', this.#path, options);
266
+ return page.data.map((data) => new Command(this.#api, data));
267
+ }
268
+ }
269
+ //# sourceMappingURL=commands.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"commands.js","sourceRoot":"","sources":["../src/commands.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAChE,OAAO,EAAE,eAAe,EAAwB,MAAM,UAAU,CAAC;AASjE,OAAO,EAAE,SAAS,EAAE,iBAAiB,EAAE,WAAW,EAAE,KAAK,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AA6B1F,SAAS,WAAW,CAAC,GAAgB,EAAE,OAAuB;IAC5D,OAAO;QACL,GAAG,CAAC,OAAO,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,GAAG,EAAE,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC;QAC/D,GAAG,EAAE,OAAO,CAAC,GAAG;QAChB,GAAG,EAAE,OAAO,CAAC,GAAG;QAChB,IAAI,EAAE,OAAO,CAAC,IAAI;QAClB,SAAS,EAAE,OAAO,CAAC,QAAQ;QAC3B,KAAK,EAAE,OAAO,CAAC,KAAK;KACrB,CAAC;AACJ,CAAC;AAED,SAAS,MAAM,CAAC,IAAY;I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I,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,OAAO,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC;IAC/D,CAAC;CACF"}
@@ -0,0 +1,93 @@
1
+ /** Everything this SDK raises, except the reason of an aborted `AbortSignal`. */
2
+ export declare class KelnError extends Error {
3
+ /** The specific cause. `code` is the field to branch on; messages are for people. */
4
+ readonly code: string | undefined;
5
+ /**
6
+ * The command a failure happened to, once the API has named it. That command may still be running:
7
+ * `sandbox.commands.get(commandId)` reaches it again. `undefined` for a failure that is not a command's.
8
+ */
9
+ commandId: string | undefined;
10
+ constructor(message: string, options?: {
11
+ code?: string | undefined;
12
+ cause?: unknown;
13
+ commandId?: string | undefined;
14
+ });
15
+ }
16
+ /**
17
+ * The API answered with an error: a non-2xx status, or an error inside a stream (an `error` event on a command's
18
+ * stream, or a chunk carrying `error`, such as Keln's `stream_interrupted`). A non-2xx answer throws the subclass named
19
+ * for its status (`RateLimitError` for a 429).
20
+ */
21
+ export declare class KelnApiError extends KelnError {
22
+ /** The HTTP status; `undefined` for an error inside a stream. */
23
+ readonly status: number | undefined;
24
+ /** The API's `error.type`, the class, such as `not_found_error`. */
25
+ readonly type: string | undefined;
26
+ /** The request field at fault, when the API names one. */
27
+ readonly param: string | undefined;
28
+ /** Seconds from `Retry-After`, when the API sent it. */
29
+ readonly retryAfter: number | undefined;
30
+ /** The complete response body (or the event's data), as received. */
31
+ readonly body: string;
32
+ /** The API's id for the request (`x-keln-request-id`), when it sent one: quote it to support. */
33
+ readonly requestId: string | undefined;
34
+ /** The answer's headers, for an HTTP error. */
35
+ readonly headers: Headers | undefined;
36
+ constructor(fields: {
37
+ status: number | undefined;
38
+ code?: string | undefined;
39
+ type?: string | undefined;
40
+ param?: string | undefined;
41
+ message: string;
42
+ retryAfter?: number | undefined;
43
+ body: string;
44
+ requestId?: string | undefined;
45
+ headers?: Headers | undefined;
46
+ });
47
+ }
48
+ /** 400. */
49
+ export declare class BadRequestError extends KelnApiError {
50
+ }
51
+ /** 401. */
52
+ export declare class AuthenticationError extends KelnApiError {
53
+ }
54
+ /** 403. */
55
+ export declare class PermissionDeniedError extends KelnApiError {
56
+ }
57
+ /** 404. */
58
+ export declare class NotFoundError extends KelnApiError {
59
+ }
60
+ /** 409. */
61
+ export declare class ConflictError extends KelnApiError {
62
+ }
63
+ /** 422. */
64
+ export declare class UnprocessableEntityError extends KelnApiError {
65
+ }
66
+ /** 429. */
67
+ export declare class RateLimitError extends KelnApiError {
68
+ }
69
+ /** Any 5xx. */
70
+ export declare class InternalServerError extends KelnApiError {
71
+ }
72
+ /** The API could not be reached, or its answer could not be read to the end. */
73
+ export declare class KelnConnectionError extends KelnError {
74
+ }
75
+ /** A call ran past its `timeout`. */
76
+ export declare class KelnTimeoutError extends KelnError {
77
+ }
78
+ /** The API's id for a request, from its answer's headers: `x-keln-request-id`, else `x-request-id`. */
79
+ export declare function requestIdOf(headers: Headers | undefined): string | undefined;
80
+ /**
81
+ * The error for an HTTP answer (`status`), or for an `error` event, which has no status. A body without the API's
82
+ * error shape (a proxy in between, say) gives the message its start and `body` all of it.
83
+ */
84
+ export declare function apiError(status: number | undefined, text: string, retryAfterHeader?: string | null, headers?: Headers): KelnApiError;
85
+ /**
86
+ * The error a streamed answer ends with after its 200: a chunk carrying `error`, such as Keln's `stream_interrupted`.
87
+ * `redact` takes the API key out of every text the error keeps.
88
+ */
89
+ export declare function streamError(data: Record<string, unknown>, raw: string, requestId: string | undefined, redact: (text: string) => string): KelnApiError;
90
+ /** Whether an error is a `409 idempotency_key_in_use`: the first request with that key has not finished yet. */
91
+ export declare function isKeyInUse(error: unknown): boolean;
92
+ /** What a safe call may try again: transport failures, 429, 502, 503, and a key still in use. */
93
+ export declare function isRetryable(error: unknown): boolean;
package/dist/errors.js ADDED
@@ -0,0 +1,173 @@
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
+ code;
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;
11
+ constructor(message, options = {}) {
12
+ super(message, options.cause === undefined ? undefined : { cause: options.cause });
13
+ this.name = new.target.name;
14
+ this.code = options.code;
15
+ this.commandId = options.commandId;
16
+ }
17
+ }
18
+ /**
19
+ * The API answered with an error: a non-2xx status, or an error inside a stream (an `error` event on a command's
20
+ * stream, or a chunk carrying `error`, such as Keln's `stream_interrupted`). A non-2xx answer throws the subclass named
21
+ * for its status (`RateLimitError` for a 429).
22
+ */
23
+ export class KelnApiError extends KelnError {
24
+ /** The HTTP status; `undefined` for an error inside a stream. */
25
+ status;
26
+ /** The API's `error.type`, the class, such as `not_found_error`. */
27
+ type;
28
+ /** The request field at fault, when the API names one. */
29
+ param;
30
+ /** Seconds from `Retry-After`, when the API sent it. */
31
+ retryAfter;
32
+ /** The complete response body (or the event's data), as received. */
33
+ body;
34
+ /** The API's id for the request (`x-keln-request-id`), when it sent one: quote it to support. */
35
+ requestId;
36
+ /** The answer's headers, for an HTTP error. */
37
+ headers;
38
+ constructor(fields) {
39
+ super(fields.message, { code: fields.code });
40
+ this.status = fields.status;
41
+ this.type = fields.type;
42
+ this.param = fields.param;
43
+ this.retryAfter = fields.retryAfter;
44
+ this.body = fields.body;
45
+ this.requestId = fields.requestId;
46
+ this.headers = fields.headers;
47
+ }
48
+ }
49
+ // One class per status, so a caller can branch on `instanceof RateLimitError`.
50
+ /** 400. */
51
+ export class BadRequestError extends KelnApiError {
52
+ }
53
+ /** 401. */
54
+ export class AuthenticationError extends KelnApiError {
55
+ }
56
+ /** 403. */
57
+ export class PermissionDeniedError extends KelnApiError {
58
+ }
59
+ /** 404. */
60
+ export class NotFoundError extends KelnApiError {
61
+ }
62
+ /** 409. */
63
+ export class ConflictError extends KelnApiError {
64
+ }
65
+ /** 422. */
66
+ export class UnprocessableEntityError extends KelnApiError {
67
+ }
68
+ /** 429. */
69
+ export class RateLimitError extends KelnApiError {
70
+ }
71
+ /** Any 5xx. */
72
+ export class InternalServerError extends KelnApiError {
73
+ }
74
+ function errorClass(status) {
75
+ if (status === undefined)
76
+ return KelnApiError;
77
+ if (status === 400)
78
+ return BadRequestError;
79
+ if (status === 401)
80
+ return AuthenticationError;
81
+ if (status === 403)
82
+ return PermissionDeniedError;
83
+ if (status === 404)
84
+ return NotFoundError;
85
+ if (status === 409)
86
+ return ConflictError;
87
+ if (status === 422)
88
+ return UnprocessableEntityError;
89
+ if (status === 429)
90
+ return RateLimitError;
91
+ if (status >= 500)
92
+ return InternalServerError;
93
+ return KelnApiError;
94
+ }
95
+ /** The API could not be reached, or its answer could not be read to the end. */
96
+ export class KelnConnectionError extends KelnError {
97
+ }
98
+ /** A call ran past its `timeout`. */
99
+ export class KelnTimeoutError extends KelnError {
100
+ }
101
+ function field(error, name) {
102
+ const value = error?.[name];
103
+ return typeof value === 'string' ? value : undefined;
104
+ }
105
+ /** The `error` object of a body, or `undefined` when it does not have the API's error shape. */
106
+ function errorObject(text) {
107
+ try {
108
+ const error = JSON.parse(text)?.error;
109
+ return error !== null && typeof error === 'object' ? error : undefined;
110
+ }
111
+ catch {
112
+ return undefined;
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) {
117
+ return headers?.get('x-keln-request-id') ?? headers?.get('x-request-id') ?? undefined;
118
+ }
119
+ /**
120
+ * The error for an HTTP answer (`status`), or for an `error` event, which has no status. A body without the API's
121
+ * error shape (a proxy in between, say) gives the message its start and `body` all of it.
122
+ */
123
+ export function apiError(status, text, retryAfterHeader, headers) {
124
+ const error = errorObject(text);
125
+ const seconds = retryAfterHeader ? Number(retryAfterHeader) : Number.NaN;
126
+ const ErrorClass = errorClass(status);
127
+ return new ErrorClass({
128
+ status,
129
+ code: field(error, 'code'),
130
+ type: field(error, 'type'),
131
+ param: field(error, 'param'),
132
+ message: field(error, 'message') ??
133
+ (text.trim().slice(0, 2000) ||
134
+ (typeof status === 'number' ? `The response (${status}) has an empty body.` : 'The error event has an empty body.')),
135
+ retryAfter: Number.isFinite(seconds) ? seconds : undefined,
136
+ body: text,
137
+ requestId: requestIdOf(headers),
138
+ headers,
139
+ });
140
+ }
141
+ /**
142
+ * The error a streamed answer ends with after its 200: a chunk carrying `error`, such as Keln's `stream_interrupted`.
143
+ * `redact` takes the API key out of every text the error keeps.
144
+ */
145
+ export function streamError(data, raw, requestId, redact) {
146
+ const error = data.error !== null && typeof data.error === 'object' ? data.error : undefined;
147
+ const text = (name) => {
148
+ const value = field(error, name);
149
+ return value === undefined ? undefined : redact(value);
150
+ };
151
+ return new KelnApiError({
152
+ status: undefined,
153
+ code: text('code'),
154
+ type: text('type'),
155
+ param: text('param'),
156
+ message: text('message') || 'The stream ended with an error.',
157
+ body: redact(raw),
158
+ requestId,
159
+ });
160
+ }
161
+ /** Whether an error is a `409 idempotency_key_in_use`: the first request with that key has not finished yet. */
162
+ export function isKeyInUse(error) {
163
+ return error instanceof KelnApiError && error.status === 409 && error.code === 'idempotency_key_in_use';
164
+ }
165
+ /** What a safe call may try again: transport failures, 429, 502, 503, and a key still in use. */
166
+ export function isRetryable(error) {
167
+ if (error instanceof KelnConnectionError)
168
+ return true;
169
+ if (!(error instanceof KelnApiError))
170
+ return false;
171
+ return error.status === 429 || error.status === 502 || error.status === 503 || isKeyInUse(error);
172
+ }
173
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA,yGAAyG;AACzG,iFAAiF;AACjF,MAAM,OAAO,SAAU,SAAQ,KAAK;IAClC,qFAAqF;IAC5E,IAAI,CAAqB;IACl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Ac;IACvC,OAAO,KAAK,YAAY,YAAY,IAAI,KAAK,CAAC,MAAM,KAAK,GAAG,IAAI,KAAK,CAAC,IAAI,KAAK,wBAAwB,CAAC;AAC1G,CAAC;AAED,iGAAiG;AACjG,MAAM,UAAU,WAAW,CAAC,KAAc;IACxC,IAAI,KAAK,YAAY,mBAAmB;QAAE,OAAO,IAAI,CAAC;IACtD,IAAI,CAAC,CAAC,KAAK,YAAY,YAAY,CAAC;QAAE,OAAO,KAAK,CAAC;IACnD,OAAO,KAAK,CAAC,MAAM,KAAK,GAAG,IAAI,KAAK,CAAC,MAAM,KAAK,GAAG,IAAI,KAAK,CAAC,MAAM,KAAK,GAAG,IAAI,UAAU,CAAC,KAAK,CAAC,CAAC;AACnG,CAAC"}
@@ -0,0 +1,33 @@
1
+ import type { Api } from './api.js';
2
+ import type { CallOptions, FileEntry, FileStat, FileWritten } from './types.js';
3
+ /** What `files.write` takes: bytes, text (sent as UTF-8), or a stream of any size, which a Node stream also is. */
4
+ export type FileData = Uint8Array | string | ReadableStream<Uint8Array> | AsyncIterable<Uint8Array>;
5
+ /** The files of one sandbox: `sandbox.files`. Paths are absolute. */
6
+ export declare class Files {
7
+ #private;
8
+ /** Made by `Sandbox`. */
9
+ constructor(api: Api, sandboxId: string);
10
+ /** The file's bytes. */
11
+ read(path: string, options?: CallOptions): Promise<Uint8Array>;
12
+ /** The file, decoded as UTF-8. */
13
+ readText(path: string, options?: CallOptions): Promise<string>;
14
+ /** Iterates the chunks of a large file as they arrive. */
15
+ stream(path: string, options?: CallOptions): AsyncGenerator<Uint8Array>;
16
+ /**
17
+ * Writes a file, replacing one that exists. `data` is sent as it comes, with no limit on its size. A write that
18
+ * fails, before or during the upload, cancels a stream `data`, so a file it reads from closes.
19
+ */
20
+ write(path: string, data: FileData, options?: CallOptions): Promise<FileWritten>;
21
+ /** A directory's entries. */
22
+ list(path: string, options?: CallOptions): Promise<FileEntry[]>;
23
+ /** What is at `path`, following symbolic links. */
24
+ stat(path: string, options?: CallOptions): Promise<FileStat>;
25
+ /** Deletes a file or a symbolic link. A directory is a `409 is_a_directory`: delete it with a command. */
26
+ delete(path: string, options?: CallOptions): Promise<void>;
27
+ /** Makes a directory and any missing parents. An existing directory is answered as it is. */
28
+ mkdir(path: string, options?: CallOptions): Promise<FileStat>;
29
+ /** Moves or renames `from` to `to`, the new path itself. An existing `to` is a `409 path_exists` unless `overwrite`. */
30
+ move(from: string, to: string, options?: CallOptions & {
31
+ overwrite?: boolean;
32
+ }): Promise<FileStat>;
33
+ }