@sistemo/sdk 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.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,69 @@
1
+ # @sistemo/sdk (JavaScript / TypeScript)
2
+
3
+ Run AI agents and untrusted code in **real isolated Firecracker microVMs** — self-host for free or use the cloud.
4
+
5
+ ```bash
6
+ npm install @sistemo/sdk
7
+ ```
8
+
9
+ Requires Node 18+ (uses the global `fetch`). Zero runtime dependencies.
10
+
11
+ ## Quickstart (< 10 lines)
12
+
13
+ ```ts
14
+ import { Sandbox } from "@sistemo/sdk";
15
+
16
+ const sb = await Sandbox.create(); // reads SISTEMO_API_KEY
17
+ const res = await sb.run("node -e 'console.log(2 + 2)'");
18
+ console.log(res.stdout, res.exitCode); // "4\n" 0
19
+ await sb.close();
20
+ ```
21
+
22
+ Get an API key from the dashboard (**Dashboard → API Keys**), then:
23
+
24
+ ```bash
25
+ export SISTEMO_API_KEY=sk_live_xxxxxxxx
26
+ ```
27
+
28
+ ## Configuration
29
+
30
+ | | |
31
+ |---|---|
32
+ | `SISTEMO_API_KEY` | your key (`sk_live_…`). Required. |
33
+ | `SISTEMO_BASE_URL` | override the API URL (default `https://api.sistemo.io`). |
34
+
35
+ Or pass them explicitly: `Sandbox.create({ apiKey: "sk_live_…", baseUrl: "https://…" })`.
36
+
37
+ ## API
38
+
39
+ ```ts
40
+ const sb = await Sandbox.create({ vcpus: 1, memoryMb: 1024, stack: "base" });
41
+ const res = await sb.run("echo hi && uname -a", 30); // -> { exitCode, stdout, stderr }
42
+ await sb.close(); // destroy
43
+ ```
44
+
45
+ A **read** API key can list resources but cannot create sandboxes or run code — use a **full** key with the SDK.
46
+
47
+ ## Errors
48
+
49
+ ```ts
50
+ import { APIError, AuthError, QuotaExceededError } from "@sistemo/sdk";
51
+
52
+ try {
53
+ const sb = await Sandbox.create();
54
+ await sb.run("...");
55
+ } catch (e) {
56
+ // Check QuotaExceededError FIRST — it and AuthError both arrive as 403, but
57
+ // they need opposite handling: an auth failure never succeeds on retry, a
58
+ // quota refusal does once you free the resource it names.
59
+ if (e instanceof QuotaExceededError) { console.log(e.detail); }
60
+ else if (e instanceof AuthError) { /* 401/403 — key invalid or read-only */ }
61
+ else if (e instanceof APIError) { console.log(e.status, e.detail, e.code); }
62
+ }
63
+ ```
64
+
65
+ `QuotaExceededError` means an account limit was reached; `detail` names which
66
+ dimension bound and how much is in use, and `GET /v1/quotas` reports every limit
67
+ alongside current usage.
68
+
69
+ Apache-2.0.
@@ -0,0 +1,140 @@
1
+ /**
2
+ * Sistemo — run AI agents and untrusted code in real isolated microVMs.
3
+ *
4
+ * ```ts
5
+ * import { Sandbox } from "@sistemo/sdk";
6
+ *
7
+ * const sb = await Sandbox.create(); // reads SISTEMO_API_KEY
8
+ * const res = await sb.run("python3 -c 'print(2 + 2)'");
9
+ * console.log(res.stdout, res.exitCode);
10
+ * await sb.close();
11
+ * ```
12
+ */
13
+ export declare class SistemoError extends Error {
14
+ }
15
+ export declare class APIError extends SistemoError {
16
+ readonly status: number;
17
+ readonly detail: string;
18
+ readonly code?: string;
19
+ constructor(status: number, detail: string, code?: string);
20
+ }
21
+ /** 401/403 — key missing, invalid, revoked, or a read-only key on a mutation. */
22
+ export declare class AuthError extends APIError {
23
+ }
24
+ /**
25
+ * 403 `quota_exceeded` — an account limit was reached.
26
+ *
27
+ * Deliberately NOT an `AuthError`, even though both arrive as 403. They need
28
+ * opposite handling, and conflating them sends callers to the wrong place:
29
+ *
30
+ * - `AuthError` — the credential cannot do this. Retrying never helps.
31
+ * - `QuotaExceededError` — the credential is fine and the request is valid.
32
+ * **Retrying succeeds once the resource is freed** (stop or destroy a machine,
33
+ * delete a volume) or the limit is raised.
34
+ *
35
+ * `detail` names the dimension that bound and how much is in use; `GET /v1/quotas`
36
+ * reports every limit alongside current usage. A message mentioning "fleet limit"
37
+ * is a fleet-wide ceiling rather than your plan, which topping up will not lift.
38
+ */
39
+ export declare class QuotaExceededError extends APIError {
40
+ }
41
+ /** 404 — resource not found (or not yours). */
42
+ export declare class NotFoundError extends APIError {
43
+ }
44
+ /** 429 — rate limited. */
45
+ export declare class RateLimitError extends APIError {
46
+ }
47
+ export interface ClientOptions {
48
+ apiKey?: string;
49
+ baseUrl?: string;
50
+ /** Per-request timeout in ms (default 120000 — create blocks until boot). */
51
+ timeoutMs?: number;
52
+ /** Extra attempts after the first (default 2 → up to 3 tries). */
53
+ maxRetries?: number;
54
+ /** Base backoff in ms (default 400). */
55
+ retryBackoffMs?: number;
56
+ /** Cap on backoff in ms (default 8000). */
57
+ retryMaxBackoffMs?: number;
58
+ }
59
+ export interface RequestOptions {
60
+ headers?: Record<string, string>;
61
+ /** Enables safe HTTP retries for mutating methods. */
62
+ idempotencyKey?: string;
63
+ /** Override client maxRetries for this call. */
64
+ maxRetries?: number;
65
+ }
66
+ /** Low-level API client. Most users want {@link Sandbox} instead. */
67
+ export declare class Client {
68
+ readonly baseUrl: string;
69
+ private readonly apiKey;
70
+ private readonly timeoutMs;
71
+ private readonly maxRetries;
72
+ private readonly retryBackoffMs;
73
+ private readonly retryMaxBackoffMs;
74
+ constructor(opts?: ClientOptions);
75
+ request<T>(method: string, path: string, body?: unknown, opts?: RequestOptions): Promise<T>;
76
+ private once;
77
+ private shouldRetryHttp;
78
+ private backoff;
79
+ /** List the account's volumes (root and data). */
80
+ listVolumes(): Promise<{
81
+ volumes: Volume[];
82
+ }>;
83
+ /** Create a standalone data volume. */
84
+ createVolume(name: string, sizeGb: number): Promise<Volume>;
85
+ /** Attach a volume (root or data) to a STOPPED machine. */
86
+ attachVolume(machineId: string, volumeId: string): Promise<{
87
+ status: string;
88
+ }>;
89
+ /**
90
+ * Detach a volume from a STOPPED machine. A detached root volume's disk is
91
+ * preserved and can be re-attached or booted onto a new sandbox.
92
+ */
93
+ detachVolume(machineId: string, volumeId: string): Promise<{
94
+ status: string;
95
+ }>;
96
+ /** Delete a detached volume. */
97
+ deleteVolume(volumeId: string): Promise<{
98
+ status: string;
99
+ }>;
100
+ }
101
+ export interface Volume {
102
+ id: string;
103
+ name: string;
104
+ size_gb: number;
105
+ role: string;
106
+ state: string;
107
+ machine_id?: string;
108
+ }
109
+ export interface ExecResult {
110
+ exitCode: number;
111
+ stdout: string;
112
+ stderr: string;
113
+ }
114
+ export interface SandboxOptions extends ClientOptions {
115
+ client?: Client;
116
+ name?: string;
117
+ vcpus?: number;
118
+ memoryMb?: number;
119
+ rootfsSizeGb?: number;
120
+ stack?: string;
121
+ metadata?: Record<string, unknown>;
122
+ /** Boot from an existing (detached/preserved) root volume instead of a fresh
123
+ * template clone. Size/stack come from the volume. */
124
+ rootVolumeId?: string;
125
+ /** Optional fixed Idempotency-Key for create (default: random UUID). */
126
+ idempotencyKey?: string;
127
+ }
128
+ /** An isolated microVM you can run code in. Create with {@link Sandbox.create}. */
129
+ export declare class Sandbox {
130
+ readonly id: string;
131
+ state: string;
132
+ private readonly client;
133
+ private constructor();
134
+ /** Provision a new microVM (resolves once it has booted). */
135
+ static create(opts?: SandboxOptions): Promise<Sandbox>;
136
+ /** Run a shell command/script inside the sandbox. */
137
+ run(script: string, timeoutSec?: number): Promise<ExecResult>;
138
+ /** Destroy the sandbox (and its disk unless `preserveStorage`). */
139
+ close(preserveStorage?: boolean): Promise<void>;
140
+ }
package/dist/index.js ADDED
@@ -0,0 +1,256 @@
1
+ /**
2
+ * Sistemo — run AI agents and untrusted code in real isolated microVMs.
3
+ *
4
+ * ```ts
5
+ * import { Sandbox } from "@sistemo/sdk";
6
+ *
7
+ * const sb = await Sandbox.create(); // reads SISTEMO_API_KEY
8
+ * const res = await sb.run("python3 -c 'print(2 + 2)'");
9
+ * console.log(res.stdout, res.exitCode);
10
+ * await sb.close();
11
+ * ```
12
+ */
13
+ const DEFAULT_BASE_URL = "https://api.sistemo.io";
14
+ // Sent on every request from non-browser runtimes (Node/Bun/Deno). A real
15
+ // User-Agent is required: the production WAF (Cloudflare) blocks generic
16
+ // library UAs with a 403. Browsers ignore attempts to set User-Agent and send
17
+ // their own (which the WAF allows), so this is a no-op there.
18
+ const USER_AGENT = "@sistemo/sdk/0.1.0";
19
+ const RETRY_STATUSES = new Set([408, 429, 500, 502, 503, 504]);
20
+ export class SistemoError extends Error {
21
+ }
22
+ export class APIError extends SistemoError {
23
+ status;
24
+ detail;
25
+ code;
26
+ constructor(status, detail, code) {
27
+ super(`[${status}] ${detail}${code ? ` (${code})` : ""}`);
28
+ this.name = "APIError";
29
+ this.status = status;
30
+ this.detail = detail;
31
+ this.code = code;
32
+ }
33
+ }
34
+ /** 401/403 — key missing, invalid, revoked, or a read-only key on a mutation. */
35
+ export class AuthError extends APIError {
36
+ }
37
+ /**
38
+ * 403 `quota_exceeded` — an account limit was reached.
39
+ *
40
+ * Deliberately NOT an `AuthError`, even though both arrive as 403. They need
41
+ * opposite handling, and conflating them sends callers to the wrong place:
42
+ *
43
+ * - `AuthError` — the credential cannot do this. Retrying never helps.
44
+ * - `QuotaExceededError` — the credential is fine and the request is valid.
45
+ * **Retrying succeeds once the resource is freed** (stop or destroy a machine,
46
+ * delete a volume) or the limit is raised.
47
+ *
48
+ * `detail` names the dimension that bound and how much is in use; `GET /v1/quotas`
49
+ * reports every limit alongside current usage. A message mentioning "fleet limit"
50
+ * is a fleet-wide ceiling rather than your plan, which topping up will not lift.
51
+ */
52
+ export class QuotaExceededError extends APIError {
53
+ }
54
+ /** 404 — resource not found (or not yours). */
55
+ export class NotFoundError extends APIError {
56
+ }
57
+ /** 429 — rate limited. */
58
+ export class RateLimitError extends APIError {
59
+ }
60
+ function apiError(status, detail, code) {
61
+ // 403 is two different things, told apart by `code` — never by the status.
62
+ if (status === 403 && code === "quota_exceeded")
63
+ return new QuotaExceededError(status, detail, code);
64
+ if (status === 401 || status === 403)
65
+ return new AuthError(status, detail, code);
66
+ if (status === 404)
67
+ return new NotFoundError(status, detail, code);
68
+ if (status === 429)
69
+ return new RateLimitError(status, detail, code);
70
+ return new APIError(status, detail, code);
71
+ }
72
+ function newIdempotencyKey() {
73
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
74
+ return crypto.randomUUID();
75
+ }
76
+ return `idem-${Date.now()}-${Math.random().toString(36).slice(2, 12)}`;
77
+ }
78
+ function sleep(ms) {
79
+ return new Promise((r) => setTimeout(r, ms));
80
+ }
81
+ /** Low-level API client. Most users want {@link Sandbox} instead. */
82
+ export class Client {
83
+ baseUrl;
84
+ apiKey;
85
+ timeoutMs;
86
+ maxRetries;
87
+ retryBackoffMs;
88
+ retryMaxBackoffMs;
89
+ constructor(opts = {}) {
90
+ const g = globalThis;
91
+ const env = g.process?.env ?? {};
92
+ const apiKey = opts.apiKey ?? env.SISTEMO_API_KEY;
93
+ if (!apiKey) {
94
+ throw new SistemoError("no API key — pass { apiKey } or set the SISTEMO_API_KEY environment variable");
95
+ }
96
+ this.apiKey = apiKey;
97
+ this.baseUrl = (opts.baseUrl ?? env.SISTEMO_BASE_URL ?? DEFAULT_BASE_URL).replace(/\/$/, "");
98
+ this.timeoutMs = opts.timeoutMs ?? 120_000;
99
+ this.maxRetries = opts.maxRetries ?? 2;
100
+ this.retryBackoffMs = opts.retryBackoffMs ?? 400;
101
+ this.retryMaxBackoffMs = opts.retryMaxBackoffMs ?? 8_000;
102
+ }
103
+ async request(method, path, body, opts = {}) {
104
+ const retries = opts.maxRetries ?? this.maxRetries;
105
+ const methodU = method.toUpperCase();
106
+ let lastErr;
107
+ for (let attempt = 0; attempt <= retries; attempt++) {
108
+ try {
109
+ return await this.once(methodU, path, body, opts);
110
+ }
111
+ catch (e) {
112
+ lastErr = e;
113
+ const can = attempt < retries &&
114
+ (e instanceof APIError
115
+ ? this.shouldRetryHttp(methodU, e.status, opts.idempotencyKey)
116
+ : e instanceof SistemoError); // connection / abort
117
+ if (!can)
118
+ throw e;
119
+ await this.backoff(attempt, e instanceof APIError ? e : undefined);
120
+ }
121
+ }
122
+ throw lastErr;
123
+ }
124
+ async once(method, path, body, opts) {
125
+ const controller = new AbortController();
126
+ const timer = setTimeout(() => controller.abort(), this.timeoutMs);
127
+ let res;
128
+ try {
129
+ const headers = {
130
+ Authorization: `Bearer ${this.apiKey}`,
131
+ Accept: "application/json",
132
+ "User-Agent": USER_AGENT,
133
+ ...(body !== undefined ? { "Content-Type": "application/json" } : {}),
134
+ ...(opts.headers ?? {}),
135
+ };
136
+ if (opts.idempotencyKey) {
137
+ headers["Idempotency-Key"] = opts.idempotencyKey;
138
+ }
139
+ res = await fetch(this.baseUrl + path, {
140
+ method,
141
+ headers,
142
+ body: body !== undefined ? JSON.stringify(body) : undefined,
143
+ signal: controller.signal,
144
+ });
145
+ }
146
+ catch (e) {
147
+ throw new SistemoError(`connection error: ${e.message}`);
148
+ }
149
+ finally {
150
+ clearTimeout(timer);
151
+ }
152
+ const text = await res.text();
153
+ if (!res.ok) {
154
+ let detail = "request failed";
155
+ let code;
156
+ try {
157
+ const parsed = JSON.parse(text);
158
+ detail = parsed.detail ?? detail;
159
+ code = parsed.code;
160
+ }
161
+ catch {
162
+ /* non-JSON error body */
163
+ }
164
+ throw apiError(res.status, detail, code);
165
+ }
166
+ return (text ? JSON.parse(text) : {});
167
+ }
168
+ shouldRetryHttp(method, status, idempotencyKey) {
169
+ if (!RETRY_STATUSES.has(status))
170
+ return false;
171
+ if (method === "GET" || method === "HEAD" || method === "OPTIONS" || method === "DELETE") {
172
+ return true;
173
+ }
174
+ return Boolean(idempotencyKey);
175
+ }
176
+ async backoff(attempt, err) {
177
+ const base = Math.min(this.retryMaxBackoffMs, this.retryBackoffMs * 2 ** attempt);
178
+ let delay = base * (0.5 + Math.random());
179
+ if (err?.status === 429)
180
+ delay = Math.max(delay, base);
181
+ await sleep(delay);
182
+ }
183
+ // --- volumes (incl. detachable root volumes) ---------------------------
184
+ /** List the account's volumes (root and data). */
185
+ async listVolumes() {
186
+ const out = await this.request("GET", "/v1/volumes");
187
+ return { volumes: out.volumes ?? [] };
188
+ }
189
+ /** Create a standalone data volume. */
190
+ createVolume(name, sizeGb) {
191
+ return this.request("POST", "/v1/volumes", { name, size_gb: sizeGb }, { idempotencyKey: newIdempotencyKey() });
192
+ }
193
+ /** Attach a volume (root or data) to a STOPPED machine. */
194
+ attachVolume(machineId, volumeId) {
195
+ return this.request("POST", `/v1/machines/${machineId}/volume/attach`, { volume_id: volumeId }, { idempotencyKey: newIdempotencyKey() });
196
+ }
197
+ /**
198
+ * Detach a volume from a STOPPED machine. A detached root volume's disk is
199
+ * preserved and can be re-attached or booted onto a new sandbox.
200
+ */
201
+ detachVolume(machineId, volumeId) {
202
+ return this.request("POST", `/v1/machines/${machineId}/volume/detach`, { volume_id: volumeId }, { idempotencyKey: newIdempotencyKey() });
203
+ }
204
+ /** Delete a detached volume. */
205
+ deleteVolume(volumeId) {
206
+ return this.request("DELETE", `/v1/volumes/${volumeId}`);
207
+ }
208
+ }
209
+ /** An isolated microVM you can run code in. Create with {@link Sandbox.create}. */
210
+ export class Sandbox {
211
+ id;
212
+ state;
213
+ client;
214
+ constructor(client, id, state) {
215
+ this.client = client;
216
+ this.id = id;
217
+ this.state = state;
218
+ }
219
+ /** Provision a new microVM (resolves once it has booted). */
220
+ static async create(opts = {}) {
221
+ const client = opts.client ?? new Client(opts);
222
+ const body = {
223
+ name: opts.name ?? "",
224
+ vcpus: opts.vcpus ?? 1,
225
+ memory_mb: opts.memoryMb ?? 1024,
226
+ rootfs_size_gb: opts.rootfsSizeGb ?? 10,
227
+ stack: opts.stack ?? "base",
228
+ metadata: opts.metadata ?? {},
229
+ };
230
+ if (opts.rootVolumeId)
231
+ body.root_volume_id = opts.rootVolumeId;
232
+ const key = opts.idempotencyKey ?? newIdempotencyKey();
233
+ const machine = await client.request("POST", "/v1/machines", body, { idempotencyKey: key });
234
+ if (!machine?.id) {
235
+ throw new APIError(502, "create machine response missing id — refusing to continue", "invalid_create_response");
236
+ }
237
+ return new Sandbox(client, machine.id, machine.state ?? "");
238
+ }
239
+ /** Run a shell command/script inside the sandbox. */
240
+ async run(script, timeoutSec = 30) {
241
+ // No Idempotency-Key: HTTP errors are not retried (would re-run the script).
242
+ // Connection failures still use the client's connection-retry path only when
243
+ // they throw SistemoError before a response — see Client.request.
244
+ const out = await this.client.request("POST", `/v1/machines/${this.id}/exec`, { script, timeout_sec: timeoutSec });
245
+ return {
246
+ exitCode: out.exit_code ?? -1,
247
+ stdout: out.stdout ?? "",
248
+ stderr: out.stderr ?? "",
249
+ };
250
+ }
251
+ /** Destroy the sandbox (and its disk unless `preserveStorage`). */
252
+ async close(preserveStorage = false) {
253
+ const q = preserveStorage ? "?preserve_storage=true" : "";
254
+ await this.client.request("DELETE", `/v1/machines/${this.id}${q}`);
255
+ }
256
+ }
package/package.json ADDED
@@ -0,0 +1,53 @@
1
+ {
2
+ "name": "@sistemo/sdk",
3
+ "version": "0.1.0",
4
+ "description": "Run AI agents and untrusted code in real isolated microVMs.",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "main": "dist/index.js",
8
+ "module": "dist/index.js",
9
+ "types": "dist/index.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.ts",
13
+ "import": "./dist/index.js"
14
+ }
15
+ },
16
+ "files": [
17
+ "dist",
18
+ "README.md",
19
+ "LICENSE"
20
+ ],
21
+ "engines": {
22
+ "node": ">=18"
23
+ },
24
+ "scripts": {
25
+ "build": "npm run clean && tsc -p tsconfig.json",
26
+ "typecheck": "tsc -p tsconfig.json --noEmit",
27
+ "test": "npm run build && node --test test/sdk.test.mjs",
28
+ "prepublishOnly": "npm run build && npm test",
29
+ "clean": "rm -rf dist"
30
+ },
31
+ "keywords": [
32
+ "sandbox",
33
+ "firecracker",
34
+ "microvm",
35
+ "ai-agents",
36
+ "code-execution"
37
+ ],
38
+ "homepage": "https://sistemo.io",
39
+ "devDependencies": {
40
+ "typescript": "^5.5.0"
41
+ },
42
+ "publishConfig": {
43
+ "access": "public"
44
+ },
45
+ "repository": {
46
+ "type": "git",
47
+ "url": "git+https://github.com/sistemo0/sistemo-sdk.git",
48
+ "directory": "js"
49
+ },
50
+ "bugs": {
51
+ "url": "https://github.com/sistemo0/sistemo-sdk/issues"
52
+ }
53
+ }