@bitkyc08/opencodex 2.100.3 → 2.100.5-preview.20261118.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 (249) hide show
  1. package/AGENTS_INSTALL.md +23 -1
  2. package/bin/ocx.mjs +8 -1
  3. package/gui/dist/assets/{App-Dnb6VMsP.js → App-BiOGtxDS.js} +21 -20
  4. package/gui/dist/assets/{Tray-BV4ms9U9.js → Tray-BwsMejUO.js} +1 -1
  5. package/gui/dist/assets/brand-mark-BY1dgACL.js +1 -0
  6. package/gui/dist/assets/{index-DCdXsMyZ.js → index-CwHSKMdG.js} +46 -13
  7. package/gui/dist/assets/index-DJxM-imn.css +2 -0
  8. package/gui/dist/assets/{segment-thumb-features-DXSidY6D.js → segment-thumb-features-Bds9Hb_7.js} +1 -1
  9. package/gui/dist/classic/assets/{App-DA-scMPq.js → App-CGLOiqQL.js} +20 -19
  10. package/gui/dist/classic/assets/{Tray-BrHaVRAq.js → Tray-Da4r2O70.js} +1 -1
  11. package/gui/dist/classic/assets/{index-BqOaGLf5.js → index-CvoKXKL9.js} +46 -13
  12. package/gui/dist/classic/assets/quota-summary-DvqzfCmr.js +1 -0
  13. package/gui/dist/classic/index.html +1 -1
  14. package/gui/dist/index.html +2 -2
  15. package/native/ocx-child/src/cli.rs +5 -3
  16. package/native/ocx-child/src/codex_home.rs +1 -0
  17. package/native/ocx-child/src/link_ws.rs +24 -19
  18. package/native/ocx-child/src/link_ws_frame.rs +136 -50
  19. package/package.json +3 -3
  20. package/src/adapters/anthropic/per-message-effort.ts +296 -0
  21. package/src/adapters/anthropic-input-schema.ts +270 -0
  22. package/src/adapters/anthropic.ts +4 -63
  23. package/src/adapters/claude-cli/adapter.ts +1 -0
  24. package/src/adapters/command-code-tool-text.ts +9 -1
  25. package/src/adapters/command-code.ts +18 -2
  26. package/src/adapters/devin/cloud-direct/chat.ts +95 -14
  27. package/src/adapters/devin/live-models.ts +11 -1
  28. package/src/adapters/google-errors.ts +14 -2
  29. package/src/adapters/kiro/reasoning.ts +3 -0
  30. package/src/adapters/kiro-tools.ts +14 -9
  31. package/src/adapters/openai-responses/passthrough.ts +3 -1
  32. package/src/adapters/openai-responses/request-strips.ts +1 -0
  33. package/src/adapters/qoder/adapter.ts +9 -1
  34. package/src/adapters/tool-catalog-nudge.ts +1 -1
  35. package/src/adapters/zed.ts +4 -2
  36. package/src/claude/chat-tool-dispatch.ts +4 -1
  37. package/src/claude/desktop-remote-store.ts +60 -10
  38. package/src/cli/account-api.ts +4 -0
  39. package/src/cli/account-auth.ts +30 -2
  40. package/src/cli/account-extended.ts +33 -2
  41. package/src/cli/capabilities-access-remote.ts +3 -3
  42. package/src/cli/capabilities-accounts.ts +3 -3
  43. package/src/cli/capabilities-base.ts +11 -6
  44. package/src/cli/capabilities-observe-system.ts +2 -2
  45. package/src/cli/claude.ts +3 -3
  46. package/src/cli/disconnect-runtime.ts +16 -6
  47. package/src/cli/dispatch.ts +7 -1
  48. package/src/cli/index.ts +2 -2
  49. package/src/cli/link-apply-restart.ts +4 -2
  50. package/src/cli/link-routes.ts +4 -1
  51. package/src/cli/link.ts +5 -4
  52. package/src/cli/logout-command.ts +23 -4
  53. package/src/cli/preflight-exemptions.ts +3 -0
  54. package/src/cli/provider.ts +3 -2
  55. package/src/cli/registry.ts +5 -2
  56. package/src/cli/resolve.ts +23 -8
  57. package/src/cli/restart-failure.ts +11 -1
  58. package/src/cli/runtime-api.ts +4 -0
  59. package/src/cli/status.ts +4 -1
  60. package/src/cli/system-command.ts +1 -1
  61. package/src/cli/system-restart-client.ts +9 -3
  62. package/src/cli/system-settings-parity.ts +2 -1
  63. package/src/client/connect.ts +73 -11
  64. package/src/client/desktop-refusal.ts +38 -0
  65. package/src/client/lifecycle-lock.ts +29 -4
  66. package/src/client/runtime-restart.ts +27 -15
  67. package/src/client/runtime.ts +4 -2
  68. package/src/client/state.ts +14 -0
  69. package/src/clients/config-export.ts +12 -7
  70. package/src/codex/account-lifecycle.ts +3 -1
  71. package/src/codex/account-pause.ts +4 -0
  72. package/src/codex/account-runtime-state.ts +4 -0
  73. package/src/codex/auth-api/main-account-probe.ts +3 -1
  74. package/src/codex/auth-api/main-hard-lock-refusal-read.ts +172 -0
  75. package/src/codex/auth-context.ts +40 -2
  76. package/src/codex/catalog/build-entries.ts +10 -0
  77. package/src/codex/catalog/derive-entry.ts +7 -0
  78. package/src/codex/catalog/metadata.ts +8 -0
  79. package/src/codex/catalog/native-models.ts +16 -6
  80. package/src/codex/catalog/pinned-models.ts +1 -0
  81. package/src/codex/catalog/provider-models.ts +5 -5
  82. package/src/codex/catalog/reserve-warn.ts +7 -5
  83. package/src/codex/catalog/reserve.ts +4 -3
  84. package/src/codex/catalog/retained-sync.ts +2 -0
  85. package/src/codex/catalog/routed-defaults.ts +35 -0
  86. package/src/codex/catalog-auto-refresh.ts +13 -2
  87. package/src/codex/config-drift-heal.ts +40 -12
  88. package/src/codex/config-write-lock.ts +39 -1
  89. package/src/codex/convergence.ts +2 -0
  90. package/src/codex/data/roster-pinned-models.json +346 -1
  91. package/src/codex/inject/config-write-section.ts +39 -1
  92. package/src/codex/inject/plan.ts +10 -8
  93. package/src/codex/inject/remove.ts +21 -19
  94. package/src/codex/inject/restore.ts +5 -1
  95. package/src/codex/inject-coordination.ts +58 -7
  96. package/src/codex/inject.ts +10 -12
  97. package/src/codex/journal-config-restore.ts +42 -0
  98. package/src/codex/journal.ts +62 -8
  99. package/src/codex/loopback-target.ts +22 -8
  100. package/src/codex/main-account.ts +94 -30
  101. package/src/codex/native-main-auth-file.ts +14 -0
  102. package/src/codex/native-main-credentials.ts +276 -0
  103. package/src/codex/native-main-owner.ts +3 -0
  104. package/src/codex/native-main-refresh-mode.ts +14 -1
  105. package/src/codex/quota.ts +63 -14
  106. package/src/combos/failover.ts +195 -1
  107. package/src/combos/index.ts +5 -0
  108. package/src/combos/resolve.ts +115 -19
  109. package/src/config/diagnostics.ts +3 -0
  110. package/src/config/live-reconcile.ts +6 -3
  111. package/src/config/load-degrade.ts +2 -0
  112. package/src/config/persisted-mutation.ts +2 -2
  113. package/src/config/persisted-projections.ts +18 -0
  114. package/src/config/process-state.ts +4 -3
  115. package/src/config/reserve-capability.ts +96 -0
  116. package/src/config/schema/config-schema.ts +6 -0
  117. package/src/config/schema/leaf-validators.ts +2 -0
  118. package/src/config/schema/routed-catalog-defaults.ts +49 -0
  119. package/src/config/subagent-models.ts +20 -12
  120. package/src/config.ts +7 -7
  121. package/src/desktop-update/acquire.ts +202 -0
  122. package/src/desktop-update/cli.ts +168 -0
  123. package/src/desktop-update/drain.ts +40 -0
  124. package/src/desktop-update/headless.ts +285 -0
  125. package/src/desktop-update/image.ts +85 -0
  126. package/src/desktop-update/install.ts +53 -0
  127. package/src/desktop-update/msi.ts +72 -0
  128. package/src/desktop-update/release.ts +128 -0
  129. package/src/desktop-update/runtime.ts +155 -0
  130. package/src/desktop-update/staging.ts +118 -0
  131. package/src/desktop-update/trust.ts +45 -0
  132. package/src/generated/compatibility-version.json +327 -195
  133. package/src/generated/model-metadata.ts +3 -3
  134. package/src/images/fulfill-video.ts +3 -3
  135. package/src/images/loop.ts +6 -2
  136. package/src/images/plan.ts +147 -11
  137. package/src/images/types.ts +13 -4
  138. package/src/images/xai-video-client.ts +72 -10
  139. package/src/lib/client-error-body.ts +6 -0
  140. package/src/lib/developer-role-rejection.ts +15 -0
  141. package/src/lib/gcp-adc.ts +48 -4
  142. package/src/lib/offline-resend.ts +150 -0
  143. package/src/lib/paced-stream.ts +3 -3
  144. package/src/lib/provider-outbound.ts +17 -6
  145. package/src/lib/request-failure-model.ts +2 -0
  146. package/src/lib/response-body-inactivity.ts +23 -1
  147. package/src/lib/upstream-retry.ts +39 -6
  148. package/src/link/explicit-route.ts +4 -4
  149. package/src/link/remote-windows.ts +79 -31
  150. package/src/link/residual-recovery.ts +20 -8
  151. package/src/messaging/budget.ts +23 -5
  152. package/src/messaging/remote-ports.ts +22 -10
  153. package/src/messaging/rpc.ts +4 -4
  154. package/src/oauth/antigravity-risk.ts +126 -0
  155. package/src/oauth/credential-siblings.ts +32 -0
  156. package/src/oauth/generic-account-failover.ts +113 -30
  157. package/src/oauth/generic-session-affinity.ts +10 -3
  158. package/src/oauth/index.ts +22 -14
  159. package/src/oauth/login-cli.ts +35 -1
  160. package/src/oauth/pool-kernel.ts +3 -3
  161. package/src/oauth/store.ts +38 -7
  162. package/src/providers/anthropic-billing-refusal.ts +27 -3
  163. package/src/providers/anthropic-reset-grants.ts +4 -0
  164. package/src/providers/claude-cli-usage.ts +2 -0
  165. package/src/providers/codebuddy-models.ts +11 -0
  166. package/src/providers/google-vertex-model-discovery.ts +49 -15
  167. package/src/providers/kiro-models.ts +5 -0
  168. package/src/providers/model-rename-fields.ts +2 -0
  169. package/src/providers/quota/workbuddy.ts +6 -2
  170. package/src/providers/registry/entries-core.ts +9 -3
  171. package/src/providers/registry/entries-extended.ts +20 -9
  172. package/src/providers/registry/model-seeds.ts +4 -1
  173. package/src/providers/stale-context-window-migration.ts +2 -0
  174. package/src/providers/workbuddy-credit-balance.ts +125 -16
  175. package/src/responses/citation-markers.ts +26 -23
  176. package/src/responses/effort-history.ts +732 -0
  177. package/src/routing/history/integrity.ts +41 -4
  178. package/src/server/auth-cors.ts +13 -3
  179. package/src/server/codex-model-list.ts +2 -1
  180. package/src/server/direct-local-http.ts +26 -3
  181. package/src/server/index/link-listener.ts +20 -14
  182. package/src/server/index/serve-options.ts +1 -0
  183. package/src/server/index.ts +3 -2
  184. package/src/server/link-turn.ts +17 -5
  185. package/src/server/management/config-routes.ts +39 -3
  186. package/src/server/management/link-child-preflight.ts +1 -1
  187. package/src/server/management/link-enrollment.ts +3 -3
  188. package/src/server/management/link-route-edit.ts +20 -1
  189. package/src/server/management/link-route-request.ts +11 -5
  190. package/src/server/management/oauth-account-routes.ts +43 -13
  191. package/src/server/management/provider-credential-release.ts +44 -0
  192. package/src/server/management/provider-overwrite-carry.ts +3 -0
  193. package/src/server/management/provider-routes.ts +12 -12
  194. package/src/server/management/static-catalog-probe.ts +33 -0
  195. package/src/server/management/usage-aggregate-cache.ts +6 -3
  196. package/src/server/messages-native.ts +16 -2
  197. package/src/server/proxy-liveness.ts +54 -9
  198. package/src/server/relay.ts +6 -1
  199. package/src/server/request-log-conversation.ts +8 -4
  200. package/src/server/request-log-failure-detail.ts +26 -9
  201. package/src/server/request-log.ts +5 -1
  202. package/src/server/reserve-capability-startup.ts +32 -0
  203. package/src/server/responses/adapter-continuation.ts +59 -25
  204. package/src/server/responses/adapter-delivery.ts +2 -0
  205. package/src/server/responses/adapter-dispatch.ts +39 -18
  206. package/src/server/responses/antigravity-fault-rotation.ts +24 -0
  207. package/src/server/responses/antigravity-validation-refusal.ts +43 -6
  208. package/src/server/responses/codex-tool-catalog.ts +47 -10
  209. package/src/server/responses/combo-selection-keepalive.ts +254 -0
  210. package/src/server/responses/combo-session-recall.ts +26 -1
  211. package/src/server/responses/combo-stream-preflight.ts +35 -26
  212. package/src/server/responses/core-combo-failure.ts +6 -0
  213. package/src/server/responses/core-combo-native.ts +2 -1
  214. package/src/server/responses/core-combo.ts +67 -28
  215. package/src/server/responses/core-errors.ts +9 -6
  216. package/src/server/responses/core-options.ts +10 -0
  217. package/src/server/responses/core.ts +21 -0
  218. package/src/server/responses/estimated-usage.ts +115 -0
  219. package/src/server/responses/input-admission.ts +41 -3
  220. package/src/server/responses/jev-model-invoke.ts +7 -2
  221. package/src/server/responses/passthrough-completion.ts +6 -3
  222. package/src/server/responses/passthrough-delivery.ts +47 -8
  223. package/src/server/responses/passthrough-dispatch.ts +3 -0
  224. package/src/server/responses/request-prepare.ts +9 -5
  225. package/src/server/responses/request-send-budget.ts +1 -1
  226. package/src/server/responses/request-transport.ts +10 -2
  227. package/src/server/responses/sidecar-execution.ts +11 -4
  228. package/src/service/desktop-supervision.d.mts +2 -0
  229. package/src/service/desktop-supervision.mjs +5 -0
  230. package/src/service/windows-checked-stop-live.ts +28 -5
  231. package/src/stall-timeout.ts +11 -0
  232. package/src/types/config.ts +15 -92
  233. package/src/types/provider.ts +13 -0
  234. package/src/types/request.ts +23 -3
  235. package/src/types/routed-catalog-defaults.ts +17 -0
  236. package/src/types/routing-profile.ts +90 -0
  237. package/src/types.ts +1 -0
  238. package/src/update/index.ts +1 -1
  239. package/src/usage/expected-prices.ts +35 -0
  240. package/src/usage/ledger-scanner.ts +44 -10
  241. package/src/usage/log.ts +14 -4
  242. package/src/usage/telemetry-contract.ts +1 -0
  243. package/src/web-search/loop.ts +20 -2
  244. package/src/web-search/parse.ts +2 -12
  245. package/src/web-search/passthrough-bridge.ts +7 -0
  246. package/src/web-search/sources.ts +13 -0
  247. package/gui/dist/assets/brand-mark-XOLJbomA.js +0 -1
  248. package/gui/dist/assets/index-DQtCRNAw.css +0 -2
  249. package/gui/dist/classic/assets/quota-summary-Dy5_wfTT.js +0 -1
@@ -0,0 +1,168 @@
1
+ /**
2
+ * Production composition of `ocx update --desktop` (#8246). The decisions live in
3
+ * `./headless.ts`; this file only binds them to the network, the filesystem, Windows Installer,
4
+ * the runtime record and the terminal.
5
+ */
6
+ import { readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
7
+ import { join, win32 } from "node:path";
8
+ import { getConfigDir } from "../config";
9
+ import { packageVersion } from "../lib/package-version";
10
+ import { findLiveProxy } from "../server/proxy-liveness";
11
+ import { requestBoundSystemRestart } from "../cli/system-restart-client";
12
+ import { CLIENT_RESTART_REQUEST_MIN_REMAINING_MS } from "../lib/system-restart-contract";
13
+ import { inspectDesktopSupervision, trustedWindowsSystemDirectory, windowsProcessPair } from "../service/desktop-supervision.mjs";
14
+ import { tryAcquireUpdateSyncMutex } from "../update/sync-update-mutex.mjs";
15
+ import { acquireBounded, fetchAcquireTransport, realAcquireTimers } from "./acquire";
16
+ import { DRAIN_DEADLINE_MS, DRAIN_STOP_DEADLINE_ENV, parseDrainResult, serviceRestartFailureDetail } from "./drain";
17
+ import { HEADLESS_EXIT, runHeadlessDesktopUpdate, type HeadlessResult } from "./headless";
18
+ import { windowsDesktopInstall, type WindowsDesktopInstall } from "./install";
19
+ import { ownImageMover } from "./image";
20
+ import { createStagingDirectory, windowsStagingDeps } from "./staging";
21
+
22
+ export const HEADLESS_USAGE = "Usage: ocx update --desktop [--check] [--json]";
23
+ /**
24
+ * The deadline handed to the bound restart request. A connected client refuses to ask for a
25
+ * restart it could not finish (and roll back) inside this window, so it must cover that budget.
26
+ */
27
+ export const RESTART_REQUEST_WINDOW_MS = CLIENT_RESTART_REQUEST_MIN_REMAINING_MS + 5_000;
28
+ const SERVICE_RESTART_TIMEOUT_MS = 150_000;
29
+ const VERSION_PROBE_TIMEOUT_MS = 20_000;
30
+
31
+ export function parseHeadlessArgs(args: readonly string[]): { ok: true; check: boolean; json: boolean } | { ok: false } {
32
+ let desktop = false, check = false, json = false;
33
+ for (const arg of args) {
34
+ if (arg === "--desktop" && !desktop) desktop = true;
35
+ else if (arg === "--check" && !check) check = true;
36
+ else if (arg === "--json" && !json) json = true;
37
+ else return { ok: false };
38
+ }
39
+ return desktop ? { ok: true, check, json } : { ok: false };
40
+ }
41
+
42
+ /** `opencodex <version>` from a bounded `--version` run of the installed executable. */
43
+ export function parseVersionOutput(output: string): string | null {
44
+ const match = /^opencodex (\S+)\s*$/m.exec(output);
45
+ return match ? match[1]! : null;
46
+ }
47
+
48
+ async function readInstalledVersion(ocxExe: string): Promise<string | null> {
49
+ try {
50
+ const child = Bun.spawn([ocxExe, "--version"], {
51
+ stdin: "ignore", stdout: "pipe", stderr: "ignore", windowsHide: true, timeout: VERSION_PROBE_TIMEOUT_MS,
52
+ });
53
+ const [output, code] = await Promise.all([new Response(child.stdout).text(), child.exited]);
54
+ return code === 0 ? parseVersionOutput(output.slice(0, 4096)) : null;
55
+ } catch {
56
+ return null;
57
+ }
58
+ }
59
+
60
+ /** The installed CLI's own `ocx stop --json`, as the app's update drain runs it. */
61
+ async function drainRuntime(install: WindowsDesktopInstall): Promise<{ ok: boolean; detail?: string }> {
62
+ try {
63
+ const child = Bun.spawn([install.ocxExe, "stop", "--json"], {
64
+ stdin: "ignore", stdout: "pipe", stderr: "ignore", windowsHide: true, timeout: DRAIN_DEADLINE_MS + 10_000,
65
+ env: { ...process.env, [DRAIN_STOP_DEADLINE_ENV]: String(DRAIN_DEADLINE_MS - 3_000) },
66
+ });
67
+ const [output, code] = await Promise.all([new Response(child.stdout).text(), child.exited]);
68
+ return parseDrainResult(output.slice(-65_536), code);
69
+ } catch {
70
+ return { ok: false, detail: "the installed ocx stop could not run" };
71
+ }
72
+ }
73
+
74
+ function desktopSupervisor(pid: number): string | null {
75
+ const evidence = inspectDesktopSupervision({ targetPid: pid });
76
+ return evidence.kind === "desktop" && evidence.runtimePid === pid ? evidence.app : null;
77
+ }
78
+
79
+ /** The installed CLI's `ocx service restart`, which confirms a different serving pid or exits 1. */
80
+ async function restartService(install: WindowsDesktopInstall): Promise<{ ok: boolean; detail?: string }> {
81
+ try {
82
+ const child = Bun.spawn([install.ocxExe, "service", "restart"], {
83
+ stdin: "ignore", stdout: "ignore", stderr: "pipe", windowsHide: true, timeout: SERVICE_RESTART_TIMEOUT_MS,
84
+ });
85
+ const [errors, code] = await Promise.all([new Response(child.stderr).text(), child.exited]);
86
+ if (code === 0) return { ok: true };
87
+ return { ok: false, detail: serviceRestartFailureDetail(errors.slice(-65_536), code) };
88
+ } catch {
89
+ return { ok: false, detail: "the installed ocx service restart could not run" };
90
+ }
91
+ }
92
+
93
+ function print(result: HeadlessResult, json: boolean): void {
94
+ if (json) {
95
+ console.log(JSON.stringify(result));
96
+ return;
97
+ }
98
+ const line = result.message;
99
+ if (result.exitCode === HEADLESS_EXIT.ok) console.log(`✅ ${line}`);
100
+ else console.error(`❌ ${line}`);
101
+ }
102
+
103
+ export async function runHeadlessDesktopUpdateCommand(args: readonly string[]): Promise<number> {
104
+ const parsed = parseHeadlessArgs(args);
105
+ if (!parsed.ok) {
106
+ console.error(HEADLESS_USAGE);
107
+ return HEADLESS_EXIT.usage;
108
+ }
109
+ const install = windowsDesktopInstall();
110
+ if (!install) {
111
+ console.error("ocx update --desktop updates a Windows OpenCodex Desktop installation and must be run with that installation's ocx.exe "
112
+ + "(next to opencodex-desktop.exe). On other installations use 'ocx update', or the app's own updater (tray → Check for Updates).");
113
+ return HEADLESS_EXIT.usage;
114
+ }
115
+ const log = (line: string) => (parsed.json ? console.error : console.log)(line);
116
+ let mutex: ReturnType<typeof tryAcquireUpdateSyncMutex> | null = null;
117
+ if (!parsed.check) {
118
+ mutex = tryAcquireUpdateSyncMutex(getConfigDir(), "update");
119
+ if (mutex.kind === "busy") {
120
+ console.error(`opencodex: another ${mutex.holder === "sync" ? "sync" : "update"} is in progress for this home; retry when it finishes.`);
121
+ return HEADLESS_EXIT.unchanged;
122
+ }
123
+ }
124
+ try {
125
+ const result = await runHeadlessDesktopUpdate({ check: parsed.check }, {
126
+ install,
127
+ currentVersion: packageVersion(),
128
+ fetch: (url, maxBytes) => acquireBounded(url, { maxBytes }, { transport: fetchAcquireTransport, timers: realAcquireTimers }),
129
+ staging: {
130
+ create: () => createStagingDirectory(windowsStagingDeps),
131
+ write: (path, bytes) => writeFileSync(path, bytes, { flag: "wx", mode: 0o600 }),
132
+ read: path => new Uint8Array(readFileSync(path)),
133
+ join: (dir, name) => join(dir, name),
134
+ discard: (dir, keep) => {
135
+ if (!keep.length) { rmSync(dir, { recursive: true, force: true }); return; }
136
+ for (const name of readdirSync(dir)) {
137
+ const path = join(dir, name);
138
+ if (!keep.includes(path)) rmSync(path, { force: true });
139
+ }
140
+ },
141
+ },
142
+ ...ownImageMover(install),
143
+ msiexecPath: () => win32.join(trustedWindowsSystemDirectory(), "msiexec.exe"),
144
+ spawnInstaller: (file, installerArgs) => {
145
+ const child = Bun.spawn([file, ...installerArgs], { stdin: "ignore", stdout: "ignore", stderr: "ignore", windowsHide: true });
146
+ return { exited: child.exited };
147
+ },
148
+ timers: realAcquireTimers,
149
+ readInstalledVersion,
150
+ runtime: {
151
+ findLive: () => findLiveProxy(),
152
+ runtimeImage: pid => windowsProcessPair(pid).child?.exe ?? null,
153
+ requestRestart: (live, targetVersion) => requestBoundSystemRestart(live, Date.now() + RESTART_REQUEST_WINDOW_MS,
154
+ { cliVersion: targetVersion, respawnRunsInstalledImage: true }),
155
+ desktopSupervisor,
156
+ drainRuntime: () => drainRuntime(install),
157
+ restartService: () => restartService(install),
158
+ now: Date.now,
159
+ wait: ms => Bun.sleep(ms),
160
+ },
161
+ log,
162
+ });
163
+ print(result, parsed.json);
164
+ return result.exitCode;
165
+ } finally {
166
+ if (mutex?.kind === "acquired") mutex.release();
167
+ }
168
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Reading the installed CLI's `ocx stop --json` result for the headless Desktop updater (#8246).
3
+ *
4
+ * The same acceptance the Desktop app applies to its own drain (`desktop/src-tauri/src/runtime_stop.rs`):
5
+ * the `ocx-stop/1` document and the process exit code must agree that this home's runtime is down.
6
+ * Exit 79 (history cleanup incomplete) still stopped the runtime; everything else is a failure.
7
+ */
8
+
9
+ /** The app's Windows drain budget; the CLI receives it as OCX_STOP_DEADLINE_MS. */
10
+ export const DRAIN_DEADLINE_MS = 75_000;
11
+ export const DRAIN_STOP_DEADLINE_ENV = "OCX_STOP_DEADLINE_MS";
12
+
13
+ export function parseDrainResult(stdout: string, exitCode: number | null): { ok: boolean; detail?: string } {
14
+ const line = stdout.split(/\r?\n/).map(text => text.trim()).filter(text => text.startsWith("{")).at(-1);
15
+ let summary: Record<string, unknown> | null = null;
16
+ try { summary = line ? JSON.parse(line) as Record<string, unknown> : null; } catch { summary = null; }
17
+ if (!summary || summary.schema !== "ocx-stop/1") {
18
+ return { ok: false, detail: `unreadable stop result (exit ${exitCode ?? "none"})` };
19
+ }
20
+ const proxyDown = summary.proxy === "stopped" || summary.proxy === "stopped-orphan";
21
+ const stopped = exitCode === 0 && summary.ok === true && summary.exitCode === 0 && summary.runtimeDown === true
22
+ && ((summary.outcome === "stopped" && proxyDown) || (summary.outcome === "not-running" && summary.proxy === "not-running"));
23
+ const historyOnly = exitCode === 79 && summary.exitCode === 79 && summary.outcome === "history-incomplete"
24
+ && summary.runtimeDown === true && proxyDown;
25
+ if (stopped || historyOnly) return { ok: true };
26
+ const message = typeof summary.message === "string" ? `: ${summary.message.slice(0, 200)}` : "";
27
+ return { ok: false, detail: `${String(summary.outcome)}/${String(summary.proxy)} exit ${exitCode ?? "none"}${message}` };
28
+ }
29
+
30
+ /**
31
+ * The reason `ocx service restart` gives for not restarting: its first warning or error line,
32
+ * which names the cause, rather than the trailing log path. Bounded; emoji markers dropped.
33
+ */
34
+ export function serviceRestartFailureDetail(stderr: string, exitCode: number | null): string {
35
+ const lines = stderr.split(/\r?\n/).map(line => line.trim()).filter(Boolean);
36
+ const marker = /^(?:\u26a0\ufe0f|\u26a0|\u274c)\s*/u;
37
+ const reason = lines.find(line => marker.test(line)) ?? lines.find(line => !/^(?:Log|Diagnostics):/i.test(line));
38
+ const text = reason?.replace(marker, "").slice(0, 400);
39
+ return `exit ${exitCode ?? "none"}${text ? `: ${text}` : ""}`;
40
+ }
@@ -0,0 +1,285 @@
1
+ /**
2
+ * Headless Windows Desktop update (`ocx update --desktop`, #8246).
3
+ *
4
+ * One pass: read the published channel, and when it announces a newer version, download the
5
+ * Windows MSI under the acquisition contract, verify it with the GUI updater's embedded key,
6
+ * stage it where nothing with fewer rights than the installer can change it (`./staging.ts`) and
7
+ * verify the staged copy again, install it non-interactively and wait for the installer's exit
8
+ * code, read the installed `ocx.exe` version back, then make the serving
9
+ * runtime that version. When nothing newer is published, the same pass still finishes an
10
+ * earlier install whose old runtime is still serving. Every dependency is injected; the
11
+ * production wiring is in `./cli.ts`.
12
+ */
13
+ import { DESKTOP_ACQUIRE_LIMITS, DESKTOP_UPDATE_FEED_URL } from "./trust";
14
+ import { DesktopAcquireError, type AcquireTimers } from "./acquire";
15
+ import { compareToInstalled, DesktopUpdateRefusal, parseDesktopFeed, verifyDesktopInstaller } from "./release";
16
+ import { describeMsiOutcome, isInstalled, runMsiInstall, type InstallerSpawn, type MsiOutcome } from "./msi";
17
+ import { settleRuntime, type RuntimeOutcome, type RuntimeReplaceDeps } from "./runtime";
18
+ import { desktopUpdateCommand, type WindowsDesktopInstall } from "./install";
19
+ import { computeVersionSkew } from "../cli/version-skew";
20
+
21
+ export const HEADLESS_RESULT_SCHEMA = "ocx.desktop.headless-update/1";
22
+
23
+ /** 0 done; 1 nothing installed; 2 installed but the old runtime still serves; 3 uncertain; 64 usage. */
24
+ export const HEADLESS_EXIT = Object.freeze({ ok: 0, unchanged: 1, runtimeStale: 2, uncertain: 3, usage: 64 });
25
+
26
+ export type HeadlessOutcome =
27
+ | "up-to-date"
28
+ | "available"
29
+ | "updated"
30
+ | "runtime-replaced"
31
+ | "installed-stopped"
32
+ | "refused"
33
+ | "failed"
34
+ | "installer-failed"
35
+ | "installer-uncertain"
36
+ | "reboot-required"
37
+ | "installed-version-mismatch"
38
+ | "old-runtime-serving";
39
+
40
+ export interface HeadlessResult {
41
+ schema: typeof HEADLESS_RESULT_SCHEMA;
42
+ outcome: HeadlessOutcome;
43
+ exitCode: number;
44
+ installedVersion: string;
45
+ targetVersion: string | null;
46
+ runtime: { pid: number | null; port: number; version: string | null } | null;
47
+ installer: { exitCode: number | null; log: string | null; rebootRequired: boolean } | null;
48
+ reason: string | null;
49
+ message: string;
50
+ }
51
+
52
+ export interface StagingArea {
53
+ /** Create a private, operation-owned directory and return its path. */
54
+ create(): string;
55
+ write(path: string, bytes: Uint8Array): void;
56
+ read(path: string): Uint8Array;
57
+ join(dir: string, name: string): string;
58
+ /** Remove this operation's directory, keeping only the named files when any are given. */
59
+ discard(dir: string, keep: readonly string[]): void;
60
+ }
61
+
62
+ export interface HeadlessDeps {
63
+ install: WindowsDesktopInstall;
64
+ /** The version of the `ocx.exe` running this command, which is the installed version. */
65
+ currentVersion: string;
66
+ fetch(url: string, maxBytes: number): Promise<Uint8Array>;
67
+ staging: StagingArea;
68
+ /**
69
+ * Rename the running `ocx.exe` image aside inside the installation (Windows allows renaming a
70
+ * running executable) and return its new path, or null when this process is not running the
71
+ * installed image. Without this, Windows Installer's Restart Manager closes this very process,
72
+ * and everything sharing its console, to replace the file, and the install rolls back. Throws
73
+ * when the image cannot be moved.
74
+ */
75
+ moveAsideOwnImage(): string | null;
76
+ /**
77
+ * After an install that did not complete, make sure the installed path holds an `ocx.exe`:
78
+ * true when it already does or the moved image was put back.
79
+ */
80
+ restoreOwnImage(moved: string): boolean;
81
+ /** Best effort: delete images earlier runs moved aside, and schedule `current` for deletion. */
82
+ retireMovedImages(current: string | null): void;
83
+ msiexecPath(): string;
84
+ spawnInstaller: InstallerSpawn;
85
+ timers: AcquireTimers;
86
+ installerTimeoutMs?: number;
87
+ runtimeDeadlineMs?: number;
88
+ readInstalledVersion(ocxExe: string): Promise<string | null>;
89
+ runtime: RuntimeReplaceDeps;
90
+ log(line: string): void;
91
+ /** Fixture key for tests only; the production composition never sets it and uses the embedded key. */
92
+ fixturePublicKey?: string;
93
+ }
94
+
95
+ export const INSTALLER_TIMEOUT_MS = 15 * 60_000;
96
+ /**
97
+ * Room for a connected client's 90-second restart budget, or a 75-second drain or service
98
+ * restart, followed by the owner's respawn and the replacement's startup.
99
+ */
100
+ export const RUNTIME_DEADLINE_MS = 240_000;
101
+
102
+ function runtimeView(live: { pid: number | null; port: number; version?: string } | null): HeadlessResult["runtime"] {
103
+ return live ? { pid: live.pid, port: live.port, version: live.version ?? null } : null;
104
+ }
105
+
106
+ function staleMessage(outcome: Extract<RuntimeOutcome, { kind: "stale" }>, target: string, install: WindowsDesktopInstall): string {
107
+ const live = outcome.live;
108
+ const who = live ? `The proxy on port ${live.port}${live.pid !== null ? ` (pid ${live.pid})` : ""} still serves ${live.version ?? "an unknown version"}` : "No proxy answers with the installed version";
109
+ const retry = `Replace it with: ${desktopUpdateCommand(install)} (or quit and reopen OpenCodex Desktop).`;
110
+ switch (outcome.reason) {
111
+ case "foreign-image":
112
+ return `${who}; this installation is ${target}. It runs from ${outcome.detail ?? "another executable"}, not ${install.ocxExe}, so it was not stopped. Restart it from the installation that owns it.`;
113
+ case "runtime-newer":
114
+ return `${who}, which is newer than this installation (${target}); it was left running.`;
115
+ case "unattested":
116
+ case "unknown-version":
117
+ case "incomparable":
118
+ return `${who}; this installation is ${target}. Its identity or version could not be verified, so it was not stopped. Run 'ocx status', then restart it through its owner. ${retry}`;
119
+ case "restart-refused":
120
+ return `${who}; this installation is ${target}. The runtime refused a restart (${outcome.detail ?? "refused"}), so nothing was stopped. ${retry}`;
121
+ case "drain-failed":
122
+ return `${who}; this installation is ${target}. Stopping it for OpenCodex Desktop to restart did not complete (${outcome.detail ?? "unconfirmed"}). Run 'ocx status'. ${retry}`;
123
+ case "service-restart-failed":
124
+ return `${who}; this installation is ${target}. Its background service owns it, and '${install.ocxExe}' service restart did not replace it (${outcome.detail ?? "unconfirmed"}). `
125
+ + `Nothing else was stopped; the installed version starts the next time that service starts the proxy, for example after Windows restarts. Run 'ocx service status'. ${retry}`;
126
+ case "replacement-timeout":
127
+ return `${who}; this installation is ${target}. A restart was requested but the new version was not observed answering in time. Run 'ocx status'. ${retry}`;
128
+ }
129
+ }
130
+
131
+ export async function runHeadlessDesktopUpdate(options: { check: boolean }, deps: HeadlessDeps): Promise<HeadlessResult> {
132
+ const installed = deps.currentVersion;
133
+ const base = { schema: HEADLESS_RESULT_SCHEMA, installedVersion: installed, installer: null, reason: null } as const;
134
+ const finish = (fields: Partial<HeadlessResult> & Pick<HeadlessResult, "outcome" | "exitCode" | "message">): HeadlessResult =>
135
+ ({ ...base, targetVersion: null, runtime: null, ...fields });
136
+
137
+ // 1. The published channel.
138
+ let candidate;
139
+ try {
140
+ candidate = parseDesktopFeed(await deps.fetch(DESKTOP_UPDATE_FEED_URL, DESKTOP_ACQUIRE_LIMITS.maxFeedBytes));
141
+ } catch (error) {
142
+ return failure(error, null);
143
+ }
144
+ const relation = compareToInstalled(installed, candidate.version);
145
+ const runtimeDeadline = () => deps.runtime.now() + (deps.runtimeDeadlineMs ?? RUNTIME_DEADLINE_MS);
146
+
147
+ // 2. Nothing newer: an earlier install may still have an old runtime serving.
148
+ if (relation !== "newer") {
149
+ if (relation === "unknown") {
150
+ return finish({ outcome: "refused", exitCode: HEADLESS_EXIT.unchanged, targetVersion: candidate.version, reason: "version_unknown",
151
+ message: `The installed version ${installed} cannot be compared with the published ${candidate.version}; nothing was changed.` });
152
+ }
153
+ const live = await deps.runtime.findLive();
154
+ // Only this home's attested runtime, older than this installation, is one an install left behind.
155
+ const stale = live?.source === "runtime" && live.version !== undefined
156
+ && computeVersionSkew(installed, live.version).relation === "cli-newer";
157
+ if (options.check || !stale) {
158
+ return finish({
159
+ outcome: stale ? "old-runtime-serving" : "up-to-date",
160
+ exitCode: stale ? HEADLESS_EXIT.runtimeStale : HEADLESS_EXIT.ok,
161
+ targetVersion: candidate.version, runtime: runtimeView(live),
162
+ message: stale
163
+ ? `OpenCodex Desktop ${installed} is installed, but the running proxy still serves ${live!.version}. Replace it with: ${desktopUpdateCommand(deps.install)}`
164
+ : `OpenCodex Desktop is up to date (${installed}).`,
165
+ });
166
+ }
167
+ deps.log(`OpenCodex Desktop ${installed} is installed, but the running proxy serves ${live!.version}; replacing it.`);
168
+ const settled = await settleRuntime({ installedExe: deps.install.ocxExe, targetVersion: installed, deadlineAt: runtimeDeadline(), wasRunning: true, expectedPort: live!.port }, deps.runtime);
169
+ return fromRuntime(settled, installed, null, "runtime-replaced");
170
+ }
171
+
172
+ if (options.check) {
173
+ const live = await deps.runtime.findLive();
174
+ return finish({ outcome: "available", exitCode: HEADLESS_EXIT.ok, targetVersion: candidate.version, runtime: runtimeView(live),
175
+ message: `OpenCodex Desktop ${candidate.version} is available (installed: ${installed}). Install it with: ${desktopUpdateCommand(deps.install)}` });
176
+ }
177
+
178
+ // 3. Download and verify.
179
+ const found = await deps.runtime.findLive();
180
+ // A proxy without this home's runtime record is not the one this update must replace.
181
+ const before = found?.source === "runtime" ? found : null;
182
+ deps.log(`Downloading OpenCodex Desktop ${candidate.version}…`);
183
+ let bytes: Uint8Array;
184
+ try {
185
+ bytes = await deps.fetch(candidate.url, DESKTOP_ACQUIRE_LIMITS.maxArtifactBytes);
186
+ verifyDesktopInstaller(bytes, candidate, deps.fixturePublicKey);
187
+ } catch (error) {
188
+ return failure(error, candidate.version);
189
+ }
190
+ deps.log(`Verified the installer signature for ${candidate.version}.`);
191
+
192
+ // 4. Stage privately, verify the staged bytes again, install.
193
+ let dir: string | null = null;
194
+ let logPath: string | null = null;
195
+ let moved: string | null = null;
196
+ let installer: MsiOutcome;
197
+ // Best effort: a file still held open (msiexec, an indexer) stays in this operation's directory.
198
+ const discard = (keep: readonly string[]) => {
199
+ if (!dir) return;
200
+ try { deps.staging.discard(dir, keep); } catch { /* left for the user or the next temp cleanup */ }
201
+ };
202
+ try {
203
+ deps.retireMovedImages(null);
204
+ dir = deps.staging.create();
205
+ const msiPath = deps.staging.join(dir, `OpenCodex-${candidate.version}-windows-x64.msi`);
206
+ logPath = deps.staging.join(dir, "msiexec.log");
207
+ deps.staging.write(msiPath, bytes);
208
+ verifyDesktopInstaller(deps.staging.read(msiPath), candidate, deps.fixturePublicKey);
209
+ try { moved = deps.moveAsideOwnImage(); }
210
+ catch (error) {
211
+ throw new Error(`the running ${deps.install.ocxExe} could not be moved aside for the installer (${error instanceof Error ? error.message : String(error)}); run this from an elevated terminal`);
212
+ }
213
+ deps.log("Installing (Windows Installer, no UI)…");
214
+ installer = await runMsiInstall({ msiexec: deps.msiexecPath(), msiPath, logPath, timeoutMs: deps.installerTimeoutMs ?? INSTALLER_TIMEOUT_MS },
215
+ { spawn: deps.spawnInstaller, timers: deps.timers });
216
+ } catch (error) {
217
+ if (moved) deps.restoreOwnImage(moved);
218
+ discard([]);
219
+ return failure(error, candidate.version);
220
+ }
221
+ const installerView = { exitCode: installer.code, log: logPath, rebootRequired: installer.kind === "installed-reboot-required" };
222
+ const previous = moved ? ` The previous ocx.exe is at ${moved}.` : "";
223
+ if (!isInstalled(installer)) {
224
+ // A finished, rolled-back install has restored the copy at the installed path; the moved image
225
+ // goes back only if that path is empty. An installer that may still be running is left alone
226
+ // with everything it may hold open: the package, the log and the moved image.
227
+ const uncertain = installer.kind === "uncertain";
228
+ const restored = moved && !uncertain ? deps.restoreOwnImage(moved) : false;
229
+ const stranded = moved && !restored ? ` The previous ocx.exe is at ${moved}.` : "";
230
+ if (!uncertain) discard(logPath ? [logPath] : []);
231
+ return finish({ outcome: uncertain ? "installer-uncertain" : "installer-failed",
232
+ exitCode: uncertain ? HEADLESS_EXIT.uncertain : HEADLESS_EXIT.unchanged,
233
+ targetVersion: candidate.version, runtime: runtimeView(before), installer: installerView, reason: installer.kind,
234
+ message: `${describeMsiOutcome(installer)} Log: ${logPath}${uncertain ? ` The staged installer is kept in ${dir}.` : ""}${stranded}` });
235
+ }
236
+ deps.log(describeMsiOutcome(installer));
237
+
238
+ // 5. Read the installed binary back; the moved image is retired only once it matches.
239
+ const readBack = await deps.readInstalledVersion(deps.install.ocxExe);
240
+ if (readBack !== candidate.version) {
241
+ discard(logPath ? [logPath] : []);
242
+ const reboot = installer.kind === "installed-reboot-required";
243
+ return finish({ outcome: reboot ? "reboot-required" : "installed-version-mismatch",
244
+ exitCode: reboot ? HEADLESS_EXIT.runtimeStale : HEADLESS_EXIT.uncertain,
245
+ targetVersion: candidate.version, runtime: runtimeView(before), installer: installerView, reason: "installed_version",
246
+ message: reboot
247
+ ? `The installer finished but ${deps.install.ocxExe} still reports ${readBack ?? "no version"}; restart Windows to complete the update to ${candidate.version}. Log: ${logPath}${previous}`
248
+ : `The installer reported success but ${deps.install.ocxExe} reports ${readBack ?? "no version"}, not ${candidate.version}. Log: ${logPath}${previous}` });
249
+ }
250
+ deps.retireMovedImages(moved);
251
+ discard([]);
252
+
253
+ // 6. Replace the runtime that still serves the old version.
254
+ const settled = await settleRuntime({ installedExe: deps.install.ocxExe, targetVersion: candidate.version, deadlineAt: runtimeDeadline(), wasRunning: before !== null, ...(before ? { expectedPort: before.port } : {}) }, deps.runtime);
255
+ return fromRuntime(settled, candidate.version, { ...installerView, log: null }, "updated");
256
+
257
+ function fromRuntime(settled: RuntimeOutcome, target: string, installerResult: HeadlessResult["installer"], done: "updated" | "runtime-replaced"): HeadlessResult {
258
+ const reboot = installerResult?.rebootRequired ? " Windows still has to restart to replace some files." : "";
259
+ if (settled.kind === "serving-target") {
260
+ return finish({ outcome: installerResult || settled.replaced ? done : "up-to-date", exitCode: HEADLESS_EXIT.ok, targetVersion: target,
261
+ runtime: runtimeView(settled.live), installer: installerResult,
262
+ message: `OpenCodex Desktop ${target} is installed and the proxy on port ${settled.live.port} serves ${target}.${reboot}` });
263
+ }
264
+ if (settled.kind === "not-running") {
265
+ return finish({ outcome: "installed-stopped", exitCode: HEADLESS_EXIT.ok, targetVersion: target, installer: installerResult,
266
+ message: `OpenCodex Desktop ${target} is installed. No proxy for this home was found, so none was started.${reboot}` });
267
+ }
268
+ return finish({ outcome: "old-runtime-serving", exitCode: HEADLESS_EXIT.runtimeStale, targetVersion: target,
269
+ runtime: runtimeView(settled.live), installer: installerResult, reason: settled.reason,
270
+ message: staleMessage(settled, target, deps.install) });
271
+ }
272
+
273
+ function failure(error: unknown, target: string | null): HeadlessResult {
274
+ if (error instanceof DesktopUpdateRefusal) {
275
+ return finish({ outcome: "refused", exitCode: HEADLESS_EXIT.unchanged, targetVersion: target, reason: error.code,
276
+ message: `Update refused: ${error.message}. Nothing was installed.` });
277
+ }
278
+ if (error instanceof DesktopAcquireError) {
279
+ return finish({ outcome: "failed", exitCode: HEADLESS_EXIT.unchanged, targetVersion: target, reason: error.code,
280
+ message: `Download failed: ${error.message}${error.retryable ? " (retryable)" : ""}. Nothing was installed.` });
281
+ }
282
+ return finish({ outcome: "failed", exitCode: HEADLESS_EXIT.unchanged, targetVersion: target, reason: "internal",
283
+ message: `Update failed before installation: ${error instanceof Error ? error.message : String(error)}. Nothing was installed.` });
284
+ }
285
+ }
@@ -0,0 +1,85 @@
1
+ /**
2
+ * The updater's own running `ocx.exe` and Windows Installer (#8246).
3
+ *
4
+ * Windows Installer's Restart Manager closes every process that maps a file the package replaces,
5
+ * which would end this command and everything sharing its console and roll the install back.
6
+ * Windows allows renaming a running image, so the running file is renamed aside inside the
7
+ * installation directory, where its mapping stays valid, and an unmapped copy of it takes the
8
+ * installed name. The name is empty only between two back-to-back renames, and then only while
9
+ * Windows Installer itself replaces the file (a major upgrade removes the old one first); the
10
+ * installer finishes or rolls back its own transaction even if this command is killed (Ctrl+C, a
11
+ * closed console, a dropped SSH session), so nothing this command did has to be put back.
12
+ */
13
+ import { constants, copyFileSync, existsSync, readdirSync, renameSync, rmSync } from "node:fs";
14
+ import { win32 } from "node:path";
15
+ import { trustedWindowsSystemDirectory } from "../service/desktop-supervision.mjs";
16
+ import { dlopen, ptr } from "bun:ffi";
17
+ import { movedImageName, sameWindowsPath } from "./runtime";
18
+ import type { WindowsDesktopInstall } from "./install";
19
+
20
+ const MOVEFILE_DELAY_UNTIL_REBOOT = 4;
21
+ /** Images earlier runs moved aside, and copies a run killed mid-swap left behind. */
22
+ const LEFTOVER_IMAGE_PATTERN = /^ocx\.exe\.\d+-\d+\.update-(?:old|new)$/i;
23
+
24
+ /** Ask Windows to delete a still-mapped file at the next restart; best effort. */
25
+ function deleteAtReboot(path: string): void {
26
+ try {
27
+ const kernel32 = dlopen(win32.join(trustedWindowsSystemDirectory(), "kernel32.dll"), { MoveFileExW: { args: ["ptr", "ptr", "u32"], returns: "i32" } });
28
+ try {
29
+ const wide = Buffer.from(`${path}\0`, "utf16le");
30
+ kernel32.symbols.MoveFileExW(ptr(wide), null, MOVEFILE_DELAY_UNTIL_REBOOT);
31
+ } finally { kernel32.close(); }
32
+ } catch { /* the next run removes it instead */ }
33
+ }
34
+
35
+ export interface OwnImageOptions {
36
+ execPath?: string;
37
+ pid?: number;
38
+ now?: () => number;
39
+ join?: (dir: string, name: string) => string;
40
+ deleteAtReboot?: (path: string) => void;
41
+ }
42
+
43
+ export function ownImageMover(install: WindowsDesktopInstall, options: OwnImageOptions = {}) {
44
+ const join = options.join ?? win32.join;
45
+ const scheduleDelete = options.deleteAtReboot ?? deleteAtReboot;
46
+ return {
47
+ moveAsideOwnImage: () => {
48
+ if (!sameWindowsPath(options.execPath ?? process.execPath, install.ocxExe)) return null;
49
+ const name = movedImageName(options.pid ?? process.pid, (options.now ?? Date.now)());
50
+ const moved = join(install.dir, name);
51
+ const copy = join(install.dir, name.replace(/\.update-old$/, ".update-new"));
52
+ // Copy first, then two renames back to back: the installed name is empty only between them.
53
+ copyFileSync(install.ocxExe, copy, constants.COPYFILE_EXCL);
54
+ try { renameSync(install.ocxExe, moved); }
55
+ catch (error) { rmSync(copy, { force: true }); throw error; }
56
+ try { renameSync(copy, install.ocxExe); }
57
+ catch (error) {
58
+ try { renameSync(moved, install.ocxExe); }
59
+ catch {
60
+ // Neither image is back at the installed name: keep both and say where they are, never delete the last copy.
61
+ const detail = error instanceof Error ? error.message : String(error);
62
+ throw new Error(`${install.ocxExe} could not be put back (${detail}). The previous ocx.exe is at ${moved} and an identical copy at ${copy}; rename either one to ${install.ocxExe}.`);
63
+ }
64
+ rmSync(copy, { force: true });
65
+ throw error;
66
+ }
67
+ return moved;
68
+ },
69
+ restoreOwnImage: (moved: string) => {
70
+ if (existsSync(install.ocxExe)) return true;
71
+ try { renameSync(moved, install.ocxExe); return true; } catch { return false; }
72
+ },
73
+ retireMovedImages: (current: string | null) => {
74
+ let names: string[] = [];
75
+ try { names = readdirSync(install.dir); } catch { return; }
76
+ for (const name of names) {
77
+ const path = join(install.dir, name);
78
+ if (!LEFTOVER_IMAGE_PATTERN.test(name) || path === current) continue;
79
+ try { rmSync(path); } catch { /* still mapped by a process; a later run or a restart removes it */ }
80
+ }
81
+ if (current) scheduleDelete(current);
82
+ },
83
+ };
84
+ }
85
+
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Recognizing a Windows OpenCodex Desktop installation from its bundled `ocx.exe` (#8246).
3
+ *
4
+ * The MSI installs `opencodex-desktop.exe` and its sidecar `ocx.exe` side by side; the headless
5
+ * updater and the stale-runtime advice apply only when this CLI is that compiled sidecar.
6
+ */
7
+ import { win32 } from "node:path";
8
+ import { existsSync } from "node:fs";
9
+ import { isStandaloneBinary } from "../lib/standalone";
10
+ import type { VersionSkew } from "../cli/version-skew";
11
+
12
+ export interface WindowsDesktopInstall {
13
+ dir: string;
14
+ ocxExe: string;
15
+ desktopExe: string;
16
+ }
17
+
18
+ export interface DesktopInstallProbe {
19
+ platform?: NodeJS.Platform;
20
+ execPath?: string;
21
+ standalone?: boolean;
22
+ exists?: (path: string) => boolean;
23
+ }
24
+
25
+ export function windowsDesktopInstall(probe: DesktopInstallProbe = {}): WindowsDesktopInstall | null {
26
+ if ((probe.platform ?? process.platform) !== "win32") return null;
27
+ if (!(probe.standalone ?? isStandaloneBinary())) return null;
28
+ const execPath = probe.execPath ?? process.execPath;
29
+ if (win32.basename(execPath).toLowerCase() !== "ocx.exe" || !/^[A-Za-z]:[\\/]/.test(execPath)) return null;
30
+ const dir = win32.dirname(execPath.replaceAll("/", "\\"));
31
+ const desktopExe = win32.join(dir, "opencodex-desktop.exe");
32
+ if (!(probe.exists ?? existsSync)(desktopExe)) return null;
33
+ return { dir, ocxExe: win32.join(dir, "ocx.exe"), desktopExe };
34
+ }
35
+
36
+ /** The command that finishes an installed update by replacing the runtime that still serves. */
37
+ export function desktopUpdateCommand(install: WindowsDesktopInstall): string {
38
+ return `"${install.ocxExe}" update --desktop`;
39
+ }
40
+
41
+ /**
42
+ * On a Desktop installation, a CLI newer than the serving proxy means the MSI installed an update
43
+ * the running runtime has not picked up. Say so, with the command that completes it, only for a
44
+ * proxy this home's runtime record attests: the command never replaces any other.
45
+ */
46
+ export function withDesktopSkewAdvice(skew: VersionSkew, install: WindowsDesktopInstall | null, liveSource: string | undefined): VersionSkew {
47
+ if (!install || liveSource !== "runtime" || skew.relation !== "cli-newer" || !skew.proxyVersion) return skew;
48
+ return {
49
+ ...skew,
50
+ warning: `OpenCodex Desktop ${skew.cliVersion} is installed, but the running proxy still serves ${skew.proxyVersion}. `
51
+ + `Replace it with: ${desktopUpdateCommand(install)} (or quit and reopen OpenCodex Desktop).`,
52
+ };
53
+ }