foldrun 26.7.0 → 26.8.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
@@ -121,7 +121,7 @@ const HELP = `foldrun — agents are just folders
121
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
122
122
  foldrun agent run <name> run one agent once on the platform (--task "…", --to, --wait, --test, --context <id>, --file <path> repeatable)
123
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>)
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>, --verbose the platform's notes on each step too)
125
125
  foldrun agent run <name> --no-task run it with no instruction, on its own prompt alone — the dashboard's Run (--to, --wait, --test)
126
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)
127
127
  foldrun agent unlink <agent> take one away: --subagent <name>, --consult <name> or --can-ask
package/docs/cli.md CHANGED
@@ -136,7 +136,7 @@ claude.ai or Claude Code there, nor any MCP configuration on disk.
136
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`) |
137
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`) |
138
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>` |
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 (its tool calls and words, and any refusal or failure; the platform's other notes on the step stay on the run page, `--verbose` shows them too), 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>`, `--verbose` |
140
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 |
141
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 |
142
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` |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "foldrun",
3
- "version": "26.7.0",
3
+ "version": "26.8.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",
@@ -11,7 +11,7 @@
11
11
  "node": ">=22"
12
12
  },
13
13
  "dependencies": {
14
- "@foldrun/core": "^24.3.0"
14
+ "@foldrun/core": "^24.3.1"
15
15
  },
16
16
  "files": [
17
17
  "bin",
@@ -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-workspaces-use.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",
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-workspaces-use.test.ts tests/cli-credentials-lock.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
@@ -2741,21 +2741,95 @@ function eventLine(e, rawAgent, open) {
2741
2741
  * tool call is two events — one line per call, printed when it completes.
2742
2742
  * `open` carries the calls still in flight across polls and reconnects.
2743
2743
  */
2744
- function printNew(run, seen, open = new Map(), { skipResult = false } = {}) {
2744
+ export function printNew(run, seen, open = new Map(), { skipResult = false, quiet = false } = {}) {
2745
2745
  // skipResult: the caller prints the last top-level step's reply in full
2746
2746
  // afterwards (foldrun code), so that one step's reply line is not printed
2747
- // twice; any other step's (a sub-agent's) stays (Codex).
2747
+ // twice; any other step's (a sub-agent's) stays (Codex). While the run is
2748
+ // live the step has no result yet to compare with, so that step's newest
2749
+ // text is HELD until something follows it: a tool call after it means it
2750
+ // was a remark on the way and it is printed; the run ending with it means
2751
+ // it is the reply (dropHeldReply) — 19 Nov 2026, the reply showed twice.
2752
+ // quiet (foldrun code): the platform's own notes on the step (`info`:
2753
+ // clock, credential, isolation, network, dns, timing, egress …) are left
2754
+ // to the run page; tool calls, the agent's words and errors stay.
2755
+ // An info note is not "something after" the held text: it neither
2756
+ // releases it (a trailing note would print the reply before its result,
2757
+ // then the caller again — Codex) nor, when quiet, shows at all — except a
2758
+ // note that something was refused (a `limits:` refusal is an info note,
2759
+ // and the user must see why a call did not run — Codex).
2748
2760
  const own = run.steps.filter((x) => !x.subagentOf);
2749
2761
  const replying = skipResult ? own.at(-1) : undefined;
2762
+ const held = heldText(seen);
2763
+ // Steps are visited in order, not in time: an older event of a later step
2764
+ // (a sub-agent's, unseen until this frame) must not release a parent's
2765
+ // newer text — that text may be the reply, whose result is still to come
2766
+ // (Codex). Events carry `t`; without one, the event releases.
2767
+ const release = (by) => {
2768
+ for (const [j, h] of held) {
2769
+ if (by?.t && h.t && String(by.t) < String(h.t)) continue;
2770
+ console.log(eventLine(h, run.steps[j]?.agent, open));
2771
+ held.delete(j);
2772
+ }
2773
+ };
2774
+ // One frame's new events, from every step, in the order they happened
2775
+ // (`t`; stable, so events with no time keep step order): a sub-agent's
2776
+ // call between two of the parent's remarks prints between them (Codex).
2777
+ const fresh = [];
2750
2778
  run.steps.forEach((step, i) => {
2751
2779
  const from = seen.get(i) ?? 0;
2752
- for (const e of step.events.slice(from)) {
2753
- if (step === replying && e.type === "text" && step.result && String(e.text).trim() === String(step.result).trim()) continue;
2754
- const line = eventLine(e, step.agent, open);
2755
- if (line !== null) console.log(line);
2756
- }
2780
+ step.events.slice(from).forEach((e) => fresh.push({ i, step, e }));
2757
2781
  seen.set(i, step.events.length);
2758
2782
  });
2783
+ if (fresh.every((x) => x.e.t)) fresh.sort((a, b) => (String(a.e.t) < String(b.e.t) ? -1 : String(a.e.t) > String(b.e.t) ? 1 : 0));
2784
+ for (const { i, step, e } of fresh) {
2785
+ const note = e.type === "info";
2786
+ if (note && quiet && !REFUSED_NOTE.test(String(e.text ?? ""))) continue;
2787
+ if (step === replying && e.type === "text") {
2788
+ if (step.result && String(e.text).trim() === String(step.result).trim()) continue;
2789
+ release();
2790
+ held.set(i, { ...e, __agent: step.agent });
2791
+ continue;
2792
+ }
2793
+ // Anything else that is not a note — a tool call, an error, any other
2794
+ // step's words (a sub-agent's) — came after the held text: it shows first.
2795
+ if (!note) release(e);
2796
+ const line = eventLine(e, step.agent, open);
2797
+ if (line !== null) console.log(line);
2798
+ }
2799
+ }
2800
+
2801
+ /** An info note that something was refused or went wrong (a `limits:`
2802
+ * refusal, "browser pod: reconnect failed …"): shown even in the quiet view. */
2803
+ const REFUSED_NOTE = /\b(refused|denied|blocked|failed|failure|error|lost|timed out)\b/i;
2804
+
2805
+ /** Whatever text is still held is printed: the turn is ending another way
2806
+ * (an error, a second Ctrl-C), so no reply follows it (Codex). */
2807
+ export function flushHeld(seen, open) {
2808
+ if (!seen) return;
2809
+ const held = heldText(seen);
2810
+ for (const [, h] of held) console.log(eventLine(h, h.__agent ?? "", open ?? new Map()));
2811
+ held.clear();
2812
+ }
2813
+
2814
+ /** printNew's held text, per step, kept beside `seen` across polls and reconnects. */
2815
+ const HELD = new WeakMap();
2816
+ /** @param {Map<number, number>} seen */
2817
+ function heldText(seen) {
2818
+ let m = HELD.get(seen);
2819
+ if (!m) HELD.set(seen, (m = new Map()));
2820
+ return m;
2821
+ }
2822
+
2823
+ /** The run is over: a held text that is not the reply printed after it is
2824
+ * printed now (the reply itself is not printed twice). */
2825
+ export function dropHeldReply(run, seen, open) {
2826
+ const held = heldText(seen);
2827
+ const own = (run.steps ?? []).filter((x) => !x.subagentOf);
2828
+ const reply = String(own.at(-1)?.result ?? "").trim();
2829
+ for (const [i, e] of held) {
2830
+ if (String(e.text).trim() !== reply) console.log(eventLine(e, run.steps[i]?.agent, open));
2831
+ }
2832
+ held.clear();
2759
2833
  }
2760
2834
 
2761
2835
  /** The stream is over: print a start line for each call that never completed. */
@@ -2899,10 +2973,10 @@ async function streamOnce(url, flags, ws, runId, seen, open = new Map(), print =
2899
2973
  * from printing twice. It used to block `invoke --watch` and `logs
2900
2974
  * --follow` for as long as a stalled tunnel cared to keep the socket.
2901
2975
  */
2902
- async function followRemote(url, flags, ws, runId, seen = new Map(), open = new Map(), { holdOpen = false, skipResult = false } = {}) {
2976
+ async function followRemote(url, flags, ws, runId, seen = new Map(), open = new Map(), { holdOpen = false, skipResult = false, quiet = false } = {}) {
2903
2977
  for (let attempt = 1; ; attempt++) {
2904
2978
  try {
2905
- const run = await streamOnce(url, flags, ws, runId, seen, open, { skipResult });
2979
+ const run = await streamOnce(url, flags, ws, runId, seen, open, { skipResult, quiet });
2906
2980
  // holdOpen: the caller reads the run once more when the stream ended
2907
2981
  // with it still live, and flushes after — a start flushed here would
2908
2982
  // print a second time when that read brings its completion (Codex).
@@ -2911,7 +2985,7 @@ async function followRemote(url, flags, ws, runId, seen = new Map(), open = new
2911
2985
  } catch (err) {
2912
2986
  if (!(err instanceof StreamIdle)) throw err;
2913
2987
  const run = await remoteCall(url, flags, `/api/workspaces/${ws}/runs/${runId}`);
2914
- printNew(run, seen, open, { skipResult });
2988
+ printNew(run, seen, open, { skipResult, quiet });
2915
2989
  if (!isLive(run)) {
2916
2990
  flushCalls(open);
2917
2991
  return run;
@@ -12855,6 +12929,7 @@ async function codeTurn(s, task) {
12855
12929
  return;
12856
12930
  }
12857
12931
  if (cancel.asked && cancel.stop === "acked") {
12932
+ flushHeld(seen, open);
12858
12933
  console.log(`\n ${c.dim(`left — the platform took the stop for ${cancel.runId}`)}`);
12859
12934
  process.exit(130);
12860
12935
  }
@@ -12873,6 +12948,10 @@ async function codeTurn(s, task) {
12873
12948
  process.on("SIGINT", onInt);
12874
12949
  let run;
12875
12950
  let runId;
12951
+ /** @type {Map<number, number> | null} */
12952
+ let seen = null;
12953
+ /** @type {Map<string, unknown> | null} */
12954
+ let open = null;
12876
12955
  try {
12877
12956
  const { packed, left, unscanned, summary } = await packFolder(dir);
12878
12957
  if (cancel.asked) return "cancelled";
@@ -12902,14 +12981,16 @@ async function codeTurn(s, task) {
12902
12981
  if (cancel.asked) stop(); // pressed while the run was being started
12903
12982
  console.log(` ${c.dim(`run ${plainText(runId)}${started.test ? " (test)" : ""} — Ctrl-C stops it; the dashboard shows it live`)}\n`);
12904
12983
  run = await remoteCall(url, flags, `/api/workspaces/${enc(ws)}/runs/${enc(runId)}`);
12905
- const seen = new Map();
12906
- const open = new Map();
12907
- printNew(run, seen, open, { skipResult: true });
12908
- if (isLive(run)) run = (await followRemote(url, flags, ws, runId, seen, open, { holdOpen: true, skipResult: true })) ?? run;
12984
+ seen = new Map();
12985
+ open = new Map();
12986
+ const view = { skipResult: true, quiet: flags.verbose !== true };
12987
+ printNew(run, seen, open, view);
12988
+ if (isLive(run)) run = (await followRemote(url, flags, ws, runId, seen, open, { holdOpen: true, ...view })) ?? run;
12909
12989
  if (isLive(run)) {
12910
12990
  run = await remoteCall(url, flags, `/api/workspaces/${enc(ws)}/runs/${enc(runId)}`);
12911
- printNew(run, seen, open, { skipResult: true });
12991
+ printNew(run, seen, open, view);
12912
12992
  }
12993
+ dropHeldReply(run, seen, open);
12913
12994
  flushCalls(open);
12914
12995
  cancel.phase = "patch";
12915
12996
 
@@ -12941,6 +13022,9 @@ async function codeTurn(s, task) {
12941
13022
  }
12942
13023
  return run.status;
12943
13024
  } finally {
13025
+ // The success path has printed or dropped any held text already; an
13026
+ // error on the way out has not (Codex).
13027
+ flushHeld(seen, open);
12944
13028
  // A stop still on its way is waited for on every way out — a thrown
12945
13029
  // follower included — so the turn never ends before the platform was
12946
13030
  // told, and says so when it cannot tell (Codex).
@@ -12972,7 +13056,11 @@ async function codeTurn(s, task) {
12972
13056
  */
12973
13057
  async function codeCmd(positional, flags, layout) {
12974
13058
  const dir = path.resolve(positional[0] ?? ".");
12975
- if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) throw new Error(`${dir} is not a folder`);
13059
+ if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) {
13060
+ // `foldrun code to my-project` (19 Nov 2026, a tester): the dashes left off.
13061
+ if (positional[0] === "to" && positional[1]) throw new Error(`${dir} is not a folder — did you mean \`foldrun code --to ${positional[1]}\`?`);
13062
+ throw new Error(`${dir} is not a folder`);
13063
+ }
12976
13064
  if (spawnSync("git", ["-C", dir, "rev-parse", "--show-toplevel"], { encoding: "utf8" }).status !== 0) {
12977
13065
  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`);
12978
13066
  }
@@ -22,6 +22,7 @@
22
22
  // CI job with a key in the environment never reads a file.
23
23
 
24
24
  import fs from "node:fs";
25
+ import crypto from "node:crypto";
25
26
  import os from "node:os";
26
27
  import path from "node:path";
27
28
 
@@ -79,6 +80,151 @@ function nameFor(profiles, account, url) {
79
80
  for (let i = 2; ; i++) if (!profiles[`${withHost}-${i}`]) return `${withHost}-${i}`;
80
81
  }
81
82
 
83
+ /** One process at a time changes the file: each change reads it and writes
84
+ * it whole, so two at once (a renewal beside `workspaces use`, two logins)
85
+ * could each undo the other (Codex review, 19 Nov 2026). The lock is a file
86
+ * linked into place beside it already holding its owner's pid and a token.
87
+ * It is stale only when that process is gone (an empty one, left by an
88
+ * older CLI, after LOCK_EMPTY_STALE_MS); see takeOver for how a
89
+ * stale one changes hands. Released only by the owner whose token it holds. Synchronous, like the
90
+ * rest of this module. */
91
+ const LOCK_EMPTY_STALE_MS = 30_000;
92
+ const LOCK_WAIT_MS = 10_000;
93
+ const pause = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
94
+ const readLock = (p) => {
95
+ try {
96
+ return fs.readFileSync(p, "utf8");
97
+ } catch {
98
+ return null;
99
+ }
100
+ };
101
+ function ownerGone(content, lockPath) {
102
+ const pid = Number(/^(\d+):/.exec(content ?? "")?.[1]);
103
+ if (!pid) {
104
+ try {
105
+ return Date.now() - fs.statSync(lockPath).mtimeMs > LOCK_EMPTY_STALE_MS;
106
+ } catch {
107
+ return false;
108
+ }
109
+ }
110
+ if (pid === process.pid) return false;
111
+ try {
112
+ process.kill(pid, 0);
113
+ return false;
114
+ } catch (err) {
115
+ return err?.code === "ESRCH";
116
+ }
117
+ }
118
+ function locked(fn) {
119
+ fs.mkdirSync(credentialsDir(), { recursive: true, mode: 0o700 });
120
+ const lock = `${file()}.lock`;
121
+ const token = `${process.pid}:${crypto.randomBytes(8).toString("hex")}`;
122
+ const until = Date.now() + LOCK_WAIT_MS;
123
+ sweepClaims(lock);
124
+ // The lock is written whole first, then hard-linked into place (atomic,
125
+ // EEXIST when held): never an empty lock to be taken for a crashed one
126
+ // while its maker is merely slow (Codex review).
127
+ const mine = `${lock}.${token.replace(":", "-")}.own`;
128
+ fs.writeFileSync(mine, token, { mode: 0o600 });
129
+ try {
130
+ for (;;) {
131
+ try {
132
+ fs.linkSync(mine, lock);
133
+ break;
134
+ } catch (err) {
135
+ if (err?.code !== "EEXIST") throw err;
136
+ }
137
+ if (takeOver(lock, token)) break;
138
+ if (Date.now() > until) throw new Error(`${lock} is held by another foldrun command — try again, or remove it if no foldrun is running`);
139
+ pause(25);
140
+ }
141
+ } finally {
142
+ fs.rmSync(mine, { force: true });
143
+ }
144
+ try {
145
+ return fn();
146
+ } finally {
147
+ if (readLock(lock) === token) fs.rmSync(lock, { force: true });
148
+ }
149
+ }
150
+
151
+ /** Take over a lock whose owner is gone, without the path ever standing
152
+ * empty (Codex review): one claim file per dead lock (keyed by its content,
153
+ * inode and time), made with O_EXCL and holding the claimant's pid, so
154
+ * exactly one contender wins it; the winner checks the lock is still that
155
+ * dead one and renames its own lock file over it. The claim stays while its
156
+ * claimant lives, so a late contender that saw the same dead lock cannot win
157
+ * it again; a claim whose claimant is gone (crashed mid-takeover) is cleared.
158
+ * Limit, accepted: without kernel file locks (Node has none) a claimant
159
+ * paused between its check and its rename while its claim is cleared as dead
160
+ * could still overlap — it needs a crash during another crash's recovery. */
161
+ function takeOver(lock, token) {
162
+ let st;
163
+ const seen = readLock(lock);
164
+ try {
165
+ st = fs.statSync(lock);
166
+ } catch {
167
+ return false;
168
+ }
169
+ if (seen === null || !ownerGone(seen, lock)) return false;
170
+ const key = crypto.createHash("sha256").update(`${seen}\0${st.ino}\0${st.mtimeMs}`).digest("hex").slice(0, 16);
171
+ const claim = `${lock}.claim-${key}`;
172
+ let fd;
173
+ try {
174
+ fd = fs.openSync(claim, "wx", 0o600);
175
+ } catch {
176
+ // Another contender has this dead lock — unless it died too.
177
+ const held = readLock(claim);
178
+ if (held !== null && ownerGone(held, claim)) fs.rmSync(claim, { force: true });
179
+ return false;
180
+ }
181
+ try {
182
+ fs.writeSync(fd, `${process.pid}:claim`);
183
+ } finally {
184
+ fs.closeSync(fd);
185
+ }
186
+ let stillDead = false;
187
+ try {
188
+ stillDead = readLock(lock) === seen && fs.statSync(lock).ino === st.ino;
189
+ } catch {
190
+ /* gone: someone released it */
191
+ }
192
+ if (!stillDead) {
193
+ fs.rmSync(claim, { force: true });
194
+ return false;
195
+ }
196
+ const tmp = `${lock}.${token.replace(":", "-")}.tmp`;
197
+ try {
198
+ fs.writeFileSync(tmp, token, { mode: 0o600 });
199
+ fs.renameSync(tmp, lock);
200
+ return true;
201
+ } catch {
202
+ fs.rmSync(tmp, { force: true });
203
+ fs.rmSync(claim, { force: true });
204
+ return false;
205
+ }
206
+ }
207
+
208
+ /** Claims whose claimant is gone go: nobody is taking that lock over. */
209
+ function sweepClaims(lock) {
210
+ const dir = path.dirname(lock);
211
+ const base = `${path.basename(lock)}.claim-`;
212
+ try {
213
+ for (const n of fs.readdirSync(dir)) {
214
+ if (!n.startsWith(base)) continue;
215
+ const p = path.join(dir, n);
216
+ try {
217
+ const held = readLock(p);
218
+ if (held !== null && ownerGone(held, p)) fs.rmSync(p, { force: true });
219
+ } catch {
220
+ /* gone meanwhile */
221
+ }
222
+ }
223
+ } catch {
224
+ /* an unreadable folder: the open below says so */
225
+ }
226
+ }
227
+
82
228
  function write(current, profiles) {
83
229
  // The old shape goes on being written for the newest profile on each URL,
84
230
  // so a machine that moves between CLI versions is not signed out by the
@@ -120,42 +266,46 @@ function write(current, profiles) {
120
266
  * @param {{ makeDefault?: boolean, name?: string }} [opts]
121
267
  */
122
268
  export function saveCredential(url, entry, { makeDefault = true, name } = {}) {
123
- const key = normaliseUrl(url);
124
- const { current, profiles } = readCredentials();
125
- const existing = name ?? Object.keys(profiles).find((n) => normaliseUrl(profiles[n].url) === key && profiles[n].account === entry.account);
126
- const profileName = existing ?? nameFor(profiles, entry.account, key);
127
- // The default project (`foldrun workspaces use`) is what is stored NOW for
128
- // this account on this platform, never what the entry carries: a renewal
129
- // writes back a profile read before a `use` or `--clear` changed it, and a
130
- // re-login to the same account keeps it (Codex review, 19 Nov 2026).
131
- const prev = profiles[profileName];
132
- const kept = prev && normaliseUrl(prev.url) === key && prev.account === entry.account && typeof prev.workspace === "string" ? { workspace: prev.workspace } : {};
133
- const { workspace: _carried, ...fields } = entry;
134
- profiles[profileName] = { ...fields, ...kept, url: key, loggedInAt: new Date().toISOString() };
135
- write(makeDefault || !current ? profileName : current, profiles);
136
- return profileName;
269
+ return locked(() => {
270
+ const key = normaliseUrl(url);
271
+ const { current, profiles } = readCredentials();
272
+ const existing = name ?? Object.keys(profiles).find((n) => normaliseUrl(profiles[n].url) === key && profiles[n].account === entry.account);
273
+ const profileName = existing ?? nameFor(profiles, entry.account, key);
274
+ // The default project (`foldrun workspaces use`) is what is stored NOW for
275
+ // this account on this platform, never what the entry carries: a renewal
276
+ // writes back a profile read before a `use` or `--clear` changed it, and a
277
+ // re-login to the same account keeps it (Codex review, 19 Nov 2026).
278
+ const prev = profiles[profileName];
279
+ const kept = prev && normaliseUrl(prev.url) === key && prev.account === entry.account && typeof prev.workspace === "string" ? { workspace: prev.workspace } : {};
280
+ const { workspace: _carried, ...fields } = entry;
281
+ profiles[profileName] = { ...fields, ...kept, url: key, loggedInAt: new Date().toISOString() };
282
+ write(makeDefault || !current ? profileName : current, profiles);
283
+ return profileName;
284
+ });
137
285
  }
138
286
 
139
287
  /** Forget one. By name, else by URL (the newest there). Returns what was
140
288
  * stored, for a best-effort revoke. */
141
289
  export function removeCredential(urlOrName) {
142
- const { current, profiles } = readCredentials();
143
- const key = (() => {
144
- if (profiles[urlOrName]) return urlOrName;
145
- try {
146
- const u = normaliseUrl(urlOrName);
147
- const here = Object.keys(profiles).filter((n) => normaliseUrl(profiles[n].url) === u);
148
- return here.sort((a, b) => String(profiles[a].loggedInAt ?? "").localeCompare(String(profiles[b].loggedInAt ?? ""))).at(-1) ?? null;
149
- } catch {
150
- return null;
151
- }
152
- })();
153
- if (!key) return null;
154
- const gone = profiles[key];
155
- delete profiles[key];
156
- const names = Object.keys(profiles);
157
- write(current === key ? names[0] ?? null : current, profiles);
158
- return gone;
290
+ return locked(() => {
291
+ const { current, profiles } = readCredentials();
292
+ const key = (() => {
293
+ if (profiles[urlOrName]) return urlOrName;
294
+ try {
295
+ const u = normaliseUrl(urlOrName);
296
+ const here = Object.keys(profiles).filter((n) => normaliseUrl(profiles[n].url) === u);
297
+ return here.sort((a, b) => String(profiles[a].loggedInAt ?? "").localeCompare(String(profiles[b].loggedInAt ?? ""))).at(-1) ?? null;
298
+ } catch {
299
+ return null;
300
+ }
301
+ })();
302
+ if (!key) return null;
303
+ const gone = profiles[key];
304
+ delete profiles[key];
305
+ const names = Object.keys(profiles);
306
+ write(current === key ? names[0] ?? null : current, profiles);
307
+ return gone;
308
+ });
159
309
  }
160
310
 
161
311
  /** The stored entry for a URL — the newest account signed in there. */
@@ -186,28 +336,32 @@ export function currentProfile() {
186
336
 
187
337
  /** Make one the profile a bare command talks as. */
188
338
  export function useProfile(name) {
189
- const { profiles } = readCredentials();
190
- if (!profiles[name]) return null;
191
- write(name, profiles);
192
- return { ...profiles[name], name };
339
+ return locked(() => {
340
+ const { profiles } = readCredentials();
341
+ if (!profiles[name]) return null;
342
+ write(name, profiles);
343
+ return { ...profiles[name], name };
344
+ });
193
345
  }
194
346
 
195
347
  /** Save (or, with null, forget) the project a profile's commands use when
196
348
  * they name none — `foldrun workspaces use`. Kept on the profile, so it is
197
349
  * one account on one platform's, and never follows a --token. */
198
350
  export function setProfileWorkspace(name, workspace, expect = {}) {
199
- const { current, profiles } = readCredentials();
200
- if (!profiles[name]) return null;
201
- // Still the account and platform it was checked against: a sign-out or a
202
- // new sign-in under the same name meanwhile saves nothing.
203
- if (expect.url && normaliseUrl(profiles[name].url) !== normaliseUrl(expect.url)) return null;
204
- if (expect.account && profiles[name].account !== expect.account) return null;
205
- const next = { ...profiles[name] };
206
- if (workspace) next.workspace = workspace;
207
- else delete next.workspace;
208
- profiles[name] = next;
209
- write(current, profiles);
210
- return { ...next, name };
351
+ return locked(() => {
352
+ const { current, profiles } = readCredentials();
353
+ if (!profiles[name]) return null;
354
+ // Still the account and platform it was checked against: a sign-out or a
355
+ // new sign-in under the same name meanwhile saves nothing.
356
+ if (expect.url && normaliseUrl(profiles[name].url) !== normaliseUrl(expect.url)) return null;
357
+ if (expect.account && profiles[name].account !== expect.account) return null;
358
+ const next = { ...profiles[name] };
359
+ if (workspace) next.workspace = workspace;
360
+ else delete next.workspace;
361
+ profiles[name] = next;
362
+ write(current, profiles);
363
+ return { ...next, name };
364
+ });
211
365
  }
212
366
 
213
367
  /** All of them, newest sign-in last. */