@openclaw/codex 2026.6.5 → 2026.6.6-beta.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 (27) hide show
  1. package/dist/{client-kMCtlApt.js → client-DovmVtbr.js} +3 -10
  2. package/dist/{client-factory-Bt49r45B.js → client-factory-XajDuvQ1.js} +1 -1
  3. package/dist/{command-handlers-DMn2M7W7.js → command-handlers-DIUFKqaF.js} +11 -9
  4. package/dist/{compact-CwnPeYnM.js → compact-BWiNkDSs.js} +96 -9
  5. package/dist/{computer-use-ClweWaMz.js → computer-use-D3pi5csE.js} +3 -2
  6. package/dist/{config-BT6SLiE6.js → config-DJXpBkGf.js} +214 -13
  7. package/dist/{conversation-binding-CzpvaBs1.js → conversation-binding-CMwrZrt7.js} +190 -65
  8. package/dist/harness.js +12 -5
  9. package/dist/index.js +11 -10
  10. package/dist/media-understanding-provider.js +6 -6
  11. package/dist/{models-DXorTaja.js → models-CQGfP7nG.js} +2 -2
  12. package/dist/{native-hook-relay-DHwz_ICg.js → native-hook-relay-CmUUO3Eu.js} +160 -4
  13. package/dist/notification-correlation-D-MYfJwV.js +382 -0
  14. package/dist/{request-D64BfplD.js → plugin-app-cache-key-NpzxEcSR.js} +4 -36
  15. package/dist/protocol-oeJQu4rs.js +9 -0
  16. package/dist/{protocol-validators-CIpP8IJ2.js → protocol-validators-B48C6S9O.js} +2296 -2273
  17. package/dist/provider-Cs6kWhDQ.js +584 -0
  18. package/dist/provider.js +1 -164
  19. package/dist/request-Dq0LUOqZ.js +36 -0
  20. package/dist/{run-attempt-BWdNnok4.js → run-attempt-DG9p9ReO.js} +374 -65
  21. package/dist/{session-binding-BgTv_YGm.js → session-binding-ElbcSq2o.js} +107 -44
  22. package/dist/{shared-client-xytpSKD0.js → shared-client-CflavQ_i.js} +3 -3
  23. package/dist/{side-question-BnvBQPqW.js → side-question-Ctu2VXAG.js} +82 -26
  24. package/dist/{thread-lifecycle-BJsazZ8j.js → thread-lifecycle-Cq1-IfZB.js} +115 -34
  25. package/npm-shrinkwrap.json +30 -30
  26. package/package.json +5 -5
  27. package/dist/notification-correlation-o8quHmTK.js +0 -656
@@ -1,12 +1,14 @@
1
- import { l as isJsonObject } from "./client-kMCtlApt.js";
2
- import { S as invalidInlineImageText, w as sanitizeInlineImageDataUrl } from "./thread-lifecycle-BJsazZ8j.js";
3
- import { s as formatCodexDisplayText } from "./notification-correlation-o8quHmTK.js";
1
+ import { c as isTrustedCodexModelBackedOpenAIProvider } from "./config-DJXpBkGf.js";
2
+ import { t as isJsonObject } from "./protocol-oeJQu4rs.js";
3
+ import { E as sanitizeInlineImageDataUrl, w as invalidInlineImageText } from "./thread-lifecycle-Cq1-IfZB.js";
4
+ import { l as formatCodexDisplayText } from "./notification-correlation-D-MYfJwV.js";
4
5
  import { addTimerTimeoutGraceMs, finiteSecondsToTimerSafeMilliseconds, resolveTimerTimeoutMs } from "openclaw/plugin-sdk/number-runtime";
5
6
  import { createHash } from "node:crypto";
6
7
  import { normalizeAgentId } from "openclaw/plugin-sdk/routing";
7
8
  import { asOptionalRecord, isRecord, normalizeTrimmedStringList } from "openclaw/plugin-sdk/string-coerce-runtime";
8
9
  import { HEARTBEAT_RESPONSE_TOOL_NAME, buildAgentHookContextChannelFields, callGatewayTool, createAgentToolResultMiddlewareRunner, createCodexAppServerToolResultExtensionRunner, embeddedAgentLog, extractToolResultMediaArtifact, filterToolResultMediaUrls, formatApprovalDisplayPath, hasNativeHookRelayInvocation, invokeNativeHookRelay, isMessagingTool, isMessagingToolSendAction, isToolWrappedWithBeforeToolCallHook, normalizeHeartbeatToolResponse, projectRuntimeToolInputSchema, registerNativeHookRelay, resolveNativeHookRelayDeferredToolApproval, runAgentHarnessAfterToolCallHook, runBeforeToolCallHook, setBeforeToolCallDiagnosticsEnabled, wrapToolWithBeforeToolCallHook } from "openclaw/plugin-sdk/agent-harness-runtime";
9
10
  import { emitTrustedDiagnosticEvent } from "openclaw/plugin-sdk/diagnostic-runtime";
11
+ import { buildExecAutoReviewInputForShellCommand, reviewExecRequestWithConfiguredModel } from "openclaw/plugin-sdk/agent-harness-exec-review-runtime";
10
12
  /** Default idle timeout while waiting for app-server turn completion. */
11
13
  const CODEX_TURN_COMPLETION_IDLE_TIMEOUT_MS = 6e4;
12
14
  /** Short guard after apparent assistant completion. */
@@ -235,6 +237,27 @@ async function handleCodexAppServerApprovalRequest(params) {
235
237
  });
236
238
  return buildApprovalResponse(params.method, context.requestParams, "approved-session");
237
239
  }
240
+ const autoReviewOutcome = await runInternalExecAutoReviewForApprovalRequest({
241
+ enabled: params.internalExecAutoReview === true && params.execPolicy?.mode === "auto",
242
+ method: params.method,
243
+ requestParams,
244
+ paramsForRun: params.paramsForRun,
245
+ context,
246
+ agentId: params.execReviewerAgentId,
247
+ signal: params.signal
248
+ });
249
+ if (autoReviewOutcome?.outcome === "approved-once") {
250
+ emitApprovalEvent(params.paramsForRun, {
251
+ phase: "resolved",
252
+ kind: context.kind,
253
+ status: "approved",
254
+ title: context.title,
255
+ ...context.eventDetails,
256
+ ...approvalEventScope(params.method, autoReviewOutcome.outcome),
257
+ message: autoReviewOutcome.reason
258
+ });
259
+ return buildApprovalResponse(params.method, context.requestParams, autoReviewOutcome.outcome);
260
+ }
238
261
  const requestResult = await requestPluginApproval({
239
262
  paramsForRun: params.paramsForRun,
240
263
  title: context.title,
@@ -350,6 +373,132 @@ function buildApprovalContext(params) {
350
373
  }
351
374
  };
352
375
  }
376
+ async function runInternalExecAutoReviewForApprovalRequest(params) {
377
+ if (!params.enabled || params.method !== "item/commandExecution/requestApproval") return;
378
+ if (hasCommandApprovalCapabilityAmendments(params.requestParams)) return;
379
+ const input = await buildAppServerExecAutoReviewInput({
380
+ requestParams: params.requestParams,
381
+ paramsForRun: params.paramsForRun
382
+ });
383
+ if (!input) return;
384
+ const reviewerConfig = resolveExecReviewerConfig(params.paramsForRun, params.agentId);
385
+ if (!canUseInternalExecAutoReviewReviewer(reviewerConfig, params.paramsForRun.config, process.env, params.paramsForRun.agentDir)) return;
386
+ const decision = await waitForInternalExecAutoReviewDecision({
387
+ signal: params.signal,
388
+ promise: reviewExecRequestWithConfiguredModel({
389
+ cfg: params.paramsForRun.config,
390
+ agentId: params.agentId ?? params.paramsForRun.agentId,
391
+ reviewer: reviewerConfig,
392
+ input
393
+ })
394
+ });
395
+ if (decision.decision !== "allow-once") return;
396
+ return {
397
+ outcome: "approved-once",
398
+ reason: `Codex app-server command approval granted by OpenClaw exec auto-reviewer: ${formatCodexDisplayText(decision.rationale)}`
399
+ };
400
+ }
401
+ async function waitForInternalExecAutoReviewDecision(params) {
402
+ if (!params.signal) return params.promise;
403
+ if (params.signal.aborted) throw toCodexAppServerApprovalCancellationError(params.signal.reason);
404
+ let onAbort;
405
+ const abortPromise = new Promise((_, reject) => {
406
+ onAbort = () => reject(toCodexAppServerApprovalCancellationError(params.signal?.reason));
407
+ params.signal?.addEventListener("abort", onAbort, { once: true });
408
+ });
409
+ try {
410
+ return await Promise.race([params.promise, abortPromise]);
411
+ } finally {
412
+ if (onAbort) params.signal.removeEventListener("abort", onAbort);
413
+ }
414
+ }
415
+ function toCodexAppServerApprovalCancellationError(reason) {
416
+ if (reason instanceof Error) return reason;
417
+ return new Error(typeof reason === "string" && reason.trim() ? reason : "Codex app-server approval cancelled.");
418
+ }
419
+ async function buildAppServerExecAutoReviewInput(params) {
420
+ const command = readString$1(params.requestParams, "command");
421
+ if (!command) return;
422
+ return buildExecAutoReviewInputForShellCommand({
423
+ command,
424
+ cwd: readString$1(params.requestParams, "cwd") ?? params.paramsForRun.workspaceDir ?? null,
425
+ host: "codex-app-server",
426
+ agent: {
427
+ id: params.paramsForRun.agentId ?? null,
428
+ sessionKey: params.paramsForRun.sessionKey ?? null
429
+ }
430
+ });
431
+ }
432
+ function hasCommandApprovalCapabilityAmendments(requestParams) {
433
+ return hasNonEmptyJsonObject(requestParams?.additionalPermissions) || hasNonEmptyJsonObject(requestParams?.networkApprovalContext) || hasNonEmptyJsonObject(requestParams?.proposedExecpolicyAmendment) || hasNonEmptyArray(requestParams?.proposedExecpolicyAmendment) || hasNonEmptyArray(requestParams?.proposedNetworkPolicyAmendments) || findAvailableCommandAmendmentDecision(requestParams) !== void 0 || commandAcceptDecisionUnavailable(requestParams);
434
+ }
435
+ function commandAcceptDecisionUnavailable(requestParams) {
436
+ const available = requestParams?.availableDecisions;
437
+ return Array.isArray(available) && !available.includes("accept");
438
+ }
439
+ function hasNonEmptyJsonObject(value) {
440
+ return isJsonObject(value) && Object.keys(value).length > 0;
441
+ }
442
+ function hasNonEmptyArray(value) {
443
+ return Array.isArray(value) && value.length > 0;
444
+ }
445
+ function resolveExecReviewerConfig(params, agentId) {
446
+ const configRoot = readUnknownRecord(params.config);
447
+ const globalExec = readUnknownRecord(readUnknownRecord(configRoot?.tools)?.exec);
448
+ return readUnknownRecord(resolveAgentExecConfig(configRoot, agentId ?? params.agentId)?.reviewer) ?? readUnknownRecord(globalExec?.reviewer);
449
+ }
450
+ function canUseInternalExecAutoReviewReviewer(reviewerConfig, config, env, agentDir) {
451
+ const model = readExecReviewerModelRef(reviewerConfig);
452
+ const slashIndex = model?.indexOf("/") ?? -1;
453
+ if (!model || slashIndex <= 0) return false;
454
+ if (configuredAgentModelAliasMatches(config, model)) return false;
455
+ if (model.slice(0, slashIndex).trim().toLowerCase() !== "openai") return false;
456
+ return isTrustedCodexModelBackedOpenAIProvider({
457
+ config,
458
+ env,
459
+ agentDir,
460
+ model: model.slice(slashIndex + 1).trim()
461
+ });
462
+ }
463
+ function readExecReviewerModelRef(reviewerConfig) {
464
+ const model = reviewerConfig?.model;
465
+ if (typeof model === "string") return model.trim() || void 0;
466
+ const primary = readUnknownRecord(model)?.primary;
467
+ return typeof primary === "string" && primary.trim() ? primary.trim() : void 0;
468
+ }
469
+ function configuredAgentModelAliasMatches(config, modelRef) {
470
+ const normalizedModelRef = normalizeExecReviewerAliasRef(modelRef);
471
+ return agentModelAliasMatches(readUnknownRecord(readUnknownRecord(readUnknownRecord(config)?.agents)?.defaults), normalizedModelRef);
472
+ }
473
+ function agentModelAliasMatches(agentConfig, normalizedModelRef) {
474
+ const models = readUnknownRecord(agentConfig?.models);
475
+ if (!models) return false;
476
+ for (const entry of Object.values(models)) {
477
+ const alias = readUnknownRecord(entry)?.alias;
478
+ if (typeof alias === "string" && normalizeExecReviewerAliasRef(alias) === normalizedModelRef) return true;
479
+ }
480
+ return false;
481
+ }
482
+ function normalizeExecReviewerAliasRef(modelRef) {
483
+ const trimmed = modelRef.trim().toLowerCase();
484
+ const slashIndex = trimmed.indexOf("/");
485
+ const authProfileIndex = trimmed.indexOf("@", slashIndex + 1);
486
+ return authProfileIndex > 0 ? trimmed.slice(0, authProfileIndex) : trimmed;
487
+ }
488
+ function resolveAgentExecConfig(configRoot, agentId) {
489
+ const normalizedAgentId = agentId ? normalizeAgentId(agentId) : void 0;
490
+ if (!normalizedAgentId) return;
491
+ const agentList = readUnknownRecord(configRoot?.agents)?.list;
492
+ if (!Array.isArray(agentList)) return;
493
+ for (const entry of agentList) {
494
+ const record = readUnknownRecord(entry);
495
+ if (typeof record?.id !== "string" || normalizeAgentId(record.id) !== normalizedAgentId) continue;
496
+ return readUnknownRecord(readUnknownRecord(record.tools)?.exec);
497
+ }
498
+ }
499
+ function readUnknownRecord(value) {
500
+ return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
501
+ }
353
502
  async function runOpenClawToolPolicyForApprovalRequest(params) {
354
503
  const policyRequest = buildOpenClawToolPolicyRequest(params.method, params.requestParams);
355
504
  if (!policyRequest) return;
@@ -2122,6 +2271,8 @@ const CODEX_NATIVE_HOOK_RELAY_EVENTS_WITH_APP_SERVER_APPROVALS = CODEX_NATIVE_HO
2122
2271
  const CODEX_NATIVE_HOOK_RELAY_MIN_TTL_MS = 30 * 6e4;
2123
2272
  /** Extra relay lifetime after the expected turn budget, preventing late hook drops. */
2124
2273
  const CODEX_NATIVE_HOOK_RELAY_TTL_GRACE_MS = 5 * 6e4;
2274
+ const CODEX_NATIVE_HOOK_RELAY_COMMAND_MIN_PARENT_MARGIN_MS = 250;
2275
+ const CODEX_NATIVE_HOOK_RELAY_COMMAND_MAX_PARENT_MARGIN_MS = 1e3;
2125
2276
  const CODEX_NATIVE_HOOK_RELAY_UNREGISTER_GRACE_MS = 1e4;
2126
2277
  const CODEX_NATIVE_HOOK_RELAY_UNREGISTER_EXTRA_GRACE_MS = 5e3;
2127
2278
  const pendingCodexNativeHookRelayUnregisters = /* @__PURE__ */ new Set();
@@ -2229,8 +2380,8 @@ function buildCodexNativeHookRelayConfig(params) {
2229
2380
  if (params.clearOmittedEvents) for (const sourcePath of CODEX_SESSION_FLAGS_HOOK_SOURCE_PATHS) hookState[`${sourcePath}:${CODEX_HOOK_KEY_LABEL_BY_NATIVE_EVENT[event]}:0:0`] = { enabled: false };
2230
2381
  continue;
2231
2382
  }
2232
- const command = params.relay.commandForEvent(event);
2233
2383
  const timeout = normalizeHookTimeoutSec(params.hookTimeoutSec);
2384
+ const command = params.relay.commandForEvent(event, { timeoutMs: resolveCodexNativeHookRelayCommandTimeoutMs(timeout) });
2234
2385
  config[`hooks.${codexEvent}`] = [{ hooks: [{
2235
2386
  type: "command",
2236
2387
  command,
@@ -2265,6 +2416,11 @@ function buildCodexNativeHookRelayDisabledConfig() {
2265
2416
  function normalizeHookTimeoutSec(value) {
2266
2417
  return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.ceil(value) : 5;
2267
2418
  }
2419
+ function resolveCodexNativeHookRelayCommandTimeoutMs(hookTimeoutSec) {
2420
+ const parentTimeoutMs = finiteSecondsToTimerSafeMilliseconds(normalizeHookTimeoutSec(hookTimeoutSec)) ?? 5e3;
2421
+ const parentMarginMs = Math.min(CODEX_NATIVE_HOOK_RELAY_COMMAND_MAX_PARENT_MARGIN_MS, Math.max(CODEX_NATIVE_HOOK_RELAY_COMMAND_MIN_PARENT_MARGIN_MS, Math.floor(parentTimeoutMs / 5)));
2422
+ return Math.max(1, parentTimeoutMs - parentMarginMs);
2423
+ }
2268
2424
  function codexCommandHookTrustedHash(params) {
2269
2425
  const identity = {
2270
2426
  event_name: CODEX_HOOK_KEY_LABEL_BY_NATIVE_EVENT[params.event],
@@ -0,0 +1,382 @@
1
+ import { n as canUseCodexModelBackedApprovalsReviewerForModel } from "./config-DJXpBkGf.js";
2
+ import { t as isJsonObject } from "./protocol-oeJQu4rs.js";
3
+ import { a as hasCodexRateLimitSnapshots, c as summarizeCodexAccountRateLimits, u as summarizeCodexRateLimits } from "./provider-Cs6kWhDQ.js";
4
+ //#region extensions/codex/src/command-formatters.ts
5
+ /** Formats the combined `/codex status` probe result. */
6
+ function formatCodexStatus(probes) {
7
+ const lines = [`Codex app-server: ${probes.models.ok || probes.account.ok || probes.limits.ok || probes.mcps.ok || probes.skills.ok ? "connected" : "unavailable"}`];
8
+ if (probes.models.ok) lines.push(`Models: ${probes.models.value.models.map((model) => formatCodexDisplayText(model.id)).slice(0, 8).join(", ") || "none"}`);
9
+ else lines.push(`Models: ${formatCodexDisplayText(probes.models.error)}`);
10
+ lines.push(`Account: ${probes.account.ok ? formatCodexAccountSummary(probes.account.value) : formatCodexDisplayText(probes.account.error)}`);
11
+ lines.push(`Rate limits: ${probes.limits.ok ? formatCodexRateLimitSummary(probes.limits.value) : formatCodexDisplayText(probes.limits.error)}`);
12
+ lines.push(`MCP servers: ${probes.mcps.ok ? summarizeArrayLike(probes.mcps.value) : formatCodexDisplayText(probes.mcps.error)}`);
13
+ lines.push(`Skills: ${probes.skills.ok ? summarizeCodexSkills(probes.skills.value) : formatCodexDisplayText(probes.skills.error)}`);
14
+ return lines.join("\n");
15
+ }
16
+ /** Formats Codex model-list results for `/codex models`. */
17
+ function formatModels(result) {
18
+ if (result.models.length === 0) return "No Codex app-server models returned.";
19
+ const lines = ["Codex models:", ...result.models.map((model) => `- ${formatCodexDisplayText(model.id)}${model.isDefault ? " (default)" : ""}`)];
20
+ if (result.truncated) lines.push("- More models available; output truncated.");
21
+ return lines.join("\n");
22
+ }
23
+ /** Formats Codex thread-list responses with safe resume hints. */
24
+ function formatThreads(response) {
25
+ const threads = extractArray(response);
26
+ if (threads.length === 0) return "No Codex threads returned.";
27
+ return ["Codex threads:", ...threads.slice(0, 10).map((thread) => {
28
+ const record = isJsonObject(thread) ? thread : {};
29
+ const id = readString$1(record, "threadId") ?? readString$1(record, "id") ?? "<unknown>";
30
+ const title = readString$1(record, "title") ?? readString$1(record, "name") ?? readString$1(record, "summary");
31
+ const details = [
32
+ readString$1(record, "model"),
33
+ readString$1(record, "cwd"),
34
+ readString$1(record, "updatedAt") ?? readString$1(record, "lastUpdatedAt")
35
+ ].filter((value) => Boolean(value));
36
+ return `- ${formatCodexDisplayText(id)}${title ? ` - ${formatCodexDisplayText(title)}` : ""}${details.length > 0 ? ` (${details.map(formatCodexDisplayText).join(", ")})` : ""}\n Resume: ${formatCodexResumeHint(id)}`;
37
+ })].join("\n");
38
+ }
39
+ /** Formats account and rate-limit output for `/codex account`. */
40
+ function formatAccount(account, limits, authOverview) {
41
+ if (authOverview) return formatAccountAuthOverview(authOverview);
42
+ const formattedLimits = limits.ok ? formatCodexRateLimitDetails(limits.value) : formatCodexDisplayText(limits.error);
43
+ const rateLimitBlock = formattedLimits.startsWith("Codex is ") ? formattedLimits : formattedLimits.includes("\n") ? `Rate limits:\n${formattedLimits}` : `Rate limits: ${formattedLimits}`;
44
+ return [`Account: ${account.ok ? formatCodexAccountSummary(account.value) : formatCodexDisplayText(account.error)}`, rateLimitBlock].join("\n\n");
45
+ }
46
+ function formatAccountAuthOverview(overview) {
47
+ const lines = [];
48
+ if (overview.currentLine) lines.push(overview.currentLine, "");
49
+ if (overview.subscriptionLabel) {
50
+ lines.push(`Subscription ${overview.subscriptionLabel}`);
51
+ if (overview.subscriptionUsage) lines.push(` ${overview.subscriptionUsage}`);
52
+ lines.push("");
53
+ }
54
+ if (overview.rows.length > 0) {
55
+ lines.push(overview.orderTitle);
56
+ for (const [index, row] of overview.rows.entries()) lines.push(` ${index + 1}. ${row.label} ${row.kind} — ${formatAuthRowStatus(row)}`);
57
+ }
58
+ while (lines.at(-1) === "") lines.pop();
59
+ return lines.map(formatCodexAccountLine).join("\n");
60
+ }
61
+ function formatAuthRowStatus(row) {
62
+ return row.billingNote ? `${row.status} · ${row.billingNote}` : row.status;
63
+ }
64
+ /** Formats Codex Computer Use readiness and plugin/MCP availability. */
65
+ function formatComputerUseStatus(status) {
66
+ const lines = [`Computer Use: ${status.ready ? "ready" : status.enabled ? "not ready" : "disabled"}`];
67
+ lines.push(`Plugin: ${formatCodexDisplayText(status.pluginName)} (${computerUsePluginState(status)})`);
68
+ lines.push(`MCP server: ${formatCodexDisplayText(status.mcpServerName)}${status.mcpServerAvailable ? ` (${status.tools.length} tools)` : " (unavailable)"}`);
69
+ if (status.marketplaceName) lines.push(`Marketplace: ${formatCodexDisplayText(status.marketplaceName)}`);
70
+ if (status.tools.length > 0) lines.push(`Tools: ${status.tools.slice(0, 8).map(formatCodexDisplayText).join(", ")}`);
71
+ lines.push(formatCodexDisplayText(status.message));
72
+ return lines.join("\n");
73
+ }
74
+ function computerUsePluginState(status) {
75
+ if (!status.installed) return "not installed";
76
+ return status.pluginEnabled ? "installed" : "installed, disabled";
77
+ }
78
+ /** Formats generic array-like Codex app-server responses. */
79
+ function formatList(response, label) {
80
+ const entries = extractArray(response);
81
+ if (entries.length === 0) return `${label}: none returned.`;
82
+ return [`${label}:`, ...entries.slice(0, 25).map((entry) => {
83
+ const record = isJsonObject(entry) ? entry : {};
84
+ return `- ${formatCodexDisplayText(readString$1(record, "name") ?? readString$1(record, "id") ?? JSON.stringify(entry))}`;
85
+ })].join("\n");
86
+ }
87
+ /** Formats Codex skills grouped by scope, omitting disabled entries. */
88
+ function formatSkills(response) {
89
+ const groups = isJsonObject(response) && Array.isArray(response.data) ? response.data : [];
90
+ if (groups.length === 0) return "Codex skills: none returned.";
91
+ const lines = ["Codex skills:"];
92
+ let renderedSkills = 0;
93
+ let loadErrors = 0;
94
+ for (const group of groups) {
95
+ const record = isJsonObject(group) ? group : {};
96
+ if (Array.isArray(record.errors)) loadErrors += record.errors.length;
97
+ const skills = Array.isArray(record.skills) ? record.skills : [];
98
+ if (skills.length === 0) continue;
99
+ for (const skill of skills) {
100
+ if (isJsonObject(skill) && skill.enabled === false) continue;
101
+ lines.push(`- ${formatCodexSkillEntry(skill)}`);
102
+ renderedSkills += 1;
103
+ }
104
+ }
105
+ if (renderedSkills === 0) {
106
+ if (loadErrors > 0) return `Codex skills: none returned (${loadErrors} load ${loadErrors === 1 ? "error" : "errors"}).`;
107
+ return "Codex skills: none returned.";
108
+ }
109
+ return lines.join("\n");
110
+ }
111
+ function formatCodexSkillEntry(entry) {
112
+ return `\`${formatCodexDisplayText(readString$1(isJsonObject(entry) ? entry : {}, "name") ?? "<unknown>")}\``;
113
+ }
114
+ const CODEX_RESUME_SAFE_THREAD_ID_PATTERN = /^[A-Za-z0-9._:-]+$/;
115
+ function formatCodexResumeHint(threadId) {
116
+ const safe = formatCodexTextForDisplay(threadId);
117
+ if (!CODEX_RESUME_SAFE_THREAD_ID_PATTERN.test(safe)) return "copy the thread id above and run /codex resume <thread-id>";
118
+ return `/codex resume ${safe}`;
119
+ }
120
+ /** Escapes Codex-originated text so it is safe to render in chat command output. */
121
+ function formatCodexDisplayText(value) {
122
+ return escapeCodexChatText(formatCodexTextForDisplay(value));
123
+ }
124
+ function formatCodexAccountSummary(value) {
125
+ const safe = formatCodexTextForDisplay(summarizeAccount(value));
126
+ return isLikelyEmailAddress(safe) ? escapeCodexChatTextPreservingAt(safe) : escapeCodexChatText(safe);
127
+ }
128
+ function formatCodexTextForDisplay(value) {
129
+ return sanitizeCodexTextForDisplay(value).trim() || "<unknown>";
130
+ }
131
+ function sanitizeCodexTextForDisplay(value) {
132
+ let safe = "";
133
+ for (const character of value) {
134
+ const codePoint = character.codePointAt(0);
135
+ safe += codePoint != null && isUnsafeDisplayCodePoint(codePoint) ? "?" : character;
136
+ }
137
+ return safe;
138
+ }
139
+ function escapeCodexChatText(value) {
140
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("@", "@").replaceAll("`", "`").replaceAll("[", "[").replaceAll("]", "]").replaceAll("(", "(").replaceAll(")", ")").replaceAll("*", "∗").replaceAll("_", "_").replaceAll("~", "~").replaceAll("|", "|");
141
+ }
142
+ function escapeCodexChatTextPreservingAt(value) {
143
+ return escapeCodexChatText(value).replaceAll("@", "@");
144
+ }
145
+ function formatCodexAccountLine(value) {
146
+ if (value === "") return "";
147
+ const safe = sanitizeCodexTextForDisplay(value).trimEnd();
148
+ if (!safe.trim()) return "";
149
+ const emailPattern = /[^\s@<>()[\]`]+@[^\s@<>()[\]`]+\.[^\s@<>()[\]`]+/gu;
150
+ let formatted = "";
151
+ let lastIndex = 0;
152
+ for (const match of safe.matchAll(emailPattern)) {
153
+ const index = match.index ?? 0;
154
+ formatted += escapeCodexChatText(safe.slice(lastIndex, index));
155
+ formatted += escapeCodexChatTextPreservingAt(match[0]);
156
+ lastIndex = index + match[0].length;
157
+ }
158
+ formatted += escapeCodexChatText(safe.slice(lastIndex));
159
+ return formatted;
160
+ }
161
+ function isLikelyEmailAddress(value) {
162
+ return /^[^\s@<>()[\]`]+@[^\s@<>()[\]`]+\.[^\s@<>()[\]`]+$/.test(value);
163
+ }
164
+ function isUnsafeDisplayCodePoint(codePoint) {
165
+ return codePoint <= 31 || codePoint >= 127 && codePoint <= 159 || codePoint === 173 || codePoint === 1564 || codePoint === 6158 || codePoint >= 8203 && codePoint <= 8207 || codePoint >= 8234 && codePoint <= 8238 || codePoint >= 8288 && codePoint <= 8303 || codePoint === 65279 || codePoint >= 65529 && codePoint <= 65531 || codePoint >= 917504 && codePoint <= 917631;
166
+ }
167
+ /** Builds the portable `/codex` command help text. */
168
+ function buildHelp() {
169
+ return [
170
+ "Codex commands:",
171
+ "- /codex status",
172
+ "- /codex models",
173
+ "- /codex threads [filter]",
174
+ "- /codex sessions --host <node> [filter]",
175
+ "- /codex resume <thread-id>",
176
+ "- /codex resume <session-id> --host <node> --bind here",
177
+ "- /codex bind [thread-id] [--cwd <path>] [--model <model>] [--provider <provider>]",
178
+ "- /codex binding",
179
+ "- /codex stop",
180
+ "- /codex steer <message>",
181
+ "- /codex model [model]",
182
+ "- /codex fast [on|off|status]",
183
+ "- /codex permissions [default|yolo|status]",
184
+ "- /codex detach",
185
+ "- /codex compact",
186
+ "- /codex review",
187
+ "- /codex diagnostics [note]",
188
+ "- /codex computer-use [status|install]",
189
+ "- /codex account",
190
+ "- /codex mcp",
191
+ "- /codex skills",
192
+ "- /codex plugins [list|enable|disable]"
193
+ ].join("\n");
194
+ }
195
+ function summarizeAccount(value) {
196
+ if (!isJsonObject(value)) return "unavailable";
197
+ const account = isJsonObject(value.account) ? value.account : value;
198
+ if (readString$1(account, "type") === "amazonBedrock") return "Amazon Bedrock";
199
+ return readString$1(account, "email") ?? readString$1(account, "accountEmail") ?? readString$1(account, "planType") ?? readString$1(account, "id") ?? "available";
200
+ }
201
+ function summarizeArrayLike(value) {
202
+ const entries = extractArray(value);
203
+ if (entries.length === 0) return "none returned";
204
+ return `${entries.length}`;
205
+ }
206
+ function summarizeCodexSkills(value) {
207
+ const groups = isJsonObject(value) && Array.isArray(value.data) ? value.data : [];
208
+ if (groups.length === 0) return "none returned";
209
+ let enabledSkills = 0;
210
+ let loadErrors = 0;
211
+ for (const group of groups) {
212
+ if (!isJsonObject(group)) continue;
213
+ if (Array.isArray(group.errors)) loadErrors += group.errors.length;
214
+ if (!Array.isArray(group.skills)) continue;
215
+ enabledSkills += group.skills.filter((skill) => !isJsonObject(skill) || skill.enabled !== false).length;
216
+ }
217
+ if (enabledSkills > 0) return `${enabledSkills}`;
218
+ if (loadErrors > 0) return `none returned (${loadErrors} load ${loadErrors === 1 ? "error" : "errors"})`;
219
+ return "none returned";
220
+ }
221
+ function formatCodexRateLimitSummary(value) {
222
+ const summary = summarizeCodexRateLimits(value);
223
+ if (summary) return formatCodexDisplayText(summary);
224
+ return formatCodexDisplayText(hasCodexRateLimitSnapshots(value) ? "none returned" : summarizeRateLimits(value));
225
+ }
226
+ function formatCodexRateLimitDetails(value) {
227
+ const lines = summarizeCodexAccountRateLimits(value);
228
+ if (!lines) return formatCodexDisplayText(hasCodexRateLimitSnapshots(value) ? "none returned" : summarizeRateLimits(value));
229
+ return lines.map(formatCodexDisplayText).join("\n");
230
+ }
231
+ function summarizeRateLimits(value) {
232
+ const entries = extractArray(value);
233
+ if (entries.length > 0) {
234
+ const count = entries.filter(isMeaningfulRateLimitSnapshot).length;
235
+ return count > 0 ? `${count}` : "none returned";
236
+ }
237
+ if (!isJsonObject(value)) return "none returned";
238
+ const keyed = value.rateLimitsByLimitId;
239
+ if (isJsonObject(keyed)) {
240
+ const count = Object.values(keyed).filter(isMeaningfulRateLimitSnapshot).length;
241
+ if (count > 0) return `${count}`;
242
+ }
243
+ return isMeaningfulRateLimitSnapshot(value.rateLimits) ? "1" : "none returned";
244
+ }
245
+ function isMeaningfulRateLimitSnapshot(value) {
246
+ if (!isJsonObject(value)) return false;
247
+ if (readString$1(value, "rateLimitReachedType") ?? readString$1(value, "rate_limit_reached_type")) return true;
248
+ return ["primary", "secondary"].some((key) => {
249
+ const window = value[key];
250
+ return isJsonObject(window) && Object.values(window).some((entry) => entry != null);
251
+ });
252
+ }
253
+ function extractArray(value) {
254
+ if (Array.isArray(value)) return value;
255
+ if (!isJsonObject(value)) return [];
256
+ for (const key of [
257
+ "data",
258
+ "items",
259
+ "threads",
260
+ "models",
261
+ "skills",
262
+ "servers",
263
+ "rateLimits"
264
+ ]) {
265
+ const child = value[key];
266
+ if (Array.isArray(child)) return child;
267
+ }
268
+ return [];
269
+ }
270
+ /** Reads and trims a non-empty string field from a JSON object. */
271
+ function readString$1(record, key) {
272
+ const value = record[key];
273
+ return typeof value === "string" && value.trim() ? value.trim() : void 0;
274
+ }
275
+ //#endregion
276
+ //#region extensions/codex/src/app-server/app-server-policy.ts
277
+ /**
278
+ * Policy promotion for Codex app-server runs that can safely use OpenClaw tool
279
+ * approvals.
280
+ */
281
+ /**
282
+ * Promotes implicit `never` approval policy to `untrusted` only when runtime
283
+ * requirements allow OpenClaw to handle tool approvals.
284
+ */
285
+ function resolveCodexAppServerForOpenClawToolPolicy(params) {
286
+ if (!params.shouldPromote || !params.canUseUntrustedApprovalPolicy || params.appServer.approvalPolicy !== "never") return params.appServer;
287
+ const explicitMode = params.execPolicy?.mode === "full" || params.pluginConfig.appServer?.mode !== void 0 || isCodexAppServerPolicyMode(params.env.OPENCLAW_CODEX_APP_SERVER_MODE);
288
+ const explicitApprovalPolicy = params.pluginConfig.appServer?.approvalPolicy !== void 0 || isCodexAppServerApprovalPolicy(params.env.OPENCLAW_CODEX_APP_SERVER_APPROVAL_POLICY) || params.appServer.approvalPolicySource === "requirements";
289
+ if (explicitMode || explicitApprovalPolicy) return params.appServer;
290
+ return {
291
+ ...params.appServer,
292
+ approvalPolicy: "untrusted"
293
+ };
294
+ }
295
+ function resolveCodexAppServerForModelProvider(params) {
296
+ const explicitProvider = normalizeModelBackedReviewerProvider(params.provider);
297
+ if (!isCodexModelBackedApprovalsReviewer(params.appServer.approvalsReviewer) || canUseCodexModelBackedApprovalsReviewerForModel({
298
+ modelProvider: explicitProvider,
299
+ model: params.model,
300
+ config: params.config,
301
+ env: params.env,
302
+ agentDir: params.agentDir,
303
+ codexConfigToml: params.codexConfigToml
304
+ })) return params.appServer;
305
+ return {
306
+ ...params.appServer,
307
+ approvalsReviewer: "user"
308
+ };
309
+ }
310
+ function isCodexAppServerPolicyMode(value) {
311
+ return value === "guardian" || value === "yolo";
312
+ }
313
+ function isCodexAppServerApprovalPolicy(value) {
314
+ return value === "never" || value === "on-request" || value === "on-failure" || value === "untrusted";
315
+ }
316
+ function isCodexModelBackedApprovalsReviewer(value) {
317
+ return value === "auto_review" || value === "guardian_subagent";
318
+ }
319
+ function normalizeModelBackedReviewerProvider(provider) {
320
+ return provider?.trim().toLowerCase() || void 0;
321
+ }
322
+ //#endregion
323
+ //#region extensions/codex/src/app-server/notification-correlation.ts
324
+ /**
325
+ * Correlates Codex app-server notifications with the active thread/turn so
326
+ * projectors can ignore global or stale events without losing diagnostics.
327
+ */
328
+ /** Returns true when a notification payload belongs to the exact active thread and turn. */
329
+ function isCodexNotificationForTurn(value, threadId, turnId) {
330
+ if (!isJsonObject(value)) return false;
331
+ return readCodexNotificationThreadId(value) === threadId && readCodexNotificationTurnId(value) === turnId;
332
+ }
333
+ /** Reads a thread id from either top-level notification params or nested turn payloads. */
334
+ function readCodexNotificationThreadId(record) {
335
+ return readNestedTurnThreadId(record) ?? readString(record, "threadId");
336
+ }
337
+ /** Reads a turn id from either top-level notification params or nested turn payloads. */
338
+ function readCodexNotificationTurnId(record) {
339
+ return readNestedTurnId(record) ?? readString(record, "turnId");
340
+ }
341
+ /** Builds structured correlation details for logs when notification routing is ambiguous. */
342
+ function describeCodexNotificationCorrelation(notification, active) {
343
+ const params = isJsonObject(notification.params) ? notification.params : void 0;
344
+ const turn = params && isJsonObject(params.turn) ? params.turn : void 0;
345
+ const threadId = params ? readString(params, "threadId") : void 0;
346
+ const turnId = params ? readString(params, "turnId") : void 0;
347
+ const nestedTurnThreadId = turn ? readString(turn, "threadId") : void 0;
348
+ const nestedTurnId = turn ? readString(turn, "id") : void 0;
349
+ const resolvedThreadId = params ? readCodexNotificationThreadId(params) : void 0;
350
+ const resolvedTurnId = params ? readCodexNotificationTurnId(params) : void 0;
351
+ const matchesActiveThread = resolvedThreadId === active.threadId;
352
+ const matchesActiveTurn = active.turnId ? matchesActiveThread && resolvedTurnId === active.turnId : void 0;
353
+ const items = turn?.items;
354
+ return {
355
+ method: notification.method,
356
+ ...params ? { paramsKeys: Object.keys(params).toSorted() } : {},
357
+ activeThreadId: active.threadId,
358
+ ...active.turnId ? { activeTurnId: active.turnId } : {},
359
+ ...threadId ? { threadId } : {},
360
+ ...turnId ? { turnId } : {},
361
+ ...nestedTurnThreadId ? { nestedTurnThreadId } : {},
362
+ ...nestedTurnId ? { nestedTurnId } : {},
363
+ ...turn ? { turnStatus: readString(turn, "status") } : {},
364
+ ...Array.isArray(items) ? { turnItemCount: items.length } : {},
365
+ matchesActiveThread,
366
+ ...matchesActiveTurn === void 0 ? {} : { matchesActiveTurn }
367
+ };
368
+ }
369
+ function readNestedTurnId(record) {
370
+ const turn = record.turn;
371
+ return isJsonObject(turn) ? readString(turn, "id") : void 0;
372
+ }
373
+ function readNestedTurnThreadId(record) {
374
+ const turn = record.turn;
375
+ return isJsonObject(turn) ? readString(turn, "threadId") : void 0;
376
+ }
377
+ function readString(record, key) {
378
+ const value = record[key];
379
+ return typeof value === "string" && value.trim() ? value.trim() : void 0;
380
+ }
381
+ //#endregion
382
+ export { resolveCodexAppServerForModelProvider as a, formatAccount as c, formatComputerUseStatus as d, formatList as f, readString$1 as g, formatThreads as h, readCodexNotificationTurnId as i, formatCodexDisplayText as l, formatSkills as m, isCodexNotificationForTurn as n, resolveCodexAppServerForOpenClawToolPolicy as o, formatModels as p, readCodexNotificationThreadId as r, buildHelp as s, describeCodexNotificationCorrelation as t, formatCodexStatus as u };
@@ -1,7 +1,6 @@
1
- import { n as CodexAppServerRpcError } from "./client-kMCtlApt.js";
2
- import { b as buildCodexAppInventoryCacheKey } from "./thread-lifecycle-BJsazZ8j.js";
3
- import { a as getLeasedSharedCodexAppServerClient, h as resolveCodexAppServerHomeDir, i as createIsolatedCodexAppServerClient, l as withTimeout, o as releaseLeasedSharedCodexAppServerClient } from "./shared-client-xytpSKD0.js";
4
- import { t as resolveCodexAppServerDirectSandboxBypassBlock } from "./sandbox-guard-C-Yv9uwY.js";
1
+ import { n as CodexAppServerRpcError } from "./client-DovmVtbr.js";
2
+ import { S as buildCodexAppInventoryCacheKey } from "./thread-lifecycle-Cq1-IfZB.js";
3
+ import { h as resolveCodexAppServerHomeDir } from "./shared-client-CflavQ_i.js";
5
4
  import { createHash } from "node:crypto";
6
5
  //#region extensions/codex/src/app-server/capabilities.ts
7
6
  /**
@@ -77,35 +76,4 @@ function fingerprintCodexPluginAppCacheCredentials(startOptions) {
77
76
  return `sha256:${hash.digest("hex")}`;
78
77
  }
79
78
  //#endregion
80
- //#region extensions/codex/src/app-server/request.ts
81
- async function requestCodexAppServerJson(params) {
82
- const sandboxBlock = resolveCodexAppServerDirectSandboxBypassBlock({
83
- method: params.method,
84
- requestParams: params.requestParams,
85
- config: params.config,
86
- sessionKey: params.sessionKey,
87
- sessionId: params.sessionId
88
- });
89
- if (sandboxBlock) throw new Error(sandboxBlock);
90
- const timeoutMs = params.timeoutMs ?? 6e4;
91
- return await withTimeout((async () => {
92
- const client = await (params.isolated ? createIsolatedCodexAppServerClient : getLeasedSharedCodexAppServerClient)({
93
- startOptions: params.startOptions,
94
- timeoutMs,
95
- authProfileId: params.authProfileId,
96
- agentDir: params.agentDir,
97
- config: params.config
98
- });
99
- try {
100
- return await client.request(params.method, params.requestParams, { timeoutMs });
101
- } finally {
102
- if (params.isolated) await client.closeAndWait({
103
- exitTimeoutMs: 2e3,
104
- forceKillDelayMs: 250
105
- });
106
- else releaseLeasedSharedCodexAppServerClient(client);
107
- }
108
- })(), timeoutMs, `codex app-server ${params.method} timed out`);
109
- }
110
- //#endregion
111
- export { describeControlFailure as i, buildCodexPluginAppCacheKey as n, CODEX_CONTROL_METHODS as r, requestCodexAppServerJson as t };
79
+ export { CODEX_CONTROL_METHODS as n, describeControlFailure as r, buildCodexPluginAppCacheKey as t };
@@ -0,0 +1,9 @@
1
+ //#region extensions/codex/src/app-server/protocol.ts
2
+ function isJsonObject(value) {
3
+ return Boolean(value && typeof value === "object" && !Array.isArray(value));
4
+ }
5
+ function isRpcResponse(message) {
6
+ return "id" in message && !("method" in message);
7
+ }
8
+ //#endregion
9
+ export { isRpcResponse as n, isJsonObject as t };