@raytrace-cli/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/LICENSE +21 -0
- package/README.md +71 -2
- package/package.json +42 -4
- package/src/client.mjs +204 -0
- package/src/index.d.ts +141 -0
- package/src/index.mjs +187 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 RayTrace contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,72 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @raytrace-cli/sdk
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Create and drive [RayTrace](https://raytracer.si) cloud sandboxes from code. Every coding-agent session in a sandbox is recorded to your organization's dashboard.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
npm install @raytrace-cli/sdk
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
Node.js 20 or newer. No dependencies.
|
|
10
|
+
|
|
11
|
+
## Authenticate
|
|
12
|
+
|
|
13
|
+
Create an org API key on your RayTrace account page (**Account → API keys**) and set it in the environment:
|
|
14
|
+
|
|
15
|
+
```sh
|
|
16
|
+
export RAYTRACE_API_KEY=rtk_...
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
Or pass it directly: `new RayTrace({ apiKey: 'rtk_...' })`.
|
|
20
|
+
|
|
21
|
+
## Quickstart
|
|
22
|
+
|
|
23
|
+
```js
|
|
24
|
+
import RayTrace from '@raytrace-cli/sdk';
|
|
25
|
+
|
|
26
|
+
const rt = new RayTrace();
|
|
27
|
+
|
|
28
|
+
// Upload a project folder (.git, .env, keys and credentials are left out).
|
|
29
|
+
const sandbox = await rt.sandboxes.create({ name: 'my-app', dir: '.', size: 'small' });
|
|
30
|
+
|
|
31
|
+
const result = await sandbox.exec('npm test', { timeoutSeconds: 300 });
|
|
32
|
+
console.log(result.exitCode, result.stdout);
|
|
33
|
+
|
|
34
|
+
await sandbox.stop();
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
## Sandboxes
|
|
38
|
+
|
|
39
|
+
| Call | What it does |
|
|
40
|
+
| --- | --- |
|
|
41
|
+
| `rt.sandboxes.create({ name, size, dir \| files \| archive })` | New sandbox from a folder, an in-memory file map, or a `.tar.gz` |
|
|
42
|
+
| `rt.sandboxes.create({ repo, ref })` | New sandbox from a Git repository: an https or ssh URL, or `owner/name` on GitHub; `ref` picks a branch or tag. Cloned with this machine's `git` and credentials |
|
|
43
|
+
| `rt.sandboxes.list()` / `rt.sandboxes.get(id)` | Your organization's sandboxes |
|
|
44
|
+
| `sandbox.exec(command, { timeoutSeconds })` | Runs a command and waits for `{ exitCode, stdout, stderr, state }` |
|
|
45
|
+
| `sandbox.stop()` | Stops it; files are kept and billing stops |
|
|
46
|
+
| `sandbox.start({ size })` | Starts it again, restoring an archived sandbox first |
|
|
47
|
+
| `sandbox.keepAlive(minutes)` | Holds off the idle stop for a long-running job (up to 4 hours) |
|
|
48
|
+
| `sandbox.destroy({ keepTraces })` | Deletes it; `keepTraces: true` keeps its recordings on paid plans |
|
|
49
|
+
| `sandbox.status`, `sandbox.size` | From the last fetch |
|
|
50
|
+
|
|
51
|
+
Sizes are `small`, `medium` and `large`.
|
|
52
|
+
|
|
53
|
+
## Usage and keys
|
|
54
|
+
|
|
55
|
+
```js
|
|
56
|
+
await rt.usage.get({ days: 30 }); // credits spent and remaining
|
|
57
|
+
await rt.apiKeys.create('ci'); // the key is returned once
|
|
58
|
+
await rt.apiKeys.list();
|
|
59
|
+
await rt.apiKeys.revoke(id);
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
## Billing and errors
|
|
63
|
+
|
|
64
|
+
Running sandboxes are paid from prepaid credits in 15-minute blocks, and stop by themselves after 15 minutes of no activity. Failed calls throw `RayTraceError` with `status` and `code`:
|
|
65
|
+
|
|
66
|
+
| `code` | Meaning |
|
|
67
|
+
| --- | --- |
|
|
68
|
+
| `insufficient_balance` | Not enough credit for the next 15 minutes; top up on the account page |
|
|
69
|
+
| `recording_plan_required` | Cloud sandboxes need an Individual or Team plan |
|
|
70
|
+
| `no_capacity` | No room right now; retry shortly |
|
|
71
|
+
|
|
72
|
+
The full HTTP contract is in [`docs/v1-contract.md`](https://github.com/Godcreatebugs/raytrace-cli/blob/main/docs/v1-contract.md).
|
package/package.json
CHANGED
|
@@ -1,6 +1,44 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@raytrace-cli/sdk",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "TypeScript/JavaScript SDK for RayTrace cloud sandboxes: create, run commands, stop, start and destroy over the /v1 API",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"homepage": "https://raytracer.si",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/Godcreatebugs/raytrace-cli.git",
|
|
11
|
+
"directory": "sdk/ts"
|
|
12
|
+
},
|
|
13
|
+
"bugs": "https://github.com/Godcreatebugs/raytrace-cli/issues",
|
|
14
|
+
"keywords": [
|
|
15
|
+
"raytrace",
|
|
16
|
+
"sandbox",
|
|
17
|
+
"coding-agents",
|
|
18
|
+
"sdk"
|
|
19
|
+
],
|
|
20
|
+
"engines": {
|
|
21
|
+
"node": ">=20.0.0"
|
|
22
|
+
},
|
|
23
|
+
"files": [
|
|
24
|
+
"src/",
|
|
25
|
+
"README.md",
|
|
26
|
+
"LICENSE"
|
|
27
|
+
],
|
|
28
|
+
"exports": {
|
|
29
|
+
".": {
|
|
30
|
+
"types": "./src/index.d.ts",
|
|
31
|
+
"import": "./src/index.mjs"
|
|
32
|
+
},
|
|
33
|
+
"./client": {
|
|
34
|
+
"types": "./src/index.d.ts",
|
|
35
|
+
"import": "./src/client.mjs"
|
|
36
|
+
}
|
|
37
|
+
},
|
|
38
|
+
"publishConfig": {
|
|
39
|
+
"access": "public"
|
|
40
|
+
},
|
|
41
|
+
"scripts": {
|
|
42
|
+
"test": "node --test test/*.test.mjs"
|
|
43
|
+
}
|
|
44
|
+
}
|
package/src/client.mjs
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
// Shared low-level /v1 HTTP client for @raytrace-cli/sdk.
|
|
2
|
+
// Zero runtime dependencies (Node 20+ native fetch + zlib + crypto).
|
|
3
|
+
import { gzipSync } from 'node:zlib';
|
|
4
|
+
import { mkdtempSync, readdirSync, readFileSync, rmSync, statSync } from 'node:fs';
|
|
5
|
+
import { join, posix } from 'node:path';
|
|
6
|
+
import { execFile } from 'node:child_process';
|
|
7
|
+
import { tmpdir } from 'node:os';
|
|
8
|
+
import { promisify } from 'node:util';
|
|
9
|
+
|
|
10
|
+
export const DEFAULT_BASE_URL = 'https://api.raytracer.si';
|
|
11
|
+
|
|
12
|
+
const DEFAULT_EXCLUDED = new Set([
|
|
13
|
+
'.git', '.raytace', '.raytrace', '.ssh', '.aws', '.azure', '.config',
|
|
14
|
+
'.claude', '.codex', '.docker', '.kube', '.gnupg', 'node_modules',
|
|
15
|
+
'.venv', '__pycache__', '.next', 'dist', 'coverage', '.DS_Store',
|
|
16
|
+
]);
|
|
17
|
+
// Files that usually hold credentials, never uploaded (the same rules as the
|
|
18
|
+
// CLI's `raytrace sandbox create`). Compared in lower case.
|
|
19
|
+
const SECRET_NAMES = new Set([
|
|
20
|
+
'.npmrc', '.netrc', '.pypirc', '.htpasswd', '.dockercfg', 'credentials', 'credentials.json', 'credentials.ini',
|
|
21
|
+
'auth.json', 'service-account.json', 'service_account.json', 'serviceaccountkey.json',
|
|
22
|
+
'client_secret.json', 'client_secrets.json', 'token.json', 'id_rsa', 'id_dsa', 'id_ecdsa',
|
|
23
|
+
'id_ed25519', 'id_ecdsa_sk', 'id_ed25519_sk', 'known_hosts',
|
|
24
|
+
]);
|
|
25
|
+
const SECRET_EXTENSIONS = /\.(pem|key|p12|pfx)$/i;
|
|
26
|
+
|
|
27
|
+
export function isSecretFile(name) {
|
|
28
|
+
const lower = String(name).toLowerCase();
|
|
29
|
+
return lower.startsWith('.env') || lower.startsWith('.secret') || SECRET_EXTENSIONS.test(lower) || SECRET_NAMES.has(lower);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export class RayTraceError extends Error {
|
|
33
|
+
constructor(message, { status = 0, code = null, topupUrl = null, body = null } = {}) {
|
|
34
|
+
super(message);
|
|
35
|
+
this.name = 'RayTraceError';
|
|
36
|
+
this.status = status;
|
|
37
|
+
this.code = code;
|
|
38
|
+
this.topupUrl = topupUrl;
|
|
39
|
+
this.body = body;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function writeOctal(buf, offset, length, value) {
|
|
44
|
+
const str = Math.max(0, value).toString(8).padStart(length - 1, '0');
|
|
45
|
+
buf.write(str.slice(-(length - 1)), offset, length - 1, 'ascii');
|
|
46
|
+
buf[offset + length - 1] = 0;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Pure-JS POSIX ustar + gzip builder (no external tar binary or npm packages).
|
|
51
|
+
* Accepts a map of relative POSIX paths -> string | Uint8Array | Buffer.
|
|
52
|
+
*/
|
|
53
|
+
export function buildTarGz(files) {
|
|
54
|
+
const chunks = [];
|
|
55
|
+
const entries = Object.entries(files || {});
|
|
56
|
+
if (!entries.length) {
|
|
57
|
+
throw new Error('Archive must contain at least one file');
|
|
58
|
+
}
|
|
59
|
+
for (const [rawPath, content] of entries) {
|
|
60
|
+
const rel = String(rawPath).replace(/^\/+/, '');
|
|
61
|
+
if (!rel || rel.includes('..') || rel.length > 99) {
|
|
62
|
+
throw new Error(`Invalid archive file path: ${rawPath}`);
|
|
63
|
+
}
|
|
64
|
+
const data = Buffer.isBuffer(content) ? content : Buffer.from(content);
|
|
65
|
+
const header = Buffer.alloc(512, 0);
|
|
66
|
+
header.write(rel, 0, Math.min(rel.length, 100), 'utf8');
|
|
67
|
+
writeOctal(header, 100, 8, 0o644);
|
|
68
|
+
writeOctal(header, 108, 8, 1000);
|
|
69
|
+
writeOctal(header, 116, 8, 1000);
|
|
70
|
+
writeOctal(header, 124, 12, data.length);
|
|
71
|
+
writeOctal(header, 136, 12, Math.floor(Date.now() / 1000));
|
|
72
|
+
header.fill(0x20, 148, 156); // checksum placeholder spaces
|
|
73
|
+
header[156] = 0x30; // '0' regular file
|
|
74
|
+
header.write('ustar\0', 257, 6, 'ascii');
|
|
75
|
+
header.write('00', 263, 2, 'ascii');
|
|
76
|
+
let sum = 0;
|
|
77
|
+
for (let i = 0; i < 512; i += 1) sum += header[i];
|
|
78
|
+
const chk = sum.toString(8).padStart(6, '0');
|
|
79
|
+
header.write(chk, 148, 6, 'ascii');
|
|
80
|
+
header[154] = 0;
|
|
81
|
+
header[155] = 0x20;
|
|
82
|
+
chunks.push(header);
|
|
83
|
+
if (data.length > 0) {
|
|
84
|
+
chunks.push(data);
|
|
85
|
+
const pad = (512 - (data.length % 512)) % 512;
|
|
86
|
+
if (pad) chunks.push(Buffer.alloc(pad, 0));
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
chunks.push(Buffer.alloc(1024, 0));
|
|
90
|
+
return gzipSync(Buffer.concat(chunks));
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// git transports a repository URL may use: https and ssh only, so a URL such
|
|
94
|
+
// as ext::<command> can never run a program.
|
|
95
|
+
const GIT_ENV = { GIT_ALLOW_PROTOCOL: 'https:ssh', GIT_TERMINAL_PROMPT: '0' };
|
|
96
|
+
|
|
97
|
+
/** The clone URL for `repo`: an https or ssh URL as given, `host/owner/name` over https, or GitHub's `owner/name`. */
|
|
98
|
+
export function repoUrl(repo) {
|
|
99
|
+
const value = String(repo || '').trim();
|
|
100
|
+
if (/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(value)) return `https://github.com/${value.replace(/\.git$/, '')}.git`;
|
|
101
|
+
if (/^[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)+\/[^\s:]+$/.test(value)) return `https://${value}`;
|
|
102
|
+
if (/^https:\/\/[^\s]+$/.test(value) || /^ssh:\/\/[^\s]+$/.test(value) || /^[A-Za-z0-9_.-]+@[A-Za-z0-9_.-]+:[^\s]+$/.test(value)) return value;
|
|
103
|
+
throw new Error(`Unsupported repo "${value}": use an https or ssh URL, or owner/name for GitHub`);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** The name a repository gives a sandbox: its last path segment, without .git. */
|
|
107
|
+
export function repoName(repo) {
|
|
108
|
+
return String(repo).replace(/\/+$/, '').split(/[/:]/).filter(Boolean).pop().replace(/\.git$/, '') || 'sandbox';
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Clones `repo` (shallow; `ref` is a branch or tag) into a temporary folder and
|
|
113
|
+
* packs it like archiveFromDirectory, then deletes the clone. Uses the git on
|
|
114
|
+
* this machine and its credentials, so private repositories work wherever
|
|
115
|
+
* `git clone` does; it never waits for a password prompt.
|
|
116
|
+
*/
|
|
117
|
+
export async function archiveFromRepo(repo, { ref = undefined } = {}) {
|
|
118
|
+
const dir = mkdtempSync(join(tmpdir(), 'raytrace-repo-'));
|
|
119
|
+
try {
|
|
120
|
+
const args = ['clone', '--depth', '1', '--quiet'];
|
|
121
|
+
if (ref) args.push('--branch', String(ref));
|
|
122
|
+
args.push('--', repoUrl(repo), join(dir, 'repo'));
|
|
123
|
+
try {
|
|
124
|
+
await promisify(execFile)('git', args, { env: { ...process.env, ...GIT_ENV }, timeout: 300_000, maxBuffer: 1 << 20 });
|
|
125
|
+
} catch (error) {
|
|
126
|
+
if (error.code === 'ENOENT') throw new Error('Creating a sandbox from a repo needs git installed on this machine');
|
|
127
|
+
throw new Error(`Could not clone ${repo}: ${String(error.stderr || error.message).trim()}`);
|
|
128
|
+
}
|
|
129
|
+
return archiveFromDirectory(join(dir, 'repo'));
|
|
130
|
+
} finally {
|
|
131
|
+
rmSync(dir, { recursive: true, force: true });
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export function archiveFromDirectory(dirPath) {
|
|
136
|
+
const files = {};
|
|
137
|
+
function walk(absDir, relPrefix) {
|
|
138
|
+
for (const entry of readdirSync(absDir, { withFileTypes: true })) {
|
|
139
|
+
if (DEFAULT_EXCLUDED.has(entry.name)) continue;
|
|
140
|
+
const abs = join(absDir, entry.name);
|
|
141
|
+
const rel = relPrefix ? posix.join(relPrefix, entry.name) : entry.name;
|
|
142
|
+
if (entry.isSymbolicLink()) continue;
|
|
143
|
+
if (entry.isDirectory()) {
|
|
144
|
+
walk(abs, rel);
|
|
145
|
+
} else if (entry.isFile() && !isSecretFile(entry.name)) {
|
|
146
|
+
const st = statSync(abs);
|
|
147
|
+
if (st.size <= 25 * 1024 * 1024) {
|
|
148
|
+
files[rel] = readFileSync(abs);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
walk(dirPath, '');
|
|
154
|
+
return buildTarGz(files);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
export class RayTraceClient {
|
|
158
|
+
constructor({ apiKey = process.env.RAYTRACE_API_KEY, baseUrl = process.env.RAYTRACE_API_URL || DEFAULT_BASE_URL, fetchImpl = globalThis.fetch } = {}) {
|
|
159
|
+
if (!apiKey) {
|
|
160
|
+
throw new Error('RayTrace API key is required (pass { apiKey } or set RAYTRACE_API_KEY)');
|
|
161
|
+
}
|
|
162
|
+
if (typeof fetchImpl !== 'function') {
|
|
163
|
+
throw new Error('A Fetch API implementation is required');
|
|
164
|
+
}
|
|
165
|
+
this.apiKey = apiKey;
|
|
166
|
+
this.baseUrl = String(baseUrl).replace(/\/+$/, '');
|
|
167
|
+
this.fetch = fetchImpl;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
async request(method, path, { headers = {}, body = undefined } = {}) {
|
|
171
|
+
const url = `${this.baseUrl}${path.startsWith('/') ? path : `/${path}`}`;
|
|
172
|
+
const reqHeaders = {
|
|
173
|
+
Authorization: `Bearer ${this.apiKey}`,
|
|
174
|
+
...headers,
|
|
175
|
+
};
|
|
176
|
+
let reqBody = body;
|
|
177
|
+
if (body !== undefined && !(body instanceof Uint8Array) && typeof body !== 'string') {
|
|
178
|
+
reqHeaders['Content-Type'] = 'application/json';
|
|
179
|
+
reqBody = JSON.stringify(body);
|
|
180
|
+
}
|
|
181
|
+
const response = await this.fetch(url, { method, headers: reqHeaders, body: reqBody });
|
|
182
|
+
const text = await response.text();
|
|
183
|
+
let parsed = null;
|
|
184
|
+
if (text) {
|
|
185
|
+
try {
|
|
186
|
+
parsed = JSON.parse(text);
|
|
187
|
+
} catch {
|
|
188
|
+
parsed = { error: text };
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
if (!response.ok) {
|
|
192
|
+
throw new RayTraceError(
|
|
193
|
+
(parsed && parsed.error) || `RayTrace API error (HTTP ${response.status})`,
|
|
194
|
+
{
|
|
195
|
+
status: response.status,
|
|
196
|
+
code: (parsed && parsed.code) || null,
|
|
197
|
+
topupUrl: (parsed && parsed.topup_url) || null,
|
|
198
|
+
body: parsed,
|
|
199
|
+
},
|
|
200
|
+
);
|
|
201
|
+
}
|
|
202
|
+
return { status: response.status, data: parsed };
|
|
203
|
+
}
|
|
204
|
+
}
|
package/src/index.d.ts
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
export type SandboxSize = 'small' | 'medium' | 'large';
|
|
2
|
+
|
|
3
|
+
export interface RayTraceOptions {
|
|
4
|
+
apiKey?: string;
|
|
5
|
+
baseUrl?: string;
|
|
6
|
+
fetchImpl?: typeof fetch;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export class RayTraceError extends Error {
|
|
10
|
+
status: number;
|
|
11
|
+
code: string | null;
|
|
12
|
+
topupUrl: string | null;
|
|
13
|
+
body: unknown;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface SandboxSummary {
|
|
17
|
+
id: string;
|
|
18
|
+
name: string;
|
|
19
|
+
status: string;
|
|
20
|
+
size: SandboxSize;
|
|
21
|
+
created: number;
|
|
22
|
+
host?: string;
|
|
23
|
+
release?: string;
|
|
24
|
+
run_id?: string;
|
|
25
|
+
paid_until?: number;
|
|
26
|
+
restoring?: boolean;
|
|
27
|
+
restored_from_archive?: boolean;
|
|
28
|
+
restore_warning?: string;
|
|
29
|
+
restore_error?: string;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface CreateSandboxOptions {
|
|
33
|
+
name?: string;
|
|
34
|
+
size?: SandboxSize;
|
|
35
|
+
archive?: Uint8Array;
|
|
36
|
+
files?: Record<string, string | Uint8Array>;
|
|
37
|
+
dir?: string;
|
|
38
|
+
/** Clone this repository and upload it: an https or ssh URL, or `owner/name` on GitHub. Uses this machine's git and its credentials. */
|
|
39
|
+
repo?: string;
|
|
40
|
+
/** With `repo`: the branch or tag to clone (default: the repository's default branch). */
|
|
41
|
+
ref?: string;
|
|
42
|
+
idempotencyKey?: string;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface ExecOptions {
|
|
46
|
+
timeoutSeconds?: number;
|
|
47
|
+
pollIntervalMs?: number;
|
|
48
|
+
requestId?: string;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export interface ExecResult {
|
|
52
|
+
commandId: string;
|
|
53
|
+
state: 'completed' | 'cancelled' | 'timed_out' | 'interrupted';
|
|
54
|
+
exitCode: number | null;
|
|
55
|
+
stdout: string;
|
|
56
|
+
stderr: string;
|
|
57
|
+
timedOut: boolean;
|
|
58
|
+
outputTruncated: boolean;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export interface UsageSummary {
|
|
62
|
+
days: number;
|
|
63
|
+
at: number;
|
|
64
|
+
wallet: {
|
|
65
|
+
balance_micros: number;
|
|
66
|
+
balance_usd: number;
|
|
67
|
+
paid_micros: number;
|
|
68
|
+
matched_micros: number;
|
|
69
|
+
refundable_micros: number;
|
|
70
|
+
refundable_usd: number;
|
|
71
|
+
burn_rate_micros_per_hour: number;
|
|
72
|
+
low_balance: boolean;
|
|
73
|
+
} | null;
|
|
74
|
+
burn_rate_micros_per_hour: number;
|
|
75
|
+
burn_rate_usd_per_hour: number;
|
|
76
|
+
running_sandboxes: number;
|
|
77
|
+
blocks_this_month: number;
|
|
78
|
+
spend_this_month_micros: number;
|
|
79
|
+
spend_this_month_usd: number;
|
|
80
|
+
ledger: Array<{ id: string; amount_micros: number; amount_usd: number; kind: string; ref: string; created: number; note: string | null }>;
|
|
81
|
+
spend_by_sandbox: Array<{ sandbox_id: string; name: string; size: SandboxSize; status: string; blocks: number; amount_micros: number; amount_usd: number; runs: number }>;
|
|
82
|
+
spend_by_day: Array<{ day: string; blocks: number; amount_micros: number; amount_usd: number }>;
|
|
83
|
+
runs: Array<{ id: string; sandbox_id: string; name: string; size: SandboxSize; started_at: number; stopped_at: number | null; paid_until: number; blocks_charged: number; stop_reason: string | null }>;
|
|
84
|
+
archives: Array<{ sandbox_id: string; name: string; run_id: string; status: string; image_release: string; bytes: number | null; created: number; uploaded: number | null }>;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export interface ApiKeySummary {
|
|
88
|
+
id: string;
|
|
89
|
+
org_id: string;
|
|
90
|
+
name: string;
|
|
91
|
+
prefix: string;
|
|
92
|
+
created_by: string | null;
|
|
93
|
+
created: number;
|
|
94
|
+
last_used: number | null;
|
|
95
|
+
revoked: number | null;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export interface ApiKeyCreated extends ApiKeySummary {
|
|
99
|
+
key: string;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export class Sandbox {
|
|
103
|
+
readonly id: string;
|
|
104
|
+
info: SandboxSummary;
|
|
105
|
+
readonly status: string;
|
|
106
|
+
readonly size: SandboxSize;
|
|
107
|
+
readonly name: string;
|
|
108
|
+
exec(command: string, options?: ExecOptions): Promise<ExecResult>;
|
|
109
|
+
start(options?: { size?: SandboxSize; waitForRestore?: boolean; pollIntervalMs?: number }): Promise<SandboxSummary>;
|
|
110
|
+
stop(): Promise<SandboxSummary>;
|
|
111
|
+
keepAlive(minutes: number): Promise<Record<string, unknown>>;
|
|
112
|
+
destroy(options?: { keepTraces?: boolean }): Promise<Record<string, unknown>>;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export class RayTraceClient {
|
|
116
|
+
constructor(options?: RayTraceOptions);
|
|
117
|
+
request(method: string, path: string, options?: { headers?: Record<string, string>; body?: unknown }): Promise<{ status: number; data: any }>;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export class RayTrace {
|
|
121
|
+
readonly client: RayTraceClient;
|
|
122
|
+
readonly sandboxes: {
|
|
123
|
+
list(): Promise<Sandbox[]>;
|
|
124
|
+
get(id: string): Promise<Sandbox>;
|
|
125
|
+
create(options: CreateSandboxOptions): Promise<Sandbox>;
|
|
126
|
+
};
|
|
127
|
+
readonly usage: {
|
|
128
|
+
get(options?: { days?: number }): Promise<UsageSummary>;
|
|
129
|
+
};
|
|
130
|
+
readonly apiKeys: {
|
|
131
|
+
create(name: string): Promise<ApiKeyCreated>;
|
|
132
|
+
list(): Promise<ApiKeySummary[]>;
|
|
133
|
+
revoke(id: string): Promise<{ id: string; revoked: boolean }>;
|
|
134
|
+
};
|
|
135
|
+
constructor(options?: RayTraceOptions);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export function buildTarGz(files: Record<string, string | Uint8Array>): Buffer;
|
|
139
|
+
export function archiveFromDirectory(dirPath: string): Buffer;
|
|
140
|
+
export function archiveFromRepo(repo: string, options?: { ref?: string }): Promise<Buffer>;
|
|
141
|
+
export default RayTrace;
|
package/src/index.mjs
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
// @raytrace-cli/sdk — Typed high-level SDK over RayTrace's frozen /v1 API.
|
|
2
|
+
import { randomBytes } from 'node:crypto';
|
|
3
|
+
import { RayTraceClient, RayTraceError, buildTarGz, archiveFromDirectory, archiveFromRepo, repoName } from './client.mjs';
|
|
4
|
+
|
|
5
|
+
export { RayTraceClient, RayTraceError, buildTarGz, archiveFromDirectory, archiveFromRepo };
|
|
6
|
+
|
|
7
|
+
const TERMINAL_STATES = new Set(['completed', 'cancelled', 'timed_out', 'interrupted']);
|
|
8
|
+
|
|
9
|
+
function sleep(ms) {
|
|
10
|
+
return new Promise(resolve => setTimeout(resolve, ms));
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function makeRequestId() {
|
|
14
|
+
return `req_${randomBytes(12).toString('hex')}`;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export class Sandbox {
|
|
18
|
+
constructor(client, info) {
|
|
19
|
+
this._client = client;
|
|
20
|
+
this.id = info.id;
|
|
21
|
+
this.info = info;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
get status() { return this.info.status; }
|
|
25
|
+
get size() { return this.info.size || 'small'; }
|
|
26
|
+
get name() { return this.info.name; }
|
|
27
|
+
|
|
28
|
+
async exec(command, { timeoutSeconds = 120, pollIntervalMs = 250, requestId = makeRequestId() } = {}) {
|
|
29
|
+
const { data: created } = await this._client.request(
|
|
30
|
+
'POST',
|
|
31
|
+
`/v1/sandboxes/${encodeURIComponent(this.id)}/commands`,
|
|
32
|
+
{ body: { command, timeout_seconds: timeoutSeconds, request_id: requestId } },
|
|
33
|
+
);
|
|
34
|
+
let job = created;
|
|
35
|
+
while (!TERMINAL_STATES.has(job.state)) {
|
|
36
|
+
await sleep(pollIntervalMs);
|
|
37
|
+
const { data: latest } = await this._client.request(
|
|
38
|
+
'GET',
|
|
39
|
+
`/v1/sandboxes/${encodeURIComponent(this.id)}/commands/${encodeURIComponent(job.command_id)}`,
|
|
40
|
+
);
|
|
41
|
+
job = latest;
|
|
42
|
+
}
|
|
43
|
+
return {
|
|
44
|
+
commandId: job.command_id,
|
|
45
|
+
state: job.state,
|
|
46
|
+
exitCode: job.exit_code,
|
|
47
|
+
stdout: job.stdout || '',
|
|
48
|
+
stderr: job.stderr || '',
|
|
49
|
+
timedOut: Boolean(job.timed_out),
|
|
50
|
+
outputTruncated: Boolean(job.output_truncated),
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
async start({ size = undefined, waitForRestore = true, pollIntervalMs = 500 } = {}) {
|
|
55
|
+
const body = size ? { size } : {};
|
|
56
|
+
const { status, data } = await this._client.request(
|
|
57
|
+
'POST',
|
|
58
|
+
`/v1/sandboxes/${encodeURIComponent(this.id)}/start`,
|
|
59
|
+
{ body },
|
|
60
|
+
);
|
|
61
|
+
this.info = { ...this.info, ...data };
|
|
62
|
+
if (status === 202 && data?.restoring && waitForRestore) {
|
|
63
|
+
while (true) {
|
|
64
|
+
await sleep(pollIntervalMs);
|
|
65
|
+
const { data: list } = await this._client.request('GET', '/v1/sandboxes');
|
|
66
|
+
const current = (list || []).find(item => item.id === this.id);
|
|
67
|
+
if (!current) break;
|
|
68
|
+
this.info = current;
|
|
69
|
+
if (current.status === 'running' || current.restore_error || current.status === 'archived') {
|
|
70
|
+
if (current.restore_error) {
|
|
71
|
+
throw new RayTraceError(`Archive restore failed: ${current.restore_error}`, { status: 500, body: current });
|
|
72
|
+
}
|
|
73
|
+
break;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return this.info;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
async stop() {
|
|
81
|
+
const { data } = await this._client.request('POST', `/v1/sandboxes/${encodeURIComponent(this.id)}/stop`);
|
|
82
|
+
this.info = { ...this.info, ...data };
|
|
83
|
+
return this.info;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
async keepAlive(minutes) {
|
|
87
|
+
const { data } = await this._client.request(
|
|
88
|
+
'POST',
|
|
89
|
+
`/v1/sandboxes/${encodeURIComponent(this.id)}/keep-alive`,
|
|
90
|
+
{ body: { minutes } },
|
|
91
|
+
);
|
|
92
|
+
return data;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
async destroy({ keepTraces = false } = {}) {
|
|
96
|
+
const qs = keepTraces ? '?keep_traces=1' : '';
|
|
97
|
+
const { data } = await this._client.request('DELETE', `/v1/sandboxes/${encodeURIComponent(this.id)}${qs}`);
|
|
98
|
+
this.info = { ...this.info, ...data, status: 'deleted' };
|
|
99
|
+
return data;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
class SandboxesResource {
|
|
104
|
+
constructor(client) {
|
|
105
|
+
this._client = client;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
async list() {
|
|
109
|
+
const { data } = await this._client.request('GET', '/v1/sandboxes');
|
|
110
|
+
return (data || []).map(item => new Sandbox(this._client, item));
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
async get(id) {
|
|
114
|
+
const all = await this.list();
|
|
115
|
+
const found = all.find(sb => sb.id === id);
|
|
116
|
+
if (!found) throw new RayTraceError(`Sandbox not found: ${id}`, { status: 404 });
|
|
117
|
+
return found;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
async create({ name = undefined, size = 'small', archive = undefined, files = undefined, dir = undefined, repo = undefined, ref = undefined, idempotencyKey = undefined } = {}) {
|
|
121
|
+
let payload = archive;
|
|
122
|
+
if (!payload) {
|
|
123
|
+
if (files) {
|
|
124
|
+
payload = buildTarGz(files);
|
|
125
|
+
} else if (dir) {
|
|
126
|
+
payload = archiveFromDirectory(dir);
|
|
127
|
+
} else if (repo) {
|
|
128
|
+
payload = await archiveFromRepo(repo, { ref });
|
|
129
|
+
} else {
|
|
130
|
+
throw new Error('Provide one of { archive, files, dir, repo } to create a sandbox');
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
const derivedName = name || (repo ? repoName(repo) : 'sandbox');
|
|
134
|
+
const cleanName = String(derivedName).replace(/[^A-Za-z0-9._ -]/g, '-').slice(0, 100) || 'sandbox';
|
|
135
|
+
const headers = {
|
|
136
|
+
'Content-Type': 'application/gzip',
|
|
137
|
+
'X-RayTrace-Name': cleanName,
|
|
138
|
+
'X-RayTrace-Size': size,
|
|
139
|
+
};
|
|
140
|
+
if (idempotencyKey) headers['Idempotency-Key'] = idempotencyKey;
|
|
141
|
+
const { data } = await this._client.request('POST', '/v1/sandboxes', { headers, body: payload });
|
|
142
|
+
return new Sandbox(this._client, data);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
class UsageResource {
|
|
147
|
+
constructor(client) {
|
|
148
|
+
this._client = client;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
async get({ days = 30 } = {}) {
|
|
152
|
+
const { data } = await this._client.request('GET', `/v1/usage?days=${encodeURIComponent(days)}`);
|
|
153
|
+
return data;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
class ApiKeysResource {
|
|
158
|
+
constructor(client) {
|
|
159
|
+
this._client = client;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
async create(name) {
|
|
163
|
+
const { data } = await this._client.request('POST', '/v1/api-keys', { body: { name } });
|
|
164
|
+
return data;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
async list() {
|
|
168
|
+
const { data } = await this._client.request('GET', '/v1/api-keys');
|
|
169
|
+
return data?.keys || [];
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
async revoke(id) {
|
|
173
|
+
const { data } = await this._client.request('DELETE', `/v1/api-keys/${encodeURIComponent(id)}`);
|
|
174
|
+
return data;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
export class RayTrace {
|
|
179
|
+
constructor(options = {}) {
|
|
180
|
+
this.client = new RayTraceClient(options);
|
|
181
|
+
this.sandboxes = new SandboxesResource(this.client);
|
|
182
|
+
this.usage = new UsageResource(this.client);
|
|
183
|
+
this.apiKeys = new ApiKeysResource(this.client);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
export default RayTrace;
|