@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.
@@ -41,10 +41,13 @@ export interface ChannelConnection {
41
41
  close(): Promise<void>
42
42
  /** The connection's status events (nats.js `status()`), which end when it closes. */
43
43
  status(): AsyncIterable<ChannelConnectionStatus>
44
+ /** Settles once the connection is closed for good, with the error that closed it, if any
45
+ * (nats.js `closed()`); already settled for one closed before the call. */
46
+ closed(): Promise<unknown>
44
47
  }
45
48
 
46
49
  /**
47
- * The topics this session follows, and the one broker connection it holds. Nothing is subscribed
50
+ * The topics this session follows, and the broker connection it holds now. Nothing is subscribed
48
51
  * for a topic: the listener relays every followed subject from the session's own durable consumer
49
52
  * (`ConsumerDelivery`), so a topic is followed by registering it, and the only subscription that
50
53
  * carries Envoy traffic is that consumer's relay subject.
@@ -56,9 +59,9 @@ export interface ChannelTopics {
56
59
  unfollow(topics: readonly string[]): void
57
60
  /** Topics currently followed, in follow order. */
58
61
  topics(): readonly string[]
59
- /** True once the connection is closed for good. */
62
+ /** True once the connection held now is closed for good. */
60
63
  isClosed(): boolean
61
- /** Drain the NATS connection; never rejects. */
64
+ /** Drain the connection held now; never rejects. */
62
65
  close(): Promise<void>
63
66
  }
64
67
 
@@ -101,10 +104,12 @@ function report(what: string, error: unknown): void {
101
104
  * One channel process follows its direct Envoy route and every topic a human or a tool added to
102
105
  * it. Each is a concrete subject the registration carries (`expandSubscriptionTopics`), and the
103
106
  * listener relays all of them from the session's own consumer, so nothing here subscribes: the
104
- * set is what a registration advertises and what the relay is filtered on.
107
+ * set is what a registration advertises and what the relay is filtered on. `connection` answers
108
+ * the connection the session holds now: a server opens a new one when its connection closes for
109
+ * good (`ChannelSessionOptions.reopen`).
105
110
  */
106
111
  export function createChannelTopics(
107
- connection: ChannelConnection,
112
+ connection: () => ChannelConnection,
108
113
  options: ChannelTopicsOptions = {},
109
114
  ): ChannelTopics {
110
115
  const following = new Set<string>()
@@ -125,22 +130,24 @@ export function createChannelTopics(
125
130
  return [...following]
126
131
  },
127
132
  isClosed() {
128
- return connection.isClosed()
133
+ return connection().isClosed()
129
134
  },
130
135
  async close() {
131
136
  following.clear()
132
- if (connection.isClosed()) return
137
+ // The connection held as the close begins: the session swaps none in once it is stopping.
138
+ const held = connection()
139
+ if (held.isClosed()) return
133
140
  const timeout = Promise.withResolvers<void>()
134
141
  const timer = setTimeout(timeout.resolve, drainTimeoutMs)
135
142
  try {
136
- await Promise.race([connection.drain(), timeout.promise])
143
+ await Promise.race([held.drain(), timeout.promise])
137
144
  } catch (error) {
138
145
  report("draining the broker connection failed", error)
139
146
  }
140
147
  clearTimeout(timer)
141
- if (connection.isClosed()) return
148
+ if (held.isClosed()) return
142
149
  try {
143
- await connection.close()
150
+ await held.close()
144
151
  } catch (error) {
145
152
  report("closing the broker connection failed", error)
146
153
  }
@@ -1,12 +1,11 @@
1
1
  import {
2
2
  type AgentStreamControlMessage,
3
- agentStreamControlSubject,
4
3
  agentStreamFramesSubject,
5
4
  comparableLines,
6
5
  } from "@legion/contracts"
7
- import { messageFor } from "@legion/envoy-client/errors"
8
6
  import { AgentStreamPublisher } from "@legion/pi-shared/agent-stream"
9
- import type { ChannelConnection, ChannelTopicSubscription } from "../channel-topics"
7
+ import type { ChannelConnection } from "../channel-topics"
8
+ import { controlSubscription } from "../control-subscription"
10
9
  import type { CodexTranscriptEvent } from "./codex-transcript"
11
10
 
12
11
  /**
@@ -32,6 +31,10 @@ export interface CodexAgentStream {
32
31
  expect(text: string, dispatchMessageId: string): void
33
32
  /** Moves the stream to another session id (`/new`): the conversation starts empty. */
34
33
  rebind(sessionId: string): void
34
+ /** The session's NATS connection closed for good and the server opened `connection` in its
35
+ * place (`channelReopener`): frames go out on it from now on, and the control subject is taken
36
+ * on it again once the connection is admitted as the session (`admitted`). */
37
+ useConnection(connection: ChannelConnection): void
35
38
  stop(): void
36
39
  }
37
40
 
@@ -51,27 +54,28 @@ export interface CodexAgentStreamOptions {
51
54
  readonly admitted?: (session: string) => Promise<void>
52
55
  }
53
56
 
54
- const encoder = new TextEncoder()
55
- const decoder = new TextDecoder()
56
- /** How long a control subscription that ended waits before it is taken again. */
57
- const RESUBSCRIBE_MS = 1_000
58
57
  /** How many expected person messages are kept for tagging. */
59
58
  const EXPECTED_MAX = 16
60
59
  /** Codex's models, as the page names a model: `provider/id`. */
61
60
  const CODEX_PROVIDER = "openai"
62
61
 
63
62
  export function startCodexAgentStream(options: CodexAgentStreamOptions): CodexAgentStream {
64
- const { connection } = options
65
63
  const now = options.now ?? Date.now
66
64
  const warn =
67
65
  options.warn ?? ((text: string): void => void process.stderr.write(`envoy-channel: ${text}\n`))
66
+ let session = options.sessionId
67
+ /** The viewer's control subject, on the session's connection now (`../control-subscription`). */
68
+ const control = controlSubscription({
69
+ connection: options.connection,
70
+ session: () => session,
71
+ ...(options.admitted === undefined ? {} : { admitted: options.admitted }),
72
+ warn,
73
+ answer: answerControl,
74
+ })
68
75
  const publisher = new AgentStreamPublisher({
69
76
  now,
70
- publish: (subject, payload) => connection.publish(subject, encoder.encode(payload)),
77
+ publish: (subject, payload) => control.publish(subject, payload),
71
78
  })
72
- let session = options.sessionId
73
- let subscription: ChannelTopicSubscription | undefined
74
- let stopped = false
75
79
  let model: string | undefined
76
80
  /** The last timestamp handed to a message: each gets one strictly past it, since the publisher
77
81
  * keys an assistant message by its timestamp. */
@@ -109,51 +113,29 @@ export function startCodexAgentStream(options: CodexAgentStreamOptions): CodexAg
109
113
  })
110
114
  }
111
115
 
112
- const pump = async (taken: ChannelTopicSubscription, forSession: string): Promise<void> => {
113
- try {
114
- for await (const message of taken) {
115
- try {
116
- const parsed: unknown = JSON.parse(decoder.decode(message.data))
117
- if (typeof parsed !== "object" || parsed === null) continue
118
- const request = parsed as AgentStreamControlMessage
119
- if (request.type !== "replay" && request.type !== "watch") continue
120
- const reply = message.reply
121
- const answer =
122
- request.type === "replay" && reply !== undefined
123
- ? JSON.stringify(publisher.replay(forSession))
124
- : undefined
125
- const arming = !publisher.watched
126
- publisher.noteViewer()
127
- if (arming) publisher.publishState(agentStreamFramesSubject(forSession))
128
- if (answer === undefined || reply === undefined) continue
129
- connection.publish(reply, encoder.encode(answer))
130
- } catch (error) {
131
- warn(`a live view control message failed — ${messageFor(error)}`)
132
- }
133
- }
134
- } catch {
135
- // A dead iterator is a dropped connection, taken again below.
136
- }
137
- if (subscription === taken) subscription = undefined
138
- if (stopped || session !== forSession) return
139
- setTimeout(() => {
140
- if (!stopped && session === forSession) subscribe()
141
- }, RESUBSCRIBE_MS).unref?.()
142
- }
143
-
144
- function subscribe(): void {
145
- if (stopped) return
146
- subscription?.unsubscribe()
147
- const taken = connection.subscribe(agentStreamControlSubject(session))
148
- subscription = taken
149
- void pump(taken, session)
116
+ /** Answers one `replay` or `watch` message on the control subject of `forSession`
117
+ * (`ControlSubscriptionOptions.answer`). A declaration: the control subscription is made before
118
+ * it. */
119
+ function answerControl(
120
+ request: AgentStreamControlMessage,
121
+ replying: boolean,
122
+ forSession: string,
123
+ ): string | undefined {
124
+ const answer =
125
+ request.type === "replay" && replying
126
+ ? JSON.stringify(publisher.replay(forSession))
127
+ : undefined
128
+ const arming = !publisher.watched
129
+ publisher.noteViewer()
130
+ if (arming) publisher.publishState(agentStreamFramesSubject(forSession))
131
+ return answer
150
132
  }
151
- subscribe()
133
+ control.start()
152
134
  publishSettings()
153
135
 
154
136
  return {
155
137
  event(event) {
156
- if (stopped) return
138
+ if (control.stopped) return
157
139
  switch (event.kind) {
158
140
  case "settings":
159
141
  if (event.model !== model) {
@@ -216,7 +198,7 @@ export function startCodexAgentStream(options: CodexAgentStreamOptions): CodexAg
216
198
  }
217
199
  },
218
200
  delivered(text, dispatchMessageId) {
219
- if (stopped) return
201
+ if (control.stopped) return
220
202
  // A person's message the hook took never becomes a user row of the transcript, so the
221
203
  // tag kept for that row is dropped rather than left for a later message with the same words.
222
204
  if (dispatchMessageId !== undefined) {
@@ -233,7 +215,7 @@ export function startCodexAgentStream(options: CodexAgentStreamOptions): CodexAg
233
215
  while (expected.length > EXPECTED_MAX) expected.shift()
234
216
  },
235
217
  rebind(next) {
236
- if (stopped || next === session) return
218
+ if (control.stopped || next === session) return
237
219
  session = next
238
220
  publisher.reset()
239
221
  expected.length = 0
@@ -241,18 +223,15 @@ export function startCodexAgentStream(options: CodexAgentStreamOptions): CodexAg
241
223
  publishSettings()
242
224
  // The old id's control subject goes at once, and the new id's is taken once the connection
243
225
  // may take it (`CodexAgentStreamOptions.admitted`): a later `/new` before then takes its own.
244
- subscription?.unsubscribe()
245
- subscription = undefined
246
- const admitted = options.admitted?.(next)
247
- if (admitted === undefined) subscribe()
248
- else
249
- void admitted.then(() => {
250
- if (!stopped && session === next) subscribe()
251
- })
226
+ control.moved()
227
+ },
228
+ useConnection(next) {
229
+ // A `/new` whose move had not landed when the connection closed is still not admitted, so
230
+ // the subject is taken on the new connection through the gate.
231
+ control.useConnection(next)
252
232
  },
253
233
  stop() {
254
- stopped = true
255
- subscription?.unsubscribe()
234
+ control.stop()
256
235
  },
257
236
  }
258
237
  }
@@ -21,18 +21,23 @@ import { connect } from "nats"
21
21
  import { z } from "zod"
22
22
  /** The npm package a Codex session runs, which its registrations name. */
23
23
  import { name as CODEX_PACKAGE_NAME } from "../../codex/package.json" with { type: "json" }
24
+ import {
25
+ admittingMoves,
26
+ channelReopener,
27
+ closeUnstartedConnection,
28
+ dialChannelNats,
29
+ sessionAdmission,
30
+ } from "../channel-connection"
24
31
  import type { ChannelConnection } from "../channel-topics"
25
32
  import { configuredValue } from "../claude-session"
26
33
  import {
27
34
  type ChannelSession,
28
35
  type ChannelToolRuntime,
29
36
  channelToolDefinitions,
30
- dialChannelNats,
31
37
  executeEnvoyTool,
32
38
  MCP_SERVER_INFO,
33
39
  mcpResult,
34
40
  postDispatchReply,
35
- sessionAdmission,
36
41
  startChannelSession,
37
42
  } from "../envoy-channel-server"
38
43
  import { inboundOffChannelSession } from "../envoy-off"
@@ -533,30 +538,49 @@ export async function runCodexEnvoyServer(): Promise<void> {
533
538
  } else {
534
539
  // Dialled as the Claude Code session's connection is (`dialChannelNats`): with a seed, no
535
540
  // credential, or the session's broker token, which is then kept renewed and, at a `/new`,
536
- // moved to the new session's (`followSession`) before that session's subjects are taken.
541
+ // moved to the new session's (`followSession`) before that session's subjects are taken. A
542
+ // connection that closes for good is replaced as the Claude Code one is (`channelReopener`):
543
+ // Codex starts no plugin server again for a thread whose server lost its connection.
544
+ const natsName = `codex-envoy-channel-${id.id}`
545
+ // A stop asked for while the token or the dial is awaited ends the start, and is no failure:
546
+ // the process ends as an asked-for stop does, as the Claude Code server's does.
537
547
  const dialled = await dialChannelNats(
538
548
  inbound,
539
- `codex-envoy-channel-${id.id}`,
549
+ natsName,
540
550
  warn,
541
551
  connect,
542
552
  stopping.signal,
543
- )
553
+ ).catch((error: unknown) => {
554
+ if (isStopping) return undefined
555
+ throw error
556
+ })
557
+ if (dialled === undefined) {
558
+ await stopped.promise
559
+ return
560
+ }
544
561
  connection = dialled.connection
545
562
  stopNatsKeeper = dialled.stop
546
563
  // Which id the connection is admitted as, where its broker token admits one session at a
547
564
  // time: the dial's, then each `/new`'s once its move lands. The live view takes a new id's
548
565
  // control subject only then (`CodexAgentStreamOptions.admitted`).
549
566
  const admission = dialled.followSession === undefined ? undefined : sessionAdmission(id.id)
550
- const follow = dialled.followSession
551
- const followSession =
552
- follow === undefined || admission === undefined
553
- ? undefined
554
- : async (): Promise<void> => {
555
- const forSession = id.id
556
- await follow()
557
- admission.admit(forSession)
558
- }
559
- session = await startChannelSession({
567
+ const admitting = admittingMoves(admission, id)
568
+ const followSession = admitting(dialled.followSession)
569
+ const reopen = channelReopener({
570
+ inbound,
571
+ name: natsName,
572
+ signal: stopping.signal,
573
+ swapKeeper: (stop) => {
574
+ stopNatsKeeper()
575
+ stopNatsKeeper = stop
576
+ },
577
+ admitting,
578
+ useConnection: (next) => {
579
+ connection = next
580
+ stream?.useConnection(next)
581
+ },
582
+ })
583
+ const started = await startChannelSession({
560
584
  capabilities: () => CODEX_CAPABILITIES,
561
585
  client,
562
586
  clientInstanceID,
@@ -592,10 +616,24 @@ export async function runCodexEnvoyServer(): Promise<void> {
592
616
  state,
593
617
  warn,
594
618
  }),
619
+ reopen,
620
+ // Ends a start still flushing through its connection's redials (`flushThroughRedials`):
621
+ // the process is stopping.
622
+ startSignal: stopping.signal,
595
623
  stateDirectory,
596
624
  title,
597
625
  ...(dispatch.enabled ? { stampTitle } : {}),
626
+ }).catch((error: unknown) => {
627
+ // A stop asked for while the session was still starting ends the start, and is no
628
+ // failure, as above.
629
+ if (isStopping) return undefined
630
+ throw error
598
631
  })
632
+ if (started === undefined) {
633
+ await stopped.promise
634
+ return
635
+ }
636
+ session = started
599
637
  stream = startCodexAgentStream({
600
638
  connection,
601
639
  sessionId: id.id,
@@ -604,6 +642,9 @@ export async function runCodexEnvoyServer(): Promise<void> {
604
642
  ? {}
605
643
  : { admitted: (next: string) => admission.admitted(next) }),
606
644
  })
645
+ // A stop that landed while the session started ran before this view existed, and stopped
646
+ // nothing of it.
647
+ if (isStopping) stream.stop()
607
648
  }
608
649
  runtime = { client, clientInstanceID, identity: id, session }
609
650
  follow(bound.transcript_path)
@@ -617,8 +658,7 @@ export async function runCodexEnvoyServer(): Promise<void> {
617
658
  follower?.stop()
618
659
  stopNatsKeeper()
619
660
  if (session === undefined && connection !== undefined) {
620
- await connection.drain().catch(() => undefined)
621
- await connection.close().catch(() => undefined)
661
+ await closeUnstartedConnection(connection)
622
662
  }
623
663
  await server.close().catch(() => undefined)
624
664
  }
@@ -0,0 +1,166 @@
1
+ // The control subject a viewer takes a session's live view on (`agentStreamControlSubject`), over
2
+ // the view's life, for both live views: Claude Code's (`./agent-stream-runner`) and Codex's
3
+ // (`./codex/codex-agent-stream`). It takes the subject only once the session's connection is
4
+ // admitted as the session (`admitted`), takes it again a moment after its subscription ended,
5
+ // moves it when the view moves to another session id or the server swaps in a new connection, and
6
+ // takes nothing on a connection closed for good or once the view stopped. What a control message
7
+ // is answered with is each view's own (`answer`).
8
+ import { type AgentStreamControlMessage, agentStreamControlSubject } from "@legion/contracts"
9
+ import { messageFor } from "@legion/envoy-client/errors"
10
+ import type { ChannelConnection, ChannelTopicSubscription } from "./channel-topics"
11
+
12
+ const encoder = new TextEncoder()
13
+ const decoder = new TextDecoder()
14
+
15
+ /** How long the view waits before taking its control subject again after the subscription's
16
+ * iterator ended, which is what a dropped connection looks like from here. */
17
+ const RESUBSCRIBE_MS = 1_000
18
+
19
+ export interface ControlSubscriptionOptions {
20
+ /** The session's NATS connection as the view starts: the server swaps in a new one when it
21
+ * closes for good (`useConnection`). */
22
+ readonly connection: ChannelConnection
23
+ /** The session id the view names now, which the control subject names: it moves at a `/clear`
24
+ * or a `/new` (`moved`). */
25
+ readonly session: () => string
26
+ /**
27
+ * Settles once the session's NATS connection is admitted as `session`, where the connection is
28
+ * admitted as one session at a time: under its broker token a new id is the connection's only
29
+ * once the move lands (`followSession`), and a subscribe before then is refused and closed by
30
+ * the server. Where this is absent the connection may take every id's subjects, and the subject
31
+ * is taken at once.
32
+ */
33
+ readonly admitted?: (session: string) => Promise<void>
34
+ /** Where a failure that must not stop the session is written. */
35
+ readonly warn: (text: string) => void
36
+ /**
37
+ * Answers one `replay` or `watch` message on the control subject of `forSession`, the session
38
+ * the subscription was taken for: what goes to the message's reply inbox, if anything.
39
+ * `replying` says whether the message carries one. A throw is warned of, and the next message
40
+ * is read.
41
+ */
42
+ readonly answer: (
43
+ request: AgentStreamControlMessage,
44
+ replying: boolean,
45
+ forSession: string,
46
+ ) => string | undefined
47
+ }
48
+
49
+ export interface ControlSubscription {
50
+ /** Whether the view stopped: it takes no subject, and its frames go nowhere, from then on. */
51
+ readonly stopped: boolean
52
+ /** Publishes on the connection held now, unless the view stopped. A closed connection throws on
53
+ * a publish, and a throw here would end the view's reader for good, so its frames are dropped
54
+ * until the server swaps in a new connection; the ring keeps them for a replay. */
55
+ publish(subject: string, payload: string): void
56
+ /** Takes the view's first control subject. */
57
+ start(): void
58
+ /** The view moved to the session id `session` names now: the old id's subject goes at once, and
59
+ * the new id's is taken once the connection may take it, so a later move before then takes its
60
+ * own. */
61
+ moved(): void
62
+ /** The session's NATS connection closed for good and the server opened `connection` in its
63
+ * place (`channelReopener`): frames go out on it from now on, and the control subject is taken
64
+ * on it again once the connection is admitted as the session. */
65
+ useConnection(connection: ChannelConnection): void
66
+ /** Stops answering the control subject. */
67
+ stop(): void
68
+ }
69
+
70
+ export function controlSubscription(options: ControlSubscriptionOptions): ControlSubscription {
71
+ /** The session's connection now; the server swaps in a new one when it closes for good. */
72
+ let connection = options.connection
73
+ let subscription: ChannelTopicSubscription | undefined
74
+ let stopped = false
75
+
76
+ const pump = async (taken: ChannelTopicSubscription, forSession: string): Promise<void> => {
77
+ try {
78
+ for await (const message of taken) {
79
+ // Any client on the bus can publish here. A `null` payload parses cleanly and then
80
+ // throws on `.type`, and a reply over the server's max_payload throws out of the
81
+ // publish; either would end the iterator and take the session deaf with it.
82
+ try {
83
+ const parsed: unknown = JSON.parse(decoder.decode(message.data))
84
+ if (typeof parsed !== "object" || parsed === null) continue
85
+ const request = parsed as AgentStreamControlMessage
86
+ if (request.type !== "replay" && request.type !== "watch") continue
87
+ const reply = message.reply
88
+ const answer = options.answer(request, reply !== undefined, forSession)
89
+ if (answer === undefined || reply === undefined) continue
90
+ connection.publish(reply, encoder.encode(answer))
91
+ } catch (error) {
92
+ options.warn(`a live view control message failed — ${messageFor(error)}`)
93
+ }
94
+ }
95
+ } catch {
96
+ // A dead iterator is a dropped connection, taken again below.
97
+ }
98
+ if (subscription === taken) subscription = undefined
99
+ if (stopped || options.session() !== forSession) return
100
+ const retry = setTimeout(() => {
101
+ // Taken again meanwhile: by a new id's subject, or on the connection the server swapped in.
102
+ if (stopped || options.session() !== forSession || subscription !== undefined) return
103
+ subscribeWhenAdmitted(forSession)
104
+ }, RESUBSCRIBE_MS)
105
+ retry.unref()
106
+ }
107
+
108
+ /** Takes the control subject on the connection held now. A closed one throws on a subscribe, so
109
+ * the subject waits for the connection the server swaps in (`useConnection`). */
110
+ function subscribe(): void {
111
+ if (stopped || connection.isClosed()) return
112
+ subscription?.unsubscribe()
113
+ const forSession = options.session()
114
+ const taken = connection.subscribe(agentStreamControlSubject(forSession))
115
+ subscription = taken
116
+ void pump(taken, forSession)
117
+ }
118
+
119
+ /** Takes `forSession`'s control subject once the connection may take it (`admitted`), unless the
120
+ * view moved on or took it meanwhile: a move whose credential move has not landed leaves the
121
+ * connection unable to take the new id's subjects, on the connection it began on and on any the
122
+ * server swaps in before the move lands. */
123
+ function subscribeWhenAdmitted(forSession: string): void {
124
+ const admitted = options.admitted?.(forSession)
125
+ if (admitted === undefined) {
126
+ subscribe()
127
+ return
128
+ }
129
+ void admitted.then(() => {
130
+ if (!stopped && options.session() === forSession && subscription === undefined) subscribe()
131
+ })
132
+ }
133
+
134
+ return {
135
+ get stopped(): boolean {
136
+ return stopped
137
+ },
138
+ publish(subject: string, payload: string): void {
139
+ if (!stopped && !connection.isClosed()) connection.publish(subject, encoder.encode(payload))
140
+ },
141
+ start(): void {
142
+ // The first subject goes through the gate too: a view starts after its session does, which
143
+ // can be after a `/clear` or a `/new` whose move has not landed.
144
+ subscribeWhenAdmitted(options.session())
145
+ },
146
+ moved(): void {
147
+ subscription?.unsubscribe()
148
+ subscription = undefined
149
+ subscribeWhenAdmitted(options.session())
150
+ },
151
+ useConnection(next: ChannelConnection): void {
152
+ connection = next
153
+ if (stopped) return
154
+ // The subscription on the closed connection is dead; the new one is taken through the gate.
155
+ subscription?.unsubscribe()
156
+ subscription = undefined
157
+ subscribeWhenAdmitted(options.session())
158
+ },
159
+ stop(): void {
160
+ if (stopped) return
161
+ stopped = true
162
+ subscription?.unsubscribe()
163
+ subscription = undefined
164
+ },
165
+ }
166
+ }