@eloxiv/daemon 0.0.0-stage → 0.1.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 (114) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +6 -2
  3. package/dist/Acp.d.ts +8 -0
  4. package/dist/Acp.d.ts.map +1 -0
  5. package/dist/Acp.js +268 -0
  6. package/dist/Acp.js.map +1 -0
  7. package/dist/Canonical.d.ts +3 -0
  8. package/dist/Canonical.d.ts.map +1 -0
  9. package/dist/Canonical.js +12 -0
  10. package/dist/Canonical.js.map +1 -0
  11. package/dist/Client.d.ts +100 -0
  12. package/dist/Client.d.ts.map +1 -0
  13. package/dist/Client.js +474 -0
  14. package/dist/Client.js.map +1 -0
  15. package/dist/Commands.d.ts +85 -0
  16. package/dist/Commands.d.ts.map +1 -0
  17. package/dist/Commands.js +370 -0
  18. package/dist/Commands.js.map +1 -0
  19. package/dist/Config.d.ts +74 -0
  20. package/dist/Config.d.ts.map +1 -0
  21. package/dist/Config.js +126 -0
  22. package/dist/Config.js.map +1 -0
  23. package/dist/Daemon.d.ts +243 -0
  24. package/dist/Daemon.d.ts.map +1 -0
  25. package/dist/Daemon.js +965 -0
  26. package/dist/Daemon.js.map +1 -0
  27. package/dist/Harness.d.ts +133 -0
  28. package/dist/Harness.d.ts.map +1 -0
  29. package/dist/Harness.js +734 -0
  30. package/dist/Harness.js.map +1 -0
  31. package/dist/Http.d.ts +15 -0
  32. package/dist/Http.d.ts.map +1 -0
  33. package/dist/Http.js +548 -0
  34. package/dist/Http.js.map +1 -0
  35. package/dist/KernelLink.d.ts +145 -0
  36. package/dist/KernelLink.d.ts.map +1 -0
  37. package/dist/KernelLink.js +109 -0
  38. package/dist/KernelLink.js.map +1 -0
  39. package/dist/LocalAuth.d.ts +99 -0
  40. package/dist/LocalAuth.d.ts.map +1 -0
  41. package/dist/LocalAuth.js +225 -0
  42. package/dist/LocalAuth.js.map +1 -0
  43. package/dist/Main.d.ts +51 -0
  44. package/dist/Main.d.ts.map +1 -0
  45. package/dist/Main.js +219 -0
  46. package/dist/Main.js.map +1 -0
  47. package/dist/Secrets.d.ts +21 -0
  48. package/dist/Secrets.d.ts.map +1 -0
  49. package/dist/Secrets.js +204 -0
  50. package/dist/Secrets.js.map +1 -0
  51. package/dist/SecureUrl.d.ts +11 -0
  52. package/dist/SecureUrl.d.ts.map +1 -0
  53. package/dist/SecureUrl.js +23 -0
  54. package/dist/SecureUrl.js.map +1 -0
  55. package/dist/State.d.ts +77 -0
  56. package/dist/State.d.ts.map +1 -0
  57. package/dist/State.js +38 -0
  58. package/dist/State.js.map +1 -0
  59. package/dist/Terminals.d.ts +49 -0
  60. package/dist/Terminals.d.ts.map +1 -0
  61. package/dist/Terminals.js +203 -0
  62. package/dist/Terminals.js.map +1 -0
  63. package/dist/bin-node.d.ts +2 -0
  64. package/dist/bin-node.d.ts.map +1 -0
  65. package/dist/bin-node.js +4 -0
  66. package/dist/bin-node.js.map +1 -0
  67. package/dist/bin.d.ts +2 -0
  68. package/dist/bin.d.ts.map +1 -0
  69. package/dist/bin.js +4 -0
  70. package/dist/bin.js.map +1 -0
  71. package/dist/index.d.ts +17 -0
  72. package/dist/index.d.ts.map +1 -0
  73. package/dist/index.js +17 -0
  74. package/dist/index.js.map +1 -0
  75. package/dist/runtime/bun.d.ts +11 -0
  76. package/dist/runtime/bun.d.ts.map +1 -0
  77. package/dist/runtime/bun.js +20 -0
  78. package/dist/runtime/bun.js.map +1 -0
  79. package/dist/runtime/node.d.ts +11 -0
  80. package/dist/runtime/node.d.ts.map +1 -0
  81. package/dist/runtime/node.js +21 -0
  82. package/dist/runtime/node.js.map +1 -0
  83. package/dist/testing.d.ts +25 -0
  84. package/dist/testing.d.ts.map +1 -0
  85. package/dist/testing.js +27 -0
  86. package/dist/testing.js.map +1 -0
  87. package/fixtures/claude-code-env-vars.txt +409 -0
  88. package/fixtures/fake-acp-agent.mjs +222 -0
  89. package/fixtures/fake-harness.mjs +299 -0
  90. package/fixtures/recorded/claude-code.jsonl +7 -0
  91. package/fixtures/recorded/codex.jsonl +6 -0
  92. package/package.json +64 -3
  93. package/scripts/build-sidecar.ts +86 -0
  94. package/src/Acp.ts +292 -0
  95. package/src/Canonical.ts +9 -0
  96. package/src/Client.ts +585 -0
  97. package/src/Commands.ts +427 -0
  98. package/src/Config.ts +179 -0
  99. package/src/Daemon.ts +1092 -0
  100. package/src/Harness.ts +839 -0
  101. package/src/Http.ts +563 -0
  102. package/src/KernelLink.ts +197 -0
  103. package/src/LocalAuth.ts +301 -0
  104. package/src/Main.ts +281 -0
  105. package/src/Secrets.ts +226 -0
  106. package/src/SecureUrl.ts +21 -0
  107. package/src/State.ts +109 -0
  108. package/src/Terminals.ts +227 -0
  109. package/src/bin-node.ts +4 -0
  110. package/src/bin.ts +4 -0
  111. package/src/index.ts +16 -0
  112. package/src/runtime/bun.ts +29 -0
  113. package/src/runtime/node.ts +30 -0
  114. package/src/testing.ts +43 -0
package/src/Harness.ts ADDED
@@ -0,0 +1,839 @@
1
+ /**
2
+ * Local agent harnesses on the person's own subscriptions: Claude Code (`claude -p`, stream-json) and Codex
3
+ * (`codex exec --json`). Each adapter runs one turn (a prompt, the Eloxiv actions as MCP tools through the
4
+ * daemon's relay, a working directory), streams normalised events, honours cancellation and a time limit,
5
+ * reports token usage when the CLI does, and detects whether the CLI is installed and signed in.
6
+ *
7
+ * The CLIs keep their own sign-in (in the person's home directory); the daemon never reads it and never sends
8
+ * anything of it to the kernel: only the normalised events below leave the machine. The harness gets a token
9
+ * for the daemon's loopback MCP endpoint that is valid for this turn only, never the device credential or the
10
+ * kernel's agent session, and an environment of named variables only (`harnessEnv`): what a CLI needs to run and find
11
+ * its own sign-in, never the daemon's secrets or anything else the daemon's environment happens to hold (API keys,
12
+ * cloud credentials, tokens).
13
+ */
14
+ import type { HarnessEvent, HarnessKind, HarnessStatus, TurnUsage } from "@eloxiv/contracts"
15
+ import { spawn } from "node:child_process"
16
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"
17
+ import { tmpdir } from "node:os"
18
+ import { join } from "node:path"
19
+
20
+ /** How to start a harness: the command (binary and leading arguments) and extra environment. */
21
+ export interface HarnessConfig {
22
+ readonly kind: HarnessKind
23
+ readonly command: ReadonlyArray<string>
24
+ readonly env?: Readonly<Record<string, string>> | undefined
25
+ /** Extra arguments placed before the prompt (for example a permission mode). */
26
+ readonly extraArgs?: ReadonlyArray<string> | undefined
27
+ /**
28
+ * More variables of the daemon's environment to pass to the CLI, by name (`ELOXIV_DAEMON_HARNESS_PASS_ENV`), for
29
+ * a person who points their CLI somewhere on purpose (a gateway's address, say). Off by default: a variable that
30
+ * holds a key or token (`ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, ...) would bill the turn to that key instead of the
31
+ * person's subscription, and a turn with workspace tools could read it. The daemon's own (`ELOXIV_*`) and a parent
32
+ * Claude Code session's variables are never passed, named or not.
33
+ */
34
+ readonly passEnv?: ReadonlyArray<string> | undefined
35
+ /** The harness speaks the Agent Client Protocol (`Acp.ts`) rather than a CLI's JSON stream. */
36
+ readonly protocol?: "acp" | undefined
37
+ /**
38
+ * An ACP agent can be limited to the Eloxiv tools (OpenCode by its permissions; a configured agent when the person
39
+ * says so). Without it the agent runs only turns that ask for workspace tools.
40
+ */
41
+ readonly toolsOnly?: boolean | undefined
42
+ }
43
+
44
+ export interface HarnessRunInput {
45
+ readonly prompt: string
46
+ readonly cwd: string
47
+ readonly model: string | null
48
+ readonly timeoutMs: number
49
+ /** The daemon's loopback MCP endpoint and this turn's token for it. */
50
+ readonly mcp: { readonly url: string; readonly token: string }
51
+ readonly signal?: AbortSignal | undefined
52
+ readonly onEvent?: ((event: HarnessEvent) => void) | undefined
53
+ /** Every raw line the CLI printed (for recording fixtures; never sent anywhere by the daemon). */
54
+ readonly onRawLine?: ((line: string) => void) | undefined
55
+ /**
56
+ * Where the turn's private files (Claude Code's MCP config) go: a directory the caller cleans up even when
57
+ * this process is killed mid-turn (the daemon uses `<state dir>/turns`, emptied at start-up). Default: tmpdir.
58
+ */
59
+ readonly scratchRoot?: string | undefined
60
+ /**
61
+ * Give the harness its built-in file and shell tools (Claude Code's Bash, Read, Edit, Write, Glob, Grep;
62
+ * Codex's shell in a workspace-write sandbox). Off by default: the harness then has only the Eloxiv tools.
63
+ */
64
+ readonly workspaceTools?: boolean | undefined
65
+ /** Keep the harness's session on disk so a later turn can resume it (default: the CLI keeps nothing). */
66
+ readonly resumable?: boolean | undefined
67
+ /** Resume this harness session (one a resumable turn kept, in the same working directory). */
68
+ readonly resume?: string | null | undefined
69
+ }
70
+
71
+ export interface HarnessResult {
72
+ readonly outcome: "succeeded" | "failed" | "cancelled" | "timed-out"
73
+ readonly result: string | null
74
+ readonly usage: TurnUsage | null
75
+ readonly error: string | null
76
+ readonly events: ReadonlyArray<HarnessEvent>
77
+ /** The harness's own session (Claude Code) or thread (Codex) id. */
78
+ readonly sessionId: string | null
79
+ }
80
+
81
+ /** What a stream parser accumulates while it reads a CLI's output. */
82
+ export interface StreamState {
83
+ sessionId: string | null
84
+ texts: Array<string>
85
+ result: string | null
86
+ usage: TurnUsage | null
87
+ error: string | null
88
+ finished: boolean
89
+ succeeded: boolean
90
+ /** Claude Code's tool calls by id: only the Eloxiv tools' results are forwarded. */
91
+ tools: Map<string, string>
92
+ }
93
+
94
+ export const newStreamState = (): StreamState => ({
95
+ tools: new Map(),
96
+ sessionId: null,
97
+ texts: [],
98
+ result: null,
99
+ usage: null,
100
+ error: null,
101
+ finished: false,
102
+ succeeded: false,
103
+ })
104
+
105
+ /** The MCP server name the harnesses see the Eloxiv tools under (Claude Code names them `mcp__eloxiv__<tool>`). */
106
+ export const MCP_SERVER = "eloxiv"
107
+
108
+ const object = (value: unknown): Record<string, unknown> | undefined =>
109
+ typeof value === "object" && value !== null && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined
110
+ const num = (value: unknown) => (typeof value === "number" && Number.isFinite(value) ? value : 0)
111
+ const str = (value: unknown) => (typeof value === "string" ? value : null)
112
+ const textOr = (value: unknown, fallback: string) => (typeof value === "string" ? value : fallback)
113
+
114
+ /** Text of an MCP or Anthropic content value: a string, or the text parts of a content array. */
115
+ const contentText = (content: unknown): string => {
116
+ if (typeof content === "string") return content
117
+ if (Array.isArray(content)) {
118
+ return content.map((part) => (object(part)?.["type"] === "text" ? textOr(object(part)?.["text"], "") : "")).join("")
119
+ }
120
+ const record = object(content)
121
+ if (record !== undefined && Array.isArray(record["content"])) return contentText(record["content"])
122
+ return content === undefined || content === null ? "" : JSON.stringify(content)
123
+ }
124
+
125
+ /** What is forwarded instead of a built-in tool's output (files, command output): never the content. */
126
+ export const NOT_FORWARDED = "[output of a built-in tool: not forwarded]"
127
+
128
+ const clip = (text: string, limit = 4000) => (text.length > limit ? `${text.slice(0, limit)}…` : text)
129
+
130
+ /**
131
+ * Claude Code's `--output-format stream-json` (with `--verbose`): `system/init`, `assistant` messages (text and
132
+ * `tool_use` blocks), `user` messages carrying `tool_result` blocks, and a final `result` with the answer,
133
+ * usage and cost.
134
+ */
135
+ export const parseClaudeLine = (line: string, state: StreamState): ReadonlyArray<HarnessEvent> => {
136
+ let message: Record<string, unknown> | undefined
137
+ try {
138
+ message = object(JSON.parse(line))
139
+ } catch {
140
+ return []
141
+ }
142
+ if (message === undefined) return []
143
+ const events: Array<HarnessEvent> = []
144
+ switch (message["type"]) {
145
+ case "system": {
146
+ if (message["subtype"] !== "init") return []
147
+ state.sessionId = str(message["session_id"])
148
+ const servers = Array.isArray(message["mcp_servers"]) ? message["mcp_servers"] : []
149
+ events.push({
150
+ type: "started",
151
+ data: {
152
+ harness: "claude-code",
153
+ sessionId: state.sessionId,
154
+ model: str(message["model"]),
155
+ mcp: servers.map((server) => ({
156
+ name: str(object(server)?.["name"]),
157
+ status: str(object(server)?.["status"]),
158
+ })),
159
+ },
160
+ })
161
+ return events
162
+ }
163
+ case "assistant": {
164
+ const content = object(message["message"])?.["content"]
165
+ for (const block of Array.isArray(content) ? content : []) {
166
+ const part = object(block)
167
+ if (part?.["type"] === "text" && typeof part["text"] === "string" && part["text"].length > 0) {
168
+ state.texts.push(part["text"])
169
+ events.push({ type: "text", data: { text: part["text"] } })
170
+ } else if (part?.["type"] === "tool_use") {
171
+ const id = str(part["id"])
172
+ if (id !== null) state.tools.set(id, str(part["name"]) ?? "")
173
+ events.push({
174
+ type: "tool-call",
175
+ data: { id: str(part["id"]), name: str(part["name"]), input: part["input"] ?? null },
176
+ })
177
+ }
178
+ }
179
+ return events
180
+ }
181
+ case "user": {
182
+ const content = object(message["message"])?.["content"]
183
+ for (const block of Array.isArray(content) ? content : []) {
184
+ const part = object(block)
185
+ if (part?.["type"] !== "tool_result") continue
186
+ const id = str(part["tool_use_id"])
187
+ const eloxiv = (state.tools.get(id ?? "") ?? "").startsWith(`mcp__${MCP_SERVER}__`)
188
+ events.push({
189
+ type: "tool-result",
190
+ data: {
191
+ id,
192
+ isError: part["is_error"] === true,
193
+ // A built-in tool's output (a file, a command's output) stays on the machine.
194
+ output: eloxiv ? clip(contentText(part["content"])) : NOT_FORWARDED,
195
+ },
196
+ })
197
+ }
198
+ return events
199
+ }
200
+ case "result": {
201
+ const usage = object(message["usage"])
202
+ if (usage !== undefined) {
203
+ const cached = num(usage["cache_read_input_tokens"])
204
+ state.usage = {
205
+ inputTokens: num(usage["input_tokens"]) + num(usage["cache_creation_input_tokens"]) + cached,
206
+ outputTokens: num(usage["output_tokens"]),
207
+ cachedInputTokens: cached,
208
+ costUsd: typeof message["total_cost_usd"] === "number" ? message["total_cost_usd"] : null,
209
+ }
210
+ events.push({ type: "usage", data: state.usage })
211
+ }
212
+ state.finished = true
213
+ state.succeeded = message["subtype"] === "success" && message["is_error"] !== true
214
+ state.result = str(message["result"]) ?? (state.texts.length > 0 ? state.texts.join("\n") : null)
215
+ if (!state.succeeded) {
216
+ state.error = str(message["result"]) ?? `Claude Code ended with ${String(message["subtype"])}`
217
+ events.push({ type: "error", data: { message: state.error } })
218
+ }
219
+ events.push({ type: "finished", data: { succeeded: state.succeeded } })
220
+ return events
221
+ }
222
+ default:
223
+ return []
224
+ }
225
+ }
226
+
227
+ /**
228
+ * Codex's `exec --json` events: `thread.started`, `turn.started`, `item.started` / `item.completed` (an
229
+ * `agent_message`, an `mcp_tool_call`, a `command_execution`, ...), `turn.completed` with usage, `turn.failed`
230
+ * and `error`.
231
+ */
232
+ export const parseCodexLine = (line: string, state: StreamState): ReadonlyArray<HarnessEvent> => {
233
+ let message: Record<string, unknown> | undefined
234
+ try {
235
+ message = object(JSON.parse(line))
236
+ } catch {
237
+ return []
238
+ }
239
+ if (message === undefined) return []
240
+ const item = object(message["item"])
241
+ switch (message["type"]) {
242
+ case "thread.started":
243
+ state.sessionId = str(message["thread_id"])
244
+ return [{ type: "started", data: { harness: "codex", sessionId: state.sessionId } }]
245
+ case "item.started":
246
+ if (item?.["type"] === "mcp_tool_call") {
247
+ return [
248
+ {
249
+ type: "tool-call",
250
+ data: {
251
+ id: str(item["id"]),
252
+ name: `${str(item["server"])}.${str(item["tool"])}`,
253
+ input: item["arguments"] ?? null,
254
+ },
255
+ },
256
+ ]
257
+ }
258
+ if (item?.["type"] === "command_execution") {
259
+ return [
260
+ { type: "tool-call", data: { id: str(item["id"]), name: "shell", input: { command: str(item["command"]) } } },
261
+ ]
262
+ }
263
+ return []
264
+ case "item.completed": {
265
+ if (item?.["type"] === "agent_message" && typeof item["text"] === "string") {
266
+ state.texts.push(item["text"])
267
+ return [{ type: "text", data: { text: item["text"] } }]
268
+ }
269
+ if (item?.["type"] === "mcp_tool_call") {
270
+ const error = object(item["error"])
271
+ return [
272
+ {
273
+ type: "tool-result",
274
+ data: {
275
+ id: str(item["id"]),
276
+ isError: error !== undefined || item["status"] === "failed",
277
+ output: clip(error !== undefined ? textOr(error["message"], "") : contentText(item["result"])),
278
+ },
279
+ },
280
+ ]
281
+ }
282
+ if (item?.["type"] === "command_execution") {
283
+ // A command's output stays on the machine.
284
+ return [
285
+ {
286
+ type: "tool-result",
287
+ data: { id: str(item["id"]), isError: num(item["exit_code"]) !== 0, output: NOT_FORWARDED },
288
+ },
289
+ ]
290
+ }
291
+ return []
292
+ }
293
+ case "turn.completed": {
294
+ const usage = object(message["usage"])
295
+ state.usage = {
296
+ inputTokens: num(usage?.["input_tokens"]),
297
+ outputTokens: num(usage?.["output_tokens"]),
298
+ cachedInputTokens: usage?.["cached_input_tokens"] === undefined ? null : num(usage["cached_input_tokens"]),
299
+ costUsd: null,
300
+ }
301
+ state.finished = true
302
+ state.succeeded = true
303
+ state.result = state.texts.length > 0 ? state.texts[state.texts.length - 1]! : null
304
+ return [
305
+ { type: "usage", data: state.usage },
306
+ { type: "finished", data: { succeeded: true } },
307
+ ]
308
+ }
309
+ case "turn.failed": {
310
+ state.finished = true
311
+ state.succeeded = false
312
+ state.error = textOr(object(message["error"])?.["message"], "Codex turn failed")
313
+ return [
314
+ { type: "error", data: { message: state.error } },
315
+ { type: "finished", data: { succeeded: false } },
316
+ ]
317
+ }
318
+ case "error": {
319
+ state.error = textOr(message["message"], "Codex reported an error")
320
+ return [{ type: "error", data: { message: state.error } }]
321
+ }
322
+ default:
323
+ return []
324
+ }
325
+ }
326
+
327
+ export const parserFor = (kind: HarnessKind) => (kind === "claude-code" ? parseClaudeLine : parseCodexLine)
328
+
329
+ /** Claude Code's built-in tools a turn with workspace tools gets. */
330
+ export const WORKSPACE_TOOLS: ReadonlyArray<string> = ["Bash", "Read", "Edit", "Write", "Glob", "Grep"]
331
+
332
+ /** The env var Codex reads the MCP bearer token from (named in its config, so the token is never in argv). */
333
+ export const CODEX_TOKEN_ENV = "ELOXIV_MCP_TOKEN"
334
+
335
+ /** The arguments of one turn, and any file they reference (removed after the turn). */
336
+ export const harnessArgs = (
337
+ config: HarnessConfig,
338
+ input: Pick<HarnessRunInput, "prompt" | "cwd" | "model" | "mcp" | "workspaceTools" | "resumable" | "resume">,
339
+ scratch: string,
340
+ ): { readonly args: ReadonlyArray<string>; readonly env: Record<string, string> } => {
341
+ const resume = input.resume === null || input.resume === undefined ? undefined : input.resume
342
+ const keep = input.resumable === true || resume !== undefined
343
+ if (config.kind === "claude-code") {
344
+ // The MCP config holds the turn's loopback token: a 0600 file in a private directory, not argv.
345
+ const mcpConfig = join(scratch, "mcp.json")
346
+ writeFileSync(
347
+ mcpConfig,
348
+ JSON.stringify({
349
+ mcpServers: {
350
+ [MCP_SERVER]: { type: "http", url: input.mcp.url, headers: { authorization: `Bearer ${input.mcp.token}` } },
351
+ },
352
+ }),
353
+ { mode: 0o600 },
354
+ )
355
+ return {
356
+ args: [
357
+ "-p",
358
+ "--output-format",
359
+ "stream-json",
360
+ "--verbose",
361
+ "--mcp-config",
362
+ mcpConfig,
363
+ "--strict-mcp-config",
364
+ // Only what the turn needs: no built-in tools unless it asked for workspace tools, and none of the
365
+ // person's user or project settings (hooks, plugins, permissions).
366
+ "--tools",
367
+ input.workspaceTools === true ? WORKSPACE_TOOLS.join(",") : "",
368
+ "--setting-sources",
369
+ "",
370
+ "--allowedTools",
371
+ [`mcp__${MCP_SERVER}`, ...(input.workspaceTools === true ? WORKSPACE_TOOLS : [])].join(","),
372
+ // Nothing is kept unless the turn is resumable (or resumes a session, which it then continues).
373
+ ...(keep ? [] : ["--no-session-persistence"]),
374
+ ...(resume === undefined ? [] : ["--resume", resume]),
375
+ ...(input.model === null ? [] : ["--model", input.model]),
376
+ ...(config.extraArgs ?? []),
377
+ "--",
378
+ input.prompt,
379
+ ],
380
+ env: {},
381
+ }
382
+ }
383
+ // `codex exec resume` takes neither `--sandbox` nor `-C`: the sandbox is a config value, and the session's
384
+ // working directory is the process's (the same one the session started in).
385
+ const sandbox = input.workspaceTools === true ? "workspace-write" : "read-only"
386
+ return {
387
+ args: [
388
+ "exec",
389
+ ...(resume === undefined ? [] : ["resume"]),
390
+ "--json",
391
+ "--skip-git-repo-check",
392
+ // The person's sign-in (CODEX_HOME's auth) still applies; their config's other MCP servers do not.
393
+ "--ignore-user-config",
394
+ ...(keep ? [] : ["--ephemeral"]),
395
+ ...(resume === undefined ? ["--sandbox", sandbox] : ["-c", `sandbox_mode=${JSON.stringify(sandbox)}`]),
396
+ ...(input.workspaceTools === true ? [] : ["--disable", "shell_tool"]),
397
+ ...(resume === undefined ? ["-C", input.cwd] : []),
398
+ "-c",
399
+ `mcp_servers.${MCP_SERVER}.url=${JSON.stringify(input.mcp.url)}`,
400
+ "-c",
401
+ `mcp_servers.${MCP_SERVER}.bearer_token_env_var=${JSON.stringify(CODEX_TOKEN_ENV)}`,
402
+ "-c",
403
+ `mcp_servers.${MCP_SERVER}.default_tools_approval_mode="approve"`,
404
+ "-c",
405
+ 'approval_policy="never"',
406
+ ...(input.model === null ? [] : ["-m", input.model]),
407
+ ...(config.extraArgs ?? []),
408
+ "--",
409
+ ...(resume === undefined ? [] : [resume]),
410
+ input.prompt,
411
+ ],
412
+ env: { [CODEX_TOKEN_ENV]: input.mcp.token },
413
+ }
414
+ }
415
+
416
+ /**
417
+ * Variables that mark a running Claude Code or Codex session (when the daemon itself was started from one) and its
418
+ * private messaging channel: a harness turn is a session of its own, never a child of the daemon's parent.
419
+ */
420
+ const SESSION_VARIABLES = new Set([
421
+ "CLAUDECODE",
422
+ "CLAUDE_CODE_ENTRYPOINT",
423
+ "CLAUDE_CODE_SESSION_ID",
424
+ "CLAUDE_CODE_CHILD_SESSION",
425
+ "CLAUDE_CODE_SESSION_ATTENDED",
426
+ "CLAUDE_CODE_MESSAGING_SOCKET",
427
+ "CLAUDE_CODE_MESSAGING_TOKEN",
428
+ "CLAUDE_CODE_BRIDGE_SESSION_ID",
429
+ "CLAUDE_CODE_REMOTE_SESSION_ID",
430
+ "CLAUDE_PID",
431
+ "CODEX_SESSION_ID",
432
+ "CODEX_TOOL_CALL_ID",
433
+ ])
434
+
435
+ /**
436
+ * What a CLI may see of the daemon's environment, by name (compared case-insensitively, as Windows does). The
437
+ * system's: where the person's home, configuration and temporary files are, the locale, the terminal, the user
438
+ * session's bus (a keyring), the SSH agent and GnuPG (git over SSH, signed commits), the editor; the network's proxy
439
+ * and certificate authorities; Windows' system variables. And the CLIs' own documented settings (Claude Code's
440
+ * https://code.claude.com/docs/en/env-vars, its network configuration with mTLS, Codex's `CODEX_HOME` and
441
+ * `CODEX_CA_CERTIFICATE`): the names below, and those under `HARNESS_ENV_PREFIXES`, less what `HARNESS_ENV_DENIED`
442
+ * refuses. `packages/daemon/test/harness.test.ts` checks every variable those documents name.
443
+ */
444
+ const HARNESS_ENV = new Set(
445
+ [
446
+ // The system.
447
+ "PATH",
448
+ "HOME",
449
+ "USER",
450
+ "LOGNAME",
451
+ "SHELL",
452
+ "LANG",
453
+ "LANGUAGE",
454
+ "TZ",
455
+ "TERM",
456
+ "COLORTERM",
457
+ "NO_COLOR",
458
+ "TMPDIR",
459
+ "TMP",
460
+ "TEMP",
461
+ "DBUS_SESSION_BUS_ADDRESS",
462
+ "SSH_AUTH_SOCK",
463
+ "SSH_AGENT_PID",
464
+ "GPG_TTY",
465
+ "GNUPGHOME",
466
+ "EDITOR",
467
+ "VISUAL",
468
+ "PAGER",
469
+ // The network: proxies and certificate authorities.
470
+ "HTTP_PROXY",
471
+ "HTTPS_PROXY",
472
+ "NO_PROXY",
473
+ "ALL_PROXY",
474
+ "NODE_EXTRA_CA_CERTS",
475
+ "NODE_TLS_REJECT_UNAUTHORIZED",
476
+ "SSL_CERT_FILE",
477
+ "SSL_CERT_DIR",
478
+ "REQUESTS_CA_BUNDLE",
479
+ "CURL_CA_BUNDLE",
480
+ // Claude Code's documented settings without a prefix of their own.
481
+ "DEBUG",
482
+ "DO_NOT_TRACK",
483
+ "IS_DEMO",
484
+ "CCR_FORCE_BUNDLE",
485
+ "PIP_INDEX_URL",
486
+ "SLASH_COMMAND_TOOL_CHAR_BUDGET",
487
+ "TASK_MAX_OUTPUT_LENGTH",
488
+ "USE_BUILTIN_RIPGREP",
489
+ "BETA_TRACING_ENDPOINT",
490
+ // Codex's logging.
491
+ "RUST_LOG",
492
+ // Windows.
493
+ "SYSTEMROOT",
494
+ "WINDIR",
495
+ "SYSTEMDRIVE",
496
+ "USERPROFILE",
497
+ "USERNAME",
498
+ "USERDOMAIN",
499
+ "HOMEDRIVE",
500
+ "HOMEPATH",
501
+ "APPDATA",
502
+ "LOCALAPPDATA",
503
+ "PROGRAMDATA",
504
+ "ALLUSERSPROFILE",
505
+ "PUBLIC",
506
+ "PROGRAMFILES",
507
+ "PROGRAMFILES(X86)",
508
+ "PROGRAMW6432",
509
+ "COMMONPROGRAMFILES",
510
+ "COMMONPROGRAMFILES(X86)",
511
+ "COMMONPROGRAMW6432",
512
+ "COMSPEC",
513
+ "PATHEXT",
514
+ "PSMODULEPATH",
515
+ "COMPUTERNAME",
516
+ "OS",
517
+ "PROCESSOR_ARCHITECTURE",
518
+ "NUMBER_OF_PROCESSORS",
519
+ ].map((name) => name.toUpperCase()),
520
+ )
521
+
522
+ /**
523
+ * Prefixes of passed variables: the locale (`LC_*`), XDG's directories, git's own (`GIT_SSH_COMMAND`, `GIT_CONFIG_*`,
524
+ * `GIT_SSL_CAINFO`), and the CLIs' documented settings (`CLAUDE_*`, `ANTHROPIC_*` model and request settings, `CODEX_*`,
525
+ * and the families Claude Code documents: `DISABLE_*`, `ENABLE_*`, `FORCE_*`, `MAX_*`, `MCP_*`, `OTEL_*`, `BASH_*`, `API_*`,
526
+ * `VERTEX_REGION_*`).
527
+ */
528
+ const HARNESS_ENV_PREFIXES = [
529
+ "LC_",
530
+ "XDG_",
531
+ "GIT_",
532
+ "CLAUDE_",
533
+ "ANTHROPIC_",
534
+ "CODEX_",
535
+ "DISABLE_",
536
+ "ENABLE_",
537
+ "FORCE_",
538
+ "MAX_",
539
+ "MCP_",
540
+ "OTEL_",
541
+ "BASH_",
542
+ "API_",
543
+ "VERTEX_REGION_",
544
+ ]
545
+
546
+ /** Settings whose names look like a credential's but are not one. */
547
+ const NOT_CREDENTIALS = new Set(["CLAUDE_CODE_API_KEY_HELPER_TTL_MS", "CLAUDE_CODE_OAUTH_SCOPES"])
548
+
549
+ /**
550
+ * Never passed unless named in `passEnv`, though they match the above:
551
+ * - **credentials**: API keys, auth, access, refresh, OAuth and bearer tokens, secrets and passwords
552
+ * (`ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`, `CLAUDE_CODE_OAUTH_TOKEN`, `CODEX_ACCESS_TOKEN`, `GIT_TOKEN`, ...),
553
+ * and request headers, which carry them (`ANTHROPIC_CUSTOM_HEADERS`, `OTEL_EXPORTER_OTLP_HEADERS`): a turn would be
554
+ * billed to a key instead of the person's subscription, and one with workspace tools could read it;
555
+ * - **another provider**: a base URL (`ANTHROPIC_BASE_URL`, `ANTHROPIC_*_BASE_URL`, `OPENAI_BASE_URL`), a cloud
556
+ * provider's switch (`CLAUDE_CODE_USE_BEDROCK`, `_VERTEX`, `_FOUNDRY`, `_MANTLE`, `_ANTHROPIC_AWS`), skipping a
557
+ * provider's sign-in (`CLAUDE_CODE_SKIP_*_AUTH`), or a provider's resource: they take the turn off the person's
558
+ * subscription.
559
+ *
560
+ * Deliberately passed although it is a secret: `CLAUDE_CODE_CLIENT_KEY_PASSPHRASE`, which unlocks the mTLS client key
561
+ * `CLAUDE_CODE_CLIENT_KEY` names. A network that requires mutual TLS refuses the CLI without it; it identifies the
562
+ * machine to the network, not a billed account, and the key file it unlocks is already readable by the person's user.
563
+ */
564
+ const HARNESS_ENV_DENIED: ReadonlyArray<RegExp> = [
565
+ /(^|_)(API_KEY|AUTH_TOKEN|ACCESS_TOKEN|REFRESH_TOKEN|OAUTH_TOKEN|BEARER_TOKEN|ID_TOKEN|TOKEN|SECRET|SECRET_KEY|SECRET_ACCESS_KEY|PASSWORD|PASSWD|CREDENTIALS?)(_|$)/u,
566
+ /(^|_)HEADERS$/u,
567
+ /_BASE_URL$/u,
568
+ /^CLAUDE_CODE_USE_(BEDROCK|VERTEX|FOUNDRY|MANTLE|ANTHROPIC_AWS)$/u,
569
+ /^CLAUDE_CODE_SKIP_[A-Z_]*AUTH$/u,
570
+ /^ANTHROPIC_(FOUNDRY_RESOURCE|VERTEX_PROJECT_ID)$/u,
571
+ ]
572
+
573
+ const never = (upper: string) => upper.startsWith("ELOXIV_") || SESSION_VARIABLES.has(upper)
574
+ const denied = (upper: string) => !NOT_CREDENTIALS.has(upper) && HARNESS_ENV_DENIED.some((rule) => rule.test(upper))
575
+ /** Whether the variable `name` is passed to a harness when the daemon's environment holds it (without `passEnv`). */
576
+ export const passesToHarness = (name: string): boolean => {
577
+ const upper = name.toUpperCase()
578
+ if (never(upper) || denied(upper)) return false
579
+ return HARNESS_ENV.has(upper) || HARNESS_ENV_PREFIXES.some((prefix) => upper.startsWith(prefix))
580
+ }
581
+
582
+ /**
583
+ * The harness's environment: the variables `passesToHarness` allows, those `passEnv` names (a credential included,
584
+ * when the person names it: never the daemon's own or a parent session's), and `extra` (the turn's own: Codex's MCP
585
+ * token). Nothing else of the daemon's environment.
586
+ */
587
+ export const harnessEnv = (
588
+ extra: Readonly<Record<string, string>>,
589
+ passEnv: ReadonlyArray<string> = [],
590
+ ): NodeJS.ProcessEnv => {
591
+ const passed = new Set(passEnv.map((name) => name.toUpperCase()))
592
+ const env: NodeJS.ProcessEnv = {}
593
+ for (const [name, value] of Object.entries(process.env)) {
594
+ const upper = name.toUpperCase()
595
+ if (never(upper)) continue
596
+ if (passesToHarness(upper) || passed.has(upper)) env[name] = value
597
+ }
598
+ return { ...env, ...extra }
599
+ }
600
+
601
+ const GRACE_MS = 3_000
602
+ /** How long output may keep arriving after the CLI itself exited, before the turn ends without it. */
603
+ const EXIT_DRAIN_MS = 2_000
604
+
605
+ /** Run one turn with `config`'s CLI. Never throws: failures are the result's `outcome` and `error`. */
606
+ export const runHarness = (config: HarnessConfig, input: HarnessRunInput): Promise<HarnessResult> =>
607
+ new Promise((resolve) => {
608
+ if (input.scratchRoot !== undefined) mkdirSync(input.scratchRoot, { recursive: true, mode: 0o700 })
609
+ const scratch = mkdtempSync(join(input.scratchRoot ?? tmpdir(), "eloxiv-harness-"))
610
+ const state = newStreamState()
611
+ const events: Array<HarnessEvent> = []
612
+ const parse = parserFor(config.kind)
613
+ let ended: HarnessResult["outcome"] | undefined
614
+ let stderr = ""
615
+ let buffer = ""
616
+ const emit = (event: HarnessEvent) => {
617
+ events.push(event)
618
+ input.onEvent?.(event)
619
+ }
620
+ const { args, env } = harnessArgs(config, input, scratch)
621
+ const [command, ...prefix] = config.command
622
+ const child = spawn(command!, [...prefix, ...args], {
623
+ cwd: input.cwd,
624
+ env: harnessEnv({ ...env, ...config.env }, config.passEnv),
625
+ stdio: ["ignore", "pipe", "pipe"],
626
+ // Its own process group, so stopping it stops whatever it started.
627
+ detached: process.platform !== "win32",
628
+ })
629
+ /** Signal the harness's whole process group (everything it started), or the process where there are no groups. */
630
+ const signalGroup = (name: NodeJS.Signals) => {
631
+ try {
632
+ if (process.platform !== "win32" && child.pid !== undefined) process.kill(-child.pid, name)
633
+ else child.kill(name)
634
+ } catch {
635
+ // Already gone.
636
+ }
637
+ }
638
+ let finished = false
639
+ const stop = (reason: "cancelled" | "timed-out") => {
640
+ if (ended !== undefined || finished) return
641
+ ended = reason
642
+ signalGroup("SIGTERM")
643
+ setTimeout(() => signalGroup("SIGKILL"), GRACE_MS).unref()
644
+ // Stop waiting for output once the group has had its grace: a descendant may hold stdout open.
645
+ setTimeout(() => finish(null), GRACE_MS + 500).unref()
646
+ }
647
+ const timer = setTimeout(() => stop("timed-out"), input.timeoutMs)
648
+ const onAbort = () => stop("cancelled")
649
+ if (input.signal?.aborted) onAbort()
650
+ input.signal?.addEventListener("abort", onAbort, { once: true })
651
+ let afterExit: (() => void) | undefined
652
+ let drain: ReturnType<typeof setTimeout> | undefined
653
+ child.stdout.setEncoding("utf8").on("data", (chunk: string) => {
654
+ afterExit?.()
655
+ buffer += chunk
656
+ let newline = buffer.indexOf("\n")
657
+ while (newline >= 0) {
658
+ const line = buffer.slice(0, newline).trim()
659
+ buffer = buffer.slice(newline + 1)
660
+ if (line.length > 0) {
661
+ input.onRawLine?.(line)
662
+ for (const event of parse(line, state)) emit(event)
663
+ }
664
+ newline = buffer.indexOf("\n")
665
+ }
666
+ })
667
+ child.stderr.setEncoding("utf8").on("data", (chunk: string) => {
668
+ stderr = (stderr + chunk).slice(-8_000)
669
+ })
670
+ const finish = (error: string | null) => {
671
+ if (finished) return
672
+ finished = true
673
+ clearTimeout(timer)
674
+ clearTimeout(drain)
675
+ // The turn is over: nothing it started outlives it.
676
+ signalGroup("SIGKILL")
677
+ child.stdout.destroy()
678
+ child.stderr.destroy()
679
+ input.signal?.removeEventListener("abort", onAbort)
680
+ rmSync(scratch, { recursive: true, force: true })
681
+ if (buffer.trim().length > 0) for (const event of parse(buffer.trim(), state)) emit(event)
682
+ const outcome = ended ?? (state.finished && state.succeeded && error === null ? "succeeded" : "failed")
683
+ const message =
684
+ outcome === "succeeded"
685
+ ? null
686
+ : outcome === "cancelled"
687
+ ? "The turn was cancelled"
688
+ : outcome === "timed-out"
689
+ ? `The turn exceeded its time limit (${input.timeoutMs} ms)`
690
+ : (state.error ?? error ?? (stderr.trim().slice(-2_000) || "The harness exited without a result"))
691
+ resolve({
692
+ outcome,
693
+ result: state.result,
694
+ usage: state.usage,
695
+ error: message,
696
+ events,
697
+ sessionId: state.sessionId,
698
+ })
699
+ }
700
+ child.on("error", (error) => finish(`Could not start ${config.command.join(" ")}: ${error.message}`))
701
+ const exitError = (code: number | null, signal: NodeJS.Signals | null) =>
702
+ code === 0 ? null : `${config.kind} exited with ${code ?? signal ?? "unknown status"}`
703
+ child.on("close", (code, signal) => finish(exitError(code, signal)))
704
+ // The CLI's own process ended: its output normally closes right after ("close" above). If something it
705
+ // started still holds stdout open, end the turn after a grace for the output to drain; the group is killed.
706
+ // The grace runs while the output is quiet: output still arriving (a slow reader, a busy machine) is read
707
+ // to the end, and the turn's own time limit bounds a descendant that keeps writing.
708
+ child.on("exit", (code, signal) => {
709
+ afterExit = () => {
710
+ clearTimeout(drain)
711
+ drain = setTimeout(() => finish(exitError(code, signal)), EXIT_DRAIN_MS)
712
+ drain.unref()
713
+ }
714
+ afterExit()
715
+ })
716
+ })
717
+
718
+ const capture = (config: HarnessConfig, args: ReadonlyArray<string>) =>
719
+ new Promise<{ code: number; stdout: string }>((resolve) => {
720
+ const [binary, ...prefix] = config.command
721
+ const child = spawn(binary!, [...prefix, ...args], {
722
+ stdio: ["ignore", "pipe", "pipe"],
723
+ env: harnessEnv({}, config.passEnv),
724
+ })
725
+ let stdout = ""
726
+ const timer = setTimeout(() => child.kill("SIGKILL"), 15_000)
727
+ child.stdout.setEncoding("utf8").on("data", (chunk: string) => (stdout += chunk))
728
+ child.stderr.setEncoding("utf8").on("data", (chunk: string) => (stdout += chunk))
729
+ child.on("error", () => {
730
+ clearTimeout(timer)
731
+ resolve({ code: -1, stdout })
732
+ })
733
+ child.on("close", (code) => {
734
+ clearTimeout(timer)
735
+ resolve({ code: code ?? -1, stdout })
736
+ })
737
+ })
738
+
739
+ /** Is the CLI installed, which version, and is it signed in to the person's subscription? */
740
+ export const detectHarness = async (config: HarnessConfig): Promise<HarnessStatus> => {
741
+ if (config.command.length === 0) {
742
+ return { kind: config.kind, available: false, version: null, loggedIn: null, detail: "not configured" }
743
+ }
744
+ if (config.protocol === "acp") {
745
+ // An ACP agent keeps its own sign-in; the daemon cannot tell without starting a session.
746
+ const probe = await capture(config, ["--version"])
747
+ if (probe.code === -1) {
748
+ return { kind: config.kind, available: false, version: null, loggedIn: null, detail: "not installed" }
749
+ }
750
+ return {
751
+ kind: config.kind,
752
+ available: true,
753
+ version: probe.code === 0 ? (probe.stdout.trim().split("\n")[0] ?? null) : null,
754
+ loggedIn: null,
755
+ detail: config.toolsOnly === true ? "ACP agent" : "ACP agent (workspace-tool turns only)",
756
+ }
757
+ }
758
+ const version = await capture(config, ["--version"])
759
+ if (version.code !== 0) {
760
+ return { kind: config.kind, available: false, version: null, loggedIn: null, detail: "not installed" }
761
+ }
762
+ const versionText = version.stdout.trim().split("\n")[0] ?? ""
763
+ if (config.kind === "claude-code") {
764
+ const status = await capture(config, ["auth", "status", "--json"])
765
+ try {
766
+ const parsed = JSON.parse(status.stdout) as { loggedIn?: unknown; authMethod?: unknown; apiProvider?: unknown }
767
+ const loggedIn = parsed.loggedIn === true
768
+ // How it is signed in, and where its turns go (`firstParty`: Anthropic itself, not Bedrock, Vertex or a gateway).
769
+ const provider = typeof parsed.apiProvider === "string" ? `, ${parsed.apiProvider}` : ""
770
+ return {
771
+ kind: config.kind,
772
+ available: true,
773
+ version: versionText,
774
+ loggedIn,
775
+ detail: loggedIn
776
+ ? `signed in (${textOr(parsed.authMethod, "unknown")}${provider})`
777
+ : "not signed in: run `claude auth login`",
778
+ }
779
+ } catch {
780
+ return {
781
+ kind: config.kind,
782
+ available: true,
783
+ version: versionText,
784
+ loggedIn: null,
785
+ detail: "sign-in state unknown",
786
+ }
787
+ }
788
+ }
789
+ const status = await capture(config, ["login", "status"])
790
+ const loggedIn = status.code === 0 && /logged in/iu.test(status.stdout)
791
+ return {
792
+ kind: config.kind,
793
+ available: true,
794
+ version: versionText,
795
+ loggedIn,
796
+ detail: loggedIn ? status.stdout.trim().split("\n")[0]! : "not signed in: run `codex login`",
797
+ }
798
+ }
799
+
800
+ /**
801
+ * The harness commands: `claude` and `codex` on the PATH, or `ELOXIV_DAEMON_CLAUDE_COMMAND` /
802
+ * `ELOXIV_DAEMON_CODEX_COMMAND` (a JSON array, or a single path); and `ELOXIV_DAEMON_HARNESS_PASS_ENV`, more variable
803
+ * names to pass to both (comma-separated; see `HarnessConfig.passEnv`).
804
+ */
805
+ export const harnessConfigs = (
806
+ env: Readonly<Record<string, string | undefined>> = process.env,
807
+ ): Record<HarnessKind, HarnessConfig> => {
808
+ const command = (name: string, fallback: string | ReadonlyArray<string>): ReadonlyArray<string> => {
809
+ const raw = env[name]
810
+ if (raw === undefined || raw.trim() === "") return typeof fallback === "string" ? [fallback] : fallback
811
+ if (raw.trim().startsWith("[")) return JSON.parse(raw) as ReadonlyArray<string>
812
+ return [raw]
813
+ }
814
+ const passEnv = (env["ELOXIV_DAEMON_HARNESS_PASS_ENV"] ?? "")
815
+ .split(",")
816
+ .map((name) => name.trim())
817
+ .filter((name) => name.length > 0)
818
+ return {
819
+ "claude-code": { kind: "claude-code", command: command("ELOXIV_DAEMON_CLAUDE_COMMAND", "claude"), passEnv },
820
+ codex: { kind: "codex", command: command("ELOXIV_DAEMON_CODEX_COMMAND", "codex"), passEnv },
821
+ opencode: {
822
+ kind: "opencode",
823
+ command: command("ELOXIV_DAEMON_OPENCODE_COMMAND", ["opencode", "acp"]),
824
+ passEnv,
825
+ protocol: "acp",
826
+ // Not tools-only: OpenCode discovers configuration and plugins in the working directory (a repository's
827
+ // `.opencode/plugins/*.ts` run as code before any permission request), which its permissions do not stop.
828
+ toolsOnly: false,
829
+ },
830
+ // Any ACP agent the person names (none by default), tools-only only when they say it is.
831
+ acp: {
832
+ kind: "acp",
833
+ command: command("ELOXIV_DAEMON_ACP_COMMAND", []),
834
+ passEnv,
835
+ protocol: "acp",
836
+ toolsOnly: env["ELOXIV_DAEMON_ACP_TOOLS_ONLY"] === "1",
837
+ },
838
+ }
839
+ }