@gakr-gakr/codex 0.1.0 → 0.1.1

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 (115) hide show
  1. package/dist/client-DNN2uyJW.js +642 -0
  2. package/dist/client-factory-Bu9OClHJ.js +9 -0
  3. package/dist/command-formatters-BpPOTePl.js +520 -0
  4. package/dist/command-handlers-BBs7Vws9.js +1533 -0
  5. package/dist/compact-CDboBy7o.js +329 -0
  6. package/dist/computer-use-DCZB46Sw.js +367 -0
  7. package/dist/config-CLMSw0p2.js +510 -0
  8. package/dist/doctor-contract-api.js +53 -0
  9. package/dist/harness.js +51 -0
  10. package/dist/index.js +1171 -0
  11. package/dist/media-understanding-provider.js +335 -0
  12. package/dist/models-jLA2SIvd.js +110 -0
  13. package/dist/node-cli-sessions-BLRDs_US.js +1216 -0
  14. package/dist/plugin-activation-CEy_oYpx.js +452 -0
  15. package/dist/prompt-overlay.js +12 -0
  16. package/dist/protocol-C9UWI98H.js +9 -0
  17. package/dist/protocol-validators-BGBspNmF.js +5988 -0
  18. package/dist/provider-catalog.js +84 -0
  19. package/dist/provider-discovery.js +33 -0
  20. package/dist/provider.js +150 -0
  21. package/dist/rate-limit-cache-9LxQdE0K.js +24 -0
  22. package/dist/request-DbSPeTcV.js +89 -0
  23. package/dist/rolldown-runtime-DUslC3ob.js +14 -0
  24. package/dist/run-attempt-BoEwzQCv.js +5463 -0
  25. package/dist/session-binding-e2GFp9VH.js +222 -0
  26. package/dist/shared-client-D7Vy0glq.js +631 -0
  27. package/dist/side-question-BDLuEzFP.js +668 -0
  28. package/dist/test-api.js +49 -0
  29. package/dist/thread-lifecycle-Clo0EHMk.js +1565 -0
  30. package/dist/vision-tools-Cofrv35p.js +1379 -0
  31. package/package.json +16 -1
  32. package/doctor-contract-api.ts +0 -68
  33. package/harness.ts +0 -72
  34. package/index.ts +0 -124
  35. package/media-understanding-provider.ts +0 -521
  36. package/prompt-overlay.ts +0 -21
  37. package/provider-catalog.ts +0 -83
  38. package/provider-discovery.ts +0 -45
  39. package/provider.ts +0 -243
  40. package/src/app-server/app-inventory-cache.ts +0 -324
  41. package/src/app-server/approval-bridge.ts +0 -1211
  42. package/src/app-server/auth-bridge.ts +0 -614
  43. package/src/app-server/capabilities.ts +0 -27
  44. package/src/app-server/client-factory.ts +0 -24
  45. package/src/app-server/client.ts +0 -715
  46. package/src/app-server/compact.ts +0 -512
  47. package/src/app-server/computer-use.ts +0 -683
  48. package/src/app-server/config.ts +0 -1038
  49. package/src/app-server/context-engine-projection.ts +0 -403
  50. package/src/app-server/dynamic-tool-diagnostics.ts +0 -73
  51. package/src/app-server/dynamic-tool-profile.ts +0 -70
  52. package/src/app-server/dynamic-tools.ts +0 -623
  53. package/src/app-server/elicitation-bridge.ts +0 -783
  54. package/src/app-server/event-projector.ts +0 -2065
  55. package/src/app-server/image-payload-sanitizer.ts +0 -167
  56. package/src/app-server/local-runtime-attribution.ts +0 -39
  57. package/src/app-server/managed-binary.ts +0 -193
  58. package/src/app-server/models.ts +0 -172
  59. package/src/app-server/native-hook-relay.ts +0 -150
  60. package/src/app-server/native-subagent-task-mirror.ts +0 -497
  61. package/src/app-server/plugin-activation.ts +0 -283
  62. package/src/app-server/plugin-app-cache-key.ts +0 -74
  63. package/src/app-server/plugin-approval-roundtrip.ts +0 -122
  64. package/src/app-server/plugin-inventory.ts +0 -357
  65. package/src/app-server/plugin-thread-config.ts +0 -455
  66. package/src/app-server/protocol-generated/json/DynamicToolCallParams.json +0 -33
  67. package/src/app-server/protocol-generated/json/v2/ErrorNotification.json +0 -199
  68. package/src/app-server/protocol-generated/json/v2/GetAccountResponse.json +0 -102
  69. package/src/app-server/protocol-generated/json/v2/ModelListResponse.json +0 -227
  70. package/src/app-server/protocol-generated/json/v2/ThreadResumeResponse.json +0 -2630
  71. package/src/app-server/protocol-generated/json/v2/ThreadStartResponse.json +0 -2630
  72. package/src/app-server/protocol-generated/json/v2/TurnCompletedNotification.json +0 -1659
  73. package/src/app-server/protocol-generated/json/v2/TurnStartResponse.json +0 -1655
  74. package/src/app-server/protocol-validators.ts +0 -203
  75. package/src/app-server/protocol.ts +0 -520
  76. package/src/app-server/rate-limit-cache.ts +0 -48
  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.ts +0 -4862
  80. package/src/app-server/session-binding.ts +0 -398
  81. package/src/app-server/session-history.ts +0 -44
  82. package/src/app-server/shared-client.ts +0 -289
  83. package/src/app-server/side-question.ts +0 -1009
  84. package/src/app-server/test-support.ts +0 -48
  85. package/src/app-server/thread-lifecycle.ts +0 -959
  86. package/src/app-server/timeout.ts +0 -9
  87. package/src/app-server/tool-progress-normalization.ts +0 -77
  88. package/src/app-server/trajectory.ts +0 -368
  89. package/src/app-server/transcript-mirror.ts +0 -208
  90. package/src/app-server/transport-stdio.ts +0 -107
  91. package/src/app-server/transport-websocket.ts +0 -90
  92. package/src/app-server/transport.ts +0 -117
  93. package/src/app-server/user-input-bridge.ts +0 -316
  94. package/src/app-server/version.ts +0 -4
  95. package/src/app-server/vision-tools.ts +0 -12
  96. package/src/command-account.ts +0 -544
  97. package/src/command-formatters.ts +0 -426
  98. package/src/command-handlers.ts +0 -2021
  99. package/src/command-plugins-management.ts +0 -137
  100. package/src/command-rpc.ts +0 -142
  101. package/src/commands.ts +0 -65
  102. package/src/conversation-binding-data.ts +0 -124
  103. package/src/conversation-binding.ts +0 -561
  104. package/src/conversation-control.ts +0 -303
  105. package/src/conversation-turn-collector.ts +0 -186
  106. package/src/conversation-turn-input.ts +0 -106
  107. package/src/migration/apply.ts +0 -501
  108. package/src/migration/helpers.ts +0 -55
  109. package/src/migration/plan.ts +0 -461
  110. package/src/migration/provider.ts +0 -41
  111. package/src/migration/source.ts +0 -643
  112. package/src/migration/targets.ts +0 -25
  113. package/src/node-cli-sessions.ts +0 -711
  114. package/test-api.ts +0 -95
  115. 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
- AutoBotPluginNodeHostCommand,
8
- AutoBotPluginNodeInvokePolicy,
9
- } from "autobot/plugin-sdk/plugin-entry";
10
- import type { PluginRuntime } from "autobot/plugin-sdk/plugin-runtime";
11
- import { resolvePreferredAutoBotTmpDir } from "autobot/plugin-sdk/temp-path";
12
- import {
13
- materializeWindowsSpawnProgram,
14
- resolveWindowsSpawnProgram,
15
- } from "autobot/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(): AutoBotPluginNodeHostCommand[] {
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(): AutoBotPluginNodeInvokePolicy[] {
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(resolvePreferredAutoBotTmpDir(), "autobot-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
- }