@sjawhar/claude-envoy 4.0.0 → 4.1.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,194 @@
1
+ import { messageFor } from "@legion/envoy-client/errors"
2
+ import { type CodexInboxItem, putInbox, takeInbox, takenBy, withdrawWaiting } from "./codex-inbox"
3
+
4
+ /**
5
+ * Puts a line into a Codex session's conversation.
6
+ *
7
+ * Codex has no call that writes into a running conversation, so a line takes one of two ways in:
8
+ *
9
+ * - While the session is idle, `codex queue`, which the Codex terminal takes as a new turn a few
10
+ * seconds later.
11
+ * - While a turn runs, the plugin's inbox (`./codex-inbox`): the `PostToolUse` hook hands it to
12
+ * the model at the turn's next tool call, and when the turn ends with it still waiting, this
13
+ * hands it to `codex queue` for the next turn. A Claude Code session reads a line that arrives
14
+ * mid-turn at the same point, its next request, or after the turn.
15
+ *
16
+ * Whether a turn runs is what the session's transcript last said (`turnStarted`, `turnEnded`,
17
+ * from `./codex-transcript`). A write resolves once the line is in the session - Codex stored
18
+ * it in its queue, or the hook took it into the turn - and rejects when `codex queue` failed, so
19
+ * the Envoy frame it carries is not answered and the listener sends it again.
20
+ *
21
+ * 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.
27
+ */
28
+ export interface CodexDeliveryOptions {
29
+ /** The session the `codex` process runs now, as its record names it. */
30
+ readonly sessionId: () => string
31
+ /** The inbox directory of a session (`codexInboxDirectory`). */
32
+ readonly inboxDirectory: (sessionId: string) => string
33
+ /** `codex queue` for the session the process runs now. */
34
+ readonly queue: (text: string) => Promise<void>
35
+ /** Told of each line the hook took into a running turn, so the live view can show it: the
36
+ * transcript records a hook's text as an instruction, not as a message of the conversation. */
37
+ readonly taken?: (item: CodexInboxItem) => void
38
+ readonly warn: (text: string) => void
39
+ /** How often a waiting line is looked at to see whether the hook took it. */
40
+ readonly pollMs?: number
41
+ }
42
+
43
+ export interface CodexDelivery {
44
+ /** Puts `item` into the session; see above. */
45
+ deliver(item: CodexInboxItem): Promise<void>
46
+ /** The transcript says a turn started. */
47
+ turnStarted(): void
48
+ /** The transcript says the turn ended: anything still waiting goes to `codex queue`. */
49
+ turnEnded(): Promise<void>
50
+ /** The session ended (`SessionEnd`, which Codex runs when it unloads the thread,
51
+ * `thread_unload_delay` after it is idle with no subscriber, 60 s by default, or at exit): every
52
+ * write from now is refused, so its Envoy frame stays unanswered and is sent again, until
53
+ * `rebind` names a session that has not ended or `sessionResumed` says this one runs again. */
54
+ sessionEnded(): void
55
+ /** The session that had ended runs again (`/resume`): writes are taken again. */
56
+ sessionResumed(): Promise<void>
57
+ /** The process moved to another session (`/new`): no turn of it runs yet, and what waited for
58
+ * the old one goes to the new one, unless the new one has already ended (`ended`). */
59
+ rebind(ended?: boolean): Promise<void>
60
+ /** Whether a turn runs, as the transcript last said. */
61
+ turnRunning(): boolean
62
+ /** Stops watching waiting lines; a write still waiting rejects. Resolves once every waiting line
63
+ * is withdrawn or found taken. */
64
+ stop(): Promise<void>
65
+ }
66
+
67
+ const WAITING_POLL_MS = 250
68
+
69
+ interface Waiter {
70
+ readonly directory: string
71
+ readonly item: CodexInboxItem
72
+ readonly resolve: () => void
73
+ readonly reject: (error: Error) => void
74
+ }
75
+
76
+ export function createCodexDelivery(options: CodexDeliveryOptions): CodexDelivery {
77
+ const pollMs = options.pollMs ?? WAITING_POLL_MS
78
+ let running = false
79
+ let stopped = false
80
+ let ended = false
81
+ /** Every line in an inbox whose write has not resolved, by file name. */
82
+ const waiting = new Map<string, Waiter>()
83
+ /** One sweep at a time, so a line is never queued twice by two sweeps. */
84
+ let sweeping: Promise<void> = Promise.resolve()
85
+
86
+ const sweepOnce = async (): Promise<void> => {
87
+ const directories = new Set([options.inboxDirectory(options.sessionId())])
88
+ for (const waiter of waiting.values()) directories.add(waiter.directory)
89
+ for (const directory of directories) {
90
+ for (const { name, item } of await takeInbox(directory, "server")) {
91
+ const waiter = waiting.get(name)
92
+ waiting.delete(name)
93
+ try {
94
+ await options.queue(item.content)
95
+ waiter?.resolve()
96
+ } catch (error) {
97
+ const failure = error instanceof Error ? error : new Error(messageFor(error))
98
+ if (waiter === undefined) {
99
+ options.warn(`a waiting message could not be queued: ${failure.message}`)
100
+ } else waiter.reject(failure)
101
+ }
102
+ }
103
+ }
104
+ }
105
+ const sweep = (): Promise<void> => {
106
+ sweeping = sweeping.then(sweepOnce).catch((error: unknown) => {
107
+ options.warn(`the Codex inbox could not be swept, and will be again: ${messageFor(error)}`)
108
+ })
109
+ return sweeping
110
+ }
111
+
112
+ /** Resolves the writes whose lines the hook took. */
113
+ const check = async (): Promise<void> => {
114
+ for (const [name, waiter] of [...waiting]) {
115
+ if ((await takenBy(waiter.directory, name)) !== "hook") continue
116
+ if (!waiting.delete(name)) continue
117
+ options.taken?.(waiter.item)
118
+ waiter.resolve()
119
+ }
120
+ }
121
+ const timer = setInterval(() => {
122
+ if (waiting.size === 0) return
123
+ void check()
124
+ .then(() => (running || ended || waiting.size === 0 ? undefined : sweep()))
125
+ .catch((error: unknown) => options.warn(messageFor(error)))
126
+ }, pollMs)
127
+ timer.unref?.()
128
+
129
+ return {
130
+ async deliver(item) {
131
+ if (stopped) throw new Error("the Codex session's delivery has stopped")
132
+ if (ended) {
133
+ throw new Error(
134
+ "the Codex session ended; the message is sent again once the session that follows starts",
135
+ )
136
+ }
137
+ if (!running) {
138
+ await options.queue(item.content)
139
+ return
140
+ }
141
+ 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 })
145
+ })
146
+ // The turn may have ended while the line was being written, after its sweep ran.
147
+ if (!running) void sweep()
148
+ await written
149
+ },
150
+ turnStarted() {
151
+ running = true
152
+ },
153
+ async turnEnded() {
154
+ running = false
155
+ await check().catch((error: unknown) => options.warn(messageFor(error)))
156
+ await sweep()
157
+ },
158
+ sessionEnded() {
159
+ ended = true
160
+ running = false
161
+ },
162
+ async sessionResumed() {
163
+ ended = false
164
+ await sweep()
165
+ },
166
+ async rebind(endedNow = false) {
167
+ ended = endedNow
168
+ running = false
169
+ if (!ended) await sweep()
170
+ },
171
+ turnRunning: () => running,
172
+ stop() {
173
+ stopped = true
174
+ clearInterval(timer)
175
+ // A refused write leaves its Envoy frame unanswered, so Envoy sends it again. Each line is
176
+ // 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)
192
+ },
193
+ }
194
+ }
@@ -0,0 +1,197 @@
1
+ import { randomBytes } from "node:crypto"
2
+ import { mkdir, readdir, readFile, rename, rm, writeFile } from "node:fs/promises"
3
+ import { join } from "node:path"
4
+
5
+ /**
6
+ * The Codex plugin's inbox: messages waiting for the running turn of one session.
7
+ *
8
+ * Codex gives a plugin no way to write into a running conversation, but a `PostToolUse` hook's
9
+ * `additionalContext` reaches the model in its very next request. So a message that arrives while
10
+ * a turn runs is written here as one file, and two parties may take it: the `PostToolUse` hook,
11
+ * which puts it into the turn at the next tool call, and the MCP server, which hands it to
12
+ * `codex queue` when the turn ends with it still here. Each takes a message by renaming its file
13
+ * into a directory of its own, so exactly one of them delivers it: `rename` within one directory
14
+ * tree is atomic, and the second rename of the same file fails.
15
+ *
16
+ * Layout under the session's directory: `waiting/<order>-<random>.json` is a message nobody took,
17
+ * `taken/` holds what the hook took and `queued/` what the server handed to `codex queue`.
18
+ */
19
+ export interface CodexInboxItem {
20
+ /** The text the model is to read. */
21
+ readonly content: string
22
+ /** The Envoy event this message is, where it is one. */
23
+ readonly eventId?: string
24
+ /** The Dispatch message this is, when it is a person's own message. */
25
+ readonly dispatchMessageId?: string
26
+ }
27
+
28
+ export type CodexInboxTaker = "hook" | "server"
29
+
30
+ const TAKEN_DIRECTORY: Record<CodexInboxTaker, string> = { hook: "taken", server: "queued" }
31
+
32
+ /** The inbox directory of one session, under the plugin's state directory. */
33
+ export function codexInboxDirectory(stateDirectory: string, sessionId: string): string {
34
+ return join(stateDirectory, "codex-inbox", encodeURIComponent(sessionId))
35
+ }
36
+
37
+ /** A file name that sorts after every name written before it in this process. */
38
+ let lastOrder = 0
39
+ function itemName(): string {
40
+ const order = Math.max(Date.now(), lastOrder + 1)
41
+ lastOrder = order
42
+ return `${String(order).padStart(15, "0")}-${randomBytes(4).toString("hex")}.json`
43
+ }
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> {
48
+ const waiting = join(directory, "waiting")
49
+ await mkdir(waiting, { recursive: true, mode: 0o700 })
50
+ const name = itemName()
51
+ const temporary = join(directory, `.${name}.tmp`)
52
+ await writeFile(temporary, JSON.stringify(item), { mode: 0o600 })
53
+ await rename(temporary, join(waiting, name))
54
+ return name
55
+ }
56
+
57
+ /** Who took the message named `name`, or undefined while it waits (or when nobody knows it). */
58
+ export async function takenBy(
59
+ directory: string,
60
+ name: string,
61
+ ): Promise<CodexInboxTaker | undefined> {
62
+ for (const taker of ["hook", "server"] as const) {
63
+ try {
64
+ await readFile(join(directory, TAKEN_DIRECTORY[taker], name))
65
+ return taker
66
+ } catch {
67
+ // Not taken by this one.
68
+ }
69
+ }
70
+ return undefined
71
+ }
72
+
73
+ /**
74
+ * Takes the one line `name` out of `directory`'s waiting lines, where nothing took it yet: answers
75
+ * whether it was still waiting, so a caller refuses its write only when no taker can deliver it.
76
+ */
77
+ export async function withdrawWaiting(directory: string, name: string): Promise<boolean> {
78
+ try {
79
+ await rm(join(directory, "waiting", name))
80
+ return true
81
+ } catch {
82
+ return false
83
+ }
84
+ }
85
+
86
+ /**
87
+ * Removes the messages waiting in `directory` that no write of this process waits for: lines an
88
+ * earlier server of the session left when it stopped. Each one's write never resolved, so the
89
+ * Envoy frame it carried was never answered and Envoy sends it again to whoever binds the session
90
+ * next; delivering the file as well would give the session the message twice (after `codex
91
+ * resume`, for one). `keep` names the files to leave.
92
+ */
93
+ export async function discardWaiting(
94
+ directory: string,
95
+ keep: (name: string) => boolean = () => false,
96
+ ): Promise<number> {
97
+ const waiting = join(directory, "waiting")
98
+ let names: string[]
99
+ try {
100
+ names = await readdir(waiting)
101
+ } catch {
102
+ return 0
103
+ }
104
+ let removed = 0
105
+ for (const name of names) {
106
+ if (!name.endsWith(".json") || keep(name)) continue
107
+ try {
108
+ await rm(join(waiting, name))
109
+ removed++
110
+ } catch {
111
+ // Taken by the hook or the sweep meanwhile.
112
+ }
113
+ }
114
+ return removed
115
+ }
116
+
117
+ /**
118
+ * The most a `PostToolUse` hook hands Codex at once, in bytes of `inboxContext`'s text. Codex
119
+ * caps a hook's `additionalContext` at 2,500 tokens by default (`hooks/src/output_spill.rs` in
120
+ * 0.154.0); past it the model gets a preview and the rest goes to a file, while the message would
121
+ * count as delivered whole. A token of a tokenizer like the one Codex's models use rarely covers
122
+ * fewer than about three and a half bytes of English, so 8,000 bytes leaves room under the cap for
123
+ * ordinary text. A message dense in rare characters can still run past it.
124
+ */
125
+ export const HOOK_CONTEXT_MAX_BYTES = 8_000
126
+
127
+ /**
128
+ * Takes waiting messages for `taker`, oldest first, and answers them. A message another taker
129
+ * renamed first is skipped, as is one whose file cannot be read once taken (it is left in the
130
+ * taker's directory, where nothing reads it again).
131
+ *
132
+ * With `maxContextBytes`, it stops at the first message that would take `inboxContext`'s text past
133
+ * that many bytes, and leaves it and every later one waiting, in order, for `codex queue` at the
134
+ * turn's end, which takes a message of any length.
135
+ */
136
+ export async function takeInbox(
137
+ directory: string,
138
+ taker: CodexInboxTaker,
139
+ maxContextBytes?: number,
140
+ ): Promise<{ readonly name: string; readonly item: CodexInboxItem }[]> {
141
+ const waiting = join(directory, "waiting")
142
+ let names: string[]
143
+ try {
144
+ names = (await readdir(waiting)).filter((name) => name.endsWith(".json")).sort()
145
+ } catch {
146
+ return []
147
+ }
148
+ if (names.length === 0) return []
149
+ const destination = join(directory, TAKEN_DIRECTORY[taker])
150
+ await mkdir(destination, { recursive: true, mode: 0o700 })
151
+ const taken: { name: string; item: CodexInboxItem }[] = []
152
+ for (const name of names) {
153
+ if (maxContextBytes !== undefined) {
154
+ let waitingItem: unknown
155
+ try {
156
+ waitingItem = JSON.parse(await readFile(join(waiting, name), "utf8"))
157
+ } catch {
158
+ continue
159
+ }
160
+ if (typeof (waitingItem as CodexInboxItem | null)?.content !== "string") continue
161
+ const items = [...taken.map(({ item }) => item), waitingItem as CodexInboxItem]
162
+ if (Buffer.byteLength(inboxContext(items)) > maxContextBytes) break
163
+ }
164
+ try {
165
+ await rename(join(waiting, name), join(destination, name))
166
+ } catch {
167
+ continue
168
+ }
169
+ try {
170
+ const parsed: unknown = JSON.parse(await readFile(join(destination, name), "utf8"))
171
+ if (
172
+ typeof parsed === "object" &&
173
+ parsed !== null &&
174
+ typeof (parsed as CodexInboxItem).content === "string"
175
+ ) {
176
+ taken.push({ item: parsed as CodexInboxItem, name })
177
+ }
178
+ } catch {
179
+ // Unreadable once taken: nothing else will try it.
180
+ }
181
+ }
182
+ return taken
183
+ }
184
+
185
+ /** The text a `PostToolUse` hook hands Codex for messages it took: each message whole, in order,
186
+ * under one line saying where they came from. A person's own message says it is theirs, since
187
+ * Codex frames hook text as an instruction rather than as something a person typed. */
188
+ export function inboxContext(items: readonly CodexInboxItem[]): string {
189
+ return [
190
+ "Messages delivered to this session while it worked (Envoy, through the Envoy plugin):",
191
+ ...items.map((item) =>
192
+ item.dispatchMessageId === undefined
193
+ ? item.content
194
+ : `A person wrote to you from Dispatch (message ${item.dispatchMessageId}):\n${item.content}`,
195
+ ),
196
+ ].join("\n\n")
197
+ }
@@ -0,0 +1,273 @@
1
+ import { link, mkdir, readdir, readFile, rm, stat, writeFile } from "node:fs/promises"
2
+ import { join } from "node:path"
3
+ import { processStarted } from "./codex-session-record"
4
+
5
+ /**
6
+ * Which of a `codex` process's plugin servers owns its Envoy session.
7
+ *
8
+ * Codex starts one MCP server per thread (measured on 0.154.0: `/new` starts a second server under
9
+ * the same `codex` process while the first runs on until Codex unloads its thread, and `/side` and
10
+ * `/btw` start one each for their fork). The record of the session the process runs is keyed by the
11
+ * process, so every one of those servers would bind it and register the same session.
12
+ *
13
+ * So each server publishes an entry, `codex-servers/<codex pid>/<seq>.json`, taking the next free
14
+ * sequence number by linking a fully written temporary file into place (`link` fails when the
15
+ * name exists), so two live entries never hold one number and the order is the order they
16
+ * published in, whatever the clock says. The owner is the live entry with the lowest number. No
17
+ * server removes another's entry, so a name a server judged dead and a name a later server took
18
+ * are never confused; the `SessionStart` hook removes a dead codex process's entries. Every server
19
+ * reads the same entries and reaches the same answer. The others stand by, serving their thread's
20
+ * `dispatch` calls, until every server that published before them is gone.
21
+ */
22
+ export interface CodexServerEntry {
23
+ /** The publication number: lower owns. */
24
+ readonly seq: number
25
+ /** The server's pid. */
26
+ readonly pid: number
27
+ /** When it started (`processStarted`), so a pid used again names nothing; null where it could
28
+ * not be read, and then only `ESRCH` says the server is gone. */
29
+ readonly started: string | null
30
+ }
31
+
32
+ /** The directory of `codex` process `codexPid`'s servers, under the plugin's state directory. */
33
+ export function codexServersDirectory(stateDirectory: string, codexPid: number): string {
34
+ return join(stateDirectory, "codex-servers", String(codexPid))
35
+ }
36
+
37
+ const ENTRY_NAME = /^(\d+)\.json$/
38
+
39
+ function entryName(entry: { readonly seq: number }): string {
40
+ return `${entry.seq}.json`
41
+ }
42
+
43
+ /**
44
+ * Publishes an entry for server `pid`, at the lowest number above every entry there, and answers
45
+ * it. The entry is written whole to a temporary file and linked into place, and `link` fails when
46
+ * the name exists, so a server that loses a number to another takes the next one, and a reader
47
+ * never sees a half-written entry.
48
+ */
49
+ export async function registerServer(
50
+ directory: string,
51
+ pid: number,
52
+ started: string | null,
53
+ ): Promise<CodexServerEntry> {
54
+ await mkdir(directory, { mode: 0o700, recursive: true })
55
+ const temporary = join(directory, `.${pid}.${process.hrtime.bigint()}.tmp`)
56
+ await writeFile(temporary, JSON.stringify({ pid, started }), { mode: 0o600 })
57
+ try {
58
+ let seq = Math.max(0, ...(await entryNames(directory)).map(({ seq: taken }) => taken)) + 1
59
+ for (;;) {
60
+ try {
61
+ await place(temporary, join(directory, entryName({ seq })), pid, started)
62
+ return { pid, seq, started }
63
+ } catch (error) {
64
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error
65
+ seq++
66
+ }
67
+ }
68
+ } finally {
69
+ await rm(temporary, { force: true })
70
+ }
71
+ }
72
+
73
+ /** Where `link` is refused (a file system without hard links), whether to fall back to an exclusive
74
+ * create; set once seen, so the fallback is not tried before every link. */
75
+ let linkRefused = false
76
+
77
+ /**
78
+ * Puts the entry at `target`, failing with `EEXIST` when the name is taken: `link` of the fully
79
+ * written `temporary`, or, on a file system that refuses hard links (`EPERM`, `ENOTSUP`,
80
+ * `EXDEV`), an exclusive create that writes the whole entry in one small write.
81
+ */
82
+ async function place(
83
+ temporary: string,
84
+ target: string,
85
+ pid: number,
86
+ started: string | null,
87
+ ): Promise<void> {
88
+ if (!linkRefused) {
89
+ try {
90
+ await link(temporary, target)
91
+ return
92
+ } catch (error) {
93
+ const code = (error as NodeJS.ErrnoException).code
94
+ if (code !== "EPERM" && code !== "ENOTSUP" && code !== "EXDEV") throw error
95
+ linkRefused = true
96
+ }
97
+ }
98
+ await writeFile(target, JSON.stringify({ pid, started }), { flag: "wx", mode: 0o600 })
99
+ }
100
+
101
+ /** Removes `self`'s entry. */
102
+ export async function unregisterServer(directory: string, self: CodexServerEntry): Promise<void> {
103
+ await rm(join(directory, entryName(self)), { force: true })
104
+ }
105
+
106
+ /** How a liveness check reads a process: `kill(pid, 0)` and its start. */
107
+ export interface ProcessProbe {
108
+ readonly signal: (pid: number) => void
109
+ readonly started: (pid: number) => string | undefined
110
+ }
111
+
112
+ /** The start each live pid was last read at, so `ps` (off Linux) runs once per pid, not every
113
+ * poll. A pid's start changes only when the pid is used again, which `ESRCH` comes before. */
114
+ const startedOf = new Map<number, string | undefined>()
115
+
116
+ const SYSTEM_PROBE: ProcessProbe = {
117
+ signal: (pid) => process.kill(pid, 0),
118
+ started: (pid) => {
119
+ if (!startedOf.has(pid)) startedOf.set(pid, processStarted(pid))
120
+ return startedOf.get(pid)
121
+ },
122
+ }
123
+
124
+ /** Whether a liveness check found the pid gone (`ESRCH`), and not merely unreadable. */
125
+ function gone(pid: number, probe: ProcessProbe): boolean {
126
+ try {
127
+ probe.signal(pid)
128
+ return false
129
+ } catch (error) {
130
+ if ((error as NodeJS.ErrnoException).code !== "ESRCH") return false // EPERM: a process runs.
131
+ startedOf.delete(pid)
132
+ return true
133
+ }
134
+ }
135
+
136
+ /**
137
+ * Whether the server `entry` names still runs. It is gone only when its pid answers `ESRCH`, or
138
+ * when both starts can be read and differ (the pid was used again); a start that cannot be read
139
+ * now, as when `ps` fails, says nothing either way, so a live owner is never judged gone for it.
140
+ */
141
+ export function serverAlive(entry: CodexServerEntry, probe: ProcessProbe = SYSTEM_PROBE): boolean {
142
+ if (gone(entry.pid, probe)) return false
143
+ const now = probe.started(entry.pid)
144
+ return entry.started === null || now === undefined || now === entry.started
145
+ }
146
+
147
+ async function entryNames(directory: string): Promise<{ seq: number; name: string }[]> {
148
+ let names: string[]
149
+ try {
150
+ names = await readdir(directory)
151
+ } catch {
152
+ return []
153
+ }
154
+ return names.flatMap((name) => {
155
+ const match = ENTRY_NAME.exec(name)
156
+ return match === null ? [] : [{ name, seq: Number(match[1]) }]
157
+ })
158
+ }
159
+
160
+ /** How long a numbered entry may stay unreadable before it counts as dead: one small write takes
161
+ * far less, so an entry still empty after this was left by a server killed in that write. */
162
+ const UNREADABLE_ENTRY_MS = 5_000
163
+
164
+ /** The entries `directory` holds, or undefined when one of them could not be read yet: a numbered
165
+ * file that is still empty or half-written (placed by an exclusive create where the file system
166
+ * has no hard links), which no look may decide past. Such a file older than
167
+ * `UNREADABLE_ENTRY_MS` counts as dead, so a server killed in that write blocks no owner for
168
+ * long. */
169
+ async function readEntries(
170
+ directory: string,
171
+ now: () => number = Date.now,
172
+ ): Promise<CodexServerEntry[] | undefined> {
173
+ const entries: CodexServerEntry[] = []
174
+ for (const { name, seq } of await entryNames(directory)) {
175
+ let text: string
176
+ try {
177
+ text = await readFile(join(directory, name), "utf8")
178
+ } catch {
179
+ continue // Removed meanwhile.
180
+ }
181
+ let parsed: { pid?: unknown; started?: unknown } | undefined
182
+ try {
183
+ parsed = JSON.parse(text) as { pid?: unknown; started?: unknown }
184
+ } catch {
185
+ parsed = undefined
186
+ }
187
+ if (typeof parsed?.pid !== "number") {
188
+ const written = await stat(join(directory, name)).then(
189
+ (info) => info.mtimeMs,
190
+ () => undefined,
191
+ )
192
+ if (written === undefined || now() - written > UNREADABLE_ENTRY_MS) continue
193
+ return undefined
194
+ }
195
+ entries.push({
196
+ pid: parsed.pid,
197
+ seq,
198
+ started: typeof parsed.started === "string" ? parsed.started : null,
199
+ })
200
+ }
201
+ return entries
202
+ }
203
+
204
+ /** The live server that owns the session: the live entry with the lowest number; undefined when
205
+ * there is none, or when an entry could not be read yet and no answer can be given. */
206
+ export async function currentOwner(
207
+ directory: string,
208
+ probe: ProcessProbe = SYSTEM_PROBE,
209
+ ): Promise<CodexServerEntry | undefined> {
210
+ const entries = await readEntries(directory)
211
+ if (entries === undefined) return undefined
212
+ const live = entries.filter((entry) => serverAlive(entry, probe))
213
+ live.sort((a, b) => a.seq - b.seq)
214
+ return live[0]
215
+ }
216
+
217
+ /**
218
+ * Resolves with `self`'s entry once it owns the session, looking every `pollMs`, or undefined when
219
+ * `signal` aborts. It publishes the entry first, and tells `published` each entry it publishes, so
220
+ * a server that stops while it stands by removes its own. A look that finds the entry gone (a
221
+ * failed write, or a directory someone removed) publishes it again, at the back of the order,
222
+ * after removing the one it had. The server owns when the owner is any entry of its own pid.
223
+ */
224
+ export function waitForOwnership(
225
+ directory: string,
226
+ pid: number,
227
+ started: string | null,
228
+ signal: AbortSignal,
229
+ published: (entry: CodexServerEntry) => void = () => undefined,
230
+ pollMs = 1_000,
231
+ probe: ProcessProbe = SYSTEM_PROBE,
232
+ ): Promise<CodexServerEntry | undefined> {
233
+ return new Promise((done) => {
234
+ let self: CodexServerEntry | undefined
235
+ let timer: ReturnType<typeof setTimeout> | undefined
236
+ const look = async (): Promise<void> => {
237
+ if (signal.aborted) return done(undefined)
238
+ const entries = await readEntries(directory)
239
+ if (
240
+ entries !== undefined &&
241
+ (self === undefined || !entries.some((entry) => entry.seq === self?.seq))
242
+ ) {
243
+ if (self !== undefined) await unregisterServer(directory, self)
244
+ self = await registerServer(directory, pid, started)
245
+ published(self)
246
+ }
247
+ const owner = await currentOwner(directory, probe)
248
+ if (owner?.pid === pid) done(self)
249
+ else timer = setTimeout(() => void look().catch(retry), pollMs)
250
+ }
251
+ const retry = (): void => {
252
+ timer = setTimeout(() => void look().catch(retry), pollMs)
253
+ }
254
+ signal.addEventListener("abort", () => {
255
+ if (timer !== undefined) clearTimeout(timer)
256
+ done(undefined)
257
+ })
258
+ void look().catch(retry)
259
+ })
260
+ }
261
+
262
+ /** Whether `self` still owns the session. The owner re-checks every few seconds and warns when it
263
+ * finds another owner, which the order of publication rules out while every entry is readable. */
264
+ export async function stillOwner(
265
+ directory: string,
266
+ self: CodexServerEntry,
267
+ probe: ProcessProbe = SYSTEM_PROBE,
268
+ ): Promise<boolean> {
269
+ const entries = await readEntries(directory)
270
+ if (entries === undefined) return true
271
+ const owner = await currentOwner(directory, probe)
272
+ return owner === undefined || owner.pid === self.pid
273
+ }