@sjawhar/claude-envoy 2.44.1 → 2.45.1
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 +2 -2
- package/README.md +14 -5
- package/bin/envoy-send.ts +8 -5
- package/dist/dispatch.js +4 -1
- package/dist/envoy-channel.js +12 -3
- package/package.json +1 -2
- package/src/envoy-channel-server.ts +12 -1
- package/src/envoy-client.ts +0 -41
package/.omp-plugin/plugin.json
CHANGED
package/AGENTS.md
CHANGED
|
@@ -122,13 +122,13 @@ Dispatch asks stay on Dispatch.
|
|
|
122
122
|
| Channel configuration | `.mcp.json`, `bin/envoy-channel.ts` | Launch is `bun ${CLAUDE_PLUGIN_ROOT}/dist/envoy-channel.js`; stdout remains pure MCP protocol. The `env` block passes through `CLAUDE_PROJECT_DIR` only — an unset `${VAR}` is substituted literally, so optional inputs are inherited, never listed. |
|
|
123
123
|
| Hook command | `hooks/hooks.json`, `hooks/session-hook.ts`, `hooks/session-title-hook.ts` | Two bundles. `dist/session-hook.js` takes its mode as an argument — `open-asks`, `dispatch-first` or `answers`, plus `answers-refresh`, which only the `answers` mode starts and hooks.json never names; an argument naming none of them throws — and each mode is a hook of its own, because Claude Code caps each hook's output at 10,000 characters. `open-asks` (every `SessionStart`) names the `dispatch` command's host and hands on the session's envoy.json in `CLAUDE_ENV_FILE`, records the current session id per Claude process, records the session's chosen title and injects the open-asks summary; always exits 0. For a Legion pane (`LEGION_STATE_DIR` set) it writes the pane's jj attribution overlay under that directory too, and keeps exactly one `export JJ_CONFIG='<chain>'` line in `CLAUDE_ENV_FILE`: the line replaces an earlier one in its place rather than joining it, since a resume or a compaction of the same session id runs the hook again over the file it already wrote and the chain it resolves can differ; when no overlay could be written the file is left as it is, no line written and none removed, since `CLAUDE_ENV_FILE` is one file per session id (`<config>/session-env/<session id>/sessionstart-hook-<n>.sh`, read on the pinned 2.1.311) — a `/clear` gets a new and empty one, and a line already there names this same session's own overlay, still on disk and still correct. `dispatch-first` (every `SessionStart`, and every `SubagentStart`, since a subagent runs the same `dispatch` command) injects the `dispatch-first` skill as `hookSpecificOutput.additionalContext` under the input's `hook_event_name` when Dispatch is configured, reading `${CLAUDE_PLUGIN_ROOT}/skills/dispatch-first/SKILL.md` at run time and exiting non-zero naming it when it is missing. On a resume or fork Claude Code adds a SessionStart hook's context only when the transcript does not already hold the same text (measured on 2.1.283), so a resumed session keeps one copy and one opened without the skill gets it; the hook itself checks nothing. `answers` (every `SessionStart`, and every `SubagentStart`) injects what people wrote to the session in the last 72 hours as `hookSpecificOutput.additionalContext`: `readSessionAnswers` from `@legion/envoy-client/session-answers` for the input's `session_id` (at `SubagentStart` the parent's, which `tests/answers-claude.test.ts` checks on the real binary), the list pi-envoy puts on every model request, or its failure line naming why when a read failed and no list read before has an item to show, and nothing when there is nothing to show, Dispatch answered its own `404 NOT_FOUND` "no route for …" (`isNoAnswersRoute`, which `dispatch answers` cannot read past either; the hook then writes the read's `notice`, naming that Dispatch, to stderr, one line per process), or Dispatch is not configured; a proxy's 404 page or a 200 that is no answers list is a failed read. Its bound is counted from its process's start, Bun's start-up included: it prints by `ANSWERS_BY_MS` (800 ms, `SESSION_ANSWERS_DEADLINE_MS`), or `ANSWERS_LEAST_WAIT_MS` (150 ms) after its code begins when the start-up took longer, carrying the last list read from `answers.json` in the session's Dispatch state directory (`readSessionAnswers` works it out from `env`) when Dispatch has not answered, then waits on `sessionAnswersSettled` for `ANSWERS_SETTLE_MS` (50 ms) more so a read that answered late still writes that file for the next hook, and calls `process.exit(0)` whatever happened, a malformed input included (stderr names why), so nothing still in flight holds it. Dispatch is resolved with `commands: "kept"` first; a fresh process has kept no `!` command's outcome, so when that resolution is off with an error the mode starts the refresher: this bundle again (`process.execPath`, `Bun.main`) in mode `answers-refresh` with the session id and project directory, detached (its own session, so a signal to the hook's process group does not reach it), stdio ignored (so it holds none of the hook's pipes) and `unref()`ed, unless `answers-refresh.lock` in the session's state directory names a live refresher (its pid; a lock older than 30 s, or whose pid is gone, is stale). The refresher takes that lock (`wx`; a second one exits at once, so a burst of `SubagentStart` hooks runs the command once), resolves Dispatch with commands run, so `envoy-config`'s run of the command ends in its own process with its own clean-up (the group killed at the 10 s timeout, the stdout file's directory removed), reads with a 12 s deadline (which writes `answers.json`), writes `{finished_at, dispatch_url, text, notice}` to `answers-refresh.json` and removes the lock. The hook polls that file every 20 ms until its print deadline and carries its `text`, and reports its `notice` on stderr, when it finished after the hook started; otherwise it carries the last list read from the Dispatch URL envoy.json names now (`sessionDispatchUrl`, resolved before the wait without reading the token, passed as `readSessionAnswers`' `dispatchUrl`; a list another Dispatch answered never stands in) or the failure line naming that the command had not finished, and exits, so the next hook carries the list the refresher read. Its `timeout` is 5. Measured with Dispatch hanging: about 870 ms wall from spawn to exit; healthy, about 220 ms. `dist/session-title-hook.js` (every `UserPromptSubmit`, no argument) records the payload's `session_title` — the name a person gave the session, which Claude Code hands a hook and the plugin nowhere else — under `${CLAUDE_PLUGIN_DATA}/titles/`, and removes that file when the field is absent or blank, which is how a rename is undone. It writes nothing to stdout and exits 0 whatever happens, a payload that is not JSON included (`open-asks` and `dispatch-first` still fail loudly on one), because Claude Code adds a `UserPromptSubmit` hook's stdout to the model's context and reads its exit code 2 as a block of the prompt, and a cosmetic title may do neither; a failure goes to stderr. Claude Code blocks the user's prompt on it, so it is a bundle apart from the other two and keeps zod, the Dispatch client and `session-settings` out of its import graph (`src/session-state.ts` holds the file helpers for that reason, `src/session-identity.ts` imports zod and is not reachable from here): 5 kB and ~68 ms against the shared bundle's 811 kB and ~165 ms, the latter all but 3 ms of it bare `bun` start-up. It checks the payload itself — a non-empty string `session_id`, an optional string `session_title` — rather than carry a schema library. Its `timeout` is 5, not the 20 the `open-asks` and `dispatch-first` hooks carry. |
|
|
124
124
|
| Real Claude Code test | `tests/answers-claude.test.ts`, `/.claude-code-pin`, `/.github/actions/install-claude-code` | The `answers` hook on the real binary: Claude Code runs with this package as `--plugin-dir`, an isolated HOME and `CLAUDE_CONFIG_DIR`, and one stand-in as its Messages endpoint (`ANTHROPIC_BASE_URL`, server-sent events as the API streams them) and Dispatch (`DISPATCH_URL`); each case reads the list off the Messages request after the moment: startup (`claude -p --session-id`), `--resume <id>`, `/compact` sent in stream-json as `legion claude-bridge` sends turns, and a subagent (the stand-in answers with an `Agent` tool call, the API name of Claude Code's Task tool). `LEGION_TEST_CLAUDE` names the binary; the test skips without it, except on GitHub Actions, where the claude-envoy job installs the release `.claude-code-pin` pins (`bun add` into the runner's temp directory). A pin bump that changes a request shape is fixed in that file. |
|
|
125
|
-
| Inbound channel server | `src/envoy-channel-server.ts`, `src/envoy-off.ts` | MCP capability, notification queue, NATS registration, session-id handoff, role persistence, rejected-frame replies, and the Envoy tools, on the envoy.json Claude Code's rule picks (`@legion/envoy-client/session-settings`); why a section is off, and that inbound messages are off, goes to stderr once as `envoy-channel: <notice>`. `runEnvoyChannelServer` chooses between that server and the two reduced modes of `src/envoy-off.ts`. With Envoy off it runs `serveEnvoyOff` instead: an MCP server that lists no tool, refuses every call with `Envoy is off for this session: <why>` (the section's notice or error), opens no NATS connection and calls no listener, and exits 0 when stdin ends or on SIGTERM, SIGINT or SIGHUP. With Envoy on and inbound messages off (`inbound.off`: no NATS server, from `envoy.natsUrls` or `ENVOY_NATS_URL`, or its seed refused), it serves the tools on `inboundOffChannelSession`: no NATS connection, nothing registered with the listener, an empty inbox, `envoy_subscribe` refused naming why, and a role `envoy_role_set` claims still persisted. |
|
|
125
|
+
| Inbound channel server | `src/envoy-channel-server.ts`, `src/envoy-off.ts` | MCP capability, notification queue, NATS registration, session-id handoff, role persistence, rejected-frame replies, and the Envoy tools, on the envoy.json Claude Code's rule picks (`@legion/envoy-client/session-settings`); why a section is off, and that inbound messages are off, goes to stderr once as `envoy-channel: <notice>`. A tool whose `executeEnvoyTool` call throws answers a tool result with `isError: true` and the error's text (`messageFor`), so the model reads the listener's own sentence, a refusal for the sender's rate among them; an unknown tool (`UnsupportedEnvoyToolError`, which MCP counts among protocol errors) and a call before the channel session has started stay JSON-RPC errors. `runEnvoyChannelServer` chooses between that server and the two reduced modes of `src/envoy-off.ts`. With Envoy off it runs `serveEnvoyOff` instead: an MCP server that lists no tool, refuses every call with `Envoy is off for this session: <why>` (the section's notice or error), opens no NATS connection and calls no listener, and exits 0 when stdin ends or on SIGTERM, SIGINT or SIGHUP. With Envoy on and inbound messages off (`inbound.off`: no NATS server, from `envoy.natsUrls` or `ENVOY_NATS_URL`, or its seed refused), it serves the tools on `inboundOffChannelSession`: no NATS connection, nothing registered with the listener, an empty inbox, `envoy_subscribe` refused naming why, and a role `envoy_role_set` claims still persisted. |
|
|
126
126
|
| A person's message | `src/user-turn-router.ts`, `src/mod-session.ts`, `src/user-turn-state.ts`, `src/claude-rows.ts` | What a frame from Dispatch's Agents page becomes (INFRA-1026). The accept step is `acceptUserTurn` (`@legion/pi-shared/accept-user-turn`), the one step both Envoy plugins take — this router and `acceptedUserTurn` in `packages/pi-envoy/extensions/envoy.ts` — so a fix to the rule lands in both: a candidate frame (`isUserTurnCandidate`), an attempt this session has not handled, the attempt recorded **before** Dispatch is asked (a 404 included), the accept, and the stored body it answers — never the frame's own text. This host supplies the record, the Dispatch client, the session id and the wording of each refusal. The record lives in `turns/<url-encoded session id>.json` and outlives the process, so no restart spends an attempt twice; it also maps each delivered row to the Dispatch message it is, which tags that row on the live view. A row is matched to a message by the shared line rule (`comparableLines`, `@legion/contracts`), which the Agents page reads a stored body by too, so the two cannot drift and show a person's message twice. A terminal session takes the body through the mod (`$.session.append` during a turn, `$.prompt.submit({asUser:true})` while idle, one submit in flight at a time, and one plain submit at a row the turn never read); a pane's goes to the bridge's inbox, with its pictures as `blocks`. That plain submit carries each unread message's own words and its Dispatch id and never points at the row (`unreadRowPrompt`): driven live, a prompt saying "Read the message above" was answered `I don't see an actual Dispatch message content above` and `it looks like an injection and I'm not going to act on it`. A `/` message runs through `$.command.run` and its output is the reply — the result's `text`, else its `context` entries, which is where a terminal `/context` puts its table and the only place it puts it, else the `<local-command-stdout>` row Claude Code wrote for that run (`src/claude-rows.ts`, which the live view parses the same rows with), waited for two seconds since the row and the result reach this process on separate posts and cross — with a waiting reply after ten seconds, and a reply saying so when the command printed nothing, since `typedInputReply` has nothing to say for an empty output; `/model` and `/effort` are picks (`$.config.set`, `set-effort`), answered with `typedInputReply`'s text once the settings frame is refreshed; a BTW is `$.model.fork`. A row of the `command` door is a run's by when it arrives and by nothing else: a run claims the first echo row to arrive inside one second of its own answer (`runsCommandRow`), and the `<local-command-stdout>` row directly behind that claimed echo is that run's output, while an echo no run claimed — and the output row behind it — is a command the person typed at their own terminal and belongs to no run. Never by the command the row names: Claude Code runs `/cost` as `/usage` and `/model anthropic/haiku` as `/model haiku`. `origin` separates nothing, measured on live Claude Code 2.1.310 (INFRA-1026): a `/model haiku` this session ran answered at 08:14:06.839 and wrote its caveat (`{"kind":"plugin"}`, `isMeta`) at .844, its echo (`{"kind":"plugin"}`) at .858 and its stdout (`{"kind":"engine"}`) at .888, a `/config` a person typed at a terminal wrote its echo and its stdout with `{"kind":"engine"}` too, and a Dispatch `/cost` whose dialog waited for the person had written no row of its own when that `/config` arrived 36 seconds later. The live view draws nothing of a claimed echo row — the person's own line reaches the page as the message Dispatch stored beside the stream — and nothing of any row Claude Code marks `isMeta`, such as the `<system-reminder>` naming the session that a terminal `/rename` leaves behind its own two rows. |
|
|
127
127
|
| Session identity | `src/session-identity.ts`, `src/session-state.ts`, `src/claude-session.ts` | `SessionIdentity` is the one mutable id holder; handoff file `sessions/<claude-pid>/session-id`; role file `roles/<url-encoded session id>.json` (`readPersistedRole`, `writePersistedRole`; the suffix is what keeps a session id of `.` or `..` inside `roles/`, since `encodeURIComponent` leaves a dot alone), whose record carries the writing process's `client_instance_id` beside the session id and the role, optional so a record written before the field loads unchanged. `CLAUDE_CODE_SESSION_ID`, or explicit `ENVOY_SESSION_ID` for QA. `src/session-state.ts` holds what the state files share and nothing that imports zod: `writeAtomicStateFile`, and `pruneStateDirectory(directory, isStale)`, the one ENOENT-tolerant sweep behind all three of them — handoffs by liveness (a `sessions/<pid>` whose Claude process is gone, anything else there left alone), titles and roles by age (`writtenLongAgo`, `STATE_FILE_MAX_AGE_MS`, thirty days). The role sweep exists because exactly one path removes a role file by hand — a soft `setRole` the listener refuses naming a session that is **not** the one the record is for, which says that session no longer holds the role. A refusal naming the record's own session keeps the file: the role is then held under that id by another process sharing this state directory, and the refused process goes on pressing its claim, refreshing the record's mtime on each heartbeat as a confirmed holder does, so the age sweep never reaches a record a process is still claiming for. The handoff sweep cannot reach either, keyed as it is by session id with no process left to ask about. All three run at startup in `startChannelSession`, each under its own `.catch` that logs and swallows: the heartbeat timer is not armed yet, so housekeeping must never cost a session its channel. |
|
|
128
128
|
| Session title | `src/session-title.ts`, `src/session-state.ts` | The title every registration sends, which Dispatch's Agents page shows in place of the id: `ENVOY_SESSION_TITLE` on one line when it holds a character that shows; else the name the person running the session gave it (`claude -n`, `--name`, `/rename`), alone, with no short id after it, since a name a person chose needs nothing to tell it apart; else a name and the current id's first eight characters (a function of the id, so it follows a `/clear` handoff, and keeps two sessions in one tmux window apart). The chosen name is read, through `readChosenTitleSync`, from the `titles/<url-encoded session id>.txt` file the hooks write under `CLAUDE_PLUGIN_DATA` (keyed by id, like the role file, so `claude --resume <id>` finds it and a `/clear`'s new id starts without one; the suffix keeps a session id of `.` or `..` inside `titles/`, since `encodeURIComponent` leaves a dot alone), and every writer and reader goes through `sessionTitleFile` so the file the hook writes is the file the server reads; that read is synchronous and swallows every error, because a cosmetic title must leave the session on its fallback rather than fail the registration carrying it, and the name goes through the same `oneLine`/`visible` pair the other sources do, so a blank or invisible one falls through to the fallback while a multi-line one is put on one line and kept. The fallback's name is the pane's tmux name (`TMUX` and `TMUX_PANE`, one bounded `tmux -u -S <socket> display-message` at startup, used only when the answering server's pid is the one in `TMUX` and the pane's process is one of this process's ancestors (`isAncestor`); `session:window` when the window's `automatic-rename` is off, else the session, never a window index; for grouped sessions the group's name), else the project directory's name (outside tmux, a refused or missing answer, or a session named only by digits in a window nobody named). That name is worked out once as the server starts; the chosen name is asked for on every call instead, so a rename reaches the page on the session's next prompt plus a heartbeat, with no watcher anywhere. `pruneStaleSessionTitles` drops title files untouched for thirty days at startup, through the sweep the handoff and role prunes share and under the same best-effort guard, since nothing else deletes a file keyed by a session id. The listener replaces the stored title on every registration, and `register` also stamps it (`stampTitle`: `writeSessionTitle` in the session's Dispatch state directory) once per id, where the `dispatch` command reads it for the `session_title` on its writes; with inbound messages or Envoy off, nothing registers, so `runEnvoyChannelServer` stamps it once for the starting id (a `/clear` there leaves the new id unstamped); nothing is stamped when the session starts with Dispatch off or under `ENVOY_SESSION_ID`. |
|
|
129
129
|
| NATS topic consumer | `src/channel-topics.ts` | Dedupe through the shared `createDeliveryDedupe`: a re-send by its `dedupe_key` (never by `event_id` alone, which the listener mints fresh for every send, so a Dispatch Retry would pass as new), and a second copy of one publish arriving on overlapping subscriptions by its `event_id`; surface the envelope's topic, and drain safely at shutdown. The promise the dedupe keeps is stated on `DELIVERY_DUPLICATE_WINDOW_MS` in `packages/contracts`. |
|
|
130
130
|
| Consumer delivery | `src/envoy-channel-server.ts` (`openRelay`, `deliverRelayed`, `renewRelayEpoch`), `src/replay-state.ts` (the `consumer` part of `replay-<session id>.json`), `../envoy-client/src/consumer-delivery.ts`, `../../scripts/e2e/envoy-session-delivery.sh` | The listener's relay of the session's durable consumer ("Overview"): the relay subscription and epoch, each frame's `received`, `done` and `nak`, and the persisted resume point. The repository's `scripts/e2e/envoy-session-delivery.sh` is the live proof under `legion claude-bridge` (`scripts/e2e/README.md`). |
|
|
131
|
-
| Outbound transport | `
|
|
131
|
+
| Outbound transport | `bin/envoy-send.ts` | `envoy-send` sends through `@legion/envoy-client`'s `createEnvoyClient(...).send`, the transport every other client uses, to the listener and with the bearer `envoySettings` resolves over the envoy.json `envoyConfigPath("command")` chooses. It names its shell's session as `source_session`, so the listener's limit on each session's sending counts it; a refusal prints the listener's own sentence and exits 1, and the message is not sent again. |
|
|
132
132
|
| Send CLI parsing | `src/send-arguments.ts` | Validates destination and message arguments. |
|
|
133
133
|
| Manual `/clear` smoke | `scripts/smoke-clear-rebind.sh` | Real `/clear` against the live listener with the build in `CLAUDE_PLUGIN_DIR` (default: a `--out` build of this tree in the smoke's scratch directory); checks the registry entry moves to the new id without the old direct subject. Sends no prompt to the model; excluded from CI. |
|
|
134
134
|
| Manual session-title smoke | `scripts/smoke-session-title.sh` | Real nats-server, a listener built from this tree, and the `dist/` of its own `--out` build of this tree for both the hook and the channel server: a chosen name registers, a rename replaces it, taking the name away restores the folder-and-short-id fallback, and the `dispatch` command's stamp carries the same name, each read back through the listener's `GET /v1/sessions`; the base revision's committed bundle is the negative control. Claude Code is not installed in an issue pod's image, though it runs there from `bunx --package @anthropic-ai/claude-code@<version> claude`, as `scripts/e2e/envoy-session-delivery.sh` runs it; this smoke writes the two hook payloads to their documented shape instead. Excluded from CI. |
|
package/README.md
CHANGED
|
@@ -170,11 +170,17 @@ message from Dispatch's Agents page as that person's own turn.
|
|
|
170
170
|
summary (the same shape as OMP on fork). `ENVOY_SESSION_ID` (QA override) disables the handoff.
|
|
171
171
|
- `envoy_inbox` is local recovery state: the most recent 50 event summaries, with no envelope
|
|
172
172
|
body, ordered newest first.
|
|
173
|
-
- `bin/envoy-send.ts` sends direct messages through
|
|
174
|
-
and with the bearer a command resolves:
|
|
175
|
-
`envoyConfigPath("command")` chooses (the `ENVOY_CONFIG_FILE`
|
|
176
|
-
session's Bash first), with `ENVOY_URL` and `ENVOY_TOKEN_FILE` or
|
|
177
|
-
|
|
173
|
+
- `bin/envoy-send.ts` sends direct messages through `@legion/envoy-client`'s `send`, the
|
|
174
|
+
transport every other client uses, to the listener and with the bearer a command resolves:
|
|
175
|
+
`envoySettings` over the envoy.json `envoyConfigPath("command")` chooses (the `ENVOY_CONFIG_FILE`
|
|
176
|
+
the `open-asks` hook hands the session's Bash first), with `ENVOY_URL` and `ENVOY_TOKEN_FILE` or
|
|
177
|
+
`ENVOY_TOKEN` over its `envoy` section. It sends the session its shell names
|
|
178
|
+
(`ENVOY_SESSION_ID`, else `CLAUDE_CODE_SESSION_ID`) as `source_session`, so the listener's limit
|
|
179
|
+
on each session's sending counts its messages. After no answer or a 5xx it sends the message
|
|
180
|
+
once more under the same idempotency key, and Envoy drops that copy as a repeat. A refusal, one
|
|
181
|
+
for the sender's rate among them, prints the listener's own sentence after
|
|
182
|
+
`Claude Envoy send failed: `, exits 1 and is not sent again. With Envoy off it sends nothing and
|
|
183
|
+
exits 1, saying why.
|
|
178
184
|
|
|
179
185
|
## What a delivered line carries
|
|
180
186
|
|
|
@@ -200,6 +206,9 @@ The server exposes the shared Envoy messaging contract, every tool of `envoyTool
|
|
|
200
206
|
`envoy_*` tools, `envoy_inbox` and `envoy_role_get` among them, and `slack_post`, a reply in a Slack
|
|
201
207
|
thread. It exposes no Dispatch tool: a `dispatch_*` call is an unknown
|
|
202
208
|
tool.
|
|
209
|
+
A tool that fails answers a tool result with `isError: true` whose text is the error, so the model
|
|
210
|
+
reads the listener's own sentence for a refused send or publish, a refusal for the sender's rate
|
|
211
|
+
among them. An unknown tool, and a call before the server has started, answer a JSON-RPC error.
|
|
203
212
|
|
|
204
213
|
## Dispatch
|
|
205
214
|
|
package/bin/envoy-send.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { messageFor } from "@legion/envoy-client/errors"
|
|
2
2
|
import { sessionConfigFile, sessionEnvoySettings } from "@legion/envoy-client/session-settings"
|
|
3
|
+
import { createEnvoyClient } from "@legion/envoy-client/transport"
|
|
3
4
|
import { configuredSessionId } from "../src/claude-session"
|
|
4
|
-
import { sendEnvoyMessage } from "../src/envoy-client"
|
|
5
5
|
import { parseSendArguments } from "../src/send-arguments"
|
|
6
6
|
|
|
7
7
|
try {
|
|
@@ -20,10 +20,13 @@ try {
|
|
|
20
20
|
...(session === undefined ? {} : { session }),
|
|
21
21
|
})
|
|
22
22
|
if (!envoy.enabled) throw new Error(`Envoy is off: ${envoy.error ?? envoy.notice}`)
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
23
|
+
// The transport every other client sends through. It names this session as the message's
|
|
24
|
+
// source, so the listener counts the message against this session's sending limit; a shell that
|
|
25
|
+
// names no session sends a blank one, which the transport leaves off the wire. A refusal is an
|
|
26
|
+
// `EnvoyApiError` whose message is the listener's own sentence, which the catch below prints.
|
|
27
|
+
await createEnvoyClient({ baseUrl: envoy.url, credential: envoy.credential, fetch }).send({
|
|
28
|
+
sourceSessionID: session ?? "",
|
|
29
|
+
targetSessionID: targetSession,
|
|
27
30
|
message,
|
|
28
31
|
})
|
|
29
32
|
process.stdout.write(`Sent Envoy message to ${targetSession}.\n`)
|
package/dist/dispatch.js
CHANGED
|
@@ -30657,7 +30657,8 @@ var ErrorWireSchema = object({
|
|
|
30657
30657
|
holder: string2().optional(),
|
|
30658
30658
|
holder_state: SessionStateSchema.optional(),
|
|
30659
30659
|
last_seen: number2().int().optional(),
|
|
30660
|
-
claim_released: boolean2().optional()
|
|
30660
|
+
claim_released: boolean2().optional(),
|
|
30661
|
+
retry_after_seconds: number2().int().positive().optional()
|
|
30661
30662
|
});
|
|
30662
30663
|
var EnvelopeResponseSchema = EnvelopeSchema.extend({
|
|
30663
30664
|
recipient: string2().optional(),
|
|
@@ -30766,6 +30767,7 @@ class EnvoyApiError extends Error {
|
|
|
30766
30767
|
sessionState;
|
|
30767
30768
|
lastSeen;
|
|
30768
30769
|
claimReleased;
|
|
30770
|
+
retryAfterSeconds;
|
|
30769
30771
|
constructor(details) {
|
|
30770
30772
|
let parsed;
|
|
30771
30773
|
try {
|
|
@@ -30782,6 +30784,7 @@ class EnvoyApiError extends Error {
|
|
|
30782
30784
|
this.sessionState = parsed?.holder_state ?? parsed?.state;
|
|
30783
30785
|
this.lastSeen = parsed?.last_seen;
|
|
30784
30786
|
this.claimReleased = parsed?.claim_released;
|
|
30787
|
+
this.retryAfterSeconds = parsed?.retry_after_seconds;
|
|
30785
30788
|
}
|
|
30786
30789
|
}
|
|
30787
30790
|
var mintedDedupeKey2 = new RegExp(MINTED_DEDUPE_KEY_PATTERN);
|
package/dist/envoy-channel.js
CHANGED
|
@@ -46446,7 +46446,8 @@ var ErrorWireSchema = object({
|
|
|
46446
46446
|
holder: string2().optional(),
|
|
46447
46447
|
holder_state: SessionStateSchema.optional(),
|
|
46448
46448
|
last_seen: number2().int().optional(),
|
|
46449
|
-
claim_released: boolean2().optional()
|
|
46449
|
+
claim_released: boolean2().optional(),
|
|
46450
|
+
retry_after_seconds: number2().int().positive().optional()
|
|
46450
46451
|
});
|
|
46451
46452
|
var EnvelopeResponseSchema = EnvelopeSchema.extend({
|
|
46452
46453
|
recipient: string2().optional(),
|
|
@@ -46555,6 +46556,7 @@ class EnvoyApiError extends Error {
|
|
|
46555
46556
|
sessionState;
|
|
46556
46557
|
lastSeen;
|
|
46557
46558
|
claimReleased;
|
|
46559
|
+
retryAfterSeconds;
|
|
46558
46560
|
constructor(details) {
|
|
46559
46561
|
let parsed;
|
|
46560
46562
|
try {
|
|
@@ -46571,6 +46573,7 @@ class EnvoyApiError extends Error {
|
|
|
46571
46573
|
this.sessionState = parsed?.holder_state ?? parsed?.state;
|
|
46572
46574
|
this.lastSeen = parsed?.last_seen;
|
|
46573
46575
|
this.claimReleased = parsed?.claim_released;
|
|
46576
|
+
this.retryAfterSeconds = parsed?.retry_after_seconds;
|
|
46574
46577
|
}
|
|
46575
46578
|
}
|
|
46576
46579
|
var mintedDedupeKey2 = new RegExp(MINTED_DEDUPE_KEY_PATTERN);
|
|
@@ -57732,7 +57735,7 @@ var import_nats2 = __toESM(require_mod4(), 1);
|
|
|
57732
57735
|
|
|
57733
57736
|
// package.json
|
|
57734
57737
|
var name = "@sjawhar/claude-envoy";
|
|
57735
|
-
var version2 = "2.
|
|
57738
|
+
var version2 = "2.45.1";
|
|
57736
57739
|
var legion = {
|
|
57737
57740
|
daemonApiVersion: 152
|
|
57738
57741
|
};
|
|
@@ -62514,7 +62517,13 @@ async function runEnvoyChannelServer() {
|
|
|
62514
62517
|
}
|
|
62515
62518
|
if (runtime === undefined)
|
|
62516
62519
|
throw new Error("Envoy channel server is still starting");
|
|
62517
|
-
|
|
62520
|
+
try {
|
|
62521
|
+
return mcpResult(await executeEnvoyTool(runtime, request.params.name, request.params.arguments));
|
|
62522
|
+
} catch (error) {
|
|
62523
|
+
if (error instanceof UnsupportedEnvoyToolError)
|
|
62524
|
+
throw error;
|
|
62525
|
+
return { content: [{ type: "text", text: messageFor(error) }], isError: true };
|
|
62526
|
+
}
|
|
62518
62527
|
});
|
|
62519
62528
|
let modLink;
|
|
62520
62529
|
const linked = Promise.withResolvers();
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sjawhar/claude-envoy",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.45.1",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"description": "Claude Code plugin for Legion's Envoy bus",
|
|
6
6
|
"type": "module",
|
|
@@ -42,7 +42,6 @@
|
|
|
42
42
|
"@legion/test-fixtures": "0.1.0",
|
|
43
43
|
"@modelcontextprotocol/sdk": "^1.30.0",
|
|
44
44
|
"bun-types": "latest",
|
|
45
|
-
"ky": "^2.0.2",
|
|
46
45
|
"nats": "^2.29.2",
|
|
47
46
|
"typescript": "^5.3.0",
|
|
48
47
|
"zod": "4.3.6"
|
|
@@ -2145,7 +2145,18 @@ export async function runEnvoyChannelServer(): Promise<void> {
|
|
|
2145
2145
|
return mcpResult(answer)
|
|
2146
2146
|
}
|
|
2147
2147
|
if (runtime === undefined) throw new Error("Envoy channel server is still starting")
|
|
2148
|
-
|
|
2148
|
+
try {
|
|
2149
|
+
return mcpResult(
|
|
2150
|
+
await executeEnvoyTool(runtime, request.params.name, request.params.arguments),
|
|
2151
|
+
)
|
|
2152
|
+
} catch (error) {
|
|
2153
|
+
// A tool that ran and failed answers a tool result with `isError`, which the model reads as
|
|
2154
|
+
// the tool's answer: the listener's own sentence, a refusal for this session's sending rate
|
|
2155
|
+
// among them. A tool this server does not have stays the JSON-RPC error it always was, since
|
|
2156
|
+
// MCP lists an unknown tool among the protocol's errors, not a tool's.
|
|
2157
|
+
if (error instanceof UnsupportedEnvoyToolError) throw error
|
|
2158
|
+
return { content: [{ type: "text", text: messageFor(error) }], isError: true }
|
|
2159
|
+
}
|
|
2149
2160
|
})
|
|
2150
2161
|
// INFRA-1026: the link to this session's Claude Code mod, bound below once the MCP transport is
|
|
2151
2162
|
// up. It is this process's own socket, closed with the server. `linked` resolves with it for
|
package/src/envoy-client.ts
DELETED
|
@@ -1,41 +0,0 @@
|
|
|
1
|
-
import type { RequestCredential } from "@legion/envoy-client/bearer"
|
|
2
|
-
import ky from "ky"
|
|
3
|
-
|
|
4
|
-
/** How long one send may take, the credential's trade included. */
|
|
5
|
-
const SEND_TIMEOUT_MS = 5_000
|
|
6
|
-
|
|
7
|
-
export type SendEnvoyMessageOptions = {
|
|
8
|
-
readonly baseUrl: string
|
|
9
|
-
/** What the send presents (`EnabledEnvoySettings.credential`): the listener's bearer, this
|
|
10
|
-
* machine's broker credential, which signs a DPoP proof for this request, or none, which
|
|
11
|
-
* sends no `Authorization` header, for a loopback listener that asks for none. */
|
|
12
|
-
readonly credential: RequestCredential | undefined
|
|
13
|
-
readonly targetSession: string
|
|
14
|
-
readonly message: string
|
|
15
|
-
/** Ends the send early, beside its own {@link SEND_TIMEOUT_MS}. */
|
|
16
|
-
readonly signal?: AbortSignal | undefined
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
/**
|
|
20
|
-
* Sends one direct message. One deadline bounds the whole send, and the credential is given it
|
|
21
|
-
* too (`RequestCredential.headers`): a broker credential waiting on a pod's missing registration
|
|
22
|
-
* stops at it, naming the session, while its trade goes on in the background.
|
|
23
|
-
*/
|
|
24
|
-
export async function sendEnvoyMessage(options: SendEnvoyMessageOptions): Promise<void> {
|
|
25
|
-
const url = new URL("/v1/messages/send", options.baseUrl)
|
|
26
|
-
const timeout = AbortSignal.timeout(SEND_TIMEOUT_MS)
|
|
27
|
-
const deadline =
|
|
28
|
-
options.signal === undefined ? timeout : AbortSignal.any([options.signal, timeout])
|
|
29
|
-
const headers =
|
|
30
|
-
(await options.credential?.headers("POST", url.toString(), undefined, deadline)) ?? {}
|
|
31
|
-
await ky.post(url, {
|
|
32
|
-
json: {
|
|
33
|
-
target_session: options.targetSession,
|
|
34
|
-
message: options.message,
|
|
35
|
-
},
|
|
36
|
-
headers,
|
|
37
|
-
retry: 0,
|
|
38
|
-
timeout: false,
|
|
39
|
-
signal: deadline,
|
|
40
|
-
})
|
|
41
|
-
}
|