owenloop 0.4.1 → 0.5.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.
Files changed (282) hide show
  1. package/CHANGELOG.md +71 -0
  2. package/README.md +182 -53
  3. package/bin/owenloop.mjs +50 -2
  4. package/dist/packages/work/src/agent/brief.d.ts +176 -0
  5. package/dist/packages/work/src/agent/brief.js +197 -0
  6. package/dist/packages/work/src/agent/loop.d.ts +141 -0
  7. package/dist/packages/work/src/agent/loop.js +669 -0
  8. package/dist/packages/work/src/agent/model-policy.d.ts +49 -0
  9. package/dist/packages/work/src/agent/model-policy.js +138 -0
  10. package/dist/packages/work/src/agent/workdir.d.ts +210 -0
  11. package/dist/packages/work/src/agent/workdir.js +319 -0
  12. package/dist/packages/work/src/bundle/cache.d.ts +92 -0
  13. package/dist/packages/work/src/bundle/cache.js +338 -0
  14. package/dist/packages/work/src/bundle/fetch.d.ts +87 -0
  15. package/dist/packages/work/src/bundle/fetch.js +345 -0
  16. package/dist/packages/work/src/bundle/types.d.ts +164 -0
  17. package/dist/packages/work/src/bundle/types.js +1 -0
  18. package/dist/packages/work/src/consumed-verifier.d.ts +45 -0
  19. package/dist/packages/work/src/consumed-verifier.js +205 -0
  20. package/dist/packages/work/src/credentials/owenloop.d.ts +11 -0
  21. package/dist/packages/work/src/credentials/owenloop.js +28 -0
  22. package/dist/packages/work/src/credentials/reader.d.ts +36 -0
  23. package/dist/packages/work/src/credentials/reader.js +32 -0
  24. package/dist/packages/work/src/credentials/resolve.d.ts +19 -0
  25. package/dist/packages/work/src/credentials/resolve.js +56 -0
  26. package/dist/packages/work/src/exec/instructions.d.ts +99 -0
  27. package/dist/packages/work/src/exec/instructions.js +323 -0
  28. package/dist/packages/work/src/exec/loop.d.ts +40 -0
  29. package/dist/packages/work/src/exec/loop.js +332 -0
  30. package/dist/packages/work/src/exec/payload.d.ts +29 -0
  31. package/dist/packages/work/src/exec/payload.js +54 -0
  32. package/dist/packages/work/src/exec/receipt.d.ts +41 -0
  33. package/dist/packages/work/src/exec/receipt.js +32 -0
  34. package/dist/packages/work/src/exec/runner.d.ts +71 -0
  35. package/dist/packages/work/src/exec/runner.js +256 -0
  36. package/dist/packages/work/src/harness/child-env.d.ts +100 -0
  37. package/dist/packages/work/src/harness/child-env.js +134 -0
  38. package/dist/packages/work/src/harness/claude.d.ts +140 -0
  39. package/dist/packages/work/src/harness/claude.js +837 -0
  40. package/dist/packages/work/src/harness/codex.d.ts +111 -0
  41. package/dist/packages/work/src/harness/codex.js +1024 -0
  42. package/dist/packages/work/src/harness/contract.d.ts +308 -0
  43. package/dist/packages/work/src/harness/contract.js +32 -0
  44. package/dist/packages/work/src/harness/fake.d.ts +59 -0
  45. package/dist/packages/work/src/harness/fake.js +91 -0
  46. package/dist/packages/work/src/harness/jsonrpc-stdio.d.ts +108 -0
  47. package/dist/packages/work/src/harness/jsonrpc-stdio.js +351 -0
  48. package/dist/packages/work/src/harness/permissions.d.ts +75 -0
  49. package/dist/packages/work/src/harness/permissions.js +182 -0
  50. package/dist/packages/work/src/harness/registry.d.ts +47 -0
  51. package/dist/packages/work/src/harness/registry.js +45 -0
  52. package/dist/packages/work/src/harness/session-store.d.ts +181 -0
  53. package/dist/packages/work/src/harness/session-store.js +523 -0
  54. package/dist/packages/work/src/harness/types.d.ts +29 -0
  55. package/dist/packages/work/src/harness/types.js +14 -0
  56. package/dist/packages/work/src/harnesses.d.ts +38 -0
  57. package/dist/packages/work/src/harnesses.js +38 -0
  58. package/dist/packages/work/src/hold/loop.d.ts +36 -0
  59. package/dist/packages/work/src/hold/loop.js +23 -0
  60. package/dist/packages/work/src/hold/mcp.d.ts +75 -0
  61. package/dist/packages/work/src/hold/mcp.js +264 -0
  62. package/dist/packages/work/src/hub/client.d.ts +23 -0
  63. package/dist/packages/work/src/hub/client.js +91 -0
  64. package/dist/packages/work/src/hub/types.d.ts +326 -0
  65. package/dist/packages/work/src/hub/types.js +26 -0
  66. package/dist/packages/work/src/lease/loop.d.ts +94 -0
  67. package/dist/packages/work/src/lease/loop.js +277 -0
  68. package/dist/packages/work/src/main.d.ts +1 -0
  69. package/dist/packages/work/src/main.js +48 -0
  70. package/dist/packages/work/src/mcp/server.d.ts +125 -0
  71. package/dist/packages/work/src/mcp/server.js +320 -0
  72. package/dist/packages/work/src/owenloop-bin.d.ts +1 -0
  73. package/dist/packages/work/src/owenloop-bin.js +18 -0
  74. package/dist/packages/work/src/roles/agent-run.d.ts +124 -0
  75. package/dist/packages/work/src/roles/agent-run.js +529 -0
  76. package/dist/packages/work/src/roles/exec.d.ts +48 -0
  77. package/dist/packages/work/src/roles/exec.js +228 -0
  78. package/dist/packages/work/src/roles/hold.d.ts +72 -0
  79. package/dist/packages/work/src/roles/hold.js +363 -0
  80. package/dist/packages/work/src/roles/join.d.ts +18 -0
  81. package/dist/packages/work/src/roles/join.js +204 -0
  82. package/dist/packages/work/src/roles/lint.d.ts +58 -0
  83. package/dist/packages/work/src/roles/lint.js +234 -0
  84. package/dist/packages/work/src/roles/prepare.d.ts +1 -0
  85. package/dist/packages/work/src/roles/prepare.js +249 -0
  86. package/dist/packages/work/src/roles/release.d.ts +48 -0
  87. package/dist/packages/work/src/roles/release.js +137 -0
  88. package/dist/packages/work/src/roles/sessions.d.ts +61 -0
  89. package/dist/packages/work/src/roles/sessions.js +180 -0
  90. package/dist/packages/work/src/roles/settings.d.ts +6 -0
  91. package/dist/packages/work/src/roles/settings.js +71 -0
  92. package/dist/packages/work/src/roles/shift.d.ts +13 -0
  93. package/dist/packages/work/src/roles/shift.js +250 -0
  94. package/dist/packages/work/src/roles/signals.d.ts +55 -0
  95. package/dist/packages/work/src/roles/signals.js +62 -0
  96. package/dist/packages/work/src/settings/provision.d.ts +21 -0
  97. package/dist/packages/work/src/settings/provision.js +47 -0
  98. package/dist/packages/work/src/settings/settings.d.ts +136 -0
  99. package/dist/packages/work/src/settings/settings.js +155 -0
  100. package/dist/packages/work/src/shift/client.d.ts +24 -0
  101. package/dist/packages/work/src/shift/client.js +124 -0
  102. package/dist/packages/work/src/shift/loop.d.ts +131 -0
  103. package/dist/packages/work/src/shift/loop.js +751 -0
  104. package/dist/packages/work/src/shift/protocol.d.ts +95 -0
  105. package/dist/packages/work/src/shift/protocol.js +24 -0
  106. package/dist/packages/work/src/shift/routing.d.ts +35 -0
  107. package/dist/packages/work/src/shift/routing.js +50 -0
  108. package/dist/packages/work/src/shift/runtime.d.ts +45 -0
  109. package/dist/packages/work/src/shift/runtime.js +337 -0
  110. package/dist/packages/work/src/shift/server.d.ts +23 -0
  111. package/dist/packages/work/src/shift/server.js +716 -0
  112. package/dist/packages/work/src/shift/spawn.d.ts +109 -0
  113. package/dist/packages/work/src/shift/spawn.js +158 -0
  114. package/dist/packages/work/src/shift/state.d.ts +79 -0
  115. package/dist/packages/work/src/shift/state.js +385 -0
  116. package/dist/packages/work/src/submit-proof.d.ts +36 -0
  117. package/dist/packages/work/src/submit-proof.js +93 -0
  118. package/dist/packages/work/src/usage.d.ts +6 -0
  119. package/dist/packages/work/src/usage.js +175 -0
  120. package/dist/src/add.d.ts +189 -0
  121. package/dist/src/add.js +300 -0
  122. package/dist/src/archive.d.ts +97 -0
  123. package/dist/src/archive.js +591 -0
  124. package/dist/src/bundle/index.d.ts +64 -0
  125. package/dist/src/bundle/index.js +508 -0
  126. package/dist/src/bundle/manifest.d.ts +50 -0
  127. package/dist/src/bundle/manifest.js +435 -0
  128. package/dist/src/bundle/runtime.d.ts +26 -0
  129. package/dist/src/bundle/runtime.js +64 -0
  130. package/dist/src/bundle/tar.d.ts +62 -0
  131. package/dist/src/bundle/tar.js +238 -0
  132. package/dist/src/bundle/types.d.ts +105 -0
  133. package/dist/src/bundle/types.js +21 -0
  134. package/dist/{cli.d.ts → src/cli.d.ts} +92 -7
  135. package/dist/src/cli.js +5968 -0
  136. package/dist/{credentials.d.ts → src/credentials.d.ts} +22 -15
  137. package/dist/{credentials.js → src/credentials.js} +35 -31
  138. package/dist/src/crypto/allowed-signers.d.ts +68 -0
  139. package/dist/src/crypto/allowed-signers.js +307 -0
  140. package/dist/src/crypto/canonical.d.ts +8 -0
  141. package/dist/src/crypto/canonical.js +92 -0
  142. package/dist/src/crypto/chain.d.ts +65 -0
  143. package/dist/src/crypto/chain.js +377 -0
  144. package/dist/src/crypto/dsse.d.ts +209 -0
  145. package/dist/src/crypto/dsse.js +282 -0
  146. package/dist/src/crypto/enrollment.d.ts +78 -0
  147. package/dist/src/crypto/enrollment.js +186 -0
  148. package/dist/src/crypto/index.d.ts +48 -0
  149. package/dist/src/crypto/index.js +44 -0
  150. package/dist/src/crypto/keys.d.ts +258 -0
  151. package/dist/src/crypto/keys.js +908 -0
  152. package/dist/src/crypto/org-root.d.ts +33 -0
  153. package/dist/src/crypto/org-root.js +78 -0
  154. package/dist/src/crypto/origin-rules.d.ts +56 -0
  155. package/dist/src/crypto/origin-rules.js +143 -0
  156. package/dist/src/crypto/policy-floor.d.ts +98 -0
  157. package/dist/src/crypto/policy-floor.js +353 -0
  158. package/dist/src/crypto/records.d.ts +316 -0
  159. package/dist/src/crypto/records.js +157 -0
  160. package/dist/src/crypto/scope.d.ts +49 -0
  161. package/dist/src/crypto/scope.js +83 -0
  162. package/dist/src/crypto/ssh.d.ts +171 -0
  163. package/dist/src/crypto/ssh.js +396 -0
  164. package/dist/src/crypto/submission.d.ts +33 -0
  165. package/dist/src/crypto/submission.js +47 -0
  166. package/dist/src/crypto/trust-roots.d.ts +29 -0
  167. package/dist/src/crypto/trust-roots.js +39 -0
  168. package/dist/src/crypto/verify-consumed.d.ts +67 -0
  169. package/dist/src/crypto/verify-consumed.js +259 -0
  170. package/dist/src/crypto/verify-origin.d.ts +50 -0
  171. package/dist/src/crypto/verify-origin.js +151 -0
  172. package/dist/src/crypto/verify-publication.d.ts +60 -0
  173. package/dist/src/crypto/verify-publication.js +150 -0
  174. package/dist/{defs.d.ts → src/defs.d.ts} +24 -1
  175. package/dist/{defs.js → src/defs.js} +181 -61
  176. package/dist/{engine.d.ts → src/engine.d.ts} +105 -9
  177. package/dist/{engine.js → src/engine.js} +251 -47
  178. package/dist/{factory.d.ts → src/factory.d.ts} +16 -0
  179. package/dist/{factory.js → src/factory.js} +16 -4
  180. package/dist/src/global-config.d.ts +59 -0
  181. package/dist/src/global-config.js +84 -0
  182. package/dist/{hub.d.ts → src/hub.d.ts} +280 -31
  183. package/dist/{hub.js → src/hub.js} +493 -52
  184. package/dist/src/index.d.ts +47 -0
  185. package/dist/src/index.js +41 -0
  186. package/dist/src/install.d.ts +538 -0
  187. package/dist/src/install.js +1981 -0
  188. package/dist/src/lock.d.ts +38 -0
  189. package/dist/src/lock.js +325 -0
  190. package/dist/src/mcp/serve.d.ts +109 -0
  191. package/dist/{mcp → src/mcp}/serve.js +335 -75
  192. package/dist/{mcp → src/mcp}/server.d.ts +6 -9
  193. package/dist/{mcp → src/mcp}/server.js +18 -10
  194. package/dist/{model.d.ts → src/model.d.ts} +15 -0
  195. package/dist/{model.js → src/model.js} +112 -2
  196. package/dist/src/order-resolver.d.ts +184 -0
  197. package/dist/src/order-resolver.js +252 -0
  198. package/dist/src/package-version.d.ts +10 -0
  199. package/dist/src/package-version.js +42 -0
  200. package/dist/{paths.d.ts → src/paths.d.ts} +14 -1
  201. package/dist/{paths.js → src/paths.js} +18 -0
  202. package/dist/src/schemas/enrollment-grant.v1.schema.json +90 -0
  203. package/dist/src/schemas/index.d.ts +1416 -0
  204. package/dist/src/schemas/index.js +31 -0
  205. package/dist/src/schemas/order.v1.schema.json +106 -0
  206. package/dist/src/schemas/origin.v1.schema.json +68 -0
  207. package/dist/src/schemas/policy-floor.v1.schema.json +29 -0
  208. package/dist/src/schemas/publication.v1.schema.json +31 -0
  209. package/dist/src/schemas/revocation.v1.schema.json +39 -0
  210. package/dist/src/schemas/submission.v1.schema.json +61 -0
  211. package/dist/src/store/def-source.d.ts +52 -0
  212. package/dist/src/store/def-source.js +335 -0
  213. package/dist/src/store/index-file.d.ts +69 -0
  214. package/dist/src/store/index-file.js +151 -0
  215. package/dist/src/store/index.d.ts +27 -0
  216. package/dist/src/store/index.js +22 -0
  217. package/dist/src/store/ingestor.d.ts +43 -0
  218. package/dist/src/store/ingestor.js +211 -0
  219. package/dist/src/store/install.d.ts +228 -0
  220. package/dist/src/store/install.js +555 -0
  221. package/dist/src/store/instruction-source.d.ts +49 -0
  222. package/dist/src/store/instruction-source.js +298 -0
  223. package/dist/src/store/origin-evidence.d.ts +21 -0
  224. package/dist/src/store/origin-evidence.js +66 -0
  225. package/dist/src/store/pre-commit-verifier.d.ts +68 -0
  226. package/dist/src/store/pre-commit-verifier.js +418 -0
  227. package/dist/src/store/resolve.d.ts +138 -0
  228. package/dist/src/store/resolve.js +363 -0
  229. package/dist/src/store/types.d.ts +288 -0
  230. package/dist/src/store/types.js +356 -0
  231. package/dist/{types.d.ts → src/types.d.ts} +58 -24
  232. package/dist/{untar.d.ts → src/untar.d.ts} +8 -23
  233. package/dist/src/untar.js +38 -0
  234. package/dist/{util.d.ts → src/util.d.ts} +3 -2
  235. package/dist/{util.js → src/util.js} +3 -2
  236. package/dist/{owenwork.d.ts → src/work-settings.d.ts} +22 -22
  237. package/dist/{owenwork.js → src/work-settings.js} +27 -27
  238. package/docs/agent-runner.md +86 -0
  239. package/docs/authoring.md +150 -59
  240. package/docs/bundles.md +250 -0
  241. package/docs/cli.md +1758 -163
  242. package/docs/crypto.md +816 -0
  243. package/docs/design.md +374 -52
  244. package/docs/embedding.md +135 -27
  245. package/docs/wire-contracts.md +380 -0
  246. package/examples/workflows/{command-worker.yaml → command-executor.yaml} +15 -15
  247. package/examples/workflows/compile-dev-playbook.yaml +338 -0
  248. package/examples/workflows/judges/gate-sharpness.md +39 -0
  249. package/examples/workflows/judges/security.md +34 -0
  250. package/package.json +22 -8
  251. package/plugins/claude-code/.claude-plugin/marketplace.json +14 -0
  252. package/plugins/claude-code/plugin/.claude-plugin/plugin.json +8 -0
  253. package/plugins/claude-code/plugin/.mcp.json +14 -0
  254. package/plugins/claude-code/plugin/hooks/hooks.json +26 -0
  255. package/plugins/claude-code/plugin/hooks/session-end.sh +40 -0
  256. package/plugins/claude-code/plugin/hooks/session-start.sh +52 -0
  257. package/plugins/claude-code/plugin/skills/author/SKILL.md +181 -0
  258. package/plugins/claude-code/plugin/skills/conduct/SKILL.md +106 -0
  259. package/plugins/claude-code/plugin/skills/shift/SKILL.md +105 -0
  260. package/plugins/codex/.agents/plugins/marketplace.json +21 -0
  261. package/plugins/codex/plugins/owenloop/.codex-plugin/plugin.json +7 -0
  262. package/plugins/codex/plugins/owenloop/.mcp.json +20 -0
  263. package/plugins/codex/plugins/owenloop/hooks/hooks.json +26 -0
  264. package/plugins/codex/plugins/owenloop/hooks/session-end.sh +40 -0
  265. package/plugins/codex/plugins/owenloop/hooks/session-start.sh +52 -0
  266. package/plugins/codex/plugins/owenloop/skills/author/SKILL.md +181 -0
  267. package/plugins/codex/plugins/owenloop/skills/conduct/SKILL.md +106 -0
  268. package/plugins/codex/plugins/owenloop/skills/shift/SKILL.md +105 -0
  269. package/dist/add.d.ts +0 -384
  270. package/dist/add.js +0 -834
  271. package/dist/cli.js +0 -3270
  272. package/dist/index.d.ts +0 -32
  273. package/dist/index.js +0 -23
  274. package/dist/lock.d.ts +0 -80
  275. package/dist/lock.js +0 -217
  276. package/dist/mcp/serve.d.ts +0 -84
  277. package/dist/untar.js +0 -164
  278. /package/dist/{schema.d.ts → src/schema.d.ts} +0 -0
  279. /package/dist/{schema.js → src/schema.js} +0 -0
  280. /package/dist/{store.d.ts → src/store.d.ts} +0 -0
  281. /package/dist/{store.js → src/store.js} +0 -0
  282. /package/dist/{types.js → src/types.js} +0 -0
@@ -0,0 +1,228 @@
1
+ /**
2
+ * `owenloop work exec <order-id>` (C5) — the detached, self-leasing command worker.
3
+ *
4
+ * The shift (C3) spawns one detached `owenloop work exec <workflow>/<run> --origin
5
+ * <url>` per COMMAND order. This process owns that order end to end: it takes the
6
+ * lease on first contact, keeps it warm while it shells the order's `command`
7
+ * out, and submits a receipt to every owed output path — then exits. It is the
8
+ * one process in the system that actually executes an order's command string.
9
+ *
10
+ * The orchestration CORE lives in `src/exec/loop.ts` (lease + runner + receipt,
11
+ * every side effect injected); this role only parses the arg contract, resolves
12
+ * origin/token, builds the real hub client + default runner, tags the exec
13
+ * holder identity, wires the signal seam, and maps the loop's `ExecOutcome` to an
14
+ * exit code.
15
+ *
16
+ * ORDER ID: a positional `<workflow>/<run>` composite (or a bare `<run>` plus
17
+ * `--workflow <wf>`), resolved by the same `resolveTarget` `hold` uses. The shift
18
+ * always emits the composite form.
19
+ *
20
+ * HOLDER IDENTITY: every get_order/heartbeat rides the B3 holder tag
21
+ * `{kind:'exec', id}` where id is `<hostname>:<pid>`. `kind:'exec'` is the drain
22
+ * exemption (B3/C6): an exec-held claim survives a SESSION drain — only a signal
23
+ * aimed at THIS process hands the order back. `--shift <cid>` (env fallback
24
+ * `OWENLOOP_SHIFT_ID`), when known, rides along on the holder as
25
+ * `shiftId` — self-declared and advisory only (D8/INV-82).
26
+ *
27
+ * Origin/credential resolution mirrors `hold`/`shift`: origin `--origin` →
28
+ * settings; the bearer comes from owenloop's store via `resolveBearer`, reading
29
+ * the `agent:<account>` slot for the account the shift set in this child's
30
+ * `OWENLOOP_ACCOUNT` spawn env (default `default`), with `OWENLOOP_TOKEN` as a
31
+ * documented dev-only override. Exec has NO `--as` flag — the spawn-env channel
32
+ * is the contract. Exit codes are documented in `src/usage.ts`.
33
+ */
34
+ import { hostname } from 'node:os';
35
+ import { createHubClient } from "../hub/client.js";
36
+ import { resolveBearer } from "../credentials/resolve.js";
37
+ import { loadSettings } from "../settings/settings.js";
38
+ import { createExecLoop } from "../exec/loop.js";
39
+ import { createDefaultStoreInstructionResolver } from "../exec/instructions.js";
40
+ import { createDefaultRunner } from "../exec/runner.js";
41
+ import { createConsumedVerifier } from "../consumed-verifier.js";
42
+ import { resolveShiftId, resolveTarget } from "./hold.js";
43
+ import { installSignalHandlers } from "./signals.js";
44
+ const DEFAULT_INTERVAL_MS = 60_000;
45
+ /**
46
+ * Parse the positional `<order-id>` plus `--workflow`/`--origin`/
47
+ * `--heartbeat-interval`/`--jump-tolerance`. Supports `--flag value` and
48
+ * `--flag=value`; a second positional or an unknown flag is an error.
49
+ */
50
+ export function parseArgs(args) {
51
+ const parsed = {};
52
+ const takeValue = (a, i) => {
53
+ const eq = a.indexOf('=');
54
+ if (eq !== -1)
55
+ return { value: a.slice(eq + 1), next: i };
56
+ const v = args[i + 1];
57
+ if (v === undefined)
58
+ return { error: `missing value for ${a}` };
59
+ return { value: v, next: i + 1 };
60
+ };
61
+ for (let i = 0; i < args.length; i++) {
62
+ const a = args[i];
63
+ if (!a.startsWith('-')) {
64
+ if (parsed.orderId !== undefined)
65
+ return { error: `unexpected extra argument '${a}'` };
66
+ parsed.orderId = a;
67
+ continue;
68
+ }
69
+ const name = a.startsWith('--') && a.includes('=') ? a.slice(0, a.indexOf('=')) : a;
70
+ switch (name) {
71
+ case '--workflow':
72
+ case '--origin':
73
+ case '--shift':
74
+ case '--heartbeat-interval':
75
+ case '--jump-tolerance': {
76
+ const r = takeValue(a, i);
77
+ if ('error' in r)
78
+ return { error: r.error };
79
+ i = r.next;
80
+ if (name === '--workflow')
81
+ parsed.workflow = r.value;
82
+ else if (name === '--origin')
83
+ parsed.origin = r.value;
84
+ else if (name === '--shift')
85
+ parsed.shift = r.value;
86
+ else if (name === '--heartbeat-interval') {
87
+ const n = Number(r.value);
88
+ if (!Number.isFinite(n) || !Number.isInteger(n) || n <= 0) {
89
+ return { error: `--heartbeat-interval must be a positive integer, got '${r.value}'` };
90
+ }
91
+ parsed.heartbeatIntervalMs = n;
92
+ }
93
+ else if (name === '--jump-tolerance') {
94
+ const n = Number(r.value);
95
+ if (!Number.isFinite(n) || !Number.isInteger(n) || n <= 0) {
96
+ return { error: `--jump-tolerance must be a positive integer, got '${r.value}'` };
97
+ }
98
+ parsed.jumpToleranceMs = n;
99
+ }
100
+ break;
101
+ }
102
+ default:
103
+ return { error: `unknown option '${a}'` };
104
+ }
105
+ }
106
+ return parsed;
107
+ }
108
+ function usage() {
109
+ process.stderr.write('usage: owenloop work exec <workflow>/<run> [--origin <url>] [--shift <id>] [--heartbeat-interval <ms>] [--jump-tolerance <ms>]\n' +
110
+ ' or: owenloop work exec <run> --workflow <wf> [...]\n');
111
+ }
112
+ function errMsg(err) {
113
+ return err instanceof Error ? err.message : String(err);
114
+ }
115
+ /** Map the loop's outcome onto the process exit code (see usage.ts). */
116
+ export function exitCodeFor(outcome) {
117
+ switch (outcome) {
118
+ case 'submitted':
119
+ case 'completed':
120
+ case 'rejected':
121
+ case 'judge-rejected':
122
+ return 0;
123
+ case 'misroute':
124
+ case 'unresolved-instructions':
125
+ case 'killed':
126
+ case 'lease-lost':
127
+ case 'ownership-error':
128
+ case 'hub-unreachable':
129
+ case 'submit-rejected':
130
+ case 'submit-failed':
131
+ case 'judge-no-verdict':
132
+ case 'reject-failed':
133
+ case 'stopped':
134
+ return 1;
135
+ }
136
+ }
137
+ export async function run(args, deps = {}) {
138
+ const out = deps.out ?? ((line) => void process.stdout.write(`${line}\n`));
139
+ const err = deps.err ?? ((line) => void process.stderr.write(`${line}\n`));
140
+ const parsed = parseArgs(args);
141
+ if (parsed.error !== undefined) {
142
+ err(`owenloop work exec: ${parsed.error}`);
143
+ usage();
144
+ return 2;
145
+ }
146
+ if (parsed.orderId === undefined || parsed.orderId === '') {
147
+ err('owenloop work exec: missing required <order-id>');
148
+ usage();
149
+ return 2;
150
+ }
151
+ const target = resolveTarget(parsed.orderId, parsed.workflow);
152
+ if ('error' in target) {
153
+ err(`owenloop work exec: ${target.error}`);
154
+ usage();
155
+ return 2;
156
+ }
157
+ const env = deps.env ?? process.env;
158
+ let settings;
159
+ try {
160
+ settings = loadSettings(env);
161
+ }
162
+ catch (e) {
163
+ err(`owenloop work exec: ${errMsg(e)}`);
164
+ return 1;
165
+ }
166
+ const consumedVerifier = deps.consumedVerifier ?? createConsumedVerifier({
167
+ env,
168
+ now: () => Date.now(),
169
+ });
170
+ const origin = parsed.origin ?? settings.hubOrigin;
171
+ if (origin === undefined || origin.trim() === '') {
172
+ err('owenloop work exec: no hub origin — pass --origin <url> or set hubOrigin in settings');
173
+ return 2;
174
+ }
175
+ const cwd = deps.cwd ?? process.cwd();
176
+ let instructions = deps.instructions;
177
+ if (instructions === undefined) {
178
+ try {
179
+ instructions = createDefaultStoreInstructionResolver({ cwd, env, consumedVerifier });
180
+ }
181
+ catch (e) {
182
+ err(`owenloop work exec: instruction store unavailable: ${errMsg(e)}`);
183
+ return 1;
184
+ }
185
+ }
186
+ const account = env['OWENLOOP_ACCOUNT'] ?? 'default';
187
+ const bearer = await resolveBearer({ origin, account, env });
188
+ if (!bearer.ok) {
189
+ err(`owenloop work exec: ${bearer.message}`);
190
+ return bearer.code;
191
+ }
192
+ const token = bearer.token;
193
+ const shiftId = resolveShiftId(parsed.shift, env);
194
+ const holder = {
195
+ kind: 'exec',
196
+ id: deps.holderId ?? `${hostname()}:${process.pid}`,
197
+ ...(shiftId !== undefined ? { shiftId } : {}),
198
+ };
199
+ const hub = deps.hub ?? createHubClient({ origin, getToken: async () => token });
200
+ const runner = deps.runner ?? createDefaultRunner();
201
+ const loop = createExecLoop({
202
+ hub,
203
+ runner,
204
+ workflow: target.workflow,
205
+ run: target.run,
206
+ origin,
207
+ env,
208
+ holder,
209
+ instructions,
210
+ cwd,
211
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
212
+ now: () => Date.now(),
213
+ out,
214
+ err,
215
+ heartbeatIntervalMs: parsed.heartbeatIntervalMs ?? DEFAULT_INTERVAL_MS,
216
+ // Test affordance only: exposes the lease loop's existing jumpToleranceMs
217
+ // knob (default unchanged) so a drill can trip the clock-jump lease check
218
+ // with a short freeze instead of a real >30s laptop sleep.
219
+ ...(parsed.jumpToleranceMs !== undefined ? { jumpToleranceMs: parsed.jumpToleranceMs } : {}),
220
+ });
221
+ installSignalHandlers(loop, deps.signalHost ?? process, err, {
222
+ role: 'exec',
223
+ drainNote: 'killing the command and releasing the order',
224
+ stopReason: 'signal',
225
+ });
226
+ const outcome = await loop.run();
227
+ return exitCodeFor(outcome);
228
+ }
@@ -0,0 +1,72 @@
1
+ import { type HubClient } from '../hub/client.ts';
2
+ import { type HoldOutcome } from '../hold/loop.ts';
3
+ import { type HoldMcpToolName } from '../hold/mcp.ts';
4
+ import type { ContactHolder } from '../hub/types.ts';
5
+ import { type SignalHost, type StdinHost } from './signals.ts';
6
+ interface ParsedArgs {
7
+ order?: string;
8
+ workflow?: string;
9
+ session?: string;
10
+ origin?: string;
11
+ as?: string;
12
+ shift?: string;
13
+ heartbeatIntervalMs?: number;
14
+ jumpToleranceMs?: number;
15
+ ignoreStdin: boolean;
16
+ mcp: boolean;
17
+ mcpTools?: HoldMcpToolName[];
18
+ error?: string;
19
+ }
20
+ /** Parse `--flag value` and `--flag=value`; unknown flags are an error. */
21
+ export declare function parseArgs(args: string[]): ParsedArgs;
22
+ /**
23
+ * Resolve (workflow, run) from `--order` (+ optional `--workflow`).
24
+ * - composite `<workflow>/<run>`: split on the FIRST `/` only (run ids must
25
+ * not be silently truncated). A conflicting `--workflow` is a usage error.
26
+ * - bare `<run>`: requires `--workflow`.
27
+ */
28
+ export declare function resolveTarget(order: string, workflowFlag?: string): {
29
+ workflow: string;
30
+ run: string;
31
+ } | {
32
+ error: string;
33
+ };
34
+ /**
35
+ * Resolve the born-bound `--shift` cid: explicit `--shift`, else env
36
+ * `OWENLOOP_SHIFT_ID`, else `undefined` (no cid known — a hand-run hold
37
+ * with no stamped/exported cid). Advisory only (D8/INV-82).
38
+ */
39
+ export declare function resolveShiftId(shift: string | undefined, env: Record<string, string | undefined>): string | undefined;
40
+ /**
41
+ * Resolve the B3 session-holder tag (D5): explicit `--session`, else env
42
+ * `OWENLOOP_SESSION`, else a per-process fallback `anon:<hostname>:<pid>` —
43
+ * NEVER undefined. The fallback is deliberately unique per process (not a
44
+ * shared constant like `'anon'`): `release --session <id>` drains match on
45
+ * session id, and a shared constant would let unrelated Shifts' claims
46
+ * collide in a drain. `opts.shiftId` rides along on the holder when known
47
+ * (advisory only, D8/INV-82); `opts.hostname`/`opts.pid` are test seams.
48
+ */
49
+ export declare function resolveHolder(session: string | undefined, env: Record<string, string | undefined>, opts?: {
50
+ shiftId?: string;
51
+ hostname?: string;
52
+ pid?: number;
53
+ }): ContactHolder;
54
+ /** Map the loop's outcome onto the process exit code (see usage.ts). */
55
+ export declare function exitCodeFor(outcome: HoldOutcome): number;
56
+ /**
57
+ * Injectable process-boundary deps for `run` — defaulting to the real ones.
58
+ * Mirrors the loop's injected-seams pattern so the ROLE wiring (signal
59
+ * handlers, stdin-EOF watcher, message lines) is testable without signaling
60
+ * the test process, closing real stdin, or reaching a real hub.
61
+ */
62
+ export interface RunDeps {
63
+ signalHost?: SignalHost;
64
+ stdin?: StdinHost;
65
+ hub?: HubClient;
66
+ out?: (line: string) => void;
67
+ err?: (line: string) => void;
68
+ /** Environment used for settings and local trust-root resolution. */
69
+ env?: Record<string, string | undefined>;
70
+ }
71
+ export declare function run(args: string[], deps?: RunDeps): Promise<number>;
72
+ export {};
@@ -0,0 +1,363 @@
1
+ /**
2
+ * `owenloop work hold --order <id>` (C4) — keeps one order's lease alive on behalf
3
+ * of an interactive session and performs the final-breath handoff when that
4
+ * session goes away.
5
+ *
6
+ * It heartbeats the order's lease on a safe cadence (default 60s — well inside
7
+ * the hub's reap TTL; no verb exposes the TTL, so the cadence is a client
8
+ * constant) with jitter/backoff on transient failures, and on SIGINT, SIGTERM,
9
+ * or stdin EOF performs a targeted `release` so the order re-offers immediately
10
+ * instead of stranding until its lease expires. The loop CORE lives in
11
+ * `src/hold/loop.ts` with every side effect injected; this role parses flags,
12
+ * resolves origin/token, builds the real hub client, wires the signal + stdin
13
+ * seams (`src/roles/signals.ts`), and maps the loop's `HoldOutcome` to an exit
14
+ * code.
15
+ *
16
+ * SESSION IDENTITY: `--session <id>` (env fallback `OWENLOOP_SESSION`) rides
17
+ * every get_order/heartbeat as the B3 holder tag `{kind:'session', id}`. A
18
+ * holder is now ALWAYS sent (D5): when no session id is configured, `id`
19
+ * falls back to `anon:<hostname>:<pid>` — never omitted. Only `kind:'session'`
20
+ * — exec identity is C5's.
21
+ *
22
+ * SHIFT ATTRIBUTION: `--shift <cid>` (env fallback
23
+ * `OWENLOOP_SHIFT_ID`), when known, rides along on the holder as
24
+ * `shiftId` — self-declared and advisory only (D8/INV-82), never used for
25
+ * authorization, routing, dispatch, or claim correctness.
26
+ *
27
+ * STDIN EOF: a live stdin pipe closing means the parent interactive session
28
+ * died, so hold takes its final breath. When stdin is `/dev/null` or already
29
+ * closed at spawn (backgrounded/detached use), pass `--ignore-stdin` so hold
30
+ * does not final-breath at birth.
31
+ *
32
+ * Origin/credential resolution mirrors `shift`: origin `--origin` → settings;
33
+ * the bearer comes from owenloop's store via `resolveBearer`, reading the
34
+ * `agent:<account>` slot for `--as <account>` (default `default`, so a hand-run
35
+ * hold and a shift-stamped `hold --as <account>` both work), with
36
+ * `OWENLOOP_TOKEN` as a documented dev-only override. Exit codes are documented
37
+ * in `src/usage.ts`.
38
+ */
39
+ import { hostname } from 'node:os';
40
+ import { createHubClient } from "../hub/client.js";
41
+ import { resolveBearer } from "../credentials/resolve.js";
42
+ import { loadSettings } from "../settings/settings.js";
43
+ import { createHoldLoop } from "../hold/loop.js";
44
+ import { createHoldMcp, HOLD_MCP_TOOL_NAMES } from "../hold/mcp.js";
45
+ import { createConsumedVerifier } from "../consumed-verifier.js";
46
+ import { createMcpServer, pumpStdin } from "../mcp/server.js";
47
+ import { installSignalHandlers, watchStdinEof } from "./signals.js";
48
+ const DEFAULT_INTERVAL_MS = 60_000;
49
+ // Deliberate duplicate of main.ts's VERSION (also '0.0.0'): the roles must not
50
+ // import the CLI entry module, and the MCP serverInfo version is cosmetic.
51
+ const VERSION = '0.0.0';
52
+ function parseMcpTools(value) {
53
+ const names = value.split(',');
54
+ if (names.length === 0 || names.some((name) => name === '')) {
55
+ return { error: '--mcp-tools must be a comma-separated list with no empty names' };
56
+ }
57
+ const allowed = new Set(HOLD_MCP_TOOL_NAMES);
58
+ const unknown = names.filter((name) => !allowed.has(name));
59
+ if (unknown.length > 0) {
60
+ return {
61
+ error: `--mcp-tools contains unknown tool(s): ${unknown.join(', ')}; expected ${HOLD_MCP_TOOL_NAMES.join(',')}`,
62
+ };
63
+ }
64
+ if (new Set(names).size !== names.length) {
65
+ return { error: '--mcp-tools must not contain duplicate names' };
66
+ }
67
+ return names;
68
+ }
69
+ /** Parse `--flag value` and `--flag=value`; unknown flags are an error. */
70
+ export function parseArgs(args) {
71
+ const parsed = { ignoreStdin: false, mcp: false };
72
+ const takeValue = (a, i) => {
73
+ const eq = a.indexOf('=');
74
+ if (eq !== -1)
75
+ return { value: a.slice(eq + 1), next: i };
76
+ const v = args[i + 1];
77
+ if (v === undefined)
78
+ return { error: `missing value for ${a}` };
79
+ return { value: v, next: i + 1 };
80
+ };
81
+ for (let i = 0; i < args.length; i++) {
82
+ const a = args[i];
83
+ const name = a.startsWith('--') && a.includes('=') ? a.slice(0, a.indexOf('=')) : a;
84
+ switch (name) {
85
+ case '--ignore-stdin':
86
+ parsed.ignoreStdin = true;
87
+ break;
88
+ case '--mcp':
89
+ parsed.mcp = true;
90
+ break;
91
+ case '--order':
92
+ case '--workflow':
93
+ case '--session':
94
+ case '--origin':
95
+ case '--as':
96
+ case '--shift':
97
+ case '--heartbeat-interval':
98
+ case '--jump-tolerance':
99
+ case '--mcp-tools': {
100
+ const r = takeValue(a, i);
101
+ if ('error' in r)
102
+ return { ignoreStdin: false, mcp: false, error: r.error };
103
+ i = r.next;
104
+ if (name === '--order')
105
+ parsed.order = r.value;
106
+ else if (name === '--workflow')
107
+ parsed.workflow = r.value;
108
+ else if (name === '--session')
109
+ parsed.session = r.value;
110
+ else if (name === '--origin')
111
+ parsed.origin = r.value;
112
+ else if (name === '--as')
113
+ parsed.as = r.value;
114
+ else if (name === '--shift')
115
+ parsed.shift = r.value;
116
+ else if (name === '--mcp-tools') {
117
+ const selected = parseMcpTools(r.value);
118
+ if ('error' in selected)
119
+ return { ignoreStdin: false, mcp: false, error: selected.error };
120
+ parsed.mcpTools = selected;
121
+ }
122
+ else if (name === '--heartbeat-interval') {
123
+ const n = Number(r.value);
124
+ if (!Number.isFinite(n) || !Number.isInteger(n) || n <= 0) {
125
+ return { ignoreStdin: false, mcp: false, error: `--heartbeat-interval must be a positive integer, got '${r.value}'` };
126
+ }
127
+ parsed.heartbeatIntervalMs = n;
128
+ }
129
+ else if (name === '--jump-tolerance') {
130
+ const n = Number(r.value);
131
+ if (!Number.isFinite(n) || !Number.isInteger(n) || n <= 0) {
132
+ return { ignoreStdin: false, mcp: false, error: `--jump-tolerance must be a positive integer, got '${r.value}'` };
133
+ }
134
+ parsed.jumpToleranceMs = n;
135
+ }
136
+ break;
137
+ }
138
+ default:
139
+ return { ignoreStdin: false, mcp: false, error: `unknown option '${a}'` };
140
+ }
141
+ }
142
+ return parsed;
143
+ }
144
+ /** Both accepted `--order` forms, for usage messages. */
145
+ const ORDER_FORMS = '--order <workflow>/<run> (or --order <run> --workflow <wf>)';
146
+ /**
147
+ * Resolve (workflow, run) from `--order` (+ optional `--workflow`).
148
+ * - composite `<workflow>/<run>`: split on the FIRST `/` only (run ids must
149
+ * not be silently truncated). A conflicting `--workflow` is a usage error.
150
+ * - bare `<run>`: requires `--workflow`.
151
+ */
152
+ export function resolveTarget(order, workflowFlag) {
153
+ const slash = order.indexOf('/');
154
+ if (slash !== -1) {
155
+ const workflow = order.slice(0, slash);
156
+ const run = order.slice(slash + 1);
157
+ if (workflow === '' || run === '') {
158
+ return { error: `--order '${order}' is malformed — expected ${ORDER_FORMS}` };
159
+ }
160
+ if (workflowFlag !== undefined && workflowFlag !== workflow) {
161
+ return { error: `--order carries workflow '${workflow}' but --workflow says '${workflowFlag}' — drop one` };
162
+ }
163
+ return { workflow, run };
164
+ }
165
+ if (workflowFlag === undefined || workflowFlag === '') {
166
+ return { error: `--order '${order}' has no workflow — use ${ORDER_FORMS}` };
167
+ }
168
+ return { workflow: workflowFlag, run: order };
169
+ }
170
+ function usage() {
171
+ process.stderr.write('usage: owenloop work hold --order <workflow>/<run> [--origin <url>] [--as <account>] [--session <id>]\n' +
172
+ ' [--shift <id>] [--heartbeat-interval <ms>] [--jump-tolerance <ms>] [--ignore-stdin] [--mcp]\n' +
173
+ ' [--mcp-tools <get_order,submit,reject>]\n' +
174
+ ' or: owenloop work hold --order <run> --workflow <wf> [...]\n');
175
+ }
176
+ function errMsg(err) {
177
+ return err instanceof Error ? err.message : String(err);
178
+ }
179
+ /**
180
+ * Resolve the born-bound `--shift` cid: explicit `--shift`, else env
181
+ * `OWENLOOP_SHIFT_ID`, else `undefined` (no cid known — a hand-run hold
182
+ * with no stamped/exported cid). Advisory only (D8/INV-82).
183
+ */
184
+ export function resolveShiftId(shift, env) {
185
+ const id = shift ?? env['OWENLOOP_SHIFT_ID'];
186
+ return id !== undefined && id !== '' ? id : undefined;
187
+ }
188
+ /**
189
+ * Resolve the B3 session-holder tag (D5): explicit `--session`, else env
190
+ * `OWENLOOP_SESSION`, else a per-process fallback `anon:<hostname>:<pid>` —
191
+ * NEVER undefined. The fallback is deliberately unique per process (not a
192
+ * shared constant like `'anon'`): `release --session <id>` drains match on
193
+ * session id, and a shared constant would let unrelated Shifts' claims
194
+ * collide in a drain. `opts.shiftId` rides along on the holder when known
195
+ * (advisory only, D8/INV-82); `opts.hostname`/`opts.pid` are test seams.
196
+ */
197
+ export function resolveHolder(session, env, opts = {}) {
198
+ const configured = session ?? env['OWENLOOP_SESSION'];
199
+ const id = configured !== undefined && configured !== '' ? configured : `anon:${opts.hostname ?? hostname()}:${opts.pid ?? process.pid}`;
200
+ return {
201
+ kind: 'session',
202
+ id,
203
+ ...(opts.shiftId !== undefined ? { shiftId: opts.shiftId } : {}),
204
+ };
205
+ }
206
+ /** Map the loop's outcome onto the process exit code (see usage.ts). */
207
+ export function exitCodeFor(outcome) {
208
+ switch (outcome) {
209
+ case 'completed':
210
+ case 'released':
211
+ case 'stopped':
212
+ return 0;
213
+ case 'ownership-error':
214
+ case 'lease-lost':
215
+ case 'hub-unreachable':
216
+ case 'release-failed':
217
+ return 1;
218
+ }
219
+ }
220
+ export async function run(args, deps = {}) {
221
+ const out = deps.out ?? ((line) => void process.stdout.write(`${line}\n`));
222
+ const err = deps.err ?? ((line) => void process.stderr.write(`${line}\n`));
223
+ const parsed = parseArgs(args);
224
+ if (parsed.error !== undefined) {
225
+ err(`owenloop work hold: ${parsed.error}`);
226
+ usage();
227
+ return 2;
228
+ }
229
+ if (parsed.order === undefined || parsed.order === '') {
230
+ err('owenloop work hold: missing required --order <id>');
231
+ usage();
232
+ return 2;
233
+ }
234
+ // In --mcp mode stdin IS the JSON-RPC transport; its EOF is the session-death
235
+ // signal that fires the final breath. --ignore-stdin (don't watch stdin) is
236
+ // therefore contradictory.
237
+ if (parsed.mcp && parsed.ignoreStdin) {
238
+ err('owenloop work hold: --mcp and --ignore-stdin are mutually exclusive (stdin is the MCP transport)');
239
+ usage();
240
+ return 2;
241
+ }
242
+ if (parsed.mcpTools !== undefined && !parsed.mcp) {
243
+ err('owenloop work hold: --mcp-tools requires --mcp');
244
+ usage();
245
+ return 2;
246
+ }
247
+ const target = resolveTarget(parsed.order, parsed.workflow);
248
+ if ('error' in target) {
249
+ err(`owenloop work hold: ${target.error}`);
250
+ usage();
251
+ return 2;
252
+ }
253
+ const env = deps.env ?? process.env;
254
+ let settings;
255
+ try {
256
+ settings = loadSettings(env);
257
+ }
258
+ catch (e) {
259
+ err(`owenloop work hold: ${errMsg(e)}`);
260
+ return 1;
261
+ }
262
+ const origin = parsed.origin ?? settings.hubOrigin;
263
+ if (origin === undefined || origin.trim() === '') {
264
+ err('owenloop work hold: no hub origin — pass --origin <url> or set hubOrigin in settings');
265
+ return 2;
266
+ }
267
+ if (parsed.as !== undefined && parsed.as.trim() === '') {
268
+ err('owenloop work hold: --as requires a non-empty account name');
269
+ return 2;
270
+ }
271
+ const account = parsed.as ?? 'default';
272
+ const bearer = await resolveBearer({ origin, account, env });
273
+ if (!bearer.ok) {
274
+ err(`owenloop work hold: ${bearer.message}`);
275
+ return bearer.code;
276
+ }
277
+ const token = bearer.token;
278
+ const shiftId = resolveShiftId(parsed.shift, env);
279
+ const holder = resolveHolder(parsed.session, env, { shiftId });
280
+ const hub = deps.hub ?? createHubClient({ origin, getToken: async () => token });
281
+ // --mcp: run the born-bound work-holder as a stdio MCP server. The default
282
+ // registers get_order/submit/reject; --mcp-tools selects an exact positive
283
+ // subset. The lease loop stays warm underneath. stdout is the JSON-RPC
284
+ // channel, so every diagnostic (and the loop's own lines) goes to stderr;
285
+ // stdin is the transport, and its EOF (the session died) fires the final
286
+ // breath.
287
+ if (parsed.mcp) {
288
+ const mount = createHoldMcp({
289
+ hub,
290
+ workflow: target.workflow,
291
+ run: target.run,
292
+ ...(parsed.mcpTools !== undefined ? { tools: parsed.mcpTools } : {}),
293
+ origin,
294
+ env,
295
+ consumedVerifier: createConsumedVerifier({
296
+ env,
297
+ now: () => Date.now(),
298
+ }),
299
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
300
+ now: () => Date.now(),
301
+ err,
302
+ holder,
303
+ ...(parsed.heartbeatIntervalMs !== undefined ? { heartbeatIntervalMs: parsed.heartbeatIntervalMs } : {}),
304
+ ...(parsed.jumpToleranceMs !== undefined ? { jumpToleranceMs: parsed.jumpToleranceMs } : {}),
305
+ });
306
+ const server = createMcpServer({
307
+ name: 'owenloop-hold',
308
+ version: VERSION,
309
+ tools: mount.tools,
310
+ write: (msg) => void process.stdout.write(`${JSON.stringify(msg)}\n`),
311
+ err,
312
+ });
313
+ installSignalHandlers(mount.loop, deps.signalHost ?? process, err, {
314
+ role: 'hold',
315
+ drainNote: 'final breath',
316
+ stopReason: 'signal',
317
+ });
318
+ // The MCP server must keep answering until the TRANSPORT ends, not until
319
+ // the lease loop does (plan section 4): a submit that closes the run
320
+ // terminates the loop, but the submit's own response frame may still be
321
+ // racing down the stdout pipe and the client may issue further calls (they
322
+ // fast-fail via the mount's terminal guard). So: stdin EOF is both the
323
+ // final-breath trigger AND the exit condition; the loop's outcome only
324
+ // decides the exit code. A signal stops the loop early too — the process
325
+ // then serves fast-fails until the parent closes the pipe (a second signal
326
+ // still hard-exits via installSignalHandlers).
327
+ const stdin = (deps.stdin ?? process.stdin);
328
+ const eof = new Promise((resolve) => {
329
+ pumpStdin(stdin, server, () => {
330
+ mount.loop.stop('stdin-eof');
331
+ resolve();
332
+ });
333
+ });
334
+ const outcome = await mount.loop.run();
335
+ await eof;
336
+ return exitCodeFor(outcome);
337
+ }
338
+ const loop = createHoldLoop({
339
+ hub,
340
+ workflow: target.workflow,
341
+ run: target.run,
342
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
343
+ now: () => Date.now(),
344
+ out,
345
+ err,
346
+ heartbeatIntervalMs: parsed.heartbeatIntervalMs ?? DEFAULT_INTERVAL_MS,
347
+ // Test affordance only: exposes the lease loop's existing jumpToleranceMs
348
+ // knob (default unchanged) so a drill can trip the clock-jump lease check
349
+ // with a short freeze instead of a real >30s laptop sleep.
350
+ ...(parsed.jumpToleranceMs !== undefined ? { jumpToleranceMs: parsed.jumpToleranceMs } : {}),
351
+ holder,
352
+ });
353
+ installSignalHandlers(loop, deps.signalHost ?? process, err, {
354
+ role: 'hold',
355
+ drainNote: 'final breath',
356
+ stopReason: 'signal',
357
+ });
358
+ if (!parsed.ignoreStdin) {
359
+ watchStdinEof(deps.stdin ?? process.stdin, () => loop.stop('stdin-eof'));
360
+ }
361
+ const outcome = await loop.run();
362
+ return exitCodeFor(outcome);
363
+ }
@@ -0,0 +1,18 @@
1
+ import type { Keychain } from '../../../../src/hub.ts';
2
+ interface ParsedArgs {
3
+ code?: string;
4
+ hub?: string;
5
+ as?: string;
6
+ error?: string;
7
+ }
8
+ /** Parse `<code> [--hub <origin>] [--as <account>]`, both `--flag value` and `--flag=value` forms. */
9
+ export declare function parseArgs(args: string[]): ParsedArgs;
10
+ export interface RunDeps {
11
+ out?: (line: string) => void;
12
+ err?: (line: string) => void;
13
+ env?: Record<string, string | undefined>;
14
+ fetchImpl?: typeof fetch;
15
+ keychain?: Keychain;
16
+ }
17
+ export declare function run(args: string[], deps?: RunDeps): Promise<number>;
18
+ export {};