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,669 @@
1
+ /**
2
+ * The `agent-run` orchestration core (Phase 3) — the detached, self-leasing
3
+ * worker that HOSTS one step agent instead of stamping a file for someone else
4
+ * to run.
5
+ *
6
+ * It is `src/exec/loop.ts` for AGENT orders: same shared lease loop, same
7
+ * first-contact race, same `mapNoHold`, same `stop()` guard, every side effect
8
+ * injected (hub, adapter resolution, step material, session-store writer,
9
+ * sleep/clock, output sinks) so tests drive it with fakes and no real process.
10
+ *
11
+ * ══ THE INVARIANT ══
12
+ *
13
+ * The step agent signals TASK completion by calling the `submit` MCP tool inside
14
+ * the mounted `owenloop work hold --mcp` grandchild. This worker learns of that ONLY
15
+ * from the hub lease outcome — `createLeaseLoop().run()` resolving `'completed'`,
16
+ * or a direct `hub.getOrder` seeing `lease.outcome`. The harness stream
17
+ * (`AgentEvent`) and the SETTLING of `adapter.start()` are telemetry and
18
+ * liveness only, and are never evidence of task success or failure.
19
+ *
20
+ * The trap this design exists to avoid: `start()` resolves at TURN end, which
21
+ * happens within milliseconds of the agent calling `submit`, while the worker's
22
+ * next lease heartbeat may be a full `heartbeatIntervalMs` away. A worker that
23
+ * read "`start()` settled with no outcome yet" as "the agent did not submit"
24
+ * would RELEASE a run that had just completed, and the hub would re-offer a
25
+ * closed order. So `start()` settling never releases. It only:
26
+ *
27
+ * 1. writes the session record `turn-ended`; then
28
+ * 2. enters the bounded CONFIRM phase (`confirmOutcome` below), racing the
29
+ * lease loop against a short-cadence `hub.getOrder` poll.
30
+ *
31
+ * ══ THE CLOSED CONTRACT QUESTION ══
32
+ *
33
+ * `docs/agent-runner.md` recorded the promise-settle semantics of a non-resume
34
+ * harness failure as OPEN: `start()` may reject with a plain `Error`, or resolve
35
+ * after emitting `exited`. As the single caller, Phase 3 CLOSES it: BOTH settle
36
+ * paths are treated identically — each writes `turn-ended` and enters the
37
+ * confirm phase, and neither is read as success or failure. Nothing in this file
38
+ * branches on the settle shape.
39
+ *
40
+ * ══ PHASE 4: RESUME ON REJECTION ══
41
+ *
42
+ * Until Phase 4 this loop only ever called `adapter.start(...)`, so a re-offer —
43
+ * including a REJECTION re-offer, where the agent needs to hear three sentences
44
+ * of feedback about work it already did — paid for a whole cold start with the
45
+ * whole brief. `chooseTurn` below now picks one of two paths per firing:
46
+ *
47
+ * RESUME — `adapter.deliver(prevRef, <the rejection delta>, ...)`. The provider
48
+ * still holds the original brief, the file reads, the tool results and the
49
+ * prior submission, so the message is ONLY what is new. Same session token,
50
+ * `attempt` incremented.
51
+ * COLD REPLAY — `adapter.start(<brief + a trailing rejection section>, ...)`.
52
+ * A new session, a new token, `attempt` incremented all the same.
53
+ *
54
+ * The resume/replay decision is spelled out in `chooseTurn`'s own comment. A
55
+ * resume that the provider refuses (`ResumeUnavailableError`) falls back to a
56
+ * cold replay WITHIN THE SAME FIRING — the order is still leased, so handing it
57
+ * back would waste a whole re-offer cycle to learn something already known.
58
+ */
59
+ import { existsSync } from 'node:fs';
60
+ import { createLeaseLoop } from "../lease/loop.js";
61
+ import { isResumeUnavailable } from "../harness/contract.js";
62
+ import { preflightStepPermissions } from "../harness/permissions.js";
63
+ import { orderId } from "../harness/session-store.js";
64
+ import { buildOwenloopMcp, renderBrief, renderRejection, renderReplayBrief, } from "./brief.js";
65
+ import { pickModel, } from "./model-policy.js";
66
+ /** Default confirm-phase cadence: one `get_order` per second. */
67
+ export const DEFAULT_CONFIRM_INTERVAL_MS = 1_000;
68
+ /** Default confirm-phase bound: give the hub 15s to show the submit's outcome. */
69
+ export const DEFAULT_SUBMIT_GRACE_MS = 15_000;
70
+ function errMsg(e) {
71
+ return e instanceof Error ? e.message : String(e);
72
+ }
73
+ function laneFromPacket(packet) {
74
+ const plan = packet.consumes?.['plan'];
75
+ if (plan === null || typeof plan !== 'object' || Array.isArray(plan))
76
+ return undefined;
77
+ const lane = plan['lane'];
78
+ return lane === 'express' || lane === 'standard' || lane === 'deep' ? lane : undefined;
79
+ }
80
+ function escalationFromPacket(packet, extensionKey) {
81
+ const extension = packet.x?.[extensionKey];
82
+ if (extension === null || typeof extension !== 'object' || Array.isArray(extension))
83
+ return undefined;
84
+ if (!('escalation' in extension))
85
+ return undefined;
86
+ const raw = extension['escalation'];
87
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw))
88
+ return undefined;
89
+ const bag = raw;
90
+ const model = typeof bag['model'] === 'string' && bag['model'] !== '' ? bag['model'] : undefined;
91
+ const attempts = typeof bag['attempts'] === 'number' && Number.isInteger(bag['attempts']) && bag['attempts'] > 0
92
+ ? bag['attempts']
93
+ : undefined;
94
+ return {
95
+ ...(model !== undefined ? { model } : {}),
96
+ ...(attempts !== undefined ? { attempts } : {}),
97
+ };
98
+ }
99
+ /**
100
+ * The reject depth driving retry escalation: the max across the step's owed
101
+ * outputs, with consult paths excluded.
102
+ *
103
+ * The exclusion matters. A consult artifact's rejects are the mentor handing
104
+ * advice back for another round, not a signal that this producer is stuck — and
105
+ * they ride a separate per-produce attempt budget for exactly that reason.
106
+ * Counting them would let one ordinary mentor round escalate the model on every
107
+ * later firing of the step, permanently, on a producer that was never failing.
108
+ */
109
+ function judgmentRejectsFromPacket(packet) {
110
+ let max = 0;
111
+ for (const owed of packet.owes) {
112
+ const path = String(owed.path ?? '');
113
+ if (path === 'consultRequest' || path.endsWith('Consult'))
114
+ continue;
115
+ const rejects = owed.judgmentRejects;
116
+ if (typeof rejects === 'number' && Number.isFinite(rejects) && rejects > max)
117
+ max = rejects;
118
+ }
119
+ return max;
120
+ }
121
+ function modelForPacket(packet, policy) {
122
+ if (packet.model === undefined)
123
+ return undefined;
124
+ if (policy === undefined)
125
+ return { model: packet.model };
126
+ return pickModel(packet.model, laneFromPacket(packet), judgmentRejectsFromPacket(packet), policy, undefined, escalationFromPacket(packet, policy.escalationExtensionKey));
127
+ }
128
+ /**
129
+ * Poll `get_order` at `intervalMs` for at most `graceMs`, answering ONE
130
+ * question: did the hub see the agent's `submit`?
131
+ *
132
+ * - `lease.outcome` present ⇒ `'submitted'` — the run closed.
133
+ * - `lease.claimed === false` with no outcome ⇒ `'lease-lost'` — something
134
+ * else took the run; releasing would be wrong and a submit would race it.
135
+ * - the grace expires, still claimed, still no outcome ⇒ `'no-submit'`.
136
+ *
137
+ * It calls `hub.getOrder` DIRECTLY rather than poking the lease loop:
138
+ * `LeaseLoop`'s public surface is `{run, stop}` with no probe-now method, and
139
+ * `src/lease/loop.ts` is load-bearing for six existing drills and must stay
140
+ * unchanged. Re-calling `get_order` while already holding the claim is exactly
141
+ * what the lease loop's own heartbeat does, so this adds no new hub semantics.
142
+ *
143
+ * A throwing `get_order` is transient by assumption: it is logged and the poll
144
+ * continues until the grace expires. Nothing here releases; only the caller does.
145
+ */
146
+ export async function confirmOutcome(o) {
147
+ const deadline = o.now() + o.graceMs;
148
+ for (;;) {
149
+ if (o.cancelled?.() === true)
150
+ return 'no-submit';
151
+ let res;
152
+ try {
153
+ res = await o.hub.getOrder({ workflow: o.workflow, run: o.run, holder: o.holder });
154
+ }
155
+ catch (e) {
156
+ o.err(`owenloop work agent-run: confirm get_order failed: ${errMsg(e)} (retrying within the grace)`);
157
+ }
158
+ if (res !== undefined) {
159
+ if (res.lease.outcome !== undefined)
160
+ return 'submitted';
161
+ if (res.lease.claimed === false)
162
+ return 'lease-lost';
163
+ }
164
+ if (o.now() >= deadline)
165
+ return 'no-submit';
166
+ await o.sleep(o.intervalMs);
167
+ }
168
+ }
169
+ export function createAgentRunLoop(opts) {
170
+ const { hub, workflow } = opts;
171
+ const runId = opts.run;
172
+ const order = orderId(workflow, runId);
173
+ let signalled = false;
174
+ let leaseSettled = false;
175
+ let torndown = false;
176
+ let leasePromise;
177
+ let adapter;
178
+ let sessionRef;
179
+ let adapterId = '';
180
+ let stepName = '';
181
+ let attempt = 1;
182
+ let createdAt = 0;
183
+ let recordCwd = opts.cwd;
184
+ /** The watermark written on every record this firing produces — see
185
+ * `SessionRecord.deliveredReasonAt`. Carried forward from the prior record
186
+ * when this firing delivered no new reasons, so it can never regress. */
187
+ let deliveredReasonAt;
188
+ /** Captures a thrown safety-gate append from the synchronous `started` event. */
189
+ let activePersistenceFailure;
190
+ let resolveOrder;
191
+ const orderReady = new Promise((r) => {
192
+ resolveOrder = r;
193
+ });
194
+ const lease = createLeaseLoop({
195
+ hub,
196
+ workflow,
197
+ run: runId,
198
+ role: 'agent-run',
199
+ holder: opts.holder,
200
+ onOrder: (res) => resolveOrder?.(res),
201
+ sleep: opts.sleep,
202
+ now: opts.now,
203
+ out: opts.out,
204
+ err: opts.err,
205
+ ...(opts.random !== undefined ? { random: opts.random } : {}),
206
+ ...(opts.heartbeatIntervalMs !== undefined ? { heartbeatIntervalMs: opts.heartbeatIntervalMs } : {}),
207
+ ...(opts.jumpToleranceMs !== undefined ? { jumpToleranceMs: opts.jumpToleranceMs } : {}),
208
+ ...(opts.failureWindowMs !== undefined ? { failureWindowMs: opts.failureWindowMs } : {}),
209
+ });
210
+ /**
211
+ * Append one session record. `harness`/`token` come from the `started` event's
212
+ * ref when there is one; before that event (a harness that died on launch)
213
+ * they fall back to the resolved adapter id and an empty token, so the store
214
+ * still shows the attempt existed and died.
215
+ */
216
+ function record(status) {
217
+ if (stepName === '')
218
+ return; // no order packet yet — nothing to key a record by
219
+ const at = opts.now();
220
+ if (createdAt === 0)
221
+ createdAt = at;
222
+ opts.appendSession({
223
+ workflow,
224
+ run: runId,
225
+ step: stepName,
226
+ order,
227
+ attempt,
228
+ harness: sessionRef?.harness ?? adapterId,
229
+ token: sessionRef?.token ?? '',
230
+ cwd: recordCwd,
231
+ status,
232
+ createdAt,
233
+ ...(deliveredReasonAt !== undefined ? { deliveredReasonAt } : {}),
234
+ updatedAt: at,
235
+ });
236
+ }
237
+ /**
238
+ * Tear the harness session down. Guarded so the signal path and the normal
239
+ * end-of-run path together still stop the session exactly once; never throws.
240
+ */
241
+ async function teardown() {
242
+ if (adapter === undefined || sessionRef === undefined || torndown)
243
+ return;
244
+ torndown = true;
245
+ try {
246
+ await adapter.stop(sessionRef);
247
+ }
248
+ catch (e) {
249
+ opts.err(`owenloop work agent-run: adapter stop failed: ${errMsg(e)} (ignored)`);
250
+ }
251
+ }
252
+ /** A first-contact / no-hold lease outcome → worker outcome. Mirrors exec. */
253
+ function mapNoHold(o) {
254
+ switch (o) {
255
+ case 'completed':
256
+ return 'completed';
257
+ case 'ownership-error':
258
+ return 'ownership-error';
259
+ case 'hub-unreachable':
260
+ return 'hub-unreachable';
261
+ case 'lease-lost':
262
+ return 'lease-lost';
263
+ case 'stopped':
264
+ return signalled ? 'killed' : 'stopped';
265
+ case 'released':
266
+ case 'release-failed':
267
+ // stop() with release fired before the hold was ever established.
268
+ return 'killed';
269
+ }
270
+ }
271
+ /**
272
+ * A lease outcome observed while the turn was still running.
273
+ *
274
+ * `'completed'` here is a SUCCESS, not a failure: the agent called `submit`
275
+ * and the lease loop's heartbeat saw the outcome before the model turn ended.
276
+ */
277
+ function mapLeaseDuringTurn(o) {
278
+ if (o === 'completed')
279
+ return 'submitted';
280
+ if (o === 'ownership-error')
281
+ return 'ownership-error';
282
+ if (o === 'hub-unreachable')
283
+ return 'hub-unreachable';
284
+ return 'lease-lost';
285
+ }
286
+ /** Log one harness event. Telemetry only — nothing here decides an outcome. */
287
+ function onEvent(e) {
288
+ switch (e.kind) {
289
+ case 'started':
290
+ sessionRef = e.ref;
291
+ opts.err(`owenloop work agent-run: session started for ${order} (harness '${e.ref.harness}')`);
292
+ // This synchronous event is the cold-start gate. The adapter must not
293
+ // begin provider work until the callback returns. A thrown durable append
294
+ // therefore aborts the turn before delivery and is handled separately
295
+ // from an ordinary harness failure below.
296
+ try {
297
+ record('active');
298
+ }
299
+ catch (error) {
300
+ activePersistenceFailure = error;
301
+ throw error;
302
+ }
303
+ return;
304
+ case 'progress':
305
+ opts.err(`owenloop work agent-run: ${e.text}`);
306
+ return;
307
+ case 'needs_input':
308
+ opts.err(`owenloop work agent-run: WARNING the step agent asked for input and this contract has no reply channel — ${e.question}`);
309
+ return;
310
+ case 'turn_ended':
311
+ opts.err(`owenloop work agent-run: turn ended for ${order} (telemetry — the hub decides the outcome)`);
312
+ return;
313
+ case 'exited':
314
+ opts.err(`owenloop work agent-run: harness exited (code ${String(e.exitCode)}${e.error !== undefined ? `, ${e.error}` : ''}) — telemetry only, ignored for the outcome`);
315
+ return;
316
+ }
317
+ }
318
+ /** Release and finish. Used by every path that hands the order back. */
319
+ async function releaseWith(reason, outcome) {
320
+ lease.stop(reason);
321
+ await leasePromise;
322
+ return outcome;
323
+ }
324
+ async function run() {
325
+ leasePromise = lease.run();
326
+ void leasePromise.then(() => {
327
+ leaseSettled = true;
328
+ });
329
+ // First contact race: the order arrives (hold established), or the lease
330
+ // resolves terminally before we ever established it.
331
+ const first = await Promise.race([
332
+ orderReady.then((res) => ({ t: 'order', res })),
333
+ leasePromise.then((o) => ({ t: 'lease', o })),
334
+ ]);
335
+ if (first.t === 'lease')
336
+ return mapNoHold(first.o);
337
+ let packet = first.res.order;
338
+ if (packet === null || packet.worker === 'command') {
339
+ opts.err(`owenloop work agent-run: ${order} is not an agent order (misroute) — releasing`);
340
+ return releaseWith('misroute', 'misroute');
341
+ }
342
+ // Consume-side verification is the prompt boundary. Do this before loading
343
+ // or rendering any step brief: `owes[].reasons` is dynamic text supplied by
344
+ // the transport, and an unverified rejection thread must never reach a
345
+ // provider session. The same whole-order gate also protects `consumes`.
346
+ const hasConsumedData = Object.keys(packet.consumes).length > 0
347
+ || packet.owes.some((owed) => owed.reasons.length > 0 || owed.proof !== undefined);
348
+ if (hasConsumedData) {
349
+ if (opts.consumedVerifier === undefined) {
350
+ const detail = `consume-side verifier is not configured; dynamic values cannot be admitted to an agent prompt`;
351
+ opts.err(`owenloop work agent-run: consumed artifact refusal (prerequisite) for ${order}: ${detail}`);
352
+ return releaseWith('unverified-consumed', 'unverified-consumed');
353
+ }
354
+ try {
355
+ const checked = await opts.consumedVerifier(packet, { hardRule: false });
356
+ if (!checked.ok) {
357
+ opts.err(`owenloop work agent-run: ${checked.reason} — releasing ${order}`);
358
+ return releaseWith('unverified-consumed', 'unverified-consumed');
359
+ }
360
+ packet = checked.order;
361
+ for (const warning of checked.warnings)
362
+ opts.err(warning);
363
+ }
364
+ catch (error) {
365
+ const detail = error instanceof Error ? error.message : String(error);
366
+ opts.err(`owenloop work agent-run: consumed artifact refusal (prerequisite) for ${order}: ${detail} — releasing`);
367
+ return releaseWith('unverified-consumed', 'unverified-consumed');
368
+ }
369
+ }
370
+ stepName = packet.step;
371
+ recordCwd = packet.workdir ?? opts.cwd;
372
+ // The step spec. No bundle / no spec ⇒ we cannot brief anybody; release so
373
+ // the order lapses back through the hub's pickup window.
374
+ let material;
375
+ try {
376
+ material = await opts.loadStep(packet);
377
+ }
378
+ catch (e) {
379
+ opts.err(`owenloop work agent-run: loading the step spec for ${order} failed: ${errMsg(e)}`);
380
+ material = null;
381
+ }
382
+ if (material === null) {
383
+ opts.err(`owenloop work agent-run: no step spec for '${packet.step}' — releasing for the pickup window`);
384
+ return releaseWith('no-template', 'no-template');
385
+ }
386
+ /** `material` is a `let`, so its null-narrowing does not survive into the
387
+ * closures below. This const carries the narrowing across. */
388
+ const step = material;
389
+ const resolution = opts.resolveAdapter(step.harness);
390
+ adapterId = resolution.id;
391
+ if (resolution.adapter === undefined) {
392
+ const known = resolution.registered.length > 0 ? resolution.registered.join(', ') : '<none>';
393
+ opts.err(`owenloop work agent-run: no adapter registered for harness '${resolution.id}' (registered: ${known}) — releasing`);
394
+ return releaseWith('no-harness', 'no-harness');
395
+ }
396
+ adapter = resolution.adapter;
397
+ /** The same object as `adapter`, but narrowed — the module-scope `adapter`
398
+ * stays `HarnessAdapter | undefined` for `teardown`/`stop`. */
399
+ const active = resolution.adapter;
400
+ attempt = opts.nextAttempt(workflow, runId, packet.step);
401
+ const spec = {
402
+ workflow,
403
+ run: runId,
404
+ origin: opts.origin,
405
+ account: opts.account,
406
+ ...(opts.shiftId !== undefined ? { shiftId: opts.shiftId } : {}),
407
+ };
408
+ // Permissions arrive PRE-NORMALIZED in the spec. `prepare` ran
409
+ // `normalizeStepPermissions` over the step's `x.harness` options at cache
410
+ // time, so this loop never looks inside an extension bag and never has a bag
411
+ // key — vendor-keyed lookup does not exist in neutral code any more.
412
+ const permissions = step.permissions;
413
+ // Mandatory final-boundary preflight. Common checks run first, followed by
414
+ // the selected adapter's exact capability check. A refusal starts neither a
415
+ // cold session nor a resumed provider process; the held claim is released.
416
+ const policyIssues = [
417
+ ...preflightStepPermissions(permissions),
418
+ ...active.preflight(permissions),
419
+ ];
420
+ if (policyIssues.length > 0) {
421
+ for (const issue of policyIssues) {
422
+ opts.err(`owenloop work agent-run: harness policy refusal for ${order} on '${resolution.id}'` +
423
+ `${issue.field !== undefined ? ` (${issue.field})` : ''}: ${issue.message}`);
424
+ }
425
+ return releaseWith('incompatible-harness-policy', 'incompatible-harness-policy');
426
+ }
427
+ // ---- PHASE 4: resume or cold replay? -----------------------------------
428
+ //
429
+ // The delta first, because "is there anything new to say?" is one of the
430
+ // resume preconditions. `renderRejection` reads `packet.owes[].reasons`
431
+ // filtered to `at > prev.deliveredReasonAt` — the packet's `owes` IS the set
432
+ // of paths being re-armed, so no extra path filter is needed here.
433
+ const prev = opts.latestSession?.(workflow, runId, packet.step) ?? null;
434
+ const dirExists = opts.dirExists ?? existsSync;
435
+ const delta = renderRejection({
436
+ packet,
437
+ ...(prev?.deliveredReasonAt !== undefined ? { deliveredReasonAt: prev.deliveredReasonAt } : {}),
438
+ });
439
+ // EVERY condition must hold. Each is a separate reason, and each is a
440
+ // documented cold-start case rather than an error:
441
+ // prev !== null first firing — there is no session to resume
442
+ // prev.token !== '' the record predates its `started` event, so
443
+ // no provider token was ever minted
444
+ // prev.harness === resolution.id NEVER resume a session into a different
445
+ // vendor; the token means nothing there
446
+ // prev.status !== 'dead' a session recorded dead is not resumable
447
+ // resumeTier !== 'replay' the adapter says it has no resume at all
448
+ // prev.cwd === recordCwd the resolved working directory moved, so the
449
+ // session is scoped to the wrong place
450
+ // dirExists(prev.cwd) a reaped work dir invalidates the session
451
+ // delta.message !== '' nothing new to say — a resume that says
452
+ // nothing spends a turn communicating nothing
453
+ const resumable = prev !== null &&
454
+ prev.token !== '' &&
455
+ prev.harness === resolution.id &&
456
+ prev.status !== 'dead' &&
457
+ active.resumeTier !== 'replay' &&
458
+ prev.cwd === recordCwd &&
459
+ dirExists(prev.cwd) &&
460
+ delta.message !== '';
461
+ // The watermark this firing's records carry. It STARTS at the prior value —
462
+ // never at the delta's — and advances only once the reasons have actually
463
+ // reached the agent (`markDelivered`, called after `deliver`/`start`
464
+ // RESOLVES). Carrying the prior value forward is also what keeps a cold start
465
+ // with no new feedback from making already-delivered reasons look undelivered.
466
+ deliveredReasonAt = prev?.deliveredReasonAt;
467
+ /**
468
+ * Advance the watermark to the newest reason this firing carried.
469
+ *
470
+ * CALLED ONLY AFTER THE TURN'S DELIVERY RESOLVED. Persisting the advance
471
+ * BEFORE the delivery is attempted permanently swallows the feedback: a
472
+ * `deliver` that fails for a non-resume reason (transport/spawn failure), or
473
+ * a process that dies mid-turn, would leave a record claiming the reasons
474
+ * were delivered by a session that never conveyed them, and the next firing
475
+ * would filter every one of them out (`at > watermark`) and cold-start with a
476
+ * BARE brief — so the agent would never learn why it was rejected and would
477
+ * repeat the rejected submission.
478
+ *
479
+ * The `ResumeUnavailable` → cold-replay fallback stays correct because
480
+ * `coldArgs()` re-renders from `prev?.deliveredReasonAt`, not from this
481
+ * variable.
482
+ */
483
+ function markDelivered() {
484
+ if (delta.deliveredReasonAt !== undefined)
485
+ deliveredReasonAt = delta.deliveredReasonAt;
486
+ }
487
+ const owenloopMcp = buildOwenloopMcp(spec);
488
+ const resolvedModel = modelForPacket(packet, opts.modelPolicy);
489
+ const deliverArgs = {
490
+ cwd: recordCwd,
491
+ owenloopMcp,
492
+ permissions,
493
+ ...(resolvedModel ?? {}),
494
+ };
495
+ /** Built lazily: a cold start after a refused resume needs a FRESH one. */
496
+ const coldArgs = () => ({
497
+ // The replay brief is the ordinary brief PLUS a trailing rejection section,
498
+ // capped at roughly 100k tokens. With no delta it is just the brief.
499
+ brief: renderReplayBrief(renderBrief(step.brief, spec), {
500
+ packet,
501
+ ...(prev?.deliveredReasonAt !== undefined
502
+ ? { deliveredReasonAt: prev.deliveredReasonAt }
503
+ : {}),
504
+ }),
505
+ cwd: recordCwd,
506
+ owenloopMcp,
507
+ permissions,
508
+ ...(resolvedModel ?? {}),
509
+ });
510
+ const path = resumable ? 'resume' : delta.message !== '' ? 'cold replay' : 'cold start';
511
+ opts.out(`owenloop work agent-run: hosting ${order} (step '${packet.step}', harness '${resolution.id}', attempt ${attempt}, ${path})`);
512
+ /** Cold-start this firing. Shared by the ordinary path and the fallback. */
513
+ async function coldStart() {
514
+ activePersistenceFailure = undefined;
515
+ try {
516
+ const ref = await active.start(coldArgs(), onEvent);
517
+ sessionRef = ref;
518
+ // The replay brief carried the reasons, and the turn it opened has now
519
+ // ended — only here is the watermark honest. (The `active` row written
520
+ // from the `started` event fires INSIDE this call and therefore still
521
+ // carries the prior watermark, which is the safe direction: a crash
522
+ // between the two re-delivers rather than swallows.)
523
+ markDelivered();
524
+ return { t: 'turn' };
525
+ }
526
+ catch (e) {
527
+ if (activePersistenceFailure !== undefined) {
528
+ await teardown();
529
+ return { t: 'turn', persistenceFailure: activePersistenceFailure };
530
+ }
531
+ return { t: 'turn', failure: e };
532
+ }
533
+ }
534
+ /**
535
+ * One turn, by whichever path the decision above picked. NEVER rejects: both
536
+ * settle shapes are folded into one 'turn' result on purpose (the closed
537
+ * contract question — see this file's header).
538
+ */
539
+ async function chooseTurn() {
540
+ if (!resumable || prev === null)
541
+ return coldStart();
542
+ // Resume keeps the PRIOR token, so the store shows two rows for the same
543
+ // `(workflow, run, step)` with the same token and successive attempts —
544
+ // which is how "same session" is observable at all. `deliver` never emits
545
+ // `started`, so the record has to be written here rather than from the
546
+ // event, and `createdAt` is the SESSION's birth, not this attempt's.
547
+ sessionRef = { harness: prev.harness, token: prev.token };
548
+ createdAt = prev.createdAt;
549
+ opts.err(`owenloop work agent-run: resuming session ${prev.token} for ${order} with ${delta.count} new rejection reason${delta.count === 1 ? '' : 's'} (no brief re-sent)`);
550
+ // Deliberately written with the PRIOR watermark: nothing has been delivered
551
+ // yet, and this row is what the next firing reads if this turn never
552
+ // completes. See `markDelivered`. This durable write is also the resume
553
+ // delivery gate; failure stops the old provider session without delivery.
554
+ try {
555
+ record('active');
556
+ }
557
+ catch (error) {
558
+ await teardown();
559
+ return { t: 'turn', persistenceFailure: error };
560
+ }
561
+ try {
562
+ await active.deliver(sessionRef, delta.message, deliverArgs, onEvent);
563
+ markDelivered();
564
+ return { t: 'turn' };
565
+ }
566
+ catch (e) {
567
+ if (!isResumeUnavailable(e))
568
+ return { t: 'turn', failure: e };
569
+ // The provider forgot the session. The order is still leased, so falling
570
+ // back HERE costs one cold start; handing it back would cost a whole
571
+ // re-offer cycle to rediscover the same fact.
572
+ opts.err(`owenloop work agent-run: resume of session ${prev.token} was refused (${errMsg(e)}) — falling back to a cold replay in this same firing`);
573
+ // Forget the dead session so the `started` event mints a new record with
574
+ // a NEW token and its own createdAt, and so teardown does not try to stop
575
+ // a session the provider has already lost.
576
+ sessionRef = undefined;
577
+ createdAt = 0;
578
+ return coldStart();
579
+ }
580
+ }
581
+ const turnDone = chooseTurn();
582
+ const raced = await Promise.race([turnDone, leasePromise.then((o) => ({ t: 'lease', o }))]);
583
+ if (raced.t === 'lease') {
584
+ await teardown();
585
+ if (raced.o === 'completed') {
586
+ opts.out(`owenloop work agent-run: ${order} completed mid-turn (the hub reported an outcome)`);
587
+ record('submitted');
588
+ return 'submitted';
589
+ }
590
+ record('dead');
591
+ if (signalled) {
592
+ opts.err(`owenloop work agent-run: signalled mid-turn — tore the session down, released ${order}`);
593
+ return 'killed';
594
+ }
595
+ opts.err(`owenloop work agent-run: lease ${raced.o} mid-turn — tore the session down, no outcome observed`);
596
+ return mapLeaseDuringTurn(raced.o);
597
+ }
598
+ if (raced.persistenceFailure !== undefined) {
599
+ opts.err(`owenloop work agent-run: durable active-session persistence failed before provider delivery for ${order}: ` +
600
+ `${errMsg(raced.persistenceFailure)} — releasing`);
601
+ return releaseWith('session-store-failed', 'session-store-failed');
602
+ }
603
+ // TURN END — NOT task end. Log the failure shape for humans, then confirm.
604
+ if (raced.failure !== undefined) {
605
+ const why = isResumeUnavailable(raced.failure)
606
+ ? `the harness could not resume the session (${errMsg(raced.failure)})`
607
+ : errMsg(raced.failure);
608
+ opts.err(`owenloop work agent-run: the turn failed (${why}) — confirming with the hub before deciding anything`);
609
+ }
610
+ record('turn-ended');
611
+ const confirmed = await Promise.race([
612
+ confirmOutcome({
613
+ hub,
614
+ workflow,
615
+ run: runId,
616
+ holder: opts.holder,
617
+ sleep: opts.sleep,
618
+ now: opts.now,
619
+ err: opts.err,
620
+ intervalMs: opts.confirmIntervalMs ?? DEFAULT_CONFIRM_INTERVAL_MS,
621
+ graceMs: opts.submitGraceMs ?? DEFAULT_SUBMIT_GRACE_MS,
622
+ cancelled: () => signalled || leaseSettled,
623
+ }).then((v) => ({ t: 'confirm', v })),
624
+ leasePromise.then((o) => ({ t: 'lease', o })),
625
+ ]);
626
+ await teardown();
627
+ if (confirmed.t === 'lease') {
628
+ if (confirmed.o === 'completed') {
629
+ record('submitted');
630
+ opts.out(`owenloop work agent-run: ${order} submitted (the lease loop observed the hub outcome)`);
631
+ return 'submitted';
632
+ }
633
+ record('dead');
634
+ if (signalled)
635
+ return 'killed';
636
+ return mapLeaseDuringTurn(confirmed.o);
637
+ }
638
+ switch (confirmed.v) {
639
+ case 'submitted':
640
+ record('submitted');
641
+ opts.out(`owenloop work agent-run: ${order} submitted (confirmed by the hub) — stopping without release`);
642
+ // The run has CLOSED. Releasing after a close is a confusing no-op that
643
+ // races nothing useful, so stop the lease without one.
644
+ lease.stop('submitted', { release: false });
645
+ await leasePromise;
646
+ return 'submitted';
647
+ case 'lease-lost':
648
+ record('dead');
649
+ opts.err(`owenloop work agent-run: the claim on ${order} is gone and no outcome was reported — not releasing`);
650
+ lease.stop('lease-lost', { release: false });
651
+ await leasePromise;
652
+ return 'lease-lost';
653
+ case 'no-submit':
654
+ record('dead');
655
+ opts.err(`owenloop work agent-run: the turn ended and no submit reached the hub within the confirm grace — releasing ${order} for re-offer`);
656
+ // Release so the hub re-offers immediately instead of waiting out the
657
+ // claim TTL. This is the ONLY path that releases on a turn end.
658
+ return releaseWith('no-submit', 'no-submit');
659
+ }
660
+ }
661
+ function stop(reason) {
662
+ if (signalled)
663
+ return;
664
+ signalled = true;
665
+ void teardown();
666
+ lease.stop(reason ?? 'signal'); // release:true — hand the killed order back
667
+ }
668
+ return { run, stop };
669
+ }