mixdog 0.7.17 → 0.8.0

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 (836) 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/smoke-loop-report.mjs +221 -0
  10. package/scripts/smoke-loop.mjs +201 -0
  11. package/scripts/smoke.mjs +113 -0
  12. package/scripts/tool-failures.mjs +143 -0
  13. package/scripts/tool-smoke.mjs +456 -0
  14. package/src/agents/debugger/AGENT.md +3 -0
  15. package/src/agents/debugger/agent.json +6 -0
  16. package/src/agents/explore/AGENT.md +4 -0
  17. package/src/agents/explore/agent.json +6 -0
  18. package/src/agents/heavy-worker/AGENT.md +3 -0
  19. package/src/agents/heavy-worker/agent.json +6 -0
  20. package/src/agents/maintainer/AGENT.md +3 -0
  21. package/src/agents/maintainer/agent.json +6 -0
  22. package/src/agents/reviewer/AGENT.md +3 -0
  23. package/src/agents/reviewer/agent.json +6 -0
  24. package/src/agents/scheduler-task.md +3 -0
  25. package/src/agents/web-researcher/AGENT.md +3 -0
  26. package/src/agents/web-researcher/agent.json +6 -0
  27. package/src/agents/webhook-handler.md +3 -0
  28. package/src/agents/worker/AGENT.md +3 -0
  29. package/src/agents/worker/agent.json +6 -0
  30. package/src/app.mjs +90 -0
  31. package/src/cli.mjs +11 -0
  32. package/src/defaults/hidden-roles.json +72 -0
  33. package/src/defaults/mixdog-config.template.json +15 -0
  34. package/src/hooks/lib/permission-evaluator.cjs +488 -0
  35. package/src/hooks/lib/settings-loader.cjs +112 -0
  36. package/src/lib/keychain-cjs.cjs +332 -0
  37. package/src/lib/plugin-paths.cjs +28 -0
  38. package/src/lib/rules-builder.cjs +315 -0
  39. package/src/mixdog-session-runtime.mjs +3704 -0
  40. package/src/output-styles/default.md +38 -0
  41. package/src/output-styles/extreme-simple.md +17 -0
  42. package/src/output-styles/simple.md +17 -0
  43. package/src/repl.mjs +322 -0
  44. package/src/rules/bridge/00-common.md +5 -0
  45. package/src/rules/bridge/20-skip-protocol.md +11 -0
  46. package/src/rules/bridge/30-explorer.md +4 -0
  47. package/src/rules/bridge/40-cycle1-agent.md +28 -0
  48. package/src/rules/bridge/41-cycle2-agent.md +59 -0
  49. package/src/rules/lead/00-tool-lead.md +5 -0
  50. package/src/rules/lead/01-general.md +5 -0
  51. package/src/rules/lead/02-channels.md +3 -0
  52. package/src/rules/lead/04-workflow.md +12 -0
  53. package/src/rules/shared/00-language.md +3 -0
  54. package/src/rules/shared/01-tool.md +3 -0
  55. package/src/runtime/agent/orchestrator/bridge-trace.mjs +814 -0
  56. package/src/runtime/agent/orchestrator/cache-mtime.mjs +60 -0
  57. package/src/runtime/agent/orchestrator/config.mjs +446 -0
  58. package/src/runtime/agent/orchestrator/context/collect.mjs +796 -0
  59. package/src/runtime/agent/orchestrator/dispatch-persist.mjs +417 -0
  60. package/src/runtime/agent/orchestrator/internal-roles.mjs +188 -0
  61. package/src/runtime/agent/orchestrator/internal-tools.mjs +88 -0
  62. package/src/runtime/agent/orchestrator/mcp/client.mjs +345 -0
  63. package/src/runtime/agent/orchestrator/providers/anthropic-oauth.mjs +2104 -0
  64. package/src/runtime/agent/orchestrator/providers/anthropic.mjs +784 -0
  65. package/src/runtime/agent/orchestrator/providers/api-usage.mjs +341 -0
  66. package/src/runtime/agent/orchestrator/providers/gemini.mjs +1679 -0
  67. package/src/runtime/agent/orchestrator/providers/grok-oauth.mjs +959 -0
  68. package/src/runtime/agent/orchestrator/providers/media-normalization.mjs +213 -0
  69. package/src/runtime/agent/orchestrator/providers/model-cache.mjs +38 -0
  70. package/src/runtime/agent/orchestrator/providers/model-catalog.mjs +471 -0
  71. package/src/runtime/agent/orchestrator/providers/oauth-usage.mjs +615 -0
  72. package/src/runtime/agent/orchestrator/providers/openai-compat-stream.mjs +808 -0
  73. package/src/runtime/agent/orchestrator/providers/openai-compat.mjs +1719 -0
  74. package/src/runtime/agent/orchestrator/providers/openai-oauth-ws.mjs +2587 -0
  75. package/src/runtime/agent/orchestrator/providers/openai-oauth.mjs +1953 -0
  76. package/src/runtime/agent/orchestrator/providers/openai-ws.mjs +136 -0
  77. package/src/runtime/agent/orchestrator/providers/opencode-go-usage.mjs +317 -0
  78. package/src/runtime/agent/orchestrator/providers/opencode-go.mjs +109 -0
  79. package/src/runtime/agent/orchestrator/providers/registry.mjs +247 -0
  80. package/src/runtime/agent/orchestrator/providers/retry-classifier.mjs +332 -0
  81. package/src/runtime/agent/orchestrator/providers/statusline-route-meta.mjs +11 -0
  82. package/src/runtime/agent/orchestrator/providers/trace-utils.mjs +50 -0
  83. package/src/runtime/agent/orchestrator/session/cache/prefetch-cache.mjs +142 -0
  84. package/src/runtime/agent/orchestrator/session/cache/read-cache.mjs +318 -0
  85. package/src/runtime/agent/orchestrator/session/cache/scoped-cache.mjs +367 -0
  86. package/src/runtime/agent/orchestrator/session/compact.mjs +882 -0
  87. package/src/runtime/agent/orchestrator/session/context-utils.mjs +233 -0
  88. package/src/runtime/agent/orchestrator/session/loop.mjs +2320 -0
  89. package/src/runtime/agent/orchestrator/session/manager.mjs +2960 -0
  90. package/src/runtime/agent/orchestrator/session/result-classification.mjs +65 -0
  91. package/src/runtime/agent/orchestrator/session/store.mjs +663 -0
  92. package/src/runtime/agent/orchestrator/session/tool-result-offload.mjs +166 -0
  93. package/src/runtime/agent/orchestrator/smart-bridge/bridge-llm.mjs +339 -0
  94. package/src/runtime/agent/orchestrator/smart-bridge/cache-strategy.mjs +419 -0
  95. package/src/runtime/agent/orchestrator/stall-policy.mjs +227 -0
  96. package/src/runtime/agent/orchestrator/tool-loop-guard.mjs +235 -0
  97. package/src/runtime/agent/orchestrator/tools/bash-session.mjs +723 -0
  98. package/src/runtime/agent/orchestrator/tools/builtin/arg-guard.mjs +389 -0
  99. package/src/runtime/agent/orchestrator/tools/builtin/bash-tool.mjs +637 -0
  100. package/src/runtime/agent/orchestrator/tools/builtin/builtin-tools.mjs +165 -0
  101. package/src/runtime/agent/orchestrator/tools/builtin/fuzzy-match.mjs +104 -0
  102. package/src/runtime/agent/orchestrator/tools/builtin/glob-walk.mjs +194 -0
  103. package/src/runtime/agent/orchestrator/tools/builtin/list-tool.mjs +596 -0
  104. package/src/runtime/agent/orchestrator/tools/builtin/native-edit-runner.mjs +110 -0
  105. package/src/runtime/agent/orchestrator/tools/builtin/path-diagnostics.mjs +153 -0
  106. package/src/runtime/agent/orchestrator/tools/builtin/read-formatting.mjs +118 -0
  107. package/src/runtime/agent/orchestrator/tools/builtin/read-open.mjs +189 -0
  108. package/src/runtime/agent/orchestrator/tools/builtin/read-single-tool.mjs +731 -0
  109. package/src/runtime/agent/orchestrator/tools/builtin/read-snapshot-runtime.mjs +168 -0
  110. package/src/runtime/agent/orchestrator/tools/builtin/read-streaming.mjs +602 -0
  111. package/src/runtime/agent/orchestrator/tools/builtin/rg-runner.mjs +465 -0
  112. package/src/runtime/agent/orchestrator/tools/builtin/search-builders.mjs +160 -0
  113. package/src/runtime/agent/orchestrator/tools/builtin/search-tool.mjs +982 -0
  114. package/src/runtime/agent/orchestrator/tools/builtin/shell-jobs.mjs +1087 -0
  115. package/src/runtime/agent/orchestrator/tools/builtin/shell-runtime.mjs +231 -0
  116. package/src/runtime/agent/orchestrator/tools/builtin/snapshot-store.mjs +223 -0
  117. package/src/runtime/agent/orchestrator/tools/builtin.mjs +478 -0
  118. package/src/runtime/agent/orchestrator/tools/code-graph-tool-defs.mjs +24 -0
  119. package/src/runtime/agent/orchestrator/tools/code-graph.mjs +4102 -0
  120. package/src/runtime/agent/orchestrator/tools/destructive-warning.mjs +323 -0
  121. package/src/runtime/agent/orchestrator/tools/graph-binary-fetcher.mjs +154 -0
  122. package/src/runtime/agent/orchestrator/tools/graph-manifest.json +26 -0
  123. package/src/runtime/agent/orchestrator/tools/patch-binary-fetcher.mjs +143 -0
  124. package/src/runtime/agent/orchestrator/tools/patch-tool-defs.mjs +18 -0
  125. package/src/runtime/agent/orchestrator/tools/patch.mjs +2772 -0
  126. package/src/runtime/agent/orchestrator/tools/progress-message.mjs +114 -0
  127. package/src/runtime/agent/orchestrator/tools/shell-command.mjs +880 -0
  128. package/src/runtime/agent/orchestrator/tools/shell-snapshot.mjs +312 -0
  129. package/src/runtime/channels/backends/discord.mjs +781 -0
  130. package/src/runtime/channels/data/voice-runtime-manifest.json +138 -0
  131. package/src/runtime/channels/index.mjs +3309 -0
  132. package/src/runtime/channels/lib/config.mjs +285 -0
  133. package/src/runtime/channels/lib/drop-trace.mjs +71 -0
  134. package/src/runtime/channels/lib/event-pipeline.mjs +81 -0
  135. package/src/runtime/channels/lib/holidays.mjs +138 -0
  136. package/src/runtime/channels/lib/hook-pipe-server.mjs +671 -0
  137. package/src/runtime/channels/lib/output-forwarder.mjs +765 -0
  138. package/src/runtime/channels/lib/runtime-paths.mjs +497 -0
  139. package/src/runtime/channels/lib/scheduler.mjs +710 -0
  140. package/src/runtime/channels/lib/session-discovery.mjs +102 -0
  141. package/src/runtime/channels/lib/state-file.mjs +68 -0
  142. package/src/runtime/channels/lib/status-snapshot.mjs +224 -0
  143. package/src/runtime/channels/lib/tool-format.mjs +124 -0
  144. package/src/runtime/channels/lib/transcript-discovery.mjs +195 -0
  145. package/src/runtime/channels/lib/voice-runtime-fetcher.mjs +734 -0
  146. package/src/runtime/channels/lib/webhook.mjs +1288 -0
  147. package/src/runtime/channels/tool-defs.mjs +177 -0
  148. package/src/runtime/lib/keychain-cjs.cjs +289 -0
  149. package/src/runtime/memory/data/runtime-manifest.json +40 -0
  150. package/src/runtime/memory/index.mjs +3600 -0
  151. package/src/runtime/memory/lib/core-memory-store.mjs +336 -0
  152. package/src/runtime/memory/lib/embedding-provider.mjs +275 -0
  153. package/src/runtime/memory/lib/embedding-worker.mjs +331 -0
  154. package/src/runtime/memory/lib/memory-cycle-requests.mjs +276 -0
  155. package/src/runtime/memory/lib/memory-cycle1.mjs +783 -0
  156. package/src/runtime/memory/lib/memory-cycle2.mjs +1389 -0
  157. package/src/runtime/memory/lib/memory-cycle3.mjs +646 -0
  158. package/src/runtime/memory/lib/memory-embed.mjs +300 -0
  159. package/src/runtime/memory/lib/memory-ops-policy.mjs +149 -0
  160. package/src/runtime/memory/lib/memory-recall-store.mjs +644 -0
  161. package/src/runtime/memory/lib/memory.mjs +418 -0
  162. package/src/runtime/memory/lib/pg/adapter.mjs +314 -0
  163. package/src/runtime/memory/lib/pg/process.mjs +366 -0
  164. package/src/runtime/memory/lib/pg/supervisor.mjs +495 -0
  165. package/src/runtime/memory/lib/runtime-fetcher.mjs +464 -0
  166. package/src/runtime/memory/lib/trace-store.mjs +734 -0
  167. package/src/runtime/memory/tool-defs.mjs +79 -0
  168. package/src/runtime/search/index.mjs +925 -0
  169. package/src/runtime/search/lib/config.mjs +61 -0
  170. package/src/runtime/search/lib/web-tools.mjs +1278 -0
  171. package/src/runtime/search/tool-defs.mjs +64 -0
  172. package/src/runtime/shared/atomic-file.mjs +435 -0
  173. package/src/runtime/shared/background-tasks.mjs +376 -0
  174. package/src/runtime/shared/child-guardian.mjs +98 -0
  175. package/src/runtime/shared/config.mjs +393 -0
  176. package/src/runtime/shared/err-text.mjs +121 -0
  177. package/src/runtime/shared/launcher-control.mjs +259 -0
  178. package/src/runtime/shared/llm/cost.mjs +66 -0
  179. package/src/runtime/shared/llm/http-agent.mjs +129 -0
  180. package/src/runtime/shared/open-url.mjs +37 -0
  181. package/src/runtime/shared/plugin-paths.mjs +25 -0
  182. package/src/runtime/shared/process-shutdown.mjs +147 -0
  183. package/src/runtime/shared/schedules-store.mjs +70 -0
  184. package/src/runtime/shared/tool-execution-contract.mjs +104 -0
  185. package/src/runtime/shared/tool-surface.mjs +950 -0
  186. package/src/runtime/shared/user-cwd.mjs +221 -0
  187. package/src/runtime/shared/user-data-guard.mjs +232 -0
  188. package/src/runtime/shared/workspace-router.mjs +259 -0
  189. package/src/standalone/bridge-tool.mjs +1414 -0
  190. package/src/standalone/channel-admin.mjs +366 -0
  191. package/src/standalone/channel-worker-preload.cjs +3 -0
  192. package/src/standalone/channel-worker.mjs +353 -0
  193. package/src/standalone/explore-tool.mjs +233 -0
  194. package/src/standalone/hook-bus.mjs +246 -0
  195. package/src/standalone/plugin-admin.mjs +247 -0
  196. package/src/standalone/provider-admin.mjs +338 -0
  197. package/src/standalone/seeds.mjs +94 -0
  198. package/src/standalone/usage-dashboard.mjs +510 -0
  199. package/src/tui/App.jsx +5438 -0
  200. package/src/tui/components/AnsiText.jsx +199 -0
  201. package/src/tui/components/ContextPanel.jsx +217 -0
  202. package/src/tui/components/Markdown.jsx +205 -0
  203. package/src/tui/components/MarkdownTable.jsx +204 -0
  204. package/src/tui/components/Message.jsx +103 -0
  205. package/src/tui/components/Picker.jsx +317 -0
  206. package/src/tui/components/PromptInput.jsx +584 -0
  207. package/src/tui/components/QueuedCommands.jsx +47 -0
  208. package/src/tui/components/SlashCommandPalette.jsx +114 -0
  209. package/src/tui/components/Spinner.jsx +317 -0
  210. package/src/tui/components/StatusLine.jsx +87 -0
  211. package/src/tui/components/TextEntryPanel.jsx +323 -0
  212. package/src/tui/components/ToolExecution.jsx +772 -0
  213. package/src/tui/components/TurnDone.jsx +78 -0
  214. package/src/tui/components/UsagePanel.jsx +331 -0
  215. package/src/tui/dist/index.mjs +12359 -0
  216. package/src/tui/engine.mjs +2410 -0
  217. package/src/tui/figures.mjs +50 -0
  218. package/src/tui/hooks/useEngine.mjs +16 -0
  219. package/src/tui/index.jsx +254 -0
  220. package/src/tui/input-editing.mjs +242 -0
  221. package/src/tui/markdown/format-token.mjs +194 -0
  222. package/src/tui/paste-attachments.mjs +198 -0
  223. package/src/tui/runtime/shared/process-shutdown.mjs +1 -0
  224. package/src/tui/spinner-verbs.mjs +45 -0
  225. package/src/tui/theme.mjs +67 -0
  226. package/src/tui/time-format.mjs +53 -0
  227. package/src/ui/ansi.mjs +115 -0
  228. package/src/ui/markdown.mjs +195 -0
  229. package/src/ui/statusline.mjs +730 -0
  230. package/src/ui/tool-card.mjs +101 -0
  231. package/src/vendor/statusline/bin/statusline-lib.mjs +805 -0
  232. package/src/vendor/statusline/bin/statusline-route.mjs +596 -0
  233. package/src/vendor/statusline/scripts/lib/gateway-settings.mjs +285 -0
  234. package/src/vendor/statusline/src/gateway/claude-current.mjs +320 -0
  235. package/src/vendor/statusline/src/gateway/route-meta.mjs +753 -0
  236. package/src/vendor/statusline/src/gateway/session-routes.mjs +244 -0
  237. package/src/workflows/default/WORKFLOW.md +7 -0
  238. package/src/workflows/default/workflow.json +14 -0
  239. package/vendor/ink/build/ansi-tokenizer.d.ts +38 -0
  240. package/vendor/ink/build/ansi-tokenizer.js +316 -0
  241. package/vendor/ink/build/ansi-tokenizer.js.map +1 -0
  242. package/vendor/ink/build/colorize.d.ts +3 -0
  243. package/vendor/ink/build/colorize.js +48 -0
  244. package/vendor/ink/build/colorize.js.map +1 -0
  245. package/vendor/ink/build/components/AccessibilityContext.d.ts +3 -0
  246. package/vendor/ink/build/components/AccessibilityContext.js +5 -0
  247. package/vendor/ink/build/components/AccessibilityContext.js.map +1 -0
  248. package/vendor/ink/build/components/AnimationContext.d.ts +9 -0
  249. package/vendor/ink/build/components/AnimationContext.js +13 -0
  250. package/vendor/ink/build/components/AnimationContext.js.map +1 -0
  251. package/vendor/ink/build/components/App.d.ts +24 -0
  252. package/vendor/ink/build/components/App.js +554 -0
  253. package/vendor/ink/build/components/App.js.map +1 -0
  254. package/vendor/ink/build/components/AppContext.d.ts +80 -0
  255. package/vendor/ink/build/components/AppContext.js +25 -0
  256. package/vendor/ink/build/components/AppContext.js.map +1 -0
  257. package/vendor/ink/build/components/BackgroundContext.d.ts +4 -0
  258. package/vendor/ink/build/components/BackgroundContext.js +3 -0
  259. package/vendor/ink/build/components/BackgroundContext.js.map +1 -0
  260. package/vendor/ink/build/components/Box.d.ts +130 -0
  261. package/vendor/ink/build/components/Box.js +34 -0
  262. package/vendor/ink/build/components/Box.js.map +1 -0
  263. package/vendor/ink/build/components/CursorContext.d.ts +11 -0
  264. package/vendor/ink/build/components/CursorContext.js +8 -0
  265. package/vendor/ink/build/components/CursorContext.js.map +1 -0
  266. package/vendor/ink/build/components/ErrorBoundary.d.ts +18 -0
  267. package/vendor/ink/build/components/ErrorBoundary.js +23 -0
  268. package/vendor/ink/build/components/ErrorBoundary.js.map +1 -0
  269. package/vendor/ink/build/components/ErrorOverview.d.ts +6 -0
  270. package/vendor/ink/build/components/ErrorOverview.js +90 -0
  271. package/vendor/ink/build/components/ErrorOverview.js.map +1 -0
  272. package/vendor/ink/build/components/FocusContext.d.ts +16 -0
  273. package/vendor/ink/build/components/FocusContext.js +17 -0
  274. package/vendor/ink/build/components/FocusContext.js.map +1 -0
  275. package/vendor/ink/build/components/Newline.d.ts +13 -0
  276. package/vendor/ink/build/components/Newline.js +8 -0
  277. package/vendor/ink/build/components/Newline.js.map +1 -0
  278. package/vendor/ink/build/components/Spacer.d.ts +7 -0
  279. package/vendor/ink/build/components/Spacer.js +11 -0
  280. package/vendor/ink/build/components/Spacer.js.map +1 -0
  281. package/vendor/ink/build/components/Static.d.ts +24 -0
  282. package/vendor/ink/build/components/Static.js +28 -0
  283. package/vendor/ink/build/components/Static.js.map +1 -0
  284. package/vendor/ink/build/components/StderrContext.d.ts +15 -0
  285. package/vendor/ink/build/components/StderrContext.js +13 -0
  286. package/vendor/ink/build/components/StderrContext.js.map +1 -0
  287. package/vendor/ink/build/components/StdinContext.d.ts +28 -0
  288. package/vendor/ink/build/components/StdinContext.js +20 -0
  289. package/vendor/ink/build/components/StdinContext.js.map +1 -0
  290. package/vendor/ink/build/components/StdoutContext.d.ts +15 -0
  291. package/vendor/ink/build/components/StdoutContext.js +13 -0
  292. package/vendor/ink/build/components/StdoutContext.js.map +1 -0
  293. package/vendor/ink/build/components/Text.d.ts +55 -0
  294. package/vendor/ink/build/components/Text.js +50 -0
  295. package/vendor/ink/build/components/Text.js.map +1 -0
  296. package/vendor/ink/build/components/Transform.d.ts +16 -0
  297. package/vendor/ink/build/components/Transform.js +15 -0
  298. package/vendor/ink/build/components/Transform.js.map +1 -0
  299. package/vendor/ink/build/cursor-helpers.d.ts +39 -0
  300. package/vendor/ink/build/cursor-helpers.js +62 -0
  301. package/vendor/ink/build/cursor-helpers.js.map +1 -0
  302. package/vendor/ink/build/devtools-window-polyfill.d.ts +1 -0
  303. package/vendor/ink/build/devtools-window-polyfill.js +68 -0
  304. package/vendor/ink/build/devtools-window-polyfill.js.map +1 -0
  305. package/vendor/ink/build/devtools.d.ts +1 -0
  306. package/vendor/ink/build/devtools.js +36 -0
  307. package/vendor/ink/build/devtools.js.map +1 -0
  308. package/vendor/ink/build/dom.d.ts +62 -0
  309. package/vendor/ink/build/dom.js +143 -0
  310. package/vendor/ink/build/dom.js.map +1 -0
  311. package/vendor/ink/build/get-max-width.d.ts +3 -0
  312. package/vendor/ink/build/get-max-width.js +10 -0
  313. package/vendor/ink/build/get-max-width.js.map +1 -0
  314. package/vendor/ink/build/hooks/use-animation.d.ts +49 -0
  315. package/vendor/ink/build/hooks/use-animation.js +87 -0
  316. package/vendor/ink/build/hooks/use-animation.js.map +1 -0
  317. package/vendor/ink/build/hooks/use-app.d.ts +5 -0
  318. package/vendor/ink/build/hooks/use-app.js +8 -0
  319. package/vendor/ink/build/hooks/use-app.js.map +1 -0
  320. package/vendor/ink/build/hooks/use-box-metrics.d.ts +59 -0
  321. package/vendor/ink/build/hooks/use-box-metrics.js +81 -0
  322. package/vendor/ink/build/hooks/use-box-metrics.js.map +1 -0
  323. package/vendor/ink/build/hooks/use-cursor.d.ts +12 -0
  324. package/vendor/ink/build/hooks/use-cursor.js +29 -0
  325. package/vendor/ink/build/hooks/use-cursor.js.map +1 -0
  326. package/vendor/ink/build/hooks/use-focus-manager.d.ts +43 -0
  327. package/vendor/ink/build/hooks/use-focus-manager.js +18 -0
  328. package/vendor/ink/build/hooks/use-focus-manager.js.map +1 -0
  329. package/vendor/ink/build/hooks/use-focus.d.ts +30 -0
  330. package/vendor/ink/build/hooks/use-focus.js +43 -0
  331. package/vendor/ink/build/hooks/use-focus.js.map +1 -0
  332. package/vendor/ink/build/hooks/use-input.d.ts +132 -0
  333. package/vendor/ink/build/hooks/use-input.js +126 -0
  334. package/vendor/ink/build/hooks/use-input.js.map +1 -0
  335. package/vendor/ink/build/hooks/use-is-screen-reader-enabled.d.ts +6 -0
  336. package/vendor/ink/build/hooks/use-is-screen-reader-enabled.js +12 -0
  337. package/vendor/ink/build/hooks/use-is-screen-reader-enabled.js.map +1 -0
  338. package/vendor/ink/build/hooks/use-paste.d.ts +35 -0
  339. package/vendor/ink/build/hooks/use-paste.js +62 -0
  340. package/vendor/ink/build/hooks/use-paste.js.map +1 -0
  341. package/vendor/ink/build/hooks/use-stderr.d.ts +5 -0
  342. package/vendor/ink/build/hooks/use-stderr.js +8 -0
  343. package/vendor/ink/build/hooks/use-stderr.js.map +1 -0
  344. package/vendor/ink/build/hooks/use-stdin.d.ts +7 -0
  345. package/vendor/ink/build/hooks/use-stdin.js +9 -0
  346. package/vendor/ink/build/hooks/use-stdin.js.map +1 -0
  347. package/vendor/ink/build/hooks/use-stdout.d.ts +5 -0
  348. package/vendor/ink/build/hooks/use-stdout.js +8 -0
  349. package/vendor/ink/build/hooks/use-stdout.js.map +1 -0
  350. package/vendor/ink/build/hooks/use-window-size.d.ts +18 -0
  351. package/vendor/ink/build/hooks/use-window-size.js +22 -0
  352. package/vendor/ink/build/hooks/use-window-size.js.map +1 -0
  353. package/vendor/ink/build/index.d.ts +42 -0
  354. package/vendor/ink/build/index.js +24 -0
  355. package/vendor/ink/build/index.js.map +1 -0
  356. package/vendor/ink/build/ink.d.ts +146 -0
  357. package/vendor/ink/build/ink.js +1022 -0
  358. package/vendor/ink/build/ink.js.map +1 -0
  359. package/vendor/ink/build/input-parser.d.ts +10 -0
  360. package/vendor/ink/build/input-parser.js +194 -0
  361. package/vendor/ink/build/input-parser.js.map +1 -0
  362. package/vendor/ink/build/instances.d.ts +3 -0
  363. package/vendor/ink/build/instances.js +8 -0
  364. package/vendor/ink/build/instances.js.map +1 -0
  365. package/vendor/ink/build/kitty-keyboard.d.ts +23 -0
  366. package/vendor/ink/build/kitty-keyboard.js +32 -0
  367. package/vendor/ink/build/kitty-keyboard.js.map +1 -0
  368. package/vendor/ink/build/log-update.d.ts +20 -0
  369. package/vendor/ink/build/log-update.js +261 -0
  370. package/vendor/ink/build/log-update.js.map +1 -0
  371. package/vendor/ink/build/measure-element.d.ts +20 -0
  372. package/vendor/ink/build/measure-element.js +13 -0
  373. package/vendor/ink/build/measure-element.js.map +1 -0
  374. package/vendor/ink/build/measure-text.d.ts +6 -0
  375. package/vendor/ink/build/measure-text.js +21 -0
  376. package/vendor/ink/build/measure-text.js.map +1 -0
  377. package/vendor/ink/build/output.d.ts +35 -0
  378. package/vendor/ink/build/output.js +328 -0
  379. package/vendor/ink/build/output.js.map +1 -0
  380. package/vendor/ink/build/parse-keypress.d.ts +20 -0
  381. package/vendor/ink/build/parse-keypress.js +495 -0
  382. package/vendor/ink/build/parse-keypress.js.map +1 -0
  383. package/vendor/ink/build/reconciler.d.ts +4 -0
  384. package/vendor/ink/build/reconciler.js +306 -0
  385. package/vendor/ink/build/reconciler.js.map +1 -0
  386. package/vendor/ink/build/render-background.d.ts +4 -0
  387. package/vendor/ink/build/render-background.js +25 -0
  388. package/vendor/ink/build/render-background.js.map +1 -0
  389. package/vendor/ink/build/render-border.d.ts +4 -0
  390. package/vendor/ink/build/render-border.js +84 -0
  391. package/vendor/ink/build/render-border.js.map +1 -0
  392. package/vendor/ink/build/render-node-to-output.d.ts +14 -0
  393. package/vendor/ink/build/render-node-to-output.js +162 -0
  394. package/vendor/ink/build/render-node-to-output.js.map +1 -0
  395. package/vendor/ink/build/render-to-string.d.ts +38 -0
  396. package/vendor/ink/build/render-to-string.js +116 -0
  397. package/vendor/ink/build/render-to-string.js.map +1 -0
  398. package/vendor/ink/build/render.d.ts +176 -0
  399. package/vendor/ink/build/render.js +71 -0
  400. package/vendor/ink/build/render.js.map +1 -0
  401. package/vendor/ink/build/renderer.d.ts +8 -0
  402. package/vendor/ink/build/renderer.js +64 -0
  403. package/vendor/ink/build/renderer.js.map +1 -0
  404. package/vendor/ink/build/sanitize-ansi.d.ts +2 -0
  405. package/vendor/ink/build/sanitize-ansi.js +27 -0
  406. package/vendor/ink/build/sanitize-ansi.js.map +1 -0
  407. package/vendor/ink/build/squash-text-nodes.d.ts +3 -0
  408. package/vendor/ink/build/squash-text-nodes.js +36 -0
  409. package/vendor/ink/build/squash-text-nodes.js.map +1 -0
  410. package/vendor/ink/build/styles.d.ts +302 -0
  411. package/vendor/ink/build/styles.js +303 -0
  412. package/vendor/ink/build/styles.js.map +1 -0
  413. package/vendor/ink/build/utils.d.ts +9 -0
  414. package/vendor/ink/build/utils.js +19 -0
  415. package/vendor/ink/build/utils.js.map +1 -0
  416. package/vendor/ink/build/wrap-text.d.ts +3 -0
  417. package/vendor/ink/build/wrap-text.js +38 -0
  418. package/vendor/ink/build/wrap-text.js.map +1 -0
  419. package/vendor/ink/build/write-synchronized.d.ts +4 -0
  420. package/vendor/ink/build/write-synchronized.js +9 -0
  421. package/vendor/ink/build/write-synchronized.js.map +1 -0
  422. package/vendor/ink/license +10 -0
  423. package/vendor/ink/package.json +137 -0
  424. package/.claude-plugin/marketplace.json +0 -34
  425. package/.claude-plugin/plugin.json +0 -20
  426. package/.gitattributes +0 -34
  427. package/.mcp.json +0 -14
  428. package/ARCHITECTURE.md +0 -77
  429. package/CHANGELOG.md +0 -30
  430. package/CONTRIBUTING.md +0 -45
  431. package/DATA-FLOW.md +0 -79
  432. package/LICENSE +0 -21
  433. package/SECURITY.md +0 -138
  434. package/UNINSTALL.md +0 -112
  435. package/agents/maintenance.md +0 -5
  436. package/agents/memory-classification.md +0 -30
  437. package/agents/scheduler-task.md +0 -18
  438. package/agents/webhook-handler.md +0 -27
  439. package/agents/worker.md +0 -24
  440. package/bin/bridge +0 -133
  441. package/bin/statusline-launcher.mjs +0 -82
  442. package/bin/statusline-lib.mjs +0 -558
  443. package/bin/statusline.mjs +0 -615
  444. package/bun.lock +0 -927
  445. package/commands/config.md +0 -16
  446. package/commands/doctor.md +0 -13
  447. package/commands/setup.md +0 -17
  448. package/defaults/hidden-roles.json +0 -68
  449. package/defaults/memory-chunk-prompt.md +0 -63
  450. package/defaults/mixdog-config.template.json +0 -27
  451. package/defaults/user-workflow.json +0 -8
  452. package/defaults/user-workflow.md +0 -17
  453. package/hooks/hooks.json +0 -73
  454. package/hooks/lib/active-instance.cjs +0 -77
  455. package/hooks/lib/permission-evaluator.cjs +0 -411
  456. package/hooks/lib/permission-route.cjs +0 -63
  457. package/hooks/lib/settings-loader.cjs +0 -117
  458. package/hooks/post-tool-use.cjs +0 -84
  459. package/hooks/pre-mcp-sandbox.cjs +0 -158
  460. package/hooks/pre-tool-subagent.cjs +0 -258
  461. package/hooks/session-start.cjs +0 -1479
  462. package/hooks/shim-launcher.cjs +0 -65
  463. package/hooks/turn-timer.cjs +0 -82
  464. package/lib/claude-md-writer.cjs +0 -386
  465. package/lib/keychain-cjs.cjs +0 -290
  466. package/lib/plugin-paths.cjs +0 -69
  467. package/lib/rules-builder.cjs +0 -241
  468. package/native/README.md +0 -117
  469. package/native/prebuilt/linux-aarch64/mixdog-shim +0 -0
  470. package/native/prebuilt/linux-x86_64/mixdog-shim +0 -0
  471. package/native/prebuilt/macos-aarch64/mixdog-shim +0 -0
  472. package/native/prebuilt/macos-x86_64/mixdog-shim +0 -0
  473. package/native/prebuilt/windows-x86_64/mixdog-shim.exe +0 -0
  474. package/prompts/code-review.txt +0 -16
  475. package/prompts/security-audit.txt +0 -17
  476. package/rules/bridge/00-common.md +0 -39
  477. package/rules/bridge/20-skip-protocol.md +0 -18
  478. package/rules/bridge/30-explorer.md +0 -33
  479. package/rules/bridge/40-cycle1-agent.md +0 -52
  480. package/rules/bridge/41-cycle2-agent.md +0 -62
  481. package/rules/lead/00-tool-lead.md +0 -61
  482. package/rules/lead/01-general.md +0 -23
  483. package/rules/lead/02-channels.md +0 -49
  484. package/rules/lead/03-team.md +0 -27
  485. package/rules/lead/04-workflow.md +0 -20
  486. package/rules/shared/00-language.md +0 -14
  487. package/rules/shared/01-tool.md +0 -138
  488. package/scripts/bootstrap.mjs +0 -130
  489. package/scripts/bridge-unify-smoke.mjs +0 -308
  490. package/scripts/build-runtime-linux.sh +0 -348
  491. package/scripts/build-runtime-macos.sh +0 -217
  492. package/scripts/build-runtime-windows.ps1 +0 -242
  493. package/scripts/builtin-utils-smoke.mjs +0 -398
  494. package/scripts/bump.mjs +0 -80
  495. package/scripts/check-json.mjs +0 -45
  496. package/scripts/check-syntax-changed.mjs +0 -102
  497. package/scripts/check-syntax.mjs +0 -58
  498. package/scripts/code-graph-batch.test.mjs +0 -33
  499. package/scripts/config-preserve-smoke.mjs +0 -180
  500. package/scripts/doctor.mjs +0 -489
  501. package/scripts/edit-normalize-fuzz.mjs +0 -130
  502. package/scripts/edit-normalize-smoke.mjs +0 -401
  503. package/scripts/edit-operation-smoke.mjs +0 -369
  504. package/scripts/edit2-smoke.mjs +0 -63
  505. package/scripts/ensure-deps.mjs +0 -259
  506. package/scripts/fuzzy-e2e.mjs +0 -28
  507. package/scripts/fuzzy-smoke.mjs +0 -26
  508. package/scripts/generate-runtime-manifest.mjs +0 -166
  509. package/scripts/guard-smoke.mjs +0 -66
  510. package/scripts/hidden-role-schema-smoke.mjs +0 -162
  511. package/scripts/hook-routing-smoke.mjs +0 -29
  512. package/scripts/inject-input.ps1 +0 -204
  513. package/scripts/io-complex-smoke.mjs +0 -667
  514. package/scripts/io-explore-bench.mjs +0 -424
  515. package/scripts/io-guardrails-smoke.mjs +0 -205
  516. package/scripts/io-mini-bench-baseline.json +0 -11
  517. package/scripts/io-mini-bench.mjs +0 -216
  518. package/scripts/io-route-harness.mjs +0 -933
  519. package/scripts/io-telemetry-report.mjs +0 -691
  520. package/scripts/mutation-bench.mjs +0 -564
  521. package/scripts/mutation-io-smoke.mjs +0 -1097
  522. package/scripts/native-patch-bridge-smoke.mjs +0 -288
  523. package/scripts/native-patch-smoke.mjs +0 -304
  524. package/scripts/openai-oauth-catalog-smoke.mjs +0 -53
  525. package/scripts/patch-interior-context-smoke.mjs +0 -49
  526. package/scripts/patch-newline-utf8-smoke.mjs +0 -157
  527. package/scripts/perf-hook-smoke.mjs +0 -71
  528. package/scripts/permission-eval-smoke.mjs +0 -443
  529. package/scripts/prep-patch.mjs +0 -53
  530. package/scripts/prep-shim.mjs +0 -96
  531. package/scripts/provider-cache-smoke.mjs +0 -687
  532. package/scripts/report-runtime-health.mjs +0 -132
  533. package/scripts/resolve-bun.mjs +0 -60
  534. package/scripts/run-mcp.mjs +0 -1448
  535. package/scripts/salvage-v4a-shatter.test.mjs +0 -58
  536. package/scripts/scoped-cache-io-smoke.mjs +0 -103
  537. package/scripts/shell-policy-round3-smoke.mjs +0 -46
  538. package/scripts/smoke-runtime-negative.ps1 +0 -100
  539. package/scripts/smoke-runtime-negative.sh +0 -95
  540. package/scripts/stall-policy-smoke.mjs +0 -50
  541. package/scripts/start-memory-worker.mjs +0 -23
  542. package/scripts/statusline-launcher-smoke.mjs +0 -82
  543. package/scripts/stress-atomic-write.mjs +0 -1028
  544. package/scripts/test-fault-inject.mjs +0 -164
  545. package/scripts/test-large-file.mjs +0 -174
  546. package/scripts/tool-edge-smoke.mjs +0 -209
  547. package/scripts/uninstall.mjs +0 -201
  548. package/scripts/webhook-selfheal-smoke.mjs +0 -27
  549. package/scripts/write-overwrite-guard-smoke.mjs +0 -56
  550. package/server-main.mjs +0 -3109
  551. package/server.mjs +0 -468
  552. package/setup/config-merge.mjs +0 -246
  553. package/setup/install.mjs +0 -574
  554. package/setup/launch-core.mjs +0 -617
  555. package/setup/launch.mjs +0 -101
  556. package/setup/locate-claude.mjs +0 -56
  557. package/setup/mixdog-cli.mjs +0 -122
  558. package/setup/setup-server.mjs +0 -3305
  559. package/setup/setup.html +0 -3740
  560. package/setup/tui.mjs +0 -325
  561. package/skills/retro-skill-proposer/SKILL.md +0 -92
  562. package/skills/schedule-add/SKILL.md +0 -77
  563. package/skills/setup/SKILL.md +0 -356
  564. package/skills/webhook-add/SKILL.md +0 -81
  565. package/src/agent/bridge-stall-watchdog.mjs +0 -337
  566. package/src/agent/index.mjs +0 -2138
  567. package/src/agent/orchestrator/ai-wrapped-dispatch.mjs +0 -1010
  568. package/src/agent/orchestrator/bridge-retry.mjs +0 -220
  569. package/src/agent/orchestrator/bridge-trace.mjs +0 -583
  570. package/src/agent/orchestrator/cache-mtime.mjs +0 -58
  571. package/src/agent/orchestrator/config.mjs +0 -405
  572. package/src/agent/orchestrator/context/collect.mjs +0 -651
  573. package/src/agent/orchestrator/dispatch-persist.mjs +0 -549
  574. package/src/agent/orchestrator/drain-registry.mjs +0 -50
  575. package/src/agent/orchestrator/explore-validator.mjs +0 -8
  576. package/src/agent/orchestrator/internal-roles.mjs +0 -118
  577. package/src/agent/orchestrator/internal-tools.mjs +0 -88
  578. package/src/agent/orchestrator/jobs.mjs +0 -116
  579. package/src/agent/orchestrator/mcp/client.mjs +0 -364
  580. package/src/agent/orchestrator/providers/anthropic-oauth.mjs +0 -1881
  581. package/src/agent/orchestrator/providers/anthropic.mjs +0 -594
  582. package/src/agent/orchestrator/providers/gemini.mjs +0 -1530
  583. package/src/agent/orchestrator/providers/grok-oauth.mjs +0 -779
  584. package/src/agent/orchestrator/providers/model-catalog.mjs +0 -374
  585. package/src/agent/orchestrator/providers/openai-compat-stream.mjs +0 -366
  586. package/src/agent/orchestrator/providers/openai-compat.mjs +0 -1511
  587. package/src/agent/orchestrator/providers/openai-oauth-ws.mjs +0 -1891
  588. package/src/agent/orchestrator/providers/openai-oauth.mjs +0 -1456
  589. package/src/agent/orchestrator/providers/openai-ws.mjs +0 -127
  590. package/src/agent/orchestrator/providers/registry.mjs +0 -192
  591. package/src/agent/orchestrator/providers/retry-classifier.mjs +0 -325
  592. package/src/agent/orchestrator/session/cache/prefetch-cache.mjs +0 -142
  593. package/src/agent/orchestrator/session/cache/read-cache.mjs +0 -319
  594. package/src/agent/orchestrator/session/cache/scoped-cache.mjs +0 -361
  595. package/src/agent/orchestrator/session/loop.mjs +0 -1478
  596. package/src/agent/orchestrator/session/manager.mjs +0 -1991
  597. package/src/agent/orchestrator/session/result-classification.mjs +0 -65
  598. package/src/agent/orchestrator/session/store.mjs +0 -632
  599. package/src/agent/orchestrator/session/stream-watchdog.mjs +0 -130
  600. package/src/agent/orchestrator/session/tool-result-offload.mjs +0 -166
  601. package/src/agent/orchestrator/session/trim.mjs +0 -491
  602. package/src/agent/orchestrator/smart-bridge/CACHE-SHARD.md +0 -115
  603. package/src/agent/orchestrator/smart-bridge/bridge-llm.mjs +0 -331
  604. package/src/agent/orchestrator/smart-bridge/cache-obs.mjs +0 -150
  605. package/src/agent/orchestrator/smart-bridge/cache-strategy.mjs +0 -228
  606. package/src/agent/orchestrator/smart-bridge/index.mjs +0 -215
  607. package/src/agent/orchestrator/smart-bridge/profiles.mjs +0 -37
  608. package/src/agent/orchestrator/smart-bridge/registry.mjs +0 -348
  609. package/src/agent/orchestrator/stall-policy.mjs +0 -201
  610. package/src/agent/orchestrator/tool-loop-guard.mjs +0 -75
  611. package/src/agent/orchestrator/tools/bash-session.mjs +0 -722
  612. package/src/agent/orchestrator/tools/builtin/arg-guard.mjs +0 -455
  613. package/src/agent/orchestrator/tools/builtin/bash-tool.mjs +0 -480
  614. package/src/agent/orchestrator/tools/builtin/builtin-tools.mjs +0 -256
  615. package/src/agent/orchestrator/tools/builtin/edit-base-guard.mjs +0 -58
  616. package/src/agent/orchestrator/tools/builtin/edit-byte-plan.mjs +0 -240
  617. package/src/agent/orchestrator/tools/builtin/edit-byte-utils.mjs +0 -113
  618. package/src/agent/orchestrator/tools/builtin/edit-commit.mjs +0 -74
  619. package/src/agent/orchestrator/tools/builtin/edit-context-utils.mjs +0 -242
  620. package/src/agent/orchestrator/tools/builtin/edit-diagnostics.mjs +0 -211
  621. package/src/agent/orchestrator/tools/builtin/edit-engine.mjs +0 -1364
  622. package/src/agent/orchestrator/tools/builtin/edit-failure-context.mjs +0 -126
  623. package/src/agent/orchestrator/tools/builtin/edit-hint.mjs +0 -141
  624. package/src/agent/orchestrator/tools/builtin/edit-match-utils.mjs +0 -194
  625. package/src/agent/orchestrator/tools/builtin/edit-partial-write.mjs +0 -60
  626. package/src/agent/orchestrator/tools/builtin/edit-stale-refresh.mjs +0 -168
  627. package/src/agent/orchestrator/tools/builtin/edit-tool.mjs +0 -173
  628. package/src/agent/orchestrator/tools/builtin/edit-utf8-guard.mjs +0 -48
  629. package/src/agent/orchestrator/tools/builtin/fuzzy-match.mjs +0 -99
  630. package/src/agent/orchestrator/tools/builtin/glob-walk.mjs +0 -193
  631. package/src/agent/orchestrator/tools/builtin/list-tool.mjs +0 -597
  632. package/src/agent/orchestrator/tools/builtin/native-edit-runner.mjs +0 -110
  633. package/src/agent/orchestrator/tools/builtin/notebook-edit-tool.mjs +0 -300
  634. package/src/agent/orchestrator/tools/builtin/path-diagnostics.mjs +0 -152
  635. package/src/agent/orchestrator/tools/builtin/read-formatting.mjs +0 -118
  636. package/src/agent/orchestrator/tools/builtin/read-open.mjs +0 -190
  637. package/src/agent/orchestrator/tools/builtin/read-single-tool.mjs +0 -728
  638. package/src/agent/orchestrator/tools/builtin/read-snapshot-runtime.mjs +0 -173
  639. package/src/agent/orchestrator/tools/builtin/read-streaming.mjs +0 -602
  640. package/src/agent/orchestrator/tools/builtin/rename-tool.mjs +0 -196
  641. package/src/agent/orchestrator/tools/builtin/rg-runner.mjs +0 -422
  642. package/src/agent/orchestrator/tools/builtin/search-builders.mjs +0 -158
  643. package/src/agent/orchestrator/tools/builtin/search-tool.mjs +0 -869
  644. package/src/agent/orchestrator/tools/builtin/shell-jobs.mjs +0 -962
  645. package/src/agent/orchestrator/tools/builtin/shell-runtime.mjs +0 -223
  646. package/src/agent/orchestrator/tools/builtin/snapshot-store.mjs +0 -206
  647. package/src/agent/orchestrator/tools/builtin/write-tool.mjs +0 -401
  648. package/src/agent/orchestrator/tools/builtin.mjs +0 -503
  649. package/src/agent/orchestrator/tools/code-graph-tool-defs.mjs +0 -24
  650. package/src/agent/orchestrator/tools/code-graph.mjs +0 -4095
  651. package/src/agent/orchestrator/tools/cwd-tool.mjs +0 -298
  652. package/src/agent/orchestrator/tools/destructive-warning.mjs +0 -323
  653. package/src/agent/orchestrator/tools/edit-normalize.mjs +0 -603
  654. package/src/agent/orchestrator/tools/graph-binary-fetcher.mjs +0 -154
  655. package/src/agent/orchestrator/tools/graph-manifest.json +0 -26
  656. package/src/agent/orchestrator/tools/host-input.mjs +0 -204
  657. package/src/agent/orchestrator/tools/patch-binary-fetcher.mjs +0 -143
  658. package/src/agent/orchestrator/tools/patch-manifest.json +0 -26
  659. package/src/agent/orchestrator/tools/patch-tool-defs.mjs +0 -20
  660. package/src/agent/orchestrator/tools/patch.mjs +0 -2754
  661. package/src/agent/orchestrator/tools/progress-message.mjs +0 -118
  662. package/src/agent/orchestrator/tools/shell-command.mjs +0 -865
  663. package/src/agent/orchestrator/tools/shell-policy-imports.mjs +0 -7
  664. package/src/agent/orchestrator/tools/shell-snapshot.mjs +0 -313
  665. package/src/agent/orchestrator/workflow-store.mjs +0 -93
  666. package/src/agent/tool-defs.mjs +0 -103
  667. package/src/channels/backends/discord.mjs +0 -784
  668. package/src/channels/data/voice-runtime-manifest.json +0 -138
  669. package/src/channels/index.mjs +0 -3268
  670. package/src/channels/lib/config.mjs +0 -292
  671. package/src/channels/lib/drop-trace.mjs +0 -71
  672. package/src/channels/lib/event-pipeline.mjs +0 -81
  673. package/src/channels/lib/holidays.mjs +0 -138
  674. package/src/channels/lib/hook-pipe-server.mjs +0 -822
  675. package/src/channels/lib/output-forwarder.mjs +0 -765
  676. package/src/channels/lib/runtime-paths.mjs +0 -517
  677. package/src/channels/lib/scheduler.mjs +0 -723
  678. package/src/channels/lib/session-discovery.mjs +0 -103
  679. package/src/channels/lib/state-file.mjs +0 -68
  680. package/src/channels/lib/status-snapshot.mjs +0 -219
  681. package/src/channels/lib/tool-format.mjs +0 -140
  682. package/src/channels/lib/transcript-discovery.mjs +0 -195
  683. package/src/channels/lib/voice-runtime-fetcher.mjs +0 -734
  684. package/src/channels/lib/webhook.mjs +0 -1318
  685. package/src/channels/tool-defs.mjs +0 -170
  686. package/src/daemon/host.mjs +0 -118
  687. package/src/daemon/mcp-transport.mjs +0 -47
  688. package/src/daemon/session.mjs +0 -100
  689. package/src/daemon/thin-client.mjs +0 -71
  690. package/src/daemon/transport.mjs +0 -163
  691. package/src/memory/data/runtime-manifest.json +0 -40
  692. package/src/memory/index.mjs +0 -3332
  693. package/src/memory/lib/core-memory-store.mjs +0 -330
  694. package/src/memory/lib/embedding-provider.mjs +0 -269
  695. package/src/memory/lib/embedding-worker.mjs +0 -323
  696. package/src/memory/lib/memory-cycle1.mjs +0 -645
  697. package/src/memory/lib/memory-cycle2.mjs +0 -1284
  698. package/src/memory/lib/memory-cycle3.mjs +0 -540
  699. package/src/memory/lib/memory-embed.mjs +0 -299
  700. package/src/memory/lib/memory-ops-policy.mjs +0 -190
  701. package/src/memory/lib/memory-recall-store.mjs +0 -638
  702. package/src/memory/lib/memory.mjs +0 -412
  703. package/src/memory/lib/pg/adapter.mjs +0 -308
  704. package/src/memory/lib/pg/process.mjs +0 -360
  705. package/src/memory/lib/pg/supervisor.mjs +0 -396
  706. package/src/memory/lib/runtime-fetcher.mjs +0 -458
  707. package/src/memory/lib/trace-store.mjs +0 -728
  708. package/src/memory/tool-defs.mjs +0 -79
  709. package/src/search/index.mjs +0 -1173
  710. package/src/search/lib/backends/anthropic-oauth.mjs +0 -98
  711. package/src/search/lib/backends/exa.mjs +0 -50
  712. package/src/search/lib/backends/firecrawl.mjs +0 -61
  713. package/src/search/lib/backends/gemini-api.mjs +0 -83
  714. package/src/search/lib/backends/grok-oauth.mjs +0 -86
  715. package/src/search/lib/backends/index.mjs +0 -150
  716. package/src/search/lib/backends/openai-api.mjs +0 -144
  717. package/src/search/lib/backends/openai-oauth.mjs +0 -102
  718. package/src/search/lib/backends/openai-web-search.mjs +0 -76
  719. package/src/search/lib/backends/tavily.mjs +0 -55
  720. package/src/search/lib/backends/xai-api.mjs +0 -113
  721. package/src/search/lib/config.mjs +0 -192
  722. package/src/search/lib/provider-usage.mjs +0 -67
  723. package/src/search/lib/providers.mjs +0 -47
  724. package/src/search/lib/search-intent.mjs +0 -109
  725. package/src/search/lib/setup-handler.mjs +0 -261
  726. package/src/search/lib/web-tools.mjs +0 -1219
  727. package/src/search/tool-defs.mjs +0 -83
  728. package/src/setup/defender-exclusion.mjs +0 -183
  729. package/src/shared/atomic-file.mjs +0 -436
  730. package/src/shared/config.mjs +0 -372
  731. package/src/shared/daemon-recycle.mjs +0 -108
  732. package/src/shared/disable-claude-builtins.mjs +0 -91
  733. package/src/shared/err-text.mjs +0 -12
  734. package/src/shared/llm/cost.mjs +0 -66
  735. package/src/shared/llm/http-agent.mjs +0 -123
  736. package/src/shared/open-url.mjs +0 -62
  737. package/src/shared/plugin-paths.mjs +0 -58
  738. package/src/shared/schedules-store.mjs +0 -70
  739. package/src/shared/seed.mjs +0 -136
  740. package/src/shared/user-cwd.mjs +0 -225
  741. package/src/shared/user-data-guard.mjs +0 -244
  742. package/src/status/aggregator.mjs +0 -584
  743. package/src/status/server.mjs +0 -413
  744. package/tools.json +0 -1653
  745. /package/{defaults → src/defaults}/cycle3-review-prompt.md +0 -0
  746. /package/{defaults → src/defaults}/memory-promote-prompt.md +0 -0
  747. /package/{hooks → src/hooks}/lib/permission-rules.cjs +0 -0
  748. /package/{lib → src/lib}/config-cjs.cjs +0 -0
  749. /package/{lib → src/lib}/hook-pipe-path.cjs +0 -0
  750. /package/{lib → src/lib}/mixdog-debug.cjs +0 -0
  751. /package/{lib → src/lib}/text-utils.cjs +0 -0
  752. /package/{rules → src/rules}/bridge/42-cycle3-agent.md +0 -0
  753. /package/src/{agent → runtime/agent}/orchestrator/activity-bus.mjs +0 -0
  754. /package/src/{agent → runtime/agent}/orchestrator/providers/anthropic-betas.mjs +0 -0
  755. /package/src/{agent → runtime/agent}/orchestrator/session/abort-lookup.mjs +0 -0
  756. /package/src/{agent → runtime/agent}/orchestrator/session/cache/post-edit-marks.mjs +0 -0
  757. /package/src/{agent → runtime/agent}/orchestrator/session/cache/scoped-cache-outcome.mjs +0 -0
  758. /package/src/{agent → runtime/agent}/orchestrator/session/cache/util.mjs +0 -0
  759. /package/src/{agent → runtime/agent}/orchestrator/session/read-dedup.mjs +0 -0
  760. /package/src/{agent → runtime/agent}/orchestrator/session/save-session-worker.mjs +0 -0
  761. /package/src/{agent → runtime/agent}/orchestrator/smart-bridge/session-builder.mjs +0 -0
  762. /package/src/{agent → runtime/agent}/orchestrator/tools/bash-policy-scan.mjs +0 -0
  763. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/advisory-lock.mjs +0 -0
  764. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/atomic-write.mjs +0 -0
  765. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/binary-file.mjs +0 -0
  766. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/cache-layers.mjs +0 -0
  767. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/cwd-utils.mjs +0 -0
  768. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/device-paths.mjs +0 -0
  769. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/diagnostics-tool.mjs +0 -0
  770. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/diff-utils.mjs +0 -0
  771. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/fs-reachability.mjs +0 -0
  772. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/grep-formatting.mjs +0 -0
  773. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/hash-utils.mjs +0 -0
  774. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/list-formatting.mjs +0 -0
  775. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/open-config-tool.mjs +0 -0
  776. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/path-locks.mjs +0 -0
  777. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/path-utils.mjs +0 -0
  778. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/read-args.mjs +0 -0
  779. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/read-batch.mjs +0 -0
  780. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/read-constants.mjs +0 -0
  781. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/read-image-resize.mjs +0 -0
  782. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/read-image.mjs +0 -0
  783. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/read-lines.mjs +0 -0
  784. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/read-mode-tool.mjs +0 -0
  785. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/read-range-index.mjs +0 -0
  786. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/read-ranges.mjs +0 -0
  787. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/read-special-files.mjs +0 -0
  788. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/read-tool.mjs +0 -0
  789. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/read-windows.mjs +0 -0
  790. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/shell-analysis.mjs +0 -0
  791. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/shell-output.mjs +0 -0
  792. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/snapshot-helpers.mjs +0 -0
  793. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/snapshot-validation.mjs +0 -0
  794. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/text-stats.mjs +0 -0
  795. /package/src/{agent → runtime/agent}/orchestrator/tools/builtin/windows-roots.mjs +0 -0
  796. /package/src/{agent → runtime/agent}/orchestrator/tools/code-graph-prewarm-worker.mjs +0 -0
  797. /package/src/{agent → runtime/agent}/orchestrator/tools/env-scrub.mjs +0 -0
  798. /package/src/{agent → runtime/agent}/orchestrator/tools/mutation-content-cache.mjs +0 -0
  799. /package/src/{agent → runtime/agent}/orchestrator/tools/mutation-planner.mjs +0 -0
  800. /package/src/{agent → runtime/agent}/orchestrator/tools/next-call-utils.mjs +0 -0
  801. /package/src/{agent → runtime/agent}/orchestrator/tools/result-compression.mjs +0 -0
  802. /package/src/{agent → runtime/agent}/orchestrator/tools/shell-exec-policy.mjs +0 -0
  803. /package/src/{agent → runtime/agent}/orchestrator/tools/shell-policy-danger-target.mjs +0 -0
  804. /package/src/{agent → runtime/agent}/orchestrator/tools/shell-policy.mjs +0 -0
  805. /package/src/{channels → runtime/channels}/lib/cli-worker-host.mjs +0 -0
  806. /package/src/{channels → runtime/channels}/lib/config-lock.mjs +0 -0
  807. /package/src/{channels → runtime/channels}/lib/event-queue.mjs +0 -0
  808. /package/src/{channels → runtime/channels}/lib/executor.mjs +0 -0
  809. /package/src/{channels → runtime/channels}/lib/format.mjs +0 -0
  810. /package/src/{channels → runtime/channels}/lib/interaction-workflows.mjs +0 -0
  811. /package/src/{channels → runtime/channels}/lib/memory-client.mjs +0 -0
  812. /package/src/{channels → runtime/channels}/lib/session-control.mjs +0 -0
  813. /package/src/{channels → runtime/channels}/lib/settings.mjs +0 -0
  814. /package/src/{channels → runtime/channels}/lib/whisper-server.mjs +0 -0
  815. /package/src/{memory → runtime/memory}/lib/agent-ipc.mjs +0 -0
  816. /package/src/{memory → runtime/memory}/lib/bridge-trace-queries.mjs +0 -0
  817. /package/src/{memory → runtime/memory}/lib/llm-worker-host.mjs +0 -0
  818. /package/src/{memory → runtime/memory}/lib/memory-cycle.mjs +0 -0
  819. /package/src/{memory → runtime/memory}/lib/memory-extraction.mjs +0 -0
  820. /package/src/{memory → runtime/memory}/lib/memory-maintenance-store.mjs +0 -0
  821. /package/src/{memory → runtime/memory}/lib/memory-recall-id-patch.mjs +0 -0
  822. /package/src/{memory → runtime/memory}/lib/memory-recall-read-query.mjs +0 -0
  823. /package/src/{memory → runtime/memory}/lib/memory-recall-scope-filter.mjs +0 -0
  824. /package/src/{memory → runtime/memory}/lib/memory-retrievers.mjs +0 -0
  825. /package/src/{memory → runtime/memory}/lib/memory-score.mjs +0 -0
  826. /package/src/{memory → runtime/memory}/lib/memory-text-utils.mjs +0 -0
  827. /package/src/{memory → runtime/memory}/lib/model-profile.mjs +0 -0
  828. /package/src/{memory → runtime/memory}/lib/project-id-resolver.mjs +0 -0
  829. /package/src/{search → runtime/search}/lib/cache.mjs +0 -0
  830. /package/src/{search → runtime/search}/lib/formatter.mjs +0 -0
  831. /package/src/{search → runtime/search}/lib/state.mjs +0 -0
  832. /package/src/{shared → runtime/shared}/abort-controller.mjs +0 -0
  833. /package/src/{shared → runtime/shared}/llm/index.mjs +0 -0
  834. /package/src/{shared → runtime/shared}/llm/pid-cleanup.mjs +0 -0
  835. /package/src/{shared → runtime/shared}/llm/usage-log.mjs +0 -0
  836. /package/src/{shared → runtime/shared}/wsl.mjs +0 -0
@@ -1,1891 +0,0 @@
1
- /**
2
- * OpenAI Codex OAuth — WebSocket transport.
3
- *
4
- * Single dispatch path for the openai-oauth provider (SSE removed in
5
- * v0.6.117). Uses the `responses_websockets=2026-02-06` beta WebSocket
6
- * upgrade on chatgpt.com/backend-api/codex/responses. Per-session
7
- * connections are pooled (5 min idle TTL, up to 8 parallel sockets per
8
- * key) so subsequent tool-loop iterations can send only the incremental
9
- * `input` delta plus `previous_response_id`, skipping the full
10
- * tools/system/history prefix each turn.
11
- *
12
- * References:
13
- * - pi-mono packages/ai/src/providers/openai-codex-responses.ts
14
- * (acquireWebSocket/release, get_incremental_items delta logic).
15
- * - openai/codex codex-rs/core/src/client.rs (turn-state echo header).
16
- *
17
- * Exposes:
18
- * sendViaWebSocket({ auth, body, sendOpts, onStreamDelta, onToolCall,
19
- * onStageChange, externalSignal, poolKey, cacheKey, iteration,
20
- * useModel, traceCtx })
21
- *
22
- * The caller (openai-oauth.mjs) supplies a fully built request body and the
23
- * auth bundle; this module handles connection caching, delta framing, event
24
- * parsing, and tracing.
25
- */
26
- import WebSocket from 'ws';
27
- import { errText } from '../../../shared/err-text.mjs';
28
- import { createHash, randomBytes } from 'crypto';
29
- import {
30
- extractCachedTokens,
31
- traceBridgeFetch,
32
- traceBridgeSse,
33
- traceBridgeUsage,
34
- appendBridgeTrace,
35
- } from '../bridge-trace.mjs';
36
- import { jitterDelayMs, populateHttpStatusFromMessage } from './retry-classifier.mjs';
37
- import {
38
- PROVIDER_RETRY_MAX_ATTEMPTS,
39
- PROVIDER_WS_ACQUIRE_TIMEOUT_MS,
40
- PROVIDER_WS_FIRST_MEANINGFUL_TIMEOUT_MS,
41
- PROVIDER_WS_HANDSHAKE_TIMEOUT_MS,
42
- PROVIDER_WS_INTER_CHUNK_TIMEOUT_MS,
43
- } from '../stall-policy.mjs';
44
-
45
- const CODEX_WS_URL = 'wss://chatgpt.com/backend-api/codex/responses';
46
- const CODEX_OAUTH_ORIGINATOR = 'codex_cli_rs';
47
- const OPENAI_WS_URL = 'wss://api.openai.com/v1/responses';
48
- const XAI_WS_URL = 'wss://api.x.ai/v1/responses';
49
- const WS_IDLE_MS = 5 * 60_000;
50
- const WS_HANDSHAKE_TIMEOUT_MS = PROVIDER_WS_HANDSHAKE_TIMEOUT_MS;
51
- const WS_ACQUIRE_TIMEOUT_MS = PROVIDER_WS_ACQUIRE_TIMEOUT_MS;
52
- // Pre-stream watchdog uses the shared provider deadline so it fails before
53
- // the 5-minute session slow warning.
54
- const WS_FIRST_MEANINGFUL_MS = PROVIDER_WS_FIRST_MEANINGFUL_TIMEOUT_MS;
55
- // Pre-`response.created` deadline. Once the socket is open and the
56
- // response.create frame is sent, a healthy server emits response.created
57
- // within seconds. If it stalls past this short bound the socket has wedged
58
- // post-upgrade with zero server events — treat it as a fast, retryable
59
- // first-byte timeout rather than waiting the longer first-meaningful window.
60
- // Only this short window is shortened; the post-`response.created`
61
- // inter-chunk / reasoning span keeps the longer deadlines below.
62
- const WS_PRE_RESPONSE_CREATED_MS = (() => {
63
- const raw = process.env.MIXDOG_PROVIDER_WS_PRE_RESPONSE_CREATED_TIMEOUT_MS;
64
- const n = Number(raw);
65
- if (Number.isFinite(n) && n > 0) return Math.min(Math.max(n, 1_000), 120_000);
66
- return 10_000;
67
- })();
68
- // Inter-chunk inactivity after first meaningful output.
69
- const WS_INTER_CHUNK_MS = PROVIDER_WS_INTER_CHUNK_TIMEOUT_MS;
70
- const MIDSTREAM_WS_TRANSIENT_RETRY_LIMIT = 2;
71
- const MIDSTREAM_DEFAULT_RETRY_LIMIT = 1;
72
- const MIDSTREAM_BACKOFF_MS = [250, 1000];
73
-
74
- // Handshake retry policy. The `ws` library surfaces a bare
75
- // `Opening handshake has timed out` Error after handshakeTimeout; transient
76
- // network blips (DNS, reset, 5xx) similarly produce single-shot failures that
77
- // waste the caller's turn when they'd succeed on retry. We wrap the acquire
78
- // step with bounded exponential backoff. Permanent auth/quota (4xx) must NOT
79
- // retry because a second attempt will hit the same deterministic server
80
- // decision and just double the user-visible latency.
81
- // Aligned to the cross-provider default (retry-classifier DEFAULT_MAX_ATTEMPTS=5,
82
- // anthropic-oauth MAX_ATTEMPTS=5, withRetry-using providers all default to 5).
83
- // Previously 3 — bumped for parity so every provider exhausts the same number
84
- // of transient-5xx attempts before surfacing failure to the caller.
85
- const HANDSHAKE_MAX_ATTEMPTS = PROVIDER_RETRY_MAX_ATTEMPTS;
86
- const HANDSHAKE_BACKOFF_BASE_MS = 500;
87
- const HANDSHAKE_BACKOFF_CAP_MS = 5000;
88
- // WS socket pool buckets are keyed by `poolKey` (the per-call sessionId)
89
- // to isolate parallel bridge invocations — each gets its own socket so
90
- // a second caller cannot grab a sibling's mid-turn entry (Codex would
91
- // otherwise reject the new response.create with "No tool output found
92
- // for function call ..."). The Codex handshake `session_id` header/URL
93
- // uses `cacheKey` — a provider-scoped unified key (e.g. 'mixdog-codex')
94
- // built in manager.mjs via providerCacheKey(). All orchestrator-internal
95
- // dispatches targeting this provider share the same cacheKey, so the
96
- // server-side prompt-cache shard is shared across every role/source.
97
- // Codex dedupes cache by handshake session_id, not by
98
- // body.prompt_cache_key alone (measured 2026-04-19 after the v0.6.151
99
- // regression).
100
- const MAX_POOLED_SOCKETS_PER_KEY = 8;
101
-
102
- // poolKey -> Entry[]
103
- // Entry: { socket, busy, idleTimer, lastResponseId, lastRequestSansInput,
104
- // lastInputLen, turnState, closing, ephemeral }
105
- const _wsPool = new Map();
106
-
107
- function _getPoolArr(poolKey) {
108
- if (!poolKey) return null;
109
- let arr = _wsPool.get(poolKey);
110
- if (!arr) {
111
- arr = [];
112
- _wsPool.set(poolKey, arr);
113
- }
114
- return arr;
115
- }
116
-
117
- function _removeFromPool(poolKey, entry) {
118
- if (!poolKey) return;
119
- const arr = _wsPool.get(poolKey);
120
- if (!arr) return;
121
- const idx = arr.indexOf(entry);
122
- if (idx >= 0) arr.splice(idx, 1);
123
- if (arr.length === 0) _wsPool.delete(poolKey);
124
- }
125
-
126
- function _scheduleIdleClose(poolKey, entry) {
127
- if (!entry) return;
128
- if (entry.idleTimer) clearTimeout(entry.idleTimer);
129
- entry.idleTimer = setTimeout(() => {
130
- if (entry.busy) return;
131
- try { entry.socket.close(1000, 'idle_timeout'); } catch {}
132
- _removeFromPool(poolKey, entry);
133
- }, WS_IDLE_MS);
134
- try { entry.idleTimer.unref?.(); } catch {}
135
- }
136
-
137
- function _clearIdle(entry) {
138
- if (entry?.idleTimer) {
139
- clearTimeout(entry.idleTimer);
140
- entry.idleTimer = null;
141
- }
142
- }
143
-
144
- function _isOpen(entry) {
145
- return entry?.socket?.readyState === WebSocket.OPEN;
146
- }
147
-
148
- // Awaited frame send. Asserts the socket is OPEN and resolves only after
149
- // the underlying transport reports the buffered write succeeded (or fails)
150
- // via the WebSocket send callback. Raw `socket.send(JSON.stringify(...))`
151
- // is fire-and-forget — a wedged or half-closed socket silently queues the
152
- // payload and the caller assumes it landed, then later times out waiting
153
- // for a server event that will never arrive. Tag any failure with
154
- // `wsSendFailed=true` so _classifyMidstreamError routes the next attempt
155
- // through a fresh socket.
156
- function _sendFrame(entry, frame) {
157
- return new Promise((resolve, reject) => {
158
- const socket = entry?.socket;
159
- if (!socket || socket.readyState !== WebSocket.OPEN) {
160
- const err = new Error(`WS send: socket not OPEN (readyState=${socket?.readyState ?? 'n/a'})`);
161
- err.wsSendFailed = true;
162
- reject(err);
163
- return;
164
- }
165
- let payload;
166
- try { payload = JSON.stringify(frame); }
167
- catch (e) {
168
- const err = e instanceof Error ? e : new Error(String(e));
169
- err.wsSendFailed = true;
170
- reject(err);
171
- return;
172
- }
173
- try {
174
- // Do NOT await the send callback: on a wedged-but-OPEN socket the
175
- // ws write callback may never fire, which would hang this Promise
176
- // before _streamResponse arms its first-byte watchdog. Fire and
177
- // resolve immediately; transport failures surface via the socket
178
- // 'error'/'close' handlers and the first-byte watchdog.
179
- socket.send(payload, () => {});
180
- resolve();
181
- } catch (e) {
182
- const err = e instanceof Error ? e : new Error(String(e));
183
- err.wsSendFailed = true;
184
- reject(err);
185
- }
186
- });
187
- }
188
-
189
- function _buildHandshakeHeaders({ auth, sessionToken, turnState, cacheKey }) {
190
- // xAI WS: do NOT pin x-grok-conv-id. Measured parallel runs show that
191
- // forcing a routing shard via that header alternates cold caches across
192
- // parallel workers; the automatic prompt-prefix cache holds up better
193
- // when each handshake is unpinned. Reference: vercel/ai xai provider.
194
- const headers = auth.type === 'xai'
195
- ? {
196
- 'Authorization': `Bearer ${auth.apiKey}`,
197
- }
198
- : auth.type === 'openai-direct'
199
- ? {
200
- 'Authorization': `Bearer ${auth.apiKey}`,
201
- 'OpenAI-Beta': 'responses_websockets=2026-02-06',
202
- }
203
- : {
204
- 'Authorization': `Bearer ${auth.access_token}`,
205
- 'chatgpt-account-id': auth.account_id || '',
206
- 'originator': CODEX_OAUTH_ORIGINATOR,
207
- 'OpenAI-Beta': 'responses_websockets=2026-02-06',
208
- };
209
- if (sessionToken) {
210
- const sid = String(sessionToken);
211
- headers['session_id'] = sid;
212
- }
213
- // x-client-request-id must be a per-request value so server-side request
214
- // traces stay distinguishable across retries / reconnects sharing the same
215
- // session_id. Reusing sessionToken (= cacheKey) collapsed every request
216
- // for the same conversation onto one trace bucket.
217
- headers['x-client-request-id'] = randomBytes(16).toString('hex');
218
- if (turnState) headers['x-codex-turn-state'] = turnState;
219
- return headers;
220
- }
221
-
222
- // handshake session_id is the conversation slot Codex uses for in-memory
223
- // prefix state. All orchestrator-internal dispatches for this provider share
224
- // the same cacheKey (built in manager.mjs via providerCacheKey()), so they
225
- // share the server-side prefix-cache shard across roles/sources.
226
- function _mintSessionToken(cacheKey, auth) {
227
- // xAI's public WebSocket endpoint uses the open connection plus
228
- // response ids for continuation; unlike Codex, it does not need the
229
- // Codex-specific session_id handshake shard.
230
- if (auth?.type === 'xai') return null;
231
- return cacheKey || 'mixdog-default';
232
- }
233
-
234
- function _openSocket({ auth, sessionToken, turnState, externalSignal, cacheKey }) {
235
- const headers = _buildHandshakeHeaders({ auth, sessionToken, turnState, cacheKey });
236
- const baseUrl = auth.type === 'xai'
237
- ? XAI_WS_URL
238
- : auth.type === 'openai-direct'
239
- ? OPENAI_WS_URL
240
- : CODEX_WS_URL;
241
- const _wsOpenStart = Date.now();
242
- if (process.env.MIXDOG_DEBUG_BRIDGE) {
243
- process.stderr.write(`[bridge-trace] ws-open-start url=${baseUrl} tokenHash=${createHash('sha256').update(String(sessionToken)).digest('hex').slice(0, 8)} ts=${_wsOpenStart}\n`);
244
- }
245
- const url = baseUrl + (sessionToken ? `?session_id=${encodeURIComponent(String(sessionToken))}` : '');
246
- return new Promise((resolve, reject) => {
247
- let settled = false;
248
- let abortListener = null;
249
- let acquireTimer = null;
250
- const settle = (ok, val) => {
251
- if (settled) return;
252
- settled = true;
253
- if (acquireTimer) {
254
- clearTimeout(acquireTimer);
255
- acquireTimer = null;
256
- }
257
- if (abortListener && externalSignal) {
258
- try { externalSignal.removeEventListener('abort', abortListener); } catch {}
259
- }
260
- (ok ? resolve : reject)(val);
261
- };
262
- const socket = new WebSocket(url, { headers, handshakeTimeout: WS_HANDSHAKE_TIMEOUT_MS });
263
- acquireTimer = setTimeout(() => {
264
- if (settled) return;
265
- if (process.env.MIXDOG_DEBUG_BRIDGE) {
266
- process.stderr.write(`[bridge-trace] ws-open-fail kind=acquire_timeout timeoutMs=${WS_ACQUIRE_TIMEOUT_MS} elapsed=${Date.now() - _wsOpenStart}ms\n`);
267
- }
268
- try { socket.terminate(); } catch {}
269
- settle(false, Object.assign(
270
- new Error(`${_wsErrLabel(auth?.type === 'xai' ? 'xai' : auth?.type === 'openai-direct' ? 'openai-direct' : 'openai-oauth')} acquire timed out before open (${WS_ACQUIRE_TIMEOUT_MS}ms)`),
271
- { code: 'EWSACQUIRETIMEOUT', acquireTimeoutMs: WS_ACQUIRE_TIMEOUT_MS },
272
- ));
273
- }, WS_ACQUIRE_TIMEOUT_MS);
274
- try { acquireTimer.unref?.(); } catch {}
275
- const capturedHeaders = { turnState: null };
276
- socket.once('upgrade', (res) => {
277
- try {
278
- const ts = res?.headers?.['x-codex-turn-state'];
279
- if (typeof ts === 'string' && ts.length) capturedHeaders.turnState = ts;
280
- } catch {}
281
- });
282
- socket.once('open', () => {
283
- if (process.env.MIXDOG_DEBUG_BRIDGE) {
284
- process.stderr.write(`[bridge-trace] ws-open-ok elapsed=${Date.now() - _wsOpenStart}ms\n`);
285
- }
286
- settle(true, { socket, turnState: capturedHeaders.turnState });
287
- });
288
- socket.once('error', (err) => {
289
- if (process.env.MIXDOG_DEBUG_BRIDGE) {
290
- process.stderr.write(`[bridge-trace] ws-open-fail kind=error msg=${String(err?.message || err).slice(0, 120)} elapsed=${Date.now() - _wsOpenStart}ms\n`);
291
- }
292
- try { socket.terminate(); } catch {}
293
- settle(false, err instanceof Error ? err : Object.assign(new Error(errText(err) || 'openai-oauth WS error'), { wsErrorEvent: true, original: err }));
294
- });
295
- socket.once('close', (code, reason) => {
296
- // Half-open handshake: the peer closed before 'open'/'error' fired
297
- // (TCP RST / TLS edge). Without this the connect Promise never
298
- // settles and only the 600s outer watchdog can break the stall
299
- // (observed stage=requesting 601s hang). Open-path closes are
300
- // no-ops here because settle() has already flipped `settled`.
301
- if (settled) return;
302
- try { socket.terminate(); } catch {}
303
- settle(false, Object.assign(
304
- new Error(`${_wsErrLabel(auth?.type === 'xai' ? 'xai' : auth?.type === 'openai-direct' ? 'openai-direct' : 'openai-oauth')} handshake closed before open (code=${code})`),
305
- { wsCloseCode: code, wsCloseReason: (reason && reason.toString) ? reason.toString('utf-8') : '' }));
306
- });
307
- socket.once('unexpected-response', (_req, res) => {
308
- if (settled) return;
309
- const status = res?.statusCode || 0;
310
- let body = '';
311
- res.on('data', c => { if (body.length < 2048) body += c.toString('utf-8'); });
312
- res.on('end', () => {
313
- if (process.env.MIXDOG_DEBUG_BRIDGE) {
314
- process.stderr.write(`[bridge-trace] ws-open-fail kind=http status=${status} body=${body.slice(0, 120)} elapsed=${Date.now() - _wsOpenStart}ms\n`);
315
- }
316
- try { socket.terminate(); } catch {}
317
- settle(false, Object.assign(new Error(`${_wsErrLabel(auth?.type === 'xai' ? 'xai' : auth?.type === 'openai-direct' ? 'openai-direct' : 'openai-oauth')} handshake ${status}: ${body.slice(0, 200)}`), { httpStatus: status, httpBody: body }));
318
- });
319
- });
320
- if (externalSignal) {
321
- const onAbort = () => {
322
- try { socket.terminate(); } catch {}
323
- const reason = externalSignal.reason;
324
- settle(false, reason instanceof Error ? reason : new Error(`${_wsErrLabel(auth?.type === 'xai' ? 'xai' : auth?.type === 'openai-direct' ? 'openai-direct' : 'openai-oauth')} handshake aborted`));
325
- };
326
- if (externalSignal.aborted) { onAbort(); return; }
327
- abortListener = onAbort;
328
- externalSignal.addEventListener('abort', onAbort, { once: true });
329
- }
330
- });
331
- }
332
-
333
- async function acquireWebSocket({ auth, poolKey, cacheKey, forceFresh, externalSignal }) {
334
- const _acqStart = Date.now();
335
- if (process.env.MIXDOG_DEBUG_BRIDGE) {
336
- process.stderr.write(`[bridge-trace] acquire-start poolKey=${poolKey} cacheKey=${cacheKey} forceFresh=${forceFresh} externalAborted=${!!externalSignal?.aborted} ts=${_acqStart}\n`);
337
- }
338
- if (externalSignal?.aborted) {
339
- const reason = externalSignal.reason;
340
- throw reason instanceof Error ? reason : new Error('Codex WS acquire aborted');
341
- }
342
- if (poolKey && !forceFresh) {
343
- const arr = _wsPool.get(poolKey) || [];
344
- // Prune dead entries first.
345
- for (let i = arr.length - 1; i >= 0; i--) {
346
- if (!_isOpen(arr[i]) || arr[i].closing) {
347
- _clearIdle(arr[i]);
348
- arr.splice(i, 1);
349
- }
350
- }
351
- if (arr.length === 0) _wsPool.delete(poolKey);
352
- // Reuse any idle open entry (cache-warm path).
353
- const idle = arr.find(e => !e.busy);
354
- if (idle) {
355
- _clearIdle(idle);
356
- idle.busy = true;
357
- // Defensive: pre-existing pooled entries created before the
358
- // prefix-hash field was introduced may not have it set. Normalize
359
- // to null so the first delta check reads a deterministic value
360
- // (and falls back to full-create instead of silently passing).
361
- if (idle.lastInputPrefixHash === undefined) idle.lastInputPrefixHash = null;
362
- if (process.env.MIXDOG_DEBUG_BRIDGE) {
363
- process.stderr.write(`[bridge-trace] acquire-reuse poolKey=${poolKey} openSockets=${arr.length} elapsed=${Date.now() - _acqStart}ms\n`);
364
- }
365
- return { entry: idle, reused: true };
366
- }
367
- // All entries busy and bucket at cap: fall through to ephemeral socket.
368
- if (arr.length >= MAX_POOLED_SOCKETS_PER_KEY) {
369
- if (process.env.MIXDOG_DEBUG_BRIDGE) {
370
- process.stderr.write(`[bridge-trace] acquire-ephemeral cacheKey=${cacheKey} reason=cap elapsed=${Date.now() - _acqStart}ms\n`);
371
- }
372
- const ephSessionToken = _mintSessionToken(cacheKey, auth);
373
- const { socket, turnState } = await _openSocket({ auth, sessionToken: ephSessionToken, turnState: null, externalSignal, cacheKey });
374
- // Drain-complete fence: same invariant as the normal acquire path —
375
- // if drain fired during the await, do NOT push an ephemeral entry
376
- // back into the pool.
377
- if (_drainComplete) {
378
- try { socket.close(1000, 'drain-complete'); } catch {}
379
- throw new Error('WS pool drained — process exiting');
380
- }
381
- const entry = {
382
- socket,
383
- busy: true,
384
- idleTimer: null,
385
- lastResponseId: null,
386
- lastRequestSansInput: null,
387
- lastInputLen: 0,
388
- lastInputPrefixHash: null,
389
- turnState: turnState || null,
390
- closing: false,
391
- ephemeral: true,
392
- sessionToken: ephSessionToken,
393
- };
394
- socket.on('close', () => { entry.closing = true; });
395
- return { entry, reused: false };
396
- }
397
- }
398
- // Parallel sockets must not inherit sibling turnState or the Codex server
399
- // treats the new request as a continuation of another in-flight turn and
400
- // returns "No tool output found for function call …". turnState only
401
- // propagates within a single entry across its own iterations.
402
- const sessionToken = _mintSessionToken(cacheKey, auth);
403
- if (process.env.MIXDOG_DEBUG_BRIDGE) {
404
- process.stderr.write(`[bridge-trace] acquire-new tokenHash=${createHash('sha256').update(String(sessionToken)).digest('hex').slice(0, 8)} elapsed=${Date.now() - _acqStart}ms\n`);
405
- }
406
- const { socket, turnState } = await _openSocket({ auth, sessionToken, turnState: null, externalSignal, cacheKey });
407
- const entry = {
408
- socket,
409
- busy: true,
410
- idleTimer: null,
411
- lastResponseId: null,
412
- lastRequestSansInput: null,
413
- lastInputLen: 0,
414
- lastInputPrefixHash: null,
415
- turnState: turnState || null,
416
- closing: false,
417
- ephemeral: false,
418
- sessionToken,
419
- };
420
- if (poolKey && !forceFresh) _getPoolArr(poolKey).push(entry);
421
- socket.on('close', () => {
422
- entry.closing = true;
423
- _removeFromPool(poolKey, entry);
424
- });
425
- return { entry, reused: false };
426
- }
427
-
428
- function releaseWebSocket({ entry, poolKey, keep }) {
429
- if (!entry) return;
430
- entry.busy = false;
431
- if (!keep || !_isOpen(entry) || !poolKey || entry.ephemeral) {
432
- try { entry.socket.close(1000, keep ? 'no_session' : 'release_no_keep'); } catch {}
433
- _removeFromPool(poolKey, entry);
434
- return;
435
- }
436
- _scheduleIdleClose(poolKey, entry);
437
- }
438
-
439
- // Port of pi-mono get_incremental_items: if the cached request (sans input)
440
- // matches the current one and the current input starts with the cached input,
441
- // return only the tail. Otherwise return the full input (fresh turn).
442
- function _sansInput(body) {
443
- const { input: _ignored, ...rest } = body;
444
- return rest;
445
- }
446
-
447
- function _stableStringify(obj) {
448
- // Shallow stable-ish: JSON.stringify with sorted top-level keys. Nested
449
- // arrays (tools, include) are order-sensitive and reflect intent, so we
450
- // do not sort them.
451
- if (obj === null || typeof obj !== 'object' || Array.isArray(obj)) return JSON.stringify(obj);
452
- const keys = Object.keys(obj).sort();
453
- const parts = [];
454
- for (const k of keys) parts.push(JSON.stringify(k) + ':' + _stableStringify(obj[k]));
455
- return '{' + parts.join(',') + '}';
456
- }
457
-
458
- function _computeDelta({ entry, body }) {
459
- if (!entry || !entry.lastRequestSansInput || !entry.lastResponseId) {
460
- return { mode: 'full', frame: { type: 'response.create', ...body } };
461
- }
462
- const curSans = _stableStringify(_sansInput(body));
463
- if (curSans !== entry.lastRequestSansInput) {
464
- return { mode: 'full', frame: { type: 'response.create', ...body } };
465
- }
466
- const prevLen = entry.lastInputLen | 0;
467
- const curInput = Array.isArray(body.input) ? body.input : [];
468
- if (curInput.length < prevLen) {
469
- return { mode: 'full', frame: { type: 'response.create', ...body } };
470
- }
471
- // Prefix integrity guard: the cached state on `entry` only stays valid
472
- // if the current request's first `prevLen` items are byte-identical to
473
- // the prior full input. If anything in the prefix mutated (a tool result
474
- // got rewritten, a reasoning item dropped, a system note rotated) the
475
- // server would mis-anchor the delta. Compare a sha256 of the serialized
476
- // prefix against the hash captured on the previous success. Mismatch →
477
- // fall back to a full create for this turn only; the entry itself stays
478
- // in the pool so the next turn can retry the delta path after
479
- // sendViaWebSocket refreshes the cache state.
480
- // Without a hash baseline prefix integrity is unprovable — force full
481
- // so sendViaWebSocket can seed the hash on success.
482
- if (entry.lastInputPrefixHash == null) {
483
- return { mode: 'full', frame: { type: 'response.create', ...body } };
484
- }
485
- const curPrefixHash = createHash('sha256')
486
- .update(JSON.stringify(curInput.slice(0, prevLen)))
487
- .digest('hex');
488
- if (curPrefixHash !== entry.lastInputPrefixHash) {
489
- return { mode: 'full', frame: { type: 'response.create', ...body } };
490
- }
491
- const tail = curInput.slice(prevLen);
492
- return {
493
- mode: 'delta',
494
- frame: {
495
- ...body,
496
- type: 'response.create',
497
- previous_response_id: entry.lastResponseId,
498
- input: tail,
499
- },
500
- };
501
- }
502
-
503
- function _estimateFrameTokens(frame) {
504
- try {
505
- const s = JSON.stringify(frame);
506
- return Math.ceil(s.length / 4);
507
- } catch { return 0; }
508
- }
509
-
510
- function _usageNum(value) {
511
- const n = Number(value || 0);
512
- return Number.isFinite(n) ? n : 0;
513
- }
514
-
515
- function _combineUsageWithWarmup(actual, warmup) {
516
- if (!warmup) return actual;
517
- if (!actual) return warmup;
518
- const actualRaw = actual.raw || {};
519
- const warmupRaw = warmup.raw || {};
520
- const actualTicks = _usageNum(actualRaw.cost_in_usd_ticks);
521
- const warmupTicks = _usageNum(warmupRaw.cost_in_usd_ticks);
522
- return {
523
- ...actual,
524
- inputTokens: _usageNum(actual.inputTokens) + _usageNum(warmup.inputTokens),
525
- outputTokens: _usageNum(actual.outputTokens) + _usageNum(warmup.outputTokens),
526
- cachedTokens: _usageNum(actual.cachedTokens) + _usageNum(warmup.cachedTokens),
527
- promptTokens: _usageNum(actual.promptTokens) + _usageNum(warmup.promptTokens),
528
- warmupInputTokens: _usageNum(warmup.inputTokens),
529
- warmupCachedTokens: _usageNum(warmup.cachedTokens),
530
- warmupOutputTokens: _usageNum(warmup.outputTokens),
531
- raw: {
532
- ...actualRaw,
533
- warmup_usage: warmupRaw,
534
- ...(actualTicks || warmupTicks ? { cost_in_usd_ticks: actualTicks + warmupTicks } : {}),
535
- },
536
- };
537
- }
538
-
539
- function _parseEvent(raw) {
540
- try { return JSON.parse(raw); } catch { return null; }
541
- }
542
-
543
- function _httpStatusFromWsClose(code, reason) {
544
- const n = Number(code || 0);
545
- const r = String(reason || '').toLowerCase();
546
- if (n === 4401
547
- || /\b(?:unauthorized|unauthorised|authentication|auth(?:enticated?)?|not authenticated|token expired|access token)\b/.test(r)) {
548
- return 401;
549
- }
550
- if (n === 4403 || /\b(?:forbidden|policy|permission denied)\b/.test(r)) return 403;
551
- if (n === 4429 || /\b(?:rate limit|quota)\b/.test(r)) return 429;
552
- return 0;
553
- }
554
-
555
- function _wsErrLabel(p) {
556
- if (p === 'xai') return 'xAI WS';
557
- if (p === 'openai-direct' || p === 'openai') return 'OpenAI WS';
558
- return 'Codex WS';
559
- }
560
- async function _streamResponse({ entry, externalSignal, onStreamDelta, onToolCall, state, logSuppressedReasoningDeltas = true, traceProvider = 'openai-oauth' }) {
561
- const errLabel = _wsErrLabel(traceProvider);
562
- const socket = entry.socket;
563
- const _streamingStart = Date.now();
564
- let _firstDeltaEmitted = false;
565
- let content = '';
566
- let model = '';
567
- let responseId = '';
568
- let responseServiceTier = '';
569
- const toolCalls = [];
570
- const webSearchCalls = [];
571
- const webSearchCallKeys = new Set();
572
- const citations = [];
573
- const citationKeys = new Set();
574
- const pendingCalls = new Map();
575
- // Reasoning items collected from response.output_item.done (or salvaged
576
- // from response.completed.response.output). The request still includes
577
- // `reasoning.encrypted_content` so the server keeps emitting the blobs,
578
- // but explicit input-side replay is INTENTIONALLY OMITTED in
579
- // convertMessagesToResponsesInput (openai-oauth.mjs:233-238) — Codex
580
- // rejects the same `rs_*` id twice in one handshake session_id with a
581
- // "Duplicate item" error. Server-side conversation state already carries
582
- // the prefix forward across the WS_IDLE_MS window. The collected
583
- // reasoningItems below are surfaced for trace/debugging only; they do
584
- // not feed back into the next request body.
585
- const reasoningItems = [];
586
- let reasoningTextDeltaCount = 0;
587
- let reasoningSummaryTextDeltaCount = 0;
588
- let reasoningOtherDeltaCount = 0;
589
- let reasoningDeltaLogEmitted = false;
590
- const pushReasoningItem = (item) => {
591
- if (!item || item.type !== 'reasoning') return;
592
- if (!item.encrypted_content) return;
593
- reasoningItems.push({
594
- id: item.id || '',
595
- encrypted_content: item.encrypted_content,
596
- summary: Array.isArray(item.summary) ? item.summary : [],
597
- });
598
- };
599
- const pushCitation = (raw, fallbackTitle = '') => {
600
- const url = raw?.url || raw?.uri || raw?.href || '';
601
- if (!url || citationKeys.has(url)) return;
602
- citationKeys.add(url);
603
- citations.push({
604
- title: raw?.title || fallbackTitle || '',
605
- url,
606
- snippet: raw?.snippet || raw?.text || raw?.description || '',
607
- source: 'openai-oauth',
608
- });
609
- };
610
- const pushOutputTextAnnotations = (contentPart) => {
611
- const annotations = Array.isArray(contentPart?.annotations) ? contentPart.annotations : [];
612
- for (const annotation of annotations) pushCitation(annotation);
613
- };
614
- const pushWebSearchCall = (item) => {
615
- if (!item || item.type !== 'web_search_call') return;
616
- let key = item.id || '';
617
- if (!key) {
618
- try { key = JSON.stringify(item.action || item); } catch { key = `${webSearchCalls.length}`; }
619
- }
620
- if (webSearchCallKeys.has(key)) return;
621
- webSearchCallKeys.add(key);
622
- webSearchCalls.push({
623
- id: item.id || '',
624
- status: item.status || '',
625
- action: item.action || null,
626
- });
627
- const action = item.action || {};
628
- if (action.url) pushCitation({ url: action.url, title: action.query || '' });
629
- if (Array.isArray(action.urls)) {
630
- for (const url of action.urls) pushCitation({ url, title: action.query || '' });
631
- }
632
- };
633
- const logReasoningDeltaSuppression = () => {
634
- if (!logSuppressedReasoningDeltas) return;
635
- const total = reasoningTextDeltaCount + reasoningSummaryTextDeltaCount + reasoningOtherDeltaCount;
636
- if (reasoningDeltaLogEmitted || total === 0) return;
637
- reasoningDeltaLogEmitted = true;
638
- process.stderr.write(`[openai-oauth-ws] suppressed reasoning text deltas from user content count=${total} text=${reasoningTextDeltaCount} summary=${reasoningSummaryTextDeltaCount} other=${reasoningOtherDeltaCount}\n`);
639
- };
640
- let usage;
641
- let done = false;
642
- let terminalError = null;
643
- // Mid-stream retry classifier needs to distinguish "stream died before we
644
- // even saw response.created" from "stream died after we had a partial
645
- // response but before completion". Mutate the shared state object so the
646
- // caller can inspect flags on the error path without us having to attach
647
- // them manually at every reject site.
648
- const midState = state || {};
649
- midState.sawResponseCreated = midState.sawResponseCreated || false;
650
- midState.sawCompleted = midState.sawCompleted || false;
651
- midState.wsCloseCode = null;
652
- midState.responseFailedPayload = null;
653
- let idleTimer = null;
654
- let keepaliveTimer = null;
655
- let abortHandler = null;
656
- let messageHandler = null;
657
- let closeHandler = null;
658
- let errorHandler = null;
659
-
660
- return new Promise((resolve, reject) => {
661
- // Pre-stream watchdog: the timer fires if the server never sends a
662
- // first event (response.created) within WS_PRE_RESPONSE_CREATED_MS
663
- // after our last frame. The socket is open and the response.create
664
- // frame was sent, but no server event has come back — a wedged
665
- // post-upgrade socket. Healthy servers ack within seconds, so this
666
- // window is intentionally short (~25s). Once response.created (or
667
- // any other meaningful event) arrives, the timer is cancelled and
668
- // the longer inter-chunk inactivity watchdog takes over — silent
669
- // gaps mid-reasoning (Codex spending 50s+ producing reasoning
670
- // tokens) are normal and should not abort the turn.
671
- const armPreStreamWatchdog = () => {
672
- if (idleTimer) clearTimeout(idleTimer);
673
- idleTimer = setTimeout(() => {
674
- if (process.env.MIXDOG_DEBUG_BRIDGE) {
675
- process.stderr.write(`[bridge-trace] ws-timeout kind=first-byte afterMs=${WS_PRE_RESPONSE_CREATED_MS}\n`);
676
- }
677
- const err = new Error(`WS stream: no first server event within ${WS_PRE_RESPONSE_CREATED_MS}ms`);
678
- // Tag the close code so _classifyMidstreamError sees a 4000
679
- // (our local pre-stream watchdog code) and routes through
680
- // the post-upgrade-no-first-event retryable bucket.
681
- err.wsCloseCode = 4000;
682
- // Tag the error object itself (not just midState): the warmup
683
- // path streams under a separate warmupState and rethrows on
684
- // timeout BEFORE it can copy flags to the outer midState, so the
685
- // outer catch's _classifyMidstreamError would otherwise see
686
- // sawResponseCreated=false + close 4000 and hit the pre-created
687
- // deny gate. err.firstByteTimeout makes both paths retryable.
688
- err.firstByteTimeout = true;
689
- midState.firstByteTimeout = true;
690
- terminalError = err;
691
- try { socket.close(4000, 'first_byte_timeout'); } catch {}
692
- // socket.close() may not settle a half-open WS (closeHandler never
693
- // fires) — reject directly so the turn retries instead of hanging
694
- // until the 600s watchdog. finish() is idempotent (Promise settles
695
- // once; cleanup is null-safe).
696
- finish();
697
- }, WS_PRE_RESPONSE_CREATED_MS);
698
- };
699
- let interChunkTimer = null;
700
- let firstMeaningfulSeen = false;
701
- const resetInterChunk = () => {
702
- if (interChunkTimer) clearTimeout(interChunkTimer);
703
- interChunkTimer = setTimeout(() => {
704
- if (process.env.MIXDOG_DEBUG_BRIDGE) {
705
- process.stderr.write(`[bridge-trace] ws-timeout kind=inter-chunk afterMs=${WS_INTER_CHUNK_MS}\n`);
706
- }
707
- terminalError = new Error(`WS stream: inter-chunk inactivity for ${WS_INTER_CHUNK_MS}ms`);
708
- try { socket.close(4000, 'inter_chunk_timeout'); } catch {}
709
- // Same half-open guard as the pre-stream watchdog: reject directly
710
- // so a stuck socket.close() cannot leave the Promise pending.
711
- finish();
712
- }, WS_INTER_CHUNK_MS);
713
- };
714
- // Called on every event that carries real output tokens or tool progress.
715
- // Disarms the pre-stream watchdog on first occurrence; thereafter resets
716
- // the rolling inter-chunk inactivity timer.
717
- const onMeaningfulOutput = () => {
718
- if (!firstMeaningfulSeen) {
719
- firstMeaningfulSeen = true;
720
- if (idleTimer) { clearTimeout(idleTimer); idleTimer = null; }
721
- }
722
- resetInterChunk();
723
- };
724
- // resetIdle kept for compat; metadata frames no longer disarm pre-stream watchdog.
725
- const resetIdle = () => { /* noop — only onMeaningfulOutput() disarms */ };
726
- const cleanup = () => {
727
- if (idleTimer) clearTimeout(idleTimer);
728
- if (interChunkTimer) { clearTimeout(interChunkTimer); interChunkTimer = null; }
729
- if (keepaliveTimer) { clearInterval(keepaliveTimer); keepaliveTimer = null; }
730
- if (messageHandler) socket.off('message', messageHandler);
731
- if (closeHandler) socket.off('close', closeHandler);
732
- if (errorHandler) socket.off('error', errorHandler);
733
- if (abortHandler && externalSignal) externalSignal.removeEventListener('abort', abortHandler);
734
- };
735
- const finish = () => {
736
- logReasoningDeltaSuppression();
737
- cleanup();
738
- if (terminalError) { reject(terminalError); return; }
739
- resolve({
740
- content,
741
- model,
742
- reasoningItems: reasoningItems.length ? reasoningItems : undefined,
743
- toolCalls: toolCalls.length ? toolCalls : undefined,
744
- citations: citations.length ? citations : undefined,
745
- webSearchCalls: webSearchCalls.length ? webSearchCalls : undefined,
746
- usage,
747
- responseId: responseId || undefined,
748
- serviceTier: responseServiceTier || undefined,
749
- });
750
- };
751
-
752
- messageHandler = (data) => {
753
- resetIdle();
754
- // Do NOT call onStreamDelta for every frame — metadata/keepalive frames
755
- // must not reset bridge-stall-watchdog's lastStreamDeltaAt. Only
756
- // meaningful output (text delta / tool call) updates that timestamp.
757
- const text = typeof data === 'string' ? data : data.toString('utf-8');
758
- const event = _parseEvent(text);
759
- if (!event) return;
760
- if (event.error) {
761
- const err = new Error(event.error.message || 'Responses WS error');
762
- try {
763
- err.payload = event.error;
764
- populateHttpStatusFromMessage(err);
765
- } catch {}
766
- terminalError = err;
767
- finish();
768
- return;
769
- }
770
- if (typeof event.type !== 'string') return;
771
- switch (event.type) {
772
- case 'response.created':
773
- midState.sawResponseCreated = true;
774
- if (event.response?.model) model = event.response.model;
775
- if (event.response?.id) responseId = event.response.id;
776
- // Server ack — cancel the short pre-`response.created`
777
- // watchdog and arm the longer inter-chunk inactivity
778
- // timer for the remainder of the stream. Reasoning
779
- // silences post-ack are normal and must not trip the
780
- // 25s first-byte deadline.
781
- onMeaningfulOutput();
782
- break;
783
- case 'response.output_text.delta':
784
- content += event.delta || '';
785
- try {
786
- if (!_firstDeltaEmitted) {
787
- _firstDeltaEmitted = true;
788
- if (process.env.MIXDOG_DEBUG_BRIDGE) {
789
- process.stderr.write(`[bridge-trace] ws-first-delta sinceStreaming=${Date.now() - _streamingStart}ms\n`);
790
- }
791
- }
792
- onStreamDelta?.();
793
- } catch {}
794
- onMeaningfulOutput();
795
- break;
796
- case 'response.reasoning_text.delta':
797
- case 'response.reasoning_summary_text.delta':
798
- if (event.type === 'response.reasoning_text.delta') reasoningTextDeltaCount += 1;
799
- else reasoningSummaryTextDeltaCount += 1;
800
- // Reasoning text is live model progress — refresh
801
- // lastStreamDeltaAt so stream-watchdog does not flag a
802
- // long reasoning span as a stall. It also counts as
803
- // liveness for the local pre-stream / inter-chunk
804
- // watchdogs: a long reasoning span without any
805
- // output_text delta would otherwise trip the
806
- // first-meaningful timer and abort an otherwise healthy
807
- // stream. Reasoning is still suppressed from user
808
- // content (no `content +=` here) — only the watchdog
809
- // timers are reset.
810
- try { onStreamDelta?.(); } catch {}
811
- onMeaningfulOutput();
812
- break;
813
- case 'response.output_item.added':
814
- if (event.item?.type === 'function_call') {
815
- pendingCalls.set(event.item.id || '', {
816
- name: event.item.name || '',
817
- callId: event.item.call_id || '',
818
- });
819
- }
820
- break;
821
- case 'response.function_call_arguments.delta':
822
- try { onStreamDelta?.(); } catch {}
823
- onMeaningfulOutput();
824
- break;
825
- case 'response.function_call_arguments.done': {
826
- const itemId = event.item_id || '';
827
- const pending = pendingCalls.get(itemId);
828
- let args = {};
829
- try { args = JSON.parse(event.arguments || '{}'); } catch {}
830
- if (pending?.callId && pending?.name) {
831
- const call = { id: pending.callId, name: pending.name, arguments: args };
832
- toolCalls.push(call);
833
- midState.emittedToolCall = true;
834
- try { onToolCall?.(call); } catch {}
835
- } else {
836
- // Synthesizing a `tc_${Date.now()}` callId here would
837
- // make the next turn fail to match the model's
838
- // function_call_output reference. Defer instead and
839
- // salvage call_id/name from the final
840
- // response.completed.output bundle below. If salvage
841
- // also fails we fail the stream explicitly — masking
842
- // the gap with a synthetic id just shifts the failure
843
- // one turn later under a confusing "No tool output
844
- // found for function call" error.
845
- toolCalls.push({
846
- id: pending?.callId || '',
847
- name: pending?.name || '',
848
- arguments: args,
849
- _pendingItemId: itemId,
850
- _deferred: true,
851
- });
852
- }
853
- try { onStreamDelta?.(); } catch {}
854
- break;
855
- }
856
- case 'response.output_item.done':
857
- // function_call / output_text already captured via their
858
- // dedicated streaming events. The one shape we still need
859
- // here is `reasoning` — carries encrypted_content that
860
- // must be replayed on the next input to keep the Codex
861
- // server-side prompt cache prefix warm.
862
- if (event.item?.type === 'reasoning') pushReasoningItem(event.item);
863
- if (event.item?.type === 'web_search_call') pushWebSearchCall(event.item);
864
- break;
865
- case 'response.completed': {
866
- const completedServiceTier = event.response?.service_tier || event.response?.serviceTier || '';
867
- if (completedServiceTier) responseServiceTier = String(completedServiceTier);
868
- if (event.response?.usage) {
869
- const u = event.response.usage;
870
- const rawUsage = responseServiceTier
871
- ? { ...u, service_tier: responseServiceTier }
872
- : u;
873
- usage = {
874
- inputTokens: u.input_tokens || 0,
875
- outputTokens: u.output_tokens || 0,
876
- cachedTokens: extractCachedTokens(u),
877
- // OpenAI Codex reports input_tokens as the total
878
- // prompt volume (cached portion is a subset, not
879
- // additive). Alias into the cross-provider
880
- // `promptTokens` field so downstream loggers have
881
- // uniform semantics.
882
- promptTokens: u.input_tokens || 0,
883
- raw: rawUsage,
884
- };
885
- }
886
- if (!model && event.response?.model) model = event.response.model;
887
- if (!responseId && event.response?.id) responseId = event.response.id;
888
- if (event.response?.output) {
889
- for (const item of event.response.output) {
890
- if (!content && item.type === 'message') {
891
- for (const c of item.content || []) {
892
- if (c.type === 'output_text') {
893
- content += c.text || '';
894
- pushOutputTextAnnotations(c);
895
- }
896
- }
897
- }
898
- if (item.type === 'message') {
899
- for (const c of item.content || []) {
900
- if (c.type === 'output_text') pushOutputTextAnnotations(c);
901
- }
902
- }
903
- if (item.type === 'web_search_call') pushWebSearchCall(item);
904
- // Salvage path: some streams emit reasoning only
905
- // inside the final response.completed.output
906
- // bundle (no per-item .done event). Dedup by id.
907
- if (item.type === 'reasoning'
908
- && !reasoningItems.some(r => r.id === item.id)) {
909
- pushReasoningItem(item);
910
- }
911
- // Salvage path for function_call: when
912
- // arguments.done fired before (or without) a
913
- // matching output_item.added, the deferred tool
914
- // call placeholder has empty id/name. The
915
- // completed.output bundle carries the canonical
916
- // call_id/name; fill them in and emit onToolCall.
917
- if (item.type === 'function_call') {
918
- const tc = toolCalls.find(
919
- (t) => t._deferred && t._pendingItemId === (item.id || ''),
920
- );
921
- if (tc) {
922
- if (!tc.id && item.call_id) tc.id = item.call_id;
923
- if (!tc.name && item.name) tc.name = item.name;
924
- if (tc.id && tc.name) {
925
- delete tc._deferred;
926
- delete tc._pendingItemId;
927
- midState.emittedToolCall = true;
928
- try { onToolCall?.(tc); } catch {}
929
- }
930
- }
931
- }
932
- }
933
- }
934
- // Salvage validation. Any deferred call still missing
935
- // id/name would propagate to the next turn as a
936
- // function_call_output the server can't anchor. Fail the
937
- // stream now so the caller sees a deterministic error
938
- // instead of a cryptic mismatch one turn later.
939
- const unresolved = toolCalls.find((t) => t._deferred);
940
- if (unresolved) {
941
- terminalError = new Error(
942
- `${errLabel} function_call salvage failed: missing call_id/name for item_id=${unresolved._pendingItemId || '?'}`,
943
- );
944
- finish();
945
- break;
946
- }
947
- midState.sawCompleted = true;
948
- done = true;
949
- finish();
950
- break;
951
- }
952
- case 'response.done': {
953
- // response.done is the terminal frame for some Codex
954
- // streams that never emit a separate response.completed.
955
- // Route through the same completed/failed/incomplete
956
- // normalization based on event.response.status so a
957
- // server-side abort (incomplete / failed) does not slip
958
- // through as success. status === 'completed' falls
959
- // through to the success path with sawCompleted set;
960
- // anything else is converted into a terminal error.
961
- const status = event.response?.status || '';
962
- if (status === 'failed') {
963
- midState.responseFailedPayload = event;
964
- const msg = event.response?.error?.message
965
- || event.error?.message
966
- || event.message
967
- || 'response.done failed';
968
- terminalError = Object.assign(
969
- new Error(`${errLabel} response.done failed: ${msg}`),
970
- { responseFailed: event },
971
- );
972
- populateHttpStatusFromMessage(terminalError, msg);
973
- done = true;
974
- finish();
975
- break;
976
- }
977
- if (status === 'incomplete') {
978
- const reasonObj = event.response?.incomplete_details
979
- || event.incomplete_details
980
- || event.response?.status_details
981
- || null;
982
- const reasonStr = reasonObj?.reason
983
- || event.response?.status
984
- || 'incomplete';
985
- terminalError = Object.assign(
986
- new Error(`${errLabel} response.done incomplete: ${reasonStr}`),
987
- { responseIncomplete: event, incompleteReason: reasonStr },
988
- );
989
- done = true;
990
- finish();
991
- break;
992
- }
993
- if (status && status !== 'completed') {
994
- terminalError = Object.assign(
995
- new Error(`${errLabel} response.done unexpected status: ${status}`),
996
- { responseDoneStatus: status },
997
- );
998
- done = true;
999
- finish();
1000
- break;
1001
- }
1002
- midState.sawCompleted = true;
1003
- done = true;
1004
- finish();
1005
- break;
1006
- }
1007
- case 'response.incomplete': {
1008
- // response.incomplete is a server-side abort (max_output_tokens,
1009
- // content filter, length, etc.). Surfacing it as success silently
1010
- // truncates the turn; convert to a terminal error so the caller
1011
- // can decide whether to retry / surface to user.
1012
- const reasonObj = event.response?.incomplete_details
1013
- || event.incomplete_details
1014
- || event.response?.status_details
1015
- || null;
1016
- const reasonStr = reasonObj?.reason
1017
- || event.response?.status
1018
- || 'incomplete';
1019
- terminalError = Object.assign(
1020
- new Error(`${errLabel} response.incomplete: ${reasonStr}`),
1021
- { responseIncomplete: event, incompleteReason: reasonStr },
1022
- );
1023
- finish();
1024
- break;
1025
- }
1026
- case 'response.failed': {
1027
- // Stash the payload so the mid-stream classifier can sniff
1028
- // network_error / stream_disconnected without re-parsing.
1029
- midState.responseFailedPayload = event;
1030
- const msg = event.response?.error?.message
1031
- || event.error?.message
1032
- || event.message
1033
- || 'response.failed';
1034
- terminalError = Object.assign(new Error(`${errLabel} response.failed: ${msg}`), {
1035
- responseFailed: event,
1036
- });
1037
- // Sniff the server message for transient/auth/permanent
1038
- // hints so the handshake / mid-stream retry classifiers
1039
- // can route by httpStatus. Without this, server-side
1040
- // events like "Our servers are currently overloaded"
1041
- // surfaced as unclassified errors and skipped the
1042
- // 5xx retry bucket entirely.
1043
- populateHttpStatusFromMessage(terminalError, msg);
1044
- finish();
1045
- break;
1046
- }
1047
- case 'error': {
1048
- const errMsg = String(event.message || event.error?.message || 'unknown');
1049
- terminalError = new Error(`${errLabel} error: ${errMsg}`);
1050
- populateHttpStatusFromMessage(terminalError, errMsg);
1051
- finish();
1052
- break;
1053
- }
1054
- default:
1055
- // Catch any other reasoning-delta variants (e.g.
1056
- // `response.reasoning.<sub>.delta`) so they are counted
1057
- // and suppressed, never reaching the user content buffer.
1058
- if (typeof event.type === 'string'
1059
- && event.type.startsWith('response.reasoning')
1060
- && event.type.endsWith('.delta')) {
1061
- reasoningOtherDeltaCount += 1;
1062
- }
1063
- // Trace-only events (response.in_progress, etc.)
1064
- break;
1065
- }
1066
- };
1067
- closeHandler = (code, reason) => {
1068
- if (done) return;
1069
- midState.wsCloseCode = code;
1070
- if (!terminalError) {
1071
- const r = reason?.toString?.('utf-8') || '';
1072
- const httpStatus = _httpStatusFromWsClose(code, r);
1073
- terminalError = Object.assign(
1074
- new Error(`Codex WS closed before response.completed (code=${code}${r ? `, reason=${r}` : ''})`),
1075
- { wsCloseCode: code, wsCloseReason: r, ...(httpStatus ? { httpStatus } : {}) },
1076
- );
1077
- } else if (terminalError && !terminalError.wsCloseCode) {
1078
- try { terminalError.wsCloseCode = code; } catch {}
1079
- try { terminalError.httpStatus = terminalError.httpStatus || _httpStatusFromWsClose(code, reason?.toString?.('utf-8') || ''); } catch {}
1080
- }
1081
- finish();
1082
- };
1083
- errorHandler = (err) => {
1084
- if (done) return;
1085
- const wrapped = err instanceof Error ? err : new Error(String(err));
1086
- if (terminalError) {
1087
- // Preserve the first terminalError; chain the later socket
1088
- // error in via `cause` (or `suppressed` if cause already set)
1089
- // so diagnostics keep the original failure visible.
1090
- try {
1091
- if (!terminalError.cause) terminalError.cause = wrapped;
1092
- else {
1093
- const list = Array.isArray(terminalError.suppressed)
1094
- ? terminalError.suppressed
1095
- : [];
1096
- list.push(wrapped);
1097
- terminalError.suppressed = list;
1098
- }
1099
- } catch {}
1100
- } else {
1101
- terminalError = wrapped;
1102
- }
1103
- try { socket.close(4001, 'stream_error'); } catch {}
1104
- finish();
1105
- };
1106
- if (externalSignal) {
1107
- abortHandler = () => {
1108
- if (done) return;
1109
- const reason = externalSignal.reason;
1110
- terminalError = reason instanceof Error ? reason : new Error('Codex WS aborted by session close');
1111
- // Tag: was this a user/caller abort, or a watchdog abort?
1112
- // Mid-stream retry must skip user aborts but may retry watchdog
1113
- // aborts. The caller-owned AbortController surfaces through
1114
- // externalSignal; bridge-stall-watchdog signals via a reason
1115
- // object whose name === 'BridgeStallAbortError'. stream-watchdog
1116
- // uses StreamStalledAbortError. Anything else → treat as user.
1117
- const reasonName = reason?.name || '';
1118
- if (reasonName === 'BridgeStallAbortError'
1119
- || reasonName === 'StreamStalledAbortError') {
1120
- midState.watchdogAbort = reasonName;
1121
- } else {
1122
- midState.userAbort = true;
1123
- }
1124
- try { socket.close(4002, 'aborted'); } catch {}
1125
- finish();
1126
- };
1127
- if (externalSignal.aborted) { abortHandler(); return; }
1128
- externalSignal.addEventListener('abort', abortHandler, { once: true });
1129
- }
1130
- socket.on('message', messageHandler);
1131
- socket.on('close', closeHandler);
1132
- socket.on('error', errorHandler);
1133
- armPreStreamWatchdog();
1134
- // Periodic client-side WS ping while the stream is active. Codex's
1135
- // server closes with 1011 "keepalive ping timeout" when it thinks the
1136
- // peer is silent during long reasoning windows where no data frames
1137
- // flow. Sending a ping every 18s from our side keeps the socket warm.
1138
- // The interval is unref'd so it never holds the event loop open, and
1139
- // cleanup() clears it on every terminal path (completed / close /
1140
- // error / abort / mid-stream retry teardown).
1141
- keepaliveTimer = setInterval(() => {
1142
- try {
1143
- if (socket.readyState !== WebSocket.OPEN) return;
1144
- socket.ping();
1145
- } catch {}
1146
- }, 18_000);
1147
- try { keepaliveTimer.unref?.(); } catch {}
1148
- });
1149
- }
1150
-
1151
- /**
1152
- * Classify a handshake error for retry eligibility.
1153
- *
1154
- * Default-deny: anything we don't recognize as transient returns null (treat
1155
- * as permanent). Permanent buckets (401/403/404/429) also return null — the
1156
- * server has made a deterministic decision that a retry can't change.
1157
- *
1158
- * Returns one of:
1159
- * 'timeout' — `ws` handshakeTimeout fired
1160
- * 'reset' — ECONNRESET / socket hang up
1161
- * 'dns' — EAI_AGAIN / ENOTFOUND / EAI_NODATA
1162
- * 'refused' — ECONNREFUSED
1163
- * 'network' — ENETUNREACH / EHOSTUNREACH / EPIPE
1164
- * 'acquire_timeout' — hard client-side open/acquire deadline fired
1165
- * 'http_5xx' (with specific status e.g. 'http_503') — server overload
1166
- * null — not retryable
1167
- */
1168
- export function _classifyHandshakeError(err) {
1169
- if (!err) return null;
1170
- const code = err.code || '';
1171
- const msg = String(err.message || '');
1172
- const status = Number(err.httpStatus || 0);
1173
-
1174
- // Permanent HTTP (auth / quota / not-found) short-circuits.
1175
- if (status === 401 || status === 403 || status === 404 || status === 429) {
1176
- return null;
1177
- }
1178
- // 5xx transient.
1179
- if (status >= 500 && status < 600) {
1180
- return `http_${status}`;
1181
- }
1182
-
1183
- // Node errno codes.
1184
- if (code === 'ECONNRESET') return 'reset';
1185
- if (code === 'EAI_AGAIN' || code === 'ENOTFOUND' || code === 'EAI_NODATA') return 'dns';
1186
- if (code === 'ECONNREFUSED') return 'refused';
1187
- if (code === 'ETIMEDOUT' || code === 'ESOCKETTIMEDOUT') return 'timeout';
1188
- if (code === 'EWSACQUIRETIMEOUT') return 'acquire_timeout';
1189
- if (code === 'ENETUNREACH' || code === 'EHOSTUNREACH' || code === 'EPIPE') return 'network';
1190
-
1191
- // `ws` library's handshake-timeout path: thrown as a bare Error.
1192
- if (/opening handshake has timed out/i.test(msg)) return 'timeout';
1193
- if (/socket hang up/i.test(msg)) return 'reset';
1194
-
1195
- return null;
1196
- }
1197
-
1198
- /**
1199
- * Classify a mid-stream error for bounded retry eligibility.
1200
- *
1201
- * Only fires AFTER `response.created` is observed and BEFORE
1202
- * `response.completed`. The window is narrow on purpose: retrying a handshake
1203
- * or a pre-create connect failure is owned by _acquireWithRetry; retrying
1204
- * after completion would replay a finished turn.
1205
- *
1206
- * Retry buckets:
1207
- * 'bridge_stall' — BridgeStallAbortError from bridge-stall-watchdog
1208
- * 'stream_stalled' — StreamStalledAbortError from stream-watchdog
1209
- * 'ws_1006' — abnormal close (connection lost)
1210
- * 'ws_1011' — server unexpected condition
1211
- * 'ws_1012' — service restart
1212
- * 'ws_4000' — our armPreStreamWatchdog close with idle_timeout
1213
- * 'ws_1000' — server-side normal close fired after response.created
1214
- * but before response.completed (truncated stream)
1215
- * 'first_byte_timeout' — post-upgrade-no-first-event: socket opened, our
1216
- * response.create frame sent, but the server never
1217
- * emitted response.created within the short
1218
- * pre-stream deadline. Fast-fail retryable.
1219
- * 'response_failed_network' — response.failed with network_error
1220
- * 'response_failed_disconnected' — response.failed with stream_disconnected
1221
- *
1222
- * Deny buckets (return null):
1223
- * - externalSignal aborted by user (state.userAbort)
1224
- * - state.sawCompleted === true (already done)
1225
- * - state.sawResponseCreated === false (still pre-stream; handshake retry
1226
- * owns that window) — EXCEPT for WS close 1011/1012, which can fire
1227
- * after the 101 upgrade but before the first response.created event,
1228
- * AND the pre-`response.created` first-byte timeout
1229
- * (state.firstByteTimeout), which is permitted a bounded retry here
1230
- * - HTTP 401 / 403 / 429 surfaced on the error
1231
- * - state.attemptIndex has reached the classifier-specific retry budget
1232
- */
1233
- export function _classifyMidstreamError(err, state) {
1234
- if (!state) return null;
1235
- const attemptIndex = state.attemptIndex | 0;
1236
- // Already completed (shouldn't throw, but defensive).
1237
- if (state.sawCompleted) return null;
1238
- // Any tool call already surfaced to the caller — retrying would
1239
- // normally duplicate the side effect. EXCEPTION: ws_1000 truncation
1240
- // (server-side normal close after response.created, before completion)
1241
- // leaves the caller with an orphaned tool_use that the next turn cannot
1242
- // pair to a tool_result, which the provider rejects with a hard 400.
1243
- // The duplicate-side-effect risk is preferable to deterministic worker
1244
- // death, especially for detached bridges that re-dispatch idempotently.
1245
- if (state.emittedToolCall) {
1246
- const _cc = Number(err?.wsCloseCode || state.wsCloseCode || 0);
1247
- if (!(_cc === 1000 && state.sawResponseCreated && !state.sawCompleted)) return null;
1248
- }
1249
- // Post-upgrade-no-first-event: the socket opened, our response.create
1250
- // frame was sent, but the server never emitted a single event before
1251
- // the short pre-`response.created` watchdog fired. The handshake retry
1252
- // layer only sees pre-upgrade failures and the legacy pre-stream gate
1253
- // below would deny this case (sawResponseCreated === false). Tag it
1254
- // here as a fast retryable bucket so the worker reconnects within
1255
- // seconds instead of stalling for the full first-meaningful window.
1256
- if (state.firstByteTimeout || err?.firstByteTimeout) {
1257
- return _allowMidstreamRetry('first_byte_timeout', attemptIndex);
1258
- }
1259
- // _sendFrame failure (socket not OPEN, send callback errored, JSON
1260
- // serialize threw). Always retryable: caller will forceFresh next
1261
- // attempt so the wedged socket is dropped.
1262
- if (err?.wsSendFailed || state.wsSendFailed) {
1263
- return _allowMidstreamRetry('ws_send_failed', attemptIndex);
1264
- }
1265
- // Pre-stream failures normally belong to the handshake retry layer. BUT
1266
- // WS close 1011 / 1012 can fire after the 101 upgrade but BEFORE the
1267
- // first response.created event when the server's keepalive times out or
1268
- // the service restarts. Neither the handshake retry layer (it only sees
1269
- // pre-upgrade failures) nor the existing mid-stream gate covers this
1270
- // window, so permit bounded retry here for those two codes only.
1271
- if (!state.sawResponseCreated) {
1272
- const closeCode = Number(err?.wsCloseCode || state.wsCloseCode || 0);
1273
- if (closeCode !== 1011 && closeCode !== 1012) return null;
1274
- }
1275
- // User/caller abort — never retry.
1276
- if (state.userAbort) return null;
1277
-
1278
- if (!err) return null;
1279
- const status = Number(err?.httpStatus || 0);
1280
- if (status === 401 || status === 403 || status === 429) return null;
1281
- // Transient 5xx surfaced via populateHttpStatusFromMessage (case 'error'
1282
- // and case 'response.failed' branches sniff server-supplied text like
1283
- // "Our servers are currently overloaded" and assign httpStatus=503).
1284
- // Allow one bounded mid-stream retry on the same budget as the WS close-
1285
- // code buckets above so server-side overload no longer leaks straight
1286
- // to the caller without a single retry attempt.
1287
- if (status >= 500 && status < 600) {
1288
- return _allowMidstreamRetry(`http_${status}`, attemptIndex);
1289
- }
1290
-
1291
- const name = err?.name || '';
1292
- if (name === 'BridgeStallAbortError') return _allowMidstreamRetry('bridge_stall', attemptIndex);
1293
- if (name === 'StreamStalledAbortError') return _allowMidstreamRetry('stream_stalled', attemptIndex);
1294
-
1295
- // Watchdog abort surfaced via externalSignal handler → err is the reason
1296
- // itself. state.watchdogAbort captures the class name when the error
1297
- // shape was preserved but the name was stripped by some wrapper.
1298
- if (state.watchdogAbort === 'BridgeStallAbortError') return _allowMidstreamRetry('bridge_stall', attemptIndex);
1299
- if (state.watchdogAbort === 'StreamStalledAbortError') return _allowMidstreamRetry('stream_stalled', attemptIndex);
1300
-
1301
- // WS close codes: prefer the decorated property, fall back to state.
1302
- const closeCode = Number(err?.wsCloseCode || state.wsCloseCode || 0);
1303
- if (closeCode === 1006) return _allowMidstreamRetry('ws_1006', attemptIndex);
1304
- if (closeCode === 1011) return _allowMidstreamRetry('ws_1011', attemptIndex);
1305
- if (closeCode === 1012) return _allowMidstreamRetry('ws_1012', attemptIndex);
1306
- // Private 4xxx codes from a server/proxy are auth/policy/application closes;
1307
- // never treat them as transient. 4000 is our local pre-stream watchdog code.
1308
- if (closeCode >= 4000 && closeCode < 5000 && closeCode !== 4000) return null;
1309
- if (closeCode === 4000) return _allowMidstreamRetry('ws_4000', attemptIndex);
1310
- // Server-side normal close (1000) AFTER response.created but BEFORE
1311
- // response.completed = truncated stream; legitimate transient. The
1312
- // pre-stream gate above already rejects 1000 before sawResponseCreated
1313
- // (handshake retry layer owns that window).
1314
- if (closeCode === 1000 && state.sawResponseCreated && !state.sawCompleted) return _allowMidstreamRetry('ws_1000', attemptIndex);
1315
-
1316
- // response.failed payload mentioning network_error / stream_disconnected.
1317
- // xAI's gRPC backend periodically rotates auth context (server-side TTL)
1318
- // and surfaces "Auth context expired" as a response.failed event. The
1319
- // attemptIndex > 0 path in sendViaWebSocket forces a fresh WS handshake,
1320
- // which re-authenticates — so a single bounded retry recovers the turn
1321
- // instead of letting the worker die mid-session.
1322
- const failed = err?.responseFailed || state.responseFailedPayload;
1323
- if (failed) {
1324
- try {
1325
- const blob = JSON.stringify(failed).toLowerCase();
1326
- if (blob.includes('stream_disconnected')) return _allowMidstreamRetry('response_failed_disconnected', attemptIndex);
1327
- if (blob.includes('network_error')) return _allowMidstreamRetry('response_failed_network', attemptIndex);
1328
- if (blob.includes('auth context expired')) return _allowMidstreamRetry('response_failed_auth_expired', attemptIndex);
1329
- } catch {}
1330
- }
1331
-
1332
- // Unknown → default-deny (don't risk a second full-cost turn for an error
1333
- // class we haven't proven is transient).
1334
- return null;
1335
- }
1336
-
1337
- function _midstreamRetryLimit(classifier) {
1338
- return classifier === 'ws_1006' || classifier === 'ws_1011'
1339
- ? MIDSTREAM_WS_TRANSIENT_RETRY_LIMIT
1340
- : MIDSTREAM_DEFAULT_RETRY_LIMIT;
1341
- }
1342
-
1343
- function _allowMidstreamRetry(classifier, attemptIndex) {
1344
- return attemptIndex < _midstreamRetryLimit(classifier) ? classifier : null;
1345
- }
1346
-
1347
- function _midstreamBackoffFor(retryNumber) {
1348
- return MIDSTREAM_BACKOFF_MS[Math.min(Math.max(retryNumber, 1), MIDSTREAM_BACKOFF_MS.length) - 1];
1349
- }
1350
-
1351
- function _backoffFor(attempt) {
1352
- // attempt is 1-based. retry 1 → 500, retry 2 → 1000, retry 3 → 2000 … capped.
1353
- const raw = HANDSHAKE_BACKOFF_BASE_MS * (1 << (attempt - 1));
1354
- return jitterDelayMs(Math.min(raw, HANDSHAKE_BACKOFF_CAP_MS));
1355
- }
1356
-
1357
- const _defaultSleep = (ms) => new Promise((r) => setTimeout(r, ms));
1358
-
1359
- async function _sleepWithAbort(ms, externalSignal, sleepFn = _defaultSleep) {
1360
- if (!ms) return;
1361
- if (!externalSignal) {
1362
- await sleepFn(ms);
1363
- return;
1364
- }
1365
- await new Promise((resolve, reject) => {
1366
- const t = setTimeout(() => {
1367
- externalSignal.removeEventListener('abort', onAbort);
1368
- resolve();
1369
- }, ms);
1370
- const onAbort = () => {
1371
- clearTimeout(t);
1372
- const reason = externalSignal.reason;
1373
- reject(reason instanceof Error ? reason : new Error('Codex WS retry backoff aborted'));
1374
- };
1375
- if (externalSignal.aborted) { onAbort(); return; }
1376
- externalSignal.addEventListener('abort', onAbort, { once: true });
1377
- });
1378
- }
1379
-
1380
- /**
1381
- * Run `_acquire({auth, poolKey, cacheKey})` with bounded exponential-backoff
1382
- * retry on transient handshake failures. The injection seams (`_acquire`,
1383
- * `_sleepFn`, `onRetry`) let unit tests drive the state machine without
1384
- * opening real sockets.
1385
- *
1386
- * On exhaustion the thrown error is tagged with:
1387
- * err.attempts — 1..HANDSHAKE_MAX_ATTEMPTS
1388
- * err.retryClassifier — final classifier string, or null for permanent
1389
- */
1390
- export async function _acquireWithRetry({
1391
- auth,
1392
- poolKey,
1393
- cacheKey,
1394
- forceFresh,
1395
- onRetry,
1396
- externalSignal,
1397
- _acquire = acquireWebSocket,
1398
- _sleepFn = _defaultSleep,
1399
- } = {}) {
1400
- let lastErr = null;
1401
- let lastClassifier = null;
1402
- for (let attempt = 1; attempt <= HANDSHAKE_MAX_ATTEMPTS; attempt++) {
1403
- if (externalSignal?.aborted) {
1404
- const reason = externalSignal.reason;
1405
- throw reason instanceof Error ? reason : new Error('Codex WS acquire aborted');
1406
- }
1407
- try {
1408
- if (attempt > 1) {
1409
- if (process.env.MIXDOG_DEBUG_BRIDGE) {
1410
- process.stderr.write(`[bridge-trace] ws-handshake-attempt n=${attempt}\n`);
1411
- }
1412
- }
1413
- return await _acquire({ auth, poolKey, cacheKey, forceFresh, externalSignal });
1414
- } catch (err) {
1415
- lastErr = err;
1416
- const classifier = _classifyHandshakeError(err);
1417
- lastClassifier = classifier;
1418
- // Permanent (or unknown → default-deny): stop immediately.
1419
- if (!classifier) {
1420
- if (err && typeof err === 'object') {
1421
- try { err.attempts = attempt; } catch {}
1422
- try { err.retryClassifier = null; } catch {}
1423
- }
1424
- throw err;
1425
- }
1426
- // Transient but exhausted: surface with tagging.
1427
- if (attempt >= HANDSHAKE_MAX_ATTEMPTS) {
1428
- if (err && typeof err === 'object') {
1429
- try { err.attempts = attempt; } catch {}
1430
- try { err.retryClassifier = classifier; } catch {}
1431
- }
1432
- try {
1433
- process.stderr.write(
1434
- `[openai-oauth-ws] handshake failed after ${attempt}/${HANDSHAKE_MAX_ATTEMPTS} attempts: ${err?.message || err}\n`,
1435
- );
1436
- } catch {}
1437
- throw err;
1438
- }
1439
- // Schedule backoff and emit progress.
1440
- const backoff = _backoffFor(attempt);
1441
- try {
1442
- process.stderr.write(
1443
- `[openai-oauth-ws] worker retry ${attempt}/${HANDSHAKE_MAX_ATTEMPTS} (transient: ${classifier}, backoff ${backoff}ms)\n`,
1444
- );
1445
- } catch {}
1446
- try {
1447
- onRetry?.({
1448
- attempt,
1449
- max: HANDSHAKE_MAX_ATTEMPTS,
1450
- classifier,
1451
- backoffMs: backoff,
1452
- error: err,
1453
- });
1454
- } catch {}
1455
- // Sleep is abort-aware: an abort during backoff rejects immediately
1456
- // instead of burning the remaining wait.
1457
- if (externalSignal) {
1458
- await new Promise((resolve, reject) => {
1459
- const t = setTimeout(() => {
1460
- externalSignal.removeEventListener('abort', onAbort);
1461
- resolve();
1462
- }, backoff);
1463
- const onAbort = () => {
1464
- clearTimeout(t);
1465
- const reason = externalSignal.reason;
1466
- reject(reason instanceof Error ? reason : new Error('Codex WS acquire aborted'));
1467
- };
1468
- if (externalSignal.aborted) { onAbort(); return; }
1469
- externalSignal.addEventListener('abort', onAbort, { once: true });
1470
- });
1471
- } else {
1472
- await _sleepFn(backoff);
1473
- }
1474
- }
1475
- }
1476
- // Unreachable — the loop either returns or throws above — but keep the
1477
- // typing honest.
1478
- if (lastErr && typeof lastErr === 'object') {
1479
- try { lastErr.attempts = HANDSHAKE_MAX_ATTEMPTS; } catch {}
1480
- try { lastErr.retryClassifier = lastClassifier; } catch {}
1481
- }
1482
- throw lastErr || new Error('acquireWithRetry: unreachable');
1483
- }
1484
-
1485
- /**
1486
- * Dispatch one tool-loop iteration over a per-session cached WebSocket.
1487
- * Returns the same shape as the SSE path: { content, model, toolCalls, usage }.
1488
- */
1489
- export async function sendViaWebSocket({
1490
- auth,
1491
- body,
1492
- sendOpts,
1493
- onStreamDelta,
1494
- onToolCall,
1495
- onStageChange,
1496
- externalSignal,
1497
- poolKey,
1498
- cacheKey,
1499
- iteration,
1500
- useModel,
1501
- displayModel,
1502
- forceFresh = false,
1503
- includeResponseId = false,
1504
- traceProvider = 'openai-oauth',
1505
- logSuppressedReasoningDeltas = true,
1506
- warmupBody = null,
1507
- // Test seams (undefined in production). Let the unit test drive the
1508
- // retry state machine without opening real sockets or touching the
1509
- // handshake-retry layer.
1510
- _acquireWithRetryFn = _acquireWithRetry,
1511
- _streamFn = _streamResponse,
1512
- _sendFrameFn = _sendFrame,
1513
- _sleepFn = _defaultSleep,
1514
- }) {
1515
- // Bounded mid-stream retry: if an attempt's stream dies after
1516
- // response.created but before response.completed from a transient cause
1517
- // (watchdog abort / ws 1006/1011/1012/4000 / response.failed with network
1518
- // error), tear down the socket and reissue the full request from scratch
1519
- // with a classifier-specific budget. ws_1006/ws_1011 get two retries with
1520
- // 250ms/1s backoff; other legacy transient buckets keep the prior one retry.
1521
- // No delta resume — content restarts, which is the accepted tradeoff for
1522
- // reviewer/worker flows that need the complete answer.
1523
- // Retries are layered ABOVE the handshake retry loop (_acquireWithRetry
1524
- // owns connect-level transience); the two never interleave because we
1525
- // force a brand-new acquire for the retry attempt.
1526
- const MAX_MIDSTREAM_RETRIES = MIDSTREAM_WS_TRANSIENT_RETRY_LIMIT;
1527
- let firstAttemptError = null;
1528
- let firstAttemptClassifier = null;
1529
- // Server-side xAI conversation anchor preserved across mid-stream
1530
- // retries. xAI keys its conversation by previous_response_id alone
1531
- // (sessionToken is null for xAI in _mintSessionToken); a forceFresh
1532
- // socket on retry would otherwise drop prev_id and cold-start a new
1533
- // server-side conversation, evicting every prefix the prior attempts
1534
- // warmed. Codex / openai-direct anchor by per-socket session_id, where
1535
- // this carry-forward would not help and is therefore gated to xAI.
1536
- let carryForwardCache = null;
1537
- const emittedProgress = [];
1538
-
1539
- for (let attemptIndex = 0; attemptIndex <= MAX_MIDSTREAM_RETRIES; attemptIndex++) {
1540
- const handshakeStart = Date.now();
1541
- let acquired;
1542
- let handshakeRetries = 0;
1543
- const handshakeRetryClassifiers = [];
1544
- try { onStageChange?.('requesting'); } catch {}
1545
- try {
1546
- acquired = await _acquireWithRetryFn({
1547
- auth,
1548
- poolKey,
1549
- cacheKey,
1550
- // Retry attempt must not reuse a pooled socket — the prior
1551
- // one is either torn down or in an unknown state.
1552
- forceFresh: forceFresh || attemptIndex > 0,
1553
- externalSignal,
1554
- onRetry: (info) => {
1555
- handshakeRetries += 1;
1556
- if (info?.classifier) handshakeRetryClassifiers.push(info.classifier);
1557
- },
1558
- });
1559
- } catch (err) {
1560
- const classifier = err?.retryClassifier || (err?.code === 'EWSACQUIRETIMEOUT' ? 'acquire_timeout' : null);
1561
- const classifiers = [...handshakeRetryClassifiers];
1562
- if (classifier && !classifiers.includes(classifier)) classifiers.push(classifier);
1563
- if (err?.httpStatus != null || classifier || handshakeRetries > 0 || classifiers.length > 0) {
1564
- traceBridgeFetch({
1565
- sessionId: poolKey,
1566
- headersMs: Date.now() - handshakeStart,
1567
- httpStatus: Number(err?.httpStatus || 0),
1568
- provider: traceProvider,
1569
- model: useModel,
1570
- transport: 'websocket',
1571
- handshakeRetries: err?.attempts ? Math.max(Number(err.attempts) - 1, 0) : handshakeRetries,
1572
- handshakeRetryClassifiers: classifiers,
1573
- });
1574
- }
1575
- // Handshake-layer failure. Don't double-wrap: if this is the retry
1576
- // attempt, surface the ORIGINAL first-attempt error (which is what
1577
- // the caller's turn actually tripped on).
1578
- if (attemptIndex > 0 && firstAttemptError) {
1579
- try { firstAttemptError.midstreamRetries = attemptIndex; } catch {}
1580
- throw firstAttemptError;
1581
- }
1582
- throw err;
1583
- }
1584
- const { entry, reused } = acquired;
1585
- // Re-seed the retry attempt's fresh entry with the prior attempt's
1586
- // last successful anchor so _computeDelta sees a non-null
1587
- // lastInputPrefixHash and prev_response_id, keeping the same xAI
1588
- // conversation slot warm instead of cold-starting one per retry.
1589
- if (carryForwardCache && auth?.type === 'xai' && !reused) {
1590
- entry.lastResponseId = carryForwardCache.lastResponseId;
1591
- entry.lastInputPrefixHash = carryForwardCache.lastInputPrefixHash;
1592
- entry.lastInputLen = carryForwardCache.lastInputLen;
1593
- entry.lastRequestSansInput = carryForwardCache.lastRequestSansInput;
1594
- }
1595
- traceBridgeFetch({
1596
- sessionId: poolKey,
1597
- headersMs: Date.now() - handshakeStart,
1598
- httpStatus: reused ? 0 : 101,
1599
- provider: traceProvider,
1600
- model: useModel,
1601
- transport: 'websocket',
1602
- handshakeRetries,
1603
- handshakeRetryClassifiers,
1604
- });
1605
-
1606
- let requestBody = body;
1607
- // Mid-stream retry: pin prev_id in the body so _computeDelta's
1608
- // mode='full' fallback (triggered when the carried prefix hash no
1609
- // longer matches the current input) still carries the conversation
1610
- // anchor. The delta path overwrites this from entry.lastResponseId,
1611
- // which equals the carried value, so the two paths agree.
1612
- if (carryForwardCache && auth?.type === 'xai' && attemptIndex > 0 && !body.previous_response_id) {
1613
- requestBody = { ...body, previous_response_id: carryForwardCache.lastResponseId };
1614
- }
1615
- let warmupResult = null;
1616
- // midState is shared between warmup and the main stream so warmup
1617
- // failures (first-byte timeout, send-failure, ws_4000) flow through
1618
- // the SAME mid-stream classifier as the main send. A wedged warmup
1619
- // socket must not bypass the retry loop and surface raw to the
1620
- // caller — release the entry, force a fresh acquire, and retry.
1621
- const midState = {
1622
- attemptIndex,
1623
- sawResponseCreated: false,
1624
- sawCompleted: false,
1625
- };
1626
- const sseStart = Date.now();
1627
- let mode = 'full';
1628
- let frame = null;
1629
- let deltaTokens = 0;
1630
- let result;
1631
- try {
1632
- if (warmupBody && typeof warmupBody === 'object' && attemptIndex === 0) {
1633
- const warmupFrame = { type: 'response.create', ...warmupBody };
1634
- await _sendFrameFn(entry, warmupFrame);
1635
- const warmupStart = Date.now();
1636
- const warmupState = {
1637
- attemptIndex,
1638
- sawResponseCreated: false,
1639
- sawCompleted: false,
1640
- };
1641
- warmupResult = await _streamFn({
1642
- entry,
1643
- externalSignal,
1644
- onStreamDelta: null,
1645
- onToolCall: null,
1646
- state: warmupState,
1647
- logSuppressedReasoningDeltas,
1648
- traceProvider,
1649
- });
1650
- // Surface warmup-time first-event timeout / send-failure
1651
- // flags onto the shared midState so the outer catch's
1652
- // classifier sees them. (warmupResult itself only resolves
1653
- // on success; failures throw and skip this block.)
1654
- if (warmupState.firstByteTimeout) midState.firstByteTimeout = true;
1655
- if (warmupState.wsSendFailed) midState.wsSendFailed = true;
1656
- if (!warmupResult?.responseId) {
1657
- throw new Error('Responses WS warmup completed without response id');
1658
- }
1659
- entry.lastResponseId = warmupResult.responseId;
1660
- entry.lastRequestSansInput = _stableStringify(_sansInput(warmupBody));
1661
- const warmupInputArr = Array.isArray(warmupBody.input) ? warmupBody.input : [];
1662
- entry.lastInputLen = warmupInputArr.length;
1663
- entry.lastInputPrefixHash = createHash('sha256')
1664
- .update(JSON.stringify(warmupInputArr))
1665
- .digest('hex');
1666
- try {
1667
- const warmupPayload = {
1668
- provider: traceProvider,
1669
- transport: 'websocket',
1670
- event: 'warmup_completed',
1671
- response_id: warmupResult.responseId,
1672
- elapsed_ms: Date.now() - warmupStart,
1673
- input_tokens: warmupResult.usage?.inputTokens || 0,
1674
- cached_tokens: warmupResult.usage?.cachedTokens || 0,
1675
- output_tokens: warmupResult.usage?.outputTokens || 0,
1676
- prompt_tokens: warmupResult.usage?.promptTokens || 0,
1677
- };
1678
- appendBridgeTrace({
1679
- sessionId: poolKey,
1680
- iteration,
1681
- kind: 'cache_warmup',
1682
- ...warmupPayload,
1683
- payload: warmupPayload,
1684
- });
1685
- } catch {}
1686
- requestBody = { ...body, previous_response_id: warmupResult.responseId };
1687
- delete requestBody.instructions;
1688
- delete requestBody.generate;
1689
- }
1690
-
1691
- ({ mode, frame } = _computeDelta({ entry, body: requestBody }));
1692
- deltaTokens = _estimateFrameTokens(frame);
1693
-
1694
- // Re-check abort after acquire/warmup — narrow window where
1695
- // externalSignal could fire between successful acquire and
1696
- // send(). Without this gate an aborted request could still
1697
- // emit one frame to the provider.
1698
- if (externalSignal?.aborted) {
1699
- throw new Error('Aborted');
1700
- }
1701
- await _sendFrameFn(entry, frame);
1702
-
1703
- if (process.env.MIXDOG_DEBUG_BRIDGE) {
1704
- process.stderr.write(`[bridge-trace] ws-streaming-start sinceAcquire=${Date.now() - handshakeStart}ms\n`);
1705
- }
1706
- try { onStageChange?.('streaming'); } catch {}
1707
- result = await _streamFn({
1708
- entry,
1709
- externalSignal,
1710
- onStreamDelta,
1711
- onToolCall,
1712
- state: midState,
1713
- logSuppressedReasoningDeltas,
1714
- traceProvider,
1715
- });
1716
- } catch (err) {
1717
- // Snapshot the xAI conversation anchor BEFORE releasing the
1718
- // entry. release closes the socket but leaves state fields
1719
- // intact; the next forceFresh acquire creates a new entry into
1720
- // which we manually carry the anchor so the retry continues the
1721
- // same conversation instead of cold-starting one.
1722
- if (auth?.type === 'xai' && entry.lastResponseId) {
1723
- carryForwardCache = {
1724
- lastResponseId: entry.lastResponseId,
1725
- lastInputPrefixHash: entry.lastInputPrefixHash,
1726
- lastInputLen: entry.lastInputLen,
1727
- lastRequestSansInput: entry.lastRequestSansInput,
1728
- };
1729
- }
1730
- releaseWebSocket({ entry, poolKey, keep: false });
1731
- // Mid-stream classification.
1732
- const classifier = _classifyMidstreamError(err, midState);
1733
- const retryLimit = classifier ? _midstreamRetryLimit(classifier) : 0;
1734
- if (classifier && attemptIndex < retryLimit) {
1735
- // Retry-eligible: stash the first-attempt error, emit progress,
1736
- // and loop. The subsequent acquire uses forceFresh so no socket
1737
- // is shared between attempts.
1738
- firstAttemptError = err;
1739
- firstAttemptClassifier = classifier;
1740
- try { err.midstreamClassifier = classifier; } catch {}
1741
- const retryNumber = attemptIndex + 1;
1742
- const backoff = _midstreamBackoffFor(retryNumber);
1743
- try {
1744
- const line = `[openai-oauth-ws] mid-stream recovered: retry ${retryNumber}/${retryLimit} (cause: ${classifier}, backoff ${backoff}ms)\n`;
1745
- process.stderr.write(line);
1746
- emittedProgress.push(line);
1747
- } catch {}
1748
- await _sleepWithAbort(backoff, externalSignal, _sleepFn);
1749
- continue;
1750
- }
1751
- // Not retryable, OR we've already exhausted the retry budget.
1752
- if (attemptIndex > 0 && firstAttemptError) {
1753
- // Exhausted path: surface the first-attempt error (the one
1754
- // the user's turn actually tripped on), tag actual retry count.
1755
- try { firstAttemptError.midstreamRetries = attemptIndex; } catch {}
1756
- try { firstAttemptError.midstreamClassifier = firstAttemptClassifier; } catch {}
1757
- // Attach the retry attempt's error so post-mortem diagnostics
1758
- // can see WHY the retry also failed instead of silently
1759
- // dropping it. Use `cause` if free, else `suppressed`.
1760
- try {
1761
- if (!firstAttemptError.cause) firstAttemptError.cause = err;
1762
- else {
1763
- const list = Array.isArray(firstAttemptError.suppressed)
1764
- ? firstAttemptError.suppressed
1765
- : [];
1766
- list.push(err);
1767
- firstAttemptError.suppressed = list;
1768
- }
1769
- } catch {}
1770
- throw firstAttemptError;
1771
- }
1772
- throw err;
1773
- }
1774
- const liveModel = result.model || useModel;
1775
- traceBridgeSse({
1776
- sessionId: poolKey,
1777
- sseParseMs: Date.now() - sseStart,
1778
- provider: traceProvider,
1779
- model: liveModel,
1780
- transport: 'websocket',
1781
- });
1782
-
1783
- // Update cache state for the next iteration in this session.
1784
- if (result.responseId) {
1785
- entry.lastResponseId = result.responseId;
1786
- entry.lastRequestSansInput = _stableStringify(_sansInput(requestBody));
1787
- const inputArr = Array.isArray(requestBody.input) ? requestBody.input : [];
1788
- entry.lastInputLen = inputArr.length;
1789
- // Capture the prefix hash for the next turn's delta integrity
1790
- // check. Serialize the full input (matching what _computeDelta
1791
- // will hash on the next turn's first prevLen items, where
1792
- // prevLen === inputArr.length).
1793
- entry.lastInputPrefixHash = createHash('sha256')
1794
- .update(JSON.stringify(inputArr))
1795
- .digest('hex');
1796
- }
1797
-
1798
- if (warmupResult?.usage) {
1799
- result.usage = _combineUsageWithWarmup(result.usage, warmupResult.usage);
1800
- }
1801
-
1802
- const requestedServiceTier = body?.service_tier || null;
1803
- const responseServiceTier = result.serviceTier || result.usage?.raw?.service_tier || null;
1804
- traceBridgeUsage({
1805
- sessionId: poolKey,
1806
- iteration,
1807
- inputTokens: result.usage?.inputTokens || 0,
1808
- outputTokens: result.usage?.outputTokens || 0,
1809
- cachedTokens: result.usage?.cachedTokens || 0,
1810
- promptTokens: result.usage?.promptTokens || 0,
1811
- model: liveModel,
1812
- modelDisplay: displayModel ? displayModel(liveModel) : liveModel,
1813
- responseId: result.responseId || null,
1814
- rawUsage: result.usage?.raw || null,
1815
- provider: traceProvider,
1816
- serviceTier: responseServiceTier,
1817
- });
1818
- // Extra WS-specific observability: transport + per-iteration delta bytes.
1819
- try {
1820
- const transportPayload = {
1821
- provider: traceProvider,
1822
- transport: 'websocket',
1823
- ws_mode: mode,
1824
- iteration_delta_tokens: deltaTokens,
1825
- reused_connection: reused,
1826
- requested_service_tier: requestedServiceTier,
1827
- response_service_tier: responseServiceTier,
1828
- handshake_retries: handshakeRetries,
1829
- handshake_retry_classifiers: handshakeRetryClassifiers,
1830
- midstream_retries: attemptIndex,
1831
- response_id: result.responseId || null,
1832
- request_has_previous_response_id: typeof frame.previous_response_id === 'string' && frame.previous_response_id.length > 0,
1833
- body_input_items: Array.isArray(requestBody.input) ? requestBody.input.length : null,
1834
- frame_input_items: Array.isArray(frame.input) ? frame.input.length : null,
1835
- frame_has_instructions: typeof frame.instructions === 'string' && frame.instructions.length > 0,
1836
- warmup_used: !!warmupResult,
1837
- warmup_response_id: warmupResult?.responseId || null,
1838
- };
1839
- appendBridgeTrace({
1840
- sessionId: poolKey,
1841
- iteration,
1842
- kind: 'transport',
1843
- ...transportPayload,
1844
- payload: transportPayload,
1845
- });
1846
- } catch {}
1847
-
1848
- releaseWebSocket({ entry, poolKey, keep: true });
1849
- const { responseId: _ignored, ...out } = result;
1850
- if (includeResponseId && result.responseId) out.responseId = result.responseId;
1851
- if (warmupResult) {
1852
- try {
1853
- Object.defineProperty(out, '__warmup', {
1854
- value: {
1855
- requestBody,
1856
- responseId: warmupResult.responseId,
1857
- usage: warmupResult.usage,
1858
- },
1859
- enumerable: false,
1860
- });
1861
- } catch {}
1862
- }
1863
- // Leave a breadcrumb on the result so downstream callers can observe
1864
- // that a retry was used (0 = first-try success, up to 2 for ws_1006/1011).
1865
- try { Object.defineProperty(out, '__midstreamRetries', { value: attemptIndex, enumerable: false }); } catch {}
1866
- return out;
1867
- }
1868
- // Unreachable — the loop either returns or throws above.
1869
- throw firstAttemptError || new Error('sendViaWebSocket: unreachable');
1870
- }
1871
-
1872
- // Drain-complete fence — set true once _closeAllPooledSockets runs so any
1873
- // in-flight acquire that resumes after drain throws instead of pushing a
1874
- // fresh socket into the cleared pool. Single-set, mirrors drain-registry's
1875
- // process-lifetime atomic invariant.
1876
- let _drainComplete = false;
1877
-
1878
- // Drain hook — registered in drain-registry external-resource bucket.
1879
- // Force-closes pooled sockets and fences subsequent acquires.
1880
- // `drainOpenaiWsPool` alias matches the registry's `drain*` naming convention;
1881
- // `_closeAllPooledSockets` kept for backward compat with existing call sites.
1882
- export function _closeAllPooledSockets(reason = 'shutdown') {
1883
- _drainComplete = true;
1884
- for (const arr of _wsPool.values()) {
1885
- for (const entry of arr) {
1886
- try { entry.socket.close(1000, reason); } catch {}
1887
- }
1888
- }
1889
- _wsPool.clear();
1890
- }
1891
- export const drainOpenaiWsPool = _closeAllPooledSockets;