@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,216 @@
1
+ import { Commands } from './commands.js';
2
+ import { KelnError } from './errors.js';
3
+ import { Files } from './files.js';
4
+ import { SandboxImages } from './images.js';
5
+ import { Terminals } from './terminals.js';
6
+ import { newIdempotencyKey, sandboxPath, sleep, untilAborted } from './util.js';
7
+ function notRunning(sandbox) {
8
+ const why = sandbox.endReason === null ? '' : ` (end_reason ${sandbox.endReason})`;
9
+ return new KelnError(`Sandbox ${sandbox.id} is ${sandbox.state}${why}, not running.`, { code: 'sandbox_not_running' });
10
+ }
11
+ /** Polls until the sandbox leaves `starting`. No deadline; the caller can cancel. */
12
+ async function whileStarting(sandbox, signal) {
13
+ let delay = 250;
14
+ while (sandbox.state === 'starting') {
15
+ await sleep(delay, signal);
16
+ delay = Math.min(delay * 2, 2000);
17
+ await sandbox.refresh({ signal });
18
+ }
19
+ }
20
+ /**
21
+ * One sandbox. Its fields are the API's, as of the last answer: `refresh()` reads them again, and every call that
22
+ * changes the sandbox updates them. `await using` deletes it on exit.
23
+ */
24
+ export class Sandbox {
25
+ id;
26
+ object;
27
+ /** New states pass through as strings. */
28
+ state;
29
+ /** The template it started from; for a sandbox started from an image, the image's template. */
30
+ template;
31
+ /** The image it started from, or `null`. */
32
+ image;
33
+ cpu;
34
+ memoryMb;
35
+ diskMb;
36
+ createdAt;
37
+ /** When it began running; billing starts here. */
38
+ startedAt;
39
+ expiresAt;
40
+ endedAt;
41
+ /** When it was paused, while it is `paused`. */
42
+ pausedAt;
43
+ /** Why a stopped sandbox stopped. */
44
+ endReason;
45
+ metadata;
46
+ network;
47
+ ports;
48
+ /** The secret a private port's requests carry as `X-Keln-Port-Token`, once the sandbox has a port. */
49
+ portToken;
50
+ /** The object as the API sent it. */
51
+ raw;
52
+ commands;
53
+ files;
54
+ terminals;
55
+ #api;
56
+ /** Made by `keln.sandboxes`. */
57
+ constructor(api, data) {
58
+ this.#api = api;
59
+ this.#apply(data);
60
+ this.commands = new Commands(api, data.id);
61
+ this.files = new Files(api, data.id);
62
+ this.terminals = new Terminals(api, data.id);
63
+ }
64
+ #apply(data) {
65
+ this.raw = data;
66
+ this.id = data.id;
67
+ this.object = data.object;
68
+ this.state = data.state;
69
+ this.template = data.template;
70
+ this.image = data.image ?? null;
71
+ this.cpu = data.cpu;
72
+ this.memoryMb = data.memory_mb;
73
+ this.diskMb = data.disk_mb;
74
+ this.createdAt = data.created_at;
75
+ this.startedAt = data.started_at ?? null;
76
+ this.expiresAt = data.expires_at;
77
+ this.endedAt = data.ended_at ?? null;
78
+ this.pausedAt = data.paused_at ?? null;
79
+ this.endReason = data.end_reason ?? null;
80
+ this.metadata = data.metadata;
81
+ this.network = data.network;
82
+ this.ports = data.ports ?? [];
83
+ this.portToken = data.port_token ?? null;
84
+ return this;
85
+ }
86
+ get #path() {
87
+ return sandboxPath(this.id);
88
+ }
89
+ /** Reads the sandbox again and updates this object. */
90
+ async refresh(options = {}) {
91
+ return this.#apply(await this.#api.json('GET', this.#path, options));
92
+ }
93
+ /** Replaces the sandbox's `network`, its `ports`, or both, while it runs. */
94
+ async update(options) {
95
+ const { signal, ...json } = options;
96
+ return this.#apply(await this.#api.json('PATCH', this.#path, { json, signal }));
97
+ }
98
+ /** Sets the expiry to now plus `seconds`, shorter or longer than before. */
99
+ async setTimeout(seconds, options = {}) {
100
+ const path = `${this.#path}/timeout`;
101
+ return this.#apply(await this.#api.json('POST', path, { ...options, json: { timeout_s: seconds } }));
102
+ }
103
+ /** Pauses the sandbox with its memory, processes and files kept. Billing stops until it is resumed. */
104
+ async pause(options = {}) {
105
+ return this.#apply(await this.#api.json('POST', `${this.#path}/pause`, options));
106
+ }
107
+ /** Runs a paused sandbox again and waits for it to run, as a create does. */
108
+ async resume(options = {}) {
109
+ const { timeoutS, signal } = options;
110
+ const json = timeoutS === undefined ? undefined : { timeout_s: timeoutS };
111
+ this.#apply(await this.#api.json('POST', `${this.#path}/resume`, { json, signal }));
112
+ await whileStarting(this, signal);
113
+ if (this.state === 'stopped' || this.state === 'paused')
114
+ throw notRunning(this);
115
+ return this;
116
+ }
117
+ /**
118
+ * Saves the sandbox's files as an image and waits until it is `ready` or `failed`, as `keln.sandboxImages.create`
119
+ * does. The sandbox keeps running.
120
+ */
121
+ async snapshot(options = {}) {
122
+ return await new SandboxImages(this.#api).create(this.id, options);
123
+ }
124
+ /** Stops the sandbox and deletes its contents; billing ends now. Stopping a stopped sandbox changes nothing. */
125
+ async delete(options = {}) {
126
+ return this.#apply(await this.#api.json('DELETE', this.#path, options));
127
+ }
128
+ async [Symbol.asyncDispose]() {
129
+ await this.delete();
130
+ }
131
+ }
132
+ /** `keln.sandboxes`. */
133
+ export class Sandboxes {
134
+ #api;
135
+ /** Made by `Keln`. */
136
+ constructor(api) {
137
+ this.#api = api;
138
+ }
139
+ /**
140
+ * Starts a sandbox and waits for it to run, with no deadline of ours. A sandbox that does not reach `running`
141
+ * throws `KelnError` with the code `sandbox_not_running`.
142
+ *
143
+ * An abort ends the call at once. The caller then has no way to reach the sandbox, so it is stopped in the
144
+ * background: the POST carries on without the signal and whatever it started is deleted, so nothing is left billing.
145
+ */
146
+ async create(options = {}) {
147
+ const { template, image, cpu, memoryMb, timeoutS, env, metadata, network, wait, idempotencyKey, signal } = options;
148
+ signal?.throwIfAborted();
149
+ const api = this.#api;
150
+ const pending = api.json('POST', '/v1/sandboxes', {
151
+ json: { template, image, cpu, memory_mb: memoryMb, timeout_s: timeoutS, env, metadata, network },
152
+ headers: { 'idempotency-key': idempotencyKey ?? newIdempotencyKey() },
153
+ });
154
+ const data = await untilAborted(pending, signal, () => {
155
+ pending.then((started) => api.send('DELETE', sandboxPath(started.id))).catch(() => { });
156
+ });
157
+ const sandbox = new Sandbox(api, data);
158
+ if (wait === false)
159
+ return sandbox;
160
+ try {
161
+ await whileStarting(sandbox, signal);
162
+ }
163
+ catch (error) {
164
+ const stop = sandbox.delete().catch(() => { });
165
+ if (!signal?.aborted)
166
+ await stop;
167
+ throw error;
168
+ }
169
+ if (sandbox.state === 'stopped')
170
+ throw notRunning(sandbox);
171
+ return sandbox;
172
+ }
173
+ async get(sandboxId, options = {}) {
174
+ return new Sandbox(this.#api, await this.#api.json('GET', sandboxPath(sandboxId), options));
175
+ }
176
+ /** Iterates the sandboxes, newest first, through every page. */
177
+ async *list(options = {}) {
178
+ const { metadata, state, limit, signal } = options;
179
+ const query = new URLSearchParams();
180
+ for (const [key, value] of Object.entries(metadata ?? {}))
181
+ query.append(`metadata[${key}]`, value);
182
+ if (state !== undefined)
183
+ query.append('state', [state].flat().join(','));
184
+ if (limit !== undefined)
185
+ query.append('limit', String(limit));
186
+ while (true) {
187
+ const page = await this.#api.json('GET', '/v1/sandboxes', { query, signal });
188
+ for (const data of page.data)
189
+ yield new Sandbox(this.#api, data);
190
+ if (!page.has_more || !page.next_cursor)
191
+ return;
192
+ query.set('after', page.next_cursor);
193
+ }
194
+ }
195
+ }
196
+ /** `keln.templates`. */
197
+ export class Templates {
198
+ #api;
199
+ /** Made by `Keln`. */
200
+ constructor(api) {
201
+ this.#api = api;
202
+ }
203
+ /** The templates a sandbox can start from, with their default sizes. */
204
+ async list(options = {}) {
205
+ const page = await this.#api.json('GET', '/v1/sandbox-templates', options);
206
+ return page.data.map((raw) => ({
207
+ object: raw.object,
208
+ name: raw.name,
209
+ cpu: raw.cpu,
210
+ memoryMb: raw.memory_mb,
211
+ diskMb: raw.disk_mb,
212
+ raw,
213
+ }));
214
+ }
215
+ }
216
+ //# sourceMappingURL=sandbox.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sandbox.js","sourceRoot":"","sources":["../src/sandbox.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AACnC,OAAO,EAAqD,aAAa,EAAE,MAAM,aAAa,CAAC;AAC/F,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAY3C,OAAO,EAAE,iBAAiB,EAAE,WAAW,EAAE,KAAK,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AA4ChF,SAAS,UAAU,CAAC,OAAgB;IAClC,MAAM,GAAG,GAAG,OAAO,CAAC,SAAS,KAAK,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,gBAAgB,OAAO,CAAC,SAAS,GAAG,CAAC;IACnF,OAAO,IAAI,SAAS,CAAC,WAAW,OAAO,CAAC,EAAE,OAAO,OAAO,CAAC,KAAK,GAAG,GAAG,gBAAgB,EAAE,EAAE,IAAI,EAAE,qBAAqB,EAAE,CAAC,CAAC;AACzH,CAAC;AAED,qFAAqF;AACrF,KAAK,UAAU,aAAa,CAAC,OAAgB,EAAE,MAA+B;IAC5E,IAAI,KAAK,GAAG,GAAG,CAAC;IAChB,OAAO,OAAO,CAAC,KAAK,KAAK,UAAU,EAAE,CAA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BAAE,MAAM,IAAI,OAAO,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;YACjE,IAAI,CAAC,IAAI,CAAC,QAAQ,IAAI,CAAC,IAAI,CAAC,WAAW;gBAAE,OAAO;YAChD,KAAK,CAAC,GAAG,CAAC,OAAO,EAAE,IAAI,CAAC,WAAW,CAAC,CAAC;QACvC,CAAC;IACH,CAAC;CACF;AAED,wBAAwB;AACxB,MAAM,OAAO,SAAS;IACX,IAAI,CAAM;IAEnB,sBAAsB;IACtB,YAAY,GAAQ;QAClB,IAAI,CAAC,IAAI,GAAG,GAAG,CAAC;IAClB,CAAC;IAED,wEAAwE;IACxE,KAAK,CAAC,IAAI,CAAC,UAAuB,EAAE;QAClC,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,IAAI,CAAC,IAAI,CAAgC,KAAK,EAAE,uBAAuB,EAAE,OAAO,CAAC,CAAC;QAC1G,OAAO,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;YAC7B,MAAM,EAAE,GAAG,CAAC,MAAM;YAClB,IAAI,EAAE,GAAG,CAAC,IAAI;YACd,GAAG,EAAE,GAAG,CAAC,GAAG;YACZ,QAAQ,EAAE,GAAG,CAAC,SAAS;YACvB,MAAM,EAAE,GAAG,CAAC,OAAO;YACnB,GAAG;SACJ,CAAC,CAAC,CAAC;IACN,CAAC;CACF"}
package/dist/sse.d.ts ADDED
@@ -0,0 +1,20 @@
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
+ /** No byte arrived for `idleTimeoutMs`. The API sends a ping while a stream is idle: this is a dead connection. */
8
+ export declare class StreamIdleError extends Error {
9
+ constructor(idleTimeoutMs: number);
10
+ }
11
+ /**
12
+ * Reads an event stream by the Server-Sent Events rules the API needs: `id`, `event`, multi-line `data`, comments
13
+ * (`: 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
14
+ * dispatched, as the rules say; a reattach with `Last-Event-ID` delivers it again. `onBytes` runs on every chunk that
15
+ * arrives, a ping included, so a caller can tell a quiet stream from a dead one.
16
+ *
17
+ * Each chunk is scanned once, so a large event (a picture as base64) takes time in proportion to its size. A CR ends
18
+ * its line at once; an LF that opens the next chunk after it is the rest of that CRLF.
19
+ */
20
+ export declare function readEventStream(body: ReadableStream<Uint8Array>, idleTimeoutMs: number, onBytes?: () => void): AsyncGenerator<ServerSentEvent>;
package/dist/sse.js ADDED
@@ -0,0 +1,119 @@
1
+ /** No byte arrived for `idleTimeoutMs`. The API sends a ping while a stream is idle: this is a dead connection. */
2
+ export class StreamIdleError extends Error {
3
+ constructor(idleTimeoutMs) {
4
+ super(`no byte arrived on the event stream for ${idleTimeoutMs} ms`);
5
+ this.name = 'StreamIdleError';
6
+ }
7
+ }
8
+ function readWithIdleTimeout(reader, idleTimeoutMs) {
9
+ if (!(idleTimeoutMs > 0))
10
+ return reader.read();
11
+ return new Promise((resolve, reject) => {
12
+ const timer = setTimeout(() => {
13
+ reject(new StreamIdleError(idleTimeoutMs));
14
+ reader.cancel().catch(() => { });
15
+ }, idleTimeoutMs);
16
+ reader.read().then((result) => {
17
+ clearTimeout(timer);
18
+ resolve(result);
19
+ }, (error) => {
20
+ clearTimeout(timer);
21
+ reject(error);
22
+ });
23
+ });
24
+ }
25
+ /**
26
+ * Reads an event stream by the Server-Sent Events rules the API needs: `id`, `event`, multi-line `data`, comments
27
+ * (`: 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
28
+ * dispatched, as the rules say; a reattach with `Last-Event-ID` delivers it again. `onBytes` runs on every chunk that
29
+ * arrives, a ping included, so a caller can tell a quiet stream from a dead one.
30
+ *
31
+ * Each chunk is scanned once, so a large event (a picture as base64) takes time in proportion to its size. A CR ends
32
+ * its line at once; an LF that opens the next chunk after it is the rest of that CRLF.
33
+ */
34
+ export async function* readEventStream(body, idleTimeoutMs, onBytes) {
35
+ const reader = body.getReader();
36
+ const decoder = new TextDecoder();
37
+ /** The start of a line that the chunks so far have not ended, in pieces, joined once when it ends. */
38
+ const pieces = [];
39
+ /** The last chunk ended with a CR, so an LF that opens the next one belongs to it. */
40
+ let afterCR = false;
41
+ let eventName = '';
42
+ let data = [];
43
+ let hasData = false;
44
+ let lastId;
45
+ let finished = false;
46
+ try {
47
+ while (true) {
48
+ const { done, value } = await readWithIdleTimeout(reader, idleTimeoutMs);
49
+ if (done) {
50
+ finished = true;
51
+ return;
52
+ }
53
+ onBytes?.();
54
+ const text = decoder.decode(value, { stream: true });
55
+ if (text === '')
56
+ continue; // the first bytes of a character that the next chunk completes
57
+ let start = afterCR && text.charCodeAt(0) === 10 ? 1 : 0;
58
+ afterCR = false;
59
+ for (let index = start; index < text.length; index++) {
60
+ const c = text.charCodeAt(index);
61
+ if (c !== 10 && c !== 13)
62
+ continue;
63
+ const end = index;
64
+ if (c === 13) {
65
+ if (index + 1 === text.length)
66
+ afterCR = true;
67
+ else if (text.charCodeAt(index + 1) === 10)
68
+ index++;
69
+ }
70
+ let line = text.slice(start, end);
71
+ if (pieces.length > 0) {
72
+ pieces.push(line);
73
+ line = pieces.join('');
74
+ pieces.length = 0;
75
+ }
76
+ start = index + 1;
77
+ if (line === '') {
78
+ if (hasData) {
79
+ yield { event: eventName === '' ? 'message' : eventName, data: data.join('\n'), id: lastId };
80
+ }
81
+ eventName = '';
82
+ data = [];
83
+ hasData = false;
84
+ continue;
85
+ }
86
+ if (line.startsWith(':'))
87
+ continue;
88
+ const colon = line.indexOf(':');
89
+ const field = colon === -1 ? line : line.slice(0, colon);
90
+ let fieldValue = colon === -1 ? '' : line.slice(colon + 1);
91
+ if (fieldValue.startsWith(' '))
92
+ fieldValue = fieldValue.slice(1);
93
+ if (field === 'event') {
94
+ eventName = fieldValue;
95
+ }
96
+ else if (field === 'data') {
97
+ data.push(fieldValue);
98
+ hasData = true;
99
+ }
100
+ else if (field === 'id' && !fieldValue.includes('\0')) {
101
+ lastId = fieldValue;
102
+ }
103
+ }
104
+ if (start < text.length)
105
+ pieces.push(text.slice(start));
106
+ }
107
+ }
108
+ finally {
109
+ if (!finished)
110
+ await reader.cancel().catch(() => { });
111
+ try {
112
+ reader.releaseLock();
113
+ }
114
+ catch {
115
+ // A read the idle timer gave up on may still be pending; the cancel above already ended the stream.
116
+ }
117
+ }
118
+ }
119
+ //# sourceMappingURL=sse.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sse.js","sourceRoot":"","sources":["../src/sse.ts"],"names":[],"mappings":"AAOA,mHAAmH;AACnH,MAAM,OAAO,eAAgB,SAAQ,KAAK;IACxC,YAAY,aAAqB;QAC/B,KAAK,CAAC,2CAA2C,aAAa,KAAK,CAAC,CAAC;QACrE,IAAI,CAAC,IAAI,GAAG,iBAAiB,CAAC;IAChC,CAAC;CACF;AAED,SAAS,mBAAmB,CAC1B,MAA+C,EAC/C,aAAqB;IAErB,IAAI,CAAC,CAAC,aAAa,GAAG,CAAC,CAAC;QAAE,OAAO,MAAM,CAAC,IAAI,EAAE,CAAC;IAC/C,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACrC,MAAM,KAAK,GAAG,UAAU,CAAC,GAAG,EAAE;YAC5B,MAAM,CAAC,IAAI,eAAe,CAAC,aAAa,CAAC,CAAC,CAAC;YAC3C,MAAM,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;QAClC,CAAC,EAAE,aAAa,CAAC,CAAC;QAClB,MAAM,CAAC,IAAI,EAAE,CAAC,IAAI,CAChB,CAAC,MAAM,EAAE,EAAE;YACT,YAAY,CAAC,KAAK,CAAC,CAAC;YACpB,OAAO,CAAC,MAAM,CAAC,CAAC;QAClB,CAAC,EACD,CAAC,KAAc,EAAE,EAAE;YACjB,YAAY,CAAC,KAAK,CAA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oG;QACtG,CAAC;IACH,CAAC;AACH,CAAC"}
@@ -0,0 +1,20 @@
1
+ /** How a stream reads its answer. The inference calls set it. */
2
+ export type StreamOptions = {
3
+ /** The call's `timeout` as a signal: when it fires, the stream throws `KelnTimeoutError`. */
4
+ timeout?: AbortSignal | undefined;
5
+ /** The call's own signal: when it aborts, the stream throws its reason. */
6
+ signal?: AbortSignal | undefined;
7
+ /** Takes the API key out of text that goes into an exception. */
8
+ redact?: ((text: string) => string) | undefined;
9
+ };
10
+ export declare class Stream<T> implements AsyncIterable<T> {
11
+ #private;
12
+ /** The API's id for the request (`x-keln-request-id`). */
13
+ readonly requestId: string | undefined;
14
+ /** Aborting it closes the stream and its connection. */
15
+ readonly controller: AbortController;
16
+ readonly response: Response;
17
+ /** Made by the inference calls. */
18
+ constructor(response: Response, controller: AbortController, operation: string, options?: StreamOptions);
19
+ [Symbol.asyncIterator](): AsyncIterator<T>;
20
+ }
@@ -0,0 +1,77 @@
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
+ export class Stream {
14
+ /** The API's id for the request (`x-keln-request-id`). */
15
+ requestId;
16
+ /** Aborting it closes the stream and its connection. */
17
+ controller;
18
+ response;
19
+ #operation;
20
+ #options;
21
+ #consumed = false;
22
+ /** Made by the inference calls. */
23
+ constructor(response, controller, operation, options = {}) {
24
+ this.response = response;
25
+ this.controller = controller;
26
+ this.requestId = response.headers.get('x-keln-request-id') ?? response.headers.get('x-request-id') ?? undefined;
27
+ this.#operation = operation;
28
+ this.#options = options;
29
+ }
30
+ async *[Symbol.asyncIterator]() {
31
+ if (this.#consumed)
32
+ throw new KelnError('A stream can be read once, and this one has been read.');
33
+ this.#consumed = true;
34
+ const { signal, timeout } = this.#options;
35
+ const redact = this.#options.redact ?? ((text) => text);
36
+ const body = this.response.body;
37
+ if (body === null)
38
+ return;
39
+ try {
40
+ for await (const sse of readEventStream(body, 0)) {
41
+ if (sse.data.startsWith('[DONE]'))
42
+ return;
43
+ let data;
44
+ try {
45
+ data = JSON.parse(sse.data);
46
+ }
47
+ catch {
48
+ throw new KelnApiError({
49
+ status: undefined,
50
+ message: `A ${this.#operation} stream event carries data that is not JSON.`,
51
+ body: redact(sse.data),
52
+ requestId: this.requestId,
53
+ });
54
+ }
55
+ if (data !== null && typeof data === 'object' && data.error) {
56
+ throw streamError(data, sse.data, this.requestId, redact);
57
+ }
58
+ yield data;
59
+ }
60
+ }
61
+ catch (error) {
62
+ if (error instanceof KelnApiError)
63
+ throw error;
64
+ if (signal?.aborted === true)
65
+ throw signal.reason;
66
+ if (timeout?.aborted === true)
67
+ throw new KelnTimeoutError(`Keln ${this.#operation} ran past its timeout.`);
68
+ if (this.controller.signal.aborted)
69
+ throw this.controller.signal.reason;
70
+ throw new KelnConnectionError(`Keln ${this.#operation} failed: the connection closed before the stream finished`, { cause: error });
71
+ }
72
+ finally {
73
+ this.controller.abort();
74
+ }
75
+ }
76
+ }
77
+ //# sourceMappingURL=streaming.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"streaming.js","sourceRoot":"","sources":["../src/streaming.ts"],"names":[],"mappings":"AAAA,yGAAyG;AACzG;;;;;;;;GAQG;AACH,OAAO,EAAE,YAAY,EAAE,mBAAmB,EAAE,SAAS,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1G,OAAO,EAAE,eAAe,EAAE,MAAM,UAAU,CAAC;AAY3C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AU,CAAC,KAAK,EAAE,CAAC;QAC1B,CAAC;IACH,CAAC;CACF"}
@@ -0,0 +1,75 @@
1
+ import type { Api } from './api.js';
2
+ import type { CallOptions, TerminalData, TerminalState } from './types.js';
3
+ export type TerminalCreateOptions = CallOptions & {
4
+ /** A shell line, run through `bash -lc`. Without `command` or `argv` the terminal runs a login shell. */
5
+ command?: string;
6
+ /** The program and its arguments, run directly. */
7
+ argv?: string[];
8
+ /** Absolute. Defaults to the user's home. */
9
+ cwd?: string;
10
+ env?: Record<string, string>;
11
+ /** Default 80. */
12
+ cols?: number;
13
+ /** Default 24. */
14
+ rows?: number;
15
+ };
16
+ /**
17
+ * An open socket to a terminal: `send` input, `resize` it, iterate its output bytes. Iterating ends when the program
18
+ * exits, with its code in `exitCode`, or after `close()`. A socket dropped before that throws `KelnConnectionError`;
19
+ * the program may still run, and `terminal.attach()` opens a new socket. An aborted signal ends it with its reason.
20
+ */
21
+ export declare class TerminalSocket implements AsyncIterable<Uint8Array> {
22
+ #private;
23
+ /** The program's exit code, once the socket has ended, if the API sent one. */
24
+ exitCode: number | undefined;
25
+ /** Every listener goes on before the socket connects: a first frame can arrive with the upgrade's answer. */
26
+ private constructor();
27
+ /** Attaches, with the retries a read gets. Used by `terminal.attach()`. */
28
+ static open(api: Api, path: string, signal: AbortSignal | undefined): Promise<TerminalSocket>;
29
+ /** Sends input to the program. */
30
+ send(data: Uint8Array | string): Promise<void>;
31
+ /** Resizes the terminal. */
32
+ resize(cols: number, rows: number): Promise<void>;
33
+ /** Closes the socket. The program keeps running; `terminal.kill()` ends it. */
34
+ close(): Promise<void>;
35
+ [Symbol.asyncIterator](): AsyncGenerator<Uint8Array>;
36
+ }
37
+ /** One terminal. Its fields are the API's, as of the last answer. */
38
+ export declare class Terminal {
39
+ #private;
40
+ id: string;
41
+ object: string;
42
+ sandboxId: string;
43
+ state: TerminalState;
44
+ cols: number;
45
+ rows: number;
46
+ exitCode: number | null;
47
+ createdAt: number;
48
+ endedAt: number | null;
49
+ /** The object as the API sent it. */
50
+ raw: TerminalData;
51
+ /** Made by `sandbox.terminals`. */
52
+ constructor(api: Api, data: TerminalData);
53
+ /**
54
+ * Opens a socket to the terminal. A terminal can be attached again after a disconnect; a socket receives the
55
+ * output written while it is attached. The signal stays with the socket: aborting it later ends the socket.
56
+ */
57
+ attach(options?: CallOptions): Promise<TerminalSocket>;
58
+ /** Reads the terminal again and updates this object. */
59
+ refresh(options?: CallOptions): Promise<this>;
60
+ /** Resizes the terminal, the same as a resize frame on a socket. */
61
+ resize(cols: number, rows: number, options?: CallOptions): Promise<this>;
62
+ /** Ends the terminal's program. Ending an exited terminal changes nothing. */
63
+ kill(options?: CallOptions): Promise<this>;
64
+ }
65
+ /** The terminals of one sandbox: `sandbox.terminals`. */
66
+ export declare class Terminals {
67
+ #private;
68
+ /** Made by `Sandbox`. */
69
+ constructor(api: Api, sandboxId: string);
70
+ /** Starts a program on a pseudo-terminal. Attach to it with `terminal.attach()`. */
71
+ create(options?: TerminalCreateOptions): Promise<Terminal>;
72
+ /** The sandbox's terminals, oldest first. */
73
+ list(options?: CallOptions): Promise<Terminal[]>;
74
+ get(terminalId: string, options?: CallOptions): Promise<Terminal>;
75
+ }