cubepod 0.0.0-stage → 0.4.1

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,202 @@
1
- # Temporary Holding Version
1
+ # cubepod — CubePod TypeScript / Node.js 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 TypeScript / JavaScript SDK for **CubePod** — persistent, E2B-compatible MicroVM agent sandboxes with dual-volume RootFS + `/workspace` isolation, 1-second Copy-on-Write forks, streaming Code Interpreter, zero-trust egress, and template builds.
4
+
5
+ - **Zero runtime dependencies** — uses native `fetch`, `ReadableStream`, `TextDecoder`, `Headers`, `URLSearchParams`, and `CompressionStream` (Node.js 20+, Deno, Bun, and modern edge runtimes).
6
+ - **Full TypeScript declarations** bundled in `src/*.d.ts`.
7
+
8
+ ---
9
+
10
+ ## Installation
11
+
12
+ ```bash
13
+ npm install cubepod
14
+ ```
15
+
16
+ ## Quick Start
17
+
18
+ ```ts
19
+ import { CubePodClient, Sandbox } from 'cubepod';
20
+
21
+ const sandbox = await Sandbox.create({
22
+ baseUrl: 'http://localhost:8080',
23
+ apiKey: process.env.CUBEPOD_API_KEY,
24
+ templateId: 'cubeplex-ubuntu24-desktop',
25
+ volumeKey: 'workspace-user-42',
26
+ });
27
+
28
+ const result = await sandbox.commands.run('ls -la /workspace');
29
+ console.log(result.stdout);
30
+
31
+ await sandbox.kill();
32
+ ```
33
+
34
+ ---
35
+
36
+ ## Sandbox Lifecycle, CoW Fork & RootFS Reset
37
+
38
+ ```ts
39
+ import { Sandbox } from 'cubepod';
40
+
41
+ const sandbox = await Sandbox.create('ubuntu:24.04', {
42
+ baseUrl: 'http://localhost:8080',
43
+ timeout: 1800,
44
+ });
45
+
46
+ // Pause compute (0 CPU/RAM) while retaining RootFS + Workspace volumes
47
+ await sandbox.pause();
48
+
49
+ // Auto-resume from Paused state
50
+ const resumed = await Sandbox.connect(sandbox.sandboxId, {
51
+ baseUrl: 'http://localhost:8080',
52
+ });
53
+
54
+ // Keepalive timeout & idle-pause lease protection
55
+ await resumed.setTimeout(3600);
56
+ await resumed.acquireLease(600);
57
+
58
+ // Reset RootFS Upper to a clean base image while keeping /workspace intact
59
+ await resumed.resetRootfs();
60
+
61
+ // Clone both RootFS and Workspace volumes via ~1s Copy-on-Write
62
+ const child = await resumed.fork({ metadata: { branch: 'experiment-1' } });
63
+ await child.kill({ deleteVolumes: true });
64
+ ```
65
+
66
+ ## Endpoints & Signed Panel URLs
67
+
68
+ ```ts
69
+ // E2B getHost compatibility
70
+ const host = await sandbox.getHost(8080);
71
+ console.log(`https://${host}`);
72
+
73
+ // Mint an HMAC-SHA256 signed /panel/{token}/ URL for web/noVNC/WebRTC views
74
+ const panel = await sandbox.createEndpoint(8080, { expiresInSeconds: 3600 });
75
+ console.log(panel.url);
76
+ ```
77
+
78
+ ## Commands & Files
79
+
80
+ `uid` and `gid` are omitted by default so the template's configured `USER` is preserved on the server. Pass `uid` / `gid` explicitly (including `uid: 0` for `root`) when overriding ownership.
81
+
82
+ ```ts
83
+ // Foreground command (uses template USER by default)
84
+ const res = await sandbox.commands.run('id');
85
+
86
+ // Background command + cursor-based log polling
87
+ const bg = await sandbox.commands.run('python3 -u worker.py', {
88
+ background: true,
89
+ workdir: '/workspace',
90
+ envs: { PYTHONUNBUFFERED: '1' },
91
+ });
92
+ const status = await sandbox.commands.getStatus(bg.id);
93
+ const logs = await sandbox.commands.getLogs(bg.id, { cursor: 0 });
94
+ await sandbox.commands.kill(bg.id);
95
+
96
+ // File read / write / list / remove
97
+ await sandbox.files.write('/workspace/app.py', 'print("hello")\n');
98
+ await sandbox.files.write('/etc/app.conf', new Uint8Array([1, 2, 3]), {
99
+ uid: 0,
100
+ gid: 0,
101
+ mode: '0600',
102
+ });
103
+ const text = await sandbox.files.readText('/workspace/app.py');
104
+ const bytes = await sandbox.files.readBytes('/workspace/app.py');
105
+ const entries = await sandbox.files.list('/workspace');
106
+ await sandbox.files.remove('/workspace/app.py');
107
+
108
+ // Atomic archive-sync (pass tar.gz Uint8Array or a file map)
109
+ await sandbox.files.archiveSync(
110
+ { 'my-skill/SKILL.md': '# My Skill\n' },
111
+ { dest: '/workspace/skills', removePaths: ['deprecated-skill'] },
112
+ );
113
+ ```
114
+
115
+ ## Code Interpreter (Streaming NDJSON & Contexts)
116
+
117
+ ```ts
118
+ const ctx = await sandbox.code.createContext({
119
+ language: 'python',
120
+ cwd: '/workspace',
121
+ });
122
+
123
+ const execution = await sandbox.code.runCode(
124
+ 'import math\nprint("pi =", math.pi)\nmath.sqrt(16)',
125
+ {
126
+ contextId: ctx.id,
127
+ onStdout: (msg) => process.stdout.write(msg.text),
128
+ onStderr: (msg) => process.stderr.write(msg.text),
129
+ onResult: (res) => console.log('Result:', res.text, res.png ? '[png]' : ''),
130
+ onError: (err) => console.error(err.name, err.value),
131
+ },
132
+ );
133
+
134
+ console.log(execution.text); // "4.0"
135
+
136
+ await sandbox.code.restartContext(ctx.id);
137
+ await sandbox.code.deleteContext(ctx.id);
138
+ ```
139
+
140
+ ## Template Catalog, Builds & WarmPools
141
+
142
+ ```ts
143
+ const client = new CubePodClient({ baseUrl: 'http://localhost:8080' });
144
+
145
+ // List templates (v1 and paginated v2 with X-Next-Token)
146
+ const templates = await client.listTemplates();
147
+ const page = await client.listTemplatesV2({ limit: 50 });
148
+
149
+ // Inspect by ID or alias (automatically URI-encoded for org/name:v1)
150
+ const tpl = await client.getTemplate('org/name:v1');
151
+
152
+ // Create and start a template build (v3/v2)
153
+ const req = await client.createTemplate({
154
+ name: 'python-data:v1',
155
+ cpuCount: 2,
156
+ memoryMB: 2048,
157
+ });
158
+
159
+ await client.startTemplateBuild(req.templateID, req.buildID, {
160
+ fromImage: 'python:3.13',
161
+ steps: [{ type: 'RUN', args: ['pip install pandas numpy'] }],
162
+ });
163
+
164
+ const buildStatus = await client.getTemplateBuildStatus(req.templateID, req.buildID);
165
+ if (buildStatus.status === 'error') {
166
+ console.error(buildStatus.reason?.step, buildStatus.reason?.message);
167
+ }
168
+
169
+ await client.updateTemplateVisibility(req.templateID, true);
170
+ await client.deleteTemplate(req.templateID);
171
+
172
+ // WarmPools
173
+ await client.createWarmPool({
174
+ name: 'python-pool',
175
+ templateRef: 'python-data:v1',
176
+ replicas: 2,
177
+ });
178
+ const pools = await client.listWarmPools();
179
+ ```
180
+
181
+ ## Error Handling
182
+
183
+ ```ts
184
+ import { CubePodAPIError, CubePodError } from 'cubepod';
185
+
186
+ try {
187
+ await client.getTemplate('non-existent');
188
+ } catch (err) {
189
+ if (err instanceof CubePodAPIError) {
190
+ console.error(err.statusCode, err.code, err.sandboxId, err.message);
191
+ } else if (err instanceof CubePodError) {
192
+ console.error(err.message);
193
+ }
194
+ }
195
+ ```
196
+
197
+ ## Running Tests
198
+
199
+ ```bash
200
+ cd sdks/typescript
201
+ npm test
202
+ ```
package/package.json CHANGED
@@ -1,6 +1,47 @@
1
1
  {
2
2
  "name": "cubepod",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.4.1",
4
+ "description": "Official TypeScript/JavaScript SDK for CubePod (E2B-compatible persistent MicroVM sandboxes)",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "main": "./src/index.js",
8
+ "types": "./src/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./src/index.d.ts",
12
+ "import": "./src/index.js",
13
+ "default": "./src/index.js"
14
+ }
15
+ },
16
+ "files": [
17
+ "src/",
18
+ "README.md"
19
+ ],
20
+ "engines": {
21
+ "node": ">=20.0.0"
22
+ },
23
+ "scripts": {
24
+ "test": "node --test tests/*.test.mjs"
25
+ },
26
+ "keywords": [
27
+ "cubepod",
28
+ "cubeplex",
29
+ "e2b",
30
+ "sandbox",
31
+ "microvm",
32
+ "ai-agents",
33
+ "code-interpreter"
34
+ ],
35
+ "repository": {
36
+ "type": "git",
37
+ "url": "git+https://github.com/cubeplexai/cubepod.git",
38
+ "directory": "sdks/typescript"
39
+ },
40
+ "homepage": "https://cubepod.cubeplex.ai",
41
+ "bugs": {
42
+ "url": "https://github.com/cubeplexai/cubepod/issues"
43
+ },
44
+ "publishConfig": {
45
+ "access": "public"
46
+ }
47
+ }
@@ -0,0 +1,18 @@
1
+ export interface TarArchiveOptions {
2
+ uid?: number;
3
+ gid?: number;
4
+ mode?: number;
5
+ mtimeSeconds?: number;
6
+ }
7
+
8
+ export function buildTarBytes(
9
+ files: Record<string, string | Uint8Array | ArrayBuffer>,
10
+ options?: TarArchiveOptions,
11
+ ): Uint8Array;
12
+
13
+ export function gzipBytes(input: Uint8Array): Promise<Uint8Array>;
14
+
15
+ export function buildTarGzBytes(
16
+ files: Record<string, string | Uint8Array | ArrayBuffer>,
17
+ options?: TarArchiveOptions,
18
+ ): Promise<Uint8Array>;
package/src/archive.js ADDED
@@ -0,0 +1,178 @@
1
+ /**
2
+ * Zero-dependency POSIX ustar tar.gz archive builder using Web CompressionStream.
3
+ */
4
+
5
+ const textEncoder = new TextEncoder();
6
+
7
+ /**
8
+ * Write an ASCII string into a fixed-length tar header slice.
9
+ *
10
+ * @param {Uint8Array} buf
11
+ * @param {number} offset
12
+ * @param {number} length
13
+ * @param {string} value
14
+ */
15
+ function writeString(buf, offset, length, value) {
16
+ const encoded = textEncoder.encode(value);
17
+ const count = Math.min(encoded.length, length);
18
+ buf.set(encoded.subarray(0, count), offset);
19
+ }
20
+
21
+ /**
22
+ * Write a zero-padded octal field into a tar header slice.
23
+ *
24
+ * @param {Uint8Array} buf
25
+ * @param {number} offset
26
+ * @param {number} length
27
+ * @param {number} value
28
+ */
29
+ function writeOctal(buf, offset, length, value) {
30
+ const digits = Math.max(0, Math.floor(value)).toString(8);
31
+ const maxDigits = length - 1;
32
+ const padded = digits.slice(-maxDigits).padStart(maxDigits, '0');
33
+ writeString(buf, offset, maxDigits, padded);
34
+ buf[offset + maxDigits] = 0;
35
+ }
36
+
37
+ /**
38
+ * Build an uncompressed POSIX ustar tar buffer from a path -> content map.
39
+ *
40
+ * @param {Record<string, string | Uint8Array | ArrayBuffer>} files
41
+ * @param {{ uid?: number; gid?: number; mode?: number; mtimeSeconds?: number }} [options]
42
+ * @returns {Uint8Array}
43
+ */
44
+ export function buildTarBytes(files, options = {}) {
45
+ const uid = options.uid ?? 1000;
46
+ const gid = options.gid ?? 1000;
47
+ const mode = options.mode ?? 0o644;
48
+ const mtimeSeconds = options.mtimeSeconds ?? Math.floor(Date.now() / 1000);
49
+
50
+ /** @type {Uint8Array[]} */
51
+ const blocks = [];
52
+
53
+ for (const [rawPath, content] of Object.entries(files)) {
54
+ const relPath = rawPath.replace(/^\/+/, '');
55
+ if (!relPath) continue;
56
+
57
+ /** @type {Uint8Array} */
58
+ let data;
59
+ if (typeof content === 'string') {
60
+ data = textEncoder.encode(content);
61
+ } else if (content instanceof Uint8Array) {
62
+ data = content;
63
+ } else if (content instanceof ArrayBuffer) {
64
+ data = new Uint8Array(content);
65
+ } else {
66
+ throw new TypeError(`Unsupported archive entry content for "${rawPath}"`);
67
+ }
68
+
69
+ const header = new Uint8Array(512);
70
+ const pathBytes = textEncoder.encode(relPath);
71
+ if (pathBytes.length <= 100) {
72
+ header.set(pathBytes, 0);
73
+ } else {
74
+ const splitIdx = relPath.lastIndexOf('/');
75
+ if (splitIdx <= 0) {
76
+ throw new RangeError(`Archive entry path exceeds 100 bytes: "${relPath}"`);
77
+ }
78
+ const prefix = relPath.slice(0, splitIdx);
79
+ const name = relPath.slice(splitIdx + 1);
80
+ if (textEncoder.encode(prefix).length > 155 || textEncoder.encode(name).length > 100) {
81
+ throw new RangeError(`Archive entry path exceeds ustar limits: "${relPath}"`);
82
+ }
83
+ writeString(header, 0, 100, name);
84
+ writeString(header, 345, 155, prefix);
85
+ }
86
+
87
+ writeOctal(header, 100, 8, mode);
88
+ writeOctal(header, 108, 8, uid);
89
+ writeOctal(header, 116, 8, gid);
90
+ writeOctal(header, 124, 12, data.length);
91
+ writeOctal(header, 136, 12, mtimeSeconds);
92
+ // Checksum field filled with spaces during checksum calculation.
93
+ header.fill(0x20, 148, 156);
94
+ header[156] = 0x30; // '0' regular file
95
+ writeString(header, 257, 6, 'ustar\0');
96
+ writeString(header, 263, 2, '00');
97
+
98
+ let checksum = 0;
99
+ for (let i = 0; i < 512; i += 1) {
100
+ checksum += header[i];
101
+ }
102
+ const cksumStr = checksum.toString(8).padStart(6, '0');
103
+ writeString(header, 148, 6, cksumStr);
104
+ header[154] = 0;
105
+ header[155] = 0x20;
106
+
107
+ blocks.push(header);
108
+ if (data.length > 0) {
109
+ blocks.push(data);
110
+ const remainder = data.length % 512;
111
+ if (remainder !== 0) {
112
+ blocks.push(new Uint8Array(512 - remainder));
113
+ }
114
+ }
115
+ }
116
+
117
+ // Two 512-byte zero blocks terminate the tar archive.
118
+ blocks.push(new Uint8Array(1024));
119
+
120
+ const totalLength = blocks.reduce((acc, part) => acc + part.length, 0);
121
+ const tar = new Uint8Array(totalLength);
122
+ let offset = 0;
123
+ for (const part of blocks) {
124
+ tar.set(part, offset);
125
+ offset += part.length;
126
+ }
127
+ return tar;
128
+ }
129
+
130
+ /**
131
+ * Compress a Uint8Array with gzip using Web Streams CompressionStream.
132
+ *
133
+ * @param {Uint8Array} input
134
+ * @returns {Promise<Uint8Array>}
135
+ */
136
+ export async function gzipBytes(input) {
137
+ const cs = new CompressionStream('gzip');
138
+ const writer = cs.writable.getWriter();
139
+ await writer.write(/** @type {BufferSource} */ (input));
140
+ await writer.close();
141
+
142
+ const reader = cs.readable.getReader();
143
+ /** @type {Uint8Array[]} */
144
+ const chunks = [];
145
+ let total = 0;
146
+ try {
147
+ while (true) {
148
+ const { value, done } = await reader.read();
149
+ if (done) break;
150
+ if (value) {
151
+ chunks.push(value);
152
+ total += value.length;
153
+ }
154
+ }
155
+ } finally {
156
+ reader.releaseLock();
157
+ }
158
+
159
+ const out = new Uint8Array(total);
160
+ let offset = 0;
161
+ for (const chunk of chunks) {
162
+ out.set(chunk, offset);
163
+ offset += chunk.length;
164
+ }
165
+ return out;
166
+ }
167
+
168
+ /**
169
+ * Pack a map of file paths and contents into a gzip-compressed tar archive.
170
+ *
171
+ * @param {Record<string, string | Uint8Array | ArrayBuffer>} files
172
+ * @param {{ uid?: number; gid?: number; mode?: number; mtimeSeconds?: number }} [options]
173
+ * @returns {Promise<Uint8Array>}
174
+ */
175
+ export async function buildTarGzBytes(files, options = {}) {
176
+ const tar = buildTarBytes(files, options);
177
+ return gzipBytes(tar);
178
+ }