@kibotos/sdk 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,198 @@
1
- # Temporary Holding Version
1
+ # `@kibotos/sdk`
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Official zero-dependency TypeScript and JavaScript SDK for the **Kibotos** v1 API.
4
+
5
+ The HTTP client uses built-in Web APIs including `fetch`, `ReadableStream`, and `AbortController` on **Node 20+**, **Bun**, **Deno**, and **Cloudflare Workers**.
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ npm install @kibotos/sdk
11
+ # or
12
+ pnpm add @kibotos/sdk
13
+ # or
14
+ bun add @kibotos/sdk
15
+ ```
16
+
17
+ ## Quick Start
18
+
19
+ ```ts
20
+ import { Kibotos } from '@kibotos/sdk';
21
+
22
+ // Reads KIBOTOS_API_KEY and KIBOTOS_API_URL (default: https://api.kibo.to/v1)
23
+ const client = new Kibotos();
24
+
25
+ // 1. Create a workspace
26
+ const created = await client.workspaces.create({
27
+ name: 'agent-runner',
28
+ template: { id: 'python-3.12' },
29
+ resources: { vcpus: 2, memory_mib: 4096 },
30
+ timeout: { seconds: 3600, action: 'stop' },
31
+ labels: { env: 'dev' },
32
+ });
33
+
34
+ // 2. Wait until available (supports timeouts > 60s via automatic chunking)
35
+ const workspace = await client.workspaces.wait(created.id, {
36
+ status: ['available', 'failed'],
37
+ timeoutSeconds: 120,
38
+ });
39
+ console.log('Workspace ready:', workspace.id, workspace.status);
40
+
41
+ // 3. Expose a port over HTTPS
42
+ const exposure = await client.exposures.create(workspace.id, {
43
+ port: 8080,
44
+ ttl_seconds: 3600,
45
+ });
46
+ console.log('Public URL:', exposure.url);
47
+
48
+ // 4. Clean up
49
+ await client.exposures.revoke(workspace.id, exposure.id);
50
+ await client.workspaces.delete(workspace.id);
51
+ ```
52
+
53
+ ## Configuration
54
+
55
+ ```ts
56
+ import { Kibotos } from '@kibotos/sdk';
57
+
58
+ const client = new Kibotos({
59
+ apiKey: 'kb_...', // Defaults to process.env.KIBOTOS_API_KEY
60
+ baseUrl: 'https://api.kibo.to/v1', // Defaults to process.env.KIBOTOS_API_URL ?? 'https://api.kibo.to/v1'
61
+ maxRetries: 3, // Defaults to 3
62
+ timeoutMs: 30_000, // Defaults to 30000 (30s)
63
+ defaultHeaders: { 'X-App': 'my-service' },
64
+ fetch: customFetch, // Optional fetch override
65
+ });
66
+ ```
67
+
68
+ In edge runtimes without `process.env` (such as Cloudflare Workers), pass `apiKey` explicitly from your environment bindings.
69
+
70
+ ## Resources
71
+
72
+ | Namespace | Methods |
73
+ | --- | --- |
74
+ | `client.zones` | `list`, `iterate` |
75
+ | `client.templates` | `list`, `iterate`, `get`, `listRevisions`, `getRevision` |
76
+ | `client.workspaces` | `create`, `list`, `iterate`, `get`, `update`, `delete`, `start`, `stop`, `setTimeout`, `setNetwork`, `setVolumes`, `setPacks`, `getMetrics`, `attachVolume`, `detachVolume`, `wait` |
77
+ | `client.workspaces` (data plane) | `exec`, `execStream`, `listFiles`, `statFile`, `readFile`, `writeFile`, `makeDir`, `moveFile`, `deleteFile`, `connectWS`, `connectTunnel`, `connectDesktop`, `connectProxy`, `wsUrl`, `tunnelWSUrl`, `desktopVNCUrl`, `proxyUrl`, `proxyWSUrl`, `wsHeaders` |
78
+ | `client.volumes` | `create`, `list`, `iterate`, `get`, `update`, `resize`, `delete`, `wait` |
79
+ | `client.exposures` | `create`, `list`, `iterate`, `get`, `revoke` |
80
+ | `client.packs` | `list`, `get`, `getRevision` |
81
+ | `client.egresses`, `client.resolvers` | `create`, `list`, `get`, `replace` (configuration), `update` (name and labels), `delete` |
82
+
83
+ Workspace creation accepts `volumes`, Pack IDs in `packs`, and a `network` policy with `allow`, `deny`, `egresses`, and `resolvers`. Use `update(id, { resources: { vcpus, memory_mib, disk_mib } })` to resize a stopped or failed workspace. The root disk can only grow. `setVolumes` and `setPacks` take the complete list, and an empty list clears it. A workspace binds up to four Packs, and Pack changes take effect on the next start. The legacy `volume` field and single-volume methods remain available. `attachVolume` leaves only the given volume attached and `detachVolume` removes every attachment, so use `setVolumes` on multi-volume workspaces.
84
+
85
+ `setNetwork` replaces the whole policy and also accepts `drain_seconds`. The response's `network.applied` is `null` while the workspace is not running. `getMetrics(id, { start, end })` accepts RFC 3339 strings or `Date` values and returns host and guest time series.
86
+
87
+ ## Commands and Files
88
+
89
+ ```ts
90
+ const ws = client.workspaces;
91
+ const result = await ws.exec(workspaceId, { argv: ['python3', '--version'] });
92
+ console.log(result.exit_code, result.stdout);
93
+
94
+ for await (const { event, data } of ws.execStream(workspaceId, { argv: ['ls', '-l'] })) {
95
+ console.log(event, data);
96
+ }
97
+
98
+ await ws.makeDir(workspaceId, { path: '/tmp/example', mode: '0750' });
99
+ await ws.writeFile(workspaceId, '/tmp/example/hello.txt', 'hello', {
100
+ mode: '0640', createOnly: true,
101
+ });
102
+ const response = await ws.readFile(workspaceId, '/tmp/example/hello.txt', {
103
+ range: 'bytes=0-2',
104
+ });
105
+ console.log(response.status, response.headers.get('Content-Range'), await response.text());
106
+ ```
107
+
108
+ `execStream` yields `started`, `stdout`, `stderr`, `heartbeat`, `exited`, and `error` events. It decodes JSON event data when present. `exec` defaults to the command's `timeout_seconds` (30 seconds if omitted) plus 15 seconds. `execStream`, `readFile`, and `writeFile` have no default client deadline. Pass `timeoutMs` to set a per-request deadline or `signal` to cancel a request.
109
+
110
+ `readFile` returns a `Response` by default. Pass `as: 'bytes'` for a `Uint8Array` or `as: 'stream'` for its readable body. Use the response form to check `206` and `Content-Range`, or `304` when using `ifNoneMatch`. `writeFile` also accepts a `Uint8Array`, `Blob`, or `ReadableStream<Uint8Array>`. The directory and metadata methods are `listFiles`, `statFile`, `makeDir`, `moveFile`, and `deleteFile`. All seven file methods accept a workspace user override.
111
+
112
+ ## WebSocket Connections
113
+
114
+ ```ts
115
+ import { WorkspaceChannel } from '@kibotos/sdk';
116
+
117
+ const connection = client.workspaces.connectWS(workspaceId);
118
+ connection.onFrame((message) => {
119
+ if (message.type === 'binary' && message.frame.channel === WorkspaceChannel.stdout) {
120
+ console.log(message.frame.stream_id, message.frame.payload);
121
+ }
122
+ if (message.type === 'control') console.log(message.frame);
123
+ });
124
+ connection.socket.addEventListener('open', () => {
125
+ connection.open(1, 'process', { action: 'start', mode: 'pipe', argv: ['printf', 'hello'] });
126
+ });
127
+ ```
128
+
129
+ `WorkspaceSocket` supports `process`, `fs.watch`, and `tunnel` streams on one connection. Use `sendControl` for JSON controls and `sendBinary` for stream payloads. The exported `encodeBinaryFrame` and `decodeBinaryFrame` use a version byte (`0x01`), a big-endian 32-bit stream ID, and a channel byte (`0` stdin, `1` stdout, `2` stderr, `3` PTY, `4` tunnel).
130
+
131
+ `connectTunnel`, `connectDesktop`, and `connectProxy` return raw WebSockets. Use `tunnelWSUrl`, `desktopVNCUrl`, `proxyWSUrl`, `wsUrl`, and `wsHeaders` to build an upgrade for your own transport. `proxyUrl` builds the HTTP(S) URL.
132
+
133
+ Authenticated native upgrades use Node's global `WebSocket` with handshake headers. Node 20 exposes the global from 20.10 with `--experimental-websocket`. For a runtime whose global lacks handshake header support, pass a `factory` that accepts the URL, headers, and requested subprotocols.
134
+
135
+ ## Auto-Pagination & Label Filtering
136
+
137
+ Resources with an `iterate(...)` method return an `AsyncIterable<T>`. For Packs, egresses, and resolvers, pass `next_page_token` from the previous list response as `page_token`.
138
+
139
+ ```ts
140
+ for await (const ws of client.workspaces.iterate({
141
+ status: 'available',
142
+ labels: { team: 'ml', env: 'prod' }, // Serialized as label.team=ml&label.env=prod
143
+ limit: 50,
144
+ })) {
145
+ console.log(ws.id, ws.name);
146
+ }
147
+ ```
148
+
149
+ ## Retries, Idempotency & Cancellation
150
+
151
+ - **Automatic idempotency**: Control-plane `POST` mutations automatically generate a UUID v4 `Idempotency-Key` header if omitted and reuse the same key across retries. You may also pass `idempotencyKey` in `RequestOptions`. `exec`, `makeDir`, and `moveFile` never send one.
152
+ - **Retries**: Exponential backoff with jitter for `retryable: true` API errors, HTTP `429` (honoring `Retry-After` seconds or HTTP-date), `500`/`502`/`503`/`504`, and transient network failures.
153
+ - **One-shot data-plane requests**: `exec`, `execStream`, `writeFile`, `makeDir`, `moveFile`, and `deleteFile` make a single attempt.
154
+ - **Cancellation**: Pass an `AbortSignal` via `{ signal }` to HTTP methods to cancel in-flight requests, retry delays, and `wait()` loops.
155
+
156
+ ## Error Handling
157
+
158
+ All SDK errors inherit from `KibotosError`:
159
+
160
+ ```ts
161
+ import {
162
+ APIConnectionError,
163
+ AuthenticationError,
164
+ ConflictError,
165
+ KibotosAPIError,
166
+ NotFoundError,
167
+ PermissionDeniedError,
168
+ RateLimitError,
169
+ UnexpectedStatusError,
170
+ WaitTimeoutError,
171
+ } from '@kibotos/sdk';
172
+
173
+ try {
174
+ await client.workspaces.get('wks_missing');
175
+ } catch (err) {
176
+ if (err instanceof NotFoundError) {
177
+ console.error('Not found:', err.code, err.requestId);
178
+ } else if (err instanceof RateLimitError) {
179
+ console.error('Rate limited; retry after ms:', err.retryAfterMs);
180
+ } else if (err instanceof UnexpectedStatusError) {
181
+ console.error('Wait stopped on unexpected status:', err.details);
182
+ } else if (err instanceof WaitTimeoutError) {
183
+ console.error('Wait timed out:', err.details);
184
+ } else if (err instanceof KibotosAPIError) {
185
+ console.error('API error:', err.status, err.code, err.message);
186
+ } else if (err instanceof APIConnectionError) {
187
+ console.error('Connection error:', err.message);
188
+ }
189
+ }
190
+ ```
191
+
192
+ ## Documentation
193
+
194
+ Reference guides live in [`docs/`](./docs) and are published at [docs.kibo.to](https://docs.kibo.to): workspaces, volumes, exposures, exec / files / tunnels, Packs and networking, templates and zones, and errors and retries.
195
+
196
+ ## License
197
+
198
+ MIT