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/defs.js CHANGED
@@ -1006,6 +1006,18 @@ export function validateDef(def) {
1006
1006
  errors.push(`step '${l.name}' produces a per-element output but has no map (\$i) consume to bind it`);
1007
1007
  }
1008
1008
  }
1009
+ // a reduce-mode step whose only produces are collections can never fire: eligibleFirings'
1010
+ // reduce branch (src/model.ts) derives the discharge set from singletonProduces(step) only,
1011
+ // so zero singleton produces means outs.length === 0 and no firing is ever pushed — the step
1012
+ // is silently dead (collection debt owed forever, absent from eligible/pending/blocked).
1013
+ for (const l of def.steps) {
1014
+ const isReduce = l.consumes.some((c) => c.mode === 'reduce');
1015
+ const hasCollectionProduce = l.produces.some((p) => p.kind === 'collection');
1016
+ const hasSingletonProduce = l.produces.some((p) => p.kind === 'singleton');
1017
+ if (isReduce && hasCollectionProduce && !hasSingletonProduce) {
1018
+ errors.push(`step ${l.name} is reduce-mode but produces only collections; reduce steps can only discharge singleton produces`);
1019
+ }
1020
+ }
1009
1021
  // same stem in both produces: and generates: on the same step is a hard error
1010
1022
  for (const l of def.steps) {
1011
1023
  if (!l.generates || l.generates.length === 0)
@@ -1147,6 +1159,17 @@ export function validateDef(def) {
1147
1159
  errors.push(`step '${l.name}': idleAfter is set but 'idle' is not in on:; idleAfter is only meaningful with the idle trigger`);
1148
1160
  }
1149
1161
  }
1162
+ // an allGreen/idle evaluator step that declares consumes can never commit: both firings
1163
+ // (src/model.ts) are built with inputs: [], so the claim fingerprint is empty, but commit-time
1164
+ // casCheck (src/engine.ts) derives required inputs from consumes and finds no fingerprint
1165
+ // entry for them — every firing is born-rejected forever. Evaluators must declare their
1166
+ // output under generates: with no consumes: (see examples/workflows/sla-watchdog.yaml, monitor).
1167
+ for (const l of def.steps) {
1168
+ const triggers = l.on ?? ['inputsGreen'];
1169
+ if (triggers.some((t) => t === 'allGreen' || t === 'idle') && l.consumes.length > 0) {
1170
+ errors.push(`evaluator step ${l.name} (on: allGreen/idle) must not declare consumes; its firings carry no input fingerprint`);
1171
+ }
1172
+ }
1150
1173
  // M2-VALIDATE: calls: step per-def rules.
1151
1174
  // Note: cross-def checks (target-def existence, child input-key validity) cannot be done here
1152
1175
  // because validateDef is a pure per-def function with no resolver. Those checks live in loadDefs
package/dist/engine.js CHANGED
@@ -1337,7 +1337,7 @@ export class Engine {
1337
1337
  const req = requiredInputs(def, arts, art);
1338
1338
  const cas = this.casCheck(arts, req, r.fingerprint ?? {});
1339
1339
  if (cas.moved) {
1340
- this.bornReject(art, cas.moved);
1340
+ this.bornReject(art, cas.moved, cas.reason);
1341
1341
  this.releaseLeaseOnBornReject(workflow, run);
1342
1342
  this.settle(workflow, def);
1343
1343
  return { path, outcome: 'born-rejected', reason: cas.reason };
@@ -1419,7 +1419,7 @@ export class Engine {
1419
1419
  if (cas.moved) {
1420
1420
  const seal = arts.get(sealPath(stem));
1421
1421
  if (seal)
1422
- this.bornReject(seal, cas.moved);
1422
+ this.bornReject(seal, cas.moved, cas.reason);
1423
1423
  this.releaseLeaseOnBornReject(workflow, run);
1424
1424
  this.settle(workflow, def);
1425
1425
  return { outcome: 'born-rejected', created: [], reason: cas.reason };
@@ -1512,7 +1512,7 @@ export class Engine {
1512
1512
  const req = plainConsumes(step).map((c) => c.stem);
1513
1513
  const cas = this.casCheck(arts, req, r.fingerprint ?? {});
1514
1514
  if (cas.moved) {
1515
- this.bornReject(sealArt, cas.moved);
1515
+ this.bornReject(sealArt, cas.moved, cas.reason);
1516
1516
  this.releaseLeaseOnBornReject(workflow, run);
1517
1517
  this.settle(workflow, def);
1518
1518
  return { path: sealP, outcome: 'born-rejected', reason: cas.reason };
@@ -2297,13 +2297,13 @@ export class Engine {
2297
2297
  });
2298
2298
  }
2299
2299
  }
2300
- bornReject(art, movedPath) {
2300
+ bornReject(art, movedPath, reasonText) {
2301
2301
  this.store.putArtifact({
2302
2302
  ...art,
2303
2303
  acceptance: 'rejected',
2304
2304
  reasons: [
2305
2305
  ...art.reasons,
2306
- reason('born-rejected', 'structural', 'engine', `born-rejected: ${movedPath} moved during this run`, art.version),
2306
+ reason('born-rejected', 'structural', 'engine', `born-rejected: ${reasonText ?? `${movedPath} moved during this run`}`, art.version),
2307
2307
  ],
2308
2308
  });
2309
2309
  }
@@ -2315,7 +2315,16 @@ export class Engine {
2315
2315
  }
2316
2316
  if (!fingerprintMatches(arts, req, fp)) {
2317
2317
  const moved = req.find((p) => (arts.get(p)?.version ?? -1) !== fp[p]) ?? req[0] ?? 'inputs';
2318
- return { moved, reason: `${moved} moved version during this run` };
2318
+ // Two structurally different causes share this branch: (a) ABSENT — the path
2319
+ // was never in the claim fingerprint at all (e.g. an allGreen/idle firing whose
2320
+ // inputs: [] yields fp={}, but the step still declares consumes:), so there is
2321
+ // no claimed version to have "moved" from; (b) CHANGED — the path WAS
2322
+ // fingerprinted but a concurrent commit moved it since claim. Keep the wording
2323
+ // distinct so the diagnostic doesn't lie about case (a).
2324
+ if (fp[moved] === undefined) {
2325
+ return { moved, reason: `${moved} was not in the claim fingerprint (this firing carried no input version for it)` };
2326
+ }
2327
+ return { moved, reason: `${moved} moved version during this run (claimed v${fp[moved]}, now v${arts.get(moved)?.version ?? -1})` };
2319
2328
  }
2320
2329
  return {};
2321
2330
  }
package/dist/hub.d.ts CHANGED
@@ -389,6 +389,38 @@ export type ReadStoredCredentialOpts = CredentialSlotSelector & {
389
389
  * it has always been.
390
390
  */
391
391
  export declare function readStoredCredential(origin: string, opts: ReadStoredCredentialOpts): Credential | null;
392
+ /**
393
+ * Enumerate the hub origins that have a usable `human` credential stored, or
394
+ * `null` when the active backend cannot be enumerated.
395
+ *
396
+ * Consumer: `owenloop mcp`'s origin inference (`resolveMcpOrigin` in
397
+ * `src/mcp/serve.ts`). When the host spawns the server with neither `--hub` nor
398
+ * `OWENLOOP_HUB`, the server tries to infer the single hub the user is logged
399
+ * in to. That inference is only sound on the FILE backend, which can list its
400
+ * `hubs` map; the keychain and external-command backends cannot enumerate:
401
+ *
402
+ * - **file** → the origins in `readCredentialFile(credentialFilePath(env)).hubs`
403
+ * whose `human` slot parses as a well-formed `Credential` (`parseCredential`).
404
+ * An origin present only under an `agent:<name>` slot is NOT returned — the
405
+ * control plane authenticates as the human.
406
+ * - **keychain** → `null`. The `Keychain` interface (get/set/delete by
407
+ * `(service, account)`) has no list operation — macOS `security` cannot
408
+ * enumerate the accounts under a service without a keychain-wide dump this
409
+ * module deliberately does not perform. There is no way to know which origins
410
+ * have entries, so it returns `null` ("cannot enumerate") rather than a
411
+ * misleading empty list.
412
+ * - **external** → `null`, for the same reason: the command answers a single
413
+ * `(origin, slot)` query; it has no listing contract.
414
+ *
415
+ * `null` (cannot enumerate), `[]` (nothing stored), and a length>1 result are
416
+ * all distinct signals the caller turns into tailored exit-2 messages — this
417
+ * function reports the fact, it never decides the outcome. It never logs or
418
+ * echoes any credential; only the origin KEYS (never secrets) are returned.
419
+ *
420
+ * `env`/`keychain` are threaded exactly as `readStoredCredential` threads them,
421
+ * so a caller passing a fixture `env` stays hermetic.
422
+ */
423
+ export declare function listStoredHubOrigins(env: Record<string, string | undefined>, keychain?: Keychain): string[] | null;
392
424
  /**
393
425
  * `.owenloop/hub.json` — written by `connect`. Safe to commit: contains no
394
426
  * secrets, only the bound hub origin. Purely a binding — `push` diffs against
@@ -506,6 +538,107 @@ export interface WhoamiIdentity {
506
538
  }
507
539
  /** Narrow a `GET /api/whoami` 200 body to its typed shape. Throws on a malformed body. */
508
540
  export declare function asWhoami(body: unknown): WhoamiIdentity;
541
+ /**
542
+ * Success shape of `POST /api/mint_agent_token` — the fields a caller is allowed
543
+ * to keep. Deliberately a WHITELIST: the real 200 body also carries a `text`
544
+ * field whose value CONTAINS the one-time `olp_` plaintext token ("Store this
545
+ * secret now …\n<olp_…>"), so a caller must never spread the raw body — it must
546
+ * build its result from these named fields only.
547
+ *
548
+ * `token` is the plaintext secret. It rides this typed shape exactly ONE hop:
549
+ * from `asMintAgentTokenOk`'s caller into `storeCredential`. It is never logged,
550
+ * printed, or embedded in an error — see `mintAgentCredential` (credentials.ts)
551
+ * and the identity model's §6 "rule of gates".
552
+ */
553
+ export interface MintAgentTokenOk {
554
+ /** Token id — a non-secret revocation handle, safe to print. */
555
+ id: string;
556
+ /** The one-time `olp_` plaintext. SECRET — store-only, never echoed. */
557
+ token: string;
558
+ /** The minted agent's id — a non-secret handle, safe to print. */
559
+ agentId: string;
560
+ /** Resolved pool NAMES the token was granted on — non-secret. */
561
+ pools: string[];
562
+ }
563
+ /**
564
+ * Narrow a `POST /api/mint_agent_token` 200 body to its typed success shape,
565
+ * validating STRICTLY (mirrors `asWhoami`/`asCreateWorkflowOk`'s throw-on-
566
+ * malformed style): a 2xx is not enough — the identity fields must be present
567
+ * and well-typed, or the "success" is a malformed response and must be treated
568
+ * as a failure rather than silently coerced.
569
+ *
570
+ * **Token hygiene (load-bearing):** every error message names the offending
571
+ * FIELD only — it never echoes a field VALUE. A malformed body could still carry
572
+ * the `olp_` plaintext (in `text`, or in a mistyped `token`), so echoing values
573
+ * here would be the exact leak §6 forbids. `id`/`agentId` must be non-empty
574
+ * strings; `token` a non-empty string starting `olp_`; `pools` an array of
575
+ * strings (empty allowed defensively — the server always resolves at least one,
576
+ * but the client does not depend on that to stay leak-safe).
577
+ */
578
+ export declare function asMintAgentTokenOk(body: unknown): MintAgentTokenOk;
579
+ /**
580
+ * One agent identity as `GET /api/agent_identities` reports it — the fields the
581
+ * setup converger and the doctor probe consult. The row is non-secret: it names
582
+ * agents and their pools, never a token.
583
+ *
584
+ * `lastContactAt` is identity-level (overwritten on EVERY authenticated contact,
585
+ * `olp_` or `mcpat_`). `lastUsedAt` is the edge-computed max over the identity's
586
+ * `agent`-kind tokens INCLUDING revoked ones — it deliberately survives a rekey.
587
+ * Both are epoch-ms or `null`; the succession UI shows `max(non-null of the two)`
588
+ * (see `lastActiveMs`). `disabled` gates whether the identity is a live
589
+ * succession candidate.
590
+ */
591
+ export interface AgentIdentitySummary {
592
+ id: string;
593
+ name: string;
594
+ disabled: boolean;
595
+ pools: string[];
596
+ lastContactAt: number | null;
597
+ lastUsedAt: number | null;
598
+ }
599
+ /**
600
+ * Narrow `GET /api/agent_identities`'s 200 body (`{identities: [...]}`) to a
601
+ * typed array. Throws on a malformed body (missing `identities` array, or a row
602
+ * missing `id`/`name`). Non-secret shape — the rows carry no token — so errors
603
+ * may name indices/fields freely. `lastContactAt`/`lastUsedAt` tolerate `null`
604
+ * or absence (→ `null`) but reject a present non-number; `pools` defaults to an
605
+ * empty array when absent, rejects a present non-array-of-strings; `disabled`
606
+ * defaults to `false`.
607
+ */
608
+ export declare function asAgentIdentities(body: unknown): AgentIdentitySummary[];
609
+ /**
610
+ * Success shape of `POST /api/rekey_agent_token` — the whitelist a caller may
611
+ * keep. Sibling of `MintAgentTokenOk`, and MUST stay a whitelist for the same
612
+ * reason: the real 200 body carries a `text` field whose value CONTAINS the new
613
+ * one-time `olp_` plaintext, so a caller must never spread the raw body.
614
+ *
615
+ * Rekey has NO `pools` field (re-keying preserves the agent's existing pool
616
+ * membership — the verb changes none), so `MintAgentTokenOk`/`asMintAgentTokenOk`
617
+ * cannot be reused. `scopes` and `revokedTokenIds` are non-secret handles.
618
+ */
619
+ export interface RekeyAgentTokenOk {
620
+ /** New token id — a non-secret revocation handle, safe to print. */
621
+ id: string;
622
+ /** The new one-time `olp_` plaintext. SECRET — store-only, never echoed. */
623
+ token: string;
624
+ /** The rekeyed agent's id — a non-secret handle, safe to print. */
625
+ agentId: string;
626
+ /** Ids of the tokens this rekey revoked — non-secret. */
627
+ revokedTokenIds: string[];
628
+ /** The new token's scopes — non-secret. */
629
+ scopes: string[];
630
+ }
631
+ /**
632
+ * Narrow a `POST /api/rekey_agent_token` 200 body to its typed success shape.
633
+ * Mirrors `asMintAgentTokenOk`'s discipline exactly: STRICT validation of the
634
+ * identity fields, and every error names the offending FIELD only — never a
635
+ * field VALUE — because a malformed body could still carry the `olp_` plaintext
636
+ * (in `text`, or a mistyped `token`), and echoing values would be the exact leak
637
+ * §6 forbids. `id`/`agentId` non-empty strings; `token` a non-empty string
638
+ * starting `olp_`; `revokedTokenIds`/`scopes` arrays of strings, each tolerated
639
+ * absent (→ empty array) but rejected if present-and-malformed.
640
+ */
641
+ export declare function asRekeyAgentTokenOk(body: unknown): RekeyAgentTokenOk;
509
642
  /**
510
643
  * Parse `GET /api/workflows`'s body into a `name -> WorkflowSummary` map for
511
644
  * `computeServerDiff`. Throws a descriptive error (the caller wraps it in a
package/dist/hub.js CHANGED
@@ -610,6 +610,49 @@ export function readStoredCredential(origin, opts) {
610
610
  const file = readCredentialFile(credentialFilePath(env));
611
611
  return parseCredential(file.hubs[key]?.[slot]);
612
612
  }
613
+ /**
614
+ * Enumerate the hub origins that have a usable `human` credential stored, or
615
+ * `null` when the active backend cannot be enumerated.
616
+ *
617
+ * Consumer: `owenloop mcp`'s origin inference (`resolveMcpOrigin` in
618
+ * `src/mcp/serve.ts`). When the host spawns the server with neither `--hub` nor
619
+ * `OWENLOOP_HUB`, the server tries to infer the single hub the user is logged
620
+ * in to. That inference is only sound on the FILE backend, which can list its
621
+ * `hubs` map; the keychain and external-command backends cannot enumerate:
622
+ *
623
+ * - **file** → the origins in `readCredentialFile(credentialFilePath(env)).hubs`
624
+ * whose `human` slot parses as a well-formed `Credential` (`parseCredential`).
625
+ * An origin present only under an `agent:<name>` slot is NOT returned — the
626
+ * control plane authenticates as the human.
627
+ * - **keychain** → `null`. The `Keychain` interface (get/set/delete by
628
+ * `(service, account)`) has no list operation — macOS `security` cannot
629
+ * enumerate the accounts under a service without a keychain-wide dump this
630
+ * module deliberately does not perform. There is no way to know which origins
631
+ * have entries, so it returns `null` ("cannot enumerate") rather than a
632
+ * misleading empty list.
633
+ * - **external** → `null`, for the same reason: the command answers a single
634
+ * `(origin, slot)` query; it has no listing contract.
635
+ *
636
+ * `null` (cannot enumerate), `[]` (nothing stored), and a length>1 result are
637
+ * all distinct signals the caller turns into tailored exit-2 messages — this
638
+ * function reports the fact, it never decides the outcome. It never logs or
639
+ * echoes any credential; only the origin KEYS (never secrets) are returned.
640
+ *
641
+ * `env`/`keychain` are threaded exactly as `readStoredCredential` threads them,
642
+ * so a caller passing a fixture `env` stays hermetic.
643
+ */
644
+ export function listStoredHubOrigins(env, keychain) {
645
+ const backend = credentialBackend(env, keychain);
646
+ if (backend.kind !== 'file')
647
+ return null;
648
+ const file = readCredentialFile(credentialFilePath(env));
649
+ const origins = [];
650
+ for (const [origin, slots] of Object.entries(file.hubs)) {
651
+ if (parseCredential(slots?.['human']) !== null)
652
+ origins.push(origin);
653
+ }
654
+ return origins;
655
+ }
613
656
  export function hubBindingPath(cwd) {
614
657
  return join(cwd, '.owenloop', 'hub.json');
615
658
  }
@@ -752,6 +795,135 @@ export function asWhoami(body) {
752
795
  identity.email = b.email;
753
796
  return identity;
754
797
  }
798
+ /**
799
+ * Narrow a `POST /api/mint_agent_token` 200 body to its typed success shape,
800
+ * validating STRICTLY (mirrors `asWhoami`/`asCreateWorkflowOk`'s throw-on-
801
+ * malformed style): a 2xx is not enough — the identity fields must be present
802
+ * and well-typed, or the "success" is a malformed response and must be treated
803
+ * as a failure rather than silently coerced.
804
+ *
805
+ * **Token hygiene (load-bearing):** every error message names the offending
806
+ * FIELD only — it never echoes a field VALUE. A malformed body could still carry
807
+ * the `olp_` plaintext (in `text`, or in a mistyped `token`), so echoing values
808
+ * here would be the exact leak §6 forbids. `id`/`agentId` must be non-empty
809
+ * strings; `token` a non-empty string starting `olp_`; `pools` an array of
810
+ * strings (empty allowed defensively — the server always resolves at least one,
811
+ * but the client does not depend on that to stay leak-safe).
812
+ */
813
+ export function asMintAgentTokenOk(body) {
814
+ if (typeof body !== 'object' || body === null) {
815
+ throw new Error('mint_agent_token: malformed success response — not an object');
816
+ }
817
+ const b = body;
818
+ if (typeof b.id !== 'string' || b.id === '') {
819
+ throw new Error('mint_agent_token: malformed success response — missing non-empty string id');
820
+ }
821
+ if (typeof b.agentId !== 'string' || b.agentId === '') {
822
+ throw new Error('mint_agent_token: malformed success response — missing non-empty string agentId');
823
+ }
824
+ if (typeof b.token !== 'string' || b.token === '') {
825
+ throw new Error('mint_agent_token: malformed success response — missing non-empty string token');
826
+ }
827
+ if (!b.token.startsWith('olp_')) {
828
+ throw new Error('mint_agent_token: malformed success response — token is not an olp_ token');
829
+ }
830
+ if (!Array.isArray(b.pools) || b.pools.some((p) => typeof p !== 'string')) {
831
+ throw new Error('mint_agent_token: malformed success response — pools must be an array of strings');
832
+ }
833
+ return { id: b.id, token: b.token, agentId: b.agentId, pools: b.pools };
834
+ }
835
+ /**
836
+ * Narrow `GET /api/agent_identities`'s 200 body (`{identities: [...]}`) to a
837
+ * typed array. Throws on a malformed body (missing `identities` array, or a row
838
+ * missing `id`/`name`). Non-secret shape — the rows carry no token — so errors
839
+ * may name indices/fields freely. `lastContactAt`/`lastUsedAt` tolerate `null`
840
+ * or absence (→ `null`) but reject a present non-number; `pools` defaults to an
841
+ * empty array when absent, rejects a present non-array-of-strings; `disabled`
842
+ * defaults to `false`.
843
+ */
844
+ export function asAgentIdentities(body) {
845
+ if (typeof body !== 'object' || body === null || !Array.isArray(body.identities)) {
846
+ throw new Error('agent_identities: malformed response — expected an `identities` array');
847
+ }
848
+ const list = body.identities;
849
+ return list.map((entry, i) => {
850
+ if (typeof entry !== 'object' || entry === null) {
851
+ throw new Error(`agent_identities: malformed response — identities[${i}] is not an object`);
852
+ }
853
+ const e = entry;
854
+ if (typeof e.id !== 'string' || e.id === '') {
855
+ throw new Error(`agent_identities: malformed response — identities[${i}] missing non-empty string id`);
856
+ }
857
+ if (typeof e.name !== 'string' || e.name === '') {
858
+ throw new Error(`agent_identities: malformed response — identities[${i}] missing non-empty string name`);
859
+ }
860
+ const epochOrNull = (v, field) => {
861
+ if (v === undefined || v === null)
862
+ return null;
863
+ if (typeof v !== 'number')
864
+ throw new Error(`agent_identities: malformed response — identities[${i}].${field} must be a number or null`);
865
+ return v;
866
+ };
867
+ let pools = [];
868
+ if (e.pools !== undefined) {
869
+ if (!Array.isArray(e.pools) || e.pools.some((p) => typeof p !== 'string')) {
870
+ throw new Error(`agent_identities: malformed response — identities[${i}].pools must be an array of strings`);
871
+ }
872
+ pools = e.pools;
873
+ }
874
+ return {
875
+ id: e.id,
876
+ name: e.name,
877
+ disabled: e.disabled === true,
878
+ pools,
879
+ lastContactAt: epochOrNull(e.lastContactAt, 'lastContactAt'),
880
+ lastUsedAt: epochOrNull(e.lastUsedAt, 'lastUsedAt'),
881
+ };
882
+ });
883
+ }
884
+ /**
885
+ * Narrow a `POST /api/rekey_agent_token` 200 body to its typed success shape.
886
+ * Mirrors `asMintAgentTokenOk`'s discipline exactly: STRICT validation of the
887
+ * identity fields, and every error names the offending FIELD only — never a
888
+ * field VALUE — because a malformed body could still carry the `olp_` plaintext
889
+ * (in `text`, or a mistyped `token`), and echoing values would be the exact leak
890
+ * §6 forbids. `id`/`agentId` non-empty strings; `token` a non-empty string
891
+ * starting `olp_`; `revokedTokenIds`/`scopes` arrays of strings, each tolerated
892
+ * absent (→ empty array) but rejected if present-and-malformed.
893
+ */
894
+ export function asRekeyAgentTokenOk(body) {
895
+ if (typeof body !== 'object' || body === null) {
896
+ throw new Error('rekey_agent_token: malformed success response — not an object');
897
+ }
898
+ const b = body;
899
+ if (typeof b.id !== 'string' || b.id === '') {
900
+ throw new Error('rekey_agent_token: malformed success response — missing non-empty string id');
901
+ }
902
+ if (typeof b.agentId !== 'string' || b.agentId === '') {
903
+ throw new Error('rekey_agent_token: malformed success response — missing non-empty string agentId');
904
+ }
905
+ if (typeof b.token !== 'string' || b.token === '') {
906
+ throw new Error('rekey_agent_token: malformed success response — missing non-empty string token');
907
+ }
908
+ if (!b.token.startsWith('olp_')) {
909
+ throw new Error('rekey_agent_token: malformed success response — token is not an olp_ token');
910
+ }
911
+ const strArray = (v, field) => {
912
+ if (v === undefined)
913
+ return [];
914
+ if (!Array.isArray(v) || v.some((x) => typeof x !== 'string')) {
915
+ throw new Error(`rekey_agent_token: malformed success response — ${field} must be an array of strings`);
916
+ }
917
+ return v;
918
+ };
919
+ return {
920
+ id: b.id,
921
+ token: b.token,
922
+ agentId: b.agentId,
923
+ revokedTokenIds: strArray(b.revokedTokenIds, 'revokedTokenIds'),
924
+ scopes: strArray(b.scopes, 'scopes'),
925
+ };
926
+ }
755
927
  /**
756
928
  * Parse `GET /api/workflows`'s body into a `name -> WorkflowSummary` map for
757
929
  * `computeServerDiff`. Throws a descriptive error (the caller wraps it in a
package/dist/index.d.ts CHANGED
@@ -21,6 +21,8 @@ export { buildDef, DefError, expandIncludes, finalizeDefs, hashDef, lintDef, loa
21
21
  export { credentialSlot, hashDefForHub, keychainServiceFor, normalizeOrigin, readStoredCredential } from './hub.ts';
22
22
  export type { Credential, CredentialSlotSelector, Keychain, ReadStoredCredentialOpts } from './hub.ts';
23
23
  export type { DefLoadFailure } from './defs.ts';
24
+ export { deleteCredential, ensureFreshOAuth, storeCredential } from './credentials.ts';
25
+ export type { CredentialIO } from './credentials.ts';
24
26
  export { buildGraph, buildTrace, eligibleFirings, graphToDot, graphToMermaid, isStalled, modelCheck, workflowStatus, } from './model.ts';
25
27
  export type { ArtifactMap, Blocker, Firing, TimeFacts, WorkflowStatus } from './model.ts';
26
28
  export { parseConsume, parseProduce, } from './paths.ts';
package/dist/index.js CHANGED
@@ -16,6 +16,7 @@ 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
18
  export { credentialSlot, hashDefForHub, keychainServiceFor, normalizeOrigin, readStoredCredential } from "./hub.js";
19
+ export { deleteCredential, ensureFreshOAuth, storeCredential } from "./credentials.js";
19
20
  export { buildGraph, buildTrace, eligibleFirings, graphToDot, graphToMermaid, isStalled, modelCheck, workflowStatus, } from "./model.js";
20
21
  export { parseConsume, parseProduce, } from "./paths.js";
21
22
  export { assertValidSchema, summarizeIssues, validateValue } from "./schema.js";
package/dist/lock.d.ts ADDED
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Generic advisory FILE LOCK — an exclusive-create lockfile with liveness-aware
3
+ * staleness, used to serialize a filesystem critical section across owenloop
4
+ * processes.
5
+ *
6
+ * Extracted verbatim (logic-identical) from `src/add.ts`'s per-project install
7
+ * lock: `add.ts` now consumes it through thin `acquireInstallLock` /
8
+ * `releaseInstallLock` wrappers that preserve the old names, types, and the
9
+ * "owenloop add" timeout wording; `src/credentials.ts` uses it to serialize the
10
+ * OAuth refresh-and-persist critical section (`credentials.lock`). The only
11
+ * behavioral addition during the move is the optional `label` (used in the
12
+ * timeout message) so each caller names itself.
13
+ *
14
+ * Depends only on node builtins so the library barrel (`src/index.ts` →
15
+ * `credentials.ts` → here) never drags the `add`/`untar` graph into its runtime
16
+ * closure.
17
+ */
18
+ export interface FileLockHandle {
19
+ lockPath: string;
20
+ acquired: boolean;
21
+ /** Per-acquisition ownership token — present when `acquired`; proof of ownership for release. */
22
+ token?: string;
23
+ }
24
+ export interface AcquireFileLockOpts {
25
+ /** Max time to wait for a live lock before failing cleanly (default 10s). */
26
+ waitMs?: number;
27
+ /**
28
+ * Age (by mtime) past which an *unparseable/abandoned* lock may be reclaimed
29
+ * (default 10m). Age NEVER reclaims a lock whose recorded pid is alive on
30
+ * this host — it only governs the fail-closed fallback for a lock we cannot
31
+ * attribute to a live owner (unparseable payload, or one without a pid).
32
+ */
33
+ staleMs?: number;
34
+ /** Poll interval while waiting on a live lock (default 100ms). */
35
+ pollMs?: number;
36
+ /** Liveness probe for the holder pid — injectable so tests are deterministic. */
37
+ isPidAlive?: (pid: number) => boolean;
38
+ /** Clock — injectable so tests are deterministic. */
39
+ now?: () => number;
40
+ /** Current hostname — injectable so cross-host tests are deterministic (default `os.hostname`). */
41
+ hostname?: () => string;
42
+ /**
43
+ * Names the holder in the timeout message ("another ${label} is in
44
+ * progress …"). Defaults to a generic phrase; `add` passes "owenloop add" so
45
+ * its existing wording is byte-identical.
46
+ */
47
+ label?: string;
48
+ }
49
+ /**
50
+ * Thrown by `acquireFileLock` when it gives up after `waitMs` on a lock a live
51
+ * owner still holds. A subclass of `Error` (not a plain `Error`) so a caller can
52
+ * `instanceof`-distinguish a clean timeout from a real filesystem failure (an
53
+ * EACCES/EROFS from the exclusive create) and map only the timeout to its own
54
+ * domain error — while `.message` stays byte-identical to the pre-extraction
55
+ * plain-`Error` message the `add` tests assert on.
56
+ */
57
+ export declare class FileLockTimeoutError extends Error {
58
+ readonly lockPath: string;
59
+ readonly holderPid: number | undefined;
60
+ readonly waitMs: number;
61
+ constructor(message: string, lockPath: string, holderPid: number | undefined, waitMs: number);
62
+ }
63
+ /**
64
+ * Acquire the file lock at `lockPath` (an exclusive-create of the file,
65
+ * `openSync(..,'wx')` — the O_EXCL create is the real serialization point). The
66
+ * payload carries an ownership token, the owner pid, a start timestamp, and the
67
+ * host. If another process holds it: reclaim it only when liveness-aware
68
+ * staleness says its owner is gone (see `lockIsStale`), otherwise poll until it
69
+ * frees, and if it does not free within `waitMs` throw a `FileLockTimeoutError`.
70
+ * Always pair with `releaseFileLock` in a `finally`.
71
+ */
72
+ export declare function acquireFileLock(lockPath: string, opts?: AcquireFileLockOpts): Promise<FileLockHandle>;
73
+ /**
74
+ * Release a lock acquired by `acquireFileLock`. Token-checked and best-effort: a
75
+ * no-op if not acquired, if the lock is already gone/unparseable, or if its
76
+ * token no longer matches this handle (someone else legitimately re-acquired it
77
+ * — deleting would steal *their* lock). Never throws; it runs in a `finally` and
78
+ * must not mask the real error.
79
+ */
80
+ export declare function releaseFileLock(handle: FileLockHandle): void;