foldrun 26.6.2 → 26.7.1

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
@@ -52,7 +52,7 @@
52
52
  // foldrun deploy [dir] push this account — or one workspace — into an installation
53
53
  // foldrun pull bring the platform's account down into this folder
54
54
  // foldrun status what differs here from what is deployed — --platform [--history]: is the platform up
55
- // foldrun workspaces what exists here, and there — show <name>, new <name> --platform
55
+ // foldrun workspaces what exists here, and there — show <name>, new <name> --platform, use <name>
56
56
  // foldrun invoke <flow> start a flow on a running platform
57
57
  // foldrun source <verb> ls / cat / put / new / mv / rm one workspace file on a platform
58
58
  // foldrun open [page] the dashboard for this workspace
@@ -276,6 +276,7 @@ const HELP = `foldrun — agents are just folders
276
276
  foldrun workspaces show <name> what is deployed in one: its agents, flows and how each fires, its files by folder (--json)
277
277
  foldrun workspaces new <name> --platform make it on the platform: blank (an AGENTS.md), or --starter for the example researcher, writer and flow
278
278
  foldrun workspaces demo make the demo pipeline project on the platform — "Try the demo pipeline"
279
+ foldrun workspaces use <name> the project your commands use when they name none (no --to, no project folder) — checked on the platform, kept on this sign-in; no name shows it, --clear forgets it
279
280
  foldrun library the account's shared library on the platform: ls [skills|tools|hooks|scripts|knowledge|memory], cat <kind>/<path>, put <kind>/<path> (--file, else stdin), rm <kind>/<path> (asks)
280
281
  foldrun library new <kind>/<name> a new one from the platform's template, as the Library page's New (--template <transport or gallery entry>, --language)
281
282
  foldrun find <words> search the account as the dashboard's ⌘K does: projects, agents, flows, tools, skills, knowledge, memory, runs (--json)
@@ -449,7 +450,7 @@ Options
449
450
  --limit <n> usage: rows of by flow and by agent, the most charged first (default 10; 0 hides them)
450
451
  --value "<text>" secrets set: skip the prompt (careful with shell history)
451
452
  --site <domain> secrets set, secrets sites: a site the secret is bound to — the egress proxy fills it for those alone (repeatable, or a,b)
452
- --clear secrets sites: unbind it; flow compute: no cap of its own; me name: no name
453
+ --clear secrets sites: unbind it; flow compute: no cap of its own; me name: no name; workspaces use: forget the default project
453
454
  --all runs: every run that matches, every page; secrets workspaces: every project may use the account secret again; storage ls: every project's storage; storage shares: expired and revoked links too; mcp connections: the disconnected ones too; team invite, team access: every project
454
455
  --none secrets workspaces, secrets set: no project may use the account secret; team access: no projects
455
456
  --if-workspaces <a,b|all|none> secrets workspaces: change it only while the list is still this one (refused, 409, when someone changed it since)
package/docs/cli.md CHANGED
@@ -144,6 +144,7 @@ claude.ai or Claude Code there, nor any MCP configuration on disk.
144
144
  | `foldrun workspaces show <name>` | what is deployed in one project (`GET /api/workspaces/<name>`): its agents with model and description, its flows and how each fires, and its files counted by top-level folder. `--json` for the document |
145
145
  | `foldrun workspaces new <name> --platform` | the dashboard's **Create project**: blank — an `AGENTS.md` and nothing to delete (`POST /api/workspaces { name, template: true }`) — or `--starter` for the example researcher, writer and publish flow (`{ name, starter: true }`). The plan's project count applies. Without `--platform` it makes the folder here, as `foldrun new` does |
146
146
  | `foldrun workspaces demo` | **Try the demo pipeline**: makes the `demo-pipeline` project on the platform — a four-step flow with a parallel pair, an approval gate and a pretend CRM tool (`POST /api/workspaces { demo: true }`) |
147
+ | `foldrun workspaces use <name>` | the project your commands use when they name none: no `--to`, and you are not standing in a project folder. Checked on the platform first (`GET /api/workspaces/<name>`) and kept on this sign-in (one account on one platform; never with `--token` or `FOLDRUN_TOKEN`). `--to` and a project folder always win over it, and a command that uses it says `project <name>` on stderr. No name shows it, `--clear` forgets it, `--json` |
147
148
  | `foldrun library` | the account's shared library on the platform, as the Library page shows it: `ls [skills\|tools\|hooks\|scripts\|knowledge\|memory]`, `cat <kind>/<path>`, `put <kind>/<path>` (from `--file`, else stdin), `new <kind>/<name>` (the Library page's New, `POST /api/library/<kind> { name, template, language }`: the platform's template — `--template` a transport or a gallery entry, `--language` for a script tool), `rm <kind>/<path>` (asks). `deploy` still pushes the whole of it |
148
149
  | `foldrun find <words>` | the dashboard's ⌘K search: projects, agents, flows, tools, skills, knowledge, memory and runs across the account, ranked the same way (`GET /api/search`; `--json`) |
149
150
  | `foldrun invoke <flow>` | start a flow on a running platform — `--watch` follows its trace here; `--test` makes it a [test run](runs#test-runs) `--once <key>` sends the key as the run's idempotency key, so a CI step that retries after a dropped response is answered with the run it already started instead of paying for a second. `--tag <t>`, repeatable, labels the run (the API's `tags`). `--inputs <name>` sends a saved input set as the task — a case of `evals/<flow>-inputs.md` or of an eval that runs the flow, as the platform has it (see [Run with saved inputs](flows#run-with-saved-inputs)). `foldrun flow run <flow>` is the same command |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "foldrun",
3
- "version": "26.6.2",
3
+ "version": "26.7.1",
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-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
@@ -13,7 +13,7 @@ import { writeAgentFiles, hasCurrentAgentRules, agentRulesBlock, codingAgent, do
13
13
  import { browserCmd } from "./browser.mjs";
14
14
  import { createRequire } from "node:module";
15
15
  import { execFileSync, spawnSync } from "node:child_process";
16
- import { defaultPlatform, saveCredential, removeCredential, normaliseUrl, profileByName, currentProfile, useProfile, listProfiles, credentialsDir } from "./credentials.mjs";
16
+ import { defaultPlatform, saveCredential, removeCredential, normaliseUrl, profileByName, currentProfile, useProfile, listProfiles, credentialsDir, setProfileWorkspace } from "./credentials.mjs";
17
17
 
18
18
  // NO_COLOR (no-color.org) turns the escapes off — for a log file, a CI
19
19
  // job, or a test that wants to match what a person reads. The tests had
@@ -2599,13 +2599,15 @@ async function renewIfDue(url, flags) {
2599
2599
  }
2600
2600
  }
2601
2601
 
2602
- /** Whether the credentials file can be written in place (or, not there yet,
2603
- * made) — checked before a renewal, which cannot be undone. */
2602
+ /** Whether the credentials file can be replaced — checked before a renewal,
2603
+ * which cannot be undone. The file is written beside itself and renamed over
2604
+ * (credentials.mjs), so its FOLDER must be writable, and the file too. */
2604
2605
  function credentialsWritable() {
2605
2606
  const dir = credentialsDir();
2606
2607
  const file = path.join(dir, "credentials.json");
2607
2608
  try {
2608
- fs.accessSync(fs.existsSync(file) ? file : dir, fs.constants.W_OK);
2609
+ fs.accessSync(dir, fs.constants.W_OK);
2610
+ if (fs.existsSync(file)) fs.accessSync(file, fs.constants.W_OK);
2609
2611
  return true;
2610
2612
  } catch {
2611
2613
  return false;
@@ -3730,7 +3732,7 @@ async function logsCmd(positional, flags, layout) {
3730
3732
  // Inside an account folder the workspace comes first, the way it does on
3731
3733
  // every other workspace-scoped command — or is the only one there is.
3732
3734
  const named = takeWorkspace(positional, layout);
3733
- if (!named && !flags.to && layout?.kind === "account") throw whichWorkspace(layout, "logs");
3735
+ if (!named && !flags.to && layout?.kind === "account" && !(flags.local !== true && remoteUrl(flags) && savedWorkspace(flags))) throw whichWorkspace(layout, "logs");
3734
3736
  if (named && layout?.workspacesDir && layout.workspaces.includes(named)) {
3735
3737
  process.env.FOLDRUN_WORKSPACE = path.join(layout.workspacesDir, named);
3736
3738
  }
@@ -3739,7 +3741,11 @@ async function logsCmd(positional, flags, layout) {
3739
3741
  // machine's store even when signed in — the same escape hatch deploy,
3740
3742
  // secrets and keys have, and the one thing `logs` was missing.
3741
3743
  const url = flags.local === true ? undefined : remoteUrl(flags);
3742
- if (url) return remoteLogs(url, positional, { ...flags, to: flags.to ?? named ?? undefined });
3744
+ if (url) {
3745
+ // Resolved before the copy: savedDefault pins flags.profile (Codex).
3746
+ const to = flags.to ?? named ?? savedDefault(flags) ?? undefined;
3747
+ return remoteLogs(url, positional, { ...flags, to });
3748
+ }
3743
3749
 
3744
3750
  const { listRuns, readRun } = await core();
3745
3751
  const T = "default";
@@ -4022,7 +4028,7 @@ async function flowInputsCmd(positional, flags, layout) {
4022
4028
  * server whether or not this terminal sticks around. `--wait` holds on for
4023
4029
  * the result like an RPC.
4024
4030
  */
4025
- async function invoke(target, flags) {
4031
+ async function invoke(target, flags, layout) {
4026
4032
  const url = remoteUrl(flags);
4027
4033
  if (!url) {
4028
4034
  throw new Error(
@@ -4030,7 +4036,7 @@ async function invoke(target, flags) {
4030
4036
  );
4031
4037
  }
4032
4038
  if (!target) throw new Error("which flow? try `foldrun invoke <flow> --to <workspace>`");
4033
- const ws = flags.to;
4039
+ const ws = flags.to ?? (inProjectFolder(layout) ? undefined : savedDefault(flags));
4034
4040
  if (!ws) throw new Error("which project is it in? pass --to <workspace>");
4035
4041
 
4036
4042
  // --wait asks in short pieces, not one long request: whatever sits in
@@ -5550,11 +5556,13 @@ async function auditCmd(positional, flags) {
5550
5556
  * dashboard's Storage page — source is what you wrote, storage is what
5551
5557
  * they wrote.
5552
5558
  */
5553
- async function sourceCmd(positional, flags) {
5559
+ async function sourceCmd(positional, flags, layout) {
5554
5560
  const [verb, a, b] = positional;
5555
5561
  const url = remoteUrl(flags);
5556
5562
  if (!url) throw new Error("source reads a project on a platform — pass --url, or `foldrun login` first");
5557
- const ws = flags.to;
5563
+ // The saved default only outside a project folder (inside one, --to as
5564
+ // before), and never for a delete: a delete names its project.
5565
+ const ws = flags.to ?? (verb === "rm" || verb === "delete" || inProjectFolder(layout) ? undefined : savedDefault(flags));
5558
5566
  if (!ws) throw new Error("which project? pass --to <workspace>");
5559
5567
  const base = `/api/workspaces/${encodeURIComponent(ws)}/source`;
5560
5568
 
@@ -6124,7 +6132,7 @@ async function reportRuntimes(url, workspace, flags, { waitSeconds = 0 } = {}) {
6124
6132
  /** `foldrun runtimes` — the deployed workspace's environments and their state. */
6125
6133
  async function runtimesCmd(flags, layout) {
6126
6134
  const url = platformFor(flags, "runtimes");
6127
- const ws = typeof flags.to === "string" ? flags.to : layout?.kind === "empty" ? null : takeWorkspace([], layout);
6135
+ const ws = typeof flags.to === "string" ? flags.to : (layout?.kind === "empty" ? null : takeWorkspace([], layout)) ?? savedDefault(flags);
6128
6136
  if (!ws) throw new Error("which project? `foldrun runtimes --to <workspace>` — or run it inside one");
6129
6137
  console.log(`\n ${c.bold(ws)} ${c.dim("runtimes")}`);
6130
6138
  const runtimes = await reportRuntimes(url, ws, flags, { waitSeconds: flags.wait === true ? 120 : 0 });
@@ -6453,6 +6461,55 @@ async function pullCmd(layout, flags, only) {
6453
6461
  * `foldrun workspaces` — what exists here, what exists there, and which are
6454
6462
  * both. `rm <name>` removes one; on the platform it needs saying twice.
6455
6463
  */
6464
+ /** `foldrun workspaces use [<name>] [--clear]`: the project this profile's
6465
+ * commands use when they name none (no --to, no project folder) — checked
6466
+ * to exist on the platform first, kept on the profile. No name shows it. */
6467
+ async function workspacesUseCmd(name, flags) {
6468
+ if (typeof flags.token === "string" || env("FOLDRUN_TOKEN")) {
6469
+ throw new Error("a default project is kept on a signed-in profile — with --token or FOLDRUN_TOKEN, name the project with --to each time");
6470
+ }
6471
+ const p = chosenProfile(flags);
6472
+ if (!p) throw new Error(NOT_SIGNED_IN);
6473
+ if (flags.clear === true) {
6474
+ if (!setProfileWorkspace(p.name, null, { url: p.url, account: p.account })) {
6475
+ throw new Error(`${p.name} changed meanwhile (signed out, or signed in again as someone else) — nothing cleared; run it again`);
6476
+ }
6477
+ if (flags.json === true) {
6478
+ console.log(JSON.stringify({ profile: p.name, url: p.url, workspace: null }));
6479
+ return 0;
6480
+ }
6481
+ console.log(`\n ${c.green("✓")} no default project for ${c.bold(p.name)} ${c.dim(`on ${p.url} — commands need --to again`)}\n`);
6482
+ return 0;
6483
+ }
6484
+ if (!name) {
6485
+ if (flags.json === true) {
6486
+ console.log(JSON.stringify({ profile: p.name, url: p.url, workspace: p.workspace ?? null }));
6487
+ return 0;
6488
+ }
6489
+ console.log(p.workspace
6490
+ ? `\n ${c.bold(p.workspace)} ${c.dim(`— ${p.name} on ${p.url}; commands without --to use it (--clear forgets it)`)}\n`
6491
+ : `\n ${c.dim(`no default project for ${p.name} on ${p.url} — \`foldrun workspaces use <name>\` sets one`)}\n`);
6492
+ return 0;
6493
+ }
6494
+ assertName(name);
6495
+ const url = p.url;
6496
+ try {
6497
+ await remoteCall(url, { ...flags, profile: p.name }, `/api/workspaces/${encodeURIComponent(name)}`);
6498
+ } catch (err) {
6499
+ if (err?.status === 404) throw new Error(`no project "${name}" on ${url} — \`foldrun workspaces new ${name} --platform\` makes it`);
6500
+ throw err;
6501
+ }
6502
+ if (!setProfileWorkspace(p.name, name, { url, account: p.account })) {
6503
+ throw new Error(`${p.name} changed while checking (signed out, or signed in again as someone else) — nothing saved; run it again`);
6504
+ }
6505
+ if (flags.json === true) {
6506
+ console.log(JSON.stringify({ profile: p.name, url, workspace: name }));
6507
+ return 0;
6508
+ }
6509
+ console.log(`\n ${c.green("✓")} ${c.bold(name)} ${c.dim(`is the project for ${p.name} on ${url} — commands without --to use it; --to, or a project folder you stand in, still win`)}\n`);
6510
+ return 0;
6511
+ }
6512
+
6456
6513
  async function workspacesCmd(positional, flags, layout) {
6457
6514
  const [verb, name] = positional;
6458
6515
  const url = flags.local === true ? undefined : remoteUrl(flags);
@@ -6473,6 +6530,8 @@ async function workspacesCmd(positional, flags, layout) {
6473
6530
  return 0;
6474
6531
  }
6475
6532
 
6533
+ if (verb === "use") return workspacesUseCmd(name, flags);
6534
+
6476
6535
  if (verb === "rm" || verb === "remove" || verb === "delete") {
6477
6536
  if (!name) throw new Error("which project? `foldrun workspaces rm <name>`");
6478
6537
  // `rm ..` joined to workspaces/ is the account folder itself. A name is
@@ -6921,7 +6980,7 @@ async function storageCmd(positional, flags, layout) {
6921
6980
  // the file were missing. --to is the answer from anywhere else.
6922
6981
  // `storage text` also takes --workspace <name> — a name, not a folder.
6923
6982
  const named = positional[0] === "text" && typeof flags.workspace === "string" && /^[^/\\.][^/\\]*$/.test(flags.workspace) ? flags.workspace : null;
6924
- const ws = typeof flags.to === "string" ? flags.to : named ?? (layout?.kind === "empty" ? null : takeWorkspace([], layout));
6983
+ const ws = typeof flags.to === "string" ? flags.to : named ?? (layout?.kind === "empty" ? null : takeWorkspace([], layout)) ?? (positional[0] === "rm" ? null : savedDefault(flags));
6925
6984
  if (!ws) throw new Error("which project? `foldrun storage ls --to <workspace>` — or run it inside one");
6926
6985
  const verb = positional[0] ?? "ls";
6927
6986
 
@@ -7226,7 +7285,7 @@ async function docsCmd(positional, flags) {
7226
7285
  */
7227
7286
  async function triggersCmd(flags, layout) {
7228
7287
  const url = platformFor(flags, "triggers");
7229
- const ws = typeof flags.to === "string" ? flags.to : layout?.kind === "empty" ? null : takeWorkspace([], layout);
7288
+ const ws = typeof flags.to === "string" ? flags.to : (layout?.kind === "empty" ? null : takeWorkspace([], layout)) ?? savedDefault(flags);
7230
7289
  if (!ws) throw new Error("which project? `foldrun triggers --to <workspace>` — or run it inside one");
7231
7290
  const days = Number(flags.since) > 0 ? Math.floor(Number(flags.since)) : 7;
7232
7291
  const body = await remoteCall(url, flags, `/api/workspaces/${enc(ws)}/triggers?days=${days}`);
@@ -9642,12 +9701,60 @@ async function reportCmd(runId, flags, layout) {
9642
9701
  // ------------------------------------------------- one tool, one agent, alone
9643
9702
 
9644
9703
  /** Which workspace a platform command is about: --to, else the folder we stand in. */
9704
+ /** The project the signed-in profile saved with `foldrun workspaces use`,
9705
+ * or null: never with --token or FOLDRUN_TOKEN (no profile speaks), and
9706
+ * never when --url / FOLDRUN_URL points at another platform than the
9707
+ * profile's. */
9708
+ function savedWorkspace(flags) {
9709
+ if (typeof flags.token === "string" || env("FOLDRUN_TOKEN")) return null;
9710
+ let p;
9711
+ try {
9712
+ p = chosenProfile(flags);
9713
+ } catch {
9714
+ return null;
9715
+ }
9716
+ if (!p?.workspace || typeof p.workspace !== "string") return null;
9717
+ const url = remoteUrl(flags);
9718
+ try {
9719
+ if (url && normaliseUrl(url) !== normaliseUrl(p.url)) return null;
9720
+ } catch {
9721
+ return null;
9722
+ }
9723
+ // The profile the name came from: the request is pinned to it (Codex) —
9724
+ // another process switching the current profile meanwhile must not pair
9725
+ // this project's name with another account's token.
9726
+ if (typeof flags.profile !== "string") flags.profile = p.name;
9727
+ return p.workspace;
9728
+ }
9729
+
9730
+ /** Standing in a project folder (or an account folder with one project):
9731
+ * the folder names the project, so the saved default never applies. */
9732
+ function inProjectFolder(layout) {
9733
+ return Boolean(layout && layout.kind !== "empty" && takeWorkspace([], layout));
9734
+ }
9735
+
9736
+ /** The saved default (savedWorkspace), said once on stderr when used, so a
9737
+ * command never acts on a project the person did not see named. */
9738
+ let usedSaved = false;
9739
+ function savedDefault(flags) {
9740
+ const saved = savedWorkspace(flags);
9741
+ // Even with --quiet or --json: it is stderr, and a command acting on a
9742
+ // project nobody named must say which (Codex review).
9743
+ if (saved && !usedSaved) {
9744
+ usedSaved = true;
9745
+ console.error(` ${c.dim(`project ${saved} (foldrun workspaces use)`)}`);
9746
+ }
9747
+ return saved;
9748
+ }
9749
+
9645
9750
  function platformWorkspace(flags, layout, what) {
9646
9751
  // A folder with no agents in it is not a workspace, whatever it is called,
9647
9752
  // and guessing from its name posts to a workspace that does not exist —
9648
9753
  // which comes back as the platform's 404 about something else entirely.
9649
9754
  const guess = layout?.kind === "empty" ? null : takeWorkspace([], layout);
9650
- const ws = typeof flags.to === "string" ? flags.to : guess;
9755
+ // Then the profile's own default (`foldrun workspaces use`), last: --to and
9756
+ // the folder you stand in always win over it.
9757
+ const ws = typeof flags.to === "string" ? flags.to : guess ?? savedDefault(flags);
9651
9758
  if (!ws) {
9652
9759
  throw new Error(
9653
9760
  `which project is it in? \`foldrun ${what} --to <workspace>\`${
@@ -16868,7 +16975,7 @@ export async function run(command, positional, flags, workspace, layout) {
16868
16975
  if (positional[0] === "rm-step") return flowRmStepCmd(positional, flags, layout);
16869
16976
  if (positional[0] === "dup-step") return flowDupStepCmd(positional, flags, layout);
16870
16977
  if (positional[0] === "show") return flowShowCmd(positional, flags, layout);
16871
- if (positional[0] === "run") return invoke(positional[1], flags);
16978
+ if (positional[0] === "run") return invoke(positional[1], flags, layout);
16872
16979
  if (positional[0] === "inputs") return flowInputsCmd(positional, flags, layout);
16873
16980
  if (positional[0] === "rotate-hook") return rotateHookCmd(positional, flags, layout);
16874
16981
  if (positional[0] === "hook") return flowHookCmd(positional, flags, layout);
@@ -16890,9 +16997,9 @@ export async function run(command, positional, flags, workspace, layout) {
16890
16997
  case "hooks":
16891
16998
  return hookCmd(positional, flags, layout);
16892
16999
  case "invoke":
16893
- return invoke(positional[0], flags);
17000
+ return invoke(positional[0], flags, layout);
16894
17001
  case "source":
16895
- return sourceCmd(positional, flags);
17002
+ return sourceCmd(positional, flags, layout);
16896
17003
  case "open":
16897
17004
  return openCmd(positional, flags);
16898
17005
  default:
@@ -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
@@ -88,11 +234,20 @@ function write(current, profiles) {
88
234
  platforms[normaliseUrl(p.url)] = { token: p.token, email: p.email ?? null, account: p.account, role: p.role, ...(p.minted ? { minted: true } : {}), loggedInAt: p.loggedInAt };
89
235
  }
90
236
  fs.mkdirSync(credentialsDir(), { recursive: true, mode: 0o700 });
237
+ // Written beside it and renamed over it: a reader in another process sees
238
+ // the old file or the new one, never half of one (Codex review, 19 Nov).
239
+ const tmp = `${file()}.${process.pid}.${Date.now()}.tmp`;
91
240
  fs.writeFileSync(
92
- file(),
241
+ tmp,
93
242
  JSON.stringify({ current, default: current && profiles[current] ? normaliseUrl(profiles[current].url) : null, profiles, platforms }, null, 2) + "\n",
94
243
  { mode: 0o600 },
95
244
  );
245
+ try {
246
+ fs.renameSync(tmp, file());
247
+ } catch (err) {
248
+ fs.rmSync(tmp, { force: true });
249
+ throw err;
250
+ }
96
251
  // `mode` applies only when the file is created; one made before (or by
97
252
  // hand) keeps whatever it had. It holds tokens: owner-only, every write.
98
253
  try {
@@ -111,35 +266,46 @@ function write(current, profiles) {
111
266
  * @param {{ makeDefault?: boolean, name?: string }} [opts]
112
267
  */
113
268
  export function saveCredential(url, entry, { makeDefault = true, name } = {}) {
114
- const key = normaliseUrl(url);
115
- const { current, profiles } = readCredentials();
116
- const existing = name ?? Object.keys(profiles).find((n) => normaliseUrl(profiles[n].url) === key && profiles[n].account === entry.account);
117
- const profileName = existing ?? nameFor(profiles, entry.account, key);
118
- profiles[profileName] = { ...entry, url: key, loggedInAt: new Date().toISOString() };
119
- write(makeDefault || !current ? profileName : current, profiles);
120
- 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
+ });
121
285
  }
122
286
 
123
287
  /** Forget one. By name, else by URL (the newest there). Returns what was
124
288
  * stored, for a best-effort revoke. */
125
289
  export function removeCredential(urlOrName) {
126
- const { current, profiles } = readCredentials();
127
- const key = (() => {
128
- if (profiles[urlOrName]) return urlOrName;
129
- try {
130
- const u = normaliseUrl(urlOrName);
131
- const here = Object.keys(profiles).filter((n) => normaliseUrl(profiles[n].url) === u);
132
- return here.sort((a, b) => String(profiles[a].loggedInAt ?? "").localeCompare(String(profiles[b].loggedInAt ?? ""))).at(-1) ?? null;
133
- } catch {
134
- return null;
135
- }
136
- })();
137
- if (!key) return null;
138
- const gone = profiles[key];
139
- delete profiles[key];
140
- const names = Object.keys(profiles);
141
- write(current === key ? names[0] ?? null : current, profiles);
142
- 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
+ });
143
309
  }
144
310
 
145
311
  /** The stored entry for a URL — the newest account signed in there. */
@@ -170,10 +336,32 @@ export function currentProfile() {
170
336
 
171
337
  /** Make one the profile a bare command talks as. */
172
338
  export function useProfile(name) {
173
- const { profiles } = readCredentials();
174
- if (!profiles[name]) return null;
175
- write(name, profiles);
176
- 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
+ });
345
+ }
346
+
347
+ /** Save (or, with null, forget) the project a profile's commands use when
348
+ * they name none — `foldrun workspaces use`. Kept on the profile, so it is
349
+ * one account on one platform's, and never follows a --token. */
350
+ export function setProfileWorkspace(name, workspace, expect = {}) {
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
+ });
177
365
  }
178
366
 
179
367
  /** All of them, newest sign-in last. */