@openclaw/codex 2026.9.1 → 2026.9.3

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 (109) hide show
  1. package/README.md +2 -0
  2. package/dist/api.js +18 -23
  3. package/dist/apply-B6el6hdO.js +357 -0
  4. package/dist/{attempt-client-cleanup-DYHcRQAa.js → attempt-client-cleanup-D6cR54TV.js} +113 -49
  5. package/dist/{attempt-context-DmQUNWwT.js → attempt-context-AO4DSjE0.js} +11 -9
  6. package/dist/{event-projector-usage-C5mcrGjp.js → attempt-notifications--H8zXR5-.js} +3 -89
  7. package/dist/auth-cache-key-Kq6oerr6.js +498 -0
  8. package/dist/auth-profile-CwzO4_RG.js +43 -0
  9. package/dist/auth-profile-selection-DFu9e167.js +45 -0
  10. package/dist/{binding-connection-E6uDsPlx.js → binding-connection-QqgcPCgk.js} +18 -3
  11. package/dist/{bounded-turn-wzJrwKKe.js → bounded-turn-lRpmZHFv.js} +54 -150
  12. package/dist/build-state-6RL6qohz.js +19 -0
  13. package/dist/{capabilities-dIjNVCYH.js → capabilities-BeqLPbtM.js} +2 -1
  14. package/dist/cli-metadata.js +1 -1
  15. package/dist/client-BEKu4yDx.js +3983 -0
  16. package/dist/command-dispatch-CisT9Jqq.js +21 -0
  17. package/dist/{command-formatters-CLHhEB1Q.js → command-formatters-DeTfrapr.js} +2 -2
  18. package/dist/{command-handlers-CTGb2csu.js → command-handlers-BfIsJEuA.js} +158 -76
  19. package/dist/command-rpc-BMqRQOFX.js +226 -0
  20. package/dist/{compact-_t0HQrUS.js → compact-CGJZ2rlb.js} +89 -49
  21. package/dist/config-JDfTI4VI.js +106 -0
  22. package/dist/{config-BhmfC1s6.js → config-options-jnIFvwxD.js} +208 -654
  23. package/dist/config-runtime-BWf6JLWG.js +11 -0
  24. package/dist/config-utils-C57JiJrU.js +69 -0
  25. package/dist/conversation-binding-CxOlHiix.js +889 -0
  26. package/dist/{plugin-marketplace-discovery-CfFlKqDl.js → conversation-control-CUCrSIQI.js} +36 -155
  27. package/dist/doctor-contract-api.js +8 -9
  28. package/dist/{dynamic-tools-BU9tmlYm.js → dynamic-tools-D-JBoaLt.js} +734 -698
  29. package/dist/{effective-mcp-catalog-DzYBW4h1.js → effective-mcp-catalog-J_5Ep5Um.js} +4 -3
  30. package/dist/{elicitation-input-DMkeki8d.js → elicitation-input-DPoK8F7w.js} +8 -22
  31. package/dist/ephemeral-turn-DSwzP8YY.js +101 -0
  32. package/dist/{event-projector-assistant-message-DHRFXKbS.js → event-projector-assistant-message-BmBM4qBV.js} +23 -27
  33. package/dist/event-projector-usage-CIyrYYid.js +102 -0
  34. package/dist/{harness-DXVZ5II5.js → harness-FR6eQgyO.js} +47 -17
  35. package/dist/harness.js +1 -1
  36. package/dist/history-rejection-B4nOXNXF.js +13 -0
  37. package/dist/{image-payload-sanitizer-CnfoUPCE.js → image-payload-sanitizer-tupAr-2o.js} +29 -15
  38. package/dist/incognito-session-uhrBF6wJ.js +15 -0
  39. package/dist/index.js +413 -2893
  40. package/dist/{isolated-completion-kg9kv4iH.js → isolated-completion-DHBefrzg.js} +12 -21
  41. package/dist/{managed-binary-4-Vjz5GH.js → managed-binary-DrjjRRUD.js} +17 -84
  42. package/dist/managed-thread-store-D1t5jh3G.js +66 -0
  43. package/dist/media-understanding-provider.js +4 -1
  44. package/dist/{model-catalog-CUM68Hkl.js → model-catalog-B_6M04Wo.js} +6 -5
  45. package/dist/{models-sYnEc0gd.js → models-P9k2qAof.js} +4 -4
  46. package/dist/native-execution-policy-umd0tgh4.js +128 -0
  47. package/dist/{native-subagent-monitor-CnH147jH.js → native-subagent-monitor-BbCUKRwC.js} +76 -48
  48. package/dist/node-cli-sessions-rj0ysJwM.js +527 -0
  49. package/dist/{node-exec-server.runtime-CstNHCmC.js → node-exec-server.runtime-BY_ctYnT.js} +54 -23
  50. package/dist/plan-BMJdMOEF.js +711 -0
  51. package/dist/plugin-activation-BQK-f5sV.js +133 -0
  52. package/dist/{thread-resume-C7pyVKeW.js → plugin-app-cache-key-CdSQzWyX.js} +5 -53
  53. package/dist/{plugin-approval-roundtrip-CNe-Xrjx.js → plugin-approval-roundtrip-DeW95wB5.js} +1 -1
  54. package/dist/plugin-inventory-CoRCzWW4.js +325 -0
  55. package/dist/plugin-marketplace-discovery-3akBizzF.js +134 -0
  56. package/dist/{plugin-metadata-cache-BFrPhb2c.js → plugin-metadata-cache-DgNfRAGA.js} +13 -9
  57. package/dist/protocol-CAAcVIKF.js +275 -0
  58. package/dist/{provider-capabilities-DW5p4k9w.js → provider-capabilities-W4tfK5Y5.js} +2 -2
  59. package/dist/{rate-limits-CawQJfUS.js → rate-limits-Bqnx1N4z.js} +1 -1
  60. package/dist/request-CGvGOpeR.js +198 -0
  61. package/dist/{run-attempt-D1hJO4fX.js → run-attempt-DwKds3DN.js} +1498 -1028
  62. package/dist/{runtime-artifact-C3jVimFn.js → runtime-artifact-T-NwqeSH.js} +28 -28
  63. package/dist/sandbox-guard-BcT66fWy.js +165 -0
  64. package/dist/{session-binding-BHuTCRZQ.js → session-binding-CKSepwIC.js} +118 -324
  65. package/dist/session-binding-record-CaZjYwNS.js +256 -0
  66. package/dist/session-catalog-HaDcp7Sv.js +1533 -0
  67. package/dist/session-catalog-adoption-BKLtSrwi.js +251 -0
  68. package/dist/session-catalog-archive-D0i2pGj2.js +56 -0
  69. package/dist/session-catalog-home-id-D7-aLiNt.js +190 -0
  70. package/dist/session-catalog-node-adoption-BUuDYY8R.js +182 -0
  71. package/dist/session-catalog-node-continue-CBtc4wkI.js +238 -0
  72. package/dist/session-catalog-parsing-CdD3JhdM.js +280 -0
  73. package/dist/session-catalog-provenance-DkJHo735.js +124 -0
  74. package/dist/{session-cli-CmFEXMAM.js → session-cli-CbgaHh0f.js} +3 -2
  75. package/dist/session-history-Cz-tOOYj.js +96 -0
  76. package/dist/{session-upstream-marker-C351-5Qw.js → session-history-import-DFN7sWRU.js} +5 -49
  77. package/dist/session-history-read-cxPUxyVV.js +50 -0
  78. package/dist/session-history-worker-runtime.js +60 -0
  79. package/dist/{settled-turn-context-D3SNWtUn.js → session-history.worker-CNEvGaU5.js} +75 -69
  80. package/dist/session-history.worker.js +2 -0
  81. package/dist/{session-initialization-BeWzjGiR.js → session-initialization-Jo86C60I.js} +2 -1
  82. package/dist/{session-permission-policy-DeWVTCMj.js → session-permission-policy-B22InTp_.js} +4 -7
  83. package/dist/{session-retirement-BujDjXVF.js → session-retirement-BSNG_mhf.js} +8 -7
  84. package/dist/session-upstream-marker-D15C9NHp.js +46 -0
  85. package/dist/settled-turn-context-Du6gdUDd.js +45 -0
  86. package/dist/{settled-turn-finalizer-BVJx4yoc.js → settled-turn-finalizer-BuLUrZl2.js} +54 -42
  87. package/dist/shared-client-CVhez2Uo.js +2911 -0
  88. package/dist/{side-question-BTZAII4l.js → side-question-DLbr2vUU.js} +135 -191
  89. package/dist/source-Da-h6f7e.js +518 -0
  90. package/dist/thread-archive-guard-D1bP04Tf.js +53 -0
  91. package/dist/{thread-lifecycle-DAcEJ_Om.js → thread-lifecycle-D1pzRwHB.js} +467 -977
  92. package/dist/{thread-ownership-zGokd8i1.js → thread-ownership-D6oASVRu.js} +15 -17
  93. package/dist/{thread-policy-g4KbJPzp.js → thread-policy-D8kI7yAO.js} +2 -2
  94. package/dist/thread-resume-T5cveyxA.js +52 -0
  95. package/dist/timeout-BVw8aaM1.js +33 -0
  96. package/dist/transcript-mirror-attestation-DibE0krH.js +89 -0
  97. package/dist/{transcript-mirror-DTUxFWa_.js → transcript-mirror-t5TOccct.js} +111 -379
  98. package/dist/{transport-stdio-CyPldczm.js → transport-stdio-BGjHoYLr.js} +80 -48
  99. package/dist/{upstream-session-fork-CYlBIGVt.js → upstream-session-fork-De-sLJ2r.js} +94 -166
  100. package/dist/{usage-Bj-rrzkR.js → usage-CPPTmBvZ.js} +4 -3
  101. package/dist/version-omm6IPI3.js +12 -0
  102. package/dist/{web-search-provider.runtime-D2FWSK4w.js → web-search-provider.runtime-CSVgQL0w.js} +3 -3
  103. package/openclaw.plugin.json +22 -1
  104. package/package.json +6 -6
  105. package/dist/request-DYAI5FQE.js +0 -475
  106. package/dist/session-catalog-yyvTWFOw.js +0 -3120
  107. package/dist/session-history-C5J1AKzG.js +0 -87
  108. package/dist/shared-client-DxcfF9KX.js +0 -7494
  109. package/dist/{auth-binding-Ds_QVm-X.js → auth-binding-Co2Vfcf_.js} +1 -1
@@ -1,3120 +0,0 @@
1
- import { $t as isJsonObject, Jt as readCodexSessionMeta, K as resolveCodexAppServerClientInstanceId, Nt as withTimeout, Vt as resolveCodexAppServerAuthProfileStore, Wt as resolveCodexAppServerPreparedAuthHandoff, Xt as CODEX_INTERACTIVE_THREAD_SOURCE_KINDS, Yt as CODEX_INTERACTIVE_CUSTOM_THREAD_SOURCES, Z as assertCodexThreadForkParams, c as getLeasedSharedCodexAppServerClient, h as releaseLeasedSharedCodexAppServerClient, q as CodexAppServerRpcError, qt as isOpenClawManagedCodexThread, y as retireSharedCodexAppServerClientIfCurrent, zt as resolveCodexAppServerAuthProfileId } from "./shared-client-DxcfF9KX.js";
2
- import { E as readCodexPluginConfig, F as resolveCodexAppServerHomeDir, I as resolveCodexAppServerLocalHomeDir, L as resolveCodexAppServerUserHomeDir, i as resolveCodexAppServerRuntimeOptions, s as resolveCodexSupervisionAppServerRuntimeOptions } from "./config-BhmfC1s6.js";
3
- import { c as reclaimCurrentCodexSessionGeneration, d as sessionBindingIdentity } from "./session-binding-BHuTCRZQ.js";
4
- import { a as closeCodexStartupClientBestEffort } from "./attempt-client-cleanup-DYHcRQAa.js";
5
- import { n as listCodexAppServerModels } from "./models-sYnEc0gd.js";
6
- import { a as replaceCodexCatalogConnectionHomes, n as buildCodexAppServerConnectionFingerprint, t as resumeCodexAppServerThread } from "./thread-resume-C7pyVKeW.js";
7
- import { g as codexCatalogHomeId, h as canonicalCodexCatalogHome, m as projectCodexUserItemText, r as importCodexThreadHistoryToTranscript } from "./transcript-mirror-DTUxFWa_.js";
8
- import { i as requestCodexAppServerJson, o as withCodexAppServerJsonClient, r as requestCodexAppServerClientJson } from "./request-DYAI5FQE.js";
9
- import { n as describeControlFailure, t as CODEX_CONTROL_METHODS } from "./capabilities-dIjNVCYH.js";
10
- import { a as formatCodexDisplayText } from "./command-formatters-CLHhEB1Q.js";
11
- import { n as createCodexCliNodeConversationBindingData } from "./conversation-binding-data-BiodpIzq.js";
12
- import { n as prepareCodexAppServerAuthBinding } from "./auth-binding-Ds_QVm-X.js";
13
- import { i as createImportedCodexSession, n as codexUpstreamBaseline, r as codexUpstreamContinueResult, t as codexLastTerminalTurnId } from "./session-upstream-marker-C351-5Qw.js";
14
- import { asFiniteNumber, isRecord, normalizeBoundedOptionalString } from "openclaw/plugin-sdk/string-coerce-runtime";
15
- import fs from "node:fs/promises";
16
- import path from "node:path";
17
- import { timestampMsToIsoString } from "openclaw/plugin-sdk/number-runtime";
18
- import { resolvePreferredOpenClawTmpDir } from "openclaw/plugin-sdk/temp-path";
19
- import { prepareAgentRuntimeAuth } from "openclaw/plugin-sdk/agent-harness-runtime";
20
- import { pruneMapToMaxSize } from "openclaw/plugin-sdk/collection-runtime";
21
- import fsSync from "node:fs";
22
- import os from "node:os";
23
- import { listAgentIds, resolveAgentDir as resolveAgentDir$1, resolveAgentWorkspaceDir, resolveAllowedModelRef, resolveDefaultAgentDir, resolveDefaultAgentId, resolveDefaultModelForAgent } from "openclaw/plugin-sdk/agent-runtime";
24
- import { runCommandBuffered } from "openclaw/plugin-sdk/process-runtime";
25
- import { resolveSessionAgentIdsStrict } from "openclaw/plugin-sdk/agent-scope-runtime";
26
- import { materializeWindowsSpawnProgram, resolveWindowsSpawnProgram } from "openclaw/plugin-sdk/windows-spawn";
27
- import { getSessionEntry, resolveStorePath } from "openclaw/plugin-sdk/session-store-runtime";
28
- import { truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
29
- import { expectDefined } from "openclaw/plugin-sdk/expect-runtime";
30
- import { sanitizeTerminalText } from "openclaw/plugin-sdk/text-chunking";
31
- import { parseAgentSessionKey } from "openclaw/plugin-sdk/routing";
32
- import process$1 from "node:process";
33
- import { resolveSessionModelRef } from "openclaw/plugin-sdk/model-session-runtime";
34
- import { resolveApiKeyForProvider } from "openclaw/plugin-sdk/provider-auth-runtime";
35
- import { createSessionCatalogAdoptionCoordinator, listSessionCatalogEntries, sessionCatalogAdoptedSessionKey, sessionCatalogAdoptedSourceKey } from "openclaw/plugin-sdk/session-catalog";
36
- import { decodeNodePtyResumeParams, decodeNodePtyStartParams, resolveNodeHostExecutable, runNodePtyCommand } from "openclaw/plugin-sdk/node-host";
37
- //#region extensions/codex/src/jsonl-lines.ts
38
- const JSONL_STREAM_THRESHOLD_BYTES = 4194304;
39
- const JSONL_READ_CHUNK_BYTES = 1048576;
40
- async function visitJsonlLines(file, visitor, chunkBytes = JSONL_READ_CHUNK_BYTES) {
41
- let size;
42
- try {
43
- size = (await fs.stat(file)).size;
44
- } catch {
45
- return {
46
- ok: false,
47
- lineCount: 0
48
- };
49
- }
50
- if (size <= JSONL_STREAM_THRESHOLD_BYTES) {
51
- let content;
52
- try {
53
- content = await fs.readFile(file, "utf8");
54
- } catch {
55
- return {
56
- ok: false,
57
- lineCount: 0
58
- };
59
- }
60
- if (content.length === 0) return {
61
- ok: true,
62
- lineCount: 0
63
- };
64
- let lineCount = 0;
65
- for (const line of content.split(/\r?\n/u)) {
66
- lineCount += 1;
67
- if (visitor(line) === false) break;
68
- }
69
- return {
70
- ok: true,
71
- lineCount
72
- };
73
- }
74
- let handle;
75
- try {
76
- handle = await fs.open(file, "r");
77
- } catch {
78
- return {
79
- ok: false,
80
- lineCount: 0
81
- };
82
- }
83
- const buffer = Buffer.allocUnsafe(chunkBytes);
84
- const decoder = new TextDecoder();
85
- let pendingFragments = [];
86
- let lineCount = 0;
87
- try {
88
- while (true) {
89
- const { bytesRead } = await handle.read(buffer, 0, buffer.length, null);
90
- if (bytesRead === 0) break;
91
- const content = decoder.decode(buffer.subarray(0, bytesRead), { stream: true });
92
- let lineStart = 0;
93
- while (true) {
94
- const newline = content.indexOf("\n", lineStart);
95
- if (newline === -1) break;
96
- let rawLine = content.slice(lineStart, newline);
97
- if (pendingFragments.length > 0) {
98
- pendingFragments.push(rawLine);
99
- rawLine = pendingFragments.join("");
100
- pendingFragments = [];
101
- }
102
- const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
103
- lineCount += 1;
104
- if (visitor(line) === false) return {
105
- ok: true,
106
- lineCount
107
- };
108
- lineStart = newline + 1;
109
- }
110
- if (lineStart < content.length) pendingFragments.push(content.slice(lineStart));
111
- }
112
- const decoderTail = decoder.decode();
113
- if (decoderTail.length > 0) pendingFragments.push(decoderTail);
114
- if (pendingFragments.length > 0) {
115
- const rawLine = pendingFragments.join("");
116
- const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
117
- lineCount += 1;
118
- visitor(line);
119
- }
120
- return {
121
- ok: true,
122
- lineCount
123
- };
124
- } catch {
125
- return {
126
- ok: false,
127
- lineCount: 0
128
- };
129
- } finally {
130
- await handle.close().catch(() => void 0);
131
- }
132
- }
133
- //#endregion
134
- //#region extensions/codex/src/node-cli-sessions.ts
135
- const CODEX_CLI_SESSIONS_LIST_COMMAND = "codex.cli.sessions.list";
136
- const CODEX_CLI_SESSION_RESUME_COMMAND = "codex.cli.session.resume";
137
- const DEFAULT_SESSION_LIMIT = 10;
138
- const MAX_SESSION_LIMIT = 50;
139
- const DEFAULT_RESUME_TIMEOUT_MS = 12e5;
140
- const SESSION_ID_PATTERN = /^[A-Za-z0-9._:-]{1,128}$/;
141
- const activeResumeSessions = /* @__PURE__ */ new Set();
142
- function createCodexCliSessionNodeHostCommands() {
143
- return [{
144
- command: CODEX_CLI_SESSIONS_LIST_COMMAND,
145
- cap: "codex-cli-sessions",
146
- handle: listLocalCodexCliSessions
147
- }, {
148
- command: CODEX_CLI_SESSION_RESUME_COMMAND,
149
- cap: "codex-cli-sessions",
150
- dangerous: true,
151
- handle: resumeLocalCodexCliSession
152
- }];
153
- }
154
- function createCodexCliSessionNodeInvokePolicies() {
155
- return [{
156
- commands: [CODEX_CLI_SESSIONS_LIST_COMMAND],
157
- defaultPlatforms: [
158
- "macos",
159
- "linux",
160
- "windows"
161
- ],
162
- handle: (ctx) => ctx.invokeNode()
163
- }, {
164
- commands: [CODEX_CLI_SESSION_RESUME_COMMAND],
165
- dangerous: true,
166
- handle: (ctx) => ctx.invokeNode()
167
- }];
168
- }
169
- async function listCodexCliSessionsOnNode(params) {
170
- const node = await resolveCodexCliNode({
171
- runtime: params.runtime,
172
- requestedNode: params.requestedNode,
173
- command: CODEX_CLI_SESSIONS_LIST_COMMAND
174
- });
175
- return {
176
- node,
177
- result: parseCodexCliSessionsListResult(await params.runtime.nodes.invoke({
178
- nodeId: readNodeId(node),
179
- command: CODEX_CLI_SESSIONS_LIST_COMMAND,
180
- params: {
181
- limit: params.limit,
182
- filter: params.filter
183
- },
184
- timeoutMs: 15e3,
185
- scopes: ["operator.write"]
186
- }))
187
- };
188
- }
189
- async function resolveCodexCliSessionForBindingOnNode(params) {
190
- const listing = await listCodexCliSessionsOnNode({
191
- runtime: params.runtime,
192
- requestedNode: params.requestedNode,
193
- filter: params.sessionId,
194
- limit: MAX_SESSION_LIMIT
195
- });
196
- if (!listing.node.commands?.includes("codex.cli.session.resume")) throw new Error(`Node ${formatNodeLabel(listing.node)} does not expose ${CODEX_CLI_SESSION_RESUME_COMMAND}.`);
197
- return {
198
- node: listing.node,
199
- session: listing.result.sessions.find((session) => session.sessionId === params.sessionId)
200
- };
201
- }
202
- async function resumeCodexCliSessionOnNode(params) {
203
- const payload = unwrapNodeInvokePayload$1(await params.runtime.nodes.invoke({
204
- nodeId: params.nodeId,
205
- command: CODEX_CLI_SESSION_RESUME_COMMAND,
206
- params: {
207
- sessionId: params.sessionId,
208
- prompt: params.prompt,
209
- cwd: params.cwd,
210
- timeoutMs: params.timeoutMs
211
- },
212
- timeoutMs: (params.timeoutMs ?? DEFAULT_RESUME_TIMEOUT_MS) + 5e3,
213
- scopes: ["operator.write"]
214
- }));
215
- if (!isRecord(payload) || payload.ok !== true || typeof payload.text !== "string") throw new Error("Codex CLI resume returned an invalid payload.");
216
- return {
217
- ok: true,
218
- sessionId: typeof payload.sessionId === "string" ? payload.sessionId : params.sessionId,
219
- text: payload.text
220
- };
221
- }
222
- function formatCodexCliSessions(params) {
223
- if (params.result.sessions.length === 0) return `No Codex CLI sessions returned from ${formatCodexDisplayText(formatNodeLabel(params.node))}.`;
224
- return [`Codex CLI sessions on ${formatCodexDisplayText(formatNodeLabel(params.node))}:`, ...params.result.sessions.map((session) => {
225
- const details = [session.cwd, session.updatedAt].filter((value) => Boolean(value));
226
- 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`;
227
- })].join("\n");
228
- }
229
- async function listLocalCodexCliSessions(paramsJSON) {
230
- const params = readRecordParam(paramsJSON);
231
- const limit = normalizeLimit$1(params.limit);
232
- const filter = typeof params.filter === "string" ? params.filter.trim().toLowerCase() : "";
233
- const codexHome = resolveCodexHome();
234
- const summaries = await readHistorySessions(codexHome);
235
- await hydrateSessionFiles(codexHome, summaries);
236
- await hydrateSessionsFromSessionFiles(codexHome, summaries);
237
- const sessions = [...summaries.values()].filter((session) => {
238
- if (!filter) return true;
239
- return [
240
- session.sessionId,
241
- session.cwd,
242
- session.lastMessage
243
- ].some((value) => value?.toLowerCase().includes(filter));
244
- }).toSorted((a, b) => compareOptionalStringsDesc(a.updatedAt, b.updatedAt)).slice(0, limit);
245
- return JSON.stringify({
246
- sessions,
247
- codexHome
248
- });
249
- }
250
- async function resumeLocalCodexCliSession(paramsJSON) {
251
- const params = readRecordParam(paramsJSON);
252
- const sessionId = typeof params.sessionId === "string" ? params.sessionId.trim() : "";
253
- const prompt = typeof params.prompt === "string" ? params.prompt.trim() : "";
254
- if (!sessionId || !SESSION_ID_PATTERN.test(sessionId)) throw new Error("Missing or invalid Codex CLI session id.");
255
- if (!prompt) throw new Error("Missing Codex CLI prompt.");
256
- if (activeResumeSessions.has(sessionId)) throw new Error(`Codex CLI session ${sessionId} already has an active resume turn.`);
257
- activeResumeSessions.add(sessionId);
258
- try {
259
- const text = await runCodexExecResume({
260
- sessionId,
261
- prompt,
262
- cwd: typeof params.cwd === "string" && params.cwd.trim() ? params.cwd.trim() : void 0,
263
- timeoutMs: normalizeTimeoutMs(params.timeoutMs)
264
- });
265
- return JSON.stringify({
266
- ok: true,
267
- sessionId,
268
- text: text.trim() || "Codex completed without a text reply."
269
- });
270
- } finally {
271
- activeResumeSessions.delete(sessionId);
272
- }
273
- }
274
- async function runCodexExecResume(params) {
275
- const outputPath = path.join(await fs.mkdtemp(path.join(resolvePreferredOpenClawTmpDir(), "openclaw-codex-cli-")), "last-message.txt");
276
- try {
277
- const args = [
278
- "exec",
279
- "resume",
280
- "--skip-git-repo-check",
281
- "--output-last-message",
282
- outputPath,
283
- params.sessionId,
284
- "-"
285
- ];
286
- const invocation = materializeWindowsSpawnProgram(resolveWindowsSpawnProgram({
287
- command: "codex",
288
- platform: process$1.platform,
289
- env: process$1.env,
290
- execPath: process$1.execPath,
291
- packageName: "@openai/codex"
292
- }), args);
293
- const result = await runCommandBuffered([invocation.command, ...invocation.argv], {
294
- cwd: params.cwd || process$1.cwd(),
295
- input: params.prompt,
296
- env: process$1.env,
297
- killGraceMs: 2e3,
298
- killProcessTree: false,
299
- terminateOnOutputError: true,
300
- timeoutMs: params.timeoutMs
301
- });
302
- if (result.termination === "timeout") throw new Error(`codex exec resume timed out after ${String(params.timeoutMs)}ms`);
303
- if (result.termination === "error" && result.error) throw result.error;
304
- if (result.code !== 0) {
305
- const message = result.stderr.toString("utf8").trim() || result.stdout.toString("utf8").trim() || `codex exec resume exited with code ${String(result.code)}`;
306
- throw new Error(message);
307
- }
308
- return await fs.readFile(outputPath, "utf8");
309
- } finally {
310
- await fs.rm(path.dirname(outputPath), {
311
- recursive: true,
312
- force: true
313
- });
314
- }
315
- }
316
- async function readHistorySessions(codexHome) {
317
- const summaries = /* @__PURE__ */ new Map();
318
- if (!(await visitJsonlLines(path.join(codexHome, "history.jsonl"), (line) => {
319
- const trimmed = line.trim();
320
- if (!trimmed) return;
321
- let parsed;
322
- try {
323
- parsed = JSON.parse(trimmed);
324
- } catch {
325
- return;
326
- }
327
- if (!isRecord(parsed) || typeof parsed.session_id !== "string") return;
328
- const sessionId = parsed.session_id.trim();
329
- if (!sessionId) return;
330
- const entry = summaries.get(sessionId) ?? {
331
- sessionId,
332
- messageCount: 0
333
- };
334
- entry.messageCount += 1;
335
- if (typeof parsed.text === "string" && parsed.text.trim()) entry.lastMessage = truncateText(parsed.text.trim(), 140);
336
- if (typeof parsed.ts === "number") entry.updatedAt = timestampMsToIsoString(parsed.ts * 1e3) ?? entry.updatedAt;
337
- summaries.set(sessionId, entry);
338
- })).ok) return /* @__PURE__ */ new Map();
339
- return summaries;
340
- }
341
- async function hydrateSessionFiles(codexHome, summaries) {
342
- if (summaries.size === 0) return;
343
- const files = await findSessionFiles(path.join(codexHome, "sessions"), 4);
344
- const pending = new Set(summaries.keys());
345
- for (const file of files) {
346
- const basename = path.basename(file);
347
- const sessionId = [...pending].find((id) => basename.includes(id));
348
- if (!sessionId) continue;
349
- const entry = summaries.get(sessionId);
350
- if (!entry) continue;
351
- entry.sessionFile = file;
352
- const cwd = readSessionMetaCwd(await readFirstLine(file) ?? "");
353
- if (cwd) entry.cwd = cwd;
354
- pending.delete(sessionId);
355
- if (pending.size === 0) return;
356
- }
357
- }
358
- async function hydrateSessionsFromSessionFiles(codexHome, summaries) {
359
- const files = await findSessionFiles(path.join(codexHome, "sessions"), 4);
360
- for (const file of files) {
361
- const summary = await readSessionFileSummary(file);
362
- if (!summary) continue;
363
- const existing = summaries.get(summary.sessionId);
364
- summaries.set(summary.sessionId, {
365
- ...summary,
366
- ...existing,
367
- cwd: existing?.cwd ?? summary.cwd,
368
- sessionFile: existing?.sessionFile ?? summary.sessionFile,
369
- updatedAt: existing?.updatedAt ?? summary.updatedAt,
370
- lastMessage: existing?.lastMessage ?? summary.lastMessage,
371
- messageCount: existing?.messageCount ?? summary.messageCount
372
- });
373
- }
374
- }
375
- async function readSessionFileSummary(file) {
376
- let sessionId = "";
377
- let cwd;
378
- let updatedAt;
379
- let lastMessage;
380
- let messageCount = 0;
381
- const result = await visitJsonlLines(file, (line) => {
382
- const trimmed = line.trim();
383
- if (!trimmed) return;
384
- let parsed;
385
- try {
386
- parsed = JSON.parse(trimmed);
387
- } catch {
388
- return;
389
- }
390
- if (!isRecord(parsed)) return;
391
- if (typeof parsed.timestamp === "string" && parsed.timestamp.trim()) updatedAt = parsed.timestamp.trim();
392
- if (parsed.type === "session_meta" && isRecord(parsed.payload)) {
393
- if (typeof parsed.payload.id === "string" && parsed.payload.id.trim()) sessionId = parsed.payload.id.trim();
394
- if (typeof parsed.payload.cwd === "string" && parsed.payload.cwd.trim()) cwd = parsed.payload.cwd.trim();
395
- return;
396
- }
397
- const messageText = readResponseItemMessageText(parsed);
398
- if (messageText) {
399
- messageCount += 1;
400
- lastMessage = truncateText(messageText, 140);
401
- }
402
- });
403
- if (!result.ok) return null;
404
- if (result.lineCount === 0) return null;
405
- if (!sessionId) sessionId = readSessionIdFromFilename(file) ?? "";
406
- if (!sessionId) return null;
407
- return {
408
- sessionId,
409
- updatedAt: updatedAt ?? await readFileMtimeIso(file),
410
- lastMessage,
411
- cwd,
412
- sessionFile: file,
413
- messageCount
414
- };
415
- }
416
- async function findSessionFiles(dir, maxDepth) {
417
- if (maxDepth < 0) return [];
418
- let entries;
419
- try {
420
- entries = await fs.readdir(dir, { withFileTypes: true });
421
- } catch {
422
- return [];
423
- }
424
- const files = [];
425
- for (const entry of entries) {
426
- const entryPath = path.join(dir, entry.name);
427
- if (entry.isDirectory()) files.push(...await findSessionFiles(entryPath, maxDepth - 1));
428
- else if (entry.isFile() && entry.name.endsWith(".jsonl")) files.push(entryPath);
429
- }
430
- return files;
431
- }
432
- function readSessionMetaCwd(line) {
433
- try {
434
- const parsed = JSON.parse(line);
435
- if (!isRecord(parsed) || parsed.type !== "session_meta" || !isRecord(parsed.payload)) return;
436
- return typeof parsed.payload.cwd === "string" && parsed.payload.cwd.trim() ? parsed.payload.cwd.trim() : void 0;
437
- } catch {
438
- return;
439
- }
440
- }
441
- function readResponseItemMessageText(parsed) {
442
- if (parsed.type !== "response_item" || !isRecord(parsed.payload)) return;
443
- if (parsed.payload.type !== "message") return;
444
- if ((typeof parsed.payload.role === "string" ? parsed.payload.role : "") !== "user") return;
445
- const parts = (Array.isArray(parsed.payload.content) ? parsed.payload.content : []).flatMap((entry) => {
446
- if (!isRecord(entry)) return [];
447
- const text = typeof entry.text === "string" ? entry.text : typeof entry.input_text === "string" ? entry.input_text : void 0;
448
- return text?.trim() ? [text.trim()] : [];
449
- });
450
- return parts.length > 0 ? parts.join(" ") : void 0;
451
- }
452
- function readSessionIdFromFilename(file) {
453
- return path.basename(file).match(/[0-9a-f]{8}-[0-9a-f-]{27,}/iu)?.[0];
454
- }
455
- async function resolveCodexCliNode(params) {
456
- const list = await params.runtime.nodes.list(params.requestedNode ? void 0 : { connected: true });
457
- const requested = params.requestedNode?.trim();
458
- const candidates = list.nodes.filter((node) => {
459
- if (requested) return [
460
- node.nodeId,
461
- node.displayName,
462
- node.remoteIp
463
- ].some((value) => value === requested);
464
- return node.connected === true && node.commands?.includes(params.command);
465
- });
466
- if (candidates.length === 0) throw new Error(requested ? `Codex CLI node ${requested} was not found.` : "No connected node exposes Codex CLI session commands.");
467
- const usable = candidates.filter((node) => node.commands?.includes(params.command));
468
- if (usable.length === 0) throw new Error(`Node ${requested ?? "candidate"} does not expose ${params.command}.`);
469
- if (usable.length > 1) throw new Error("Multiple Codex CLI-capable nodes connected. Pass --host <node-id>.");
470
- return expectDefined(usable[0], "single usable Codex CLI node");
471
- }
472
- function parseCodexCliSessionsListResult(raw) {
473
- const payload = unwrapNodeInvokePayload$1(raw);
474
- if (!isRecord(payload) || !Array.isArray(payload.sessions)) throw new Error("Codex CLI session list returned an invalid payload.");
475
- return {
476
- codexHome: typeof payload.codexHome === "string" ? payload.codexHome : "",
477
- sessions: payload.sessions.flatMap((entry) => {
478
- if (!isRecord(entry) || typeof entry.sessionId !== "string") return [];
479
- return [{
480
- sessionId: entry.sessionId,
481
- updatedAt: typeof entry.updatedAt === "string" ? entry.updatedAt : void 0,
482
- lastMessage: typeof entry.lastMessage === "string" ? entry.lastMessage : void 0,
483
- cwd: typeof entry.cwd === "string" ? entry.cwd : void 0,
484
- sessionFile: typeof entry.sessionFile === "string" ? entry.sessionFile : void 0,
485
- messageCount: typeof entry.messageCount === "number" && Number.isFinite(entry.messageCount) ? entry.messageCount : 0
486
- }];
487
- })
488
- };
489
- }
490
- function unwrapNodeInvokePayload$1(raw) {
491
- const record = isRecord(raw) ? raw : {};
492
- if (typeof record.payloadJSON === "string" && record.payloadJSON.trim()) try {
493
- return JSON.parse(record.payloadJSON);
494
- } catch (error) {
495
- throw new Error("Codex CLI node command returned malformed payloadJSON.", { cause: error });
496
- }
497
- if ("payload" in record) return record.payload;
498
- return raw;
499
- }
500
- function readRecordParam(paramsJSON) {
501
- if (!paramsJSON?.trim()) return {};
502
- try {
503
- const parsed = JSON.parse(paramsJSON);
504
- return isRecord(parsed) ? parsed : {};
505
- } catch {
506
- return {};
507
- }
508
- }
509
- function resolveCodexHome() {
510
- return process$1.env.CODEX_HOME?.trim() || path.join(os.homedir(), ".codex");
511
- }
512
- async function readFirstLine(file) {
513
- let firstLine;
514
- return (await visitJsonlLines(file, (line) => {
515
- firstLine = line;
516
- return false;
517
- }, 65536)).ok ? firstLine : void 0;
518
- }
519
- async function readFileMtimeIso(file) {
520
- try {
521
- return (await fs.stat(file)).mtime.toISOString();
522
- } catch {
523
- return;
524
- }
525
- }
526
- function normalizeLimit$1(value) {
527
- return typeof value === "number" && Number.isFinite(value) ? Math.min(MAX_SESSION_LIMIT, Math.max(1, Math.floor(value))) : DEFAULT_SESSION_LIMIT;
528
- }
529
- function normalizeTimeoutMs(value) {
530
- return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.min(36e5, Math.floor(value)) : DEFAULT_RESUME_TIMEOUT_MS;
531
- }
532
- function truncateText(value, max) {
533
- if (value.length <= max) return value;
534
- return `${truncateUtf16Safe(value, Math.max(0, max - 3))}...`;
535
- }
536
- function compareOptionalStringsDesc(a, b) {
537
- return (b ?? "").localeCompare(a ?? "");
538
- }
539
- function readNodeId(node) {
540
- if (!node.nodeId) throw new Error("Codex CLI node did not include a node id.");
541
- return node.nodeId;
542
- }
543
- function formatNodeLabel(node) {
544
- return [
545
- node.displayName,
546
- node.nodeId,
547
- node.remoteIp
548
- ].filter(Boolean).join(" / ") || "node";
549
- }
550
- //#endregion
551
- //#region extensions/codex/src/command-rpc.ts
552
- async function prepareControlAuth(options, startOptions) {
553
- if (!options.onResponse || !options.config || !options.sessionKey || options.authProfileId === null || startOptions.homeScope === "user") return {
554
- authProfileId: options.authProfileId ?? void 0,
555
- clientOptions: { authProfileId: options.authProfileId }
556
- };
557
- const config = options.config;
558
- const { sessionAgentId } = resolveSessionAgentIdsStrict({
559
- config,
560
- sessionKey: options.sessionKey,
561
- agentId: options.agentId
562
- });
563
- const agentDir = options.agentDir ?? resolveAgentDir$1(config, sessionAgentId);
564
- const workspaceDir = resolveAgentWorkspaceDir(config, sessionAgentId);
565
- const entry = getSessionEntry({
566
- agentId: sessionAgentId,
567
- storePath: resolveStorePath(config.session?.store, { agentId: sessionAgentId }),
568
- sessionKey: options.sessionKey,
569
- hydrateSkillPromptRefs: false,
570
- readConsistency: "latest"
571
- });
572
- const model = resolveSessionModelRef(config, entry, sessionAgentId);
573
- const store = resolveCodexAppServerAuthProfileStore({
574
- agentDir,
575
- config
576
- });
577
- const { plan, attempts } = prepareAgentRuntimeAuth({
578
- provider: model.provider,
579
- modelId: model.model,
580
- config,
581
- agentDir,
582
- workspaceDir,
583
- authProfileStore: store,
584
- sessionAuthProfileId: entry?.authProfileOverride ?? options.authProfileId,
585
- sessionAuthProfileSource: entry?.authProfileOverrideSource,
586
- harnessId: "codex",
587
- harnessAuthBootstrap: "harness"
588
- });
589
- const route = plan.modelRoute;
590
- const resolvedAuth = route ? await resolveApiKeyForProvider({
591
- provider: route.provider,
592
- modelId: route.modelId,
593
- modelApi: route.api,
594
- cfg: config,
595
- agentDir,
596
- workspaceDir,
597
- store,
598
- profileId: attempts[0]?.profileId,
599
- lockedProfile: plan.forwardedAuthProfileSource === "user",
600
- allowAuthProfileFallback: attempts[0]?.allowAuthProfileFallback,
601
- skipSetupProviderFallback: true
602
- }) : void 0;
603
- const handoff = await resolveCodexAppServerPreparedAuthHandoff({
604
- authRequirement: route?.authRequirement,
605
- resolvedApiKey: resolvedAuth?.apiKey,
606
- authProfileId: route ? plan.forwardedAuthProfileId : resolveCodexAppServerAuthProfileId({
607
- authProfileId: plan.forwardedAuthProfileId,
608
- store,
609
- config
610
- }),
611
- authProfileStore: store,
612
- agentDir,
613
- homeScope: startOptions.homeScope ?? "agent",
614
- config,
615
- subscriptionProfileRequiredError: "Prepared Codex subscription route requires a forwarded OpenAI OAuth or token profile.",
616
- subscriptionProfileUnusableError: "Prepared Codex subscription auth profile is unusable."
617
- });
618
- const binding = handoff.authProfileId ? await prepareCodexAppServerAuthBinding({
619
- authProfileId: handoff.authProfileId,
620
- authProfileStore: store,
621
- agentDir,
622
- config
623
- }) : void 0;
624
- return {
625
- authProfileId: handoff.authProfileId,
626
- clientOptions: {
627
- ...handoff.preparedAuth ? { preparedAuth: handoff.preparedAuth } : { authProfileId: handoff.authProfileId },
628
- authRequirement: route?.authRequirement,
629
- authProfileStore: binding?.authProfileStore ?? store,
630
- authBindingFingerprint: binding?.fingerprint,
631
- agentDir
632
- }
633
- };
634
- }
635
- function requestOptions(pluginConfig, limit, config, agentDir) {
636
- const runtime = resolveCodexAppServerRuntimeOptions({ pluginConfig });
637
- return {
638
- limit,
639
- timeoutMs: runtime.requestTimeoutMs,
640
- startOptions: runtime.start,
641
- config,
642
- agentDir
643
- };
644
- }
645
- async function codexControlRequest(pluginConfig, method, requestParams, options = {}) {
646
- const runtime = options.startOptions ? resolveCodexSupervisionAppServerRuntimeOptions({ pluginConfig }) : resolveCodexAppServerRuntimeOptions({ pluginConfig });
647
- const startOptions = options.startOptions ?? runtime.start;
648
- const auth = await prepareControlAuth(options, startOptions);
649
- const controlRequestOptions = {
650
- timeoutMs: options.timeoutMs ?? runtime.requestTimeoutMs,
651
- assertCurrent: options.assertCurrent,
652
- startOptions,
653
- config: options.config,
654
- sessionKey: options.sessionKey,
655
- sessionId: options.sessionId,
656
- agentDir: options.agentDir,
657
- isolated: options.isolated,
658
- ...auth.clientOptions
659
- };
660
- if (options.onResponse || options.beforeRequest) return await withCodexAppServerJsonClient(controlRequestOptions, async (request, client, scope) => {
661
- await options.beforeRequest?.(request, client, scope);
662
- scope.assertCurrent();
663
- let response;
664
- if (method === "thread/resume") {
665
- if (!isJsonObject(requestParams) || typeof requestParams.threadId !== "string") throw new Error("Codex thread/resume requires a thread id.");
666
- response = await resumeCodexAppServerThread({
667
- client,
668
- request: {
669
- ...requestParams,
670
- threadId: requestParams.threadId
671
- },
672
- requestResume: () => request({
673
- method,
674
- requestParams
675
- }),
676
- abandonClient: () => closeCodexStartupClientBestEffort(client)
677
- });
678
- } else response = await request({
679
- method,
680
- requestParams
681
- });
682
- await options.onResponse?.(response, client, {
683
- authProfileId: auth.authProfileId,
684
- assertCurrent: scope.assertCurrent
685
- });
686
- scope.assertCurrent();
687
- return response;
688
- });
689
- return await requestCodexAppServerJson({
690
- method,
691
- requestParams,
692
- ...controlRequestOptions
693
- });
694
- }
695
- async function safeCodexControlRequest(pluginConfig, method, requestParams, options = {}) {
696
- return await safeValue(async () => await codexControlRequest(pluginConfig, method, requestParams, options));
697
- }
698
- async function safeCodexModelList(pluginConfig, limit, config, agentDir) {
699
- return await safeValue(async () => await listCodexAppServerModels(requestOptions(pluginConfig, limit, config, agentDir)));
700
- }
701
- async function readCodexStatusProbes(pluginConfig, config, agentDir) {
702
- const [models, account, limits, mcps, skills] = await Promise.all([
703
- safeCodexModelList(pluginConfig, 20, config, agentDir),
704
- safeCodexControlRequest(pluginConfig, CODEX_CONTROL_METHODS.account, { refreshToken: false }, {
705
- config,
706
- agentDir
707
- }),
708
- safeCodexControlRequest(pluginConfig, CODEX_CONTROL_METHODS.rateLimits, void 0, {
709
- config,
710
- agentDir
711
- }),
712
- safeCodexControlRequest(pluginConfig, CODEX_CONTROL_METHODS.listMcpServers, { limit: 100 }, {
713
- config,
714
- agentDir
715
- }),
716
- safeCodexControlRequest(pluginConfig, CODEX_CONTROL_METHODS.listSkills, {}, {
717
- config,
718
- agentDir
719
- })
720
- ]);
721
- return {
722
- models,
723
- account,
724
- limits,
725
- mcps,
726
- skills
727
- };
728
- }
729
- async function safeValue(read) {
730
- try {
731
- return {
732
- ok: true,
733
- value: await read()
734
- };
735
- } catch (error) {
736
- return {
737
- ok: false,
738
- error: describeControlFailure(error)
739
- };
740
- }
741
- }
742
- //#endregion
743
- //#region extensions/codex/src/app-server/thread-archive-guard.ts
744
- const DESCENDANT_PAGE_LIMIT = 100;
745
- const MAX_DESCENDANT_PAGES = 100;
746
- const MAX_THREAD_ID_LENGTH = 256;
747
- const MAX_CURSOR_LENGTH$1 = 4096;
748
- function readNextCursor(value) {
749
- if (value === void 0 || value === null) return;
750
- if (typeof value !== "string" || !value.trim() || value.length > MAX_CURSOR_LENGTH$1) throw new Error("Codex app-server returned an invalid descendant-list cursor");
751
- return value;
752
- }
753
- /**
754
- * Native archive includes the spawned subtree. Enumerate that same subtree first so an
755
- * OpenClaw-owned descendant cannot be stopped as an undocumented side effect.
756
- */
757
- async function assertCodexArchiveDescendantsUnowned(params) {
758
- const ancestorThreadId = normalizeBoundedOptionalString(params.threadId, MAX_THREAD_ID_LENGTH);
759
- if (!ancestorThreadId) throw new Error("cannot verify Codex archive descendants for an invalid thread id");
760
- const seenCursors = /* @__PURE__ */ new Set();
761
- const seenThreadIds = /* @__PURE__ */ new Set([ancestorThreadId]);
762
- let cursor;
763
- for (let pageIndex = 0; pageIndex < MAX_DESCENDANT_PAGES; pageIndex += 1) {
764
- const response = await params.listPage({
765
- ancestorThreadId,
766
- archived: false,
767
- limit: DESCENDANT_PAGE_LIMIT,
768
- sortKey: "created_at",
769
- sortDirection: "desc",
770
- useStateDbOnly: true,
771
- ...cursor ? { cursor } : {}
772
- });
773
- if (!isJsonObject(response) || !Array.isArray(response.data)) throw new Error("Codex app-server returned an invalid descendant-list response");
774
- if (response.data.length > DESCENDANT_PAGE_LIMIT) throw new Error("Codex app-server exceeded the descendant-list page limit");
775
- for (const value of response.data) {
776
- if (!isJsonObject(value)) throw new Error("Codex app-server returned an invalid descendant thread");
777
- const descendantThreadId = normalizeBoundedOptionalString(value.id, MAX_THREAD_ID_LENGTH);
778
- if (!descendantThreadId) throw new Error("Codex app-server returned a descendant without a valid thread id");
779
- if (seenThreadIds.has(descendantThreadId)) throw new Error("Codex app-server returned a cyclic descendant thread list");
780
- seenThreadIds.add(descendantThreadId);
781
- await params.assertDescendantIdle(descendantThreadId);
782
- if (await params.bindingStore.hasOtherThreadOwner(descendantThreadId)) throw new Error("cannot archive a Codex thread while a spawned descendant is owned by an OpenClaw session");
783
- }
784
- const nextCursor = readNextCursor(response.nextCursor);
785
- if (!nextCursor) return;
786
- if (seenCursors.has(nextCursor)) throw new Error("Codex app-server returned a repeated descendant-list cursor");
787
- seenCursors.add(nextCursor);
788
- cursor = nextCursor;
789
- }
790
- throw new Error("Codex descendant enumeration exceeded its safety limit");
791
- }
792
- //#endregion
793
- //#region extensions/codex/src/session-catalog-parsing.ts
794
- const DEFAULT_PAGE_LIMIT = 50;
795
- const CODEX_APP_SERVER_THREADS_CAPABILITY = "codex-app-server-threads";
796
- const CODEX_APP_SERVER_THREADS_LIST_COMMAND = "codex.appServer.threads.list.v1";
797
- const CODEX_APP_SERVER_THREAD_TURNS_LIST_COMMAND = "codex.appServer.thread.turns.list.v1";
798
- const CODEX_LOCAL_SESSION_HOST_ID = "gateway:local";
799
- const NODE_INVOKE_TIMEOUT_MS = 65e3;
800
- const MAX_SEARCH_LENGTH = 500;
801
- const MAX_CURSOR_LENGTH = 4096;
802
- const MAX_CURSOR_COUNT = 100;
803
- const MAX_HOST_ID_LENGTH = 256;
804
- const MAX_CWD_LENGTH = 4096;
805
- const MAX_SESSION_NAME_LENGTH = 500;
806
- const MAX_SESSION_PREVIEW_LENGTH = 500;
807
- const MAX_SESSION_KEY_LENGTH = 1024;
808
- const MAX_METADATA_LENGTH = 500;
809
- const MAX_ACTIVE_FLAGS = 16;
810
- const MAX_TRANSCRIPT_PAGE_BYTES = 20971520;
811
- var CatalogParamsError = class extends Error {};
812
- function readControlCursor(value, label) {
813
- if (value === void 0 || value === null) return;
814
- if (typeof value !== "string" || !value.trim() || value.length > 4096) throw new CatalogParamsError(`invalid Codex session catalog ${label} cursor`);
815
- return value;
816
- }
817
- function boundedCatalogString(value, maxLength, overflow = "omit") {
818
- if (typeof value !== "string") return;
819
- const normalized = value.trim();
820
- if (!normalized) return;
821
- if (normalized.length <= maxLength) return normalized;
822
- return overflow === "truncate" ? truncateUtf16Safe(normalized, maxLength) : void 0;
823
- }
824
- function catalogPreview(value) {
825
- if (typeof value !== "string") return;
826
- return boundedCatalogString(sanitizeTerminalText(value.replace(/\s+/g, " ")), MAX_SESSION_PREVIEW_LENGTH, "truncate");
827
- }
828
- function normalizeInteractiveThreadSource(source) {
829
- if (CODEX_INTERACTIVE_THREAD_SOURCE_KINDS.some((kind) => kind === source) || CODEX_INTERACTIVE_CUSTOM_THREAD_SOURCES.some((kind) => kind === source)) return source;
830
- if (isRecord(source) && CODEX_INTERACTIVE_CUSTOM_THREAD_SOURCES.some((kind) => kind === source.custom)) return source.custom;
831
- }
832
- function isInteractiveThreadSource(source) {
833
- return normalizeInteractiveThreadSource(source) !== void 0;
834
- }
835
- function toCatalogSession(thread, archived) {
836
- const source = normalizeInteractiveThreadSource(thread.source);
837
- if (!source) return;
838
- const record = thread;
839
- const threadId = boundedCatalogString(thread.id, 256);
840
- if (!threadId) return;
841
- const activeFlags = thread.status?.type === "active" ? thread.status.activeFlags?.flatMap((flag) => {
842
- const normalized = boundedCatalogString(flag, 128);
843
- return normalized ? [normalized] : [];
844
- }).slice(0, MAX_ACTIVE_FLAGS) : void 0;
845
- const gitInfo = isRecord(record.gitInfo) ? record.gitInfo : void 0;
846
- const sessionId = boundedCatalogString(thread.sessionId, 256);
847
- const name = boundedCatalogString(thread.name, MAX_SESSION_NAME_LENGTH, "truncate");
848
- const fallbackName = name ? void 0 : catalogPreview(thread.preview);
849
- const cwd = boundedCatalogString(thread.cwd, MAX_CWD_LENGTH);
850
- const modelProvider = boundedCatalogString(record.modelProvider, MAX_METADATA_LENGTH, "truncate");
851
- const cliVersion = boundedCatalogString(record.cliVersion, MAX_METADATA_LENGTH, "truncate");
852
- const gitBranch = boundedCatalogString(gitInfo?.branch, MAX_METADATA_LENGTH, "truncate");
853
- return {
854
- threadId,
855
- status: thread.status?.type ?? "notLoaded",
856
- archived,
857
- ...sessionId ? { sessionId } : {},
858
- ...thread.name === null ? { name: null } : name ? { name } : {},
859
- ...fallbackName ? { fallbackName } : {},
860
- ...cwd ? { cwd } : {},
861
- ...activeFlags?.length ? { activeFlags } : {},
862
- ...typeof thread.createdAt === "number" && Number.isFinite(thread.createdAt) ? { createdAt: thread.createdAt } : {},
863
- ...typeof thread.updatedAt === "number" && Number.isFinite(thread.updatedAt) ? { updatedAt: thread.updatedAt } : {},
864
- ...typeof record.recencyAt === "number" && Number.isFinite(record.recencyAt) ? { recencyAt: record.recencyAt } : record.recencyAt === null ? { recencyAt: null } : {},
865
- source,
866
- ...modelProvider ? { modelProvider } : {},
867
- ...cliVersion ? { cliVersion } : {},
868
- ...gitBranch ? { gitBranch } : {}
869
- };
870
- }
871
- function normalizeLimit(value, key) {
872
- if (value === void 0) return DEFAULT_PAGE_LIMIT;
873
- if (!Number.isInteger(value) || value < 1 || value > 100) throw new CatalogParamsError(`${key} must be an integer from 1 to 100`);
874
- return value;
875
- }
876
- function readBoundedOptionalString(params, key, maxLength) {
877
- const value = params[key];
878
- if (value === void 0) return;
879
- if (typeof value !== "string") throw new CatalogParamsError(`${key} must be a string`);
880
- const trimmed = value.trim();
881
- if (!trimmed) return;
882
- if (trimmed.length > maxLength) throw new CatalogParamsError(`${key} must be at most ${maxLength} characters`);
883
- return trimmed;
884
- }
885
- function requireOnlyKeys(params, allowed) {
886
- const unknown = Object.keys(params).find((key) => !allowed.has(key));
887
- if (unknown) throw new CatalogParamsError(`unknown Codex session catalog parameter: ${unknown}`);
888
- }
889
- function readPageParams(value) {
890
- if (!isRecord(value)) throw new CatalogParamsError("Codex session catalog parameters must be an object");
891
- const params = value;
892
- requireOnlyKeys(params, /* @__PURE__ */ new Set([
893
- "cursor",
894
- "limit",
895
- "searchTerm",
896
- "cwd"
897
- ]));
898
- const cursor = readBoundedOptionalString(params, "cursor", MAX_CURSOR_LENGTH);
899
- const searchTerm = readBoundedOptionalString(params, "searchTerm", MAX_SEARCH_LENGTH);
900
- const cwd = readBoundedOptionalString(params, "cwd", MAX_CWD_LENGTH);
901
- return {
902
- limit: normalizeLimit(params.limit, "limit"),
903
- ...cursor ? { cursor } : {},
904
- ...searchTerm ? { searchTerm } : {},
905
- ...cwd ? { cwd } : {}
906
- };
907
- }
908
- function readGatewayParams(value) {
909
- if (value !== void 0 && !isRecord(value)) throw new CatalogParamsError("Codex session catalog parameters must be an object");
910
- const params = isRecord(value) ? value : {};
911
- requireOnlyKeys(params, /* @__PURE__ */ new Set([
912
- "search",
913
- "limitPerHost",
914
- "hostIds",
915
- "cursors"
916
- ]));
917
- const search = readBoundedOptionalString(params, "search", MAX_SEARCH_LENGTH);
918
- let hostIds;
919
- if (params.hostIds !== void 0) {
920
- if (!Array.isArray(params.hostIds) || params.hostIds.length > 100) throw new CatalogParamsError(`hostIds must contain at most 100 host ids`);
921
- hostIds = [...new Set(params.hostIds.map((hostId) => readHostId(hostId)))];
922
- }
923
- let cursors;
924
- if (params.cursors !== void 0) {
925
- if (!isRecord(params.cursors)) throw new CatalogParamsError("cursors must be an object");
926
- const entries = Object.entries(params.cursors);
927
- if (entries.length > MAX_CURSOR_COUNT) throw new CatalogParamsError(`cursors may contain at most ${MAX_CURSOR_COUNT} hosts`);
928
- cursors = {};
929
- for (const [hostId, cursor] of entries) {
930
- const normalizedHostId = hostId.trim();
931
- 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}`);
932
- if (typeof cursor !== "string" || !cursor.trim() || cursor.trim().length > 4096) throw new CatalogParamsError(`invalid cursor for Codex session catalog host: ${hostId}`);
933
- cursors[normalizedHostId] = cursor.trim();
934
- }
935
- }
936
- return {
937
- limitPerHost: normalizeLimit(params.limitPerHost, "limitPerHost"),
938
- ...search ? { search } : {},
939
- ...hostIds && hostIds.length > 0 ? { hostIds } : {},
940
- ...cursors && Object.keys(cursors).length > 0 ? { cursors } : {}
941
- };
942
- }
943
- function readHostId(value) {
944
- if (typeof value !== "string") throw new CatalogParamsError("Codex session catalog host ids must be strings");
945
- const hostId = value.trim();
946
- 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}`);
947
- return hostId;
948
- }
949
- function parseJsonParams(paramsJSON) {
950
- if (!paramsJSON?.trim()) return {};
951
- try {
952
- return JSON.parse(paramsJSON);
953
- } catch (error) {
954
- throw new Error("Codex session catalog parameters must be valid JSON", { cause: error });
955
- }
956
- }
957
- function parseOptionalCatalogString(value, field, maxLength) {
958
- if (value === void 0) return;
959
- if (typeof value !== "string" || value.length > maxLength) throw new Error(`Codex session catalog returned an invalid ${field}`);
960
- return value;
961
- }
962
- function parseCatalogSession(value, options = {}) {
963
- 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");
964
- const status = parseOptionalCatalogString(value.status, "status", 64);
965
- if (!status?.trim()) throw new Error("Codex session catalog returned an invalid status");
966
- if (value.activeFlags !== void 0 && !Array.isArray(value.activeFlags)) throw new Error("Codex session catalog returned invalid active flags");
967
- if (Array.isArray(value.activeFlags) && value.activeFlags.length > MAX_ACTIVE_FLAGS) throw new Error("Codex session catalog returned too many active flags");
968
- const activeFlags = Array.isArray(value.activeFlags) ? value.activeFlags.map((entry) => {
969
- const flag = parseOptionalCatalogString(entry, "active flag", 128);
970
- if (flag === void 0) throw new Error("Codex session catalog returned an invalid active flag");
971
- return flag;
972
- }) : void 0;
973
- const sessionId = parseOptionalCatalogString(value.sessionId, "session id", 256);
974
- const name = value.name === null ? null : parseOptionalCatalogString(value.name, "session name", MAX_SESSION_NAME_LENGTH);
975
- const fallbackName = parseOptionalCatalogString(value.fallbackName, "session fallback name", MAX_SESSION_PREVIEW_LENGTH);
976
- const cwd = parseOptionalCatalogString(value.cwd, "cwd", MAX_CWD_LENGTH);
977
- const source = parseOptionalCatalogString(value.source, "source", MAX_METADATA_LENGTH);
978
- const modelProvider = parseOptionalCatalogString(value.modelProvider, "model provider", MAX_METADATA_LENGTH);
979
- const cliVersion = parseOptionalCatalogString(value.cliVersion, "CLI version", MAX_METADATA_LENGTH);
980
- const gitBranch = parseOptionalCatalogString(value.gitBranch, "Git branch", MAX_METADATA_LENGTH);
981
- const sessionKey = options.allowSessionKey ? parseOptionalCatalogString(value.sessionKey, "OpenClaw session key", MAX_SESSION_KEY_LENGTH) : void 0;
982
- const createdAt = asFiniteNumber(value.createdAt);
983
- const updatedAt = asFiniteNumber(value.updatedAt);
984
- const recencyAt = value.recencyAt === null ? null : asFiniteNumber(value.recencyAt);
985
- return {
986
- threadId: value.threadId,
987
- status,
988
- archived: value.archived,
989
- ...sessionId !== void 0 ? { sessionId } : {},
990
- ...name !== void 0 ? { name } : {},
991
- ...fallbackName !== void 0 ? { fallbackName } : {},
992
- ...cwd !== void 0 ? { cwd } : {},
993
- ...activeFlags && activeFlags.length > 0 ? { activeFlags } : {},
994
- ...createdAt !== void 0 ? { createdAt } : {},
995
- ...updatedAt !== void 0 ? { updatedAt } : {},
996
- ...recencyAt !== void 0 ? { recencyAt } : {},
997
- ...source !== void 0 ? { source } : {},
998
- ...modelProvider !== void 0 ? { modelProvider } : {},
999
- ...cliVersion !== void 0 ? { cliVersion } : {},
1000
- ...gitBranch !== void 0 ? { gitBranch } : {},
1001
- ...sessionKey !== void 0 ? { sessionKey } : {}
1002
- };
1003
- }
1004
- function parseCatalogPage(value, options = {}) {
1005
- if (!isRecord(value) || !Array.isArray(value.sessions) || value.sessions.length > 100) throw new Error("Codex session catalog returned an invalid page");
1006
- const nextCursor = parseOptionalCatalogString(value.nextCursor, "next cursor", MAX_CURSOR_LENGTH);
1007
- const backwardsCursor = parseOptionalCatalogString(value.backwardsCursor, "backwards cursor", MAX_CURSOR_LENGTH);
1008
- return {
1009
- sessions: value.sessions.map((session) => parseCatalogSession(session, options)),
1010
- ...nextCursor ? { nextCursor } : {},
1011
- ...backwardsCursor ? { backwardsCursor } : {}
1012
- };
1013
- }
1014
- function filterCatalogPageByTitle(page, searchTerm) {
1015
- if (!searchTerm) return page;
1016
- return {
1017
- ...page,
1018
- sessions: page.sessions.filter((session) => (session.name ?? session.fallbackName)?.toLocaleLowerCase().includes(searchTerm.toLocaleLowerCase()))
1019
- };
1020
- }
1021
- function unwrapNodeInvokePayload(value) {
1022
- if (!isRecord(value)) return value;
1023
- if (typeof value.payloadJSON === "string" && value.payloadJSON.trim()) try {
1024
- return JSON.parse(value.payloadJSON);
1025
- } catch (error) {
1026
- throw new Error("Codex node returned malformed session catalog JSON", { cause: error });
1027
- }
1028
- return "payload" in value ? value.payload : value;
1029
- }
1030
- function catalogErrorDetail(error) {
1031
- if (error instanceof Error) return error.message.trim();
1032
- if (typeof error === "string") return error.trim();
1033
- if (error && typeof error === "object" && "message" in error) {
1034
- const message = error.message;
1035
- return typeof message === "string" ? message.trim() : "";
1036
- }
1037
- return "";
1038
- }
1039
- function catalogError(code, error) {
1040
- const summary = {
1041
- APP_SERVER_UNAVAILABLE: "Codex app-server is unavailable on this host",
1042
- NODE_INVOKE_FAILED: "The paired node could not return its Codex session catalog",
1043
- NODE_LIST_FAILED: "Paired nodes could not be listed"
1044
- }[code] ?? "Codex session catalog request failed";
1045
- const detail = code === "NODE_LIST_FAILED" ? catalogErrorDetail(error) : "";
1046
- return {
1047
- code,
1048
- message: detail && detail !== summary ? `${summary}: ${detail}` : summary
1049
- };
1050
- }
1051
- function parseTranscriptPage(value) {
1052
- 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");
1053
- const nextCursor = readControlCursor(value.nextCursor, "transcript next response");
1054
- const backwardsCursor = readControlCursor(value.backwardsCursor, "transcript backwards response");
1055
- const page = {
1056
- data: value.data,
1057
- ...nextCursor ? { nextCursor } : {},
1058
- ...backwardsCursor ? { backwardsCursor } : {}
1059
- };
1060
- if (Buffer.byteLength(JSON.stringify(page), "utf8") > MAX_TRANSCRIPT_PAGE_BYTES) throw new Error("Codex app-server transcript page exceeds the safe response size");
1061
- return page;
1062
- }
1063
- function requireBoundThread(entry) {
1064
- if (!entry.boundThreadId) throw new CatalogParamsError("Codex adoption is missing its bound thread. Retry.");
1065
- return entry.boundThreadId;
1066
- }
1067
- //#endregion
1068
- //#region extensions/codex/src/session-catalog-node-adoption.ts
1069
- const CODEX_NODE_SESSION_KEY_PREFIX = "harness:codex:node-session:";
1070
- const continueOperations = /* @__PURE__ */ new Map();
1071
- const sessionActionTails = /* @__PURE__ */ new Map();
1072
- async function runSessionActionExclusive(threadId, run) {
1073
- const operation = (sessionActionTails.get(threadId) ?? Promise.resolve()).then(run);
1074
- const tail = operation.then(() => void 0, () => void 0);
1075
- sessionActionTails.set(threadId, tail);
1076
- try {
1077
- return await operation;
1078
- } finally {
1079
- if (sessionActionTails.get(threadId) === tail) sessionActionTails.delete(threadId);
1080
- }
1081
- }
1082
- function adoptionSessionKeyRest(sessionKey) {
1083
- const trimmed = sessionKey.trim();
1084
- return parseAgentSessionKey(trimmed)?.rest ?? trimmed;
1085
- }
1086
- function nodeAdoptionSessionKey(hostId, threadId) {
1087
- const source = JSON.stringify([hostId, threadId]);
1088
- return sessionCatalogAdoptedSessionKey(CODEX_NODE_SESSION_KEY_PREFIX, source);
1089
- }
1090
- function readNodeSessionMarker(entry) {
1091
- const codex = isRecord(entry.pluginExtensions?.codex) ? entry.pluginExtensions.codex : void 0;
1092
- const marker = codex && isRecord(codex.sessionCatalog) ? codex.sessionCatalog : void 0;
1093
- 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;
1094
- return {
1095
- sourceHostId: marker.sourceHostId,
1096
- sourceThreadId: marker.sourceThreadId,
1097
- nodeId: marker.nodeId,
1098
- ...marker.initializing === true ? { initializing: true } : {}
1099
- };
1100
- }
1101
- function listNodeAdoptedSessionEntries(params) {
1102
- const adopted = /* @__PURE__ */ new Map();
1103
- for (const { agentId, entry, sessionKey } of listSessionCatalogEntries({
1104
- ...params.agentId ? { agentId: params.agentId } : {},
1105
- config: params.config ?? {},
1106
- runtime: params.runtime,
1107
- sessionEntries: params.sessionEntries
1108
- })) {
1109
- const marker = readNodeSessionMarker(entry);
1110
- const sessionId = entry.sessionId?.trim();
1111
- 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;
1112
- const sourceKey = sessionCatalogAdoptedSourceKey(marker.sourceHostId, marker.sourceThreadId);
1113
- if (adopted.has(sourceKey)) throw new Error(`multiple OpenClaw sessions adopt Codex thread ${marker.sourceThreadId} on ${marker.sourceHostId}`);
1114
- adopted.set(sourceKey, {
1115
- key: sessionKey,
1116
- sessionId,
1117
- agentId,
1118
- ...marker.initializing === true ? { initializing: true } : {}
1119
- });
1120
- }
1121
- return adopted;
1122
- }
1123
- function findNodeAdoptedSessionEntry(params) {
1124
- return listNodeAdoptedSessionEntries(params).get(sessionCatalogAdoptedSourceKey(params.hostId, params.threadId));
1125
- }
1126
- function nodeSessionMarker(params) {
1127
- return {
1128
- sourceHostId: params.hostId,
1129
- sourceThreadId: params.threadId,
1130
- nodeId: params.nodeId,
1131
- ...params.initializing === true ? { initializing: true } : {}
1132
- };
1133
- }
1134
- async function finalizeNodeAdoptedSession(params) {
1135
- const changedError = () => new CatalogParamsError("Codex OpenClaw session changed before it could be bound. Retry.");
1136
- let finalized;
1137
- try {
1138
- finalized = await params.api.runtime.agent.session.patchSessionEntry({
1139
- sessionKey: params.adopted.key,
1140
- readConsistency: "latest",
1141
- preserveActivity: true,
1142
- update: (entry) => {
1143
- const current = readNodeSessionMarker(entry);
1144
- 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();
1145
- if (current.initializing !== true) return { archivedAt: void 0 };
1146
- const codex = isRecord(entry.pluginExtensions?.codex) ? entry.pluginExtensions.codex : {};
1147
- return {
1148
- archivedAt: void 0,
1149
- pluginExtensions: {
1150
- ...entry.pluginExtensions,
1151
- codex: {
1152
- ...codex,
1153
- sessionCatalog: params.marker
1154
- }
1155
- }
1156
- };
1157
- }
1158
- });
1159
- } catch (error) {
1160
- const currentEntry = params.api.runtime.agent.session.getSessionEntry({
1161
- sessionKey: params.adopted.key,
1162
- readConsistency: "latest"
1163
- });
1164
- const current = currentEntry ? readNodeSessionMarker(currentEntry) : void 0;
1165
- 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;
1166
- throw error;
1167
- }
1168
- if (!finalized) throw changedError();
1169
- }
1170
- async function createOrReuseNodeAdoptedSession(params) {
1171
- const existing = findNodeAdoptedSessionEntry({
1172
- agentId: params.agentId,
1173
- config: params.config,
1174
- runtime: params.api.runtime,
1175
- hostId: params.hostId,
1176
- threadId: params.record.threadId,
1177
- includeInitializing: true
1178
- });
1179
- if (existing) return existing;
1180
- const initializingMarker = {
1181
- ...nodeSessionMarker({
1182
- hostId: params.hostId,
1183
- threadId: params.record.threadId,
1184
- nodeId: params.nodeId
1185
- }),
1186
- initializing: true
1187
- };
1188
- try {
1189
- const created = await params.api.runtime.agent.session.createSessionEntry({
1190
- cfg: params.config,
1191
- key: nodeAdoptionSessionKey(params.hostId, params.record.threadId),
1192
- agentId: params.agentId,
1193
- recoverMatchingInitialEntry: true,
1194
- displayName: params.record.name ?? void 0,
1195
- ...params.record.cwd?.trim() ? { spawnedCwd: params.record.cwd.trim() } : {},
1196
- initialEntry: {
1197
- agentHarnessId: "codex",
1198
- modelSelectionLocked: true,
1199
- pluginExtensions: { codex: { sessionCatalog: initializingMarker } }
1200
- },
1201
- afterCreate: async (entry) => {
1202
- const storePath = resolveStorePath(params.config.session?.store, { agentId: entry.agentId });
1203
- await importCodexThreadHistoryToTranscript({
1204
- thread: params.history.thread,
1205
- throughTurnId: params.history.throughTurnId,
1206
- storePath,
1207
- sessionId: entry.sessionId,
1208
- sessionKey: entry.key,
1209
- agentId: entry.agentId,
1210
- ...params.record.cwd?.trim() ? { cwd: params.record.cwd.trim() } : {},
1211
- modelProvider: params.record.modelProvider,
1212
- config: params.config
1213
- });
1214
- return { pluginExtensions: { codex: { sessionCatalog: initializingMarker } } };
1215
- }
1216
- });
1217
- return {
1218
- key: created.key,
1219
- sessionId: created.sessionId,
1220
- agentId: created.agentId,
1221
- initializing: true
1222
- };
1223
- } catch (error) {
1224
- const raced = findNodeAdoptedSessionEntry({
1225
- agentId: params.agentId,
1226
- config: params.config,
1227
- runtime: params.api.runtime,
1228
- hostId: params.hostId,
1229
- threadId: params.record.threadId,
1230
- includeInitializing: true
1231
- });
1232
- if (raced) return raced;
1233
- throw error;
1234
- }
1235
- }
1236
- //#endregion
1237
- //#region extensions/codex/src/session-catalog-adoption.ts
1238
- const CODEX_SUPERVISION_SESSION_KEY_PREFIX = "harness:codex:supervision:";
1239
- const boundCatalogSessionId = (value) => boundedCatalogString(value, 256);
1240
- function requireIdleThread(thread, action) {
1241
- if (thread.status?.type === "idle" || action === "archive" && thread.status?.type === "notLoaded") return;
1242
- 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"}`);
1243
- throw new CatalogParamsError(action === "archive" ? "Codex session cannot be archived in its current state" : "Codex session cannot start a branch in its current state");
1244
- }
1245
- function adoptionSessionKey(threadId, sourceHomeId) {
1246
- const source = sourceHomeId ? JSON.stringify([sourceHomeId, threadId]) : threadId;
1247
- return sessionCatalogAdoptedSessionKey(CODEX_SUPERVISION_SESSION_KEY_PREFIX, source);
1248
- }
1249
- function isAdoptionSessionKeyForThread(sessionKey, threadId, sourceHomeId) {
1250
- return adoptionSessionKeyRest(sessionKey) === adoptionSessionKey(threadId, sourceHomeId);
1251
- }
1252
- function readCodexSupervisionMarker(entry) {
1253
- const codex = isRecord(entry.pluginExtensions?.codex) ? entry.pluginExtensions.codex : void 0;
1254
- const marker = codex && isRecord(codex.supervision) ? codex.supervision : void 0;
1255
- const sourceThreadId = marker?.sourceThreadId;
1256
- const sourceHomeId = marker?.sourceHomeId;
1257
- if (typeof sourceThreadId !== "string" || !sourceThreadId.trim() || sourceHomeId !== void 0 && (typeof sourceHomeId !== "string" || !sourceHomeId.trim())) return;
1258
- return {
1259
- sourceThreadId: sourceThreadId.trim(),
1260
- ...typeof sourceHomeId === "string" ? { sourceHomeId: sourceHomeId.trim() } : {}
1261
- };
1262
- }
1263
- async function listAdoptedSessionEntries(params) {
1264
- const adopted = /* @__PURE__ */ new Map();
1265
- for (const { agentId, entry, sessionKey } of listSessionCatalogEntries({
1266
- ...params.agentId ? { agentId: params.agentId } : {},
1267
- config: params.config ?? {},
1268
- runtime: params.runtime,
1269
- sessionEntries: params.sessionEntries
1270
- })) {
1271
- const sessionKeyRest = adoptionSessionKeyRest(sessionKey);
1272
- const marker = readCodexSupervisionMarker(entry);
1273
- if (!sessionKeyRest.startsWith(CODEX_SUPERVISION_SESSION_KEY_PREFIX) || !marker || entry.initializationPending === true || entry.agentHarnessId !== "codex" || entry.modelSelectionLocked !== true) continue;
1274
- const sessionId = entry.sessionId?.trim();
1275
- if (!sessionId) continue;
1276
- const binding = await params.bindingStore.read(sessionBindingIdentity({
1277
- sessionId,
1278
- sessionKey,
1279
- config: params.config
1280
- }));
1281
- const sourceThreadId = binding?.supervisionSourceThreadId?.trim();
1282
- const boundThreadId = binding?.threadId.trim();
1283
- if (binding?.connectionScope !== "supervision" || !sourceThreadId || !boundThreadId || sessionKeyRest !== adoptionSessionKey(sourceThreadId, marker.sourceHomeId)) continue;
1284
- const sourceKey = sessionCatalogAdoptedSourceKey(marker.sourceHomeId ?? "gateway:local", sourceThreadId);
1285
- if (adopted.has(sourceKey)) throw new Error(`multiple OpenClaw sessions adopt Codex thread ${sourceThreadId} from the same home`);
1286
- adopted.set(sourceKey, {
1287
- key: sessionKey,
1288
- sessionId,
1289
- agentId,
1290
- boundThreadId
1291
- });
1292
- }
1293
- return adopted;
1294
- }
1295
- async function findAdoptedSessionEntry(params) {
1296
- const adopted = await listAdoptedSessionEntries(params);
1297
- return adopted.get(sessionCatalogAdoptedSourceKey(params.sourceHomeId ?? "gateway:local", params.threadId)) ?? (params.sourceHomeId && params.allowLegacy === true ? adopted.get(sessionCatalogAdoptedSourceKey("gateway:local", params.threadId)) : void 0);
1298
- }
1299
- function matchesPendingAdoptionBinding(binding, expected) {
1300
- const historyCoveredThrough = binding?.historyCoveredThrough;
1301
- 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));
1302
- }
1303
- async function ensurePendingAdoptionBinding(params) {
1304
- const pending = {
1305
- sourceThreadId: params.sourceThreadId,
1306
- connectionFingerprint: params.connectionFingerprint,
1307
- ...params.lastTurnId ? { lastTurnId: params.lastTurnId } : {}
1308
- };
1309
- const ownsGeneration = await reclaimCurrentCodexSessionGeneration({
1310
- assertCurrent: params.initialization.assertCurrent,
1311
- bindingStore: params.bindingStore,
1312
- identity: params.identity,
1313
- config: params.config
1314
- });
1315
- params.initialization.assertCurrent();
1316
- if (!ownsGeneration) throw new Error(`failed to claim the OpenClaw session generation for ${params.sourceThreadId}`);
1317
- const existing = await params.bindingStore.read(params.identity);
1318
- params.initialization.assertCurrent();
1319
- if (existing) {
1320
- if (matchesPendingAdoptionBinding(existing, params)) return;
1321
- throw new Error(`OpenClaw session is already bound to Codex thread ${existing.threadId}`);
1322
- }
1323
- const binding = {
1324
- threadId: params.sourceThreadId,
1325
- connectionScope: "supervision",
1326
- supervisionSourceThreadId: params.sourceThreadId,
1327
- cwd: params.cwd,
1328
- historyCoveredThrough: (/* @__PURE__ */ new Date()).toISOString(),
1329
- conversationSourceTransferComplete: true,
1330
- preserveNativeModel: true,
1331
- pendingSupervisionBranch: pending
1332
- };
1333
- await params.initialization.bind(binding);
1334
- }
1335
- async function createOrReuseAdoptedSession(params) {
1336
- const runtime = params.api.runtime;
1337
- const lookup = {
1338
- ...params,
1339
- runtime,
1340
- threadId: params.sourceThread.id
1341
- };
1342
- const existing = await findAdoptedSessionEntry(lookup);
1343
- if (existing) return existing;
1344
- try {
1345
- const spawnedCwd = params.sourceThread.cwd?.trim() || void 0;
1346
- const pendingLastTurnId = codexLastTerminalTurnId(params.sourceThread, boundCatalogSessionId);
1347
- const marker = {
1348
- sourceThreadId: params.sourceThread.id,
1349
- ...params.sourceHomeId ? { sourceHomeId: params.sourceHomeId } : {}
1350
- };
1351
- const created = await createImportedCodexSession({
1352
- runtime: params.api.runtime,
1353
- bindingStore: params.bindingStore,
1354
- config: params.config,
1355
- key: adoptionSessionKey(params.sourceThread.id, params.sourceHomeId),
1356
- agentId: params.agentId,
1357
- displayName: params.sourceThread.name ?? void 0,
1358
- thread: params.sourceThread,
1359
- throughTurnId: pendingLastTurnId ?? null,
1360
- recoverMatchingInitialEntry: true,
1361
- initialEntry: {
1362
- agentHarnessId: "codex",
1363
- modelSelectionLocked: true,
1364
- pluginExtensions: { codex: { supervision: {
1365
- ...marker,
1366
- initializing: true,
1367
- modelLocked: true
1368
- } } }
1369
- },
1370
- afterImport: async (entry, initialization) => {
1371
- const identity = sessionBindingIdentity({
1372
- sessionId: entry.sessionId,
1373
- sessionKey: entry.key,
1374
- config: params.config
1375
- });
1376
- await ensurePendingAdoptionBinding({
1377
- bindingStore: params.bindingStore,
1378
- config: params.config,
1379
- identity,
1380
- initialization,
1381
- sourceThreadId: params.sourceThread.id,
1382
- connectionFingerprint: params.connectionFingerprint,
1383
- cwd: spawnedCwd ?? "",
1384
- ...pendingLastTurnId ? { lastTurnId: pendingLastTurnId } : {}
1385
- });
1386
- return { pluginExtensions: { codex: { supervision: {
1387
- ...marker,
1388
- modelLocked: true
1389
- } } } };
1390
- }
1391
- });
1392
- return {
1393
- key: created.key,
1394
- sessionId: created.sessionId,
1395
- agentId: created.agentId,
1396
- boundThreadId: params.sourceThread.id
1397
- };
1398
- } catch (error) {
1399
- const raced = await findAdoptedSessionEntry(lookup);
1400
- if (raced) return raced;
1401
- throw error;
1402
- }
1403
- }
1404
- async function continueLocalCodexSessionInner(params) {
1405
- await params.control.requireEligibleThread(params.threadId);
1406
- const existing = await findAdoptedSessionEntry({
1407
- ...params,
1408
- runtime: params.api.runtime
1409
- });
1410
- if (existing) {
1411
- const boundThreadId = requireBoundThread(existing);
1412
- const boundThread = await params.control.readThread(boundThreadId, true);
1413
- if (boundThread.id !== boundThreadId) throw new Error("Codex app-server returned a different thread than requested");
1414
- const changedError = () => new CatalogParamsError("Codex OpenClaw session changed before it could be opened. Retry.");
1415
- if (!await params.api.runtime.agent.session.patchSessionEntry({
1416
- sessionKey: existing.key,
1417
- readConsistency: "latest",
1418
- preserveActivity: true,
1419
- update: (entry) => {
1420
- if (entry.sessionId?.trim() !== existing.sessionId || entry.initializationPending === true || entry.agentHarnessId !== "codex" || entry.modelSelectionLocked !== true) throw changedError();
1421
- return { archivedAt: void 0 };
1422
- }
1423
- })) throw changedError();
1424
- const connectionFingerprint = params.control.connectionFingerprint;
1425
- if (connectionFingerprint) params.onContinued?.({
1426
- connectionFingerprint,
1427
- ...codexUpstreamBaseline(boundThread, boundCatalogSessionId)
1428
- });
1429
- return {
1430
- sessionKey: existing.key,
1431
- disposition: "existing"
1432
- };
1433
- }
1434
- const sourceThread = await params.control.readThread(params.threadId, true);
1435
- if (sourceThread.id !== params.threadId) throw new Error("Codex app-server returned a different thread than requested");
1436
- if (sourceThread.status?.type !== "notLoaded") requireIdleThread(sourceThread, "continue");
1437
- const connectionFingerprint = params.control.connectionFingerprint;
1438
- if (!connectionFingerprint) throw new Error("Codex Continue requires a pinned app-server connection");
1439
- const adopted = await createOrReuseAdoptedSession({
1440
- ...params,
1441
- sourceThread,
1442
- connectionFingerprint
1443
- });
1444
- const boundThreadId = requireBoundThread(adopted);
1445
- const baselineThread = boundThreadId === sourceThread.id ? sourceThread : await params.control.readThread(boundThreadId, true);
1446
- if (baselineThread.id !== boundThreadId) throw new Error("Codex app-server returned a different thread than requested");
1447
- params.onContinued?.({
1448
- connectionFingerprint,
1449
- ...codexUpstreamBaseline(baselineThread, boundCatalogSessionId)
1450
- });
1451
- return {
1452
- sessionKey: adopted.key,
1453
- disposition: "forked"
1454
- };
1455
- }
1456
- /** Creates one locked OpenClaw branch whose first harness run forks the Codex source. */
1457
- async function continueLocalCodexSession(params) {
1458
- const sourceKey = sessionCatalogAdoptedSourceKey(params.hostId ?? "gateway:local", params.threadId);
1459
- const operationKey = sessionCatalogAdoptedSourceKey(params.agentId, sourceKey);
1460
- const current = continueOperations.get(operationKey);
1461
- if (current) return await current;
1462
- const run = async (control) => await continueLocalCodexSessionInner({
1463
- ...params,
1464
- control
1465
- });
1466
- const operation = runSessionActionExclusive(sourceKey, async () => params.control.withPinnedConnection(run));
1467
- continueOperations.set(operationKey, operation);
1468
- try {
1469
- return await operation;
1470
- } finally {
1471
- if (continueOperations.get(operationKey) === operation) continueOperations.delete(operationKey);
1472
- }
1473
- }
1474
- //#endregion
1475
- //#region extensions/codex/src/session-catalog-archive.ts
1476
- async function assertNoPendingSupervisionBranch(params) {
1477
- const adoptedEntries = [params.agentId, ...listAgentIds(params.config).filter((agentId) => agentId !== params.agentId)].flatMap((agentId) => params.runtime.agent.session.listSessionEntries({
1478
- agentId,
1479
- readOnly: true
1480
- })).filter((candidate) => isAdoptionSessionKeyForThread(candidate.sessionKey, params.threadId, params.sourceHomeId) || params.sourceHomeId !== void 0 && params.allowLegacy === true && isAdoptionSessionKeyForThread(candidate.sessionKey, params.threadId));
1481
- for (const adopted of adoptedEntries) {
1482
- if (adopted.entry.initializationPending === true) throw new CatalogParamsError("Codex session cannot be archived while its OpenClaw branch is initializing");
1483
- const sessionId = adopted.entry.sessionId?.trim();
1484
- if (!sessionId) continue;
1485
- const binding = await params.bindingStore.read(sessionBindingIdentity({
1486
- sessionId,
1487
- sessionKey: adopted.sessionKey,
1488
- config: params.config
1489
- }));
1490
- 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");
1491
- }
1492
- }
1493
- /** Archives one inactive Gateway-local Codex thread after a fresh status read. */
1494
- async function archiveLocalCodexSession(params) {
1495
- return await runSessionActionExclusive(sessionCatalogAdoptedSourceKey(params.hostId ?? "gateway:local", params.threadId), async () => {
1496
- return await params.bindingStore.withThreadArchiveFence(async () => {
1497
- const run = async (control) => {
1498
- await assertNoPendingSupervisionBranch(params);
1499
- await control.requireEligibleThread(params.threadId);
1500
- const thread = await control.readThread(params.threadId, false);
1501
- if (thread.id !== params.threadId) throw new Error("Codex app-server returned a different thread than requested");
1502
- requireIdleThread(thread, "archive");
1503
- if (await params.bindingStore.hasOtherThreadOwner(params.threadId)) throw new CatalogParamsError("Codex session cannot be archived while it is attached to an OpenClaw session");
1504
- await assertCodexArchiveDescendantsUnowned({
1505
- bindingStore: params.bindingStore,
1506
- threadId: params.threadId,
1507
- listPage: (request) => control.listDescendantPage(request),
1508
- assertDescendantIdle: async (descendantThreadId) => {
1509
- const descendant = await control.readThread(descendantThreadId, false);
1510
- if (descendant.id !== descendantThreadId) throw new Error("Codex app-server returned a different descendant than requested");
1511
- requireIdleThread(descendant, "archive");
1512
- }
1513
- });
1514
- await control.archiveThread(params.threadId);
1515
- return { archived: true };
1516
- };
1517
- return await params.control.withPinnedConnection(run);
1518
- });
1519
- });
1520
- }
1521
- //#endregion
1522
- //#region extensions/codex/src/session-catalog-create.ts
1523
- const CODEX_AGENT_RUNTIME_ID = "codex";
1524
- const CODEX_CATALOG_DEFAULT_MODEL_REF = "openai/gpt-5.6-sol";
1525
- function resolveCodexCatalogCreateSession(config, requestedAgentId) {
1526
- if (!config) return;
1527
- const agentId = requestedAgentId ?? resolveDefaultAgentId(config);
1528
- const defaultModel = resolveDefaultModelForAgent({
1529
- cfg: config,
1530
- agentId
1531
- });
1532
- return "error" in resolveAllowedModelRef({
1533
- cfg: config,
1534
- catalog: [],
1535
- raw: CODEX_CATALOG_DEFAULT_MODEL_REF,
1536
- defaultProvider: defaultModel.provider,
1537
- defaultModel: defaultModel.model,
1538
- agentId
1539
- }) ? void 0 : {
1540
- model: CODEX_CATALOG_DEFAULT_MODEL_REF,
1541
- agentRuntime: CODEX_AGENT_RUNTIME_ID
1542
- };
1543
- }
1544
- //#endregion
1545
- //#region extensions/codex/src/session-catalog-node-continue.ts
1546
- const CODEX_NODE_CONTINUE_COMMANDS = [
1547
- CODEX_APP_SERVER_THREADS_LIST_COMMAND,
1548
- CODEX_APP_SERVER_THREAD_TURNS_LIST_COMMAND,
1549
- CODEX_CLI_SESSION_RESUME_COMMAND
1550
- ];
1551
- const NODE_CATALOG_LIST_RESPONSE_TIMEOUT_MS = 8e3;
1552
- const continueNodeAdoption = createSessionCatalogAdoptionCoordinator();
1553
- function nodeLabel(node) {
1554
- return node.displayName?.trim() || node.remoteIp?.trim() || node.nodeId;
1555
- }
1556
- function compareNodeLabels(left, right) {
1557
- const leftLabel = nodeLabel(left);
1558
- const rightLabel = nodeLabel(right);
1559
- if (leftLabel < rightLabel) return -1;
1560
- if (leftLabel > rightLabel) return 1;
1561
- return 0;
1562
- }
1563
- function canContinueCodexOnNode(node) {
1564
- return node.connected === true && CODEX_NODE_CONTINUE_COMMANDS.every((command) => node.commands?.includes(command) === true && node.invocableCommands?.includes(command) === true);
1565
- }
1566
- async function listPairedNode(params) {
1567
- const hostId = `node:${params.node.nodeId}`;
1568
- const common = {
1569
- hostId,
1570
- label: nodeLabel(params.node),
1571
- kind: "node",
1572
- nodeId: params.node.nodeId,
1573
- canContinueCodex: canContinueCodexOnNode(params.node),
1574
- ...params.terminalCapabilities
1575
- };
1576
- if (params.node.connected !== true) {
1577
- const host = {
1578
- ...common,
1579
- connected: false,
1580
- sessions: [],
1581
- error: {
1582
- code: "NODE_OFFLINE",
1583
- message: "Paired node is offline"
1584
- }
1585
- };
1586
- params.onHost?.(host);
1587
- return host;
1588
- }
1589
- if (!params.node.commands?.includes("codex.appServer.threads.list.v1")) {
1590
- const host = {
1591
- ...common,
1592
- connected: true,
1593
- sessions: []
1594
- };
1595
- params.onHost?.(host);
1596
- return host;
1597
- }
1598
- const eventualHost = Promise.resolve().then(async () => {
1599
- const page = filterCatalogPageByTitle(parseCatalogPage(unwrapNodeInvokePayload(await params.runtime.nodes.invoke({
1600
- nodeId: params.node.nodeId,
1601
- command: CODEX_APP_SERVER_THREADS_LIST_COMMAND,
1602
- params: {
1603
- agentId: params.agentId,
1604
- cursor: params.query.cursors?.[hostId],
1605
- limit: params.query.limitPerHost,
1606
- searchTerm: params.query.search
1607
- },
1608
- timeoutMs: NODE_INVOKE_TIMEOUT_MS,
1609
- scopes: ["operator.write"]
1610
- }))), params.query.search);
1611
- return {
1612
- ...common,
1613
- connected: true,
1614
- ...page,
1615
- sessions: page.sessions.map((session) => {
1616
- const adopted = params.adoptedSessions.get(sessionCatalogAdoptedSourceKey(hostId, session.threadId));
1617
- return adopted ? Object.assign({}, session, { sessionKey: adopted.key }) : session;
1618
- })
1619
- };
1620
- }).catch((error) => ({
1621
- ...common,
1622
- connected: true,
1623
- sessions: [],
1624
- error: catalogError("NODE_INVOKE_FAILED", error)
1625
- }));
1626
- if (params.onHost) eventualHost.then(params.onHost).catch(() => void 0);
1627
- try {
1628
- return await withTimeout(eventualHost, NODE_CATALOG_LIST_RESPONSE_TIMEOUT_MS, "paired node Codex session catalog timed out");
1629
- } catch (error) {
1630
- return {
1631
- ...common,
1632
- connected: true,
1633
- sessions: [],
1634
- error: catalogError("NODE_INVOKE_FAILED", error)
1635
- };
1636
- }
1637
- }
1638
- async function requireNodeForCodexContinue(params) {
1639
- const nodeId = params.hostId.slice(5).trim();
1640
- if (!nodeId || params.hostId !== `node:${nodeId}`) throw new CatalogParamsError("Codex session catalog hostId is invalid");
1641
- const node = (await params.runtime.nodes.list()).nodes.find((candidate) => candidate.nodeId === nodeId);
1642
- if (!node || !canContinueCodexOnNode(node)) throw new CatalogParamsError("paired node does not permit Codex session continuation");
1643
- return {
1644
- node,
1645
- nodeId
1646
- };
1647
- }
1648
- async function resolveNodeCodexRecord(params) {
1649
- let cursor;
1650
- const seenCursors = /* @__PURE__ */ new Set();
1651
- for (let pageIndex = 0; pageIndex < 100; pageIndex += 1) {
1652
- const page = parseCatalogPage(unwrapNodeInvokePayload(await params.runtime.nodes.invoke({
1653
- nodeId: params.nodeId,
1654
- command: CODEX_APP_SERVER_THREADS_LIST_COMMAND,
1655
- params: {
1656
- agentId: params.agentId,
1657
- limit: 100,
1658
- ...cursor ? { cursor } : {}
1659
- },
1660
- timeoutMs: NODE_INVOKE_TIMEOUT_MS,
1661
- scopes: ["operator.write"]
1662
- })));
1663
- const record = page.sessions.find((candidate) => candidate.threadId === params.threadId);
1664
- if (record) return record;
1665
- const nextCursor = page.nextCursor?.trim();
1666
- if (!nextCursor) break;
1667
- if (seenCursors.has(nextCursor)) throw new CatalogParamsError("Codex session eligibility could not be verified");
1668
- seenCursors.add(nextCursor);
1669
- cursor = nextCursor;
1670
- }
1671
- throw new CatalogParamsError("Codex session is unavailable on the paired node");
1672
- }
1673
- function requireContinuableNodeRecord(record) {
1674
- if (record.archived) throw new CatalogParamsError("Codex session is archived on the paired node");
1675
- if (!isInteractiveThreadSource(record.source)) throw new CatalogParamsError("Codex session is not a non-archived interactive Codex session");
1676
- if (record.status === "idle" || record.status === "notLoaded") return;
1677
- if (record.status === "active") throw new CatalogParamsError("Codex session is active on the paired node; wait for it to finish before continuing");
1678
- throw new CatalogParamsError("Codex session cannot be continued in its current state");
1679
- }
1680
- async function readNodeCodexHistory(params) {
1681
- const page = parseTranscriptPage(unwrapNodeInvokePayload(await params.runtime.nodes.invoke({
1682
- nodeId: params.nodeId,
1683
- command: CODEX_APP_SERVER_THREAD_TURNS_LIST_COMMAND,
1684
- params: {
1685
- agentId: params.agentId,
1686
- threadId: params.record.threadId,
1687
- limit: 50
1688
- },
1689
- timeoutMs: NODE_INVOKE_TIMEOUT_MS,
1690
- scopes: ["operator.write"]
1691
- })));
1692
- const thread = {
1693
- id: params.record.threadId,
1694
- createdAt: params.record.createdAt ?? 0,
1695
- modelProvider: params.record.modelProvider ?? "openai",
1696
- projectId: null,
1697
- turns: page.data.toReversed()
1698
- };
1699
- return {
1700
- thread,
1701
- throughTurnId: codexLastTerminalTurnId(thread, (value) => boundedCatalogString(value, 256)) ?? null
1702
- };
1703
- }
1704
- async function continueNodeCodexSessionInner(params) {
1705
- const { nodeId } = await requireNodeForCodexContinue({
1706
- runtime: params.api.runtime,
1707
- hostId: params.hostId
1708
- });
1709
- const record = await resolveNodeCodexRecord({
1710
- agentId: params.agentId,
1711
- runtime: params.api.runtime,
1712
- nodeId,
1713
- threadId: params.threadId
1714
- });
1715
- requireContinuableNodeRecord(record);
1716
- const existing = findNodeAdoptedSessionEntry({
1717
- agentId: params.agentId,
1718
- config: params.config,
1719
- runtime: params.api.runtime,
1720
- hostId: params.hostId,
1721
- threadId: params.threadId,
1722
- includeInitializing: true
1723
- });
1724
- let adopted;
1725
- let disposition;
1726
- if (existing) {
1727
- adopted = existing;
1728
- disposition = "existing";
1729
- } else {
1730
- const history = await readNodeCodexHistory({
1731
- agentId: params.agentId,
1732
- runtime: params.api.runtime,
1733
- nodeId,
1734
- record
1735
- });
1736
- adopted = await createOrReuseNodeAdoptedSession({
1737
- agentId: params.agentId,
1738
- api: params.api,
1739
- config: params.config,
1740
- hostId: params.hostId,
1741
- nodeId,
1742
- record,
1743
- history
1744
- });
1745
- disposition = "forked";
1746
- }
1747
- const marker = nodeSessionMarker({
1748
- hostId: params.hostId,
1749
- threadId: params.threadId,
1750
- nodeId
1751
- });
1752
- return {
1753
- sessionKey: adopted.key,
1754
- disposition,
1755
- conversationBinding: {
1756
- summary: "Continue this Codex session on its paired node.",
1757
- detachHint: "Start a new chat to leave the paired-node Codex session.",
1758
- data: createCodexCliNodeConversationBindingData({
1759
- nodeId,
1760
- sessionId: params.threadId,
1761
- agentId: adopted.agentId,
1762
- cwd: record.cwd
1763
- })
1764
- },
1765
- afterConversationBound: async () => await finalizeNodeAdoptedSession({
1766
- api: params.api,
1767
- adopted,
1768
- marker
1769
- })
1770
- };
1771
- }
1772
- async function continueNodeCodexSession(params) {
1773
- if (params.clientScopes?.includes("operator.admin") !== true) throw new CatalogParamsError("continuing a paired-node Codex session requires operator.admin");
1774
- const nodeId = params.hostId.slice(5).trim();
1775
- if (!nodeId || params.hostId !== `node:${nodeId}`) throw new CatalogParamsError("Codex session catalog hostId is invalid");
1776
- const agentId = resolveSessionAgentIdsStrict({
1777
- config: params.config,
1778
- agentId: params.agentId
1779
- }).sessionAgentId;
1780
- const sourceKey = sessionCatalogAdoptedSourceKey(`node:${nodeId}`, params.threadId);
1781
- const operationKey = sessionCatalogAdoptedSourceKey(agentId, sourceKey);
1782
- return await continueNodeAdoption({
1783
- sourceKey: operationKey,
1784
- findExisting: () => void 0,
1785
- create: () => runSessionActionExclusive(sourceKey, async () => continueNodeCodexSessionInner({
1786
- ...params,
1787
- agentId
1788
- })),
1789
- complete: async (continued) => continued
1790
- });
1791
- }
1792
- //#endregion
1793
- //#region extensions/codex/src/session-catalog-terminal.ts
1794
- const CODEX_TERMINAL_RESUME_COMMAND = "codex.terminal.resume.v1";
1795
- const CODEX_TERMINAL_START_COMMAND = "codex.terminal.start.v1";
1796
- function createCodexTerminalStartNodeHostCommand() {
1797
- return {
1798
- command: CODEX_TERMINAL_START_COMMAND,
1799
- cap: CODEX_APP_SERVER_THREADS_CAPABILITY,
1800
- dangerous: false,
1801
- duplex: true,
1802
- isAvailable: ({ env }) => Boolean(resolveNodeHostExecutable("codex", {
1803
- env,
1804
- strategy: "direct"
1805
- })),
1806
- handle: async (paramsJSON, io) => {
1807
- if (!io) throw new Error("Codex terminal command requires duplex transport");
1808
- const params = decodeNodePtyStartParams(paramsJSON);
1809
- const resolution = resolveNodeHostExecutable("codex", { strategy: "direct" });
1810
- if (!resolution) throw new Error("Codex CLI is unavailable; install codex on this node and reconnect");
1811
- return JSON.stringify(await runNodePtyCommand({
1812
- file: resolution.executable,
1813
- args: params.initialMessage !== void 0 ? ["--", params.initialMessage] : [],
1814
- cwd: params.cwd,
1815
- requiredCwd: true,
1816
- cols: params.cols,
1817
- rows: params.rows
1818
- }, io));
1819
- }
1820
- };
1821
- }
1822
- function resolveCodexCatalogTerminalHome(sources) {
1823
- const runtimeConfig = sources.getRuntimeConfig();
1824
- if (!runtimeConfig) throw new Error("OpenClaw runtime config is unavailable");
1825
- const agentDir = sources.source?.agentDir ?? (sources.agentId ? resolveAgentDir$1(runtimeConfig, sources.agentId) : resolveDefaultAgentDir(runtimeConfig));
1826
- const startOptions = sources.source?.appServer.start ?? resolveCodexSupervisionAppServerRuntimeOptions({ pluginConfig: sources.getPluginConfig() }).start;
1827
- return resolveCodexAppServerLocalHomeDir(startOptions, agentDir);
1828
- }
1829
- function resolveLocalCodexTerminalExecutable(env = process.env) {
1830
- return resolveLocalCodexTerminalResolution(env)?.executable;
1831
- }
1832
- function resolveLocalCodexTerminalResolution(env = process.env) {
1833
- return resolveNodeHostExecutable("codex", {
1834
- env,
1835
- pathEnv: env.PATH ?? env.Path ?? "",
1836
- strategy: "fallback"
1837
- });
1838
- }
1839
- function codexNodeTerminalCapability(node) {
1840
- const commands = node.invocableCommands ?? node.commands;
1841
- return {
1842
- canOpenTerminalCodex: node.connected === true && commands?.includes("codex.terminal.resume.v1") === true,
1843
- canStartTerminal: node.connected === true && node.invocableCommands?.includes("codex.terminal.start.v1") === true
1844
- };
1845
- }
1846
- function createCodexTerminalNodeHostCommand(bindRequest, configSources) {
1847
- return {
1848
- command: CODEX_TERMINAL_RESUME_COMMAND,
1849
- cap: CODEX_APP_SERVER_THREADS_CAPABILITY,
1850
- dangerous: false,
1851
- duplex: true,
1852
- isAvailable: ({ env }) => Boolean(resolveNodeHostExecutable("codex", {
1853
- env,
1854
- pathEnv: env.PATH ?? env.Path ?? "",
1855
- strategy: "direct"
1856
- })),
1857
- handle: async (paramsJSON, io) => {
1858
- if (!io) throw new Error("Codex terminal command requires duplex transport");
1859
- const request = bindRequest(paramsJSON);
1860
- const resume = decodeNodePtyResumeParams(request.paramsJSON, (value) => {
1861
- 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");
1862
- return value;
1863
- });
1864
- const record = await request.control.requireEligibleThread(resume.threadId);
1865
- const resolution = resolveNodeHostExecutable("codex", {
1866
- env: process.env,
1867
- pathEnv: process.env.PATH ?? process.env.Path ?? "",
1868
- strategy: "direct"
1869
- });
1870
- if (!resolution) throw new Error("Codex CLI is unavailable");
1871
- return JSON.stringify(await runNodePtyCommand({
1872
- file: resolution.executable,
1873
- args: ["resume", resume.threadId],
1874
- ...record.cwd ? { cwd: record.cwd } : {},
1875
- env: { CODEX_HOME: resolveCodexCatalogTerminalHome({
1876
- ...configSources,
1877
- agentId: request.agentId
1878
- }) },
1879
- cols: resume.cols,
1880
- rows: resume.rows
1881
- }, io));
1882
- }
1883
- };
1884
- }
1885
- async function resolveNodeCatalogEligibleThread(params) {
1886
- let cursor;
1887
- const seenCursors = /* @__PURE__ */ new Set();
1888
- for (let pageIndex = 0; pageIndex < 100; pageIndex += 1) {
1889
- const raw = await params.runtime.nodes.invoke({
1890
- nodeId: params.nodeId,
1891
- command: CODEX_APP_SERVER_THREADS_LIST_COMMAND,
1892
- params: {
1893
- agentId: params.agentId,
1894
- limit: 100,
1895
- ...cursor ? { cursor } : {}
1896
- },
1897
- timeoutMs: NODE_INVOKE_TIMEOUT_MS,
1898
- scopes: ["operator.write"]
1899
- });
1900
- const page = params.parseCatalogPage(unwrapNodeInvokePayload(raw));
1901
- const record = page.sessions.find((candidate) => candidate.threadId === params.threadId);
1902
- if (record) {
1903
- if (isInteractiveThreadSource(record.source)) return record;
1904
- break;
1905
- }
1906
- const nextCursor = page.nextCursor?.trim();
1907
- if (!nextCursor || seenCursors.has(nextCursor)) break;
1908
- seenCursors.add(nextCursor);
1909
- cursor = nextCursor;
1910
- }
1911
- throw new CatalogParamsError("Codex session is not a non-archived interactive Codex session");
1912
- }
1913
- async function openCodexCatalogTerminal(params) {
1914
- const title = `codex resume ${params.threadId.slice(0, 8)}…`;
1915
- if (params.hostId === "gateway:local" || params.hostId.startsWith(`gateway:local:`)) {
1916
- const record = await params.control.requireEligibleThread(params.threadId);
1917
- const resolution = resolveLocalCodexTerminalResolution();
1918
- if (!resolution) throw new CatalogParamsError("Codex CLI is unavailable");
1919
- return {
1920
- kind: "local",
1921
- argv: [
1922
- resolution.executable,
1923
- "resume",
1924
- params.threadId
1925
- ],
1926
- ...record.cwd ? { cwd: record.cwd } : {},
1927
- env: { CODEX_HOME: resolveCodexCatalogTerminalHome(params) },
1928
- ...resolution.pathEnv ? { pathEnv: resolution.pathEnv } : {},
1929
- title
1930
- };
1931
- }
1932
- if (!params.hostId.startsWith("node:")) throw new CatalogParamsError("hostId is invalid");
1933
- const nodeId = params.hostId.slice(5);
1934
- if (!(await params.api.runtime.nodes.list()).nodes.find((candidate) => {
1935
- const commands = candidate.invocableCommands ?? candidate.commands;
1936
- return candidate.nodeId === nodeId && candidate.connected === true && commands?.includes("codex.appServer.threads.list.v1") === true && commands.includes("codex.terminal.resume.v1");
1937
- })) throw new CatalogParamsError("paired-node Codex terminal is unavailable");
1938
- const record = await resolveNodeCatalogEligibleThread({
1939
- agentId: params.agentId,
1940
- runtime: params.api.runtime,
1941
- nodeId,
1942
- threadId: params.threadId,
1943
- parseCatalogPage: params.parseCatalogPage
1944
- });
1945
- return {
1946
- kind: "node",
1947
- nodeId,
1948
- command: CODEX_TERMINAL_RESUME_COMMAND,
1949
- paramsJSON: JSON.stringify({
1950
- agentId: params.agentId,
1951
- threadId: params.threadId
1952
- }),
1953
- ...record.cwd ? { cwd: record.cwd } : {},
1954
- title
1955
- };
1956
- }
1957
- async function startCodexCatalogTerminal(params) {
1958
- if (params.nodeId) return {
1959
- kind: "node",
1960
- nodeId: params.nodeId,
1961
- command: CODEX_TERMINAL_START_COMMAND,
1962
- paramsJSON: JSON.stringify({
1963
- cwd: params.cwd,
1964
- initialMessage: params.initialMessage
1965
- }),
1966
- cwd: params.cwd,
1967
- title: "codex"
1968
- };
1969
- const resolution = resolveLocalCodexTerminalResolution();
1970
- if (!resolution) throw new CatalogParamsError("Codex CLI is unavailable; install Codex or add codex to PATH, then try again");
1971
- return {
1972
- kind: "local",
1973
- argv: [resolution.executable, ...params.initialMessage !== void 0 ? ["--", params.initialMessage] : []],
1974
- cwd: params.cwd,
1975
- env: { CODEX_HOME: resolveCodexCatalogTerminalHome(params) },
1976
- ...resolution.pathEnv ? { pathEnv: resolution.pathEnv } : {},
1977
- title: "codex"
1978
- };
1979
- }
1980
- //#endregion
1981
- //#region extensions/codex/src/session-catalog-listing.ts
1982
- async function listVisiblePage(params) {
1983
- const excluded = params.excludedThreadIds;
1984
- const sessions = [];
1985
- let cursor = params.cursor;
1986
- let nextCursor;
1987
- let backwardsCursor;
1988
- const seenCursors = /* @__PURE__ */ new Set();
1989
- for (let pageIndex = 0; pageIndex < 20; pageIndex += 1) {
1990
- let excludedFromPage = false;
1991
- const rawPage = await params.control.listPage({
1992
- limit: params.limit - sessions.length,
1993
- ...cursor ? { cursor } : {},
1994
- ...params.searchTerm ? { searchTerm: params.searchTerm } : {},
1995
- ...params.cwd ? { cwd: params.cwd } : {}
1996
- });
1997
- const page = filterCatalogPageByTitle(parseCatalogPage(rawPage), params.searchTerm);
1998
- if (pageIndex === 0) backwardsCursor = page.backwardsCursor;
1999
- for (const managed of rawPage.managedThreads ?? []) {
2000
- excludedFromPage = true;
2001
- await params.onExcludedThread?.(managed);
2002
- }
2003
- for (const session of page.sessions) {
2004
- if (!excluded?.has(session.threadId)) {
2005
- sessions.push(session);
2006
- continue;
2007
- }
2008
- excludedFromPage = true;
2009
- await params.onExcludedThread?.({ threadId: session.threadId });
2010
- }
2011
- nextCursor = page.nextCursor;
2012
- if (!nextCursor || sessions.length >= params.limit || !excludedFromPage) break;
2013
- if (seenCursors.has(nextCursor)) throw new Error("Codex session catalog returned a repeated exclusion cursor");
2014
- seenCursors.add(nextCursor);
2015
- cursor = nextCursor;
2016
- }
2017
- return {
2018
- sessions: sessions.slice(0, params.limit),
2019
- ...nextCursor ? { nextCursor } : {},
2020
- ...backwardsCursor ? { backwardsCursor } : {}
2021
- };
2022
- }
2023
- async function listGatewayHost(params) {
2024
- const hostId = params.source?.hostId ?? "gateway:local";
2025
- const label = params.source?.label ?? "Local Codex";
2026
- const sourceHomeId = params.source?.sourceHomeId ?? "gateway:local";
2027
- try {
2028
- const page = await listVisiblePage({
2029
- control: params.control,
2030
- cursor: params.query.cursors?.[hostId],
2031
- excludedThreadIds: params.excludedThreadIds,
2032
- limit: params.query.limitPerHost,
2033
- onExcludedThread: params.onExcludedThread,
2034
- searchTerm: params.query.search
2035
- });
2036
- const adoptedSessions = await listAdoptedSessionEntries({
2037
- agentId: params.agentId,
2038
- bindingStore: params.bindingStore,
2039
- config: params.config,
2040
- runtime: params.runtime,
2041
- sessionEntries: params.sessionEntries
2042
- });
2043
- return {
2044
- hostId,
2045
- label,
2046
- kind: "gateway",
2047
- connected: true,
2048
- ...page,
2049
- sessions: page.sessions.map((session) => {
2050
- const adopted = adoptedSessions.get(sessionCatalogAdoptedSourceKey(sourceHomeId, session.threadId)) ?? (hostId === "gateway:local" ? adoptedSessions.get(sessionCatalogAdoptedSourceKey("gateway:local", session.threadId)) : void 0);
2051
- const sourced = params.source ? Object.assign({}, session, { sourceHomeId: params.source.sourceHomeId }) : session;
2052
- return adopted ? Object.assign({}, sourced, { sessionKey: adopted.key }) : sourced;
2053
- })
2054
- };
2055
- } catch (error) {
2056
- return {
2057
- hostId,
2058
- label,
2059
- kind: "gateway",
2060
- connected: false,
2061
- sessions: [],
2062
- error: catalogError("APP_SERVER_UNAVAILABLE", error)
2063
- };
2064
- }
2065
- }
2066
- /** Lists Gateway-local and paired-node Codex sessions with per-host failures. */
2067
- async function listCodexSessionCatalog(params) {
2068
- const agentId = resolveSessionAgentIdsStrict({
2069
- config: params.config ?? {},
2070
- agentId: params.agentId
2071
- }).sessionAgentId;
2072
- const query = readGatewayParams(params.query);
2073
- const requestedHostIds = query.hostIds ? new Set(query.hostIds) : void 0;
2074
- const localSources = params.localHomes?.filter((source) => !requestedHostIds || requestedHostIds.has(source.hostId)) ?? (params.includeLocal !== false && (!requestedHostIds || requestedHostIds.has("gateway:local")) ? [void 0] : []);
2075
- const managedThreads = await params.bindingStore.managedThreads?.snapshot();
2076
- const fallbackSource = params.control.homesForAgent(agentId)[0];
2077
- const localHosts = localSources.map((source) => (() => {
2078
- const ownershipSource = source ?? fallbackSource;
2079
- const managedThreadIds = ownershipSource ? managedThreads?.get(ownershipSource.sourceHomeId) : void 0;
2080
- return listGatewayHost({
2081
- agentId,
2082
- bindingStore: params.bindingStore,
2083
- config: params.config,
2084
- control: params.control.forRequest(agentId, ownershipSource),
2085
- query,
2086
- runtime: params.runtime,
2087
- sessionEntries: params.sessionEntries,
2088
- excludedThreadIds: managedThreadIds,
2089
- ...ownershipSource && params.bindingStore.managedThreads ? { onExcludedThread: async ({ threadId, rolloutPath }) => {
2090
- if (!managedThreadIds?.has(threadId)) await params.bindingStore.managedThreads?.mark({
2091
- sourceHomeId: ownershipSource.sourceHomeId,
2092
- threadId,
2093
- ...rolloutPath ? { rolloutPath } : {}
2094
- });
2095
- } } : {},
2096
- ...source ? { source } : {}
2097
- });
2098
- })());
2099
- for (const host of localHosts) if (params.onHost) host.then(params.onHost).catch(() => void 0);
2100
- if (!(!requestedHostIds || query.hostIds?.some((hostId) => hostId.startsWith("node:")))) return { hosts: await Promise.all(localHosts) };
2101
- let nodes;
2102
- try {
2103
- nodes = (await (params.listNodes?.() ?? params.runtime.nodes.list())).nodes.filter((node) => node.gatewayLocal !== true && (node.commands?.includes("codex.appServer.threads.list.v1") || codexNodeTerminalCapability(node).canStartTerminal) && (!requestedHostIds || requestedHostIds.has(`node:${node.nodeId}`))).slice(0, 100 - localHosts.length);
2104
- } catch (error) {
2105
- const registryHost = {
2106
- hostId: "node:registry",
2107
- label: "Paired nodes",
2108
- kind: "node",
2109
- connected: false,
2110
- canStartTerminal: false,
2111
- sessions: [],
2112
- error: catalogError("NODE_LIST_FAILED", error)
2113
- };
2114
- params.onHost?.(registryHost);
2115
- return { hosts: [...await Promise.all(localHosts), registryHost] };
2116
- }
2117
- const adoptedNodeSessions = listNodeAdoptedSessionEntries({
2118
- agentId,
2119
- config: params.config,
2120
- runtime: params.runtime,
2121
- sessionEntries: params.sessionEntries
2122
- });
2123
- const nodeHosts = nodes.toSorted(compareNodeLabels).map((node) => listPairedNode({
2124
- agentId,
2125
- runtime: params.runtime,
2126
- node,
2127
- query,
2128
- adoptedSessions: adoptedNodeSessions,
2129
- terminalCapabilities: codexNodeTerminalCapability(node),
2130
- ...params.onHost ? { onHost: params.onHost } : {}
2131
- }));
2132
- return { hosts: await Promise.all([...localHosts, ...nodeHosts]) };
2133
- }
2134
- /** Builds the node-local read-only Codex app-server catalog command. */
2135
- function createCodexSessionCatalogNodeHostCommands(controlFactory, configSources, bindingStore) {
2136
- const bindRequest = (paramsJSON) => {
2137
- const parsed = parseJsonParams(paramsJSON);
2138
- if (!isRecord(parsed)) throw new CatalogParamsError("Codex session catalog parameters must be an object");
2139
- const requestedAgentId = readBoundedOptionalString(parsed, "agentId", 256);
2140
- const config = configSources.getRuntimeConfig() ?? {};
2141
- const agentId = resolveSessionAgentIdsStrict({
2142
- config,
2143
- agentId: requestedAgentId
2144
- }).sessionAgentId;
2145
- if (!listAgentIds(config).includes(agentId)) throw new CatalogParamsError(`unknown Codex session catalog agent: ${agentId}`);
2146
- const request = { ...parsed };
2147
- delete request.agentId;
2148
- const source = controlFactory.homesForAgent(agentId)[0];
2149
- return {
2150
- agentId,
2151
- control: controlFactory.forRequest(agentId, source),
2152
- sourceHomeId: source?.sourceHomeId,
2153
- params: request,
2154
- paramsJSON: JSON.stringify(request)
2155
- };
2156
- };
2157
- return [
2158
- {
2159
- command: CODEX_APP_SERVER_THREADS_LIST_COMMAND,
2160
- cap: CODEX_APP_SERVER_THREADS_CAPABILITY,
2161
- dangerous: false,
2162
- handle: async (paramsJSON) => {
2163
- const request = bindRequest(paramsJSON);
2164
- const pageParams = readPageParams(request.params);
2165
- try {
2166
- const managedThreads = await bindingStore?.managedThreads?.snapshot();
2167
- const sourceHomeId = request.sourceHomeId;
2168
- const managedThreadIds = sourceHomeId ? managedThreads?.get(sourceHomeId) : void 0;
2169
- const page = await listVisiblePage({
2170
- control: request.control,
2171
- cursor: pageParams.cursor,
2172
- cwd: pageParams.cwd,
2173
- excludedThreadIds: managedThreadIds,
2174
- limit: pageParams.limit,
2175
- ...sourceHomeId && bindingStore?.managedThreads ? { onExcludedThread: async ({ threadId, rolloutPath }) => {
2176
- if (!managedThreadIds?.has(threadId)) await bindingStore.managedThreads?.mark({
2177
- sourceHomeId,
2178
- threadId,
2179
- ...rolloutPath ? { rolloutPath } : {}
2180
- });
2181
- } } : {},
2182
- searchTerm: pageParams.searchTerm
2183
- });
2184
- return JSON.stringify(page);
2185
- } catch {
2186
- throw new Error("Codex app-server catalog is unavailable");
2187
- }
2188
- }
2189
- },
2190
- {
2191
- command: CODEX_APP_SERVER_THREAD_TURNS_LIST_COMMAND,
2192
- cap: CODEX_APP_SERVER_THREADS_CAPABILITY,
2193
- dangerous: false,
2194
- handle: async (paramsJSON) => {
2195
- const request = bindRequest(paramsJSON);
2196
- const action = readNodeTranscriptParams(request.params);
2197
- try {
2198
- await request.control.requireEligibleThread(action.threadId);
2199
- const page = parseTranscriptPage(await request.control.listTurnPage({
2200
- threadId: action.threadId,
2201
- limit: action.limit,
2202
- sortDirection: "desc",
2203
- itemsView: "full",
2204
- ...action.cursor ? { cursor: action.cursor } : {}
2205
- }));
2206
- return JSON.stringify(page);
2207
- } catch (error) {
2208
- if (error instanceof CatalogParamsError) throw error;
2209
- throw new Error("Codex app-server transcript is unavailable", { cause: error });
2210
- }
2211
- }
2212
- },
2213
- createCodexTerminalNodeHostCommand(bindRequest, configSources),
2214
- createCodexTerminalStartNodeHostCommand()
2215
- ];
2216
- }
2217
- function readNodeTranscriptParams(value) {
2218
- if (!isRecord(value)) throw new CatalogParamsError("Codex session read parameters must be an object");
2219
- requireOnlyKeys(value, /* @__PURE__ */ new Set([
2220
- "threadId",
2221
- "cursor",
2222
- "limit"
2223
- ]));
2224
- const threadId = readBoundedOptionalString(value, "threadId", 256);
2225
- if (!threadId) throw new CatalogParamsError("threadId is required");
2226
- const cursor = readBoundedOptionalString(value, "cursor", MAX_CURSOR_LENGTH);
2227
- return {
2228
- threadId,
2229
- limit: readBoundedLimit(value.limit, "limit", 20, 50),
2230
- ...cursor ? { cursor } : {}
2231
- };
2232
- }
2233
- function readBoundedLimit(value, key, fallback, max) {
2234
- if (value === void 0) return fallback;
2235
- if (!Number.isInteger(value) || value < 1 || value > max) throw new CatalogParamsError(`${key} must be an integer from 1 to ${max}`);
2236
- return value;
2237
- }
2238
- function flattenTranscriptPageDesc(page) {
2239
- return page.data.flatMap((turn) => turn.items.toReversed());
2240
- }
2241
- /** Reads the persisted transcript for a Gateway-local or paired-node Codex session. */
2242
- async function readCodexSessionTranscript(params) {
2243
- if (params.source || params.hostId === "gateway:local") {
2244
- await params.control.requireEligibleThread(params.threadId);
2245
- const listParams = {
2246
- threadId: params.threadId,
2247
- limit: params.limit,
2248
- sortDirection: "desc",
2249
- itemsView: "full",
2250
- ...params.cursor ? { cursor: params.cursor } : {}
2251
- };
2252
- const page = parseTranscriptPage(await params.control.listTurnPage(listParams));
2253
- return {
2254
- hostId: params.hostId,
2255
- label: params.source?.label ?? "Local Codex",
2256
- threadId: params.threadId,
2257
- items: flattenTranscriptPageDesc(page),
2258
- ...page.nextCursor ? { nextCursor: page.nextCursor } : {},
2259
- ...page.backwardsCursor ? { backwardsCursor: page.backwardsCursor } : {}
2260
- };
2261
- }
2262
- const nodeId = params.hostId.slice(5);
2263
- 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"));
2264
- if (!node) throw new CatalogParamsError("paired-node Codex session host is offline or unavailable");
2265
- const page = parseTranscriptPage(unwrapNodeInvokePayload(await params.runtime.nodes.invoke({
2266
- nodeId,
2267
- command: CODEX_APP_SERVER_THREAD_TURNS_LIST_COMMAND,
2268
- params: {
2269
- agentId: params.agentId,
2270
- threadId: params.threadId,
2271
- limit: params.limit,
2272
- ...params.cursor ? { cursor: params.cursor } : {}
2273
- },
2274
- timeoutMs: NODE_INVOKE_TIMEOUT_MS,
2275
- scopes: ["operator.write"]
2276
- })));
2277
- return {
2278
- hostId: params.hostId,
2279
- label: nodeLabel(node),
2280
- threadId: params.threadId,
2281
- items: flattenTranscriptPageDesc(page),
2282
- ...page.nextCursor ? { nextCursor: page.nextCursor } : {},
2283
- ...page.backwardsCursor ? { backwardsCursor: page.backwardsCursor } : {}
2284
- };
2285
- }
2286
- //#endregion
2287
- //#region extensions/codex/src/session-catalog-transcript-item.ts
2288
- const CODEX_MESSAGE_TYPES = /* @__PURE__ */ new Map([
2289
- ["userMessage", "userMessage"],
2290
- ["agentMessage", "agentMessage"],
2291
- ["reasoning", "reasoning"]
2292
- ]);
2293
- const CODEX_TOOL_TYPES = /* @__PURE__ */ new Set([
2294
- "commandExecution",
2295
- "fileChange",
2296
- "mcpToolCall",
2297
- "dynamicToolCall",
2298
- "collabAgentToolCall",
2299
- "webSearch",
2300
- "imageView",
2301
- "imageGeneration"
2302
- ]);
2303
- function toGenericTranscriptItem(item) {
2304
- let type = CODEX_MESSAGE_TYPES.get(item.type);
2305
- if (!type && CODEX_TOOL_TYPES.has(item.type)) type = item.result !== void 0 || Boolean(item.aggregatedOutput) ? "toolResult" : "toolCall";
2306
- type ??= "other";
2307
- const fallback = item.title ?? item.name ?? item.tool ?? item.command ?? item.query ?? void 0;
2308
- const resultText = item.aggregatedOutput || (item.result === void 0 ? void 0 : JSON.stringify(item.result, null, 2));
2309
- const changesText = Array.isArray(item.changes) ? item.changes.map((change) => `${change.kind}: ${change.path}`).join("\n") || void 0 : void 0;
2310
- const text = item.type === "userMessage" ? projectCodexUserItemText(item) : item.text || resultText || changesText || fallback;
2311
- return {
2312
- id: item.id,
2313
- type,
2314
- ...text ? { text } : {},
2315
- raw: item
2316
- };
2317
- }
2318
- //#endregion
2319
- //#region extensions/codex/src/session-upstream-activity.ts
2320
- const CODEX_UPSTREAM_TURN_LIMIT = 100;
2321
- const CODEX_APP_SERVER_INVALID_REQUEST_CODE = -32600;
2322
- const CODEX_THREAD_NOT_LOADED_MESSAGE_PREFIX = "thread not loaded:";
2323
- function isCodexThreadGoneError(error) {
2324
- return error instanceof CodexAppServerRpcError && error.code === CODEX_APP_SERVER_INVALID_REQUEST_CODE && error.message.startsWith(CODEX_THREAD_NOT_LOADED_MESSAGE_PREFIX);
2325
- }
2326
- function readMarker(probe) {
2327
- if (!isRecord(probe.marker)) return;
2328
- const turnId = probe.marker.turnId;
2329
- if (turnId !== null && typeof turnId !== "string") return;
2330
- const count = probe.marker.userMessageCount;
2331
- if (count !== void 0 && (!Number.isSafeInteger(count) || count < 0)) return;
2332
- return {
2333
- turnId,
2334
- ...count === void 0 ? {} : { userMessageCount: count }
2335
- };
2336
- }
2337
- function upstreamConnectionFingerprint(probe) {
2338
- return isRecord(probe.upstreamRef) && typeof probe.upstreamRef.connectionFingerprint === "string" ? probe.upstreamRef.connectionFingerprint : void 0;
2339
- }
2340
- function classifyCodexUpstreamTurns(params) {
2341
- const marker = readMarker(params.probe);
2342
- if (!marker) return;
2343
- const newest = params.turns[0];
2344
- if (!newest?.id) return;
2345
- const markerIndex = marker.turnId === null ? -1 : params.turns.findIndex((turn) => turn.id === marker.turnId);
2346
- const candidateTurns = markerIndex < 0 ? params.turns : params.turns.slice(0, markerIndex + 1);
2347
- const newestUserMessageCount = countUserMessages(newest);
2348
- if (!(marker.turnId !== newest.id || marker.userMessageCount === void 0 || newestUserMessageCount > marker.userMessageCount)) return;
2349
- const ownTexts = new Set(params.probe.ownRecentUserTexts);
2350
- let humanTurns = 0;
2351
- let occurredAt;
2352
- for (const turn of candidateTurns) {
2353
- const userMessages = turn.items.filter((item) => item.type === "userMessage");
2354
- const alreadySeen = turn.id === marker.turnId ? marker.userMessageCount ?? userMessages.length : 0;
2355
- for (const item of userMessages.slice(alreadySeen)) {
2356
- const texts = normalizeUserMessageTexts(item);
2357
- if (ownTexts.has(texts.join(" ")) || texts.length > 1 && texts.every((text) => ownTexts.has(text))) continue;
2358
- humanTurns += 1;
2359
- if (occurredAt === void 0) {
2360
- const timestampSeconds = turn.completedAt ?? turn.startedAt;
2361
- occurredAt = typeof timestampSeconds === "number" && Number.isFinite(timestampSeconds) ? timestampSeconds * 1e3 : params.now ?? Date.now();
2362
- }
2363
- }
2364
- }
2365
- const activityId = `${newest.id}:${newestUserMessageCount}`;
2366
- return {
2367
- kind: "activity",
2368
- sessionKey: params.probe.sessionKey,
2369
- humanTurns,
2370
- nextMarker: {
2371
- turnId: newest.id,
2372
- userMessageCount: newestUserMessageCount
2373
- },
2374
- ...humanTurns > 0 ? {
2375
- occurredAt: occurredAt ?? params.now ?? Date.now(),
2376
- dedupeId: activityId
2377
- } : {}
2378
- };
2379
- }
2380
- function countUserMessages(turn) {
2381
- return turn.items.filter((item) => item.type === "userMessage").length;
2382
- }
2383
- function normalizeUserMessageTexts(item) {
2384
- const typed = item;
2385
- const contentTexts = typed.content?.filter((input) => input.type === "text").map((input) => input.text.trim().replace(/\s+/g, " ")).filter(Boolean);
2386
- return contentTexts?.length ? contentTexts : [(typed.text ?? "").trim().replace(/\s+/g, " ")];
2387
- }
2388
- async function checkCodexUpstreamActivity(probes, control, resolveThreadId = async (probe) => probe.threadId) {
2389
- return await control.withPinnedConnection(async (pinned) => {
2390
- const activities = [];
2391
- for (const probe of probes) {
2392
- const fingerprint = upstreamConnectionFingerprint(probe);
2393
- if (probe.upstreamKind !== "codex-app-server" || !fingerprint || fingerprint !== pinned.connectionFingerprint) continue;
2394
- try {
2395
- const threadId = await resolveThreadId(probe);
2396
- const page = await pinned.listTurnPage({
2397
- threadId,
2398
- limit: CODEX_UPSTREAM_TURN_LIMIT,
2399
- sortDirection: "desc",
2400
- itemsView: "full"
2401
- });
2402
- const marker = readMarker(probe);
2403
- if (page.data.length === 0 && marker) {
2404
- try {
2405
- await pinned.readThread(threadId, false);
2406
- } catch (error) {
2407
- if (isCodexThreadGoneError(error)) activities.push({
2408
- kind: "missing",
2409
- sessionKey: probe.sessionKey
2410
- });
2411
- }
2412
- continue;
2413
- }
2414
- const activity = classifyCodexUpstreamTurns({
2415
- probe,
2416
- turns: page.data
2417
- });
2418
- if (activity) activities.push(activity);
2419
- } catch {}
2420
- }
2421
- return activities;
2422
- });
2423
- }
2424
- function createChecker(params) {
2425
- const resolveThreadId = async (probe) => {
2426
- const config = params.getRuntimeConfig();
2427
- const sessionId = params.api.runtime.agent.session.getSessionEntry({
2428
- agentId: probe.agentId,
2429
- sessionKey: probe.sessionKey,
2430
- readConsistency: "latest"
2431
- })?.sessionId?.trim();
2432
- if (!sessionId) return probe.threadId;
2433
- const binding = await params.bindingStore.read(sessionBindingIdentity({
2434
- sessionId,
2435
- sessionKey: probe.sessionKey,
2436
- config
2437
- }));
2438
- return binding?.connectionScope === "supervision" && binding.supervisionSourceThreadId === probe.threadId ? binding.threadId : probe.threadId;
2439
- };
2440
- return async (probes) => {
2441
- const groups = /* @__PURE__ */ new Map();
2442
- for (const probe of probes) {
2443
- const fingerprint = upstreamConnectionFingerprint(probe);
2444
- if (!fingerprint) continue;
2445
- const control = params.control.forUpstream(probe.agentId, fingerprint);
2446
- if (!control) continue;
2447
- const key = `${probe.agentId}\0${fingerprint}`;
2448
- const group = groups.get(key) ?? {
2449
- control,
2450
- probes: []
2451
- };
2452
- group.probes.push(probe);
2453
- groups.set(key, group);
2454
- }
2455
- return (await Promise.all([...groups.values()].map((group) => checkCodexUpstreamActivity(group.probes, group.control, resolveThreadId)))).flat();
2456
- };
2457
- }
2458
- //#endregion
2459
- //#region extensions/codex/src/session-catalog-homes.ts
2460
- function existingCatalogHomeCandidates(value, label) {
2461
- const codexHome = canonicalCodexCatalogHome(value);
2462
- try {
2463
- if (!fsSync.statSync(codexHome).isDirectory()) return [];
2464
- } catch {
2465
- return [];
2466
- }
2467
- return [{
2468
- codexHome,
2469
- label: `Local Codex · ${label ?? path.basename(codexHome)}`
2470
- }];
2471
- }
2472
- /** Resolves every local Codex store the operator already owns, without path disclosure. */
2473
- function resolveCodexCatalogHomes(params) {
2474
- const { config, env, ownerAgentId, pluginConfig } = params;
2475
- const ownerAgentDir = resolveAgentDir$1(config, ownerAgentId, env);
2476
- const configuredHomes = readCodexPluginConfig(pluginConfig).sessionCatalog?.homes ?? [];
2477
- const base = resolveCodexSupervisionAppServerRuntimeOptions({
2478
- pluginConfig,
2479
- env,
2480
- agentDir: ownerAgentDir,
2481
- config
2482
- });
2483
- const primaryCodexHome = canonicalCodexCatalogHome(resolveCodexAppServerLocalHomeDir(base.start, ownerAgentDir, env));
2484
- const processUserHome = canonicalCodexCatalogHome(resolveCodexAppServerUserHomeDir(env));
2485
- const processHomeConfigured = Boolean(env.CODEX_HOME?.trim());
2486
- const candidates = [{
2487
- codexHome: primaryCodexHome,
2488
- label: "Local Codex",
2489
- usesProcessHomeFallback: base.start.transport === "stdio" && base.start.homeScope === "user" && !processHomeConfigured
2490
- }];
2491
- if (base.start.transport === "stdio") {
2492
- candidates.push({
2493
- codexHome: processUserHome,
2494
- label: "Local Codex · user",
2495
- usesProcessHomeFallback: !processHomeConfigured
2496
- });
2497
- const agentIds = listAgentIds(config).toSorted((left, right) => left === ownerAgentId ? -1 : right === ownerAgentId ? 1 : left.localeCompare(right));
2498
- candidates.push(...agentIds.flatMap((agentId) => existingCatalogHomeCandidates(resolveCodexAppServerHomeDir(resolveAgentDir$1(config, agentId, env)), agentId)), ...configuredHomes.flatMap((entry) => {
2499
- const { path: home, label } = typeof entry === "string" ? { path: entry } : entry;
2500
- return existingCatalogHomeCandidates(home, label);
2501
- }));
2502
- }
2503
- const seen = /* @__PURE__ */ new Set();
2504
- const homes = [];
2505
- for (const candidate of candidates) {
2506
- if (seen.has(candidate.codexHome)) continue;
2507
- seen.add(candidate.codexHome);
2508
- const sourceHomeId = codexCatalogHomeId(candidate.codexHome);
2509
- const primary = homes.length === 0;
2510
- homes.push({
2511
- sourceHomeId,
2512
- hostId: primary ? CODEX_LOCAL_SESSION_HOST_ID : `${CODEX_LOCAL_SESSION_HOST_ID}:${sourceHomeId}`,
2513
- label: candidate.label,
2514
- agentDir: ownerAgentDir,
2515
- appServer: primary ? base : {
2516
- ...base,
2517
- start: {
2518
- ...base.start,
2519
- homeScope: "user",
2520
- env: {
2521
- ...base.start.env,
2522
- CODEX_HOME: candidate.codexHome
2523
- }
2524
- }
2525
- },
2526
- ...base.connectionClass === "remote" ? {} : { localSessionsRoot: path.join(candidate.codexHome, "sessions") },
2527
- usesProcessHomeFallback: candidate.usesProcessHomeFallback ?? false
2528
- });
2529
- if (homes.length >= 100) break;
2530
- }
2531
- return homes;
2532
- }
2533
- /** Discovers Codex homes once per immutable Gateway config generation. */
2534
- function createCodexCatalogHomeResolver(params) {
2535
- const env = params.env ?? process.env;
2536
- const homesByConfig = /* @__PURE__ */ new WeakMap();
2537
- const buildSnapshot = (config) => {
2538
- const pluginConfig = params.getPluginConfig();
2539
- const homesByAgent = new Map(listAgentIds(config).map((agentId) => [agentId, resolveCodexCatalogHomes({
2540
- config,
2541
- pluginConfig,
2542
- ownerAgentId: agentId,
2543
- env
2544
- })]));
2545
- replaceCodexCatalogConnectionHomes([...homesByAgent.values()].flatMap((homes) => homes.filter((home) => home.appServer.start.transport === "stdio").map((home) => ({
2546
- agentDir: home.agentDir,
2547
- fingerprint: buildCodexAppServerConnectionFingerprint(home.appServer, home.agentDir),
2548
- codexHome: resolveCodexAppServerLocalHomeDir(home.appServer.start, home.agentDir, env)
2549
- }))));
2550
- homesByConfig.set(config, homesByAgent);
2551
- return homesByAgent;
2552
- };
2553
- let lastSnapshot = buildSnapshot(params.config);
2554
- return { forAgent(agentId) {
2555
- const config = params.getRuntimeConfig();
2556
- if (!config) return lastSnapshot.get(agentId) ?? [];
2557
- const cached = homesByConfig.get(config);
2558
- if (cached) return cached.get(agentId) ?? [];
2559
- lastSnapshot = buildSnapshot(config);
2560
- return lastSnapshot.get(agentId) ?? [];
2561
- } };
2562
- }
2563
- //#endregion
2564
- //#region extensions/codex/src/session-catalog-control.ts
2565
- const CODEX_SESSION_CATALOG_LIST_TTL_MS = 32e3;
2566
- const CODEX_SESSION_CATALOG_LIST_CACHE_MAX_ENTRIES = 32;
2567
- function codexCatalogPageCacheKey(params, agentId, source) {
2568
- return JSON.stringify([
2569
- agentId,
2570
- source?.sourceHomeId ?? null,
2571
- params.cursor ?? null,
2572
- params.limit ?? null,
2573
- params.searchTerm?.trim().toLocaleLowerCase() || null,
2574
- params.cwd?.trim() || null
2575
- ]);
2576
- }
2577
- function createCodexCatalogRequestSnapshot(requestTimeoutMs, request) {
2578
- return {
2579
- requestTimeoutMs,
2580
- listThreads: (params, timeoutMs) => request(CODEX_CONTROL_METHODS.listThreads, params, timeoutMs),
2581
- listThreadTurns: (params) => request(CODEX_CONTROL_METHODS.listThreadTurns, params),
2582
- forkThread: (params, assertCurrent) => request(CODEX_CONTROL_METHODS.forkThread, assertCodexThreadForkParams(params), void 0, assertCurrent),
2583
- readThread: async (threadId, includeTurns, timeoutMs) => (await request(CODEX_CONTROL_METHODS.readThread, {
2584
- threadId,
2585
- includeTurns
2586
- }, timeoutMs)).thread,
2587
- archiveThread: async (threadId, assertCurrent) => {
2588
- await request(CODEX_CONTROL_METHODS.archiveThread, { threadId }, void 0, assertCurrent);
2589
- }
2590
- };
2591
- }
2592
- function createCodexSessionCatalogControlFromRequests(params) {
2593
- return {
2594
- forkContext: params.forkContext,
2595
- ...params.clientId ? { clientId: params.clientId } : {},
2596
- ...params.connectionFingerprint ? { connectionFingerprint: params.connectionFingerprint } : {},
2597
- withPinnedConnection: params.withPinnedConnection,
2598
- async requireEligibleThread(threadId) {
2599
- const requests = params.createRequestSnapshot();
2600
- const deadline = params.now() + requests.requestTimeoutMs;
2601
- const unverified = () => new CatalogParamsError("Codex session eligibility could not be verified. Refresh the catalog and verify the session in its native Codex home before retrying.");
2602
- const remaining = () => {
2603
- const timeoutMs = Math.ceil(deadline - params.now());
2604
- if (timeoutMs <= 0) throw unverified();
2605
- return timeoutMs;
2606
- };
2607
- const verify = async () => {
2608
- if (params.sourceHomeId && await params.managedThreads?.has(params.sourceHomeId, threadId)) throw unverified();
2609
- const root = params.localSessionsRoot;
2610
- const thread = root ? await requests.readThread(threadId, false, remaining()) : void 0;
2611
- if (root && (!thread || thread.id !== threadId || !isInteractiveThreadSource(thread.source))) throw unverified();
2612
- let cursor;
2613
- const seenCursors = /* @__PURE__ */ new Set();
2614
- for (let pageIndex = 0; pageIndex < 100; pageIndex += 1) {
2615
- const page = await requests.listThreads({
2616
- archived: false,
2617
- limit: 100,
2618
- modelProviders: [],
2619
- sortKey: root ? "recency_at" : "updated_at",
2620
- sortDirection: "desc",
2621
- ...root ? {
2622
- useStateDbOnly: true,
2623
- ...thread?.cwd ? { cwd: thread.cwd } : {}
2624
- } : {},
2625
- ...cursor ? { cursor } : {}
2626
- }, remaining());
2627
- remaining();
2628
- const candidate = page.data.find((value) => value.id === threadId);
2629
- if (candidate) {
2630
- if (!isInteractiveThreadSource(candidate.source)) throw unverified();
2631
- if (root && thread) {
2632
- const rolloutPath = thread.path;
2633
- if (!rolloutPath || !candidate.path || rolloutPath.replace(/\.zst$/u, "") !== candidate.path.replace(/\.zst$/u, "")) throw unverified();
2634
- const metadata = await readCodexSessionMeta(root, rolloutPath, threadId);
2635
- remaining();
2636
- if (!metadata || !isInteractiveThreadSource(metadata.source) || metadata.originator === "openclaw") throw unverified();
2637
- return thread;
2638
- }
2639
- return candidate;
2640
- }
2641
- const nextCursor = readControlCursor(page.nextCursor, "next response");
2642
- if (!nextCursor || seenCursors.has(nextCursor)) throw unverified();
2643
- seenCursors.add(nextCursor);
2644
- cursor = nextCursor;
2645
- }
2646
- throw unverified();
2647
- };
2648
- return await withTimeout(verify(), requests.requestTimeoutMs, "Codex session eligibility could not be verified", unverified);
2649
- },
2650
- retireConnection: params.retireConnection,
2651
- async listPage(pageParams) {
2652
- const limit = normalizeLimit(pageParams.limit, "limit");
2653
- const search = pageParams.searchTerm?.trim().toLocaleLowerCase() || void 0;
2654
- const cwd = pageParams.cwd?.trim() || void 0;
2655
- const maxPages = search ? 20 : 1;
2656
- const sessions = [];
2657
- const managedThreads = [];
2658
- let cursor = readControlCursor(pageParams.cursor, "request");
2659
- let nextCursor;
2660
- let backwardsCursor;
2661
- const seenCursors = new Set(cursor ? [cursor] : []);
2662
- const requests = params.createRequestSnapshot();
2663
- const deadline = params.now() + requests.requestTimeoutMs;
2664
- for (let pageIndex = 0; pageIndex < maxPages; pageIndex += 1) {
2665
- const remainingTimeoutMs = Math.ceil(deadline - params.now());
2666
- if (remainingTimeoutMs <= 0) throw new Error("Codex session catalog listing timed out");
2667
- const response = await requests.listThreads({
2668
- archived: false,
2669
- limit: limit - sessions.length,
2670
- modelProviders: [],
2671
- sortKey: "updated_at",
2672
- sortDirection: "desc",
2673
- ...cwd ? { cwd } : {},
2674
- ...cursor ? { cursor } : {}
2675
- }, remainingTimeoutMs);
2676
- if (pageIndex === 0) backwardsCursor = readControlCursor(response.backwardsCursor, "backwards response");
2677
- for (const thread of response.data) {
2678
- if (await isOpenClawManagedCodexThread(thread, params.localSessionsRoot)) {
2679
- const rolloutPath = typeof thread.path === "string" ? thread.path.trim() : "";
2680
- managedThreads.push({
2681
- threadId: thread.id,
2682
- ...rolloutPath ? { rolloutPath } : {}
2683
- });
2684
- continue;
2685
- }
2686
- const session = toCatalogSession(thread, false);
2687
- if (session && (!search || (session.name ?? session.fallbackName)?.toLocaleLowerCase().includes(search))) sessions.push(session);
2688
- }
2689
- nextCursor = readControlCursor(response.nextCursor, "next response");
2690
- if (!nextCursor || sessions.length >= limit) break;
2691
- if (seenCursors.has(nextCursor)) throw new Error("Codex session catalog returned a repeated search cursor");
2692
- seenCursors.add(nextCursor);
2693
- cursor = nextCursor;
2694
- }
2695
- return {
2696
- sessions,
2697
- ...managedThreads.length > 0 ? { managedThreads } : {},
2698
- ...nextCursor ? { nextCursor } : {},
2699
- ...backwardsCursor ? { backwardsCursor } : {}
2700
- };
2701
- },
2702
- async listDescendantPage(listParams) {
2703
- const requests = params.createRequestSnapshot();
2704
- return await requests.listThreads(listParams, requests.requestTimeoutMs);
2705
- },
2706
- async readThread(threadId, includeTurns = false) {
2707
- return await params.createRequestSnapshot().readThread(threadId, includeTurns);
2708
- },
2709
- async listTurnPage(listParams) {
2710
- return await params.createRequestSnapshot().listThreadTurns(listParams);
2711
- },
2712
- async forkThread(forkParams, assertCurrent) {
2713
- return await params.createRequestSnapshot().forkThread(forkParams, assertCurrent);
2714
- },
2715
- async archiveThread(threadId, assertCurrent) {
2716
- await params.createRequestSnapshot().archiveThread(threadId, assertCurrent);
2717
- }
2718
- };
2719
- }
2720
- /** Builds the passive catalog over the Codex plugin's canonical shared client. */
2721
- function createCodexSessionCatalogControl(params) {
2722
- const now = params.now ?? Date.now;
2723
- const getPluginConfig = () => params.getPluginConfig();
2724
- const homeResolver = createCodexCatalogHomeResolver({
2725
- config: params.getRuntimeConfig() ?? params.config ?? {},
2726
- getRuntimeConfig: params.getRuntimeConfig,
2727
- getPluginConfig: params.getPluginConfig,
2728
- ...params.env ? { env: params.env } : {}
2729
- });
2730
- const requestOptionsByConfig = /* @__PURE__ */ new WeakMap();
2731
- const catalogPagesByConfig = /* @__PURE__ */ new WeakMap();
2732
- const resolveRequestOptions = (startOptions, agentId, source) => {
2733
- const runtimeConfig = params.getRuntimeConfig();
2734
- const agentDir = source?.agentDir ?? resolveAgentDir$1(runtimeConfig ?? {}, agentId);
2735
- const resolvedStartOptions = source?.appServer.start ?? startOptions;
2736
- if (!runtimeConfig) return {
2737
- agentDir,
2738
- config: void 0,
2739
- startOptions: structuredClone(resolvedStartOptions)
2740
- };
2741
- let byAgent = requestOptionsByConfig.get(runtimeConfig);
2742
- const cacheKey = `${agentId ?? ""}\0${source?.sourceHomeId ?? ""}`;
2743
- const cached = byAgent?.get(cacheKey);
2744
- if (cached) return cached;
2745
- const resolved = {
2746
- agentDir,
2747
- config: structuredClone(runtimeConfig),
2748
- startOptions: structuredClone(resolvedStartOptions)
2749
- };
2750
- if (!byAgent) {
2751
- byAgent = /* @__PURE__ */ new Map();
2752
- requestOptionsByConfig.set(runtimeConfig, byAgent);
2753
- }
2754
- byAgent.set(cacheKey, resolved);
2755
- return resolved;
2756
- };
2757
- const createRequestSnapshot = (agentId, source) => {
2758
- const pluginConfig = getPluginConfig();
2759
- const runtime = source?.appServer ?? resolveCodexSupervisionAppServerRuntimeOptions({ pluginConfig });
2760
- const requestOptions = resolveRequestOptions(runtime.start, agentId, source);
2761
- return createCodexCatalogRequestSnapshot(runtime.requestTimeoutMs, async (method, requestParams, timeoutMs, assertCurrent) => await codexControlRequest(pluginConfig, method, requestParams, {
2762
- ...requestOptions,
2763
- assertCurrent,
2764
- ...timeoutMs === void 0 ? {} : { timeoutMs }
2765
- }));
2766
- };
2767
- const forRequest = (agentId, source) => {
2768
- const withPinnedConnection = async (run) => {
2769
- const pluginConfig = getPluginConfig();
2770
- const runtime = source?.appServer ?? resolveCodexSupervisionAppServerRuntimeOptions({ pluginConfig });
2771
- const { agentDir, config: runtimeConfig, startOptions } = resolveRequestOptions(runtime.start, agentId, source);
2772
- const client = await getLeasedSharedCodexAppServerClient({
2773
- agentDir,
2774
- config: runtimeConfig,
2775
- startOptions,
2776
- timeoutMs: runtime.requestTimeoutMs
2777
- });
2778
- try {
2779
- const requests = createCodexCatalogRequestSnapshot(runtime.requestTimeoutMs, async (method, requestParams, timeoutMs, assertCurrent) => await requestCodexAppServerClientJson({
2780
- client,
2781
- method,
2782
- requestParams,
2783
- config: runtimeConfig,
2784
- timeoutMs: timeoutMs ?? runtime.requestTimeoutMs,
2785
- assertCurrent
2786
- }));
2787
- const pinnedControl = createCodexSessionCatalogControlFromRequests({
2788
- forkContext: {
2789
- client,
2790
- appServer: runtime,
2791
- pluginConfig,
2792
- agentDir,
2793
- localSessionsRoot: source?.localSessionsRoot
2794
- },
2795
- clientId: resolveCodexAppServerClientInstanceId(client),
2796
- retireConnection: () => {
2797
- retireSharedCodexAppServerClientIfCurrent(client);
2798
- },
2799
- connectionFingerprint: buildCodexAppServerConnectionFingerprint(runtime, agentDir),
2800
- createRequestSnapshot: () => requests,
2801
- ...source?.localSessionsRoot ? { localSessionsRoot: source.localSessionsRoot } : {},
2802
- sourceHomeId: source?.sourceHomeId,
2803
- managedThreads: params.managedThreads,
2804
- now,
2805
- withPinnedConnection: async (nestedRun) => await nestedRun(pinnedControl)
2806
- });
2807
- return await run(pinnedControl);
2808
- } finally {
2809
- releaseLeasedSharedCodexAppServerClient(client);
2810
- }
2811
- };
2812
- const control = createCodexSessionCatalogControlFromRequests({
2813
- createRequestSnapshot: () => createRequestSnapshot(agentId, source),
2814
- ...source?.localSessionsRoot ? { localSessionsRoot: source.localSessionsRoot } : {},
2815
- now,
2816
- withPinnedConnection
2817
- });
2818
- return {
2819
- ...control,
2820
- requireEligibleThread: (threadId) => withPinnedConnection((pinned) => pinned.requireEligibleThread(threadId)),
2821
- async listPage(pageParams) {
2822
- const runtimeConfig = params.getRuntimeConfig();
2823
- if (!runtimeConfig) return await control.listPage(pageParams);
2824
- let cache = catalogPagesByConfig.get(runtimeConfig);
2825
- if (!cache) {
2826
- cache = /* @__PURE__ */ new Map();
2827
- catalogPagesByConfig.set(runtimeConfig, cache);
2828
- }
2829
- const key = codexCatalogPageCacheKey(pageParams, agentId, source);
2830
- const cached = cache.get(key);
2831
- if (cached) {
2832
- cache.delete(key);
2833
- cache.set(key, cached);
2834
- if (cached.expiresAt > now()) return cached.value ?? await cached.page;
2835
- }
2836
- if (cached) cache.delete(key);
2837
- const page = control.listPage(pageParams);
2838
- const staleValue = cached?.value;
2839
- const entry = {
2840
- expiresAt: Number.POSITIVE_INFINITY,
2841
- page,
2842
- ...staleValue ? { value: staleValue } : {}
2843
- };
2844
- cache.set(key, entry);
2845
- pruneMapToMaxSize(cache, CODEX_SESSION_CATALOG_LIST_CACHE_MAX_ENTRIES);
2846
- const settle = (value) => {
2847
- if (cache.get(key) === entry) {
2848
- entry.value = value;
2849
- entry.expiresAt = now() + CODEX_SESSION_CATALOG_LIST_TTL_MS;
2850
- }
2851
- return value;
2852
- };
2853
- const restore = () => {
2854
- if (cache.get(key) !== entry) return;
2855
- if (staleValue) cache.set(key, {
2856
- expiresAt: now(),
2857
- page: Promise.resolve(staleValue),
2858
- value: staleValue
2859
- });
2860
- else cache.delete(key);
2861
- };
2862
- if (staleValue) {
2863
- page.then(settle, restore);
2864
- return staleValue;
2865
- }
2866
- try {
2867
- return settle(await page);
2868
- } catch (error) {
2869
- restore();
2870
- throw error;
2871
- }
2872
- }
2873
- };
2874
- };
2875
- const homesForAgent = (agentId) => homeResolver.forAgent(agentId);
2876
- const forUpstream = (agentId, connectionFingerprint) => {
2877
- const source = homesForAgent(agentId).find((home) => buildCodexAppServerConnectionFingerprint(home.appServer, home.agentDir) === connectionFingerprint);
2878
- return source ? forRequest(agentId, source) : void 0;
2879
- };
2880
- return {
2881
- forRequest,
2882
- forUpstream,
2883
- homesForAgent
2884
- };
2885
- }
2886
- //#endregion
2887
- //#region extensions/codex/src/session-catalog.ts
2888
- /** Allows read-only catalog and transcript commands on supported paired-node platforms. */
2889
- function createCodexSessionCatalogNodeInvokePolicies() {
2890
- return [{
2891
- commands: [
2892
- CODEX_APP_SERVER_THREADS_LIST_COMMAND,
2893
- CODEX_APP_SERVER_THREAD_TURNS_LIST_COMMAND,
2894
- CODEX_TERMINAL_RESUME_COMMAND,
2895
- CODEX_TERMINAL_START_COMMAND
2896
- ],
2897
- defaultPlatforms: [
2898
- "macos",
2899
- "linux",
2900
- "windows"
2901
- ],
2902
- handle: (context) => {
2903
- if (context.command === "codex.terminal.start.v1") return context.client?.scopes?.includes("operator.admin") && context.config.gateway?.cliAgents?.enabled === true && context.config.gateway?.terminal?.enabled !== false ? { ok: true } : {
2904
- ok: false,
2905
- message: "Native terminal start requires operator.admin and enabled CLI agents and terminals"
2906
- };
2907
- return context.command === "codex.terminal.resume.v1" ? { ok: true } : context.invokeNode();
2908
- }
2909
- }];
2910
- }
2911
- function toGenericCatalogHost(host, localTerminalAvailable) {
2912
- const local = isLocalCodexCatalogHost(host.hostId);
2913
- return {
2914
- hostId: host.hostId,
2915
- label: host.label,
2916
- kind: host.kind,
2917
- connected: host.connected,
2918
- ...host.nodeId ? { nodeId: host.nodeId } : {},
2919
- sessions: host.sessions.map((session) => {
2920
- const continuableStatus = !session.archived && (session.status === "idle" || session.status === "notLoaded");
2921
- const canContinue = (local || host.canContinueCodex === true) && continuableStatus && isInteractiveThreadSource(session.source);
2922
- const canArchive = local && continuableStatus && isInteractiveThreadSource(session.source);
2923
- const canOpenTerminal = isInteractiveThreadSource(session.source) && (local ? localTerminalAvailable : host.canOpenTerminalCodex === true);
2924
- const name = session.name ?? session.fallbackName;
2925
- return {
2926
- threadId: session.threadId,
2927
- ...session.sourceHomeId ? { sourceHomeId: session.sourceHomeId } : {},
2928
- ...name ? { name } : {},
2929
- ...session.cwd ? { cwd: session.cwd } : {},
2930
- status: session.status,
2931
- ...session.createdAt != null ? { createdAt: session.createdAt } : {},
2932
- ...session.updatedAt != null ? { updatedAt: session.updatedAt } : {},
2933
- ...session.recencyAt != null ? { recencyAt: session.recencyAt } : {},
2934
- ...session.source ? { source: session.source } : {},
2935
- ...session.modelProvider ? { modelProvider: session.modelProvider } : {},
2936
- ...session.cliVersion ? { cliVersion: session.cliVersion } : {},
2937
- ...session.gitBranch ? { gitBranch: session.gitBranch } : {},
2938
- archived: session.archived,
2939
- ...session.sessionKey ? { sessionKey: session.sessionKey } : {},
2940
- canContinue,
2941
- canArchive,
2942
- canOpenTerminal
2943
- };
2944
- }),
2945
- ...host.nextCursor ? { nextCursor: host.nextCursor } : {},
2946
- ...host.error ? { error: host.error } : {}
2947
- };
2948
- }
2949
- function isLocalCodexCatalogHost(hostId) {
2950
- return hostId === "gateway:local" || hostId.startsWith(`gateway:local:`);
2951
- }
2952
- function resolveLocalCatalogHomeForThread(params) {
2953
- if (params.homes.length === 0) throw new CatalogParamsError("local Codex sessions are unavailable in isolated state");
2954
- const exact = params.sourceHomeId ? params.homes.filter((home) => home.sourceHomeId === params.sourceHomeId) : params.homes.filter((home) => home.hostId === params.hostId);
2955
- if (exact.length === 0 || params.sourceHomeId && exact[0]?.hostId !== params.hostId) throw new CatalogParamsError("Codex session source home is unavailable");
2956
- return exact[0];
2957
- }
2958
- function registerCodexSessionCatalog(params) {
2959
- const catalogHomes = (agentId, allowProcessHomeFallback) => {
2960
- const homes = params.control.homesForAgent(agentId);
2961
- return allowProcessHomeFallback === false ? homes.filter((home) => !home.usesProcessHomeFallback) : homes;
2962
- };
2963
- const resolveRequestAgentId = (agentId) => resolveSessionAgentIdsStrict({
2964
- config: params.getRuntimeConfig() ?? params.api.config,
2965
- agentId
2966
- }).sessionAgentId;
2967
- const bindRequest = (request) => {
2968
- const agentId = resolveRequestAgentId(request.agentId);
2969
- const source = isLocalCodexCatalogHost(request.hostId) ? resolveLocalCatalogHomeForThread({
2970
- homes: [...catalogHomes(agentId, request.allowProcessHomeFallback)],
2971
- hostId: request.hostId,
2972
- ...request.sourceHomeId ? { sourceHomeId: request.sourceHomeId } : {}
2973
- }) : void 0;
2974
- return {
2975
- agentId,
2976
- source,
2977
- control: params.control.forRequest(agentId, source)
2978
- };
2979
- };
2980
- const bindLocalRequest = (request) => {
2981
- const bound = bindRequest(request);
2982
- if (!bound.source) throw new CatalogParamsError("Codex session catalog hostId is invalid");
2983
- return {
2984
- ...bound,
2985
- source: bound.source
2986
- };
2987
- };
2988
- const checkUpstreamActivity = createChecker(params);
2989
- params.api.registerSessionCatalog({
2990
- id: "codex",
2991
- label: "Codex",
2992
- supportsProcessHomeIsolation: true,
2993
- resolveCreateSession: ({ agentId }) => resolveCodexCatalogCreateSession(params.getRuntimeConfig() ?? params.api.config, agentId),
2994
- list: async (query) => {
2995
- const localTerminalAvailable = resolveLocalCodexTerminalExecutable() !== void 0;
2996
- const { agentId: requestedAgentId, allowProcessHomeFallback, listNodes, onHost, sessionEntries, ...gatewayQuery } = query;
2997
- const agentId = resolveRequestAgentId(requestedAgentId);
2998
- const localHomes = [...catalogHomes(agentId, allowProcessHomeFallback)];
2999
- const mapHost = (host) => ({
3000
- ...toGenericCatalogHost(host, localTerminalAvailable),
3001
- canStartTerminal: host.kind === "gateway" ? localTerminalAvailable && localHomes.some((home) => home.hostId === host.hostId && home.appServer.start.transport === "stdio") : host.canStartTerminal === true
3002
- });
3003
- return (await listCodexSessionCatalog({
3004
- agentId,
3005
- bindingStore: params.bindingStore,
3006
- config: params.getRuntimeConfig(),
3007
- runtime: params.api.runtime,
3008
- control: params.control,
3009
- query: gatewayQuery,
3010
- listNodes,
3011
- sessionEntries,
3012
- localHomes,
3013
- ...onHost ? { onHost: (host) => onHost(mapHost(host)) } : {}
3014
- })).hosts.map(mapHost);
3015
- },
3016
- read: async (request) => {
3017
- const { agentId, source, control } = bindRequest(request);
3018
- const page = await readCodexSessionTranscript({
3019
- agentId,
3020
- runtime: params.api.runtime,
3021
- control,
3022
- hostId: request.hostId,
3023
- threadId: request.threadId,
3024
- cursor: request.cursor,
3025
- limit: request.limit ?? 20,
3026
- ...source ? { source } : {}
3027
- });
3028
- return {
3029
- ...page,
3030
- items: page.items.map(toGenericTranscriptItem)
3031
- };
3032
- },
3033
- continueSession: async (request) => {
3034
- const config = params.getRuntimeConfig();
3035
- if (!config) throw new Error("OpenClaw runtime config is unavailable");
3036
- if (request.hostId.startsWith("node:")) return await continueNodeCodexSession({
3037
- agentId: resolveRequestAgentId(request.agentId),
3038
- api: params.api,
3039
- config,
3040
- hostId: request.hostId,
3041
- threadId: request.threadId,
3042
- clientScopes: request.clientScopes
3043
- });
3044
- if (!isLocalCodexCatalogHost(request.hostId)) throw new CatalogParamsError("Codex session catalog hostId is invalid");
3045
- const { agentId, source, control } = bindLocalRequest(request);
3046
- let upstreamBaseline;
3047
- const continued = await continueLocalCodexSession({
3048
- agentId,
3049
- api: params.api,
3050
- bindingStore: params.bindingStore,
3051
- config,
3052
- control,
3053
- threadId: request.threadId,
3054
- hostId: source.hostId,
3055
- sourceHomeId: source.sourceHomeId,
3056
- ...source.hostId === "gateway:local" ? { allowLegacy: true } : {},
3057
- onContinued: (baseline) => {
3058
- upstreamBaseline = baseline;
3059
- }
3060
- });
3061
- return codexUpstreamContinueResult(continued.sessionKey, request.threadId, upstreamBaseline);
3062
- },
3063
- checkUpstreamActivity: (probes, policy) => checkUpstreamActivity(probes.filter((probe) => !isLocalCodexCatalogHost(probe.hostId) || policy?.allowProcessHomeFallback !== false || catalogHomes(probe.agentId, false).some((home) => home.hostId === probe.hostId))),
3064
- archive: async (request) => {
3065
- if (request.confirmNoOtherRunner !== true) throw new CatalogParamsError("archive requires confirmation that no other runner is active");
3066
- if (!isLocalCodexCatalogHost(request.hostId)) throw new CatalogParamsError("paired-node Codex sessions are view-only");
3067
- const config = params.getRuntimeConfig();
3068
- if (!config) throw new Error("OpenClaw runtime config is unavailable");
3069
- const { agentId, source, control } = bindLocalRequest(request);
3070
- await archiveLocalCodexSession({
3071
- agentId,
3072
- bindingStore: params.bindingStore,
3073
- config,
3074
- control,
3075
- runtime: params.api.runtime,
3076
- threadId: request.threadId,
3077
- hostId: source.hostId,
3078
- sourceHomeId: source.sourceHomeId,
3079
- ...source.hostId === "gateway:local" ? { allowLegacy: true } : {}
3080
- });
3081
- return { ok: true };
3082
- },
3083
- openTerminal: async (request) => {
3084
- const { agentId, source, control } = bindRequest(request);
3085
- return await openCodexCatalogTerminal({
3086
- api: params.api,
3087
- control,
3088
- getPluginConfig: params.getPluginConfig,
3089
- getRuntimeConfig: params.getRuntimeConfig,
3090
- parseCatalogPage,
3091
- ...source ? { source } : {},
3092
- ...request,
3093
- agentId
3094
- });
3095
- },
3096
- startTerminalSession: async (request) => {
3097
- const source = request.nodeId ? void 0 : resolveLocalCatalogHomeForThread({
3098
- homes: [...catalogHomes(request.agentId, request.allowProcessHomeFallback)],
3099
- hostId: request.hostId ?? "gateway:local"
3100
- });
3101
- if (source && source.appServer.start.transport !== "stdio") throw new CatalogParamsError("Native terminal start requires a local Codex source");
3102
- return await startCodexCatalogTerminal({
3103
- getPluginConfig: params.getPluginConfig,
3104
- getRuntimeConfig: params.getRuntimeConfig,
3105
- ...request,
3106
- source
3107
- });
3108
- }
3109
- });
3110
- }
3111
- const codexSessionCatalogRuntime = {
3112
- register: registerCodexSessionCatalog,
3113
- list: listCodexSessionCatalog,
3114
- readTranscript: readCodexSessionTranscript,
3115
- continueLocal: continueLocalCodexSession,
3116
- continueNode: continueNodeCodexSession,
3117
- archiveLocal: archiveLocalCodexSession
3118
- };
3119
- //#endregion
3120
- export { CODEX_LOCAL_SESSION_HOST_ID as a, readCodexStatusProbes as c, createCodexCliSessionNodeHostCommands as d, createCodexCliSessionNodeInvokePolicies as f, resumeCodexCliSessionOnNode as g, resolveCodexCliSessionForBindingOnNode as h, createCodexSessionCatalogNodeHostCommands as i, requestOptions as l, listCodexCliSessionsOnNode as m, createCodexSessionCatalogNodeInvokePolicies as n, assertCodexArchiveDescendantsUnowned as o, formatCodexCliSessions as p, createCodexSessionCatalogControl as r, codexControlRequest as s, codexSessionCatalogRuntime as t, safeCodexControlRequest as u };