@raytrace-cli/sdk 0.2.0 → 0.2.2

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
@@ -50,6 +50,30 @@ await sandbox.stop();
50
50
 
51
51
  Sizes are `small`, `medium` and `large`.
52
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
+
53
77
  ## Usage and keys
54
78
 
55
79
  ```js
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@raytrace-cli/sdk",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
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",
package/src/client.mjs CHANGED
@@ -108,6 +108,56 @@ export function repoName(repo) {
108
108
  return String(repo).replace(/\/+$/, '').split(/[/:]/).filter(Boolean).pop().replace(/\.git$/, '') || 'sandbox';
109
109
  }
110
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
+
111
161
  /**
112
162
  * Clones `repo` (shallow; `ref` is a branch or tag) into a temporary folder and
113
163
  * packs it like archiveFromDirectory, then deletes the clone. Uses the git on
package/src/index.d.ts CHANGED
@@ -39,6 +39,14 @@ export interface CreateSandboxOptions {
39
39
  repo?: string;
40
40
  /** With `repo`: the branch or tag to clone (default: the repository's default branch). */
41
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;
42
50
  idempotencyKey?: string;
43
51
  }
44
52
 
@@ -99,13 +107,33 @@ export interface ApiKeyCreated extends ApiKeySummary {
99
107
  key: string;
100
108
  }
101
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
+
102
125
  export class Sandbox {
103
126
  readonly id: string;
127
+ readonly repos: SandboxRepos;
128
+ /** Set by create({ connect: true }). */
129
+ git?: ConnectedRepo;
104
130
  info: SandboxSummary;
105
131
  readonly status: string;
106
132
  readonly size: SandboxSize;
107
133
  readonly name: string;
108
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>;
109
137
  start(options?: { size?: SandboxSize; waitForRestore?: boolean; pollIntervalMs?: number }): Promise<SandboxSummary>;
110
138
  stop(): Promise<SandboxSummary>;
111
139
  keepAlive(minutes: number): Promise<Record<string, unknown>>;
@@ -138,4 +166,10 @@ export class RayTrace {
138
166
  export function buildTarGz(files: Record<string, string | Uint8Array>): Buffer;
139
167
  export function archiveFromDirectory(dirPath: string): Buffer;
140
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;
141
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, archiveFromRepo, repoName } 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, archiveFromRepo };
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; }
@@ -32,7 +58,7 @@ export class Sandbox {
32
58
  { body: { command, timeout_seconds: timeoutSeconds, request_id: requestId } },
33
59
  );
34
60
  let job = created;
35
- while (!TERMINAL_STATES.has(job.state)) {
61
+ while (!TERMINAL_STATES.has(job.state) || job.recovery_pending) {
36
62
  await sleep(pollIntervalMs);
37
63
  const { data: latest } = await this._client.request(
38
64
  'GET',
@@ -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(
@@ -64,12 +110,12 @@ export class Sandbox {
64
110
  await sleep(pollIntervalMs);
65
111
  const { data: list } = await this._client.request('GET', '/v1/sandboxes');
66
112
  const current = (list || []).find(item => item.id === this.id);
67
- if (!current) break;
113
+ if (!current) throw new RayTraceError(`Sandbox ${this.id} disappeared while restoring`, { status: 404 });
68
114
  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
- }
115
+ if (current.restore_error) {
116
+ throw new RayTraceError(`Archive restore failed: ${current.restore_error}`, { status: 500, body: current });
117
+ }
118
+ if (!current.restoring && (current.status === 'running' || current.status === 'archived')) {
73
119
  break;
74
120
  }
75
121
  }
@@ -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, ref = 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) {
@@ -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