@sjawhar/claude-envoy 2.7.1 → 2.9.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.
@@ -1,26 +1,26 @@
1
- // One session's delivery record, in one file per session id under `CLAUDE_PLUGIN_DATA`: the
2
- // replay engine's (`@legion/envoy-client/replay`: its cursors, the subjects it follows and the
3
- // frames it was shown in the last 72 hours), and consumer delivery's
4
- // (`@legion/envoy-client/consumer-delivery`: the resume point and when each topic was first
5
- // followed). Claude Code can resume a session at any later time, so no sweep prunes these files;
6
- // each holds only cursors, followed subjects, a resume point and at most 72 hours of ledger,
7
- // since the engine drops older ledger entries before every write.
1
+ // One session's delivery record, in one file per session id under `CLAUDE_PLUGIN_DATA` (named
2
+ // `replay-<id>.json` since the first release that wrote one): the delivery ledger's
3
+ // (`@legion/envoy-client/delivery-ledger`: the topics it follows and the frames it was shown in
4
+ // the last 72 hours), and consumer delivery's (`@legion/envoy-client/consumer-delivery`: the
5
+ // resume point and when each topic was first followed). Claude Code can resume a session at any
6
+ // later time, so no sweep prunes these files; each holds only followed subjects, a resume point
7
+ // and at most 72 hours of ledger, since the ledger drops older entries before every write.
8
8
  import { join } from "node:path"
9
9
  import {
10
10
  type ConsumerDeliverySnapshot,
11
11
  ConsumerDeliverySnapshotSchema,
12
12
  } from "@legion/envoy-client/consumer-delivery"
13
- import { type ReplaySnapshot, ReplaySnapshotSchema } from "@legion/envoy-client/replay"
13
+ import { type LedgerSnapshot, LedgerSnapshotSchema } from "@legion/envoy-client/delivery-ledger"
14
14
  import type { z } from "zod"
15
15
  import { writeAtomicStateFile } from "./session-state"
16
16
  import { readStateFile } from "./state-file"
17
17
 
18
18
  /**
19
- * A session's file: the replay snapshot, and the consumer delivery snapshot once the session had
20
- * one. `consumer` is optional, so a file a release before consumer delivery wrote still reads, and
21
- * such a release reading a newer file passes over it.
19
+ * A session's file: the delivery ledger's snapshot, and the consumer delivery snapshot once the
20
+ * session had one. `consumer` is optional, so a file a release before consumer delivery wrote
21
+ * still reads, and such a release reading a newer file passes over it.
22
22
  */
23
- export const ReplayStateFileSchema = ReplaySnapshotSchema.extend({
23
+ export const ReplayStateFileSchema = LedgerSnapshotSchema.extend({
24
24
  consumer: ConsumerDeliverySnapshotSchema.optional(),
25
25
  })
26
26
 
@@ -35,10 +35,10 @@ export function replayStateFile(stateDirectory: string, sessionId: string): stri
35
35
  /**
36
36
  * The record a session's file holds; an empty one when there is no file, which is a session that
37
37
  * never ran this plugin, or a new id (a `/clear`, a fresh start). A file that cannot be read or
38
- * holds no replay snapshot throws.
38
+ * holds no ledger snapshot throws.
39
39
  */
40
40
  export async function readReplayState(file: string): Promise<ReplayStateFile> {
41
- return await readStateFile(file, ReplayStateFileSchema, { ledger: [] }, "holds no replay state")
41
+ return await readStateFile(file, ReplayStateFileSchema, { ledger: [] }, "holds no delivery state")
42
42
  }
43
43
 
44
44
  /** Replaces the session's file by rename, mode 0600, as every other state file is written. */
@@ -48,8 +48,8 @@ export async function writeReplayState(file: string, state: ReplayStateFile): Pr
48
48
 
49
49
  /** Writes one session's file from its two parts, each written whenever its owner changes it. */
50
50
  export interface ReplayStateWriter {
51
- /** The replay engine's snapshot changed; resolves once a file holding it is in place. */
52
- replay(snapshot: ReplaySnapshot): Promise<void>
51
+ /** The delivery ledger's snapshot changed; resolves once a file holding it is in place. */
52
+ ledger(snapshot: LedgerSnapshot): Promise<void>
53
53
  /** The consumer delivery snapshot changed; resolves once a file holding it is in place. */
54
54
  consumer(snapshot: ConsumerDeliverySnapshot): Promise<void>
55
55
  /** Resolves once every write asked for so far has finished, failed ones included. */
@@ -71,7 +71,7 @@ export function replayStateWriter(file: string, restored: ReplayStateFile): Repl
71
71
  return run
72
72
  }
73
73
  return {
74
- replay: (snapshot) =>
74
+ ledger: (snapshot) =>
75
75
  write(
76
76
  current.consumer === undefined ? snapshot : { ...snapshot, consumer: current.consumer },
77
77
  ),
@@ -1,262 +0,0 @@
1
- import type { RelayHeaders } from "@legion/envoy-client/consumer-delivery"
2
- import {
3
- createDeliveryDedupe,
4
- type DedupeIdentity,
5
- DedupeIdentitySchema,
6
- type DeliveryDedupe,
7
- readArrivals,
8
- } from "@legion/envoy-client/delivery"
9
- import { messageFor } from "@legion/envoy-client/errors"
10
- import { expandSubscriptionTopics } from "@legion/envoy-client/transport"
11
- import { z } from "zod"
12
-
13
- /** A message as the broker yields it (a nats.js `Msg` satisfies this). */
14
- export interface ChannelBrokerMessage {
15
- readonly subject: string
16
- readonly data: Uint8Array
17
- readonly reply?: string
18
- /** The message's NATS headers; only a relay frame (consumer delivery) carries any read here. */
19
- readonly headers?: RelayHeaders
20
- }
21
-
22
- /** A broker message as the forwarder delivers it: decoded once and classified. */
23
- export interface ChannelInboundMessage extends ChannelBrokerMessage {
24
- /** `data` decoded as UTF-8 once, at the broker boundary. */
25
- readonly raw: string
26
- /**
27
- * The event already reached the channel queue, or its relayed copy is the one shown
28
- * (`ChannelForwarderOptions.relayed`); direct request-reply still needs its receipt.
29
- */
30
- readonly duplicate?: true
31
- /**
32
- * The topic the envelope itself names. It differs from `subject` when the listener forwarded
33
- * a lane (a role topic) onto the direct subject and is waiting for a receipt.
34
- */
35
- readonly envelopeTopic?: string
36
- }
37
-
38
- export interface ChannelTopicSubscription extends AsyncIterable<ChannelBrokerMessage> {
39
- unsubscribe(): void
40
- }
41
-
42
- /** A nats.js connection status event; only its `type` is read. */
43
- export interface ChannelConnectionStatus {
44
- readonly type: string
45
- }
46
-
47
- /** The NATS connection surface used by a channel session. */
48
- export interface ChannelForwarderConnection {
49
- subscribe(subject: string): ChannelTopicSubscription
50
- publish(subject: string, data: Uint8Array): void
51
- flush(): Promise<void>
52
- isClosed(): boolean
53
- drain(): Promise<void>
54
- close(): Promise<void>
55
- /** The connection's status events (nats.js `status()`), which end when it closes. */
56
- status(): AsyncIterable<ChannelConnectionStatus>
57
- }
58
-
59
- export interface ChannelForwarder {
60
- /** Start delivering a topic; a topic already followed is left alone. */
61
- follow(topic: string): void
62
- /** Stop delivering the given topics, or every topic when the list is empty. */
63
- unfollow(topics: readonly string[]): Promise<void>
64
- /** Topics currently delivered, in follow order. */
65
- topics(): readonly string[]
66
- /** True once the connection is closed for good. */
67
- isClosed(): boolean
68
- /** Stop every subscription and drain the NATS connection; never rejects. */
69
- close(): Promise<void>
70
- }
71
-
72
- /** The replay ledger as the live path sees it (`@legion/envoy-client/replay`). */
73
- export interface ChannelForwarderLedger {
74
- /** Whether the session was shown the frame already, before this process started included. */
75
- delivered(frame: DedupeIdentity): boolean
76
- /** Records a frame Claude Code was handed, so no replay shows it again; never rejects. */
77
- recordDelivered(frame: DedupeIdentity): Promise<void>
78
- }
79
-
80
- export interface ChannelForwarderOptions {
81
- /**
82
- * Hands one frame on and resolves whether Claude Code got it; `false`, or a rejection, releases
83
- * the frame's dedupe claim, so a re-send of it still arrives.
84
- */
85
- readonly deliver: (message: ChannelInboundMessage) => Promise<boolean>
86
- /** How long close waits for a broker drain before closing outright. */
87
- readonly drainTimeoutMs?: number
88
- /** The claims of the live path; a replay engine reads them to leave a frame in flight alone. */
89
- readonly dedupe?: DeliveryDedupe
90
- readonly ledger?: ChannelForwarderLedger
91
- /**
92
- * A frame whose delivery rejected, after its claim was released: `topic` is the subscription it
93
- * came on, which says whether a replay will show it again, and `receivedAt` when the
94
- * subscription yielded it (`Date.now`, `readArrivals`), however long the frames before it took
95
- * to deliver, which says whether a replay cursor started past it.
96
- */
97
- readonly failed?: (
98
- message: ChannelInboundMessage,
99
- topic: string,
100
- error: unknown,
101
- receivedAt: number,
102
- ) => void
103
- /**
104
- * Whether the listener relays the subscription `topic`'s subject from the session's consumer
105
- * (consumer delivery), which shows its frames: a core frame on it claims nothing and goes on as
106
- * a duplicate, only to answer a lane's receipt. Read before the claim, so the core copy never
107
- * holds the claim its relayed copy needs.
108
- */
109
- readonly relayed?: (topic: string) => boolean
110
- }
111
-
112
- interface Following {
113
- readonly subscription: ChannelTopicSubscription
114
- readonly done: Promise<void>
115
- }
116
-
117
- // A delivery's identity fields parse independently: a field the shared rule refuses identifies
118
- // nothing, and its valid sibling can still recognise a repeat. `topic` follows the same rule
119
- // before it is exposed as the envelope topic.
120
- const DeliveryIdentity = DedupeIdentitySchema.extend({
121
- event_id: DedupeIdentitySchema.shape.event_id.catch(undefined),
122
- dedupe_key: DedupeIdentitySchema.shape.dedupe_key.catch(undefined),
123
- source: DedupeIdentitySchema.shape.source.catch(undefined),
124
- source_event_id: DedupeIdentitySchema.shape.source_event_id.catch(undefined),
125
- topic: z.string().min(1).optional().catch(undefined),
126
- })
127
-
128
- const decoder = new TextDecoder()
129
- const DEFAULT_DRAIN_TIMEOUT_MS = 1_000
130
-
131
- /** A frame's identity fields, each kept only when valid; undefined for a frame that is not JSON. */
132
- export function deliveryIdentity(raw: string): z.infer<typeof DeliveryIdentity> | undefined {
133
- let parsed: unknown
134
- try {
135
- parsed = JSON.parse(raw)
136
- } catch {
137
- return undefined
138
- }
139
- const identity = DeliveryIdentity.safeParse(parsed)
140
- return identity.success ? identity.data : undefined
141
- }
142
-
143
- function report(what: string, error: unknown): void {
144
- process.stderr.write(`envoy-channel: ${what} — ${messageFor(error)}\n`)
145
- }
146
-
147
- /**
148
- * One channel process receives both its direct Envoy route and every followed
149
- * topic. It deduplicates at the broker boundary, by event id and by dedupe key,
150
- * so an event covered by several patterns, and a re-send of one already
151
- * delivered, still becomes one line in the session's conversation. With a replay
152
- * ledger, a frame the session was shown before this process started is dropped
153
- * too, and each frame handed on is recorded there before its claim settles.
154
- */
155
- export function createChannelForwarder(
156
- connection: ChannelForwarderConnection,
157
- options: ChannelForwarderOptions,
158
- ): ChannelForwarder {
159
- const following = new Map<string, Following>()
160
- const dedupe = options.dedupe ?? createDeliveryDedupe()
161
- const drainTimeoutMs = options.drainTimeoutMs ?? DEFAULT_DRAIN_TIMEOUT_MS
162
-
163
- const deliver = async (topic: string, subscription: ChannelTopicSubscription): Promise<void> => {
164
- try {
165
- for await (const { message, receivedAt } of readArrivals(subscription)) {
166
- const raw = decoder.decode(message.data)
167
- const identity = deliveryIdentity(raw)
168
- // The relay shows this subject's frames: the core copy answers only a lane's receipt.
169
- let claim = options.relayed?.(topic) === true ? undefined : dedupe.claim(identity)
170
- // A repeat of a frame the session was shown before this process started, which only the
171
- // replay ledger knows of: it goes on as a duplicate, which still answers a lane's receipt.
172
- if (claim !== undefined && identity !== undefined && options.ledger?.delivered(identity)) {
173
- claim.settle()
174
- claim = undefined
175
- }
176
- // A nats.js Msg exposes subject/data/reply through prototype getters,
177
- // which an object spread would silently drop; copy the fields by name.
178
- const inbound: ChannelInboundMessage = {
179
- subject: message.subject,
180
- data: message.data,
181
- raw,
182
- // nats.js MsgImpl.reply is a getter returning "" when unset; absent means no reply address.
183
- ...(message.reply ? { reply: message.reply } : {}),
184
- ...(identity?.topic === undefined ? {} : { envelopeTopic: identity.topic }),
185
- ...(claim === undefined ? { duplicate: true } : {}),
186
- }
187
- let handed: boolean
188
- try {
189
- handed = await options.deliver(inbound)
190
- } catch (error) {
191
- claim?.release()
192
- report(`could not deliver a message on ${message.subject}`, error)
193
- // A duplicate was never being shown; only its receipt can have failed.
194
- if (claim !== undefined) options.failed?.(inbound, topic, error, receivedAt)
195
- continue
196
- }
197
- if (claim === undefined) continue
198
- if (!handed) {
199
- claim.release()
200
- continue
201
- }
202
- // Recorded before the claim settles, so a replay never finds the frame neither pending
203
- // nor in the ledger and shows it a second time. The next frame does not wait for the
204
- // write: a repeat of this one meanwhile still finds its claim.
205
- const taken = claim
206
- const settle = () => taken.settle()
207
- if (identity === undefined || options.ledger === undefined) settle()
208
- else void options.ledger.recordDelivered(identity).then(settle, settle)
209
- }
210
- } catch (error) {
211
- report(`delivery from ${topic} stopped`, error)
212
- }
213
- }
214
-
215
- const stop = async (topics: readonly string[]): Promise<void> => {
216
- const stopping = topics.flatMap((topic) => {
217
- const entry = following.get(topic)
218
- if (entry === undefined) return []
219
- following.delete(topic)
220
- entry.subscription.unsubscribe()
221
- return [entry.done]
222
- })
223
- await Promise.all(stopping)
224
- }
225
-
226
- return {
227
- follow(topic) {
228
- for (const subject of expandSubscriptionTopics([topic])) {
229
- if (following.has(subject)) continue
230
- const subscription = connection.subscribe(subject)
231
- following.set(subject, { subscription, done: deliver(subject, subscription) })
232
- }
233
- },
234
- unfollow(topics) {
235
- return stop(topics.length === 0 ? [...following.keys()] : expandSubscriptionTopics(topics))
236
- },
237
- topics() {
238
- return [...following.keys()]
239
- },
240
- isClosed() {
241
- return connection.isClosed()
242
- },
243
- async close() {
244
- await stop([...following.keys()])
245
- if (connection.isClosed()) return
246
- const timeout = Promise.withResolvers<void>()
247
- const timer = setTimeout(timeout.resolve, drainTimeoutMs)
248
- try {
249
- await Promise.race([connection.drain(), timeout.promise])
250
- } catch (error) {
251
- report("draining the broker connection failed", error)
252
- }
253
- clearTimeout(timer)
254
- if (connection.isClosed()) return
255
- try {
256
- await connection.close()
257
- } catch (error) {
258
- report("closing the broker connection failed", error)
259
- }
260
- },
261
- }
262
- }