@bitkyc08/opencodex 2.96.0 → 2.97.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 (240) hide show
  1. package/bin/ocx.mjs +214 -19
  2. package/gui/dist/assets/{App-bwugJRKn.js → App-DuNhggE1.js} +15 -15
  3. package/gui/dist/assets/{Tray-BOPQyDbH.js → Tray-CEw0y0jR.js} +1 -1
  4. package/gui/dist/assets/index-CynE_Rue.js +94 -0
  5. package/gui/dist/assets/{quota-summary-6HsrHQAy.js → quota-summary-VHFSlUuM.js} +1 -1
  6. package/gui/dist/index.html +1 -1
  7. package/package.json +1 -1
  8. package/src/adapters/command-code.ts +15 -16
  9. package/src/adapters/cursor/transport-retry.ts +2 -2
  10. package/src/adapters/devin/cloud-direct/chat.ts +15 -6
  11. package/src/adapters/kiro/stream.ts +63 -4
  12. package/src/adapters/kiro-constants.ts +15 -1
  13. package/src/adapters/kiro-events.ts +31 -1
  14. package/src/adapters/kiro-retry.ts +3 -3
  15. package/src/adapters/ollama-native.ts +11 -1
  16. package/src/adapters/openai-responses/empty-assistant.ts +15 -3
  17. package/src/adapters/openai-responses/passthrough.ts +5 -4
  18. package/src/adapters/openai-responses/reasoning.ts +9 -4
  19. package/src/adapters/openai-responses/request-strips.ts +1 -1
  20. package/src/adapters/physical-send.ts +3 -3
  21. package/src/adapters/zed-openai-stream.ts +2 -1
  22. package/src/bridge/errors.ts +11 -2
  23. package/src/bridge/response-json.ts +2 -1
  24. package/src/bridge/sse.ts +14 -6
  25. package/src/chat/failure-verdict.ts +21 -0
  26. package/src/chat/outbound.ts +139 -21
  27. package/src/claude/outbound.ts +49 -2
  28. package/src/cli/capabilities-base.ts +25 -3
  29. package/src/cli/capabilities-command.ts +12 -3
  30. package/src/cli/capability-contracts.ts +2 -0
  31. package/src/cli/codex-launch-auth.ts +30 -1
  32. package/src/cli/codex-launcher.ts +12 -5
  33. package/src/cli/codex-shim-autorestore.ts +5 -4
  34. package/src/cli/dispatch.ts +11 -176
  35. package/src/cli/help.ts +2 -2
  36. package/src/cli/index.ts +5 -1
  37. package/src/cli/link.ts +1 -1
  38. package/src/cli/registry.ts +11 -3
  39. package/src/cli/root.ts +8 -0
  40. package/src/cli/sync-command.ts +243 -0
  41. package/src/cli/sync-fanout-process.ts +92 -0
  42. package/src/cli/sync-fanout.ts +150 -0
  43. package/src/cli/sync-flags.ts +10 -0
  44. package/src/cli/sync-link-status.ts +39 -0
  45. package/src/cli/sync-update-guard.ts +18 -0
  46. package/src/client/connect.ts +31 -14
  47. package/src/client/link-home.ts +3 -2
  48. package/src/client/machine-listener.ts +3 -0
  49. package/src/client/restore-ownership.ts +19 -1
  50. package/src/client/runtime-restart.ts +12 -4
  51. package/src/client/runtime.ts +40 -11
  52. package/src/client/stop-routing.ts +62 -0
  53. package/src/client/sync-runtime.ts +65 -0
  54. package/src/clients/config-export.ts +32 -3
  55. package/src/codex/auth-context.ts +49 -103
  56. package/src/codex/catalog/antigravity-discovery.ts +16 -5
  57. package/src/codex/catalog/provider-models.ts +6 -8
  58. package/src/codex/forward-transport-headers.ts +35 -6
  59. package/src/codex/inject/config-toml.ts +88 -0
  60. package/src/codex/inject/multi-agent-v2.ts +30 -4
  61. package/src/codex/inject/plan.ts +34 -7
  62. package/src/codex/inject-coordination.ts +11 -0
  63. package/src/codex/inject.ts +18 -7
  64. package/src/codex/lineage.ts +13 -7
  65. package/src/codex/quota.ts +22 -6
  66. package/src/codex/request-owned-affinity-key.ts +11 -0
  67. package/src/codex/request-owned-affinity.ts +118 -0
  68. package/src/codex/request-owned-main-pin.ts +86 -0
  69. package/src/codex/role-capability.ts +52 -41
  70. package/src/codex/routing/active-account.ts +13 -5
  71. package/src/codex/routing/selection.ts +40 -1
  72. package/src/codex/routing/thread-affinity-store.ts +916 -0
  73. package/src/codex/routing/thread-affinity.ts +90 -12
  74. package/src/codex/toml-source-lines.ts +72 -13
  75. package/src/combos/failover.ts +6 -109
  76. package/src/combos/request.ts +2 -2
  77. package/src/combos/resolve.ts +29 -11
  78. package/src/config/process-state.ts +5 -0
  79. package/src/config/schema/leaf-validators.ts +1 -0
  80. package/src/generated/compatibility-version.json +433 -165
  81. package/src/images/loop.ts +2 -1
  82. package/src/lib/client-error-body.ts +184 -0
  83. package/src/lib/client-retry-after.ts +66 -0
  84. package/src/lib/config-ownership.ts +4 -0
  85. package/src/lib/context-overflow-verdict.ts +113 -0
  86. package/src/lib/desktop-cli-handoff.d.mts +1 -1
  87. package/src/lib/desktop-cli-handoff.mjs +11 -1
  88. package/src/lib/empty-tool-catalog.ts +25 -3
  89. package/src/lib/error-destination.ts +47 -0
  90. package/src/lib/failure-detail.ts +66 -0
  91. package/src/lib/model-identity.ts +44 -0
  92. package/src/lib/private-sqlite-path.ts +124 -0
  93. package/src/lib/response-service-tier.ts +17 -0
  94. package/src/lib/retry-after.ts +3 -0
  95. package/src/lib/spend-ledger-owner.ts +43 -4
  96. package/src/lib/upstream-condition.ts +142 -0
  97. package/src/lib/upstream-retry.ts +14 -11
  98. package/src/lib/windows-owner-acl.ts +13 -6
  99. package/src/link/remote-platform.ts +14 -0
  100. package/src/link/remote-windows.ts +51 -9
  101. package/src/link/ssh-argv.ts +63 -10
  102. package/src/oauth/generic-account-failover.ts +13 -11
  103. package/src/oauth/index.ts +36 -74
  104. package/src/oauth/oauth-errors.ts +67 -0
  105. package/src/oauth/store.ts +1 -1
  106. package/src/protocols/codecs/ollama.ts +197 -0
  107. package/src/protocols/encoders/adapter-events.ts +4 -0
  108. package/src/protocols/encoders/chat.ts +18 -10
  109. package/src/protocols/trace.ts +18 -0
  110. package/src/providers/fastwire.ts +3 -2
  111. package/src/providers/quota/anthropic-usage-windows.ts +13 -3
  112. package/src/providers/quota/vendor-probes-key.ts +60 -24
  113. package/src/providers/request-pacing.ts +3 -2
  114. package/src/responses/apply-patch-envelope.ts +45 -19
  115. package/src/responses/compaction-history-framing.ts +5 -1
  116. package/src/responses/freeform-wrapper-scan.ts +5 -3
  117. package/src/responses/progressive-freeform-input.ts +354 -45
  118. package/src/routing/fallback-policy.ts +3 -1
  119. package/src/server/admission-model-scope.ts +17 -6
  120. package/src/server/admitted-http-turn.ts +56 -0
  121. package/src/server/auth-cors.ts +5 -0
  122. package/src/server/chat-completions.ts +45 -20
  123. package/src/server/chat-native-sse.ts +52 -7
  124. package/src/server/chat-native.ts +60 -35
  125. package/src/server/claude-bridge-pool-session.ts +59 -0
  126. package/src/server/claude-messages.ts +51 -24
  127. package/src/server/context-history.ts +5 -1
  128. package/src/server/inbound-body-admission.ts +11 -4
  129. package/src/server/index/ollama-routes.ts +89 -0
  130. package/src/server/index/serve-options.ts +21 -4
  131. package/src/server/index/websocket-handler.ts +4 -2
  132. package/src/server/index.ts +6 -36
  133. package/src/server/inference/client-encoder-delivery.ts +4 -2
  134. package/src/server/json-serialized-bytes.ts +44 -0
  135. package/src/server/management/agent-settings-routes.ts +24 -21
  136. package/src/server/management/codex-cli-update-routes.ts +2 -1
  137. package/src/server/management/route-registry.ts +1 -1
  138. package/src/server/messages-native-scope.ts +2 -1
  139. package/src/server/messages-native-tool-guard.ts +1 -1
  140. package/src/server/messages-native.ts +12 -7
  141. package/src/server/messages-shared.ts +6 -2
  142. package/src/server/native-final-log.ts +93 -0
  143. package/src/server/ollama-inbound.ts +349 -0
  144. package/src/server/ollama-native-paths.ts +21 -0
  145. package/src/server/ollama-route-policy.ts +73 -0
  146. package/src/server/relay.ts +22 -3
  147. package/src/server/request-decompress.ts +4 -2
  148. package/src/server/request-log-failure-attribution.ts +22 -0
  149. package/src/server/request-log-failure-detail.ts +80 -0
  150. package/src/server/request-log-terminal-status.ts +4 -2
  151. package/src/server/request-log.ts +79 -42
  152. package/src/server/response-log-body.ts +6 -1
  153. package/src/server/responses/account-change-state.ts +17 -6
  154. package/src/server/responses/adapter-continuation.ts +9 -4
  155. package/src/server/responses/adapter-delivery.ts +5 -4
  156. package/src/server/responses/adapter-dispatch.ts +31 -30
  157. package/src/server/responses/anthropic-thinking-recovery.ts +3 -0
  158. package/src/server/responses/codex-auth-error.ts +19 -18
  159. package/src/server/responses/codex-ws-exchange.ts +11 -8
  160. package/src/server/responses/codex-ws-metadata.ts +94 -21
  161. package/src/server/responses/codex-ws-request.ts +3 -1
  162. package/src/server/responses/compact.ts +53 -23
  163. package/src/server/responses/compaction-recovery.ts +4 -2
  164. package/src/server/responses/compaction-routing.ts +9 -4
  165. package/src/server/responses/core-auth.ts +32 -14
  166. package/src/server/responses/core-codex-account.ts +17 -6
  167. package/src/server/responses/core-combo-failure.ts +5 -1
  168. package/src/server/responses/core-combo-native.ts +2 -1
  169. package/src/server/responses/core-combo.ts +41 -27
  170. package/src/server/responses/core-errors.ts +22 -20
  171. package/src/server/responses/core-lifetime.ts +6 -3
  172. package/src/server/responses/core-normalize.ts +1 -0
  173. package/src/server/responses/core-options.ts +7 -0
  174. package/src/server/responses/core-pipeline.ts +4 -3
  175. package/src/server/responses/fetch-helpers.ts +7 -1
  176. package/src/server/responses/input-admission.ts +28 -2
  177. package/src/server/responses/native-injection.ts +1 -1
  178. package/src/server/responses/native-response-json.ts +13 -4
  179. package/src/server/responses/native-response-output.ts +1 -2
  180. package/src/server/responses/non-replayable-error.ts +2 -1
  181. package/src/server/responses/pacing-overload.ts +3 -2
  182. package/src/server/responses/passthrough-delivery.ts +55 -14
  183. package/src/server/responses/passthrough-dispatch.ts +19 -17
  184. package/src/server/responses/passthrough-error.ts +9 -9
  185. package/src/server/responses/policy-fallback.ts +2 -1
  186. package/src/server/responses/request-prepare.ts +67 -48
  187. package/src/server/responses/request-transport.ts +35 -31
  188. package/src/server/responses/run-turn-execution.ts +6 -6
  189. package/src/server/responses/sidecar-execution.ts +16 -12
  190. package/src/server/responses/spend-storage-error.ts +2 -1
  191. package/src/server/responses/ws-upstream.ts +9 -0
  192. package/src/server/responses-custom-tool-repair.ts +14 -3
  193. package/src/server/responses-terminal-repair.ts +5 -2
  194. package/src/server/responses-undeclared-tool-guard.ts +39 -16
  195. package/src/server/safe-response-headers.ts +162 -13
  196. package/src/server/turn-state-handles.ts +164 -0
  197. package/src/server/workflow-refusal.ts +2 -1
  198. package/src/service/ownership-mutation-lease.d.mts +11 -2
  199. package/src/service/ownership-mutation-lease.mjs +53 -11
  200. package/src/types/config.ts +2 -0
  201. package/src/update/index.ts +133 -25
  202. package/src/update/npm-install.d.mts +8 -0
  203. package/src/update/npm-install.mjs +20 -1
  204. package/src/update/orchestrated-admission.d.mts +4 -0
  205. package/src/update/orchestrated-admission.mjs +12 -0
  206. package/src/update/orchestrated-arguments.d.mts +12 -0
  207. package/src/update/orchestrated-arguments.mjs +64 -0
  208. package/src/update/orchestrated-child.d.mts +12 -0
  209. package/src/update/orchestrated-child.mjs +70 -0
  210. package/src/update/orchestrated-entry.ts +234 -0
  211. package/src/update/orchestrated-identity-probe-entry.ts +20 -0
  212. package/src/update/orchestrated-identity.ts +53 -0
  213. package/src/update/orchestrated-live-identity.ts +48 -0
  214. package/src/update/orchestrated-node-driver.mjs +99 -0
  215. package/src/update/orchestrated-outcome.d.mts +21 -0
  216. package/src/update/orchestrated-outcome.mjs +40 -0
  217. package/src/update/orchestrated-plan.ts +49 -0
  218. package/src/update/orchestrated-pnpm.d.mts +8 -0
  219. package/src/update/orchestrated-pnpm.mjs +33 -0
  220. package/src/update/orchestrated-session.d.mts +37 -0
  221. package/src/update/orchestrated-session.mjs +264 -0
  222. package/src/update/orchestrated-token.d.mts +10 -0
  223. package/src/update/orchestrated-token.mjs +21 -0
  224. package/src/update/orchestrated-token.ts +3 -0
  225. package/src/update/orchestrated-tree.d.mts +1 -0
  226. package/src/update/orchestrated-tree.mjs +14 -0
  227. package/src/update/pnpm-global-install.d.mts +6 -0
  228. package/src/update/pnpm-global-install.mjs +9 -2
  229. package/src/update/posix-install-supervisor-entry.mjs +6 -0
  230. package/src/update/posix-install-supervisor.d.mts +10 -0
  231. package/src/update/posix-install-supervisor.mjs +88 -0
  232. package/src/update/sync-update-mutex.d.mts +10 -0
  233. package/src/update/sync-update-mutex.mjs +164 -0
  234. package/src/update/sync-update-mutex.ts +1 -0
  235. package/src/update/test-home-guard.mjs +33 -0
  236. package/src/update/transactional-install.mjs +2 -2
  237. package/src/usage/error-detail.ts +225 -0
  238. package/src/usage/log.ts +60 -27
  239. package/src/web-search/loop.ts +31 -5
  240. package/gui/dist/assets/index-ebuVUtB7.js +0 -94
@@ -5,8 +5,9 @@ import { manualUpdateFailureGuidance } from "./update-failure-guidance.mjs";
5
5
  import { STOP_HISTORY_INCOMPLETE_EXIT_CODE } from "./stop-contract.mjs";
6
6
  import { proxyIdentityAt } from "../server/proxy-liveness";
7
7
  import { probeProxyLiveness } from "./proxy-liveness-probe.mjs";
8
+ import { verifyOrchestratedInstall } from "./orchestrated-tree.mjs";
8
9
  import { decidePostStopUpdate } from "./stop-decision.mjs";
9
- import { existsSync, readFileSync, readdirSync } from "node:fs";
10
+ import { existsSync, readFileSync, readdirSync, realpathSync } from "node:fs";
10
11
  import { fileURLToPath } from "node:url";
11
12
  import { dirname, join, resolve } from "node:path";
12
13
  import { getConfigDir, loadConfig } from "../config";
@@ -43,6 +44,11 @@ import { withoutSiblingMarker } from "../codex/sibling-start";
43
44
  import { packageVersion } from "../lib/package-version";
44
45
  import { isStandaloneModuleUrl } from "../lib/standalone";
45
46
  import { selfLaunchArgv } from "../lib/self-launch-argv";
47
+ import { createLegacyUpdateSession, createOrchestratedChildSession, decodeOrchestratedExpect } from "./orchestrated-session.mjs";
48
+ import { runPosixInstallerSync } from "./posix-install-supervisor.mjs";
49
+ import { runWindowsInstallerSync } from "./npm-install.mjs";
50
+ import { protectOrchestratedWorkerSignals } from "./orchestrated-child.mjs";
51
+ import type { OrchestratedChildArgs } from "./orchestrated-arguments.mjs";
46
52
  import { PNPM_READ_CWD, withPnpmCommandCwd, pnpmReadEnvironment } from "./pnpm-read-policy.mjs";
47
53
  import {
48
54
  freshServingPid, hasRestartableServiceManager, readParentPid, readServiceManagerPid, restartServiceManagerJob,
@@ -109,6 +115,7 @@ function runPnpmCandidate(
109
115
  args: readonly string[],
110
116
  capture = false,
111
117
  probeSpawn: typeof probeSpawnSync = probeSpawnSync,
118
+ probeEnv: NodeJS.ProcessEnv = process.env,
112
119
  ): { status: number | null; stdout?: string | null; stderr?: string | null } {
113
120
  const invocation = pnpmInvocationForPath(commandPath, args);
114
121
  if (!invocation) return { status: 1 };
@@ -118,7 +125,7 @@ function runPnpmCandidate(
118
125
  timeout: 20_000,
119
126
  windowsHide: true,
120
127
  cwd: PNPM_READ_CWD,
121
- env: pnpmReadEnvironment(unprivilegedOwnershipMutationEnvironment(process.env)),
128
+ env: pnpmReadEnvironment(unprivilegedOwnershipMutationEnvironment(probeEnv)),
122
129
  ...invocation.options,
123
130
  });
124
131
  }
@@ -126,7 +133,7 @@ function runPnpmCandidate(
126
133
  /** Resolve the exact pnpm executable/group/bin that own this package. */
127
134
  export function resolveCurrentPnpmGlobalOwner(
128
135
  invoked = process.argv[1],
129
- deps: { commandPaths?: readonly string[]; spawn?: typeof probeSpawnSync } = {},
136
+ deps: { commandPaths?: readonly string[]; spawn?: typeof probeSpawnSync; env?: NodeJS.ProcessEnv } = {},
130
137
  ): PnpmGlobalOwnerResult {
131
138
  const probeSpawn = deps.spawn ?? probeSpawnSync;
132
139
  return resolvePnpmGlobalOwner({
@@ -134,7 +141,7 @@ export function resolveCurrentPnpmGlobalOwner(
134
141
  packagePath: packageRoot(),
135
142
  commandPaths: deps.commandPaths ?? resolvePnpmCommands(),
136
143
  runningShimPath: runningPnpmShimPath(invoked),
137
- runPnpm: (commandPath, args, capture) => runPnpmCandidate(commandPath, args, capture, probeSpawn),
144
+ runPnpm: (commandPath, args, capture) => runPnpmCandidate(commandPath, args, capture, probeSpawn, deps.env),
138
145
  });
139
146
  }
140
147
 
@@ -159,10 +166,30 @@ export function runOwnedPnpm(
159
166
  stdio: "inherit" | "pipe" | "ignore" = capture ? "pipe" : "inherit",
160
167
  probeSpawn: typeof probeSpawnSync = probeSpawnSync,
161
168
  authorizeMutation: (kind: "package") => boolean = () => ["root", "bin", "list", "config", "view", "--version"].includes(args[0] ?? ""),
162
- ): { status: number | null; stdout?: string | null; stderr?: string | null } {
169
+ session?: Pick<ReturnType<typeof createOrchestratedChildSession>, "retainInstallerFence" | "noteUntrackedInstaller" | "confirmInstallerExit">,
170
+ markerPath = join(getConfigDir(), "update-orchestrated.json"),
171
+ ): { status: number | null; stdout?: string | null; stderr?: string | null; processTreeExited?: boolean } {
163
172
  const target = ownerPnpmTarget(owner, args);
164
173
  if (!target) return { status: 1 };
165
- return withPnpmCommandCwd(args, cwd => authorizeMutation("package") ? guardedSpawnSync(authorizeMutation, "package", target.bin, target.args, {
174
+ const mutating = ["add", "install", "update", "remove", "uninstall"].includes(args[0] ?? "");
175
+ try { return withPnpmCommandCwd(args, cwd => {
176
+ if (mutating && !capture && session && authorizeMutation("package")) {
177
+ const env = pnpmReadEnvironment(unprivilegedOwnershipMutationEnvironment(target.env));
178
+ if (process.platform === "win32") {
179
+ session.noteUntrackedInstaller();
180
+ const result = runWindowsInstallerSync({ file: target.bin, args: target.args, options: target.options }, { cwd, env, authorizeMutation });
181
+ if (result.processTreeExited && Number.isInteger(result.status)) session.confirmInstallerExit();
182
+ else { session.retainInstallerFence(); return { ...result, processTreeExited: false }; }
183
+ return result;
184
+ }
185
+ const result = runPosixInstallerSync({ file: target.bin, args: target.args, markerPath, cwd, env, authorizeMutation });
186
+ if (!Number.isInteger(result.status) || result.signal || !result.groupExited || result.groupKilled !== false || result.processTreeExited === false) {
187
+ session.retainInstallerFence();
188
+ return { ...result, processTreeExited: false };
189
+ }
190
+ return { ...result, processTreeExited: true };
191
+ }
192
+ const result = authorizeMutation("package") ? guardedSpawnSync(authorizeMutation, "package", target.bin, target.args, {
166
193
  stdio,
167
194
  encoding: "utf8",
168
195
  timeout: 180_000,
@@ -172,7 +199,10 @@ export function runOwnedPnpm(
172
199
  cwd,
173
200
  env: pnpmReadEnvironment(unprivilegedOwnershipMutationEnvironment(target.env)),
174
201
  ...target.options,
175
- }, probeSpawn) : { status: 1 });
202
+ }, probeSpawn) : { status: 1, signal: null };
203
+ if (mutating && (!Number.isInteger(result.status) || result.signal)) session?.retainInstallerFence();
204
+ return result;
205
+ }); } catch (error) { if (mutating) session?.retainInstallerFence(); throw error; }
176
206
  }
177
207
 
178
208
  /** Re-read the owning group's active package and return its verified launcher. */
@@ -221,9 +251,9 @@ function npmSpawnTarget(args: readonly string[]): SpawnTarget | null {
221
251
  return { bin: invocation.file, args: invocation.args, options: invocation.options };
222
252
  }
223
253
 
224
- function pnpmSpawnTarget(args: readonly string[], owner?: PnpmGlobalOwner): SpawnTarget | null {
254
+ function pnpmSpawnTarget(args: readonly string[], owner?: PnpmGlobalOwner, env?: NodeJS.ProcessEnv): SpawnTarget | null {
225
255
  if (owner) {
226
- const invocation = pnpmOwnerInvocation(owner, args);
256
+ const invocation = pnpmOwnerInvocation(owner, args, process.platform, env);
227
257
  if (!invocation) return null;
228
258
  return {
229
259
  bin: invocation.file,
@@ -241,19 +271,20 @@ export function registrySpawnTarget(
241
271
  installer: Installer,
242
272
  args: readonly string[],
243
273
  owner?: PnpmGlobalOwner,
274
+ env?: NodeJS.ProcessEnv,
244
275
  ): SpawnTarget | null {
245
276
  if (installer === "standalone") return null;
246
277
  // A pnpm command without an owner would silently fall back to the first PATH
247
278
  // candidate. That is unsafe when multiple PNPM_HOME installations expose the
248
279
  // same version, so registry queries use the same hard binding as mutation.
249
280
  return installer === "pnpm"
250
- ? owner ? pnpmSpawnTarget(args, owner) : null
281
+ ? owner ? pnpmSpawnTarget(args, owner, env) : null
251
282
  : npmSpawnTarget(args);
252
283
  }
253
284
 
254
- function selectedPnpmOwner(owner?: PnpmGlobalOwner): PnpmGlobalOwner | undefined {
285
+ function selectedPnpmOwner(owner?: PnpmGlobalOwner, probeSpawn?: typeof probeSpawnSync, env?: NodeJS.ProcessEnv): PnpmGlobalOwner | undefined {
255
286
  if (owner) return owner;
256
- const result = resolveCurrentPnpmGlobalOwner();
287
+ const result = resolveCurrentPnpmGlobalOwner(undefined, { spawn: probeSpawn, env });
257
288
  return result.ok ? result.owner : undefined;
258
289
  }
259
290
 
@@ -299,10 +330,11 @@ export function latestVersion(
299
330
  installer: Installer = detectInstall(),
300
331
  owner?: PnpmGlobalOwner,
301
332
  probeSpawn: typeof probeSpawnSync = probeSpawnSync,
333
+ probeEnv?: NodeJS.ProcessEnv,
302
334
  ): string | null {
303
- const resolvedOwner = installer === "pnpm" ? selectedPnpmOwner(owner) : undefined;
335
+ const resolvedOwner = installer === "pnpm" ? selectedPnpmOwner(owner, probeSpawn, probeEnv) : undefined;
304
336
  if (installer === "pnpm" && !resolvedOwner) return null;
305
- const manager = registrySpawnTarget(installer, ["view", `${PKG}@${tag}`, "version"], resolvedOwner);
337
+ const manager = registrySpawnTarget(installer, ["view", `${PKG}@${tag}`, "version"], resolvedOwner, probeEnv);
306
338
  if (!manager) return null;
307
339
  const r = probeSpawn(manager.bin, manager.args, {
308
340
  encoding: "utf8",
@@ -310,8 +342,8 @@ export function latestVersion(
310
342
  windowsHide: true,
311
343
  cwd: installer === "pnpm" ? PNPM_READ_CWD : undefined,
312
344
  env: installer === "pnpm"
313
- ? pnpmReadEnvironment(unprivilegedOwnershipMutationEnvironment(manager.env ?? process.env))
314
- : unprivilegedOwnershipMutationEnvironment(manager.env ?? process.env),
345
+ ? pnpmReadEnvironment(unprivilegedOwnershipMutationEnvironment(manager.env ?? probeEnv ?? process.env))
346
+ : unprivilegedOwnershipMutationEnvironment(manager.env ?? probeEnv ?? process.env),
315
347
  ...manager.options,
316
348
  });
317
349
  return r.status === 0 && typeof r.stdout === "string" ? (r.stdout.trim() || null) : null;
@@ -417,9 +449,35 @@ async function resolvedRuntimeOwnership(): Promise<RuntimeOwnershipObservation>
417
449
  * are updated in the Node bin launcher before Bun starts, so Windows does not replace the running
418
450
  * Bun binary.
419
451
  */
420
- export async function runUpdate(): Promise<void> {
452
+ export async function runUpdate(child?: Extract<OrchestratedChildArgs, { ok: true }>): Promise<void> {
453
+ let session: ReturnType<typeof createOrchestratedChildSession> | undefined;
454
+ if (child) {
455
+ try {
456
+ const expect = decodeOrchestratedExpect(child.expect);
457
+ session = createOrchestratedChildSession({ home: getConfigDir(), resultPath: child.resultPath, resultCapability: child.resultCapability, expect, notAfter: child.notAfter,
458
+ verifyIdentity: async () => (await import("./orchestrated-entry")).verifyOrchestratedChildIdentity(expect, child.version) });
459
+ if (!session.start().ok) { process.exitCode = 10; return; }
460
+ protectOrchestratedWorkerSignals();
461
+ } catch (error) {
462
+ console.error(`Orchestrated update preflight failed: ${error instanceof Error ? error.message : String(error)}`);
463
+ process.exitCode = 1;
464
+ return;
465
+ }
466
+ } else {
467
+ session = createLegacyUpdateSession({ home: getConfigDir() });
468
+ const started = session.start();
469
+ if (!started.ok) { console.error(`opencodex: ${started.error}`); process.exitCode = 1; return; }
470
+ process.once("exit", () => session?.finishPreflight());
471
+ }
472
+ try { await runUpdateWithSession(child, session); }
473
+ finally { session?.finishPreflight(); }
474
+ }
475
+
476
+ async function runUpdateWithSession(child: Extract<OrchestratedChildArgs, { ok: true }> | undefined,
477
+ session: ReturnType<typeof createOrchestratedChildSession> | undefined): Promise<void> {
421
478
  const ownership = detectInstallOwnership();
422
479
  const installer = ownership.installer;
480
+ if (child && installer !== "bun") { process.exitCode = 1; return; }
423
481
  const current = currentVersion();
424
482
  const tag = updateTag(current);
425
483
  console.log(`opencodex v${current} (installed via ${installer}, tag ${tag})`);
@@ -454,9 +512,10 @@ export async function runUpdate(): Promise<void> {
454
512
  process.exit(1);
455
513
  }
456
514
  const owner = ownerResult?.ok ? ownerResult.owner : undefined;
457
- const latest = latestVersion(tag, installer, owner);
515
+ const latest = child?.version ?? latestVersion(tag, installer, owner);
458
516
  if (latest && latest === current) {
459
517
  console.log(`Already on the latest ${tag} version (v${latest}).`);
518
+ if (child) process.exitCode = 1;
460
519
  return;
461
520
  }
462
521
 
@@ -465,6 +524,7 @@ export async function runUpdate(): Promise<void> {
465
524
  const integrity = checkUpdatePackageIntegrity(latest, probeSpawnSync, installer, owner);
466
525
  if (integrity.ok === false) {
467
526
  console.error(`⚠️ ${integrity.reason} — aborting the update before stopping the proxy.`);
527
+ if (child) { process.exitCode = 1; return; }
468
528
  process.exit(1);
469
529
  }
470
530
  if (integrity.ok === "skipped") {
@@ -487,11 +547,15 @@ export async function runUpdate(): Promise<void> {
487
547
  : updateSpawnTarget(bin, cmdArgs);
488
548
  if (!target) {
489
549
  console.error(`⚠️ Could not resolve ${bin} from a trusted absolute PATH entry; aborting before stopping the proxy.`);
550
+ if (child) { process.exitCode = 1; return; }
490
551
  process.exit(1);
491
552
  }
492
553
 
493
554
  const { serviceStatePaths } = await import("../service");
494
- const updateExitCode = await withUpdateOwnershipLease(serviceStatePaths(), async mutation => {
555
+ let mutationStarted = false, completed = false, installerUncertain = false, installedRoot: string | undefined;
556
+ let updateExitCode: number | undefined;
557
+ try {
558
+ updateExitCode = await withUpdateOwnershipLease(serviceStatePaths(), async mutation => {
495
559
  // Ownership inspection imports the service CLI, which reaches this update entry again.
496
560
  // Load it only after entering the lease; the policy itself stays a dependency-free import.
497
561
  const { inspectUpdateServiceHome } = await import("./service-home-authority");
@@ -519,6 +583,11 @@ export async function runUpdate(): Promise<void> {
519
583
  console.error("⚠️ Update stopped before tray handoff, runtime stop, or package replacement because runtime authority does not permit it.");
520
584
  return 1;
521
585
  }
586
+ if (session) {
587
+ const admission = await session.enterMutation();
588
+ if (!admission.ok) return 10;
589
+ mutationStarted = true;
590
+ }
522
591
  let trayWasInstalled = false;
523
592
  let trayWasRunning = false;
524
593
  if (!homePolicy.packageOnly && process.platform === "win32") {
@@ -869,6 +938,7 @@ export async function runUpdate(): Promise<void> {
869
938
  // Every post-update action below receives the verified active launcher.
870
939
  if (installer === "pnpm") {
871
940
  let update: ReturnType<typeof runPnpmGlobalUpdate>;
941
+ installerUncertain = true;
872
942
  try {
873
943
  if (!homePolicy.authorizeMutation("package")) return 1;
874
944
  update = runPnpmGlobalUpdate({
@@ -883,7 +953,7 @@ export async function runUpdate(): Promise<void> {
883
953
  args,
884
954
  capture,
885
955
  capture ? "pipe" : installStdio,
886
- probeSpawnSync, homePolicy.authorizeMutation,
956
+ probeSpawnSync, homePolicy.authorizeMutation, session,
887
957
  ) : { status: 1, stdout: "", stderr: "" },
888
958
  log: line => console.log(line),
889
959
  });
@@ -894,9 +964,12 @@ export async function runUpdate(): Promise<void> {
894
964
  ok: false,
895
965
  phase: "rollback",
896
966
  rolledBack: false,
967
+ processTreeExited: false,
897
968
  error: "pnpm update failed unexpectedly; active package could not be verified",
898
969
  };
970
+ session?.retainInstallerFence();
899
971
  }
972
+ installerUncertain = !update.ok && update.processTreeExited === false;
900
973
  if (update.ok) {
901
974
  postUpdateLauncher = join(update.path, "bin", "ocx.mjs");
902
975
  postUpdateLauncherUsable = true;
@@ -909,14 +982,35 @@ export async function runUpdate(): Promise<void> {
909
982
  }
910
983
  } else {
911
984
  if (!homePolicy.authorizeMutation("package")) return 1;
912
- r = guardedSpawnSync(homePolicy.authorizeMutation, "package", target.bin, target.args, {
985
+ installerUncertain = true;
986
+ if (session && process.platform === "win32") {
987
+ session.noteUntrackedInstaller();
988
+ const supervised = runWindowsInstallerSync({ file: target.bin, args: target.args, options: target.options }, {
989
+ env: mutation.unprivilegedEnvironment(), authorizeMutation: homePolicy.authorizeMutation,
990
+ });
991
+ if (supervised.processTreeExited === true && Number.isInteger(supervised.status)) session.confirmInstallerExit();
992
+ else session.retainInstallerFence();
993
+ r = supervised;
994
+ installerUncertain = supervised.processTreeExited !== true || !Number.isInteger(supervised.status);
995
+ } else if (session) {
996
+ try {
997
+ const supervised = runPosixInstallerSync({ file: target.bin, args: target.args,
998
+ markerPath: join(getConfigDir(), "update-orchestrated.json"),
999
+ authorizeMutation: homePolicy.authorizeMutation, env: mutation.unprivilegedEnvironment() });
1000
+ installerUncertain = !Number.isInteger(supervised.status) || Boolean(supervised.signal) || !supervised.groupExited || supervised.groupKilled !== false || supervised.processTreeExited === false;
1001
+ if (installerUncertain) session.retainInstallerFence();
1002
+ r = supervised;
1003
+ } catch (error) { session.retainInstallerFence(); throw error; }
1004
+ } else r = guardedSpawnSync(homePolicy.authorizeMutation, "package", target.bin, target.args, {
913
1005
  stdio: installStdio,
914
1006
  encoding: installStdio === "pipe" ? "utf8" : undefined,
915
- timeout: 180000,
1007
+ // The parent watchdog reports overrun without killing an active transaction.
1008
+ timeout: child ? undefined : 180000,
916
1009
  windowsHide: true,
917
1010
  ...target.options,
918
1011
  env: mutation.unprivilegedEnvironment(),
919
1012
  });
1013
+ if (!session) installerUncertain = r.status === null;
920
1014
  }
921
1015
  if (r && installStdio === "pipe") logSpawnOutput("", r);
922
1016
  }
@@ -932,6 +1026,11 @@ export async function runUpdate(): Promise<void> {
932
1026
  return 1;
933
1027
  }
934
1028
  if (!r) throw new Error("update replacement returned no result");
1029
+ if (installerUncertain) { console.error("Installer termination was not confirmed; update recovery is deferred."); return 1; }
1030
+ if (session && r.status === 0 && latest) {
1031
+ const root = realpathSync.native(packageRoot());
1032
+ if (verifyOrchestratedInstall(root, latest, "bun")) installedRoot = root;
1033
+ }
935
1034
  const postInstallPlan = planUpdateRuntimeHandling({
936
1035
  ...(await resolvedRuntimeOwnership()),
937
1036
  serviceInstalled: serviceWasInstalled,
@@ -1186,12 +1285,21 @@ export async function runUpdate(): Promise<void> {
1186
1285
  return 1;
1187
1286
  }
1188
1287
  } catch (error) {
1189
- await recoverStoppedRuntime("update failed unexpectedly");
1190
- if (trayWasRunning) {
1288
+ if (!installerUncertain) await recoverStoppedRuntime("update failed unexpectedly");
1289
+ if (trayWasRunning && !installerUncertain) {
1191
1290
  try { const { guardedStartWindowsTray } = await import("./guarded-tray-ops"); if (homePolicy.authorizeMutation("own-tray")) guardedStartWindowsTray(homePolicy.authorizeMutation); } catch { /* retain original failure */ }
1192
1291
  }
1193
1292
  throw error;
1194
1293
  }
1195
1294
  });
1196
- if (updateExitCode) process.exit(updateExitCode);
1295
+ completed = true;
1296
+ } finally {
1297
+ if (session && mutationStarted) session.finish(installedRoot
1298
+ ? { phase: "installed", activeRoot: installedRoot, ...(!completed || updateExitCode ? { recoveryFailed: true, error: "runtime-unhealthy" } : {}) }
1299
+ : { phase: "failed", error: installerUncertain ? "installer-timeout" : "update-failed", ...(installerUncertain ? { terminationConfirmed: false } : {}) });
1300
+ }
1301
+ if (updateExitCode) {
1302
+ if (child) process.exitCode = updateExitCode;
1303
+ else process.exit(updateExitCode);
1304
+ } else if (child && !mutationStarted) process.exitCode = 1;
1197
1305
  }
@@ -0,0 +1,8 @@
1
+ import type { NpmInvocation } from "./npm-invocation.mjs";
2
+
3
+ export declare function runWindowsInstallerSync(invocation: NpmInvocation, options?: {
4
+ env?: NodeJS.ProcessEnv;
5
+ cwd?: string;
6
+ timeoutMs?: number;
7
+ authorizeMutation?: (kind: "package") => boolean;
8
+ }): { status: number | null; processTreeExited: boolean };
@@ -1,12 +1,26 @@
1
1
  // Windows Node-launcher compatibility code. The install owns its entire process tree until
2
2
  // exit is proved; a timeout signal alone never authorizes stage removal.
3
- import { guardedSpawn, materializeMutationData } from "./mutation-guard.mjs";
3
+ import { guardedSpawn, guardedSpawnSync, materializeMutationData } from "./mutation-guard.mjs";
4
4
  import { dirname, join, win32 } from "node:path";
5
5
  import { fileURLToPath } from "node:url";
6
6
 
7
7
  const JOIN_MS = 10000;
8
8
  const failure = message => ({ status: null, processTreeExited: false, error: { code: "EINSTALLJOIN", message } });
9
9
 
10
+ /** Bridge synchronous pnpm transactions to the same Windows Job Object barrier. */
11
+ export function runWindowsInstallerSync(invocation, { env = process.env, cwd, timeoutMs = 180000, authorizeMutation = () => false } = {}) {
12
+ const moduleUrl = import.meta.url;
13
+ const script = `import {readFileSync} from 'node:fs';import {runNpmInstall} from ${JSON.stringify(moduleUrl)};const input=JSON.parse(readFileSync(0,'utf8'));console.log(JSON.stringify(await runNpmInstall(input.invocation,{timeoutMs:input.timeoutMs,authorizeMutation:()=>true})));`;
14
+ const result = guardedSpawnSync(authorizeMutation, "package", process.execPath, ["--input-type=module", "-e", script], {
15
+ input: JSON.stringify({ invocation, timeoutMs }), env, cwd, encoding: "utf8", windowsHide: true, stdio: ["pipe", "pipe", "inherit"],
16
+ });
17
+ try {
18
+ const value = JSON.parse(result.stdout);
19
+ if (result.status !== 0 || typeof value.processTreeExited !== "boolean") throw Error("invalid supervisor result");
20
+ return value;
21
+ } catch { return failure("Windows installer supervisor did not confirm process-tree exit"); }
22
+ }
23
+
10
24
  function quoteWindowsArg(value) {
11
25
  return '"' + value.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\*)$/, "$1$1") + '"';
12
26
  }
@@ -16,6 +30,11 @@ export async function runNpmInstall(invocation, { env = process.env, timeoutMs =
16
30
  env = materializeMutationData(env);
17
31
  if (!invocation) return { status: 1, processTreeExited: true, error: { code: "ENOENT", message: "npm invocation unavailable" } };
18
32
  if (process.platform === "win32") {
33
+ // The PowerShell helper assigns npm to a kill-on-close Job Object before it
34
+ // resumes the suspended process, then terminates the job on timeout and
35
+ // waits for the job to become empty. An unconfirmed join retains the stage.
36
+ // Windows acceptance still needs orchestrated npm and pnpm worker tests proving
37
+ // marker visibility across supervisor failure and Job Object termination.
19
38
  // Resolve from the same absolute system directory as the hardened cmd hop.
20
39
  // Never search PATH for PowerShell, and never interpolate the JSON as code.
21
40
  const roots = new Set(Object.entries(env).filter(([key, value]) => key.toLowerCase() === "systemroot" && value !== undefined).map(([, value]) => value));
@@ -0,0 +1,4 @@
1
+ import type { observeOrchestratedPlan } from "./orchestrated-entry";
2
+ import type { OrchestratedUpdateArgs } from "./orchestrated-arguments.mjs";
3
+ export declare function decideOrchestratedApply(plan: Awaited<ReturnType<typeof observeOrchestratedPlan>>, request: Extract<OrchestratedUpdateArgs, { ok: true }>, now: number):
4
+ | { kind: "proceed" } | { kind: "done"; exitCode: 0 | 10; result: { schema: "ocx.update.result/1"; applied: boolean; fromVersion: string; toVersion: string | null; installer: string; restarted: boolean; healthy: boolean; rolledBack: boolean; error?: string } };
@@ -0,0 +1,12 @@
1
+ /** Resolve decisions that require no mutation before starting an update worker. */
2
+ export function decideOrchestratedApply(plan, request, now) {
3
+ const result = { schema: "ocx.update.result/1", applied: false, fromVersion: plan.currentVersion,
4
+ toVersion: plan.targetVersion, installer: plan.installer, restarted: false, healthy: false, rolledBack: false };
5
+ const refuse = error => ({ kind: "done", exitCode: 10, result: { ...result, error } });
6
+ if (request.expectPlan && request.expectPlan !== plan.planToken) return refuse("plan-changed");
7
+ if (request.notAfter !== undefined && now > request.notAfter) return refuse("deadline-passed");
8
+ if (plan.updateInFlight) return refuse("update-in-flight");
9
+ if (plan.reason === "up-to-date") return { kind: "done", exitCode: 0, result };
10
+ if (!plan.canApply) return refuse(plan.reason ?? "plan-unavailable");
11
+ return { kind: "proceed" };
12
+ }
@@ -0,0 +1,12 @@
1
+ export type OrchestratedUpdateArgs = { ok: false } | {
2
+ ok: true;
3
+ mode: "plan" | "apply";
4
+ tag?: "latest" | "preview";
5
+ version?: string;
6
+ expectPlan?: string;
7
+ notAfter?: number;
8
+ };
9
+ export declare function parseOrchestratedUpdateArgs(argv: readonly string[]): OrchestratedUpdateArgs;
10
+ export declare function isOrchestratedUpdateArgv(argv: readonly string[]): boolean;
11
+ export type OrchestratedChildArgs = { ok: false } | { ok: true; version: string; expect: string; resultPath: string; resultCapability: string; notAfter?: number };
12
+ export declare function parseOrchestratedChildArgs(argv: readonly string[], env: Record<string, string | undefined>): OrchestratedChildArgs;
@@ -0,0 +1,64 @@
1
+ const CORE = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z.-]+))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/;
2
+
3
+ export function isOrchestratedUpdateArgv(argv) {
4
+ return argv.some(arg => /^(--plan|--yes|--json|--expect-plan|--not-after|--orchestrated-expect|--orchestrated-result)(?:=|$)/.test(arg));
5
+ }
6
+
7
+ /**
8
+ * Internal child grammar is accepted only in the explicitly marked child process, with its result capability.
9
+ * The capability is taken out of env on every call, so no subprocess started afterwards inherits it.
10
+ */
11
+ export function parseOrchestratedChildArgs(argv, env) {
12
+ const resultCapability = env.OCX_UPDATE_RESULT_CAPABILITY;
13
+ delete env.OCX_UPDATE_RESULT_CAPABILITY;
14
+ if (env.OCX_UPDATE_ORCHESTRATED_CHILD !== "1") return { ok: false };
15
+ if (typeof resultCapability !== "string" || !/^[A-Za-z0-9_-]{43}$/.test(resultCapability)) return { ok: false };
16
+ const values = new Map();
17
+ const allowed = new Set(["--version", "--orchestrated-expect", "--orchestrated-result", "--not-after"]);
18
+ for (let i = 0; i < argv.length; i++) {
19
+ const flag = argv[i], value = argv[++i];
20
+ if (!allowed.has(flag) || values.has(flag) || !value || value.startsWith("-")) return { ok: false };
21
+ values.set(flag, value);
22
+ }
23
+ const version = values.get("--version"), expect = values.get("--orchestrated-expect"), resultPath = values.get("--orchestrated-result"), deadline = values.get("--not-after");
24
+ if (!version || !strictSemver(version) || !expect || !resultPath || (deadline !== undefined
25
+ && (!/^\d+$/.test(deadline) || !Number.isSafeInteger(Number(deadline)) || Number(deadline) <= 0))) return { ok: false };
26
+ return { ok: true, version, expect, resultPath, resultCapability, ...(deadline === undefined ? {} : { notAfter: Number(deadline) }) };
27
+ }
28
+
29
+ function strictSemver(value) {
30
+ if (value.length > 128) return false;
31
+ const match = CORE.exec(value);
32
+ return Boolean(match && (match[4] === undefined || match[4].split(".").every(part =>
33
+ part.length > 0 && /^[0-9A-Za-z-]+$/.test(part) && (!/^\d+$/.test(part) || /^(0|[1-9]\d*)$/.test(part)))));
34
+ }
35
+
36
+ /** Parse only the public orchestrated grammar; callers map an invalid result to exit 64. */
37
+ export function parseOrchestratedUpdateArgs(argv) {
38
+ const flags = new Map();
39
+ const switches = new Set(["--plan", "--yes", "--json"]);
40
+ const values = new Set(["--tag", "--version", "--expect-plan", "--not-after"]);
41
+ for (let i = 0; i < argv.length; i++) {
42
+ const arg = argv[i];
43
+ if (switches.has(arg)) {
44
+ if (flags.has(arg)) return { ok: false };
45
+ flags.set(arg, true);
46
+ } else if (values.has(arg)) {
47
+ if (flags.has(arg) || i + 1 >= argv.length || argv[i + 1].startsWith("-")) return { ok: false };
48
+ flags.set(arg, argv[++i]);
49
+ } else return { ok: false };
50
+ }
51
+ const plan = flags.has("--plan"), apply = flags.has("--yes");
52
+ if (plan === apply || !flags.has("--json")) return { ok: false };
53
+ if (flags.has("--tag") && flags.has("--version")) return { ok: false };
54
+ const tag = flags.get("--tag"), version = flags.get("--version");
55
+ if (tag !== undefined && tag !== "latest" && tag !== "preview") return { ok: false };
56
+ if (version !== undefined && !strictSemver(version)) return { ok: false };
57
+ const expectPlan = flags.get("--expect-plan"), deadline = flags.get("--not-after");
58
+ if (plan && (expectPlan !== undefined || deadline !== undefined)) return { ok: false };
59
+ if (expectPlan !== undefined && !/^[A-Za-z0-9_-]{16,128}$/.test(expectPlan)) return { ok: false };
60
+ if (deadline !== undefined && (!/^\d+$/.test(deadline) || !Number.isSafeInteger(Number(deadline)) || Number(deadline) <= 0)) return { ok: false };
61
+ return { ok: true, mode: plan ? "plan" : "apply", ...(tag === undefined ? {} : { tag }),
62
+ ...(version === undefined ? {} : { version }), ...(expectPlan === undefined ? {} : { expectPlan }),
63
+ ...(deadline === undefined ? {} : { notAfter: Number(deadline) }) };
64
+ }
@@ -0,0 +1,12 @@
1
+ import type { ChildProcess } from "node:child_process";
2
+ import type { EventEmitter } from "node:events";
3
+
4
+ export declare function protectOrchestratedWorkerSignals(): void;
5
+
6
+ export declare function waitForOrchestratedChild(child: ChildProcess, options?: {
7
+ signals?: EventEmitter;
8
+ timeoutMs?: number;
9
+ overrunMs?: number;
10
+ setTimer?: (callback: () => void, timeoutMs: number) => unknown;
11
+ clearTimer?: (timer: unknown) => void;
12
+ }): Promise<{ confirmed: boolean; code: number | null; signal: NodeJS.Signals | null; reason?: "overrun" }>;
@@ -0,0 +1,70 @@
1
+ const SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
2
+
3
+ /** Keep a worker alive until its synchronous installer and recovery finish. */
4
+ export function protectOrchestratedWorkerSignals() {
5
+ for (const signal of process.platform === "win32" ? SIGNALS.slice(0, 2) : SIGNALS) process.on(signal, () => {});
6
+ }
7
+
8
+ /** Forward catchable signals and require a close event within 60 seconds after interruption. */
9
+ export function waitForOrchestratedChild(child, options = {}) {
10
+ const signals = options.signals ?? process;
11
+ const startTimer = options.setTimer ?? setTimeout;
12
+ const stopTimer = options.clearTimer ?? clearTimeout;
13
+ const timeoutMs = options.timeoutMs ?? 60_000;
14
+ return new Promise(resolve => {
15
+ let timer;
16
+ let overrunTimer;
17
+ let settled = false;
18
+ const handlers = new Map();
19
+ const cleanupSignals = () => {
20
+ for (const [signal, handler] of handlers) signals.removeListener(signal, handler);
21
+ if (timer !== undefined) stopTimer(timer);
22
+ if (overrunTimer !== undefined) stopTimer(overrunTimer);
23
+ };
24
+ const onClose = (code, signal) => {
25
+ child.removeListener("error", onError);
26
+ if (settled) return;
27
+ settled = true;
28
+ cleanupSignals();
29
+ resolve({ confirmed: true, code, signal });
30
+ };
31
+ const armTimer = () => {
32
+ if (timer !== undefined) return;
33
+ timer = startTimer(() => {
34
+ if (settled) return;
35
+ settled = true;
36
+ cleanupSignals();
37
+ // Keep the child listeners until close: a late error must not become unhandled.
38
+ resolve({ confirmed: false, code: null, signal: null });
39
+ }, timeoutMs);
40
+ };
41
+ const onError = () => armTimer();
42
+ child.once("close", onClose);
43
+ child.on("error", onError);
44
+ for (const signal of SIGNALS) {
45
+ const handler = () => {
46
+ armTimer();
47
+ try { child.kill(signal); } catch { /* Wait for close or return uncertainty. */ }
48
+ };
49
+ handlers.set(signal, handler);
50
+ signals.on(signal, handler);
51
+ }
52
+ if (options.overrunMs !== undefined) {
53
+ let remaining = Math.max(0, options.overrunMs);
54
+ const schedule = () => {
55
+ const delay = Math.min(remaining, 2_147_483_647);
56
+ overrunTimer = startTimer(() => {
57
+ if (settled) return;
58
+ remaining -= delay;
59
+ if (remaining > 0) { schedule(); return; }
60
+ settled = true;
61
+ cleanupSignals();
62
+ // Do not signal a transaction in progress. The caller must detach its
63
+ // handles and leave the child's in-flight marker intact.
64
+ resolve({ confirmed: false, code: null, signal: null, reason: "overrun" });
65
+ }, delay);
66
+ };
67
+ schedule();
68
+ }
69
+ });
70
+ }