@kodelyth/codex 2026.5.42 → 2026.6.2

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.
Files changed (138) hide show
  1. package/package.json +17 -2
  2. package/doctor-contract-api.test.ts +0 -44
  3. package/doctor-contract-api.ts +0 -68
  4. package/harness.ts +0 -72
  5. package/index.test.ts +0 -230
  6. package/index.ts +0 -66
  7. package/media-understanding-provider.test.ts +0 -486
  8. package/media-understanding-provider.ts +0 -521
  9. package/prompt-overlay-runtime-contract.test.ts +0 -48
  10. package/prompt-overlay.ts +0 -21
  11. package/provider-catalog.ts +0 -83
  12. package/provider-discovery.ts +0 -45
  13. package/provider.test.ts +0 -384
  14. package/provider.ts +0 -243
  15. package/src/app-server/app-inventory-cache.test.ts +0 -176
  16. package/src/app-server/app-inventory-cache.ts +0 -324
  17. package/src/app-server/approval-bridge.test.ts +0 -1471
  18. package/src/app-server/approval-bridge.ts +0 -1211
  19. package/src/app-server/auth-bridge.test.ts +0 -1449
  20. package/src/app-server/auth-bridge.ts +0 -614
  21. package/src/app-server/auth-profile-runtime-contract.test.ts +0 -239
  22. package/src/app-server/capabilities.ts +0 -27
  23. package/src/app-server/client-factory.ts +0 -24
  24. package/src/app-server/client.test.ts +0 -563
  25. package/src/app-server/client.ts +0 -715
  26. package/src/app-server/compact.test.ts +0 -710
  27. package/src/app-server/compact.ts +0 -500
  28. package/src/app-server/computer-use.test.ts +0 -788
  29. package/src/app-server/computer-use.ts +0 -683
  30. package/src/app-server/config.test.ts +0 -879
  31. package/src/app-server/config.ts +0 -1038
  32. package/src/app-server/context-engine-projection.test.ts +0 -252
  33. package/src/app-server/context-engine-projection.ts +0 -403
  34. package/src/app-server/delivery-no-reply-runtime-contract.test.ts +0 -80
  35. package/src/app-server/dynamic-tool-diagnostics.ts +0 -73
  36. package/src/app-server/dynamic-tool-profile.ts +0 -69
  37. package/src/app-server/dynamic-tools.test.ts +0 -1302
  38. package/src/app-server/dynamic-tools.ts +0 -623
  39. package/src/app-server/elicitation-bridge.test.ts +0 -1056
  40. package/src/app-server/elicitation-bridge.ts +0 -783
  41. package/src/app-server/event-projector.test.ts +0 -2668
  42. package/src/app-server/event-projector.ts +0 -2057
  43. package/src/app-server/image-payload-sanitizer.test.ts +0 -49
  44. package/src/app-server/image-payload-sanitizer.ts +0 -167
  45. package/src/app-server/klaw-owned-tool-runtime-contract.test.ts +0 -456
  46. package/src/app-server/local-runtime-attribution.ts +0 -39
  47. package/src/app-server/managed-binary.test.ts +0 -139
  48. package/src/app-server/managed-binary.ts +0 -193
  49. package/src/app-server/models.test.ts +0 -246
  50. package/src/app-server/models.ts +0 -172
  51. package/src/app-server/native-hook-relay.test.ts +0 -271
  52. package/src/app-server/native-hook-relay.ts +0 -150
  53. package/src/app-server/native-subagent-task-mirror.test.ts +0 -573
  54. package/src/app-server/native-subagent-task-mirror.ts +0 -497
  55. package/src/app-server/outcome-fallback-runtime-contract.test.ts +0 -404
  56. package/src/app-server/plugin-activation.test.ts +0 -336
  57. package/src/app-server/plugin-activation.ts +0 -283
  58. package/src/app-server/plugin-app-cache-key.ts +0 -74
  59. package/src/app-server/plugin-approval-roundtrip.ts +0 -122
  60. package/src/app-server/plugin-inventory.test.ts +0 -355
  61. package/src/app-server/plugin-inventory.ts +0 -357
  62. package/src/app-server/plugin-thread-config.test.ts +0 -865
  63. package/src/app-server/plugin-thread-config.ts +0 -455
  64. package/src/app-server/protocol-generated/json/DynamicToolCallParams.json +0 -33
  65. package/src/app-server/protocol-generated/json/v2/ErrorNotification.json +0 -199
  66. package/src/app-server/protocol-generated/json/v2/GetAccountResponse.json +0 -102
  67. package/src/app-server/protocol-generated/json/v2/ModelListResponse.json +0 -227
  68. package/src/app-server/protocol-generated/json/v2/ThreadResumeResponse.json +0 -2630
  69. package/src/app-server/protocol-generated/json/v2/ThreadStartResponse.json +0 -2630
  70. package/src/app-server/protocol-generated/json/v2/TurnCompletedNotification.json +0 -1659
  71. package/src/app-server/protocol-generated/json/v2/TurnStartResponse.json +0 -1655
  72. package/src/app-server/protocol-validators.test.ts +0 -75
  73. package/src/app-server/protocol-validators.ts +0 -203
  74. package/src/app-server/protocol.ts +0 -520
  75. package/src/app-server/rate-limit-cache.ts +0 -48
  76. package/src/app-server/rate-limits.test.ts +0 -202
  77. package/src/app-server/rate-limits.ts +0 -583
  78. package/src/app-server/request.ts +0 -73
  79. package/src/app-server/run-attempt.context-engine.test.ts +0 -1004
  80. package/src/app-server/run-attempt.test.ts +0 -9477
  81. package/src/app-server/run-attempt.ts +0 -4683
  82. package/src/app-server/run-attempt.vision-tools.test.ts +0 -35
  83. package/src/app-server/schema-normalization-runtime-contract.test.ts +0 -206
  84. package/src/app-server/session-binding.test.ts +0 -303
  85. package/src/app-server/session-binding.ts +0 -398
  86. package/src/app-server/session-history.ts +0 -44
  87. package/src/app-server/shared-client.test.ts +0 -589
  88. package/src/app-server/shared-client.ts +0 -289
  89. package/src/app-server/side-question.test.ts +0 -1175
  90. package/src/app-server/side-question.ts +0 -1007
  91. package/src/app-server/test-support.ts +0 -48
  92. package/src/app-server/thread-lifecycle.test.ts +0 -447
  93. package/src/app-server/thread-lifecycle.ts +0 -939
  94. package/src/app-server/thread-lifecycle.user-mcp-servers.test.ts +0 -442
  95. package/src/app-server/timeout.ts +0 -9
  96. package/src/app-server/tool-progress-normalization.ts +0 -77
  97. package/src/app-server/trajectory.test.ts +0 -205
  98. package/src/app-server/trajectory.ts +0 -365
  99. package/src/app-server/transcript-mirror.test.ts +0 -524
  100. package/src/app-server/transcript-mirror.ts +0 -208
  101. package/src/app-server/transcript-repair-runtime-contract.test.ts +0 -44
  102. package/src/app-server/transport-stdio.test.ts +0 -171
  103. package/src/app-server/transport-stdio.ts +0 -107
  104. package/src/app-server/transport-websocket.test.ts +0 -69
  105. package/src/app-server/transport-websocket.ts +0 -90
  106. package/src/app-server/transport.ts +0 -117
  107. package/src/app-server/user-input-bridge.test.ts +0 -249
  108. package/src/app-server/user-input-bridge.ts +0 -316
  109. package/src/app-server/version.ts +0 -4
  110. package/src/app-server/vision-tools.ts +0 -12
  111. package/src/command-account.ts +0 -544
  112. package/src/command-formatters.ts +0 -425
  113. package/src/command-handlers.ts +0 -2004
  114. package/src/command-rpc.test.ts +0 -16
  115. package/src/command-rpc.ts +0 -142
  116. package/src/commands.test.ts +0 -3312
  117. package/src/commands.ts +0 -65
  118. package/src/conversation-binding-data.ts +0 -124
  119. package/src/conversation-binding.test.ts +0 -599
  120. package/src/conversation-binding.ts +0 -561
  121. package/src/conversation-control.test.ts +0 -126
  122. package/src/conversation-control.ts +0 -303
  123. package/src/conversation-turn-collector.test.ts +0 -191
  124. package/src/conversation-turn-collector.ts +0 -186
  125. package/src/conversation-turn-input.test.ts +0 -141
  126. package/src/conversation-turn-input.ts +0 -106
  127. package/src/manifest.test.ts +0 -20
  128. package/src/migration/apply.ts +0 -501
  129. package/src/migration/helpers.ts +0 -55
  130. package/src/migration/plan.ts +0 -461
  131. package/src/migration/provider.test.ts +0 -1741
  132. package/src/migration/provider.ts +0 -41
  133. package/src/migration/source.ts +0 -643
  134. package/src/migration/targets.ts +0 -25
  135. package/src/node-cli-sessions.test.ts +0 -180
  136. package/src/node-cli-sessions.ts +0 -711
  137. package/test-api.ts +0 -82
  138. package/tsconfig.json +0 -16
@@ -1,711 +0,0 @@
1
- import { spawn } from "node:child_process";
2
- import fs from "node:fs/promises";
3
- import os from "node:os";
4
- import path from "node:path";
5
- import process from "node:process";
6
- import type {
7
- KlawPluginNodeHostCommand,
8
- KlawPluginNodeInvokePolicy,
9
- } from "klaw/plugin-sdk/plugin-entry";
10
- import type { PluginRuntime } from "klaw/plugin-sdk/plugin-runtime";
11
- import { resolvePreferredKlawTmpDir } from "klaw/plugin-sdk/temp-path";
12
- import {
13
- materializeWindowsSpawnProgram,
14
- resolveWindowsSpawnProgram,
15
- } from "klaw/plugin-sdk/windows-spawn";
16
- import { formatCodexDisplayText } from "./command-formatters.js";
17
-
18
- export const CODEX_CLI_SESSIONS_LIST_COMMAND = "codex.cli.sessions.list";
19
- export const CODEX_CLI_SESSION_RESUME_COMMAND = "codex.cli.session.resume";
20
-
21
- const DEFAULT_SESSION_LIMIT = 10;
22
- const MAX_SESSION_LIMIT = 50;
23
- const DEFAULT_RESUME_TIMEOUT_MS = 20 * 60_000;
24
- const SESSION_ID_PATTERN = /^[A-Za-z0-9._:-]{1,128}$/;
25
- const activeResumeSessions = new Set<string>();
26
-
27
- export type CodexCliSessionSummary = {
28
- sessionId: string;
29
- updatedAt?: string;
30
- lastMessage?: string;
31
- cwd?: string;
32
- sessionFile?: string;
33
- messageCount: number;
34
- };
35
-
36
- export type CodexCliSessionsListResult = {
37
- sessions: CodexCliSessionSummary[];
38
- codexHome: string;
39
- };
40
-
41
- export type CodexCliSessionResumeResult = {
42
- ok: true;
43
- sessionId: string;
44
- text: string;
45
- };
46
-
47
- type CodexCliSessionNodeInfo = {
48
- nodeId?: string;
49
- displayName?: string;
50
- remoteIp?: string;
51
- connected?: boolean;
52
- commands?: string[];
53
- };
54
-
55
- type CodexCliResumeSpawnRuntime = {
56
- platform: NodeJS.Platform;
57
- env: NodeJS.ProcessEnv;
58
- execPath: string;
59
- };
60
-
61
- const DEFAULT_RESUME_SPAWN_RUNTIME: CodexCliResumeSpawnRuntime = {
62
- platform: process.platform,
63
- env: process.env,
64
- execPath: process.execPath,
65
- };
66
-
67
- export function createCodexCliSessionNodeHostCommands(): KlawPluginNodeHostCommand[] {
68
- return [
69
- {
70
- command: CODEX_CLI_SESSIONS_LIST_COMMAND,
71
- cap: "codex-cli-sessions",
72
- handle: listLocalCodexCliSessions,
73
- },
74
- {
75
- command: CODEX_CLI_SESSION_RESUME_COMMAND,
76
- cap: "codex-cli-sessions",
77
- dangerous: true,
78
- handle: resumeLocalCodexCliSession,
79
- },
80
- ];
81
- }
82
-
83
- export function createCodexCliSessionNodeInvokePolicies(): KlawPluginNodeInvokePolicy[] {
84
- return [
85
- {
86
- commands: [CODEX_CLI_SESSIONS_LIST_COMMAND],
87
- defaultPlatforms: ["macos", "linux", "windows"],
88
- handle: (ctx) => ctx.invokeNode(),
89
- },
90
- {
91
- commands: [CODEX_CLI_SESSION_RESUME_COMMAND],
92
- dangerous: true,
93
- handle: (ctx) => ctx.invokeNode(),
94
- },
95
- ];
96
- }
97
-
98
- export async function listCodexCliSessionsOnNode(params: {
99
- runtime: PluginRuntime;
100
- requestedNode?: string;
101
- filter?: string;
102
- limit?: number;
103
- }): Promise<{ node: CodexCliSessionNodeInfo; result: CodexCliSessionsListResult }> {
104
- const node = await resolveCodexCliNode({
105
- runtime: params.runtime,
106
- requestedNode: params.requestedNode,
107
- command: CODEX_CLI_SESSIONS_LIST_COMMAND,
108
- });
109
- const raw = await params.runtime.nodes.invoke({
110
- nodeId: readNodeId(node),
111
- command: CODEX_CLI_SESSIONS_LIST_COMMAND,
112
- params: {
113
- limit: params.limit,
114
- filter: params.filter,
115
- },
116
- timeoutMs: 15_000,
117
- });
118
- return { node, result: parseCodexCliSessionsListResult(raw) };
119
- }
120
-
121
- export async function resolveCodexCliSessionForBindingOnNode(params: {
122
- runtime: PluginRuntime;
123
- requestedNode: string;
124
- sessionId: string;
125
- }): Promise<{ node: CodexCliSessionNodeInfo; session?: CodexCliSessionSummary }> {
126
- const listing = await listCodexCliSessionsOnNode({
127
- runtime: params.runtime,
128
- requestedNode: params.requestedNode,
129
- filter: params.sessionId,
130
- limit: MAX_SESSION_LIMIT,
131
- });
132
- if (!listing.node.commands?.includes(CODEX_CLI_SESSION_RESUME_COMMAND)) {
133
- throw new Error(
134
- `Node ${formatNodeLabel(listing.node)} does not expose ${CODEX_CLI_SESSION_RESUME_COMMAND}.`,
135
- );
136
- }
137
- return {
138
- node: listing.node,
139
- session: listing.result.sessions.find((session) => session.sessionId === params.sessionId),
140
- };
141
- }
142
-
143
- export async function resumeCodexCliSessionOnNode(params: {
144
- runtime: PluginRuntime;
145
- nodeId: string;
146
- sessionId: string;
147
- prompt: string;
148
- cwd?: string;
149
- timeoutMs?: number;
150
- }): Promise<CodexCliSessionResumeResult> {
151
- const raw = await params.runtime.nodes.invoke({
152
- nodeId: params.nodeId,
153
- command: CODEX_CLI_SESSION_RESUME_COMMAND,
154
- params: {
155
- sessionId: params.sessionId,
156
- prompt: params.prompt,
157
- cwd: params.cwd,
158
- timeoutMs: params.timeoutMs,
159
- },
160
- timeoutMs: (params.timeoutMs ?? DEFAULT_RESUME_TIMEOUT_MS) + 5_000,
161
- });
162
- const payload = unwrapNodeInvokePayload(raw);
163
- if (!isRecord(payload) || payload.ok !== true || typeof payload.text !== "string") {
164
- throw new Error("Codex CLI resume returned an invalid payload.");
165
- }
166
- return {
167
- ok: true,
168
- sessionId: typeof payload.sessionId === "string" ? payload.sessionId : params.sessionId,
169
- text: payload.text,
170
- };
171
- }
172
-
173
- export function formatCodexCliSessions(params: {
174
- node: CodexCliSessionNodeInfo;
175
- result: CodexCliSessionsListResult;
176
- }): string {
177
- if (params.result.sessions.length === 0) {
178
- return `No Codex CLI sessions returned from ${formatCodexDisplayText(formatNodeLabel(params.node))}.`;
179
- }
180
- return [
181
- `Codex CLI sessions on ${formatCodexDisplayText(formatNodeLabel(params.node))}:`,
182
- ...params.result.sessions.map((session) => {
183
- const details = [session.cwd, session.updatedAt].filter((value): value is string =>
184
- Boolean(value),
185
- );
186
- return `- ${formatCodexDisplayText(session.sessionId)}${
187
- session.lastMessage ? ` - ${formatCodexDisplayText(session.lastMessage)}` : ""
188
- }${details.length > 0 ? ` (${details.map(formatCodexDisplayText).join(", ")})` : ""}\n Bind: /codex resume ${formatCodexDisplayText(
189
- session.sessionId,
190
- )} --host ${formatCodexDisplayText(readNodeId(params.node))} --bind here`;
191
- }),
192
- ].join("\n");
193
- }
194
-
195
- async function listLocalCodexCliSessions(paramsJSON?: string | null): Promise<string> {
196
- const params = readRecordParam(paramsJSON);
197
- const limit = normalizeLimit(params.limit);
198
- const filter = typeof params.filter === "string" ? params.filter.trim().toLowerCase() : "";
199
- const codexHome = resolveCodexHome();
200
- const summaries = await readHistorySessions(codexHome);
201
- await hydrateSessionFiles(codexHome, summaries);
202
- await hydrateSessionsFromSessionFiles(codexHome, summaries);
203
- const sessions = [...summaries.values()]
204
- .filter((session) => {
205
- if (!filter) {
206
- return true;
207
- }
208
- return [session.sessionId, session.cwd, session.lastMessage].some((value) =>
209
- value?.toLowerCase().includes(filter),
210
- );
211
- })
212
- .toSorted((a, b) => compareOptionalStringsDesc(a.updatedAt, b.updatedAt))
213
- .slice(0, limit);
214
- return JSON.stringify({ sessions, codexHome } satisfies CodexCliSessionsListResult);
215
- }
216
-
217
- async function resumeLocalCodexCliSession(paramsJSON?: string | null): Promise<string> {
218
- const params = readRecordParam(paramsJSON);
219
- const sessionId = typeof params.sessionId === "string" ? params.sessionId.trim() : "";
220
- const prompt = typeof params.prompt === "string" ? params.prompt.trim() : "";
221
- if (!sessionId || !SESSION_ID_PATTERN.test(sessionId)) {
222
- throw new Error("Missing or invalid Codex CLI session id.");
223
- }
224
- if (!prompt) {
225
- throw new Error("Missing Codex CLI prompt.");
226
- }
227
- if (activeResumeSessions.has(sessionId)) {
228
- throw new Error(`Codex CLI session ${sessionId} already has an active resume turn.`);
229
- }
230
- activeResumeSessions.add(sessionId);
231
- try {
232
- const text = await runCodexExecResume({
233
- sessionId,
234
- prompt,
235
- cwd: typeof params.cwd === "string" && params.cwd.trim() ? params.cwd.trim() : undefined,
236
- timeoutMs: normalizeTimeoutMs(params.timeoutMs),
237
- });
238
- return JSON.stringify({
239
- ok: true,
240
- sessionId,
241
- text: text.trim() || "Codex completed without a text reply.",
242
- } satisfies CodexCliSessionResumeResult);
243
- } finally {
244
- activeResumeSessions.delete(sessionId);
245
- }
246
- }
247
-
248
- async function runCodexExecResume(params: {
249
- sessionId: string;
250
- prompt: string;
251
- cwd?: string;
252
- timeoutMs: number;
253
- }): Promise<string> {
254
- const outputPath = path.join(
255
- await fs.mkdtemp(path.join(resolvePreferredKlawTmpDir(), "klaw-codex-cli-")),
256
- "last-message.txt",
257
- );
258
- try {
259
- const args = [
260
- "exec",
261
- "resume",
262
- "--skip-git-repo-check",
263
- "--output-last-message",
264
- outputPath,
265
- params.sessionId,
266
- "-",
267
- ];
268
- const invocation = resolveCodexCliResumeSpawnInvocation(args, {
269
- platform: process.platform,
270
- env: process.env,
271
- execPath: process.execPath,
272
- });
273
- const child = spawn(invocation.command, invocation.args, {
274
- cwd: params.cwd || process.cwd(),
275
- stdio: ["pipe", "pipe", "pipe"],
276
- env: process.env,
277
- shell: invocation.shell,
278
- windowsHide: invocation.windowsHide,
279
- });
280
- const stdout: Buffer[] = [];
281
- const stderr: Buffer[] = [];
282
- let timedOut = false;
283
- let forceKillTimeout: NodeJS.Timeout | undefined;
284
- const timeout = setTimeout(() => {
285
- timedOut = true;
286
- child.kill("SIGTERM");
287
- forceKillTimeout = setTimeout(() => child.kill("SIGKILL"), 2_000);
288
- forceKillTimeout.unref?.();
289
- }, params.timeoutMs);
290
- child.stdout.on("data", (chunk: Buffer) => stdout.push(chunk));
291
- child.stderr.on("data", (chunk: Buffer) => stderr.push(chunk));
292
- child.stdin.end(params.prompt);
293
- const exitCode = await new Promise<number | null>((resolve, reject) => {
294
- child.on("error", reject);
295
- child.on("exit", (code) => resolve(code));
296
- }).finally(() => {
297
- clearTimeout(timeout);
298
- if (forceKillTimeout) {
299
- clearTimeout(forceKillTimeout);
300
- }
301
- });
302
- if (timedOut) {
303
- throw new Error(`codex exec resume timed out after ${String(params.timeoutMs)}ms`);
304
- }
305
- if (exitCode !== 0) {
306
- const message =
307
- Buffer.concat(stderr).toString("utf8").trim() ||
308
- Buffer.concat(stdout).toString("utf8").trim() ||
309
- `codex exec resume exited with code ${String(exitCode)}`;
310
- throw new Error(message);
311
- }
312
- return await fs.readFile(outputPath, "utf8");
313
- } finally {
314
- await fs.rm(path.dirname(outputPath), { recursive: true, force: true });
315
- }
316
- }
317
-
318
- export function resolveCodexCliResumeSpawnInvocation(
319
- args: string[],
320
- runtime: CodexCliResumeSpawnRuntime = DEFAULT_RESUME_SPAWN_RUNTIME,
321
- ): { command: string; args: string[]; shell?: boolean; windowsHide?: boolean } {
322
- const program = resolveWindowsSpawnProgram({
323
- command: "codex",
324
- platform: runtime.platform,
325
- env: runtime.env,
326
- execPath: runtime.execPath,
327
- packageName: "@openai/codex",
328
- });
329
- const resolved = materializeWindowsSpawnProgram(program, args);
330
- return {
331
- command: resolved.command,
332
- args: resolved.argv,
333
- shell: resolved.shell,
334
- windowsHide: resolved.windowsHide,
335
- };
336
- }
337
-
338
- async function readHistorySessions(
339
- codexHome: string,
340
- ): Promise<Map<string, CodexCliSessionSummary>> {
341
- const summaries = new Map<string, CodexCliSessionSummary>();
342
- const historyPath = path.join(codexHome, "history.jsonl");
343
- const content = await readFileIfExists(historyPath);
344
- if (!content) {
345
- return summaries;
346
- }
347
- for (const line of content.split(/\r?\n/u)) {
348
- const trimmed = line.trim();
349
- if (!trimmed) {
350
- continue;
351
- }
352
- let parsed: unknown;
353
- try {
354
- parsed = JSON.parse(trimmed) as unknown;
355
- } catch {
356
- continue;
357
- }
358
- if (!isRecord(parsed) || typeof parsed.session_id !== "string") {
359
- continue;
360
- }
361
- const sessionId = parsed.session_id.trim();
362
- if (!sessionId) {
363
- continue;
364
- }
365
- const entry = summaries.get(sessionId) ?? {
366
- sessionId,
367
- messageCount: 0,
368
- };
369
- entry.messageCount += 1;
370
- if (typeof parsed.text === "string" && parsed.text.trim()) {
371
- entry.lastMessage = truncateText(parsed.text.trim(), 140);
372
- }
373
- if (typeof parsed.ts === "number" && Number.isFinite(parsed.ts)) {
374
- entry.updatedAt = new Date(parsed.ts * 1000).toISOString();
375
- }
376
- summaries.set(sessionId, entry);
377
- }
378
- return summaries;
379
- }
380
-
381
- async function hydrateSessionFiles(
382
- codexHome: string,
383
- summaries: Map<string, CodexCliSessionSummary>,
384
- ): Promise<void> {
385
- if (summaries.size === 0) {
386
- return;
387
- }
388
- const sessionsDir = path.join(codexHome, "sessions");
389
- const files = await findSessionFiles(sessionsDir, 4);
390
- const pending = new Set(summaries.keys());
391
- for (const file of files) {
392
- const basename = path.basename(file);
393
- const sessionId = [...pending].find((id) => basename.includes(id));
394
- if (!sessionId) {
395
- continue;
396
- }
397
- const entry = summaries.get(sessionId);
398
- if (!entry) {
399
- continue;
400
- }
401
- entry.sessionFile = file;
402
- const firstLine = (await readFirstLine(file)) ?? "";
403
- const cwd = readSessionMetaCwd(firstLine);
404
- if (cwd) {
405
- entry.cwd = cwd;
406
- }
407
- pending.delete(sessionId);
408
- if (pending.size === 0) {
409
- return;
410
- }
411
- }
412
- }
413
-
414
- async function hydrateSessionsFromSessionFiles(
415
- codexHome: string,
416
- summaries: Map<string, CodexCliSessionSummary>,
417
- ): Promise<void> {
418
- const sessionsDir = path.join(codexHome, "sessions");
419
- const files = await findSessionFiles(sessionsDir, 4);
420
- for (const file of files) {
421
- const summary = await readSessionFileSummary(file);
422
- if (!summary) {
423
- continue;
424
- }
425
- const existing = summaries.get(summary.sessionId);
426
- summaries.set(summary.sessionId, {
427
- ...summary,
428
- ...existing,
429
- cwd: existing?.cwd ?? summary.cwd,
430
- sessionFile: existing?.sessionFile ?? summary.sessionFile,
431
- updatedAt: existing?.updatedAt ?? summary.updatedAt,
432
- lastMessage: existing?.lastMessage ?? summary.lastMessage,
433
- messageCount: existing?.messageCount ?? summary.messageCount,
434
- });
435
- }
436
- }
437
-
438
- async function readSessionFileSummary(file: string): Promise<CodexCliSessionSummary | null> {
439
- const content = await readFileIfExists(file);
440
- if (!content) {
441
- return null;
442
- }
443
- let sessionId = "";
444
- let cwd: string | undefined;
445
- let updatedAt: string | undefined;
446
- let lastMessage: string | undefined;
447
- let messageCount = 0;
448
- for (const line of content.split(/\r?\n/u)) {
449
- const trimmed = line.trim();
450
- if (!trimmed) {
451
- continue;
452
- }
453
- let parsed: unknown;
454
- try {
455
- parsed = JSON.parse(trimmed) as unknown;
456
- } catch {
457
- continue;
458
- }
459
- if (!isRecord(parsed)) {
460
- continue;
461
- }
462
- if (typeof parsed.timestamp === "string" && parsed.timestamp.trim()) {
463
- updatedAt = parsed.timestamp.trim();
464
- }
465
- if (parsed.type === "session_meta" && isRecord(parsed.payload)) {
466
- if (typeof parsed.payload.id === "string" && parsed.payload.id.trim()) {
467
- sessionId = parsed.payload.id.trim();
468
- }
469
- if (typeof parsed.payload.cwd === "string" && parsed.payload.cwd.trim()) {
470
- cwd = parsed.payload.cwd.trim();
471
- }
472
- continue;
473
- }
474
- const messageText = readResponseItemMessageText(parsed);
475
- if (messageText) {
476
- messageCount += 1;
477
- lastMessage = truncateText(messageText, 140);
478
- }
479
- }
480
- if (!sessionId) {
481
- sessionId = readSessionIdFromFilename(file) ?? "";
482
- }
483
- if (!sessionId) {
484
- return null;
485
- }
486
- return {
487
- sessionId,
488
- updatedAt: updatedAt ?? (await readFileMtimeIso(file)),
489
- lastMessage,
490
- cwd,
491
- sessionFile: file,
492
- messageCount,
493
- };
494
- }
495
-
496
- async function findSessionFiles(dir: string, maxDepth: number): Promise<string[]> {
497
- if (maxDepth < 0) {
498
- return [];
499
- }
500
- let entries: Array<import("node:fs").Dirent>;
501
- try {
502
- entries = await fs.readdir(dir, { withFileTypes: true });
503
- } catch {
504
- return [];
505
- }
506
- const files: string[] = [];
507
- for (const entry of entries) {
508
- const entryPath = path.join(dir, entry.name);
509
- if (entry.isDirectory()) {
510
- files.push(...(await findSessionFiles(entryPath, maxDepth - 1)));
511
- } else if (entry.isFile() && entry.name.endsWith(".jsonl")) {
512
- files.push(entryPath);
513
- }
514
- }
515
- return files;
516
- }
517
-
518
- function readSessionMetaCwd(line: string): string | undefined {
519
- try {
520
- const parsed = JSON.parse(line) as unknown;
521
- if (!isRecord(parsed) || parsed.type !== "session_meta" || !isRecord(parsed.payload)) {
522
- return undefined;
523
- }
524
- return typeof parsed.payload.cwd === "string" && parsed.payload.cwd.trim()
525
- ? parsed.payload.cwd.trim()
526
- : undefined;
527
- } catch {
528
- return undefined;
529
- }
530
- }
531
-
532
- function readResponseItemMessageText(parsed: Record<string, unknown>): string | undefined {
533
- if (parsed.type !== "response_item" || !isRecord(parsed.payload)) {
534
- return undefined;
535
- }
536
- if (parsed.payload.type !== "message") {
537
- return undefined;
538
- }
539
- const role = typeof parsed.payload.role === "string" ? parsed.payload.role : "";
540
- if (role !== "user") {
541
- return undefined;
542
- }
543
- const content = Array.isArray(parsed.payload.content) ? parsed.payload.content : [];
544
- const parts = content.flatMap((entry) => {
545
- if (!isRecord(entry)) {
546
- return [];
547
- }
548
- const text =
549
- typeof entry.text === "string"
550
- ? entry.text
551
- : typeof entry.input_text === "string"
552
- ? entry.input_text
553
- : undefined;
554
- return text?.trim() ? [text.trim()] : [];
555
- });
556
- return parts.length > 0 ? parts.join(" ") : undefined;
557
- }
558
-
559
- function readSessionIdFromFilename(file: string): string | undefined {
560
- const match = path.basename(file).match(/[0-9a-f]{8}-[0-9a-f-]{27,}/iu);
561
- return match?.[0];
562
- }
563
-
564
- async function resolveCodexCliNode(params: {
565
- runtime: PluginRuntime;
566
- requestedNode?: string;
567
- command: string;
568
- }): Promise<CodexCliSessionNodeInfo> {
569
- const list = await params.runtime.nodes.list(
570
- params.requestedNode ? undefined : { connected: true },
571
- );
572
- const requested = params.requestedNode?.trim();
573
- const candidates = list.nodes.filter((node) => {
574
- if (requested) {
575
- return [node.nodeId, node.displayName, node.remoteIp].some((value) => value === requested);
576
- }
577
- return node.connected === true && node.commands?.includes(params.command);
578
- });
579
- if (candidates.length === 0) {
580
- throw new Error(
581
- requested
582
- ? `Codex CLI node ${requested} was not found.`
583
- : "No connected node exposes Codex CLI session commands.",
584
- );
585
- }
586
- const usable = candidates.filter((node) => node.commands?.includes(params.command));
587
- if (usable.length === 0) {
588
- throw new Error(`Node ${requested ?? "candidate"} does not expose ${params.command}.`);
589
- }
590
- if (usable.length > 1) {
591
- throw new Error("Multiple Codex CLI-capable nodes connected. Pass --host <node-id>.");
592
- }
593
- return usable[0];
594
- }
595
-
596
- function parseCodexCliSessionsListResult(raw: unknown): CodexCliSessionsListResult {
597
- const payload = unwrapNodeInvokePayload(raw);
598
- if (!isRecord(payload) || !Array.isArray(payload.sessions)) {
599
- throw new Error("Codex CLI session list returned an invalid payload.");
600
- }
601
- return {
602
- codexHome: typeof payload.codexHome === "string" ? payload.codexHome : "",
603
- sessions: payload.sessions.flatMap((entry) => {
604
- if (!isRecord(entry) || typeof entry.sessionId !== "string") {
605
- return [];
606
- }
607
- return [
608
- {
609
- sessionId: entry.sessionId,
610
- updatedAt: typeof entry.updatedAt === "string" ? entry.updatedAt : undefined,
611
- lastMessage: typeof entry.lastMessage === "string" ? entry.lastMessage : undefined,
612
- cwd: typeof entry.cwd === "string" ? entry.cwd : undefined,
613
- sessionFile: typeof entry.sessionFile === "string" ? entry.sessionFile : undefined,
614
- messageCount:
615
- typeof entry.messageCount === "number" && Number.isFinite(entry.messageCount)
616
- ? entry.messageCount
617
- : 0,
618
- },
619
- ];
620
- }),
621
- };
622
- }
623
-
624
- function unwrapNodeInvokePayload(raw: unknown): unknown {
625
- const record = isRecord(raw) ? raw : {};
626
- if (typeof record.payloadJSON === "string" && record.payloadJSON.trim()) {
627
- try {
628
- return JSON.parse(record.payloadJSON) as unknown;
629
- } catch (error) {
630
- throw new Error("Codex CLI node command returned malformed payloadJSON.", {
631
- cause: error,
632
- });
633
- }
634
- }
635
- if ("payload" in record) {
636
- return record.payload;
637
- }
638
- return raw;
639
- }
640
-
641
- function readRecordParam(paramsJSON?: string | null): Record<string, unknown> {
642
- if (!paramsJSON?.trim()) {
643
- return {};
644
- }
645
- try {
646
- const parsed = JSON.parse(paramsJSON) as unknown;
647
- return isRecord(parsed) ? parsed : {};
648
- } catch {
649
- return {};
650
- }
651
- }
652
-
653
- function resolveCodexHome(): string {
654
- return process.env.CODEX_HOME?.trim() || path.join(os.homedir(), ".codex");
655
- }
656
-
657
- async function readFileIfExists(file: string): Promise<string | undefined> {
658
- try {
659
- return await fs.readFile(file, "utf8");
660
- } catch {
661
- return undefined;
662
- }
663
- }
664
-
665
- async function readFirstLine(file: string): Promise<string | undefined> {
666
- const content = await readFileIfExists(file);
667
- return content?.split(/\r?\n/u)[0];
668
- }
669
-
670
- async function readFileMtimeIso(file: string): Promise<string | undefined> {
671
- try {
672
- return (await fs.stat(file)).mtime.toISOString();
673
- } catch {
674
- return undefined;
675
- }
676
- }
677
-
678
- function normalizeLimit(value: unknown): number {
679
- return typeof value === "number" && Number.isFinite(value)
680
- ? Math.min(MAX_SESSION_LIMIT, Math.max(1, Math.floor(value)))
681
- : DEFAULT_SESSION_LIMIT;
682
- }
683
-
684
- function normalizeTimeoutMs(value: unknown): number {
685
- return typeof value === "number" && Number.isFinite(value) && value > 0
686
- ? Math.min(60 * 60_000, Math.floor(value))
687
- : DEFAULT_RESUME_TIMEOUT_MS;
688
- }
689
-
690
- function truncateText(value: string, max: number): string {
691
- return value.length > max ? `${value.slice(0, max - 3)}...` : value;
692
- }
693
-
694
- function compareOptionalStringsDesc(a?: string, b?: string): number {
695
- return (b ?? "").localeCompare(a ?? "");
696
- }
697
-
698
- function readNodeId(node: CodexCliSessionNodeInfo): string {
699
- if (!node.nodeId) {
700
- throw new Error("Codex CLI node did not include a node id.");
701
- }
702
- return node.nodeId;
703
- }
704
-
705
- function formatNodeLabel(node: CodexCliSessionNodeInfo): string {
706
- return [node.displayName, node.nodeId, node.remoteIp].filter(Boolean).join(" / ") || "node";
707
- }
708
-
709
- function isRecord(value: unknown): value is Record<string, unknown> {
710
- return Boolean(value && typeof value === "object" && !Array.isArray(value));
711
- }