@yansigit/opencodex 2.31.3 → 2.33.0

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 (176) hide show
  1. package/README.md +2 -2
  2. package/bin/ocx.mjs +99 -70
  3. package/gui/dist/assets/index-DKLr4LTE.js +102 -0
  4. package/gui/dist/assets/index-DrSQdTRd.css +1 -0
  5. package/gui/dist/index.html +2 -2
  6. package/package.json +6 -5
  7. package/src/adapters/anthropic.ts +25 -13
  8. package/src/adapters/azure.ts +20 -4
  9. package/src/adapters/base.ts +5 -1
  10. package/src/adapters/command-code.ts +42 -10
  11. package/src/adapters/cursor/live-models.ts +8 -0
  12. package/src/adapters/cursor/live-transport.ts +1 -1
  13. package/src/adapters/cursor/native-exec-desktop.ts +16 -0
  14. package/src/adapters/cursor/protobuf-events.ts +158 -7
  15. package/src/adapters/cursor/protobuf-request.ts +33 -15
  16. package/src/adapters/cursor/request-builder.ts +4 -3
  17. package/src/adapters/cursor/tool-definitions.ts +27 -1
  18. package/src/adapters/cursor/types.ts +4 -3
  19. package/src/adapters/cursor.ts +9 -0
  20. package/src/adapters/google-antigravity-replay.ts +2 -2
  21. package/src/adapters/google-antigravity-wire.ts +7 -0
  22. package/src/adapters/google-errors.ts +6 -2
  23. package/src/adapters/google-http.ts +30 -7
  24. package/src/adapters/google-truncation.ts +5 -0
  25. package/src/adapters/google-wire-compiler.ts +38 -6
  26. package/src/adapters/google.ts +154 -33
  27. package/src/adapters/kiro-tools.ts +20 -9
  28. package/src/adapters/kiro.ts +0 -3
  29. package/src/adapters/openai-chat.ts +9 -0
  30. package/src/adapters/openai-responses.ts +4 -1
  31. package/src/adapters/tool-catalog-nudge.ts +1 -1
  32. package/src/adapters/xai-web-search.ts +7 -2
  33. package/src/bridge.ts +133 -24
  34. package/src/claude/context-windows.ts +16 -9
  35. package/src/cli/dispatch.ts +50 -2
  36. package/src/cli/doctor.ts +26 -13
  37. package/src/cli/help.ts +4 -3
  38. package/src/cli/index.ts +20 -6
  39. package/src/cli/models.ts +13 -3
  40. package/src/cli/observe.ts +20 -5
  41. package/src/cli/provider.ts +8 -1
  42. package/src/cli/registry.ts +7 -5
  43. package/src/cli/status.ts +25 -1
  44. package/src/cli/system-restart-client.ts +1 -1
  45. package/src/cli/usage-report.ts +134 -0
  46. package/src/codex/app-server-processes.ts +3 -1
  47. package/src/codex/auth-api.ts +4 -2
  48. package/src/codex/autostart-health.ts +16 -0
  49. package/src/codex/catalog/aggregation.ts +12 -0
  50. package/src/codex/catalog/effort.ts +42 -12
  51. package/src/codex/catalog/metadata.ts +27 -1
  52. package/src/codex/catalog/model-metadata.ts +593 -0
  53. package/src/codex/catalog/parsing.ts +71 -27
  54. package/src/codex/catalog/provider-fetch.ts +189 -33
  55. package/src/codex/catalog/sync.ts +6 -5
  56. package/src/codex/convergence.ts +5 -0
  57. package/src/codex/desktop-app-restart.ts +342 -0
  58. package/src/codex/history-job.ts +32 -3
  59. package/src/codex/history-manifest.ts +112 -0
  60. package/src/codex/history-migration-guardian.ts +5 -5
  61. package/src/codex/history-provider.ts +825 -247
  62. package/src/codex/history-worker.ts +8 -5
  63. package/src/codex/inject.ts +49 -21
  64. package/src/codex/injected-marker.ts +1 -1
  65. package/src/codex/internal/history-writer.ts +4 -3
  66. package/src/codex/native-profile-startup.ts +157 -27
  67. package/src/codex/native-residue.ts +26 -33
  68. package/src/codex/shim.ts +56 -3
  69. package/src/combos/failover.ts +27 -0
  70. package/src/compatibility/index.ts +26 -0
  71. package/src/compatibility/manifest.ts +253 -0
  72. package/src/compatibility/openai-responses.ts +81 -0
  73. package/src/config/atomic-write.ts +219 -0
  74. package/src/config/paths.ts +40 -0
  75. package/src/config/process-state.ts +308 -0
  76. package/src/config/provider-validation.ts +214 -0
  77. package/src/config.ts +153 -814
  78. package/src/generated/compatibility-version.json +232 -148
  79. package/src/images/loop.ts +37 -6
  80. package/src/images/plan.ts +5 -4
  81. package/src/integrations/ownership-policy.ts +141 -0
  82. package/src/integrations/ownership.ts +10 -0
  83. package/src/integrations/state.ts +44 -5
  84. package/src/integrations/writer.ts +6 -0
  85. package/src/lib/azure-identity.ts +154 -0
  86. package/src/lib/bounded-body.ts +14 -2
  87. package/src/lib/debug.ts +42 -0
  88. package/src/lib/errors.ts +14 -0
  89. package/src/lib/process-control.ts +2 -1
  90. package/src/lib/provider-outbound.ts +45 -33
  91. package/src/lib/provider-tls-profile.ts +309 -0
  92. package/src/lib/proxy-env.ts +49 -0
  93. package/src/lib/redact.ts +10 -1
  94. package/src/lib/state-store-registrations.ts +2 -0
  95. package/src/lib/tool-argument-integers.ts +56 -5
  96. package/src/oauth/antigravity-routing.ts +282 -236
  97. package/src/oauth/callback-server.ts +22 -2
  98. package/src/oauth/command-code.ts +5 -16
  99. package/src/oauth/google-antigravity.ts +42 -5
  100. package/src/oauth/health.ts +1 -1
  101. package/src/oauth/index.ts +15 -3
  102. package/src/oauth/kimi.ts +9 -1
  103. package/src/oauth/open-browser-choice.ts +26 -0
  104. package/src/oauth/store.ts +6 -0
  105. package/src/providers/antigravity-quota.ts +3 -1
  106. package/src/providers/api-keys.ts +2 -1
  107. package/src/providers/auto-compact-budget.ts +65 -0
  108. package/src/providers/derive.ts +4 -0
  109. package/src/providers/key-failover.ts +5 -1
  110. package/src/providers/openai-tiers.ts +5 -0
  111. package/src/providers/provider-id-rewrite.ts +1 -0
  112. package/src/providers/quota.ts +59 -13
  113. package/src/providers/registry.ts +4 -2
  114. package/src/providers/request-pacing.ts +33 -6
  115. package/src/providers/xai-transport.ts +21 -0
  116. package/src/reasoning-effort.ts +19 -2
  117. package/src/responses/apply-patch-envelope.ts +63 -0
  118. package/src/responses/custom-tool-compat.ts +132 -38
  119. package/src/responses/google-provider-options.ts +36 -0
  120. package/src/responses/namespace-tool-compat.ts +84 -4
  121. package/src/responses/parser.ts +14 -2
  122. package/src/responses/provider-opaque-metadata.ts +3 -3
  123. package/src/responses/reasoning-replay-cache.ts +81 -3
  124. package/src/responses/schema.ts +37 -0
  125. package/src/responses/state.ts +94 -4
  126. package/src/router.ts +8 -2
  127. package/src/server/auth-cors.ts +37 -7
  128. package/src/server/images.ts +19 -35
  129. package/src/server/index.ts +102 -21
  130. package/src/server/local-management-read-client.ts +1 -1
  131. package/src/server/local-provider-reload-client.ts +1 -1
  132. package/src/server/management/agent-settings-routes.ts +206 -16
  133. package/src/server/management/combo-routes.ts +6 -0
  134. package/src/server/management/config-routes.ts +35 -6
  135. package/src/server/management/context.ts +1 -1
  136. package/src/server/management/logs-usage-routes.ts +27 -6
  137. package/src/server/management/model-routes.ts +8 -4
  138. package/src/server/management/model-rows.ts +4 -0
  139. package/src/server/management/native-integration-routes.ts +2 -1
  140. package/src/server/management/oauth-account-routes.ts +25 -4
  141. package/src/server/management/provider-capability-config.ts +1 -1
  142. package/src/server/management/provider-routes.ts +113 -15
  143. package/src/server/management/routing-profile-routes.ts +3 -0
  144. package/src/server/management/system-restart.ts +1 -1
  145. package/src/server/port-reclaim.ts +1 -1
  146. package/src/server/proxy-liveness.ts +2 -1
  147. package/src/server/request-log-conversation.ts +30 -0
  148. package/src/server/request-log.ts +21 -0
  149. package/src/server/responses/agent-task-recovery.ts +1 -1
  150. package/src/server/responses/codex-auth-error.ts +55 -0
  151. package/src/server/responses/combo-stream-preflight.ts +171 -0
  152. package/src/server/responses/compact.ts +36 -22
  153. package/src/server/responses/core.ts +584 -247
  154. package/src/server/responses/empty-completion-guard.ts +35 -6
  155. package/src/server/responses/fetch-helpers.ts +20 -102
  156. package/src/server/responses/v2-native-parent-override.ts +59 -0
  157. package/src/server/responses/ws-upstream.ts +75 -2
  158. package/src/server/responses-custom-tool-repair.ts +41 -5
  159. package/src/server/responses-undeclared-tool-guard.ts +241 -18
  160. package/src/service.ts +9 -5
  161. package/src/types/config.ts +16 -1
  162. package/src/types/provider.ts +16 -0
  163. package/src/types/request.ts +34 -1
  164. package/src/types/tools.ts +114 -11
  165. package/src/types.ts +7 -1
  166. package/src/update/index.ts +5 -4
  167. package/src/update/job.ts +3 -1
  168. package/src/update/transactional-install.mjs +8 -1
  169. package/src/usage/log.ts +16 -8
  170. package/src/usage/summary.ts +201 -8
  171. package/src/vision/describe.ts +18 -13
  172. package/src/web-search/executor.ts +10 -3
  173. package/src/web-search/gemini-executor.ts +6 -4
  174. package/src/web-search/loop.ts +42 -6
  175. package/gui/dist/assets/index-CGoDO3uO.css +0 -1
  176. package/gui/dist/assets/index-Cxt5fZMP.js +0 -102
@@ -54,6 +54,7 @@ import {
54
54
  disabledNativeSlugs,
55
55
  desktopAllowlistSuppressedNativeSlugs,
56
56
  NATIVE_OPENAI_MODELS,
57
+ nativeContextLimits,
57
58
  shouldIncludeAccountBoundNativeOpenAi,
58
59
  shouldIncludeNativeOpenAi,
59
60
  } from "./catalog/metadata";
@@ -286,6 +287,7 @@ function prepareCatalog(
286
287
  // selector-qualified rows when a live selector is configured.
287
288
  const observedNativeSlugs: string[] = [];
288
289
  const disabledNative = disabledNativeSlugs(config);
290
+ const openaiContextCap = nativeContextLimits(config);
289
291
  const nativeCatalogModels = mergeCatalogModelsWithNativeRecovery(
290
292
  active?.models ?? catalog.models ?? [],
291
293
  [catalog.models ?? [], ...nativeRecoverySources],
@@ -304,6 +306,7 @@ function prepareCatalog(
304
306
  suppressedBareNativeSlugs,
305
307
  disabledNativeAccountSlugs: new Set(),
306
308
  multiAgentV2Enabled,
309
+ openaiContextCap,
307
310
  });
308
311
  const accountBoundEntries = accountSelectors.length === 0
309
312
  ? []
@@ -320,6 +323,7 @@ function prepareCatalog(
320
323
  disabledNativeAccountSlugs: new Set([...disabledNative].filter(slug => suppressedBareNativeSlugs.has(slug))),
321
324
  multiAgentV2Enabled,
322
325
  keepNativeChatGptOnV1: config.keepNativeChatGptOnV1 === true,
326
+ openaiContextCap,
323
327
  accountNativeSlugs,
324
328
  accountNativeSlugsBySelector,
325
329
  }).filter(entry => trustedAccountBoundNativeCatalogSlug(entry) !== undefined);
@@ -352,6 +356,7 @@ function prepareCatalog(
352
356
  includeNativeOpenAi,
353
357
  accountBoundEntries,
354
358
  suppressedBareNativeSlugs,
359
+ openaiContextCap,
355
360
  policy: {
356
361
  ...CANONICAL_NATIVE_CATALOG_CONTENT_POLICY,
357
362
  nativeBackfillSlugs: [...availableBareNativeSlugs, ...observedNativeSlugs],
@@ -0,0 +1,342 @@
1
+ /**
2
+ * Full restart of the Codex desktop app (the Electron shell), Windows only.
3
+ *
4
+ * `--restart-codex` deliberately signals only `codex app-server` /
5
+ * `codex-code-mode-host` processes: `isCodexAppServerCommandLine` requires a
6
+ * `codex` executable token, so the shell that owns the model picker is never a
7
+ * match. On macOS that is enough, because the respawned app-server re-emits
8
+ * `codex-app-server-initialized` and the renderer drops its cached
9
+ * `model/list`. On Windows MSIX it is not: externally terminating the child
10
+ * does not reliably re-emit that event in the surviving shell, so the picker
11
+ * keeps showing the old catalog until the app itself is restarted (#2292).
12
+ *
13
+ * This is therefore a SEPARATE opt-in flag rather than a widening of
14
+ * `--restart-codex`. Quitting the desktop app ends live conversations, which is
15
+ * a different consent from restarting a background helper, and the CLI contract
16
+ * for `--restart-codex` promises the narrow behavior.
17
+ *
18
+ * Everything here fails CLOSED: if the package cannot be identified, if a
19
+ * target is part of our own ancestry, or if any target survives termination,
20
+ * nothing is relaunched and the caller is told to restart manually. A stale
21
+ * picker is a much smaller problem than a wrongly killed process.
22
+ */
23
+ import { resolveTrustedWindowsPowerShellExe, resolveTrustedWindowsTaskkillExe } from "../lib/windows-elevation";
24
+ import { execFileSync } from "node:child_process";
25
+
26
+ /** Bounded subprocess options. A hung Appx/CIM probe must never wedge `ocx sync`. */
27
+ export interface DesktopAppExecOptions {
28
+ timeout?: number;
29
+ windowsHide?: boolean;
30
+ }
31
+
32
+ export interface DesktopAppRestartIo {
33
+ platform?: NodeJS.Platform;
34
+ /** Returns stdout. Options are part of the seam so the timeout is testable. */
35
+ execFile?: (file: string, args: readonly string[], options?: DesktopAppExecOptions) => string;
36
+ /** Process ancestry of the current process, innermost first. Used for the self-kill guard. */
37
+ ancestryPids?: () => number[];
38
+ isAlive?: (pid: number) => boolean;
39
+ sleep?: (ms: number) => void;
40
+ now?: () => number;
41
+ }
42
+
43
+ export type DesktopAppRestartReason =
44
+ | "windows_only"
45
+ | "package_discovery_failed"
46
+ | "no_targets"
47
+ | "self_ancestry"
48
+ | "targets_survived";
49
+
50
+ export interface DesktopAppRestartResult {
51
+ attempted: boolean;
52
+ stopped: number[];
53
+ surviving: number[];
54
+ relaunch: "started" | "skipped";
55
+ reason?: DesktopAppRestartReason;
56
+ }
57
+
58
+ /** How long a graceful close is given before the forced pass. */
59
+ const GRACEFUL_EXIT_TIMEOUT_MS = 15_000;
60
+ /** How long a forced kill is given before the target counts as surviving. */
61
+ const FORCED_EXIT_TIMEOUT_MS = 5_000;
62
+ /** Every probe is bounded; PowerShell module loading is the slow part. */
63
+ const PROBE_TIMEOUT_MS = 10_000;
64
+
65
+ interface DesktopPackage {
66
+ family: string;
67
+ installLocation: string;
68
+ aumid: string;
69
+ }
70
+
71
+ /**
72
+ * Runtime discovery, never a hardcoded identifier. The beta MSIX package family
73
+ * changes between builds, so a literal AUMID would silently stop matching and
74
+ * then either do nothing or — worse — match a package we did not mean.
75
+ */
76
+ function discoverPackage(exec: NonNullable<DesktopAppRestartIo["execFile"]>): DesktopPackage | null {
77
+ const script = [
78
+ "$ErrorActionPreference='SilentlyContinue'",
79
+ "Import-Module Appx -ErrorAction SilentlyContinue",
80
+ "$p = Get-AppxPackage -Name OpenAI.Codex",
81
+ "if (-not $p) { $p = Get-AppxPackage -Name OpenAI.CodexBeta }",
82
+ "if (-not $p -or -not $p.InstallLocation) { 'MISS' } else {",
83
+ " $p.PackageFamilyName; $p.InstallLocation; \"$($p.PackageFamilyName)!App\"",
84
+ "}",
85
+ ].join("; ");
86
+ let stdout: string;
87
+ try {
88
+ stdout = exec(resolveTrustedWindowsPowerShellExe(), ["-NoProfile", "-NonInteractive", "-Command", script], {
89
+ timeout: PROBE_TIMEOUT_MS,
90
+ windowsHide: true,
91
+ });
92
+ } catch {
93
+ return null;
94
+ }
95
+ const lines = stdout.split(/\r?\n/).map(line => line.trim()).filter(line => line.length > 0);
96
+ if (lines.length < 3 || lines[0] === "MISS") return null;
97
+ const [family, installLocation, aumid] = lines;
98
+ if (!family || !installLocation || !aumid) return null;
99
+ return { family, installLocation, aumid };
100
+ }
101
+
102
+ interface DesktopProcess {
103
+ pid: number;
104
+ parentPid: number;
105
+ /** Win32_Process CreationDate. Guards against PID reuse across the wait window. */
106
+ createdAt: string;
107
+ }
108
+
109
+ /**
110
+ * Only `ChatGPT.exe` processes whose image lives under the discovered install
111
+ * location AND owned by the current user. The install location alone is not
112
+ * enough: an MSIX package under `WindowsApps` is shared, so on a multi-user
113
+ * machine another account's Codex desktop matches the same path. The app-server
114
+ * collector already pays for `GetOwner` for exactly this reason.
115
+ *
116
+ * `CreationDate` is captured so a PID can be re-verified before it is signalled;
117
+ * a graceful-close window is long enough for Windows to recycle a PID.
118
+ */
119
+ function listPackageProcesses(
120
+ exec: NonNullable<DesktopAppRestartIo["execFile"]>,
121
+ installLocation: string,
122
+ ): DesktopProcess[] {
123
+ const literal = installLocation.replace(/'/g, "''");
124
+ const script = [
125
+ "$ErrorActionPreference='SilentlyContinue'",
126
+ `$root = '${literal}'`,
127
+ "$me = ([Security.Principal.WindowsIdentity]::GetCurrent()).Name",
128
+ "Get-CimInstance Win32_Process -Filter \"Name='ChatGPT.exe'\" |",
129
+ " Where-Object { $_.ExecutablePath -and $_.ExecutablePath.StartsWith($root, 'OrdinalIgnoreCase') } |",
130
+ " ForEach-Object {",
131
+ " $o = Invoke-CimMethod -InputObject $_ -MethodName GetOwner",
132
+ " if ($o -and $o.ReturnValue -eq 0 -and $o.User) {",
133
+ " $owner = if ($o.Domain) { \"$($o.Domain)\\$($o.User)\" } else { $o.User }",
134
+ " if ($owner -ieq $me) {",
135
+ " \"$($_.ProcessId) $($_.ParentProcessId) $($_.CreationDate.ToString('o'))\"",
136
+ " }",
137
+ " }",
138
+ " }",
139
+ ].join(" ");
140
+ let stdout: string;
141
+ try {
142
+ stdout = exec(resolveTrustedWindowsPowerShellExe(), ["-NoProfile", "-NonInteractive", "-Command", script], {
143
+ timeout: PROBE_TIMEOUT_MS,
144
+ windowsHide: true,
145
+ });
146
+ } catch {
147
+ return [];
148
+ }
149
+ const processes: DesktopProcess[] = [];
150
+ for (const line of stdout.split(/\r?\n/)) {
151
+ const match = /^\s*(\d+)\s+(\d+)\s+(\S+)\s*$/.exec(line);
152
+ if (!match) continue;
153
+ const pid = Number(match[1]);
154
+ const parentPid = Number(match[2]);
155
+ const createdAt = match[3]!;
156
+ if (Number.isSafeInteger(pid) && Number.isSafeInteger(parentPid)) {
157
+ processes.push({ pid, parentPid, createdAt });
158
+ }
159
+ }
160
+ return processes;
161
+ }
162
+
163
+ /**
164
+ * True when the PID still names the same process we verified. Between listing
165
+ * and signalling there is a graceful-close window, and a `taskkill /T /F` on a
166
+ * recycled PID would tear down an unrelated process tree.
167
+ */
168
+ function stillSameProcess(
169
+ exec: NonNullable<DesktopAppRestartIo["execFile"]>,
170
+ installLocation: string,
171
+ target: DesktopProcess,
172
+ ): boolean {
173
+ const current = listPackageProcesses(exec, installLocation)
174
+ .find(p => p.pid === target.pid);
175
+ return current !== undefined && current.createdAt === target.createdAt;
176
+ }
177
+
178
+ /** Roots are the package processes whose parent is not itself in the package tree. */
179
+ function rootProcesses(processes: readonly DesktopProcess[]): DesktopProcess[] {
180
+ const inTree = new Set(processes.map(p => p.pid));
181
+ return processes.filter(p => !inTree.has(p.parentPid));
182
+ }
183
+
184
+ /**
185
+ * Full Windows parent chain for this process, innermost first.
186
+ *
187
+ * `process.ppid` is one level, which is not enough: a terminal hosted inside the
188
+ * desktop app sits several hops below `ChatGPT.exe`, so a one-level check would
189
+ * miss the exact case the guard exists for and we would terminate our own host.
190
+ * The chain therefore comes from CIM, with a bound so a corrupted parent cycle
191
+ * cannot spin.
192
+ */
193
+ function windowsAncestryPids(exec: NonNullable<DesktopAppRestartIo["execFile"]>): number[] {
194
+ const chain: number[] = [process.pid];
195
+ let current = process.pid;
196
+ for (let hop = 0; hop < 16; hop++) {
197
+ let stdout: string;
198
+ try {
199
+ stdout = exec(resolveTrustedWindowsPowerShellExe(), [
200
+ "-NoProfile", "-NonInteractive", "-Command",
201
+ `$ErrorActionPreference='SilentlyContinue'; (Get-CimInstance Win32_Process -Filter "ProcessId=${current}").ParentProcessId`,
202
+ ], { timeout: PROBE_TIMEOUT_MS, windowsHide: true });
203
+ } catch {
204
+ // An unreadable chain must not be read as "not our ancestor".
205
+ return [];
206
+ }
207
+ const parent = Number(stdout.trim());
208
+ if (!Number.isSafeInteger(parent) || parent <= 0 || chain.includes(parent)) break;
209
+ chain.push(parent);
210
+ current = parent;
211
+ }
212
+ return chain;
213
+ }
214
+
215
+ function defaultExecFile(file: string, args: readonly string[], options?: DesktopAppExecOptions): string {
216
+ return execFileSync(file, [...args], {
217
+ encoding: "utf-8",
218
+ timeout: options?.timeout ?? PROBE_TIMEOUT_MS,
219
+ windowsHide: options?.windowsHide ?? true,
220
+ });
221
+ }
222
+
223
+ function defaultIsAlive(pid: number): boolean {
224
+ try {
225
+ process.kill(pid, 0);
226
+ return true;
227
+ } catch {
228
+ return false;
229
+ }
230
+ }
231
+
232
+ function defaultSleep(ms: number): void {
233
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
234
+ }
235
+
236
+ function waitForExit(
237
+ pid: number,
238
+ timeoutMs: number,
239
+ isAlive: (pid: number) => boolean,
240
+ sleep: (ms: number) => void,
241
+ now: () => number,
242
+ ): boolean {
243
+ const deadline = now() + timeoutMs;
244
+ while (now() < deadline) {
245
+ if (!isAlive(pid)) return true;
246
+ sleep(250);
247
+ }
248
+ return !isAlive(pid);
249
+ }
250
+
251
+ /**
252
+ * Stop every package-tree root gracefully, force the stragglers, then relaunch
253
+ * through the discovered AUMID. Returns without relaunching if anything
254
+ * survived, because launching a second shell beside a stuck one is worse than
255
+ * leaving the user to restart it.
256
+ */
257
+ export function restartCodexDesktopApp(io: DesktopAppRestartIo = {}): DesktopAppRestartResult {
258
+ const platform = io.platform ?? process.platform;
259
+ const skipped = (reason: DesktopAppRestartReason): DesktopAppRestartResult => ({
260
+ attempted: false, stopped: [], surviving: [], relaunch: "skipped", reason,
261
+ });
262
+ if (platform !== "win32") return skipped("windows_only");
263
+
264
+ const exec = io.execFile ?? defaultExecFile;
265
+ const pkg = discoverPackage(exec);
266
+ if (!pkg) return skipped("package_discovery_failed");
267
+
268
+ const processes = listPackageProcesses(exec, pkg.installLocation);
269
+ const roots = rootProcesses(processes);
270
+ if (roots.length === 0) return skipped("no_targets");
271
+
272
+ const ancestryPids = io.ancestryPids ? io.ancestryPids() : windowsAncestryPids(exec);
273
+ if (ancestryPids.length === 0) {
274
+ // Fail closed: an unreadable ancestry chain cannot prove we are outside the
275
+ // tree we are about to terminate.
276
+ return skipped("self_ancestry");
277
+ }
278
+ const ancestry = new Set(ancestryPids);
279
+ if (processes.some(p => ancestry.has(p.pid))) {
280
+ // Terminating our own tree would kill this command mid-flight and leave the
281
+ // user with neither a restarted app nor an explanation.
282
+ return skipped("self_ancestry");
283
+ }
284
+
285
+ const isAlive = io.isAlive ?? defaultIsAlive;
286
+ const sleep = io.sleep ?? defaultSleep;
287
+ const now = io.now ?? (() => Date.now());
288
+ const stopped: number[] = [];
289
+ const surviving: number[] = [];
290
+
291
+ for (const root of roots) {
292
+ const pid = root.pid;
293
+ // Re-verify immediately before the graceful close: the listing is already
294
+ // one probe old.
295
+ if (!stillSameProcess(exec, pkg.installLocation, root)) {
296
+ stopped.push(pid);
297
+ continue;
298
+ }
299
+ try {
300
+ exec(resolveTrustedWindowsPowerShellExe(), [
301
+ "-NoProfile", "-NonInteractive", "-Command",
302
+ `$p = Get-Process -Id ${pid} -ErrorAction SilentlyContinue; if ($p) { [void]$p.CloseMainWindow() }`,
303
+ ], { timeout: PROBE_TIMEOUT_MS, windowsHide: true });
304
+ } catch {
305
+ /* a refused graceful close still gets the forced pass below */
306
+ }
307
+ if (waitForExit(pid, GRACEFUL_EXIT_TIMEOUT_MS, isAlive, sleep, now)) {
308
+ stopped.push(pid);
309
+ continue;
310
+ }
311
+ // The wait window is long enough for Windows to recycle a PID, and the next
312
+ // step is `/T /F` against a whole tree. Confirm the PID is still the process
313
+ // we verified, or leave it alone.
314
+ if (!stillSameProcess(exec, pkg.installLocation, root)) {
315
+ stopped.push(pid);
316
+ continue;
317
+ }
318
+ try {
319
+ exec(resolveTrustedWindowsTaskkillExe(), ["/PID", String(pid), "/T", "/F"], {
320
+ timeout: PROBE_TIMEOUT_MS, windowsHide: true,
321
+ });
322
+ } catch {
323
+ /* fall through to the liveness check: the process state decides, not the exit code */
324
+ }
325
+ if (waitForExit(pid, FORCED_EXIT_TIMEOUT_MS, isAlive, sleep, now)) stopped.push(pid);
326
+ else surviving.push(pid);
327
+ }
328
+
329
+ if (surviving.length > 0) {
330
+ return { attempted: true, stopped, surviving, relaunch: "skipped", reason: "targets_survived" };
331
+ }
332
+
333
+ try {
334
+ exec(resolveTrustedWindowsPowerShellExe(), [
335
+ "-NoProfile", "-NonInteractive", "-Command",
336
+ `Start-Process 'shell:AppsFolder\\${pkg.aumid}'`,
337
+ ], { timeout: PROBE_TIMEOUT_MS, windowsHide: true });
338
+ } catch {
339
+ return { attempted: true, stopped, surviving, relaunch: "skipped", reason: "targets_survived" };
340
+ }
341
+ return { attempted: true, stopped, surviving, relaunch: "started" };
342
+ }
@@ -109,7 +109,8 @@ export type CodexHistoryJobOutcome =
109
109
  | { readonly kind: "skipped" }
110
110
  | { readonly kind: "blocked"; readonly reason: "busy" | "database" | "unsafe-path" | "desired_disabled" | "desired_enabled" }
111
111
  | { readonly kind: "failed"; readonly reason: "worker-error" | "worker-died" | "timeout";
112
- readonly message: string; readonly historyFailureReason?: CodexHistoryFailureReason };
112
+ readonly message: string; readonly historyFailureReason?: CodexHistoryFailureReason;
113
+ readonly rows?: number; readonly files?: number };
113
114
 
114
115
  /**
115
116
  * Derive the durable history operation from admitted intent.
@@ -174,7 +175,14 @@ function isPlausibleWorkerResult(
174
175
  || message.reason === "desired_disabled" || message.reason === "desired_enabled";
175
176
  case "error":
176
177
  return typeof message.message === "string"
177
- && (message.reason === undefined || message.reason === "busy" || message.reason === "permission");
178
+ && (message.rows === undefined || (Number.isSafeInteger(message.rows) && Number(message.rows) >= 0))
179
+ && (message.files === undefined || (Number.isSafeInteger(message.files) && Number(message.files) >= 0))
180
+ && ((message.rows === undefined && message.files === undefined)
181
+ || (message.rows !== undefined && message.files !== undefined))
182
+ && (message.reason === undefined
183
+ || message.reason === "busy"
184
+ || message.reason === "permission"
185
+ || message.reason === "integrity");
178
186
  default:
179
187
  return false;
180
188
  }
@@ -224,6 +232,7 @@ export function describeHistoryJobFailure(
224
232
  : surface === "recover-legacy"
225
233
  ? "the Codex history DB is locked (Codex app/IDE open?). Close it and rerun this command."
226
234
  : "the Codex app appears to be holding the history database. Close Codex and run `ocx restore` again.";
235
+ const busyStateText = "Codex history state is busy (database, backup manifest, or rollout file); this is not enough evidence to blame the Codex app. It is retried automatically while the proxy runs; run 'ocx doctor' before forcing another attempt.";
227
236
  if (outcome.kind === "blocked") {
228
237
  if (outcome.reason === "busy") return busyText;
229
238
  switch (outcome.reason) {
@@ -237,10 +246,22 @@ export function describeHistoryJobFailure(
237
246
  return "Codex integration is enabled, so the history operation was skipped.";
238
247
  }
239
248
  }
240
- if (outcome.historyFailureReason === "busy") return busyText;
249
+ const partiallyChanged = (outcome.rows ?? 0) > 0 || (outcome.files ?? 0) > 0;
250
+ if (partiallyChanged && outcome.historyFailureReason === "busy") {
251
+ return "Codex history metadata changed but did not converge because manifest finalization remained busy; the manifest was retained for review and safe retry. Run 'ocx doctor'.";
252
+ }
253
+ if (partiallyChanged && outcome.historyFailureReason === "permission") {
254
+ return "Codex history metadata changed but did not converge because permission was denied while finalizing the manifest; the manifest was retained for review and safe retry. Run 'ocx doctor'.";
255
+ }
256
+ if (outcome.historyFailureReason === "busy") return busyStateText;
241
257
  if (outcome.historyFailureReason === "permission") {
242
258
  return "permission was denied while writing Codex history; this is not a Codex app lock. Run 'ocx doctor'.";
243
259
  }
260
+ if (outcome.historyFailureReason === "integrity") {
261
+ return partiallyChanged
262
+ ? "the history backup or its restore target changed after a partial restore; the manifest was retained for review and safe retry. Run 'ocx doctor'."
263
+ : "the history backup or its restore target failed integrity checks; no unverified provider metadata was applied. Run 'ocx doctor'.";
264
+ }
244
265
  switch (outcome.reason) {
245
266
  case "worker-error":
246
267
  return `the history worker failed (${outcome.message}). Run 'ocx doctor'.`;
@@ -277,6 +298,9 @@ function classifyWorkerResult(result: HistoryWorkerResult): CodexHistoryJobOutco
277
298
  reason: "worker-error",
278
299
  message: redactWorkerMessage(result.message),
279
300
  ...(result.reason ? { historyFailureReason: result.reason } : {}),
301
+ ...(result.rows !== undefined && result.files !== undefined
302
+ ? { rows: result.rows, files: result.files }
303
+ : {}),
280
304
  };
281
305
  }
282
306
  return result.outcome === "skipped"
@@ -284,6 +308,11 @@ function classifyWorkerResult(result: HistoryWorkerResult): CodexHistoryJobOutco
284
308
  : { kind: "converged", rows: result.rows, files: result.files, ...(result.proof ? { proof: result.proof } : {}) };
285
309
  }
286
310
 
311
+ /** Test seam for the parent-side Worker result classification contract. */
312
+ export function classifyWorkerResultForTests(result: HistoryWorkerResult): CodexHistoryJobOutcome {
313
+ return classifyWorkerResult(result);
314
+ }
315
+
287
316
  /**
288
317
  * Run one history unit in a Worker and join it before returning.
289
318
  *
@@ -0,0 +1,112 @@
1
+ import { createHash } from "node:crypto";
2
+ import { isAbsolute, resolve } from "node:path";
3
+
4
+ /** Sources whose native OpenAI provenance can be restored exactly. */
5
+ export const CODEX_HISTORY_RESUMABLE_SOURCES = ["cli", "vscode"] as const;
6
+
7
+ export interface CodexHistoryBackupEntry {
8
+ id: string;
9
+ rolloutPath: string;
10
+ modelProvider: string;
11
+ source: string;
12
+ hasUserEvent: 0 | 1;
13
+ }
14
+
15
+ export interface CodexHistoryBackupManifest {
16
+ version: 1;
17
+ stateDbPath: string;
18
+ entries: Record<string, CodexHistoryBackupEntry>;
19
+ }
20
+
21
+ export type CodexHistoryManifestValidation =
22
+ | { readonly ok: true; readonly manifest: CodexHistoryBackupManifest }
23
+ | { readonly ok: false; readonly reason: "foreign-database" }
24
+ | {
25
+ readonly ok: false;
26
+ readonly reason: "schema";
27
+ readonly scope: "manifest" | "entry-shape" | "entry-provenance";
28
+ };
29
+
30
+ function codexHistoryPathIdentity(path: string): string {
31
+ const canonical = resolve(path);
32
+ return process.platform === "win32" ? canonical.toLowerCase() : canonical;
33
+ }
34
+
35
+ /**
36
+ * Canonical identity used by both backup naming and manifest ownership checks.
37
+ * Windows paths are case-insensitive for this contract; other platforms keep
38
+ * the resolved path's case.
39
+ */
40
+ export function codexHistoryStateDbIdentity(path: string): string {
41
+ return codexHistoryPathIdentity(path);
42
+ }
43
+
44
+ /** Stable, non-secret file-name component for one state database. */
45
+ export function codexHistoryBackupId(stateDbPath: string): string {
46
+ return createHash("sha256")
47
+ .update(codexHistoryStateDbIdentity(stateDbPath))
48
+ .digest("hex")
49
+ .slice(0, 16);
50
+ }
51
+
52
+ /** Platform-aware identity comparison shared by database and rollout checks. */
53
+ export function sameCodexHistoryPath(left: string, right: string): boolean {
54
+ return codexHistoryPathIdentity(left) === codexHistoryPathIdentity(right);
55
+ }
56
+
57
+ function isRecord(value: unknown): value is Record<string, unknown> {
58
+ return typeof value === "object" && value !== null && !Array.isArray(value);
59
+ }
60
+
61
+ function hasAllowedProvenance(entry: Record<string, unknown>): boolean {
62
+ return (entry.modelProvider === "openai"
63
+ && CODEX_HISTORY_RESUMABLE_SOURCES.includes(
64
+ entry.source as (typeof CODEX_HISTORY_RESUMABLE_SOURCES)[number],
65
+ ))
66
+ || (entry.modelProvider === "opencodex" && entry.source === "exec");
67
+ }
68
+
69
+ /**
70
+ * Validate only the versioned data contract and database ownership identity.
71
+ * Filesystem type checks, reads, fingerprints, rollout inspection, SQLite, and
72
+ * mutation deliberately remain with the callers.
73
+ */
74
+ export function validateCodexHistoryBackupManifest(
75
+ raw: unknown,
76
+ expectedStateDbPath: string,
77
+ ): CodexHistoryManifestValidation {
78
+ if (!isRecord(raw)
79
+ || raw.version !== 1
80
+ || typeof raw.stateDbPath !== "string"
81
+ || !raw.stateDbPath.trim()
82
+ || !isAbsolute(raw.stateDbPath)
83
+ || !isRecord(raw.entries)) {
84
+ return { ok: false, reason: "schema", scope: "manifest" };
85
+ }
86
+ if (!sameCodexHistoryPath(raw.stateDbPath, expectedStateDbPath)) {
87
+ return { ok: false, reason: "foreign-database" };
88
+ }
89
+
90
+ for (const [id, value] of Object.entries(raw.entries)) {
91
+ if (!isRecord(value)) {
92
+ return { ok: false, reason: "schema", scope: "entry-shape" };
93
+ }
94
+ if (!id
95
+ || value.id !== id
96
+ || typeof value.rolloutPath !== "string"
97
+ || !value.rolloutPath.trim()
98
+ || !isAbsolute(value.rolloutPath)
99
+ || typeof value.modelProvider !== "string"
100
+ || !value.modelProvider.trim()
101
+ || typeof value.source !== "string"
102
+ || !value.source.trim()
103
+ || typeof value.hasUserEvent !== "number"
104
+ || !Number.isSafeInteger(value.hasUserEvent)
105
+ || (value.hasUserEvent !== 0 && value.hasUserEvent !== 1)
106
+ || !hasAllowedProvenance(value)) {
107
+ return { ok: false, reason: "schema", scope: "entry-provenance" };
108
+ }
109
+ }
110
+
111
+ return { ok: true, manifest: raw as unknown as CodexHistoryBackupManifest };
112
+ }
@@ -2,11 +2,11 @@ import { migrateHistoryToOpenai } from "./history-provider";
2
2
  import { resolveCodexHistoryJobTarget, runCodexHistoryJob } from "./history-job";
3
3
 
4
4
  /**
5
- * Daemon-side retry for the one-time Design-B history migration.
5
+ * Daemon-side retry for the one-time Design-B history metadata restoration.
6
6
  *
7
7
  * Most upgrades run `ocx start` while the Codex app still holds `state_5.sqlite`,
8
- * so the inject-time migration often fails on the FIRST start exactly the moment
9
- * every legacy thread is still tagged `opencodex` and invisible to the app. Instead
8
+ * so the inject-time restore can fail on the FIRST start while manifest-backed original
9
+ * metadata is still pending. Instead
10
10
  * of asking the user to close the app and rerun start, this guardian keeps retrying
11
11
  * in the background until the migration lands.
12
12
  *
@@ -77,7 +77,7 @@ export function startHistoryMigrationGuardian(deps: HistoryMigrationGuardianDeps
77
77
  if (!result.failed) {
78
78
  const moved = result.rows + ((result as { ejectedRows?: number }).ejectedRows ?? 0);
79
79
  if (moved > 0) {
80
- log.log(`🩹 history-migration: ${moved} legacy opencodex thread(s) migrated back to openai.`);
80
+ log.log(`🩹 history-migration: restored original provider metadata for ${moved} manifest-backed thread(s).`);
81
81
  }
82
82
  // Zero mutations are authoritative only when the worker verified the
83
83
  // exact DB/manifest state while H was held.
@@ -92,7 +92,7 @@ export function startHistoryMigrationGuardian(deps: HistoryMigrationGuardianDeps
92
92
  }
93
93
  if (ticks >= maxTicks) {
94
94
  stopped = true;
95
- log.log("⚠️ history-migration: Could not verify that legacy threads were migrated; the history database may be busy, unavailable, or not yet ready. Run 'ocx sync' (or check 'ocx doctor').");
95
+ log.log("⚠️ history-migration: Could not verify that backed-up provider metadata was restored; the history database may be busy, unavailable, or not yet ready. Run 'ocx sync' (or check 'ocx doctor').");
96
96
  return;
97
97
  }
98
98
  schedule();