@quietrobot/sandboxes 0.2.2 → 0.3.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/dist/index.js CHANGED
@@ -23,7 +23,88 @@ function homePath(p) {
23
23
  return `${HOME}/${p.slice(2)}`;
24
24
  return p.startsWith("/") ? p : `${HOME}/${p}`;
25
25
  }
26
+ /**
27
+ * Channels: messages between your sandboxes, and between them and your own
28
+ * code. Sending to a new name makes a channel. Every reader sees every
29
+ * message (read); take() hands each message to one caller only, for work
30
+ * queues. Outside a sandbox use `new Sandboxes().channels`; inside a sandbox
31
+ * started with { channels: [...] } use `Channels.inSandbox()`, which needs no
32
+ * key.
33
+ */
34
+ export class Channels {
35
+ req;
36
+ /** @internal */
37
+ constructor(req) {
38
+ this.req = req;
39
+ }
40
+ /**
41
+ * Channels from inside a sandbox started with `channels`, through
42
+ * $QR_CHANNELS_URL: no API key, and only this sandbox can use it.
43
+ */
44
+ static inSandbox(opts = {}) {
45
+ const env = typeof process !== "undefined" && process ? process.env : {};
46
+ const base = (opts.url ?? env.QR_CHANNELS_URL ?? "").replace(/\/$/, "");
47
+ if (!base)
48
+ throw new Error("No QR_CHANNELS_URL: start this sandbox with { channels: [\"<name>\"] } to use channels from inside it");
49
+ const f = opts.fetch ?? fetch;
50
+ return new Channels(async (method, path, body) => {
51
+ const res = await f(base + path, {
52
+ method,
53
+ headers: body === undefined ? {} : { "Content-Type": "application/json" },
54
+ body: body === undefined ? undefined : JSON.stringify(body),
55
+ });
56
+ if (!res.ok) {
57
+ const j = (await res.json().catch(() => null));
58
+ throw new SandboxesError(res.status, j?.error?.code ?? "http_error", j?.error?.message ?? `HTTP ${res.status}`);
59
+ }
60
+ return (await res.json());
61
+ });
62
+ }
63
+ /** The channels you can use (inside a sandbox: the ones it was started with). */
64
+ async list() {
65
+ return (await this.req("GET", "/")).channels;
66
+ }
67
+ get(name) {
68
+ return this.req("GET", `/${enc(name)}`);
69
+ }
70
+ /** Sends any JSON value (64 KB at most). Readers waiting on the channel get it at once. */
71
+ send(name, body) {
72
+ return this.req("POST", `/${enc(name)}/messages`, { body });
73
+ }
74
+ /**
75
+ * Messages after `after` (0 = the oldest kept, "latest" = only new ones),
76
+ * oldest first. `wait` (seconds, up to 25) waits for one when there are none
77
+ * yet. Pass `next` back as `after` to carry on.
78
+ */
79
+ read(name, opts = {}) {
80
+ return this.req("GET", `/${enc(name)}/messages${query(opts)}`);
81
+ }
82
+ /** Waits for and yields every new message, in order, until `signal` aborts. */
83
+ async *listen(name, opts = {}) {
84
+ let after = opts.after ?? "latest";
85
+ while (!opts.signal?.aborted) {
86
+ const r = await this.read(name, { after, wait: 25 });
87
+ for (const m of r.messages)
88
+ yield m;
89
+ after = r.next;
90
+ }
91
+ }
92
+ /**
93
+ * Takes the oldest message nobody has (a work queue: one taker per
94
+ * message), or null when none came within `wait` seconds. With leaseSec it
95
+ * is offered again unless you ack() it in time.
96
+ */
97
+ async take(name, opts = {}) {
98
+ return (await this.req("POST", `/${enc(name)}/take`, opts)).message;
99
+ }
100
+ /** Marks a message you took with a lease as done. */
101
+ ack(name, seq) {
102
+ return this.req("POST", `/${enc(name)}/messages/${seq}/ack`);
103
+ }
104
+ }
26
105
  const isoTime = (t) => (t instanceof Date ? t.toISOString() : t);
106
+ /** A run is over in these states. */
107
+ export const RUN_FINISHED = ["done", "failed", "stopped", "cancelled"];
27
108
  export class SandboxesError extends Error {
28
109
  status;
29
110
  code;
@@ -88,10 +169,39 @@ export class Sandboxes {
88
169
  */
89
170
  secrets = {
90
171
  list: async () => (await this.request("GET", "/secrets")).secrets,
91
- /** Adds a secret, or replaces the value and hosts of one with the same name. */
92
- set: (name, value, hosts) => this.request("POST", "/secrets", { name, value, hosts }),
172
+ /**
173
+ * Adds a secret, or replaces the value and hosts of one with the same name.
174
+ * Rules and budget are kept when left out.
175
+ */
176
+ set: (name, value, hosts, opts = {}) => this.request("POST", "/secrets", { name, value, hosts, ...opts }),
177
+ /** Changes a secret's hosts, call rules or budget without sending the value again. */
178
+ update: (name, changes) => this.request("PATCH", `/secrets/${enc(name)}`, changes),
179
+ /**
180
+ * Replaces a secret's value (rolls the key). Allowed hosts, rules and budget
181
+ * are kept unless hosts is given. Where the service can be checked
182
+ * (Anthropic, OpenAI) the new value is tested first; if it's refused the
183
+ * old value stays and this throws SandboxesError with code "key_rejected".
184
+ * Running sandboxes use the new value on their next call.
185
+ */
186
+ roll: (name, value, opts = {}) => this.request("PATCH", `/secrets/${enc(name)}`, { value, ...opts }),
187
+ /**
188
+ * Checks a key with its service. Without value, tests the saved one (a
189
+ * refusal marks it failing, a pass clears that). With value, tests that
190
+ * candidate without saving it or changing anything.
191
+ */
192
+ test: (name, value) => this.request("POST", `/secrets/${enc(name)}/test`, value === undefined ? {} : { value }),
93
193
  delete: (name) => this.request("DELETE", `/secrets/${enc(name)}`),
94
194
  };
195
+ /**
196
+ * Commands a rule is holding until a person decides. Any key can list them;
197
+ * only a person signed in to the dashboard can approve or deny, so a key
198
+ * inside a sandbox can never let its own command through.
199
+ */
200
+ approvals = {
201
+ list: async () => (await this.request("GET", "/approvals")).approvals,
202
+ };
203
+ /** Messages between your sandboxes and your code. Inside a sandbox, use Channels.inSandbox() instead. */
204
+ channels = Object.assign(new Channels((method, path, body) => this.request(method, `/channels${path === "/" ? "" : path}`, body)), { delete: (name) => this.request("DELETE", `/channels/${enc(name)}`) });
95
205
  /** Folders kept between sandboxes. Attach one with create({ volumes: [{ name, path }] }). */
96
206
  volumes = {
97
207
  list: async () => (await this.request("GET", "/volumes")).volumes,
@@ -102,7 +212,7 @@ export class Sandboxes {
102
212
  /** Lifecycle events sent to your own URLs, signed the Standard Webhooks way. Check them with verifyWebhook(). */
103
213
  webhooks = {
104
214
  list: () => this.request("GET", "/webhooks"),
105
- /** The answer carries the signing secret, shown this once. events defaults to sandbox.*, approval.* and volume.save_failed. */
215
+ /** The answer carries the signing secret, shown this once. events defaults to sandbox.*, approval.*, volume.save_failed and run.* (flow runs started, finished, failed, stopped, cancelled or waiting for a person). */
106
216
  create: (opts) => this.request("POST", "/webhooks", opts),
107
217
  get: (id) => this.request("GET", `/webhooks/${enc(id)}`),
108
218
  update: (id, opts) => this.request("PATCH", `/webhooks/${enc(id)}`, opts),
@@ -112,10 +222,157 @@ export class Sandboxes {
112
222
  deliveries: (id) => this.request("GET", `/webhooks/${enc(id)}/deliveries`),
113
223
  redeliver: (id, deliveryId) => this.request("POST", `/webhooks/${enc(id)}/deliveries/${enc(deliveryId)}/redeliver`),
114
224
  };
225
+ /** Loops and graphs: what a graph will do and cost before it runs. */
226
+ graphs = {
227
+ /** The recipes under their old name. Use recipes.list(). */
228
+ templates: async () => (await this.request("GET", "/graph-templates")).templates,
229
+ /**
230
+ * Plays a graph, a recipe or a saved flow 2,000 times (seeded) without
231
+ * starting anything. The answer's forecast says what it will cost, how
232
+ * long it takes, how many loops it makes and which guard stops it.
233
+ */
234
+ simulate: (opts) => this.request("POST", "/graphs/simulate", opts),
235
+ };
236
+ /** Recipes: ready-made flows to start from, by category, each with its default guards. */
237
+ recipes = {
238
+ /** Every recipe, or one level: list({ level: "everyday" }). */
239
+ list: async (opts = {}) => (await this.request("GET", opts.level ? `/recipes?level=${enc(opts.level)}` : "/recipes")).recipes,
240
+ get: (id) => this.request("GET", `/recipes/${enc(id)}`),
241
+ };
242
+ /**
243
+ * Flows: graphs saved from the playground's builder or sent here, with
244
+ * their guards, layout and versions. A flow may be a draft that doesn't run
245
+ * yet; its problem says why.
246
+ */
247
+ flows = {
248
+ /** Your flows, newest change first, without their graphs. */
249
+ list: async () => (await this.request("GET", "/flows")).flows,
250
+ get: (id) => this.request("GET", `/flows/${enc(id)}`),
251
+ /** Saves a new flow from a graph, from a recipe ({ recipe: id }), or blank. Recorded as version 1. */
252
+ create: (opts = {}) => this.request("POST", "/flows", opts),
253
+ /** Saves the flow. Fields left out keep their value. This doesn't record a version: saveVersion and a run of a changed flow do. */
254
+ update: (id, opts) => this.request("PUT", `/flows/${enc(id)}`, opts),
255
+ /** Deletes the flow and its versions. Its runs stay. */
256
+ delete: (id) => this.request("DELETE", `/flows/${enc(id)}`),
257
+ /**
258
+ * Checks a flow without saving or running it: a flow JSON, { flow: id } or
259
+ * { recipe: id }. The same checks as a save and a run, your plan's
260
+ * sandboxes at once, and the steps your Policies will likely hold.
261
+ * valid is false, with problems, when it wouldn't run; nothing throws for that.
262
+ */
263
+ validate: (opts) => this.request("POST", "/flows/validate", opts),
264
+ /**
265
+ * Drafts a flow from plain words, like "Every morning, summarize the news
266
+ * about our competitors and ask me before posting it". Claude drafts it with
267
+ * your own saved Claude key (ANTHROPIC_API_KEY first, or name one in key),
268
+ * and it is checked like any flow. save: true also saves it (flowId).
269
+ */
270
+ draft: (opts) => this.request("POST", "/flows/draft", opts),
271
+ /** The flow JSON, without ids or timestamps. Pass it to create() to make a copy, here or in another organization. */
272
+ export: (id) => this.request("GET", `/flows/${enc(id)}/export`),
273
+ /** The flow JSON's schema (JSON Schema 2020-12), for editors. */
274
+ schema: () => this.request("GET", "/flows/schema"),
275
+ /** The flow's versions, newest first. The newest 50 are kept. */
276
+ versions: async (id) => (await this.request("GET", `/flows/${enc(id)}/versions`)).versions,
277
+ /** One version in full: its graph, guards and layout. */
278
+ version: (id, version) => this.request("GET", `/flows/${enc(id)}/versions/${enc(String(version))}`),
279
+ /** Saves the flow as it is now as a new version, with a note of up to 200 characters. Returns its number. */
280
+ saveVersion: async (id, opts = {}) => (await this.request("POST", `/flows/${enc(id)}/versions`, opts)).version,
281
+ /** Puts a version back: the flow's graph, guards and layout become that version's (the name stays), recorded as a new version. */
282
+ restore: (id, version) => this.request("POST", `/flows/${enc(id)}/restore`, { version }),
283
+ /** Runs the flow, like runs.create({ flow: id }). The run's flowVersion says which version it ran. */
284
+ run: (id, opts = {}) => this.request("POST", `/flows/${enc(id)}/runs`, opts),
285
+ /** The flow's runs, newest first (limit up to 100). */
286
+ runs: async (id, opts = {}) => (await this.request("GET", `/flows/${enc(id)}/runs${query({ limit: opts.limit })}`)).runs,
287
+ /** The flow's triggers: what starts it on its own. */
288
+ triggers: async (id) => (await this.request("GET", `/flows/${enc(id)}/triggers`)).triggers,
289
+ /**
290
+ * Adds a trigger, up to 10 a flow: a webhook, a schedule or GitHub events.
291
+ * secret is in this answer only: the webhook's token (send it in
292
+ * X-QR-Token), or the secret for GitHub's webhook form. Triggers need Pay
293
+ * as you go with a card; otherwise 402 card_required.
294
+ */
295
+ addTrigger: (id, opts) => this.request("POST", `/flows/${enc(id)}/triggers`, opts),
296
+ /** Turns a trigger on or off, or changes its schedule, events or repository. */
297
+ updateTrigger: (id, triggerId, opts) => this.request("PATCH", `/flows/${enc(id)}/triggers/${enc(triggerId)}`, opts),
298
+ deleteTrigger: (id, triggerId) => this.request("DELETE", `/flows/${enc(id)}/triggers/${enc(triggerId)}`),
299
+ /** What a run of the flow will do and cost, like graphs.simulate({ flow: id }). */
300
+ simulate: (id, opts = {}) => this.request("POST", "/graphs/simulate", { flow: id, ...opts }),
301
+ };
302
+ /**
303
+ * GitHub Actions runner pools: each queued job in the repository or
304
+ * organization whose runs-on asks for quietrobot (or quietrobot-4cpu,
305
+ * quietrobot-performance-8cpu, ...) gets a fresh sandbox for that one job,
306
+ * destroyed when the job ends and billed by the second.
307
+ */
308
+ githubRunners = {
309
+ list: async () => (await this.request("GET", "/github-runners")).pools,
310
+ /** The pool and its latest jobs. */
311
+ get: (id, opts = {}) => this.request("GET", `/github-runners/${enc(id)}${query({ limit: opts.limit })}`),
312
+ /** Adds a pool. Paste webhookUrl and webhookSecret into the GitHub webhook form. */
313
+ create: (opts) => this.request("POST", "/github-runners", opts),
314
+ update: (id, opts) => this.request("PATCH", `/github-runners/${enc(id)}`, opts),
315
+ /** Removes the pool; its running runners are stopped. */
316
+ delete: (id) => this.request("DELETE", `/github-runners/${enc(id)}`),
317
+ /** A new webhook secret: the old one stops working at once. */
318
+ rotateSecret: (id) => this.request("POST", `/github-runners/${enc(id)}/rotate-secret`),
319
+ };
320
+ /**
321
+ * Runs play a graph on real sandboxes and stop themselves at a guard
322
+ * (loops, time, spend), checked on the server. An external run is one you
323
+ * play yourself (LangGraph and the like) and report with reportStep.
324
+ */
325
+ runs = {
326
+ /** Starts a run of a graph, of a recipe ({ recipe: id }) or of a saved flow ({ flow: id }). */
327
+ create: (opts) => this.request("POST", "/runs", opts),
328
+ /** Recent runs, newest first (limit up to 100). */
329
+ list: async (opts = {}) => (await this.request("GET", `/runs${query({ limit: opts.limit })}`)).runs,
330
+ /** The run with its steps. */
331
+ get: (id) => this.request("GET", `/runs/${enc(id)}`),
332
+ /** Stops a run; its sandboxes are deleted as usual. */
333
+ cancel: (id) => this.request("POST", `/runs/${enc(id)}/cancel`),
334
+ /** Keeps a finished run's step outputs past your plan's run history. */
335
+ pin: (id) => this.request("POST", `/runs/${enc(id)}/pin`),
336
+ /** Lets a pinned run's outputs be removed with your other old runs. */
337
+ unpin: (id) => this.request("DELETE", `/runs/${enc(id)}/pin`),
338
+ /** Makes a new result link for the files a finished run kept (the old address stops working). */
339
+ link: (id) => this.request("POST", `/runs/${enc(id)}/page`),
340
+ /** Turns a run's result link off at once. */
341
+ unlink: (id) => this.request("DELETE", `/runs/${enc(id)}/page`),
342
+ /** Starts what a finished run built from its last checkpoint and shares its port for an hour. Left out: the flow's graph.serve, else a guess from its files. */
343
+ preview: (id, opts = {}) => this.request("POST", `/runs/${enc(id)}/preview`, opts),
344
+ /** Polls the run every second until it is done, failed, stopped or cancelled, and returns it. */
345
+ wait: async (id, opts = {}) => {
346
+ const deadline = Date.now() + (opts.timeoutMs ?? 30 * 60_000);
347
+ const seen = new Map();
348
+ for (;;) {
349
+ const run = await this.runs.get(id);
350
+ for (const step of run.steps ?? []) {
351
+ if (seen.get(step.id) === step.status)
352
+ continue;
353
+ seen.set(step.id, step.status);
354
+ opts.onStep?.(step, run);
355
+ }
356
+ if (RUN_FINISHED.includes(run.status))
357
+ return run;
358
+ if (Date.now() > deadline)
359
+ throw new SandboxesError(408, "run_timeout", `Run ${id} is still ${run.status}`);
360
+ await sleep(1000);
361
+ }
362
+ },
363
+ /** External runs: ends the run as done or failed (with the error). */
364
+ finish: (id, opts) => this.request("POST", `/runs/${enc(id)}/finish`, opts),
365
+ /** External runs: reports one step. When the answer says stop, a guard was reached; stop the loop. */
366
+ reportStep: (id, step) => this.request("POST", `/runs/${enc(id)}/steps`, {
367
+ ...step,
368
+ startedAt: isoTime(step.startedAt),
369
+ finishedAt: isoTime(step.finishedAt),
370
+ }),
371
+ };
115
372
  async create(opts = {}) {
116
373
  return new Sandbox(this, await this.request("POST", "/sandboxes", opts));
117
374
  }
118
- /** A sandbox by id, or by name for a durable one. */
375
+ /** A sandbox by id, or by name for a saved one. */
119
376
  async get(id) {
120
377
  return new Sandbox(this, await this.request("GET", `/sandboxes/${enc(id)}`));
121
378
  }
@@ -160,7 +417,9 @@ export class Sandboxes {
160
417
  }
161
418
  /** Builds a template again, with a new Dockerfile or the same one. */
162
419
  async rebuildTemplate(idOrName, dockerfile) {
163
- return this.request("POST", `/templates/${enc(idOrName)}/builds`, dockerfile === undefined ? {} : { dockerfile });
420
+ // The API answers { build, warnings }.
421
+ const r = await this.request("POST", `/templates/${enc(idOrName)}/builds`, dockerfile === undefined ? {} : { dockerfile });
422
+ return (r.build ?? r);
164
423
  }
165
424
  async updateTemplate(idOrName, changes) {
166
425
  return this.request("PATCH", `/templates/${enc(idOrName)}`, changes);
@@ -203,6 +462,33 @@ export class Sandboxes {
203
462
  async usage(days) {
204
463
  return this.request("GET", `/usage${query({ days })}`);
205
464
  }
465
+ /**
466
+ * What your own AI keys (Claude, OpenAI) were used for: every call Quiet Robot
467
+ * made or passed on with one (Playground steps, flow drafting, sandboxes,
468
+ * hosted Kip), by key, where it was used, model and day, with tokens (cache
469
+ * reads and writes too) and the cost estimated at list price. `days`: 1 to
470
+ * 400 (default 30); `key`: one key by its secret name.
471
+ */
472
+ async aiKeyUsage(opts = {}) {
473
+ return this.request("GET", `/usage/ai-keys${query({ days: opts.days, key: opts.key })}`);
474
+ }
475
+ /** Everything the organization stores, item by item, with its monthly cost and this month's storage bill. */
476
+ async storage() {
477
+ return this.request("GET", "/storage");
478
+ }
479
+ /**
480
+ * Your organization's rules, read-only: the defaults new sandboxes get, the
481
+ * approval rules that hold commands, Undo checkpoints and the outbound
482
+ * check. Owners and admins change them on the dashboard's Policies page, so
483
+ * an API key can't loosen them.
484
+ */
485
+ async policy() {
486
+ return this.request("GET", "/policy");
487
+ }
488
+ /** Your outbound check's address, or null when there is none. Set on the dashboard's Policies page. */
489
+ async outboundCheck() {
490
+ return this.request("GET", "/outbound-check");
491
+ }
206
492
  async audit(opts = {}) {
207
493
  return (await this.request("GET", `/audit${query(opts)}`)).events;
208
494
  }
@@ -553,6 +839,17 @@ export class Sandbox {
553
839
  const r = await this.client.request("POST", this.path("/fork"), opts);
554
840
  return { snapshot: r.snapshot, sandboxes: r.sandboxes.map((s) => new Sandbox(this.client, s)), errors: r.errors ?? [] };
555
841
  }
842
+ /**
843
+ * Starts up to 10 running copies of this sandbox with everything in it at
844
+ * this instant: memory, running programs, env and files. Each copy has the
845
+ * source's size, template, network rules and metadata, its own id and no
846
+ * ports. The source keeps running; it is held paused only while it is
847
+ * copied (freezeMs). Copies are named <name>-1, <name>-2, ...
848
+ */
849
+ async clone(opts = {}) {
850
+ const r = await this.client.request("POST", this.path("/clone"), opts);
851
+ return { ...r, sandboxes: r.sandboxes.map((s) => new Sandbox(this.client, s)), errors: r.errors ?? [] };
852
+ }
556
853
  /**
557
854
  * Gives this sandbox a new size. A running or paused sandbox can't change size in
558
855
  * place, so this copies it (fork with the new size), destroys the original and
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quietrobot/sandboxes",
3
- "version": "0.2.2",
3
+ "version": "0.3.0",
4
4
  "description": "TypeScript client for Quiet Robot Sandboxes: governed sandboxes for AI agents",
5
5
  "keywords": [
6
6
  "sandbox",
@@ -38,7 +38,8 @@
38
38
  "sideEffects": false,
39
39
  "scripts": {
40
40
  "build": "tsc -p .",
41
- "prepack": "tsc -p ."
41
+ "prepack": "tsc -p .",
42
+ "test": "tsc -p . && node --test test/*.test.mjs"
42
43
  },
43
44
  "publishConfig": {
44
45
  "access": "public"