@bitkyc08/opencodex 2.91.0 → 2.93.0-preview.20261027

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 (360) hide show
  1. package/bin/ocx.mjs +47 -8
  2. package/gui/dist/assets/App-CJZoq-uF.js +58 -0
  3. package/gui/dist/assets/{Tray-BuLy7hL1.js → Tray-BWQPcgZn.js} +1 -1
  4. package/gui/dist/assets/index-DRe8Hhfz.css +1 -0
  5. package/gui/dist/assets/index-Xfct8owH.js +94 -0
  6. package/gui/dist/assets/quota-summary-DxToX1rV.js +1 -0
  7. package/gui/dist/index.html +2 -2
  8. package/gui/dist/provider-icons/workbuddy-color.svg +29 -0
  9. package/package.json +8 -7
  10. package/src/adapters/anthropic.ts +28 -5
  11. package/src/adapters/coding-agent/batch-dispatcher.ts +122 -0
  12. package/src/adapters/coding-agent/profile.ts +54 -16
  13. package/src/adapters/coding-agent/turn.ts +30 -2
  14. package/src/adapters/command-code.ts +114 -7
  15. package/src/adapters/cursor/native-exec-fs.ts +11 -9
  16. package/src/adapters/devin/live-models.ts +4 -0
  17. package/src/adapters/google-vertex-endpoint.ts +9 -1
  18. package/src/adapters/google-vertex-key-project.ts +223 -0
  19. package/src/adapters/google-wire-compiler.ts +1 -2
  20. package/src/adapters/google.ts +13 -3
  21. package/src/adapters/kiro/reasoning.ts +2 -0
  22. package/src/adapters/kiro-refusal.ts +6 -1
  23. package/src/adapters/kiro-wire.ts +1 -1
  24. package/src/adapters/openai-chat/messages.ts +8 -2
  25. package/src/adapters/openai-chat/passthrough.ts +35 -14
  26. package/src/adapters/openai-chat/reasoning-replay.ts +27 -16
  27. package/src/adapters/openai-chat/reasoning-wire.ts +117 -8
  28. package/src/adapters/openai-chat/required-tool-result.ts +64 -0
  29. package/src/adapters/openai-chat/tool-name-registry.ts +3 -1
  30. package/src/adapters/openai-chat.ts +9 -10
  31. package/src/adapters/openai-responses/passthrough.ts +7 -4
  32. package/src/adapters/openai-responses/reasoning.ts +13 -0
  33. package/src/adapters/openai-responses/request-strips.ts +60 -0
  34. package/src/adapters/qoder/adapter.ts +129 -8
  35. package/src/adapters/qoder/scaffold-guard.ts +5 -0
  36. package/src/adapters/reasoning-controls.ts +16 -0
  37. package/src/adapters/registry.ts +5 -0
  38. package/src/adapters/tool-call-id.ts +1 -3
  39. package/src/adapters/workbuddy-schema.ts +61 -0
  40. package/src/adapters/workbuddy.ts +68 -0
  41. package/src/bridge/errors.ts +27 -0
  42. package/src/bridge/response-json.ts +1 -1
  43. package/src/bridge/sse.ts +1 -1
  44. package/src/bridge.ts +1 -1
  45. package/src/chat/inbound.ts +4 -1
  46. package/src/chat/outbound.ts +20 -6
  47. package/src/chat/reasoning-details.ts +28 -5
  48. package/src/claude/desktop-first-party.ts +54 -4
  49. package/src/claude/desktop-picker.ts +11 -8
  50. package/src/claude/first-party-settings.ts +3 -1
  51. package/src/claude/inbound.ts +2 -1
  52. package/src/claude/intercept/local-ca.ts +2 -1
  53. package/src/claude/intercept/picker-ca-cleanup.ts +4 -2
  54. package/src/claude/intercept/picker-ca-startup.ts +3 -1
  55. package/src/claude/intercept/picker-models.ts +6 -3
  56. package/src/claude/intercept/picker-runtime.ts +3 -2
  57. package/src/claude/intercept/runtime.ts +6 -3
  58. package/src/claude/model-info.ts +31 -8
  59. package/src/cli/account-api.ts +11 -0
  60. package/src/cli/capabilities-agents-routing.ts +3 -3
  61. package/src/cli/capabilities-base.ts +7 -1
  62. package/src/cli/capabilities-observe-system.ts +10 -0
  63. package/src/cli/claude-desktop.ts +9 -8
  64. package/src/cli/claude.ts +3 -2
  65. package/src/cli/codex-cli-update.ts +8 -0
  66. package/src/cli/codex-shim-autorestore.ts +9 -0
  67. package/src/cli/combo-result.ts +13 -0
  68. package/src/cli/combo-stats.ts +3 -0
  69. package/src/cli/combo.ts +83 -41
  70. package/src/cli/cross-home-owner.ts +13 -1
  71. package/src/cli/dispatch.ts +25 -6
  72. package/src/cli/ensure-desired-integrations.ts +8 -6
  73. package/src/cli/export-command.ts +4 -1
  74. package/src/cli/help.ts +2 -1
  75. package/src/cli/index.ts +45 -45
  76. package/src/cli/integration-plan-dto.ts +4 -0
  77. package/src/cli/launcher-context.ts +49 -2
  78. package/src/cli/link.ts +45 -32
  79. package/src/cli/opencode.ts +20 -9
  80. package/src/cli/provider.ts +2 -1
  81. package/src/cli/registry.ts +6 -4
  82. package/src/cli/root.ts +9 -0
  83. package/src/cli/status.ts +59 -1
  84. package/src/cli/stop-restore.ts +113 -0
  85. package/src/cli/sync-expectation.ts +60 -0
  86. package/src/cli/uninstall-integrations.ts +41 -7
  87. package/src/cli/usage-compare.ts +68 -12
  88. package/src/client/connect.ts +40 -3
  89. package/src/client/link-home.ts +10 -1
  90. package/src/client/link-ingress.ts +1 -1
  91. package/src/client/link-readiness.ts +97 -0
  92. package/src/client/link-relay-transport.ts +79 -11
  93. package/src/client/link-relay.ts +74 -15
  94. package/src/client/link-tunnel.ts +45 -18
  95. package/src/client/machine-api.ts +3 -1
  96. package/src/client/machine-listener.ts +20 -2
  97. package/src/client/runtime.ts +20 -2
  98. package/src/client/sync-expectation.ts +118 -0
  99. package/src/clients/config-export/agent-clients.ts +96 -0
  100. package/src/clients/config-export/contracts.ts +25 -7
  101. package/src/clients/config-export/qoder.ts +38 -23
  102. package/src/clients/config-export/reasoning-metadata.ts +55 -8
  103. package/src/clients/config-export.ts +12 -0
  104. package/src/clients/lazycodex.ts +7 -2
  105. package/src/clients/reasoning-controls.ts +49 -0
  106. package/src/codex/account-store.ts +17 -3
  107. package/src/codex/app-server-restart-service.ts +6 -5
  108. package/src/codex/auth-api/account-identity.ts +14 -0
  109. package/src/codex/auth-api/account-list.ts +29 -2
  110. package/src/codex/auth-api/http.ts +13 -0
  111. package/src/codex/auth-api/main-account-probe.ts +2 -2
  112. package/src/codex/auth-api/pool-mode-gate.ts +16 -3
  113. package/src/codex/auth-api/pool-quota-probe.ts +15 -0
  114. package/src/codex/auth-context.ts +15 -12
  115. package/src/codex/catalog/build-entries.ts +22 -0
  116. package/src/codex/catalog/configured-tiers.ts +70 -0
  117. package/src/codex/catalog/effort.ts +52 -11
  118. package/src/codex/catalog/gather-capture.ts +5 -2
  119. package/src/codex/catalog/heal-observation.ts +155 -13
  120. package/src/codex/catalog/metadata.ts +6 -0
  121. package/src/codex/catalog/model-hints.ts +60 -11
  122. package/src/codex/catalog/model-visibility.ts +3 -2
  123. package/src/codex/catalog/native-models.ts +18 -3
  124. package/src/codex/catalog/parsing.ts +10 -8
  125. package/src/codex/catalog/pinned-models.ts +2 -1
  126. package/src/codex/catalog/provider-models.ts +18 -13
  127. package/src/codex/catalog/retained-sync.ts +2 -1
  128. package/src/codex/catalog/routed-gather.ts +19 -20
  129. package/src/codex/catalog/write-audit.ts +3 -2
  130. package/src/codex/catalog-self-heal.ts +43 -23
  131. package/src/codex/chatgpt-refresh-failure.ts +6 -2
  132. package/src/codex/cli-install-provenance.ts +418 -0
  133. package/src/codex/cli-installation-targets.ts +5 -1
  134. package/src/codex/cli-update-plan.ts +43 -16
  135. package/src/codex/collision-identity.ts +30 -5
  136. package/src/codex/convergence.ts +4 -3
  137. package/src/codex/data/roster-pinned-models.json +177 -1
  138. package/src/codex/desired-state.ts +6 -1
  139. package/src/codex/desktop-app/picker-freshness.ts +10 -8
  140. package/src/codex/desktop-compatibility/installed-build.ts +88 -12
  141. package/src/codex/desktop-compatibility/runtime.ts +29 -5
  142. package/src/codex/desktop-compatibility/usage-activation.ts +2 -1
  143. package/src/codex/desktop-compatibility/usage-controller.ts +9 -1
  144. package/src/codex/desktop-compatibility/windows-certificate-trust.ts +46 -12
  145. package/src/codex/inject/config-toml.ts +0 -18
  146. package/src/codex/inject/plan.ts +18 -3
  147. package/src/codex/inject/remove.ts +6 -2
  148. package/src/codex/inject.ts +1 -1
  149. package/src/codex/journal.ts +61 -1
  150. package/src/codex/model-entitlements.ts +1 -1
  151. package/src/codex/native-main-owner.ts +27 -1
  152. package/src/codex/native-profile-store.ts +2 -1
  153. package/src/codex/pool-credit-policy.ts +35 -1
  154. package/src/codex/pool-refresh-backoff.ts +3 -1
  155. package/src/codex/quota-types.ts +3 -0
  156. package/src/codex/quota.ts +24 -4
  157. package/src/codex/role-auto-assign.ts +6 -2
  158. package/src/codex/subagent-defaults.ts +49 -4
  159. package/src/codex/user-identity.ts +35 -6
  160. package/src/codex/windows-current-sid.ts +162 -0
  161. package/src/combos/failover.ts +17 -2
  162. package/src/combos/jev-decision-contract.ts +22 -1
  163. package/src/combos/jev-quota-activation.ts +5 -1
  164. package/src/combos/jev-quota-route.ts +1 -1
  165. package/src/combos/jev-quota.ts +9 -1
  166. package/src/combos/jev-service-exchange.ts +3 -1
  167. package/src/combos/jev-session-pin-config.ts +51 -0
  168. package/src/combos/jev.ts +101 -9
  169. package/src/combos/resolve.ts +45 -1
  170. package/src/combos/types.ts +43 -0
  171. package/src/config/load-degrade.ts +5 -0
  172. package/src/config/paths.ts +19 -3
  173. package/src/config/pending-teardown.ts +22 -1
  174. package/src/config/provider-validation.ts +22 -4
  175. package/src/config/removed-opencode-free.ts +11 -0
  176. package/src/config/schema/leaf-validators.ts +6 -0
  177. package/src/generated/compatibility-version.json +467 -311
  178. package/src/generated/model-metadata.ts +5 -5
  179. package/src/images/loop.ts +16 -2
  180. package/src/integrations/catalog-refresh.ts +1 -1
  181. package/src/integrations/hermes-profiles.ts +251 -0
  182. package/src/integrations/merge.ts +8 -0
  183. package/src/integrations/mutation-plan.ts +19 -4
  184. package/src/integrations/registry.ts +5 -0
  185. package/src/integrations/state.ts +36 -1
  186. package/src/integrations/writer.ts +18 -4
  187. package/src/lib/bun-path-runtime.mjs +2 -1
  188. package/src/lib/decision-quota-sink.ts +10 -0
  189. package/src/lib/errors.ts +62 -0
  190. package/src/lib/eventstream-decoder.ts +81 -37
  191. package/src/lib/opaque-proxy-tunnel.ts +32 -8
  192. package/src/lib/pinned-http.ts +35 -2
  193. package/src/lib/process-control.ts +13 -1
  194. package/src/lib/socks5-fetch.ts +59 -64
  195. package/src/lib/socks5-upload-waiter.ts +50 -0
  196. package/src/lib/sse-decoder.ts +7 -2
  197. package/src/lib/state-store-sweeper.ts +40 -14
  198. package/src/lib/translator-budget.ts +4 -4
  199. package/src/lib/upstream-retry.ts +4 -1
  200. package/src/lib/windows-native-principal-worker.ts +14 -0
  201. package/src/lib/windows-native-principal.ts +188 -0
  202. package/src/lib/windows-secret-acl.ts +39 -3
  203. package/src/lib/windows-user-principal.ts +62 -18
  204. package/src/link/diagnostics.ts +193 -0
  205. package/src/link/relay-auth.ts +6 -0
  206. package/src/link/ssh-config.ts +35 -3
  207. package/src/link/status-projection.ts +39 -0
  208. package/src/link/supervisor.ts +45 -12
  209. package/src/link/tunnel-history.ts +109 -0
  210. package/src/link/tunnel-state.ts +80 -17
  211. package/src/messaging/remote-files.ts +24 -1
  212. package/src/oauth/generic-account-failover.ts +91 -7
  213. package/src/oauth/index.ts +15 -0
  214. package/src/oauth/model-discovery-auth.ts +5 -0
  215. package/src/oauth/store.ts +4 -1
  216. package/src/oauth/token-guardian.ts +7 -0
  217. package/src/oauth/types.ts +9 -0
  218. package/src/oauth/workbuddy.ts +139 -0
  219. package/src/providers/account-quota-disk.ts +12 -4
  220. package/src/providers/antigravity-quota-identity.ts +37 -0
  221. package/src/providers/base-url-choices.ts +8 -5
  222. package/src/providers/codebuddy-models.ts +6 -0
  223. package/src/providers/codex-capacity.ts +3 -1
  224. package/src/providers/derive.ts +51 -3
  225. package/src/providers/kiro-models.ts +3 -0
  226. package/src/providers/mimo-thinking.ts +12 -0
  227. package/src/providers/model-discovery.ts +2 -0
  228. package/src/providers/model-rename-fields.ts +2 -0
  229. package/src/providers/model-rename-migration.ts +10 -0
  230. package/src/providers/openai-sidecar-credit.ts +2 -2
  231. package/src/providers/quota/account-cache.ts +3 -2
  232. package/src/providers/quota/antigravity.ts +25 -14
  233. package/src/providers/quota/report-cache.ts +13 -4
  234. package/src/providers/quota/vendor-probes-key.ts +60 -0
  235. package/src/providers/quota/workbuddy.ts +83 -0
  236. package/src/providers/quota-decision-antigravity.ts +64 -0
  237. package/src/providers/quota-decision-publication.ts +11 -0
  238. package/src/providers/quota-decision-snapshot.ts +21 -4
  239. package/src/providers/quota-types.ts +2 -0
  240. package/src/providers/quota.ts +3 -1
  241. package/src/providers/reasoning-capabilities.ts +76 -0
  242. package/src/providers/registry/entries-core.ts +23 -12
  243. package/src/providers/registry/entries-extended.ts +83 -27
  244. package/src/providers/registry/model-ids.ts +5 -0
  245. package/src/providers/registry/model-seeds.ts +120 -56
  246. package/src/providers/registry/types.ts +29 -2
  247. package/src/providers/resolved-model-policy.ts +30 -10
  248. package/src/providers/routed-config.ts +24 -1
  249. package/src/providers/stale-model-roster-migration.ts +123 -18
  250. package/src/providers/workbuddy-credit-balance.ts +81 -0
  251. package/src/providers/workbuddy-models.ts +37 -0
  252. package/src/providers/workbuddy.ts +60 -0
  253. package/src/remote-control/workspace-pi-runtime.ts +11 -6
  254. package/src/responses/compaction-summary.ts +45 -0
  255. package/src/responses/muse-tool-name-alias.ts +1 -2
  256. package/src/responses/parser.ts +3 -2
  257. package/src/responses/reasoning-replay-cache.ts +18 -14
  258. package/src/responses/schema.ts +1 -0
  259. package/src/responses/thought-signature-replay.ts +10 -2
  260. package/src/router.ts +2 -0
  261. package/src/routing/analytics.ts +2 -3
  262. package/src/routing/capability.ts +8 -2
  263. package/src/routing/fallback-policy.ts +3 -3
  264. package/src/routing/history/ingest.ts +28 -3
  265. package/src/server/auth-cors.ts +4 -2
  266. package/src/server/chat-completions.ts +21 -1
  267. package/src/server/chat-native-eligibility.ts +7 -0
  268. package/src/server/chat-native-reasoning.ts +24 -7
  269. package/src/server/chat-native.ts +13 -2
  270. package/src/server/claude-messages.ts +3 -0
  271. package/src/server/direct-local-http.ts +5 -2
  272. package/src/server/effort-policy.ts +5 -1
  273. package/src/server/index/link-relay-sessions.ts +9 -5
  274. package/src/server/index/live-sideband.ts +18 -15
  275. package/src/server/index/optional-listeners.ts +4 -0
  276. package/src/server/index/serve-options.ts +5 -4
  277. package/src/server/local-management-read-client.ts +3 -1
  278. package/src/server/management/agent-settings-routes.ts +27 -15
  279. package/src/server/management/combo-routes.ts +14 -4
  280. package/src/server/management/config-routes.ts +2 -2
  281. package/src/server/management/decision-discovery.ts +12 -2
  282. package/src/server/management/hermes-profile-routes.ts +156 -0
  283. package/src/server/management/integration-routes.ts +85 -24
  284. package/src/server/management/link-routes.ts +5 -2
  285. package/src/server/management/model-routes.ts +2 -2
  286. package/src/server/management/model-row-export-metadata.ts +25 -6
  287. package/src/server/management/model-rows.ts +15 -20
  288. package/src/server/management/native-integration-routes.ts +11 -8
  289. package/src/server/management/provider-routes.ts +1 -1
  290. package/src/server/management/route-registry.ts +4 -0
  291. package/src/server/management-api.ts +5 -0
  292. package/src/server/models-capabilities.ts +21 -3
  293. package/src/server/port-reclaim.ts +51 -9
  294. package/src/server/request-log-conversation.ts +49 -0
  295. package/src/server/request-log.ts +2 -0
  296. package/src/server/responses/adapter-delivery.ts +11 -1
  297. package/src/server/responses/adapter-dispatch.ts +2 -2
  298. package/src/server/responses/anthropic-thinking-recovery.ts +1 -0
  299. package/src/server/responses/codex-ws-exchange.ts +39 -9
  300. package/src/server/responses/codex-ws-session.ts +38 -4
  301. package/src/server/responses/codex-ws-wire.ts +6 -1
  302. package/src/server/responses/combo-required-tool-contract.ts +103 -0
  303. package/src/server/responses/combo-stream-preflight.ts +8 -1
  304. package/src/server/responses/compact.ts +14 -5
  305. package/src/server/responses/context-overflow.ts +8 -1
  306. package/src/server/responses/core-combo-failure.ts +10 -0
  307. package/src/server/responses/core-combo.ts +74 -44
  308. package/src/server/responses/core-lifetime.ts +5 -2
  309. package/src/server/responses/core-normalize.ts +17 -4
  310. package/src/server/responses/core-opaque-recovery.ts +1 -0
  311. package/src/server/responses/core-options.ts +7 -0
  312. package/src/server/responses/core-replay.ts +2 -1
  313. package/src/server/responses/jev-combo-choice.ts +39 -0
  314. package/src/server/responses/jev-session-pin.ts +203 -0
  315. package/src/server/responses/main-hard-lock-routing.ts +60 -44
  316. package/src/server/responses/passthrough-delivery.ts +44 -2
  317. package/src/server/responses/policy-fallback.ts +6 -1
  318. package/src/server/responses/request-compression.ts +12 -7
  319. package/src/server/responses/request-prepare.ts +32 -7
  320. package/src/server/responses/request-sidecar-auth.ts +2 -0
  321. package/src/server/responses/request-transport.ts +25 -6
  322. package/src/server/responses/response-effects.ts +22 -10
  323. package/src/server/responses/run-turn-execution.ts +2 -4
  324. package/src/server/responses/sidecar-execution.ts +13 -7
  325. package/src/server/responses-phase-inference.ts +267 -0
  326. package/src/server/sse-payload-rewrite.ts +14 -1
  327. package/src/server/stop-teardown.ts +36 -1
  328. package/src/server/ws-bridge.ts +1 -1
  329. package/src/service/definition.ts +20 -8
  330. package/src/service/desktop-supervision.d.mts +7 -4
  331. package/src/service/desktop-supervision.mjs +90 -13
  332. package/src/service/ownership-mutation-lease.mjs +21 -7
  333. package/src/types/config.ts +14 -2
  334. package/src/types/provider.ts +29 -7
  335. package/src/types/request.ts +11 -0
  336. package/src/types/wire.ts +1 -0
  337. package/src/types.ts +1 -0
  338. package/src/update/bind-probe.ts +29 -0
  339. package/src/update/codex-cli-update-launch-policy.d.mts +9 -0
  340. package/src/update/codex-cli-update-launch-policy.mjs +30 -0
  341. package/src/update/job.ts +10 -29
  342. package/src/update/npm-install-job.ps1 +173 -0
  343. package/src/update/npm-install.mjs +70 -0
  344. package/src/update/stop-contract.d.mts +1 -0
  345. package/src/update/stop-contract.mjs +14 -0
  346. package/src/update/stop-decision.d.mts +1 -1
  347. package/src/update/stop-decision.mjs +13 -3
  348. package/src/update/teardown-handover.ts +166 -0
  349. package/src/update/transactional-install.d.mts +14 -3
  350. package/src/update/transactional-install.mjs +33 -7
  351. package/src/usage/expected-prices.ts +64 -31
  352. package/src/usage/jev-stats.ts +54 -14
  353. package/src/usage/timeline.ts +19 -9
  354. package/src/vision/eligibility.ts +15 -5
  355. package/src/vision/plan.ts +2 -2
  356. package/src/web-search/loop.ts +16 -2
  357. package/gui/dist/assets/App-nZ34cR5G.js +0 -58
  358. package/gui/dist/assets/index-DGXS51sp.js +0 -94
  359. package/gui/dist/assets/index-DPeB9HpV.css +0 -1
  360. package/gui/dist/assets/quota-summary-DO1Sx5TM.js +0 -1
@@ -1,3 +1,4 @@
1
+ import { flushLinkDiagnostics, recordLinkDiagnostic } from "../link/diagnostics";
1
2
  import { existsSync } from "node:fs";
2
3
  import type { Server } from "bun";
3
4
  import { siblingRuntimeField, withSiblingMarker } from "../codex/sibling-start";
@@ -20,6 +21,7 @@ import type { ReplacementStartRequest } from "../server/restart-replacement";
20
21
  import type { OcxClientConnectionConfig } from "../types";
21
22
  import { createLinkKeySource } from "./link-ingress";
22
23
  import { HOME_INITIATED_LINK_TUNNEL } from "./link-relay";
24
+ import { clientInitiatedLinkReadiness, createHomeInitiatedLinkReadiness } from "./link-readiness";
23
25
  import { createClientLinkSupervisor, type ClientLinkSupervisor } from "./link-tunnel";
24
26
  import { clientLinkStatePath, isChildInitiatedLink, recordChildInitiatedLink } from "./link-state";
25
27
  import { startMachineListener, type MachineListenerDeps } from "./machine-listener";
@@ -164,6 +166,7 @@ export async function recycleStandalone(
164
166
  console.warn(`[client] listener stop failed: ${error instanceof Error ? error.message : String(error)}`);
165
167
  }
166
168
  cleanup();
169
+ await flushLinkDiagnostics();
167
170
  // Recycling back to standalone after `ocx disconnect` must actually bring a standalone
168
171
  // proxy back, under every launch shape.
169
172
  //
@@ -227,7 +230,7 @@ export async function bindClientListener(
227
230
  preferred: number;
228
231
  explicitPort: boolean;
229
232
  configuredPort: number;
230
- } & Pick<MachineListenerDeps, "linkStatus" | "linkKeySource" | "linkTunnel" | "restart">,
233
+ } & Pick<MachineListenerDeps, "linkStatus" | "linkKeySource" | "linkTunnel" | "linkReadiness" | "restart">,
231
234
  io: ClientRuntimeIo = {},
232
235
  ): Promise<{ server: Server<unknown>; port: number }> {
233
236
  const { linkMode } = request;
@@ -267,6 +270,7 @@ export async function bindClientListener(
267
270
  ...(request.linkStatus ? { linkStatus: request.linkStatus } : {}),
268
271
  ...(request.linkKeySource ? { linkKeySource: request.linkKeySource } : {}),
269
272
  ...(request.linkTunnel ? { linkTunnel: request.linkTunnel } : {}),
273
+ ...(request.linkReadiness ? { linkReadiness: request.linkReadiness } : {}),
270
274
  ...(request.restart ? { restart: request.restart } : {}),
271
275
  });
272
276
  return { server, port: server.port ?? port };
@@ -318,10 +322,19 @@ export async function startClientRuntime(
318
322
  const serve = async (rollback?: { port: number; portWaitMs: number }): Promise<boolean> => {
319
323
  const supervisor = supervised
320
324
  ? createClientLinkSupervisor({
325
+ diagnostic: recordLinkDiagnostic,
321
326
  onLinkEnded: () => scheduleStandaloneRecycle(state.value.tokenFingerprint),
322
327
  linkKey,
323
328
  })
324
329
  : null;
330
+ // What `/readyz` reports about the link: the supervisor's tunnel, or for a Home-initiated
331
+ // link the shared relay preflight. A link with neither refuses every relayed request.
332
+ const link = state.value.link;
333
+ const linkReadiness: MachineListenerDeps["linkReadiness"] = !linkMode ? undefined
334
+ : supervisor ? () => clientInitiatedLinkReadiness(supervisor.status())
335
+ : homeInitiated && link && linkKey
336
+ ? createHomeInitiatedLinkReadiness({ target: { tunnelPort: link.tunnelPort, linkId: link.linkId, apiKeyId: state.value.apiKeyId }, linkKey })
337
+ : () => ({ ready: false, reason: "tunnel_unavailable" });
325
338
  const { server, port: boundPort } = await bindClientListener({
326
339
  state: state.value,
327
340
  linkMode,
@@ -332,6 +345,7 @@ export async function startClientRuntime(
332
345
  restart: { attestationSecret, startedAt: CLIENT_RUNTIME_STARTED_AT, request: () => restartController.request() },
333
346
  ...(linkMode ? { linkStatus: () => activeSupervisor?.status() ?? { kind: "stopped" as const }, linkKeySource: linkKey } : {}),
334
347
  ...(supervisor ? { linkTunnel: supervisor } : homeInitiated ? { linkTunnel: HOME_INITIATED_LINK_TUNNEL } : {}),
348
+ ...(linkReadiness ? { linkReadiness } : {}),
335
349
  }, rollback === undefined ? io : { ...io, portWaitMs: rollback.portWaitMs });
336
350
  const publish = (): void => {
337
351
  activeServer = server;
@@ -417,7 +431,10 @@ export async function startClientRuntime(
417
431
  await recycleStandalone(state.value.tokenFingerprint);
418
432
  }
419
433
  },
420
- exitProcess: code => { process.exit(code); },
434
+ exitProcess: async code => {
435
+ await flushLinkDiagnostics();
436
+ process.exit(code);
437
+ },
421
438
  });
422
439
 
423
440
  installCrashGuards();
@@ -444,6 +461,7 @@ export async function startClientRuntime(
444
461
  console.warn(`[client] listener stop failed: ${error instanceof Error ? error.message : String(error)}`);
445
462
  } finally {
446
463
  cleanup();
464
+ await flushLinkDiagnostics();
447
465
  // launchd relaunches only unsuccessful exits; an external signal must still count.
448
466
  process.exit(handledSignalExitCode(signal));
449
467
  }
@@ -0,0 +1,118 @@
1
+ /**
2
+ * #7694: a caller-supplied identity that `ocx sync` must find before it syncs anything.
3
+ *
4
+ * GOAT reads `ocx connect status --json` and then runs `ocx sync` in a separate process; between
5
+ * the two the machine can be disconnected or relinked to another Home. The expectation closes that
6
+ * gap by being checked inside the same locked block that selects the connected path
7
+ * (`syncConnectedClient`), and every later write there is compare-and-swapped against the
8
+ * connection that passed it. A mismatch writes nothing and never falls back to local providers.
9
+ */
10
+ import type { DesktopDisconnectReceipt } from "../claude/desktop-remote-store";
11
+ import { readDesktopDisconnectReceipt } from "../claude/desktop-remote-store";
12
+ import { isLinkConnection, pendingClientConnectMayOwnToken, readClientConnectionState, type ClientConnectionState } from "./state";
13
+
14
+ export type ClientSyncExpectation =
15
+ | { kind: "link"; linkId: string }
16
+ | { kind: "hub"; apiKeyId: string };
17
+
18
+ export type ClientSyncMismatchPhase = "child_link_mismatch" | "hub_client_mismatch";
19
+
20
+ export type ClientSyncMismatchReason =
21
+ | "disconnected"
22
+ | "invalid_state"
23
+ | "disconnect_pending"
24
+ | "pending_operation"
25
+ | "hub_client"
26
+ | "link_client"
27
+ | "other_link"
28
+ | "other_key";
29
+
30
+ type DisconnectReceiptRead =
31
+ | { kind: "absent" }
32
+ | { kind: "valid"; value: Pick<DesktopDisconnectReceipt, "phase"> }
33
+ | { kind: "unsafe" };
34
+
35
+ /** What a connect in flight leaves behind before it commits: nothing, its marker, or an unreadable one. */
36
+ export type PendingConnectRead = "absent" | "present" | "unsafe";
37
+
38
+ export class ClientSyncExpectationError extends Error {
39
+ readonly phase: ClientSyncMismatchPhase;
40
+ readonly reason: ClientSyncMismatchReason;
41
+
42
+ constructor(expectation: ClientSyncExpectation, reason: ClientSyncMismatchReason) {
43
+ const phase = mismatchPhase(expectation);
44
+ super(`${phase}: ${reason}`);
45
+ this.name = "ClientSyncExpectationError";
46
+ this.phase = phase;
47
+ this.reason = reason;
48
+ }
49
+ }
50
+
51
+ export function mismatchPhase(expectation: ClientSyncExpectation): ClientSyncMismatchPhase {
52
+ return expectation.kind === "link" ? "child_link_mismatch" : "hub_client_mismatch";
53
+ }
54
+
55
+ function errorCode(error: unknown): unknown {
56
+ return error && typeof error === "object" && "code" in error ? (error as { code: unknown }).code : undefined;
57
+ }
58
+
59
+ /**
60
+ * A lock the check needs is held: the apply lock by a link connect or another apply
61
+ * (`link_apply_busy`), the client lifecycle lock (`client_lifecycle_busy`), or the config mutation
62
+ * lock by another config writer. Only real contention counts for the config lock, classified as in
63
+ * `src/config/mutation-lock.ts`; any other acquisition or storage failure stays itself. Before the
64
+ * check ran, a pinned sync cannot know which connection it would serve, so it is refused as pending.
65
+ */
66
+ export function isClientSyncLockBusy(error: unknown): boolean {
67
+ const code = errorCode(error);
68
+ if (code === "link_apply_busy" || code === "client_lifecycle_busy") return true;
69
+ if (code !== "CONFIG_MUTATION_LOCK_UNAVAILABLE") return false;
70
+ const cause = (error as { cause?: unknown }).cause;
71
+ const causeCode = errorCode(cause);
72
+ return causeCode === "SQLITE_BUSY" || causeCode === "SQLITE_LOCKED"
73
+ || (cause instanceof Error && /database (?:is|table is) locked/i.test(cause.message));
74
+ }
75
+
76
+ /**
77
+ * Pure verdict: null when the expectation holds. An unfinished disconnect wins over everything,
78
+ * because it is already tearing down whichever connection the state still names. A connect only
79
+ * starts from a disconnected machine, so its marker is consulted only there.
80
+ */
81
+ export function classifyClientSyncExpectation(
82
+ state: ClientConnectionState,
83
+ receipt: DisconnectReceiptRead,
84
+ expectation: ClientSyncExpectation,
85
+ pendingConnect: PendingConnectRead = "absent",
86
+ ): ClientSyncMismatchReason | null {
87
+ if (receipt.kind === "unsafe" || (receipt.kind === "valid" && receipt.value.phase !== "complete")) return "disconnect_pending";
88
+ if (state.kind === "invalid" || state.kind === "mismatched") return "invalid_state";
89
+ if (state.kind === "disconnected") {
90
+ if (pendingConnect === "present") return "pending_operation";
91
+ return pendingConnect === "unsafe" ? "invalid_state" : "disconnected";
92
+ }
93
+ const connection = state.value;
94
+ if (connection.pendingOperation) return "pending_operation";
95
+ if (expectation.kind === "link") {
96
+ if (!isLinkConnection(connection)) return "hub_client";
97
+ return connection.link?.linkId === expectation.linkId ? null : "other_link";
98
+ }
99
+ if (isLinkConnection(connection)) return "link_client";
100
+ return connection.apiKeyId === expectation.apiKeyId ? null : "other_key";
101
+ }
102
+
103
+ function readPendingConnect(): PendingConnectRead {
104
+ try { return pendingClientConnectMayOwnToken() ? "present" : "absent"; }
105
+ catch { return "unsafe"; }
106
+ }
107
+
108
+ /** Read-only; the caller holds the client lifecycle and config mutation locks. */
109
+ export function assertClientSyncExpectation(expectation: ClientSyncExpectation): void {
110
+ const state = readClientConnectionState();
111
+ const reason = classifyClientSyncExpectation(
112
+ state,
113
+ readDesktopDisconnectReceipt(),
114
+ expectation,
115
+ state.kind === "disconnected" ? readPendingConnect() : "absent",
116
+ );
117
+ if (reason) throw new ClientSyncExpectationError(expectation, reason);
118
+ }
@@ -0,0 +1,96 @@
1
+ import { homedir } from "node:os";
2
+ import { isAbsolute, join } from "node:path";
3
+ import { isLoopbackHostname, shouldInjectApiAuthHeader } from "../../codex/loopback-target";
4
+ import { ClientPathError } from "../client-path";
5
+ import { parseSegment } from "../../integrations/merge";
6
+ import type { ExportContext, ExportClientId, ManagedContribution, OpencodeLaunchEnv } from "./contracts";
7
+ import { LOOPBACK_API_KEY_PLACEHOLDER } from "./constants";
8
+ import { normalizeExportModels, authoritativeContextWindow } from "./model-metadata";
9
+ import { buildQoderClientConfig, buildQoderContribution } from "./qoder";
10
+
11
+ export function agentHomeDir(client: "qoder-cn" | "workbuddy" | "workbuddy-ai", env: OpencodeLaunchEnv = process.env, home = homedir()): string {
12
+ const key = client === "qoder-cn" ? "QODERCN_CONFIG_DIR" : "WORKBUDDY_CONFIG_DIR";
13
+ // Both WorkBuddy editions use the same native override; the default roots stay separate.
14
+ const override = env[key]?.trim() || (client === "qoder-cn" ? undefined : env.CODEBUDDY_CONFIG_DIR?.trim());
15
+ if (!override) return join(home, `.${client}`);
16
+ if (override === "~") return home;
17
+ if (override.startsWith("~/") || override.startsWith("~\\")) return join(home, override.slice(2));
18
+ if (!isAbsolute(override)) throw new ClientPathError(`${key} must be an absolute path or start with ~.`);
19
+ return override;
20
+ }
21
+
22
+ export function agentConfigPath(client: "qoder-cn" | "workbuddy" | "workbuddy-ai", env: OpencodeLaunchEnv = process.env, home = homedir()): string {
23
+ return join(agentHomeDir(client, env, home), client === "qoder-cn" ? "settings.json" : "models.json");
24
+ }
25
+
26
+ export function buildQoderCnClientConfig(ctx: ExportContext) {
27
+ return buildQoderClientConfig(ctx);
28
+ }
29
+ export function buildQoderCnContribution(ctx: ExportContext): ManagedContribution {
30
+ return { ...buildQoderContribution(ctx), clientId: "qoder-cn" };
31
+ }
32
+
33
+ function modelSelector(id: string): string | null {
34
+ const selector = `[id=${id}]`;
35
+ const parsed = parseSegment(selector);
36
+ if (parsed.kind !== "select" || parsed.criteria[0]?.value !== id) {
37
+ return null;
38
+ }
39
+ return selector;
40
+ }
41
+
42
+ function workbuddyRows(ctx: ExportContext) {
43
+ return normalizeExportModels(ctx.models).map(model => {
44
+ return {
45
+ id: model.namespaced,
46
+ name: `OpenCodex: ${model.displayName ?? model.namespaced}`,
47
+ vendor: "OpenAI",
48
+ url: `${ctx.baseUrl.replace(/\/+$/, "")}/chat/completions`,
49
+ apiKey: LOOPBACK_API_KEY_PLACEHOLDER,
50
+ ...(authoritativeContextWindow(model.maxInputTokens) ? { maxInputTokens: authoritativeContextWindow(model.maxInputTokens) } : {}),
51
+ ...(authoritativeContextWindow(model.maxTokens) ? { maxOutputTokens: authoritativeContextWindow(model.maxTokens) } : {}),
52
+ ...(model.supportsTools === undefined ? {} : { supportsToolCall: model.supportsTools }),
53
+ ...(model.inputModalities === undefined ? {} : { supportsImages: model.inputModalities.includes("image") }),
54
+ ...(model.supportsReasoning === undefined ? {} : { supportsReasoning: model.supportsReasoning }),
55
+ };
56
+ });
57
+ }
58
+
59
+ export function buildWorkbuddyClientConfig(ctx: ExportContext) {
60
+ if (shouldInjectApiAuthHeader(ctx.config) || !isLoopbackHostname(new URL(ctx.baseUrl).hostname)) {
61
+ throw new Error("WorkBuddy's placeholder API key requires a loopback-only listener.");
62
+ }
63
+ return { models: workbuddyRows(ctx) };
64
+ }
65
+
66
+ export function summarizeWorkbuddy(document: unknown) {
67
+ const rows = Array.isArray(document) ? document : (document as { models?: unknown[] } | undefined)?.models ?? [];
68
+ return { modelCount: rows.length, modelsWithoutLimits: rows.filter(row => !(row as { maxInputTokens?: number }).maxInputTokens).length };
69
+ }
70
+
71
+ /** Write-time validation must not prevent status, disable or snapshot recovery. */
72
+ export function workbuddyApplyRefusal(ctx: ExportContext): string | null {
73
+ const models = workbuddyRows(ctx);
74
+ if (models.some(model => modelSelector(model.id) === null)) {
75
+ return "WorkBuddy model ID cannot be represented by a managed array selector.";
76
+ }
77
+ if (models.length === 0) return "WorkBuddy has no models in the selected OpenCodex catalog.";
78
+ const available = (ctx.document as { availableModels?: unknown } | undefined)?.availableModels;
79
+ if (Array.isArray(available) && available.length > 0 && models.some(model => !available.includes(model.id) && !available.includes(`custom-local:${model.id}`))) {
80
+ return "WorkBuddy availableModels hides OpenCodex models; remove the restriction in WorkBuddy before enabling this connection.";
81
+ }
82
+ return null;
83
+ }
84
+
85
+ /** An unaddressable catalog contributes no desired rows; recorded ownership still protects recovery. */
86
+ export function buildWorkbuddyContribution(clientId: ExportClientId, ctx: ExportContext): ManagedContribution {
87
+ const fragments: ManagedContribution["fragments"][number][] = [];
88
+ for (const model of workbuddyRows(ctx)) {
89
+ const selector = modelSelector(model.id);
90
+ // Apply/refresh refuse in validateApply. Status/disable must classify the
91
+ // saved fragment paths without depending on today's unaddressable catalog.
92
+ if (selector === null) return { clientId, fragments: [] };
93
+ fragments.push({ path: [...(Array.isArray(ctx.document) ? [] : ["models"]), selector], value: model });
94
+ }
95
+ return { clientId, fragments };
96
+ }
@@ -57,10 +57,13 @@ export interface OpencodeCatalogModel {
57
57
  inputModalities?: readonly string[];
58
58
  /** Declared effort ladder. Exported as opencode model variants where the client reads them. */
59
59
  reasoningEfforts?: readonly string[];
60
+ supportsThinkingToggle?: boolean;
61
+ supportsReasoningEffort?: boolean;
62
+ defaultThinkingEnabled?: boolean;
60
63
  /**
61
64
  * Declared default effort. Carried so every client export reads one deduped, visibility-
62
- * filtered ladder per model. The opencode serializer deliberately does NOT turn it into a
63
- * model-level setting — see {@link opencodeEffortVariants} for why.
65
+ * filtered ladder per model. Client serializers map it into their own model defaults
66
+ * and allow the selected variant to override it.
64
67
  */
65
68
  defaultReasoningEffort?: string;
66
69
  supportsTools?: boolean;
@@ -90,6 +93,9 @@ export interface ExportModel {
90
93
  inputModalities?: string[];
91
94
  /** Optional effort ladder exported only to clients that support it. */
92
95
  reasoningEfforts?: string[];
96
+ supportsThinkingToggle?: boolean;
97
+ supportsReasoningEffort?: boolean;
98
+ defaultThinkingEnabled?: boolean;
93
99
  defaultReasoningEffort?: string;
94
100
  supportsTools?: boolean;
95
101
  supportsReasoning?: boolean;
@@ -116,6 +122,9 @@ export interface EffectiveModelExportMetadata {
116
122
  inputModalities?: string[];
117
123
  /** Effective ladder; `[]` is an explicit "no rungs" declaration and survives as `[]`. */
118
124
  reasoningEfforts?: string[];
125
+ supportsThinkingToggle?: boolean;
126
+ supportsReasoningEffort?: boolean;
127
+ defaultThinkingEnabled?: boolean;
119
128
  /**
120
129
  * A default some canonical source declared — never one synthesized from the ladder's
121
130
  * preference order, and only when it is a member of the effective ladder. An empty
@@ -128,11 +137,14 @@ export interface EffectiveModelExportMetadata {
128
137
  }
129
138
 
130
139
  /**
131
- * The per-row evidence the capability booleans are derived from. Only positive, canonical
132
- * signals — no independent provider fact tables, no name-based inference.
140
+ * Canonical explicit capabilities and positive evidence for otherwise unknown booleans.
141
+ * No independent provider fact tables or name-based inference.
133
142
  */
134
143
  export interface ExportCapabilityEvidence {
135
144
  native?: boolean;
145
+ supportsReasoning?: boolean;
146
+ supportsThinkingToggle?: boolean;
147
+ supportsReasoningEffort?: boolean;
136
148
  reasoningEfforts?: readonly string[];
137
149
  supportsReasoningSummaries?: boolean;
138
150
  /** Normalized upstream capability names a catalog row carried (e.g. `"tools"`). */
@@ -156,8 +168,7 @@ export function knownToolsSupport(evidence: ExportCapabilityEvidence): boolean |
156
168
  }
157
169
 
158
170
  /**
159
- * Reasoning support a canonical source positively asserts, or undefined when nothing is
160
- * known.
171
+ * Explicit reasoning support, or positive canonical evidence when no boolean is declared.
161
172
  *
162
173
  * Never `false` from a missing or empty effort ladder: an empty ladder says "no ADJUSTABLE
163
174
  * effort", which is not the claim "cannot reason" — a model can reason at a fixed depth with
@@ -167,8 +178,10 @@ export function knownToolsSupport(evidence: ExportCapabilityEvidence): boolean |
167
178
  * nothing about whether the model reasons, so it is not positive evidence on its own.
168
179
  */
169
180
  export function knownReasoningSupport(evidence: ExportCapabilityEvidence): boolean | undefined {
181
+ if (typeof evidence.supportsReasoning === "boolean") return evidence.supportsReasoning;
182
+ if (evidence.supportsThinkingToggle === true || evidence.supportsReasoningEffort === true) return true;
170
183
  if (evidence.supportsReasoningSummaries === true) return true;
171
- if (evidence.reasoningEfforts !== undefined
184
+ if (evidence.supportsReasoningEffort !== false && evidence.reasoningEfforts !== undefined
172
185
  && canonicalizeReasoningEfforts(evidence.reasoningEfforts).some(effort => effort !== "none")) {
173
186
  return true;
174
187
  }
@@ -203,6 +216,9 @@ export type DroidReasoningDefaults = Record<string, string>;
203
216
 
204
217
  export type ExportClientId =
205
218
  | "qoder"
219
+ | "qoder-cn"
220
+ | "workbuddy"
221
+ | "workbuddy-ai"
206
222
  | "opencode"
207
223
  | "pi"
208
224
  | "omp"
@@ -262,6 +278,8 @@ export interface ExportClientSpec {
262
278
  * reasoning as the Grok managed block's non-loopback refusal.
263
279
  */
264
280
  loopbackOnly: boolean;
281
+ /** Refuse apply/refresh without blocking status, disable or Undo. Pure and value-free. */
282
+ validateApply?: (ctx: ExportContext) => string | null;
265
283
  /**
266
284
  * True when the destination file may carry comments and trailing commas
267
285
  * even though `format` is "json" and serialization stays pretty JSON.
@@ -1,8 +1,7 @@
1
1
  import { homedir } from "node:os";
2
2
  import { isAbsolute, join } from "node:path";
3
3
  import { isLoopbackHostname, shouldInjectApiAuthHeader } from "../../codex/loopback-target";
4
- import { formatSelectorConjunction } from "../../integrations/merge";
5
- import { ClientPathError } from "../config-export";
4
+ import { ClientPathError } from "../client-path";
6
5
  import type { ExportContext, ManagedContribution, OpencodeLaunchEnv } from "./contracts";
7
6
  import { LOOPBACK_API_KEY_PLACEHOLDER, OPENCODE_PROVIDER_ID } from "./constants";
8
7
  import { authoritativeContextWindow, normalizeExportModels } from "./model-metadata";
@@ -30,7 +29,7 @@ export function qoderConfigPath(env: OpencodeLaunchEnv = process.env, home: stri
30
29
  return join(qoderHomeDir(env, home), "settings.json");
31
30
  }
32
31
 
33
- /** Qoder IDE and qodercli share this provider and custom-model catalog. */
32
+ /** Qoder IDE and qodercli share this custom-provider catalog. */
34
33
  export function buildQoderClientConfig(ctx: ExportContext) {
35
34
  if (shouldInjectApiAuthHeader(ctx.config) || !isLoopbackHostname(new URL(ctx.baseUrl).hostname)) {
36
35
  throw new Error("Qoder's placeholder API key requires a loopback-only listener.");
@@ -49,26 +48,21 @@ function qoderDocument(ctx: ExportContext) {
49
48
  baseUrl: ctx.baseUrl,
50
49
  apiKey: LOOPBACK_API_KEY_PLACEHOLDER,
51
50
  ...(models[0] ? { defaultModel: models[0].namespaced } : {}),
52
- models: models.map(model => ({ model: model.namespaced })),
51
+ // Register each key once; legacy customModels entries shadow this provider.
52
+ models: models.map(model => ({
53
+ model: model.namespaced,
54
+ displayName: model.namespaced,
55
+ contextWindow: authoritativeContextWindow(model.contextWindow) ?? 128000,
56
+ })),
53
57
  },
54
58
  },
55
- modelConfigs: {
56
- customModels: models.map(model => ({
57
- provider: OPENCODE_PROVIDER_ID,
58
- apiKey: LOOPBACK_API_KEY_PLACEHOLDER,
59
- model: model.namespaced,
60
- baseURL: ctx.baseUrl,
61
- displayName: model.namespaced,
62
- maxInputTokens: authoritativeContextWindow(model.contextWindow) ?? 128000,
63
- })),
64
- },
65
59
  };
66
60
  }
67
61
 
68
62
  export type QoderGeneratedConfig = ReturnType<typeof buildQoderClientConfig>;
69
63
 
70
64
  export function summarizeQoder(document: unknown): { modelCount: number; modelsWithoutLimits: number } {
71
- const models = (document as QoderGeneratedConfig | undefined)?.modelConfigs?.customModels ?? [];
65
+ const models = (document as QoderGeneratedConfig | undefined)?.providers?.[OPENCODE_PROVIDER_ID]?.models ?? [];
72
66
  return { modelCount: models.length, modelsWithoutLimits: 0 };
73
67
  }
74
68
 
@@ -80,14 +74,35 @@ export function buildQoderContribution(ctx: ExportContext): ManagedContribution
80
74
  clientId: "qoder",
81
75
  fragments: [
82
76
  { path: ["providers", OPENCODE_PROVIDER_ID], value: doc.providers[OPENCODE_PROVIDER_ID] },
83
- ...doc.modelConfigs.customModels.map(model => {
84
- const selector = formatSelectorConjunction([
85
- { field: "provider", value: OPENCODE_PROVIDER_ID },
86
- { field: "model", value: model.model },
87
- ]);
88
- if (selector === null) throw new Error("Qoder model ID cannot be represented by a managed array selector.");
89
- return { path: ["modelConfigs", "customModels", selector], value: model };
90
- }),
91
77
  ],
92
78
  };
93
79
  }
80
+
81
+ function isPlainRecord(value: unknown): value is Record<string, unknown> {
82
+ return typeof value === "object" && value !== null && !Array.isArray(value);
83
+ }
84
+
85
+ /**
86
+ * Does an unowned legacy `modelConfigs.customModels` row name a model this
87
+ * contribution's provider catalog exports? Qoder rejects the whole provider
88
+ * when one key appears in both catalogs, so keeping such a row while adding
89
+ * `providers.opencodex` recreates the failure the provider-only export fixes,
90
+ * and deleting it would discard configuration we never wrote. `owned` holds
91
+ * the rows an ownership record still names; refresh removes those itself.
92
+ */
93
+ export function qoderLegacyCatalogCollision(
94
+ doc: unknown,
95
+ contribution: ManagedContribution,
96
+ owned: ReadonlySet<unknown>,
97
+ ): boolean {
98
+ const provider = contribution.fragments.find(fragment => fragment.path.length === 2
99
+ && fragment.path[0] === "providers" && fragment.path[1] === OPENCODE_PROVIDER_ID)?.value;
100
+ const exported = new Set(isPlainRecord(provider) && Array.isArray(provider.models)
101
+ ? provider.models.flatMap(model => isPlainRecord(model) && typeof model.model === "string" ? [model.model] : [])
102
+ : []);
103
+ const modelConfigs = isPlainRecord(doc) ? doc.modelConfigs : undefined;
104
+ const rows = isPlainRecord(modelConfigs) ? modelConfigs.customModels : undefined;
105
+ if (exported.size === 0 || !Array.isArray(rows)) return false;
106
+ return rows.some(row => isPlainRecord(row) && row.provider === OPENCODE_PROVIDER_ID
107
+ && typeof row.model === "string" && exported.has(row.model) && !owned.has(row));
108
+ }
@@ -1,16 +1,55 @@
1
1
  import { canonicalizeReasoningEfforts, isDeclaredReasoningEffort } from "../../reasoning-effort";
2
2
  import { knownReasoningSupport, type OpencodeCatalogModel } from "./contracts";
3
3
 
4
- /** Unknown and explicitly empty ladders have different client-side meanings. */
5
- export function exportReasoningEfforts(model: OpencodeCatalogModel): string[] | undefined {
6
- return model.reasoningEfforts === undefined ? undefined : canonicalizeReasoningEfforts(model.reasoningEfforts);
4
+ type ReasoningMetadata = Pick<OpencodeCatalogModel, "reasoningEfforts" | "defaultReasoningEffort"
5
+ | "supportsReasoning" | "supportsThinkingToggle" | "supportsReasoningEffort" | "defaultThinkingEnabled">;
6
+
7
+ /** Shared row projection; an effective projection owns the default even when it omits it. */
8
+ export function resolveExportReasoningAxes(effective: ReasoningMetadata | undefined, row: ReasoningMetadata) {
9
+ const supportsThinkingToggle = effective?.supportsThinkingToggle ?? row.supportsThinkingToggle;
10
+ const supportsReasoningEffort = effective?.supportsReasoningEffort ?? row.supportsReasoningEffort;
11
+ const defaultThinkingEnabled = effective?.defaultThinkingEnabled ?? row.defaultThinkingEnabled;
12
+ const declaredEfforts = effective?.reasoningEfforts ?? row.reasoningEfforts;
13
+ const effortDisabled = supportsReasoningEffort === false
14
+ || (effective?.supportsReasoning ?? row.supportsReasoning) === false;
15
+ return {
16
+ supportsThinkingToggle,
17
+ supportsReasoningEffort,
18
+ defaultThinkingEnabled,
19
+ reasoningEfforts: declaredEfforts === undefined ? undefined : effortDisabled ? [] : [...declaredEfforts],
20
+ // Falling back through an existing projection would revive a synthetic picker default.
21
+ // Older rows without a projection retain their own declared default.
22
+ defaultReasoningEffort: effortDisabled ? undefined : effective !== undefined
23
+ ? effective.defaultReasoningEffort : row.defaultReasoningEffort,
24
+ };
7
25
  }
8
26
 
9
- /** Carry an authoritative default, never invent one or revive a cleared ladder. */
10
- export function exportDefaultReasoningEffort(model: OpencodeCatalogModel): string | undefined {
27
+ /** Effort-enum client compatibility only; never write these choices back into model facts. */
28
+ export function exportReasoningEfforts(model: ReasoningMetadata): string[] | undefined {
29
+ if (model.supportsReasoning === false) return [];
30
+ const efforts = model.reasoningEfforts === undefined ? undefined : canonicalizeReasoningEfforts(model.reasoningEfforts);
31
+ if (model.supportsReasoningEffort === false) {
32
+ return model.supportsThinkingToggle === true ? ["none", "high"] : [];
33
+ }
34
+ if (model.supportsThinkingToggle === true) {
35
+ const strengths = efforts?.filter(effort => effort !== "none") ?? [];
36
+ return strengths.length ? ["none", ...strengths] : ["none", "high"];
37
+ }
38
+ return model.supportsThinkingToggle === false ? efforts?.filter(effort => effort !== "none") : efforts;
39
+ }
40
+
41
+ /** Encode the declared effort/default-thinking choice without inventing a strength. */
42
+ export function exportDefaultReasoningEffort(model: ReasoningMetadata): string | undefined {
43
+ const efforts = exportReasoningEfforts(model);
44
+ if (model.supportsThinkingToggle === true && model.supportsReasoning !== false) {
45
+ if (model.defaultThinkingEnabled === false) return "none";
46
+ const toggleOnly = model.supportsReasoningEffort === false
47
+ || !model.reasoningEfforts?.some(effort => isDeclaredReasoningEffort(effort) && effort !== "none");
48
+ if (toggleOnly) return model.defaultThinkingEnabled === true ? "high" : undefined;
49
+ if (model.defaultThinkingEnabled === true && model.defaultReasoningEffort === "none") return undefined;
50
+ }
11
51
  const effort = model.defaultReasoningEffort;
12
52
  if (typeof effort !== "string" || !isDeclaredReasoningEffort(effort)) return undefined;
13
- const efforts = exportReasoningEfforts(model);
14
53
  return efforts === undefined || efforts.includes(effort) ? effort : undefined;
15
54
  }
16
55
 
@@ -34,9 +73,17 @@ export function legacyReasoningMetadata(model: OpencodeCatalogModel): {
34
73
  const suppressed: Record<string, LegacyEffortVariant> = Object.fromEntries(
35
74
  ["none", "minimal", "low", "medium", "high", "xhigh", "max"].map(id => [id, { disabled: true }]),
36
75
  );
37
- const variants = efforts?.length
76
+ let variants = efforts?.length
38
77
  ? Object.fromEntries(efforts.map(effort => [effort, { reasoningEffort: effort }]))
39
- : reasoning === true ? suppressed : undefined;
78
+ : reasoning === true || model.supportsReasoning === false || model.supportsReasoningEffort === false ? suppressed : undefined;
79
+ // Constrained controls replace generated choices; a negative toggle by itself does not
80
+ // declare the still-unknown effort axis unsupported.
81
+ if (model.supportsThinkingToggle === true || model.supportsReasoningEffort !== undefined
82
+ || model.supportsReasoning === false || (model.supportsThinkingToggle === false && efforts !== undefined)) {
83
+ variants = { ...suppressed, ultra: { disabled: true }, ...variants };
84
+ } else if (model.supportsThinkingToggle === false) {
85
+ variants = { none: { disabled: true }, ...variants };
86
+ }
40
87
  return {
41
88
  ...(typeof reasoning === "boolean" ? { reasoning } : {}),
42
89
  ...(defaultEffort !== undefined ? { options: { reasoningEffort: defaultEffort } } : {}),
@@ -85,6 +85,7 @@ import {
85
85
 
86
86
  export type { CommandCodeGeneratedConfig, CommandCodeModelEntry, CommandCodeProviderBlock };
87
87
  export { buildCommandCodeClientConfig, summarizeCommandCode, buildCommandCodeContribution, commandCodeProviderRoot };
88
+ import { agentConfigPath, buildQoderCnClientConfig, buildQoderCnContribution, buildWorkbuddyClientConfig, buildWorkbuddyContribution, summarizeWorkbuddy, workbuddyApplyRefusal } from "./config-export/agent-clients";
88
89
  import { buildQoderClientConfig, summarizeQoder, buildQoderContribution, qoderConfigPath } from "./config-export/qoder";
89
90
  export { buildQoderClientConfig, qoderConfigPath, qoderHomeDir, type QoderGeneratedConfig } from "./config-export/qoder";
90
91
 
@@ -1401,6 +1402,17 @@ export const EXPORT_CLIENTS: Record<ExportClientId, ExportClientSpec> = {
1401
1402
  buildContribution: buildQoderContribution,
1402
1403
  loopbackOnly: true,
1403
1404
  },
1405
+ "qoder-cn": {
1406
+ id: "qoder-cn", filename: "qoder-cn-settings.json", destination: env => agentConfigPath("qoder-cn", env),
1407
+ apiKeyEnv: "", exportHint: "Qoder CN uses a non-secret loopback placeholder.", format: "json",
1408
+ build: buildQoderCnClientConfig, summarize: summarizeQoder, buildContribution: buildQoderCnContribution, loopbackOnly: true,
1409
+ },
1410
+ ...Object.fromEntries((["workbuddy", "workbuddy-ai"] as const).map(id => [id, {
1411
+ id, filename: `${id}-models.json`, destination: (env: NodeJS.ProcessEnv) => agentConfigPath(id, env),
1412
+ apiKeyEnv: "", exportHint: "WorkBuddy uses a non-secret loopback placeholder.", format: "json" as const,
1413
+ build: buildWorkbuddyClientConfig, summarize: summarizeWorkbuddy, validateApply: workbuddyApplyRefusal,
1414
+ buildContribution: (ctx: ExportContext) => buildWorkbuddyContribution(id, ctx), loopbackOnly: true,
1415
+ }])) as Record<"workbuddy" | "workbuddy-ai", ExportClientSpec>,
1404
1416
  opencode: {
1405
1417
  id: "opencode",
1406
1418
  filename: "opencode.json",
@@ -7,13 +7,18 @@
7
7
  * own config under OpenCode. Neither proves LazyCodex is installed, and `~/.omo` exists for all
8
8
  * of them, so this reads only LazyCodex's footprint inside CODEX_HOME: the Codex plugin
9
9
  * `omo@sisyphuslabs` enabled in config.toml (the key LazyCodex's own doctor checks) and an
10
- * installed copy of it carrying the `lazycodex-install.json` receipt its installer writes.
10
+ * installed copy of it. A copy counts when it carries the plugin manifest, which every install
11
+ * route writes, or the `lazycodex-install.json` receipt only the npx installer writes: a copy the
12
+ * plugin's auto-update syncs from the marketplace has no receipt, and an update leaves the old
13
+ * version directory behind empty.
11
14
  */
12
15
  import { existsSync, readdirSync, readFileSync } from "node:fs";
13
16
  import { join } from "node:path";
14
17
 
15
18
  export const LAZYCODEX_PLUGIN_ID = "omo@sisyphuslabs";
16
19
 
20
+ const INSTALL_MARKERS = [join(".codex-plugin", "plugin.json"), "lazycodex-install.json"];
21
+
17
22
  export interface LazyCodexDetection {
18
23
  readonly detected: boolean;
19
24
  readonly pluginEnabled: boolean;
@@ -35,7 +40,7 @@ function pluginInstalled(codexHome: string): boolean {
35
40
  const root = join(codexHome, "plugins", "cache", "sisyphuslabs", "omo");
36
41
  try {
37
42
  return readdirSync(root, { withFileTypes: true })
38
- .some(entry => entry.isDirectory() && existsSync(join(root, entry.name, "lazycodex-install.json")));
43
+ .some(entry => entry.isDirectory() && INSTALL_MARKERS.some(marker => existsSync(join(root, entry.name, marker))));
39
44
  } catch {
40
45
  return false;
41
46
  }