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,837 @@
1
+ /**
2
+ * The Claude Code harness adapter — `HarnessAdapter` (`./contract.ts`)
3
+ * implemented on top of `@anthropic-ai/claude-agent-sdk`.
4
+ *
5
+ * WHY THIS FILE IS ALLOWED TO NAME A VENDOR. `test/harness-isolation.test.ts`
6
+ * greps `/claude|codex|anthropic|openai/i` over the full text — comments
7
+ * included — of every `.ts` under `src/harness/`, and allowlists exactly two
8
+ * paths: `claude.ts` and `codex.ts`. That is why this whole adapter lives in one
9
+ * file. Do NOT split it into `src/harness/claude/*.ts` or a `claude-options.ts`
10
+ * helper: those paths are not allowlisted and the isolation test fails on them.
11
+ *
12
+ * SHAPE. Every decision lives in the two exported pure-ish functions
13
+ * (`buildChildEnv`, `buildClaudeOptions`); `start`/`deliver`/`stop` are thin I/O
14
+ * shells over them. That split is what lets `test/harness-claude.test.ts` prove
15
+ * the option mapping and the environment hygiene with no SDK process, no
16
+ * network, and no login.
17
+ *
18
+ * NO PRINTING. There is zero `console.*` under `src/`. Diagnostics leave this
19
+ * module as `{kind:'progress', text}` `AgentEvent`s through the caller's
20
+ * `onEvent`, never as a print.
21
+ *
22
+ * NOTHING IMPORTS THIS YET. Phase 3's worker (the composition root) is the first
23
+ * production importer; importing this module is what fires the module-scope
24
+ * `register(claudeAdapter)` below and puts the adapter in the runtime registry.
25
+ */
26
+ import { randomUUID } from 'node:crypto';
27
+ import { accessSync, constants, existsSync } from 'node:fs';
28
+ import { delimiter, join } from 'node:path';
29
+ import { register } from "./registry.js";
30
+ import { filterOwenloopEnv } from "./child-env.js";
31
+ import { normalizeStepPermissions, validateHarnessOptions } from "./permissions.js";
32
+ import { ResumeUnavailableError } from "./contract.js";
33
+ /** The registry key — the id a step def names in `x.harness.id`, and the key
34
+ * `harness-versions.json` pins the CLI under. */
35
+ const HARNESS_ID = 'claude-code';
36
+ // ---------------------------------------------------------------------------
37
+ // Environment hygiene
38
+ // ---------------------------------------------------------------------------
39
+ /**
40
+ * The variables deleted from the child environment unless API billing is
41
+ * explicitly allowed.
42
+ *
43
+ * `ANTHROPIC_API_KEY` / `ANTHROPIC_AUTH_TOKEN`: an inherited key SILENTLY
44
+ * shadows the operator's subscription OAuth and bills API credits instead. That
45
+ * shadowing is the entire reason this strip exists — it is a correctness
46
+ * requirement, not hardening.
47
+ *
48
+ * `CLAUDECODE`: set by an already-running Claude Code process to mark "you are
49
+ * inside me". Inheriting it confuses a nested launch, so it goes under the same
50
+ * toggle — one flag, one list, no second knob.
51
+ *
52
+ * `CLAUDE_CODE_OAUTH_TOKEN` IS DELIBERATELY NOT IN THIS LIST AND MUST NEVER BE
53
+ * ADDED TO IT: it is the subscription credential, and the launchd path needs it
54
+ * to survive. `test/harness-claude.test.ts` asserts that explicitly so a future
55
+ * "tidy up the strip list" edit fails loudly instead of silently breaking
56
+ * headless auth. Phase 6 measured it end to end under a real launchd job —
57
+ * `test/tools/launchd-env-probe.sh`, which observes the variable arriving in the
58
+ * job AND surviving `buildChildEnv`, while `OWENLOOP_TOKEN` set in the same
59
+ * plist does not survive.
60
+ */
61
+ const STRIPPED_ENV_KEYS = ['ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN', 'CLAUDECODE'];
62
+ /** The machine-level opt-out. Read from the environment INSIDE this module on
63
+ * purpose: the contract deliberately refused an `allowApiBilling` field on
64
+ * `StartArgs` (it is machine config, not per-start data) and `src/settings.ts`
65
+ * is shared surface another phase may be editing. */
66
+ const ALLOW_API_BILLING_VAR = 'OWENLOOP_ALLOW_API_BILLING';
67
+ /** Operator override for the CLI binary; see `resolveExecutable`. */
68
+ const BIN_OVERRIDE_VAR = 'OWENLOOP_CLAUDE_BIN';
69
+ /**
70
+ * Build the environment the harness child runs under.
71
+ *
72
+ * WHY IT SPREADS RATHER THAN LISTS. The SDK's `Options.env` REPLACES the
73
+ * subprocess environment entirely — it is NOT merged with `process.env` (see
74
+ * that field's own JSDoc in the installed `sdk.d.ts`). Both halves of that bite:
75
+ *
76
+ * - passing only the deltas would blow away `PATH`/`HOME` and break the child;
77
+ * - omitting `env` altogether would let an ambient API key through, which is
78
+ * exactly the bug this function exists to prevent.
79
+ *
80
+ * So the caller ALWAYS sets `env`, and this function always returns a full
81
+ * environment: spread the source, then delete.
82
+ *
83
+ * `source` is a parameter rather than a read of `process.env` so the unit test
84
+ * injects a fixture and never mutates the real environment. The input is not
85
+ * mutated.
86
+ *
87
+ * `delete` is used rather than assigning `undefined`: an own key holding
88
+ * `undefined` is not obviously equivalent to an absent key across the SDK's
89
+ * serialization boundary, and deleting removes the question.
90
+ *
91
+ * TWO INDEPENDENT FILTERS RUN HERE, and conflating them would break one of
92
+ * them:
93
+ *
94
+ * 1. `STRIPPED_ENV_KEYS` — the vendor API-key strip. It is specific to THIS
95
+ * adapter, it is a correctness requirement (an inherited key shadows the
96
+ * subscription and bills credits), and it is under the `allowApiBilling`
97
+ * opt-out.
98
+ * 2. `filterOwenloopEnv` — Phase 6's `OWENLOOP_*` namespace allowlist, shared
99
+ * with the other adapter and NOT under any opt-out. It removes owenloop's
100
+ * own variables that no harness child has a consumer for — the hub bearer
101
+ * override above all — and touches nothing outside that namespace. In
102
+ * particular it cannot reach `CLAUDE_CODE_OAUTH_TOKEN`, which is not an
103
+ * `OWENLOOP_*` name and therefore survives by construction, which is what
104
+ * Phase 6 item 3 needs under launchd.
105
+ *
106
+ * Everything else survives: `PATH`, `HOME`, `TMPDIR`, proxy and TLS variables,
107
+ * and the three admitted `OWENLOOP_*` names the mounted work-holder MCP child
108
+ * actually reads.
109
+ */
110
+ export function buildChildEnv(source, opts) {
111
+ const result = filterOwenloopEnv(source);
112
+ if (!opts.allowApiBilling) {
113
+ for (const key of STRIPPED_ENV_KEYS)
114
+ delete result[key];
115
+ }
116
+ return result;
117
+ }
118
+ /** Whether API billing is allowed, from a machine-level environment toggle.
119
+ * Default is OFF — the strip happens unless the operator opted in. */
120
+ export function allowApiBillingFrom(source) {
121
+ return source[ALLOW_API_BILLING_VAR] === '1';
122
+ }
123
+ // ---------------------------------------------------------------------------
124
+ // Binary resolution
125
+ // ---------------------------------------------------------------------------
126
+ /**
127
+ * Resolve the CLI executable: `OWENLOOP_CLAUDE_BIN` → a `claude` on `PATH` →
128
+ * `undefined`.
129
+ *
130
+ * `undefined` means the caller OMITS `pathToClaudeCodeExecutable` entirely and
131
+ * lets the SDK use its own bundled executable. That third case is a decision,
132
+ * not an oversight: the bundled executable is the same CLI reading the same
133
+ * credential store, so subscription auth still works, whereas throwing would
134
+ * make the adapter unusable on a machine where the CLI sits somewhere unusual.
135
+ *
136
+ * The `PATH` walk is done in-process (`accessSync` with `X_OK`) rather than by
137
+ * shelling out: no shell, no extra child, and it is unit-testable against a
138
+ * fixture `PATH` the test builds and `chmod`s itself.
139
+ *
140
+ * `source` is the CHILD environment (a spread of `process.env`), so the override
141
+ * and the `PATH` searched are the same ones the child will see.
142
+ */
143
+ export function resolveExecutable(source) {
144
+ const override = source[BIN_OVERRIDE_VAR];
145
+ if (override !== undefined && override !== '')
146
+ return override;
147
+ const path = source['PATH'];
148
+ if (path === undefined || path === '')
149
+ return undefined;
150
+ for (const dir of path.split(delimiter)) {
151
+ if (dir === '')
152
+ continue;
153
+ const candidate = join(dir, 'claude');
154
+ try {
155
+ accessSync(candidate, constants.X_OK);
156
+ return candidate;
157
+ }
158
+ catch {
159
+ // not here (or not executable) — keep walking
160
+ }
161
+ }
162
+ return undefined;
163
+ }
164
+ // ---------------------------------------------------------------------------
165
+ // Option mapping
166
+ // ---------------------------------------------------------------------------
167
+ /**
168
+ * The six-value closed union the SDK types `Options.permissionMode` as.
169
+ * `StepPermissions.permissionMode` arrives as an UNVALIDATED non-empty string
170
+ * (normalization passes it through by design and leaves validation to
171
+ * `owenloop work lint`), so narrowing is mandatory, not defensive style.
172
+ */
173
+ const PERMISSION_MODES = [
174
+ 'default',
175
+ 'acceptEdits',
176
+ 'bypassPermissions',
177
+ 'plan',
178
+ 'dontAsk',
179
+ 'auto',
180
+ ];
181
+ /** The five-value closed union the SDK types `Options.effort` as. */
182
+ const EFFORT_LEVELS = ['low', 'medium', 'high', 'xhigh', 'max'];
183
+ /** Audited built-ins that cannot mutate the filesystem. WebFetch/WebSearch
184
+ * can read the unrestricted network without weakening a read-only filesystem. */
185
+ const READ_ONLY_TOOLS = new Set(['Read', 'Glob', 'Grep', 'WebFetch', 'WebSearch']);
186
+ /** Audited built-ins allowed when only the network is restricted. */
187
+ const OWENLOOP_ONLY_NETWORK_TOOLS = new Set([
188
+ 'Read',
189
+ 'Glob',
190
+ 'Grep',
191
+ 'Edit',
192
+ 'Write',
193
+ 'NotebookEdit',
194
+ 'TodoWrite',
195
+ 'TaskCreate',
196
+ 'TaskUpdate',
197
+ 'TaskList',
198
+ 'TaskGet',
199
+ ]);
200
+ /** The intersection when both restrictions apply: local reads only, with no
201
+ * unrestricted-network readers. */
202
+ const READ_ONLY_OWENLOOP_ONLY_NETWORK_TOOLS = [...READ_ONLY_TOOLS]
203
+ .filter((tool) => OWENLOOP_ONLY_NETWORK_TOOLS.has(tool));
204
+ const BORN_BOUND_OWENLOOP_TOOL_NAMES = ['get_order', 'submit'];
205
+ const BORN_BOUND_OWENLOOP_TOOLS = BORN_BOUND_OWENLOOP_TOOL_NAMES.map((name) => `mcp__owenloop__${name}`);
206
+ const RESTRICTED_OWENLOOP_DENIED_TOOLS = ['mcp__owenloop__reject'];
207
+ const OWENLOOP_CONTROL_TOOLS = new Set([
208
+ ...BORN_BOUND_OWENLOOP_TOOLS,
209
+ 'mcp__plugin_owenloop_owenloop__get_order',
210
+ 'mcp__plugin_owenloop_owenloop__submit',
211
+ ]);
212
+ const OWENLOOP_CONTROL_DENY_SPECS = new Set([
213
+ ...OWENLOOP_CONTROL_TOOLS,
214
+ 'mcp__owenloop',
215
+ 'mcp__owenloop__*',
216
+ 'mcp__plugin_owenloop_owenloop',
217
+ 'mcp__plugin_owenloop_owenloop__*',
218
+ 'mcp__*',
219
+ ]);
220
+ function claudePreflight(permissions) {
221
+ const issues = [];
222
+ if (permissions.permissionMode !== undefined && !PERMISSION_MODES.includes(permissions.permissionMode)) {
223
+ issues.push({
224
+ field: 'permissionMode',
225
+ message: `permissionMode must be one of ${PERMISSION_MODES.join('|')}`,
226
+ });
227
+ }
228
+ if (permissions.effort !== undefined && !EFFORT_LEVELS.includes(permissions.effort)) {
229
+ issues.push({ field: 'effort', message: `effort must be one of ${EFFORT_LEVELS.join('|')}` });
230
+ }
231
+ if (permissions.filesystem === 'workspace-write') {
232
+ issues.push({
233
+ field: 'filesystem',
234
+ message: "filesystem 'workspace-write' is unsupported by this adapter; use 'read-only' or 'unrestricted'",
235
+ });
236
+ }
237
+ const allowed = permissions.tools;
238
+ if (allowed !== undefined) {
239
+ const unsupportedMcp = allowed.filter((tool) => tool.startsWith('mcp__') && !OWENLOOP_CONTROL_TOOLS.has(tool));
240
+ if (unsupportedMcp.length > 0) {
241
+ issues.push({
242
+ field: 'tools',
243
+ message: `external MCP tools cannot be enforced by this adapter's exact allow-list: ` +
244
+ unsupportedMcp.join(', '),
245
+ });
246
+ }
247
+ }
248
+ if (permissions.filesystem === 'read-only' && allowed !== undefined) {
249
+ const unsafe = allowed.filter((tool) => !READ_ONLY_TOOLS.has(tool) && !OWENLOOP_CONTROL_TOOLS.has(tool));
250
+ if (unsafe.length > 0) {
251
+ issues.push({
252
+ field: 'tools',
253
+ message: `filesystem 'read-only' cannot allow non-read-only tool(s): ${unsafe.join(', ')}`,
254
+ });
255
+ }
256
+ }
257
+ if (permissions.network === 'owenloop-only' && allowed !== undefined) {
258
+ const unsafe = allowed.filter((tool) => !OWENLOOP_ONLY_NETWORK_TOOLS.has(tool) && !OWENLOOP_CONTROL_TOOLS.has(tool));
259
+ if (unsafe.length > 0) {
260
+ issues.push({
261
+ field: 'tools',
262
+ message: `network 'owenloop-only' cannot allow network-capable or unaudited tool(s): ${unsafe.join(', ')}`,
263
+ });
264
+ }
265
+ }
266
+ const deniedControl = (permissions.disallowedTools ?? []).filter((tool) => OWENLOOP_CONTROL_DENY_SPECS.has(tool));
267
+ if (deniedControl.length > 0) {
268
+ issues.push({
269
+ field: 'disallowedTools',
270
+ message: `the born-bound Owenloop control plane must retain get_order/submit access; remove: ${deniedControl.join(', ')}`,
271
+ });
272
+ }
273
+ return issues;
274
+ }
275
+ /**
276
+ * The error text a resume against a token the provider does not know is
277
+ * expected to carry. SECONDARY detection only — `deliver` pre-checks with
278
+ * `getSessionInfo`, which is deterministic. The exact provider string is
279
+ * UNVERIFIED and can change between releases, which is precisely why it is not
280
+ * the primary path.
281
+ */
282
+ const RESUME_FAILURE_RE = /no conversation found|session not found|--resume/i;
283
+ function isPlainMap(v) {
284
+ return typeof v === 'object' && v !== null && !Array.isArray(v);
285
+ }
286
+ /** The mount for owenloop's own work-holder MCP surface, built from the worker's
287
+ * verbatim argv. `alwaysLoad` forces its tools into the turn-1 prompt instead of
288
+ * deferring them behind tool search — a step agent that cannot see `submit` on
289
+ * turn 1 cannot finish its order. */
290
+ function owenloopMount(mount) {
291
+ return { type: 'stdio', command: mount.command, args: mount.args, alwaysLoad: true };
292
+ }
293
+ /** Restricted sessions register a positive two-tool subset. The selector is
294
+ * derived from the same names used by `allowedTools`, so the declared exception
295
+ * and the MCP server's actual `tools/list` cannot drift within this adapter. */
296
+ function restrictedOwenloopMount(mount) {
297
+ return owenloopMount({
298
+ command: mount.command,
299
+ args: [...mount.args, `--mcp-tools=${BORN_BOUND_OWENLOOP_TOOL_NAMES.join(',')}`],
300
+ });
301
+ }
302
+ /**
303
+ * `mcpServers`, with the owenloop mount layered ON TOP of whatever the step's
304
+ * bag declared. An author's own `owenloop` entry is overwritten, exactly as the
305
+ * legacy frontmatter builder overwrites it today — the mount is born bound to a
306
+ * specific order and a step def may not redirect it.
307
+ */
308
+ function mergeMcpServers(bagServers, mount) {
309
+ const base = isPlainMap(bagServers) ? bagServers : {};
310
+ return { ...base, owenloop: owenloopMount(mount) };
311
+ }
312
+ /**
313
+ * Map `StartArgs` + the Claude-owned extensions bag onto the SDK's `Options`.
314
+ *
315
+ * The mapping knowledge is PORTED from the legacy compile-time frontmatter
316
+ * builder — the knowledge is correct, only the output format changed. Nothing is
317
+ * imported from `src/adapters/`; the isolation test forbids that dependency
318
+ * direction.
319
+ */
320
+ export function buildClaudeOptions(inputs, extra) {
321
+ const { permissions } = inputs;
322
+ const isolated = permissions.tools !== undefined ||
323
+ permissions.filesystem === 'read-only' ||
324
+ permissions.network === 'owenloop-only';
325
+ const options = {
326
+ cwd: inputs.cwd,
327
+ env: extra.env,
328
+ abortController: extra.abortController,
329
+ mcpServers: isolated
330
+ ? { owenloop: restrictedOwenloopMount(inputs.owenloopMcp) }
331
+ : mergeMcpServers(permissions.extensions['mcpServers'], inputs.owenloopMcp),
332
+ ...(isolated ? { settingSources: [], strictMcpConfig: true, skills: [] } : {}),
333
+ stderr: (data) => {
334
+ extra.onEvent({ kind: 'progress', text: `stderr: ${data.trimEnd()}` });
335
+ },
336
+ };
337
+ // Omit the key entirely when nothing resolves — see `resolveExecutable`.
338
+ const executable = resolveExecutable(extra.env);
339
+ if (executable !== undefined)
340
+ options.pathToClaudeCodeExecutable = executable;
341
+ // PRECEDENCE, fixed by the contract: the per-start override wins over the
342
+ // step's configured value, for both model and effort.
343
+ const model = inputs.model ?? permissions.model;
344
+ if (model !== undefined)
345
+ options.model = model;
346
+ const rawEffort = inputs.effort ?? permissions.effort;
347
+ if (rawEffort !== undefined) {
348
+ if (EFFORT_LEVELS.includes(rawEffort)) {
349
+ options.effort = rawEffort;
350
+ }
351
+ else {
352
+ // Dropped rather than thrown or coerced — the same stance normalization
353
+ // takes for a bad `maxTurns`. The linter only checks effort is a string,
354
+ // so an unlintable-but-legal bag can carry an out-of-union value.
355
+ extra.onEvent({
356
+ kind: 'progress',
357
+ text: `dropped out-of-range effort '${rawEffort}' (expected one of ${EFFORT_LEVELS.join('|')})`,
358
+ });
359
+ }
360
+ }
361
+ if (permissions.permissionMode !== undefined) {
362
+ if (PERMISSION_MODES.includes(permissions.permissionMode)) {
363
+ const mode = permissions.permissionMode;
364
+ options.permissionMode = mode;
365
+ // 'bypassPermissions' is IGNORED by the SDK without this companion flag.
366
+ // Missing it is a silent downgrade to prompting, which in a headless run
367
+ // means the step stalls forever on a prompt no human will answer.
368
+ if (mode === 'bypassPermissions')
369
+ options.allowDangerouslySkipPermissions = true;
370
+ }
371
+ else {
372
+ extra.onEvent({
373
+ kind: 'progress',
374
+ text: `dropped unknown permissionMode '${permissions.permissionMode}' (expected one of ${PERMISSION_MODES.join('|')})`,
375
+ });
376
+ }
377
+ }
378
+ // `tools` and `allowedTools` are DIFFERENT SDK options and the step def's
379
+ // single `tools:` field needs both: `tools` is the base set of AVAILABLE
380
+ // built-in tools (what the legacy frontmatter `tools:` meant), `allowedTools`
381
+ // is the set auto-allowed WITHOUT a permission prompt. Only `tools` leaves
382
+ // every call waiting on a prompt nobody will answer headless; only
383
+ // `allowedTools` fails to restrict the surface the author asked to restrict.
384
+ //
385
+ // ABSENT means "the step named no tools" and normally sets NEITHER key: the
386
+ // SDK reads `tools: []` as "disable all built-in tools". Isolation is the
387
+ // exception: the audited built-in list becomes explicit, and `allowedTools`
388
+ // also auto-allows the born-bound get_order/submit MCP tools so the restricted
389
+ // agent can inspect and finish its order without an unattended permission prompt.
390
+ // The restricted MCP child itself registers exactly those two tools; allowedTools
391
+ // is permission automation, not an MCP visibility filter.
392
+ let effectiveTools = permissions.tools;
393
+ if (effectiveTools === undefined && permissions.filesystem === 'read-only') {
394
+ // Filesystem and network are independent. A read-only filesystem still gets
395
+ // audited network readers unless the step separately restricts the network.
396
+ effectiveTools = permissions.network === 'owenloop-only'
397
+ ? READ_ONLY_OWENLOOP_ONLY_NETWORK_TOOLS
398
+ : [...READ_ONLY_TOOLS];
399
+ }
400
+ else if (effectiveTools === undefined && permissions.network === 'owenloop-only') {
401
+ effectiveTools = [...OWENLOOP_ONLY_NETWORK_TOOLS];
402
+ }
403
+ if (effectiveTools !== undefined) {
404
+ options.tools = effectiveTools.filter((tool) => !OWENLOOP_CONTROL_TOOLS.has(tool));
405
+ options.allowedTools = [
406
+ ...new Set([...effectiveTools, ...BORN_BOUND_OWENLOOP_TOOLS]),
407
+ ];
408
+ }
409
+ if (isolated) {
410
+ // Defense in depth only: the restricted MCP child does not register `reject`
411
+ // at all. The deny protects against SDK/tool-surface regressions without being
412
+ // the visibility boundary.
413
+ options.disallowedTools = [
414
+ ...new Set([
415
+ ...(permissions.disallowedTools ?? []),
416
+ ...RESTRICTED_OWENLOOP_DENIED_TOOLS,
417
+ ]),
418
+ ];
419
+ }
420
+ else if (permissions.disallowedTools !== undefined) {
421
+ options.disallowedTools = [...permissions.disallowedTools];
422
+ }
423
+ // Normalization already guaranteed a positive integer or absence.
424
+ if (permissions.maxTurns !== undefined)
425
+ options.maxTurns = permissions.maxTurns;
426
+ const skills = permissions.extensions['skills'];
427
+ if (!isolated && (skills === 'all' || (Array.isArray(skills) && skills.every((s) => typeof s === 'string')))) {
428
+ options.skills = skills;
429
+ }
430
+ if (extra.sessionId !== undefined)
431
+ options.sessionId = extra.sessionId;
432
+ if (extra.resume !== undefined)
433
+ options.resume = extra.resume;
434
+ // EXTENSIONS KEYS DELIBERATELY NOT MAPPED, so a reviewer reads intent rather
435
+ // than an omission:
436
+ // - `hooks`: `Options.hooks` takes JS callback matchers, not the settings-file
437
+ // JSON shape a bag carries. Different types; a bag `hooks` map cannot be
438
+ // passed through.
439
+ // - `memory`, `background`, `isolation`, `color`, `initialPrompt`: Task-tool
440
+ // subagent-frontmatter concepts with no `Options` equivalent at this SDK
441
+ // version.
442
+ // Unknown extension keys are ignored in silence — `owenloop work lint` is the place
443
+ // that warns about them.
444
+ //
445
+ // Outside isolation, `settingSources` and `strictMcpConfig` stay unset so the
446
+ // SDK preserves its normal settings and MCP behavior, including the full
447
+ // get_order/submit/reject work-holder server. Isolation sets `settingSources: []`
448
+ // and `strictMcpConfig: true` above, mounts the positive two-tool work-holder
449
+ // subset, and removes settings, hooks, skills, or external MCP that could bypass
450
+ // the authored restriction.
451
+ // `persistSession` always stays unset: its default is `true`, and disabling it
452
+ // would break resume-on-rejection.
453
+ return options;
454
+ }
455
+ const DEFAULT_START_DEPENDENCIES = {
456
+ createSessionId: randomUUID,
457
+ loadQuery: async () => {
458
+ const { query } = await import('@anthropic-ai/claude-agent-sdk');
459
+ return (args) => query(args);
460
+ },
461
+ };
462
+ /** Module-level, process-wide, keyed by session token. Only reachable from the
463
+ * process that started the session — which is exactly why `stop` is documented
464
+ * as a no-op on a token this process did not start. */
465
+ const SESSIONS = new Map();
466
+ /**
467
+ * Drive the SDK message stream to TURN END and map it onto `AgentEvent`s.
468
+ *
469
+ * Resolves at the `result` message — turn end, per the contract — not at process
470
+ * exit, and regardless of whether the result reports an error.
471
+ *
472
+ * `onInit` fires after a matching `system/init` confirms the preselected cold-
473
+ * start session id. `startClaude` emits `{kind:'started'}` before query creation;
474
+ * this callback marks the later provider confirmation, not the persistence gate.
475
+ *
476
+ * PHASE 6, ITEM 1 — EXPORTED, AND TYPED ON `AsyncIterable` RATHER THAN `Query`.
477
+ * This is the one function that maps the SDK's message stream onto this
478
+ * project's `AgentEvent` contract, so it is the only place a recorded transcript
479
+ * can prove the mapping still matches a shipped vendor build without spawning
480
+ * the vendor binary. `Query` is an `AsyncGenerator` PLUS control methods
481
+ * (`interrupt`, `setModel`, …) that this function never calls; asking only for
482
+ * what it uses is what lets a fixture drive it. A live `Query` still satisfies
483
+ * the narrower type, so nothing at the call sites changes.
484
+ */
485
+ export async function consumeTurn(q, onEvent, onInit, expectedSessionId) {
486
+ let sessionId;
487
+ for await (const message of q) {
488
+ if (message.type === 'system' && message.subtype === 'init') {
489
+ if (expectedSessionId !== undefined && message.session_id !== expectedSessionId) {
490
+ throw new Error(`provider session id mismatch: expected ${expectedSessionId}, received ${message.session_id}`);
491
+ }
492
+ sessionId = message.session_id;
493
+ // The ONLY place these are observable. The live smoke asserts on the
494
+ // `apiKeySource` here (subscription OAuth vs. an API key), and a later
495
+ // phase's version-mismatch warning will want `claude_code_version`.
496
+ const servers = message.mcp_servers.map((s) => `${s.name}=${s.status}`).join(',');
497
+ onEvent({
498
+ kind: 'progress',
499
+ text: `session ${message.session_id}: cliVersion=${message.claude_code_version} ` +
500
+ `model=${message.model} apiKeySource=${message.apiKeySource} ` +
501
+ `permissionMode=${message.permissionMode} cwd=${message.cwd} mcp=[${servers}]`,
502
+ });
503
+ onInit?.(sessionId);
504
+ }
505
+ else if (message.type === 'result') {
506
+ if (message.subtype !== 'success') {
507
+ // The contract's channel for "something went wrong that is not a resume
508
+ // failure". Emitted BEFORE turn_ended so a caller reading events in
509
+ // order sees the cause before the turn closes.
510
+ onEvent({
511
+ kind: 'exited',
512
+ exitCode: null,
513
+ error: message.errors.join('; ') || message.subtype,
514
+ });
515
+ }
516
+ onEvent({ kind: 'turn_ended' });
517
+ return { sessionId, sawResult: true };
518
+ }
519
+ // `needs_input` is NEVER emitted: this SDK path has no blocking-question
520
+ // channel that maps to it, and the contract has no reply channel by design.
521
+ }
522
+ return { sessionId, sawResult: false };
523
+ }
524
+ /** The message text of an unknown thrown value, for an `exited` event. */
525
+ function errText(err) {
526
+ return err instanceof Error ? err.message : String(err);
527
+ }
528
+ export async function startClaude(args, onEvent, dependencies = DEFAULT_START_DEPENDENCIES) {
529
+ // The provider token exists before any SDK work. `started` is synchronous by
530
+ // contract, so the caller's fsynced active-row append must return before the
531
+ // query factory can initialize a process or receive prompt bytes.
532
+ const sessionId = dependencies.createSessionId();
533
+ const ref = { harness: HARNESS_ID, token: sessionId };
534
+ try {
535
+ onEvent({ kind: 'started', ref });
536
+ }
537
+ catch (err) {
538
+ try {
539
+ onEvent({ kind: 'exited', exitCode: null, error: errText(err) });
540
+ }
541
+ catch {
542
+ // Preserve the durable-persistence failure that closed the start gate.
543
+ }
544
+ throw err;
545
+ }
546
+ const env = buildChildEnv(process.env, { allowApiBilling: allowApiBillingFrom(process.env) });
547
+ const abortController = new AbortController();
548
+ const options = buildClaudeOptions(args, { env, abortController, onEvent, sessionId });
549
+ let q;
550
+ try {
551
+ // A plain STRING prompt, not an AsyncIterable. Query construction is the
552
+ // provider-delivery boundary in the pinned SDK, so it must remain after the
553
+ // `started` callback above. Streaming input buys this adapter nothing else.
554
+ const query = await dependencies.loadQuery();
555
+ q = query({ prompt: args.brief, options });
556
+ }
557
+ catch (err) {
558
+ try {
559
+ abortController.abort();
560
+ }
561
+ catch {
562
+ // An already-aborted controller is equivalent to success.
563
+ }
564
+ onEvent({ kind: 'exited', exitCode: null, error: errText(err) });
565
+ throw err;
566
+ }
567
+ SESSIONS.set(sessionId, { query: q, abortController, options });
568
+ let initVerified = false;
569
+ let outcome;
570
+ try {
571
+ outcome = await consumeTurn(q, onEvent, () => {
572
+ initVerified = true;
573
+ }, sessionId);
574
+ }
575
+ catch (err) {
576
+ // An init mismatch or pre-init failure must not leave the preselected token
577
+ // resumable. A post-init provider failure keeps the same registry behavior as
578
+ // before; `stop()` can still find and idempotently close that verified session.
579
+ if (!initVerified)
580
+ SESSIONS.delete(sessionId);
581
+ try {
582
+ abortController.abort();
583
+ }
584
+ catch {
585
+ // An already-aborted controller is equivalent to success.
586
+ }
587
+ try {
588
+ q.close();
589
+ }
590
+ catch {
591
+ // Preserve the provider or session-integrity error that caused the abort.
592
+ }
593
+ onEvent({ kind: 'exited', exitCode: null, error: errText(err) });
594
+ throw err;
595
+ }
596
+ if (outcome.sessionId === undefined) {
597
+ SESSIONS.delete(sessionId);
598
+ try {
599
+ abortController.abort();
600
+ }
601
+ catch {
602
+ // An already-aborted controller is equivalent to success.
603
+ }
604
+ try {
605
+ q.close();
606
+ }
607
+ catch {
608
+ // The missing-init error below is authoritative.
609
+ }
610
+ const why = outcome.sawResult
611
+ ? 'the turn ended without confirming the supplied session id'
612
+ : 'the stream ended before confirming the supplied session id';
613
+ onEvent({ kind: 'exited', exitCode: null, error: why });
614
+ throw new Error(`harness start failed: ${why}`);
615
+ }
616
+ return ref;
617
+ }
618
+ async function deliver(ref, message, args, onEvent) {
619
+ // Session lookup is scoped to the PROJECT DIRECTORY, so a deleted worktree can
620
+ // never resume no matter how good the token is. Distinct message on purpose —
621
+ // the caller reads these to tell the two failures apart.
622
+ if (!existsSync(args.cwd)) {
623
+ throw new ResumeUnavailableError(`resume cwd no longer exists: ${args.cwd}`);
624
+ }
625
+ // Deterministic pre-check, rather than parsing a failed query's error text
626
+ // (that string is unverified and can change between releases).
627
+ //
628
+ // KNOWN FALSE NEGATIVE, accepted: this also returns undefined for a session
629
+ // that exists but has no extractable summary, which downgrades a resumable
630
+ // session to a cold replay. The failure direction is a wasted replay — never a
631
+ // hang and never a wrong-session resume — so it is the safe way to be wrong.
632
+ let known = false;
633
+ try {
634
+ const { getSessionInfo } = await import('@anthropic-ai/claude-agent-sdk');
635
+ known = (await getSessionInfo(ref.token, { dir: args.cwd })) !== undefined;
636
+ }
637
+ catch {
638
+ known = false;
639
+ }
640
+ if (!known) {
641
+ throw new ResumeUnavailableError(`provider no longer knows session ${ref.token}`);
642
+ }
643
+ const env = buildChildEnv(process.env, { allowApiBilling: allowApiBillingFrom(process.env) });
644
+ const abortController = new AbortController();
645
+ // PHASE 4: `args` IS THE SOURCE OF TRUTH, not `SESSIONS`.
646
+ //
647
+ // Until Phase 4 this branched on `SESSIONS.get(ref.token)` and, on a miss, built
648
+ // a MINIMAL option set — no permission mode, no tool lists, no model. A resume
649
+ // that happens in a different process from the start (a re-offered step is
650
+ // dispatched as a fresh `owenloop work agent-run` child, so that is the normal case,
651
+ // not the exotic one) therefore ran the resumed turn under weaker permissions
652
+ // than the turn it continued, and stalled headless. `DeliverArgs` now carries
653
+ // the same normalized `StepPermissions` the caller passed to `start`, so the
654
+ // same mapping runs on both paths and the in-process map is no longer consulted
655
+ // for options at all.
656
+ //
657
+ // A resumed turn does not inherit permission mode / tool lists / model from the
658
+ // session — they are per-invocation flags — which is exactly why they must be
659
+ // re-mapped here.
660
+ const options = buildClaudeOptions(args, {
661
+ env,
662
+ abortController,
663
+ onEvent,
664
+ resume: ref.token,
665
+ });
666
+ // `forkSession` is deliberately NOT set: a fork would mint a new session id the
667
+ // caller does not know about, and resume must continue the SAME session.
668
+ const { query } = await import('@anthropic-ai/claude-agent-sdk');
669
+ const q = query({ prompt: message, options });
670
+ SESSIONS.set(ref.token, { query: q, abortController, options });
671
+ try {
672
+ // Never emits `started` — the contract forbids re-emitting it on a resume.
673
+ await consumeTurn(q, onEvent);
674
+ }
675
+ catch (err) {
676
+ const text = errText(err);
677
+ // Belt and braces behind the `getSessionInfo` pre-check.
678
+ if (RESUME_FAILURE_RE.test(text)) {
679
+ throw new ResumeUnavailableError(`provider refused resume of session ${ref.token}: ${text}`);
680
+ }
681
+ onEvent({ kind: 'exited', exitCode: null, error: text });
682
+ throw err;
683
+ }
684
+ }
685
+ async function stop(ref) {
686
+ const session = SESSIONS.get(ref.token);
687
+ // Idempotent by contract: an already-dead session is not an error, and a
688
+ // session started by a previous process is simply not reachable from here.
689
+ if (session === undefined)
690
+ return;
691
+ SESSIONS.delete(ref.token);
692
+ try {
693
+ session.abortController.abort();
694
+ }
695
+ catch {
696
+ // an already-aborted controller is exactly the not-an-error case
697
+ }
698
+ try {
699
+ // Terminates the underlying process and cleans up pending requests, MCP
700
+ // transports and the CLI subprocess. `interrupt()` is not usable here: it is
701
+ // streaming-input-mode only, and this adapter sends a plain string prompt.
702
+ session.query.close();
703
+ }
704
+ catch {
705
+ // a close that throws on an already-exited child is likewise not an error
706
+ }
707
+ }
708
+ /**
709
+ * The singleton. Exported so tests use the object directly rather than through
710
+ * registry state, even though importing this module also registers it.
711
+ */
712
+ // ---------------------------------------------------------------------------
713
+ // Static option-bag check (`owenloop work lint`)
714
+ // ---------------------------------------------------------------------------
715
+ /**
716
+ * The field vocabulary this harness understands inside a step's `x.harness` map.
717
+ * Moved here from the deleted `src/adapters/claude-code.ts`: which option names
718
+ * are legal is vendor knowledge, so it belongs in the vendor's own file and
719
+ * nowhere else.
720
+ *
721
+ * `name` and `description` are RESERVED — owenloop generates the subagent
722
+ * identity, so a def that sets them is overridden silently and is worth an error.
723
+ */
724
+ const RESERVED_KEYS = ['name', 'description'];
725
+ const KNOWN_FIELDS = new Set([
726
+ 'name',
727
+ 'description',
728
+ 'tools',
729
+ 'disallowedTools',
730
+ 'filesystem',
731
+ 'network',
732
+ 'model',
733
+ 'permissionMode',
734
+ 'maxTurns',
735
+ 'skills',
736
+ 'mcpServers',
737
+ 'hooks',
738
+ 'memory',
739
+ 'background',
740
+ 'effort',
741
+ 'isolation',
742
+ 'color',
743
+ 'initialPrompt',
744
+ ]);
745
+ const MEMORY_SCOPES = new Set(['user', 'project', 'local']);
746
+ function typeName(v) {
747
+ if (v === null)
748
+ return 'null';
749
+ if (Array.isArray(v))
750
+ return 'array';
751
+ return typeof v;
752
+ }
753
+ /**
754
+ * Check one step's `x.harness` option map against this harness's vocabulary.
755
+ *
756
+ * `bag` arrives with `id` already stripped by the def parser, so `id` is never
757
+ * reported as an unknown field. Unknown fields are WARNINGS (a def may be written
758
+ * against a newer CLI than this owenloop build); wrong types and reserved keys
759
+ * are ERRORS. Never throws — a malformed bag produces findings.
760
+ */
761
+ function lintStep(bag, step) {
762
+ const findings = [
763
+ ...validateHarnessOptions(bag, step),
764
+ ...claudePreflight(normalizeStepPermissions(bag)).map((issue) => ({
765
+ severity: 'error',
766
+ step,
767
+ message: issue.message,
768
+ ...(issue.field !== undefined ? { field: issue.field } : {}),
769
+ })),
770
+ ];
771
+ const err = (message, field) => {
772
+ findings.push({ severity: 'error', step, message, ...(field !== undefined ? { field } : {}) });
773
+ };
774
+ const warn = (message, field) => {
775
+ findings.push({ severity: 'warning', step, message, ...(field !== undefined ? { field } : {}) });
776
+ };
777
+ for (const key of RESERVED_KEYS) {
778
+ if (key in bag)
779
+ err(`'${key}' is generated and cannot be set in the bag`, key);
780
+ }
781
+ for (const key of Object.keys(bag)) {
782
+ if (!KNOWN_FIELDS.has(key)) {
783
+ warn(`unknown field '${key}' — known fields: ${[...KNOWN_FIELDS].join(', ')}`, key);
784
+ }
785
+ }
786
+ const check = (field, ok, expected) => {
787
+ if (field in bag && !ok(bag[field])) {
788
+ err(`${field} must be ${expected}, got ${typeName(bag[field])}`, field);
789
+ }
790
+ };
791
+ check('skills', (v) => v === 'all' || (Array.isArray(v) && v.every((e) => typeof e === 'string')), "'all' or a string[]");
792
+ check('background', (v) => typeof v === 'boolean', 'a boolean');
793
+ check('mcpServers', isPlainMap, 'a map');
794
+ check('hooks', isPlainMap, 'a map');
795
+ if ('memory' in bag && !MEMORY_SCOPES.has(bag['memory'])) {
796
+ err(`memory must be one of ${[...MEMORY_SCOPES].join('|')}`, 'memory');
797
+ }
798
+ if (isPlainMap(bag['mcpServers']) && 'owenloop' in bag['mcpServers']) {
799
+ warn('mcpServers.owenloop is reserved and is replaced by the worker at start', 'mcpServers');
800
+ }
801
+ return findings;
802
+ }
803
+ /**
804
+ * The command a human runs to re-open this session in an interactive terminal.
805
+ *
806
+ * WHY IT RESOLVES THE BINARY RATHER THAN PRINTING A BARE NAME. An operator who
807
+ * set `OWENLOOP_CLAUDE_BIN` did so because the plain name does not run on their
808
+ * machine, and a listing that prints a command they cannot paste is worse than
809
+ * printing nothing. `resolveExecutable` returns `undefined` when neither the
810
+ * override nor a `PATH` hit exists; the bare CLI name is the honest fallback
811
+ * there, since the SDK's own bundled executable has no stable path to name.
812
+ *
813
+ * It reads `process.env` and not the child environment: this is a command for
814
+ * the OPERATOR's shell, not for a harness child.
815
+ */
816
+ function resumeCommand(ref) {
817
+ return {
818
+ command: resolveExecutable(process.env) ?? 'claude',
819
+ args: ['--resume', ref.token],
820
+ };
821
+ }
822
+ export const claudeAdapter = {
823
+ id: HARNESS_ID,
824
+ // The provider stores the session and resumes it from the opaque token this
825
+ // adapter puts in `HarnessSessionRef.token`.
826
+ resumeTier: 'native-token',
827
+ preflight: claudePreflight,
828
+ start: startClaude,
829
+ deliver,
830
+ stop,
831
+ lintStep,
832
+ resumeCommand,
833
+ };
834
+ // Self-registration at import time: importing this module is what puts the
835
+ // adapter in the runtime registry. WHO imports it is a composition root's
836
+ // decision (`src/roles/agent-run.ts`, `src/roles/lint.ts`), not this module's.
837
+ register(claudeAdapter);