@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.
@@ -0,0 +1,594 @@
1
+ import { spawn } from "node:child_process"
2
+ import { unwatchFile, watchFile } from "node:fs"
3
+ import { homedir } from "node:os"
4
+ import { join, resolve } from "node:path"
5
+ import { DELIVERY_CAPABILITIES } from "@legion/contracts"
6
+ import { activeDispatchSettings } from "@legion/envoy-client/dispatch-config"
7
+ import { DispatchClient } from "@legion/envoy-client/dispatch-http"
8
+ import { sessionDirectory as dispatchSessionDirectory } from "@legion/envoy-client/dispatch-session-directory"
9
+ import { writeSessionTitle } from "@legion/envoy-client/dispatch-session-state"
10
+ import { messageFor } from "@legion/envoy-client/errors"
11
+ import { natsConnectionOptions } from "@legion/envoy-client/nats-connection"
12
+ import {
13
+ sessionConfigFile,
14
+ sessionDispatchSettings,
15
+ sessionSettings,
16
+ } from "@legion/envoy-client/session-settings"
17
+ import { createEnvoyClient, newClientInstanceID } from "@legion/envoy-client/transport"
18
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js"
19
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
20
+ import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js"
21
+ import { connect } from "nats"
22
+ import { z } from "zod"
23
+ /** The npm package a Codex session runs, which its registrations name. */
24
+ import { name as CODEX_PACKAGE_NAME } from "../../codex/package.json" with { type: "json" }
25
+ import type { ChannelConnection } from "../channel-topics"
26
+ import { configuredValue } from "../claude-session"
27
+ import {
28
+ type ChannelSession,
29
+ type ChannelToolRuntime,
30
+ channelToolDefinitions,
31
+ executeEnvoyTool,
32
+ MCP_SERVER_INFO,
33
+ mcpResult,
34
+ postDispatchReply,
35
+ startChannelSession,
36
+ } from "../envoy-channel-server"
37
+ import { inboundOffChannelSession } from "../envoy-off"
38
+ import { installedPluginVersion } from "../installed-build"
39
+ import { SessionIdentity } from "../session-identity"
40
+ import { sessionTitle } from "../session-title"
41
+ import { type CodexAgentStream, startCodexAgentStream } from "./codex-agent-stream"
42
+ import { askSideQuestion, type CodexCommand, codexProcessEnv, queueMessage } from "./codex-cli"
43
+ import { createCodexDelivery } from "./codex-delivery"
44
+ import { codexInboxDirectory, discardWaiting } from "./codex-inbox"
45
+ import {
46
+ type CodexServerEntry,
47
+ codexServersDirectory,
48
+ stillOwner,
49
+ unregisterServer,
50
+ waitForOwnership,
51
+ } from "./codex-owner"
52
+ import {
53
+ type CodexSessionRecord,
54
+ codexEndedFile,
55
+ codexHome,
56
+ codexPluginDataDirectory,
57
+ codexSessionRecordFile,
58
+ processStarted,
59
+ readCodexSessionRecord,
60
+ recordOfProcess,
61
+ SHARED_APP_SERVER_NOTE,
62
+ sessionEnded,
63
+ sharedAppServer,
64
+ watchRecord,
65
+ } from "./codex-session-record"
66
+ import {
67
+ findTranscript,
68
+ followTranscript,
69
+ latestTurnCwd,
70
+ type TranscriptFollower,
71
+ threadIdShape,
72
+ transcriptEvents,
73
+ } from "./codex-transcript"
74
+ import { createCodexUserTurnRouter } from "./codex-user-turns"
75
+
76
+ /**
77
+ * The Envoy plugin's MCP server under the Codex CLI: `codex/.codex-plugin/plugin.json`
78
+ * starts `dist/envoy-channel.js --host codex` in the plugin's own directory, as a child of the
79
+ * `codex` process.
80
+ *
81
+ * It serves the Envoy tools and the `dispatch` tool at once, and starts the session's Envoy side
82
+ * when the plugin's `SessionStart` hook records which session the `codex` process runs
83
+ * (`./codex-session-record`), which Codex does at the session's first prompt. From then on it is
84
+ * the Claude Code plugin's session code (`startChannelSession`) with Codex's parts: a line goes
85
+ * into the session through `codex queue` or the `PostToolUse` hook (`./codex-delivery`), a
86
+ * person's message through `./codex-user-turns`, and the live view comes from the session's
87
+ * transcript (`./codex-agent-stream`). A `/new` moves it to the new session's id through the same
88
+ * hand-off file a Claude Code `/clear` writes.
89
+ *
90
+ * Codex starts one such server per thread, so a `codex` process can have several (a `/new` starts
91
+ * one beside the old thread's, and `/side` and `/btw` one each). Only the one that owns the
92
+ * process's session (`./codex-owner`) runs the Envoy side; the others serve their thread's
93
+ * `dispatch` calls and take the session over once the owner is gone.
94
+ */
95
+
96
+ const CODEX_INSTRUCTIONS =
97
+ "Envoy delivers trusted, internal session and Dispatch events into this conversation. Use the Envoy tools for Envoy actions, and reach Dispatch through this server's `dispatch` tool (the `dispatch` skill teaches its commands). Dispatch asks stay on Dispatch."
98
+
99
+ /** How often the session record is looked at while the server waits for it, and after. */
100
+ const RECORD_POLL_MS = 250
101
+
102
+ /** The capabilities a Codex session advertises: all three, since every one has a way in. */
103
+ const CODEX_CAPABILITIES = DELIVERY_CAPABILITIES
104
+
105
+ const DispatchToolArguments = z.object({
106
+ args: z.array(z.string()),
107
+ stdin: z.string().optional(),
108
+ })
109
+
110
+ /** Why a standby server's Envoy tools do not run (`./codex-owner`). */
111
+ const STANDBY_NOTE =
112
+ "another of this codex process's plugin servers serves its Envoy session, because Codex starts one server per thread and one of them owns the session; after /new, this thread's Envoy tools start once every server started before this one has exited, which for the previous thread's server is thread_unload_delay (60 s by default) after that thread went idle with no subscriber, and messages to this session arrive meanwhile; the dispatch tool works now"
113
+
114
+ /** How often the owning server checks it still owns the session. */
115
+ const OWNER_RECHECK_MS = 5_000
116
+
117
+ /**
118
+ * The Codex thread whose turn made a tool call, from the request's `_meta`: Codex 0.154.0 sends
119
+ * `threadId` on every MCP tool call, beside `x-codex-turn-metadata` naming the same thread
120
+ * (measured). Undefined when the call names none.
121
+ */
122
+ export function callingThread(meta: unknown): string | undefined {
123
+ if (typeof meta !== "object" || meta === null) return undefined
124
+ const named = (meta as { threadId?: unknown }).threadId
125
+ const turn = (meta as { "x-codex-turn-metadata"?: { thread_id?: unknown } })[
126
+ "x-codex-turn-metadata"
127
+ ]
128
+ const thread = typeof named === "string" && named !== "" ? named : turn?.thread_id
129
+ // Checked once here: everything downstream (CODEX_THREAD_ID, the transcript search) takes it.
130
+ return typeof thread === "string" && threadIdShape(thread) ? thread : undefined
131
+ }
132
+
133
+ /** The `dispatch` tool's definition: the command, as a tool that runs outside Codex's sandbox. */
134
+ export function dispatchToolDefinition() {
135
+ return {
136
+ description:
137
+ 'Runs the `dispatch` command as this session, outside Codex\'s sandbox. Pass the words after `dispatch` as `args` (for example ["read", "--issue", "LEGION-3"]) and what the command would read on standard input as `stdin` (the text of a here-document given as `--body-file -`). `["--help"]` lists the commands. Answers with what the command printed and its exit code: 0 written or read, 1 refused by Dispatch, 2 a usage error.',
138
+ inputSchema: {
139
+ properties: {
140
+ args: {
141
+ description: "The command's words after `dispatch`.",
142
+ items: { type: "string" },
143
+ type: "array",
144
+ },
145
+ stdin: {
146
+ description: "What the command reads on standard input, where a flag says `-`.",
147
+ type: "string",
148
+ },
149
+ },
150
+ required: ["args"],
151
+ type: "object",
152
+ },
153
+ name: "dispatch",
154
+ }
155
+ }
156
+
157
+ /** How long one `dispatch` tool call may run. */
158
+ const DISPATCH_TOOL_TIMEOUT_MS = 120_000
159
+
160
+ /** Runs the plugin's own `dispatch` command (`dist/dispatch.js`) with this server's Bun, outside
161
+ * Codex's sandbox, and answers its exit code and everything it printed, in order. */
162
+ export function runDispatchCommand(
163
+ script: string,
164
+ args: readonly string[],
165
+ stdin: string,
166
+ options: { readonly cwd: string; readonly env: Record<string, string> },
167
+ ): Promise<{ readonly code: number; readonly output: string }> {
168
+ return new Promise((done) => {
169
+ const child = spawn(process.execPath, [script, ...args], {
170
+ cwd: options.cwd,
171
+ env: options.env,
172
+ stdio: ["pipe", "pipe", "pipe"],
173
+ })
174
+ let output = ""
175
+ const take = (chunk: Buffer): void => {
176
+ output += chunk.toString()
177
+ }
178
+ child.stdout.on("data", take)
179
+ child.stderr.on("data", take)
180
+ const timer = setTimeout(() => child.kill("SIGKILL"), DISPATCH_TOOL_TIMEOUT_MS)
181
+ child.on("error", (error) => {
182
+ clearTimeout(timer)
183
+ done({ code: 2, output: `dispatch: could not run ${script}: ${error.message}\n` })
184
+ })
185
+ child.on("close", (code, signal) => {
186
+ clearTimeout(timer)
187
+ done({
188
+ code: code ?? 2,
189
+ output: signal === null ? output : `${output}dispatch: stopped by ${signal}\n`,
190
+ })
191
+ })
192
+ // A command that exits without reading all of a long stdin raises EPIPE here, which
193
+ // would otherwise end this server; the command's own exit code is the answer.
194
+ child.stdin.on("error", () => undefined)
195
+ child.stdin.end(stdin)
196
+ })
197
+ }
198
+
199
+ /** The plugin's state directory: the one Codex hands its hooks, worked out from where it
200
+ * installed the plugin, else a directory of the plugin's own under the person's state home. */
201
+ function stateDirectoryFor(pluginRoot: string): string {
202
+ return (
203
+ configuredValue(process.env["PLUGIN_DATA"]) ??
204
+ codexPluginDataDirectory(pluginRoot) ??
205
+ join(
206
+ configuredValue(process.env["XDG_STATE_HOME"]) ?? join(homedir(), ".local", "state"),
207
+ "claude-envoy",
208
+ "codex",
209
+ )
210
+ )
211
+ }
212
+
213
+ /** Resolves with the record once the `SessionStart` hook has written it for a session that has not
214
+ * ended, polling the file. */
215
+ function waitForRecord(
216
+ file: string,
217
+ pid: number,
218
+ signal: AbortSignal,
219
+ ended: (sessionId: string) => Promise<boolean>,
220
+ ): Promise<CodexSessionRecord | undefined> {
221
+ return new Promise((done) => {
222
+ const look = (): void => {
223
+ void readCodexSessionRecord(file).then(async (record) => {
224
+ // A record an earlier process with the same id left behind names no session of this one,
225
+ // and a session that has ended is not registered again (a takeover after `/new`, before
226
+ // the new thread's first prompt).
227
+ if (record === undefined || !recordOfProcess(record, pid)) return
228
+ if (await ended(record.session_id)) return
229
+ unwatchFile(file, look)
230
+ done(record)
231
+ })
232
+ }
233
+ watchFile(file, { interval: RECORD_POLL_MS }, look)
234
+ signal.addEventListener("abort", () => {
235
+ unwatchFile(file, look)
236
+ done(undefined)
237
+ })
238
+ look()
239
+ })
240
+ }
241
+
242
+ export async function runCodexEnvoyServer(): Promise<void> {
243
+ const pluginRoot = process.cwd()
244
+ const stateDirectory = stateDirectoryFor(pluginRoot)
245
+ const codexPid = process.ppid
246
+ /** Codex's shared app server runs several sessions in this one process, whose Envoy traffic this
247
+ * plugin cannot tell apart, so it registers none of them (`sharedAppServer`); `dispatch` still
248
+ * acts as the thread that calls it. */
249
+ const shared = sharedAppServer(codexPid)
250
+ const recordFile = codexSessionRecordFile(stateDirectory, codexPid)
251
+ const serversDirectory = codexServersDirectory(stateDirectory, codexPid)
252
+ /** This server's entry, once `waitForOwnership` published it. */
253
+ let self: CodexServerEntry | undefined
254
+ let stopWatchingRecord: () => void = () => undefined
255
+ let recheck: ReturnType<typeof setInterval> | undefined
256
+ /** Whether session `sessionId` of this process has ended (`SessionEnd`'s marker). */
257
+ const endedNow = (sessionId: string): Promise<boolean> =>
258
+ sessionEnded(codexEndedFile(stateDirectory, codexPid, sessionId))
259
+ const configFile = sessionConfigFile("codex", process.env)
260
+ const warn = (text: string): void => void process.stderr.write(`envoy-channel: ${text}\n`)
261
+ const bundlePath = resolve(pluginRoot, process.argv[1] ?? "")
262
+
263
+ let record: CodexSessionRecord | undefined
264
+ let runtime: ChannelToolRuntime | undefined
265
+ let notReady = "this session's Envoy side starts at its first prompt"
266
+ const stopping = new AbortController()
267
+
268
+ const server = new Server(MCP_SERVER_INFO, {
269
+ capabilities: { tools: {} },
270
+ instructions: CODEX_INSTRUCTIONS,
271
+ })
272
+ const tools = [...channelToolDefinitions(), dispatchToolDefinition()]
273
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools }))
274
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
275
+ if (request.params.name === "dispatch") {
276
+ const thread = callingThread(request.params._meta)
277
+ return {
278
+ content: [
279
+ { text: await runDispatchTool(request.params.arguments, thread), type: "text" as const },
280
+ ],
281
+ }
282
+ }
283
+ if (runtime === undefined) throw new Error(`Envoy is not ready: ${notReady}`)
284
+ return mcpResult(await executeEnvoyTool(runtime, request.params.name, request.params.arguments))
285
+ })
286
+
287
+ /** Runs the `dispatch` command in this process, as `thread`, the Codex thread whose turn made the
288
+ * call, in the directory that thread's newest turn ran in, and answers what it printed and its
289
+ * exit code. Codex names the thread on every tool call (`callingThread`), so a fork or a second
290
+ * session of the same process acts as itself and never as the session Envoy registered. */
291
+ const runDispatchTool = async (raw: unknown, thread: string | undefined): Promise<string> => {
292
+ const parsed = DispatchToolArguments.safeParse(raw)
293
+ if (!parsed.success)
294
+ return `dispatch: the tool takes args (a list of strings) and an optional stdin\n[exit 2]`
295
+ // The record, read now when the server has not seen it yet: the hook writes it before the turn's
296
+ // first request, and the server reads it on a poll.
297
+ const read = shared ? undefined : (record ?? (await readCodexSessionRecord(recordFile)))
298
+ const current = read !== undefined && recordOfProcess(read, codexPid) ? read : undefined
299
+ // A Codex that names no thread on the call (older than 0.154.0) acts as the record's session,
300
+ // which is the one session of a process this plugin registers; under the shared app server
301
+ // there is no such session to fall back on.
302
+ const sessionId = thread ?? current?.session_id
303
+ if (sessionId === undefined) {
304
+ return shared
305
+ ? `dispatch: ${SHARED_APP_SERVER_NOTE}\n[exit 2]`
306
+ : `dispatch: this session has no id yet; Codex records it at the session's first prompt\n[exit 2]`
307
+ }
308
+ const own = current?.session_id === sessionId ? current : undefined
309
+ const home = own?.codex_home ?? codexHome(process.env)
310
+ const transcript = own?.transcript_path ?? (await findTranscript(home, sessionId))
311
+ const env: Record<string, string> = {}
312
+ for (const [name, value] of Object.entries(process.env)) {
313
+ if (value !== undefined) env[name] = value
314
+ }
315
+ env["CODEX_HOME"] = home
316
+ env["CODEX_THREAD_ID"] = sessionId
317
+ env["DISPATCH_HOST"] = "codex"
318
+ if (configFile.path !== null) env["ENVOY_CONFIG_FILE"] = configFile.path
319
+ const { code, output } = await runDispatchCommand(
320
+ join(pluginRoot, "dist", "dispatch.js"),
321
+ parsed.data.args,
322
+ parsed.data.stdin ?? "",
323
+ { cwd: (await latestTurnCwd(transcript)) ?? own?.cwd ?? current?.cwd ?? homedir(), env },
324
+ )
325
+ return `${output}${output.endsWith("\n") || output === "" ? "" : "\n"}[exit ${code}]`
326
+ }
327
+
328
+ let session: ChannelSession | undefined
329
+ let connection: ChannelConnection | undefined
330
+ let stream: CodexAgentStream | undefined
331
+ let follower: TranscriptFollower | undefined
332
+ let delivery: ReturnType<typeof createCodexDelivery> | undefined
333
+
334
+ const stopped = Promise.withResolvers<void>()
335
+ let isStopping = false
336
+ const stop = (): void => {
337
+ if (isStopping) return
338
+ isStopping = true
339
+ stopping.abort()
340
+ stopWatchingRecord()
341
+ clearInterval(recheck)
342
+ follower?.stop()
343
+ stream?.stop()
344
+ // The entry goes once the delivery's waiting lines are withdrawn, so a server that takes over
345
+ // never discards a line this one still answers for.
346
+ const withdrawn = (delivery?.stop() ?? Promise.resolve()).finally(() =>
347
+ self === undefined
348
+ ? undefined
349
+ : unregisterServer(serversDirectory, self).catch(() => undefined),
350
+ )
351
+ if (session === undefined) {
352
+ void withdrawn.finally(stopped.resolve)
353
+ return
354
+ }
355
+ void Promise.all([withdrawn, session.shutdown()]).finally(stopped.resolve)
356
+ }
357
+ process.stdin.once("end", stop)
358
+ process.once("SIGTERM", stop)
359
+ process.once("SIGINT", stop)
360
+ process.once("SIGHUP", stop)
361
+ await server.connect(new StdioServerTransport())
362
+
363
+ if (shared) {
364
+ notReady = SHARED_APP_SERVER_NOTE
365
+ warn(SHARED_APP_SERVER_NOTE)
366
+ await stopped.promise
367
+ await server.close().catch(() => undefined)
368
+ return
369
+ }
370
+ // One server per codex process owns its Envoy session (`./codex-owner`): Codex starts one per
371
+ // thread, and the others stand by, serving their thread's `dispatch` calls, until every server
372
+ // older than them is gone.
373
+ notReady = STANDBY_NOTE
374
+ const owning = await waitForOwnership(
375
+ serversDirectory,
376
+ process.pid,
377
+ processStarted(process.pid) ?? null,
378
+ stopping.signal,
379
+ (entry) => {
380
+ self = entry
381
+ },
382
+ )
383
+ if (owning === undefined) {
384
+ await stopped.promise
385
+ await server.close().catch(() => undefined)
386
+ return
387
+ }
388
+ notReady =
389
+ "this session's Envoy side starts once Codex records the session at its first prompt; a fork or an ephemeral session, which keeps no transcript, is never registered"
390
+ // The owner looks again every few seconds and warns if it finds another owner, which the order
391
+ // of publication rules out while every entry is readable.
392
+ const owned = owning
393
+ recheck = setInterval(() => {
394
+ void stillOwner(serversDirectory, owned).then(
395
+ (still) => {
396
+ if (!still)
397
+ warn(`another plugin server of codex process ${codexPid} owns its Envoy session as well`)
398
+ },
399
+ () => undefined,
400
+ )
401
+ }, OWNER_RECHECK_MS)
402
+ recheck.unref?.()
403
+ record = await waitForRecord(recordFile, codexPid, stopping.signal, endedNow)
404
+ if (record === undefined) {
405
+ await stopped.promise
406
+ await server.close().catch(() => undefined)
407
+ return
408
+ }
409
+ const bound = record
410
+ /** Whether the session the record names has ended, as its marker last said. */
411
+ let recordEnded = false
412
+ // Lines an earlier owner of this session left waiting: that server is gone, so no write waits on
413
+ // them, and Envoy sends each one's frame again.
414
+ await discardWaiting(codexInboxDirectory(stateDirectory, bound.session_id))
415
+ /** Whether the session code, the live view and the transcript follower have started; a `/new`
416
+ * before then is applied once they have. */
417
+ let ready = false
418
+ /** Moves this server's Codex parts to the session `next` names (`/new`): the delivery's turn
419
+ * state and waiting lines, the live view, and the transcript followed. The Envoy session code
420
+ * follows the hand-off file the hook wrote beside the record on its own. */
421
+ let moveTo: (next: CodexSessionRecord) => void = () => undefined
422
+ // Watched from now, so a `/new` while the session starts is seen, and read once at once, so an
423
+ // end marked between the bind's own read and this watch is seen too.
424
+ stopWatchingRecord = watchRecord(
425
+ recordFile,
426
+ codexPid,
427
+ endedNow,
428
+ (next, ended) => {
429
+ if (next.session_id === record?.session_id) {
430
+ // The same session ended (`SessionEnd`), or runs again (`/resume`). Before the delivery
431
+ // exists, its creation reads `recordEnded` instead.
432
+ if (ended !== recordEnded) {
433
+ recordEnded = ended
434
+ if (ended) delivery?.sessionEnded()
435
+ else void delivery?.sessionResumed().catch((error: unknown) => warn(messageFor(error)))
436
+ }
437
+ return
438
+ }
439
+ record = next
440
+ recordEnded = ended
441
+ if (ready) moveTo(next)
442
+ },
443
+ RECORD_POLL_MS,
444
+ )
445
+ const id = new SessionIdentity(bound.session_id, bound.cwd)
446
+ const { dispatch, envoy, notice } = sessionSettings(configFile, process.env, {
447
+ cwd: bound.cwd,
448
+ session: () => id.id,
449
+ })
450
+ if (notice !== null) warn(notice)
451
+ const title = await sessionTitle(
452
+ {
453
+ ENVOY_SESSION_TITLE: process.env["ENVOY_SESSION_TITLE"],
454
+ TMUX: process.env["TMUX"],
455
+ TMUX_PANE: process.env["TMUX_PANE"],
456
+ },
457
+ bound.cwd,
458
+ )
459
+ const stampTitle = (sessionId: string, value: string): void => {
460
+ writeSessionTitle(dispatchSessionDirectory(process.env, sessionId), value)
461
+ }
462
+ if (!envoy.enabled) {
463
+ notReady = `Envoy is off for this session: ${envoy.error ?? envoy.notice}`
464
+ if (dispatch.enabled) stampTitle(id.id, title(id.id))
465
+ await stopped.promise
466
+ await server.close().catch(() => undefined)
467
+ return
468
+ }
469
+
470
+ const command = (): CodexCommand => ({
471
+ codexHome: record?.codex_home ?? bound.codex_home,
472
+ // Codex's own environment, not this server's: Codex gave this server only `env_vars`.
473
+ env: codexProcessEnv(codexPid, process.env),
474
+ executable: record?.codex_executable ?? bound.codex_executable ?? "codex",
475
+ })
476
+ const client = createEnvoyClient({
477
+ baseUrl: envoy.url,
478
+ credential: envoy.credential,
479
+ fetch: globalThis.fetch,
480
+ })
481
+ const clientInstanceID = newClientInstanceID()
482
+ /** The session the `codex` process runs now, as its record names it: what `codex queue` and the
483
+ * inbox are addressed by, which moves at `/new` before the Envoy session code adopts the new
484
+ * id from the hand-off file. */
485
+ const runningSession = (): string => record?.session_id ?? bound.session_id
486
+ const codexDelivery = createCodexDelivery({
487
+ inboxDirectory: (sessionId) => codexInboxDirectory(stateDirectory, sessionId),
488
+ queue: (text) =>
489
+ queueMessage(command(), runningSession(), text, join(stateDirectory, "codex-long-messages")),
490
+ sessionId: runningSession,
491
+ taken: (item) => stream?.delivered(item.content, item.dispatchMessageId),
492
+ warn,
493
+ })
494
+ delivery = codexDelivery
495
+ // An end the watcher saw before the delivery existed.
496
+ if (recordEnded) codexDelivery.sessionEnded()
497
+
498
+ /** Reads the transcript of the session now bound into the delivery's turn state and the live
499
+ * view, from its first line; a `/new` starts this again on the new session's transcript. */
500
+ const follow = (path: string | null): void => {
501
+ follower?.stop()
502
+ follower = undefined
503
+ if (path === null) return
504
+ follower = followTranscript(
505
+ path,
506
+ (line) => {
507
+ for (const event of transcriptEvents(line)) {
508
+ if (event.kind === "turn-started") codexDelivery.turnStarted()
509
+ else if (event.kind === "turn-ended") {
510
+ void codexDelivery.turnEnded().catch((error: unknown) => warn(messageFor(error)))
511
+ }
512
+ stream?.event(event)
513
+ }
514
+ },
515
+ { warn },
516
+ )
517
+ }
518
+
519
+ moveTo = (next) => {
520
+ void codexDelivery.rebind(recordEnded).catch((error: unknown) => warn(messageFor(error)))
521
+ stream?.rebind(next.session_id)
522
+ follow(next.transcript_path)
523
+ }
524
+
525
+ try {
526
+ const { inbound } = envoy
527
+ if ("off" in inbound) {
528
+ session = inboundOffChannelSession({ identity: id, stateDirectory, why: inbound.off })
529
+ } else {
530
+ connection = await connect(
531
+ natsConnectionOptions({
532
+ name: `codex-envoy-channel-${id.id}`,
533
+ seed: inbound.natsSeed,
534
+ servers: inbound.natsUrls,
535
+ }),
536
+ )
537
+ session = await startChannelSession({
538
+ capabilities: () => CODEX_CAPABILITIES,
539
+ client,
540
+ clientInstanceID,
541
+ configFile,
542
+ connection,
543
+ handoffPid: codexPid,
544
+ heartbeatMs: envoy.heartbeatMs,
545
+ identity: id,
546
+ notifier: {
547
+ notification: ({ content, eventId }) =>
548
+ codexDelivery.deliver({ content, ...(eventId === undefined ? {} : { eventId }) }),
549
+ },
550
+ pluginVersion: installedPluginVersion(bundlePath) ?? "source",
551
+ pluginName: CODEX_PACKAGE_NAME,
552
+ router: (state) =>
553
+ createCodexUserTurnRouter({
554
+ ask: (question) => askSideQuestion(command(), id.id, question),
555
+ deliver: (item) => codexDelivery.deliver(item),
556
+ dispatch: (ms) => {
557
+ const active = activeDispatchSettings(
558
+ sessionDispatchSettings(configFile, process.env, { cwd: bound.cwd }).dispatch,
559
+ )
560
+ return active === null
561
+ ? undefined
562
+ : new DispatchClient(active.url, active.credential, fetch, {
563
+ signal: AbortSignal.timeout(ms),
564
+ })
565
+ },
566
+ expect: (text, messageId) => stream?.expect(text, messageId),
567
+ reply: (target, result) => postDispatchReply(id, configFile, target, result),
568
+ sessionId: () => id.id,
569
+ state,
570
+ warn,
571
+ }),
572
+ stateDirectory,
573
+ title,
574
+ ...(dispatch.enabled ? { stampTitle } : {}),
575
+ })
576
+ stream = startCodexAgentStream({ connection, sessionId: id.id, warn })
577
+ }
578
+ runtime = { client, clientInstanceID, identity: id, session }
579
+ follow(bound.transcript_path)
580
+
581
+ ready = true
582
+ // A `/new` the record watcher saw while the session was starting.
583
+ if (record !== undefined && record.session_id !== bound.session_id) moveTo(record)
584
+ if (isStopping) await session.shutdown()
585
+ await stopped.promise
586
+ } finally {
587
+ follower?.stop()
588
+ if (session === undefined && connection !== undefined) {
589
+ await connection.drain().catch(() => undefined)
590
+ await connection.close().catch(() => undefined)
591
+ }
592
+ await server.close().catch(() => undefined)
593
+ }
594
+ }