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,277 @@
1
+ /**
2
+ * The lease-loop core — keeps ONE order's lease alive by heartbeating the hub
3
+ * on a safe cadence, and performs a bounded final-breath release on shutdown.
4
+ *
5
+ * Extracted from C4's `hold` loop (C5, plan decision 4) so the two self-leasing
6
+ * roles share ONE implementation of cadence/backoff/clock-jump/classification/
7
+ * final-breath rather than duplicating it:
8
+ * - `hold` (`src/hold/loop.ts`) wraps this with `role: 'hold'` — its observable
9
+ * behavior (outcomes, exit codes, every emitted message string) is unchanged;
10
+ * the hold tests pass unedited.
11
+ * - `exec` (`src/exec/loop.ts`) wraps this with `role: 'exec'` and an `onOrder`
12
+ * callback so it can read the first-contact order packet and run the command
13
+ * while this loop keeps the lease warm underneath it.
14
+ *
15
+ * Like C3's shift loop, every side effect is injected (hub client, sleep/clock,
16
+ * jitter, output sinks) so every test drives it with a fake hub, a scriptable
17
+ * clock, and no real timers.
18
+ *
19
+ * LIFECYCLE
20
+ * - First contact: `get_order({workflow, run, holder})`. This beats the lease,
21
+ * closes the B2 pickup window, tags the holder, and validates the
22
+ * (workflow, run) pairing. On a claimed lease it fires `onOrder(res)` (so the
23
+ * caller can read the packet from the SAME response — no second fetch) and
24
+ * returns `holding`. `lease.claimed:false` with an `outcome` ⇒ the order
25
+ * already finished (`completed`); with no outcome ⇒ nothing to hold
26
+ * (`lease-lost`). A 403 ⇒ `ownership-error`; other throws retry under the
27
+ * backoff policy before giving up `hub-unreachable`.
28
+ * - Tick: abortable `sleep(heartbeatIntervalMs)` → clock-jump check (a wall gap
29
+ * beyond interval + tolerance, e.g. a laptop sleeping, triggers a `get_order`
30
+ * lease check BEFORE the next beat so we fail fast on a dead lease) →
31
+ * `heartbeat({workflow, run, holder})`.
32
+ * - Heartbeat failure: 403 ⇒ `ownership-error` immediately; any other error
33
+ * (the engine's lease-gone 500 included) is classified via `get_order`
34
+ * (`outcome` ⇒ `completed`, unclaimed ⇒ `lease-lost`, still claimed / classify
35
+ * failed ⇒ transient). Transient failures back off (exponential + jitter,
36
+ * base 1s ×2 cap 30s) without ever sleeping past the failure window; once
37
+ * consecutive failures span `failureWindowMs`, one last classify then
38
+ * `hub-unreachable`.
39
+ * - `stop(reason, {release?})` flips a flag checked between awaits AND aborts
40
+ * the in-flight interval sleep (final breath fires ~immediately, not up to a
41
+ * full interval late), then — unless the order already `completed` or the
42
+ * caller passed `release:false` — a targeted `release` bounded at
43
+ * RELEASE_CAP_MS. `release:false` is exec's "the run just closed via submit,
44
+ * don't release" path (a release then would be a confusing no-op). Release is
45
+ * idempotent hub-side (`not-held` is a no-op, never a throw), so a normal
46
+ * completion or a reaper race both land as `released`; a throw/timeout is
47
+ * `release-failed`.
48
+ *
49
+ * OUTCOME → the role maps each to an exit code in one place (see the roles).
50
+ */
51
+ import { HubError } from "../hub/types.js";
52
+ const DEFAULT_INTERVAL_MS = 60_000;
53
+ const DEFAULT_JUMP_TOLERANCE_MS = 30_000;
54
+ const DEFAULT_FAILURE_WINDOW_MS = 180_000;
55
+ const BACKOFF_BASE_MS = 1_000;
56
+ const BACKOFF_CAP_MS = 30_000;
57
+ const BACKOFF_JITTER = 0.2;
58
+ const RELEASE_CAP_MS = 5_000;
59
+ function errMsg(e) {
60
+ return e instanceof Error ? e.message : String(e);
61
+ }
62
+ function isForbidden(e) {
63
+ return e instanceof HubError && e.status === 403;
64
+ }
65
+ export function createLeaseLoop(opts) {
66
+ const interval = opts.heartbeatIntervalMs ?? DEFAULT_INTERVAL_MS;
67
+ const jumpTolerance = opts.jumpToleranceMs ?? DEFAULT_JUMP_TOLERANCE_MS;
68
+ const failureWindow = opts.failureWindowMs ?? DEFAULT_FAILURE_WINDOW_MS;
69
+ const random = opts.random ?? Math.random;
70
+ const { workflow, role } = opts;
71
+ const runId = opts.run;
72
+ const req = { workflow, run: runId, ...(opts.holder !== undefined ? { holder: opts.holder } : {}) };
73
+ let stopped = false;
74
+ let stopReason = '';
75
+ let releaseOnStop = true;
76
+ // A single stop promise, resolved once, so any in-flight (or later) abortable
77
+ // sleep returns immediately after stop().
78
+ let resolveStop;
79
+ const stopPromise = new Promise((r) => {
80
+ resolveStop = r;
81
+ });
82
+ // Shared consecutive-failure tracker (first contact + heartbeat both feed it).
83
+ let firstFailureAt;
84
+ let attempt = 0;
85
+ function recordFailure() {
86
+ if (firstFailureAt === undefined)
87
+ firstFailureAt = opts.now();
88
+ attempt++;
89
+ }
90
+ function resetFailures() {
91
+ firstFailureAt = undefined;
92
+ attempt = 0;
93
+ }
94
+ function failureWindowExceeded() {
95
+ return firstFailureAt !== undefined && opts.now() - firstFailureAt >= failureWindow;
96
+ }
97
+ /** Sleep that resolves early when stop() fires. */
98
+ async function abortableSleep(ms) {
99
+ if (stopped)
100
+ return;
101
+ await Promise.race([opts.sleep(ms), stopPromise]);
102
+ }
103
+ /** Backoff delay for the current `attempt`, jittered and window-bounded. */
104
+ function backoffDelay() {
105
+ const raw = Math.min(BACKOFF_CAP_MS, BACKOFF_BASE_MS * 2 ** Math.max(0, attempt - 1));
106
+ const jittered = raw * (1 + (random() * 2 - 1) * BACKOFF_JITTER);
107
+ let delay = Math.max(0, Math.round(jittered));
108
+ // Never sleep past the failure window — leave room for the final classify.
109
+ if (firstFailureAt !== undefined) {
110
+ const remaining = failureWindow - (opts.now() - firstFailureAt);
111
+ if (remaining > 0)
112
+ delay = Math.min(delay, remaining);
113
+ }
114
+ return delay;
115
+ }
116
+ /**
117
+ * A get_order lease probe used for the clock-jump check and for classifying a
118
+ * heartbeat failure. Any throw (including a 403, which on this path means the
119
+ * hub is being flaky rather than a fresh ownership loss the beat already
120
+ * surfaced) is reported as `transient` so the caller's backoff owns it.
121
+ */
122
+ async function probe() {
123
+ try {
124
+ const res = await opts.hub.getOrder(req);
125
+ if (res.lease.claimed)
126
+ return 'holding';
127
+ return res.lease.outcome !== undefined ? 'completed' : 'lease-lost';
128
+ }
129
+ catch {
130
+ return 'transient';
131
+ }
132
+ }
133
+ /**
134
+ * Establish the hold. Returns `holding` once the lease is confirmed (after
135
+ * firing `onOrder`), a terminal outcome, or `stopped` if stop() arrived before
136
+ * we established it.
137
+ */
138
+ async function firstContact() {
139
+ for (;;) {
140
+ if (stopped)
141
+ return 'stopped';
142
+ try {
143
+ const res = await opts.hub.getOrder(req);
144
+ resetFailures();
145
+ if (res.lease.claimed) {
146
+ opts.onOrder?.(res);
147
+ return 'holding';
148
+ }
149
+ return res.lease.outcome !== undefined ? 'completed' : 'lease-lost';
150
+ }
151
+ catch (e) {
152
+ if (isForbidden(e)) {
153
+ opts.err(`owenloop work ${role}: ${workflow}/${runId} is not yours to hold (forbidden)`);
154
+ return 'ownership-error';
155
+ }
156
+ recordFailure();
157
+ opts.err(`owenloop work ${role}: first contact failed: ${errMsg(e)} (retrying)`);
158
+ if (failureWindowExceeded())
159
+ return 'hub-unreachable';
160
+ await abortableSleep(backoffDelay());
161
+ }
162
+ }
163
+ }
164
+ /** One heartbeat tick. Returns a terminal outcome, or `undefined` to continue. */
165
+ async function tick() {
166
+ const before = opts.now();
167
+ await abortableSleep(interval);
168
+ if (stopped)
169
+ return undefined; // final breath handled by the caller
170
+ // Clock-jump guard: a wall gap well beyond the interval (laptop sleep) means
171
+ // the lease may have lapsed while we were suspended — check before beating.
172
+ const gap = opts.now() - before;
173
+ if (gap > interval + jumpTolerance) {
174
+ opts.err(`owenloop work ${role}: clock jump detected (${gap}ms gap) — verifying lease before beat`);
175
+ const p = await probe();
176
+ if (p === 'completed')
177
+ return 'completed';
178
+ if (p === 'lease-lost')
179
+ return 'lease-lost';
180
+ // 'holding' → carry on and beat; 'transient' → fall through, the beat's
181
+ // own failure handling will pick up the unreachable hub.
182
+ }
183
+ try {
184
+ await opts.hub.heartbeat(req);
185
+ resetFailures();
186
+ return undefined;
187
+ }
188
+ catch (e) {
189
+ if (isForbidden(e)) {
190
+ opts.err(`owenloop work ${role}: heartbeat forbidden — the claim is no longer yours`);
191
+ return 'ownership-error';
192
+ }
193
+ // Classify the failure: did the order finish, or was the lease lost?
194
+ const p = await probe();
195
+ if (p === 'completed')
196
+ return 'completed';
197
+ if (p === 'lease-lost')
198
+ return 'lease-lost';
199
+ // Transient (still claimed, or the classify call itself failed): back off.
200
+ recordFailure();
201
+ opts.err(`owenloop work ${role}: heartbeat failed: ${errMsg(e)} (attempt ${attempt}, backing off)`);
202
+ if (failureWindowExceeded()) {
203
+ const last = await probe();
204
+ if (last === 'completed')
205
+ return 'completed';
206
+ if (last === 'lease-lost')
207
+ return 'lease-lost';
208
+ opts.err(`owenloop work ${role}: hub unreachable for ${failureWindow}ms — giving up`);
209
+ return 'hub-unreachable';
210
+ }
211
+ await abortableSleep(backoffDelay());
212
+ return undefined;
213
+ }
214
+ }
215
+ /**
216
+ * The final breath: a targeted release, bounded at RELEASE_CAP_MS. Skipped
217
+ * when the order already completed (a completed order has no claim to hand
218
+ * back) or when stop() asked for `release:false`. Idempotent hub-side, so
219
+ * `not-held` is success.
220
+ */
221
+ async function finalBreath(alreadyCompleted) {
222
+ if (alreadyCompleted)
223
+ return 'completed';
224
+ if (!releaseOnStop)
225
+ return 'stopped';
226
+ opts.out(`owenloop work ${role}: final breath (${stopReason || 'stop'}) — releasing ${workflow}/${runId}`);
227
+ try {
228
+ const raced = await Promise.race([
229
+ opts.hub.release({ workflow, run: runId }).then(() => 'ok'),
230
+ opts.sleep(RELEASE_CAP_MS).then(() => 'timeout'),
231
+ ]);
232
+ if (raced === 'timeout') {
233
+ opts.err(`owenloop work ${role}: release timed out after ${RELEASE_CAP_MS}ms — order strands until its lease TTL`);
234
+ return 'release-failed';
235
+ }
236
+ opts.out(`owenloop work ${role}: released ${workflow}/${runId} — the order re-offers on the next tick`);
237
+ return 'released';
238
+ }
239
+ catch (e) {
240
+ opts.err(`owenloop work ${role}: release failed: ${errMsg(e)} — order strands until its lease TTL`);
241
+ return 'release-failed';
242
+ }
243
+ }
244
+ async function run() {
245
+ const fc = await firstContact();
246
+ if (fc === 'stopped')
247
+ return 'stopped';
248
+ if (fc !== 'holding')
249
+ return fc;
250
+ opts.out(`owenloop work ${role}: holding ${workflow}/${runId}` +
251
+ (opts.holder !== undefined ? ` as ${opts.holder.kind} ${opts.holder.id}` : '') +
252
+ ` (heartbeat every ${interval}ms)`);
253
+ for (;;) {
254
+ if (stopped)
255
+ break;
256
+ const outcome = await tick();
257
+ if (outcome === 'completed')
258
+ return 'completed';
259
+ if (outcome !== undefined)
260
+ return outcome;
261
+ if (stopped)
262
+ break;
263
+ }
264
+ // Stopped while holding → hand off.
265
+ return finalBreath(false);
266
+ }
267
+ function stop(reason, stopOpts) {
268
+ if (stopped)
269
+ return;
270
+ stopped = true;
271
+ stopReason = reason ?? '';
272
+ if (stopOpts?.release === false)
273
+ releaseOnStop = false;
274
+ resolveStop();
275
+ }
276
+ return { run, stop };
277
+ }
@@ -0,0 +1 @@
1
+ export declare function mainAsync(argv: string[]): Promise<number>;
@@ -0,0 +1,48 @@
1
+ /**
2
+ * `owenloop work` entry point: parse argv, dispatch one execution role, and map
3
+ * the role's returned code onto the process exit code.
4
+ *
5
+ * Exit-code contract (stable; roles and scripts depend on it):
6
+ * 0 success, or `--help` / `help` / `--version`
7
+ * 2 usage error — unknown or missing role, or a role's own arg validation
8
+ * failed (missing `--order`, missing `<order-id>`, …). Usage goes to stderr.
9
+ * 3 a role is a not-yet-implemented skeleton stub. Distinct from 0 so a
10
+ * script can never mistake a stub's "did nothing" for real success.
11
+ *
12
+ * The role table contains loaders rather than imported functions. This keeps
13
+ * `owenloop work settings` and `owenloop work lint` from evaluating unrelated
14
+ * worker or harness modules, and leaves the model SDK behind the adapter's own
15
+ * dynamic import boundary.
16
+ */
17
+ import { USAGE } from "./usage.js";
18
+ const VERSION = '0.0.0';
19
+ const ROLES = {
20
+ hold: () => import("./roles/hold.js"),
21
+ exec: () => import("./roles/exec.js"),
22
+ 'agent-run': () => import("./roles/agent-run.js"),
23
+ prepare: () => import("./roles/prepare.js"),
24
+ lint: () => import("./roles/lint.js"),
25
+ settings: () => import("./roles/settings.js"),
26
+ release: () => import("./roles/release.js"),
27
+ join: () => import("./roles/join.js"),
28
+ sessions: () => import("./roles/sessions.js"),
29
+ };
30
+ export async function mainAsync(argv) {
31
+ const [first, ...rest] = argv;
32
+ if (first === undefined || first === '--help' || first === '-h' || first === 'help') {
33
+ process.stdout.write(USAGE);
34
+ return 0;
35
+ }
36
+ if (first === '--version') {
37
+ process.stdout.write(`${VERSION}\n`);
38
+ return 0;
39
+ }
40
+ const loader = ROLES[first];
41
+ if (loader === undefined) {
42
+ process.stderr.write(`owenloop work: unknown command '${first}'\n\n`);
43
+ process.stderr.write(USAGE);
44
+ return 2;
45
+ }
46
+ const module = await loader();
47
+ return module.run(rest);
48
+ }
@@ -0,0 +1,125 @@
1
+ /**
2
+ * A minimal, dependency-light MCP server core — newline-delimited JSON-RPC 2.0
3
+ * over stdio, hand-rolled (plan decision 1).
4
+ *
5
+ * WHY hand-rolled, not `@modelcontextprotocol/sdk`: this repo's posture is one
6
+ * runtime dep (`yaml`). The SDK drags zod and a transport stack for a surface we
7
+ * need only a few hundred lines of. The hub side already proves interop against
8
+ * the official SDK client, and the `--mcp` e2e tests here drive a real
9
+ * client-side handshake, so drift is tested rather than assumed.
10
+ *
11
+ * The core is transport-agnostic and side-effect-injected: it exposes
12
+ * `handleLine(line)` (feed it one framed JSON-RPC line) and `close(reason)`
13
+ * (transport EOF), and it emits every outbound frame through the injected
14
+ * `write(msg)`. Unit tests feed lines and inspect writes with no child process;
15
+ * `pumpStdin` wires the real `process.stdin`/`process.stdout` in the roles.
16
+ *
17
+ * Supported methods (the subset the Shift + work-holder need):
18
+ * - `initialize` → capabilities `{tools:{}}`, serverInfo, and the
19
+ * agreed protocolVersion (echo the client's when
20
+ * recognized, else answer with ours).
21
+ * - `notifications/initialized` → no-op (no response; it is a notification).
22
+ * - `ping` → `{}`.
23
+ * - `tools/list` → the registered tool defs.
24
+ * - `tools/call` → dispatch to the tool handler; the result is
25
+ * `{content:[{type:'text',text:<JSON>}], isError?}`.
26
+ * - `notifications/cancelled` → abort a tracked in-flight `tools/call`; the
27
+ * aborted call sends NO response frame.
28
+ * - outbound `notifications/progress` when a call carried
29
+ * `params._meta.progressToken` (via `ctx.sendProgress`).
30
+ *
31
+ * Errors: unknown method → -32601; malformed JSON / bad envelope → -32700;
32
+ * invalid params → -32602. A notification (no `id`) never gets a response, even
33
+ * on error. The process must never crash on a bad line.
34
+ */
35
+ export declare const PARSE_ERROR = -32700;
36
+ export declare const INVALID_REQUEST = -32600;
37
+ export declare const METHOD_NOT_FOUND = -32601;
38
+ export declare const INVALID_PARAMS = -32602;
39
+ export declare const INTERNAL_ERROR = -32603;
40
+ /** A tool result as MCP serves it: text content blocks, optional error flag. */
41
+ export interface ToolResult {
42
+ content: Array<{
43
+ type: 'text';
44
+ text: string;
45
+ }>;
46
+ isError?: boolean;
47
+ }
48
+ /** Convenience: wrap a JSON-able value as a single text content block. */
49
+ export declare function textResult(value: unknown, isError?: boolean): ToolResult;
50
+ /** The per-call context handed to a tool handler. */
51
+ export interface ToolCallContext {
52
+ /** True once the caller cancelled this request (`notifications/cancelled`). */
53
+ readonly cancelled: boolean;
54
+ /** Register a callback fired when this request is cancelled. */
55
+ onCancel(cb: () => void): void;
56
+ /**
57
+ * Emit a `notifications/progress` frame for this call. A no-op when the caller
58
+ * supplied no `progressToken` (progress is meaningless without one).
59
+ */
60
+ sendProgress(payload: {
61
+ progress?: number;
62
+ total?: number;
63
+ message?: string;
64
+ }): void;
65
+ }
66
+ export type ToolHandler = (args: Record<string, unknown>, ctx: ToolCallContext) => Promise<ToolResult> | ToolResult;
67
+ /** A registered tool: its advertised shape plus the handler that runs it. */
68
+ export interface ToolRegistration {
69
+ name: string;
70
+ description: string;
71
+ /** JSON-Schema for the tool's arguments (advertised via `tools/list`). */
72
+ inputSchema: Record<string, unknown>;
73
+ handler: ToolHandler;
74
+ }
75
+ export interface McpServerOptions {
76
+ name: string;
77
+ version: string;
78
+ tools: ToolRegistration[];
79
+ /** Outbound frame sink — the caller JSON-serializes + newline-terminates. */
80
+ write: (msg: unknown) => void;
81
+ /** Diagnostic sink (stderr); protocol frames never go here. */
82
+ err?: (line: string) => void;
83
+ }
84
+ export interface McpServer {
85
+ /** Feed one framed JSON-RPC line (no trailing newline required). */
86
+ handleLine(line: string): Promise<void>;
87
+ /**
88
+ * Transport EOF — cancels in-flight calls so parked handlers unblock. Their
89
+ * replies are still flushed (close-cancel ≠ client-cancel; see `InFlight`).
90
+ */
91
+ close(reason?: string): void;
92
+ }
93
+ export declare function createMcpServer(opts: McpServerOptions): McpServer;
94
+ /** The slice of a readable stream `pumpStdin` needs — injectable for tests. */
95
+ export interface LineStream {
96
+ on(event: 'data', handler: (chunk: Buffer | string) => void): unknown;
97
+ on(event: 'end' | 'close', handler: () => void): unknown;
98
+ setEncoding?(enc: string): void;
99
+ resume?(): void;
100
+ }
101
+ /**
102
+ * Wire a real byte stream (`process.stdin`) into a server: buffer bytes, split
103
+ * on newlines, feed each complete line to `server.handleLine`, and call
104
+ * `server.close` + `onEof` once on EOF. A trailing partial line at EOF is
105
+ * flushed if non-empty.
106
+ *
107
+ * Every line is DISPATCHED THE MOMENT IT ARRIVES — never queued behind an
108
+ * in-flight `tools/call`. JSON-RPC over MCP is a concurrent protocol: while a
109
+ * long `whats_next` park is outstanding, `notifications/cancelled` must reach
110
+ * the server to abort it (D12 cancel-mid-park) and `ping` must still answer.
111
+ * Serializing the pump behind the in-flight call chain would deadlock exactly
112
+ * those frames on the real transport. Per-frame ordering still holds for the
113
+ * non-parking methods because `handleLine` runs synchronously up to the first
114
+ * tool-handler await, and responses are matched by id, not by order.
115
+ *
116
+ * EOF flushes the tail line, then calls `server.close` RIGHT AWAY — `close()`
117
+ * cancels any parked in-flight call, which is what lets a process waiting on
118
+ * this pump actually exit (chaining the close behind a parked call would
119
+ * deadlock EOF against the very call only the close can unpark). A close-cancel
120
+ * does NOT suppress the call's reply the way a client cancel does — every call
121
+ * received before EOF still answers. `onEof` fires only after every dispatched
122
+ * line has settled, so those reply frames are on the pipe before the caller
123
+ * acts on EOF (e.g. exits the process).
124
+ */
125
+ export declare function pumpStdin(stream: LineStream, server: McpServer, onEof?: () => void): void;