owenloop 0.3.1 → 0.4.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/dist/cli.js CHANGED
@@ -31,20 +31,24 @@
31
31
  *
32
32
  * Global: --db <path> (env OWENLOOP_DB), --defs <dir> (env OWENLOOP_DEFS).
33
33
  */
34
- import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
35
- import { basename, dirname, join, resolve } from 'node:path';
36
- import { spawn } from 'node:child_process';
37
- import { execFileSync } from 'node:child_process';
34
+ import { existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
35
+ import { basename, delimiter, dirname, join, resolve } from 'node:path';
36
+ import { spawn, spawnSync } from 'node:child_process';
38
37
  import { createServer } from 'node:http';
38
+ import { createInterface } from 'node:readline/promises';
39
+ import { hostname } from 'node:os';
39
40
  import { parse as parseYaml } from 'yaml';
40
41
  import { Engine } from "./engine.js";
41
42
  import { buildGraph, buildTrace, graphToDot, graphToMermaid, modelCheck } from "./model.js";
42
43
  import { openStore } from "./store.js";
43
44
  import { buildDef, DefError, finalizeDefs, lintDef, loadDefs, loadDefsRaw, loadDefsUnfinalized, validateDef, } from "./defs.js";
44
- import { dbPathRefusingSymlink, detId, mkdirRefusingSymlink, nowMs, parseDurationMs, randId } from "./util.js";
45
+ import { CliError, dbPathRefusingSymlink, detId, mkdirRefusingSymlink, nowMs, parseDurationMs, randId } from "./util.js";
46
+ import { authHeader, deleteCredential, discoverMetadata, ensureFreshOAuth, hubFetch, hubMaxResponseBytes, mintAgentCredential, readBodyBounded, refreshOAuth, rekeyAgentCredential, storeCredential, } from "./credentials.js";
47
+ import { runMcpCommand } from "./mcp/serve.js";
45
48
  import { DEFAULT_TAR_LIMITS, extractTarGz } from "./untar.js";
46
49
  import { acquireInstallLock, ADD_JOURNAL_FILENAME, archivePathViolation, commitInstall, finalizeInstallCommit, githubShaUrl, githubTarballUrl, installFolder, parkOldNameDir, parseRepoSpec, readLockfile, recoverInterruptedInstall, releaseInstallLock, removeAddJournal, rollbackInstallCommit, RollbackFailedError, stageFiles, STAGING_DIRNAME, writeAddJournal, writeLockfile, } from "./add.js";
47
- import { asCreateWorkflowOk, asWhoami, computeServerDiff, createWorkflowError, credentialFilePath, hashDefForHub, hubBindingPath, normalizeOrigin, parseWorkflowList, pkcePair, randomState, readCredentialFile, readHubBinding, resolveEndpoint, writeCredentialFile, writeHubBinding, } from "./hub.js";
50
+ import { asAgentIdentities, asCreateWorkflowOk, asWhoami, computeServerDiff, credentialBackend, createWorkflowError, credentialFilePath, credentialSlot, externalCredentialCommand, hashDefForHub, hubBindingPath, keychainServiceFor, listStoredHubOrigins, normalizeOrigin, parseWorkflowList, pkcePair, randomState, readCredentialFile, readHubBinding, readStoredCredential, resolveEndpoint, resolveKeychain, writeCredentialFile, writeHubBinding, } from "./hub.js";
51
+ import { owenworkSettingsPath, readOwenworkSettingsRaw, writeOwenworkHubOrigin } from "./owenwork.js";
48
52
  function defaultIO() {
49
53
  return {
50
54
  cwd: process.cwd(),
@@ -54,8 +58,33 @@ function defaultIO() {
54
58
  fetch: globalThis.fetch,
55
59
  openUrl: defaultOpenUrl,
56
60
  readStdin: defaultReadStdin,
61
+ prompt: defaultPrompt,
62
+ runCommand: defaultRunCommand,
57
63
  };
58
64
  }
65
+ /**
66
+ * The default interactive prompt: a one-shot `node:readline/promises` question
67
+ * whose text and echo go to STDERR (so stdout remains the parseable JSON
68
+ * document). Closed immediately after the single read.
69
+ */
70
+ async function defaultPrompt(question) {
71
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
72
+ try {
73
+ return await rl.question(question);
74
+ }
75
+ finally {
76
+ rl.close();
77
+ }
78
+ }
79
+ /**
80
+ * The default local-command runner: `spawnSync` with `shell: false` (argv is
81
+ * passed as a vector, never interpolated into a shell) and captured, not
82
+ * inherited, stdio. Only the plugin probe uses it.
83
+ */
84
+ function defaultRunCommand(cmd, args) {
85
+ const r = spawnSync(cmd, args, { encoding: 'utf8' });
86
+ return { status: r.status, stdout: r.stdout ?? '', stderr: r.stderr ?? '' };
87
+ }
59
88
  /** Fire-and-forget browser open — never blocks the login flow on the child. */
60
89
  function defaultOpenUrl(url) {
61
90
  const platform = process.platform;
@@ -73,51 +102,6 @@ async function defaultReadStdin() {
73
102
  chunks.push(chunk);
74
103
  return Buffer.concat(chunks).toString('utf8');
75
104
  }
76
- /**
77
- * The default macOS keychain backend (generic passwords under service
78
- * `owenloop-hub`). The secret is fed through the `security -i` command stream on
79
- * stdin, never as a `-w` argv value, so it never appears in `ps`/shell history.
80
- * Returns `undefined` off macOS or when `OWENLOOP_NO_KEYCHAIN=1`, so callers
81
- * fall back to the 0600 credential file.
82
- */
83
- const KEYCHAIN_SERVICE = 'owenloop-hub';
84
- function defaultKeychain(env) {
85
- if (env.OWENLOOP_NO_KEYCHAIN === '1')
86
- return undefined;
87
- if (process.platform !== 'darwin')
88
- return undefined;
89
- return {
90
- get(account) {
91
- try {
92
- const out = execFileSync('security', ['find-generic-password', '-s', KEYCHAIN_SERVICE, '-a', account, '-w'], {
93
- encoding: 'utf8',
94
- stdio: ['ignore', 'pipe', 'ignore'],
95
- });
96
- return out.replace(/\n$/, '');
97
- }
98
- catch {
99
- return null; // not found (errSecItemNotFound) — treated as "no credential"
100
- }
101
- },
102
- set(account, value) {
103
- // `security -i` reads newline-terminated commands from stdin; the secret
104
- // rides in that stdin stream (single-quoted), never on this process's argv.
105
- const sq = (s) => `'${s.replace(/'/g, `'\\''`)}'`;
106
- const cmd = `add-generic-password -U -s ${sq(KEYCHAIN_SERVICE)} -a ${sq(account)} -w ${sq(value)}\n`;
107
- execFileSync('security', ['-i'], { input: cmd, stdio: ['pipe', 'ignore', 'ignore'] });
108
- },
109
- delete(account) {
110
- try {
111
- execFileSync('security', ['delete-generic-password', '-s', KEYCHAIN_SERVICE, '-a', account], {
112
- stdio: 'ignore',
113
- });
114
- }
115
- catch {
116
- // Not found — already absent; a no-op delete is success.
117
- }
118
- },
119
- };
120
- }
121
105
  /**
122
106
  * Flags that are always boolean and must never consume the following token as
123
107
  * a value — `owenloop push --force foo` must force-push only `foo`, not treat
@@ -130,6 +114,7 @@ function defaultKeychain(env) {
130
114
  */
131
115
  const BOOLEAN_FLAGS = new Set([
132
116
  'assume-provided',
117
+ 'strict-inputs',
133
118
  'shallow',
134
119
  'now',
135
120
  'all',
@@ -185,8 +170,6 @@ const flag = (args, key) => {
185
170
  const v = last(args, key);
186
171
  return v === 'true' || v === '' || (v !== undefined && v !== 'false');
187
172
  };
188
- class CliError extends Error {
189
- }
190
173
  /**
191
174
  * A 429 from the hub during a push batch (REL-10). Thrown from the batch loop
192
175
  * and handled by an explicit `instanceof` branch that halts the rest of the
@@ -392,13 +375,18 @@ Commands:
392
375
  defs list available workflow definitions
393
376
  add <owner>/<repo>[@ref] fetch, validate, and install a repo's workflow defs (public repos)
394
377
  add --recover finish or undo a crash-interrupted install (offline; no network)
395
- login [--hub <url>] [--with-token] authenticate the CLI against a hub, verified via whoami (loopback OAuth, or --with-token from stdin)
396
- logout [--hub <url>] delete the stored credential for a hub
397
- connect [--hub <url>] bind this project to a hub and verify the stored credential (whoami)
398
- push [<defName>...] [--force] [--dry-run] publish local workflow defs to the bound hub (server-diffed, idempotent)
378
+ login [--hub <url>] [--with-token] [--as <slot>] authenticate the CLI against a hub, verified via whoami (loopback OAuth, or --with-token from stdin)
379
+ logout [--hub <url>] [--as <slot>] delete the stored credential for a hub in one slot
380
+ connect [--hub <url>] [--as <slot>] bind this project to a hub and verify the stored credential (whoami)
381
+ push [<defName>...] [--force] [--dry-run] [--as <slot>] publish local workflow defs to the bound hub (server-diffed, idempotent)
382
+ --as names the credential slot: human (default), agent, or agent:<account>
383
+ agent new <name> [--pools <a,b>] [--hub <url>] mint a new agent identity on the hub and store its token in slot agent:<name> (the token is never printed)
384
+ setup [--hub <url>] [--new-agent <name> | --replace-agent <name>] [--pools <a,b>] converge this machine's install: human login, agent credential, owenwork settings, plugin (idempotent)
385
+ doctor [--hub <url>] check this machine's owenloop install and report each piece (read-only)
386
+ mcp [--hub <url>] serve the hub control plane over stdio MCP (spawned by MCP hosts, not run by humans)
399
387
  lint [<def-name>] check def(s) for wiring problems
400
- check <def> [--format text|json] [--max-depth N] [--max-states N] [--max-collection N] [--assume-provided]
401
- bounded reachability check (deadlocks, stuck, dead steps, declared invariants)
388
+ check <def> [--format text|json] [--max-depth N] [--max-states N] [--max-collection N] [--assume-provided] [--strict-inputs]
389
+ bounded reachability check (stall states, true deadlocks, stuck, dead steps, declared invariants)
402
390
  create <def> [--title t] [--provide name=json ...] [--param k=v ...]
403
391
  provide <wf> <name> [--value json] supply an owed (seedOwed) input
404
392
  adopt <wf> re-pin an instance to the current def (§28); settles new debts
@@ -457,12 +445,16 @@ export const COMMAND_OPTIONS = new Map([
457
445
  ['help', cmdOpts()],
458
446
  ['defs', cmdOpts()],
459
447
  ['add', cmdOpts('recover')],
460
- ['login', cmdOpts('hub', 'with-token')],
461
- ['logout', cmdOpts('hub')],
462
- ['connect', cmdOpts('hub')],
463
- ['push', cmdOpts('dry-run', 'force', 'hub')],
448
+ ['login', cmdOpts('hub', 'with-token', 'as')],
449
+ ['logout', cmdOpts('hub', 'as')],
450
+ ['connect', cmdOpts('hub', 'as')],
451
+ ['push', cmdOpts('dry-run', 'force', 'hub', 'as')],
452
+ ['agent', cmdOpts('pools', 'hub')],
453
+ ['setup', cmdOpts('hub', 'new-agent', 'replace-agent', 'pools')],
454
+ ['doctor', cmdOpts('hub')],
455
+ ['mcp', cmdOpts('hub')],
464
456
  ['lint', cmdOpts()],
465
- ['check', cmdOpts('format', 'max-depth', 'max-states', 'max-collection', 'assume-provided')],
457
+ ['check', cmdOpts('format', 'max-depth', 'max-states', 'max-collection', 'assume-provided', 'strict-inputs')],
466
458
  ['create', cmdOpts('title', 'provide', 'param')],
467
459
  ['provide', cmdOpts('value')],
468
460
  ['adopt', cmdOpts()],
@@ -618,19 +610,24 @@ function dispatch(command, io, args) {
618
610
  const maxDepth = numOpt(args, 'max-depth');
619
611
  const maxStates = numOpt(args, 'max-states');
620
612
  const maxCollection = numOpt(args, 'max-collection');
621
- const report = modelCheck(def, {
613
+ // `--strict-inputs` restores the pre-existing seedOwed-starts-owed behavior;
614
+ // it takes precedence over `--assume-provided` when both are passed (the
615
+ // newer explicit opt-out wins; `--assume-provided` is otherwise redundant
616
+ // with the new default and is kept only so it never errors as unknown).
617
+ const strictInputs = flag(args, 'strict-inputs');
618
+ const bounds = {
622
619
  ...(maxDepth !== undefined ? { maxDepth } : {}),
623
620
  ...(maxStates !== undefined ? { maxStates } : {}),
624
621
  ...(maxCollection !== undefined ? { maxCollectionSize: maxCollection } : {}),
625
- ...(flag(args, 'assume-provided') ? { assumeProvided: true } : {}),
626
- });
622
+ };
623
+ const report = modelCheck(def, { ...bounds, assumeProvided: !strictInputs });
627
624
  if (format === 'json') {
628
625
  print(io, report);
629
626
  }
630
627
  else {
631
628
  // text format
632
- const clean = report.deadlocks.length === 0 && report.stuck.length === 0
633
- && report.invariantViolations.length === 0;
629
+ const clean = report.deadlocks.length === 0
630
+ && report.invariantViolations.length === 0 && report.structurallyDeadSteps.length === 0;
634
631
  const status = clean && report.completable ? 'OK' : clean ? 'INCOMPLETE' : 'DEFECTS FOUND';
635
632
  io.out(`=== owenloop check: ${def.name} ===`);
636
633
  io.out(`Status: ${status}`);
@@ -641,16 +638,42 @@ function dispatch(command, io, args) {
641
638
  io.out(`SEARCH INCOMPLETE — bounds hit: ${report.boundsHit.join(', ')}`);
642
639
  io.out('Verdicts apply only within the explored region.');
643
640
  }
641
+ if (report.stallStates.length > 0) {
642
+ io.out('');
643
+ io.out(`Stall states (expected — maxAttempts / human-escalation brakes) (${report.stallStates.length}):`);
644
+ for (const s of report.stallStates) {
645
+ io.out(` path: ${s.path.map((p) => `${p.step}/${p.outcome}`).join(' -> ') || '(initial state)'}`);
646
+ }
647
+ }
644
648
  if (report.deadlocks.length > 0) {
645
649
  io.out('');
646
- io.out(`Deadlocks (${report.deadlocks.length}):`);
650
+ io.out(`True deadlocks (no path to completion at unlimited attempts) (${report.deadlocks.length}):`);
647
651
  for (const d of report.deadlocks) {
648
652
  io.out(` path: ${d.path.map((s) => `${s.step}/${s.outcome}`).join(' -> ') || '(initial state)'}`);
649
653
  }
650
654
  }
655
+ if (strictInputs) {
656
+ const seedOwedNames = def.inputs.filter((i) => i.seedOwed).map((i) => i.name);
657
+ const initialDeadlock = report.deadlocks.some((d) => d.path.length === 0);
658
+ if (seedOwedNames.length > 0 && initialDeadlock) {
659
+ // precision: would treating seedOwed inputs as provided dissolve the
660
+ // initial-state deadlock? If so, it's caused solely by unprovided
661
+ // seedOwed inputs, not a structural defect — print a hint pointing at
662
+ // the new default. This never fires for a deadlock that survives
663
+ // providing the seeded inputs (a structural one).
664
+ const probe = modelCheck(def, { ...bounds, assumeProvided: true });
665
+ const clearedByProvide = !probe.deadlocks.some((d) => d.path.length === 0);
666
+ if (clearedByProvide) {
667
+ io.out('');
668
+ io.out(`Hint: the initial-state deadlock is caused solely by unprovided seedOwed input(s): ${seedOwedNames.join(', ')}.`);
669
+ io.out(` Seeded inputs are assumed provided by default; this appears only because --strict-inputs was passed.`);
670
+ io.out(` Re-run 'owenloop check ${def.name}' without --strict-inputs to check the real reachable space.`);
671
+ }
672
+ }
673
+ }
651
674
  if (report.stuck.length > 0) {
652
675
  io.out('');
653
- io.out(`Stuck states (${report.stuck.length}):`);
676
+ io.out(`Stuck states (brake tripped; other branches still moving — informational) (${report.stuck.length}):`);
654
677
  for (const s of report.stuck) {
655
678
  io.out(` path: ${s.path.map((p) => `${p.step}/${p.outcome}`).join(' -> ') || '(initial state)'}`);
656
679
  }
@@ -663,9 +686,13 @@ function dispatch(command, io, args) {
663
686
  io.out(` path: ${v.path.map((s) => `${s.step}/${s.outcome}`).join(' -> ') || '(initial state)'}`);
664
687
  }
665
688
  }
666
- if (report.deadSteps.length > 0) {
689
+ if (report.structurallyDeadSteps.length > 0) {
667
690
  io.out('');
668
- io.out(`Dead steps (never fire in explored space): ${report.deadSteps.join(', ')}`);
691
+ io.out(`Structurally dead steps (can never fire — wiring defect): ${report.structurallyDeadSteps.join(', ')}`);
692
+ }
693
+ if (report.unreachedSteps.length > 0) {
694
+ io.out('');
695
+ io.out(`Unreached within bounds (raise --max-states/--max-depth): ${report.unreachedSteps.join(', ')}`);
669
696
  }
670
697
  if (report.completePath) {
671
698
  io.out('');
@@ -678,16 +705,32 @@ function dispatch(command, io, args) {
678
705
  // counterexample path was produced by real applyOutcome/settleInMemory
679
706
  // transitions (pinned to the live Engine by the conformance test). The path
680
707
  // is a genuine executable witness; bounds only cause MISSES, never
681
- // fabrications. Contrast deadlocks/stuck, where the maxCollectionSize cap can
682
- // manufacture a spurious "no moves" state — hence those require !bounded.
708
+ // fabrications. Contrast true deadlocks, where the maxCollectionSize cap can
709
+ // manufacture a spurious "no moves" state — hence that requires !bounded.
683
710
  // Do NOT remove this asymmetry; it encodes a real soundness distinction.
684
- // - definite deadlock/stuck only when EXHAUSTIVE (!bounded) → nonzero
685
- // - truncated with no invariant violations → 0
711
+ // - structurally-dead steps → ALWAYS nonzero, regardless of bounded. Unlike
712
+ // true deadlocks (found by the bounded BFS, so a tighter maxCollectionSize
713
+ // can manufacture a spurious one), structurally-dead is a STATIC canEverFire
714
+ // finding that needs no search bounds at all — it is sound and bounds-
715
+ // independent by construction (model.ts's canEverFire only ever returns
716
+ // false when certain), so it belongs with invariant violations, not with
717
+ // true deadlocks. unreachedSteps (the other dead-step bucket) must NEVER
718
+ // affect the exit code — it is purely a bounds artifact.
719
+ // - definite (true) deadlock only when EXHAUSTIVE (!bounded) → nonzero
720
+ // - stall states and stuck states are by-design brakes and NEVER affect the
721
+ // exit code — a stall state (report.stallStates) is EXPECTED (a human-
722
+ // escalation brake whose freeze, once lifted, re-arms a producer), and a
723
+ // stuck state (report.stuck) is purely informational (a brake tripped on
724
+ // one branch while the line still moves on another). Neither is a defect.
725
+ // - truncated with no invariant violations / structurally-dead steps / true
726
+ // deadlocks → 0
686
727
  const hasDefiniteDefect = report.invariantViolations.length > 0 ||
687
- (!report.bounded && (report.deadlocks.length > 0 || report.stuck.length > 0));
728
+ report.structurallyDeadSteps.length > 0 ||
729
+ (!report.bounded && report.deadlocks.length > 0);
688
730
  if (hasDefiniteDefect) {
689
731
  throw new CliError(`definite defects found (${report.invariantViolations.length} invariant violation(s), ` +
690
- `${report.deadlocks.length} deadlock(s), ${report.stuck.length} stuck state(s))`);
732
+ `${report.structurallyDeadSteps.length} structurally dead step(s), ` +
733
+ `${report.deadlocks.length} true deadlock(s))`);
691
734
  }
692
735
  return 0;
693
736
  }
@@ -1169,57 +1212,6 @@ function statusEntry(engine, w) {
1169
1212
  // one if ever needed).
1170
1213
  const ADD_SHA_TIMEOUT_MS = 30_000;
1171
1214
  const ADD_TARBALL_TIMEOUT_MS = 300_000;
1172
- /**
1173
- * Read a `Response` body while enforcing a byte `cap`, so a hostile server can
1174
- * never make us allocate an oversized body. Rejects UP FRONT on a declared
1175
- * oversize `Content-Length`; otherwise streams the body in chunks, counting the
1176
- * bytes that actually land in memory, and cancels the stream the moment the
1177
- * running total crosses the cap — the chunk buffer never holds more than `cap`
1178
- * plus one chunk. `label` names the request in the error and is origin+path or
1179
- * `owner/repo@sha` only — never a token. Counting post-decode bytes (what lands
1180
- * in memory) is deliberate: the cap protects memory, not wire bytes.
1181
- *
1182
- * `res.body === null` (empty/no-body response) yields empty bytes, so callers
1183
- * behave exactly as they did under `arrayBuffer()`. An absent, malformed, or
1184
- * multi-valued `Content-Length` skips the header check — the counting path is
1185
- * the real guard (GitHub codeload tarballs are typically chunked, no header). A
1186
- * `TimeoutError`/`AbortError` from `read()` (the abort signal fired mid-body)
1187
- * propagates untouched, so each call site's existing timeout mapping still
1188
- * fires exactly as it did for `arrayBuffer()` rejections. `cancel()` may reject
1189
- * on an already-errored stream — swallowed; the cap `CliError` is the story.
1190
- */
1191
- async function readBodyBounded(res, cap, label) {
1192
- const declared = Number(res.headers.get('content-length'));
1193
- if (Number.isFinite(declared) && declared > cap) {
1194
- await res.body?.cancel().catch(() => { });
1195
- throw new CliError(`response body for ${label} exceeds the ${cap}-byte cap (declared Content-Length ${declared})`);
1196
- }
1197
- if (res.body === null)
1198
- return new Uint8Array(0);
1199
- const reader = res.body.getReader();
1200
- const chunks = [];
1201
- let total = 0;
1202
- for (;;) {
1203
- const { done, value } = await reader.read();
1204
- if (done)
1205
- break;
1206
- if (value === undefined)
1207
- continue;
1208
- total += value.byteLength;
1209
- chunks.push(value);
1210
- if (total > cap) {
1211
- await reader.cancel().catch(() => { });
1212
- throw new CliError(`response body for ${label} exceeds the ${cap}-byte cap`);
1213
- }
1214
- }
1215
- const out = new Uint8Array(total);
1216
- let offset = 0;
1217
- for (const chunk of chunks) {
1218
- out.set(chunk, offset);
1219
- offset += chunk.byteLength;
1220
- }
1221
- return out;
1222
- }
1223
1215
  /**
1224
1216
  * Cap on the `add` tarball download body, enforced DURING the stream by
1225
1217
  * `readBodyBounded` — defense in depth with `extractTarGz`'s own post-hoc
@@ -1469,10 +1461,10 @@ async function dispatchAdd(io, args) {
1469
1461
  // publishing.
1470
1462
  const report = modelCheck(stagedDef, { assumeProvided: true });
1471
1463
  const hasDefiniteDefect = report.invariantViolations.length > 0 ||
1472
- (!report.bounded && (report.deadlocks.length > 0 || report.stuck.length > 0));
1464
+ (!report.bounded && report.deadlocks.length > 0);
1473
1465
  if (hasDefiniteDefect) {
1474
1466
  reasons.push(`${stagedDef.name}: definite defects found (${report.invariantViolations.length} invariant violation(s), ` +
1475
- `${report.deadlocks.length} deadlock(s), ${report.stuck.length} stuck state(s))`);
1467
+ `${report.deadlocks.length} true deadlock(s))`);
1476
1468
  }
1477
1469
  }
1478
1470
  // Strict backstop: only if the aggregate pass found nothing, run the FULL
@@ -1722,229 +1714,55 @@ function resolveHub(io, args) {
1722
1714
  throw new CliError(e.message);
1723
1715
  }
1724
1716
  }
1725
- function resolveKeychain(io) {
1726
- if (io.env.OWENLOOP_NO_KEYCHAIN === '1')
1727
- return undefined;
1728
- return io.keychain ?? defaultKeychain(io.env);
1729
- }
1730
- function credentialBackend(io) {
1731
- const kc = resolveKeychain(io);
1732
- return kc ? { kind: 'keychain', kc } : { kind: 'file' };
1733
- }
1734
- /**
1735
- * Read the stored credential for `origin` from the chosen backend ONLY. A
1736
- * keychain-backed read NEVER falls through to the file (that fallback was the
1737
- * REL-6 shadowing bug), and a corrupt keychain entry reads as absent (`null`)
1738
- * — login overwrites it, logout clears it — never as a reason to consult the
1739
- * file.
1740
- */
1741
- function readCredential(io, origin) {
1742
- const backend = credentialBackend(io);
1743
- if (backend.kind === 'keychain') {
1744
- const raw = backend.kc.get(origin);
1745
- if (!raw)
1746
- return null;
1747
- try {
1748
- return JSON.parse(raw);
1749
- }
1750
- catch {
1751
- return null; // corrupt entry — treat as absent; do NOT consult the file
1752
- }
1753
- }
1754
- const file = readCredentialFile(credentialFilePath(io.env));
1755
- return file.hubs[origin] ?? null;
1756
- }
1757
1717
  /**
1758
- * Store a credential for `origin` in the chosen backend ONLY; returns which
1759
- * one. A failed keychain write is a hard error (REL-6), never a silent
1760
- * fall-through to the file — the escape hatch is to choose the file backend up
1761
- * front with `OWENLOOP_NO_KEYCHAIN=1`.
1718
+ * Parse `--as <human | agent | agent:NAME>` into a `CredentialSlotSelector`.
1719
+ * Absent `--as` means the **human** slot — the everyday interactive case.
1720
+ * A malformed value (or an invalid account name, validated by `credentialSlot`)
1721
+ * is a usage error, never a silent coercion to some other slot.
1762
1722
  */
1763
- function storeCredential(io, origin, cred) {
1764
- const backend = credentialBackend(io);
1765
- if (backend.kind === 'keychain') {
1766
- try {
1767
- backend.kc.set(origin, JSON.stringify(cred));
1768
- }
1769
- catch (e) {
1770
- throw new CliError(`could not write the credential to the OS keychain: ${e.message}. ` +
1771
- 'Fix the keychain, or set OWENLOOP_NO_KEYCHAIN=1 to use the 0600 file store');
1772
- }
1773
- return 'keychain';
1774
- }
1775
- const path = credentialFilePath(io.env);
1776
- const file = readCredentialFile(path);
1777
- file.hubs[origin] = cred;
1778
- writeCredentialFile(path, file);
1779
- return 'file';
1780
- }
1781
- /**
1782
- * Delete any stored credential for `origin` from BOTH backends. Deliberately
1783
- * not routed through `credentialBackend`: logout is a defensive dual-clear
1784
- * (the proposal explicitly blesses it), so a live refresh token can never be
1785
- * stranded in the store that wasn't the currently-chosen one. Returns whether
1786
- * anything was removed.
1787
- */
1788
- function deleteCredential(io, origin) {
1789
- let removed = false;
1790
- const kc = resolveKeychain(io);
1791
- if (kc && kc.get(origin) !== null) {
1792
- kc.delete(origin);
1793
- removed = true;
1794
- }
1795
- const path = credentialFilePath(io.env);
1796
- const file = readCredentialFile(path);
1797
- if (file.hubs[origin] !== undefined) {
1798
- delete file.hubs[origin];
1799
- writeCredentialFile(path, file);
1800
- removed = true;
1801
- }
1802
- return removed;
1803
- }
1804
- /** The Bearer value for an authenticated request. Never logged. */
1805
- function authHeader(cred) {
1806
- return `Bearer ${cred.accessToken}`;
1807
- }
1808
- // Request deadline for EVERY hub/auth call — OAuth discovery, DCR, code
1809
- // exchange, token refresh, whoami, workflow list, and push (REL-7). These are
1810
- // all small JSON round-trips, so one budget fits them all;
1811
- // OWENLOOP_HUB_TIMEOUT_MS overrides it (a test knob, consistent with
1812
- // OWENLOOP_LOGIN_TIMEOUT_MS and the project's other OWENLOOP_* test-only knobs).
1813
- const HUB_TIMEOUT_MS = 30_000;
1814
- function hubTimeoutMs(io) {
1815
- const override = Number(io.env.OWENLOOP_HUB_TIMEOUT_MS);
1816
- return Number.isFinite(override) && override > 0 ? override : HUB_TIMEOUT_MS;
1817
- }
1818
- // Cap on any hub/auth JSON RESPONSE body (OAuth discovery, DCR, code exchange,
1819
- // token refresh, whoami, the workflow list, create_workflow). Hub responses are
1820
- // small round-trips — the largest realistic body is a workflows summary list,
1821
- // far below 8 MiB. This is a RESPONSE cap; the hub's 32MB figure (the 413 path)
1822
- // is a REQUEST cap and responses never echo YAML. OWENLOOP_HUB_MAX_RESPONSE_BYTES
1823
- // overrides it (a test-only knob, consistent with OWENLOOP_HUB_TIMEOUT_MS).
1824
- const HUB_MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
1825
- function hubMaxResponseBytes(io) {
1826
- const override = Number(io.env.OWENLOOP_HUB_MAX_RESPONSE_BYTES);
1827
- return Number.isFinite(override) && override > 0 ? override : HUB_MAX_RESPONSE_BYTES;
1828
- }
1829
- /**
1830
- * `fetch` wrapper putting a deadline on every hub/auth call (REL-7). The abort
1831
- * signal is threaded into `fetch` AND the body is read (via `readBodyBounded`,
1832
- * which caps the response size — see HUB_MAX_RESPONSE_BYTES) inside the same
1833
- * try, so the deadline covers a stalled BODY read too — the exact undici
1834
- * behavior the two `add` fetches document (`AbortSignal.timeout` ties the
1835
- * signal to the body stream). The returned `Response` re-exposes the read
1836
- * body, so every call site's `res.json()` / `res.status` /
1837
- * `res.headers.get(...)` usage is byte-for-byte unchanged. A
1838
- * `TimeoutError`/`AbortError` becomes a clear `CliError` (naming the request,
1839
- * which is origin+path only — never a token); anything else is rethrown
1840
- * untouched.
1841
- *
1842
- * `redirect: 'error'` is forced on every call — after the `...init` spread, so
1843
- * no caller can override it — to close the redirect gap `resolveEndpoint`
1844
- * (SEC-4) cannot see: same-origin validation covers only the INITIAL URL, but a
1845
- * validated endpoint answering 307/308 would re-send the POST body (refresh
1846
- * token, PKCE verifier, auth code, workflow YAML) to a foreign origin — undici
1847
- * strips the Authorization header on a cross-origin redirect but RESENDS the
1848
- * body. The hub protocol has no redirects, so any 3xx is a hard, loud failure
1849
- * mapped to a `CliError` (again naming origin+path only, never a token).
1850
- */
1851
- async function hubFetch(io, url, init) {
1852
- const fetchFn = io.fetch ?? globalThis.fetch;
1853
- const ms = hubTimeoutMs(io);
1854
- const method = (init?.method ?? 'GET').toUpperCase();
1723
+ function resolveSlot(args) {
1724
+ const raw = last(args, 'as');
1725
+ const sel = parseSlotArg(raw);
1726
+ // Validate eagerly so a bad account name fails before any network or store
1727
+ // access, with the same wording every later call site would produce.
1855
1728
  try {
1856
- const res = await fetchFn(url, { ...init, signal: AbortSignal.timeout(ms), redirect: 'error' });
1857
- // 204/304 carry no body — reading one would be a spec violation.
1858
- if (res.status === 204 || res.status === 304) {
1859
- return new Response(null, { status: res.status, statusText: res.statusText, headers: res.headers });
1860
- }
1861
- const body = await readBodyBounded(res, hubMaxResponseBytes(io), `${method} ${url}`);
1862
- return new Response(body, { status: res.status, statusText: res.statusText, headers: res.headers });
1729
+ credentialSlot(sel);
1863
1730
  }
1864
1731
  catch (e) {
1865
- const err = e;
1866
- if (err.name === 'TimeoutError' || err.name === 'AbortError') {
1867
- throw new CliError(`hub did not respond within ${ms / 1000}s (${method} ${url})`);
1868
- }
1869
- // `redirect: 'error'` makes undici reject a 3xx with a TypeError whose
1870
- // cause message is 'unexpected redirect' (verified on Node 22.22.3 and 26).
1871
- // Substring-match for slack against undici wording drift — if it ever stops
1872
- // matching, the raw TypeError still surfaces (fail-closed, just less pretty).
1873
- const cause = String(err.cause?.message ?? '');
1874
- if (err.name === 'TypeError' && cause.includes('unexpected redirect')) {
1875
- throw new CliError(`hub responded with a redirect — refusing to follow it (${method} ${url}); redirects are not part of the hub protocol`);
1876
- }
1877
- throw e;
1732
+ throw new CliError(`--as: ${e.message}`);
1878
1733
  }
1734
+ return sel;
1735
+ }
1736
+ function parseSlotArg(raw) {
1737
+ if (raw === undefined)
1738
+ return { principal: 'human' };
1739
+ if (raw === 'human')
1740
+ return { principal: 'human' };
1741
+ if (raw === 'agent')
1742
+ return { principal: 'agent' };
1743
+ if (raw.startsWith('agent:'))
1744
+ return { principal: 'agent', account: raw.slice('agent:'.length) };
1745
+ throw new CliError(`--as: unrecognized slot '${raw}' — expected 'human', 'agent', or 'agent:<account>'`);
1879
1746
  }
1880
1747
  /**
1881
- * Ensure an `oauth` credential's access token is fresh: if it expires within
1882
- * 60s, refresh once (grant_type=refresh_token) and persist the new token. No-op
1883
- * for `agent`/`oauth-pasted` credentials (they don't refresh). Returns the
1884
- * possibly-updated credential.
1748
+ * The "nothing stored here" message for a read that missed. It names the SLOT,
1749
+ * not just the origin — a credential may well exist for this hub under another
1750
+ * principal, and the fix is `--as`, not another `login`.
1885
1751
  */
1886
- async function ensureFreshOAuth(io, origin, cred, persist = true) {
1887
- if (cred.kind !== 'oauth')
1888
- return cred;
1889
- if (cred.expiresAt - nowMs() > 60_000)
1890
- return cred;
1891
- return refreshOAuth(io, origin, cred, persist);
1752
+ function emptySlotMessage(origin, slot) {
1753
+ const name = credentialSlot(slot);
1754
+ return `no stored credential for ${origin} in slot \`${name}\` — run \`owenloop login\` (or pass --as agent:<name>)`;
1892
1755
  }
1893
1756
  /**
1894
- * `persist` defaults to true — the normal case is refreshing an ALREADY
1895
- * stored, trusted credential (push/connect), where persisting immediately
1896
- * matters because refresh tokens can be single-use/rotating: losing the new
1897
- * one to a later crash would strand the user. `verifyCredential`'s login-time
1898
- * use passes `persist: false` — a not-yet-stored credential must never be
1899
- * written to disk/keychain before it is proven to work end to end (a 401 on
1900
- * the retry after this refresh still fails the overall login), matching the
1901
- * "never store an unverified token" rule enforced at every login call site.
1757
+ * Read the stored credential for `origin` in `slot`. Thin wrapper over the
1758
+ * shared `readStoredCredential` in `hub.ts` (the same implementation the public
1759
+ * package export uses), threading the CLI's injected `env`/`keychain`. Callers
1760
+ * pass a pre-normalized origin (`resolveHub` output); the wrapper's
1761
+ * normalization is idempotent, so CLI behavior is unchanged. REL-6 no-fallback
1762
+ * and corrupt-entry-as-absent semantics live in `hub.ts`.
1902
1763
  */
1903
- async function refreshOAuth(io, origin, cred, persist = true) {
1904
- const tokenEndpoint = await discoverTokenEndpoint(io, origin);
1905
- const body = new URLSearchParams({
1906
- grant_type: 'refresh_token',
1907
- refresh_token: cred.refreshToken,
1908
- client_id: cred.clientId,
1909
- });
1910
- const res = await hubFetch(io, tokenEndpoint, {
1911
- method: 'POST',
1912
- headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
1913
- body: body.toString(),
1914
- });
1915
- if (!res.ok) {
1916
- throw new CliError('credential expired and refresh failed — run `owenloop login`');
1917
- }
1918
- const json = (await res.json());
1919
- if (typeof json.access_token !== 'string') {
1920
- throw new CliError('credential expired and refresh returned no access token — run `owenloop login`');
1921
- }
1922
- const expiresIn = typeof json.expires_in === 'number' ? json.expires_in : 3600;
1923
- const refreshed = {
1924
- kind: 'oauth',
1925
- accessToken: json.access_token,
1926
- refreshToken: typeof json.refresh_token === 'string' ? json.refresh_token : cred.refreshToken,
1927
- expiresAt: nowMs() + expiresIn * 1000,
1928
- clientId: cred.clientId,
1929
- };
1930
- if (persist)
1931
- storeCredential(io, origin, refreshed);
1932
- return refreshed;
1933
- }
1934
- async function discoverMetadata(io, origin) {
1935
- const res = await hubFetch(io, resolveEndpoint(origin, '/.well-known/oauth-authorization-server'), {
1936
- headers: { Accept: 'application/json' },
1937
- });
1938
- if (!res.ok) {
1939
- throw new CliError(`could not read OAuth metadata from ${origin} (HTTP ${res.status})`);
1940
- }
1941
- return (await res.json());
1942
- }
1943
- async function discoverTokenEndpoint(io, origin) {
1944
- const meta = await discoverMetadata(io, origin);
1945
- if (!meta.token_endpoint)
1946
- throw new CliError(`hub ${origin} advertises no token_endpoint`);
1947
- return resolveEndpoint(origin, meta.token_endpoint);
1764
+ function readCredential(io, origin, slot) {
1765
+ return readStoredCredential(origin, { ...slot, env: io.env, keychain: io.keychain });
1948
1766
  }
1949
1767
  /**
1950
1768
  * GET `path` on `origin` with a bearer credential, refreshing an expiring
@@ -1954,13 +1772,13 @@ async function discoverTokenEndpoint(io, origin) {
1954
1772
  * semantics on the final status (a 401 after the retry, a non-2xx, etc. —
1955
1773
  * left to the caller since the wording differs slightly by context).
1956
1774
  */
1957
- async function authedGet(io, origin, cred, path, persist = true) {
1958
- let current = await ensureFreshOAuth(io, origin, cred, persist);
1775
+ async function authedGet(io, origin, slot, cred, path, persist = true) {
1776
+ let current = await ensureFreshOAuth(io, origin, slot, cred, persist);
1959
1777
  let res = await hubFetch(io, resolveEndpoint(origin, path), {
1960
1778
  headers: { Authorization: authHeader(current), Accept: 'application/json' },
1961
1779
  });
1962
1780
  if (res.status === 401 && current.kind === 'oauth') {
1963
- current = await refreshOAuth(io, origin, current, persist);
1781
+ current = await refreshOAuth(io, origin, slot, current, persist);
1964
1782
  res = await hubFetch(io, resolveEndpoint(origin, path), {
1965
1783
  headers: { Authorization: authHeader(current), Accept: 'application/json' },
1966
1784
  });
@@ -2002,8 +1820,8 @@ function assertAuthOk(res, cred, origin) {
2002
1820
  * verified here hasn't been stored yet at all; a refresh mid-verify must not
2003
1821
  * sneak a not-yet-proven credential onto disk ahead of the pass/fail verdict.
2004
1822
  */
2005
- async function verifyCredential(io, origin, cred, persist = true) {
2006
- const { res, cred: current } = await authedGet(io, origin, cred, '/api/whoami', persist);
1823
+ async function verifyCredential(io, origin, slot, cred, persist = true) {
1824
+ const { res, cred: current } = await authedGet(io, origin, slot, cred, '/api/whoami', persist);
2007
1825
  assertAuthOk(res, current, origin);
2008
1826
  const body = await res.json();
2009
1827
  return { cred: current, identity: asWhoami(body) };
@@ -2014,10 +1832,30 @@ async function verifyCredential(io, origin, cred, persist = true) {
2014
1832
  * `olp_`/`mcpat_` token from stdin instead (never argv). Either way the
2015
1833
  * credential is verified before it is stored, and stored in the OS keychain or
2016
1834
  * a 0600 file — never plaintext in the repo or `.env`.
1835
+ *
1836
+ * The SLOT the credential lands in follows the credential KIND, with `--as`
1837
+ * naming the agent account: a human credential (loopback `oauth`, or a pasted
1838
+ * `mcpat_`) writes `human`; a pasted `olp_` agent token writes
1839
+ * `agent:<account>` (`default` unless `--as agent:NAME`). A `--as` that
1840
+ * contradicts the credential kind is a usage error, not a silent coercion —
1841
+ * that is what keeps the agent slot holding agent keys.
1842
+ *
1843
+ * Refused outright while an external credential command is configured: that
1844
+ * command, not the local store, is what every read consults, so there is nothing
1845
+ * for `login` to usefully write. The check is here — before the "did a
1846
+ * credential already exist?" probe, which would otherwise RUN the command and
1847
+ * report its failure instead of this far more actionable reason — with
1848
+ * `storeCredential`'s own throw kept as the invariant backstop for any other
1849
+ * write path.
2017
1850
  */
2018
1851
  async function dispatchLogin(io, args) {
2019
1852
  const origin = resolveHub(io, args);
2020
- const existed = readCredential(io, origin) !== null;
1853
+ const asked = resolveSlot(args);
1854
+ const asGiven = last(args, 'as') !== undefined;
1855
+ if (externalCredentialCommand(io.env) !== undefined) {
1856
+ throw new CliError('an external credential command is configured (OWENLOOP_CREDENTIAL_COMMAND), so it — not the ' +
1857
+ 'local store — supplies credentials for this hub; unset it to use `owenloop login`');
1858
+ }
2021
1859
  if (flag(args, 'with-token')) {
2022
1860
  const readStdin = io.readStdin ?? defaultReadStdin;
2023
1861
  const token = (await readStdin()).trim();
@@ -2030,12 +1868,23 @@ async function dispatchLogin(io, args) {
2030
1868
  cred = { kind: 'oauth-pasted', accessToken: token };
2031
1869
  else
2032
1870
  throw new CliError('unrecognized token — expected an `olp_` agent token or an `mcpat_` access token');
2033
- const { identity } = await verifyCredential(io, origin, cred); // never store an unverified token
2034
- const storage = storeCredential(io, origin, cred);
1871
+ // Contradictions are usage errors, refused BEFORE any network call so
1872
+ // nothing is verified or stored under a slot the token does not belong in.
1873
+ if (cred.kind === 'agent' && asGiven && asked.principal === 'human') {
1874
+ throw new CliError('an `olp_` agent token cannot be stored in the `human` slot — drop `--as human`, or pass `--as agent[:<account>]`');
1875
+ }
1876
+ if (cred.kind !== 'agent' && asked.principal === 'agent') {
1877
+ throw new CliError(`a ${cred.kind} credential is a human credential and cannot be stored in the \`${credentialSlot(asked)}\` slot — drop \`--as\`, or paste an \`olp_\` agent token`);
1878
+ }
1879
+ const slot = cred.kind === 'agent' ? { principal: 'agent', ...(asked.principal === 'agent' && asked.account !== undefined ? { account: asked.account } : {}) } : { principal: 'human' };
1880
+ const existed = readCredential(io, origin, slot) !== null;
1881
+ const { identity } = await verifyCredential(io, origin, slot, cred); // never store an unverified token
1882
+ const storage = await storeCredential(io, origin, slot, cred);
2035
1883
  print(io, {
2036
1884
  ok: true,
2037
1885
  hub: origin,
2038
1886
  kind: cred.kind,
1887
+ slot: credentialSlot(slot),
2039
1888
  storage,
2040
1889
  replaced: existed,
2041
1890
  org: identity.orgName,
@@ -2045,6 +1894,42 @@ async function dispatchLogin(io, args) {
2045
1894
  });
2046
1895
  return 0;
2047
1896
  }
1897
+ // Loopback OAuth always yields a HUMAN credential — `--as agent*` on this
1898
+ // flow is a contradiction, refused before the browser is opened.
1899
+ if (asked.principal === 'agent') {
1900
+ throw new CliError(`the loopback OAuth login produces a human credential and cannot be stored in the \`${credentialSlot(asked)}\` slot — drop \`--as\`, or use \`login --with-token\` with an \`olp_\` agent token`);
1901
+ }
1902
+ const r = await runLoopbackOAuth(io, origin);
1903
+ print(io, {
1904
+ ok: true,
1905
+ hub: origin,
1906
+ kind: r.cred.kind,
1907
+ slot: credentialSlot({ principal: 'human' }),
1908
+ storage: r.storage,
1909
+ replaced: r.replaced,
1910
+ org: r.identity.orgName,
1911
+ orgId: r.identity.orgId,
1912
+ identity: r.identity.actor,
1913
+ ...(r.identity.email ? { email: r.identity.email } : {}),
1914
+ });
1915
+ return 0;
1916
+ }
1917
+ /**
1918
+ * The loopback OAuth auth-code + PKCE(S256) round-trip, extracted verbatim from
1919
+ * `dispatchLogin` so `setup`'s human-login gate (step 2) runs the exact same
1920
+ * flow — one implementation, one behavior. Always targets the **human** slot
1921
+ * (the only slot loopback OAuth can produce). Binds a single-use 127.0.0.1:0
1922
+ * catcher, discovers the hub's OAuth metadata, dynamically registers a client
1923
+ * for the concrete redirect URI, opens the browser, waits for the callback,
1924
+ * exchanges the code, verifies the resulting credential against `whoami`
1925
+ * (persist=false — an unverified token must never reach storage ahead of its
1926
+ * pass/fail verdict), then stores it. Returns whether a human credential was
1927
+ * already present (`replaced`), the stored credential, the verified identity,
1928
+ * and the storage backend actually used.
1929
+ */
1930
+ async function runLoopbackOAuth(io, origin) {
1931
+ const slot = { principal: 'human' };
1932
+ const existed = readCredential(io, origin, slot) !== null;
2048
1933
  // Loopback OAuth: bind the port FIRST (the service matches redirect URIs by
2049
1934
  // exact string — no RFC 8252 variable-port allowance — so the DCR must carry
2050
1935
  // the concrete 127.0.0.1:<port> callback).
@@ -2076,20 +1961,9 @@ async function dispatchLogin(io, args) {
2076
1961
  redirectUri,
2077
1962
  verifier,
2078
1963
  });
2079
- const { cred, identity } = await verifyCredential(io, origin, exchanged, false); // never store an unverified token
2080
- const storage = storeCredential(io, origin, cred);
2081
- print(io, {
2082
- ok: true,
2083
- hub: origin,
2084
- kind: cred.kind,
2085
- storage,
2086
- replaced: existed,
2087
- org: identity.orgName,
2088
- orgId: identity.orgId,
2089
- identity: identity.actor,
2090
- ...(identity.email ? { email: identity.email } : {}),
2091
- });
2092
- return 0;
1964
+ const { cred, identity } = await verifyCredential(io, origin, slot, exchanged, false); // never store an unverified token
1965
+ const storage = await storeCredential(io, origin, slot, cred);
1966
+ return { cred, identity, storage, replaced: existed };
2093
1967
  }
2094
1968
  finally {
2095
1969
  void server;
@@ -2220,13 +2094,21 @@ async function exchangeCode(io, origin, tokenEndpoint, p) {
2220
2094
  };
2221
2095
  }
2222
2096
  /**
2223
- * `owenloop logout` — delete the stored credential for a hub from both the
2224
- * keychain and the file store. Cheap; completes the credential lifecycle.
2097
+ * `owenloop logout` — delete the stored credential for a hub, in ONE slot
2098
+ * (`--as`, default `human`), from both the keychain and the file store. Cheap;
2099
+ * completes the credential lifecycle. Other slots for the same origin are left
2100
+ * alone: the keychain cannot enumerate its accounts, so a blanket
2101
+ * clear-everything is not implementable and is not faked.
2225
2102
  */
2226
2103
  async function dispatchLogout(io, args) {
2227
2104
  const origin = resolveHub(io, args);
2228
- const removed = deleteCredential(io, origin);
2229
- print(io, { ok: true, hub: origin, removed });
2105
+ const slot = resolveSlot(args);
2106
+ const removed = await deleteCredential(io, origin, slot);
2107
+ const slotName = credentialSlot(slot);
2108
+ if (!removed) {
2109
+ io.err(`no stored credential for ${origin} in slot \`${slotName}\` — another slot may hold one (see --as)`);
2110
+ }
2111
+ print(io, { ok: true, hub: origin, slot: slotName, removed });
2230
2112
  return 0;
2231
2113
  }
2232
2114
  /**
@@ -2239,10 +2121,11 @@ async function dispatchLogout(io, args) {
2239
2121
  */
2240
2122
  async function dispatchConnect(io, args) {
2241
2123
  const origin = resolveHub(io, args);
2242
- const cred = readCredential(io, origin);
2124
+ const slot = resolveSlot(args);
2125
+ const cred = readCredential(io, origin, slot);
2243
2126
  if (!cred)
2244
- throw new CliError(`no stored credential for ${origin} — run \`owenloop login\` first`);
2245
- const { identity } = await verifyCredential(io, origin, cred);
2127
+ throw new CliError(emptySlotMessage(origin, slot));
2128
+ const { identity } = await verifyCredential(io, origin, slot, cred);
2246
2129
  const path = hubBindingPath(io.cwd);
2247
2130
  const existing = readHubBinding(path);
2248
2131
  const switched = existing !== null && existing.hub !== origin;
@@ -2274,6 +2157,7 @@ async function dispatchPush(io, args) {
2274
2157
  const defsDir = last(args, 'defs') ?? io.env.OWENLOOP_DEFS ?? join(io.cwd, 'workflows');
2275
2158
  const dryRun = flag(args, 'dry-run');
2276
2159
  const force = flag(args, 'force');
2160
+ const slot = resolveSlot(args);
2277
2161
  // Require a project binding.
2278
2162
  const bindingPath = hubBindingPath(io.cwd);
2279
2163
  const binding = readHubBinding(bindingPath);
@@ -2301,9 +2185,9 @@ async function dispatchPush(io, args) {
2301
2185
  throw new CliError(`this project is bound to ${origin}, not ${requested} — re-run \`owenloop connect\` to rebind`);
2302
2186
  }
2303
2187
  }
2304
- let cred = readCredential(io, origin);
2188
+ let cred = readCredential(io, origin, slot);
2305
2189
  if (!cred)
2306
- throw new CliError(`no stored credential for ${origin} — run \`owenloop login\``);
2190
+ throw new CliError(emptySlotMessage(origin, slot));
2307
2191
  // Load defs (same machinery as lint/add).
2308
2192
  if (!existsSync(defsDir))
2309
2193
  throw new CliError(`defs directory not found: ${defsDir}`);
@@ -2337,10 +2221,10 @@ async function dispatchPush(io, args) {
2337
2221
  reasons.push(...validateDef(def).map((e) => `${def.name}: ${e}`));
2338
2222
  const report = modelCheck(def, { assumeProvided: true });
2339
2223
  const hasDefiniteDefect = report.invariantViolations.length > 0 ||
2340
- (!report.bounded && (report.deadlocks.length > 0 || report.stuck.length > 0));
2224
+ (!report.bounded && report.deadlocks.length > 0);
2341
2225
  if (hasDefiniteDefect) {
2342
2226
  reasons.push(`${def.name}: definite defects found (${report.invariantViolations.length} invariant violation(s), ` +
2343
- `${report.deadlocks.length} deadlock(s), ${report.stuck.length} stuck state(s))`);
2227
+ `${report.deadlocks.length} true deadlock(s))`);
2344
2228
  }
2345
2229
  }
2346
2230
  // Assemble the push candidates: verbatim source yaml + the server-canonical
@@ -2390,7 +2274,7 @@ async function dispatchPush(io, args) {
2390
2274
  }
2391
2275
  // Fetch the server's own list once — the diff source of truth. Always
2392
2276
  // fetched, even under --force, so the new/changed labels stay accurate.
2393
- const { res: listRes, cred: listCred } = await authedGet(io, origin, cred, '/api/workflows');
2277
+ const { res: listRes, cred: listCred } = await authedGet(io, origin, slot, cred, '/api/workflows');
2394
2278
  assertAuthOk(listRes, listCred, origin);
2395
2279
  cred = listCred;
2396
2280
  let serverMap;
@@ -2420,7 +2304,7 @@ async function dispatchPush(io, args) {
2420
2304
  return 0;
2421
2305
  }
2422
2306
  // Refresh an expiring oauth token once up front (per-request 401 refresh below covers mid-batch expiry).
2423
- cred = await ensureFreshOAuth(io, origin, cred);
2307
+ cred = await ensureFreshOAuth(io, origin, slot, cred);
2424
2308
  const pushedNames = [];
2425
2309
  const noopNames = [];
2426
2310
  const failed = [];
@@ -2431,7 +2315,7 @@ async function dispatchPush(io, args) {
2431
2315
  try {
2432
2316
  let res = await createWorkflowRequest(io, origin, cred, c.yaml);
2433
2317
  if (res.status === 401 && cred.kind === 'oauth') {
2434
- cred = await refreshOAuth(io, origin, cred);
2318
+ cred = await refreshOAuth(io, origin, slot, cred);
2435
2319
  res = await createWorkflowRequest(io, origin, cred, c.yaml);
2436
2320
  }
2437
2321
  if (res.status === 401) {
@@ -2499,6 +2383,16 @@ async function dispatchPush(io, args) {
2499
2383
  });
2500
2384
  return failed.length === 0 ? 0 : 1;
2501
2385
  }
2386
+ /**
2387
+ * `owenloop mcp` — serve the human control plane to a local MCP host over stdio.
2388
+ * A thin adapter: read the optional `--hub <url>` flag and hand `io` (which
2389
+ * satisfies the module's `McpIo`) to `runMcpCommand`, which resolves the origin,
2390
+ * builds the tool list, and pumps stdin until EOF. All the logic lives in
2391
+ * `src/mcp/serve.ts`; this stays a two-line dispatch like every other verb.
2392
+ */
2393
+ async function dispatchMcp(io, args) {
2394
+ return runMcpCommand(io, { hubFlag: last(args, 'hub') });
2395
+ }
2502
2396
  function createWorkflowRequest(io, origin, cred, yaml) {
2503
2397
  return hubFetch(io, resolveEndpoint(origin, '/api/create_workflow'), {
2504
2398
  method: 'POST',
@@ -2510,6 +2404,792 @@ function createWorkflowRequest(io, origin, cred, yaml) {
2510
2404
  body: JSON.stringify({ yaml }),
2511
2405
  });
2512
2406
  }
2407
+ /**
2408
+ * Resolve the hub `agent new` mints on: `--hub <origin>` (normalized via
2409
+ * `normalizeOrigin`) → else the ONE hub the credential FILE knows → else a
2410
+ * `CliError` with `exitCode: 2` naming both remedies.
2411
+ *
2412
+ * Deliberately NOT `resolveHub` (`--hub → OWENLOOP_HUB → DEFAULT_HUB`): silently
2413
+ * defaulting a MINT to the production hub while the user is logged into a dev hub
2414
+ * would mint on the wrong org, and a mint is not undone by a retry. `OWENLOOP_HUB`
2415
+ * is intentionally excluded so this stays in parity with O2's `owenloop mcp`.
2416
+ *
2417
+ * `listStoredHubOrigins` is backend-aware (shared with O2's `owenloop mcp`): only
2418
+ * the FILE backend can enumerate, so it returns `null` on a keychain- or
2419
+ * external-command-backed machine — those must pass `--hub`. A file-backed store
2420
+ * returns the origins with a valid `human` slot: `[]` (log in first), exactly one
2421
+ * (used automatically), or more than one (the non-secret origin keys are listed
2422
+ * back so the user can pick).
2423
+ */
2424
+ function resolveAgentHub(io, args) {
2425
+ const flagVal = last(args, 'hub');
2426
+ if (flagVal !== undefined) {
2427
+ try {
2428
+ return normalizeOrigin(flagVal);
2429
+ }
2430
+ catch (e) {
2431
+ throw new CliError(e.message);
2432
+ }
2433
+ }
2434
+ const origins = listStoredHubOrigins(io.env, io.keychain);
2435
+ if (origins === null) {
2436
+ const backend = credentialBackend(io.env, io.keychain);
2437
+ const which = backend.kind === 'external' ? 'external-command' : 'keychain';
2438
+ throw new CliError(`cannot determine which hub to mint on — the ${which} credential store cannot be enumerated; ` +
2439
+ 'pass --hub <origin>', { exitCode: 2 });
2440
+ }
2441
+ if (origins.length === 1)
2442
+ return origins[0];
2443
+ throw new CliError('cannot determine which hub to mint on — pass --hub <origin>, or log in to exactly one hub first ' +
2444
+ '(owenloop login --hub <origin>)' +
2445
+ (origins.length > 1 ? `; stored hubs: ${origins.join(', ')}` : ''), { exitCode: 2 });
2446
+ }
2447
+ /**
2448
+ * `owenloop agent new <name>` — mint a new agent identity on the hub and store
2449
+ * its `olp_` token in slot `agent:<name>`.
2450
+ *
2451
+ * **Secret hygiene (identity model §6, "rule of gates"):** the minted token goes
2452
+ * process→store ONLY — it never appears on stdout, stderr, in an error, or in a
2453
+ * log. `mintAgentCredential` (credentials.ts) owns the token end to end and
2454
+ * returns none of it; the confirmation printed here is built from an explicit
2455
+ * WHITELIST of non-secret fields (name, pools, storage backend, revocation ids).
2456
+ *
2457
+ * Ordering is load-bearing (PR #69 lesson, carried by `mintAgentCredential`): the
2458
+ * client-side name validation and the external-command refusal both run BEFORE
2459
+ * any network call, so a refusal that would make the credential unstorable never
2460
+ * mints a server-side token first — minting then failing to store would burn the
2461
+ * agent name permanently.
2462
+ *
2463
+ * Exit codes: 0 ok; 1 generic failure (invalid name, name taken, pool/shape
2464
+ * rejection, network timeout, minted-but-unstored); 2 the hub is unresolvable;
2465
+ * 3 the human credential is absent or irrecoverable (remedy names
2466
+ * `owenloop login --hub <origin>`).
2467
+ *
2468
+ * A subcommand switch (`new` only today) leaves room for `agent list`/etc. later.
2469
+ */
2470
+ async function dispatchAgent(io, args) {
2471
+ const sub = args.positionals[1];
2472
+ if (sub !== 'new') {
2473
+ throw new CliError(`unknown agent subcommand '${sub ?? ''}' — expected: agent new <name>`);
2474
+ }
2475
+ const name = args.positionals[2];
2476
+ if (name === undefined) {
2477
+ throw new CliError('missing required argument: <name> (usage: owenloop agent new <name> [--pools a,b] [--hub <url>])');
2478
+ }
2479
+ // Validate the agent name eagerly — before any I/O — with the store's own
2480
+ // wording, so a bad name never reaches the network or the store.
2481
+ try {
2482
+ credentialSlot({ principal: 'agent', account: name });
2483
+ }
2484
+ catch (e) {
2485
+ throw new CliError(`agent new: invalid agent name — ${e.message}`);
2486
+ }
2487
+ // --pools: split on `,`, trim, drop empties. Absent → undefined (key omitted
2488
+ // from the request; the server then defaults to the minter's personal pool).
2489
+ // Present but empty (`--pools ""` / `--pools ,`) → usage error, before any I/O.
2490
+ // No client-side pool-name validation — the server is the enforcement of record.
2491
+ const poolsRaw = last(args, 'pools');
2492
+ let pools;
2493
+ if (poolsRaw !== undefined) {
2494
+ pools = poolsRaw
2495
+ .split(',')
2496
+ .map((p) => p.trim())
2497
+ .filter((p) => p !== '');
2498
+ if (pools.length === 0) {
2499
+ throw new CliError('--pools requires at least one pool name');
2500
+ }
2501
+ }
2502
+ // Refuse an external-command setup at the TOP of the dispatcher — before the
2503
+ // human-credential read (which would otherwise RUN the command) and before any
2504
+ // network call (PR #69 lesson; `mintAgentCredential` carries the same guard as
2505
+ // a library backstop). Refusing only at store time would mint a server-side
2506
+ // token we could never store locally, permanently burning the agent name.
2507
+ if (externalCredentialCommand(io.env) !== undefined) {
2508
+ throw new CliError('an external credential command is configured (OWENLOOP_CREDENTIAL_COMMAND), so it — not the ' +
2509
+ 'local store — supplies credentials for this hub; unset it to use `owenloop login`');
2510
+ }
2511
+ const origin = resolveAgentHub(io, args);
2512
+ // The human bearer for the resolved origin. Absent → exit 3 with the verbatim
2513
+ // remedy the brief mandates.
2514
+ const cred = readCredential(io, origin, { principal: 'human' });
2515
+ if (cred === null) {
2516
+ throw new CliError(`no human credential for ${origin} — run: owenloop login --hub ${origin}`, { exitCode: 3 });
2517
+ }
2518
+ let result;
2519
+ try {
2520
+ result = await mintAgentCredential(io, origin, { principal: 'human' }, cred, { name, pools });
2521
+ }
2522
+ catch (e) {
2523
+ // A refresh-failure-family error (the human oauth is irrecoverable, or a 401
2524
+ // survived the refresh-and-retry) is exit 3 with the login remedy; every
2525
+ // other CliError propagates as-is — a network timeout stays exit 1, because a
2526
+ // flaky network is not an irrecoverable credential.
2527
+ if (e instanceof CliError && /run `owenloop login`/.test(e.message)) {
2528
+ throw new CliError(`${e.message} — run: owenloop login --hub ${origin}`, { exitCode: 3 });
2529
+ }
2530
+ throw e;
2531
+ }
2532
+ // Confirmation: whitelisted, non-secret fields ONLY. `text`/`token` are
2533
+ // structurally absent from `result`, so there is nothing here to leak.
2534
+ print(io, {
2535
+ ok: true,
2536
+ hub: origin,
2537
+ name,
2538
+ slot: `agent:${name}`,
2539
+ pools: result.pools,
2540
+ scopes: ['work'],
2541
+ storage: result.storage,
2542
+ agentId: result.agentId,
2543
+ tokenId: result.id,
2544
+ });
2545
+ return 0;
2546
+ }
2547
+ /**
2548
+ * The plugin check is rendered but NON-FATAL while the marketplace is not yet
2549
+ * fetchably published (the brief's open question): `doctor` shows ✓/✗ but the
2550
+ * plugin never flips the exit code, and `setup` PRINTS install instructions
2551
+ * instead of failing. Flip to `true` once the shell-out install lands.
2552
+ */
2553
+ const PLUGIN_CHECK_FATAL = false;
2554
+ /**
2555
+ * Resolve the hub `setup`/`doctor` target. Deviates from `resolveAgentHub` in
2556
+ * exactly ONE way (documented in the plan §4): a fresh machine — which is the
2557
+ * Flow A mainline — has NO stored hub, so instead of `resolveAgentHub`'s exit-2
2558
+ * it falls back to the production `DEFAULT_HUB` with a printed notice. The
2559
+ * wrong-hub-mint risk `resolveAgentHub` guards against does not apply: the mint
2560
+ * happens only AFTER the human logs in through this hub's own browser consent,
2561
+ * and the target line is printed first.
2562
+ *
2563
+ * - `--hub <origin>` → `normalizeOrigin`.
2564
+ * - else `listStoredHubOrigins`: exactly one → use it; more than one → `CliError`
2565
+ * exitCode 2 listing them; zero or `null` (keychain/external cannot enumerate)
2566
+ * → `DEFAULT_HUB` + notice.
2567
+ *
2568
+ * `OWENLOOP_HUB` stays excluded (O2/O3 parity). Shared by both commands so they
2569
+ * agree on the target.
2570
+ */
2571
+ function resolveSetupHub(io, args) {
2572
+ const flagVal = last(args, 'hub');
2573
+ if (flagVal !== undefined) {
2574
+ try {
2575
+ return normalizeOrigin(flagVal);
2576
+ }
2577
+ catch (e) {
2578
+ throw new CliError(e.message);
2579
+ }
2580
+ }
2581
+ const origins = listStoredHubOrigins(io.env, io.keychain);
2582
+ if (origins !== null && origins.length === 1)
2583
+ return origins[0];
2584
+ if (origins !== null && origins.length > 1) {
2585
+ throw new CliError(`more than one hub is configured on this machine — pass --hub <origin> to pick one; stored hubs: ${origins.join(', ')}`, { exitCode: 2 });
2586
+ }
2587
+ io.err(`targeting ${DEFAULT_HUB} (pass --hub to override)`);
2588
+ return DEFAULT_HUB;
2589
+ }
2590
+ /**
2591
+ * Is `cmd` an executable file on `env.PATH`? A pure PATH scan (no exec), so it is
2592
+ * hermetic-testable by pointing `PATH` at a fixture dir with a chmod +x stub.
2593
+ * A directory entry, a non-executable file, or an unreadable dir is skipped.
2594
+ */
2595
+ function commandOnPath(env, cmd) {
2596
+ const path = env.PATH;
2597
+ if (!path)
2598
+ return false;
2599
+ for (const dir of path.split(delimiter)) {
2600
+ if (dir === '')
2601
+ continue;
2602
+ const full = join(dir, cmd);
2603
+ try {
2604
+ const st = statSync(full);
2605
+ if (st.isFile() && (st.mode & 0o111) !== 0)
2606
+ return true;
2607
+ }
2608
+ catch {
2609
+ // not here — keep scanning
2610
+ }
2611
+ }
2612
+ return false;
2613
+ }
2614
+ /**
2615
+ * Coerce a raw string (a hostname) into a valid agent account name, or `''` when
2616
+ * nothing usable survives. Lowercase; drop every character outside the account
2617
+ * body class `[a-z0-9._-]`; strip leading non-alphanumerics (the account MUST
2618
+ * start alphanumeric); clamp to 64 chars. A suggestion only — never parsed or
2619
+ * matched (§2); the user may accept it or type any valid label.
2620
+ */
2621
+ export function sanitizeAgentName(raw) {
2622
+ let s = raw.toLowerCase().replace(/[^a-z0-9._-]/g, '');
2623
+ s = s.replace(/^[^a-z0-9]+/, '');
2624
+ if (s.length > 64)
2625
+ s = s.slice(0, 64);
2626
+ return s;
2627
+ }
2628
+ /**
2629
+ * The identity's last-active instant in epoch-ms: `max` of its two non-null
2630
+ * timestamps (`lastUsedAt`, the rekey-surviving token-level max; `lastContactAt`,
2631
+ * the identity-level any-protocol contact), or `null` when both are absent. Both
2632
+ * recording paths are monotone, so `max` is the correct "most recent activity".
2633
+ */
2634
+ export function lastActiveMs(identity) {
2635
+ const c = identity.lastContactAt;
2636
+ const u = identity.lastUsedAt;
2637
+ if (c === null)
2638
+ return u;
2639
+ if (u === null)
2640
+ return c;
2641
+ return Math.max(c, u);
2642
+ }
2643
+ /**
2644
+ * Render an elapsed-time delta (ms) as a short relative string: `just now`,
2645
+ * `<n>m ago`, `<n>h ago`, `<n>d ago`. A `null` delta (no recorded activity)
2646
+ * renders `never`. Negative deltas (clock skew) clamp to `just now`.
2647
+ */
2648
+ export function formatLastActive(deltaMs) {
2649
+ if (deltaMs === null)
2650
+ return 'never';
2651
+ const ms = Math.max(0, deltaMs);
2652
+ const min = Math.floor(ms / 60_000);
2653
+ if (min < 1)
2654
+ return 'just now';
2655
+ if (min < 60)
2656
+ return `${min}m ago`;
2657
+ const hr = Math.floor(min / 60);
2658
+ if (hr < 24)
2659
+ return `${hr}h ago`;
2660
+ return `${Math.floor(hr / 24)}d ago`;
2661
+ }
2662
+ /**
2663
+ * File-backend agent account names stored for `origin`, or `null` when the
2664
+ * backend cannot enumerate (keychain/external) — mirrors `listStoredHubOrigins`'
2665
+ * backend-awareness. The keychain interface is get/set/delete only, so the real
2666
+ * agent probe on a keychain machine is the identity-name-keyed reads in step 3.
2667
+ */
2668
+ function enumerateAgentAccounts(io, origin) {
2669
+ if (credentialBackend(io.env, io.keychain).kind !== 'file')
2670
+ return null;
2671
+ const file = readCredentialFile(credentialFilePath(io.env));
2672
+ return Object.keys(file.hubs[origin] ?? {})
2673
+ .filter((k) => k.startsWith('agent:'))
2674
+ .map((k) => k.slice('agent:'.length));
2675
+ }
2676
+ /**
2677
+ * Probe local agent slots (`names`) for one that verifies live against the hub's
2678
+ * `whoami`. Reads each `agent:<name>` slot; a hit is verified with `authedGet`
2679
+ * (ensureFreshOAuth no-ops on the `agent` kind; a 401 = revoked → `sawRevoked`).
2680
+ * Prefers a slot whose `whoami actor.id` matches a listed identity id; falls back
2681
+ * to the first otherwise-verified slot (id/name mismatch is tolerated, never a
2682
+ * hard fail — see plan §5). Never a write.
2683
+ */
2684
+ async function probeAgentSlots(io, origin, names, identities) {
2685
+ let verified = null;
2686
+ let sawSlot = false;
2687
+ let sawRevoked = false;
2688
+ for (const name of names) {
2689
+ const cred = readCredential(io, origin, { principal: 'agent', account: name });
2690
+ if (cred === null)
2691
+ continue;
2692
+ sawSlot = true;
2693
+ let res;
2694
+ try {
2695
+ ({ res } = await authedGet(io, origin, { principal: 'agent', account: name }, cred, '/api/whoami'));
2696
+ }
2697
+ catch {
2698
+ continue;
2699
+ }
2700
+ if (res.status === 401) {
2701
+ sawRevoked = true;
2702
+ continue;
2703
+ }
2704
+ if (!res.ok)
2705
+ continue;
2706
+ let actorId = '';
2707
+ try {
2708
+ actorId = asWhoami(await res.json()).actor.id;
2709
+ }
2710
+ catch {
2711
+ continue;
2712
+ }
2713
+ const byId = identities.find((i) => i.id === actorId);
2714
+ const byName = identities.find((i) => i.name === name);
2715
+ const va = { name, actorId, identity: byId ?? byName };
2716
+ if (byId)
2717
+ return { verified: va, sawSlot, sawRevoked };
2718
+ if (verified === null)
2719
+ verified = va;
2720
+ }
2721
+ return { verified, sawSlot, sawRevoked };
2722
+ }
2723
+ /**
2724
+ * The interactive prompt for setup, or the non-interactive guard. Returns
2725
+ * `io.prompt` when injected; else, when stdin is a real TTY, the default
2726
+ * readline prompt; else a `CliError` naming the two bypass flags — thrown BEFORE
2727
+ * any mutation so a scripted/piped run never blocks or half-applies.
2728
+ */
2729
+ function requirePrompt(io) {
2730
+ if (io.prompt)
2731
+ return io.prompt;
2732
+ if (process.stdin.isTTY)
2733
+ return defaultPrompt;
2734
+ throw new CliError('setup needs to ask which agent to use, but stdin is not interactive — pass ' +
2735
+ '--new-agent <name> to create a new agent, or --replace-agent <name> to replace an existing one');
2736
+ }
2737
+ /**
2738
+ * Prompt for an agent name (Flow A). Offers `sanitizeAgentName(hostname())` as a
2739
+ * prefill an empty answer accepts; an invalid answer re-prompts once, then a
2740
+ * `CliError`. The name is a SUGGESTION only — any valid label is accepted.
2741
+ */
2742
+ async function promptAgentName(io) {
2743
+ const prompt = requirePrompt(io);
2744
+ const prefill = sanitizeAgentName(hostname());
2745
+ const question = prefill ? `Name this agent [${prefill}]: ` : 'Name this agent: ';
2746
+ for (let attempt = 0; attempt < 2; attempt++) {
2747
+ const raw = (await prompt(question)).trim();
2748
+ const answer = raw === '' ? prefill : raw;
2749
+ if (answer === '') {
2750
+ io.err('an agent name is required');
2751
+ continue;
2752
+ }
2753
+ try {
2754
+ credentialSlot({ principal: 'agent', account: answer });
2755
+ return answer;
2756
+ }
2757
+ catch {
2758
+ io.err(`invalid agent name '${answer}' — expected 1-64 chars matching [A-Za-z0-9][A-Za-z0-9._-]*`);
2759
+ }
2760
+ }
2761
+ throw new CliError('no valid agent name provided');
2762
+ }
2763
+ /**
2764
+ * Render the succession question (Flow B) and read a choice. The framing
2765
+ * sentences are VERBATIM from the model doc; the radio glyphs become numbered
2766
+ * terminal choices (the honest line-input adaptation). `[1]` = new installation;
2767
+ * `[k]` = replace the (k-2)th non-disabled identity. Each Replace line shows the
2768
+ * name, `last active <relative>`, and pools. Invalid input re-prompts once, then
2769
+ * a `CliError`.
2770
+ */
2771
+ async function promptSuccession(io, identities) {
2772
+ const prompt = requirePrompt(io);
2773
+ const candidates = identities.filter((i) => !i.disabled);
2774
+ const now = nowMs();
2775
+ const lines = [
2776
+ 'Is this a new installation, or does it replace an existing one?',
2777
+ '',
2778
+ ' [1] New installation → create a new agent',
2779
+ ];
2780
+ candidates.forEach((id, i) => {
2781
+ const active = lastActiveMs(id);
2782
+ const rel = formatLastActive(active === null ? null : now - active);
2783
+ const pools = id.pools.length ? id.pools.join(', ') : '(none)';
2784
+ lines.push(` [${i + 2}] Replace: ${id.name} last active ${rel} · pools: ${pools}`);
2785
+ });
2786
+ lines.push('');
2787
+ lines.push('⚠ "Replace" revokes that agent\'s current credential. If it is still');
2788
+ lines.push(' running somewhere, it will be disconnected there.');
2789
+ lines.push('');
2790
+ const max = candidates.length + 1;
2791
+ const question = `${lines.join('\n')}\nChoose [1-${max}]: `;
2792
+ for (let attempt = 0; attempt < 2; attempt++) {
2793
+ const raw = (await prompt(attempt === 0 ? question : `Choose [1-${max}]: `)).trim();
2794
+ const n = Number(raw);
2795
+ if (Number.isInteger(n) && n >= 1 && n <= max) {
2796
+ if (n === 1)
2797
+ return { kind: 'new' };
2798
+ return { kind: 'replace', identity: candidates[n - 2] };
2799
+ }
2800
+ io.err(`please enter a number between 1 and ${max}`);
2801
+ }
2802
+ throw new CliError('no valid choice provided');
2803
+ }
2804
+ /** Probe the Claude Code plugin state: is `claude` on PATH, and does `plugin list` mention owenloop? */
2805
+ function probePlugin(io) {
2806
+ if (!commandOnPath(io.env, 'claude'))
2807
+ return { claudeFound: false, installed: false };
2808
+ const run = io.runCommand ?? defaultRunCommand;
2809
+ try {
2810
+ return { claudeFound: true, installed: run('claude', ['plugin', 'list']).stdout.includes('owenloop') };
2811
+ }
2812
+ catch {
2813
+ return { claudeFound: true, installed: false };
2814
+ }
2815
+ }
2816
+ /**
2817
+ * The plugin ACT step. While the marketplace is unpublished this PRINTS the
2818
+ * manual install instructions instead of shelling out — the single seam a real
2819
+ * shell-out install would replace later. Never fails setup.
2820
+ */
2821
+ function installPluginStep(io, state) {
2822
+ if (!state.claudeFound)
2823
+ io.err('Claude Code (claude) not detected on PATH.');
2824
+ io.err('Claude Code plugin — install manually:');
2825
+ io.err(' claude plugin marketplace add owenloop');
2826
+ io.err(' claude plugin install owenloop@owenloop');
2827
+ }
2828
+ /**
2829
+ * `owenloop setup` — converge this machine's install in six probe→(skip|act)
2830
+ * steps, idempotently: a second run performs ZERO writes (no store mutation, no
2831
+ * settings write, no browser, no mint/rekey/register POST). Each ACT is reached
2832
+ * only through its probe failing.
2833
+ *
2834
+ * Flags: `--hub <url>`; mutually-exclusive `--new-agent <name>` / `--replace-agent
2835
+ * <name>` (bypass the interactive agent branches); `--pools <a,b>` (mint only —
2836
+ * a usage error with `--replace-agent`, which preserves pools).
2837
+ *
2838
+ * Exit: 0 when every step ended skipped/done/noted AND doctor's core (non-plugin)
2839
+ * checks pass; 1 otherwise. Any hard failure throws (mapped to an exit code by
2840
+ * `mainAsync`).
2841
+ */
2842
+ async function dispatchSetup(io, args) {
2843
+ // --- usage validation, before any I/O ---
2844
+ const newAgent = last(args, 'new-agent');
2845
+ const replaceAgent = last(args, 'replace-agent');
2846
+ if (newAgent !== undefined && replaceAgent !== undefined) {
2847
+ throw new CliError('pass at most one of --new-agent or --replace-agent, not both');
2848
+ }
2849
+ const poolsRaw = last(args, 'pools');
2850
+ let pools;
2851
+ if (poolsRaw !== undefined) {
2852
+ pools = poolsRaw
2853
+ .split(',')
2854
+ .map((p) => p.trim())
2855
+ .filter((p) => p !== '');
2856
+ if (pools.length === 0)
2857
+ throw new CliError('--pools requires at least one pool name');
2858
+ }
2859
+ if (replaceAgent !== undefined && pools !== undefined) {
2860
+ throw new CliError("--pools cannot be combined with --replace-agent — re-keying preserves the agent's pools (manage pools in the console)");
2861
+ }
2862
+ for (const [flagName, val] of [
2863
+ ['--new-agent', newAgent],
2864
+ ['--replace-agent', replaceAgent],
2865
+ ]) {
2866
+ if (val !== undefined) {
2867
+ try {
2868
+ credentialSlot({ principal: 'agent', account: val });
2869
+ }
2870
+ catch (e) {
2871
+ throw new CliError(`${flagName}: invalid agent name — ${e.message}`);
2872
+ }
2873
+ }
2874
+ }
2875
+ // Symmetric with `dispatchLogin`: when an external credential command supplies
2876
+ // this hub's credentials, the local store is never consulted, so setup's
2877
+ // human-login step (step 2, which opens the loopback OAuth browser) and its
2878
+ // agent mint would strand keys nobody reads. Refuse BEFORE any browser opens —
2879
+ // otherwise setup completes the full OAuth round-trip only to fail at
2880
+ // storeCredential's backstop, wasting a browser trip on the flagship command.
2881
+ if (externalCredentialCommand(io.env) !== undefined) {
2882
+ throw new CliError('an external credential command is configured (OWENLOOP_CREDENTIAL_COMMAND), so it — not the ' +
2883
+ 'local store — supplies credentials for this hub; unset it to use `owenloop login`');
2884
+ }
2885
+ const origin = resolveSetupHub(io, args);
2886
+ const steps = [];
2887
+ // --- [1/6] inspect: zero writes, best-effort probes ---
2888
+ io.err('[1/6] inspect');
2889
+ io.err(` human credential: ${readCredential(io, origin, { principal: 'human' }) !== null ? 'present' : 'none — will log in'}`);
2890
+ const inspectSettingsPath = owenworkSettingsPath(io.env);
2891
+ let settingsNote;
2892
+ if (!existsSync(inspectSettingsPath)) {
2893
+ settingsNote = 'missing — will write';
2894
+ }
2895
+ else {
2896
+ try {
2897
+ const raw = readOwenworkSettingsRaw(inspectSettingsPath);
2898
+ const found = raw && typeof raw.hubOrigin === 'string' ? raw.hubOrigin : undefined;
2899
+ settingsNote = found === origin ? `hubOrigin already ${origin}` : `hubOrigin ${found ?? '(unset)'} — will update`;
2900
+ }
2901
+ catch {
2902
+ settingsNote = 'present but unreadable — step 4 will error if still corrupt';
2903
+ }
2904
+ }
2905
+ io.err(` owenwork settings: ${settingsNote}`);
2906
+ io.err(` claude on PATH: ${commandOnPath(io.env, 'claude') ? 'yes' : 'no'}`);
2907
+ const inspectAccts = enumerateAgentAccounts(io, origin);
2908
+ io.err(inspectAccts === null
2909
+ ? ' agent slots: checked in step 3'
2910
+ : ` agent slots: ${inspectAccts.length ? inspectAccts.map((a) => `agent:${a}`).join(', ') : 'none'}`);
2911
+ steps.push({ step: 'inspect', action: 'done', detail: 'probed local state' });
2912
+ // --- [2/6] human login: the hard gate that makes step 3's rekey legal ---
2913
+ io.err('[2/6] human login');
2914
+ let humanCred = readCredential(io, origin, { principal: 'human' });
2915
+ let humanIdentity;
2916
+ if (humanCred !== null) {
2917
+ try {
2918
+ const verified = await verifyCredential(io, origin, { principal: 'human' }, humanCred);
2919
+ humanCred = verified.cred;
2920
+ humanIdentity = verified.identity;
2921
+ io.err(`✓ human: ${humanIdentity.email ?? humanIdentity.actor.id} @ ${humanIdentity.orgName}`);
2922
+ steps.push({ step: 'human login', action: 'skipped', detail: `${humanIdentity.email ?? humanIdentity.actor.id} @ ${humanIdentity.orgName}` });
2923
+ }
2924
+ catch (e) {
2925
+ if (!(e instanceof CliError))
2926
+ throw e; // a genuine non-credential error is not a re-login trigger
2927
+ const r = await runLoopbackOAuth(io, origin);
2928
+ humanCred = r.cred;
2929
+ humanIdentity = r.identity;
2930
+ io.err(`✓ human: signed in as ${humanIdentity.email ?? humanIdentity.actor.id} @ ${humanIdentity.orgName}`);
2931
+ steps.push({ step: 'human login', action: 'done', detail: `signed in as ${humanIdentity.email ?? humanIdentity.actor.id}` });
2932
+ }
2933
+ }
2934
+ else {
2935
+ const r = await runLoopbackOAuth(io, origin);
2936
+ humanCred = r.cred;
2937
+ humanIdentity = r.identity;
2938
+ io.err(`✓ human: signed in as ${humanIdentity.email ?? humanIdentity.actor.id} @ ${humanIdentity.orgName}`);
2939
+ steps.push({ step: 'human login', action: 'done', detail: `signed in as ${humanIdentity.email ?? humanIdentity.actor.id}` });
2940
+ }
2941
+ // --- [3/6] agent ---
2942
+ io.err('[3/6] agent');
2943
+ const { res: idRes } = await authedGet(io, origin, { principal: 'human' }, humanCred, '/api/agent_identities');
2944
+ if (idRes.status === 403) {
2945
+ throw new CliError('setup needs an admin credential to manage agents (hub returned 403)');
2946
+ }
2947
+ assertAuthOk(idRes, humanCred, origin);
2948
+ const identities = asAgentIdentities(await idRes.json());
2949
+ const candidateNames = new Set(identities.map((i) => i.name));
2950
+ candidateNames.add('default');
2951
+ const probe = await probeAgentSlots(io, origin, [...candidateNames], identities);
2952
+ let agentAccount;
2953
+ if (probe.verified !== null) {
2954
+ agentAccount = probe.verified.name;
2955
+ const poolsStr = probe.verified.identity ? ` (pools: ${probe.verified.identity.pools.join(', ') || 'none'})` : '';
2956
+ io.err(`✓ agent: ${agentAccount}${poolsStr}`);
2957
+ steps.push({ step: 'agent', action: 'skipped', detail: `agent:${agentAccount} verified` });
2958
+ }
2959
+ else {
2960
+ // ACT — resolve which agent to connect, then mint or rekey.
2961
+ let action;
2962
+ if (newAgent !== undefined) {
2963
+ action = { mode: 'mint', name: newAgent };
2964
+ }
2965
+ else if (replaceAgent !== undefined) {
2966
+ const target = identities.find((i) => i.name === replaceAgent);
2967
+ if (target === undefined) {
2968
+ throw new CliError(`no agent named '${replaceAgent}' on ${origin} — available: ${identities.map((i) => i.name).join(', ') || '(none)'}`);
2969
+ }
2970
+ action = { mode: 'rekey', agentId: target.id, name: replaceAgent };
2971
+ }
2972
+ else if (identities.length === 0) {
2973
+ // Flow A — fresh org, prompt for a name.
2974
+ action = { mode: 'mint', name: await promptAgentName(io) };
2975
+ }
2976
+ else {
2977
+ // Flow B — succession.
2978
+ const choice = await promptSuccession(io, identities);
2979
+ action =
2980
+ choice.kind === 'new'
2981
+ ? { mode: 'mint', name: await promptAgentName(io) }
2982
+ : { mode: 'rekey', agentId: choice.identity.id, name: choice.identity.name };
2983
+ }
2984
+ if (action.mode === 'mint') {
2985
+ const result = await mintAgentCredential(io, origin, { principal: 'human' }, humanCred, { name: action.name, pools });
2986
+ agentAccount = action.name;
2987
+ io.err(`✓ agent: minted agent:${agentAccount} (pools: ${result.pools.join(', ') || 'none'})`);
2988
+ steps.push({ step: 'agent', action: 'done', detail: `minted agent:${agentAccount}` });
2989
+ }
2990
+ else {
2991
+ const result = await rekeyAgentCredential(io, origin, { principal: 'human' }, humanCred, { agentId: action.agentId, name: action.name });
2992
+ agentAccount = action.name;
2993
+ io.err(`✓ agent: re-keyed agent:${agentAccount} (revoked ${result.revokedTokenIds.length} old token(s))`);
2994
+ steps.push({ step: 'agent', action: 'done', detail: `re-keyed agent:${agentAccount}` });
2995
+ }
2996
+ }
2997
+ // --- [4/6] owenwork settings ---
2998
+ io.err('[4/6] owenwork settings');
2999
+ const settingsPath = owenworkSettingsPath(io.env);
3000
+ const existingSettings = readOwenworkSettingsRaw(settingsPath); // corrupt file → hard CliError (never clobber)
3001
+ const currentHub = existingSettings && typeof existingSettings.hubOrigin === 'string' ? existingSettings.hubOrigin : undefined;
3002
+ if (existingSettings !== null && currentHub === origin) {
3003
+ io.err(`✓ owenwork settings: hubOrigin already ${origin}`);
3004
+ steps.push({ step: 'owenwork settings', action: 'skipped', detail: settingsPath });
3005
+ }
3006
+ else {
3007
+ const written = writeOwenworkHubOrigin(io.env, origin);
3008
+ io.err(`✓ owenwork settings: hubOrigin ${written.previous ?? '(unset)'} → ${origin}`);
3009
+ steps.push({ step: 'owenwork settings', action: 'done', detail: `${written.previous ?? '(unset)'} → ${origin}` });
3010
+ }
3011
+ if (agentAccount !== 'default') {
3012
+ io.err(`non-default agent account — run owenwork with OWENWORK_ACCOUNT=${agentAccount}`);
3013
+ }
3014
+ // --- [5/6] plugin (non-fatal) ---
3015
+ io.err('[5/6] plugin');
3016
+ const pluginState = probePlugin(io);
3017
+ if (pluginState.installed) {
3018
+ io.err('✓ plugin: owenloop installed');
3019
+ steps.push({ step: 'plugin', action: 'skipped', detail: 'installed' });
3020
+ }
3021
+ else {
3022
+ installPluginStep(io, pluginState);
3023
+ steps.push({
3024
+ step: 'plugin',
3025
+ action: 'noted',
3026
+ detail: pluginState.claudeFound ? 'not installed — printed manual instructions' : 'claude not on PATH — printed manual instructions',
3027
+ });
3028
+ }
3029
+ // --- [6/6] doctor pass ---
3030
+ io.err('[6/6] doctor');
3031
+ const doctor = await runDoctor(io, origin);
3032
+ print(io, { ok: doctor.ok, hub: origin, steps, doctor: { ok: doctor.ok, checks: doctor.checks } });
3033
+ return doctor.ok ? 0 : 1;
3034
+ }
3035
+ /**
3036
+ * `owenloop doctor` — the read-only probe of the five install surfaces plus the
3037
+ * plugin, rendering one distinct ✓/✗ line each. NO configuration writes (no
3038
+ * mint, rekey, slot create/delete, settings write, or browser). The one
3039
+ * carve-out: `authedGet`'s persist=true MAY rotate-and-persist an expiring human
3040
+ * oauth token — as every authed verb does — because a refresh WITHOUT persisting
3041
+ * would strand the rotated refresh token and corrupt the install (worse than a
3042
+ * write). Tests use non-expiring tokens so the strict zero-write assertion holds.
3043
+ */
3044
+ async function dispatchDoctor(io, args) {
3045
+ const origin = resolveSetupHub(io, args);
3046
+ const doctor = await runDoctor(io, origin);
3047
+ print(io, { ok: doctor.ok, hub: origin, checks: doctor.checks });
3048
+ return doctor.ok ? 0 : 1;
3049
+ }
3050
+ /**
3051
+ * Run the six doctor checks in order, printing each ✓/✗ line to stderr and
3052
+ * returning the structured result. Never short-circuits — a machine with no
3053
+ * working human credential still renders lines 3–6 (the agent probe degrades
3054
+ * honestly). `ok` reflects checks 1–5 only; the plugin check (6) renders but,
3055
+ * while `PLUGIN_CHECK_FATAL` is false, never affects `ok`.
3056
+ */
3057
+ async function runDoctor(io, origin) {
3058
+ const checks = [];
3059
+ let coreOk = true;
3060
+ const record = (label, ok, detail, core) => {
3061
+ io.err(`${ok ? '✓' : '✗'} ${label}: ${detail}`);
3062
+ checks.push({ label, ok, detail });
3063
+ if (core && !ok)
3064
+ coreOk = false;
3065
+ };
3066
+ // 1. human slot
3067
+ const humanCred = readCredential(io, origin, { principal: 'human' });
3068
+ if (humanCred === null) {
3069
+ record('human credential', false, `none stored for ${origin} — run owenloop setup (or owenloop login --hub ${origin})`, true);
3070
+ }
3071
+ else {
3072
+ record('human credential', true, 'present', true);
3073
+ }
3074
+ // 2. human plane
3075
+ let humanOk = false;
3076
+ let usableHumanCred = null;
3077
+ if (humanCred !== null) {
3078
+ try {
3079
+ const { cred, identity } = await verifyCredential(io, origin, { principal: 'human' }, humanCred);
3080
+ humanOk = true;
3081
+ usableHumanCred = cred;
3082
+ record('human plane', true, `${identity.email ?? identity.actor.id} @ ${identity.orgName}`, true);
3083
+ }
3084
+ catch (e) {
3085
+ const msg = e instanceof Error ? e.message : String(e);
3086
+ if (/refresh/i.test(msg)) {
3087
+ record('human plane', false, 'human credential present but irrecoverable (refresh failed) — run owenloop login', true);
3088
+ }
3089
+ else if (/rejected by the hub|revoked or invalid/.test(msg)) {
3090
+ record('human plane', false, 'human credential rejected by the hub — run owenloop login', true);
3091
+ }
3092
+ else {
3093
+ record('human plane', false, `could not reach the hub — ${msg}`, true);
3094
+ }
3095
+ }
3096
+ }
3097
+ else {
3098
+ record('human plane', false, 'not checked — no human credential to verify', true);
3099
+ }
3100
+ // Best-effort identities listing for the agent checks (soft: a 403/failure degrades, never throws).
3101
+ let identities = [];
3102
+ let identitiesForbidden = false;
3103
+ let identitiesAvailable = false;
3104
+ if (humanOk && usableHumanCred !== null) {
3105
+ try {
3106
+ const { res } = await authedGet(io, origin, { principal: 'human' }, usableHumanCred, '/api/agent_identities');
3107
+ if (res.status === 403) {
3108
+ identitiesForbidden = true;
3109
+ }
3110
+ else if (res.ok) {
3111
+ identities = asAgentIdentities(await res.json());
3112
+ identitiesAvailable = true;
3113
+ }
3114
+ }
3115
+ catch {
3116
+ // leave degraded
3117
+ }
3118
+ }
3119
+ // 3. agent slot (presence) + 4. agent plane (verification)
3120
+ const candidateNames = new Set(identities.map((i) => i.name));
3121
+ const fileAccts = enumerateAgentAccounts(io, origin);
3122
+ if (fileAccts !== null)
3123
+ for (const a of fileAccts)
3124
+ candidateNames.add(a);
3125
+ candidateNames.add('default');
3126
+ const agentProbe = await probeAgentSlots(io, origin, [...candidateNames], identities);
3127
+ if (!agentProbe.sawSlot) {
3128
+ if (!identitiesAvailable && !humanOk && fileAccts === null) {
3129
+ record('agent slot', false, 'not probeable without a working human credential', true);
3130
+ }
3131
+ else {
3132
+ record('agent slot', false, `no agent credential stored for ${origin} — run owenloop setup`, true);
3133
+ }
3134
+ record('agent plane', false, 'no agent credential to verify — run owenloop setup', true);
3135
+ }
3136
+ else {
3137
+ record('agent slot', true, 'present', true);
3138
+ if (agentProbe.verified !== null) {
3139
+ const va = agentProbe.verified;
3140
+ const pools = va.identity
3141
+ ? `pools: ${va.identity.pools.join(', ') || 'none'}`
3142
+ : identitiesForbidden
3143
+ ? '(pools not visible — requires an admin credential)'
3144
+ : '(pools unknown)';
3145
+ const idPart = va.identity ? va.identity.id : va.actorId;
3146
+ record('agent plane', true, `${va.name} (agent id ${idPart}) · ${pools}`, true);
3147
+ }
3148
+ else if (agentProbe.sawRevoked) {
3149
+ record('agent plane', false, 'agent token revoked or invalid — re-run owenloop setup (Replace) or Reconnect in the console', true);
3150
+ }
3151
+ else {
3152
+ record('agent plane', false, 'agent credential present but could not be verified against the hub', true);
3153
+ }
3154
+ }
3155
+ // 5. owenwork settings
3156
+ const settingsPath = owenworkSettingsPath(io.env);
3157
+ let settingsRaw = null;
3158
+ let settingsError = null;
3159
+ try {
3160
+ settingsRaw = readOwenworkSettingsRaw(settingsPath);
3161
+ }
3162
+ catch (e) {
3163
+ settingsError = e instanceof Error ? e.message : String(e);
3164
+ }
3165
+ if (settingsError !== null) {
3166
+ record('owenwork settings', false, settingsError, true);
3167
+ }
3168
+ else if (settingsRaw === null) {
3169
+ record('owenwork settings', false, `missing (${settingsPath})`, true);
3170
+ }
3171
+ else {
3172
+ const found = typeof settingsRaw.hubOrigin === 'string' ? settingsRaw.hubOrigin : undefined;
3173
+ if (found !== origin) {
3174
+ record('owenwork settings', false, `hubOrigin is ${found ?? '(unset)'}, expected ${origin}`, true);
3175
+ }
3176
+ else {
3177
+ record('owenwork settings', true, settingsPath, true);
3178
+ }
3179
+ }
3180
+ // 6. plugin (rendered; non-core while PLUGIN_CHECK_FATAL is false)
3181
+ const pluginState = probePlugin(io);
3182
+ if (!pluginState.claudeFound) {
3183
+ record('plugin', false, 'Claude Code (claude) not on PATH', PLUGIN_CHECK_FATAL);
3184
+ }
3185
+ else if (!pluginState.installed) {
3186
+ record('plugin', false, 'plugin not installed — claude plugin marketplace add owenloop && claude plugin install owenloop@owenloop', PLUGIN_CHECK_FATAL);
3187
+ }
3188
+ else {
3189
+ record('plugin', true, 'owenloop installed', PLUGIN_CHECK_FATAL);
3190
+ }
3191
+ return { ok: coreOk, checks };
3192
+ }
2513
3193
  /**
2514
3194
  * Async entry point that adds network I/O for `add` and the hub commands on top
2515
3195
  * of the otherwise fully-synchronous engine/CLI (see the doc comment on
@@ -2518,7 +3198,7 @@ function createWorkflowRequest(io, origin, cred, yaml) {
2518
3198
  * the async path, so every existing command and test keeps working exactly as
2519
3199
  * before.
2520
3200
  */
2521
- export const ASYNC_COMMANDS = new Set(['add', 'login', 'logout', 'connect', 'push']);
3201
+ export const ASYNC_COMMANDS = new Set(['add', 'login', 'logout', 'connect', 'push', 'agent', 'setup', 'doctor', 'mcp']);
2522
3202
  export async function mainAsync(argv, io = defaultIO()) {
2523
3203
  const args = parseArgs(argv);
2524
3204
  const command = args.positionals[0];
@@ -2540,6 +3220,14 @@ export async function mainAsync(argv, io = defaultIO()) {
2540
3220
  return await dispatchConnect(io, args);
2541
3221
  case 'push':
2542
3222
  return await dispatchPush(io, args);
3223
+ case 'agent':
3224
+ return await dispatchAgent(io, args);
3225
+ case 'setup':
3226
+ return await dispatchSetup(io, args);
3227
+ case 'doctor':
3228
+ return await dispatchDoctor(io, args);
3229
+ case 'mcp':
3230
+ return await dispatchMcp(io, args);
2543
3231
  default:
2544
3232
  return main(argv, io); // unreachable — ASYNC_COMMANDS guards the switch
2545
3233
  }
@@ -2551,7 +3239,8 @@ export async function mainAsync(argv, io = defaultIO()) {
2551
3239
  else {
2552
3240
  io.err(`error: ${e.message}`);
2553
3241
  }
2554
- return 1;
3242
+ // A CliError carries its own exit code (default 1); everything else is 1.
3243
+ return e instanceof CliError ? e.exitCode : 1;
2555
3244
  }
2556
3245
  }
2557
3246
  /** Run the CLI. Returns a process exit code. */
@@ -2575,6 +3264,7 @@ export function main(argv, io = defaultIO()) {
2575
3264
  else {
2576
3265
  io.err(`error: ${e.message}`);
2577
3266
  }
2578
- return 1;
3267
+ // A CliError carries its own exit code (default 1); everything else is 1.
3268
+ return e instanceof CliError ? e.exitCode : 1;
2579
3269
  }
2580
3270
  }