@raytrace-cli/sdk 0.1.0 → 0.2.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
@@ -39,6 +39,7 @@ await sandbox.stop();
39
39
  | Call | What it does |
40
40
  | --- | --- |
41
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 |
42
43
  | `rt.sandboxes.list()` / `rt.sandboxes.get(id)` | Your organization's sandboxes |
43
44
  | `sandbox.exec(command, { timeoutSeconds })` | Runs a command and waits for `{ exitCode, stdout, stderr, state }` |
44
45
  | `sandbox.stop()` | Stops it; files are kept and billing stops |
@@ -49,6 +50,30 @@ await sandbox.stop();
49
50
 
50
51
  Sizes are `small`, `medium` and `large`.
51
52
 
53
+ ## Connect GitHub
54
+
55
+ A sandbox can clone, fetch and push a GitHub repository without any GitHub
56
+ key inside it: its git goes through RayTrace, which opens the repositories
57
+ attached to it with your organization's RayTrace GitHub App. First, an org
58
+ admin installs the App on the repositories and connects it on the
59
+ [account page](https://raytracer.si/account.html).
60
+
61
+ ```js
62
+ const sandbox = await rt.sandboxes.create({ repo: 'acme/app', connect: true });
63
+ sandbox.git; // { repo: 'acme/app', branch: 'raytrace/1a2b3c4d/work', ... }
64
+ await sandbox.exec('git commit -am "Fix" && git push -u origin HEAD');
65
+ ```
66
+
67
+ | Call | What it does |
68
+ | --- | --- |
69
+ | `rt.sandboxes.create({ repo, connect: true })` | Uploads, then attaches `repo` and makes `/workspace` a clone of it on its work branch. With `dir` or `files`, those are uploaded and `repo` is what it is connected to |
70
+ | `sandbox.connectRepo(repo, { ref, commit })` | The same for a sandbox that exists |
71
+ | `sandbox.repos.list()` / `sandbox.repos.set([...])` | The repositories its git may open; `set` replaces the list, `[]` takes them all off |
72
+
73
+ An agent in the sandbox pushes only to branches under `raytrace/<8 characters
74
+ of the sandbox id>/`; anything else, including `main`, is refused, and no branch
75
+ can be deleted. Every clone, fetch and push is recorded with the sandbox's evidence.
76
+
52
77
  ## Usage and keys
53
78
 
54
79
  ```js
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@raytrace-cli/sdk",
3
- "version": "0.1.0",
3
+ "version": "0.2.1",
4
4
  "description": "TypeScript/JavaScript SDK for RayTrace cloud sandboxes: create, run commands, stop, start and destroy over the /v1 API",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -11,7 +11,12 @@
11
11
  "directory": "sdk/ts"
12
12
  },
13
13
  "bugs": "https://github.com/Godcreatebugs/raytrace-cli/issues",
14
- "keywords": ["raytrace", "sandbox", "coding-agents", "sdk"],
14
+ "keywords": [
15
+ "raytrace",
16
+ "sandbox",
17
+ "coding-agents",
18
+ "sdk"
19
+ ],
15
20
  "engines": {
16
21
  "node": ">=20.0.0"
17
22
  },
package/src/client.mjs CHANGED
@@ -1,8 +1,11 @@
1
1
  // Shared low-level /v1 HTTP client for @raytrace-cli/sdk.
2
2
  // Zero runtime dependencies (Node 20+ native fetch + zlib + crypto).
3
3
  import { gzipSync } from 'node:zlib';
4
- import { readdirSync, readFileSync, statSync } from 'node:fs';
4
+ import { mkdtempSync, readdirSync, readFileSync, rmSync, statSync } from 'node:fs';
5
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';
6
9
 
7
10
  export const DEFAULT_BASE_URL = 'https://api.raytracer.si';
8
11
 
@@ -87,6 +90,98 @@ export function buildTarGz(files) {
87
90
  return gzipSync(Buffer.concat(chunks));
88
91
  }
89
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
+ // GitHub's rules for account and repository names (RayTrace's API checks the same).
112
+ const GITHUB_NAME = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})\/[A-Za-z0-9._-]{1,100}$/;
113
+ const GITHUB_URL = /^(?:https:\/\/github\.com\/|ssh:\/\/git@github\.com\/|git@github\.com:)?([^/\s]+\/[^/\s]+?)(?:\.git)?\/?$/i;
114
+
115
+ /** `owner/name` for a GitHub repository given as owner/name or a github.com https or ssh URL; null for anything else. */
116
+ export function githubRepo(repo) {
117
+ const name = GITHUB_URL.exec(String(repo ?? '').trim())?.[1];
118
+ if (!name || !GITHUB_NAME.test(name) || ['.', '..'].includes(name.split('/')[1])) return null;
119
+ return name;
120
+ }
121
+
122
+ /** The branch a connected sandbox works on. Its agent may push only to raytrace/<these 8 characters>/... */
123
+ export function workBranch(sandboxId) {
124
+ return `raytrace/${String(sandboxId).slice(4, 12)}/work`;
125
+ }
126
+
127
+ const GIT_REF = /^(?!-)(?!.*\.\.)[A-Za-z0-9._/-]{1,200}$/;
128
+ const GIT_COMMIT = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
129
+ const quote = (value) => `'${String(value).replace(/'/g, `'\\''`)}'`;
130
+
131
+ /**
132
+ * The shell commands that turn a sandbox's uploaded files into a clone of
133
+ * `repo`: a Git repository whose origin is GitHub (the sandbox's relay opens
134
+ * it), lined up with `commit` (when GitHub has it), else `ref`, else the
135
+ * default branch, on a branch of its own. The uploaded files stay as they are;
136
+ * a file the upload left out (a secret, say) is taken from the commit, so it
137
+ * is not committed as deleted. A folder that is already a repository is left alone.
138
+ */
139
+ export function connectScript({ repo, sandboxId, ref = undefined, commit = undefined, dir = '/workspace' }) {
140
+ const name = githubRepo(repo);
141
+ if (!name) throw new Error(`Not a GitHub repository: ${repo} (use owner/name)`);
142
+ if (ref !== undefined && !GIT_REF.test(String(ref))) throw new Error(`Not a branch or tag name: ${ref}`);
143
+ if (commit !== undefined && !GIT_COMMIT.test(String(commit))) throw new Error(`Not a commit id: ${commit}`);
144
+ const fallback = quote(ref ?? 'HEAD');
145
+ const branch = workBranch(sandboxId);
146
+ return [
147
+ 'set -e',
148
+ `cd ${quote(dir)}`,
149
+ `if [ -e .git ]; then echo "RayTrace: $(pwd) is already a Git repository; left as it is." >&2; exit 0; fi`,
150
+ 'git -c init.defaultBranch=main init -q',
151
+ `git remote add origin ${quote(`https://github.com/${name}.git`)}`,
152
+ commit ? `git fetch -q --depth 1 origin ${commit} 2>/dev/null || git fetch -q --depth 1 origin ${fallback}`
153
+ : `git fetch -q --depth 1 origin ${fallback}`,
154
+ 'git reset -q FETCH_HEAD',
155
+ 'if [ -n "$(git ls-files --deleted)" ]; then git ls-files -z --deleted | git checkout -q --pathspec-from-file=- --pathspec-file-nul; fi',
156
+ `git checkout -q -b ${quote(branch)}`,
157
+ `echo ${quote(`Connected to ${name} on branch ${branch}. Push with: git push -u origin ${branch}`)}`,
158
+ ].join('\n');
159
+ }
160
+
161
+ /**
162
+ * Clones `repo` (shallow; `ref` is a branch or tag) into a temporary folder and
163
+ * packs it like archiveFromDirectory, then deletes the clone. Uses the git on
164
+ * this machine and its credentials, so private repositories work wherever
165
+ * `git clone` does; it never waits for a password prompt.
166
+ */
167
+ export async function archiveFromRepo(repo, { ref = undefined } = {}) {
168
+ const dir = mkdtempSync(join(tmpdir(), 'raytrace-repo-'));
169
+ try {
170
+ const args = ['clone', '--depth', '1', '--quiet'];
171
+ if (ref) args.push('--branch', String(ref));
172
+ args.push('--', repoUrl(repo), join(dir, 'repo'));
173
+ try {
174
+ await promisify(execFile)('git', args, { env: { ...process.env, ...GIT_ENV }, timeout: 300_000, maxBuffer: 1 << 20 });
175
+ } catch (error) {
176
+ if (error.code === 'ENOENT') throw new Error('Creating a sandbox from a repo needs git installed on this machine');
177
+ throw new Error(`Could not clone ${repo}: ${String(error.stderr || error.message).trim()}`);
178
+ }
179
+ return archiveFromDirectory(join(dir, 'repo'));
180
+ } finally {
181
+ rmSync(dir, { recursive: true, force: true });
182
+ }
183
+ }
184
+
90
185
  export function archiveFromDirectory(dirPath) {
91
186
  const files = {};
92
187
  function walk(absDir, relPrefix) {
package/src/index.d.ts CHANGED
@@ -35,7 +35,18 @@ export interface CreateSandboxOptions {
35
35
  archive?: Uint8Array;
36
36
  files?: Record<string, string | Uint8Array>;
37
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. */
38
39
  repo?: string;
40
+ /** With `repo`: the branch or tag to clone (default: the repository's default branch). */
41
+ ref?: string;
42
+ /**
43
+ * With `repo` as a GitHub repository: after the upload, attach it and make
44
+ * /workspace a clone of it on the branch the agent may push to
45
+ * (`raytrace/<id[4:12]>/work`). Needs the RayTrace GitHub App installed on
46
+ * it and connected on your account page. With `dir` or `files`, those are
47
+ * what is uploaded and `repo` is only what it is connected to.
48
+ */
49
+ connect?: boolean;
39
50
  idempotencyKey?: string;
40
51
  }
41
52
 
@@ -96,13 +107,33 @@ export interface ApiKeyCreated extends ApiKeySummary {
96
107
  key: string;
97
108
  }
98
109
 
110
+ export interface ConnectedRepo {
111
+ /** owner/name */
112
+ repo: string;
113
+ /** The branch /workspace is on, under the only prefix the sandbox may push to. */
114
+ branch: string;
115
+ output: string;
116
+ }
117
+
118
+ export interface SandboxRepos {
119
+ /** The GitHub repositories (owner/name) this sandbox's git may open. */
120
+ list(): Promise<string[]>;
121
+ /** Replaces the whole list; [] takes them all off. Each must be one the org's GitHub App is installed on. */
122
+ set(repos: string[]): Promise<string[]>;
123
+ }
124
+
99
125
  export class Sandbox {
100
126
  readonly id: string;
127
+ readonly repos: SandboxRepos;
128
+ /** Set by create({ connect: true }). */
129
+ git?: ConnectedRepo;
101
130
  info: SandboxSummary;
102
131
  readonly status: string;
103
132
  readonly size: SandboxSize;
104
133
  readonly name: string;
105
134
  exec(command: string, options?: ExecOptions): Promise<ExecResult>;
135
+ /** Attaches a GitHub repository and makes /workspace a clone of it (see CreateSandboxOptions.connect). */
136
+ connectRepo(repo: string, options?: { ref?: string; commit?: string; timeoutSeconds?: number }): Promise<ConnectedRepo>;
106
137
  start(options?: { size?: SandboxSize; waitForRestore?: boolean; pollIntervalMs?: number }): Promise<SandboxSummary>;
107
138
  stop(): Promise<SandboxSummary>;
108
139
  keepAlive(minutes: number): Promise<Record<string, unknown>>;
@@ -134,4 +165,11 @@ export class RayTrace {
134
165
 
135
166
  export function buildTarGz(files: Record<string, string | Uint8Array>): Buffer;
136
167
  export function archiveFromDirectory(dirPath: string): Buffer;
168
+ export function archiveFromRepo(repo: string, options?: { ref?: string }): Promise<Buffer>;
169
+ /** owner/name for owner/name or a github.com https or ssh URL; null for anything else. */
170
+ export function githubRepo(repo: string): string | null;
171
+ /** The branch a connected sandbox works on: raytrace/<id[4:12]>/work. */
172
+ export function workBranch(sandboxId: string): string;
173
+ /** The shell commands connectRepo runs in the sandbox. */
174
+ export function connectScript(options: { repo: string; sandboxId: string; ref?: string; commit?: string; dir?: string }): string;
137
175
  export default RayTrace;
package/src/index.mjs CHANGED
@@ -1,8 +1,8 @@
1
1
  // @raytrace-cli/sdk — Typed high-level SDK over RayTrace's frozen /v1 API.
2
2
  import { randomBytes } from 'node:crypto';
3
- import { RayTraceClient, RayTraceError, buildTarGz, archiveFromDirectory } from './client.mjs';
3
+ import { RayTraceClient, RayTraceError, buildTarGz, archiveFromDirectory, archiveFromRepo, repoName, githubRepo, workBranch, connectScript } from './client.mjs';
4
4
 
5
- export { RayTraceClient, RayTraceError, buildTarGz, archiveFromDirectory };
5
+ export { RayTraceClient, RayTraceError, buildTarGz, archiveFromDirectory, archiveFromRepo, githubRepo, workBranch, connectScript };
6
6
 
7
7
  const TERMINAL_STATES = new Set(['completed', 'cancelled', 'timed_out', 'interrupted']);
8
8
 
@@ -14,11 +14,37 @@ function makeRequestId() {
14
14
  return `req_${randomBytes(12).toString('hex')}`;
15
15
  }
16
16
 
17
+ /** The GitHub repositories a sandbox's git may open (through its relay, with the org's GitHub App). */
18
+ class SandboxRepos {
19
+ constructor(client, id) {
20
+ this._client = client;
21
+ this._path = `/v1/sandboxes/${encodeURIComponent(id)}/repos`;
22
+ }
23
+
24
+ async list() {
25
+ const { data } = await this._client.request('GET', this._path);
26
+ return data?.repos || [];
27
+ }
28
+
29
+ /** Replaces the whole list; [] takes them all off. Each must be one the org's GitHub App is installed on. */
30
+ async set(repos) {
31
+ if (!Array.isArray(repos)) throw new Error('repos.set takes a list of GitHub repositories (owner/name)');
32
+ const names = repos.map((repo) => {
33
+ const name = githubRepo(repo);
34
+ if (!name) throw new Error(`Not a GitHub repository: ${repo} (use owner/name)`);
35
+ return name;
36
+ });
37
+ const { data } = await this._client.request('PUT', this._path, { body: { repos: names } });
38
+ return data?.repos || [];
39
+ }
40
+ }
41
+
17
42
  export class Sandbox {
18
43
  constructor(client, info) {
19
44
  this._client = client;
20
45
  this.id = info.id;
21
46
  this.info = info;
47
+ this.repos = new SandboxRepos(client, info.id);
22
48
  }
23
49
 
24
50
  get status() { return this.info.status; }
@@ -51,6 +77,26 @@ export class Sandbox {
51
77
  };
52
78
  }
53
79
 
80
+ /**
81
+ * Connects this sandbox to a GitHub repository: attaches it (keeping any
82
+ * already attached), then makes /workspace a clone of it on the branch the
83
+ * agent may push to (workBranch). `commit` lines the files up with that
84
+ * commit when GitHub has it, else `ref`, else the default branch.
85
+ */
86
+ async connectRepo(repo, { ref = undefined, commit = undefined, timeoutSeconds = 300 } = {}) {
87
+ const name = githubRepo(repo);
88
+ if (!name) throw new Error(`Not a GitHub repository: ${repo} (use owner/name)`);
89
+ const script = connectScript({ repo: name, sandboxId: this.id, ref, commit });
90
+ const attached = await this.repos.list();
91
+ if (!attached.some((other) => other.toLowerCase() === name.toLowerCase())) await this.repos.set([...attached, name]);
92
+ const result = await this.exec(script, { timeoutSeconds });
93
+ if (result.exitCode !== 0) {
94
+ const why = result.stderr.trim() || result.stdout.trim() || `the setup command ended ${result.state}`;
95
+ throw new RayTraceError(`Could not connect ${this.id} to ${name}: ${why}`, { body: result });
96
+ }
97
+ return { repo: name, branch: workBranch(this.id), output: result.stdout };
98
+ }
99
+
54
100
  async start({ size = undefined, waitForRestore = true, pollIntervalMs = 500 } = {}) {
55
101
  const body = size ? { size } : {};
56
102
  const { status, data } = await this._client.request(
@@ -117,7 +163,12 @@ class SandboxesResource {
117
163
  return found;
118
164
  }
119
165
 
120
- async create({ name = undefined, size = 'small', archive = undefined, files = undefined, dir = undefined, repo = undefined, idempotencyKey = undefined } = {}) {
166
+ async create({ name = undefined, size = 'small', archive = undefined, files = undefined, dir = undefined, repo = undefined, ref = undefined, connect = false, idempotencyKey = undefined } = {}) {
167
+ if (connect) {
168
+ // Checked before anything is uploaded: connectScript throws on a ref it would not run.
169
+ if (!githubRepo(repo)) throw new Error('connect needs repo: a GitHub repository, as owner/name');
170
+ connectScript({ repo, sandboxId: '', ref });
171
+ }
121
172
  let payload = archive;
122
173
  if (!payload) {
123
174
  if (files) {
@@ -125,12 +176,12 @@ class SandboxesResource {
125
176
  } else if (dir) {
126
177
  payload = archiveFromDirectory(dir);
127
178
  } else if (repo) {
128
- payload = buildTarGz({ 'README.md': `# ${repo}\n` });
179
+ payload = await archiveFromRepo(repo, { ref });
129
180
  } else {
130
181
  throw new Error('Provide one of { archive, files, dir, repo } to create a sandbox');
131
182
  }
132
183
  }
133
- const derivedName = name || (repo ? String(repo).split('/').filter(Boolean).pop() : 'sandbox');
184
+ const derivedName = name || (repo ? repoName(repo) : 'sandbox');
134
185
  const cleanName = String(derivedName).replace(/[^A-Za-z0-9._ -]/g, '-').slice(0, 100) || 'sandbox';
135
186
  const headers = {
136
187
  'Content-Type': 'application/gzip',
@@ -139,7 +190,18 @@ class SandboxesResource {
139
190
  };
140
191
  if (idempotencyKey) headers['Idempotency-Key'] = idempotencyKey;
141
192
  const { data } = await this._client.request('POST', '/v1/sandboxes', { headers, body: payload });
142
- return new Sandbox(this._client, data);
193
+ const sandbox = new Sandbox(this._client, data);
194
+ if (connect) {
195
+ try {
196
+ sandbox.git = await sandbox.connectRepo(repo, { ref });
197
+ } catch (error) {
198
+ // The sandbox exists either way: say so, and hand it over to retry or destroy.
199
+ error.message = `Sandbox ${sandbox.id} was created, but ${error.message.replace(/^Could not/, 'could not')}`;
200
+ error.sandbox = sandbox;
201
+ throw error;
202
+ }
203
+ }
204
+ return sandbox;
143
205
  }
144
206
  }
145
207