owenloop 0.3.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,19 @@ All notable changes to this project are documented here. The format is based on
4
4
  [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project
5
5
  adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
 
7
+ ## [0.4.0](https://github.com/typicalday/owenloop/compare/v0.3.1...v0.4.0) (2026-07-21)
8
+
9
+
10
+ ### ⚠ BREAKING CHANGES
11
+
12
+ * `Keychain` methods take `(service, account)`, the `readStoredCredential` options argument is required and must carry a principal, and credentials stored under the previous keying are not read. There is deliberately no migration path — re-run `owenloop login`.
13
+
14
+ ### Features
15
+
16
+ * **hub:** optional external command for hub credentials ([#69](https://github.com/typicalday/owenloop/issues/69)) ([bd52654](https://github.com/typicalday/owenloop/commit/bd526545983e055a479be2f93e1e644a2ee37131))
17
+ * principal-namespaced credential slots for hub credentials ([#68](https://github.com/typicalday/owenloop/issues/68)) ([253174f](https://github.com/typicalday/owenloop/commit/253174f33d51f90f1e051e85ff21a15b4d11e031))
18
+ * **store:** export read-only credential surface (readStoredCredential) ([#66](https://github.com/typicalday/owenloop/issues/66)) ([ed43efd](https://github.com/typicalday/owenloop/commit/ed43efdc7f305ca231f35f251c9d13886898d41a))
19
+
7
20
  ## [0.3.1](https://github.com/typicalday/owenloop/compare/v0.3.0...v0.3.1) (2026-07-17)
8
21
 
9
22
 
package/README.md CHANGED
@@ -428,6 +428,12 @@ since. The changes that need operator or embedder attention:
428
428
  and store a credential in the macOS Keychain or a `0600` file — see the
429
429
  [Hub](docs/cli.md#hub-login--connect--push--logout) section and the `add`
430
430
  [trust model](docs/cli.md#add--installing-shared-workflow-defs-from-github).
431
+ A hub origin now holds one credential per named **slot** (`--as
432
+ human|agent|agent:<account>`), and credentials stored under the earlier keying
433
+ are not read — there is no migration, so re-run `owenloop login`. Setting
434
+ `OWENLOOP_CREDENTIAL_COMMAND` instead supplies the credential from a command
435
+ of your own (a secret manager, or any host without a keychain); it takes
436
+ precedence over both stores and fails loudly rather than falling back.
431
437
  - **Max-lease cap is now opt-in.** There is no default lease ceiling; anyone who
432
438
  relied on the brief post-0.2.1 default cap must set `maxLeaseMs` (or a
433
439
  per-step `maxLease`) explicitly.
package/dist/cli.d.ts CHANGED
@@ -31,12 +31,8 @@
31
31
  *
32
32
  * Global: --db <path> (env OWENLOOP_DB), --defs <dir> (env OWENLOOP_DEFS).
33
33
  */
34
- /** An OS keychain backend, keyed by hub origin (the `account`). */
35
- export interface Keychain {
36
- get(account: string): string | null;
37
- set(account: string, value: string): void;
38
- delete(account: string): void;
39
- }
34
+ import type { Keychain } from './hub.ts';
35
+ export type { Keychain } from './hub.ts';
40
36
  export interface CliIO {
41
37
  cwd: string;
42
38
  env: Record<string, string | undefined>;
@@ -58,7 +54,7 @@ export interface CliIO {
58
54
  /** Read a secret from stdin (`login --with-token`). Default: drain `process.stdin`. */
59
55
  readStdin?: () => Promise<string>;
60
56
  }
61
- export declare const USAGE = "owenloop \u2014 a dataflow workflow engine\n\nUsage: owenloop <command> [args] [--db <path>] [--defs <dir>]\n\nCommands:\n defs list available workflow definitions\n add <owner>/<repo>[@ref] fetch, validate, and install a repo's workflow defs (public repos)\n add --recover finish or undo a crash-interrupted install (offline; no network)\n login [--hub <url>] [--with-token] authenticate the CLI against a hub, verified via whoami (loopback OAuth, or --with-token from stdin)\n logout [--hub <url>] delete the stored credential for a hub\n connect [--hub <url>] bind this project to a hub and verify the stored credential (whoami)\n push [<defName>...] [--force] [--dry-run] publish local workflow defs to the bound hub (server-diffed, idempotent)\n lint [<def-name>] check def(s) for wiring problems\n check <def> [--format text|json] [--max-depth N] [--max-states N] [--max-collection N] [--assume-provided]\n bounded reachability check (deadlocks, stuck, dead steps, declared invariants)\n create <def> [--title t] [--provide name=json ...] [--param k=v ...]\n provide <wf> <name> [--value json] supply an owed (seedOwed) input\n adopt <wf> re-pin an instance to the current def (\u00A728); settles new debts\n tick <wf> [--now <ms>] [--shallow] [--label <l>]... pull eligible orders (deep: also from calls: children; --shallow for this instance only; --label filters to matching-label steps)\n reap <wf> [--now] run the reaper; --now forces every claim stale (TTL 0)\n runs <wf> [--open] list this instance's runs (+ claim state for open ones)\n order <wf> <run> print the order packet issued at claim time (persisted in the claim txn)\n status <wf> derive debts / eligible / blocked\n status --all every instance's status in one call (fleet read)\n wait <wf> --until eligible|done [--timeout <dur>] block until engine state matches\n show <wf> dump raw artifacts\n trace <wf> [--format text] causal timeline + artifact biographies\n graph <def-or-wf> [--format dot|mermaid|json] wiring graph (+ live overlay if wf id)\n list list workflow instances\n green <wf> <run> <path> [--value json] [--terminal]\n emit <wf> <run> --items '[{...}]' accrete collection elements\n seal <wf> <run> [--value json] signal a collection is complete\n reject <wf> <path> --by <author> --text <msg>\n retract <wf> <path> --by <author> --text <msg>\n skip <wf> <path> --by <author> --text <msg>\n retry <wf> <path> [--by <author>] [--text <guidance>] clear a \u00A76 stall\n heartbeat <wf> <run> [--now <ms>] touch liveness timestamp on an open run\n close <wf> <run> [--outcome ok|no_work|failed|skipped] [--summary s]\n delete <wf> [--recursive] refuse if children exist unless --recursive (cascades)\n\nEnvironment: OWENLOOP_DB, OWENLOOP_DEFS";
57
+ export declare const USAGE = "owenloop \u2014 a dataflow workflow engine\n\nUsage: owenloop <command> [args] [--db <path>] [--defs <dir>]\n\nCommands:\n defs list available workflow definitions\n add <owner>/<repo>[@ref] fetch, validate, and install a repo's workflow defs (public repos)\n add --recover finish or undo a crash-interrupted install (offline; no network)\n login [--hub <url>] [--with-token] [--as <slot>] authenticate the CLI against a hub, verified via whoami (loopback OAuth, or --with-token from stdin)\n logout [--hub <url>] [--as <slot>] delete the stored credential for a hub in one slot\n connect [--hub <url>] [--as <slot>] bind this project to a hub and verify the stored credential (whoami)\n push [<defName>...] [--force] [--dry-run] [--as <slot>] publish local workflow defs to the bound hub (server-diffed, idempotent)\n --as names the credential slot: human (default), agent, or agent:<account>\n lint [<def-name>] check def(s) for wiring problems\n check <def> [--format text|json] [--max-depth N] [--max-states N] [--max-collection N] [--assume-provided]\n bounded reachability check (deadlocks, stuck, dead steps, declared invariants)\n create <def> [--title t] [--provide name=json ...] [--param k=v ...]\n provide <wf> <name> [--value json] supply an owed (seedOwed) input\n adopt <wf> re-pin an instance to the current def (\u00A728); settles new debts\n tick <wf> [--now <ms>] [--shallow] [--label <l>]... pull eligible orders (deep: also from calls: children; --shallow for this instance only; --label filters to matching-label steps)\n reap <wf> [--now] run the reaper; --now forces every claim stale (TTL 0)\n runs <wf> [--open] list this instance's runs (+ claim state for open ones)\n order <wf> <run> print the order packet issued at claim time (persisted in the claim txn)\n status <wf> derive debts / eligible / blocked\n status --all every instance's status in one call (fleet read)\n wait <wf> --until eligible|done [--timeout <dur>] block until engine state matches\n show <wf> dump raw artifacts\n trace <wf> [--format text] causal timeline + artifact biographies\n graph <def-or-wf> [--format dot|mermaid|json] wiring graph (+ live overlay if wf id)\n list list workflow instances\n green <wf> <run> <path> [--value json] [--terminal]\n emit <wf> <run> --items '[{...}]' accrete collection elements\n seal <wf> <run> [--value json] signal a collection is complete\n reject <wf> <path> --by <author> --text <msg>\n retract <wf> <path> --by <author> --text <msg>\n skip <wf> <path> --by <author> --text <msg>\n retry <wf> <path> [--by <author>] [--text <guidance>] clear a \u00A76 stall\n heartbeat <wf> <run> [--now <ms>] touch liveness timestamp on an open run\n close <wf> <run> [--outcome ok|no_work|failed|skipped] [--summary s]\n delete <wf> [--recursive] refuse if children exist unless --recursive (cascades)\n\nEnvironment: OWENLOOP_DB, OWENLOOP_DEFS";
62
58
  /**
63
59
  * Single source of truth for the `--options` each command accepts, consulted by
64
60
  * `preflight` before any side effect. Unknown-OPTION rejection AND
package/dist/cli.js CHANGED
@@ -34,7 +34,6 @@
34
34
  import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
35
35
  import { basename, dirname, join, resolve } from 'node:path';
36
36
  import { spawn } from 'node:child_process';
37
- import { execFileSync } from 'node:child_process';
38
37
  import { createServer } from 'node:http';
39
38
  import { parse as parseYaml } from 'yaml';
40
39
  import { Engine } from "./engine.js";
@@ -44,7 +43,7 @@ import { buildDef, DefError, finalizeDefs, lintDef, loadDefs, loadDefsRaw, loadD
44
43
  import { dbPathRefusingSymlink, detId, mkdirRefusingSymlink, nowMs, parseDurationMs, randId } from "./util.js";
45
44
  import { DEFAULT_TAR_LIMITS, extractTarGz } from "./untar.js";
46
45
  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";
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";
48
47
  function defaultIO() {
49
48
  return {
50
49
  cwd: process.cwd(),
@@ -73,51 +72,6 @@ async function defaultReadStdin() {
73
72
  chunks.push(chunk);
74
73
  return Buffer.concat(chunks).toString('utf8');
75
74
  }
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
75
  /**
122
76
  * Flags that are always boolean and must never consume the following token as
123
77
  * a value — `owenloop push --force foo` must force-push only `foo`, not treat
@@ -392,10 +346,11 @@ Commands:
392
346
  defs list available workflow definitions
393
347
  add <owner>/<repo>[@ref] fetch, validate, and install a repo's workflow defs (public repos)
394
348
  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)
349
+ login [--hub <url>] [--with-token] [--as <slot>] authenticate the CLI against a hub, verified via whoami (loopback OAuth, or --with-token from stdin)
350
+ logout [--hub <url>] [--as <slot>] delete the stored credential for a hub in one slot
351
+ connect [--hub <url>] [--as <slot>] bind this project to a hub and verify the stored credential (whoami)
352
+ push [<defName>...] [--force] [--dry-run] [--as <slot>] publish local workflow defs to the bound hub (server-diffed, idempotent)
353
+ --as names the credential slot: human (default), agent, or agent:<account>
399
354
  lint [<def-name>] check def(s) for wiring problems
400
355
  check <def> [--format text|json] [--max-depth N] [--max-states N] [--max-collection N] [--assume-provided]
401
356
  bounded reachability check (deadlocks, stuck, dead steps, declared invariants)
@@ -457,10 +412,10 @@ export const COMMAND_OPTIONS = new Map([
457
412
  ['help', cmdOpts()],
458
413
  ['defs', cmdOpts()],
459
414
  ['add', cmdOpts('recover')],
460
- ['login', cmdOpts('hub', 'with-token')],
461
- ['logout', cmdOpts('hub')],
462
- ['connect', cmdOpts('hub')],
463
- ['push', cmdOpts('dry-run', 'force', 'hub')],
415
+ ['login', cmdOpts('hub', 'with-token', 'as')],
416
+ ['logout', cmdOpts('hub', 'as')],
417
+ ['connect', cmdOpts('hub', 'as')],
418
+ ['push', cmdOpts('dry-run', 'force', 'hub', 'as')],
464
419
  ['lint', cmdOpts()],
465
420
  ['check', cmdOpts('format', 'max-depth', 'max-states', 'max-collection', 'assume-provided')],
466
421
  ['create', cmdOpts('title', 'provide', 'param')],
@@ -1722,49 +1677,82 @@ function resolveHub(io, args) {
1722
1677
  throw new CliError(e.message);
1723
1678
  }
1724
1679
  }
1725
- function resolveKeychain(io) {
1726
- if (io.env.OWENLOOP_NO_KEYCHAIN === '1')
1727
- return undefined;
1728
- return io.keychain ?? defaultKeychain(io.env);
1680
+ /**
1681
+ * Parse `--as <human | agent | agent:NAME>` into a `CredentialSlotSelector`.
1682
+ * Absent `--as` means the **human** slot — the everyday interactive case.
1683
+ * A malformed value (or an invalid account name, validated by `credentialSlot`)
1684
+ * is a usage error, never a silent coercion to some other slot.
1685
+ */
1686
+ function resolveSlot(args) {
1687
+ const raw = last(args, 'as');
1688
+ const sel = parseSlotArg(raw);
1689
+ // Validate eagerly so a bad account name fails before any network or store
1690
+ // access, with the same wording every later call site would produce.
1691
+ try {
1692
+ credentialSlot(sel);
1693
+ }
1694
+ catch (e) {
1695
+ throw new CliError(`--as: ${e.message}`);
1696
+ }
1697
+ return sel;
1729
1698
  }
1730
- function credentialBackend(io) {
1731
- const kc = resolveKeychain(io);
1732
- return kc ? { kind: 'keychain', kc } : { kind: 'file' };
1699
+ function parseSlotArg(raw) {
1700
+ if (raw === undefined)
1701
+ return { principal: 'human' };
1702
+ if (raw === 'human')
1703
+ return { principal: 'human' };
1704
+ if (raw === 'agent')
1705
+ return { principal: 'agent' };
1706
+ if (raw.startsWith('agent:'))
1707
+ return { principal: 'agent', account: raw.slice('agent:'.length) };
1708
+ throw new CliError(`--as: unrecognized slot '${raw}' — expected 'human', 'agent', or 'agent:<account>'`);
1733
1709
  }
1734
1710
  /**
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.
1711
+ * The "nothing stored here" message for a read that missed. It names the SLOT,
1712
+ * not just the origin — a credential may well exist for this hub under another
1713
+ * principal, and the fix is `--as`, not another `login`.
1740
1714
  */
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;
1715
+ function emptySlotMessage(origin, slot) {
1716
+ const name = credentialSlot(slot);
1717
+ return `no stored credential for ${origin} in slot \`${name}\` — run \`owenloop login\` (or pass --as agent:<name>)`;
1756
1718
  }
1757
1719
  /**
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`.
1720
+ * Read the stored credential for `origin` in `slot`. Thin wrapper over the
1721
+ * shared `readStoredCredential` in `hub.ts` (the same implementation the public
1722
+ * package export uses), threading the CLI's injected `env`/`keychain`. Callers
1723
+ * pass a pre-normalized origin (`resolveHub` output); the wrapper's
1724
+ * normalization is idempotent, so CLI behavior is unchanged. REL-6 no-fallback
1725
+ * and corrupt-entry-as-absent semantics live in `hub.ts`.
1762
1726
  */
1763
- function storeCredential(io, origin, cred) {
1764
- const backend = credentialBackend(io);
1727
+ function readCredential(io, origin, slot) {
1728
+ return readStoredCredential(origin, { ...slot, env: io.env, keychain: io.keychain });
1729
+ }
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
+ }
1765
1753
  if (backend.kind === 'keychain') {
1766
1754
  try {
1767
- backend.kc.set(origin, JSON.stringify(cred));
1755
+ backend.kc.set(keychainServiceFor(origin), account, JSON.stringify(cred));
1768
1756
  }
1769
1757
  catch (e) {
1770
1758
  throw new CliError(`could not write the credential to the OS keychain: ${e.message}. ` +
@@ -1774,28 +1762,40 @@ function storeCredential(io, origin, cred) {
1774
1762
  }
1775
1763
  const path = credentialFilePath(io.env);
1776
1764
  const file = readCredentialFile(path);
1777
- file.hubs[origin] = cred;
1765
+ file.hubs[origin] = { ...file.hubs[origin], [account]: cred };
1778
1766
  writeCredentialFile(path, file);
1779
1767
  return 'file';
1780
1768
  }
1781
1769
  /**
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.
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`).
1787
1780
  */
1788
- function deleteCredential(io, origin) {
1781
+ function deleteCredential(io, origin, slot) {
1782
+ const account = credentialSlot(slot);
1789
1783
  let removed = false;
1790
- const kc = resolveKeychain(io);
1791
- if (kc && kc.get(origin) !== null) {
1792
- kc.delete(origin);
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);
1793
1788
  removed = true;
1794
1789
  }
1795
1790
  const path = credentialFilePath(io.env);
1796
1791
  const file = readCredentialFile(path);
1797
- if (file.hubs[origin] !== undefined) {
1798
- delete file.hubs[origin];
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
1799
  writeCredentialFile(path, file);
1800
1800
  removed = true;
1801
1801
  }
@@ -1882,13 +1882,16 @@ async function hubFetch(io, url, init) {
1882
1882
  * 60s, refresh once (grant_type=refresh_token) and persist the new token. No-op
1883
1883
  * for `agent`/`oauth-pasted` credentials (they don't refresh). Returns the
1884
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.
1885
1888
  */
1886
- async function ensureFreshOAuth(io, origin, cred, persist = true) {
1889
+ async function ensureFreshOAuth(io, origin, slot, cred, persist = true) {
1887
1890
  if (cred.kind !== 'oauth')
1888
1891
  return cred;
1889
1892
  if (cred.expiresAt - nowMs() > 60_000)
1890
1893
  return cred;
1891
- return refreshOAuth(io, origin, cred, persist);
1894
+ return refreshOAuth(io, origin, slot, cred, persist);
1892
1895
  }
1893
1896
  /**
1894
1897
  * `persist` defaults to true — the normal case is refreshing an ALREADY
@@ -1900,7 +1903,7 @@ async function ensureFreshOAuth(io, origin, cred, persist = true) {
1900
1903
  * the retry after this refresh still fails the overall login), matching the
1901
1904
  * "never store an unverified token" rule enforced at every login call site.
1902
1905
  */
1903
- async function refreshOAuth(io, origin, cred, persist = true) {
1906
+ async function refreshOAuth(io, origin, slot, cred, persist = true) {
1904
1907
  const tokenEndpoint = await discoverTokenEndpoint(io, origin);
1905
1908
  const body = new URLSearchParams({
1906
1909
  grant_type: 'refresh_token',
@@ -1927,8 +1930,12 @@ async function refreshOAuth(io, origin, cred, persist = true) {
1927
1930
  expiresAt: nowMs() + expiresIn * 1000,
1928
1931
  clientId: cred.clientId,
1929
1932
  };
1930
- if (persist)
1931
- storeCredential(io, origin, refreshed);
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
+ }
1932
1939
  return refreshed;
1933
1940
  }
1934
1941
  async function discoverMetadata(io, origin) {
@@ -1954,13 +1961,13 @@ async function discoverTokenEndpoint(io, origin) {
1954
1961
  * semantics on the final status (a 401 after the retry, a non-2xx, etc. —
1955
1962
  * left to the caller since the wording differs slightly by context).
1956
1963
  */
1957
- async function authedGet(io, origin, cred, path, persist = true) {
1958
- let current = await ensureFreshOAuth(io, origin, cred, persist);
1964
+ async function authedGet(io, origin, slot, cred, path, persist = true) {
1965
+ let current = await ensureFreshOAuth(io, origin, slot, cred, persist);
1959
1966
  let res = await hubFetch(io, resolveEndpoint(origin, path), {
1960
1967
  headers: { Authorization: authHeader(current), Accept: 'application/json' },
1961
1968
  });
1962
1969
  if (res.status === 401 && current.kind === 'oauth') {
1963
- current = await refreshOAuth(io, origin, current, persist);
1970
+ current = await refreshOAuth(io, origin, slot, current, persist);
1964
1971
  res = await hubFetch(io, resolveEndpoint(origin, path), {
1965
1972
  headers: { Authorization: authHeader(current), Accept: 'application/json' },
1966
1973
  });
@@ -2002,8 +2009,8 @@ function assertAuthOk(res, cred, origin) {
2002
2009
  * verified here hasn't been stored yet at all; a refresh mid-verify must not
2003
2010
  * sneak a not-yet-proven credential onto disk ahead of the pass/fail verdict.
2004
2011
  */
2005
- async function verifyCredential(io, origin, cred, persist = true) {
2006
- const { res, cred: current } = await authedGet(io, origin, cred, '/api/whoami', persist);
2012
+ async function verifyCredential(io, origin, slot, cred, persist = true) {
2013
+ const { res, cred: current } = await authedGet(io, origin, slot, cred, '/api/whoami', persist);
2007
2014
  assertAuthOk(res, current, origin);
2008
2015
  const body = await res.json();
2009
2016
  return { cred: current, identity: asWhoami(body) };
@@ -2014,10 +2021,30 @@ async function verifyCredential(io, origin, cred, persist = true) {
2014
2021
  * `olp_`/`mcpat_` token from stdin instead (never argv). Either way the
2015
2022
  * credential is verified before it is stored, and stored in the OS keychain or
2016
2023
  * a 0600 file — never plaintext in the repo or `.env`.
2024
+ *
2025
+ * The SLOT the credential lands in follows the credential KIND, with `--as`
2026
+ * naming the agent account: a human credential (loopback `oauth`, or a pasted
2027
+ * `mcpat_`) writes `human`; a pasted `olp_` agent token writes
2028
+ * `agent:<account>` (`default` unless `--as agent:NAME`). A `--as` that
2029
+ * contradicts the credential kind is a usage error, not a silent coercion —
2030
+ * that is what keeps the agent slot holding agent keys.
2031
+ *
2032
+ * Refused outright while an external credential command is configured: that
2033
+ * command, not the local store, is what every read consults, so there is nothing
2034
+ * for `login` to usefully write. The check is here — before the "did a
2035
+ * credential already exist?" probe, which would otherwise RUN the command and
2036
+ * report its failure instead of this far more actionable reason — with
2037
+ * `storeCredential`'s own throw kept as the invariant backstop for any other
2038
+ * write path.
2017
2039
  */
2018
2040
  async function dispatchLogin(io, args) {
2019
2041
  const origin = resolveHub(io, args);
2020
- const existed = readCredential(io, origin) !== null;
2042
+ const asked = resolveSlot(args);
2043
+ const asGiven = last(args, 'as') !== undefined;
2044
+ if (externalCredentialCommand(io.env) !== undefined) {
2045
+ throw new CliError('an external credential command is configured (OWENLOOP_CREDENTIAL_COMMAND), so it — not the ' +
2046
+ 'local store — supplies credentials for this hub; unset it to use `owenloop login`');
2047
+ }
2021
2048
  if (flag(args, 'with-token')) {
2022
2049
  const readStdin = io.readStdin ?? defaultReadStdin;
2023
2050
  const token = (await readStdin()).trim();
@@ -2030,12 +2057,23 @@ async function dispatchLogin(io, args) {
2030
2057
  cred = { kind: 'oauth-pasted', accessToken: token };
2031
2058
  else
2032
2059
  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);
2060
+ // Contradictions are usage errors, refused BEFORE any network call so
2061
+ // nothing is verified or stored under a slot the token does not belong in.
2062
+ if (cred.kind === 'agent' && asGiven && asked.principal === 'human') {
2063
+ throw new CliError('an `olp_` agent token cannot be stored in the `human` slot — drop `--as human`, or pass `--as agent[:<account>]`');
2064
+ }
2065
+ if (cred.kind !== 'agent' && asked.principal === 'agent') {
2066
+ 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`);
2067
+ }
2068
+ const slot = cred.kind === 'agent' ? { principal: 'agent', ...(asked.principal === 'agent' && asked.account !== undefined ? { account: asked.account } : {}) } : { principal: 'human' };
2069
+ const existed = readCredential(io, origin, slot) !== null;
2070
+ const { identity } = await verifyCredential(io, origin, slot, cred); // never store an unverified token
2071
+ const storage = storeCredential(io, origin, slot, cred);
2035
2072
  print(io, {
2036
2073
  ok: true,
2037
2074
  hub: origin,
2038
2075
  kind: cred.kind,
2076
+ slot: credentialSlot(slot),
2039
2077
  storage,
2040
2078
  replaced: existed,
2041
2079
  org: identity.orgName,
@@ -2045,6 +2083,13 @@ async function dispatchLogin(io, args) {
2045
2083
  });
2046
2084
  return 0;
2047
2085
  }
2086
+ // Loopback OAuth always yields a HUMAN credential — `--as agent*` on this
2087
+ // flow is a contradiction, refused before the browser is opened.
2088
+ if (asked.principal === 'agent') {
2089
+ 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
+ }
2091
+ const slot = { principal: 'human' };
2092
+ const existed = readCredential(io, origin, slot) !== null;
2048
2093
  // Loopback OAuth: bind the port FIRST (the service matches redirect URIs by
2049
2094
  // exact string — no RFC 8252 variable-port allowance — so the DCR must carry
2050
2095
  // the concrete 127.0.0.1:<port> callback).
@@ -2076,12 +2121,13 @@ async function dispatchLogin(io, args) {
2076
2121
  redirectUri,
2077
2122
  verifier,
2078
2123
  });
2079
- const { cred, identity } = await verifyCredential(io, origin, exchanged, false); // never store an unverified token
2080
- const storage = storeCredential(io, origin, cred);
2124
+ const { cred, identity } = await verifyCredential(io, origin, slot, exchanged, false); // never store an unverified token
2125
+ const storage = storeCredential(io, origin, slot, cred);
2081
2126
  print(io, {
2082
2127
  ok: true,
2083
2128
  hub: origin,
2084
2129
  kind: cred.kind,
2130
+ slot: credentialSlot(slot),
2085
2131
  storage,
2086
2132
  replaced: existed,
2087
2133
  org: identity.orgName,
@@ -2220,13 +2266,21 @@ async function exchangeCode(io, origin, tokenEndpoint, p) {
2220
2266
  };
2221
2267
  }
2222
2268
  /**
2223
- * `owenloop logout` — delete the stored credential for a hub from both the
2224
- * keychain and the file store. Cheap; completes the credential lifecycle.
2269
+ * `owenloop logout` — delete the stored credential for a hub, in ONE slot
2270
+ * (`--as`, default `human`), from both the keychain and the file store. Cheap;
2271
+ * completes the credential lifecycle. Other slots for the same origin are left
2272
+ * alone: the keychain cannot enumerate its accounts, so a blanket
2273
+ * clear-everything is not implementable and is not faked.
2225
2274
  */
2226
2275
  async function dispatchLogout(io, args) {
2227
2276
  const origin = resolveHub(io, args);
2228
- const removed = deleteCredential(io, origin);
2229
- print(io, { ok: true, hub: origin, removed });
2277
+ const slot = resolveSlot(args);
2278
+ const removed = deleteCredential(io, origin, slot);
2279
+ const slotName = credentialSlot(slot);
2280
+ if (!removed) {
2281
+ io.err(`no stored credential for ${origin} in slot \`${slotName}\` — another slot may hold one (see --as)`);
2282
+ }
2283
+ print(io, { ok: true, hub: origin, slot: slotName, removed });
2230
2284
  return 0;
2231
2285
  }
2232
2286
  /**
@@ -2239,10 +2293,11 @@ async function dispatchLogout(io, args) {
2239
2293
  */
2240
2294
  async function dispatchConnect(io, args) {
2241
2295
  const origin = resolveHub(io, args);
2242
- const cred = readCredential(io, origin);
2296
+ const slot = resolveSlot(args);
2297
+ const cred = readCredential(io, origin, slot);
2243
2298
  if (!cred)
2244
- throw new CliError(`no stored credential for ${origin} — run \`owenloop login\` first`);
2245
- const { identity } = await verifyCredential(io, origin, cred);
2299
+ throw new CliError(emptySlotMessage(origin, slot));
2300
+ const { identity } = await verifyCredential(io, origin, slot, cred);
2246
2301
  const path = hubBindingPath(io.cwd);
2247
2302
  const existing = readHubBinding(path);
2248
2303
  const switched = existing !== null && existing.hub !== origin;
@@ -2274,6 +2329,7 @@ async function dispatchPush(io, args) {
2274
2329
  const defsDir = last(args, 'defs') ?? io.env.OWENLOOP_DEFS ?? join(io.cwd, 'workflows');
2275
2330
  const dryRun = flag(args, 'dry-run');
2276
2331
  const force = flag(args, 'force');
2332
+ const slot = resolveSlot(args);
2277
2333
  // Require a project binding.
2278
2334
  const bindingPath = hubBindingPath(io.cwd);
2279
2335
  const binding = readHubBinding(bindingPath);
@@ -2301,9 +2357,9 @@ async function dispatchPush(io, args) {
2301
2357
  throw new CliError(`this project is bound to ${origin}, not ${requested} — re-run \`owenloop connect\` to rebind`);
2302
2358
  }
2303
2359
  }
2304
- let cred = readCredential(io, origin);
2360
+ let cred = readCredential(io, origin, slot);
2305
2361
  if (!cred)
2306
- throw new CliError(`no stored credential for ${origin} — run \`owenloop login\``);
2362
+ throw new CliError(emptySlotMessage(origin, slot));
2307
2363
  // Load defs (same machinery as lint/add).
2308
2364
  if (!existsSync(defsDir))
2309
2365
  throw new CliError(`defs directory not found: ${defsDir}`);
@@ -2390,7 +2446,7 @@ async function dispatchPush(io, args) {
2390
2446
  }
2391
2447
  // Fetch the server's own list once — the diff source of truth. Always
2392
2448
  // fetched, even under --force, so the new/changed labels stay accurate.
2393
- const { res: listRes, cred: listCred } = await authedGet(io, origin, cred, '/api/workflows');
2449
+ const { res: listRes, cred: listCred } = await authedGet(io, origin, slot, cred, '/api/workflows');
2394
2450
  assertAuthOk(listRes, listCred, origin);
2395
2451
  cred = listCred;
2396
2452
  let serverMap;
@@ -2420,7 +2476,7 @@ async function dispatchPush(io, args) {
2420
2476
  return 0;
2421
2477
  }
2422
2478
  // Refresh an expiring oauth token once up front (per-request 401 refresh below covers mid-batch expiry).
2423
- cred = await ensureFreshOAuth(io, origin, cred);
2479
+ cred = await ensureFreshOAuth(io, origin, slot, cred);
2424
2480
  const pushedNames = [];
2425
2481
  const noopNames = [];
2426
2482
  const failed = [];
@@ -2431,7 +2487,7 @@ async function dispatchPush(io, args) {
2431
2487
  try {
2432
2488
  let res = await createWorkflowRequest(io, origin, cred, c.yaml);
2433
2489
  if (res.status === 401 && cred.kind === 'oauth') {
2434
- cred = await refreshOAuth(io, origin, cred);
2490
+ cred = await refreshOAuth(io, origin, slot, cred);
2435
2491
  res = await createWorkflowRequest(io, origin, cred, c.yaml);
2436
2492
  }
2437
2493
  if (res.status === 401) {