@openclaw/codex 2026.7.1 → 2026.7.2-beta.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 (48) hide show
  1. package/README.md +27 -3
  2. package/dist/app-server-policy-Scc-Wevo.js +49 -0
  3. package/dist/{attempt-notifications-BGsEIIDI.js → attempt-notifications-BFmNhqFl.js} +3 -6
  4. package/dist/auth-binding-C1czuHPA.js +62 -0
  5. package/dist/cli-metadata.js +20 -0
  6. package/dist/{app-server-policy-C968Kgin.js → command-formatters-Dq9InZUK.js} +39 -51
  7. package/dist/{command-handlers-Dv-pzAmg.js → command-handlers-IgqmL_kv.js} +161 -61
  8. package/dist/{compact-4mVBriKT.js → compact-DCTmg3id.js} +39 -10
  9. package/dist/computer-use-CPcU8TjG.js +685 -0
  10. package/dist/conversation-control-CGkBlfc5.js +286 -0
  11. package/dist/doctor-contract-api.js +120 -81
  12. package/dist/{provider-capabilities-CDnHbmUZ.js → dynamic-tools-C_1tEs34.js} +6109 -5725
  13. package/dist/harness.js +59 -15
  14. package/dist/index.js +1460 -269
  15. package/dist/{media-understanding-provider-BHOu9-Gg.js → media-understanding-provider-D31dOJwb.js} +32 -15
  16. package/dist/media-understanding-provider.js +1 -1
  17. package/dist/{models-DDmO1zwd.js → models-uh26C8QU.js} +5 -9
  18. package/dist/notification-correlation-KmfV4EkP.js +67 -0
  19. package/dist/plugin-app-cache-key-Ceb-lm2c.js +315 -0
  20. package/dist/{provider-zjPfx5Fs.js → rate-limits-DyXaYAxU.js} +10 -266
  21. package/dist/request-B_oQsCXy.js +157 -0
  22. package/dist/{run-attempt-FUyOjGCV.js → run-attempt-MLzoMe_m.js} +7395 -6430
  23. package/dist/runtime-artifact-C2ITXdhM.js +488 -0
  24. package/dist/{sandbox-guard-DA2TQfZW.js → sandbox-guard-D1Wky__S.js} +10 -1
  25. package/dist/{config-CYEDnLJ2.js → session-binding-h1mmCGnl.js} +985 -31
  26. package/dist/session-catalog-CEvoXWHA.js +2412 -0
  27. package/dist/session-cli-XsEuWb_C.js +175 -0
  28. package/dist/{shared-client-4ICy3U6d.js → shared-client-JiAnW6pc.js} +2193 -1319
  29. package/dist/{side-question-N4OaDer2.js → side-question-DqDvIwSU.js} +140 -70
  30. package/dist/{thread-lifecycle-qWE88Dn2.js → thread-lifecycle-CN_pPtPh.js} +1826 -1188
  31. package/dist/{protocol-validators-dZQ-UTOa.js → transcript-mirror-D9rTxx2P.js} +485 -2
  32. package/dist/transport-stdio-DXgGZ7Ib.js +88 -0
  33. package/dist/usage-D5Rohxoc.js +25 -0
  34. package/dist/{web-search-provider.runtime-BSlriav6.js → web-search-provider.runtime-CKVBn3fP.js} +3 -3
  35. package/npm-shrinkwrap.json +56 -30
  36. package/openclaw.plugin.json +177 -14
  37. package/package.json +8 -6
  38. package/dist/command-rpc-eLM_mtC7.js +0 -784
  39. package/dist/computer-use-Bmaz333N.js +0 -377
  40. package/dist/notification-correlation-Bo7KB3ks.js +0 -35
  41. package/dist/plugin-app-cache-key-BrhVdeEf.js +0 -98
  42. package/dist/prompt-overlay.js +0 -15
  43. package/dist/protocol-2POPqAY4.js +0 -13
  44. package/dist/provider-catalog.js +0 -79
  45. package/dist/provider-discovery.js +0 -34
  46. package/dist/provider.js +0 -2
  47. package/dist/request-BcJyl8KL.js +0 -36
  48. package/dist/session-binding-C1ZXdP-x.js +0 -627
@@ -0,0 +1,2412 @@
1
+ import { J as CODEX_INTERACTIVE_THREAD_SOURCE_KINDS, R as CodexAppServerRpcError, Z as isJsonObject, a as getLeasedSharedCodexAppServerClient, c as releaseLeasedSharedCodexAppServerClient, q as CODEX_INTERACTIVE_CUSTOM_THREAD_SOURCES } from "./shared-client-JiAnW6pc.js";
2
+ import { E as resolveCodexSupervisionAppServerRuntimeOptions, b as resolveCodexAppServerRuntimeOptions, c as sessionBindingIdentity, s as reclaimCurrentCodexSessionGeneration } from "./session-binding-h1mmCGnl.js";
3
+ import { r as importCodexThreadHistoryToTranscript } from "./transcript-mirror-D9rTxx2P.js";
4
+ import { n as listCodexAppServerModels } from "./models-uh26C8QU.js";
5
+ import { t as buildCodexAppServerConnectionFingerprint } from "./plugin-app-cache-key-Ceb-lm2c.js";
6
+ import { d as CODEX_CONTROL_METHODS, f as describeControlFailure, r as formatCodexDisplayText } from "./command-formatters-Dq9InZUK.js";
7
+ import { n as createCodexCliNodeConversationBindingData } from "./conversation-binding-data-BHRpYbX3.js";
8
+ import { n as requestCodexAppServerClientJson, r as requestCodexAppServerJson } from "./request-B_oQsCXy.js";
9
+ import fs from "node:fs/promises";
10
+ import path from "node:path";
11
+ import { timestampMsToIsoString } from "openclaw/plugin-sdk/number-runtime";
12
+ import { resolvePreferredOpenClawTmpDir } from "openclaw/plugin-sdk/temp-path";
13
+ import { truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
14
+ import { createHash } from "node:crypto";
15
+ import os from "node:os";
16
+ import { listAgentIds, resolveDefaultAgentDir, resolveDefaultAgentId } from "openclaw/plugin-sdk/agent-runtime";
17
+ import { parseAgentSessionKey } from "openclaw/plugin-sdk/routing";
18
+ import { isRecord } from "openclaw/plugin-sdk/string-coerce-runtime";
19
+ import { materializeWindowsSpawnProgram, resolveWindowsSpawnProgram } from "openclaw/plugin-sdk/windows-spawn";
20
+ import { spawn } from "node:child_process";
21
+ import { resolveStorePath } from "openclaw/plugin-sdk/session-store-runtime";
22
+ import { expectDefined } from "openclaw/plugin-sdk/expect-runtime";
23
+ import process$1 from "node:process";
24
+ import { decodeNodePtyResumeParams, resolveNodeHostExecutable, runNodePtyCommand } from "openclaw/plugin-sdk/node-host";
25
+ //#region extensions/codex/src/node-cli-sessions.ts
26
+ const CODEX_CLI_SESSIONS_LIST_COMMAND = "codex.cli.sessions.list";
27
+ const CODEX_CLI_SESSION_RESUME_COMMAND = "codex.cli.session.resume";
28
+ const DEFAULT_SESSION_LIMIT = 10;
29
+ const MAX_SESSION_LIMIT = 50;
30
+ const DEFAULT_RESUME_TIMEOUT_MS = 20 * 6e4;
31
+ const SESSION_ID_PATTERN = /^[A-Za-z0-9._:-]{1,128}$/;
32
+ const activeResumeSessions = /* @__PURE__ */ new Set();
33
+ const DEFAULT_RESUME_SPAWN_RUNTIME = {
34
+ platform: process$1.platform,
35
+ env: process$1.env,
36
+ execPath: process$1.execPath
37
+ };
38
+ function createCodexCliSessionNodeHostCommands() {
39
+ return [{
40
+ command: CODEX_CLI_SESSIONS_LIST_COMMAND,
41
+ cap: "codex-cli-sessions",
42
+ handle: listLocalCodexCliSessions
43
+ }, {
44
+ command: CODEX_CLI_SESSION_RESUME_COMMAND,
45
+ cap: "codex-cli-sessions",
46
+ dangerous: true,
47
+ handle: resumeLocalCodexCliSession
48
+ }];
49
+ }
50
+ function createCodexCliSessionNodeInvokePolicies() {
51
+ return [{
52
+ commands: [CODEX_CLI_SESSIONS_LIST_COMMAND],
53
+ defaultPlatforms: [
54
+ "macos",
55
+ "linux",
56
+ "windows"
57
+ ],
58
+ handle: (ctx) => ctx.invokeNode()
59
+ }, {
60
+ commands: [CODEX_CLI_SESSION_RESUME_COMMAND],
61
+ dangerous: true,
62
+ handle: (ctx) => ctx.invokeNode()
63
+ }];
64
+ }
65
+ async function listCodexCliSessionsOnNode(params) {
66
+ const node = await resolveCodexCliNode({
67
+ runtime: params.runtime,
68
+ requestedNode: params.requestedNode,
69
+ command: CODEX_CLI_SESSIONS_LIST_COMMAND
70
+ });
71
+ return {
72
+ node,
73
+ result: parseCodexCliSessionsListResult(await params.runtime.nodes.invoke({
74
+ nodeId: readNodeId(node),
75
+ command: CODEX_CLI_SESSIONS_LIST_COMMAND,
76
+ params: {
77
+ limit: params.limit,
78
+ filter: params.filter
79
+ },
80
+ timeoutMs: 15e3,
81
+ scopes: ["operator.write"]
82
+ }))
83
+ };
84
+ }
85
+ async function resolveCodexCliSessionForBindingOnNode(params) {
86
+ const listing = await listCodexCliSessionsOnNode({
87
+ runtime: params.runtime,
88
+ requestedNode: params.requestedNode,
89
+ filter: params.sessionId,
90
+ limit: MAX_SESSION_LIMIT
91
+ });
92
+ if (!listing.node.commands?.includes("codex.cli.session.resume")) throw new Error(`Node ${formatNodeLabel(listing.node)} does not expose ${CODEX_CLI_SESSION_RESUME_COMMAND}.`);
93
+ return {
94
+ node: listing.node,
95
+ session: listing.result.sessions.find((session) => session.sessionId === params.sessionId)
96
+ };
97
+ }
98
+ async function resumeCodexCliSessionOnNode(params) {
99
+ const payload = unwrapNodeInvokePayload$1(await params.runtime.nodes.invoke({
100
+ nodeId: params.nodeId,
101
+ command: CODEX_CLI_SESSION_RESUME_COMMAND,
102
+ params: {
103
+ sessionId: params.sessionId,
104
+ prompt: params.prompt,
105
+ cwd: params.cwd,
106
+ timeoutMs: params.timeoutMs
107
+ },
108
+ timeoutMs: (params.timeoutMs ?? DEFAULT_RESUME_TIMEOUT_MS) + 5e3,
109
+ scopes: ["operator.write"]
110
+ }));
111
+ if (!isRecord(payload) || payload.ok !== true || typeof payload.text !== "string") throw new Error("Codex CLI resume returned an invalid payload.");
112
+ return {
113
+ ok: true,
114
+ sessionId: typeof payload.sessionId === "string" ? payload.sessionId : params.sessionId,
115
+ text: payload.text
116
+ };
117
+ }
118
+ function formatCodexCliSessions(params) {
119
+ if (params.result.sessions.length === 0) return `No Codex CLI sessions returned from ${formatCodexDisplayText(formatNodeLabel(params.node))}.`;
120
+ return [`Codex CLI sessions on ${formatCodexDisplayText(formatNodeLabel(params.node))}:`, ...params.result.sessions.map((session) => {
121
+ const details = [session.cwd, session.updatedAt].filter((value) => Boolean(value));
122
+ return `- ${formatCodexDisplayText(session.sessionId)}${session.lastMessage ? ` - ${formatCodexDisplayText(session.lastMessage)}` : ""}${details.length > 0 ? ` (${details.map(formatCodexDisplayText).join(", ")})` : ""}\n Bind: /codex resume ${formatCodexDisplayText(session.sessionId)} --host ${formatCodexDisplayText(readNodeId(params.node))} --bind here`;
123
+ })].join("\n");
124
+ }
125
+ async function listLocalCodexCliSessions(paramsJSON) {
126
+ const params = readRecordParam(paramsJSON);
127
+ const limit = normalizeLimit$1(params.limit);
128
+ const filter = typeof params.filter === "string" ? params.filter.trim().toLowerCase() : "";
129
+ const codexHome = resolveCodexHome();
130
+ const summaries = await readHistorySessions(codexHome);
131
+ await hydrateSessionFiles(codexHome, summaries);
132
+ await hydrateSessionsFromSessionFiles(codexHome, summaries);
133
+ const sessions = [...summaries.values()].filter((session) => {
134
+ if (!filter) return true;
135
+ return [
136
+ session.sessionId,
137
+ session.cwd,
138
+ session.lastMessage
139
+ ].some((value) => value?.toLowerCase().includes(filter));
140
+ }).toSorted((a, b) => compareOptionalStringsDesc(a.updatedAt, b.updatedAt)).slice(0, limit);
141
+ return JSON.stringify({
142
+ sessions,
143
+ codexHome
144
+ });
145
+ }
146
+ async function resumeLocalCodexCliSession(paramsJSON) {
147
+ const params = readRecordParam(paramsJSON);
148
+ const sessionId = typeof params.sessionId === "string" ? params.sessionId.trim() : "";
149
+ const prompt = typeof params.prompt === "string" ? params.prompt.trim() : "";
150
+ if (!sessionId || !SESSION_ID_PATTERN.test(sessionId)) throw new Error("Missing or invalid Codex CLI session id.");
151
+ if (!prompt) throw new Error("Missing Codex CLI prompt.");
152
+ if (activeResumeSessions.has(sessionId)) throw new Error(`Codex CLI session ${sessionId} already has an active resume turn.`);
153
+ activeResumeSessions.add(sessionId);
154
+ try {
155
+ const text = await runCodexExecResume({
156
+ sessionId,
157
+ prompt,
158
+ cwd: typeof params.cwd === "string" && params.cwd.trim() ? params.cwd.trim() : void 0,
159
+ timeoutMs: normalizeTimeoutMs(params.timeoutMs)
160
+ });
161
+ return JSON.stringify({
162
+ ok: true,
163
+ sessionId,
164
+ text: text.trim() || "Codex completed without a text reply."
165
+ });
166
+ } finally {
167
+ activeResumeSessions.delete(sessionId);
168
+ }
169
+ }
170
+ async function runCodexExecResume(params) {
171
+ const outputPath = path.join(await fs.mkdtemp(path.join(resolvePreferredOpenClawTmpDir(), "openclaw-codex-cli-")), "last-message.txt");
172
+ try {
173
+ const invocation = resolveCodexCliResumeSpawnInvocation([
174
+ "exec",
175
+ "resume",
176
+ "--skip-git-repo-check",
177
+ "--output-last-message",
178
+ outputPath,
179
+ params.sessionId,
180
+ "-"
181
+ ], {
182
+ platform: process$1.platform,
183
+ env: process$1.env,
184
+ execPath: process$1.execPath
185
+ });
186
+ const child = spawn(invocation.command, invocation.args, {
187
+ cwd: params.cwd || process$1.cwd(),
188
+ stdio: [
189
+ "pipe",
190
+ "pipe",
191
+ "pipe"
192
+ ],
193
+ env: process$1.env,
194
+ shell: invocation.shell,
195
+ windowsHide: invocation.windowsHide
196
+ });
197
+ const stdout = [];
198
+ const stderr = [];
199
+ let timedOut = false;
200
+ let forceKillTimeout;
201
+ const timeout = setTimeout(() => {
202
+ timedOut = true;
203
+ child.kill("SIGTERM");
204
+ forceKillTimeout = setTimeout(() => child.kill("SIGKILL"), 2e3);
205
+ forceKillTimeout.unref?.();
206
+ }, params.timeoutMs);
207
+ child.stdout.on("data", (chunk) => stdout.push(chunk));
208
+ child.stderr.on("data", (chunk) => stderr.push(chunk));
209
+ child.stdin.end(params.prompt);
210
+ const exitCode = await new Promise((resolve, reject) => {
211
+ child.on("error", reject);
212
+ child.on("exit", (code) => resolve(code));
213
+ }).finally(() => {
214
+ clearTimeout(timeout);
215
+ if (forceKillTimeout) clearTimeout(forceKillTimeout);
216
+ });
217
+ if (timedOut) throw new Error(`codex exec resume timed out after ${String(params.timeoutMs)}ms`);
218
+ if (exitCode !== 0) {
219
+ const message = Buffer.concat(stderr).toString("utf8").trim() || Buffer.concat(stdout).toString("utf8").trim() || `codex exec resume exited with code ${String(exitCode)}`;
220
+ throw new Error(message);
221
+ }
222
+ return await fs.readFile(outputPath, "utf8");
223
+ } finally {
224
+ await fs.rm(path.dirname(outputPath), {
225
+ recursive: true,
226
+ force: true
227
+ });
228
+ }
229
+ }
230
+ function resolveCodexCliResumeSpawnInvocation(args, runtime = DEFAULT_RESUME_SPAWN_RUNTIME) {
231
+ const resolved = materializeWindowsSpawnProgram(resolveWindowsSpawnProgram({
232
+ command: "codex",
233
+ platform: runtime.platform,
234
+ env: runtime.env,
235
+ execPath: runtime.execPath,
236
+ packageName: "@openai/codex"
237
+ }), args);
238
+ return {
239
+ command: resolved.command,
240
+ args: resolved.argv,
241
+ shell: resolved.shell,
242
+ windowsHide: resolved.windowsHide
243
+ };
244
+ }
245
+ async function readHistorySessions(codexHome) {
246
+ const summaries = /* @__PURE__ */ new Map();
247
+ const content = await readFileIfExists(path.join(codexHome, "history.jsonl"));
248
+ if (!content) return summaries;
249
+ for (const line of content.split(/\r?\n/u)) {
250
+ const trimmed = line.trim();
251
+ if (!trimmed) continue;
252
+ let parsed;
253
+ try {
254
+ parsed = JSON.parse(trimmed);
255
+ } catch {
256
+ continue;
257
+ }
258
+ if (!isRecord(parsed) || typeof parsed.session_id !== "string") continue;
259
+ const sessionId = parsed.session_id.trim();
260
+ if (!sessionId) continue;
261
+ const entry = summaries.get(sessionId) ?? {
262
+ sessionId,
263
+ messageCount: 0
264
+ };
265
+ entry.messageCount += 1;
266
+ if (typeof parsed.text === "string" && parsed.text.trim()) entry.lastMessage = truncateText(parsed.text.trim(), 140);
267
+ if (typeof parsed.ts === "number") entry.updatedAt = timestampMsToIsoString(parsed.ts * 1e3) ?? entry.updatedAt;
268
+ summaries.set(sessionId, entry);
269
+ }
270
+ return summaries;
271
+ }
272
+ async function hydrateSessionFiles(codexHome, summaries) {
273
+ if (summaries.size === 0) return;
274
+ const files = await findSessionFiles(path.join(codexHome, "sessions"), 4);
275
+ const pending = new Set(summaries.keys());
276
+ for (const file of files) {
277
+ const basename = path.basename(file);
278
+ const sessionId = [...pending].find((id) => basename.includes(id));
279
+ if (!sessionId) continue;
280
+ const entry = summaries.get(sessionId);
281
+ if (!entry) continue;
282
+ entry.sessionFile = file;
283
+ const cwd = readSessionMetaCwd(await readFirstLine(file) ?? "");
284
+ if (cwd) entry.cwd = cwd;
285
+ pending.delete(sessionId);
286
+ if (pending.size === 0) return;
287
+ }
288
+ }
289
+ async function hydrateSessionsFromSessionFiles(codexHome, summaries) {
290
+ const files = await findSessionFiles(path.join(codexHome, "sessions"), 4);
291
+ for (const file of files) {
292
+ const summary = await readSessionFileSummary(file);
293
+ if (!summary) continue;
294
+ const existing = summaries.get(summary.sessionId);
295
+ summaries.set(summary.sessionId, {
296
+ ...summary,
297
+ ...existing,
298
+ cwd: existing?.cwd ?? summary.cwd,
299
+ sessionFile: existing?.sessionFile ?? summary.sessionFile,
300
+ updatedAt: existing?.updatedAt ?? summary.updatedAt,
301
+ lastMessage: existing?.lastMessage ?? summary.lastMessage,
302
+ messageCount: existing?.messageCount ?? summary.messageCount
303
+ });
304
+ }
305
+ }
306
+ async function readSessionFileSummary(file) {
307
+ const content = await readFileIfExists(file);
308
+ if (!content) return null;
309
+ let sessionId = "";
310
+ let cwd;
311
+ let updatedAt;
312
+ let lastMessage;
313
+ let messageCount = 0;
314
+ for (const line of content.split(/\r?\n/u)) {
315
+ const trimmed = line.trim();
316
+ if (!trimmed) continue;
317
+ let parsed;
318
+ try {
319
+ parsed = JSON.parse(trimmed);
320
+ } catch {
321
+ continue;
322
+ }
323
+ if (!isRecord(parsed)) continue;
324
+ if (typeof parsed.timestamp === "string" && parsed.timestamp.trim()) updatedAt = parsed.timestamp.trim();
325
+ if (parsed.type === "session_meta" && isRecord(parsed.payload)) {
326
+ if (typeof parsed.payload.id === "string" && parsed.payload.id.trim()) sessionId = parsed.payload.id.trim();
327
+ if (typeof parsed.payload.cwd === "string" && parsed.payload.cwd.trim()) cwd = parsed.payload.cwd.trim();
328
+ continue;
329
+ }
330
+ const messageText = readResponseItemMessageText(parsed);
331
+ if (messageText) {
332
+ messageCount += 1;
333
+ lastMessage = truncateText(messageText, 140);
334
+ }
335
+ }
336
+ if (!sessionId) sessionId = readSessionIdFromFilename(file) ?? "";
337
+ if (!sessionId) return null;
338
+ return {
339
+ sessionId,
340
+ updatedAt: updatedAt ?? await readFileMtimeIso(file),
341
+ lastMessage,
342
+ cwd,
343
+ sessionFile: file,
344
+ messageCount
345
+ };
346
+ }
347
+ async function findSessionFiles(dir, maxDepth) {
348
+ if (maxDepth < 0) return [];
349
+ let entries;
350
+ try {
351
+ entries = await fs.readdir(dir, { withFileTypes: true });
352
+ } catch {
353
+ return [];
354
+ }
355
+ const files = [];
356
+ for (const entry of entries) {
357
+ const entryPath = path.join(dir, entry.name);
358
+ if (entry.isDirectory()) files.push(...await findSessionFiles(entryPath, maxDepth - 1));
359
+ else if (entry.isFile() && entry.name.endsWith(".jsonl")) files.push(entryPath);
360
+ }
361
+ return files;
362
+ }
363
+ function readSessionMetaCwd(line) {
364
+ try {
365
+ const parsed = JSON.parse(line);
366
+ if (!isRecord(parsed) || parsed.type !== "session_meta" || !isRecord(parsed.payload)) return;
367
+ return typeof parsed.payload.cwd === "string" && parsed.payload.cwd.trim() ? parsed.payload.cwd.trim() : void 0;
368
+ } catch {
369
+ return;
370
+ }
371
+ }
372
+ function readResponseItemMessageText(parsed) {
373
+ if (parsed.type !== "response_item" || !isRecord(parsed.payload)) return;
374
+ if (parsed.payload.type !== "message") return;
375
+ if ((typeof parsed.payload.role === "string" ? parsed.payload.role : "") !== "user") return;
376
+ const parts = (Array.isArray(parsed.payload.content) ? parsed.payload.content : []).flatMap((entry) => {
377
+ if (!isRecord(entry)) return [];
378
+ const text = typeof entry.text === "string" ? entry.text : typeof entry.input_text === "string" ? entry.input_text : void 0;
379
+ return text?.trim() ? [text.trim()] : [];
380
+ });
381
+ return parts.length > 0 ? parts.join(" ") : void 0;
382
+ }
383
+ function readSessionIdFromFilename(file) {
384
+ return path.basename(file).match(/[0-9a-f]{8}-[0-9a-f-]{27,}/iu)?.[0];
385
+ }
386
+ async function resolveCodexCliNode(params) {
387
+ const list = await params.runtime.nodes.list(params.requestedNode ? void 0 : { connected: true });
388
+ const requested = params.requestedNode?.trim();
389
+ const candidates = list.nodes.filter((node) => {
390
+ if (requested) return [
391
+ node.nodeId,
392
+ node.displayName,
393
+ node.remoteIp
394
+ ].some((value) => value === requested);
395
+ return node.connected === true && node.commands?.includes(params.command);
396
+ });
397
+ if (candidates.length === 0) throw new Error(requested ? `Codex CLI node ${requested} was not found.` : "No connected node exposes Codex CLI session commands.");
398
+ const usable = candidates.filter((node) => node.commands?.includes(params.command));
399
+ if (usable.length === 0) throw new Error(`Node ${requested ?? "candidate"} does not expose ${params.command}.`);
400
+ if (usable.length > 1) throw new Error("Multiple Codex CLI-capable nodes connected. Pass --host <node-id>.");
401
+ return expectDefined(usable[0], "single usable Codex CLI node");
402
+ }
403
+ function parseCodexCliSessionsListResult(raw) {
404
+ const payload = unwrapNodeInvokePayload$1(raw);
405
+ if (!isRecord(payload) || !Array.isArray(payload.sessions)) throw new Error("Codex CLI session list returned an invalid payload.");
406
+ return {
407
+ codexHome: typeof payload.codexHome === "string" ? payload.codexHome : "",
408
+ sessions: payload.sessions.flatMap((entry) => {
409
+ if (!isRecord(entry) || typeof entry.sessionId !== "string") return [];
410
+ return [{
411
+ sessionId: entry.sessionId,
412
+ updatedAt: typeof entry.updatedAt === "string" ? entry.updatedAt : void 0,
413
+ lastMessage: typeof entry.lastMessage === "string" ? entry.lastMessage : void 0,
414
+ cwd: typeof entry.cwd === "string" ? entry.cwd : void 0,
415
+ sessionFile: typeof entry.sessionFile === "string" ? entry.sessionFile : void 0,
416
+ messageCount: typeof entry.messageCount === "number" && Number.isFinite(entry.messageCount) ? entry.messageCount : 0
417
+ }];
418
+ })
419
+ };
420
+ }
421
+ function unwrapNodeInvokePayload$1(raw) {
422
+ const record = isRecord(raw) ? raw : {};
423
+ if (typeof record.payloadJSON === "string" && record.payloadJSON.trim()) try {
424
+ return JSON.parse(record.payloadJSON);
425
+ } catch (error) {
426
+ throw new Error("Codex CLI node command returned malformed payloadJSON.", { cause: error });
427
+ }
428
+ if ("payload" in record) return record.payload;
429
+ return raw;
430
+ }
431
+ function readRecordParam(paramsJSON) {
432
+ if (!paramsJSON?.trim()) return {};
433
+ try {
434
+ const parsed = JSON.parse(paramsJSON);
435
+ return isRecord(parsed) ? parsed : {};
436
+ } catch {
437
+ return {};
438
+ }
439
+ }
440
+ function resolveCodexHome() {
441
+ return process$1.env.CODEX_HOME?.trim() || path.join(os.homedir(), ".codex");
442
+ }
443
+ async function readFileIfExists(file) {
444
+ try {
445
+ return await fs.readFile(file, "utf8");
446
+ } catch {
447
+ return;
448
+ }
449
+ }
450
+ async function readFirstLine(file) {
451
+ return (await readFileIfExists(file))?.split(/\r?\n/u)[0];
452
+ }
453
+ async function readFileMtimeIso(file) {
454
+ try {
455
+ return (await fs.stat(file)).mtime.toISOString();
456
+ } catch {
457
+ return;
458
+ }
459
+ }
460
+ function normalizeLimit$1(value) {
461
+ return typeof value === "number" && Number.isFinite(value) ? Math.min(MAX_SESSION_LIMIT, Math.max(1, Math.floor(value))) : DEFAULT_SESSION_LIMIT;
462
+ }
463
+ function normalizeTimeoutMs(value) {
464
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.min(60 * 6e4, Math.floor(value)) : DEFAULT_RESUME_TIMEOUT_MS;
465
+ }
466
+ function truncateText(value, max) {
467
+ if (value.length <= max) return value;
468
+ return `${truncateUtf16Safe(value, Math.max(0, max - 3))}...`;
469
+ }
470
+ function compareOptionalStringsDesc(a, b) {
471
+ return (b ?? "").localeCompare(a ?? "");
472
+ }
473
+ function readNodeId(node) {
474
+ if (!node.nodeId) throw new Error("Codex CLI node did not include a node id.");
475
+ return node.nodeId;
476
+ }
477
+ function formatNodeLabel(node) {
478
+ return [
479
+ node.displayName,
480
+ node.nodeId,
481
+ node.remoteIp
482
+ ].filter(Boolean).join(" / ") || "node";
483
+ }
484
+ //#endregion
485
+ //#region extensions/codex/src/app-server/thread-archive-guard.ts
486
+ const DESCENDANT_PAGE_LIMIT = 100;
487
+ const MAX_DESCENDANT_PAGES = 100;
488
+ const MAX_THREAD_ID_LENGTH = 256;
489
+ const MAX_CURSOR_LENGTH$1 = 4096;
490
+ function readBoundedId(value) {
491
+ if (typeof value !== "string") return;
492
+ const normalized = value.trim();
493
+ return normalized && normalized.length <= MAX_THREAD_ID_LENGTH ? normalized : void 0;
494
+ }
495
+ function readNextCursor(value) {
496
+ if (value === void 0 || value === null) return;
497
+ if (typeof value !== "string" || !value.trim() || value.length > MAX_CURSOR_LENGTH$1) throw new Error("Codex app-server returned an invalid descendant-list cursor");
498
+ return value;
499
+ }
500
+ /**
501
+ * Native archive includes the spawned subtree. Enumerate that same subtree first so an
502
+ * OpenClaw-owned descendant cannot be stopped as an undocumented side effect.
503
+ */
504
+ async function assertCodexArchiveDescendantsUnowned(params) {
505
+ const ancestorThreadId = readBoundedId(params.threadId);
506
+ if (!ancestorThreadId) throw new Error("cannot verify Codex archive descendants for an invalid thread id");
507
+ const seenCursors = /* @__PURE__ */ new Set();
508
+ const seenThreadIds = /* @__PURE__ */ new Set([ancestorThreadId]);
509
+ let cursor;
510
+ for (let pageIndex = 0; pageIndex < MAX_DESCENDANT_PAGES; pageIndex += 1) {
511
+ const response = await params.listPage({
512
+ ancestorThreadId,
513
+ archived: false,
514
+ limit: DESCENDANT_PAGE_LIMIT,
515
+ sortKey: "created_at",
516
+ sortDirection: "desc",
517
+ useStateDbOnly: true,
518
+ ...cursor ? { cursor } : {}
519
+ });
520
+ if (!isJsonObject(response) || !Array.isArray(response.data)) throw new Error("Codex app-server returned an invalid descendant-list response");
521
+ if (response.data.length > DESCENDANT_PAGE_LIMIT) throw new Error("Codex app-server exceeded the descendant-list page limit");
522
+ for (const value of response.data) {
523
+ if (!isJsonObject(value)) throw new Error("Codex app-server returned an invalid descendant thread");
524
+ const descendantThreadId = readBoundedId(value.id);
525
+ if (!descendantThreadId) throw new Error("Codex app-server returned a descendant without a valid thread id");
526
+ if (seenThreadIds.has(descendantThreadId)) throw new Error("Codex app-server returned a cyclic descendant thread list");
527
+ seenThreadIds.add(descendantThreadId);
528
+ await params.assertDescendantIdle(descendantThreadId);
529
+ if (await params.bindingStore.hasOtherThreadOwner(descendantThreadId)) throw new Error("cannot archive a Codex thread while a spawned descendant is owned by an OpenClaw session");
530
+ }
531
+ const nextCursor = readNextCursor(response.nextCursor);
532
+ if (!nextCursor) return;
533
+ if (seenCursors.has(nextCursor)) throw new Error("Codex app-server returned a repeated descendant-list cursor");
534
+ seenCursors.add(nextCursor);
535
+ cursor = nextCursor;
536
+ }
537
+ throw new Error("Codex descendant enumeration exceeded its safety limit");
538
+ }
539
+ //#endregion
540
+ //#region extensions/codex/src/command-rpc.ts
541
+ function requestOptions(pluginConfig, limit, config, agentDir) {
542
+ const runtime = resolveCodexAppServerRuntimeOptions({ pluginConfig });
543
+ return {
544
+ limit,
545
+ timeoutMs: runtime.requestTimeoutMs,
546
+ startOptions: runtime.start,
547
+ config,
548
+ agentDir
549
+ };
550
+ }
551
+ async function codexControlRequest(pluginConfig, method, requestParams, options = {}) {
552
+ const runtime = resolveCodexAppServerRuntimeOptions({ pluginConfig });
553
+ return await requestCodexAppServerJson({
554
+ method,
555
+ requestParams,
556
+ timeoutMs: options.timeoutMs ?? runtime.requestTimeoutMs,
557
+ startOptions: options.startOptions ?? runtime.start,
558
+ config: options.config,
559
+ sessionKey: options.sessionKey,
560
+ sessionId: options.sessionId,
561
+ authProfileId: options.authProfileId,
562
+ agentDir: options.agentDir,
563
+ isolated: options.isolated
564
+ });
565
+ }
566
+ async function safeCodexControlRequest(pluginConfig, method, requestParams, options = {}) {
567
+ return await safeValue(async () => await codexControlRequest(pluginConfig, method, requestParams, options));
568
+ }
569
+ async function safeCodexModelList(pluginConfig, limit, config, agentDir) {
570
+ return await safeValue(async () => await listCodexAppServerModels(requestOptions(pluginConfig, limit, config, agentDir)));
571
+ }
572
+ async function readCodexStatusProbes(pluginConfig, config, agentDir) {
573
+ const [models, account, limits, mcps, skills] = await Promise.all([
574
+ safeCodexModelList(pluginConfig, 20, config, agentDir),
575
+ safeCodexControlRequest(pluginConfig, CODEX_CONTROL_METHODS.account, { refreshToken: false }, {
576
+ config,
577
+ agentDir
578
+ }),
579
+ safeCodexControlRequest(pluginConfig, CODEX_CONTROL_METHODS.rateLimits, void 0, {
580
+ config,
581
+ agentDir
582
+ }),
583
+ safeCodexControlRequest(pluginConfig, CODEX_CONTROL_METHODS.listMcpServers, { limit: 100 }, {
584
+ config,
585
+ agentDir
586
+ }),
587
+ safeCodexControlRequest(pluginConfig, CODEX_CONTROL_METHODS.listSkills, {}, {
588
+ config,
589
+ agentDir
590
+ })
591
+ ]);
592
+ return {
593
+ models,
594
+ account,
595
+ limits,
596
+ mcps,
597
+ skills
598
+ };
599
+ }
600
+ async function safeValue(read) {
601
+ try {
602
+ return {
603
+ ok: true,
604
+ value: await read()
605
+ };
606
+ } catch (error) {
607
+ return {
608
+ ok: false,
609
+ error: describeControlFailure(error)
610
+ };
611
+ }
612
+ }
613
+ //#endregion
614
+ //#region extensions/codex/src/session-catalog-parsing.ts
615
+ const DEFAULT_PAGE_LIMIT = 50;
616
+ const CODEX_APP_SERVER_THREADS_CAPABILITY = "codex-app-server-threads";
617
+ const CODEX_APP_SERVER_THREADS_LIST_COMMAND = "codex.appServer.threads.list.v1";
618
+ const CODEX_APP_SERVER_THREAD_TURNS_LIST_COMMAND = "codex.appServer.thread.turns.list.v1";
619
+ const CODEX_LOCAL_SESSION_HOST_ID = "gateway:local";
620
+ const NODE_INVOKE_TIMEOUT_MS = 65e3;
621
+ const MAX_SEARCH_LENGTH = 500;
622
+ const MAX_CURSOR_LENGTH = 4096;
623
+ const MAX_CURSOR_COUNT = 100;
624
+ const MAX_HOST_ID_LENGTH = 256;
625
+ const MAX_CWD_LENGTH = 4096;
626
+ const MAX_SESSION_NAME_LENGTH = 500;
627
+ const MAX_SESSION_KEY_LENGTH = 1024;
628
+ const MAX_METADATA_LENGTH = 500;
629
+ const MAX_ACTIVE_FLAGS = 16;
630
+ const MAX_TRANSCRIPT_PAGE_BYTES = 20 * 1024 * 1024;
631
+ var CatalogParamsError = class extends Error {};
632
+ function readControlCursor(value, label) {
633
+ if (value === void 0 || value === null) return;
634
+ if (typeof value !== "string" || !value.trim() || value.length > 4096) throw new CatalogParamsError(`invalid Codex session catalog ${label} cursor`);
635
+ return value;
636
+ }
637
+ function boundedCatalogString(value, maxLength, overflow = "omit") {
638
+ if (typeof value !== "string") return;
639
+ const normalized = value.trim();
640
+ if (!normalized) return;
641
+ if (normalized.length <= maxLength) return normalized;
642
+ return overflow === "truncate" ? truncateUtf16Safe(normalized, maxLength) : void 0;
643
+ }
644
+ function normalizeInteractiveThreadSource(source) {
645
+ if (CODEX_INTERACTIVE_THREAD_SOURCE_KINDS.some((kind) => kind === source) || CODEX_INTERACTIVE_CUSTOM_THREAD_SOURCES.some((kind) => kind === source)) return source;
646
+ if (isRecord(source) && CODEX_INTERACTIVE_CUSTOM_THREAD_SOURCES.some((kind) => kind === source.custom)) return source.custom;
647
+ }
648
+ function isInteractiveThreadSource(source) {
649
+ return normalizeInteractiveThreadSource(source) !== void 0;
650
+ }
651
+ function toCatalogSession(thread, archived) {
652
+ const source = normalizeInteractiveThreadSource(thread.source);
653
+ if (!source) return;
654
+ const record = thread;
655
+ const threadId = boundedCatalogString(thread.id, 256);
656
+ if (!threadId) return;
657
+ const activeFlags = thread.status?.type === "active" ? thread.status.activeFlags?.flatMap((flag) => {
658
+ const normalized = boundedCatalogString(flag, 128);
659
+ return normalized ? [normalized] : [];
660
+ }).slice(0, MAX_ACTIVE_FLAGS) : void 0;
661
+ const gitInfo = isRecord(record.gitInfo) ? record.gitInfo : void 0;
662
+ const sessionId = boundedCatalogString(thread.sessionId, 256);
663
+ const name = boundedCatalogString(thread.name, MAX_SESSION_NAME_LENGTH, "truncate");
664
+ const cwd = boundedCatalogString(thread.cwd, MAX_CWD_LENGTH);
665
+ const modelProvider = boundedCatalogString(record.modelProvider, MAX_METADATA_LENGTH, "truncate");
666
+ const cliVersion = boundedCatalogString(record.cliVersion, MAX_METADATA_LENGTH, "truncate");
667
+ const gitBranch = boundedCatalogString(gitInfo?.branch, MAX_METADATA_LENGTH, "truncate");
668
+ return {
669
+ threadId,
670
+ status: thread.status?.type ?? "notLoaded",
671
+ archived,
672
+ ...sessionId ? { sessionId } : {},
673
+ ...thread.name === null ? { name: null } : name ? { name } : {},
674
+ ...cwd ? { cwd } : {},
675
+ ...activeFlags?.length ? { activeFlags } : {},
676
+ ...typeof thread.createdAt === "number" && Number.isFinite(thread.createdAt) ? { createdAt: thread.createdAt } : {},
677
+ ...typeof thread.updatedAt === "number" && Number.isFinite(thread.updatedAt) ? { updatedAt: thread.updatedAt } : {},
678
+ ...typeof record.recencyAt === "number" && Number.isFinite(record.recencyAt) ? { recencyAt: record.recencyAt } : record.recencyAt === null ? { recencyAt: null } : {},
679
+ source,
680
+ ...modelProvider ? { modelProvider } : {},
681
+ ...cliVersion ? { cliVersion } : {},
682
+ ...gitBranch ? { gitBranch } : {}
683
+ };
684
+ }
685
+ function normalizeLimit(value, key) {
686
+ if (value === void 0) return DEFAULT_PAGE_LIMIT;
687
+ if (!Number.isInteger(value) || value < 1 || value > 100) throw new CatalogParamsError(`${key} must be an integer from 1 to 100`);
688
+ return value;
689
+ }
690
+ function readOptionalString(params, key, maxLength) {
691
+ const value = params[key];
692
+ if (value === void 0) return;
693
+ if (typeof value !== "string") throw new CatalogParamsError(`${key} must be a string`);
694
+ const trimmed = value.trim();
695
+ if (!trimmed) return;
696
+ if (trimmed.length > maxLength) throw new CatalogParamsError(`${key} must be at most ${maxLength} characters`);
697
+ return trimmed;
698
+ }
699
+ function requireOnlyKeys(params, allowed) {
700
+ const unknown = Object.keys(params).find((key) => !allowed.has(key));
701
+ if (unknown) throw new CatalogParamsError(`unknown Codex session catalog parameter: ${unknown}`);
702
+ }
703
+ function readPageParams(value) {
704
+ if (!isRecord(value)) throw new CatalogParamsError("Codex session catalog parameters must be an object");
705
+ const params = value;
706
+ requireOnlyKeys(params, /* @__PURE__ */ new Set([
707
+ "cursor",
708
+ "limit",
709
+ "searchTerm",
710
+ "cwd"
711
+ ]));
712
+ const cursor = readOptionalString(params, "cursor", MAX_CURSOR_LENGTH);
713
+ const searchTerm = readOptionalString(params, "searchTerm", MAX_SEARCH_LENGTH);
714
+ const cwd = readOptionalString(params, "cwd", MAX_CWD_LENGTH);
715
+ return {
716
+ limit: normalizeLimit(params.limit, "limit"),
717
+ ...cursor ? { cursor } : {},
718
+ ...searchTerm ? { searchTerm } : {},
719
+ ...cwd ? { cwd } : {}
720
+ };
721
+ }
722
+ function readGatewayParams(value) {
723
+ if (value !== void 0 && !isRecord(value)) throw new CatalogParamsError("Codex session catalog parameters must be an object");
724
+ const params = isRecord(value) ? value : {};
725
+ requireOnlyKeys(params, /* @__PURE__ */ new Set([
726
+ "search",
727
+ "limitPerHost",
728
+ "hostIds",
729
+ "cursors"
730
+ ]));
731
+ const search = readOptionalString(params, "search", MAX_SEARCH_LENGTH);
732
+ let hostIds;
733
+ if (params.hostIds !== void 0) {
734
+ if (!Array.isArray(params.hostIds) || params.hostIds.length > 100) throw new CatalogParamsError(`hostIds must contain at most 100 host ids`);
735
+ hostIds = [...new Set(params.hostIds.map((hostId) => readHostId(hostId)))];
736
+ }
737
+ let cursors;
738
+ if (params.cursors !== void 0) {
739
+ if (!isRecord(params.cursors)) throw new CatalogParamsError("cursors must be an object");
740
+ const entries = Object.entries(params.cursors);
741
+ if (entries.length > MAX_CURSOR_COUNT) throw new CatalogParamsError(`cursors may contain at most ${MAX_CURSOR_COUNT} hosts`);
742
+ cursors = {};
743
+ for (const [hostId, cursor] of entries) {
744
+ const normalizedHostId = hostId.trim();
745
+ if (normalizedHostId.length === 0 || normalizedHostId.length > MAX_HOST_ID_LENGTH || !normalizedHostId.startsWith("gateway:") && !normalizedHostId.startsWith("node:")) throw new CatalogParamsError(`invalid Codex session catalog host id: ${hostId}`);
746
+ if (typeof cursor !== "string" || !cursor.trim() || cursor.trim().length > 4096) throw new CatalogParamsError(`invalid cursor for Codex session catalog host: ${hostId}`);
747
+ cursors[normalizedHostId] = cursor.trim();
748
+ }
749
+ }
750
+ return {
751
+ limitPerHost: normalizeLimit(params.limitPerHost, "limitPerHost"),
752
+ ...search ? { search } : {},
753
+ ...hostIds && hostIds.length > 0 ? { hostIds } : {},
754
+ ...cursors && Object.keys(cursors).length > 0 ? { cursors } : {}
755
+ };
756
+ }
757
+ function readHostId(value) {
758
+ if (typeof value !== "string") throw new CatalogParamsError("Codex session catalog host ids must be strings");
759
+ const hostId = value.trim();
760
+ if (hostId.length === 0 || hostId.length > MAX_HOST_ID_LENGTH || !hostId.startsWith("gateway:") && !hostId.startsWith("node:")) throw new CatalogParamsError(`invalid Codex session catalog host id: ${value}`);
761
+ return hostId;
762
+ }
763
+ function parseJsonParams(paramsJSON) {
764
+ if (!paramsJSON?.trim()) return {};
765
+ try {
766
+ return JSON.parse(paramsJSON);
767
+ } catch (error) {
768
+ throw new Error("Codex session catalog parameters must be valid JSON", { cause: error });
769
+ }
770
+ }
771
+ function readFiniteNumber(value) {
772
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
773
+ }
774
+ function parseOptionalCatalogString(value, field, maxLength) {
775
+ if (value === void 0) return;
776
+ if (typeof value !== "string" || value.length > maxLength) throw new Error(`Codex session catalog returned an invalid ${field}`);
777
+ return value;
778
+ }
779
+ function parseCatalogSession(value, options = {}) {
780
+ if (!isRecord(value) || typeof value.threadId !== "string" || !value.threadId.trim() || value.threadId.length > 256 || value.archived !== false) throw new Error("Codex session catalog returned an invalid session");
781
+ const status = parseOptionalCatalogString(value.status, "status", 64);
782
+ if (!status?.trim()) throw new Error("Codex session catalog returned an invalid status");
783
+ if (value.activeFlags !== void 0 && !Array.isArray(value.activeFlags)) throw new Error("Codex session catalog returned invalid active flags");
784
+ if (Array.isArray(value.activeFlags) && value.activeFlags.length > MAX_ACTIVE_FLAGS) throw new Error("Codex session catalog returned too many active flags");
785
+ const activeFlags = Array.isArray(value.activeFlags) ? value.activeFlags.map((entry) => {
786
+ const flag = parseOptionalCatalogString(entry, "active flag", 128);
787
+ if (flag === void 0) throw new Error("Codex session catalog returned an invalid active flag");
788
+ return flag;
789
+ }) : void 0;
790
+ const sessionId = parseOptionalCatalogString(value.sessionId, "session id", 256);
791
+ const name = value.name === null ? null : parseOptionalCatalogString(value.name, "session name", MAX_SESSION_NAME_LENGTH);
792
+ const cwd = parseOptionalCatalogString(value.cwd, "cwd", MAX_CWD_LENGTH);
793
+ const source = parseOptionalCatalogString(value.source, "source", MAX_METADATA_LENGTH);
794
+ const modelProvider = parseOptionalCatalogString(value.modelProvider, "model provider", MAX_METADATA_LENGTH);
795
+ const cliVersion = parseOptionalCatalogString(value.cliVersion, "CLI version", MAX_METADATA_LENGTH);
796
+ const gitBranch = parseOptionalCatalogString(value.gitBranch, "Git branch", MAX_METADATA_LENGTH);
797
+ const openClawSessionKey = options.allowOpenClawSessionKey ? parseOptionalCatalogString(value.openClawSessionKey, "OpenClaw session key", MAX_SESSION_KEY_LENGTH) : void 0;
798
+ const createdAt = readFiniteNumber(value.createdAt);
799
+ const updatedAt = readFiniteNumber(value.updatedAt);
800
+ const recencyAt = value.recencyAt === null ? null : readFiniteNumber(value.recencyAt);
801
+ return {
802
+ threadId: value.threadId,
803
+ status,
804
+ archived: value.archived,
805
+ ...sessionId !== void 0 ? { sessionId } : {},
806
+ ...name !== void 0 ? { name } : {},
807
+ ...cwd !== void 0 ? { cwd } : {},
808
+ ...activeFlags && activeFlags.length > 0 ? { activeFlags } : {},
809
+ ...createdAt !== void 0 ? { createdAt } : {},
810
+ ...updatedAt !== void 0 ? { updatedAt } : {},
811
+ ...recencyAt !== void 0 ? { recencyAt } : {},
812
+ ...source !== void 0 ? { source } : {},
813
+ ...modelProvider !== void 0 ? { modelProvider } : {},
814
+ ...cliVersion !== void 0 ? { cliVersion } : {},
815
+ ...gitBranch !== void 0 ? { gitBranch } : {},
816
+ ...openClawSessionKey !== void 0 ? { openClawSessionKey } : {}
817
+ };
818
+ }
819
+ function parseCatalogPage(value, options = {}) {
820
+ if (!isRecord(value) || !Array.isArray(value.sessions) || value.sessions.length > 100) throw new Error("Codex session catalog returned an invalid page");
821
+ const nextCursor = parseOptionalCatalogString(value.nextCursor, "next cursor", MAX_CURSOR_LENGTH);
822
+ const backwardsCursor = parseOptionalCatalogString(value.backwardsCursor, "backwards cursor", MAX_CURSOR_LENGTH);
823
+ return {
824
+ sessions: value.sessions.map((session) => parseCatalogSession(session, options)),
825
+ ...nextCursor ? { nextCursor } : {},
826
+ ...backwardsCursor ? { backwardsCursor } : {}
827
+ };
828
+ }
829
+ function filterCatalogPageByTitle(page, searchTerm) {
830
+ if (!searchTerm) return page;
831
+ return {
832
+ ...page,
833
+ sessions: page.sessions.filter((session) => session.name?.toLocaleLowerCase().includes(searchTerm.toLocaleLowerCase()))
834
+ };
835
+ }
836
+ function unwrapNodeInvokePayload(value) {
837
+ if (!isRecord(value)) return value;
838
+ if (typeof value.payloadJSON === "string" && value.payloadJSON.trim()) try {
839
+ return JSON.parse(value.payloadJSON);
840
+ } catch (error) {
841
+ throw new Error("Codex node returned malformed session catalog JSON", { cause: error });
842
+ }
843
+ return "payload" in value ? value.payload : value;
844
+ }
845
+ function catalogErrorDetail(error) {
846
+ if (error instanceof Error) return error.message.trim();
847
+ if (typeof error === "string") return error.trim();
848
+ if (error && typeof error === "object" && "message" in error) {
849
+ const message = error.message;
850
+ return typeof message === "string" ? message.trim() : "";
851
+ }
852
+ return "";
853
+ }
854
+ function catalogError(code, error) {
855
+ const summary = {
856
+ APP_SERVER_UNAVAILABLE: "Codex app-server is unavailable on this host",
857
+ NODE_INVOKE_FAILED: "The paired node could not return its Codex session catalog",
858
+ NODE_LIST_FAILED: "Paired nodes could not be listed"
859
+ }[code] ?? "Codex session catalog request failed";
860
+ const detail = code === "NODE_LIST_FAILED" ? catalogErrorDetail(error) : "";
861
+ return {
862
+ code,
863
+ message: detail && detail !== summary ? `${summary}: ${detail}` : summary
864
+ };
865
+ }
866
+ function parseTranscriptPage(value) {
867
+ if (!isRecord(value) || !Array.isArray(value.data) || value.data.length > 50 || value.data.some((turn) => !isRecord(turn) || !Array.isArray(turn.items) || turn.items.some((item) => !isRecord(item)))) throw new Error("Codex app-server returned an invalid transcript page");
868
+ const nextCursor = readControlCursor(value.nextCursor, "transcript next response");
869
+ const backwardsCursor = readControlCursor(value.backwardsCursor, "transcript backwards response");
870
+ const page = {
871
+ data: value.data,
872
+ ...nextCursor ? { nextCursor } : {},
873
+ ...backwardsCursor ? { backwardsCursor } : {}
874
+ };
875
+ if (Buffer.byteLength(JSON.stringify(page), "utf8") > MAX_TRANSCRIPT_PAGE_BYTES) throw new Error("Codex app-server transcript page exceeds the safe response size");
876
+ return page;
877
+ }
878
+ function requireBoundThread(entry) {
879
+ if (!entry.boundThreadId) throw new CatalogParamsError("Codex adoption is missing its bound thread. Retry.");
880
+ return entry.boundThreadId;
881
+ }
882
+ //#endregion
883
+ //#region extensions/codex/src/session-catalog-node-adoption.ts
884
+ const CODEX_NODE_SESSION_KEY_PREFIX = "harness:codex:node-session:";
885
+ const continueOperations = /* @__PURE__ */ new Map();
886
+ const sessionActionTails = /* @__PURE__ */ new Map();
887
+ async function runSessionActionExclusive(threadId, run) {
888
+ const operation = (sessionActionTails.get(threadId) ?? Promise.resolve()).then(run);
889
+ const tail = operation.then(() => void 0, () => void 0);
890
+ sessionActionTails.set(threadId, tail);
891
+ try {
892
+ return await operation;
893
+ } finally {
894
+ if (sessionActionTails.get(threadId) === tail) sessionActionTails.delete(threadId);
895
+ }
896
+ }
897
+ function adoptionSessionKeyRest(sessionKey) {
898
+ const trimmed = sessionKey.trim();
899
+ return parseAgentSessionKey(trimmed)?.rest ?? trimmed;
900
+ }
901
+ function listSupervisionAgentIds(config) {
902
+ const defaultAgentId = resolveDefaultAgentId(config);
903
+ return [defaultAgentId, ...listAgentIds(config).filter((agentId) => agentId !== defaultAgentId)];
904
+ }
905
+ function adoptedSourceKey(hostId, threadId) {
906
+ return `${hostId}\u0000${threadId}`;
907
+ }
908
+ function lastTerminalTurnId(thread) {
909
+ for (let index = (thread.turns?.length ?? 0) - 1; index >= 0; index -= 1) {
910
+ const turn = thread.turns?.[index];
911
+ const turnId = boundedCatalogString(turn?.id, 256);
912
+ if (!turnId) continue;
913
+ if (turn?.status === "completed" || turn?.status === "interrupted" || turn?.status === "failed") return turnId;
914
+ }
915
+ }
916
+ function nodeAdoptionSessionKey(hostId, threadId) {
917
+ const digest = createHash("sha256").update(JSON.stringify([hostId, threadId])).digest("hex");
918
+ return `${CODEX_NODE_SESSION_KEY_PREFIX}${digest}`;
919
+ }
920
+ function readNodeSessionMarker(entry) {
921
+ const codex = isRecord(entry.pluginExtensions?.codex) ? entry.pluginExtensions.codex : void 0;
922
+ const marker = codex && isRecord(codex.sessionCatalog) ? codex.sessionCatalog : void 0;
923
+ if (!marker || typeof marker.sourceHostId !== "string" || !marker.sourceHostId.startsWith("node:") || typeof marker.sourceThreadId !== "string" || !marker.sourceThreadId.trim() || typeof marker.nodeId !== "string" || !marker.nodeId.trim()) return;
924
+ return {
925
+ sourceHostId: marker.sourceHostId,
926
+ sourceThreadId: marker.sourceThreadId,
927
+ nodeId: marker.nodeId,
928
+ ...marker.initializing === true ? { initializing: true } : {}
929
+ };
930
+ }
931
+ function listNodeAdoptedSessionEntries(params) {
932
+ const adopted = /* @__PURE__ */ new Map();
933
+ for (const agentId of listSupervisionAgentIds(params.config ?? {})) for (const { entry, sessionKey } of params.runtime.agent.session.listSessionEntries({ agentId })) {
934
+ const marker = readNodeSessionMarker(entry);
935
+ const sessionId = entry.sessionId?.trim();
936
+ if (!marker || marker.initializing === true && params.includeInitializing !== true || entry.initializationPending === true || entry.agentHarnessId !== "codex" || entry.modelSelectionLocked !== true || !sessionId || adoptionSessionKeyRest(sessionKey) !== nodeAdoptionSessionKey(marker.sourceHostId, marker.sourceThreadId) || marker.sourceHostId !== `node:${marker.nodeId}`) continue;
937
+ const sourceKey = adoptedSourceKey(marker.sourceHostId, marker.sourceThreadId);
938
+ if (adopted.has(sourceKey)) throw new Error(`multiple OpenClaw sessions adopt Codex thread ${marker.sourceThreadId} on ${marker.sourceHostId}`);
939
+ adopted.set(sourceKey, {
940
+ key: sessionKey,
941
+ sessionId,
942
+ agentId,
943
+ ...marker.initializing === true ? { initializing: true } : {}
944
+ });
945
+ }
946
+ return adopted;
947
+ }
948
+ function findNodeAdoptedSessionEntry(params) {
949
+ return listNodeAdoptedSessionEntries(params).get(adoptedSourceKey(params.hostId, params.threadId));
950
+ }
951
+ function nodeSessionMarker(params) {
952
+ return {
953
+ sourceHostId: params.hostId,
954
+ sourceThreadId: params.threadId,
955
+ nodeId: params.nodeId,
956
+ ...params.initializing === true ? { initializing: true } : {}
957
+ };
958
+ }
959
+ async function finalizeNodeAdoptedSession(params) {
960
+ const changedError = () => new CatalogParamsError("Codex OpenClaw session changed before it could be bound. Retry.");
961
+ let finalized;
962
+ try {
963
+ finalized = await params.api.runtime.agent.session.patchSessionEntry({
964
+ sessionKey: params.adopted.key,
965
+ readConsistency: "latest",
966
+ preserveActivity: true,
967
+ update: (entry) => {
968
+ const current = readNodeSessionMarker(entry);
969
+ if (entry.sessionId?.trim() !== params.adopted.sessionId || entry.initializationPending === true || entry.agentHarnessId !== "codex" || entry.modelSelectionLocked !== true || !current || current.sourceHostId !== params.marker.sourceHostId || current.sourceThreadId !== params.marker.sourceThreadId || current.nodeId !== params.marker.nodeId) throw changedError();
970
+ if (current.initializing !== true) return { archivedAt: void 0 };
971
+ const codex = isRecord(entry.pluginExtensions?.codex) ? entry.pluginExtensions.codex : {};
972
+ return {
973
+ archivedAt: void 0,
974
+ pluginExtensions: {
975
+ ...entry.pluginExtensions,
976
+ codex: {
977
+ ...codex,
978
+ sessionCatalog: params.marker
979
+ }
980
+ }
981
+ };
982
+ }
983
+ });
984
+ } catch (error) {
985
+ const currentEntry = params.api.runtime.agent.session.getSessionEntry({
986
+ sessionKey: params.adopted.key,
987
+ readConsistency: "latest"
988
+ });
989
+ const current = currentEntry ? readNodeSessionMarker(currentEntry) : void 0;
990
+ if (currentEntry?.sessionId?.trim() === params.adopted.sessionId && current?.initializing !== true && current?.sourceHostId === params.marker.sourceHostId && current.sourceThreadId === params.marker.sourceThreadId && current.nodeId === params.marker.nodeId) return;
991
+ throw error;
992
+ }
993
+ if (!finalized) throw changedError();
994
+ }
995
+ async function createOrReuseNodeAdoptedSession(params) {
996
+ const existing = findNodeAdoptedSessionEntry({
997
+ config: params.config,
998
+ runtime: params.api.runtime,
999
+ hostId: params.hostId,
1000
+ threadId: params.record.threadId,
1001
+ includeInitializing: true
1002
+ });
1003
+ if (existing) return existing;
1004
+ const initializingMarker = {
1005
+ ...nodeSessionMarker({
1006
+ hostId: params.hostId,
1007
+ threadId: params.record.threadId,
1008
+ nodeId: params.nodeId
1009
+ }),
1010
+ initializing: true
1011
+ };
1012
+ try {
1013
+ const created = await params.api.runtime.agent.session.createSessionEntry({
1014
+ cfg: params.config,
1015
+ key: nodeAdoptionSessionKey(params.hostId, params.record.threadId),
1016
+ agentId: resolveDefaultAgentId(params.config),
1017
+ recoverMatchingInitialEntry: true,
1018
+ ...params.record.name?.trim() ? { label: params.record.name.trim() } : {},
1019
+ ...params.record.cwd?.trim() ? { spawnedCwd: params.record.cwd.trim() } : {},
1020
+ initialEntry: {
1021
+ agentHarnessId: "codex",
1022
+ modelSelectionLocked: true,
1023
+ pluginExtensions: { codex: { sessionCatalog: initializingMarker } }
1024
+ },
1025
+ afterCreate: async (entry) => {
1026
+ const storePath = resolveStorePath(params.config.session?.store, { agentId: entry.agentId });
1027
+ await importCodexThreadHistoryToTranscript({
1028
+ thread: params.history.thread,
1029
+ throughTurnId: params.history.throughTurnId,
1030
+ storePath,
1031
+ sessionId: entry.sessionId,
1032
+ sessionKey: entry.key,
1033
+ agentId: entry.agentId,
1034
+ ...params.record.cwd?.trim() ? { cwd: params.record.cwd.trim() } : {},
1035
+ modelProvider: params.record.modelProvider,
1036
+ config: params.config
1037
+ });
1038
+ return { pluginExtensions: { codex: { sessionCatalog: initializingMarker } } };
1039
+ }
1040
+ });
1041
+ return {
1042
+ key: created.key,
1043
+ sessionId: created.sessionId,
1044
+ agentId: created.agentId,
1045
+ initializing: true
1046
+ };
1047
+ } catch (error) {
1048
+ const raced = findNodeAdoptedSessionEntry({
1049
+ config: params.config,
1050
+ runtime: params.api.runtime,
1051
+ hostId: params.hostId,
1052
+ threadId: params.record.threadId,
1053
+ includeInitializing: true
1054
+ });
1055
+ if (raced) return raced;
1056
+ throw error;
1057
+ }
1058
+ }
1059
+ //#endregion
1060
+ //#region extensions/codex/src/session-catalog-node-continue.ts
1061
+ const CODEX_NODE_CONTINUE_COMMANDS = [
1062
+ CODEX_APP_SERVER_THREADS_LIST_COMMAND,
1063
+ CODEX_APP_SERVER_THREAD_TURNS_LIST_COMMAND,
1064
+ CODEX_CLI_SESSION_RESUME_COMMAND
1065
+ ];
1066
+ function nodeLabel(node) {
1067
+ return node.displayName?.trim() || node.remoteIp?.trim() || node.nodeId;
1068
+ }
1069
+ function compareNodeLabels(left, right) {
1070
+ const leftLabel = nodeLabel(left);
1071
+ const rightLabel = nodeLabel(right);
1072
+ if (leftLabel < rightLabel) return -1;
1073
+ if (leftLabel > rightLabel) return 1;
1074
+ return 0;
1075
+ }
1076
+ function canContinueCodexOnNode(node) {
1077
+ return node.connected === true && CODEX_NODE_CONTINUE_COMMANDS.every((command) => node.commands?.includes(command) === true && node.invocableCommands?.includes(command) === true);
1078
+ }
1079
+ async function listPairedNode(params) {
1080
+ const hostId = `node:${params.node.nodeId}`;
1081
+ const common = {
1082
+ hostId,
1083
+ label: nodeLabel(params.node),
1084
+ kind: "node",
1085
+ nodeId: params.node.nodeId,
1086
+ canContinueCodex: canContinueCodexOnNode(params.node)
1087
+ };
1088
+ if (params.node.connected !== true) return {
1089
+ ...common,
1090
+ connected: false,
1091
+ sessions: [],
1092
+ error: {
1093
+ code: "NODE_OFFLINE",
1094
+ message: "Paired node is offline"
1095
+ }
1096
+ };
1097
+ try {
1098
+ const page = filterCatalogPageByTitle(parseCatalogPage(unwrapNodeInvokePayload(await params.runtime.nodes.invoke({
1099
+ nodeId: params.node.nodeId,
1100
+ command: CODEX_APP_SERVER_THREADS_LIST_COMMAND,
1101
+ params: {
1102
+ cursor: params.query.cursors?.[hostId],
1103
+ limit: params.query.limitPerHost,
1104
+ searchTerm: params.query.search
1105
+ },
1106
+ timeoutMs: NODE_INVOKE_TIMEOUT_MS,
1107
+ scopes: ["operator.write"]
1108
+ }))), params.query.search);
1109
+ return {
1110
+ ...common,
1111
+ connected: true,
1112
+ ...page,
1113
+ sessions: page.sessions.map((session) => {
1114
+ const adopted = params.adoptedSessions.get(adoptedSourceKey(hostId, session.threadId));
1115
+ return adopted ? Object.assign({}, session, { openClawSessionKey: adopted.key }) : session;
1116
+ })
1117
+ };
1118
+ } catch (error) {
1119
+ return {
1120
+ ...common,
1121
+ connected: true,
1122
+ sessions: [],
1123
+ error: catalogError("NODE_INVOKE_FAILED", error)
1124
+ };
1125
+ }
1126
+ }
1127
+ async function requireNodeForCodexContinue(params) {
1128
+ const nodeId = params.hostId.slice(5).trim();
1129
+ if (!nodeId || params.hostId !== `node:${nodeId}`) throw new CatalogParamsError("Codex session catalog hostId is invalid");
1130
+ const node = (await params.runtime.nodes.list()).nodes.find((candidate) => candidate.nodeId === nodeId);
1131
+ if (!node || !canContinueCodexOnNode(node)) throw new CatalogParamsError("paired node does not permit Codex session continuation");
1132
+ return {
1133
+ node,
1134
+ nodeId
1135
+ };
1136
+ }
1137
+ async function resolveNodeCodexRecord(params) {
1138
+ let cursor;
1139
+ const seenCursors = /* @__PURE__ */ new Set();
1140
+ for (let pageIndex = 0; pageIndex < 100; pageIndex += 1) {
1141
+ const page = parseCatalogPage(unwrapNodeInvokePayload(await params.runtime.nodes.invoke({
1142
+ nodeId: params.nodeId,
1143
+ command: CODEX_APP_SERVER_THREADS_LIST_COMMAND,
1144
+ params: {
1145
+ limit: 100,
1146
+ ...cursor ? { cursor } : {}
1147
+ },
1148
+ timeoutMs: NODE_INVOKE_TIMEOUT_MS,
1149
+ scopes: ["operator.write"]
1150
+ })));
1151
+ const record = page.sessions.find((candidate) => candidate.threadId === params.threadId);
1152
+ if (record) return record;
1153
+ const nextCursor = page.nextCursor?.trim();
1154
+ if (!nextCursor) break;
1155
+ if (seenCursors.has(nextCursor)) throw new CatalogParamsError("Codex session eligibility could not be verified");
1156
+ seenCursors.add(nextCursor);
1157
+ cursor = nextCursor;
1158
+ }
1159
+ throw new CatalogParamsError("Codex session is unavailable on the paired node");
1160
+ }
1161
+ function requireContinuableNodeRecord(record) {
1162
+ if (record.archived) throw new CatalogParamsError("Codex session is archived on the paired node");
1163
+ if (!isInteractiveThreadSource(record.source)) throw new CatalogParamsError("Codex session is not a non-archived interactive Codex session");
1164
+ if (record.status === "idle" || record.status === "notLoaded") return;
1165
+ if (record.status === "active") throw new CatalogParamsError("Codex session is active on the paired node; wait for it to finish before continuing");
1166
+ throw new CatalogParamsError("Codex session cannot be continued in its current state");
1167
+ }
1168
+ async function readNodeCodexHistory(params) {
1169
+ const page = parseTranscriptPage(unwrapNodeInvokePayload(await params.runtime.nodes.invoke({
1170
+ nodeId: params.nodeId,
1171
+ command: CODEX_APP_SERVER_THREAD_TURNS_LIST_COMMAND,
1172
+ params: {
1173
+ threadId: params.record.threadId,
1174
+ limit: 50
1175
+ },
1176
+ timeoutMs: NODE_INVOKE_TIMEOUT_MS,
1177
+ scopes: ["operator.write"]
1178
+ })));
1179
+ const thread = {
1180
+ id: params.record.threadId,
1181
+ createdAt: params.record.createdAt ?? 0,
1182
+ modelProvider: params.record.modelProvider ?? "openai",
1183
+ turns: page.data.toReversed()
1184
+ };
1185
+ return {
1186
+ thread,
1187
+ throughTurnId: lastTerminalTurnId(thread) ?? null
1188
+ };
1189
+ }
1190
+ async function continueNodeCodexSessionInner(params) {
1191
+ const { nodeId } = await requireNodeForCodexContinue({
1192
+ runtime: params.api.runtime,
1193
+ hostId: params.hostId
1194
+ });
1195
+ const record = await resolveNodeCodexRecord({
1196
+ runtime: params.api.runtime,
1197
+ nodeId,
1198
+ threadId: params.threadId
1199
+ });
1200
+ requireContinuableNodeRecord(record);
1201
+ const existing = findNodeAdoptedSessionEntry({
1202
+ config: params.config,
1203
+ runtime: params.api.runtime,
1204
+ hostId: params.hostId,
1205
+ threadId: params.threadId,
1206
+ includeInitializing: true
1207
+ });
1208
+ let adopted;
1209
+ let disposition;
1210
+ if (existing) {
1211
+ adopted = existing;
1212
+ disposition = "existing";
1213
+ } else {
1214
+ const history = await readNodeCodexHistory({
1215
+ runtime: params.api.runtime,
1216
+ nodeId,
1217
+ record
1218
+ });
1219
+ adopted = await createOrReuseNodeAdoptedSession({
1220
+ api: params.api,
1221
+ config: params.config,
1222
+ hostId: params.hostId,
1223
+ nodeId,
1224
+ record,
1225
+ history
1226
+ });
1227
+ disposition = "forked";
1228
+ }
1229
+ const marker = nodeSessionMarker({
1230
+ hostId: params.hostId,
1231
+ threadId: params.threadId,
1232
+ nodeId
1233
+ });
1234
+ return {
1235
+ sessionKey: adopted.key,
1236
+ disposition,
1237
+ conversationBinding: {
1238
+ summary: "Continue this Codex session on its paired node.",
1239
+ detachHint: "Start a new chat to leave the paired-node Codex session.",
1240
+ data: createCodexCliNodeConversationBindingData({
1241
+ nodeId,
1242
+ sessionId: record.sessionId?.trim() || params.threadId,
1243
+ agentId: adopted.agentId,
1244
+ cwd: record.cwd
1245
+ })
1246
+ },
1247
+ afterConversationBound: async () => await finalizeNodeAdoptedSession({
1248
+ api: params.api,
1249
+ adopted,
1250
+ marker
1251
+ })
1252
+ };
1253
+ }
1254
+ async function continueNodeCodexSession(params) {
1255
+ if (params.clientScopes?.includes("operator.admin") !== true) throw new CatalogParamsError("continuing a paired-node Codex session requires operator.admin");
1256
+ const nodeId = params.hostId.slice(5).trim();
1257
+ if (!nodeId || params.hostId !== `node:${nodeId}`) throw new CatalogParamsError("Codex session catalog hostId is invalid");
1258
+ const sourceKey = adoptedSourceKey(`node:${nodeId}`, params.threadId);
1259
+ const current = continueOperations.get(sourceKey);
1260
+ if (current) return await current;
1261
+ const operation = runSessionActionExclusive(sourceKey, async () => continueNodeCodexSessionInner(params));
1262
+ continueOperations.set(sourceKey, operation);
1263
+ try {
1264
+ return await operation;
1265
+ } finally {
1266
+ if (continueOperations.get(sourceKey) === operation) continueOperations.delete(sourceKey);
1267
+ }
1268
+ }
1269
+ //#endregion
1270
+ //#region extensions/codex/src/session-catalog-terminal.ts
1271
+ const CODEX_TERMINAL_RESUME_COMMAND = "codex.terminal.resume.v1";
1272
+ function resolveLocalCodexTerminalExecutable(env = process.env) {
1273
+ return resolveLocalCodexTerminalResolution(env)?.executable;
1274
+ }
1275
+ function resolveLocalCodexTerminalResolution(env = process.env) {
1276
+ return resolveNodeHostExecutable("codex", {
1277
+ env,
1278
+ pathEnv: env.PATH ?? env.Path ?? "",
1279
+ strategy: "fallback"
1280
+ });
1281
+ }
1282
+ function codexNodeTerminalCapability(node) {
1283
+ const commands = node.invocableCommands ?? node.commands;
1284
+ return node.connected === true && commands?.includes("codex.terminal.resume.v1") === true ? { canOpenTerminalCodex: true } : {};
1285
+ }
1286
+ async function requireCatalogEligibleThread(control, threadId) {
1287
+ let cursor;
1288
+ const seenCursors = /* @__PURE__ */ new Set();
1289
+ for (let pageIndex = 0; pageIndex < 100; pageIndex += 1) {
1290
+ const page = await control.listPage({
1291
+ limit: 100,
1292
+ ...cursor ? { cursor } : {}
1293
+ });
1294
+ const candidate = page.sessions.find((session) => session.threadId === threadId);
1295
+ if (candidate) {
1296
+ if (isInteractiveThreadSource(candidate.source)) return candidate;
1297
+ throw new CatalogParamsError("Codex session is not a non-archived interactive Codex session");
1298
+ }
1299
+ const nextCursor = page.nextCursor?.trim();
1300
+ if (!nextCursor) throw new CatalogParamsError("Codex session is not a non-archived interactive Codex session");
1301
+ if (seenCursors.has(nextCursor)) throw new CatalogParamsError("Codex session eligibility could not be verified");
1302
+ seenCursors.add(nextCursor);
1303
+ cursor = nextCursor;
1304
+ }
1305
+ throw new CatalogParamsError("Codex session eligibility could not be verified");
1306
+ }
1307
+ function createCodexTerminalNodeHostCommand(control) {
1308
+ return {
1309
+ command: CODEX_TERMINAL_RESUME_COMMAND,
1310
+ cap: CODEX_APP_SERVER_THREADS_CAPABILITY,
1311
+ dangerous: false,
1312
+ duplex: true,
1313
+ isAvailable: ({ env }) => Boolean(resolveNodeHostExecutable("codex", {
1314
+ env,
1315
+ pathEnv: env.PATH ?? env.Path ?? "",
1316
+ strategy: "direct"
1317
+ })),
1318
+ handle: async (paramsJSON, io) => {
1319
+ if (!io) throw new Error("Codex terminal command requires duplex transport");
1320
+ const resume = decodeNodePtyResumeParams(paramsJSON, (value) => {
1321
+ if (typeof value !== "string" || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu.test(value)) throw new CatalogParamsError("threadId must be a UUID");
1322
+ return value;
1323
+ });
1324
+ const record = await requireCatalogEligibleThread(control, resume.threadId);
1325
+ const resolution = resolveNodeHostExecutable("codex", {
1326
+ env: process.env,
1327
+ pathEnv: process.env.PATH ?? process.env.Path ?? "",
1328
+ strategy: "direct"
1329
+ });
1330
+ if (!resolution) throw new Error("Codex CLI is unavailable");
1331
+ return JSON.stringify(await runNodePtyCommand({
1332
+ file: resolution.executable,
1333
+ args: ["resume", resume.threadId],
1334
+ cwd: record.cwd,
1335
+ cols: resume.cols,
1336
+ rows: resume.rows
1337
+ }, io));
1338
+ }
1339
+ };
1340
+ }
1341
+ async function resolveNodeCatalogEligibleThread(params) {
1342
+ let cursor;
1343
+ const seenCursors = /* @__PURE__ */ new Set();
1344
+ for (let pageIndex = 0; pageIndex < 100; pageIndex += 1) {
1345
+ const raw = await params.runtime.nodes.invoke({
1346
+ nodeId: params.nodeId,
1347
+ command: CODEX_APP_SERVER_THREADS_LIST_COMMAND,
1348
+ params: {
1349
+ limit: 100,
1350
+ ...cursor ? { cursor } : {}
1351
+ },
1352
+ timeoutMs: NODE_INVOKE_TIMEOUT_MS,
1353
+ scopes: ["operator.write"]
1354
+ });
1355
+ const page = params.parseCatalogPage(unwrapNodeInvokePayload(raw));
1356
+ const record = page.sessions.find((candidate) => candidate.threadId === params.threadId);
1357
+ if (record) {
1358
+ if (isInteractiveThreadSource(record.source)) return record;
1359
+ break;
1360
+ }
1361
+ const nextCursor = page.nextCursor?.trim();
1362
+ if (!nextCursor || seenCursors.has(nextCursor)) break;
1363
+ seenCursors.add(nextCursor);
1364
+ cursor = nextCursor;
1365
+ }
1366
+ throw new CatalogParamsError("Codex session is not a non-archived interactive Codex session");
1367
+ }
1368
+ async function openCodexCatalogTerminal(params) {
1369
+ const title = `codex resume ${params.threadId.slice(0, 8)}…`;
1370
+ if (params.hostId === "gateway:local") {
1371
+ const record = await requireCatalogEligibleThread(params.control, params.threadId);
1372
+ const resolution = resolveLocalCodexTerminalResolution();
1373
+ if (!resolution) throw new CatalogParamsError("Codex CLI is unavailable");
1374
+ return {
1375
+ kind: "local",
1376
+ argv: [
1377
+ resolution.executable,
1378
+ "resume",
1379
+ params.threadId
1380
+ ],
1381
+ ...record.cwd ? { cwd: record.cwd } : {},
1382
+ ...resolution.pathEnv ? { pathEnv: resolution.pathEnv } : {},
1383
+ title
1384
+ };
1385
+ }
1386
+ if (!params.hostId.startsWith("node:")) throw new CatalogParamsError("hostId is invalid");
1387
+ const nodeId = params.hostId.slice(5);
1388
+ if (!(await params.api.runtime.nodes.list()).nodes.find((candidate) => {
1389
+ const commands = candidate.invocableCommands ?? candidate.commands;
1390
+ return candidate.nodeId === nodeId && candidate.connected === true && commands?.includes("codex.appServer.threads.list.v1") === true && commands.includes("codex.terminal.resume.v1");
1391
+ })) throw new CatalogParamsError("paired-node Codex terminal is unavailable");
1392
+ const record = await resolveNodeCatalogEligibleThread({
1393
+ runtime: params.api.runtime,
1394
+ nodeId,
1395
+ threadId: params.threadId,
1396
+ parseCatalogPage: params.parseCatalogPage
1397
+ });
1398
+ return {
1399
+ kind: "node",
1400
+ nodeId,
1401
+ command: CODEX_TERMINAL_RESUME_COMMAND,
1402
+ paramsJSON: JSON.stringify({ threadId: params.threadId }),
1403
+ ...record.cwd ? { cwd: record.cwd } : {},
1404
+ title
1405
+ };
1406
+ }
1407
+ //#endregion
1408
+ //#region extensions/codex/src/session-catalog-transcript-item.ts
1409
+ const CODEX_MESSAGE_TYPES = /* @__PURE__ */ new Map([
1410
+ ["userMessage", "userMessage"],
1411
+ ["agentMessage", "agentMessage"],
1412
+ ["reasoning", "reasoning"]
1413
+ ]);
1414
+ const CODEX_TOOL_TYPES = /* @__PURE__ */ new Set([
1415
+ "commandExecution",
1416
+ "fileChange",
1417
+ "mcpToolCall",
1418
+ "dynamicToolCall",
1419
+ "collabAgentToolCall",
1420
+ "webSearch",
1421
+ "imageView",
1422
+ "imageGeneration"
1423
+ ]);
1424
+ function toGenericTranscriptItem(item) {
1425
+ let type = CODEX_MESSAGE_TYPES.get(item.type);
1426
+ if (!type && CODEX_TOOL_TYPES.has(item.type)) type = item.result !== void 0 || Boolean(item.aggregatedOutput) ? "toolResult" : "toolCall";
1427
+ type ??= "other";
1428
+ const fallback = item.title ?? item.name ?? item.tool ?? item.command ?? item.query ?? void 0;
1429
+ const resultText = item.aggregatedOutput || (item.result === void 0 ? void 0 : JSON.stringify(item.result, null, 2));
1430
+ const changesText = Array.isArray(item.changes) ? item.changes.map((change) => `${change.kind}: ${change.path}`).join("\n") || void 0 : void 0;
1431
+ const text = item.text || resultText || changesText || fallback;
1432
+ return {
1433
+ id: item.id,
1434
+ type,
1435
+ ...text ? { text } : {},
1436
+ raw: item
1437
+ };
1438
+ }
1439
+ //#endregion
1440
+ //#region extensions/codex/src/session-upstream-activity.ts
1441
+ const CODEX_UPSTREAM_TURN_LIMIT = 100;
1442
+ const CODEX_APP_SERVER_INVALID_REQUEST_CODE = -32600;
1443
+ const CODEX_THREAD_NOT_LOADED_MESSAGE_PREFIX = "thread not loaded:";
1444
+ function isCodexThreadGoneError(error) {
1445
+ return error instanceof CodexAppServerRpcError && error.code === CODEX_APP_SERVER_INVALID_REQUEST_CODE && error.message.startsWith(CODEX_THREAD_NOT_LOADED_MESSAGE_PREFIX);
1446
+ }
1447
+ function readMarker(probe) {
1448
+ if (!isRecord(probe.marker)) return;
1449
+ const turnId = probe.marker.turnId;
1450
+ if (turnId !== null && typeof turnId !== "string") return;
1451
+ const count = probe.marker.userMessageCount;
1452
+ if (count !== void 0 && (!Number.isSafeInteger(count) || count < 0)) return;
1453
+ return {
1454
+ turnId,
1455
+ ...count === void 0 ? {} : { userMessageCount: count }
1456
+ };
1457
+ }
1458
+ function upstreamConnectionFingerprint(probe) {
1459
+ return isRecord(probe.upstreamRef) && typeof probe.upstreamRef.connectionFingerprint === "string" ? probe.upstreamRef.connectionFingerprint : void 0;
1460
+ }
1461
+ function classifyCodexUpstreamTurns(params) {
1462
+ const marker = readMarker(params.probe);
1463
+ if (!marker) return;
1464
+ const newest = params.turns[0];
1465
+ if (!newest?.id) return;
1466
+ const markerIndex = marker.turnId === null ? -1 : params.turns.findIndex((turn) => turn.id === marker.turnId);
1467
+ const candidateTurns = markerIndex < 0 ? params.turns : params.turns.slice(0, markerIndex + 1);
1468
+ const newestUserMessageCount = countUserMessages(newest);
1469
+ if (!(marker.turnId !== newest.id || marker.userMessageCount === void 0 || newestUserMessageCount > marker.userMessageCount)) return;
1470
+ const ownTexts = new Set(params.probe.ownRecentUserTexts);
1471
+ let humanTurns = 0;
1472
+ let occurredAt;
1473
+ for (const turn of candidateTurns) {
1474
+ const userMessages = turn.items.filter((item) => item.type === "userMessage");
1475
+ const alreadySeen = turn.id === marker.turnId ? marker.userMessageCount ?? userMessages.length : 0;
1476
+ for (const item of userMessages.slice(alreadySeen)) {
1477
+ const texts = normalizeUserMessageTexts(item);
1478
+ if (ownTexts.has(texts.join(" ")) || texts.length > 1 && texts.every((text) => ownTexts.has(text))) continue;
1479
+ humanTurns += 1;
1480
+ if (occurredAt === void 0) {
1481
+ const timestampSeconds = turn.completedAt ?? turn.startedAt;
1482
+ occurredAt = typeof timestampSeconds === "number" && Number.isFinite(timestampSeconds) ? timestampSeconds * 1e3 : params.now ?? Date.now();
1483
+ }
1484
+ }
1485
+ }
1486
+ const activityId = `${newest.id}:${newestUserMessageCount}`;
1487
+ return {
1488
+ kind: "activity",
1489
+ sessionKey: params.probe.sessionKey,
1490
+ humanTurns,
1491
+ nextMarker: {
1492
+ turnId: newest.id,
1493
+ userMessageCount: newestUserMessageCount
1494
+ },
1495
+ ...humanTurns > 0 ? {
1496
+ occurredAt: occurredAt ?? params.now ?? Date.now(),
1497
+ dedupeId: activityId
1498
+ } : {}
1499
+ };
1500
+ }
1501
+ function countUserMessages(turn) {
1502
+ return turn.items.filter((item) => item.type === "userMessage").length;
1503
+ }
1504
+ function normalizeUserMessageTexts(item) {
1505
+ const typed = item;
1506
+ const contentTexts = typed.content?.filter((input) => input.type === "text").map((input) => input.text.trim().replace(/\s+/g, " ")).filter(Boolean);
1507
+ return contentTexts?.length ? contentTexts : [(typed.text ?? "").trim().replace(/\s+/g, " ")];
1508
+ }
1509
+ async function checkCodexUpstreamActivity(probes, control, resolveThreadId = async (probe) => probe.threadId) {
1510
+ return await control.withPinnedConnection(async (pinned) => {
1511
+ const activities = [];
1512
+ for (const probe of probes) {
1513
+ const fingerprint = upstreamConnectionFingerprint(probe);
1514
+ if (probe.upstreamKind !== "codex-app-server" || !fingerprint || fingerprint !== pinned.connectionFingerprint) continue;
1515
+ try {
1516
+ const threadId = await resolveThreadId(probe);
1517
+ const page = await pinned.listTurnPage({
1518
+ threadId,
1519
+ limit: CODEX_UPSTREAM_TURN_LIMIT,
1520
+ sortDirection: "desc",
1521
+ itemsView: "full"
1522
+ });
1523
+ const marker = readMarker(probe);
1524
+ if (page.data.length === 0 && marker) {
1525
+ try {
1526
+ await pinned.readThread(threadId, false);
1527
+ } catch (error) {
1528
+ if (isCodexThreadGoneError(error)) activities.push({
1529
+ kind: "missing",
1530
+ sessionKey: probe.sessionKey
1531
+ });
1532
+ }
1533
+ continue;
1534
+ }
1535
+ const activity = classifyCodexUpstreamTurns({
1536
+ probe,
1537
+ turns: page.data
1538
+ });
1539
+ if (activity) activities.push(activity);
1540
+ } catch {}
1541
+ }
1542
+ return activities;
1543
+ });
1544
+ }
1545
+ function createChecker(params) {
1546
+ return async (probes) => await checkCodexUpstreamActivity(probes, params.control, async (probe) => {
1547
+ const config = params.getRuntimeConfig();
1548
+ const sessionId = params.api.runtime.agent.session.getSessionEntry({
1549
+ agentId: probe.agentId,
1550
+ sessionKey: probe.sessionKey,
1551
+ readConsistency: "latest"
1552
+ })?.sessionId?.trim();
1553
+ if (!sessionId) return probe.threadId;
1554
+ const binding = await params.bindingStore.read(sessionBindingIdentity({
1555
+ sessionId,
1556
+ sessionKey: probe.sessionKey,
1557
+ config
1558
+ }));
1559
+ return binding?.connectionScope === "supervision" && binding.supervisionSourceThreadId === probe.threadId ? binding.threadId : probe.threadId;
1560
+ });
1561
+ }
1562
+ //#endregion
1563
+ //#region extensions/codex/src/session-upstream-marker.ts
1564
+ function lastIdentifiableTurn(thread, normalizeTurnId) {
1565
+ for (let index = (thread.turns?.length ?? 0) - 1; index >= 0; index -= 1) {
1566
+ const turn = thread.turns?.[index];
1567
+ const turnId = normalizeTurnId(turn?.id);
1568
+ if (turn && turnId) return {
1569
+ ...turn,
1570
+ id: turnId
1571
+ };
1572
+ }
1573
+ }
1574
+ function codexUpstreamBaseline(thread, normalizeTurnId) {
1575
+ const turn = lastIdentifiableTurn(thread, normalizeTurnId);
1576
+ return {
1577
+ turnId: turn?.id ?? null,
1578
+ userMessageCount: turn?.items.filter((item) => item.type === "userMessage").length ?? 0
1579
+ };
1580
+ }
1581
+ function codexLastTerminalTurnId(thread, normalizeTurnId) {
1582
+ for (let index = (thread.turns?.length ?? 0) - 1; index >= 0; index -= 1) {
1583
+ const turn = thread.turns?.[index];
1584
+ const turnId = normalizeTurnId(turn?.id);
1585
+ if (!turn || !turnId) continue;
1586
+ if (turn.status === "completed" || turn.status === "interrupted" || turn.status === "failed") return turnId;
1587
+ }
1588
+ }
1589
+ /** Build the upstream link seed for a continued Codex session, if a baseline exists. */
1590
+ function codexUpstreamContinueResult(sessionKey, threadId, baseline) {
1591
+ if (!baseline) return { sessionKey };
1592
+ return {
1593
+ sessionKey,
1594
+ upstream: {
1595
+ kind: "codex-app-server",
1596
+ ref: {
1597
+ connectionFingerprint: baseline.connectionFingerprint,
1598
+ threadId
1599
+ },
1600
+ marker: {
1601
+ turnId: baseline.turnId,
1602
+ userMessageCount: baseline.userMessageCount
1603
+ }
1604
+ }
1605
+ };
1606
+ }
1607
+ //#endregion
1608
+ //#region extensions/codex/src/session-catalog.ts
1609
+ const boundCatalogSessionId = (value) => boundedCatalogString(value, 256);
1610
+ const CODEX_SUPERVISION_SESSION_KEY_PREFIX = "harness:codex:supervision:";
1611
+ function createCodexSessionCatalogControlFromRequests(params) {
1612
+ return {
1613
+ ...params.connectionFingerprint ? { connectionFingerprint: params.connectionFingerprint } : {},
1614
+ withPinnedConnection: params.withPinnedConnection,
1615
+ async listPage(pageParams) {
1616
+ const limit = normalizeLimit(pageParams.limit, "limit");
1617
+ const search = pageParams.searchTerm?.trim().toLocaleLowerCase() || void 0;
1618
+ const cwd = pageParams.cwd?.trim() || void 0;
1619
+ const maxPages = search ? 20 : 1;
1620
+ const sessions = [];
1621
+ let cursor = readControlCursor(pageParams.cursor, "request");
1622
+ let nextCursor;
1623
+ let backwardsCursor;
1624
+ const seenCursors = new Set(cursor ? [cursor] : []);
1625
+ const requests = params.createRequestSnapshot();
1626
+ const deadline = params.now() + requests.requestTimeoutMs;
1627
+ for (let pageIndex = 0; pageIndex < maxPages; pageIndex += 1) {
1628
+ const remaining = limit - sessions.length;
1629
+ const remainingTimeoutMs = Math.ceil(deadline - params.now());
1630
+ if (remainingTimeoutMs <= 0) throw new Error("Codex session catalog listing timed out");
1631
+ const response = await requests.listThreads({
1632
+ archived: false,
1633
+ limit: remaining,
1634
+ modelProviders: [],
1635
+ sortKey: "recency_at",
1636
+ sortDirection: "desc",
1637
+ ...cwd ? { cwd } : {},
1638
+ ...cursor ? { cursor } : {}
1639
+ }, remainingTimeoutMs);
1640
+ if (pageIndex === 0) backwardsCursor = readControlCursor(response.backwardsCursor, "backwards response");
1641
+ sessions.push(...response.data.flatMap((thread) => {
1642
+ const session = toCatalogSession(thread, false);
1643
+ return session ? [session] : [];
1644
+ }).filter((session) => !search || session.name?.toLocaleLowerCase().includes(search)));
1645
+ nextCursor = readControlCursor(response.nextCursor, "next response");
1646
+ if (!nextCursor || sessions.length >= limit) break;
1647
+ if (seenCursors.has(nextCursor)) throw new Error("Codex session catalog returned a repeated search cursor");
1648
+ seenCursors.add(nextCursor);
1649
+ cursor = nextCursor;
1650
+ }
1651
+ return {
1652
+ sessions,
1653
+ ...nextCursor ? { nextCursor } : {},
1654
+ ...backwardsCursor ? { backwardsCursor } : {}
1655
+ };
1656
+ },
1657
+ async listDescendantPage(listParams) {
1658
+ const requests = params.createRequestSnapshot();
1659
+ return await requests.listThreads(listParams, requests.requestTimeoutMs);
1660
+ },
1661
+ async readThread(threadId, includeTurns = false) {
1662
+ return await params.createRequestSnapshot().readThread(threadId, includeTurns);
1663
+ },
1664
+ async listTurnPage(listParams) {
1665
+ return await params.createRequestSnapshot().listThreadTurns(listParams);
1666
+ },
1667
+ async archiveThread(threadId) {
1668
+ await params.createRequestSnapshot().archiveThread(threadId);
1669
+ }
1670
+ };
1671
+ }
1672
+ /** Builds the passive catalog over the Codex plugin's canonical shared client. */
1673
+ function createCodexSessionCatalogControl(params) {
1674
+ const now = params.now ?? Date.now;
1675
+ const getPluginConfig = () => params.getPluginConfig();
1676
+ const createRequestSnapshot = () => {
1677
+ const pluginConfig = getPluginConfig();
1678
+ const runtime = resolveCodexSupervisionAppServerRuntimeOptions({ pluginConfig });
1679
+ const requestOptions = {
1680
+ config: structuredClone(params.getRuntimeConfig()),
1681
+ startOptions: structuredClone(runtime.start)
1682
+ };
1683
+ return {
1684
+ requestTimeoutMs: runtime.requestTimeoutMs,
1685
+ listThreads: async (listParams, timeoutMs) => await codexControlRequest(pluginConfig, CODEX_CONTROL_METHODS.listThreads, listParams, {
1686
+ ...requestOptions,
1687
+ timeoutMs
1688
+ }),
1689
+ readThread: async (threadId, includeTurns) => (await codexControlRequest(pluginConfig, CODEX_CONTROL_METHODS.readThread, {
1690
+ threadId,
1691
+ includeTurns
1692
+ }, requestOptions)).thread,
1693
+ listThreadTurns: async (listParams) => await codexControlRequest(pluginConfig, CODEX_CONTROL_METHODS.listThreadTurns, listParams, requestOptions),
1694
+ archiveThread: async (threadId) => {
1695
+ await codexControlRequest(pluginConfig, CODEX_CONTROL_METHODS.archiveThread, { threadId }, requestOptions);
1696
+ }
1697
+ };
1698
+ };
1699
+ const withPinnedConnection = async (run) => {
1700
+ const runtime = resolveCodexSupervisionAppServerRuntimeOptions({ pluginConfig: getPluginConfig() });
1701
+ const runtimeConfig = structuredClone(params.getRuntimeConfig());
1702
+ const client = await getLeasedSharedCodexAppServerClient({
1703
+ config: runtimeConfig,
1704
+ startOptions: structuredClone(runtime.start),
1705
+ timeoutMs: runtime.requestTimeoutMs
1706
+ });
1707
+ try {
1708
+ const requests = {
1709
+ requestTimeoutMs: runtime.requestTimeoutMs,
1710
+ listThreads: async (listParams, timeoutMs) => await requestCodexAppServerClientJson({
1711
+ client,
1712
+ method: CODEX_CONTROL_METHODS.listThreads,
1713
+ requestParams: listParams,
1714
+ config: runtimeConfig,
1715
+ timeoutMs
1716
+ }),
1717
+ readThread: async (threadId, includeTurns) => (await requestCodexAppServerClientJson({
1718
+ client,
1719
+ method: CODEX_CONTROL_METHODS.readThread,
1720
+ requestParams: {
1721
+ threadId,
1722
+ includeTurns
1723
+ },
1724
+ config: runtimeConfig,
1725
+ timeoutMs: runtime.requestTimeoutMs
1726
+ })).thread,
1727
+ listThreadTurns: async (listParams) => await requestCodexAppServerClientJson({
1728
+ client,
1729
+ method: CODEX_CONTROL_METHODS.listThreadTurns,
1730
+ requestParams: listParams,
1731
+ config: runtimeConfig,
1732
+ timeoutMs: runtime.requestTimeoutMs
1733
+ }),
1734
+ archiveThread: async (threadId) => {
1735
+ await requestCodexAppServerClientJson({
1736
+ client,
1737
+ method: CODEX_CONTROL_METHODS.archiveThread,
1738
+ requestParams: { threadId },
1739
+ config: runtimeConfig,
1740
+ timeoutMs: runtime.requestTimeoutMs
1741
+ });
1742
+ }
1743
+ };
1744
+ const pinnedControl = createCodexSessionCatalogControlFromRequests({
1745
+ connectionFingerprint: buildCodexAppServerConnectionFingerprint(runtime, resolveDefaultAgentDir(runtimeConfig ?? {})),
1746
+ createRequestSnapshot: () => requests,
1747
+ now,
1748
+ withPinnedConnection: async (nestedRun) => await nestedRun(pinnedControl)
1749
+ });
1750
+ return await run(pinnedControl);
1751
+ } finally {
1752
+ releaseLeasedSharedCodexAppServerClient(client);
1753
+ }
1754
+ };
1755
+ return createCodexSessionCatalogControlFromRequests({
1756
+ createRequestSnapshot,
1757
+ now,
1758
+ withPinnedConnection
1759
+ });
1760
+ }
1761
+ async function listGatewayHost(params) {
1762
+ try {
1763
+ const page = parseCatalogPage(await params.control.listPage({
1764
+ limit: params.query.limitPerHost,
1765
+ ...params.query.cursors?.["gateway:local"] ? { cursor: params.query.cursors[CODEX_LOCAL_SESSION_HOST_ID] } : {},
1766
+ ...params.query.search ? { searchTerm: params.query.search } : {}
1767
+ }));
1768
+ const adoptedSessions = await listAdoptedSessionEntries({
1769
+ bindingStore: params.bindingStore,
1770
+ config: params.config,
1771
+ runtime: params.runtime
1772
+ });
1773
+ return {
1774
+ hostId: CODEX_LOCAL_SESSION_HOST_ID,
1775
+ label: "Local Codex",
1776
+ kind: "gateway",
1777
+ connected: true,
1778
+ ...page,
1779
+ sessions: page.sessions.map((session) => {
1780
+ const adopted = adoptedSessions.get(session.threadId);
1781
+ return adopted ? Object.assign({}, session, { openClawSessionKey: adopted.key }) : session;
1782
+ })
1783
+ };
1784
+ } catch (error) {
1785
+ return {
1786
+ hostId: CODEX_LOCAL_SESSION_HOST_ID,
1787
+ label: "Local Codex",
1788
+ kind: "gateway",
1789
+ connected: false,
1790
+ sessions: [],
1791
+ error: catalogError("APP_SERVER_UNAVAILABLE", error)
1792
+ };
1793
+ }
1794
+ }
1795
+ /** Lists Gateway-local and paired-node Codex sessions with per-host failures. */
1796
+ async function listCodexSessionCatalog(params) {
1797
+ const query = readGatewayParams(params.query);
1798
+ const requestedHostIds = query.hostIds ? new Set(query.hostIds) : void 0;
1799
+ const localHosts = !requestedHostIds || requestedHostIds.has("gateway:local") ? [listGatewayHost({
1800
+ bindingStore: params.bindingStore,
1801
+ config: params.config,
1802
+ control: params.control,
1803
+ query,
1804
+ runtime: params.runtime
1805
+ })] : [];
1806
+ if (!(!requestedHostIds || query.hostIds?.some((hostId) => hostId.startsWith("node:")))) return { hosts: await Promise.all(localHosts) };
1807
+ let nodes;
1808
+ try {
1809
+ nodes = (await params.runtime.nodes.list()).nodes.filter((node) => node.commands?.includes("codex.appServer.threads.list.v1") && (!requestedHostIds || requestedHostIds.has(`node:${node.nodeId}`))).slice(0, 100 - localHosts.length);
1810
+ } catch (error) {
1811
+ return { hosts: [...await Promise.all(localHosts), {
1812
+ hostId: "node:registry",
1813
+ label: "Paired nodes",
1814
+ kind: "node",
1815
+ connected: false,
1816
+ sessions: [],
1817
+ error: catalogError("NODE_LIST_FAILED", error)
1818
+ }] };
1819
+ }
1820
+ const adoptedNodeSessions = listNodeAdoptedSessionEntries({
1821
+ config: params.config,
1822
+ runtime: params.runtime
1823
+ });
1824
+ const nodeHosts = nodes.toSorted(compareNodeLabels).map(async (node) => {
1825
+ const host = await listPairedNode({
1826
+ runtime: params.runtime,
1827
+ node,
1828
+ query,
1829
+ adoptedSessions: adoptedNodeSessions
1830
+ });
1831
+ return Object.assign(host, codexNodeTerminalCapability(node));
1832
+ });
1833
+ return { hosts: await Promise.all([...localHosts, ...nodeHosts]) };
1834
+ }
1835
+ /** Builds the node-local read-only Codex app-server catalog command. */
1836
+ function createCodexSessionCatalogNodeHostCommands(control) {
1837
+ return [
1838
+ {
1839
+ command: CODEX_APP_SERVER_THREADS_LIST_COMMAND,
1840
+ cap: CODEX_APP_SERVER_THREADS_CAPABILITY,
1841
+ dangerous: false,
1842
+ handle: async (paramsJSON) => {
1843
+ const pageParams = readPageParams(parseJsonParams(paramsJSON));
1844
+ try {
1845
+ const page = filterCatalogPageByTitle(parseCatalogPage(await control.listPage(pageParams)), pageParams.searchTerm);
1846
+ return JSON.stringify(page);
1847
+ } catch {
1848
+ throw new Error("Codex app-server catalog is unavailable");
1849
+ }
1850
+ }
1851
+ },
1852
+ {
1853
+ command: CODEX_APP_SERVER_THREAD_TURNS_LIST_COMMAND,
1854
+ cap: CODEX_APP_SERVER_THREADS_CAPABILITY,
1855
+ dangerous: false,
1856
+ handle: async (paramsJSON) => {
1857
+ const action = readNodeTranscriptParams(parseJsonParams(paramsJSON));
1858
+ try {
1859
+ await requireCatalogEligibleThread(control, action.threadId);
1860
+ const page = parseTranscriptPage(await control.listTurnPage({
1861
+ threadId: action.threadId,
1862
+ limit: action.limit,
1863
+ sortDirection: "desc",
1864
+ itemsView: "full",
1865
+ ...action.cursor ? { cursor: action.cursor } : {}
1866
+ }));
1867
+ return JSON.stringify(page);
1868
+ } catch (error) {
1869
+ if (error instanceof CatalogParamsError) throw error;
1870
+ throw new Error("Codex app-server transcript is unavailable", { cause: error });
1871
+ }
1872
+ }
1873
+ },
1874
+ createCodexTerminalNodeHostCommand(control)
1875
+ ];
1876
+ }
1877
+ function readNodeTranscriptParams(value) {
1878
+ if (!isRecord(value)) throw new CatalogParamsError("Codex session read parameters must be an object");
1879
+ requireOnlyKeys(value, /* @__PURE__ */ new Set([
1880
+ "threadId",
1881
+ "cursor",
1882
+ "limit"
1883
+ ]));
1884
+ const threadId = readOptionalString(value, "threadId", 256);
1885
+ if (!threadId) throw new CatalogParamsError("threadId is required");
1886
+ const cursor = readOptionalString(value, "cursor", MAX_CURSOR_LENGTH);
1887
+ return {
1888
+ threadId,
1889
+ limit: readBoundedLimit(value.limit, "limit", 20, 50),
1890
+ ...cursor ? { cursor } : {}
1891
+ };
1892
+ }
1893
+ function readBoundedLimit(value, key, fallback, max) {
1894
+ if (value === void 0) return fallback;
1895
+ if (!Number.isInteger(value) || value < 1 || value > max) throw new CatalogParamsError(`${key} must be an integer from 1 to ${max}`);
1896
+ return value;
1897
+ }
1898
+ function flattenTranscriptPageDesc(page) {
1899
+ return page.data.flatMap((turn) => turn.items.toReversed());
1900
+ }
1901
+ /** Reads the persisted transcript for a Gateway-local or paired-node Codex session. */
1902
+ async function readCodexSessionTranscript(params) {
1903
+ if (params.hostId === "gateway:local") {
1904
+ await requireCatalogEligibleThread(params.control, params.threadId);
1905
+ const page = parseTranscriptPage(await params.control.listTurnPage({
1906
+ threadId: params.threadId,
1907
+ limit: params.limit,
1908
+ sortDirection: "desc",
1909
+ itemsView: "full",
1910
+ ...params.cursor ? { cursor: params.cursor } : {}
1911
+ }));
1912
+ return {
1913
+ hostId: params.hostId,
1914
+ label: "Local Codex",
1915
+ threadId: params.threadId,
1916
+ items: flattenTranscriptPageDesc(page),
1917
+ ...page.nextCursor ? { nextCursor: page.nextCursor } : {},
1918
+ ...page.backwardsCursor ? { backwardsCursor: page.backwardsCursor } : {}
1919
+ };
1920
+ }
1921
+ const nodeId = params.hostId.slice(5);
1922
+ const node = (await params.runtime.nodes.list()).nodes.find((candidate) => candidate.nodeId === nodeId && candidate.connected === true && candidate.commands?.includes("codex.appServer.thread.turns.list.v1"));
1923
+ if (!node) throw new CatalogParamsError("paired-node Codex session host is offline or unavailable");
1924
+ const page = parseTranscriptPage(unwrapNodeInvokePayload(await params.runtime.nodes.invoke({
1925
+ nodeId,
1926
+ command: CODEX_APP_SERVER_THREAD_TURNS_LIST_COMMAND,
1927
+ params: {
1928
+ threadId: params.threadId,
1929
+ limit: params.limit,
1930
+ ...params.cursor ? { cursor: params.cursor } : {}
1931
+ },
1932
+ timeoutMs: NODE_INVOKE_TIMEOUT_MS,
1933
+ scopes: ["operator.write"]
1934
+ })));
1935
+ return {
1936
+ hostId: params.hostId,
1937
+ label: nodeLabel(node),
1938
+ threadId: params.threadId,
1939
+ items: flattenTranscriptPageDesc(page),
1940
+ ...page.nextCursor ? { nextCursor: page.nextCursor } : {},
1941
+ ...page.backwardsCursor ? { backwardsCursor: page.backwardsCursor } : {}
1942
+ };
1943
+ }
1944
+ function requireIdleThread(thread, action) {
1945
+ if (thread.status?.type === "idle" || action === "archive" && thread.status?.type === "notLoaded") return;
1946
+ if (thread.status?.type === "active") throw new CatalogParamsError(`Codex session is active in this App Server; wait for it to finish before ${action === "continue" ? "starting a branch" : "archiving"}`);
1947
+ throw new CatalogParamsError(action === "archive" ? "Codex session cannot be archived in its current state" : "Codex session cannot start a branch in its current state");
1948
+ }
1949
+ function adoptionSessionKey(threadId) {
1950
+ const digest = createHash("sha256").update(threadId).digest("hex");
1951
+ return `${CODEX_SUPERVISION_SESSION_KEY_PREFIX}${digest}`;
1952
+ }
1953
+ function isAdoptionSessionKeyForThread(sessionKey, threadId) {
1954
+ return adoptionSessionKeyRest(sessionKey) === adoptionSessionKey(threadId);
1955
+ }
1956
+ async function listAdoptedSessionEntries(params) {
1957
+ const adopted = /* @__PURE__ */ new Map();
1958
+ for (const agentId of listSupervisionAgentIds(params.config ?? {})) for (const { entry, sessionKey } of params.runtime.agent.session.listSessionEntries({ agentId })) {
1959
+ const sessionKeyRest = adoptionSessionKeyRest(sessionKey);
1960
+ if (!sessionKeyRest.startsWith(CODEX_SUPERVISION_SESSION_KEY_PREFIX) || entry.initializationPending === true || entry.agentHarnessId !== "codex" || entry.modelSelectionLocked !== true) continue;
1961
+ const sessionId = entry.sessionId?.trim();
1962
+ if (!sessionId) continue;
1963
+ const binding = await params.bindingStore.read(sessionBindingIdentity({
1964
+ sessionId,
1965
+ sessionKey,
1966
+ config: params.config
1967
+ }));
1968
+ const sourceThreadId = binding?.supervisionSourceThreadId?.trim();
1969
+ const boundThreadId = binding?.threadId.trim();
1970
+ if (binding?.connectionScope !== "supervision" || !sourceThreadId || !boundThreadId || sessionKeyRest !== adoptionSessionKey(sourceThreadId)) continue;
1971
+ if (adopted.has(sourceThreadId)) throw new Error(`multiple OpenClaw sessions adopt Codex thread ${sourceThreadId}`);
1972
+ adopted.set(sourceThreadId, {
1973
+ key: sessionKey,
1974
+ sessionId,
1975
+ agentId,
1976
+ boundThreadId
1977
+ });
1978
+ }
1979
+ return adopted;
1980
+ }
1981
+ async function findAdoptedSessionEntry(params) {
1982
+ return (await listAdoptedSessionEntries(params)).get(params.threadId);
1983
+ }
1984
+ var CodexAdoptionBindingCleanupError = class extends AggregateError {};
1985
+ async function clearCreatedAdoptionBinding(params) {
1986
+ let cleared = false;
1987
+ let clearError;
1988
+ try {
1989
+ cleared = await params.bindingStore.mutate(params.identity, {
1990
+ kind: "clear",
1991
+ threadId: params.sourceThreadId,
1992
+ expectedPendingSupervisionBranch: params.expectedPending
1993
+ });
1994
+ } catch (error) {
1995
+ clearError = error;
1996
+ }
1997
+ if (cleared) return;
1998
+ let current;
1999
+ try {
2000
+ current = await params.bindingStore.read(params.identity);
2001
+ } catch (readError) {
2002
+ throw new CodexAdoptionBindingCleanupError([
2003
+ params.cause,
2004
+ ...clearError ? [clearError] : [],
2005
+ readError
2006
+ ], `OpenClaw session creation failed and the Codex binding could not be verified for ${params.sourceThreadId}`);
2007
+ }
2008
+ if (!matchesPendingSupervisionOwner(current, params.expectedPending)) return;
2009
+ throw new CodexAdoptionBindingCleanupError([params.cause, ...clearError ? [clearError] : []], `OpenClaw session creation failed and the Codex binding could not be cleared for ${params.sourceThreadId}`);
2010
+ }
2011
+ function matchesPendingAdoptionBinding(binding, expected) {
2012
+ const historyCoveredThrough = binding?.historyCoveredThrough;
2013
+ return binding?.threadId === expected.sourceThreadId && binding.connectionScope === "supervision" && binding.supervisionSourceThreadId === expected.sourceThreadId && binding.cwd === expected.cwd && binding.conversationSourceTransferComplete === true && binding.preserveNativeModel === true && binding.pendingSupervisionBranch?.sourceThreadId === expected.sourceThreadId && binding.pendingSupervisionBranch.connectionFingerprint === expected.connectionFingerprint && binding.pendingSupervisionBranch.lastTurnId === expected.lastTurnId && (binding.pendingSupervisionBranch.cleanupThreadIds?.length ?? 0) === 0 && typeof historyCoveredThrough === "string" && Number.isFinite(Date.parse(historyCoveredThrough));
2014
+ }
2015
+ function matchesPendingSupervisionOwner(binding, expected) {
2016
+ const pending = binding?.pendingSupervisionBranch;
2017
+ const cleanupThreadIds = pending?.cleanupThreadIds ?? [];
2018
+ const expectedCleanupThreadIds = expected.cleanupThreadIds ?? [];
2019
+ return binding?.threadId === expected.sourceThreadId && binding.connectionScope === "supervision" && binding.supervisionSourceThreadId === expected.sourceThreadId && pending?.sourceThreadId === expected.sourceThreadId && pending.connectionFingerprint === expected.connectionFingerprint && pending.lastTurnId === expected.lastTurnId && cleanupThreadIds.length === expectedCleanupThreadIds.length && cleanupThreadIds.every((threadId, index) => threadId === expectedCleanupThreadIds[index]);
2020
+ }
2021
+ async function ensurePendingAdoptionBinding(params) {
2022
+ const pending = {
2023
+ sourceThreadId: params.sourceThreadId,
2024
+ connectionFingerprint: params.connectionFingerprint,
2025
+ ...params.lastTurnId ? { lastTurnId: params.lastTurnId } : {}
2026
+ };
2027
+ if (!await reclaimCurrentCodexSessionGeneration({
2028
+ bindingStore: params.bindingStore,
2029
+ identity: params.identity,
2030
+ config: params.config
2031
+ })) throw new Error(`failed to claim the OpenClaw session generation for ${params.sourceThreadId}`);
2032
+ const existing = await params.bindingStore.read(params.identity);
2033
+ if (existing) {
2034
+ if (matchesPendingAdoptionBinding(existing, params)) return;
2035
+ throw new Error(`OpenClaw session is already bound to Codex thread ${existing.threadId}`);
2036
+ }
2037
+ const binding = {
2038
+ threadId: params.sourceThreadId,
2039
+ connectionScope: "supervision",
2040
+ supervisionSourceThreadId: params.sourceThreadId,
2041
+ cwd: params.cwd,
2042
+ historyCoveredThrough: (/* @__PURE__ */ new Date()).toISOString(),
2043
+ conversationSourceTransferComplete: true,
2044
+ preserveNativeModel: true,
2045
+ pendingSupervisionBranch: pending
2046
+ };
2047
+ let stored;
2048
+ try {
2049
+ stored = await params.bindingStore.mutate(params.identity, {
2050
+ kind: "set",
2051
+ if: { kind: "absent" },
2052
+ binding
2053
+ });
2054
+ } catch (error) {
2055
+ if (matchesPendingAdoptionBinding(await params.bindingStore.read(params.identity), params)) return;
2056
+ throw error;
2057
+ }
2058
+ if (stored) return;
2059
+ if (!matchesPendingAdoptionBinding(await params.bindingStore.read(params.identity), params)) throw new Error(`failed to bind OpenClaw session to Codex thread ${params.sourceThreadId}`);
2060
+ }
2061
+ async function createOrReuseAdoptedSession(params) {
2062
+ const existing = await findAdoptedSessionEntry({
2063
+ bindingStore: params.bindingStore,
2064
+ config: params.config,
2065
+ runtime: params.api.runtime,
2066
+ threadId: params.sourceThread.id
2067
+ });
2068
+ if (existing) return existing;
2069
+ let createdBindingIdentity;
2070
+ let createdPendingBinding;
2071
+ try {
2072
+ const label = params.sourceThread.name?.trim() || void 0;
2073
+ const spawnedCwd = params.sourceThread.cwd?.trim() || void 0;
2074
+ const pendingLastTurnId = codexLastTerminalTurnId(params.sourceThread, boundCatalogSessionId);
2075
+ const marker = { sourceThreadId: params.sourceThread.id };
2076
+ const created = await params.api.runtime.agent.session.createSessionEntry({
2077
+ cfg: params.config,
2078
+ key: adoptionSessionKey(params.sourceThread.id),
2079
+ agentId: resolveDefaultAgentId(params.config),
2080
+ recoverMatchingInitialEntry: true,
2081
+ ...label ? { label } : {},
2082
+ ...spawnedCwd ? { spawnedCwd } : {},
2083
+ initialEntry: {
2084
+ agentHarnessId: "codex",
2085
+ modelSelectionLocked: true,
2086
+ pluginExtensions: { codex: { supervision: {
2087
+ ...marker,
2088
+ initializing: true,
2089
+ modelLocked: true
2090
+ } } }
2091
+ },
2092
+ afterCreate: async (entry) => {
2093
+ createdBindingIdentity = sessionBindingIdentity({
2094
+ sessionId: entry.sessionId,
2095
+ sessionKey: entry.key,
2096
+ config: params.config
2097
+ });
2098
+ const storePath = resolveStorePath(params.config.session?.store, { agentId: entry.agentId });
2099
+ await importCodexThreadHistoryToTranscript({
2100
+ thread: params.sourceThread,
2101
+ throughTurnId: pendingLastTurnId ?? null,
2102
+ storePath,
2103
+ sessionId: entry.sessionId,
2104
+ sessionKey: entry.key,
2105
+ agentId: entry.agentId,
2106
+ ...spawnedCwd ? { cwd: spawnedCwd } : {},
2107
+ modelProvider: params.sourceThread.modelProvider,
2108
+ config: params.config
2109
+ });
2110
+ createdPendingBinding = {
2111
+ sourceThreadId: params.sourceThread.id,
2112
+ connectionFingerprint: params.connectionFingerprint,
2113
+ ...pendingLastTurnId ? { lastTurnId: pendingLastTurnId } : {}
2114
+ };
2115
+ await ensurePendingAdoptionBinding({
2116
+ bindingStore: params.bindingStore,
2117
+ config: params.config,
2118
+ identity: createdBindingIdentity,
2119
+ sourceThreadId: params.sourceThread.id,
2120
+ connectionFingerprint: params.connectionFingerprint,
2121
+ cwd: spawnedCwd ?? "",
2122
+ ...pendingLastTurnId ? { lastTurnId: pendingLastTurnId } : {}
2123
+ });
2124
+ return { pluginExtensions: { codex: { supervision: {
2125
+ ...marker,
2126
+ modelLocked: true
2127
+ } } } };
2128
+ }
2129
+ });
2130
+ return {
2131
+ key: created.key,
2132
+ sessionId: created.sessionId,
2133
+ agentId: created.agentId,
2134
+ boundThreadId: params.sourceThread.id
2135
+ };
2136
+ } catch (error) {
2137
+ let raced = await findAdoptedSessionEntry({
2138
+ bindingStore: params.bindingStore,
2139
+ config: params.config,
2140
+ runtime: params.api.runtime,
2141
+ threadId: params.sourceThread.id
2142
+ });
2143
+ if (raced) return raced;
2144
+ if (createdBindingIdentity && createdPendingBinding) {
2145
+ await clearCreatedAdoptionBinding({
2146
+ bindingStore: params.bindingStore,
2147
+ identity: createdBindingIdentity,
2148
+ sourceThreadId: params.sourceThread.id,
2149
+ expectedPending: createdPendingBinding,
2150
+ cause: error
2151
+ });
2152
+ raced = await findAdoptedSessionEntry({
2153
+ bindingStore: params.bindingStore,
2154
+ config: params.config,
2155
+ runtime: params.api.runtime,
2156
+ threadId: params.sourceThread.id
2157
+ });
2158
+ if (raced) return raced;
2159
+ }
2160
+ throw error;
2161
+ }
2162
+ }
2163
+ async function continueLocalCodexSessionInner(params) {
2164
+ await requireCatalogEligibleThread(params.control, params.threadId);
2165
+ const existing = await findAdoptedSessionEntry({
2166
+ bindingStore: params.bindingStore,
2167
+ config: params.config,
2168
+ runtime: params.api.runtime,
2169
+ threadId: params.threadId
2170
+ });
2171
+ if (existing) {
2172
+ const boundThreadId = requireBoundThread(existing);
2173
+ const boundThread = await params.control.readThread(boundThreadId, true);
2174
+ if (boundThread.id !== boundThreadId) throw new Error("Codex app-server returned a different thread than requested");
2175
+ const changedError = () => new CatalogParamsError("Codex OpenClaw session changed before it could be opened. Retry.");
2176
+ if (!await params.api.runtime.agent.session.patchSessionEntry({
2177
+ sessionKey: existing.key,
2178
+ readConsistency: "latest",
2179
+ preserveActivity: true,
2180
+ update: (entry) => {
2181
+ if (entry.sessionId?.trim() !== existing.sessionId || entry.initializationPending === true || entry.agentHarnessId !== "codex" || entry.modelSelectionLocked !== true) throw changedError();
2182
+ return { archivedAt: void 0 };
2183
+ }
2184
+ })) throw changedError();
2185
+ const connectionFingerprint = params.control.connectionFingerprint;
2186
+ if (connectionFingerprint) params.onContinued?.({
2187
+ connectionFingerprint,
2188
+ ...codexUpstreamBaseline(boundThread, boundCatalogSessionId)
2189
+ });
2190
+ return {
2191
+ sessionKey: existing.key,
2192
+ disposition: "existing"
2193
+ };
2194
+ }
2195
+ const sourceThread = await params.control.readThread(params.threadId, true);
2196
+ if (sourceThread.id !== params.threadId) throw new Error("Codex app-server returned a different thread than requested");
2197
+ if (sourceThread.status?.type !== "notLoaded") requireIdleThread(sourceThread, "continue");
2198
+ const connectionFingerprint = params.control.connectionFingerprint;
2199
+ if (!connectionFingerprint) throw new Error("Codex Continue requires a pinned app-server connection");
2200
+ const adopted = await createOrReuseAdoptedSession({
2201
+ api: params.api,
2202
+ bindingStore: params.bindingStore,
2203
+ config: params.config,
2204
+ sourceThread,
2205
+ connectionFingerprint
2206
+ });
2207
+ const boundThreadId = requireBoundThread(adopted);
2208
+ const baselineThread = boundThreadId === sourceThread.id ? sourceThread : await params.control.readThread(boundThreadId, true);
2209
+ if (baselineThread.id !== boundThreadId) throw new Error("Codex app-server returned a different thread than requested");
2210
+ params.onContinued?.({
2211
+ connectionFingerprint,
2212
+ ...codexUpstreamBaseline(baselineThread, boundCatalogSessionId)
2213
+ });
2214
+ return {
2215
+ sessionKey: adopted.key,
2216
+ disposition: "forked"
2217
+ };
2218
+ }
2219
+ /** Creates one locked OpenClaw branch whose first harness run forks the Codex source. */
2220
+ async function continueLocalCodexSession(params) {
2221
+ const sourceKey = adoptedSourceKey(CODEX_LOCAL_SESSION_HOST_ID, params.threadId);
2222
+ const current = continueOperations.get(sourceKey);
2223
+ if (current) return await current;
2224
+ const operation = runSessionActionExclusive(sourceKey, async () => params.control.withPinnedConnection(async (control) => continueLocalCodexSessionInner({
2225
+ ...params,
2226
+ control
2227
+ })));
2228
+ continueOperations.set(sourceKey, operation);
2229
+ try {
2230
+ return await operation;
2231
+ } finally {
2232
+ if (continueOperations.get(sourceKey) === operation) continueOperations.delete(sourceKey);
2233
+ }
2234
+ }
2235
+ async function assertNoPendingSupervisionBranch(params) {
2236
+ const adoptedEntries = listSupervisionAgentIds(params.config).flatMap((agentId) => params.runtime.agent.session.listSessionEntries({ agentId })).filter((candidate) => isAdoptionSessionKeyForThread(candidate.sessionKey, params.threadId));
2237
+ for (const adopted of adoptedEntries) {
2238
+ if (adopted.entry.initializationPending === true) throw new CatalogParamsError("Codex session cannot be archived while its OpenClaw branch is initializing");
2239
+ const sessionId = adopted.entry.sessionId?.trim();
2240
+ if (!sessionId) continue;
2241
+ const binding = await params.bindingStore.read(sessionBindingIdentity({
2242
+ sessionId,
2243
+ sessionKey: adopted.sessionKey,
2244
+ config: params.config
2245
+ }));
2246
+ if (binding?.connectionScope === "supervision" && binding.supervisionSourceThreadId === params.threadId && binding.pendingSupervisionBranch?.sourceThreadId === params.threadId) throw new CatalogParamsError("Codex session cannot be archived until its OpenClaw branch starts");
2247
+ }
2248
+ }
2249
+ /** Archives one inactive Gateway-local Codex thread after a fresh status read. */
2250
+ async function archiveLocalCodexSession(params) {
2251
+ return await runSessionActionExclusive(adoptedSourceKey(CODEX_LOCAL_SESSION_HOST_ID, params.threadId), async () => {
2252
+ return await params.bindingStore.withThreadArchiveFence(async () => {
2253
+ return await params.control.withPinnedConnection(async (control) => {
2254
+ await requireCatalogEligibleThread(control, params.threadId);
2255
+ await assertNoPendingSupervisionBranch(params);
2256
+ const thread = await control.readThread(params.threadId, false);
2257
+ if (thread.id !== params.threadId) throw new Error("Codex app-server returned a different thread than requested");
2258
+ requireIdleThread(thread, "archive");
2259
+ if (await params.bindingStore.hasOtherThreadOwner(params.threadId)) throw new CatalogParamsError("Codex session cannot be archived while it is attached to an OpenClaw session");
2260
+ await assertCodexArchiveDescendantsUnowned({
2261
+ bindingStore: params.bindingStore,
2262
+ threadId: params.threadId,
2263
+ listPage: (request) => control.listDescendantPage(request),
2264
+ assertDescendantIdle: async (descendantThreadId) => {
2265
+ const descendant = await control.readThread(descendantThreadId, false);
2266
+ if (descendant.id !== descendantThreadId) throw new Error("Codex app-server returned a different descendant than requested");
2267
+ requireIdleThread(descendant, "archive");
2268
+ }
2269
+ });
2270
+ await control.archiveThread(params.threadId);
2271
+ return { archived: true };
2272
+ });
2273
+ });
2274
+ });
2275
+ }
2276
+ /** Allows read-only catalog and transcript commands on supported paired-node platforms. */
2277
+ function createCodexSessionCatalogNodeInvokePolicies() {
2278
+ return [{
2279
+ commands: [
2280
+ CODEX_APP_SERVER_THREADS_LIST_COMMAND,
2281
+ CODEX_APP_SERVER_THREAD_TURNS_LIST_COMMAND,
2282
+ CODEX_TERMINAL_RESUME_COMMAND
2283
+ ],
2284
+ defaultPlatforms: [
2285
+ "macos",
2286
+ "linux",
2287
+ "windows"
2288
+ ],
2289
+ handle: (context) => context.command === "codex.terminal.resume.v1" ? { ok: true } : context.invokeNode()
2290
+ }];
2291
+ }
2292
+ function toGenericCatalogHost(host, localTerminalAvailable) {
2293
+ const local = host.hostId === CODEX_LOCAL_SESSION_HOST_ID;
2294
+ return {
2295
+ hostId: host.hostId,
2296
+ label: host.label,
2297
+ kind: host.kind,
2298
+ connected: host.connected,
2299
+ ...host.nodeId ? { nodeId: host.nodeId } : {},
2300
+ sessions: host.sessions.map((session) => {
2301
+ const continuableStatus = !session.archived && (session.status === "idle" || session.status === "notLoaded");
2302
+ const canContinue = (local || host.canContinueCodex === true) && continuableStatus && isInteractiveThreadSource(session.source);
2303
+ const canArchive = local && continuableStatus && isInteractiveThreadSource(session.source);
2304
+ const canOpenTerminal = isInteractiveThreadSource(session.source) && (local ? localTerminalAvailable : host.canOpenTerminalCodex === true);
2305
+ return {
2306
+ threadId: session.threadId,
2307
+ ...session.name != null ? { name: session.name } : {},
2308
+ ...session.cwd ? { cwd: session.cwd } : {},
2309
+ status: session.status,
2310
+ ...session.createdAt != null ? { createdAt: session.createdAt } : {},
2311
+ ...session.updatedAt != null ? { updatedAt: session.updatedAt } : {},
2312
+ ...session.recencyAt != null ? { recencyAt: session.recencyAt } : {},
2313
+ ...session.source ? { source: session.source } : {},
2314
+ ...session.modelProvider ? { modelProvider: session.modelProvider } : {},
2315
+ ...session.cliVersion ? { cliVersion: session.cliVersion } : {},
2316
+ ...session.gitBranch ? { gitBranch: session.gitBranch } : {},
2317
+ archived: session.archived,
2318
+ ...session.openClawSessionKey ? { openClawSessionKey: session.openClawSessionKey } : {},
2319
+ canContinue,
2320
+ canArchive,
2321
+ canOpenTerminal
2322
+ };
2323
+ }),
2324
+ ...host.nextCursor ? { nextCursor: host.nextCursor } : {},
2325
+ ...host.error ? { error: host.error } : {}
2326
+ };
2327
+ }
2328
+ function registerCodexSessionCatalog(params) {
2329
+ const provider = {
2330
+ id: "codex",
2331
+ label: "Codex",
2332
+ list: async (query) => {
2333
+ const localTerminalAvailable = resolveLocalCodexTerminalExecutable() !== void 0;
2334
+ return (await listCodexSessionCatalog({
2335
+ bindingStore: params.bindingStore,
2336
+ config: params.getRuntimeConfig(),
2337
+ runtime: params.api.runtime,
2338
+ control: params.control,
2339
+ query
2340
+ })).hosts.map((host) => toGenericCatalogHost(host, localTerminalAvailable));
2341
+ },
2342
+ read: async (request) => {
2343
+ const page = await readCodexSessionTranscript({
2344
+ runtime: params.api.runtime,
2345
+ control: params.control,
2346
+ hostId: request.hostId,
2347
+ threadId: request.threadId,
2348
+ cursor: request.cursor,
2349
+ limit: request.limit ?? 20
2350
+ });
2351
+ return {
2352
+ ...page,
2353
+ items: page.items.map(toGenericTranscriptItem)
2354
+ };
2355
+ },
2356
+ continueSession: async (request) => {
2357
+ const config = params.getRuntimeConfig();
2358
+ if (!config) throw new Error("OpenClaw runtime config is unavailable");
2359
+ if (request.hostId.startsWith("node:")) return await continueNodeCodexSession({
2360
+ api: params.api,
2361
+ config,
2362
+ hostId: request.hostId,
2363
+ threadId: request.threadId,
2364
+ clientScopes: request.clientScopes
2365
+ });
2366
+ if (request.hostId !== "gateway:local") throw new CatalogParamsError("Codex session catalog hostId is invalid");
2367
+ let upstreamBaseline;
2368
+ return codexUpstreamContinueResult((await continueLocalCodexSession({
2369
+ api: params.api,
2370
+ bindingStore: params.bindingStore,
2371
+ config,
2372
+ control: params.control,
2373
+ threadId: request.threadId,
2374
+ onContinued: (baseline) => {
2375
+ upstreamBaseline = baseline;
2376
+ }
2377
+ })).sessionKey, request.threadId, upstreamBaseline);
2378
+ },
2379
+ checkUpstreamActivity: createChecker(params),
2380
+ archive: async (request) => {
2381
+ if (request.confirmNoOtherRunner !== true) throw new CatalogParamsError("archive requires confirmation that no other runner is active");
2382
+ if (request.hostId !== "gateway:local") throw new CatalogParamsError("paired-node Codex sessions are view-only");
2383
+ const config = params.getRuntimeConfig();
2384
+ if (!config) throw new Error("OpenClaw runtime config is unavailable");
2385
+ await archiveLocalCodexSession({
2386
+ bindingStore: params.bindingStore,
2387
+ config,
2388
+ control: params.control,
2389
+ runtime: params.api.runtime,
2390
+ threadId: request.threadId
2391
+ });
2392
+ return { ok: true };
2393
+ },
2394
+ openTerminal: (request) => openCodexCatalogTerminal({
2395
+ api: params.api,
2396
+ control: params.control,
2397
+ parseCatalogPage,
2398
+ ...request
2399
+ })
2400
+ };
2401
+ params.api.registerSessionCatalog(provider);
2402
+ }
2403
+ const codexSessionCatalogRuntime = {
2404
+ register: registerCodexSessionCatalog,
2405
+ list: listCodexSessionCatalog,
2406
+ readTranscript: readCodexSessionTranscript,
2407
+ continueLocal: continueLocalCodexSession,
2408
+ continueNode: continueNodeCodexSession,
2409
+ archiveLocal: archiveLocalCodexSession
2410
+ };
2411
+ //#endregion
2412
+ export { CODEX_LOCAL_SESSION_HOST_ID as a, requestOptions as c, createCodexCliSessionNodeHostCommands as d, createCodexCliSessionNodeInvokePolicies as f, resumeCodexCliSessionOnNode as g, resolveCodexCliSessionForBindingOnNode as h, createCodexSessionCatalogNodeInvokePolicies as i, safeCodexControlRequest as l, listCodexCliSessionsOnNode as m, createCodexSessionCatalogControl as n, codexControlRequest as o, formatCodexCliSessions as p, createCodexSessionCatalogNodeHostCommands as r, readCodexStatusProbes as s, codexSessionCatalogRuntime as t, assertCodexArchiveDescendantsUnowned as u };