@fudrouter/fsrouter 0.6.72 → 0.6.74

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 (314) hide show
  1. package/dist/lib/headroom/detect.js +97 -7
  2. package/dist/lib/headroom/process.js +136 -4
  3. package/dist/open-sse/config/appConstants.js +23 -79
  4. package/dist/open-sse/config/cliFingerprints.js +1 -1
  5. package/dist/open-sse/config/errorConfig.js +0 -11
  6. package/dist/open-sse/config/grokCli.js +10 -0
  7. package/dist/open-sse/config/kiroConstants.js +99 -46
  8. package/dist/open-sse/config/runtimeConfig.js +2 -0
  9. package/dist/open-sse/config/ttsModels.js +2 -0
  10. package/dist/open-sse/executors/antigravity.js +250 -164
  11. package/dist/open-sse/executors/base.js +16 -11
  12. package/dist/open-sse/executors/codex.js +269 -1108
  13. package/dist/open-sse/executors/commandCode.js +1 -1
  14. package/dist/open-sse/executors/commandcode.js +10 -4
  15. package/dist/open-sse/executors/cursor.js +96 -203
  16. package/dist/open-sse/executors/default.js +146 -244
  17. package/dist/open-sse/executors/github.js +128 -73
  18. package/dist/open-sse/executors/grok-cli.js +527 -94
  19. package/dist/open-sse/executors/grok-web.js +5 -7
  20. package/dist/open-sse/executors/index.js +12 -0
  21. package/dist/open-sse/executors/kiro.js +150 -61
  22. package/dist/open-sse/executors/opencode-go.js +12 -4
  23. package/dist/open-sse/executors/opencode.js +1 -1
  24. package/dist/open-sse/executors/perplexity-web.js +20 -96
  25. package/dist/open-sse/executors/qoder.js +28 -18
  26. package/dist/open-sse/executors/vertex.js +53 -7
  27. package/dist/open-sse/executors/xiaomi-tokenplan.js +6 -5
  28. package/dist/open-sse/handlers/chatCore/nonStreamingHandler.js +97 -85
  29. package/dist/open-sse/handlers/chatCore/requestDetail.js +32 -8
  30. package/dist/open-sse/handlers/chatCore/sseToJsonHandler.js +13 -7
  31. package/dist/open-sse/handlers/chatCore/streamingHandler.js +74 -25
  32. package/dist/open-sse/handlers/chatCore.js +35 -41
  33. package/dist/open-sse/handlers/embeddingProviders/index.js +1 -0
  34. package/dist/open-sse/handlers/embeddingProviders/openai.js +8 -16
  35. package/dist/open-sse/handlers/imageProviders/blackForestLabs.js +2 -21
  36. package/dist/open-sse/handlers/imageProviders/cloudflareAi.js +2 -30
  37. package/dist/open-sse/handlers/imageProviders/codex.js +2 -20
  38. package/dist/open-sse/handlers/imageProviders/comfyui.js +5 -18
  39. package/dist/open-sse/handlers/imageProviders/falAi.js +2 -22
  40. package/dist/open-sse/handlers/imageProviders/gemini.js +2 -16
  41. package/dist/open-sse/handlers/imageProviders/huggingface.js +2 -17
  42. package/dist/open-sse/handlers/imageProviders/index.js +3 -4
  43. package/dist/open-sse/handlers/imageProviders/leonardo.js +1 -1
  44. package/dist/open-sse/handlers/imageProviders/nanobanana.js +4 -23
  45. package/dist/open-sse/handlers/imageProviders/openai.js +15 -43
  46. package/dist/open-sse/handlers/imageProviders/runwayml.js +2 -26
  47. package/dist/open-sse/handlers/imageProviders/sdwebui.js +4 -20
  48. package/dist/open-sse/handlers/imageProviders/stabilityAi.js +2 -26
  49. package/dist/open-sse/handlers/imageProviders/weavy.js +1 -1
  50. package/dist/open-sse/handlers/search/chatSearch.js +60 -14
  51. package/dist/open-sse/handlers/ttsProviders/gemini.js +14 -3
  52. package/dist/open-sse/handlers/ttsProviders/index.js +4 -2
  53. package/dist/open-sse/handlers/ttsProviders/openai.js +4 -1
  54. package/dist/open-sse/handlers/ttsProviders/openrouter.js +7 -4
  55. package/dist/open-sse/handlers/videoCore.js +166 -0
  56. package/dist/open-sse/handlers/videoProviders/weavy.js +1 -1
  57. package/dist/open-sse/mcp-server/catalog.js +1 -1
  58. package/dist/open-sse/mcp-server/server.js +2 -2
  59. package/dist/open-sse/mcp-server/tools/advancedTools.js +2 -2
  60. package/dist/open-sse/mcp-server/tools/agentSkillTools.js +1 -1
  61. package/dist/open-sse/mcp-server/tools/compressionTools.js +4 -4
  62. package/dist/open-sse/mcp-server/tools/gamificationTools.js +10 -10
  63. package/dist/open-sse/mcp-server/tools/githubSkillTools.js +1 -1
  64. package/dist/open-sse/mcp-server/tools/memoryTools.js +3 -3
  65. package/dist/open-sse/mcp-server/tools/notionTools.js +2 -2
  66. package/dist/open-sse/mcp-server/tools/obsidianTools.js +2 -2
  67. package/dist/open-sse/mcp-server/tools/pickFastestModel.js +1 -1
  68. package/dist/open-sse/mcp-server/tools/pluginTools.js +4 -4
  69. package/dist/open-sse/mcp-server/tools/skillTools.js +2 -2
  70. package/dist/open-sse/providers/capabilities.js +24 -4
  71. package/dist/open-sse/providers/registry/alicode-intl.js +1 -1
  72. package/dist/open-sse/providers/registry/anthropic.js +1 -8
  73. package/dist/open-sse/providers/registry/codex.js +0 -9
  74. package/dist/open-sse/providers/registry/cohere.js +0 -2
  75. package/dist/open-sse/providers/registry/gemini.js +0 -2
  76. package/dist/open-sse/providers/registry/github.js +9 -6
  77. package/dist/open-sse/providers/registry/grok-cli.js +28 -18
  78. package/dist/open-sse/providers/registry/index.js +74 -80
  79. package/dist/open-sse/providers/registry/kiro.js +12 -0
  80. package/dist/open-sse/providers/registry/mistral.js +0 -3
  81. package/dist/open-sse/providers/registry/openai.js +0 -3
  82. package/dist/open-sse/providers/registry/perplexity.js +0 -2
  83. package/dist/open-sse/providers/registry/xai.js +5 -3
  84. package/dist/open-sse/rtk/autodetect.js +10 -2
  85. package/dist/open-sse/rtk/caveman.js +2 -93
  86. package/dist/open-sse/rtk/cavemanPrompts.js +34 -2
  87. package/dist/open-sse/rtk/constants.js +7 -2
  88. package/dist/open-sse/rtk/headroom.js +133 -0
  89. package/dist/open-sse/rtk/ponytail.js +1 -1
  90. package/dist/open-sse/rtk/registry.js +2 -0
  91. package/dist/open-sse/services/accountFallback.js +0 -108
  92. package/dist/open-sse/services/combo/quotaExhaustionCutoff.js +2 -2
  93. package/dist/open-sse/services/combo/quotaShareStrategy.js +1 -1
  94. package/dist/open-sse/services/combo/resolveAutoStrategy.js +1 -1
  95. package/dist/open-sse/services/combo/sessionStickiness.js +1 -1
  96. package/dist/open-sse/services/combo/targetSorters.js +2 -2
  97. package/dist/open-sse/services/combo/validateQuality.js +1 -1
  98. package/dist/open-sse/services/comboConfig.js +1 -1
  99. package/dist/open-sse/services/emergencyFallback.js +1 -1
  100. package/dist/open-sse/services/grokCliModels.js +127 -0
  101. package/dist/open-sse/services/model.js +7 -1
  102. package/dist/open-sse/services/provider.js +1 -1
  103. package/dist/open-sse/services/proxyAutoSelector.js +1 -1
  104. package/dist/open-sse/services/tokenRefresh/providers.js +3 -3
  105. package/dist/open-sse/services/usage/codex.js +148 -214
  106. package/dist/open-sse/services/usage/grok-cli.js +61 -7
  107. package/dist/open-sse/services/usage/misc.js +0 -19
  108. package/dist/open-sse/services/usage.js +0 -2
  109. package/dist/open-sse/translator/concerns/paramSupport.js +2 -2
  110. package/dist/open-sse/translator/concerns/thinkingUnified.js +6 -0
  111. package/dist/open-sse/translator/index.js +97 -59
  112. package/dist/open-sse/translator/request/claude-to-kiro.js +67 -40
  113. package/dist/open-sse/translator/request/openai-responses.js +1 -0
  114. package/dist/open-sse/translator/request/openai-to-commandcode.js +0 -4
  115. package/dist/open-sse/translator/request/openai-to-kiro.js +49 -20
  116. package/dist/open-sse/translator/response/commandcode-to-openai.js +0 -4
  117. package/dist/open-sse/utils/bypassHandler.js +18 -3
  118. package/dist/open-sse/utils/claudeCloaking.js +15 -5
  119. package/dist/open-sse/utils/cursorImages.js +1 -1
  120. package/dist/open-sse/utils/error.js +0 -17
  121. package/dist/open-sse/utils/keepaliveThreshold.js +4 -4
  122. package/dist/open-sse/utils/kiroSessionReplay.js +125 -0
  123. package/dist/open-sse/utils/noThinkingAlias.js +1 -1
  124. package/dist/open-sse/utils/proxyFetch.js +0 -1
  125. package/dist/open-sse/utils/reasoningContentInjector.js +4 -7
  126. package/dist/open-sse/utils/responsesStatePolicy.js +1 -1
  127. package/dist/open-sse/utils/responsesStreamHelpers.js +1 -0
  128. package/dist/open-sse/utils/sessionManager.js +49 -22
  129. package/dist/open-sse/utils/stream.js +54 -77
  130. package/dist/open-sse/utils/streamHandler.js +19 -15
  131. package/dist/open-sse/utils/streamHelpers.js +2 -17
  132. package/dist/open-sse/utils/usageTracking.js +103 -12
  133. package/dist/routes/headroom/extras/route.js +58 -0
  134. package/dist/routes/headroom/restart/route.js +33 -0
  135. package/open-sse/config/appConstants.js +23 -79
  136. package/open-sse/config/errorConfig.js +0 -11
  137. package/open-sse/config/grokCli.js +10 -0
  138. package/open-sse/config/kiroConstants.js +99 -46
  139. package/open-sse/config/runtimeConfig.js +2 -0
  140. package/open-sse/config/ttsModels.js +2 -0
  141. package/open-sse/executors/antigravity.js +250 -164
  142. package/open-sse/executors/base.js +16 -11
  143. package/open-sse/executors/codex.js +269 -1108
  144. package/open-sse/executors/commandcode.js +10 -4
  145. package/open-sse/executors/cursor.js +96 -203
  146. package/open-sse/executors/default.js +146 -244
  147. package/open-sse/executors/github.js +128 -73
  148. package/open-sse/executors/grok-cli.js +527 -94
  149. package/open-sse/executors/grok-web.js +5 -7
  150. package/open-sse/executors/index.js +12 -0
  151. package/open-sse/executors/kiro.js +150 -61
  152. package/open-sse/executors/opencode-go.js +12 -4
  153. package/open-sse/executors/opencode.js +1 -1
  154. package/open-sse/executors/perplexity-web.js +20 -96
  155. package/open-sse/executors/qoder.js +28 -18
  156. package/open-sse/executors/vertex.js +53 -7
  157. package/open-sse/executors/xiaomi-tokenplan.js +6 -5
  158. package/open-sse/handlers/chatCore/nonStreamingHandler.js +97 -85
  159. package/open-sse/handlers/chatCore/requestDetail.js +32 -8
  160. package/open-sse/handlers/chatCore/sseToJsonHandler.js +13 -7
  161. package/open-sse/handlers/chatCore/streamingHandler.js +74 -25
  162. package/open-sse/handlers/chatCore.js +35 -41
  163. package/open-sse/handlers/embeddingProviders/index.js +1 -0
  164. package/open-sse/handlers/embeddingProviders/openai.js +8 -16
  165. package/open-sse/handlers/imageProviders/blackForestLabs.js +2 -21
  166. package/open-sse/handlers/imageProviders/cloudflareAi.js +2 -30
  167. package/open-sse/handlers/imageProviders/codex.js +2 -20
  168. package/open-sse/handlers/imageProviders/comfyui.js +5 -18
  169. package/open-sse/handlers/imageProviders/falAi.js +2 -22
  170. package/open-sse/handlers/imageProviders/gemini.js +2 -16
  171. package/open-sse/handlers/imageProviders/huggingface.js +2 -17
  172. package/open-sse/handlers/imageProviders/index.js +3 -4
  173. package/open-sse/handlers/imageProviders/leonardo.js +1 -1
  174. package/open-sse/handlers/imageProviders/nanobanana.js +4 -23
  175. package/open-sse/handlers/imageProviders/openai.js +15 -43
  176. package/open-sse/handlers/imageProviders/runwayml.js +2 -26
  177. package/open-sse/handlers/imageProviders/sdwebui.js +4 -20
  178. package/open-sse/handlers/imageProviders/stabilityAi.js +2 -26
  179. package/open-sse/handlers/imageProviders/weavy.js +1 -1
  180. package/open-sse/handlers/search/chatSearch.js +60 -14
  181. package/open-sse/handlers/ttsProviders/gemini.js +14 -3
  182. package/open-sse/handlers/ttsProviders/index.js +4 -2
  183. package/open-sse/handlers/ttsProviders/openai.js +4 -1
  184. package/open-sse/handlers/ttsProviders/openrouter.js +7 -4
  185. package/open-sse/handlers/videoCore.js +166 -0
  186. package/open-sse/handlers/videoProviders/weavy.js +1 -1
  187. package/open-sse/mcp-server/audit.js +1 -1
  188. package/open-sse/mcp-server/catalog.js +2 -2
  189. package/open-sse/mcp-server/descriptionCompressor.js +1 -1
  190. package/open-sse/mcp-server/mcpCallerIdentity.js +1 -1
  191. package/open-sse/mcp-server/schemas/tools.js +1 -1
  192. package/open-sse/mcp-server/server.js +4 -4
  193. package/open-sse/mcp-server/tools/advancedTools.js +5 -5
  194. package/open-sse/mcp-server/tools/agentSkillTools.js +1 -1
  195. package/open-sse/mcp-server/tools/compressionTools.js +4 -4
  196. package/open-sse/mcp-server/tools/gamificationTools.js +10 -10
  197. package/open-sse/mcp-server/tools/githubSkillTools.js +1 -1
  198. package/open-sse/mcp-server/tools/memoryTools.js +3 -3
  199. package/open-sse/mcp-server/tools/notionTools.js +2 -2
  200. package/open-sse/mcp-server/tools/obsidianTools.js +2 -2
  201. package/open-sse/mcp-server/tools/pickFastestModel.js +3 -3
  202. package/open-sse/mcp-server/tools/pluginTools.js +4 -4
  203. package/open-sse/mcp-server/tools/skillTools.js +2 -2
  204. package/open-sse/providers/capabilities.js +24 -4
  205. package/open-sse/providers/registry/alicode-intl.js +1 -1
  206. package/open-sse/providers/registry/anthropic.js +1 -8
  207. package/open-sse/providers/registry/codex.js +0 -9
  208. package/open-sse/providers/registry/cohere.js +0 -2
  209. package/open-sse/providers/registry/gemini.js +0 -2
  210. package/open-sse/providers/registry/github.js +9 -6
  211. package/open-sse/providers/registry/grok-cli.js +28 -18
  212. package/open-sse/providers/registry/index.js +74 -80
  213. package/open-sse/providers/registry/kiro.js +12 -0
  214. package/open-sse/providers/registry/mistral.js +0 -3
  215. package/open-sse/providers/registry/openai.js +0 -3
  216. package/open-sse/providers/registry/perplexity.js +0 -2
  217. package/open-sse/providers/registry/xai.js +5 -3
  218. package/open-sse/rtk/autodetect.js +10 -2
  219. package/open-sse/rtk/caveman.js +2 -93
  220. package/open-sse/rtk/cavemanPrompts.js +34 -2
  221. package/open-sse/rtk/constants.js +7 -2
  222. package/open-sse/rtk/headroom.js +133 -0
  223. package/open-sse/rtk/ponytail.js +1 -1
  224. package/open-sse/rtk/registry.js +2 -0
  225. package/open-sse/services/accountFallback.js +0 -108
  226. package/open-sse/services/combo/quotaExhaustionCutoff.js +2 -2
  227. package/open-sse/services/combo/quotaShareStrategy.js +1 -1
  228. package/open-sse/services/combo/resolveAutoStrategy.js +1 -1
  229. package/open-sse/services/combo/sessionStickiness.js +1 -1
  230. package/open-sse/services/combo/shadowRouting.js +1 -1
  231. package/open-sse/services/combo/targetSorters.js +4 -4
  232. package/open-sse/services/combo/validateQuality.js +1 -1
  233. package/open-sse/services/evalRouting.js +1 -1
  234. package/open-sse/services/grokCliModels.js +127 -0
  235. package/open-sse/services/model.js +7 -1
  236. package/open-sse/services/modelCapabilities.js +1 -1
  237. package/open-sse/services/modelFamilyFallback.js +1 -1
  238. package/open-sse/services/provider.js +1 -1
  239. package/open-sse/services/providerCooldownTracker.js +1 -1
  240. package/open-sse/services/rateLimitManager.js +1 -1
  241. package/open-sse/services/tokenRefresh/providers.js +3 -3
  242. package/open-sse/services/usage/codex.js +148 -214
  243. package/open-sse/services/usage/grok-cli.js +61 -7
  244. package/open-sse/services/usage/misc.js +0 -19
  245. package/open-sse/services/usage.js +0 -2
  246. package/open-sse/translator/concerns/paramSupport.js +2 -2
  247. package/open-sse/translator/concerns/thinkingUnified.js +6 -0
  248. package/open-sse/translator/index.js +97 -59
  249. package/open-sse/translator/request/claude-to-kiro.js +67 -40
  250. package/open-sse/translator/request/openai-responses.js +1 -0
  251. package/open-sse/translator/request/openai-to-commandcode.js +0 -4
  252. package/open-sse/translator/request/openai-to-kiro.js +49 -20
  253. package/open-sse/translator/response/commandcode-to-openai.js +0 -4
  254. package/open-sse/utils/bypassHandler.js +18 -3
  255. package/open-sse/utils/claudeCloaking.js +15 -5
  256. package/open-sse/utils/error.js +0 -17
  257. package/open-sse/utils/kiroSessionReplay.js +125 -0
  258. package/open-sse/utils/logger.js +1 -1
  259. package/open-sse/utils/proxyFetch.js +0 -1
  260. package/open-sse/utils/reasoningContentInjector.js +4 -7
  261. package/open-sse/utils/responsesStreamHelpers.js +1 -0
  262. package/open-sse/utils/sessionManager.js +49 -22
  263. package/open-sse/utils/stream.js +54 -77
  264. package/open-sse/utils/streamHandler.js +19 -15
  265. package/open-sse/utils/streamHelpers.js +2 -17
  266. package/open-sse/utils/usageTracking.js +103 -12
  267. package/package.json +4 -7
  268. package/public/assets/EndpointPageClient.C2WMTYy0.js +6 -0
  269. package/public/assets/{Loading.Bj-WGl4k.js → Loading.BHPtQ9vj.js} +1 -1
  270. package/public/assets/{NoAuthProxyCard.qAv57b-0.js → NoAuthProxyCard.BDcXaWvM.js} +1 -1
  271. package/public/assets/index.Be3gbrBl.js +89 -0
  272. package/public/assets/index.COMgQZYj.css +1 -0
  273. package/public/assets/{page.CbkENBd5.js → page.-lpNgYAw.js} +1 -1
  274. package/public/assets/{page.CssmrzTT.js → page.11hpNKmq.js} +1 -1
  275. package/public/assets/{page.C72FTTJr.js → page.B-LxsnqU.js} +1 -1
  276. package/public/assets/{page.sOFOrxqq.js → page.B-dzeIUC.js} +1 -1
  277. package/public/assets/{page.CsxWmPoI.js → page.B-nBR75u.js} +1 -1
  278. package/public/assets/{page.Dx_GRRdT.js → page.B3QqvLep.js} +1 -1
  279. package/public/assets/{page.DPyOkPVo.js → page.B8xdkCWA.js} +1 -1
  280. package/public/assets/{page.DUI8kqOY.js → page.BFb7yUd8.js} +1 -1
  281. package/public/assets/page.BbPPdoas.js +1 -0
  282. package/public/assets/page.BdS20a1O.js +1 -0
  283. package/public/assets/{page.DibhF7f-.js → page.BfmI9KYe.js} +1 -1
  284. package/public/assets/{page.DX4Nno6M.js → page.BgGJovOg.js} +1 -1
  285. package/public/assets/{page.BnmTC5jG.js → page.C0gBvR4O.js} +1 -1
  286. package/public/assets/{page.D5gj98Oe.js → page.C6bYizL7.js} +1 -1
  287. package/public/assets/{page.vla5Mzki.js → page.C8sLEMa6.js} +1 -1
  288. package/public/assets/{page.CXd_R9yU.js → page.CCNsZBXp.js} +1 -1
  289. package/public/assets/{page.CQlVGoXg.js → page.CF_YSLwP.js} +1 -1
  290. package/public/assets/{page.BbO1pspY.js → page.CPTtRDxw.js} +1 -1
  291. package/public/assets/{page.D1oKew1j.js → page.CdMmlUEm.js} +1 -1
  292. package/public/assets/{page.DxMDTbSx.js → page.Cged1bOZ.js} +1 -1
  293. package/public/assets/{page.Cj5h09Zo.js → page.Ch647dVk.js} +1 -1
  294. package/public/assets/{page.DVIHRbxB.js → page.CpvXDkQF.js} +1 -1
  295. package/public/assets/{page.i4KDuWcM.js → page.CrBl7f8N.js} +1 -1
  296. package/public/assets/{page.BSLJ4tx5.js → page.CrP7niA2.js} +1 -1
  297. package/public/assets/{page.CnTop8Zt.js → page.CvUFZzXr.js} +1 -1
  298. package/public/assets/{page.O2ddJYoT.js → page.CyUqJPmx.js} +1 -1
  299. package/public/assets/{page.DBhu4Arl.js → page.D8Rp8fFR.js} +1 -1
  300. package/public/assets/{page.CPZav1_c.js → page.Df9qtrdG.js} +1 -1
  301. package/public/assets/{page.Qkkv8roc.js → page.DiL4Gwqe.js} +1 -1
  302. package/public/assets/{page.BdmJ3yY3.js → page.Dl1apZE2.js} +1 -1
  303. package/public/assets/{page.1qjqvrwX.js → page.HV0w1d5C.js} +1 -1
  304. package/public/assets/{page.ChX1NqmC.js → page.N1x4YL8_.js} +1 -1
  305. package/public/assets/{page.Dh5f0XJC.js → page.P2Ny5veR.js} +1 -1
  306. package/public/assets/{page.CSs3-gdt.js → page.fOOCr18J.js} +1 -1
  307. package/public/assets/{page.Ir7KvKcF.js → page.sUIPWIiF.js} +1 -1
  308. package/public/assets/{page.CzlQTyAL.js → page.tE7PpWYW.js} +1 -1
  309. package/public/assets/{page.DzZLqI5Q.js → page.uziaGZsT.js} +1 -1
  310. package/public/index.html +2 -2
  311. package/public/assets/EndpointPageClient.LyNNvZ4z.js +0 -6
  312. package/public/assets/index.BuPfZebu.css +0 -1
  313. package/public/assets/index.CShjRV_B.js +0 -89
  314. package/public/assets/page.DD_czjjP.js +0 -1
@@ -1,12 +1,15 @@
1
1
  import { translateResponse, initState } from "../translator/index.js";
2
2
  import { FORMATS } from "../translator/formats.js";
3
3
  import { trackPendingRequest, appendRequestLog } from '../../dist/lib/usageDb.js';
4
- import { extractUsage, hasValidUsage, estimateUsage, logUsage, addBufferToUsage, filterUsageForFormat, COLORS } from "./usageTracking.js";
4
+ import { extractUsage, mergeUsage, hasValidUsage, estimateUsage, logUsage, addBufferToUsage, filterUsageForFormat, COLORS } from "./usageTracking.js";
5
5
  import { parseSSELine, hasValuableContent, fixInvalidId, formatSSE } from "./streamHelpers.js";
6
6
  import { getOpenAIResponsesEventName, isOpenAIResponsesTerminalEvent, formatIncompleteOpenAIResponsesStreamFailure } from "./responsesStreamHelpers.js";
7
7
  import { dbg, isDebugEnabled } from "./debugLog.js";
8
8
 
9
+ import { SSE_DONE, SSE_HEADERS, SSE_HEADERS_NO_BUFFER } from "./sseConstants.js";
10
+
9
11
  export { COLORS, formatSSE };
12
+ export { SSE_DONE, SSE_HEADERS, SSE_HEADERS_NO_BUFFER };
10
13
 
11
14
  // sharedEncoder is stateless — safe to share across streams
12
15
  const sharedEncoder = new TextEncoder();
@@ -68,6 +71,7 @@ export function createSSEStream(options = {}) {
68
71
  let currentOpenAIResponsesEvent = null;
69
72
  let openAIResponsesTerminalSeen = false;
70
73
  let openAIResponsesDoneSent = false;
74
+ let streamDoneSent = false; // track duplicate [DONE] across transform + flush
71
75
 
72
76
  return new TransformStream({
73
77
  transform(chunk, controller) {
@@ -99,35 +103,6 @@ export function createSSEStream(options = {}) {
99
103
  let output;
100
104
  let injectedUsage = false;
101
105
 
102
- // Handle raw JSON error disguised as SSE in passthrough mode
103
- if (trimmed.startsWith("{")) {
104
- try {
105
- const parsedJson = JSON.parse(trimmed);
106
- if (parsedJson && (parsedJson.error || parsedJson.code !== undefined || parsedJson.msg)) {
107
- const errorMsg = parsedJson.error?.message || parsedJson.msg || (typeof parsedJson.error === "string" ? parsedJson.error : JSON.stringify(parsedJson));
108
- const errorChunk = {
109
- id: `err_${Date.now()}`,
110
- object: "chat.completion.chunk",
111
- created: Math.floor(Date.now() / 1000),
112
- model: model || "unknown",
113
- choices: [{
114
- index: 0,
115
- delta: { content: `\n\n[Provider Error]: ${errorMsg}\n\n` },
116
- finish_reason: "stop"
117
- }]
118
- };
119
- output = formatSSE(errorChunk, FORMATS.OPENAI);
120
- reqLogger?.appendConvertedChunk?.(output);
121
- controller.enqueue(sharedEncoder.encode(output));
122
-
123
- const doneOutput = "data: [DONE]\n\n";
124
- reqLogger?.appendConvertedChunk?.(doneOutput);
125
- controller.enqueue(sharedEncoder.encode(doneOutput));
126
- continue;
127
- }
128
- } catch (e) {}
129
- }
130
-
131
106
  if (trimmed.startsWith("data:") && trimmed.slice(5).trim() !== "[DONE]") {
132
107
  try {
133
108
  const parsed = JSON.parse(trimmed.slice(5).trim());
@@ -155,17 +130,25 @@ export function createSSEStream(options = {}) {
155
130
  }
156
131
  }
157
132
 
133
+ // Strip empty tool_calls arrays that break AI SDK reasoning tracking.
134
+ // Some providers (e.g. CodeBuddy CN) include `"tool_calls": []` in
135
+ // every streaming delta. @ai-sdk/openai-compatible checks
136
+ // `delta.tool_calls != null` — an empty array passes this check,
137
+ // causing premature `reasoning-end` on every chunk.
138
+ if (parsed?.choices) {
139
+ for (const choice of parsed.choices) {
140
+ if (choice.delta?.tool_calls && Array.isArray(choice.delta.tool_calls) && choice.delta.tool_calls.length === 0) {
141
+ delete choice.delta.tool_calls;
142
+ fieldsInjected = true;
143
+ }
144
+ }
145
+ }
146
+
158
147
  if (!hasValuableContent(parsed, FORMATS.OPENAI)) {
159
148
  continue;
160
149
  }
161
150
 
162
151
  const delta = parsed.choices?.[0]?.delta;
163
-
164
- // Map refusal to content for clients that do not support the refusal field
165
- if (delta?.refusal && !delta?.content) {
166
- delta.content = `[Refusal]: ${delta.refusal}`;
167
- }
168
-
169
152
  const content = delta?.content;
170
153
  const reasoning = delta?.reasoning_content;
171
154
  if (content && typeof content === "string") {
@@ -179,7 +162,7 @@ export function createSSEStream(options = {}) {
179
162
 
180
163
  const extracted = extractUsage(parsed);
181
164
  if (extracted) {
182
- usage = extracted;
165
+ usage = mergeUsage(usage, extracted);
183
166
  }
184
167
 
185
168
  const isFinishChunk = parsed.choices?.[0]?.finish_reason;
@@ -198,7 +181,12 @@ export function createSSEStream(options = {}) {
198
181
  output = `data: ${JSON.stringify(parsed)}\n`;
199
182
  injectedUsage = true;
200
183
  }
201
- } catch { }
184
+ } catch {
185
+ // Skip non-JSON data lines silently — don't forward garbage to clients.
186
+ // Upstream providers sometimes return plain-text errors (HTML, rate-limit
187
+ // messages) in the SSE stream that would break downstream JSON decoders.
188
+ continue;
189
+ }
202
190
  }
203
191
 
204
192
  if (!injectedUsage) {
@@ -219,37 +207,6 @@ export function createSSEStream(options = {}) {
219
207
 
220
208
  const parsed = parseSSELine(trimmed, targetFormat);
221
209
  if (!parsed) continue;
222
-
223
- // Intercept raw JSON error that provider sent instead of SSE
224
- if (parsed._isRawError) {
225
- const errorMsg = parsed.raw.error?.message || parsed.raw.msg || (typeof parsed.raw.error === "string" ? parsed.raw.error : JSON.stringify(parsed.raw));
226
- const errorChunk = {
227
- id: `err_${Date.now()}`,
228
- object: "chat.completion.chunk",
229
- created: Math.floor(Date.now() / 1000),
230
- model: model || "unknown",
231
- choices: [{
232
- index: 0,
233
- delta: { content: `\n\n[Provider Error]: ${errorMsg}\n\n` },
234
- finish_reason: "stop"
235
- }]
236
- };
237
- const output = formatSSE(errorChunk, sourceFormat);
238
- reqLogger?.appendConvertedChunk?.(output);
239
- controller.enqueue(sharedEncoder.encode(output));
240
- sseEmittedCount++;
241
-
242
- const doneOutput = "data: [DONE]\n\n";
243
- reqLogger?.appendConvertedChunk?.(doneOutput);
244
- controller.enqueue(sharedEncoder.encode(doneOutput));
245
- if (targetFormat === FORMATS.OPENAI_RESPONSES && sourceFormat === FORMATS.OPENAI_RESPONSES) openAIResponsesDoneSent = true;
246
- continue;
247
- }
248
-
249
- // Map refusal to content for older clients that do not support refusal field
250
- if (parsed.choices?.[0]?.delta?.refusal && !parsed.choices[0].delta.content) {
251
- parsed.choices[0].delta.content = `[Refusal]: ${parsed.choices[0].delta.refusal}`;
252
- }
253
210
 
254
211
  // Responses API same-format passthrough: preserve event framing + track terminal state
255
212
  const isOpenAIResponsesStream = targetFormat === FORMATS.OPENAI_RESPONSES;
@@ -274,9 +231,12 @@ export function createSSEStream(options = {}) {
274
231
  sseEmittedCount++;
275
232
  }
276
233
 
277
- const output = "data: [DONE]\n\n";
278
- reqLogger?.appendConvertedChunk?.(output);
279
- controller.enqueue(sharedEncoder.encode(output));
234
+ if (keepsOpenAIResponsesFormat && !streamDoneSent) {
235
+ const doneOutput = "data: [DONE]\n\n";
236
+ reqLogger?.appendConvertedChunk?.(doneOutput);
237
+ controller.enqueue(sharedEncoder.encode(doneOutput));
238
+ }
239
+ streamDoneSent = true;
280
240
  if (keepsOpenAIResponsesFormat) openAIResponsesDoneSent = true;
281
241
  continue;
282
242
  }
@@ -320,7 +280,7 @@ export function createSSEStream(options = {}) {
320
280
 
321
281
  // Extract usage
322
282
  const extracted = extractUsage(parsed);
323
- if (extracted) state.usage = extracted; // Keep original usage for logging
283
+ if (extracted) state.usage = mergeUsage(state.usage, extracted); // Keep original usage for logging
324
284
 
325
285
  // Responses same-format passthrough: re-emit with original event framing
326
286
  if (keepsOpenAIResponsesFormat && openAIResponsesEventName) {
@@ -396,14 +356,23 @@ export function createSSEStream(options = {}) {
396
356
  usage = estimateUsage(body, totalContentLength, FORMATS.OPENAI);
397
357
  }
398
358
 
359
+ if (hasValidUsage(usage)) {
360
+ logUsage(provider, usage, model, connectionId, apiKey);
361
+ } else {
362
+ appendRequestLog({ model, provider, connectionId, tokens: null, status: "200 OK" }).catch(() => { });
363
+ }
399
364
 
400
365
  // IMPORTANT: In passthrough mode we still must terminate the SSE stream.
401
366
  // Some clients (e.g. OpenClaw) expect the OpenAI-style sentinel:
402
367
  // data: [DONE]\n\n
403
368
  // Without it they can hang until timeout and trigger failover.
404
- const doneOutput = "data: [DONE]\n\n";
405
- reqLogger?.appendConvertedChunk?.(doneOutput);
406
- controller.enqueue(sharedEncoder.encode(doneOutput));
369
+ // Gemini-family clients (Antigravity, Vertex, Gemini) reject this sentinel with 400 syntax errors.
370
+ const isGeminiFamily = provider === "antigravity" || provider === "gemini" || provider === "vertex";
371
+ if (!streamDoneSent && !isGeminiFamily) {
372
+ const doneOutput = "data: [DONE]\n\n";
373
+ reqLogger?.appendConvertedChunk?.(doneOutput);
374
+ controller.enqueue(sharedEncoder.encode(doneOutput));
375
+ }
407
376
 
408
377
  if (onStreamComplete) {
409
378
  onStreamComplete({
@@ -464,15 +433,23 @@ export function createSSEStream(options = {}) {
464
433
  openAIResponsesTerminalSeen = true;
465
434
  }
466
435
 
467
- if (!keepsOpenAIResponsesFormat || !openAIResponsesDoneSent) {
436
+ if (keepsOpenAIResponsesFormat && !openAIResponsesDoneSent && !streamDoneSent) {
468
437
  const doneOutput = "data: [DONE]\n\n";
469
438
  reqLogger?.appendConvertedChunk?.(doneOutput);
470
439
  controller.enqueue(sharedEncoder.encode(doneOutput));
440
+ openAIResponsesDoneSent = true;
441
+ streamDoneSent = true;
471
442
  }
472
443
 
473
444
  if (!hasValidUsage(state?.usage) && totalContentLength > 0) {
474
445
  state.usage = estimateUsage(body, totalContentLength, sourceFormat);
475
446
  }
447
+
448
+ if (hasValidUsage(state?.usage)) {
449
+ logUsage(state.provider || targetFormat, state.usage, model, connectionId, apiKey);
450
+ } else {
451
+ appendRequestLog({ model, provider, connectionId, tokens: null, status: "200 OK" }).catch(() => { });
452
+ }
476
453
 
477
454
  if (onStreamComplete) {
478
455
  onStreamComplete({
@@ -15,16 +15,19 @@ function getTimeString() {
15
15
  * @param {string} options.provider - Provider name
16
16
  * @param {string} options.model - Model name
17
17
  */
18
- export function createStreamController({ onDisconnect, onError, log, provider, model } = {}) {
18
+ export function createStreamController({ onDisconnect, onError, log, provider, model, reqTag = "" } = {}) {
19
19
  const abortController = new AbortController();
20
20
  const startTime = Date.now();
21
21
  let disconnected = false;
22
22
  let abortTimeout = null;
23
23
 
24
- const logStream = (status) => {
24
+ // Only abnormal terminations are logged; normal completion is covered by "📊 done".
25
+ // isError uses errorLine (always shown, ignores LOG_LEVEL) so failures survive quiet levels.
26
+ const logStream = (symbol, status, isError = false) => {
25
27
  const duration = Date.now() - startTime;
26
- const p = provider?.toUpperCase() || "UNKNOWN";
27
- console.log(`[${getTimeString()}] 🌊 [STREAM] ${p} | ${model || "unknown"} | ${duration}ms | ${status}`);
28
+ const emit = isError ? log?.errorLine : log?.line;
29
+ if (emit) emit(reqTag, symbol, `${status} · ${provider}/${model} · ${duration}ms`);
30
+ else console.log(`[${getTimeString()}] ${symbol} ${provider}/${model} · ${status} · ${duration}ms`);
28
31
  };
29
32
 
30
33
  return {
@@ -38,7 +41,7 @@ export function createStreamController({ onDisconnect, onError, log, provider, m
38
41
  if (disconnected) return;
39
42
  disconnected = true;
40
43
 
41
- logStream(`disconnect: ${reason}`);
44
+ logStream("⚡", `DISCONNECT: ${reason}`);
42
45
  dbg("CTRL", `${provider}/${model} | disconnect=${reason} | dur=${Date.now() - startTime}ms`);
43
46
 
44
47
  // Delay abort to allow cleanup
@@ -49,13 +52,11 @@ export function createStreamController({ onDisconnect, onError, log, provider, m
49
52
  onDisconnect?.({ reason, duration: Date.now() - startTime });
50
53
  },
51
54
 
52
- // Call when stream completes normally
55
+ // Call when stream completes normally (no line here — "📊 done" is authoritative)
53
56
  handleComplete: () => {
54
57
  if (disconnected) return;
55
58
  disconnected = true;
56
59
 
57
- logStream("complete");
58
-
59
60
  if (abortTimeout) {
60
61
  clearTimeout(abortTimeout);
61
62
  abortTimeout = null;
@@ -73,11 +74,11 @@ export function createStreamController({ onDisconnect, onError, log, provider, m
73
74
  }
74
75
 
75
76
  if (error.name === "AbortError") {
76
- logStream("aborted");
77
+ logStream("", "ABORTED");
77
78
  return;
78
79
  }
79
80
 
80
- logStream(`error: ${error.message}`);
81
+ logStream("✗", `ERROR: ${error.message}${error.stack ? `\n ${error.stack}` : ""}`, true);
81
82
  onError?.(error);
82
83
  },
83
84
 
@@ -128,7 +129,10 @@ export function createDisconnectAwareStream(transformStream, streamController, o
128
129
  controller.enqueue(value);
129
130
  } catch (error) {
130
131
  const wasConnected = streamController.isConnected();
131
- streamController.handleError(error);
132
+ // Controller already closed = downstream ended; not an upstream error, skip noisy log.
133
+ const msg0 = error?.message || "";
134
+ const isControllerClosed = msg0.includes("already closed") || msg0.includes("Invalid state");
135
+ if (!isControllerClosed) streamController.handleError(error);
132
136
  reader.cancel().catch(() => {});
133
137
  writer.abort().catch(() => {});
134
138
 
@@ -184,7 +188,7 @@ export function createDisconnectAwareStream(transformStream, streamController, o
184
188
  * @param {TransformStream} transformStream - Transform stream for SSE
185
189
  * @param {object} streamController - Stream controller from createStreamController
186
190
  */
187
- export function pipeWithDisconnect(providerResponse, transformStream, streamController, onAbortTerminal = null) {
191
+ export function pipeWithDisconnect(providerResponse, transformStream, streamController, onAbortTerminal = null, stallTimeoutMs = STREAM_STALL_TIMEOUT_MS) {
188
192
  let stallTimer = null;
189
193
  let chunkCount = 0;
190
194
  let totalBytes = 0;
@@ -198,10 +202,10 @@ export function pipeWithDisconnect(providerResponse, transformStream, streamCont
198
202
  clearStall();
199
203
  stallTimer = setTimeout(() => {
200
204
  stallTimer = null;
201
- dbg(tag, `STALL TIMEOUT ${STREAM_STALL_TIMEOUT_MS}ms | chunks=${chunkCount} | bytes=${totalBytes} | sinceLast=${Date.now() - lastChunkAt}ms`);
205
+ dbg(tag, `STALL TIMEOUT ${stallTimeoutMs}ms | chunks=${chunkCount} | bytes=${totalBytes} | sinceLast=${Date.now() - lastChunkAt}ms`);
202
206
  streamController.handleError?.(new Error("stream stall timeout"));
203
207
  streamController.abort?.();
204
- }, STREAM_STALL_TIMEOUT_MS);
208
+ }, stallTimeoutMs);
205
209
  };
206
210
 
207
211
  // Wrap controller so every termination path clears the stall timer.
@@ -218,7 +222,7 @@ export function pipeWithDisconnect(providerResponse, transformStream, streamCont
218
222
  };
219
223
 
220
224
  armStall();
221
- dbg(tag, `pipe start | stallTimeout=${STREAM_STALL_TIMEOUT_MS}ms`);
225
+ dbg(tag, `pipe start | stallTimeout=${stallTimeoutMs}ms`);
222
226
 
223
227
  const upstreamTap = new TransformStream({
224
228
  transform(chunk, controller) {
@@ -17,19 +17,6 @@ export function parseSSELine(line, format = null) {
17
17
  return null;
18
18
  }
19
19
 
20
- // Handle raw JSON errors disguised as SSE
21
- if (line.charCodeAt(0) === 123) { // '{' = 123
22
- try {
23
- const parsedJson = JSON.parse(line.trim());
24
- // Check if it looks like an error payload
25
- if (parsedJson && (parsedJson.error || parsedJson.code !== undefined || parsedJson.msg)) {
26
- return { _isRawError: true, raw: parsedJson };
27
- }
28
- } catch (e) {
29
- // Ignore parse errors, continue to normal SSE check
30
- }
31
- }
32
-
33
20
  // Standard SSE format: "data: {...}"
34
21
  if (line.charCodeAt(0) !== 100) return null; // 'd' = 100
35
22
 
@@ -51,13 +38,11 @@ export function hasValuableContent(chunk, format) {
51
38
  // OpenAI format
52
39
  if (format === FORMATS.OPENAI && chunk.choices?.[0]?.delta) {
53
40
  const delta = chunk.choices[0].delta;
54
- return !!(delta.content && delta.content !== "" ||
41
+ return delta.content && delta.content !== "" ||
55
42
  delta.reasoning_content && delta.reasoning_content !== "" ||
56
43
  delta.tool_calls && delta.tool_calls.length > 0 ||
57
- delta.refusal && delta.refusal !== "" ||
58
44
  chunk.choices[0].finish_reason ||
59
- delta.role ||
60
- chunk.usage);
45
+ delta.role;
61
46
  }
62
47
 
63
48
  // Claude format
@@ -2,9 +2,11 @@
2
2
  * Token Usage Tracking - Extract, normalize, estimate and log token usage
3
3
  */
4
4
 
5
- import { saveRequestUsage, appendRequestLog } from '../../dist/lib/usageDb.js';
6
5
  import { FORMATS } from "../translator/formats.js";
7
6
 
7
+ // Legacy per-chunk usage console line; off by default (superseded by "📊 done")
8
+ const DEBUG_USAGE = process.env.LOG_USAGE_VERBOSE === "1";
9
+
8
10
  // ANSI color codes
9
11
  export const COLORS = {
10
12
  reset: "\x1b[0m",
@@ -142,6 +144,68 @@ export function normalizeUsage(usage) {
142
144
  return normalized;
143
145
  }
144
146
 
147
+ /**
148
+ * Canonicalize usage into ONE storage/cost convention so token counts and cost
149
+ * are consistent across providers:
150
+ * prompt_tokens = total input INCLUDING cache read + cache creation
151
+ * cached_tokens = cache-read portion (subset of prompt_tokens)
152
+ * cache_creation_input_tokens = cache-write portion (subset of prompt_tokens)
153
+ * completion_tokens, reasoning_tokens, total_tokens
154
+ *
155
+ * Discriminator: Claude reports cache_read_input_tokens with a prompt that
156
+ * EXCLUDES cache, so we fold cache into prompt. OpenAI/Gemini report
157
+ * cached_tokens already counted inside prompt, so we pass through. Idempotent:
158
+ * once folded the output carries cached_tokens (not cache_read_input_tokens),
159
+ * so re-running takes the passthrough branch and does not double-add.
160
+ *
161
+ * @param {object} usage - a normalizeUsage()-shaped object
162
+ * @returns {object|null} canonical token object, or null for invalid input
163
+ */
164
+ export function canonicalizeUsage(usage) {
165
+ if (!usage || typeof usage !== "object" || Array.isArray(usage)) return null;
166
+
167
+ const num = (v) => (Number.isFinite(Number(v)) ? Number(v) : 0);
168
+ const completion = num(usage.completion_tokens ?? usage.output_tokens);
169
+ const reasoning = num(usage.reasoning_tokens);
170
+ // Fall back to the nested prompt_tokens_details.cache_creation_tokens shape
171
+ // (buildUsage()'s OpenAI-forwarding format) when the top-level field is
172
+ // absent, so callers that pass a buildUsage() object through don't silently
173
+ // drop cache_creation.
174
+ const cacheCreation = num(usage.cache_creation_input_tokens ?? usage.prompt_tokens_details?.cache_creation_tokens);
175
+
176
+ let prompt = num(usage.prompt_tokens ?? usage.input_tokens);
177
+ let cached;
178
+
179
+ // Claude path: prompt excludes cache; cache_read_input_tokens and/or
180
+ // cache_creation_input_tokens are separate. A cache-miss "first write" only
181
+ // carries cache_creation_input_tokens (no cache_read_input_tokens yet), so
182
+ // check both fields — otherwise a first-write request falls through to the
183
+ // OpenAI passthrough branch below and cache_creation never gets folded in.
184
+ // Guard on the absence of `cached_tokens`: our own canonical output always
185
+ // sets that key (even to 0), so re-running canonicalizeUsage on an already-
186
+ // folded result takes the passthrough branch instead of folding again.
187
+ if (usage.cached_tokens === undefined &&
188
+ (usage.cache_read_input_tokens !== undefined || usage.cache_creation_input_tokens !== undefined)) {
189
+ cached = num(usage.cache_read_input_tokens);
190
+ prompt = prompt + cached + cacheCreation;
191
+ } else {
192
+ // OpenAI/Gemini path (or already-canonical input): prompt already includes cached_tokens.
193
+ cached = num(usage.cached_tokens);
194
+ }
195
+
196
+ const result = {
197
+ prompt_tokens: prompt,
198
+ completion_tokens: completion,
199
+ // Recompute rather than pass through: when the fold branch ran above,
200
+ // an upstream total_tokens (cache-exclusive) would otherwise be stale.
201
+ total_tokens: prompt + completion,
202
+ cached_tokens: cached,
203
+ cache_creation_input_tokens: cacheCreation,
204
+ };
205
+ if (reasoning > 0) result.reasoning_tokens = reasoning;
206
+ return result;
207
+ }
208
+
145
209
  /**
146
210
  * Check if usage has valid token data
147
211
  * Valid = has at least one token field with value > 0
@@ -172,6 +236,19 @@ export function hasValidUsage(usage) {
172
236
  export function extractUsage(chunk) {
173
237
  if (!chunk || typeof chunk !== "object") return null;
174
238
 
239
+ // Claude format (message_start event): carries input_tokens + cache_read +
240
+ // cache_creation. message_delta later carries only the final output_tokens,
241
+ // so callers must MERGE (mergeUsage), not overwrite, to keep cache counts.
242
+ if (chunk.type === "message_start" && chunk.message?.usage && typeof chunk.message.usage === "object") {
243
+ const u = chunk.message.usage;
244
+ return normalizeUsage({
245
+ prompt_tokens: u.input_tokens || 0,
246
+ completion_tokens: u.output_tokens || 0,
247
+ cache_read_input_tokens: u.cache_read_input_tokens,
248
+ cache_creation_input_tokens: u.cache_creation_input_tokens
249
+ });
250
+ }
251
+
175
252
  // Claude format (message_delta event)
176
253
  if (chunk.type === "message_delta" && chunk.usage && typeof chunk.usage === "object") {
177
254
  return normalizeUsage({
@@ -233,6 +310,27 @@ export function extractUsage(chunk) {
233
310
  return null;
234
311
  }
235
312
 
313
+ // Field-wise max-merge of two usage objects. Anthropic splits usage across
314
+ // events: message_start has real input+cache (output is a placeholder 1),
315
+ // message_delta has the real cumulative output (input/cache absent). Max keeps
316
+ // the meaningful value from each without clobbering. Idempotent for other
317
+ // providers that emit a single complete usage object.
318
+ export function mergeUsage(prev, next) {
319
+ if (!prev) return next || null;
320
+ if (!next) return prev;
321
+ const merged = { ...prev };
322
+ for (const [k, v] of Object.entries(next)) {
323
+ // typeof NaN === "number" — guard with Number.isFinite so one malformed
324
+ // chunk can't poison the whole accumulation (Math.max(x, NaN) is NaN).
325
+ if (typeof v === "number" && Number.isFinite(v)) {
326
+ merged[k] = Math.max(typeof merged[k] === "number" ? merged[k] : 0, v);
327
+ } else if (v && typeof v === "object") {
328
+ merged[k] = v; // nested details objects: take latest
329
+ }
330
+ }
331
+ return merged;
332
+ }
333
+
236
334
  /**
237
335
  * Estimate input tokens from request body
238
336
  * Calculate total body size for more accurate estimation
@@ -306,6 +404,10 @@ export function estimateUsage(body, contentLength, targetFormat = FORMATS.OPENAI
306
404
  export function logUsage(provider, usage, model = null, connectionId = null, apiKey = null) {
307
405
  if (!usage || typeof usage !== "object") return;
308
406
 
407
+ // Console output moved to the unified "📊 done" line (streamingHandler). Kept as
408
+ // a no-op hook so callers stay unchanged; usage persistence happens via saveUsageStats.
409
+ if (!DEBUG_USAGE) return;
410
+
309
411
  const p = provider?.toUpperCase() || "UNKNOWN";
310
412
 
311
413
  // Support both formats:
@@ -333,15 +435,4 @@ export function logUsage(provider, usage, model = null, connectionId = null, api
333
435
  if (reasoning) msg += ` | reasoning=${reasoning}`;
334
436
 
335
437
  console.log(msg);
336
-
337
- // Save to usage DB
338
- const tokens = {
339
- prompt_tokens: inTokens,
340
- completion_tokens: outTokens,
341
- cache_read_input_tokens: cacheRead || 0,
342
- cache_creation_input_tokens: cacheCreation || 0,
343
- reasoning_tokens: reasoning || 0
344
- };
345
- saveRequestUsage({ model, provider, connectionId, tokens, apiKey: apiKey || undefined }).catch(() => { });
346
- appendRequestLog({ model, provider, connectionId, tokens, status: "200 OK" }).catch(() => { });
347
438
  }
package/package.json CHANGED
@@ -1,18 +1,15 @@
1
1
  {
2
2
  "name": "@fudrouter/fsrouter",
3
- "version": "0.6.72",
3
+ "version": "0.6.74",
4
4
  "private": false,
5
5
  "type": "module",
6
- "description": "9Router v2 \u2014 Express Backend (API, SSE, DB, Auth, MITM)",
6
+ "description": "9Router v2 Express Backend (API, SSE, DB, Auth, MITM)",
7
7
  "main": "dist/server.js",
8
8
  "bin": {
9
9
  "fsrouter": "bin/cli.cjs"
10
10
  },
11
11
  "scripts": {
12
- "dev": "tsx watch src/server.ts",
13
- "start": "node dist/server.js",
14
- "build": "tsc --project tsconfig.json || true && node bin/rewriteSseImports.js && node bin/copyJs.js",
15
- "typecheck": "tsc --noEmit"
12
+ "start": "node dist/server.js"
16
13
  },
17
14
  "dependencies": {
18
15
  "bcryptjs": "^3.0.3",
@@ -40,4 +37,4 @@
40
37
  "open-sse": "./open-sse/index.js",
41
38
  "open-sse/*": "./open-sse/*"
42
39
  }
43
- }
40
+ }
@@ -0,0 +1,6 @@
1
+ import{r as tt,v as $t,u as zt,j as e,B as c,M as q,C as Bt,f as Vt}from"./index.Be3gbrBl.js";import{b as a}from"./router.Cjj1--8t.js";import{C as st,I as ee,T as Ie}from"./NoAuthProxyCard.BDcXaWvM.js";import{C as at}from"./Loading.BHPtQ9vj.js";const Jt=["zh-CN","zh-TW"],Gt=[{icon:"public",title:"Access Anywhere",desc:"Use your API from any network"},{icon:"group",title:"Share Endpoint",desc:"Share URL with team members"},{icon:"code",title:"Use in Cursor/Cline",desc:"Connect AI tools remotely"},{icon:"lock",title:"Encrypted",desc:"End-to-end TLS via Cloudflare"}],De=2e3,nt=3e5,Xt=5e3,Oe=5,Yt=1e4,Qt=5e3;async function lt(h){if(!h)return!1;try{return(await fetch(`${h}/api/health`,{mode:"cors",cache:"no-store",signal:AbortSignal.timeout(Qt)})).ok}catch{return!1}}async function Zt(...h){const d=h.filter(Boolean).map(lt);return d.length?new Promise(x=>{let j=d.length;d.forEach(L=>L.then(b=>{b?x(!0):--j===0&&x(!1)}))}):!1}const He=[{id:"lite",label:"Lite",desc:"Drop filler, keep grammar"},{id:"full",label:"Full",desc:"Drop articles, fragments OK"},{id:"ultra",label:"Ultra",desc:"Telegraphic, max compression"},{id:"wenyan-lite",label:"文 Lite",desc:"Classical Chinese, light compression",wenyan:!0},{id:"wenyan",label:"文 Full",desc:"Maximum 文言文, 80-90% reduction",wenyan:!0},{id:"wenyan-ultra",label:"文 Ultra",desc:"Extreme classical compression",wenyan:!0}];function es({machineId:h}){const[d,x]=a.useState([]),[j,L]=a.useState(!0),[b,N]=a.useState(!1),[te,se]=a.useState(""),[be,ye]=a.useState(null),[w,$]=a.useState(null),[ae,Fe]=a.useState(!1),[z,rt]=a.useState(!0),[Me,it]=a.useState(!0),[Ke,We]=a.useState(!1),[ot,qe]=a.useState("en"),[ct,je]=a.useState(!0),[p,ne]=a.useState(!1),[U,le]=a.useState(!1),[R,re]=a.useState(""),[I,we]=a.useState(""),[P,C]=a.useState(!1),[dt,T]=a.useState(""),[ie,v]=a.useState(null),[ut,B]=a.useState(!1),[mt,V]=a.useState(!1),[f,D]=a.useState(!1),[O,oe]=a.useState(!1),[H,F]=a.useState(""),[A,J]=a.useState(!1),[ht,_]=a.useState(""),[M,u]=a.useState(null),[$e,ze]=a.useState(""),[xt,Be]=a.useState(""),[ve,ce]=a.useState(null),[de,ke]=a.useState(!1),[Ne,Ce]=a.useState([]),[pt,Ve]=a.useState(""),[ft,Te]=a.useState(!1),[gt,K]=a.useState(!1),[bt,G]=a.useState(!1),ue=a.useRef(null),X=a.useRef(0),Y=a.useRef(0),me=a.useRef(!1),he=a.useRef(!1),xe=a.useRef(!1),pe=a.useRef(!1),[yt,Se]=a.useState(!1),[jt,Ee]=a.useState(!1),[Pe,Je]=a.useState(new Set),[wt,vt]=a.useState(!1);a.useEffect(()=>{typeof window<"u"&&vt(!["localhost","127.0.0.1","::1"].includes(window.location.hostname))},[]),a.useEffect(()=>(qe(tt()),$t(()=>qe(tt()))),[]);const Ae=Jt.includes(ot);Ae||He.filter(t=>!t.wenyan),a.useEffect(()=>{const t=He.find(s=>s.id===cavemanLevel);t!=null&&t.wenyan&&!Ae&&(setCavemanLevel("ultra"),Et({cavemanLevel:"ultra"}))},[Ae,cavemanLevel]);const{copied:W,copy:Q}=zt(),kt=!z||!Me,Nt=z?"Change the default dashboard password before activating the tunnel.":'Enable "Require login" and set a custom password before activating the tunnel.';a.useEffect(()=>{ue.current&&(ue.current.scrollTop=ue.current.scrollHeight)},[Ne]),a.useEffect(()=>{Xe(),Ct()},[]),a.useEffect(()=>{if(!(p||f))return;const n=(!p||U)&&(!f||O),r=()=>{document.hidden||Ge()};if(document.addEventListener("visibilitychange",r),n)return()=>document.removeEventListener("visibilitychange",r);const o=setInterval(()=>{document.hidden||Ge()},Xt);return()=>{clearInterval(o),document.removeEventListener("visibilitychange",r)}},[p,f,U,O]),a.useEffect(()=>{const t=async()=>{if(!document.hidden){if(p&&(R||I)){const o=await Zt(I,R);me.current=o,o?(X.current=0,le(!0),xe.current||(xe.current=!0,Se(!0))):(X.current+=1,X.current>=Oe&&le(!1))}else me.current=!1;if(f&&H){const o=await lt(H);he.current=o,o?(Y.current=0,oe(!0),pe.current||(pe.current=!0,Ee(!0))):(Y.current+=1,Y.current>=Oe&&oe(!1))}else he.current=!1}};if(!(p&&(R||I)||f&&H)||(t(),(!p||U)&&(!f||O)))return;const r=setInterval(t,Yt);return()=>clearInterval(r)},[p,R,I,f,H,U,O]);const fe=a.useCallback((t,s,l,n,r,o)=>{s.current?(l.current=0,n(!0),r.current||(r.current=!0,o(!0))):(l.current+=1,l.current>=Oe&&n(!1))},[]),Ge=async()=>{var t,s,l,n,r,o,m;try{const y=await fetch("/api/tunnel/status",{cache:"no-store"});if(!y.ok)return;const g=await y.json(),i=((t=g.tunnel)==null?void 0:t.settingsEnabled)??((s=g.tunnel)==null?void 0:s.enabled)??!1,E=((l=g.tunnel)==null?void 0:l.tunnelUrl)||"";re(E),we(((n=g.tunnel)==null?void 0:n.publicUrl)||""),ne(i),fe(null,me,X,le,xe,Se);const k=((r=g.tailscale)==null?void 0:r.settingsEnabled)??((o=g.tailscale)==null?void 0:o.enabled)??!1,Re=((m=g.tailscale)==null?void 0:m.tunnelUrl)||"";F(Re),D(k),fe(null,he,Y,oe,pe,Ee)}catch{}},Ct=async()=>{var t,s,l,n,r,o,m;je(!0);try{const[y,g]=await Promise.all([fetch("/api/settings"),fetch("/api/tunnel/status",{cache:"no-store"})]);if(y.ok){const i=await y.json();Fe(i.requireApiKey||!1),rt(i.requireLogin!==!1),it(i.hasPassword||!1),We(i.tunnelDashboardAccess||!1),setRtkEnabledState(i.rtkEnabled!==!1),setCavemanEnabled(!!i.cavemanEnabled),setCavemanLevel(i.cavemanLevel||"full"),setHeadroomEnabled(!!i.headroomEnabled),setHeadroomUrl(i.headroomUrl||""),setHeadroomCompressUserMessages(!!i.headroomCompressUserMessages),setPonytailEnabled(!!i.ponytailEnabled),setPonytailLevel(i.ponytailLevel||"full"),setPaleoEnabled(!!i.paleoEnabled),setPaleoLevel(i.paleoLevel||"full"),Z()}if(g.ok){const i=await g.json(),E=((t=i.tunnel)==null?void 0:t.settingsEnabled)??((s=i.tunnel)==null?void 0:s.enabled)??!1,k=((l=i.tunnel)==null?void 0:l.tunnelUrl)||"";re(k),we(((n=i.tunnel)==null?void 0:n.publicUrl)||""),ne(E),fe(null,me,X,le,xe,Se);const Re=((r=i.tailscale)==null?void 0:r.settingsEnabled)??((o=i.tailscale)==null?void 0:o.enabled)??!1,qt=((m=i.tailscale)==null?void 0:m.tunnelUrl)||"";F(qt),D(Re),fe(null,he,Y,oe,pe,Ee)}}catch(y){console.log("Error loading settings:",y)}finally{je(!1)}},Tt=async t=>{try{(await fetch("/api/settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({tunnelDashboardAccess:t})})).ok&&We(t)}catch(s){console.log("Error updating tunnelDashboardAccess:",s)}},St=async t=>{try{(await fetch("/api/settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({requireApiKey:t})})).ok&&Fe(t)}catch(s){console.log("Error updating requireApiKey:",s)}},Et=async t=>{try{await fetch("/api/settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}catch(s){console.log("Error updating setting:",s)}},Z=a.useCallback(async()=>{setHeadroomStatus(t=>({...t,loading:!0}));try{const s=await(await fetch("/api/headroom/status",{headers:{"Cache-Control":"no-store"}})).json();setHeadroomStatus({...s,loading:!1}),s.url&&!headroomUrl&&setHeadroomUrl(s.url)}catch{setHeadroomStatus({installed:!1,running:!1,python:null,loading:!1})}},[headroomUrl]);a.useCallback(async()=>{setHeadroomActionError(""),setHeadroomActionLoading(!0);try{const t=await fetch("/api/headroom/start",{method:"POST"}),s=await t.json().catch(()=>({}));if(!t.ok)throw new Error(s.error||"Failed to start proxy");await Z()}catch(t){setHeadroomActionError(t.message)}finally{setHeadroomActionLoading(!1)}},[Z]),a.useCallback(async()=>{setHeadroomActionLoading(!0);try{await fetch("/api/headroom/stop",{method:"POST"}),await Z()}finally{setHeadroomActionLoading(!1)}},[Z]);const Xe=async()=>{try{const t=await fetch("/api/keys"),s=await t.json();t.ok&&x(s.keys||[])}catch(t){console.log("Error fetching data:",t)}finally{L(!1)}},Pt=async(...t)=>{var n;C(!0),T("Waiting for tunnel ready...");const s=t.filter(Boolean).map(r=>`${r}/api/health`),l=Date.now();for(;Date.now()-l<nt;){if(await new Promise(o=>setTimeout(o,De)),await Promise.any(s.map(async o=>{if((await fetch(o,{mode:"cors",cache:"no-store"})).ok)return!0;throw new Error("not ready")})).catch(()=>!1))return ne(!0),C(!1),T(""),!0;if((Date.now()-l)%1e4<De)try{const o=await fetch("/api/tunnel/status");if(o.ok&&!((n=(await o.json()).tunnel)!=null&&n.enabled))return v({type:"error",message:"Tunnel process stopped unexpectedly."}),C(!1),T(""),!1}catch{}}return v({type:"error",message:"Tunnel created but not reachable. Please try again."}),C(!1),T(""),!1},At=async()=>{B(!1),C(!0),v(null),T("Creating tunnel...");let t=!0;(async()=>{var l;for(;t;){try{const n=await fetch("/api/tunnel/status");if(n.ok){const r=await n.json();(l=r.download)!=null&&l.downloading?T(`Downloading cloudflared... ${r.download.progress}%`):t&&T("Creating tunnel...")}}catch{}await new Promise(n=>setTimeout(n,1e3))}})();try{const l=await fetch("/api/tunnel/enable",{method:"POST"});t=!1;const n=await l.json();if(!l.ok){v({type:"error",message:n.error||"Failed to enable tunnel"});return}const r=n.tunnelUrl;if(!r){v({type:"error",message:"No tunnel URL returned"});return}re(r),we(n.publicUrl||""),await Pt(n.publicUrl,r)}catch(l){v({type:"error",message:l.message})}finally{t=!1,C(!1),T("")}},_t=async()=>{C(!0),v(null);try{const t=await fetch("/api/tunnel/disable",{method:"POST"}),s=await t.json();t.ok?(ne(!1),re(""),V(!1),v({type:"success",message:"Tunnel disabled"})):v({type:"error",message:s.error||"Failed to disable tunnel"})}catch(t){v({type:"error",message:t.message})}finally{C(!1)}},Lt=async()=>{ce(null);try{const t=await fetch("/api/tunnel/tailscale-check");if(t.ok){const s=await t.json();return ce(s.installed),s}}catch{}return ce(!1),{installed:!1}},Ut=async()=>{ke(!0),u(null),Ce([]);try{const t=await fetch("/api/tunnel/tailscale-install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sudoPassword:pt})});Ve("");const s=t.body.getReader(),l=new TextDecoder;let n="";for(;;){const{done:r,value:o}=await s.read();if(r)break;n+=l.decode(o,{stream:!0});const m=n.split(`
2
+
3
+ `);n=m.pop()||"";for(const y of m){const g=y.split(`
4
+ `);let i="progress",E=null;for(const k of g)if(k.startsWith("event: ")&&(i=k.slice(7).trim()),k.startsWith("data: "))try{E=JSON.parse(k.slice(6))}catch{}if(E)if(i==="progress")Ce(k=>[...k.slice(-50),E.message]);else if(i==="done"){ce(!0),ke(!1),K(!1),Le();return}else i==="error"&&u({type:"error",message:E.error||"Install failed"})}}}catch(t){u({type:"error",message:t.message})}finally{ke(!1)}},_e=async t=>{_("Waiting for Tailscale ready...");const s=`${t}/api/health`,l=Date.now();for(;Date.now()-l<nt;){await new Promise(n=>setTimeout(n,De));try{const n=await fetch(s,{mode:"no-cors",cache:"no-store"});if(n.ok||n.type==="opaque")return!0}catch{}}return!1},Ye=(t,s)=>{ze(t),Be(s)},S=()=>{ze(""),Be("")},Le=async()=>{K(!1),Te(!0),J(!0),u(null),_("Connecting..."),S();try{const t=await fetch("/api/tunnel/tailscale-enable",{method:"POST"}),s=await t.json();if(t.ok&&s.success){F(s.tunnelUrl||"");const l=await _e(s.tunnelUrl);D(!0),u(l?null:{type:"warning",message:"Connected but not reachable yet."});return}if(s.needsLogin&&s.authUrl){Ye(s.authUrl,"Open Login Page"),_('Login required — click "Open Login Page" to continue');for(let l=0;l<40;l++){await new Promise(n=>setTimeout(n,3e3));try{const n=await fetch("/api/tunnel/tailscale-check");if(n.ok&&(await n.json()).loggedIn){S(),_("Starting funnel...");const o=await fetch("/api/tunnel/tailscale-enable",{method:"POST"}),m=await o.json();if(o.ok&&m.success){F(m.tunnelUrl||"");const y=await _e(m.tunnelUrl);D(!0),u(y?null:{type:"warning",message:"Connected but not reachable yet."})}else m.funnelNotEnabled&&m.enableUrl?await Qe(m.enableUrl):u({type:"error",message:m.error||"Failed to start funnel"});return}}catch{}}S(),u({type:"error",message:"Login timed out. Please try again."});return}if(s.funnelNotEnabled&&s.enableUrl){await Qe(s.enableUrl);return}u({type:"error",message:s.error||"Failed to connect"})}catch(t){u({type:"error",message:t.message})}finally{J(!1),Te(!1),_(""),S()}},Qe=async t=>{Ye(t,"Open Funnel Settings"),_('Click "Open Funnel Settings" to enable Funnel...');for(let s=0;s<40;s++){await new Promise(l=>setTimeout(l,3e3));try{const l=await fetch("/api/tunnel/tailscale-enable",{method:"POST"}),n=await l.json();if(l.ok&&n.success){S(),F(n.tunnelUrl||"");const r=await _e(n.tunnelUrl);D(!0),u(r?null:{type:"warning",message:"Connected but not reachable yet."});return}if(n.funnelNotEnabled)continue;if(n.error){S(),u({type:"error",message:n.error});return}}catch{}}S(),u({type:"error",message:"Timed out waiting for Funnel to be enabled."})},Rt=async()=>{J(!0),u(null);try{const t=await fetch("/api/tunnel/tailscale-disable",{method:"POST"}),s=await t.json();t.ok?(D(!1),F(""),G(!1),u({type:"success",message:"Tailscale disabled"})):u({type:"error",message:s.error||"Failed to disable Tailscale"})}catch(t){u({type:"error",message:t.message})}finally{J(!1)}},Ze=async()=>{u(null),Ce([]);const t=await Lt();t!=null&&t.installed&&(t!=null&&t.hasCachedPassword)?Le():K(!0)},It=async()=>{if(te.trim())try{const t=await fetch("/api/keys",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:te})}),s=await t.json();t.ok&&(ye(s.key),await Xe(),se(""),N(!1))}catch(t){console.log("Error creating key:",t)}},Dt=async t=>{$({title:"Delete API Key",message:"Delete this API key?",onConfirm:async()=>{$(null);try{(await fetch(`/api/keys/${t}`,{method:"DELETE"})).ok&&(x(d.filter(l=>l.id!==t)),Je(l=>{const n=new Set(l);return n.delete(t),n}))}catch(s){console.log("Error deleting key:",s)}}})},et=async(t,s)=>{try{(await fetch(`/api/keys/${t}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({isActive:s})})).ok&&x(n=>n.map(r=>r.id===t?{...r,isActive:s}:r))}catch(l){console.log("Error toggling key:",l)}},Ot=t=>t?t.length>8?t.slice(0,8)+"...":t:"",Ht=t=>{Je(s=>{const l=new Set(s);return l.has(t)?l.delete(t):l.add(t),l})},[Ft,Mt]=a.useState("/v1");if(a.useEffect(()=>{typeof window<"u"&&Mt(`${window.location.origin}/v1`)},[]),j)return e.jsxs("div",{className:"flex flex-col gap-8",children:[e.jsx(at,{}),e.jsx(at,{})]});const Kt=Ft,Wt=!!headroomStatus.running,Ue=headroomStatus.localUrl!==!1;return headroomStatus.canStart,Ue&&headroomStatus.managedPid,headroomStatus.loading||Wt||Ue&&headroomStatus.installed,e.jsxs("div",{className:"flex flex-col gap-8",children:[e.jsxs(st,{children:[e.jsxs("h2",{className:"text-lg font-semibold mb-4 flex items-center gap-2",children:[e.jsx("span",{className:"material-symbols-outlined text-primary",children:"api"}),"API Endpoint"]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(ts,{label:"Local",url:Kt,copyId:"local_url",copied:W,onCopy:Q}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`text-xs font-mono px-1.5 py-0.5 rounded shrink-0 min-w-[88px] text-center ${p?"bg-primary/10 text-primary":"bg-surface-2 text-text-muted"}`,children:"Tunnel"}),p&&!P&&U?e.jsxs(e.Fragment,{children:[e.jsx(ee,{value:`${I||R}/v1`,readOnly:!0,className:"flex-1 font-mono text-sm"}),e.jsx("button",{onClick:()=>Q(`${I||R}/v1`,"tunnel_url"),className:"p-2 hover:bg-black/5 dark:hover:bg-white/5 rounded text-text-muted hover:text-primary transition-colors shrink-0",children:e.jsx("span",{className:"material-symbols-outlined text-[18px]",children:W==="tunnel_url"?"check":"content_copy"})}),e.jsx("button",{onClick:()=>V(!0),className:"p-2 hover:bg-red-500/10 rounded text-red-500 transition-colors shrink-0",title:"Disable Tunnel",children:e.jsx("span",{className:"material-symbols-outlined text-[18px]",children:"power_settings_new"})})]}):p&&!P&&!U?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex-1 flex items-center gap-2 px-3 py-1.5 rounded border border-amber-300 dark:border-amber-800 bg-amber-500/5 text-sm text-amber-600 dark:text-amber-400",children:[e.jsx("span",{className:"material-symbols-outlined animate-spin text-sm",children:"progress_activity"}),yt?"Tunnel reconnecting...":"Tunnel checking..."]}),e.jsx("button",{onClick:()=>V(!0),className:"p-2 hover:bg-red-500/10 rounded text-red-500 transition-colors shrink-0",title:"Disable Tunnel",children:e.jsx("span",{className:"material-symbols-outlined text-[18px]",children:"power_settings_new"})})]}):P?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex-1 flex items-center gap-2 px-3 py-1.5 rounded border border-border bg-input text-sm text-text-muted",children:[e.jsx("span",{className:"material-symbols-outlined animate-spin text-sm",children:"progress_activity"}),dt||"Creating tunnel..."]}),e.jsx("button",{onClick:()=>{C(!1),T("")},className:"p-2 hover:bg-red-500/10 rounded text-red-500 transition-colors shrink-0",title:"Stop",children:e.jsx("span",{className:"material-symbols-outlined text-[18px]",children:"power_settings_new"})})]}):(ie==null?void 0:ie.type)==="error"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex-1 flex items-center gap-2 px-3 py-1.5 rounded border border-red-300 dark:border-red-800 bg-red-500/5 text-sm text-red-600 dark:text-red-400",children:[e.jsx("span",{className:"material-symbols-outlined text-sm",children:"error"}),ie.message]}),e.jsx(c,{size:"sm",icon:"cloud_upload",onClick:()=>B(!0),children:"Enable"})]}):ct?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex-1 flex items-center gap-2 px-3 py-1.5 rounded border border-border bg-input text-sm text-text-muted",children:[e.jsx("span",{className:"material-symbols-outlined animate-spin text-sm",children:"progress_activity"}),"Checking..."]}),e.jsx("button",{onClick:()=>je(!1),className:"p-2 hover:bg-red-500/10 rounded text-red-500 transition-colors shrink-0",title:"Stop",children:e.jsx("span",{className:"material-symbols-outlined text-[18px]",children:"power_settings_new"})})]}):e.jsx(c,{size:"sm",icon:"cloud_upload",onClick:()=>{B(!0)},children:"Enable"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`text-xs font-mono px-1.5 py-0.5 rounded shrink-0 min-w-[88px] text-center ${f?"bg-primary/10 text-primary":"bg-surface-2 text-text-muted"}`,children:"Tailscale"}),f&&!A&&O?e.jsxs(e.Fragment,{children:[e.jsx(ee,{value:`${H}/v1`,readOnly:!0,className:"flex-1 font-mono text-sm"}),e.jsx("button",{onClick:()=>Q(`${H}/v1`,"ts_url"),className:"p-2 hover:bg-black/5 dark:hover:bg-white/5 rounded text-text-muted hover:text-primary transition-colors shrink-0",children:e.jsx("span",{className:"material-symbols-outlined text-[18px]",children:W==="ts_url"?"check":"content_copy"})}),e.jsx("button",{onClick:()=>G(!0),className:"p-2 hover:bg-red-500/10 rounded text-red-500 transition-colors shrink-0",title:"Disable Tailscale",children:e.jsx("span",{className:"material-symbols-outlined text-[18px]",children:"power_settings_new"})})]}):f&&!A&&!O?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex-1 flex items-center gap-2 px-3 py-1.5 rounded border border-amber-300 dark:border-amber-800 bg-amber-500/5 text-sm text-amber-600 dark:text-amber-400",children:[e.jsx("span",{className:"material-symbols-outlined animate-spin text-sm",children:"progress_activity"}),jt?"Tailscale reconnecting...":"Tailscale checking..."]}),e.jsx("button",{onClick:()=>G(!0),className:"p-2 hover:bg-red-500/10 rounded text-red-500 transition-colors shrink-0",title:"Disable Tailscale",children:e.jsx("span",{className:"material-symbols-outlined text-[18px]",children:"power_settings_new"})})]}):A||ft?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex-1 flex items-center gap-2 px-3 py-1.5 rounded border border-border bg-input text-sm text-text-muted",children:[e.jsx("span",{className:"material-symbols-outlined animate-spin text-sm",children:"progress_activity"}),ht||"Connecting..."]}),$e&&e.jsx(c,{size:"sm",icon:"open_in_new",onClick:()=>window.open($e,"tailscale_auth","width=600,height=700,noopener,noreferrer"),children:xt||"Open"}),e.jsx("button",{onClick:()=>{J(!1),Te(!1),_(""),S()},className:"p-2 hover:bg-red-500/10 rounded text-red-500 transition-colors shrink-0",title:"Stop",children:e.jsx("span",{className:"material-symbols-outlined text-[18px]",children:"power_settings_new"})})]}):(M==null?void 0:M.type)==="error"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex-1 flex items-center gap-2 px-3 py-1.5 rounded border border-red-300 dark:border-red-800 bg-red-500/5 text-sm text-red-600 dark:text-red-400",children:[e.jsx("span",{className:"material-symbols-outlined text-sm",children:"error"}),M.message]}),e.jsx(c,{size:"sm",icon:"vpn_lock",onClick:Ze,children:"Enable"})]}):e.jsx(c,{size:"sm",icon:"vpn_lock",onClick:()=>{Ze()},className:"bg-linear-to-r from-indigo-500 to-purple-500 hover:from-indigo-600 hover:to-purple-600 text-white!",children:"Enable"})]})]}),kt&&!p&&!f&&e.jsx("div",{className:"mt-4",children:e.jsx(ge,{message:Nt,action:{label:"Open settings",href:"/dashboard/profile"}})}),(p||f)&&e.jsxs("div",{className:"mt-4 flex flex-col gap-2",children:[!ae&&e.jsx(ge,{message:"Require API key is disabled — your endpoint is publicly accessible without authentication.",action:{label:"Enable",href:"#require-api-key"}}),(!z||!Me)&&e.jsx(ge,{message:z?"Dashboard uses the default password — change it in Profile settings.":"Require login is disabled — anyone can access your dashboard via tunnel.",action:{label:z?"Change password":"Enable",href:"/dashboard/profile"}})]}),(p||f)&&e.jsxs("div",{className:"mt-4 pt-4 border-t border-border flex items-center gap-3",children:[e.jsx(Ie,{checked:Ke,onChange:()=>Tt(!Ke)}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("p",{className:"font-medium text-sm",children:"Allow dashboard access via tunnel"}),e.jsx(as,{text:"When enabled, the dashboard can be accessed through your tunnel or Tailscale URL (login still required). When disabled, dashboard access via tunnel/Tailscale is completely blocked."})]})]})]}),e.jsxs(st,{id:"require-api-key",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("h2",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx("span",{className:"material-symbols-outlined text-primary",children:"vpn_key"}),"API Keys"]}),e.jsx(c,{icon:"add",onClick:()=>N(!0),children:"Create Key"})]}),e.jsxs("div",{className:"flex items-center justify-between pb-4 mb-4 border-b border-border",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Require API key"}),e.jsx("p",{className:"text-sm text-text-muted",children:"Requests without a valid key will be rejected"})]}),e.jsx(Ie,{checked:ae,onChange:()=>St(!ae)})]}),wt&&!ae&&e.jsx("div",{className:"mb-4 -mt-2",children:e.jsx(ge,{message:"Endpoint is exposed without an API key."})}),d.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx("div",{className:"inline-flex items-center justify-center w-16 h-16 rounded-full bg-primary/10 text-primary mb-4",children:e.jsx("span",{className:"material-symbols-outlined text-[32px]",children:"vpn_key"})}),e.jsx("p",{className:"text-text-main font-medium mb-1",children:"No API keys yet"}),e.jsx("p",{className:"text-sm text-text-muted mb-4",children:"Create your first API key to get started"}),e.jsx(c,{icon:"add",onClick:()=>N(!0),children:"Create Key"})]}):e.jsx("div",{className:"flex flex-col",children:d.map(t=>e.jsxs("div",{className:`group flex items-center justify-between py-3 border-b border-black/[0.03] dark:border-white/[0.03] last:border-b-0 ${t.isActive===!1?"opacity-60":""}`,children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:t.name}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("code",{className:"text-xs text-text-muted font-mono",children:Pe.has(t.id)?t.key:Ot(t.key)}),e.jsx("button",{onClick:()=>Ht(t.id),className:"p-1 hover:bg-black/5 dark:hover:bg-white/5 rounded text-text-muted hover:text-primary opacity-100 sm:opacity-0 sm:group-hover:opacity-100 transition-all",title:Pe.has(t.id)?"Hide key":"Show key",children:e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:Pe.has(t.id)?"visibility_off":"visibility"})}),e.jsx("button",{onClick:()=>Q(t.key,t.id),className:"p-1 hover:bg-black/5 dark:hover:bg-white/5 rounded text-text-muted hover:text-primary opacity-100 sm:opacity-0 sm:group-hover:opacity-100 transition-all",children:e.jsx("span",{className:"material-symbols-outlined text-[14px]",children:W===t.id?"check":"content_copy"})})]}),e.jsxs("p",{className:"text-xs text-text-muted mt-1",children:["Created ",new Date(t.createdAt).toLocaleDateString()]}),t.isActive===!1&&e.jsx("p",{className:"text-xs text-orange-500 mt-1",children:"Paused"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ie,{size:"sm",checked:t.isActive??!0,onChange:s=>{t.isActive&&!s?$({title:"Pause API Key",message:`Pause API key "${t.name}"?
5
+
6
+ This key will stop working immediately but can be resumed later.`,onConfirm:async()=>{$(null),et(t.id,s)}}):et(t.id,s)},title:t.isActive?"Pause key":"Resume key"}),e.jsx("button",{onClick:()=>Dt(t.id),className:"p-2 hover:bg-red-500/10 rounded text-red-500 opacity-100 sm:opacity-0 sm:group-hover:opacity-100 transition-all",children:e.jsx("span",{className:"material-symbols-outlined text-[18px]",children:"delete"})})]})]},t.id))})]}),e.jsx(q,{isOpen:b,title:"Create API Key",onClose:()=>{N(!1),se("")},children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsx(ee,{label:"Key Name",value:te,onChange:t=>se(t.target.value),placeholder:"Production Key"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(c,{onClick:It,fullWidth:!0,disabled:!te.trim(),children:"Create"}),e.jsx(c,{onClick:()=>{N(!1),se("")},variant:"ghost",fullWidth:!0,children:"Cancel"})]})]})}),e.jsx(q,{isOpen:!!be,title:"API Key Created",onClose:()=>ye(null),children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg p-4",children:[e.jsx("p",{className:"text-sm text-yellow-800 dark:text-yellow-200 mb-2 font-medium",children:"Save this key now!"}),e.jsx("p",{className:"text-sm text-yellow-700 dark:text-yellow-300",children:"This is the only time you will see this key. Store it securely."})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ee,{value:be||"",readOnly:!0,className:"flex-1 font-mono text-sm"}),e.jsx(c,{variant:"secondary",icon:W==="created_key"?"check":"content_copy",onClick:()=>Q(be,"created_key"),children:W==="created_key"?"Copied!":"Copy"})]}),e.jsx(c,{onClick:()=>ye(null),fullWidth:!0,children:"Done"})]})}),e.jsx(q,{isOpen:ut,title:"Enable Tunnel",onClose:()=>B(!1),children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsx("div",{className:"bg-surface-2 border border-border-subtle rounded-lg p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("span",{className:"material-symbols-outlined text-primary",children:"cloud_upload"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-text-main font-medium mb-1",children:"Cloudflare Tunnel"}),e.jsx("p",{className:"text-sm text-text-muted",children:"Expose your local FSRouter to the internet. No port forwarding, no static IP needed. Share endpoint URL with your team or use it in Cursor, Cline, and other AI tools from anywhere."})]})]})}),e.jsx("div",{className:"grid grid-cols-2 gap-3",children:Gt.map(t=>e.jsxs("div",{className:"flex flex-col items-center text-center p-3 rounded-lg bg-sidebar/50",children:[e.jsx("span",{className:"material-symbols-outlined text-xl text-primary mb-1",children:t.icon}),e.jsx("p",{className:"text-xs font-semibold",children:t.title}),e.jsx("p",{className:"text-xs text-text-muted",children:t.desc})]},t.title))}),e.jsx("p",{className:"text-xs text-text-muted",children:"Requires outbound port 7844 (TCP/UDP). Connection may take 10-30s."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(c,{onClick:At,fullWidth:!0,children:"Start Tunnel"}),e.jsx(c,{onClick:()=>B(!1),variant:"ghost",fullWidth:!0,children:"Cancel"})]})]})}),e.jsx(q,{isOpen:mt,title:"Disable Tunnel",onClose:()=>!P&&V(!1),children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsx("p",{className:"text-sm text-text-muted",children:"The Cloudflare tunnel will be disconnected. Remote access via tunnel URL will stop working."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(c,{onClick:_t,fullWidth:!0,disabled:P,variant:"danger",children:P?"Disabling...":"Disable"}),e.jsx(c,{onClick:()=>V(!1),variant:"ghost",fullWidth:!0,disabled:P,children:"Cancel"})]})]})}),e.jsx(q,{isOpen:gt,title:"Tailscale Funnel",onClose:()=>{de||(K(!1),Ve(""),u(null))},children:e.jsxs("div",{className:"flex flex-col gap-4",children:[ve===null&&e.jsxs("p",{className:"text-sm text-text-muted flex items-center gap-2",children:[e.jsx("span",{className:"material-symbols-outlined animate-spin text-sm",children:"progress_activity"}),"Checking..."]}),ve===!1&&!de&&e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsx("p",{className:"text-sm text-text-muted",children:"Tailscale is not installed. Install it to enable Funnel."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(c,{onClick:Ut,fullWidth:!0,children:"Install Tailscale"}),e.jsx(c,{onClick:()=>K(!1),variant:"ghost",fullWidth:!0,children:"Cancel"})]})]}),de&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-text-muted",children:[e.jsx("span",{className:"material-symbols-outlined animate-spin text-sm",children:"progress_activity"}),"Installing Tailscale..."]}),Ne.length>0&&e.jsx("div",{ref:ue,className:"bg-black/5 dark:bg-white/5 rounded p-2 max-h-40 overflow-y-auto font-mono text-xs text-text-muted",children:Ne.map((t,s)=>e.jsx("div",{children:t},s))})]}),ve===!0&&!de&&e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-green-600 dark:text-green-400",children:[e.jsx("span",{className:"material-symbols-outlined text-[16px]",children:"check_circle"}),"Tailscale installed"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(c,{onClick:()=>Le(),fullWidth:!0,children:"Connect"}),e.jsx(c,{onClick:()=>K(!1),variant:"ghost",fullWidth:!0,children:"Cancel"})]})]}),M&&e.jsx(ss,{status:M})]})}),e.jsx(q,{isOpen:bt,title:"Disable Tailscale",onClose:()=>!A&&G(!1),children:e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsx("p",{className:"text-sm text-text-muted",children:"Tailscale Funnel will be stopped. Remote access via Tailscale URL will stop working."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(c,{onClick:Rt,fullWidth:!0,disabled:A,variant:"danger",children:A?"Disabling...":"Disable"}),e.jsx(c,{onClick:()=>G(!1),variant:"ghost",fullWidth:!0,disabled:A,children:"Cancel"})]})]})}),e.jsx(Bt,{isOpen:!!w,onClose:()=>$(null),onConfirm:w==null?void 0:w.onConfirm,title:(w==null?void 0:w.title)||"Confirm",message:w==null?void 0:w.message,variant:"danger"})]})}function ts({label:h,url:d,copyId:x,copied:j,onCopy:L,badge:b,actions:N}){return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`text-xs font-mono px-1.5 py-0.5 rounded shrink-0 min-w-[88px] text-center ${b==="CF"||b==="TS"?"bg-primary/10 text-primary":"bg-surface-2 text-text-muted"}`,children:h}),e.jsx(ee,{value:d,readOnly:!0,className:"flex-1 font-mono text-sm"}),e.jsx("button",{onClick:()=>L(d,x),className:"p-2 hover:bg-black/5 dark:hover:bg-white/5 rounded text-text-muted hover:text-primary transition-colors shrink-0",children:e.jsx("span",{className:"material-symbols-outlined text-[18px]",children:j===x?"check":"content_copy"})}),N]})}function ss({status:h,className:d=""}){const x=j=>j.split(/(https?:\/\/[^\s]+)/g).map((b,N)=>/^https?:\/\//.test(b)?e.jsx("a",{href:b,target:"_blank",rel:"noreferrer",className:"underline font-medium",children:b},N):b);return e.jsx("div",{className:`p-2 rounded text-sm ${d} ${h.type==="success"?"bg-green-500/10 text-green-600 dark:text-green-400":h.type==="warning"?"bg-yellow-500/10 text-yellow-600 dark:text-yellow-400":h.type==="info"?"bg-blue-500/10 text-blue-600 dark:text-blue-400":"bg-red-500/10 text-red-600 dark:text-red-400"}`,children:x(h.message)})}function as({text:h}){return e.jsxs("span",{className:"relative group inline-flex items-center",children:[e.jsx("span",{className:"material-symbols-outlined text-[14px] text-text-muted cursor-help",children:"help"}),e.jsx("span",{className:"pointer-events-none absolute left-5 top-1/2 -translate-y-1/2 z-50 w-64 rounded bg-gray-900 dark:bg-gray-800 text-white text-xs px-2.5 py-1.5 opacity-0 group-hover:opacity-100 transition-opacity shadow-lg",children:h})]})}function ge({message:h,action:d}){return e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 rounded-lg bg-amber-500/10 border border-amber-500/20 text-amber-700 dark:text-amber-400",children:[e.jsx("span",{className:"material-symbols-outlined text-[16px] shrink-0 mt-0.5",children:"warning"}),e.jsx("p",{className:"text-xs flex-1",children:h}),d&&e.jsx("a",{href:d.href,className:"text-xs font-medium underline shrink-0 hover:opacity-80",onClick:d.href.startsWith("#")?x=>{var j;x.preventDefault(),(j=document.getElementById(d.href.slice(1)))==null||j.scrollIntoView({behavior:"smooth"})}:void 0,children:d.label})]})}es.propTypes={machineId:Vt.string.isRequired};export{es as A};