mixdog 0.7.18 → 0.8.1

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 (847) hide show
  1. package/README.md +37 -331
  2. package/package.json +67 -99
  3. package/scripts/boot-smoke.mjs +94 -0
  4. package/scripts/build-tui.mjs +52 -0
  5. package/scripts/compact-smoke.mjs +199 -0
  6. package/scripts/lead-workflow-smoke.mjs +598 -0
  7. package/scripts/live-worker-smoke.mjs +239 -0
  8. package/scripts/output-style-smoke.mjs +101 -0
  9. package/scripts/session-context-bench.mjs +172 -0
  10. package/scripts/smoke-loop-report.mjs +221 -0
  11. package/scripts/smoke-loop.mjs +201 -0
  12. package/scripts/smoke.mjs +113 -0
  13. package/scripts/tool-failures.mjs +143 -0
  14. package/scripts/tool-smoke.mjs +452 -0
  15. package/src/agents/debugger/AGENT.md +3 -0
  16. package/src/agents/debugger/agent.json +6 -0
  17. package/src/agents/explore/AGENT.md +4 -0
  18. package/src/agents/explore/agent.json +6 -0
  19. package/src/agents/heavy-worker/AGENT.md +3 -0
  20. package/src/agents/heavy-worker/agent.json +6 -0
  21. package/src/agents/maintainer/AGENT.md +3 -0
  22. package/src/agents/maintainer/agent.json +6 -0
  23. package/src/agents/reviewer/AGENT.md +3 -0
  24. package/src/agents/reviewer/agent.json +6 -0
  25. package/src/agents/scheduler-task.md +3 -0
  26. package/src/agents/web-researcher/AGENT.md +3 -0
  27. package/src/agents/web-researcher/agent.json +6 -0
  28. package/src/agents/webhook-handler.md +3 -0
  29. package/src/agents/worker/AGENT.md +3 -0
  30. package/src/agents/worker/agent.json +6 -0
  31. package/src/app.mjs +90 -0
  32. package/src/cli.mjs +11 -0
  33. package/src/defaults/hidden-roles.json +72 -0
  34. package/src/defaults/mixdog-config.template.json +15 -0
  35. package/src/hooks/lib/permission-evaluator.cjs +488 -0
  36. package/src/hooks/lib/settings-loader.cjs +112 -0
  37. package/src/lib/keychain-cjs.cjs +332 -0
  38. package/src/lib/plugin-paths.cjs +28 -0
  39. package/src/lib/rules-builder.cjs +315 -0
  40. package/src/mixdog-session-runtime.mjs +3813 -0
  41. package/src/output-styles/default.md +38 -0
  42. package/src/output-styles/extreme-simple.md +17 -0
  43. package/src/output-styles/simple.md +17 -0
  44. package/src/repl.mjs +330 -0
  45. package/src/rules/bridge/00-common.md +5 -0
  46. package/src/rules/bridge/20-skip-protocol.md +11 -0
  47. package/src/rules/bridge/30-explorer.md +4 -0
  48. package/src/rules/bridge/40-cycle1-agent.md +28 -0
  49. package/src/rules/bridge/41-cycle2-agent.md +59 -0
  50. package/src/rules/lead/00-tool-lead.md +5 -0
  51. package/src/rules/lead/01-general.md +5 -0
  52. package/src/rules/lead/02-channels.md +3 -0
  53. package/src/rules/lead/04-workflow.md +12 -0
  54. package/src/rules/shared/00-language.md +3 -0
  55. package/src/rules/shared/01-tool.md +3 -0
  56. package/src/runtime/agent/orchestrator/bridge-trace.mjs +814 -0
  57. package/src/runtime/agent/orchestrator/cache-mtime.mjs +60 -0
  58. package/src/runtime/agent/orchestrator/config.mjs +446 -0
  59. package/src/runtime/agent/orchestrator/context/collect.mjs +796 -0
  60. package/src/runtime/agent/orchestrator/dispatch-persist.mjs +417 -0
  61. package/src/runtime/agent/orchestrator/internal-roles.mjs +188 -0
  62. package/src/runtime/agent/orchestrator/internal-tools.mjs +88 -0
  63. package/src/runtime/agent/orchestrator/mcp/client.mjs +345 -0
  64. package/src/runtime/agent/orchestrator/providers/anthropic-oauth.mjs +2104 -0
  65. package/src/runtime/agent/orchestrator/providers/anthropic.mjs +784 -0
  66. package/src/runtime/agent/orchestrator/providers/api-usage.mjs +341 -0
  67. package/src/runtime/agent/orchestrator/providers/gemini.mjs +1679 -0
  68. package/src/runtime/agent/orchestrator/providers/grok-oauth.mjs +959 -0
  69. package/src/runtime/agent/orchestrator/providers/media-normalization.mjs +213 -0
  70. package/src/runtime/agent/orchestrator/providers/model-cache.mjs +38 -0
  71. package/src/runtime/agent/orchestrator/providers/model-catalog.mjs +471 -0
  72. package/src/runtime/agent/orchestrator/providers/oauth-usage.mjs +615 -0
  73. package/src/runtime/agent/orchestrator/providers/openai-compat-stream.mjs +808 -0
  74. package/src/runtime/agent/orchestrator/providers/openai-compat.mjs +1719 -0
  75. package/src/runtime/agent/orchestrator/providers/openai-oauth-ws.mjs +2587 -0
  76. package/src/runtime/agent/orchestrator/providers/openai-oauth.mjs +1953 -0
  77. package/src/runtime/agent/orchestrator/providers/openai-ws.mjs +136 -0
  78. package/src/runtime/agent/orchestrator/providers/opencode-go-usage.mjs +317 -0
  79. package/src/runtime/agent/orchestrator/providers/opencode-go.mjs +109 -0
  80. package/src/runtime/agent/orchestrator/providers/registry.mjs +247 -0
  81. package/src/runtime/agent/orchestrator/providers/retry-classifier.mjs +332 -0
  82. package/src/runtime/agent/orchestrator/providers/statusline-route-meta.mjs +11 -0
  83. package/src/runtime/agent/orchestrator/providers/trace-utils.mjs +50 -0
  84. package/src/runtime/agent/orchestrator/session/cache/post-edit-marks.mjs +42 -0
  85. package/src/runtime/agent/orchestrator/session/cache/prefetch-cache.mjs +142 -0
  86. package/src/runtime/agent/orchestrator/session/cache/read-cache.mjs +318 -0
  87. package/src/runtime/agent/orchestrator/session/cache/scoped-cache.mjs +367 -0
  88. package/src/runtime/agent/orchestrator/session/compact.mjs +882 -0
  89. package/src/runtime/agent/orchestrator/session/context-utils.mjs +233 -0
  90. package/src/runtime/agent/orchestrator/session/loop.mjs +2269 -0
  91. package/src/runtime/agent/orchestrator/session/manager.mjs +2972 -0
  92. package/src/runtime/agent/orchestrator/session/result-classification.mjs +65 -0
  93. package/src/runtime/agent/orchestrator/session/store.mjs +870 -0
  94. package/src/runtime/agent/orchestrator/session/tool-result-offload.mjs +166 -0
  95. package/src/runtime/agent/orchestrator/smart-bridge/bridge-llm.mjs +339 -0
  96. package/src/runtime/agent/orchestrator/smart-bridge/cache-strategy.mjs +419 -0
  97. package/src/runtime/agent/orchestrator/stall-policy.mjs +227 -0
  98. package/src/runtime/agent/orchestrator/tool-loop-guard.mjs +235 -0
  99. package/src/runtime/agent/orchestrator/tools/bash-session.mjs +723 -0
  100. package/src/runtime/agent/orchestrator/tools/builtin/advisory-lock.mjs +171 -0
  101. package/src/runtime/agent/orchestrator/tools/builtin/arg-guard.mjs +389 -0
  102. package/src/runtime/agent/orchestrator/tools/builtin/bash-tool.mjs +637 -0
  103. package/src/runtime/agent/orchestrator/tools/builtin/builtin-tools.mjs +165 -0
  104. package/src/runtime/agent/orchestrator/tools/builtin/fuzzy-match.mjs +104 -0
  105. package/src/runtime/agent/orchestrator/tools/builtin/glob-walk.mjs +194 -0
  106. package/src/runtime/agent/orchestrator/tools/builtin/list-tool.mjs +596 -0
  107. package/src/runtime/agent/orchestrator/tools/builtin/native-edit-runner.mjs +110 -0
  108. package/src/runtime/agent/orchestrator/tools/builtin/path-diagnostics.mjs +153 -0
  109. package/src/runtime/agent/orchestrator/tools/builtin/read-formatting.mjs +118 -0
  110. package/src/runtime/agent/orchestrator/tools/builtin/read-open.mjs +189 -0
  111. package/src/runtime/agent/orchestrator/tools/builtin/read-single-tool.mjs +731 -0
  112. package/src/runtime/agent/orchestrator/tools/builtin/read-snapshot-runtime.mjs +168 -0
  113. package/src/runtime/agent/orchestrator/tools/builtin/read-streaming.mjs +602 -0
  114. package/src/runtime/agent/orchestrator/tools/builtin/rg-runner.mjs +465 -0
  115. package/src/runtime/agent/orchestrator/tools/builtin/search-builders.mjs +160 -0
  116. package/src/runtime/agent/orchestrator/tools/builtin/search-tool.mjs +982 -0
  117. package/src/runtime/agent/orchestrator/tools/builtin/shell-jobs.mjs +1087 -0
  118. package/src/runtime/agent/orchestrator/tools/builtin/shell-runtime.mjs +231 -0
  119. package/src/runtime/agent/orchestrator/tools/builtin/snapshot-store.mjs +223 -0
  120. package/src/runtime/agent/orchestrator/tools/builtin.mjs +478 -0
  121. package/src/runtime/agent/orchestrator/tools/code-graph-tool-defs.mjs +24 -0
  122. package/src/runtime/agent/orchestrator/tools/code-graph.mjs +4102 -0
  123. package/src/runtime/agent/orchestrator/tools/destructive-warning.mjs +323 -0
  124. package/src/runtime/agent/orchestrator/tools/graph-binary-fetcher.mjs +154 -0
  125. package/src/runtime/agent/orchestrator/tools/graph-manifest.json +26 -0
  126. package/src/runtime/agent/orchestrator/tools/patch-binary-fetcher.mjs +143 -0
  127. package/src/runtime/agent/orchestrator/tools/patch-tool-defs.mjs +18 -0
  128. package/src/runtime/agent/orchestrator/tools/patch.mjs +2772 -0
  129. package/src/runtime/agent/orchestrator/tools/progress-message.mjs +114 -0
  130. package/src/runtime/agent/orchestrator/tools/shell-command.mjs +880 -0
  131. package/src/runtime/agent/orchestrator/tools/shell-snapshot.mjs +312 -0
  132. package/src/runtime/channels/backends/discord.mjs +781 -0
  133. package/src/runtime/channels/data/voice-runtime-manifest.json +138 -0
  134. package/src/runtime/channels/index.mjs +3309 -0
  135. package/src/runtime/channels/lib/config.mjs +285 -0
  136. package/src/runtime/channels/lib/drop-trace.mjs +71 -0
  137. package/src/runtime/channels/lib/event-pipeline.mjs +81 -0
  138. package/src/runtime/channels/lib/holidays.mjs +138 -0
  139. package/src/runtime/channels/lib/hook-pipe-server.mjs +671 -0
  140. package/src/runtime/channels/lib/output-forwarder.mjs +765 -0
  141. package/src/runtime/channels/lib/runtime-paths.mjs +497 -0
  142. package/src/runtime/channels/lib/scheduler.mjs +710 -0
  143. package/src/runtime/channels/lib/session-discovery.mjs +102 -0
  144. package/src/runtime/channels/lib/state-file.mjs +68 -0
  145. package/src/runtime/channels/lib/status-snapshot.mjs +224 -0
  146. package/src/runtime/channels/lib/tool-format.mjs +122 -0
  147. package/src/runtime/channels/lib/transcript-discovery.mjs +195 -0
  148. package/src/runtime/channels/lib/voice-runtime-fetcher.mjs +734 -0
  149. package/src/runtime/channels/lib/webhook.mjs +1288 -0
  150. package/src/runtime/channels/tool-defs.mjs +177 -0
  151. package/src/runtime/lib/keychain-cjs.cjs +289 -0
  152. package/src/runtime/memory/data/runtime-manifest.json +40 -0
  153. package/src/runtime/memory/index.mjs +3706 -0
  154. package/src/runtime/memory/lib/core-memory-store.mjs +336 -0
  155. package/src/runtime/memory/lib/embedding-provider.mjs +275 -0
  156. package/src/runtime/memory/lib/embedding-worker.mjs +331 -0
  157. package/src/runtime/memory/lib/memory-cycle-requests.mjs +276 -0
  158. package/src/runtime/memory/lib/memory-cycle1.mjs +783 -0
  159. package/src/runtime/memory/lib/memory-cycle2.mjs +1389 -0
  160. package/src/runtime/memory/lib/memory-cycle3.mjs +646 -0
  161. package/src/runtime/memory/lib/memory-embed.mjs +300 -0
  162. package/src/runtime/memory/lib/memory-ops-policy.mjs +149 -0
  163. package/src/runtime/memory/lib/memory-recall-store.mjs +644 -0
  164. package/src/runtime/memory/lib/memory.mjs +418 -0
  165. package/src/runtime/memory/lib/pg/adapter.mjs +328 -0
  166. package/src/runtime/memory/lib/pg/process.mjs +366 -0
  167. package/src/runtime/memory/lib/pg/supervisor.mjs +495 -0
  168. package/src/runtime/memory/lib/runtime-fetcher.mjs +464 -0
  169. package/src/runtime/memory/lib/trace-store.mjs +734 -0
  170. package/src/runtime/memory/tool-defs.mjs +79 -0
  171. package/src/runtime/search/index.mjs +925 -0
  172. package/src/runtime/search/lib/config.mjs +61 -0
  173. package/src/runtime/search/lib/web-tools.mjs +1278 -0
  174. package/src/runtime/search/tool-defs.mjs +64 -0
  175. package/src/runtime/shared/atomic-file.mjs +435 -0
  176. package/src/runtime/shared/background-tasks.mjs +376 -0
  177. package/src/runtime/shared/child-guardian.mjs +98 -0
  178. package/src/runtime/shared/config.mjs +393 -0
  179. package/src/runtime/shared/err-text.mjs +121 -0
  180. package/src/runtime/shared/launcher-control.mjs +259 -0
  181. package/src/runtime/shared/llm/http-agent.mjs +129 -0
  182. package/src/runtime/shared/open-url.mjs +37 -0
  183. package/src/runtime/shared/plugin-paths.mjs +25 -0
  184. package/src/runtime/shared/process-shutdown.mjs +147 -0
  185. package/src/runtime/shared/schedules-store.mjs +70 -0
  186. package/src/runtime/shared/tool-execution-contract.mjs +104 -0
  187. package/src/runtime/shared/tool-surface.mjs +947 -0
  188. package/src/runtime/shared/user-cwd.mjs +221 -0
  189. package/src/runtime/shared/user-data-guard.mjs +232 -0
  190. package/src/runtime/shared/workspace-router.mjs +259 -0
  191. package/src/standalone/bridge-tool.mjs +1414 -0
  192. package/src/standalone/channel-admin.mjs +366 -0
  193. package/src/standalone/channel-worker-preload.cjs +3 -0
  194. package/src/standalone/channel-worker.mjs +353 -0
  195. package/src/standalone/explore-tool.mjs +233 -0
  196. package/src/standalone/hook-bus.mjs +246 -0
  197. package/src/standalone/plugin-admin.mjs +247 -0
  198. package/src/standalone/provider-admin.mjs +338 -0
  199. package/src/standalone/seeds.mjs +94 -0
  200. package/src/standalone/usage-dashboard.mjs +510 -0
  201. package/src/tui/App.jsx +5446 -0
  202. package/src/tui/components/AnsiText.jsx +199 -0
  203. package/src/tui/components/ContextPanel.jsx +265 -0
  204. package/src/tui/components/Markdown.jsx +205 -0
  205. package/src/tui/components/MarkdownTable.jsx +204 -0
  206. package/src/tui/components/Message.jsx +103 -0
  207. package/src/tui/components/Picker.jsx +317 -0
  208. package/src/tui/components/PromptInput.jsx +584 -0
  209. package/src/tui/components/QueuedCommands.jsx +47 -0
  210. package/src/tui/components/SlashCommandPalette.jsx +114 -0
  211. package/src/tui/components/Spinner.jsx +317 -0
  212. package/src/tui/components/StatusLine.jsx +87 -0
  213. package/src/tui/components/TextEntryPanel.jsx +323 -0
  214. package/src/tui/components/ToolExecution.jsx +791 -0
  215. package/src/tui/components/TurnDone.jsx +78 -0
  216. package/src/tui/components/UsagePanel.jsx +331 -0
  217. package/src/tui/dist/index.mjs +12420 -0
  218. package/src/tui/engine.mjs +2410 -0
  219. package/src/tui/figures.mjs +50 -0
  220. package/src/tui/hooks/useEngine.mjs +16 -0
  221. package/src/tui/index.jsx +254 -0
  222. package/src/tui/input-editing.mjs +242 -0
  223. package/src/tui/markdown/format-token.mjs +194 -0
  224. package/src/tui/paste-attachments.mjs +198 -0
  225. package/src/tui/runtime/shared/process-shutdown.mjs +1 -0
  226. package/src/tui/spinner-verbs.mjs +45 -0
  227. package/src/tui/theme.mjs +67 -0
  228. package/src/tui/time-format.mjs +53 -0
  229. package/src/ui/ansi.mjs +115 -0
  230. package/src/ui/markdown.mjs +195 -0
  231. package/src/ui/statusline.mjs +730 -0
  232. package/src/ui/tool-card.mjs +99 -0
  233. package/src/vendor/statusline/bin/statusline-lib.mjs +805 -0
  234. package/src/vendor/statusline/bin/statusline-route.mjs +596 -0
  235. package/src/vendor/statusline/scripts/lib/gateway-settings.mjs +285 -0
  236. package/src/vendor/statusline/src/gateway/claude-current.mjs +320 -0
  237. package/src/vendor/statusline/src/gateway/route-meta.mjs +753 -0
  238. package/src/vendor/statusline/src/gateway/session-routes.mjs +244 -0
  239. package/src/workflows/default/WORKFLOW.md +7 -0
  240. package/src/workflows/default/workflow.json +14 -0
  241. package/vendor/ink/build/ansi-tokenizer.d.ts +38 -0
  242. package/vendor/ink/build/ansi-tokenizer.js +316 -0
  243. package/vendor/ink/build/ansi-tokenizer.js.map +1 -0
  244. package/vendor/ink/build/colorize.d.ts +3 -0
  245. package/vendor/ink/build/colorize.js +48 -0
  246. package/vendor/ink/build/colorize.js.map +1 -0
  247. package/vendor/ink/build/components/AccessibilityContext.d.ts +3 -0
  248. package/vendor/ink/build/components/AccessibilityContext.js +5 -0
  249. package/vendor/ink/build/components/AccessibilityContext.js.map +1 -0
  250. package/vendor/ink/build/components/AnimationContext.d.ts +9 -0
  251. package/vendor/ink/build/components/AnimationContext.js +13 -0
  252. package/vendor/ink/build/components/AnimationContext.js.map +1 -0
  253. package/vendor/ink/build/components/App.d.ts +24 -0
  254. package/vendor/ink/build/components/App.js +554 -0
  255. package/vendor/ink/build/components/App.js.map +1 -0
  256. package/vendor/ink/build/components/AppContext.d.ts +80 -0
  257. package/vendor/ink/build/components/AppContext.js +25 -0
  258. package/vendor/ink/build/components/AppContext.js.map +1 -0
  259. package/vendor/ink/build/components/BackgroundContext.d.ts +4 -0
  260. package/vendor/ink/build/components/BackgroundContext.js +3 -0
  261. package/vendor/ink/build/components/BackgroundContext.js.map +1 -0
  262. package/vendor/ink/build/components/Box.d.ts +130 -0
  263. package/vendor/ink/build/components/Box.js +34 -0
  264. package/vendor/ink/build/components/Box.js.map +1 -0
  265. package/vendor/ink/build/components/CursorContext.d.ts +11 -0
  266. package/vendor/ink/build/components/CursorContext.js +8 -0
  267. package/vendor/ink/build/components/CursorContext.js.map +1 -0
  268. package/vendor/ink/build/components/ErrorBoundary.d.ts +18 -0
  269. package/vendor/ink/build/components/ErrorBoundary.js +23 -0
  270. package/vendor/ink/build/components/ErrorBoundary.js.map +1 -0
  271. package/vendor/ink/build/components/ErrorOverview.d.ts +6 -0
  272. package/vendor/ink/build/components/ErrorOverview.js +90 -0
  273. package/vendor/ink/build/components/ErrorOverview.js.map +1 -0
  274. package/vendor/ink/build/components/FocusContext.d.ts +16 -0
  275. package/vendor/ink/build/components/FocusContext.js +17 -0
  276. package/vendor/ink/build/components/FocusContext.js.map +1 -0
  277. package/vendor/ink/build/components/Newline.d.ts +13 -0
  278. package/vendor/ink/build/components/Newline.js +8 -0
  279. package/vendor/ink/build/components/Newline.js.map +1 -0
  280. package/vendor/ink/build/components/Spacer.d.ts +7 -0
  281. package/vendor/ink/build/components/Spacer.js +11 -0
  282. package/vendor/ink/build/components/Spacer.js.map +1 -0
  283. package/vendor/ink/build/components/Static.d.ts +24 -0
  284. package/vendor/ink/build/components/Static.js +28 -0
  285. package/vendor/ink/build/components/Static.js.map +1 -0
  286. package/vendor/ink/build/components/StderrContext.d.ts +15 -0
  287. package/vendor/ink/build/components/StderrContext.js +13 -0
  288. package/vendor/ink/build/components/StderrContext.js.map +1 -0
  289. package/vendor/ink/build/components/StdinContext.d.ts +28 -0
  290. package/vendor/ink/build/components/StdinContext.js +20 -0
  291. package/vendor/ink/build/components/StdinContext.js.map +1 -0
  292. package/vendor/ink/build/components/StdoutContext.d.ts +15 -0
  293. package/vendor/ink/build/components/StdoutContext.js +13 -0
  294. package/vendor/ink/build/components/StdoutContext.js.map +1 -0
  295. package/vendor/ink/build/components/Text.d.ts +55 -0
  296. package/vendor/ink/build/components/Text.js +50 -0
  297. package/vendor/ink/build/components/Text.js.map +1 -0
  298. package/vendor/ink/build/components/Transform.d.ts +16 -0
  299. package/vendor/ink/build/components/Transform.js +15 -0
  300. package/vendor/ink/build/components/Transform.js.map +1 -0
  301. package/vendor/ink/build/cursor-helpers.d.ts +39 -0
  302. package/vendor/ink/build/cursor-helpers.js +62 -0
  303. package/vendor/ink/build/cursor-helpers.js.map +1 -0
  304. package/vendor/ink/build/devtools-window-polyfill.d.ts +1 -0
  305. package/vendor/ink/build/devtools-window-polyfill.js +68 -0
  306. package/vendor/ink/build/devtools-window-polyfill.js.map +1 -0
  307. package/vendor/ink/build/devtools.d.ts +1 -0
  308. package/vendor/ink/build/devtools.js +36 -0
  309. package/vendor/ink/build/devtools.js.map +1 -0
  310. package/vendor/ink/build/dom.d.ts +62 -0
  311. package/vendor/ink/build/dom.js +143 -0
  312. package/vendor/ink/build/dom.js.map +1 -0
  313. package/vendor/ink/build/get-max-width.d.ts +3 -0
  314. package/vendor/ink/build/get-max-width.js +10 -0
  315. package/vendor/ink/build/get-max-width.js.map +1 -0
  316. package/vendor/ink/build/hooks/use-animation.d.ts +49 -0
  317. package/vendor/ink/build/hooks/use-animation.js +87 -0
  318. package/vendor/ink/build/hooks/use-animation.js.map +1 -0
  319. package/vendor/ink/build/hooks/use-app.d.ts +5 -0
  320. package/vendor/ink/build/hooks/use-app.js +8 -0
  321. package/vendor/ink/build/hooks/use-app.js.map +1 -0
  322. package/vendor/ink/build/hooks/use-box-metrics.d.ts +59 -0
  323. package/vendor/ink/build/hooks/use-box-metrics.js +81 -0
  324. package/vendor/ink/build/hooks/use-box-metrics.js.map +1 -0
  325. package/vendor/ink/build/hooks/use-cursor.d.ts +12 -0
  326. package/vendor/ink/build/hooks/use-cursor.js +29 -0
  327. package/vendor/ink/build/hooks/use-cursor.js.map +1 -0
  328. package/vendor/ink/build/hooks/use-focus-manager.d.ts +43 -0
  329. package/vendor/ink/build/hooks/use-focus-manager.js +18 -0
  330. package/vendor/ink/build/hooks/use-focus-manager.js.map +1 -0
  331. package/vendor/ink/build/hooks/use-focus.d.ts +30 -0
  332. package/vendor/ink/build/hooks/use-focus.js +43 -0
  333. package/vendor/ink/build/hooks/use-focus.js.map +1 -0
  334. package/vendor/ink/build/hooks/use-input.d.ts +132 -0
  335. package/vendor/ink/build/hooks/use-input.js +126 -0
  336. package/vendor/ink/build/hooks/use-input.js.map +1 -0
  337. package/vendor/ink/build/hooks/use-is-screen-reader-enabled.d.ts +6 -0
  338. package/vendor/ink/build/hooks/use-is-screen-reader-enabled.js +12 -0
  339. package/vendor/ink/build/hooks/use-is-screen-reader-enabled.js.map +1 -0
  340. package/vendor/ink/build/hooks/use-paste.d.ts +35 -0
  341. package/vendor/ink/build/hooks/use-paste.js +62 -0
  342. package/vendor/ink/build/hooks/use-paste.js.map +1 -0
  343. package/vendor/ink/build/hooks/use-stderr.d.ts +5 -0
  344. package/vendor/ink/build/hooks/use-stderr.js +8 -0
  345. package/vendor/ink/build/hooks/use-stderr.js.map +1 -0
  346. package/vendor/ink/build/hooks/use-stdin.d.ts +7 -0
  347. package/vendor/ink/build/hooks/use-stdin.js +9 -0
  348. package/vendor/ink/build/hooks/use-stdin.js.map +1 -0
  349. package/vendor/ink/build/hooks/use-stdout.d.ts +5 -0
  350. package/vendor/ink/build/hooks/use-stdout.js +8 -0
  351. package/vendor/ink/build/hooks/use-stdout.js.map +1 -0
  352. package/vendor/ink/build/hooks/use-window-size.d.ts +18 -0
  353. package/vendor/ink/build/hooks/use-window-size.js +22 -0
  354. package/vendor/ink/build/hooks/use-window-size.js.map +1 -0
  355. package/vendor/ink/build/index.d.ts +42 -0
  356. package/vendor/ink/build/index.js +24 -0
  357. package/vendor/ink/build/index.js.map +1 -0
  358. package/vendor/ink/build/ink.d.ts +146 -0
  359. package/vendor/ink/build/ink.js +1022 -0
  360. package/vendor/ink/build/ink.js.map +1 -0
  361. package/vendor/ink/build/input-parser.d.ts +10 -0
  362. package/vendor/ink/build/input-parser.js +194 -0
  363. package/vendor/ink/build/input-parser.js.map +1 -0
  364. package/vendor/ink/build/instances.d.ts +3 -0
  365. package/vendor/ink/build/instances.js +8 -0
  366. package/vendor/ink/build/instances.js.map +1 -0
  367. package/vendor/ink/build/kitty-keyboard.d.ts +23 -0
  368. package/vendor/ink/build/kitty-keyboard.js +32 -0
  369. package/vendor/ink/build/kitty-keyboard.js.map +1 -0
  370. package/vendor/ink/build/log-update.d.ts +20 -0
  371. package/vendor/ink/build/log-update.js +261 -0
  372. package/vendor/ink/build/log-update.js.map +1 -0
  373. package/vendor/ink/build/measure-element.d.ts +20 -0
  374. package/vendor/ink/build/measure-element.js +13 -0
  375. package/vendor/ink/build/measure-element.js.map +1 -0
  376. package/vendor/ink/build/measure-text.d.ts +6 -0
  377. package/vendor/ink/build/measure-text.js +21 -0
  378. package/vendor/ink/build/measure-text.js.map +1 -0
  379. package/vendor/ink/build/output.d.ts +35 -0
  380. package/vendor/ink/build/output.js +328 -0
  381. package/vendor/ink/build/output.js.map +1 -0
  382. package/vendor/ink/build/parse-keypress.d.ts +20 -0
  383. package/vendor/ink/build/parse-keypress.js +495 -0
  384. package/vendor/ink/build/parse-keypress.js.map +1 -0
  385. package/vendor/ink/build/reconciler.d.ts +4 -0
  386. package/vendor/ink/build/reconciler.js +306 -0
  387. package/vendor/ink/build/reconciler.js.map +1 -0
  388. package/vendor/ink/build/render-background.d.ts +4 -0
  389. package/vendor/ink/build/render-background.js +25 -0
  390. package/vendor/ink/build/render-background.js.map +1 -0
  391. package/vendor/ink/build/render-border.d.ts +4 -0
  392. package/vendor/ink/build/render-border.js +84 -0
  393. package/vendor/ink/build/render-border.js.map +1 -0
  394. package/vendor/ink/build/render-node-to-output.d.ts +14 -0
  395. package/vendor/ink/build/render-node-to-output.js +162 -0
  396. package/vendor/ink/build/render-node-to-output.js.map +1 -0
  397. package/vendor/ink/build/render-to-string.d.ts +38 -0
  398. package/vendor/ink/build/render-to-string.js +116 -0
  399. package/vendor/ink/build/render-to-string.js.map +1 -0
  400. package/vendor/ink/build/render.d.ts +176 -0
  401. package/vendor/ink/build/render.js +71 -0
  402. package/vendor/ink/build/render.js.map +1 -0
  403. package/vendor/ink/build/renderer.d.ts +8 -0
  404. package/vendor/ink/build/renderer.js +64 -0
  405. package/vendor/ink/build/renderer.js.map +1 -0
  406. package/vendor/ink/build/sanitize-ansi.d.ts +2 -0
  407. package/vendor/ink/build/sanitize-ansi.js +27 -0
  408. package/vendor/ink/build/sanitize-ansi.js.map +1 -0
  409. package/vendor/ink/build/squash-text-nodes.d.ts +3 -0
  410. package/vendor/ink/build/squash-text-nodes.js +36 -0
  411. package/vendor/ink/build/squash-text-nodes.js.map +1 -0
  412. package/vendor/ink/build/styles.d.ts +302 -0
  413. package/vendor/ink/build/styles.js +303 -0
  414. package/vendor/ink/build/styles.js.map +1 -0
  415. package/vendor/ink/build/utils.d.ts +9 -0
  416. package/vendor/ink/build/utils.js +19 -0
  417. package/vendor/ink/build/utils.js.map +1 -0
  418. package/vendor/ink/build/wrap-text.d.ts +3 -0
  419. package/vendor/ink/build/wrap-text.js +38 -0
  420. package/vendor/ink/build/wrap-text.js.map +1 -0
  421. package/vendor/ink/build/write-synchronized.d.ts +4 -0
  422. package/vendor/ink/build/write-synchronized.js +9 -0
  423. package/vendor/ink/build/write-synchronized.js.map +1 -0
  424. package/vendor/ink/license +10 -0
  425. package/vendor/ink/package.json +137 -0
  426. package/.claude-plugin/marketplace.json +0 -34
  427. package/.claude-plugin/plugin.json +0 -20
  428. package/.gitattributes +0 -34
  429. package/.mcp.json +0 -14
  430. package/ARCHITECTURE.md +0 -77
  431. package/CHANGELOG.md +0 -30
  432. package/CONTRIBUTING.md +0 -45
  433. package/DATA-FLOW.md +0 -79
  434. package/LICENSE +0 -21
  435. package/SECURITY.md +0 -138
  436. package/UNINSTALL.md +0 -115
  437. package/agents/maintenance.md +0 -5
  438. package/agents/memory-classification.md +0 -30
  439. package/agents/scheduler-task.md +0 -18
  440. package/agents/webhook-handler.md +0 -27
  441. package/agents/worker.md +0 -24
  442. package/bin/bridge +0 -133
  443. package/bin/statusline-launcher.mjs +0 -82
  444. package/bin/statusline-lib.mjs +0 -581
  445. package/bin/statusline-route.mjs +0 -273
  446. package/bin/statusline.mjs +0 -638
  447. package/bun.lock +0 -927
  448. package/commands/config.md +0 -16
  449. package/commands/doctor.md +0 -13
  450. package/commands/model.md +0 -61
  451. package/commands/setup.md +0 -17
  452. package/defaults/hidden-roles.json +0 -68
  453. package/defaults/memory-chunk-prompt.md +0 -63
  454. package/defaults/mixdog-config.template.json +0 -27
  455. package/defaults/user-workflow.json +0 -8
  456. package/defaults/user-workflow.md +0 -17
  457. package/hooks/hooks.json +0 -73
  458. package/hooks/lib/active-instance.cjs +0 -77
  459. package/hooks/lib/permission-evaluator.cjs +0 -411
  460. package/hooks/lib/permission-route.cjs +0 -63
  461. package/hooks/lib/settings-loader.cjs +0 -117
  462. package/hooks/post-tool-use.cjs +0 -84
  463. package/hooks/pre-mcp-sandbox.cjs +0 -158
  464. package/hooks/pre-tool-subagent.cjs +0 -258
  465. package/hooks/session-start.cjs +0 -1493
  466. package/hooks/shim-launcher.cjs +0 -65
  467. package/hooks/turn-timer.cjs +0 -82
  468. package/lib/claude-md-writer.cjs +0 -386
  469. package/lib/keychain-cjs.cjs +0 -290
  470. package/lib/plugin-paths.cjs +0 -69
  471. package/lib/rules-builder.cjs +0 -241
  472. package/native/README.md +0 -117
  473. package/native/prebuilt/linux-aarch64/mixdog-shim +0 -0
  474. package/native/prebuilt/linux-x86_64/mixdog-shim +0 -0
  475. package/native/prebuilt/macos-aarch64/mixdog-shim +0 -0
  476. package/native/prebuilt/macos-x86_64/mixdog-shim +0 -0
  477. package/native/prebuilt/windows-x86_64/mixdog-shim.exe +0 -0
  478. package/prompts/code-review.txt +0 -16
  479. package/prompts/security-audit.txt +0 -17
  480. package/rules/bridge/00-common.md +0 -39
  481. package/rules/bridge/20-skip-protocol.md +0 -18
  482. package/rules/bridge/30-explorer.md +0 -33
  483. package/rules/bridge/40-cycle1-agent.md +0 -52
  484. package/rules/bridge/41-cycle2-agent.md +0 -62
  485. package/rules/lead/00-tool-lead.md +0 -61
  486. package/rules/lead/01-general.md +0 -26
  487. package/rules/lead/02-channels.md +0 -49
  488. package/rules/lead/03-team.md +0 -27
  489. package/rules/lead/04-workflow.md +0 -20
  490. package/rules/shared/00-language.md +0 -14
  491. package/rules/shared/01-tool.md +0 -138
  492. package/scripts/bootstrap.mjs +0 -130
  493. package/scripts/bridge-unify-smoke.mjs +0 -308
  494. package/scripts/build-runtime-linux.sh +0 -348
  495. package/scripts/build-runtime-macos.sh +0 -217
  496. package/scripts/build-runtime-windows.ps1 +0 -242
  497. package/scripts/builtin-utils-smoke.mjs +0 -398
  498. package/scripts/bump.mjs +0 -80
  499. package/scripts/check-json.mjs +0 -45
  500. package/scripts/check-syntax-changed.mjs +0 -102
  501. package/scripts/check-syntax.mjs +0 -58
  502. package/scripts/code-graph-batch.test.mjs +0 -33
  503. package/scripts/config-preserve-smoke.mjs +0 -180
  504. package/scripts/doctor.mjs +0 -489
  505. package/scripts/edit-normalize-fuzz.mjs +0 -130
  506. package/scripts/edit-normalize-smoke.mjs +0 -401
  507. package/scripts/edit-operation-smoke.mjs +0 -369
  508. package/scripts/edit2-smoke.mjs +0 -63
  509. package/scripts/ensure-deps.mjs +0 -259
  510. package/scripts/fuzzy-e2e.mjs +0 -28
  511. package/scripts/fuzzy-smoke.mjs +0 -26
  512. package/scripts/gateway-model.mjs +0 -596
  513. package/scripts/generate-runtime-manifest.mjs +0 -166
  514. package/scripts/guard-smoke.mjs +0 -66
  515. package/scripts/hidden-role-schema-smoke.mjs +0 -162
  516. package/scripts/hook-routing-smoke.mjs +0 -29
  517. package/scripts/inject-input.ps1 +0 -204
  518. package/scripts/io-complex-smoke.mjs +0 -667
  519. package/scripts/io-explore-bench.mjs +0 -424
  520. package/scripts/io-guardrails-smoke.mjs +0 -205
  521. package/scripts/io-mini-bench-baseline.json +0 -11
  522. package/scripts/io-mini-bench.mjs +0 -216
  523. package/scripts/io-route-harness.mjs +0 -933
  524. package/scripts/io-telemetry-report.mjs +0 -691
  525. package/scripts/lib/gateway-inventory.mjs +0 -178
  526. package/scripts/lib/gateway-settings.mjs +0 -78
  527. package/scripts/mutation-bench.mjs +0 -564
  528. package/scripts/mutation-io-smoke.mjs +0 -1097
  529. package/scripts/native-patch-bridge-smoke.mjs +0 -288
  530. package/scripts/native-patch-smoke.mjs +0 -304
  531. package/scripts/openai-oauth-catalog-smoke.mjs +0 -53
  532. package/scripts/patch-interior-context-smoke.mjs +0 -49
  533. package/scripts/patch-newline-utf8-smoke.mjs +0 -157
  534. package/scripts/perf-hook-smoke.mjs +0 -71
  535. package/scripts/permission-eval-smoke.mjs +0 -443
  536. package/scripts/prep-patch.mjs +0 -53
  537. package/scripts/prep-shim.mjs +0 -96
  538. package/scripts/provider-cache-smoke.mjs +0 -687
  539. package/scripts/report-runtime-health.mjs +0 -132
  540. package/scripts/resolve-bun.mjs +0 -60
  541. package/scripts/run-mcp.mjs +0 -1473
  542. package/scripts/salvage-v4a-shatter.test.mjs +0 -58
  543. package/scripts/scoped-cache-io-smoke.mjs +0 -103
  544. package/scripts/shell-policy-round3-smoke.mjs +0 -46
  545. package/scripts/smoke-runtime-negative.ps1 +0 -100
  546. package/scripts/smoke-runtime-negative.sh +0 -95
  547. package/scripts/stall-policy-smoke.mjs +0 -50
  548. package/scripts/start-memory-worker.mjs +0 -23
  549. package/scripts/statusline-launcher-smoke.mjs +0 -235
  550. package/scripts/stress-atomic-write.mjs +0 -1028
  551. package/scripts/test-fault-inject.mjs +0 -164
  552. package/scripts/test-large-file.mjs +0 -174
  553. package/scripts/tool-edge-smoke.mjs +0 -209
  554. package/scripts/uninstall.mjs +0 -238
  555. package/scripts/webhook-selfheal-smoke.mjs +0 -27
  556. package/scripts/write-overwrite-guard-smoke.mjs +0 -56
  557. package/server-main.mjs +0 -3350
  558. package/server.mjs +0 -468
  559. package/setup/config-merge.mjs +0 -246
  560. package/setup/install.mjs +0 -574
  561. package/setup/launch-core.mjs +0 -617
  562. package/setup/launch.mjs +0 -101
  563. package/setup/locate-claude.mjs +0 -56
  564. package/setup/mixdog-cli.mjs +0 -122
  565. package/setup/setup-server.mjs +0 -3305
  566. package/setup/setup.html +0 -3740
  567. package/setup/tui.mjs +0 -325
  568. package/skills/retro-skill-proposer/SKILL.md +0 -92
  569. package/skills/schedule-add/SKILL.md +0 -77
  570. package/skills/setup/SKILL.md +0 -356
  571. package/skills/webhook-add/SKILL.md +0 -81
  572. package/src/agent/bridge-stall-watchdog.mjs +0 -337
  573. package/src/agent/index.mjs +0 -2229
  574. package/src/agent/orchestrator/ai-wrapped-dispatch.mjs +0 -1010
  575. package/src/agent/orchestrator/bridge-retry.mjs +0 -220
  576. package/src/agent/orchestrator/bridge-trace.mjs +0 -601
  577. package/src/agent/orchestrator/cache-mtime.mjs +0 -58
  578. package/src/agent/orchestrator/config.mjs +0 -405
  579. package/src/agent/orchestrator/context/collect.mjs +0 -651
  580. package/src/agent/orchestrator/dispatch-persist.mjs +0 -549
  581. package/src/agent/orchestrator/drain-registry.mjs +0 -50
  582. package/src/agent/orchestrator/explore-validator.mjs +0 -8
  583. package/src/agent/orchestrator/internal-roles.mjs +0 -118
  584. package/src/agent/orchestrator/internal-tools.mjs +0 -88
  585. package/src/agent/orchestrator/jobs.mjs +0 -116
  586. package/src/agent/orchestrator/mcp/client.mjs +0 -364
  587. package/src/agent/orchestrator/providers/anthropic-oauth.mjs +0 -1884
  588. package/src/agent/orchestrator/providers/anthropic.mjs +0 -598
  589. package/src/agent/orchestrator/providers/gemini.mjs +0 -1530
  590. package/src/agent/orchestrator/providers/grok-oauth.mjs +0 -779
  591. package/src/agent/orchestrator/providers/model-catalog.mjs +0 -374
  592. package/src/agent/orchestrator/providers/openai-compat-stream.mjs +0 -366
  593. package/src/agent/orchestrator/providers/openai-compat.mjs +0 -1511
  594. package/src/agent/orchestrator/providers/openai-oauth-ws.mjs +0 -1891
  595. package/src/agent/orchestrator/providers/openai-oauth.mjs +0 -1456
  596. package/src/agent/orchestrator/providers/openai-ws.mjs +0 -127
  597. package/src/agent/orchestrator/providers/registry.mjs +0 -192
  598. package/src/agent/orchestrator/providers/retry-classifier.mjs +0 -325
  599. package/src/agent/orchestrator/session/cache/post-edit-marks.mjs +0 -42
  600. package/src/agent/orchestrator/session/cache/prefetch-cache.mjs +0 -142
  601. package/src/agent/orchestrator/session/cache/read-cache.mjs +0 -319
  602. package/src/agent/orchestrator/session/cache/scoped-cache.mjs +0 -361
  603. package/src/agent/orchestrator/session/loop.mjs +0 -1619
  604. package/src/agent/orchestrator/session/manager.mjs +0 -1991
  605. package/src/agent/orchestrator/session/result-classification.mjs +0 -65
  606. package/src/agent/orchestrator/session/store.mjs +0 -632
  607. package/src/agent/orchestrator/session/stream-watchdog.mjs +0 -130
  608. package/src/agent/orchestrator/session/tool-result-offload.mjs +0 -166
  609. package/src/agent/orchestrator/session/trim.mjs +0 -491
  610. package/src/agent/orchestrator/smart-bridge/CACHE-SHARD.md +0 -115
  611. package/src/agent/orchestrator/smart-bridge/bridge-llm.mjs +0 -331
  612. package/src/agent/orchestrator/smart-bridge/cache-obs.mjs +0 -150
  613. package/src/agent/orchestrator/smart-bridge/cache-strategy.mjs +0 -228
  614. package/src/agent/orchestrator/smart-bridge/index.mjs +0 -215
  615. package/src/agent/orchestrator/smart-bridge/profiles.mjs +0 -37
  616. package/src/agent/orchestrator/smart-bridge/registry.mjs +0 -348
  617. package/src/agent/orchestrator/stall-policy.mjs +0 -201
  618. package/src/agent/orchestrator/tool-loop-guard.mjs +0 -75
  619. package/src/agent/orchestrator/tools/bash-session.mjs +0 -722
  620. package/src/agent/orchestrator/tools/builtin/advisory-lock.mjs +0 -171
  621. package/src/agent/orchestrator/tools/builtin/arg-guard.mjs +0 -511
  622. package/src/agent/orchestrator/tools/builtin/bash-tool.mjs +0 -480
  623. package/src/agent/orchestrator/tools/builtin/builtin-tools.mjs +0 -256
  624. package/src/agent/orchestrator/tools/builtin/edit-base-guard.mjs +0 -58
  625. package/src/agent/orchestrator/tools/builtin/edit-byte-plan.mjs +0 -240
  626. package/src/agent/orchestrator/tools/builtin/edit-byte-utils.mjs +0 -113
  627. package/src/agent/orchestrator/tools/builtin/edit-commit.mjs +0 -74
  628. package/src/agent/orchestrator/tools/builtin/edit-context-utils.mjs +0 -242
  629. package/src/agent/orchestrator/tools/builtin/edit-diagnostics.mjs +0 -211
  630. package/src/agent/orchestrator/tools/builtin/edit-engine.mjs +0 -1364
  631. package/src/agent/orchestrator/tools/builtin/edit-failure-context.mjs +0 -126
  632. package/src/agent/orchestrator/tools/builtin/edit-hint.mjs +0 -141
  633. package/src/agent/orchestrator/tools/builtin/edit-match-utils.mjs +0 -194
  634. package/src/agent/orchestrator/tools/builtin/edit-partial-write.mjs +0 -60
  635. package/src/agent/orchestrator/tools/builtin/edit-stale-refresh.mjs +0 -168
  636. package/src/agent/orchestrator/tools/builtin/edit-tool.mjs +0 -173
  637. package/src/agent/orchestrator/tools/builtin/edit-utf8-guard.mjs +0 -48
  638. package/src/agent/orchestrator/tools/builtin/fuzzy-match.mjs +0 -99
  639. package/src/agent/orchestrator/tools/builtin/glob-walk.mjs +0 -193
  640. package/src/agent/orchestrator/tools/builtin/list-tool.mjs +0 -597
  641. package/src/agent/orchestrator/tools/builtin/native-edit-runner.mjs +0 -110
  642. package/src/agent/orchestrator/tools/builtin/notebook-edit-tool.mjs +0 -300
  643. package/src/agent/orchestrator/tools/builtin/path-diagnostics.mjs +0 -152
  644. package/src/agent/orchestrator/tools/builtin/read-formatting.mjs +0 -118
  645. package/src/agent/orchestrator/tools/builtin/read-open.mjs +0 -190
  646. package/src/agent/orchestrator/tools/builtin/read-single-tool.mjs +0 -728
  647. package/src/agent/orchestrator/tools/builtin/read-snapshot-runtime.mjs +0 -173
  648. package/src/agent/orchestrator/tools/builtin/read-streaming.mjs +0 -602
  649. package/src/agent/orchestrator/tools/builtin/rename-tool.mjs +0 -196
  650. package/src/agent/orchestrator/tools/builtin/rg-runner.mjs +0 -422
  651. package/src/agent/orchestrator/tools/builtin/search-builders.mjs +0 -158
  652. package/src/agent/orchestrator/tools/builtin/search-tool.mjs +0 -869
  653. package/src/agent/orchestrator/tools/builtin/shell-jobs.mjs +0 -962
  654. package/src/agent/orchestrator/tools/builtin/shell-runtime.mjs +0 -223
  655. package/src/agent/orchestrator/tools/builtin/snapshot-store.mjs +0 -206
  656. package/src/agent/orchestrator/tools/builtin/write-tool.mjs +0 -401
  657. package/src/agent/orchestrator/tools/builtin.mjs +0 -503
  658. package/src/agent/orchestrator/tools/code-graph-tool-defs.mjs +0 -24
  659. package/src/agent/orchestrator/tools/code-graph.mjs +0 -4095
  660. package/src/agent/orchestrator/tools/cwd-tool.mjs +0 -298
  661. package/src/agent/orchestrator/tools/destructive-warning.mjs +0 -323
  662. package/src/agent/orchestrator/tools/edit-normalize.mjs +0 -603
  663. package/src/agent/orchestrator/tools/graph-binary-fetcher.mjs +0 -154
  664. package/src/agent/orchestrator/tools/graph-manifest.json +0 -26
  665. package/src/agent/orchestrator/tools/host-input.mjs +0 -204
  666. package/src/agent/orchestrator/tools/patch-binary-fetcher.mjs +0 -143
  667. package/src/agent/orchestrator/tools/patch-manifest.json +0 -26
  668. package/src/agent/orchestrator/tools/patch-tool-defs.mjs +0 -20
  669. package/src/agent/orchestrator/tools/patch.mjs +0 -2754
  670. package/src/agent/orchestrator/tools/progress-message.mjs +0 -118
  671. package/src/agent/orchestrator/tools/shell-command.mjs +0 -865
  672. package/src/agent/orchestrator/tools/shell-policy-imports.mjs +0 -7
  673. package/src/agent/orchestrator/tools/shell-snapshot.mjs +0 -313
  674. package/src/agent/orchestrator/workflow-store.mjs +0 -93
  675. package/src/agent/tool-defs.mjs +0 -110
  676. package/src/channels/backends/discord.mjs +0 -784
  677. package/src/channels/data/voice-runtime-manifest.json +0 -138
  678. package/src/channels/index.mjs +0 -3268
  679. package/src/channels/lib/config.mjs +0 -292
  680. package/src/channels/lib/drop-trace.mjs +0 -71
  681. package/src/channels/lib/event-pipeline.mjs +0 -81
  682. package/src/channels/lib/holidays.mjs +0 -138
  683. package/src/channels/lib/hook-pipe-server.mjs +0 -822
  684. package/src/channels/lib/output-forwarder.mjs +0 -765
  685. package/src/channels/lib/runtime-paths.mjs +0 -552
  686. package/src/channels/lib/scheduler.mjs +0 -723
  687. package/src/channels/lib/session-discovery.mjs +0 -103
  688. package/src/channels/lib/state-file.mjs +0 -68
  689. package/src/channels/lib/status-snapshot.mjs +0 -219
  690. package/src/channels/lib/tool-format.mjs +0 -140
  691. package/src/channels/lib/transcript-discovery.mjs +0 -195
  692. package/src/channels/lib/voice-runtime-fetcher.mjs +0 -734
  693. package/src/channels/lib/webhook.mjs +0 -1318
  694. package/src/channels/tool-defs.mjs +0 -170
  695. package/src/daemon/host.mjs +0 -118
  696. package/src/daemon/mcp-transport.mjs +0 -47
  697. package/src/daemon/session.mjs +0 -100
  698. package/src/daemon/thin-client.mjs +0 -71
  699. package/src/daemon/transport.mjs +0 -163
  700. package/src/gateway/claude-current.mjs +0 -255
  701. package/src/gateway/oauth-usage.mjs +0 -598
  702. package/src/gateway/route-meta.mjs +0 -629
  703. package/src/gateway/server.mjs +0 -713
  704. package/src/memory/data/runtime-manifest.json +0 -40
  705. package/src/memory/index.mjs +0 -3332
  706. package/src/memory/lib/core-memory-store.mjs +0 -330
  707. package/src/memory/lib/embedding-provider.mjs +0 -269
  708. package/src/memory/lib/embedding-worker.mjs +0 -323
  709. package/src/memory/lib/memory-cycle1.mjs +0 -645
  710. package/src/memory/lib/memory-cycle2.mjs +0 -1284
  711. package/src/memory/lib/memory-cycle3.mjs +0 -540
  712. package/src/memory/lib/memory-embed.mjs +0 -299
  713. package/src/memory/lib/memory-ops-policy.mjs +0 -190
  714. package/src/memory/lib/memory-recall-store.mjs +0 -638
  715. package/src/memory/lib/memory.mjs +0 -412
  716. package/src/memory/lib/pg/adapter.mjs +0 -308
  717. package/src/memory/lib/pg/process.mjs +0 -360
  718. package/src/memory/lib/pg/supervisor.mjs +0 -396
  719. package/src/memory/lib/runtime-fetcher.mjs +0 -458
  720. package/src/memory/lib/trace-store.mjs +0 -728
  721. package/src/memory/tool-defs.mjs +0 -79
  722. package/src/search/index.mjs +0 -1173
  723. package/src/search/lib/backends/anthropic-oauth.mjs +0 -98
  724. package/src/search/lib/backends/exa.mjs +0 -50
  725. package/src/search/lib/backends/firecrawl.mjs +0 -61
  726. package/src/search/lib/backends/gemini-api.mjs +0 -83
  727. package/src/search/lib/backends/grok-oauth.mjs +0 -86
  728. package/src/search/lib/backends/index.mjs +0 -150
  729. package/src/search/lib/backends/openai-api.mjs +0 -144
  730. package/src/search/lib/backends/openai-oauth.mjs +0 -102
  731. package/src/search/lib/backends/openai-web-search.mjs +0 -76
  732. package/src/search/lib/backends/tavily.mjs +0 -55
  733. package/src/search/lib/backends/xai-api.mjs +0 -113
  734. package/src/search/lib/config.mjs +0 -192
  735. package/src/search/lib/provider-usage.mjs +0 -67
  736. package/src/search/lib/providers.mjs +0 -47
  737. package/src/search/lib/search-intent.mjs +0 -109
  738. package/src/search/lib/setup-handler.mjs +0 -261
  739. package/src/search/lib/web-tools.mjs +0 -1219
  740. package/src/search/tool-defs.mjs +0 -83
  741. package/src/setup/defender-exclusion.mjs +0 -183
  742. package/src/shared/atomic-file.mjs +0 -436
  743. package/src/shared/config.mjs +0 -372
  744. package/src/shared/daemon-recycle.mjs +0 -108
  745. package/src/shared/disable-claude-builtins.mjs +0 -91
  746. package/src/shared/err-text.mjs +0 -12
  747. package/src/shared/llm/http-agent.mjs +0 -123
  748. package/src/shared/open-url.mjs +0 -62
  749. package/src/shared/plugin-paths.mjs +0 -58
  750. package/src/shared/schedules-store.mjs +0 -70
  751. package/src/shared/seed.mjs +0 -161
  752. package/src/shared/user-cwd.mjs +0 -225
  753. package/src/shared/user-data-guard.mjs +0 -244
  754. package/src/status/aggregator.mjs +0 -584
  755. package/src/status/server.mjs +0 -413
  756. package/tools.json +0 -1671
  757. /package/{defaults → src/defaults}/cycle3-review-prompt.md +0 -0
  758. /package/{defaults → src/defaults}/memory-promote-prompt.md +0 -0
  759. /package/{hooks → src/hooks}/lib/permission-rules.cjs +0 -0
  760. /package/{lib → src/lib}/config-cjs.cjs +0 -0
  761. /package/{lib → src/lib}/hook-pipe-path.cjs +0 -0
  762. /package/{lib → src/lib}/mixdog-debug.cjs +0 -0
  763. /package/{lib → src/lib}/text-utils.cjs +0 -0
  764. /package/{rules → src/rules}/bridge/42-cycle3-agent.md +0 -0
  765. /package/src/{agent → runtime/agent}/orchestrator/activity-bus.mjs +0 -0
  766. /package/src/{agent → runtime/agent}/orchestrator/providers/anthropic-betas.mjs +0 -0
  767. /package/src/{agent → runtime/agent}/orchestrator/session/abort-lookup.mjs +0 -0
  768. /package/src/{agent → runtime/agent}/orchestrator/session/cache/scoped-cache-outcome.mjs +0 -0
  769. /package/src/{agent → runtime/agent}/orchestrator/session/cache/util.mjs +0 -0
  770. /package/src/{agent → runtime/agent}/orchestrator/session/read-dedup.mjs +0 -0
  771. /package/src/{agent → runtime/agent}/orchestrator/session/save-session-worker.mjs +0 -0
  772. /package/src/{agent → runtime/agent}/orchestrator/smart-bridge/session-builder.mjs +0 -0
  773. /package/src/{agent → runtime/agent}/orchestrator/tools/bash-policy-scan.mjs +0 -0
  774. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/atomic-write.mjs +0 -0
  775. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/binary-file.mjs +0 -0
  776. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/cache-layers.mjs +0 -0
  777. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/cwd-utils.mjs +0 -0
  778. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/device-paths.mjs +0 -0
  779. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/diagnostics-tool.mjs +0 -0
  780. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/diff-utils.mjs +0 -0
  781. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/fs-reachability.mjs +0 -0
  782. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/grep-formatting.mjs +0 -0
  783. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/hash-utils.mjs +0 -0
  784. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/list-formatting.mjs +0 -0
  785. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/open-config-tool.mjs +0 -0
  786. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/path-locks.mjs +0 -0
  787. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/path-utils.mjs +0 -0
  788. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/read-args.mjs +0 -0
  789. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/read-batch.mjs +0 -0
  790. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/read-constants.mjs +0 -0
  791. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/read-image-resize.mjs +0 -0
  792. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/read-image.mjs +0 -0
  793. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/read-lines.mjs +0 -0
  794. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/read-mode-tool.mjs +0 -0
  795. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/read-range-index.mjs +0 -0
  796. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/read-ranges.mjs +0 -0
  797. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/read-special-files.mjs +0 -0
  798. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/read-tool.mjs +0 -0
  799. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/read-windows.mjs +0 -0
  800. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/shell-analysis.mjs +0 -0
  801. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/shell-output.mjs +0 -0
  802. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/snapshot-helpers.mjs +0 -0
  803. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/snapshot-validation.mjs +0 -0
  804. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/text-stats.mjs +0 -0
  805. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/windows-roots.mjs +0 -0
  806. /package/src/{agent → runtime/agent}/orchestrator/tools/code-graph-prewarm-worker.mjs +0 -0
  807. /package/src/{agent → runtime/agent}/orchestrator/tools/env-scrub.mjs +0 -0
  808. /package/src/{agent → runtime/agent}/orchestrator/tools/mutation-content-cache.mjs +0 -0
  809. /package/src/{agent → runtime/agent}/orchestrator/tools/mutation-planner.mjs +0 -0
  810. /package/src/{agent → runtime/agent}/orchestrator/tools/next-call-utils.mjs +0 -0
  811. /package/src/{agent → runtime/agent}/orchestrator/tools/result-compression.mjs +0 -0
  812. /package/src/{agent → runtime/agent}/orchestrator/tools/shell-exec-policy.mjs +0 -0
  813. /package/src/{agent → runtime/agent}/orchestrator/tools/shell-policy-danger-target.mjs +0 -0
  814. /package/src/{agent → runtime/agent}/orchestrator/tools/shell-policy.mjs +0 -0
  815. /package/src/{channels → runtime/channels}/lib/cli-worker-host.mjs +0 -0
  816. /package/src/{channels → runtime/channels}/lib/config-lock.mjs +0 -0
  817. /package/src/{channels → runtime/channels}/lib/event-queue.mjs +0 -0
  818. /package/src/{channels → runtime/channels}/lib/executor.mjs +0 -0
  819. /package/src/{channels → runtime/channels}/lib/format.mjs +0 -0
  820. /package/src/{channels → runtime/channels}/lib/interaction-workflows.mjs +0 -0
  821. /package/src/{channels → runtime/channels}/lib/memory-client.mjs +0 -0
  822. /package/src/{channels → runtime/channels}/lib/session-control.mjs +0 -0
  823. /package/src/{channels → runtime/channels}/lib/settings.mjs +0 -0
  824. /package/src/{channels → runtime/channels}/lib/whisper-server.mjs +0 -0
  825. /package/src/{memory → runtime/memory}/lib/agent-ipc.mjs +0 -0
  826. /package/src/{memory → runtime/memory}/lib/bridge-trace-queries.mjs +0 -0
  827. /package/src/{memory → runtime/memory}/lib/llm-worker-host.mjs +0 -0
  828. /package/src/{memory → runtime/memory}/lib/memory-cycle.mjs +0 -0
  829. /package/src/{memory → runtime/memory}/lib/memory-extraction.mjs +0 -0
  830. /package/src/{memory → runtime/memory}/lib/memory-maintenance-store.mjs +0 -0
  831. /package/src/{memory → runtime/memory}/lib/memory-recall-id-patch.mjs +0 -0
  832. /package/src/{memory → runtime/memory}/lib/memory-recall-read-query.mjs +0 -0
  833. /package/src/{memory → runtime/memory}/lib/memory-recall-scope-filter.mjs +0 -0
  834. /package/src/{memory → runtime/memory}/lib/memory-retrievers.mjs +0 -0
  835. /package/src/{memory → runtime/memory}/lib/memory-score.mjs +0 -0
  836. /package/src/{memory → runtime/memory}/lib/memory-text-utils.mjs +0 -0
  837. /package/src/{memory → runtime/memory}/lib/model-profile.mjs +0 -0
  838. /package/src/{memory → runtime/memory}/lib/project-id-resolver.mjs +0 -0
  839. /package/src/{search → runtime/search}/lib/cache.mjs +0 -0
  840. /package/src/{search → runtime/search}/lib/formatter.mjs +0 -0
  841. /package/src/{search → runtime/search}/lib/state.mjs +0 -0
  842. /package/src/{shared → runtime/shared}/abort-controller.mjs +0 -0
  843. /package/src/{shared → runtime/shared}/llm/cost.mjs +0 -0
  844. /package/src/{shared → runtime/shared}/llm/index.mjs +0 -0
  845. /package/src/{shared → runtime/shared}/llm/pid-cleanup.mjs +0 -0
  846. /package/src/{shared → runtime/shared}/llm/usage-log.mjs +0 -0
  847. /package/src/{shared → runtime/shared}/wsl.mjs +0 -0
@@ -1,1456 +0,0 @@
1
- /**
2
- * OpenAI ChatGPT OAuth (Codex) provider.
3
- *
4
- * Dispatches over the WebSocket upgrade of chatgpt.com/backend-api/codex/
5
- * responses (responses_websockets=2026-02-06 beta). Authenticates via PKCE
6
- * OAuth or reuses ~/.codex/auth.json. Streaming/framing lives in
7
- * openai-oauth-ws.mjs; this file owns auth, model catalog, request-body
8
- * shape, and HTTP/SSE fallback when WebSocket transport is unhealthy.
9
- */
10
- import { createServer } from 'http';
11
- import { randomBytes, createHash } from 'crypto';
12
- import { readFileSync, existsSync, mkdirSync, statSync } from 'fs';
13
- import { join } from 'path';
14
- import { homedir } from 'os';
15
- import { getPluginData } from '../config.mjs';
16
- import { enrichModels } from './model-catalog.mjs';
17
- import { writeJsonAtomicSync } from '../../../shared/atomic-file.mjs';
18
-
19
- import { sendViaWebSocket } from './openai-oauth-ws.mjs';
20
- import { resolveProviderCacheKey } from '../smart-bridge/cache-strategy.mjs';
21
- import {
22
- appendBridgeTrace,
23
- traceBridgeFetch,
24
- traceBridgeSse,
25
- traceBridgeUsage,
26
- } from '../bridge-trace.mjs';
27
- import {
28
- PROVIDER_GENERATE_TOTAL_TIMEOUT_MS,
29
- PROVIDER_HTTP_RESPONSE_TIMEOUT_MS,
30
- createTimeoutSignal,
31
- } from '../stall-policy.mjs';
32
- import { populateHttpStatusFromMessage } from './retry-classifier.mjs';
33
- import { getLlmDispatcher, preconnect } from '../../../shared/llm/http-agent.mjs';
34
- // --- Constants ---
35
- const CLIENT_ID = 'app_EMoamEEZ73f0CkXaXp7hrann';
36
- const CODEX_OAUTH_ORIGINATOR = 'codex_cli_rs';
37
- const TOKEN_URL = 'https://auth.openai.com/oauth/token';
38
- const CODEX_RESPONSES_URL = 'https://chatgpt.com/backend-api/codex/responses';
39
- // Version string baked into the models endpoint query — Codex rejects the
40
- // request without it. Keep close to the latest published Codex CLI because
41
- // older versions trigger a visibility-filtered catalog (e.g. only rollout
42
- // models). Bump when the real CLI bumps.
43
- // Codex backend gates new model exposures (e.g. gpt-5.5 only on >= 0.130.0)
44
- // on the client_version header. Resolve dynamically from npm so newly-shipped
45
- // models surface within a day instead of waiting on a hardcoded bump here.
46
- // Cached 24h in-process; npm failure falls back to the floor below.
47
- const CODEX_CLIENT_VERSION_FLOOR = '0.130.0';
48
- const CODEX_VERSION_CACHE_TTL_MS = 24 * 60 * 60_000;
49
- let _codexVersionCache = { value: null, fetchedAt: 0 };
50
-
51
- async function _resolveCodexClientVersion() {
52
- const now = Date.now();
53
- if (_codexVersionCache.value && now - _codexVersionCache.fetchedAt < CODEX_VERSION_CACHE_TTL_MS) {
54
- return _codexVersionCache.value;
55
- }
56
- try {
57
- const res = await fetch('https://registry.npmjs.org/@openai/codex/latest', {
58
- signal: AbortSignal.timeout(5_000),
59
- });
60
- if (res.ok) {
61
- const j = await res.json();
62
- const v = String(j?.version || '').trim();
63
- if (/^\d+\.\d+\.\d+/.test(v)) {
64
- _codexVersionCache = { value: v, fetchedAt: now };
65
- return v;
66
- }
67
- }
68
- } catch { /* network down / npm rejects — use floor */ }
69
- _codexVersionCache = { value: CODEX_CLIENT_VERSION_FLOOR, fetchedAt: now };
70
- return CODEX_CLIENT_VERSION_FLOOR;
71
- }
72
- const CODEX_MODEL_CACHE_TTL_MS = 24 * 60 * 60_000;
73
- const CODEX_MODEL_CACHE_SCHEMA_VERSION = 2;
74
- const TOKEN_REFRESH_SKEW_MS = 5 * 60_000;
75
-
76
- function _codexModelCachePath() {
77
- return join(getPluginData(), 'openai-oauth-models.json');
78
- }
79
-
80
- function _loadCodexModelCacheSync() {
81
- const path = _codexModelCachePath();
82
- if (!existsSync(path)) return null;
83
- try {
84
- const raw = JSON.parse(readFileSync(path, 'utf-8'));
85
- if (raw?.version !== CODEX_MODEL_CACHE_SCHEMA_VERSION) return null;
86
- if (!raw?.fetchedAt || !Array.isArray(raw.models)) return null;
87
- if (Date.now() - raw.fetchedAt > CODEX_MODEL_CACHE_TTL_MS) return null;
88
- return raw.models;
89
- } catch { return null; }
90
- }
91
-
92
- async function _loadCodexModelCache() {
93
- return _loadCodexModelCacheSync();
94
- }
95
-
96
- async function _saveCodexModelCache(models) {
97
- try {
98
- writeJsonAtomicSync(_codexModelCachePath(), {
99
- version: CODEX_MODEL_CACHE_SCHEMA_VERSION,
100
- fetchedAt: Date.now(),
101
- models,
102
- }, { lock: true, fsyncDir: true });
103
- _inMemoryCodexCatalog = Array.isArray(models) ? models.slice() : null;
104
- } catch { /* best-effort */ }
105
- }
106
-
107
- // In-memory mirror of the on-disk catalog, same pattern as anthropic-oauth.
108
- // Populated on first listModels() and after every _saveCodexModelCache.
109
- let _inMemoryCodexCatalog = null;
110
- let _codexRefreshInFlight = null;
111
- let _oauthRefreshInFlight = null;
112
- let _lastCodexListModelsError = '';
113
-
114
- export function getOpenAIOAuthModelCatalogError() {
115
- return _lastCodexListModelsError;
116
- }
117
-
118
- function _codexCatalogHas(id) {
119
- if (!id || !Array.isArray(_inMemoryCodexCatalog)) return false;
120
- return _inMemoryCodexCatalog.some(m => m.id === id);
121
- }
122
-
123
- function _findCachedCodexModel(id) {
124
- if (!id) return null;
125
- if (!Array.isArray(_inMemoryCodexCatalog)) {
126
- _inMemoryCodexCatalog = _loadCodexModelCacheSync();
127
- }
128
- if (!Array.isArray(_inMemoryCodexCatalog)) return null;
129
- return _inMemoryCodexCatalog.find(m => m?.id === id) || null;
130
- }
131
-
132
- function _codexServiceTiers(modelInfo) {
133
- return Array.isArray(modelInfo?.serviceTiers) ? modelInfo.serviceTiers : [];
134
- }
135
-
136
- function _codexModelBlocksServiceTier(id, serviceTier) {
137
- if (serviceTier !== 'priority') return false;
138
- const family = _codexFamily(id);
139
- return family === 'gpt-mini' || family === 'gpt-nano' || family === 'gpt-codex';
140
- }
141
-
142
- export function codexModelSupportsServiceTier(id, serviceTier) {
143
- if (_codexModelBlocksServiceTier(id, serviceTier)) return false;
144
- const info = _findCachedCodexModel(id);
145
- if (!info) return true;
146
- const tiers = _codexServiceTiers(info);
147
- if (!tiers.length) return false;
148
- return tiers.some(t => t?.id === serviceTier);
149
- }
150
-
151
- // Codex returns dated ids (gpt-5.4-mini-2026-03-17). Strip the trailing
152
- // -YYYY-MM-DD to get the version alias (gpt-5.4-mini). Unknown shapes pass
153
- // through unchanged.
154
- function _displayCodexModel(id) {
155
- if (!id || typeof id !== 'string') return id;
156
- return id.replace(/-\d{4}-\d{2}-\d{2}$/, '');
157
- }
158
-
159
- function _normalizeCodexModel(m) {
160
- const id = m?.slug || m?.id;
161
- const family = _codexFamily(id);
162
- const serviceTiers = Array.isArray(m?.service_tiers)
163
- ? m.service_tiers
164
- .map(t => ({
165
- id: String(t?.id || '').trim(),
166
- name: String(t?.name || '').trim(),
167
- description: String(t?.description || '').trim(),
168
- }))
169
- .filter(t => t.id)
170
- : [];
171
- const additionalSpeedTiers = Array.isArray(m?.additional_speed_tiers)
172
- ? m.additional_speed_tiers.map(t => String(t || '').trim()).filter(Boolean)
173
- : [];
174
- // Codex doesn't use dated ids — everything is effectively a version alias.
175
- return {
176
- id,
177
- name: m?.display_name || id,
178
- display: m?.display_name || id,
179
- family,
180
- provider: 'openai-oauth',
181
- contextWindow: m?.context_window || m?.max_context_window || 1000000,
182
- maxContextWindow: m?.max_context_window || null,
183
- outputTokens: m?.auto_compact_token_limit || 32768,
184
- autoCompactTokenLimit: m?.auto_compact_token_limit || null,
185
- tier: 'version',
186
- latest: false,
187
- description: m?.description || '',
188
- reasoningLevels: (m?.supported_reasoning_levels || []).map(r => r.effort),
189
- serviceTiers,
190
- defaultServiceTier: m?.default_service_tier || null,
191
- additionalSpeedTiers,
192
- };
193
- }
194
-
195
- function _codexFamily(id) {
196
- const s = String(id || '').toLowerCase();
197
- if (s.includes('nano')) return 'gpt-nano';
198
- if (s.includes('mini')) return 'gpt-mini';
199
- if (s.includes('codex')) return 'gpt-codex';
200
- if (s.startsWith('gpt-5.5')) return 'gpt-5.5';
201
- if (s.startsWith('gpt-5.4')) return 'gpt-5.4';
202
- if (s.startsWith('gpt-5.2')) return 'gpt-5.2';
203
- if (s.startsWith('gpt-5')) return 'gpt-5';
204
- return 'gpt';
205
- }
206
-
207
- // Compare two Codex ids by the X.Y version embedded in `gpt-X.Y`. Mirrors
208
- // anthropic-oauth's _compareVersion, but Codex ids have no trailing date so
209
- // the version lives in the dotted number, not a -YYYY-MM-DD suffix.
210
- function _compareVersion(a, b) {
211
- const na = (String(a).match(/gpt-(\d+)\.(\d+)/) || []).slice(1).map(Number);
212
- const nb = (String(b).match(/gpt-(\d+)\.(\d+)/) || []).slice(1).map(Number);
213
- for (let i = 0; i < Math.max(na.length, nb.length); i++) {
214
- if ((na[i] || 0) !== (nb[i] || 0)) return (na[i] || 0) - (nb[i] || 0);
215
- }
216
- return String(a).localeCompare(String(b));
217
- }
218
-
219
- // Main gpt-5 chat family only: exclude the mini/nano/codex variants so "latest"
220
- // resolves to the flagship, not a smaller sibling.
221
- function _isMainCodexFamily(family) {
222
- return typeof family === 'string' && family.startsWith('gpt-5');
223
- }
224
-
225
- // Mark the highest-version model per family as `latest: true`. VERSION-based
226
- // (Codex ids carry no `created`), mirroring anthropic-oauth's per-family pass.
227
- function _markLatestCodex(models) {
228
- const byFamily = new Map();
229
- for (const m of models) {
230
- if (!m?.id) continue;
231
- const cur = byFamily.get(m.family);
232
- if (!cur || _compareVersion(m.id, cur.id) > 0) {
233
- byFamily.set(m.family, m);
234
- }
235
- }
236
- for (const m of byFamily.values()) m.latest = true;
237
- }
238
-
239
- // Newest MAIN gpt-5 chat model by version, read from the SYNC in-memory
240
- // catalog mirror. Returns null until populated; callers warm via
241
- // ensureLatestCodexModel when null.
242
- export function resolveLatestCodexModel() {
243
- if (!Array.isArray(_inMemoryCodexCatalog)) return null;
244
- let best = null;
245
- for (const m of _inMemoryCodexCatalog) {
246
- if (!m?.id || !_isMainCodexFamily(m.family)) continue;
247
- if (!best || _compareVersion(m.id, best.id) > 0) best = m;
248
- }
249
- return best?.id || null;
250
- }
251
-
252
- export async function ensureLatestCodexModel(provider) {
253
- let m = resolveLatestCodexModel();
254
- if (m) return m;
255
- await provider._refreshModelCache();
256
- m = resolveLatestCodexModel();
257
- if (m) return m;
258
- throw new Error('[openai-oauth] model catalog unavailable after warmup — cannot resolve default model');
259
- }
260
-
261
- function getOwnTokenPath() {
262
- const dir = getPluginData();
263
- if (!existsSync(dir))
264
- mkdirSync(dir, { recursive: true });
265
- return join(dir, 'openai-oauth.json');
266
- }
267
-
268
- // Public predicate used by config.buildDefaultConfig — provider is enabled
269
- // when own tokens exist OR codex bootstrap auth is present. Single truth:
270
- // same loader the runtime uses (loadTokens), no parallel hard-coded path probe.
271
- export function hasOpenAIOAuthCredentials() {
272
- try {
273
- const tokens = loadTokens();
274
- return !!(tokens?.access_token && tokens?.refresh_token);
275
- } catch { return false; }
276
- }
277
- function _normalizeExpiresAt(value) {
278
- const n = Number(value || 0);
279
- if (!Number.isFinite(n) || n <= 0) return 0;
280
- return n < 1e12 ? n * 1000 : n;
281
- }
282
- function _tokensMaxMtime() {
283
- let max = 0;
284
- const paths = [getOwnTokenPath(), join(homedir(), '.codex', 'auth.json')];
285
- for (const p of paths) {
286
- try {
287
- const s = statSync(p);
288
- if (s.mtimeMs > max) max = s.mtimeMs;
289
- } catch { /* not present — skip */ }
290
- }
291
- return max;
292
- }
293
-
294
- function _codexCliAuthPath() {
295
- return join(homedir(), '.codex', 'auth.json');
296
- }
297
- function _loadOwnCodexTokens() {
298
- const ownPath = getOwnTokenPath();
299
- if (!existsSync(ownPath)) return null;
300
- try {
301
- const stat = statSync(ownPath);
302
- const own = JSON.parse(readFileSync(ownPath, 'utf-8'));
303
- if (own.access_token && own.refresh_token) {
304
- return {
305
- ...own,
306
- expires_at: _normalizeExpiresAt(own.expires_at ?? own.expiresAt) || _expiryFromAccessToken(own.access_token),
307
- account_id: own.account_id || extractAccountId(own.access_token),
308
- _mtimeMs: stat.mtimeMs,
309
- };
310
- }
311
- }
312
- catch { /* fall through */ }
313
- return null;
314
- }
315
- function _loadCodexCliTokens() {
316
- const codexPath = _codexCliAuthPath();
317
- if (!existsSync(codexPath)) return null;
318
- try {
319
- const stat = statSync(codexPath);
320
- const data = JSON.parse(readFileSync(codexPath, 'utf-8'));
321
- const tokens = data.tokens || data;
322
- if (tokens.access_token && tokens.refresh_token) {
323
- const expiresAt = _normalizeExpiresAt(data.expires_at ?? tokens.expires_at ?? data.expiresAt ?? tokens.expiresAt) || _expiryFromAccessToken(tokens.access_token);
324
- return {
325
- access_token: tokens.access_token,
326
- refresh_token: tokens.refresh_token,
327
- expires_at: expiresAt,
328
- account_id: tokens.account_id || extractAccountId(tokens.access_token),
329
- _mtimeMs: stat.mtimeMs,
330
- };
331
- }
332
- }
333
- catch { /* fall through */ }
334
- return null;
335
- }
336
- // Own store is authoritative (accurate expires_at from refresh); the Codex CLI
337
- // store seeds the initial bootstrap. But the refresh-token lineage is shared
338
- // single-use with the Codex CLI, so when the CLI store is STRICTLY newer on
339
- // disk (an independent `codex login`/CLI refresh) we must adopt it instead of
340
- // replaying our consumed token. Freshest-wins, own preferred on a tie.
341
- function loadTokens() {
342
- const own = _loadOwnCodexTokens();
343
- const cli = _loadCodexCliTokens();
344
- if (own && cli) return (cli._mtimeMs > own._mtimeMs) ? cli : own;
345
- return own || cli;
346
- }
347
- function saveTokens(tokens) {
348
- const target = getOwnTokenPath();
349
- writeJsonAtomicSync(target, tokens, { lock: true, fsyncDir: true, mode: 0o600, secret: true });
350
- }
351
- // Write rotated tokens back to the Codex CLI store (~/.codex/auth.json) so the
352
- // Codex CLI picks up the rotation instead of replaying a consumed refresh_token
353
- // from the shared single-use lineage. Mirrors anthropic-oauth's write-back.
354
- // Best-effort; the own store stays authoritative. Host-owned file: preserve all
355
- // other fields and don't re-permission it (no secret/mode).
356
- function _writeBackCodexCliTokens(tokens) {
357
- const path = _codexCliAuthPath();
358
- if (!existsSync(path)) return;
359
- try {
360
- const raw = JSON.parse(readFileSync(path, 'utf-8'));
361
- if (!raw || typeof raw !== 'object') return;
362
- const slot = (raw.tokens && typeof raw.tokens === 'object') ? raw.tokens : raw;
363
- slot.access_token = tokens.access_token;
364
- slot.refresh_token = tokens.refresh_token;
365
- raw.last_refresh = new Date().toISOString();
366
- // Preserve the Codex CLI file's existing POSIX mode (writeJsonAtomicSync
367
- // otherwise defaults to 0o600, re-permissioning a host-owned file).
368
- let mode;
369
- try { mode = statSync(path).mode & 0o777; } catch { /* keep helper default */ }
370
- writeJsonAtomicSync(path, raw, { lock: true, fsyncDir: true, mode });
371
- } catch (err) {
372
- process.stderr.write(`[openai-oauth] Codex CLI store write-back failed: ${String(err?.message || err).slice(0, 200)}\n`);
373
- }
374
- }
375
- function extractAccountId(token) {
376
- try {
377
- const parts = token.split('.');
378
- if (parts.length !== 3)
379
- return undefined;
380
- const payload = JSON.parse(Buffer.from(parts[1], 'base64').toString('utf-8'));
381
- return payload?.['https://api.openai.com/auth']?.chatgpt_account_id;
382
- }
383
- catch {
384
- return undefined;
385
- }
386
- }
387
- // Derive token expiry from the access_token's JWT `exp` claim (epoch ms), as a
388
- // fallback when the source store carries no explicit expires_at — e.g. the Codex
389
- // CLI's ~/.codex/auth.json records only last_refresh, so expires_at resolves to 0
390
- // and ensureAuth reads that as "never expires", disabling proactive refresh; the
391
- // token then only refreshes reactively after a request fails (and a WS handshake
392
- // 401 can surface as an opaque transport error that the 401 path misses). Returns
393
- // 0 for opaque (non-JWT) tokens. JWT `exp` is epoch SECONDS (RFC 7519).
394
- function _expiryFromAccessToken(token) {
395
- try {
396
- const parts = String(token || '').split('.');
397
- if (parts.length !== 3) return 0;
398
- const payload = JSON.parse(Buffer.from(parts[1], 'base64').toString('utf-8'));
399
- const exp = Number(payload?.exp);
400
- return Number.isFinite(exp) && exp > 0 ? exp * 1000 : 0;
401
- }
402
- catch { return 0; }
403
- }
404
- // --- Token refresh ---
405
- async function refreshTokens(refreshToken) {
406
- const controller = new AbortController();
407
- const timeout = setTimeout(() => controller.abort(), 30_000);
408
- try {
409
- const res = await fetch(TOKEN_URL, {
410
- method: 'POST',
411
- headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
412
- body: new URLSearchParams({
413
- grant_type: 'refresh_token',
414
- refresh_token: refreshToken,
415
- client_id: CLIENT_ID,
416
- }),
417
- // Never follow a redirect on a secret-bearing request: a token
418
- // endpoint that 307/308-redirects would replay the refresh_token to
419
- // the redirect target. Fail loud instead.
420
- redirect: 'error',
421
- signal: controller.signal,
422
- dispatcher: getLlmDispatcher(),
423
- });
424
- if (!res.ok) {
425
- const text = await res.text().catch(() => '');
426
- // Distinguish a terminally-dead refresh token (consumed by the Codex
427
- // CLI's single-use lineage) from transient failures, so the caller can
428
- // re-read disk and retry once with a newer token instead of
429
- // collapsing every failure to a generic null.
430
- if (res.status === 400 || res.status === 401 || /invalid_grant|revoked|reused/i.test(text)) {
431
- throw Object.assign(new Error(`OpenAI OAuth token refresh ${res.status} (invalid_grant)`), { isInvalidGrant: true });
432
- }
433
- return null;
434
- }
435
- const json = await res.json();
436
- if (!json.access_token) return null;
437
- const expiresAt = _normalizeExpiresAt(json.expires_at ?? json.expiresAt)
438
- || (typeof json.expires_in === 'number' ? Date.now() + json.expires_in * 1000 : 0);
439
- const tokens = {
440
- access_token: json.access_token,
441
- refresh_token: json.refresh_token || refreshToken,
442
- expires_at: expiresAt,
443
- account_id: extractAccountId(json.access_token),
444
- };
445
- // CLI store first, own store last: the own store keeps the newest mtime
446
- // (and its accurate refresh expires_at), so freshest-wins loadTokens
447
- // treats our refresh as authoritative while the CLI still picks up the
448
- // rotated token.
449
- _writeBackCodexCliTokens(tokens);
450
- saveTokens(tokens);
451
- return tokens;
452
- } catch (err) {
453
- if (err?.name === 'AbortError')
454
- throw new Error('OpenAI OAuth token refresh timed out after 30000ms');
455
- throw err;
456
- } finally {
457
- clearTimeout(timeout);
458
- }
459
- }
460
- // --- Build Responses API request ---
461
- /**
462
- * Convert a message slice to Responses API input items.
463
- */
464
- function convertMessagesToResponsesInput(messages) {
465
- const out = [];
466
- for (const m of messages) {
467
- if (!m || m.role === 'system') continue;
468
- if (m.role === 'tool') {
469
- out.push({
470
- type: 'function_call_output',
471
- call_id: m.toolCallId || '',
472
- output: m.content,
473
- });
474
- continue;
475
- }
476
- if (m.role === 'assistant' && Array.isArray(m.toolCalls) && m.toolCalls.length) {
477
- // Reasoning replay deliberately omitted: Codex rejects an
478
- // `rs_*` reasoning item with the same id across the same
479
- // handshake session_id (in-memory conversation state lives
480
- // for the WS_IDLE_MS window even after a socket close).
481
- // Server-side state already preserves the prefix; sending
482
- // reasoning in `input` triggers "Duplicate item".
483
- if (m.content) out.push({ role: 'assistant', content: m.content });
484
- for (const tc of m.toolCalls) {
485
- out.push({
486
- type: 'function_call',
487
- call_id: tc.id,
488
- name: tc.name,
489
- arguments: JSON.stringify(tc.arguments),
490
- });
491
- }
492
- continue;
493
- }
494
- out.push({
495
- role: m.role === 'assistant' ? 'assistant' : 'user',
496
- content: m.content,
497
- });
498
- }
499
- return out;
500
- }
501
- export function buildRequestBody(messages, model, tools, sendOpts) {
502
- // Extract system/instructions
503
- const systemMsgs = messages.filter(m => m.role === 'system');
504
- const instructions = systemMsgs.map(m => m.content).join('\n\n') || 'You are a helpful assistant.';
505
- const opts = sendOpts || {};
506
- const input = convertMessagesToResponsesInput(messages);
507
- // Match the body shape pi-mono and the official Codex CLI ship so the
508
- // server-side auto-cache routes correctly. text.verbosity / include /
509
- // tool_choice / parallel_tool_calls are all inert without side effects
510
- // for most callers but their presence affects how Codex classifies the
511
- // request (and therefore whether the prompt cache is consulted).
512
- const body = {
513
- model,
514
- instructions,
515
- input,
516
- store: process.env.MIXDOG_OAI_STORE === 'true' ? true : false,
517
- stream: true,
518
- reasoning: { effort: opts.effort || 'medium' },
519
- text: { verbosity: 'medium' },
520
- include: ['reasoning.encrypted_content'],
521
- tool_choice: opts.toolChoice || 'auto',
522
- parallel_tool_calls: true,
523
- };
524
- // Resolver guarantees a stable shared key (never sessionId) so a fresh
525
- // session reuses the warm shard — see cache-strategy.resolveProviderCacheKey.
526
- // Clamp to 64 chars (Responses API caps prompt_cache_key; the old sessionId
527
- // fallback at 71 chars would 400 before streaming).
528
- body.prompt_cache_key = String(resolveProviderCacheKey(opts, 'openai-oauth')).slice(0, 64);
529
- // NOTE: prompt_cache_retention is a public OpenAI Responses API parameter —
530
- // the Codex endpoint (chatgpt.com/backend-api/codex/responses) returns
531
- // 400 "Unsupported parameter" when it's included. Re-verified 2026-04-19.
532
- // Leave cache behavior to the Codex server-side default (in-memory, 5-10
533
- // min). Callers who want extended retention should use the public OpenAI
534
- // API provider instead of OAuth.
535
- if (opts.fast === true) {
536
- // 'priority' is the only fast-class value the Codex OAuth backend
537
- // accepts on the wire: 'fast' is hard-rejected ("Unsupported
538
- // service_tier: fast", probed 2026-06-11). Match official Codex:
539
- // only send the request value when the model catalog advertises it.
540
- if (codexModelSupportsServiceTier(model, 'priority')) {
541
- body.service_tier = 'priority';
542
- }
543
- }
544
- // Add tools
545
- if (tools?.length) {
546
- body.tools = tools.map(t => ({
547
- type: 'function',
548
- name: t.name,
549
- description: t.description,
550
- parameters: t.inputSchema,
551
- }));
552
- }
553
- return body;
554
- }
555
-
556
- function _envFlag(name, fallback = true) {
557
- const raw = process.env[name];
558
- if (raw == null || raw === '') return fallback;
559
- return !['0', 'false', 'off', 'no'].includes(String(raw).toLowerCase());
560
- }
561
-
562
- function _parseJsonObject(value) {
563
- try {
564
- const parsed = JSON.parse(value || '{}');
565
- return parsed && typeof parsed === 'object' ? parsed : {};
566
- } catch {
567
- return {};
568
- }
569
- }
570
-
571
- function _extractCachedTokens(usage) {
572
- const details = usage?.input_tokens_details || usage?.prompt_tokens_details || {};
573
- return Number(details.cached_tokens ?? details.cached ?? usage?.cached_tokens ?? 0) || 0;
574
- }
575
-
576
- function _sseEventsFromBuffer(buffer) {
577
- const frames = [];
578
- let rest = buffer.replace(/\r\n/g, '\n');
579
- let idx;
580
- while ((idx = rest.indexOf('\n\n')) >= 0) {
581
- frames.push(rest.slice(0, idx));
582
- rest = rest.slice(idx + 2);
583
- }
584
- return { frames, rest };
585
- }
586
-
587
- function _parseSseFrame(frame) {
588
- const lines = String(frame || '').split('\n');
589
- const data = [];
590
- for (const line of lines) {
591
- if (!line || line.startsWith(':')) continue;
592
- if (line.startsWith('data:')) data.push(line.slice(5).trimStart());
593
- }
594
- if (!data.length) return null;
595
- const raw = data.join('\n').trim();
596
- if (!raw || raw === '[DONE]') return null;
597
- try { return JSON.parse(raw); } catch { return null; }
598
- }
599
-
600
- function _pushOutputTextAnnotations(part, citations, citationKeys) {
601
- const annotations = Array.isArray(part?.annotations) ? part.annotations : [];
602
- for (const raw of annotations) {
603
- const url = raw?.url || raw?.uri || raw?.href || '';
604
- if (!url || citationKeys.has(url)) continue;
605
- citationKeys.add(url);
606
- citations.push({
607
- title: raw?.title || '',
608
- url,
609
- snippet: raw?.snippet || raw?.text || raw?.description || '',
610
- source: 'openai-oauth',
611
- });
612
- }
613
- }
614
-
615
- function _buildOpenAIHttpFallbackHeaders({ auth, cacheKey }) {
616
- const headers = {
617
- Authorization: `Bearer ${auth.access_token}`,
618
- 'Content-Type': 'application/json',
619
- Accept: 'text/event-stream',
620
- 'OpenAI-Beta': 'responses=experimental',
621
- originator: CODEX_OAUTH_ORIGINATOR,
622
- 'chatgpt-account-id': auth.account_id || '',
623
- 'x-client-request-id': randomBytes(16).toString('hex'),
624
- };
625
- if (cacheKey) headers.session_id = String(cacheKey);
626
- return headers;
627
- }
628
-
629
- function _shouldUseOpenAIHttpFallback(err, externalSignal) {
630
- if (!_envFlag('MIXDOG_OPENAI_OAUTH_HTTP_FALLBACK', true)) return false;
631
- if (externalSignal?.aborted) return false;
632
- const status = Number(err?.httpStatus || err?.status || 0);
633
- if (status === 401 || status === 403 || status === 404 || status === 429) return false;
634
- if (status >= 500 && status < 600) return true;
635
- const code = String(err?.code || '');
636
- if (['EWSACQUIRETIMEOUT', 'ETIMEDOUT', 'ESOCKETTIMEDOUT', 'ECONNRESET', 'EAI_AGAIN', 'ENOTFOUND', 'EAI_NODATA', 'ECONNREFUSED', 'ENETUNREACH', 'EHOSTUNREACH', 'EPIPE'].includes(code)) {
637
- return true;
638
- }
639
- const classifier = String(err?.retryClassifier || err?.midstreamClassifier || '');
640
- if (['timeout', 'reset', 'dns', 'refused', 'network', 'acquire_timeout', 'http_5xx', 'first_byte_timeout'].includes(classifier)) {
641
- return true;
642
- }
643
- if (/^http_5\d\d$/.test(classifier)) return true;
644
- if (err?.firstByteTimeout) return true;
645
- const msg = String(err?.message || '');
646
- return /opening handshake has timed out|socket hang up|acquire timed out|no first server event/i.test(msg);
647
- }
648
-
649
- async function sendViaHttpSse({
650
- auth,
651
- body,
652
- opts,
653
- onStreamDelta,
654
- onToolCall,
655
- onStageChange,
656
- externalSignal,
657
- poolKey,
658
- cacheKey,
659
- iteration,
660
- useModel,
661
- fetchFn = fetch,
662
- } = {}) {
663
- const totalTimeout = createTimeoutSignal(
664
- externalSignal,
665
- PROVIDER_GENERATE_TOTAL_TIMEOUT_MS,
666
- 'OpenAI OAuth HTTP fallback total',
667
- );
668
- const headerTimeout = createTimeoutSignal(
669
- totalTimeout.signal,
670
- PROVIDER_HTTP_RESPONSE_TIMEOUT_MS,
671
- 'OpenAI OAuth HTTP fallback initial response',
672
- );
673
- const headers = _buildOpenAIHttpFallbackHeaders({ auth, cacheKey });
674
- const fetchStartedAt = Date.now();
675
- let response;
676
- try {
677
- try { onStageChange?.('requesting'); } catch {}
678
- response = await fetchFn(CODEX_RESPONSES_URL, {
679
- method: 'POST',
680
- headers,
681
- body: JSON.stringify(body),
682
- signal: headerTimeout.signal,
683
- dispatcher: getLlmDispatcher(),
684
- });
685
- } catch (err) {
686
- if (headerTimeout.signal?.aborted && headerTimeout.signal.reason instanceof Error) throw headerTimeout.signal.reason;
687
- throw err;
688
- } finally {
689
- headerTimeout.cleanup();
690
- }
691
-
692
- traceBridgeFetch({
693
- sessionId: poolKey,
694
- headersMs: Date.now() - fetchStartedAt,
695
- httpStatus: response.status,
696
- provider: 'openai-oauth',
697
- model: useModel,
698
- transport: 'http',
699
- });
700
-
701
- if (!response.ok) {
702
- const text = await response.text().catch(() => '');
703
- const err = new Error(`OpenAI OAuth HTTP fallback ${response.status}: ${text.slice(0, 200)}`);
704
- err.httpStatus = response.status;
705
- err.headers = response.headers;
706
- populateHttpStatusFromMessage(err, text);
707
- totalTimeout.cleanup();
708
- throw err;
709
- }
710
- if (!response.body) {
711
- totalTimeout.cleanup();
712
- throw new Error('OpenAI OAuth HTTP fallback returned no response body');
713
- }
714
-
715
- try { onStageChange?.('streaming'); } catch {}
716
- const sseStartedAt = Date.now();
717
- const reader = response.body.getReader();
718
- const decoder = new TextDecoder();
719
- // After headerTimeout.cleanup() the in-flight fetch no longer carries a live
720
- // signal, so a totalTimeout / external abort that fires during a pending
721
- // reader.read() would otherwise leave the pooled request hanging. Keep the
722
- // reader tied to totalTimeout for the whole stream: on abort, cancel the
723
- // reader so the awaited read() unblocks and the socket is released back to
724
- // the shared pool instead of leaking. reader.cancel() may resolve the
725
- // pending read() as {done:true} rather than rejecting, which would let a
726
- // partial response surface as success — so record the abort reason and
727
- // re-throw it after the loop unblocks (see below).
728
- let _streamAbortReason = null;
729
- let _onTotalAbort = null;
730
- if (totalTimeout.signal) {
731
- _onTotalAbort = () => {
732
- const reason = totalTimeout.signal.reason;
733
- _streamAbortReason = reason instanceof Error
734
- ? reason
735
- : new Error('OpenAI OAuth HTTP fallback aborted');
736
- try { reader.cancel(_streamAbortReason).catch(() => {}); } catch {}
737
- };
738
- if (totalTimeout.signal.aborted) _onTotalAbort();
739
- else totalTimeout.signal.addEventListener('abort', _onTotalAbort, { once: true });
740
- }
741
- let buffer = '';
742
- let content = '';
743
- let model = '';
744
- let responseId = '';
745
- let serviceTier = '';
746
- let usage = null;
747
- let ttftMs = null;
748
- const toolCalls = [];
749
- const pendingCalls = new Map();
750
- const reasoningItems = [];
751
- const citations = [];
752
- const citationKeys = new Set();
753
- const webSearchCalls = [];
754
- const webSearchCallKeys = new Set();
755
- let completed = false;
756
-
757
- const pushWebSearchCall = (item) => {
758
- if (!item || item.type !== 'web_search_call') return;
759
- const key = item.id || JSON.stringify(item.action || item);
760
- if (webSearchCallKeys.has(key)) return;
761
- webSearchCallKeys.add(key);
762
- webSearchCalls.push({ id: item.id || '', status: item.status || '', action: item.action || null });
763
- };
764
- const pushReasoningItem = (item) => {
765
- if (item?.type === 'reasoning' && item.encrypted_content && !reasoningItems.some(r => r.id === item.id)) {
766
- reasoningItems.push({
767
- id: item.id || '',
768
- encrypted_content: item.encrypted_content,
769
- summary: Array.isArray(item.summary) ? item.summary : [],
770
- });
771
- }
772
- };
773
- const meaningful = () => {
774
- if (ttftMs == null) ttftMs = Date.now() - sseStartedAt;
775
- try { onStreamDelta?.(); } catch {}
776
- };
777
- const handleEvent = (event) => {
778
- if (!event || typeof event.type !== 'string') return;
779
- switch (event.type) {
780
- case 'response.created':
781
- if (event.response?.model) model = event.response.model;
782
- if (event.response?.id) responseId = event.response.id;
783
- break;
784
- case 'response.output_text.delta':
785
- content += event.delta || '';
786
- meaningful();
787
- break;
788
- case 'response.reasoning_text.delta':
789
- case 'response.reasoning_summary_text.delta':
790
- meaningful();
791
- break;
792
- case 'response.output_item.added':
793
- if (event.item?.type === 'function_call') {
794
- pendingCalls.set(event.item.id || '', {
795
- name: event.item.name || '',
796
- callId: event.item.call_id || '',
797
- });
798
- }
799
- break;
800
- case 'response.function_call_arguments.delta':
801
- meaningful();
802
- break;
803
- case 'response.function_call_arguments.done': {
804
- const itemId = event.item_id || '';
805
- const pending = pendingCalls.get(itemId);
806
- const call = {
807
- id: pending?.callId || event.call_id || '',
808
- name: pending?.name || event.name || '',
809
- arguments: _parseJsonObject(event.arguments),
810
- _pendingItemId: itemId,
811
- };
812
- toolCalls.push(call);
813
- if (call.id && call.name) {
814
- delete call._pendingItemId;
815
- try { onToolCall?.(call); } catch {}
816
- }
817
- meaningful();
818
- break;
819
- }
820
- case 'response.output_item.done': {
821
- const item = event.item || {};
822
- pushReasoningItem(item);
823
- pushWebSearchCall(item);
824
- if (item.type === 'function_call') {
825
- const tc = toolCalls.find(t => t._pendingItemId === (item.id || ''));
826
- if (tc) {
827
- if (!tc.id && item.call_id) tc.id = item.call_id;
828
- if (!tc.name && item.name) tc.name = item.name;
829
- if (tc.id && tc.name) {
830
- delete tc._pendingItemId;
831
- try { onToolCall?.(tc); } catch {}
832
- }
833
- }
834
- }
835
- break;
836
- }
837
- case 'response.completed': {
838
- const resp = event.response || {};
839
- serviceTier = resp.service_tier || resp.serviceTier || serviceTier;
840
- if (!model && resp.model) model = resp.model;
841
- if (!responseId && resp.id) responseId = resp.id;
842
- if (resp.usage) {
843
- usage = {
844
- inputTokens: resp.usage.input_tokens || 0,
845
- outputTokens: resp.usage.output_tokens || 0,
846
- cachedTokens: _extractCachedTokens(resp.usage),
847
- promptTokens: resp.usage.input_tokens || 0,
848
- raw: serviceTier ? { ...resp.usage, service_tier: serviceTier } : resp.usage,
849
- };
850
- }
851
- for (const item of resp.output || []) {
852
- if (item.type === 'message') {
853
- for (const part of item.content || []) {
854
- if (!content && part.type === 'output_text') content += part.text || '';
855
- if (part.type === 'output_text') _pushOutputTextAnnotations(part, citations, citationKeys);
856
- }
857
- } else if (item.type === 'reasoning') {
858
- pushReasoningItem(item);
859
- } else if (item.type === 'web_search_call') {
860
- pushWebSearchCall(item);
861
- } else if (item.type === 'function_call') {
862
- const tc = toolCalls.find(t => t._pendingItemId === (item.id || ''));
863
- if (tc) {
864
- if (!tc.id && item.call_id) tc.id = item.call_id;
865
- if (!tc.name && item.name) tc.name = item.name;
866
- if (tc.id && tc.name) {
867
- delete tc._pendingItemId;
868
- try { onToolCall?.(tc); } catch {}
869
- }
870
- } else if (item.call_id && item.name) {
871
- const call = {
872
- id: item.call_id,
873
- name: item.name,
874
- arguments: _parseJsonObject(item.arguments),
875
- };
876
- toolCalls.push(call);
877
- try { onToolCall?.(call); } catch {}
878
- }
879
- }
880
- }
881
- completed = true;
882
- break;
883
- }
884
- case 'response.done':
885
- if (!event.response || event.response.status === 'completed') completed = true;
886
- else if (event.response.status === 'failed') {
887
- const msg = event.response?.error?.message || 'response.done failed';
888
- const err = new Error(`OpenAI OAuth HTTP fallback response.done failed: ${msg}`);
889
- populateHttpStatusFromMessage(err, msg);
890
- throw err;
891
- } else if (event.response.status === 'incomplete') {
892
- throw new Error(`OpenAI OAuth HTTP fallback response.done incomplete: ${event.response?.incomplete_details?.reason || 'incomplete'}`);
893
- }
894
- break;
895
- case 'response.failed': {
896
- const msg = event.response?.error?.message || event.error?.message || event.message || 'response.failed';
897
- const err = new Error(`OpenAI OAuth HTTP fallback response.failed: ${msg}`);
898
- populateHttpStatusFromMessage(err, msg);
899
- throw err;
900
- }
901
- case 'response.incomplete':
902
- throw new Error(`OpenAI OAuth HTTP fallback response.incomplete: ${event.response?.incomplete_details?.reason || 'incomplete'}`);
903
- case 'error': {
904
- const msg = event.message || event.error?.message || 'unknown';
905
- const err = new Error(`OpenAI OAuth HTTP fallback error: ${msg}`);
906
- populateHttpStatusFromMessage(err, msg);
907
- throw err;
908
- }
909
- default:
910
- break;
911
- }
912
- };
913
-
914
- try {
915
- while (true) {
916
- if (totalTimeout.signal.aborted) {
917
- const reason = totalTimeout.signal.reason;
918
- throw reason instanceof Error ? reason : new Error('OpenAI OAuth HTTP fallback aborted');
919
- }
920
- const { value, done } = await reader.read();
921
- if (done) break;
922
- buffer += decoder.decode(value, { stream: true });
923
- const parsed = _sseEventsFromBuffer(buffer);
924
- buffer = parsed.rest;
925
- for (const frame of parsed.frames) {
926
- const event = _parseSseFrame(frame);
927
- if (event) handleEvent(event);
928
- }
929
- }
930
- // The read() above can unblock via reader.cancel() as {done:true} on an
931
- // external/total-timeout abort. Surface that as the abort/timeout error
932
- // instead of treating the partial stream as a successful response.
933
- if (_streamAbortReason) throw _streamAbortReason;
934
- buffer += decoder.decode();
935
- const parsed = _sseEventsFromBuffer(buffer + '\n\n');
936
- for (const frame of parsed.frames) {
937
- const event = _parseSseFrame(frame);
938
- if (event) handleEvent(event);
939
- }
940
- } finally {
941
- try { reader.releaseLock?.(); } catch {}
942
- if (_onTotalAbort && totalTimeout.signal) {
943
- try { totalTimeout.signal.removeEventListener('abort', _onTotalAbort); } catch {}
944
- }
945
- totalTimeout.cleanup();
946
- }
947
-
948
- const unresolved = toolCalls.find(t => t._pendingItemId);
949
- if (unresolved) {
950
- throw new Error(`OpenAI OAuth HTTP fallback function_call salvage failed: missing call_id/name for item_id=${unresolved._pendingItemId || '?'}`);
951
- }
952
- if (!completed && !content && !toolCalls.length) {
953
- throw new Error('OpenAI OAuth HTTP fallback ended before response.completed');
954
- }
955
-
956
- const liveModel = model || useModel;
957
- traceBridgeSse({
958
- sessionId: poolKey,
959
- sseParseMs: Date.now() - sseStartedAt,
960
- ttftMs,
961
- provider: 'openai-oauth',
962
- model: liveModel,
963
- transport: 'sse',
964
- });
965
- if (usage) {
966
- traceBridgeUsage({
967
- sessionId: poolKey,
968
- iteration,
969
- inputTokens: usage.inputTokens || 0,
970
- outputTokens: usage.outputTokens || 0,
971
- cachedTokens: usage.cachedTokens || 0,
972
- promptTokens: usage.promptTokens || 0,
973
- model: liveModel,
974
- modelDisplay: _displayCodexModel(liveModel),
975
- responseId: responseId || null,
976
- rawUsage: usage.raw || null,
977
- provider: 'openai-oauth',
978
- serviceTier,
979
- });
980
- }
981
- return {
982
- content,
983
- model: liveModel,
984
- reasoningItems: reasoningItems.length ? reasoningItems : undefined,
985
- toolCalls: toolCalls.length ? toolCalls.map(({ _pendingItemId, ...t }) => t) : undefined,
986
- citations: citations.length ? citations : undefined,
987
- webSearchCalls: webSearchCalls.length ? webSearchCalls : undefined,
988
- usage: usage || undefined,
989
- responseId: responseId || undefined,
990
- serviceTier: serviceTier || undefined,
991
- };
992
- }
993
-
994
- // --- Provider ---
995
- export class OpenAIOAuthProvider {
996
- // OpenAI input_tokens already INCLUDES cached_tokens (cached is a subset),
997
- // so input alone is the context footprint. See registry.mjs.
998
- static inputExcludesCache = false;
999
- name = 'openai-oauth';
1000
- tokens = null;
1001
- _refreshFallbackUntil = 0;
1002
- _forceHttpFallback = false;
1003
- config;
1004
- constructor(config) {
1005
- this.config = config || {};
1006
- this.tokens = loadTokens();
1007
- // Warm a kept-alive socket to the Codex responses API so the first
1008
- // request skips the cold TLS handshake. Best-effort; never throws.
1009
- preconnect('https://chatgpt.com');
1010
- }
1011
- getCachedModelInfo(model) {
1012
- return _findCachedCodexModel(model);
1013
- }
1014
- async ensureAuth({ forceRefresh = false, reason = 'preemptive' } = {}) {
1015
- if (!this.tokens) this.tokens = loadTokens();
1016
- if (!this.tokens)
1017
- throw new Error('OpenAI OAuth not authenticated. Run codex login first.');
1018
- // Pick up disk-rotated tokens (codex login, host refresh) the moment
1019
- // the auth file is rewritten — without this, a fresh login is ignored
1020
- // until the in-memory token hits its expiry skew.
1021
- const diskMtime = _tokensMaxMtime();
1022
- // Watermark guards termination: if the newest file on disk isn't loadable
1023
- // (e.g. a logged-out host auth.json beside a valid own store), loadTokens
1024
- // falls back to the older valid store; record the scanned mtime so this
1025
- // check can't re-fire on every ensureAuth().
1026
- if (diskMtime > 0 && diskMtime > (this._lastDiskScan || 0) && diskMtime > (this.tokens._mtimeMs || 0)) {
1027
- const fresh = loadTokens();
1028
- if (fresh?.access_token) {
1029
- this.tokens = fresh;
1030
- this._refreshFallbackUntil = 0;
1031
- process.stderr.write(`[openai-oauth] Reloaded tokens from disk (mtime change)\n`);
1032
- }
1033
- this._lastDiskScan = diskMtime;
1034
- }
1035
- if (!forceRefresh && this._refreshFallbackUntil > Date.now() && this.tokens?.access_token) {
1036
- return this.tokens;
1037
- }
1038
- const expiring = this.tokens.expires_at
1039
- ? this.tokens.expires_at < Date.now() + TOKEN_REFRESH_SKEW_MS
1040
- : false;
1041
- if (forceRefresh || expiring) {
1042
- this._refreshFallbackUntil = 0;
1043
- this.tokens = await this._refreshTokens({ force: forceRefresh, reason });
1044
- }
1045
- return this.tokens;
1046
- }
1047
-
1048
- async _refreshTokens({ force = false, reason = 'preemptive' } = {}) {
1049
- const currentToken = this.tokens?.access_token || null;
1050
- const disk = loadTokens();
1051
- const validAfter = Date.now() + (force ? 0 : TOKEN_REFRESH_SKEW_MS);
1052
- if (disk?.access_token && disk.access_token !== currentToken
1053
- && (!disk.expires_at || disk.expires_at >= validAfter)) {
1054
- this.tokens = disk;
1055
- process.stderr.write(`[openai-oauth] Reloaded tokens from disk\n`);
1056
- return disk;
1057
- }
1058
- if (!this.tokens && disk) this.tokens = disk;
1059
-
1060
- if (_oauthRefreshInFlight) {
1061
- const shared = await _oauthRefreshInFlight;
1062
- this.tokens = shared;
1063
- if (!force || shared?.access_token !== currentToken) return this.tokens;
1064
- }
1065
-
1066
- const startingTokens = this.tokens || disk;
1067
- _oauthRefreshInFlight = (async () => {
1068
- const latest = loadTokens() || startingTokens;
1069
- const latestValidAfter = Date.now() + (force ? 0 : TOKEN_REFRESH_SKEW_MS);
1070
- if (latest?.access_token && latest.access_token !== currentToken
1071
- && (!latest.expires_at || latest.expires_at >= latestValidAfter)) {
1072
- process.stderr.write(`[openai-oauth] Reloaded tokens from disk\n`);
1073
- return latest;
1074
- }
1075
-
1076
- if (!latest?.refresh_token) {
1077
- if (!force && latest?.access_token && (!latest.expires_at || latest.expires_at > Date.now())) {
1078
- process.stderr.write(`[openai-oauth] WARNING: token expiring but no refresh token; using current token until expiry\n`);
1079
- this._refreshFallbackUntil = Date.now() + TOKEN_REFRESH_SKEW_MS;
1080
- return latest;
1081
- }
1082
- throw new Error('OpenAI OAuth refresh token not available. Run codex login to re-authenticate.');
1083
- }
1084
-
1085
- try {
1086
- const _refreshT0 = Date.now();
1087
- const _expiringInMs = (latest?.expires_at ?? 0) - Date.now();
1088
- if (process.env.MIXDOG_DEBUG_BRIDGE) { process.stderr.write(`[bridge-trace] auth-refresh-needed expiringInMs=${_expiringInMs}\n`); }
1089
- process.stderr.write(`[openai-oauth] Token ${reason}, refreshing...\n`);
1090
- let refreshed;
1091
- try {
1092
- refreshed = await refreshTokens(latest.refresh_token);
1093
- } catch (refreshErr) {
1094
- // invalid_grant: the Codex CLI rotated this single-use refresh
1095
- // token between our disk read and this refresh. Re-read both
1096
- // stores and retry ONCE with the freshest different token.
1097
- if (!refreshErr?.isInvalidGrant) throw refreshErr;
1098
- process.stderr.write('[openai-oauth] invalid_grant — re-reading disk, retrying refresh\n');
1099
- const candidates = [_loadOwnCodexTokens(), _loadCodexCliTokens()].filter(Boolean)
1100
- .sort((a, b) => (b._mtimeMs || 0) - (a._mtimeMs || 0));
1101
- const freshTok = candidates.find(c => c.refresh_token && c.refresh_token !== latest.refresh_token);
1102
- if (!freshTok) throw refreshErr;
1103
- refreshed = await refreshTokens(freshTok.refresh_token);
1104
- }
1105
- if (process.env.MIXDOG_DEBUG_BRIDGE) { process.stderr.write(`[bridge-trace] auth-refresh-done elapsed=${Date.now() - _refreshT0}ms ok=${!!refreshed}\n`); }
1106
- if (!refreshed) throw new Error('refresh returned null');
1107
- process.stderr.write(`[openai-oauth] Token refreshed, expires in ${Math.round(((refreshed.expires_at || Date.now()) - Date.now()) / 1000)}s\n`);
1108
- return refreshed;
1109
- }
1110
- catch (err) {
1111
- const msg = err instanceof Error ? err.message : String(err);
1112
- if (!force && latest?.access_token && (!latest.expires_at || latest.expires_at > Date.now())) {
1113
- this._refreshFallbackUntil = Date.now() + TOKEN_REFRESH_SKEW_MS;
1114
- process.stderr.write(`[openai-oauth] Refresh failed (${msg}); using still-valid current token\n`);
1115
- return latest;
1116
- }
1117
- throw new Error(`OpenAI OAuth token refresh failed (${msg}). Run codex login to re-authenticate.`);
1118
- }
1119
- })().finally(() => { _oauthRefreshInFlight = null; });
1120
-
1121
- this.tokens = await _oauthRefreshInFlight;
1122
- return this.tokens;
1123
- }
1124
- async send(messages, model, tools, sendOpts) {
1125
- const opts = sendOpts || {};
1126
- const onStageChange = typeof opts.onStageChange === 'function' ? opts.onStageChange : null;
1127
- const onStreamDelta = typeof opts.onStreamDelta === 'function' ? opts.onStreamDelta : null;
1128
- const onToolCall = typeof opts.onToolCall === 'function' ? opts.onToolCall : null;
1129
- const externalSignal = opts.signal || null;
1130
- const _sendSessionId = opts.sessionId || '(none)';
1131
- const _sendRole = opts.role || '(none)';
1132
- if (process.env.MIXDOG_DEBUG_BRIDGE) { process.stderr.write(`[bridge-trace] auth-start sessionHash=${createHash('sha256').update(String(_sendSessionId)).digest('hex').slice(0, 8)} role=${_sendRole} expiringInMs=${this.tokens?.expires_at ? this.tokens.expires_at - Date.now() : 'unknown'}\n`); }
1133
- // Build request body in parallel with auth resolution. ensureAuth is
1134
- // a no-op fast-path on cached tokens, but a refresh round-trip can
1135
- // take 300ms+; the body build (message serialisation) overlaps cleanly.
1136
- const useModel = model || await ensureLatestCodexModel(this);
1137
- // Escape hatch for callers (e.g. the web-search backend) that ship a
1138
- // fully-formed request body with a server-side tool shape buildRequestBody
1139
- // can't express. Routing through send() still gives them the 401/403
1140
- // force-refresh retry + HTTP/SSE fallback instead of a hard fail.
1141
- const _bodyP = opts._prebuiltBody
1142
- ? Promise.resolve(opts._prebuiltBody)
1143
- : Promise.resolve().then(() => buildRequestBody(messages, useModel, tools, sendOpts));
1144
- const _authP = this.ensureAuth();
1145
- let auth = await _authP;
1146
- const body = await _bodyP;
1147
- // poolKey ≠ cacheKey by design (see openai-oauth-ws.mjs:57-68).
1148
- // poolKey is per-session so parallel reviewer/worker callers each
1149
- // get their own socket bucket — a sibling cannot grab a mid-turn
1150
- // entry and trip Codex's "No tool call found for function call
1151
- // output with call_id …" rejection. cacheKey is provider-scoped
1152
- // (e.g. `mixdog-codex`) and feeds both `body.prompt_cache_key` and
1153
- // the handshake `session_id` header, so all orchestrator-internal
1154
- // dispatches land on the same server-side prompt-cache shard
1155
- // regardless of which logical session opened the socket.
1156
- // poolKey defaults to sessionId (per-session socket isolation); cacheKey
1157
- // resolves to the shared 'mixdog-codex' shard (never sessionId) so a
1158
- // fresh session reuses the warm prefix cache.
1159
- const poolKey = opts.sessionId || null;
1160
- const cacheKey = resolveProviderCacheKey(opts, 'openai-oauth');
1161
- const iteration = Number.isFinite(Number(opts.iteration)) ? Number(opts.iteration) : null;
1162
- const sendWs = typeof opts._sendViaWebSocketFn === 'function' ? opts._sendViaWebSocketFn : sendViaWebSocket;
1163
- const sendHttp = typeof opts._sendViaHttpSseFn === 'function' ? opts._sendViaHttpSseFn : sendViaHttpSse;
1164
- const _t1 = Date.now();
1165
- const recordLiveModel = (result) => {
1166
- if (result?.model && !_codexCatalogHas(result.model)) {
1167
- void this._refreshModelCache();
1168
- }
1169
- return result;
1170
- };
1171
- const dispatchHttp = async (reason, originalErr = null) => {
1172
- appendBridgeTrace({
1173
- sessionId: poolKey,
1174
- iteration,
1175
- kind: 'transport_fallback',
1176
- provider: 'openai-oauth',
1177
- model: useModel,
1178
- transport: 'http',
1179
- payload: {
1180
- from: 'websocket',
1181
- to: 'http',
1182
- reason,
1183
- error_code: originalErr?.code || null,
1184
- error_http_status: Number(originalErr?.httpStatus || 0) || null,
1185
- error_classifier: originalErr?.retryClassifier || originalErr?.midstreamClassifier || null,
1186
- },
1187
- });
1188
- process.stderr.write(`[openai-oauth] WebSocket unhealthy (${reason}); falling back to HTTP/SSE\n`);
1189
- const result = await sendHttp({
1190
- auth,
1191
- body,
1192
- opts,
1193
- onStreamDelta,
1194
- onToolCall,
1195
- onStageChange,
1196
- externalSignal,
1197
- poolKey,
1198
- cacheKey,
1199
- iteration,
1200
- useModel,
1201
- fetchFn: opts._fetchFn,
1202
- });
1203
- this._forceHttpFallback = true;
1204
- if (process.env.MIXDOG_DEBUG_BRIDGE) {
1205
- process.stderr.write(`[bridge-trace] provider-send-end elapsed=${Date.now() - _t1}ms result=ok transport=http-fallback\n`);
1206
- }
1207
- return recordLiveModel(result);
1208
- };
1209
- const dispatchWs = (forceFresh = false) => sendWs({
1210
- auth,
1211
- body,
1212
- sendOpts: opts,
1213
- onStreamDelta,
1214
- onToolCall,
1215
- onStageChange,
1216
- externalSignal,
1217
- poolKey,
1218
- cacheKey,
1219
- iteration,
1220
- useModel,
1221
- displayModel: _displayCodexModel,
1222
- forceFresh,
1223
- });
1224
- if (opts.forceHttpFallback === true
1225
- || this._forceHttpFallback
1226
- || _envFlag('MIXDOG_OPENAI_OAUTH_FORCE_HTTP_FALLBACK', false)) {
1227
- return dispatchHttp('forced');
1228
- }
1229
-
1230
- // Prefer WebSocket for hot cache/delta transport; fall back to HTTP/SSE
1231
- // after retry-exhausted handshake/acquire/no-first-event failures.
1232
- try {
1233
- if (process.env.MIXDOG_DEBUG_BRIDGE) { process.stderr.write(`[bridge-trace] provider-send-start model=${useModel} role=${_sendRole} sessionHash=${createHash('sha256').update(String(_sendSessionId)).digest('hex').slice(0, 8)} iteration=${iteration ?? '(none)'}\n`); }
1234
- const result = await dispatchWs(false);
1235
- if (process.env.MIXDOG_DEBUG_BRIDGE) { process.stderr.write(`[bridge-trace] provider-send-end elapsed=${Date.now() - _t1}ms result=ok\n`); }
1236
- return recordLiveModel(result);
1237
- } catch (err) {
1238
- const status = err?.httpStatus;
1239
- if (status === 401 || status === 403) {
1240
- process.stderr.write(`[openai-oauth-ws] ${status} — forcing refresh and retrying once over WS\n`);
1241
- if (process.env.MIXDOG_DEBUG_BRIDGE) { process.stderr.write(`[bridge-trace] provider-${status}-retry attempt=1\n`); }
1242
- this._refreshFallbackUntil = 0;
1243
- auth = await this.ensureAuth({ forceRefresh: true, reason: String(status) });
1244
- try {
1245
- const result = await dispatchWs(true);
1246
- if (process.env.MIXDOG_DEBUG_BRIDGE) { process.stderr.write(`[bridge-trace] provider-send-end elapsed=${Date.now() - _t1}ms result=ok\n`); }
1247
- return recordLiveModel(result);
1248
- } catch (retryErr) {
1249
- if (_shouldUseOpenAIHttpFallback(retryErr, externalSignal)) {
1250
- try {
1251
- return await dispatchHttp(retryErr?.retryClassifier || retryErr?.code || retryErr?.message || 'ws_auth_retry_failed', retryErr);
1252
- } catch (fallbackErr) {
1253
- try { retryErr.fallbackError = fallbackErr; } catch {}
1254
- throw retryErr;
1255
- }
1256
- }
1257
- throw retryErr;
1258
- }
1259
- }
1260
- const msg = err?.message || '';
1261
- const isUnknownModel = status === 404
1262
- || /unknown[_\s-]?model|model[_\s-]?not[_\s-]?found/i.test(msg);
1263
- if (isUnknownModel && !opts._modelRetry) {
1264
- process.stderr.write(`[openai-oauth-ws] unknown model — refreshing catalog + 1 retry\n`);
1265
- await this._refreshModelCache();
1266
- return this.send(messages, model, tools, { ...opts, _modelRetry: true });
1267
- }
1268
- if (_shouldUseOpenAIHttpFallback(err, externalSignal)) {
1269
- try {
1270
- return await dispatchHttp(err?.retryClassifier || err?.midstreamClassifier || err?.code || err?.message || 'ws_failed', err);
1271
- } catch (fallbackErr) {
1272
- try { err.fallbackError = fallbackErr; } catch {}
1273
- throw err;
1274
- }
1275
- }
1276
- throw err;
1277
- }
1278
- }
1279
- async listModels() {
1280
- // Dynamic lookup via Codex /backend-api/codex/models. Cached 24h.
1281
- // Endpoint returns rich metadata (context_window, reasoning levels,
1282
- // visibility) that is more detailed than /v1/models.
1283
- const cached = await _loadCodexModelCache();
1284
- if (cached) {
1285
- _lastCodexListModelsError = '';
1286
- _inMemoryCodexCatalog = cached.slice();
1287
- return cached;
1288
- }
1289
- try {
1290
- const auth = await this.ensureAuth();
1291
- const clientVersion = await _resolveCodexClientVersion();
1292
- const url = `https://chatgpt.com/backend-api/codex/models?client_version=${clientVersion}`;
1293
- const res = await fetch(url, {
1294
- signal: AbortSignal.timeout(10_000),
1295
- method: 'GET',
1296
- headers: {
1297
- 'Authorization': `Bearer ${auth.access_token}`,
1298
- 'OpenAI-Beta': 'responses=experimental',
1299
- 'originator': 'codex_cli_rs',
1300
- 'chatgpt-account-id': auth.account_id || '',
1301
- },
1302
- dispatcher: getLlmDispatcher(),
1303
- });
1304
- if (!res.ok) throw new Error(`codex list_models ${res.status}`);
1305
- const data = await res.json();
1306
- const items = Array.isArray(data?.models) ? data.models : [];
1307
- const normalized = items.map(m => _normalizeCodexModel(m));
1308
- _markLatestCodex(normalized);
1309
- const enriched = await enrichModels(normalized);
1310
- await _saveCodexModelCache(enriched);
1311
- _lastCodexListModelsError = '';
1312
- return enriched;
1313
- } catch (err) {
1314
- _lastCodexListModelsError = err?.message || String(err);
1315
- process.stderr.write(`[openai-oauth] listModels fetch failed (${_lastCodexListModelsError})\n`);
1316
- // No fallback catalog — empty list signals the UI to show a
1317
- // "catalog unavailable, retry" state. Codex has no equivalent to
1318
- // Anthropic's family tokens so there's no meaningful minimal list.
1319
- return [];
1320
- }
1321
- }
1322
- // Force a catalog refresh (ignores 24h TTL). De-duped via
1323
- // _codexRefreshInFlight so concurrent callers share one HTTP round-trip.
1324
- async _refreshModelCache() {
1325
- if (_codexRefreshInFlight) return _codexRefreshInFlight;
1326
- _codexRefreshInFlight = (async () => {
1327
- try {
1328
- const auth = await this.ensureAuth();
1329
- const clientVersion = await _resolveCodexClientVersion();
1330
- const url = `https://chatgpt.com/backend-api/codex/models?client_version=${clientVersion}`;
1331
- const res = await fetch(url, {
1332
- signal: AbortSignal.timeout(10_000),
1333
- method: 'GET',
1334
- headers: {
1335
- 'Authorization': `Bearer ${auth.access_token}`,
1336
- 'OpenAI-Beta': 'responses=experimental',
1337
- 'originator': 'codex_cli_rs',
1338
- 'chatgpt-account-id': auth.account_id || '',
1339
- },
1340
- dispatcher: getLlmDispatcher(),
1341
- });
1342
- if (!res.ok) throw new Error(`codex list_models ${res.status}`);
1343
- const data = await res.json();
1344
- const items = Array.isArray(data?.models) ? data.models : [];
1345
- const normalized = items.map(m => _normalizeCodexModel(m));
1346
- _markLatestCodex(normalized);
1347
- const enriched = await enrichModels(normalized);
1348
- await _saveCodexModelCache(enriched);
1349
- process.stderr.write(`[openai-oauth] catalog refreshed (${enriched.length} models)\n`);
1350
- return enriched;
1351
- } catch (err) {
1352
- process.stderr.write(`[openai-oauth] catalog refresh failed (${err.message})\n`);
1353
- return null;
1354
- } finally {
1355
- _codexRefreshInFlight = null;
1356
- }
1357
- })();
1358
- return _codexRefreshInFlight;
1359
- }
1360
-
1361
- async isAvailable() {
1362
- return this.tokens !== null;
1363
- }
1364
- }
1365
-
1366
- const AUTHORIZE_URL = 'https://auth.openai.com/oauth/authorize';
1367
- const CODEX_OAUTH_SCOPE = 'openid profile email offline_access api.connectors.read api.connectors.invoke';
1368
- const CALLBACK_HOST = '127.0.0.1';
1369
- const CALLBACK_PORT = 1455;
1370
- const CALLBACK_PATH = '/auth/callback';
1371
- const REDIRECT_URI = `http://localhost:${CALLBACK_PORT}${CALLBACK_PATH}`;
1372
- const LOGIN_TIMEOUT_MS = 5 * 60_000;
1373
- const TOKEN_TIMEOUT_MS = 30_000;
1374
-
1375
- function generatePKCE() {
1376
- const verifier = randomBytes(64).toString('base64url');
1377
- const challenge = createHash('sha256').update(verifier).digest('base64url');
1378
- return { verifier, challenge };
1379
- }
1380
-
1381
- export async function loginOAuth() {
1382
- const pkce = generatePKCE();
1383
- const state = randomBytes(16).toString('hex');
1384
- const url = new URL(AUTHORIZE_URL);
1385
- url.searchParams.set('response_type', 'code');
1386
- url.searchParams.set('client_id', CLIENT_ID);
1387
- url.searchParams.set('redirect_uri', REDIRECT_URI);
1388
- url.searchParams.set('scope', CODEX_OAUTH_SCOPE);
1389
- url.searchParams.set('code_challenge', pkce.challenge);
1390
- url.searchParams.set('code_challenge_method', 'S256');
1391
- url.searchParams.set('id_token_add_organizations', 'true');
1392
- url.searchParams.set('codex_cli_simplified_flow', 'true');
1393
- url.searchParams.set('state', state);
1394
- url.searchParams.set('originator', CODEX_OAUTH_ORIGINATOR);
1395
- process.stderr.write(`\n[openai-oauth] Open this URL to log in to ChatGPT (Codex):\n${url.toString()}\n\n`);
1396
- const { openInBrowser } = await import('../../../shared/open-url.mjs');
1397
- openInBrowser(url.toString());
1398
-
1399
- return new Promise((resolve) => {
1400
- const timeout = setTimeout(() => { server.close(); resolve(null); }, LOGIN_TIMEOUT_MS);
1401
- const server = createServer(async (req, res) => {
1402
- const u = new URL(req.url || '/', `http://${CALLBACK_HOST}:${CALLBACK_PORT}`);
1403
- if (u.pathname !== CALLBACK_PATH) {
1404
- res.writeHead(404);
1405
- res.end();
1406
- return;
1407
- }
1408
- const code = u.searchParams.get('code');
1409
- if (!code || u.searchParams.get('state') !== state) {
1410
- res.writeHead(400);
1411
- res.end('Invalid');
1412
- clearTimeout(timeout);
1413
- server.close();
1414
- resolve(null);
1415
- return;
1416
- }
1417
- res.writeHead(200, { 'Content-Type': 'text/html' });
1418
- res.end('<html><body><h2>Codex login successful! You can close this tab.</h2></body></html>');
1419
- clearTimeout(timeout);
1420
- server.close();
1421
- try {
1422
- const tokenRes = await fetch(TOKEN_URL, {
1423
- method: 'POST',
1424
- headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
1425
- body: new URLSearchParams({
1426
- grant_type: 'authorization_code',
1427
- code,
1428
- redirect_uri: REDIRECT_URI,
1429
- client_id: CLIENT_ID,
1430
- code_verifier: pkce.verifier,
1431
- }),
1432
- redirect: 'error',
1433
- signal: AbortSignal.timeout(TOKEN_TIMEOUT_MS),
1434
- });
1435
- if (!tokenRes.ok) { resolve(null); return; }
1436
- const json = await tokenRes.json();
1437
- if (!json.access_token || !json.refresh_token) { resolve(null); return; }
1438
- const expiresAt = (typeof json.expires_in === 'number'
1439
- ? Date.now() + json.expires_in * 1000
1440
- : 0) || _expiryFromAccessToken(json.access_token);
1441
- const tokens = {
1442
- access_token: json.access_token,
1443
- refresh_token: json.refresh_token,
1444
- expires_at: expiresAt,
1445
- account_id: extractAccountId(json.access_token),
1446
- };
1447
- saveTokens(tokens);
1448
- resolve(tokens);
1449
- } catch {
1450
- resolve(null);
1451
- }
1452
- });
1453
- server.listen(CALLBACK_PORT, CALLBACK_HOST);
1454
- server.on('error', () => { clearTimeout(timeout); resolve(null); });
1455
- });
1456
- }