@sjawhar/claude-envoy 1.18.0 → 1.19.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.
@@ -2,6 +2,7 @@ import { type Stats, unwatchFile, watchFile } from "node:fs"
2
2
  import { rm } from "node:fs/promises"
3
3
  import {
4
4
  agentSubject,
5
+ DELIVERY_CAPABILITIES,
5
6
  type DeliveryCapability,
6
7
  ROLE_TOPIC_PREFIX,
7
8
  zodSchemaApi,
@@ -22,6 +23,8 @@ import {
22
23
  type RenderInboundResult,
23
24
  renderInbound,
24
25
  } from "@legion/envoy-client/delivery"
26
+ import { activeDispatchSettings } from "@legion/envoy-client/dispatch-config"
27
+ import { DispatchClient } from "@legion/envoy-client/dispatch-http"
25
28
  import { sessionDirectory as dispatchSessionDirectory } from "@legion/envoy-client/dispatch-session-directory"
26
29
  import { writeSessionTitle } from "@legion/envoy-client/dispatch-session-state"
27
30
  import { subscriptionRemovedTopics } from "@legion/envoy-client/dispatch-subscribe"
@@ -84,9 +87,11 @@ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
84
87
  import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js"
85
88
  import { connect } from "nats"
86
89
  import { z } from "zod"
90
+ import type { ModContentBlock, ModEvent } from "../hooks/mod-protocol"
87
91
  import { name as packageName, version as packageVersion } from "../package.json" with {
88
92
  type: "json",
89
93
  }
94
+ import { type AgentStreamRunner, startAgentStream } from "./agent-stream-runner"
90
95
  import {
91
96
  type ChannelForwarder,
92
97
  type ChannelForwarderConnection,
@@ -95,9 +100,9 @@ import {
95
100
  createChannelForwarder,
96
101
  deliveryIdentity,
97
102
  } from "./channel-forwarder"
98
- import { type ChannelGate, detectClaudeChannel, installedPluginVersion } from "./claude-channel"
99
103
  import { claudeProjectDirectory, claudeSessionId, configuredValue } from "./claude-session"
100
104
  import { inboundOffChannelSession, serveEnvoyOff } from "./envoy-off"
105
+ import { installedPluginVersion } from "./installed-build"
101
106
  import {
102
107
  endPane,
103
108
  type LegionClaim,
@@ -120,6 +125,8 @@ import {
120
125
  type LegionToolRuntime,
121
126
  legionToolDefinition,
122
127
  } from "./legion-tool"
128
+ import { type ModLink, startModLink } from "./mod-link"
129
+ import { type ModSession, modSession } from "./mod-session"
123
130
  import {
124
131
  type ReplayStateFile,
125
132
  type ReplayStateWriter,
@@ -145,14 +152,24 @@ import {
145
152
  touchStateFile,
146
153
  } from "./session-state"
147
154
  import { type SessionTitle, sessionTitle } from "./session-title"
155
+ import {
156
+ createUserTurnRouter,
157
+ type UserTurnRouter,
158
+ type UserTurnRouterOptions,
159
+ } from "./user-turn-router"
160
+ import {
161
+ pruneStaleSessionTurns,
162
+ readUserTurnState,
163
+ type UserTurnState,
164
+ userTurnState,
165
+ userTurnStateFile,
166
+ } from "./user-turn-state"
148
167
 
149
- const CHANNEL_NOTIFICATION_METHOD = "notifications/claude/channel" as const
150
168
  const CHANNEL_INSTRUCTIONS =
151
- "Envoy delivers trusted, internal session and Dispatch events as <channel> messages. The content is rendered Envoy state; producer identifies its Envoy producer (source is the channel name), topic is the NATS subject, event_id identifies this delivery, dedupe_key is the dedupe identity (a repeat of one already delivered is not shown again), urgency is how soon the sender asks you to act (it does not change when or in what order deliveries arrive), from_session identifies the origin session, and reply metadata names any correlation. Use the Envoy tools for Envoy actions, and reach Dispatch through the `dispatch` command in Bash (`dispatch --help` lists its commands; the `dispatch` skill teaches them). Dispatch asks stay on Dispatch. This channel advertises Aside only: it does not support targeted BTW delivery or permission relay."
169
+ "Envoy delivers trusted, internal session and Dispatch events into this conversation. Use the Envoy tools for Envoy actions, and reach Dispatch through the `dispatch` command in Bash (`dispatch --help` lists its commands; the `dispatch` skill teaches them). Dispatch asks stay on Dispatch."
152
170
  const CHANNEL_INBOX_LIMIT = 50
153
171
  const EMPTY_RECEIPT = new Uint8Array()
154
172
  const encoder = new TextEncoder()
155
- const ChannelMetaKey = /^[A-Za-z_][A-Za-z0-9_]*$/
156
173
  /** How often the handoff file is checked for a `/clear`. */
157
174
  const HANDOFF_POLL_MS = 250
158
175
  /** How long a handoff waits for NATS to confirm the new direct subject before retrying. */
@@ -188,17 +205,35 @@ function undefinedOnNotFound(error: unknown): undefined {
188
205
  export const MCP_SERVER_INFO = { name: "envoy", version: packageVersion } as const
189
206
 
190
207
  /**
191
- * The delivery modes a session whose deliveries are channel notifications advertises: Claude Code
192
- * queues a notification for the model's next turn, which is an aside and cannot be a steer.
208
+ * What a session takes, which Dispatch checks every targeted delivery against.
209
+ *
210
+ * A terminal session reaches the model only through its mod (`./mod-session`): until one
211
+ * connects no message reaches the model at all, so it advertises nothing and Dispatch refuses a
212
+ * message to it rather than reporting it delivered; with one it takes an Aside, a Send and the
213
+ * side turn a BTW is. A Legion pane's messages go through the bridge's inbox, which needs no mod
214
+ * (`INBOX_CAPABILITIES`), and it gains the BTW when the mod connects.
193
215
  */
194
- export const CHANNEL_CAPABILITIES = ["aside"] as const satisfies readonly DeliveryCapability[]
216
+ export function sessionCapabilities(session: {
217
+ readonly pane: boolean
218
+ readonly mod: boolean
219
+ }): readonly DeliveryCapability[] {
220
+ if (!session.pane) return session.mod ? DELIVERY_CAPABILITIES : []
221
+ return session.mod ? [...INBOX_CAPABILITIES, "btw"] : INBOX_CAPABILITIES
222
+ }
195
223
 
224
+ /**
225
+ * One line this server writes into the session: a rendered Envoy delivery, a replayed one, or a
226
+ * notice of Envoy's own. Claude Code took these as `<channel>` messages until INFRA-1026 removed
227
+ * that channel; what writes them now is the session's own conversation, through the mod
228
+ * (`./mod-session`) or, in a Legion pane, the bridge's inbox (`./legion-inbox`).
229
+ */
196
230
  export interface ChannelNotification {
197
- readonly method: typeof CHANNEL_NOTIFICATION_METHOD
198
- readonly params: {
199
- readonly content: string
200
- readonly meta: Readonly<Record<string, string>>
201
- }
231
+ readonly content: string
232
+ /** The envelope this line is, where it is one: the id the Legion bridge answers it by. */
233
+ readonly eventId?: string
234
+ /** `content` as Claude Code's own blocks, where a line carries more than its text (a person's
235
+ * pictures); the text alone is still `content`, for a reader that does not know the field. */
236
+ readonly blocks?: readonly ModContentBlock[]
202
237
  }
203
238
 
204
239
  export interface ChannelNotifier {
@@ -221,7 +256,8 @@ export interface ChannelDelivery {
221
256
  * Queue one rendered envelope onto the notifier, behind every frame queued before it. Resolves
222
257
  * whether it went to Claude Code, once the notifier resolved its write: `false` for a frame
223
258
  * skipped, dropped, suppressed, or answered on Dispatch with an error instead (once that reply
224
- * is posted). `late` is a relay frame delivered before or stored before the current epoch
259
+ * is posted), and `true` without a write for an event whose card the session already has.
260
+ * `late` is a relay frame delivered before or stored before the current epoch
225
261
  * (`ConsumerFrame.late`): a late BTW is suppressed, as a replayed one is.
226
262
  */
227
263
  enqueue(input: {
@@ -234,9 +270,9 @@ export interface ChannelDelivery {
234
270
  }
235
271
 
236
272
  /**
237
- * The channel delivery of a running session, which also shows what replay recovers
238
- * (`@legion/envoy-client/replay`), on the same notifier as a live frame: the channel notification,
239
- * or the Legion bridge's inbox.
273
+ * The delivery path of a running session, which also shows what replay recovers
274
+ * (`@legion/envoy-client/replay`), on the same notifier as a live frame: the mod's write into
275
+ * the conversation, or the Legion bridge's inbox.
240
276
  */
241
277
  export interface ChannelDeliveryPath extends ChannelDelivery {
242
278
  /**
@@ -268,6 +304,21 @@ export interface ChannelSession {
268
304
  * ready again from it. The hook runs detached from the heartbeat; a rejection is logged.
269
305
  */
270
306
  onRoleRegained(hook: RoleRegainHook): void
307
+ /**
308
+ * The session's advertised delivery modes have changed (`ChannelSessionOptions.capabilities` is
309
+ * read again): register, so Dispatch learns what the session takes now. A terminal session
310
+ * advertises nothing until its mod connects, which is the change this exists for.
311
+ */
312
+ capabilitiesChanged(): void
313
+ /**
314
+ * Takes one of the mod's events, in the order the link yielded them, for the router of a
315
+ * person's messages (`./user-turn-router`). The live view owns the link's one event stream and
316
+ * hands each event over.
317
+ */
318
+ observe(event: ModEvent): void
319
+ /** The Dispatch message a delivered row of the conversation is, or undefined for a row of the
320
+ * session's own: what tags that row on the live view's frames. */
321
+ messageOf(row: string): string | undefined
271
322
  /** Drain NATS, deregister this listener route, and release timer resources. */
272
323
  shutdown(): Promise<void>
273
324
  }
@@ -278,10 +329,19 @@ export interface ChannelSessionOptions {
278
329
  readonly notifier: ChannelNotifier
279
330
  /**
280
331
  * The delivery modes the session advertises to the listener, which Dispatch checks every
281
- * targeted delivery against: the ones `notifier` honours (`CHANNEL_CAPABILITIES`, or
282
- * `INBOX_CAPABILITIES` for the Legion bridge's inbox).
332
+ * targeted delivery against. Read at each registration rather than once, because what the
333
+ * session can take changes while it runs: a terminal session takes nothing until its mod
334
+ * connects, and a Legion pane gains `btw` when it does. The owner says so with
335
+ * `ChannelSession.capabilitiesChanged`.
283
336
  */
284
- readonly capabilities: readonly DeliveryCapability[]
337
+ readonly capabilities: () => readonly DeliveryCapability[]
338
+ /**
339
+ * The router a person's messages go through (`./user-turn-router`), built for the record of
340
+ * the session id now bound: at startup, and again whenever a `/clear` moves the session to
341
+ * another id, since that record is kept per session id (`./user-turn-state`). Omitted, every
342
+ * frame arrives as the card it renders as.
343
+ */
344
+ readonly router?: (state: UserTurnState) => UserTurnRouter
285
345
  readonly client: Pick<
286
346
  EnvoyClient,
287
347
  | "subscribe"
@@ -398,26 +458,17 @@ class UnsupportedEnvoyToolError extends Error {
398
458
  }
399
459
  }
400
460
 
401
- /** Claude Code silently drops invalid keys, so remove them before writing a notification. */
402
- export function sanitizeChannelMetadata(
403
- metadata: Readonly<Record<string, string | undefined>>,
404
- ): Record<string, string> {
405
- const sanitized: Record<string, string> = {}
406
- for (const [key, value] of Object.entries(metadata)) {
407
- if (value !== undefined && ChannelMetaKey.test(key)) sanitized[key] = value
408
- }
409
- return sanitized
410
- }
411
-
412
461
  /**
413
- * Answer a targeted Dispatch delivery this session could not honour, so the
414
- * sender sees the attempt fail instead of waiting on a reply that never comes.
462
+ * Answer a targeted Dispatch delivery, on the sender's behalf: the reply this session has for it,
463
+ * or the error that stopped it, so the sender sees the attempt fail instead of waiting on a reply
464
+ * that never comes. `followUp` asks Dispatch to post an answer to an attempt its first reply
465
+ * already settled, which every answer after the first needs (`postDeliveryReply`).
415
466
  */
416
- async function postDispatchReply(
467
+ export async function postDispatchReply(
417
468
  identity: SessionIdentity,
418
469
  configFile: SessionConfigFile,
419
470
  delivery: DispatchDelivery,
420
- result: { readonly error: string },
471
+ result: { readonly body?: string; readonly error?: string; readonly followUp?: boolean },
421
472
  ): Promise<void> {
422
473
  const config = sessionDispatchSettings(configFile, process.env, {
423
474
  cwd: identity.directory,
@@ -428,73 +479,89 @@ async function postDispatchReply(
428
479
  }
429
480
 
430
481
  /**
431
- * Render inbound Envoy envelopes through the shared renderer and write them to the notifier one at
432
- * a time, in the order they were queued. A frame's promise resolves once the notifier resolved its
433
- * write: in a Legion pane, once the bridge answered that Claude Code took the message into a step;
434
- * in channel mode, once the MCP transport took the `notifications/claude/channel` write, the
435
- * strongest signal Claude Code gives there (it acknowledges no notification).
482
+ * Render inbound Envoy envelopes through the shared renderer and hand each one to the session,
483
+ * one at a time, in the order they were queued.
484
+ *
485
+ * A frame a person's own message, command, pick or BTW (`router`, `./user-turn-router`) is taken
486
+ * by the router and nothing is written as a card; everything else is written to the notifier as
487
+ * the rendered card it is, which names its sender. A frame's promise resolves once the session
488
+ * has it: in a Legion pane, once the bridge answered that Claude Code took the message into a
489
+ * step; in a terminal session, once the mod stored the row.
490
+ *
491
+ * Routing runs in the same queue as the writes, so a person's message and the cards around it
492
+ * reach the session in the order they arrived. A frame whose write the session never confirmed
493
+ * is left unanswered, so Envoy sends it again and the mod writes it once (`./mod-session`).
436
494
  */
437
495
  export function createChannelDelivery(input: {
438
496
  readonly identity: SessionIdentity
439
497
  readonly notifier: ChannelNotifier
440
498
  /** The session's envoy.json, which a rejected Dispatch frame's reply reads. */
441
499
  readonly configFile: SessionConfigFile
500
+ /** What a person's own message, command, pick or BTW becomes; omitted, every frame is a card. */
501
+ readonly router?: () => UserTurnRouter | undefined
442
502
  }): ChannelDeliveryPath {
443
503
  const inbox: ChannelInboxEntry[] = []
444
504
  let tail = Promise.resolve()
445
505
 
446
- const queue = (notification: ChannelNotification): Promise<void> => {
447
- const queued = tail.then(() => input.notifier.notification(notification))
448
- tail = queued.catch((error: unknown) => {
449
- process.stderr.write(`envoy-channel: channel notification failed — ${messageFor(error)}\n`)
450
- })
451
- return queued
506
+ /** Runs `work` behind everything queued before it, keeping the frames in order. */
507
+ const queued = <T>(work: () => Promise<T>): Promise<T> => {
508
+ const run = tail.then(work)
509
+ tail = run.then(
510
+ () => undefined,
511
+ (error: unknown) => {
512
+ process.stderr.write(`envoy-channel: a delivery failed — ${messageFor(error)}\n`)
513
+ },
514
+ )
515
+ return run
452
516
  }
453
517
 
454
- /** Lists a rendered frame in the inbox and queues `content` for it. */
455
- const show = (rendered: RenderInboundResult, subject: string, content: string): Promise<void> => {
518
+ const write = (notification: ChannelNotification): Promise<void> =>
519
+ queued(() => input.notifier.notification(notification))
520
+
521
+ /** Lists a rendered frame in the inbox, naming one Envoy event once: the server is
522
+ * at-least-once, so the copy Envoy sends after an unanswered frame is written to the session
523
+ * again — where the mod's record keeps it from reaching the engine twice (`./mod-session`) —
524
+ * and a person reading the inbox is owed the message, not the attempts.
525
+ *
526
+ * A frame with no `event_id` names no event, so it is always listed: two such frames are two
527
+ * messages. A record that keyed them all by the word the entry shows instead — `unknown` —
528
+ * listed the first and dropped every later one, while the session was written all of them
529
+ * (INFRA-1026 review). The inbox is its own record now: a frame is skipped only where its
530
+ * real id is already in it, which takes the insertions and the bound that record took. */
531
+ const list = (rendered: RenderInboundResult): void => {
456
532
  const envelope = rendered.envelope
457
- if (envelope !== undefined) {
458
- inbox.unshift({
459
- event_id: envelope.event_id ?? "unknown",
460
- at: inboundTimestamp(envelope.issued_at),
461
- from: envelope.source_session ?? envelope.source,
462
- summary: envelope.payload_summary ?? "unknown",
463
- })
464
- if (inbox.length > CHANNEL_INBOX_LIMIT) inbox.pop()
465
- }
466
- return queue({
467
- method: CHANNEL_NOTIFICATION_METHOD,
468
- params: {
469
- content,
470
- // Claude Code stamps its own `source="<channel name>"` attribute on the
471
- // <channel> tag, so the Envoy producer travels under `producer`.
472
- meta: sanitizeChannelMetadata({
473
- producer: envelope?.source ?? "unknown",
474
- // A forward on the agent subject (a role message, or an ad-hoc topic's copy the
475
- // publish route confirms with this session) carries the topic it was published to.
476
- topic: envelope?.topic || subject,
477
- event_id: envelope?.event_id,
478
- dedupe_key: envelope?.dedupe_key,
479
- urgency: envelope?.urgency,
480
- from_session: envelope?.source_session,
481
- // One vocabulary for the inbox: the inbound schema reads a frame old enough to carry
482
- // the string "none" as `false`, and the metadata carries that one spelling.
483
- expects_reply: envelope?.expects_reply?.toString(),
484
- in_reply_to: envelope?.in_reply_to,
485
- }),
486
- },
533
+ if (envelope === undefined) return
534
+ const eventId = envelope.event_id
535
+ if (eventId !== undefined && inbox.some((entry) => entry.event_id === eventId)) return
536
+ inbox.unshift({
537
+ event_id: eventId ?? "unknown",
538
+ at: inboundTimestamp(envelope.issued_at),
539
+ from: envelope.source_session ?? envelope.source,
540
+ summary: envelope.payload_summary ?? "unknown",
487
541
  })
542
+ if (inbox.length > CHANNEL_INBOX_LIMIT) inbox.pop()
543
+ }
544
+
545
+ /** The notification a rendered frame is, as `content`: the line, and the envelope's id where
546
+ * it has one, which is what the Legion bridge answers the line by. */
547
+ const notification = (rendered: RenderInboundResult, content: string): ChannelNotification => ({
548
+ content,
549
+ ...(rendered.envelope?.event_id === undefined ? {} : { eventId: rendered.envelope.event_id }),
550
+ })
551
+
552
+ /** Lists a rendered frame and writes `content` into the session as the card it is. */
553
+ const show = (rendered: RenderInboundResult, content: string): Promise<void> => {
554
+ list(rendered)
555
+ return write(notification(rendered, content))
488
556
  }
489
557
 
490
- // A BTW never starts a turn here. The listener sends one only to a session that advertises
491
- // `btw`, which this one never does, and neither delivery path can show a message without
492
- // starting a turn (the Legion bridge's inbox starts one when Claude Code is idle). So a BTW that
493
- // arrives replayed or late anyway is passed over, named on stderr.
558
+ // A replayed or late BTW is never answered: the question was asked while this session was not
559
+ // taking messages, and Dispatch has long since recorded the attempt. Only a live one runs
560
+ // (`./user-turn-router`).
494
561
  const passOverBtw = (rendered: RenderInboundResult, how: "replayed" | "late"): boolean => {
495
562
  if (rendered.delivery?.mode !== "btw") return false
496
563
  process.stderr.write(
497
- `envoy-channel: passing over ${how} BTW ${rendered.envelope?.event_id ?? "unknown"}: a BTW never starts a turn\n`,
564
+ `envoy-channel: passing over ${how} BTW ${rendered.envelope?.event_id ?? "unknown"}: it was asked while this session was not taking messages\n`,
498
565
  )
499
566
  return true
500
567
  }
@@ -530,20 +597,35 @@ export function createChannelDelivery(input: {
530
597
  return tail.then(() => false)
531
598
  }
532
599
  if (late === true && passOverBtw(rendered, "late")) return tail.then(() => false)
533
- return show(rendered, subject, rendered.content).then(() => true)
600
+ return queued(async () => {
601
+ // A message Dispatch accepted as this session's own turn is never also a card. A failure
602
+ // after that acceptance throws, so the frame is not answered and the listener sends it
603
+ // again, rather than a person's message vanishing into a delivery nobody kept.
604
+ const routed = await input.router?.()?.route(rendered)
605
+ if (routed === true) {
606
+ list(rendered)
607
+ return true
608
+ }
609
+ // Written here rather than through `write`: this already runs inside the queue, and
610
+ // `write` would wait on a tail this call is itself the end of. A write that failed
611
+ // throws, so the frame goes unanswered and Envoy sends the event again; the mod writes
612
+ // the message of one event id once, however many copies of it arrive
613
+ // (`../hooks/mod-writer.ts`, `writeOnce`), so the resend costs the model nothing and the
614
+ // listener's copy is the only one that can still reach it.
615
+ await input.notifier.notification(notification(rendered, rendered.content))
616
+ list(rendered)
617
+ return true
618
+ })
534
619
  },
535
620
  async replay(frame) {
536
621
  const rendered = renderInbound(frame.data, input.identity.id, frame.subject)
537
622
  if (replaySuppressed(rendered)) return "suppressed"
538
623
  if (passOverBtw(rendered, "replayed")) return "suppressed"
539
- await show(rendered, frame.subject, replayedText(rendered.content, frame.time))
624
+ await show(rendered, replayedText(rendered.content, frame.time))
540
625
  return "shown"
541
626
  },
542
627
  notice(content) {
543
- return queue({
544
- method: CHANNEL_NOTIFICATION_METHOD,
545
- params: { content, meta: { producer: "envoy" } },
546
- })
628
+ return write({ content })
547
629
  },
548
630
  inbox() {
549
631
  return [...inbox]
@@ -586,10 +668,20 @@ export async function enqueueChannelMessage(
586
668
  export async function startChannelSession(options: ChannelSessionOptions): Promise<ChannelSession> {
587
669
  const { identity } = options
588
670
  let directSubject = agentSubject(identity.id)
671
+ /**
672
+ * What this session does with a person's direct messages, for the id now bound: the record is
673
+ * kept per session id (`./user-turn-state`), so a `/clear` builds another one. Undefined until
674
+ * the record is loaded, and for a session the owner gave no router.
675
+ */
676
+ let router: UserTurnRouter | undefined
677
+ /** The record the router above reads and writes, kept so a shutdown can wait for its writes
678
+ * and so the live view can read which Dispatch message a row is (`messageOf`). */
679
+ let turns: UserTurnState | undefined
589
680
  const delivery = createChannelDelivery({
590
681
  identity,
591
682
  notifier: options.notifier,
592
683
  configFile: options.configFile,
684
+ router: () => router,
593
685
  })
594
686
  const userTopics = new Set<string>()
595
687
  let heldRole: string | undefined
@@ -773,6 +865,30 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
773
865
  return rememberedTopics(snapshot.state)
774
866
  }
775
867
 
868
+ /**
869
+ * Builds the router of a person's messages for the id now bound, on the record that id's file
870
+ * holds: at startup, and again after a `/clear`, since no attempt of the id left behind may be
871
+ * spent under the new one. A record that cannot be read leaves the session with none, and
872
+ * every frame then arrives as the card it renders as: taking a person's message as their own
873
+ * turn needs the record of which attempts this session has already spent, and without it an
874
+ * attempt could be accepted twice.
875
+ */
876
+ const restoreTurns = async (): Promise<void> => {
877
+ router = undefined
878
+ turns = undefined
879
+ if (options.router === undefined) return
880
+ const file = userTurnStateFile(options.stateDirectory, identity.id)
881
+ const restored = await readUserTurnState(file).catch((error: unknown) => {
882
+ process.stderr.write(
883
+ `envoy-channel: could not read this session's record of the messages it took (${messageFor(error)}); its messages arrive as cards\n`,
884
+ )
885
+ return undefined
886
+ })
887
+ if (restored === undefined) return
888
+ turns = userTurnState(file, restored)
889
+ router = options.router(turns)
890
+ }
891
+
776
892
  /** A sweep runs on the engine's own chain, never in the registry's. */
777
893
  const triggerReplay = (): void => {
778
894
  if (!shuttingDown) void replay.sweep()
@@ -1098,7 +1214,7 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
1098
1214
  topics,
1099
1215
  port: 0,
1100
1216
  title,
1101
- capabilities: options.capabilities,
1217
+ capabilities: options.capabilities(),
1102
1218
  driving: false,
1103
1219
  selfSubscribed: true,
1104
1220
  clientInstanceID: options.clientInstanceID,
@@ -1383,6 +1499,9 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
1383
1499
  // nothing, and the old id's sweep in flight writes nothing more. Loading it closes the old
1384
1500
  // id's relay (its unanswered frames `nak`) and subscribes the new id's relay subject.
1385
1501
  await restoreReplay()
1502
+ // The new id takes a record of its own: an attempt the old id handled is the old id's, and
1503
+ // the rows of a conversation a `/clear` ended name nothing in the new one.
1504
+ await restoreTurns()
1386
1505
  roleTransferFrom ??= previous
1387
1506
  // The new relay subject reaches the server before the registration that asks for it. Not
1388
1507
  // fatal: a relayed frame nobody answers pauses the relay, which sends again after its backoff
@@ -1581,6 +1700,9 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
1581
1700
  // (ten minutes after it stopped) still follows them, and its sweep still reads them. Its relay
1582
1701
  // comes with it too, restored and subscribed before the first registration asks for it.
1583
1702
  const remembered = await restoreReplay()
1703
+ // What this session has already done with the messages Dispatch sent it, before any frame can
1704
+ // arrive: an attempt a process before this one spent must not be spent again.
1705
+ await restoreTurns()
1584
1706
  // The NATS subscription precedes registration so the listener never routes
1585
1707
  // a direct delivery to an advertised but deaf channel process.
1586
1708
  forwarder.follow(directSubject)
@@ -1646,6 +1768,7 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
1646
1768
  for (const prune of [
1647
1769
  () => pruneStaleSessionHandoffs(options.stateDirectory),
1648
1770
  () => pruneStaleSessionTitles(options.stateDirectory),
1771
+ () => pruneStaleSessionTurns(options.stateDirectory),
1649
1772
  // The role sweep is told whose session this is: see `pruneStaleSessionRoles`.
1650
1773
  () => pruneStaleSessionRoles(options.stateDirectory, identity.id),
1651
1774
  ]) {
@@ -1727,6 +1850,21 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
1727
1850
  onRoleRegained(hook) {
1728
1851
  regained = hook
1729
1852
  },
1853
+ capabilitiesChanged() {
1854
+ if (shuttingDown) return
1855
+ // The same path a reconnect takes: one more registration, behind whatever is queued.
1856
+ serialized(register).catch((error: unknown) => {
1857
+ process.stderr.write(
1858
+ `envoy-channel: could not advertise this session's delivery modes (${messageFor(error)}); the next heartbeat retries\n`,
1859
+ )
1860
+ })
1861
+ },
1862
+ observe(event) {
1863
+ router?.observe(event)
1864
+ },
1865
+ messageOf(row) {
1866
+ return turns?.messageOf(row)
1867
+ },
1730
1868
  async rememberRole(role) {
1731
1869
  heldRole = role
1732
1870
  await writeRoleRecord(roleStateFile(options.stateDirectory, identity.id), role)
@@ -1756,8 +1894,10 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
1756
1894
  `envoy-channel: session deregistration failed — ${messageFor(error)}\n`,
1757
1895
  )
1758
1896
  })
1759
- // What was written meanwhile (a resume point, a ledger record) lands before the process goes.
1897
+ // What was written meanwhile (a resume point, a ledger record, a message taken) lands
1898
+ // before the process goes.
1760
1899
  await stateWriter?.idle()
1900
+ await turns?.idle()
1761
1901
  // The handoff directory stays: Claude Code restarts this server inside the
1762
1902
  // same `claude` process (plugin reload, changed config), and the hook does
1763
1903
  // not rewrite the file until the next SessionStart. Startup pruning removes
@@ -1996,35 +2136,18 @@ export async function runEnvoyChannelServer(): Promise<void> {
1996
2136
  directory,
1997
2137
  )
1998
2138
  const stateDirectory = pluginStateDirectory()
1999
- // The Legion bridge's inbox takes the events itself; otherwise they go to Claude Code's channel.
2139
+ // In a Legion pane a person's message goes to the bridge's inbox, which makes it a user turn;
2140
+ // in a terminal session everything this server writes goes through the mod.
2000
2141
  const inboxSocket = configuredValue(process.env[INBOX_VARIABLE])
2001
2142
  // The plugin's own bundle, which Claude Code runs from its plugin cache when installed.
2002
2143
  const bundlePath = process.argv[1] ?? ""
2003
2144
  // One connection to the bridge carries every line this server writes into the session: each
2004
2145
  // Envoy delivery, and the reminders and notices the phase endpoint writes.
2005
2146
  const inbox = inboxSocket === undefined ? undefined : createInboxNotifier(inboxSocket)
2006
- // Claude Code drops a notification from a channel it did not load without telling this server,
2007
- // so such a session advertises no delivery mode and Dispatch refuses a message to it rather than
2008
- // reporting it delivered. The bridge's inbox needs no channel.
2009
- const channel: ChannelGate =
2010
- inboxSocket === undefined
2011
- ? detectClaudeChannel({
2012
- claudePid: process.ppid,
2013
- bundlePath,
2014
- environment: process.env,
2015
- })
2016
- : { loaded: true }
2017
- if (!channel.loaded) {
2018
- process.stderr.write(
2019
- `envoy-channel: Claude Code did not load this server as a channel: ${channel.why}; the session advertises no delivery mode, so Dispatch refuses messages to it instead of losing them\n`,
2020
- )
2021
- }
2022
2147
 
2023
2148
  const server = new Server(MCP_SERVER_INFO, {
2024
- capabilities: { tools: {}, experimental: { "claude/channel": {} } },
2025
- instructions: channel.loaded
2026
- ? CHANNEL_INSTRUCTIONS
2027
- : `${CHANNEL_INSTRUCTIONS} Claude Code did not load this channel for this session (${channel.why}), so no Envoy event or Dispatch message reaches you as a <channel> message, and the session advertises no delivery mode; envoy_inbox still lists what arrived.`,
2149
+ capabilities: { tools: {} },
2150
+ instructions: CHANNEL_INSTRUCTIONS,
2028
2151
  })
2029
2152
  const client = createEnvoyClient({
2030
2153
  baseUrl: envoy.url,
@@ -2057,14 +2180,7 @@ export async function runEnvoyChannelServer(): Promise<void> {
2057
2180
  booted: claimBooted.promise,
2058
2181
  readState: (signal) => daemon.state({ signal }),
2059
2182
  reportActivity: (input) => daemon.activity(input),
2060
- inbox:
2061
- inbox === undefined
2062
- ? undefined
2063
- : (text) =>
2064
- inbox.notification({
2065
- method: CHANNEL_NOTIFICATION_METHOD,
2066
- params: { content: text, meta: {} },
2067
- }),
2183
+ inbox: inbox === undefined ? undefined : (text) => inbox.notification({ content: text }),
2068
2184
  publish: client.publish,
2069
2185
  env: process.env,
2070
2186
  log: phaseLog,
@@ -2105,24 +2221,58 @@ export async function runEnvoyChannelServer(): Promise<void> {
2105
2221
  if (runtime === undefined) throw new Error("Envoy channel server is still starting")
2106
2222
  return mcpResult(await executeEnvoyTool(runtime, request.params.name, request.params.arguments))
2107
2223
  })
2108
- // The endpoint is told every line this server writes for a delivery: the `UserPromptSubmit`
2109
- // that carries one back is that delivery's turn, not a fresh assignment, and this server, which
2110
- // writes them all, is the only place that knows.
2224
+ // INFRA-1026: the link to this session's Claude Code mod, bound below once the MCP transport is
2225
+ // up. It is this process's own socket, closed with the server. `linked` resolves with it for
2226
+ // the live view, which also needs the NATS connection this function opens further down.
2227
+ let modLink: ModLink | undefined
2228
+ const linked = Promise.withResolvers<ModLink>()
2229
+ // The Agents page's live view of this session, once both the link and the connection are up.
2230
+ let agentStream: AgentStreamRunner | undefined
2231
+ // The session itself, as this server drives it (`./mod-session`). The link binds after this
2232
+ // server starts and can fail to bind at all, so every call goes through the holder above: a
2233
+ // session with no mod answers none of them, which is what "no mod" means here.
2234
+ const claude: ModSession = modSession({
2235
+ link: {
2236
+ request: (call, args, requestOptions) => {
2237
+ const link = modLink
2238
+ if (link === undefined) {
2239
+ return Promise.reject(new Error("this session has no link to Claude Code"))
2240
+ }
2241
+ return link.request(call, args, requestOptions)
2242
+ },
2243
+ connected: () => modLink?.connected() === true,
2244
+ },
2245
+ warn: (text) => process.stderr.write(`envoy-channel: ${text}\n`),
2246
+ })
2247
+ // Every line this server writes into the session: the bridge's inbox in a Legion pane, and the
2248
+ // mod's own write in a terminal session, which is a row of the turn running and the prompt of
2249
+ // a new turn while the session is idle (`ModSession.show`), since an appended row an idle
2250
+ // session never reads would wait for the person to type. The endpoint is told every line
2251
+ // written for a delivery: the `UserPromptSubmit` that carries one back is that delivery's
2252
+ // turn, not a fresh assignment, and this server, which writes them all, is the only place
2253
+ // that knows.
2254
+ const writer: ChannelNotifier = inbox ?? {
2255
+ notification: async ({ content, blocks, eventId }) => {
2256
+ await claude.show({
2257
+ content: blocks ?? [{ type: "text", text: content }],
2258
+ text: content,
2259
+ // The Envoy event this line is, where it is one: what the mod's write is idempotent by,
2260
+ // so the copy Envoy sends after an unanswered frame is written once (`./mod-session`).
2261
+ ...(eventId === undefined ? {} : { eventId }),
2262
+ })
2263
+ },
2264
+ }
2111
2265
  const notifier: ChannelNotifier =
2112
- inbox === undefined
2113
- ? server
2114
- : phaseHook === undefined
2115
- ? inbox
2116
- : {
2117
- notification: async (notification) => {
2118
- phaseHook.deliveryWritten(notification.params.content)
2119
- await inbox.notification(notification)
2120
- },
2121
- }
2122
- // A session whose deliveries are channel notifications Claude Code did not load shows the model
2123
- // nothing, so it advertises no delivery mode at all.
2124
- const capabilities =
2125
- inboxSocket !== undefined ? INBOX_CAPABILITIES : channel.loaded ? CHANNEL_CAPABILITIES : []
2266
+ phaseHook === undefined
2267
+ ? writer
2268
+ : {
2269
+ notification: async (notification) => {
2270
+ phaseHook.deliveryWritten(notification.content)
2271
+ await writer.notification(notification)
2272
+ },
2273
+ }
2274
+ const capabilities = (): readonly DeliveryCapability[] =>
2275
+ sessionCapabilities({ pane: inboxSocket !== undefined, mod: modLink?.connected() === true })
2126
2276
  const booting = new AbortController()
2127
2277
 
2128
2278
  const stopped = Promise.withResolvers<void>()
@@ -2134,6 +2284,8 @@ export async function runEnvoyChannelServer(): Promise<void> {
2134
2284
  booting.abort()
2135
2285
  // A reminder waiting on a 15-minute WAITING wait holds no shutting-down server open.
2136
2286
  phaseHook?.stop()
2287
+ void modLink?.close().catch(() => undefined)
2288
+ agentStream?.stop()
2137
2289
  if (session === undefined) {
2138
2290
  stopped.resolve()
2139
2291
  return
@@ -2147,6 +2299,59 @@ export async function runEnvoyChannelServer(): Promise<void> {
2147
2299
  // `tmux kill-session` hangs us up directly; deregister instead of dying.
2148
2300
  process.once("SIGHUP", stop)
2149
2301
  await server.connect(new StdioServerTransport())
2302
+ // The mod (`../hooks/mod.ts`) probes this socket from its own `session.start` and gives up
2303
+ // after about half a minute, so it is bound as early as the transport allows. Started, not
2304
+ // awaited: the transport is already reading stdin, and an await here would let the client's
2305
+ // first tool call arrive before the session below exists. A session whose link cannot bind
2306
+ // runs exactly as it does today, the mod finding nothing and staying silent.
2307
+ void startModLink({
2308
+ // The id Claude Code gave this process, which is what the mod reads as `$.session.id()`;
2309
+ // the ENVOY_SESSION_ID override names an Envoy identity, never a Claude Code session.
2310
+ sessionId: claudeSessionId({ CLAUDE_CODE_SESSION_ID: process.env["CLAUDE_CODE_SESSION_ID"] }),
2311
+ env: process.env,
2312
+ warn: (text) => process.stderr.write(`envoy-channel: ${text}\n`),
2313
+ }).then(
2314
+ (link) => {
2315
+ modLink = link
2316
+ // The server was already stopping when the bind finished: nothing will read this link.
2317
+ if (stopping) void link.close().catch(() => undefined)
2318
+ else linked.resolve(link)
2319
+ },
2320
+ (error: unknown) => {
2321
+ process.stderr.write(
2322
+ `envoy-channel: no link to this session's Claude Code mod — ${messageFor(error)}; the session runs on without one\n`,
2323
+ )
2324
+ },
2325
+ )
2326
+
2327
+ /**
2328
+ * The router of a person's messages, built again for each session id the session binds
2329
+ * (`ChannelSessionOptions.router`). Everything it needs that does not move with the id - the
2330
+ * Claude Code session, Dispatch, where a pane's message goes - is this process's.
2331
+ */
2332
+ const router = (state: UserTurnState): UserTurnRouter => {
2333
+ const options: UserTurnRouterOptions = {
2334
+ dispatch: (ms) => {
2335
+ const active = activeDispatchSettings(
2336
+ sessionDispatchSettings(configFile, process.env, { cwd: directory }).dispatch,
2337
+ )
2338
+ return active === null
2339
+ ? undefined
2340
+ : new DispatchClient(active.url, active.credential, fetch, AbortSignal.timeout(ms))
2341
+ },
2342
+ effortPicked: (effort) => agentStream?.pickedEffort(effort),
2343
+ refreshSettings: () => agentStream?.refresh(),
2344
+ reply: (delivery, result) => postDispatchReply(identity, configFile, delivery, result),
2345
+ session: claude,
2346
+ sessionId: () => identity.id,
2347
+ state,
2348
+ warn: (text) => process.stderr.write(`envoy-channel: ${text}\n`),
2349
+ // A pane's person message is a line of the bridge's inbox, which makes it a user turn;
2350
+ // the phase endpoint is told of it as it is told of every line this server writes.
2351
+ ...(inboxSocket === undefined ? {} : { inbox: (input) => notifier.notification(input) }),
2352
+ }
2353
+ return createUserTurnRouter(options)
2354
+ }
2150
2355
 
2151
2356
  let connection: ChannelForwarderConnection | undefined
2152
2357
  try {
@@ -2173,6 +2378,7 @@ export async function runEnvoyChannelServer(): Promise<void> {
2173
2378
  connection,
2174
2379
  notifier,
2175
2380
  capabilities,
2381
+ router,
2176
2382
  client,
2177
2383
  heartbeatMs: envoy.heartbeatMs,
2178
2384
  configFile,
@@ -2184,6 +2390,57 @@ export async function runEnvoyChannelServer(): Promise<void> {
2184
2390
  // The QA override names a fixed identity; only a Claude-minted id follows `/clear`.
2185
2391
  ...(configuredValue(overrideSessionId) === undefined ? { handoffPid: process.ppid } : {}),
2186
2392
  })
2393
+ // INFRA-1026: the Agents page's live view, once this session's mod has a link to bind to.
2394
+ // It needs the bus as well as the link, so it starts here rather than beside the bind; a
2395
+ // session whose link never binds never starts one, and runs as it did before.
2396
+ const bus = connection
2397
+ const live = session
2398
+ void linked.promise.then((link) => {
2399
+ if (stopping) return
2400
+ agentStream = startAgentStream({
2401
+ connection: bus,
2402
+ // Only a Claude-minted id follows `/clear`; the override names a fixed identity.
2403
+ followsSessionId: configuredValue(overrideSessionId) === undefined,
2404
+ // A pane is the session whose person messages go to the bridge's inbox, which is the
2405
+ // same signal the router reads (`inPane`): a pane holds a daemon claim only where a
2406
+ // daemon started it, and the row the bridge seeds is there either way.
2407
+ isPane: inbox !== undefined,
2408
+ link,
2409
+ sessionId: identity.id,
2410
+ // The link's events have one consumer, and two things behind it need them: the
2411
+ // session's own turn tracking, which must not ride on a router this id may have none
2412
+ // of (`restoreTurns`), and the router itself, in that order.
2413
+ observe: (event) => {
2414
+ claude.observe(event)
2415
+ live.observe(event)
2416
+ },
2417
+ // The rows this session claims as its own, each asked by the row's own id and each
2418
+ // drawn by what it is (`./agent-stream-claude`). The `observe` above runs
2419
+ // first, so the session has already claimed a row when this stream records it.
2420
+ //
2421
+ // - the echo row a command this session ran for a person claimed: the view draws
2422
+ // nothing of it, since Claude Code echoes the command it ran rather than the one
2423
+ // they sent (`claude.runsCommandRow`);
2424
+ // - the row of a prompt at the messages a turn never read, which quotes rows the
2425
+ // view has already drawn (`claude.runsUnreadPrompt`);
2426
+ // - a row this session appended, which is the one `isMeta` row the view draws: a
2427
+ // card handed to a running turn is such a row and nothing else
2428
+ // (`claude.appendedRow`).
2429
+ appendedRow: (row) => claude.appendedRow(row),
2430
+ runsCommandRow: (row) => claude.runsCommandRow(row),
2431
+ runsUnreadPrompt: (row) => claude.runsUnreadPrompt(row),
2432
+ tagFor: (row) => live.messageOf(row),
2433
+ })
2434
+ // The session takes messages once the mod is there, and says so: a terminal session
2435
+ // advertises nothing until then, and a pane gains the side turn a BTW is. A hello is
2436
+ // not enough to hear it by: the mod sends one per Claude Code process, so a server
2437
+ // Claude Code starts again inside that process gets none, and a hello that landed
2438
+ // before this listener existed is gone. So the link's own word that a mod is talking to
2439
+ // it says so too - now, if one already is (INFRA-1026 review).
2440
+ link.onSessionId(() => live.capabilitiesChanged())
2441
+ link.onConnected(() => live.capabilitiesChanged())
2442
+ if (link.connected()) live.capabilitiesChanged()
2443
+ })
2187
2444
  }
2188
2445
  runtime = { identity, client, session, clientInstanceID }
2189
2446
  if (pane !== undefined && daemon !== undefined && !stopping) {
@@ -2206,6 +2463,7 @@ export async function runEnvoyChannelServer(): Promise<void> {
2206
2463
  if (stopping) await session.shutdown()
2207
2464
  await stopped.promise
2208
2465
  } finally {
2466
+ await modLink?.close().catch(() => undefined)
2209
2467
  if (session === undefined && connection !== undefined) {
2210
2468
  await connection.drain().catch(() => undefined)
2211
2469
  await connection.close().catch(() => undefined)