@sjawhar/claude-envoy 1.18.0 → 1.20.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/src/envoy-off.ts CHANGED
@@ -23,8 +23,13 @@ export function inboundOffChannelSession(options: {
23
23
  throw new Error(`inbound messages are off for this session: ${why}`)
24
24
  },
25
25
  unfollow: async () => [],
26
- // No heartbeat runs, so no role is ever regained.
26
+ // No heartbeat runs, so no role is ever regained, nothing is advertised for a change to
27
+ // reach, no mod event has a router here to read it, and no row of a delivery was ever
28
+ // recorded: this session takes no inbound message at all.
27
29
  onRoleRegained: () => undefined,
30
+ capabilitiesChanged: () => undefined,
31
+ observe: () => undefined,
32
+ messageOf: () => undefined,
28
33
  async rememberRole(role) {
29
34
  await writePersistedRole(roleStateFile(stateDirectory, identity.id), {
30
35
  session_id: identity.id,
@@ -0,0 +1,26 @@
1
+ // Which build of this plugin Claude Code is running, read off the path of the bundle it loaded.
2
+ //
3
+ // Claude Code installs a plugin under `…/plugins/cache/<marketplace>/<plugin>/<version>/`, where
4
+ // the version is the published npm version, since this plugin's marketplace entry is an `npm`
5
+ // source. Every registration names that build to the listener, so the Agents page can tell a
6
+ // session running a release from one running a checkout.
7
+ import { sep } from "node:path"
8
+
9
+ /** The segments after `…/plugins/cache/` in a plugin install path, or undefined for any other
10
+ * path: a source checkout, `--plugin-dir`, or a bare server config. */
11
+ function pluginCacheSegments(bundlePath: string): string[] | undefined {
12
+ const parts = bundlePath.split(sep)
13
+ for (let index = 0; index + 1 < parts.length; index++) {
14
+ if (parts[index] === "plugins" && parts[index + 1] === "cache") return parts.slice(index + 2)
15
+ }
16
+ return undefined
17
+ }
18
+
19
+ /**
20
+ * The version a plugin install path names (`…/plugins/cache/<marketplace>/<plugin>/<version>/…`,
21
+ * the published npm version for this plugin, whose marketplace entry is an `npm` source), or
22
+ * undefined for any other path.
23
+ */
24
+ export function installedPluginVersion(bundlePath: string): string | undefined {
25
+ return pluginCacheSegments(bundlePath)?.[2]
26
+ }
@@ -5,9 +5,9 @@ import type { ChannelNotification, ChannelNotifier } from "./envoy-channel-serve
5
5
 
6
6
  /**
7
7
  * The variable `legion claude-bridge` exports to Claude Code, and so to this server, naming its
8
- * inbox socket (`packages/daemon/internal/claudebridge/inbox.go`): Claude Code's print mode never
9
- * delivers a `notifications/claude/channel`, so in a Legion pane each Envoy delivery goes there and
10
- * the bridge sends it to Claude Code as a user turn.
8
+ * inbox socket (`packages/daemon/internal/claudebridge/inbox.go`): in a Legion pane each Envoy
9
+ * delivery goes there and the bridge sends it to Claude Code as a user turn, which is what makes
10
+ * a person's own message a turn of the pane's own conversation.
11
11
  */
12
12
  export const INBOX_VARIABLE = "LEGION_CLAUDE_INBOX"
13
13
 
@@ -35,12 +35,15 @@ interface InboxAnswer {
35
35
  /**
36
36
  * A notifier that writes each delivery to the bridge's inbox at `socketPath`, one JSON line
37
37
  * `{id, content}` (the envelope's `event_id`, else a fresh id; the rendered content), and resolves
38
- * once the bridge answers `{id, ok: true}`. The bridge answers `ok` only when Claude Code re-emits
39
- * that user message (`--replay-user-messages`), that is once it took the delivery into a step, and
40
- * an error when Claude Code never takes it: a relayed frame is answered `done` on the one and `nak`
41
- * on the other. An answer with an error, a closed socket or an answer for another id rejects. The
42
- * bridge answers one connection's lines in order, so one connection, opened on first use and again
43
- * after it closes, carries every delivery.
38
+ * once the bridge answers `{id, ok: true}`. A line whose delivery carries more than its text - a
39
+ * person's own message and the pictures it embeds - also carries `blocks`, Claude Code's own
40
+ * content blocks for it (INFRA-1026); `content` stays the text, so a bridge that does not know
41
+ * the field delivers the message as it always did. The bridge answers `ok` only when Claude Code
42
+ * re-emits that user message (`--replay-user-messages`), that is once it took the delivery into a
43
+ * step, and an error when Claude Code never takes it: a relayed frame is answered `done` on the
44
+ * one and `nak` on the other. An answer with an error, a closed socket or an answer for another
45
+ * id rejects. The bridge answers one connection's lines in order, so one connection, opened on
46
+ * first use and again after it closes, carries every delivery.
44
47
  */
45
48
  export function createInboxNotifier(socketPath: string): ChannelNotifier {
46
49
  let socket: Socket | undefined
@@ -100,10 +103,18 @@ export function createInboxNotifier(socketPath: string): ChannelNotifier {
100
103
 
101
104
  return {
102
105
  notification(notification: ChannelNotification): Promise<void> {
103
- const id = notification.params.meta["event_id"] ?? randomUUID()
106
+ const id = notification.eventId ?? randomUUID()
104
107
  const settle = Promise.withResolvers<void>()
105
108
  waiting.push({ id, settle })
106
- connected().write(`${JSON.stringify({ id, content: notification.params.content })}\n`)
109
+ // `blocks` is additional: `content` is the message's text whatever a reader makes of the
110
+ // blocks, so a bridge that does not know the field delivers the message as it always did.
111
+ connected().write(
112
+ `${JSON.stringify({
113
+ id,
114
+ content: notification.content,
115
+ ...(notification.blocks === undefined ? {} : { blocks: notification.blocks }),
116
+ })}\n`,
117
+ )
107
118
  return settle.promise
108
119
  },
109
120
  }
@@ -0,0 +1,562 @@
1
+ import { randomUUID } from "node:crypto"
2
+ import { chmod, lstat, mkdir, stat, unlink } from "node:fs/promises"
3
+ import {
4
+ createServer,
5
+ request as httpRequest,
6
+ type IncomingMessage,
7
+ type Server,
8
+ type ServerResponse,
9
+ } from "node:http"
10
+ import { dirname } from "node:path"
11
+ import {
12
+ MOD_HEALTH_MARKER,
13
+ MOD_INSTANCE_HEADER,
14
+ MOD_POLL_HOLD_MS,
15
+ MOD_ROUTE_EVENTS,
16
+ MOD_ROUTE_HEALTH,
17
+ MOD_ROUTE_REQUESTS,
18
+ MOD_ROUTE_RESULTS,
19
+ MOD_STATUS_TAKEN,
20
+ MOD_URL_BASE,
21
+ type ModAckBody,
22
+ type ModCallArguments,
23
+ type ModCallName,
24
+ type ModCallResults,
25
+ type ModEvent,
26
+ type ModHealthBody,
27
+ type ModRequest,
28
+ type ModRequestsBody,
29
+ type ModResult,
30
+ type ModResultValue,
31
+ resolveModSocketPath,
32
+ } from "../hooks/mod-protocol"
33
+
34
+ /** How long a `request()` waits for the mod's answer when the caller names no bound. A `$` call
35
+ * of the mod's is the engine's own work, and a `session.message` can wait for a turn already
36
+ * running before the engine takes its prompt — 8.5 s, 11.2 s and 12.4 s in the submits
37
+ * recorded on 2.1.310 — so the caller of one passes a bound of its own
38
+ * (`./mod-session.ts`, `SHOW_TIMEOUT_MS`). */
39
+ const MOD_REQUEST_TIMEOUT_MS = 30_000
40
+
41
+ /** How long the bind's probe waits for a server that may hold the path. Long enough for a live
42
+ * server to answer a request it serves out of memory, short enough not to stall the MCP server's
43
+ * start on a socket file nothing is behind. */
44
+ const MOD_PROBE_TIMEOUT_MS = 1_000
45
+
46
+ /** The most events held for an owner that is not reading them. One session's events are small and
47
+ * the live view (`./agent-stream-runner`) consumes them as they arrive; past this the oldest go,
48
+ * since the newest frame is the one a live view needs. */
49
+ const MOD_EVENT_BUFFER = 2_048
50
+
51
+ /** The `Host` of every request on the socket: over a Unix socket the host names nothing, and both
52
+ * sides use the link's own name so a stray request is recognisable. */
53
+ const MOD_HOST = new URL(MOD_URL_BASE).host
54
+
55
+ /** The link to this session's Claude Code mod: what it said, and what it can be asked to do. */
56
+ export interface ModLink {
57
+ /** The socket this link is bound to. */
58
+ readonly socketPath: string
59
+ /** Everything the mod has sent, in the order it sent it. One consumer: each event goes to the
60
+ * first `next()` that asks for it. Events sent before the owner starts reading are held, the
61
+ * oldest dropped past 2048; the iterator ends when the link closes. */
62
+ readonly events: AsyncIterableIterator<ModEvent>
63
+ /** Ask the mod to make one call, and resolve with its answer. Rejects with the mod's own error
64
+ * when the call failed, when `timeoutMs` passes with no answer, and when the link closes
65
+ * first. A request whose own bound is up leaves the queue with it, so a mod that connects an
66
+ * hour later is handed no work nobody is waiting for (INFRA-1026 review).
67
+ *
68
+ * Nothing here reports a request handed to a mod. A hand-out is a write into a poll's
69
+ * response, which a SIGSTOPped process never reads, so it proves nothing about the session
70
+ * (INFRA-1026 review, round eleven, repro `R-A`). What the session did with a message is the
71
+ * row the mod answers with, and a request the mod never answered is one its caller leaves
72
+ * unanswered too: Envoy sends the frame again, and the mod writes the message once
73
+ * (`../hooks/mod-writer.ts`, `writeOnce`). */
74
+ readonly request: <N extends ModCallName>(
75
+ call: N,
76
+ args: ModCallArguments[N],
77
+ options?: { readonly timeoutMs?: number },
78
+ ) => Promise<ModCallResults[N]>
79
+ /** The session id the mod last reported: its boot id, then whatever a `/clear` moved it to.
80
+ * Undefined until the mod says hello. */
81
+ readonly sessionId: () => string | undefined
82
+ /** Called whenever that id changes, the first report included. */
83
+ readonly onSessionId: (listener: (sessionId: string) => void) => void
84
+ /** Whether a mod is talking to this link now: true while a poll is held, and for one hold
85
+ * after the mod's last poll or event, so a mod that stopped stops counting within about ten
86
+ * seconds. A session's delivery modes are read off this (`sessionCapabilities`), and the
87
+ * mod's first event - its hello - is as good a proof that it is there as its first poll. */
88
+ readonly connected: () => boolean
89
+ /** Called when a poll or an event arrives while this link did not count as connected: the
90
+ * rising edge of `connected()`. The mod sends its hello once per Claude Code process, so a
91
+ * server Claude Code starts again inside that process hears nothing else from a mod that is
92
+ * already there, and neither does a listener added after the hello landed (INFRA-1026
93
+ * review). There is no falling edge: `connected()` goes false on its own, about ten seconds
94
+ * after the mod's last poll. */
95
+ readonly onConnected: (listener: () => void) => void
96
+ /** Stop serving, unlink the socket, end `events` and reject every unanswered request. */
97
+ readonly close: () => Promise<void>
98
+ }
99
+
100
+ /** What `startModLink` needs: whose session this is, and the environment the socket path is
101
+ * resolved against (the same rule the mod resolves it by, in `../hooks/mod-protocol`). */
102
+ export interface ModLinkOptions {
103
+ readonly sessionId: string
104
+ readonly env: Readonly<Record<string, string | undefined>>
105
+ /** Where a refused second mod is reported; this process's stderr when the caller names none. */
106
+ readonly warn?: (text: string) => void
107
+ }
108
+
109
+ /** One poll of the mod's, held open until there is work for it or the hold is up. */
110
+ interface HeldPoll {
111
+ readonly answer: (requests: readonly ModRequest[]) => void
112
+ readonly timer: ReturnType<typeof setTimeout>
113
+ }
114
+
115
+ /** One request made of the mod and not yet answered. */
116
+ interface PendingRequest {
117
+ readonly call: ModCallName
118
+ readonly settle: PromiseWithResolvers<ModResultValue>
119
+ readonly timer: ReturnType<typeof setTimeout>
120
+ }
121
+
122
+ /** A one-consumer stream of what the mod sent. */
123
+ interface ModEventStream {
124
+ readonly iterator: AsyncIterableIterator<ModEvent>
125
+ readonly push: (event: ModEvent) => void
126
+ readonly end: () => void
127
+ }
128
+
129
+ /** Whether a live link answers `GET /healthz` at `socketPath` with its marker: the one way to
130
+ * tell a socket another server owns from one a dead server left behind. */
131
+ function probeHealth(socketPath: string, timeoutMs: number): Promise<boolean> {
132
+ const { promise, resolve } = Promise.withResolvers<boolean>()
133
+ const probe = httpRequest(
134
+ {
135
+ socketPath,
136
+ path: MOD_ROUTE_HEALTH,
137
+ method: "GET",
138
+ headers: { host: MOD_HOST },
139
+ timeout: timeoutMs,
140
+ },
141
+ (response: IncomingMessage) => {
142
+ let body = ""
143
+ response.setEncoding("utf8")
144
+ response.on("data", (chunk: string) => {
145
+ body += chunk
146
+ })
147
+ response.on("end", () => {
148
+ if (response.statusCode !== 200) {
149
+ resolve(false)
150
+ return
151
+ }
152
+ let parsed: unknown
153
+ try {
154
+ parsed = JSON.parse(body)
155
+ } catch {
156
+ resolve(false)
157
+ return
158
+ }
159
+ if (typeof parsed !== "object" || parsed === null || !("link" in parsed)) {
160
+ resolve(false)
161
+ return
162
+ }
163
+ resolve(parsed.link === MOD_HEALTH_MARKER)
164
+ })
165
+ },
166
+ )
167
+ probe.on("error", () => resolve(false))
168
+ probe.on("timeout", () => {
169
+ probe.destroy()
170
+ resolve(false)
171
+ })
172
+ probe.end()
173
+ return promise
174
+ }
175
+
176
+ /** The events of a `POST /events` body, or undefined when the body is not one. The mod is this
177
+ * socket's only writer, so an item that carries a `kind` is the event it says it is. */
178
+ function readEvents(body: unknown): readonly ModEvent[] | undefined {
179
+ if (typeof body !== "object" || body === null || !("events" in body)) return undefined
180
+ const events = body.events
181
+ if (!Array.isArray(events)) return undefined
182
+ return events.filter(
183
+ (event: unknown): event is ModEvent =>
184
+ typeof event === "object" &&
185
+ event !== null &&
186
+ "kind" in event &&
187
+ typeof event.kind === "string",
188
+ )
189
+ }
190
+
191
+ /** The results of a `POST /results` body, or undefined when the body is not one. */
192
+ function readResults(body: unknown): readonly ModResult[] | undefined {
193
+ if (typeof body !== "object" || body === null || !("results" in body)) return undefined
194
+ const results = body.results
195
+ if (!Array.isArray(results)) return undefined
196
+ return results.filter(
197
+ (result: unknown): result is ModResult =>
198
+ typeof result === "object" &&
199
+ result !== null &&
200
+ "id" in result &&
201
+ typeof result.id === "string" &&
202
+ "ok" in result &&
203
+ typeof result.ok === "boolean",
204
+ )
205
+ }
206
+
207
+ /** A stream whose `push` buffers while nobody reads and whose `end` closes the iterator for
208
+ * good: the owner reads the mod's events from it at its own pace. */
209
+ function createEventStream(limit: number): ModEventStream {
210
+ const buffered: ModEvent[] = []
211
+ let waiting: ((result: IteratorResult<ModEvent>) => void) | undefined
212
+ let ended = false
213
+ const iterator: AsyncIterableIterator<ModEvent> = {
214
+ [Symbol.asyncIterator]() {
215
+ return iterator
216
+ },
217
+ next(): Promise<IteratorResult<ModEvent>> {
218
+ const next = buffered.shift()
219
+ if (next !== undefined) return Promise.resolve({ value: next, done: false })
220
+ if (ended) return Promise.resolve({ value: undefined, done: true })
221
+ const { promise, resolve } = Promise.withResolvers<IteratorResult<ModEvent>>()
222
+ waiting = resolve
223
+ return promise
224
+ },
225
+ }
226
+ return {
227
+ iterator,
228
+ push(event: ModEvent): void {
229
+ if (ended) return
230
+ const settle = waiting
231
+ if (settle !== undefined) {
232
+ waiting = undefined
233
+ settle({ value: event, done: false })
234
+ return
235
+ }
236
+ buffered.push(event)
237
+ if (buffered.length > limit) buffered.splice(0, buffered.length - limit)
238
+ },
239
+ end(): void {
240
+ if (ended) return
241
+ ended = true
242
+ const settle = waiting
243
+ if (settle !== undefined) {
244
+ waiting = undefined
245
+ settle({ value: undefined, done: true })
246
+ }
247
+ },
248
+ }
249
+ }
250
+
251
+ /** Whether something is at `path` at all. */
252
+ async function exists(path: string): Promise<boolean> {
253
+ try {
254
+ await stat(path)
255
+ return true
256
+ } catch {
257
+ return false
258
+ }
259
+ }
260
+
261
+ /** The directory the socket sits in, made when it is missing and checked when it is not: a
262
+ * directory of this user's own, `0700`, and no symbolic link to one elsewhere. Anyone who can
263
+ * write this directory can bind the socket before this server does and then read the
264
+ * conversation and submit prompts as the person, so a directory that is open to anyone else is
265
+ * refused rather than tightened: whatever left it open may have left something in it too
266
+ * (INFRA-1026 review). `mkdir` can only drop bits of the `0700` it is given, so a directory
267
+ * this server made is never the one that is refused. */
268
+ async function privateDirectory(path: string): Promise<void> {
269
+ await mkdir(path, { recursive: true, mode: 0o700 })
270
+ const directory = await lstat(path)
271
+ if (!directory.isDirectory()) {
272
+ throw new Error(`${path} is not a directory of its own, so the socket has no private home`)
273
+ }
274
+ // Windows has no `getuid`, and no Unix socket for the mod either; a host without one has no
275
+ // owner to compare and the mode below is the whole check.
276
+ const user = process.getuid?.()
277
+ if (user !== undefined && directory.uid !== user) {
278
+ throw new Error(`${path} belongs to uid ${directory.uid}, not to this user (uid ${user})`)
279
+ }
280
+ if ((directory.mode & 0o077) !== 0) {
281
+ throw new Error(
282
+ `${path} is mode ${(directory.mode & 0o777).toString(8)}, which lets another user into this session's socket; chmod 700 it`,
283
+ )
284
+ }
285
+ }
286
+
287
+ /** Serve `socketPath`, inside a directory only this user can use, with a stale socket unlinked;
288
+ * refuses a path a live link already answers. */
289
+ async function bind(server: Server, socketPath: string): Promise<void> {
290
+ await privateDirectory(dirname(socketPath))
291
+ if (await exists(socketPath)) {
292
+ if (await probeHealth(socketPath, MOD_PROBE_TIMEOUT_MS)) {
293
+ throw new Error(`another claude-envoy server already serves this session at ${socketPath}`)
294
+ }
295
+ await unlink(socketPath).catch(() => undefined)
296
+ }
297
+ const { promise, resolve, reject } = Promise.withResolvers<void>()
298
+ server.once("error", reject)
299
+ server.listen(socketPath, () => {
300
+ server.removeListener("error", reject)
301
+ resolve()
302
+ })
303
+ await promise
304
+ await chmod(socketPath, 0o600)
305
+ }
306
+
307
+ /**
308
+ * Bind this session's mod socket and serve the four routes the mod speaks (`MOD_ROUTE_*` in
309
+ * `../hooks/mod-protocol`): its events in, its poll for work and its answers, and the liveness
310
+ * probe both the mod and the next server use.
311
+ *
312
+ * The path is the one the mod computes from the same rule, so neither side guesses, and it sits
313
+ * in a directory of this user's own (`privateDirectory`). A socket that is already there is
314
+ * probed: a live link answering the marker owns this session and the bind is refused; anything
315
+ * else is a socket a dead server left, unlinked and bound over. The bound socket is the user's
316
+ * alone (`0600`).
317
+ *
318
+ * One link serves one mod: the first mod instance to name itself in a post holds it, and every
319
+ * other is refused (`MOD_STATUS_TAKEN`), so two Claude Code processes that booted on one session
320
+ * id do not share a live view or a person's Send (INFRA-1026 review).
321
+ *
322
+ * Rejects when the session names no socket path or no private directory for it, when another
323
+ * server owns it, and when the bind itself fails. Nothing here stops the MCP server: the caller
324
+ * says on stderr what it could not do and carries on.
325
+ */
326
+ export async function startModLink(options: ModLinkOptions): Promise<ModLink> {
327
+ const resolved = resolveModSocketPath(options.sessionId, options.env)
328
+ if (resolved.path === undefined) {
329
+ throw new Error(`no socket path for this session: ${resolved.refusal}`)
330
+ }
331
+ const socketPath = resolved.path
332
+
333
+ const stream = createEventStream(MOD_EVENT_BUFFER)
334
+ const queued: ModRequest[] = []
335
+ const held = new Set<HeldPoll>()
336
+ const pending = new Map<string, PendingRequest>()
337
+ const sessionIdListeners: ((sessionId: string) => void)[] = []
338
+ const connectedListeners: (() => void)[] = []
339
+ const warn =
340
+ options.warn ??
341
+ ((text: string): void => {
342
+ process.stderr.write(`claude-envoy: ${text}\n`)
343
+ })
344
+ /** The mod instance this link serves: the first one to name itself in a post. */
345
+ let instance: string | undefined
346
+ let reportedSessionId: string | undefined
347
+ let lastPollAt = 0
348
+ let closed = false
349
+
350
+ const isConnected = (): boolean =>
351
+ !closed && (held.size > 0 || Date.now() - lastPollAt < MOD_POLL_HOLD_MS * 2)
352
+
353
+ /** One post of the mod's arrived. A post that lands while the link counts as disconnected is
354
+ * the rising edge `onConnected` reports, and the only word a server hears from a mod that
355
+ * said its hello to an earlier server in the same Claude Code process. */
356
+ const heard = (): void => {
357
+ const before = isConnected()
358
+ lastPollAt = Date.now()
359
+ if (!before) for (const listener of connectedListeners) listener()
360
+ }
361
+
362
+ const reportSessionId = (sessionId: string): void => {
363
+ if (sessionId === reportedSessionId) return
364
+ reportedSessionId = sessionId
365
+ for (const listener of sessionIdListeners) listener(sessionId)
366
+ }
367
+
368
+ /** Hand the work waiting to the poll that is held, if one is. */
369
+ const wake = (): void => {
370
+ const [poll] = held
371
+ if (poll === undefined || queued.length === 0) return
372
+ held.delete(poll)
373
+ clearTimeout(poll.timer)
374
+ poll.answer(queued.splice(0, queued.length))
375
+ }
376
+
377
+ const answerJson = (response: ServerResponse, status: number, body: unknown): void => {
378
+ const text = JSON.stringify(body)
379
+ response.writeHead(status, {
380
+ "content-type": "application/json",
381
+ "content-length": Buffer.byteLength(text),
382
+ })
383
+ response.end(text)
384
+ }
385
+
386
+ const readBody = (incoming: IncomingMessage): Promise<string> => {
387
+ const { promise, resolve, reject } = Promise.withResolvers<string>()
388
+ let body = ""
389
+ incoming.setEncoding("utf8")
390
+ incoming.on("data", (chunk: string) => {
391
+ body += chunk
392
+ })
393
+ incoming.on("end", () => resolve(body))
394
+ incoming.on("error", reject)
395
+ return promise
396
+ }
397
+
398
+ const serve = async (incoming: IncomingMessage, response: ServerResponse): Promise<void> => {
399
+ const route = (incoming.url ?? "").split("?")[0]
400
+ if (route === MOD_ROUTE_HEALTH && incoming.method === "GET") {
401
+ answerJson(response, 200, { link: MOD_HEALTH_MARKER } satisfies ModHealthBody)
402
+ return
403
+ }
404
+ if (
405
+ incoming.method !== "POST" ||
406
+ (route !== MOD_ROUTE_EVENTS && route !== MOD_ROUTE_RESULTS && route !== MOD_ROUTE_REQUESTS)
407
+ ) {
408
+ answerJson(response, 404, { error: `no route ${incoming.method ?? ""} ${route ?? ""}` })
409
+ return
410
+ }
411
+ const named = incoming.headers[MOD_INSTANCE_HEADER]
412
+ const mod = typeof named === "string" ? named : undefined
413
+ if (mod !== undefined) {
414
+ instance ??= mod
415
+ if (instance !== mod) {
416
+ warn(
417
+ `a second Claude Code mod (${mod}) posted to a link mod ${instance} holds, so two processes booted on one session id; it is refused and stops (${socketPath})`,
418
+ )
419
+ answerJson(response, MOD_STATUS_TAKEN, {
420
+ error: `this session's link belongs to mod ${instance}`,
421
+ })
422
+ return
423
+ }
424
+ }
425
+ const text = await readBody(incoming)
426
+ let body: unknown
427
+ try {
428
+ body = text.length === 0 ? {} : JSON.parse(text)
429
+ } catch {
430
+ answerJson(response, 400, { error: "the body is not JSON" })
431
+ return
432
+ }
433
+ if (route === MOD_ROUTE_EVENTS) {
434
+ heard()
435
+ const events = readEvents(body)
436
+ if (events === undefined) {
437
+ answerJson(response, 400, { error: "the body carries no events" })
438
+ return
439
+ }
440
+ for (const event of events) {
441
+ if (event.kind === "hello" || event.kind === "session-id") reportSessionId(event.sessionId)
442
+ stream.push(event)
443
+ }
444
+ answerJson(response, 200, { ok: true } satisfies ModAckBody)
445
+ return
446
+ }
447
+ if (route === MOD_ROUTE_RESULTS) {
448
+ const results = readResults(body)
449
+ if (results === undefined) {
450
+ answerJson(response, 400, { error: "the body carries no results" })
451
+ return
452
+ }
453
+ for (const result of results) {
454
+ const waiting = pending.get(result.id)
455
+ if (waiting === undefined) continue
456
+ pending.delete(result.id)
457
+ clearTimeout(waiting.timer)
458
+ if (result.ok) waiting.settle.resolve(result.value)
459
+ else waiting.settle.reject(new Error(`the mod could not ${waiting.call}: ${result.error}`))
460
+ }
461
+ answerJson(response, 200, { ok: true } satisfies ModAckBody)
462
+ return
463
+ }
464
+ heard()
465
+ if (queued.length > 0 || closed) {
466
+ answerJson(response, 200, {
467
+ requests: queued.splice(0, queued.length),
468
+ } satisfies ModRequestsBody)
469
+ return
470
+ }
471
+ // Held, not blocked: this handler returns and the server goes on serving, so a `GET /healthz`
472
+ // on another connection is answered while the mod waits here.
473
+ const poll: HeldPoll = {
474
+ answer: (requests) => answerJson(response, 200, { requests } satisfies ModRequestsBody),
475
+ timer: setTimeout(() => {
476
+ held.delete(poll)
477
+ answerJson(response, 200, { requests: [] } satisfies ModRequestsBody)
478
+ }, MOD_POLL_HOLD_MS),
479
+ }
480
+ poll.timer.unref()
481
+ held.add(poll)
482
+ incoming.on("close", () => {
483
+ if (held.delete(poll)) clearTimeout(poll.timer)
484
+ })
485
+ }
486
+
487
+ const server = createServer((incoming, response) => {
488
+ void serve(incoming, response).catch(() => {
489
+ if (response.headersSent) response.end()
490
+ else answerJson(response, 500, { error: "the mod link failed" })
491
+ })
492
+ })
493
+ await bind(server, socketPath)
494
+
495
+ const close = async (): Promise<void> => {
496
+ if (closed) return
497
+ closed = true
498
+ for (const waiting of pending.values()) {
499
+ clearTimeout(waiting.timer)
500
+ waiting.settle.reject(new Error("the mod link closed before the mod answered"))
501
+ }
502
+ pending.clear()
503
+ // The queue goes with them: every request it held has just been rejected, and a mod that
504
+ // posts one last poll as this server goes down is handed none of it. A request no mod took
505
+ // leaves the queue when its own bound is up or when the link drops, and never sits there
506
+ // waiting for a mod that polls an hour later (INFRA-1026 review).
507
+ queued.length = 0
508
+ for (const poll of held) {
509
+ clearTimeout(poll.timer)
510
+ poll.answer([])
511
+ }
512
+ held.clear()
513
+ stream.end()
514
+ server.closeAllConnections()
515
+ const { promise, resolve } = Promise.withResolvers<void>()
516
+ server.close(() => resolve())
517
+ await promise
518
+ await unlink(socketPath).catch(() => undefined)
519
+ }
520
+
521
+ return {
522
+ socketPath,
523
+ events: stream.iterator,
524
+ request<N extends ModCallName>(
525
+ call: N,
526
+ args: ModCallArguments[N],
527
+ requestOptions?: { readonly timeoutMs?: number },
528
+ ): Promise<ModCallResults[N]> {
529
+ if (closed) return Promise.reject(new Error("the mod link is closed"))
530
+ const timeoutMs = requestOptions?.timeoutMs ?? MOD_REQUEST_TIMEOUT_MS
531
+ const id = randomUUID()
532
+ const settle = Promise.withResolvers<ModResultValue>()
533
+ // One arm of ModRequest per call name, a correlation the compiler cannot follow through `N`.
534
+ const request = { id, call, args } as ModRequest
535
+ const timer = setTimeout(() => {
536
+ pending.delete(id)
537
+ // Out of the queue with it. Queued is where a request waits while no mod is polling,
538
+ // and a mod that connects an hour later would otherwise run work whose caller gave up
539
+ // long ago; in a session whose mod never connects the queue would grow for the life of
540
+ // the process (INFRA-1026 review).
541
+ const waiting = queued.indexOf(request)
542
+ if (waiting !== -1) queued.splice(waiting, 1)
543
+ settle.reject(new Error(`the mod did not answer ${call} within ${timeoutMs} ms`))
544
+ }, timeoutMs)
545
+ timer.unref()
546
+ pending.set(id, { call, settle, timer })
547
+ queued.push(request)
548
+ wake()
549
+ // The mod answers the call it was asked for, so the value is that call's own.
550
+ return settle.promise as Promise<ModCallResults[N]>
551
+ },
552
+ sessionId: () => reportedSessionId,
553
+ onSessionId(listener: (sessionId: string) => void): void {
554
+ sessionIdListeners.push(listener)
555
+ },
556
+ connected: isConnected,
557
+ onConnected(listener: () => void): void {
558
+ connectedListeners.push(listener)
559
+ },
560
+ close,
561
+ }
562
+ }