@sjawhar/claude-envoy 4.21.1 → 4.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -52,6 +52,9 @@ export interface CodexAgentStreamOptions {
52
52
  * Claude Code live view's).
53
53
  */
54
54
  readonly admitted?: (session: string) => Promise<void>
55
+ /** Whether a viewer can take this session: false over the listener's relay socket, which
56
+ * carries no agent stream (`ControlSubscriptionOptions.liveView`). True by default. */
57
+ readonly liveView?: boolean
55
58
  }
56
59
 
57
60
  /** How many expected person messages are kept for tagging. */
@@ -69,6 +72,7 @@ export function startCodexAgentStream(options: CodexAgentStreamOptions): CodexAg
69
72
  connection: options.connection,
70
73
  session: () => session,
71
74
  ...(options.admitted === undefined ? {} : { admitted: options.admitted }),
75
+ ...(options.liveView === undefined ? {} : { liveView: options.liveView }),
72
76
  warn,
73
77
  answer: answerControl,
74
78
  })
@@ -25,7 +25,7 @@ import {
25
25
  admittingMoves,
26
26
  channelReopener,
27
27
  closeUnstartedConnection,
28
- dialChannelNats,
28
+ dialChannelInbound,
29
29
  sessionAdmission,
30
30
  } from "../channel-connection"
31
31
  import type { ChannelConnection } from "../channel-topics"
@@ -536,16 +536,19 @@ export async function runCodexEnvoyServer(): Promise<void> {
536
536
  if ("off" in inbound) {
537
537
  session = inboundOffChannelSession({ identity: id, stateDirectory, why: inbound.off })
538
538
  } else {
539
- // Dialled as the Claude Code session's connection is (`dialChannelNats`): with a seed, no
540
- // credential, or the session's broker token, which is then kept renewed and, at a `/new`,
541
- // moved to the new session's (`followSession`) before that session's subjects are taken. A
539
+ // Dialled as the Claude Code session's connection is (`dialChannelInbound`): NATS with a
540
+ // seed, no credential, or the session's broker token, which is then kept renewed and, at a
541
+ // `/new`, moved to the new session's (`followSession`) before that session's subjects are
542
+ // taken; or the listener's relay socket, opened again for the new session at a `/new`. A
542
543
  // connection that closes for good is replaced as the Claude Code one is (`channelReopener`):
543
544
  // Codex starts no plugin server again for a thread whose server lost its connection.
544
545
  const natsName = `codex-envoy-channel-${id.id}`
545
546
  // A stop asked for while the token or the dial is awaited ends the start, and is no failure:
546
547
  // the process ends as an asked-for stop does, as the Claude Code server's does.
547
- const dialled = await dialChannelNats(
548
+ const dialled = await dialChannelInbound(
548
549
  inbound,
550
+ envoy.url,
551
+ () => id.id,
549
552
  natsName,
550
553
  warn,
551
554
  connect,
@@ -568,6 +571,8 @@ export async function runCodexEnvoyServer(): Promise<void> {
568
571
  const followSession = admitting(dialled.followSession)
569
572
  const reopen = channelReopener({
570
573
  inbound,
574
+ listenerUrl: envoy.url,
575
+ session: () => id.id,
571
576
  name: natsName,
572
577
  signal: stopping.signal,
573
578
  swapKeeper: (stop) => {
@@ -590,6 +595,9 @@ export async function runCodexEnvoyServer(): Promise<void> {
590
595
  heartbeatMs: envoy.heartbeatMs,
591
596
  identity: id,
592
597
  ...(followSession === undefined ? {} : { followSession }),
598
+ ...(dialled.reportOutagesTo === undefined
599
+ ? {}
600
+ : { reportOutagesTo: dialled.reportOutagesTo }),
593
601
  notifier: {
594
602
  notification: ({ content, eventId }) =>
595
603
  codexDelivery.deliver({ content, ...(eventId === undefined ? {} : { eventId }) }),
@@ -636,6 +644,7 @@ export async function runCodexEnvoyServer(): Promise<void> {
636
644
  session = started
637
645
  stream = startCodexAgentStream({
638
646
  connection,
647
+ liveView: dialled.liveView,
639
648
  sessionId: id.id,
640
649
  warn,
641
650
  ...(admission === undefined
@@ -31,6 +31,13 @@ export interface ControlSubscriptionOptions {
31
31
  * is taken at once.
32
32
  */
33
33
  readonly admitted?: (session: string) => Promise<void>
34
+ /**
35
+ * Whether a viewer can take this session: false where the session's inbound is the listener's
36
+ * relay socket (`ENVOY_INBOUND=listener`), which carries no agent stream
37
+ * (`@legion/envoy-client/listener-relay`), so the control subject is never taken, no viewer arms
38
+ * the view's publisher, and no frame goes out. True by default.
39
+ */
40
+ readonly liveView?: boolean
34
41
  /** Where a failure that must not stop the session is written. */
35
42
  readonly warn: (text: string) => void
36
43
  /**
@@ -108,7 +115,7 @@ export function controlSubscription(options: ControlSubscriptionOptions): Contro
108
115
  /** Takes the control subject on the connection held now. A closed one throws on a subscribe, so
109
116
  * the subject waits for the connection the server swaps in (`useConnection`). */
110
117
  function subscribe(): void {
111
- if (stopped || connection.isClosed()) return
118
+ if (stopped || options.liveView === false || connection.isClosed()) return
112
119
  subscription?.unsubscribe()
113
120
  const forSession = options.session()
114
121
  const taken = connection.subscribe(agentStreamControlSubject(forSession))
@@ -19,7 +19,6 @@ import {
19
19
  inboundRestoredNoticeText,
20
20
  inboundUnavailable,
21
21
  inboundUnavailableNoticeText,
22
- registerWithRelay,
23
22
  } from "@legion/envoy-client/consumer-delivery"
24
23
  import {
25
24
  createDeliveryDedupe,
@@ -46,7 +45,9 @@ import {
46
45
  SHUTDOWN_SETTLE_MS,
47
46
  } from "@legion/envoy-client/envoy-settings"
48
47
  import { LoggableError, messageFor, natsFailureReason } from "@legion/envoy-client/errors"
48
+ import type { RelayOutage } from "@legion/envoy-client/listener-relay"
49
49
  import { machineID } from "@legion/envoy-client/machine"
50
+ import { refusedTopicsNoticeText, registerWithRelay } from "@legion/envoy-client/relay-registration"
50
51
  import {
51
52
  type SessionConfigFile,
52
53
  sessionConfigFile,
@@ -98,7 +99,7 @@ import {
98
99
  admittingMoves,
99
100
  channelReopener,
100
101
  closeUnstartedConnection,
101
- dialChannelNats,
102
+ dialChannelInbound,
102
103
  type ReopenConnection,
103
104
  type ReopenedConnection,
104
105
  START_STOPPING,
@@ -372,6 +373,9 @@ export interface ChannelSessionOptions {
372
373
  * alone. A failed move leaves the relay closed and the next registration retries it.
373
374
  */
374
375
  readonly followSession?: () => Promise<void>
376
+ /** Has a refused trade of the connection's own told the session's outage report: the relay
377
+ * socket's (`ListenerRelay.reportOutagesTo`); absent for NATS. */
378
+ readonly reportOutagesTo?: (outage: RelayOutage) => void
375
379
  /**
376
380
  * Told each `/clear` this session adopts from the handoff file, as it moves from `previous` to
377
381
  * `next` (`adoptHandoff`), before the new id registers: what else the server keeps under the
@@ -1341,6 +1345,9 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
1341
1345
  })
1342
1346
  },
1343
1347
  )
1348
+ // A relay socket's refused trade is this session's outage too, told once with its
1349
+ // registrations', which only a registration the listener accepted ends.
1350
+ options.reportOutagesTo?.(inboundOutage)
1344
1351
 
1345
1352
  /** The title last stamped, so a heartbeat stamps nothing new. */
1346
1353
  let stampedTitle: { readonly sessionID: string; readonly title: string } | undefined
@@ -1418,7 +1425,7 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
1418
1425
  relay: asking?.delivery,
1419
1426
  ...(relayMissing === undefined ? {} : { relayMissing }),
1420
1427
  ownAgentSubject: directSubject,
1421
- followed: followedTopics.topics(),
1428
+ followed: () => followedTopics.topics(),
1422
1429
  roles: heldRole === undefined ? [] : [heldRole],
1423
1430
  outage: inboundOutage,
1424
1431
  send: (topics, deliveryRequest) => {
@@ -1453,6 +1460,27 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
1453
1460
  answered: (result) => {
1454
1461
  if (asking !== undefined) takeDeliveryAnswer(sessionID, asking, result)
1455
1462
  },
1463
+ // An edge listener refused these topics for the projects of the session's token: they stop
1464
+ // being followed, here and in the ledger, so no later registration carries them and a
1465
+ // restart does not follow them again, and the session is told which, once, where it is told
1466
+ // an outage, whichever path registered. A session this process has since left keeps its own.
1467
+ drop: (topics, reason) => {
1468
+ if (identity.id !== sessionID) return
1469
+ for (const topic of topics) userTopics.delete(topic)
1470
+ followedTopics.unfollow(topics)
1471
+ ledger.followedChanged().catch((error: unknown) => {
1472
+ process.stderr.write(
1473
+ `envoy-channel: the topics the listener refused stay in the delivery state until it is written next — ${messageFor(error)}\n`,
1474
+ )
1475
+ })
1476
+ if (shuttingDown) return
1477
+ delivery.notice(refusedTopicsNoticeText(topics, reason)).catch((noticeError: unknown) => {
1478
+ process.stderr.write(
1479
+ `envoy-channel: the session could not be told which topics the listener refused — ${messageFor(noticeError)}\n`,
1480
+ )
1481
+ })
1482
+ },
1483
+ log: (line) => process.stderr.write(`envoy-channel: ${line}\n`),
1456
1484
  })
1457
1485
  }
1458
1486
 
@@ -2109,6 +2137,7 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
2109
2137
  }
2110
2138
  connection = live
2111
2139
  followSession = reopened.followSession
2140
+ reopened.reportOutagesTo?.(inboundOutage)
2112
2141
  // A handoff that waits for its relay opens it on this connection as it registers.
2113
2142
  if (relay !== undefined && !handoffDeliveryPending) subscribeRelay(relay)
2114
2143
  watchConnection(live)
@@ -2775,12 +2804,16 @@ export async function runEnvoyChannelServer(): Promise<void> {
2775
2804
  session = inboundOffChannelSession({ identity, stateDirectory, why: inbound.off })
2776
2805
  } else {
2777
2806
  starting =
2778
- inbound.natsCredential.kind === "broker"
2779
- ? "it waits for this session's broker token, and its stderr says what each trade came to"
2780
- : "it connects to NATS"
2807
+ "relaySetting" in inbound
2808
+ ? "it opens the listener's relay socket for this session, and its stderr says why an open failed"
2809
+ : inbound.natsCredential.kind === "broker"
2810
+ ? "it waits for this session's broker token, and its stderr says what each trade came to"
2811
+ : "it connects to NATS"
2781
2812
  const natsName = `claude-envoy-channel-${identity.id}`
2782
- const dialled = await dialChannelNats(
2813
+ const dialled = await dialChannelInbound(
2783
2814
  inbound,
2815
+ envoy.url,
2816
+ currentSessionId,
2784
2817
  natsName,
2785
2818
  (text, dialError) => {
2786
2819
  // A redial's warning names what the start waits on; the token keeper warns through the
@@ -2808,6 +2841,8 @@ export async function runEnvoyChannelServer(): Promise<void> {
2808
2841
  const followSession = admitting(dialled.followSession)
2809
2842
  const reopen = channelReopener({
2810
2843
  inbound,
2844
+ listenerUrl: envoy.url,
2845
+ session: currentSessionId,
2811
2846
  name: natsName,
2812
2847
  signal: booting.signal,
2813
2848
  swapKeeper: (stop) => {
@@ -2838,6 +2873,9 @@ export async function runEnvoyChannelServer(): Promise<void> {
2838
2873
  // The QA override names a fixed identity; only a Claude-minted id follows `/clear`.
2839
2874
  ...(configuredValue(overrideSessionId) === undefined ? { handoffPid: process.ppid } : {}),
2840
2875
  ...(followSession === undefined ? {} : { followSession }),
2876
+ ...(dialled.reportOutagesTo === undefined
2877
+ ? {}
2878
+ : { reportOutagesTo: dialled.reportOutagesTo }),
2841
2879
  // The live view follows a `/clear` the mod reported before it began listening.
2842
2880
  adopted: (previous, next) => agentStream?.sessionAdopted(previous, next),
2843
2881
  reopen,
@@ -2859,6 +2897,7 @@ export async function runEnvoyChannelServer(): Promise<void> {
2859
2897
  if (stopping || connection === undefined) return
2860
2898
  agentStream = startAgentStream({
2861
2899
  connection,
2900
+ liveView: dialled.liveView,
2862
2901
  // Only a Claude-minted id follows `/clear`; the override names a fixed identity.
2863
2902
  followsSessionId: configuredValue(overrideSessionId) === undefined,
2864
2903
  ...(admission === undefined ? {} : { admitted: (id: string) => admission.admitted(id) }),