@sjawhar/claude-envoy 1.18.0 → 1.20.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 +2 -2
- package/.omp-plugin/plugin.json +2 -2
- package/AGENTS.md +167 -42
- package/README.md +95 -177
- package/dist/dispatch.js +54 -6
- package/dist/envoy-channel.js +2413 -875
- package/dist/session-hook.js +54 -6
- package/hooks/claude-mod.d.ts +500 -0
- package/hooks/hooks.json +2 -1
- package/hooks/mod-protocol.ts +728 -0
- package/hooks/mod-writer.ts +506 -0
- package/hooks/mod.ts +716 -0
- package/package.json +2 -2
- package/scripts/smoke-clear-rebind.sh +1 -1
- package/scripts/smoke-session-title.sh +1 -1
- package/skills/agent-secrets/SKILL.md +55 -4
- package/src/agent-stream-claude.ts +558 -0
- package/src/agent-stream-runner.ts +340 -0
- package/src/bounded-set.ts +54 -0
- package/src/channel-forwarder.ts +1 -1
- package/src/claude-rows.ts +195 -0
- package/src/envoy-channel-server.ts +394 -136
- package/src/envoy-off.ts +6 -1
- package/src/installed-build.ts +26 -0
- package/src/legion-inbox.ts +22 -11
- package/src/mod-link.ts +562 -0
- package/src/mod-session.ts +499 -0
- package/src/replay-state.ts +2 -18
- package/src/state-file.ts +39 -0
- package/src/user-turn-router.ts +496 -0
- package/src/user-turn-state.ts +134 -0
- package/scripts/smoke-channel.sh +0 -178
- package/src/claude-channel.ts +0 -705
|
@@ -0,0 +1,499 @@
|
|
|
1
|
+
// The Claude Code session as the router drives it (INFRA-1026): what the mod says is happening in
|
|
2
|
+
// it, and the calls that put something into it.
|
|
3
|
+
//
|
|
4
|
+
// Where a message goes — a row of the turn running, or the prompt of a new turn — and whether a
|
|
5
|
+
// turn that ended without reading a row is pointed at it are the mod's to decide, not this
|
|
6
|
+
// file's: the mod is the one process where the turn's events and this plugin's writes arrive in
|
|
7
|
+
// one order. Three review rounds found a race in deciding them here, each from the same cause —
|
|
8
|
+
// two posts whose order is not the order the session saw (INFRA-1026 review, rounds nine to
|
|
9
|
+
// eleven). So this file hands the mod one message and reads back the row it became
|
|
10
|
+
// (`session.message`, `../hooks/mod-protocol.ts`), and what is left here is what the row's own
|
|
11
|
+
// id answers:
|
|
12
|
+
//
|
|
13
|
+
// - a `$.command.run` of this session's writes its rows after the call that asked for it has
|
|
14
|
+
// answered (19 ms and 90 ms after it, measured on 2.1.310), and nothing in a row tells it
|
|
15
|
+
// from a command a person typed at the session's own terminal: in a terminal session both
|
|
16
|
+
// carry `origin.kind` `engine`, and the command a row names need not be the one asked for,
|
|
17
|
+
// since Claude Code runs `/cost` as `/usage` and `/model anthropic/haiku` as
|
|
18
|
+
// `/model haiku`. So a run claims the first echo row that arrives within `COMMAND_ECHO_MS`
|
|
19
|
+
// of its own answer, and the output row directly behind that echo (`runsCommandRow`,
|
|
20
|
+
// `runCommand`); every other command row is a person's.
|
|
21
|
+
// - the live view draws a row by what it is, and asks here by the row's own id
|
|
22
|
+
// (`appendedRow`, `runsUnreadPrompt`). Both are answered from the stamp the mod puts on the
|
|
23
|
+
// row's own event (`ModEvent`'s `wrote`), which is in place before the view reads that
|
|
24
|
+
// event, since the server hands every event here first (`./envoy-channel-server`).
|
|
25
|
+
//
|
|
26
|
+
// Nothing in this file opens a socket or reads the link's stream: the live view reads the mod's
|
|
27
|
+
// events and hands each one here (`observe`).
|
|
28
|
+
import { messageFor } from "@legion/envoy-client/errors"
|
|
29
|
+
import type {
|
|
30
|
+
ModCallResults,
|
|
31
|
+
ModConfigValue,
|
|
32
|
+
ModContentBlock,
|
|
33
|
+
ModEffort,
|
|
34
|
+
ModEvent,
|
|
35
|
+
ModUnreadMessage,
|
|
36
|
+
} from "../hooks/mod-protocol"
|
|
37
|
+
import { rememberBounded } from "./bounded-set"
|
|
38
|
+
import { claudeCommandOutput, claudeEchoedCommandLine } from "./claude-rows"
|
|
39
|
+
import type { ModLink } from "./mod-link"
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* How long a card's write may take before its caller gives up on it (`show`).
|
|
43
|
+
*
|
|
44
|
+
* The mod answers as soon as the session has the message: a `$.session.append` into the turn
|
|
45
|
+
* running resolved in 9 ms on 2.1.310, and an idle `$.prompt.submit` in 81 ms to 166 ms, each
|
|
46
|
+
* with the row already written (`/legion/scratch/tmp/infra-1026-spike/logs`). What can take
|
|
47
|
+
* longer is a person typing in the moment the mod found the session idle: the prompt then waits
|
|
48
|
+
* for their turn to end — 8.5 s, 11.2 s and 12.4 s in the submits recorded — and the mod's own
|
|
49
|
+
* store costs a little more under load (a `get` of 114 ms and a `set` of 175 ms were seen,
|
|
50
|
+
* `/legion/scratch/tmp/infra-1026-store`). Thirty seconds covers all of that; past it the frame
|
|
51
|
+
* is left unanswered, Envoy sends it again, and the mod's record of the event id is what keeps
|
|
52
|
+
* the one message from being written twice (`../hooks/mod-writer.ts`, `writeOnce`).
|
|
53
|
+
*/
|
|
54
|
+
const SHOW_TIMEOUT_MS = 30_000
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* How long a `$.command.run` may take. A command waits for the turn running and for a dialog at
|
|
58
|
+
* the terminal, neither of which has a bound of its own; a day is past any of that and inside
|
|
59
|
+
* the 32-bit range a timer takes. What a person sees meanwhile is the router's waiting reply,
|
|
60
|
+
* posted ten seconds in.
|
|
61
|
+
*/
|
|
62
|
+
const COMMAND_TIMEOUT_MS = 24 * 60 * 60 * 1_000
|
|
63
|
+
|
|
64
|
+
/** How long a `$.model.fork` may take: one model call with the conversation as its context, which
|
|
65
|
+
* the link's own 30 seconds would cut short. */
|
|
66
|
+
const FORK_TIMEOUT_MS = 10 * 60 * 1_000
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* How long a run whose echo row has been claimed waits for the output row Claude Code wrote
|
|
70
|
+
* behind it. The row reaches this process as a `session.append` event on a post of its own, so
|
|
71
|
+
* it and the call's result can cross: measured on 2.1.310, the row followed the result by 29 ms
|
|
72
|
+
* for `/context` (`/legion/scratch/tmp/infra-1026-spike/logs/mod3-q7-int.jsonl:70-73`) and by
|
|
73
|
+
* 158 ms for `/effort low` (`logs/mod3-q2-310.jsonl:98-102`). Two seconds is more than ten times
|
|
74
|
+
* either, and it is all a command that wrote no row costs the person before they are told it
|
|
75
|
+
* printed nothing.
|
|
76
|
+
*/
|
|
77
|
+
const COMMAND_OUTPUT_MS = 2_000
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* How long after its own answer a `$.command.run` may still claim the echo row Claude Code
|
|
81
|
+
* wrote for it.
|
|
82
|
+
*
|
|
83
|
+
* Measured on live Claude Code 2.1.310 (INFRA-1026): a `/model haiku` this session ran answered
|
|
84
|
+
* at 08:14:06.839 and its echo row landed at 08:14:06.858, 19 ms later; an earlier recording of
|
|
85
|
+
* the same shape put that echo 90 ms after the answer. One second is more than ten times the
|
|
86
|
+
* longest seen.
|
|
87
|
+
*
|
|
88
|
+
* It is bounded at all because a run that claims every later row takes rows that are not its
|
|
89
|
+
* own: a Dispatch `/cost` whose dialog waited for the person was asked at 08:09:56.390 and had
|
|
90
|
+
* written no row of its own when the person typed `/config` at their own terminal 36 seconds
|
|
91
|
+
* later, and the rule before this one gave that run the person's echo and output rows - the
|
|
92
|
+
* person's command vanished from the live view, and their `/cost` reply read
|
|
93
|
+
* `Config dialog dismissed`.
|
|
94
|
+
*/
|
|
95
|
+
const COMMAND_ECHO_MS = 1_000
|
|
96
|
+
|
|
97
|
+
/** The most claimed rows of one kind this session remembers (`rememberBounded`). The live view
|
|
98
|
+
* asks about a row in the same tick this session claimed it (`runsCommandRow`,
|
|
99
|
+
* `runsUnreadPrompt`, `appendedRow`), so a handful would answer every ask; this is the bound
|
|
100
|
+
* that keeps a record from growing for the session's life. */
|
|
101
|
+
const CLAIMED_ROWS_MAX = 64
|
|
102
|
+
|
|
103
|
+
/** The session's model, as a `/config` row names it. */
|
|
104
|
+
const MODEL_CONFIG_KEY = "model"
|
|
105
|
+
|
|
106
|
+
/** What the router does to this session. */
|
|
107
|
+
export interface ModSession {
|
|
108
|
+
/** Whether the mod is polling the link now; nothing below reaches the session without one. */
|
|
109
|
+
connected(): boolean
|
|
110
|
+
/** Take one of the mod's events. The live view hands over every event it reads, in order. */
|
|
111
|
+
observe(event: ModEvent): void
|
|
112
|
+
/**
|
|
113
|
+
* Whether the row `row` names is the echo row a `$.command.run` of this session's claimed,
|
|
114
|
+
* which is the row the live view must not draw as a person's message: Claude Code echoes the
|
|
115
|
+
* command it ran rather than the one that was asked for - `/cost` ran as `/usage`, and
|
|
116
|
+
* `/model anthropic/haiku` as `/model haiku`, measured live on 2.1.310 (INFRA-1026) - so the
|
|
117
|
+
* echo drawn is a second message the person never wrote, beside Dispatch's stored copy of the
|
|
118
|
+
* one they did send.
|
|
119
|
+
*
|
|
120
|
+
* One echo row per run, claimed inside `COMMAND_ECHO_MS` of that run's own answer: `origin`
|
|
121
|
+
* separates nothing, since a run's rows and a person's terminal command both reach
|
|
122
|
+
* `{"kind":"engine"}` (measured on live Claude Code 2.1.310, INFRA-1026). Every other row of
|
|
123
|
+
* the `command` door is a person's own, and the live view draws it.
|
|
124
|
+
*/
|
|
125
|
+
runsCommandRow(row: string): boolean
|
|
126
|
+
/**
|
|
127
|
+
* Whether the row `row` names is the row Claude Code wrote for the prompt this session
|
|
128
|
+
* pointed the model at unread messages with (`unreadRowPrompt`), which the live view must not
|
|
129
|
+
* draw: that prompt quotes rows the view has already drawn, so drawn it shows a viewer each
|
|
130
|
+
* of those messages twice.
|
|
131
|
+
*
|
|
132
|
+
* Answered from the stamp the mod put on the row's own event (`ModEvent`'s `wrote`), as
|
|
133
|
+
* `appendedRow` is. Read instead off the prompt's wording, a card carrying those words — a
|
|
134
|
+
* review of this code, or a message quoting one — was a card the view never drew (INFRA-1026
|
|
135
|
+
* review, round ten). Every other prompt row is a person's own prompt or a card an idle
|
|
136
|
+
* session took, and the view draws it.
|
|
137
|
+
*/
|
|
138
|
+
runsUnreadPrompt(row: string): boolean
|
|
139
|
+
/**
|
|
140
|
+
* Whether the row `row` names is the row one message this session was handed became: a card
|
|
141
|
+
* or a person's message appended into the turn running. Claude Code marks such a row
|
|
142
|
+
* `isMeta`, which the live view draws nothing of otherwise, so this is the one `isMeta` row
|
|
143
|
+
* it must draw (`./agent-stream-claude`).
|
|
144
|
+
*
|
|
145
|
+
* Answered from the stamp the mod put on the row's own event (`ModEvent`'s `wrote`), which
|
|
146
|
+
* the mod sends for the rows it appended itself: Claude Code does not re-enter a mod's own
|
|
147
|
+
* `session.append` hook for them (`../hooks/mod.ts`). The stamp is what separates such a row
|
|
148
|
+
* from another installed plugin's append, which reaches that hook under a `plugin` origin of
|
|
149
|
+
* its own — `{"kind":"plugin","name":"<the other plugin>"}`, measured in the issue's spike
|
|
150
|
+
* (`/legion/scratch/tmp/infra-1026-spike/logs`, where `spike-mod2` and `spike-mod3p` name
|
|
151
|
+
* themselves) — so a rule keeping every `plugin` origin drew another mod's model-facing
|
|
152
|
+
* context as the person's words (INFRA-1026 review, round ten).
|
|
153
|
+
*/
|
|
154
|
+
appendedRow(row: string): boolean
|
|
155
|
+
/**
|
|
156
|
+
* Hand the session one card: an Envoy delivery that is not the person's own message — an ask
|
|
157
|
+
* answer, a teammate's or an architect's message, an issue event, a notice of Envoy's own.
|
|
158
|
+
*
|
|
159
|
+
* The mod decides what the card becomes: the prompt of a new turn while nothing is running,
|
|
160
|
+
* submitted without `asUser` as the card's own text and stored nowhere else — an append
|
|
161
|
+
* starts nothing, so a card only appended would sit there until the person typed (INFRA-1026
|
|
162
|
+
* review), and a card appended *and* quoted by a prompt reached the model twice (INFRA-1026,
|
|
163
|
+
* handoff v6: both of the Agents page's rows 8 and 10 of session 225642d4 carried the one
|
|
164
|
+
* card) — or a row of the turn running, which the model reads at that turn's next request and
|
|
165
|
+
* which one prompt of the mod's quotes in full when the turn ends without a request having
|
|
166
|
+
* read it (`unreadRowPrompt`).
|
|
167
|
+
*
|
|
168
|
+
* It resolves when the mod answers with the write the card became - a row appended, or a
|
|
169
|
+
* prompt the engine took - and on nothing else: that answer is the proof the session has the
|
|
170
|
+
* card. A session that cannot take it — stopped, wedged,
|
|
171
|
+
* gone — answers nothing, so this rejects when `showMs` is up, the frame goes unanswered, and
|
|
172
|
+
* Envoy sends the card again (check k7's SIGSTOP, message, SIGKILL and `claude --resume <id>`
|
|
173
|
+
* clause). That resend is written once: the mod records the row each `eventId` became and
|
|
174
|
+
* answers a copy of that event from the record, writing nothing (`../hooks/mod-writer.ts`,
|
|
175
|
+
* `writeOnce`). A card with no `eventId` — a notice this server writes for itself — is
|
|
176
|
+
* written as it comes.
|
|
177
|
+
*/
|
|
178
|
+
show(card: {
|
|
179
|
+
readonly text: string
|
|
180
|
+
readonly content: readonly ModContentBlock[]
|
|
181
|
+
/** The Envoy event this card is, which the mod's write is idempotent by. */
|
|
182
|
+
readonly eventId?: string
|
|
183
|
+
}): Promise<void>
|
|
184
|
+
/**
|
|
185
|
+
* Hand the session a person's own message, as their own words (`asUser`). The mod decides
|
|
186
|
+
* what it becomes, as it does for a card: a row of the turn running, or the prompt of a new
|
|
187
|
+
* turn.
|
|
188
|
+
*
|
|
189
|
+
* As a row it resolves with the row's id, which the caller records as that Dispatch message.
|
|
190
|
+
* As a prompt it resolves with undefined: the row is the prompt's, and the caller recognises
|
|
191
|
+
* it by its text. A prompt the session dropped reaches the caller through `failed`, since the
|
|
192
|
+
* person is owed a reply on Dispatch for a message their session refused; anything else that
|
|
193
|
+
* went wrong rejects, leaving the frame for Envoy to send again.
|
|
194
|
+
*
|
|
195
|
+
* It carries the frame's Envoy event id exactly as a card does, and for the same reason: when
|
|
196
|
+
* the mod's answer is late this rejects, the frame goes unanswered and Envoy sends it again,
|
|
197
|
+
* and the resend arrives as a *card* — the Dispatch attempt is spent, so the accept refuses
|
|
198
|
+
* it (`./user-turn-router`, `acceptUserTurn`). Without the id the two writes are two records
|
|
199
|
+
* and the model reads the person's words twice, once as their own prompt and once as a card;
|
|
200
|
+
* with it the resend finds the row this write left and nothing is written again
|
|
201
|
+
* (`../hooks/mod-writer.ts`, `writeOnce`).
|
|
202
|
+
*/
|
|
203
|
+
deliver(input: {
|
|
204
|
+
readonly text: string
|
|
205
|
+
/** The Dispatch message the text is, which the prompt at an unread row names. */
|
|
206
|
+
readonly messageId: string
|
|
207
|
+
readonly content: readonly ModContentBlock[]
|
|
208
|
+
/** The Envoy event this message is, which the mod's write is idempotent by; absent only for
|
|
209
|
+
* a message that reached this session as no frame of Envoy's. */
|
|
210
|
+
readonly eventId?: string
|
|
211
|
+
readonly failed?: (error: unknown) => void
|
|
212
|
+
}): Promise<string | undefined>
|
|
213
|
+
/** Run one slash command and answer what it printed, which is the empty string where it
|
|
214
|
+
* printed nothing. */
|
|
215
|
+
runCommand(command: string, args: string): Promise<string>
|
|
216
|
+
/** Ask the model one question off to the side, with the conversation as its context, and answer
|
|
217
|
+
* what it said. It adds nothing to the conversation. */
|
|
218
|
+
fork(prompt: string): Promise<string>
|
|
219
|
+
/** Set the session's model, and answer the value Claude Code stored. */
|
|
220
|
+
setModel(model: string): Promise<ModConfigValue>
|
|
221
|
+
/** Set the effort the mod puts on every later request, and answer what is now in force. */
|
|
222
|
+
setEffort(effort: ModEffort | null): Promise<ModEffort | null>
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
export interface ModSessionOptions {
|
|
226
|
+
readonly link: Pick<ModLink, "request" | "connected">
|
|
227
|
+
/** Where a failure that must not stop the session is written. */
|
|
228
|
+
readonly warn: (text: string) => void
|
|
229
|
+
/** How long a run whose echo row has been claimed waits for the output row behind it;
|
|
230
|
+
* `COMMAND_OUTPUT_MS` by default, named by the tests that drive it. */
|
|
231
|
+
readonly commandOutputMs?: number
|
|
232
|
+
/** How long after its own answer a run may still claim an echo row; `COMMAND_ECHO_MS` by
|
|
233
|
+
* default, named by the tests that drive it. */
|
|
234
|
+
readonly commandEchoMs?: number
|
|
235
|
+
/** How long a card's write waits for the mod's answer; `SHOW_TIMEOUT_MS` by default, named by
|
|
236
|
+
* the tests that drive it. */
|
|
237
|
+
readonly showMs?: number
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/** One `$.command.run` whose rows are still to come, and the rows it claimed. A run's rows
|
|
241
|
+
* arrive after the call answers - 5 ms, 19 ms and 49 ms behind it for a `/model haiku`
|
|
242
|
+
* measured on live Claude Code 2.1.310 (INFRA-1026) - so a run claims the first echo row
|
|
243
|
+
* inside `COMMAND_ECHO_MS` of its own answer, and the output row directly behind that echo. */
|
|
244
|
+
interface CommandRun {
|
|
245
|
+
/** Whether this run may claim an echo row now: true from the moment its own call answers
|
|
246
|
+
* until it has claimed one or `COMMAND_ECHO_MS` has passed. */
|
|
247
|
+
claiming: boolean
|
|
248
|
+
/** The echo row this run claimed, which is the row the live view draws nothing of. */
|
|
249
|
+
echo?: string
|
|
250
|
+
/** Woken by that row, so a run claims and moves on the moment its echo lands. */
|
|
251
|
+
claimed?: () => void
|
|
252
|
+
/** What the output row held, once the row behind this run's echo has been read. */
|
|
253
|
+
output?: string
|
|
254
|
+
/** Woken by that row, so a result carrying no output answers the moment the row lands. */
|
|
255
|
+
arrived?: () => void
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* What a `$.command.run` result says the command printed, or undefined where it says nothing
|
|
260
|
+
* and the output row is the only place the output is.
|
|
261
|
+
*
|
|
262
|
+
* Measured on 2.1.310 in a terminal session: `/context` resolves `{context: ["## Context Usage…
|
|
263
|
+
* "]}` with no `text` field at all
|
|
264
|
+
* (`/legion/scratch/tmp/infra-1026-spike/logs/mod3-q7-int.jsonl:70-73`), and `/effort low`
|
|
265
|
+
* resolves `{}` (`logs/mod3-q2-310.jsonl:98-102`). A `context` entry is Claude Code's own
|
|
266
|
+
* markdown of the table, where the output row holds the terminal's drawing of it, escape codes
|
|
267
|
+
* and all, so it is read before the row and after the text.
|
|
268
|
+
*/
|
|
269
|
+
function resultOutput(result: ModCallResults["command.run"]): string | undefined {
|
|
270
|
+
if (result.text !== undefined && result.text.trim() !== "") return result.text
|
|
271
|
+
const context = result.context?.join("\n\n")
|
|
272
|
+
return context !== undefined && context.trim() !== "" ? context : undefined
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* The session behind `options.link`. Every call rejects when the mod does not answer; the caller
|
|
277
|
+
* decides what a frame does then, and nothing here writes to the session on its own.
|
|
278
|
+
*/
|
|
279
|
+
export function modSession(options: ModSessionOptions): ModSession {
|
|
280
|
+
const { link, warn } = options
|
|
281
|
+
/** The `$.command.run` calls whose rows are still to come, oldest first. A run is here from
|
|
282
|
+
* the call going out until the rows it claims have been read or the waits for them have
|
|
283
|
+
* passed, so this holds what a person has running and nothing else. */
|
|
284
|
+
const commandRuns: CommandRun[] = []
|
|
285
|
+
/** The echo rows this session's runs claimed, newest last and bounded by `CLAIMED_ROWS_MAX`:
|
|
286
|
+
* what `runsCommandRow` answers from. */
|
|
287
|
+
const claimedEchoes = new Set<string>()
|
|
288
|
+
/** The rows the mod stamped `pointer`, newest last and bounded by `CLAIMED_ROWS_MAX`: what
|
|
289
|
+
* `runsUnreadPrompt` answers from. */
|
|
290
|
+
const claimedUnreadPrompts = new Set<string>()
|
|
291
|
+
/** The rows the mod stamped `message`, newest last and bounded by `CLAIMED_ROWS_MAX`: what
|
|
292
|
+
* `appendedRow` answers from. */
|
|
293
|
+
const claimedAppends = new Set<string>()
|
|
294
|
+
/** The run whose claimed echo row was the last row of the `command` door to arrive, so the
|
|
295
|
+
* output row directly behind that echo is read as its output and no later row is. */
|
|
296
|
+
let behindEcho: CommandRun | undefined
|
|
297
|
+
const outputMs = options.commandOutputMs ?? COMMAND_OUTPUT_MS
|
|
298
|
+
const echoMs = options.commandEchoMs ?? COMMAND_ECHO_MS
|
|
299
|
+
const showMs = options.showMs ?? SHOW_TIMEOUT_MS
|
|
300
|
+
|
|
301
|
+
const runsCommandRow = (row: string): boolean => claimedEchoes.has(row)
|
|
302
|
+
const runsUnreadPrompt = (row: string): boolean => claimedUnreadPrompts.has(row)
|
|
303
|
+
const appendedRow = (row: string): boolean => claimedAppends.has(row)
|
|
304
|
+
|
|
305
|
+
/** One row of the `command` door, given to the run it belongs to or to no run at all.
|
|
306
|
+
*
|
|
307
|
+
* A run claims one echo row: the first to arrive after its own call answered and inside
|
|
308
|
+
* `COMMAND_ECHO_MS` of that answer, oldest unclaimed run first. The output row directly
|
|
309
|
+
* behind that echo is what the run printed. An echo no run claimed is a command a person
|
|
310
|
+
* typed at their own terminal, and the output row behind it is theirs too: measured on live
|
|
311
|
+
* Claude Code 2.1.310 (INFRA-1026), the two are told apart by that timing and by nothing
|
|
312
|
+
* else - the person's `/config` echo and the `/usage` echo of a run this session made both
|
|
313
|
+
* carried `origin {"kind":"engine"}`, and the command a row names says nothing either, since
|
|
314
|
+
* `/cost` runs as `/usage`.
|
|
315
|
+
*/
|
|
316
|
+
const commandRow = (uuid: string, content: readonly ModContentBlock[]): void => {
|
|
317
|
+
if (claudeEchoedCommandLine(content) !== undefined) {
|
|
318
|
+
const claiming = commandRuns.find((waiting) => waiting.claiming)
|
|
319
|
+
behindEcho = claiming
|
|
320
|
+
if (claiming === undefined) return
|
|
321
|
+
claiming.claiming = false
|
|
322
|
+
claiming.echo = uuid
|
|
323
|
+
rememberBounded(claimedEchoes, uuid, CLAIMED_ROWS_MAX)
|
|
324
|
+
claiming.claimed?.()
|
|
325
|
+
return
|
|
326
|
+
}
|
|
327
|
+
const run = behindEcho
|
|
328
|
+
behindEcho = undefined
|
|
329
|
+
const output = claudeCommandOutput(content)
|
|
330
|
+
if (output === undefined || run === undefined) return
|
|
331
|
+
run.output = output
|
|
332
|
+
run.arrived?.()
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/** This run is over: no row that arrives from here on is its. */
|
|
336
|
+
const endRun = (run: CommandRun): void => {
|
|
337
|
+
const at = commandRuns.indexOf(run)
|
|
338
|
+
if (at !== -1) commandRuns.splice(at, 1)
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/**
|
|
342
|
+
* What the rows of `run` held, waited for in the order they arrive: the echo row inside
|
|
343
|
+
* `COMMAND_ECHO_MS` of the call's answer, then the output row directly behind it inside
|
|
344
|
+
* `COMMAND_OUTPUT_MS`. The waits are started the moment the call answers, which is when the
|
|
345
|
+
* run may first claim a row, and the run is one wait however many callers read it.
|
|
346
|
+
*
|
|
347
|
+
* A run that claimed no echo claimed nothing: it printed nothing here, and whatever the call
|
|
348
|
+
* itself answered is the only reply there is (`runCommand`). A run whose echo was claimed and
|
|
349
|
+
* whose output row never came printed nothing too.
|
|
350
|
+
*/
|
|
351
|
+
const commandRowsOf = async (run: CommandRun): Promise<string> => {
|
|
352
|
+
try {
|
|
353
|
+
const echoed = Promise.withResolvers<void>()
|
|
354
|
+
const echoTimer = setTimeout(echoed.resolve, echoMs)
|
|
355
|
+
echoTimer.unref()
|
|
356
|
+
run.claimed = () => {
|
|
357
|
+
clearTimeout(echoTimer)
|
|
358
|
+
echoed.resolve()
|
|
359
|
+
}
|
|
360
|
+
run.claiming = true
|
|
361
|
+
await echoed.promise
|
|
362
|
+
run.claiming = false
|
|
363
|
+
if (run.echo === undefined) return ""
|
|
364
|
+
if (run.output === undefined) {
|
|
365
|
+
const waited = Promise.withResolvers<void>()
|
|
366
|
+
const timer = setTimeout(waited.resolve, outputMs)
|
|
367
|
+
timer.unref()
|
|
368
|
+
run.arrived = () => {
|
|
369
|
+
clearTimeout(timer)
|
|
370
|
+
waited.resolve()
|
|
371
|
+
}
|
|
372
|
+
await waited.promise
|
|
373
|
+
}
|
|
374
|
+
return run.output ?? ""
|
|
375
|
+
} finally {
|
|
376
|
+
endRun(run)
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/**
|
|
381
|
+
* Hand the mod one message and answer with the write it became.
|
|
382
|
+
*
|
|
383
|
+
* What the mod does with it — a row of the turn running, or the prompt of a new turn, and the
|
|
384
|
+
* one prompt that points the model at a row no request read — is the mod's own
|
|
385
|
+
* (`../hooks/mod-writer.ts`, `writeMessage`). What this file needs back is that answer, which
|
|
386
|
+
* is the proof the session has the message: `as` says which write it was, and a row's uuid
|
|
387
|
+
* comes with it.
|
|
388
|
+
*/
|
|
389
|
+
const written = async (
|
|
390
|
+
message: ModUnreadMessage,
|
|
391
|
+
content: readonly ModContentBlock[],
|
|
392
|
+
eventId: string | undefined,
|
|
393
|
+
): Promise<ModCallResults["session.message"]> =>
|
|
394
|
+
await link.request(
|
|
395
|
+
"session.message",
|
|
396
|
+
{ content, message, ...(eventId === undefined ? {} : { eventId }) },
|
|
397
|
+
{ timeoutMs: showMs },
|
|
398
|
+
)
|
|
399
|
+
|
|
400
|
+
return {
|
|
401
|
+
connected: () => link.connected(),
|
|
402
|
+
observe(event) {
|
|
403
|
+
if (event.kind !== "append") return
|
|
404
|
+
// Every row of the `command` door is read, and `commandRow` says whose it is: a row a
|
|
405
|
+
// run this session made claimed, or a row of a command a person typed at their own
|
|
406
|
+
// terminal, which belongs to nobody here.
|
|
407
|
+
if (event.door === "command") commandRow(event.uuid, event.message.content)
|
|
408
|
+
// What the mod stamped the row it wrote: the row one message became, which is the one
|
|
409
|
+
// `isMeta` row the live view draws, or the row of the prompt pointing the model at
|
|
410
|
+
// messages a turn never read, which that view draws nothing of. Claimed here, where the
|
|
411
|
+
// event arrives, and nowhere else: the server hands every event to this session before
|
|
412
|
+
// the view records it (`./envoy-channel-server`), so the claim is in place for the row
|
|
413
|
+
// being recorded, while a claim made from the answer of the call that wrote the row
|
|
414
|
+
// lands after the view has already read it (INFRA-1026 k2, measured live on 2.1.310 — a
|
|
415
|
+
// card delivered into a running turn reached the model and was drawn nowhere).
|
|
416
|
+
if (event.wrote === "message") rememberBounded(claimedAppends, event.uuid, CLAIMED_ROWS_MAX)
|
|
417
|
+
if (event.wrote === "pointer") {
|
|
418
|
+
rememberBounded(claimedUnreadPrompts, event.uuid, CLAIMED_ROWS_MAX)
|
|
419
|
+
}
|
|
420
|
+
},
|
|
421
|
+
async show({ text, content, eventId }) {
|
|
422
|
+
const answer = await written({ kind: "card", text }, content, eventId)
|
|
423
|
+
if (answer.deny !== undefined) throw new Error(`the session refused the card: ${answer.deny}`)
|
|
424
|
+
},
|
|
425
|
+
async deliver({ text, messageId, content, eventId, failed }) {
|
|
426
|
+
let answer: ModCallResults["session.message"]
|
|
427
|
+
try {
|
|
428
|
+
answer = await written({ kind: "person", messageId, text }, content, eventId)
|
|
429
|
+
} catch (error) {
|
|
430
|
+
// The mod answered nothing: the frame stays unanswered and Envoy sends it again, which
|
|
431
|
+
// the Dispatch attempt this message was accepted under turns into a card
|
|
432
|
+
// (`./user-turn-router`, `acceptUserTurn`) — written once, because that card carries
|
|
433
|
+
// the event id this write carried.
|
|
434
|
+
warn(`a message from Dispatch did not enter this session — ${messageFor(error)}`)
|
|
435
|
+
throw error
|
|
436
|
+
}
|
|
437
|
+
if (answer.deny !== undefined) {
|
|
438
|
+
const refusal = new Error(`the session dropped the prompt: ${answer.deny}`)
|
|
439
|
+
// A prompt the session dropped is the person's to be told about: their own words were
|
|
440
|
+
// refused, and Dispatch is where they are waiting. A row it refused is this server's
|
|
441
|
+
// failure to write, and the frame is left for Envoy to send again.
|
|
442
|
+
if (answer.as !== "prompt" || failed === undefined) throw refusal
|
|
443
|
+
warn(`a message from Dispatch did not enter this session — ${messageFor(refusal)}`)
|
|
444
|
+
failed(refusal)
|
|
445
|
+
return undefined
|
|
446
|
+
}
|
|
447
|
+
// The row of a prompt is the prompt's own, which the caller recognises by its text; the
|
|
448
|
+
// row of an append is this message's, and the caller records it as that Dispatch message.
|
|
449
|
+
return answer.as === "row" ? answer.uuid : undefined
|
|
450
|
+
},
|
|
451
|
+
appendedRow,
|
|
452
|
+
runsCommandRow,
|
|
453
|
+
runsUnreadPrompt,
|
|
454
|
+
async runCommand(command, args) {
|
|
455
|
+
const run: CommandRun = { claiming: false }
|
|
456
|
+
commandRuns.push(run)
|
|
457
|
+
let result: ModCallResults["command.run"]
|
|
458
|
+
try {
|
|
459
|
+
result = await link.request(
|
|
460
|
+
"command.run",
|
|
461
|
+
{ command, ...(args === "" ? {} : { args }) },
|
|
462
|
+
{ timeoutMs: COMMAND_TIMEOUT_MS },
|
|
463
|
+
)
|
|
464
|
+
} catch (error) {
|
|
465
|
+
endRun(run)
|
|
466
|
+
throw error
|
|
467
|
+
}
|
|
468
|
+
// The run's own rows are still to come: measured on live Claude Code 2.1.310
|
|
469
|
+
// (INFRA-1026), a `/model haiku` answered at 08:14:06.839 and its caveat, echo and
|
|
470
|
+
// output rows followed at .844, .858 and .888. So the wait for them is started whatever
|
|
471
|
+
// the result carried - the echo this run claims is the row the live view must not draw,
|
|
472
|
+
// and the claim is what makes the output row behind it this run's rather than a
|
|
473
|
+
// person's typing.
|
|
474
|
+
const rows = commandRowsOf(run)
|
|
475
|
+
// What the command printed, in the order the measurements put it: the result's own
|
|
476
|
+
// text, then its `context` entries, which is where a terminal `/context` puts its table
|
|
477
|
+
// and the only place it puts it
|
|
478
|
+
// (`/legion/scratch/tmp/infra-1026-spike/logs/mod3-q7-int.jsonl:70-73`, a result with no
|
|
479
|
+
// `text` field at all), then the output row this run claimed.
|
|
480
|
+
return resultOutput(result) ?? (await rows)
|
|
481
|
+
},
|
|
482
|
+
async fork(prompt) {
|
|
483
|
+
const result = await link.request("model.fork", { prompt }, { timeoutMs: FORK_TIMEOUT_MS })
|
|
484
|
+
if (!result.isAnswered) throw new Error(result.reason)
|
|
485
|
+
return result.text
|
|
486
|
+
},
|
|
487
|
+
async setModel(model) {
|
|
488
|
+
const result = await link.request("config.set", { key: MODEL_CONFIG_KEY, value: model })
|
|
489
|
+
if (result.deny !== undefined) {
|
|
490
|
+
throw new Error(`the session refused the model: ${result.deny}`)
|
|
491
|
+
}
|
|
492
|
+
return result.value
|
|
493
|
+
},
|
|
494
|
+
async setEffort(effort) {
|
|
495
|
+
const result = await link.request("set-effort", { effort })
|
|
496
|
+
return result.effort
|
|
497
|
+
},
|
|
498
|
+
}
|
|
499
|
+
}
|
package/src/replay-state.ts
CHANGED
|
@@ -5,16 +5,15 @@
|
|
|
5
5
|
// followed). Claude Code can resume a session at any later time, so no sweep prunes these files;
|
|
6
6
|
// each holds only cursors, followed subjects, a resume point and at most 72 hours of ledger,
|
|
7
7
|
// since the engine drops older ledger entries before every write.
|
|
8
|
-
import { readFile } from "node:fs/promises"
|
|
9
8
|
import { join } from "node:path"
|
|
10
9
|
import {
|
|
11
10
|
type ConsumerDeliverySnapshot,
|
|
12
11
|
ConsumerDeliverySnapshotSchema,
|
|
13
12
|
} from "@legion/envoy-client/consumer-delivery"
|
|
14
|
-
import { hasErrnoCode } from "@legion/envoy-client/errors"
|
|
15
13
|
import { type ReplaySnapshot, ReplaySnapshotSchema } from "@legion/envoy-client/replay"
|
|
16
14
|
import type { z } from "zod"
|
|
17
15
|
import { writeAtomicStateFile } from "./session-state"
|
|
16
|
+
import { readStateFile } from "./state-file"
|
|
18
17
|
|
|
19
18
|
/**
|
|
20
19
|
* A session's file: the replay snapshot, and the consumer delivery snapshot once the session had
|
|
@@ -39,22 +38,7 @@ export function replayStateFile(stateDirectory: string, sessionId: string): stri
|
|
|
39
38
|
* holds no replay snapshot throws.
|
|
40
39
|
*/
|
|
41
40
|
export async function readReplayState(file: string): Promise<ReplayStateFile> {
|
|
42
|
-
|
|
43
|
-
try {
|
|
44
|
-
text = await readFile(file, "utf8")
|
|
45
|
-
} catch (error) {
|
|
46
|
-
if (hasErrnoCode(error, "ENOENT")) return { ledger: [] }
|
|
47
|
-
throw error
|
|
48
|
-
}
|
|
49
|
-
let parsed: unknown
|
|
50
|
-
try {
|
|
51
|
-
parsed = JSON.parse(text)
|
|
52
|
-
} catch {
|
|
53
|
-
throw new Error(`${file} is not JSON`)
|
|
54
|
-
}
|
|
55
|
-
const snapshot = ReplayStateFileSchema.safeParse(parsed)
|
|
56
|
-
if (!snapshot.success) throw new Error(`${file} holds no replay state`)
|
|
57
|
-
return snapshot.data
|
|
41
|
+
return await readStateFile(file, ReplayStateFileSchema, { ledger: [] }, "holds no replay state")
|
|
58
42
|
}
|
|
59
43
|
|
|
60
44
|
/** Replaces the session's file by rename, mode 0600, as every other state file is written. */
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// Reading one of the plugin's JSON state files under `CLAUDE_PLUGIN_DATA`, shared by the records
|
|
2
|
+
// that keep one file per session id (`./replay-state`, `./user-turn-state`): no file is an empty
|
|
3
|
+
// record, and a file that holds something else is the caller's own refusal.
|
|
4
|
+
//
|
|
5
|
+
// It is not in `./session-state`, which writes those same files, because that module is the title
|
|
6
|
+
// hook's whole dependency graph and may not pull zod in: the hook runs before every user prompt,
|
|
7
|
+
// with Claude Code blocking the prompt on it.
|
|
8
|
+
import { readFile } from "node:fs/promises"
|
|
9
|
+
import { hasErrnoCode } from "@legion/envoy-client/errors"
|
|
10
|
+
import type { z } from "zod"
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* What `file` holds, read through `schema`; `empty` when there is no file at all. A file that is
|
|
14
|
+
* not JSON, or that `schema` refuses, throws: `refusal` finishes the sentence after the path, so
|
|
15
|
+
* each record names what it wanted of the file in its own words.
|
|
16
|
+
*/
|
|
17
|
+
export async function readStateFile<T>(
|
|
18
|
+
file: string,
|
|
19
|
+
schema: z.ZodType<T>,
|
|
20
|
+
empty: T,
|
|
21
|
+
refusal: string,
|
|
22
|
+
): Promise<T> {
|
|
23
|
+
let text: string
|
|
24
|
+
try {
|
|
25
|
+
text = await readFile(file, "utf8")
|
|
26
|
+
} catch (error) {
|
|
27
|
+
if (hasErrnoCode(error, "ENOENT")) return empty
|
|
28
|
+
throw error
|
|
29
|
+
}
|
|
30
|
+
let parsed: unknown
|
|
31
|
+
try {
|
|
32
|
+
parsed = JSON.parse(text)
|
|
33
|
+
} catch {
|
|
34
|
+
throw new Error(`${file} is not JSON`)
|
|
35
|
+
}
|
|
36
|
+
const state = schema.safeParse(parsed)
|
|
37
|
+
if (!state.success) throw new Error(`${file} ${refusal}`)
|
|
38
|
+
return state.data
|
|
39
|
+
}
|