@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.
@@ -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.0",
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
@@ -1,5 +1,12 @@
1
1
  import { messageFor } from "@legion/envoy-client/errors"
2
- import { type CodexInboxItem, putInbox, takeInbox, takenBy, withdrawWaiting } from "./codex-inbox"
2
+ import {
3
+ type CodexInboxItem,
4
+ inboxItemName,
5
+ putInbox,
6
+ takeInbox,
7
+ takenBy,
8
+ withdrawWaiting,
9
+ } from "./codex-inbox"
3
10
 
4
11
  /**
5
12
  * Puts a line into a Codex session's conversation.
@@ -19,11 +26,12 @@ import { type CodexInboxItem, putInbox, takeInbox, takenBy, withdrawWaiting } fr
19
26
  * the Envoy frame it carries is not answered and the listener sends it again.
20
27
  *
21
28
  * Every write settles, because the session's frames are written one behind another and one that
22
- * never settled would hold back every later one: a line the hook did not take is queued at the
23
- * turn's end, and, while no turn runs, by a sweep every `pollMs`; a sweep looks at the inbox of
24
- * every session a line still waits in, so a `/new` that moves the session to another id while a
25
- * line waits for the old one queues it for the new one; and a sweep that fails is logged and
26
- * tried again rather than ending the ones after it.
29
+ * never settled would hold back every later one: a write's waiter is in place before its line can
30
+ * be seen, so whatever takes the line, a sweep or the hook, finds the write to settle; a line the
31
+ * hook did not take is queued at the turn's end, and, while no turn runs, by a sweep every
32
+ * `pollMs`; a sweep looks at the inbox of every session a line still waits in, so a `/new` that
33
+ * moves the session to another id while a line waits for the old one queues it for the new one;
34
+ * and a sweep that fails is logged and tried again rather than ending the ones after it.
27
35
  */
28
36
  export interface CodexDeliveryOptions {
29
37
  /** The session the `codex` process runs now, as its record names it. */
@@ -60,7 +68,9 @@ export interface CodexDelivery {
60
68
  /** Whether a turn runs, as the transcript last said. */
61
69
  turnRunning(): boolean
62
70
  /** Stops watching waiting lines; a write still waiting rejects. Resolves once every waiting line
63
- * is withdrawn or found taken. */
71
+ * is withdrawn or found taken: a line still being written is withdrawn once it is in place, and
72
+ * a sweep already running first settles the writes of the lines it takes. No sweep starts after
73
+ * this. */
64
74
  stop(): Promise<void>
65
75
  }
66
76
 
@@ -69,6 +79,9 @@ const WAITING_POLL_MS = 250
69
79
  interface Waiter {
70
80
  readonly directory: string
71
81
  readonly item: CodexInboxItem
82
+ /** Whether the line's file is in place: false when writing it failed, and the write then rejects
83
+ * with that failure itself. */
84
+ readonly landed: Promise<boolean>
72
85
  readonly resolve: () => void
73
86
  readonly reject: (error: Error) => void
74
87
  }
@@ -103,6 +116,9 @@ export function createCodexDelivery(options: CodexDeliveryOptions): CodexDeliver
103
116
  }
104
117
  }
105
118
  const sweep = (): Promise<void> => {
119
+ // Once stop() has run, every line left is stop()'s to withdraw or find taken: a sweep that
120
+ // queued one now would leave stop() a line it cannot withdraw and whose queueing it never saw.
121
+ if (stopped) return sweeping
106
122
  sweeping = sweeping.then(sweepOnce).catch((error: unknown) => {
107
123
  options.warn(`the Codex inbox could not be swept, and will be again: ${messageFor(error)}`)
108
124
  })
@@ -139,13 +155,33 @@ export function createCodexDelivery(options: CodexDeliveryOptions): CodexDeliver
139
155
  return
140
156
  }
141
157
  const directory = options.inboxDirectory(options.sessionId())
142
- const name = await putInbox(directory, item)
143
- const written = new Promise<void>((resolve, reject) => {
144
- waiting.set(name, { directory, item, reject, resolve })
158
+ // The waiter is in place before the write of its line starts. A waiter registered only once
159
+ // the write returned missed a sweep or a stop() that came between: the sweep queued the line
160
+ // with no write to settle, or stop() did not see it, and the write never settled.
161
+ const name = inboxItemName()
162
+ const written = Promise.withResolvers<void>()
163
+ // A sweep can settle the write before putInbox returns; the write is awaited below.
164
+ written.promise.catch(() => undefined)
165
+ const landed = Promise.withResolvers<boolean>()
166
+ waiting.set(name, {
167
+ directory,
168
+ item,
169
+ landed: landed.promise,
170
+ resolve: written.resolve,
171
+ reject: written.reject,
145
172
  })
146
- // The turn may have ended while the line was being written, after its sweep ran.
147
- if (!running) void sweep()
148
- await written
173
+ try {
174
+ await putInbox(directory, item, name)
175
+ landed.resolve(true)
176
+ } catch (error) {
177
+ landed.resolve(false)
178
+ waiting.delete(name)
179
+ throw error
180
+ }
181
+ // The turn may have ended while the line was being written, after its sweep ran. A session
182
+ // that ended meanwhile gets the line once it runs again, as the poll waits for that too.
183
+ if (!running && !ended) void sweep()
184
+ await written.promise
149
185
  },
150
186
  turnStarted() {
151
187
  running = true
@@ -174,21 +210,28 @@ export function createCodexDelivery(options: CodexDeliveryOptions): CodexDeliver
174
210
  clearInterval(timer)
175
211
  // A refused write leaves its Envoy frame unanswered, so Envoy sends it again. Each line is
176
212
  // withdrawn before its write is refused, so the hook cannot deliver it as well; a line the
177
- // hook took first was delivered, and its write resolves.
178
- const left = [...waiting]
179
- waiting.clear()
180
- return Promise.all(
181
- left.map(async ([name, waiter]) => {
182
- if (await withdrawWaiting(waiter.directory, name)) {
183
- waiter.reject(
184
- new Error("the Codex session's delivery stopped before the message was taken"),
185
- )
186
- } else {
187
- if ((await takenBy(waiter.directory, name)) === "hook") options.taken?.(waiter.item)
188
- waiter.resolve()
189
- }
190
- }),
191
- ).then(() => undefined)
213
+ // hook took first was delivered, and its write resolves. A sweep that already started
214
+ // settles the writes of the lines it takes, so stop() takes what is left only once it ends.
215
+ return sweeping
216
+ .then(() => {
217
+ const left = [...waiting]
218
+ waiting.clear()
219
+ return Promise.all(
220
+ left.map(async ([name, waiter]) => {
221
+ // A write whose line never landed rejects with its own failure.
222
+ if (!(await waiter.landed)) return
223
+ if (await withdrawWaiting(waiter.directory, name)) {
224
+ waiter.reject(
225
+ new Error("the Codex session's delivery stopped before the message was taken"),
226
+ )
227
+ } else {
228
+ if ((await takenBy(waiter.directory, name)) === "hook") options.taken?.(waiter.item)
229
+ waiter.resolve()
230
+ }
231
+ }),
232
+ )
233
+ })
234
+ .then(() => undefined)
192
235
  },
193
236
  }
194
237
  }
@@ -34,20 +34,24 @@ export function codexInboxDirectory(stateDirectory: string, sessionId: string):
34
34
  return join(stateDirectory, "codex-inbox", encodeURIComponent(sessionId))
35
35
  }
36
36
 
37
- /** A file name that sorts after every name written before it in this process. */
37
+ /** A file name for a new line: it sorts after every name chosen before it in this process. */
38
38
  let lastOrder = 0
39
- function itemName(): string {
39
+ export function inboxItemName(): string {
40
40
  const order = Math.max(Date.now(), lastOrder + 1)
41
41
  lastOrder = order
42
42
  return `${String(order).padStart(15, "0")}-${randomBytes(4).toString("hex")}.json`
43
43
  }
44
44
 
45
- /** Writes `item` as a waiting message and answers its file name, which `isWaiting` and
46
- * `takenBy` look up. The file is renamed into place whole, so a reader never sees half of it. */
47
- export async function putInbox(directory: string, item: CodexInboxItem): Promise<string> {
45
+ /** Writes `item` as a waiting message named `name` and answers the name, which `takenBy` and
46
+ * `withdrawWaiting` look up. The file is renamed into place whole, so a reader never sees half of
47
+ * it. A caller that must be ready for the line before anyone can see it chooses `name` first. */
48
+ export async function putInbox(
49
+ directory: string,
50
+ item: CodexInboxItem,
51
+ name: string = inboxItemName(),
52
+ ): Promise<string> {
48
53
  const waiting = join(directory, "waiting")
49
54
  await mkdir(waiting, { recursive: true, mode: 0o700 })
50
- const name = itemName()
51
55
  const temporary = join(directory, `.${name}.tmp`)
52
56
  await writeFile(temporary, JSON.stringify(item), { mode: 0o600 })
53
57
  await rename(temporary, join(waiting, name))