@sjawhar/claude-envoy 4.15.2 → 4.15.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sjawhar/claude-envoy",
3
- "version": "4.15.2",
3
+ "version": "4.15.4",
4
4
  "license": "Apache-2.0",
5
5
  "description": "Claude Code plugin for Legion's Envoy bus",
6
6
  "type": "module",
@@ -19,7 +19,7 @@
19
19
  "AGENTS.md"
20
20
  ],
21
21
  "legion": {
22
- "daemonApiVersion": 188
22
+ "daemonApiVersion": 189
23
23
  },
24
24
  "repository": {
25
25
  "type": "git",
@@ -7,7 +7,6 @@ import {
7
7
  AGENT_STREAM_WATCH_INTERVAL_MS,
8
8
  type AgentStreamCommand,
9
9
  type AgentStreamControlMessage,
10
- agentStreamControlSubject,
11
10
  agentStreamFramesSubject,
12
11
  } from "@legion/contracts"
13
12
  import { messageFor } from "@legion/envoy-client/errors"
@@ -15,19 +14,14 @@ import { AgentStreamPublisher } from "@legion/pi-shared/agent-stream"
15
14
  import type { ModConfigRow, ModEffort, ModEvent } from "../hooks/mod-protocol"
16
15
  import { claudeAgentStreamCommands, createClaudeAgentStream } from "./agent-stream-claude"
17
16
  import { rememberBounded } from "./bounded-set"
18
- import type { ChannelConnection, ChannelTopicSubscription } from "./channel-topics"
17
+ import type { ChannelConnection } from "./channel-topics"
18
+ import { controlSubscription } from "./control-subscription"
19
19
  import type { ModLink } from "./mod-link"
20
20
 
21
- const encoder = new TextEncoder()
22
- const decoder = new TextDecoder()
23
-
24
21
  /** How long the live view waits for the mod to answer one of its reads (`$.session.model()`,
25
22
  * `$.config.list()`, `$.command.list()`). Each is served out of the session's own memory, so a
26
23
  * wait this long means the mod is gone rather than busy, and the header keeps its last values. */
27
24
  const AGENT_STREAM_CALL_TIMEOUT_MS = 5_000
28
- /** How long the live view waits before taking its control subject again after the subscription's
29
- * iterator ended, which is what a dropped connection looks like from here. */
30
- const AGENT_STREAM_RESUBSCRIBE_MS = 1_000
31
25
 
32
26
  /**
33
27
  * The most row ids this stream remembers having read, so a row that arrives twice is read once.
@@ -51,10 +45,12 @@ export interface AgentStreamOptions {
51
45
  /** The session id the Agents page knows this session by, which both subjects name. */
52
46
  readonly sessionId: string
53
47
  /**
54
- * Whether the stream follows the session id the mod reports. Claude Code mints a new one on
55
- * `/clear` and the channel rebinds to it (`adoptHandoff`), so the two are the same id; under
56
- * the `ENVOY_SESSION_ID` override the session registers a fixed id of its own and the Claude
57
- * id names nothing Dispatch knows, so the stream stays where it started.
48
+ * Whether the stream follows the session's id through a `/clear`. Claude Code mints a new one on
49
+ * `/clear` and the channel rebinds to it (`adoptHandoff`), so the two are the same id; the
50
+ * stream moves at the mod's report of it, in the order of the conversation's own events, and at
51
+ * the server's adoption of it (`sessionAdopted`), which covers a report the link made before the
52
+ * stream listened. Under the `ENVOY_SESSION_ID` override the session registers a fixed id of
53
+ * its own and the Claude id names nothing Dispatch knows, so the stream stays where it started.
58
54
  */
59
55
  readonly followsSessionId: boolean
60
56
  /**
@@ -112,6 +108,18 @@ export interface AgentStreamRunner {
112
108
  /** The effort a person's pick put in force, shown by the header at once: Claude Code reports
113
109
  * an effort only on a request of its own, and an idle session makes none. */
114
110
  readonly pickedEffort: (effort: ModEffort) => void
111
+ /** The session's NATS connection closed for good and the server opened `connection` in its
112
+ * place: frames go out on it from now on, and the control subject is taken on it again. */
113
+ readonly useConnection: (connection: ChannelConnection) => void
114
+ /**
115
+ * The server adopted a `/clear`, moving the session from `previous` to `next`
116
+ * (`ChannelSessionOptions.adopted`): a stream still on `previous` moves to `next`. The link tells
117
+ * its listeners of the mod's report of the new id once, and the stream starts only once the
118
+ * session has, so a `/clear` early in the session can be reported before the stream listens; the
119
+ * adoption is what then moves it. A stream the mod's report already moved on is left where it
120
+ * is: the adoption of an earlier `/clear` must not move it back.
121
+ */
122
+ readonly sessionAdopted: (previous: string, next: string) => void
115
123
  }
116
124
 
117
125
  /**
@@ -132,13 +140,23 @@ export interface AgentStreamRunner {
132
140
  * publishes no settings and no commands, and its conversation stays empty.
133
141
  */
134
142
  export function startAgentStream(options: AgentStreamOptions): AgentStreamRunner {
135
- const { connection, link } = options
143
+ const { link } = options
136
144
  const now = options.now ?? Date.now
137
145
  const warn =
138
146
  options.warn ?? ((text: string): void => void process.stderr.write(`envoy-channel: ${text}\n`))
147
+ /** The id both subjects name now; it moves with the mod's own id after a `/clear`. */
148
+ let session = options.sessionId
149
+ /** The viewer's control subject, on the session's connection now (`./control-subscription`). */
150
+ const control = controlSubscription({
151
+ connection: options.connection,
152
+ session: () => session,
153
+ ...(options.admitted === undefined ? {} : { admitted: options.admitted }),
154
+ warn,
155
+ answer: answerControl,
156
+ })
139
157
  const publisher = new AgentStreamPublisher({
140
158
  now,
141
- publish: (subject, payload) => connection.publish(subject, encoder.encode(payload)),
159
+ publish: (subject, payload) => control.publish(subject, payload),
142
160
  })
143
161
  const stream = createClaudeAgentStream({
144
162
  isPane: options.isPane === true,
@@ -151,10 +169,6 @@ export function startAgentStream(options: AgentStreamOptions): AgentStreamRunner
151
169
  : { runsUnreadPrompt: options.runsUnreadPrompt }),
152
170
  ...(options.tagFor === undefined ? {} : { tagFor: options.tagFor }),
153
171
  })
154
- /** The id both subjects name now; it moves with the mod's own id after a `/clear`. */
155
- let session = options.sessionId
156
- let subscription: ChannelTopicSubscription | undefined
157
- let stopped = false
158
172
  /** What the mod last said of the session's model, its `/config` rows and its commands. They
159
173
  * survive a session id change: the process and its model do not change with the id. */
160
174
  let model: string | undefined
@@ -194,7 +208,7 @@ export function startAgentStream(options: AgentStreamOptions): AgentStreamRunner
194
208
  /** Read the session's model and its `/config` rows, and publish what they say. One read at a
195
209
  * time: a watch arrives every ten seconds and the answers rarely change. */
196
210
  const refreshSettings = (): void => {
197
- if (stopped || readingSettings || !link.connected()) return
211
+ if (control.stopped || readingSettings || !link.connected()) return
198
212
  readingSettings = true
199
213
  void Promise.all([
200
214
  link.request("session.model", undefined, { timeoutMs: AGENT_STREAM_CALL_TIMEOUT_MS }),
@@ -203,7 +217,7 @@ export function startAgentStream(options: AgentStreamOptions): AgentStreamRunner
203
217
  .then(([answeredModel, rows]) => {
204
218
  model = answeredModel
205
219
  configRows = rows
206
- if (!stopped) publishSettings()
220
+ if (!control.stopped) publishSettings()
207
221
  })
208
222
  .catch((error: unknown) => {
209
223
  warn(`the live view could not read this session's model — ${messageFor(error)}`)
@@ -214,13 +228,13 @@ export function startAgentStream(options: AgentStreamOptions): AgentStreamRunner
214
228
  }
215
229
 
216
230
  const refreshCommands = (): void => {
217
- if (stopped || readingCommands || !link.connected()) return
231
+ if (control.stopped || readingCommands || !link.connected()) return
218
232
  readingCommands = true
219
233
  void link
220
234
  .request("command.list", undefined, { timeoutMs: AGENT_STREAM_CALL_TIMEOUT_MS })
221
235
  .then((commands) => {
222
236
  listedCommands = claudeAgentStreamCommands(commands)
223
- if (!stopped) publishCommands()
237
+ if (!control.stopped) publishCommands()
224
238
  })
225
239
  .catch((error: unknown) => {
226
240
  warn(`the live view could not read this session's commands — ${messageFor(error)}`)
@@ -230,67 +244,41 @@ export function startAgentStream(options: AgentStreamOptions): AgentStreamRunner
230
244
  })
231
245
  }
232
246
 
233
- const pump = async (taken: ChannelTopicSubscription, forSession: string): Promise<void> => {
234
- try {
235
- for await (const message of taken) {
236
- // Any client on the bus can publish here. A `null` payload parses cleanly and then
237
- // throws on `.type`, and a reply over the server's max_payload throws out of the
238
- // publish; either would end the iterator and take the session deaf with it.
239
- try {
240
- const parsed: unknown = JSON.parse(decoder.decode(message.data))
241
- if (typeof parsed !== "object" || parsed === null) continue
242
- const request = parsed as AgentStreamControlMessage
243
- if (request.type !== "replay" && request.type !== "watch") continue
244
- refreshSettings()
245
- if (
246
- request.type === "replay" ||
247
- !viewerAttached ||
248
- now() - commandsRefreshedOnWatchAt >= AGENT_STREAM_WATCH_INTERVAL_MS
249
- ) {
250
- refreshCommands()
251
- if (request.type === "watch" && viewerAttached) commandsRefreshedOnWatchAt = now()
252
- }
253
- // Taken before this message arms anything, so a bare replay from a client that never
254
- // attached a viewer gets an empty history rather than the ring.
255
- const reply = message.reply
256
- const answer =
257
- request.type === "replay" && reply !== undefined
258
- ? JSON.stringify(publisher.replay(forSession))
259
- : undefined
260
- const arming = !publisher.watched
261
- publisher.noteViewer()
262
- viewerAttached = true
263
- if (arming) publisher.publishState(agentStreamFramesSubject(forSession))
264
- if (answer === undefined || reply === undefined) continue
265
- connection.publish(reply, encoder.encode(answer))
266
- } catch (error) {
267
- warn(`a live view control message failed — ${messageFor(error)}`)
268
- }
269
- }
270
- } catch {
271
- // A dead iterator is a dropped connection, taken again below.
247
+ /** Answers one `replay` or `watch` message on the control subject of `forSession`
248
+ * (`ControlSubscriptionOptions.answer`), the way every Oh My Pi session does
249
+ * (`packages/pi-envoy`, `pumpAgentStreamControl`). A declaration: the control subscription is
250
+ * made before it. */
251
+ function answerControl(
252
+ request: AgentStreamControlMessage,
253
+ replying: boolean,
254
+ forSession: string,
255
+ ): string | undefined {
256
+ refreshSettings()
257
+ if (
258
+ request.type === "replay" ||
259
+ !viewerAttached ||
260
+ now() - commandsRefreshedOnWatchAt >= AGENT_STREAM_WATCH_INTERVAL_MS
261
+ ) {
262
+ refreshCommands()
263
+ if (request.type === "watch" && viewerAttached) commandsRefreshedOnWatchAt = now()
272
264
  }
273
- if (subscription === taken) subscription = undefined
274
- if (stopped || session !== forSession) return
275
- const retry = setTimeout(() => {
276
- if (stopped || session !== forSession) return
277
- subscribe()
278
- }, AGENT_STREAM_RESUBSCRIBE_MS)
279
- retry.unref()
280
- }
281
-
282
- function subscribe(): void {
283
- if (stopped) return
284
- subscription?.unsubscribe()
285
- const taken = connection.subscribe(agentStreamControlSubject(session))
286
- subscription = taken
287
- void pump(taken, session)
265
+ // Taken before this message arms anything, so a bare replay from a client that never
266
+ // attached a viewer gets an empty history rather than the ring.
267
+ const answer =
268
+ request.type === "replay" && replying
269
+ ? JSON.stringify(publisher.replay(forSession))
270
+ : undefined
271
+ const arming = !publisher.watched
272
+ publisher.noteViewer()
273
+ viewerAttached = true
274
+ if (arming) publisher.publishState(agentStreamFramesSubject(forSession))
275
+ return answer
288
276
  }
289
277
 
290
- // A `/clear` ends the conversation and the process goes on under a new id: the ring holds the
291
- // previous one, and a viewer opening the new id must not be served it.
292
- link.onSessionId((next: string) => {
293
- if (stopped || !options.followsSessionId || next === session) return
278
+ /** A `/clear` ends the conversation and the process goes on under `next`: the ring holds the
279
+ * previous one, and a viewer opening the new id must not be served it. */
280
+ const moveTo = (next: string): void => {
281
+ if (control.stopped || !options.followsSessionId || next === session) return
294
282
  session = next
295
283
  publisher.reset()
296
284
  stream.reset()
@@ -302,15 +290,12 @@ export function startAgentStream(options: AgentStreamOptions): AgentStreamRunner
302
290
  publishCommands()
303
291
  // The old id's control subject goes at once, and the new id's is taken once the connection
304
292
  // may take it (`AgentStreamOptions.admitted`): a later `/clear` before then takes its own.
305
- subscription?.unsubscribe()
306
- subscription = undefined
307
- const admitted = options.admitted?.(next)
308
- if (admitted === undefined) subscribe()
309
- else
310
- void admitted.then(() => {
311
- if (!stopped && session === next) subscribe()
312
- })
313
- })
293
+ control.moved()
294
+ }
295
+ // The mod's report moves the stream between the conversation's own events. The id the link
296
+ // reported before this listener joined is not read: it can be older than `options.sessionId`,
297
+ // the id the server had adopted when the stream started.
298
+ link.onSessionId(moveTo)
314
299
 
315
300
  const reading = (async (): Promise<void> => {
316
301
  for await (const event of link.events) {
@@ -336,22 +321,25 @@ export function startAgentStream(options: AgentStreamOptions): AgentStreamRunner
336
321
  warn(`the live view stopped reading this session's events — ${messageFor(error)}`)
337
322
  })
338
323
 
339
- subscribe()
324
+ control.start()
340
325
 
341
326
  return {
342
327
  refresh(): void {
343
328
  refreshSettings()
344
329
  },
345
330
  pickedEffort(effort: ModEffort): void {
346
- if (stopped) return
331
+ if (control.stopped) return
347
332
  stream.pickedEffort(effort)
348
333
  publishSettings()
349
334
  },
350
335
  stop(): void {
351
- if (stopped) return
352
- stopped = true
353
- subscription?.unsubscribe()
354
- subscription = undefined
336
+ control.stop()
337
+ },
338
+ useConnection(next: ChannelConnection): void {
339
+ control.useConnection(next)
340
+ },
341
+ sessionAdopted(previous: string, next: string): void {
342
+ if (session === previous) moveTo(next)
355
343
  },
356
344
  }
357
345
  }
@@ -0,0 +1,306 @@
1
+ // The NATS connection a channel server holds for its session, over the session's life: dialed with
2
+ // the session's credential and redialed until it opens (`dialChannelNats`), admitted as one session
3
+ // id at a time where it presents the session's broker token (`sessionAdmission`,
4
+ // `admittingMoves`), replaced once it closes for good (`channelReopener`), and closed with a bound
5
+ // where no session took it (`closeUnstartedConnection`). Both channel servers take theirs from
6
+ // here: Claude Code's (`./envoy-channel-server`) and Codex's (`./codex/codex-server`).
7
+ import { LoggableError } from "@legion/envoy-client/errors"
8
+ import {
9
+ connectNats,
10
+ NATS_DIAL_PLAN,
11
+ type NatsDialPlan,
12
+ natsConnectionOptions,
13
+ natsDialFailure,
14
+ natsServersForLog,
15
+ } from "@legion/envoy-client/nats-connection"
16
+ import {
17
+ followNatsCredential,
18
+ keepNatsCredential,
19
+ type NatsCredential,
20
+ } from "@legion/envoy-client/nats-credential"
21
+ import { type ConnectionOptions, connect, type NatsConnection } from "nats"
22
+ import type { ChannelConnection } from "./channel-topics"
23
+ import type { SessionIdentity } from "./session-identity"
24
+
25
+ /** Why a dial or a start a stop ended did not come up: the process is stopping (`dialChannelNats`,
26
+ * and the start's own flush, `startChannelSession`). */
27
+ export const START_STOPPING =
28
+ "the channel server stopped before its NATS subscriptions reached the server"
29
+
30
+ /** Which session id a connection that presents a broker token is admitted as: one at a time, the
31
+ * dial's first, then each `/clear`'s once its move lands (`followSession`). */
32
+ export interface SessionAdmission {
33
+ /** Records that the connection is admitted as `session` now. */
34
+ readonly admit: (session: string) => void
35
+ /** Settles once the connection is admitted as `session`: at once where it is now, else when a
36
+ * later `admit` names it. Only the latest id asked about is waited for: a wait for an id asked
37
+ * about before it is dropped unsettled, since the live view takes only its latest id's subject.
38
+ * The wait is kept through an `admit` of another id, which an earlier `/clear`'s move can land
39
+ * as after the live view has heard of a later one. */
40
+ readonly admitted: (session: string) => Promise<void>
41
+ }
42
+
43
+ /** A {@link SessionAdmission} admitted as `first`. */
44
+ export function sessionAdmission(first: string): SessionAdmission {
45
+ let current = first
46
+ let pending: { readonly session: string; readonly wait: PromiseWithResolvers<void> } | undefined
47
+ return {
48
+ admit: (session) => {
49
+ current = session
50
+ if (pending?.session !== session) return
51
+ pending.wait.resolve()
52
+ pending = undefined
53
+ },
54
+ admitted: (session) => {
55
+ if (session === current) return Promise.resolve()
56
+ if (pending?.session !== session) {
57
+ pending = { session, wait: Promise.withResolvers<void>() }
58
+ }
59
+ return pending.wait.promise
60
+ },
61
+ }
62
+ }
63
+
64
+ /** A connection's credential move (`followSession`), wrapped so that it records, once it lands,
65
+ * the id it admitted the connection as (`admittingMoves`). */
66
+ export type AdmittingMove = (
67
+ follow: (() => Promise<void>) | undefined,
68
+ ) => (() => Promise<void>) | undefined
69
+
70
+ /**
71
+ * Wraps each connection's credential move so that it records, once it lands, the id it admits the
72
+ * connection as: the id the session had as the move began, which a later `/clear` or `/new` does
73
+ * not change. Each server wraps its first connection's move and each one a reopen dials in its
74
+ * place (`channelReopener`). A connection that presents no broker token has no move to wrap, and
75
+ * `admission` is then undefined.
76
+ */
77
+ export function admittingMoves(
78
+ admission: SessionAdmission | undefined,
79
+ identity: SessionIdentity,
80
+ ): AdmittingMove {
81
+ return (follow) =>
82
+ follow === undefined || admission === undefined
83
+ ? undefined
84
+ : async (): Promise<void> => {
85
+ const forSession = identity.id
86
+ await follow()
87
+ admission.admit(forSession)
88
+ }
89
+ }
90
+
91
+ /** The channel server's NATS connection, as `dialChannelNats` opened it. */
92
+ export interface ChannelNats {
93
+ readonly connection: NatsConnection
94
+ /** Stops the keeper of the connection's broker token; nothing where it presents none. */
95
+ readonly stop: () => void
96
+ /** The move a `/clear` runs before the new id's relay subject opens (`followNatsCredential`),
97
+ * where the connection presents the session's broker token. */
98
+ readonly followSession?: () => Promise<void>
99
+ }
100
+
101
+ /** How a failed dial names the credential it presented. */
102
+ const CREDENTIAL_NAMES: Record<NatsCredential["kind"], string> = {
103
+ broker: "the session's broker token",
104
+ seed: "an nkey seed",
105
+ none: "no credential",
106
+ }
107
+
108
+ /** The channel server's dials: every plugin's waits, for the server's life. */
109
+ export const CHANNEL_DIAL_PLAN: NatsDialPlan = {
110
+ ...NATS_DIAL_PLAN,
111
+ budgetMs: Number.POSITIVE_INFINITY,
112
+ }
113
+
114
+ /** What `dialChannelNats` dials: the session's NATS servers, the setting that names them, and the
115
+ * credential the connection presents (`EnvoyInbound` where inbound messages are on). */
116
+ export interface ChannelNatsSettings {
117
+ readonly natsUrls: readonly string[]
118
+ readonly natsServersSetting: string
119
+ readonly natsCredential: NatsCredential
120
+ }
121
+
122
+ /**
123
+ * Opens the session's NATS connection with the credential `inbound` resolved. A broker token is
124
+ * signed into the CONNECT itself, so a live one is taken before the dial; and the connection is
125
+ * then kept on a token the auth service admits (`keepNatsCredential`, warnings through `warn`,
126
+ * with no dial error, which tells them from a redial's), until `stop` or the connection closing.
127
+ * A dial that fails is dialed again as `plan` says, which by default is for the server's life;
128
+ * each redial is warned of, naming the servers by their setting and the credential it presented
129
+ * beside why it failed, as a log may print both
130
+ * (`natsDialFailure`: no part of a server's text, and the reason nats.js's code or the server's
131
+ * fixed refusal, never text derived from what the servers were set to or what the client sent),
132
+ * and `warn` is handed the failed dial's error with its line. A dial that fails for good (an
133
+ * authorization refusal, or the end of a finite `plan`) throws the same line, as a
134
+ * `LoggableError`; the error keeps no cause: nats.js's own error still carries them. A token that
135
+ * cannot be taken fails with the credential's own line (`BrokerNatsCredential.ready`). `dial` is
136
+ * nats.js's `connect`, or a test's.
137
+ *
138
+ * `signal` aborting (the process is stopping) ends the wait for the token and for the dial at once,
139
+ * with `START_STOPPING`, and starts no further dial; the token trade itself goes on, since it is
140
+ * shared with every caller of this session's token, and a connection the dial still makes is
141
+ * closed.
142
+ */
143
+ export async function dialChannelNats(
144
+ inbound: ChannelNatsSettings,
145
+ name: string,
146
+ warn: (text: string, dialError?: unknown) => void,
147
+ dial: (options: ConnectionOptions) => Promise<NatsConnection> = connect,
148
+ signal?: AbortSignal,
149
+ plan: NatsDialPlan = CHANNEL_DIAL_PLAN,
150
+ ): Promise<ChannelNats> {
151
+ const stopped = Promise.withResolvers<"stopping">()
152
+ const onAbort = (): void => stopped.resolve("stopping")
153
+ if (signal?.aborted === true) onAbort()
154
+ signal?.addEventListener("abort", onAbort)
155
+ /** `waited`, or `START_STOPPING` the moment `signal` aborts. A rejection that lands after the
156
+ * stop won is settled here, never left unhandled. */
157
+ const unlessStopped = async <T>(waited: Promise<T>): Promise<T> => {
158
+ const outcome = await Promise.race([
159
+ waited.then(
160
+ (value) => ({ value }),
161
+ (error: unknown) => ({ error }),
162
+ ),
163
+ stopped.promise,
164
+ ])
165
+ if (outcome === "stopping") throw new Error(START_STOPPING)
166
+ if ("error" in outcome) throw outcome.error
167
+ return outcome.value
168
+ }
169
+ try {
170
+ const { natsCredential } = inbound
171
+ const failed = (error: unknown): string =>
172
+ natsDialFailure(
173
+ natsServersForLog(inbound.natsServersSetting, inbound.natsUrls.length),
174
+ error,
175
+ CREDENTIAL_NAMES[natsCredential.kind],
176
+ )
177
+ const broker = natsCredential.kind === "broker" ? natsCredential.broker : undefined
178
+ // Waits on the token client's retry loop for the server's life: a pod session not registered
179
+ // yet (#4153), a broker that does not answer, a 5xx. Claude Code does not restart a channel
180
+ // server that ended, so a start that failed on any of them would leave the session with no
181
+ // delivery at all; the loop says what it waits on at each wait, and a refusal no trade cures
182
+ // still ends the start. `unlessStopped` ends the wait at a stop.
183
+ await unlessStopped(
184
+ broker?.ready({ life: signal ?? new AbortController().signal }) ?? Promise.resolve(),
185
+ )
186
+ // A dial that fails is dialed again for the server's life, as the token wait above is:
187
+ // Claude Code starts no channel server again once one ended, and a hub closes a dial whose
188
+ // CONNECT came after its 2 s authentication timeout, then answers the next one. Each dial has
189
+ // its own bound (`connectNats`); a stop ends the redials.
190
+ const dialing = connectNats(
191
+ dial,
192
+ natsConnectionOptions({ servers: inbound.natsUrls, name, credential: natsCredential }),
193
+ plan,
194
+ {
195
+ stopped: () => signal?.aborted === true,
196
+ onRetry: (error, delayMs) =>
197
+ warn(`${failed(error)}; dialing again in ${delayMs} ms`, error),
198
+ },
199
+ )
200
+ let connection: NatsConnection
201
+ try {
202
+ connection = await unlessStopped(dialing)
203
+ } catch (error) {
204
+ if (signal?.aborted === true) {
205
+ // A dial that completes after the stop opened a connection nobody will use.
206
+ dialing.then((late) => late.close()).catch(() => undefined)
207
+ throw new Error(START_STOPPING)
208
+ }
209
+ throw new LoggableError(failed(error))
210
+ }
211
+ if (broker === undefined) return { connection, stop: () => {} }
212
+ return {
213
+ connection,
214
+ stop: keepNatsCredential(connection, broker, warn),
215
+ followSession: () => followNatsCredential(connection, broker),
216
+ }
217
+ } finally {
218
+ signal?.removeEventListener("abort", onAbort)
219
+ }
220
+ }
221
+
222
+ /** How long a start that failed waits for its connection to drain before closing it. */
223
+ const START_DRAIN_BOUND_MS = 2_000
224
+
225
+ /**
226
+ * Ends the connection of a session that never started: its start failed, or a stop ended it.
227
+ * Both servers' teardowns call it (`runEnvoyChannelServer`, `./codex/codex-server`). The drain is
228
+ * bounded: a connection still redialing, or one whose path stopped carrying the hub's answers, as
229
+ * one whose start a stop ended can be, may never finish a drain, and the close after it is what
230
+ * ends the connection for good.
231
+ */
232
+ export async function closeUnstartedConnection(connection: ChannelConnection): Promise<void> {
233
+ await Promise.race([connection.drain().catch(() => undefined), Bun.sleep(START_DRAIN_BOUND_MS)])
234
+ await connection.close().catch(() => undefined)
235
+ }
236
+
237
+ /** A connection `ChannelSessionOptions.reopen` opened in place of one closed for good. */
238
+ export interface ReopenedConnection {
239
+ readonly connection: ChannelConnection
240
+ /** `ChannelSessionOptions.followSession`, for this connection. */
241
+ readonly followSession?: () => Promise<void>
242
+ }
243
+
244
+ /** Opens a new NATS connection in place of one closed for good (`ChannelSessionOptions.reopen`). */
245
+ export type ReopenConnection = (failed: (dialError: unknown) => void) => Promise<ReopenedConnection>
246
+
247
+ /** What a server hands `channelReopener`. */
248
+ export interface ChannelReopenerOptions {
249
+ /** What the server's first connection was dialed with. */
250
+ readonly inbound: ChannelNatsSettings
251
+ /** The connection name every connection of the server presents. */
252
+ readonly name: string
253
+ /** Aborts when the server stops: it ends a dial's waits and its redials, and closes a connection
254
+ * a dial opened after it. */
255
+ readonly signal: AbortSignal
256
+ /** Stops the token keeper the server holds now and holds `stop` in its place: the one the
257
+ * server's teardown stops. */
258
+ readonly swapKeeper: (stop: () => void) => void
259
+ /** The server's wrapper of a connection's credential move (`admittingMoves`). */
260
+ readonly admitting: AdmittingMove
261
+ /** Moves what else the server holds on its connection, its live view, to `connection`. */
262
+ readonly useConnection: (connection: ChannelConnection) => void
263
+ }
264
+
265
+ /**
266
+ * A server's `ChannelSessionOptions.reopen`: a new connection once the session's closed for good,
267
+ * dialed as the server's first one was, warning of each redial on stderr, until one opens or the
268
+ * server stops. The closed connection's token keeper stops before the dial, and the new one's is
269
+ * the one the teardown stops; the live view moves to the new connection. Under a broker token the
270
+ * new connection presents the token the session's credential holds as it dials, the one traded
271
+ * last (a lapsed one is traded again for the id the session has now): through a `/clear`, the old
272
+ * id's until the `/clear`'s move has traded the new id's, and the new id's from then on, even
273
+ * where the connection closed before the move reconnected with it. The admission is left as it
274
+ * is either way: a `/clear` whose move had not ended runs it again on the new connection
275
+ * (`register`), and that admits the new id once the connection presents its token, at once where
276
+ * it already does. A connection a dial opens after the server began stopping is closed. Both
277
+ * servers take theirs from here: Claude Code's (`runEnvoyChannelServer`) and Codex's
278
+ * (`./codex/codex-server`).
279
+ */
280
+ export function channelReopener(options: ChannelReopenerOptions): ReopenConnection {
281
+ return async (failed) => {
282
+ options.swapKeeper(() => undefined)
283
+ const next = await dialChannelNats(
284
+ options.inbound,
285
+ options.name,
286
+ (text, dialError) => {
287
+ process.stderr.write(`envoy-channel: ${text}\n`)
288
+ if (dialError !== undefined) failed(dialError)
289
+ },
290
+ connect,
291
+ options.signal,
292
+ )
293
+ if (options.signal.aborted) {
294
+ next.stop()
295
+ void next.connection.close().catch(() => undefined)
296
+ throw new Error(START_STOPPING)
297
+ }
298
+ options.swapKeeper(next.stop)
299
+ options.useConnection(next.connection)
300
+ const followSession = options.admitting(next.followSession)
301
+ return {
302
+ connection: next.connection,
303
+ ...(followSession === undefined ? {} : { followSession }),
304
+ }
305
+ }
306
+ }