@openclaw/codex 2026.7.1-beta.2 → 2026.7.1-beta.5

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 (39) hide show
  1. package/dist/{app-server-policy-B7hqD3Xj.js → app-server-policy-BUk0GLMy.js} +5 -5
  2. package/dist/{attempt-notifications-tqyQ_Tdn.js → attempt-notifications-BGsEIIDI.js} +5 -40
  3. package/dist/{command-handlers-C9K-KRU-.js → command-handlers-UVniG5Hl.js} +267 -232
  4. package/dist/command-rpc-BjgEPh19.js +784 -0
  5. package/dist/compact-CZzbcygx.js +603 -0
  6. package/dist/{computer-use-CpurU-G9.js → computer-use-DDeySrnb.js} +3 -3
  7. package/dist/{config-C_whBx3M.js → config-CYEDnLJ2.js} +36 -15
  8. package/dist/conversation-binding-data-BHRpYbX3.js +121 -0
  9. package/dist/doctor-contract-api.js +439 -22
  10. package/dist/harness.js +29 -10
  11. package/dist/index.js +1117 -19
  12. package/dist/{media-understanding-provider-BOeoBhEw.js → media-understanding-provider-DgqRvU2_.js} +13 -8
  13. package/dist/media-understanding-provider.js +1 -1
  14. package/dist/{models-DpzY1xpp.js → models-DDmO1zwd.js} +2 -2
  15. package/dist/notification-correlation-Bo7KB3ks.js +35 -0
  16. package/dist/{plugin-app-cache-key-BrZUG9jj.js → plugin-app-cache-key-o-AHbdaf.js} +8 -4
  17. package/dist/{protocol-dh-ETiNd.js → protocol-2POPqAY4.js} +2 -1
  18. package/dist/{protocol-validators-CJiWigAJ.js → protocol-validators-dZQ-UTOa.js} +116 -59
  19. package/dist/{provider-capabilities-wqedK49Z.js → provider-capabilities-gTCwjfmh.js} +2916 -114
  20. package/dist/{provider-nmtMDcGH.js → provider-cc_62eQE.js} +19 -10
  21. package/dist/provider.js +2 -2
  22. package/dist/{request-BQuSQF29.js → request-BcJyl8KL.js} +2 -2
  23. package/dist/{run-attempt-DikbXia_.js → run-attempt-8SPLiDlT.js} +907 -3002
  24. package/dist/{sandbox-guard-pTY2COoC.js → sandbox-guard-DA2TQfZW.js} +3 -3
  25. package/dist/session-binding-Dc03iwRF.js +595 -0
  26. package/dist/session-binding-meta-B7aEMU7g.js +6 -0
  27. package/dist/{shared-client-rR6TDJA3.js → shared-client-4ICy3U6d.js} +892 -103
  28. package/dist/{side-question-Ca9wqmd0.js → side-question-DkjXvYv7.js} +132 -140
  29. package/dist/{thread-lifecycle-D6R40plk.js → thread-lifecycle-BskXnNP-.js} +609 -444
  30. package/dist/{web-search-provider.runtime-B6eZEFmd.js → web-search-provider.runtime-B5F42P7x.js} +3 -3
  31. package/npm-shrinkwrap.json +34 -34
  32. package/openclaw.plugin.json +20 -0
  33. package/package.json +9 -6
  34. package/dist/client-IcTBKEqA.js +0 -732
  35. package/dist/client-factory-DfFu9JH_.js +0 -15
  36. package/dist/compact-CILptrPS.js +0 -278
  37. package/dist/conversation-binding-DOJtUxOy.js +0 -1570
  38. package/dist/rate-limit-cache-C7qmZ0Jh.js +0 -26
  39. package/dist/session-binding-Cm0Gg7Z1.js +0 -339
@@ -0,0 +1,784 @@
1
+ import { d as resolveCodexAppServerRuntimeOptions, m as resolveCodexModelBackedReviewerPolicyContext, o as isCodexFastServiceTier } from "./config-CYEDnLJ2.js";
2
+ import { n as listCodexAppServerModels } from "./models-DDmO1zwd.js";
3
+ import { d as resolveCodexAppServerRequestModelSelection, p as resolveCodexBindingModelProviderFallback } from "./thread-lifecycle-BskXnNP-.js";
4
+ import { a as getLeasedSharedCodexAppServerClient, o as releaseLeasedSharedCodexAppServerClient } from "./shared-client-4ICy3U6d.js";
5
+ import { i as normalizeCodexAppServerBindingModelProvider, n as bindingStoreKey, r as isCodexAppServerNativeAuthProfile } from "./session-binding-Dc03iwRF.js";
6
+ import { i as describeControlFailure, r as CODEX_CONTROL_METHODS } from "./plugin-app-cache-key-o-AHbdaf.js";
7
+ import { a as formatCodexDisplayText } from "./app-server-policy-BUk0GLMy.js";
8
+ import { t as requestCodexAppServerJson } from "./request-BcJyl8KL.js";
9
+ import fs from "node:fs/promises";
10
+ import path from "node:path";
11
+ import { timestampMsToIsoString } from "openclaw/plugin-sdk/number-runtime";
12
+ import { resolvePreferredOpenClawTmpDir } from "openclaw/plugin-sdk/temp-path";
13
+ import { truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
14
+ import os from "node:os";
15
+ import { isRecord } from "openclaw/plugin-sdk/string-coerce-runtime";
16
+ import { materializeWindowsSpawnProgram, resolveWindowsSpawnProgram } from "openclaw/plugin-sdk/windows-spawn";
17
+ import { spawn } from "node:child_process";
18
+ import process from "node:process";
19
+ //#region extensions/codex/src/command-authorization.ts
20
+ const CODEX_NATIVE_EXECUTION_AUTH_ERROR = "Only an owner or operator.admin can control Codex native execution.";
21
+ function canMutateCodexHost(ctx) {
22
+ return ctx.senderIsOwner === true || ctx.gatewayClientScopes?.includes("operator.admin") === true;
23
+ }
24
+ //#endregion
25
+ //#region extensions/codex/src/conversation-control.ts
26
+ const CODEX_CONVERSATION_CONTROL_STATE = Symbol.for("openclaw.codex.conversationControl");
27
+ function getActiveTurns() {
28
+ const globalState = globalThis;
29
+ globalState[CODEX_CONVERSATION_CONTROL_STATE] ??= /* @__PURE__ */ new Map();
30
+ return globalState[CODEX_CONVERSATION_CONTROL_STATE];
31
+ }
32
+ function trackCodexConversationActiveTurn(active) {
33
+ const activeTurns = getActiveTurns();
34
+ const key = bindingStoreKey(active.identity);
35
+ activeTurns.set(key, active);
36
+ return () => {
37
+ if (activeTurns.get(key)?.turnId === active.turnId) activeTurns.delete(key);
38
+ };
39
+ }
40
+ function readCodexConversationActiveTurn(identity) {
41
+ return getActiveTurns().get(bindingStoreKey(identity));
42
+ }
43
+ async function stopCodexConversationTurn(params) {
44
+ const active = readCodexConversationActiveTurn(params.identity);
45
+ if (!active) return {
46
+ stopped: false,
47
+ message: "No active Codex run to stop."
48
+ };
49
+ const runtime = resolveCodexAppServerRuntimeOptions({ pluginConfig: params.pluginConfig });
50
+ const lookup = buildBindingLookup(params);
51
+ const binding = await params.bindingStore.read(params.identity);
52
+ const client = await getLeasedSharedCodexAppServerClient({
53
+ startOptions: runtime.start,
54
+ timeoutMs: runtime.requestTimeoutMs,
55
+ authProfileId: binding?.authProfileId,
56
+ ...lookup
57
+ });
58
+ try {
59
+ await client.request("turn/interrupt", {
60
+ threadId: active.threadId,
61
+ turnId: active.turnId
62
+ }, { timeoutMs: runtime.requestTimeoutMs });
63
+ } finally {
64
+ releaseLeasedSharedCodexAppServerClient(client);
65
+ }
66
+ return {
67
+ stopped: true,
68
+ message: "Codex stop requested."
69
+ };
70
+ }
71
+ async function steerCodexConversationTurn(params) {
72
+ const active = readCodexConversationActiveTurn(params.identity);
73
+ const text = params.message.trim();
74
+ if (!text) return {
75
+ steered: false,
76
+ message: "Usage: /codex steer <message>"
77
+ };
78
+ if (!active) return {
79
+ steered: false,
80
+ message: "No active Codex run to steer."
81
+ };
82
+ const runtime = resolveCodexAppServerRuntimeOptions({ pluginConfig: params.pluginConfig });
83
+ const lookup = buildBindingLookup(params);
84
+ const binding = await params.bindingStore.read(params.identity);
85
+ const client = await getLeasedSharedCodexAppServerClient({
86
+ startOptions: runtime.start,
87
+ timeoutMs: runtime.requestTimeoutMs,
88
+ authProfileId: binding?.authProfileId,
89
+ ...lookup
90
+ });
91
+ try {
92
+ await client.request("turn/steer", {
93
+ threadId: active.threadId,
94
+ expectedTurnId: active.turnId,
95
+ input: [{
96
+ type: "text",
97
+ text,
98
+ text_elements: []
99
+ }]
100
+ }, { timeoutMs: runtime.requestTimeoutMs });
101
+ } finally {
102
+ releaseLeasedSharedCodexAppServerClient(client);
103
+ }
104
+ return {
105
+ steered: true,
106
+ message: "Sent steer message to Codex."
107
+ };
108
+ }
109
+ async function setCodexConversationModel(params) {
110
+ const model = params.model.trim();
111
+ if (!model) return "Usage: /codex model <model>";
112
+ const lookup = buildBindingLookup(params);
113
+ const binding = await requireThreadBinding(params.bindingStore, params.identity);
114
+ const reviewerPolicyContext = resolveCodexModelBackedReviewerPolicyContext({
115
+ provider: "codex",
116
+ model,
117
+ bindingModelProvider: binding.modelProvider,
118
+ bindingModel: binding.model,
119
+ nativeAuthProfile: isCodexAppServerNativeAuthProfile({
120
+ authProfileId: binding.authProfileId,
121
+ ...lookup
122
+ })
123
+ });
124
+ const runtime = resolveCodexAppServerRuntimeOptions({
125
+ pluginConfig: params.pluginConfig,
126
+ modelProvider: reviewerPolicyContext.modelProvider,
127
+ model: reviewerPolicyContext.model,
128
+ config: params.config,
129
+ agentDir: params.agentDir
130
+ });
131
+ const modelSelection = resolveCodexAppServerRequestModelSelection({
132
+ model,
133
+ modelProvider: resolveConversationControlModelProvider({
134
+ authProfileId: binding.authProfileId,
135
+ bindingModel: binding.model,
136
+ bindingModelProvider: binding.modelProvider,
137
+ currentModel: model,
138
+ ...lookup
139
+ }),
140
+ authProfileId: binding.authProfileId,
141
+ ...lookup
142
+ });
143
+ const response = await resumeThreadWithOverrides({
144
+ runtime,
145
+ threadId: binding.threadId,
146
+ authProfileId: binding.authProfileId,
147
+ ...lookup,
148
+ model: modelSelection.model,
149
+ modelProvider: modelSelection.modelProvider
150
+ });
151
+ const nextModel = response.model ?? modelSelection.model;
152
+ const nextModelProvider = normalizeCodexAppServerBindingModelProvider({
153
+ authProfileId: binding.authProfileId,
154
+ modelProvider: response.modelProvider ?? modelSelection.modelProvider,
155
+ ...lookup
156
+ });
157
+ const modelChanged = nextModel !== binding.model || nextModelProvider !== binding.modelProvider;
158
+ await patchThreadBinding(params.bindingStore, params.identity, binding.threadId, {
159
+ cwd: response.thread.cwd ?? binding.cwd,
160
+ model: nextModel,
161
+ modelProvider: nextModelProvider,
162
+ ...modelChanged && binding.contextEngine?.projection ? { contextEngine: {
163
+ ...binding.contextEngine,
164
+ projection: void 0
165
+ } } : {},
166
+ approvalPolicy: binding.approvalPolicy,
167
+ sandbox: binding.sandbox,
168
+ serviceTier: binding.serviceTier ?? runtime.serviceTier ?? void 0
169
+ });
170
+ return `Codex model set to ${formatCodexDisplayText(response.model ?? model)}.`;
171
+ }
172
+ async function setCodexConversationFastMode(params) {
173
+ const binding = await requireThreadBinding(params.bindingStore, params.identity);
174
+ if (params.enabled == null) return `Codex fast mode: ${isCodexFastServiceTier(binding.serviceTier) ? "on" : "off"}.`;
175
+ const serviceTier = params.enabled ? "priority" : "flex";
176
+ await patchThreadBinding(params.bindingStore, params.identity, binding.threadId, { serviceTier });
177
+ return `Codex fast mode ${params.enabled ? "enabled" : "disabled"}.`;
178
+ }
179
+ async function setCodexConversationPermissions(params) {
180
+ const binding = await requireThreadBinding(params.bindingStore, params.identity);
181
+ if (!params.mode) return `Codex permissions: ${formatPermissionsMode(binding)}.`;
182
+ const policy = permissionsForMode(params.mode);
183
+ await patchThreadBinding(params.bindingStore, params.identity, binding.threadId, {
184
+ approvalPolicy: policy.approvalPolicy,
185
+ sandbox: policy.sandbox
186
+ });
187
+ return `Codex permissions set to ${params.mode === "yolo" ? "full access" : "default"}.`;
188
+ }
189
+ function parseCodexFastModeArg(arg) {
190
+ const normalized = arg?.trim().toLowerCase();
191
+ if (!normalized || normalized === "status") return;
192
+ if (normalized === "on" || normalized === "true" || normalized === "fast") return true;
193
+ if (normalized === "off" || normalized === "false" || normalized === "flex") return false;
194
+ }
195
+ function parseCodexPermissionsModeArg(arg) {
196
+ const normalized = arg?.trim().toLowerCase();
197
+ if (!normalized || normalized === "status") return;
198
+ if (normalized === "yolo" || normalized === "full" || normalized === "full-access") return "yolo";
199
+ if (normalized === "default" || normalized === "guardian") return "default";
200
+ }
201
+ function formatPermissionsMode(binding) {
202
+ return binding.approvalPolicy === "never" && binding.sandbox === "danger-full-access" ? "full access" : "default";
203
+ }
204
+ async function requireThreadBinding(bindingStore, identity) {
205
+ const binding = await bindingStore.read(identity);
206
+ if (!binding?.threadId) throw new Error("No Codex thread is attached to this OpenClaw session yet.");
207
+ return binding;
208
+ }
209
+ async function patchThreadBinding(bindingStore, identity, threadId, patch) {
210
+ if (!await bindingStore.mutate(identity, {
211
+ kind: "patch",
212
+ threadId,
213
+ patch
214
+ })) throw new Error("Codex thread binding changed while applying the control update.");
215
+ }
216
+ async function resumeThreadWithOverrides(params) {
217
+ const runtime = params.runtime;
218
+ const client = await getLeasedSharedCodexAppServerClient({
219
+ startOptions: runtime.start,
220
+ timeoutMs: runtime.requestTimeoutMs,
221
+ authProfileId: params.authProfileId,
222
+ ...buildBindingLookup(params)
223
+ });
224
+ try {
225
+ return await client.request(CODEX_CONTROL_METHODS.resumeThread, {
226
+ threadId: params.threadId,
227
+ ...params.model ? { model: params.model } : {},
228
+ ...params.modelProvider ? { modelProvider: params.modelProvider } : {},
229
+ approvalPolicy: params.approvalPolicy ?? runtime.approvalPolicy,
230
+ sandbox: params.sandbox ?? runtime.sandbox,
231
+ approvalsReviewer: runtime.approvalsReviewer,
232
+ ...params.serviceTier ? { serviceTier: params.serviceTier } : {}
233
+ }, { timeoutMs: runtime.requestTimeoutMs });
234
+ } finally {
235
+ releaseLeasedSharedCodexAppServerClient(client);
236
+ }
237
+ }
238
+ function buildBindingLookup(params) {
239
+ const agentDir = params.agentDir?.trim();
240
+ return {
241
+ ...agentDir ? { agentDir } : {},
242
+ ...params.config ? { config: params.config } : {}
243
+ };
244
+ }
245
+ function resolveConversationControlModelProvider(params) {
246
+ const modelProvider = resolveCodexBindingModelProviderFallback({
247
+ currentModel: params.currentModel,
248
+ bindingModel: params.bindingModel,
249
+ bindingModelProvider: params.bindingModelProvider
250
+ })?.trim();
251
+ if (!modelProvider || modelProvider.toLowerCase() === "codex") return;
252
+ if (isCodexAppServerNativeAuthProfile(params) && modelProvider.toLowerCase() === "openai") return;
253
+ return modelProvider.toLowerCase() === "openai" ? "openai" : modelProvider;
254
+ }
255
+ function permissionsForMode(mode) {
256
+ return mode === "yolo" ? {
257
+ approvalPolicy: "never",
258
+ sandbox: "danger-full-access"
259
+ } : {
260
+ approvalPolicy: "on-request",
261
+ sandbox: "workspace-write"
262
+ };
263
+ }
264
+ //#endregion
265
+ //#region extensions/codex/src/node-cli-sessions.ts
266
+ const CODEX_CLI_SESSIONS_LIST_COMMAND = "codex.cli.sessions.list";
267
+ const CODEX_CLI_SESSION_RESUME_COMMAND = "codex.cli.session.resume";
268
+ const DEFAULT_SESSION_LIMIT = 10;
269
+ const MAX_SESSION_LIMIT = 50;
270
+ const DEFAULT_RESUME_TIMEOUT_MS = 20 * 6e4;
271
+ const SESSION_ID_PATTERN = /^[A-Za-z0-9._:-]{1,128}$/;
272
+ const activeResumeSessions = /* @__PURE__ */ new Set();
273
+ const DEFAULT_RESUME_SPAWN_RUNTIME = {
274
+ platform: process.platform,
275
+ env: process.env,
276
+ execPath: process.execPath
277
+ };
278
+ function createCodexCliSessionNodeHostCommands() {
279
+ return [{
280
+ command: CODEX_CLI_SESSIONS_LIST_COMMAND,
281
+ cap: "codex-cli-sessions",
282
+ handle: listLocalCodexCliSessions
283
+ }, {
284
+ command: CODEX_CLI_SESSION_RESUME_COMMAND,
285
+ cap: "codex-cli-sessions",
286
+ dangerous: true,
287
+ handle: resumeLocalCodexCliSession
288
+ }];
289
+ }
290
+ function createCodexCliSessionNodeInvokePolicies() {
291
+ return [{
292
+ commands: [CODEX_CLI_SESSIONS_LIST_COMMAND],
293
+ defaultPlatforms: [
294
+ "macos",
295
+ "linux",
296
+ "windows"
297
+ ],
298
+ handle: (ctx) => ctx.invokeNode()
299
+ }, {
300
+ commands: [CODEX_CLI_SESSION_RESUME_COMMAND],
301
+ dangerous: true,
302
+ handle: (ctx) => ctx.invokeNode()
303
+ }];
304
+ }
305
+ async function listCodexCliSessionsOnNode(params) {
306
+ const node = await resolveCodexCliNode({
307
+ runtime: params.runtime,
308
+ requestedNode: params.requestedNode,
309
+ command: CODEX_CLI_SESSIONS_LIST_COMMAND
310
+ });
311
+ return {
312
+ node,
313
+ result: parseCodexCliSessionsListResult(await params.runtime.nodes.invoke({
314
+ nodeId: readNodeId(node),
315
+ command: CODEX_CLI_SESSIONS_LIST_COMMAND,
316
+ params: {
317
+ limit: params.limit,
318
+ filter: params.filter
319
+ },
320
+ timeoutMs: 15e3
321
+ }))
322
+ };
323
+ }
324
+ async function resolveCodexCliSessionForBindingOnNode(params) {
325
+ const listing = await listCodexCliSessionsOnNode({
326
+ runtime: params.runtime,
327
+ requestedNode: params.requestedNode,
328
+ filter: params.sessionId,
329
+ limit: MAX_SESSION_LIMIT
330
+ });
331
+ if (!listing.node.commands?.includes("codex.cli.session.resume")) throw new Error(`Node ${formatNodeLabel(listing.node)} does not expose ${CODEX_CLI_SESSION_RESUME_COMMAND}.`);
332
+ return {
333
+ node: listing.node,
334
+ session: listing.result.sessions.find((session) => session.sessionId === params.sessionId)
335
+ };
336
+ }
337
+ async function resumeCodexCliSessionOnNode(params) {
338
+ const payload = unwrapNodeInvokePayload(await params.runtime.nodes.invoke({
339
+ nodeId: params.nodeId,
340
+ command: CODEX_CLI_SESSION_RESUME_COMMAND,
341
+ params: {
342
+ sessionId: params.sessionId,
343
+ prompt: params.prompt,
344
+ cwd: params.cwd,
345
+ timeoutMs: params.timeoutMs
346
+ },
347
+ timeoutMs: (params.timeoutMs ?? DEFAULT_RESUME_TIMEOUT_MS) + 5e3
348
+ }));
349
+ if (!isRecord(payload) || payload.ok !== true || typeof payload.text !== "string") throw new Error("Codex CLI resume returned an invalid payload.");
350
+ return {
351
+ ok: true,
352
+ sessionId: typeof payload.sessionId === "string" ? payload.sessionId : params.sessionId,
353
+ text: payload.text
354
+ };
355
+ }
356
+ function formatCodexCliSessions(params) {
357
+ if (params.result.sessions.length === 0) return `No Codex CLI sessions returned from ${formatCodexDisplayText(formatNodeLabel(params.node))}.`;
358
+ return [`Codex CLI sessions on ${formatCodexDisplayText(formatNodeLabel(params.node))}:`, ...params.result.sessions.map((session) => {
359
+ const details = [session.cwd, session.updatedAt].filter((value) => Boolean(value));
360
+ 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`;
361
+ })].join("\n");
362
+ }
363
+ async function listLocalCodexCliSessions(paramsJSON) {
364
+ const params = readRecordParam(paramsJSON);
365
+ const limit = normalizeLimit(params.limit);
366
+ const filter = typeof params.filter === "string" ? params.filter.trim().toLowerCase() : "";
367
+ const codexHome = resolveCodexHome();
368
+ const summaries = await readHistorySessions(codexHome);
369
+ await hydrateSessionFiles(codexHome, summaries);
370
+ await hydrateSessionsFromSessionFiles(codexHome, summaries);
371
+ const sessions = [...summaries.values()].filter((session) => {
372
+ if (!filter) return true;
373
+ return [
374
+ session.sessionId,
375
+ session.cwd,
376
+ session.lastMessage
377
+ ].some((value) => value?.toLowerCase().includes(filter));
378
+ }).toSorted((a, b) => compareOptionalStringsDesc(a.updatedAt, b.updatedAt)).slice(0, limit);
379
+ return JSON.stringify({
380
+ sessions,
381
+ codexHome
382
+ });
383
+ }
384
+ async function resumeLocalCodexCliSession(paramsJSON) {
385
+ const params = readRecordParam(paramsJSON);
386
+ const sessionId = typeof params.sessionId === "string" ? params.sessionId.trim() : "";
387
+ const prompt = typeof params.prompt === "string" ? params.prompt.trim() : "";
388
+ if (!sessionId || !SESSION_ID_PATTERN.test(sessionId)) throw new Error("Missing or invalid Codex CLI session id.");
389
+ if (!prompt) throw new Error("Missing Codex CLI prompt.");
390
+ if (activeResumeSessions.has(sessionId)) throw new Error(`Codex CLI session ${sessionId} already has an active resume turn.`);
391
+ activeResumeSessions.add(sessionId);
392
+ try {
393
+ const text = await runCodexExecResume({
394
+ sessionId,
395
+ prompt,
396
+ cwd: typeof params.cwd === "string" && params.cwd.trim() ? params.cwd.trim() : void 0,
397
+ timeoutMs: normalizeTimeoutMs(params.timeoutMs)
398
+ });
399
+ return JSON.stringify({
400
+ ok: true,
401
+ sessionId,
402
+ text: text.trim() || "Codex completed without a text reply."
403
+ });
404
+ } finally {
405
+ activeResumeSessions.delete(sessionId);
406
+ }
407
+ }
408
+ async function runCodexExecResume(params) {
409
+ const outputPath = path.join(await fs.mkdtemp(path.join(resolvePreferredOpenClawTmpDir(), "openclaw-codex-cli-")), "last-message.txt");
410
+ try {
411
+ const invocation = resolveCodexCliResumeSpawnInvocation([
412
+ "exec",
413
+ "resume",
414
+ "--skip-git-repo-check",
415
+ "--output-last-message",
416
+ outputPath,
417
+ params.sessionId,
418
+ "-"
419
+ ], {
420
+ platform: process.platform,
421
+ env: process.env,
422
+ execPath: process.execPath
423
+ });
424
+ const child = spawn(invocation.command, invocation.args, {
425
+ cwd: params.cwd || process.cwd(),
426
+ stdio: [
427
+ "pipe",
428
+ "pipe",
429
+ "pipe"
430
+ ],
431
+ env: process.env,
432
+ shell: invocation.shell,
433
+ windowsHide: invocation.windowsHide
434
+ });
435
+ const stdout = [];
436
+ const stderr = [];
437
+ let timedOut = false;
438
+ let forceKillTimeout;
439
+ const timeout = setTimeout(() => {
440
+ timedOut = true;
441
+ child.kill("SIGTERM");
442
+ forceKillTimeout = setTimeout(() => child.kill("SIGKILL"), 2e3);
443
+ forceKillTimeout.unref?.();
444
+ }, params.timeoutMs);
445
+ child.stdout.on("data", (chunk) => stdout.push(chunk));
446
+ child.stderr.on("data", (chunk) => stderr.push(chunk));
447
+ child.stdin.end(params.prompt);
448
+ const exitCode = await new Promise((resolve, reject) => {
449
+ child.on("error", reject);
450
+ child.on("exit", (code) => resolve(code));
451
+ }).finally(() => {
452
+ clearTimeout(timeout);
453
+ if (forceKillTimeout) clearTimeout(forceKillTimeout);
454
+ });
455
+ if (timedOut) throw new Error(`codex exec resume timed out after ${String(params.timeoutMs)}ms`);
456
+ if (exitCode !== 0) {
457
+ const message = Buffer.concat(stderr).toString("utf8").trim() || Buffer.concat(stdout).toString("utf8").trim() || `codex exec resume exited with code ${String(exitCode)}`;
458
+ throw new Error(message);
459
+ }
460
+ return await fs.readFile(outputPath, "utf8");
461
+ } finally {
462
+ await fs.rm(path.dirname(outputPath), {
463
+ recursive: true,
464
+ force: true
465
+ });
466
+ }
467
+ }
468
+ function resolveCodexCliResumeSpawnInvocation(args, runtime = DEFAULT_RESUME_SPAWN_RUNTIME) {
469
+ const resolved = materializeWindowsSpawnProgram(resolveWindowsSpawnProgram({
470
+ command: "codex",
471
+ platform: runtime.platform,
472
+ env: runtime.env,
473
+ execPath: runtime.execPath,
474
+ packageName: "@openai/codex"
475
+ }), args);
476
+ return {
477
+ command: resolved.command,
478
+ args: resolved.argv,
479
+ shell: resolved.shell,
480
+ windowsHide: resolved.windowsHide
481
+ };
482
+ }
483
+ async function readHistorySessions(codexHome) {
484
+ const summaries = /* @__PURE__ */ new Map();
485
+ const content = await readFileIfExists(path.join(codexHome, "history.jsonl"));
486
+ if (!content) return summaries;
487
+ for (const line of content.split(/\r?\n/u)) {
488
+ const trimmed = line.trim();
489
+ if (!trimmed) continue;
490
+ let parsed;
491
+ try {
492
+ parsed = JSON.parse(trimmed);
493
+ } catch {
494
+ continue;
495
+ }
496
+ if (!isRecord(parsed) || typeof parsed.session_id !== "string") continue;
497
+ const sessionId = parsed.session_id.trim();
498
+ if (!sessionId) continue;
499
+ const entry = summaries.get(sessionId) ?? {
500
+ sessionId,
501
+ messageCount: 0
502
+ };
503
+ entry.messageCount += 1;
504
+ if (typeof parsed.text === "string" && parsed.text.trim()) entry.lastMessage = truncateText(parsed.text.trim(), 140);
505
+ if (typeof parsed.ts === "number") entry.updatedAt = timestampMsToIsoString(parsed.ts * 1e3) ?? entry.updatedAt;
506
+ summaries.set(sessionId, entry);
507
+ }
508
+ return summaries;
509
+ }
510
+ async function hydrateSessionFiles(codexHome, summaries) {
511
+ if (summaries.size === 0) return;
512
+ const files = await findSessionFiles(path.join(codexHome, "sessions"), 4);
513
+ const pending = new Set(summaries.keys());
514
+ for (const file of files) {
515
+ const basename = path.basename(file);
516
+ const sessionId = [...pending].find((id) => basename.includes(id));
517
+ if (!sessionId) continue;
518
+ const entry = summaries.get(sessionId);
519
+ if (!entry) continue;
520
+ entry.sessionFile = file;
521
+ const cwd = readSessionMetaCwd(await readFirstLine(file) ?? "");
522
+ if (cwd) entry.cwd = cwd;
523
+ pending.delete(sessionId);
524
+ if (pending.size === 0) return;
525
+ }
526
+ }
527
+ async function hydrateSessionsFromSessionFiles(codexHome, summaries) {
528
+ const files = await findSessionFiles(path.join(codexHome, "sessions"), 4);
529
+ for (const file of files) {
530
+ const summary = await readSessionFileSummary(file);
531
+ if (!summary) continue;
532
+ const existing = summaries.get(summary.sessionId);
533
+ summaries.set(summary.sessionId, {
534
+ ...summary,
535
+ ...existing,
536
+ cwd: existing?.cwd ?? summary.cwd,
537
+ sessionFile: existing?.sessionFile ?? summary.sessionFile,
538
+ updatedAt: existing?.updatedAt ?? summary.updatedAt,
539
+ lastMessage: existing?.lastMessage ?? summary.lastMessage,
540
+ messageCount: existing?.messageCount ?? summary.messageCount
541
+ });
542
+ }
543
+ }
544
+ async function readSessionFileSummary(file) {
545
+ const content = await readFileIfExists(file);
546
+ if (!content) return null;
547
+ let sessionId = "";
548
+ let cwd;
549
+ let updatedAt;
550
+ let lastMessage;
551
+ let messageCount = 0;
552
+ for (const line of content.split(/\r?\n/u)) {
553
+ const trimmed = line.trim();
554
+ if (!trimmed) continue;
555
+ let parsed;
556
+ try {
557
+ parsed = JSON.parse(trimmed);
558
+ } catch {
559
+ continue;
560
+ }
561
+ if (!isRecord(parsed)) continue;
562
+ if (typeof parsed.timestamp === "string" && parsed.timestamp.trim()) updatedAt = parsed.timestamp.trim();
563
+ if (parsed.type === "session_meta" && isRecord(parsed.payload)) {
564
+ if (typeof parsed.payload.id === "string" && parsed.payload.id.trim()) sessionId = parsed.payload.id.trim();
565
+ if (typeof parsed.payload.cwd === "string" && parsed.payload.cwd.trim()) cwd = parsed.payload.cwd.trim();
566
+ continue;
567
+ }
568
+ const messageText = readResponseItemMessageText(parsed);
569
+ if (messageText) {
570
+ messageCount += 1;
571
+ lastMessage = truncateText(messageText, 140);
572
+ }
573
+ }
574
+ if (!sessionId) sessionId = readSessionIdFromFilename(file) ?? "";
575
+ if (!sessionId) return null;
576
+ return {
577
+ sessionId,
578
+ updatedAt: updatedAt ?? await readFileMtimeIso(file),
579
+ lastMessage,
580
+ cwd,
581
+ sessionFile: file,
582
+ messageCount
583
+ };
584
+ }
585
+ async function findSessionFiles(dir, maxDepth) {
586
+ if (maxDepth < 0) return [];
587
+ let entries;
588
+ try {
589
+ entries = await fs.readdir(dir, { withFileTypes: true });
590
+ } catch {
591
+ return [];
592
+ }
593
+ const files = [];
594
+ for (const entry of entries) {
595
+ const entryPath = path.join(dir, entry.name);
596
+ if (entry.isDirectory()) files.push(...await findSessionFiles(entryPath, maxDepth - 1));
597
+ else if (entry.isFile() && entry.name.endsWith(".jsonl")) files.push(entryPath);
598
+ }
599
+ return files;
600
+ }
601
+ function readSessionMetaCwd(line) {
602
+ try {
603
+ const parsed = JSON.parse(line);
604
+ if (!isRecord(parsed) || parsed.type !== "session_meta" || !isRecord(parsed.payload)) return;
605
+ return typeof parsed.payload.cwd === "string" && parsed.payload.cwd.trim() ? parsed.payload.cwd.trim() : void 0;
606
+ } catch {
607
+ return;
608
+ }
609
+ }
610
+ function readResponseItemMessageText(parsed) {
611
+ if (parsed.type !== "response_item" || !isRecord(parsed.payload)) return;
612
+ if (parsed.payload.type !== "message") return;
613
+ if ((typeof parsed.payload.role === "string" ? parsed.payload.role : "") !== "user") return;
614
+ const parts = (Array.isArray(parsed.payload.content) ? parsed.payload.content : []).flatMap((entry) => {
615
+ if (!isRecord(entry)) return [];
616
+ const text = typeof entry.text === "string" ? entry.text : typeof entry.input_text === "string" ? entry.input_text : void 0;
617
+ return text?.trim() ? [text.trim()] : [];
618
+ });
619
+ return parts.length > 0 ? parts.join(" ") : void 0;
620
+ }
621
+ function readSessionIdFromFilename(file) {
622
+ return path.basename(file).match(/[0-9a-f]{8}-[0-9a-f-]{27,}/iu)?.[0];
623
+ }
624
+ async function resolveCodexCliNode(params) {
625
+ const list = await params.runtime.nodes.list(params.requestedNode ? void 0 : { connected: true });
626
+ const requested = params.requestedNode?.trim();
627
+ const candidates = list.nodes.filter((node) => {
628
+ if (requested) return [
629
+ node.nodeId,
630
+ node.displayName,
631
+ node.remoteIp
632
+ ].some((value) => value === requested);
633
+ return node.connected === true && node.commands?.includes(params.command);
634
+ });
635
+ if (candidates.length === 0) throw new Error(requested ? `Codex CLI node ${requested} was not found.` : "No connected node exposes Codex CLI session commands.");
636
+ const usable = candidates.filter((node) => node.commands?.includes(params.command));
637
+ if (usable.length === 0) throw new Error(`Node ${requested ?? "candidate"} does not expose ${params.command}.`);
638
+ if (usable.length > 1) throw new Error("Multiple Codex CLI-capable nodes connected. Pass --host <node-id>.");
639
+ return usable[0];
640
+ }
641
+ function parseCodexCliSessionsListResult(raw) {
642
+ const payload = unwrapNodeInvokePayload(raw);
643
+ if (!isRecord(payload) || !Array.isArray(payload.sessions)) throw new Error("Codex CLI session list returned an invalid payload.");
644
+ return {
645
+ codexHome: typeof payload.codexHome === "string" ? payload.codexHome : "",
646
+ sessions: payload.sessions.flatMap((entry) => {
647
+ if (!isRecord(entry) || typeof entry.sessionId !== "string") return [];
648
+ return [{
649
+ sessionId: entry.sessionId,
650
+ updatedAt: typeof entry.updatedAt === "string" ? entry.updatedAt : void 0,
651
+ lastMessage: typeof entry.lastMessage === "string" ? entry.lastMessage : void 0,
652
+ cwd: typeof entry.cwd === "string" ? entry.cwd : void 0,
653
+ sessionFile: typeof entry.sessionFile === "string" ? entry.sessionFile : void 0,
654
+ messageCount: typeof entry.messageCount === "number" && Number.isFinite(entry.messageCount) ? entry.messageCount : 0
655
+ }];
656
+ })
657
+ };
658
+ }
659
+ function unwrapNodeInvokePayload(raw) {
660
+ const record = isRecord(raw) ? raw : {};
661
+ if (typeof record.payloadJSON === "string" && record.payloadJSON.trim()) try {
662
+ return JSON.parse(record.payloadJSON);
663
+ } catch (error) {
664
+ throw new Error("Codex CLI node command returned malformed payloadJSON.", { cause: error });
665
+ }
666
+ if ("payload" in record) return record.payload;
667
+ return raw;
668
+ }
669
+ function readRecordParam(paramsJSON) {
670
+ if (!paramsJSON?.trim()) return {};
671
+ try {
672
+ const parsed = JSON.parse(paramsJSON);
673
+ return isRecord(parsed) ? parsed : {};
674
+ } catch {
675
+ return {};
676
+ }
677
+ }
678
+ function resolveCodexHome() {
679
+ return process.env.CODEX_HOME?.trim() || path.join(os.homedir(), ".codex");
680
+ }
681
+ async function readFileIfExists(file) {
682
+ try {
683
+ return await fs.readFile(file, "utf8");
684
+ } catch {
685
+ return;
686
+ }
687
+ }
688
+ async function readFirstLine(file) {
689
+ return (await readFileIfExists(file))?.split(/\r?\n/u)[0];
690
+ }
691
+ async function readFileMtimeIso(file) {
692
+ try {
693
+ return (await fs.stat(file)).mtime.toISOString();
694
+ } catch {
695
+ return;
696
+ }
697
+ }
698
+ function normalizeLimit(value) {
699
+ return typeof value === "number" && Number.isFinite(value) ? Math.min(MAX_SESSION_LIMIT, Math.max(1, Math.floor(value))) : DEFAULT_SESSION_LIMIT;
700
+ }
701
+ function normalizeTimeoutMs(value) {
702
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.min(60 * 6e4, Math.floor(value)) : DEFAULT_RESUME_TIMEOUT_MS;
703
+ }
704
+ function truncateText(value, max) {
705
+ if (value.length <= max) return value;
706
+ return `${truncateUtf16Safe(value, Math.max(0, max - 3))}...`;
707
+ }
708
+ function compareOptionalStringsDesc(a, b) {
709
+ return (b ?? "").localeCompare(a ?? "");
710
+ }
711
+ function readNodeId(node) {
712
+ if (!node.nodeId) throw new Error("Codex CLI node did not include a node id.");
713
+ return node.nodeId;
714
+ }
715
+ function formatNodeLabel(node) {
716
+ return [
717
+ node.displayName,
718
+ node.nodeId,
719
+ node.remoteIp
720
+ ].filter(Boolean).join(" / ") || "node";
721
+ }
722
+ //#endregion
723
+ //#region extensions/codex/src/command-rpc.ts
724
+ function requestOptions(pluginConfig, limit, config) {
725
+ const runtime = resolveCodexAppServerRuntimeOptions({ pluginConfig });
726
+ return {
727
+ limit,
728
+ timeoutMs: runtime.requestTimeoutMs,
729
+ startOptions: runtime.start,
730
+ config
731
+ };
732
+ }
733
+ async function codexControlRequest(pluginConfig, method, requestParams, options = {}) {
734
+ const runtime = resolveCodexAppServerRuntimeOptions({ pluginConfig });
735
+ return await requestCodexAppServerJson({
736
+ method,
737
+ requestParams,
738
+ timeoutMs: runtime.requestTimeoutMs,
739
+ startOptions: runtime.start,
740
+ config: options.config,
741
+ sessionKey: options.sessionKey,
742
+ sessionId: options.sessionId,
743
+ authProfileId: options.authProfileId,
744
+ agentDir: options.agentDir,
745
+ isolated: options.isolated
746
+ });
747
+ }
748
+ async function safeCodexControlRequest(pluginConfig, method, requestParams, options = {}) {
749
+ return await safeValue(async () => await codexControlRequest(pluginConfig, method, requestParams, options));
750
+ }
751
+ async function safeCodexModelList(pluginConfig, limit, config) {
752
+ return await safeValue(async () => await listCodexAppServerModels(requestOptions(pluginConfig, limit, config)));
753
+ }
754
+ async function readCodexStatusProbes(pluginConfig, config) {
755
+ const [models, account, limits, mcps, skills] = await Promise.all([
756
+ safeCodexModelList(pluginConfig, 20, config),
757
+ safeCodexControlRequest(pluginConfig, CODEX_CONTROL_METHODS.account, { refreshToken: false }, { config }),
758
+ safeCodexControlRequest(pluginConfig, CODEX_CONTROL_METHODS.rateLimits, void 0, { config }),
759
+ safeCodexControlRequest(pluginConfig, CODEX_CONTROL_METHODS.listMcpServers, { limit: 100 }, { config }),
760
+ safeCodexControlRequest(pluginConfig, CODEX_CONTROL_METHODS.listSkills, {}, { config })
761
+ ]);
762
+ return {
763
+ models,
764
+ account,
765
+ limits,
766
+ mcps,
767
+ skills
768
+ };
769
+ }
770
+ async function safeValue(read) {
771
+ try {
772
+ return {
773
+ ok: true,
774
+ value: await read()
775
+ };
776
+ } catch (error) {
777
+ return {
778
+ ok: false,
779
+ error: describeControlFailure(error)
780
+ };
781
+ }
782
+ }
783
+ //#endregion
784
+ export { canMutateCodexHost as S, setCodexConversationPermissions as _, createCodexCliSessionNodeHostCommands as a, trackCodexConversationActiveTurn as b, listCodexCliSessionsOnNode as c, formatPermissionsMode as d, parseCodexFastModeArg as f, setCodexConversationModel as g, setCodexConversationFastMode as h, safeCodexControlRequest as i, resolveCodexCliSessionForBindingOnNode as l, readCodexConversationActiveTurn as m, readCodexStatusProbes as n, createCodexCliSessionNodeInvokePolicies as o, parseCodexPermissionsModeArg as p, requestOptions as r, formatCodexCliSessions as s, codexControlRequest as t, resumeCodexCliSessionOnNode as u, steerCodexConversationTurn as v, CODEX_NATIVE_EXECUTION_AUTH_ERROR as x, stopCodexConversationTurn as y };