@sjawhar/claude-envoy 4.6.0 → 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.
- package/.claude-plugin/plugin.json +1 -1
- package/.omp-plugin/plugin.json +1 -1
- package/README.md +33 -14
- package/bin/envoy-channel.ts +15 -1
- package/bin/envoy-send.ts +122 -15
- package/dist/THIRD_PARTY_NOTICES +0 -30
- package/dist/codex-hook.js +8550 -8194
- package/dist/codex-tool-hook.js +2 -3
- package/dist/dispatch.js +9504 -9106
- package/dist/envoy-channel.js +23425 -22778
- package/dist/session-hook.js +8599 -8242
- package/dist/session-title-hook.js +248 -14
- package/hooks/session-hook.ts +15 -7
- package/hooks/session-title-hook.ts +4 -0
- package/package.json +2 -1
- package/src/agent-stream-runner.ts +18 -1
- package/src/channel-topics.ts +3 -2
- package/src/codex/codex-agent-stream.ts +19 -1
- package/src/codex/codex-delivery.ts +71 -28
- package/src/codex/codex-inbox.ts +10 -6
- package/src/codex/codex-server.ts +39 -8
- package/src/envoy-channel-server.ts +334 -37
- package/src/envoy-client.ts +111 -0
- package/src/process-exit.ts +23 -0
- package/src/send-arguments.ts +91 -2
|
@@ -8,7 +8,6 @@ import { DispatchClient } from "@legion/envoy-client/dispatch-http"
|
|
|
8
8
|
import { sessionDirectory as dispatchSessionDirectory } from "@legion/envoy-client/dispatch-session-directory"
|
|
9
9
|
import { writeSessionTitle } from "@legion/envoy-client/dispatch-session-state"
|
|
10
10
|
import { messageFor } from "@legion/envoy-client/errors"
|
|
11
|
-
import { natsConnectionOptions } from "@legion/envoy-client/nats-connection"
|
|
12
11
|
import {
|
|
13
12
|
sessionConfigFile,
|
|
14
13
|
sessionDispatchSettings,
|
|
@@ -28,10 +27,12 @@ import {
|
|
|
28
27
|
type ChannelSession,
|
|
29
28
|
type ChannelToolRuntime,
|
|
30
29
|
channelToolDefinitions,
|
|
30
|
+
dialChannelNats,
|
|
31
31
|
executeEnvoyTool,
|
|
32
32
|
MCP_SERVER_INFO,
|
|
33
33
|
mcpResult,
|
|
34
34
|
postDispatchReply,
|
|
35
|
+
sessionAdmission,
|
|
35
36
|
startChannelSession,
|
|
36
37
|
} from "../envoy-channel-server"
|
|
37
38
|
import { inboundOffChannelSession } from "../envoy-off"
|
|
@@ -328,6 +329,8 @@ export async function runCodexEnvoyServer(): Promise<void> {
|
|
|
328
329
|
let session: ChannelSession | undefined
|
|
329
330
|
let connection: ChannelConnection | undefined
|
|
330
331
|
let stream: CodexAgentStream | undefined
|
|
332
|
+
/** Stops the keeper of the connection's broker token, once one is dialled. */
|
|
333
|
+
let stopNatsKeeper: () => void = () => undefined
|
|
331
334
|
let follower: TranscriptFollower | undefined
|
|
332
335
|
let delivery: ReturnType<typeof createCodexDelivery> | undefined
|
|
333
336
|
|
|
@@ -341,6 +344,7 @@ export async function runCodexEnvoyServer(): Promise<void> {
|
|
|
341
344
|
clearInterval(recheck)
|
|
342
345
|
follower?.stop()
|
|
343
346
|
stream?.stop()
|
|
347
|
+
stopNatsKeeper()
|
|
344
348
|
// The entry goes once the delivery's waiting lines are withdrawn, so a server that takes over
|
|
345
349
|
// never discards a line this one still answers for.
|
|
346
350
|
const withdrawn = (delivery?.stop() ?? Promise.resolve()).finally(() =>
|
|
@@ -527,13 +531,31 @@ export async function runCodexEnvoyServer(): Promise<void> {
|
|
|
527
531
|
if ("off" in inbound) {
|
|
528
532
|
session = inboundOffChannelSession({ identity: id, stateDirectory, why: inbound.off })
|
|
529
533
|
} else {
|
|
530
|
-
connection
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
}
|
|
534
|
+
// Dialled as the Claude Code session's connection is (`dialChannelNats`): with a seed, no
|
|
535
|
+
// 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.
|
|
537
|
+
const dialled = await dialChannelNats(
|
|
538
|
+
inbound,
|
|
539
|
+
`codex-envoy-channel-${id.id}`,
|
|
540
|
+
warn,
|
|
541
|
+
connect,
|
|
542
|
+
stopping.signal,
|
|
536
543
|
)
|
|
544
|
+
connection = dialled.connection
|
|
545
|
+
stopNatsKeeper = dialled.stop
|
|
546
|
+
// Which id the connection is admitted as, where its broker token admits one session at a
|
|
547
|
+
// time: the dial's, then each `/new`'s once its move lands. The live view takes a new id's
|
|
548
|
+
// control subject only then (`CodexAgentStreamOptions.admitted`).
|
|
549
|
+
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
|
+
}
|
|
537
559
|
session = await startChannelSession({
|
|
538
560
|
capabilities: () => CODEX_CAPABILITIES,
|
|
539
561
|
client,
|
|
@@ -543,6 +565,7 @@ export async function runCodexEnvoyServer(): Promise<void> {
|
|
|
543
565
|
handoffPid: codexPid,
|
|
544
566
|
heartbeatMs: envoy.heartbeatMs,
|
|
545
567
|
identity: id,
|
|
568
|
+
...(followSession === undefined ? {} : { followSession }),
|
|
546
569
|
notifier: {
|
|
547
570
|
notification: ({ content, eventId }) =>
|
|
548
571
|
codexDelivery.deliver({ content, ...(eventId === undefined ? {} : { eventId }) }),
|
|
@@ -573,7 +596,14 @@ export async function runCodexEnvoyServer(): Promise<void> {
|
|
|
573
596
|
title,
|
|
574
597
|
...(dispatch.enabled ? { stampTitle } : {}),
|
|
575
598
|
})
|
|
576
|
-
stream = startCodexAgentStream({
|
|
599
|
+
stream = startCodexAgentStream({
|
|
600
|
+
connection,
|
|
601
|
+
sessionId: id.id,
|
|
602
|
+
warn,
|
|
603
|
+
...(admission === undefined
|
|
604
|
+
? {}
|
|
605
|
+
: { admitted: (next: string) => admission.admitted(next) }),
|
|
606
|
+
})
|
|
577
607
|
}
|
|
578
608
|
runtime = { client, clientInstanceID, identity: id, session }
|
|
579
609
|
follow(bound.transcript_path)
|
|
@@ -585,6 +615,7 @@ export async function runCodexEnvoyServer(): Promise<void> {
|
|
|
585
615
|
await stopped.promise
|
|
586
616
|
} finally {
|
|
587
617
|
follower?.stop()
|
|
618
|
+
stopNatsKeeper()
|
|
588
619
|
if (session === undefined && connection !== undefined) {
|
|
589
620
|
await connection.drain().catch(() => undefined)
|
|
590
621
|
await connection.close().catch(() => undefined)
|
|
@@ -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 {
|
|
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
|
|
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 — ${
|
|
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
|
-
|
|
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 — ${
|
|
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)
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
2314
|
-
|
|
2315
|
-
|
|
2316
|
-
|
|
2317
|
-
|
|
2318
|
-
|
|
2319
|
-
|
|
2320
|
-
|
|
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
|
-
|
|
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,
|