@seqyuan/annodex 0.1.11 → 0.1.12

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 (519) hide show
  1. package/app/api/agent/[id]/events/route.ts +94 -0
  2. package/app/api/agent/[id]/route.ts +83 -0
  3. package/app/api/agent/new/route.ts +53 -0
  4. package/app/api/auth/all-providers/route.ts +21 -0
  5. package/app/api/auth/api-key/[provider]/route.ts +7 -0
  6. package/app/api/auth/login/[provider]/route.ts +7 -0
  7. package/app/api/auth/login/route.ts +22 -0
  8. package/app/api/auth/logout/[provider]/route.ts +7 -0
  9. package/app/api/auth/providers/route.ts +15 -0
  10. package/app/api/auth/status/route.ts +6 -0
  11. package/app/api/default-cwd/route.ts +22 -0
  12. package/app/api/files/[...path]/route.ts +621 -0
  13. package/app/api/harness/route.ts +47 -0
  14. package/app/api/home/route.ts +6 -0
  15. package/app/api/internal/runtime/route.ts +26 -0
  16. package/app/api/models/route.ts +67 -0
  17. package/app/api/models-config/discover/route.ts +42 -0
  18. package/app/api/models-config/route.ts +152 -0
  19. package/app/api/models-config/test/route.ts +154 -0
  20. package/app/api/projects/browse/route.ts +51 -0
  21. package/app/api/projects/route.ts +83 -0
  22. package/app/api/reports/[id]/route.ts +108 -0
  23. package/app/api/search/route.ts +122 -0
  24. package/app/api/sessions/[id]/context/route.ts +23 -0
  25. package/app/api/sessions/[id]/route.ts +124 -0
  26. package/app/api/sessions/new/route.ts +5 -0
  27. package/app/api/sessions/route.ts +16 -0
  28. package/app/api/settings/route.ts +51 -0
  29. package/app/api/skills/install/route.ts +249 -0
  30. package/app/api/skills/route.ts +161 -0
  31. package/app/api/skills/search/route.ts +121 -0
  32. package/app/api/soul/route.ts +47 -0
  33. package/app/api/version/route.ts +55 -0
  34. package/app/globals.css +736 -0
  35. package/app/layout.tsx +40 -0
  36. package/app/login/page.tsx +133 -0
  37. package/app/page.tsx +10 -0
  38. package/components/AppShell.tsx +1058 -0
  39. package/components/ChatInput.tsx +1103 -0
  40. package/components/ChatMinimap.tsx +381 -0
  41. package/components/ChatWindow.tsx +576 -0
  42. package/components/CodeMirrorEditor.tsx +137 -0
  43. package/components/ConversationSearch.tsx +369 -0
  44. package/components/DataTableViewer.tsx +248 -0
  45. package/components/FileExplorer.tsx +758 -0
  46. package/components/FileIcons.tsx +241 -0
  47. package/components/FileViewer.tsx +1273 -0
  48. package/components/GlobalFileEditor.tsx +98 -0
  49. package/components/MarkdownRenderer.tsx +331 -0
  50. package/components/MermaidDiagram.tsx +80 -0
  51. package/components/MessageView.tsx +1141 -0
  52. package/components/ModelsConfig.tsx +1991 -0
  53. package/components/ProjectContext.tsx +252 -0
  54. package/components/ProjectFolderPicker.tsx +202 -0
  55. package/components/ProjectsConfig.tsx +288 -0
  56. package/components/ProviderIcons.tsx +91 -0
  57. package/components/ReportPanel.tsx +237 -0
  58. package/components/ResizeHandle.tsx +105 -0
  59. package/components/SessionSidebar.tsx +1464 -0
  60. package/components/SettingsDialog.tsx +287 -0
  61. package/components/SkillsConfig.tsx +1093 -0
  62. package/components/SubagentPanel.tsx +191 -0
  63. package/components/TabBar.tsx +115 -0
  64. package/components/ToolPanel.tsx +131 -0
  65. package/components/WidgetRenderer.tsx +505 -0
  66. package/components/viewers/DocumentToolbar.tsx +78 -0
  67. package/components/viewers/DocxViewer.tsx +97 -0
  68. package/components/viewers/PdfViewer.tsx +206 -0
  69. package/components/viewers/PptxViewer.tsx +240 -0
  70. package/components/viewers/XlsxViewer.tsx +143 -0
  71. package/hooks/useAgentSession.ts +710 -0
  72. package/hooks/useAudio.ts +50 -0
  73. package/hooks/useDragDrop.ts +52 -0
  74. package/hooks/useResizable.ts +60 -0
  75. package/hooks/useTheme.ts +85 -0
  76. package/lib/agent-client.ts +39 -0
  77. package/lib/annodex-config.ts +556 -0
  78. package/lib/auth-token.ts +74 -0
  79. package/lib/auth.ts +90 -0
  80. package/lib/brand.ts +5 -0
  81. package/lib/code-theme.ts +32 -0
  82. package/lib/codex-compat-proxy.ts +1603 -0
  83. package/lib/codex-home.ts +6 -0
  84. package/lib/codex-server.ts +796 -0
  85. package/lib/codex-session.ts +590 -0
  86. package/lib/codex-usage.ts +213 -0
  87. package/lib/file-paths.ts +34 -0
  88. package/lib/model-discovery.ts +379 -0
  89. package/lib/normalize.ts +30 -0
  90. package/lib/npx.ts +87 -0
  91. package/lib/pi-types.ts +49 -0
  92. package/lib/projects.ts +269 -0
  93. package/lib/provider-api.ts +88 -0
  94. package/lib/report-prompt.ts +61 -0
  95. package/lib/report-store.ts +597 -0
  96. package/lib/report-update-parser.ts +66 -0
  97. package/lib/rpc-manager.ts +668 -0
  98. package/lib/runtime-state.ts +117 -0
  99. package/lib/session-reader.ts +903 -0
  100. package/lib/session-runtime.ts +105 -0
  101. package/lib/subagent-progress.ts +279 -0
  102. package/lib/types.ts +241 -0
  103. package/lib/widget-export.ts +318 -0
  104. package/lib/widget-guidelines.ts +288 -0
  105. package/lib/widget-prompt.ts +76 -0
  106. package/lib/widget-utils.ts +523 -0
  107. package/package.json +23 -18
  108. package/postcss.config.mjs +8 -0
  109. package/proxy.ts +64 -0
  110. package/scripts/postinstall.cjs +25 -0
  111. package/tsconfig.json +41 -0
  112. package/.next/BUILD_ID +0 -1
  113. package/.next/app-path-routes-manifest.json +0 -39
  114. package/.next/build-manifest.json +0 -20
  115. package/.next/diagnostics/build-diagnostics.json +0 -6
  116. package/.next/diagnostics/framework.json +0 -1
  117. package/.next/export-marker.json +0 -6
  118. package/.next/images-manifest.json +0 -68
  119. package/.next/next-minimal-server.js.nft.json +0 -1
  120. package/.next/next-server.js.nft.json +0 -1
  121. package/.next/package.json +0 -1
  122. package/.next/prerender-manifest.json +0 -109
  123. package/.next/react-loadable-manifest.json +0 -2320
  124. package/.next/required-server-files.js +0 -343
  125. package/.next/required-server-files.json +0 -343
  126. package/.next/routes-manifest.json +0 -286
  127. package/.next/server/app/_global-error/page.js +0 -32
  128. package/.next/server/app/_global-error/page.js.nft.json +0 -1
  129. package/.next/server/app/_global-error/page_client-reference-manifest.js +0 -1
  130. package/.next/server/app/_global-error.html +0 -1
  131. package/.next/server/app/_global-error.meta +0 -16
  132. package/.next/server/app/_global-error.rsc +0 -14
  133. package/.next/server/app/_global-error.segments/_full.segment.rsc +0 -14
  134. package/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +0 -5
  135. package/.next/server/app/_global-error.segments/_global-error.segment.rsc +0 -5
  136. package/.next/server/app/_global-error.segments/_head.segment.rsc +0 -5
  137. package/.next/server/app/_global-error.segments/_index.segment.rsc +0 -5
  138. package/.next/server/app/_global-error.segments/_tree.segment.rsc +0 -1
  139. package/.next/server/app/_not-found/page.js +0 -2
  140. package/.next/server/app/_not-found/page.js.nft.json +0 -1
  141. package/.next/server/app/_not-found/page_client-reference-manifest.js +0 -1
  142. package/.next/server/app/_not-found.html +0 -1
  143. package/.next/server/app/_not-found.meta +0 -16
  144. package/.next/server/app/_not-found.rsc +0 -18
  145. package/.next/server/app/_not-found.segments/_full.segment.rsc +0 -18
  146. package/.next/server/app/_not-found.segments/_head.segment.rsc +0 -6
  147. package/.next/server/app/_not-found.segments/_index.segment.rsc +0 -5
  148. package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +0 -5
  149. package/.next/server/app/_not-found.segments/_not-found.segment.rsc +0 -5
  150. package/.next/server/app/_not-found.segments/_tree.segment.rsc +0 -4
  151. package/.next/server/app/api/agent/[id]/events/route.js +0 -3
  152. package/.next/server/app/api/agent/[id]/events/route.js.nft.json +0 -1
  153. package/.next/server/app/api/agent/[id]/events/route_client-reference-manifest.js +0 -1
  154. package/.next/server/app/api/agent/[id]/route.js +0 -1
  155. package/.next/server/app/api/agent/[id]/route.js.nft.json +0 -1
  156. package/.next/server/app/api/agent/[id]/route_client-reference-manifest.js +0 -1
  157. package/.next/server/app/api/agent/new/route.js +0 -1
  158. package/.next/server/app/api/agent/new/route.js.nft.json +0 -1
  159. package/.next/server/app/api/agent/new/route_client-reference-manifest.js +0 -1
  160. package/.next/server/app/api/auth/all-providers/route.js +0 -1
  161. package/.next/server/app/api/auth/all-providers/route.js.nft.json +0 -1
  162. package/.next/server/app/api/auth/all-providers/route_client-reference-manifest.js +0 -1
  163. package/.next/server/app/api/auth/api-key/[provider]/route.js +0 -1
  164. package/.next/server/app/api/auth/api-key/[provider]/route.js.nft.json +0 -1
  165. package/.next/server/app/api/auth/api-key/[provider]/route_client-reference-manifest.js +0 -1
  166. package/.next/server/app/api/auth/login/[provider]/route.js +0 -1
  167. package/.next/server/app/api/auth/login/[provider]/route.js.nft.json +0 -1
  168. package/.next/server/app/api/auth/login/[provider]/route_client-reference-manifest.js +0 -1
  169. package/.next/server/app/api/auth/login/route.js +0 -1
  170. package/.next/server/app/api/auth/login/route.js.nft.json +0 -1
  171. package/.next/server/app/api/auth/login/route_client-reference-manifest.js +0 -1
  172. package/.next/server/app/api/auth/logout/[provider]/route.js +0 -1
  173. package/.next/server/app/api/auth/logout/[provider]/route.js.nft.json +0 -1
  174. package/.next/server/app/api/auth/logout/[provider]/route_client-reference-manifest.js +0 -1
  175. package/.next/server/app/api/auth/providers/route.js +0 -1
  176. package/.next/server/app/api/auth/providers/route.js.nft.json +0 -1
  177. package/.next/server/app/api/auth/providers/route_client-reference-manifest.js +0 -1
  178. package/.next/server/app/api/auth/status/route.js +0 -1
  179. package/.next/server/app/api/auth/status/route.js.nft.json +0 -1
  180. package/.next/server/app/api/auth/status/route_client-reference-manifest.js +0 -1
  181. package/.next/server/app/api/default-cwd/route.js +0 -1
  182. package/.next/server/app/api/default-cwd/route.js.nft.json +0 -1
  183. package/.next/server/app/api/default-cwd/route_client-reference-manifest.js +0 -1
  184. package/.next/server/app/api/files/[...path]/route.js +0 -4
  185. package/.next/server/app/api/files/[...path]/route.js.nft.json +0 -1
  186. package/.next/server/app/api/files/[...path]/route_client-reference-manifest.js +0 -1
  187. package/.next/server/app/api/harness/route.js +0 -1
  188. package/.next/server/app/api/harness/route.js.nft.json +0 -1
  189. package/.next/server/app/api/harness/route_client-reference-manifest.js +0 -1
  190. package/.next/server/app/api/home/route.js +0 -1
  191. package/.next/server/app/api/home/route.js.nft.json +0 -1
  192. package/.next/server/app/api/home/route_client-reference-manifest.js +0 -1
  193. package/.next/server/app/api/internal/runtime/route.js +0 -1
  194. package/.next/server/app/api/internal/runtime/route.js.nft.json +0 -1
  195. package/.next/server/app/api/internal/runtime/route_client-reference-manifest.js +0 -1
  196. package/.next/server/app/api/models/route.js +0 -1
  197. package/.next/server/app/api/models/route.js.nft.json +0 -1
  198. package/.next/server/app/api/models/route_client-reference-manifest.js +0 -1
  199. package/.next/server/app/api/models-config/discover/route.js +0 -1
  200. package/.next/server/app/api/models-config/discover/route.js.nft.json +0 -1
  201. package/.next/server/app/api/models-config/discover/route_client-reference-manifest.js +0 -1
  202. package/.next/server/app/api/models-config/route.js +0 -1
  203. package/.next/server/app/api/models-config/route.js.nft.json +0 -1
  204. package/.next/server/app/api/models-config/route_client-reference-manifest.js +0 -1
  205. package/.next/server/app/api/models-config/test/route.js +0 -1
  206. package/.next/server/app/api/models-config/test/route.js.nft.json +0 -1
  207. package/.next/server/app/api/models-config/test/route_client-reference-manifest.js +0 -1
  208. package/.next/server/app/api/projects/browse/route.js +0 -1
  209. package/.next/server/app/api/projects/browse/route.js.nft.json +0 -1
  210. package/.next/server/app/api/projects/browse/route_client-reference-manifest.js +0 -1
  211. package/.next/server/app/api/projects/route.js +0 -1
  212. package/.next/server/app/api/projects/route.js.nft.json +0 -1
  213. package/.next/server/app/api/projects/route_client-reference-manifest.js +0 -1
  214. package/.next/server/app/api/reports/[id]/route.js +0 -10
  215. package/.next/server/app/api/reports/[id]/route.js.nft.json +0 -1
  216. package/.next/server/app/api/reports/[id]/route_client-reference-manifest.js +0 -1
  217. package/.next/server/app/api/search/route.js +0 -1
  218. package/.next/server/app/api/search/route.js.nft.json +0 -1
  219. package/.next/server/app/api/search/route_client-reference-manifest.js +0 -1
  220. package/.next/server/app/api/sessions/[id]/context/route.js +0 -1
  221. package/.next/server/app/api/sessions/[id]/context/route.js.nft.json +0 -1
  222. package/.next/server/app/api/sessions/[id]/context/route_client-reference-manifest.js +0 -1
  223. package/.next/server/app/api/sessions/[id]/route.js +0 -1
  224. package/.next/server/app/api/sessions/[id]/route.js.nft.json +0 -1
  225. package/.next/server/app/api/sessions/[id]/route_client-reference-manifest.js +0 -1
  226. package/.next/server/app/api/sessions/new/route.js +0 -1
  227. package/.next/server/app/api/sessions/new/route.js.nft.json +0 -1
  228. package/.next/server/app/api/sessions/new/route_client-reference-manifest.js +0 -1
  229. package/.next/server/app/api/sessions/route.js +0 -1
  230. package/.next/server/app/api/sessions/route.js.nft.json +0 -1
  231. package/.next/server/app/api/sessions/route_client-reference-manifest.js +0 -1
  232. package/.next/server/app/api/settings/route.js +0 -1
  233. package/.next/server/app/api/settings/route.js.nft.json +0 -1
  234. package/.next/server/app/api/settings/route_client-reference-manifest.js +0 -1
  235. package/.next/server/app/api/skills/install/route.js +0 -5
  236. package/.next/server/app/api/skills/install/route.js.nft.json +0 -1
  237. package/.next/server/app/api/skills/install/route_client-reference-manifest.js +0 -1
  238. package/.next/server/app/api/skills/route.js +0 -6
  239. package/.next/server/app/api/skills/route.js.nft.json +0 -1
  240. package/.next/server/app/api/skills/route_client-reference-manifest.js +0 -1
  241. package/.next/server/app/api/skills/search/route.js +0 -1
  242. package/.next/server/app/api/skills/search/route.js.nft.json +0 -1
  243. package/.next/server/app/api/skills/search/route_client-reference-manifest.js +0 -1
  244. package/.next/server/app/api/soul/route.js +0 -1
  245. package/.next/server/app/api/soul/route.js.nft.json +0 -1
  246. package/.next/server/app/api/soul/route_client-reference-manifest.js +0 -1
  247. package/.next/server/app/api/version/route.js +0 -1
  248. package/.next/server/app/api/version/route.js.nft.json +0 -1
  249. package/.next/server/app/api/version/route_client-reference-manifest.js +0 -1
  250. package/.next/server/app/index.html +0 -1
  251. package/.next/server/app/index.meta +0 -14
  252. package/.next/server/app/index.rsc +0 -17
  253. package/.next/server/app/index.segments/__PAGE__.segment.rsc +0 -6
  254. package/.next/server/app/index.segments/_full.segment.rsc +0 -17
  255. package/.next/server/app/index.segments/_head.segment.rsc +0 -6
  256. package/.next/server/app/index.segments/_index.segment.rsc +0 -5
  257. package/.next/server/app/index.segments/_tree.segment.rsc +0 -4
  258. package/.next/server/app/login/page.js +0 -2
  259. package/.next/server/app/login/page.js.nft.json +0 -1
  260. package/.next/server/app/login/page_client-reference-manifest.js +0 -1
  261. package/.next/server/app/login.html +0 -1
  262. package/.next/server/app/login.meta +0 -15
  263. package/.next/server/app/login.rsc +0 -22
  264. package/.next/server/app/login.segments/_full.segment.rsc +0 -22
  265. package/.next/server/app/login.segments/_head.segment.rsc +0 -6
  266. package/.next/server/app/login.segments/_index.segment.rsc +0 -5
  267. package/.next/server/app/login.segments/_tree.segment.rsc +0 -4
  268. package/.next/server/app/login.segments/login/__PAGE__.segment.rsc +0 -9
  269. package/.next/server/app/login.segments/login.segment.rsc +0 -5
  270. package/.next/server/app/page.js +0 -261
  271. package/.next/server/app/page.js.nft.json +0 -1
  272. package/.next/server/app/page_client-reference-manifest.js +0 -1
  273. package/.next/server/app-paths-manifest.json +0 -39
  274. package/.next/server/chunks/1048.js +0 -1
  275. package/.next/server/chunks/1367.js +0 -77
  276. package/.next/server/chunks/1381.js +0 -1
  277. package/.next/server/chunks/165.js +0 -1
  278. package/.next/server/chunks/1681.js +0 -215
  279. package/.next/server/chunks/1688.js +0 -45
  280. package/.next/server/chunks/1703.js +0 -79
  281. package/.next/server/chunks/1712.js +0 -43
  282. package/.next/server/chunks/1813.js +0 -1
  283. package/.next/server/chunks/2325.js +0 -80
  284. package/.next/server/chunks/258.js +0 -1
  285. package/.next/server/chunks/2671.js +0 -287
  286. package/.next/server/chunks/2778.js +0 -1
  287. package/.next/server/chunks/2943.js +0 -1
  288. package/.next/server/chunks/3031.js +0 -226
  289. package/.next/server/chunks/3181.js +0 -1
  290. package/.next/server/chunks/3493.js +0 -1
  291. package/.next/server/chunks/3672.js +0 -1
  292. package/.next/server/chunks/3701.js +0 -104
  293. package/.next/server/chunks/4013.js +0 -1
  294. package/.next/server/chunks/402.js +0 -2
  295. package/.next/server/chunks/4035.js +0 -80
  296. package/.next/server/chunks/4248.js +0 -153
  297. package/.next/server/chunks/4367.js +0 -1
  298. package/.next/server/chunks/4406.js +0 -141
  299. package/.next/server/chunks/4741.js +0 -18
  300. package/.next/server/chunks/4768.js +0 -1
  301. package/.next/server/chunks/4858.js +0 -148
  302. package/.next/server/chunks/4980.js +0 -1
  303. package/.next/server/chunks/5155.js +0 -5
  304. package/.next/server/chunks/5293.js +0 -166
  305. package/.next/server/chunks/5399.js +0 -8
  306. package/.next/server/chunks/5409.js +0 -1
  307. package/.next/server/chunks/5797.js +0 -93
  308. package/.next/server/chunks/5851.js +0 -36
  309. package/.next/server/chunks/6206.js +0 -1
  310. package/.next/server/chunks/6296.js +0 -1
  311. package/.next/server/chunks/63.js +0 -45
  312. package/.next/server/chunks/6346.js +0 -1
  313. package/.next/server/chunks/6406.js +0 -23
  314. package/.next/server/chunks/642.js +0 -1
  315. package/.next/server/chunks/6429.js +0 -50
  316. package/.next/server/chunks/6729.js +0 -64
  317. package/.next/server/chunks/6907.js +0 -115
  318. package/.next/server/chunks/6980.js +0 -1
  319. package/.next/server/chunks/7073.js +0 -24
  320. package/.next/server/chunks/7233.js +0 -24
  321. package/.next/server/chunks/7307.js +0 -1
  322. package/.next/server/chunks/7362.js +0 -9
  323. package/.next/server/chunks/7567.js +0 -29
  324. package/.next/server/chunks/7765.js +0 -1
  325. package/.next/server/chunks/7890.js +0 -1
  326. package/.next/server/chunks/8065.js +0 -1
  327. package/.next/server/chunks/8238.js +0 -34
  328. package/.next/server/chunks/8276.js +0 -1
  329. package/.next/server/chunks/8336.js +0 -1
  330. package/.next/server/chunks/8477.js +0 -3
  331. package/.next/server/chunks/8490.js +0 -1
  332. package/.next/server/chunks/8916.js +0 -1
  333. package/.next/server/chunks/9280.js +0 -252
  334. package/.next/server/chunks/9315.js +0 -1
  335. package/.next/server/chunks/9537.js +0 -90
  336. package/.next/server/chunks/966.js +0 -1
  337. package/.next/server/chunks/9818.js +0 -21
  338. package/.next/server/chunks/static/media/pdf.worker.min.c476e1a0.mjs +0 -6
  339. package/.next/server/functions-config-manifest.json +0 -16
  340. package/.next/server/interception-route-rewrite-manifest.js +0 -1
  341. package/.next/server/middleware-build-manifest.js +0 -1
  342. package/.next/server/middleware-manifest.json +0 -6
  343. package/.next/server/middleware-react-loadable-manifest.js +0 -1
  344. package/.next/server/middleware.js +0 -18
  345. package/.next/server/middleware.js.nft.json +0 -1
  346. package/.next/server/next-font-manifest.js +0 -1
  347. package/.next/server/next-font-manifest.json +0 -1
  348. package/.next/server/pages/404.html +0 -1
  349. package/.next/server/pages/500.html +0 -1
  350. package/.next/server/pages-manifest.json +0 -4
  351. package/.next/server/prefetch-hints.json +0 -1
  352. package/.next/server/server-reference-manifest.js +0 -1
  353. package/.next/server/server-reference-manifest.json +0 -1
  354. package/.next/server/webpack-runtime.js +0 -1
  355. package/.next/static/chunks/0b9a0da7.9075af772487e743.js +0 -62
  356. package/.next/static/chunks/1413.922d232de90c0c41.js +0 -115
  357. package/.next/static/chunks/1643.467a526a1f24f54d.js +0 -24
  358. package/.next/static/chunks/1852.5543122f11aa7fed.js +0 -1
  359. package/.next/static/chunks/1960.b1e26436d7a5f586.js +0 -1
  360. package/.next/static/chunks/2170a4aa.4213bb2183c9cdf9.js +0 -1
  361. package/.next/static/chunks/2274.6cd173f80a1405a2.js +0 -21
  362. package/.next/static/chunks/2419.347fdfe3c170854d.js +0 -166
  363. package/.next/static/chunks/2619.9aac8983f30c7c8a.js +0 -1
  364. package/.next/static/chunks/2623.d20fabd8e18197c6.js +0 -287
  365. package/.next/static/chunks/2729.f5365061a849d659.js +0 -34
  366. package/.next/static/chunks/2821.934bcf60fbdc28c6.js +0 -1
  367. package/.next/static/chunks/2918becc.abff2ece1de37bc1.js +0 -153
  368. package/.next/static/chunks/2947.114e51cb06d1c01a.js +0 -23
  369. package/.next/static/chunks/3079.4c511fa1144e3adf.js +0 -79
  370. package/.next/static/chunks/3274.208ca44844cd7d95.js +0 -148
  371. package/.next/static/chunks/3308.465a94263d04bfea.js +0 -73
  372. package/.next/static/chunks/3325.e4bfe1ca657f3b5b.js +0 -80
  373. package/.next/static/chunks/3506.2a7eaa08b9f55337.js +0 -90
  374. package/.next/static/chunks/363642f4-043c1475ab9af70e.js +0 -1
  375. package/.next/static/chunks/3794-123fdf632563f469.js +0 -32
  376. package/.next/static/chunks/3837.a755ccfe6f9c1c1c.js +0 -5
  377. package/.next/static/chunks/394.91597771688df6d0.js +0 -1
  378. package/.next/static/chunks/3997.1009c06025691712.js +0 -1
  379. package/.next/static/chunks/4453.91a357dc43c21745.js +0 -1
  380. package/.next/static/chunks/4491.44fdf20580ac72bd.js +0 -24
  381. package/.next/static/chunks/4829.cf1d50e43e6d9db5.js +0 -1
  382. package/.next/static/chunks/498.fe1d9da9ecad6c36.js +0 -1
  383. package/.next/static/chunks/4bd1b696-e356ca5ba0218e27.js +0 -1
  384. package/.next/static/chunks/5019.b5a1a2b8daf17525.js +0 -1
  385. package/.next/static/chunks/5034.8f16c3fa3ce75411.js +0 -1
  386. package/.next/static/chunks/5074.d16651da01ec4e02.js +0 -1
  387. package/.next/static/chunks/51fb665c.0950e1b79671348d.js +0 -45
  388. package/.next/static/chunks/532.5956ed631aff722b.js +0 -9
  389. package/.next/static/chunks/5326.69460442bdcd6cd3.js +0 -1
  390. package/.next/static/chunks/5403.ff110bf5bf600758.js +0 -64
  391. package/.next/static/chunks/547.902a733488cfe3f7.js +0 -77
  392. package/.next/static/chunks/5567.540d7fc108ad6ee5.js +0 -215
  393. package/.next/static/chunks/5590.ef62922166d308b4.js +0 -1
  394. package/.next/static/chunks/5690.9d6eb1edb1399995.js +0 -1
  395. package/.next/static/chunks/5749.25faee4a1e55b854.js +0 -226
  396. package/.next/static/chunks/58bb9007.1ccb6bba34b4c635.js +0 -80
  397. package/.next/static/chunks/6121.f3f43f1896ea0cd9.js +0 -1
  398. package/.next/static/chunks/6600.583c88eef37aa524.js +0 -1
  399. package/.next/static/chunks/6696.a41aec266e657d54.js +0 -141
  400. package/.next/static/chunks/6922.42148793782d2fe7.js +0 -1
  401. package/.next/static/chunks/7006.e191611ffc2b9528.js +0 -43
  402. package/.next/static/chunks/7343.9fbb58204d8ac681.js +0 -1
  403. package/.next/static/chunks/73972abe.25a4cffa03b2bcef.js +0 -119
  404. package/.next/static/chunks/7547.58bda8a2aabba0d4.js +0 -93
  405. package/.next/static/chunks/7648.4ae2f183b4db0353.js +0 -1
  406. package/.next/static/chunks/7874.8db6929b94cdf697.js +0 -1
  407. package/.next/static/chunks/7959.1f20a35df316216a.js +0 -104
  408. package/.next/static/chunks/83.85d62d7fc9850b75.js +0 -29
  409. package/.next/static/chunks/8436.cab94b59cca0a8ff.js +0 -1
  410. package/.next/static/chunks/8451.ff6ff72b57dc52e1.js +0 -1
  411. package/.next/static/chunks/8489.45f22859734f514f.js +0 -36
  412. package/.next/static/chunks/8568.f85d8b36fc9a9037.js +0 -1
  413. package/.next/static/chunks/8771-3e14b6810486df1f.js +0 -1
  414. package/.next/static/chunks/8863.be51033a67436277.js +0 -1
  415. package/.next/static/chunks/90542734.dc1a2723e4f6affb.js +0 -1
  416. package/.next/static/chunks/9500.1488aec06ee78127.js +0 -1
  417. package/.next/static/chunks/9633.155548b5fca6e580.js +0 -1
  418. package/.next/static/chunks/9779.673004a62d70e36a.js +0 -1
  419. package/.next/static/chunks/app/_global-error/page-cc518af6b1ffb191.js +0 -1
  420. package/.next/static/chunks/app/_not-found/page-c72daab99269beff.js +0 -1
  421. package/.next/static/chunks/app/api/agent/[id]/events/route-cc518af6b1ffb191.js +0 -1
  422. package/.next/static/chunks/app/api/agent/[id]/route-cc518af6b1ffb191.js +0 -1
  423. package/.next/static/chunks/app/api/agent/new/route-cc518af6b1ffb191.js +0 -1
  424. package/.next/static/chunks/app/api/auth/all-providers/route-cc518af6b1ffb191.js +0 -1
  425. package/.next/static/chunks/app/api/auth/api-key/[provider]/route-cc518af6b1ffb191.js +0 -1
  426. package/.next/static/chunks/app/api/auth/login/[provider]/route-cc518af6b1ffb191.js +0 -1
  427. package/.next/static/chunks/app/api/auth/login/route-cc518af6b1ffb191.js +0 -1
  428. package/.next/static/chunks/app/api/auth/logout/[provider]/route-cc518af6b1ffb191.js +0 -1
  429. package/.next/static/chunks/app/api/auth/providers/route-cc518af6b1ffb191.js +0 -1
  430. package/.next/static/chunks/app/api/auth/status/route-cc518af6b1ffb191.js +0 -1
  431. package/.next/static/chunks/app/api/default-cwd/route-cc518af6b1ffb191.js +0 -1
  432. package/.next/static/chunks/app/api/files/[...path]/route-cc518af6b1ffb191.js +0 -1
  433. package/.next/static/chunks/app/api/harness/route-cc518af6b1ffb191.js +0 -1
  434. package/.next/static/chunks/app/api/home/route-cc518af6b1ffb191.js +0 -1
  435. package/.next/static/chunks/app/api/internal/runtime/route-cc518af6b1ffb191.js +0 -1
  436. package/.next/static/chunks/app/api/models/route-cc518af6b1ffb191.js +0 -1
  437. package/.next/static/chunks/app/api/models-config/discover/route-cc518af6b1ffb191.js +0 -1
  438. package/.next/static/chunks/app/api/models-config/route-cc518af6b1ffb191.js +0 -1
  439. package/.next/static/chunks/app/api/models-config/test/route-cc518af6b1ffb191.js +0 -1
  440. package/.next/static/chunks/app/api/projects/browse/route-cc518af6b1ffb191.js +0 -1
  441. package/.next/static/chunks/app/api/projects/route-cc518af6b1ffb191.js +0 -1
  442. package/.next/static/chunks/app/api/reports/[id]/route-cc518af6b1ffb191.js +0 -1
  443. package/.next/static/chunks/app/api/search/route-cc518af6b1ffb191.js +0 -1
  444. package/.next/static/chunks/app/api/sessions/[id]/context/route-cc518af6b1ffb191.js +0 -1
  445. package/.next/static/chunks/app/api/sessions/[id]/route-cc518af6b1ffb191.js +0 -1
  446. package/.next/static/chunks/app/api/sessions/new/route-cc518af6b1ffb191.js +0 -1
  447. package/.next/static/chunks/app/api/sessions/route-cc518af6b1ffb191.js +0 -1
  448. package/.next/static/chunks/app/api/settings/route-cc518af6b1ffb191.js +0 -1
  449. package/.next/static/chunks/app/api/skills/install/route-cc518af6b1ffb191.js +0 -1
  450. package/.next/static/chunks/app/api/skills/route-cc518af6b1ffb191.js +0 -1
  451. package/.next/static/chunks/app/api/skills/search/route-cc518af6b1ffb191.js +0 -1
  452. package/.next/static/chunks/app/api/soul/route-cc518af6b1ffb191.js +0 -1
  453. package/.next/static/chunks/app/api/version/route-cc518af6b1ffb191.js +0 -1
  454. package/.next/static/chunks/app/layout-be148b7ae915b22a.js +0 -1
  455. package/.next/static/chunks/app/login/page-ebf0e6de99062783.js +0 -1
  456. package/.next/static/chunks/app/page-a4bfb7d711561cb3.js +0 -260
  457. package/.next/static/chunks/d3ac728e.7964f816a1ca64e5.js +0 -1
  458. package/.next/static/chunks/framework-711ef29bc66f648c.js +0 -1
  459. package/.next/static/chunks/main-app-45a0f19af99d61b6.js +0 -1
  460. package/.next/static/chunks/main-f74964b7ae52493e.js +0 -5
  461. package/.next/static/chunks/next/dist/client/components/builtin/app-error-cc518af6b1ffb191.js +0 -1
  462. package/.next/static/chunks/next/dist/client/components/builtin/forbidden-cc518af6b1ffb191.js +0 -1
  463. package/.next/static/chunks/next/dist/client/components/builtin/global-error-9bfa08b9491621f2.js +0 -1
  464. package/.next/static/chunks/next/dist/client/components/builtin/not-found-cc518af6b1ffb191.js +0 -1
  465. package/.next/static/chunks/next/dist/client/components/builtin/unauthorized-cc518af6b1ffb191.js +0 -1
  466. package/.next/static/chunks/polyfills-42372ed130431b0a.js +0 -1
  467. package/.next/static/chunks/webpack-fcf4a889ecbd753c.js +0 -1
  468. package/.next/static/css/45029451a1d7255d.css +0 -3
  469. package/.next/static/lFCcFmLd1ThQXTFUP6olh/_buildManifest.js +0 -1
  470. package/.next/static/lFCcFmLd1ThQXTFUP6olh/_ssgManifest.js +0 -1
  471. package/.next/static/media/15605e25b523335c-s.woff2 +0 -0
  472. package/.next/static/media/1a3dce5cfb5f7760-s.woff2 +0 -0
  473. package/.next/static/media/1cdd02902f937a18-s.woff2 +0 -0
  474. package/.next/static/media/4c4b3b30b6bcb2be-s.woff2 +0 -0
  475. package/.next/static/media/641a7b8a5800ee0e-s.woff2 +0 -0
  476. package/.next/static/media/7deddc85b7ffd1dc-s.p.woff2 +0 -0
  477. package/.next/static/media/ec14413c594b3356-s.p.woff2 +0 -0
  478. package/.next/static/media/pdf.worker.min.29aaf158.mjs +0 -6
  479. package/.next/trace +0 -74
  480. package/.next/trace-build +0 -1
  481. package/.next/types/app/api/agent/[id]/events/route.ts +0 -351
  482. package/.next/types/app/api/agent/[id]/route.ts +0 -351
  483. package/.next/types/app/api/agent/new/route.ts +0 -351
  484. package/.next/types/app/api/auth/all-providers/route.ts +0 -351
  485. package/.next/types/app/api/auth/api-key/[provider]/route.ts +0 -351
  486. package/.next/types/app/api/auth/login/[provider]/route.ts +0 -351
  487. package/.next/types/app/api/auth/login/route.ts +0 -351
  488. package/.next/types/app/api/auth/logout/[provider]/route.ts +0 -351
  489. package/.next/types/app/api/auth/providers/route.ts +0 -351
  490. package/.next/types/app/api/auth/status/route.ts +0 -351
  491. package/.next/types/app/api/default-cwd/route.ts +0 -351
  492. package/.next/types/app/api/files/[...path]/route.ts +0 -351
  493. package/.next/types/app/api/harness/route.ts +0 -351
  494. package/.next/types/app/api/home/route.ts +0 -351
  495. package/.next/types/app/api/internal/runtime/route.ts +0 -351
  496. package/.next/types/app/api/models/route.ts +0 -351
  497. package/.next/types/app/api/models-config/discover/route.ts +0 -351
  498. package/.next/types/app/api/models-config/route.ts +0 -351
  499. package/.next/types/app/api/models-config/test/route.ts +0 -351
  500. package/.next/types/app/api/projects/browse/route.ts +0 -351
  501. package/.next/types/app/api/projects/route.ts +0 -351
  502. package/.next/types/app/api/reports/[id]/route.ts +0 -351
  503. package/.next/types/app/api/search/route.ts +0 -351
  504. package/.next/types/app/api/sessions/[id]/context/route.ts +0 -351
  505. package/.next/types/app/api/sessions/[id]/route.ts +0 -351
  506. package/.next/types/app/api/sessions/new/route.ts +0 -351
  507. package/.next/types/app/api/sessions/route.ts +0 -351
  508. package/.next/types/app/api/settings/route.ts +0 -351
  509. package/.next/types/app/api/skills/install/route.ts +0 -351
  510. package/.next/types/app/api/skills/route.ts +0 -351
  511. package/.next/types/app/api/skills/search/route.ts +0 -351
  512. package/.next/types/app/api/soul/route.ts +0 -351
  513. package/.next/types/app/api/version/route.ts +0 -351
  514. package/.next/types/app/layout.ts +0 -87
  515. package/.next/types/app/login/page.ts +0 -87
  516. package/.next/types/app/page.ts +0 -87
  517. package/.next/types/package.json +0 -1
  518. package/.next/types/routes.d.ts +0 -106
  519. package/.next/types/validator.ts +0 -376
@@ -0,0 +1,1603 @@
1
+ /**
2
+ * Codex Compat Proxy - Responses API <-> Chat Completions translation.
3
+ *
4
+ * Codex CLI speaks OpenAI Responses. Many third-party providers used by
5
+ * annodex, including DeepSeek-style and relay providers, expose Chat
6
+ * Completions. This in-process proxy keeps Codex on Responses while translating
7
+ * the upstream request/response shape.
8
+ */
9
+
10
+ import { createServer, type IncomingMessage, type ServerResponse } from "http";
11
+ import { request as httpRequest } from "http";
12
+ import { request as httpsRequest } from "https";
13
+ import { randomBytes } from "crypto";
14
+ import { URL } from "url";
15
+ import type { ReasoningConfig } from "./provider-api";
16
+
17
+ interface ProxyOptions {
18
+ targetUrl: string;
19
+ apiKey: string;
20
+ defaultThinking?: string;
21
+ /** Provider-level thinking/reasoning parameter mapping override. */
22
+ reasoningConfig?: ReasoningConfig;
23
+ port?: number;
24
+ }
25
+
26
+ type JsonObject = Record<string, unknown>;
27
+
28
+ interface ResponsesRequestBody extends JsonObject {
29
+ model?: string;
30
+ instructions?: unknown;
31
+ input?: unknown;
32
+ tools?: JsonObject[];
33
+ tool_choice?: unknown;
34
+ stream?: boolean;
35
+ reasoning?: { enabled?: boolean; effort?: string } | null;
36
+ temperature?: number;
37
+ top_p?: number;
38
+ max_output_tokens?: number;
39
+ max_tokens?: number;
40
+ max_completion_tokens?: number;
41
+ stop?: string | string[];
42
+ frequency_penalty?: number;
43
+ presence_penalty?: number;
44
+ parallel_tool_calls?: boolean;
45
+ }
46
+
47
+ interface ChatMessage extends JsonObject {
48
+ role: string;
49
+ content: unknown;
50
+ tool_calls?: ChatToolCall[];
51
+ tool_call_id?: string;
52
+ reasoning_content?: string;
53
+ }
54
+
55
+ interface ChatToolCall {
56
+ id: string;
57
+ type: "function";
58
+ function: {
59
+ name: string;
60
+ arguments: string;
61
+ };
62
+ }
63
+
64
+ interface ChatRequestBody extends JsonObject {
65
+ model: string;
66
+ messages: ChatMessage[];
67
+ stream?: boolean;
68
+ stream_options?: JsonObject;
69
+ tools?: ChatTool[];
70
+ tool_choice?: unknown;
71
+ thinking?: { type: string };
72
+ enable_thinking?: boolean;
73
+ reasoning_effort?: string;
74
+ temperature?: number;
75
+ top_p?: number;
76
+ max_tokens?: number;
77
+ max_completion_tokens?: number;
78
+ stop?: string | string[];
79
+ frequency_penalty?: number;
80
+ presence_penalty?: number;
81
+ parallel_tool_calls?: boolean;
82
+ }
83
+
84
+ interface ChatTool {
85
+ type: "function";
86
+ function: {
87
+ name: string;
88
+ description?: string;
89
+ parameters: unknown;
90
+ };
91
+ }
92
+
93
+ type ToolKind = "function" | "custom";
94
+
95
+ interface ToolSpec {
96
+ chatName: string;
97
+ originalName: string;
98
+ namespace?: string;
99
+ kind: ToolKind;
100
+ }
101
+
102
+ interface ToolContext {
103
+ specs: Map<string, ToolSpec>;
104
+ }
105
+
106
+ interface StreamToolCallState {
107
+ outputIndex: number;
108
+ itemId: string;
109
+ callId: string;
110
+ name: string;
111
+ arguments: string;
112
+ done: boolean;
113
+ }
114
+
115
+ type InlineThinkMode = "detecting" | "reasoning" | "text";
116
+
117
+ interface SSEStreamState {
118
+ responseId: string;
119
+ messageId: string;
120
+ reasoningId: string;
121
+ createdAt: number;
122
+ model: string;
123
+ text: string;
124
+ textStarted: boolean;
125
+ contentStarted: boolean;
126
+ messageOutputIndex: number | null;
127
+ reasoningText: string;
128
+ reasoningStarted: boolean;
129
+ reasoningDone: boolean;
130
+ reasoningOutputIndex: number | null;
131
+ inlineThinkMode: InlineThinkMode;
132
+ inlineThinkBuffer: string;
133
+ nextOutputIndex: number;
134
+ toolCalls: Array<StreamToolCallState | undefined>;
135
+ outputItems: Array<{ outputIndex: number; item: JsonObject }>;
136
+ finalUsage: JsonObject | null;
137
+ finishReason: string | null;
138
+ toolContext: ToolContext;
139
+ }
140
+
141
+ type ThinkingEffort = "off" | "minimal" | "low" | "medium" | "high" | "xhigh";
142
+
143
+ interface ThinkingMapping {
144
+ supportsEffort: boolean;
145
+ effortMap: Record<ThinkingEffort, string | null>;
146
+ thinkingParam?: "thinking" | "enable_thinking";
147
+ effortParam?: "reasoning_effort" | "reasoning.effort";
148
+ }
149
+
150
+ const THINK_OPEN_TAG = "<think>";
151
+ const THINK_CLOSE_TAG = "</think>";
152
+ const ERROR_BODY_PREVIEW_LIMIT = 1024;
153
+
154
+ const EXTRA_CHAT_PASSTHROUGH_FIELDS = [
155
+ "logit_bias",
156
+ "logprobs",
157
+ "metadata",
158
+ "n",
159
+ "response_format",
160
+ "seed",
161
+ "service_tier",
162
+ "top_logprobs",
163
+ "user",
164
+ ] as const;
165
+
166
+ function buildThinkingMapping(config: ReasoningConfig): ThinkingMapping {
167
+ const mode = config.effortValueMode ?? "generic";
168
+ let effortMap: Record<ThinkingEffort, string | null>;
169
+ switch (mode) {
170
+ case "deepseek":
171
+ effortMap = { off: null, minimal: "high", low: "high", medium: "high", high: "high", xhigh: "max" };
172
+ break;
173
+ case "glm":
174
+ effortMap = { off: null, minimal: "low", low: "low", medium: "medium", high: "high", xhigh: "high" };
175
+ break;
176
+ case "openrouter":
177
+ effortMap = { off: null, minimal: "minimal", low: "low", medium: "medium", high: "high", xhigh: "xhigh" };
178
+ break;
179
+ default:
180
+ effortMap = { off: null, minimal: "enabled", low: "enabled", medium: "enabled", high: "enabled", xhigh: "enabled" };
181
+ break;
182
+ }
183
+ return {
184
+ supportsEffort: config.supportsEffort ?? (config.effortParam !== "none" && config.effortParam !== null),
185
+ thinkingParam: config.thinkingParam ?? undefined,
186
+ effortParam: config.effortParam === null || config.effortParam === "none" ? undefined : (config.effortParam ?? undefined),
187
+ effortMap,
188
+ };
189
+ }
190
+
191
+ const THINKING_MAPPINGS: Record<string, ThinkingMapping> = {
192
+ deepseek: {
193
+ supportsEffort: true,
194
+ thinkingParam: "thinking",
195
+ effortParam: "reasoning_effort",
196
+ effortMap: {
197
+ off: null,
198
+ minimal: "high",
199
+ low: "high",
200
+ medium: "high",
201
+ high: "high",
202
+ xhigh: "max",
203
+ },
204
+ },
205
+ kimi: {
206
+ supportsEffort: false,
207
+ thinkingParam: "thinking",
208
+ effortMap: {
209
+ off: null,
210
+ minimal: "enabled",
211
+ low: "enabled",
212
+ medium: "enabled",
213
+ high: "enabled",
214
+ xhigh: "enabled",
215
+ },
216
+ },
217
+ qwen: {
218
+ supportsEffort: false,
219
+ thinkingParam: "enable_thinking",
220
+ effortMap: {
221
+ off: null,
222
+ minimal: "enabled",
223
+ low: "enabled",
224
+ medium: "enabled",
225
+ high: "enabled",
226
+ xhigh: "enabled",
227
+ },
228
+ },
229
+ glm: {
230
+ supportsEffort: true,
231
+ thinkingParam: "thinking",
232
+ effortParam: "reasoning_effort",
233
+ effortMap: {
234
+ off: null,
235
+ minimal: "low",
236
+ low: "low",
237
+ medium: "medium",
238
+ high: "high",
239
+ xhigh: "high",
240
+ },
241
+ },
242
+ openrouter: {
243
+ supportsEffort: true,
244
+ effortParam: "reasoning.effort",
245
+ effortMap: {
246
+ off: null,
247
+ minimal: "minimal",
248
+ low: "low",
249
+ medium: "medium",
250
+ high: "high",
251
+ xhigh: "xhigh",
252
+ },
253
+ },
254
+ generic: {
255
+ supportsEffort: false,
256
+ thinkingParam: "thinking",
257
+ effortMap: {
258
+ off: null,
259
+ minimal: "enabled",
260
+ low: "enabled",
261
+ medium: "enabled",
262
+ high: "enabled",
263
+ xhigh: "enabled",
264
+ },
265
+ },
266
+ };
267
+
268
+ function isRecord(value: unknown): value is JsonObject {
269
+ return typeof value === "object" && value !== null && !Array.isArray(value);
270
+ }
271
+
272
+ function stringField(value: unknown): string | undefined {
273
+ return typeof value === "string" && value.trim() ? value : undefined;
274
+ }
275
+
276
+ function canonicalJsonString(value: unknown): string {
277
+ if (typeof value === "string") return canonicalizeJsonStringIfParseable(value);
278
+ try {
279
+ return JSON.stringify(value ?? "");
280
+ } catch {
281
+ return String(value ?? "");
282
+ }
283
+ }
284
+
285
+ function canonicalizeJsonStringIfParseable(value: string): string {
286
+ const trimmed = value.trim();
287
+ if (!trimmed) return value;
288
+ try {
289
+ return JSON.stringify(JSON.parse(trimmed));
290
+ } catch {
291
+ return value;
292
+ }
293
+ }
294
+
295
+ function appendText(existing: string | undefined, text: string | undefined): string | undefined {
296
+ const trimmed = text?.trim();
297
+ if (!trimmed) return existing;
298
+ if (!existing) return trimmed;
299
+ if (existing.includes(trimmed)) return existing;
300
+ return `${existing}\n\n${trimmed}`;
301
+ }
302
+
303
+ function instructionText(value: unknown): string {
304
+ if (typeof value === "string") return value;
305
+ if (Array.isArray(value)) {
306
+ return value
307
+ .map((part) => {
308
+ if (typeof part === "string") return part;
309
+ if (isRecord(part)) return stringField(part.text);
310
+ return undefined;
311
+ })
312
+ .filter((part): part is string => Boolean(part))
313
+ .join("\n\n");
314
+ }
315
+ return "";
316
+ }
317
+
318
+ function contentToChatContent(content: unknown): unknown {
319
+ if (content === null || typeof content === "string") return content;
320
+ if (!Array.isArray(content)) return content;
321
+
322
+ const textParts: string[] = [];
323
+ const richParts: JsonObject[] = [];
324
+ let hasNonText = false;
325
+
326
+ for (const part of content) {
327
+ if (!isRecord(part)) continue;
328
+ const type = stringField(part.type) ?? "";
329
+ if (type === "input_text" || type === "output_text" || type === "text") {
330
+ const text = stringField(part.text);
331
+ if (text) {
332
+ textParts.push(text);
333
+ richParts.push({ type: "text", text });
334
+ }
335
+ continue;
336
+ }
337
+ if (type === "refusal") {
338
+ const text = stringField(part.refusal);
339
+ if (text) textParts.push(text);
340
+ continue;
341
+ }
342
+ if (type === "input_image" && part.image_url) {
343
+ hasNonText = true;
344
+ const imageUrl = isRecord(part.image_url) ? part.image_url : { url: String(part.image_url) };
345
+ richParts.push({ type: "image_url", image_url: imageUrl });
346
+ }
347
+ }
348
+
349
+ if (!hasNonText) return textParts.join("\n");
350
+ return richParts;
351
+ }
352
+
353
+ function normalizeRole(role: unknown): "system" | "user" | "assistant" | "tool" {
354
+ const normalized = typeof role === "string" ? role.trim().toLowerCase() : "user";
355
+ if (normalized === "system" || normalized === "developer") return "system";
356
+ if (normalized === "assistant") return "assistant";
357
+ if (normalized === "tool") return "tool";
358
+ return "user";
359
+ }
360
+
361
+ function normalizeParameters(value: unknown): unknown {
362
+ const schema: JsonObject = isRecord(value) ? { ...value } : {};
363
+ if (!schema.type) schema.type = "object";
364
+ if (schema.type === "object") {
365
+ if (!isRecord(schema.properties)) schema.properties = {};
366
+ if (!Array.isArray(schema.required)) schema.required = [];
367
+ }
368
+ return schema;
369
+ }
370
+
371
+ function customToolParameters(): JsonObject {
372
+ return {
373
+ type: "object",
374
+ properties: {
375
+ input: { type: "string" },
376
+ },
377
+ required: ["input"],
378
+ additionalProperties: false,
379
+ };
380
+ }
381
+
382
+ function flattenNamespaceToolName(namespace: string, name: string): string {
383
+ if (!namespace) return name;
384
+ if (!name) return namespace;
385
+ if (namespace.endsWith("__") || name.startsWith("__")) return `${namespace}${name}`;
386
+ return `${namespace}__${name}`;
387
+ }
388
+
389
+ function combineDescriptions(parent: string | undefined, child: string | undefined): string | undefined {
390
+ const a = parent?.trim() ?? "";
391
+ const b = child?.trim() ?? "";
392
+ if (!a && !b) return undefined;
393
+ if (!a) return b;
394
+ if (!b) return a;
395
+ return `${a}\n\n${b}`;
396
+ }
397
+
398
+ function buildToolContext(tools: unknown): ToolContext {
399
+ const context: ToolContext = { specs: new Map() };
400
+ if (!Array.isArray(tools)) return context;
401
+
402
+ const addSpec = (spec: ToolSpec) => {
403
+ if (!spec.chatName) return;
404
+ context.specs.set(spec.chatName, spec);
405
+ };
406
+
407
+ for (const tool of tools) {
408
+ if (!isRecord(tool)) continue;
409
+ const type = stringField(tool.type) ?? "function";
410
+ if (type === "namespace") {
411
+ const namespace = stringField(tool.name) ?? "";
412
+ const children = Array.isArray(tool.tools) ? tool.tools : [];
413
+ for (const child of children) {
414
+ if (!isRecord(child)) continue;
415
+ const fn = isRecord(child.function) ? child.function : undefined;
416
+ const name = stringField(child.name) ?? stringField(fn?.name);
417
+ if (!name) continue;
418
+ const chatName = flattenNamespaceToolName(namespace, name);
419
+ addSpec({ chatName, originalName: name, namespace, kind: "function" });
420
+ }
421
+ continue;
422
+ }
423
+
424
+ const fn = isRecord(tool.function) ? tool.function : undefined;
425
+ const name =
426
+ stringField(tool.name)
427
+ ?? stringField(fn?.name)
428
+ ?? (type !== "function" ? type : undefined);
429
+ if (!name) continue;
430
+ addSpec({
431
+ chatName: name,
432
+ originalName: name,
433
+ kind: type === "custom" ? "custom" : "function",
434
+ });
435
+ }
436
+
437
+ return context;
438
+ }
439
+
440
+ function responsesToolsToChatTools(tools: unknown, context: ToolContext): ChatTool[] {
441
+ if (!Array.isArray(tools)) return [];
442
+ const converted: ChatTool[] = [];
443
+ const seen = new Set<string>();
444
+
445
+ const addTool = (chatName: string, description: string | undefined, parameters: unknown) => {
446
+ if (!chatName || seen.has(chatName)) return;
447
+ seen.add(chatName);
448
+ converted.push({
449
+ type: "function",
450
+ function: {
451
+ name: chatName,
452
+ ...(description ? { description } : {}),
453
+ parameters,
454
+ },
455
+ });
456
+ };
457
+
458
+ for (const tool of tools) {
459
+ if (!isRecord(tool)) continue;
460
+ const type = stringField(tool.type) ?? "function";
461
+ if (type === "namespace") {
462
+ const namespace = stringField(tool.name) ?? "";
463
+ const namespaceDescription = stringField(tool.description);
464
+ const children = Array.isArray(tool.tools) ? tool.tools : [];
465
+ for (const child of children) {
466
+ if (!isRecord(child)) continue;
467
+ const fn = isRecord(child.function) ? child.function : undefined;
468
+ const name = stringField(child.name) ?? stringField(fn?.name);
469
+ if (!name) continue;
470
+ const chatName = flattenNamespaceToolName(namespace, name);
471
+ const description = combineDescriptions(namespaceDescription, stringField(child.description) ?? stringField(fn?.description));
472
+ const parameters = child.parameters ?? fn?.parameters ?? child.input_schema ?? child.schema;
473
+ addTool(chatName, description, normalizeParameters(parameters));
474
+ }
475
+ continue;
476
+ }
477
+
478
+ const fn = isRecord(tool.function) ? tool.function : undefined;
479
+ const name =
480
+ stringField(tool.name)
481
+ ?? stringField(fn?.name)
482
+ ?? (type !== "function" ? type : undefined);
483
+ if (!name) continue;
484
+
485
+ const spec = context.specs.get(name);
486
+ const description = stringField(tool.description) ?? stringField(fn?.description);
487
+ const parameters = spec?.kind === "custom"
488
+ ? customToolParameters()
489
+ : normalizeParameters(tool.parameters ?? fn?.parameters ?? tool.input_schema ?? tool.schema);
490
+ addTool(name, description, parameters);
491
+ }
492
+
493
+ return converted;
494
+ }
495
+
496
+ function responsesToolChoiceToChat(toolChoice: unknown, context: ToolContext): unknown {
497
+ if (typeof toolChoice === "string") return toolChoice;
498
+ if (!isRecord(toolChoice)) return toolChoice;
499
+
500
+ const type = stringField(toolChoice.type);
501
+ if (type === "auto" || type === "none" || type === "required") return type;
502
+
503
+ const fn = isRecord(toolChoice.function) ? toolChoice.function : undefined;
504
+ const namespace = stringField(toolChoice.namespace) ?? stringField(fn?.namespace) ?? "";
505
+ const name = stringField(toolChoice.name) ?? stringField(fn?.name);
506
+ if (!name) return undefined;
507
+ const chatName = namespace ? flattenNamespaceToolName(namespace, name) : name;
508
+ if (!context.specs.has(chatName) && !context.specs.has(name)) return undefined;
509
+ return { type: "function", function: { name: chatName } };
510
+ }
511
+
512
+ function mapToolNameForChat(item: JsonObject, context: ToolContext): string {
513
+ const name = stringField(item.name) ?? "unknown_tool";
514
+ const namespace = stringField(item.namespace) ?? "";
515
+ const chatName = namespace ? flattenNamespaceToolName(namespace, name) : name;
516
+ if (context.specs.has(chatName)) return chatName;
517
+ return name;
518
+ }
519
+
520
+ function extractReasoningText(value: unknown): string | undefined {
521
+ if (!isRecord(value)) return undefined;
522
+
523
+ const direct = stringField(value.reasoning_content)
524
+ ?? stringField(value.reasoning)
525
+ ?? stringField(value.text);
526
+ if (direct) return direct;
527
+
528
+ const summary = value.summary;
529
+ if (Array.isArray(summary)) {
530
+ const parts = summary
531
+ .map((part) => isRecord(part) ? stringField(part.text) ?? stringField(part.summary) : undefined)
532
+ .filter((part): part is string => Boolean(part));
533
+ if (parts.length) return parts.join("\n\n");
534
+ }
535
+
536
+ const details = value.reasoning_details;
537
+ if (Array.isArray(details)) {
538
+ const parts: string[] = [];
539
+ for (const detail of details) {
540
+ if (!isRecord(detail)) continue;
541
+ const summaryText = stringField(detail.summary) ?? stringField(detail.text);
542
+ if (summaryText) parts.push(summaryText);
543
+ if (Array.isArray(detail.parts)) {
544
+ for (const part of detail.parts) {
545
+ if (isRecord(part)) {
546
+ const text = stringField(part.text);
547
+ if (text) parts.push(text);
548
+ }
549
+ }
550
+ }
551
+ }
552
+ if (parts.length) return parts.join("\n\n");
553
+ }
554
+
555
+ return undefined;
556
+ }
557
+
558
+ function attachToolCallToAssistant(
559
+ messages: ChatMessage[],
560
+ call: ChatToolCall,
561
+ reasoning: string | undefined,
562
+ forceReasoningPlaceholder: boolean,
563
+ ) {
564
+ const last = messages[messages.length - 1];
565
+ const canAttach = last?.role === "assistant" && !last.tool_call_id;
566
+ const target = canAttach
567
+ ? last
568
+ : (() => {
569
+ const message: ChatMessage = { role: "assistant", content: null };
570
+ messages.push(message);
571
+ return message;
572
+ })();
573
+
574
+ target.tool_calls = [...(target.tool_calls ?? []), call];
575
+ if (!target.reasoning_content?.trim() && (reasoning?.trim() || forceReasoningPlaceholder)) {
576
+ target.reasoning_content = reasoning?.trim() || "tool call";
577
+ }
578
+ }
579
+
580
+ function functionCallFromResponsesItem(item: JsonObject, context: ToolContext): ChatToolCall | null {
581
+ const callId = stringField(item.call_id) ?? stringField(item.id);
582
+ if (!callId) return null;
583
+ const name = mapToolNameForChat(item, context);
584
+ const args = canonicalJsonString(item.arguments ?? {});
585
+ return { id: callId, type: "function", function: { name, arguments: args } };
586
+ }
587
+
588
+ function customToolCallFromResponsesItem(item: JsonObject, context: ToolContext): ChatToolCall | null {
589
+ const callId = stringField(item.call_id) ?? stringField(item.id);
590
+ if (!callId) return null;
591
+ const name = mapToolNameForChat(item, context);
592
+ const input = item.input ?? item.arguments ?? "";
593
+ const args = typeof input === "string"
594
+ ? JSON.stringify({ input })
595
+ : canonicalJsonString(input);
596
+ return { id: callId, type: "function", function: { name, arguments: args } };
597
+ }
598
+
599
+ function appendResponsesInput(
600
+ input: unknown,
601
+ messages: ChatMessage[],
602
+ context: ToolContext,
603
+ forceReasoningPlaceholder: boolean,
604
+ ) {
605
+ const items = typeof input === "string" ? [input] : Array.isArray(input) ? input : isRecord(input) ? [input] : [];
606
+ let pendingReasoning: string | undefined;
607
+ let lastReasoning: string | undefined;
608
+
609
+ for (const item of items) {
610
+ if (typeof item === "string") {
611
+ messages.push({ role: "user", content: item });
612
+ pendingReasoning = undefined;
613
+ continue;
614
+ }
615
+ if (!isRecord(item)) continue;
616
+
617
+ const type = stringField(item.type);
618
+ if (type === "reasoning") {
619
+ pendingReasoning = appendText(pendingReasoning, extractReasoningText(item));
620
+ lastReasoning = appendText(lastReasoning, extractReasoningText(item));
621
+ continue;
622
+ }
623
+
624
+ if (type === "function_call") {
625
+ const call = functionCallFromResponsesItem(item, context);
626
+ if (call) {
627
+ const reasoning = appendText(pendingReasoning, extractReasoningText(item)) ?? lastReasoning;
628
+ attachToolCallToAssistant(messages, call, reasoning, forceReasoningPlaceholder);
629
+ pendingReasoning = undefined;
630
+ }
631
+ continue;
632
+ }
633
+
634
+ if (type === "custom_tool_call" || type === "tool_search_call") {
635
+ const call = customToolCallFromResponsesItem(item, context);
636
+ if (call) {
637
+ const reasoning = appendText(pendingReasoning, extractReasoningText(item)) ?? lastReasoning;
638
+ attachToolCallToAssistant(messages, call, reasoning, forceReasoningPlaceholder);
639
+ pendingReasoning = undefined;
640
+ }
641
+ continue;
642
+ }
643
+
644
+ if (type === "function_call_output" || type === "custom_tool_call_output" || type === "tool_search_output") {
645
+ const callId = stringField(item.call_id);
646
+ if (!callId) continue;
647
+ const output = item.output ?? item.content ?? item;
648
+ messages.push({ role: "tool", tool_call_id: callId, content: typeof output === "string" ? output : canonicalJsonString(output) });
649
+ pendingReasoning = undefined;
650
+ continue;
651
+ }
652
+
653
+ if (type === "tool_call" && isRecord(item.tool_use)) {
654
+ const toolUse = item.tool_use;
655
+ const callId = stringField(toolUse.id);
656
+ const name = stringField(toolUse.name);
657
+ if (callId && name) {
658
+ attachToolCallToAssistant(messages, {
659
+ id: callId,
660
+ type: "function",
661
+ function: { name, arguments: canonicalJsonString(toolUse.input ?? {}) },
662
+ }, pendingReasoning ?? lastReasoning, forceReasoningPlaceholder);
663
+ pendingReasoning = undefined;
664
+ }
665
+ continue;
666
+ }
667
+
668
+ if (type === "tool_result" && isRecord(item.content)) {
669
+ const callId = stringField(item.content.tool_use_id);
670
+ if (callId) {
671
+ messages.push({ role: "tool", tool_call_id: callId, content: canonicalJsonString(item.content.content ?? "") });
672
+ }
673
+ pendingReasoning = undefined;
674
+ continue;
675
+ }
676
+
677
+ if (type === "message" || item.role !== undefined || item.content !== undefined) {
678
+ const role = normalizeRole(item.role);
679
+ const content = contentToChatContent(item.content);
680
+ const message: ChatMessage = {
681
+ role,
682
+ content: role === "assistant" && (content === null || (Array.isArray(content) && content.length === 0)) ? "" : content,
683
+ };
684
+ if (role === "assistant") {
685
+ const reasoning = appendText(pendingReasoning, extractReasoningText(item));
686
+ if (reasoning) {
687
+ message.reasoning_content = reasoning;
688
+ lastReasoning = appendText(lastReasoning, reasoning);
689
+ }
690
+ } else {
691
+ pendingReasoning = undefined;
692
+ }
693
+ messages.push(message);
694
+ }
695
+ }
696
+
697
+ for (const message of messages) {
698
+ if (forceReasoningPlaceholder && message.role === "assistant" && message.tool_calls?.length && !message.reasoning_content?.trim()) {
699
+ message.reasoning_content = "tool call";
700
+ }
701
+ }
702
+ }
703
+
704
+ function collapseSystemMessagesToHead(messages: ChatMessage[]): ChatMessage[] {
705
+ const system: string[] = [];
706
+ const rest: ChatMessage[] = [];
707
+ for (const message of messages) {
708
+ if (message.role === "system" && typeof message.content === "string" && message.content.trim()) {
709
+ system.push(message.content);
710
+ } else {
711
+ rest.push(message);
712
+ }
713
+ }
714
+ return system.length ? [{ role: "system", content: system.join("\n\n") }, ...rest] : rest;
715
+ }
716
+
717
+ function detectProvider(modelId?: string, providerHint?: string): keyof typeof THINKING_MAPPINGS {
718
+ const model = (modelId ?? "").toLowerCase();
719
+ const text = `${model} ${providerHint ?? ""}`.toLowerCase();
720
+ if (model.includes("openrouter") || model.includes("deeprouter")) return "openrouter";
721
+ if (text.includes("openrouter") || text.includes("deeprouter")) return "openrouter";
722
+ if (text.includes("deepseek")) return "deepseek";
723
+ if (text.includes("siliconflow")) return "deepseek";
724
+ if (text.includes("kimi") || text.includes("moonshot")) return "kimi";
725
+ if (text.includes("qwen")) return "qwen";
726
+ if (text.includes("glm") || text.includes("zhipu") || text.includes("chatglm")) return "glm";
727
+ return "generic";
728
+ }
729
+
730
+ function requiresAssistantToolReasoning(modelId: string | undefined, providerHint: string | undefined): boolean {
731
+ const text = `${modelId ?? ""} ${providerHint ?? ""}`.toLowerCase();
732
+ return /deepseek|kimi|moonshot|siliconflow/.test(text);
733
+ }
734
+
735
+ function normalizeEffort(value?: string | null): ThinkingEffort {
736
+ if (!value) return "off";
737
+ const normalized = value.trim().toLowerCase();
738
+ if (normalized === "xhigh" || normalized === "max") return "xhigh";
739
+ if (normalized === "high") return "high";
740
+ if (normalized === "medium") return "medium";
741
+ if (normalized === "low") return "low";
742
+ if (normalized === "minimal") return "minimal";
743
+ if (normalized === "off" || normalized === "none" || normalized === "disabled" || normalized === "false") return "off";
744
+ return "medium";
745
+ }
746
+
747
+ function applyThinking(chat: ChatRequestBody, body: ResponsesRequestBody, defaultThinking: string, providerHint?: string, customMapping?: ThinkingMapping) {
748
+ const provider = detectProvider(body.model, providerHint);
749
+ const mapping = customMapping ?? (THINKING_MAPPINGS[provider] ?? THINKING_MAPPINGS.generic);
750
+
751
+ const explicitReasoning = body.reasoning !== undefined;
752
+ let requested = normalizeEffort(defaultThinking);
753
+ if (explicitReasoning) {
754
+ if (!body.reasoning || body.reasoning.enabled === false) requested = "off";
755
+ else requested = normalizeEffort(body.reasoning.effort);
756
+ }
757
+
758
+ const mapped = mapping.effortMap[requested];
759
+ if (mapped === null) {
760
+ if (explicitReasoning && mapping.effortParam === "reasoning.effort") {
761
+ chat.reasoning = { effort: "none" };
762
+ }
763
+ return;
764
+ }
765
+
766
+ if (mapping.thinkingParam === "enable_thinking") chat.enable_thinking = true;
767
+ else if (mapping.thinkingParam === "thinking") chat.thinking = { type: "enabled" };
768
+
769
+ if (mapping.supportsEffort && mapped !== "enabled") {
770
+ if (mapping.effortParam === "reasoning.effort") chat.reasoning = { effort: mapped };
771
+ else chat.reasoning_effort = mapped;
772
+ }
773
+ }
774
+
775
+ function responsesToChat(
776
+ body: ResponsesRequestBody,
777
+ defaultThinking: string,
778
+ context = buildToolContext(body.tools),
779
+ providerHint?: string,
780
+ customMapping?: ThinkingMapping,
781
+ ): ChatRequestBody {
782
+ const messages: ChatMessage[] = [];
783
+ const instructions = instructionText(body.instructions);
784
+ if (instructions) messages.push({ role: "system", content: instructions });
785
+ appendResponsesInput(body.input, messages, context, requiresAssistantToolReasoning(body.model, providerHint));
786
+
787
+ const model = body.model || "deepseek-chat";
788
+ const chat: ChatRequestBody = {
789
+ model,
790
+ messages: collapseSystemMessagesToHead(messages),
791
+ };
792
+
793
+ if (body.max_output_tokens !== undefined) chat.max_tokens = body.max_output_tokens;
794
+ if (body.max_tokens !== undefined) chat.max_tokens = body.max_tokens;
795
+ if (body.max_completion_tokens !== undefined) chat.max_completion_tokens = body.max_completion_tokens;
796
+ if (body.temperature !== undefined) chat.temperature = body.temperature;
797
+ if (body.top_p !== undefined) chat.top_p = body.top_p;
798
+ if (body.stream !== undefined) chat.stream = body.stream;
799
+ if (body.stop !== undefined) chat.stop = body.stop;
800
+ if (body.frequency_penalty !== undefined) chat.frequency_penalty = body.frequency_penalty;
801
+ if (body.presence_penalty !== undefined) chat.presence_penalty = body.presence_penalty;
802
+
803
+ applyThinking(chat, body, defaultThinking, providerHint, customMapping);
804
+
805
+ const tools = responsesToolsToChatTools(body.tools, context);
806
+ if (tools.length) {
807
+ chat.tools = tools;
808
+ if (body.parallel_tool_calls !== undefined) chat.parallel_tool_calls = body.parallel_tool_calls;
809
+ const toolChoice = responsesToolChoiceToChat(body.tool_choice, context);
810
+ if (toolChoice !== undefined) chat.tool_choice = toolChoice;
811
+ }
812
+
813
+ for (const key of EXTRA_CHAT_PASSTHROUGH_FIELDS) {
814
+ if (body[key] !== undefined) chat[key] = body[key];
815
+ }
816
+
817
+ if (chat.stream) {
818
+ chat.stream_options = {
819
+ ...(isRecord(body.stream_options) ? body.stream_options : {}),
820
+ include_usage: true,
821
+ };
822
+ }
823
+
824
+ return chat;
825
+ }
826
+
827
+ function responseStatus(finishReason?: string | null): string {
828
+ if (finishReason === "length") return "incomplete";
829
+ return "completed";
830
+ }
831
+
832
+ function defaultUsage(): JsonObject {
833
+ return { input_tokens: 0, output_tokens: 0, total_tokens: 0 };
834
+ }
835
+
836
+ function chatUsageToResponsesUsage(value: unknown): JsonObject {
837
+ if (!isRecord(value)) return defaultUsage();
838
+ const input = Number(value.prompt_tokens ?? value.input_tokens ?? 0);
839
+ const output = Number(value.completion_tokens ?? value.output_tokens ?? 0);
840
+ const total = Number(value.total_tokens ?? input + output);
841
+ const usage: JsonObject = {
842
+ input_tokens: input,
843
+ output_tokens: output,
844
+ total_tokens: total,
845
+ };
846
+ if (isRecord(value.prompt_tokens_details)) usage.input_tokens_details = value.prompt_tokens_details;
847
+ if (isRecord(value.completion_tokens_details)) usage.output_tokens_details = value.completion_tokens_details;
848
+ return usage;
849
+ }
850
+
851
+ function responseReasoningItem(responseId: string, text: string): JsonObject {
852
+ return {
853
+ id: `rs_${responseId}`,
854
+ type: "reasoning",
855
+ reasoning_content: text,
856
+ summary: [{ type: "summary_text", text }],
857
+ };
858
+ }
859
+
860
+ function customToolInputFromArguments(argumentsText: string): string {
861
+ try {
862
+ const parsed = JSON.parse(argumentsText) as unknown;
863
+ if (isRecord(parsed) && typeof parsed.input === "string") return parsed.input;
864
+ } catch {
865
+ // Keep raw text for non-JSON custom tool calls.
866
+ }
867
+ return argumentsText;
868
+ }
869
+
870
+ function responseToolCallItem(
871
+ callId: string,
872
+ chatName: string,
873
+ argumentsText: string,
874
+ status: "in_progress" | "completed",
875
+ context: ToolContext,
876
+ ): JsonObject {
877
+ const spec = context.specs.get(chatName);
878
+ if (spec?.kind === "custom") {
879
+ return {
880
+ id: `ctc_${callId}`,
881
+ type: "custom_tool_call",
882
+ status,
883
+ call_id: callId,
884
+ name: spec.originalName,
885
+ input: customToolInputFromArguments(argumentsText),
886
+ };
887
+ }
888
+
889
+ const item: JsonObject = {
890
+ id: `fc_${callId}`,
891
+ type: "function_call",
892
+ status,
893
+ call_id: callId,
894
+ name: spec?.originalName ?? chatName,
895
+ arguments: argumentsText,
896
+ };
897
+ if (spec?.namespace) item.namespace = spec.namespace;
898
+ return item;
899
+ }
900
+
901
+ function chatToResponses(chatResp: JsonObject, fallbackModel: string, context: ToolContext): JsonObject {
902
+ const responseId = `resp_${randomBytes(12).toString("hex")}`;
903
+ const choices = Array.isArray(chatResp.choices) ? chatResp.choices : [];
904
+ const choice = isRecord(choices[0]) ? choices[0] : {};
905
+ const message = isRecord(choice.message) ? choice.message : {};
906
+ const output: JsonObject[] = [];
907
+
908
+ const reasoning = extractReasoningText(message);
909
+ if (reasoning) output.push(responseReasoningItem(responseId, reasoning));
910
+
911
+ const content = typeof message.content === "string" ? message.content : "";
912
+ if (content) {
913
+ output.push({
914
+ id: `msg_${randomBytes(12).toString("hex")}`,
915
+ type: "message",
916
+ status: "completed",
917
+ role: "assistant",
918
+ content: [{ type: "output_text", text: content, annotations: [] }],
919
+ });
920
+ }
921
+
922
+ const toolCalls = Array.isArray(message.tool_calls) ? message.tool_calls : [];
923
+ for (const toolCall of toolCalls) {
924
+ if (!isRecord(toolCall)) continue;
925
+ const fn = isRecord(toolCall.function) ? toolCall.function : {};
926
+ const callId = stringField(toolCall.id) ?? `call_${output.length}`;
927
+ const name = stringField(fn.name) ?? "unknown_tool";
928
+ const args = canonicalizeJsonStringIfParseable(typeof fn.arguments === "string" ? fn.arguments : "{}");
929
+ output.push(responseToolCallItem(callId, name, args, "completed", context));
930
+ }
931
+
932
+ const status = responseStatus(stringField(choice.finish_reason));
933
+ const response: JsonObject = {
934
+ id: responseId,
935
+ object: "response",
936
+ created_at: typeof chatResp.created === "number" ? chatResp.created : Math.floor(Date.now() / 1000),
937
+ status,
938
+ model: stringField(chatResp.model) ?? fallbackModel,
939
+ output,
940
+ usage: chatUsageToResponsesUsage(chatResp.usage),
941
+ };
942
+ if (status === "incomplete") response.incomplete_details = { reason: "max_output_tokens" };
943
+ return response;
944
+ }
945
+
946
+ function formatSSE(event: string, payload: unknown): string {
947
+ return `event: ${event}\ndata: ${JSON.stringify(payload)}\n\n`;
948
+ }
949
+
950
+ function createStreamState(model: string, context: ToolContext): SSEStreamState {
951
+ const responseId = `resp_${randomBytes(12).toString("hex")}`;
952
+ return {
953
+ responseId,
954
+ messageId: `msg_${randomBytes(12).toString("hex")}`,
955
+ reasoningId: `rs_${responseId}`,
956
+ createdAt: Math.floor(Date.now() / 1000),
957
+ model: model || "deepseek-chat",
958
+ text: "",
959
+ textStarted: false,
960
+ contentStarted: false,
961
+ messageOutputIndex: null,
962
+ reasoningText: "",
963
+ reasoningStarted: false,
964
+ reasoningDone: false,
965
+ reasoningOutputIndex: null,
966
+ inlineThinkMode: "detecting",
967
+ inlineThinkBuffer: "",
968
+ nextOutputIndex: 0,
969
+ toolCalls: [],
970
+ outputItems: [],
971
+ finalUsage: null,
972
+ finishReason: null,
973
+ toolContext: context,
974
+ };
975
+ }
976
+
977
+ function baseResponse(state: SSEStreamState, status: string, output: JsonObject[] = []): JsonObject {
978
+ return {
979
+ id: state.responseId,
980
+ object: "response",
981
+ created_at: state.createdAt,
982
+ status,
983
+ model: state.model,
984
+ output,
985
+ usage: state.finalUsage ?? defaultUsage(),
986
+ };
987
+ }
988
+
989
+ function startedStreamEvents(state: SSEStreamState): string {
990
+ const response = baseResponse(state, "in_progress");
991
+ return formatSSE("response.created", { type: "response.created", response })
992
+ + formatSSE("response.in_progress", { type: "response.in_progress", response });
993
+ }
994
+
995
+ function nextOutputIndex(state: SSEStreamState): number {
996
+ return state.nextOutputIndex++;
997
+ }
998
+
999
+ function pushReasoningDelta(state: SSEStreamState, delta: string): string[] {
1000
+ if (!delta) return [];
1001
+ const events: string[] = [];
1002
+ if (!state.reasoningStarted) {
1003
+ state.reasoningStarted = true;
1004
+ state.reasoningOutputIndex = nextOutputIndex(state);
1005
+ events.push(formatSSE("response.output_item.added", {
1006
+ type: "response.output_item.added",
1007
+ output_index: state.reasoningOutputIndex,
1008
+ item: {
1009
+ id: state.reasoningId,
1010
+ type: "reasoning",
1011
+ status: "in_progress",
1012
+ reasoning_content: "",
1013
+ summary: [],
1014
+ },
1015
+ }));
1016
+ events.push(formatSSE("response.reasoning_summary_part.added", {
1017
+ type: "response.reasoning_summary_part.added",
1018
+ item_id: state.reasoningId,
1019
+ output_index: state.reasoningOutputIndex,
1020
+ summary_index: 0,
1021
+ part: { type: "summary_text", text: "" },
1022
+ }));
1023
+ }
1024
+
1025
+ state.reasoningText += delta;
1026
+ events.push(formatSSE("response.reasoning_summary_text.delta", {
1027
+ type: "response.reasoning_summary_text.delta",
1028
+ item_id: state.reasoningId,
1029
+ output_index: state.reasoningOutputIndex ?? 0,
1030
+ summary_index: 0,
1031
+ delta,
1032
+ }));
1033
+ return events;
1034
+ }
1035
+
1036
+ function finalizeReasoning(state: SSEStreamState): string[] {
1037
+ if (!state.reasoningStarted || state.reasoningDone) return [];
1038
+ const outputIndex = state.reasoningOutputIndex ?? 0;
1039
+ const item = responseReasoningItem(state.responseId, state.reasoningText);
1040
+ state.outputItems.push({ outputIndex, item });
1041
+ state.reasoningDone = true;
1042
+ return [
1043
+ formatSSE("response.reasoning_summary_text.done", {
1044
+ type: "response.reasoning_summary_text.done",
1045
+ item_id: state.reasoningId,
1046
+ output_index: outputIndex,
1047
+ summary_index: 0,
1048
+ text: state.reasoningText,
1049
+ }),
1050
+ formatSSE("response.reasoning_summary_part.done", {
1051
+ type: "response.reasoning_summary_part.done",
1052
+ item_id: state.reasoningId,
1053
+ output_index: outputIndex,
1054
+ summary_index: 0,
1055
+ part: { type: "summary_text", text: state.reasoningText },
1056
+ }),
1057
+ formatSSE("response.output_item.done", {
1058
+ type: "response.output_item.done",
1059
+ output_index: outputIndex,
1060
+ item,
1061
+ }),
1062
+ ];
1063
+ }
1064
+
1065
+ function pushTextDelta(state: SSEStreamState, delta: string): string[] {
1066
+ if (!delta) return [];
1067
+ const events: string[] = [];
1068
+ if (!state.textStarted) {
1069
+ state.textStarted = true;
1070
+ state.messageOutputIndex = nextOutputIndex(state);
1071
+ events.push(formatSSE("response.output_item.added", {
1072
+ type: "response.output_item.added",
1073
+ output_index: state.messageOutputIndex,
1074
+ item: {
1075
+ id: state.messageId,
1076
+ type: "message",
1077
+ status: "in_progress",
1078
+ role: "assistant",
1079
+ content: [],
1080
+ },
1081
+ }));
1082
+ }
1083
+ if (!state.contentStarted) {
1084
+ state.contentStarted = true;
1085
+ events.push(formatSSE("response.content_part.added", {
1086
+ type: "response.content_part.added",
1087
+ item_id: state.messageId,
1088
+ output_index: state.messageOutputIndex ?? 0,
1089
+ content_index: 0,
1090
+ part: { type: "output_text", text: "", annotations: [] },
1091
+ }));
1092
+ }
1093
+
1094
+ state.text += delta;
1095
+ events.push(formatSSE("response.output_text.delta", {
1096
+ type: "response.output_text.delta",
1097
+ item_id: state.messageId,
1098
+ output_index: state.messageOutputIndex ?? 0,
1099
+ content_index: 0,
1100
+ delta,
1101
+ }));
1102
+ return events;
1103
+ }
1104
+
1105
+ function finalizeText(state: SSEStreamState): string[] {
1106
+ if (!state.textStarted) return [];
1107
+ const outputIndex = state.messageOutputIndex ?? 0;
1108
+ const item: JsonObject = {
1109
+ id: state.messageId,
1110
+ type: "message",
1111
+ status: "completed",
1112
+ role: "assistant",
1113
+ content: [{ type: "output_text", text: state.text, annotations: [] }],
1114
+ };
1115
+ state.outputItems.push({ outputIndex, item });
1116
+ return [
1117
+ formatSSE("response.output_text.done", {
1118
+ type: "response.output_text.done",
1119
+ item_id: state.messageId,
1120
+ output_index: outputIndex,
1121
+ content_index: 0,
1122
+ text: state.text,
1123
+ }),
1124
+ formatSSE("response.content_part.done", {
1125
+ type: "response.content_part.done",
1126
+ item_id: state.messageId,
1127
+ output_index: outputIndex,
1128
+ content_index: 0,
1129
+ part: { type: "output_text", text: state.text, annotations: [] },
1130
+ }),
1131
+ formatSSE("response.output_item.done", {
1132
+ type: "response.output_item.done",
1133
+ output_index: outputIndex,
1134
+ item,
1135
+ }),
1136
+ ];
1137
+ }
1138
+
1139
+ function handleContentDelta(state: SSEStreamState, delta: string): string[] {
1140
+ if (!delta) return [];
1141
+ const events: string[] = [];
1142
+
1143
+ if (state.inlineThinkMode === "text") {
1144
+ events.push(...finalizeReasoning(state));
1145
+ events.push(...pushTextDelta(state, delta));
1146
+ return events;
1147
+ }
1148
+
1149
+ state.inlineThinkBuffer += delta;
1150
+ if (state.inlineThinkMode === "detecting") {
1151
+ const trimmed = state.inlineThinkBuffer.trimStart();
1152
+ if (!trimmed) return events;
1153
+ if (trimmed.startsWith(THINK_OPEN_TAG)) {
1154
+ state.inlineThinkMode = "reasoning";
1155
+ state.inlineThinkBuffer = trimmed.slice(THINK_OPEN_TAG.length);
1156
+ } else if (THINK_OPEN_TAG.startsWith(trimmed)) {
1157
+ return events;
1158
+ } else {
1159
+ state.inlineThinkMode = "text";
1160
+ const text = state.inlineThinkBuffer;
1161
+ state.inlineThinkBuffer = "";
1162
+ events.push(...finalizeReasoning(state));
1163
+ events.push(...pushTextDelta(state, text));
1164
+ return events;
1165
+ }
1166
+ }
1167
+
1168
+ if (state.inlineThinkMode === "reasoning") {
1169
+ const closeIndex = state.inlineThinkBuffer.indexOf(THINK_CLOSE_TAG);
1170
+ if (closeIndex === -1) return events;
1171
+ const reasoning = state.inlineThinkBuffer.slice(0, closeIndex);
1172
+ const answer = state.inlineThinkBuffer.slice(closeIndex + THINK_CLOSE_TAG.length);
1173
+ state.inlineThinkBuffer = "";
1174
+ state.inlineThinkMode = "text";
1175
+ events.push(...pushReasoningDelta(state, reasoning));
1176
+ events.push(...finalizeReasoning(state));
1177
+ events.push(...pushTextDelta(state, answer));
1178
+ }
1179
+
1180
+ return events;
1181
+ }
1182
+
1183
+ function flushInlineThink(state: SSEStreamState): string[] {
1184
+ const events: string[] = [];
1185
+ if (!state.inlineThinkBuffer) return events;
1186
+ if (state.inlineThinkMode === "reasoning") {
1187
+ const closeIndex = state.inlineThinkBuffer.indexOf(THINK_CLOSE_TAG);
1188
+ const reasoning = closeIndex === -1
1189
+ ? state.inlineThinkBuffer
1190
+ : state.inlineThinkBuffer.slice(0, closeIndex);
1191
+ const answer = closeIndex === -1
1192
+ ? ""
1193
+ : state.inlineThinkBuffer.slice(closeIndex + THINK_CLOSE_TAG.length);
1194
+ events.push(...pushReasoningDelta(state, reasoning));
1195
+ events.push(...finalizeReasoning(state));
1196
+ events.push(...pushTextDelta(state, answer));
1197
+ } else {
1198
+ events.push(...finalizeReasoning(state));
1199
+ events.push(...pushTextDelta(state, state.inlineThinkBuffer));
1200
+ }
1201
+ state.inlineThinkBuffer = "";
1202
+ state.inlineThinkMode = "text";
1203
+ return events;
1204
+ }
1205
+
1206
+ function toolCallItemId(callId: string, chatName: string, context: ToolContext): string {
1207
+ const spec = context.specs.get(chatName);
1208
+ return `${spec?.kind === "custom" ? "ctc" : "fc"}_${callId}`;
1209
+ }
1210
+
1211
+ function pushToolCallDelta(state: SSEStreamState, toolCall: JsonObject): string[] {
1212
+ const events: string[] = [];
1213
+ const index = typeof toolCall.index === "number" ? toolCall.index : state.toolCalls.length;
1214
+ const fn = isRecord(toolCall.function) ? toolCall.function : {};
1215
+ let current = state.toolCalls[index];
1216
+ const id = stringField(toolCall.id);
1217
+ const name = stringField(fn.name);
1218
+ const argsDelta = typeof fn.arguments === "string" ? fn.arguments : "";
1219
+
1220
+ if (!current) {
1221
+ const callId = id ?? `call_${index}`;
1222
+ const chatName = name ?? "unknown_tool";
1223
+ current = {
1224
+ outputIndex: nextOutputIndex(state),
1225
+ itemId: toolCallItemId(callId, chatName, state.toolContext),
1226
+ callId,
1227
+ name: chatName,
1228
+ arguments: "",
1229
+ done: false,
1230
+ };
1231
+ state.toolCalls[index] = current;
1232
+ events.push(formatSSE("response.output_item.added", {
1233
+ type: "response.output_item.added",
1234
+ output_index: current.outputIndex,
1235
+ item: responseToolCallItem(current.callId, current.name, "", "in_progress", state.toolContext),
1236
+ }));
1237
+ }
1238
+
1239
+ if (id) current.callId = id;
1240
+ if (name && current.name === "unknown_tool") {
1241
+ current.name = name;
1242
+ current.itemId = toolCallItemId(current.callId, current.name, state.toolContext);
1243
+ }
1244
+
1245
+ if (argsDelta) {
1246
+ current.arguments += argsDelta;
1247
+ const spec = state.toolContext.specs.get(current.name);
1248
+ if (spec?.kind !== "custom") {
1249
+ events.push(formatSSE("response.function_call_arguments.delta", {
1250
+ type: "response.function_call_arguments.delta",
1251
+ item_id: current.itemId,
1252
+ output_index: current.outputIndex,
1253
+ delta: argsDelta,
1254
+ }));
1255
+ }
1256
+ }
1257
+
1258
+ return events;
1259
+ }
1260
+
1261
+ function finalizeTools(state: SSEStreamState): string[] {
1262
+ const events: string[] = [];
1263
+ for (const toolCall of state.toolCalls) {
1264
+ if (!toolCall || toolCall.done) continue;
1265
+ toolCall.done = true;
1266
+ const args = canonicalizeJsonStringIfParseable(toolCall.arguments);
1267
+ const spec = state.toolContext.specs.get(toolCall.name);
1268
+ if (spec?.kind === "custom") {
1269
+ const input = customToolInputFromArguments(args);
1270
+ if (input) {
1271
+ events.push(formatSSE("response.custom_tool_call_input.delta", {
1272
+ type: "response.custom_tool_call_input.delta",
1273
+ item_id: toolCall.itemId,
1274
+ output_index: toolCall.outputIndex,
1275
+ delta: input,
1276
+ }));
1277
+ }
1278
+ events.push(formatSSE("response.custom_tool_call_input.done", {
1279
+ type: "response.custom_tool_call_input.done",
1280
+ item_id: toolCall.itemId,
1281
+ output_index: toolCall.outputIndex,
1282
+ input,
1283
+ }));
1284
+ } else {
1285
+ events.push(formatSSE("response.function_call_arguments.done", {
1286
+ type: "response.function_call_arguments.done",
1287
+ item_id: toolCall.itemId,
1288
+ output_index: toolCall.outputIndex,
1289
+ arguments: args,
1290
+ }));
1291
+ }
1292
+
1293
+ const item = responseToolCallItem(toolCall.callId, toolCall.name, args, "completed", state.toolContext);
1294
+ state.outputItems.push({ outputIndex: toolCall.outputIndex, item });
1295
+ events.push(formatSSE("response.output_item.done", {
1296
+ type: "response.output_item.done",
1297
+ output_index: toolCall.outputIndex,
1298
+ item,
1299
+ }));
1300
+ }
1301
+ return events;
1302
+ }
1303
+
1304
+ function translateChatSSEToResponsesEvents(chunk: JsonObject, state: SSEStreamState): string[] {
1305
+ const events: string[] = [];
1306
+ const model = stringField(chunk.model);
1307
+ if (model) state.model = model;
1308
+ if (isRecord(chunk.usage)) state.finalUsage = chatUsageToResponsesUsage(chunk.usage);
1309
+
1310
+ const choices = Array.isArray(chunk.choices) ? chunk.choices : [];
1311
+ const choice = isRecord(choices[0]) ? choices[0] : undefined;
1312
+ if (!choice) return events;
1313
+
1314
+ if (typeof choice.finish_reason === "string") state.finishReason = choice.finish_reason;
1315
+ const delta = isRecord(choice.delta) ? choice.delta : {};
1316
+
1317
+ const reasoningDelta = stringField(delta.reasoning_content) ?? stringField(delta.reasoning);
1318
+ if (reasoningDelta) {
1319
+ events.push(...pushReasoningDelta(state, reasoningDelta));
1320
+ }
1321
+
1322
+ const contentDelta = typeof delta.content === "string" ? delta.content : "";
1323
+ if (contentDelta) {
1324
+ events.push(...handleContentDelta(state, contentDelta));
1325
+ }
1326
+
1327
+ if (Array.isArray(delta.tool_calls)) {
1328
+ events.push(...flushInlineThink(state));
1329
+ events.push(...finalizeReasoning(state));
1330
+ for (const toolCall of delta.tool_calls) {
1331
+ if (isRecord(toolCall)) events.push(...pushToolCallDelta(state, toolCall));
1332
+ }
1333
+ }
1334
+
1335
+ return events;
1336
+ }
1337
+
1338
+ function sseStreamFinalize(state: SSEStreamState): string[] {
1339
+ const events: string[] = [];
1340
+ events.push(...flushInlineThink(state));
1341
+ events.push(...finalizeReasoning(state));
1342
+ events.push(...finalizeText(state));
1343
+ events.push(...finalizeTools(state));
1344
+
1345
+ const sorted = [...state.outputItems].sort((a, b) => a.outputIndex - b.outputIndex).map((entry) => entry.item);
1346
+ const status = responseStatus(state.finishReason);
1347
+ const response = baseResponse(state, status, sorted);
1348
+ if (status === "incomplete") response.incomplete_details = { reason: "max_output_tokens" };
1349
+ events.push(formatSSE("response.completed", {
1350
+ type: "response.completed",
1351
+ response,
1352
+ }));
1353
+ events.push("data: [DONE]\n\n");
1354
+ return events;
1355
+ }
1356
+
1357
+ function responsesErrorFromUpstream(statusCode: number, contentType: string | undefined, body: Buffer): JsonObject {
1358
+ let message = body.toString("utf8").slice(0, ERROR_BODY_PREVIEW_LIMIT);
1359
+ let type = "upstream_error";
1360
+ let code: string | number = statusCode;
1361
+ let param: unknown;
1362
+
1363
+ if (contentType?.toLowerCase().includes("json")) {
1364
+ try {
1365
+ const parsed = JSON.parse(body.toString("utf8")) as unknown;
1366
+ const error = isRecord(parsed) && isRecord(parsed.error) ? parsed.error : parsed;
1367
+ if (isRecord(error)) {
1368
+ message = stringField(error.message) ?? stringField(error.detail) ?? message;
1369
+ type = stringField(error.type) ?? stringField(error.error_type) ?? type;
1370
+ code = error.code as string | number ?? code;
1371
+ param = error.param;
1372
+ }
1373
+ } catch {
1374
+ // Keep plain text preview.
1375
+ }
1376
+ }
1377
+
1378
+ const error: JsonObject = { message: message || `Upstream returned HTTP ${statusCode}`, type, code };
1379
+ if (param !== undefined) error.param = param;
1380
+ return { error };
1381
+ }
1382
+
1383
+ function appendStreamChunk(buffer: { value: string }, chunk: Buffer, state: SSEStreamState, res: ServerResponse) {
1384
+ buffer.value += chunk.toString("utf8");
1385
+ while (buffer.value.includes("\n")) {
1386
+ const newlineIndex = buffer.value.indexOf("\n");
1387
+ const line = buffer.value.slice(0, newlineIndex).trim();
1388
+ buffer.value = buffer.value.slice(newlineIndex + 1);
1389
+ if (!line || line.startsWith(":")) continue;
1390
+ if (line === "data: [DONE]") continue;
1391
+ if (!line.startsWith("data: ")) continue;
1392
+ try {
1393
+ const payload = JSON.parse(line.slice(6)) as unknown;
1394
+ if (isRecord(payload)) {
1395
+ for (const event of translateChatSSEToResponsesEvents(payload, state)) res.write(event);
1396
+ }
1397
+ } catch {
1398
+ // Ignore malformed upstream chunks.
1399
+ }
1400
+ }
1401
+ }
1402
+
1403
+ function hasVersionSuffix(baseUrl: string): boolean {
1404
+ const segment = baseUrl.split("/").pop() ?? "";
1405
+ return /^v\d+/i.test(segment);
1406
+ }
1407
+
1408
+ export function chatCompletionsUrl(baseUrl: string): string {
1409
+ const base = baseUrl.trim().replace(/#+$/, "").replace(/\/+$/, "");
1410
+ if (!base) return base;
1411
+ if (/\/chat\/completions$/i.test(base)) return base;
1412
+ const rest = base.split("://")[1] ?? base;
1413
+ const originOnly = !rest.includes("/");
1414
+ let url = originOnly && !hasVersionSuffix(base)
1415
+ ? `${base}/v1/chat/completions`
1416
+ : `${base}/chat/completions`;
1417
+ while (url.includes("/v1/v1/")) url = url.replace("/v1/v1/", "/v1/");
1418
+ return url;
1419
+ }
1420
+
1421
+ export class CompatProxy {
1422
+ private server: ReturnType<typeof createServer> | null = null;
1423
+ private port = 0;
1424
+ public readonly targetUrl: string;
1425
+ public readonly apiKey: string;
1426
+ public readonly defaultThinking: string;
1427
+ public readonly reasoningConfig?: ReasoningConfig;
1428
+
1429
+ constructor(opts: ProxyOptions) {
1430
+ this.targetUrl = chatCompletionsUrl(opts.targetUrl);
1431
+ this.apiKey = opts.apiKey;
1432
+ this.defaultThinking = opts.defaultThinking ?? "disabled";
1433
+ this.reasoningConfig = opts.reasoningConfig;
1434
+ if (opts.port) this.port = opts.port;
1435
+ }
1436
+
1437
+ async start(): Promise<number> {
1438
+ return new Promise((resolve, reject) => {
1439
+ this.server = createServer((req, res) => this.handleRequest(req, res));
1440
+ this.server.on("error", reject);
1441
+ this.server.listen(this.port, "127.0.0.1", () => {
1442
+ const addr = this.server?.address();
1443
+ if (addr && typeof addr === "object") {
1444
+ this.port = addr.port;
1445
+ resolve(this.port);
1446
+ } else {
1447
+ reject(new Error("Failed to get server address"));
1448
+ }
1449
+ });
1450
+ });
1451
+ }
1452
+
1453
+ async stop(): Promise<void> {
1454
+ return new Promise((resolve) => {
1455
+ if (!this.server) {
1456
+ resolve();
1457
+ return;
1458
+ }
1459
+ this.server.close(() => resolve());
1460
+ this.server = null;
1461
+ });
1462
+ }
1463
+
1464
+ getPort(): number {
1465
+ return this.port;
1466
+ }
1467
+
1468
+ getBaseUrl(): string {
1469
+ return `http://127.0.0.1:${this.port}/v1`;
1470
+ }
1471
+
1472
+ private handleRequest(req: IncomingMessage, res: ServerResponse): void {
1473
+ if (req.url === "/health") {
1474
+ res.writeHead(200, { "Content-Type": "application/json" });
1475
+ res.end(JSON.stringify({ status: "ok", target: this.targetUrl }));
1476
+ return;
1477
+ }
1478
+ if (req.method !== "POST" || !req.url?.startsWith("/v1/responses")) {
1479
+ res.writeHead(404);
1480
+ res.end();
1481
+ return;
1482
+ }
1483
+
1484
+ const chunks: Buffer[] = [];
1485
+ req.on("data", (chunk: Buffer) => chunks.push(chunk));
1486
+ req.on("end", () => {
1487
+ try {
1488
+ const body = JSON.parse(Buffer.concat(chunks).toString()) as ResponsesRequestBody;
1489
+ this.proxyRequest(body, res);
1490
+ } catch {
1491
+ res.writeHead(400, { "Content-Type": "application/json" });
1492
+ res.end(JSON.stringify({ error: { message: "Invalid JSON", type: "invalid_request_error" } }));
1493
+ }
1494
+ });
1495
+ }
1496
+
1497
+ private proxyRequest(body: ResponsesRequestBody, res: ServerResponse): void {
1498
+ const context = buildToolContext(body.tools);
1499
+ const customMapping = this.reasoningConfig ? buildThinkingMapping(this.reasoningConfig) : undefined;
1500
+ const chatBody = responsesToChat(body, this.defaultThinking, context, this.targetUrl, customMapping);
1501
+ const targetUrl = new URL(this.targetUrl);
1502
+ const isHttps = targetUrl.protocol === "https:";
1503
+ const requestFn = isHttps ? httpsRequest : httpRequest;
1504
+
1505
+ const upstreamReq = requestFn({
1506
+ hostname: targetUrl.hostname,
1507
+ port: targetUrl.port || (isHttps ? 443 : 80),
1508
+ path: targetUrl.pathname + targetUrl.search,
1509
+ method: "POST",
1510
+ headers: {
1511
+ "Content-Type": "application/json",
1512
+ Authorization: `Bearer ${this.apiKey}`,
1513
+ },
1514
+ }, (upstreamRes) => {
1515
+ const statusCode = upstreamRes.statusCode ?? 502;
1516
+ const contentType = String(upstreamRes.headers["content-type"] ?? "");
1517
+ const upstreamIsStream = chatBody.stream === true || contentType.includes("text/event-stream");
1518
+
1519
+ if (statusCode < 200 || statusCode >= 300) {
1520
+ const errorChunks: Buffer[] = [];
1521
+ upstreamRes.on("data", (chunk: Buffer) => errorChunks.push(chunk));
1522
+ upstreamRes.on("end", () => {
1523
+ const error = responsesErrorFromUpstream(statusCode, contentType, Buffer.concat(errorChunks));
1524
+ res.writeHead(statusCode, { "Content-Type": "application/json" });
1525
+ res.end(JSON.stringify(error));
1526
+ });
1527
+ return;
1528
+ }
1529
+
1530
+ if (upstreamIsStream) {
1531
+ const state = createStreamState(chatBody.model, context);
1532
+ res.writeHead(200, {
1533
+ "Content-Type": "text/event-stream",
1534
+ "Cache-Control": "no-cache",
1535
+ Connection: "keep-alive",
1536
+ });
1537
+ res.write(startedStreamEvents(state));
1538
+ const buffer = { value: "" };
1539
+ upstreamRes.on("data", (chunk: Buffer) => appendStreamChunk(buffer, chunk, state, res));
1540
+ upstreamRes.on("end", () => {
1541
+ for (const event of sseStreamFinalize(state)) res.write(event);
1542
+ res.end();
1543
+ });
1544
+ upstreamRes.on("error", () => res.end());
1545
+ return;
1546
+ }
1547
+
1548
+ const responseChunks: Buffer[] = [];
1549
+ upstreamRes.on("data", (chunk: Buffer) => responseChunks.push(chunk));
1550
+ upstreamRes.on("end", () => {
1551
+ try {
1552
+ const chatResp = JSON.parse(Buffer.concat(responseChunks).toString()) as JsonObject;
1553
+ const response = chatToResponses(chatResp, chatBody.model, context);
1554
+ res.writeHead(200, { "Content-Type": "application/json" });
1555
+ res.end(JSON.stringify(response));
1556
+ } catch {
1557
+ res.writeHead(502, { "Content-Type": "application/json" });
1558
+ res.end(JSON.stringify({ error: { message: "Invalid upstream JSON", type: "upstream_error" } }));
1559
+ }
1560
+ });
1561
+ });
1562
+
1563
+ upstreamReq.on("error", (error) => {
1564
+ res.writeHead(502, { "Content-Type": "application/json" });
1565
+ res.end(JSON.stringify({ error: { message: `Upstream error: ${error.message}`, type: "upstream_error" } }));
1566
+ });
1567
+ upstreamReq.write(JSON.stringify(chatBody));
1568
+ upstreamReq.end();
1569
+ }
1570
+ }
1571
+
1572
+ const NON_OPENAI_BASE_URL_PATTERNS = [
1573
+ /deepseek/i,
1574
+ /moonshot/i,
1575
+ /zhipu|bigmodel/i,
1576
+ /qwen/i,
1577
+ /kimi/i,
1578
+ /minimax/i,
1579
+ /siliconflow/i,
1580
+ /together/i,
1581
+ /groq/i,
1582
+ /dashscope/i,
1583
+ /lingyiwanwu|yi-api/i,
1584
+ /stepfun|step-api/i,
1585
+ /baichuan/i,
1586
+ /\/chat\/completions(?:$|[?#])/i,
1587
+ ];
1588
+
1589
+ export function needsCompatProxy(baseUrl: string): boolean {
1590
+ if (!baseUrl) return false;
1591
+ const normalized = baseUrl.toLowerCase();
1592
+ if (normalized.includes("api.openai.com")) return false;
1593
+ return NON_OPENAI_BASE_URL_PATTERNS.some((pattern) => pattern.test(normalized));
1594
+ }
1595
+
1596
+ export const __compatProxyTest = {
1597
+ responsesToChat,
1598
+ chatToResponses,
1599
+ buildToolContext,
1600
+ translateChatSSEToResponsesEvents,
1601
+ sseStreamFinalize,
1602
+ createStreamState,
1603
+ };