@sjawhar/claude-envoy 4.6.1 → 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.
@@ -1,4 +1,207 @@
1
1
  // @bun
2
+ // ../contracts/src/held-secrets.ts
3
+ var WITHHELD = "<withheld>";
4
+ var SCRUB_RUN = 10;
5
+ var SHORTEST_HELD = SCRUB_RUN;
6
+ var HELD_PAST_LAPSE_MS = 60 * 60000;
7
+ var KEY = Symbol.for("@legion/contracts/held-secrets");
8
+ function held() {
9
+ const global = globalThis;
10
+ global[KEY] ??= { values: new Set, windows: new Set, forgets: new Map };
11
+ return global[KEY];
12
+ }
13
+ function addWindows(windows, value) {
14
+ for (let at = 0;at + SCRUB_RUN <= value.length; at += 1) {
15
+ windows.add(value.slice(at, at + SCRUB_RUN));
16
+ }
17
+ }
18
+ function forgetLapsed(registry, now) {
19
+ let forgot = false;
20
+ for (const [value, at] of registry.forgets) {
21
+ if (at > now)
22
+ continue;
23
+ registry.forgets.delete(value);
24
+ registry.values.delete(value);
25
+ forgot = true;
26
+ }
27
+ if (!forgot)
28
+ return;
29
+ registry.windows.clear();
30
+ for (const value of registry.values)
31
+ addWindows(registry.windows, value);
32
+ }
33
+ function holdSecret(value, lapsesAt) {
34
+ if (value.length < SHORTEST_HELD)
35
+ return value;
36
+ const registry = held();
37
+ forgetLapsed(registry, Date.now());
38
+ const forgetAt = lapsesAt === undefined ? undefined : Number(lapsesAt) + HELD_PAST_LAPSE_MS;
39
+ if (registry.values.has(value)) {
40
+ const was = registry.forgets.get(value);
41
+ if (was === undefined)
42
+ return value;
43
+ if (forgetAt === undefined)
44
+ registry.forgets.delete(value);
45
+ else if (forgetAt > was)
46
+ registry.forgets.set(value, forgetAt);
47
+ return value;
48
+ }
49
+ registry.values.add(value);
50
+ if (forgetAt !== undefined)
51
+ registry.forgets.set(value, forgetAt);
52
+ addWindows(registry.windows, value);
53
+ return value;
54
+ }
55
+ function decoded(text) {
56
+ try {
57
+ return decodeURIComponent(text);
58
+ } catch {
59
+ return text;
60
+ }
61
+ }
62
+ function holdUrlUserinfo(url) {
63
+ let parsed;
64
+ try {
65
+ parsed = new URL(url);
66
+ } catch {
67
+ return url;
68
+ }
69
+ if (parsed.username === "" && parsed.password === "")
70
+ return url;
71
+ const user = decoded(parsed.username);
72
+ const password = decoded(parsed.password);
73
+ for (const value of [parsed.username, parsed.password, user, password])
74
+ holdSecret(value);
75
+ const pair = `${user}:${password}`;
76
+ holdSecret(pair);
77
+ holdSecret(btoa(String.fromCharCode(...new TextEncoder().encode(pair))));
78
+ return url;
79
+ }
80
+ function scrub(text) {
81
+ const { windows } = held();
82
+ if (windows.size === 0 || text.length < SCRUB_RUN)
83
+ return text;
84
+ const spans = [];
85
+ for (let at = 0;at + SCRUB_RUN <= text.length; at += 1) {
86
+ if (!windows.has(text.slice(at, at + SCRUB_RUN)))
87
+ continue;
88
+ const end = at + SCRUB_RUN;
89
+ const last = spans.at(-1);
90
+ if (last !== undefined && at <= last[1])
91
+ last[1] = end;
92
+ else
93
+ spans.push([at, end]);
94
+ }
95
+ if (spans.length === 0)
96
+ return text;
97
+ let out = "";
98
+ let from = 0;
99
+ for (const [start, end] of spans) {
100
+ out += text.slice(from, start) + WITHHELD;
101
+ from = end;
102
+ }
103
+ return out + text.slice(from);
104
+ }
105
+ function scrubProcessStreams() {
106
+ for (const stream of [process.stdout, process.stderr]) {
107
+ const marked = stream;
108
+ if (marked[KEY])
109
+ continue;
110
+ marked[KEY] = true;
111
+ const write = stream.write.bind(stream);
112
+ stream.write = (chunk, ...rest) => {
113
+ if (typeof chunk === "string")
114
+ return write(scrub(chunk), ...rest);
115
+ if (chunk instanceof Uint8Array) {
116
+ const text = new TextDecoder().decode(chunk);
117
+ const scrubbed = scrub(text);
118
+ return write(scrubbed === text ? chunk : scrubbed, ...rest);
119
+ }
120
+ return write(chunk, ...rest);
121
+ };
122
+ }
123
+ }
124
+
125
+ // ../contracts/src/log-text.ts
126
+ var URL_NOT_PRINTED = "(not printed: it carries a credential or is not a plain http(s) URL)";
127
+ function isCleanUrl(raw) {
128
+ for (let at = 0;at < raw.length; at += 1) {
129
+ const code = raw.charCodeAt(at);
130
+ if (code <= 32 || code >= 127 || `@%?#\\`.includes(raw[at] ?? ""))
131
+ return false;
132
+ }
133
+ const scheme = /^(https?):\/\//i.exec(raw);
134
+ if (scheme === null || !URL.canParse(raw))
135
+ return false;
136
+ const rest = raw.slice(scheme[0].length);
137
+ const slash = rest.indexOf("/");
138
+ const hostPort = slash < 0 ? rest : rest.slice(0, slash);
139
+ const path = slash < 0 ? "" : rest.slice(slash);
140
+ return isHostPort(hostPort) && /^[A-Za-z0-9._~/-]*$/.test(path);
141
+ }
142
+ function isHostPort(hostPort) {
143
+ let host = hostPort;
144
+ let port;
145
+ if (hostPort.startsWith("[")) {
146
+ const end = hostPort.indexOf("]");
147
+ if (end < 0)
148
+ return false;
149
+ host = hostPort.slice(1, end);
150
+ const after = hostPort.slice(end + 1);
151
+ if (after !== "") {
152
+ if (!after.startsWith(":"))
153
+ return false;
154
+ port = after.slice(1);
155
+ }
156
+ if (!/^[0-9A-Fa-f:.]+$/.test(host) || !URL.canParse(`http://[${host}]`))
157
+ return false;
158
+ } else {
159
+ const colon = hostPort.indexOf(":");
160
+ if (colon >= 0) {
161
+ host = hostPort.slice(0, colon);
162
+ port = hostPort.slice(colon + 1);
163
+ }
164
+ if (!isDnsName(host))
165
+ return false;
166
+ }
167
+ return port === undefined || /^[0-9]{1,5}$/.test(port);
168
+ }
169
+ function isDnsName(name) {
170
+ if (name === "" || name.length > 253)
171
+ return false;
172
+ return name.split(".").every((label) => /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$/.test(label));
173
+ }
174
+ function urlForText(url, setting) {
175
+ return isCleanUrl(url) ? url : `${setting} ${URL_NOT_PRINTED}`;
176
+ }
177
+ function requestForText(base, requestUrl, setting) {
178
+ if (!isCleanUrl(base))
179
+ return `${setting} ${URL_NOT_PRINTED}`;
180
+ const head = requestUrl.slice(0, base.length);
181
+ const rest = requestUrl.slice(base.length);
182
+ const follows = rest === "" || base.endsWith("/") || rest.startsWith("/") || rest.startsWith("?");
183
+ if (head.toLowerCase() !== base.toLowerCase() || !follows)
184
+ return `${setting} ${URL_NOT_PRINTED}`;
185
+ return `${base}${rest}`;
186
+ }
187
+ function isHttpUrl(value) {
188
+ if (!URL.canParse(value))
189
+ return false;
190
+ const { protocol } = new URL(value);
191
+ return protocol === "http:" || protocol === "https:";
192
+ }
193
+ var ERROR_CODE = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;
194
+ var SYSCALL = /^[a-z]+$/;
195
+ var ERROR_NAME = /^[A-Za-z]+$/;
196
+ function errorClass(error) {
197
+ if (!(error instanceof Error))
198
+ return `a thrown ${typeof error} (message withheld)`;
199
+ const { code, syscall } = error;
200
+ if (typeof code === "string" && ERROR_CODE.test(code))
201
+ return typeof syscall === "string" && SYSCALL.test(syscall) ? `${syscall} ${code}` : code;
202
+ return `${ERROR_NAME.test(error.name) ? error.name : "Error"} (message withheld)`;
203
+ }
204
+
2
205
  // ../envoy-client/src/errors.ts
3
206
  function dispatchCode(error) {
4
207
  if (!("fromDispatch" in error) || !("code" in error))
@@ -8,26 +211,56 @@ function dispatchCode(error) {
8
211
  }
9
212
  function messageFor(error) {
10
213
  if (!(error instanceof Error))
11
- return String(error);
214
+ return scrub(String(error));
12
215
  const code = dispatchCode(error);
13
- return code === undefined || error.message.startsWith(code) ? error.message : `${code}: ${error.message}`;
216
+ return scrub(code === undefined || error.message.startsWith(code) ? error.message : `${code}: ${error.message}`);
14
217
  }
15
218
  function hasErrnoCode(error, code) {
16
219
  return error instanceof Error && "code" in error && error.code === code;
17
220
  }
18
- function withoutUserinfo(url) {
19
- let parsed;
20
- try {
21
- parsed = new URL(url);
22
- } catch {
23
- return url.slice(url.lastIndexOf("@") + 1);
221
+ var NOT_CONNECTED = new Set(["ECONNREFUSED", "EHOSTUNREACH", "ENETUNREACH"]);
222
+ function reachedNothing(error) {
223
+ if (!(error instanceof Error))
224
+ return false;
225
+ const { code, syscall } = error;
226
+ return syscall === "getaddrinfo" || typeof code === "string" && NOT_CONNECTED.has(code);
227
+ }
228
+
229
+ class LoggableError extends Error {
230
+ constructor(message) {
231
+ super(message);
24
232
  }
25
- if (parsed.username === "" && parsed.password === "")
26
- return url;
27
- parsed.username = "";
28
- parsed.password = "";
29
- const shown = parsed.toString();
30
- return shown.endsWith("/") && !url.endsWith("/") ? shown.slice(0, -1) : shown;
233
+ }
234
+ var SERVER_REFUSALS = [
235
+ "Authorization Violation",
236
+ "User Authentication Expired",
237
+ "Account Authentication Expired",
238
+ "Authentication Timeout"
239
+ ];
240
+ var SERVER_ERROR_CODES = {
241
+ AUTHORIZATION_VIOLATION: true,
242
+ AUTHENTICATION_EXPIRED: true,
243
+ AUTHENTICATION_TIMEOUT: true,
244
+ ACCOUNT_EXPIRED: true,
245
+ PERMISSIONS_VIOLATION: true,
246
+ NATS_PROTOCOL_ERR: true
247
+ };
248
+ function serverText(code, text) {
249
+ const said = text.trim().replace(/^'(.*)'$/s, "$1").trim().toLowerCase();
250
+ const refusal = SERVER_REFUSALS.find((fixed) => fixed.toLowerCase() === said);
251
+ if (refusal !== undefined)
252
+ return refusal;
253
+ return code === "PERMISSIONS_VIOLATION" ? "the server refused a permission (its text is withheld)" : "the server refused the connection (its text is withheld)";
254
+ }
255
+ function natsFailureReason(error) {
256
+ if (error instanceof LoggableError)
257
+ return scrub(error.message);
258
+ if (error instanceof Error && error.name === "NatsError") {
259
+ const { code } = error;
260
+ if (typeof code === "string" && code !== "")
261
+ return SERVER_ERROR_CODES[code] === true ? serverText(code, error.message) : code;
262
+ }
263
+ return errorClass(error);
31
264
  }
32
265
 
33
266
  // src/session-state.ts
@@ -117,6 +350,7 @@ async function pruneStaleSessionTitles(stateDirectory) {
117
350
  }
118
351
 
119
352
  // hooks/session-title-hook.ts
353
+ scrubProcessStreams();
120
354
  function chosenTitlePayload(raw) {
121
355
  if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
122
356
  throw new Error(`expected a JSON object, received ${JSON.stringify(raw)}`);
@@ -88,7 +88,9 @@
88
88
 
89
89
  import { appendFileSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"
90
90
  import { join } from "node:path"
91
- import { formatOpenAsksSummary } from "@legion/envoy-client/dispatch-execute"
91
+ import { scrubProcessStreams } from "@legion/contracts/held-secrets"
92
+ import { urlForText } from "@legion/contracts/log-text"
93
+ import { formatOpenAsksSummary, linkBaseOf } from "@legion/envoy-client/dispatch-execute"
92
94
  import {
93
95
  dispatchFirstSkillFile,
94
96
  readDispatchFirstContext,
@@ -96,7 +98,7 @@ import {
96
98
  import { DispatchClient } from "@legion/envoy-client/dispatch-http"
97
99
  import { sessionDirectory, writeAtomically } from "@legion/envoy-client/dispatch-session-directory"
98
100
  import { offWithError } from "@legion/envoy-client/envoy-config"
99
- import { hasErrnoCode, messageFor, withoutUserinfo } from "@legion/envoy-client/errors"
101
+ import { hasErrnoCode, messageFor } from "@legion/envoy-client/errors"
100
102
  import {
101
103
  readSessionAnswers,
102
104
  SESSION_ANSWERS_DEADLINE_MS,
@@ -118,6 +120,10 @@ import { sessionHandoffFile, writeSessionHandoff } from "../src/session-identity
118
120
  import { recordChosenTitle } from "../src/session-state"
119
121
  import { parseHookArguments } from "./hook-arguments"
120
122
 
123
+ // Every line this hook writes, the context Claude Code hands the model on stdout included, passes
124
+ // the scrub of the secrets it holds (`@legion/contracts/held-secrets`).
125
+ scrubProcessStreams()
126
+
121
127
  const OPEN_ASKS_TIMEOUT_MS = 3_000
122
128
  const OpenAsksInput = z.object({
123
129
  session_id: z.string().min(1),
@@ -317,10 +323,10 @@ async function openAsks(raw: unknown): Promise<void> {
317
323
  if (dispatch.enabled) {
318
324
  try {
319
325
  const snapshot = await new DispatchClient(dispatch.url, dispatch.credential, fetch, {
320
- signal: AbortSignal.timeout(OPEN_ASKS_TIMEOUT_MS),
326
+ deadlineMs: OPEN_ASKS_TIMEOUT_MS,
321
327
  }).openAsks(input.session_id)
322
328
  process.stdout.write(
323
- `Dispatch authored-ask summary:\n${formatOpenAsksSummary(snapshot, dispatch.publicUrl ?? dispatch.url)}\n`,
329
+ `Dispatch authored-ask summary:\n${formatOpenAsksSummary(snapshot, linkBaseOf(dispatch.publicUrl ?? dispatch.url))}\n`,
324
330
  )
325
331
  } catch (error) {
326
332
  process.stdout.write(`Dispatch authored-ask summary unavailable: ${messageFor(error)}\n`)
@@ -460,10 +466,12 @@ async function refreshedAnswers(
460
466
  if (outcome.dispatch_url === dispatchUrl) {
461
467
  return { text: outcome.text ?? undefined, notice: outcome.notice ?? undefined }
462
468
  }
463
- // Compared whole above; the reason reaches the session's context, so it names the URL
464
- // without the user and password it may carry.
469
+ // Compared whole above; the reason reaches the session's context, so it names the URL only
470
+ // where it is a plain http(s) URL, and by a fixed phrase otherwise (`urlForText`).
465
471
  const read =
466
- outcome.dispatch_url === null ? "no Dispatch" : withoutUserinfo(outcome.dispatch_url)
472
+ outcome.dispatch_url === null
473
+ ? "no Dispatch"
474
+ : urlForText(outcome.dispatch_url, "another Dispatch URL")
467
475
  return {
468
476
  reason: `the refresher read ${read}, not the Dispatch envoy.json names now`,
469
477
  }
@@ -14,9 +14,13 @@
14
14
  // UserPromptSubmit hook's stdout to the model's context and reads its exit code 2 as a block of
15
15
  // the prompt, and a cosmetic title must do neither. A failure goes to stderr, which Claude Code
16
16
  // shows the user and the model never sees.
17
+ import { scrubProcessStreams } from "@legion/contracts/held-secrets"
17
18
  import { messageFor } from "@legion/envoy-client/errors"
18
19
  import { recordChosenTitle } from "../src/session-state"
19
20
 
21
+ // Every line this hook writes passes the scrub of the secrets it holds.
22
+ scrubProcessStreams()
23
+
20
24
  interface ChosenTitlePayload {
21
25
  readonly sessionId: string
22
26
  readonly title: string | undefined
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sjawhar/claude-envoy",
3
- "version": "4.6.1",
3
+ "version": "4.7.0",
4
4
  "license": "Apache-2.0",
5
5
  "description": "Claude Code plugin for Legion's Envoy bus",
6
6
  "type": "module",
@@ -36,6 +36,7 @@
36
36
  },
37
37
  "devDependencies": {
38
38
  "@biomejs/biome": "^2.3.14",
39
+ "@legion/broker-client": "0.1.0",
39
40
  "@legion/contracts": "0.10.0",
40
41
  "@legion/envoy-client": "0.1.0",
41
42
  "@legion/pi-shared": "0.1.0",
@@ -57,6 +57,14 @@ export interface AgentStreamOptions {
57
57
  * id names nothing Dispatch knows, so the stream stays where it started.
58
58
  */
59
59
  readonly followsSessionId: boolean
60
+ /**
61
+ * Settles once the session's NATS connection is admitted as `session`, where the connection is
62
+ * admitted as one session at a time: under its broker token a `/clear`'s new id is the
63
+ * connection's only once the move lands (`followSession`), and a subscribe before then is
64
+ * refused and closed by the server. Where this is absent the connection may take every id's
65
+ * subjects, and the new control subject is taken at once.
66
+ */
67
+ readonly admitted?: (session: string) => Promise<void>
60
68
  /** Whether this session is a Legion pane, whose first command the daemon's bridge writes
61
69
  * rather than a person (`./agent-stream-claude`, `PANE_SEEDED_COMMAND`). */
62
70
  readonly isPane?: boolean
@@ -292,7 +300,16 @@ export function startAgentStream(options: AgentStreamOptions): AgentStreamRunner
292
300
  // still holds, so they are put back under the new id rather than read again.
293
301
  publishSettings()
294
302
  publishCommands()
295
- subscribe()
303
+ // The old id's control subject goes at once, and the new id's is taken once the connection
304
+ // may take it (`AgentStreamOptions.admitted`): a later `/clear` before then takes its own.
305
+ subscription?.unsubscribe()
306
+ subscription = undefined
307
+ const admitted = options.admitted?.(next)
308
+ if (admitted === undefined) subscribe()
309
+ else
310
+ void admitted.then(() => {
311
+ if (!stopped && session === next) subscribe()
312
+ })
296
313
  })
297
314
 
298
315
  const reading = (async (): Promise<void> => {
@@ -1,6 +1,6 @@
1
1
  import type { RelayHeaders } from "@legion/envoy-client/consumer-delivery"
2
2
  import { DedupeIdentitySchema } from "@legion/envoy-client/delivery"
3
- import { messageFor } from "@legion/envoy-client/errors"
3
+ import { natsFailureReason } from "@legion/envoy-client/errors"
4
4
  import { expandSubscriptionTopics } from "@legion/envoy-client/transport"
5
5
  import { z } from "zod"
6
6
 
@@ -92,8 +92,9 @@ export function deliveryIdentity(raw: string): z.infer<typeof DeliveryIdentity>
92
92
  return identity.success ? identity.data : undefined
93
93
  }
94
94
 
95
+ /** A failed drain or close of the NATS connection, as a log may print it (`natsFailureReason`). */
95
96
  function report(what: string, error: unknown): void {
96
- process.stderr.write(`envoy-channel: ${what} — ${messageFor(error)}\n`)
97
+ process.stderr.write(`envoy-channel: ${what} — ${natsFailureReason(error)}\n`)
97
98
  }
98
99
 
99
100
  /**
@@ -40,6 +40,15 @@ export interface CodexAgentStreamOptions {
40
40
  readonly sessionId: string
41
41
  readonly now?: () => number
42
42
  readonly warn?: (text: string) => void
43
+ /**
44
+ * Settles once the session's NATS connection is admitted as `session`, where the connection is
45
+ * admitted as one session at a time: under its broker token a `/new`'s new id is the
46
+ * connection's only once the move lands (`followSession`), and a subscribe before then is
47
+ * refused and closed by the server. Where this is absent the connection may take every id's
48
+ * subjects, and the new control subject is taken at once (`AgentStreamOptions.admitted`, the
49
+ * Claude Code live view's).
50
+ */
51
+ readonly admitted?: (session: string) => Promise<void>
43
52
  }
44
53
 
45
54
  const encoder = new TextEncoder()
@@ -230,7 +239,16 @@ export function startCodexAgentStream(options: CodexAgentStreamOptions): CodexAg
230
239
  expected.length = 0
231
240
  toolNames.clear()
232
241
  publishSettings()
233
- subscribe()
242
+ // The old id's control subject goes at once, and the new id's is taken once the connection
243
+ // may take it (`CodexAgentStreamOptions.admitted`): a later `/new` before then takes its own.
244
+ subscription?.unsubscribe()
245
+ subscription = undefined
246
+ const admitted = options.admitted?.(next)
247
+ if (admitted === undefined) subscribe()
248
+ else
249
+ void admitted.then(() => {
250
+ if (!stopped && session === next) subscribe()
251
+ })
234
252
  },
235
253
  stop() {
236
254
  stopped = true
@@ -8,7 +8,6 @@ import { DispatchClient } from "@legion/envoy-client/dispatch-http"
8
8
  import { sessionDirectory as dispatchSessionDirectory } from "@legion/envoy-client/dispatch-session-directory"
9
9
  import { writeSessionTitle } from "@legion/envoy-client/dispatch-session-state"
10
10
  import { messageFor } from "@legion/envoy-client/errors"
11
- import { natsConnectionOptions } from "@legion/envoy-client/nats-connection"
12
11
  import {
13
12
  sessionConfigFile,
14
13
  sessionDispatchSettings,
@@ -28,10 +27,12 @@ import {
28
27
  type ChannelSession,
29
28
  type ChannelToolRuntime,
30
29
  channelToolDefinitions,
30
+ dialChannelNats,
31
31
  executeEnvoyTool,
32
32
  MCP_SERVER_INFO,
33
33
  mcpResult,
34
34
  postDispatchReply,
35
+ sessionAdmission,
35
36
  startChannelSession,
36
37
  } from "../envoy-channel-server"
37
38
  import { inboundOffChannelSession } from "../envoy-off"
@@ -328,6 +329,8 @@ export async function runCodexEnvoyServer(): Promise<void> {
328
329
  let session: ChannelSession | undefined
329
330
  let connection: ChannelConnection | undefined
330
331
  let stream: CodexAgentStream | undefined
332
+ /** Stops the keeper of the connection's broker token, once one is dialled. */
333
+ let stopNatsKeeper: () => void = () => undefined
331
334
  let follower: TranscriptFollower | undefined
332
335
  let delivery: ReturnType<typeof createCodexDelivery> | undefined
333
336
 
@@ -341,6 +344,7 @@ export async function runCodexEnvoyServer(): Promise<void> {
341
344
  clearInterval(recheck)
342
345
  follower?.stop()
343
346
  stream?.stop()
347
+ stopNatsKeeper()
344
348
  // The entry goes once the delivery's waiting lines are withdrawn, so a server that takes over
345
349
  // never discards a line this one still answers for.
346
350
  const withdrawn = (delivery?.stop() ?? Promise.resolve()).finally(() =>
@@ -527,13 +531,31 @@ export async function runCodexEnvoyServer(): Promise<void> {
527
531
  if ("off" in inbound) {
528
532
  session = inboundOffChannelSession({ identity: id, stateDirectory, why: inbound.off })
529
533
  } else {
530
- connection = await connect(
531
- natsConnectionOptions({
532
- name: `codex-envoy-channel-${id.id}`,
533
- seed: inbound.natsSeed,
534
- servers: inbound.natsUrls,
535
- }),
534
+ // Dialled as the Claude Code session's connection is (`dialChannelNats`): with a seed, no
535
+ // credential, or the session's broker token, which is then kept renewed and, at a `/new`,
536
+ // moved to the new session's (`followSession`) before that session's subjects are taken.
537
+ const dialled = await dialChannelNats(
538
+ inbound,
539
+ `codex-envoy-channel-${id.id}`,
540
+ warn,
541
+ connect,
542
+ stopping.signal,
536
543
  )
544
+ connection = dialled.connection
545
+ stopNatsKeeper = dialled.stop
546
+ // Which id the connection is admitted as, where its broker token admits one session at a
547
+ // time: the dial's, then each `/new`'s once its move lands. The live view takes a new id's
548
+ // control subject only then (`CodexAgentStreamOptions.admitted`).
549
+ const admission = dialled.followSession === undefined ? undefined : sessionAdmission(id.id)
550
+ const follow = dialled.followSession
551
+ const followSession =
552
+ follow === undefined || admission === undefined
553
+ ? undefined
554
+ : async (): Promise<void> => {
555
+ const forSession = id.id
556
+ await follow()
557
+ admission.admit(forSession)
558
+ }
537
559
  session = await startChannelSession({
538
560
  capabilities: () => CODEX_CAPABILITIES,
539
561
  client,
@@ -543,6 +565,7 @@ export async function runCodexEnvoyServer(): Promise<void> {
543
565
  handoffPid: codexPid,
544
566
  heartbeatMs: envoy.heartbeatMs,
545
567
  identity: id,
568
+ ...(followSession === undefined ? {} : { followSession }),
546
569
  notifier: {
547
570
  notification: ({ content, eventId }) =>
548
571
  codexDelivery.deliver({ content, ...(eventId === undefined ? {} : { eventId }) }),
@@ -573,7 +596,14 @@ export async function runCodexEnvoyServer(): Promise<void> {
573
596
  title,
574
597
  ...(dispatch.enabled ? { stampTitle } : {}),
575
598
  })
576
- stream = startCodexAgentStream({ connection, sessionId: id.id, warn })
599
+ stream = startCodexAgentStream({
600
+ connection,
601
+ sessionId: id.id,
602
+ warn,
603
+ ...(admission === undefined
604
+ ? {}
605
+ : { admitted: (next: string) => admission.admitted(next) }),
606
+ })
577
607
  }
578
608
  runtime = { client, clientInstanceID, identity: id, session }
579
609
  follow(bound.transcript_path)
@@ -585,6 +615,7 @@ export async function runCodexEnvoyServer(): Promise<void> {
585
615
  await stopped.promise
586
616
  } finally {
587
617
  follower?.stop()
618
+ stopNatsKeeper()
588
619
  if (session === undefined && connection !== undefined) {
589
620
  await connection.drain().catch(() => undefined)
590
621
  await connection.close().catch(() => undefined)