@openclaw/codex 2026.9.2 → 2026.9.4

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 (120) hide show
  1. package/README.md +2 -0
  2. package/dist/api.js +29 -26
  3. package/dist/apply-CvT8tW5i.js +356 -0
  4. package/dist/{attempt-client-cleanup-Bp1ZOnk2.js → attempt-client-cleanup-DKHzbwt5.js} +38 -214
  5. package/dist/{attempt-context-CSazkWns.js → attempt-context-D44yeDII.js} +9 -7
  6. package/dist/{event-projector-usage-ZqEVbAEY.js → attempt-notifications-C9XufG6l.js} +3 -106
  7. package/dist/{auth-binding-Ds_QVm-X.js → auth-binding-CWlKVccJ.js} +2 -2
  8. package/dist/auth-cache-key-7orQae_j.js +498 -0
  9. package/dist/auth-profile-CwzO4_RG.js +43 -0
  10. package/dist/auth-profile-selection-DFu9e167.js +45 -0
  11. package/dist/binding-connection-D3udKbIE.js +60 -0
  12. package/dist/{bounded-turn-DxGJRYbY.js → bounded-turn-C_Hneydj.js} +28 -125
  13. package/dist/build-state-BCmg9-5p.js +19 -0
  14. package/dist/{capabilities-B1mgvpP8.js → capabilities-8vx68WLH.js} +1 -1
  15. package/dist/cli-metadata.js +1 -1
  16. package/dist/client-B57KWPQx.js +4005 -0
  17. package/dist/command-dispatch-BpduNGVf.js +21 -0
  18. package/dist/{command-formatters-DSbGMXA0.js → command-formatters-lxlkNZgU.js} +4 -3
  19. package/dist/{command-handlers-DOJvGv6-.js → command-handlers-tiL9iWj7.js} +788 -135
  20. package/dist/command-rpc-CR5EOEZX.js +233 -0
  21. package/dist/{compact-Y_xBqrHN.js → compact-B_H3AOd7.js} +19 -14
  22. package/dist/config-oIORaQ5T.js +106 -0
  23. package/dist/{config-CyapYSji.js → config-options-CXMq1T-C.js} +205 -593
  24. package/dist/config-runtime-D0zGNIHu.js +11 -0
  25. package/dist/{config-utils-C57JiJrU.js → config-utils-DujwEnhg.js} +2 -4
  26. package/dist/conversation-binding-DsB4-O7U.js +900 -0
  27. package/dist/{plugin-marketplace-discovery-B7gHXJ3d.js → conversation-control-CtUu1b3m.js} +11 -143
  28. package/dist/doctor-contract-api.js +5 -5
  29. package/dist/{dynamic-tools-BwpvTxaX.js → dynamic-tools-CmN5RAip.js} +133 -76
  30. package/dist/{effective-mcp-catalog-CY9Jn4bA.js → effective-mcp-catalog-Bd73bqA8.js} +3 -3
  31. package/dist/{elicitation-input-DMkeki8d.js → elicitation-input-DPoK8F7w.js} +8 -22
  32. package/dist/ephemeral-turn-D78_VmzO.js +101 -0
  33. package/dist/{event-projector-assistant-message-B9kp6iGC.js → event-projector-assistant-message-BmBM4qBV.js} +12 -25
  34. package/dist/event-projector-items-5VhsECCO.js +200 -0
  35. package/dist/event-projector-usage-BfXmpOec.js +102 -0
  36. package/dist/{harness-Czh2Sdoc.js → harness-C7rRa7bm.js} +48 -24
  37. package/dist/harness.js +1 -1
  38. package/dist/history-rejection-B4nOXNXF.js +13 -0
  39. package/dist/incognito-session-uhrBF6wJ.js +15 -0
  40. package/dist/index.js +406 -2915
  41. package/dist/inference-context-Dr_mzvk4.js +94 -0
  42. package/dist/inference-proxy-HGXKUIre.js +311 -0
  43. package/dist/{isolated-completion-CRh-51AK.js → isolated-completion-DWVb5U2J.js} +7 -4
  44. package/dist/launch-args-RXQwn8zV.js +90 -0
  45. package/dist/{managed-binary-DcpnJF9x.js → managed-binary-D22rNEcR.js} +13 -103
  46. package/dist/managed-thread-store-D1t5jh3G.js +66 -0
  47. package/dist/media-understanding-provider.js +4 -1
  48. package/dist/migration-provider-api.js +2 -0
  49. package/dist/{model-catalog-DT5vo6qo.js → model-catalog-Dq2n8f_p.js} +6 -5
  50. package/dist/{models-CcrgSMQR.js → models-PCKOim-h.js} +3 -3
  51. package/dist/native-execution-policy-umd0tgh4.js +128 -0
  52. package/dist/native-subagent-history-DjtPloaU.js +140 -0
  53. package/dist/native-subagent-history-owner-Pcp7JuVF.js +34 -0
  54. package/dist/{native-subagent-monitor-B3bvQGcg.js → native-subagent-monitor-fQ7eIXEf.js} +115 -460
  55. package/dist/native-subagent-task-ids-BzTdT0Uw.js +387 -0
  56. package/dist/node-cli-sessions-DKaOmVUh.js +527 -0
  57. package/dist/{node-exec-server.runtime-nfbUOtUB.js → node-exec-server.runtime-Cl2vapEi.js} +55 -24
  58. package/dist/plan-7uG-Fp36.js +947 -0
  59. package/dist/plugin-activation-BYQculil.js +138 -0
  60. package/dist/{thread-resume-BLgqkUc1.js → plugin-app-cache-key-d0eKxy7b.js} +4 -52
  61. package/dist/{plugin-approval-roundtrip-aQVdyL5g.js → plugin-approval-roundtrip-Bz3FT8W5.js} +1 -1
  62. package/dist/plugin-inventory-oL4Na1ZG.js +328 -0
  63. package/dist/plugin-marketplace-discovery-P-Vndfqq.js +137 -0
  64. package/dist/{plugin-metadata-cache-BwCLTY_U.js → plugin-metadata-cache-ClPJpRio.js} +17 -9
  65. package/dist/protocol-5bh1G-H7.js +275 -0
  66. package/dist/provider-MQ8PVkuE.js +50 -0
  67. package/dist/{provider-capabilities-BpG9Ltc5.js → provider-capabilities-BvCUL69A.js} +2 -2
  68. package/dist/{rate-limits-Fx_l4eNa.js → rate-limits-CBMmWBr9.js} +1 -1
  69. package/dist/request-B7hEkBGq.js +212 -0
  70. package/dist/rpc-error-ttN_QjEm.js +30 -0
  71. package/dist/{run-attempt-BzthFQSM.js → run-attempt-CvsAAGa0.js} +664 -377
  72. package/dist/{runtime-artifact-Bh_gf6-t.js → runtime-artifact-BJ0rXBZ_.js} +27 -27
  73. package/dist/sandbox-guard-BxgyoM8M.js +166 -0
  74. package/dist/{session-binding-4Ki04sW-.js → session-binding-CI8UuilT.js} +30 -48
  75. package/dist/{session-binding-record-CyaXZvTe.js → session-binding-record-Bcvslnhf.js} +12 -26
  76. package/dist/session-catalog-adoption-tcZi1IfX.js +251 -0
  77. package/dist/session-catalog-archive-CwKg8Xz2.js +56 -0
  78. package/dist/session-catalog-ct-AH01I.js +1477 -0
  79. package/dist/session-catalog-home-id-CwhLdC03.js +18 -0
  80. package/dist/session-catalog-node-adoption-B1tgDW-m.js +182 -0
  81. package/dist/session-catalog-node-continue-Ci-DXyJP.js +238 -0
  82. package/dist/session-catalog-provenance-D-dIfRAH.js +96 -0
  83. package/dist/{session-cli-BjLhpmS1.js → session-cli-DNN_jhGc.js} +3 -2
  84. package/dist/{session-history-DWmMqiqW.js → session-history-Cz-tOOYj.js} +6 -3
  85. package/dist/{session-upstream-marker-DReTpGz6.js → session-history-import-DwyijFI6.js} +5 -50
  86. package/dist/{session-history-read-LHldwvyh.js → session-history-read-cxPUxyVV.js} +21 -7
  87. package/dist/session-history-worker-runtime.js +18 -6
  88. package/dist/session-history.worker-BeK1YOyT.js +378 -0
  89. package/dist/session-history.worker.js +1 -1
  90. package/dist/{session-initialization-BCFVnLL4.js → session-initialization-Ct0_Hzmg.js} +2 -2
  91. package/dist/{session-permission-policy-BaueHmSj.js → session-permission-policy-BBmXA8Eg.js} +4 -7
  92. package/dist/{session-retirement-DNdmYdFc.js → session-retirement-B2YfbAAT.js} +6 -5
  93. package/dist/session-upstream-marker-D15C9NHp.js +46 -0
  94. package/dist/{settled-turn-context-BOM3Y1pl.js → settled-turn-context-Du6gdUDd.js} +9 -9
  95. package/dist/{settled-turn-finalizer-BI-b1sry.js → settled-turn-finalizer-Dn91stmc.js} +8 -7
  96. package/dist/shared-client-CscigXXL.js +3109 -0
  97. package/dist/{side-question-B6DWAw1A.js → side-question-BGMJQf4U.js} +65 -170
  98. package/dist/source-CElXU0Oy.js +518 -0
  99. package/dist/thread-archive-guard-DfpBr-Sz.js +53 -0
  100. package/dist/thread-history-page-D0JIp48V.js +361 -0
  101. package/dist/{thread-lifecycle-DPK30jad.js → thread-lifecycle-DXl1-I6b.js} +187 -639
  102. package/dist/{thread-ownership-CbucAmmp.js → thread-ownership-BsDRTsyp.js} +13 -15
  103. package/dist/thread-policy-BuEQfE0g.js +54 -0
  104. package/dist/thread-resume-DsDOZpFg.js +52 -0
  105. package/dist/timeout-BVw8aaM1.js +33 -0
  106. package/dist/transcript-history-projection-v17wXgdK.js +238 -0
  107. package/dist/{transcript-mirror-_njEB84z.js → transcript-mirror-C5CKgNy6.js} +50 -260
  108. package/dist/{transcript-mirror-attestation-Byl34PC-.js → transcript-mirror-attestation-DibE0krH.js} +17 -4
  109. package/dist/{transport-stdio-CzTngV0j.js → transport-stdio-BGjHoYLr.js} +73 -43
  110. package/dist/{upstream-session-fork-1fwbNKzQ.js → upstream-session-fork-BZerMte_.js} +27 -19
  111. package/dist/{usage-i9fv5-4m.js → usage-tCk-mg_x.js} +4 -3
  112. package/dist/version-omm6IPI3.js +12 -0
  113. package/dist/{web-search-provider.runtime-DKQn67A7.js → web-search-provider.runtime-B7bGbGWq.js} +3 -3
  114. package/openclaw.plugin.json +23 -1
  115. package/package.json +4 -4
  116. package/dist/request-C8H22rPi.js +0 -475
  117. package/dist/session-catalog-B47uwekb.js +0 -3272
  118. package/dist/session-history.worker-zZVcx0ME.js +0 -267
  119. package/dist/shared-client-CKhX2kFt.js +0 -7505
  120. package/dist/thread-policy-CTalhWFy.js +0 -105
package/README.md CHANGED
@@ -34,4 +34,6 @@ For a supervised branch, Codex App Server selects the snapshot fork's model and
34
34
 
35
35
  The visible-history mirror keeps at most 200 user or assistant messages, 512 KiB total, and 64 KiB per message. Image inputs become `[Image attachment]`; image data and local paths are not copied.
36
36
 
37
+ When settled-turn recovery rejects history, the `codex settled-turn finalization context capture failed` warning includes a stable `reason`, such as `item_limit`, `byte_limit`, `field_limit`, `unsupported_user_image`, or `snapshot_invalidated`. Unknown failures use `history_read_failed`. The warning excludes transcript content and exception text. Rejected history remains unavailable for finalization, and completed actions are never replayed.
38
+
37
39
  See the [Codex harness](https://docs.openclaw.ai/plugins/codex-harness) and [Codex supervision](https://docs.openclaw.ai/plugins/codex-supervision) guides.
package/dist/api.js CHANGED
@@ -1,10 +1,13 @@
1
- import { a as resolveCodexAppServerStartOptionsForAgent, i as resolveCodexAppServerRuntimeOptions } from "./config-CyapYSji.js";
2
- import { n as resolveManagedCodexAppServerStartOptions, o as CODEX_APP_SERVER_VERSION, r as resolveManagedCodexNativeCommand, t as isManagedCodexDesktopCommand } from "./managed-binary-DcpnJF9x.js";
1
+ import { a as resolveCodexAppServerStartOptionsForAgent } from "./config-options-CXMq1T-C.js";
2
+ import { i as resolveManagedCodexNativeCommand, r as resolveManagedCodexAppServerStartOptions, t as isManagedCodexDesktopCommand } from "./managed-binary-D22rNEcR.js";
3
+ import { t as CODEX_APP_SERVER_VERSION } from "./version-omm6IPI3.js";
4
+ import "./config-oIORaQ5T.js";
5
+ import { n as resolveCodexAppServerRuntimeOptions } from "./config-runtime-D0zGNIHu.js";
3
6
  import { listAgentIds, resolveAgentDir } from "openclaw/plugin-sdk/agent-scope-runtime";
7
+ import { runUtf8CommandWithTimeout } from "openclaw/plugin-sdk/process-runtime";
4
8
  import path from "node:path";
5
- import { resolveDefaultModelForAgent } from "openclaw/plugin-sdk/agent-runtime";
6
- import { execFile } from "node:child_process";
7
9
  import { fileURLToPath } from "node:url";
10
+ import { resolveDefaultModelForAgent } from "openclaw/plugin-sdk/agent-runtime";
8
11
  import { resolveEffectiveAgentRuntime } from "openclaw/plugin-sdk/command-auth-native";
9
12
  //#region extensions/codex/src/doctor.ts
10
13
  const CODEX_MANAGED_APP_SERVER_CHECK_ID = "codex/managed-app-server";
@@ -13,7 +16,7 @@ const CODEX_VERSION_MAX_BUFFER_BYTES = 65536;
13
16
  function managedCodexFinding(params) {
14
17
  return {
15
18
  checkId: CODEX_MANAGED_APP_SERVER_CHECK_ID,
16
- severity: "error",
19
+ severity: params.severity ?? "error",
17
20
  source: "codex",
18
21
  message: params.message,
19
22
  ...params.path ? { path: params.path } : {},
@@ -27,31 +30,26 @@ function readErrorMessage(error) {
27
30
  function parseCodexVersion(output) {
28
31
  return /(?:^|\s)(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?)(?:\s|$)/u.exec(output)?.[1];
29
32
  }
30
- function runVersionCommand(command) {
31
- return new Promise((resolve, reject) => {
32
- execFile(command, ["--version"], {
33
- encoding: "utf8",
34
- maxBuffer: CODEX_VERSION_MAX_BUFFER_BYTES,
35
- timeout: CODEX_VERSION_TIMEOUT_MS,
36
- windowsHide: true
37
- }, (error, stdout, stderr) => {
38
- if (error) {
39
- reject(new Error(readErrorMessage(error), { cause: error }));
40
- return;
41
- }
42
- resolve({
43
- stdout,
44
- stderr
45
- });
46
- });
33
+ async function runVersionCommand(command, env) {
34
+ const result = await runUtf8CommandWithTimeout([command, "--version"], {
35
+ baseEnv: env,
36
+ input: "",
37
+ timeoutMs: CODEX_VERSION_TIMEOUT_MS,
38
+ maxOutputBytes: CODEX_VERSION_MAX_BUFFER_BYTES,
39
+ outputCapture: "head",
40
+ terminateOnOutputLimit: true,
41
+ killProcessTree: true,
42
+ killSignal: "SIGKILL",
43
+ killGraceMs: 0
47
44
  });
45
+ if (result.termination !== "exit" || result.code !== 0 || result.outputLimitExceeded) throw new Error(result.outputLimitExceeded ? "Version output exceeded its capture limit" : result.termination === "timeout" ? `Version probe timed out after ${CODEX_VERSION_TIMEOUT_MS} ms` : `Version probe failed (${result.signal ?? result.code ?? result.termination})`);
46
+ return result;
48
47
  }
49
48
  function createCodexManagedAppServerHealthCheck(params) {
50
49
  const resolveStartOptions = params.deps?.resolveStartOptions ?? resolveManagedCodexAppServerStartOptions;
51
50
  const resolveAgentStartOptions = params.deps?.resolveAgentStartOptions ?? resolveCodexAppServerStartOptionsForAgent;
52
51
  const isDesktopCommand = params.deps?.isDesktopCommand ?? isManagedCodexDesktopCommand;
53
52
  const resolveNativeCommand = params.deps?.resolveNativeCommand ?? resolveManagedCodexNativeCommand;
54
- const executeVersion = params.deps?.runVersionCommand ?? runVersionCommand;
55
53
  return {
56
54
  id: CODEX_MANAGED_APP_SERVER_CHECK_ID,
57
55
  kind: "plugin",
@@ -66,6 +64,9 @@ function createCodexManagedAppServerHealthCheck(params) {
66
64
  }).start;
67
65
  if (start.transport !== "stdio" || start.commandSource !== "managed") return [];
68
66
  const env = ctx.env ?? process.env;
67
+ const isFinalization = ctx.mode === "fix" && env.OPENCLAW_UPDATE_POST_CORE === "1";
68
+ const versionFailureSeverity = isFinalization ? "warning" : "error";
69
+ const versionFailureHint = isFinalization ? "Codex readiness will be rechecked by its plugin after restart; inspect the Codex plugin if the warning persists." : void 0;
69
70
  let resolved;
70
71
  for (const agentId of listAgentIds(ctx.cfg)) {
71
72
  const model = resolveDefaultModelForAgent({
@@ -106,21 +107,23 @@ function createCodexManagedAppServerHealthCheck(params) {
106
107
  })];
107
108
  let output;
108
109
  try {
109
- output = await executeVersion(nativeCommand);
110
+ output = await (params.deps?.runVersionCommand ? params.deps.runVersionCommand(nativeCommand) : runVersionCommand(nativeCommand, env));
110
111
  } catch (error) {
111
112
  return [managedCodexFinding({
112
113
  message: `Managed Codex app-server version check failed: ${readErrorMessage(error)}`,
114
+ severity: versionFailureSeverity,
113
115
  path: nativeCommand,
114
116
  requirement: `Codex ${CODEX_APP_SERVER_VERSION} must report its version within ${CODEX_VERSION_TIMEOUT_MS} ms`,
115
- fixHint: "Repair or reinstall the staged OpenClaw package, then rerun the candidate check before cutover."
117
+ fixHint: versionFailureHint ?? "Repair or reinstall the staged OpenClaw package, then rerun the candidate check before cutover."
116
118
  })];
117
119
  }
118
120
  const detectedVersion = parseCodexVersion(`${output.stdout}\n${output.stderr}`);
119
121
  if (detectedVersion !== "0.153.4") return [managedCodexFinding({
122
+ severity: versionFailureSeverity,
120
123
  message: detectedVersion ? `Managed Codex app-server version mismatch: expected ${CODEX_APP_SERVER_VERSION}, detected ${detectedVersion}.` : `Managed Codex app-server did not report a parseable version; expected ${CODEX_APP_SERVER_VERSION}.`,
121
124
  path: nativeCommand,
122
125
  requirement: `the exact OpenClaw-pinned Codex version ${CODEX_APP_SERVER_VERSION}`,
123
- fixHint: "Reinstall the staged OpenClaw package so its managed @openai/codex dependency matches the pinned version, then rerun the candidate check."
126
+ fixHint: versionFailureHint ?? "Reinstall the staged OpenClaw package so its managed @openai/codex dependency matches the pinned version, then rerun the candidate check."
124
127
  })];
125
128
  return [];
126
129
  }
@@ -0,0 +1,356 @@
1
+ import { c as CODEX_PLUGINS_MARKETPLACE_NAME } from "./plugin-inventory-oL4Na1ZG.js";
2
+ import { x as readCodexPluginConfig } from "./protocol-5bh1G-H7.js";
3
+ import { s as resolveCodexAppServerFallbackApiKeyCacheKey } from "./auth-cache-key-7orQae_j.js";
4
+ import { r as buildCodexPluginAppCacheKey, s as defaultCodexAppInventoryCache } from "./plugin-app-cache-key-d0eKxy7b.js";
5
+ import { i as requestCodexAppServerJson } from "./request-B7hEkBGq.js";
6
+ import "./config-oIORaQ5T.js";
7
+ import { n as resolveCodexAppServerRuntimeOptions } from "./config-runtime-D0zGNIHu.js";
8
+ import { i as resolveCodexAppServerAuthProfileIdForAgent } from "./auth-profile-CwzO4_RG.js";
9
+ import { c as getLeasedSharedCodexAppServerClient, et as resolveCodexAppServerAuthAccountCacheKey, h as releaseLeasedSharedCodexAppServerClient, o as clearSharedCodexAppServerClientIfCurrentAndWait } from "./shared-client-CscigXXL.js";
10
+ import { t as ensureCodexPluginActivation } from "./plugin-activation-BYQculil.js";
11
+ import { CODEX_PLUGIN_CONFIG_PATH, buildCodexMigrationPlan, buildCodexPluginsConfigValue, hasCodexPluginConfigConflict, n as applyCodexAuthItems, r as resolveCodexConfigPatchMode, readCodexPluginMigrationConfigEntry, t as resolveCodexMigrationTargets } from "./plan-7uG-Fp36.js";
12
+ import { uniqueStrings } from "openclaw/plugin-sdk/string-coerce-runtime";
13
+ import { parseStrictNonNegativeInteger } from "openclaw/plugin-sdk/number-runtime";
14
+ import path from "node:path";
15
+ import { coerceErrorMessage } from "openclaw/plugin-sdk/error-runtime";
16
+ import { sleep } from "openclaw/plugin-sdk/runtime-env";
17
+ import { MIGRATION_REASON_TARGET_EXISTS, applyMigrationManualItem, markMigrationItemConflict, markMigrationItemError, markMigrationItemSkipped, resolveMigrationConfigRuntime, summarizeMigrationItems, writeMigrationConfigPath } from "openclaw/plugin-sdk/migration";
18
+ import { archiveMigrationItem, copyMemoryMigrationFileItem, copyMigrationFileItem, withCachedMigrationConfigRuntime, writeMigrationReport } from "openclaw/plugin-sdk/migration-runtime";
19
+ //#region extensions/codex/src/migration/apply-report.ts
20
+ function codexPluginActivationReportState(result) {
21
+ switch (result.reason) {
22
+ case "already_active":
23
+ case "installed": return {
24
+ installed: true,
25
+ enabled: true
26
+ };
27
+ case "auth_required": return {
28
+ installed: true,
29
+ enabled: false
30
+ };
31
+ case "disabled":
32
+ case "install_failed":
33
+ case "marketplace_missing":
34
+ case "plugin_missing": return {
35
+ installed: false,
36
+ enabled: false
37
+ };
38
+ case "refresh_failed": return {
39
+ installed: true,
40
+ enabled: false
41
+ };
42
+ }
43
+ return result.reason;
44
+ }
45
+ function sanitizeAppsNeedingAuth(apps) {
46
+ return apps.map((app) => ({
47
+ id: app.id,
48
+ name: app.name,
49
+ needsAuth: true
50
+ }));
51
+ }
52
+ //#endregion
53
+ //#region extensions/codex/src/migration/apply.ts
54
+ const CODEX_PLUGIN_AUTH_REQUIRED_REASON = "auth_required";
55
+ const CODEX_PLUGIN_NOT_SELECTED_REASON = "not selected for migration";
56
+ const CODEX_PLUGIN_LOAD_WARNING = "Some Codex plugins could not be migrated. Run `openclaw migrate codex` after onboarding.";
57
+ const TARGET_CODEX_MARKETPLACE_DISCOVERY_POLL_MS = 250;
58
+ const TARGET_CODEX_MARKETPLACE_DISCOVERY_TIMEOUT_MS = 3e4;
59
+ const TARGET_CODEX_MARKETPLACE_DISCOVERY_TIMEOUT_ENV = "OPENCLAW_CODEX_MIGRATION_PLUGIN_LIST_TIMEOUT_MS";
60
+ var CodexPluginConfigConflictError = class extends Error {
61
+ constructor(reason) {
62
+ super(reason);
63
+ this.reason = reason;
64
+ this.name = "CodexPluginConfigConflictError";
65
+ }
66
+ };
67
+ function shouldReturnCodexPluginConfigPatch(ctx) {
68
+ return resolveCodexConfigPatchMode(ctx) === "return";
69
+ }
70
+ function prepareTargetCodexAppServer(ctx) {
71
+ const appServer = resolveTargetCodexAppServer(ctx);
72
+ const targets = resolveCodexMigrationTargets(ctx);
73
+ let warmedClient;
74
+ const ready = getLeasedSharedCodexAppServerClient({
75
+ startOptions: appServer.start,
76
+ timeoutMs: 6e4,
77
+ agentDir: targets.agentDir,
78
+ config: ctx.config
79
+ }).then((client) => {
80
+ warmedClient = client;
81
+ }, () => void 0);
82
+ return { async dispose() {
83
+ await ready;
84
+ if (warmedClient) releaseLeasedSharedCodexAppServerClient(warmedClient);
85
+ await clearSharedCodexAppServerClientIfCurrentAndWait(warmedClient, {
86
+ exitTimeoutMs: 2e3,
87
+ forceKillDelayMs: 250
88
+ });
89
+ } };
90
+ }
91
+ async function applyCodexMigrationPlan(params) {
92
+ const plan = params.plan ?? await buildCodexMigrationPlan(params.ctx);
93
+ const reportDir = params.ctx.reportDir ?? path.join(params.ctx.stateDir, "migration", "codex");
94
+ const items = [];
95
+ const targets = resolveCodexMigrationTargets(params.ctx);
96
+ const codexHome = typeof plan.metadata?.codexHome === "string" && plan.metadata.codexHome.trim() ? plan.metadata.codexHome : plan.source;
97
+ const authSource = {
98
+ codexHome,
99
+ authPath: path.join(codexHome, "auth.json"),
100
+ modelsCachePath: path.join(codexHome, "models_cache.json")
101
+ };
102
+ const runtime = withCachedMigrationConfigRuntime(params.ctx.runtime ?? params.runtime, params.ctx.config);
103
+ const applyCtx = {
104
+ ...params.ctx,
105
+ runtime
106
+ };
107
+ for (const item of plan.items) {
108
+ if (item.status !== "planned") {
109
+ items.push(item);
110
+ continue;
111
+ }
112
+ if (item.id === "config:codex-plugins") items.push(await applyCodexPluginConfigItem(applyCtx, item, items));
113
+ else if (item.kind === "auth") items.push(...await applyCodexAuthItems({
114
+ ctx: applyCtx,
115
+ item,
116
+ source: authSource,
117
+ targets
118
+ }));
119
+ else if (item.kind === "plugin" && item.action === "install") items.push(await applyCodexPluginInstallItem(applyCtx, item));
120
+ else if (item.kind === "manual") items.push(applyMigrationManualItem(item));
121
+ else if (item.action === "archive") items.push(await archiveMigrationItem(item, reportDir));
122
+ else if (item.kind === "memory") items.push(await copyMemoryMigrationFileItem(item, reportDir, {
123
+ workspaceDir: targets.workspaceDir,
124
+ overwrite: params.ctx.overwrite
125
+ }));
126
+ else items.push(await copyMigrationFileItem(item, reportDir, { overwrite: params.ctx.overwrite }));
127
+ }
128
+ const result = {
129
+ ...plan,
130
+ items,
131
+ summary: summarizeMigrationItems(items),
132
+ backupPath: params.ctx.backupPath,
133
+ reportDir
134
+ };
135
+ if (items.some(isCodexPluginLoadWarningItem)) {
136
+ result.warnings = uniqueStrings([...result.warnings ?? [], CODEX_PLUGIN_LOAD_WARNING]);
137
+ result.nextSteps = uniqueStrings([CODEX_PLUGIN_LOAD_WARNING, ...result.nextSteps ?? []]);
138
+ }
139
+ await writeMigrationReport(result, { title: "Codex Migration Report" });
140
+ return result;
141
+ }
142
+ async function applyCodexPluginInstallItem(ctx, item) {
143
+ const policy = readCodexPluginPolicy(item);
144
+ if (!policy) return {
145
+ ...markMigrationItemError(item, "invalid Codex plugin migration item"),
146
+ details: {
147
+ ...item.details,
148
+ code: "invalid_plugin_item"
149
+ }
150
+ };
151
+ try {
152
+ const appCacheKey = await buildTargetCodexPluginAppCacheKey(ctx);
153
+ const appServer = resolveTargetCodexAppServer(ctx);
154
+ const result = await ensureCodexPluginActivation({
155
+ identity: policy,
156
+ installEvenIfActive: true,
157
+ request: async (method, requestParams) => await requestTargetCodexAppServerJson({
158
+ method,
159
+ requestParams,
160
+ timeoutMs: 6e4,
161
+ startOptions: appServer.start,
162
+ agentDir: resolveCodexMigrationTargets(ctx).agentDir,
163
+ config: ctx.config,
164
+ isolated: false
165
+ }),
166
+ appCache: defaultCodexAppInventoryCache,
167
+ appCacheKey
168
+ });
169
+ const baseDetails = {
170
+ ...item.details,
171
+ code: result.reason,
172
+ activationReason: result.reason,
173
+ ...codexPluginActivationReportState(result),
174
+ installAttempted: result.installAttempted,
175
+ diagnostics: result.diagnostics.map((diagnostic) => diagnostic.message)
176
+ };
177
+ if (result.ok) return {
178
+ ...item,
179
+ status: "migrated",
180
+ ...result.reason === "already_active" ? { reason: "already active" } : {},
181
+ details: baseDetails
182
+ };
183
+ if (result.reason === CODEX_PLUGIN_AUTH_REQUIRED_REASON) return {
184
+ ...item,
185
+ status: "skipped",
186
+ reason: CODEX_PLUGIN_AUTH_REQUIRED_REASON,
187
+ details: {
188
+ ...baseDetails,
189
+ appsNeedingAuth: sanitizeAppsNeedingAuth(result.installResponse?.appsNeedingAuth ?? [])
190
+ }
191
+ };
192
+ if (result.reason === "plugin_missing" || result.reason === "marketplace_missing") return {
193
+ ...item,
194
+ status: "warning",
195
+ reason: result.reason,
196
+ message: `Codex plugin "${policy.pluginName}" could not be migrated automatically`,
197
+ details: {
198
+ ...baseDetails,
199
+ warningReason: CODEX_PLUGIN_LOAD_WARNING
200
+ }
201
+ };
202
+ return {
203
+ ...item,
204
+ status: "error",
205
+ reason: result.reason,
206
+ details: baseDetails
207
+ };
208
+ } catch (error) {
209
+ if (isCodexPluginInventoryLoadError(error)) return {
210
+ ...item,
211
+ status: "warning",
212
+ reason: "plugin_inventory_unavailable",
213
+ message: `Codex plugin "${policy.pluginName}" could not be migrated automatically`,
214
+ details: {
215
+ ...item.details,
216
+ code: "plugin_inventory_unavailable",
217
+ warningReason: CODEX_PLUGIN_LOAD_WARNING,
218
+ diagnostic: coerceErrorMessage(error)
219
+ }
220
+ };
221
+ return {
222
+ ...item,
223
+ status: "error",
224
+ reason: coerceErrorMessage(error),
225
+ details: {
226
+ ...item.details,
227
+ code: "plugin_install_failed"
228
+ }
229
+ };
230
+ }
231
+ }
232
+ function isCodexPluginInventoryLoadError(error) {
233
+ return coerceErrorMessage(error).includes("codex app-server plugin/list timed out");
234
+ }
235
+ function resolveTargetCodexAppServer(ctx) {
236
+ return resolveCodexAppServerRuntimeOptions({ pluginConfig: readCodexPluginConfig(ctx.config) });
237
+ }
238
+ async function requestTargetCodexAppServerJson(params) {
239
+ if (params.method !== "plugin/list") return await requestCodexAppServerJson(params);
240
+ const deadline = Date.now() + params.timeoutMs;
241
+ const discoveryTimeoutMs = targetCodexMarketplaceDiscoveryTimeoutMs();
242
+ const discoveryDeadline = Math.min(deadline, Date.now() + discoveryTimeoutMs);
243
+ let lastResponse;
244
+ let attempt = 0;
245
+ do {
246
+ attempt += 1;
247
+ const remainingMs = Math.max(1, discoveryDeadline - Date.now());
248
+ lastResponse = await requestCodexAppServerJson({
249
+ ...params,
250
+ timeoutMs: remainingMs
251
+ });
252
+ if (hasOpenAiCuratedMarketplace(lastResponse)) return lastResponse;
253
+ if (Date.now() >= discoveryDeadline) return lastResponse;
254
+ const waitMs = Math.min(TARGET_CODEX_MARKETPLACE_DISCOVERY_POLL_MS, discoveryDeadline - Date.now());
255
+ await sleep(waitMs);
256
+ } while (Date.now() < discoveryDeadline);
257
+ return lastResponse;
258
+ }
259
+ function hasOpenAiCuratedMarketplace(response) {
260
+ if (!response || typeof response !== "object" || !("marketplaces" in response)) return false;
261
+ const marketplaces = response.marketplaces;
262
+ return Array.isArray(marketplaces) && marketplaces.some((marketplace) => marketplace && typeof marketplace === "object" && marketplace.name === "openai-curated");
263
+ }
264
+ function targetCodexMarketplaceDiscoveryTimeoutMs(env = process.env) {
265
+ const configured = parseStrictNonNegativeInteger(env[TARGET_CODEX_MARKETPLACE_DISCOVERY_TIMEOUT_ENV]);
266
+ if (configured !== void 0) return configured;
267
+ return TARGET_CODEX_MARKETPLACE_DISCOVERY_TIMEOUT_MS;
268
+ }
269
+ function isCodexPluginLoadWarningItem(item) {
270
+ return item.kind === "plugin" && item.action === "install" && item.status === "warning" && item.details?.warningReason === CODEX_PLUGIN_LOAD_WARNING;
271
+ }
272
+ async function buildTargetCodexPluginAppCacheKey(ctx) {
273
+ const targets = resolveCodexMigrationTargets(ctx);
274
+ const appServer = resolveTargetCodexAppServer(ctx);
275
+ const authProfileId = resolveCodexAppServerAuthProfileIdForAgent({
276
+ agentDir: targets.agentDir,
277
+ config: ctx.config
278
+ });
279
+ const accountId = await resolveCodexAppServerAuthAccountCacheKey({
280
+ authProfileId,
281
+ agentDir: targets.agentDir,
282
+ config: ctx.config
283
+ });
284
+ const envApiKeyFingerprint = authProfileId ? void 0 : resolveCodexAppServerFallbackApiKeyCacheKey({ startOptions: appServer.start });
285
+ return buildCodexPluginAppCacheKey({
286
+ appServer,
287
+ agentDir: targets.agentDir,
288
+ authProfileId,
289
+ accountId,
290
+ envApiKeyFingerprint
291
+ });
292
+ }
293
+ async function applyCodexPluginConfigItem(ctx, item, appliedItems) {
294
+ if (appliedItems.filter((candidate) => candidate.kind === "plugin" && candidate.action === "install" && readCodexPluginPolicy(candidate) !== void 0 && !isCodexPluginConfigTerminal(candidate)).length > 0) return {
295
+ ...item,
296
+ status: "warning",
297
+ reason: "selected Codex plugin activation is incomplete"
298
+ };
299
+ const entries = appliedItems.map(readAppliedPluginConfigEntry).filter((entry) => entry !== void 0);
300
+ if (entries.length === 0) return {
301
+ ...markMigrationItemSkipped(item, "no selected Codex plugins"),
302
+ deferredCompletion: true
303
+ };
304
+ const returnPatch = shouldReturnCodexPluginConfigPatch(ctx);
305
+ const configApi = resolveMigrationConfigRuntime(ctx);
306
+ const currentConfig = returnPatch ? ctx.config : configApi?.current?.();
307
+ if (!currentConfig) return markMigrationItemError(item, "config runtime unavailable");
308
+ const value = buildCodexPluginsConfigValue(entries, currentConfig);
309
+ if (!ctx.overwrite && hasCodexPluginConfigConflict(currentConfig, value)) return markMigrationItemConflict(item, MIGRATION_REASON_TARGET_EXISTS);
310
+ const migratedItem = {
311
+ ...item,
312
+ status: "migrated",
313
+ details: {
314
+ ...item.details,
315
+ path: [...CODEX_PLUGIN_CONFIG_PATH],
316
+ value
317
+ }
318
+ };
319
+ if (returnPatch) return migratedItem;
320
+ if (!configApi?.mutateConfigFile) return markMigrationItemError(item, "config runtime unavailable");
321
+ try {
322
+ await configApi.mutateConfigFile({
323
+ base: "runtime",
324
+ afterWrite: { mode: "auto" },
325
+ mutate(draft) {
326
+ if (!ctx.overwrite && hasCodexPluginConfigConflict(draft, value)) throw new CodexPluginConfigConflictError(MIGRATION_REASON_TARGET_EXISTS);
327
+ writeMigrationConfigPath(draft, CODEX_PLUGIN_CONFIG_PATH, value);
328
+ }
329
+ });
330
+ return migratedItem;
331
+ } catch (error) {
332
+ if (error instanceof CodexPluginConfigConflictError) return markMigrationItemConflict(item, error.reason);
333
+ return markMigrationItemError(item, coerceErrorMessage(error));
334
+ }
335
+ }
336
+ function isCodexPluginConfigTerminal(item) {
337
+ return item.status === "migrated" || item.status === "skipped" && (item.deferredCompletion === true || item.reason === CODEX_PLUGIN_NOT_SELECTED_REASON || item.reason === CODEX_PLUGIN_AUTH_REQUIRED_REASON);
338
+ }
339
+ function readAppliedPluginConfigEntry(item) {
340
+ if (item.status === "migrated" || item.deferredCompletion === true) return readCodexPluginMigrationConfigEntry(item, true);
341
+ if (item.status === "skipped" && item.reason === CODEX_PLUGIN_AUTH_REQUIRED_REASON) return readCodexPluginMigrationConfigEntry(item, false);
342
+ }
343
+ function readCodexPluginPolicy(item) {
344
+ const entry = readCodexPluginMigrationConfigEntry(item, true);
345
+ if (!entry) return;
346
+ return {
347
+ configKey: entry.configKey,
348
+ marketplaceName: CODEX_PLUGINS_MARKETPLACE_NAME,
349
+ pluginName: entry.pluginName,
350
+ enabled: true,
351
+ allowDestructiveActions: true,
352
+ destructiveApprovalMode: "allow"
353
+ };
354
+ }
355
+ //#endregion
356
+ export { applyCodexMigrationPlan, prepareTargetCodexAppServer };