@sjawhar/claude-envoy 2.8.0 → 2.10.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/AGENTS.md +68 -72
- package/README.md +34 -38
- package/dist/dispatch.js +135 -138
- package/dist/envoy-channel.js +706 -1372
- package/dist/session-hook.js +3 -52
- package/package.json +1 -1
- package/skills/approval-review/SKILL.md +256 -0
- package/skills/approval-review/references/never-decide.md +154 -0
- package/skills/approval-review/references/reviewer-principles.md +54 -0
- package/skills/envoy/SKILL.md +96 -22
- package/skills/envoy/references/deliveries.md +71 -15
- package/skills/envoy/references/legion.md +34 -8
- package/src/agent-stream-runner.ts +2 -2
- package/src/channel-topics.ts +148 -0
- package/src/envoy-channel-server.ts +279 -378
- package/src/replay-state.ts +17 -17
- package/src/channel-forwarder.ts +0 -262
|
@@ -12,22 +12,32 @@ import {
|
|
|
12
12
|
type ConsumerDelivery,
|
|
13
13
|
type ConsumerDeliverySnapshot,
|
|
14
14
|
type ConsumerFrame,
|
|
15
|
+
type ConsumerGapNotice,
|
|
15
16
|
createConsumerDelivery,
|
|
17
|
+
gapNoticeText,
|
|
18
|
+
inboundUnavailable,
|
|
19
|
+
inboundUnavailableNoticeText,
|
|
20
|
+
registerWithRelay,
|
|
16
21
|
} from "@legion/envoy-client/consumer-delivery"
|
|
17
22
|
import {
|
|
18
23
|
createDeliveryDedupe,
|
|
19
24
|
type DispatchDelivery,
|
|
20
|
-
expectsLaneReceipt,
|
|
21
25
|
inboundTimestamp,
|
|
22
26
|
postDeliveryReply,
|
|
23
27
|
type RenderInboundResult,
|
|
24
28
|
renderInbound,
|
|
25
29
|
} from "@legion/envoy-client/delivery"
|
|
30
|
+
import {
|
|
31
|
+
closeReplayedRemoval,
|
|
32
|
+
createDeliveryLedger,
|
|
33
|
+
type DeliveryLedger,
|
|
34
|
+
envoyNoticeText,
|
|
35
|
+
failureNoticeFields,
|
|
36
|
+
} from "@legion/envoy-client/delivery-ledger"
|
|
26
37
|
import { activeDispatchSettings } from "@legion/envoy-client/dispatch-config"
|
|
27
38
|
import { DispatchClient } from "@legion/envoy-client/dispatch-http"
|
|
28
39
|
import { sessionDirectory as dispatchSessionDirectory } from "@legion/envoy-client/dispatch-session-directory"
|
|
29
40
|
import { writeSessionTitle } from "@legion/envoy-client/dispatch-session-state"
|
|
30
|
-
import { subscriptionRemovedTopics } from "@legion/envoy-client/dispatch-subscribe"
|
|
31
41
|
import {
|
|
32
42
|
heartbeatRetryDelayMs,
|
|
33
43
|
REGISTRATION_SETTLE_MS,
|
|
@@ -36,21 +46,6 @@ import {
|
|
|
36
46
|
import { messageFor } from "@legion/envoy-client/errors"
|
|
37
47
|
import { machineID } from "@legion/envoy-client/machine"
|
|
38
48
|
import { natsConnectionOptions } from "@legion/envoy-client/nats-connection"
|
|
39
|
-
import {
|
|
40
|
-
closeReplayedRemoval,
|
|
41
|
-
createReplayEngine,
|
|
42
|
-
envoyNoticeText,
|
|
43
|
-
failureNoticeFields,
|
|
44
|
-
type ReplayDeliveryOutcome,
|
|
45
|
-
type ReplayFrame,
|
|
46
|
-
type ReplayNotice,
|
|
47
|
-
reachesPrivateStreamSubject,
|
|
48
|
-
rememberedTopics,
|
|
49
|
-
replayedText,
|
|
50
|
-
replayFollowedSubjects,
|
|
51
|
-
replaySuppressed,
|
|
52
|
-
routeReplayNotice,
|
|
53
|
-
} from "@legion/envoy-client/replay"
|
|
54
49
|
import {
|
|
55
50
|
type SessionConfigFile,
|
|
56
51
|
sessionConfigFile,
|
|
@@ -58,6 +53,12 @@ import {
|
|
|
58
53
|
sessionSettings,
|
|
59
54
|
} from "@legion/envoy-client/session-settings"
|
|
60
55
|
import { postSlackReply } from "@legion/envoy-client/slack-post"
|
|
56
|
+
import {
|
|
57
|
+
refuseUncapturedTopics,
|
|
58
|
+
registrationTopics,
|
|
59
|
+
rememberedTopics,
|
|
60
|
+
replayFollowedSubjects,
|
|
61
|
+
} from "@legion/envoy-client/stream-topics"
|
|
61
62
|
import {
|
|
62
63
|
EnvoyToolOperation,
|
|
63
64
|
envoyToolSpecs,
|
|
@@ -93,13 +94,12 @@ import { name as packageName, version as packageVersion } from "../package.json"
|
|
|
93
94
|
}
|
|
94
95
|
import { type AgentStreamRunner, startAgentStream } from "./agent-stream-runner"
|
|
95
96
|
import {
|
|
96
|
-
type
|
|
97
|
-
type ChannelForwarderConnection,
|
|
98
|
-
type ChannelInboundMessage,
|
|
97
|
+
type ChannelConnection,
|
|
99
98
|
type ChannelTopicSubscription,
|
|
100
|
-
|
|
99
|
+
type ChannelTopics,
|
|
100
|
+
createChannelTopics,
|
|
101
101
|
deliveryIdentity,
|
|
102
|
-
} from "./channel-
|
|
102
|
+
} from "./channel-topics"
|
|
103
103
|
import { claudeProjectDirectory, claudeSessionId, configuredValue } from "./claude-session"
|
|
104
104
|
import { inboundOffChannelSession, serveEnvoyOff } from "./envoy-off"
|
|
105
105
|
import { installedPluginVersion } from "./installed-build"
|
|
@@ -168,7 +168,6 @@ import {
|
|
|
168
168
|
const CHANNEL_INSTRUCTIONS =
|
|
169
169
|
"Envoy delivers trusted, internal session and Dispatch events into this conversation. Use the Envoy tools for Envoy actions, and reach Dispatch through the `dispatch` command in Bash (`dispatch --help` lists its commands; the `dispatch` skill teaches them). Dispatch asks stay on Dispatch."
|
|
170
170
|
const CHANNEL_INBOX_LIMIT = 50
|
|
171
|
-
const EMPTY_RECEIPT = new Uint8Array()
|
|
172
171
|
const encoder = new TextEncoder()
|
|
173
172
|
/** How often the handoff file is checked for a `/clear`. */
|
|
174
173
|
const HANDOFF_POLL_MS = 250
|
|
@@ -258,7 +257,7 @@ export interface ChannelDelivery {
|
|
|
258
257
|
* skipped, dropped, suppressed, or answered on Dispatch with an error instead (once that reply
|
|
259
258
|
* is posted), and `true` without a write for an event whose card the session already has.
|
|
260
259
|
* `late` is a relay frame delivered before or stored before the current epoch
|
|
261
|
-
* (`ConsumerFrame.late`): a late BTW is suppressed
|
|
260
|
+
* (`ConsumerFrame.late`): a late BTW is suppressed.
|
|
262
261
|
*/
|
|
263
262
|
enqueue(input: {
|
|
264
263
|
readonly subject: string
|
|
@@ -270,25 +269,23 @@ export interface ChannelDelivery {
|
|
|
270
269
|
}
|
|
271
270
|
|
|
272
271
|
/**
|
|
273
|
-
* The delivery path of a running session, which also shows
|
|
274
|
-
*
|
|
275
|
-
* the conversation, or the Legion bridge's inbox.
|
|
272
|
+
* The delivery path of a running session, which also shows Envoy's own notices on the same
|
|
273
|
+
* notifier as a live frame: the mod's write into the conversation, or the Legion bridge's inbox.
|
|
276
274
|
*/
|
|
277
275
|
export interface ChannelDeliveryPath extends ChannelDelivery {
|
|
278
276
|
/**
|
|
279
|
-
* Shows a
|
|
280
|
-
*
|
|
281
|
-
*
|
|
282
|
-
*
|
|
277
|
+
* Shows a notice of Envoy's own; a rejection says it was not shown. `addressed` names the
|
|
278
|
+
* session the notice is for: the notice waits its turn behind every frame queued before it,
|
|
279
|
+
* and a `/clear` can move this process to another id while it waits, so the id is compared
|
|
280
|
+
* when the notice's turn comes, and a notice for an id this process no longer serves is
|
|
281
|
+
* refused rather than shown to the conversation it moved to.
|
|
283
282
|
*/
|
|
284
|
-
|
|
285
|
-
/** Shows a notice of Envoy's own; a rejection says it was not shown. */
|
|
286
|
-
notice(content: string): Promise<void>
|
|
283
|
+
notice(content: string, addressed?: string): Promise<void>
|
|
287
284
|
}
|
|
288
285
|
|
|
289
286
|
export interface ChannelSession {
|
|
290
287
|
readonly delivery: ChannelDelivery
|
|
291
|
-
/** Every
|
|
288
|
+
/** Every subject this session follows, direct route included. */
|
|
292
289
|
topics(): readonly string[]
|
|
293
290
|
/** Follow Envoy topics and refresh the registry interest; returns the topics that were new. */
|
|
294
291
|
follow(topics: readonly string[]): Promise<readonly string[]>
|
|
@@ -325,7 +322,7 @@ export interface ChannelSession {
|
|
|
325
322
|
|
|
326
323
|
export interface ChannelSessionOptions {
|
|
327
324
|
readonly identity: SessionIdentity
|
|
328
|
-
readonly connection:
|
|
325
|
+
readonly connection: ChannelConnection
|
|
329
326
|
readonly notifier: ChannelNotifier
|
|
330
327
|
/**
|
|
331
328
|
* The delivery modes the session advertises to the listener, which Dispatch checks every
|
|
@@ -344,13 +341,7 @@ export interface ChannelSessionOptions {
|
|
|
344
341
|
readonly router?: (state: UserTurnState) => UserTurnRouter
|
|
345
342
|
readonly client: Pick<
|
|
346
343
|
EnvoyClient,
|
|
347
|
-
| "
|
|
348
|
-
| "unsubscribe"
|
|
349
|
-
| "unregisterSession"
|
|
350
|
-
| "setRole"
|
|
351
|
-
| "getRole"
|
|
352
|
-
| "getInterest"
|
|
353
|
-
| "replay"
|
|
344
|
+
"subscribe" | "unsubscribe" | "unregisterSession" | "setRole" | "getRole" | "getInterest"
|
|
354
345
|
>
|
|
355
346
|
readonly heartbeatMs: number
|
|
356
347
|
/**
|
|
@@ -373,7 +364,7 @@ export interface ChannelSessionOptions {
|
|
|
373
364
|
readonly scheduleRetry?: (run: () => void, delayMs: number) => () => void
|
|
374
365
|
/**
|
|
375
366
|
* `${CLAUDE_PLUGIN_DATA}`: role state per session id, the per-process handoff files, and the
|
|
376
|
-
*
|
|
367
|
+
* delivery state per session id.
|
|
377
368
|
*/
|
|
378
369
|
readonly stateDirectory: string
|
|
379
370
|
/**
|
|
@@ -515,9 +506,6 @@ export function createChannelDelivery(input: {
|
|
|
515
506
|
return run
|
|
516
507
|
}
|
|
517
508
|
|
|
518
|
-
const write = (notification: ChannelNotification): Promise<void> =>
|
|
519
|
-
queued(() => input.notifier.notification(notification))
|
|
520
|
-
|
|
521
509
|
/** Lists a rendered frame in the inbox, naming one Envoy event once: the server is
|
|
522
510
|
* at-least-once, so the copy Envoy sends after an unanswered frame is written to the session
|
|
523
511
|
* again — where the mod's record keeps it from reaching the engine twice (`./mod-session`) —
|
|
@@ -549,19 +537,13 @@ export function createChannelDelivery(input: {
|
|
|
549
537
|
...(rendered.envelope?.event_id === undefined ? {} : { eventId: rendered.envelope.event_id }),
|
|
550
538
|
})
|
|
551
539
|
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
list(rendered)
|
|
555
|
-
return write(notification(rendered, content))
|
|
556
|
-
}
|
|
557
|
-
|
|
558
|
-
// A replayed or late BTW is never answered: the question was asked while this session was not
|
|
559
|
-
// taking messages, and Dispatch has long since recorded the attempt. Only a live one runs
|
|
540
|
+
// A late BTW is never answered: the question was asked while this session was not taking
|
|
541
|
+
// messages, and Dispatch has long since recorded the attempt. Only a live one runs
|
|
560
542
|
// (`./user-turn-router`).
|
|
561
|
-
const
|
|
543
|
+
const passOverLateBtw = (rendered: RenderInboundResult): boolean => {
|
|
562
544
|
if (rendered.delivery?.mode !== "btw") return false
|
|
563
545
|
process.stderr.write(
|
|
564
|
-
`envoy-channel: passing over
|
|
546
|
+
`envoy-channel: passing over late BTW ${rendered.envelope?.event_id ?? "unknown"}: it was asked while this session was not taking messages\n`,
|
|
565
547
|
)
|
|
566
548
|
return true
|
|
567
549
|
}
|
|
@@ -596,7 +578,7 @@ export function createChannelDelivery(input: {
|
|
|
596
578
|
)
|
|
597
579
|
return tail.then(() => false)
|
|
598
580
|
}
|
|
599
|
-
if (late === true &&
|
|
581
|
+
if (late === true && passOverLateBtw(rendered)) return tail.then(() => false)
|
|
600
582
|
return queued(async () => {
|
|
601
583
|
// A message Dispatch accepted as this session's own turn is never also a card. A failure
|
|
602
584
|
// after that acceptance throws, so the frame is not answered and the listener sends it
|
|
@@ -606,8 +588,8 @@ export function createChannelDelivery(input: {
|
|
|
606
588
|
list(rendered)
|
|
607
589
|
return true
|
|
608
590
|
}
|
|
609
|
-
// Written here rather than through `
|
|
610
|
-
// `
|
|
591
|
+
// Written here rather than through another `queued` call: this already runs inside the
|
|
592
|
+
// queue, and a nested `queued` would wait on a tail this call is itself the end of. A write that failed
|
|
611
593
|
// throws, so the frame goes unanswered and Envoy sends the event again; the mod writes
|
|
612
594
|
// the message of one event id once, however many copies of it arrive
|
|
613
595
|
// (`../hooks/mod-writer.ts`, `writeOnce`), so the resend costs the model nothing and the
|
|
@@ -617,15 +599,15 @@ export function createChannelDelivery(input: {
|
|
|
617
599
|
return true
|
|
618
600
|
})
|
|
619
601
|
},
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
602
|
+
notice(content, addressed) {
|
|
603
|
+
return queued(async () => {
|
|
604
|
+
if (addressed !== undefined && addressed !== input.identity.id) {
|
|
605
|
+
throw new Error(
|
|
606
|
+
`the notice names session ${addressed}, and this process serves ${input.identity.id}`,
|
|
607
|
+
)
|
|
608
|
+
}
|
|
609
|
+
await input.notifier.notification({ content })
|
|
610
|
+
})
|
|
629
611
|
},
|
|
630
612
|
inbox() {
|
|
631
613
|
return [...inbox]
|
|
@@ -634,36 +616,10 @@ export function createChannelDelivery(input: {
|
|
|
634
616
|
}
|
|
635
617
|
|
|
636
618
|
/**
|
|
637
|
-
*
|
|
638
|
-
*
|
|
639
|
-
*
|
|
640
|
-
*
|
|
641
|
-
* relays (consumer delivery), answers the receipt and queues nothing.
|
|
642
|
-
*/
|
|
643
|
-
export async function enqueueChannelMessage(
|
|
644
|
-
delivery: ChannelDelivery,
|
|
645
|
-
connection: ChannelForwarderConnection,
|
|
646
|
-
directSubject: string,
|
|
647
|
-
message: ChannelInboundMessage,
|
|
648
|
-
): Promise<boolean> {
|
|
649
|
-
const queued = message.duplicate
|
|
650
|
-
? Promise.resolve(false)
|
|
651
|
-
: delivery.enqueue({ subject: message.subject, raw: message.raw })
|
|
652
|
-
const lane = {
|
|
653
|
-
subject: message.subject,
|
|
654
|
-
directSubject,
|
|
655
|
-
envelopeTopic: message.envelopeTopic,
|
|
656
|
-
reply: message.reply,
|
|
657
|
-
}
|
|
658
|
-
if (expectsLaneReceipt(lane)) connection.publish(lane.reply, EMPTY_RECEIPT)
|
|
659
|
-
return queued
|
|
660
|
-
}
|
|
661
|
-
|
|
662
|
-
/**
|
|
663
|
-
* Begin one real NATS consumer before advertising the route to Envoy. The
|
|
664
|
-
* channel server owns direct and followed subjects, and the listener's relay
|
|
665
|
-
* subject when it delivers the session's consumer, so no Monitor or helper
|
|
666
|
-
* process is needed between NATS and Claude Code.
|
|
619
|
+
* Begin the session's relay subscription before advertising the route to Envoy. The channel
|
|
620
|
+
* server holds the listener's relay subject for the session's own durable consumer, which is
|
|
621
|
+
* every message it receives, so no Monitor or helper process is needed between NATS and Claude
|
|
622
|
+
* Code.
|
|
667
623
|
*/
|
|
668
624
|
export async function startChannelSession(options: ChannelSessionOptions): Promise<ChannelSession> {
|
|
669
625
|
const { identity } = options
|
|
@@ -747,122 +703,81 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
|
|
|
747
703
|
})
|
|
748
704
|
}
|
|
749
705
|
|
|
750
|
-
// The
|
|
706
|
+
// The relay path's claims: a frame being delivered is not handed on a second time, and a claim
|
|
707
|
+
// outlives the frame, so a redelivery that arrives before the ledger records it is a repeat.
|
|
751
708
|
const dedupe = createDeliveryDedupe()
|
|
752
709
|
/**
|
|
753
|
-
* The session id whose
|
|
754
|
-
* current id, so the work of one id never lands in another's file across a `/clear`.
|
|
710
|
+
* The session id whose delivery record the ledger holds. The ledger does nothing until it is
|
|
711
|
+
* the current id, so the work of one id never lands in another's file across a `/clear`.
|
|
755
712
|
*/
|
|
756
|
-
let
|
|
713
|
+
let ledgerBound: string | undefined
|
|
757
714
|
|
|
758
715
|
/**
|
|
759
|
-
*
|
|
760
|
-
*
|
|
761
|
-
*
|
|
762
|
-
* The frame is claimed in the live path's dedupe before it is handed to the write queue, as a
|
|
763
|
-
* live frame is (`createChannelForwarder`, `deliverRelayed`): a live copy that arrives while the
|
|
764
|
-
* channel write is still open finds the claim and is a repeat, rather than being shown beside
|
|
765
|
-
* it. The claim is released when the frame was not shown after all (the renderer suppressed it,
|
|
766
|
-
* the write failed), so a later copy still reaches the session, and settled once it was shown:
|
|
767
|
-
* the dedupe's record outlives the claim, so a copy that arrives before the engine records the
|
|
768
|
-
* frame in its ledger is a repeat too. A frame the live path is delivering now is that path's to
|
|
769
|
-
* show and record, so the sweep leaves the stream's copy for a later one (`queued`); a frame the
|
|
770
|
-
* dedupe recorded and let go of that the ledger does not hold (one shown before a `/clear` moved
|
|
771
|
-
* the engine, say) is handed over with no claim.
|
|
716
|
+
* Tells the session a gap notice of consumer delivery: a notice card, because it is about the
|
|
717
|
+
* messages the session was shown, which the session itself must know of.
|
|
772
718
|
*/
|
|
773
|
-
const
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
}
|
|
779
|
-
try {
|
|
780
|
-
await closeReplayedRemoval(frame, {
|
|
781
|
-
sessionID: identity.id,
|
|
782
|
-
engine: replay,
|
|
783
|
-
close: (topic) => userTopics.delete(topic),
|
|
784
|
-
unregister: unfollowRemovedTopics,
|
|
785
|
-
followedChanged: () => replay.followedChanged(),
|
|
786
|
-
})
|
|
787
|
-
const outcome = await delivery.replay(frame)
|
|
788
|
-
if (outcome === "shown") claim?.settle()
|
|
789
|
-
else claim?.release()
|
|
790
|
-
return outcome
|
|
791
|
-
} catch (error) {
|
|
792
|
-
claim?.release()
|
|
793
|
-
throw error
|
|
794
|
-
}
|
|
795
|
-
}
|
|
796
|
-
|
|
797
|
-
/**
|
|
798
|
-
* Tells the session a notice of the replay engine or of consumer delivery (a gap). That the
|
|
799
|
-
* listener does not replay goes where every start notice of this server goes, as pi-envoy raises
|
|
800
|
-
* it as a warning rather than a card for the model; every other one is a notice card.
|
|
801
|
-
*/
|
|
802
|
-
const tellNotice = (notice: ReplayNotice): void => {
|
|
803
|
-
routeReplayNotice(notice, {
|
|
804
|
-
warn: (message) => process.stderr.write(`envoy-channel: ${message}\n`),
|
|
805
|
-
card: (content) => {
|
|
806
|
-
delivery.notice(content).catch((error: unknown) => {
|
|
807
|
-
process.stderr.write(
|
|
808
|
-
`envoy-channel: ${notice.message} (the session could not be told — ${messageFor(error)})\n`,
|
|
809
|
-
)
|
|
810
|
-
})
|
|
811
|
-
},
|
|
719
|
+
const tellGapNotice = (notice: ConsumerGapNotice): void => {
|
|
720
|
+
delivery.notice(gapNoticeText(notice)).catch((error: unknown) => {
|
|
721
|
+
process.stderr.write(
|
|
722
|
+
`envoy-channel: ${notice.message} (the session could not be told — ${messageFor(error)})\n`,
|
|
723
|
+
)
|
|
812
724
|
})
|
|
813
725
|
}
|
|
814
726
|
|
|
815
|
-
/** The writer of the bound id's state file (`replayStateWriter`), set by `
|
|
727
|
+
/** The writer of the bound id's state file (`replayStateWriter`), set by `restoreDelivery`. */
|
|
816
728
|
let stateWriter: ReplayStateWriter | undefined
|
|
817
729
|
|
|
818
730
|
/**
|
|
819
|
-
*
|
|
820
|
-
*
|
|
731
|
+
* What this session was already shown, and the notice naming a frame it could not be shown
|
|
732
|
+
* (`@legion/envoy-client/delivery-ledger`), with its state in the session id's file.
|
|
821
733
|
*/
|
|
822
|
-
const
|
|
734
|
+
const ledger: DeliveryLedger = createDeliveryLedger({
|
|
823
735
|
host: {
|
|
824
|
-
sessionID: () => (shuttingDown ||
|
|
825
|
-
// What the
|
|
736
|
+
sessionID: () => (shuttingDown || ledgerBound !== identity.id ? undefined : identity.id),
|
|
737
|
+
// What the ledger persists, so a restart follows it again (`replayFollowedSubjects`).
|
|
826
738
|
followedSubjects: () => replayFollowedSubjects(directSubject, userTopics),
|
|
827
|
-
|
|
828
|
-
|
|
739
|
+
// The notice goes to the session the ledger addresses it to. This process serves one
|
|
740
|
+
// session at a time, so `delivery.notice` compares the addressed id with the one it
|
|
741
|
+
// serves when the notice's queued turn comes, which is after any `/clear` that landed
|
|
742
|
+
// while it waited: a notice naming another session is refused, which the ledger reports
|
|
743
|
+
// as a notice that could not be shown, and nothing is carded to a conversation the
|
|
744
|
+
// message was never sent to.
|
|
745
|
+
showFailureNotice: (addressed, notice) =>
|
|
746
|
+
delivery.notice(envoyNoticeText(failureNoticeFields(notice)), addressed),
|
|
829
747
|
failureNoticeFailed: (notice, error) => {
|
|
830
748
|
process.stderr.write(
|
|
831
749
|
`envoy-channel: message ${notice.eventId} from ${notice.sender} was not shown, nor was the notice naming it — ${messageFor(error)}\n`,
|
|
832
750
|
)
|
|
833
751
|
},
|
|
834
|
-
notify: tellNotice,
|
|
835
752
|
log: (message, error) => {
|
|
836
753
|
process.stderr.write(
|
|
837
754
|
`envoy-channel: ${message}${error === undefined ? "" : ` — ${messageFor(error)}`}\n`,
|
|
838
755
|
)
|
|
839
756
|
},
|
|
840
|
-
write: (change) => stateWriter?.
|
|
757
|
+
write: (change) => stateWriter?.ledger(change.snapshot()),
|
|
841
758
|
},
|
|
842
|
-
transport: options.client,
|
|
843
|
-
dedupe,
|
|
844
759
|
})
|
|
845
760
|
|
|
846
761
|
/**
|
|
847
|
-
* Loads the current id's state file: the
|
|
848
|
-
*
|
|
849
|
-
*
|
|
850
|
-
*
|
|
762
|
+
* Loads the current id's state file: the ledger's record, and the consumer delivery snapshot
|
|
763
|
+
* into a new relay for the id, whose subject it subscribes (`openRelay`). Returns the topics it
|
|
764
|
+
* followed that a restore follows again (`rememberedTopics`). A file that cannot be read starts
|
|
765
|
+
* the session's record over; its next write replaces the file.
|
|
851
766
|
*/
|
|
852
|
-
const
|
|
767
|
+
const restoreDelivery = async (): Promise<readonly string[]> => {
|
|
853
768
|
const sessionId = identity.id
|
|
854
769
|
const file = replayStateFile(options.stateDirectory, sessionId)
|
|
855
770
|
const snapshot = await readReplayState(file).catch((error: unknown): ReplayStateFile => {
|
|
856
771
|
process.stderr.write(
|
|
857
|
-
`envoy-channel: could not read the
|
|
772
|
+
`envoy-channel: could not read the delivery state (${messageFor(error)}); this session's record starts over\n`,
|
|
858
773
|
)
|
|
859
774
|
return { ledger: [] }
|
|
860
775
|
})
|
|
861
|
-
|
|
776
|
+
ledger.restore(snapshot)
|
|
862
777
|
stateWriter = replayStateWriter(file, snapshot)
|
|
863
778
|
openRelay(sessionId, stateWriter, snapshot.consumer)
|
|
864
|
-
|
|
865
|
-
return rememberedTopics(snapshot.state)
|
|
779
|
+
ledgerBound = sessionId
|
|
780
|
+
return rememberedTopics(snapshot.state?.topics)
|
|
866
781
|
}
|
|
867
782
|
|
|
868
783
|
/**
|
|
@@ -889,30 +804,15 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
|
|
|
889
804
|
router = options.router(turns)
|
|
890
805
|
}
|
|
891
806
|
|
|
892
|
-
/** A sweep runs on the engine's own chain, never in the registry's. */
|
|
893
|
-
const triggerReplay = (): void => {
|
|
894
|
-
if (!shuttingDown) void replay.sweep()
|
|
895
|
-
}
|
|
896
|
-
|
|
897
|
-
/** A human Dispatch subscription removal naming this session drops its topics here too. */
|
|
898
|
-
const takeRemovals = (raw: string): void => {
|
|
899
|
-
const removedTopics = subscriptionRemovedTopics(raw, identity.id)
|
|
900
|
-
// An empty list would mean "every topic" to both unfollow and the listener.
|
|
901
|
-
if (removedTopics !== undefined && removedTopics.length > 0) {
|
|
902
|
-
for (const topic of removedTopics) userTopics.delete(topic)
|
|
903
|
-
void dropRemovedTopics(removedTopics)
|
|
904
|
-
}
|
|
905
|
-
}
|
|
906
|
-
|
|
907
807
|
/**
|
|
908
|
-
* Consumer delivery (`@legion/envoy-client/consumer-delivery`)
|
|
909
|
-
*
|
|
910
|
-
* for consumer delivery (the relay's epoch
|
|
911
|
-
* relays the session's durable consumer on that subject: its
|
|
912
|
-
* topic the stream stores, each frame handed to the channel's
|
|
913
|
-
* answered `done` once written (`deliverRelayed`).
|
|
914
|
-
*
|
|
915
|
-
*
|
|
808
|
+
* Consumer delivery (`@legion/envoy-client/consumer-delivery`), the one path a message reaches
|
|
809
|
+
* this session by. The current id's relay subject is subscribed before any registration under
|
|
810
|
+
* that id, and every registration asks the listener for consumer delivery (the relay's epoch
|
|
811
|
+
* and resume point). The listener relays the session's durable consumer on that subject: its
|
|
812
|
+
* agent subject and every followed topic the stream stores, each frame handed to the channel's
|
|
813
|
+
* write queue in stream order and answered `done` once written (`deliverRelayed`). A
|
|
814
|
+
* registration the listener can give no consumer is refused, and the session receives nothing
|
|
815
|
+
* until a later heartbeat's registration is accepted.
|
|
916
816
|
*/
|
|
917
817
|
interface Relay {
|
|
918
818
|
readonly sessionID: string
|
|
@@ -923,8 +823,21 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
|
|
|
923
823
|
}
|
|
924
824
|
let relay: Relay | undefined
|
|
925
825
|
|
|
926
|
-
|
|
927
|
-
|
|
826
|
+
/**
|
|
827
|
+
* A `subscription.removed` the relay delivered: the topics it names leave this session, the
|
|
828
|
+
* way `envoy_unsubscribe` leaves it, and the listener's registry too, but only those the
|
|
829
|
+
* session followed before the stream stored the frame (`closeReplayedRemoval`), so a removal
|
|
830
|
+
* the stream kept while the session was away never closes a topic followed again since.
|
|
831
|
+
*/
|
|
832
|
+
const closeRemovedSubscriptions = async (frame: ConsumerFrame): Promise<void> => {
|
|
833
|
+
await closeReplayedRemoval(frame, {
|
|
834
|
+
sessionID: identity.id,
|
|
835
|
+
relay: relay?.sessionID === identity.id ? relay.delivery : undefined,
|
|
836
|
+
close: (topic) => userTopics.delete(topic),
|
|
837
|
+
unregister: unfollowRemovedTopics,
|
|
838
|
+
followedChanged: () => ledger.followedChanged(),
|
|
839
|
+
})
|
|
840
|
+
}
|
|
928
841
|
|
|
929
842
|
/**
|
|
930
843
|
* Hands one relay frame to the channel's write queue, and answers it once Claude Code has it:
|
|
@@ -942,7 +855,7 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
|
|
|
942
855
|
frame.nak()
|
|
943
856
|
return
|
|
944
857
|
}
|
|
945
|
-
|
|
858
|
+
await closeRemovedSubscriptions(frame)
|
|
946
859
|
const identityOf = deliveryIdentity(frame.data)
|
|
947
860
|
const claim = dedupe.claim(identityOf)
|
|
948
861
|
// A copy of a frame shown or being shown (another subject, a core frame of an unstored topic).
|
|
@@ -964,8 +877,8 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
|
|
|
964
877
|
frame.done()
|
|
965
878
|
return
|
|
966
879
|
}
|
|
967
|
-
// Recorded before the claim settles and before `done`,
|
|
968
|
-
if (identityOf !== undefined) await
|
|
880
|
+
// Recorded before the claim settles and before `done`, so no redelivery shows it again.
|
|
881
|
+
if (identityOf !== undefined) await ledger.recordDelivered(identityOf)
|
|
969
882
|
claim.settle()
|
|
970
883
|
frame.done()
|
|
971
884
|
owner.delivery.persist()
|
|
@@ -986,10 +899,10 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
|
|
|
986
899
|
closeRelay()
|
|
987
900
|
const consumer: ConsumerDelivery = createConsumerDelivery({
|
|
988
901
|
sessionID,
|
|
989
|
-
ledger
|
|
902
|
+
ledger,
|
|
990
903
|
host: {
|
|
991
904
|
deliver: (frame) => deliverRelayed(owner, frame),
|
|
992
|
-
gap:
|
|
905
|
+
gap: tellGapNotice,
|
|
993
906
|
log: (message, error) => {
|
|
994
907
|
process.stderr.write(
|
|
995
908
|
`envoy-channel: ${message}${error === undefined ? "" : ` — ${messageFor(error)}`}\n`,
|
|
@@ -1035,8 +948,7 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
|
|
|
1035
948
|
|
|
1036
949
|
/**
|
|
1037
950
|
* The relay's session left (a `/clear`) or shuts down: its unsettled frames are answered `nak`,
|
|
1038
|
-
*
|
|
1039
|
-
* until a registration answers otherwise.
|
|
951
|
+
* its subject is unsubscribed, and nothing is relayed until the next registration is answered.
|
|
1040
952
|
*/
|
|
1041
953
|
function closeRelay(): void {
|
|
1042
954
|
const owner = relay
|
|
@@ -1062,70 +974,30 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
|
|
|
1062
974
|
}
|
|
1063
975
|
|
|
1064
976
|
/**
|
|
1065
|
-
* What a registration's answer says of consumer delivery, for the id it registered
|
|
1066
|
-
*
|
|
1067
|
-
*
|
|
1068
|
-
* `closeRelay` is the one place a relay is dropped and `delivery.close()` left consumer mode
|
|
1069
|
-
* there. An answer for an id this process has left, or for a relay since closed, changes
|
|
1070
|
-
* nothing.
|
|
977
|
+
* What a registration's answer says of consumer delivery, for the id it registered and the
|
|
978
|
+
* relay it asked for. An answer for an id this process has left, or for a relay since closed,
|
|
979
|
+
* changes nothing.
|
|
1071
980
|
*/
|
|
1072
|
-
const takeDeliveryAnswer = (
|
|
1073
|
-
sessionID: string,
|
|
1074
|
-
topics: readonly string[],
|
|
1075
|
-
asked: Relay | undefined,
|
|
1076
|
-
result: SubscribeResult,
|
|
1077
|
-
): void => {
|
|
981
|
+
const takeDeliveryAnswer = (sessionID: string, asked: Relay, result: SubscribeResult): void => {
|
|
1078
982
|
if (sessionID !== identity.id || relay !== asked) return
|
|
1079
|
-
asked
|
|
983
|
+
asked.delivery.answered(result.delivery)
|
|
1080
984
|
}
|
|
1081
985
|
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
relayed: relaysCoreTopic,
|
|
1086
|
-
failed: (message, topic, error, receivedAt) => {
|
|
1087
|
-
// A frame no sweep will show again gets its notice at once: a role forward, already
|
|
1088
|
-
// acknowledged, one on a subscription the replay does not read (refused, not started, or
|
|
1089
|
-
// the listener's replay failing), or one received before its subject's cursor started.
|
|
1090
|
-
// The stream's copy of any other waits for a sweep. The notice is asked for this
|
|
1091
|
-
// process's one session by name, read when the failure lands.
|
|
1092
|
-
const envelope = renderInbound(message.raw, identity.id, message.subject).envelope
|
|
1093
|
-
if (envelope !== undefined)
|
|
1094
|
-
void replay.liveFailed(identity.id, topic, envelope, error, receivedAt)
|
|
1095
|
-
},
|
|
1096
|
-
deliver: async (message) => {
|
|
1097
|
-
takeRemovals(message.raw)
|
|
1098
|
-
return enqueueChannelMessage(delivery, options.connection, directSubject, message)
|
|
1099
|
-
},
|
|
1100
|
-
})
|
|
986
|
+
// Nothing is subscribed per topic: this holds the followed set a registration carries, and
|
|
987
|
+
// the one NATS subscription this process makes is the relay's (`openRelay`).
|
|
988
|
+
const followedTopics: ChannelTopics = createChannelTopics(options.connection)
|
|
1101
989
|
|
|
1102
990
|
/**
|
|
1103
|
-
*
|
|
1104
|
-
*
|
|
1105
|
-
*/
|
|
1106
|
-
function dropRemovedTopics(topics: readonly string[]): Promise<void> {
|
|
1107
|
-
unfollowRemovedTopics(topics)
|
|
1108
|
-
return replay.followedChanged()
|
|
1109
|
-
}
|
|
1110
|
-
|
|
1111
|
-
/**
|
|
1112
|
-
* Starts dropping removed topics from the forwarder and the registry entry, each failure
|
|
1113
|
-
* reported here: the drop half of `dropRemovedTopics`, and what a replayed removal takes out of
|
|
1114
|
-
* the registry (`closeReplayedRemoval`).
|
|
991
|
+
* Drops removed topics from the followed set and the registry entry, its failure reported
|
|
992
|
+
* here: what a removal frame takes out of the registry (`closeReplayedRemoval`).
|
|
1115
993
|
*/
|
|
1116
994
|
function unfollowRemovedTopics(topics: readonly string[]): void {
|
|
1117
|
-
const { dropping, unsubscribing } = dropFromForwarderAndRegistry(topics)
|
|
1118
|
-
dropping.catch((error: unknown) => {
|
|
1119
|
-
process.stderr.write(
|
|
1120
|
-
`envoy-channel: could not drop a removed subscription — ${messageFor(error)}\n`,
|
|
1121
|
-
)
|
|
1122
|
-
})
|
|
1123
995
|
// Dispatch has already removed them from the entry, but a registration in
|
|
1124
996
|
// flight at that moment adds them back; removing them again behind it undoes
|
|
1125
997
|
// that. A failure here is not retried by name: the heartbeat's own interest
|
|
1126
998
|
// reconciliation (below) brings the entry back in line with what this session
|
|
1127
999
|
// actually follows, whatever caused the drift.
|
|
1128
|
-
|
|
1000
|
+
dropFromTopicsAndRegistry(topics).catch((error: unknown) => {
|
|
1129
1001
|
process.stderr.write(
|
|
1130
1002
|
`envoy-channel: could not drop a removed subscription from the registry — ${messageFor(error)}; the next heartbeat reconciles it\n`,
|
|
1131
1003
|
)
|
|
@@ -1133,45 +1005,55 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
|
|
|
1133
1005
|
}
|
|
1134
1006
|
|
|
1135
1007
|
/**
|
|
1136
|
-
* Drops `topics` from the
|
|
1137
|
-
*
|
|
1138
|
-
*
|
|
1139
|
-
*
|
|
1140
|
-
*
|
|
1141
|
-
*
|
|
1142
|
-
* `unfollow` below — take these same two steps in this order; only whether they
|
|
1143
|
-
* wait for them differs.
|
|
1008
|
+
* Drops `topics` from the followed set and the registry entry — the two steps every removal
|
|
1009
|
+
* here takes once a caller has already taken them out of `userTopics`. The followed set is cut
|
|
1010
|
+
* first, synchronously, so no registration queued behind the registry write advertises a
|
|
1011
|
+
* dropped topic again, and the relay stops taking them at once. Both callers here —
|
|
1012
|
+
* `unfollowRemovedTopics`, a removal's best-effort drop, and the public `unfollow` below —
|
|
1013
|
+
* take these same two steps in this order; only whether they wait for them differs.
|
|
1144
1014
|
*/
|
|
1145
|
-
function
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
unsubscribing: serialized(() =>
|
|
1158
|
-
options.client.unsubscribe({
|
|
1159
|
-
sessionID: identity.id,
|
|
1160
|
-
topics,
|
|
1161
|
-
clientInstanceID: options.clientInstanceID,
|
|
1162
|
-
}),
|
|
1163
|
-
),
|
|
1015
|
+
function dropFromTopicsAndRegistry(topics: readonly string[]): Promise<void> {
|
|
1016
|
+
followedTopics.unfollow(topics)
|
|
1017
|
+
// The relay takes the topics the session follows now, before a registration carries them:
|
|
1018
|
+
// the same set the registration will carry (`registrationTopics`).
|
|
1019
|
+
if (relay?.sessionID === identity.id) {
|
|
1020
|
+
relay.delivery.setFollowed(
|
|
1021
|
+
registrationTopics(
|
|
1022
|
+
directSubject,
|
|
1023
|
+
followedTopics.topics(),
|
|
1024
|
+
heldRole === undefined ? [] : [heldRole],
|
|
1025
|
+
),
|
|
1026
|
+
)
|
|
1164
1027
|
}
|
|
1028
|
+
// The release names this process, so the listener frees the role claim of this process
|
|
1029
|
+
// alone where one of these topics is a role's: a second process that resumed this session
|
|
1030
|
+
// id keeps the role it holds.
|
|
1031
|
+
return serialized(() =>
|
|
1032
|
+
options.client.unsubscribe({
|
|
1033
|
+
sessionID: identity.id,
|
|
1034
|
+
topics,
|
|
1035
|
+
clientInstanceID: options.clientInstanceID,
|
|
1036
|
+
}),
|
|
1037
|
+
)
|
|
1165
1038
|
}
|
|
1166
1039
|
|
|
1167
1040
|
/**
|
|
1168
|
-
*
|
|
1169
|
-
*
|
|
1170
|
-
*
|
|
1041
|
+
* Said once per outage: the listener refused this session's registration, so it has no consumer
|
|
1042
|
+
* and receives nothing. The session still runs, and the heartbeat registers again every tick
|
|
1043
|
+
* until one is accepted; the reason is the listener's own, one of those
|
|
1044
|
+
* `ErrorWireSchema.reason` lists (`@legion/envoy-client`'s `transport.ts`), which the error
|
|
1045
|
+
* carries in its message and which `inboundUnavailableNoticeText` words for every host.
|
|
1171
1046
|
*/
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1047
|
+
const inboundOutage = inboundUnavailable((why) => {
|
|
1048
|
+
process.stderr.write(
|
|
1049
|
+
`envoy-channel: this session receives nothing (${why}); registering again every heartbeat\n`,
|
|
1050
|
+
)
|
|
1051
|
+
delivery.notice(inboundUnavailableNoticeText(why)).catch((noticeError: unknown) => {
|
|
1052
|
+
process.stderr.write(
|
|
1053
|
+
`envoy-channel: the session could not be told that it receives nothing — ${messageFor(noticeError)}\n`,
|
|
1054
|
+
)
|
|
1055
|
+
})
|
|
1056
|
+
})
|
|
1175
1057
|
|
|
1176
1058
|
/** The title last stamped, so a heartbeat stamps nothing new. */
|
|
1177
1059
|
let stampedTitle: { readonly sessionID: string; readonly title: string } | undefined
|
|
@@ -1180,10 +1062,11 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
|
|
|
1180
1062
|
|
|
1181
1063
|
/**
|
|
1182
1064
|
* Advertise the current id and topics; runs only inside `serialized`. The title is also stamped
|
|
1183
|
-
* for the `dispatch` command (`options.stampTitle`) whenever it or the id changes.
|
|
1184
|
-
*
|
|
1185
|
-
*
|
|
1186
|
-
*
|
|
1065
|
+
* for the `dispatch` command (`options.stampTitle`) whenever it or the id changes. The rest is
|
|
1066
|
+
* the sequence every host shares, `registerWithRelay`: the topics the listener will store for
|
|
1067
|
+
* this session (`registrationTopics`), taken by the relay as followed first, the relay's
|
|
1068
|
+
* delivery request, the outage told once, and the answer's consumer taken
|
|
1069
|
+
* (`takeDeliveryAnswer`).
|
|
1187
1070
|
*/
|
|
1188
1071
|
const register = async (): Promise<void> => {
|
|
1189
1072
|
const title = options.title?.(identity.id) ?? ""
|
|
@@ -1207,34 +1090,46 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
|
|
|
1207
1090
|
}
|
|
1208
1091
|
}
|
|
1209
1092
|
const sessionID = identity.id
|
|
1210
|
-
const
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1093
|
+
const asking = relay?.sessionID === sessionID ? relay : undefined
|
|
1094
|
+
await registerWithRelay({
|
|
1095
|
+
relay: asking?.delivery,
|
|
1096
|
+
ownAgentSubject: directSubject,
|
|
1097
|
+
followed: followedTopics.topics(),
|
|
1098
|
+
roles: heldRole === undefined ? [] : [heldRole],
|
|
1099
|
+
outage: inboundOutage,
|
|
1100
|
+
send: (topics, deliveryRequest) => {
|
|
1101
|
+
const registering = options.client.subscribe({
|
|
1102
|
+
sessionID,
|
|
1103
|
+
directory: identity.directory,
|
|
1104
|
+
topics,
|
|
1105
|
+
port: 0,
|
|
1106
|
+
title,
|
|
1107
|
+
capabilities: options.capabilities(),
|
|
1108
|
+
driving: false,
|
|
1109
|
+
selfSubscribed: true,
|
|
1110
|
+
clientInstanceID: options.clientInstanceID,
|
|
1111
|
+
plugin: { name: packageName, version: options.pluginVersion },
|
|
1112
|
+
delivery: deliveryRequest,
|
|
1113
|
+
})
|
|
1114
|
+
// Held as a promise that settles either way, so a deregistration waits for the call to
|
|
1115
|
+
// leave the wire without taking on its rejection.
|
|
1116
|
+
const settled = registering.then(
|
|
1117
|
+
() => undefined,
|
|
1118
|
+
() => undefined,
|
|
1119
|
+
)
|
|
1120
|
+
registrationInFlight = settled
|
|
1121
|
+
void settled.then(() => {
|
|
1122
|
+
if (registrationInFlight === settled) registrationInFlight = undefined
|
|
1123
|
+
})
|
|
1124
|
+
return registering
|
|
1125
|
+
},
|
|
1126
|
+
// A registration the listener refused, for any of the reasons `ErrorWireSchema.reason`
|
|
1127
|
+
// lists, leaves the session with no consumer at all, as every other failed registration
|
|
1128
|
+
// does: the session is told once and the heartbeat asks again.
|
|
1129
|
+
answered: (result) => {
|
|
1130
|
+
if (asking !== undefined) takeDeliveryAnswer(sessionID, asking, result)
|
|
1131
|
+
},
|
|
1235
1132
|
})
|
|
1236
|
-
const result = await registering
|
|
1237
|
-
takeDeliveryAnswer(sessionID, topics, asking, result)
|
|
1238
1133
|
}
|
|
1239
1134
|
|
|
1240
1135
|
/**
|
|
@@ -1464,7 +1359,7 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
|
|
|
1464
1359
|
const previous = identity.id
|
|
1465
1360
|
const previousSubject = directSubject
|
|
1466
1361
|
const nextSubject = agentSubject(next)
|
|
1467
|
-
|
|
1362
|
+
followedTopics.follow(nextSubject)
|
|
1468
1363
|
try {
|
|
1469
1364
|
// Bounded: this runs inside the registry chain, and a flush on a stalled NATS
|
|
1470
1365
|
// connection never settles, which would hold every later write and shutdown.
|
|
@@ -1481,7 +1376,7 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
|
|
|
1481
1376
|
// The session stays on the old id until a later tick retries, so the new
|
|
1482
1377
|
// subject leaves the topic list; otherwise the next registration would
|
|
1483
1378
|
// advertise it under the old id.
|
|
1484
|
-
|
|
1379
|
+
followedTopics.unfollow([nextSubject])
|
|
1485
1380
|
throw error
|
|
1486
1381
|
}
|
|
1487
1382
|
identity.set(next)
|
|
@@ -1491,16 +1386,14 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
|
|
|
1491
1386
|
// process, which `/clear` would otherwise add one of per session.
|
|
1492
1387
|
forgetBrokerSession(previous)
|
|
1493
1388
|
directSubject = nextSubject
|
|
1494
|
-
// `unfollow`
|
|
1495
|
-
//
|
|
1496
|
-
|
|
1497
|
-
//
|
|
1498
|
-
|
|
1499
|
-
//
|
|
1500
|
-
//
|
|
1501
|
-
|
|
1502
|
-
// id's relay (its unanswered frames `nak`) and subscribes the new id's relay subject.
|
|
1503
|
-
await restoreReplay()
|
|
1389
|
+
// `unfollow` only takes the subject out of the topic list a registration carries: nothing is
|
|
1390
|
+
// subscribed per topic, so there is nothing to drain and nothing to wait for.
|
|
1391
|
+
followedTopics.unfollow([previousSubject])
|
|
1392
|
+
// The new id's delivery state: none after a `/clear`, which starts afresh as a new session
|
|
1393
|
+
// does, so nothing published before it existed comes back. Until it is loaded, the ledger
|
|
1394
|
+
// records nothing. Loading it closes the old id's relay (its unanswered frames `nak`) and
|
|
1395
|
+
// subscribes the new id's relay subject.
|
|
1396
|
+
await restoreDelivery()
|
|
1504
1397
|
// The new id takes a record of its own: an attempt the old id handled is the old id's, and
|
|
1505
1398
|
// the rows of a conversation a `/clear` ended name nothing in the new one.
|
|
1506
1399
|
await restoreTurns()
|
|
@@ -1526,17 +1419,17 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
|
|
|
1526
1419
|
let interestsRead = false
|
|
1527
1420
|
|
|
1528
1421
|
/**
|
|
1529
|
-
* Brings the registry entry and
|
|
1422
|
+
* Brings the registry entry and the topic set this session registers into line
|
|
1530
1423
|
* with each other. The first successful read adopts every topic the entry lists;
|
|
1531
1424
|
* every later read subtracts every topic the entry lists that
|
|
1532
|
-
* `
|
|
1425
|
+
* `followedTopics.topics()` no longer names.
|
|
1533
1426
|
*
|
|
1534
|
-
* Subtracting is safe only while `
|
|
1535
|
-
* session, so both windows where it is not are checked after the read,
|
|
1536
|
-
* because both open while the read is in flight. `interestsRead` is
|
|
1537
|
-
* a read has succeeded, when the
|
|
1538
|
-
* the entry legitimately holds more. `shuttingDown` is set as teardown
|
|
1539
|
-
* and `
|
|
1427
|
+
* Subtracting is safe only while `followedTopics.topics()` is authoritative for
|
|
1428
|
+
* this session, so both windows where it is not are checked after the read,
|
|
1429
|
+
* together, because both open while the read is in flight. `interestsRead` is
|
|
1430
|
+
* false until a read has succeeded, when the set holds only the direct subject
|
|
1431
|
+
* while the entry legitimately holds more. `shuttingDown` is set as teardown
|
|
1432
|
+
* begins, and `close()` empties the topic list in that same synchronous step,
|
|
1540
1433
|
* so a shutdown landing mid-read would leave an emptied list looking like total
|
|
1541
1434
|
* drift. Neither is read before the await: the early return at the top only
|
|
1542
1435
|
* saves a round trip, and guards nothing.
|
|
@@ -1550,7 +1443,7 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
|
|
|
1550
1443
|
* slipping through loses one topic.
|
|
1551
1444
|
*
|
|
1552
1445
|
* A 404 completes the read: it is the genuinely-new-session case, and the
|
|
1553
|
-
*
|
|
1446
|
+
* topic set is already complete. Any other failure leaves `interestsRead` false
|
|
1554
1447
|
* and the next heartbeat adopts again, so a permanent outage means the entry is
|
|
1555
1448
|
* never reconciled. That is the correct direction, because nothing undoes a
|
|
1556
1449
|
* wrong subtraction: `unregisterSession` deletes only the sessions row, so a
|
|
@@ -1578,13 +1471,13 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
|
|
|
1578
1471
|
for (const topic of registry?.topics ?? []) {
|
|
1579
1472
|
if (topic === directSubject || topic.startsWith(ROLE_TOPIC_PREFIX)) continue
|
|
1580
1473
|
userTopics.add(topic)
|
|
1581
|
-
|
|
1474
|
+
followedTopics.follow(topic)
|
|
1582
1475
|
}
|
|
1583
1476
|
interestsRead = true
|
|
1584
1477
|
return
|
|
1585
1478
|
}
|
|
1586
1479
|
if (registry === undefined) return
|
|
1587
|
-
const followed = new Set(
|
|
1480
|
+
const followed = new Set(followedTopics.topics())
|
|
1588
1481
|
const drifted = registry.topics.filter(
|
|
1589
1482
|
(topic) =>
|
|
1590
1483
|
topic !== directSubject && !topic.startsWith(ROLE_TOPIC_PREFIX) && !followed.has(topic),
|
|
@@ -1666,9 +1559,6 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
|
|
|
1666
1559
|
)
|
|
1667
1560
|
} finally {
|
|
1668
1561
|
heartbeatInFlight = false
|
|
1669
|
-
// Every tick also sweeps the stream, so a missed trigger is caught up, and a listener that
|
|
1670
|
-
// does not replay yet keeps being asked.
|
|
1671
|
-
triggerReplay()
|
|
1672
1562
|
if (heartbeatRequested) {
|
|
1673
1563
|
heartbeatRequested = false
|
|
1674
1564
|
void heartbeat()
|
|
@@ -1697,20 +1587,20 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
|
|
|
1697
1587
|
else void heartbeat()
|
|
1698
1588
|
}
|
|
1699
1589
|
|
|
1700
|
-
// The session's
|
|
1590
|
+
// The session's delivery record comes first, so a redelivery of a frame it was shown before is
|
|
1701
1591
|
// dropped against it. The topics it followed come back with it: a session the listener reaped
|
|
1702
|
-
// (ten minutes after it stopped) still follows them, and its
|
|
1703
|
-
// comes with it too, restored and subscribed before the first registration asks for it.
|
|
1704
|
-
const remembered = await
|
|
1592
|
+
// (ten minutes after it stopped) still follows them, and its consumer still holds them. Its
|
|
1593
|
+
// relay comes with it too, restored and subscribed before the first registration asks for it.
|
|
1594
|
+
const remembered = await restoreDelivery()
|
|
1705
1595
|
// What this session has already done with the messages Dispatch sent it, before any frame can
|
|
1706
1596
|
// arrive: an attempt a process before this one spent must not be spent again.
|
|
1707
1597
|
await restoreTurns()
|
|
1708
1598
|
// The NATS subscription precedes registration so the listener never routes
|
|
1709
1599
|
// a direct delivery to an advertised but deaf channel process.
|
|
1710
|
-
|
|
1600
|
+
followedTopics.follow(directSubject)
|
|
1711
1601
|
for (const topic of remembered) {
|
|
1712
1602
|
userTopics.add(topic)
|
|
1713
|
-
|
|
1603
|
+
followedTopics.follow(topic)
|
|
1714
1604
|
}
|
|
1715
1605
|
// Best-effort: a listener outage must not fail startup. It leaves
|
|
1716
1606
|
// `interestsRead` false, so the heartbeat retries the adopt and never
|
|
@@ -1722,7 +1612,17 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
|
|
|
1722
1612
|
})
|
|
1723
1613
|
await options.connection.flush()
|
|
1724
1614
|
await serialized(async () => {
|
|
1725
|
-
|
|
1615
|
+
// Best-effort, as the interests read above is: a listener that refuses this registration
|
|
1616
|
+
// because it can give the session no consumer (`inboundOutage` tells the session
|
|
1617
|
+
// once, naming the listener's reason), or one that is down, must not take the whole channel
|
|
1618
|
+
// with it — the tools, the role and the `dispatch` command work without it. Every heartbeat
|
|
1619
|
+
// asks again, and `registrationFailed` makes the first accepted one a regain of the role.
|
|
1620
|
+
await register().catch((error: unknown) => {
|
|
1621
|
+
registrationFailed = true
|
|
1622
|
+
process.stderr.write(
|
|
1623
|
+
`envoy-channel: the first registration failed (${messageFor(error)}); the next heartbeat retries\n`,
|
|
1624
|
+
)
|
|
1625
|
+
})
|
|
1726
1626
|
// Best-effort, as the interests read above is, and for a sharper reason: registration has
|
|
1727
1627
|
// already happened, so a throw here takes down a channel the registry is advertising and
|
|
1728
1628
|
// leaves the Agents page a row that never beats again.
|
|
@@ -1758,9 +1658,6 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
|
|
|
1758
1658
|
}
|
|
1759
1659
|
}
|
|
1760
1660
|
})
|
|
1761
|
-
// The first sweep, once the listener knows what the session follows: what was stored while it
|
|
1762
|
-
// was away (a resume included), or, for a new session, its cursors' start at the stream's end.
|
|
1763
|
-
triggerReplay()
|
|
1764
1661
|
// Housekeeping of the plugin's own state directories, each best-effort for the reason the
|
|
1765
1662
|
// interests read above is: the heartbeat timer below is not armed yet, so a sweep that threw
|
|
1766
1663
|
// here would take the session's whole channel down over a dead pid's handoff, a cosmetic title
|
|
@@ -1801,14 +1698,13 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
|
|
|
1801
1698
|
requestHeartbeat()
|
|
1802
1699
|
}
|
|
1803
1700
|
// nats.js resubscribes by itself after a reconnect; what was published while it was away is in
|
|
1804
|
-
// the stream
|
|
1805
|
-
//
|
|
1701
|
+
// the stream, and the relay restarts at its ack floor on the new epoch's registration. The
|
|
1702
|
+
// status events end when the connection closes.
|
|
1806
1703
|
void (async () => {
|
|
1807
1704
|
try {
|
|
1808
1705
|
for await (const status of options.connection.status()) {
|
|
1809
1706
|
if (status.type !== "reconnect") continue
|
|
1810
1707
|
renewRelayEpoch()
|
|
1811
|
-
triggerReplay()
|
|
1812
1708
|
}
|
|
1813
1709
|
} catch (error) {
|
|
1814
1710
|
process.stderr.write(
|
|
@@ -1819,22 +1715,30 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
|
|
|
1819
1715
|
|
|
1820
1716
|
return {
|
|
1821
1717
|
delivery,
|
|
1822
|
-
topics: () =>
|
|
1718
|
+
topics: () => followedTopics.topics(),
|
|
1823
1719
|
async follow(topics) {
|
|
1720
|
+
// A topic no stream subject captures is followed but never registered, since the listener
|
|
1721
|
+
// stores none: it drops such a topic from the row and names it in a warning
|
|
1722
|
+
// (`registrationTopics`). This call is a caller naming the topic by hand — the tool, and
|
|
1723
|
+
// nothing else: a stored row and a restored state reach `followedTopics.follow` instead —
|
|
1724
|
+
// so it is refused by name, in the listener's own words, rather than leaving the session
|
|
1725
|
+
// following a subject nothing is ever delivered on. A private stream subject is left out
|
|
1726
|
+
// of the registration without a word, as it always was (`refuseUncapturedTopics`).
|
|
1727
|
+
refuseUncapturedTopics(identity.id, directSubject, topics)
|
|
1824
1728
|
if (shuttingDown) return []
|
|
1825
1729
|
const fresh: string[] = []
|
|
1826
1730
|
for (const topic of expandSubscriptionTopics(topics)) {
|
|
1827
1731
|
if (topic === directSubject || userTopics.has(topic)) continue
|
|
1828
1732
|
userTopics.add(topic)
|
|
1829
|
-
|
|
1733
|
+
followedTopics.follow(topic)
|
|
1830
1734
|
fresh.push(topic)
|
|
1831
1735
|
}
|
|
1832
1736
|
await options.connection.flush()
|
|
1833
1737
|
await serialized(register)
|
|
1834
1738
|
if (fresh.length > 0) {
|
|
1835
|
-
//
|
|
1836
|
-
|
|
1837
|
-
|
|
1739
|
+
// Recorded at once, so a restart follows the topic again; the relay takes frames stored
|
|
1740
|
+
// from this follow on, never the stream's older ones (`setFollowed`).
|
|
1741
|
+
await ledger.followedChanged()
|
|
1838
1742
|
}
|
|
1839
1743
|
return fresh
|
|
1840
1744
|
},
|
|
@@ -1842,11 +1746,10 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
|
|
|
1842
1746
|
const requested = topics.length === 0 ? [...userTopics] : expandSubscriptionTopics(topics)
|
|
1843
1747
|
const removed = requested.filter((topic) => userTopics.delete(topic))
|
|
1844
1748
|
if (removed.length === 0) return []
|
|
1845
|
-
const
|
|
1846
|
-
// Recorded at once, so a restart does not follow the topics again from the
|
|
1847
|
-
await
|
|
1749
|
+
const unsubscribing = dropFromTopicsAndRegistry(removed)
|
|
1750
|
+
// Recorded at once, so a restart does not follow the topics again from the delivery state.
|
|
1751
|
+
await ledger.followedChanged()
|
|
1848
1752
|
await unsubscribing
|
|
1849
|
-
await dropping
|
|
1850
1753
|
return removed
|
|
1851
1754
|
},
|
|
1852
1755
|
onRoleRegained(hook) {
|
|
@@ -1881,7 +1784,7 @@ export async function startChannelSession(options: ChannelSessionOptions): Promi
|
|
|
1881
1784
|
if (handoffFile !== undefined) unwatchFile(handoffFile, handoffFileChanged)
|
|
1882
1785
|
// The relay's unanswered frames `nak`, so the listener sends them to whoever resumes.
|
|
1883
1786
|
closeRelay()
|
|
1884
|
-
await
|
|
1787
|
+
await followedTopics.close()
|
|
1885
1788
|
// The heartbeat is stopped and `follow` refuses while shutting down, so no registration
|
|
1886
1789
|
// starts from here. What the chain still holds is waited out — a registration it runs after
|
|
1887
1790
|
// the DELETE would write the record back — and so is one already on the wire, both bounded,
|
|
@@ -1952,17 +1855,15 @@ export async function executeEnvoyTool(
|
|
|
1952
1855
|
message: args.message,
|
|
1953
1856
|
...toMessageMetadata(args),
|
|
1954
1857
|
})
|
|
1955
|
-
// The answer the model reads, its line first. A topic
|
|
1956
|
-
//
|
|
1957
|
-
//
|
|
1958
|
-
// words the Oh My Pi plugin uses (`publishConfirmationText`).
|
|
1858
|
+
// The answer the model reads, its line first. A publish to a topic the stream captures is
|
|
1859
|
+
// answered with the envelope alone; a kept answer is a success of its own, which the line
|
|
1860
|
+
// says in the words the Oh My Pi plugin uses (`publishConfirmationText`).
|
|
1959
1861
|
return {
|
|
1960
1862
|
message: publishConfirmationText(result),
|
|
1961
1863
|
event_id: result.envelope.event_id,
|
|
1962
1864
|
topic: result.envelope.topic,
|
|
1963
1865
|
...(result.holder === undefined ? {} : { holder: result.holder }),
|
|
1964
1866
|
...(result.holderState === undefined ? {} : { holder_state: result.holderState }),
|
|
1965
|
-
unresponsive: result.unresponsive,
|
|
1966
1867
|
...(result.kept === undefined ? {} : { kept: result.kept }),
|
|
1967
1868
|
...(result.keptReason === undefined ? {} : { kept_reason: result.keptReason }),
|
|
1968
1869
|
}
|
|
@@ -2376,7 +2277,7 @@ export async function runEnvoyChannelServer(): Promise<void> {
|
|
|
2376
2277
|
return createUserTurnRouter(options)
|
|
2377
2278
|
}
|
|
2378
2279
|
|
|
2379
|
-
let connection:
|
|
2280
|
+
let connection: ChannelConnection | undefined
|
|
2380
2281
|
try {
|
|
2381
2282
|
const { inbound } = envoy
|
|
2382
2283
|
if ("off" in inbound) {
|