@sjawhar/claude-envoy 4.0.1 → 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,308 @@
1
+ import { spawnSync } from "node:child_process"
2
+ import { readFileSync, readlinkSync, unwatchFile, watchFile } from "node:fs"
3
+ import { mkdir, readFile, rename, utimes, writeFile } from "node:fs/promises"
4
+ import { homedir } from "node:os"
5
+ import { basename, dirname, join } from "node:path"
6
+ import { z } from "zod"
7
+ import { processExists } from "../session-identity"
8
+ import { pruneStateDirectory } from "../session-state"
9
+
10
+ /**
11
+ * How the Codex plugin's MCP server learns which session it serves.
12
+ *
13
+ * Codex starts the plugin's MCP server as a child of the `codex` process with a stripped
14
+ * environment and no session id, and runs the plugin's hooks as children of that same process
15
+ * with the session's id in their input. So the `SessionStart` hook writes this record under the
16
+ * `codex` process's id, and the server, whose parent that process is, reads it. `SessionStart`
17
+ * runs at the session's first prompt and again after `/new`, with the new session's id. Codex
18
+ * starts one server per thread, so a process can have several; the one that owns the process's
19
+ * session (`./codex-owner`) follows the record to each session the process runs. Measured on Codex
20
+ * CLI 0.154.0.
21
+ */
22
+ export const CodexSessionRecord = z.object({
23
+ session_id: z.string().min(1),
24
+ transcript_path: z.string().nullable(),
25
+ codex_home: z.string().min(1),
26
+ cwd: z.string().min(1),
27
+ source: z.string().nullable(),
28
+ /** The `codex` binary the session runs (`/proc/<pid>/exe`), or null where it cannot be read. */
29
+ codex_executable: z.string().nullable(),
30
+ /** When the `codex` process started (`processStarted`: `/proc/<pid>/stat`, or `ps` where there
31
+ * is no /proc). A record whose start is not the server's parent's was written by an earlier
32
+ * process that had the same id, and names nothing the server runs under; the hook writes no
33
+ * record where the start cannot be read. Null only in a record of an earlier build. */
34
+ codex_started: z.string().nullable().default(null),
35
+ })
36
+ export type CodexSessionRecord = z.infer<typeof CodexSessionRecord>
37
+
38
+ /** The file the record for the `codex` process `pid` lives in. */
39
+ export function codexSessionRecordFile(stateDirectory: string, pid: number): string {
40
+ return join(stateDirectory, "codex-sessions", `${pid}.json`)
41
+ }
42
+
43
+ /**
44
+ * The marker the `SessionEnd` hook leaves when session `sessionId` of `codex` process `pid` ended:
45
+ * a file of its own beside the record, so the hook never rewrites a record a `SessionStart` may be
46
+ * writing at that moment. A `SessionStart` that names the session again (`/resume`) removes it.
47
+ */
48
+ export function codexEndedFile(stateDirectory: string, pid: number, sessionId: string): string {
49
+ return join(stateDirectory, "codex-sessions", `${pid}.${encodeURIComponent(sessionId)}.ended`)
50
+ }
51
+
52
+ /**
53
+ * Leaves session `sessionId`'s ended marker, then touches the record's times, unchanged: a server
54
+ * watches the record file (`fs.watchFile`, which polls its stat), so the touch is what makes the
55
+ * owning server read the marker, and so stop delivering into the ended thread, as soon as it is
56
+ * there rather than at the next `SessionStart`.
57
+ */
58
+ export async function markSessionEnded(
59
+ stateDirectory: string,
60
+ pid: number,
61
+ sessionId: string,
62
+ ): Promise<void> {
63
+ const marker = codexEndedFile(stateDirectory, pid, sessionId)
64
+ await mkdir(dirname(marker), { mode: 0o700, recursive: true })
65
+ await writeFile(marker, "", { mode: 0o600 })
66
+ const now = new Date()
67
+ await utimes(codexSessionRecordFile(stateDirectory, pid), now, now)
68
+ }
69
+
70
+ /**
71
+ * Calls `changed` with the record and whether its session has ended each time the record file's stat
72
+ * changes (a new record, or `markSessionEnded`'s touch), and once at once: a marker left before the
73
+ * watch began, when nothing would move the stat again, is read all the same. Answers the stop.
74
+ */
75
+ export function watchRecord(
76
+ file: string,
77
+ pid: number,
78
+ ended: (sessionId: string) => Promise<boolean>,
79
+ changed: (record: CodexSessionRecord, ended: boolean) => void,
80
+ intervalMs: number,
81
+ ): () => void {
82
+ const look = (): void => {
83
+ void readCodexSessionRecord(file).then(async (record) => {
84
+ if (record === undefined || !recordOfProcess(record, pid)) return
85
+ changed(record, await ended(record.session_id))
86
+ })
87
+ }
88
+ watchFile(file, { interval: intervalMs }, look)
89
+ look()
90
+ return () => unwatchFile(file, look)
91
+ }
92
+
93
+ /** Whether the marker `codexEndedFile` names is there. */
94
+ export async function sessionEnded(file: string): Promise<boolean> {
95
+ try {
96
+ await readFile(file)
97
+ return true
98
+ } catch {
99
+ return false
100
+ }
101
+ }
102
+
103
+ /** Writes the record whole, through a temporary file renamed into place. */
104
+ export async function writeCodexSessionRecord(
105
+ file: string,
106
+ value: CodexSessionRecord,
107
+ ): Promise<void> {
108
+ await mkdir(dirname(file), { recursive: true, mode: 0o700 })
109
+ const temporary = `${file}.${process.pid}.tmp`
110
+ await writeFile(temporary, JSON.stringify(value), { mode: 0o600 })
111
+ await rename(temporary, file)
112
+ }
113
+
114
+ /** The record in `file`, or undefined when there is none or it does not parse. */
115
+ export async function readCodexSessionRecord(
116
+ file: string,
117
+ ): Promise<CodexSessionRecord | undefined> {
118
+ try {
119
+ const parsed = CodexSessionRecord.safeParse(JSON.parse(await readFile(file, "utf8")))
120
+ return parsed.success ? parsed.data : undefined
121
+ } catch {
122
+ return undefined
123
+ }
124
+ }
125
+
126
+ /** Codex's home as the person runs it: `CODEX_HOME`, else `~/.codex`, Codex's own default. */
127
+ export function codexHome(env: Readonly<Record<string, string | undefined>>): string {
128
+ const set = env["CODEX_HOME"]
129
+ return set !== undefined && set !== "" ? set : join(env["HOME"] || homedir(), ".codex")
130
+ }
131
+
132
+ /**
133
+ * The plugin's state directory, worked out from where Codex installed the plugin. A hook is handed
134
+ * it as `PLUGIN_DATA`; the MCP server is not, but runs in the plugin's own directory, which Codex
135
+ * installs at `<Codex home>/plugins/cache/<marketplace>/<plugin>/<version>` and whose state
136
+ * directory is `<Codex home>/plugins/data/<plugin>-<marketplace>` (measured on 0.154.0). Answers
137
+ * undefined for a directory of any other shape.
138
+ */
139
+ export function codexPluginDataDirectory(pluginRoot: string): string | undefined {
140
+ const version = pluginRoot
141
+ const plugin = dirname(version)
142
+ const marketplace = dirname(plugin)
143
+ const cache = dirname(marketplace)
144
+ const plugins = dirname(cache)
145
+ if (basename(cache) !== "cache" || basename(plugins) !== "plugins") return undefined
146
+ return join(plugins, "data", `${basename(plugin)}-${basename(marketplace)}`)
147
+ }
148
+
149
+ /** How many parents `codexProcessId` follows before it gives up. */
150
+ const MAX_ANCESTORS = 16
151
+
152
+ /**
153
+ * The `codex` process this process belongs to: the nearest ancestor Linux names `codex`, else the
154
+ * parent. Codex runs a hook's command through a shell, which runs a single command in its own
155
+ * place, so the parent is normally `codex` itself; the walk covers a shell that does not.
156
+ */
157
+ export function codexProcessId(
158
+ readComm: (pid: number) => string | undefined = procComm,
159
+ readParent: (pid: number) => number | undefined = procParent,
160
+ ): number {
161
+ let pid: number | undefined = process.ppid
162
+ for (let step = 0; pid !== undefined && pid > 1 && step < MAX_ANCESTORS; step++) {
163
+ if (readComm(pid) === "codex") return pid
164
+ pid = readParent(pid)
165
+ }
166
+ return process.ppid
167
+ }
168
+
169
+ function procComm(pid: number): string | undefined {
170
+ try {
171
+ return readFileSync(`/proc/${pid}/comm`, "utf8").trim()
172
+ } catch {
173
+ return undefined
174
+ }
175
+ }
176
+
177
+ function procParent(pid: number): number | undefined {
178
+ try {
179
+ const stat = readFileSync(`/proc/${pid}/stat`, "utf8")
180
+ const parent = Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[1])
181
+ return Number.isInteger(parent) ? parent : undefined
182
+ } catch {
183
+ return undefined
184
+ }
185
+ }
186
+
187
+ /** How the hook and the server run `ps`: in one fixed environment, so the start time each prints
188
+ * is the same text (macOS's `ps` formats it by the locale and the time zone), and briefly. */
189
+ const PS_OPTIONS = {
190
+ encoding: "utf8",
191
+ env: { LC_ALL: "C", PATH: process.env["PATH"] ?? "/usr/bin:/bin", TZ: "UTC" },
192
+ timeout: 1_000,
193
+ } as const
194
+
195
+ /** When process `pid` started: the 22nd field of `/proc/<pid>/stat` (clock ticks since boot), or
196
+ * where there is no /proc, `ps`'s start time to the second, prefixed `ps:`; undefined where
197
+ * neither can be read. Two processes that had one id never share it. */
198
+ export function processStarted(pid: number): string | undefined {
199
+ try {
200
+ const stat = readFileSync(`/proc/${pid}/stat`, "utf8")
201
+ return stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19]
202
+ } catch {
203
+ // No /proc (macOS): `ps` names the start to the second, which a reused pid does not repeat
204
+ // within a second of the process it replaced exiting, and the hook and the server read it
205
+ // the same way.
206
+ const ps = spawnSync("ps", ["-o", "lstart=", "-p", String(pid)], PS_OPTIONS)
207
+ const started = ps.status === 0 ? ps.stdout.trim() : ""
208
+ return started === "" ? undefined : `ps:${started}`
209
+ }
210
+ }
211
+
212
+ /** Whether `record` belongs to the `codex` process `pid` now runs, rather than to an earlier
213
+ * process that had the same id. A record or a process whose start cannot be read is not taken:
214
+ * records outlive their process, and a new `codex` that reused the pid would otherwise bind to the
215
+ * old one's session and register it until its first prompt. */
216
+ export function recordOfProcess(record: CodexSessionRecord, pid: number): boolean {
217
+ const started = processStarted(pid)
218
+ return record.codex_started !== null && started !== undefined && record.codex_started === started
219
+ }
220
+
221
+ /**
222
+ * Whether the `codex` process `pid` is Codex's shared app server (`codex app-server`), which runs
223
+ * several sessions in one process: a later plain `codex` reuses one `codex agents` started, and
224
+ * Codex 0.170.0's terminal runs every session in a background `codex app-server --managed-daemon`
225
+ * (measured on 0.170.0). This plugin keys a session by its process, so there two sessions would
226
+ * share one record and one hand-off, and one would take the other's identity, so it registers none
227
+ * of them with Envoy; `dispatch` still acts as the thread that calls it.
228
+ */
229
+ export function sharedAppServer(pid: number): boolean {
230
+ let argv: string[]
231
+ try {
232
+ argv = readFileSync(`/proc/${pid}/cmdline`, "utf8").split("\0")
233
+ } catch {
234
+ const ps = spawnSync("ps", ["-o", "args=", "-p", String(pid)], PS_OPTIONS)
235
+ if (ps.status !== 0) return false
236
+ argv = ps.stdout.trim().split(/\s+/)
237
+ }
238
+ return SHARED_SUBCOMMANDS.has(codexSubcommand(argv.slice(1)) ?? "")
239
+ }
240
+
241
+ /** The subcommands that run several sessions in one process: `app-server` (the daemon `codex agents`
242
+ * and 0.170.0's terminal start) and `agents` (`codex agents --no-daemon` runs the app server inside
243
+ * its own process, 0.170.0). */
244
+ const SHARED_SUBCOMMANDS = new Set(["agents", "app-server"])
245
+
246
+ /** The options of `codex` that take a value as the next argument (`codex --help`, 0.154.0). */
247
+ const VALUE_OPTIONS = new Set([
248
+ "-c",
249
+ "--config",
250
+ "--enable",
251
+ "--disable",
252
+ "--remote",
253
+ "--remote-auth-token-env",
254
+ "-i",
255
+ "--image",
256
+ "-m",
257
+ "--model",
258
+ "--local-provider",
259
+ "-p",
260
+ "--profile",
261
+ "-s",
262
+ "--sandbox",
263
+ "-a",
264
+ "--ask-for-approval",
265
+ "-C",
266
+ "--cd",
267
+ "--add-dir",
268
+ ])
269
+
270
+ /** The subcommand of a `codex` command line (its arguments after the binary): the first argument
271
+ * that is neither an option nor an option's value, or undefined when there is none. */
272
+ export function codexSubcommand(args: readonly string[]): string | undefined {
273
+ for (let index = 0; index < args.length; index++) {
274
+ const arg = args[index] ?? ""
275
+ if (arg === "--") return args[index + 1]
276
+ if (!arg.startsWith("-")) return arg
277
+ if (VALUE_OPTIONS.has(arg)) index++
278
+ }
279
+ return undefined
280
+ }
281
+
282
+ /** What a session of the shared app server is told about Envoy and Dispatch. */
283
+ export const SHARED_APP_SERVER_NOTE =
284
+ "Codex runs this session in its shared app server (`codex app-server`), which runs several sessions in one process, so the Envoy plugin does not register it with Envoy: it receives no Envoy messages and does not show on Dispatch's Agents page. Its `dispatch` tool works, acting as this session."
285
+
286
+ /** Removes what `codex` processes that have exited left (their records, ended markers and server
287
+ * entries), so a later process that reuses a pid never finds any of it. */
288
+ export async function pruneCodexSessionRecords(stateDirectory: string): Promise<void> {
289
+ // Records and ended markers, then the server entries (`./codex-owner`), of exited codex pids.
290
+ await pruneStateDirectory(join(stateDirectory, "codex-sessions"), (file) => {
291
+ const match = /^(\d+)\.(?:json|.+\.ended)$/.exec(basename(file))
292
+ return match !== null && !processExists(Number(match[1]))
293
+ })
294
+ await pruneStateDirectory(join(stateDirectory, "codex-servers"), (file) => {
295
+ const name = basename(file)
296
+ return /^\d+$/.test(name) && !processExists(Number(name))
297
+ })
298
+ }
299
+
300
+ /** The binary the `codex` process `pid` runs, so the plugin calls the same Codex the session
301
+ * runs; undefined where the process cannot be read. */
302
+ export function codexExecutable(pid: number): string | undefined {
303
+ try {
304
+ return readlinkSync(`/proc/${pid}/exe`)
305
+ } catch {
306
+ return undefined
307
+ }
308
+ }
@@ -0,0 +1,373 @@
1
+ import { type FSWatcher, watch } from "node:fs"
2
+ import { open } from "node:fs/promises"
3
+ import { join } from "node:path"
4
+
5
+ /**
6
+ * What a Codex session's transcript says, one line at a time.
7
+ *
8
+ * Codex appends each session to one JSON-lines file as it runs (`<Codex home>/sessions/<date>/
9
+ * rollout-<time>-<session id>.jsonl`; every hook is handed its path as `transcript_path`). Each
10
+ * line is `{timestamp, type, payload}`. This reads the few kinds the Codex plugin needs - a turn's
11
+ * start and end, the model and effort a turn ran with, what the person typed, what the model
12
+ * wrote, and each tool call and its output - and ignores every other kind, so a Codex release
13
+ * that adds one changes nothing here. Measured on Codex CLI 0.154.0.
14
+ */
15
+ export type CodexTranscriptEvent =
16
+ | { readonly kind: "turn-started"; readonly turnId: string; readonly at: number }
17
+ | { readonly kind: "turn-ended"; readonly turnId: string | undefined; readonly at: number }
18
+ | {
19
+ readonly kind: "settings"
20
+ readonly model: string
21
+ readonly effort: string | null
22
+ readonly at: number
23
+ }
24
+ | { readonly kind: "user"; readonly id: string; readonly text: string; readonly at: number }
25
+ | { readonly kind: "assistant"; readonly id: string; readonly text: string; readonly at: number }
26
+ | { readonly kind: "reasoning"; readonly id: string; readonly text: string; readonly at: number }
27
+ | {
28
+ readonly kind: "tool-call"
29
+ readonly callId: string
30
+ readonly name: string
31
+ readonly arguments: string
32
+ readonly at: number
33
+ }
34
+ | {
35
+ readonly kind: "tool-result"
36
+ readonly callId: string
37
+ readonly output: string
38
+ readonly at: number
39
+ }
40
+
41
+ type Json = Record<string, unknown>
42
+
43
+ function record(value: unknown): Json | undefined {
44
+ return typeof value === "object" && value !== null && !Array.isArray(value)
45
+ ? (value as Json)
46
+ : undefined
47
+ }
48
+
49
+ function text(value: unknown): string | undefined {
50
+ return typeof value === "string" ? value : undefined
51
+ }
52
+
53
+ /** The text of a content list: every part that carries a `text` string, joined by newlines. */
54
+ function contentText(content: unknown): string {
55
+ if (typeof content === "string") return content
56
+ if (!Array.isArray(content)) return ""
57
+ const pieces: string[] = []
58
+ for (const part of content) {
59
+ const piece = text(record(part)?.["text"])
60
+ if (piece !== undefined) pieces.push(piece)
61
+ }
62
+ return pieces.join("\n")
63
+ }
64
+
65
+ /** A tool call's output as text: Codex writes a string, or a list of content parts. */
66
+ function outputText(output: unknown): string {
67
+ if (typeof output === "string") return output
68
+ const asRecord = record(output)
69
+ if (asRecord !== undefined) return contentText(asRecord["content"] ?? asRecord["body"])
70
+ return contentText(output)
71
+ }
72
+
73
+ /** The line's own timestamp in milliseconds, or `fallback` when it has none Codex wrote. */
74
+ function lineTime(line: Json, fallback: number): number {
75
+ const stamp = text(line["timestamp"])
76
+ const parsed = stamp === undefined ? Number.NaN : Date.parse(stamp)
77
+ return Number.isFinite(parsed) ? parsed : fallback
78
+ }
79
+
80
+ /**
81
+ * The events one transcript line holds: none for a line this reader does not use or cannot
82
+ * parse. `now` stands in for a line with no timestamp of its own.
83
+ */
84
+ export function transcriptEvents(raw: string, now: number = Date.now()): CodexTranscriptEvent[] {
85
+ let parsed: unknown
86
+ try {
87
+ parsed = JSON.parse(raw)
88
+ } catch {
89
+ return []
90
+ }
91
+ const line = record(parsed)
92
+ const payload = record(line?.["payload"])
93
+ if (line === undefined || payload === undefined) return []
94
+ const at = lineTime(line, now)
95
+ const kind = text(payload["type"])
96
+ switch (line["type"]) {
97
+ case "event_msg": {
98
+ if (kind === "task_started") {
99
+ const turnId = text(payload["turn_id"])
100
+ return turnId === undefined ? [] : [{ at, kind: "turn-started", turnId }]
101
+ }
102
+ if (kind === "task_complete" || kind === "turn_aborted") {
103
+ return [{ at, kind: "turn-ended", turnId: text(payload["turn_id"]) }]
104
+ }
105
+ // What the person sent, as Codex's own record of the user turn: the model-facing user
106
+ // messages beside it also carry the environment and instruction blocks Codex adds.
107
+ if (kind === "item_completed") {
108
+ const item = record(payload["item"])
109
+ const id = text(item?.["id"])
110
+ if (item?.["type"] === "UserMessage" && id !== undefined) {
111
+ return [{ at, id, kind: "user", text: contentText(item["content"]) }]
112
+ }
113
+ }
114
+ return []
115
+ }
116
+ case "turn_context": {
117
+ const model = text(payload["model"])
118
+ if (model === undefined) return []
119
+ const settings = record(record(payload["collaboration_mode"])?.["settings"])
120
+ const effort = text(settings?.["reasoning_effort"]) ?? text(payload["effort"]) ?? null
121
+ return [{ at, effort, kind: "settings", model }]
122
+ }
123
+ case "response_item": {
124
+ if (kind === "message" && payload["role"] === "assistant") {
125
+ const id = text(payload["id"]) ?? `assistant-${at}`
126
+ return [{ at, id, kind: "assistant", text: contentText(payload["content"]) }]
127
+ }
128
+ if (kind === "reasoning") {
129
+ const summary = contentText(payload["summary"])
130
+ if (summary === "") return []
131
+ return [
132
+ { at, id: text(payload["id"]) ?? `reasoning-${at}`, kind: "reasoning", text: summary },
133
+ ]
134
+ }
135
+ if (kind === "function_call" || kind === "custom_tool_call") {
136
+ const callId = text(payload["call_id"])
137
+ if (callId === undefined) return []
138
+ const args = payload["arguments"] ?? payload["input"]
139
+ return [
140
+ {
141
+ arguments: typeof args === "string" ? args : JSON.stringify(args ?? {}),
142
+ at,
143
+ callId,
144
+ kind: "tool-call",
145
+ name: text(payload["name"]) ?? "tool",
146
+ },
147
+ ]
148
+ }
149
+ if (kind === "function_call_output" || kind === "custom_tool_call_output") {
150
+ const callId = text(payload["call_id"])
151
+ if (callId === undefined) return []
152
+ return [{ at, callId, kind: "tool-result", output: outputText(payload["output"]) }]
153
+ }
154
+ return []
155
+ }
156
+ default:
157
+ return []
158
+ }
159
+ }
160
+
161
+ export interface TranscriptFollower {
162
+ /** Stops reading; the callback is not called again. */
163
+ stop(): void
164
+ /** Resolves once everything the file held when the follower started has been handed over. */
165
+ readonly caughtUp: Promise<void>
166
+ }
167
+
168
+ /** How often a follower looks at the file again when no change notification arrived. */
169
+ const TRANSCRIPT_POLL_MS = 500
170
+
171
+ /**
172
+ * Hands every line of the transcript at `path` to `onLine`, from its first line, then each line
173
+ * Codex appends, whole lines only: a line still being written waits for its newline. A file that
174
+ * does not exist yet is waited for. Change notifications wake it early; a poll covers a
175
+ * filesystem that sends none.
176
+ */
177
+ export function followTranscript(
178
+ path: string,
179
+ onLine: (line: string) => void,
180
+ options: { readonly pollMs?: number; readonly warn?: (text: string) => void } = {},
181
+ ): TranscriptFollower {
182
+ const pollMs = options.pollMs ?? TRANSCRIPT_POLL_MS
183
+ let offset = 0
184
+ let partial = ""
185
+ let stopped = false
186
+ let reading = false
187
+ let again = false
188
+ let watcher: FSWatcher | undefined
189
+ const caughtUp = Promise.withResolvers<void>()
190
+ const decoder = new TextDecoder()
191
+
192
+ const read = async (): Promise<void> => {
193
+ if (stopped) return
194
+ if (reading) {
195
+ again = true
196
+ return
197
+ }
198
+ reading = true
199
+ try {
200
+ do {
201
+ again = false
202
+ let handle: Awaited<ReturnType<typeof open>> | undefined
203
+ try {
204
+ handle = await open(path, "r")
205
+ } catch {
206
+ return
207
+ }
208
+ try {
209
+ const { size } = await handle.stat()
210
+ if (size < offset) {
211
+ // The file was replaced or cut: read it again from the start.
212
+ offset = 0
213
+ partial = ""
214
+ }
215
+ while (offset < size && !stopped) {
216
+ const buffer = new Uint8Array(Math.min(size - offset, 1 << 20))
217
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, offset)
218
+ if (bytesRead === 0) break
219
+ offset += bytesRead
220
+ partial += decoder.decode(buffer.subarray(0, bytesRead), { stream: true })
221
+ let newline = partial.indexOf("\n")
222
+ while (newline >= 0) {
223
+ const line = partial.slice(0, newline)
224
+ partial = partial.slice(newline + 1)
225
+ if (line.trim() !== "" && !stopped) onLine(line)
226
+ newline = partial.indexOf("\n")
227
+ }
228
+ }
229
+ caughtUp.resolve()
230
+ } finally {
231
+ await handle.close()
232
+ }
233
+ if (watcher === undefined && !stopped) {
234
+ try {
235
+ watcher = watch(path, () => void read())
236
+ watcher.on("error", () => undefined)
237
+ } catch {
238
+ // No change notifications here: the poll below reads the file anyway.
239
+ }
240
+ }
241
+ } while (again && !stopped)
242
+ } catch (error) {
243
+ options.warn?.(`could not read the Codex transcript ${path}: ${String(error)}`)
244
+ } finally {
245
+ reading = false
246
+ }
247
+ }
248
+
249
+ const timer = setInterval(() => void read(), pollMs)
250
+ timer.unref?.()
251
+ void read()
252
+ return {
253
+ caughtUp: caughtUp.promise,
254
+ stop: () => {
255
+ stopped = true
256
+ clearInterval(timer)
257
+ watcher?.close()
258
+ caughtUp.resolve()
259
+ },
260
+ }
261
+ }
262
+
263
+ /** How much `latestTurnCwd` reads at a time, walking back from the transcript's end. */
264
+ const TURN_CWD_CHUNK_BYTES = 256 * 1024
265
+ /** The longest line `latestTurnCwd` keeps whole; a `turn_context` line is a few kilobytes. */
266
+ const TURN_CWD_LINE_MAX_BYTES = 1024 * 1024
267
+
268
+ /**
269
+ * The directory the session's newest turn ran in, from the last `turn_context` line of its
270
+ * transcript (`payload.cwd`, which Codex writes at every turn, measured on 0.154.0): where a
271
+ * `/cd` moved the session, and not the directory `SessionStart` named. It reads the file back
272
+ * from its end a chunk at a time until it meets such a line, so a long turn costs only the reads
273
+ * it takes to pass it. Undefined when the file cannot be read or holds no such line.
274
+ */
275
+ export async function latestTurnCwd(transcriptPath: string | null): Promise<string | undefined> {
276
+ if (transcriptPath === null) return undefined
277
+ let handle: Awaited<ReturnType<typeof open>> | undefined
278
+ try {
279
+ handle = await open(transcriptPath, "r")
280
+ let end = (await handle.stat()).size
281
+ // The bytes after the earliest newline read so far: the start of a line a later chunk completes.
282
+ let carry = Buffer.alloc(0)
283
+ // Set once that line has grown past `TURN_CWD_LINE_MAX_BYTES`: no `turn_context` is that long,
284
+ // so the rest of it is skipped rather than copied at every chunk.
285
+ let dropping = false
286
+ while (end > 0) {
287
+ const length = Math.min(end, TURN_CWD_CHUNK_BYTES)
288
+ const chunk = Buffer.alloc(length)
289
+ await handle.read(chunk, 0, length, end - length)
290
+ end -= length
291
+ const joined = dropping ? chunk : Buffer.concat([chunk, carry])
292
+ const firstNewline = end === 0 ? -1 : joined.indexOf(10)
293
+ if (firstNewline < 0 && end > 0) {
294
+ // No line starts in this chunk: all of it belongs to a line an earlier chunk completes.
295
+ if (!dropping && joined.length > TURN_CWD_LINE_MAX_BYTES) dropping = true
296
+ carry = dropping ? Buffer.alloc(0) : joined
297
+ continue
298
+ }
299
+ // While dropping, what follows this chunk's last newline is the over-long line's start.
300
+ const stop = dropping ? Math.max(joined.lastIndexOf(10), 0) : joined.length
301
+ dropping = false
302
+ const whole = joined
303
+ .subarray(firstNewline + 1, Math.max(stop, firstNewline + 1))
304
+ .toString("utf8")
305
+ .split("\n")
306
+ carry = firstNewline < 0 ? Buffer.alloc(0) : joined.subarray(0, firstNewline)
307
+ for (let index = whole.length - 1; index >= 0; index--) {
308
+ const cwd = turnContextCwd(whole[index] ?? "")
309
+ if (cwd !== undefined) return cwd
310
+ }
311
+ }
312
+ return undefined
313
+ } catch {
314
+ return undefined
315
+ } finally {
316
+ await handle?.close().catch(() => undefined)
317
+ }
318
+ }
319
+
320
+ /** A transcript line's `turn_context` directory, or undefined for any other line. */
321
+ function turnContextCwd(line: string): string | undefined {
322
+ if (!line.includes('"turn_context"')) return undefined
323
+ try {
324
+ const parsed = JSON.parse(line) as { type?: unknown; payload?: { cwd?: unknown } }
325
+ return parsed.type === "turn_context" && typeof parsed.payload?.cwd === "string"
326
+ ? parsed.payload.cwd
327
+ : undefined
328
+ } catch {
329
+ return undefined
330
+ }
331
+ }
332
+
333
+ /**
334
+ * The transcript of thread `threadId` under the Codex home `home`: Codex writes each session to
335
+ * `sessions/<yyyy>/<mm>/<dd>/rollout-<time>-<thread id>.jsonl` (measured on 0.154.0). The newest
336
+ * such file when there are several; null when there is none or the id is not a thread id's shape.
337
+ * A found path is kept for the life of the process, since the scan reads the whole tree.
338
+ */
339
+ const foundTranscripts = new Map<string, string>()
340
+ const missedTranscripts = new Map<string, number>()
341
+ /** How long a thread `findTranscript` found no transcript for is not looked for again. */
342
+ const TRANSCRIPT_MISS_MS = 30_000
343
+
344
+ /** Whether `id` has the shape of a Codex thread id: letters, digits and hyphens, nothing a path
345
+ * or a glob could read otherwise. */
346
+ export function threadIdShape(id: string): boolean {
347
+ return /^[0-9A-Za-z-]+$/.test(id)
348
+ }
349
+
350
+ export async function findTranscript(home: string, threadId: string): Promise<string | null> {
351
+ if (!threadIdShape(threadId)) return null
352
+ const key = `${home}\0${threadId}`
353
+ const known = foundTranscripts.get(key)
354
+ if (known !== undefined) return known
355
+ // A thread with no transcript (a fork's) is looked for again only after a while, not at every
356
+ // call, since the scan reads the whole tree.
357
+ const missed = missedTranscripts.get(key)
358
+ if (missed !== undefined && Date.now() - missed < TRANSCRIPT_MISS_MS) return null
359
+ const glob = new Bun.Glob(`**/rollout-*-${threadId}.jsonl`)
360
+ const found: string[] = []
361
+ try {
362
+ for await (const file of glob.scan({ absolute: true, cwd: join(home, "sessions") })) {
363
+ found.push(file)
364
+ }
365
+ } catch {
366
+ return null
367
+ }
368
+ const newest = found.sort().at(-1)
369
+ // A thread's transcript keeps its path, so a found one is not searched for again.
370
+ if (newest !== undefined) foundTranscripts.set(key, newest)
371
+ else missedTranscripts.set(key, Date.now())
372
+ return newest ?? null
373
+ }