owenloop 0.4.0 → 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,19 +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';
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';
37
37
  import { createServer } from 'node:http';
38
+ import { createInterface } from 'node:readline/promises';
39
+ import { hostname } from 'node:os';
38
40
  import { parse as parseYaml } from 'yaml';
39
41
  import { Engine } from "./engine.js";
40
42
  import { buildGraph, buildTrace, graphToDot, graphToMermaid, modelCheck } from "./model.js";
41
43
  import { openStore } from "./store.js";
42
44
  import { buildDef, DefError, finalizeDefs, lintDef, loadDefs, loadDefsRaw, loadDefsUnfinalized, validateDef, } from "./defs.js";
43
- 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";
44
48
  import { DEFAULT_TAR_LIMITS, extractTarGz } from "./untar.js";
45
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";
46
- import { asCreateWorkflowOk, asWhoami, computeServerDiff, credentialBackend, createWorkflowError, credentialFilePath, credentialSlot, externalCredentialCommand, hashDefForHub, hubBindingPath, keychainServiceFor, normalizeOrigin, parseWorkflowList, pkcePair, randomState, readCredentialFile, readHubBinding, readStoredCredential, resolveEndpoint, resolveKeychain, 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";
47
52
  function defaultIO() {
48
53
  return {
49
54
  cwd: process.cwd(),
@@ -53,8 +58,33 @@ function defaultIO() {
53
58
  fetch: globalThis.fetch,
54
59
  openUrl: defaultOpenUrl,
55
60
  readStdin: defaultReadStdin,
61
+ prompt: defaultPrompt,
62
+ runCommand: defaultRunCommand,
56
63
  };
57
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
+ }
58
88
  /** Fire-and-forget browser open — never blocks the login flow on the child. */
59
89
  function defaultOpenUrl(url) {
60
90
  const platform = process.platform;
@@ -84,6 +114,7 @@ async function defaultReadStdin() {
84
114
  */
85
115
  const BOOLEAN_FLAGS = new Set([
86
116
  'assume-provided',
117
+ 'strict-inputs',
87
118
  'shallow',
88
119
  'now',
89
120
  'all',
@@ -139,8 +170,6 @@ const flag = (args, key) => {
139
170
  const v = last(args, key);
140
171
  return v === 'true' || v === '' || (v !== undefined && v !== 'false');
141
172
  };
142
- class CliError extends Error {
143
- }
144
173
  /**
145
174
  * A 429 from the hub during a push batch (REL-10). Thrown from the batch loop
146
175
  * and handled by an explicit `instanceof` branch that halts the rest of the
@@ -351,9 +380,13 @@ Commands:
351
380
  connect [--hub <url>] [--as <slot>] bind this project to a hub and verify the stored credential (whoami)
352
381
  push [<defName>...] [--force] [--dry-run] [--as <slot>] publish local workflow defs to the bound hub (server-diffed, idempotent)
353
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)
354
387
  lint [<def-name>] check def(s) for wiring problems
355
- check <def> [--format text|json] [--max-depth N] [--max-states N] [--max-collection N] [--assume-provided]
356
- 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)
357
390
  create <def> [--title t] [--provide name=json ...] [--param k=v ...]
358
391
  provide <wf> <name> [--value json] supply an owed (seedOwed) input
359
392
  adopt <wf> re-pin an instance to the current def (§28); settles new debts
@@ -416,8 +449,12 @@ export const COMMAND_OPTIONS = new Map([
416
449
  ['logout', cmdOpts('hub', 'as')],
417
450
  ['connect', cmdOpts('hub', 'as')],
418
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')],
419
456
  ['lint', cmdOpts()],
420
- ['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')],
421
458
  ['create', cmdOpts('title', 'provide', 'param')],
422
459
  ['provide', cmdOpts('value')],
423
460
  ['adopt', cmdOpts()],
@@ -573,19 +610,24 @@ function dispatch(command, io, args) {
573
610
  const maxDepth = numOpt(args, 'max-depth');
574
611
  const maxStates = numOpt(args, 'max-states');
575
612
  const maxCollection = numOpt(args, 'max-collection');
576
- 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 = {
577
619
  ...(maxDepth !== undefined ? { maxDepth } : {}),
578
620
  ...(maxStates !== undefined ? { maxStates } : {}),
579
621
  ...(maxCollection !== undefined ? { maxCollectionSize: maxCollection } : {}),
580
- ...(flag(args, 'assume-provided') ? { assumeProvided: true } : {}),
581
- });
622
+ };
623
+ const report = modelCheck(def, { ...bounds, assumeProvided: !strictInputs });
582
624
  if (format === 'json') {
583
625
  print(io, report);
584
626
  }
585
627
  else {
586
628
  // text format
587
- const clean = report.deadlocks.length === 0 && report.stuck.length === 0
588
- && report.invariantViolations.length === 0;
629
+ const clean = report.deadlocks.length === 0
630
+ && report.invariantViolations.length === 0 && report.structurallyDeadSteps.length === 0;
589
631
  const status = clean && report.completable ? 'OK' : clean ? 'INCOMPLETE' : 'DEFECTS FOUND';
590
632
  io.out(`=== owenloop check: ${def.name} ===`);
591
633
  io.out(`Status: ${status}`);
@@ -596,16 +638,42 @@ function dispatch(command, io, args) {
596
638
  io.out(`SEARCH INCOMPLETE — bounds hit: ${report.boundsHit.join(', ')}`);
597
639
  io.out('Verdicts apply only within the explored region.');
598
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
+ }
599
648
  if (report.deadlocks.length > 0) {
600
649
  io.out('');
601
- io.out(`Deadlocks (${report.deadlocks.length}):`);
650
+ io.out(`True deadlocks (no path to completion at unlimited attempts) (${report.deadlocks.length}):`);
602
651
  for (const d of report.deadlocks) {
603
652
  io.out(` path: ${d.path.map((s) => `${s.step}/${s.outcome}`).join(' -> ') || '(initial state)'}`);
604
653
  }
605
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
+ }
606
674
  if (report.stuck.length > 0) {
607
675
  io.out('');
608
- io.out(`Stuck states (${report.stuck.length}):`);
676
+ io.out(`Stuck states (brake tripped; other branches still moving — informational) (${report.stuck.length}):`);
609
677
  for (const s of report.stuck) {
610
678
  io.out(` path: ${s.path.map((p) => `${p.step}/${p.outcome}`).join(' -> ') || '(initial state)'}`);
611
679
  }
@@ -618,9 +686,13 @@ function dispatch(command, io, args) {
618
686
  io.out(` path: ${v.path.map((s) => `${s.step}/${s.outcome}`).join(' -> ') || '(initial state)'}`);
619
687
  }
620
688
  }
621
- if (report.deadSteps.length > 0) {
689
+ if (report.structurallyDeadSteps.length > 0) {
690
+ io.out('');
691
+ io.out(`Structurally dead steps (can never fire — wiring defect): ${report.structurallyDeadSteps.join(', ')}`);
692
+ }
693
+ if (report.unreachedSteps.length > 0) {
622
694
  io.out('');
623
- io.out(`Dead steps (never fire in explored space): ${report.deadSteps.join(', ')}`);
695
+ io.out(`Unreached within bounds (raise --max-states/--max-depth): ${report.unreachedSteps.join(', ')}`);
624
696
  }
625
697
  if (report.completePath) {
626
698
  io.out('');
@@ -633,16 +705,32 @@ function dispatch(command, io, args) {
633
705
  // counterexample path was produced by real applyOutcome/settleInMemory
634
706
  // transitions (pinned to the live Engine by the conformance test). The path
635
707
  // is a genuine executable witness; bounds only cause MISSES, never
636
- // fabrications. Contrast deadlocks/stuck, where the maxCollectionSize cap can
637
- // 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.
638
710
  // Do NOT remove this asymmetry; it encodes a real soundness distinction.
639
- // - definite deadlock/stuck only when EXHAUSTIVE (!bounded) → nonzero
640
- // - 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
641
727
  const hasDefiniteDefect = report.invariantViolations.length > 0 ||
642
- (!report.bounded && (report.deadlocks.length > 0 || report.stuck.length > 0));
728
+ report.structurallyDeadSteps.length > 0 ||
729
+ (!report.bounded && report.deadlocks.length > 0);
643
730
  if (hasDefiniteDefect) {
644
731
  throw new CliError(`definite defects found (${report.invariantViolations.length} invariant violation(s), ` +
645
- `${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))`);
646
734
  }
647
735
  return 0;
648
736
  }
@@ -1124,57 +1212,6 @@ function statusEntry(engine, w) {
1124
1212
  // one if ever needed).
1125
1213
  const ADD_SHA_TIMEOUT_MS = 30_000;
1126
1214
  const ADD_TARBALL_TIMEOUT_MS = 300_000;
1127
- /**
1128
- * Read a `Response` body while enforcing a byte `cap`, so a hostile server can
1129
- * never make us allocate an oversized body. Rejects UP FRONT on a declared
1130
- * oversize `Content-Length`; otherwise streams the body in chunks, counting the
1131
- * bytes that actually land in memory, and cancels the stream the moment the
1132
- * running total crosses the cap — the chunk buffer never holds more than `cap`
1133
- * plus one chunk. `label` names the request in the error and is origin+path or
1134
- * `owner/repo@sha` only — never a token. Counting post-decode bytes (what lands
1135
- * in memory) is deliberate: the cap protects memory, not wire bytes.
1136
- *
1137
- * `res.body === null` (empty/no-body response) yields empty bytes, so callers
1138
- * behave exactly as they did under `arrayBuffer()`. An absent, malformed, or
1139
- * multi-valued `Content-Length` skips the header check — the counting path is
1140
- * the real guard (GitHub codeload tarballs are typically chunked, no header). A
1141
- * `TimeoutError`/`AbortError` from `read()` (the abort signal fired mid-body)
1142
- * propagates untouched, so each call site's existing timeout mapping still
1143
- * fires exactly as it did for `arrayBuffer()` rejections. `cancel()` may reject
1144
- * on an already-errored stream — swallowed; the cap `CliError` is the story.
1145
- */
1146
- async function readBodyBounded(res, cap, label) {
1147
- const declared = Number(res.headers.get('content-length'));
1148
- if (Number.isFinite(declared) && declared > cap) {
1149
- await res.body?.cancel().catch(() => { });
1150
- throw new CliError(`response body for ${label} exceeds the ${cap}-byte cap (declared Content-Length ${declared})`);
1151
- }
1152
- if (res.body === null)
1153
- return new Uint8Array(0);
1154
- const reader = res.body.getReader();
1155
- const chunks = [];
1156
- let total = 0;
1157
- for (;;) {
1158
- const { done, value } = await reader.read();
1159
- if (done)
1160
- break;
1161
- if (value === undefined)
1162
- continue;
1163
- total += value.byteLength;
1164
- chunks.push(value);
1165
- if (total > cap) {
1166
- await reader.cancel().catch(() => { });
1167
- throw new CliError(`response body for ${label} exceeds the ${cap}-byte cap`);
1168
- }
1169
- }
1170
- const out = new Uint8Array(total);
1171
- let offset = 0;
1172
- for (const chunk of chunks) {
1173
- out.set(chunk, offset);
1174
- offset += chunk.byteLength;
1175
- }
1176
- return out;
1177
- }
1178
1215
  /**
1179
1216
  * Cap on the `add` tarball download body, enforced DURING the stream by
1180
1217
  * `readBodyBounded` — defense in depth with `extractTarGz`'s own post-hoc
@@ -1424,10 +1461,10 @@ async function dispatchAdd(io, args) {
1424
1461
  // publishing.
1425
1462
  const report = modelCheck(stagedDef, { assumeProvided: true });
1426
1463
  const hasDefiniteDefect = report.invariantViolations.length > 0 ||
1427
- (!report.bounded && (report.deadlocks.length > 0 || report.stuck.length > 0));
1464
+ (!report.bounded && report.deadlocks.length > 0);
1428
1465
  if (hasDefiniteDefect) {
1429
1466
  reasons.push(`${stagedDef.name}: definite defects found (${report.invariantViolations.length} invariant violation(s), ` +
1430
- `${report.deadlocks.length} deadlock(s), ${report.stuck.length} stuck state(s))`);
1467
+ `${report.deadlocks.length} true deadlock(s))`);
1431
1468
  }
1432
1469
  }
1433
1470
  // Strict backstop: only if the aggregate pass found nothing, run the FULL
@@ -1727,232 +1764,6 @@ function emptySlotMessage(origin, slot) {
1727
1764
  function readCredential(io, origin, slot) {
1728
1765
  return readStoredCredential(origin, { ...slot, env: io.env, keychain: io.keychain });
1729
1766
  }
1730
- /**
1731
- * Store a credential for `origin` in `slot`, in the chosen backend ONLY;
1732
- * returns which one. A failed keychain write is a hard error (REL-6), never a
1733
- * silent fall-through to the file — the escape hatch is to choose the file
1734
- * backend up front with `OWENLOOP_NO_KEYCHAIN=1`. Backend selection is the
1735
- * shared `credentialBackend` from `hub.ts`, so read and write agree on one
1736
- * choice. That shared selection now has a third variant: when an external
1737
- * credential command is configured this throws, because the command — not the
1738
- * local store — is what reads will consult.
1739
- *
1740
- * The file backend MERGES into the origin's slot map: writing `agent:ci` must
1741
- * leave a `human` credential for the same origin intact.
1742
- */
1743
- function storeCredential(io, origin, slot, cred) {
1744
- const account = credentialSlot(slot);
1745
- const backend = credentialBackend(io.env, io.keychain);
1746
- if (backend.kind === 'external') {
1747
- // Writing to a store that reads will never consult is exactly the
1748
- // "half-working setup hands back a stale key" failure the external command
1749
- // exists to prevent, so refuse loudly instead.
1750
- throw new CliError('an external credential command is configured (OWENLOOP_CREDENTIAL_COMMAND), so it — not the ' +
1751
- 'local store — supplies credentials for this hub; unset it to use `owenloop login`');
1752
- }
1753
- if (backend.kind === 'keychain') {
1754
- try {
1755
- backend.kc.set(keychainServiceFor(origin), account, JSON.stringify(cred));
1756
- }
1757
- catch (e) {
1758
- throw new CliError(`could not write the credential to the OS keychain: ${e.message}. ` +
1759
- 'Fix the keychain, or set OWENLOOP_NO_KEYCHAIN=1 to use the 0600 file store');
1760
- }
1761
- return 'keychain';
1762
- }
1763
- const path = credentialFilePath(io.env);
1764
- const file = readCredentialFile(path);
1765
- file.hubs[origin] = { ...file.hubs[origin], [account]: cred };
1766
- writeCredentialFile(path, file);
1767
- return 'file';
1768
- }
1769
- /**
1770
- * Delete the stored credential for `(origin, slot)` from BOTH backends.
1771
- * Deliberately not routed through `credentialBackend`: logout is a defensive
1772
- * dual-clear (the proposal explicitly blesses it), so a live refresh token can
1773
- * never be stranded in the store that wasn't the currently-chosen one. Returns
1774
- * whether anything was removed.
1775
- *
1776
- * Only the NAMED slot is removed. A blanket "clear every slot for this origin"
1777
- * is not implementable — the keychain cannot enumerate its accounts — and
1778
- * faking it on the file backend alone would be a half-truth, so the slot is
1779
- * always explicit (defaulting to `human`).
1780
- */
1781
- function deleteCredential(io, origin, slot) {
1782
- const account = credentialSlot(slot);
1783
- let removed = false;
1784
- const kc = resolveKeychain(io.env, io.keychain);
1785
- const service = keychainServiceFor(origin);
1786
- if (kc && kc.get(service, account) !== null) {
1787
- kc.delete(service, account);
1788
- removed = true;
1789
- }
1790
- const path = credentialFilePath(io.env);
1791
- const file = readCredentialFile(path);
1792
- const slots = file.hubs[origin];
1793
- if (slots !== undefined && slots[account] !== undefined) {
1794
- delete slots[account];
1795
- // Drop the origin key once its last slot is gone, so the file never keeps
1796
- // an empty husk that a later read would have to special-case.
1797
- if (Object.keys(slots).length === 0)
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();
1855
- 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 });
1863
- }
1864
- 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;
1878
- }
1879
- }
1880
- /**
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.
1885
- *
1886
- * `slot` is the slot the credential was READ from — a refreshed token must be
1887
- * written back to that same slot, never to a default one.
1888
- */
1889
- async function ensureFreshOAuth(io, origin, slot, cred, persist = true) {
1890
- if (cred.kind !== 'oauth')
1891
- return cred;
1892
- if (cred.expiresAt - nowMs() > 60_000)
1893
- return cred;
1894
- return refreshOAuth(io, origin, slot, cred, persist);
1895
- }
1896
- /**
1897
- * `persist` defaults to true — the normal case is refreshing an ALREADY
1898
- * stored, trusted credential (push/connect), where persisting immediately
1899
- * matters because refresh tokens can be single-use/rotating: losing the new
1900
- * one to a later crash would strand the user. `verifyCredential`'s login-time
1901
- * use passes `persist: false` — a not-yet-stored credential must never be
1902
- * written to disk/keychain before it is proven to work end to end (a 401 on
1903
- * the retry after this refresh still fails the overall login), matching the
1904
- * "never store an unverified token" rule enforced at every login call site.
1905
- */
1906
- async function refreshOAuth(io, origin, slot, cred, persist = true) {
1907
- const tokenEndpoint = await discoverTokenEndpoint(io, origin);
1908
- const body = new URLSearchParams({
1909
- grant_type: 'refresh_token',
1910
- refresh_token: cred.refreshToken,
1911
- client_id: cred.clientId,
1912
- });
1913
- const res = await hubFetch(io, tokenEndpoint, {
1914
- method: 'POST',
1915
- headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
1916
- body: body.toString(),
1917
- });
1918
- if (!res.ok) {
1919
- throw new CliError('credential expired and refresh failed — run `owenloop login`');
1920
- }
1921
- const json = (await res.json());
1922
- if (typeof json.access_token !== 'string') {
1923
- throw new CliError('credential expired and refresh returned no access token — run `owenloop login`');
1924
- }
1925
- const expiresIn = typeof json.expires_in === 'number' ? json.expires_in : 3600;
1926
- const refreshed = {
1927
- kind: 'oauth',
1928
- accessToken: json.access_token,
1929
- refreshToken: typeof json.refresh_token === 'string' ? json.refresh_token : cred.refreshToken,
1930
- expiresAt: nowMs() + expiresIn * 1000,
1931
- clientId: cred.clientId,
1932
- };
1933
- // When an external command supplies credentials it owns the credential's
1934
- // whole lifecycle; owenloop must not write a refreshed token into a store it
1935
- // will never read (and `storeCredential` refuses in that mode anyway).
1936
- if (persist && externalCredentialCommand(io.env) === undefined) {
1937
- storeCredential(io, origin, slot, refreshed);
1938
- }
1939
- return refreshed;
1940
- }
1941
- async function discoverMetadata(io, origin) {
1942
- const res = await hubFetch(io, resolveEndpoint(origin, '/.well-known/oauth-authorization-server'), {
1943
- headers: { Accept: 'application/json' },
1944
- });
1945
- if (!res.ok) {
1946
- throw new CliError(`could not read OAuth metadata from ${origin} (HTTP ${res.status})`);
1947
- }
1948
- return (await res.json());
1949
- }
1950
- async function discoverTokenEndpoint(io, origin) {
1951
- const meta = await discoverMetadata(io, origin);
1952
- if (!meta.token_endpoint)
1953
- throw new CliError(`hub ${origin} advertises no token_endpoint`);
1954
- return resolveEndpoint(origin, meta.token_endpoint);
1955
- }
1956
1767
  /**
1957
1768
  * GET `path` on `origin` with a bearer credential, refreshing an expiring
1958
1769
  * oauth token first and retrying exactly once after a 401→refresh for oauth.
@@ -2068,7 +1879,7 @@ async function dispatchLogin(io, args) {
2068
1879
  const slot = cred.kind === 'agent' ? { principal: 'agent', ...(asked.principal === 'agent' && asked.account !== undefined ? { account: asked.account } : {}) } : { principal: 'human' };
2069
1880
  const existed = readCredential(io, origin, slot) !== null;
2070
1881
  const { identity } = await verifyCredential(io, origin, slot, cred); // never store an unverified token
2071
- const storage = storeCredential(io, origin, slot, cred);
1882
+ const storage = await storeCredential(io, origin, slot, cred);
2072
1883
  print(io, {
2073
1884
  ok: true,
2074
1885
  hub: origin,
@@ -2088,6 +1899,35 @@ async function dispatchLogin(io, args) {
2088
1899
  if (asked.principal === 'agent') {
2089
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`);
2090
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) {
2091
1931
  const slot = { principal: 'human' };
2092
1932
  const existed = readCredential(io, origin, slot) !== null;
2093
1933
  // Loopback OAuth: bind the port FIRST (the service matches redirect URIs by
@@ -2122,20 +1962,8 @@ async function dispatchLogin(io, args) {
2122
1962
  verifier,
2123
1963
  });
2124
1964
  const { cred, identity } = await verifyCredential(io, origin, slot, exchanged, false); // never store an unverified token
2125
- const storage = storeCredential(io, origin, slot, cred);
2126
- print(io, {
2127
- ok: true,
2128
- hub: origin,
2129
- kind: cred.kind,
2130
- slot: credentialSlot(slot),
2131
- storage,
2132
- replaced: existed,
2133
- org: identity.orgName,
2134
- orgId: identity.orgId,
2135
- identity: identity.actor,
2136
- ...(identity.email ? { email: identity.email } : {}),
2137
- });
2138
- return 0;
1965
+ const storage = await storeCredential(io, origin, slot, cred);
1966
+ return { cred, identity, storage, replaced: existed };
2139
1967
  }
2140
1968
  finally {
2141
1969
  void server;
@@ -2275,7 +2103,7 @@ async function exchangeCode(io, origin, tokenEndpoint, p) {
2275
2103
  async function dispatchLogout(io, args) {
2276
2104
  const origin = resolveHub(io, args);
2277
2105
  const slot = resolveSlot(args);
2278
- const removed = deleteCredential(io, origin, slot);
2106
+ const removed = await deleteCredential(io, origin, slot);
2279
2107
  const slotName = credentialSlot(slot);
2280
2108
  if (!removed) {
2281
2109
  io.err(`no stored credential for ${origin} in slot \`${slotName}\` — another slot may hold one (see --as)`);
@@ -2393,10 +2221,10 @@ async function dispatchPush(io, args) {
2393
2221
  reasons.push(...validateDef(def).map((e) => `${def.name}: ${e}`));
2394
2222
  const report = modelCheck(def, { assumeProvided: true });
2395
2223
  const hasDefiniteDefect = report.invariantViolations.length > 0 ||
2396
- (!report.bounded && (report.deadlocks.length > 0 || report.stuck.length > 0));
2224
+ (!report.bounded && report.deadlocks.length > 0);
2397
2225
  if (hasDefiniteDefect) {
2398
2226
  reasons.push(`${def.name}: definite defects found (${report.invariantViolations.length} invariant violation(s), ` +
2399
- `${report.deadlocks.length} deadlock(s), ${report.stuck.length} stuck state(s))`);
2227
+ `${report.deadlocks.length} true deadlock(s))`);
2400
2228
  }
2401
2229
  }
2402
2230
  // Assemble the push candidates: verbatim source yaml + the server-canonical
@@ -2555,6 +2383,16 @@ async function dispatchPush(io, args) {
2555
2383
  });
2556
2384
  return failed.length === 0 ? 0 : 1;
2557
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
+ }
2558
2396
  function createWorkflowRequest(io, origin, cred, yaml) {
2559
2397
  return hubFetch(io, resolveEndpoint(origin, '/api/create_workflow'), {
2560
2398
  method: 'POST',
@@ -2566,6 +2404,792 @@ function createWorkflowRequest(io, origin, cred, yaml) {
2566
2404
  body: JSON.stringify({ yaml }),
2567
2405
  });
2568
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
+ }
2569
3193
  /**
2570
3194
  * Async entry point that adds network I/O for `add` and the hub commands on top
2571
3195
  * of the otherwise fully-synchronous engine/CLI (see the doc comment on
@@ -2574,7 +3198,7 @@ function createWorkflowRequest(io, origin, cred, yaml) {
2574
3198
  * the async path, so every existing command and test keeps working exactly as
2575
3199
  * before.
2576
3200
  */
2577
- 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']);
2578
3202
  export async function mainAsync(argv, io = defaultIO()) {
2579
3203
  const args = parseArgs(argv);
2580
3204
  const command = args.positionals[0];
@@ -2596,6 +3220,14 @@ export async function mainAsync(argv, io = defaultIO()) {
2596
3220
  return await dispatchConnect(io, args);
2597
3221
  case 'push':
2598
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);
2599
3231
  default:
2600
3232
  return main(argv, io); // unreachable — ASYNC_COMMANDS guards the switch
2601
3233
  }
@@ -2607,7 +3239,8 @@ export async function mainAsync(argv, io = defaultIO()) {
2607
3239
  else {
2608
3240
  io.err(`error: ${e.message}`);
2609
3241
  }
2610
- return 1;
3242
+ // A CliError carries its own exit code (default 1); everything else is 1.
3243
+ return e instanceof CliError ? e.exitCode : 1;
2611
3244
  }
2612
3245
  }
2613
3246
  /** Run the CLI. Returns a process exit code. */
@@ -2631,6 +3264,7 @@ export function main(argv, io = defaultIO()) {
2631
3264
  else {
2632
3265
  io.err(`error: ${e.message}`);
2633
3266
  }
2634
- return 1;
3267
+ // A CliError carries its own exit code (default 1); everything else is 1.
3268
+ return e instanceof CliError ? e.exitCode : 1;
2635
3269
  }
2636
3270
  }