@sjawhar/claude-envoy 4.0.0 → 4.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.
package/scripts/build.ts CHANGED
@@ -40,6 +40,10 @@ export const BUNDLE_ENTRYPOINTS = {
40
40
  "envoy-channel": "bin/envoy-channel.ts",
41
41
  "session-hook": "hooks/session-hook.ts",
42
42
  "session-title-hook": "hooks/session-title-hook.ts",
43
+ // The Codex CLI's hooks: `codex-tool-hook` runs after every tool call, so it is a
44
+ // bundle of its own that imports the inbox alone, as `session-title-hook` is for each prompt.
45
+ "codex-hook": "hooks/codex-hook.ts",
46
+ "codex-tool-hook": "hooks/codex-tool-hook.ts",
43
47
  dispatch: "../envoy-client/bin/dispatch.ts",
44
48
  } as const
45
49
 
@@ -399,19 +403,114 @@ async function buildOut(out: string): Promise<void> {
399
403
  await buildLegionPlugin(join(out, "legion"))
400
404
  }
401
405
 
406
+ /** What the Codex plugin, `@sjawhar/codex-envoy`, takes from `codex/`: its npm
407
+ * manifest, its plugin manifest, its hooks and its README. It is a package of its own because
408
+ * Codex's plugin rules and Claude Code's cannot both hold in one directory: Codex's validator
409
+ * (`validate_plugin.py` of the `plugin-creator` skill Codex installs) refuses a manifest that
410
+ * names its hooks file, so its hooks must sit at `hooks/hooks.json`, which is also where Claude
411
+ * Code reads its own, and an npm install of a plugin reads the package's root, never a
412
+ * subdirectory. Measured on Codex CLI 0.154.0 and Claude Code 2.1.325. */
413
+ const CODEX_SOURCES = [".codex-plugin", "hooks", "package.json", "README.md"] as const
414
+
415
+ /** Each skill Claude Code may not load on its own (`disable-model-invocation: true`) and what
416
+ * Codex shows for it. Codex's validator refuses that field; Codex's own form of it is the skill's
417
+ * `agents/openai.yaml` with `policy.allow_implicit_invocation: false`, which keeps the skill out
418
+ * of the model's context until a person names it as `$<skill>`, and that file needs a display
419
+ * name and a 25-64 character description. A skill that sets the field and is not listed here
420
+ * fails the build, so a new one is described on purpose. */
421
+ export const CODEX_EXPLICIT_SKILLS: Readonly<
422
+ Record<string, { readonly displayName: string; readonly shortDescription: string }>
423
+ > = {
424
+ "thermonuclear-code-quality": {
425
+ displayName: "Thermonuclear Code Quality",
426
+ shortDescription: "Deep maintainability audit of a branch or PR diff",
427
+ },
428
+ "thermonuclear-deep-review": {
429
+ displayName: "Thermonuclear Deep Review",
430
+ shortDescription: "Deep correctness and security review of a diff",
431
+ },
432
+ }
433
+
434
+ /** `SKILL.md` as Codex takes it: its `disable-model-invocation` line gone, and, when that line
435
+ * said `true`, the `agents/openai.yaml` that says the same thing in Codex's terms; null for a
436
+ * skill that sets nothing. */
437
+ export function codexSkill(
438
+ name: string,
439
+ source: string,
440
+ ): { readonly skill: string; readonly openaiYaml: string | null } {
441
+ const match = /^---\n([\s\S]*?)\n---\n/.exec(source)
442
+ if (match === null) throw new Error(`skill ${name} has no frontmatter`)
443
+ const lines = (match[1] as string).split("\n")
444
+ const field = lines.find((line) => /^disable-model-invocation\s*:/.test(line))
445
+ if (field === undefined) return { skill: source, openaiYaml: null }
446
+ const value = field.slice(field.indexOf(":") + 1).trim()
447
+ if (value !== "true" && value !== "false") {
448
+ throw new Error(`skill ${name} sets disable-model-invocation to ${value}, not true or false`)
449
+ }
450
+ const kept = lines.filter((line) => line !== field)
451
+ const skill = `---\n${kept.join("\n")}\n---\n${source.slice(match[0].length)}`
452
+ if (value === "false") return { skill, openaiYaml: null }
453
+ const shown = CODEX_EXPLICIT_SKILLS[name]
454
+ if (shown === undefined) {
455
+ throw new Error(
456
+ `skill ${name} sets disable-model-invocation: true, so CODEX_EXPLICIT_SKILLS must describe it`,
457
+ )
458
+ }
459
+ const openaiYaml = [
460
+ "interface:",
461
+ ` display_name: ${JSON.stringify(shown.displayName)}`,
462
+ ` short_description: ${JSON.stringify(shown.shortDescription)}`,
463
+ "policy:",
464
+ " allow_implicit_invocation: false",
465
+ "",
466
+ ].join("\n")
467
+ return { skill, openaiYaml }
468
+ }
469
+
470
+ /** `out` as the Codex plugin's package: `codex/`'s files, this package's skills as Codex takes
471
+ * them (`codexSkill`), and `dist/` — copied from `dist` when given, the bundles a checked build
472
+ * already holds, else built afresh. */
473
+ export async function buildCodexPlugin(out: string, dist?: string): Promise<void> {
474
+ await mkdir(out, { recursive: true })
475
+ for (const source of CODEX_SOURCES) {
476
+ await cp(join(packageRoot, "codex", source), join(out, source), { recursive: true })
477
+ }
478
+ const skills = join(packageRoot, "skills")
479
+ for (const name of (await readdir(skills)).sort()) {
480
+ const target = join(out, "skills", name)
481
+ await cp(join(skills, name), target, { recursive: true, dereference: true })
482
+ const skillFile = join(target, "SKILL.md")
483
+ const { skill, openaiYaml } = codexSkill(name, await readFile(skillFile, "utf8"))
484
+ await writeFile(skillFile, skill)
485
+ if (openaiYaml !== null) {
486
+ await mkdir(join(target, "agents"), { recursive: true })
487
+ await writeFile(join(target, "agents", "openai.yaml"), openaiYaml)
488
+ }
489
+ }
490
+ if (dist === undefined) await buildBundles(join(out, "dist"))
491
+ else await cp(dist, join(out, "dist"), { recursive: true })
492
+ }
493
+
402
494
  const USAGE =
403
- "usage: bun scripts/build.ts --out <dir>. dist/ and legion/ are generated, never committed: " +
404
- "release.yaml's claude_envoy_build builds them and packs them into the tarball it publishes " +
405
- "to npm."
495
+ "usage: bun scripts/build.ts --out <dir> | --codex-out <dir> [--dist <built dist/>]. dist/ " +
496
+ "and legion/ are generated, never committed: release.yaml's claude_envoy_build builds them " +
497
+ "and packs them into the tarballs it publishes to npm."
406
498
 
407
- type Mode = { readonly kind: "out"; readonly dir: string }
499
+ type Mode =
500
+ | { readonly kind: "out"; readonly dir: string }
501
+ | { readonly kind: "codex-out"; readonly dir: string; readonly dist?: string }
408
502
 
409
- /** The one mode `args` names, or null for none, more than one, an unknown argument, or `--out`
503
+ /** The one mode `args` names, or null for none, more than one, an unknown argument, or a flag
410
504
  * with no directory after it. */
411
- function parseMode(args: readonly string[]): Mode | null {
412
- const [first, second, ...rest] = args
413
- if (rest.length > 0 || second === undefined) return null
414
- if (first === "--out" && !second.startsWith("--")) return { kind: "out", dir: second }
505
+ export function parseMode(args: readonly string[]): Mode | null {
506
+ const isValue = (value: string | undefined): value is string =>
507
+ value !== undefined && !value.startsWith("--")
508
+ const [first, second, third, fourth, ...rest] = args
509
+ if (rest.length > 0 || !isValue(second)) return null
510
+ if (first === "--out" && third === undefined) return { kind: "out", dir: second }
511
+ if (first !== "--codex-out") return null
512
+ if (third === undefined) return { kind: "codex-out", dir: second }
513
+ if (third === "--dist" && isValue(fourth)) return { kind: "codex-out", dir: second, dist: fourth }
415
514
  return null
416
515
  }
417
516
 
@@ -426,9 +525,14 @@ if (import.meta.main) {
426
525
  }
427
526
  const refusal = await outRefusal(mode.dir)
428
527
  if (refusal !== null) {
429
- process.stderr.write(`refusing --out: ${refusal}\n`)
528
+ process.stderr.write(`refusing --${mode.kind}: ${refusal}\n`)
430
529
  process.exit(1)
431
530
  }
432
- await buildOut(mode.dir)
433
- process.stdout.write(`built the Claude Envoy plugin into ${resolve(mode.dir)}\n`)
531
+ if (mode.kind === "out") {
532
+ await buildOut(mode.dir)
533
+ process.stdout.write(`built the Claude Envoy plugin into ${resolve(mode.dir)}\n`)
534
+ } else {
535
+ await buildCodexPlugin(mode.dir, mode.dist)
536
+ process.stdout.write(`built the Codex Envoy plugin into ${resolve(mode.dir)}\n`)
537
+ }
434
538
  }
@@ -0,0 +1,240 @@
1
+ import {
2
+ type AgentStreamControlMessage,
3
+ agentStreamControlSubject,
4
+ agentStreamFramesSubject,
5
+ comparableLines,
6
+ } from "@legion/contracts"
7
+ import { messageFor } from "@legion/envoy-client/errors"
8
+ import { AgentStreamPublisher } from "@legion/pi-shared/agent-stream"
9
+ import type { ChannelConnection, ChannelTopicSubscription } from "../channel-topics"
10
+ import type { CodexTranscriptEvent } from "./codex-transcript"
11
+
12
+ /**
13
+ * The Agents page's live view of a Codex session.
14
+ *
15
+ * The conversation comes from the session's transcript (`./codex-transcript`): what the person
16
+ * typed, what the model wrote and its reasoning summaries, and each tool call with its output,
17
+ * become messages on the publisher both other hosts use (`@legion/pi-shared/agent-stream`), which
18
+ * turns them into the frames the page draws and publishes them only while a viewer watches. A
19
+ * line the plugin's hook put into a running turn reaches the transcript as an instruction to the
20
+ * model rather than a message of the conversation, so it is recorded here as the message it is
21
+ * (`delivered`). The viewer's control subject is answered as the Claude Code and Oh My Pi
22
+ * sessions answer it (`../agent-stream-runner`, `packages/pi-envoy`).
23
+ */
24
+ export interface CodexAgentStream {
25
+ /** Records one event of the transcript of the session now bound. */
26
+ event(event: CodexTranscriptEvent): void
27
+ /** Records a line the hook took into a running turn, as a message of the conversation, tagged
28
+ * with the Dispatch message it is where it is a person's own. */
29
+ delivered(text: string, dispatchMessageId?: string): void
30
+ /** Expects the user message a person's message is about to become through `codex queue`, so
31
+ * its row is tagged with the Dispatch message it is and the page shows it once. */
32
+ expect(text: string, dispatchMessageId: string): void
33
+ /** Moves the stream to another session id (`/new`): the conversation starts empty. */
34
+ rebind(sessionId: string): void
35
+ stop(): void
36
+ }
37
+
38
+ export interface CodexAgentStreamOptions {
39
+ readonly connection: ChannelConnection
40
+ readonly sessionId: string
41
+ readonly now?: () => number
42
+ readonly warn?: (text: string) => void
43
+ }
44
+
45
+ const encoder = new TextEncoder()
46
+ const decoder = new TextDecoder()
47
+ /** How long a control subscription that ended waits before it is taken again. */
48
+ const RESUBSCRIBE_MS = 1_000
49
+ /** How many expected person messages are kept for tagging. */
50
+ const EXPECTED_MAX = 16
51
+ /** Codex's models, as the page names a model: `provider/id`. */
52
+ const CODEX_PROVIDER = "openai"
53
+
54
+ export function startCodexAgentStream(options: CodexAgentStreamOptions): CodexAgentStream {
55
+ const { connection } = options
56
+ const now = options.now ?? Date.now
57
+ const warn =
58
+ options.warn ?? ((text: string): void => void process.stderr.write(`envoy-channel: ${text}\n`))
59
+ const publisher = new AgentStreamPublisher({
60
+ now,
61
+ publish: (subject, payload) => connection.publish(subject, encoder.encode(payload)),
62
+ })
63
+ let session = options.sessionId
64
+ let subscription: ChannelTopicSubscription | undefined
65
+ let stopped = false
66
+ let model: string | undefined
67
+ /** The last timestamp handed to a message: each gets one strictly past it, since the publisher
68
+ * keys an assistant message by its timestamp. */
69
+ let allocated = 0
70
+ const expected: { key: string; dispatchMessageId: string }[] = []
71
+ const toolNames = new Map<string, string>()
72
+
73
+ const framesSubject = (): string => agentStreamFramesSubject(session)
74
+ const at = (wanted: number): number => {
75
+ allocated = Math.max(wanted, allocated + 1)
76
+ return allocated
77
+ }
78
+ const record = (message: Record<string, unknown>, dispatchMessageId?: string): void => {
79
+ publisher.record(framesSubject(), message, false, dispatchMessageId)
80
+ }
81
+ const tagFor = (text: string): string | undefined => {
82
+ const key = comparableLines(text).join("\n")
83
+ const index = expected.findIndex((entry) => entry.key === key)
84
+ if (index < 0) return undefined
85
+ const [entry] = expected.splice(index, 1)
86
+ return entry?.dispatchMessageId
87
+ }
88
+
89
+ const publishSettings = (): void => {
90
+ if (model === undefined) {
91
+ publisher.setSettings(framesSubject(), { reported: false })
92
+ return
93
+ }
94
+ const id = `${CODEX_PROVIDER}/${model}`
95
+ publisher.setSettings(framesSubject(), {
96
+ model: id,
97
+ models: [id],
98
+ reported: true,
99
+ thinking: null,
100
+ })
101
+ }
102
+
103
+ const pump = async (taken: ChannelTopicSubscription, forSession: string): Promise<void> => {
104
+ try {
105
+ for await (const message of taken) {
106
+ try {
107
+ const parsed: unknown = JSON.parse(decoder.decode(message.data))
108
+ if (typeof parsed !== "object" || parsed === null) continue
109
+ const request = parsed as AgentStreamControlMessage
110
+ if (request.type !== "replay" && request.type !== "watch") continue
111
+ const reply = message.reply
112
+ const answer =
113
+ request.type === "replay" && reply !== undefined
114
+ ? JSON.stringify(publisher.replay(forSession))
115
+ : undefined
116
+ const arming = !publisher.watched
117
+ publisher.noteViewer()
118
+ if (arming) publisher.publishState(agentStreamFramesSubject(forSession))
119
+ if (answer === undefined || reply === undefined) continue
120
+ connection.publish(reply, encoder.encode(answer))
121
+ } catch (error) {
122
+ warn(`a live view control message failed — ${messageFor(error)}`)
123
+ }
124
+ }
125
+ } catch {
126
+ // A dead iterator is a dropped connection, taken again below.
127
+ }
128
+ if (subscription === taken) subscription = undefined
129
+ if (stopped || session !== forSession) return
130
+ setTimeout(() => {
131
+ if (!stopped && session === forSession) subscribe()
132
+ }, RESUBSCRIBE_MS).unref?.()
133
+ }
134
+
135
+ function subscribe(): void {
136
+ if (stopped) return
137
+ subscription?.unsubscribe()
138
+ const taken = connection.subscribe(agentStreamControlSubject(session))
139
+ subscription = taken
140
+ void pump(taken, session)
141
+ }
142
+ subscribe()
143
+ publishSettings()
144
+
145
+ return {
146
+ event(event) {
147
+ if (stopped) return
148
+ switch (event.kind) {
149
+ case "settings":
150
+ if (event.model !== model) {
151
+ model = event.model
152
+ publishSettings()
153
+ }
154
+ return
155
+ case "user":
156
+ record(
157
+ {
158
+ content: [{ text: event.text, type: "text" }],
159
+ role: "user",
160
+ tag: event.id,
161
+ timestamp: at(event.at),
162
+ },
163
+ tagFor(event.text),
164
+ )
165
+ return
166
+ case "assistant":
167
+ record({
168
+ content: [{ text: event.text, type: "text" }],
169
+ ...(model === undefined ? {} : { model, provider: CODEX_PROVIDER }),
170
+ role: "assistant",
171
+ timestamp: at(event.at),
172
+ })
173
+ return
174
+ case "reasoning":
175
+ record({
176
+ content: [{ thinking: event.text, type: "thinking" }],
177
+ role: "assistant",
178
+ timestamp: at(event.at),
179
+ })
180
+ return
181
+ case "tool-call": {
182
+ toolNames.set(event.callId, event.name)
183
+ let args: unknown = event.arguments
184
+ try {
185
+ args = JSON.parse(event.arguments)
186
+ } catch {
187
+ // Arguments that are not JSON are shown as the text they are.
188
+ }
189
+ record({
190
+ content: [{ arguments: args, id: event.callId, name: event.name, type: "toolCall" }],
191
+ role: "assistant",
192
+ timestamp: at(event.at),
193
+ })
194
+ return
195
+ }
196
+ case "tool-result":
197
+ record({
198
+ content: [{ text: event.output, type: "text" }],
199
+ role: "toolResult",
200
+ timestamp: at(event.at),
201
+ toolCallId: event.callId,
202
+ toolName: toolNames.get(event.callId) ?? "tool",
203
+ })
204
+ return
205
+ default:
206
+ return
207
+ }
208
+ },
209
+ delivered(text, dispatchMessageId) {
210
+ if (stopped) return
211
+ // A person's message the hook took never becomes a user row of the transcript, so the
212
+ // tag kept for that row is dropped rather than left for a later message with the same words.
213
+ if (dispatchMessageId !== undefined) {
214
+ const index = expected.findIndex((entry) => entry.dispatchMessageId === dispatchMessageId)
215
+ if (index >= 0) expected.splice(index, 1)
216
+ }
217
+ record(
218
+ { content: [{ text, type: "text" }], role: "user", timestamp: at(now()) },
219
+ dispatchMessageId,
220
+ )
221
+ },
222
+ expect(text, dispatchMessageId) {
223
+ expected.push({ dispatchMessageId, key: comparableLines(text).join("\n") })
224
+ while (expected.length > EXPECTED_MAX) expected.shift()
225
+ },
226
+ rebind(next) {
227
+ if (stopped || next === session) return
228
+ session = next
229
+ publisher.reset()
230
+ expected.length = 0
231
+ toolNames.clear()
232
+ publishSettings()
233
+ subscribe()
234
+ },
235
+ stop() {
236
+ stopped = true
237
+ subscription?.unsubscribe()
238
+ },
239
+ }
240
+ }
@@ -0,0 +1,280 @@
1
+ import { spawn } from "node:child_process"
2
+ import { randomBytes } from "node:crypto"
3
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs"
4
+ import { join } from "node:path"
5
+
6
+ /**
7
+ * The two things the Codex plugin asks of Codex itself: put a message into a running
8
+ * session (`codex queue`), and answer a side question in a throwaway copy of the session's
9
+ * conversation (`codex app-server`'s `thread/fork`). Both run the same `codex` binary the session
10
+ * runs, against the session's own Codex home.
11
+ */
12
+ export interface CodexCommand {
13
+ /** The `codex` binary the session runs. */
14
+ readonly executable: string
15
+ /** The session's Codex home, which `codex queue` and the app server read the session from. */
16
+ readonly codexHome: string
17
+ /** The environment to run it in; `CODEX_HOME` is set over it. */
18
+ readonly env: Readonly<Record<string, string | undefined>>
19
+ }
20
+
21
+ /** How long `codex queue` may take before it counts as failed. */
22
+ const QUEUE_TIMEOUT_MS = 30_000
23
+
24
+ /**
25
+ * The environment the `codex` process `pid` started with, read from `/proc/<pid>/environ`, or
26
+ * `fallback` where that file cannot be read (another platform, another user's process).
27
+ *
28
+ * Codex starts a plugin's MCP server with only the variables its manifest's `env_vars` names, so
29
+ * this server's own environment lacks the ones Codex itself reads, among them the variable a
30
+ * model provider's `env_key` names. A `codex app-server` run in that environment answers a side
31
+ * question's turn ``Missing environment variable: `<env_key>` `` (measured on 0.154.0 against a
32
+ * provider whose key is an environment variable). The process the session runs in has them.
33
+ */
34
+ export function codexProcessEnv(
35
+ pid: number,
36
+ fallback: Readonly<Record<string, string | undefined>>,
37
+ read: (path: string) => string = (path) => readFileSync(path, "utf8"),
38
+ ): Readonly<Record<string, string | undefined>> {
39
+ let raw: string
40
+ try {
41
+ raw = read(`/proc/${pid}/environ`)
42
+ } catch {
43
+ return fallback
44
+ }
45
+ const env: Record<string, string> = {}
46
+ for (const entry of raw.split("\0")) {
47
+ const equals = entry.indexOf("=")
48
+ if (equals > 0) env[entry.slice(0, equals)] = entry.slice(equals + 1)
49
+ }
50
+ return Object.keys(env).length === 0 ? fallback : env
51
+ }
52
+
53
+ function childEnv(command: CodexCommand): Record<string, string> {
54
+ const env: Record<string, string> = {}
55
+ for (const [name, value] of Object.entries(command.env)) {
56
+ if (value !== undefined) env[name] = value
57
+ }
58
+ env["CODEX_HOME"] = command.codexHome
59
+ return env
60
+ }
61
+
62
+ /**
63
+ * Queues `message` for the session `threadId`: the Codex terminal running it takes the message
64
+ * as a new turn of its own, a few seconds later when it is idle and once its running turn ends
65
+ * otherwise (measured on Codex CLI 0.154.0). Resolves once Codex has stored it; rejects naming
66
+ * why when `codex queue` fails.
67
+ */
68
+ export function queueMessage(
69
+ command: CodexCommand,
70
+ threadId: string,
71
+ text: string,
72
+ spillDirectory?: string,
73
+ ): Promise<void> {
74
+ let message: string
75
+ try {
76
+ message = fitArgument(text, spillDirectory)
77
+ } catch (error) {
78
+ return Promise.reject(error)
79
+ }
80
+ return new Promise((resolve, reject) => {
81
+ // `--message=<text>` and not `--message <text>`: `codex queue` reads a separate value that starts
82
+ // with `-` (a Markdown list) as an option of its own and exits 2 (measured on 0.154.0).
83
+ const child = spawn(
84
+ command.executable,
85
+ ["queue", "--thread", threadId, `--message=${message}`],
86
+ {
87
+ env: childEnv(command),
88
+ stdio: ["ignore", "pipe", "pipe"],
89
+ },
90
+ )
91
+ let output = ""
92
+ child.stdout.on("data", (chunk: Buffer) => {
93
+ output += chunk.toString()
94
+ })
95
+ child.stderr.on("data", (chunk: Buffer) => {
96
+ output += chunk.toString()
97
+ })
98
+ const timer = setTimeout(() => child.kill("SIGKILL"), QUEUE_TIMEOUT_MS)
99
+ child.on("error", (error) => {
100
+ clearTimeout(timer)
101
+ reject(new Error(`could not run ${command.executable} queue: ${error.message}`))
102
+ })
103
+ child.on("close", (code, signal) => {
104
+ clearTimeout(timer)
105
+ if (code === 0) resolve()
106
+ else {
107
+ reject(
108
+ new Error(
109
+ `${command.executable} queue exited ${signal ?? code}: ${output.trim().slice(-500)}`,
110
+ ),
111
+ )
112
+ }
113
+ })
114
+ })
115
+ }
116
+
117
+ /** The longest message `codex queue` is handed as its argument. Linux refuses a single argument
118
+ * over 128 KiB (`MAX_ARG_STRLEN`) and the spawn would fail on every resend of the frame. */
119
+ const QUEUE_ARGUMENT_MAX_BYTES = 96 * 1024
120
+ /** How much of a longer message is quoted before the line naming the file holding all of it. */
121
+ const QUEUE_HEAD_CHARS = 8_000
122
+
123
+ /**
124
+ * `text` as one argument `codex queue` can take: itself, or, past the bound, its start and a line
125
+ * naming a file under `spillDirectory` that holds the whole of it. Throws when it is too long and
126
+ * there is nowhere to put it.
127
+ */
128
+ export function fitArgument(text: string, spillDirectory: string | undefined): string {
129
+ if (Buffer.byteLength(text) <= QUEUE_ARGUMENT_MAX_BYTES) return text
130
+ if (spillDirectory === undefined) {
131
+ throw new Error(`the message is ${Buffer.byteLength(text)} bytes, over what codex queue takes`)
132
+ }
133
+ mkdirSync(spillDirectory, { mode: 0o700, recursive: true })
134
+ const file = join(spillDirectory, `${Date.now()}-${randomBytes(4).toString("hex")}.txt`)
135
+ writeFileSync(file, text, { mode: 0o600 })
136
+ return `${text.slice(0, QUEUE_HEAD_CHARS)}\n\n[This message is ${Buffer.byteLength(text)} bytes long; the whole of it is in ${file}.]`
137
+ }
138
+
139
+ /** How long a side question may run before it is abandoned. */
140
+ const SIDE_QUESTION_TIMEOUT_MS = 5 * 60_000
141
+
142
+ interface JsonRpcMessage {
143
+ readonly id?: number
144
+ readonly method?: string
145
+ readonly params?: Record<string, unknown>
146
+ readonly result?: Record<string, unknown>
147
+ readonly error?: { readonly message?: string }
148
+ }
149
+
150
+ /**
151
+ * Answers `question` in a throwaway copy of the session `threadId`'s conversation and resolves
152
+ * with what the model wrote. The copy runs in a `codex app-server` of its own with plugins and
153
+ * hooks off (so it registers nothing and runs none of this plugin), a read-only sandbox and no
154
+ * approvals (so it can read files and change nothing), and `ephemeral`, so Codex keeps no
155
+ * transcript of it. The session's own conversation is left as it was.
156
+ */
157
+ export function askSideQuestion(
158
+ command: CodexCommand,
159
+ threadId: string,
160
+ question: string,
161
+ timeoutMs: number = SIDE_QUESTION_TIMEOUT_MS,
162
+ ): Promise<string> {
163
+ return new Promise((resolve, reject) => {
164
+ const child = spawn(
165
+ command.executable,
166
+ ["app-server", "--disable", "plugins", "--disable", "hooks"],
167
+ { env: childEnv(command), stdio: ["pipe", "pipe", "pipe"] },
168
+ )
169
+ let settled = false
170
+ let stderr = ""
171
+ const finish = (error: Error | undefined, answer?: string): void => {
172
+ if (settled) return
173
+ settled = true
174
+ clearTimeout(timer)
175
+ child.kill("SIGTERM")
176
+ if (error !== undefined) reject(error)
177
+ else resolve(answer ?? "")
178
+ }
179
+ const timer = setTimeout(
180
+ () => finish(new Error(`the side question had no answer after ${timeoutMs} ms`)),
181
+ timeoutMs,
182
+ )
183
+ let next = 1
184
+ const pending = new Map<number, (message: JsonRpcMessage) => void>()
185
+ const call = (method: string, params: unknown): Promise<Record<string, unknown>> =>
186
+ new Promise((done, fail) => {
187
+ const id = next++
188
+ pending.set(id, (message) => {
189
+ if (message.error !== undefined) {
190
+ fail(new Error(`${method}: ${message.error.message ?? "refused"}`))
191
+ } else done(message.result ?? {})
192
+ })
193
+ child.stdin.write(`${JSON.stringify({ id, jsonrpc: "2.0", method, params })}\n`)
194
+ })
195
+ let forkId: string | undefined
196
+ let turnId: string | undefined
197
+ const answers: string[] = []
198
+ let buffer = ""
199
+ child.stdout.on("data", (chunk: Buffer) => {
200
+ buffer += chunk.toString()
201
+ let newline = buffer.indexOf("\n")
202
+ while (newline >= 0) {
203
+ const line = buffer.slice(0, newline)
204
+ buffer = buffer.slice(newline + 1)
205
+ newline = buffer.indexOf("\n")
206
+ let message: JsonRpcMessage
207
+ try {
208
+ message = JSON.parse(line) as JsonRpcMessage
209
+ } catch {
210
+ continue
211
+ }
212
+ if (message.id !== undefined && message.method === undefined) {
213
+ pending.get(message.id)?.(message)
214
+ pending.delete(message.id)
215
+ continue
216
+ }
217
+ const params = message.params ?? {}
218
+ if (params["threadId"] !== forkId) continue
219
+ if (message.method === "item/completed") {
220
+ const item = params["item"] as Record<string, unknown> | undefined
221
+ if (item?.["type"] === "agentMessage" && typeof item["text"] === "string") {
222
+ answers.push(item["text"])
223
+ }
224
+ } else if (message.method === "turn/completed") {
225
+ const turn = params["turn"] as Record<string, unknown> | undefined
226
+ if (turnId === undefined || turn?.["id"] === turnId) {
227
+ const status = turn?.["status"]
228
+ if (status === "failed") {
229
+ const error = turn?.["error"] as { message?: string } | null | undefined
230
+ finish(
231
+ new Error(
232
+ `the side question's turn failed: ${error?.message ?? "no reason given"}`,
233
+ ),
234
+ )
235
+ } else finish(undefined, answers.join("\n\n"))
236
+ }
237
+ }
238
+ }
239
+ })
240
+ child.stderr.on("data", (chunk: Buffer) => {
241
+ stderr = (stderr + chunk.toString()).slice(-2000)
242
+ })
243
+ // A write to an app server that has died raises EPIPE here; its `close` says why it ended.
244
+ child.stdin.on("error", () => undefined)
245
+ child.on("error", (error) =>
246
+ finish(new Error(`could not run ${command.executable} app-server: ${error.message}`)),
247
+ )
248
+ child.on("close", (code) => {
249
+ finish(
250
+ new Error(
251
+ `${command.executable} app-server exited ${code} before answering: ${stderr.trim()}`,
252
+ ),
253
+ )
254
+ })
255
+ void (async () => {
256
+ try {
257
+ await call("initialize", { clientInfo: { name: "claude-envoy-btw", version: "1" } })
258
+ child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", method: "initialized" })}\n`)
259
+ const fork = await call("thread/fork", {
260
+ approvalPolicy: "never",
261
+ ephemeral: true,
262
+ excludeTurns: true,
263
+ sandbox: "read-only",
264
+ threadId,
265
+ })
266
+ const thread = fork["thread"] as Record<string, unknown> | undefined
267
+ forkId = typeof thread?.["id"] === "string" ? thread["id"] : undefined
268
+ if (forkId === undefined) throw new Error("thread/fork answered no thread")
269
+ const turn = await call("turn/start", {
270
+ input: [{ text: question, text_elements: [], type: "text" }],
271
+ threadId: forkId,
272
+ })
273
+ const started = turn["turn"] as Record<string, unknown> | undefined
274
+ turnId = typeof started?.["id"] === "string" ? started["id"] : undefined
275
+ } catch (error) {
276
+ finish(error instanceof Error ? error : new Error(String(error)))
277
+ }
278
+ })()
279
+ })
280
+ }