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/dist/hub.js CHANGED
@@ -10,6 +10,34 @@
10
10
  * etc.) so this module stays trivially testable and `cli.ts` doesn't widen its
11
11
  * export surface.
12
12
  *
13
+ * The keychain backend selection and the read side of credential storage also
14
+ * live here (`defaultKeychain` / `resolveKeychain` / `credentialBackend` /
15
+ * `readStoredCredential`): the `security` shell-out is synchronous and
16
+ * injectable, so it stays consistent with this module's network-free, testable
17
+ * charter, and it lets the public barrel (`src/index.ts`) export a supported
18
+ * read-only `readStoredCredential` without pulling in `cli.ts` (which the
19
+ * core/hub boundary lint forbids). `cli.ts` keeps thin wrappers so there is one
20
+ * implementation of backend selection, not two.
21
+ *
22
+ * Backend precedence is **external → keychain → file**, resolved once in
23
+ * `credentialBackend`. The external backend is an OPTIONAL, explicitly
24
+ * configured command (`OWENLOOP_CREDENTIAL_COMMAND`) that prints a credential
25
+ * for the requested `(origin, slot)` — it gives non-macOS workers, CI, and
26
+ * users whose secrets live in a secret manager a supported way to feed owenloop
27
+ * a credential without owenloop learning about any specific manager. When it is
28
+ * configured it is AUTHORITATIVE: a failure of any kind is a loud error and
29
+ * never a fallthrough to a store (see `runCredentialCommand`). When it is not
30
+ * configured, behaviour is byte-for-byte what it was before it existed.
31
+ *
32
+ * Credentials are keyed by **slot**, not by origin alone: one stored credential
33
+ * per `(normalized origin, principal-account)` pair, the slot being `human` or
34
+ * `agent:<account>` (account defaults to `default`). See `CredentialSlotSelector`
35
+ * and `credentialSlot`. A reader must always name the slot it wants — it can
36
+ * never guess — so a host or CLI verb can never accidentally read the wrong
37
+ * principal's credential. There is deliberately NO migration from the older
38
+ * one-slot-per-origin keying: entries written under it are simply never found
39
+ * and read as absent; the upgrade step is re-running `login`.
40
+ *
13
41
  * `.owenloop/hub.json` is a pure binding (which hub this project publishes to)
14
42
  * — there is no client-side push ledger. `push` diffs local defs against the
15
43
  * server's own `hash` (`GET /api/workflows`, see `computeServerDiff`), and
@@ -36,6 +64,7 @@
36
64
  * `push` diff), so keeping it in this module — not in engine core — is what
37
65
  * lets `defs.ts` stay host/hub-agnostic.
38
66
  */
67
+ import { execFileSync } from 'node:child_process';
39
68
  import { createHash, randomBytes } from 'node:crypto';
40
69
  import { chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
41
70
  import { basename, dirname, join } from 'node:path';
@@ -157,6 +186,87 @@ export function pkcePair() {
157
186
  export function randomState() {
158
187
  return base64url(randomBytes(16));
159
188
  }
189
+ /**
190
+ * Legal agent account names. Deliberately conservative — alphanumeric start,
191
+ * then alphanumerics plus `.`/`_`/`-`, 1..64 chars — so an empty, over-long, or
192
+ * exotic name can never reach the keychain or the file key. Widening this later
193
+ * is a two-way door; narrowing it would not be.
194
+ */
195
+ const ACCOUNT_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
196
+ /** The default agent account when `--as agent` names none. */
197
+ const DEFAULT_ACCOUNT = 'default';
198
+ /**
199
+ * Resolve a selector to its slot string: `'human'` or `` `agent:${account}` ``.
200
+ *
201
+ * This is the ONE place account defaulting and validation happen — every read,
202
+ * write, and delete path funnels through it, so no call site re-implements the
203
+ * `agent:` concatenation. Throws on an invalid account name, and on `account`
204
+ * supplied alongside `principal: 'human'`: TypeScript's excess-property check
205
+ * does not reliably reject that against a union, so it is a runtime error too
206
+ * rather than a silently ignored argument.
207
+ *
208
+ * `agent:human` cannot collide with `human` by construction — the `agent:`
209
+ * prefix differs — so no extra guard is needed.
210
+ */
211
+ export function credentialSlot(sel) {
212
+ if (sel.principal === 'human') {
213
+ if (sel.account !== undefined) {
214
+ throw new Error("credential slot: `account` is only meaningful with principal 'agent', not 'human'");
215
+ }
216
+ return 'human';
217
+ }
218
+ if (sel.principal !== 'agent') {
219
+ throw new Error(`credential slot: unknown principal '${String(sel.principal)}'`);
220
+ }
221
+ const account = sel.account ?? DEFAULT_ACCOUNT;
222
+ if (typeof account !== 'string' || !ACCOUNT_RE.test(account)) {
223
+ throw new Error(`invalid agent account '${String(account)}' — expected 1-64 chars matching [A-Za-z0-9][A-Za-z0-9._-]*`);
224
+ }
225
+ return `agent:${account}`;
226
+ }
227
+ /**
228
+ * The keychain SERVICE for a hub origin; the slot is the keychain ACCOUNT.
229
+ * `origin` must already be `normalizeOrigin`d — every call site normalizes
230
+ * first, so SEC-2 (remote plaintext rejected) happens before any keychain or
231
+ * filesystem access.
232
+ */
233
+ export function keychainServiceFor(normalizedOrigin) {
234
+ return `owenloop:${normalizedOrigin}`;
235
+ }
236
+ /**
237
+ * Shape-guard a stored credential value, returning `null` when it is not a
238
+ * well-formed `Credential`. Used on BOTH backends so "a corrupt entry reads as
239
+ * absent" is symmetric: previously the keychain path did an unchecked
240
+ * `JSON.parse(...) as Credential` and the file path validated nothing at all,
241
+ * so a truncated or hand-edited entry could surface as a bogus credential
242
+ * instead of a clean miss.
243
+ */
244
+ export function parseCredential(raw) {
245
+ if (typeof raw !== 'object' || raw === null)
246
+ return null;
247
+ const c = raw;
248
+ if (typeof c.accessToken !== 'string' || c.accessToken === '')
249
+ return null;
250
+ if (c.kind === 'agent' || c.kind === 'oauth-pasted') {
251
+ return { kind: c.kind, accessToken: c.accessToken };
252
+ }
253
+ if (c.kind === 'oauth') {
254
+ if (typeof c.refreshToken !== 'string' || c.refreshToken === '')
255
+ return null;
256
+ if (typeof c.expiresAt !== 'number' || !Number.isFinite(c.expiresAt))
257
+ return null;
258
+ if (typeof c.clientId !== 'string' || c.clientId === '')
259
+ return null;
260
+ return {
261
+ kind: 'oauth',
262
+ accessToken: c.accessToken,
263
+ refreshToken: c.refreshToken,
264
+ expiresAt: c.expiresAt,
265
+ clientId: c.clientId,
266
+ };
267
+ }
268
+ return null;
269
+ }
160
270
  /** The user-level config dir (never the project dir). Derives from the caller's env. */
161
271
  export function configDir(env) {
162
272
  const xdg = env.XDG_CONFIG_HOME;
@@ -170,15 +280,30 @@ export function configDir(env) {
170
280
  export function credentialFilePath(env) {
171
281
  return join(configDir(env), 'credentials.json');
172
282
  }
173
- /** Read the credential file; a missing file is an empty store, not an error. */
283
+ /**
284
+ * Read the credential file; a missing file is an empty store, not an error.
285
+ *
286
+ * A file whose `version` is not `2` also reads as an EMPTY store — no throw, no
287
+ * migration, no hybrid write. That is how entries under the older
288
+ * one-slot-per-origin keying become invisible (there are no external users, so
289
+ * the documented upgrade step is re-running `login`). Stated deliberately: the
290
+ * next write then replaces such a file wholesale, which is acceptable because
291
+ * its entries are unreachable by design.
292
+ *
293
+ * Genuinely broken JSON, or a `hubs` that is not an object, still throws —
294
+ * "corrupt reads as absent" is about a corrupt ENTRY (see `parseCredential`),
295
+ * not a destroyed file.
296
+ */
174
297
  export function readCredentialFile(path) {
175
298
  if (!existsSync(path))
176
- return { version: 1, hubs: {} };
299
+ return { version: 2, hubs: {} };
177
300
  const parsed = JSON.parse(readFileSync(path, 'utf8'));
178
- if (!parsed || typeof parsed !== 'object' || typeof parsed.hubs !== 'object') {
301
+ if (!parsed || typeof parsed !== 'object' || typeof parsed.hubs !== 'object' || parsed.hubs === null) {
179
302
  throw new Error(`malformed credential file at ${path}`);
180
303
  }
181
- return { version: 1, hubs: parsed.hubs };
304
+ if (parsed.version !== 2)
305
+ return { version: 2, hubs: {} };
306
+ return { version: 2, hubs: parsed.hubs };
182
307
  }
183
308
  /**
184
309
  * Write `data` to `path` atomically, refusing a symlinked (or directory)
@@ -235,6 +360,256 @@ export function writeCredentialFile(path, file) {
235
360
  chmodSync(dir, 0o700);
236
361
  writeFileAtomic(path, `${JSON.stringify(file, null, 2)}\n`, { mode: 0o600 });
237
362
  }
363
+ /**
364
+ * The default macOS keychain backend (generic passwords under service
365
+ * `owenloop:<origin>`, account = the credential slot). The secret is fed through
366
+ * the `security -i` command stream on stdin, never as a `-w` argv value, so it
367
+ * never appears in `ps`/shell history. Returns `undefined` off macOS or when
368
+ * `OWENLOOP_NO_KEYCHAIN=1`, so callers fall back to the 0600 credential file.
369
+ */
370
+ export function defaultKeychain(env) {
371
+ if (env.OWENLOOP_NO_KEYCHAIN === '1')
372
+ return undefined;
373
+ if (process.platform !== 'darwin')
374
+ return undefined;
375
+ return {
376
+ get(service, account) {
377
+ try {
378
+ const out = execFileSync('security', ['find-generic-password', '-s', service, '-a', account, '-w'], {
379
+ encoding: 'utf8',
380
+ stdio: ['ignore', 'pipe', 'ignore'],
381
+ });
382
+ return out.replace(/\n$/, '');
383
+ }
384
+ catch {
385
+ return null; // not found (errSecItemNotFound) — treated as "no credential"
386
+ }
387
+ },
388
+ set(service, account, value) {
389
+ // `security -i` reads newline-terminated commands from stdin; the secret
390
+ // rides in that stdin stream (single-quoted), never on this process's argv.
391
+ // The service string now carries `:` and `//` — inert for `security`, but
392
+ // the single-quote escaping stays as the general guard it always was.
393
+ const sq = (s) => `'${s.replace(/'/g, `'\\''`)}'`;
394
+ const cmd = `add-generic-password -U -s ${sq(service)} -a ${sq(account)} -w ${sq(value)}\n`;
395
+ execFileSync('security', ['-i'], { input: cmd, stdio: ['pipe', 'ignore', 'ignore'] });
396
+ },
397
+ delete(service, account) {
398
+ try {
399
+ execFileSync('security', ['delete-generic-password', '-s', service, '-a', account], {
400
+ stdio: 'ignore',
401
+ });
402
+ }
403
+ catch {
404
+ // Not found — already absent; a no-op delete is success.
405
+ }
406
+ },
407
+ };
408
+ }
409
+ /**
410
+ * The configured external credential command, or `undefined` when it is unset
411
+ * or blank.
412
+ *
413
+ * Configuration is a single environment variable, `OWENLOOP_CREDENTIAL_COMMAND`,
414
+ * read off the caller-supplied `env` record like every other knob in this module
415
+ * (`OWENLOOP_NO_KEYCHAIN`, `OWENLOOP_HUB`, the `*_TIMEOUT_MS` overrides) — never
416
+ * `process.env` directly, so hosts and tests stay hermetic. Explicit config
417
+ * only: there is deliberately no discovery, no scanning for helper binaries, and
418
+ * no implicit default.
419
+ *
420
+ * An all-whitespace value is treated as NOT configured, and that decision is
421
+ * made HERE rather than at each call site, so "is the external backend active?"
422
+ * has exactly one answer.
423
+ */
424
+ export function externalCredentialCommand(env) {
425
+ const raw = env.OWENLOOP_CREDENTIAL_COMMAND;
426
+ if (typeof raw !== 'string' || raw.trim() === '')
427
+ return undefined;
428
+ return raw;
429
+ }
430
+ /** Request deadline for the external credential command; see `runCredentialCommand`. */
431
+ const CREDENTIAL_COMMAND_TIMEOUT_MS = 10_000;
432
+ /** Cap on the command's stdout, so a runaway helper cannot exhaust memory. */
433
+ const CREDENTIAL_COMMAND_MAX_BUFFER = 1024 * 1024;
434
+ function credentialCommandTimeoutMs(env) {
435
+ const override = Number(env.OWENLOOP_CREDENTIAL_COMMAND_TIMEOUT_MS);
436
+ return Number.isFinite(override) && override > 0 ? override : CREDENTIAL_COMMAND_TIMEOUT_MS;
437
+ }
438
+ /**
439
+ * Run the configured external credential command and return the credential it
440
+ * printed. THROWS on every failure — it never returns `null` and never falls
441
+ * through to a store.
442
+ *
443
+ * That asymmetry with the stores is deliberate. In a store a corrupt entry reads
444
+ * as absent (REL-6, see `parseCredential`); from the external command a corrupt
445
+ * result is a hard ERROR, because a configured command is AUTHORITATIVE and a
446
+ * silent miss there is exactly the failure this feature exists to prevent — a
447
+ * half-working helper quietly handing back a stale local key.
448
+ *
449
+ * Invocation contract:
450
+ * - The configured value is a shell command line, run as `/bin/sh -c <command>`,
451
+ * so a user can write `my-helper --hub prod` or a pipeline.
452
+ * - Context reaches the child through the ENVIRONMENT, never argv, so nothing
453
+ * has to be shell-quoted into the command string and the secret never rides on
454
+ * a command line: `OWENLOOP_CREDENTIAL_ORIGIN` (the NORMALIZED origin) and
455
+ * `OWENLOOP_CREDENTIAL_SLOT` (exactly what `credentialSlot()` returned).
456
+ * - `OWENLOOP_CREDENTIAL_COMMAND` is DELETED from the child's environment. That
457
+ * deletion is deliberate: a helper that shells back into `owenloop` would
458
+ * otherwise recurse forever.
459
+ * - stdout must be a JSON object that satisfies `parseCredential` — the same one
460
+ * guard both stores use, so there is exactly one definition of "a well-formed
461
+ * credential". A bare token is deliberately NOT accepted; inferring `kind`
462
+ * would duplicate `login`'s token-kind logic.
463
+ * - stdio is `['ignore', 'pipe', 'inherit']`: the helper's own diagnostics go
464
+ * straight to the user's stderr and owenloop never captures, stores, or echoes
465
+ * them (captured stderr could carry the secret into an error message or a
466
+ * log). stdout is captured and never logged.
467
+ */
468
+ function runCredentialCommand(command, env, origin, slot) {
469
+ // The command string itself came from the user's own config, not a secret
470
+ // store, so naming it is useful. Captured stdout is or contains the SECRET and
471
+ // must never reach an error message.
472
+ const fail = (detail) => {
473
+ throw new Error(`external credential command failed for ${origin} slot \`${slot}\`: ${detail}`);
474
+ };
475
+ const childEnv = {};
476
+ for (const [k, v] of Object.entries(env)) {
477
+ if (v !== undefined)
478
+ childEnv[k] = v;
479
+ }
480
+ delete childEnv.OWENLOOP_CREDENTIAL_COMMAND;
481
+ childEnv.OWENLOOP_CREDENTIAL_ORIGIN = origin;
482
+ childEnv.OWENLOOP_CREDENTIAL_SLOT = slot;
483
+ const timeout = credentialCommandTimeoutMs(env);
484
+ let out;
485
+ try {
486
+ out = execFileSync('/bin/sh', ['-c', command], {
487
+ encoding: 'utf8',
488
+ env: childEnv,
489
+ stdio: ['ignore', 'pipe', 'inherit'],
490
+ timeout,
491
+ maxBuffer: CREDENTIAL_COMMAND_MAX_BUFFER,
492
+ });
493
+ }
494
+ catch (e) {
495
+ const err = e;
496
+ if (err.code === 'ETIMEDOUT' || (err.status === null && typeof err.signal === 'string')) {
497
+ return fail(`command timed out after ${timeout}ms`);
498
+ }
499
+ if (typeof err.status === 'number')
500
+ return fail(`command exited with status ${err.status}`);
501
+ // Only the errno CODE is surfaced — it is a fixed token (ENOENT, ENOBUFS,
502
+ // …) that can never carry the child's output.
503
+ return fail(`command could not be run (${typeof err.code === 'string' ? err.code : 'unknown error'})`);
504
+ }
505
+ const trimmed = out.trim();
506
+ if (trimmed === '')
507
+ return fail('command produced no output');
508
+ let decoded;
509
+ try {
510
+ decoded = JSON.parse(trimmed);
511
+ }
512
+ catch {
513
+ return fail('command produced output that is not JSON');
514
+ }
515
+ const cred = parseCredential(decoded);
516
+ if (cred === null)
517
+ return fail('command produced a value that is not a well-formed credential');
518
+ return cred;
519
+ }
520
+ /**
521
+ * Resolve the keychain backend for this env, honoring the hard override:
522
+ * `OWENLOOP_NO_KEYCHAIN=1` forces the file backend (`undefined`) EVEN when a
523
+ * keychain is injected; otherwise the injected backend wins, else the platform
524
+ * default.
525
+ */
526
+ export function resolveKeychain(env, injected) {
527
+ if (env.OWENLOOP_NO_KEYCHAIN === '1')
528
+ return undefined;
529
+ return injected ?? defaultKeychain(env);
530
+ }
531
+ /**
532
+ * `OWENLOOP_NO_KEYCHAIN=1` deliberately does NOT affect the external branch: it
533
+ * selects between the two LOCAL stores, and the external command sits in front
534
+ * of both.
535
+ */
536
+ export function credentialBackend(env, injected) {
537
+ const command = externalCredentialCommand(env);
538
+ if (command !== undefined)
539
+ return { kind: 'external', command };
540
+ const kc = resolveKeychain(env, injected);
541
+ return kc ? { kind: 'keychain', kc } : { kind: 'file' };
542
+ }
543
+ /**
544
+ * Read the stored hub credential for `origin` **in the named slot** from the
545
+ * chosen backend ONLY — the supported, read-only programmatic surface
546
+ * (owenwork's CredentialReader seam wires to this once released). Secret hygiene
547
+ * is unchanged: this function never logs or echoes the returned credential, and
548
+ * there is deliberately no write/delete companion on the public surface —
549
+ * `login` / `logout` remain the only way to store or remove a credential.
550
+ *
551
+ * `opts` and its `principal` are both required, so a caller can never
552
+ * accidentally read the wrong principal's credential:
553
+ *
554
+ * ```ts
555
+ * readStoredCredential(origin, { principal: 'human' });
556
+ * readStoredCredential(origin, { principal: 'agent' }); // agent:default
557
+ * readStoredCredential(origin, { principal: 'agent', account: 'ci' }); // agent:ci
558
+ * ```
559
+ *
560
+ * Passing `account` with `principal: 'human'` throws (see `credentialSlot`),
561
+ * because TypeScript's excess-property check does not reliably reject it
562
+ * against a union.
563
+ *
564
+ * `origin` is normalized (idempotent on already-normalized input, so the CLI's
565
+ * pre-normalized callers are unaffected) BEFORE any keychain or filesystem
566
+ * access, so the storage key matches what `login` persisted and an invalid or
567
+ * plaintext-remote origin throws at normalization (SEC-2), exactly as the CLI
568
+ * would.
569
+ *
570
+ * Backend is selected once (`credentialBackend`), with precedence external →
571
+ * keychain → file. A keychain-backed read NEVER falls through to the file (that
572
+ * fallback was the REL-6 shadowing bug), and a corrupt entry reads as absent
573
+ * (`null`) on either store — never as a reason to consult the other. The file
574
+ * backend derives its path from the supplied `env` (HOME / XDG_CONFIG_HOME),
575
+ * never `process.env` directly, so a caller passing `opts.env` stays hermetic;
576
+ * only the top-level default falls back to `process.env`.
577
+ *
578
+ * **When `OWENLOOP_CREDENTIAL_COMMAND` is configured this function can THROW
579
+ * instead of returning `null`**, and it does not consult a store at all. The
580
+ * command is authoritative, so a nonzero exit, a timeout, empty output, or
581
+ * output that is not a well-formed credential is a loud error naming the origin
582
+ * and the slot — never a silent fallthrough to a stale local entry. See
583
+ * `runCredentialCommand`. When it is NOT configured, behaviour is exactly what
584
+ * it has always been.
585
+ */
586
+ export function readStoredCredential(origin, opts) {
587
+ const env = opts.env ?? process.env;
588
+ // Normalization runs FIRST, so SEC-2 (plaintext remote origins rejected) and
589
+ // slot validation both apply to the external path too — a bad origin or
590
+ // account never reaches the child process.
591
+ const key = normalizeOrigin(origin);
592
+ const slot = credentialSlot(opts);
593
+ const backend = credentialBackend(env, opts.keychain);
594
+ if (backend.kind === 'external') {
595
+ return runCredentialCommand(backend.command, env, key, slot);
596
+ }
597
+ if (backend.kind === 'keychain') {
598
+ const raw = backend.kc.get(keychainServiceFor(key), slot);
599
+ if (!raw)
600
+ return null;
601
+ let decoded;
602
+ try {
603
+ decoded = JSON.parse(raw);
604
+ }
605
+ catch {
606
+ return null; // corrupt entry — treat as absent; do NOT consult the file
607
+ }
608
+ return parseCredential(decoded);
609
+ }
610
+ const file = readCredentialFile(credentialFilePath(env));
611
+ return parseCredential(file.hubs[key]?.[slot]);
612
+ }
238
613
  export function hubBindingPath(cwd) {
239
614
  return join(cwd, '.owenloop', 'hub.json');
240
615
  }
package/dist/index.d.ts CHANGED
@@ -18,7 +18,8 @@ export type { CreateEngineOpts, CreatedEngine } from './factory.ts';
18
18
  export { Store, openStore, StoreVersionError } from './store.ts';
19
19
  export type { ArtifactRow, RunRow, TaskRow, WorkflowRow } from './store.ts';
20
20
  export { buildDef, DefError, expandIncludes, finalizeDefs, hashDef, lintDef, loadDefFile, loadDefs, loadDefsRaw, parseDef, SUPPORTED_ENGINE_VERSION, validateDef } from './defs.ts';
21
- export { hashDefForHub } from './hub.ts';
21
+ export { credentialSlot, hashDefForHub, keychainServiceFor, normalizeOrigin, readStoredCredential } from './hub.ts';
22
+ export type { Credential, CredentialSlotSelector, Keychain, ReadStoredCredentialOpts } from './hub.ts';
22
23
  export type { DefLoadFailure } from './defs.ts';
23
24
  export { buildGraph, buildTrace, eligibleFirings, graphToDot, graphToMermaid, isStalled, modelCheck, workflowStatus, } from './model.ts';
24
25
  export type { ArtifactMap, Blocker, Firing, TimeFacts, WorkflowStatus } from './model.ts';
package/dist/index.js CHANGED
@@ -15,7 +15,7 @@ export { Engine } from "./engine.js";
15
15
  export { createEngine } from "./factory.js";
16
16
  export { Store, openStore, StoreVersionError } from "./store.js";
17
17
  export { buildDef, DefError, expandIncludes, finalizeDefs, hashDef, lintDef, loadDefFile, loadDefs, loadDefsRaw, parseDef, SUPPORTED_ENGINE_VERSION, validateDef } from "./defs.js";
18
- export { hashDefForHub } from "./hub.js";
18
+ export { credentialSlot, hashDefForHub, keychainServiceFor, normalizeOrigin, readStoredCredential } from "./hub.js";
19
19
  export { buildGraph, buildTrace, eligibleFirings, graphToDot, graphToMermaid, isStalled, modelCheck, workflowStatus, } from "./model.js";
20
20
  export { parseConsume, parseProduce, } from "./paths.js";
21
21
  export { assertValidSchema, summarizeIssues, validateValue } from "./schema.js";
package/docs/cli.md CHANGED
@@ -33,10 +33,10 @@ positional or the next `--flag`, never consumed as this flag's argument. Use
33
33
  | `defs` | list available workflow definitions |
34
34
  | `add <owner>/<repo>[@ref]` | fetch, validate, and install a repo's workflow defs from GitHub (public repos only) — see below |
35
35
  | `add --recover` | finish or undo a crash-interrupted install, offline — no network call — see below |
36
- | `login [--hub <url>] [--with-token]` | authenticate the CLI against a hub — loopback OAuth, or `--with-token` from stdin — see [Hub](#hub-login--connect--push--logout) |
37
- | `connect [--hub <url>]` | bind this project to a hub (writes `.owenloop/hub.json`) and verify the credential |
38
- | `push [<defName>...] [--force] [--dry-run]` | publish local workflow defs to the bound hub (idempotent against the hub's own def hashes) |
39
- | `logout [--hub <url>]` | delete the stored credential for a hub |
36
+ | `login [--hub <url>] [--with-token] [--as <slot>]` | authenticate the CLI against a hub — loopback OAuth, or `--with-token` from stdin — see [Hub](#hub-login--connect--push--logout) |
37
+ | `connect [--hub <url>] [--as <slot>]` | bind this project to a hub (writes `.owenloop/hub.json`) and verify the credential |
38
+ | `push [<defName>...] [--force] [--dry-run] [--as <slot>]` | publish local workflow defs to the bound hub (idempotent against the hub's own def hashes) |
39
+ | `logout [--hub <url>] [--as <slot>]` | delete the stored credential for a hub |
40
40
  | `create <def> [--title t] [--provide name=json …] [--param k=v …]` | start an instance; prints `{workflow}` |
41
41
  | `provide <wf> <name> [--value json]` | supply a seeded input after the fact |
42
42
  | `tick <wf> [--now=<ms>] [--shallow] [--label <l>]…` | claim and emit eligible **orders** (the jobs to run); deep by default — also descends into live `calls:` children (`--shallow` = this instance only); repeatable `--label` claims unlabeled steps plus matching-label steps — see below |
@@ -337,20 +337,83 @@ that can't call the hub is never written to disk):
337
337
  table). An `olp_`-prefixed **agent** token or an `mcpat_`-prefixed **access**
338
338
  token is accepted; anything else is rejected before any network call.
339
339
 
340
+ **Credential slots (`--as`).** A hub origin holds more than one credential, each
341
+ in a named **slot**, so a human sign-in and any number of agent tokens coexist
342
+ on the same machine without overwriting each other:
343
+
344
+ | `--as` value | slot | who it is |
345
+ |---|---|---|
346
+ | *(omitted)* | depends on the credential — see below | |
347
+ | `human` | `human` | you, via loopback OAuth or a pasted `mcpat_` token |
348
+ | `agent` | `agent:default` | an agent token with no account name |
349
+ | `agent:<account>` | `agent:<account>` | a named agent, e.g. `agent:ci` |
350
+
351
+ An account name is 1–64 characters matching `[A-Za-z0-9][A-Za-z0-9._-]*`;
352
+ anything else is a usage error. With `--as` omitted, a credential lands in the
353
+ slot it belongs to: loopback OAuth and pasted `mcpat_` tokens go to `human`,
354
+ `olp_` agent tokens go to `agent:default`. The two contradictions are refused as
355
+ usage errors **before any network call**, so nothing unverified is stored:
356
+ `--as human` with an `olp_` token, and `--as agent[:…]` with an OAuth or pasted
357
+ human credential. `login`'s JSON reports the `slot` it wrote.
358
+
359
+ `connect`, `push`, and `logout` take the same `--as` and act on exactly that
360
+ slot — there is no fallback to another slot, so `push --as agent:ci` with an
361
+ empty `agent:ci` fails rather than quietly pushing as you. `logout` without
362
+ `--as` removes only `human`.
363
+
340
364
  **Where the credential lands.** On macOS it goes into the login **Keychain**
341
- (`security`, service `owenloop-hub`, one item per hub origin) with the secret
342
- fed over stdin, never on the command line. Elsewhere — or with
343
- `OWENLOOP_NO_KEYCHAIN=1` — it falls back to a `0600` file at
365
+ (`security`, service `owenloop:<hub origin>`, one item per slot, with the slot
366
+ name as the account) with the secret fed over stdin, never on the command line.
367
+ Elsewhere — or with `OWENLOOP_NO_KEYCHAIN=1` — it falls back to a `0600` file at
344
368
  `$XDG_CONFIG_HOME/owenloop/credentials.json` (or `~/.config/owenloop/…`) inside
345
- a `0700` directory. Either way the token is never written into the repo or a
346
- `.env`. `login`'s JSON reports `storage: "keychain" | "file"` and `kind`, and
347
- prints **no token value** to stdout/stderr.
369
+ a `0700` directory, keyed `hubs[origin][slot]`. Either way the token is never
370
+ written into the repo or a `.env`. `login`'s JSON reports `storage: "keychain" |
371
+ "file"` and `kind`, and prints **no token value** to stdout/stderr. A credential
372
+ stored by an earlier release used a different keying and is **not** read; there
373
+ is deliberately no migration, so re-run `owenloop login`.
348
374
 
349
375
  The backend is chosen once from your platform and env and then used for every
350
376
  read and write — a keychain-backed CLI never silently drops to the file store.
351
377
  If the keychain write fails (locked or unavailable), `login` errors out instead
352
378
  of writing the secret elsewhere: unlock the keychain, or set
353
- `OWENLOOP_NO_KEYCHAIN=1` to select the file store up front.
379
+ `OWENLOOP_NO_KEYCHAIN=1` to select the file store up front. Programmatic hosts
380
+ can read (only read) a stored credential through the same backend logic via the
381
+ package's exported `readStoredCredential` — see
382
+ [Embedding](embedding.md#whats-exported).
383
+
384
+ **Supplying the credential from your own tooling.** If your secrets live in a
385
+ secret manager, or you run on a host with no keychain, set
386
+ `OWENLOOP_CREDENTIAL_COMMAND` to a shell command line that prints a credential.
387
+ It takes precedence over both stores, so the full order is **external command →
388
+ keychain → file**, still chosen once. Nothing is auto-detected: the variable is
389
+ the only way to turn this on, and an unset or blank value leaves everything
390
+ exactly as described above.
391
+
392
+ The contract:
393
+
394
+ - The command runs as `/bin/sh -c "<your command>"`, so a pipeline or arguments
395
+ work (`my-helper --hub prod`).
396
+ - Context arrives in the **environment**, not on the command line:
397
+ `OWENLOOP_CREDENTIAL_ORIGIN` (the normalized hub origin) and
398
+ `OWENLOOP_CREDENTIAL_SLOT` (`human` or `agent:<account>`). Your command should
399
+ return the credential for exactly that pair.
400
+ - `OWENLOOP_CREDENTIAL_COMMAND` is **removed** from the command's own
401
+ environment, so a helper that shells back into `owenloop` cannot recurse.
402
+ - It must print a credential as a JSON object on **stdout** — the same shape
403
+ stored in `credentials.json`, e.g. `{"kind":"agent","accessToken":"olp_…"}` or
404
+ a full `{"kind":"oauth", …}` object. A bare token is not accepted. stdout is
405
+ captured and never logged; the command's **stderr passes straight through** to
406
+ your terminal, so put diagnostics there — never the secret.
407
+ - It must finish within 10s, overridable with
408
+ `OWENLOOP_CREDENTIAL_COMMAND_TIMEOUT_MS`.
409
+
410
+ A configured command is **authoritative**: a nonzero exit, a timeout, empty
411
+ output, or output that is not a well-formed credential is a hard error naming
412
+ the hub and the slot — never a quiet fall back to a keychain or file entry,
413
+ which would risk handing back a stale key. For the same reason `login` refuses
414
+ to run while the variable is set (unset it if you want to use the local store
415
+ again), and a refreshed OAuth token is not written to the local store — your
416
+ command owns the credential's lifecycle. `logout` still clears local entries.
354
417
 
355
418
  Both branches verify the credential against `GET /api/whoami` before storing
356
419
  it — a `401` there means the credential is never written to disk. On success
package/docs/embedding.md CHANGED
@@ -262,6 +262,40 @@ all the shared types (`Order`, `CommitResult`, `WorkflowStatus`, `WorkflowDef`,
262
262
  `EngineEvent`, `EngineListener`, …). For most hosts, `createEngine` + the engine methods + the `Order` /
263
263
  `CommitResult` / `WorkflowStatus` types are the whole surface you need.
264
264
 
265
+ The index also exports a **read-only credential surface** for hosts that need
266
+ to read a stored hub credential through owenloop's own store logic instead of
267
+ duplicating it: `readStoredCredential(origin, opts)` returns the `Credential`
268
+ for a hub origin **and slot** (or `null` if none is stored), using the same
269
+ backend selection as the CLI — macOS Keychain, or the `0600` credentials file
270
+ elsewhere / with `OWENLOOP_NO_KEYCHAIN=1` (see
271
+ [where the credential lands](cli.md#hub-login--connect--push--logout)). The
272
+ backend is chosen once and a keychain-backed read never falls through to the
273
+ file; a corrupt keychain entry reads as absent. The origin is normalized with
274
+ the exported `normalizeOrigin` (invalid or plaintext-remote origins throw,
275
+ exactly as in the CLI), and `ReadStoredCredentialOpts` lets tests and hosts
276
+ inject `env` and a `Keychain` backend — whose `get`/`set`/`delete` now take
277
+ `(service, account)`, the account being the slot.
278
+
279
+ `opts` is required, and carries the slot selector: `{ principal: 'human' }` or
280
+ `{ principal: 'agent', account?: string }` (`account` defaults to `'default'`,
281
+ and is only meaningful for `'agent'`). The companion exports `credentialSlot`
282
+ (selector → the canonical slot string `human` / `agent:<account>`, throwing on
283
+ an invalid account name) and `keychainServiceFor` (normalized origin → the
284
+ keychain service name) let a host address the same slots the CLI does without
285
+ re-deriving the keying. Slots never fall back to one another: an empty
286
+ `agent:ci` reads as `null` even when `human` is populated. The function never
287
+ logs or echoes the secret, and there is deliberately no write or delete companion on the public
288
+ surface — `login`/`logout` remain the only way to store or remove a credential.
289
+
290
+ One behaviour to handle: when the user has set `OWENLOOP_CREDENTIAL_COMMAND` (an
291
+ external command that supplies the credential, ahead of both stores — see
292
+ [where the credential lands](cli.md#hub-login--connect--push--logout)),
293
+ `readStoredCredential` consults that command instead of any store, and a failing
294
+ command **throws** rather than returning `null`. So in that mode `null` still
295
+ means "no credential", but an exception means "the configured command could not
296
+ produce one" — surface its message rather than treating it as an empty slot,
297
+ because falling back to a local store is exactly what the setting forbids.
298
+
265
299
  `SUPPORTED_ENGINE_VERSION` is the programmatic form of the design.md §27
266
300
  engine-version contract — the highest `engine:` a def may declare and still load.
267
301
  Tooling can preflight-check a def's `engine:` field against it before handing the
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "owenloop",
3
- "version": "0.3.1",
3
+ "version": "0.4.0",
4
4
  "description": "Deterministic rails for agentic workflows. Declare steps and dependencies; the engine guarantees order, redoes what changes invalidate, and stops what keeps failing — instead of hoping the agent follows through.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "typicalday",