@sjawhar/claude-envoy 4.15.1 → 4.15.3

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.
@@ -1,5 +1,6 @@
1
1
  import { type Stats, unwatchFile, watchFile } from "node:fs"
2
2
  import { rm } from "node:fs/promises"
3
+ import { setImmediate as nextTurn } from "node:timers/promises"
3
4
  import {
4
5
  DELIVERY_CAPABILITIES,
5
6
  type DeliveryCapability,
@@ -15,6 +16,7 @@ import {
15
16
  type ConsumerGapNotice,
16
17
  createConsumerDelivery,
17
18
  gapNoticeText,
19
+ inboundRestoredNoticeText,
18
20
  inboundUnavailable,
19
21
  inboundUnavailableNoticeText,
20
22
  registerWithRelay,
@@ -45,16 +47,6 @@ import {
45
47
  } from "@legion/envoy-client/envoy-settings"
46
48
  import { LoggableError, messageFor, natsFailureReason } from "@legion/envoy-client/errors"
47
49
  import { machineID } from "@legion/envoy-client/machine"
48
- import {
49
- natsConnectionOptions,
50
- natsDialFailure,
51
- natsServersForLog,
52
- } from "@legion/envoy-client/nats-connection"
53
- import {
54
- followNatsCredential,
55
- keepNatsCredential,
56
- type NatsCredential,
57
- } from "@legion/envoy-client/nats-credential"
58
50
  import {
59
51
  type SessionConfigFile,
60
52
  sessionConfigFile,
@@ -96,13 +88,23 @@ import { findPushedBranchHead, paneHandoffReport } from "@legion/pi-shared/hando
96
88
  import { Server } from "@modelcontextprotocol/sdk/server/index.js"
97
89
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
98
90
  import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js"
99
- import { type ConnectionOptions, connect, type NatsConnection } from "nats"
91
+ import { connect } from "nats"
100
92
  import { z } from "zod"
101
93
  import type { ModContentBlock, ModEvent } from "../hooks/mod-protocol"
102
94
  import { name as packageName, version as packageVersion } from "../package.json" with {
103
95
  type: "json",
104
96
  }
105
97
  import { type AgentStreamRunner, startAgentStream } from "./agent-stream-runner"
98
+ import {
99
+ admittingMoves,
100
+ channelReopener,
101
+ closeUnstartedConnection,
102
+ dialChannelNats,
103
+ type ReopenConnection,
104
+ type ReopenedConnection,
105
+ START_STOPPING,
106
+ sessionAdmission,
107
+ } from "./channel-connection"
106
108
  import {
107
109
  type ChannelConnection,
108
110
  type ChannelTopicSubscription,
@@ -370,6 +372,23 @@ export interface ChannelSessionOptions {
370
372
  * alone. A failed move leaves the relay closed and the next registration retries it.
371
373
  */
372
374
  readonly followSession?: () => Promise<void>
375
+ /**
376
+ * Told each `/clear` this session adopts from the handoff file, as it moves from `previous` to
377
+ * `next` (`adoptHandoff`), before the new id registers: what else the server keeps under the
378
+ * session's id moves with it. The live view does (`AgentStreamRunner.sessionAdopted`), since the
379
+ * mod's own report of a `/clear` can come before the view listens for one.
380
+ */
381
+ readonly adopted?: (previous: string, next: string) => void
382
+ /**
383
+ * Opens a new NATS connection once the one the session holds closed for good while it runs:
384
+ * nats.js gives up on a repeated authorization refusal under an nkey seed or no credential, and
385
+ * a `close()` ends one too. The server dials as its start did (`dialChannelNats`) until a dial
386
+ * opens one or the server stops; `failed` is handed each dial's error meanwhile, which the
387
+ * session's refused registration names. Rejects once the server stops, and with a dial that
388
+ * failed for good, which the session dials again at its next heartbeat. Omitted, a connection
389
+ * closed for good stays closed, and the session is told it receives nothing.
390
+ */
391
+ readonly reopen?: ReopenConnection
373
392
  /** Ends a start still waiting for its connection to come back (`flushThroughRedials`): the
374
393
  * process is stopping. */
375
394
  readonly startSignal?: AbortSignal
@@ -642,167 +661,84 @@ export function createChannelDelivery(input: {
642
661
  }
643
662
  }
644
663
 
645
- /** Which session id a connection that presents a broker token is admitted as: one at a time, the
646
- * dial's first, then each `/clear`'s once its move lands (`followSession`). */
647
- export interface SessionAdmission {
648
- /** Records that the connection is admitted as `session` now. */
649
- readonly admit: (session: string) => void
650
- /** Settles once the connection is admitted as `session`: at once where it is now, else when a
651
- * later `admit` names it. Only the latest id asked about is waited for: a wait for an id asked
652
- * about before it is dropped unsettled, since the live view takes only its latest id's subject.
653
- * The wait is kept through an `admit` of another id, which an earlier `/clear`'s move can land
654
- * as after the live view has heard of a later one. */
655
- readonly admitted: (session: string) => Promise<void>
664
+ /** How long the startup flush waits before asking again after a redial rejected it, and how often
665
+ * it looks whether the connection was closed for good meanwhile. */
666
+ const REDIAL_FLUSH_RETRY_MS = 250
667
+
668
+ /** Why a start that `flushThroughRedials` ended did not come up: its connection closed for good,
669
+ * where nothing could replace it. */
670
+ const START_CLOSED = "the NATS connection closed before its subscriptions reached the server"
671
+
672
+ /** Why a session holds no live NATS connection: the error it closed with, and the last dial of a
673
+ * new one that failed. */
674
+ interface LostConnection {
675
+ readonly closeError: unknown
676
+ dialError: unknown
656
677
  }
657
678
 
658
- /** A {@link SessionAdmission} admitted as `first`. */
659
- export function sessionAdmission(first: string): SessionAdmission {
660
- let current = first
661
- let pending: { readonly session: string; readonly wait: PromiseWithResolvers<void> } | undefined
662
- return {
663
- admit: (session) => {
664
- current = session
665
- if (pending?.session !== session) return
666
- pending.wait.resolve()
667
- pending = undefined
668
- },
669
- admitted: (session) => {
670
- if (session === current) return Promise.resolve()
671
- if (pending?.session !== session) {
672
- pending = { session, wait: Promise.withResolvers<void>() }
673
- }
674
- return pending.wait.promise
675
- },
676
- }
679
+ /**
680
+ * Why a session holds no live NATS connection, as a log and a notice may print it
681
+ * (`natsFailureReason`): the error its connection closed with, else the last dial of a new one
682
+ * that failed, else this plugin's own words for a close that named no error (a `close()`).
683
+ */
684
+ function lostConnectionReason(lost: LostConnection): string {
685
+ const why = lost.closeError ?? lost.dialError
686
+ return why === undefined ? "it closed and named no error" : natsFailureReason(why)
677
687
  }
678
688
 
679
- /** The channel server's NATS connection, as `dialChannelNats` opened it. */
680
- export interface ChannelNats {
681
- readonly connection: NatsConnection
682
- /** Stops the keeper of the connection's broker token; nothing where it presents none. */
683
- readonly stop: () => void
684
- /** The move a `/clear` runs before the new id's relay subject opens (`followNatsCredential`),
685
- * where the connection presents the session's broker token. */
686
- readonly followSession?: () => Promise<void>
689
+ /** A start's flush that the connection's close for good ended, with the flush error that showed
690
+ * the close where one did (`flushThroughRedials`). */
691
+ interface ClosedBeforeFlush {
692
+ readonly error: unknown
687
693
  }
688
694
 
689
- /** How a failed dial names the credential it presented. */
690
- const CREDENTIAL_NAMES: Record<NatsCredential["kind"], string> = {
691
- broker: "the session's broker token",
692
- seed: "an nkey seed",
693
- none: "no credential",
695
+ /** Why a start without a way to replace its connection ended: it closed for good before the
696
+ * session's subscriptions reached the server. Named as a log may print it (`natsFailureReason`),
697
+ * with no cause, which an error printed whole would print with it. */
698
+ function closedStart(closed: ClosedBeforeFlush): Error {
699
+ return closed.error === undefined
700
+ ? new Error(START_CLOSED)
701
+ : new Error(`${START_CLOSED}: ${natsFailureReason(closed.error)}`)
694
702
  }
695
703
 
704
+ /** How long the start waits for nats.js to settle a closed connection's `closed()`. */
705
+ const CLOSE_ERROR_WAIT_MS = 1_000
706
+
696
707
  /**
697
- * Opens the session's NATS connection with the credential `inbound` resolved. A broker token is
698
- * signed into the CONNECT itself, so a live one is taken before the dial; and the connection is
699
- * then kept on a token the auth service admits (`keepNatsCredential`, warnings through `warn`),
700
- * until `stop` or the connection closing. A dial that fails throws naming the servers by their
701
- * setting and the credential it presented beside why it failed, as a log may print both
702
- * (`natsDialFailure`: no part of a server's text, and the reason nats.js's code or the server's
703
- * fixed refusal, never text derived from what the servers were set to or what the client sent).
704
- * The error keeps no cause: nats.js's own error still carries them. A token that cannot be taken
705
- * fails with the credential's own line (`BrokerNatsCredential.ready`). `dial` is nats.js's
706
- * `connect`, or a test's.
707
- *
708
- * `signal` aborting (the process is stopping) ends the wait for the token and for the dial at once,
709
- * with `START_STOPPING`; the token trade itself goes on, since it is shared with every caller of
710
- * this session's token, and a connection the dial still makes is closed.
708
+ * The error a connection closed for good closed with (nats.js's `closed()`), if any: nats.js marks
709
+ * the connection closed a moment before it settles `closed()`, so the read is bounded, and a
710
+ * connection that settles nothing in that time is taken to have closed naming no error.
711
711
  */
712
- export async function dialChannelNats(
713
- inbound: {
714
- readonly natsUrls: readonly string[]
715
- readonly natsServersSetting: string
716
- readonly natsCredential: NatsCredential
717
- },
718
- name: string,
719
- warn: (text: string) => void,
720
- dial: (options: ConnectionOptions) => Promise<NatsConnection> = connect,
721
- signal?: AbortSignal,
722
- ): Promise<ChannelNats> {
723
- const stopped = Promise.withResolvers<"stopping">()
724
- const onAbort = (): void => stopped.resolve("stopping")
725
- if (signal?.aborted === true) onAbort()
726
- signal?.addEventListener("abort", onAbort)
727
- /** `waited`, or `START_STOPPING` the moment `signal` aborts. A rejection that lands after the
728
- * stop won is settled here, never left unhandled. */
729
- const unlessStopped = async <T>(waited: Promise<T>): Promise<T> => {
730
- const outcome = await Promise.race([
731
- waited.then(
732
- (value) => ({ value }),
733
- (error: unknown) => ({ error }),
712
+ async function closeErrorOf(connection: ChannelConnection): Promise<unknown> {
713
+ const waited = Promise.withResolvers<undefined>()
714
+ const timer = setTimeout(() => waited.resolve(undefined), CLOSE_ERROR_WAIT_MS)
715
+ try {
716
+ return await Promise.race([
717
+ connection.closed().then(
718
+ (error) => error,
719
+ (error: unknown) => error,
734
720
  ),
735
- stopped.promise,
721
+ waited.promise,
736
722
  ])
737
- if (outcome === "stopping") throw new Error(START_STOPPING)
738
- if ("error" in outcome) throw outcome.error
739
- return outcome.value
740
- }
741
- try {
742
- const { natsCredential } = inbound
743
- const broker = natsCredential.kind === "broker" ? natsCredential.broker : undefined
744
- // Waits on the token client's retry loop for the server's life: a pod session not registered
745
- // yet (#4153), a broker that does not answer, a 5xx. Claude Code does not restart a channel
746
- // server that ended, so a start that failed on any of them would leave the session with no
747
- // delivery at all; the loop says what it waits on at each wait, and a refusal no trade cures
748
- // still ends the start. `unlessStopped` ends the wait at a stop.
749
- await unlessStopped(
750
- broker?.ready({ life: signal ?? new AbortController().signal }) ?? Promise.resolve(),
751
- )
752
- const dialing = dial(
753
- natsConnectionOptions({ servers: inbound.natsUrls, name, credential: natsCredential }),
754
- )
755
- let connection: NatsConnection
756
- try {
757
- connection = await unlessStopped(dialing)
758
- } catch (error) {
759
- if (signal?.aborted === true) {
760
- // A dial that completes after the stop opened a connection nobody will use.
761
- dialing.then((late) => late.close()).catch(() => undefined)
762
- throw new Error(START_STOPPING)
763
- }
764
- throw new Error(
765
- natsDialFailure(
766
- natsServersForLog(inbound.natsServersSetting, inbound.natsUrls.length),
767
- error,
768
- CREDENTIAL_NAMES[natsCredential.kind],
769
- ),
770
- )
771
- }
772
- if (broker === undefined) return { connection, stop: () => {} }
773
- return {
774
- connection,
775
- stop: keepNatsCredential(connection, broker, warn),
776
- followSession: () => followNatsCredential(connection, broker),
777
- }
778
723
  } finally {
779
- signal?.removeEventListener("abort", onAbort)
724
+ clearTimeout(timer)
780
725
  }
781
726
  }
782
727
 
783
- /** How long the startup flush waits before asking again after a redial rejected it, and how often
784
- * it looks whether the connection was closed for good meanwhile. */
785
- const REDIAL_FLUSH_RETRY_MS = 250
786
-
787
- /** Why a start that `flushThroughRedials` ended did not come up. */
788
- const START_STOPPING = "the channel server stopped before its NATS subscriptions reached the server"
789
- const START_CLOSED = "the NATS connection closed before its subscriptions reached the server"
790
- /** How long a start that failed waits for its connection to drain before closing it. */
791
- const START_DRAIN_BOUND_MS = 2_000
792
-
793
728
  /**
794
729
  * Flushes `connection`, asking again while the connection redials: nats.js rejects every pending
795
730
  * flush with DISCONNECT each time it redials (`protocol.js`'s `prepare`), and a hub that is
796
731
  * restarting, or whose auth service is away, as a channel server starts is a hub it reconnects to,
797
- * not one that fails the session's start. The start ends, naming why, the moment `signal` aborts
798
- * (the process is stopping) or the connection closes for good — before an attempt, while a flush
799
- * is pending, during the wait to ask again, and after a flush that succeeded once stopping began —
800
- * since nats.js's close leaves a pending flush unsettled, so only watching the connection sees it.
732
+ * not one that fails the session's start. Resolves undefined once a flush reached the server. The
733
+ * start ends the moment `signal` aborts (the process is stopping), with `START_STOPPING`. A
734
+ * connection that closes for good meanwhile is answered with `ClosedBeforeFlush`, for the start to
735
+ * replace — before an attempt, while a flush is pending, and during the wait to ask again — since
736
+ * nats.js's close leaves a pending flush unsettled, so only watching the connection sees it.
801
737
  */
802
738
  async function flushThroughRedials(
803
739
  connection: ChannelConnection,
804
740
  signal: AbortSignal | undefined,
805
- ): Promise<void> {
741
+ ): Promise<ClosedBeforeFlush | undefined> {
806
742
  const ended = Promise.withResolvers<"stopping" | "closed">()
807
743
  const check = (): void => {
808
744
  if (signal?.aborted === true) ended.resolve("stopping")
@@ -810,15 +746,6 @@ async function flushThroughRedials(
810
746
  }
811
747
  const watch = setInterval(check, REDIAL_FLUSH_RETRY_MS)
812
748
  signal?.addEventListener("abort", check)
813
- // A stop is its own reason; a closed connection is named with the flush error that showed it,
814
- // as a log may print it (`natsFailureReason`), and keeps no cause, which an error printed whole
815
- // would print with it.
816
- const failure = (why: "stopping" | "closed", error?: unknown): Error =>
817
- why === "stopping"
818
- ? new Error(START_STOPPING)
819
- : error === undefined
820
- ? new Error(START_CLOSED)
821
- : new Error(`${START_CLOSED}: ${natsFailureReason(error)}`)
822
749
  try {
823
750
  for (;;) {
824
751
  check()
@@ -827,19 +754,21 @@ async function flushThroughRedials(
827
754
  (error: unknown) => ({ flushed: false as const, error }),
828
755
  )
829
756
  const outcome = await Promise.race([attempt, ended.promise])
830
- if (outcome === "stopping" || outcome === "closed") throw failure(outcome)
757
+ if (outcome === "stopping") throw new Error(START_STOPPING)
758
+ if (outcome === "closed") return { error: undefined }
831
759
  if (outcome.flushed) {
832
- if (signal?.aborted === true) throw failure("stopping")
833
- return
760
+ if (signal?.aborted === true) throw new Error(START_STOPPING)
761
+ return undefined
834
762
  }
835
763
  check()
836
- if (signal?.aborted === true) throw failure("stopping", outcome.error)
837
- if (connection.isClosed()) throw failure("closed", outcome.error)
764
+ if (signal?.aborted === true) throw new Error(START_STOPPING)
765
+ if (connection.isClosed()) return { error: outcome.error }
838
766
  const waited = await Promise.race([
839
767
  Bun.sleep(REDIAL_FLUSH_RETRY_MS).then(() => "asked again" as const),
840
768
  ended.promise,
841
769
  ])
842
- if (waited !== "asked again") throw failure(waited, outcome.error)
770
+ if (waited === "stopping") throw new Error(START_STOPPING)
771
+ if (waited === "closed") return { error: outcome.error }
843
772
  }
844
773
  } finally {
845
774
  clearInterval(watch)
@@ -856,6 +785,23 @@ async function flushThroughRedials(
856
785
  export async function startChannelSession(options: ChannelSessionOptions): Promise<ChannelSession> {
857
786
  const { identity } = options
858
787
  let directSubject = legacyAgentSubject(identity.id)
788
+ /** The NATS connection the session holds now, and the credential move that goes with it: the
789
+ * start's, until it closes for good and `options.reopen` opens another (`connectionClosed`). */
790
+ let connection = options.connection
791
+ let followSession = options.followSession
792
+ /**
793
+ * Why the session holds no live connection, while it holds none: the error its connection
794
+ * closed with, and the last dial of a new one that failed. Its registrations go out with no
795
+ * relay meanwhile, naming why (`relayMissing`).
796
+ */
797
+ let connectionLost: LostConnection | undefined
798
+ /** Whether a new connection is being dialed or set up now (`reopenConnection`): one at a time. */
799
+ let reopening = false
800
+ /** The connections whose close for good the session has taken up (`connectionClosed`), and
801
+ * those it watches (`watchConnection`): each once, whether the start found the connection
802
+ * closed, its watch did, or a reopen opened it while the session was still starting. */
803
+ const lostConnections = new WeakSet<ChannelConnection>()
804
+ const watchedConnections = new WeakSet<ChannelConnection>()
859
805
  /**
860
806
  * What this session does with a person's direct messages, for the id now bound: the record is
861
807
  * kept per session id (`./user-turn-state`), so a `/clear` builds another one. Undefined until
@@ -1054,7 +1000,15 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
1054
1000
  readonly delivery: ConsumerDelivery
1055
1001
  /** The id's state file, which also holds the relay's snapshot. */
1056
1002
  readonly state: ReplayStateWriter
1003
+ /** Undefined while the session holds no live connection (`connectionLost`), and once the
1004
+ * subscription ended with an error of its own (`stopped`). */
1057
1005
  subscription: ChannelTopicSubscription | undefined
1006
+ /**
1007
+ * The error the relay subscription ended with on a live connection: the server refused it, say.
1008
+ * Until the heartbeat takes the subject again (`resubscribeRelay`), the session holds no relay
1009
+ * subject, and its registration is refused naming why (`relayMissing`).
1010
+ */
1011
+ stopped: { readonly error: unknown } | undefined
1058
1012
  }
1059
1013
  let relay: Relay | undefined
1060
1014
 
@@ -1122,9 +1076,10 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
1122
1076
  /**
1123
1077
  * A new relay for session `sessionID`, its snapshot `restored` (before any `setFollowed`), its
1124
1078
  * subject subscribed at once; another id's relay is closed first. Its epoch begins as it is
1125
- * made, on this process's one NATS connection; a reconnect begins another (`renewRelayEpoch`).
1126
- * Every later change of its snapshot goes into the id's state file: after a frame is written,
1127
- * after the followed topics change, and after a registration answer moves the stream.
1079
+ * made, on the session's NATS connection; a reconnect begins another (`renewRelayEpoch`), and so
1080
+ * does a new connection in place of one closed for good (`connectionClosed`). Every later
1081
+ * change of its snapshot goes into the id's state file: after a frame is written, after the
1082
+ * followed topics change, and after a registration answer moves the stream.
1128
1083
  */
1129
1084
  const openRelay = (
1130
1085
  sessionID: string,
@@ -1144,7 +1099,9 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
1144
1099
  )
1145
1100
  },
1146
1101
  },
1147
- publish: (reply, body) => options.connection.publish(reply, encoder.encode(body)),
1102
+ // The connection held as the answer goes out: one that replaced a connection closed for
1103
+ // good answers what the closed one could not.
1104
+ publish: (reply, body) => connection.publish(reply, encoder.encode(body)),
1148
1105
  persist: (snapshot) => {
1149
1106
  if (relay !== owner) return false
1150
1107
  state.consumer(snapshot).catch((error: unknown) => {
@@ -1161,14 +1118,40 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
1161
1118
  delivery: consumer,
1162
1119
  state,
1163
1120
  subscription: undefined,
1121
+ stopped: undefined,
1164
1122
  }
1165
1123
  relay = owner
1166
- const subscription = options.connection.subscribe(consumer.subject)
1124
+ subscribeRelay(owner)
1125
+ }
1126
+
1127
+ /**
1128
+ * Subscribes `owner`'s subject on the connection held now, each message to the relay. On a
1129
+ * connection closed for good, which nats.js refuses a subscribe on, it subscribes nothing: the
1130
+ * subject is taken on the connection that replaces it (`reopenFor`), as it is for a connection
1131
+ * lost after the subscribe. Throws where the connection cannot take a subscription otherwise (it
1132
+ * is draining).
1133
+ */
1134
+ const subscribeRelay = (owner: Relay): void => {
1135
+ if (connection.isClosed()) {
1136
+ owner.subscription = undefined
1137
+ return
1138
+ }
1139
+ const subscription = connection.subscribe(owner.delivery.subject)
1167
1140
  owner.subscription = subscription
1141
+ owner.stopped = undefined
1168
1142
  void pumpRelay(owner, subscription)
1169
1143
  }
1170
1144
 
1171
- /** Each relay message goes to the relay, which answers `received` at once and queues it. */
1145
+ /**
1146
+ * Each relay message goes to the relay, which answers `received` at once and queues it. A
1147
+ * subscription nats.js ends with an error of its own (a refusal from the server) leaves the
1148
+ * session with no relay subject while its connection stays up: nothing else takes it again, and a
1149
+ * registration that asked for it would be answered with a consumer relayed to nobody. So the
1150
+ * error is kept (`Relay.stopped`), the session registers at once with no relay, which tells it
1151
+ * once that it receives nothing and names why, and the next heartbeat takes the subject again
1152
+ * (`resubscribeRelay`). A subscription that ends with no error is one this process unsubscribed
1153
+ * or whose connection closed, which `closeRelay` and `connectionClosed` see to.
1154
+ */
1172
1155
  const pumpRelay = async (owner: Relay, subscription: ChannelTopicSubscription): Promise<void> => {
1173
1156
  try {
1174
1157
  for await (const message of subscription) {
@@ -1178,9 +1161,61 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
1178
1161
  process.stderr.write(
1179
1162
  `envoy-channel: the relay subscription of ${owner.sessionID} stopped — ${natsFailureReason(error)}\n`,
1180
1163
  )
1164
+ if (owner.subscription !== subscription) return
1165
+ owner.subscription = undefined
1166
+ owner.stopped = { error }
1167
+ if (shuttingDown || relay !== owner) return
1168
+ serialized(register).catch(() => {
1169
+ registrationFailed = true
1170
+ })
1181
1171
  }
1182
1172
  }
1183
1173
 
1174
+ /**
1175
+ * Takes the relay subject again after its subscription ended with an error of its own, while the
1176
+ * connection is up: before each heartbeat's registration. The subscription counts as taken only
1177
+ * once the server has answered a flush behind it, since nats-server refuses a subscription as it
1178
+ * reads it, before that answer: a refusal ends the subscription before the flush returns, and
1179
+ * then the registration still goes out with no relay. A flush that is rejected (the connection
1180
+ * redials, and sends the subscription again after it) or that times out says nothing of whether
1181
+ * the server will take it, so the subscription is given up, the error it ended with is kept, and
1182
+ * the next heartbeat tries again: until a flush confirms it, no registration asks the listener to
1183
+ * relay to it and the session is not told it receives again. Once it is confirmed a new epoch
1184
+ * begins, so the listener restarts the relay at its ack floor.
1185
+ */
1186
+ const resubscribeRelay = async (): Promise<void> => {
1187
+ const owner = relay
1188
+ const previous = owner?.stopped
1189
+ if (owner === undefined || previous === undefined || owner.sessionID !== identity.id) return
1190
+ if (connectionLost !== undefined || connection.isClosed()) return
1191
+ try {
1192
+ subscribeRelay(owner)
1193
+ } catch (error) {
1194
+ owner.stopped = { error }
1195
+ return
1196
+ }
1197
+ const taken = owner.subscription
1198
+ const confirmed = await withTimeout(
1199
+ connection.flush(),
1200
+ options.handoffFlushTimeoutMs ?? HANDOFF_FLUSH_TIMEOUT_MS,
1201
+ "flushing NATS",
1202
+ ).then(
1203
+ () => true,
1204
+ () => false,
1205
+ )
1206
+ // nats.js ends a refused subscription as it reads the server's refusal, before the flush's
1207
+ // answer; the pump sees the end a turn of the event loop later.
1208
+ await nextTurn()
1209
+ if (relay !== owner || owner.subscription !== taken) return
1210
+ if (!confirmed) {
1211
+ taken?.unsubscribe()
1212
+ owner.subscription = undefined
1213
+ owner.stopped = previous
1214
+ return
1215
+ }
1216
+ owner.delivery.beginEpoch()
1217
+ }
1218
+
1184
1219
  /**
1185
1220
  * The relay's session left (a `/clear`) or shuts down: its unsettled frames are answered `nak`,
1186
1221
  * its subject is unsubscribed, and nothing is relayed until the next registration is answered.
@@ -1220,7 +1255,7 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
1220
1255
 
1221
1256
  // Nothing is subscribed per topic: this holds the followed set a registration carries, and
1222
1257
  // the one NATS subscription this process makes is the relay's (`openRelay`).
1223
- const followedTopics: ChannelTopics = createChannelTopics(options.connection)
1258
+ const followedTopics: ChannelTopics = createChannelTopics(() => connection)
1224
1259
 
1225
1260
  /**
1226
1261
  * Drops removed topics from the followed set and the registry entry, its failure reported
@@ -1277,18 +1312,35 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
1277
1312
  * and receives nothing. The session still runs, and the heartbeat registers again every tick
1278
1313
  * until one is accepted; the reason is the listener's own, one of those
1279
1314
  * `ErrorWireSchema.reason` lists (`@legion/envoy-client`'s `transport.ts`), which the error
1280
- * carries in its message and which `inboundUnavailableNoticeText` words for every host.
1315
+ * carries in its message and which `inboundUnavailableNoticeText` words for every host. The
1316
+ * accepted registration that ends the outage is said too, or the session would read itself as
1317
+ * deaf after it recovered. Neither is said once shutdown has begun: a registration still on the
1318
+ * wire as the session leaves is no outage of a running session.
1281
1319
  */
1282
- const inboundOutage = inboundUnavailable((why) => {
1283
- process.stderr.write(
1284
- `envoy-channel: this session receives nothing (${why}); registering again every heartbeat\n`,
1285
- )
1286
- delivery.notice(inboundUnavailableNoticeText(why)).catch((noticeError: unknown) => {
1320
+ const inboundOutage = inboundUnavailable(
1321
+ (why) => {
1322
+ if (shuttingDown) return
1287
1323
  process.stderr.write(
1288
- `envoy-channel: the session could not be told that it receives nothing — ${messageFor(noticeError)}\n`,
1324
+ `envoy-channel: this session receives nothing (${why}); registering again every heartbeat\n`,
1289
1325
  )
1290
- })
1291
- })
1326
+ delivery.notice(inboundUnavailableNoticeText(why)).catch((noticeError: unknown) => {
1327
+ process.stderr.write(
1328
+ `envoy-channel: the session could not be told that it receives nothing — ${messageFor(noticeError)}\n`,
1329
+ )
1330
+ })
1331
+ },
1332
+ () => {
1333
+ if (shuttingDown) return
1334
+ process.stderr.write(
1335
+ "envoy-channel: this session receives again: its registration was accepted\n",
1336
+ )
1337
+ delivery.notice(inboundRestoredNoticeText()).catch((noticeError: unknown) => {
1338
+ process.stderr.write(
1339
+ `envoy-channel: the session could not be told that it receives again — ${messageFor(noticeError)}\n`,
1340
+ )
1341
+ })
1342
+ },
1343
+ )
1292
1344
 
1293
1345
  /** The title last stamped, so a heartbeat stamps nothing new. */
1294
1346
  let stampedTitle: { readonly sessionID: string; readonly title: string } | undefined
@@ -1304,8 +1356,14 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
1304
1356
  * (`takeDeliveryAnswer`).
1305
1357
  */
1306
1358
  const register = async (): Promise<void> => {
1307
- if (handoffDeliveryPending) {
1308
- await options.followSession?.()
1359
+ // Nothing registers once shutdown has begun: a registration queued before it would find the
1360
+ // relay closed, be refused and tell the leaving session an outage, and one the chain still
1361
+ // holds past the shutdown's bounded wait would land after the DELETE and write the record back.
1362
+ if (shuttingDown) return
1363
+ // With no live connection the handoff's relay waits for the connection that replaces it: its
1364
+ // credential cannot move, and its subject cannot be subscribed (`connectionClosed`).
1365
+ if (handoffDeliveryPending && connectionLost === undefined) {
1366
+ await followSession?.()
1309
1367
  if (shuttingDown) return
1310
1368
  // A refused subscription is closed by nats.js, not restored by its next reconnect, so no
1311
1369
  // new relay opens until the connection has been admitted as this session.
@@ -1314,7 +1372,7 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
1314
1372
  // Confirm the new relay before asking the listener to deliver to it. A stalled flush is
1315
1373
  // bounded; the listener retries a frame that reached no subscriber.
1316
1374
  await withTimeout(
1317
- options.connection.flush(),
1375
+ connection.flush(),
1318
1376
  options.handoffFlushTimeoutMs ?? HANDOFF_FLUSH_TIMEOUT_MS,
1319
1377
  "flushing NATS",
1320
1378
  ).catch((error: unknown) => {
@@ -1344,9 +1402,21 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
1344
1402
  }
1345
1403
  }
1346
1404
  const sessionID = identity.id
1347
- const asking = relay?.sessionID === sessionID ? relay : undefined
1405
+ // While no connection is live, or the relay's subscription ended with an error of its own, the
1406
+ // session holds no relay subject, and the refusal names why.
1407
+ const lost = connectionLost
1408
+ const stopped = relay?.stopped
1409
+ // The subscription's own error, in the words Oh My Pi names it in (`Relay.missing`).
1410
+ const relayMissing =
1411
+ lost !== undefined
1412
+ ? lostConnectionReason(lost)
1413
+ : stopped === undefined
1414
+ ? undefined
1415
+ : natsFailureReason(stopped.error)
1416
+ const asking = relayMissing === undefined && relay?.sessionID === sessionID ? relay : undefined
1348
1417
  await registerWithRelay({
1349
1418
  relay: asking?.delivery,
1419
+ ...(relayMissing === undefined ? {} : { relayMissing }),
1350
1420
  ownAgentSubject: directSubject,
1351
1421
  followed: followedTopics.topics(),
1352
1422
  roles: heldRole === undefined ? [] : [heldRole],
@@ -1618,7 +1688,7 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
1618
1688
  // Bounded: this runs inside the registry chain, and a flush on a stalled NATS
1619
1689
  // connection never settles, which would hold every later write and shutdown.
1620
1690
  await withTimeout(
1621
- options.connection.flush(),
1691
+ connection.flush(),
1622
1692
  options.handoffFlushTimeoutMs ?? HANDOFF_FLUSH_TIMEOUT_MS,
1623
1693
  "flushing NATS",
1624
1694
  )
@@ -1634,6 +1704,7 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
1634
1704
  throw error
1635
1705
  }
1636
1706
  identity.set(next)
1707
+ options.adopted?.(previous, next)
1637
1708
  // The last call for the old id has been made (its deregistration above; the role moves to
1638
1709
  // the new id under the new id's own credential, `restoreRole`), so the key pair and
1639
1710
  // renewing token it traded under go with it rather than renewing for the life of this
@@ -1761,17 +1832,27 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
1761
1832
  dropRetry = undefined
1762
1833
  }
1763
1834
  const heartbeat = async (fromRetry = false): Promise<void> => {
1764
- if (shuttingDown || heartbeatInFlight) return
1835
+ if (shuttingDown) return
1836
+ // A session left with no connection, its last dial failed for good, dials again each tick.
1837
+ reopenConnection()
1838
+ if (heartbeatInFlight) return
1765
1839
  heartbeatInFlight = true
1766
1840
  try {
1767
1841
  await serialized(async () => {
1768
1842
  await adoptHandoff()
1843
+ // A relay subscription that ended with an error of its own is taken again first, so this
1844
+ // registration asks for it.
1845
+ await resubscribeRelay()
1769
1846
  try {
1770
1847
  await register()
1771
1848
  } catch (error) {
1772
1849
  registrationFailed = true
1773
1850
  throw error
1774
1851
  }
1852
+ // A body the chain held while shutdown began writes no role: `register` returned without
1853
+ // registering, and a role write the chain still holds past the shutdown's bounded wait
1854
+ // would land after the DELETE.
1855
+ if (shuttingDown) return
1775
1856
  await reassertRole(registrationFailed)
1776
1857
  await transferRole()
1777
1858
  await syncRegisteredInterests()
@@ -1831,7 +1912,9 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
1831
1912
  // The session's delivery record comes first, so a redelivery of a frame it was shown before is
1832
1913
  // dropped against it. The topics it followed come back with it: a session the listener reaped
1833
1914
  // (ten minutes after it stopped) still follows them, and its consumer still holds them. Its
1834
- // relay comes with it too, restored and subscribed before the first registration asks for it.
1915
+ // relay comes with it too, restored and subscribed before the first registration asks for it;
1916
+ // on a connection already closed for good it is subscribed on the one that replaces it
1917
+ // (`subscribeRelay`), as the flush below finds.
1835
1918
  const remembered = await restoreDelivery()
1836
1919
  // What this session has already done with the messages Dispatch sent it, before any frame can
1837
1920
  // arrive: an attempt a process before this one spent must not be spent again.
@@ -1853,7 +1936,20 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
1853
1936
  })
1854
1937
  // The subscriptions reach the server before the first registration routes anything to them,
1855
1938
  // through any redial the connection is making as the session starts.
1856
- await flushThroughRedials(options.connection, options.startSignal)
1939
+ const closedBeforeFlush = await flushThroughRedials(connection, options.startSignal)
1940
+ if (closedBeforeFlush !== undefined) {
1941
+ // A session with no way to replace its connection cannot start without it.
1942
+ if (options.reopen === undefined) throw closedStart(closedBeforeFlush)
1943
+ // Neither Claude Code nor Codex starts a channel server again, so failing the start here would
1944
+ // leave the session without Envoy for its life: the start goes on, and the connection is
1945
+ // replaced as one lost while the session runs is (`connectionClosed`). The first registration
1946
+ // below is refused naming why, which tells the session once that it receives nothing, and the
1947
+ // new connection's tells it that it receives again. A stop asked for meanwhile still ends the
1948
+ // start as a stop: a close the server makes itself dials nothing.
1949
+ const closeError = await closeErrorOf(connection)
1950
+ if (options.startSignal?.aborted === true) throw new Error(START_STOPPING)
1951
+ connectionClosed(connection, closeError ?? closedBeforeFlush.error)
1952
+ }
1857
1953
  await serialized(async () => {
1858
1954
  // Best-effort, as the interests read above is: a listener that refuses this registration
1859
1955
  // because it can give the session no consumer (`inboundOutage` tells the session
@@ -1940,21 +2036,136 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
1940
2036
  watchFile(handoffFile, { interval: HANDOFF_POLL_MS }, handoffFileChanged)
1941
2037
  requestHeartbeat()
1942
2038
  }
1943
- // nats.js resubscribes by itself after a reconnect; what was published while it was away is in
1944
- // the stream, and the relay restarts at its ack floor on the new epoch's registration. The
1945
- // status events end when the connection closes.
1946
- void (async () => {
2039
+ /**
2040
+ * The session's connection closed for good, and not by its shutdown: nats.js gave up on it (a
2041
+ * repeated authorization refusal under an nkey seed or no credential), or something closed it,
2042
+ * while the session ran or before its start's subscriptions reached the server. Until a new
2043
+ * connection is live the session holds no relay subject, so its registration is refused naming
2044
+ * why (`relayMissing`), and the session is told once that it receives nothing; a new connection
2045
+ * is dialed at once (`reopenConnection`). A function declaration: the start calls it before the
2046
+ * session's watch of its connection begins.
2047
+ */
2048
+ function connectionClosed(closed: ChannelConnection, closeError: unknown): void {
2049
+ if (shuttingDown || closed !== connection || lostConnections.has(closed)) return
2050
+ lostConnections.add(closed)
2051
+ connectionLost = { closeError, dialError: undefined }
2052
+ // Ended with its connection: nothing is relayed until a new one takes the subject again.
2053
+ if (relay !== undefined) relay.subscription = undefined
2054
+ process.stderr.write(
2055
+ `envoy-channel: the NATS connection closed for good (${lostConnectionReason(connectionLost)}); ${options.reopen === undefined ? "nothing dials a new one" : "dialing a new one"}\n`,
2056
+ )
2057
+ // Refused now rather than at the next heartbeat, since the session receives nothing from this
2058
+ // moment: the refusal is told by the outage (`inboundOutage`), once.
2059
+ serialized(register).catch(() => {
2060
+ registrationFailed = true
2061
+ })
2062
+ reopenConnection()
2063
+ }
2064
+
2065
+ /**
2066
+ * Dials a new connection in place of the one lost, unless one is being dialed or set up: at the
2067
+ * loss, and at every heartbeat while the session holds none, so a dial that failed for good (an
2068
+ * authorization refusal under an nkey seed or no credential, which no redial cures) is dialed
2069
+ * again a heartbeat later. A connection lost again while its replacement was set up is dialed
2070
+ * for at once. A function declaration: the first heartbeat can run before the start returns.
2071
+ */
2072
+ function reopenConnection(): void {
2073
+ const lost = connectionLost
2074
+ const reopen = options.reopen
2075
+ if (lost === undefined || reopen === undefined || reopening || shuttingDown) return
2076
+ reopening = true
2077
+ void reopenFor(lost, reopen).finally(() => {
2078
+ reopening = false
2079
+ if (connectionLost !== undefined && connectionLost !== lost) reopenConnection()
2080
+ })
2081
+ }
2082
+
2083
+ /**
2084
+ * `options.reopen` dials until a connection opens or the server stops, each failed dial's error
2085
+ * kept as why the session holds no relay subject. On the connection it opens the relay's subject
2086
+ * is subscribed again and a new epoch begins, so the listener restarts the relay at its ack
2087
+ * floor, and the registration it accepts tells the session it receives again. A dial that
2088
+ * failed for good is said once per failure, and the next heartbeat dials again.
2089
+ */
2090
+ async function reopenFor(lost: LostConnection, reopen: ReopenConnection): Promise<void> {
2091
+ let reopened: ReopenedConnection
1947
2092
  try {
1948
- for await (const status of options.connection.status()) {
1949
- if (status.type !== "reconnect") continue
1950
- renewRelayEpoch()
1951
- }
2093
+ reopened = await reopen((dialError) => {
2094
+ lost.dialError = dialError
2095
+ })
1952
2096
  } catch (error) {
2097
+ if (shuttingDown || options.startSignal?.aborted === true) return
2098
+ lost.dialError = error
1953
2099
  process.stderr.write(
1954
- `envoy-channel: the NATS connection's status reader failed — ${natsFailureReason(error)}\n`,
2100
+ `envoy-channel: gave up opening a new NATS connection (${natsFailureReason(error)}); dialing again at the next heartbeat\n`,
1955
2101
  )
2102
+ return
1956
2103
  }
1957
- })()
2104
+ const live = reopened.connection
2105
+ if (shuttingDown) {
2106
+ // The server stopped as the dial opened it: nothing will use this connection.
2107
+ void live.close().catch(() => undefined)
2108
+ return
2109
+ }
2110
+ connection = live
2111
+ followSession = reopened.followSession
2112
+ // A handoff that waits for its relay opens it on this connection as it registers.
2113
+ if (relay !== undefined && !handoffDeliveryPending) subscribeRelay(relay)
2114
+ watchConnection(live)
2115
+ await serialized(async () => {
2116
+ // The subscription reaches the server before the registration routes anything to it. A
2117
+ // stalled flush is bounded; the listener retries a frame that reached no subscriber.
2118
+ await withTimeout(
2119
+ live.flush(),
2120
+ options.handoffFlushTimeoutMs ?? HANDOFF_FLUSH_TIMEOUT_MS,
2121
+ "flushing NATS",
2122
+ ).catch((error: unknown) => {
2123
+ process.stderr.write(
2124
+ `envoy-channel: could not confirm the relay subscription on the new NATS connection — ${natsFailureReason(error)}\n`,
2125
+ )
2126
+ })
2127
+ // Closed for good again meanwhile: that close is the one the session is told of now.
2128
+ if (shuttingDown || live !== connection || live.isClosed()) return
2129
+ connectionLost = undefined
2130
+ relay?.delivery.beginEpoch()
2131
+ await register()
2132
+ }).catch((error: unknown) => {
2133
+ registrationFailed = true
2134
+ process.stderr.write(
2135
+ `envoy-channel: could not register on the new NATS connection (${messageFor(error)}); the next heartbeat retries\n`,
2136
+ )
2137
+ })
2138
+ }
2139
+
2140
+ /**
2141
+ * Follows `watched`, the connection the session holds. nats.js resubscribes by itself after a
2142
+ * reconnect; what was published while it was away is in the stream, and the relay restarts at
2143
+ * its ack floor on the new epoch's registration. nats.js 2.29.3 never ends a connection's status
2144
+ * readers, even after it closes, so this reader stays parked on a closed connection; the close
2145
+ * is read from `closed()`, and a close for good is `connectionClosed`'s.
2146
+ */
2147
+ function watchConnection(watched: ChannelConnection): void {
2148
+ // A reopen during the start watches its connection before the start's own watch begins.
2149
+ if (watchedConnections.has(watched)) return
2150
+ watchedConnections.add(watched)
2151
+ void (async () => {
2152
+ try {
2153
+ for await (const status of watched.status()) {
2154
+ if (status.type !== "reconnect") continue
2155
+ renewRelayEpoch()
2156
+ }
2157
+ } catch (error) {
2158
+ process.stderr.write(
2159
+ `envoy-channel: the NATS connection's status reader failed — ${natsFailureReason(error)}\n`,
2160
+ )
2161
+ }
2162
+ })()
2163
+ void watched.closed().then(
2164
+ (closeError) => connectionClosed(watched, closeError),
2165
+ (closeError: unknown) => connectionClosed(watched, closeError),
2166
+ )
2167
+ }
2168
+ watchConnection(connection)
1958
2169
 
1959
2170
  return {
1960
2171
  delivery,
@@ -1976,7 +2187,9 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
1976
2187
  followedTopics.follow(topic)
1977
2188
  fresh.push(topic)
1978
2189
  }
1979
- await options.connection.flush()
2190
+ // With no live connection there is nothing to flush, and the registration below is refused
2191
+ // naming why (`connectionClosed`).
2192
+ if (!connection.isClosed()) await connection.flush()
1980
2193
  await serialized(register)
1981
2194
  if (fresh.length > 0) {
1982
2195
  // Recorded at once, so a restart follows the topic again; the relay takes frames stored
@@ -2014,8 +2227,10 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
2014
2227
  return turns?.messageOf(row)
2015
2228
  },
2016
2229
  async rememberRole(role) {
2017
- heldRole = role
2018
- await writeRoleRecord(roleStateFile(options.stateDirectory, identity.id), role)
2230
+ await serialized(async () => {
2231
+ heldRole = role
2232
+ await writeRoleRecord(roleStateFile(options.stateDirectory, identity.id), role)
2233
+ })
2019
2234
  },
2020
2235
  async shutdown() {
2021
2236
  if (shuttingDown) return
@@ -2563,10 +2778,16 @@ export async function runEnvoyChannelServer(): Promise<void> {
2563
2778
  inbound.natsCredential.kind === "broker"
2564
2779
  ? "it waits for this session's broker token, and its stderr says what each trade came to"
2565
2780
  : "it connects to NATS"
2781
+ const natsName = `claude-envoy-channel-${identity.id}`
2566
2782
  const dialled = await dialChannelNats(
2567
2783
  inbound,
2568
- `claude-envoy-channel-${identity.id}`,
2569
- (text) => process.stderr.write(`envoy-channel: ${text}\n`),
2784
+ natsName,
2785
+ (text, dialError) => {
2786
+ // A redial's warning names what the start waits on; the token keeper warns through the
2787
+ // same channel once the connection is up, and names nothing the start waits on.
2788
+ if (dialError !== undefined) starting = text
2789
+ process.stderr.write(`envoy-channel: ${text}\n`)
2790
+ },
2570
2791
  connect,
2571
2792
  booting.signal,
2572
2793
  ).catch((error: unknown) => {
@@ -2583,15 +2804,22 @@ export async function runEnvoyChannelServer(): Promise<void> {
2583
2804
  // control subject only then (`AgentStreamOptions.admitted`).
2584
2805
  const admission =
2585
2806
  dialled.followSession === undefined ? undefined : sessionAdmission(identity.id)
2586
- const follow = dialled.followSession
2587
- const followSession =
2588
- follow === undefined || admission === undefined
2589
- ? undefined
2590
- : async (): Promise<void> => {
2591
- const forSession = identity.id
2592
- await follow()
2593
- admission.admit(forSession)
2594
- }
2807
+ const admitting = admittingMoves(admission, identity)
2808
+ const followSession = admitting(dialled.followSession)
2809
+ const reopen = channelReopener({
2810
+ inbound,
2811
+ name: natsName,
2812
+ signal: booting.signal,
2813
+ swapKeeper: (stop) => {
2814
+ stopNatsKeeper()
2815
+ stopNatsKeeper = stop
2816
+ },
2817
+ admitting,
2818
+ useConnection: (next) => {
2819
+ connection = next
2820
+ agentStream?.useConnection(next)
2821
+ },
2822
+ })
2595
2823
  const started = await startChannelSession({
2596
2824
  identity,
2597
2825
  connection,
@@ -2610,6 +2838,9 @@ export async function runEnvoyChannelServer(): Promise<void> {
2610
2838
  // The QA override names a fixed identity; only a Claude-minted id follows `/clear`.
2611
2839
  ...(configuredValue(overrideSessionId) === undefined ? { handoffPid: process.ppid } : {}),
2612
2840
  ...(followSession === undefined ? {} : { followSession }),
2841
+ // The live view follows a `/clear` the mod reported before it began listening.
2842
+ adopted: (previous, next) => agentStream?.sessionAdopted(previous, next),
2843
+ reopen,
2613
2844
  startSignal: booting.signal,
2614
2845
  }).catch((error: unknown) => {
2615
2846
  // A stop asked for while the session was still starting (its connection waiting on the
@@ -2621,13 +2852,13 @@ export async function runEnvoyChannelServer(): Promise<void> {
2621
2852
  session = started
2622
2853
  // INFRA-1026: the Agents page's live view, once this session's mod has a link to bind to.
2623
2854
  // It needs the bus as well as the link, so it starts here rather than beside the bind; a
2624
- // session whose link never binds never starts one, and runs as it did before.
2625
- const bus = connection
2855
+ // session whose link never binds never starts one, and runs as it did before. The bus is
2856
+ // the connection held as the link binds: a reopen may have replaced the start's.
2626
2857
  const live = session
2627
2858
  void linked.promise.then((link) => {
2628
- if (stopping) return
2859
+ if (stopping || connection === undefined) return
2629
2860
  agentStream = startAgentStream({
2630
- connection: bus,
2861
+ connection,
2631
2862
  // Only a Claude-minted id follows `/clear`; the override names a fixed identity.
2632
2863
  followsSessionId: configuredValue(overrideSessionId) === undefined,
2633
2864
  ...(admission === undefined ? {} : { admitted: (id: string) => admission.admitted(id) }),
@@ -2708,13 +2939,7 @@ export async function runEnvoyChannelServer(): Promise<void> {
2708
2939
  await linking
2709
2940
  await modLink?.close().catch(() => undefined)
2710
2941
  if (session === undefined && connection !== undefined) {
2711
- // Bounded: a connection still redialing, as one whose start a stop ended can be, may never
2712
- // finish a drain, and the close after it is what ends the connection for good.
2713
- await Promise.race([
2714
- connection.drain().catch(() => undefined),
2715
- Bun.sleep(START_DRAIN_BOUND_MS),
2716
- ])
2717
- await connection.close().catch(() => undefined)
2942
+ await closeUnstartedConnection(connection)
2718
2943
  }
2719
2944
  // Release stdin so the process can exit once the session is deregistered,
2720
2945
  // even when the parent has not closed its end yet.