@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/README.md CHANGED
@@ -98,16 +98,187 @@ await sbx.rewind({ snapshotId: snap.id }); // files back as they were
98
98
  const fresh = await qr.create({ snapshotId: snap.id });
99
99
  ```
100
100
 
101
+ ## Loops and graphs
102
+
103
+ A graph is JSON: steps that run commands, edges that branch on pass (the default), fail or always
104
+ and may loop back. A run plays it on real sandboxes, saves a checkpoint after
105
+ each step that passes, and stops itself at a guard (loops, time, spend)
106
+ checked on the server. Simulate it first to see what it will cost.
107
+
108
+ ```ts
109
+ import type { Graph } from "@quietrobot/sandboxes";
110
+
111
+ const graph: Graph = {
112
+ name: "Fix until tests pass",
113
+ start: "test",
114
+ nodes: [
115
+ { id: "test", kind: "run", cmd: "python3 test.py", passRate: 0.4 },
116
+ { id: "fix", kind: "run", cmd: "./fix.sh" },
117
+ { id: "done", kind: "end" },
118
+ ],
119
+ edges: [
120
+ { from: "test", to: "fix", when: "fail" },
121
+ { from: "fix", to: "test", when: "always" },
122
+ { from: "test", to: "done", when: "pass" },
123
+ ],
124
+ };
125
+ const guards = { maxLoops: 5, timeSec: 300, budgetUsd: 0.25 };
126
+
127
+ const { forecast } = await qr.graphs.simulate({ graph, guards });
128
+ console.log(forecast.costUsd.p90, forecast.worstCaseUsd, forecast.worstCaseWhy);
129
+
130
+ const run = await qr.runs.create({ graph, guards });
131
+ const done = await qr.runs.wait(run.id, { onStep: (s) => console.log(s.node, s.status, s.message ?? "") });
132
+ console.log(done.status, done.loops, done.costUsd);
133
+ ```
134
+
135
+ Also `qr.runs.list({ limit })`, `qr.runs.get(id)` and `qr.runs.cancel(id)`.
136
+ For a loop you play yourself, create the run with `mode: "external"`, report
137
+ each step with `qr.runs.reportStep(id, { node, status, sandboxId })` and stop
138
+ when the answer says `stop: true`; end it with
139
+ `qr.runs.finish(id, { status: "done" })`.
140
+
141
+ Besides `run`, a step's `kind` can be `code` (a script in `lang`: python, node
142
+ or bash), `model` (asks a model with your own key; with `output: "decision"`
143
+ it picks one of `choices` and the run follows the edge whose `when` is
144
+ `choice:<label>`), `branch` (a yes or no check), `approval` (waits for a
145
+ person), `wait`, `fork` and `judge` (copy the sandbox into lanes, keep the
146
+ best) and `end`.
147
+
148
+ ### Flows and recipes
149
+
150
+ A flow is a graph saved with its guards, from the Agent Playground's builder
151
+ or from here. It keeps versions, and you run it by id. A recipe is a
152
+ ready-made flow to start from.
153
+
154
+ ```ts
155
+ const recipes = await qr.recipes.list(); // id, name, category, guards, graph
156
+ const flow = await qr.flows.create({ recipe: "fix-until-pass" }); // or { graph, guards, name }
157
+
158
+ await qr.flows.update(flow.id, { guards: { maxLoops: 3 } }); // fields left out keep their value
159
+ await qr.flows.saveVersion(flow.id, { note: "Three loops" });
160
+
161
+ const { forecast } = await qr.flows.simulate(flow.id);
162
+ const run = await qr.flows.run(flow.id); // same as qr.runs.create({ flow: flow.id })
163
+ const done = await qr.runs.wait(run.id);
164
+ console.log(done.status, done.flowVersion);
165
+ ```
166
+
167
+ Also `qr.flows.list()`, `qr.flows.get(id)`, `qr.flows.delete(id)`,
168
+ `qr.flows.runs(id, { limit })`, `qr.recipes.get(id)`, and for versions
169
+ `qr.flows.versions(id)`, `qr.flows.version(id, n)` and
170
+ `qr.flows.restore(id, n)`. A flow may be a draft that can't run yet: `runnable`
171
+ is false and `problem` says why. `qr.runs.create` and `qr.graphs.simulate`
172
+ take `{ recipe: id }` or `{ flow: id }` in place of `graph`; `{ template: id }`
173
+ and `qr.graphs.templates()` are the old names for recipes and still work.
174
+
175
+ #### Flow JSON
176
+
177
+ A flow as JSON is `{ name, graph, guards, layout }`: the same document the
178
+ Playground's JSON editor shows. Export it, keep it in your repository, check
179
+ it and save it back:
180
+
181
+ ```ts
182
+ const doc = await qr.flows.export(flow.id); // no ids or timestamps
183
+ doc.guards = { ...doc.guards, maxLoops: 3 };
184
+
185
+ const check = await qr.flows.validate(doc); // or { flow: id } or { recipe: id }
186
+ if (!check.valid) for (const p of check.problems) console.log(p.code, p.path, p.message);
187
+ console.log(check.sandboxes, check.policy); // sandboxes at once vs your plan, steps your Policies will hold
188
+
189
+ const copy = await qr.flows.create(doc); // a copy, here or in another organization
190
+ ```
191
+
192
+ `validate` runs the same checks as a run (your plan's sandboxes at once,
193
+ model keys, switched-off steps) without saving or starting anything; a flow
194
+ that wouldn't run comes back with `valid: false` rather than an error. Each
195
+ problem has a `code` (`invalid_flow`, `plan_limit`, `missing_secret`, ...)
196
+ and, when it points at one, a `step` and a JSON `path` like
197
+ `/graph/nodes/2/cmd`. `qr.flows.schema()` is the JSON Schema for editors.
198
+
199
+ Not sure where to start? Describe it in plain words and get a flow back,
200
+ drafted with your own saved Claude key (a few cents) and checked like any other:
201
+
202
+ ```ts
203
+ const d = await qr.flows.draft({ description: "Every Monday, summarize last week's issues and ask me before posting it", save: true });
204
+ d.summary.forEach((s, i) => console.log(`${i + 1}. ${s}`)); // one sentence per step
205
+ await qr.flows.run(d.flowId!);
206
+ ```
207
+
208
+ A Decide (`branch`) step can take its condition in plain words too:
209
+ `{ kind: "branch", question: "the summary mentions pricing" }` has Claude
210
+ answer Yes or No, and `{ kind: "branch", question: "the tests passed", from: "test" }`
211
+ uses that step's result, with no AI. An agent's `doneIf` is the same kind of
212
+ check for when it says it is done.
213
+
214
+ ## Messages between sandboxes (channels)
215
+
216
+ A channel is a named queue your sandboxes and your own code share. Start a
217
+ sandbox with the channels it may use; inside, `Channels.inSandbox()` needs no
218
+ key, and only that sandbox can use its address.
219
+
220
+ ```ts
221
+ import { Channels, Sandboxes } from "@quietrobot/sandboxes";
222
+
223
+ const qr = new Sandboxes();
224
+ const worker = await qr.create({ channels: ["jobs", "results"] });
225
+
226
+ // From your code (API key):
227
+ await qr.channels.send("jobs", { file: "report.py" });
228
+ for await (const m of qr.channels.listen("results")) console.log(m.body);
229
+
230
+ // Inside the sandbox (no key; QR_CHANNELS_URL is set for you):
231
+ const ch = Channels.inSandbox();
232
+ const job = await ch.take("jobs", { wait: 25, leaseSec: 300 }); // one worker per job
233
+ if (job) {
234
+ await ch.send("results", { done: job.body });
235
+ await ch.ack("jobs", job.seq);
236
+ }
237
+ ```
238
+
239
+ `read(name, { after, wait })` gives every reader every message, oldest first;
240
+ `take` hands each message to one caller only. Messages are any JSON up to
241
+ 64 KB, kept 7 days. Sandboxes in deny mode can't use channels.
242
+
101
243
  ## Everything else
102
244
 
103
245
  - Sandboxes: `qr.get(id)` / `qr.connect(id)`, `qr.list(status)`, `sbx.refresh()`,
104
246
  `sbx.setTimeout(sec)`, `sbx.setEgress({...})`, `sbx.metrics(hours)`,
105
247
  `sbx.executions()`, `sbx.audit()`, `sbx.destroy()`.
106
248
  - Create options: `template`, `region`, `cpus`, `memoryMb`, `timeoutSec`,
107
- `cpuClass`, `autoPauseSec`, `egress`, `secrets`, `env`, `snapshotId`, `name`, `durable`,
108
- `ifExists`, `volumes`.
249
+ `cpuClass`, `autoPauseSec`, `egress`, `secrets`, `secretBudgets`, `channels`, `env`, `snapshotId`, `name`, `ephemeral`,
250
+ `durable`, `ifExists`, `volumes`.
251
+ - Key rules and budgets: `qr.secrets.set(name, value, hosts, { rules, budget })`
252
+ or `qr.secrets.update(name, { rules, budget })` limits which calls a key may
253
+ make (`[{ methods: ["POST"], paths: ["/v1/chat/completions"] }]`) and how
254
+ much it may be used per run and per month (`{ perRun: { requests: 200, usd: 2 },
255
+ perMonth: { usd: 50 } }`). Past the budget, its calls are refused.
256
+ - Rolling a key: `qr.secrets.roll(name, newValue)` replaces the value and keeps
257
+ its allowed hosts, rules and budget. Anthropic and OpenAI keys are tested
258
+ first; a refused key throws `SandboxesError` with code `key_rejected` and the
259
+ old value stays. `qr.secrets.test(name)` checks the saved key,
260
+ `qr.secrets.test(name, candidate)` checks one without saving it.
261
+ - Held commands: `qr.approvals.list()` lists what's waiting for a person. Only a
262
+ person signed in to the dashboard can approve or deny.
263
+ - Saved by default: a sandbox keeps its files through pauses and its time
264
+ limit, and is deleted 72 hours after its last use. Pass `ephemeral: true`
265
+ for a throwaway one that is deleted when it stops. Take a snapshot to keep
266
+ files longer.
109
267
  - Account: `qr.snapshots()`, `qr.deleteSnapshot(id)`, `qr.reservations()`,
110
- `qr.usage(days)`, `qr.audit()`, `qr.secrets`, `qr.volumes`, `qr.webhooks`.
268
+ `qr.usage(days)`, `qr.aiKeyUsage({ days, key })` (what your own Claude and OpenAI
269
+ keys were used for), `qr.storage()` (everything stored, with its monthly cost),
270
+ `qr.policy()` (your organization's rules, read-only), `qr.outboundCheck()`,
271
+ `qr.audit()`, `qr.secrets`, `qr.volumes`, `qr.webhooks`.
272
+ - Live clones: `await sbx.clone({ count: 3 })` starts running copies with
273
+ memory and programs as they are this instant; the original keeps running.
274
+ - Flow triggers: `qr.flows.triggers(id)`, `qr.flows.addTrigger(id, { kind:
275
+ "schedule", schedule: { every: "day", hour: 9 } })` (or `"webhook"`,
276
+ `"github"`), `updateTrigger`, `deleteTrigger`. Needs Pay as you go with a card.
277
+ - GitHub Actions runners: `qr.githubRunners.create({ repository, token })`,
278
+ then put `runs-on: quietrobot` in a workflow; also `list`, `get`, `update`,
279
+ `delete`, `rotateSecret`. See [runners/](../runners/README.md).
280
+ - Recipes carry `links` (`open`, `simulate`, `run`): pages to hand a person
281
+ that open the recipe in their Playground.
111
282
  - Templates: start from one of ours with `template: "code-interpreter"` (or
112
283
  `browser`, `desktop`, `coding-agent`, `fullstack-js`, `go`, `rust`,
113
284
  `postgres`), or build your own from a Dockerfile: