@bitkyc08/opencodex 2.100.5 → 2.100.6

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 (536) hide show
  1. package/README.md +1 -1
  2. package/bin/ocx.mjs +2 -0
  3. package/gui/dist/assets/App-BI8LQ7Qk.css +1 -0
  4. package/gui/dist/assets/App-CsZ1Gr7S.js +60 -0
  5. package/gui/dist/assets/Tray-CVqm4S4W.js +1 -0
  6. package/gui/dist/assets/brand-mark-BebhnAtV.js +1 -0
  7. package/gui/dist/assets/index-BtwVlpeQ.css +2 -0
  8. package/gui/dist/assets/index-CEeMegqE.js +138 -0
  9. package/gui/dist/assets/{segment-thumb-features-Bquysdn5.js → segment-thumb-features-COdzmORE.js} +1 -1
  10. package/gui/dist/classic/assets/App-BJgUWNJ8.js +59 -0
  11. package/gui/dist/classic/assets/App-CoiVLRW3.css +1 -0
  12. package/gui/dist/classic/assets/Tray-BDlcOLDK.js +1 -0
  13. package/gui/dist/classic/assets/index-B9Jgli_W.js +138 -0
  14. package/gui/dist/classic/assets/usage-companion-chart-vbzDcND0.js +1 -0
  15. package/gui/dist/classic/index.html +1 -1
  16. package/gui/dist/index.html +2 -2
  17. package/native/ocx-child/Cargo.lock +62 -0
  18. package/native/ocx-child/Cargo.toml +1 -0
  19. package/native/ocx-child/src/journal.rs +32 -10
  20. package/native/ocx-child/src/state.rs +2 -1
  21. package/native/ocx-child/src/toml_surgeon.rs +183 -72
  22. package/package.json +2 -2
  23. package/src/adapters/agy-acp/acp.ts +202 -0
  24. package/src/adapters/agy-acp/adapter.ts +554 -0
  25. package/src/adapters/agy-acp/binary.ts +79 -0
  26. package/src/adapters/agy-acp/options.ts +163 -0
  27. package/src/adapters/agy-acp/output-redaction.ts +270 -0
  28. package/src/adapters/agy-acp/policy.ts +105 -0
  29. package/src/adapters/agy-acp/process.ts +218 -0
  30. package/src/adapters/anthropic/account-metadata.ts +4 -1
  31. package/src/adapters/anthropic/advisor-tool.ts +43 -9
  32. package/src/adapters/anthropic/client-identity.ts +2 -0
  33. package/src/adapters/anthropic.ts +102 -14
  34. package/src/adapters/antigravity-refusal.ts +5 -1
  35. package/src/adapters/base.ts +25 -2
  36. package/src/adapters/claude-cli/adapter.ts +1 -0
  37. package/src/adapters/claude-cli/usage-admission.ts +12 -9
  38. package/src/adapters/codebuddy/adapter.ts +1 -0
  39. package/src/adapters/command-code.ts +2 -2
  40. package/src/adapters/cursor/http1-bidi.ts +7 -2
  41. package/src/adapters/cursor/live-transport.ts +2 -0
  42. package/src/adapters/cursor/request-builder.ts +4 -4
  43. package/src/adapters/cursor/tool-naming.ts +5 -5
  44. package/src/adapters/cursor/transport-retry.ts +14 -8
  45. package/src/adapters/cursor/transport.ts +2 -0
  46. package/src/adapters/cursor.ts +8 -2
  47. package/src/adapters/google-error-details.ts +105 -0
  48. package/src/adapters/google-errors.ts +183 -31
  49. package/src/adapters/google-http.ts +66 -22
  50. package/src/adapters/google-truncation.ts +48 -3
  51. package/src/adapters/google-vertex-endpoint.ts +12 -1
  52. package/src/adapters/google.ts +54 -26
  53. package/src/adapters/kiro/adapter.ts +39 -38
  54. package/src/adapters/kiro/stream.ts +59 -9
  55. package/src/adapters/kiro-retry.ts +5 -3
  56. package/src/adapters/m365-copilot/LICENSE +21 -0
  57. package/src/adapters/m365-copilot/fenced.ts +745 -0
  58. package/src/adapters/m365-copilot/images.ts +89 -0
  59. package/src/adapters/m365-copilot/tools.ts +284 -0
  60. package/src/adapters/m365-copilot/transport.ts +232 -0
  61. package/src/adapters/m365-copilot.ts +143 -0
  62. package/src/adapters/openai-chat/tool-schema.ts +2 -2
  63. package/src/adapters/openai-responses/passthrough.ts +1 -0
  64. package/src/adapters/openai-responses/reasoning.ts +23 -3
  65. package/src/adapters/physical-send.ts +11 -4
  66. package/src/adapters/qoder/adapter.ts +17 -3
  67. package/src/adapters/registry.ts +15 -1
  68. package/src/adapters/zed.ts +2 -1
  69. package/src/advisor/consult.ts +1 -0
  70. package/src/bridge/response-json.ts +6 -2
  71. package/src/bridge/sse.ts +21 -9
  72. package/src/chat/inbound.ts +11 -8
  73. package/src/chat/outbound.ts +28 -7
  74. package/src/claude/context-windows.ts +32 -8
  75. package/src/claude/desktop-3p.ts +18 -14
  76. package/src/claude/desktop-picker-platform.ts +1 -1
  77. package/src/claude/desktop-picker.ts +3 -3
  78. package/src/claude/inbound-content-options.ts +11 -1
  79. package/src/claude/intercept/picker-ca-cleanup.ts +17 -5
  80. package/src/claude/intercept/picker-ca.ts +162 -27
  81. package/src/claude/intercept/picker-trust-linux.ts +411 -0
  82. package/src/claude/intercept/picker-trust.ts +35 -3
  83. package/src/claude/intercept/runtime.ts +2 -2
  84. package/src/claude/subagent-force-status.ts +24 -5
  85. package/src/claude/subscription-reserve.ts +87 -0
  86. package/src/cli/account-api.ts +3 -0
  87. package/src/cli/account-auth.ts +65 -11
  88. package/src/cli/account-extended.ts +1 -1
  89. package/src/cli/account-next-actions.ts +4 -1
  90. package/src/cli/account-policy-dto.ts +1 -1
  91. package/src/cli/account-policy.ts +6 -3
  92. package/src/cli/account-probe.ts +66 -0
  93. package/src/cli/account.ts +8 -2
  94. package/src/cli/capabilities-accounts.ts +8 -1
  95. package/src/cli/capabilities-agents-routing.ts +2 -2
  96. package/src/cli/capabilities-base.ts +4 -4
  97. package/src/cli/capabilities-integrations.ts +44 -4
  98. package/src/cli/capabilities-provider-models.ts +6 -0
  99. package/src/cli/claude-context-settings.ts +60 -0
  100. package/src/cli/claude-desktop.ts +2 -2
  101. package/src/cli/claude.ts +15 -7
  102. package/src/cli/client-start-fence.ts +64 -1
  103. package/src/cli/combo-result.ts +1 -0
  104. package/src/cli/combo-stats.ts +1 -1
  105. package/src/cli/combo.ts +19 -2
  106. package/src/cli/config-command.ts +21 -8
  107. package/src/cli/connect.ts +16 -0
  108. package/src/cli/cross-home-owner.ts +65 -18
  109. package/src/cli/dispatch.ts +4 -0
  110. package/src/cli/gateway-client-command.ts +128 -0
  111. package/src/cli/index.ts +98 -97
  112. package/src/cli/init.ts +20 -4
  113. package/src/cli/integrations.ts +23 -3
  114. package/src/cli/launcher-context.ts +12 -1
  115. package/src/cli/link.ts +24 -5
  116. package/src/cli/models-runtime-subcommands.ts +1 -0
  117. package/src/cli/models-runtime.ts +32 -0
  118. package/src/cli/start-owner-fence.ts +5 -2
  119. package/src/cli/status.ts +3 -3
  120. package/src/cli/stop-client-process.ts +51 -0
  121. package/src/cli/stop-restore.ts +383 -36
  122. package/src/cli/sync-command.ts +2 -2
  123. package/src/cli/uninstall-client-state.ts +7 -0
  124. package/src/client/connect.ts +72 -13
  125. package/src/client/hub-client.ts +38 -0
  126. package/src/client/hub-relay.ts +61 -36
  127. package/src/client/hub-session.ts +106 -0
  128. package/src/client/lifecycle-lock.ts +6 -1
  129. package/src/client/link-relay.ts +2 -1
  130. package/src/client/machine-listener.ts +60 -1
  131. package/src/client/runtime-restart.ts +1 -0
  132. package/src/client/runtime.ts +104 -34
  133. package/src/client/state.ts +11 -0
  134. package/src/client/stop-darwin-process.ts +73 -0
  135. package/src/client/stop-file-routing.ts +49 -0
  136. package/src/client/stop-native-handoff.ts +108 -0
  137. package/src/client/stop-routing.ts +41 -7
  138. package/src/client/stop-teardown-owner.ts +173 -0
  139. package/src/client/sync-runtime.ts +23 -4
  140. package/src/clients/config-export/opencode-wire.ts +24 -0
  141. package/src/clients/config-export.ts +28 -19
  142. package/src/codex/auth-api/login-flow.ts +68 -33
  143. package/src/codex/auth-api/main-account-probe.ts +3 -3
  144. package/src/codex/auth-api/pool-quota-probe.ts +8 -7
  145. package/src/codex/auth-api/routes.ts +1 -1
  146. package/src/codex/catalog/aggregation.ts +22 -10
  147. package/src/codex/catalog/gather-capture.ts +11 -2
  148. package/src/codex/catalog/m365-copilot-models.ts +52 -0
  149. package/src/codex/catalog/provider-models.ts +126 -53
  150. package/src/codex/catalog/routed-gather.ts +26 -12
  151. package/src/codex/catalog-admission.ts +4 -6
  152. package/src/codex/catalog-auto-refresh.ts +4 -2
  153. package/src/codex/catalog-self-heal.ts +4 -2
  154. package/src/codex/control-plane-models.ts +6 -0
  155. package/src/codex/convergence.ts +10 -0
  156. package/src/codex/desktop-app/picker-freshness.ts +3 -14
  157. package/src/codex/desktop-app/types.ts +6 -0
  158. package/src/codex/desktop-app/windows-command-payload.ts +9 -0
  159. package/src/codex/desktop-app/windows.ts +20 -12
  160. package/src/codex/desktop-compatibility/installed-build.ts +61 -58
  161. package/src/codex/desktop-compatibility/runtime-ownership.ts +11 -5
  162. package/src/codex/desktop-compatibility/runtime.ts +51 -14
  163. package/src/codex/desktop-compatibility/windows-activation-source.ts +28 -13
  164. package/src/codex/desktop-compatibility/windows-package-command.ts +73 -33
  165. package/src/codex/desktop-compatibility/windows-package-launch.ts +41 -9
  166. package/src/codex/desktop-compatibility/windows-package-proof.ts +104 -0
  167. package/src/codex/inject/config-toml.ts +67 -73
  168. package/src/codex/inject/plan.ts +11 -10
  169. package/src/codex/inject/remove.ts +4 -1
  170. package/src/codex/inject.ts +1 -0
  171. package/src/codex/journal-config-restore.ts +31 -4
  172. package/src/codex/journal.ts +16 -4
  173. package/src/codex/model-cache.ts +98 -27
  174. package/src/codex/native-residue.ts +14 -13
  175. package/src/codex/paths.ts +65 -28
  176. package/src/codex/quota-observation-freshness.ts +4 -0
  177. package/src/codex/quota.ts +71 -8
  178. package/src/codex/routing/selection.ts +32 -8
  179. package/src/combos/capability-policy.ts +31 -0
  180. package/src/combos/failover.ts +82 -74
  181. package/src/combos/identifiers.ts +2 -2
  182. package/src/combos/index.ts +3 -0
  183. package/src/combos/jev-model-backend.ts +12 -4
  184. package/src/combos/jev-session-pin-config.ts +22 -9
  185. package/src/combos/jev.ts +15 -4
  186. package/src/combos/request-capability.ts +214 -0
  187. package/src/combos/request.ts +22 -15
  188. package/src/combos/resolve.ts +5 -2
  189. package/src/combos/suggestion-channel.ts +89 -0
  190. package/src/combos/types.ts +14 -1
  191. package/src/config/account-auto-pause-revisions.ts +33 -10
  192. package/src/config/atomic-write.ts +1 -1
  193. package/src/config/codex-ws-incremental-setting.ts +34 -0
  194. package/src/config/diagnostics.ts +47 -8
  195. package/src/config/live-topology.ts +4 -2
  196. package/src/config/load-degrade.ts +96 -2
  197. package/src/config/mutation-lock.ts +7 -3
  198. package/src/config/paths.ts +3 -0
  199. package/src/config/pending-teardown.ts +19 -3
  200. package/src/config/process-state.ts +30 -12
  201. package/src/config/provider-validation.ts +10 -0
  202. package/src/config/salvage.ts +2 -2
  203. package/src/config/schema/account-auto-pause.ts +15 -1
  204. package/src/config/schema/agy-acp-references.ts +257 -0
  205. package/src/config/schema/config-schema.ts +32 -0
  206. package/src/config/schema/leaf-validators.ts +42 -0
  207. package/src/config/schema/subscription-reserve.ts +33 -0
  208. package/src/config/windows-process-command-line.ts +27 -9
  209. package/src/config.ts +6 -0
  210. package/src/generated/compatibility-version.json +806 -402
  211. package/src/images/loop.ts +79 -39
  212. package/src/integrations/catalog-refresh.ts +19 -1
  213. package/src/integrations/gateway-clients/agy.ts +340 -0
  214. package/src/integrations/gateway-clients/antigravity.ts +224 -0
  215. package/src/integrations/gateway-clients/index.ts +89 -0
  216. package/src/integrations/gateway-clients/io.ts +278 -0
  217. package/src/integrations/gateway-clients/types.ts +80 -0
  218. package/src/integrations/route-intent-disconnect.ts +37 -21
  219. package/src/lib/app-owned-memory-stores.ts +9 -0
  220. package/src/lib/cloud-code-appeal-link.ts +30 -0
  221. package/src/lib/errors.ts +32 -0
  222. package/src/lib/executor-physical-send-receipt.ts +42 -0
  223. package/src/lib/failure-detail.ts +1 -0
  224. package/src/lib/gcp-adc.ts +5 -0
  225. package/src/lib/http-date.ts +91 -0
  226. package/src/lib/lab-passive-linker-registration.ts +2 -1
  227. package/src/lib/local-chat-completion.ts +13 -3
  228. package/src/lib/local-internal-call-capability.ts +1 -3
  229. package/src/lib/messages-error-body.ts +2 -1
  230. package/src/lib/outbound-credential-registry.ts +40 -4
  231. package/src/lib/pinned-http.ts +7 -2
  232. package/src/lib/process-control.ts +1 -0
  233. package/src/lib/provider-egress.ts +16 -0
  234. package/src/lib/provider-outbound.ts +3 -0
  235. package/src/lib/redact-folding.ts +12 -3
  236. package/src/lib/redact.ts +37 -19
  237. package/src/lib/request-execution-budget.ts +241 -32
  238. package/src/lib/request-peer-scope.ts +64 -0
  239. package/src/lib/response-send-readings.ts +41 -0
  240. package/src/lib/state-store-registrations.ts +5 -0
  241. package/src/lib/tool-envelope-echo-filter.ts +33 -5
  242. package/src/lib/upstream-condition.ts +10 -3
  243. package/src/lib/upstream-retry.ts +95 -20
  244. package/src/lib/windows-secret-acl.ts +24 -7
  245. package/src/link/child-activity.ts +60 -4
  246. package/src/link/codex-settings.ts +2 -1
  247. package/src/link/relay-auth.ts +1 -0
  248. package/src/link/route-rounds.ts +32 -9
  249. package/src/link/status-projection.ts +42 -5
  250. package/src/link/supervisor.ts +96 -11
  251. package/src/link/tunnel-history.ts +5 -0
  252. package/src/oauth/account-auto-pause-policy.ts +72 -19
  253. package/src/oauth/account-auto-pause.ts +40 -16
  254. package/src/oauth/anthropic-account-refusal.ts +7 -0
  255. package/src/oauth/anthropic-continuity.ts +70 -9
  256. package/src/oauth/anthropic-identity.ts +75 -11
  257. package/src/oauth/anthropic-login-slot.ts +258 -0
  258. package/src/oauth/anthropic-routing.ts +24 -9
  259. package/src/oauth/anthropic-send-ownership.ts +4 -3
  260. package/src/oauth/anthropic.ts +30 -11
  261. package/src/oauth/health.ts +7 -2
  262. package/src/oauth/index.ts +50 -48
  263. package/src/oauth/key-providers.ts +2 -0
  264. package/src/oauth/login-cli.ts +11 -0
  265. package/src/oauth/login-flow-state.ts +10 -4
  266. package/src/oauth/m365-copilot-browser.ts +222 -0
  267. package/src/oauth/m365-copilot-web-session.ts +25 -0
  268. package/src/oauth/m365-copilot.ts +57 -0
  269. package/src/oauth/model-discovery-auth.ts +5 -0
  270. package/src/oauth/plan.ts +44 -0
  271. package/src/oauth/pool-kernel.ts +22 -8
  272. package/src/oauth/pool-settings-capability.ts +14 -3
  273. package/src/oauth/reauth-precheck.ts +27 -0
  274. package/src/oauth/store-anthropic-instance.ts +3 -1
  275. package/src/oauth/store.ts +121 -23
  276. package/src/oauth/types.ts +27 -2
  277. package/src/protocols/codecs/chat-ir.ts +7 -4
  278. package/src/protocols/codecs/gemini-interactions.ts +770 -0
  279. package/src/protocols/codecs/gemini.ts +470 -0
  280. package/src/protocols/contract.ts +2 -0
  281. package/src/protocols/encoders/adapter-events.ts +5 -3
  282. package/src/protocols/encoders/chat.ts +23 -7
  283. package/src/protocols/settings.ts +3 -0
  284. package/src/providers/account-quota-disk.ts +26 -8
  285. package/src/providers/api-key-pause.ts +2 -2
  286. package/src/providers/api-key-response-ownership.ts +14 -4
  287. package/src/providers/claude-cli-usage-state.ts +1 -0
  288. package/src/providers/claude-cli-usage.ts +24 -7
  289. package/src/providers/default-aliases.ts +11 -5
  290. package/src/providers/derive.ts +5 -1
  291. package/src/providers/fastwire.ts +6 -5
  292. package/src/providers/free-directory.ts +2 -2
  293. package/src/providers/google-vertex-location.ts +2 -1
  294. package/src/providers/google-vertex-model-discovery.ts +22 -0
  295. package/src/providers/key-failover.ts +18 -23
  296. package/src/providers/m365-copilot-discovery-fetch.ts +17 -0
  297. package/src/providers/m365-copilot-discovery.ts +68 -0
  298. package/src/providers/m365-copilot-models.ts +32 -0
  299. package/src/providers/model-rename-fields.ts +6 -0
  300. package/src/providers/new-model-policy-runtime.ts +27 -6
  301. package/src/providers/openai-forward-destination.ts +19 -0
  302. package/src/providers/openai-tiers-destination.ts +3 -19
  303. package/src/providers/quota/account-cache.ts +183 -27
  304. package/src/providers/quota/anthropic-account-quota.ts +21 -17
  305. package/src/providers/quota/anthropic-cooldown-recovery.ts +57 -27
  306. package/src/providers/quota/anthropic-decision-windows.ts +7 -3
  307. package/src/providers/quota/anthropic-usage-windows.ts +34 -4
  308. package/src/providers/quota/antigravity-account-probe.ts +165 -0
  309. package/src/providers/quota/antigravity.ts +71 -3
  310. package/src/providers/quota/vendor-probes-oauth.ts +52 -28
  311. package/src/providers/quota-decision-publication.ts +1 -1
  312. package/src/providers/quota-decision-snapshot.ts +4 -1
  313. package/src/providers/quota-types.ts +2 -0
  314. package/src/providers/quota.ts +8 -7
  315. package/src/providers/registry/agy-acp-models.ts +3 -0
  316. package/src/providers/registry/entries-core.ts +9 -0
  317. package/src/providers/registry/entries-extended.ts +60 -0
  318. package/src/providers/registry/model-seeds.ts +51 -0
  319. package/src/providers/request-pacing.ts +37 -7
  320. package/src/providers/service-tier.ts +2 -0
  321. package/src/providers/xai-privacy-mode.ts +52 -0
  322. package/src/remote/hub-management-relay.ts +74 -0
  323. package/src/responses/id-limits.ts +2 -0
  324. package/src/responses/input-media.ts +15 -3
  325. package/src/responses/parser-tools.ts +74 -11
  326. package/src/responses/parser.ts +16 -14
  327. package/src/responses/provider-opaque-metadata.ts +10 -0
  328. package/src/responses/reasoning-envelope.ts +3 -0
  329. package/src/responses/schema.ts +2 -3
  330. package/src/responses/spill-store.ts +5 -3
  331. package/src/responses/state/connection-scope.ts +232 -0
  332. package/src/responses/state/entry-types.ts +47 -0
  333. package/src/responses/state/snapshot-codec.ts +75 -14
  334. package/src/responses/state/snapshot-select.ts +2 -0
  335. package/src/responses/state/spill-codec.ts +59 -0
  336. package/src/responses/state/spill-queue.ts +11 -2
  337. package/src/responses/state.ts +178 -159
  338. package/src/router.ts +2 -6
  339. package/src/routing/compatibility/behavior.ts +6 -2
  340. package/src/routing/compatibility/subject.ts +17 -12
  341. package/src/routing/machine-weighted-routing.ts +58 -0
  342. package/src/server/advisor-admission-scope.ts +15 -7
  343. package/src/server/auth-cors.ts +27 -0
  344. package/src/server/chat-completions.ts +37 -17
  345. package/src/server/chat-native-eligibility.ts +21 -0
  346. package/src/server/chat-native.ts +15 -6
  347. package/src/server/claude-messages.ts +54 -6
  348. package/src/server/credential-recovery-attempt.ts +32 -0
  349. package/src/server/effort-policy.ts +6 -3
  350. package/src/server/gemini-inbound.ts +267 -0
  351. package/src/server/gemini-interactions-inbound.ts +229 -0
  352. package/src/server/gemini-interactions-store.ts +129 -0
  353. package/src/server/gemini-native-catalog.ts +64 -0
  354. package/src/server/gemini-native-log.ts +33 -0
  355. package/src/server/gemini-native-paths.ts +88 -0
  356. package/src/server/gemini-native-wire.ts +201 -0
  357. package/src/server/gemini-native.ts +218 -0
  358. package/src/server/grok-upstream-envelope-echo.ts +8 -2
  359. package/src/server/hub-relay-auth.ts +87 -0
  360. package/src/server/hub-usage-windows.ts +135 -0
  361. package/src/server/hub-usage.ts +16 -3
  362. package/src/server/inbound-body-admission.ts +2 -1
  363. package/src/server/index/anthropic-model-listing.ts +75 -0
  364. package/src/server/index/gemini-routes.ts +147 -0
  365. package/src/server/index/link-management.ts +3 -22
  366. package/src/server/index/link-relay-sessions.ts +71 -13
  367. package/src/server/index/link-websocket.ts +2 -0
  368. package/src/server/index/passive-management-read.ts +55 -0
  369. package/src/server/index/serve-options.ts +93 -107
  370. package/src/server/index/websocket-handler.ts +15 -2
  371. package/src/server/index.ts +10 -0
  372. package/src/server/inference/client-encoder-delivery.ts +2 -1
  373. package/src/server/inference/context.ts +33 -6
  374. package/src/server/management/agent-settings-routes.ts +33 -16
  375. package/src/server/management/claude-code-settings-patch.ts +6 -0
  376. package/src/server/management/combo-routes.ts +21 -1
  377. package/src/server/management/combo-suggestion-routes.ts +212 -0
  378. package/src/server/management/config-routes.ts +12 -4
  379. package/src/server/management/context.ts +2 -0
  380. package/src/server/management/gateway-client-routes.ts +62 -0
  381. package/src/server/management/integration-routes.ts +5 -0
  382. package/src/server/management/link-routes.ts +5 -1
  383. package/src/server/management/m365-copilot-provider-probe.ts +23 -0
  384. package/src/server/management/model-routes.ts +32 -2
  385. package/src/server/management/model-rows.ts +36 -3
  386. package/src/server/management/oauth-account-routes.ts +68 -15
  387. package/src/server/management/protocol-settings-patch.ts +1 -0
  388. package/src/server/management/provider-omitted-fields.ts +25 -0
  389. package/src/server/management/provider-overwrite-carry.ts +33 -8
  390. package/src/server/management/provider-routes.ts +10 -16
  391. package/src/server/management/request-history-routes.ts +2 -2
  392. package/src/server/management/route-registry.ts +10 -0
  393. package/src/server/management/shared.ts +118 -30
  394. package/src/server/management/sibling-guard.ts +2 -1
  395. package/src/server/management/system-routes.ts +6 -0
  396. package/src/server/management-auth.ts +8 -1
  397. package/src/server/messages-native-scope.ts +19 -0
  398. package/src/server/messages-native.ts +156 -59
  399. package/src/server/messages-shared.ts +6 -0
  400. package/src/server/models-capabilities.ts +24 -0
  401. package/src/server/native-chat-bridge.ts +259 -0
  402. package/src/server/ollama-inbound.ts +36 -184
  403. package/src/server/passive-route-linker.ts +3 -1
  404. package/src/server/port-reclaim.ts +48 -4
  405. package/src/server/proxy-liveness.ts +79 -22
  406. package/src/server/relay.ts +16 -9
  407. package/src/server/request-log-account-rotation.ts +2 -1
  408. package/src/server/request-log-attempt-recovery.ts +24 -2
  409. package/src/server/request-log-attempt-usage.ts +5 -4
  410. package/src/server/request-log-committed-terminal.ts +87 -0
  411. package/src/server/request-log-failure-attribution.ts +3 -3
  412. package/src/server/request-log-failure-detail.ts +34 -0
  413. package/src/server/request-log-key-failure.ts +27 -0
  414. package/src/server/request-log-terminal-status.ts +25 -12
  415. package/src/server/request-log.ts +59 -63
  416. package/src/server/responses/adapter-continuation.ts +77 -44
  417. package/src/server/responses/adapter-delivery.ts +47 -22
  418. package/src/server/responses/adapter-dispatch.ts +150 -149
  419. package/src/server/responses/advisor-retention.ts +12 -4
  420. package/src/server/responses/advisor-slot.ts +97 -2
  421. package/src/server/responses/agent-task-recovery.ts +44 -11
  422. package/src/server/responses/agy-acp-preflight.ts +41 -0
  423. package/src/server/responses/anthropic-image-context.ts +44 -0
  424. package/src/server/responses/antigravity-validation-refusal.ts +25 -1
  425. package/src/server/responses/buffered-sse-json.ts +18 -1
  426. package/src/server/responses/codex-ws-correlation.ts +5 -2
  427. package/src/server/responses/codex-ws-exchange.ts +91 -8
  428. package/src/server/responses/codex-ws-incremental.ts +136 -0
  429. package/src/server/responses/codex-ws-pool.ts +22 -8
  430. package/src/server/responses/codex-ws-request.ts +5 -0
  431. package/src/server/responses/codex-ws-send-accounting.ts +8 -0
  432. package/src/server/responses/codex-ws-session.ts +14 -0
  433. package/src/server/responses/codex-ws-wire.ts +44 -22
  434. package/src/server/responses/combo-admission-snapshot.ts +93 -0
  435. package/src/server/responses/combo-required-tool-stream.ts +16 -4
  436. package/src/server/responses/combo-selection-keepalive.ts +5 -0
  437. package/src/server/responses/combo-stream-preflight.ts +182 -73
  438. package/src/server/responses/compact-response-body.ts +27 -0
  439. package/src/server/responses/compact.ts +174 -121
  440. package/src/server/responses/compaction-recovery.ts +7 -0
  441. package/src/server/responses/core-codex-account.ts +88 -62
  442. package/src/server/responses/core-combo-failure.ts +15 -0
  443. package/src/server/responses/core-combo-native.ts +12 -1
  444. package/src/server/responses/core-combo.ts +340 -94
  445. package/src/server/responses/core-normalize.ts +19 -12
  446. package/src/server/responses/core-opaque-recovery.ts +15 -4
  447. package/src/server/responses/core-options.ts +50 -5
  448. package/src/server/responses/core-pipeline.ts +11 -0
  449. package/src/server/responses/core.ts +7 -1
  450. package/src/server/responses/empty-completion-guard.ts +21 -7
  451. package/src/server/responses/estimated-usage.ts +2 -1
  452. package/src/server/responses/fetch-helpers.ts +95 -19
  453. package/src/server/responses/history-slim.ts +204 -0
  454. package/src/server/responses/hosted-advisor-spend.ts +49 -0
  455. package/src/server/responses/image-context-recovery.ts +199 -0
  456. package/src/server/responses/input-admission.ts +36 -11
  457. package/src/server/responses/jev-model-invoke.ts +23 -16
  458. package/src/server/responses/non-replayable-error.ts +12 -2
  459. package/src/server/responses/passthrough-build-error.ts +5 -3
  460. package/src/server/responses/passthrough-delivery.ts +74 -33
  461. package/src/server/responses/passthrough-dispatch.ts +170 -197
  462. package/src/server/responses/policy-fallback.ts +7 -2
  463. package/src/server/responses/policy-request-scope.ts +36 -2
  464. package/src/server/responses/replay-owner.ts +20 -0
  465. package/src/server/responses/request-prepare.ts +97 -16
  466. package/src/server/responses/request-send-budget.ts +97 -25
  467. package/src/server/responses/request-sidecar-auth.ts +138 -65
  468. package/src/server/responses/request-spend-target.ts +13 -1
  469. package/src/server/responses/request-spend.ts +228 -47
  470. package/src/server/responses/request-transport.ts +395 -70
  471. package/src/server/responses/run-turn-execution.ts +40 -9
  472. package/src/server/responses/sidecar-execution.ts +214 -67
  473. package/src/server/responses/sidecar-send-budget.ts +9 -9
  474. package/src/server/responses/terminal-guard.ts +35 -9
  475. package/src/server/responses/ws-upstream.ts +27 -6
  476. package/src/server/responses-phase-inference.ts +32 -9
  477. package/src/server/responses-terminal-repair.ts +14 -35
  478. package/src/server/system-env.ts +8 -5
  479. package/src/server/ws-bridge.ts +23 -17
  480. package/src/service/health-sentinel-linux.ts +16 -7
  481. package/src/service/systemd.ts +11 -2
  482. package/src/service/windows-checked-stop-live.ts +60 -55
  483. package/src/service/windows-checked-stop.ts +29 -11
  484. package/src/service/windows-guarded-manager.ts +14 -26
  485. package/src/service/windows-process-evidence.ts +82 -74
  486. package/src/service/windows-process-native.ts +69 -20
  487. package/src/service/windows-service-stop.ts +14 -12
  488. package/src/service/windows-stop-binding.ts +14 -5
  489. package/src/service/windows-stop-confirm.ts +1 -1
  490. package/src/service/windows-task-instance-stop.ts +98 -0
  491. package/src/service/windows-taskxml.ts +30 -7
  492. package/src/sidecar/anthropic-binding.ts +1 -1
  493. package/src/stall-timeout.ts +30 -0
  494. package/src/telemetry/aggregate.ts +6 -3
  495. package/src/types/account-auto-pause.ts +19 -1
  496. package/src/types/accounts.ts +21 -0
  497. package/src/types/anthropic-account-pool.ts +1 -1
  498. package/src/types/combo-capability-policy.ts +19 -0
  499. package/src/types/config.ts +22 -2
  500. package/src/types/provider.ts +42 -8
  501. package/src/types/request.ts +15 -0
  502. package/src/types/tools.ts +22 -5
  503. package/src/types/wire.ts +1 -0
  504. package/src/types.ts +4 -0
  505. package/src/update/check-types.ts +2 -0
  506. package/src/update/job.ts +8 -3
  507. package/src/update/managed-release.ts +6 -0
  508. package/src/update/orchestrated-entry.ts +13 -4
  509. package/src/update/refresh-scheduler.ts +17 -7
  510. package/src/usage/attempt-delivery.ts +6 -0
  511. package/src/usage/cache-provenance.ts +71 -0
  512. package/src/usage/cost.ts +216 -27
  513. package/src/usage/credit-billing.ts +88 -0
  514. package/src/usage/jev-stats.ts +13 -9
  515. package/src/usage/log.ts +5 -33
  516. package/src/usage/summary.ts +8 -43
  517. package/src/usage/user-cost-overlays.ts +13 -1
  518. package/src/vision/index.ts +8 -3
  519. package/src/vision/plan.ts +28 -14
  520. package/src/vision/routed-describe.ts +24 -36
  521. package/src/web-search/header-deadline.ts +14 -3
  522. package/src/web-search/index.ts +6 -4
  523. package/src/web-search/loop.ts +240 -78
  524. package/src/web-search/progress-stream.ts +29 -2
  525. package/src/web-search/run-turn-loop.ts +5 -1
  526. package/gui/dist/assets/App-BGP8I0V4.css +0 -1
  527. package/gui/dist/assets/App-BRExzhwL.js +0 -60
  528. package/gui/dist/assets/Tray-DHCWAn8V.js +0 -1
  529. package/gui/dist/assets/brand-mark-C70PuQ3j.js +0 -1
  530. package/gui/dist/assets/index-DJxM-imn.css +0 -2
  531. package/gui/dist/assets/index-Dy1jIGty.js +0 -138
  532. package/gui/dist/classic/assets/App-B4j-Txmb.css +0 -1
  533. package/gui/dist/classic/assets/App-CaC-E6Vl.js +0 -59
  534. package/gui/dist/classic/assets/Tray-BG253fiL.js +0 -1
  535. package/gui/dist/classic/assets/index-CR_AThOp.js +0 -138
  536. package/gui/dist/classic/assets/quota-summary-B7KQPpEC.js +0 -1
@@ -12,22 +12,15 @@
12
12
  * (unreadable) instead of silently taking the new process's identity;
13
13
  * - Schedule PID: QueryServiceStatusEx on x64, else sc.exe queryex Schedule run from the
14
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.
15
+ * - terminate and watch: native process handles are required. No PID-only termination
16
+ * is attempted when the native API is unavailable.
25
17
  */
26
18
  import { execFile } from "node:child_process";
27
19
  import { existsSync } from "node:fs";
28
20
  import { join } from "node:path";
29
21
 
30
22
  import { resolveTrustedWindowsPowerShellExe, resolveTrustedWindowsSystemDirectory } from "../lib/windows-elevation";
23
+ import { windowsLauncherVbsPath, windowsServiceScriptPath } from "./state";
31
24
  import type { WindowsProcessEntry } from "./windows-guarded-manager";
32
25
  import {
33
26
  windowsProcessNative,
@@ -60,8 +53,12 @@ export type WindowsStopProcessEntry = WindowsProcessEntry & { startTime: number
60
53
  const SNAPSHOT_MAX_BUFFER = 16 * 1024 * 1024;
61
54
  const SMALL_MAX_BUFFER = 64 * 1024;
62
55
  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;
56
+ /**
57
+ * Owner reads stop being admitted this long before the snapshot's cap, counted from the
58
+ * helper's own process start. It covers one in-flight 1 s CIM call plus serialization and
59
+ * exit, so optional owner evidence cannot turn a readable table into a timed-out one.
60
+ */
61
+ export const SNAPSHOT_OWNER_RESERVE_MS = 2_000;
65
62
 
66
63
  function trustedProgram(program: WindowsEvidenceCommand["program"]): string {
67
64
  if (program === "powershell") return resolveTrustedWindowsPowerShellExe();
@@ -99,11 +96,72 @@ function powershellArgs(script: string): string[] {
99
96
  return ["-NoProfile", "-NoLogo", "-NonInteractive", "-Command", script];
100
97
  }
101
98
 
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";
99
+ /**
100
+ * Owner enrichment admits at most 32 candidates within 1.5 s; individual CIM calls also
101
+ * have a 1 s operation cap. Unqueried owners stay unknown and every process row survives.
102
+ * No owner read starts later than `timeoutMs - SNAPSHOT_OWNER_RESERVE_MS` after the helper
103
+ * process started: a cold PowerShell start and first CIM query can use most of the cap on
104
+ * a hosted runner, and the 1.5 s loop budget alone did not count that time.
105
+ * Owner reads prioritize this home's complete launcher/script tokens before other possible
106
+ * wrapper candidates. A fresh CIM read after GetOwnerSid binds that owner to the original
107
+ * creation time; a reused PID cannot prove a foreign owner.
108
+ */
109
+ export function windowsProcessSnapshotScript(timeoutMs: number): string {
110
+ // A cap that is not a finite number admits no owner read; it never reaches the script text.
111
+ const ownerCutoffMs = Number.isFinite(timeoutMs) ? Math.max(0, Math.floor(timeoutMs) - SNAPSHOT_OWNER_RESERVE_MS) : 0;
112
+ // The helper's own command line must not contain either installation path as a token.
113
+ const paths = [windowsLauncherVbsPath(), windowsServiceScriptPath()]
114
+ .map(path => Buffer.from(path, "utf8").toString("base64"));
115
+ return [
116
+ "[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false);",
117
+ "$currentSid = $null; try { $currentSid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value } catch { $currentSid = $null };",
118
+ "$tokens = @('" + paths.join("','") + "') | ForEach-Object { [regex]::Escape([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($_))) };",
119
+ "$homePath = '(?:^|[\\s\\x22\\x27])(?:' + ($tokens -join '|') + ')(?=$|[\\s\\x22\\x27])';",
120
+ "$rows = @(Get-CimInstance Win32_Process -ErrorAction Stop);",
121
+ "$priority = @($rows | Where-Object { $_.CommandLine -match $homePath });",
122
+ "$fallback = @($rows | Where-Object { $_.CommandLine -notmatch $homePath -and",
123
+ " (($_.Name -match '^(wscript|cscript|cmd)\\.exe$') -or (-not $_.Name) -or ($_.CommandLine -like '*opencodex-service*')) });",
124
+ "$ownerBudget = @{ Remaining = 32; Clock = [Diagnostics.Stopwatch]::StartNew();",
125
+ " Until = [Diagnostics.Process]::GetCurrentProcess().StartTime.ToUniversalTime().AddMilliseconds(" + ownerCutoffMs + ") };",
126
+ "$owners = @{};",
127
+ "foreach ($process in ($priority + $fallback)) {",
128
+ " if (!$currentSid -or $ownerBudget.Remaining -le 0 -or $ownerBudget.Clock.ElapsedMilliseconds -ge 1500",
129
+ " -or [DateTime]::UtcNow -ge $ownerBudget.Until) { break };",
130
+ " $ownerBudget.Remaining--;",
131
+ " try {",
132
+ " $owner = Invoke-CimMethod -InputObject $process -MethodName GetOwnerSid -OperationTimeoutSec 1 -ErrorAction Stop;",
133
+ " if ($ownerBudget.Clock.ElapsedMilliseconds -ge 1500 -or [DateTime]::UtcNow -ge $ownerBudget.Until) { break };",
134
+ " $after = Get-CimInstance -InputObject $process -OperationTimeoutSec 1 -ErrorAction Stop;",
135
+ " $owners[$process.ProcessId] = @{ Sid = $owner.Sid; ReturnValue = $owner.ReturnValue;",
136
+ " CreationDate = if ($after.CreationDate) { $after.CreationDate.ToUniversalTime().ToString('o') } else { $null } };",
137
+ " } catch { continue }",
138
+ "};",
139
+ "$rows | Select-Object ProcessId,ParentProcessId,Name,CommandLine,",
140
+ "@{Name='CreationDate';Expression={ if ($_.CreationDate) { $_.CreationDate.ToUniversalTime().ToString('o') } else { $null } }},",
141
+ "@{Name='CurrentUserSid';Expression={ $currentSid }},",
142
+ "@{Name='Owner';Expression={ $owners[$_.ProcessId] }} | ConvertTo-Json -Depth 3 -Compress",
143
+ ].join(" ");
144
+ }
145
+
146
+ const SID_PATTERN = /^S-1-\d+(?:-\d+){1,15}$/i;
147
+ const USER_ACCOUNT_SID_PATTERN = /^S-1-(?:5-21|12-1)(?:-\d{1,10}){4}$/i;
148
+
149
+ function foreignProcessOwner(record: Record<string, unknown>, startTime: number | null): boolean | null {
150
+ const sid = (value: unknown): string | null => typeof value === "string" && value.length <= 256 && SID_PATTERN.test(value)
151
+ && value.split("-").slice(3).every(part => Number(part) <= 0xffff_ffff)
152
+ ? value.toUpperCase() : null;
153
+ const current = sid(record.CurrentUserSid);
154
+ const owner = record.Owner;
155
+ if (startTime === null || current === null || typeof owner !== "object" || owner === null) return null;
156
+ const evidence = owner as Record<string, unknown>;
157
+ const observed = sid(evidence.Sid);
158
+ if (evidence.ReturnValue !== 0 || observed === null || evidence.CreationDate !== record.CreationDate) return null;
159
+ if (observed === current && USER_ACCOUNT_SID_PATTERN.test(current)) return false;
160
+ // Supported installs run as the current account: local/domain or Entra ID. Other SID
161
+ // namespaces, including built-in and virtual service accounts, remain conservative.
162
+ // This exclusion never adds authority to terminate a candidate.
163
+ return USER_ACCOUNT_SID_PATTERN.test(current) && USER_ACCOUNT_SID_PATTERN.test(observed) ? true : null;
164
+ }
107
165
 
108
166
  /** Parse the snapshot JSON. Unparseable output is null: an unread table proves nothing. */
109
167
  export function parseWindowsProcessSnapshot(output: string): WindowsStopProcessEntry[] | null {
@@ -130,6 +188,7 @@ export function parseWindowsProcessSnapshot(output: string): WindowsStopProcessE
130
188
  name: typeof record.Name === "string" ? record.Name : null,
131
189
  commandLine: typeof record.CommandLine === "string" ? record.CommandLine : null,
132
190
  startTime: Number.isFinite(created) ? created : null,
191
+ foreignOwner: foreignProcessOwner(record, Number.isFinite(created) ? created : null),
133
192
  });
134
193
  }
135
194
  return entries;
@@ -145,7 +204,7 @@ export function overlayNativeCreationTimes(
145
204
  creationTime: (pid: number) => number | null,
146
205
  ): WindowsStopProcessEntry[] {
147
206
  return entries.map(entry => {
148
- if (entry.startTime === null) return entry;
207
+ if (entry.startTime === null) return { ...entry, foreignOwner: null };
149
208
  let native: number | null;
150
209
  try {
151
210
  native = creationTime(entry.pid);
@@ -153,7 +212,7 @@ export function overlayNativeCreationTimes(
153
212
  native = null;
154
213
  }
155
214
  const agrees = native !== null && Math.abs(native - entry.startTime) <= NATIVE_CIM_TOLERANCE_MS;
156
- return { ...entry, startTime: agrees ? native : null };
215
+ return { ...entry, startTime: agrees ? native : null, foreignOwner: agrees ? entry.foreignOwner : null };
157
216
  });
158
217
  }
159
218
 
@@ -165,7 +224,7 @@ export async function windowsProcessSnapshot(options: WindowsEvidenceOptions): P
165
224
  try {
166
225
  entries = parseWindowsProcessSnapshot(await run({
167
226
  program: "powershell",
168
- args: powershellArgs(WINDOWS_PROCESS_SNAPSHOT_SCRIPT),
227
+ args: powershellArgs(windowsProcessSnapshotScript(options.timeoutMs)),
169
228
  timeoutMs: options.timeoutMs,
170
229
  maxBufferBytes: SNAPSHOT_MAX_BUFFER,
171
230
  }));
@@ -214,67 +273,16 @@ export async function readScheduleServicePid(options: WindowsEvidenceOptions): P
214
273
  }
215
274
  }
216
275
 
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. */
276
+ /** Terminate only through a handle that verifies creation identity and token ownership. */
251
277
  export async function terminateWindowsProcessBound(
252
278
  pid: number,
253
279
  boundStartTime: number,
254
280
  options: WindowsEvidenceOptions,
255
281
  ): Promise<WindowsTerminateResult> {
256
282
  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));
283
+ if (!native) return { status: "unavailable" };
271
284
  try {
272
- return parseFallbackTerminateOutput(await run({
273
- program: "powershell",
274
- args: powershellArgs(windowsFallbackTerminateScript(pid, boundStartTime, exitWaitMs)),
275
- timeoutMs,
276
- maxBufferBytes: SMALL_MAX_BUFFER,
277
- }));
285
+ return native.terminate(pid, boundStartTime);
278
286
  } catch {
279
287
  return { status: "unavailable" };
280
288
  }
@@ -1,13 +1,14 @@
1
1
  /**
2
2
  * In-process Windows process primitives for the checked service stop (#7771).
3
3
  *
4
- * Four questions the checked stop asks of the kernel and the SCM:
4
+ * Process evidence the stop paths ask of the kernel and the SCM:
5
5
  *
6
6
  * - when was this process created (GetProcessTimes), so a PID that was reused between
7
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;
8
+ * - does a live process share the caller's token user, and what is its creation identity
9
+ * and optional command line (all read through the same handle for Link stop);
10
+ * - terminate exactly the bound process: verify its creation time and token user on
11
+ * the same handle passed to TerminateProcess, so PID reuse cannot redirect the stop;
11
12
  * - has a bound process exited (WaitForSingleObject with a zero timeout on a handle
12
13
  * opened at bind time), so the wait needs neither an enumeration nor PowerShell;
13
14
  * - which process hosts the Task Scheduler service (QueryServiceStatusEx on "Schedule"),
@@ -17,13 +18,11 @@
17
18
  * (every importer loads this module on every platform), the DLLs load from the
18
19
  * GetSystemDirectoryW path so the search order cannot substitute them, a failed load is
19
20
  * 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.
21
+ * platform get null here. A test that simulates a platform never reaches the real kernel.
24
22
  */
25
23
  import { join } from "node:path";
26
24
 
25
+ import { readWindowsProcessCommandLineFromHandle } from "../config/windows-process-command-line";
27
26
  import { resolveTrustedWindowsSystemDirectory } from "../lib/windows-elevation";
28
27
 
29
28
  const PROCESS_TERMINATE = 0x0001;
@@ -41,19 +40,20 @@ const SERVICE_RUNNING = 4;
41
40
  const SERVICE_STATUS_PROCESS_BYTES = 36;
42
41
  const SERVICE_STATUS_STATE_OFFSET = 4;
43
42
  const SERVICE_STATUS_PID_OFFSET = 28;
43
+ /** 100 ns intervals between 0001-01-01 (.NET) and 1601-01-01 (FILETIME). */
44
+ const FILETIME_DOTNET_EPOCH = 504_911_232_000_000_000n;
44
45
  /** 100 ns intervals between 1601-01-01 and 1970-01-01. */
45
46
  const FILETIME_UNIX_EPOCH = 116_444_736_000_000_000n;
46
47
  const TERMINATE_EXIT_CODE = 1;
47
48
 
48
49
  /** Result of one checked terminate. Only "terminated" means this call ended the process. */
49
- export type WindowsTerminateStatus = "terminated" | "gone" | "reused" | "denied" | "unavailable";
50
+ export type WindowsTerminateStatus = "terminated" | "gone" | "reused" | "denied" | "unavailable" | "owner-unverified";
50
51
 
51
52
  export interface WindowsTerminateResult {
52
53
  status: WindowsTerminateStatus;
53
54
  /**
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.
55
+ * True when the primitive itself observed the process exit after terminating it.
56
+ * The native primitive leaves exit confirmation to the bind-time watch.
57
57
  */
58
58
  exited?: boolean;
59
59
  }
@@ -66,12 +66,19 @@ export type WindowsProcessWatch =
66
66
  export interface WindowsProcessNativeApi {
67
67
  /** Creation time in epoch ms (FILETIME truncated to ms), or null when unreadable. */
68
68
  creationTime(pid: number): number | null;
69
- terminate(pid: number, boundStartTime: number): WindowsTerminateResult;
69
+ /** Creation in .NET ticks at CIM precision from a live process with the same token user. */
70
+ sameUserIdentity(pid: number, withCommandLine?: boolean): { ticks: bigint; commandLine?: string } | null;
71
+ terminate(pid: number, boundStartTime: number | bigint): WindowsTerminateResult;
70
72
  openWatch(pid: number, boundStartTime: number): WindowsProcessWatch;
71
73
  /** PID of the running Task Scheduler service host, or null when it cannot be read. */
72
74
  scheduleServicePid(): number | null;
73
75
  }
74
76
 
77
+ /** Keep compatibility with CIM timestamps in saved runtime and teardown records. */
78
+ function fileTimeToCimTicks(fileTime: bigint): bigint {
79
+ return (fileTime + FILETIME_DOTNET_EPOCH) / 10n * 10n;
80
+ }
81
+
75
82
  /** FILETIME (100 ns since 1601) to epoch ms, truncated. Zero or pre-1970 is unreadable. */
76
83
  export function fileTimeToEpochMs(fileTime: bigint): number | null {
77
84
  if (fileTime <= FILETIME_UNIX_EPOCH) return null;
@@ -121,12 +128,13 @@ function loadNativeApi(): WindowsProcessNativeApi | null {
121
128
  if (nativeApi !== undefined) return nativeApi;
122
129
  nativeApi = null;
123
130
  if (process.platform !== "win32" || process.arch !== "x64") return null;
124
- let ptr: typeof import("bun:ffi").ptr;
131
+ let ffi: typeof import("bun:ffi");
132
+ let readWindowsCurrentSid: typeof import("../codex/windows-current-sid").readWindowsCurrentSid;
125
133
  let kernel32;
126
134
  let advapi32;
127
135
  try {
128
- const ffi = require("bun:ffi") as typeof import("bun:ffi");
129
- ptr = ffi.ptr;
136
+ ffi = require("bun:ffi") as typeof import("bun:ffi");
137
+ ({ readWindowsCurrentSid } = require("../codex/windows-current-sid") as typeof import("../codex/windows-current-sid"));
130
138
  const systemDirectory = resolveTrustedWindowsSystemDirectory();
131
139
  kernel32 = ffi.dlopen(join(systemDirectory, "kernel32.dll"), {
132
140
  OpenProcess: { args: ["u32", "i32", "u32"], returns: "u64" },
@@ -135,24 +143,44 @@ function loadNativeApi(): WindowsProcessNativeApi | null {
135
143
  TerminateProcess: { args: ["u64", "u32"], returns: "i32" },
136
144
  WaitForSingleObject: { args: ["u64", "u32"], returns: "u32" },
137
145
  GetLastError: { args: [], returns: "u32" },
146
+ GetCurrentProcess: { args: [], returns: "u64" },
147
+ LocalFree: { args: ["ptr"], returns: "ptr" },
138
148
  }).symbols;
139
149
  advapi32 = ffi.dlopen(join(systemDirectory, "advapi32.dll"), {
140
150
  OpenSCManagerW: { args: ["ptr", "ptr", "u32"], returns: "u64" },
141
151
  OpenServiceW: { args: ["u64", "ptr", "u32"], returns: "u64" },
142
152
  QueryServiceStatusEx: { args: ["u64", "i32", "ptr", "u32", "ptr"], returns: "i32" },
143
153
  CloseServiceHandle: { args: ["u64"], returns: "i32" },
154
+ OpenProcessToken: { args: ["u64", "u32", "ptr"], returns: "i32" },
155
+ GetTokenInformation: { args: ["u64", "u32", "ptr", "u32", "ptr"], returns: "i32" },
156
+ ConvertSidToStringSidW: { args: ["ptr", "ptr"], returns: "i32" },
144
157
  }).symbols;
145
158
  } catch {
146
159
  return null;
147
160
  }
148
161
  const k = kernel32;
149
162
  const a = advapi32;
163
+ const { ptr, read } = ffi;
150
164
 
151
- const handleCreationTime = (handle: Handle): number | null => {
165
+ const handleUserSid = (handle: Handle): string => readWindowsCurrentSid({
166
+ openProcessToken: (access, token) => a.OpenProcessToken(handle, access, ptr(token)),
167
+ getTokenInformation: (token, kind, buffer, length) =>
168
+ a.GetTokenInformation(token, kind, ptr(buffer), buffer.byteLength, ptr(length)),
169
+ convertSidToStringSid: (sid, output) => a.ConvertSidToStringSidW(sid as import("bun:ffi").Pointer, ptr(output)),
170
+ readCodeUnit: (address, offset) => read.u16(address as import("bun:ffi").Pointer, offset),
171
+ localFree: address => { k.LocalFree(address as import("bun:ffi").Pointer); },
172
+ closeHandle: token => { k.CloseHandle(token); },
173
+ });
174
+
175
+ const handleFileTime = (handle: Handle): bigint | null => {
152
176
  const times = new BigUint64Array(4);
153
177
  const base = ptr(times);
154
178
  const ok = k.GetProcessTimes(handle, base, base + 8, base + 16, base + 24);
155
- return ok ? fileTimeToEpochMs(times[0]!) : null;
179
+ return ok && times[0]! > FILETIME_UNIX_EPOCH ? times[0]! : null;
180
+ };
181
+ const handleCreationTime = (handle: Handle): number | null => {
182
+ const ticks = handleFileTime(handle);
183
+ return ticks === null ? null : fileTimeToEpochMs(ticks);
156
184
  };
157
185
  // true = exited, false = running, null = unreadable.
158
186
  const handleExited = (handle: Handle): boolean | null => {
@@ -180,16 +208,37 @@ function loadNativeApi(): WindowsProcessNativeApi | null {
180
208
  k.CloseHandle(handle);
181
209
  }
182
210
  },
211
+ sameUserIdentity(pid, withCommandLine) {
212
+ const handle = k.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE, 0, pid);
213
+ if (!handle) return null;
214
+ try {
215
+ const fileTime = handleFileTime(handle);
216
+ if (fileTime === null || handleUserSid(handle) !== handleUserSid(k.GetCurrentProcess())) return null;
217
+ const commandLine = withCommandLine ? readWindowsProcessCommandLineFromHandle(handle) : undefined;
218
+ if (handleExited(handle) !== false) return null;
219
+ return { ticks: fileTimeToCimTicks(fileTime), commandLine };
220
+ } catch {
221
+ return null;
222
+ } finally {
223
+ k.CloseHandle(handle);
224
+ }
225
+ },
183
226
  terminate(pid, boundStartTime) {
184
227
  const handle = k.OpenProcess(PROCESS_TERMINATE | PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE, 0, pid);
185
228
  if (!handle) return { status: openFailure() };
186
229
  try {
187
- const created = handleCreationTime(handle);
188
- if (created === null) return { status: "unavailable" };
230
+ const fileTime = handleFileTime(handle);
231
+ if (fileTime === null) return { status: "unavailable" };
232
+ const created = typeof boundStartTime === "number" ? fileTimeToEpochMs(fileTime) : fileTimeToCimTicks(fileTime);
189
233
  if (created !== boundStartTime) return { status: "reused" };
190
234
  const before = handleExited(handle);
191
235
  if (before === true) return { status: "gone" };
192
236
  if (before === null) return { status: "unavailable" };
237
+ try {
238
+ if (handleUserSid(handle) !== handleUserSid(k.GetCurrentProcess())) return { status: "owner-unverified" };
239
+ } catch {
240
+ return { status: handleExited(handle) === true ? "gone" : "owner-unverified" };
241
+ }
193
242
  if (k.TerminateProcess(handle, TERMINATE_EXIT_CODE)) return { status: "terminated" };
194
243
  const error = Number(k.GetLastError()) >>> 0;
195
244
  // TerminateProcess on a process that exited meanwhile also fails with access denied.
@@ -21,7 +21,7 @@ import type { PendingTeardownPartA } from "../config/pending-teardown";
21
21
  import { readRuntimePort } from "../config/process-state";
22
22
  import type { WinswStatus } from "../lib/winsw";
23
23
  import type { ServiceStopOutcome } from "./orchestration";
24
- import { guardedStopWindowsServiceChecked, stopWindowsServiceChecked, windowsStopClock, type WindowsCheckedStopDeps, type WindowsCheckedStopOptions, type WindowsCheckedStopResult, type WindowsStopAdmission, type WindowsStopReason } from "./windows-checked-stop";
24
+ import { guardedStopWindowsServiceChecked, stopWindowsServiceChecked, WindowsCheckedStopRefusedError, windowsStopClock, type WindowsCheckedStopDeps, type WindowsCheckedStopOptions, type WindowsCheckedStopResult, type WindowsStopAdmission, type WindowsStopReason } from "./windows-checked-stop";
25
25
  import { stopperUnderHomeWrapper, windowsCheckedStopLiveDeps, windowsStopConfirmLiveDeps, type WindowsCheckedStopLiveOptions } from "./windows-checked-stop-live";
26
26
  import { windowsListenPort } from "./windows-ops";
27
27
  import type { WindowsStopProcessEntry } from "./windows-process-evidence";
@@ -65,7 +65,7 @@ export interface WindowsPartARequest {
65
65
  admission?: WindowsStopAdmission;
66
66
  /** The evidence snapshot (windowsProcessSnapshot) a guarded revalidation already read. */
67
67
  bindSnapshot?: readonly WindowsStopProcessEntry[];
68
- /** The updater's authorizer: throws to refuse, at entry, before each manager stop and before each terminate. */
68
+ /** The updater's authorizer, called at entry and at each stop or terminate boundary. */
69
69
  authorize?: () => void | Promise<void>;
70
70
  /**
71
71
  * A hard cap (the route: 6 s with a receipt, 4 s for a stray sweep). An overrun answers
@@ -123,7 +123,9 @@ export const UNDER_OWN_WRAPPER_DETAIL = "this stop runs under this home's servic
123
123
 
124
124
  /** Part A with the live dependencies (or the test hook), optionally capped. */
125
125
  export async function runWindowsServiceStopPartA(request: WindowsPartARequest = {}): Promise<WindowsCheckedStopResult> {
126
+ const deadline = request.capMs === undefined ? Infinity : performance.now() + request.capMs;
126
127
  let expired = false;
128
+ const withinCap = () => !expired && performance.now() < deadline;
127
129
  let underOwnWrapper = false;
128
130
  const options: WindowsCheckedStopOptions = {
129
131
  ...(request.admission ? { admission: request.admission } : {}),
@@ -131,7 +133,7 @@ export async function runWindowsServiceStopPartA(request: WindowsPartARequest =
131
133
  };
132
134
  const run = async (): Promise<WindowsCheckedStopResult> => {
133
135
  if (hooks?.partA) return hooks.partA(request);
134
- const live: WindowsCheckedStopLiveOptions = { gate: () => !expired };
136
+ const live: WindowsCheckedStopLiveOptions = { gate: withinCap };
135
137
  const base = (hooks?.liveDeps ?? windowsCheckedStopLiveDeps)(live);
136
138
  const selfPid = base.selfPid ?? process.pid;
137
139
  const guard = (table: readonly WindowsStopProcessEntry[] | null): boolean =>
@@ -150,7 +152,7 @@ export async function runWindowsServiceStopPartA(request: WindowsPartARequest =
150
152
  },
151
153
  };
152
154
  const authorize = async (): Promise<void> => {
153
- if (expired) throw new Error("the checked stop's cap has passed");
155
+ if (!withinCap()) throw new Error("the checked stop's cap has passed");
154
156
  await request.authorize?.();
155
157
  };
156
158
  const result = await (request.authorize || request.capMs !== undefined
@@ -170,19 +172,19 @@ export async function runWindowsServiceStopPartA(request: WindowsPartARequest =
170
172
  };
171
173
  if (request.capMs === undefined) return run();
172
174
  const work = run().catch(error => {
173
- if (error && typeof error === "object" && "partial" in error) return (error as { partial: WindowsCheckedStopResult }).partial;
175
+ if (!request.authorize && error instanceof WindowsCheckedStopRefusedError) return error.partial;
174
176
  throw error;
175
177
  });
176
178
  let timer: ReturnType<typeof setTimeout> | undefined;
177
- const cap = new Promise<null>(resolve => { timer = setTimeout(() => resolve(null), request.capMs); });
179
+ const cap = new Promise<null>(resolve => {
180
+ timer = setTimeout(() => {
181
+ expired = true;
182
+ resolve(null);
183
+ }, Math.ceil(deadline - performance.now()));
184
+ });
178
185
  try {
179
186
  const result = await Promise.race([work, cap]);
180
- if (result === null) {
181
- expired = true;
182
- work.catch(() => undefined);
183
- return unknownResult("the checked stop did not finish within its cap");
184
- }
185
- return result;
187
+ return result !== null && withinCap() ? result : unknownResult("the checked stop did not finish within its cap");
186
188
  } finally {
187
189
  if (timer) clearTimeout(timer);
188
190
  }
@@ -12,7 +12,7 @@
12
12
  * Scheduler service host proven by the SCM PID, or, only while this home's task is
13
13
  * registered, its parent is gone. A parent PID that is not in the table, or whose
14
14
  * creation time is later than the wrapper's (a reused PID), counts as gone;
15
- * 4. a creation time was read for it.
15
+ * 4. its creation time and same-account owner SID were verified.
16
16
  *
17
17
  * A wrapper that passes 1-2 but fails lineage (a launcher started by hand from a live
18
18
  * shell, an orphan while no task is registered) is reported as unbound and never touched.
@@ -23,6 +23,7 @@
23
23
  * manager is registered, is an ancestor of the child.
24
24
  *
25
25
  * Pure: the caller supplies the snapshot and every fact; nothing here reads the machine.
26
+ * Proven foreign owners are never candidates, but stay in the table for parent evidence.
26
27
  */
27
28
  import { createHash } from "node:crypto";
28
29
 
@@ -64,10 +65,15 @@ export interface WindowsStopBinding {
64
65
  unbound: { pid: number; startTime: number | null }[];
65
66
  /** Candidates whose evidence cannot be read; any entry makes the stop unknown. */
66
67
  unreadable: number[];
68
+ /** Otherwise eligible wrappers whose same-account ownership could not be proven. */
69
+ ownershipUnverified: number[];
67
70
  /** The child as observed in the snapshot, for lineage and a WinSW survival check. */
68
71
  child: { pid: number; startTime: number | null } | null;
69
72
  }
70
73
 
74
+ export const WRAPPER_OWNER_REFUSAL =
75
+ "same-account ownership of a service wrapper could not be proven. Stop it from its owning Windows session using Task Manager, then retry";
76
+
71
77
  /** The lowercased image name when it is one of the three wrapper images, else null. */
72
78
  export function windowsWrapperImage(name: string | null | undefined): string | null {
73
79
  if (!name) return null;
@@ -114,7 +120,7 @@ export function bindWindowsStopWrappers(context: WindowsStopBindingContext): Win
114
120
  const unreadable = new Set<number>();
115
121
  const candidates: WindowsStopProcessEntry[] = [];
116
122
  for (const entry of processes) {
117
- if (entry.pid === context.childPid || !matchesPath(entry)) continue;
123
+ if (entry.pid === context.childPid || entry.foreignOwner === true || !matchesPath(entry)) continue;
118
124
  if (entry.name === null) unreadable.add(entry.pid);
119
125
  else if (windowsWrapperImage(entry.name)) candidates.push(entry);
120
126
  }
@@ -132,7 +138,7 @@ export function bindWindowsStopWrappers(context: WindowsStopBindingContext): Win
132
138
  for (let changed = true; changed;) {
133
139
  changed = false;
134
140
  for (const entry of candidates) {
135
- if (bound.has(entry.pid) || entry.startTime === null) continue;
141
+ if (bound.has(entry.pid) || entry.startTime === null || entry.foreignOwner !== false) continue;
136
142
  if (lineage(entry)) {
137
143
  bound.add(entry.pid);
138
144
  changed = true;
@@ -141,15 +147,17 @@ export function bindWindowsStopWrappers(context: WindowsStopBindingContext): Win
141
147
  }
142
148
 
143
149
  const unbound: WindowsStopBinding["unbound"] = [];
150
+ const ownershipUnverified: number[] = [];
144
151
  for (const entry of candidates) {
145
152
  if (bound.has(entry.pid)) continue;
146
153
  if (entry.startTime === null) unreadable.add(entry.pid);
154
+ else if (lineage(entry)) ownershipUnverified.push(entry.pid);
147
155
  else if (context.taskRegistered && parentLink(entry) === "unreadable") unreadable.add(entry.pid);
148
156
  else unbound.push({ pid: entry.pid, startTime: entry.startTime });
149
157
  }
150
158
 
151
159
  for (const entry of processes) {
152
- if (entry.pid === context.childPid || entry.commandLine?.trim() || !windowsWrapperImage(entry.name)) continue;
160
+ if (entry.pid === context.childPid || entry.foreignOwner === true || entry.commandLine?.trim() || !windowsWrapperImage(entry.name)) continue;
153
161
  if (descendsFromBound(entry) || (context.managerRegistered && childAncestors.has(entry.pid))) {
154
162
  unreadable.add(entry.pid);
155
163
  }
@@ -170,6 +178,7 @@ export function bindWindowsStopWrappers(context: WindowsStopBindingContext): Win
170
178
  })),
171
179
  unbound,
172
180
  unreadable: [...unreadable].sort((a, b) => a - b),
181
+ ownershipUnverified,
173
182
  child: childEntry ? { pid: childEntry.pid, startTime: childEntry.startTime } : null,
174
183
  };
175
184
  }
@@ -181,7 +190,7 @@ export function windowsHomeWrapperPids(
181
190
  selfPid?: number,
182
191
  ): number[] {
183
192
  return processes
184
- .filter(entry => entry.pid !== selfPid && windowsWrapperImage(entry.name)
193
+ .filter(entry => entry.pid !== selfPid && entry.foreignOwner !== true && windowsWrapperImage(entry.name)
185
194
  && canonicalPaths.some(path => commandLineHasPathToken(entry.commandLine, path)))
186
195
  .map(entry => entry.pid);
187
196
  }
@@ -120,7 +120,7 @@ export async function confirmWindowsStopFreed(deps: WindowsStopConfirmDeps): Pro
120
120
  if (result.lateWrappers.length > 0) return finish("survived", "a wrapper of this home is running after the stop");
121
121
  if (result.listener?.identity === "ours") return finish("survived", "this installation answers on the port again");
122
122
  if (processes === null) return finish("unknown", "the final process list could not be read");
123
- const unnamed = processes.some(entry => entry.name === null && entry.pid !== (deps.selfPid ?? process.pid)
123
+ const unnamed = processes.some(entry => entry.name === null && entry.foreignOwner !== true && entry.pid !== (deps.selfPid ?? process.pid)
124
124
  && deps.canonicalPaths.some(path => commandLineHasPathToken(entry.commandLine, path)));
125
125
  if (unnamed) return finish("unknown", "a process carrying this home's paths has an unreadable image name");
126
126
  if (held) return finish("freed", "the port stayed free for the hold and no wrapper of this home is running");