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,1024 @@
1
+ /**
2
+ * `codexAdapter` — the `HarnessAdapter` for OpenAI's `codex app-server`
3
+ * (pinned to `codex-cli 0.146.0`, the `"codex"` key in `harness-versions.json`).
4
+ *
5
+ * THIS IS THE ONLY FILE UNDER `src/harness/` ALLOWED TO KNOW THE NAME `codex`.
6
+ * `test/harness-isolation.test.ts` allowlists `src/harness/codex.ts` by exact
7
+ * path; every other module in the layer, including `./jsonrpc-stdio.ts`, is
8
+ * checked against `/claude|codex|anthropic|openai/i` over its full text,
9
+ * comments included. Keep vendor knowledge — argv, method names, param shapes,
10
+ * notification names — inside this file.
11
+ *
12
+ * Attribution: the JSON-RPC client in `./jsonrpc-stdio.ts` was adapted from the
13
+ * kanna project (`github.com/jakemor/kanna`), specifically the knowledge in its
14
+ * `src/server/codex-app-server.ts` and `src/server/codex-app-server-protocol.ts`
15
+ * — knowledge only, no source, and kanna is not a dependency. Copyright (c) 2025
16
+ * Jake Mor. Its LICENSE is the MIT text with the grant narrowed to "any person
17
+ * other than Jacob Eiting and RevenueCat, Inc." (which is why GitHub reports
18
+ * NOASSERTION rather than MIT). That carve-out does not name typicalday, so the
19
+ * port is permitted; the permission notice requires the copyright line be
20
+ * reproduced, which it is here and in `./jsonrpc-stdio.ts`.
21
+ *
22
+ * PROTOCOL FACTS THIS FILE IS BUILT ON (all probed against the pinned binary on
23
+ * 2026-07-30; the full account is `docs/agent-runner.md`, "Phase 2B"):
24
+ * - `thread/start` does NOT carry the brief. The brief rides a separate
25
+ * `turn/start`.
26
+ * - There is a mandatory `initialize` request followed by an `initialized`
27
+ * notification. Both are in the DEFAULT (non-experimental) method set.
28
+ * - Inbound frames omit the `jsonrpc` member entirely.
29
+ * - An unknown method sent as a REQUEST (one carrying an `id`) IS answered, but
30
+ * with `-32600 Invalid request: unknown variant '<method>', expected one of
31
+ * ...` — NOT the `-32601 Method not found` the JSON-RPC spec reserves for it.
32
+ * Sent as a NOTIFICATION (no `id`) it is silently dropped, which is correct.
33
+ * Malformed params on a KNOWN method also come back as `-32600`
34
+ * (`Invalid request: missing field 'threadId'`). So `-32600` is this server's
35
+ * catch-all for "I could not make sense of your request" — see below.
36
+ * - An unknown thread id on `thread/resume` returns `-32600` with the message
37
+ * `no rollout found for thread id <id>`. Because `-32600` is the catch-all
38
+ * above, the resume-unavailable test matches the code AND the message.
39
+ * - `turn/start`'s RESPONSE is an ACK: it came back in 5 ms carrying the created
40
+ * `Turn` with `status:'inProgress'`, while the turn actually ended 7.4 s later
41
+ * with a `turn/completed` notification. Resolving `start`/`deliver` on the
42
+ * response would report a finished turn that had barely begun. Both recorded
43
+ * timings are visible in `test/fixtures/codex-app-server-session.jsonl`.
44
+ * - The owenloop MCP mount is `config.mcp_servers.<name>`, a PER-THREAD option
45
+ * that MERGES with `~/.codex/config.toml` rather than replacing it.
46
+ * - An MCP server child does NOT inherit this process's environment. codex hands
47
+ * it only `HOME, LOGNAME, PATH, SHELL, TMPDIR, USER, __CF_USER_TEXT_ENCODING`
48
+ * plus `mcp_servers.<name>.env`. See `mountEnv` — without it the owenloop
49
+ * mount dies before its MCP `initialize` reply and the step agent has no
50
+ * `submit` tool.
51
+ *
52
+ * ENVIRONMENT IS INHERITED UNTOUCHED — a decision, not an omission. `codex`
53
+ * reads its own `~/.codex/auth.json` or the OS keyring, and there is no API-key
54
+ * environment variable on this side that silently shadows subscription auth and
55
+ * bills API credits. The Claude adapter strips its child environment for exactly
56
+ * that reason; copying the strip here would be cargo-culted protection against a
57
+ * failure mode that does not exist. So: no `env` on the spawn, no strip list, no
58
+ * billing opt-out flag.
59
+ *
60
+ * Failure stance: every diagnostic leaves as `{kind:'progress'}` through
61
+ * `onEvent` — nothing under `src/` prints. A resume against a token the provider
62
+ * has forgotten rejects with `ResumeUnavailableError`; every other failure emits
63
+ * `{kind:'exited'}` and rejects with the underlying error.
64
+ */
65
+ import { existsSync } from 'node:fs';
66
+ import { ResumeUnavailableError } from "./contract.js";
67
+ import { register } from "./registry.js";
68
+ import { normalizeStepPermissions, validateHarnessOptions } from "./permissions.js";
69
+ import { ADMITTED_OWENLOOP_KEYS, filterOwenloopEnv } from "./child-env.js";
70
+ import { JsonRpcError, startStdioRpc } from "./jsonrpc-stdio.js";
71
+ /** The adapter id. Matches the `"codex"` key in `harness-versions.json`, so the
72
+ * worker can use one string for both the version pin and the adapter lookup. */
73
+ export const HARNESS_ID = 'codex';
74
+ /** The MCP server name the step agent's `get_order` / `submit` tools live under. */
75
+ const OWENLOOP_MCP_NAME = 'owenloop';
76
+ /** `codex app-server` — the subcommand that speaks JSON-RPC over stdio. */
77
+ const APP_SERVER_ARGS = ['app-server'];
78
+ /** Client identity sent on `initialize`. Version is informational only. */
79
+ const CLIENT_INFO = { name: 'owenloop', version: '0.1.0' };
80
+ /** Handshake and thread setup are fast; a long budget would only mask a hang. */
81
+ const SETUP_TIMEOUT_MS = 30_000;
82
+ /**
83
+ * Budget for the `turn/start` ACK only — measured at 5 ms, so this is enormous
84
+ * slack, deliberately. It costs nothing: the gate settles on `turn/completed`
85
+ * independently, so a generous ack budget can never delay a finished turn, while
86
+ * a tight one could fail a healthy turn on a slow machine.
87
+ */
88
+ const TURN_START_TIMEOUT_MS = 15 * 60_000;
89
+ /** `turn/interrupt` is best-effort during teardown; never block on it. */
90
+ const INTERRUPT_TIMEOUT_MS = 5_000;
91
+ /**
92
+ * How long teardown waits, AFTER an accepted `turn/interrupt`, for the server to
93
+ * emit the `turn/completed` that carries `status:'interrupted'`.
94
+ *
95
+ * Without this wait, teardown would kill the child while the in-flight
96
+ * `start`/`deliver` promise is still parked on the gate; the child's death then
97
+ * REJECTS that promise through `onExit`, and a caller who asked for an orderly
98
+ * stop gets a process-death error instead of an interrupted turn. Bounded, so a
99
+ * server that never answers cannot stall teardown.
100
+ */
101
+ const INTERRUPT_SETTLE_MS = 5_000;
102
+ /** `item/commandExecution/outputDelta` can be enormous; cap what reaches the log. */
103
+ const PROGRESS_TEXT_CAP = 2_000;
104
+ /**
105
+ * The resume-failure signature, in ONE place.
106
+ *
107
+ * Observed verbatim on 0.146.0: `no rollout found for thread id <uuid>` with
108
+ * code `-32600`. The `thread not found` alternative is defensive against a
109
+ * wording change.
110
+ *
111
+ * Matching `-32600` ALONE would be actively wrong, and that is measured, not
112
+ * assumed: the same code and no other comes back for an unknown method name
113
+ * (`unknown variant '<method>'`) and for a missing required param
114
+ * (`missing field 'threadId'`). A client that read bare `-32600` as
115
+ * "thread is gone" would answer a typo in a method name by throwing away a live
116
+ * thread and cold-replaying the entire step.
117
+ */
118
+ export const RESUME_UNAVAILABLE_MESSAGE_RE = /no rollout found|thread not found/i;
119
+ /** The JSON-RPC code the resume failure rides. Never sufficient on its own. */
120
+ export const RESUME_UNAVAILABLE_CODE = -32600;
121
+ /** True only when BOTH the code and the message say "I do not know this thread". */
122
+ export function isResumeMiss(err) {
123
+ if (!(err instanceof JsonRpcError))
124
+ return false;
125
+ return err.code === RESUME_UNAVAILABLE_CODE && RESUME_UNAVAILABLE_MESSAGE_RE.test(err.message);
126
+ }
127
+ /** The three legal `SandboxMode` values in 0.146.0. */
128
+ const SANDBOX_MODES = new Set(['read-only', 'workspace-write', 'danger-full-access']);
129
+ /**
130
+ * Default sandbox. A delivery-line step agent must be able to edit its own
131
+ * worktree, so `read-only` would fail every builder step; `danger-full-access`
132
+ * is available when a step asks for it, but granting it silently is not this
133
+ * adapter's call.
134
+ */
135
+ const DEFAULT_SANDBOX = 'workspace-write';
136
+ /** `AskForApproval` values this adapter passes through untouched. */
137
+ const NATIVE_APPROVAL_POLICIES = new Set(['untrusted', 'on-request', 'never']);
138
+ const UNRESTRICTED_SANDBOX = 'danger-full-access';
139
+ function unsupportedFilesystemMessage(filesystem) {
140
+ return (`filesystem '${filesystem}' is unsupported by this adapter because Codex app-server ` +
141
+ 'configuration layers are outside the thread sandbox');
142
+ }
143
+ const UNSUPPORTED_MAX_TURNS_MESSAGE = 'maxTurns is unsupported by this adapter because Codex app-server has no thread or turn limit parameter';
144
+ function codexPreflight(permissions) {
145
+ const issues = [];
146
+ if (permissions.maxTurns !== undefined) {
147
+ issues.push({ field: 'maxTurns', message: UNSUPPORTED_MAX_TURNS_MESSAGE });
148
+ }
149
+ if (permissions.filesystem === 'read-only' || permissions.filesystem === 'workspace-write') {
150
+ issues.push({
151
+ field: 'filesystem',
152
+ message: unsupportedFilesystemMessage(permissions.filesystem),
153
+ });
154
+ }
155
+ if (permissions.tools !== undefined) {
156
+ issues.push({ field: 'tools', message: 'tool allow-lists are unsupported by this adapter' });
157
+ }
158
+ if (permissions.disallowedTools !== undefined) {
159
+ issues.push({ field: 'disallowedTools', message: 'tool deny-lists are unsupported by this adapter' });
160
+ }
161
+ if (permissions.network === 'owenloop-only') {
162
+ issues.push({
163
+ field: 'network',
164
+ message: "network 'owenloop-only' is unsupported by this adapter",
165
+ });
166
+ }
167
+ if (permissions.filesystem === undefined &&
168
+ permissions.network === 'unrestricted' &&
169
+ permissions.extensions['sandbox'] === 'read-only') {
170
+ issues.push({
171
+ field: 'network',
172
+ message: "network 'unrestricted' cannot be enabled with sandbox 'read-only'; " +
173
+ "use sandbox 'workspace-write' or 'danger-full-access'",
174
+ });
175
+ }
176
+ if (permissions.permissionMode !== undefined &&
177
+ !NATIVE_APPROVAL_POLICIES.has(permissions.permissionMode)) {
178
+ issues.push({
179
+ field: 'permissionMode',
180
+ message: `permissionMode must be one of ${[...NATIVE_APPROVAL_POLICIES].join('|')}`,
181
+ });
182
+ }
183
+ const sandbox = permissions.extensions['sandbox'];
184
+ if (sandbox !== undefined && (typeof sandbox !== 'string' || !SANDBOX_MODES.has(sandbox))) {
185
+ issues.push({
186
+ field: 'sandbox',
187
+ message: `sandbox must be one of ${[...SANDBOX_MODES].join('|')}`,
188
+ });
189
+ }
190
+ if (permissions.filesystem === 'unrestricted' &&
191
+ typeof sandbox === 'string' &&
192
+ SANDBOX_MODES.has(sandbox) &&
193
+ UNRESTRICTED_SANDBOX !== sandbox) {
194
+ issues.push({
195
+ field: 'sandbox',
196
+ message: `sandbox '${sandbox}' conflicts with filesystem 'unrestricted' ` +
197
+ `(which requires '${UNRESTRICTED_SANDBOX}')`,
198
+ });
199
+ }
200
+ return issues;
201
+ }
202
+ /** `permissionMode` → `approvalPolicy`, with no invalid-value fallback. */
203
+ function toApprovalPolicy(mode) {
204
+ if (mode === undefined)
205
+ return 'never';
206
+ if (NATIVE_APPROVAL_POLICIES.has(mode))
207
+ return mode;
208
+ throw new Error(`permissionMode must be one of ${[...NATIVE_APPROVAL_POLICIES].join('|')}`);
209
+ }
210
+ function isPlainMap(v) {
211
+ return typeof v === 'object' && v !== null && !Array.isArray(v);
212
+ }
213
+ /**
214
+ * Non-`OWENLOOP_*` variables the owenloop CLI reads and the mount must carry.
215
+ * `HOME` is already in codex's own core set; re-supplying it costs nothing and
216
+ * keeps this list a complete statement of what the child needs.
217
+ */
218
+ const MOUNT_ENV_KEEP = ['HOME', 'XDG_CONFIG_HOME', 'XDG_STATE_HOME', 'XDG_CACHE_HOME'];
219
+ /**
220
+ * The environment for the owenloop mount, forwarded from THIS process.
221
+ *
222
+ * MEASURED, not assumed: `codex app-server` 0.146.0 does NOT give an MCP server
223
+ * child its own environment. It hands the child exactly
224
+ * `HOME, LOGNAME, PATH, SHELL, TMPDIR, USER, __CF_USER_TEXT_ENCODING`
225
+ * plus whatever `mcp_servers.<name>.env` supplies. So `OWENLOOP_TOKEN` never
226
+ * arrives on its own, `owenloop work hold --mcp` exits 2 before answering
227
+ * `initialize`, and codex reports the mount as
228
+ * `status:'failed'` / `handshaking with MCP server failed: connection closed:
229
+ * initialize response`. The agent then has no `submit` tool and the order can
230
+ * never complete. The Claude adapter never needed this because Claude Code
231
+ * passes its own environment to MCP children.
232
+ *
233
+ * PHASE 6 NARROWED THE `OWENLOOP_*` HALF FROM A PREFIX TO AN ALLOWLIST. It used
234
+ * to forward the whole `OWENLOOP_*` prefix so a new variable could not silently
235
+ * stop reaching the mount. That default is now inverted: `ADMITTED_OWENLOOP_KEYS`
236
+ * (`src/harness/child-env.ts`) enumerates the names a harness child may see, and
237
+ * a new `OWENLOOP_*` variable does NOT reach the mount until somebody adds it
238
+ * there with a named consumer. The reason is the same fact that made the prefix
239
+ * rule better than `{...process.env}`: `thread/start` params are persisted in
240
+ * codex's rollout file, so anything that reaches this mount has a path to disk —
241
+ * and the hub bearer override in particular must not take it.
242
+ *
243
+ * `MOUNT_ENV_KEEP` is unchanged. Note that the mount's environment is exactly
244
+ * what this function returns, so an ambient variable that is neither admitted
245
+ * nor in `MOUNT_ENV_KEEP` reaches the mount only through codex's own core set.
246
+ *
247
+ * This does not contradict "environment inherited untouched": that was about the
248
+ * `codex app-server` SPAWN, which now applies the same namespace filter and
249
+ * nothing else. This function restores what codex strips back off one specific
250
+ * child — the unified owenloop binary's work-holder command.
251
+ */
252
+ function mountEnv() {
253
+ const out = {};
254
+ for (const [key, value] of Object.entries(process.env)) {
255
+ if (value === undefined)
256
+ continue;
257
+ if (ADMITTED_OWENLOOP_KEYS.has(key) || MOUNT_ENV_KEEP.includes(key)) {
258
+ out[key] = value;
259
+ }
260
+ }
261
+ return out;
262
+ }
263
+ /** The mount for owenloop's own work-holder MCP surface, verbatim from the worker. */
264
+ function owenloopMount(mcp) {
265
+ return { command: mcp.command, args: [...mcp.args], env: mountEnv() };
266
+ }
267
+ /**
268
+ * Build the `thread/start` params. PURE — exported for tests.
269
+ *
270
+ * Takes `DeliverArgs`, not `StartArgs`, because it never reads `brief` and Phase
271
+ * 4's `deliver` needs the identical mapping (`StartArgs` is assignable to
272
+ * `DeliverArgs`, so every `start` call site is unaffected).
273
+ *
274
+ * Deliberately unmapped, so a reader sees intent rather than oversight:
275
+ * - `permissions.tools` / `permissions.disallowedTools`: 0.146.0 has no
276
+ * per-thread built-in-tool allow-list; the sandbox and the approval policy
277
+ * are the levers it does have. Adapter preflight refuses both fields.
278
+ * - `permissions.maxTurns`: no `thread/start` or `turn/start` equivalent.
279
+ * Adapter preflight and this direct-call boundary both refuse the field.
280
+ * - `permissions.effort`: not a `ThreadStartParams` field — it is a
281
+ * `turn/start` param, so it lands in `buildTurnStartParams`.
282
+ * - every `extensions` key other than `mcpServers`, `codexConfig` and
283
+ * `sandbox`: those are the other harness's frontmatter concepts (`hooks`,
284
+ * `memory`, `skills`, `background`, `isolation`, `color`, `initialPrompt`).
285
+ * Unknown keys are ignored silently; `owenloop work lint` is where an unknown key
286
+ * gets warned about.
287
+ */
288
+ export function buildThreadStartParams(args, onEvent) {
289
+ // Retained for source compatibility with callers that previously received
290
+ // fallback diagnostics. Invalid explicit policy now throws instead.
291
+ void onEvent;
292
+ if (args.permissions.maxTurns !== undefined) {
293
+ throw new Error(UNSUPPORTED_MAX_TURNS_MESSAGE);
294
+ }
295
+ const ext = args.permissions.extensions;
296
+ const sandbox = resolveSandbox(args.permissions);
297
+ if (args.permissions.network === 'unrestricted' && sandbox === 'read-only') {
298
+ throw new Error("network 'unrestricted' cannot be enabled with sandbox 'read-only'; " +
299
+ "use sandbox 'workspace-write' or 'danger-full-access'");
300
+ }
301
+ // The escape hatch: any other config key, without re-opening the contract.
302
+ // `mcp_servers` is merged in AFTER it, so the owenloop mount always wins.
303
+ const extraConfig = isPlainMap(ext['codexConfig']) ? { ...ext['codexConfig'] } : {};
304
+ const bagServers = isPlainMap(ext['mcpServers']) ? ext['mcpServers'] : {};
305
+ const configuredServers = isPlainMap(extraConfig['mcp_servers']) ? extraConfig['mcp_servers'] : {};
306
+ const mcpServers = {
307
+ ...configuredServers,
308
+ ...bagServers,
309
+ // The owenloop mount wins on a key clash, mirroring how the legacy
310
+ // frontmatter builder overwrites an author's own `owenloop` entry. Without
311
+ // it the agent has no `submit` tool and the order can never complete.
312
+ [OWENLOOP_MCP_NAME]: owenloopMount(args.owenloopMcp),
313
+ };
314
+ const config = { ...extraConfig, mcp_servers: mcpServers };
315
+ if (args.permissions.network === 'unrestricted' && sandbox === 'workspace-write') {
316
+ const authored = isPlainMap(config['sandbox_workspace_write'])
317
+ ? config['sandbox_workspace_write']
318
+ : {};
319
+ config['sandbox_workspace_write'] = { ...authored, network_access: true };
320
+ }
321
+ const params = {
322
+ cwd: args.cwd,
323
+ config,
324
+ approvalPolicy: toApprovalPolicy(args.permissions.permissionMode),
325
+ sandbox,
326
+ };
327
+ // Phase 1's precedence rule, verbatim: the per-start override beats the
328
+ // normalized step-def value. Omit the KEY entirely when neither is set —
329
+ // sending `model: null` would pin the thread to a null model rather than
330
+ // letting the server pick its default.
331
+ const model = args.model ?? args.permissions.model;
332
+ if (model !== undefined)
333
+ params['model'] = model;
334
+ return params;
335
+ }
336
+ /** Resolve supported neutral filesystem policy, then the legacy adapter override. */
337
+ function resolveSandbox(permissions) {
338
+ if (permissions.filesystem === 'read-only' || permissions.filesystem === 'workspace-write') {
339
+ throw new Error(unsupportedFilesystemMessage(permissions.filesystem));
340
+ }
341
+ if (permissions.filesystem === 'unrestricted') {
342
+ const mapped = UNRESTRICTED_SANDBOX;
343
+ const raw = permissions.extensions['sandbox'];
344
+ if (raw !== undefined && raw !== mapped) {
345
+ throw new Error(`sandbox '${String(raw)}' conflicts with filesystem 'unrestricted' ` +
346
+ `(which requires '${mapped}')`);
347
+ }
348
+ return mapped;
349
+ }
350
+ const raw = permissions.extensions['sandbox'];
351
+ if (raw === undefined)
352
+ return DEFAULT_SANDBOX;
353
+ if (typeof raw === 'string' && SANDBOX_MODES.has(raw))
354
+ return raw;
355
+ throw new Error(`sandbox must be one of ${[...SANDBOX_MODES].join('|')}`);
356
+ }
357
+ /**
358
+ * Build the `turn/start` params. PURE — exported for tests.
359
+ *
360
+ * `input` is an ARRAY of `UserInput`; the text variant is `{type:'text', text}`.
361
+ * A bare string is the natural wrong guess and the server rejects it.
362
+ */
363
+ export function buildTurnStartParams(threadId, text, effort) {
364
+ const params = {
365
+ threadId,
366
+ input: [{ type: 'text', text }],
367
+ };
368
+ // `ReasoningEffort` is `{"type":"string","minLength":1}` — an OPEN string, not
369
+ // a closed union, so a non-empty value passes through unnarrowed.
370
+ if (effort !== undefined && effort !== '')
371
+ params['effort'] = effort;
372
+ return params;
373
+ }
374
+ /**
375
+ * Build the `thread/resume` params. PURE — exported for tests.
376
+ *
377
+ * `base` is the resolved `thread/start` params from the session map when this
378
+ * process started the thread. `ThreadResumeParams` accepts `approvalPolicy`,
379
+ * `sandbox`, `model` and `config`, and a resumed thread that does not re-supply
380
+ * them reverts to the server's defaults.
381
+ *
382
+ * PHASE 4 CLOSED CONTRACT OBSERVATION 1. `deliver`'s third argument originally
383
+ * carried only `cwd` and `owenloopMcp`, so a resume in a different process from
384
+ * the start had nothing to rebuild `approvalPolicy`
385
+ * / `sandbox` / `model` from and silently reverted to server defaults. It now
386
+ * carries the normalized `StepPermissions`, so this function derives the SAME
387
+ * params `buildThreadStartParams` would, and `args` WINS over `base` on every
388
+ * key — `base` only fills in what a `DeliverArgs` cannot express.
389
+ *
390
+ * The owenloop mount is ALWAYS re-supplied. Without it the resumed agent has no
391
+ * `submit` tool — a silent, total failure.
392
+ */
393
+ export function buildThreadResumeParams(threadId, args, base, onEvent) {
394
+ const fromArgs = buildThreadStartParams(args, onEvent);
395
+ const baseConfig = base !== undefined && isPlainMap(base['config']) ? base['config'] : {};
396
+ const argsConfig = isPlainMap(fromArgs['config']) ? fromArgs['config'] : {};
397
+ const baseServers = isPlainMap(baseConfig['mcp_servers']) ? baseConfig['mcp_servers'] : {};
398
+ const argsServers = isPlainMap(argsConfig['mcp_servers']) ? argsConfig['mcp_servers'] : {};
399
+ const params = {
400
+ ...(base ?? {}),
401
+ ...fromArgs,
402
+ threadId,
403
+ config: {
404
+ ...baseConfig,
405
+ ...argsConfig,
406
+ // `argsServers` already carries the owenloop mount and is spread last, so
407
+ // the mount still wins over anything `base` held under the same name.
408
+ mcp_servers: { ...baseServers, ...argsServers },
409
+ },
410
+ };
411
+ return params;
412
+ }
413
+ // ---- notification mapping ---------------------------------------------------
414
+ /** Trim a progress line to something a log can hold. */
415
+ function cap(text) {
416
+ return text.length > PROGRESS_TEXT_CAP ? `${text.slice(0, PROGRESS_TEXT_CAP)}…` : text;
417
+ }
418
+ function str(v) {
419
+ return typeof v === 'string' && v !== '' ? v : undefined;
420
+ }
421
+ function asMap(v) {
422
+ return isPlainMap(v) ? v : {};
423
+ }
424
+ /**
425
+ * Read a `turn/completed` frame's outcome. PURE — exported for tests.
426
+ * Returns `undefined` for anything that is not a `turn/completed`.
427
+ */
428
+ export function readTurnCompleted(method, params) {
429
+ if (method !== 'turn/completed')
430
+ return undefined;
431
+ const turn = asMap(asMap(params)['turn']);
432
+ const err = asMap(turn['error']);
433
+ const message = str(err['message']);
434
+ const details = str(err['additionalDetails']);
435
+ return {
436
+ status: str(turn['status']) ?? 'completed',
437
+ turnId: str(turn['id']),
438
+ error: message === undefined
439
+ ? undefined
440
+ : details === undefined
441
+ ? message
442
+ : `${message} (${details})`,
443
+ };
444
+ }
445
+ /**
446
+ * Map one server→client notification to an `AgentEvent`.
447
+ *
448
+ * PURE and TOTAL — this is the function the recorded fixture replays through, so
449
+ * it must never throw on a shape it has not seen. `undefined` means "not worth
450
+ * surfacing"; nothing may depend on any particular progress line existing.
451
+ *
452
+ * `thread/started` maps to nothing on purpose: `start` emits `{kind:'started'}`
453
+ * itself from the `thread/start` RESPONSE, so the token is captured even if the
454
+ * notification ordering changes.
455
+ */
456
+ export function mapNotification(method, params) {
457
+ const p = asMap(params);
458
+ switch (method) {
459
+ case 'thread/started':
460
+ return undefined;
461
+ case 'turn/started': {
462
+ const id = str(asMap(p['turn'])['id']) ?? '(unknown)';
463
+ return { kind: 'progress', text: `turn ${id} started` };
464
+ }
465
+ case 'turn/completed': {
466
+ const outcome = readTurnCompleted(method, params);
467
+ if (outcome === undefined)
468
+ return undefined;
469
+ return { kind: 'progress', text: `turn ${outcome.turnId ?? '(unknown)'} ${outcome.status}` };
470
+ }
471
+ case 'item/agentMessage/delta': {
472
+ const delta = str(p['delta']) ?? str(p['text']);
473
+ return delta === undefined ? undefined : { kind: 'progress', text: cap(delta) };
474
+ }
475
+ case 'item/started':
476
+ case 'item/completed': {
477
+ const item = asMap(p['item']);
478
+ const kind = str(item['type']) ?? str(item['itemType']) ?? 'item';
479
+ const id = str(item['id']) ?? '(unknown)';
480
+ return { kind: 'progress', text: `${method} ${kind} ${id}` };
481
+ }
482
+ case 'item/commandExecution/outputDelta': {
483
+ const chunk = str(p['chunk']) ?? str(p['delta']) ?? str(p['output']);
484
+ return chunk === undefined ? undefined : { kind: 'progress', text: cap(chunk) };
485
+ }
486
+ case 'item/reasoning/textDelta':
487
+ case 'item/reasoning/summaryTextDelta':
488
+ case 'item/plan/delta': {
489
+ const delta = str(p['delta']) ?? str(p['text']);
490
+ return delta === undefined ? undefined : { kind: 'progress', text: cap(delta) };
491
+ }
492
+ case 'turn/plan/updated':
493
+ case 'turn/diff/updated':
494
+ return { kind: 'progress', text: method };
495
+ case 'mcpServer/startupStatus/updated': {
496
+ const name = str(p['name']) ?? '(unnamed)';
497
+ const status = str(p['status']) ?? '(unknown)';
498
+ const err = str(p['error']);
499
+ return {
500
+ kind: 'progress',
501
+ text: cap(`MCP server '${name}' status ${status}${err === undefined ? '' : `: ${err}`}`),
502
+ };
503
+ }
504
+ case 'error': {
505
+ // The top-level error notification carries a `TurnError`.
506
+ const message = str(asMap(p['error'])['message']) ?? 'unspecified error';
507
+ return { kind: 'exited', exitCode: null, error: message };
508
+ }
509
+ default:
510
+ return undefined;
511
+ }
512
+ }
513
+ /**
514
+ * Read an `mcpServer/startupStatus/updated` frame for the owenloop mount's
515
+ * FAILURE only. PURE — exported for tests.
516
+ *
517
+ * Gates on an explicit `'failed'`, never on the absence of a `'ready'`: absence
518
+ * of a notification is not proof of failure, and gating on ever seeing `'ready'`
519
+ * would deadlock the moment the notification is renamed.
520
+ */
521
+ export function readOwenloopMountFailure(method, params) {
522
+ if (method !== 'mcpServer/startupStatus/updated')
523
+ return undefined;
524
+ const p = asMap(params);
525
+ if (str(p['name']) !== OWENLOOP_MCP_NAME)
526
+ return undefined;
527
+ if (str(p['status']) !== 'failed')
528
+ return undefined;
529
+ const err = str(p['error']) ?? str(p['failureReason']) ?? 'no reason reported';
530
+ return `owenloop MCP server failed to start: ${err}`;
531
+ }
532
+ /**
533
+ * Module-level, process-wide. `stop` on a token this process did not start is a
534
+ * documented no-op — `HarnessSessionRef` carries no pid, so cross-process
535
+ * teardown is impossible under the current contract (observation 2).
536
+ */
537
+ const SESSIONS = new Map();
538
+ /** The binary. `OWENLOOP_CODEX_BIN` overrides; otherwise `PATH` resolves `codex`. */
539
+ function resolveBin() {
540
+ return process.env['OWENLOOP_CODEX_BIN'] ?? 'codex';
541
+ }
542
+ /**
543
+ * Wire one turn's settle semantics.
544
+ *
545
+ * TURN END, NOT PROCESS END. `turn/completed` settles the promise:
546
+ * - `completed` → emit `turn_ended`, resolve.
547
+ * - `failed` → emit `exited` carrying the error FIRST, then `turn_ended`,
548
+ * then resolve. The contract says everything except a resume
549
+ * failure surfaces as an `exited` event; resolving after it is
550
+ * the shape both adapters picked, and they must not diverge.
551
+ * - `interrupted` → emit `turn_ended`, resolve. `stop()` caused it.
552
+ * - `inProgress` → ignore; the turn is not over.
553
+ *
554
+ * If the child dies before any `turn/completed`, the promise REJECTS with that
555
+ * error and no `turn_ended` is synthesized — a dead process did not finish a turn.
556
+ */
557
+ function createTurnGate(onEvent) {
558
+ let settle;
559
+ let turnId;
560
+ let settled = false;
561
+ const promise = new Promise((resolve, reject) => {
562
+ settle = (err) => {
563
+ if (settled)
564
+ return;
565
+ settled = true;
566
+ if (err !== undefined)
567
+ reject(err);
568
+ else
569
+ resolve();
570
+ };
571
+ });
572
+ // The gate can reject with NOBODY awaiting it. Both setup failure paths do
573
+ // exactly that: `thread/start` or `thread/resume` throws, the handler calls
574
+ // `dispose()`, disposal kills the child, `onExit` fires, and `gate.fail(...)`
575
+ // rejects a promise `runTurn` was never reached to await. Node then raises an
576
+ // unhandledRejection and takes the process down — turning a clean, correctly
577
+ // reported ResumeUnavailableError into a crash. (Caught by the live smoke,
578
+ // not by any unit test; the ordering only happens against a real child.)
579
+ //
580
+ // A no-op handler marks the ORIGINAL promise handled. It does not swallow the
581
+ // rejection for real awaiters: `promise.catch(noop)` returns a new promise,
582
+ // and a later `await promise` in `runTurn` still rejects exactly as before.
583
+ promise.catch(() => { });
584
+ // The executor above runs synchronously, so `settle` is assigned by here.
585
+ const done = settle;
586
+ return {
587
+ promise,
588
+ currentTurnId: () => turnId,
589
+ fail: (err) => done(err),
590
+ onNotification(method, params) {
591
+ if (method === 'turn/started') {
592
+ turnId = str(asMap(asMap(params)['turn'])['id']);
593
+ }
594
+ const mounted = readOwenloopMountFailure(method, params);
595
+ const event = mapNotification(method, params);
596
+ if (event !== undefined)
597
+ onEvent(event);
598
+ if (mounted !== undefined) {
599
+ // A silent dead order otherwise: with no `submit` tool the agent can
600
+ // never complete the order, so burning the turn's tokens is pointless.
601
+ onEvent({ kind: 'exited', exitCode: null, error: mounted });
602
+ done(new Error(mounted));
603
+ return;
604
+ }
605
+ const outcome = readTurnCompleted(method, params);
606
+ if (outcome === undefined)
607
+ return;
608
+ if (outcome.status === 'inProgress')
609
+ return;
610
+ if (outcome.status === 'failed') {
611
+ onEvent({ kind: 'exited', exitCode: null, error: outcome.error ?? 'turn failed' });
612
+ }
613
+ onEvent({ kind: 'turn_ended' });
614
+ done();
615
+ },
616
+ };
617
+ }
618
+ /**
619
+ * Answer every server→client request. An unanswered one hangs the turn past the
620
+ * worker's lease, which is the single worst outcome available in this file.
621
+ *
622
+ * Exactly ONE thing is auto-approved — a tool call on owenloop's own MCP mount,
623
+ * see the `mcpServer/elicitation/request` case. Everything else is refused:
624
+ * under `approvalPolicy:'never'` a command/file approval request should not
625
+ * arrive at all; if one does, throwing (which the client turns into a JSON-RPC
626
+ * error reply) is a loud, non-hanging failure, whereas inventing an approval the
627
+ * policy said would never be asked for is a security decision this adapter is
628
+ * not authorized to make.
629
+ *
630
+ * `item/tool/requestUserInput` and every non-owenloop elicitation emit
631
+ * `needs_input` and then throw: the Phase 1 contract deliberately has no reply
632
+ * channel, so replying `{answers:{}}` would be fabricating a user's answer. The
633
+ * error reply surfaces to the model as a failed tool call — the least-wrong
634
+ * behavior available (contract observation 3).
635
+ */
636
+ function handleServerRequest(onEvent) {
637
+ return async (method, params) => {
638
+ switch (method) {
639
+ case 'item/tool/requestUserInput': {
640
+ const questions = asMap(params)['questions'];
641
+ const asked = Array.isArray(questions)
642
+ ? questions.map((q) => str(asMap(q)['question']) ?? str(asMap(q)['header']) ?? '').filter((q) => q !== '')
643
+ : [];
644
+ const question = asked.length > 0 ? asked.join(' / ') : 'the harness asked for user input';
645
+ onEvent({ kind: 'needs_input', question: cap(question) });
646
+ throw new Error('owenloop hosts this session headlessly and cannot answer user input');
647
+ }
648
+ case 'mcpServer/elicitation/request': {
649
+ const p = asMap(params);
650
+ // MEASURED: `approvalPolicy:'never'` does NOT cover MCP tool calls in
651
+ // 0.146.0. Every single call to an MCP tool arrives here first as an
652
+ // elicitation carrying `_meta.codex_approval_kind:'mcp_tool_call'`, and
653
+ // an error reply is recorded as `user rejected MCP tool call`. Refusing
654
+ // therefore does not fail safe — it makes `submit` impossible, so the
655
+ // agent can never green its artifact and every codex order dies owing.
656
+ //
657
+ // This grants exactly one thing: a call to a tool on owenloop's OWN
658
+ // mount. That mount is not third-party code — this adapter wrote it into
659
+ // `thread/start` itself, and `buildThreadStartParams` lets the owenloop
660
+ // entry win any key clash, so `serverName === 'owenloop'` cannot be some
661
+ // other server wearing the name. Any other server, and any elicitation
662
+ // that is not a tool-call approval, still gets `needs_input` + a throw.
663
+ if (str(p['serverName']) === OWENLOOP_MCP_NAME &&
664
+ str(asMap(p['_meta'])['codex_approval_kind']) === 'mcp_tool_call') {
665
+ return { action: 'accept', content: {} };
666
+ }
667
+ const message = str(p['message']) ?? 'an MCP server asked for user input';
668
+ onEvent({ kind: 'needs_input', question: cap(message) });
669
+ throw new Error('owenloop hosts this session headlessly and cannot answer an elicitation');
670
+ }
671
+ case 'item/commandExecution/requestApproval':
672
+ case 'item/fileChange/requestApproval':
673
+ case 'item/permissions/requestApproval':
674
+ case 'applyPatchApproval':
675
+ case 'execCommandApproval': {
676
+ onEvent({
677
+ kind: 'progress',
678
+ text: `refusing '${method}': owenloop runs with approvalPolicy 'never' and does not grant approvals`,
679
+ });
680
+ throw new Error(`'${method}' is not answerable by a headless host`);
681
+ }
682
+ default: {
683
+ onEvent({ kind: 'progress', text: `refusing unsupported server request '${method}'` });
684
+ throw new Error(`'${method}' is not supported by this host`);
685
+ }
686
+ }
687
+ };
688
+ }
689
+ /** Spawn one app-server, complete the handshake, and return the wired client. */
690
+ async function openClient(cwd, onEvent, gate) {
691
+ let exitReported = false;
692
+ const reportExit = (exitCode, error) => {
693
+ if (exitReported)
694
+ return;
695
+ exitReported = true;
696
+ onEvent({ kind: 'exited', exitCode, ...(error !== undefined ? { error } : {}) });
697
+ };
698
+ const client = startStdioRpc({
699
+ command: resolveBin(),
700
+ args: [...APP_SERVER_ARGS],
701
+ cwd,
702
+ // PHASE 6 ITEM 5 — the `OWENLOOP_*` namespace filter, and ONLY that.
703
+ //
704
+ // This is NOT the other adapter's vendor API-key strip, and it must not
705
+ // drift into one: `ANTHROPIC_*` and `OPENAI_*` continue to reach this
706
+ // app-server untouched, which is the recorded decision in
707
+ // `docs/agent-runner.md`. What changes is that owenloop's own variables with
708
+ // no consumer inside this process tree — the hub bearer override above all —
709
+ // stop arriving, because this server persists `thread/start` params under
710
+ // `~/.codex/sessions/` and an inherited secret therefore reaches disk.
711
+ //
712
+ // The value is a FULL environment (`process.env` minus the denied names),
713
+ // because supplying `env` to the transport replaces the child's environment
714
+ // rather than merging into it.
715
+ env: filterOwenloopEnv(process.env),
716
+ // Every unknown notification lands here and is ignored by `mapNotification`
717
+ // — unsolicited traffic arrives before any request completes, and throwing
718
+ // on one would kill a healthy session.
719
+ onNotification: (method, params) => gate.onNotification(method, params),
720
+ onServerRequest: handleServerRequest(onEvent),
721
+ onStderr: (line) => onEvent({ kind: 'progress', text: cap(line) }),
722
+ onExit: (code, signal) => {
723
+ reportExit(code, signal === null ? undefined : `killed by ${signal}`);
724
+ // Resolve-on-turn-end means a death BEFORE `turn/completed` is a failure,
725
+ // not a finished turn. If the turn already ended this is a no-op.
726
+ gate.fail(new Error(`app-server exited (code=${String(code)}, signal=${String(signal)})`));
727
+ },
728
+ });
729
+ try {
730
+ const init = await client.request('initialize', { clientInfo: CLIENT_INFO }, SETUP_TIMEOUT_MS);
731
+ client.notify('initialized', {});
732
+ // The only place the running binary's own version is observable, and the
733
+ // intended input to a `harness-versions.json` mismatch WARNING that is still
734
+ // NOT BUILT as of Phase 6 — see the "known gap" entry in
735
+ // `docs/agent-runner.md`. This line only surfaces the value; nothing reads
736
+ // it back. `test/harness-contract-fixtures.test.ts` pins the line's shape so
737
+ // a future consumer has something stable to parse.
738
+ onEvent({
739
+ kind: 'progress',
740
+ text: `app-server ready: userAgent=${str(init['userAgent']) ?? '(unknown)'}`,
741
+ });
742
+ return { client, reportExit };
743
+ }
744
+ catch (err) {
745
+ // THE HANDSHAKE IS INSIDE THE TRY FOR A REASON. It is spawn-adjacent, so it
746
+ // is tempting to treat it as part of "starting up" and leave the failure to
747
+ // the caller — but the child is ALREADY SPAWNED and, being `detached`, it is
748
+ // the leader of its own process group. A wedged binary, a wrong
749
+ // `OWENLOOP_CODEX_BIN`, or an `initialize` that times out would otherwise
750
+ // leave that group running with nobody holding a handle to it, and the caller
751
+ // would see a rejection with no `exited` event to explain it.
752
+ reportExit(null, describe(err));
753
+ await client.dispose();
754
+ throw err;
755
+ }
756
+ }
757
+ /** The message text for an `exited` event or a progress line. */
758
+ function describe(err) {
759
+ return err instanceof Error ? err.message : String(err);
760
+ }
761
+ /** A timer that cannot by itself hold the event loop — or a test runner — open. */
762
+ function sleepUnref(ms) {
763
+ return new Promise((resolve) => {
764
+ const t = setTimeout(resolve, ms);
765
+ t.unref();
766
+ });
767
+ }
768
+ /**
769
+ * Tear one session's child down: interrupt the live turn if there is one, wait
770
+ * briefly for the interruption to land, then dispose.
771
+ *
772
+ * Shared by `stop` and by the failure path of a turn that never ended, because
773
+ * both need the same thing and the failure path is the easier one to get wrong:
774
+ * a turn whose gate rejected (an owenloop mount failure is the case that
775
+ * matters) is still RUNNING on the server, and leaving it alone burns tokens on
776
+ * an answer nobody will ever read.
777
+ *
778
+ * Never throws. Every step is best-effort: an already-finished turn, a dead
779
+ * child, and a timeout all mean the same thing at teardown — the child is going
780
+ * away — and none of them is a failure of `stop`.
781
+ */
782
+ async function teardownSession(token, session) {
783
+ const turnId = session.gate?.currentTurnId() ?? session.turnId;
784
+ if (turnId !== undefined) {
785
+ try {
786
+ await session.client.request('turn/interrupt', { threadId: token, turnId }, INTERRUPT_TIMEOUT_MS);
787
+ // The interrupt was accepted; give the server its beat to emit
788
+ // `turn/completed{status:'interrupted'}` so a caller parked on the gate
789
+ // sees an interrupted turn rather than the child's death.
790
+ const gate = session.gate;
791
+ if (gate !== undefined) {
792
+ await Promise.race([gate.promise.then(noop, noop), sleepUnref(INTERRUPT_SETTLE_MS)]);
793
+ }
794
+ }
795
+ catch {
796
+ // Best effort — see the doc comment.
797
+ }
798
+ }
799
+ try {
800
+ await session.client.dispose();
801
+ }
802
+ catch {
803
+ // Disposal of an already-exited child is exactly the case the contract
804
+ // calls not-an-error.
805
+ }
806
+ }
807
+ function noop() {
808
+ /* a settled gate is information, not an outcome, at teardown */
809
+ }
810
+ /**
811
+ * A turn that rejected did NOT end — drop the session and tear the child down.
812
+ *
813
+ * The case this exists for is the owenloop mount failure: the gate rejects the
814
+ * instant `mcpServer/startupStatus/updated` reports `failed`, but the SERVER is
815
+ * still happily running the turn, and an agent with no `submit` tool can only
816
+ * spend tokens on an order it cannot possibly complete. A child death or a
817
+ * `turn/start` ACK timeout land here too, and the same answer fits: nothing more
818
+ * will come of this turn, so nothing should still be running for it.
819
+ *
820
+ * The resume token stays valid — the rollout on disk outlives the child, so a
821
+ * later `deliver` can still resume the thread with a fresh app-server.
822
+ */
823
+ async function abandonTurn(token, session) {
824
+ if (SESSIONS.get(token) === session)
825
+ SESSIONS.delete(token);
826
+ await teardownSession(token, session);
827
+ }
828
+ async function runTurn(client, gate, params) {
829
+ // The RESPONSE acknowledges the turn's creation; it is NOT turn end. Awaiting
830
+ // both means a server that answers late still cannot make us miss the
831
+ // `turn/completed` that already settled the gate.
832
+ await Promise.all([client.request('turn/start', params, TURN_START_TIMEOUT_MS), gate.promise]);
833
+ }
834
+ const KNOWN_FIELDS = new Set([
835
+ 'name',
836
+ 'description',
837
+ 'tools',
838
+ 'disallowedTools',
839
+ 'filesystem',
840
+ 'network',
841
+ 'permissionMode',
842
+ 'maxTurns',
843
+ 'model',
844
+ 'effort',
845
+ 'sandbox',
846
+ 'mcpServers',
847
+ 'codexConfig',
848
+ ]);
849
+ function lintStep(bag, step) {
850
+ const findings = [
851
+ ...validateHarnessOptions(bag, step),
852
+ ...codexPreflight(normalizeStepPermissions(bag)).map((issue) => ({
853
+ severity: 'error',
854
+ step,
855
+ message: issue.message,
856
+ ...(issue.field !== undefined ? { field: issue.field } : {}),
857
+ })),
858
+ ];
859
+ const error = (field, message) => {
860
+ findings.push({ severity: 'error', step, field, message });
861
+ };
862
+ const warning = (field, message) => {
863
+ findings.push({ severity: 'warning', step, field, message });
864
+ };
865
+ for (const key of Object.keys(bag)) {
866
+ if (!KNOWN_FIELDS.has(key)) {
867
+ warning(key, `unknown field '${key}' — known fields: ${[...KNOWN_FIELDS].join(', ')}`);
868
+ }
869
+ }
870
+ for (const field of ['mcpServers', 'codexConfig']) {
871
+ if (field in bag && !isPlainMap(bag[field]))
872
+ error(field, `${field} must be a map`);
873
+ }
874
+ if (isPlainMap(bag['mcpServers']) && 'owenloop' in bag['mcpServers']) {
875
+ warning('mcpServers', 'mcpServers.owenloop is reserved and is replaced by the worker at start');
876
+ }
877
+ if (isPlainMap(bag['codexConfig']) &&
878
+ isPlainMap(bag['codexConfig']['mcp_servers']) &&
879
+ 'owenloop' in bag['codexConfig']['mcp_servers']) {
880
+ warning('codexConfig', 'codexConfig.mcp_servers.owenloop is reserved and is replaced by the worker at start');
881
+ }
882
+ return findings;
883
+ }
884
+ export const codexAdapter = {
885
+ id: HARNESS_ID,
886
+ resumeTier: 'native-token',
887
+ preflight: codexPreflight,
888
+ lintStep,
889
+ /**
890
+ * The command a human runs to re-open this thread in an interactive terminal.
891
+ *
892
+ * It goes through `resolveBin`, the SAME resolution the app-server spawn uses,
893
+ * so an operator who set `OWENLOOP_CODEX_BIN` is handed a command that runs on
894
+ * their machine rather than a bare name their shell cannot find. The token in
895
+ * `HarnessSessionRef` is the thread id, which is exactly what the CLI's
896
+ * `resume` subcommand takes.
897
+ */
898
+ resumeCommand(ref) {
899
+ return { command: resolveBin(), args: ['resume', ref.token] };
900
+ },
901
+ async start(args, onEvent) {
902
+ const gate = createTurnGate(onEvent);
903
+ const startParams = buildThreadStartParams(args, onEvent);
904
+ // Handshake failure disposes the child inside `openClient` — see the catch
905
+ // there. Nothing is spawned and unowned by the time this rejects.
906
+ const { client, reportExit } = await openClient(args.cwd, onEvent, gate);
907
+ let threadId;
908
+ try {
909
+ const res = await client.request('thread/start', startParams, SETUP_TIMEOUT_MS);
910
+ const id = str(asMap(res['thread'])['id']);
911
+ if (id === undefined)
912
+ throw new Error('thread/start returned no thread id');
913
+ threadId = id;
914
+ }
915
+ catch (err) {
916
+ // No token exists yet, so there is nothing to hand back and nothing to
917
+ // invent. Report, tear down, reject.
918
+ reportExit(null, describe(err));
919
+ await client.dispose();
920
+ throw err;
921
+ }
922
+ const ref = { harness: HARNESS_ID, token: threadId };
923
+ // The gate goes on the session BEFORE the turn is started, so a `stop` that
924
+ // lands mid-turn can read the live turn id off it and interrupt.
925
+ const session = { client, startParams, gate };
926
+ SESSIONS.set(threadId, session);
927
+ // BEFORE the turn runs and before resolving: the caller persists the token
928
+ // on this event, so a mid-turn crash still leaves a resumable record.
929
+ onEvent({ kind: 'started', ref });
930
+ try {
931
+ await runTurn(client, gate, buildTurnStartParams(threadId, args.brief, args.effort ?? args.permissions.effort));
932
+ }
933
+ catch (err) {
934
+ await abandonTurn(threadId, session);
935
+ throw err;
936
+ }
937
+ finally {
938
+ session.turnId = gate.currentTurnId();
939
+ delete session.gate;
940
+ }
941
+ return ref;
942
+ },
943
+ async deliver(ref, message, args, onEvent) {
944
+ const previous = SESSIONS.get(ref.token);
945
+ // PHASE 4: the map is no longer the source of truth for thread configuration.
946
+ // `args.permissions` is, and `buildThreadResumeParams` maps it. `startParams`
947
+ // survives only as a filler for keys a `DeliverArgs` cannot express, and a
948
+ // miss is now an ordinary cross-process resume rather than a degraded one —
949
+ // which is why the "minimal thread configuration" warning is gone.
950
+ const startParams = previous?.startParams;
951
+ // Match cold start: validate all thread configuration before checking the
952
+ // worktree, disposing an existing session, or spawning a replacement
953
+ // app-server. Unsupported policy is the first direct-call boundary.
954
+ const resumeParams = buildThreadResumeParams(ref.token, args, startParams, onEvent);
955
+ // A rollout records its cwd; a vanished worktree cannot host the resumed
956
+ // turn, and finding that out from the server takes a spawn plus a handshake.
957
+ if (!existsSync(args.cwd)) {
958
+ throw new ResumeUnavailableError(`resume cwd no longer exists: ${args.cwd}`);
959
+ }
960
+ const gate = createTurnGate(onEvent);
961
+ if (previous !== undefined) {
962
+ // ALWAYS a fresh app-server, even when this process still holds a live one.
963
+ // A live client's notifications are bound to the gate it was opened with,
964
+ // and the client exposes no rewire; reusing it would route this turn's
965
+ // `turn/completed` to the PREVIOUS turn's already-settled gate and hang
966
+ // this one forever. Resume is cheap; a hung order is not.
967
+ SESSIONS.delete(ref.token);
968
+ await previous.client.dispose();
969
+ }
970
+ const { client, reportExit } = await openClient(args.cwd, onEvent, gate);
971
+ try {
972
+ await client.request('thread/resume', resumeParams, SETUP_TIMEOUT_MS);
973
+ }
974
+ catch (err) {
975
+ if (isResumeMiss(err)) {
976
+ // The ONLY failure that rejects with ResumeUnavailableError. The caller
977
+ // owns the cold-replay fallback; this adapter only reports. The `exited`
978
+ // event for the disposed child comes from `onExit`, unchanged — a
979
+ // forgotten thread is reported by the rejection, not by a second
980
+ // synthesized failure message.
981
+ await client.dispose();
982
+ throw new ResumeUnavailableError(`provider no longer knows thread ${ref.token}: ${describe(err)}`);
983
+ }
984
+ reportExit(null, describe(err));
985
+ await client.dispose();
986
+ throw err;
987
+ }
988
+ const session = {
989
+ client,
990
+ gate,
991
+ ...(startParams !== undefined ? { startParams } : {}),
992
+ };
993
+ SESSIONS.set(ref.token, session);
994
+ try {
995
+ // NEVER re-emits `started` — the contract forbids it on a resume.
996
+ await runTurn(client, gate,
997
+ // Phase 4: effort is a `turn/start` param, so a resumed turn has to
998
+ // re-supply it exactly as `start` does — same precedence rule.
999
+ buildTurnStartParams(ref.token, message, args.effort ?? args.permissions.effort));
1000
+ }
1001
+ catch (err) {
1002
+ await abandonTurn(ref.token, session);
1003
+ throw err;
1004
+ }
1005
+ finally {
1006
+ session.turnId = gate.currentTurnId();
1007
+ delete session.gate;
1008
+ }
1009
+ },
1010
+ async stop(ref) {
1011
+ const session = SESSIONS.get(ref.token);
1012
+ // A miss is NOT an error: the contract requires idempotence, an already-dead
1013
+ // session is fine, and a session started by another process is simply not
1014
+ // reachable from here.
1015
+ if (session === undefined)
1016
+ return;
1017
+ SESSIONS.delete(ref.token);
1018
+ await teardownSession(ref.token, session);
1019
+ },
1020
+ };
1021
+ // Adapters self-register at IMPORT time; whoever imports this module is what
1022
+ // puts it in the runtime registry. Phase 3's worker owns that import — this
1023
+ // phase only makes the import sufficient.
1024
+ register(codexAdapter);