@bitkyc08/opencodex 2.97.0 → 2.98.0-preview.20261107

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 (290) hide show
  1. package/bin/ocx.mjs +1 -1
  2. package/gui/dist/assets/App-6TFtZsUF.css +1 -0
  3. package/gui/dist/assets/App-B8_sOxoz.js +59 -0
  4. package/gui/dist/assets/Tray-DpWEp6ee.js +1 -0
  5. package/gui/dist/assets/WantedSansVariable.split.0-Dwvb1WRx.woff2 +0 -0
  6. package/gui/dist/assets/WantedSansVariable.split.1-1wKD2RxI.woff2 +0 -0
  7. package/gui/dist/assets/WantedSansVariable.split.10-CAKA6LIP.woff2 +0 -0
  8. package/gui/dist/assets/WantedSansVariable.split.11-k5H85R4b.woff2 +0 -0
  9. package/gui/dist/assets/WantedSansVariable.split.12-BHboLsUv.woff2 +0 -0
  10. package/gui/dist/assets/WantedSansVariable.split.13-9GV377ix.woff2 +0 -0
  11. package/gui/dist/assets/WantedSansVariable.split.14-DovDXnrj.woff2 +0 -0
  12. package/gui/dist/assets/WantedSansVariable.split.15-DTdykCig.woff2 +0 -0
  13. package/gui/dist/assets/WantedSansVariable.split.16-CKz2ccgK.woff2 +0 -0
  14. package/gui/dist/assets/WantedSansVariable.split.17-Z2RD_KRZ.woff2 +0 -0
  15. package/gui/dist/assets/WantedSansVariable.split.18-BcKtfonJ.woff2 +0 -0
  16. package/gui/dist/assets/WantedSansVariable.split.19-DEQPOSZn.woff2 +0 -0
  17. package/gui/dist/assets/WantedSansVariable.split.2-DryboyuA.woff2 +0 -0
  18. package/gui/dist/assets/WantedSansVariable.split.20-Bia5JMls.woff2 +0 -0
  19. package/gui/dist/assets/WantedSansVariable.split.21-Cr4jFw-E.woff2 +0 -0
  20. package/gui/dist/assets/WantedSansVariable.split.22-DjjB69TZ.woff2 +0 -0
  21. package/gui/dist/assets/WantedSansVariable.split.23-CvUzJskt.woff2 +0 -0
  22. package/gui/dist/assets/WantedSansVariable.split.24-i_eMg5ox.woff2 +0 -0
  23. package/gui/dist/assets/WantedSansVariable.split.25-2aKHwPX-.woff2 +0 -0
  24. package/gui/dist/assets/WantedSansVariable.split.26-B6wXoCEL.woff2 +0 -0
  25. package/gui/dist/assets/WantedSansVariable.split.27-D4h1WfGM.woff2 +0 -0
  26. package/gui/dist/assets/WantedSansVariable.split.28-kvRPCStd.woff2 +0 -0
  27. package/gui/dist/assets/WantedSansVariable.split.29-DHAiwleD.woff2 +0 -0
  28. package/gui/dist/assets/WantedSansVariable.split.3-7H--eyZi.woff2 +0 -0
  29. package/gui/dist/assets/WantedSansVariable.split.30-C66cfAY2.woff2 +0 -0
  30. package/gui/dist/assets/WantedSansVariable.split.31-FDmtiNim.woff2 +0 -0
  31. package/gui/dist/assets/WantedSansVariable.split.32-DouHt2Dd.woff2 +0 -0
  32. package/gui/dist/assets/WantedSansVariable.split.33-B8HVvkJX.woff2 +0 -0
  33. package/gui/dist/assets/WantedSansVariable.split.34-BtkRu1FN.woff2 +0 -0
  34. package/gui/dist/assets/WantedSansVariable.split.35-DBylQbtk.woff2 +0 -0
  35. package/gui/dist/assets/WantedSansVariable.split.36-Sg089Kgh.woff2 +0 -0
  36. package/gui/dist/assets/WantedSansVariable.split.37-CYtvbriS.woff2 +0 -0
  37. package/gui/dist/assets/WantedSansVariable.split.38-DKkSLf8Z.woff2 +0 -0
  38. package/gui/dist/assets/WantedSansVariable.split.39-CecotKZD.woff2 +0 -0
  39. package/gui/dist/assets/WantedSansVariable.split.4-Bv8O3ZMb.woff2 +0 -0
  40. package/gui/dist/assets/WantedSansVariable.split.40-DdCvkmOU.woff2 +0 -0
  41. package/gui/dist/assets/WantedSansVariable.split.41-ESn674Hc.woff2 +0 -0
  42. package/gui/dist/assets/WantedSansVariable.split.42-DL9V7NNV.woff2 +0 -0
  43. package/gui/dist/assets/WantedSansVariable.split.43-yipO0cyk.woff2 +0 -0
  44. package/gui/dist/assets/WantedSansVariable.split.44-6rTmLZhm.woff2 +0 -0
  45. package/gui/dist/assets/WantedSansVariable.split.45-BJAj8lrm.woff2 +0 -0
  46. package/gui/dist/assets/WantedSansVariable.split.46-BDTzMn2c.woff2 +0 -0
  47. package/gui/dist/assets/WantedSansVariable.split.47-Bxd4wGgi.woff2 +0 -0
  48. package/gui/dist/assets/WantedSansVariable.split.48-DxnFBLnH.woff2 +0 -0
  49. package/gui/dist/assets/WantedSansVariable.split.49-DnVD0aOD.woff2 +0 -0
  50. package/gui/dist/assets/WantedSansVariable.split.5-B1wI2pp5.woff2 +0 -0
  51. package/gui/dist/assets/WantedSansVariable.split.50-D9JlkZd6.woff2 +0 -0
  52. package/gui/dist/assets/WantedSansVariable.split.51-D9Vw6Bu3.woff2 +0 -0
  53. package/gui/dist/assets/WantedSansVariable.split.52-ClEJk4kn.woff2 +0 -0
  54. package/gui/dist/assets/WantedSansVariable.split.53-BSXU0vh-.woff2 +0 -0
  55. package/gui/dist/assets/WantedSansVariable.split.54-EcuxkR9v.woff2 +0 -0
  56. package/gui/dist/assets/WantedSansVariable.split.55-CYiFhQX8.woff2 +0 -0
  57. package/gui/dist/assets/WantedSansVariable.split.56--Gk9g8BK.woff2 +0 -0
  58. package/gui/dist/assets/WantedSansVariable.split.57-DnkOPZcy.woff2 +0 -0
  59. package/gui/dist/assets/WantedSansVariable.split.58-9MB8504z.woff2 +0 -0
  60. package/gui/dist/assets/WantedSansVariable.split.59-ByxIsN72.woff2 +0 -0
  61. package/gui/dist/assets/WantedSansVariable.split.6-Bmk0dRVw.woff2 +0 -0
  62. package/gui/dist/assets/WantedSansVariable.split.60-Bxwx_aWQ.woff2 +0 -0
  63. package/gui/dist/assets/WantedSansVariable.split.61-DA2z5sm7.woff2 +0 -0
  64. package/gui/dist/assets/WantedSansVariable.split.62-C5iJPJZn.woff2 +0 -0
  65. package/gui/dist/assets/WantedSansVariable.split.63-DAqrmaEc.woff2 +0 -0
  66. package/gui/dist/assets/WantedSansVariable.split.64-BgXFsljb.woff2 +0 -0
  67. package/gui/dist/assets/WantedSansVariable.split.65-DKiWujvu.woff2 +0 -0
  68. package/gui/dist/assets/WantedSansVariable.split.66-8po4vUZ4.woff2 +0 -0
  69. package/gui/dist/assets/WantedSansVariable.split.67-Cy5qyI9O.woff2 +0 -0
  70. package/gui/dist/assets/WantedSansVariable.split.68-BKny7Fy3.woff2 +0 -0
  71. package/gui/dist/assets/WantedSansVariable.split.69-B4VU4u_b.woff2 +0 -0
  72. package/gui/dist/assets/WantedSansVariable.split.7-BuqwNpgA.woff2 +0 -0
  73. package/gui/dist/assets/WantedSansVariable.split.70-BCd4n346.woff2 +0 -0
  74. package/gui/dist/assets/WantedSansVariable.split.71-CkQppaWn.woff2 +0 -0
  75. package/gui/dist/assets/WantedSansVariable.split.72-Db7vaoFs.woff2 +0 -0
  76. package/gui/dist/assets/WantedSansVariable.split.73-DI80TYWl.woff2 +0 -0
  77. package/gui/dist/assets/WantedSansVariable.split.74-tMCtDAHB.woff2 +0 -0
  78. package/gui/dist/assets/WantedSansVariable.split.75-Ciw0D5WG.woff2 +0 -0
  79. package/gui/dist/assets/WantedSansVariable.split.76-DoLjFgp-.woff2 +0 -0
  80. package/gui/dist/assets/WantedSansVariable.split.77-CpT2uvMy.woff2 +0 -0
  81. package/gui/dist/assets/WantedSansVariable.split.78-CkcJ4iZ1.woff2 +0 -0
  82. package/gui/dist/assets/WantedSansVariable.split.79-DsOUJjEM.woff2 +0 -0
  83. package/gui/dist/assets/WantedSansVariable.split.8-DsjypPd6.woff2 +0 -0
  84. package/gui/dist/assets/WantedSansVariable.split.80-C0VwHTte.woff2 +0 -0
  85. package/gui/dist/assets/WantedSansVariable.split.81-DTelu57i.woff2 +0 -0
  86. package/gui/dist/assets/WantedSansVariable.split.82-BiMndGN1.woff2 +0 -0
  87. package/gui/dist/assets/WantedSansVariable.split.83-CVcC6eDG.woff2 +0 -0
  88. package/gui/dist/assets/WantedSansVariable.split.84-DlhZVt_O.woff2 +0 -0
  89. package/gui/dist/assets/WantedSansVariable.split.85-S8I2D3pA.woff2 +0 -0
  90. package/gui/dist/assets/WantedSansVariable.split.86-DozXXpH5.woff2 +0 -0
  91. package/gui/dist/assets/WantedSansVariable.split.87-Dsn0Vuuo.woff2 +0 -0
  92. package/gui/dist/assets/WantedSansVariable.split.88-iNwxxDCr.woff2 +0 -0
  93. package/gui/dist/assets/WantedSansVariable.split.89-B63u_9CZ.woff2 +0 -0
  94. package/gui/dist/assets/WantedSansVariable.split.9-Bi3IzpMI.woff2 +0 -0
  95. package/gui/dist/assets/WantedSansVariable.split.90-ByeH1Pqf.woff2 +0 -0
  96. package/gui/dist/assets/WantedSansVariable.split.91-UQLlagpm.woff2 +0 -0
  97. package/gui/dist/assets/brand-mark-VPhzz-WE.js +1 -0
  98. package/gui/dist/assets/geist-cyrillic-ext-wght-normal-DjL33-gN.woff2 +0 -0
  99. package/gui/dist/assets/geist-cyrillic-wght-normal-BEAKL7Jp.woff2 +0 -0
  100. package/gui/dist/assets/geist-latin-ext-wght-normal-DC-KSUi6.woff2 +0 -0
  101. package/gui/dist/assets/geist-latin-wght-normal-BgDaEnEv.woff2 +0 -0
  102. package/gui/dist/assets/geist-mono-cyrillic-ext-wght-normal-X_5orZeX.woff2 +0 -0
  103. package/gui/dist/assets/geist-mono-cyrillic-wght-normal-DiZS0aHC.woff2 +0 -0
  104. package/gui/dist/assets/geist-mono-latin-ext-wght-normal-Bwz-egvJ.woff2 +0 -0
  105. package/gui/dist/assets/geist-mono-latin-wght-normal-XN7g48iV.woff2 +0 -0
  106. package/gui/dist/assets/geist-mono-symbols2-wght-normal-CO5SzqOn.woff2 +0 -0
  107. package/gui/dist/assets/geist-mono-vietnamese-wght-normal-DadHysG0.woff2 +0 -0
  108. package/gui/dist/assets/geist-vietnamese-wght-normal-6IgcOCM7.woff2 +0 -0
  109. package/gui/dist/assets/index-5REODpG3.css +2 -0
  110. package/gui/dist/assets/index-BWKBeK77.js +94 -0
  111. package/gui/dist/assets/segment-thumb-features-BQYzrze9.js +1 -0
  112. package/gui/dist/classic/assets/App-Bz65x1J6.js +58 -0
  113. package/gui/dist/{assets/Tray-CEw0y0jR.js → classic/assets/Tray-kk7mdO6I.js} +1 -1
  114. package/gui/dist/classic/assets/index-Dp2j8bSc.js +94 -0
  115. package/gui/dist/classic/assets/quota-summary-CvamtHjB.js +1 -0
  116. package/gui/dist/classic/index.html +47 -0
  117. package/gui/dist/favicon.png +0 -0
  118. package/gui/dist/favicon.svg +14 -0
  119. package/gui/dist/index.html +15 -2
  120. package/package.json +1 -1
  121. package/src/adapters/anthropic.ts +17 -8
  122. package/src/adapters/google.ts +7 -7
  123. package/src/adapters/kiro/adapter.ts +18 -3
  124. package/src/adapters/kiro/conversation.ts +8 -8
  125. package/src/adapters/kiro/payload.ts +45 -12
  126. package/src/adapters/kiro/stream.ts +169 -12
  127. package/src/adapters/kiro/structured-output-json.ts +191 -0
  128. package/src/adapters/kiro/structured-output-schema.ts +542 -0
  129. package/src/adapters/kiro/structured-output.ts +367 -0
  130. package/src/adapters/kiro-constants.ts +9 -0
  131. package/src/adapters/kiro-tools.ts +14 -9
  132. package/src/adapters/kiro-wire.ts +9 -5
  133. package/src/adapters/openai-chat/messages.ts +58 -5
  134. package/src/adapters/openai-chat/mistral-image-limit.ts +50 -0
  135. package/src/adapters/openai-chat/passthrough.ts +5 -3
  136. package/src/adapters/openai-chat/tool-schema.ts +83 -13
  137. package/src/adapters/openai-responses/opengateway-input.ts +18 -6
  138. package/src/adapters/openai-responses/tool-output-recovery.ts +79 -0
  139. package/src/adapters/qoder/live-models.ts +115 -1
  140. package/src/claude/failure-verdict.ts +21 -0
  141. package/src/claude/inbound-content-options.ts +15 -2
  142. package/src/claude/inbound-model-options.ts +2 -1
  143. package/src/claude/inbound-records.ts +2 -0
  144. package/src/claude/inbound.ts +17 -11
  145. package/src/claude/outbound.ts +52 -23
  146. package/src/cli/capabilities-access-remote.ts +13 -0
  147. package/src/cli/capabilities-base.ts +1 -0
  148. package/src/cli/capabilities-provider-models.ts +3 -3
  149. package/src/cli/codex-shim-autorestore.ts +7 -0
  150. package/src/cli/config-command.ts +11 -2
  151. package/src/cli/connect.ts +17 -2
  152. package/src/cli/dispatch.ts +3 -1
  153. package/src/cli/doctor.ts +95 -7
  154. package/src/cli/index.ts +12 -7
  155. package/src/cli/link-apply-restart.ts +9 -2
  156. package/src/cli/models.ts +124 -38
  157. package/src/cli/registry.ts +1 -1
  158. package/src/cli/restart-failure.ts +17 -0
  159. package/src/cli/stop-approval.ts +2 -2
  160. package/src/cli/sync-command.ts +1 -1
  161. package/src/cli/sync-fanout.ts +15 -4
  162. package/src/cli/system-restart-client.ts +5 -0
  163. package/src/cli/uninstall-client-state.ts +12 -1
  164. package/src/cli/update-restart-child.ts +13 -3
  165. package/src/cli/update-restart-home.ts +6 -3
  166. package/src/cli/update-restart.ts +36 -19
  167. package/src/client/connect.ts +4 -1
  168. package/src/client/hub-client.ts +5 -0
  169. package/src/client/link-management-relay.ts +39 -2
  170. package/src/client/link-readiness.ts +3 -1
  171. package/src/client/machine-api.ts +2 -1
  172. package/src/client/machine-listener.ts +7 -0
  173. package/src/client/orphan-token-recovery.ts +322 -0
  174. package/src/codex/catalog/provider-models.ts +12 -4
  175. package/src/codex/native-profile-api.ts +27 -1
  176. package/src/codex/shim-diagnostics.ts +7 -0
  177. package/src/codex/shim-legacy-record.ts +290 -0
  178. package/src/codex/shim-windows-refresh.ts +9 -2
  179. package/src/codex/shim-wrapper-write.ts +7 -0
  180. package/src/codex/shim.ts +80 -21
  181. package/src/config/diagnostics.ts +9 -9
  182. package/src/config/load-degrade.ts +27 -27
  183. package/src/config/provider-validation.ts +9 -2
  184. package/src/config/removed-opencode-free-backup.ts +6 -3
  185. package/src/config/tracked-runtime-inspection.ts +3 -3
  186. package/src/generated/compatibility-version.json +219 -147
  187. package/src/images/loop.ts +2 -2
  188. package/src/lib/client-error-body.ts +37 -6
  189. package/src/lib/config-ownership-removal.ts +422 -0
  190. package/src/lib/config-ownership.ts +646 -81
  191. package/src/lib/context-overflow-verdict.ts +3 -3
  192. package/src/lib/crash-guard.ts +4 -2
  193. package/src/lib/desktop-cli-handoff.d.mts +3 -4
  194. package/src/lib/desktop-cli-handoff.mjs +7 -16
  195. package/src/lib/errors.ts +1 -0
  196. package/src/lib/local-management-capability.ts +3 -1
  197. package/src/lib/messages-error-body.ts +162 -0
  198. package/src/lib/messages-sse-error-presentation.ts +93 -0
  199. package/src/lib/passive-read.ts +9 -4
  200. package/src/lib/socks5-fetch.ts +21 -9
  201. package/src/lib/upstream-retry.ts +81 -1
  202. package/src/lib/windows-owner-acl.ts +9 -3
  203. package/src/lib/winsw.ts +5 -5
  204. package/src/lib/workflow-budget.ts +3 -1
  205. package/src/oauth/index.ts +7 -0
  206. package/src/oauth/store.ts +20 -10
  207. package/src/protocols/codecs/messages-ir.ts +15 -9
  208. package/src/protocols/encoders/adapter-events.ts +26 -7
  209. package/src/protocols/encoders/messages.ts +72 -28
  210. package/src/providers/antigravity-models.ts +45 -12
  211. package/src/providers/free-directory.ts +2 -2
  212. package/src/providers/reasoning-metadata.ts +2 -1
  213. package/src/providers/registry/entries-extended.ts +9 -0
  214. package/src/reasoning-effort.ts +7 -2
  215. package/src/remote/hub-usage.ts +3 -0
  216. package/src/server/admission-model-scope.ts +1 -1
  217. package/src/server/admitted-http-turn.ts +2 -1
  218. package/src/server/anthropic-rate-limit-headers.ts +75 -3
  219. package/src/server/claude-messages.ts +130 -67
  220. package/src/server/gui-static.ts +4 -1
  221. package/src/server/hub-usage.ts +7 -2
  222. package/src/server/index/link-management.ts +8 -0
  223. package/src/server/index/ollama-routes.ts +2 -0
  224. package/src/server/index/serve-options.ts +23 -20
  225. package/src/server/index/startup-warnings.ts +5 -12
  226. package/src/server/index/websocket-handler.ts +1 -0
  227. package/src/server/inference/client-encoder-delivery.ts +5 -1
  228. package/src/server/management/logs-usage-routes.ts +89 -4
  229. package/src/server/management/provider-routes.ts +2 -22
  230. package/src/server/management/qoder-provider-probe.ts +105 -0
  231. package/src/server/management/route-registry.ts +3 -0
  232. package/src/server/management/usage-aggregate-cache.ts +15 -5
  233. package/src/server/management/usage-source-facets.ts +38 -0
  234. package/src/server/messages-native-tool-guard.ts +11 -3
  235. package/src/server/messages-native.ts +111 -40
  236. package/src/server/messages-response-headers.ts +25 -11
  237. package/src/server/messages-shared.ts +94 -64
  238. package/src/server/messages-sse-error-filter.ts +199 -0
  239. package/src/server/request-log.ts +12 -0
  240. package/src/server/responses/adapter-continuation.ts +11 -5
  241. package/src/server/responses/adapter-delivery.ts +14 -8
  242. package/src/server/responses/adapter-dispatch.ts +8 -8
  243. package/src/server/responses/anthropic-thinking-recovery.ts +2 -2
  244. package/src/server/responses/codex-auth-error.ts +8 -4
  245. package/src/server/responses/codex-ws-wire.ts +19 -3
  246. package/src/server/responses/compact.ts +4 -1
  247. package/src/server/responses/core-auth.ts +1 -1
  248. package/src/server/responses/core-combo-failure.ts +2 -0
  249. package/src/server/responses/core-combo.ts +2 -0
  250. package/src/server/responses/core-errors.ts +5 -4
  251. package/src/server/responses/core-options.ts +2 -0
  252. package/src/server/responses/empty-completion-guard.ts +4 -1
  253. package/src/server/responses/pacing-overload.ts +1 -1
  254. package/src/server/responses/passthrough-dispatch.ts +5 -5
  255. package/src/server/responses/request-prepare.ts +3 -1
  256. package/src/server/responses/request-transport.ts +9 -8
  257. package/src/server/responses/response-effects.ts +3 -2
  258. package/src/server/responses/terminal-guard.ts +30 -0
  259. package/src/server/restart-replacement.ts +3 -1
  260. package/src/server/sse-payload-rewrite.ts +23 -11
  261. package/src/server/workflow-refusal.ts +1 -1
  262. package/src/server/ws-bridge.ts +4 -0
  263. package/src/service/definition.ts +36 -4
  264. package/src/service/launchd.ts +89 -32
  265. package/src/service/logging.ts +34 -7
  266. package/src/service/plist-xml.ts +59 -0
  267. package/src/service/state.ts +8 -0
  268. package/src/service/systemd-env.ts +2 -0
  269. package/src/service/systemd.ts +31 -7
  270. package/src/service/windows-taskxml.ts +16 -7
  271. package/src/service-manager-probe.ts +4 -10
  272. package/src/types/provider.ts +2 -0
  273. package/src/types/request.ts +13 -1
  274. package/src/update/config-preflight.ts +48 -0
  275. package/src/update/index.ts +15 -1
  276. package/src/usage/client.ts +43 -0
  277. package/src/usage/error-detail.ts +1 -1
  278. package/src/usage/log.ts +4 -0
  279. package/src/usage/source-facets.ts +51 -0
  280. package/src/usage/source-filter.ts +65 -0
  281. package/src/usage/summary.ts +50 -8
  282. package/src/web-search/anthropic-executor.ts +105 -24
  283. package/src/web-search/executor.ts +5 -3
  284. package/src/web-search/loop.ts +2 -1
  285. package/src/web-search/progress-stream.ts +64 -5
  286. package/gui/dist/assets/App-DuNhggE1.js +0 -58
  287. package/gui/dist/assets/index-CynE_Rue.js +0 -94
  288. package/gui/dist/assets/quota-summary-VHFSlUuM.js +0 -1
  289. /package/gui/dist/{assets → classic/assets}/App-B4j-Txmb.css +0 -0
  290. /package/gui/dist/{assets → classic/assets}/index-CHWwDo9L.css +0 -0
@@ -37,7 +37,7 @@ import {
37
37
  TRANSLATOR_MAX_TURN_BYTES,
38
38
  TranslatorBudgetExceededError,
39
39
  } from "../lib/translator-budget";
40
- import { parseStreamWithProgress, RoutedModelInactivityError, WebSearchStreamProtocolError, WebSearchAdapterEventError } from "../web-search/progress-stream";
40
+ import { parseStreamWithProgress, RoutedModelInactivityError, WebSearchConsumerInactivityError, WebSearchStreamProtocolError, WebSearchAdapterEventError } from "../web-search/progress-stream";
41
41
  import { fulfillImageCall } from "./fulfill";
42
42
  import { parseVideoCallArgs, pollVideoWithHeartbeats, buildVideoResult, createVideoBudget } from "./fulfill-video";
43
43
  import { submitVideoJob } from "./xai-video-client";
@@ -895,7 +895,7 @@ export async function runWithImageBridge(deps: ImageBridgeDeps): Promise<Respons
895
895
  if (error instanceof LoopError) throw error;
896
896
  if (error instanceof SendBudgetExhaustedError) throw new LoopError(429, error.message,
897
897
  { type: "error", status: 429, errorType: "rate_limit_error", code: error.code, message: error.message, retryable: false });
898
- if (error instanceof RoutedModelInactivityError) throw new LoopError(504, error.message);
898
+ if (error instanceof RoutedModelInactivityError || error instanceof WebSearchConsumerInactivityError) throw new LoopError(504, error.message);
899
899
  if (error instanceof WebSearchStreamProtocolError) throw new LoopError(502, error.message);
900
900
  throw new LoopError(502, `Provider stream error: ${error instanceof Error ? error.message : String(error)}`);
901
901
  } finally {
@@ -23,8 +23,8 @@ function literalMap<const T extends readonly string[]>(values: T): ReadonlyMap<s
23
23
  }
24
24
  export const OPENAI_ERROR_TYPES = literalMap(openaiTypes);
25
25
  export const OPENAI_ERROR_CODES = literalMap(openaiCodes);
26
- export const ANTHROPIC_ERROR_TYPES = literalMap(["invalid_request_error", "authentication_error", "permission_error", "not_found_error", "request_too_large", "rate_limit_error", "api_error", "overloaded_error", "billing_error", "timeout_error", "conflict_error"] as const);
27
- export const ANTHROPIC_ERROR_CODES = literalMap([...ANTHROPIC_ERROR_TYPES.values(), ...openaiCodes] as const);
26
+ export const ANTHROPIC_ERROR_TYPES = literalMap(["invalid_request_error", "authentication_error", "permission_error", "not_found_error", "request_too_large", "rate_limit_error", "api_error", "overloaded_error", "billing_error", "timeout_error", "conflict_error", "send_budget_exhausted"] as const);
27
+ export const ANTHROPIC_ERROR_CODES = literalMap([...ANTHROPIC_ERROR_TYPES.values(), ...openaiCodes, "desktop_model_mapping_unavailable", "thread_unsupported_request"] as const);
28
28
  export const CLAUDE_CONTEXT_OVERFLOW_MESSAGE = "prompt is too long: The request exceeds the model's context window.";
29
29
  export const CLIENT_ERROR_CONTRACTS = {
30
30
  context_overflow: "The request exceeds the model's context window.",
@@ -67,6 +67,9 @@ const CODE_MESSAGES: ReadonlyMap<string, string> = new Map([
67
67
  ["upstream_reset_replay_refused", CLIENT_ERROR_CONTRACTS.replay_refused],
68
68
  ...["cyber_policy", "invalid_prompt", "misalignment_policy_violation", "bio_policy", "model_not_in_plan", "translation_buffer_limit", "invalid_refusal", "undeclared_tool_call", "required_tool_contract_unsatisfied"].map(code => [code, CLIENT_ERROR_CONTRACTS[code as ClientErrorContract]] as const),
69
69
  ]);
70
+ export function clientErrorCodeMessage(code: string | undefined): string | undefined {
71
+ return CODE_MESSAGES.get(code ?? "");
72
+ }
70
73
  /** Local guidance is selected only by a closed reason supplied by the owning proxy call site. */
71
74
  export const LOCAL_CHAT_ERROR_MESSAGES: ReadonlyMap<string, string> = new Map([
72
75
  ["credentials_paused", "The configured credentials are paused. Resume an account or key in account settings before retrying."],
@@ -137,14 +140,28 @@ export function comboFailureEvidence(response: Response): string | undefined { r
137
140
 
138
141
  /** Identity belongs to the locally constructed object, never to serialized fields. */
139
142
  const proxyErrors = new WeakSet<object>();
140
- export function markProxyError<T extends object>(value: T): T { proxyErrors.add(value); return value; }
143
+ export type ProxyErrorPresentation = "roster" | "pacing" | "input" | "outbound" | "inbound" | "send" | "cooldown" | "cooldown_pinned" | "hard_lock" | "recovery" | "usage" | "model_availability" | "oauth_login" | "discovery" | "muse_http" | "config" | "workflow" | "workflow_unbound" | "scope" | "body_stall" | "body_overflow" | "combo" | "copilot" | "pool_refresh";
144
+ const proxyPresentations = new WeakMap<object, ProxyErrorPresentation>();
145
+ export function proxyErrorPresentation(value: object): ProxyErrorPresentation | undefined { return proxyPresentations.get(value); }
146
+ export function markProxyError<T extends object>(value: T, presentation?: ProxyErrorPresentation): T {
147
+ proxyErrors.add(value);
148
+ if (presentation !== undefined) proxyPresentations.set(value, presentation);
149
+ return value;
150
+ }
151
+ export function carryProxyErrorPresentation<T extends object>(source: object, target: T): T {
152
+ const kind = proxyErrorPresentation(source);
153
+ if (source instanceof Response && target instanceof Response && source.status !== target.status) return target;
154
+ if (kind !== undefined && proxyErrorPresentation(target) === undefined) proxyPresentations.set(target, kind);
155
+ return target;
156
+ }
141
157
  export function isProxyError(value: object): boolean { return proxyErrors.has(value); }
142
158
  export function carryProxyError<T extends object>(source: object, target: T): T {
143
- return isProxyError(source) ? markProxyError(target) : target;
159
+ return isProxyError(source) ? carryProxyErrorPresentation(source, markProxyError(target)) : target;
144
160
  }
145
161
  /** The tool guard records only messages it constructs for this response's request context. */
146
- export interface ProxyErrorMessageFields { type?: string; code?: string | null }
162
+ export interface ProxyErrorMessageFields { type?: string; code?: string | null; presentation?: ProxyErrorPresentation }
147
163
  const proxyMessages = new WeakMap<object, Map<string, Set<string>>>();
164
+ const proxyMessagePresentations = new WeakMap<object, Map<string, Map<string, ProxyErrorPresentation>>>();
148
165
  const errorFields = (fields: ProxyErrorMessageFields) => JSON.stringify([fields.type ?? null, fields.code ?? null]);
149
166
  export function rememberProxyErrorMessage(context: object, message: string, fields: ProxyErrorMessageFields & { status: number }): void {
150
167
  let messages = proxyMessages.get(context);
@@ -153,17 +170,31 @@ export function rememberProxyErrorMessage(context: object, message: string, fiel
153
170
  if (!allowed) { allowed = new Set(); messages.set(message, allowed); }
154
171
  const classified = classifyError(fields.status, fields.type ?? "upstream_error", message);
155
172
  // The bridge may classify a field while preserving the other field's explicit local verdict.
156
- for (const type of [fields.type, classified.type]) for (const code of [fields.code, classified.code]) allowed.add(errorFields({ type, code }));
173
+ for (const type of [fields.type, classified.type]) for (const code of [fields.code, classified.code]) {
174
+ const key = errorFields({ type, code }); allowed.add(key);
175
+ if (fields.presentation !== undefined) {
176
+ let rows = proxyMessagePresentations.get(context);
177
+ if (!rows) { rows = new Map(); proxyMessagePresentations.set(context, rows); }
178
+ let kinds = rows.get(message); if (!kinds) { kinds = new Map(); rows.set(message, kinds); }
179
+ kinds.set(key, fields.presentation);
180
+ }
181
+ }
157
182
  }
158
183
  export function carryProxyErrorContext(source: object, target: object): void {
159
184
  carryProxyIncompleteContext(source, target);
160
185
  let messages = proxyMessages.get(source);
161
186
  if (!messages) { messages = new Map(); proxyMessages.set(source, messages); }
162
187
  proxyMessages.set(target, messages);
188
+ let presentations = proxyMessagePresentations.get(source);
189
+ if (!presentations) { presentations = new Map(); proxyMessagePresentations.set(source, presentations); }
190
+ proxyMessagePresentations.set(target, presentations);
163
191
  }
164
192
  export function hasProxyErrorMessage(context: object | undefined, message: string, fields: ProxyErrorMessageFields): boolean {
165
193
  return context !== undefined && proxyMessages.get(context)?.get(message)?.has(errorFields(fields)) === true;
166
194
  }
195
+ export function proxyMessagePresentation(context: object | undefined, message: string, fields: ProxyErrorMessageFields): ProxyErrorPresentation | undefined {
196
+ return context === undefined ? undefined : proxyMessagePresentations.get(context)?.get(message)?.get(errorFields(fields));
197
+ }
167
198
  // These complete sentences contain only proxy literals, including each recognized reason.
168
199
  const PROXY_FIXED_MESSAGES: ReadonlyMap<string, string> = literalMap([
169
200
  "internal replay returned a non-JSON response",
@@ -0,0 +1,422 @@
1
+ import { existsSync, lstatSync, readdirSync, readlinkSync, realpathSync, rmdirSync, unlinkSync, type Stats } from "node:fs";
2
+ import { basename, dirname, isAbsolute, join, parse, resolve, sep } from "node:path";
3
+ import { isWindowsReparsePoint, nativeReparseProbeApplies } from "./private-sqlite-path";
4
+ import { isCurrentWindowsProcessElevated } from "./windows-elevation";
5
+ import { verifyWindowsEntriesAcl, WINDOWS_OWNER_ACL_TIMEOUT_MS, type WindowsAclEntry } from "./windows-owner-acl";
6
+
7
+ /**
8
+ * Path checks for `ocx uninstall`'s owned-state removal. Every recorded path is resolved from the
9
+ * canonical config root one component at a time: the directories between the root and the entry must
10
+ * be real directories that resolve exactly to their root-relative location, checked again immediately
11
+ * before each unlink, listing and rmdir. An entry that does not meet this stays in place and is
12
+ * reported. The guarantee covers the state each check observes; Bun and Node provide no
13
+ * directory-handle-relative unlink, so it does not extend to a concurrent change made by the same
14
+ * account between a check and the removal that follows it.
15
+ */
16
+
17
+ // Read once at load: tests replace `process.platform`, and the native query must follow the real system.
18
+ const NATIVE_REPARSE = nativeReparseProbeApplies(process.platform, process.arch);
19
+ const DARWIN_LS_BATCH = 128;
20
+ /** Linux resolves up to 40 links in one lookup (macOS 32); a longer chain or a cycle stops here. */
21
+ const MAX_LINK_DEPTH = 40;
22
+ /**
23
+ * Paths per ACL read. Each read is one bounded PowerShell call taking its paths over stdin, so a
24
+ * large tree costs more reads rather than outgrowing a single read's deadline.
25
+ */
26
+ const WINDOWS_ACL_BATCH = 256;
27
+
28
+ export class OwnedPathRedirectedError extends Error {
29
+ constructor() {
30
+ super("a directory on the way to the owned path is not a real directory inside the config root");
31
+ this.name = "OwnedPathRedirectedError";
32
+ }
33
+ }
34
+
35
+ export const ELEVATED_UNINSTALL_REFUSAL = "ocx uninstall is running with elevated privileges, but another account can change "
36
+ + "the config directory, a directory above it or a directory inside it, or the config directory holds a link that leads "
37
+ + "outside it (on Windows, any link). Run 'ocx uninstall' as the account that owns the config directory, without sudo or administrator rights, "
38
+ + "or restrict those directories to that account and remove such links first.";
39
+
40
+ /** Windows without the native token probe (Bun cannot run `bun:ffi` on ARM64): the run is treated as elevated. */
41
+ export const UNKNOWN_ELEVATION_UNINSTALL_REFUSAL = "ocx uninstall could not determine whether it is running with elevated "
42
+ + "privileges, and could not confirm that only this account can change the config directory. Stop opencodex, then "
43
+ + "remove the config directory yourself.";
44
+
45
+ let elevationProbeForTests: (() => boolean) | null = null;
46
+ let directoryListedHookForTests: ((path: string) => void) | null = null;
47
+
48
+ /** Test seam: decide whether uninstall counts as elevated; null restores the platform probe. */
49
+ export function setUninstallElevationProbeForTests(probe: (() => boolean) | null): void {
50
+ elevationProbeForTests = probe;
51
+ }
52
+
53
+ /** Test seam: called after an owned directory is listed and before its children are removed. */
54
+ export function setOwnedDirectoryListedHookForTests(hook: ((path: string) => void) | null): void {
55
+ directoryListedHookForTests = hook;
56
+ }
57
+
58
+ type Elevation = "elevated" | "unelevated" | "unknown";
59
+
60
+ /** POSIX effective uid 0, or an elevated Windows token; a Windows token the native probe cannot read is unknown. */
61
+ function uninstallElevation(): Elevation {
62
+ if (elevationProbeForTests) return elevationProbeForTests() ? "elevated" : "unelevated";
63
+ if (process.platform !== "win32") return process.geteuid?.() === 0 ? "elevated" : "unelevated";
64
+ const native = isCurrentWindowsProcessElevated();
65
+ return native === null ? "unknown" : native ? "elevated" : "unelevated";
66
+ }
67
+
68
+ /** Whether the ownership checks apply: an elevated run, or one whose elevation is unknown. */
69
+ export function uninstallRunsElevated(): boolean {
70
+ return uninstallElevation() !== "unelevated";
71
+ }
72
+
73
+ function samePath(left: string, right: string): boolean {
74
+ return process.platform === "win32" ? left.toLowerCase() === right.toLowerCase() : left === right;
75
+ }
76
+
77
+ /** A link of any kind: a symlink or junction, or on Windows any other reparse point. */
78
+ function isLinkEntry(path: string, entry: Stats): boolean {
79
+ return entry.isSymbolicLink() || (NATIVE_REPARSE && isWindowsReparsePoint(path));
80
+ }
81
+
82
+ /** Another account can change this directory's entries (POSIX mode and owner). */
83
+ function posixSharedWritable(entry: Stats, euid: number): boolean {
84
+ return entry.uid !== euid || (entry.mode & 0o022) !== 0;
85
+ }
86
+
87
+ /** An ancestor no other account can change: owned by the uid or root, and not shared-writable unless sticky. */
88
+ function posixTrustedAncestor(entry: Stats, euid: number): boolean {
89
+ const sticky = (entry.mode & 0o1000) !== 0;
90
+ return (entry.uid === euid || entry.uid === 0) && ((entry.mode & 0o022) === 0 || sticky);
91
+ }
92
+
93
+ function errorCode(error: unknown): unknown {
94
+ return error !== null && typeof error === "object" && "code" in error ? error.code : undefined;
95
+ }
96
+
97
+ type Walk = { path: string; complete: boolean };
98
+
99
+ /**
100
+ * Every directory and link a spelling walk passed. macOS ACLs grant access independently of mode
101
+ * bits, including the right to delete a link itself, so each of them is ACL-checked afterwards.
102
+ */
103
+ type Visited = Set<string>;
104
+
105
+ /**
106
+ * Walk `parts` from the trusted directory `start` the way the kernel resolves them, following
107
+ * links. Every directory passed must be a trusted ancestor and every link must be owned by the uid or
108
+ * root, since a sticky directory still lets a link's owner replace it. A link target's `..` is taken
109
+ * from the physical directory reached so far, as the kernel does. Stops at the first missing entry.
110
+ */
111
+ function walkTrusted(
112
+ start: string,
113
+ parts: readonly string[],
114
+ euid: number,
115
+ depth: number,
116
+ visited: Visited,
117
+ /** The last component may be a regular file: a link in the tree can name a file. */
118
+ finalMayBeFile = false,
119
+ ): Walk {
120
+ let current = start;
121
+ const meaningful = parts.filter(part => part !== "" && part !== ".");
122
+ for (const [index, part] of meaningful.entries()) {
123
+ const last = index === meaningful.length - 1;
124
+ if (part === "..") { current = dirname(current); continue; }
125
+ const next = join(current, part);
126
+ let entry: Stats;
127
+ try {
128
+ entry = lstatSync(next);
129
+ } catch (error) {
130
+ if (errorCode(error) === "ENOENT") return { path: current, complete: false };
131
+ throw error;
132
+ }
133
+ if (entry.isSymbolicLink()) {
134
+ if (depth >= MAX_LINK_DEPTH || (entry.uid !== euid && entry.uid !== 0)) throw new OwnedPathRedirectedError();
135
+ visited.add(next);
136
+ const target = readlinkSync(next);
137
+ const walked = walkTrusted(
138
+ isAbsolute(target) ? parse(target).root : current, target.split(sep), euid, depth + 1, visited, finalMayBeFile && last,
139
+ );
140
+ if (!walked.complete) return walked;
141
+ current = walked.path;
142
+ continue;
143
+ }
144
+ if (finalMayBeFile && last && entry.isFile()) {
145
+ current = next;
146
+ continue;
147
+ }
148
+ if (!entry.isDirectory() || !posixTrustedAncestor(entry, euid)) throw new OwnedPathRedirectedError();
149
+ visited.add(next);
150
+ current = next;
151
+ }
152
+ return { path: current, complete: true };
153
+ }
154
+
155
+ /**
156
+ * The spelling uninstall was given must resolve only through directories and links no other account
157
+ * can change, because the teardown steps before the remover use it as given. A root that does not
158
+ * exist yet needs its nearest existing directory closed to every other account, sticky or not.
159
+ * Returns what the walk passed, for the ACL check, or null when the spelling is not trusted.
160
+ */
161
+ function posixSpellingVisited(configDir: string, euid: number): string[] | null {
162
+ const absolute = resolve(configDir);
163
+ const top = parse(absolute).root;
164
+ if (!posixTrustedAncestor(lstatSync(top), euid)) return null;
165
+ const visited: Visited = new Set([top]);
166
+ const walked = walkTrusted(top, absolute.slice(top.length).split(sep), euid, 0, visited);
167
+ // The walk built its path from verified real directories; its realpath only normalizes spelling
168
+ // (case, Unicode form), which a case- or normalization-insensitive volume may store differently.
169
+ if (walked.complete) return realpathSync.native(walked.path) === realpathSync.native(configDir) ? [...visited] : null;
170
+ const nearest = lstatSync(walked.path);
171
+ return (nearest.uid === euid || nearest.uid === 0) && (nearest.mode & 0o022) === 0 ? [...visited, walked.path] : null;
172
+ }
173
+
174
+ /** Windows: no component of the given spelling may be a link; returns the nearest existing directory. */
175
+ function windowsSpellingNearest(configDir: string): string | null {
176
+ const absolute = resolve(configDir);
177
+ let current = parse(absolute).root;
178
+ for (const part of absolute.slice(current.length).split(sep).filter(Boolean)) {
179
+ const next = join(current, part);
180
+ let entry: Stats;
181
+ try {
182
+ entry = lstatSync(next);
183
+ } catch (error) {
184
+ if (errorCode(error) === "ENOENT") return current;
185
+ throw error;
186
+ }
187
+ if (!entry.isDirectory() || isLinkEntry(next, entry)) return null;
188
+ current = next;
189
+ }
190
+ return current;
191
+ }
192
+
193
+ /**
194
+ * Throw unless the root still resolves to itself and every directory in `parts` below it is a real
195
+ * directory, not a link, whose resolved path stays inside the root. The relative part is not compared
196
+ * as a string: a case- or normalization-insensitive volume may store a name in another spelling. With
197
+ * `elevatedUid` set, each directory below the root must also be owned by that uid and not group- or
198
+ * other-writable.
199
+ */
200
+ function assertRealDirectoryChain(rootPath: string, parts: readonly string[], options: OwnedRemovalOptions): void {
201
+ const root = lstatSync(rootPath);
202
+ if (!root.isDirectory() || root.isSymbolicLink()) throw new OwnedPathRedirectedError();
203
+ if (options.rootIdentity && !sameIdentity(rootPath, options.rootIdentity)) throw new OwnedPathRedirectedError();
204
+ if (!samePath(realpathSync.native(rootPath), rootPath)) throw new OwnedPathRedirectedError();
205
+ let current = rootPath;
206
+ for (const part of parts) {
207
+ current = join(current, part);
208
+ const entry = lstatSync(current);
209
+ if (!entry.isDirectory() || isLinkEntry(current, entry)) throw new OwnedPathRedirectedError();
210
+ if (options.elevatedUid !== undefined && posixSharedWritable(entry, options.elevatedUid)) throw new OwnedPathRedirectedError();
211
+ }
212
+ if (parts.length > 0 && !isInsideRoot(rootPath, realpathSync.native(current))) throw new OwnedPathRedirectedError();
213
+ }
214
+
215
+ function isInsideRoot(rootPath: string, candidate: string): boolean {
216
+ const prefix = rootPath.endsWith(sep) ? rootPath : rootPath + sep;
217
+ return process.platform === "win32"
218
+ ? candidate.toLowerCase().startsWith(prefix.toLowerCase())
219
+ : candidate.startsWith(prefix);
220
+ }
221
+
222
+ function isAtOrInsideRoot(rootPath: string, candidate: string): boolean {
223
+ return samePath(candidate, rootPath) || isInsideRoot(rootPath, candidate);
224
+ }
225
+
226
+ /** The device and inode of the directory a canonical root named when it was resolved. */
227
+ export type RootIdentity = { dev: bigint; ino: bigint };
228
+
229
+ export function rootIdentity(rootPath: string): RootIdentity {
230
+ const entry = lstatSync(rootPath, { bigint: true });
231
+ return { dev: entry.dev, ino: entry.ino };
232
+ }
233
+
234
+ function sameIdentity(rootPath: string, identity: RootIdentity): boolean {
235
+ const entry = lstatSync(rootPath, { bigint: true });
236
+ return entry.dev === identity.dev && entry.ino === identity.ino;
237
+ }
238
+
239
+ /**
240
+ * Whether the canonical root is still a real directory that resolves to itself and, with
241
+ * `identity`, is still the directory it named when it was resolved.
242
+ */
243
+ export function canonicalRootUnchanged(rootPath: string, identity?: RootIdentity): boolean {
244
+ try {
245
+ assertRealDirectoryChain(rootPath, [], { rootIdentity: identity });
246
+ return true;
247
+ } catch {
248
+ return false;
249
+ }
250
+ }
251
+
252
+ /**
253
+ * Whether the recorded entry `parts` exists below `rootPath`. Absent means a real directory on the
254
+ * way, or the entry itself, does not exist (or a regular file sits where a directory would be). A link
255
+ * on the way, or any other lookup failure, throws so the entry is reported rather than dropped.
256
+ */
257
+ export function ownedEntryPresent(rootPath: string, parts: readonly string[]): boolean {
258
+ let current = rootPath;
259
+ for (const [index, part] of parts.entries()) {
260
+ current = join(current, part);
261
+ let entry: Stats;
262
+ try {
263
+ entry = lstatSync(current);
264
+ } catch (error) {
265
+ if (errorCode(error) === "ENOENT") return false;
266
+ throw error;
267
+ }
268
+ if (index === parts.length - 1) return true;
269
+ if (isLinkEntry(current, entry)) throw new OwnedPathRedirectedError();
270
+ if (!entry.isDirectory()) return false;
271
+ }
272
+ return false;
273
+ }
274
+
275
+ export interface OwnedRemovalOptions {
276
+ /** POSIX uid of an elevated run: directories removal passes through must belong to it alone. */
277
+ elevatedUid?: number;
278
+ /** The root's identity when it was resolved; every check also requires the root to still be it. */
279
+ rootIdentity?: RootIdentity;
280
+ }
281
+
282
+ /**
283
+ * Remove the recorded entry `parts` below the canonical `rootPath`. A final-component link is
284
+ * unlinked itself, never its target; a directory is emptied and removed with the chain rechecked for
285
+ * every child and before the rmdir.
286
+ */
287
+ export function removeOwnedEntry(rootPath: string, parts: readonly string[], options: OwnedRemovalOptions = {}): void {
288
+ assertRealDirectoryChain(rootPath, parts.slice(0, -1), options);
289
+ const path = join(rootPath, ...parts);
290
+ const entry = lstatSync(path);
291
+ if (entry.isSymbolicLink() || !entry.isDirectory()) {
292
+ unlinkSync(path);
293
+ return;
294
+ }
295
+ assertRealDirectoryChain(rootPath, parts, options);
296
+ const names = readdirSync(path);
297
+ directoryListedHookForTests?.(path);
298
+ for (const name of names) removeOwnedEntry(rootPath, [...parts, name], options);
299
+ assertRealDirectoryChain(rootPath, parts, options);
300
+ rmdirSync(path);
301
+ }
302
+
303
+ /**
304
+ * Every real directory in the root's tree, and every link in it, for the ownership checks. The
305
+ * teardown steps before the remover read and write files anywhere in the tree, so a link at any
306
+ * depth, to a file or a directory, must resolve to the root or a place inside it, through
307
+ * directories and links `resolveLink` accepts (it returns what it passed, or null). One that does
308
+ * not makes the tree unacceptable and the result is null.
309
+ */
310
+ function rootTree(
311
+ rootPath: string,
312
+ resolveLink: (link: string) => { path: string; visited: string[] } | null,
313
+ ): { directories: string[]; links: string[] } | null {
314
+ const directories: string[] = [];
315
+ const links: string[] = [];
316
+ const pending = [rootPath];
317
+ while (pending.length > 0) {
318
+ const directory = pending.pop()!;
319
+ directories.push(directory);
320
+ for (const name of readdirSync(directory)) {
321
+ const child = join(directory, name);
322
+ const entry = lstatSync(child);
323
+ if (isLinkEntry(child, entry)) {
324
+ const resolved = resolveLink(child);
325
+ if (resolved === null || !isAtOrInsideRoot(rootPath, resolved.path)) return null;
326
+ links.push(...resolved.visited);
327
+ } else if (entry.isDirectory()) {
328
+ pending.push(child);
329
+ }
330
+ }
331
+ }
332
+ return { directories, links };
333
+ }
334
+
335
+ function rootAncestors(rootPath: string): string[] {
336
+ const ancestors: string[] = [];
337
+ for (let current = dirname(rootPath); ; current = dirname(current)) {
338
+ ancestors.push(current);
339
+ if (dirname(current) === current) return ancestors;
340
+ }
341
+ }
342
+
343
+ function windowsAclAllows(entries: readonly WindowsAclEntry[]): boolean {
344
+ for (let start = 0; start < entries.length; start += WINDOWS_ACL_BATCH) {
345
+ if (!verifyWindowsEntriesAcl(entries.slice(start, start + WINDOWS_ACL_BATCH), WINDOWS_OWNER_ACL_TIMEOUT_MS)) return false;
346
+ }
347
+ return true;
348
+ }
349
+
350
+ /**
351
+ * macOS extended ACLs grant access independently of the mode bits. True when no listed directory has
352
+ * an allow entry; deny entries (such as the stock "everyone deny delete") take nothing away from the
353
+ * owner. A failed read counts as an allow entry.
354
+ */
355
+ function darwinAclsDenyOnly(paths: readonly string[]): boolean {
356
+ for (let start = 0; start < paths.length; start += DARWIN_LS_BATCH) {
357
+ const result = Bun.spawnSync(["/bin/ls", "-lde", "--", ...paths.slice(start, start + DARWIN_LS_BATCH)], {
358
+ stdin: "ignore", stdout: "pipe", stderr: "ignore", env: { PATH: "/usr/bin:/bin", LC_ALL: "C" },
359
+ });
360
+ if (!result.success) return false;
361
+ if (result.stdout.toString().split("\n").some(line => /^\s*\d+: .* allow \S+$/.test(line))) return false;
362
+ }
363
+ return true;
364
+ }
365
+
366
+ /**
367
+ * When uninstall runs elevated, a reason to refuse the whole run if another account can change the
368
+ * spelling it was given, the canonical root, one of its ancestors, or any directory in the root's
369
+ * tree, or if a link in that tree leads outside it. Null when the run is not elevated or all of it
370
+ * belongs to the elevated account alone. A missing root is checked through its nearest existing
371
+ * directory. A run whose elevation is unknown is checked as elevated.
372
+ */
373
+ export function elevatedRemovalRefusal(configDir: string): string | null {
374
+ const elevation = uninstallElevation();
375
+ if (elevation === "unelevated") return null;
376
+ const refusal = elevation === "unknown" ? UNKNOWN_ELEVATION_UNINSTALL_REFUSAL : ELEVATED_UNINSTALL_REFUSAL;
377
+ try {
378
+ return onlyThisAccountCanChange(configDir) ? null : refusal;
379
+ } catch {
380
+ return refusal;
381
+ }
382
+ }
383
+
384
+ function onlyThisAccountCanChange(configDir: string): boolean {
385
+ if (process.platform === "win32") {
386
+ const nearest = windowsSpellingNearest(configDir);
387
+ if (nearest === null) return false;
388
+ if (!existsSync(configDir)) {
389
+ return windowsAclAllows([
390
+ ...rootAncestors(nearest).map(path => ({ path, directory: true, policy: "trusted-ancestry" as const })),
391
+ { path: nearest, directory: true, policy: "write-private" as const },
392
+ ]);
393
+ }
394
+ const rootPath = realpathSync.native(configDir);
395
+ // An elevated Windows run accepts no link or reparse point anywhere in the tree.
396
+ const tree = rootTree(rootPath, () => null);
397
+ if (tree === null) return false;
398
+ return windowsAclAllows([
399
+ ...rootAncestors(rootPath).map(path => ({ path, directory: true, policy: "trusted-ancestry" as const })),
400
+ ...tree.directories.map(path => ({ path, directory: true, policy: "write-private" as const })),
401
+ ]);
402
+ }
403
+ const euid = process.geteuid?.();
404
+ if (euid === undefined) return false;
405
+ const visited = posixSpellingVisited(configDir, euid);
406
+ if (visited === null) return false;
407
+ const darwin = process.platform === "darwin";
408
+ if (!existsSync(configDir)) return !darwin || darwinAclsDenyOnly(visited);
409
+ const rootPath = realpathSync.native(configDir);
410
+ // Each link is resolved the way the kernel does, through trusted directories and links only, so a
411
+ // link that leaves the root on the way back into it is refused as well.
412
+ const tree = rootTree(rootPath, link => {
413
+ const linkVisited: Visited = new Set();
414
+ const walked = walkTrusted(dirname(link), [basename(link)], euid, 0, linkVisited, true);
415
+ return walked.complete ? { path: realpathSync.native(walked.path), visited: [...linkVisited] } : null;
416
+ });
417
+ if (tree === null) return false;
418
+ const ancestors = rootAncestors(rootPath);
419
+ if (!ancestors.every(path => posixTrustedAncestor(lstatSync(path), euid))) return false;
420
+ if (tree.directories.some(path => posixSharedWritable(lstatSync(path), euid))) return false;
421
+ return !darwin || darwinAclsDenyOnly([...new Set([...visited, ...ancestors, ...tree.directories, ...tree.links])]);
422
+ }