@sjawhar/claude-envoy 4.6.1 → 4.7.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.
@@ -43,9 +43,18 @@ import {
43
43
  REGISTRATION_SETTLE_MS,
44
44
  SHUTDOWN_SETTLE_MS,
45
45
  } from "@legion/envoy-client/envoy-settings"
46
- import { messageFor } from "@legion/envoy-client/errors"
46
+ import { LoggableError, messageFor, natsFailureReason } from "@legion/envoy-client/errors"
47
47
  import { machineID } from "@legion/envoy-client/machine"
48
- import { natsConnectionOptions } from "@legion/envoy-client/nats-connection"
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"
49
58
  import {
50
59
  type SessionConfigFile,
51
60
  sessionConfigFile,
@@ -87,7 +96,7 @@ import { findPushedBranchHead, paneHandoffReport } from "@legion/pi-shared/hando
87
96
  import { Server } from "@modelcontextprotocol/sdk/server/index.js"
88
97
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
89
98
  import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js"
90
- import { connect } from "nats"
99
+ import { type ConnectionOptions, connect, type NatsConnection } from "nats"
91
100
  import { z } from "zod"
92
101
  import type { ModContentBlock, ModEvent } from "../hooks/mod-protocol"
93
102
  import { name as packageName, version as packageVersion } from "../package.json" with {
@@ -175,11 +184,12 @@ const HANDOFF_POLL_MS = 250
175
184
  /** How long a handoff waits for NATS to confirm the new direct subject before retrying. */
176
185
  const HANDOFF_FLUSH_TIMEOUT_MS = 10_000
177
186
 
178
- /** `promise`, or a rejection naming `what` once `ms` pass. */
187
+ /** `promise`, or a rejection naming `what` once `ms` pass. Its text is this server's own, so a
188
+ * NATS failure line prints it whole (`LoggableError`). */
179
189
  async function withTimeout<T>(promise: Promise<T>, ms: number, what: string): Promise<T> {
180
190
  let timer: ReturnType<typeof setTimeout> | undefined
181
191
  const expired = new Promise<never>((_, reject) => {
182
- timer = setTimeout(() => reject(new Error(`${what} timed out after ${ms} ms`)), ms)
192
+ timer = setTimeout(() => reject(new LoggableError(`${what} timed out after ${ms} ms`)), ms)
183
193
  })
184
194
  try {
185
195
  return await Promise.race([promise, expired])
@@ -352,6 +362,17 @@ export interface ChannelSessionOptions {
352
362
  readonly configFile: SessionConfigFile
353
363
  /** How long a handoff waits for NATS to confirm the new direct subject before it retries. */
354
364
  readonly handoffFlushTimeoutMs?: number
365
+ /**
366
+ * Moves the NATS connection to the broker token of the id now bound and returns once the
367
+ * connection is back, admitted with it (`followNatsCredential`), where the connection presents
368
+ * the session's broker token; absent otherwise. A handoff runs it before the new id's relay
369
+ * subject is subscribed: the auth service grants a session's token that session's subjects
370
+ * alone. A failed move leaves the relay closed and the next registration retries it.
371
+ */
372
+ readonly followSession?: () => Promise<void>
373
+ /** Ends a start still waiting for its connection to come back (`flushThroughRedials`): the
374
+ * process is stopping. */
375
+ readonly startSignal?: AbortSignal
355
376
  /** How long a deregistration waits for a registration already on the wire (default
356
377
  * `REGISTRATION_SETTLE_MS`), past which the DELETE goes out anyway. The shutdown path spends
357
378
  * at most `SHUTDOWN_SETTLE_MS` of it, over both of its waits. */
@@ -621,6 +642,211 @@ export function createChannelDelivery(input: {
621
642
  }
622
643
  }
623
644
 
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>
656
+ }
657
+
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
+ }
677
+ }
678
+
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>
687
+ }
688
+
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",
694
+ }
695
+
696
+ /**
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.
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 }),
734
+ ),
735
+ stopped.promise,
736
+ ])
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
+ } finally {
779
+ signal?.removeEventListener("abort", onAbort)
780
+ }
781
+ }
782
+
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
+ /**
794
+ * Flushes `connection`, asking again while the connection redials: nats.js rejects every pending
795
+ * flush with DISCONNECT each time it redials (`protocol.js`'s `prepare`), and a hub that is
796
+ * 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.
801
+ */
802
+ async function flushThroughRedials(
803
+ connection: ChannelConnection,
804
+ signal: AbortSignal | undefined,
805
+ ): Promise<void> {
806
+ const ended = Promise.withResolvers<"stopping" | "closed">()
807
+ const check = (): void => {
808
+ if (signal?.aborted === true) ended.resolve("stopping")
809
+ else if (connection.isClosed()) ended.resolve("closed")
810
+ }
811
+ const watch = setInterval(check, REDIAL_FLUSH_RETRY_MS)
812
+ 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
+ try {
823
+ for (;;) {
824
+ check()
825
+ const attempt = connection.flush().then(
826
+ () => ({ flushed: true as const }),
827
+ (error: unknown) => ({ flushed: false as const, error }),
828
+ )
829
+ const outcome = await Promise.race([attempt, ended.promise])
830
+ if (outcome === "stopping" || outcome === "closed") throw failure(outcome)
831
+ if (outcome.flushed) {
832
+ if (signal?.aborted === true) throw failure("stopping")
833
+ return
834
+ }
835
+ check()
836
+ if (signal?.aborted === true) throw failure("stopping", outcome.error)
837
+ if (connection.isClosed()) throw failure("closed", outcome.error)
838
+ const waited = await Promise.race([
839
+ Bun.sleep(REDIAL_FLUSH_RETRY_MS).then(() => "asked again" as const),
840
+ ended.promise,
841
+ ])
842
+ if (waited !== "asked again") throw failure(waited, outcome.error)
843
+ }
844
+ } finally {
845
+ clearInterval(watch)
846
+ signal?.removeEventListener("abort", check)
847
+ }
848
+ }
849
+
624
850
  /**
625
851
  * Begin the session's relay subscription before advertising the route to Envoy. The channel
626
852
  * server holds the listener's relay subject for the session's own durable consumer, which is
@@ -733,6 +959,9 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
733
959
  /** The writer of the bound id's state file (`replayStateWriter`), set by `restoreDelivery`. */
734
960
  let stateWriter: ReplayStateWriter | undefined
735
961
 
962
+ /** A handoff's relay still needs its new credential and delivery state before registration. */
963
+ let handoffDeliveryPending = false
964
+
736
965
  /**
737
966
  * What this session was already shown, and the notice naming a frame it could not be shown
738
967
  * (`@legion/envoy-client/delivery-ledger`), with its state in the session id's file.
@@ -947,7 +1176,7 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
947
1176
  }
948
1177
  } catch (error) {
949
1178
  process.stderr.write(
950
- `envoy-channel: the relay subscription of ${owner.sessionID} stopped — ${messageFor(error)}\n`,
1179
+ `envoy-channel: the relay subscription of ${owner.sessionID} stopped — ${natsFailureReason(error)}\n`,
951
1180
  )
952
1181
  }
953
1182
  }
@@ -1075,6 +1304,25 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
1075
1304
  * (`takeDeliveryAnswer`).
1076
1305
  */
1077
1306
  const register = async (): Promise<void> => {
1307
+ if (handoffDeliveryPending) {
1308
+ await options.followSession?.()
1309
+ if (shuttingDown) return
1310
+ // A refused subscription is closed by nats.js, not restored by its next reconnect, so no
1311
+ // new relay opens until the connection has been admitted as this session.
1312
+ await restoreDelivery()
1313
+ handoffDeliveryPending = false
1314
+ // Confirm the new relay before asking the listener to deliver to it. A stalled flush is
1315
+ // bounded; the listener retries a frame that reached no subscriber.
1316
+ await withTimeout(
1317
+ options.connection.flush(),
1318
+ options.handoffFlushTimeoutMs ?? HANDOFF_FLUSH_TIMEOUT_MS,
1319
+ "flushing NATS",
1320
+ ).catch((error: unknown) => {
1321
+ process.stderr.write(
1322
+ `envoy-channel: could not confirm the relay subscription of ${identity.id} — ${natsFailureReason(error)}\n`,
1323
+ )
1324
+ })
1325
+ }
1078
1326
  const title = options.title?.(identity.id) ?? ""
1079
1327
  if (
1080
1328
  options.stampTitle !== undefined &&
@@ -1392,30 +1640,17 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
1392
1640
  // process, which `/clear` would otherwise add one of per session.
1393
1641
  forgetBrokerSession(previous)
1394
1642
  directSubject = nextSubject
1643
+ // The old relay closes before moving credentials. Registration retries a failed move,
1644
+ // even though the identity already names the new session, and only then opens its relay.
1645
+ closeRelay()
1646
+ handoffDeliveryPending = true
1395
1647
  // `unfollow` only takes the subject out of the topic list a registration carries: nothing is
1396
1648
  // subscribed per topic, so there is nothing to drain and nothing to wait for.
1397
1649
  followedTopics.unfollow([previousSubject])
1398
- // The new id's delivery state: none after a `/clear`, which starts afresh as a new session
1399
- // does, so nothing published before it existed comes back. Until it is loaded, the ledger
1400
- // records nothing. Loading it closes the old id's relay (its unanswered frames `nak`) and
1401
- // subscribes the new id's relay subject.
1402
- await restoreDelivery()
1403
1650
  // The new id takes a record of its own: an attempt the old id handled is the old id's, and
1404
1651
  // the rows of a conversation a `/clear` ended name nothing in the new one.
1405
1652
  await restoreTurns()
1406
1653
  roleTransferFrom ??= previous
1407
- // The new relay subject reaches the server before the registration that asks for it. Not
1408
- // fatal: a relayed frame nobody answers pauses the relay, which sends again after its backoff
1409
- // and at the registration below.
1410
- await withTimeout(
1411
- options.connection.flush(),
1412
- options.handoffFlushTimeoutMs ?? HANDOFF_FLUSH_TIMEOUT_MS,
1413
- "flushing NATS",
1414
- ).catch((error: unknown) => {
1415
- process.stderr.write(
1416
- `envoy-channel: could not confirm the relay subscription of ${next} — ${messageFor(error)}\n`,
1417
- )
1418
- })
1419
1654
  await register()
1420
1655
  await transferRole()
1421
1656
  process.stderr.write(`envoy: session id changed ${previous} -> ${next}; re-registered\n`)
@@ -1616,7 +1851,9 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
1616
1851
  `envoy-channel: could not read the registered interests (${messageFor(error)}); the next heartbeat retries\n`,
1617
1852
  )
1618
1853
  })
1619
- await options.connection.flush()
1854
+ // The subscriptions reach the server before the first registration routes anything to them,
1855
+ // through any redial the connection is making as the session starts.
1856
+ await flushThroughRedials(options.connection, options.startSignal)
1620
1857
  await serialized(async () => {
1621
1858
  // Best-effort, as the interests read above is: a listener that refuses this registration
1622
1859
  // because it can give the session no consumer (`inboundOutage` tells the session
@@ -1714,7 +1951,7 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
1714
1951
  }
1715
1952
  } catch (error) {
1716
1953
  process.stderr.write(
1717
- `envoy-channel: the NATS connection's status reader failed — ${messageFor(error)}\n`,
1954
+ `envoy-channel: the NATS connection's status reader failed — ${natsFailureReason(error)}\n`,
1718
1955
  )
1719
1956
  }
1720
1957
  })()
@@ -2072,6 +2309,9 @@ export async function runEnvoyChannelServer(): Promise<void> {
2072
2309
  // at a time, and a restart is a new instance with a new id.
2073
2310
  const clientInstanceID = newClientInstanceID()
2074
2311
  let runtime: ChannelToolRuntime | undefined
2312
+ // What the start waits on, for a tool call it answers before the session is up: a start under
2313
+ // NATS_AUTH=broker waits for the session's token for as long as the server lives.
2314
+ let starting = "it reads its settings"
2075
2315
  let claim: LegionClaim | undefined
2076
2316
  const daemon = pane === undefined ? undefined : createLegionDaemonClient(pane.daemonUrl)
2077
2317
  // INFRA-220: the phase reminder's Claude Code host (`./legion-phase-hook`), which Claude Code's
@@ -2149,7 +2389,8 @@ export async function runEnvoyChannelServer(): Promise<void> {
2149
2389
  else if (op === "ready_for_update") phaseHook?.updateAnswered()
2150
2390
  return mcpResult(answer)
2151
2391
  }
2152
- if (runtime === undefined) throw new Error("Envoy channel server is still starting")
2392
+ if (runtime === undefined)
2393
+ throw new Error(`Envoy channel server is still starting: ${starting}`)
2153
2394
  try {
2154
2395
  return mcpResult(
2155
2396
  await executeEnvoyTool(runtime, request.params.name, request.params.arguments),
@@ -2220,10 +2461,16 @@ export async function runEnvoyChannelServer(): Promise<void> {
2220
2461
  const stopped = Promise.withResolvers<void>()
2221
2462
  let stopping = false
2222
2463
  let session: ChannelSession | undefined
2464
+ // Stops the keeper of the connection's broker token, where it presents one. Declared before
2465
+ // `stop`, which may run on a signal before the connection is dialled.
2466
+ let stopNatsKeeper = (): void => {}
2223
2467
  const stop = (): void => {
2224
2468
  if (stopping) return
2225
2469
  stopping = true
2226
2470
  booting.abort()
2471
+ // The token keeper stops before the session drains its connection: a renewal it ran on a
2472
+ // draining connection would be refused and warned about as a failure, at an ordinary stop.
2473
+ stopNatsKeeper()
2227
2474
  // A reminder waiting on a 15-minute WAITING wait holds no shutting-down server open.
2228
2475
  phaseHook?.stop()
2229
2476
  void modLink?.close().catch(() => undefined)
@@ -2246,7 +2493,9 @@ export async function runEnvoyChannelServer(): Promise<void> {
2246
2493
  // awaited: the transport is already reading stdin, and an await here would let the client's
2247
2494
  // first tool call arrive before the session below exists. A session whose link cannot bind
2248
2495
  // runs exactly as it does today, the mod finding nothing and staying silent.
2249
- void startModLink({
2496
+ // Kept, so a start that fails still waits for the bind and closes what it bound (the `finally`
2497
+ // below): a link bound after the failure would otherwise hold its socket for a dead session.
2498
+ const linking = startModLink({
2250
2499
  // The id Claude Code gave this process, which is what the mod reads as `$.session.id()`;
2251
2500
  // the ENVOY_SESSION_ID override names an Envoy identity, never a Claude Code session.
2252
2501
  sessionId: claudeSessionId({ CLAUDE_CODE_SESSION_ID: process.env["CLAUDE_CODE_SESSION_ID"] }),
@@ -2280,7 +2529,7 @@ export async function runEnvoyChannelServer(): Promise<void> {
2280
2529
  return active === null
2281
2530
  ? undefined
2282
2531
  : new DispatchClient(active.url, active.credential, fetch, {
2283
- signal: AbortSignal.timeout(ms),
2532
+ deadlineMs: ms,
2284
2533
  })
2285
2534
  },
2286
2535
  effortPicked: (effort) => agentStream?.pickedEffort(effort),
@@ -2310,14 +2559,40 @@ export async function runEnvoyChannelServer(): Promise<void> {
2310
2559
  stampOnce(() => identity.id)
2311
2560
  session = inboundOffChannelSession({ identity, stateDirectory, why: inbound.off })
2312
2561
  } else {
2313
- connection = await connect(
2314
- natsConnectionOptions({
2315
- servers: inbound.natsUrls,
2316
- name: `claude-envoy-channel-${identity.id}`,
2317
- seed: inbound.natsSeed,
2318
- }),
2319
- )
2320
- session = await startChannelSession({
2562
+ starting =
2563
+ inbound.natsCredential.kind === "broker"
2564
+ ? "it waits for this session's broker token, and its stderr says what each trade came to"
2565
+ : "it connects to NATS"
2566
+ const dialled = await dialChannelNats(
2567
+ inbound,
2568
+ `claude-envoy-channel-${identity.id}`,
2569
+ (text) => process.stderr.write(`envoy-channel: ${text}\n`),
2570
+ connect,
2571
+ booting.signal,
2572
+ ).catch((error: unknown) => {
2573
+ // A stop asked for while the token or the dial was awaited, as in the start below.
2574
+ if (stopping) return undefined
2575
+ throw error
2576
+ })
2577
+ if (dialled === undefined) return
2578
+ connection = dialled.connection
2579
+ stopNatsKeeper = dialled.stop
2580
+ starting = "it registers this session with Envoy"
2581
+ // Which id the connection is admitted as, where its broker token admits one session at a
2582
+ // time: the dial's, then each `/clear`'s once its move lands. The live view takes a new id's
2583
+ // control subject only then (`AgentStreamOptions.admitted`).
2584
+ const admission =
2585
+ 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
+ }
2595
+ const started = await startChannelSession({
2321
2596
  identity,
2322
2597
  connection,
2323
2598
  notifier,
@@ -2334,7 +2609,16 @@ export async function runEnvoyChannelServer(): Promise<void> {
2334
2609
  ...(stamping ? { stampTitle } : {}),
2335
2610
  // The QA override names a fixed identity; only a Claude-minted id follows `/clear`.
2336
2611
  ...(configuredValue(overrideSessionId) === undefined ? { handoffPid: process.ppid } : {}),
2612
+ ...(followSession === undefined ? {} : { followSession }),
2613
+ startSignal: booting.signal,
2614
+ }).catch((error: unknown) => {
2615
+ // A stop asked for while the session was still starting (its connection waiting on the
2616
+ // hub) ends the start, and is no failure: the process ends as an asked-for stop does.
2617
+ if (stopping) return undefined
2618
+ throw error
2337
2619
  })
2620
+ if (started === undefined) return
2621
+ session = started
2338
2622
  // INFRA-1026: the Agents page's live view, once this session's mod has a link to bind to.
2339
2623
  // It needs the bus as well as the link, so it starts here rather than beside the bind; a
2340
2624
  // session whose link never binds never starts one, and runs as it did before.
@@ -2346,6 +2630,7 @@ export async function runEnvoyChannelServer(): Promise<void> {
2346
2630
  connection: bus,
2347
2631
  // Only a Claude-minted id follows `/clear`; the override names a fixed identity.
2348
2632
  followsSessionId: configuredValue(overrideSessionId) === undefined,
2633
+ ...(admission === undefined ? {} : { admitted: (id: string) => admission.admitted(id) }),
2349
2634
  // A pane is the session whose person messages go to the bridge's inbox, which is the
2350
2635
  // same signal the router reads (`inPane`): a pane holds a daemon claim only where a
2351
2636
  // daemon started it, and the row the bridge seeds is there either way.
@@ -2414,9 +2699,21 @@ export async function runEnvoyChannelServer(): Promise<void> {
2414
2699
  if (stopping) await session.shutdown()
2415
2700
  await stopped.promise
2416
2701
  } finally {
2702
+ // A start that failed ends here as an asked-for stop does: every part it started stops, a
2703
+ // session it registered deregisters, and a mod link still binding is closed once bound
2704
+ // (`stopping` makes the bind close it), so no socket outlives the session. A stop already
2705
+ // under way makes `stop` a no-op.
2706
+ stop()
2707
+ await stopped.promise
2708
+ await linking
2417
2709
  await modLink?.close().catch(() => undefined)
2418
2710
  if (session === undefined && connection !== undefined) {
2419
- await connection.drain().catch(() => 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
+ ])
2420
2717
  await connection.close().catch(() => undefined)
2421
2718
  }
2422
2719
  // Release stdin so the process can exit once the session is deregistered,
@@ -0,0 +1,111 @@
1
+ import type { RequestCredential } from "@legion/envoy-client/bearer"
2
+ import { createEnvoyClient } from "@legion/envoy-client/transport"
3
+
4
+ export type SendEnvoyMessageOptions = {
5
+ readonly baseUrl: string
6
+ /** What the send presents (`EnabledEnvoySettings.credential`): the listener's bearer, this
7
+ * machine's broker credential, which signs a DPoP proof for this request, or none, which
8
+ * sends no `Authorization` header, for a loopback listener that asks for none. */
9
+ readonly credential: RequestCredential | undefined
10
+ /** The session the shell names, which the message goes from (`source_session`), so the
11
+ * listener counts it against that session's sending limit; "" for a shell that names none,
12
+ * which the transport leaves off the wire. */
13
+ readonly sourceSession?: string
14
+ readonly targetSession: string
15
+ readonly message: string
16
+ /** The key the send goes under: the one an unconfirmed send named, to resend it safely. One is
17
+ * minted where none is given. */
18
+ readonly idempotencyKey?: string
19
+ }
20
+
21
+ /** What a stored send went without. */
22
+ export type SentEnvoyMessage = {
23
+ /**
24
+ * Why the send went without its credential: the very error the credential's `headers` threw
25
+ * for the attempt the listener stored, which a listener that asks for no credential stores as
26
+ * it stores any. Undefined where that attempt carried the credential, an attempt before it that
27
+ * went without included, and where the send was handed none to carry.
28
+ */
29
+ readonly withoutCredential: unknown
30
+ }
31
+
32
+ /**
33
+ * `credential`, every member of it as it is, with the outcome of its last `headers` kept: the
34
+ * error it threw or rejected with, rethrown unchanged, or none where it answered headers. A
35
+ * bearer's headers still come at once, and a broker credential's as its promise settles.
36
+ */
37
+ function recorded(credential: RequestCredential): {
38
+ readonly credential: RequestCredential
39
+ readonly lastFailure: () => unknown
40
+ } {
41
+ let failure: unknown
42
+ const answered = (headers: Readonly<Record<string, string>>) => {
43
+ failure = undefined
44
+ return headers
45
+ }
46
+ const failed = (error: unknown): never => {
47
+ failure = error
48
+ throw error
49
+ }
50
+ return {
51
+ credential: {
52
+ scheme: credential.scheme,
53
+ headers: (method, url, session, signal) => {
54
+ try {
55
+ const ready = credential.headers(method, url, session, signal)
56
+ return ready instanceof Promise ? ready.then(answered, failed) : answered(ready)
57
+ } catch (error) {
58
+ return failed(error)
59
+ }
60
+ },
61
+ ...(credential.stale === undefined
62
+ ? {}
63
+ : { stale: (session, presented) => credential.stale?.(session, presented) }),
64
+ ...(credential.identity === undefined
65
+ ? {}
66
+ : { identity: (presented) => credential.identity?.(presented) }),
67
+ secret: () => credential.secret(),
68
+ },
69
+ lastFailure: () => failure,
70
+ }
71
+ }
72
+
73
+ /**
74
+ * Sends one direct message through envoy-client's own send (`createEnvoyClient().send`), so the
75
+ * `envoy-send` command keeps every rule a session's own send keeps:
76
+ * - one idempotency key for the message, on every attempt, so the listener stores it at most
77
+ * once however many attempts reach it;
78
+ * - an attempt that got no answer or a 5xx is sent again under that key, after 250 ms;
79
+ * - a send that may have arrived is told so (`EnvoySendUnconfirmedError`), naming the key that
80
+ * resends it safely, never "failed";
81
+ * - each attempt's credential waits the attempt less the request's reserve
82
+ * (`credentialDeadline`), and a credential that could not be minted lets the request go
83
+ * without it, which a listener that asks for no credential answers. A listener that wants one
84
+ * answers 401 at its auth gate, and the error names both halves and no resend, since nothing
85
+ * was stored.
86
+ *
87
+ * A stored send answers what it went without (`SentEnvoyMessage`), so the command can say so: a
88
+ * sign-in revoked for good is stored without the credential by a listener that asks for none, and
89
+ * nothing else would tell the person.
90
+ */
91
+ export async function sendEnvoyMessage(
92
+ options: SendEnvoyMessageOptions,
93
+ ): Promise<SentEnvoyMessage> {
94
+ const kept = options.credential === undefined ? undefined : recorded(options.credential)
95
+ const client = createEnvoyClient({
96
+ baseUrl: options.baseUrl,
97
+ fetch: globalThis.fetch,
98
+ credential: kept?.credential,
99
+ })
100
+ // The shell's session as the message's source, so the listener counts the message against that
101
+ // session's sending limit; a shell that names no session sends a blank one, which the transport
102
+ // leaves off the wire. A refusal is an `EnvoyApiError` whose message is the listener's own
103
+ // sentence, which `envoy-send` prints.
104
+ await client.send({
105
+ sourceSessionID: options.sourceSession ?? "",
106
+ targetSessionID: options.targetSession,
107
+ message: options.message,
108
+ ...(options.idempotencyKey === undefined ? {} : { idempotencyKey: options.idempotencyKey }),
109
+ })
110
+ return { withoutCredential: kept?.lastFailure() }
111
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Ends the channel server's process with `code` once everything already written to stdout and
3
+ * stderr has reached the pipe: an MCP reply Claude Code reads on stdout, or the failure line on
4
+ * stderr. A handle nothing will use can outlive the run (a NATS dial that a stop ended waits out
5
+ * nats.js's own dial timeout), so the process ends here rather than when that handle lets go; but
6
+ * `process.exit` drops what Bun still holds for a full pipe, and in Bun a write's callback, and
7
+ * `drain`, come before the bytes leave. Ending each stream is what waits: its callback runs once
8
+ * the pipe has taken every byte, however slow the reader.
9
+ */
10
+ export async function exitProcess(code: number): Promise<never> {
11
+ await Promise.all([ended(process.stdout), ended(process.stderr)])
12
+ process.exit(code)
13
+ }
14
+
15
+ /** Ends `stream` and settles once every byte written to it has been handed on, or it failed. */
16
+ function ended(stream: NodeJS.WriteStream): Promise<void> {
17
+ return new Promise((settle) => {
18
+ if (stream.destroyed || stream.writableFinished) return settle()
19
+ // A reader gone (EPIPE) fails the stream: nothing is left to wait for.
20
+ stream.once("error", () => settle())
21
+ stream.end(() => settle())
22
+ })
23
+ }