foldrun 26.5.2 → 26.6.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/bin/foldrun.mjs CHANGED
@@ -46,6 +46,7 @@
46
46
  // foldrun eval grades <eval> what a grader found in the real runs it graded — eval grade <eval> --run <id> grades one
47
47
  // foldrun eval trends evals by change: each eval against its last run on a different commit
48
48
  // foldrun agent run <name> run one agent once on a platform, no flow
49
+ // foldrun code [dir] code with an agent in a sandbox on the platform: it gets the folder, you apply its patch
49
50
  // foldrun tool test <name> exercise one tool alone — no model, no run
50
51
  // foldrun hook <verb> ls / add / test / rm — your own code at every tool call and step
51
52
  // foldrun deploy [dir] push this account — or one workspace — into an installation
@@ -119,6 +120,8 @@ const HELP = `foldrun — agents are just folders
119
120
  foldrun check --rules every rule check knows: id, level, what it guards against (--json)
120
121
  foldrun check --to <ws> --online also the network checks, run by the platform: known vulnerabilities for exact runtime pins (OSV) and remote MCP servers' tool text — and what could not be checked
121
122
  foldrun agent run <name> run one agent once on the platform (--task "…", --to, --wait, --test, --context <id>, --file <path> repeatable)
123
+ foldrun agent run <name> --snapshot [dir|id] …on a folder: sent first (what git would commit, checked for secrets), the agent works on it in snapshot/, and the patch of its changes is on the run (foldrun report <run-id> patch)
124
+ foldrun code [dir] code with an agent on the platform: each message sends the folder (a snapshot), the agent works on it in its own sandbox, and you apply the patch it hands back after git apply --check (--to — made, with its coder agent, after a yes when it does not exist; --agent <name> (default coder, added on first use with a yes), --task "…" one turn and exit, --yes apply without asking, --test, --context <id>)
122
125
  foldrun agent run <name> --no-task run it with no instruction, on its own prompt alone — the dashboard's Run (--to, --wait, --test)
123
126
  foldrun agent link <agent> add to its team, in its frontmatter: --subagent <worker> (--isolated: sandbox: own on the worker), --consult <agent> or --can-ask (--description for a worker with none)
124
127
  foldrun agent unlink <agent> take one away: --subagent <name>, --consult <name> or --can-ask
@@ -175,6 +178,7 @@ const HELP = `foldrun — agents are just folders
175
178
  foldrun runs rm <run-id> <run-id>… delete several: lists them, asks once, then deletes them in one runs/bulk call per project, as the dashboard does
176
179
  foldrun runs rm --until <30d|date> delete every finished run that started before then — records, captured calls, archived outputs (an admin; --to <workspace>, --dry-run, --yes); live runs are left alone
177
180
  foldrun report <run-id> one run, whole: header, every step, what it wrote and what is still waiting
181
+ foldrun report <run-id> patch the patch a snapshot run made: the patch to stdout, what it changes to stderr; --apply puts it into --dir <folder> (default here) after git apply --check, asking first unless --yes (--agent <name> when several agents ran)
178
182
  foldrun report <run-id> get <agent>/<path> download a file the run archived from that agent's outputs/ (--file <path>|-, --force)
179
183
  foldrun report <run-id> --compare [<run-id>] beside the flow's last good run (or the one named): changed files and what differs step by step (--json)
180
184
  foldrun report <run-id> --tree the run as one tree: step → model call → tool call, with what went wrong marked (--json)
@@ -338,15 +342,18 @@ Options
338
342
  --starter new, workspaces new: include the example researcher, writer and publish flow (a new project is blank)
339
343
  --transport <k> tool new: script (default), http or mcp
340
344
  --language <l> tool new, source new, library new: the script's language — javascript, python, bash
341
- --task "<text>" the instruction for a manual run
345
+ --task "<text>" the instruction for a manual run; code: one turn, then exit
342
346
  --no-task agent run: start it with no instruction — the agent works from its own prompt alone
343
347
  --task "<text>" flow inputs save: the task the saved set holds (--file <path> reads it from a file)
344
- --test run, invoke: a test run — nothing outward, state/ untouched, receipts on the run page
348
+ --snapshot [dir|id] agent run: a folder for the agent to work on — sent first (this folder when bare), or a snapshot id foldrun snapshot push answered
349
+ --apply report patch: put the patch into --dir (default this folder) after git apply --check, asking first unless --yes
350
+ --dir <folder> report patch: the folder --apply puts the patch into (default this one)
351
+ --test run, invoke, code: a test run — nothing outward, state/ untouched, receipts on the run page
345
352
  --file <path> invoke, agent run: a file handed to the run (repeatable) — a storage path, or ./local-file uploaded to storage/inputs/ first; the first step finds them in inputs/ and can read images and PDFs (FOL-163)
346
353
  --require-customer keys create: every run (or gateway call) with the key must name an end customer (FOL-168)
347
354
  --customer <id> invoke, agent run: which of your own users the run is for (FOL-168) — limits and blocks follow it; runs: only that customer's runs
348
355
  --reason "<text>" customers block: why, kept on the block and the audit log
349
- --context <id> invoke, agent run: a turn of that conversation — the first step reads the earlier runs started with the same context (any id you choose, 1–200 printable characters); runs: only that conversation's runs
356
+ --context <id> invoke, agent run, code: a turn of that conversation — the first step reads the earlier runs started with the same context (any id you choose, 1–200 printable characters); runs: only that conversation's runs
350
357
  --follow logs: keep tailing a live run (with --url: on the platform)
351
358
  --status <s> runs, stop, rerun: only these statuses, comma-separated (failed, completed, awaiting-approval…)
352
359
  --since <span> runs, stop, rerun: only runs started within 24h, 7d, 90m, 2w, or today (the last 24h)
@@ -359,7 +366,7 @@ Options
359
366
  --verdict <v> runs: only completed runs whose summary leads with it — good, bad, quiet, blocked (comma-separated)
360
367
  --q <words> runs: the runs page's text search — every word, any order, across id, flow, project, status, verdict, summary and failure; assistant history: search the conversations
361
368
  --flow <name> export: that flow and everything it runs; runs, stop, rerun: only that flow's runs; flow add: the other flow a subflow step runs; flow draft: the existing flow to redraft
362
- --agent <name> export: that agent and what it grants; flow add: the agent a chain, parallel or router step runs; rerun: from the first step that agent runs; report live: whose browser frame; source new: the agent the document belongs to
369
+ --agent <name> code: the agent that works on the folder (default coder); report patch: whose patch, when several agents ran; export: that agent and what it grants; flow add: the agent a chain, parallel or router step runs; rerun: from the first step that agent runs; report live: whose browser frame; source new: the agent the document belongs to
363
370
  --instruction "<text>" flow add: what a new step (chain, parallel, router) is told to do
364
371
  --after <n> flow add, flow move-step, flow paste: put the new group after the nth (0 = first); --before <n> before it (flow add); default last
365
372
  --group <n> flow add, flow move-step, flow paste: the group a step joins, in parallel
@@ -432,7 +439,7 @@ Options
432
439
  --stale [days] agent ls: only agents not run in that many days (never run included); bare, those past alerts: stale_days
433
440
  --reason "<text>" account pause, project pause: why — shown to everyone who opens it
434
441
  --stop account pause, project pause: also stop every run going now (asks; --yes to mean it)
435
- --yes approve, stop, rerun (bulk), pause --stop, flow rotate-hook, flow draft, assistant, history restore, restore <ws>, import, billing plan, workspace set name, team remove, and every rm/revoke/unshare: skip the confirmation, deliberately (required with no terminal)
442
+ --yes code, report patch: apply the patch without asking; approve, stop, rerun (bulk), pause --stop, flow rotate-hook, flow draft, assistant, history restore, restore <ws>, import, billing plan, workspace set name, team remove, and every rm/revoke/unshare: skip the confirmation, deliberately (required with no terminal)
436
443
  --json report: the raw run record instead of the report; runs: { runs, next }; runs outputs: { runId, files, totalBytes }; observe, usage, api version, changelog, find, preferences, workspace vocabulary, flags, projects, workspaces show, agent ls, flow ls, agent import --list, backups requests, team, hook ls, secrets ls, triggers, storage ls --all: the raw document; version: {cli, core, platform}
437
444
  --events <a,b> account set notify: failed, awaiting-approval, completed
438
445
  --failed webhooks deliveries: only the ones that gave up
@@ -528,7 +535,7 @@ if (!command || command === "--help" || command === "-h") {
528
535
  // `--value` as the account's argument and stored an empty secret; `--force
529
536
  // ./dir` swallowed the directory. A flag followed by another flag is also
530
537
  // boolean, so an unlisted switch at least does not eat its neighbour.
531
- const BOOLEAN_FLAGS = new Set(["read-only", "account", "follow", "force", "oauth2", "wait", "watch", "print", "dry-run", "help", "no-browser", "local", "test", "flat", "yes", "platform", "json", "forever", "all", "check", "new-client", "quiet", "off", "can-ask", "preview", "csv", "failed", "starter", "history", "list", "library", "clear", "security", "changed", "write-baseline", "no-baseline", "rules", "calls", "tree", "tool-error", "stop", "last", "no-pkce", "generate-key", "device", "write", "dpop", "export", "isolated", "no-wait", "dismissed", "unread", "team", "started", "mine", "none", "a2a", "gateway", "claude-code", "login", "unreachable", "public-card", "private-card", "return-immediately", "online", "overwrite", "no-send", "event-wait", "with-client", "use", "clear-name", "clear-description", "clear-examples", "clear-accept-risk", "clear-address", "clear-email", "clear-abn", "no-task", "empty", "plain", "no-beep", "require-customer", "no-write"]);
538
+ const BOOLEAN_FLAGS = new Set(["apply", "read-only", "account", "follow", "force", "oauth2", "wait", "watch", "print", "dry-run", "help", "no-browser", "local", "test", "flat", "yes", "platform", "json", "forever", "all", "check", "new-client", "quiet", "off", "can-ask", "preview", "csv", "failed", "starter", "history", "list", "library", "clear", "security", "changed", "write-baseline", "no-baseline", "rules", "calls", "tree", "tool-error", "stop", "last", "no-pkce", "generate-key", "device", "write", "dpop", "export", "isolated", "no-wait", "dismissed", "unread", "team", "started", "mine", "none", "a2a", "gateway", "claude-code", "login", "unreachable", "public-card", "private-card", "return-immediately", "online", "overwrite", "no-send", "event-wait", "with-client", "use", "clear-name", "clear-description", "clear-examples", "clear-accept-risk", "clear-address", "clear-email", "clear-abn", "no-task", "empty", "plain", "no-beep", "require-customer", "no-write"]);
532
539
  // Flags said more than once collect into a list: `--tag a --tag b`.
533
540
  const REPEATABLE = new Set(["tag", "expect", "header", "site", "add", "remove", "rule", "authorize-param", "example", "accept-risk"]);
534
541
  /** Flags that become a list only when given more than once (FOL-163 `--file`). */
package/docs/cli.md CHANGED
@@ -44,6 +44,7 @@ claude.ai or Claude Code there, nor any MCP configuration on disk.
44
44
  | `foldrun extract [dir]` | move each single-file script tool — a `tools/<name>.md` with its program in a fenced block — into a folder: `tools/<name>/tool.md` with `run:` pointing at `run.js`, `run.py` or `run.sh` beside it. Frontmatter is edited as text, never re-serialised, so the diff is only what moved. A tool that already has a folder is left for you; `--dry-run` lists what it would do |
45
45
  | `foldrun check --to <ws>` | validate the copy that is DEPLOYED, rather than the folder in front of you — a project edited through the API, by an agent or by `foldrun source put`, has had no way to be checked short of spending a run. The files are fetched into a temporary folder and the ordinary check runs over them, so there is one copy of the rules; the output names the project and the platform it checked. `--online` adds the network checks the platform runs: known vulnerabilities for exact runtime pins and remote MCP servers' tool text, and what could not be checked (an editor's key or above; the platform keeps the answer 10 minutes while the files are unchanged). Either way it ends with when the platform's [daily rescan](checks#online-checks-and-the-daily-rescan) last ran, as the Checks page does — a platform that does not say leaves the line out |
46
46
  | `foldrun agent run <name>` | run one agent once on a platform, with no flow file: a flow of one step. `--task "…"` is the instruction and is required. Prints the run id and how to follow it; `--wait` holds on (in 25-second pieces, as `invoke` does) and then prints the same report `foldrun report` would; `--test` makes it a [test run](runs#test-runs) |
47
+ | `foldrun agent run <name> --snapshot [dir\|id]` | run it on a folder: the folder (this one when bare) is sent first, exactly as `snapshot push` sends it, or a snapshot id that command answered is used as it is. The agent finds it in `snapshot/`; when the run ends the patch of what it changed is on the run (`foldrun report <run-id> patch`). Needs an install that runs steps in sandboxes (`FOLDRUN_RUN_ISOLATION=k8s`) |
47
48
  | `foldrun agent run <name> --no-task` | run it with no instruction, as the dashboard's **Run** on an agent row does (`POST …/agents/<agent>/run` with `{}`): the agent works from its own prompt alone. Explicit, so a mistyped `--task` never starts a run with nothing to do; `--task` and `--no-task` together are refused. `--wait`, `--test` and `--to` as for `agent run` |
48
49
  | `foldrun agent link <agent>` | add to an agent's team, in its own frontmatter — `--subagent <worker>` (`subagents:`, a worker it delegates to), `--consult <agent>` (`agents:`, a colleague it asks) or `--can-ask` (`ask` in `tools:`, so it may ask you mid-step). The edit is core's, the one the canvas's docks make: only the lines of that one list change, flow style stays flow style, comments and the prose stay byte for byte. A sub-agent without a `description:` needs one, because the model picks a sub-agent by it — asked for at a terminal, `--description "…"` otherwise, and written into the worker's file first. `--isolated` also writes `sandbox: own` on the worker: each job it is handed runs in its own sandbox, with its own tools, secrets and network, not cut to the delegating agent's; its reply comes back with the files it wrote (`foldrun docs agents`). Says which flows use the agent ("used by 3 flows"), since the change reaches all of them. Prints the diff, and refuses an edit `foldrun check` would call an error; `--dry-run` writes nothing. In this folder by default (`--workspace <name>` in an account with several); `--to <workspace>` edits the deployed copy through `PATCH /api/workspaces/<ws>/agents/<name>`. In this folder it re-reads each file just before writing — after the description prompt, after `check` — and refuses, writing nothing to either file, when one changed since it was read |
49
50
  | `foldrun agent import <workspace>/<agent>` | copy an agent you already have in another project into this one: its `agent.md` and own `skills/`, `scripts/`, `knowledge/` — never `memory/`, `outputs/` or `state/`. Into the project you stand in, or `--workspace <name>`; `--as <name>` imports it under another name (and rewrites `name:`), which a name clash requires. `--to <workspace>` does it on the platform (`POST /api/workspaces/<ws>/agents/import`) and lists the tools, skills, scripts and secrets the copy uses that the project lacks. See [Importing an agent](workspaces#importing-an-agent-you-already-have) |
@@ -101,6 +102,7 @@ claude.ai or Claude Code there, nor any MCP configuration on disk.
101
102
  | `foldrun report <run-id> --compare [<run-id>]` | this run beside the flow's [last good run](runs#compare-with-the-last-good-run), or the one named: whether they ran the same files and which changed, then what differs step by step (status, new errors, instruction, model, tools, time, tokens). `--json` |
102
103
  | `foldrun report <run-id> --tree` | the run as [one tree](runs#the-trace-tree): each step, each model call (model, tokens, why it stopped) and each tool call under the call that asked for it, with how long each took and `← what went wrong` on the first failure. `--json` gives the tree and the failure path |
103
104
  | `foldrun report <run-id> --calls` · `foldrun report <run-id> call <call-id>` | what the run [recorded](runs#what-a-run-records): `--calls` adds every model call (model, time, tokens and cache share, why it stopped, tools) and lists the tool calls whose input and output were kept; `call <call-id>` prints one of those, secrets masked (`--json`). The header says which commit the run ran and how long it queued |
105
+ | `foldrun report <run-id> patch` | the patch a snapshot run made — by the platform, in the held sandbox, against a fresh copy of what was sent, never by the agent. The patch goes to stdout (so `> fix.patch` or `\| git apply` work) and what it changes to stderr; a run that changed nothing says so and exits 0, one with no patch says why and exits 1. `--apply` puts it into `--dir <folder>` (this one by default) after `git apply --check`, asking first unless `--yes`; `--agent <name>` when several agents ran |
104
106
  | `foldrun report <run-id> get <agent>/<path>` | download one file the run archived — whatever that agent left in `outputs/`, copied under the run when it ended. Writes it beside you under its own name; `--file <path>` names somewhere else (`-` for stdout), `--force` overwrites |
105
107
  | `foldrun report <run-id> live` | the run page's live browser view: which agents' browsers have posted a frame, and when; `--agent <name>` saves the newest frame as a JPEG (`--file <path>`, `-` for stdout) and prints the page's address, the engine and whether the browser has closed (`GET …/runs/<id>/live`) |
106
108
  | `foldrun insights` | recurring [problems](runs#insights) found in the last week of runs — a prompt mostly uncached, a big tool result sent again, a retry loop, steps near their timeout — each with why, what to do, about what it cost and the runs it was seen in. `--days <1-30>`, `--to <workspace>`, `--json` |
@@ -134,6 +136,7 @@ claude.ai or Claude Code there, nor any MCP configuration on disk.
134
136
  | `foldrun export [workspace]` | a deployed project as a `.zip` — agents, flows, tools, skills, scripts, evals, knowledge; never memory, state, storage or a secret's value. `--flow <name>` exports that flow with every flow and agent it runs and the tools, skills and scripts they grant; `--agent <name>` that agent and what it grants. Written under the name the platform gives it (`<ws>.zip`, `<ws>-flow-<name>.zip`); `--file <path>` (`-` for stdout), `--force` to replace (`GET …/export`) |
135
137
  | `foldrun import <file.zip>` | take a package in: first shows what it adds, what is identical, what it would replace and what it still needs (secrets, tools, skills, scripts, agents, flows), then asks. Never deletes; replacing a file needs `--overwrite`. `--to <workspace>` (a name that does not exist makes it, from a project package), `--dry-run` previews only (`--json` for the plan), `--yes` with no terminal (`POST …/import`) |
136
138
  | `foldrun snapshot push [dir]` | send a folder for an agent on foldrun to work on (a snapshot). What goes is what git would commit — tracked files and untracked ones `.gitignore` does not exclude, as they are on disk; links and submodules are left out and named. A secret in any file stops it before anything leaves the machine (remove it, or leave the file out with `.gitignore`); the platform checks again. Answers the snapshot id, kept 7 days from the last send and while a run uses it. `--to <workspace>`, `--dry-run` packs and checks only, `--out <file.tar.gz>` keeps the archive (`--force` over a file that is there), `--json` (`POST …/snapshots`) |
139
+ | `foldrun code [dir]` | code with an agent that works in a sandbox on the platform, not on this computer — see [Coding in a sandbox](#coding-in-a-sandbox). Each message sends the folder as a snapshot (as `snapshot push` does), runs the agent on it in its own sandbox as a turn of one conversation, prints what it does as it does it, and offers the patch it hands back: `git apply --check`, git's stat, a yes, then `git apply`. Ctrl-C stops the run; `/new` starts a fresh conversation, `/quit` leaves. `--to <workspace>` (a project that does not exist is made, blank with its `coder` agent, after a yes), `--agent <name>` (default `coder`, added to the project on first use after a yes), `--task "…"` one turn and exit (for scripts), `--yes` applies without asking (required with no terminal), `--test`, `--context <id>` |
137
140
  | `foldrun status [workspace]` | per workspace: what is added, changed and only-on-the-platform, plus which files moved there since your last deploy from here. Reads only |
138
141
  | `foldrun status --platform` | is the platform up: overall, each component (dashboard and API, run workers, scheduler, model providers, email, storage) and any incident or maintenance the operator posted, with its latest update. Reads the open `/api/status` — no key needed; the signed-in platform, `--url` / `FOLDRUN_URL`, or the default, dash.foldrun.io. `--json` prints the answer as is. Exits 1, saying *status unavailable — the platform may be down*, when it does not answer. Plain `foldrun status` opens with the same one-line verdict |
139
142
  | `foldrun status --platform --history` | what the status page draws as bars: each component's uptime over the window and a mark per day — up, degraded or maintenance, an outage, or no samples — then the incidents and maintenance in it, from the open `GET /api/status/history?days=<n>`. `--days 1-90` (default 90), `--json` |
@@ -238,13 +241,15 @@ claude.ai or Claude Code there, nor any MCP configuration on disk.
238
241
  | `--as <name>` | `agent import`: the name the copy gets in this project (rewrites its `name:`); `storage put`: the path one uploaded file lands at |
239
242
  | `--transport <k>` | `tool new`: `script` (the default — a folder with its program beside it), `http` or `mcp` |
240
243
  | `--language <l>` | `tool new`, `source new`, `library new`: the script's language — `javascript`, `python` or `bash` |
241
- | `--task "<text>"` | the instruction for a manual run |
244
+ | `--task "<text>"` | the instruction for a manual run; `code`: one turn, then exit |
245
+ | `--snapshot [dir\|id]` | `agent run`: a folder for the agent to work on — sent first (this folder when bare), or a snapshot id `snapshot push` answered |
246
+ | `--apply`, `--dir <folder>` | `report patch`: put the patch into the folder (this one by default) after `git apply --check`, asking first unless `--yes` |
242
247
  | `--no-task` | `agent run`: start it with no instruction — the agent works from its own prompt alone |
243
248
  | `--task "<text>"` | `flow inputs save`: the task the saved set holds |
244
249
  | `--file <path>` | `invoke`, `agent run`: a file handed to the run — repeatable; a storage path, or a local one (`./`, `../`, `/`, `~`) uploaded to `storage/inputs/<upload id>/` first. The first step finds them in `inputs/` ([inputs](runs#inputs)) |
245
250
  | `--customer <id>` | `invoke`, `agent run`: which of your own users the run is for ([end customers](runs#end-customers)); `runs`: only that customer's runs |
246
- | `--context <id>` | `invoke`, `agent run`: a turn of that [conversation](runs#conversations) — the first step reads the earlier runs started with the same context (any id you choose, 1–200 printable characters, no spaces); `runs`: only that conversation's runs |
247
- | `--test` | `run`, `invoke`, `agent run`: a test run — every step runs, nothing outward happens, `state/` and `storage/` are left alone, and the run page lists what would have happened. See [Test runs](runs#test-runs) |
251
+ | `--context <id>` | `invoke`, `agent run`, `code`: a turn of that [conversation](runs#conversations) — the first step reads the earlier runs started with the same context (any id you choose, 1–200 printable characters, no spaces); `runs`: only that conversation's runs |
252
+ | `--test` | `run`, `invoke`, `agent run`, `code`: a test run — every step runs, nothing outward happens, `state/` and `storage/` are left alone, and the run page lists what would have happened. See [Test runs](runs#test-runs) |
248
253
  | `--follow` | `logs`: keep tailing a live run — locally, or on the platform with `--url` |
249
254
  | `--status <s>` | `runs`, and a bulk `stop` or `rerun`: only these statuses, comma-separated — `failed`, `completed`, `awaiting-approval`, `running`, `queued` |
250
255
  | `--since <span>` | `runs`, and a bulk `stop` or `rerun`: only runs started within `24h`, `7d`, `90m`, `2w`, or `today` (the dashboard's "Today": the last 24 hours). `--status stopped` names a run a person stopped (its record says failed; `--status failed` names it too). `observe` and `triggers` take a number of days instead (sent as `?days=`). `--until <span\|date>` on a bulk `stop` or `rerun`: only runs started before then |
@@ -291,7 +296,7 @@ claude.ai or Claude Code there, nor any MCP configuration on disk.
291
296
  | `--event-wait` | `reject`: refuse a step waiting on `wait: event` rather than a person's gate |
292
297
  | `--note "<text>"` | `approve`: guidance the approved step reads in its prompt — "approve, but skip the Sydney batch". `reject`: the reason, recorded on the trace |
293
298
  | `--read-only` | `mcp`: offer the AI app only the tools that read — no `run_flow`, `run_agent`, `decide_approval`, `answer_question`, `message_run`, `stop_run`, `create_workspace`, `write_file` or `delete_file` |
294
- | `--yes` | skip the confirmation, deliberately: `approve`, `stop`, `deploy` (when it would delete files), and a bulk `stop` or `rerun`, `flow rotate-hook`, `flow draft`, `assistant`, `mcp disconnect`, `a2a cancel`, `history restore`, `restore`, `billing plan`, `repo deploy`/`merge`, `workspace set name`, and every delete — `runs rm`, `storage rm`, `storage unshare`, `source rm`, `secrets rm`, `keys revoke`, `keys delete`, `workspaces rm`. Required when there is no terminal to ask; without it nothing is deleted |
299
+ | `--yes` | skip the confirmation, deliberately: `code` and `report patch` (apply the patch), `approve`, `stop`, `deploy` (when it would delete files), and a bulk `stop` or `rerun`, `flow rotate-hook`, `flow draft`, `assistant`, `mcp disconnect`, `a2a cancel`, `history restore`, `restore`, `billing plan`, `repo deploy`/`merge`, `workspace set name`, and every delete — `runs rm`, `storage rm`, `storage unshare`, `source rm`, `secrets rm`, `keys revoke`, `keys delete`, `workspaces rm`. Required when there is no terminal to ask; without it nothing is deleted |
295
300
  | `--json` | `report`: the raw run record instead of the report. `observe`, `usage`, `workspaces`, `workspaces show`, `agent ls`, `flow ls`, `agent import --list`, `assistant`, `backups requests`, `status --platform --history`, `signup status`, `team`, `secrets ls`, `triggers`, `storage ls --all`: the raw document |
296
301
  | `--events <a,b>` | `account set notify`: which events are notified on — `failed`, `awaiting-approval`, `completed` |
297
302
  | `--watch` | `invoke`: follow the run's trace here as it happens; the exit code is the run's |
@@ -588,6 +593,54 @@ named — by `--url`, by `FOLDRUN_URL`, or by having signed in (`--local` puts a
588
593
  deploy back on this machine): then it lists that project's runs there, prints one run's
589
594
  trail, and `--follow` tails a live one. `open` always needs a platform.
590
595
 
596
+ ## Coding in a sandbox
597
+
598
+ `foldrun code` is a coding session where the agent never runs on your
599
+ computer. You type in the terminal; the work happens in a sandbox on the
600
+ platform (its own pod, under gVisor where the install runs it), and only a
601
+ patch comes back.
602
+
603
+ ```sh
604
+ cd my-app # a git folder
605
+ foldrun code --to dev-desk # each message: send, run, review, apply
606
+ ```
607
+
608
+ Each message is one turn:
609
+
610
+ 1. **The folder goes as a snapshot** — what git would commit, as it is on
611
+ disk now, links left out, refused if any file holds a secret (checked
612
+ here and again on the platform). A folder that has not changed since the
613
+ last turn is not stored twice.
614
+ 2. **The agent runs on it** in its own sandbox, as an ordinary run: on the
615
+ run page of whatever install you are signed in to, self-hosted included,
616
+ with its cost and every tool call. The turns of a session share a
617
+ [conversation](runs#conversations), so it reads what it did before.
618
+ 3. **The patch comes back** — made by the platform, not the agent, against
619
+ a fresh copy of what was sent. `git apply --check` first; git's stat; then
620
+ you say yes. A folder you edited meanwhile so the patch no longer fits is
621
+ refused whole, never half-applied, and the patch is kept for you.
622
+
623
+ The agent is a file like any other, `agents/coder/agent.md` — added on first
624
+ use after a yes, or yours with `--agent <name>`. A `--to` project that does
625
+ not exist yet is made after the same one yes, blank with that agent in it. So everything that governs
626
+ it is frontmatter: `tools:`, `model:`, `effort:`, `size:` and `resources:`
627
+ for the sandbox, `runtime:` for what the project needs installed, `hooks:`
628
+ at every tool call, `limits:`, `network:`, `budget:`. Edit it, deploy, and
629
+ the next turn runs the new one.
630
+
631
+ `--task "…"` runs one turn and exits, for a script; with no terminal,
632
+ `--yes` applies the patch. The same three steps by hand:
633
+
634
+ ```sh
635
+ foldrun agent run coder --to dev-desk --task "fix the failing test" --snapshot .
636
+ foldrun report <run-id> patch --to dev-desk # the patch, to stdout
637
+ foldrun report <run-id> patch --to dev-desk --apply # into this folder
638
+ ```
639
+
640
+ A snapshot needs an install that runs steps in sandboxes
641
+ (`FOLDRUN_RUN_ISOLATION=k8s`); one that does not refuses the run and runs
642
+ nothing.
643
+
591
644
  ## The loop, in order
592
645
 
593
646
  ```sh
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "foldrun",
3
- "version": "26.5.2",
3
+ "version": "26.6.0",
4
4
  "description": "Agents are just folders. Write them, check them, run them — on your machine.",
5
5
  "license": "FSL-1.1-ALv2",
6
6
  "type": "module",
@@ -22,7 +22,7 @@
22
22
  ],
23
23
  "scripts": {
24
24
  "e2e": "FOLDRUN_E2E=1 FOLDRUN_DATA=$(mktemp -d /tmp/foldrun-e2e-XXXXXX) node --test --test-timeout=300000 tests/e2e.test.ts",
25
- "test": "FOLDRUN_DATA=$(mktemp -d /tmp/foldrun-test-XXXXXX) node --test tests/cli-account.test.ts tests/model-credential.test.ts tests/cli-approvals.test.ts tests/cli-issues.test.ts tests/cli-capture.test.ts tests/cli-stop.test.ts tests/cli-account-settings.test.ts tests/cli-team-me.test.ts tests/cli-schedule.test.ts tests/cli-billing.test.ts tests/cli-storage.test.ts tests/cli-scaffold.test.ts tests/cli-secrets.test.ts tests/cli-site-login.test.ts tests/cli-check-library.test.ts tests/cli-check-timezone.test.ts tests/cli-check-frontmatter.test.ts tests/cli-agent-import.test.ts tests/cli-check-subagents.test.ts tests/cli-connect.test.ts tests/cli-accounts.test.ts tests/cli-remote.test.ts tests/cli-stream.test.ts tests/cli-doctor.test.ts tests/cli-tool-test.test.ts tests/cli-agent-run.test.ts tests/cli-check-remote.test.ts tests/cli-shares.test.ts tests/cli-triggers.test.ts tests/cli-providers.test.ts tests/cli-rerun-put.test.ts tests/cli-guide.test.ts tests/cli-runtimes.test.ts tests/cli-deploy-safety.test.ts tests/cli-operator.test.ts tests/cli-flow-patterns.test.ts tests/cli-flow-rm-step.test.ts tests/cli-flow-dup-step.test.ts tests/cli-flow-write-stale.test.ts tests/cli-agent-link-stale.test.ts tests/cli-agent-link-isolated.test.ts tests/cli-parity.test.ts tests/cli-invoke-inputs.test.ts tests/cli-audit-keys.test.ts tests/cli-version.test.ts tests/cli-check-web-warnings.test.ts tests/cli-report-image.test.ts tests/cli-report-cache.test.ts tests/cli-check-workspace-paths.test.ts tests/cli-parity-dashboard.test.ts tests/cli-api-standards.test.ts tests/cli-backups-onboarding.test.ts tests/cli-check-limits.test.ts tests/cli-gallery.test.ts tests/cli-status-platform.test.ts tests/cli-webhooks-notifications.test.ts tests/cli-flags.test.ts tests/cli-api-coverage.test.ts tests/cli-hooks.test.ts tests/cli-release.test.ts tests/cli-terminal.test.ts tests/cli-network.test.ts tests/cli-assistant.test.ts tests/cli-check-scan.test.ts tests/cli-published.test.ts tests/cli-init-target.test.ts tests/cli-flow-filter.test.ts tests/cli-eval-grades.test.ts tests/cli-eval-compare.test.ts tests/cli-proposals.test.ts tests/cli-inbox.test.ts tests/cli-usage-compute.test.ts tests/cli-usage-meters.test.ts tests/cli-fol105.test.ts tests/cli-key-renew.test.ts tests/cli-wait-failed.test.ts tests/cli-mcp.test.ts tests/cli-a2a.test.ts tests/cli-gateway.test.ts tests/cli-switches.test.ts tests/cli-parity-runs.test.ts tests/cli-parity-b.test.ts tests/cli-parity-clears.test.ts tests/cli-parity-c.test.ts tests/cli-runs-paging.test.ts tests/cli-budget-invoices.test.ts tests/cli-observe-analysis.test.ts tests/cli-failure-retention.test.ts tests/cli-snapshot.test.ts tests/cli-run-money.test.ts tests/cli-talk.test.ts tests/cli-text.test.ts tests/cli-browser.test.ts tests/cli-read-concurrency.test.ts",
25
+ "test": "FOLDRUN_DATA=$(mktemp -d /tmp/foldrun-test-XXXXXX) node --test tests/cli-account.test.ts tests/model-credential.test.ts tests/cli-approvals.test.ts tests/cli-issues.test.ts tests/cli-capture.test.ts tests/cli-stop.test.ts tests/cli-account-settings.test.ts tests/cli-team-me.test.ts tests/cli-schedule.test.ts tests/cli-billing.test.ts tests/cli-storage.test.ts tests/cli-scaffold.test.ts tests/cli-secrets.test.ts tests/cli-site-login.test.ts tests/cli-check-library.test.ts tests/cli-check-timezone.test.ts tests/cli-check-frontmatter.test.ts tests/cli-agent-import.test.ts tests/cli-check-subagents.test.ts tests/cli-connect.test.ts tests/cli-accounts.test.ts tests/cli-remote.test.ts tests/cli-stream.test.ts tests/cli-doctor.test.ts tests/cli-tool-test.test.ts tests/cli-agent-run.test.ts tests/cli-check-remote.test.ts tests/cli-shares.test.ts tests/cli-triggers.test.ts tests/cli-providers.test.ts tests/cli-rerun-put.test.ts tests/cli-guide.test.ts tests/cli-runtimes.test.ts tests/cli-deploy-safety.test.ts tests/cli-operator.test.ts tests/cli-flow-patterns.test.ts tests/cli-flow-rm-step.test.ts tests/cli-flow-dup-step.test.ts tests/cli-flow-write-stale.test.ts tests/cli-agent-link-stale.test.ts tests/cli-agent-link-isolated.test.ts tests/cli-parity.test.ts tests/cli-invoke-inputs.test.ts tests/cli-audit-keys.test.ts tests/cli-version.test.ts tests/cli-check-web-warnings.test.ts tests/cli-report-image.test.ts tests/cli-report-cache.test.ts tests/cli-check-workspace-paths.test.ts tests/cli-parity-dashboard.test.ts tests/cli-api-standards.test.ts tests/cli-backups-onboarding.test.ts tests/cli-check-limits.test.ts tests/cli-gallery.test.ts tests/cli-status-platform.test.ts tests/cli-webhooks-notifications.test.ts tests/cli-flags.test.ts tests/cli-api-coverage.test.ts tests/cli-hooks.test.ts tests/cli-release.test.ts tests/cli-terminal.test.ts tests/cli-network.test.ts tests/cli-assistant.test.ts tests/cli-check-scan.test.ts tests/cli-published.test.ts tests/cli-init-target.test.ts tests/cli-flow-filter.test.ts tests/cli-eval-grades.test.ts tests/cli-eval-compare.test.ts tests/cli-proposals.test.ts tests/cli-inbox.test.ts tests/cli-usage-compute.test.ts tests/cli-usage-meters.test.ts tests/cli-fol105.test.ts tests/cli-key-renew.test.ts tests/cli-wait-failed.test.ts tests/cli-mcp.test.ts tests/cli-a2a.test.ts tests/cli-gateway.test.ts tests/cli-switches.test.ts tests/cli-parity-runs.test.ts tests/cli-parity-b.test.ts tests/cli-parity-clears.test.ts tests/cli-parity-c.test.ts tests/cli-runs-paging.test.ts tests/cli-budget-invoices.test.ts tests/cli-observe-analysis.test.ts tests/cli-failure-retention.test.ts tests/cli-snapshot.test.ts tests/cli-code.test.ts tests/cli-run-money.test.ts tests/cli-talk.test.ts tests/cli-text.test.ts tests/cli-browser.test.ts tests/cli-read-concurrency.test.ts",
26
26
  "release": "node scripts/release.mjs",
27
27
  "typecheck": "tsc -p tsconfig.json",
28
28
  "docs:sync": "node scripts/sync-docs.mjs",
package/src/commands.mjs CHANGED
@@ -2098,7 +2098,10 @@ function promptVisible(question) {
2098
2098
  const { stdin } = process;
2099
2099
  stdin.resume();
2100
2100
  stdin.setEncoding("utf8");
2101
+ const onEnd = () => resolve(""); // the input closed (Ctrl-D): no answer, which every caller reads as a no
2102
+ stdin.once("end", onEnd);
2101
2103
  stdin.once("data", (line) => {
2104
+ stdin.off("end", onEnd);
2102
2105
  stdin.pause();
2103
2106
  resolve(String(line).replace(/\r?\n$/, ""));
2104
2107
  });
@@ -2745,6 +2748,31 @@ class StreamIdle extends Error {
2745
2748
  }
2746
2749
  }
2747
2750
 
2751
+ /**
2752
+ * An SSE frame's event name and data, read as the WHATWG spec says: every
2753
+ * `data:` line, joined with "\n", one leading space dropped from each. The
2754
+ * platform sends the run record indented, so its JSON spans one `data:`
2755
+ * line per line; reading only the first ("{") dropped every frame, and no
2756
+ * live run showed its tool calls (19 Nov 2026). A CR before the LF is
2757
+ * dropped too.
2758
+ * @param {string} frame
2759
+ */
2760
+ export function sseFields(frame) {
2761
+ let event = "";
2762
+ const data = [];
2763
+ for (const raw of frame.split("\n")) {
2764
+ const line = raw.endsWith("\r") ? raw.slice(0, -1) : raw;
2765
+ const colon = line.indexOf(":");
2766
+ if (colon <= 0) continue;
2767
+ const field = line.slice(0, colon);
2768
+ let value = line.slice(colon + 1);
2769
+ if (value.startsWith(" ")) value = value.slice(1);
2770
+ if (field === "event") event = value;
2771
+ else if (field === "data") data.push(value);
2772
+ }
2773
+ return { event, data: data.join("\n") };
2774
+ }
2775
+
2748
2776
  /**
2749
2777
  * One connection to a run's stream, printed as frames land. Resolves with
2750
2778
  * the finished run on `done`, with the last run seen if the server ends it
@@ -2796,8 +2824,7 @@ async function streamOnce(url, flags, ws, runId, seen, open = new Map()) {
2796
2824
  while ((cut = buffer.indexOf("\n\n")) !== -1) {
2797
2825
  const frame = buffer.slice(0, cut);
2798
2826
  buffer = buffer.slice(cut + 2);
2799
- const event = frame.match(/^event: (.*)$/m)?.[1];
2800
- const data = frame.match(/^data: (.*)$/m)?.[1];
2827
+ const { event, data } = sseFields(frame);
2801
2828
  if (!event || !data) continue;
2802
2829
  if (event === "run") {
2803
2830
  try {
@@ -2832,11 +2859,14 @@ async function streamOnce(url, flags, ws, runId, seen, open = new Map()) {
2832
2859
  * from printing twice. It used to block `invoke --watch` and `logs
2833
2860
  * --follow` for as long as a stalled tunnel cared to keep the socket.
2834
2861
  */
2835
- async function followRemote(url, flags, ws, runId, seen = new Map(), open = new Map()) {
2862
+ async function followRemote(url, flags, ws, runId, seen = new Map(), open = new Map(), { holdOpen = false } = {}) {
2836
2863
  for (let attempt = 1; ; attempt++) {
2837
2864
  try {
2838
2865
  const run = await streamOnce(url, flags, ws, runId, seen, open);
2839
- flushCalls(open);
2866
+ // holdOpen: the caller reads the run once more when the stream ended
2867
+ // with it still live, and flushes after — a start flushed here would
2868
+ // print a second time when that read brings its completion (Codex).
2869
+ if (!(holdOpen && run && isLive(run))) flushCalls(open);
2840
2870
  return run;
2841
2871
  } catch (err) {
2842
2872
  if (!(err instanceof StreamIdle)) throw err;
@@ -9714,6 +9744,10 @@ async function agentRunCmd(positional, flags, layout) {
9714
9744
  const base = `/api/workspaces/${encodeURIComponent(ws)}/agents/${encodeURIComponent(name)}`;
9715
9745
  if (flags.context !== undefined && typeof flags.context !== "string") throw new Error("which conversation? `--context <id>`");
9716
9746
  const files = await runInputs(url, flags, ws);
9747
+ // --snapshot [dir|id]: a folder for the agent to work on (Part B3). It
9748
+ // finds it in snapshot/; the patch of what it changed is on the run when
9749
+ // it ends (`foldrun report <run-id> patch`).
9750
+ const snapshot = flags.snapshot === undefined ? null : await snapshotFor(url, flags, ws, flags.snapshot);
9717
9751
 
9718
9752
  // A waited run that FAILS is the answer to the question, not a fault in
9719
9753
  // the call: 200 with its status since FOL-106, 500 with the same record
@@ -9735,7 +9769,7 @@ async function agentRunCmd(positional, flags, layout) {
9735
9769
  // at the proxy, send-capable secrets withheld, state/ kept.
9736
9770
  // --context <id> (FOL-162): a turn of that conversation — the agent
9737
9771
  // reads the earlier runs started with the same context first.
9738
- body: JSON.stringify({ ...(task ? { task } : {}), ...(flags.test === true ? { test: true } : {}), ...(typeof flags.context === "string" ? { context: flags.context } : {}), ...(files.length ? { inputs: files } : {}), ...(typeof flags.customer === "string" ? { customer: flags.customer } : {}) }),
9772
+ body: JSON.stringify({ ...(task ? { task } : {}), ...(flags.test === true ? { test: true } : {}), ...(typeof flags.context === "string" ? { context: flags.context } : {}), ...(files.length ? { inputs: files } : {}), ...(typeof flags.customer === "string" ? { customer: flags.customer } : {}), ...(snapshot ? { snapshot } : {}) }),
9739
9773
  }),
9740
9774
  );
9741
9775
  const runId = body?.runId;
@@ -9746,7 +9780,8 @@ async function agentRunCmd(positional, flags, layout) {
9746
9780
  `\n ${c.green("✓")} queued ${c.bold(runId)}${body.test ? ` ${c.amber("TEST")}` : ""} ${c.dim(`${name} · ${ws}`)}`,
9747
9781
  );
9748
9782
  console.log(` ${c.dim(`foldrun report ${runId} --to ${ws}`)}`);
9749
- console.log(` ${c.dim(`foldrun logs ${runId} --to ${ws} --follow`)}\n`);
9783
+ console.log(` ${c.dim(`foldrun logs ${runId} --to ${ws} --follow`)}${snapshot ? "" : "\n"}`);
9784
+ if (snapshot) console.log(` ${c.dim(`foldrun report ${runId} patch --to ${ws} --apply (when it ends: put its changes into the folder)`)}\n`);
9750
9785
  return 0;
9751
9786
  }
9752
9787
 
@@ -12171,6 +12206,49 @@ async function snapshotCmd(positional, flags, layout) {
12171
12206
  const verb = positional[0];
12172
12207
  if (verb !== "push") throw new Error("`foldrun snapshot push [dir] --to <workspace>` — send a git folder for an agent on foldrun to work on (--dry-run, --out <file.tar.gz> [--force], --json)");
12173
12208
  const dir = path.resolve(positional[1] ?? ".");
12209
+ const { packed, left, unscanned, summary } = await packFolder(dir);
12210
+ if (typeof flags.out === "string") {
12211
+ // Never over a file that is there unless asked (--force), as export does:
12212
+ // a preview must not be able to destroy a file named by mistake (Codex).
12213
+ if (fs.existsSync(flags.out) && flags.force !== true) throw new Error(`${flags.out} already exists — --force replaces it`);
12214
+ fs.writeFileSync(flags.out, packed.archive);
12215
+ }
12216
+ if (flags["dry-run"] === true) {
12217
+ if (flags.json === true) console.log(JSON.stringify({ dryRun: true, snapshotId: packed.sha256, files: packed.files, bytes: packed.bytes, compressedBytes: packed.archive.length, leftOut: left, unscanned }, null, 2));
12218
+ else {
12219
+ console.log(`\n ${c.bold(summary)} ${c.dim(`· ${packed.sha256.slice(0, 12)}`)}`);
12220
+ for (const l of left.slice(0, 20)) console.log(` ${c.dim(`left out: ${l}`)}`);
12221
+ if (unscanned.length) console.log(` ${c.amber("!")} not checked for secrets (binary): ${unscanned.slice(0, 10).join(", ")}${unscanned.length > 10 ? " …" : ""}`);
12222
+ console.log(`\n ${c.dim("(--dry-run: nothing sent)")}\n`);
12223
+ }
12224
+ return 0;
12225
+ }
12226
+
12227
+ const url = platformFor(flags, "snapshot push");
12228
+ const ws = platformWorkspace(flags, layout, "snapshot push");
12229
+ const body = await pushPacked(url, flags, ws, packed);
12230
+ if (flags.json === true) {
12231
+ console.log(JSON.stringify({ ...body, leftOut: left, unscanned }, null, 2));
12232
+ return 0;
12233
+ }
12234
+ console.log(`\n ${c.green("✓")} ${summary} → ${c.bold(ws)}${body.reused ? c.dim(" (already there)") : ""}`);
12235
+ console.log(` snapshot ${c.bold(String(body.snapshotId))}`);
12236
+ console.log(` ${c.dim(`kept until ${body.expiresAt}, and while a run uses it`)}`);
12237
+ for (const l of left.slice(0, 20)) console.log(` ${c.dim(`left out: ${l}`)}`);
12238
+ if (unscanned.length) console.log(` ${c.amber("!")} not checked for secrets (binary): ${unscanned.slice(0, 10).join(", ")}${unscanned.length > 10 ? " …" : ""}`);
12239
+ console.log();
12240
+ return 0;
12241
+ }
12242
+
12243
+ /**
12244
+ * A git folder packed as a snapshot: what git would commit (the tracked files
12245
+ * and the untracked ones .gitignore does not exclude), as they are on disk
12246
+ * now. Links and anything that is not a plain file are left out and named; a
12247
+ * secret in any file refuses it before anything leaves the machine. Shared by
12248
+ * `snapshot push`, `agent run --snapshot` and `foldrun code`, so the three
12249
+ * send exactly the same thing.
12250
+ */
12251
+ async function packFolder(dir) {
12174
12252
  if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) throw new Error(`${dir} is not a folder`);
12175
12253
  const git = spawnSync("git", ["-C", dir, "ls-files", "-z", "--cached", "--others", "--exclude-standard"], { encoding: "buffer", maxBuffer: 256 * 1024 * 1024 });
12176
12254
  if (git.error || git.status !== 0) {
@@ -12233,26 +12311,13 @@ async function snapshotCmd(positional, flags, layout) {
12233
12311
  if (err instanceof SnapshotRefused) throw new Error(`not sent: ${err.message}`);
12234
12312
  throw err;
12235
12313
  }
12236
- if (typeof flags.out === "string") {
12237
- // Never over a file that is there unless asked (--force), as export does:
12238
- // a preview must not be able to destroy a file named by mistake (Codex).
12239
- if (fs.existsSync(flags.out) && flags.force !== true) throw new Error(`${flags.out} already exists — --force replaces it`);
12240
- fs.writeFileSync(flags.out, packed.archive);
12241
- }
12242
12314
  const summary = `${packed.files} file${packed.files === 1 ? "" : "s"}, ${packed.bytes} bytes (${packed.archive.length} compressed)`;
12243
- if (flags["dry-run"] === true) {
12244
- if (flags.json === true) console.log(JSON.stringify({ dryRun: true, snapshotId: packed.sha256, files: packed.files, bytes: packed.bytes, compressedBytes: packed.archive.length, leftOut: left, unscanned }, null, 2));
12245
- else {
12246
- console.log(`\n ${c.bold(summary)} ${c.dim(`· ${packed.sha256.slice(0, 12)}`)}`);
12247
- for (const l of left.slice(0, 20)) console.log(` ${c.dim(`left out: ${l}`)}`);
12248
- if (unscanned.length) console.log(` ${c.amber("!")} not checked for secrets (binary): ${unscanned.slice(0, 10).join(", ")}${unscanned.length > 10 ? " …" : ""}`);
12249
- console.log(`\n ${c.dim("(--dry-run: nothing sent)")}\n`);
12250
- }
12251
- return 0;
12252
- }
12315
+ return { packed, left, unscanned, summary };
12316
+ }
12253
12317
 
12254
- const url = platformFor(flags, "snapshot push");
12255
- const ws = platformWorkspace(flags, layout, "snapshot push");
12318
+ /** Send a packed folder to POST …/snapshots; answers the platform's body
12319
+ * ({ snapshotId, files, bytes, expiresAt, reused }). */
12320
+ async function pushPacked(url, flags, ws, packed) {
12256
12321
  const token = await renewedToken(url, flags);
12257
12322
  const res = await remoteFetch(
12258
12323
  url,
@@ -12268,17 +12333,544 @@ async function snapshotCmd(positional, flags, layout) {
12268
12333
  /* not JSON — the status says enough */
12269
12334
  }
12270
12335
  if (!res.ok) throw new HttpError(`${body.error ?? `snapshot push → HTTP ${res.status}`}${res.status === 401 || res.status === 403 ? refusedHint(url, flags) : ""}`, res.status, body);
12271
- if (flags.json === true) {
12272
- console.log(JSON.stringify({ ...body, leftOut: left, unscanned }, null, 2));
12336
+ return body;
12337
+ }
12338
+
12339
+ /** What a send left out, and what went without a secret scan (binary files):
12340
+ * named, as `snapshot push` names them, so nobody takes "checked" to cover them. */
12341
+ function sentNotes(left, unscanned) {
12342
+ for (const l of left.slice(0, 10)) console.log(` ${c.dim(`left out: ${l}`)}`);
12343
+ if (unscanned.length) console.log(` ${c.amber("!")} not checked for secrets (binary): ${unscanned.slice(0, 10).join(", ")}${unscanned.length > 10 ? " …" : ""}`);
12344
+ }
12345
+
12346
+ /** A snapshot id as the platform names one: the archive's sha256. */
12347
+ const SNAPSHOT_ID = /^[0-9a-f]{64}$/;
12348
+
12349
+ /**
12350
+ * `--snapshot [dir|id]` on `agent run`: the folder to send (bare: this one),
12351
+ * or the id a `snapshot push` answered. A folder is packed and sent first;
12352
+ * answers the id the run takes.
12353
+ */
12354
+ async function snapshotFor(url, flags, ws, value) {
12355
+ const given = value === true ? "." : String(value);
12356
+ if (SNAPSHOT_ID.test(given) && !fs.existsSync(given)) return given;
12357
+ const { packed, left, unscanned, summary } = await packFolder(path.resolve(given));
12358
+ const body = await pushPacked(url, flags, ws, packed);
12359
+ console.log(` ${c.dim(`sent ${summary} → snapshot ${String(body.snapshotId).slice(0, 12)}${body.reused ? " (already there)" : ""}`)}`);
12360
+ sentNotes(left, unscanned);
12361
+ return String(body.snapshotId);
12362
+ }
12363
+
12364
+ /**
12365
+ * The patch a snapshot run made, read from the run's archive: the agent's
12366
+ * outputs/snapshot.json says whether there is one (changed, unchanged, or
12367
+ * unavailable with the reason), outputs/snapshot.patch holds it. The patch
12368
+ * is made by the platform in the held pod against a fresh copy of what was
12369
+ * sent, never by the agent (platform snapshot-patch.ts).
12370
+ */
12371
+ async function runPatch(url, flags, ws, run, agentFlag) {
12372
+ // Only a run that was sent a folder has a patch the PLATFORM made: on any
12373
+ // other run, outputs/snapshot.patch is whatever the agent chose to write
12374
+ // there, and must never be applied as one (Codex review).
12375
+ if (!run.snapshot?.id) {
12376
+ return { agent: null, status: "none", reason: `run ${run.id} was not sent a folder (\`agent run --snapshot\`, \`foldrun code\`), so it has no patch` };
12377
+ }
12378
+ const agents = [...new Set((run.steps ?? []).filter((s) => !s.subagentOf).map((s) => s.agent))];
12379
+ const agent = typeof agentFlag === "string" ? agentFlag : agents.length === 1 ? agents[0] : null;
12380
+ if (!agent) throw new Error(`run ${run.id} has steps by ${agents.join(", ")} — say whose patch with --agent <name>`);
12381
+ const archive = (rel) => `/api/workspaces/${enc(ws)}/runs/${enc(run.id)}/archive?agent=${enc(agent)}&path=${enc(rel)}`;
12382
+ let meta;
12383
+ try {
12384
+ const { bytes } = await remoteBytes(url, flags, archive("snapshot.json"), `${agent}/snapshot.json in ${run.id}`);
12385
+ meta = JSON.parse(Buffer.from(bytes).toString("utf8"));
12386
+ } catch (err) {
12387
+ if (err instanceof HttpError && err.status === 404) {
12388
+ return { agent, status: "none", reason: `${agent} in ${run.id} has no snapshot.json — the run was not sent a folder (\`agent run --snapshot\`), or it has not finished` };
12389
+ }
12390
+ throw err;
12391
+ }
12392
+ if (meta?.status !== "changed") return { agent, status: meta?.status ?? "unavailable", reason: meta?.reason ?? null, meta };
12393
+ const { bytes } = await remoteBytes(url, flags, archive("snapshot.patch"), `${agent}/snapshot.patch in ${run.id}`);
12394
+ return { agent, status: "changed", meta, patch: Buffer.from(bytes) };
12395
+ }
12396
+
12397
+ /** What a patch changes, as git's own stat lines — read from the summary the platform wrote. */
12398
+ function patchSummaryLines(meta) {
12399
+ const out = [];
12400
+ for (const [list, mark] of [[meta?.modified, c.amber("M")], [meta?.added, c.green("A")], [meta?.deleted, c.red("D")]]) {
12401
+ for (const f of list ?? []) out.push(` ${mark} ${typeof f === "string" ? f : f?.path ?? JSON.stringify(f)}`);
12402
+ }
12403
+ return out;
12404
+ }
12405
+
12406
+ /**
12407
+ * Put a run's patch into a folder: `git apply --check` first, then git's own
12408
+ * stat, then a yes (or --yes), then `git apply`. Run from the repository's
12409
+ * top with --directory: a `git apply` started in a subfolder silently skips
12410
+ * every path the patch names, because patch paths read from the top.
12411
+ * Answers whether it was applied.
12412
+ */
12413
+ /** @param {{ asked: boolean, onAsk?: Set<() => void> } | null} [cancel] a turn's Ctrl-C state: pressed means "do not apply" */
12414
+ async function applyPatch(dir, patch, flags, label, cancel = null) {
12415
+ const top = spawnSync("git", ["-C", dir, "rev-parse", "--show-toplevel"], { encoding: "utf8" });
12416
+ const pre = spawnSync("git", ["-C", dir, "rev-parse", "--show-prefix"], { encoding: "utf8" });
12417
+ if (top.status !== 0 || pre.status !== 0) throw new Error(`${dir} is not in a git repository — the patch is applied with git`);
12418
+ // Only git's own line ending is taken off: a folder whose name starts or
12419
+ // ends with a space is still that folder, not its neighbour (Codex).
12420
+ const root = top.stdout.replace(/\r?\n$/, "");
12421
+ const prefix = pre.stdout.replace(/\r?\n$/, "").replace(/\/$/, "");
12422
+ if (fs.realpathSync(path.join(root, prefix)) !== fs.realpathSync(dir)) {
12423
+ throw new Error(`git places ${dir} at ${path.join(root, prefix)} — not applying a patch to a folder other than the one named`);
12424
+ }
12425
+ // The patch goes to git on stdin, from memory: the bytes checked are the
12426
+ // bytes applied, and no file in a shared temp folder can be swapped or
12427
+ // aimed elsewhere in between (Codex).
12428
+ const git = (...more) => spawnSync("git", ["-C", root, "apply", ...(prefix ? [`--directory=${prefix}`] : []), ...more], { input: patch, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
12429
+ const check = git("--check");
12430
+ if (check.status !== 0 || check.error) {
12431
+ throw new Error(`the patch does not apply to ${dir} as it is now — it was made against the folder as it was sent. git said:\n${String(check.stderr).trim()}\nThe patch is kept at ${keepPatch(patch, label)}`);
12432
+ }
12433
+ // git refuses paths that climb out, name .git, or pass through a link; it
12434
+ // would still make or change a link or a submodule entry, which the
12435
+ // platform's own patch never holds (snapshot-patch.ts refuses links, and
12436
+ // diffs with --no-renames). Read from the patch's own header lines, which
12437
+ // no hunk line can imitate (those begin with space, + , - or \\), never
12438
+ // from git's display output (Codex).
12439
+ const odd = patchTypeProblems(String(patch));
12440
+ // An existing path that is a link here is refused too, whatever mode the
12441
+ // patch claims for it.
12442
+ const touched = git("--numstat", "-z");
12443
+ if (touched.status !== 0 || touched.error) throw new Error(`git could not read the patch: ${String(touched.stderr || touched.error?.message).trim()}`);
12444
+ for (const rel of numstatPaths(String(touched.stdout))) {
12445
+ /** @type {fs.Stats | null} */
12446
+ let st = null;
12447
+ try {
12448
+ st = fs.lstatSync(path.join(root, rel));
12449
+ } catch {
12450
+ /* a new file */
12451
+ }
12452
+ if (st?.isSymbolicLink()) odd.push(`${rel} is a link in this folder`);
12453
+ }
12454
+ if (odd.length) {
12455
+ throw new Error(`the patch makes or changes a link, a submodule, a rename or a copy, which foldrun's patches never do — not applied:\n${odd.join("\n")}\nThe patch is kept at ${keepPatch(patch, label)}`);
12456
+ }
12457
+ for (const line of String(git("--stat").stdout).trimEnd().split("\n")) if (line.trim()) console.log(` ${line.trim()}`);
12458
+ if (flags.yes !== true && !process.stdin.isTTY) {
12459
+ console.log(` ${c.dim(`not applied — no terminal to ask, and --yes applies without asking. The patch is at ${keepPatch(patch, label)}`)}`);
12460
+ return false;
12461
+ }
12462
+ if (flags.yes !== true && !/^y(es)?$/i.test((await cancellablePrompt(` apply it to ${dir}? [y/N] `, cancel)) ?? "")) {
12463
+ console.log(` ${c.dim(`not applied — the patch is at ${keepPatch(patch, label)}`)}`);
12464
+ return false;
12465
+ }
12466
+ // The checks above run git synchronously, and a Ctrl-C pressed meanwhile
12467
+ // reaches its handler only when the event loop turns — which --yes would
12468
+ // never let it do before the apply. A timer passes through the loop's
12469
+ // poll phase, where the signal is delivered (Codex).
12470
+ await new Promise((resolve) => setTimeout(resolve, 20));
12471
+ if (cancel?.asked) {
12472
+ console.log(` ${c.dim(`not applied — you pressed Ctrl-C. The patch is at ${keepPatch(patch, label)}`)}`);
12473
+ return false;
12474
+ }
12475
+ const done = git();
12476
+ if (done.status !== 0 || done.error) throw new Error(`git apply failed: ${String(done.stderr).trim()} — the patch is kept at ${keepPatch(patch, label)}`);
12477
+ console.log(` ${c.green("✓")} applied ${c.dim("— review it with git diff, and commit it when you are happy")}`);
12478
+ return true;
12479
+ }
12480
+
12481
+ /** The header lines of a patch that a foldrun patch never has. An
12482
+ * allowlist, not a list of bad modes: git reads a mode as octal, so
12483
+ * `0120000` is a link to it too (Codex, reproduced) — so every mode line
12484
+ * must say exactly 100644 or 100755, an index line may carry only those,
12485
+ * and renames, copies and similarity headers are refused outright (the
12486
+ * platform diffs with --no-renames). Header lines only: inside a hunk every
12487
+ * line begins with a space, "+", "-" or "\\", so file content cannot pose
12488
+ * as one. */
12489
+ export function patchTypeProblems(patch) {
12490
+ const out = [];
12491
+ let inHunk = false;
12492
+ for (const line of patch.split("\n")) {
12493
+ if (line.startsWith("diff --git ")) inHunk = false;
12494
+ else if (line.startsWith("@@")) inHunk = true;
12495
+ if (inHunk && /^[ +\-\\]/.test(line)) continue;
12496
+ if (/^(?:new file mode|deleted file mode|new mode|old mode)/.test(line)) {
12497
+ if (!/^(?:new file mode|deleted file mode|new mode|old mode) 100(?:644|755)$/.test(line)) out.push(line);
12498
+ } else if (line.startsWith("index ")) {
12499
+ if (!/^index [0-9a-f]+\.\.[0-9a-f]+(?: 100644| 100755)?$/.test(line)) out.push(line);
12500
+ } else if (/^(?:rename|copy|similarity index|dissimilarity index)\b/.test(line)) out.push(line);
12501
+ }
12502
+ return out;
12503
+ }
12504
+
12505
+ /** The paths of `git apply --numstat -z`: "<added>\t<deleted>\t<path>\0" per file. */
12506
+ function numstatPaths(out) {
12507
+ return out.split("\0").map((rec) => rec.split("\t").slice(2).join("\t")).filter(Boolean);
12508
+ }
12509
+
12510
+ /** A one-line answer from the terminal that Ctrl-C (via `cancel.onAsk`) or
12511
+ * EOF ends with null, its listeners removed — so the session goes on to
12512
+ * its next prompt rather than waiting for a line nobody will type (Codex). */
12513
+ function cancellablePrompt(question, cancel) {
12514
+ return new Promise((resolve) => {
12515
+ const { stdin } = process;
12516
+ const done = (/** @type {string | null} */ v) => {
12517
+ stdin.off("data", onData);
12518
+ stdin.off("end", onEnd);
12519
+ cancel?.onAsk?.delete(onCancel);
12520
+ stdin.pause();
12521
+ resolve(v);
12522
+ };
12523
+ const onData = (/** @type {string} */ line) => done(String(line).replace(/\r?\n$/, ""));
12524
+ const onEnd = () => done(null);
12525
+ const onCancel = () => {
12526
+ process.stdout.write("\n");
12527
+ done(null);
12528
+ };
12529
+ process.stdout.write(question);
12530
+ if (cancel?.asked) return done(null);
12531
+ cancel?.onAsk?.add(onCancel);
12532
+ stdin.setEncoding("utf8");
12533
+ stdin.once("data", onData);
12534
+ stdin.once("end", onEnd);
12535
+ stdin.resume();
12536
+ });
12537
+ }
12538
+
12539
+ /** A patch not applied, kept for the person: in a fresh private folder
12540
+ * (0700), as a new file (0600) that refuses to open anything already there. */
12541
+ function keepPatch(patch, label) {
12542
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "foldrun-patch-"));
12543
+ const file = path.join(dir, `${String(label).replace(/[^A-Za-z0-9_.-]/g, "_")}.patch`);
12544
+ fs.writeFileSync(file, patch, { mode: 0o600, flag: "wx" });
12545
+ return file;
12546
+ }
12547
+
12548
+ /**
12549
+ * `foldrun report <run-id> patch [--apply] [--dir <folder>] [--agent <name>]`
12550
+ * — the patch a snapshot run made. Without --apply the patch itself goes to
12551
+ * stdout (so `> fix.patch` or `| git apply` work) and what it changes to
12552
+ * stderr; with --apply it is put into --dir (this folder by default) after
12553
+ * `git apply --check`, asking first unless --yes.
12554
+ */
12555
+ async function reportPatchCmd(runId, flags, layout) {
12556
+ if (!runId) throw new Error("`foldrun report <run-id> patch` — which run?");
12557
+ const url = platformFor(flags, "report patch");
12558
+ const ws = await workspaceOfRun(url, flags, layout, runId);
12559
+ const run = await remoteCall(url, flags, `/api/workspaces/${enc(ws)}/runs/${enc(runId)}`);
12560
+ if (isLive(run)) throw new Error(`run ${runId} is still ${run.status} — the patch is made when it ends (\`foldrun logs ${runId} --to ${ws} --follow\`)`);
12561
+ const p = await runPatch(url, flags, ws, run, flags.agent);
12562
+ if (p.status === "unchanged") {
12563
+ console.error(`\n ${c.dim(`${p.agent} changed nothing in the folder it was sent`)}\n`);
12273
12564
  return 0;
12274
12565
  }
12275
- console.log(`\n ${c.green("✓")} ${summary} → ${c.bold(ws)}${body.reused ? c.dim(" (already there)") : ""}`);
12276
- console.log(` snapshot ${c.bold(String(body.snapshotId))}`);
12277
- console.log(` ${c.dim(`kept until ${body.expiresAt}, and while a run uses it`)}`);
12278
- for (const l of left.slice(0, 20)) console.log(` ${c.dim(`left out: ${l}`)}`);
12279
- if (unscanned.length) console.log(` ${c.amber("!")} not checked for secrets (binary): ${unscanned.slice(0, 10).join(", ")}${unscanned.length > 10 ? " …" : ""}`);
12566
+ if (p.status !== "changed") {
12567
+ console.error(`\n ${c.red("✗")} no patch: ${p.reason ?? p.status}\n`);
12568
+ return 1;
12569
+ }
12570
+ if (flags.apply !== true) {
12571
+ console.error(["", ...patchSummaryLines(p.meta), ""].join("\n"));
12572
+ // Waited for: the CLI exits as soon as this returns, and an unflushed
12573
+ // pipe would hand `| git apply` half a patch (Codex).
12574
+ await new Promise((resolve) => process.stdout.write(p.patch ?? "", () => resolve(undefined)));
12575
+ return 0;
12576
+ }
12577
+ const dir = path.resolve(typeof flags.dir === "string" ? flags.dir : ".");
12578
+ console.log(`\n ${c.bold(`patch from ${runId}`)} ${c.dim(`· ${p.agent} · into ${dir}`)}\n`);
12579
+ const applied = await applyPatch(dir, p.patch, flags, runId);
12280
12580
  console.log();
12281
- return 0;
12581
+ return applied ? 0 : 1;
12582
+ }
12583
+
12584
+ /** The agent `foldrun code` makes in a project that has none. Plain
12585
+ * markdown like any other: the person edits its tools, model, hooks and
12586
+ * limits in the file (or the dashboard), and every turn runs it in its
12587
+ * own sandbox. */
12588
+ export const CODER_AGENT = `---
12589
+ name: coder
12590
+ description: Changes code in a folder sent by \`foldrun code\`, and checks the change with the folder's own tests.
12591
+ model: default
12592
+ effort: medium
12593
+ tools: [write, code]
12594
+ ---
12595
+
12596
+ You work on a code folder a person sent from their computer. It is in
12597
+ snapshot/ under your working directory. Only what you change there comes
12598
+ back to them, as a patch they review and apply.
12599
+
12600
+ - Read before you change anything: find the files the task is about, and
12601
+ the project's own conventions (README, AGENTS.md, CLAUDE.md, the tests).
12602
+ - Make the smallest change that does the task. Do not reformat, rename or
12603
+ tidy what the task does not need.
12604
+ - Run the project's tests or build for what you changed, and fix what
12605
+ fails. If you cannot run them (a service is missing, a package will not
12606
+ install), say so plainly rather than guessing they pass.
12607
+ - Never put a secret in a file, and never create .git or links in
12608
+ snapshot/.
12609
+ - End with a short summary: what you changed, file by file, and what you
12610
+ ran to check it.
12611
+ `;
12612
+
12613
+ /** `foldrun code` needs its agent in the project; offers to make `coder`. */
12614
+ /**
12615
+ * The project `foldrun code --to` names, made when it is not there (owner,
12616
+ * 19 Nov 2026): one question — or --yes — makes it blank, with the coder
12617
+ * agent (ensureCodeAgent adds it without asking again). Created with
12618
+ * ifAbsent, so a project made meanwhile is used, never written over. True
12619
+ * when it was made now.
12620
+ */
12621
+ async function ensureCodeProject(url, flags, ws, agent) {
12622
+ try {
12623
+ await remoteCall(url, flags, `/api/workspaces/${enc(ws)}`);
12624
+ return false;
12625
+ } catch (err) {
12626
+ if (!(err instanceof HttpError && err.status === 404)) throw err;
12627
+ }
12628
+ assertName(ws);
12629
+ if (agent !== "coder") throw new Error(`no project "${ws}" on ${url}, so no agent "${agent}" in it — leave out --agent and foldrun code offers to make the project with a coder agent`);
12630
+ console.log(`\n ${c.amber("!")} there is no project ${c.bold(ws)} on ${url}.`);
12631
+ console.log(` ${c.dim("foldrun code can make it — blank, with a coder agent (agents/coder/agent.md: tools [write, code], model default) to edit like any other.")}`);
12632
+ if (!(await confirmed(flags, "foldrun code", `create ${ws}? [y/N] `))) throw new Error(`nothing created — \`foldrun workspaces new ${ws} --platform\` makes it, or name one that exists with --to`);
12633
+ try {
12634
+ await remoteCall(url, flags, "/api/workspaces", { method: "POST", body: JSON.stringify({ name: ws, template: true, ifAbsent: true }) });
12635
+ } catch (err) {
12636
+ if (!(err instanceof HttpError && err.status === 409)) throw err;
12637
+ return false; // made meanwhile: used as it is
12638
+ }
12639
+ console.log(` ${c.green("✓")} created ${ws}`);
12640
+ return true;
12641
+ }
12642
+
12643
+ /** @param {boolean} [fresh] the project was made this moment: add the agent without asking twice */
12644
+ async function ensureCodeAgent(url, flags, ws, agent, fresh = false) {
12645
+ const r = await remoteCall(url, flags, `/api/workspaces/${enc(ws)}/agents`);
12646
+ if ((r.agents ?? []).some((a) => a.name === agent)) return;
12647
+ if (agent !== "coder") throw new Error(`no agent "${agent}" in ${ws} — \`foldrun agent ls --to ${ws}\` lists them; leave out --agent and foldrun code offers to make one called coder`);
12648
+ if (!fresh) {
12649
+ console.log(`\n ${c.amber("!")} ${ws} has no ${c.bold("coder")} agent yet.`);
12650
+ console.log(` ${c.dim("foldrun code can add one (agents/coder/agent.md: tools [write, code], model default) — edit it afterwards like any agent.")}`);
12651
+ if (!(await confirmed(flags, "foldrun code", `add it to ${ws}? [y/N] `))) throw new Error(`nothing started — add an agent with \`foldrun agent new\`, or name one with --agent <name>`);
12652
+ }
12653
+ // Create-only (ifMatch: null): a coder written meanwhile — another
12654
+ // session, or someone while this one waited for the yes — is used, never
12655
+ // written over (Codex).
12656
+ try {
12657
+ await remoteCall(url, flags, `/api/workspaces/${enc(ws)}/source`, {
12658
+ method: "PUT",
12659
+ body: JSON.stringify({ path: "agents/coder/agent.md", content: CODER_AGENT, message: "foldrun code: the coder agent", ifMatch: null }),
12660
+ });
12661
+ } catch (err) {
12662
+ if (err instanceof HttpError && err.status === 409) {
12663
+ console.log(` ${c.dim(`a coder agent appeared in ${ws} meanwhile — using that one`)}`);
12664
+ return;
12665
+ }
12666
+ throw err;
12667
+ }
12668
+ console.log(` ${c.green("✓")} added agents/coder/agent.md to ${ws}`);
12669
+ }
12670
+
12671
+ /**
12672
+ * One turn of `foldrun code`: the folder as it is now goes as a snapshot,
12673
+ * the agent runs on it in its own sandbox (a turn of the session's
12674
+ * conversation, so it reads the earlier turns), its events print as they
12675
+ * happen, and the patch it leaves is offered to apply. Ctrl-C stops the run
12676
+ * on the platform. Answers the run's status.
12677
+ */
12678
+ async function codeTurn(s, task) {
12679
+ const { url, flags, ws, agent, dir } = s;
12680
+ // Ctrl-C is recorded the moment it is pressed, before the run even has an
12681
+ // id, and an interrupted turn never applies a patch — however the race
12682
+ // between the stop and the run's own end comes out (Codex). A second
12683
+ // Ctrl-C retries a stop that failed; after a stop was sent, it leaves.
12684
+ // stop: "none" (not sent, or sent and refused), "inflight", "acked".
12685
+ // Ctrl-C is recorded the moment it is pressed, and only an ACKNOWLEDGED
12686
+ // stop lets a further Ctrl-C leave: never while the stop is still on its
12687
+ // way (Codex). After the run ended (phase "patch"), Ctrl-C means "do not
12688
+ // apply", and the session goes on.
12689
+ /** @type {{ asked: boolean, runId: string | null, stop: "none" | "inflight" | "acked", phase: "run" | "patch", stopPromise: Promise<unknown> | null, onAsk: Set<() => void> }} */
12690
+ const cancel = { asked: false, runId: null, stop: "none", phase: "run", stopPromise: null, onAsk: new Set() };
12691
+ const stop = () => {
12692
+ if (!cancel.runId || cancel.stop !== "none") return;
12693
+ cancel.stop = "inflight";
12694
+ cancel.stopPromise = remoteCall(url, flags, `/api/workspaces/${enc(ws)}/runs/${enc(cancel.runId)}/stop`, { method: "POST", body: "{}" }).then(
12695
+ () => (cancel.stop = "acked"),
12696
+ (err) => {
12697
+ cancel.stop = "none";
12698
+ console.log(` ${c.red("✗")} stop: ${explain(err)} — Ctrl-C again tries once more`);
12699
+ },
12700
+ );
12701
+ };
12702
+ const onInt = () => {
12703
+ if (cancel.phase === "patch") {
12704
+ if (!cancel.asked) console.log(`\n ${c.amber("not applying")} ${c.dim("— this turn's patch will be kept, not applied")}`);
12705
+ cancel.asked = true;
12706
+ for (const f of [...cancel.onAsk]) f();
12707
+ return;
12708
+ }
12709
+ if (cancel.asked && cancel.stop === "acked") {
12710
+ console.log(`\n ${c.dim(`left — the platform took the stop for ${cancel.runId}`)}`);
12711
+ process.exit(130);
12712
+ }
12713
+ if (cancel.asked && cancel.stop === "inflight") {
12714
+ console.log(`\n ${c.dim("the stop is on its way to the platform — waiting for its answer")}`);
12715
+ return;
12716
+ }
12717
+ if (cancel.asked && !cancel.runId) {
12718
+ console.log(`\n ${c.dim("waiting for the run to start, so it can be stopped")}`);
12719
+ return;
12720
+ }
12721
+ cancel.asked = true;
12722
+ console.log(`\n ${c.amber("stopping")}${cancel.runId ? ` ${cancel.runId}` : ""} …`);
12723
+ stop();
12724
+ };
12725
+ process.on("SIGINT", onInt);
12726
+ let run;
12727
+ let runId;
12728
+ try {
12729
+ const { packed, left, unscanned, summary } = await packFolder(dir);
12730
+ if (cancel.asked) return "cancelled";
12731
+ const snap = await pushPacked(url, flags, ws, packed);
12732
+ console.log(` ${c.dim(`sent ${summary}${snap.reused ? " (already there)" : ""}`)}`);
12733
+ sentNotes(left, unscanned);
12734
+ if (cancel.asked) return "cancelled";
12735
+ let started;
12736
+ try {
12737
+ started = await remoteCall(url, flags, `/api/workspaces/${enc(ws)}/agents/${enc(agent)}/run`, {
12738
+ method: "POST",
12739
+ body: JSON.stringify({ task, snapshot: String(snap.snapshotId), context: s.context, ...(flags.test === true ? { test: true } : {}) }),
12740
+ });
12741
+ } catch (err) {
12742
+ // The platform may have taken the run before the answer was lost.
12743
+ if (cancel.asked) throw new Error(`${explain(err)} — the run may have started anyway: \`foldrun runs --to ${ws}\` shows it, and \`foldrun stop <run-id>\` stops it`);
12744
+ throw err;
12745
+ }
12746
+ runId = started?.runId;
12747
+ if (!runId) throw new Error(`${url} started no run — ${JSON.stringify(started).slice(0, 200)}`);
12748
+ cancel.runId = runId;
12749
+ if (cancel.asked) stop(); // pressed while the run was being started
12750
+ console.log(` ${c.dim(`run ${runId}${started.test ? " (test)" : ""} — Ctrl-C stops it; the dashboard shows it live`)}\n`);
12751
+ run = await remoteCall(url, flags, `/api/workspaces/${enc(ws)}/runs/${enc(runId)}`);
12752
+ const seen = new Map();
12753
+ const open = new Map();
12754
+ printNew(run, seen, open);
12755
+ if (isLive(run)) run = (await followRemote(url, flags, ws, runId, seen, open, { holdOpen: true })) ?? run;
12756
+ if (isLive(run)) {
12757
+ run = await remoteCall(url, flags, `/api/workspaces/${enc(ws)}/runs/${enc(runId)}`);
12758
+ printNew(run, seen, open);
12759
+ }
12760
+ flushCalls(open);
12761
+ cancel.phase = "patch";
12762
+
12763
+ const own = (run.steps ?? []).filter((x) => !x.subagentOf);
12764
+ const reply = own.at(-1)?.result;
12765
+ if (reply) console.log(`\n${String(reply).trim().split("\n").map((l) => ` ${l}`).join("\n")}`);
12766
+ const cost = (run.steps ?? []).reduce((sum, x) => sum + (x.costUsd ?? 0), 0);
12767
+ console.log(`\n ${run.status === "completed" ? c.green("✓") : c.red("✗")} ${run.status} ${c.dim(`· $${cost.toFixed(4)} · ${runId}`)}`);
12768
+ if (cancel.asked) {
12769
+ console.log(` ${c.dim(`stopped by you — nothing applied. What it made, if anything: foldrun report ${runId} patch --to ${ws}`)}\n`);
12770
+ return "cancelled";
12771
+ }
12772
+ if (run.status !== "completed") {
12773
+ console.log(` ${c.dim(`foldrun report ${runId} --to ${ws} — what happened; a patch it made anyway: foldrun report ${runId} patch --to ${ws}`)}\n`);
12774
+ return run.status;
12775
+ }
12776
+ const p = await runPatch(url, flags, ws, run, agent);
12777
+ if (cancel.asked) {
12778
+ console.log(` ${c.dim(`not applied — you pressed Ctrl-C. It stays on the run: foldrun report ${runId} patch --to ${ws}`)}\n`);
12779
+ return run.status;
12780
+ }
12781
+ if (p.status === "unchanged") console.log(` ${c.dim("no change to the folder")}\n`);
12782
+ else if (p.status !== "changed") console.log(` ${c.amber("!")} no patch: ${p.reason ?? p.status}\n`);
12783
+ else {
12784
+ console.log();
12785
+ await applyPatch(dir, p.patch, flags, runId, cancel);
12786
+ console.log();
12787
+ }
12788
+ return run.status;
12789
+ } finally {
12790
+ // A stop still on its way is waited for on every way out — a thrown
12791
+ // follower included — so the turn never ends before the platform was
12792
+ // told, and says so when it cannot tell (Codex).
12793
+ if (cancel.stop === "inflight" && cancel.stopPromise) {
12794
+ const answered = await Promise.race([cancel.stopPromise.then(() => true), new Promise((r) => setTimeout(() => r(false), timeoutSeconds(flags) * 1000))]);
12795
+ if (!answered) console.log(` ${c.amber("!")} the stop for ${cancel.runId} was sent but the platform has not answered — \`foldrun runs --to ${ws}\` shows whether it is still going`);
12796
+ }
12797
+ process.off("SIGINT", onInt);
12798
+ }
12799
+ }
12800
+
12801
+ /**
12802
+ * `foldrun code [dir] --to <workspace>` — code with an agent that works in
12803
+ * a sandbox on the platform, not on this computer. Each message sends the
12804
+ * folder as a snapshot (what git would commit, checked for secrets here and
12805
+ * there), runs the agent on it in its own pod — gVisor where the install
12806
+ * runs it — and offers the patch it hands back, which `git apply` puts into
12807
+ * the folder after a yes. Nothing the agent runs touches this machine.
12808
+ *
12809
+ * The agent is an ordinary agent file (`--agent`, default `coder`, made on
12810
+ * first use with a yes), so its tools, model, hooks, limits and network are
12811
+ * frontmatter like any other; each turn is an ordinary run, on the run page
12812
+ * of whatever install this profile is signed in to. The turns of a session
12813
+ * share a conversation (`context`), so the agent reads the earlier ones.
12814
+ *
12815
+ * `--task "…"` runs one turn and exits (for scripts; 0 when it completed,
12816
+ * 130 when you stopped it, 1 otherwise); with no terminal it needs --yes to
12817
+ * apply. /new starts a fresh conversation, /quit leaves.
12818
+ */
12819
+ async function codeCmd(positional, flags, layout) {
12820
+ const dir = path.resolve(positional[0] ?? ".");
12821
+ if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) throw new Error(`${dir} is not a folder`);
12822
+ if (spawnSync("git", ["-C", dir, "rev-parse", "--show-toplevel"], { encoding: "utf8" }).status !== 0) {
12823
+ throw new Error(`${dir} is not in a git repository — foldrun code sends what git would commit and applies the agent's patch with git, so \`git init\` it first`);
12824
+ }
12825
+ const url = platformFor(flags, "code");
12826
+ const ws = platformWorkspace(flags, layout, "code");
12827
+ const agent = typeof flags.agent === "string" ? flags.agent : "coder";
12828
+ // Usage first: a call that cannot run must not add an agent on its way out (Codex).
12829
+ if (typeof flags.task === "string" && !flags.task.trim()) throw new Error('--task needs the instruction, e.g. --task "add a test for the parser"');
12830
+ if (typeof flags.task !== "string" && !process.stdin.isTTY) throw new Error('foldrun code is a conversation — in a script, give one turn with --task "…" (and --yes to apply the patch)');
12831
+ await ensureCodeAgent(url, flags, ws, agent, await ensureCodeProject(url, flags, ws, agent));
12832
+ const newContext = () => `code-${crypto.randomBytes(8).toString("hex")}`;
12833
+ const s = { url, flags, ws, agent, dir, context: typeof flags.context === "string" ? flags.context : newContext() };
12834
+
12835
+ if (typeof flags.task === "string") {
12836
+ console.log(`\n ${c.bold("foldrun code")} ${c.dim(`· ${agent} · ${ws} · ${dir}`)}\n`);
12837
+ const status = await codeTurn(s, flags.task.trim());
12838
+ return status === "completed" ? 0 : status === "cancelled" ? 130 : 1;
12839
+ }
12840
+ const { createInterface } = await import("node:readline/promises");
12841
+ console.log(`\n ${c.bold("foldrun code")} ${c.dim(`· ${agent} · ${ws} on ${url}`)}`);
12842
+ console.log(` ${c.dim(`${dir} — each message sends it to a sandbox; you apply what comes back`)}`);
12843
+ console.log(` ${c.dim("/new a fresh conversation /quit leave")}\n`);
12844
+ for (;;) {
12845
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
12846
+ // Closing the input (Ctrl-D) leaves question() unsettled on Node 26 —
12847
+ // it neither resolves nor rejects — so the close is raced with it.
12848
+ const answer = await new Promise((resolve) => {
12849
+ rl.once("close", () => resolve(null));
12850
+ rl.question(`${c.bold("you ›")} `).then(resolve, () => resolve(null));
12851
+ });
12852
+ rl.close();
12853
+ const line = answer === null ? "/quit" : String(answer).trim();
12854
+ if (!line) continue;
12855
+ if (line === "/quit" || line === "/exit") {
12856
+ console.log();
12857
+ return 0;
12858
+ }
12859
+ if (line === "/new") {
12860
+ s.context = newContext();
12861
+ console.log(` ${c.dim("a fresh conversation — the agent no longer reads the earlier turns")}\n`);
12862
+ continue;
12863
+ }
12864
+ if (line.startsWith("/")) {
12865
+ console.log(` ${c.dim("/new a fresh conversation /quit leave")}\n`);
12866
+ continue;
12867
+ }
12868
+ try {
12869
+ await codeTurn(s, line);
12870
+ } catch (err) {
12871
+ console.log(` ${c.red("✗")} ${explain(err)}\n`);
12872
+ }
12873
+ }
12282
12874
  }
12283
12875
 
12284
12876
  /**
@@ -16023,6 +16615,8 @@ export async function run(command, positional, flags, workspace, layout) {
16023
16615
  return importCmd(positional, flags, layout);
16024
16616
  case "snapshot":
16025
16617
  return snapshotCmd(positional, flags, layout);
16618
+ case "code":
16619
+ return codeCmd(positional, flags, layout);
16026
16620
  case "status":
16027
16621
  return statusCmd(layout, flags, positional[0]);
16028
16622
  case "workspaces":
@@ -16150,6 +16744,7 @@ export async function run(command, positional, flags, workspace, layout) {
16150
16744
  case "report":
16151
16745
  if (positional[1] === "live") return reportLiveCmd(positional[0], flags, layout);
16152
16746
  if (positional[1] === "call") return reportCallCmd(positional[0], positional[2], flags, layout);
16747
+ if (positional[1] === "patch") return reportPatchCmd(positional[0], flags, layout);
16153
16748
  return positional[1] === "get" ? reportGetCmd(positional[0], positional[2], flags, layout) : reportCmd(positional[0], flags, layout);
16154
16749
  case "stop":
16155
16750
  // No run id and a filter: every run the filter matches (runs/bulk).