owenloop 0.4.0 → 0.5.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.
Files changed (155) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/README.md +98 -25
  3. package/bin/owenloop.mjs +2 -2
  4. package/dist/packages/work/src/agent/brief.d.ts +172 -0
  5. package/dist/packages/work/src/agent/brief.js +193 -0
  6. package/dist/packages/work/src/agent/loop.d.ts +135 -0
  7. package/dist/packages/work/src/agent/loop.js +542 -0
  8. package/dist/packages/work/src/agent/workdir.d.ts +210 -0
  9. package/dist/packages/work/src/agent/workdir.js +319 -0
  10. package/dist/packages/work/src/bundle/cache.d.ts +90 -0
  11. package/dist/packages/work/src/bundle/cache.js +324 -0
  12. package/dist/packages/work/src/bundle/fetch.d.ts +85 -0
  13. package/dist/packages/work/src/bundle/fetch.js +325 -0
  14. package/dist/packages/work/src/bundle/types.d.ts +160 -0
  15. package/dist/packages/work/src/bundle/types.js +1 -0
  16. package/dist/packages/work/src/credentials/owenloop.d.ts +11 -0
  17. package/dist/packages/work/src/credentials/owenloop.js +28 -0
  18. package/dist/packages/work/src/credentials/reader.d.ts +36 -0
  19. package/dist/packages/work/src/credentials/reader.js +32 -0
  20. package/dist/packages/work/src/credentials/resolve.d.ts +19 -0
  21. package/dist/packages/work/src/credentials/resolve.js +56 -0
  22. package/dist/packages/work/src/exec/loop.d.ts +29 -0
  23. package/dist/packages/work/src/exec/loop.js +215 -0
  24. package/dist/packages/work/src/exec/receipt.d.ts +38 -0
  25. package/dist/packages/work/src/exec/receipt.js +21 -0
  26. package/dist/packages/work/src/exec/runner.d.ts +65 -0
  27. package/dist/packages/work/src/exec/runner.js +185 -0
  28. package/dist/packages/work/src/harness/child-env.d.ts +100 -0
  29. package/dist/packages/work/src/harness/child-env.js +127 -0
  30. package/dist/packages/work/src/harness/claude.d.ts +128 -0
  31. package/dist/packages/work/src/harness/claude.js +635 -0
  32. package/dist/packages/work/src/harness/codex.d.ts +110 -0
  33. package/dist/packages/work/src/harness/codex.js +896 -0
  34. package/dist/packages/work/src/harness/contract.d.ts +283 -0
  35. package/dist/packages/work/src/harness/contract.js +32 -0
  36. package/dist/packages/work/src/harness/fake.d.ts +59 -0
  37. package/dist/packages/work/src/harness/fake.js +90 -0
  38. package/dist/packages/work/src/harness/jsonrpc-stdio.d.ts +108 -0
  39. package/dist/packages/work/src/harness/jsonrpc-stdio.js +344 -0
  40. package/dist/packages/work/src/harness/permissions.d.ts +62 -0
  41. package/dist/packages/work/src/harness/permissions.js +93 -0
  42. package/dist/packages/work/src/harness/registry.d.ts +47 -0
  43. package/dist/packages/work/src/harness/registry.js +45 -0
  44. package/dist/packages/work/src/harness/session-store.d.ts +163 -0
  45. package/dist/packages/work/src/harness/session-store.js +319 -0
  46. package/dist/packages/work/src/harness/types.d.ts +29 -0
  47. package/dist/packages/work/src/harness/types.js +14 -0
  48. package/dist/packages/work/src/harnesses.d.ts +38 -0
  49. package/dist/packages/work/src/harnesses.js +38 -0
  50. package/dist/packages/work/src/hold/loop.d.ts +36 -0
  51. package/dist/packages/work/src/hold/loop.js +23 -0
  52. package/dist/packages/work/src/hold/mcp.d.ts +55 -0
  53. package/dist/packages/work/src/hold/mcp.js +149 -0
  54. package/dist/packages/work/src/hub/client.d.ts +22 -0
  55. package/dist/packages/work/src/hub/client.js +78 -0
  56. package/dist/packages/work/src/hub/types.d.ts +290 -0
  57. package/dist/packages/work/src/hub/types.js +28 -0
  58. package/dist/packages/work/src/lease/loop.d.ts +94 -0
  59. package/dist/packages/work/src/lease/loop.js +277 -0
  60. package/dist/packages/work/src/main.d.ts +1 -0
  61. package/dist/packages/work/src/main.js +48 -0
  62. package/dist/packages/work/src/mcp/server.d.ts +125 -0
  63. package/dist/packages/work/src/mcp/server.js +320 -0
  64. package/dist/packages/work/src/roles/agent-run.d.ts +118 -0
  65. package/dist/packages/work/src/roles/agent-run.js +447 -0
  66. package/dist/packages/work/src/roles/exec.d.ts +40 -0
  67. package/dist/packages/work/src/roles/exec.js +203 -0
  68. package/dist/packages/work/src/roles/hold.d.ts +68 -0
  69. package/dist/packages/work/src/roles/hold.js +324 -0
  70. package/dist/packages/work/src/roles/join.d.ts +18 -0
  71. package/dist/packages/work/src/roles/join.js +204 -0
  72. package/dist/packages/work/src/roles/lint.d.ts +59 -0
  73. package/dist/packages/work/src/roles/lint.js +200 -0
  74. package/dist/packages/work/src/roles/prepare.d.ts +1 -0
  75. package/dist/packages/work/src/roles/prepare.js +249 -0
  76. package/dist/packages/work/src/roles/release.d.ts +48 -0
  77. package/dist/packages/work/src/roles/release.js +137 -0
  78. package/dist/packages/work/src/roles/sessions.d.ts +61 -0
  79. package/dist/packages/work/src/roles/sessions.js +180 -0
  80. package/dist/packages/work/src/roles/settings.d.ts +6 -0
  81. package/dist/packages/work/src/roles/settings.js +66 -0
  82. package/dist/packages/work/src/roles/shift.d.ts +12 -0
  83. package/dist/packages/work/src/roles/shift.js +228 -0
  84. package/dist/packages/work/src/roles/signals.d.ts +55 -0
  85. package/dist/packages/work/src/roles/signals.js +62 -0
  86. package/dist/packages/work/src/settings/provision.d.ts +21 -0
  87. package/dist/packages/work/src/settings/provision.js +47 -0
  88. package/dist/packages/work/src/settings/settings.d.ts +120 -0
  89. package/dist/packages/work/src/settings/settings.js +116 -0
  90. package/dist/packages/work/src/shift/client.d.ts +24 -0
  91. package/dist/packages/work/src/shift/client.js +124 -0
  92. package/dist/packages/work/src/shift/loop.d.ts +120 -0
  93. package/dist/packages/work/src/shift/loop.js +468 -0
  94. package/dist/packages/work/src/shift/protocol.d.ts +91 -0
  95. package/dist/packages/work/src/shift/protocol.js +24 -0
  96. package/dist/packages/work/src/shift/routing.d.ts +35 -0
  97. package/dist/packages/work/src/shift/routing.js +50 -0
  98. package/dist/packages/work/src/shift/runtime.d.ts +43 -0
  99. package/dist/packages/work/src/shift/runtime.js +274 -0
  100. package/dist/packages/work/src/shift/server.d.ts +23 -0
  101. package/dist/packages/work/src/shift/server.js +716 -0
  102. package/dist/packages/work/src/shift/spawn.d.ts +86 -0
  103. package/dist/packages/work/src/shift/spawn.js +100 -0
  104. package/dist/packages/work/src/shift/state.d.ts +77 -0
  105. package/dist/packages/work/src/shift/state.js +162 -0
  106. package/dist/packages/work/src/usage.d.ts +6 -0
  107. package/dist/packages/work/src/usage.js +175 -0
  108. package/dist/{add.d.ts → src/add.d.ts} +12 -40
  109. package/dist/{add.js → src/add.js} +11 -176
  110. package/dist/src/cli.d.ts +147 -0
  111. package/dist/{cli.js → src/cli.js} +1643 -353
  112. package/dist/src/credentials.d.ts +280 -0
  113. package/dist/src/credentials.js +697 -0
  114. package/dist/{defs.js → src/defs.js} +59 -36
  115. package/dist/{engine.d.ts → src/engine.d.ts} +8 -8
  116. package/dist/{engine.js → src/engine.js} +29 -20
  117. package/dist/{hub.d.ts → src/hub.d.ts} +330 -2
  118. package/dist/{hub.js → src/hub.js} +531 -1
  119. package/dist/{index.d.ts → src/index.d.ts} +3 -1
  120. package/dist/{index.js → src/index.js} +2 -1
  121. package/dist/src/lock.d.ts +80 -0
  122. package/dist/src/lock.js +217 -0
  123. package/dist/src/mcp/serve.d.ts +85 -0
  124. package/dist/src/mcp/serve.js +702 -0
  125. package/dist/src/mcp/server.d.ts +132 -0
  126. package/dist/src/mcp/server.js +327 -0
  127. package/dist/{model.d.ts → src/model.d.ts} +59 -4
  128. package/dist/{model.js → src/model.js} +149 -22
  129. package/dist/{types.d.ts → src/types.d.ts} +66 -24
  130. package/dist/{util.d.ts → src/util.d.ts} +25 -0
  131. package/dist/{util.js → src/util.js} +26 -0
  132. package/dist/src/work-settings.d.ts +57 -0
  133. package/dist/src/work-settings.js +84 -0
  134. package/docs/authoring.md +102 -53
  135. package/docs/cli.md +883 -29
  136. package/docs/design.md +119 -45
  137. package/docs/embedding.md +39 -14
  138. package/examples/workflows/{command-worker.yaml → command-executor.yaml} +15 -15
  139. package/examples/workflows/compile-dev-playbook.yaml +338 -0
  140. package/examples/workflows/judges/gate-sharpness.md +39 -0
  141. package/examples/workflows/judges/security.md +34 -0
  142. package/package.json +17 -8
  143. package/dist/cli.d.ts +0 -83
  144. /package/dist/{defs.d.ts → src/defs.d.ts} +0 -0
  145. /package/dist/{factory.d.ts → src/factory.d.ts} +0 -0
  146. /package/dist/{factory.js → src/factory.js} +0 -0
  147. /package/dist/{paths.d.ts → src/paths.d.ts} +0 -0
  148. /package/dist/{paths.js → src/paths.js} +0 -0
  149. /package/dist/{schema.d.ts → src/schema.d.ts} +0 -0
  150. /package/dist/{schema.js → src/schema.js} +0 -0
  151. /package/dist/{store.d.ts → src/store.d.ts} +0 -0
  152. /package/dist/{store.js → src/store.js} +0 -0
  153. /package/dist/{types.js → src/types.js} +0 -0
  154. /package/dist/{untar.d.ts → src/untar.d.ts} +0 -0
  155. /package/dist/{untar.js → src/untar.js} +0 -0
@@ -543,7 +543,7 @@ export function credentialBackend(env, injected) {
543
543
  /**
544
544
  * Read the stored hub credential for `origin` **in the named slot** from the
545
545
  * chosen backend ONLY — the supported, read-only programmatic surface
546
- * (owenwork's CredentialReader seam wires to this once released). Secret hygiene
546
+ * (owenloop's CredentialReader seam wires to this once released). Secret hygiene
547
547
  * is unchanged: this function never logs or echoes the returned credential, and
548
548
  * there is deliberately no write/delete companion on the public surface —
549
549
  * `login` / `logout` remain the only way to store or remove a credential.
@@ -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,493 @@ 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_`; `crews` 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.crews) || b.crews.some((p) => typeof p !== 'string')) {
831
+ throw new Error('mint_agent_token: malformed success response — crews must be an array of strings');
832
+ }
833
+ return { id: b.id, token: b.token, agentId: b.agentId, crews: b.crews };
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; `crews` 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 crews = [];
868
+ if (e.crews !== undefined) {
869
+ if (!Array.isArray(e.crews) || e.crews.some((p) => typeof p !== 'string')) {
870
+ throw new Error(`agent_identities: malformed response — identities[${i}].crews must be an array of strings`);
871
+ }
872
+ crews = e.crews;
873
+ }
874
+ return {
875
+ id: e.id,
876
+ name: e.name,
877
+ disabled: e.disabled === true,
878
+ crews,
879
+ lastContactAt: epochOrNull(e.lastContactAt, 'lastContactAt'),
880
+ lastUsedAt: epochOrNull(e.lastUsedAt, 'lastUsedAt'),
881
+ };
882
+ });
883
+ }
884
+ /**
885
+ * Validate the five common `CapabilityRouteWire` fields on one row. `prefix` is the
886
+ * endpoint-qualified lead-in the caller wants (e.g.
887
+ * `add_capability_route: malformed success response`) and `where` names the
888
+ * offending position (`route`, or `routes[2]`) — a FIELD/INDEX name only,
889
+ * never a value.
890
+ *
891
+ * `crewName` is validated LENIENTLY here, unlike the other four fields: absent or
892
+ * `null` both yield `null`, because `null` is the hub's own answer for a dangling
893
+ * route. A caller that additionally KNOWS its crew is live (`asCapabilityRouteAdded`
894
+ * resolves by name) layers its own non-null check on top of this shared call.
895
+ */
896
+ function asCapabilityRouteRow(entry, prefix, where) {
897
+ if (typeof entry !== 'object' || entry === null) {
898
+ throw new Error(`${prefix} — ${where} is not an object`);
899
+ }
900
+ const e = entry;
901
+ for (const field of ['capability', 'crewId', 'createdBy']) {
902
+ if (typeof e[field] !== 'string' || e[field] === '') {
903
+ throw new Error(`${prefix} — ${where} missing non-empty string ${field}`);
904
+ }
905
+ }
906
+ if (typeof e.createdAt !== 'number') {
907
+ throw new Error(`${prefix} — ${where} missing number createdAt`);
908
+ }
909
+ // Lenient exactly like `asCrewRow`'s `ownerMemberId`: absent or null both mean
910
+ // "no name to report" — here, a DANGLING route whose crew row is gone.
911
+ let crewName = null;
912
+ if (e.crewName !== undefined && e.crewName !== null) {
913
+ if (typeof e.crewName !== 'string' || e.crewName === '') {
914
+ throw new Error(`${prefix} — ${where} crewName must be a non-empty string or null`);
915
+ }
916
+ crewName = e.crewName;
917
+ }
918
+ return {
919
+ capability: e.capability,
920
+ crewId: e.crewId,
921
+ crewName,
922
+ createdBy: e.createdBy,
923
+ createdAt: e.createdAt,
924
+ };
925
+ }
926
+ /**
927
+ * Narrow `POST /api/add_capability_route`'s 200 body
928
+ * (`{ text, route, alreadyRouted, routedCrewCount }`). Throws on anything
929
+ * malformed, naming the offending FIELD only — same discipline as
930
+ * `asAgentIdentities`, so no body value is echoed.
931
+ *
932
+ * `route.crewName` is required to be a NON-NULL non-empty string here, on top
933
+ * of `asCapabilityRouteRow`'s lenient check. That is not a contradiction: an add
934
+ * resolves its crew BY NAME, so the crew is live by construction and a `null`
935
+ * name in THIS response is genuinely malformed — whereas a `null` name in a
936
+ * `capability_routes` row is the legitimate dangling-route case. Layering a
937
+ * call-site-specific check on top of the shared row call is the established
938
+ * shape in this family, not a new pattern.
939
+ */
940
+ export function asCapabilityRouteAdded(body) {
941
+ const prefix = 'add_capability_route: malformed success response';
942
+ if (typeof body !== 'object' || body === null) {
943
+ throw new Error(`${prefix} — not an object`);
944
+ }
945
+ const b = body;
946
+ if (b.route === undefined) {
947
+ throw new Error(`${prefix} — missing route`);
948
+ }
949
+ const route = asCapabilityRouteRow(b.route, prefix, 'route');
950
+ if (route.crewName === null) {
951
+ throw new Error(`${prefix} — route missing non-empty string crewName`);
952
+ }
953
+ if (typeof b.alreadyRouted !== 'boolean') {
954
+ throw new Error(`${prefix} — missing boolean alreadyRouted`);
955
+ }
956
+ if (typeof b.routedCrewCount !== 'number') {
957
+ throw new Error(`${prefix} — missing number routedCrewCount`);
958
+ }
959
+ return { route, alreadyRouted: b.alreadyRouted, routedCrewCount: b.routedCrewCount };
960
+ }
961
+ /**
962
+ * Narrow `POST /api/remove_capability_route`'s 200 body
963
+ * (`{ text, capability, crewId, removed, remainingCrewIds }`).
964
+ *
965
+ * `removed` must be a BOOLEAN — this guard is how the CLI proves the 2xx really
966
+ * was the remove verb's answer. BOTH boolean values are valid, deliberate hub
967
+ * responses:
968
+ * - `true` — the `(capability, crew)` pair was bound and is now removed;
969
+ * - `false` — the pair was never bound, so there was nothing to do. The hub
970
+ * answers this with a 200, never a 404 (the `removeCrewMember` `{existed}`
971
+ * house pattern), and that tolerance is what makes `capability unbind` idempotent.
972
+ *
973
+ * `crewId` is LENIENT (absent or `null` both yield `null`) because `null` is a
974
+ * real hub output, not a defect: `manage-capability-routes.ts` resolves it as
975
+ * `namedCrew?.id ?? thisCapabilityRows.find(...)?.crewId ?? null`, so it is `null`
976
+ * on exactly the tolerant `removed: false` path where the argument matched
977
+ * neither a live crew name nor one of this capability's own route rows. Requiring a
978
+ * non-empty string here would throw on a normal success.
979
+ *
980
+ * `remainingCrewIds` is deliberately NOT lenient — it must be PRESENT and an
981
+ * array of non-empty strings. The asymmetry is the point: for a nullable name,
982
+ * the lenient default (`null`) is the SAFE reading, but defaulting an absent
983
+ * `remainingCrewIds` to `[]` would assert "this capability is now PARKED" — the
984
+ * alarming reading, and exactly the signal an operator acts on — off a malformed
985
+ * body. It lists LIVE crews only, so `[]` genuinely means zero live routes
986
+ * remain (which can happen while a dangling row survives, since such a row routes
987
+ * nothing).
988
+ *
989
+ * The stdout shape built from this is documented in `docs/cli.md`'s
990
+ * "Printed JSON" table under capability routes.
991
+ */
992
+ export function asCapabilityRouteRemoved(body) {
993
+ const prefix = 'remove_capability_route: malformed success response';
994
+ if (typeof body !== 'object' || body === null) {
995
+ throw new Error(`${prefix} — not an object`);
996
+ }
997
+ const b = body;
998
+ if (typeof b.removed !== 'boolean') {
999
+ throw new Error(`${prefix} — missing boolean removed`);
1000
+ }
1001
+ if (typeof b.capability !== 'string' || b.capability === '') {
1002
+ throw new Error(`${prefix} — missing non-empty string capability`);
1003
+ }
1004
+ let crewId = null;
1005
+ if (b.crewId !== undefined && b.crewId !== null) {
1006
+ if (typeof b.crewId !== 'string' || b.crewId === '') {
1007
+ throw new Error(`${prefix} — crewId must be a non-empty string or null`);
1008
+ }
1009
+ crewId = b.crewId;
1010
+ }
1011
+ if (!Array.isArray(b.remainingCrewIds)) {
1012
+ throw new Error(`${prefix} — missing array remainingCrewIds`);
1013
+ }
1014
+ const remainingCrewIds = b.remainingCrewIds.map((entry, i) => {
1015
+ if (typeof entry !== 'string' || entry === '') {
1016
+ throw new Error(`${prefix} — remainingCrewIds[${i}] is not a non-empty string`);
1017
+ }
1018
+ return entry;
1019
+ });
1020
+ return { capability: b.capability, crewId, removed: b.removed, remainingCrewIds };
1021
+ }
1022
+ /**
1023
+ * Narrow `GET /api/capability_routes`'s 200 body (`{ text, routes: [...] }`) to a
1024
+ * typed array. An EMPTY array is valid — that is the "this org has no routes
1025
+ * yet" case, not an error.
1026
+ *
1027
+ * Rows are plain `CapabilityRouteWire`, ONE per `(capability, crew)` pair ordered by
1028
+ * `capability, crew_id`, so a capability bound to many crews yields MANY rows — the array
1029
+ * is forwarded as-is and must never be collapsed into a per-capability map. A row
1030
+ * whose `crewName` is `null` is a dangling route and is kept, not dropped.
1031
+ */
1032
+ export function asCapabilityRoutes(body) {
1033
+ if (typeof body !== 'object' || body === null || !Array.isArray(body.routes)) {
1034
+ throw new Error('capability_routes: malformed response — expected a `routes` array');
1035
+ }
1036
+ const list = body.routes;
1037
+ return list.map((entry, i) => asCapabilityRouteRow(entry, 'capability_routes: malformed response', `routes[${i}]`));
1038
+ }
1039
+ /**
1040
+ * The `orphan:` prefix the hub uses to name its reserved orphan crew
1041
+ * (`packages/hub-core/src/crews-table.ts` / `verbs/manage-crews.ts`). Mirrored
1042
+ * here as a named constant — not an invention — so a future reader can tell at
1043
+ * a glance that this string is copied from the hub's source of truth, not
1044
+ * independently chosen.
1045
+ */
1046
+ const ORPHAN_CREW_NAME_PREFIX = 'orphan:';
1047
+ /**
1048
+ * Validate the common `CrewWire` fields on one row. `prefix` is the
1049
+ * endpoint-qualified lead-in (e.g. `crews: malformed response`) and `where`
1050
+ * names the offending position (`crew`, or `crews[2]`) — a FIELD/INDEX name
1051
+ * only, never a value, mirroring `asCapabilityRouteRow`'s discipline exactly.
1052
+ */
1053
+ function asCrewRow(entry, prefix, where) {
1054
+ if (typeof entry !== 'object' || entry === null) {
1055
+ throw new Error(`${prefix} — ${where} is not an object`);
1056
+ }
1057
+ const e = entry;
1058
+ for (const field of ['id', 'name', 'kind', 'createdBy']) {
1059
+ if (typeof e[field] !== 'string' || e[field] === '') {
1060
+ throw new Error(`${prefix} — ${where} missing non-empty string ${field}`);
1061
+ }
1062
+ }
1063
+ if (typeof e.createdAt !== 'number') {
1064
+ throw new Error(`${prefix} — ${where} missing number createdAt`);
1065
+ }
1066
+ // Lenient exactly like `asCapabilityRouteRow`'s `crewName`: absent or null both
1067
+ // mean "no owner" — a serializer that drops `undefined` must not turn a valid
1068
+ // shared crew into a hard failure.
1069
+ let ownerMemberId = null;
1070
+ if (e.ownerMemberId !== undefined && e.ownerMemberId !== null) {
1071
+ if (typeof e.ownerMemberId !== 'string' || e.ownerMemberId === '') {
1072
+ throw new Error(`${prefix} — ${where} ownerMemberId must be a non-empty string or null`);
1073
+ }
1074
+ ownerMemberId = e.ownerMemberId;
1075
+ }
1076
+ return {
1077
+ id: e.id,
1078
+ name: e.name,
1079
+ kind: e.kind,
1080
+ ownerMemberId,
1081
+ createdBy: e.createdBy,
1082
+ createdAt: e.createdAt,
1083
+ };
1084
+ }
1085
+ /**
1086
+ * Validate one `CrewMemberWire` row. The wire row also carries `crewId`; it is
1087
+ * deliberately NOT validated and NOT printed here, because inside
1088
+ * `crews[i].members[j]` it is structurally the enclosing crew's `id` and
1089
+ * repeating it adds no information.
1090
+ */
1091
+ function asCrewMemberRow(entry, prefix, where) {
1092
+ if (typeof entry !== 'object' || entry === null) {
1093
+ throw new Error(`${prefix} — ${where} is not an object`);
1094
+ }
1095
+ const e = entry;
1096
+ for (const field of ['principalKind', 'principalId', 'addedBy']) {
1097
+ if (typeof e[field] !== 'string' || e[field] === '') {
1098
+ throw new Error(`${prefix} — ${where} missing non-empty string ${field}`);
1099
+ }
1100
+ }
1101
+ if (typeof e.addedAt !== 'number') {
1102
+ throw new Error(`${prefix} — ${where} missing number addedAt`);
1103
+ }
1104
+ return {
1105
+ principalKind: e.principalKind,
1106
+ principalId: e.principalId,
1107
+ addedBy: e.addedBy,
1108
+ addedAt: e.addedAt,
1109
+ };
1110
+ }
1111
+ /**
1112
+ * Narrow `GET /api/crews`'s 200 body (`{ text, crews: [...] }`) to a typed
1113
+ * array. An EMPTY array is valid (a brand-new org). `GET /api/crews`
1114
+ * deliberately returns the org's reserved orphan crew when it exists — this
1115
+ * never filters it out; instead every row gets a derived `orphan` boolean,
1116
+ * always present (`true` or `false`), so a scripted consumer never branches on
1117
+ * the key's existence.
1118
+ */
1119
+ export function asCrews(body) {
1120
+ if (typeof body !== 'object' || body === null || !Array.isArray(body.crews)) {
1121
+ throw new Error('crews: malformed response — expected a `crews` array');
1122
+ }
1123
+ const list = body.crews;
1124
+ const prefix = 'crews: malformed response';
1125
+ return list.map((entry, i) => {
1126
+ const row = asCrewRow(entry, prefix, `crews[${i}]`);
1127
+ const e = entry;
1128
+ if (!Array.isArray(e.members)) {
1129
+ throw new Error(`${prefix} — crews[${i}] missing members array`);
1130
+ }
1131
+ const members = e.members.map((m, j) => asCrewMemberRow(m, prefix, `crews[${i}].members[${j}]`));
1132
+ const orphan = row.kind === 'orphan' || row.name.startsWith(ORPHAN_CREW_NAME_PREFIX);
1133
+ return { ...row, orphan, members };
1134
+ });
1135
+ }
1136
+ /**
1137
+ * Narrow `POST /api/create_crew`'s 200 body (`{ text, crew }`) to the typed
1138
+ * row.
1139
+ */
1140
+ export function asCrewCreated(body) {
1141
+ const prefix = 'create_crew: malformed success response';
1142
+ if (typeof body !== 'object' || body === null) {
1143
+ throw new Error(`${prefix} — not an object`);
1144
+ }
1145
+ const b = body;
1146
+ if (b.crew === undefined) {
1147
+ throw new Error(`${prefix} — missing crew`);
1148
+ }
1149
+ return asCrewRow(b.crew, prefix, 'crew');
1150
+ }
1151
+ /**
1152
+ * Narrow `POST /api/delete_crew`'s 200 body. `crewId` and `deleted` are always
1153
+ * present (`deleted` is a genuine boolean — both values are valid, deliberate
1154
+ * hub answers, exactly like `asCapabilityRouteRemoved`). Each of the six transfer
1155
+ * fields is validated ONLY IF PRESENT and OMITTED from the returned object when
1156
+ * absent — never defaulted to `0`, `null`, or `[]`. Absence is the hub's way of
1157
+ * saying "nothing moved"; default-filling would assert a transfer that never
1158
+ * happened. `runsTransferred`/`runningRunsTransferred` are ARRAYS OF IDS, not
1159
+ * counts — `stampsTransferred`/`membersRemoved` are the counts.
1160
+ */
1161
+ export function asCrewDeleted(body) {
1162
+ const prefix = 'delete_crew: malformed success response';
1163
+ if (typeof body !== 'object' || body === null) {
1164
+ throw new Error(`${prefix} — not an object`);
1165
+ }
1166
+ const b = body;
1167
+ if (typeof b.crewId !== 'string' || b.crewId === '') {
1168
+ throw new Error(`${prefix} — missing non-empty string crewId`);
1169
+ }
1170
+ if (typeof b.deleted !== 'boolean') {
1171
+ throw new Error(`${prefix} — missing boolean deleted`);
1172
+ }
1173
+ const out = { crewId: b.crewId, deleted: b.deleted };
1174
+ const numberIfPresent = (field) => {
1175
+ if (b[field] === undefined)
1176
+ return;
1177
+ if (typeof b[field] !== 'number') {
1178
+ throw new Error(`${prefix} — ${field} must be a number`);
1179
+ }
1180
+ out[field] = b[field];
1181
+ };
1182
+ const stringIfPresent = (field) => {
1183
+ if (b[field] === undefined)
1184
+ return;
1185
+ if (typeof b[field] !== 'string' || b[field] === '') {
1186
+ throw new Error(`${prefix} — ${field} must be a non-empty string`);
1187
+ }
1188
+ out[field] = b[field];
1189
+ };
1190
+ const stringArrayIfPresent = (field) => {
1191
+ if (b[field] === undefined)
1192
+ return;
1193
+ const v = b[field];
1194
+ if (!Array.isArray(v) || v.some((x) => typeof x !== 'string' || x === '')) {
1195
+ throw new Error(`${prefix} — ${field} must be an array of strings`);
1196
+ }
1197
+ out[field] = v;
1198
+ };
1199
+ numberIfPresent('membersRemoved');
1200
+ stringIfPresent('orphanCrewId');
1201
+ stringIfPresent('orphanCrewName');
1202
+ numberIfPresent('stampsTransferred');
1203
+ stringArrayIfPresent('runsTransferred');
1204
+ stringArrayIfPresent('runningRunsTransferred');
1205
+ return out;
1206
+ }
1207
+ /** Narrow `POST /api/add_crew_member`'s 200 body (`{ text, member }`) to the typed row. */
1208
+ export function asCrewMemberAdded(body) {
1209
+ const prefix = 'add_crew_member: malformed success response';
1210
+ if (typeof body !== 'object' || body === null) {
1211
+ throw new Error(`${prefix} — not an object`);
1212
+ }
1213
+ const b = body;
1214
+ if (b.member === undefined) {
1215
+ throw new Error(`${prefix} — missing member`);
1216
+ }
1217
+ return asCrewMemberRow(b.member, prefix, 'member');
1218
+ }
1219
+ /**
1220
+ * Narrow `POST /api/remove_crew_member`'s 200 body (`{ text, crewId,
1221
+ * principalId, removed }`). `removed` must be a genuine boolean — both values
1222
+ * are valid, deliberate hub answers: `false` means the principal was never a
1223
+ * member (tolerant, a normal success), exactly like `asCapabilityRouteRemoved`.
1224
+ */
1225
+ export function asCrewMemberRemoved(body) {
1226
+ const prefix = 'remove_crew_member: malformed success response';
1227
+ if (typeof body !== 'object' || body === null) {
1228
+ throw new Error(`${prefix} — not an object`);
1229
+ }
1230
+ const b = body;
1231
+ if (typeof b.crewId !== 'string' || b.crewId === '') {
1232
+ throw new Error(`${prefix} — missing non-empty string crewId`);
1233
+ }
1234
+ if (typeof b.principalId !== 'string' || b.principalId === '') {
1235
+ throw new Error(`${prefix} — missing non-empty string principalId`);
1236
+ }
1237
+ if (typeof b.removed !== 'boolean') {
1238
+ throw new Error(`${prefix} — missing boolean removed`);
1239
+ }
1240
+ return { crewId: b.crewId, principalId: b.principalId, removed: b.removed };
1241
+ }
1242
+ /**
1243
+ * Narrow a `POST /api/rekey_agent_token` 200 body to its typed success shape.
1244
+ * Mirrors `asMintAgentTokenOk`'s discipline exactly: STRICT validation of the
1245
+ * identity fields, and every error names the offending FIELD only — never a
1246
+ * field VALUE — because a malformed body could still carry the `olp_` plaintext
1247
+ * (in `text`, or a mistyped `token`), and echoing values would be the exact leak
1248
+ * §6 forbids. `id`/`agentId` non-empty strings; `token` a non-empty string
1249
+ * starting `olp_`; `revokedTokenIds`/`scopes` arrays of strings, each tolerated
1250
+ * absent (→ empty array) but rejected if present-and-malformed.
1251
+ */
1252
+ export function asRekeyAgentTokenOk(body) {
1253
+ if (typeof body !== 'object' || body === null) {
1254
+ throw new Error('rekey_agent_token: malformed success response — not an object');
1255
+ }
1256
+ const b = body;
1257
+ if (typeof b.id !== 'string' || b.id === '') {
1258
+ throw new Error('rekey_agent_token: malformed success response — missing non-empty string id');
1259
+ }
1260
+ if (typeof b.agentId !== 'string' || b.agentId === '') {
1261
+ throw new Error('rekey_agent_token: malformed success response — missing non-empty string agentId');
1262
+ }
1263
+ if (typeof b.token !== 'string' || b.token === '') {
1264
+ throw new Error('rekey_agent_token: malformed success response — missing non-empty string token');
1265
+ }
1266
+ if (!b.token.startsWith('olp_')) {
1267
+ throw new Error('rekey_agent_token: malformed success response — token is not an olp_ token');
1268
+ }
1269
+ const strArray = (v, field) => {
1270
+ if (v === undefined)
1271
+ return [];
1272
+ if (!Array.isArray(v) || v.some((x) => typeof x !== 'string')) {
1273
+ throw new Error(`rekey_agent_token: malformed success response — ${field} must be an array of strings`);
1274
+ }
1275
+ return v;
1276
+ };
1277
+ return {
1278
+ id: b.id,
1279
+ token: b.token,
1280
+ agentId: b.agentId,
1281
+ revokedTokenIds: strArray(b.revokedTokenIds, 'revokedTokenIds'),
1282
+ scopes: strArray(b.scopes, 'scopes'),
1283
+ };
1284
+ }
755
1285
  /**
756
1286
  * Parse `GET /api/workflows`'s body into a `name -> WorkflowSummary` map for
757
1287
  * `computeServerDiff`. Throws a descriptive error (the caller wraps it in a
@@ -8,7 +8,7 @@
8
8
  * green"); a commit-fingerprint CAS makes concurrent advancement safe.
9
9
  *
10
10
  * This is the public API. The engine is domain-neutral: a *wiring* (a set of
11
- * workflow definitions + a worker that executes orders) layers a concrete
11
+ * workflow definitions + a Step Agent that executes orders) layers a concrete
12
12
  * process — software delivery, research, triage — on top of it.
13
13
  */
14
14
  export { Engine } from './engine.ts';
@@ -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';
@@ -8,7 +8,7 @@
8
8
  * green"); a commit-fingerprint CAS makes concurrent advancement safe.
9
9
  *
10
10
  * This is the public API. The engine is domain-neutral: a *wiring* (a set of
11
- * workflow definitions + a worker that executes orders) layers a concrete
11
+ * workflow definitions + a Step Agent that executes orders) layers a concrete
12
12
  * process — software delivery, research, triage — on top of it.
13
13
  */
14
14
  export { Engine } from "./engine.js";
@@ -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";
@@ -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;