@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
package/src/images.ts ADDED
@@ -0,0 +1,174 @@
1
+ import type { Api } from './api.js';
2
+ import type { CallOptions, SandboxImageData, SandboxImageError, SandboxImageListData, SandboxImageState } from './types.js';
3
+ import { imagePath, newIdempotencyKey, sandboxPath, sleep, untilAborted } from './util.js';
4
+
5
+ export type SandboxImageCreateOptions = CallOptions & {
6
+ /** Your labels, returned as given. */
7
+ metadata?: Record<string, string>;
8
+ /** `false` returns at once, with the image still `creating`. Default `true`: waits until it is `ready` or `failed`. */
9
+ wait?: boolean;
10
+ /** The `Idempotency-Key`. Defaults to a fresh one per call. A retry with it never saves a second image. */
11
+ idempotencyKey?: string;
12
+ };
13
+
14
+ export type SandboxImageListOptions = CallOptions & {
15
+ /** Only images in these states. Without it, the API lists creating, ready and failed ones. */
16
+ state?: SandboxImageState | SandboxImageState[];
17
+ /** Images per page, up to 100. The iteration goes through every page either way. */
18
+ limit?: number;
19
+ };
20
+
21
+ /** Polls until the image leaves `creating`. No deadline; the caller can cancel. */
22
+ async function whileCreating(image: SandboxImage, signal: AbortSignal | undefined): Promise<void> {
23
+ let delay = 250;
24
+ while (image.state === 'creating') {
25
+ await sleep(delay, signal);
26
+ delay = Math.min(delay * 2, 2000);
27
+ await image.refresh({ signal });
28
+ }
29
+ }
30
+
31
+ /**
32
+ * One image: a sandbox's files, saved so new sandboxes start from them (`keln.sandboxes.create({ image: image.id })`).
33
+ * Its fields are the API's, as of the last answer: `refresh()` reads them again, and every call that changes the image
34
+ * updates them.
35
+ */
36
+ export class SandboxImage {
37
+ id!: string;
38
+ object!: string;
39
+ /** New states pass through as strings. */
40
+ state!: SandboxImageState;
41
+ /** The sandbox it was saved from. */
42
+ sandboxId!: string;
43
+ /** The template that sandbox started from (through any images in between). */
44
+ template!: string;
45
+ /** The default vCPUs of a sandbox started from it (the saved sandbox's). */
46
+ cpu!: number;
47
+ memoryMb!: number;
48
+ diskMb!: number;
49
+ /** Its stored size, which storage is billed on; `null` until `ready`. */
50
+ sizeBytes!: number | null;
51
+ createdAt!: number;
52
+ readyAt!: number | null;
53
+ /** Why a `failed` image failed. */
54
+ error!: SandboxImageError | null;
55
+ metadata!: Record<string, string>;
56
+ /** The object as the API sent it. */
57
+ raw!: SandboxImageData;
58
+ readonly #api: Api;
59
+
60
+ /** Made by `keln.sandboxImages` and `sandbox.snapshot()`. */
61
+ constructor(api: Api, data: SandboxImageData) {
62
+ this.#api = api;
63
+ this.#apply(data);
64
+ }
65
+
66
+ #apply(data: SandboxImageData): this {
67
+ this.raw = data;
68
+ this.id = data.id;
69
+ this.object = data.object;
70
+ this.state = data.state;
71
+ this.sandboxId = data.sandbox_id;
72
+ this.template = data.template;
73
+ this.cpu = data.cpu;
74
+ this.memoryMb = data.memory_mb;
75
+ this.diskMb = data.disk_mb;
76
+ this.sizeBytes = data.size_bytes ?? null;
77
+ this.createdAt = data.created_at;
78
+ this.readyAt = data.ready_at ?? null;
79
+ this.error = data.error ?? null;
80
+ this.metadata = data.metadata;
81
+ return this;
82
+ }
83
+
84
+ get #path(): string {
85
+ return imagePath(this.id);
86
+ }
87
+
88
+ /** Reads the image again and updates this object. */
89
+ async refresh(options: CallOptions = {}): Promise<this> {
90
+ return this.#apply(await this.#api.json<SandboxImageData>('GET', this.#path, options));
91
+ }
92
+
93
+ /**
94
+ * Waits until the image leaves `creating`: `ready`, or `failed` with `error` saying why. No deadline of ours, and a
95
+ * failed image is a result, not an exception. Aborting stops the waiting, not the save.
96
+ */
97
+ async wait(options: CallOptions = {}): Promise<this> {
98
+ options.signal?.throwIfAborted();
99
+ await whileCreating(this, options.signal);
100
+ return this;
101
+ }
102
+
103
+ /** Deletes the image; its storage billing ends now. Sandboxes started from it keep running. */
104
+ async delete(options: CallOptions = {}): Promise<this> {
105
+ return this.#apply(await this.#api.json<SandboxImageData>('DELETE', this.#path, options));
106
+ }
107
+ }
108
+
109
+ /** `keln.sandboxImages`. */
110
+ export class SandboxImages {
111
+ readonly #api: Api;
112
+
113
+ /** Made by `Keln`. */
114
+ constructor(api: Api) {
115
+ this.#api = api;
116
+ }
117
+
118
+ /**
119
+ * Saves a running sandbox's files (its whole disk, not its memory or processes) as an image, and waits until it is
120
+ * `ready` or `failed`, with no deadline of ours. A failed image is returned, with `error` saying why. The sandbox keeps
121
+ * running. Environment variables set through the API are not saved; files are.
122
+ *
123
+ * An abort ends the call at once. The caller then has no handle on the image, so it is deleted in the background: the
124
+ * POST carries on without the signal and whatever it saved is deleted, so nothing is left billing.
125
+ */
126
+ async create(sandboxId: string, options: SandboxImageCreateOptions = {}): Promise<SandboxImage> {
127
+ const { metadata, wait, idempotencyKey, signal } = options;
128
+ signal?.throwIfAborted();
129
+ const api = this.#api;
130
+ const pending = api.json<SandboxImageData>('POST', `${sandboxPath(sandboxId)}/snapshot`, {
131
+ json: { metadata },
132
+ headers: { 'idempotency-key': idempotencyKey ?? newIdempotencyKey() },
133
+ });
134
+ const data = await untilAborted(pending, signal, () => {
135
+ pending.then((saved) => api.send('DELETE', imagePath(saved.id))).catch(() => {});
136
+ });
137
+ const image = new SandboxImage(api, data);
138
+ if (wait === false) return image;
139
+ try {
140
+ await whileCreating(image, signal);
141
+ } catch (error) {
142
+ const remove = image.delete().catch(() => {});
143
+ if (!signal?.aborted) await remove;
144
+ throw error;
145
+ }
146
+ return image;
147
+ }
148
+
149
+ async get(imageId: string, options: CallOptions = {}): Promise<SandboxImage> {
150
+ return new SandboxImage(this.#api, await this.#api.json<SandboxImageData>('GET', imagePath(imageId), options));
151
+ }
152
+
153
+ /** Iterates the images, newest first, through every page. */
154
+ async *list(options: SandboxImageListOptions = {}): AsyncGenerator<SandboxImage> {
155
+ const { state, limit, signal } = options;
156
+ const query = new URLSearchParams();
157
+ if (state !== undefined) query.append('state', [state].flat().join(','));
158
+ if (limit !== undefined) query.append('limit', String(limit));
159
+ while (true) {
160
+ const page = await this.#api.json<SandboxImageListData>('GET', '/v1/images', { query, signal });
161
+ for (const data of page.data) yield new SandboxImage(this.#api, data);
162
+ if (!page.has_more || !page.next_cursor) return;
163
+ query.set('after', page.next_cursor);
164
+ }
165
+ }
166
+
167
+ /**
168
+ * Deletes an image; its storage billing ends now. Sandboxes started from it keep running. It answers the image
169
+ * `deleted`, and after that the image is a `404 image_not_found`.
170
+ */
171
+ async delete(imageId: string, options: CallOptions = {}): Promise<SandboxImage> {
172
+ return new SandboxImage(this.#api, await this.#api.json<SandboxImageData>('DELETE', imagePath(imageId), options));
173
+ }
174
+ }
package/src/index.ts ADDED
@@ -0,0 +1,114 @@
1
+ export type { KelnOptions } from './api.js';
2
+ export { Keln } from './client.js';
3
+ export { Command, Commands } from './commands.js';
4
+ export type { CommandLine, CommandOptions, OutputOptions, RunOptions } from './commands.js';
5
+ export {
6
+ AuthenticationError,
7
+ BadRequestError,
8
+ ConflictError,
9
+ InternalServerError,
10
+ KelnApiError,
11
+ KelnConnectionError,
12
+ KelnError,
13
+ KelnTimeoutError,
14
+ NotFoundError,
15
+ PermissionDeniedError,
16
+ RateLimitError,
17
+ UnprocessableEntityError,
18
+ } from './errors.js';
19
+ export { ApiPromise } from './api-promise.js';
20
+ export {
21
+ Audio,
22
+ Chat,
23
+ Completions,
24
+ Decisions,
25
+ Embeddings,
26
+ Images,
27
+ ModelListPromise,
28
+ Models,
29
+ Rerank,
30
+ Responses,
31
+ Speech,
32
+ Transcriptions,
33
+ } from './inference.js';
34
+ export { toFile } from './uploads.js';
35
+ export type { ToFileInput, Uploadable } from './uploads.js';
36
+ export type {
37
+ ImageEditParams,
38
+ ImageGenerateParams,
39
+ ImageInput,
40
+ ImagesResponse,
41
+ ImageStreamEvent,
42
+ ImageUsage,
43
+ AudioResponseFormat,
44
+ SpeechAudio,
45
+ SpeechCreateParams,
46
+ SpeechTurn,
47
+ SpeechUsage,
48
+ Transcription,
49
+ TranscriptionCreateParams,
50
+ TranscriptionDiarized,
51
+ TranscriptionUsage,
52
+ TranscriptionVerbose,
53
+ ChatCompletion,
54
+ ChatCompletionChunk,
55
+ ChatCompletionCreateParams,
56
+ ChatMessage,
57
+ ChatWebSearchOptions,
58
+ CodeExecutionOptions,
59
+ CreateEmbeddingResponse,
60
+ DecisionCreateParams,
61
+ DecisionResponse,
62
+ EmbeddingCreateParams,
63
+ InferenceCallOptions,
64
+ Model,
65
+ ModelList,
66
+ ReasoningEffort,
67
+ RerankCreateParams,
68
+ RerankResponse,
69
+ Response,
70
+ ResponseCreateParams,
71
+ ResponseStreamEvent,
72
+ ResponseUsage,
73
+ ServiceTier,
74
+ Usage,
75
+ } from './inference.js';
76
+ export { Stream } from './streaming.js';
77
+ export { Files } from './files.js';
78
+ export type { FileData } from './files.js';
79
+ export { SandboxImage, SandboxImages } from './images.js';
80
+ export type { SandboxImageCreateOptions, SandboxImageListOptions } from './images.js';
81
+ export { Sandbox, Sandboxes, Templates } from './sandbox.js';
82
+ export type { SandboxCreateOptions, SandboxListOptions, SandboxUpdateOptions } from './sandbox.js';
83
+ export { Terminal, Terminals, TerminalSocket } from './terminals.js';
84
+ export type { TerminalCreateOptions } from './terminals.js';
85
+ export type {
86
+ CallOptions,
87
+ CommandData,
88
+ CommandEvent,
89
+ CommandResult,
90
+ CommandState,
91
+ ExitEvent,
92
+ FileEntry,
93
+ FileEntryData,
94
+ FileStat,
95
+ FileStatData,
96
+ FileWritten,
97
+ FileWrittenData,
98
+ Network,
99
+ OutputEvent,
100
+ Port,
101
+ SandboxData,
102
+ SandboxImageData,
103
+ SandboxImageError,
104
+ SandboxImageState,
105
+ SandboxState,
106
+ SandboxTemplate,
107
+ SandboxTemplateData,
108
+ StartedEvent,
109
+ TerminalData,
110
+ TerminalState,
111
+ } from './types.js';
112
+ export { VERSION } from './util.js';
113
+ export { Web } from './web.js';
114
+ export type { WebFetchOptions, WebFetchResult, WebResult, WebSearchOptions, WebSearchResult, WebUsage } from './web.js';