owenloop 0.4.1 → 0.5.0

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 (154) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/README.md +58 -31
  3. package/bin/owenloop.mjs +2 -2
  4. package/dist/packages/work/src/agent/brief.d.ts +172 -0
  5. package/dist/packages/work/src/agent/brief.js +193 -0
  6. package/dist/packages/work/src/agent/loop.d.ts +135 -0
  7. package/dist/packages/work/src/agent/loop.js +542 -0
  8. package/dist/packages/work/src/agent/workdir.d.ts +210 -0
  9. package/dist/packages/work/src/agent/workdir.js +319 -0
  10. package/dist/packages/work/src/bundle/cache.d.ts +90 -0
  11. package/dist/packages/work/src/bundle/cache.js +324 -0
  12. package/dist/packages/work/src/bundle/fetch.d.ts +85 -0
  13. package/dist/packages/work/src/bundle/fetch.js +325 -0
  14. package/dist/packages/work/src/bundle/types.d.ts +160 -0
  15. package/dist/packages/work/src/bundle/types.js +1 -0
  16. package/dist/packages/work/src/credentials/owenloop.d.ts +11 -0
  17. package/dist/packages/work/src/credentials/owenloop.js +28 -0
  18. package/dist/packages/work/src/credentials/reader.d.ts +36 -0
  19. package/dist/packages/work/src/credentials/reader.js +32 -0
  20. package/dist/packages/work/src/credentials/resolve.d.ts +19 -0
  21. package/dist/packages/work/src/credentials/resolve.js +56 -0
  22. package/dist/packages/work/src/exec/loop.d.ts +29 -0
  23. package/dist/packages/work/src/exec/loop.js +215 -0
  24. package/dist/packages/work/src/exec/receipt.d.ts +38 -0
  25. package/dist/packages/work/src/exec/receipt.js +21 -0
  26. package/dist/packages/work/src/exec/runner.d.ts +65 -0
  27. package/dist/packages/work/src/exec/runner.js +185 -0
  28. package/dist/packages/work/src/harness/child-env.d.ts +100 -0
  29. package/dist/packages/work/src/harness/child-env.js +127 -0
  30. package/dist/packages/work/src/harness/claude.d.ts +128 -0
  31. package/dist/packages/work/src/harness/claude.js +635 -0
  32. package/dist/packages/work/src/harness/codex.d.ts +110 -0
  33. package/dist/packages/work/src/harness/codex.js +896 -0
  34. package/dist/packages/work/src/harness/contract.d.ts +283 -0
  35. package/dist/packages/work/src/harness/contract.js +32 -0
  36. package/dist/packages/work/src/harness/fake.d.ts +59 -0
  37. package/dist/packages/work/src/harness/fake.js +90 -0
  38. package/dist/packages/work/src/harness/jsonrpc-stdio.d.ts +108 -0
  39. package/dist/packages/work/src/harness/jsonrpc-stdio.js +344 -0
  40. package/dist/packages/work/src/harness/permissions.d.ts +62 -0
  41. package/dist/packages/work/src/harness/permissions.js +93 -0
  42. package/dist/packages/work/src/harness/registry.d.ts +47 -0
  43. package/dist/packages/work/src/harness/registry.js +45 -0
  44. package/dist/packages/work/src/harness/session-store.d.ts +163 -0
  45. package/dist/packages/work/src/harness/session-store.js +319 -0
  46. package/dist/packages/work/src/harness/types.d.ts +29 -0
  47. package/dist/packages/work/src/harness/types.js +14 -0
  48. package/dist/packages/work/src/harnesses.d.ts +38 -0
  49. package/dist/packages/work/src/harnesses.js +38 -0
  50. package/dist/packages/work/src/hold/loop.d.ts +36 -0
  51. package/dist/packages/work/src/hold/loop.js +23 -0
  52. package/dist/packages/work/src/hold/mcp.d.ts +55 -0
  53. package/dist/packages/work/src/hold/mcp.js +149 -0
  54. package/dist/packages/work/src/hub/client.d.ts +22 -0
  55. package/dist/packages/work/src/hub/client.js +78 -0
  56. package/dist/packages/work/src/hub/types.d.ts +290 -0
  57. package/dist/packages/work/src/hub/types.js +28 -0
  58. package/dist/packages/work/src/lease/loop.d.ts +94 -0
  59. package/dist/packages/work/src/lease/loop.js +277 -0
  60. package/dist/packages/work/src/main.d.ts +1 -0
  61. package/dist/packages/work/src/main.js +48 -0
  62. package/dist/packages/work/src/mcp/server.d.ts +125 -0
  63. package/dist/packages/work/src/mcp/server.js +320 -0
  64. package/dist/packages/work/src/roles/agent-run.d.ts +118 -0
  65. package/dist/packages/work/src/roles/agent-run.js +447 -0
  66. package/dist/packages/work/src/roles/exec.d.ts +40 -0
  67. package/dist/packages/work/src/roles/exec.js +203 -0
  68. package/dist/packages/work/src/roles/hold.d.ts +68 -0
  69. package/dist/packages/work/src/roles/hold.js +324 -0
  70. package/dist/packages/work/src/roles/join.d.ts +18 -0
  71. package/dist/packages/work/src/roles/join.js +204 -0
  72. package/dist/packages/work/src/roles/lint.d.ts +59 -0
  73. package/dist/packages/work/src/roles/lint.js +200 -0
  74. package/dist/packages/work/src/roles/prepare.d.ts +1 -0
  75. package/dist/packages/work/src/roles/prepare.js +249 -0
  76. package/dist/packages/work/src/roles/release.d.ts +48 -0
  77. package/dist/packages/work/src/roles/release.js +137 -0
  78. package/dist/packages/work/src/roles/sessions.d.ts +61 -0
  79. package/dist/packages/work/src/roles/sessions.js +180 -0
  80. package/dist/packages/work/src/roles/settings.d.ts +6 -0
  81. package/dist/packages/work/src/roles/settings.js +66 -0
  82. package/dist/packages/work/src/roles/shift.d.ts +12 -0
  83. package/dist/packages/work/src/roles/shift.js +228 -0
  84. package/dist/packages/work/src/roles/signals.d.ts +55 -0
  85. package/dist/packages/work/src/roles/signals.js +62 -0
  86. package/dist/packages/work/src/settings/provision.d.ts +21 -0
  87. package/dist/packages/work/src/settings/provision.js +47 -0
  88. package/dist/packages/work/src/settings/settings.d.ts +120 -0
  89. package/dist/packages/work/src/settings/settings.js +116 -0
  90. package/dist/packages/work/src/shift/client.d.ts +24 -0
  91. package/dist/packages/work/src/shift/client.js +124 -0
  92. package/dist/packages/work/src/shift/loop.d.ts +120 -0
  93. package/dist/packages/work/src/shift/loop.js +468 -0
  94. package/dist/packages/work/src/shift/protocol.d.ts +91 -0
  95. package/dist/packages/work/src/shift/protocol.js +24 -0
  96. package/dist/packages/work/src/shift/routing.d.ts +35 -0
  97. package/dist/packages/work/src/shift/routing.js +50 -0
  98. package/dist/packages/work/src/shift/runtime.d.ts +43 -0
  99. package/dist/packages/work/src/shift/runtime.js +274 -0
  100. package/dist/packages/work/src/shift/server.d.ts +23 -0
  101. package/dist/packages/work/src/shift/server.js +716 -0
  102. package/dist/packages/work/src/shift/spawn.d.ts +86 -0
  103. package/dist/packages/work/src/shift/spawn.js +100 -0
  104. package/dist/packages/work/src/shift/state.d.ts +77 -0
  105. package/dist/packages/work/src/shift/state.js +162 -0
  106. package/dist/packages/work/src/usage.d.ts +6 -0
  107. package/dist/packages/work/src/usage.js +175 -0
  108. package/dist/{cli.d.ts → src/cli.d.ts} +18 -3
  109. package/dist/{cli.js → src/cli.js} +770 -114
  110. package/dist/{credentials.d.ts → src/credentials.d.ts} +18 -12
  111. package/dist/{credentials.js → src/credentials.js} +14 -12
  112. package/dist/{defs.js → src/defs.js} +36 -36
  113. package/dist/{engine.d.ts → src/engine.d.ts} +8 -8
  114. package/dist/{engine.js → src/engine.js} +14 -14
  115. package/dist/{hub.d.ts → src/hub.d.ts} +205 -10
  116. package/dist/{hub.js → src/hub.js} +370 -12
  117. package/dist/{index.d.ts → src/index.d.ts} +1 -1
  118. package/dist/{index.js → src/index.js} +1 -1
  119. package/dist/{mcp → src/mcp}/serve.d.ts +5 -4
  120. package/dist/{mcp → src/mcp}/serve.js +168 -31
  121. package/dist/{mcp → src/mcp}/server.d.ts +6 -9
  122. package/dist/{mcp → src/mcp}/server.js +6 -9
  123. package/dist/{model.js → src/model.js} +1 -1
  124. package/dist/{types.d.ts → src/types.d.ts} +18 -18
  125. package/dist/{util.d.ts → src/util.d.ts} +3 -2
  126. package/dist/{util.js → src/util.js} +3 -2
  127. package/dist/{owenwork.d.ts → src/work-settings.d.ts} +22 -22
  128. package/dist/{owenwork.js → src/work-settings.js} +27 -27
  129. package/docs/authoring.md +93 -53
  130. package/docs/cli.md +597 -76
  131. package/docs/design.md +33 -33
  132. package/docs/embedding.md +10 -9
  133. package/examples/workflows/{command-worker.yaml → command-executor.yaml} +15 -15
  134. package/examples/workflows/compile-dev-playbook.yaml +338 -0
  135. package/examples/workflows/judges/gate-sharpness.md +39 -0
  136. package/examples/workflows/judges/security.md +34 -0
  137. package/package.json +17 -8
  138. /package/dist/{add.d.ts → src/add.d.ts} +0 -0
  139. /package/dist/{add.js → src/add.js} +0 -0
  140. /package/dist/{defs.d.ts → src/defs.d.ts} +0 -0
  141. /package/dist/{factory.d.ts → src/factory.d.ts} +0 -0
  142. /package/dist/{factory.js → src/factory.js} +0 -0
  143. /package/dist/{lock.d.ts → src/lock.d.ts} +0 -0
  144. /package/dist/{lock.js → src/lock.js} +0 -0
  145. /package/dist/{model.d.ts → src/model.d.ts} +0 -0
  146. /package/dist/{paths.d.ts → src/paths.d.ts} +0 -0
  147. /package/dist/{paths.js → src/paths.js} +0 -0
  148. /package/dist/{schema.d.ts → src/schema.d.ts} +0 -0
  149. /package/dist/{schema.js → src/schema.js} +0 -0
  150. /package/dist/{store.d.ts → src/store.d.ts} +0 -0
  151. /package/dist/{store.js → src/store.js} +0 -0
  152. /package/dist/{types.js → src/types.js} +0 -0
  153. /package/dist/{untar.d.ts → src/untar.d.ts} +0 -0
  154. /package/dist/{untar.js → src/untar.js} +0 -0
@@ -0,0 +1,635 @@
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 { accessSync, constants, existsSync } from 'node:fs';
27
+ import { delimiter, join } from 'node:path';
28
+ import { register } from "./registry.js";
29
+ import { filterOwenloopEnv } from "./child-env.js";
30
+ import { ResumeUnavailableError } from "./contract.js";
31
+ /** The registry key — the id a step def names in `x.harness.id`, and the key
32
+ * `harness-versions.json` pins the CLI under. */
33
+ const HARNESS_ID = 'claude-code';
34
+ // ---------------------------------------------------------------------------
35
+ // Environment hygiene
36
+ // ---------------------------------------------------------------------------
37
+ /**
38
+ * The variables deleted from the child environment unless API billing is
39
+ * explicitly allowed.
40
+ *
41
+ * `ANTHROPIC_API_KEY` / `ANTHROPIC_AUTH_TOKEN`: an inherited key SILENTLY
42
+ * shadows the operator's subscription OAuth and bills API credits instead. That
43
+ * shadowing is the entire reason this strip exists — it is a correctness
44
+ * requirement, not hardening.
45
+ *
46
+ * `CLAUDECODE`: set by an already-running Claude Code process to mark "you are
47
+ * inside me". Inheriting it confuses a nested launch, so it goes under the same
48
+ * toggle — one flag, one list, no second knob.
49
+ *
50
+ * `CLAUDE_CODE_OAUTH_TOKEN` IS DELIBERATELY NOT IN THIS LIST AND MUST NEVER BE
51
+ * ADDED TO IT: it is the subscription credential, and the launchd path needs it
52
+ * to survive. `test/harness-claude.test.ts` asserts that explicitly so a future
53
+ * "tidy up the strip list" edit fails loudly instead of silently breaking
54
+ * headless auth. Phase 6 measured it end to end under a real launchd job —
55
+ * `test/tools/launchd-env-probe.sh`, which observes the variable arriving in the
56
+ * job AND surviving `buildChildEnv`, while `OWENLOOP_TOKEN` set in the same
57
+ * plist does not survive.
58
+ */
59
+ const STRIPPED_ENV_KEYS = ['ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN', 'CLAUDECODE'];
60
+ /** The machine-level opt-out. Read from the environment INSIDE this module on
61
+ * purpose: the contract deliberately refused an `allowApiBilling` field on
62
+ * `StartArgs` (it is machine config, not per-start data) and `src/settings.ts`
63
+ * is shared surface another phase may be editing. */
64
+ const ALLOW_API_BILLING_VAR = 'OWENLOOP_ALLOW_API_BILLING';
65
+ /** Operator override for the CLI binary; see `resolveExecutable`. */
66
+ const BIN_OVERRIDE_VAR = 'OWENLOOP_CLAUDE_BIN';
67
+ /**
68
+ * Build the environment the harness child runs under.
69
+ *
70
+ * WHY IT SPREADS RATHER THAN LISTS. The SDK's `Options.env` REPLACES the
71
+ * subprocess environment entirely — it is NOT merged with `process.env` (see
72
+ * that field's own JSDoc in the installed `sdk.d.ts`). Both halves of that bite:
73
+ *
74
+ * - passing only the deltas would blow away `PATH`/`HOME` and break the child;
75
+ * - omitting `env` altogether would let an ambient API key through, which is
76
+ * exactly the bug this function exists to prevent.
77
+ *
78
+ * So the caller ALWAYS sets `env`, and this function always returns a full
79
+ * environment: spread the source, then delete.
80
+ *
81
+ * `source` is a parameter rather than a read of `process.env` so the unit test
82
+ * injects a fixture and never mutates the real environment. The input is not
83
+ * mutated.
84
+ *
85
+ * `delete` is used rather than assigning `undefined`: an own key holding
86
+ * `undefined` is not obviously equivalent to an absent key across the SDK's
87
+ * serialization boundary, and deleting removes the question.
88
+ *
89
+ * TWO INDEPENDENT FILTERS RUN HERE, and conflating them would break one of
90
+ * them:
91
+ *
92
+ * 1. `STRIPPED_ENV_KEYS` — the vendor API-key strip. It is specific to THIS
93
+ * adapter, it is a correctness requirement (an inherited key shadows the
94
+ * subscription and bills credits), and it is under the `allowApiBilling`
95
+ * opt-out.
96
+ * 2. `filterOwenloopEnv` — Phase 6's `OWENLOOP_*` namespace allowlist, shared
97
+ * with the other adapter and NOT under any opt-out. It removes owenloop's
98
+ * own variables that no harness child has a consumer for — the hub bearer
99
+ * override above all — and touches nothing outside that namespace. In
100
+ * particular it cannot reach `CLAUDE_CODE_OAUTH_TOKEN`, which is not an
101
+ * `OWENLOOP_*` name and therefore survives by construction, which is what
102
+ * Phase 6 item 3 needs under launchd.
103
+ *
104
+ * Everything else survives: `PATH`, `HOME`, `TMPDIR`, proxy and TLS variables,
105
+ * and the three admitted `OWENLOOP_*` names the mounted work-holder MCP child
106
+ * actually reads.
107
+ */
108
+ export function buildChildEnv(source, opts) {
109
+ const result = filterOwenloopEnv(source);
110
+ if (!opts.allowApiBilling) {
111
+ for (const key of STRIPPED_ENV_KEYS)
112
+ delete result[key];
113
+ }
114
+ return result;
115
+ }
116
+ /** Whether API billing is allowed, from a machine-level environment toggle.
117
+ * Default is OFF — the strip happens unless the operator opted in. */
118
+ export function allowApiBillingFrom(source) {
119
+ return source[ALLOW_API_BILLING_VAR] === '1';
120
+ }
121
+ // ---------------------------------------------------------------------------
122
+ // Binary resolution
123
+ // ---------------------------------------------------------------------------
124
+ /**
125
+ * Resolve the CLI executable: `OWENLOOP_CLAUDE_BIN` → a `claude` on `PATH` →
126
+ * `undefined`.
127
+ *
128
+ * `undefined` means the caller OMITS `pathToClaudeCodeExecutable` entirely and
129
+ * lets the SDK use its own bundled executable. That third case is a decision,
130
+ * not an oversight: the bundled executable is the same CLI reading the same
131
+ * credential store, so subscription auth still works, whereas throwing would
132
+ * make the adapter unusable on a machine where the CLI sits somewhere unusual.
133
+ *
134
+ * The `PATH` walk is done in-process (`accessSync` with `X_OK`) rather than by
135
+ * shelling out: no shell, no extra child, and it is unit-testable against a
136
+ * fixture `PATH` the test builds and `chmod`s itself.
137
+ *
138
+ * `source` is the CHILD environment (a spread of `process.env`), so the override
139
+ * and the `PATH` searched are the same ones the child will see.
140
+ */
141
+ export function resolveExecutable(source) {
142
+ const override = source[BIN_OVERRIDE_VAR];
143
+ if (override !== undefined && override !== '')
144
+ return override;
145
+ const path = source['PATH'];
146
+ if (path === undefined || path === '')
147
+ return undefined;
148
+ for (const dir of path.split(delimiter)) {
149
+ if (dir === '')
150
+ continue;
151
+ const candidate = join(dir, 'claude');
152
+ try {
153
+ accessSync(candidate, constants.X_OK);
154
+ return candidate;
155
+ }
156
+ catch {
157
+ // not here (or not executable) — keep walking
158
+ }
159
+ }
160
+ return undefined;
161
+ }
162
+ // ---------------------------------------------------------------------------
163
+ // Option mapping
164
+ // ---------------------------------------------------------------------------
165
+ /**
166
+ * The six-value closed union the SDK types `Options.permissionMode` as.
167
+ * `StepPermissions.permissionMode` arrives as an UNVALIDATED non-empty string
168
+ * (normalization passes it through by design and leaves validation to
169
+ * `owenloop work lint`), so narrowing is mandatory, not defensive style.
170
+ */
171
+ const PERMISSION_MODES = [
172
+ 'default',
173
+ 'acceptEdits',
174
+ 'bypassPermissions',
175
+ 'plan',
176
+ 'dontAsk',
177
+ 'auto',
178
+ ];
179
+ /** The five-value closed union the SDK types `Options.effort` as. */
180
+ const EFFORT_LEVELS = ['low', 'medium', 'high', 'xhigh', 'max'];
181
+ /**
182
+ * The error text a resume against a token the provider does not know is
183
+ * expected to carry. SECONDARY detection only — `deliver` pre-checks with
184
+ * `getSessionInfo`, which is deterministic. The exact provider string is
185
+ * UNVERIFIED and can change between releases, which is precisely why it is not
186
+ * the primary path.
187
+ */
188
+ const RESUME_FAILURE_RE = /no conversation found|session not found|--resume/i;
189
+ function isPlainMap(v) {
190
+ return typeof v === 'object' && v !== null && !Array.isArray(v);
191
+ }
192
+ /** The mount for owenloop's own work-holder MCP surface, built from the worker's
193
+ * verbatim argv. `alwaysLoad` forces its tools into the turn-1 prompt instead of
194
+ * deferring them behind tool search — a step agent that cannot see `submit` on
195
+ * turn 1 cannot finish its order. */
196
+ function owenloopMount(mount) {
197
+ return { type: 'stdio', command: mount.command, args: mount.args, alwaysLoad: true };
198
+ }
199
+ /**
200
+ * `mcpServers`, with the owenloop mount layered ON TOP of whatever the step's
201
+ * bag declared. An author's own `owenloop` entry is overwritten, exactly as the
202
+ * legacy frontmatter builder overwrites it today — the mount is born bound to a
203
+ * specific order and a step def may not redirect it.
204
+ */
205
+ function mergeMcpServers(bagServers, mount) {
206
+ const base = isPlainMap(bagServers) ? bagServers : {};
207
+ return { ...base, owenloop: owenloopMount(mount) };
208
+ }
209
+ /**
210
+ * Map `StartArgs` + the Claude-owned extensions bag onto the SDK's `Options`.
211
+ *
212
+ * The mapping knowledge is PORTED from the legacy compile-time frontmatter
213
+ * builder — the knowledge is correct, only the output format changed. Nothing is
214
+ * imported from `src/adapters/`; the isolation test forbids that dependency
215
+ * direction.
216
+ */
217
+ export function buildClaudeOptions(inputs, extra) {
218
+ const { permissions } = inputs;
219
+ const options = {
220
+ cwd: inputs.cwd,
221
+ env: extra.env,
222
+ abortController: extra.abortController,
223
+ mcpServers: mergeMcpServers(permissions.extensions['mcpServers'], inputs.owenloopMcp),
224
+ stderr: (data) => {
225
+ extra.onEvent({ kind: 'progress', text: `stderr: ${data.trimEnd()}` });
226
+ },
227
+ };
228
+ // Omit the key entirely when nothing resolves — see `resolveExecutable`.
229
+ const executable = resolveExecutable(extra.env);
230
+ if (executable !== undefined)
231
+ options.pathToClaudeCodeExecutable = executable;
232
+ // PRECEDENCE, fixed by the contract: the per-start override wins over the
233
+ // step's configured value, for both model and effort.
234
+ const model = inputs.model ?? permissions.model;
235
+ if (model !== undefined)
236
+ options.model = model;
237
+ const rawEffort = inputs.effort ?? permissions.effort;
238
+ if (rawEffort !== undefined) {
239
+ if (EFFORT_LEVELS.includes(rawEffort)) {
240
+ options.effort = rawEffort;
241
+ }
242
+ else {
243
+ // Dropped rather than thrown or coerced — the same stance normalization
244
+ // takes for a bad `maxTurns`. The linter only checks effort is a string,
245
+ // so an unlintable-but-legal bag can carry an out-of-union value.
246
+ extra.onEvent({
247
+ kind: 'progress',
248
+ text: `dropped out-of-range effort '${rawEffort}' (expected one of ${EFFORT_LEVELS.join('|')})`,
249
+ });
250
+ }
251
+ }
252
+ if (permissions.permissionMode !== undefined) {
253
+ if (PERMISSION_MODES.includes(permissions.permissionMode)) {
254
+ const mode = permissions.permissionMode;
255
+ options.permissionMode = mode;
256
+ // 'bypassPermissions' is IGNORED by the SDK without this companion flag.
257
+ // Missing it is a silent downgrade to prompting, which in a headless run
258
+ // means the step stalls forever on a prompt no human will answer.
259
+ if (mode === 'bypassPermissions')
260
+ options.allowDangerouslySkipPermissions = true;
261
+ }
262
+ else {
263
+ extra.onEvent({
264
+ kind: 'progress',
265
+ text: `dropped unknown permissionMode '${permissions.permissionMode}' (expected one of ${PERMISSION_MODES.join('|')})`,
266
+ });
267
+ }
268
+ }
269
+ // `tools` and `allowedTools` are DIFFERENT SDK options and the step def's
270
+ // single `tools:` field needs both: `tools` is the base set of AVAILABLE
271
+ // built-in tools (what the legacy frontmatter `tools:` meant), `allowedTools`
272
+ // is the set auto-allowed WITHOUT a permission prompt. Only `tools` leaves
273
+ // every call waiting on a prompt nobody will answer headless; only
274
+ // `allowedTools` fails to restrict the surface the author asked to restrict.
275
+ //
276
+ // ABSENT means "the step named no tools" and must set NEITHER key: the SDK
277
+ // reads `tools: []` as "disable all built-in tools", which would yield an
278
+ // agent with no tools at all.
279
+ if (permissions.tools !== undefined) {
280
+ options.tools = [...permissions.tools];
281
+ options.allowedTools = [...permissions.tools];
282
+ }
283
+ if (permissions.disallowedTools !== undefined) {
284
+ options.disallowedTools = [...permissions.disallowedTools];
285
+ }
286
+ // Normalization already guaranteed a positive integer or absence.
287
+ if (permissions.maxTurns !== undefined)
288
+ options.maxTurns = permissions.maxTurns;
289
+ const skills = permissions.extensions['skills'];
290
+ if (skills === 'all' || (Array.isArray(skills) && skills.every((s) => typeof s === 'string'))) {
291
+ options.skills = skills;
292
+ }
293
+ if (extra.resume !== undefined)
294
+ options.resume = extra.resume;
295
+ // EXTENSIONS KEYS DELIBERATELY NOT MAPPED, so a reviewer reads intent rather
296
+ // than an omission:
297
+ // - `hooks`: `Options.hooks` takes JS callback matchers, not the settings-file
298
+ // JSON shape a bag carries. Different types; a bag `hooks` map cannot be
299
+ // passed through.
300
+ // - `memory`, `background`, `isolation`, `color`, `initialPrompt`: Task-tool
301
+ // subagent-frontmatter concepts with no `Options` equivalent at this SDK
302
+ // version.
303
+ // Unknown extension keys are ignored in silence — `owenloop work lint` is the place
304
+ // that warns about them.
305
+ //
306
+ // OPTIONS DELIBERATELY LEFT UNSET, so nobody "helpfully" adds them:
307
+ // - `settingSources`: omitted means ALL filesystem settings load, matching the
308
+ // CLI's own default and today's behavior. Passing `[]` would silently stop
309
+ // project instruction files from loading.
310
+ // - `strictMcpConfig`: leaving it unset preserves the operator's project/user
311
+ // MCP config, again matching today.
312
+ // - `persistSession`: defaults to `true`. Setting it `false` would make the
313
+ // session unresumable and break the resume-on-rejection phase outright.
314
+ return options;
315
+ }
316
+ /** Module-level, process-wide, keyed by session token. Only reachable from the
317
+ * process that started the session — which is exactly why `stop` is documented
318
+ * as a no-op on a token this process did not start. */
319
+ const SESSIONS = new Map();
320
+ /**
321
+ * Drive the SDK message stream to TURN END and map it onto `AgentEvent`s.
322
+ *
323
+ * Resolves at the `result` message — turn end, per the contract — not at process
324
+ * exit, and regardless of whether the result reports an error.
325
+ *
326
+ * `onInit` fires the instant the session id is known, so `start` can emit
327
+ * `{kind:'started'}` BEFORE it resolves: the caller persists the token on that
328
+ * event, which is what leaves a resumable record behind after a mid-turn crash.
329
+ *
330
+ * PHASE 6, ITEM 1 — EXPORTED, AND TYPED ON `AsyncIterable` RATHER THAN `Query`.
331
+ * This is the one function that maps the SDK's message stream onto this
332
+ * project's `AgentEvent` contract, so it is the only place a recorded transcript
333
+ * can prove the mapping still matches a shipped vendor build without spawning
334
+ * the vendor binary. `Query` is an `AsyncGenerator` PLUS control methods
335
+ * (`interrupt`, `setModel`, …) that this function never calls; asking only for
336
+ * what it uses is what lets a fixture drive it. A live `Query` still satisfies
337
+ * the narrower type, so nothing at the call sites changes.
338
+ */
339
+ export async function consumeTurn(q, onEvent, onInit) {
340
+ let sessionId;
341
+ for await (const message of q) {
342
+ if (message.type === 'system' && message.subtype === 'init') {
343
+ sessionId = message.session_id;
344
+ // The ONLY place these are observable. The live smoke asserts on the
345
+ // `apiKeySource` here (subscription OAuth vs. an API key), and a later
346
+ // phase's version-mismatch warning will want `claude_code_version`.
347
+ const servers = message.mcp_servers.map((s) => `${s.name}=${s.status}`).join(',');
348
+ onEvent({
349
+ kind: 'progress',
350
+ text: `session ${message.session_id}: cliVersion=${message.claude_code_version} ` +
351
+ `model=${message.model} apiKeySource=${message.apiKeySource} ` +
352
+ `permissionMode=${message.permissionMode} cwd=${message.cwd} mcp=[${servers}]`,
353
+ });
354
+ onInit?.(sessionId);
355
+ }
356
+ else if (message.type === 'result') {
357
+ if (message.subtype !== 'success') {
358
+ // The contract's channel for "something went wrong that is not a resume
359
+ // failure". Emitted BEFORE turn_ended so a caller reading events in
360
+ // order sees the cause before the turn closes.
361
+ onEvent({
362
+ kind: 'exited',
363
+ exitCode: null,
364
+ error: message.errors.join('; ') || message.subtype,
365
+ });
366
+ }
367
+ onEvent({ kind: 'turn_ended' });
368
+ return { sessionId, sawResult: true };
369
+ }
370
+ // `needs_input` is NEVER emitted: this SDK path has no blocking-question
371
+ // channel that maps to it, and the contract has no reply channel by design.
372
+ }
373
+ return { sessionId, sawResult: false };
374
+ }
375
+ /** The message text of an unknown thrown value, for an `exited` event. */
376
+ function errText(err) {
377
+ return err instanceof Error ? err.message : String(err);
378
+ }
379
+ async function start(args, onEvent) {
380
+ const env = buildChildEnv(process.env, { allowApiBilling: allowApiBillingFrom(process.env) });
381
+ const abortController = new AbortController();
382
+ const options = buildClaudeOptions(args, { env, abortController, onEvent });
383
+ // A plain STRING prompt, not an AsyncIterable. Knowingly accepted consequence:
384
+ // `Query.interrupt()`, `setPermissionMode()` and `setModel()` are documented as
385
+ // streaming-input-mode only, so `stop()` uses abort + `close()` instead.
386
+ // Streaming input buys this adapter nothing else. Keep the SDK behind this
387
+ // call-site boundary so registry/lint/session commands stay SDK-free.
388
+ const { query } = await import('@anthropic-ai/claude-agent-sdk');
389
+ const q = query({ prompt: args.brief, options });
390
+ let ref;
391
+ let outcome;
392
+ try {
393
+ outcome = await consumeTurn(q, onEvent, (sessionId) => {
394
+ ref = { harness: HARNESS_ID, token: sessionId };
395
+ SESSIONS.set(sessionId, { query: q, abortController, options });
396
+ onEvent({ kind: 'started', ref });
397
+ });
398
+ }
399
+ catch (err) {
400
+ onEvent({ kind: 'exited', exitCode: null, error: errText(err) });
401
+ throw err;
402
+ }
403
+ if (ref === undefined) {
404
+ // No init message means no token. Do NOT invent one — a fabricated token
405
+ // would be persisted as resumable and fail confusingly much later.
406
+ const why = outcome.sawResult
407
+ ? 'the turn ended without a session id'
408
+ : 'the stream ended before a session id arrived';
409
+ onEvent({ kind: 'exited', exitCode: null, error: why });
410
+ throw new Error(`harness start failed: ${why}`);
411
+ }
412
+ return ref;
413
+ }
414
+ async function deliver(ref, message, args, onEvent) {
415
+ // Session lookup is scoped to the PROJECT DIRECTORY, so a deleted worktree can
416
+ // never resume no matter how good the token is. Distinct message on purpose —
417
+ // the caller reads these to tell the two failures apart.
418
+ if (!existsSync(args.cwd)) {
419
+ throw new ResumeUnavailableError(`resume cwd no longer exists: ${args.cwd}`);
420
+ }
421
+ // Deterministic pre-check, rather than parsing a failed query's error text
422
+ // (that string is unverified and can change between releases).
423
+ //
424
+ // KNOWN FALSE NEGATIVE, accepted: this also returns undefined for a session
425
+ // that exists but has no extractable summary, which downgrades a resumable
426
+ // session to a cold replay. The failure direction is a wasted replay — never a
427
+ // hang and never a wrong-session resume — so it is the safe way to be wrong.
428
+ let known = false;
429
+ try {
430
+ const { getSessionInfo } = await import('@anthropic-ai/claude-agent-sdk');
431
+ known = (await getSessionInfo(ref.token, { dir: args.cwd })) !== undefined;
432
+ }
433
+ catch {
434
+ known = false;
435
+ }
436
+ if (!known) {
437
+ throw new ResumeUnavailableError(`provider no longer knows session ${ref.token}`);
438
+ }
439
+ const env = buildChildEnv(process.env, { allowApiBilling: allowApiBillingFrom(process.env) });
440
+ const abortController = new AbortController();
441
+ // PHASE 4: `args` IS THE SOURCE OF TRUTH, not `SESSIONS`.
442
+ //
443
+ // Until Phase 4 this branched on `SESSIONS.get(ref.token)` and, on a miss, built
444
+ // a MINIMAL option set — no permission mode, no tool lists, no model. A resume
445
+ // that happens in a different process from the start (a re-offered step is
446
+ // dispatched as a fresh `owenloop work agent-run` child, so that is the normal case,
447
+ // not the exotic one) therefore ran the resumed turn under weaker permissions
448
+ // than the turn it continued, and stalled headless. `DeliverArgs` now carries
449
+ // the same normalized `StepPermissions` the caller passed to `start`, so the
450
+ // same mapping runs on both paths and the in-process map is no longer consulted
451
+ // for options at all.
452
+ //
453
+ // A resumed turn does not inherit permission mode / tool lists / model from the
454
+ // session — they are per-invocation flags — which is exactly why they must be
455
+ // re-mapped here.
456
+ const options = buildClaudeOptions(args, {
457
+ env,
458
+ abortController,
459
+ onEvent,
460
+ resume: ref.token,
461
+ });
462
+ // `forkSession` is deliberately NOT set: a fork would mint a new session id the
463
+ // caller does not know about, and resume must continue the SAME session.
464
+ const { query } = await import('@anthropic-ai/claude-agent-sdk');
465
+ const q = query({ prompt: message, options });
466
+ SESSIONS.set(ref.token, { query: q, abortController, options });
467
+ try {
468
+ // Never emits `started` — the contract forbids re-emitting it on a resume.
469
+ await consumeTurn(q, onEvent);
470
+ }
471
+ catch (err) {
472
+ const text = errText(err);
473
+ // Belt and braces behind the `getSessionInfo` pre-check.
474
+ if (RESUME_FAILURE_RE.test(text)) {
475
+ throw new ResumeUnavailableError(`provider refused resume of session ${ref.token}: ${text}`);
476
+ }
477
+ onEvent({ kind: 'exited', exitCode: null, error: text });
478
+ throw err;
479
+ }
480
+ }
481
+ async function stop(ref) {
482
+ const session = SESSIONS.get(ref.token);
483
+ // Idempotent by contract: an already-dead session is not an error, and a
484
+ // session started by a previous process is simply not reachable from here.
485
+ if (session === undefined)
486
+ return;
487
+ SESSIONS.delete(ref.token);
488
+ try {
489
+ session.abortController.abort();
490
+ }
491
+ catch {
492
+ // an already-aborted controller is exactly the not-an-error case
493
+ }
494
+ try {
495
+ // Terminates the underlying process and cleans up pending requests, MCP
496
+ // transports and the CLI subprocess. `interrupt()` is not usable here: it is
497
+ // streaming-input-mode only, and this adapter sends a plain string prompt.
498
+ session.query.close();
499
+ }
500
+ catch {
501
+ // a close that throws on an already-exited child is likewise not an error
502
+ }
503
+ }
504
+ /**
505
+ * The singleton. Exported so tests use the object directly rather than through
506
+ * registry state, even though importing this module also registers it.
507
+ */
508
+ // ---------------------------------------------------------------------------
509
+ // Static option-bag check (`owenloop work lint`)
510
+ // ---------------------------------------------------------------------------
511
+ /**
512
+ * The field vocabulary this harness understands inside a step's `x.harness` map.
513
+ * Moved here from the deleted `src/adapters/claude-code.ts`: which option names
514
+ * are legal is vendor knowledge, so it belongs in the vendor's own file and
515
+ * nowhere else.
516
+ *
517
+ * `name` and `description` are RESERVED — owenloop generates the subagent
518
+ * identity, so a def that sets them is overridden silently and is worth an error.
519
+ */
520
+ const RESERVED_KEYS = ['name', 'description'];
521
+ const KNOWN_FIELDS = new Set([
522
+ 'name',
523
+ 'description',
524
+ 'tools',
525
+ 'disallowedTools',
526
+ 'model',
527
+ 'permissionMode',
528
+ 'maxTurns',
529
+ 'skills',
530
+ 'mcpServers',
531
+ 'hooks',
532
+ 'memory',
533
+ 'background',
534
+ 'effort',
535
+ 'isolation',
536
+ 'color',
537
+ 'initialPrompt',
538
+ ]);
539
+ const MEMORY_SCOPES = new Set(['user', 'project', 'local']);
540
+ function typeName(v) {
541
+ if (v === null)
542
+ return 'null';
543
+ if (Array.isArray(v))
544
+ return 'array';
545
+ return typeof v;
546
+ }
547
+ function isStringOrStringArray(v) {
548
+ if (typeof v === 'string')
549
+ return true;
550
+ return Array.isArray(v) && v.every((e) => typeof e === 'string');
551
+ }
552
+ /**
553
+ * Check one step's `x.harness` option map against this harness's vocabulary.
554
+ *
555
+ * `bag` arrives with `id` already stripped by the def parser, so `id` is never
556
+ * reported as an unknown field. Unknown fields are WARNINGS (a def may be written
557
+ * against a newer CLI than this owenloop build); wrong types and reserved keys
558
+ * are ERRORS. Never throws — a malformed bag produces findings.
559
+ */
560
+ function lintStep(bag, step) {
561
+ const findings = [];
562
+ const err = (message, field) => {
563
+ findings.push({ severity: 'error', step, message, ...(field !== undefined ? { field } : {}) });
564
+ };
565
+ const warn = (message, field) => {
566
+ findings.push({ severity: 'warning', step, message, ...(field !== undefined ? { field } : {}) });
567
+ };
568
+ for (const key of RESERVED_KEYS) {
569
+ if (key in bag)
570
+ err(`'${key}' is generated and cannot be set in the bag`, key);
571
+ }
572
+ for (const key of Object.keys(bag)) {
573
+ if (!KNOWN_FIELDS.has(key)) {
574
+ warn(`unknown field '${key}' — known fields: ${[...KNOWN_FIELDS].join(', ')}`, key);
575
+ }
576
+ }
577
+ const check = (field, ok, expected) => {
578
+ if (field in bag && !ok(bag[field])) {
579
+ err(`${field} must be ${expected}, got ${typeName(bag[field])}`, field);
580
+ }
581
+ };
582
+ check('tools', isStringOrStringArray, 'a string or string[]');
583
+ check('disallowedTools', isStringOrStringArray, 'a string or string[]');
584
+ check('model', (v) => typeof v === 'string', 'a string');
585
+ check('effort', (v) => typeof v === 'string', 'a string');
586
+ check('skills', (v) => Array.isArray(v) && v.every((e) => typeof e === 'string'), 'a string[]');
587
+ check('background', (v) => typeof v === 'boolean', 'a boolean');
588
+ check('mcpServers', isPlainMap, 'a map');
589
+ check('hooks', isPlainMap, 'a map');
590
+ check('maxTurns', (v) => typeof v === 'number' && Number.isInteger(v) && v > 0, 'a positive integer');
591
+ if ('permissionMode' in bag && !PERMISSION_MODES.includes(bag['permissionMode'])) {
592
+ err(`permissionMode must be one of ${PERMISSION_MODES.join('|')}`, 'permissionMode');
593
+ }
594
+ if ('memory' in bag && !MEMORY_SCOPES.has(bag['memory'])) {
595
+ err(`memory must be one of ${[...MEMORY_SCOPES].join('|')}`, 'memory');
596
+ }
597
+ if (isPlainMap(bag['mcpServers']) && 'owenloop' in bag['mcpServers']) {
598
+ warn('mcpServers.owenloop is reserved and is replaced by the worker at start', 'mcpServers');
599
+ }
600
+ return findings;
601
+ }
602
+ /**
603
+ * The command a human runs to re-open this session in an interactive terminal.
604
+ *
605
+ * WHY IT RESOLVES THE BINARY RATHER THAN PRINTING A BARE NAME. An operator who
606
+ * set `OWENLOOP_CLAUDE_BIN` did so because the plain name does not run on their
607
+ * machine, and a listing that prints a command they cannot paste is worse than
608
+ * printing nothing. `resolveExecutable` returns `undefined` when neither the
609
+ * override nor a `PATH` hit exists; the bare CLI name is the honest fallback
610
+ * there, since the SDK's own bundled executable has no stable path to name.
611
+ *
612
+ * It reads `process.env` and not the child environment: this is a command for
613
+ * the OPERATOR's shell, not for a harness child.
614
+ */
615
+ function resumeCommand(ref) {
616
+ return {
617
+ command: resolveExecutable(process.env) ?? 'claude',
618
+ args: ['--resume', ref.token],
619
+ };
620
+ }
621
+ export const claudeAdapter = {
622
+ id: HARNESS_ID,
623
+ // The provider stores the session and resumes it from the opaque token this
624
+ // adapter puts in `HarnessSessionRef.token`.
625
+ resumeTier: 'native-token',
626
+ start,
627
+ deliver,
628
+ stop,
629
+ lintStep,
630
+ resumeCommand,
631
+ };
632
+ // Self-registration at import time: importing this module is what puts the
633
+ // adapter in the runtime registry. WHO imports it is a composition root's
634
+ // decision (`src/roles/agent-run.ts`, `src/roles/lint.ts`), not this module's.
635
+ register(claudeAdapter);