@bitkyc08/opencodex 2.100.2 → 2.100.3

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 (561) hide show
  1. package/README.md +1 -1
  2. package/bin/ocx.mjs +32 -18
  3. package/gui/dist/assets/{App-COo8Yopd.css → App-BGP8I0V4.css} +1 -1
  4. package/gui/dist/assets/App-Dnb6VMsP.js +59 -0
  5. package/gui/dist/assets/{Tray-BcaI-VCr.js → Tray-BV4ms9U9.js} +1 -1
  6. package/gui/dist/assets/{brand-mark-DU-0Vdkr.js → brand-mark-XOLJbomA.js} +1 -1
  7. package/gui/dist/assets/index-DCdXsMyZ.js +105 -0
  8. package/gui/dist/assets/{index-DJEkIDAi.css → index-DQtCRNAw.css} +1 -1
  9. package/gui/dist/assets/{segment-thumb-features-e9A_FogJ.js → segment-thumb-features-DXSidY6D.js} +1 -1
  10. package/gui/dist/classic/assets/App-DA-scMPq.js +58 -0
  11. package/gui/dist/classic/assets/{Tray-DT146AhS.js → Tray-BrHaVRAq.js} +1 -1
  12. package/gui/dist/classic/assets/index-BqOaGLf5.js +105 -0
  13. package/gui/dist/classic/assets/{quota-summary-CakPe9Ni.js → quota-summary-Dy5_wfTT.js} +1 -1
  14. package/gui/dist/classic/index.html +1 -1
  15. package/gui/dist/index.html +2 -2
  16. package/native/ocx-child/Cargo.toml +9 -0
  17. package/native/ocx-child/src/cli.rs +402 -20
  18. package/native/ocx-child/src/codex_home.rs +98 -14
  19. package/native/ocx-child/src/daemon.rs +2 -1
  20. package/native/ocx-child/src/lib.rs +3 -0
  21. package/native/ocx-child/src/link_ws.rs +2598 -0
  22. package/native/ocx-child/src/link_ws_advert.rs +346 -0
  23. package/native/ocx-child/src/link_ws_frame.rs +749 -0
  24. package/native/ocx-child/src/parity.rs +5 -1
  25. package/native/ocx-child/src/platform.rs +152 -6
  26. package/native/ocx-child/src/relay.rs +150 -19
  27. package/package.json +3 -3
  28. package/src/adapters/anthropic/advisor-tool.ts +176 -0
  29. package/src/adapters/anthropic/beta-body-pairs.ts +6 -0
  30. package/src/adapters/anthropic/client-identity.ts +3 -1
  31. package/src/adapters/anthropic/passthrough.ts +9 -3
  32. package/src/adapters/anthropic.ts +31 -14
  33. package/src/adapters/client-fingerprint.ts +3 -3
  34. package/src/adapters/cursor/discovery.ts +17 -0
  35. package/src/adapters/cursor/native-exec-desktop.ts +2 -1
  36. package/src/adapters/cursor/native-exec-shell.ts +2 -1
  37. package/src/adapters/cursor/protobuf-request.ts +8 -8
  38. package/src/adapters/cursor.ts +7 -6
  39. package/src/adapters/google-antigravity-wire.ts +7 -5
  40. package/src/adapters/google-wire-compiler.ts +2 -2
  41. package/src/adapters/google.ts +9 -2
  42. package/src/adapters/kiro/payload.ts +7 -4
  43. package/src/adapters/kiro/reasoning.ts +44 -1
  44. package/src/adapters/kiro/structured-output.ts +10 -8
  45. package/src/adapters/kiro-tools.ts +61 -15
  46. package/src/adapters/openai-chat/destination-policy.ts +16 -0
  47. package/src/adapters/openai-chat/reasoning-replay.ts +4 -1
  48. package/src/adapters/zed.ts +3 -0
  49. package/src/advisor/consult.ts +15 -4
  50. package/src/advisor/context.ts +12 -3
  51. package/src/advisor/runtime.ts +35 -5
  52. package/src/advisor/settings.ts +8 -0
  53. package/src/advisor/synthetic-tool.ts +21 -8
  54. package/src/bridge/response-json.ts +11 -2
  55. package/src/bridge/sse.ts +43 -8
  56. package/src/claude/auth-detect.ts +21 -33
  57. package/src/claude/desktop-3p.ts +11 -5
  58. package/src/claude/desktop-gateway-state.ts +2 -0
  59. package/src/claude/desktop-remote-store-artifact.ts +14 -3
  60. package/src/claude/desktop-remote-store.ts +24 -4
  61. package/src/claude/inbound-content-options.ts +31 -16
  62. package/src/claude/outbound.ts +13 -3
  63. package/src/cli/account-api.ts +17 -1
  64. package/src/cli/account-auth.ts +54 -21
  65. package/src/cli/account-key-quota.ts +34 -5
  66. package/src/cli/account.ts +4 -2
  67. package/src/cli/advisor.ts +7 -4
  68. package/src/cli/alias.ts +38 -1
  69. package/src/cli/capabilities-access-remote.ts +128 -3
  70. package/src/cli/capabilities-accounts.ts +3 -3
  71. package/src/cli/capabilities-agents-routing.ts +17 -10
  72. package/src/cli/capabilities-base.ts +41 -16
  73. package/src/cli/capabilities-integrations.ts +2 -2
  74. package/src/cli/capabilities-provider-models.ts +18 -2
  75. package/src/cli/capabilities-route-to.ts +43 -0
  76. package/src/cli/capabilities.ts +2 -0
  77. package/src/cli/capability-contracts.ts +1 -1
  78. package/src/cli/claude-desktop.ts +30 -11
  79. package/src/cli/claude.ts +17 -3
  80. package/src/cli/codex-launcher.ts +3 -1
  81. package/src/cli/codex-shim-autorestore.ts +5 -42
  82. package/src/cli/config-command.ts +14 -1
  83. package/src/cli/config-root-startup.ts +34 -0
  84. package/src/cli/connect.ts +88 -16
  85. package/src/cli/desktop-runtime-guidance.ts +1 -1
  86. package/src/cli/disconnect-runtime.ts +168 -0
  87. package/src/cli/dispatch.ts +54 -12
  88. package/src/cli/export-command.ts +1 -1
  89. package/src/cli/gui-pair-client.ts +6 -3
  90. package/src/cli/gui.ts +10 -5
  91. package/src/cli/help-catalog.ts +11 -0
  92. package/src/cli/help.ts +4 -3
  93. package/src/cli/index.ts +83 -92
  94. package/src/cli/inspect.ts +11 -2
  95. package/src/cli/integrations.ts +26 -1
  96. package/src/cli/link-capture.ts +64 -0
  97. package/src/cli/link-child-ops.ts +218 -40
  98. package/src/cli/link-cleanup.ts +8 -5
  99. package/src/cli/link-diagnostics.ts +67 -0
  100. package/src/cli/link-enrollment.ts +158 -12
  101. package/src/cli/link-operations.ts +52 -0
  102. package/src/cli/link-recover.ts +152 -0
  103. package/src/cli/link-routes.ts +87 -0
  104. package/src/cli/link-status-child.ts +44 -1
  105. package/src/cli/link-status-traffic.ts +34 -0
  106. package/src/cli/link.ts +314 -37
  107. package/src/cli/message-command.ts +1 -1
  108. package/src/cli/message-mcp-command.ts +23 -10
  109. package/src/cli/models-runtime.ts +3 -3
  110. package/src/cli/opencode.ts +3 -1
  111. package/src/cli/pi-sync.ts +35 -0
  112. package/src/cli/preflight-exemptions.ts +46 -0
  113. package/src/cli/registry.ts +28 -12
  114. package/src/cli/restart-failure.ts +5 -2
  115. package/src/cli/root.ts +5 -1
  116. package/src/cli/route-to.ts +172 -0
  117. package/src/cli/runtime-api.ts +5 -8
  118. package/src/cli/status.ts +3 -1
  119. package/src/cli/stop-approval.ts +66 -19
  120. package/src/cli/stop-report.ts +23 -0
  121. package/src/cli/stop-windows-checked.ts +304 -0
  122. package/src/cli/sync-command.ts +70 -15
  123. package/src/cli/sync-fanout.ts +74 -19
  124. package/src/cli/sync-flags.ts +40 -3
  125. package/src/cli/sync-link-status.ts +18 -2
  126. package/src/cli/sync-update-guard.ts +7 -2
  127. package/src/cli/system-restart-client.ts +3 -2
  128. package/src/cli/uninstall-plan.ts +77 -5
  129. package/src/cli/uninstall-stop.ts +152 -0
  130. package/src/cli/v2-input.ts +10 -6
  131. package/src/cli/v2-local-output.ts +3 -2
  132. package/src/cli/v2-runtime.ts +10 -3
  133. package/src/cli/v2.ts +22 -7
  134. package/src/client/connect.ts +321 -34
  135. package/src/client/link-home-features.ts +27 -0
  136. package/src/client/link-home.ts +92 -4
  137. package/src/client/link-ingress.ts +21 -3
  138. package/src/client/link-join.ts +12 -2
  139. package/src/client/link-parity-reporter.ts +60 -6
  140. package/src/client/link-relay-transport.ts +161 -36
  141. package/src/client/link-relay.ts +150 -6
  142. package/src/client/link-request-compression.ts +84 -0
  143. package/src/client/link-state.ts +11 -5
  144. package/src/client/link-status.ts +39 -1
  145. package/src/client/link-teardown.ts +1 -0
  146. package/src/client/link-tunnel.ts +56 -5
  147. package/src/client/link-websocket-limits.ts +89 -0
  148. package/src/client/link-websocket.ts +586 -0
  149. package/src/client/link-ws-advertisement.ts +100 -0
  150. package/src/client/link-ws-framer.ts +241 -0
  151. package/src/client/link-ws-transport.ts +177 -0
  152. package/src/client/machine-api.ts +13 -2
  153. package/src/client/machine-listener.ts +48 -7
  154. package/src/client/route-intent-apply.ts +293 -0
  155. package/src/client/route-intent-file-originals.ts +97 -0
  156. package/src/client/route-intent-native-originals.ts +201 -0
  157. package/src/client/route-intent-watch.ts +141 -0
  158. package/src/client/runtime-restart.ts +127 -5
  159. package/src/client/runtime.ts +61 -15
  160. package/src/client/state.ts +30 -0
  161. package/src/client/sync-expectation.ts +36 -2
  162. package/src/client/sync-runtime.ts +7 -0
  163. package/src/clients/config-export/alias-selectors.ts +63 -40
  164. package/src/clients/config-export/contracts.ts +2 -0
  165. package/src/clients/config-export/nested-selectors.ts +42 -0
  166. package/src/clients/config-export.ts +22 -3
  167. package/src/codex/account-store.ts +12 -3
  168. package/src/codex/account-usability.ts +13 -0
  169. package/src/codex/auth-api/account-list.ts +29 -3
  170. package/src/codex/auth-collision.ts +23 -22
  171. package/src/codex/auth-context.ts +21 -6
  172. package/src/codex/catalog/gather-capture.ts +8 -2
  173. package/src/codex/catalog/parsing.ts +7 -3
  174. package/src/codex/catalog/provider-models.ts +54 -15
  175. package/src/codex/catalog/retained-sync.ts +2 -1
  176. package/src/codex/catalog/routed-gather.ts +1 -1
  177. package/src/codex/catalog-auto-refresh.ts +11 -0
  178. package/src/codex/cli-update-job.ts +35 -13
  179. package/src/codex/convergence.ts +2 -2
  180. package/src/codex/desktop-compatibility/native-identity.ts +4 -8
  181. package/src/codex/features.ts +2 -2
  182. package/src/codex/history-provider.ts +31 -0
  183. package/src/codex/inject/multi-agent-v2.ts +9 -3
  184. package/src/codex/inject/paginated-openai-compat.ts +54 -1
  185. package/src/codex/inject/plan.ts +20 -2
  186. package/src/codex/inject.ts +2 -0
  187. package/src/codex/journal-config-restore.ts +217 -0
  188. package/src/codex/journal.ts +75 -6
  189. package/src/codex/main-account.ts +23 -30
  190. package/src/codex/native-main-auth-file.ts +104 -0
  191. package/src/codex/native-profile-manager.ts +4 -3
  192. package/src/codex/native-profile-store.ts +3 -61
  193. package/src/codex/orca-import.ts +10 -1
  194. package/src/codex/quota-history.ts +13 -0
  195. package/src/codex/quota-window-conflict.ts +103 -0
  196. package/src/codex/quota.ts +23 -1
  197. package/src/codex/subagent-model-fallback.ts +3 -1
  198. package/src/codex/websocket-activity.ts +171 -16
  199. package/src/codex/websocket-registry.ts +11 -4
  200. package/src/combos/cooldown-store.ts +25 -5
  201. package/src/combos/failover.ts +330 -2
  202. package/src/config/dashboard-trusted-proxy.ts +83 -0
  203. package/src/config/diagnostics.ts +28 -0
  204. package/src/config/feature-flags.ts +9 -0
  205. package/src/config/live-reconcile.ts +10 -1
  206. package/src/config/load-degrade.ts +12 -1
  207. package/src/config/multi-agent-surface.ts +28 -5
  208. package/src/config/pending-teardown.ts +60 -3
  209. package/src/config/process-state.ts +175 -4
  210. package/src/config/provider-validation.ts +4 -4
  211. package/src/config/schema/config-schema.ts +6 -0
  212. package/src/config/schema/leaf-validators.ts +9 -2
  213. package/src/config/windows-process-command-line.ts +107 -0
  214. package/src/generated/compatibility-version.json +948 -392
  215. package/src/generated/model-metadata.ts +1 -1
  216. package/src/images/loop.ts +3 -0
  217. package/src/integrations/model-name-guard.ts +25 -0
  218. package/src/integrations/route-intent-catalog.ts +26 -0
  219. package/src/integrations/route-intent-connected.ts +262 -0
  220. package/src/integrations/route-intent-contract.ts +55 -0
  221. package/src/integrations/route-intent-disconnect.ts +109 -0
  222. package/src/integrations/route-intent-initial.ts +64 -0
  223. package/src/integrations/route-intent-state.ts +117 -0
  224. package/src/integrations/route-intent-tick.ts +65 -0
  225. package/src/integrations/route-intent.ts +212 -0
  226. package/src/integrations/writer.ts +44 -11
  227. package/src/lib/client-retry-after.ts +29 -0
  228. package/src/lib/config-ownership.ts +13 -0
  229. package/src/lib/desktop-gui-origin.ts +28 -0
  230. package/src/lib/errors.ts +1 -1
  231. package/src/lib/gui-pair-capability.ts +2 -1
  232. package/src/lib/messages-error-body.ts +4 -1
  233. package/src/lib/outbound-credential-registry.ts +362 -4
  234. package/src/lib/paced-stream.ts +34 -0
  235. package/src/lib/passive-key-fetch-proof.ts +30 -0
  236. package/src/lib/passive-read.ts +5 -0
  237. package/src/lib/process-control.ts +76 -12
  238. package/src/lib/redact.ts +84 -8
  239. package/src/lib/state-store-registrations.ts +11 -0
  240. package/src/lib/state-store-sweeper.ts +4 -0
  241. package/src/lib/supervisor-markers.ts +18 -0
  242. package/src/lib/terminal-safe-text.ts +58 -0
  243. package/src/lib/translator-budget.ts +3 -2
  244. package/src/lib/upstream-retry.ts +14 -4
  245. package/src/link/alias-lock.ts +119 -0
  246. package/src/link/child-activity.ts +28 -2
  247. package/src/link/child-binary-cache-fill.d.mts +50 -0
  248. package/src/link/child-binary-cache-fill.mjs +494 -0
  249. package/src/link/child-binary-cache-start.ts +73 -0
  250. package/src/link/child-binary-source.ts +12 -5
  251. package/src/link/child-gated-ocx.ts +29 -11
  252. package/src/link/child-observations.ts +2 -1
  253. package/src/link/child-observe.ts +2 -2
  254. package/src/link/child-ops-engine.ts +159 -91
  255. package/src/link/child-ops-host.ts +138 -0
  256. package/src/link/child-ops-runners.ts +319 -0
  257. package/src/link/child-ops-scheduler.ts +207 -0
  258. package/src/link/child-ops-types.ts +89 -0
  259. package/src/link/child-parity.ts +23 -4
  260. package/src/link/child-policy.ts +93 -0
  261. package/src/link/child-update-contract.ts +12 -3
  262. package/src/link/codex-settings.ts +1 -1
  263. package/src/link/compatibility.ts +18 -1
  264. package/src/link/diagnostics-read.ts +163 -0
  265. package/src/link/diagnostics.ts +20 -7
  266. package/src/link/explicit-route.ts +209 -0
  267. package/src/link/link-recover.ts +113 -0
  268. package/src/link/management-routes.ts +3 -1
  269. package/src/link/operation-recovery-slot.ts +44 -0
  270. package/src/link/operations-journal.ts +408 -0
  271. package/src/link/peer-report.ts +1 -1
  272. package/src/link/relay-auth.ts +14 -0
  273. package/src/link/remote-plant.ts +152 -14
  274. package/src/link/remote-platform.ts +21 -10
  275. package/src/link/remote-probe.ts +11 -3
  276. package/src/link/remote-windows.ts +50 -10
  277. package/src/link/request-compression.ts +30 -0
  278. package/src/link/residual-recovery.ts +54 -0
  279. package/src/link/retirement.ts +128 -0
  280. package/src/link/route-intent-watch.ts +41 -0
  281. package/src/link/route-intent.ts +209 -0
  282. package/src/link/route-proof.ts +82 -0
  283. package/src/link/route-rounds.ts +579 -0
  284. package/src/link/route-select.ts +95 -0
  285. package/src/link/route-trust.ts +96 -0
  286. package/src/link/ssh-argv.ts +172 -24
  287. package/src/link/ssh-capture-redact.ts +253 -0
  288. package/src/link/ssh-capture.ts +497 -0
  289. package/src/link/ssh-runner.ts +141 -14
  290. package/src/link/status-projection.ts +87 -0
  291. package/src/link/store.ts +54 -1
  292. package/src/link/supervisor.ts +543 -55
  293. package/src/link/sync-fanout-classify.ts +16 -0
  294. package/src/link/sync-then-restart.ts +65 -0
  295. package/src/link/tombstones.ts +209 -0
  296. package/src/link/traffic.ts +178 -0
  297. package/src/link/ws-activity-holds.ts +474 -0
  298. package/src/local-credentials/publication-fence.ts +20 -1
  299. package/src/messaging/mcp-queue-rpc.ts +1 -1
  300. package/src/messaging/mcp-queue-server.ts +16 -1
  301. package/src/messaging/mcp-resume-tools.ts +25 -0
  302. package/src/messaging/remote-enrollment.ts +3 -3
  303. package/src/messaging/remote-tunnels.ts +2 -2
  304. package/src/messaging/resume-permissions.ts +27 -0
  305. package/src/messaging/rpc.ts +46 -2
  306. package/src/oauth/anthropic-continuity.ts +23 -7
  307. package/src/oauth/anthropic-routing.ts +5 -2
  308. package/src/oauth/anthropic.ts +22 -2
  309. package/src/oauth/claude-keychain-read.ts +78 -68
  310. package/src/oauth/index.ts +24 -6
  311. package/src/oauth/local-token-detect.ts +8 -29
  312. package/src/oauth/login-cli-errors.ts +5 -1
  313. package/src/oauth/login-cli.ts +33 -18
  314. package/src/oauth/login-flow-state.ts +26 -3
  315. package/src/oauth/meta-muse.ts +1 -1
  316. package/src/oauth/store.ts +7 -0
  317. package/src/oauth/xai.ts +248 -14
  318. package/src/protocols/contract.ts +4 -0
  319. package/src/protocols/encoders/messages.ts +1 -0
  320. package/src/providers/alias-template.ts +48 -0
  321. package/src/providers/anthropic-billing-ownership.ts +2 -0
  322. package/src/providers/anthropic-output-caps.ts +46 -0
  323. package/src/providers/anthropic-reset-grant-ledger.ts +9 -3
  324. package/src/providers/antigravity-effort-families.ts +11 -3
  325. package/src/providers/antigravity-models.ts +32 -9
  326. package/src/providers/antigravity-wire-snapshot.ts +3 -2
  327. package/src/providers/api-key-pause.ts +3 -0
  328. package/src/providers/api-key-resolve.ts +49 -7
  329. package/src/providers/api-key-response-ownership.ts +2 -0
  330. package/src/providers/api-key-selection.ts +51 -9
  331. package/src/providers/api-keys.ts +6 -2
  332. package/src/providers/cache-affinity-identity.ts +73 -0
  333. package/src/providers/cache-affinity.ts +256 -0
  334. package/src/providers/default-aliases.ts +98 -20
  335. package/src/providers/google-vertex-model-discovery.ts +510 -0
  336. package/src/providers/key-failover.ts +123 -8
  337. package/src/providers/key-store.ts +3 -3
  338. package/src/providers/kiro-models.ts +3 -5
  339. package/src/providers/label.ts +31 -5
  340. package/src/providers/mistral-transport.ts +17 -4
  341. package/src/providers/model-rename-fields.ts +3 -0
  342. package/src/providers/muse-key-quota.ts +14 -6
  343. package/src/providers/new-model-policy-runtime.ts +17 -4
  344. package/src/providers/new-model-policy.ts +30 -4
  345. package/src/providers/passive-key-observation.ts +252 -0
  346. package/src/providers/quota/account-cache.ts +2 -1
  347. package/src/providers/quota/anthropic-cooldown-recovery-worker.ts +121 -0
  348. package/src/providers/quota/passive-key-limits.ts +272 -0
  349. package/src/providers/quota/passive-wire-model.ts +126 -0
  350. package/src/providers/quota/report-cache.ts +61 -2
  351. package/src/providers/quota-key-accounts.ts +11 -6
  352. package/src/providers/quota-types.ts +18 -0
  353. package/src/providers/quota.ts +11 -12
  354. package/src/providers/registry/entries-core.ts +34 -16
  355. package/src/providers/registry/entries-extended.ts +32 -0
  356. package/src/providers/registry/model-seeds.ts +35 -0
  357. package/src/providers/resolved-model-policy.ts +7 -0
  358. package/src/providers/routed-config.ts +8 -3
  359. package/src/providers/xai-transport.ts +3 -0
  360. package/src/remote/features.ts +17 -0
  361. package/src/responses/anthropic-progress.ts +10 -4
  362. package/src/responses/citation-markers.ts +231 -0
  363. package/src/responses/spill-store.ts +5 -1
  364. package/src/responses/state/replay-input.ts +50 -0
  365. package/src/responses/state/replay-owner.ts +24 -0
  366. package/src/responses/state/snapshot-codec.ts +9 -0
  367. package/src/responses/state/spill-queue.ts +1 -0
  368. package/src/responses/state.ts +42 -60
  369. package/src/router.ts +2 -2
  370. package/src/routing/home-route-capture.ts +123 -0
  371. package/src/routing/home-route-intent.ts +200 -0
  372. package/src/routing/route-intent-state.ts +178 -0
  373. package/src/routing/route-to-live-settings.ts +35 -0
  374. package/src/routing/route-to-local.ts +145 -0
  375. package/src/routing/route-to-status.ts +94 -0
  376. package/src/routing/route-to-sync-child.ts +32 -0
  377. package/src/server/adapter-resolve.ts +21 -1
  378. package/src/server/admitted-http-turn.ts +3 -0
  379. package/src/server/auth-cors.ts +98 -0
  380. package/src/server/bare-upstream-error.ts +220 -0
  381. package/src/server/chat-native.ts +14 -5
  382. package/src/server/claude-messages.ts +6 -4
  383. package/src/server/codex-model-list.ts +2 -1
  384. package/src/server/configured-credentials.ts +37 -5
  385. package/src/server/gui-desktop-authorization.ts +36 -0
  386. package/src/server/gui-pair-delivery.ts +6 -3
  387. package/src/server/gui-session.ts +10 -1
  388. package/src/server/inbound-body-admission.ts +17 -4
  389. package/src/server/index/link-listener.ts +190 -12
  390. package/src/server/index/link-management.ts +15 -1
  391. package/src/server/index/link-relay-sessions.ts +87 -8
  392. package/src/server/index/link-websocket-limits.ts +136 -0
  393. package/src/server/index/link-websocket.ts +692 -0
  394. package/src/server/index/optional-listeners.ts +97 -7
  395. package/src/server/index/route-intent-watch.ts +47 -0
  396. package/src/server/index/serve-contract.ts +86 -0
  397. package/src/server/index/serve-options.ts +35 -86
  398. package/src/server/index/startup-warnings.ts +8 -2
  399. package/src/server/index/websocket-handler.ts +26 -4
  400. package/src/server/index.ts +12 -2
  401. package/src/server/inference/client-encoder-delivery.ts +2 -0
  402. package/src/server/inspection-tee.ts +39 -2
  403. package/src/server/lifecycle.ts +2 -0
  404. package/src/server/link-turn.ts +137 -0
  405. package/src/server/management/advisor-routes.ts +10 -2
  406. package/src/server/management/agent-settings-routes.ts +50 -16
  407. package/src/server/management/anthropic-reset-grant-routes.ts +1 -1
  408. package/src/server/management/context.ts +9 -2
  409. package/src/server/management/desktop-authorization.ts +41 -0
  410. package/src/server/management/desktop-compatibility-routes.ts +9 -8
  411. package/src/server/management/desktop-compatibility-runtime-routes.ts +3 -2
  412. package/src/server/management/desktop-compatibility-settings-routes.ts +5 -3
  413. package/src/server/management/home-integration-decision.ts +89 -0
  414. package/src/server/management/integration-routes.ts +208 -81
  415. package/src/server/management/link-child-ops-routes.ts +145 -43
  416. package/src/server/management/link-child-preflight.ts +31 -0
  417. package/src/server/management/link-diagnostics-route.ts +29 -0
  418. package/src/server/management/link-enrollment.ts +199 -47
  419. package/src/server/management/link-operation.ts +609 -0
  420. package/src/server/management/link-recover-route.ts +103 -0
  421. package/src/server/management/link-route-edit.ts +173 -0
  422. package/src/server/management/link-route-request.ts +62 -0
  423. package/src/server/management/link-route-state.ts +83 -7
  424. package/src/server/management/link-routes.ts +553 -51
  425. package/src/server/management/link-traffic-status.ts +13 -0
  426. package/src/server/management/model-routes.ts +122 -36
  427. package/src/server/management/model-rows.ts +2 -1
  428. package/src/server/management/native-integration-routes.ts +176 -70
  429. package/src/server/management/oauth-account-routes.ts +36 -13
  430. package/src/server/management/protocol-routes.ts +7 -0
  431. package/src/server/management/provider-completion-test.ts +4 -4
  432. package/src/server/management/provider-overwrite-carry.ts +11 -0
  433. package/src/server/management/provider-routes.ts +64 -61
  434. package/src/server/management/provider-routing-quota.ts +45 -0
  435. package/src/server/management/route-registry.ts +22 -3
  436. package/src/server/management/route-to-routes.ts +257 -0
  437. package/src/server/management/system-restart.ts +4 -2
  438. package/src/server/management/usage-aggregate-cache.ts +101 -66
  439. package/src/server/management-api.ts +17 -3
  440. package/src/server/management-auth.ts +13 -1
  441. package/src/server/messages-native-preflight.ts +27 -4
  442. package/src/server/messages-native.ts +17 -5
  443. package/src/server/persistent-gui-session.ts +6 -3
  444. package/src/server/proxy-liveness.ts +33 -6
  445. package/src/server/relay-eager.ts +36 -12
  446. package/src/server/relay.ts +183 -116
  447. package/src/server/request-body-facts.ts +48 -0
  448. package/src/server/request-decompress.ts +65 -2
  449. package/src/server/request-log-account-rotation.ts +6 -0
  450. package/src/server/request-log-attempt-usage.ts +69 -0
  451. package/src/server/request-log-cache-affinity.ts +60 -0
  452. package/src/server/request-log-conversation.ts +45 -2
  453. package/src/server/request-log-terminal-status.ts +210 -24
  454. package/src/server/request-log.ts +71 -79
  455. package/src/server/responses/adapter-continuation.ts +2 -1
  456. package/src/server/responses/adapter-delivery.ts +2 -0
  457. package/src/server/responses/adapter-dispatch.ts +5 -7
  458. package/src/server/responses/advisor-plan-slot.ts +33 -1
  459. package/src/server/responses/advisor-question.ts +21 -0
  460. package/src/server/responses/advisor-slot.ts +10 -3
  461. package/src/server/responses/bare-namespace-aliases.ts +18 -0
  462. package/src/server/responses/buffered-sse-json.ts +9 -3
  463. package/src/server/responses/code-mode-collab-surface.ts +11 -0
  464. package/src/server/responses/codex-tool-catalog.ts +156 -0
  465. package/src/server/responses/combo-required-tool-fulfillments.ts +4 -2
  466. package/src/server/responses/combo-stream-preflight.ts +557 -54
  467. package/src/server/responses/compact.ts +32 -8
  468. package/src/server/responses/core-codex-account.ts +17 -3
  469. package/src/server/responses/core-combo-failure.ts +8 -0
  470. package/src/server/responses/core-combo.ts +32 -4
  471. package/src/server/responses/core-errors.ts +5 -2
  472. package/src/server/responses/core-lifetime.ts +3 -2
  473. package/src/server/responses/core-normalize.ts +3 -1
  474. package/src/server/responses/core-options.ts +6 -0
  475. package/src/server/responses/core.ts +2 -0
  476. package/src/server/responses/fetch-helpers.ts +15 -10
  477. package/src/server/responses/native-replay-guard.ts +57 -0
  478. package/src/server/responses/opengateway-completion-guard.ts +10 -4
  479. package/src/server/responses/outbound-request-body.ts +29 -0
  480. package/src/server/responses/passthrough-completion.ts +105 -8
  481. package/src/server/responses/passthrough-delivery.ts +31 -11
  482. package/src/server/responses/passthrough-dispatch.ts +74 -73
  483. package/src/server/responses/policy-fallback.ts +13 -1
  484. package/src/server/responses/request-prepare.ts +50 -6
  485. package/src/server/responses/request-transport.ts +10 -3
  486. package/src/server/responses/reset-replay.ts +46 -2
  487. package/src/server/responses/run-turn-execution.ts +2 -0
  488. package/src/server/responses/sidecar-execution.ts +14 -0
  489. package/src/server/responses/terminal-error-redaction.ts +222 -25
  490. package/src/server/responses/ws-upstream.ts +2 -2
  491. package/src/server/sse-payload-rewrite.ts +3 -2
  492. package/src/server/stop-service-route.ts +85 -0
  493. package/src/server/system-env-shell.ts +12 -1
  494. package/src/server/system-env.ts +5 -3
  495. package/src/server/windows-tcp-drop.ts +21 -4
  496. package/src/server/workflow-refusal.ts +8 -0
  497. package/src/server/ws-bridge.ts +191 -12
  498. package/src/service/cli-windows-stop.ts +189 -0
  499. package/src/service/cli.ts +41 -12
  500. package/src/service/disconnected-client-restart.ts +60 -0
  501. package/src/service/guarded-manager-target.ts +18 -1
  502. package/src/service/health.ts +99 -6
  503. package/src/service/launchd.ts +84 -31
  504. package/src/service/orchestration.ts +418 -91
  505. package/src/service/repair.ts +223 -6
  506. package/src/service/restart-proxy-stop.ts +79 -0
  507. package/src/service/service-child-ownership.ts +6 -2
  508. package/src/service/windows-checked-stop-live.ts +467 -0
  509. package/src/service/windows-checked-stop.ts +435 -0
  510. package/src/service/windows-command-line-token.ts +23 -0
  511. package/src/service/windows-guarded-manager.ts +77 -34
  512. package/src/service/windows-ops.ts +38 -56
  513. package/src/service/windows-process-evidence.ts +292 -0
  514. package/src/service/windows-process-native.ts +262 -0
  515. package/src/service/windows-service-stop.ts +321 -0
  516. package/src/service/windows-stop-binding.ts +187 -0
  517. package/src/service/windows-stop-budget.ts +123 -0
  518. package/src/service/windows-stop-confirm.ts +158 -0
  519. package/src/service/windows-stop-deadline.ts +56 -0
  520. package/src/service.ts +2 -2
  521. package/src/types/config.ts +42 -18
  522. package/src/types/link.ts +20 -0
  523. package/src/types/multi-agent.ts +13 -0
  524. package/src/types/provider.ts +47 -2
  525. package/src/types/request.ts +4 -0
  526. package/src/types.ts +3 -0
  527. package/src/update/guarded-runtime-ops.ts +5 -7
  528. package/src/update/index.ts +25 -10
  529. package/src/update/install-detection.mjs +3 -1
  530. package/src/update/job-pinned-start.ts +2 -0
  531. package/src/update/job-windows-restart.ts +19 -32
  532. package/src/update/job.ts +12 -5
  533. package/src/update/npm-install.d.mts +11 -0
  534. package/src/update/npm-install.mjs +44 -7
  535. package/src/update/orchestrated-entry.ts +1 -1
  536. package/src/update/orchestrated-node-driver.mjs +3 -2
  537. package/src/update/orchestrated-pnpm.d.mts +4 -0
  538. package/src/update/orchestrated-pnpm.mjs +50 -6
  539. package/src/update/orchestrated-session.d.mts +3 -1
  540. package/src/update/orchestrated-session.mjs +21 -6
  541. package/src/update/pnpm-global-install.d.mts +21 -3
  542. package/src/update/pnpm-global-install.mjs +322 -19
  543. package/src/update/pnpm-store-layout.mjs +46 -0
  544. package/src/update/sync-update-mutex.d.mts +3 -2
  545. package/src/update/sync-update-mutex.mjs +57 -8
  546. package/src/update/transactional-install.d.mts +3 -1
  547. package/src/update/transactional-install.mjs +545 -12
  548. package/src/update/windows-installer-marker.d.mts +1 -0
  549. package/src/update/windows-installer-marker.mjs +44 -0
  550. package/src/usage/expected-prices.ts +8 -0
  551. package/src/usage/filter-index.ts +326 -77
  552. package/src/usage/ledger-scanner.ts +15 -0
  553. package/src/usage/link-log-fields.ts +48 -0
  554. package/src/usage/log.ts +43 -2
  555. package/src/usage/request-body.ts +37 -0
  556. package/src/web-search/loop.ts +3 -0
  557. package/gui/dist/assets/App-BpJOzw4F.js +0 -59
  558. package/gui/dist/assets/index-Bbor_y80.js +0 -94
  559. package/gui/dist/classic/assets/App-BrIlUiLc.js +0 -58
  560. package/gui/dist/classic/assets/index-DyJHagvT.js +0 -94
  561. package/src/server/management/desktop-compatibility-authorization.ts +0 -12
@@ -16,10 +16,8 @@ import { OCX_ELEVATED_STAGING_UNREADABLE, runWindowsElevatedScheduledTaskRegistr
16
16
  import { defaultWinswEntry, installWinswService, statusWinswRaw, uninstallWinswService, WINSW_SERVICE_ID, type WinswStatus } from "../lib/winsw";
17
17
  import { forgetEphemeralSecretDir, forgetEphemeralSecretPath, hardenElevatedStageDir, hardenElevatedStagePath, hardenSecretDir } from "../lib/windows-secret-acl";
18
18
  import { recordOwnedConfigPath } from "../lib/config-ownership";
19
- import { killWindowsSchedulerWrappers } from "../lib/windows-service-wrappers";
20
19
  import { isTestHomeGuardArmed } from "../lib/test-home-guard";
21
20
  import { writeServiceApiTokenFile } from "./guards";
22
- import type { ServiceStopOutcome } from "./orchestration";
23
21
  import { TASK, windowsLauncherVbsPath, windowsTaskXmlPath, serviceStatePath, writeServiceInstallState, serviceSourceDir, cliEntry } from "./state";
24
22
  import { decodeSchtasksOutput, querySchtasks, schtasks, type WindowsSchedulerTaskProbe, schtasksErrorDetail, probeWindowsSchedulerTask, rollbackWindowsSchedulerTaskOwnedByAttempt } from "./windows-scheduler";
25
23
  import { buildWindowsServiceScript, buildWindowsSchtasksCreateArgs, buildWindowsSchtasksCreateArgsForXml, buildWindowsLauncherVbs, resolvedWindowsTaskSid, buildWindowsTaskXmlDocument, windowsTaskRegistrationOwnedByAttempt, windowsTaskRegistrationHealthy } from "./windows-taskxml";
@@ -63,11 +61,14 @@ export function winswListenPort(deps: { readXml?: () => string } = {}): number |
63
61
  * over, since before #2107 these files had no hardening at all and a failure here would
64
62
  * regress a user who has no credential to protect.
65
63
  */
66
- export function writeServiceDefinitionFile(path: string, content: string, encoding: "utf8" | "utf16le"): void {
67
- writeFileSync(path, content, { encoding, mode: 0o600 });
64
+ /** Bytes are written as they are: a restored snapshot must not be re-encoded through `encoding`. */
65
+ export function writeServiceDefinitionFile(path: string, content: string | Buffer, encoding: "utf8" | "utf16le"): void {
66
+ if (typeof content === "string") writeFileSync(path, content, { encoding, mode: 0o600 });
67
+ else writeFileSync(path, content, { mode: 0o600 });
68
68
  try { chmodSync(path, 0o600); } catch { /* superseded by the Windows ACL below */ }
69
69
  if (process.platform === "win32") {
70
- hardenSecretPath(path, { required: definitionCarriesCredential(content) });
70
+ const text = typeof content === "string" ? content : content.toString(encoding);
71
+ hardenSecretPath(path, { required: definitionCarriesCredential(text) });
71
72
  }
72
73
  }
73
74
 
@@ -125,6 +126,38 @@ export function writeWindowsSchedulerAssets(runtime: DurableBunRuntime = durable
125
126
  );
126
127
  }
127
128
 
129
+ /**
130
+ * The on-disk scheduler assets as they are now, so a failed rewrite can put back what the
131
+ * registered task already runs. The returned restore rewrites only assets whose bytes changed
132
+ * (one that failed to write is still intact) and removes one that did not exist before.
133
+ */
134
+ export function snapshotWindowsSchedulerAssets(): () => void {
135
+ const assets = [
136
+ { path: windowsServiceScriptPath(), encoding: "utf8" as const },
137
+ { path: windowsLauncherVbsPath(), encoding: "utf16le" as const },
138
+ { path: windowsTaskXmlPath(), encoding: "utf16le" as const },
139
+ ].map(asset => {
140
+ try { return { ...asset, bytes: readFileSync(asset.path) as Buffer | null }; }
141
+ catch (error) {
142
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return { ...asset, bytes: null };
143
+ throw error;
144
+ }
145
+ });
146
+ return () => {
147
+ for (const asset of assets) {
148
+ let current: Buffer | null;
149
+ try { current = readFileSync(asset.path); }
150
+ catch (error) {
151
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
152
+ current = null;
153
+ }
154
+ if (asset.bytes === null) { if (current !== null) unlinkSync(asset.path); continue; }
155
+ if (current !== null && current.equals(asset.bytes)) continue;
156
+ writeServiceDefinitionFile(asset.path, asset.bytes, asset.encoding);
157
+ }
158
+ };
159
+ }
160
+
128
161
  const WINDOWS_SCHEDULER_STAGE_PREFIX = "opencodex-service-stage-";
129
162
 
130
163
  const ownedWindowsSchedulerStages = new Set<string>();
@@ -851,42 +884,10 @@ export function stopWindows(beforeMutation?: () => void): void {
851
884
  }
852
885
  }
853
886
 
854
- /**
855
- * `stopWindows` for callers that need to know whether it worked.
856
- *
857
- * The void form swallows a non-benign `/end` failure, which is right for best-effort
858
- * teardown and wrong for deciding whether an update may replace files: a scheduler that
859
- * refused to stop can respawn the proxy on top of a half-written install (#3008).
860
- */
861
- export function stopWindowsChecked(): boolean {
862
- try {
863
- schtasks(["/end", "/tn", TASK]);
864
- return true;
865
- } catch (error) {
866
- return isWindowsSchedulerEndBenign(error);
867
- }
868
- }
869
-
870
887
  export function statusWindows(): string { try { return schtasks(["/query", "/tn", TASK]); } catch { return ""; } }
871
888
 
872
889
  export function statusWindowsXml(): string { try { return schtasks(["/query", "/tn", TASK, "/xml"]); } catch { return ""; } }
873
890
 
874
- /**
875
- * Best-effort termination of surviving Windows scheduler launcher/wrapper processes.
876
- * `schtasks /end` ends the task instance but often leaves wscript/cmd running the
877
- * `:loop` batch, which brings the proxy back during a stop or restart.
878
- *
879
- * The matching rule — canonical paths of THIS installation, as complete
880
- * command-line tokens — lives in lib/windows-service-wrappers so the update job
881
- * cannot drift away from it again.
882
- */
883
- export function killWindowsServiceWrapperProcesses(): void {
884
- killWindowsSchedulerWrappers({
885
- scriptPath: windowsServiceScriptPath(),
886
- launcherPath: windowsLauncherVbsPath(),
887
- });
888
- }
889
-
890
891
  export function uninstallWindows(): void {
891
892
  const probe = probeWindowsSchedulerTask(TASK);
892
893
  if (probe.status === "present") {
@@ -909,22 +910,3 @@ export function uninstallWindows(): void {
909
910
  if (existsSync(windowsLauncherVbsPath())) unlinkSync(windowsLauncherVbsPath());
910
911
  if (existsSync(windowsTaskXmlPath())) unlinkSync(windowsTaskXmlPath());
911
912
  }
912
-
913
- /**
914
- * Collapse the Windows backend observations into one outcome.
915
- *
916
- * Extracted so the precedence is testable by calling it. The rule that matters: a readable
917
- * failure outranks an unreadable state, and an unreadable state outranks success — a
918
- * scheduler we cannot see may still respawn the proxy.
919
- */
920
- export function classifyWindowsServiceStop(o: {
921
- stopped: boolean;
922
- failed: boolean;
923
- schedulerStopped: boolean;
924
- stateUnknown: boolean;
925
- }): ServiceStopOutcome {
926
- if (o.failed) return "failed";
927
- if (o.stateUnknown) return "state-unknown";
928
- if (o.stopped) return o.schedulerStopped ? "stopped-respawnable" : "stopped";
929
- return "absent";
930
- }
@@ -0,0 +1,292 @@
1
+ /**
2
+ * Process evidence for the checked Windows service stop (#7771): a process snapshot that
3
+ * carries creation times, the Task Scheduler service PID, a checked terminate, and a
4
+ * bind-time exit watch. Each facade uses the in-process primitive from
5
+ * src/service/windows-process-native.ts where Bun's FFI runs (Windows x64) and a bounded
6
+ * spawned fallback elsewhere on Windows (ARM64):
7
+ *
8
+ * - snapshot: one Get-CimInstance Win32_Process query with CreationDate. On x64 every
9
+ * creation time is re-read through GetProcessTimes and kept only when it agrees with
10
+ * CIM to the millisecond, so the bound value is the exact one the handle terminate
11
+ * compares later, and a PID reused between the CIM query and the native read is null
12
+ * (unreadable) instead of silently taking the new process's identity;
13
+ * - Schedule PID: QueryServiceStatusEx on x64, else sc.exe queryex Schedule run from the
14
+ * trusted system directory with a cap; unreadable is null;
15
+ * - terminate: the handle primitive on x64. ARM64 runs ONE trusted PowerShell script that
16
+ * re-reads Get-Process -Id StartTime, compares it with the bound CIM creation time
17
+ * (1 s tolerance, UTC), calls Kill() on the same Process object and reads the exit back.
18
+ * Kill() opens its own handle by PID, so a window between the in-script check and the
19
+ * kill remains; that, and the 1 s tolerance, are the accepted residuals of the fallback;
20
+ * - watch: x64 only; elsewhere "unavailable", and the checked stop takes the exit from
21
+ * the terminate read-back.
22
+ *
23
+ * Only integers ever reach a script; paths and command lines are compared in TypeScript.
24
+ * Nothing calls this module yet.
25
+ */
26
+ import { execFile } from "node:child_process";
27
+ import { existsSync } from "node:fs";
28
+ import { join } from "node:path";
29
+
30
+ import { resolveTrustedWindowsPowerShellExe, resolveTrustedWindowsSystemDirectory } from "../lib/windows-elevation";
31
+ import type { WindowsProcessEntry } from "./windows-guarded-manager";
32
+ import {
33
+ windowsProcessNative,
34
+ windowsProcessPlatform,
35
+ windowsProcessPlatformSimulated,
36
+ type WindowsProcessWatch,
37
+ type WindowsTerminateResult,
38
+ } from "./windows-process-native";
39
+
40
+ /** A spawned helper. "powershell" and "sc" resolve inside the trusted system directory. */
41
+ export interface WindowsEvidenceCommand {
42
+ program: "powershell" | "sc";
43
+ args: string[];
44
+ timeoutMs: number;
45
+ maxBufferBytes: number;
46
+ }
47
+
48
+ /** Runs a command and resolves stdout; rejects on a nonzero exit, a timeout or overflow. */
49
+ export type WindowsEvidenceRunner = (command: WindowsEvidenceCommand) => Promise<string>;
50
+
51
+ export interface WindowsEvidenceOptions {
52
+ timeoutMs: number;
53
+ /** Injected in tests. Unset on a simulated platform means no spawn at all. */
54
+ run?: WindowsEvidenceRunner;
55
+ }
56
+
57
+ /** A process-table row with the creation time the binding rule requires (null = unreadable). */
58
+ export type WindowsStopProcessEntry = WindowsProcessEntry & { startTime: number | null };
59
+
60
+ const SNAPSHOT_MAX_BUFFER = 16 * 1024 * 1024;
61
+ const SMALL_MAX_BUFFER = 64 * 1024;
62
+ const NATIVE_CIM_TOLERANCE_MS = 1;
63
+ /** Kill() read-back inside the ARM64 script; the checked stop's wait covers the rest. */
64
+ export const FALLBACK_TERMINATE_EXIT_WAIT_MS = 1_000;
65
+
66
+ function trustedProgram(program: WindowsEvidenceCommand["program"]): string {
67
+ if (program === "powershell") return resolveTrustedWindowsPowerShellExe();
68
+ const sc = join(resolveTrustedWindowsSystemDirectory(), "sc.exe");
69
+ if (!existsSync(sc)) throw new Error("sc.exe was not found in the trusted system directory.");
70
+ return sc;
71
+ }
72
+
73
+ const defaultRunner: WindowsEvidenceRunner = command => new Promise((resolve, reject) => {
74
+ let file: string;
75
+ try {
76
+ file = trustedProgram(command.program);
77
+ } catch (error) {
78
+ reject(error);
79
+ return;
80
+ }
81
+ execFile(file, command.args, {
82
+ encoding: "utf8",
83
+ timeout: command.timeoutMs,
84
+ maxBuffer: command.maxBufferBytes,
85
+ windowsHide: true,
86
+ }, (error, stdout) => {
87
+ if (error) reject(error);
88
+ else resolve(stdout);
89
+ });
90
+ });
91
+
92
+ function runnerFor(options: WindowsEvidenceOptions): WindowsEvidenceRunner | null {
93
+ if (options.run) return options.run;
94
+ if (windowsProcessPlatformSimulated() || windowsProcessPlatform() !== "win32") return null;
95
+ return defaultRunner;
96
+ }
97
+
98
+ function powershellArgs(script: string): string[] {
99
+ return ["-NoProfile", "-NoLogo", "-NonInteractive", "-Command", script];
100
+ }
101
+
102
+ /** The snapshot query. CreationDate is emitted as an ISO UTC string, never as a JSON date. */
103
+ export const WINDOWS_PROCESS_SNAPSHOT_SCRIPT = "Get-CimInstance Win32_Process | Select-Object "
104
+ + "ProcessId,ParentProcessId,Name,CommandLine,"
105
+ + "@{Name='CreationDate';Expression={ if ($_.CreationDate) { $_.CreationDate.ToUniversalTime().ToString('o') } else { $null } }} "
106
+ + "| ConvertTo-Json -Compress";
107
+
108
+ /** Parse the snapshot JSON. Unparseable output is null: an unread table proves nothing. */
109
+ export function parseWindowsProcessSnapshot(output: string): WindowsStopProcessEntry[] | null {
110
+ const trimmed = output.trim();
111
+ if (!trimmed) return [];
112
+ let parsed: unknown;
113
+ try {
114
+ parsed = JSON.parse(trimmed);
115
+ } catch {
116
+ return null;
117
+ }
118
+ const rows = Array.isArray(parsed) ? parsed : [parsed];
119
+ const entries: WindowsStopProcessEntry[] = [];
120
+ for (const row of rows) {
121
+ if (typeof row !== "object" || row === null) continue;
122
+ const record = row as Record<string, unknown>;
123
+ const pid = Number(record.ProcessId);
124
+ const parent = Number(record.ParentProcessId);
125
+ if (!Number.isSafeInteger(pid) || pid <= 0) continue;
126
+ const created = typeof record.CreationDate === "string" ? Date.parse(record.CreationDate) : Number.NaN;
127
+ entries.push({
128
+ pid,
129
+ parentPid: Number.isSafeInteger(parent) && parent > 0 ? parent : null,
130
+ name: typeof record.Name === "string" ? record.Name : null,
131
+ commandLine: typeof record.CommandLine === "string" ? record.CommandLine : null,
132
+ startTime: Number.isFinite(created) ? created : null,
133
+ });
134
+ }
135
+ return entries;
136
+ }
137
+
138
+ /**
139
+ * Replace each CIM creation time with the native one when both agree to the millisecond.
140
+ * A disagreement (or a missing side) is null: the binding rule then treats the process as
141
+ * unreadable rather than binding an identity the terminate check would not reproduce.
142
+ */
143
+ export function overlayNativeCreationTimes(
144
+ entries: readonly WindowsStopProcessEntry[],
145
+ creationTime: (pid: number) => number | null,
146
+ ): WindowsStopProcessEntry[] {
147
+ return entries.map(entry => {
148
+ if (entry.startTime === null) return entry;
149
+ let native: number | null;
150
+ try {
151
+ native = creationTime(entry.pid);
152
+ } catch {
153
+ native = null;
154
+ }
155
+ const agrees = native !== null && Math.abs(native - entry.startTime) <= NATIVE_CIM_TOLERANCE_MS;
156
+ return { ...entry, startTime: agrees ? native : null };
157
+ });
158
+ }
159
+
160
+ /** Every process with its creation time, or null when the table cannot be read. */
161
+ export async function windowsProcessSnapshot(options: WindowsEvidenceOptions): Promise<WindowsStopProcessEntry[] | null> {
162
+ const run = runnerFor(options);
163
+ if (!run) return null;
164
+ let entries: WindowsStopProcessEntry[] | null;
165
+ try {
166
+ entries = parseWindowsProcessSnapshot(await run({
167
+ program: "powershell",
168
+ args: powershellArgs(WINDOWS_PROCESS_SNAPSHOT_SCRIPT),
169
+ timeoutMs: options.timeoutMs,
170
+ maxBufferBytes: SNAPSHOT_MAX_BUFFER,
171
+ }));
172
+ } catch {
173
+ return null;
174
+ }
175
+ if (entries === null) return null;
176
+ const native = windowsProcessNative();
177
+ return native ? overlayNativeCreationTimes(entries, pid => native.creationTime(pid)) : entries;
178
+ }
179
+
180
+ /**
181
+ * sc.exe queryex Schedule: the PID only while STATE is 4 (RUNNING). The field names and
182
+ * the numeric state are not localized; the trailing state word is ignored.
183
+ */
184
+ export function parseScQueryexPid(output: string): number | null {
185
+ const state = /^\s*STATE\s*:\s*(\d+)/m.exec(output);
186
+ if (!state || Number(state[1]) !== 4) return null;
187
+ const pid = /^\s*PID\s*:\s*(\d+)\s*$/m.exec(output);
188
+ if (!pid) return null;
189
+ const value = Number(pid[1]);
190
+ return Number.isSafeInteger(value) && value > 0 ? value : null;
191
+ }
192
+
193
+ /** The Task Scheduler service host's PID, or null when it cannot be proven. */
194
+ export async function readScheduleServicePid(options: WindowsEvidenceOptions): Promise<number | null> {
195
+ const native = options.run ? null : windowsProcessNative();
196
+ if (native) {
197
+ try {
198
+ return native.scheduleServicePid();
199
+ } catch {
200
+ return null;
201
+ }
202
+ }
203
+ const run = runnerFor(options);
204
+ if (!run) return null;
205
+ try {
206
+ return parseScQueryexPid(await run({
207
+ program: "sc",
208
+ args: ["queryex", "Schedule"],
209
+ timeoutMs: options.timeoutMs,
210
+ maxBufferBytes: SMALL_MAX_BUFFER,
211
+ }));
212
+ } catch {
213
+ return null;
214
+ }
215
+ }
216
+
217
+ /**
218
+ * The ARM64 terminate script. pid and the bound time must be safe integers; nothing else
219
+ * is interpolated. One status word is printed on the last line.
220
+ */
221
+ export function windowsFallbackTerminateScript(pid: number, boundStartTime: number, exitWaitMs: number): string {
222
+ for (const value of [pid, boundStartTime, exitWaitMs]) {
223
+ if (!Number.isSafeInteger(value) || value < 0) throw new Error("terminate script inputs must be non-negative integers");
224
+ }
225
+ return [
226
+ "$ErrorActionPreference = 'Stop';",
227
+ "try { $p = Get-Process -Id " + pid + " -ErrorAction Stop } catch { 'gone'; exit 0 };",
228
+ "try { $start = $p.StartTime.ToUniversalTime() } catch {",
229
+ " try { if ($p.HasExited) { 'gone' } else { 'denied' } } catch { 'denied' }; exit 0 };",
230
+ "$bound = [DateTimeOffset]::FromUnixTimeMilliseconds(" + boundStartTime + ").UtcDateTime;",
231
+ "if ([Math]::Abs(($start - $bound).TotalMilliseconds) -gt 1000) { 'reused'; exit 0 };",
232
+ "try { $p.Kill() }",
233
+ "catch [System.InvalidOperationException] { 'gone'; exit 0 }",
234
+ "catch [System.ComponentModel.Win32Exception] { 'denied'; exit 0 }",
235
+ "catch { 'unavailable'; exit 0 };",
236
+ "if ($p.WaitForExit(" + exitWaitMs + ")) { 'terminated-exited' } else { 'terminated' }",
237
+ ].join(" ");
238
+ }
239
+
240
+ /** Map the script's last line; anything unexpected is "unavailable", never success. */
241
+ export function parseFallbackTerminateOutput(output: string): WindowsTerminateResult {
242
+ const lines = output.split(/\r?\n/).map(line => line.trim()).filter(Boolean);
243
+ const word = lines[lines.length - 1] ?? "";
244
+ if (word === "terminated-exited") return { status: "terminated", exited: true };
245
+ if (word === "terminated") return { status: "terminated", exited: false };
246
+ if (word === "gone" || word === "reused" || word === "denied") return { status: word };
247
+ return { status: "unavailable" };
248
+ }
249
+
250
+ /** Terminate pid only if it is still the process created at boundStartTime. */
251
+ export async function terminateWindowsProcessBound(
252
+ pid: number,
253
+ boundStartTime: number,
254
+ options: WindowsEvidenceOptions,
255
+ ): Promise<WindowsTerminateResult> {
256
+ const native = options.run ? null : windowsProcessNative();
257
+ if (native) {
258
+ try {
259
+ return native.terminate(pid, boundStartTime);
260
+ } catch {
261
+ return { status: "unavailable" };
262
+ }
263
+ }
264
+ const run = runnerFor(options);
265
+ if (!run) return { status: "unavailable" };
266
+ // A timeout derived from a deadline can be fractional, and both execFile and the script
267
+ // take whole milliseconds. A timeout that floors to 0 would mean no timeout at all.
268
+ const timeoutMs = Math.floor(options.timeoutMs);
269
+ if (!(timeoutMs > 0)) return { status: "unavailable" };
270
+ const exitWaitMs = Math.max(0, Math.min(FALLBACK_TERMINATE_EXIT_WAIT_MS, timeoutMs - 500));
271
+ try {
272
+ return parseFallbackTerminateOutput(await run({
273
+ program: "powershell",
274
+ args: powershellArgs(windowsFallbackTerminateScript(pid, boundStartTime, exitWaitMs)),
275
+ timeoutMs,
276
+ maxBufferBytes: SMALL_MAX_BUFFER,
277
+ }));
278
+ } catch {
279
+ return { status: "unavailable" };
280
+ }
281
+ }
282
+
283
+ /** A bind-time exit watch; "unavailable" wherever the handle primitive cannot run. */
284
+ export function openWindowsProcessWatch(pid: number, boundStartTime: number): WindowsProcessWatch {
285
+ const native = windowsProcessNative();
286
+ if (!native) return { status: "unavailable" };
287
+ try {
288
+ return native.openWatch(pid, boundStartTime);
289
+ } catch {
290
+ return { status: "unavailable" };
291
+ }
292
+ }
@@ -0,0 +1,262 @@
1
+ /**
2
+ * In-process Windows process primitives for the checked service stop (#7771).
3
+ *
4
+ * Four questions the checked stop asks of the kernel and the SCM:
5
+ *
6
+ * - when was this process created (GetProcessTimes), so a PID that was reused between
7
+ * bind and terminate is told apart from the process that was bound;
8
+ * - terminate exactly the bound process: OpenProcess, read the creation time on THAT
9
+ * handle, compare, TerminateProcess on the same handle, close. There is no gap between
10
+ * the identity check and the kill in which the PID could be reused;
11
+ * - has a bound process exited (WaitForSingleObject with a zero timeout on a handle
12
+ * opened at bind time), so the wait needs neither an enumeration nor PowerShell;
13
+ * - which process hosts the Task Scheduler service (QueryServiceStatusEx on "Schedule"),
14
+ * the parent the binding rule accepts for a launcher the scheduler started.
15
+ *
16
+ * Loading follows src/config/windows-process-command-line.ts: bun:ffi is required lazily
17
+ * (every importer loads this module on every platform), the DLLs load from the
18
+ * GetSystemDirectoryW path so the search order cannot substitute them, a failed load is
19
+ * cached as null, and every handle is closed in a finally. Windows ARM64 and every other
20
+ * platform get null here; src/service/windows-process-evidence.ts then uses the spawned
21
+ * fallbacks. A test that simulates a platform never reaches the real kernel.
22
+ *
23
+ * Nothing calls this module yet; the stop paths move to it in a later change.
24
+ */
25
+ import { join } from "node:path";
26
+
27
+ import { resolveTrustedWindowsSystemDirectory } from "../lib/windows-elevation";
28
+
29
+ const PROCESS_TERMINATE = 0x0001;
30
+ const PROCESS_QUERY_LIMITED_INFORMATION = 0x1000;
31
+ const SYNCHRONIZE = 0x0010_0000;
32
+ const WAIT_OBJECT_0 = 0;
33
+ const WAIT_TIMEOUT = 0x102;
34
+ const ERROR_ACCESS_DENIED = 5;
35
+ const ERROR_INVALID_PARAMETER = 87;
36
+ const SC_MANAGER_CONNECT = 0x0001;
37
+ const SERVICE_QUERY_STATUS = 0x0004;
38
+ const SC_STATUS_PROCESS_INFO = 0;
39
+ const SERVICE_RUNNING = 4;
40
+ /** SERVICE_STATUS_PROCESS is nine DWORDs; dwCurrentState is the second, dwProcessId the eighth. */
41
+ const SERVICE_STATUS_PROCESS_BYTES = 36;
42
+ const SERVICE_STATUS_STATE_OFFSET = 4;
43
+ const SERVICE_STATUS_PID_OFFSET = 28;
44
+ /** 100 ns intervals between 1601-01-01 and 1970-01-01. */
45
+ const FILETIME_UNIX_EPOCH = 116_444_736_000_000_000n;
46
+ const TERMINATE_EXIT_CODE = 1;
47
+
48
+ /** Result of one checked terminate. Only "terminated" means this call ended the process. */
49
+ export type WindowsTerminateStatus = "terminated" | "gone" | "reused" | "denied" | "unavailable";
50
+
51
+ export interface WindowsTerminateResult {
52
+ status: WindowsTerminateStatus;
53
+ /**
54
+ * True when the primitive itself observed the process exit after terminating it. The
55
+ * x64 primitive does not wait (the checked stop waits on its bind-time handles); the
56
+ * ARM64 fallback reads the exit back inside its script and reports it here.
57
+ */
58
+ exited?: boolean;
59
+ }
60
+
61
+ /** A bind-time handle the checked stop polls instead of enumerating processes again. */
62
+ export type WindowsProcessWatch =
63
+ | { status: "open"; exited(): boolean | null; close(): void }
64
+ | { status: "gone" | "reused" | "denied" | "unavailable" };
65
+
66
+ export interface WindowsProcessNativeApi {
67
+ /** Creation time in epoch ms (FILETIME truncated to ms), or null when unreadable. */
68
+ creationTime(pid: number): number | null;
69
+ terminate(pid: number, boundStartTime: number): WindowsTerminateResult;
70
+ openWatch(pid: number, boundStartTime: number): WindowsProcessWatch;
71
+ /** PID of the running Task Scheduler service host, or null when it cannot be read. */
72
+ scheduleServicePid(): number | null;
73
+ }
74
+
75
+ /** FILETIME (100 ns since 1601) to epoch ms, truncated. Zero or pre-1970 is unreadable. */
76
+ export function fileTimeToEpochMs(fileTime: bigint): number | null {
77
+ if (fileTime <= FILETIME_UNIX_EPOCH) return null;
78
+ const ms = (fileTime - FILETIME_UNIX_EPOCH) / 10_000n;
79
+ return ms > BigInt(Number.MAX_SAFE_INTEGER) ? null : Number(ms);
80
+ }
81
+
82
+ /** Decode SERVICE_STATUS_PROCESS: the PID only while the service reports RUNNING. */
83
+ export function decodeServiceStatusProcess(buffer: Uint8Array): number | null {
84
+ if (buffer.byteLength < SERVICE_STATUS_PROCESS_BYTES) return null;
85
+ const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
86
+ if (view.getUint32(SERVICE_STATUS_STATE_OFFSET, true) !== SERVICE_RUNNING) return null;
87
+ const pid = view.getUint32(SERVICE_STATUS_PID_OFFSET, true);
88
+ return pid > 0 ? pid : null;
89
+ }
90
+
91
+ let nativeApi: WindowsProcessNativeApi | null | undefined;
92
+ let nativeApiForTests: WindowsProcessNativeApi | null | undefined;
93
+ let platformForTests: NodeJS.Platform | null = null;
94
+
95
+ /** Replace the native API in tests; null forces "unavailable", undefined restores the real one. */
96
+ export function setWindowsProcessNativeForTests(next: WindowsProcessNativeApi | null | undefined): void {
97
+ nativeApiForTests = next;
98
+ }
99
+
100
+ /**
101
+ * Simulate a platform in tests. While set, the real kernel is never called: the native
102
+ * API reads as unavailable unless a test API is installed as well.
103
+ */
104
+ export function setWindowsProcessPlatformForTests(next: NodeJS.Platform | null): void {
105
+ platformForTests = next;
106
+ }
107
+
108
+ /** The platform the Windows stop primitives act for (the simulated one in tests). */
109
+ export function windowsProcessPlatform(): NodeJS.Platform {
110
+ return platformForTests ?? process.platform;
111
+ }
112
+
113
+ /** True while a test simulates the platform; nothing may then reach the real machine. */
114
+ export function windowsProcessPlatformSimulated(): boolean {
115
+ return platformForTests !== null;
116
+ }
117
+
118
+ type Handle = number | bigint;
119
+
120
+ function loadNativeApi(): WindowsProcessNativeApi | null {
121
+ if (nativeApi !== undefined) return nativeApi;
122
+ nativeApi = null;
123
+ if (process.platform !== "win32" || process.arch !== "x64") return null;
124
+ let ptr: typeof import("bun:ffi").ptr;
125
+ let kernel32;
126
+ let advapi32;
127
+ try {
128
+ const ffi = require("bun:ffi") as typeof import("bun:ffi");
129
+ ptr = ffi.ptr;
130
+ const systemDirectory = resolveTrustedWindowsSystemDirectory();
131
+ kernel32 = ffi.dlopen(join(systemDirectory, "kernel32.dll"), {
132
+ OpenProcess: { args: ["u32", "i32", "u32"], returns: "u64" },
133
+ CloseHandle: { args: ["u64"], returns: "i32" },
134
+ GetProcessTimes: { args: ["u64", "ptr", "ptr", "ptr", "ptr"], returns: "i32" },
135
+ TerminateProcess: { args: ["u64", "u32"], returns: "i32" },
136
+ WaitForSingleObject: { args: ["u64", "u32"], returns: "u32" },
137
+ GetLastError: { args: [], returns: "u32" },
138
+ }).symbols;
139
+ advapi32 = ffi.dlopen(join(systemDirectory, "advapi32.dll"), {
140
+ OpenSCManagerW: { args: ["ptr", "ptr", "u32"], returns: "u64" },
141
+ OpenServiceW: { args: ["u64", "ptr", "u32"], returns: "u64" },
142
+ QueryServiceStatusEx: { args: ["u64", "i32", "ptr", "u32", "ptr"], returns: "i32" },
143
+ CloseServiceHandle: { args: ["u64"], returns: "i32" },
144
+ }).symbols;
145
+ } catch {
146
+ return null;
147
+ }
148
+ const k = kernel32;
149
+ const a = advapi32;
150
+
151
+ const handleCreationTime = (handle: Handle): number | null => {
152
+ const times = new BigUint64Array(4);
153
+ const base = ptr(times);
154
+ const ok = k.GetProcessTimes(handle, base, base + 8, base + 16, base + 24);
155
+ return ok ? fileTimeToEpochMs(times[0]!) : null;
156
+ };
157
+ // true = exited, false = running, null = unreadable.
158
+ const handleExited = (handle: Handle): boolean | null => {
159
+ const wait = Number(k.WaitForSingleObject(handle, 0)) >>> 0;
160
+ if (wait === WAIT_OBJECT_0) return true;
161
+ if (wait === WAIT_TIMEOUT) return false;
162
+ return null;
163
+ };
164
+ // GetLastError is read immediately after the failed call. If the runtime ever clobbers
165
+ // it, the answer degrades to "unavailable", which the checked stop reports as unknown.
166
+ const openFailure = (): "gone" | "denied" | "unavailable" => {
167
+ const error = Number(k.GetLastError()) >>> 0;
168
+ if (error === ERROR_INVALID_PARAMETER) return "gone";
169
+ if (error === ERROR_ACCESS_DENIED) return "denied";
170
+ return "unavailable";
171
+ };
172
+
173
+ nativeApi = {
174
+ creationTime(pid) {
175
+ const handle = k.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid);
176
+ if (!handle) return null;
177
+ try {
178
+ return handleCreationTime(handle);
179
+ } finally {
180
+ k.CloseHandle(handle);
181
+ }
182
+ },
183
+ terminate(pid, boundStartTime) {
184
+ const handle = k.OpenProcess(PROCESS_TERMINATE | PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE, 0, pid);
185
+ if (!handle) return { status: openFailure() };
186
+ try {
187
+ const created = handleCreationTime(handle);
188
+ if (created === null) return { status: "unavailable" };
189
+ if (created !== boundStartTime) return { status: "reused" };
190
+ const before = handleExited(handle);
191
+ if (before === true) return { status: "gone" };
192
+ if (before === null) return { status: "unavailable" };
193
+ if (k.TerminateProcess(handle, TERMINATE_EXIT_CODE)) return { status: "terminated" };
194
+ const error = Number(k.GetLastError()) >>> 0;
195
+ // TerminateProcess on a process that exited meanwhile also fails with access denied.
196
+ if (handleExited(handle) === true) return { status: "gone" };
197
+ return { status: error === ERROR_ACCESS_DENIED ? "denied" : "unavailable" };
198
+ } finally {
199
+ k.CloseHandle(handle);
200
+ }
201
+ },
202
+ openWatch(pid, boundStartTime) {
203
+ const handle = k.OpenProcess(SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION, 0, pid);
204
+ if (!handle) return { status: openFailure() };
205
+ let keep = false;
206
+ try {
207
+ const created = handleCreationTime(handle);
208
+ if (created === null) return { status: "unavailable" };
209
+ if (created !== boundStartTime) return { status: "reused" };
210
+ keep = true;
211
+ let closed = false;
212
+ return {
213
+ status: "open",
214
+ exited: () => (closed ? null : handleExited(handle)),
215
+ close: () => {
216
+ if (closed) return;
217
+ closed = true;
218
+ k.CloseHandle(handle);
219
+ },
220
+ };
221
+ } finally {
222
+ if (!keep) k.CloseHandle(handle);
223
+ }
224
+ },
225
+ scheduleServicePid() {
226
+ const manager = a.OpenSCManagerW(null, null, SC_MANAGER_CONNECT);
227
+ if (!manager) return null;
228
+ try {
229
+ const name = Buffer.from("Schedule\0", "utf16le");
230
+ const service = a.OpenServiceW(manager, ptr(name), SERVICE_QUERY_STATUS);
231
+ if (!service) return null;
232
+ try {
233
+ const buffer = new Uint8Array(SERVICE_STATUS_PROCESS_BYTES);
234
+ const needed = new Uint32Array(1);
235
+ const ok = a.QueryServiceStatusEx(
236
+ service, SC_STATUS_PROCESS_INFO, ptr(buffer), SERVICE_STATUS_PROCESS_BYTES, ptr(needed),
237
+ );
238
+ return ok ? decodeServiceStatusProcess(buffer) : null;
239
+ } finally {
240
+ a.CloseServiceHandle(service);
241
+ }
242
+ } finally {
243
+ a.CloseServiceHandle(manager);
244
+ }
245
+ },
246
+ };
247
+ return nativeApi;
248
+ }
249
+
250
+ /**
251
+ * The native API, or null where it cannot run: non-Windows, Windows ARM64, a failed DLL
252
+ * load, or a test that simulates a platform without installing a test API.
253
+ */
254
+ export function windowsProcessNative(): WindowsProcessNativeApi | null {
255
+ if (nativeApiForTests !== undefined) return nativeApiForTests;
256
+ if (platformForTests !== null) return null;
257
+ try {
258
+ return loadNativeApi();
259
+ } catch {
260
+ return null;
261
+ }
262
+ }