foldrun 8.0.0 → 8.1.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/docs/api.md CHANGED
@@ -203,7 +203,7 @@ paying for the steps around it.
203
203
  | `/api/workspaces/<ws>/runs/<id>/calls/<call>` | GET | one tool call's recorded content (see [Runs](runs#what-a-run-records)): `{ call: { id, tool, input, output, inputChars, outputChars, truncated, inputCut, outputCut } }` — what it was given and what it gave back, secrets masked, each at most 65,536 characters; `inputChars`/`outputChars` are the whole length, `inputCut`/`outputCut` say which part was cut (`truncated`: either). `<call>` is the tool event's `call`; an event with `captured: true` has content here. 404 when nothing was recorded: the workspace says `capture: metadata`, or the run is from before 19 Oct 2026. A run's steps also carry `calls`, each model call (`n`, `at`, `ms`, `model`, `stop`, `tokens`, `tools`, and `subagent` / `attempt` when a sub-agent or a later attempt made it); a step that handed jobs to `sandbox: own` sub-agents carries `delegations` (`id`, `agent`, `status`, `costUsd`, `ms`), and each job is a step of its own with `subagentOf` (the delegating agent), `delegation` (that `id`) and `wrote` (the workspace paths it changed — copied into the delegating step's sandbox too, up to 4 MiB a job); and the run its `revision` (the workspace's latest revision when a worker picked it up — a deploy's commit, or the id an edit through `/source` was saved as) and `drivenAt` (when that was) |
204
204
  | `/api/workspaces/<ws>/runs/<id>/trace` | GET | the run as one tree (see [Runs](runs#the-trace-tree)): `{ tree, failure }`. Each span is `{ id, kind, label, start, end, status, children, … }`, where `kind` is `run`, `step`, `model` (one model call: `model`, `stop`, `tokens`), `tool` (`call`, `captured` when its input and output were recorded) or `error` (`text`); `start`/`end` are epoch milliseconds and `status` is `ok`, `error`, `running`, `waiting`, `skipped` or `pending`. A tool call sits under the model call that asked for it. `failure` is the ids from the root to the first thing that went wrong, which the run page opens on; `[]` when nothing did |
205
205
  | `/api/workspaces/<ws>/runs/<id>/compare?with=` | GET | this run beside another of the same flow (see [Runs](runs#compare-with-the-last-good-run)): `{ comparison: { base, run, revisionChanged, changedFiles, steps }, chosen }`. Each step is `{ step, agent, base, run, changes }`: both sides' status, instruction, model, seconds, tokens, model calls, tool counts, tool errors, first errors and first line said, and `changes` in words (`status: completed → failed`, `new error: …`, `instruction changed`, `tools: +web ×3`, `took 12s → 48s`, …). `changedFiles` lists the files changed between the revisions the two ran (null when one is unknown). `with` names the other run; unasked it is the newest earlier run of the flow that finished well, else the run this one re-ran (`chosen` says which) |
206
- | `/api/workspaces/<ws>/runs/<id>` | GET, DELETE | the whole run: every step, its output, cost, timing, the runner `image` it ran on and — for a step that browsed through the account's pod from slim — its `browserPod` reconnects and fallback ([runs](runs#the-record)). `?wait=true&timeout=<s>` instead blocks until the run stops (or `timeout`, default 300, max 900) and answers the verdict the run routes give — `200` completed, `500` failed with the record, `202` still going (`timedOut`) or parked on a person (`awaitingApproval`). Ask in short pieces: whatever sits in front of the platform cuts a request that stays silent too long (Cloudflare at 100 s, an AWS ALB at 60 s), and a flow can run for many minutes — the CLI's `--wait` asks 25 s at a time and comes back here on every `202` |
206
+ | `/api/workspaces/<ws>/runs/<id>` | GET, DELETE | the whole run: every step, its output, cost, timing, the runner `image` it ran on and — for a step that browsed through the account's pod from slim — its `browserPod` reconnects and fallback ([runs](runs#the-record)). `?wait=true&timeout=<s>` instead blocks until the run stops (or `timeout`, default 300, max 900) and answers the verdict the run routes give — `200` once the run has ended, however it ended: `ok: true` when it completed, `ok: false` with its `status` and `failure: { agent, reason }` when it failed or was stopped (a run that fails is the answer, not a fault in the call — it was a `500` before 29 Oct 2026); `202` still going (`timedOut`) or parked on a person (`awaitingApproval`). A start refused before any run exists — a paused account or workspace (`423`), an agent or flow that is not there (`404`), `overlap: skip` (`409`) — is answered as such and waits for nothing. Ask in short pieces: whatever sits in front of the platform cuts a request that stays silent too long (Cloudflare at 100 s, an AWS ALB at 60 s), and a flow can run for many minutes — the CLI's `--wait` asks 25 s at a time and comes back here on every `202` |
207
207
  | `/api/workspaces/<ws>/runs/<id>/stream` | GET | server-sent events, live |
208
208
  | `/api/workspaces/<ws>/runs/<id>/stop` | POST | destroys the sandbox, not just the record |
209
209
  | `/api/workspaces/<ws>/runs/<id>/rerun` | POST | again — `step` to start partway, or `agent` to start at the first step that agent runs (one of the two is required). `instruction` tells that step something else this once, in place of the flow's (the flow file is not changed); the new run's `rerunOf` says `{ run, step, instruction }`. Takes `?wait=true&timeout=` like a flow start |
@@ -337,7 +337,7 @@ Reads return which secrets exist, never their values.
337
337
  | Route | Methods | |
338
338
  |---|---|---|
339
339
  | `/api/keys` | GET, POST, DELETE | API keys — an admin's (`keys:manage`) to list, mint and revoke; any key may revoke itself (DELETE with its own `id`, audited as self — what `foldrun logout` does). POST `label`, `role` (viewer \| editor \| admin, never above your own, default editor), `workspaces` (names, or `null` for all — never wider than your own scope); `expires` (`30d`, `90d`, `365d`, any number of days up to 3650, or `never` — the default; anything else is a 400, never a key that lives forever); returns `{ ok, key, id, prefix, role, workspaces, expiresAt }`, and the key is shown once. GET lists each key with `createdAt`, `createdBy`, `expiresAt`, `lastUsedAt`, `lastIp` and `replacedBy` (the id of the key a rotation replaced it with; `null` until then) — the last-use pair written at most once a minute per key, the address cut to its /24 (IPv4) or /48 (IPv6). A key past its `expiresAt` is refused with 401 `API key expired on <date>`; the owner is emailed seven days before. Mint, revoke and rotate are written to the audit log. POST with `workspace` or `access` is refused (400): those minted deploy keys for the platform's own git, which went on 17 Oct 2026 — a deploy key minted before is refused everywhere (403). A key for one workspace is `workspaces: ["<ws>"]`. DELETE `id`. `?tenant=` / body `tenant` is read only on an install with no users yet (first-run bootstrap), and there, when the install has a setup token (`FOLDRUN_SETUP_TOKEN`, written by the self-hosting installer), only with that token in `X-Foldrun-Setup-Token` |
340
- | `/api/keys/<id>/rotate` | POST | a new key with the old one's label, role, workspaces and deploy scope — and, when it had an end, the same lifetime from today — returned once like a mint (`{ ok, key, id, prefix, role, workspaces, expiresAt, replaced: { id, endsAt } }`). `grace`: `0` (default — the old key is revoked at once), or a duration up to `7d` such as `1h` or `24h`, during which the old key still works and after which it is refused as expired. A key is rotated once: rotating a key already replaced is 409 `this key was already rotated to <prefix>…; rotate that one` — and someone who lost the new key's secret rotates the NEW key, which mints another and ends the lost one (rotating the old one again would leave the lost key working). Two rotations of one key at once mint one key. `keys:manage`; a key outside the caller's scope is 404. Audited as `apikey.rotated` |
340
+ | `/api/keys/<id>/rotate` | POST | a new key with the old one's label, role, workspaces and deploy scope — and, when it had an end, the same lifetime from today — returned once like a mint (`{ ok, key, id, prefix, role, workspaces, expiresAt, replaced: { id, endsAt } }`). `grace`: `0` (default — the old key is revoked at once), or a duration up to `7d` such as `1h` or `24h`, during which the old key still works and after which it is refused as expired. A key is rotated once: rotating a key already replaced is 409 `this key was already rotated to <prefix>…; rotate that one` — and someone who lost the new key's secret rotates the NEW key, which mints another and ends the lost one (rotating the old one again would leave the lost key working). Two rotations of one key at once mint one key. `keys:manage`; a key outside the caller's scope is 404 — except that a key `foldrun login` minted may rotate **itself**, whatever its role: same label, role, workspaces and 90-day lifetime from today, the old key ending 10 minutes later (`grace` is not read). That is how the CLI renews its sign-in; any other key rotating itself still needs `keys:manage`. Audited as `apikey.rotated` (`self: true` for a self-rotation) |
341
341
  | `/api/team` | GET, POST | members with their roles and workspace scope; mint an invite — `role` (viewer \| editor \| admin, default editor), `workspaces` (names, or omit for all), `email` (only that address can accept it; sent through the account's `RESEND_API_KEY` unless `send: false`). An invite works **once**, for seven days, and a newer invite to the same address revokes the older ones still pending. Returns `id`, `path` (the invite's relative URL, shown only here), `expires`, `sent` and any `sendError` either way; the full link is in the mail. Links made before 29 Oct 2026 (`inv1`–`inv3`) are refused |
342
342
  | `/api/team/invites?all=1` | GET | the account's invites, newest first — pending ones unless `all=1` (then accepted, revoked and expired too): `{ invites: [{ id, email, role, workspaces, invitedBy, createdAt, expiresAt, status }] }`, `email` `null` for a link anyone may use, `workspaces` `null` for all, `status` `pending` \| `accepted` \| `revoked` \| `expired`. Never the link. `team:manage` — an admin key included; a caller scoped to some workspaces sees only the invites inside its scope |
343
343
  | `/api/team/invites/<id>` | DELETE | revoke an invite: its link stops working at once. `{ ok, revoked, invite }` — `revoked: false` when it was already revoked or expired; `404` for an id that is not this account's; `409` for one already accepted (remove the member instead). `team:manage`, a key included; a scoped caller only inside its scope, and an admin invite only by the owner. Audited as `member.invite_revoked` |
@@ -463,8 +463,8 @@ signed-in person, never by a key — mints an ordinary API key at their role.
463
463
  |---|---|---|
464
464
  | `/api/cli/login` | POST | `hostname` → `{ id, code, verifyUrl, expiresAt, interval }`. Open: there is no credential yet. Ten-minute lifetime |
465
465
  | `/api/cli/login/<id>` | GET | `{ status }` — `pending`, `denied`, `expired`, or `approved` with `token`, `account`, `email`, `role`. The key is returned once; the request is gone after |
466
- | `/api/cli/authorize` | GET, POST | `?code=` describes the request (machine, expiry). POST `{ code, decision }` from a session approves (mints the key, labelled `cli · <hostname>`) or denies — `decision` is `approve` or `deny`, and absent approves; any other word is a `400`. Every role may sign its own CLI in; an owner's key is an admin's |
467
- | `/api/me` | GET | who is calling: `account`, `owner`, `role`, `workspaces` (null: all), and the `actor` — a person's email, or a key's id, label, prefix and who minted it |
466
+ | `/api/cli/authorize` | GET, POST | `?code=` describes the request (machine, expiry). POST `{ code, decision }` from a session approves (mints the key, labelled `cli · <hostname>`, ending in 90 days — the CLI renews it itself before then, see `/api/keys/<id>/rotate`) or denies — `decision` is `approve` or `deny`, and absent approves; any other word is a `400`. Every role may sign its own CLI in; an owner's key is an admin's |
467
+ | `/api/me` | GET | who is calling: `account`, `owner`, `role`, `workspaces` (null: all), and the `actor` — a person's email, or a key's id, label, prefix, who minted it, `expiresAt` (null: never) and `origin` (`cli-login` for a key `foldrun login` minted, else null) |
468
468
  | `/api/me/onboarding` | GET, PATCH | the account's getting-started steps, each derived from what is really there — `{ steps: [{ id, title, why, href, cli?, done }], done, total, complete, next, dismissed, dismissedAt }`. Steps: `model` (first; only for an account that must bring its own key — done once it has one, or a `provider:` block in the account's AGENTS.md), `workspace`, `agent` (an agent written or deployed after the workspace was made), `run`, `success` (a completed run), `secret`, `trigger` (a schedule or webhook), `teammate` (a second member), `billing` (hosted, not fully waived: a saved card or a plan), `cli` (any API key or CLI login). PATCH `{ dismissed: true or false }` hides or brings back the dashboard card for the signed-in person (kept in their prefs); a key reads `dismissed: false` and cannot PATCH |
469
469
  | `/api/me/inbox` | GET, POST | your inbox — what waits on you across the workspaces you may see. GET `{ person, items: [{ id, kind (approval, question, issue, proposal, run), bucket (mine, started, team), why, workspace, title, detail, at, href, read, dismissed }], counts: { mine, started, team, unread } }`, newest first. `mine` is assigned to you (named in `approvers:`, owner of the flow or agent, or you asked for the proposal); `started` is runs you started — failed or BLOCKED/BAD this week, a gate on one (someone else decides it), a question it asked; `team` is the rest that waits in your workspaces. By default `mine` and `started`; `?bucket=mine\|started\|team\|all`, `?kind=`, `?workspace=`, `?dismissed=1` for what you set aside. `counts.unread` is unread `mine` + `started`. POST `{ ids \| id, action: read\|unread\|dismiss\|restore }` changes your view only — dismissing never decides a gate or resolves an issue; ids name an occurrence, so a thing that happens again is new. A key acts for the person who minted it, inside the key's own scope; one no person minted is a `400` |
470
470
  | `/api/me/notifications` | GET, PATCH | what mail you get. GET `{ email, categories: [{ category, label, description, required, why?, perWorkspace, enabled, workspaces: { <ws>: bool } }] }` for `security`, `invites`, `billing`, `account` (required — always sent) and `run-alerts`, `approvals` (per workspace), `low-balance`, `product-updates`. PATCH `{ category, enabled, workspace? }` or `{ preferences: [ … ] }`; answers the same as GET. Turning a required category off is a `409` with the reason; `workspace` on an account-wide category is a `400`; `enabled: true` account-wide clears that category's per-workspace offs. A key acts for the person who minted it |
package/docs/cli.md CHANGED
@@ -314,6 +314,13 @@ revoked like any other — and the CLI stored it in `~/.foldrun/credentials.json
314
314
  (mode 0600; `FOLDRUN_HOME` moves the directory). An owner's terminal is an
315
315
  admin's: a key is never an owner.
316
316
 
317
+ That key lasts 90 days, and renews itself: when a command finds fewer than
318
+ 14 days left, the CLI rotates the key from itself (same label, role and
319
+ workspaces) and stores the new one, saying so on one dim line. A machine in
320
+ use never sees its sign-in end; one left unused for 90 days is signed out,
321
+ and the next command says to run `foldrun login` again. A key handed in with
322
+ `--token` or `FOLDRUN_TOKEN` is never renewed — its end is its owner's.
323
+
317
324
  `foldrun login --url https://foldrun.example.com` signs in to your own
318
325
  installation; the last one signed in to is the default afterwards, and
319
326
  `--url` on any command picks another. `foldrun login --token <key>` stores a
package/docs/security.md CHANGED
@@ -92,6 +92,16 @@ At rest, each account has its own encryption key; the account keys are
92
92
  wrapped by one root key the platform holds. A stolen copy of an account's
93
93
  secrets opens nothing without it.
94
94
 
95
+ The egress proxy can run without that root key
96
+ ([`FOLDRUN_EGRESS_MINIMAL_BOOT`](environment)). It is then given only what it
97
+ uses, each derived from the root key for that one purpose: the public half
98
+ of the key the worker signs every step's lease with, the key of the
99
+ certificate authority it signs bound sites with, and the key that seals the
100
+ identity signing keys. A lease is sealed under the step's own token, which
101
+ the lease store never holds, so the proxy opens a step's credentials only
102
+ when that step presents its token — and a lease nobody but the worker could
103
+ have signed is refused.
104
+
95
105
  Backups are encrypted before they leave the server. The nightly archive —
96
106
  every workspace, run record and the database — and the server's key file
97
107
  are encrypted with age to a public key whose private half is not on the
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "foldrun",
3
- "version": "8.0.0",
3
+ "version": "8.1.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-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",
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-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-fol105.test.ts tests/cli-key-renew.test.ts tests/cli-wait-failed.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
@@ -2511,6 +2511,48 @@ async function versionCmd(flags) {
2511
2511
  return 0;
2512
2512
  }
2513
2513
 
2514
+ /**
2515
+ * Renew this machine's `foldrun login` key before it ends (FOL-71). Such a
2516
+ * key lives 90 days; with under RENEW_DAYS left the CLI rotates it itself
2517
+ * (POST /api/keys/<own id>/rotate — a cli-login key may, whatever its role)
2518
+ * and stores the new one, so a machine in use never sees it end. Once per
2519
+ * command, only for a key `login` minted and stored here — never --token or
2520
+ * FOLDRUN_TOKEN, whose holder chose them — and it never fails the command
2521
+ * it rides on: any problem leaves the old key in place to try next time.
2522
+ * Costs a request only when the end is near or not yet known (/api/me, at
2523
+ * most daily for a key that does not renew, e.g. on an older platform).
2524
+ */
2525
+ const RENEW_DAYS = 14;
2526
+ const DAY_MS = 86_400_000;
2527
+ let renewChecked = false;
2528
+ async function renewIfDue(url, flags) {
2529
+ if (renewChecked || flags.token || env("FOLDRUN_TOKEN")) return;
2530
+ renewChecked = true;
2531
+ try {
2532
+ const p = chosenProfile(flags);
2533
+ if (!p?.minted || !p.token) return;
2534
+ const now = Date.now();
2535
+ const ends = p.expiresAt ? Date.parse(p.expiresAt) : NaN;
2536
+ if (p.renews === true && ends - now > RENEW_DAYS * DAY_MS) return;
2537
+ if (p.renews === false && p.checkedAt && now - Date.parse(p.checkedAt) < DAY_MS) return;
2538
+ const { name, current: _c, url: at, loggedInAt: _l, ...entry } = p;
2539
+ const save = (fields) => saveCredential(at, { ...entry, ...fields }, { name, makeDefault: false });
2540
+ const meRes = await remoteFetch(at, "/api/me", {}, { token: p.token });
2541
+ if (!meRes.ok) return;
2542
+ const a = /** @type {any} */ (await meRes.json())?.actor ?? {};
2543
+ if (a.kind !== "key" || a.origin !== "cli-login") return void save({ renews: false, checkedAt: new Date(now).toISOString() });
2544
+ if (!a.expiresAt || Date.parse(a.expiresAt) - now > RENEW_DAYS * DAY_MS) return void save({ renews: true, expiresAt: a.expiresAt ?? null, checkedAt: undefined });
2545
+ const res = await remoteFetch(at, `/api/keys/${enc(a.id)}/rotate`, { method: "POST", headers: { "content-type": "application/json" }, body: "{}" }, { token: p.token });
2546
+ if (!res.ok) return;
2547
+ const r = /** @type {any} */ (await res.json());
2548
+ if (typeof r.key !== "string") return;
2549
+ save({ token: r.key, renews: true, expiresAt: r.expiresAt ?? null, checkedAt: undefined });
2550
+ if (flags.quiet !== true) console.error(` ${c.dim(`renewed this machine's sign-in as "${name}"${r.expiresAt ? ` — it now lasts until ${String(r.expiresAt).slice(0, 10)}` : ""}`)}`);
2551
+ } catch {
2552
+ // Offline, an old platform, a read-only home: the old key still works.
2553
+ }
2554
+ }
2555
+
2514
2556
  /**
2515
2557
  * A call to the platform's API, as JSON. A body that is not JSON is not the
2516
2558
  * platform talking — a Cloudflare challenge, a proxy's error page, a tunnel
@@ -2521,6 +2563,7 @@ async function versionCmd(flags) {
2521
2563
  * @returns {Promise<any>}
2522
2564
  */
2523
2565
  async function remoteCall(url, flags, apiPath, init = {}, { seconds } = {}) {
2566
+ await renewIfDue(url, flags);
2524
2567
  const token = tokenFor(url, flags);
2525
2568
  const res = await remoteFetch(
2526
2569
  url,
@@ -3516,13 +3559,14 @@ async function invoke(target, flags) {
3516
3559
  // used to land here after 100 s while the run carried on was the trigger.
3517
3560
  const WAIT_PIECE_S = 25;
3518
3561
  const wait = flags.wait === true ? `?wait=true&timeout=${WAIT_PIECE_S}` : "";
3519
- // A waited run that FAILS is answered with 500 and a full record (see
3520
- // server/wait.ts). That is not an error in the call, it is the answer to
3521
- // it, so it is reported as a failed run rather than thrown as a transport
3522
- // fault — the difference between "your flow failed" and "the platform is
3523
- // down", which is the first thing anyone reading this needs to know.
3562
+ // A waited run that FAILS is the answer to the call, not an error in it:
3563
+ // reported as a failed run, with why, never thrown as a transport fault —
3564
+ // the difference between "your flow failed" and "the platform is down".
3565
+ // A platform since FOL-106 answers it 200 with `status` and `failure`;
3566
+ // one before answered 500 with the same record, which is still read.
3524
3567
  const reportFailedRun = (body, ws) => {
3525
3568
  if (body?.result) console.log(`\n${body.result}\n`);
3569
+ if (body?.failure?.reason) console.log(` ${c.red("why")} ${c.dim(body.failure.agent ?? "?")} ${firstLine(body.failure.reason, 200)}`);
3526
3570
  for (const st of body?.steps ?? []) {
3527
3571
  const mark = st.status === "completed" ? c.green("✓") : st.status === "skipped" ? c.dim("–") : c.red("✗");
3528
3572
  console.log(` ${mark} ${c.dim(st.agent ?? "?")} ${st.status}${st.skipReason ? c.dim(` (${st.skipReason})`) : ""}`);
@@ -3595,6 +3639,7 @@ async function invoke(target, flags) {
3595
3639
  const run = body.run ?? body;
3596
3640
  const status = run.status ?? body.status ?? "finished";
3597
3641
  const ok = status === "completed";
3642
+ if (!ok && status !== "awaiting-approval" && body.runId && body.status) return reportFailedRun(body, ws);
3598
3643
  if (body.result) console.log(`\n${body.result}\n`);
3599
3644
  const mark = ok ? c.green("✓") : status === "awaiting-approval" ? c.amber("⏸") : c.red("✗");
3600
3645
  console.log(` ${mark} ${status}${body.costUsd != null ? ` · $${Number(body.costUsd).toFixed(4)}` : ""}${status === "awaiting-approval" ? c.dim(` — ${url}/dashboard/${ws}/runs/${body.runId}`) : ""}\n`);
@@ -3919,7 +3964,7 @@ async function login(flags) {
3919
3964
  // elsewhere; logout only forgets it.
3920
3965
  const name = saveCredential(url, { token: poll.token, email: poll.email, account: poll.account, role: poll.role, minted: true }, { name: typeof flags.profile === "string" ? flags.profile : undefined });
3921
3966
  console.log(`\n ${c.green("✓")} signed in to ${c.bold(url)} as ${poll.email} ${c.dim(`(${poll.account}, ${poll.role})`)}\n`);
3922
- console.log(` ${c.dim(`Stored as the account "${name}" in ~/.foldrun/credentials.json. \`foldrun accounts\` lists every account signed in here; \`foldrun use ${name}\` switches.`)}\n`);
3967
+ console.log(` ${c.dim(`Stored as the account "${name}" in ${credentialsShown()}. \`foldrun accounts\` lists every account signed in here; \`foldrun use ${name}\` switches.`)}\n`);
3923
3968
  return 0;
3924
3969
  }
3925
3970
  }
@@ -3975,7 +4020,7 @@ async function whoami(flags) {
3975
4020
  console.log(` role ${me.role}`);
3976
4021
  console.log(` workspaces ${me.workspaces === null ? "all" : me.workspaces.join(", ") || "none"}`);
3977
4022
  const profile = flags.token || env("FOLDRUN_TOKEN") ? null : chosenProfile(flags);
3978
- const source = flags.token ? "--token" : env("FOLDRUN_TOKEN") ? "FOLDRUN_TOKEN" : `~/.foldrun/credentials.json as "${profile?.name ?? "?"}"`;
4023
+ const source = flags.token ? "--token" : env("FOLDRUN_TOKEN") ? "FOLDRUN_TOKEN" : `${credentialsShown()} as "${profile?.name ?? "?"}"`;
3979
4024
  console.log(` ${c.dim(`credential from ${source}`)}`);
3980
4025
  const others = listProfiles().filter((p) => p.name !== profile?.name);
3981
4026
  console.log(others.length ? ` ${c.dim(`also signed in as: ${others.map((p) => p.name).join(", ")} — \`foldrun accounts\``)}\n` : "\n");
@@ -4870,7 +4915,10 @@ async function pullCmd(layout, flags, only) {
4870
4915
  const { isSourcePath, LIBRARY_KINDS } = await core();
4871
4916
  const url = remoteUrl(flags);
4872
4917
  if (!url) throw new Error("pull brings a platform's account down — pass --url, or `foldrun login` first");
4873
- const root = layout.accountRoot;
4918
+ // A bare folder (nothing of foldrun's yet) is the account root itself, as
4919
+ // in guideCmd — core reads it as a flat workspace whose account is the
4920
+ // PARENT, and pull would write workspaces/, AGENTS.md and CLAUDE.md there.
4921
+ const root = layout.kind === "empty" ? (layout.workspaceDir ?? process.cwd()) : layout.accountRoot;
4874
4922
  const wsRoot = layout.workspacesDir ?? path.join(root, "workspaces");
4875
4923
 
4876
4924
  const names = (await remoteWorkspaceNames(url, flags)).filter((n) => (only ? n === only : true));
@@ -4921,6 +4969,7 @@ async function pullCmd(layout, flags, only) {
4921
4969
  `\n ${c.green("✓")} pulled ${names.length} workspace${names.length === 1 ? "" : "s"} from ${url} ` +
4922
4970
  c.dim(`${written} file${written === 1 ? "" : "s"} written, ${incoming.length - written} already current`),
4923
4971
  );
4972
+ console.log(` ${c.dim(`into ${root}`)}`);
4924
4973
  const rules = writeAgentFiles(root);
4925
4974
  for (const [file, what] of [["AGENTS.md", rules.agentsMd], ["CLAUDE.md", rules.claudeMd]]) {
4926
4975
  if (what === "created" || what === "updated") console.log(` ${c.green("✓")} ${file} ${c.dim(`${what} — the coding-agent rules, pointing at \`foldrun docs\``)}`);
@@ -5667,8 +5716,32 @@ function printDefaults(d) {
5667
5716
  /** network_enforce: as a person reads it. Off is never "allowed" outright:
5668
5717
  * the level above (the account, or the install's own switch) may refuse
5669
5718
  * anyway, and this file cannot see either, so off says what it leaves to. */
5670
- function networkEnforceText(on, above) {
5671
- return on ? `refused ${c.dim("— a site off an agent's network: list gets a 403")}` : c.dim(`${above}'s — this file does not ask to refuse`);
5719
+ function networkEnforceText(on, above, aboveOn = false) {
5720
+ if (on) return `refused ${c.dim("— a site off an agent's network: list gets a 403")}`;
5721
+ // Either level's true is enough (core networkEnforceWanted), so the level
5722
+ // below cannot turn it off: say what a run here actually gets.
5723
+ if (aboveOn) return `refused ${c.dim(`— ${above} enforces it; this file does not ask, and cannot turn it off`)}`;
5724
+ return c.dim(`${above}'s — this file does not ask to refuse`);
5725
+ }
5726
+
5727
+ /** Whether the account's own AGENTS.md has network_enforce on — null when
5728
+ * this credential may not read the account (a workspace-scoped key). */
5729
+ async function accountEnforces(url, flags) {
5730
+ try {
5731
+ const { defaults } = await remoteCall(url, flags, "/api/account");
5732
+ return defaults?.networkEnforce === true;
5733
+ } catch (err) {
5734
+ if (err instanceof HttpError && (err.status === 403 || err.status === 404)) return null;
5735
+ throw err;
5736
+ }
5737
+ }
5738
+
5739
+ /** Where this machine keeps its keys, written the way a person would type it.
5740
+ * FOLDRUN_HOME moves the folder, so the path is read, never assumed. */
5741
+ function credentialsShown() {
5742
+ const file = path.join(credentialsDir(), "credentials.json");
5743
+ const home = os.homedir();
5744
+ return file.startsWith(home + path.sep) ? `~${file.slice(home.length)}` : file;
5672
5745
  }
5673
5746
 
5674
5747
  /** `on`/`off` (or true/false, yes/no) for network_enforce, or an error. */
@@ -6926,7 +6999,15 @@ export function podTries(step) {
6926
6999
  }
6927
7000
 
6928
7001
  /** Whichever error this step recorded — on the step, or on its last try. */
6929
- const stepError = (step) => step.error ?? [...(step.tries ?? [])].reverse().find((t) => t.error)?.error ?? null;
7002
+ // A step refused before its agent started (no model key, a login token)
7003
+ // records only an error event — no `error`, no tries — so a failed step
7004
+ // falls back to its last error event: the reason was in the record all
7005
+ // along, and `report` and `agent run --wait` printed nothing about it (FOL-106).
7006
+ const stepError = (step) =>
7007
+ step.error ??
7008
+ [...(step.tries ?? [])].reverse().find((t) => t.error)?.error ??
7009
+ (step.status === "failed" ? [...(step.events ?? [])].reverse().find((e) => e.type === "error")?.text : null) ??
7010
+ null;
6930
7011
 
6931
7012
  /**
6932
7013
  * `foldrun report <run-id>` — one run, whole, readable without a browser.
@@ -7165,6 +7246,7 @@ async function reportCmd(runId, flags, layout) {
7165
7246
  if (err) {
7166
7247
  console.log(` ${c.red(firstLine(err, 96))}`);
7167
7248
  for (const e of (step.events ?? []).slice(-4)) {
7249
+ if (e.text === err) continue; // already the red line above
7168
7250
  console.log(` ${EVENT_MARK(e)} ${c.dim(firstLine(e.text, 92))}`);
7169
7251
  }
7170
7252
  }
@@ -7320,9 +7402,10 @@ async function agentRunCmd(positional, flags, layout) {
7320
7402
  const wait = flags.wait === true ? `?wait=true&timeout=${WAIT_PIECE_S}` : "";
7321
7403
  const base = `/api/workspaces/${encodeURIComponent(ws)}/agents/${encodeURIComponent(name)}`;
7322
7404
 
7323
- // A waited run that FAILS is answered with 500 and a full record — the
7324
- // answer to the question, not a fault in the call. So the run id is taken
7325
- // off it and the report is printed like any other.
7405
+ // A waited run that FAILS is the answer to the question, not a fault in
7406
+ // the call: 200 with its status since FOL-106, 500 with the same record
7407
+ // from a platform before. Either way the run id is taken off it and the
7408
+ // report is printed like any other.
7326
7409
  const waited = async (fn) => {
7327
7410
  try {
7328
7411
  return await fn();
@@ -9914,11 +9997,14 @@ async function workspaceCmd(positional, flags, layout) {
9914
9997
  console.log(` notify ${notify}`);
9915
9998
  console.log(` budget ${budget}`);
9916
9999
  console.log(` compute ${computeText(d.compute, c.dim("no cap of its own — the account's"))}`);
9917
- if (d.networkEnforce !== undefined) console.log(` network ${networkEnforceText(d.networkEnforce, "the account")}`);
10000
+ if (d.networkEnforce !== undefined) console.log(` network ${networkEnforceText(d.networkEnforce, "the account", aboveOn === true)}`);
9918
10001
  };
10002
+ /** @type {boolean | null} */
10003
+ let aboveOn = null;
9919
10004
 
9920
10005
  if (!verb) {
9921
10006
  const d = await workspaceDefaults(url, flags, ws);
10007
+ aboveOn = await accountEnforces(url, flags);
9922
10008
  show({ description: typeof d.description === "string" ? d.description : "", timezone: d.timezone ?? null, budget: d.budget ?? null, notify: d.notify ?? null, networkEnforce: d.network_enforce === true, compute: computeOfFile(d.compute) }, ws);
9923
10009
  const halt = await pauseState(remoteCall(url, flags, `/api/workspaces/${enc(ws)}/pause`));
9924
10010
  if (halt) console.log(` paused ${halt.paused ? c.red(`${halt.paused.scope === "account" ? "by the account: " : ""}${pauseLine(halt.paused)}`) : c.dim("no")}`);
@@ -9968,8 +10054,13 @@ async function workspaceCmd(positional, flags, layout) {
9968
10054
  }
9969
10055
  }
9970
10056
  const r = await remoteCall(url, flags, `/api/workspaces/${enc(ws)}`, { method: "PATCH", body: JSON.stringify(patch) });
10057
+ const turnedOff = key === "network_enforce" && patch.network_enforce !== true;
10058
+ if (turnedOff) aboveOn = await accountEnforces(url, flags);
9971
10059
  if (r.defaults) show(r.defaults, r.name ?? ws);
9972
10060
  console.log(`\n ${c.green("✓")} ${r.renamed ? `renamed to ${r.name}` : verb === "clear" ? `${key} cleared` : `${key} set`} ${c.dim(`on ${r.name ?? ws}`)}`);
10061
+ // FOL-105: "off" here only drops this file's own true — the account's on
10062
+ // still refuses, and a ✓ alone read as if runs here were now allowed.
10063
+ if (turnedOff && aboveOn) console.log(` ${c.amber("!")} still refused here: the account enforces network_enforce — \`foldrun account set network_enforce off\` turns it off for every workspace`);
9973
10064
  if (r.brokeWebhooks?.length) console.log(` ${c.amber("!")} webhook URLs changed for ${r.brokeWebhooks.join(", ")} — copy the new ones from each flow`);
9974
10065
  console.log();
9975
10066
  return 0;