@openclaw/codex 2026.9.2 → 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 (108) hide show
  1. package/README.md +2 -0
  2. package/dist/api.js +14 -19
  3. package/dist/apply-B6el6hdO.js +357 -0
  4. package/dist/{attempt-client-cleanup-Bp1ZOnk2.js → attempt-client-cleanup-D6cR54TV.js} +39 -19
  5. package/dist/{attempt-context-CSazkWns.js → attempt-context-AO4DSjE0.js} +8 -6
  6. package/dist/{event-projector-usage-ZqEVbAEY.js → attempt-notifications--H8zXR5-.js} +3 -106
  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-QqgcPCgk.js +60 -0
  11. package/dist/{bounded-turn-DxGJRYbY.js → bounded-turn-lRpmZHFv.js} +25 -122
  12. package/dist/build-state-6RL6qohz.js +19 -0
  13. package/dist/{capabilities-B1mgvpP8.js → capabilities-BeqLPbtM.js} +1 -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-DSbGMXA0.js → command-formatters-DeTfrapr.js} +2 -2
  18. package/dist/{command-handlers-DOJvGv6-.js → command-handlers-BfIsJEuA.js} +31 -21
  19. package/dist/command-rpc-BMqRQOFX.js +226 -0
  20. package/dist/{compact-Y_xBqrHN.js → compact-CGJZ2rlb.js} +19 -14
  21. package/dist/config-JDfTI4VI.js +106 -0
  22. package/dist/{config-CyapYSji.js → config-options-jnIFvwxD.js} +204 -592
  23. package/dist/config-runtime-BWf6JLWG.js +11 -0
  24. package/dist/conversation-binding-CxOlHiix.js +889 -0
  25. package/dist/{plugin-marketplace-discovery-B7gHXJ3d.js → conversation-control-CUCrSIQI.js} +10 -142
  26. package/dist/doctor-contract-api.js +5 -5
  27. package/dist/{dynamic-tools-BwpvTxaX.js → dynamic-tools-D-JBoaLt.js} +66 -70
  28. package/dist/{effective-mcp-catalog-CY9Jn4bA.js → effective-mcp-catalog-J_5Ep5Um.js} +3 -3
  29. package/dist/{elicitation-input-DMkeki8d.js → elicitation-input-DPoK8F7w.js} +8 -22
  30. package/dist/ephemeral-turn-DSwzP8YY.js +101 -0
  31. package/dist/{event-projector-assistant-message-B9kp6iGC.js → event-projector-assistant-message-BmBM4qBV.js} +12 -25
  32. package/dist/event-projector-usage-CIyrYYid.js +102 -0
  33. package/dist/{harness-Czh2Sdoc.js → harness-FR6eQgyO.js} +31 -24
  34. package/dist/harness.js +1 -1
  35. package/dist/history-rejection-B4nOXNXF.js +13 -0
  36. package/dist/incognito-session-uhrBF6wJ.js +15 -0
  37. package/dist/index.js +411 -2875
  38. package/dist/{isolated-completion-CRh-51AK.js → isolated-completion-DHBefrzg.js} +7 -4
  39. package/dist/launch-args-RXQwn8zV.js +90 -0
  40. package/dist/{managed-binary-DcpnJF9x.js → managed-binary-DrjjRRUD.js} +4 -103
  41. package/dist/managed-thread-store-D1t5jh3G.js +66 -0
  42. package/dist/media-understanding-provider.js +4 -1
  43. package/dist/{model-catalog-DT5vo6qo.js → model-catalog-B_6M04Wo.js} +6 -5
  44. package/dist/{models-CcrgSMQR.js → models-P9k2qAof.js} +3 -3
  45. package/dist/native-execution-policy-umd0tgh4.js +128 -0
  46. package/dist/{native-subagent-monitor-B3bvQGcg.js → native-subagent-monitor-BbCUKRwC.js} +69 -42
  47. package/dist/node-cli-sessions-rj0ysJwM.js +527 -0
  48. package/dist/{node-exec-server.runtime-nfbUOtUB.js → node-exec-server.runtime-BY_ctYnT.js} +53 -22
  49. package/dist/plan-BMJdMOEF.js +711 -0
  50. package/dist/plugin-activation-BQK-f5sV.js +133 -0
  51. package/dist/{thread-resume-BLgqkUc1.js → plugin-app-cache-key-CdSQzWyX.js} +4 -52
  52. package/dist/{plugin-approval-roundtrip-aQVdyL5g.js → plugin-approval-roundtrip-DeW95wB5.js} +1 -1
  53. package/dist/plugin-inventory-CoRCzWW4.js +325 -0
  54. package/dist/plugin-marketplace-discovery-3akBizzF.js +134 -0
  55. package/dist/{plugin-metadata-cache-BwCLTY_U.js → plugin-metadata-cache-DgNfRAGA.js} +13 -9
  56. package/dist/protocol-CAAcVIKF.js +275 -0
  57. package/dist/{provider-capabilities-BpG9Ltc5.js → provider-capabilities-W4tfK5Y5.js} +2 -2
  58. package/dist/{rate-limits-Fx_l4eNa.js → rate-limits-Bqnx1N4z.js} +1 -1
  59. package/dist/request-CGvGOpeR.js +198 -0
  60. package/dist/{run-attempt-BzthFQSM.js → run-attempt-DwKds3DN.js} +589 -373
  61. package/dist/{runtime-artifact-Bh_gf6-t.js → runtime-artifact-T-NwqeSH.js} +27 -27
  62. package/dist/sandbox-guard-BcT66fWy.js +165 -0
  63. package/dist/{session-binding-4Ki04sW-.js → session-binding-CKSepwIC.js} +29 -47
  64. package/dist/{session-binding-record-CyaXZvTe.js → session-binding-record-CaZjYwNS.js} +11 -25
  65. package/dist/session-catalog-HaDcp7Sv.js +1533 -0
  66. package/dist/session-catalog-adoption-BKLtSrwi.js +251 -0
  67. package/dist/session-catalog-archive-D0i2pGj2.js +56 -0
  68. package/dist/session-catalog-home-id-D7-aLiNt.js +190 -0
  69. package/dist/session-catalog-node-adoption-BUuDYY8R.js +182 -0
  70. package/dist/session-catalog-node-continue-CBtc4wkI.js +238 -0
  71. package/dist/session-catalog-parsing-CdD3JhdM.js +280 -0
  72. package/dist/session-catalog-provenance-DkJHo735.js +124 -0
  73. package/dist/{session-cli-BjLhpmS1.js → session-cli-CbgaHh0f.js} +3 -2
  74. package/dist/{session-history-DWmMqiqW.js → session-history-Cz-tOOYj.js} +6 -3
  75. package/dist/{session-upstream-marker-DReTpGz6.js → session-history-import-DFN7sWRU.js} +5 -50
  76. package/dist/{session-history-read-LHldwvyh.js → session-history-read-cxPUxyVV.js} +21 -7
  77. package/dist/session-history-worker-runtime.js +18 -6
  78. package/dist/{session-history.worker-zZVcx0ME.js → session-history.worker-CNEvGaU5.js} +58 -51
  79. package/dist/session-history.worker.js +1 -1
  80. package/dist/{session-initialization-BCFVnLL4.js → session-initialization-Jo86C60I.js} +2 -2
  81. package/dist/{session-permission-policy-BaueHmSj.js → session-permission-policy-B22InTp_.js} +4 -7
  82. package/dist/{session-retirement-DNdmYdFc.js → session-retirement-BSNG_mhf.js} +6 -5
  83. package/dist/session-upstream-marker-D15C9NHp.js +46 -0
  84. package/dist/{settled-turn-context-BOM3Y1pl.js → settled-turn-context-Du6gdUDd.js} +9 -9
  85. package/dist/{settled-turn-finalizer-BI-b1sry.js → settled-turn-finalizer-BuLUrZl2.js} +7 -6
  86. package/dist/shared-client-CVhez2Uo.js +2911 -0
  87. package/dist/{side-question-B6DWAw1A.js → side-question-DLbr2vUU.js} +64 -169
  88. package/dist/source-Da-h6f7e.js +518 -0
  89. package/dist/thread-archive-guard-D1bP04Tf.js +53 -0
  90. package/dist/{thread-lifecycle-DPK30jad.js → thread-lifecycle-D1pzRwHB.js} +112 -616
  91. package/dist/{thread-ownership-CbucAmmp.js → thread-ownership-D6oASVRu.js} +13 -15
  92. package/dist/thread-policy-D8kI7yAO.js +54 -0
  93. package/dist/thread-resume-T5cveyxA.js +52 -0
  94. package/dist/timeout-BVw8aaM1.js +33 -0
  95. package/dist/{transcript-mirror-attestation-Byl34PC-.js → transcript-mirror-attestation-DibE0krH.js} +17 -4
  96. package/dist/{transcript-mirror-_njEB84z.js → transcript-mirror-t5TOccct.js} +50 -260
  97. package/dist/{transport-stdio-CzTngV0j.js → transport-stdio-BGjHoYLr.js} +73 -43
  98. package/dist/{upstream-session-fork-1fwbNKzQ.js → upstream-session-fork-De-sLJ2r.js} +26 -18
  99. package/dist/{usage-i9fv5-4m.js → usage-CPPTmBvZ.js} +4 -3
  100. package/dist/version-omm6IPI3.js +12 -0
  101. package/dist/{web-search-provider.runtime-DKQn67A7.js → web-search-provider.runtime-CSVgQL0w.js} +3 -3
  102. package/openclaw.plugin.json +22 -1
  103. package/package.json +4 -4
  104. package/dist/request-C8H22rPi.js +0 -475
  105. package/dist/session-catalog-B47uwekb.js +0 -3272
  106. package/dist/shared-client-CKhX2kFt.js +0 -7505
  107. package/dist/thread-policy-CTalhWFy.js +0 -105
  108. package/dist/{auth-binding-Ds_QVm-X.js → auth-binding-Co2Vfcf_.js} +1 -1
@@ -0,0 +1,1533 @@
1
+ import { l as sessionBindingIdentity } from "./session-binding-record-CaZjYwNS.js";
2
+ import { c as resolveCodexAppServerLocalHomeDir, i as assertCodexThreadForkParams, l as resolveCodexAppServerUserHomeDir, s as resolveCodexAppServerHomeDir, x as readCodexPluginConfig } from "./protocol-CAAcVIKF.js";
3
+ import { i as isCodexThreadReadMissingError, n as readCodexSessionMeta, t as isOpenClawManagedCodexThread } from "./session-catalog-provenance-DkJHo735.js";
4
+ import { t as CODEX_CONTROL_METHODS } from "./capabilities-BeqLPbtM.js";
5
+ import { C as requireOnlyKeys, T as unwrapNodeInvokePayload, _ as parseTranscriptPage, a as CODEX_LOCAL_SESSION_HOST_ID, b as readGatewayParams, c as MAX_TRANSCRIPT_PAGE_BYTES, d as catalogError, f as filterCatalogPageByTitle, g as parseJsonParams, h as parseCatalogPage, i as CODEX_CATALOG_TRANSCRIPT_READ_COMMAND, l as NODE_INVOKE_TIMEOUT_MS, m as normalizeLimit, n as CODEX_APP_SERVER_THREADS_LIST_COMMAND, o as CatalogParamsError, p as isInteractiveThreadSource, r as CODEX_APP_SERVER_THREAD_TURNS_LIST_COMMAND, s as MAX_CURSOR_LENGTH, t as CODEX_APP_SERVER_THREADS_CAPABILITY, v as readBoundedOptionalString, w as toCatalogSession, x as readPageParams, y as readControlCursor } from "./session-catalog-parsing-CdD3JhdM.js";
6
+ import { a as projectCodexUserItemText, n as codexCatalogHomeId, t as canonicalCodexCatalogHome } from "./session-catalog-home-id-D7-aLiNt.js";
7
+ import { r as codexUpstreamContinueResult } from "./session-upstream-marker-D15C9NHp.js";
8
+ import { i as replaceCodexCatalogConnectionHomes, t as buildCodexAppServerConnectionFingerprint } from "./plugin-app-cache-key-CdSQzWyX.js";
9
+ import { n as withTimeout } from "./timeout-BVw8aaM1.js";
10
+ import { isRecord } from "openclaw/plugin-sdk/string-coerce-runtime";
11
+ import { resolveDefaultAgentDir } from "openclaw/plugin-sdk/agent-harness-registration";
12
+ import { listAgentIds, resolveAgentDir, resolveDefaultAgentId, resolveSessionAgentIdsStrict } from "openclaw/plugin-sdk/agent-scope-runtime";
13
+ import { z } from "zod";
14
+ import fs from "node:fs";
15
+ import path from "node:path";
16
+ import { publishSessionCatalogHost, sessionCatalogPaging } from "openclaw/plugin-sdk/session-catalog-paging";
17
+ import { decodeNodePtyResumeParams, decodeNodePtyStartParams, resolveNodeHostExecutable, runNodePtyCommand } from "openclaw/plugin-sdk/node-host";
18
+ import { pruneMapToMaxSize } from "openclaw/plugin-sdk/collection-runtime";
19
+ //#region extensions/codex/src/session-catalog-create.ts
20
+ const CODEX_AGENT_RUNTIME_ID = "codex";
21
+ const CODEX_CATALOG_DEFAULT_MODEL_REF = "openai/gpt-5.6-sol";
22
+ function resolveCodexCatalogCreateSession(modelConfig, config, requestedAgentId) {
23
+ if (!config) return;
24
+ const agentId = requestedAgentId ?? resolveDefaultAgentId(config);
25
+ const defaultModel = modelConfig.resolveDefaultModelForAgent({
26
+ cfg: config,
27
+ agentId
28
+ });
29
+ return "error" in modelConfig.resolveAllowedModelRef({
30
+ cfg: config,
31
+ catalog: [],
32
+ raw: CODEX_CATALOG_DEFAULT_MODEL_REF,
33
+ defaultProvider: defaultModel.provider,
34
+ defaultModel: defaultModel.model,
35
+ agentId
36
+ }) ? void 0 : {
37
+ model: CODEX_CATALOG_DEFAULT_MODEL_REF,
38
+ agentRuntime: CODEX_AGENT_RUNTIME_ID
39
+ };
40
+ }
41
+ //#endregion
42
+ //#region extensions/codex/src/session-catalog-node-lookup.ts
43
+ async function lookupNodeCodexCatalogRecord(params) {
44
+ let cursor;
45
+ const seenCursors = /* @__PURE__ */ new Set();
46
+ for (let pageIndex = 0; pageIndex < 100; pageIndex += 1) {
47
+ const raw = await params.runtime.nodes.invoke({
48
+ nodeId: params.nodeId,
49
+ command: CODEX_APP_SERVER_THREADS_LIST_COMMAND,
50
+ params: {
51
+ agentId: params.agentId,
52
+ limit: 100,
53
+ ...cursor ? { cursor } : {}
54
+ },
55
+ timeoutMs: NODE_INVOKE_TIMEOUT_MS,
56
+ scopes: ["operator.write"]
57
+ });
58
+ const page = parseCatalogPage(unwrapNodeInvokePayload(raw));
59
+ const record = page.sessions.find((candidate) => candidate.threadId === params.threadId);
60
+ if (record) return {
61
+ kind: "found",
62
+ record
63
+ };
64
+ const nextCursor = page.nextCursor?.trim();
65
+ if (!nextCursor) break;
66
+ if (seenCursors.has(nextCursor)) return { kind: "cursor-cycle" };
67
+ seenCursors.add(nextCursor);
68
+ cursor = nextCursor;
69
+ }
70
+ return { kind: "missing" };
71
+ }
72
+ //#endregion
73
+ //#region extensions/codex/src/session-catalog-terminal.ts
74
+ const CODEX_TERMINAL_RESUME_COMMAND = "codex.terminal.resume.v1";
75
+ const CODEX_TERMINAL_START_COMMAND = "codex.terminal.start.v1";
76
+ function createCodexTerminalStartNodeHostCommand() {
77
+ return {
78
+ command: CODEX_TERMINAL_START_COMMAND,
79
+ cap: CODEX_APP_SERVER_THREADS_CAPABILITY,
80
+ dangerous: false,
81
+ duplex: true,
82
+ isAvailable: ({ env }) => Boolean(resolveNodeHostExecutable("codex", {
83
+ env,
84
+ strategy: "direct"
85
+ })),
86
+ handle: async (paramsJSON, io) => {
87
+ if (!io) throw new Error("Codex terminal command requires duplex transport");
88
+ const params = decodeNodePtyStartParams(paramsJSON);
89
+ const resolution = resolveNodeHostExecutable("codex", { strategy: "direct" });
90
+ if (!resolution) throw new Error("Codex CLI is unavailable; install codex on this node and reconnect");
91
+ return JSON.stringify(await runNodePtyCommand({
92
+ file: resolution.executable,
93
+ args: params.initialMessage !== void 0 ? ["--", params.initialMessage] : [],
94
+ cwd: params.cwd,
95
+ requiredCwd: true,
96
+ cols: params.cols,
97
+ rows: params.rows
98
+ }, io));
99
+ }
100
+ };
101
+ }
102
+ function resolveCodexCatalogTerminalHome(sources) {
103
+ const runtimeConfig = sources.getRuntimeConfig();
104
+ if (!runtimeConfig) throw new Error("OpenClaw runtime config is unavailable");
105
+ const agentDir = sources.source?.agentDir ?? (sources.agentId ? resolveAgentDir(runtimeConfig, sources.agentId) : resolveDefaultAgentDir(runtimeConfig));
106
+ const startOptions = sources.source?.appServer.start ?? sources.resolveRuntimeOptions({ pluginConfig: sources.getPluginConfig() }).start;
107
+ return resolveCodexAppServerLocalHomeDir(startOptions, agentDir);
108
+ }
109
+ function resolveLocalCodexTerminalExecutable(env = process.env) {
110
+ return resolveLocalCodexTerminalResolution(env)?.executable;
111
+ }
112
+ function resolveLocalCodexTerminalResolution(env = process.env) {
113
+ return resolveNodeHostExecutable("codex", {
114
+ env,
115
+ pathEnv: env.PATH ?? env.Path ?? "",
116
+ strategy: "fallback"
117
+ });
118
+ }
119
+ function codexNodeTerminalCapability(node) {
120
+ const commands = node.invocableCommands ?? node.commands;
121
+ return {
122
+ canOpenTerminalCodex: node.connected === true && commands?.includes("codex.terminal.resume.v1") === true,
123
+ canStartTerminal: node.connected === true && node.invocableCommands?.includes("codex.terminal.start.v1") === true
124
+ };
125
+ }
126
+ function createCodexTerminalNodeHostCommand(bindRequest, configSources) {
127
+ return {
128
+ command: CODEX_TERMINAL_RESUME_COMMAND,
129
+ cap: CODEX_APP_SERVER_THREADS_CAPABILITY,
130
+ dangerous: false,
131
+ duplex: true,
132
+ isAvailable: ({ env }) => Boolean(resolveNodeHostExecutable("codex", {
133
+ env,
134
+ pathEnv: env.PATH ?? env.Path ?? "",
135
+ strategy: "direct"
136
+ })),
137
+ handle: async (paramsJSON, io) => {
138
+ if (!io) throw new Error("Codex terminal command requires duplex transport");
139
+ const request = bindRequest(paramsJSON);
140
+ const resume = decodeNodePtyResumeParams(request.paramsJSON, (value) => {
141
+ 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");
142
+ return value;
143
+ });
144
+ const record = await request.control.requireEligibleThread(resume.threadId);
145
+ const resolution = resolveNodeHostExecutable("codex", {
146
+ env: process.env,
147
+ pathEnv: process.env.PATH ?? process.env.Path ?? "",
148
+ strategy: "direct"
149
+ });
150
+ if (!resolution) throw new Error("Codex CLI is unavailable");
151
+ return JSON.stringify(await runNodePtyCommand({
152
+ file: resolution.executable,
153
+ args: ["resume", resume.threadId],
154
+ ...record.cwd ? { cwd: record.cwd } : {},
155
+ env: { CODEX_HOME: resolveCodexCatalogTerminalHome({
156
+ ...configSources,
157
+ agentId: request.agentId
158
+ }) },
159
+ cols: resume.cols,
160
+ rows: resume.rows
161
+ }, io));
162
+ }
163
+ };
164
+ }
165
+ async function openCodexCatalogTerminal(params) {
166
+ const title = `codex resume ${params.threadId.slice(0, 8)}…`;
167
+ if (params.hostId === "gateway:local" || params.hostId.startsWith(`gateway:local:`)) {
168
+ const record = await params.control.requireEligibleThread(params.threadId);
169
+ const resolution = resolveLocalCodexTerminalResolution();
170
+ if (!resolution) throw new CatalogParamsError("Codex CLI is unavailable");
171
+ return {
172
+ kind: "local",
173
+ argv: [
174
+ resolution.executable,
175
+ "resume",
176
+ params.threadId
177
+ ],
178
+ ...record.cwd ? { cwd: record.cwd } : {},
179
+ env: { CODEX_HOME: resolveCodexCatalogTerminalHome(params) },
180
+ ...resolution.pathEnv ? { pathEnv: resolution.pathEnv } : {},
181
+ title
182
+ };
183
+ }
184
+ if (!params.hostId.startsWith("node:")) throw new CatalogParamsError("hostId is invalid");
185
+ const nodeId = params.hostId.slice(5);
186
+ if (!(await params.api.runtime.nodes.list()).nodes.find((candidate) => {
187
+ const commands = candidate.invocableCommands ?? candidate.commands;
188
+ return candidate.nodeId === nodeId && candidate.connected === true && commands?.includes("codex.appServer.threads.list.v1") === true && commands.includes("codex.terminal.resume.v1");
189
+ })) throw new CatalogParamsError("paired-node Codex terminal is unavailable");
190
+ const lookup = await lookupNodeCodexCatalogRecord({
191
+ agentId: params.agentId,
192
+ runtime: params.api.runtime,
193
+ nodeId,
194
+ threadId: params.threadId
195
+ });
196
+ if (lookup.kind !== "found" || !isInteractiveThreadSource(lookup.record.source)) throw new CatalogParamsError("Codex session is not a non-archived interactive Codex session");
197
+ const record = lookup.record;
198
+ return {
199
+ kind: "node",
200
+ nodeId,
201
+ command: CODEX_TERMINAL_RESUME_COMMAND,
202
+ paramsJSON: JSON.stringify({
203
+ agentId: params.agentId,
204
+ threadId: params.threadId
205
+ }),
206
+ ...record.cwd ? { cwd: record.cwd } : {},
207
+ title
208
+ };
209
+ }
210
+ async function startCodexCatalogTerminal(params) {
211
+ if (params.nodeId) return {
212
+ kind: "node",
213
+ nodeId: params.nodeId,
214
+ command: CODEX_TERMINAL_START_COMMAND,
215
+ paramsJSON: JSON.stringify({
216
+ cwd: params.cwd,
217
+ initialMessage: params.initialMessage
218
+ }),
219
+ cwd: params.cwd,
220
+ title: "codex"
221
+ };
222
+ const resolution = resolveLocalCodexTerminalResolution();
223
+ if (!resolution) throw new CatalogParamsError("Codex CLI is unavailable; install Codex or add codex to PATH, then try again");
224
+ return {
225
+ kind: "local",
226
+ argv: [resolution.executable, ...params.initialMessage !== void 0 ? ["--", params.initialMessage] : []],
227
+ cwd: params.cwd,
228
+ env: { CODEX_HOME: resolveCodexCatalogTerminalHome(params) },
229
+ ...resolution.pathEnv ? { pathEnv: resolution.pathEnv } : {},
230
+ title: "codex"
231
+ };
232
+ }
233
+ //#endregion
234
+ //#region extensions/codex/src/session-catalog-transcript-item.ts
235
+ const CODEX_MESSAGE_TYPES = /* @__PURE__ */ new Map([
236
+ ["userMessage", "userMessage"],
237
+ ["agentMessage", "agentMessage"],
238
+ ["reasoning", "reasoning"]
239
+ ]);
240
+ const CODEX_TOOL_TYPES = /* @__PURE__ */ new Set([
241
+ "commandExecution",
242
+ "fileChange",
243
+ "mcpToolCall",
244
+ "dynamicToolCall",
245
+ "collabAgentToolCall",
246
+ "webSearch",
247
+ "imageView",
248
+ "imageGeneration"
249
+ ]);
250
+ function toGenericTranscriptItem(item) {
251
+ let type = CODEX_MESSAGE_TYPES.get(item.type);
252
+ if (!type && CODEX_TOOL_TYPES.has(item.type)) type = item.result !== void 0 || Boolean(item.aggregatedOutput) ? "toolResult" : "toolCall";
253
+ type ??= "other";
254
+ const fallback = item.title ?? item.name ?? item.tool ?? item.command ?? item.query ?? void 0;
255
+ const resultText = item.aggregatedOutput || (item.result === void 0 ? void 0 : JSON.stringify(item.result, null, 2));
256
+ const changesText = Array.isArray(item.changes) ? item.changes.map((change) => `${change.kind}: ${change.path}`).join("\n") || void 0 : void 0;
257
+ const text = item.type === "userMessage" ? projectCodexUserItemText(item) : item.text || resultText || changesText || fallback;
258
+ return {
259
+ id: item.id,
260
+ type,
261
+ ...text ? { text } : {},
262
+ raw: item
263
+ };
264
+ }
265
+ //#endregion
266
+ //#region extensions/codex/src/session-catalog-transcript.ts
267
+ const TURN_ITEM_CURSOR_PREFIX = "turn-item:";
268
+ const transcriptPageSchema = z.strictObject({
269
+ items: z.array(z.strictObject({
270
+ id: z.string(),
271
+ type: z.enum([
272
+ "userMessage",
273
+ "agentMessage",
274
+ "reasoning",
275
+ "toolCall",
276
+ "toolResult",
277
+ "other"
278
+ ]),
279
+ text: z.string().optional(),
280
+ raw: z.record(z.string(), z.json()).optional(),
281
+ truncated: z.boolean().optional()
282
+ })),
283
+ nextCursor: z.string().optional()
284
+ });
285
+ function parseCodexCatalogTranscriptPage(value) {
286
+ return transcriptPageSchema.parse(value);
287
+ }
288
+ function encodeTurnItemCursor(turnCursor, itemId) {
289
+ return TURN_ITEM_CURSOR_PREFIX + Buffer.from(JSON.stringify([turnCursor, itemId])).toString("base64url");
290
+ }
291
+ function decodeTurnItemCursor(cursor) {
292
+ if (!cursor?.startsWith(TURN_ITEM_CURSOR_PREFIX)) return { turnCursor: cursor };
293
+ let value;
294
+ try {
295
+ value = JSON.parse(Buffer.from(cursor.slice(10), "base64url").toString());
296
+ } catch {
297
+ throw new CatalogParamsError("invalid Codex transcript item cursor");
298
+ }
299
+ if (!Array.isArray(value) || value.length !== 2 || typeof value[0] !== "string" || !value[0] || typeof value[1] !== "string" || !value[1]) throw new CatalogParamsError("invalid Codex transcript item cursor");
300
+ return {
301
+ turnCursor: value[0],
302
+ itemId: value[1]
303
+ };
304
+ }
305
+ function projectTranscriptPage(items, limit) {
306
+ const projected = items.map(toGenericTranscriptItem);
307
+ const page = sessionCatalogPaging.boundTranscriptPage(projected.toReversed(), limit, 0).items;
308
+ for (const [index, item] of page.entries()) if (item.text !== projected[index]?.text && projected[index]?.text) item.truncated = true;
309
+ return page;
310
+ }
311
+ function pageFitsNodeTransport(page) {
312
+ return Buffer.byteLength(JSON.stringify({ payloadJSON: JSON.stringify(page) }), "utf8") <= MAX_TRANSCRIPT_PAGE_BYTES;
313
+ }
314
+ /** The legacy API can anchor a turn, but cannot continue within that turn. */
315
+ async function readLegacyCodexTranscriptPage(readTurns, request) {
316
+ const { turnCursor, itemId } = decodeTurnItemCursor(request.cursor);
317
+ const page = parseTranscriptPage(await readTurns({
318
+ threadId: request.threadId,
319
+ limit: 1,
320
+ sortDirection: "desc",
321
+ itemsView: "full",
322
+ ...turnCursor ? { cursor: turnCursor } : {}
323
+ }));
324
+ const source = page.data.flatMap((turn) => turn.items.toReversed());
325
+ const anchorIndex = itemId ? source.findIndex((item) => item.id === itemId) : -1;
326
+ if (itemId && anchorIndex < 0) throw new CatalogParamsError("Codex transcript changed; refresh the session before loading older items");
327
+ const remaining = source.slice(anchorIndex + 1);
328
+ const items = projectTranscriptPage(remaining, request.limit);
329
+ const result = () => {
330
+ const lastSource = remaining[items.length - 1];
331
+ const partial = lastSource !== void 0 && items.length < remaining.length;
332
+ const nativeCursor = partial ? page.backwardsCursor : page.nextCursor;
333
+ const cursor = nativeCursor ? partial ? encodeTurnItemCursor(nativeCursor, lastSource.id) : nativeCursor : void 0;
334
+ if (partial && !cursor) throw new Error("Codex app-server did not provide a transcript continuation anchor");
335
+ return {
336
+ items,
337
+ ...cursor ? { nextCursor: cursor } : {}
338
+ };
339
+ };
340
+ let bounded = result();
341
+ while (!pageFitsNodeTransport(bounded)) {
342
+ if (items.length <= 1) throw new Error("Codex transcript item exceeds the safe response size");
343
+ items.pop();
344
+ bounded = result();
345
+ }
346
+ return bounded;
347
+ }
348
+ /** Uses the native store's item cursor whenever that store supports item history. */
349
+ async function readCodexCatalogTranscriptPage(control, request) {
350
+ if ((await control.requireEligibleThread(request.threadId)).historyMode !== "paginated") return readLegacyCodexTranscriptPage((params) => control.listTurnPage(params), request);
351
+ let limit = request.limit;
352
+ for (;;) {
353
+ const page = await control.listItemPage({
354
+ threadId: request.threadId,
355
+ limit,
356
+ sortDirection: "desc",
357
+ ...request.cursor ? { cursor: request.cursor } : {}
358
+ });
359
+ const nextCursor = readControlCursor(page.nextCursor, "transcript next response");
360
+ const items = projectTranscriptPage(page.data.map(({ item }) => item), limit);
361
+ const result = {
362
+ items,
363
+ ...nextCursor ? { nextCursor } : {}
364
+ };
365
+ const fittingCount = items.length - (pageFitsNodeTransport(result) ? 0 : 1);
366
+ if (fittingCount === page.data.length) return result;
367
+ if (fittingCount < 1) throw new Error("Codex transcript item exceeds the safe response size");
368
+ limit = fittingCount;
369
+ }
370
+ }
371
+ //#endregion
372
+ //#region extensions/codex/src/session-catalog-listing.ts
373
+ async function listVisiblePage(params) {
374
+ const excluded = params.excludedThreadIds;
375
+ const sessions = [];
376
+ let cursor = params.cursor;
377
+ let nextCursor;
378
+ let backwardsCursor;
379
+ const seenCursors = /* @__PURE__ */ new Set();
380
+ for (let pageIndex = 0; pageIndex < 20; pageIndex += 1) {
381
+ params.signal?.throwIfAborted();
382
+ let excludedFromPage = false;
383
+ const rawPage = await params.control.listPage({
384
+ limit: params.limit - sessions.length,
385
+ ...cursor ? { cursor } : {},
386
+ ...params.searchTerm ? { searchTerm: params.searchTerm } : {},
387
+ ...params.cwd ? { cwd: params.cwd } : {}
388
+ });
389
+ params.signal?.throwIfAborted();
390
+ const page = filterCatalogPageByTitle(parseCatalogPage(rawPage), params.searchTerm);
391
+ if (pageIndex === 0) backwardsCursor = page.backwardsCursor;
392
+ for (const managed of rawPage.managedThreads ?? []) {
393
+ excludedFromPage = true;
394
+ params.signal?.throwIfAborted();
395
+ await params.onExcludedThread?.(managed);
396
+ }
397
+ for (const session of page.sessions) {
398
+ if (!excluded?.has(session.threadId)) {
399
+ sessions.push(session);
400
+ continue;
401
+ }
402
+ excludedFromPage = true;
403
+ params.signal?.throwIfAborted();
404
+ await params.onExcludedThread?.({ threadId: session.threadId });
405
+ }
406
+ nextCursor = page.nextCursor;
407
+ if (!nextCursor || sessions.length >= params.limit || !excludedFromPage) break;
408
+ if (seenCursors.has(nextCursor)) throw new Error("Codex session catalog returned a repeated exclusion cursor");
409
+ seenCursors.add(nextCursor);
410
+ cursor = nextCursor;
411
+ }
412
+ return {
413
+ sessions: sessions.slice(0, params.limit),
414
+ ...nextCursor ? { nextCursor } : {},
415
+ ...backwardsCursor ? { backwardsCursor } : {}
416
+ };
417
+ }
418
+ async function listGatewayHost(params) {
419
+ const hostId = params.source?.hostId ?? "gateway:local";
420
+ const label = params.source?.label ?? "Local Codex";
421
+ const sourceHomeId = params.source?.sourceHomeId ?? "gateway:local";
422
+ try {
423
+ const page = await listVisiblePage({
424
+ control: params.control,
425
+ cursor: params.query.cursors?.[hostId],
426
+ excludedThreadIds: params.excludedThreadIds,
427
+ limit: params.query.limitPerHost,
428
+ onExcludedThread: params.onExcludedThread,
429
+ searchTerm: params.query.search,
430
+ signal: params.signal
431
+ });
432
+ params.signal?.throwIfAborted();
433
+ const { listAdoptedSessionEntries } = await import("./session-catalog-adoption-BKLtSrwi.js");
434
+ const { sessionCatalogAdoptedSourceKey } = await import("openclaw/plugin-sdk/session-catalog");
435
+ params.signal?.throwIfAborted();
436
+ const adoptedSessions = await listAdoptedSessionEntries({
437
+ agentId: params.agentId,
438
+ bindingStore: params.bindingStore,
439
+ config: params.config,
440
+ runtime: params.runtime,
441
+ sessionEntries: params.sessionEntries
442
+ });
443
+ return {
444
+ hostId,
445
+ label,
446
+ kind: "gateway",
447
+ connected: true,
448
+ ...page,
449
+ sessions: page.sessions.map((session) => {
450
+ const adopted = adoptedSessions.get(sessionCatalogAdoptedSourceKey(sourceHomeId, session.threadId)) ?? (hostId === "gateway:local" ? adoptedSessions.get(sessionCatalogAdoptedSourceKey("gateway:local", session.threadId)) : void 0);
451
+ const sourced = params.source ? Object.assign({}, session, { sourceHomeId: params.source.sourceHomeId }) : session;
452
+ return adopted ? Object.assign({}, sourced, { sessionKey: adopted.key }) : sourced;
453
+ })
454
+ };
455
+ } catch (error) {
456
+ return {
457
+ hostId,
458
+ label,
459
+ kind: "gateway",
460
+ connected: false,
461
+ sessions: [],
462
+ error: catalogError("APP_SERVER_UNAVAILABLE", error)
463
+ };
464
+ }
465
+ }
466
+ /** Lists Gateway-local and paired-node Codex sessions with per-host failures. */
467
+ async function listCodexSessionCatalog(params) {
468
+ const agentId = resolveSessionAgentIdsStrict({
469
+ config: params.config ?? {},
470
+ agentId: params.agentId
471
+ }).sessionAgentId;
472
+ const query = readGatewayParams(params.query);
473
+ const requestedHostIds = query.hostIds ? new Set(query.hostIds) : void 0;
474
+ const localSources = params.localHomes?.filter((source) => !requestedHostIds || requestedHostIds.has(source.hostId)) ?? (params.includeLocal !== false && (!requestedHostIds || requestedHostIds.has("gateway:local")) ? [void 0] : []);
475
+ const managedThreads = await params.bindingStore.managedThreads?.snapshot();
476
+ params.signal?.throwIfAborted();
477
+ const fallbackSource = params.control.homesForAgent(agentId)[0];
478
+ const localHosts = localSources.map((source) => (() => {
479
+ const ownershipSource = source ?? fallbackSource;
480
+ const managedThreadIds = ownershipSource ? managedThreads?.get(ownershipSource.sourceHomeId) : void 0;
481
+ return listGatewayHost({
482
+ agentId,
483
+ bindingStore: params.bindingStore,
484
+ config: params.config,
485
+ control: params.control.forRequest(agentId, ownershipSource),
486
+ query,
487
+ runtime: params.runtime,
488
+ sessionEntries: params.sessionEntries,
489
+ signal: params.signal,
490
+ excludedThreadIds: managedThreadIds,
491
+ ...ownershipSource && params.bindingStore.managedThreads ? { onExcludedThread: async ({ threadId, rolloutPath }) => {
492
+ if (!managedThreadIds?.has(threadId)) await params.bindingStore.managedThreads?.mark({
493
+ sourceHomeId: ownershipSource.sourceHomeId,
494
+ threadId,
495
+ ...rolloutPath ? { rolloutPath } : {}
496
+ });
497
+ } } : {},
498
+ ...source ? { source } : {}
499
+ });
500
+ })());
501
+ for (const host of localHosts) publishSessionCatalogHost(params, host);
502
+ if (!(!requestedHostIds || query.hostIds?.some((hostId) => hostId.startsWith("node:")))) return { hosts: await Promise.all(localHosts) };
503
+ let nodes;
504
+ try {
505
+ 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);
506
+ } catch (error) {
507
+ const registryHost = {
508
+ hostId: "node:registry",
509
+ label: "Paired nodes",
510
+ kind: "node",
511
+ connected: false,
512
+ canStartTerminal: false,
513
+ sessions: [],
514
+ error: catalogError("NODE_LIST_FAILED", error)
515
+ };
516
+ params.onHost?.(registryHost);
517
+ return { hosts: [...await Promise.all(localHosts), registryHost] };
518
+ }
519
+ params.signal?.throwIfAborted();
520
+ const { listNodeAdoptedSessionEntries } = await import("./session-catalog-node-adoption-BUuDYY8R.js");
521
+ const { compareNodeLabels, listPairedNode } = await import("./session-catalog-node-continue-CBtc4wkI.js");
522
+ params.signal?.throwIfAborted();
523
+ const adoptedNodeSessions = listNodeAdoptedSessionEntries({
524
+ agentId,
525
+ config: params.config,
526
+ runtime: params.runtime,
527
+ sessionEntries: params.sessionEntries
528
+ });
529
+ const nodeHosts = nodes.toSorted(compareNodeLabels).map((node) => listPairedNode({
530
+ agentId,
531
+ runtime: params.runtime,
532
+ node,
533
+ query,
534
+ adoptedSessions: adoptedNodeSessions,
535
+ terminalCapabilities: codexNodeTerminalCapability(node),
536
+ waitUntil: params.waitUntil,
537
+ signal: params.signal,
538
+ ...params.onHost ? { onHost: params.onHost } : {}
539
+ }));
540
+ return { hosts: await Promise.all([...localHosts, ...nodeHosts]) };
541
+ }
542
+ /** Builds the node-local read-only Codex app-server catalog command. */
543
+ function createCodexSessionCatalogNodeHostCommands(controlFactory, configSources, bindingStore) {
544
+ const bindRequest = (paramsJSON) => {
545
+ const parsed = parseJsonParams(paramsJSON);
546
+ if (!isRecord(parsed)) throw new CatalogParamsError("Codex session catalog parameters must be an object");
547
+ const requestedAgentId = readBoundedOptionalString(parsed, "agentId", 256);
548
+ const config = configSources.getRuntimeConfig() ?? {};
549
+ const agentId = resolveSessionAgentIdsStrict({
550
+ config,
551
+ agentId: requestedAgentId
552
+ }).sessionAgentId;
553
+ if (!listAgentIds(config).includes(agentId)) throw new CatalogParamsError(`unknown Codex session catalog agent: ${agentId}`);
554
+ const request = { ...parsed };
555
+ delete request.agentId;
556
+ const source = controlFactory.homesForAgent(agentId)[0];
557
+ return {
558
+ agentId,
559
+ control: controlFactory.forRequest(agentId, source),
560
+ sourceHomeId: source?.sourceHomeId,
561
+ params: request,
562
+ paramsJSON: JSON.stringify(request)
563
+ };
564
+ };
565
+ const commands = [
566
+ {
567
+ command: CODEX_APP_SERVER_THREADS_LIST_COMMAND,
568
+ cap: CODEX_APP_SERVER_THREADS_CAPABILITY,
569
+ dangerous: false,
570
+ handle: async (paramsJSON) => {
571
+ const request = bindRequest(paramsJSON);
572
+ const pageParams = readPageParams(request.params);
573
+ try {
574
+ const managedThreads = await bindingStore?.managedThreads?.snapshot();
575
+ const sourceHomeId = request.sourceHomeId;
576
+ const managedThreadIds = sourceHomeId ? managedThreads?.get(sourceHomeId) : void 0;
577
+ const page = await listVisiblePage({
578
+ control: request.control,
579
+ cursor: pageParams.cursor,
580
+ cwd: pageParams.cwd,
581
+ excludedThreadIds: managedThreadIds,
582
+ limit: pageParams.limit,
583
+ ...sourceHomeId && bindingStore?.managedThreads ? { onExcludedThread: async ({ threadId, rolloutPath }) => {
584
+ if (!managedThreadIds?.has(threadId)) await bindingStore.managedThreads?.mark({
585
+ sourceHomeId,
586
+ threadId,
587
+ ...rolloutPath ? { rolloutPath } : {}
588
+ });
589
+ } } : {},
590
+ searchTerm: pageParams.searchTerm
591
+ });
592
+ return JSON.stringify(page);
593
+ } catch {
594
+ throw new Error("Codex app-server catalog is unavailable");
595
+ }
596
+ }
597
+ },
598
+ {
599
+ command: CODEX_APP_SERVER_THREAD_TURNS_LIST_COMMAND,
600
+ cap: CODEX_APP_SERVER_THREADS_CAPABILITY,
601
+ dangerous: false,
602
+ handle: async (paramsJSON) => {
603
+ const request = bindRequest(paramsJSON);
604
+ const action = readNodeTranscriptParams(request.params);
605
+ try {
606
+ await request.control.requireEligibleThread(action.threadId);
607
+ const page = parseTranscriptPage(await request.control.listTurnPage({
608
+ threadId: action.threadId,
609
+ limit: action.limit,
610
+ sortDirection: "desc",
611
+ itemsView: "full",
612
+ ...action.cursor ? { cursor: action.cursor } : {}
613
+ }));
614
+ return JSON.stringify(page);
615
+ } catch (error) {
616
+ if (error instanceof CatalogParamsError) throw error;
617
+ throw new Error("Codex app-server transcript is unavailable", { cause: error });
618
+ }
619
+ }
620
+ },
621
+ {
622
+ command: CODEX_CATALOG_TRANSCRIPT_READ_COMMAND,
623
+ cap: CODEX_APP_SERVER_THREADS_CAPABILITY,
624
+ dangerous: false,
625
+ handle: async (paramsJSON) => {
626
+ const request = bindRequest(paramsJSON);
627
+ const action = readNodeTranscriptParams(request.params);
628
+ try {
629
+ return JSON.stringify(await readCodexCatalogTranscriptPage(request.control, action));
630
+ } catch (error) {
631
+ if (error instanceof CatalogParamsError) throw error;
632
+ throw new Error("Codex app-server transcript is unavailable", { cause: error });
633
+ }
634
+ }
635
+ },
636
+ createCodexTerminalNodeHostCommand(bindRequest, configSources),
637
+ createCodexTerminalStartNodeHostCommand()
638
+ ];
639
+ return process.env.OPENCLAW_NODE_EXEC_HOST?.trim().toLowerCase() === "app" ? commands.filter(({ command }) => command !== CODEX_CATALOG_TRANSCRIPT_READ_COMMAND) : commands;
640
+ }
641
+ function readNodeTranscriptParams(value) {
642
+ if (!isRecord(value)) throw new CatalogParamsError("Codex session read parameters must be an object");
643
+ requireOnlyKeys(value, /* @__PURE__ */ new Set([
644
+ "threadId",
645
+ "cursor",
646
+ "limit"
647
+ ]));
648
+ const threadId = readBoundedOptionalString(value, "threadId", 256);
649
+ if (!threadId) throw new CatalogParamsError("threadId is required");
650
+ const cursor = readBoundedOptionalString(value, "cursor", MAX_CURSOR_LENGTH);
651
+ return {
652
+ threadId,
653
+ limit: readBoundedLimit(value.limit, "limit", 20, 50),
654
+ ...cursor ? { cursor } : {}
655
+ };
656
+ }
657
+ function readBoundedLimit(value, key, fallback, max) {
658
+ if (value === void 0) return fallback;
659
+ if (!Number.isInteger(value) || value < 1 || value > max) throw new CatalogParamsError(`${key} must be an integer from 1 to ${max}`);
660
+ return value;
661
+ }
662
+ /** Reads the persisted transcript for a Gateway-local or paired-node Codex session. */
663
+ async function readCodexSessionTranscript(params) {
664
+ const cursor = readControlCursor(params.cursor, "transcript request");
665
+ const limit = readBoundedLimit(params.limit, "limit", 20, 50);
666
+ if (params.source || params.hostId === "gateway:local") {
667
+ const page = await readCodexCatalogTranscriptPage(params.control, {
668
+ threadId: params.threadId,
669
+ limit,
670
+ cursor
671
+ });
672
+ return {
673
+ hostId: params.hostId,
674
+ label: params.source?.label ?? "Local Codex",
675
+ threadId: params.threadId,
676
+ ...page
677
+ };
678
+ }
679
+ const nodeId = params.hostId.slice(5);
680
+ 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"));
681
+ if (!node) throw new CatalogParamsError("paired-node Codex session host is offline or unavailable");
682
+ const invoke = async (command, request) => unwrapNodeInvokePayload(await params.runtime.nodes.invoke({
683
+ nodeId,
684
+ command,
685
+ params: {
686
+ agentId: params.agentId,
687
+ threadId: params.threadId,
688
+ ...request
689
+ },
690
+ timeoutMs: NODE_INVOKE_TIMEOUT_MS,
691
+ scopes: ["operator.write"]
692
+ }));
693
+ const page = node.commands?.includes("codex.sessionCatalog.transcript.read.v1") ? parseCodexCatalogTranscriptPage(await invoke(CODEX_CATALOG_TRANSCRIPT_READ_COMMAND, {
694
+ cursor,
695
+ limit
696
+ })) : await readLegacyCodexTranscriptPage(async ({ cursor: turnCursor, limit: turnLimit }) => parseTranscriptPage(await invoke(CODEX_APP_SERVER_THREAD_TURNS_LIST_COMMAND, {
697
+ cursor: turnCursor,
698
+ limit: turnLimit
699
+ })), {
700
+ threadId: params.threadId,
701
+ cursor,
702
+ limit
703
+ });
704
+ const { nodeLabel } = await import("./session-catalog-node-continue-CBtc4wkI.js");
705
+ return {
706
+ hostId: params.hostId,
707
+ label: nodeLabel(node),
708
+ threadId: params.threadId,
709
+ ...page
710
+ };
711
+ }
712
+ //#endregion
713
+ //#region extensions/codex/src/session-upstream-activity.ts
714
+ const CODEX_UPSTREAM_TURN_LIMIT = 100;
715
+ function readMarker(probe) {
716
+ if (!isRecord(probe.marker)) return;
717
+ const turnId = probe.marker.turnId;
718
+ if (turnId !== null && typeof turnId !== "string") return;
719
+ const count = probe.marker.userMessageCount;
720
+ if (count !== void 0 && (!Number.isSafeInteger(count) || count < 0)) return;
721
+ return {
722
+ turnId,
723
+ ...count === void 0 ? {} : { userMessageCount: count }
724
+ };
725
+ }
726
+ function upstreamConnectionFingerprint(probe) {
727
+ return isRecord(probe.upstreamRef) && typeof probe.upstreamRef.connectionFingerprint === "string" ? probe.upstreamRef.connectionFingerprint : void 0;
728
+ }
729
+ function classifyCodexUpstreamTurns(params) {
730
+ const marker = readMarker(params.probe);
731
+ if (!marker) return;
732
+ const newest = params.turns[0];
733
+ if (!newest?.id) return;
734
+ const markerIndex = marker.turnId === null ? -1 : params.turns.findIndex((turn) => turn.id === marker.turnId);
735
+ const candidateTurns = markerIndex < 0 ? params.turns : params.turns.slice(0, markerIndex + 1);
736
+ const newestUserMessageCount = countUserMessages(newest);
737
+ if (!(marker.turnId !== newest.id || marker.userMessageCount === void 0 || newestUserMessageCount > marker.userMessageCount)) return;
738
+ const ownTexts = new Set(params.probe.ownRecentUserTexts);
739
+ let humanTurns = 0;
740
+ let occurredAt;
741
+ for (const turn of candidateTurns) {
742
+ const userMessages = turn.items.filter((item) => item.type === "userMessage");
743
+ const alreadySeen = turn.id === marker.turnId ? marker.userMessageCount ?? userMessages.length : 0;
744
+ for (const item of userMessages.slice(alreadySeen)) {
745
+ const texts = normalizeUserMessageTexts(item);
746
+ if (ownTexts.has(texts.join(" ")) || texts.length > 1 && texts.every((text) => ownTexts.has(text))) continue;
747
+ humanTurns += 1;
748
+ if (occurredAt === void 0) {
749
+ const timestampSeconds = turn.completedAt ?? turn.startedAt;
750
+ occurredAt = typeof timestampSeconds === "number" && Number.isFinite(timestampSeconds) ? timestampSeconds * 1e3 : params.now ?? Date.now();
751
+ }
752
+ }
753
+ }
754
+ const activityId = `${newest.id}:${newestUserMessageCount}`;
755
+ return {
756
+ kind: "activity",
757
+ sessionKey: params.probe.sessionKey,
758
+ humanTurns,
759
+ nextMarker: {
760
+ turnId: newest.id,
761
+ userMessageCount: newestUserMessageCount
762
+ },
763
+ ...humanTurns > 0 ? {
764
+ occurredAt: occurredAt ?? params.now ?? Date.now(),
765
+ dedupeId: activityId
766
+ } : {}
767
+ };
768
+ }
769
+ function countUserMessages(turn) {
770
+ return turn.items.filter((item) => item.type === "userMessage").length;
771
+ }
772
+ function normalizeUserMessageTexts(item) {
773
+ const typed = item;
774
+ const contentTexts = typed.content?.filter((input) => input.type === "text").map((input) => input.text.trim().replace(/\s+/g, " ")).filter(Boolean);
775
+ return contentTexts?.length ? contentTexts : [(typed.text ?? "").trim().replace(/\s+/g, " ")];
776
+ }
777
+ async function checkCodexUpstreamActivity(probes, control, resolveThreadId = (probe) => probe.threadId) {
778
+ return await control.withPinnedConnection(async (pinned) => {
779
+ const activities = [];
780
+ for (const probe of probes) {
781
+ const fingerprint = upstreamConnectionFingerprint(probe);
782
+ if (probe.upstreamKind !== "codex-app-server" || !fingerprint || fingerprint !== pinned.connectionFingerprint) continue;
783
+ try {
784
+ const threadId = resolveThreadId(probe);
785
+ const page = await pinned.listTurnPage({
786
+ threadId,
787
+ limit: CODEX_UPSTREAM_TURN_LIMIT,
788
+ sortDirection: "desc",
789
+ itemsView: "full"
790
+ });
791
+ const marker = readMarker(probe);
792
+ if (page.data.length === 0 && marker) {
793
+ try {
794
+ await pinned.readThread(threadId, false);
795
+ } catch (error) {
796
+ if (isCodexThreadReadMissingError(error, threadId)) activities.push({
797
+ kind: "missing",
798
+ sessionKey: probe.sessionKey
799
+ });
800
+ }
801
+ continue;
802
+ }
803
+ const activity = classifyCodexUpstreamTurns({
804
+ probe,
805
+ turns: page.data
806
+ });
807
+ if (activity) activities.push(activity);
808
+ } catch {}
809
+ }
810
+ return activities;
811
+ });
812
+ }
813
+ function createChecker(params) {
814
+ const resolveThreadId = (probe) => {
815
+ const config = params.getRuntimeConfig();
816
+ const sessionId = params.api.runtime.agent.session.getSessionEntry({
817
+ agentId: probe.agentId,
818
+ sessionKey: probe.sessionKey,
819
+ readConsistency: "latest"
820
+ })?.sessionId?.trim();
821
+ if (!sessionId) return probe.threadId;
822
+ const binding = params.bindingStore.read(sessionBindingIdentity({
823
+ sessionId,
824
+ sessionKey: probe.sessionKey,
825
+ config
826
+ }));
827
+ return binding?.connectionScope === "supervision" && binding.supervisionSourceThreadId === probe.threadId ? binding.threadId : probe.threadId;
828
+ };
829
+ return async (probes) => {
830
+ const groups = /* @__PURE__ */ new Map();
831
+ for (const probe of probes) {
832
+ const fingerprint = upstreamConnectionFingerprint(probe);
833
+ if (!fingerprint) continue;
834
+ const control = params.control.forUpstream(probe.agentId, fingerprint);
835
+ if (!control) continue;
836
+ const key = `${probe.agentId}\0${fingerprint}`;
837
+ const group = groups.get(key) ?? {
838
+ control,
839
+ probes: []
840
+ };
841
+ group.probes.push(probe);
842
+ groups.set(key, group);
843
+ }
844
+ return (await Promise.all([...groups.values()].map((group) => checkCodexUpstreamActivity(group.probes, group.control, resolveThreadId)))).flat();
845
+ };
846
+ }
847
+ //#endregion
848
+ //#region extensions/codex/src/session-catalog-homes.ts
849
+ function existingCatalogHomeCandidates(value, label) {
850
+ const codexHome = canonicalCodexCatalogHome(value);
851
+ try {
852
+ if (!fs.statSync(codexHome).isDirectory()) return [];
853
+ } catch {
854
+ return [];
855
+ }
856
+ return [{
857
+ codexHome,
858
+ label: `Local Codex · ${label ?? path.basename(codexHome)}`
859
+ }];
860
+ }
861
+ /** Resolves every local Codex store the operator already owns, without path disclosure. */
862
+ function resolveCodexCatalogHomes(params) {
863
+ const { config, env, ownerAgentId, pluginConfig } = params;
864
+ const ownerAgentDir = resolveAgentDir(config, ownerAgentId, env);
865
+ const configuredHomes = readCodexPluginConfig(pluginConfig).sessionCatalog?.homes ?? [];
866
+ const base = params.resolveRuntimeOptions({
867
+ pluginConfig,
868
+ env,
869
+ agentDir: ownerAgentDir,
870
+ config
871
+ });
872
+ const primaryCodexHome = canonicalCodexCatalogHome(resolveCodexAppServerLocalHomeDir(base.start, ownerAgentDir, env));
873
+ const processUserHome = canonicalCodexCatalogHome(resolveCodexAppServerUserHomeDir(env));
874
+ const processHomeConfigured = Boolean(env.CODEX_HOME?.trim());
875
+ const candidates = [{
876
+ codexHome: primaryCodexHome,
877
+ label: "Local Codex",
878
+ usesProcessHomeFallback: base.start.transport === "stdio" && base.start.homeScope === "user" && !processHomeConfigured
879
+ }];
880
+ if (base.start.transport === "stdio") {
881
+ candidates.push({
882
+ codexHome: processUserHome,
883
+ label: "Local Codex · user",
884
+ usesProcessHomeFallback: !processHomeConfigured
885
+ });
886
+ const agentIds = listAgentIds(config).toSorted((left, right) => left === ownerAgentId ? -1 : right === ownerAgentId ? 1 : left.localeCompare(right));
887
+ candidates.push(...agentIds.flatMap((agentId) => existingCatalogHomeCandidates(resolveCodexAppServerHomeDir(resolveAgentDir(config, agentId, env)), agentId)), ...configuredHomes.flatMap((entry) => {
888
+ const { path: home, label } = typeof entry === "string" ? { path: entry } : entry;
889
+ return existingCatalogHomeCandidates(home, label);
890
+ }));
891
+ }
892
+ const seen = /* @__PURE__ */ new Set();
893
+ const homes = [];
894
+ for (const candidate of candidates) {
895
+ if (seen.has(candidate.codexHome)) continue;
896
+ seen.add(candidate.codexHome);
897
+ const sourceHomeId = codexCatalogHomeId(candidate.codexHome);
898
+ const primary = homes.length === 0;
899
+ homes.push({
900
+ sourceHomeId,
901
+ hostId: primary ? CODEX_LOCAL_SESSION_HOST_ID : `${CODEX_LOCAL_SESSION_HOST_ID}:${sourceHomeId}`,
902
+ label: candidate.label,
903
+ agentDir: ownerAgentDir,
904
+ appServer: primary ? base : {
905
+ ...base,
906
+ start: {
907
+ ...base.start,
908
+ homeScope: "user",
909
+ env: {
910
+ ...base.start.env,
911
+ CODEX_HOME: candidate.codexHome
912
+ }
913
+ }
914
+ },
915
+ ...base.connectionClass === "remote" ? {} : { localSessionsRoot: path.join(candidate.codexHome, "sessions") },
916
+ usesProcessHomeFallback: candidate.usesProcessHomeFallback ?? false
917
+ });
918
+ if (homes.length >= 100) break;
919
+ }
920
+ return homes;
921
+ }
922
+ /** Discovers Codex homes once per immutable Gateway config generation. */
923
+ function createCodexCatalogHomeResolver(params) {
924
+ const env = params.env ?? process.env;
925
+ const homesByConfig = /* @__PURE__ */ new WeakMap();
926
+ const buildSnapshot = (config) => {
927
+ const pluginConfig = params.getPluginConfig();
928
+ const homesByAgent = new Map(listAgentIds(config).map((agentId) => [agentId, resolveCodexCatalogHomes({
929
+ config,
930
+ pluginConfig,
931
+ ownerAgentId: agentId,
932
+ env,
933
+ resolveRuntimeOptions: params.resolveRuntimeOptions
934
+ })]));
935
+ replaceCodexCatalogConnectionHomes([...homesByAgent.values()].flatMap((homes) => homes.filter((home) => home.appServer.start.transport === "stdio").map((home) => ({
936
+ agentDir: home.agentDir,
937
+ fingerprint: buildCodexAppServerConnectionFingerprint(home.appServer, home.agentDir),
938
+ codexHome: resolveCodexAppServerLocalHomeDir(home.appServer.start, home.agentDir, env)
939
+ }))));
940
+ homesByConfig.set(config, homesByAgent);
941
+ return homesByAgent;
942
+ };
943
+ let lastSnapshot = buildSnapshot(params.config);
944
+ return { forAgent(agentId) {
945
+ const config = params.getRuntimeConfig();
946
+ if (!config) return lastSnapshot.get(agentId) ?? [];
947
+ const cached = homesByConfig.get(config);
948
+ if (cached) return cached.get(agentId) ?? [];
949
+ lastSnapshot = buildSnapshot(config);
950
+ return lastSnapshot.get(agentId) ?? [];
951
+ } };
952
+ }
953
+ //#endregion
954
+ //#region extensions/codex/src/session-catalog-control.ts
955
+ const CODEX_SESSION_CATALOG_LIST_TTL_MS = 32e3;
956
+ const CODEX_SESSION_CATALOG_LIST_CACHE_MAX_ENTRIES = 32;
957
+ function codexCatalogPageCacheKey(params, agentId, source) {
958
+ return JSON.stringify([
959
+ agentId,
960
+ source?.sourceHomeId ?? null,
961
+ params.cursor ?? null,
962
+ params.limit ?? null,
963
+ params.searchTerm?.trim().toLocaleLowerCase() || null,
964
+ params.cwd?.trim() || null
965
+ ]);
966
+ }
967
+ function createCodexCatalogRequestSnapshot(requestTimeoutMs, request) {
968
+ return {
969
+ requestTimeoutMs,
970
+ listThreads: (params, timeoutMs) => request(CODEX_CONTROL_METHODS.listThreads, params, timeoutMs),
971
+ listThreadTurns: (params) => request(CODEX_CONTROL_METHODS.listThreadTurns, params),
972
+ listThreadItems: (params) => request(CODEX_CONTROL_METHODS.listThreadItems, params),
973
+ forkThread: (params, assertCurrent) => request(CODEX_CONTROL_METHODS.forkThread, assertCodexThreadForkParams(params), void 0, assertCurrent),
974
+ readThread: async (threadId, includeTurns, timeoutMs) => (await request(CODEX_CONTROL_METHODS.readThread, {
975
+ threadId,
976
+ includeTurns
977
+ }, timeoutMs)).thread,
978
+ archiveThread: async (threadId, assertCurrent) => {
979
+ await request(CODEX_CONTROL_METHODS.archiveThread, { threadId }, void 0, assertCurrent);
980
+ }
981
+ };
982
+ }
983
+ function createCodexSessionCatalogControlFromRequests(params) {
984
+ return {
985
+ forkContext: params.forkContext,
986
+ ...params.clientId ? { clientId: params.clientId } : {},
987
+ ...params.connectionFingerprint ? { connectionFingerprint: params.connectionFingerprint } : {},
988
+ withPinnedConnection: params.withPinnedConnection,
989
+ async requireEligibleThread(threadId) {
990
+ const requests = params.createRequestSnapshot();
991
+ const deadline = params.now() + requests.requestTimeoutMs;
992
+ 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.");
993
+ const remaining = () => {
994
+ const timeoutMs = Math.ceil(deadline - params.now());
995
+ if (timeoutMs <= 0) throw unverified();
996
+ return timeoutMs;
997
+ };
998
+ const verify = async () => {
999
+ if (params.sourceHomeId && await params.managedThreads?.has(params.sourceHomeId, threadId)) throw unverified();
1000
+ const root = params.localSessionsRoot;
1001
+ const thread = root ? await requests.readThread(threadId, false, remaining()) : void 0;
1002
+ if (root && (!thread || thread.id !== threadId || !isInteractiveThreadSource(thread.source))) throw unverified();
1003
+ let cursor;
1004
+ const seenCursors = /* @__PURE__ */ new Set();
1005
+ for (let pageIndex = 0; pageIndex < 100; pageIndex += 1) {
1006
+ const page = await requests.listThreads({
1007
+ archived: false,
1008
+ limit: 100,
1009
+ modelProviders: [],
1010
+ sortKey: root ? "recency_at" : "updated_at",
1011
+ sortDirection: "desc",
1012
+ ...root ? {
1013
+ useStateDbOnly: true,
1014
+ ...thread?.cwd ? { cwd: thread.cwd } : {}
1015
+ } : {},
1016
+ ...cursor ? { cursor } : {}
1017
+ }, remaining());
1018
+ remaining();
1019
+ const candidate = page.data.find((value) => value.id === threadId);
1020
+ if (candidate) {
1021
+ if (!isInteractiveThreadSource(candidate.source)) throw unverified();
1022
+ if (root && thread) {
1023
+ const rolloutPath = thread.path;
1024
+ if (!rolloutPath || !candidate.path || rolloutPath.replace(/\.zst$/u, "") !== candidate.path.replace(/\.zst$/u, "")) throw unverified();
1025
+ const metadata = await readCodexSessionMeta(root, rolloutPath, threadId);
1026
+ remaining();
1027
+ if (!metadata || !isInteractiveThreadSource(metadata.source) || metadata.originator === "openclaw") throw unverified();
1028
+ return thread;
1029
+ }
1030
+ return candidate;
1031
+ }
1032
+ const nextCursor = readControlCursor(page.nextCursor, "next response");
1033
+ if (!nextCursor || seenCursors.has(nextCursor)) throw unverified();
1034
+ seenCursors.add(nextCursor);
1035
+ cursor = nextCursor;
1036
+ }
1037
+ throw unverified();
1038
+ };
1039
+ return await withTimeout(verify(), requests.requestTimeoutMs, "Codex session eligibility could not be verified", unverified);
1040
+ },
1041
+ retireConnection: params.retireConnection,
1042
+ async listPage(pageParams) {
1043
+ const limit = normalizeLimit(pageParams.limit, "limit");
1044
+ const search = pageParams.searchTerm?.trim().toLocaleLowerCase() || void 0;
1045
+ const cwd = pageParams.cwd?.trim() || void 0;
1046
+ const maxPages = search ? 20 : 1;
1047
+ const sessions = [];
1048
+ const managedThreads = [];
1049
+ let cursor = readControlCursor(pageParams.cursor, "request");
1050
+ let nextCursor;
1051
+ let backwardsCursor;
1052
+ const seenCursors = new Set(cursor ? [cursor] : []);
1053
+ const requests = params.createRequestSnapshot();
1054
+ const deadline = params.now() + requests.requestTimeoutMs;
1055
+ const { sanitizeTerminalText } = await import("openclaw/plugin-sdk/text-chunking");
1056
+ for (let pageIndex = 0; pageIndex < maxPages; pageIndex += 1) {
1057
+ const remainingTimeoutMs = Math.ceil(deadline - params.now());
1058
+ if (remainingTimeoutMs <= 0) throw new Error("Codex session catalog listing timed out");
1059
+ const response = await requests.listThreads({
1060
+ archived: false,
1061
+ limit: limit - sessions.length,
1062
+ modelProviders: [],
1063
+ sortKey: "updated_at",
1064
+ sortDirection: "desc",
1065
+ ...cwd ? { cwd } : {},
1066
+ ...cursor ? { cursor } : {}
1067
+ }, remainingTimeoutMs);
1068
+ if (pageIndex === 0) backwardsCursor = readControlCursor(response.backwardsCursor, "backwards response");
1069
+ for (const thread of response.data) {
1070
+ if (await isOpenClawManagedCodexThread(thread, params.localSessionsRoot)) {
1071
+ const rolloutPath = typeof thread.path === "string" ? thread.path.trim() : "";
1072
+ managedThreads.push({
1073
+ threadId: thread.id,
1074
+ ...rolloutPath ? { rolloutPath } : {}
1075
+ });
1076
+ continue;
1077
+ }
1078
+ const session = toCatalogSession(thread, false, sanitizeTerminalText);
1079
+ if (session && (!search || (session.name ?? session.fallbackName)?.toLocaleLowerCase().includes(search))) sessions.push(session);
1080
+ }
1081
+ nextCursor = readControlCursor(response.nextCursor, "next response");
1082
+ if (!nextCursor || sessions.length >= limit) break;
1083
+ if (seenCursors.has(nextCursor)) throw new Error("Codex session catalog returned a repeated search cursor");
1084
+ seenCursors.add(nextCursor);
1085
+ cursor = nextCursor;
1086
+ }
1087
+ return {
1088
+ sessions,
1089
+ ...managedThreads.length > 0 ? { managedThreads } : {},
1090
+ ...nextCursor ? { nextCursor } : {},
1091
+ ...backwardsCursor ? { backwardsCursor } : {}
1092
+ };
1093
+ },
1094
+ async listDescendantPage(listParams) {
1095
+ const requests = params.createRequestSnapshot();
1096
+ return await requests.listThreads(listParams, requests.requestTimeoutMs);
1097
+ },
1098
+ async readThread(threadId, includeTurns = false) {
1099
+ return await params.createRequestSnapshot().readThread(threadId, includeTurns);
1100
+ },
1101
+ async listTurnPage(listParams) {
1102
+ return await params.createRequestSnapshot().listThreadTurns(listParams);
1103
+ },
1104
+ listItemPage: (listParams) => params.createRequestSnapshot().listThreadItems(listParams),
1105
+ async forkThread(forkParams, assertCurrent) {
1106
+ return await params.createRequestSnapshot().forkThread(forkParams, assertCurrent);
1107
+ },
1108
+ async archiveThread(threadId, assertCurrent) {
1109
+ await params.createRequestSnapshot().archiveThread(threadId, assertCurrent);
1110
+ }
1111
+ };
1112
+ }
1113
+ /** Builds the passive catalog over the Codex plugin's canonical shared client. */
1114
+ function createCodexSessionCatalogControl(params) {
1115
+ const now = params.now ?? Date.now;
1116
+ const getPluginConfig = () => params.getPluginConfig();
1117
+ const homeResolver = createCodexCatalogHomeResolver({
1118
+ config: params.getRuntimeConfig() ?? params.config ?? {},
1119
+ getRuntimeConfig: params.getRuntimeConfig,
1120
+ getPluginConfig: params.getPluginConfig,
1121
+ resolveRuntimeOptions: params.resolveRuntimeOptions,
1122
+ ...params.env ? { env: params.env } : {}
1123
+ });
1124
+ const requestOptionsByConfig = /* @__PURE__ */ new WeakMap();
1125
+ const catalogPagesByConfig = /* @__PURE__ */ new WeakMap();
1126
+ const resolveRequestOptions = (startOptions, agentId, source) => {
1127
+ const runtimeConfig = params.getRuntimeConfig();
1128
+ const agentDir = source?.agentDir ?? resolveAgentDir(runtimeConfig ?? {}, agentId);
1129
+ const resolvedStartOptions = source?.appServer.start ?? startOptions;
1130
+ if (!runtimeConfig) return {
1131
+ agentDir,
1132
+ config: void 0,
1133
+ startOptions: structuredClone(resolvedStartOptions)
1134
+ };
1135
+ let byAgent = requestOptionsByConfig.get(runtimeConfig);
1136
+ const cacheKey = `${agentId ?? ""}\0${source?.sourceHomeId ?? ""}`;
1137
+ const cached = byAgent?.get(cacheKey);
1138
+ if (cached) return cached;
1139
+ const resolved = {
1140
+ agentDir,
1141
+ config: structuredClone(runtimeConfig),
1142
+ startOptions: structuredClone(resolvedStartOptions)
1143
+ };
1144
+ if (!byAgent) {
1145
+ byAgent = /* @__PURE__ */ new Map();
1146
+ requestOptionsByConfig.set(runtimeConfig, byAgent);
1147
+ }
1148
+ byAgent.set(cacheKey, resolved);
1149
+ return resolved;
1150
+ };
1151
+ const createRequestSnapshot = (agentId, source) => {
1152
+ const pluginConfig = getPluginConfig();
1153
+ const runtime = source?.appServer ?? params.resolveRuntimeOptions({ pluginConfig });
1154
+ const requestOptions = resolveRequestOptions(runtime.start, agentId, source);
1155
+ return createCodexCatalogRequestSnapshot(runtime.requestTimeoutMs, async (method, requestParams, timeoutMs, assertCurrent) => {
1156
+ const { codexControlRequest } = await import("./command-rpc-BMqRQOFX.js").then((n) => n.n);
1157
+ return await codexControlRequest(pluginConfig, method, requestParams, {
1158
+ ...requestOptions,
1159
+ assertCurrent,
1160
+ ...timeoutMs === void 0 ? {} : { timeoutMs }
1161
+ });
1162
+ });
1163
+ };
1164
+ const forRequest = (agentId, source) => {
1165
+ const withPinnedConnection = async (run) => {
1166
+ const pluginConfig = getPluginConfig();
1167
+ const runtime = source?.appServer ?? params.resolveRuntimeOptions({ pluginConfig });
1168
+ const { agentDir, config: runtimeConfig, startOptions } = resolveRequestOptions(runtime.start, agentId, source);
1169
+ const { getLeasedSharedCodexAppServerClient, releaseLeasedSharedCodexAppServerClient, retireSharedCodexAppServerClientIfCurrent } = await import("./shared-client-CVhez2Uo.js").then((n) => n.y);
1170
+ const { resolveCodexAppServerClientInstanceId } = await import("./client-BEKu4yDx.js").then((n) => n.n);
1171
+ const { requestCodexAppServerClientJson } = await import("./request-CGvGOpeR.js").then((n) => n.a);
1172
+ const client = await getLeasedSharedCodexAppServerClient({
1173
+ agentDir,
1174
+ config: runtimeConfig,
1175
+ startOptions,
1176
+ timeoutMs: runtime.requestTimeoutMs
1177
+ });
1178
+ try {
1179
+ const requests = createCodexCatalogRequestSnapshot(runtime.requestTimeoutMs, async (method, requestParams, timeoutMs, assertCurrent) => await requestCodexAppServerClientJson({
1180
+ client,
1181
+ method,
1182
+ requestParams,
1183
+ config: runtimeConfig,
1184
+ timeoutMs: timeoutMs ?? runtime.requestTimeoutMs,
1185
+ assertCurrent
1186
+ }));
1187
+ const pinnedControl = createCodexSessionCatalogControlFromRequests({
1188
+ forkContext: {
1189
+ client,
1190
+ appServer: runtime,
1191
+ pluginConfig,
1192
+ agentDir,
1193
+ localSessionsRoot: source?.localSessionsRoot
1194
+ },
1195
+ clientId: resolveCodexAppServerClientInstanceId(client),
1196
+ retireConnection: () => {
1197
+ retireSharedCodexAppServerClientIfCurrent(client);
1198
+ },
1199
+ connectionFingerprint: buildCodexAppServerConnectionFingerprint(runtime, agentDir),
1200
+ createRequestSnapshot: () => requests,
1201
+ ...source?.localSessionsRoot ? { localSessionsRoot: source.localSessionsRoot } : {},
1202
+ sourceHomeId: source?.sourceHomeId,
1203
+ managedThreads: params.managedThreads,
1204
+ now,
1205
+ withPinnedConnection: async (nestedRun) => await nestedRun(pinnedControl)
1206
+ });
1207
+ return await run(pinnedControl);
1208
+ } finally {
1209
+ releaseLeasedSharedCodexAppServerClient(client);
1210
+ }
1211
+ };
1212
+ const control = createCodexSessionCatalogControlFromRequests({
1213
+ createRequestSnapshot: () => createRequestSnapshot(agentId, source),
1214
+ ...source?.localSessionsRoot ? { localSessionsRoot: source.localSessionsRoot } : {},
1215
+ now,
1216
+ withPinnedConnection
1217
+ });
1218
+ return {
1219
+ ...control,
1220
+ requireEligibleThread: (threadId) => withPinnedConnection((pinned) => pinned.requireEligibleThread(threadId)),
1221
+ async listPage(pageParams) {
1222
+ const runtimeConfig = params.getRuntimeConfig();
1223
+ if (!runtimeConfig) return await control.listPage(pageParams);
1224
+ let cache = catalogPagesByConfig.get(runtimeConfig);
1225
+ if (!cache) {
1226
+ cache = /* @__PURE__ */ new Map();
1227
+ catalogPagesByConfig.set(runtimeConfig, cache);
1228
+ }
1229
+ const key = codexCatalogPageCacheKey(pageParams, agentId, source);
1230
+ const cached = cache.get(key);
1231
+ if (cached) {
1232
+ cache.delete(key);
1233
+ cache.set(key, cached);
1234
+ if (cached.expiresAt > now()) return cached.value ?? await cached.page;
1235
+ }
1236
+ if (cached) cache.delete(key);
1237
+ const page = control.listPage(pageParams);
1238
+ const staleValue = cached?.value;
1239
+ const entry = {
1240
+ expiresAt: Number.POSITIVE_INFINITY,
1241
+ page,
1242
+ ...staleValue ? { value: staleValue } : {}
1243
+ };
1244
+ cache.set(key, entry);
1245
+ pruneMapToMaxSize(cache, CODEX_SESSION_CATALOG_LIST_CACHE_MAX_ENTRIES);
1246
+ const settle = (value) => {
1247
+ if (cache.get(key) === entry) {
1248
+ entry.value = value;
1249
+ entry.expiresAt = now() + CODEX_SESSION_CATALOG_LIST_TTL_MS;
1250
+ }
1251
+ return value;
1252
+ };
1253
+ const restore = () => {
1254
+ if (cache.get(key) !== entry) return;
1255
+ if (staleValue) cache.set(key, {
1256
+ expiresAt: now(),
1257
+ page: Promise.resolve(staleValue),
1258
+ value: staleValue
1259
+ });
1260
+ else cache.delete(key);
1261
+ };
1262
+ if (staleValue) {
1263
+ page.then(settle, restore);
1264
+ return staleValue;
1265
+ }
1266
+ try {
1267
+ return settle(await page);
1268
+ } catch (error) {
1269
+ restore();
1270
+ throw error;
1271
+ }
1272
+ }
1273
+ };
1274
+ };
1275
+ const homesForAgent = (agentId) => homeResolver.forAgent(agentId);
1276
+ const forUpstream = (agentId, connectionFingerprint) => {
1277
+ const source = homesForAgent(agentId).find((home) => buildCodexAppServerConnectionFingerprint(home.appServer, home.agentDir) === connectionFingerprint);
1278
+ return source ? forRequest(agentId, source) : void 0;
1279
+ };
1280
+ return {
1281
+ forRequest,
1282
+ forUpstream,
1283
+ homesForAgent
1284
+ };
1285
+ }
1286
+ //#endregion
1287
+ //#region extensions/codex/src/session-catalog.ts
1288
+ /** Allows read-only catalog and transcript commands on supported paired-node platforms. */
1289
+ function createCodexSessionCatalogNodeInvokePolicies() {
1290
+ return [{
1291
+ commands: [
1292
+ CODEX_APP_SERVER_THREADS_LIST_COMMAND,
1293
+ CODEX_APP_SERVER_THREAD_TURNS_LIST_COMMAND,
1294
+ CODEX_CATALOG_TRANSCRIPT_READ_COMMAND,
1295
+ CODEX_TERMINAL_RESUME_COMMAND,
1296
+ CODEX_TERMINAL_START_COMMAND
1297
+ ],
1298
+ defaultPlatforms: [
1299
+ "macos",
1300
+ "linux",
1301
+ "windows"
1302
+ ],
1303
+ handle: (context) => {
1304
+ 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 } : {
1305
+ ok: false,
1306
+ message: "Native terminal start requires operator.admin and enabled CLI agents and terminals"
1307
+ };
1308
+ return context.command === "codex.terminal.resume.v1" ? { ok: true } : context.invokeNode();
1309
+ }
1310
+ }];
1311
+ }
1312
+ function toGenericCatalogHost(host, localTerminalAvailable) {
1313
+ const local = isLocalCodexCatalogHost(host.hostId);
1314
+ return {
1315
+ hostId: host.hostId,
1316
+ label: host.label,
1317
+ kind: host.kind,
1318
+ connected: host.connected,
1319
+ ...host.nodeId ? { nodeId: host.nodeId } : {},
1320
+ sessions: host.sessions.map((session) => {
1321
+ const continuableStatus = !session.archived && (session.status === "idle" || session.status === "notLoaded");
1322
+ const canContinue = (local || host.canContinueCodex === true) && continuableStatus && isInteractiveThreadSource(session.source);
1323
+ const canArchive = local && continuableStatus && isInteractiveThreadSource(session.source);
1324
+ const canOpenTerminal = isInteractiveThreadSource(session.source) && (local ? localTerminalAvailable : host.canOpenTerminalCodex === true);
1325
+ const name = session.name ?? session.fallbackName;
1326
+ return {
1327
+ threadId: session.threadId,
1328
+ ...session.sourceHomeId ? { sourceHomeId: session.sourceHomeId } : {},
1329
+ ...name ? { name } : {},
1330
+ ...session.cwd ? { cwd: session.cwd } : {},
1331
+ status: session.status,
1332
+ ...session.createdAt != null ? { createdAt: session.createdAt } : {},
1333
+ ...session.updatedAt != null ? { updatedAt: session.updatedAt } : {},
1334
+ ...session.recencyAt != null ? { recencyAt: session.recencyAt } : {},
1335
+ ...session.source ? { source: session.source } : {},
1336
+ ...session.modelProvider ? { modelProvider: session.modelProvider } : {},
1337
+ ...session.cliVersion ? { cliVersion: session.cliVersion } : {},
1338
+ ...session.gitBranch ? { gitBranch: session.gitBranch } : {},
1339
+ archived: session.archived,
1340
+ ...session.sessionKey ? { sessionKey: session.sessionKey } : {},
1341
+ canContinue,
1342
+ canArchive,
1343
+ canOpenTerminal
1344
+ };
1345
+ }),
1346
+ ...host.nextCursor ? { nextCursor: host.nextCursor } : {},
1347
+ ...host.error ? { error: host.error } : {}
1348
+ };
1349
+ }
1350
+ function isLocalCodexCatalogHost(hostId) {
1351
+ return hostId === "gateway:local" || hostId.startsWith(`gateway:local:`);
1352
+ }
1353
+ function resolveLocalCatalogHomeForThread(params) {
1354
+ if (params.homes.length === 0) throw new CatalogParamsError("local Codex sessions are unavailable in isolated state");
1355
+ const exact = params.sourceHomeId ? params.homes.filter((home) => home.sourceHomeId === params.sourceHomeId) : params.homes.filter((home) => home.hostId === params.hostId);
1356
+ if (exact.length === 0 || params.sourceHomeId && exact[0]?.hostId !== params.hostId) throw new CatalogParamsError("Codex session source home is unavailable");
1357
+ return exact[0];
1358
+ }
1359
+ function registerCodexSessionCatalog(params) {
1360
+ const catalogHomes = (agentId, allowProcessHomeFallback) => {
1361
+ const homes = params.control.homesForAgent(agentId);
1362
+ return allowProcessHomeFallback === false ? homes.filter((home) => !home.usesProcessHomeFallback) : homes;
1363
+ };
1364
+ const resolveRequestAgentId = (agentId) => resolveSessionAgentIdsStrict({
1365
+ config: params.getRuntimeConfig() ?? params.api.config,
1366
+ agentId
1367
+ }).sessionAgentId;
1368
+ const bindRequest = (request) => {
1369
+ const agentId = resolveRequestAgentId(request.agentId);
1370
+ const source = isLocalCodexCatalogHost(request.hostId) ? resolveLocalCatalogHomeForThread({
1371
+ homes: [...catalogHomes(agentId, request.allowProcessHomeFallback)],
1372
+ hostId: request.hostId,
1373
+ ...request.sourceHomeId ? { sourceHomeId: request.sourceHomeId } : {}
1374
+ }) : void 0;
1375
+ return {
1376
+ agentId,
1377
+ source,
1378
+ control: params.control.forRequest(agentId, source)
1379
+ };
1380
+ };
1381
+ const bindLocalRequest = (request) => {
1382
+ const bound = bindRequest(request);
1383
+ if (!bound.source) throw new CatalogParamsError("Codex session catalog hostId is invalid");
1384
+ return {
1385
+ ...bound,
1386
+ source: bound.source
1387
+ };
1388
+ };
1389
+ const checkUpstreamActivity = createChecker(params);
1390
+ params.api.registerSessionCatalog({
1391
+ id: "codex",
1392
+ label: "Codex",
1393
+ supportsProcessHomeIsolation: true,
1394
+ resolveCreateSession: ({ agentId }) => resolveCodexCatalogCreateSession(params.api.runtime.modelConfig, params.getRuntimeConfig() ?? params.api.config, agentId),
1395
+ list: async (query) => {
1396
+ const localTerminalAvailable = resolveLocalCodexTerminalExecutable() !== void 0;
1397
+ const { agentId: requestedAgentId, allowProcessHomeFallback, listNodes, onHost, waitUntil, signal, sessionEntries, ...gatewayQuery } = query;
1398
+ const agentId = resolveRequestAgentId(requestedAgentId);
1399
+ const localHomes = [...catalogHomes(agentId, allowProcessHomeFallback)];
1400
+ const mapHost = (host) => ({
1401
+ ...toGenericCatalogHost(host, localTerminalAvailable),
1402
+ canStartTerminal: host.kind === "gateway" ? localTerminalAvailable && host.hostId === "gateway:local" && localHomes.some((home) => home.hostId === host.hostId && home.appServer.start.transport === "stdio") : host.canStartTerminal === true
1403
+ });
1404
+ return (await listCodexSessionCatalog({
1405
+ agentId,
1406
+ bindingStore: params.bindingStore,
1407
+ config: params.getRuntimeConfig(),
1408
+ runtime: params.api.runtime,
1409
+ control: params.control,
1410
+ query: gatewayQuery,
1411
+ listNodes,
1412
+ waitUntil,
1413
+ signal,
1414
+ sessionEntries,
1415
+ localHomes,
1416
+ ...onHost ? { onHost: (host) => onHost(mapHost(host)) } : {}
1417
+ })).hosts.map(mapHost);
1418
+ },
1419
+ read: async (request) => {
1420
+ const { agentId, source, control } = bindRequest(request);
1421
+ return await readCodexSessionTranscript({
1422
+ agentId,
1423
+ runtime: params.api.runtime,
1424
+ control,
1425
+ hostId: request.hostId,
1426
+ threadId: request.threadId,
1427
+ cursor: request.cursor,
1428
+ limit: request.limit ?? 20,
1429
+ ...source ? { source } : {}
1430
+ });
1431
+ },
1432
+ continueSession: async (request) => {
1433
+ const config = params.getRuntimeConfig();
1434
+ if (!config) throw new Error("OpenClaw runtime config is unavailable");
1435
+ if (request.hostId.startsWith("node:")) return await continueNodeCodexSession({
1436
+ agentId: resolveRequestAgentId(request.agentId),
1437
+ api: params.api,
1438
+ config,
1439
+ hostId: request.hostId,
1440
+ threadId: request.threadId,
1441
+ clientScopes: request.clientScopes
1442
+ });
1443
+ if (!isLocalCodexCatalogHost(request.hostId)) throw new CatalogParamsError("Codex session catalog hostId is invalid");
1444
+ const { agentId, source, control } = bindLocalRequest(request);
1445
+ let upstreamBaseline;
1446
+ const continued = await continueLocalCodexSession({
1447
+ agentId,
1448
+ api: params.api,
1449
+ bindingStore: params.bindingStore,
1450
+ config,
1451
+ control,
1452
+ threadId: request.threadId,
1453
+ hostId: source.hostId,
1454
+ sourceHomeId: source.sourceHomeId,
1455
+ ...source.hostId === "gateway:local" ? { allowLegacy: true } : {},
1456
+ onContinued: (baseline) => {
1457
+ upstreamBaseline = baseline;
1458
+ }
1459
+ });
1460
+ return codexUpstreamContinueResult(continued.sessionKey, request.threadId, upstreamBaseline);
1461
+ },
1462
+ checkUpstreamActivity: (probes, policy) => checkUpstreamActivity(probes.filter((probe) => !isLocalCodexCatalogHost(probe.hostId) || policy?.allowProcessHomeFallback !== false || catalogHomes(probe.agentId, false).some((home) => home.hostId === probe.hostId))),
1463
+ archive: async (request) => {
1464
+ if (request.confirmNoOtherRunner !== true) throw new CatalogParamsError("archive requires confirmation that no other runner is active");
1465
+ if (!isLocalCodexCatalogHost(request.hostId)) throw new CatalogParamsError("paired-node Codex sessions are view-only");
1466
+ const config = params.getRuntimeConfig();
1467
+ if (!config) throw new Error("OpenClaw runtime config is unavailable");
1468
+ const { agentId, source, control } = bindLocalRequest(request);
1469
+ await archiveLocalCodexSession({
1470
+ agentId,
1471
+ bindingStore: params.bindingStore,
1472
+ config,
1473
+ control,
1474
+ runtime: params.api.runtime,
1475
+ threadId: request.threadId,
1476
+ hostId: source.hostId,
1477
+ sourceHomeId: source.sourceHomeId,
1478
+ ...source.hostId === "gateway:local" ? { allowLegacy: true } : {}
1479
+ });
1480
+ return { ok: true };
1481
+ },
1482
+ openTerminal: async (request) => {
1483
+ const { agentId, source, control } = bindRequest(request);
1484
+ return await openCodexCatalogTerminal({
1485
+ api: params.api,
1486
+ control,
1487
+ getPluginConfig: params.getPluginConfig,
1488
+ getRuntimeConfig: params.getRuntimeConfig,
1489
+ resolveRuntimeOptions: params.resolveRuntimeOptions,
1490
+ ...source ? { source } : {},
1491
+ ...request,
1492
+ agentId
1493
+ });
1494
+ },
1495
+ startTerminalSession: async (request) => {
1496
+ if (!request.nodeId && request.hostId && request.hostId !== "gateway:local") throw new CatalogParamsError("Codex terminal host is unavailable; select the local machine or a connected node");
1497
+ const source = request.nodeId ? void 0 : resolveLocalCatalogHomeForThread({
1498
+ homes: [...catalogHomes(request.agentId, request.allowProcessHomeFallback)],
1499
+ hostId: request.hostId ?? "gateway:local"
1500
+ });
1501
+ if (source && source.appServer.start.transport !== "stdio") throw new CatalogParamsError("Native terminal start requires a local Codex source");
1502
+ return await startCodexCatalogTerminal({
1503
+ getPluginConfig: params.getPluginConfig,
1504
+ getRuntimeConfig: params.getRuntimeConfig,
1505
+ resolveRuntimeOptions: params.resolveRuntimeOptions,
1506
+ ...request,
1507
+ source
1508
+ });
1509
+ }
1510
+ });
1511
+ }
1512
+ const codexSessionCatalogRuntime = {
1513
+ register: registerCodexSessionCatalog,
1514
+ list: listCodexSessionCatalog,
1515
+ readTranscript: readCodexSessionTranscript,
1516
+ continueLocal: continueLocalCodexSession,
1517
+ continueNode: continueNodeCodexSession,
1518
+ archiveLocal: archiveLocalCodexSession
1519
+ };
1520
+ async function continueLocalCodexSession(...args) {
1521
+ const { continueLocalCodexSession: run } = await import("./session-catalog-adoption-BKLtSrwi.js");
1522
+ return run(...args);
1523
+ }
1524
+ async function archiveLocalCodexSession(...args) {
1525
+ const { archiveLocalCodexSession: run } = await import("./session-catalog-archive-D0i2pGj2.js");
1526
+ return run(...args);
1527
+ }
1528
+ async function continueNodeCodexSession(...args) {
1529
+ const { continueNodeCodexSession: run } = await import("./session-catalog-node-continue-CBtc4wkI.js");
1530
+ return run(...args);
1531
+ }
1532
+ //#endregion
1533
+ export { lookupNodeCodexCatalogRecord as a, createCodexSessionCatalogNodeHostCommands as i, createCodexSessionCatalogNodeInvokePolicies as n, createCodexSessionCatalogControl as r, codexSessionCatalogRuntime as t };