@sjawhar/claude-envoy 4.6.0 → 4.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,111 @@
1
+ import type { RequestCredential } from "@legion/envoy-client/bearer"
2
+ import { createEnvoyClient } from "@legion/envoy-client/transport"
3
+
4
+ export type SendEnvoyMessageOptions = {
5
+ readonly baseUrl: string
6
+ /** What the send presents (`EnabledEnvoySettings.credential`): the listener's bearer, this
7
+ * machine's broker credential, which signs a DPoP proof for this request, or none, which
8
+ * sends no `Authorization` header, for a loopback listener that asks for none. */
9
+ readonly credential: RequestCredential | undefined
10
+ /** The session the shell names, which the message goes from (`source_session`), so the
11
+ * listener counts it against that session's sending limit; "" for a shell that names none,
12
+ * which the transport leaves off the wire. */
13
+ readonly sourceSession?: string
14
+ readonly targetSession: string
15
+ readonly message: string
16
+ /** The key the send goes under: the one an unconfirmed send named, to resend it safely. One is
17
+ * minted where none is given. */
18
+ readonly idempotencyKey?: string
19
+ }
20
+
21
+ /** What a stored send went without. */
22
+ export type SentEnvoyMessage = {
23
+ /**
24
+ * Why the send went without its credential: the very error the credential's `headers` threw
25
+ * for the attempt the listener stored, which a listener that asks for no credential stores as
26
+ * it stores any. Undefined where that attempt carried the credential, an attempt before it that
27
+ * went without included, and where the send was handed none to carry.
28
+ */
29
+ readonly withoutCredential: unknown
30
+ }
31
+
32
+ /**
33
+ * `credential`, every member of it as it is, with the outcome of its last `headers` kept: the
34
+ * error it threw or rejected with, rethrown unchanged, or none where it answered headers. A
35
+ * bearer's headers still come at once, and a broker credential's as its promise settles.
36
+ */
37
+ function recorded(credential: RequestCredential): {
38
+ readonly credential: RequestCredential
39
+ readonly lastFailure: () => unknown
40
+ } {
41
+ let failure: unknown
42
+ const answered = (headers: Readonly<Record<string, string>>) => {
43
+ failure = undefined
44
+ return headers
45
+ }
46
+ const failed = (error: unknown): never => {
47
+ failure = error
48
+ throw error
49
+ }
50
+ return {
51
+ credential: {
52
+ scheme: credential.scheme,
53
+ headers: (method, url, session, signal) => {
54
+ try {
55
+ const ready = credential.headers(method, url, session, signal)
56
+ return ready instanceof Promise ? ready.then(answered, failed) : answered(ready)
57
+ } catch (error) {
58
+ return failed(error)
59
+ }
60
+ },
61
+ ...(credential.stale === undefined
62
+ ? {}
63
+ : { stale: (session, presented) => credential.stale?.(session, presented) }),
64
+ ...(credential.identity === undefined
65
+ ? {}
66
+ : { identity: (presented) => credential.identity?.(presented) }),
67
+ secret: () => credential.secret(),
68
+ },
69
+ lastFailure: () => failure,
70
+ }
71
+ }
72
+
73
+ /**
74
+ * Sends one direct message through envoy-client's own send (`createEnvoyClient().send`), so the
75
+ * `envoy-send` command keeps every rule a session's own send keeps:
76
+ * - one idempotency key for the message, on every attempt, so the listener stores it at most
77
+ * once however many attempts reach it;
78
+ * - an attempt that got no answer or a 5xx is sent again under that key, after 250 ms;
79
+ * - a send that may have arrived is told so (`EnvoySendUnconfirmedError`), naming the key that
80
+ * resends it safely, never "failed";
81
+ * - each attempt's credential waits the attempt less the request's reserve
82
+ * (`credentialDeadline`), and a credential that could not be minted lets the request go
83
+ * without it, which a listener that asks for no credential answers. A listener that wants one
84
+ * answers 401 at its auth gate, and the error names both halves and no resend, since nothing
85
+ * was stored.
86
+ *
87
+ * A stored send answers what it went without (`SentEnvoyMessage`), so the command can say so: a
88
+ * sign-in revoked for good is stored without the credential by a listener that asks for none, and
89
+ * nothing else would tell the person.
90
+ */
91
+ export async function sendEnvoyMessage(
92
+ options: SendEnvoyMessageOptions,
93
+ ): Promise<SentEnvoyMessage> {
94
+ const kept = options.credential === undefined ? undefined : recorded(options.credential)
95
+ const client = createEnvoyClient({
96
+ baseUrl: options.baseUrl,
97
+ fetch: globalThis.fetch,
98
+ credential: kept?.credential,
99
+ })
100
+ // The shell's session as the message's source, so the listener counts the message against that
101
+ // session's sending limit; a shell that names no session sends a blank one, which the transport
102
+ // leaves off the wire. A refusal is an `EnvoyApiError` whose message is the listener's own
103
+ // sentence, which `envoy-send` prints.
104
+ await client.send({
105
+ sourceSessionID: options.sourceSession ?? "",
106
+ targetSessionID: options.targetSession,
107
+ message: options.message,
108
+ ...(options.idempotencyKey === undefined ? {} : { idempotencyKey: options.idempotencyKey }),
109
+ })
110
+ return { withoutCredential: kept?.lastFailure() }
111
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Ends the channel server's process with `code` once everything already written to stdout and
3
+ * stderr has reached the pipe: an MCP reply Claude Code reads on stdout, or the failure line on
4
+ * stderr. A handle nothing will use can outlive the run (a NATS dial that a stop ended waits out
5
+ * nats.js's own dial timeout), so the process ends here rather than when that handle lets go; but
6
+ * `process.exit` drops what Bun still holds for a full pipe, and in Bun a write's callback, and
7
+ * `drain`, come before the bytes leave. Ending each stream is what waits: its callback runs once
8
+ * the pipe has taken every byte, however slow the reader.
9
+ */
10
+ export async function exitProcess(code: number): Promise<never> {
11
+ await Promise.all([ended(process.stdout), ended(process.stderr)])
12
+ process.exit(code)
13
+ }
14
+
15
+ /** Ends `stream` and settles once every byte written to it has been handed on, or it failed. */
16
+ function ended(stream: NodeJS.WriteStream): Promise<void> {
17
+ return new Promise((settle) => {
18
+ if (stream.destroyed || stream.writableFinished) return settle()
19
+ // A reader gone (EPIPE) fails the stream: nothing is left to wait for.
20
+ stream.once("error", () => settle())
21
+ stream.end(() => settle())
22
+ })
23
+ }
@@ -1,13 +1,102 @@
1
+ import { isCleanUrl } from "@legion/contracts/log-text"
1
2
  import { z } from "zod"
2
3
 
3
4
  const SendArgumentsSchema = z.tuple([z.string().min(1), z.string().min(1)]).rest(z.string().min(1))
4
5
 
6
+ /** The flag that sends a message under a key the caller names: the one an unconfirmed send
7
+ * printed, so the listener drops the resend as a repeat if the first copy arrived. */
8
+ export const IDEMPOTENCY_KEY_FLAG = "--idempotency-key"
9
+
5
10
  export type SendArguments = {
6
11
  readonly targetSession: string
7
12
  readonly message: string
13
+ /** The key the send goes under, where the caller names one; one is minted otherwise. */
14
+ readonly idempotencyKey?: string
8
15
  }
9
16
 
17
+ /**
18
+ * `[--idempotency-key <key>] <target session> <message words…>`. The flag comes first, so a
19
+ * message whose words begin with it is still a message.
20
+ */
10
21
  export function parseSendArguments(arguments_: readonly string[]): SendArguments {
11
- const [targetSession, ...words] = SendArgumentsSchema.parse(arguments_)
12
- return { targetSession, message: words.join(" ") }
22
+ let rest = arguments_
23
+ let idempotencyKey: string | undefined
24
+ if (rest[0] === IDEMPOTENCY_KEY_FLAG) {
25
+ idempotencyKey = z.string().min(1).parse(rest[1])
26
+ rest = rest.slice(2)
27
+ }
28
+ const [targetSession, ...words] = SendArgumentsSchema.parse(rest)
29
+ return {
30
+ targetSession,
31
+ message: words.join(" "),
32
+ ...(idempotencyKey === undefined ? {} : { idempotencyKey }),
33
+ }
34
+ }
35
+
36
+ /**
37
+ * `value` as one word of a POSIX shell command that bash and zsh both read as the same text:
38
+ * bare where every character is one neither shell expands, single-quoted otherwise, with each `'`
39
+ * closed, escaped and reopened. A leading `=` is quoted too: zsh's EQUALS option, on by default,
40
+ * reads a bare `=word` as the path of the command `word`.
41
+ */
42
+ export function shellWord(value: string): string {
43
+ return /^[A-Za-z0-9_./:@%+-][A-Za-z0-9_./:=@%+-]*$/.test(value)
44
+ ? value
45
+ : `'${value.replaceAll("'", "'\\''")}'`
46
+ }
47
+
48
+ /** What the resend command an unconfirmed send prints is built of. */
49
+ export interface Resend {
50
+ /** The command's own script (`bun <script>`). */
51
+ readonly script: string
52
+ /** The directory the send ran in: a checkout's own `.envoy/envoy.json` is read from it. */
53
+ readonly cwd: string
54
+ /**
55
+ * The settings, by name and value, that chose the send's listener and credential (the envoy.json
56
+ * it read, `ENVOY_URL`, `ENVOY_TOKEN_FILE`, the session): each is carried as `NAME=value` ahead
57
+ * of the command, so the resend goes where the send went from any shell it is run in.
58
+ */
59
+ readonly settings: readonly (readonly [name: string, value: string])[]
60
+ readonly idempotencyKey: string
61
+ readonly targetSession: string
62
+ readonly message: string
63
+ }
64
+
65
+ /**
66
+ * What an unconfirmed send prints of its resend: the command, or, where a setting it carries is a
67
+ * URL no printed line may name, that setting's name and no command.
68
+ */
69
+ export type ResendCommand = { readonly command: string } | { readonly unprinted: string }
70
+
71
+ /** Whether `name` names a URL setting (`ENVOY_URL`), which prints only as `isCleanUrl` allows. */
72
+ const URL_SETTING = /_URL$/
73
+
74
+ /**
75
+ * The command that sends the same message again under its key, to the same listener, as
76
+ * `envoy-send` was run: `cd <cwd> && NAME=value … bun <script> --idempotency-key <key> <target>
77
+ * <message>`. The listener drops it as a repeat if the first copy arrived.
78
+ *
79
+ * A URL setting is printed only where it is a plain http(s) URL with no place a credential can sit
80
+ * (`isCleanUrl`, `@legion/contracts/log-text`), the one rule every client names a configured URL
81
+ * by. Where one is not, such as a URL with user info of any length, no command is built, only the
82
+ * setting's name (`unprinted`): the scrub of held secrets takes out a held value of 10 characters
83
+ * or more, so a shorter user and password would print whole, and the URL with its user info taken
84
+ * out could still print part of it, since the parser can split such a URL otherwise than its
85
+ * writer meant (`https://user:p@ssw0rd` reads `ssw0rd` as the host).
86
+ */
87
+ export function resendCommand(resend: Resend): ResendCommand {
88
+ const unclean = resend.settings.find(
89
+ ([name, value]) => URL_SETTING.test(name) && !isCleanUrl(value),
90
+ )
91
+ if (unclean !== undefined) return { unprinted: unclean[0] }
92
+ const assignments = resend.settings.map(([name, value]) => `${name}=${shellWord(value)}`)
93
+ const command = [
94
+ "bun",
95
+ resend.script,
96
+ IDEMPOTENCY_KEY_FLAG,
97
+ resend.idempotencyKey,
98
+ resend.targetSession,
99
+ resend.message,
100
+ ].map(shellWord)
101
+ return { command: `cd ${shellWord(resend.cwd)} && ${[...assignments, ...command].join(" ")}` }
13
102
  }