@openclaw/codex 2026.6.11 → 2026.7.1-1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/dist/{app-server-policy-BPTiVNsW.js → app-server-policy-C968Kgin.js} +5 -5
  2. package/dist/{attempt-notifications-BYnndyFl.js → attempt-notifications-BGsEIIDI.js} +29 -40
  3. package/dist/{command-handlers-DEPTJYk0.js → command-handlers-Dv-pzAmg.js} +278 -237
  4. package/dist/command-rpc-eLM_mtC7.js +784 -0
  5. package/dist/compact-4mVBriKT.js +603 -0
  6. package/dist/{computer-use-ClrJwoFp.js → computer-use-Bmaz333N.js} +3 -3
  7. package/dist/{config-CszD0vP3.js → config-CYEDnLJ2.js} +44 -18
  8. package/dist/conversation-binding-data-BHRpYbX3.js +121 -0
  9. package/dist/doctor-contract-api.js +590 -22
  10. package/dist/harness.js +29 -10
  11. package/dist/index.js +1134 -35
  12. package/dist/{media-understanding-provider-ZUQHN7gT.js → media-understanding-provider-BHOu9-Gg.js} +13 -8
  13. package/dist/media-understanding-provider.js +1 -1
  14. package/dist/{models-CAmfBWRl.js → models-DDmO1zwd.js} +2 -2
  15. package/dist/notification-correlation-Bo7KB3ks.js +35 -0
  16. package/dist/{plugin-app-cache-key-C9ILt7bl.js → plugin-app-cache-key-BrhVdeEf.js} +13 -5
  17. package/dist/{protocol-dh-ETiNd.js → protocol-2POPqAY4.js} +2 -1
  18. package/dist/{protocol-validators-B19q5BIX.js → protocol-validators-dZQ-UTOa.js} +205 -56
  19. package/dist/provider-capabilities-DzI8fgEu.js +6172 -0
  20. package/dist/provider-catalog.js +4 -2
  21. package/dist/{provider-B-OHpbD3.js → provider-zjPfx5Fs.js} +94 -23
  22. package/dist/provider.js +2 -2
  23. package/dist/{request-Dcd452Nk.js → request-BcJyl8KL.js} +2 -2
  24. package/dist/{run-attempt-CXxtFC9d.js → run-attempt-DNSNk_G8.js} +1250 -2992
  25. package/dist/{sandbox-guard-3tnjhjFb.js → sandbox-guard-DA2TQfZW.js} +5 -3
  26. package/dist/session-binding-C1ZXdP-x.js +627 -0
  27. package/dist/session-binding-meta-B7aEMU7g.js +6 -0
  28. package/dist/shared-client-4ICy3U6d.js +1853 -0
  29. package/dist/{side-question-C-DhgJOd.js → side-question-CMOpEhvY.js} +134 -142
  30. package/dist/{thread-lifecycle-DtT3-ehU.js → thread-lifecycle-qWE88Dn2.js} +803 -481
  31. package/dist/{web-search-provider.runtime-CkwxrXQj.js → web-search-provider.runtime-BSlriav6.js} +3 -3
  32. package/npm-shrinkwrap.json +34 -34
  33. package/openclaw.plugin.json +23 -3
  34. package/package.json +9 -6
  35. package/dist/client-CLrtWgrD.js +0 -729
  36. package/dist/client-factory-Bm6HsGob.js +0 -18
  37. package/dist/compact-aQJ0ZKhe.js +0 -278
  38. package/dist/conversation-binding-t0XMLz-j.js +0 -1557
  39. package/dist/provider-capabilities-D7hnTO76.js +0 -3201
  40. package/dist/rate-limit-cache-C7qmZ0Jh.js +0 -26
  41. package/dist/session-binding-HOuPt-E0.js +0 -338
  42. package/dist/shared-client-Dtx5i7Ez.js +0 -1013
@@ -1,1557 +0,0 @@
1
- import { n as isJsonObject } from "./protocol-dh-ETiNd.js";
2
- import { H as readCodexNotificationTurnId, V as readCodexNotificationThreadId, d as resolveCodexAppServerRequestModelSelection, p as resolveCodexBindingModelProviderFallback, t as CODEX_NATIVE_PERSONALITY_NONE } from "./thread-lifecycle-DtT3-ehU.js";
3
- import { d as resolveCodexAppServerRuntimeOptions, h as resolveOpenClawExecPolicyForCodexAppServer, i as codexSandboxPolicyForTurn, n as canUseCodexModelBackedApprovalsReviewerForModel, o as isCodexFastServiceTier, p as resolveCodexModelBackedReviewerPolicyContext } from "./config-CszD0vP3.js";
4
- import { r as assertCodexThreadStartResponse } from "./protocol-validators-B19q5BIX.js";
5
- import { a as normalizeCodexAppServerBindingModelProvider, i as isCodexAppServerNativeAuthProfile, l as writeCodexAppServerBinding, n as clearCodexAppServerBinding, o as readCodexAppServerBinding } from "./session-binding-HOuPt-E0.js";
6
- import { r as CODEX_CONTROL_METHODS } from "./plugin-app-cache-key-C9ILt7bl.js";
7
- import { a as formatCodexDisplayText, t as resolveCodexAppServerForModelProvider } from "./app-server-policy-BPTiVNsW.js";
8
- import { a as getLeasedSharedCodexAppServerClient, o as releaseLeasedSharedCodexAppServerClient, p as resolveCodexAppServerAuthProfileIdForAgent } from "./shared-client-Dtx5i7Ez.js";
9
- import { n as resolveCodexNativeExecutionBlock, r as resolveCodexNativeSandboxBlock } from "./sandbox-guard-3tnjhjFb.js";
10
- import fs from "node:fs/promises";
11
- import path from "node:path";
12
- import { resolveTimerTimeoutMs, timestampMsToIsoString } from "openclaw/plugin-sdk/number-runtime";
13
- import { resolvePreferredOpenClawTmpDir } from "openclaw/plugin-sdk/temp-path";
14
- import { asOptionalRecord, isRecord, normalizeSingleOrTrimmedStringList } from "openclaw/plugin-sdk/string-coerce-runtime";
15
- import os from "node:os";
16
- import { resolveSessionAgentIds } from "openclaw/plugin-sdk/agent-runtime";
17
- import { loadExecApprovals } from "openclaw/plugin-sdk/exec-approvals-runtime";
18
- import { materializeWindowsSpawnProgram, resolveWindowsSpawnProgram } from "openclaw/plugin-sdk/windows-spawn";
19
- import { formatErrorMessage, resolveSandboxContext } from "openclaw/plugin-sdk/agent-harness-runtime";
20
- import { spawn } from "node:child_process";
21
- import { loadSessionStore, resolveSessionStoreEntry, resolveStorePath } from "openclaw/plugin-sdk/session-store-runtime";
22
- import { fileURLToPath } from "node:url";
23
- import process$1 from "node:process";
24
- //#region extensions/codex/src/conversation-binding-data.ts
25
- const BINDING_DATA_VERSION = 1;
26
- function createCodexConversationBindingData(params) {
27
- const agentDir = params.agentDir?.trim();
28
- const agentId = params.agentId?.trim();
29
- return {
30
- kind: "codex-app-server-session",
31
- version: BINDING_DATA_VERSION,
32
- sessionFile: params.sessionFile,
33
- workspaceDir: params.workspaceDir,
34
- ...agentDir ? { agentDir } : {},
35
- ...agentId ? { agentId } : {}
36
- };
37
- }
38
- function createCodexCliNodeConversationBindingData(params) {
39
- const cwd = params.cwd?.trim();
40
- return {
41
- kind: "codex-cli-node-session",
42
- version: BINDING_DATA_VERSION,
43
- nodeId: params.nodeId,
44
- sessionId: params.sessionId,
45
- ...cwd ? { cwd } : {}
46
- };
47
- }
48
- function readCodexConversationBindingData(binding) {
49
- const data = binding?.data;
50
- if (!data || typeof data !== "object" || Array.isArray(data)) return;
51
- return readCodexConversationBindingDataRecord(data);
52
- }
53
- function readCodexConversationBindingDataRecord(data) {
54
- if (data.kind === "codex-cli-node-session") {
55
- if (data.version !== BINDING_DATA_VERSION || typeof data.nodeId !== "string" || !data.nodeId.trim() || typeof data.sessionId !== "string" || !data.sessionId.trim()) return;
56
- return {
57
- kind: "codex-cli-node-session",
58
- version: BINDING_DATA_VERSION,
59
- nodeId: data.nodeId.trim(),
60
- sessionId: data.sessionId.trim(),
61
- cwd: typeof data.cwd === "string" && data.cwd.trim() ? data.cwd.trim() : void 0
62
- };
63
- }
64
- if (data.kind !== "codex-app-server-session") return;
65
- if (data.version !== BINDING_DATA_VERSION || typeof data.sessionFile !== "string" || !data.sessionFile.trim()) return;
66
- return {
67
- kind: "codex-app-server-session",
68
- version: BINDING_DATA_VERSION,
69
- sessionFile: data.sessionFile,
70
- workspaceDir: typeof data.workspaceDir === "string" && data.workspaceDir.trim() ? data.workspaceDir : process$1.cwd(),
71
- agentDir: typeof data.agentDir === "string" && data.agentDir.trim() ? data.agentDir : void 0,
72
- agentId: typeof data.agentId === "string" && data.agentId.trim() ? data.agentId : void 0
73
- };
74
- }
75
- function resolveCodexDefaultWorkspaceDir(pluginConfig) {
76
- return readString$1(asOptionalRecord(asOptionalRecord(pluginConfig)?.appServer), "defaultWorkspaceDir") ?? process$1.cwd();
77
- }
78
- function readString$1(record, key) {
79
- const value = record?.[key];
80
- return typeof value === "string" && value.trim() ? value.trim() : void 0;
81
- }
82
- //#endregion
83
- //#region extensions/codex/src/conversation-control.ts
84
- const CODEX_CONVERSATION_CONTROL_STATE = Symbol.for("openclaw.codex.conversationControl");
85
- function getActiveTurns() {
86
- const globalState = globalThis;
87
- globalState[CODEX_CONVERSATION_CONTROL_STATE] ??= /* @__PURE__ */ new Map();
88
- return globalState[CODEX_CONVERSATION_CONTROL_STATE];
89
- }
90
- function trackCodexConversationActiveTurn(active) {
91
- const activeTurns = getActiveTurns();
92
- activeTurns.set(active.sessionFile, active);
93
- return () => {
94
- if (activeTurns.get(active.sessionFile)?.turnId === active.turnId) activeTurns.delete(active.sessionFile);
95
- };
96
- }
97
- function readCodexConversationActiveTurn(sessionFile) {
98
- return getActiveTurns().get(sessionFile);
99
- }
100
- async function stopCodexConversationTurn(params) {
101
- const active = readCodexConversationActiveTurn(params.sessionFile);
102
- if (!active) return {
103
- stopped: false,
104
- message: "No active Codex run to stop."
105
- };
106
- const runtime = resolveCodexAppServerRuntimeOptions({ pluginConfig: params.pluginConfig });
107
- const lookup = buildBindingLookup(params);
108
- const binding = await readCodexAppServerBinding(params.sessionFile, lookup);
109
- const client = await getLeasedSharedCodexAppServerClient({
110
- startOptions: runtime.start,
111
- timeoutMs: runtime.requestTimeoutMs,
112
- authProfileId: binding?.authProfileId,
113
- ...lookup
114
- });
115
- try {
116
- await client.request("turn/interrupt", {
117
- threadId: active.threadId,
118
- turnId: active.turnId
119
- }, { timeoutMs: runtime.requestTimeoutMs });
120
- } finally {
121
- releaseLeasedSharedCodexAppServerClient(client);
122
- }
123
- return {
124
- stopped: true,
125
- message: "Codex stop requested."
126
- };
127
- }
128
- async function steerCodexConversationTurn(params) {
129
- const active = readCodexConversationActiveTurn(params.sessionFile);
130
- const text = params.message.trim();
131
- if (!text) return {
132
- steered: false,
133
- message: "Usage: /codex steer <message>"
134
- };
135
- if (!active) return {
136
- steered: false,
137
- message: "No active Codex run to steer."
138
- };
139
- const runtime = resolveCodexAppServerRuntimeOptions({ pluginConfig: params.pluginConfig });
140
- const lookup = buildBindingLookup(params);
141
- const binding = await readCodexAppServerBinding(params.sessionFile, lookup);
142
- const client = await getLeasedSharedCodexAppServerClient({
143
- startOptions: runtime.start,
144
- timeoutMs: runtime.requestTimeoutMs,
145
- authProfileId: binding?.authProfileId,
146
- ...lookup
147
- });
148
- try {
149
- await client.request("turn/steer", {
150
- threadId: active.threadId,
151
- expectedTurnId: active.turnId,
152
- input: [{
153
- type: "text",
154
- text,
155
- text_elements: []
156
- }]
157
- }, { timeoutMs: runtime.requestTimeoutMs });
158
- } finally {
159
- releaseLeasedSharedCodexAppServerClient(client);
160
- }
161
- return {
162
- steered: true,
163
- message: "Sent steer message to Codex."
164
- };
165
- }
166
- async function setCodexConversationModel(params) {
167
- const model = params.model.trim();
168
- if (!model) return "Usage: /codex model <model>";
169
- const lookup = buildBindingLookup(params);
170
- const binding = await requireThreadBinding(params.sessionFile, lookup);
171
- const reviewerPolicyContext = resolveCodexModelBackedReviewerPolicyContext({
172
- provider: "codex",
173
- model,
174
- bindingModelProvider: binding.modelProvider,
175
- bindingModel: binding.model,
176
- nativeAuthProfile: isCodexAppServerNativeAuthProfile({
177
- authProfileId: binding.authProfileId,
178
- ...lookup
179
- })
180
- });
181
- const runtime = resolveCodexAppServerRuntimeOptions({
182
- pluginConfig: params.pluginConfig,
183
- modelProvider: reviewerPolicyContext.modelProvider,
184
- model: reviewerPolicyContext.model,
185
- config: params.config,
186
- agentDir: params.agentDir
187
- });
188
- const modelSelection = resolveCodexAppServerRequestModelSelection({
189
- model,
190
- modelProvider: resolveConversationControlModelProvider({
191
- authProfileId: binding.authProfileId,
192
- bindingModel: binding.model,
193
- bindingModelProvider: binding.modelProvider,
194
- currentModel: model,
195
- ...lookup
196
- }),
197
- authProfileId: binding.authProfileId,
198
- ...lookup
199
- });
200
- const response = await resumeThreadWithOverrides({
201
- runtime,
202
- threadId: binding.threadId,
203
- authProfileId: binding.authProfileId,
204
- ...lookup,
205
- model: modelSelection.model,
206
- modelProvider: modelSelection.modelProvider
207
- });
208
- await writeCodexAppServerBinding(params.sessionFile, {
209
- ...binding,
210
- cwd: response.thread.cwd ?? binding.cwd,
211
- model: response.model ?? modelSelection.model,
212
- modelProvider: response.modelProvider ?? modelSelection.modelProvider,
213
- approvalPolicy: binding.approvalPolicy,
214
- sandbox: binding.sandbox,
215
- serviceTier: binding.serviceTier ?? runtime.serviceTier ?? void 0
216
- }, lookup);
217
- return `Codex model set to ${formatCodexDisplayText(response.model ?? model)}.`;
218
- }
219
- async function setCodexConversationFastMode(params) {
220
- const lookup = buildBindingLookup(params);
221
- const binding = await requireThreadBinding(params.sessionFile, lookup);
222
- if (params.enabled == null) return `Codex fast mode: ${isCodexFastServiceTier(binding.serviceTier) ? "on" : "off"}.`;
223
- const serviceTier = params.enabled ? "priority" : "flex";
224
- await writeCodexAppServerBinding(params.sessionFile, {
225
- ...binding,
226
- serviceTier
227
- }, lookup);
228
- return `Codex fast mode ${params.enabled ? "enabled" : "disabled"}.`;
229
- }
230
- async function setCodexConversationPermissions(params) {
231
- const lookup = buildBindingLookup(params);
232
- const binding = await requireThreadBinding(params.sessionFile, lookup);
233
- if (!params.mode) return `Codex permissions: ${formatPermissionsMode(binding)}.`;
234
- const policy = permissionsForMode(params.mode);
235
- await writeCodexAppServerBinding(params.sessionFile, {
236
- ...binding,
237
- approvalPolicy: policy.approvalPolicy,
238
- sandbox: policy.sandbox
239
- }, lookup);
240
- return `Codex permissions set to ${params.mode === "yolo" ? "full access" : "default"}.`;
241
- }
242
- function parseCodexFastModeArg(arg) {
243
- const normalized = arg?.trim().toLowerCase();
244
- if (!normalized || normalized === "status") return;
245
- if (normalized === "on" || normalized === "true" || normalized === "fast") return true;
246
- if (normalized === "off" || normalized === "false" || normalized === "flex") return false;
247
- }
248
- function parseCodexPermissionsModeArg(arg) {
249
- const normalized = arg?.trim().toLowerCase();
250
- if (!normalized || normalized === "status") return;
251
- if (normalized === "yolo" || normalized === "full" || normalized === "full-access") return "yolo";
252
- if (normalized === "default" || normalized === "guardian") return "default";
253
- }
254
- function formatPermissionsMode(binding) {
255
- return binding.approvalPolicy === "never" && binding.sandbox === "danger-full-access" ? "full access" : "default";
256
- }
257
- async function requireThreadBinding(sessionFile, lookup = {}) {
258
- const binding = await readCodexAppServerBinding(sessionFile, lookup);
259
- if (!binding?.threadId) throw new Error("No Codex thread is attached to this OpenClaw session yet.");
260
- return binding;
261
- }
262
- async function resumeThreadWithOverrides(params) {
263
- const runtime = params.runtime;
264
- const client = await getLeasedSharedCodexAppServerClient({
265
- startOptions: runtime.start,
266
- timeoutMs: runtime.requestTimeoutMs,
267
- authProfileId: params.authProfileId,
268
- ...buildBindingLookup(params)
269
- });
270
- try {
271
- return await client.request(CODEX_CONTROL_METHODS.resumeThread, {
272
- threadId: params.threadId,
273
- ...params.model ? { model: params.model } : {},
274
- ...params.modelProvider ? { modelProvider: params.modelProvider } : {},
275
- approvalPolicy: params.approvalPolicy ?? runtime.approvalPolicy,
276
- sandbox: params.sandbox ?? runtime.sandbox,
277
- approvalsReviewer: runtime.approvalsReviewer,
278
- ...params.serviceTier ? { serviceTier: params.serviceTier } : {},
279
- persistExtendedHistory: true
280
- }, { timeoutMs: runtime.requestTimeoutMs });
281
- } finally {
282
- releaseLeasedSharedCodexAppServerClient(client);
283
- }
284
- }
285
- function buildBindingLookup(params) {
286
- const agentDir = params.agentDir?.trim();
287
- return {
288
- ...agentDir ? { agentDir } : {},
289
- ...params.config ? { config: params.config } : {}
290
- };
291
- }
292
- function resolveConversationControlModelProvider(params) {
293
- const modelProvider = resolveCodexBindingModelProviderFallback({
294
- currentModel: params.currentModel,
295
- bindingModel: params.bindingModel,
296
- bindingModelProvider: params.bindingModelProvider
297
- })?.trim();
298
- if (!modelProvider || modelProvider.toLowerCase() === "codex") return;
299
- if (isCodexAppServerNativeAuthProfile(params) && modelProvider.toLowerCase() === "openai") return;
300
- return modelProvider.toLowerCase() === "openai" ? "openai" : modelProvider;
301
- }
302
- function permissionsForMode(mode) {
303
- return mode === "yolo" ? {
304
- approvalPolicy: "never",
305
- sandbox: "danger-full-access"
306
- } : {
307
- approvalPolicy: "on-request",
308
- sandbox: "workspace-write"
309
- };
310
- }
311
- //#endregion
312
- //#region extensions/codex/src/conversation-turn-collector.ts
313
- const MAX_PENDING_NOTIFICATIONS_PER_TURN = 100;
314
- function createCodexConversationTurnCollector(threadId) {
315
- let turnId;
316
- let completed = false;
317
- let failedError;
318
- let timeout;
319
- const assistantTextByItem = /* @__PURE__ */ new Map();
320
- const assistantOrder = [];
321
- const pendingNotificationsByTurnId = /* @__PURE__ */ new Map();
322
- let resolveCompletion;
323
- let rejectCompletion;
324
- const rememberItem = (itemId) => {
325
- if (!assistantOrder.includes(itemId)) assistantOrder.push(itemId);
326
- };
327
- const collectReplyText = () => {
328
- return assistantOrder.map((itemId) => assistantTextByItem.get(itemId)?.trim()).filter((text) => Boolean(text)).at(-1) ?? "";
329
- };
330
- const clearWaitState = () => {
331
- if (timeout) {
332
- clearTimeout(timeout);
333
- timeout = void 0;
334
- }
335
- resolveCompletion = void 0;
336
- rejectCompletion = void 0;
337
- };
338
- const finish = () => {
339
- if (completed) return;
340
- completed = true;
341
- if (failedError) rejectCompletion?.(new Error(failedError));
342
- else resolveCompletion?.({ replyText: collectReplyText() });
343
- clearWaitState();
344
- };
345
- const handleNotification = (notification) => {
346
- const params = isJsonObject(notification.params) ? notification.params : void 0;
347
- if (!params || readCodexNotificationThreadId(params) !== threadId) return;
348
- if (!turnId) {
349
- const pendingTurnId = readNotificationTurnId(params);
350
- if (pendingTurnId) {
351
- const pending = pendingNotificationsByTurnId.get(pendingTurnId) ?? [];
352
- if (pending.length < MAX_PENDING_NOTIFICATIONS_PER_TURN) {
353
- pending.push(notification);
354
- pendingNotificationsByTurnId.set(pendingTurnId, pending);
355
- }
356
- }
357
- return;
358
- }
359
- if (!isNotificationForTurn(params, threadId, turnId)) return;
360
- if (notification.method === "item/agentMessage/delta") {
361
- const itemId = readString(params, "itemId") ?? readString(params, "id") ?? "assistant";
362
- const delta = readTextString(params, "delta");
363
- if (!delta) return;
364
- rememberItem(itemId);
365
- assistantTextByItem.set(itemId, `${assistantTextByItem.get(itemId) ?? ""}${delta}`);
366
- return;
367
- }
368
- if (notification.method === "item/completed") {
369
- const item = isJsonObject(params.item) ? params.item : void 0;
370
- if (item?.type === "agentMessage") {
371
- const itemId = readString(item, "id") ?? readString(params, "itemId") ?? "assistant";
372
- const text = readTextString(item, "text");
373
- if (text) {
374
- rememberItem(itemId);
375
- assistantTextByItem.set(itemId, text);
376
- }
377
- }
378
- return;
379
- }
380
- if (notification.method === "turn/completed") {
381
- const turn = isJsonObject(params.turn) ? params.turn : void 0;
382
- if (readString(turn, "status") === "failed") failedError = readString(asOptionalRecord(turn?.error), "message") ?? "codex app-server turn failed";
383
- const items = Array.isArray(turn?.items) ? turn.items : [];
384
- for (const item of items) {
385
- if (!isJsonObject(item) || item.type !== "agentMessage") continue;
386
- const itemId = readString(item, "id") ?? `assistant-${assistantOrder.length + 1}`;
387
- const text = readTextString(item, "text");
388
- if (text) {
389
- rememberItem(itemId);
390
- assistantTextByItem.set(itemId, text);
391
- }
392
- }
393
- finish();
394
- }
395
- };
396
- return {
397
- setTurnId(nextTurnId) {
398
- turnId = nextTurnId;
399
- const pending = pendingNotificationsByTurnId.get(nextTurnId) ?? [];
400
- pendingNotificationsByTurnId.clear();
401
- for (const notification of pending) handleNotification(notification);
402
- },
403
- handleNotification,
404
- wait(params) {
405
- if (completed) return failedError ? Promise.reject(new Error(failedError)) : Promise.resolve({ replyText: collectReplyText() });
406
- return new Promise((resolve, reject) => {
407
- resolveCompletion = resolve;
408
- rejectCompletion = reject;
409
- timeout = setTimeout(() => {
410
- completed = true;
411
- reject(/* @__PURE__ */ new Error("codex app-server bound turn timed out"));
412
- clearWaitState();
413
- }, resolveTimerTimeoutMs(params.timeoutMs, 100, 100));
414
- timeout.unref?.();
415
- });
416
- }
417
- };
418
- }
419
- function isNotificationForTurn(params, threadId, turnId) {
420
- if (readCodexNotificationThreadId(params) !== threadId) return false;
421
- if (!turnId) return true;
422
- const directTurnId = readString(params, "turnId");
423
- if (directTurnId) return directTurnId === turnId;
424
- return readString(isJsonObject(params.turn) ? params.turn : void 0, "id") === turnId;
425
- }
426
- function readNotificationTurnId(params) {
427
- return readCodexNotificationTurnId(params);
428
- }
429
- function readString(record, key) {
430
- const value = record?.[key];
431
- return typeof value === "string" && value.trim() ? value.trim() : void 0;
432
- }
433
- function readTextString(record, key) {
434
- const value = record?.[key];
435
- return typeof value === "string" && value.length > 0 ? value : void 0;
436
- }
437
- //#endregion
438
- //#region extensions/codex/src/conversation-turn-input.ts
439
- const IMAGE_EXTENSIONS = new Set([
440
- ".avif",
441
- ".gif",
442
- ".jpeg",
443
- ".jpg",
444
- ".png",
445
- ".webp"
446
- ]);
447
- function buildCodexConversationTurnInput(params) {
448
- return [{
449
- type: "text",
450
- text: params.prompt,
451
- text_elements: []
452
- }, ...extractInboundMedia(params.event).map(toCodexImageInput).filter((item) => item !== void 0)];
453
- }
454
- function extractInboundMedia(event) {
455
- const metadata = event.metadata ?? {};
456
- const paths = normalizeSingleOrTrimmedStringList(metadata.mediaPaths).concat(normalizeSingleOrTrimmedStringList(metadata.mediaPath));
457
- const urls = normalizeSingleOrTrimmedStringList(metadata.mediaUrls).concat(normalizeSingleOrTrimmedStringList(metadata.mediaUrl));
458
- const mimeTypes = normalizeSingleOrTrimmedStringList(metadata.mediaTypes).concat(normalizeSingleOrTrimmedStringList(metadata.mediaType));
459
- const count = Math.max(paths.length, urls.length, mimeTypes.length);
460
- const media = [];
461
- for (let index = 0; index < count; index += 1) media.push({
462
- path: paths[index],
463
- url: urls[index],
464
- mimeType: mimeTypes[index] ?? mimeTypes[0]
465
- });
466
- return media;
467
- }
468
- function toCodexImageInput(media) {
469
- if (!isImageMedia(media)) return;
470
- const localPath = media.path ?? readLocalMediaPath(media.url);
471
- if (localPath) {
472
- const normalized = normalizeFileUrl(localPath);
473
- return normalized ? {
474
- type: "localImage",
475
- path: normalized
476
- } : void 0;
477
- }
478
- return media.url ? {
479
- type: "image",
480
- url: media.url
481
- } : void 0;
482
- }
483
- function isImageMedia(media) {
484
- if (media.mimeType?.toLowerCase().startsWith("image/")) return true;
485
- const candidate = media.path ?? media.url;
486
- if (!candidate) return false;
487
- return IMAGE_EXTENSIONS.has(path.extname(candidate.split(/[?#]/, 1)[0] ?? "").toLowerCase());
488
- }
489
- function normalizeFileUrl(value) {
490
- if (!value.startsWith("file://")) return value;
491
- try {
492
- return fileURLToPath(value);
493
- } catch {
494
- return;
495
- }
496
- }
497
- function readLocalMediaPath(value) {
498
- if (!value) return;
499
- if (value.startsWith("file://")) return value;
500
- if (value.startsWith("//")) return;
501
- if (path.isAbsolute(value) || path.win32.isAbsolute(value)) return value;
502
- return /^[a-z][a-z0-9+.-]*:/i.test(value) ? void 0 : value;
503
- }
504
- //#endregion
505
- //#region extensions/codex/src/node-cli-sessions.ts
506
- const CODEX_CLI_SESSIONS_LIST_COMMAND = "codex.cli.sessions.list";
507
- const CODEX_CLI_SESSION_RESUME_COMMAND = "codex.cli.session.resume";
508
- const DEFAULT_SESSION_LIMIT = 10;
509
- const MAX_SESSION_LIMIT = 50;
510
- const DEFAULT_RESUME_TIMEOUT_MS = 20 * 6e4;
511
- const SESSION_ID_PATTERN = /^[A-Za-z0-9._:-]{1,128}$/;
512
- const activeResumeSessions = /* @__PURE__ */ new Set();
513
- const DEFAULT_RESUME_SPAWN_RUNTIME = {
514
- platform: process$1.platform,
515
- env: process$1.env,
516
- execPath: process$1.execPath
517
- };
518
- function createCodexCliSessionNodeHostCommands() {
519
- return [{
520
- command: CODEX_CLI_SESSIONS_LIST_COMMAND,
521
- cap: "codex-cli-sessions",
522
- handle: listLocalCodexCliSessions
523
- }, {
524
- command: CODEX_CLI_SESSION_RESUME_COMMAND,
525
- cap: "codex-cli-sessions",
526
- dangerous: true,
527
- handle: resumeLocalCodexCliSession
528
- }];
529
- }
530
- function createCodexCliSessionNodeInvokePolicies() {
531
- return [{
532
- commands: [CODEX_CLI_SESSIONS_LIST_COMMAND],
533
- defaultPlatforms: [
534
- "macos",
535
- "linux",
536
- "windows"
537
- ],
538
- handle: (ctx) => ctx.invokeNode()
539
- }, {
540
- commands: [CODEX_CLI_SESSION_RESUME_COMMAND],
541
- dangerous: true,
542
- handle: (ctx) => ctx.invokeNode()
543
- }];
544
- }
545
- async function listCodexCliSessionsOnNode(params) {
546
- const node = await resolveCodexCliNode({
547
- runtime: params.runtime,
548
- requestedNode: params.requestedNode,
549
- command: CODEX_CLI_SESSIONS_LIST_COMMAND
550
- });
551
- return {
552
- node,
553
- result: parseCodexCliSessionsListResult(await params.runtime.nodes.invoke({
554
- nodeId: readNodeId(node),
555
- command: CODEX_CLI_SESSIONS_LIST_COMMAND,
556
- params: {
557
- limit: params.limit,
558
- filter: params.filter
559
- },
560
- timeoutMs: 15e3
561
- }))
562
- };
563
- }
564
- async function resolveCodexCliSessionForBindingOnNode(params) {
565
- const listing = await listCodexCliSessionsOnNode({
566
- runtime: params.runtime,
567
- requestedNode: params.requestedNode,
568
- filter: params.sessionId,
569
- limit: MAX_SESSION_LIMIT
570
- });
571
- if (!listing.node.commands?.includes("codex.cli.session.resume")) throw new Error(`Node ${formatNodeLabel(listing.node)} does not expose ${CODEX_CLI_SESSION_RESUME_COMMAND}.`);
572
- return {
573
- node: listing.node,
574
- session: listing.result.sessions.find((session) => session.sessionId === params.sessionId)
575
- };
576
- }
577
- async function resumeCodexCliSessionOnNode(params) {
578
- const payload = unwrapNodeInvokePayload(await params.runtime.nodes.invoke({
579
- nodeId: params.nodeId,
580
- command: CODEX_CLI_SESSION_RESUME_COMMAND,
581
- params: {
582
- sessionId: params.sessionId,
583
- prompt: params.prompt,
584
- cwd: params.cwd,
585
- timeoutMs: params.timeoutMs
586
- },
587
- timeoutMs: (params.timeoutMs ?? DEFAULT_RESUME_TIMEOUT_MS) + 5e3
588
- }));
589
- if (!isRecord(payload) || payload.ok !== true || typeof payload.text !== "string") throw new Error("Codex CLI resume returned an invalid payload.");
590
- return {
591
- ok: true,
592
- sessionId: typeof payload.sessionId === "string" ? payload.sessionId : params.sessionId,
593
- text: payload.text
594
- };
595
- }
596
- function formatCodexCliSessions(params) {
597
- if (params.result.sessions.length === 0) return `No Codex CLI sessions returned from ${formatCodexDisplayText(formatNodeLabel(params.node))}.`;
598
- return [`Codex CLI sessions on ${formatCodexDisplayText(formatNodeLabel(params.node))}:`, ...params.result.sessions.map((session) => {
599
- const details = [session.cwd, session.updatedAt].filter((value) => Boolean(value));
600
- 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`;
601
- })].join("\n");
602
- }
603
- async function listLocalCodexCliSessions(paramsJSON) {
604
- const params = readRecordParam(paramsJSON);
605
- const limit = normalizeLimit(params.limit);
606
- const filter = typeof params.filter === "string" ? params.filter.trim().toLowerCase() : "";
607
- const codexHome = resolveCodexHome();
608
- const summaries = await readHistorySessions(codexHome);
609
- await hydrateSessionFiles(codexHome, summaries);
610
- await hydrateSessionsFromSessionFiles(codexHome, summaries);
611
- const sessions = [...summaries.values()].filter((session) => {
612
- if (!filter) return true;
613
- return [
614
- session.sessionId,
615
- session.cwd,
616
- session.lastMessage
617
- ].some((value) => value?.toLowerCase().includes(filter));
618
- }).toSorted((a, b) => compareOptionalStringsDesc(a.updatedAt, b.updatedAt)).slice(0, limit);
619
- return JSON.stringify({
620
- sessions,
621
- codexHome
622
- });
623
- }
624
- async function resumeLocalCodexCliSession(paramsJSON) {
625
- const params = readRecordParam(paramsJSON);
626
- const sessionId = typeof params.sessionId === "string" ? params.sessionId.trim() : "";
627
- const prompt = typeof params.prompt === "string" ? params.prompt.trim() : "";
628
- if (!sessionId || !SESSION_ID_PATTERN.test(sessionId)) throw new Error("Missing or invalid Codex CLI session id.");
629
- if (!prompt) throw new Error("Missing Codex CLI prompt.");
630
- if (activeResumeSessions.has(sessionId)) throw new Error(`Codex CLI session ${sessionId} already has an active resume turn.`);
631
- activeResumeSessions.add(sessionId);
632
- try {
633
- const text = await runCodexExecResume({
634
- sessionId,
635
- prompt,
636
- cwd: typeof params.cwd === "string" && params.cwd.trim() ? params.cwd.trim() : void 0,
637
- timeoutMs: normalizeTimeoutMs(params.timeoutMs)
638
- });
639
- return JSON.stringify({
640
- ok: true,
641
- sessionId,
642
- text: text.trim() || "Codex completed without a text reply."
643
- });
644
- } finally {
645
- activeResumeSessions.delete(sessionId);
646
- }
647
- }
648
- async function runCodexExecResume(params) {
649
- const outputPath = path.join(await fs.mkdtemp(path.join(resolvePreferredOpenClawTmpDir(), "openclaw-codex-cli-")), "last-message.txt");
650
- try {
651
- const invocation = resolveCodexCliResumeSpawnInvocation([
652
- "exec",
653
- "resume",
654
- "--skip-git-repo-check",
655
- "--output-last-message",
656
- outputPath,
657
- params.sessionId,
658
- "-"
659
- ], {
660
- platform: process$1.platform,
661
- env: process$1.env,
662
- execPath: process$1.execPath
663
- });
664
- const child = spawn(invocation.command, invocation.args, {
665
- cwd: params.cwd || process$1.cwd(),
666
- stdio: [
667
- "pipe",
668
- "pipe",
669
- "pipe"
670
- ],
671
- env: process$1.env,
672
- shell: invocation.shell,
673
- windowsHide: invocation.windowsHide
674
- });
675
- const stdout = [];
676
- const stderr = [];
677
- let timedOut = false;
678
- let forceKillTimeout;
679
- const timeout = setTimeout(() => {
680
- timedOut = true;
681
- child.kill("SIGTERM");
682
- forceKillTimeout = setTimeout(() => child.kill("SIGKILL"), 2e3);
683
- forceKillTimeout.unref?.();
684
- }, params.timeoutMs);
685
- child.stdout.on("data", (chunk) => stdout.push(chunk));
686
- child.stderr.on("data", (chunk) => stderr.push(chunk));
687
- child.stdin.end(params.prompt);
688
- const exitCode = await new Promise((resolve, reject) => {
689
- child.on("error", reject);
690
- child.on("exit", (code) => resolve(code));
691
- }).finally(() => {
692
- clearTimeout(timeout);
693
- if (forceKillTimeout) clearTimeout(forceKillTimeout);
694
- });
695
- if (timedOut) throw new Error(`codex exec resume timed out after ${String(params.timeoutMs)}ms`);
696
- if (exitCode !== 0) {
697
- const message = Buffer.concat(stderr).toString("utf8").trim() || Buffer.concat(stdout).toString("utf8").trim() || `codex exec resume exited with code ${String(exitCode)}`;
698
- throw new Error(message);
699
- }
700
- return await fs.readFile(outputPath, "utf8");
701
- } finally {
702
- await fs.rm(path.dirname(outputPath), {
703
- recursive: true,
704
- force: true
705
- });
706
- }
707
- }
708
- function resolveCodexCliResumeSpawnInvocation(args, runtime = DEFAULT_RESUME_SPAWN_RUNTIME) {
709
- const resolved = materializeWindowsSpawnProgram(resolveWindowsSpawnProgram({
710
- command: "codex",
711
- platform: runtime.platform,
712
- env: runtime.env,
713
- execPath: runtime.execPath,
714
- packageName: "@openai/codex"
715
- }), args);
716
- return {
717
- command: resolved.command,
718
- args: resolved.argv,
719
- shell: resolved.shell,
720
- windowsHide: resolved.windowsHide
721
- };
722
- }
723
- async function readHistorySessions(codexHome) {
724
- const summaries = /* @__PURE__ */ new Map();
725
- const content = await readFileIfExists(path.join(codexHome, "history.jsonl"));
726
- if (!content) return summaries;
727
- for (const line of content.split(/\r?\n/u)) {
728
- const trimmed = line.trim();
729
- if (!trimmed) continue;
730
- let parsed;
731
- try {
732
- parsed = JSON.parse(trimmed);
733
- } catch {
734
- continue;
735
- }
736
- if (!isRecord(parsed) || typeof parsed.session_id !== "string") continue;
737
- const sessionId = parsed.session_id.trim();
738
- if (!sessionId) continue;
739
- const entry = summaries.get(sessionId) ?? {
740
- sessionId,
741
- messageCount: 0
742
- };
743
- entry.messageCount += 1;
744
- if (typeof parsed.text === "string" && parsed.text.trim()) entry.lastMessage = truncateText(parsed.text.trim(), 140);
745
- if (typeof parsed.ts === "number") entry.updatedAt = timestampMsToIsoString(parsed.ts * 1e3) ?? entry.updatedAt;
746
- summaries.set(sessionId, entry);
747
- }
748
- return summaries;
749
- }
750
- async function hydrateSessionFiles(codexHome, summaries) {
751
- if (summaries.size === 0) return;
752
- const files = await findSessionFiles(path.join(codexHome, "sessions"), 4);
753
- const pending = new Set(summaries.keys());
754
- for (const file of files) {
755
- const basename = path.basename(file);
756
- const sessionId = [...pending].find((id) => basename.includes(id));
757
- if (!sessionId) continue;
758
- const entry = summaries.get(sessionId);
759
- if (!entry) continue;
760
- entry.sessionFile = file;
761
- const cwd = readSessionMetaCwd(await readFirstLine(file) ?? "");
762
- if (cwd) entry.cwd = cwd;
763
- pending.delete(sessionId);
764
- if (pending.size === 0) return;
765
- }
766
- }
767
- async function hydrateSessionsFromSessionFiles(codexHome, summaries) {
768
- const files = await findSessionFiles(path.join(codexHome, "sessions"), 4);
769
- for (const file of files) {
770
- const summary = await readSessionFileSummary(file);
771
- if (!summary) continue;
772
- const existing = summaries.get(summary.sessionId);
773
- summaries.set(summary.sessionId, {
774
- ...summary,
775
- ...existing,
776
- cwd: existing?.cwd ?? summary.cwd,
777
- sessionFile: existing?.sessionFile ?? summary.sessionFile,
778
- updatedAt: existing?.updatedAt ?? summary.updatedAt,
779
- lastMessage: existing?.lastMessage ?? summary.lastMessage,
780
- messageCount: existing?.messageCount ?? summary.messageCount
781
- });
782
- }
783
- }
784
- async function readSessionFileSummary(file) {
785
- const content = await readFileIfExists(file);
786
- if (!content) return null;
787
- let sessionId = "";
788
- let cwd;
789
- let updatedAt;
790
- let lastMessage;
791
- let messageCount = 0;
792
- for (const line of content.split(/\r?\n/u)) {
793
- const trimmed = line.trim();
794
- if (!trimmed) continue;
795
- let parsed;
796
- try {
797
- parsed = JSON.parse(trimmed);
798
- } catch {
799
- continue;
800
- }
801
- if (!isRecord(parsed)) continue;
802
- if (typeof parsed.timestamp === "string" && parsed.timestamp.trim()) updatedAt = parsed.timestamp.trim();
803
- if (parsed.type === "session_meta" && isRecord(parsed.payload)) {
804
- if (typeof parsed.payload.id === "string" && parsed.payload.id.trim()) sessionId = parsed.payload.id.trim();
805
- if (typeof parsed.payload.cwd === "string" && parsed.payload.cwd.trim()) cwd = parsed.payload.cwd.trim();
806
- continue;
807
- }
808
- const messageText = readResponseItemMessageText(parsed);
809
- if (messageText) {
810
- messageCount += 1;
811
- lastMessage = truncateText(messageText, 140);
812
- }
813
- }
814
- if (!sessionId) sessionId = readSessionIdFromFilename(file) ?? "";
815
- if (!sessionId) return null;
816
- return {
817
- sessionId,
818
- updatedAt: updatedAt ?? await readFileMtimeIso(file),
819
- lastMessage,
820
- cwd,
821
- sessionFile: file,
822
- messageCount
823
- };
824
- }
825
- async function findSessionFiles(dir, maxDepth) {
826
- if (maxDepth < 0) return [];
827
- let entries;
828
- try {
829
- entries = await fs.readdir(dir, { withFileTypes: true });
830
- } catch {
831
- return [];
832
- }
833
- const files = [];
834
- for (const entry of entries) {
835
- const entryPath = path.join(dir, entry.name);
836
- if (entry.isDirectory()) files.push(...await findSessionFiles(entryPath, maxDepth - 1));
837
- else if (entry.isFile() && entry.name.endsWith(".jsonl")) files.push(entryPath);
838
- }
839
- return files;
840
- }
841
- function readSessionMetaCwd(line) {
842
- try {
843
- const parsed = JSON.parse(line);
844
- if (!isRecord(parsed) || parsed.type !== "session_meta" || !isRecord(parsed.payload)) return;
845
- return typeof parsed.payload.cwd === "string" && parsed.payload.cwd.trim() ? parsed.payload.cwd.trim() : void 0;
846
- } catch {
847
- return;
848
- }
849
- }
850
- function readResponseItemMessageText(parsed) {
851
- if (parsed.type !== "response_item" || !isRecord(parsed.payload)) return;
852
- if (parsed.payload.type !== "message") return;
853
- if ((typeof parsed.payload.role === "string" ? parsed.payload.role : "") !== "user") return;
854
- const parts = (Array.isArray(parsed.payload.content) ? parsed.payload.content : []).flatMap((entry) => {
855
- if (!isRecord(entry)) return [];
856
- const text = typeof entry.text === "string" ? entry.text : typeof entry.input_text === "string" ? entry.input_text : void 0;
857
- return text?.trim() ? [text.trim()] : [];
858
- });
859
- return parts.length > 0 ? parts.join(" ") : void 0;
860
- }
861
- function readSessionIdFromFilename(file) {
862
- return path.basename(file).match(/[0-9a-f]{8}-[0-9a-f-]{27,}/iu)?.[0];
863
- }
864
- async function resolveCodexCliNode(params) {
865
- const list = await params.runtime.nodes.list(params.requestedNode ? void 0 : { connected: true });
866
- const requested = params.requestedNode?.trim();
867
- const candidates = list.nodes.filter((node) => {
868
- if (requested) return [
869
- node.nodeId,
870
- node.displayName,
871
- node.remoteIp
872
- ].some((value) => value === requested);
873
- return node.connected === true && node.commands?.includes(params.command);
874
- });
875
- if (candidates.length === 0) throw new Error(requested ? `Codex CLI node ${requested} was not found.` : "No connected node exposes Codex CLI session commands.");
876
- const usable = candidates.filter((node) => node.commands?.includes(params.command));
877
- if (usable.length === 0) throw new Error(`Node ${requested ?? "candidate"} does not expose ${params.command}.`);
878
- if (usable.length > 1) throw new Error("Multiple Codex CLI-capable nodes connected. Pass --host <node-id>.");
879
- return usable[0];
880
- }
881
- function parseCodexCliSessionsListResult(raw) {
882
- const payload = unwrapNodeInvokePayload(raw);
883
- if (!isRecord(payload) || !Array.isArray(payload.sessions)) throw new Error("Codex CLI session list returned an invalid payload.");
884
- return {
885
- codexHome: typeof payload.codexHome === "string" ? payload.codexHome : "",
886
- sessions: payload.sessions.flatMap((entry) => {
887
- if (!isRecord(entry) || typeof entry.sessionId !== "string") return [];
888
- return [{
889
- sessionId: entry.sessionId,
890
- updatedAt: typeof entry.updatedAt === "string" ? entry.updatedAt : void 0,
891
- lastMessage: typeof entry.lastMessage === "string" ? entry.lastMessage : void 0,
892
- cwd: typeof entry.cwd === "string" ? entry.cwd : void 0,
893
- sessionFile: typeof entry.sessionFile === "string" ? entry.sessionFile : void 0,
894
- messageCount: typeof entry.messageCount === "number" && Number.isFinite(entry.messageCount) ? entry.messageCount : 0
895
- }];
896
- })
897
- };
898
- }
899
- function unwrapNodeInvokePayload(raw) {
900
- const record = isRecord(raw) ? raw : {};
901
- if (typeof record.payloadJSON === "string" && record.payloadJSON.trim()) try {
902
- return JSON.parse(record.payloadJSON);
903
- } catch (error) {
904
- throw new Error("Codex CLI node command returned malformed payloadJSON.", { cause: error });
905
- }
906
- if ("payload" in record) return record.payload;
907
- return raw;
908
- }
909
- function readRecordParam(paramsJSON) {
910
- if (!paramsJSON?.trim()) return {};
911
- try {
912
- const parsed = JSON.parse(paramsJSON);
913
- return isRecord(parsed) ? parsed : {};
914
- } catch {
915
- return {};
916
- }
917
- }
918
- function resolveCodexHome() {
919
- return process$1.env.CODEX_HOME?.trim() || path.join(os.homedir(), ".codex");
920
- }
921
- async function readFileIfExists(file) {
922
- try {
923
- return await fs.readFile(file, "utf8");
924
- } catch {
925
- return;
926
- }
927
- }
928
- async function readFirstLine(file) {
929
- return (await readFileIfExists(file))?.split(/\r?\n/u)[0];
930
- }
931
- async function readFileMtimeIso(file) {
932
- try {
933
- return (await fs.stat(file)).mtime.toISOString();
934
- } catch {
935
- return;
936
- }
937
- }
938
- function normalizeLimit(value) {
939
- return typeof value === "number" && Number.isFinite(value) ? Math.min(MAX_SESSION_LIMIT, Math.max(1, Math.floor(value))) : DEFAULT_SESSION_LIMIT;
940
- }
941
- function normalizeTimeoutMs(value) {
942
- return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.min(60 * 6e4, Math.floor(value)) : DEFAULT_RESUME_TIMEOUT_MS;
943
- }
944
- function truncateText(value, max) {
945
- return value.length > max ? `${value.slice(0, max - 3)}...` : value;
946
- }
947
- function compareOptionalStringsDesc(a, b) {
948
- return (b ?? "").localeCompare(a ?? "");
949
- }
950
- function readNodeId(node) {
951
- if (!node.nodeId) throw new Error("Codex CLI node did not include a node id.");
952
- return node.nodeId;
953
- }
954
- function formatNodeLabel(node) {
955
- return [
956
- node.displayName,
957
- node.nodeId,
958
- node.remoteIp
959
- ].filter(Boolean).join(" / ") || "node";
960
- }
961
- //#endregion
962
- //#region extensions/codex/src/conversation-binding.ts
963
- const DEFAULT_BOUND_TURN_TIMEOUT_MS = 20 * 6e4;
964
- const DEFAULT_AGENT_ID = "main";
965
- const VALID_AGENT_ID_PATTERN = /^[a-z0-9][a-z0-9_-]{0,63}$/i;
966
- const INVALID_AGENT_ID_CHARS_PATTERN = /[^a-z0-9_-]+/g;
967
- const LEADING_DASH_PATTERN = /^-+/;
968
- const TRAILING_DASH_PATTERN = /-+$/;
969
- const NATIVE_CONVERSATION_INTERACTIVE_APPROVALS_UNAVAILABLE = "OpenClaw native Codex conversation binding cannot route interactive approvals yet; use the Codex harness or explicit /acp spawn codex for that workflow.";
970
- async function resolveConversationAppServerRuntime(params) {
971
- const execPolicy = resolveConversationExecPolicy({
972
- config: params.config,
973
- agentId: params.agentId,
974
- sessionKey: params.sessionKey
975
- });
976
- const sandboxForPolicy = execPolicy.touched && execPolicy.security === "full" && execPolicy.ask !== "off" ? await resolveSandboxContext({
977
- config: params.config,
978
- sessionKey: params.sessionKey,
979
- workspaceDir: params.workspaceDir
980
- }) : void 0;
981
- return {
982
- execPolicy,
983
- runtime: resolveCodexAppServerRuntimeOptions({
984
- pluginConfig: params.pluginConfig,
985
- execPolicy,
986
- modelProvider: params.modelProvider,
987
- model: params.model,
988
- config: params.config,
989
- agentDir: params.agentDir,
990
- openClawSandboxActive: Boolean(sandboxForPolicy?.enabled)
991
- })
992
- };
993
- }
994
- const CODEX_CONVERSATION_GLOBAL_STATE = Symbol.for("openclaw.codex.conversationBinding");
995
- const CODEX_CONVERSATION_THREAD_DEVELOPER_INSTRUCTIONS = "This Codex thread is bound to an OpenClaw conversation. Answer normally; OpenClaw will deliver your final response back to the conversation.";
996
- function getGlobalState() {
997
- const globalState = globalThis;
998
- globalState[CODEX_CONVERSATION_GLOBAL_STATE] ??= { queues: /* @__PURE__ */ new Map() };
999
- return globalState[CODEX_CONVERSATION_GLOBAL_STATE];
1000
- }
1001
- async function startCodexConversationThread(params) {
1002
- const workspaceDir = params.workspaceDir?.trim() || resolveCodexDefaultWorkspaceDir(params.pluginConfig);
1003
- const agentDir = params.agentDir?.trim();
1004
- const agentLookup = buildAgentLookup({
1005
- agentDir,
1006
- config: params.config
1007
- });
1008
- const existingBinding = await readCodexAppServerBinding(params.sessionFile, { ...agentLookup });
1009
- const authProfileId = resolveCodexAppServerAuthProfileIdForAgent({
1010
- authProfileId: params.authProfileId ?? existingBinding?.authProfileId,
1011
- ...agentLookup
1012
- });
1013
- if (params.threadId?.trim()) await attachExistingThread({
1014
- pluginConfig: params.pluginConfig,
1015
- sessionFile: params.sessionFile,
1016
- threadId: params.threadId.trim(),
1017
- workspaceDir,
1018
- ...agentDir ? { agentDir } : {},
1019
- model: params.model,
1020
- modelProvider: params.modelProvider,
1021
- authProfileId,
1022
- approvalPolicy: params.approvalPolicy,
1023
- sandbox: params.sandbox,
1024
- serviceTier: params.serviceTier,
1025
- config: params.config,
1026
- sessionKey: params.sessionKey,
1027
- agentId: params.agentId
1028
- });
1029
- else await createThread({
1030
- pluginConfig: params.pluginConfig,
1031
- sessionFile: params.sessionFile,
1032
- workspaceDir,
1033
- ...agentDir ? { agentDir } : {},
1034
- model: params.model,
1035
- modelProvider: params.modelProvider,
1036
- authProfileId,
1037
- approvalPolicy: params.approvalPolicy,
1038
- sandbox: params.sandbox,
1039
- serviceTier: params.serviceTier,
1040
- config: params.config,
1041
- sessionKey: params.sessionKey,
1042
- agentId: params.agentId
1043
- });
1044
- return createCodexConversationBindingData({
1045
- sessionFile: params.sessionFile,
1046
- workspaceDir,
1047
- ...agentDir ? { agentDir } : {},
1048
- agentId: params.agentId
1049
- });
1050
- }
1051
- async function handleCodexConversationInboundClaim(event, ctx, options = {}) {
1052
- const data = readCodexConversationBindingData(ctx.pluginBinding);
1053
- if (!data) return;
1054
- if (event.commandAuthorized !== true) return { handled: true };
1055
- const prompt = event.bodyForAgent?.trim() || event.content?.trim() || "";
1056
- if (!prompt) return { handled: true };
1057
- const nativeExecutionBlock = data.kind === "codex-cli-node-session" ? resolveCodexNativeSandboxBlock({
1058
- config: options.config,
1059
- sessionKey: event.sessionKey ?? ctx.sessionKey,
1060
- surface: "Codex CLI node conversation binding"
1061
- }) : resolveCodexNativeExecutionBlock({
1062
- config: options.config,
1063
- sessionKey: event.sessionKey ?? ctx.sessionKey,
1064
- agentId: data.agentId,
1065
- surface: "Codex app-server conversation binding"
1066
- });
1067
- if (nativeExecutionBlock) return {
1068
- handled: true,
1069
- reply: { text: nativeExecutionBlock }
1070
- };
1071
- if (data.kind === "codex-cli-node-session") {
1072
- const resume = options.resumeCodexCliSessionOnNode;
1073
- if (!resume) return {
1074
- handled: true,
1075
- reply: { text: "Codex CLI node binding is unavailable because Gateway node runtime is not attached." }
1076
- };
1077
- try {
1078
- return {
1079
- handled: true,
1080
- reply: (await enqueueBoundTurn(`${data.nodeId}:${data.sessionId}`, async () => {
1081
- return { reply: { text: (await resume({
1082
- nodeId: data.nodeId,
1083
- sessionId: data.sessionId,
1084
- prompt,
1085
- cwd: data.cwd,
1086
- timeoutMs: options.timeoutMs
1087
- })).text.trim() || "Codex completed without a text reply." } };
1088
- })).reply
1089
- };
1090
- } catch (error) {
1091
- return {
1092
- handled: true,
1093
- reply: { text: `Codex CLI node turn failed: ${formatCodexDisplayText(formatErrorMessage(error))}` }
1094
- };
1095
- }
1096
- }
1097
- try {
1098
- return {
1099
- handled: true,
1100
- reply: (await enqueueBoundTurn(data.sessionFile, () => runBoundTurnWithMissingThreadRecovery({
1101
- data,
1102
- prompt,
1103
- event,
1104
- config: options.config,
1105
- sessionKey: event.sessionKey ?? ctx.sessionKey,
1106
- pluginConfig: options.pluginConfig,
1107
- timeoutMs: options.timeoutMs
1108
- }))).reply
1109
- };
1110
- } catch (error) {
1111
- return {
1112
- handled: true,
1113
- reply: { text: `Codex app-server turn failed: ${formatCodexDisplayText(formatErrorMessage(error))}` }
1114
- };
1115
- }
1116
- }
1117
- async function handleCodexConversationBindingResolved(event) {
1118
- if (event.status !== "denied") return;
1119
- const data = readCodexConversationBindingDataRecord(event.request.data ?? {});
1120
- if (!data || data.kind !== "codex-app-server-session") return;
1121
- await clearCodexAppServerBinding(data.sessionFile);
1122
- }
1123
- async function resolveThreadBindingRuntime(params) {
1124
- const agentLookup = buildAgentLookup({
1125
- agentDir: params.agentDir,
1126
- config: params.config
1127
- });
1128
- const modelProvider = resolveThreadRequestModelProvider({
1129
- authProfileId: params.authProfileId,
1130
- modelProvider: params.modelProvider,
1131
- ...agentLookup
1132
- });
1133
- const modelSelection = resolveOptionalThreadRequestModelSelection({
1134
- model: params.model,
1135
- modelProvider,
1136
- authProfileId: params.authProfileId,
1137
- ...agentLookup
1138
- });
1139
- const reviewerModelProvider = resolveModelBackedReviewerPolicyProvider({
1140
- authProfileId: params.authProfileId,
1141
- modelProvider: params.modelProvider,
1142
- ...agentLookup
1143
- });
1144
- const { execPolicy, runtime } = await resolveConversationAppServerRuntime({
1145
- pluginConfig: params.pluginConfig,
1146
- config: params.config,
1147
- agentId: params.agentId,
1148
- sessionKey: params.sessionKey,
1149
- workspaceDir: params.workspaceDir,
1150
- modelProvider: reviewerModelProvider,
1151
- model: params.model,
1152
- agentDir: params.agentDir
1153
- });
1154
- const modelScopedRuntime = resolveCodexAppServerForModelProvider({
1155
- appServer: runtime,
1156
- provider: reviewerModelProvider,
1157
- model: params.model,
1158
- config: params.config,
1159
- env: process.env,
1160
- agentDir: params.agentDir
1161
- });
1162
- assertNativeConversationApprovalPolicySupported({
1163
- execPolicy,
1164
- approvalPolicy: execPolicy?.touched ? modelScopedRuntime.approvalPolicy : params.approvalPolicy ?? modelScopedRuntime.approvalPolicy,
1165
- approvalsReviewer: modelScopedRuntime.approvalsReviewer,
1166
- modelBackedApprovalsReviewerUnavailable: !canUseCodexModelBackedApprovalsReviewerForModel({
1167
- modelProvider: reviewerModelProvider,
1168
- model: params.model,
1169
- config: params.config,
1170
- env: process.env,
1171
- agentDir: params.agentDir
1172
- })
1173
- });
1174
- const client = await getLeasedSharedCodexAppServerClient({
1175
- startOptions: runtime.start,
1176
- timeoutMs: runtime.requestTimeoutMs,
1177
- authProfileId: params.authProfileId,
1178
- ...agentLookup
1179
- });
1180
- return {
1181
- execPolicy,
1182
- runtime: modelScopedRuntime,
1183
- agentLookup,
1184
- model: modelSelection?.model,
1185
- modelProvider: modelSelection?.modelProvider ?? modelProvider,
1186
- client
1187
- };
1188
- }
1189
- function buildThreadRequestRuntimeOptions(params, resolved) {
1190
- const serviceTier = params.serviceTier ?? resolved.runtime.serviceTier;
1191
- const sandbox = resolved.execPolicy?.touched ? resolved.runtime.sandbox : params.sandbox ?? resolved.runtime.sandbox;
1192
- return {
1193
- approvalPolicy: resolved.execPolicy?.touched ? resolved.runtime.approvalPolicy : params.approvalPolicy ?? resolved.runtime.approvalPolicy,
1194
- approvalsReviewer: resolved.runtime.approvalsReviewer,
1195
- ...codexConversationSandboxOrPermissions(resolved.runtime, sandbox),
1196
- ...serviceTier ? { serviceTier } : {}
1197
- };
1198
- }
1199
- function codexConversationSandboxOrPermissions(runtime, sandbox) {
1200
- const networkProxy = runtime.networkProxy;
1201
- if (networkProxy) return { config: networkProxy.configPatch };
1202
- return { sandbox };
1203
- }
1204
- async function requestNewConversationBindingThread(params, resolved) {
1205
- return await resolved.client.request("thread/start", {
1206
- cwd: params.workspaceDir,
1207
- ...resolved.model ? { model: resolved.model } : {},
1208
- ...resolved.modelProvider ? { modelProvider: resolved.modelProvider } : {},
1209
- personality: CODEX_NATIVE_PERSONALITY_NONE,
1210
- ...buildThreadRequestRuntimeOptions(params, resolved),
1211
- developerInstructions: CODEX_CONVERSATION_THREAD_DEVELOPER_INSTRUCTIONS,
1212
- experimentalRawEvents: true,
1213
- persistExtendedHistory: true
1214
- }, { timeoutMs: resolved.runtime.requestTimeoutMs });
1215
- }
1216
- async function writeThreadBindingFromResponse(params, resolved, response) {
1217
- const runtimeApprovalPolicy = typeof resolved.runtime.approvalPolicy === "string" ? resolved.runtime.approvalPolicy : void 0;
1218
- await writeCodexAppServerBinding(params.sessionFile, {
1219
- threadId: response.thread.id,
1220
- cwd: response.thread.cwd ?? params.workspaceDir,
1221
- authProfileId: params.authProfileId,
1222
- model: response.model ?? resolved.model ?? params.model,
1223
- modelProvider: normalizeCodexAppServerBindingModelProvider({
1224
- authProfileId: params.authProfileId,
1225
- modelProvider: response.modelProvider ?? resolved.modelProvider ?? params.modelProvider,
1226
- ...resolved.agentLookup
1227
- }),
1228
- approvalPolicy: resolved.execPolicy?.touched ? runtimeApprovalPolicy : params.approvalPolicy ?? runtimeApprovalPolicy,
1229
- sandbox: resolved.execPolicy?.touched ? resolved.runtime.sandbox : params.sandbox ?? resolved.runtime.sandbox,
1230
- serviceTier: params.serviceTier ?? resolved.runtime.serviceTier ?? void 0,
1231
- networkProxyProfileName: resolved.runtime.networkProxy?.profileName,
1232
- networkProxyConfigFingerprint: resolved.runtime.networkProxy?.configFingerprint
1233
- }, { ...resolved.agentLookup });
1234
- }
1235
- async function attachExistingThread(params) {
1236
- const resolved = await resolveThreadBindingRuntime(params);
1237
- try {
1238
- await writeThreadBindingFromResponse(params, resolved, resolved.runtime.networkProxy ? await requestNewConversationBindingThread(params, resolved) : await resolved.client.request(CODEX_CONTROL_METHODS.resumeThread, {
1239
- threadId: params.threadId,
1240
- ...resolved.model ? { model: resolved.model } : {},
1241
- ...resolved.modelProvider ? { modelProvider: resolved.modelProvider } : {},
1242
- personality: CODEX_NATIVE_PERSONALITY_NONE,
1243
- ...buildThreadRequestRuntimeOptions(params, resolved),
1244
- persistExtendedHistory: true
1245
- }, { timeoutMs: resolved.runtime.requestTimeoutMs }));
1246
- } finally {
1247
- releaseLeasedSharedCodexAppServerClient(resolved.client);
1248
- }
1249
- }
1250
- async function createThread(params) {
1251
- const resolved = await resolveThreadBindingRuntime(params);
1252
- try {
1253
- await writeThreadBindingFromResponse(params, resolved, await requestNewConversationBindingThread(params, resolved));
1254
- } finally {
1255
- releaseLeasedSharedCodexAppServerClient(resolved.client);
1256
- }
1257
- }
1258
- async function runBoundTurn(params) {
1259
- const agentLookup = buildAgentLookup({
1260
- agentDir: params.data.agentDir,
1261
- config: params.config
1262
- });
1263
- const binding = await readCodexAppServerBinding(params.data.sessionFile, agentLookup);
1264
- if (!binding?.threadId) throw new Error("bound Codex conversation has no thread binding");
1265
- let threadId = binding.threadId;
1266
- const workspaceDir = binding.cwd || params.data.workspaceDir;
1267
- const reviewerModelProvider = resolveModelBackedReviewerPolicyProvider({
1268
- authProfileId: binding.authProfileId,
1269
- modelProvider: binding.modelProvider,
1270
- ...agentLookup
1271
- });
1272
- const { execPolicy, runtime } = await resolveConversationAppServerRuntime({
1273
- pluginConfig: params.pluginConfig,
1274
- config: params.config,
1275
- agentId: params.data.agentId,
1276
- sessionKey: params.sessionKey,
1277
- workspaceDir,
1278
- modelProvider: reviewerModelProvider,
1279
- model: binding.model,
1280
- agentDir: params.data.agentDir
1281
- });
1282
- const modelScopedRuntime = resolveCodexAppServerForModelProvider({
1283
- appServer: runtime,
1284
- provider: reviewerModelProvider,
1285
- model: binding.model,
1286
- config: params.config,
1287
- env: process.env,
1288
- agentDir: params.data.agentDir
1289
- });
1290
- const modelBackedApprovalsReviewerUnavailable = !canUseCodexModelBackedApprovalsReviewerForModel({
1291
- modelProvider: reviewerModelProvider,
1292
- model: binding.model,
1293
- config: params.config,
1294
- env: process.env,
1295
- agentDir: params.data.agentDir
1296
- });
1297
- const useModelScopedPolicy = execPolicy?.touched === true || modelBackedApprovalsReviewerUnavailable;
1298
- const approvalPolicy = useModelScopedPolicy ? modelScopedRuntime.approvalPolicy : binding.approvalPolicy ?? modelScopedRuntime.approvalPolicy;
1299
- const sandbox = useModelScopedPolicy ? modelScopedRuntime.sandbox : binding.sandbox ?? modelScopedRuntime.sandbox;
1300
- const permissionProfile = modelScopedRuntime.networkProxy?.profileName;
1301
- const networkProxyConfigFingerprint = modelScopedRuntime.networkProxy?.configFingerprint;
1302
- const networkProxyBindingChanged = binding.networkProxyProfileName !== permissionProfile || binding.networkProxyConfigFingerprint !== networkProxyConfigFingerprint;
1303
- const serviceTier = binding.serviceTier ?? runtime.serviceTier;
1304
- let useStickyNetworkProfile = permissionProfile !== void 0 && binding.networkProxyProfileName === permissionProfile && binding.networkProxyConfigFingerprint === networkProxyConfigFingerprint;
1305
- assertNativeConversationApprovalPolicySupported({
1306
- execPolicy,
1307
- approvalPolicy,
1308
- approvalsReviewer: modelScopedRuntime.approvalsReviewer,
1309
- modelBackedApprovalsReviewerUnavailable
1310
- });
1311
- const modelSelection = binding.model ? resolveCodexAppServerRequestModelSelection({
1312
- model: binding.model,
1313
- modelProvider: binding.modelProvider,
1314
- authProfileId: binding.authProfileId,
1315
- ...agentLookup
1316
- }) : void 0;
1317
- const client = await getLeasedSharedCodexAppServerClient({
1318
- startOptions: runtime.start,
1319
- timeoutMs: runtime.requestTimeoutMs,
1320
- authProfileId: binding.authProfileId,
1321
- ...agentLookup
1322
- });
1323
- let notificationCleanup = () => void 0;
1324
- let requestCleanup = () => void 0;
1325
- try {
1326
- if (networkProxyBindingChanged) {
1327
- const response = assertCodexThreadStartResponse(await client.request("thread/start", {
1328
- cwd: workspaceDir,
1329
- ...modelSelection?.model ? { model: modelSelection.model } : {},
1330
- ...modelSelection?.modelProvider ? { modelProvider: modelSelection.modelProvider } : {},
1331
- personality: CODEX_NATIVE_PERSONALITY_NONE,
1332
- approvalPolicy,
1333
- approvalsReviewer: modelScopedRuntime.approvalsReviewer,
1334
- ...modelScopedRuntime.networkProxy ? { config: modelScopedRuntime.networkProxy.configPatch } : { sandbox },
1335
- ...serviceTier ? { serviceTier } : {},
1336
- developerInstructions: CODEX_CONVERSATION_THREAD_DEVELOPER_INSTRUCTIONS,
1337
- experimentalRawEvents: true,
1338
- persistExtendedHistory: true
1339
- }, { timeoutMs: runtime.requestTimeoutMs }));
1340
- threadId = response.thread.id;
1341
- await writeCodexAppServerBinding(params.data.sessionFile, {
1342
- threadId,
1343
- cwd: response.thread.cwd ?? workspaceDir,
1344
- authProfileId: binding.authProfileId,
1345
- model: response.model ?? modelSelection?.model ?? binding.model,
1346
- modelProvider: normalizeCodexAppServerBindingModelProvider({
1347
- authProfileId: binding.authProfileId,
1348
- modelProvider: response.modelProvider ?? modelSelection?.modelProvider ?? binding.modelProvider,
1349
- ...agentLookup
1350
- }),
1351
- approvalPolicy: typeof approvalPolicy === "string" ? approvalPolicy : void 0,
1352
- sandbox,
1353
- serviceTier: serviceTier ?? void 0,
1354
- networkProxyProfileName: modelScopedRuntime.networkProxy?.profileName,
1355
- networkProxyConfigFingerprint: modelScopedRuntime.networkProxy?.configFingerprint
1356
- }, agentLookup);
1357
- useStickyNetworkProfile = modelScopedRuntime.networkProxy !== void 0;
1358
- }
1359
- const collector = createCodexConversationTurnCollector(threadId);
1360
- notificationCleanup = client.addNotificationHandler((notification) => collector.handleNotification(notification));
1361
- requestCleanup = client.addRequestHandler(async (request) => {
1362
- if (request.method === "item/tool/call") return {
1363
- contentItems: [{
1364
- type: "inputText",
1365
- text: "OpenClaw native Codex conversation binding does not expose dynamic OpenClaw tools yet."
1366
- }],
1367
- success: false
1368
- };
1369
- if (request.method === "item/commandExecution/requestApproval" || request.method === "item/fileChange/requestApproval") return {
1370
- decision: "decline",
1371
- reason: "OpenClaw native Codex conversation binding cannot route interactive approvals yet; use the Codex harness or explicit /acp spawn codex for that workflow."
1372
- };
1373
- if (request.method === "item/permissions/requestApproval") return {
1374
- permissions: {},
1375
- scope: "turn"
1376
- };
1377
- if (request.method.includes("requestApproval")) return {
1378
- decision: "decline",
1379
- reason: "OpenClaw native Codex conversation binding cannot route interactive approvals yet; use the Codex harness or explicit /acp spawn codex for that workflow."
1380
- };
1381
- });
1382
- const turnId = (await client.request("turn/start", {
1383
- threadId,
1384
- input: buildCodexConversationTurnInput({
1385
- prompt: params.prompt,
1386
- event: params.event
1387
- }),
1388
- cwd: workspaceDir,
1389
- approvalPolicy,
1390
- approvalsReviewer: modelScopedRuntime.approvalsReviewer,
1391
- ...useStickyNetworkProfile ? {} : { sandboxPolicy: codexSandboxPolicyForTurn(sandbox, workspaceDir) },
1392
- ...modelSelection?.model ? { model: modelSelection.model } : {},
1393
- personality: CODEX_NATIVE_PERSONALITY_NONE,
1394
- ...serviceTier ? { serviceTier } : {}
1395
- }, { timeoutMs: runtime.requestTimeoutMs })).turn.id;
1396
- const activeCleanup = trackCodexConversationActiveTurn({
1397
- sessionFile: params.data.sessionFile,
1398
- threadId,
1399
- turnId
1400
- });
1401
- collector.setTurnId(turnId);
1402
- return { reply: { text: (await collector.wait({ timeoutMs: params.timeoutMs ?? DEFAULT_BOUND_TURN_TIMEOUT_MS }).finally(activeCleanup)).replyText.trim() || "Codex completed without a text reply." } };
1403
- } finally {
1404
- notificationCleanup();
1405
- requestCleanup();
1406
- releaseLeasedSharedCodexAppServerClient(client);
1407
- }
1408
- }
1409
- function assertNativeConversationApprovalPolicySupported(params) {
1410
- if (params.approvalPolicy !== "never" && (params.execPolicy?.touched === true || params.modelBackedApprovalsReviewerUnavailable && params.approvalsReviewer === "user")) throw new Error(NATIVE_CONVERSATION_INTERACTIVE_APPROVALS_UNAVAILABLE);
1411
- }
1412
- async function runBoundTurnWithMissingThreadRecovery(params) {
1413
- try {
1414
- return await runBoundTurn(params);
1415
- } catch (error) {
1416
- if (!isCodexThreadNotFoundError(error)) throw error;
1417
- const agentLookup = buildAgentLookup({
1418
- agentDir: params.data.agentDir,
1419
- config: params.config
1420
- });
1421
- const binding = await readCodexAppServerBinding(params.data.sessionFile, agentLookup);
1422
- const useCurrentRuntimePolicy = resolveConversationExecPolicy({
1423
- config: params.config,
1424
- agentId: params.data.agentId,
1425
- sessionKey: params.sessionKey
1426
- }).touched;
1427
- await startCodexConversationThread({
1428
- pluginConfig: params.pluginConfig,
1429
- sessionFile: params.data.sessionFile,
1430
- workspaceDir: binding?.cwd || params.data.workspaceDir,
1431
- ...agentLookup,
1432
- model: binding?.model,
1433
- modelProvider: binding?.modelProvider,
1434
- authProfileId: binding?.authProfileId,
1435
- approvalPolicy: useCurrentRuntimePolicy ? void 0 : binding?.approvalPolicy,
1436
- sandbox: useCurrentRuntimePolicy ? void 0 : binding?.sandbox,
1437
- serviceTier: binding?.serviceTier,
1438
- config: params.config,
1439
- sessionKey: params.sessionKey,
1440
- agentId: params.data.agentId
1441
- });
1442
- return await runBoundTurn(params);
1443
- }
1444
- }
1445
- function resolveConversationExecPolicy(params) {
1446
- const agentId = params.agentId ?? (params.config ? resolveSessionAgentIds({
1447
- sessionKey: params.sessionKey,
1448
- config: params.config
1449
- }).sessionAgentId : void 0);
1450
- return resolveOpenClawExecPolicyForCodexAppServer({
1451
- config: params.config,
1452
- agentId,
1453
- execOverrides: readSessionExecOverrides({
1454
- config: params.config,
1455
- agentId,
1456
- sessionKey: params.sessionKey
1457
- }),
1458
- approvals: loadExecApprovals()
1459
- });
1460
- }
1461
- function readSessionExecOverrides(params) {
1462
- const sessionKey = params.sessionKey?.trim();
1463
- if (!params.config || !sessionKey) return;
1464
- if (!canReadSessionExecOverrides({
1465
- config: params.config,
1466
- agentId: params.agentId,
1467
- sessionKey
1468
- })) return;
1469
- const entry = resolveSessionStoreEntry({
1470
- store: loadSessionStore(resolveStorePath(params.config.session?.store, { agentId: params.agentId }), { skipCache: true }),
1471
- sessionKey
1472
- }).existing;
1473
- if (!entry?.execSecurity && !entry?.execAsk) return;
1474
- return {
1475
- security: entry.execSecurity,
1476
- ask: entry.execAsk
1477
- };
1478
- }
1479
- function canReadSessionExecOverrides(params) {
1480
- const agentId = normalizeAgentIdOrDefault(params.agentId);
1481
- if (!agentId) return true;
1482
- const sessionAgentId = parseAgentIdFromSessionKey(params.sessionKey);
1483
- if (!sessionAgentId) return isDefaultAgentSessionKeyForAgent({
1484
- config: params.config,
1485
- agentId
1486
- });
1487
- return sessionAgentId === agentId;
1488
- }
1489
- function parseAgentIdFromSessionKey(sessionKey) {
1490
- const raw = sessionKey?.trim();
1491
- if (!raw) return;
1492
- const parts = raw.toLowerCase().split(":").filter(Boolean);
1493
- if (parts.length < 3 || parts[0] !== "agent" || !parts[2]) return;
1494
- return normalizeAgentIdOrDefault(parts[1]);
1495
- }
1496
- function isDefaultAgentSessionKeyForAgent(params) {
1497
- return normalizeAgentId(params.agentId) === resolveDefaultPolicyAgentId(params.config);
1498
- }
1499
- function resolveDefaultPolicyAgentId(config) {
1500
- const agents = (config.agents?.list ?? []).filter((entry) => entry !== null && typeof entry === "object");
1501
- return normalizeAgentId((agents.find((entry) => entry?.default) ?? agents[0])?.id);
1502
- }
1503
- function normalizeAgentIdOrDefault(value) {
1504
- const normalized = normalizeAgentId(value);
1505
- return normalized === DEFAULT_AGENT_ID && !(value ?? "").trim() ? void 0 : normalized;
1506
- }
1507
- function normalizeAgentId(value) {
1508
- const trimmed = (value ?? "").trim();
1509
- if (!trimmed) return DEFAULT_AGENT_ID;
1510
- const normalized = trimmed.toLowerCase();
1511
- if (VALID_AGENT_ID_PATTERN.test(trimmed)) return normalized;
1512
- return normalized.replace(INVALID_AGENT_ID_CHARS_PATTERN, "-").replace(LEADING_DASH_PATTERN, "").replace(TRAILING_DASH_PATTERN, "").slice(0, 64) || DEFAULT_AGENT_ID;
1513
- }
1514
- function isCodexThreadNotFoundError(error) {
1515
- const message = formatErrorMessage(error);
1516
- return /\bthread not found:/iu.test(message) || /\bbound Codex conversation has no thread binding\b/u.test(message);
1517
- }
1518
- function enqueueBoundTurn(key, run) {
1519
- const state = getGlobalState();
1520
- const next = (state.queues.get(key) ?? Promise.resolve()).then(run, run);
1521
- const queued = next.then(() => void 0, () => void 0);
1522
- state.queues.set(key, queued);
1523
- next.finally(() => {
1524
- if (state.queues.get(key) === queued) state.queues.delete(key);
1525
- }).catch(() => void 0);
1526
- return next;
1527
- }
1528
- function resolveThreadRequestModelProvider(params) {
1529
- const modelProvider = params.modelProvider?.trim();
1530
- if (!modelProvider || modelProvider.toLowerCase() === "codex") return;
1531
- if (isCodexAppServerNativeAuthProfile(params) && modelProvider.toLowerCase() === "openai") return;
1532
- return modelProvider.toLowerCase() === "openai" ? "openai" : modelProvider;
1533
- }
1534
- function resolveOptionalThreadRequestModelSelection(params) {
1535
- if (!params.model?.trim()) return;
1536
- return resolveCodexAppServerRequestModelSelection({
1537
- model: params.model,
1538
- modelProvider: params.modelProvider,
1539
- authProfileId: params.authProfileId,
1540
- agentDir: params.agentDir,
1541
- config: params.config
1542
- });
1543
- }
1544
- function resolveModelBackedReviewerPolicyProvider(params) {
1545
- const modelProvider = params.modelProvider?.trim();
1546
- if (modelProvider && modelProvider.toLowerCase() !== "codex") return modelProvider.toLowerCase() === "openai" ? "openai" : modelProvider;
1547
- return isCodexAppServerNativeAuthProfile(params) ? "openai" : void 0;
1548
- }
1549
- function buildAgentLookup(params) {
1550
- const agentDir = params.agentDir?.trim();
1551
- return {
1552
- ...agentDir ? { agentDir } : {},
1553
- ...params.config ? { config: params.config } : {}
1554
- };
1555
- }
1556
- //#endregion
1557
- export { steerCodexConversationTurn as _, createCodexCliSessionNodeInvokePolicies as a, readCodexConversationBindingData as b, resolveCodexCliSessionForBindingOnNode as c, parseCodexFastModeArg as d, parseCodexPermissionsModeArg as f, setCodexConversationPermissions as g, setCodexConversationModel as h, createCodexCliSessionNodeHostCommands as i, resumeCodexCliSessionOnNode as l, setCodexConversationFastMode as m, handleCodexConversationInboundClaim as n, formatCodexCliSessions as o, readCodexConversationActiveTurn as p, startCodexConversationThread as r, listCodexCliSessionsOnNode as s, handleCodexConversationBindingResolved as t, formatPermissionsMode as u, stopCodexConversationTurn as v, resolveCodexDefaultWorkspaceDir as x, createCodexCliNodeConversationBindingData as y };