@whxway/loom 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (347) hide show
  1. package/.next/BUILD_ID +1 -1
  2. package/.next/build-manifest.json +3 -3
  3. package/.next/cache/.tsbuildinfo +1 -1
  4. package/.next/diagnostics/route-bundle-stats.json +35 -35
  5. package/.next/fallback-build-manifest.json +3 -3
  6. package/.next/server/app/(auth)/login/page_client-reference-manifest.js +1 -1
  7. package/.next/server/app/(dashboard)/logs/page_client-reference-manifest.js +1 -1
  8. package/.next/server/app/(dashboard)/mcp/page_client-reference-manifest.js +1 -1
  9. package/.next/server/app/(dashboard)/mcp/presets/page_client-reference-manifest.js +1 -1
  10. package/.next/server/app/(dashboard)/models/[name]/page_client-reference-manifest.js +1 -1
  11. package/.next/server/app/(dashboard)/page_client-reference-manifest.js +1 -1
  12. package/.next/server/app/(dashboard)/playground/audio/speech/page_client-reference-manifest.js +1 -1
  13. package/.next/server/app/(dashboard)/playground/audio/transcription/page_client-reference-manifest.js +1 -1
  14. package/.next/server/app/(dashboard)/playground/chat/page_client-reference-manifest.js +1 -1
  15. package/.next/server/app/(dashboard)/playground/embedding/page_client-reference-manifest.js +1 -1
  16. package/.next/server/app/(dashboard)/playground/image/page_client-reference-manifest.js +1 -1
  17. package/.next/server/app/(dashboard)/playground/page_client-reference-manifest.js +1 -1
  18. package/.next/server/app/(dashboard)/playground/video/page_client-reference-manifest.js +1 -1
  19. package/.next/server/app/(dashboard)/providers/[name]/page_client-reference-manifest.js +1 -1
  20. package/.next/server/app/(dashboard)/providers/page_client-reference-manifest.js +1 -1
  21. package/.next/server/app/(dashboard)/settings/api-keys/page_client-reference-manifest.js +1 -1
  22. package/.next/server/app/(dashboard)/settings/page_client-reference-manifest.js +1 -1
  23. package/.next/server/app/(dashboard)/settings/users/page_client-reference-manifest.js +1 -1
  24. package/.next/server/app/_global-error.html +1 -1
  25. package/.next/server/app/_global-error.rsc +1 -1
  26. package/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
  27. package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  28. package/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  29. package/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  30. package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  31. package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  32. package/.next/server/app/_not-found.html +2 -2
  33. package/.next/server/app/_not-found.rsc +3 -3
  34. package/.next/server/app/_not-found.segments/_full.segment.rsc +3 -3
  35. package/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
  36. package/.next/server/app/_not-found.segments/_index.segment.rsc +2 -2
  37. package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
  38. package/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
  39. package/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -2
  40. package/.next/server/app/api/adapters/route.js.nft.json +1 -1
  41. package/.next/server/app/api/apikeys/[id]/route.js.nft.json +1 -1
  42. package/.next/server/app/api/apikeys/route.js.nft.json +1 -1
  43. package/.next/server/app/api/capabilities/route.js.nft.json +1 -1
  44. package/.next/server/app/api/conversations/[id]/messages/route.js.nft.json +1 -1
  45. package/.next/server/app/api/conversations/[id]/route.js.nft.json +1 -1
  46. package/.next/server/app/api/conversations/route.js.nft.json +1 -1
  47. package/.next/server/app/api/health/route.js.nft.json +1 -1
  48. package/.next/server/app/api/login/route.js.nft.json +1 -1
  49. package/.next/server/app/api/logout/route.js.nft.json +1 -1
  50. package/.next/server/app/api/logs/generations/[id]/images/[idx]/route.js.nft.json +1 -1
  51. package/.next/server/app/api/logs/generations/[id]/route.js.nft.json +1 -1
  52. package/.next/server/app/api/logs/generations/route.js.nft.json +1 -1
  53. package/.next/server/app/api/mcp/presets/route.js.nft.json +1 -1
  54. package/.next/server/app/api/mcp/servers/[id]/check/route.js +1 -1
  55. package/.next/server/app/api/mcp/servers/[id]/check/route.js.nft.json +1 -1
  56. package/.next/server/app/api/mcp/servers/[id]/route.js.nft.json +1 -1
  57. package/.next/server/app/api/mcp/servers/[id]/tools/route.js.nft.json +1 -1
  58. package/.next/server/app/api/mcp/servers/route.js.nft.json +1 -1
  59. package/.next/server/app/api/messages/[id]/rate/route.js.nft.json +1 -1
  60. package/.next/server/app/api/models/[id]/route.js.nft.json +1 -1
  61. package/.next/server/app/api/models/route.js.nft.json +1 -1
  62. package/.next/server/app/api/ping/route.js.nft.json +1 -1
  63. package/.next/server/app/api/playground/chat/route.js +4 -4
  64. package/.next/server/app/api/playground/chat/route.js.nft.json +1 -1
  65. package/.next/server/app/api/playground/embedding/route.js +4 -4
  66. package/.next/server/app/api/playground/embedding/route.js.nft.json +1 -1
  67. package/.next/server/app/api/providers/[id]/check/route.js.nft.json +1 -1
  68. package/.next/server/app/api/providers/[id]/models/route.js.nft.json +1 -1
  69. package/.next/server/app/api/providers/[id]/route.js.nft.json +1 -1
  70. package/.next/server/app/api/providers/probe/route.js.nft.json +1 -1
  71. package/.next/server/app/api/providers/reload/route.js.nft.json +1 -1
  72. package/.next/server/app/api/providers/route.js.nft.json +1 -1
  73. package/.next/server/app/api/stats/models/[name]/route.js.nft.json +1 -1
  74. package/.next/server/app/api/stats/route.js.nft.json +1 -1
  75. package/.next/server/app/api/tools/[id]/route.js.nft.json +1 -1
  76. package/.next/server/app/api/tools/route.js.nft.json +1 -1
  77. package/.next/server/app/api/users/[username]/route.js.nft.json +1 -1
  78. package/.next/server/app/api/users/me/preferences/route.js +1 -1
  79. package/.next/server/app/api/users/me/preferences/route.js.nft.json +1 -1
  80. package/.next/server/app/api/users/me/route.js.nft.json +1 -1
  81. package/.next/server/app/api/users/route.js.nft.json +1 -1
  82. package/.next/server/app/api/v1/audio/speech/route.js +1 -1
  83. package/.next/server/app/api/v1/audio/speech/route.js.nft.json +1 -1
  84. package/.next/server/app/api/v1/audio/transcriptions/route.js +4 -4
  85. package/.next/server/app/api/v1/audio/transcriptions/route.js.nft.json +1 -1
  86. package/.next/server/app/api/v1/chat/completions/route.js +1 -1
  87. package/.next/server/app/api/v1/chat/completions/route.js.nft.json +1 -1
  88. package/.next/server/app/api/v1/embeddings/route.js +1 -1
  89. package/.next/server/app/api/v1/embeddings/route.js.nft.json +1 -1
  90. package/.next/server/app/api/v1/images/generations/route.js +1 -1
  91. package/.next/server/app/api/v1/images/generations/route.js.nft.json +1 -1
  92. package/.next/server/app/api/v1/models/route.js.nft.json +1 -1
  93. package/.next/server/app/api/v1/rerank/route.js +1 -1
  94. package/.next/server/app/api/v1/rerank/route.js.nft.json +1 -1
  95. package/.next/server/app/api/v1/videos/[id]/content/route.js +4 -4
  96. package/.next/server/app/api/v1/videos/[id]/content/route.js.nft.json +1 -1
  97. package/.next/server/app/api/v1/videos/[id]/route.js +4 -4
  98. package/.next/server/app/api/v1/videos/[id]/route.js.nft.json +1 -1
  99. package/.next/server/app/api/v1/videos/route.js +1 -1
  100. package/.next/server/app/api/v1/videos/route.js.nft.json +1 -1
  101. package/.next/server/app/api/variants/route.js.nft.json +1 -1
  102. package/.next/server/app/index.html +2 -2
  103. package/.next/server/app/index.rsc +7 -7
  104. package/.next/server/app/index.segments/!KGRhc2hib2FyZCk/__PAGE__.segment.rsc +2 -2
  105. package/.next/server/app/index.segments/!KGRhc2hib2FyZCk.segment.rsc +3 -3
  106. package/.next/server/app/index.segments/_full.segment.rsc +7 -7
  107. package/.next/server/app/index.segments/_head.segment.rsc +1 -1
  108. package/.next/server/app/index.segments/_index.segment.rsc +2 -2
  109. package/.next/server/app/index.segments/_tree.segment.rsc +2 -2
  110. package/.next/server/app/login.html +2 -2
  111. package/.next/server/app/login.rsc +3 -3
  112. package/.next/server/app/login.segments/!KGF1dGgp/login/__PAGE__.segment.rsc +1 -1
  113. package/.next/server/app/login.segments/!KGF1dGgp/login.segment.rsc +1 -1
  114. package/.next/server/app/login.segments/!KGF1dGgp.segment.rsc +1 -1
  115. package/.next/server/app/login.segments/_full.segment.rsc +3 -3
  116. package/.next/server/app/login.segments/_head.segment.rsc +1 -1
  117. package/.next/server/app/login.segments/_index.segment.rsc +2 -2
  118. package/.next/server/app/login.segments/_tree.segment.rsc +2 -2
  119. package/.next/server/app/logs.html +2 -2
  120. package/.next/server/app/logs.rsc +7 -7
  121. package/.next/server/app/logs.segments/!KGRhc2hib2FyZCk/logs/__PAGE__.segment.rsc +2 -2
  122. package/.next/server/app/logs.segments/!KGRhc2hib2FyZCk/logs.segment.rsc +1 -1
  123. package/.next/server/app/logs.segments/!KGRhc2hib2FyZCk.segment.rsc +3 -3
  124. package/.next/server/app/logs.segments/_full.segment.rsc +7 -7
  125. package/.next/server/app/logs.segments/_head.segment.rsc +1 -1
  126. package/.next/server/app/logs.segments/_index.segment.rsc +2 -2
  127. package/.next/server/app/logs.segments/_tree.segment.rsc +2 -2
  128. package/.next/server/app/mcp/presets.html +2 -2
  129. package/.next/server/app/mcp/presets.rsc +7 -7
  130. package/.next/server/app/mcp/presets.segments/!KGRhc2hib2FyZCk/mcp/presets/__PAGE__.segment.rsc +2 -2
  131. package/.next/server/app/mcp/presets.segments/!KGRhc2hib2FyZCk/mcp/presets.segment.rsc +1 -1
  132. package/.next/server/app/mcp/presets.segments/!KGRhc2hib2FyZCk/mcp.segment.rsc +1 -1
  133. package/.next/server/app/mcp/presets.segments/!KGRhc2hib2FyZCk.segment.rsc +3 -3
  134. package/.next/server/app/mcp/presets.segments/_full.segment.rsc +7 -7
  135. package/.next/server/app/mcp/presets.segments/_head.segment.rsc +1 -1
  136. package/.next/server/app/mcp/presets.segments/_index.segment.rsc +2 -2
  137. package/.next/server/app/mcp/presets.segments/_tree.segment.rsc +2 -2
  138. package/.next/server/app/mcp.html +2 -2
  139. package/.next/server/app/mcp.rsc +7 -7
  140. package/.next/server/app/mcp.segments/!KGRhc2hib2FyZCk/mcp/__PAGE__.segment.rsc +2 -2
  141. package/.next/server/app/mcp.segments/!KGRhc2hib2FyZCk/mcp.segment.rsc +1 -1
  142. package/.next/server/app/mcp.segments/!KGRhc2hib2FyZCk.segment.rsc +3 -3
  143. package/.next/server/app/mcp.segments/_full.segment.rsc +7 -7
  144. package/.next/server/app/mcp.segments/_head.segment.rsc +1 -1
  145. package/.next/server/app/mcp.segments/_index.segment.rsc +2 -2
  146. package/.next/server/app/mcp.segments/_tree.segment.rsc +2 -2
  147. package/.next/server/app/playground/audio/speech.html +2 -2
  148. package/.next/server/app/playground/audio/speech.rsc +8 -8
  149. package/.next/server/app/playground/audio/speech.segments/!KGRhc2hib2FyZCk/playground/audio/speech/__PAGE__.segment.rsc +2 -2
  150. package/.next/server/app/playground/audio/speech.segments/!KGRhc2hib2FyZCk/playground/audio/speech.segment.rsc +1 -1
  151. package/.next/server/app/playground/audio/speech.segments/!KGRhc2hib2FyZCk/playground/audio.segment.rsc +1 -1
  152. package/.next/server/app/playground/audio/speech.segments/!KGRhc2hib2FyZCk/playground.segment.rsc +2 -2
  153. package/.next/server/app/playground/audio/speech.segments/!KGRhc2hib2FyZCk.segment.rsc +3 -3
  154. package/.next/server/app/playground/audio/speech.segments/_full.segment.rsc +8 -8
  155. package/.next/server/app/playground/audio/speech.segments/_head.segment.rsc +1 -1
  156. package/.next/server/app/playground/audio/speech.segments/_index.segment.rsc +2 -2
  157. package/.next/server/app/playground/audio/speech.segments/_tree.segment.rsc +2 -2
  158. package/.next/server/app/playground/audio/transcription.html +2 -2
  159. package/.next/server/app/playground/audio/transcription.rsc +8 -8
  160. package/.next/server/app/playground/audio/transcription.segments/!KGRhc2hib2FyZCk/playground/audio/transcription/__PAGE__.segment.rsc +2 -2
  161. package/.next/server/app/playground/audio/transcription.segments/!KGRhc2hib2FyZCk/playground/audio/transcription.segment.rsc +1 -1
  162. package/.next/server/app/playground/audio/transcription.segments/!KGRhc2hib2FyZCk/playground/audio.segment.rsc +1 -1
  163. package/.next/server/app/playground/audio/transcription.segments/!KGRhc2hib2FyZCk/playground.segment.rsc +2 -2
  164. package/.next/server/app/playground/audio/transcription.segments/!KGRhc2hib2FyZCk.segment.rsc +3 -3
  165. package/.next/server/app/playground/audio/transcription.segments/_full.segment.rsc +8 -8
  166. package/.next/server/app/playground/audio/transcription.segments/_head.segment.rsc +1 -1
  167. package/.next/server/app/playground/audio/transcription.segments/_index.segment.rsc +2 -2
  168. package/.next/server/app/playground/audio/transcription.segments/_tree.segment.rsc +2 -2
  169. package/.next/server/app/playground/chat.html +2 -2
  170. package/.next/server/app/playground/chat.rsc +8 -8
  171. package/.next/server/app/playground/chat.segments/!KGRhc2hib2FyZCk/playground/chat/__PAGE__.segment.rsc +2 -2
  172. package/.next/server/app/playground/chat.segments/!KGRhc2hib2FyZCk/playground/chat.segment.rsc +1 -1
  173. package/.next/server/app/playground/chat.segments/!KGRhc2hib2FyZCk/playground.segment.rsc +2 -2
  174. package/.next/server/app/playground/chat.segments/!KGRhc2hib2FyZCk.segment.rsc +3 -3
  175. package/.next/server/app/playground/chat.segments/_full.segment.rsc +8 -8
  176. package/.next/server/app/playground/chat.segments/_head.segment.rsc +1 -1
  177. package/.next/server/app/playground/chat.segments/_index.segment.rsc +2 -2
  178. package/.next/server/app/playground/chat.segments/_tree.segment.rsc +2 -2
  179. package/.next/server/app/playground/embedding.html +2 -2
  180. package/.next/server/app/playground/embedding.rsc +8 -8
  181. package/.next/server/app/playground/embedding.segments/!KGRhc2hib2FyZCk/playground/embedding/__PAGE__.segment.rsc +2 -2
  182. package/.next/server/app/playground/embedding.segments/!KGRhc2hib2FyZCk/playground/embedding.segment.rsc +1 -1
  183. package/.next/server/app/playground/embedding.segments/!KGRhc2hib2FyZCk/playground.segment.rsc +2 -2
  184. package/.next/server/app/playground/embedding.segments/!KGRhc2hib2FyZCk.segment.rsc +3 -3
  185. package/.next/server/app/playground/embedding.segments/_full.segment.rsc +8 -8
  186. package/.next/server/app/playground/embedding.segments/_head.segment.rsc +1 -1
  187. package/.next/server/app/playground/embedding.segments/_index.segment.rsc +2 -2
  188. package/.next/server/app/playground/embedding.segments/_tree.segment.rsc +2 -2
  189. package/.next/server/app/playground/image.html +2 -2
  190. package/.next/server/app/playground/image.rsc +8 -8
  191. package/.next/server/app/playground/image.segments/!KGRhc2hib2FyZCk/playground/image/__PAGE__.segment.rsc +2 -2
  192. package/.next/server/app/playground/image.segments/!KGRhc2hib2FyZCk/playground/image.segment.rsc +1 -1
  193. package/.next/server/app/playground/image.segments/!KGRhc2hib2FyZCk/playground.segment.rsc +2 -2
  194. package/.next/server/app/playground/image.segments/!KGRhc2hib2FyZCk.segment.rsc +3 -3
  195. package/.next/server/app/playground/image.segments/_full.segment.rsc +8 -8
  196. package/.next/server/app/playground/image.segments/_head.segment.rsc +1 -1
  197. package/.next/server/app/playground/image.segments/_index.segment.rsc +2 -2
  198. package/.next/server/app/playground/image.segments/_tree.segment.rsc +2 -2
  199. package/.next/server/app/playground/video.html +2 -2
  200. package/.next/server/app/playground/video.rsc +8 -8
  201. package/.next/server/app/playground/video.segments/!KGRhc2hib2FyZCk/playground/video/__PAGE__.segment.rsc +2 -2
  202. package/.next/server/app/playground/video.segments/!KGRhc2hib2FyZCk/playground/video.segment.rsc +1 -1
  203. package/.next/server/app/playground/video.segments/!KGRhc2hib2FyZCk/playground.segment.rsc +2 -2
  204. package/.next/server/app/playground/video.segments/!KGRhc2hib2FyZCk.segment.rsc +3 -3
  205. package/.next/server/app/playground/video.segments/_full.segment.rsc +8 -8
  206. package/.next/server/app/playground/video.segments/_head.segment.rsc +1 -1
  207. package/.next/server/app/playground/video.segments/_index.segment.rsc +2 -2
  208. package/.next/server/app/playground/video.segments/_tree.segment.rsc +2 -2
  209. package/.next/server/app/playground.html +2 -2
  210. package/.next/server/app/playground.rsc +8 -8
  211. package/.next/server/app/playground.segments/!KGRhc2hib2FyZCk/playground/__PAGE__.segment.rsc +2 -2
  212. package/.next/server/app/playground.segments/!KGRhc2hib2FyZCk/playground.segment.rsc +2 -2
  213. package/.next/server/app/playground.segments/!KGRhc2hib2FyZCk.segment.rsc +3 -3
  214. package/.next/server/app/playground.segments/_full.segment.rsc +8 -8
  215. package/.next/server/app/playground.segments/_head.segment.rsc +1 -1
  216. package/.next/server/app/playground.segments/_index.segment.rsc +2 -2
  217. package/.next/server/app/playground.segments/_tree.segment.rsc +2 -2
  218. package/.next/server/app/providers.html +2 -2
  219. package/.next/server/app/providers.rsc +7 -7
  220. package/.next/server/app/providers.segments/!KGRhc2hib2FyZCk/providers/__PAGE__.segment.rsc +2 -2
  221. package/.next/server/app/providers.segments/!KGRhc2hib2FyZCk/providers.segment.rsc +1 -1
  222. package/.next/server/app/providers.segments/!KGRhc2hib2FyZCk.segment.rsc +3 -3
  223. package/.next/server/app/providers.segments/_full.segment.rsc +7 -7
  224. package/.next/server/app/providers.segments/_head.segment.rsc +1 -1
  225. package/.next/server/app/providers.segments/_index.segment.rsc +2 -2
  226. package/.next/server/app/providers.segments/_tree.segment.rsc +2 -2
  227. package/.next/server/app/settings/api-keys.html +2 -2
  228. package/.next/server/app/settings/api-keys.rsc +7 -7
  229. package/.next/server/app/settings/api-keys.segments/!KGRhc2hib2FyZCk/settings/api-keys/__PAGE__.segment.rsc +2 -2
  230. package/.next/server/app/settings/api-keys.segments/!KGRhc2hib2FyZCk/settings/api-keys.segment.rsc +1 -1
  231. package/.next/server/app/settings/api-keys.segments/!KGRhc2hib2FyZCk/settings.segment.rsc +1 -1
  232. package/.next/server/app/settings/api-keys.segments/!KGRhc2hib2FyZCk.segment.rsc +3 -3
  233. package/.next/server/app/settings/api-keys.segments/_full.segment.rsc +7 -7
  234. package/.next/server/app/settings/api-keys.segments/_head.segment.rsc +1 -1
  235. package/.next/server/app/settings/api-keys.segments/_index.segment.rsc +2 -2
  236. package/.next/server/app/settings/api-keys.segments/_tree.segment.rsc +2 -2
  237. package/.next/server/app/settings/users.html +2 -2
  238. package/.next/server/app/settings/users.rsc +7 -7
  239. package/.next/server/app/settings/users.segments/!KGRhc2hib2FyZCk/settings/users/__PAGE__.segment.rsc +2 -2
  240. package/.next/server/app/settings/users.segments/!KGRhc2hib2FyZCk/settings/users.segment.rsc +1 -1
  241. package/.next/server/app/settings/users.segments/!KGRhc2hib2FyZCk/settings.segment.rsc +1 -1
  242. package/.next/server/app/settings/users.segments/!KGRhc2hib2FyZCk.segment.rsc +3 -3
  243. package/.next/server/app/settings/users.segments/_full.segment.rsc +7 -7
  244. package/.next/server/app/settings/users.segments/_head.segment.rsc +1 -1
  245. package/.next/server/app/settings/users.segments/_index.segment.rsc +2 -2
  246. package/.next/server/app/settings/users.segments/_tree.segment.rsc +2 -2
  247. package/.next/server/app/settings.html +2 -2
  248. package/.next/server/app/settings.rsc +8 -8
  249. package/.next/server/app/settings.segments/!KGRhc2hib2FyZCk/settings/__PAGE__.segment.rsc +2 -2
  250. package/.next/server/app/settings.segments/!KGRhc2hib2FyZCk/settings.segment.rsc +1 -1
  251. package/.next/server/app/settings.segments/!KGRhc2hib2FyZCk.segment.rsc +3 -3
  252. package/.next/server/app/settings.segments/_full.segment.rsc +8 -8
  253. package/.next/server/app/settings.segments/_head.segment.rsc +1 -1
  254. package/.next/server/app/settings.segments/_index.segment.rsc +2 -2
  255. package/.next/server/app/settings.segments/_tree.segment.rsc +2 -2
  256. package/.next/server/chunks/[root-of-the-server]__019oqc3._.js +3 -0
  257. package/.next/server/chunks/[root-of-the-server]__019oqc3._.js.map +1 -0
  258. package/.next/server/chunks/[root-of-the-server]__01ou67p._.js +1 -1
  259. package/.next/server/chunks/[root-of-the-server]__01ou67p._.js.map +1 -1
  260. package/.next/server/chunks/[root-of-the-server]__02sypva._.js +2 -2
  261. package/.next/server/chunks/[root-of-the-server]__02sypva._.js.map +1 -1
  262. package/.next/server/chunks/[root-of-the-server]__0myi8j1._.js +2 -2
  263. package/.next/server/chunks/[root-of-the-server]__0myi8j1._.js.map +1 -1
  264. package/.next/server/chunks/[root-of-the-server]__0wiw6hu._.js +3 -0
  265. package/.next/server/chunks/[root-of-the-server]__0wiw6hu._.js.map +1 -0
  266. package/.next/server/chunks/[root-of-the-server]__0xrm_9r._.js +3 -0
  267. package/.next/server/chunks/[root-of-the-server]__0xrm_9r._.js.map +1 -0
  268. package/.next/server/chunks/[root-of-the-server]__11t79he._.js +1 -1
  269. package/.next/server/chunks/[root-of-the-server]__11t79he._.js.map +1 -1
  270. package/.next/server/chunks/[root-of-the-server]__1fs5lo-._.js +1 -1
  271. package/.next/server/chunks/[root-of-the-server]__1fs5lo-._.js.map +1 -1
  272. package/.next/server/chunks/[root-of-the-server]__1qg3d87._.js +2 -2
  273. package/.next/server/chunks/[root-of-the-server]__1qg3d87._.js.map +1 -1
  274. package/.next/server/chunks/[root-of-the-server]__1zgou-a._.js +6 -0
  275. package/.next/server/chunks/[root-of-the-server]__1zgou-a._.js.map +1 -0
  276. package/.next/server/chunks/_00k5vl0._.js +3 -0
  277. package/.next/server/chunks/_00k5vl0._.js.map +1 -0
  278. package/.next/server/chunks/_06hthvw._.js +3 -0
  279. package/.next/server/chunks/_06hthvw._.js.map +1 -0
  280. package/.next/server/chunks/_0c6vpbw._.js +3 -0
  281. package/.next/server/chunks/_0c6vpbw._.js.map +1 -0
  282. package/.next/server/chunks/_0hawg18._.js +3 -0
  283. package/.next/server/chunks/_0hawg18._.js.map +1 -0
  284. package/.next/server/chunks/_0kr91st._.js +3 -0
  285. package/.next/server/chunks/_0kr91st._.js.map +1 -0
  286. package/.next/server/chunks/_1i4x7k4._.js +3 -0
  287. package/.next/server/chunks/_1i4x7k4._.js.map +1 -0
  288. package/.next/server/chunks/_1lk_ovb._.js +3 -0
  289. package/.next/server/chunks/_1lk_ovb._.js.map +1 -0
  290. package/.next/server/chunks/_1wk63w9._.js +3 -0
  291. package/.next/server/chunks/_1wk63w9._.js.map +1 -0
  292. package/.next/server/chunks/_1wl3z8e._.js +3 -0
  293. package/.next/server/chunks/_1wl3z8e._.js.map +1 -0
  294. package/.next/server/chunks/lib_server_11s_lvw._.js +1 -1
  295. package/.next/server/chunks/lib_server_11s_lvw._.js.map +1 -1
  296. package/.next/server/chunks/lib_server_gateway_index_ts_1nvei3v._.js +2 -2
  297. package/.next/server/chunks/lib_server_gateway_index_ts_1nvei3v._.js.map +1 -1
  298. package/.next/server/chunks/ssr/app_(dashboard)_settings_page_tsx_1hwv4x8._.js +2 -2
  299. package/.next/server/chunks/ssr/app_(dashboard)_settings_page_tsx_1hwv4x8._.js.map +1 -1
  300. package/.next/server/chunks/ssr/lib_schemas_preferences_ts_1fy1exu._.js +1 -1
  301. package/.next/server/chunks/ssr/lib_schemas_preferences_ts_1fy1exu._.js.map +1 -1
  302. package/.next/server/middleware-build-manifest.js +3 -3
  303. package/.next/server/pages/404.html +2 -2
  304. package/.next/server/pages/500.html +1 -1
  305. package/.next/static/chunks/{2zeeni2y2fh59.js → 1si1c1m377t3w.js} +1 -1
  306. package/.next/static/chunks/2yzdc8m536xea.css +1 -0
  307. package/.next/static/chunks/3oj24pftrz5zy.js +11 -0
  308. package/.next/trace +2 -2
  309. package/.next/trace-build +1 -1
  310. package/bin/loom.mjs +1 -1
  311. package/drizzle/0019_timeout_default_3600.sql +36 -0
  312. package/drizzle/meta/0019_snapshot.json +1309 -0
  313. package/drizzle/meta/_journal.json +7 -0
  314. package/package.json +1 -1
  315. package/.next/server/chunks/[root-of-the-server]__00b7x8i._.js +0 -3
  316. package/.next/server/chunks/[root-of-the-server]__00b7x8i._.js.map +0 -1
  317. package/.next/server/chunks/[root-of-the-server]__022u2d9._.js +0 -3
  318. package/.next/server/chunks/[root-of-the-server]__022u2d9._.js.map +0 -1
  319. package/.next/server/chunks/[root-of-the-server]__0g3mnim._.js +0 -6
  320. package/.next/server/chunks/[root-of-the-server]__0g3mnim._.js.map +0 -1
  321. package/.next/server/chunks/[root-of-the-server]__1gon00b._.js +0 -3
  322. package/.next/server/chunks/[root-of-the-server]__1gon00b._.js.map +0 -1
  323. package/.next/server/chunks/[root-of-the-server]__1xj9qqs._.js +0 -3
  324. package/.next/server/chunks/[root-of-the-server]__1xj9qqs._.js.map +0 -1
  325. package/.next/server/chunks/_028m5t0._.js +0 -3
  326. package/.next/server/chunks/_028m5t0._.js.map +0 -1
  327. package/.next/server/chunks/_0eq8a_c._.js +0 -3
  328. package/.next/server/chunks/_0eq8a_c._.js.map +0 -1
  329. package/.next/server/chunks/_0n06usu._.js +0 -3
  330. package/.next/server/chunks/_0n06usu._.js.map +0 -1
  331. package/.next/server/chunks/_0tcchv1._.js +0 -3
  332. package/.next/server/chunks/_0tcchv1._.js.map +0 -1
  333. package/.next/server/chunks/_14120rw._.js +0 -3
  334. package/.next/server/chunks/_14120rw._.js.map +0 -1
  335. package/.next/server/chunks/_1633jn_._.js +0 -3
  336. package/.next/server/chunks/_1633jn_._.js.map +0 -1
  337. package/.next/server/chunks/_19jpf08._.js +0 -3
  338. package/.next/server/chunks/_19jpf08._.js.map +0 -1
  339. package/.next/server/chunks/_1gi5m-_._.js +0 -3
  340. package/.next/server/chunks/_1gi5m-_._.js.map +0 -1
  341. package/.next/server/chunks/_1jgm_7u._.js +0 -3
  342. package/.next/server/chunks/_1jgm_7u._.js.map +0 -1
  343. package/.next/static/chunks/0cbg1vmtl84ae.css +0 -1
  344. package/.next/static/chunks/29p-wdja_cbgh.js +0 -11
  345. /package/.next/static/{wCZkC7ZaYrxG37d-e2tac → TZ8IS4-HWznFu8M4EwNGp}/_buildManifest.js +0 -0
  346. /package/.next/static/{wCZkC7ZaYrxG37d-e2tac → TZ8IS4-HWznFu8M4EwNGp}/_clientMiddlewareManifest.js +0 -0
  347. /package/.next/static/{wCZkC7ZaYrxG37d-e2tac → TZ8IS4-HWznFu8M4EwNGp}/_ssgManifest.js +0 -0
@@ -134,6 +134,13 @@
134
134
  "when": 1780991701367,
135
135
  "tag": "0018_melted_lily_hollister",
136
136
  "breakpoints": true
137
+ },
138
+ {
139
+ "idx": 19,
140
+ "version": "6",
141
+ "when": 1781020718836,
142
+ "tag": "0019_timeout_default_3600",
143
+ "breakpoints": true
137
144
  }
138
145
  ]
139
146
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@whxway/loom",
3
- "version": "1.1.0",
3
+ "version": "1.2.0",
4
4
  "description": "Self-hosted AI testing platform — try models and MCP servers, log every request, and front your apps through an OpenAI-compatible gateway.",
5
5
  "keywords": [
6
6
  "ai",
@@ -1,3 +0,0 @@
1
- module.exports=[918622,(e,t,r)=>{t.exports=e.x("next/dist/compiled/next-server/app-page-turbo.runtime.prod.js",()=>require("next/dist/compiled/next-server/app-page-turbo.runtime.prod.js"))},556704,(e,t,r)=>{t.exports=e.x("next/dist/server/app-render/work-async-storage.external.js",()=>require("next/dist/server/app-render/work-async-storage.external.js"))},832319,(e,t,r)=>{t.exports=e.x("next/dist/server/app-render/work-unit-async-storage.external.js",()=>require("next/dist/server/app-render/work-unit-async-storage.external.js"))},324725,(e,t,r)=>{t.exports=e.x("next/dist/server/app-render/after-task-async-storage.external.js",()=>require("next/dist/server/app-render/after-task-async-storage.external.js"))},193695,(e,t,r)=>{t.exports=e.x("next/dist/shared/lib/no-fallback-error.external.js",()=>require("next/dist/shared/lib/no-fallback-error.external.js"))},750227,(e,t,r)=>{t.exports=e.x("node:path",()=>require("node:path"))},666680,(e,t,r)=>{t.exports=e.x("node:crypto",()=>require("node:crypto"))},494977,839604,e=>{"use strict";var t=e.i(152358),r=e.i(469719);let a=r.z.object({type:r.z.literal("text"),text:r.z.string()}),i=r.z.object({type:r.z.literal("image_url"),image_url:r.z.object({url:r.z.string(),detail:r.z.enum(["auto","low","high"]).optional()})}),n=r.z.object({type:r.z.literal("file"),file:r.z.object({filename:r.z.string(),file_data:r.z.string(),mime_type:r.z.string().optional()})}),o=r.z.object({type:r.z.literal("tool_call"),tool_call:r.z.object({id:r.z.string(),name:r.z.string(),arguments:r.z.string(),source:r.z.string().optional()})}),l=r.z.object({type:r.z.literal("tool_result"),tool_result:r.z.object({tool_call_id:r.z.string(),name:r.z.string().optional(),content:r.z.string(),is_error:r.z.boolean().optional(),source:r.z.string().optional()})}),s=r.z.discriminatedUnion("type",[a,i,n,o,l]),d=r.z.union([r.z.string(),r.z.array(s)]);function c(e){return"string"==typeof e?e:Array.isArray(e)?e.map(e=>"text"===e.type?e.text:"").filter(Boolean).join("\n"):""}e.s(["extractText",0,c,"messageContentSchema",0,d],839604),(0,t.registerCapability)({id:"chat",label:"Chat",description:"Conversational completion. Canonical OpenAI chat-completion shape.",defaultVariantId:"chat.completions",variantPreference:["responses","chat.completions"],priority:10,matches:e=>/^(gpt|chatgpt|o\d|claude|gemini|llama|qwen|deepseek-(chat|r1|reasoner|v\d)|mistral|mixtral|grok|yi|baichuan|moonshot|kimi|hunyuan|glm|spark|abab|step|doubao|ernie)/i.test(e)||/-(chat|instruct)\b/i.test(e),summarizeInput:e=>{let t=e.messages;if(!Array.isArray(t)||0===t.length)return"";let r=[...t].reverse().find(e=>e?.role==="user")??t[t.length-1];return c(r?.content??"").slice(0,200)}}),(0,t.registerCapability)({id:"embedding",label:"Embedding",description:"Vector embeddings.",defaultVariantId:"embeddings",priority:20,matches:e=>/\b(embedding|embed|bge|gte|m3e|e5|cohere-embed|text-embedding)/i.test(e),summarizeInput:e=>{let t=e.input;return"string"==typeof t?t.slice(0,200):Array.isArray(t)?`${t.length} input(s): ${t.map(e=>"string"==typeof e?e:"").join(" / ").slice(0,200)}`:""}}),(0,t.registerCapability)({id:"image",label:"Image generation",description:"Text-to-image.",defaultVariantId:"images.generations",priority:30,matches:e=>/\b(dall-?e|gpt-image|stable[-_]?diffusion|sd-?\d|sdxl|flux|imagen|midjourney|kandinsky|playground-v|cogview|ideogram)/i.test(e),summarizeInput:e=>{let t=e.prompt,r=e.n,a="string"==typeof t?t.slice(0,180):"";return r&&r>1?`(\xd7${r}) ${a}`:a}}),(0,t.registerCapability)({id:"audio.speech",label:"Text-to-speech",description:"Synthesize speech audio from text.",defaultVariantId:"audio.speech",priority:25,matches:e=>/\b(tts|speech|voice|elevenlabs|piper|xtts|fish)/i.test(e),summarizeInput:e=>{let t=e.input,r=e.voice,a="string"==typeof t?t.slice(0,180):"";return r?`[${r}] ${a}`:a}}),(0,t.registerCapability)({id:"audio.transcription",label:"Speech-to-text",description:"Transcribe audio to text.",defaultVariantId:"audio.transcriptions",priority:25,matches:e=>/\b(whisper|stt|transcribe|asr|conformer|paraformer)/i.test(e),summarizeInput:()=>"audio input"}),(0,t.registerCapability)({id:"rerank",label:"Rerank",description:"Cross-encoder re-ranking (Cohere /rerank-style).",defaultVariantId:"rerank",priority:30,matches:e=>/\brerank|\brerank-|\bbge-reranker|\bjina-reranker|\bcohere-rerank/i.test(e),summarizeInput:e=>{let t=e.query,r=e.documents,a=Array.isArray(r)?r.length:0,i="string"==typeof t?t.slice(0,160):"";return`(over ${a} doc${1===a?"":"s"}) ${i}`}}),(0,t.registerCapability)({id:"video",label:"Video generation",description:"Text-to-video (asynchronous; create + poll + download).",defaultVariantId:"videos",priority:30,matches:e=>/\b(sora|veo|kling|runway|gen-?\d|luma|pika|wan|hailuo|cogvideo|mochi|hunyuan-video)/i.test(e),summarizeInput:e=>{let t=e.prompt,r=e.seconds,a=e.size,i="string"==typeof t?t.slice(0,160):"",n=[];return r&&n.push(`${r}s`),a&&n.push(a),n.length>0?`[${n.join(" ")}] ${i}`:i}}),e.s([],494977)},898947,e=>{"use strict";var t=e.i(875225),r=e.i(846344),a=e.i(110726),i=e.i(425568),n=e.i(152358);e.i(494977);var o=e.i(183397);e.i(439782);let l=new Map,s=new Map;async function d(e){let t=(0,o.resolveAdapter)(e),r=(0,i.decryptSecret)(e.apiKeyEncrypted),a=await t.fetchModels(e,r),l=[];for(let r of a){let a=t.extractModelMeta(r,e);a&&l.push({id:a.upstream_id,provider_id:e.id,provider_name:e.name,adapter_id:t.id,capability:function(e,t){let r=e.capabilities;return r.embeddings?"embedding":r.audio_in||r.audio_out?r.audio_in?"audio.transcription":"audio.speech":r.chat||r.responses?"chat":(0,n.classifyModel)(t)}(a,a.upstream_id),meta:a})}return l}async function c(e){let t=s.get(e.id);if(t)return t;let r=(async()=>{let t={fetchedAt:Date.now(),models:[],error:null};try{t.models=await d(e)}catch(a){t.error=a instanceof Error?a.message:String(a);let r=l.get(e.id);r?.models?.length&&(t.models=r.models)}return l.set(e.id,t),t})().finally(()=>{s.delete(e.id)});return s.set(e.id,r),r}async function u(e,t={}){let r,a=l.get(e.id);return!t.force&&a&&Date.now()-a.fetchedAt<(Number.isFinite(r=Number(process.env.LOOM_MODELS_CACHE_TTL))&&r>=0?1e3*r:3e5)?a:c(e)}function p(){return r.db.select().from(a.schema.providers).where((0,t.eq)(a.schema.providers.enabled,!0)).all()}async function m(e={}){let t=p(),r=await Promise.all(t.map(t=>u(t,e))),a=[];for(let e of r)a.push(...e.models);return a}async function h(e){return e.enabled?(await u(e)).models.length:0}async function y(){let e=p(),t=await Promise.all(e.map(e=>u(e))),r={};return e.forEach((e,a)=>{r[e.id]=t[a].models.length}),r}async function g(e){let t=p(),r=await Promise.all(t.map(e=>u(e)));for(let a=0;a<t.length;a++){let i=r[a].models.find(t=>t.id===e);if(i)return{provider:t[a],upstreamModelId:i.id,meta:i.meta}}return null}async function f(e,t={}){return(await u(e,t)).models}e.s(["clearDiscoveryCache",0,function(){l.clear()},"discoverModels",0,d,"discoveredCountByProvider",0,y,"discoveredCountForProvider",0,h,"discoveredForProvider",0,f,"getDiscoveryStatus",0,function(e){return l.get(e)??null},"listAllDiscovered",0,m,"resolveByDiscovery",0,g])},348628,23060,e=>{"use strict";var t=e.i(666680),r=e.i(875225),a=e.i(518899),i=e.i(846344),n=e.i(401632),o=e.i(425568),l=e.i(803028),s=e.i(898947),d=e.i(183397);function c(e,t){return{id:e.id,name:e.name,provider_name:e.name,adapter_id:e.adapterId,base_url:e.baseUrl,proxy:e.baseUrl,api_version:e.apiVersion??null,has_api_key:!!e.apiKeyEncrypted,default_params:e.defaultParams??{},http_proxy:e.httpProxy??null,document_page:e.documentPage??"",model_page:e.modelPage??"",health_check_url:e.healthCheckUrl??null,last_health_status:e.lastHealthStatus??null,last_health_checked_at:e.lastHealthCheckedAt??null,last_health_error:e.lastHealthError??null,is_local:!!e.isLocal,enabled:!!e.enabled,n_models:t,created_at:e.createdAt,updated_at:e.updatedAt}}function u(e){return i.db.select().from(n.providers).where((0,r.eq)(n.providers.id,e)).get()||i.db.select().from(n.providers).where((0,r.eq)(n.providers.name,e)).get()}async function p(){let e=i.db.select().from(n.providers).orderBy(n.providers.name).all(),t=function(){let e=i.db.select({providerId:n.models.providerId,c:a.sql`count(*)`.as("c")}).from(n.models).groupBy(n.models.providerId).all(),t={};for(let r of e)t[r.providerId]=Number(r.c);return t}(),r=await (0,s.discoveredCountByProvider)();return e.map(e=>c(e,(t[e.id]??0)+(r[e.id]??0)))}async function m(e){var t;let o,d=u(e);if(!d)throw(0,l.notFound)("Provider not found");let p=(t=d.id,o=i.db.select({c:a.sql`count(*)`.as("c")}).from(n.models).where((0,r.eq)(n.models.providerId,t)).get(),Number(o?.c??0)),m=await (0,s.discoveredCountForProvider)(d);return c(d,p+m)}async function h(e){let a=e.name.trim(),c=e.base_url.trim();if(i.db.select().from(n.providers).where((0,r.eq)(n.providers.name,a)).get())throw(0,l.badRequest)("Provider name already exists");let u=(0,t.randomUUID)(),p=function(e){if(e.adapter_id&&e.adapter_id.trim())return e.adapter_id.trim();let t={id:"",name:"",adapterId:"",baseUrl:e.base_url,apiVersion:e.api_version??null,apiKeyEncrypted:null,defaultParams:{},httpProxy:null,documentPage:null,modelPage:null,healthCheckUrl:null,lastHealthStatus:null,lastHealthCheckedAt:null,lastHealthError:null,isLocal:!1,enabled:!0,createdAt:"",updatedAt:""};return(0,d.resolveAdapter)(t).id}({adapter_id:e.adapter_id,base_url:c,api_version:e.api_version??null});return i.db.insert(n.providers).values({id:u,name:a,adapterId:p,baseUrl:c,apiVersion:e.api_version?.trim()||null,apiKeyEncrypted:(0,o.encryptSecret)(e.api_key??null),defaultParams:e.default_params??{},httpProxy:e.http_proxy??null,documentPage:e.document_page??null,modelPage:e.model_page??null,healthCheckUrl:e.health_check_url?.trim()||null,isLocal:!!e.is_local,enabled:e.enabled??!0}).run(),(0,s.clearDiscoveryCache)(),m(u)}async function y(e,t){let a=u(e);if(!a)throw(0,l.notFound)("Provider not found");let d={};if(void 0!==t.name){let e=t.name.trim();if(!e)throw(0,l.badRequest)("Provider name cannot be empty");if(e!==a.name){if(i.db.select().from(n.providers).where((0,r.eq)(n.providers.name,e)).get())throw(0,l.badRequest)("Provider name already exists");d.name=e}}if(void 0!==t.adapter_id){let e=t.adapter_id?.trim();if(!e)throw(0,l.badRequest)("adapter_id cannot be empty");d.adapterId=e}if(void 0!==t.base_url){let e=t.base_url.trim();if(!e)throw(0,l.badRequest)("base_url cannot be empty");d.baseUrl=e}if(void 0!==t.api_version&&(d.apiVersion=t.api_version?.trim()||null),void 0!==t.api_key&&(d.apiKeyEncrypted=t.api_key?(0,o.encryptSecret)(t.api_key):null),void 0!==t.default_params&&(d.defaultParams=t.default_params??{}),void 0!==t.http_proxy&&(d.httpProxy=t.http_proxy??null),void 0!==t.document_page&&(d.documentPage=t.document_page),void 0!==t.model_page&&(d.modelPage=t.model_page),void 0!==t.health_check_url){let e=t.health_check_url?.trim()||null;e!==a.healthCheckUrl&&(d.healthCheckUrl=e,d.lastHealthStatus=null,d.lastHealthCheckedAt=null,d.lastHealthError=null)}return void 0!==t.is_local&&(d.isLocal=!!t.is_local),void 0!==t.enabled&&(d.enabled=!!t.enabled),d.updatedAt=new Date().toISOString(),i.db.update(n.providers).set(d).where((0,r.eq)(n.providers.id,a.id)).run(),(0,s.clearDiscoveryCache)(),m(a.id)}async function g(e){let t=u(e);if(!t)throw(0,l.notFound)("Provider not found");i.db.delete(n.providers).where((0,r.eq)(n.providers.id,t.id)).run(),(0,s.clearDiscoveryCache)()}async function f(e){let t=Date.now();try{let r=await fetch(e,{method:"GET",signal:AbortSignal.timeout(1e4)}),a=Date.now()-t;if(!r.ok){let e=await r.text().catch(()=>r.statusText);return{ok:!1,error:`HTTP ${r.status}: ${e.slice(0,200)}`,latency_ms:a}}let i=await r.json().catch(()=>null);if(!i||"ok"!==i.status)return{ok:!1,error:`Expected {"status":"ok"}, got ${JSON.stringify(i).slice(0,200)}`,latency_ms:a};return{ok:!0,latency_ms:a}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e),latency_ms:Date.now()-t}}}async function v(e){let t=u(e);if(!t)throw(0,l.notFound)("Provider not found");if(t.healthCheckUrl){let e=await f(t.healthCheckUrl);return i.db.update(n.providers).set({lastHealthStatus:e.ok?"ok":"down",lastHealthCheckedAt:new Date().toISOString(),lastHealthError:e.ok?null:e.error??null,updatedAt:new Date().toISOString()}).where((0,r.eq)(n.providers.id,t.id)).run(),e}let a=Date.now();try{let e=await (0,s.discoverModels)(t);return{ok:!0,models:e.length,latency_ms:Date.now()-a}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e),latency_ms:Date.now()-a}}}e.i(439782),e.s(["checkProvider",0,v,"createProvider",0,h,"deleteProvider",0,g,"findProviderByIdOrName",0,u,"getProvider",0,m,"listProviders",0,p,"probeHealthCheckUrl",0,f,"updateProvider",0,y],23060),e.s([],348628)}];
2
-
3
- //# sourceMappingURL=%5Broot-of-the-server%5D__00b7x8i._.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../../lib/server/capabilities/chat.ts","../../../lib/schemas/content.ts","../../../lib/server/capabilities/embedding.ts","../../../lib/server/capabilities/image.ts","../../../lib/server/capabilities/audio-speech.ts","../../../lib/server/capabilities/audio-transcription.ts","../../../lib/server/capabilities/rerank.ts","../../../lib/server/capabilities/video.ts","../../../lib/server/discovery.ts","../../../lib/server/providers/service.ts","../../../lib/server/providers/serializer.ts"],"sourcesContent":["import \"server-only\";\nimport { registerCapability } from \"./index\";\nimport { extractText, type MessageContent } from \"@/lib/schemas/content\";\n\nregisterCapability({\n id: \"chat\",\n label: \"Chat\",\n description: \"Conversational completion. Canonical OpenAI chat-completion shape.\",\n defaultVariantId: \"chat.completions\",\n // Gateway opinion: Responses API is more capable (better tool calls,\n // reasoning, multi-step) so prefer it when the model claims support.\n variantPreference: [\"responses\", \"chat.completions\"],\n priority: 10,\n matches: (id) =>\n /^(gpt|chatgpt|o\\d|claude|gemini|llama|qwen|deepseek-(chat|r1|reasoner|v\\d)|mistral|mixtral|grok|yi|baichuan|moonshot|kimi|hunyuan|glm|spark|abab|step|doubao|ernie)/i.test(id) ||\n /-(chat|instruct)\\b/i.test(id),\n summarizeInput: (body) => {\n const messages = (body as { messages?: Array<{ role?: string; content?: MessageContent }> }).messages;\n if (!Array.isArray(messages) || messages.length === 0) return \"\";\n const lastUser = [...messages].reverse().find((m) => m?.role === \"user\");\n const target = lastUser ?? messages[messages.length - 1];\n // Text-only summary; attachments don't contribute.\n return extractText(target?.content ?? \"\").slice(0, 200);\n },\n});\n","import { z } from \"zod\";\n\n/**\n * Canonical chat-message content shape — modelled on OpenAI's\n * multimodal chat-completion payload so it round-trips upstream without\n * translation in the chat.completions variant. Variants that need a\n * different shape (Responses API: input_text / input_image / input_file)\n * translate on the way out.\n *\n * Always-array content is allowed too — a plain text turn can be either\n * a bare string OR `[{type:\"text\", text:\"…\"}]`; both are accepted\n * end-to-end and rendered the same way.\n */\n\nexport const textPartSchema = z.object({\n type: z.literal(\"text\"),\n text: z.string(),\n});\n\nexport const imageUrlPartSchema = z.object({\n type: z.literal(\"image_url\"),\n image_url: z.object({\n /** Either an https:// URL or a `data:` URL. Inline base64 is the\n * default path from the FE — no server-side upload needed. */\n url: z.string(),\n detail: z.enum([\"auto\", \"low\", \"high\"]).optional(),\n }),\n});\n\nexport const filePartSchema = z.object({\n type: z.literal(\"file\"),\n file: z.object({\n filename: z.string(),\n /** Inline `data:<mime>;base64,…` URL. */\n file_data: z.string(),\n /** Convenience copy of the mime type, for FE chip icons. */\n mime_type: z.string().optional(),\n }),\n});\n\n/**\n * Tool-call request: an assistant message asks the runtime to invoke\n * one or more registered tools. Mirrors OpenAI's\n * `choices[].message.tool_calls[]` shape so chat.completions can\n * round-trip without translation. We model each call as a single\n * ContentPart so the FE renders them in-order with other text/image\n * parts; the upstream-facing shape is reconstructed in the variant\n * layer when forwarding back as conversation history.\n */\nexport const toolCallPartSchema = z.object({\n type: z.literal(\"tool_call\"),\n tool_call: z.object({\n id: z.string(),\n name: z.string(),\n /** Stored as a string for fidelity with upstream — JSON-parsed\n * for display only. */\n arguments: z.string(),\n /** Friendly origin label, populated server-side from the MCP\n * server name so the UI can show \"github · search_repositories\"\n * without a separate lookup. */\n source: z.string().optional(),\n }),\n});\n\n/**\n * Tool result: a `role: \"tool\"` message body carrying the textual\n * output of a single tool invocation, linked back via\n * `tool_call_id`. Errors are marked via `is_error: true` so the UI\n * can style them distinctly.\n */\nexport const toolResultPartSchema = z.object({\n type: z.literal(\"tool_result\"),\n tool_result: z.object({\n tool_call_id: z.string(),\n name: z.string().optional(),\n content: z.string(),\n is_error: z.boolean().optional(),\n source: z.string().optional(),\n }),\n});\n\nexport const contentPartSchema = z.discriminatedUnion(\"type\", [\n textPartSchema,\n imageUrlPartSchema,\n filePartSchema,\n toolCallPartSchema,\n toolResultPartSchema,\n]);\n\nexport const messageContentSchema = z.union([z.string(), z.array(contentPartSchema)]);\n\nexport type TextPart = z.infer<typeof textPartSchema>;\nexport type ImageUrlPart = z.infer<typeof imageUrlPartSchema>;\nexport type FilePart = z.infer<typeof filePartSchema>;\nexport type ToolCallPart = z.infer<typeof toolCallPartSchema>;\nexport type ToolResultPart = z.infer<typeof toolResultPartSchema>;\nexport type ContentPart = z.infer<typeof contentPartSchema>;\nexport type MessageContent = z.infer<typeof messageContentSchema>;\n\n// ---- helpers ----\n\n/** Concatenate every text part. Non-text parts contribute nothing.\n * Used wherever we need a flat string view (log summaries, title\n * generation, search index). */\nexport function extractText(content: MessageContent): string {\n if (typeof content === \"string\") return content;\n if (!Array.isArray(content)) return \"\";\n return content\n .map((p) => (p.type === \"text\" ? p.text : \"\"))\n .filter(Boolean)\n .join(\"\\n\");\n}\n\n/** True when at least one non-text part is present. */\nexport function hasAttachments(content: MessageContent): boolean {\n if (typeof content === \"string\") return false;\n if (!Array.isArray(content)) return false;\n return content.some((p) => p.type !== \"text\");\n}\n","import \"server-only\";\nimport { registerCapability } from \"./index\";\n\nregisterCapability({\n id: \"embedding\",\n label: \"Embedding\",\n description: \"Vector embeddings.\",\n defaultVariantId: \"embeddings\",\n priority: 20,\n matches: (id) => /\\b(embedding|embed|bge|gte|m3e|e5|cohere-embed|text-embedding)/i.test(id),\n summarizeInput: (body) => {\n const input = (body as { input?: unknown }).input;\n if (typeof input === \"string\") return input.slice(0, 200);\n if (Array.isArray(input)) {\n return `${input.length} input(s): ${input.map((s) => (typeof s === \"string\" ? s : \"\")).join(\" / \").slice(0, 200)}`;\n }\n return \"\";\n },\n});\n","import \"server-only\";\nimport { registerCapability } from \"./index\";\n\nregisterCapability({\n id: \"image\",\n label: \"Image generation\",\n description: \"Text-to-image.\",\n defaultVariantId: \"images.generations\",\n priority: 30,\n matches: (id) => /\\b(dall-?e|gpt-image|stable[-_]?diffusion|sd-?\\d|sdxl|flux|imagen|midjourney|kandinsky|playground-v|cogview|ideogram)/i.test(id),\n summarizeInput: (body) => {\n const prompt = (body as { prompt?: unknown }).prompt;\n const n = (body as { n?: number }).n;\n const text = typeof prompt === \"string\" ? prompt.slice(0, 180) : \"\";\n return n && n > 1 ? `(×${n}) ${text}` : text;\n },\n});\n","import \"server-only\";\nimport { registerCapability } from \"./index\";\n\nregisterCapability({\n id: \"audio.speech\",\n label: \"Text-to-speech\",\n description: \"Synthesize speech audio from text.\",\n defaultVariantId: \"audio.speech\",\n priority: 25,\n matches: (id) => /\\b(tts|speech|voice|elevenlabs|piper|xtts|fish)/i.test(id),\n summarizeInput: (body) => {\n const input = (body as { input?: unknown }).input;\n const voice = (body as { voice?: string }).voice;\n const text = typeof input === \"string\" ? input.slice(0, 180) : \"\";\n return voice ? `[${voice}] ${text}` : text;\n },\n});\n","import \"server-only\";\nimport { registerCapability } from \"./index\";\n\nregisterCapability({\n id: \"audio.transcription\",\n label: \"Speech-to-text\",\n description: \"Transcribe audio to text.\",\n defaultVariantId: \"audio.transcriptions\",\n priority: 25,\n matches: (id) => /\\b(whisper|stt|transcribe|asr|conformer|paraformer)/i.test(id),\n summarizeInput: () => \"audio input\",\n});\n","import \"server-only\";\nimport { registerCapability } from \"./index\";\n\nregisterCapability({\n id: \"rerank\",\n label: \"Rerank\",\n description: \"Cross-encoder re-ranking (Cohere /rerank-style).\",\n defaultVariantId: \"rerank\",\n priority: 30,\n matches: (id) => /\\brerank|\\brerank-|\\bbge-reranker|\\bjina-reranker|\\bcohere-rerank/i.test(id),\n summarizeInput: (body) => {\n const query = (body as { query?: string }).query;\n const docs = (body as { documents?: unknown[] }).documents;\n const count = Array.isArray(docs) ? docs.length : 0;\n const q = typeof query === \"string\" ? query.slice(0, 160) : \"\";\n return `(over ${count} doc${count === 1 ? \"\" : \"s\"}) ${q}`;\n },\n});\n","import \"server-only\";\nimport { registerCapability } from \"./index\";\n\nregisterCapability({\n id: \"video\",\n label: \"Video generation\",\n description: \"Text-to-video (asynchronous; create + poll + download).\",\n defaultVariantId: \"videos\",\n priority: 30,\n matches: (id) => /\\b(sora|veo|kling|runway|gen-?\\d|luma|pika|wan|hailuo|cogvideo|mochi|hunyuan-video)/i.test(id),\n summarizeInput: (body) => {\n const prompt = (body as { prompt?: unknown }).prompt;\n const seconds = (body as { seconds?: number | string }).seconds;\n const size = (body as { size?: string }).size;\n const text = typeof prompt === \"string\" ? prompt.slice(0, 160) : \"\";\n const tags: string[] = [];\n if (seconds) tags.push(`${seconds}s`);\n if (size) tags.push(size);\n return tags.length > 0 ? `[${tags.join(\" \")}] ${text}` : text;\n },\n});\n","import \"server-only\";\nimport { eq } from \"drizzle-orm\";\nimport { db, schema } from \"./db\";\nimport { decryptSecret } from \"./crypto\";\nimport { classifyModel } from \"./capabilities\";\nimport \"./capabilities/register\";\nimport { resolveAdapter } from \"./adapters\";\nimport \"./adapters/register\";\nimport type { NormalizedModelMeta } from \"@/lib/schemas/adapter\";\nimport type { Provider } from \"./db/schema\";\n\n/**\n * Dynamic model discovery.\n *\n * Each provider's `/models`-style endpoint is fetched by its registered\n * ProviderAdapter (`lib/server/adapters/`). The adapter is the single\n * point of variability — it handles URL/header quirks, parses the\n * upstream-specific JSON, and projects each raw entry into a\n * NormalizedModelMeta. Results are cached per-provider with a short TTL\n * so we don't hammer upstreams on every request.\n *\n * Important Azure caveat: the Azure-OpenAI catalog endpoint returns base\n * model names (`gpt-4o`), not callable deployment names. The\n * `azure-openai` adapter surfaces those with `capabilities.chat=false`\n * so admins know to register a deployment override row.\n */\n\nexport interface DiscoveredModel {\n /** The id the user supplies as `\"model\"` in their request. */\n id: string;\n /** Provider id this model belongs to (DB primary key). */\n provider_id: string;\n /** Convenience copy of the provider's name. */\n provider_name: string;\n /** Adapter id that fetched this entry. */\n adapter_id: string;\n /** Inferred capability id (chat | embedding | image | …) — adapter\n * projection first, then heuristic fallback. */\n capability: string;\n /** Full normalized projection — see lib/schemas/adapter.ts. */\n meta: NormalizedModelMeta;\n}\n\ninterface CacheEntry {\n fetchedAt: number;\n models: DiscoveredModel[];\n error: string | null;\n}\n\nconst cache = new Map<string, CacheEntry>();\n// In-flight refreshes — coalesces a thundering herd of concurrent\n// stale lookups into a single upstream /models request. The first\n// caller starts the fetch, subsequent callers reuse the same promise.\nconst pendingRefresh = new Map<string, Promise<CacheEntry>>();\n\nfunction cacheTtlMs(): number {\n const seconds = Number(process.env.LOOM_MODELS_CACHE_TTL);\n if (Number.isFinite(seconds) && seconds >= 0) return seconds * 1000;\n return 5 * 60 * 1000; // 5-minute default\n}\n\nfunction isFresh(entry: CacheEntry): boolean {\n return Date.now() - entry.fetchedAt < cacheTtlMs();\n}\n\n/**\n * Walk the adapter's NormalizedModelMeta to decide which gateway\n * capability id (\"chat\", \"embedding\", \"image\", …) this model serves.\n * Falls back to name heuristics when the adapter didn't say.\n */\nfunction capabilityFromMeta(meta: NormalizedModelMeta, fallbackId: string): string {\n const c = meta.capabilities;\n if (c.embeddings) return \"embedding\";\n if (c.audio_in || c.audio_out) {\n // Coarse — most providers won't distinguish here.\n return c.audio_in ? \"audio.transcription\" : \"audio.speech\";\n }\n if (c.chat || c.responses) return \"chat\";\n return classifyModel(fallbackId);\n}\n\n/** Fetch the model list for a provider via its adapter, bypassing the cache. */\nexport async function discoverModels(provider: Provider): Promise<DiscoveredModel[]> {\n const adapter = resolveAdapter(provider);\n const apiKey = decryptSecret(provider.apiKeyEncrypted);\n\n const rawEntries = await adapter.fetchModels(provider, apiKey);\n const out: DiscoveredModel[] = [];\n for (const raw of rawEntries) {\n const meta = adapter.extractModelMeta(raw, provider);\n if (!meta) continue;\n out.push({\n id: meta.upstream_id,\n provider_id: provider.id,\n provider_name: provider.name,\n adapter_id: adapter.id,\n capability: capabilityFromMeta(meta, meta.upstream_id),\n meta,\n });\n }\n return out;\n}\n\nasync function refreshProvider(provider: Provider): Promise<CacheEntry> {\n // Coalesce concurrent refreshers — without this, a discovery\n // route hit + a chat request triggering resolveByDiscovery can\n // both miss the cache simultaneously and each fire the upstream\n // /models call. Same provider id → same in-flight promise.\n const inflight = pendingRefresh.get(provider.id);\n if (inflight) return inflight;\n\n const fresh = (async () => {\n const entry: CacheEntry = { fetchedAt: Date.now(), models: [], error: null };\n try {\n entry.models = await discoverModels(provider);\n } catch (err) {\n entry.error = err instanceof Error ? err.message : String(err);\n // Keep stale models if we had any, so a transient upstream blip doesn't blank the list\n const prev = cache.get(provider.id);\n if (prev?.models?.length) entry.models = prev.models;\n }\n cache.set(provider.id, entry);\n return entry;\n })().finally(() => {\n pendingRefresh.delete(provider.id);\n });\n\n pendingRefresh.set(provider.id, fresh);\n return fresh;\n}\n\nasync function getEntry(provider: Provider, opts: { force?: boolean } = {}): Promise<CacheEntry> {\n const existing = cache.get(provider.id);\n if (!opts.force && existing && isFresh(existing)) return existing;\n return refreshProvider(provider);\n}\n\nfunction enabledProviders(): Provider[] {\n return db.select().from(schema.providers).where(eq(schema.providers.enabled, true)).all();\n}\n\n/**\n * Return the union of every enabled provider's discovered models. Failures on\n * individual providers are tolerated — they just contribute fewer entries.\n */\nexport async function listAllDiscovered(opts: { force?: boolean } = {}): Promise<DiscoveredModel[]> {\n const providers = enabledProviders();\n const entries = await Promise.all(providers.map((p) => getEntry(p, opts)));\n const out: DiscoveredModel[] = [];\n for (const e of entries) out.push(...e.models);\n return out;\n}\n\n/** Best-effort count of discovered models for a single provider. */\nexport async function discoveredCountForProvider(provider: Provider): Promise<number> {\n if (!provider.enabled) return 0;\n const entry = await getEntry(provider);\n return entry.models.length;\n}\n\n/** Best-effort per-provider count of discovered models (zero on failure). */\nexport async function discoveredCountByProvider(): Promise<Record<string, number>> {\n const providers = enabledProviders();\n const entries = await Promise.all(providers.map((p) => getEntry(p)));\n const out: Record<string, number> = {};\n providers.forEach((p, i) => { out[p.id] = entries[i].models.length; });\n return out;\n}\n\n/**\n * Locate which enabled provider exposes a model with the given id. Returns\n * the first match in providers-table order; cache entries are fetched in\n * parallel so total latency is bounded by the slowest provider, not the\n * sum across them.\n */\nexport async function resolveByDiscovery(\n modelName: string,\n): Promise<{ provider: Provider; upstreamModelId: string; meta: NormalizedModelMeta } | null> {\n const providers = enabledProviders();\n const entries = await Promise.all(providers.map((p) => getEntry(p)));\n for (let i = 0; i < providers.length; i++) {\n const hit = entries[i].models.find((m) => m.id === modelName);\n if (hit) return { provider: providers[i], upstreamModelId: hit.id, meta: hit.meta };\n }\n return null;\n}\n\n/** Cache-aware per-provider model list. Refreshes when stale, returns\n * the cached entry otherwise. Prefer this over `discoverModels` from\n * outside this module — it populates the cache so subsequent\n * `getDiscoveryStatus` lookups see fresh data. */\nexport async function discoveredForProvider(\n provider: Provider,\n opts: { force?: boolean } = {},\n): Promise<DiscoveredModel[]> {\n const entry = await getEntry(provider, opts);\n return entry.models;\n}\n\n/** Lookup the last cache state for a provider (no fetch). */\nexport function getDiscoveryStatus(providerId: string): CacheEntry | null {\n return cache.get(providerId) ?? null;\n}\n\n/** Drop the entire cache (e.g. on provider mutation). */\nexport function clearDiscoveryCache(): void {\n cache.clear();\n}\n","import \"server-only\";\nimport { randomUUID } from \"node:crypto\";\nimport { eq, sql } from \"drizzle-orm\";\nimport { db } from \"../db\";\nimport { models, providers } from \"../db/schema\";\nimport { decryptSecret, encryptSecret } from \"../crypto\";\nimport { badRequest, notFound } from \"../response\";\nimport { clearDiscoveryCache, discoverModels, discoveredCountByProvider, discoveredCountForProvider } from \"../discovery\";\nimport { resolveAdapter } from \"../adapters\";\nimport \"../adapters/register\";\nimport { serializeProvider } from \"./serializer\";\nimport type { ProviderDTO } from \"@/lib/schemas/provider\";\nimport type { ProviderCreateInput, ProviderUpdateInput } from \"@/lib/schemas/provider\";\nimport type { Provider } from \"../db/schema\";\n\n/** DB-only count of models per provider (excludes discovered). */\nfunction dbModelCounts(): Record<string, number> {\n const rows = db\n .select({ providerId: models.providerId, c: sql<number>`count(*)`.as(\"c\") })\n .from(models)\n .groupBy(models.providerId)\n .all();\n const map: Record<string, number> = {};\n for (const r of rows) map[r.providerId] = Number(r.c);\n return map;\n}\n\n/** DB-only count of models for a single provider (excludes discovered). */\nfunction dbModelCountForProvider(providerId: string): number {\n const row = db\n .select({ c: sql<number>`count(*)`.as(\"c\") })\n .from(models)\n .where(eq(models.providerId, providerId))\n .get();\n return Number(row?.c ?? 0);\n}\n\nexport function findProviderByIdOrName(idOrName: string): Provider | undefined {\n return (\n db.select().from(providers).where(eq(providers.id, idOrName)).get() ||\n db.select().from(providers).where(eq(providers.name, idOrName)).get()\n );\n}\n\nexport function loadProviderApiKey(p: Provider): string | null {\n return decryptSecret(p.apiKeyEncrypted);\n}\n\nexport async function listProviders(): Promise<ProviderDTO[]> {\n const rows = db.select().from(providers).orderBy(providers.name).all();\n const dbCounts = dbModelCounts();\n const discoveredCounts = await discoveredCountByProvider();\n return rows.map((p) => serializeProvider(p, (dbCounts[p.id] ?? 0) + (discoveredCounts[p.id] ?? 0)));\n}\n\nexport async function getProvider(idOrName: string): Promise<ProviderDTO> {\n const provider = findProviderByIdOrName(idOrName);\n if (!provider) throw notFound(\"Provider not found\");\n const dbCount = dbModelCountForProvider(provider.id);\n const discoveredCount = await discoveredCountForProvider(provider);\n return serializeProvider(provider, dbCount + discoveredCount);\n}\n\n/**\n * Resolve the adapter id for a (about-to-be-persisted) provider. Falls\n * back to the registry's `matches()` pass when the caller didn't pick\n * one explicitly. Built so we never persist an empty `adapter_id`.\n */\nfunction resolveAdapterId(input: { adapter_id?: string; base_url: string; api_version?: string | null }): string {\n if (input.adapter_id && input.adapter_id.trim()) return input.adapter_id.trim();\n // Synthesize a placeholder Provider for the registry's matches() pass.\n const probe: Provider = {\n id: \"\",\n name: \"\",\n adapterId: \"\",\n baseUrl: input.base_url,\n apiVersion: input.api_version ?? null,\n apiKeyEncrypted: null,\n defaultParams: {},\n httpProxy: null,\n documentPage: null,\n modelPage: null,\n healthCheckUrl: null,\n lastHealthStatus: null,\n lastHealthCheckedAt: null,\n lastHealthError: null,\n isLocal: false,\n enabled: true,\n createdAt: \"\",\n updatedAt: \"\",\n };\n return resolveAdapter(probe).id;\n}\n\nexport async function createProvider(input: ProviderCreateInput): Promise<ProviderDTO> {\n const name = input.name.trim();\n const baseUrl = input.base_url.trim();\n\n const dup = db.select().from(providers).where(eq(providers.name, name)).get();\n if (dup) throw badRequest(\"Provider name already exists\");\n\n const id = randomUUID();\n const adapterId = resolveAdapterId({ adapter_id: input.adapter_id, base_url: baseUrl, api_version: input.api_version ?? null });\n\n db.insert(providers).values({\n id,\n name,\n adapterId,\n baseUrl,\n apiVersion: input.api_version?.trim() || null,\n apiKeyEncrypted: encryptSecret(input.api_key ?? null),\n defaultParams: input.default_params ?? {},\n httpProxy: input.http_proxy ?? null,\n documentPage: input.document_page ?? null,\n modelPage: input.model_page ?? null,\n healthCheckUrl: input.health_check_url?.trim() || null,\n isLocal: !!input.is_local,\n enabled: input.enabled ?? true,\n }).run();\n clearDiscoveryCache();\n\n return getProvider(id);\n}\n\nexport async function updateProvider(idOrName: string, input: ProviderUpdateInput): Promise<ProviderDTO> {\n const provider = findProviderByIdOrName(idOrName);\n if (!provider) throw notFound(\"Provider not found\");\n\n const updates: Partial<typeof providers.$inferInsert> = {};\n\n if (input.name !== undefined) {\n const newName = input.name.trim();\n if (!newName) throw badRequest(\"Provider name cannot be empty\");\n if (newName !== provider.name) {\n const dup = db.select().from(providers).where(eq(providers.name, newName)).get();\n if (dup) throw badRequest(\"Provider name already exists\");\n updates.name = newName;\n }\n }\n if (input.adapter_id !== undefined) {\n const a = input.adapter_id?.trim();\n if (!a) throw badRequest(\"adapter_id cannot be empty\");\n updates.adapterId = a;\n }\n if (input.base_url !== undefined) {\n const newUrl = input.base_url.trim();\n if (!newUrl) throw badRequest(\"base_url cannot be empty\");\n updates.baseUrl = newUrl;\n }\n if (input.api_version !== undefined) updates.apiVersion = input.api_version?.trim() || null;\n if (input.api_key !== undefined) {\n updates.apiKeyEncrypted = input.api_key ? encryptSecret(input.api_key) : null;\n }\n if (input.default_params !== undefined) updates.defaultParams = input.default_params ?? {};\n if (input.http_proxy !== undefined) updates.httpProxy = input.http_proxy ?? null;\n if (input.document_page !== undefined) updates.documentPage = input.document_page;\n if (input.model_page !== undefined) updates.modelPage = input.model_page;\n if (input.health_check_url !== undefined) {\n const newUrl = input.health_check_url?.trim() || null;\n // Whenever the health URL itself changes (or is cleared), wipe the\n // cached status — the previous result was for a different endpoint.\n if (newUrl !== provider.healthCheckUrl) {\n updates.healthCheckUrl = newUrl;\n updates.lastHealthStatus = null;\n updates.lastHealthCheckedAt = null;\n updates.lastHealthError = null;\n }\n }\n if (input.is_local !== undefined) updates.isLocal = !!input.is_local;\n if (input.enabled !== undefined) updates.enabled = !!input.enabled;\n\n updates.updatedAt = new Date().toISOString();\n\n db.update(providers).set(updates).where(eq(providers.id, provider.id)).run();\n clearDiscoveryCache();\n return getProvider(provider.id);\n}\n\nexport async function deleteProvider(idOrName: string): Promise<void> {\n const provider = findProviderByIdOrName(idOrName);\n if (!provider) throw notFound(\"Provider not found\");\n db.delete(providers).where(eq(providers.id, provider.id)).run();\n clearDiscoveryCache();\n}\n\n/** Probe an arbitrary health-check URL. Pure I/O — no DB writes. Used\n * both by `checkProvider` (for the saved URL branch) and by the\n * `POST /providers/probe` endpoint, which lets the form Test button\n * validate the URL the user is currently editing before they save. */\nexport async function probeHealthCheckUrl(\n url: string,\n): Promise<{ ok: boolean; error?: string; latency_ms: number }> {\n const start = Date.now();\n try {\n const res = await fetch(url, {\n method: \"GET\",\n signal: AbortSignal.timeout(10_000),\n });\n const ms = Date.now() - start;\n if (!res.ok) {\n const text = await res.text().catch(() => res.statusText);\n return { ok: false, error: `HTTP ${res.status}: ${text.slice(0, 200)}`, latency_ms: ms };\n }\n const json = (await res.json().catch(() => null)) as { status?: unknown } | null;\n if (!json || json.status !== \"ok\") {\n return {\n ok: false,\n error: `Expected {\"status\":\"ok\"}, got ${JSON.stringify(json).slice(0, 200)}`,\n latency_ms: ms,\n };\n }\n return { ok: true, latency_ms: ms };\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n return { ok: false, error: msg, latency_ms: Date.now() - start };\n }\n}\n\n/**\n * Provider health probe for a saved provider. Two strategies, in\n * priority order:\n * 1. If `provider.healthCheckUrl` is set → call `probeHealthCheckUrl`\n * and persist the outcome to `last_health_*` so the UI can render\n * a real status pill without re-probing on every render.\n * 2. Otherwise → fall back to discovery via the resolved adapter,\n * which returns a model count on success. Discovery probes do NOT\n * update `last_health_*` (those columns are tied to the explicit\n * health URL contract).\n */\nexport async function checkProvider(idOrName: string): Promise<{ ok: boolean; models?: number; error?: string; latency_ms?: number }> {\n const provider = findProviderByIdOrName(idOrName);\n if (!provider) throw notFound(\"Provider not found\");\n\n if (provider.healthCheckUrl) {\n const result = await probeHealthCheckUrl(provider.healthCheckUrl);\n db.update(providers).set({\n lastHealthStatus: result.ok ? \"ok\" : \"down\",\n lastHealthCheckedAt: new Date().toISOString(),\n lastHealthError: result.ok ? null : (result.error ?? null),\n updatedAt: new Date().toISOString(),\n }).where(eq(providers.id, provider.id)).run();\n return result;\n }\n\n // No dedicated health endpoint — fall back to a discovery probe via\n // the adapter (which handles URL, auth, and shape per upstream).\n const start = Date.now();\n try {\n const models = await discoverModels(provider);\n return { ok: true, models: models.length, latency_ms: Date.now() - start };\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n return { ok: false, error: msg, latency_ms: Date.now() - start };\n }\n}\n","import \"server-only\";\nimport type { Provider } from \"../db/schema\";\nimport type { ProviderDTO } from \"@/lib/schemas/provider\";\n\nexport function serializeProvider(p: Provider, modelCount?: number): ProviderDTO {\n return {\n id: p.id,\n name: p.name,\n provider_name: p.name,\n adapter_id: p.adapterId,\n base_url: p.baseUrl,\n proxy: p.baseUrl,\n api_version: p.apiVersion ?? null,\n has_api_key: !!p.apiKeyEncrypted,\n default_params: (p.defaultParams ?? {}) as Record<string, unknown>,\n http_proxy: p.httpProxy ?? null,\n document_page: p.documentPage ?? \"\",\n model_page: p.modelPage ?? \"\",\n health_check_url: p.healthCheckUrl ?? null,\n last_health_status: p.lastHealthStatus ?? null,\n last_health_checked_at: p.lastHealthCheckedAt ?? null,\n last_health_error: p.lastHealthError ?? null,\n is_local: !!p.isLocal,\n enabled: !!p.enabled,\n n_models: modelCount,\n created_at: p.createdAt,\n updated_at: p.updatedAt,\n };\n}\n"],"names":["textPartSchema","object","type","literal","text","string","imageUrlPartSchema","image_url","url","detail","enum","optional","filePartSchema","file","filename","file_data","mime_type","toolCallPartSchema","tool_call","id","name","arguments","source","toolResultPartSchema","tool_result","tool_call_id","content","is_error","boolean","contentPartSchema","discriminatedUnion","messageContentSchema","union","array","extractText","Array","isArray","map","p","filter","Boolean","join","hasAttachments","some","cache","Map","pendingRefresh","cacheTtlMs","seconds","Number","process","env","LOOM_MODELS_CACHE_TTL","isFinite","isFresh","entry","Date","now","fetchedAt","capabilityFromMeta","meta","fallbackId","c","capabilities","embeddings","audio_in","audio_out","chat","responses","discoverModels","provider","adapter","apiKey","apiKeyEncrypted","rawEntries","fetchModels","out","raw","extractModelMeta","push","upstream_id","provider_id","provider_name","adapter_id","capability","refreshProvider","inflight","get","fresh","models","error","err","Error","message","String","prev","length","set","finally","delete","getEntry","opts","existing","force","enabledProviders","select","from","providers","where","enabled","all","listAllDiscovered","entries","Promise","e","discoveredCountForProvider","discoveredCountByProvider","forEach","i","resolveByDiscovery","modelName","hit","find","m","upstreamModelId","discoveredForProvider","getDiscoveryStatus","providerId","clearDiscoveryCache","clear","serializeProvider","modelCount","adapterId","base_url","baseUrl","proxy","api_version","apiVersion","has_api_key","default_params","defaultParams","http_proxy","httpProxy","document_page","documentPage","model_page","modelPage","health_check_url","healthCheckUrl","last_health_status","lastHealthStatus","last_health_checked_at","lastHealthCheckedAt","last_health_error","lastHealthError","is_local","isLocal","n_models","created_at","createdAt","updated_at","updatedAt"],"mappings":"mhCACA,IAAA,EAAA,EAAA,CAAA,CAAA,QCDA,EAAA,EAAA,CAAA,CAAA,QAcO,IAAMA,EAAiB,EAAA,CAAC,CAACC,MAAM,CAAC,CACnCC,KAAM,EAAA,CAAC,CAACC,OAAO,CAAC,QAChBC,KAAM,EAAA,CAAC,CAACC,MAAM,EAClB,GAEaC,EAAqB,EAAA,CAAC,CAACL,MAAM,CAAC,CACvCC,KAAM,EAAA,CAAC,CAACC,OAAO,CAAC,aAChBI,UAAW,EAAA,CAAC,CAACN,MAAM,CAAC,CAGhBO,IAAK,EAAA,CAAC,CAACH,MAAM,GACbI,OAAQ,EAAA,CAAC,CAACC,IAAI,CAAC,CAAC,OAAQ,MAAO,OAAO,EAAEC,QAAQ,EACpD,EACJ,GAEaC,EAAiB,EAAA,CAAC,CAACX,MAAM,CAAC,CACnCC,KAAM,EAAA,CAAC,CAACC,OAAO,CAAC,QAChBU,KAAM,EAAA,CAAC,CAACZ,MAAM,CAAC,CACXa,SAAU,EAAA,CAAC,CAACT,MAAM,GAElBU,UAAW,EAAA,CAAC,CAACV,MAAM,GAEnBW,UAAW,EAAA,CAAC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AI,KACrD,UAAW,IAAI,OAAO,WAAW,EACrC,GAAG,KAAK,CAAC,CAAA,EAAA,EAAA,EAAA,AAAE,EAAC,EAAA,SAAS,CAAC,EAAE,CAAE,EAAS,EAAE,GAAG,GAAG,GACpC,CACX,CAIA,IAAM,EAAQ,KAAK,GAAG,GACtB,GAAI,CACA,IAAM,EAAS,MAAM,CAAA,EAAA,EAAA,cAAA,AAAc,EAAC,GACpC,MAAO,CAAE,IAAI,EAAM,OAAQ,EAAO,MAAM,CAAE,WAAY,KAAK,GAAG,GAAK,CAAM,CAC7E,CAAE,MAAO,EAAK,CAEV,MAAO,CAAE,IAAI,EAAO,MADR,CACe,YADA,MAAQ,EAAI,OAAO,CAAG,OAAO,GACxB,WAAY,KAAK,GAAG,GAAK,CAAM,CACnE,CACJ,CArPA,EAAA,CAAA,CAAA"}
@@ -1,3 +0,0 @@
1
- module.exports=[814747,(e,t,r)=>{t.exports=e.x("path",()=>require("path"))},872031,e=>{"use strict";var t=e.i(902157),r=e.i(750227);let a=process.env.LOOM_USER_CWD||process.cwd(),n=(0,r.resolve)(a,"data","log-artifacts");function i(e){return(0,r.resolve)(n,e)}function o(e,t,a){return(0,r.resolve)(i(e),`${t}.${a}`)}function s(e,t){return`/api/logs/generations/${encodeURIComponent(e)}/images/${t}`}async function l(e,r){let a=r.data;if(!Array.isArray(a))return[];let n=[],l=!1;for(let r=0;r<a.length;r++){let u=a[r];if(!u||"object"!=typeof u)continue;let d="string"==typeof u.b64_json?u.b64_json:null;if(!d)continue;let p=Buffer.from(d,"base64"),c="string"==typeof u.mime?u.mime:"string"==typeof u.output_format?`image/${u.output_format}`:"image/png",g=o(e,r,function(e){switch(e.toLowerCase()){case"image/png":return"png";case"image/jpeg":case"image/jpg":return"jpg";case"image/webp":return"webp";case"image/gif":return"gif";default:return"bin"}}(c));l||((0,t.mkdirSync)(i(e),{recursive:!0}),l=!0),await t.promises.writeFile(g,p),delete u.b64_json,u.url=s(e,r),u.loom_artifact=!0,u.bytes=p.byteLength,u.mime=c,n.push({index:r,mime:c,bytes:p.byteLength,path:g,url:s(e,r)})}return n.length>0&&(r.loom_artifacts=n.map(e=>({index:e.index,url:e.url,mime:e.mime,bytes:e.bytes}))),n}async function u(e,r){for(let a of["png","jpg","webp","gif","bin"]){let n=o(e,r,a);try{let e=await t.promises.readFile(n),r="jpg"===a?"image/jpeg":"bin"===a?"application/octet-stream":`image/${a}`;return{buf:e,mime:r}}catch{}}return null}e.s(["persistImageArtifacts",0,l,"readArtifact",0,u])},59639,(e,t,r)=>{t.exports=e.x("node:process",()=>require("node:process"))},738038,e=>{"use strict";var t=e.i(747909),r=e.i(174017),a=e.i(996250),n=e.i(759756),i=e.i(561916),o=e.i(174677),s=e.i(869741),l=e.i(316795),u=e.i(487718),d=e.i(995169),p=e.i(47587),c=e.i(666012),g=e.i(570101),h=e.i(626937),m=e.i(10372),f=e.i(193695);e.i(52474);var R=e.i(600220),v=e.i(456315),y=e.i(435e3);e.i(867661);var w=e.i(319580);let b=(0,v.defineRoute)({body:y.playgroundEmbeddingSchema,handler:({user:e,body:t})=>(0,w.runEmbeddingComparison)(e,t)});e.s(["POST",0,b],632050);var E=e.i(632050);let C=new t.AppRouteRouteModule({definition:{kind:r.RouteKind.APP_ROUTE,page:"/api/playground/embedding/route",pathname:"/api/playground/embedding",filename:"route",bundlePath:""},distDir:".next",relativeProjectDir:"",resolvedPagePath:"[project]/app/api/playground/embedding/route.ts",nextConfigOutput:"",userland:E,...{}}),{workAsyncStorage:x,workUnitAsyncStorage:A,serverHooks:_}=C;async function P(e,t,a){a.requestMeta&&(0,n.setRequestMeta)(e,a.requestMeta),C.isDev&&(0,n.addRequestMeta)(e,"devRequestTimingInternalsEnd",process.hrtime.bigint());let v="/api/playground/embedding/route";v=v.replace(/\/index$/,"")||"/";let y=await C.prepare(e,t,{srcPage:v,multiZoneDraftMode:!1});if(!y)return t.statusCode=400,t.end("Bad Request"),null==a.waitUntil||a.waitUntil.call(a,Promise.resolve()),null;let{buildId:w,deploymentId:b,params:E,nextConfig:x,parsedUrl:A,isDraftMode:_,prerenderManifest:P,routerServerContext:S,isOnDemandRevalidate:T,revalidateOnlyGenerated:N,resolvedPathname:O,clientReferenceManifest:q,serverActionsManifest:I}=y,U=(0,s.normalizeAppPath)(v),j=!!(P.dynamicRoutes[U]||P.routes[O]),H=async()=>((null==S?void 0:S.render404)?await S.render404(e,t,A,!1):t.end("This page could not be found"),null);if(j&&!_){let e=!!P.routes[O],t=P.dynamicRoutes[U];if(t&&!1===t.fallback&&!e){if(x.adapterPath)return await H();throw new f.NoFallbackError}}let M=null;!j||C.isDev||_||(M="/index"===(M=O)?"/":M);let $=!0===C.isDev||!j,k=j&&!$;I&&q&&(0,o.setManifestsSingleton)({page:v,clientReferenceManifest:q,serverActionsManifest:I});let D=e.method||"GET",F=(0,i.getTracer)(),L=F.getActiveScopeSpan(),K=!!(null==S?void 0:S.isWrappedByNextServer),B=!!(0,n.getRequestMeta)(e,"minimalMode"),W=(0,n.getRequestMeta)(e,"incrementalCache")||await C.getIncrementalCache(e,x,P,B);null==W||W.resetRequestCache(),globalThis.__incrementalCache=W;let G={params:E,previewProps:P.preview,renderOpts:{experimental:{authInterrupts:!!x.experimental.authInterrupts},cacheComponents:!!x.cacheComponents,supportsDynamicResponse:$,incrementalCache:W,cacheLifeProfiles:x.cacheLife,waitUntil:a.waitUntil,onClose:e=>{t.on("close",e)},onAfterTaskError:void 0,onInstrumentationRequestError:(t,r,a,n)=>C.onRequestError(e,t,a,n,S)},sharedContext:{buildId:w,deploymentId:b}},V=new l.NodeNextRequest(e),X=new l.NodeNextResponse(t),z=u.NextRequestAdapter.fromNodeNextRequest(V,(0,u.signalFromNodeResponse)(t));try{let n,o=async e=>C.handle(z,G).finally(()=>{if(!e)return;e.setAttributes({"http.status_code":t.statusCode,"next.rsc":!1});let r=F.getRootSpanAttributes();if(!r)return;if(r.get("next.span_type")!==d.BaseServerSpan.handleRequest)return void console.warn(`Unexpected root span type '${r.get("next.span_type")}'. Please report this Next.js issue https://github.com/vercel/next.js`);let a=r.get("next.route");if(a){let t=`${D} ${a}`;e.setAttributes({"next.route":a,"http.route":a,"next.span_name":t}),e.updateName(t),n&&n!==e&&(n.setAttribute("http.route",a),n.updateName(t))}else e.updateName(`${D} ${v}`)}),s=async n=>{var i,s;let l=async({previousCacheEntry:r})=>{try{if(!B&&T&&N&&!r)return t.statusCode=404,t.setHeader("x-nextjs-cache","REVALIDATED"),t.end("This page could not be found"),null;let i=await o(n);e.fetchMetrics=G.renderOpts.fetchMetrics;let s=G.renderOpts.pendingWaitUntil;s&&a.waitUntil&&(a.waitUntil(s),s=void 0);let l=G.renderOpts.collectedTags;if(!j)return await (0,c.sendResponse)(V,X,i,G.renderOpts.pendingWaitUntil),null;{let e=await i.blob(),t=(0,g.toNodeOutgoingHttpHeaders)(i.headers);l&&(t[m.NEXT_CACHE_TAGS_HEADER]=l),!t["content-type"]&&e.type&&(t["content-type"]=e.type);let r=void 0!==G.renderOpts.collectedRevalidate&&!(G.renderOpts.collectedRevalidate>=m.INFINITE_CACHE)&&G.renderOpts.collectedRevalidate,a=void 0===G.renderOpts.collectedExpire||G.renderOpts.collectedExpire>=m.INFINITE_CACHE?void 0:G.renderOpts.collectedExpire;return{value:{kind:R.CachedRouteKind.APP_ROUTE,status:i.status,body:Buffer.from(await e.arrayBuffer()),headers:t},cacheControl:{revalidate:r,expire:a}}}}catch(t){throw(null==r?void 0:r.isStale)&&await C.onRequestError(e,t,{routerKind:"App Router",routePath:v,routeType:"route",revalidateReason:(0,p.getRevalidateReason)({isStaticGeneration:k,isOnDemandRevalidate:T})},!1,S),t}},u=await C.handleResponse({req:e,nextConfig:x,cacheKey:M,routeKind:r.RouteKind.APP_ROUTE,isFallback:!1,prerenderManifest:P,isRoutePPREnabled:!1,isOnDemandRevalidate:T,revalidateOnlyGenerated:N,responseGenerator:l,waitUntil:a.waitUntil,isMinimalMode:B});if(!j)return null;if((null==u||null==(i=u.value)?void 0:i.kind)!==R.CachedRouteKind.APP_ROUTE)throw Object.defineProperty(Error(`Invariant: app-route received invalid cache entry ${null==u||null==(s=u.value)?void 0:s.kind}`),"__NEXT_ERROR_CODE",{value:"E701",enumerable:!1,configurable:!0});B||t.setHeader("x-nextjs-cache",T?"REVALIDATED":u.isMiss?"MISS":u.isStale?"STALE":"HIT"),_&&t.setHeader("Cache-Control","private, no-cache, no-store, max-age=0, must-revalidate");let d=(0,g.fromNodeOutgoingHttpHeaders)(u.value.headers);return B&&j||d.delete(m.NEXT_CACHE_TAGS_HEADER),!u.cacheControl||t.getHeader("Cache-Control")||d.get("Cache-Control")||d.set("Cache-Control",(0,h.getCacheControlHeader)(u.cacheControl)),await (0,c.sendResponse)(V,X,new Response(u.value.body,{headers:d,status:u.value.status||200})),null};K&&L?await s(L):(n=F.getActiveScopeSpan(),await F.withPropagatedContext(e.headers,()=>F.trace(d.BaseServerSpan.handleRequest,{spanName:`${D} ${v}`,kind:i.SpanKind.SERVER,attributes:{"http.method":D,"http.target":e.url}},s),void 0,!K))}catch(t){if(t instanceof f.NoFallbackError||await C.onRequestError(e,t,{routerKind:"App Router",routePath:U,routeType:"route",revalidateReason:(0,p.getRevalidateReason)({isStaticGeneration:k,isOnDemandRevalidate:T})},!1,S),j)throw t;return await (0,c.sendResponse)(V,X,new Response(null,{status:500})),null}}e.s(["handler",0,P,"patchFetch",0,function(){return(0,a.patchFetch)({workAsyncStorage:x,workUnitAsyncStorage:A})},"routeModule",0,C,"serverHooks",0,_,"workAsyncStorage",0,x,"workUnitAsyncStorage",0,A],738038)},70729,e=>{e.v(e=>Promise.resolve().then(()=>e(666680)))}];
2
-
3
- //# sourceMappingURL=%5Broot-of-the-server%5D__022u2d9._.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../../lib/server/gateway/artifacts.ts","../../../node_modules/next/dist/esm/build/templates/app-route.js","../../../app/api/playground/embedding/route.ts"],"sourcesContent":["import \"server-only\";\nimport { promises as fs, mkdirSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\n\n/**\n * Image artifact persistence for `generation_logs`.\n *\n * Why: image-generation upstreams return either a hosted `url` (which\n * expires) or a base64 `b64_json` blob (~MB per image). Persisting the\n * raw b64 inline in `generation_logs.generation` (JSON column) bloats\n * the DB by a factor of 10–100× and makes the log viewer's JSON tree\n * unusable. Mirroring the existing `sanitizeForJsonView` strategy for\n * large text/JSON, we strip the b64 from the log payload and write\n * each image to a per-log directory on disk; the log keeps a stable\n * `url` reference (and `loom_artifact: true` marker) that the FE log\n * viewer reads to render inline thumbnails.\n *\n * The original (untouched) payload is still served to the API caller\n * — only the *log copy* is rewritten. The image-generation playground\n * therefore continues to receive b64_json verbatim.\n */\n\nconst USER_CWD = process.env.LOOM_USER_CWD || process.cwd();\nconst ARTIFACTS_ROOT = resolve(USER_CWD, \"data\", \"log-artifacts\");\n\nexport interface PersistedArtifact {\n /** Position within the upstream `data[]` array. */\n index: number;\n mime: string;\n bytes: number;\n /** Absolute filesystem path. */\n path: string;\n /** Same-origin URL the FE viewer (and the log JSON) reference. */\n url: string;\n}\n\nfunction extFromMime(mime: string): string {\n switch (mime.toLowerCase()) {\n case \"image/png\": return \"png\";\n case \"image/jpeg\":\n case \"image/jpg\": return \"jpg\";\n case \"image/webp\": return \"webp\";\n case \"image/gif\": return \"gif\";\n default: return \"bin\";\n }\n}\n\nexport function artifactDir(logId: string): string {\n return resolve(ARTIFACTS_ROOT, logId);\n}\n\nexport function artifactPath(logId: string, index: number, ext: string): string {\n return resolve(artifactDir(logId), `${index}.${ext}`);\n}\n\nexport function artifactUrl(logId: string, index: number): string {\n return `/api/logs/generations/${encodeURIComponent(logId)}/images/${index}`;\n}\n\n/**\n * Walk the log copy of `normalized.data[]` and persist every `b64_json`\n * to disk. Mutates the passed object in place — callers MUST clone\n * first if they need to preserve the original (e.g. to forward it to\n * the API caller as-is).\n *\n * Returns the descriptors of every artifact written, ordered by index.\n */\nexport async function persistImageArtifacts(\n logId: string,\n normalized: Record<string, unknown>,\n): Promise<PersistedArtifact[]> {\n const data = (normalized as { data?: unknown }).data;\n if (!Array.isArray(data)) return [];\n\n const artifacts: PersistedArtifact[] = [];\n let dirEnsured = false;\n\n for (let i = 0; i < data.length; i++) {\n const entry = data[i];\n if (!entry || typeof entry !== \"object\") continue;\n const e = entry as Record<string, unknown>;\n const b64 = typeof e.b64_json === \"string\" ? e.b64_json : null;\n if (!b64) continue;\n\n // Decode + write.\n const buf = Buffer.from(b64, \"base64\");\n const mime = typeof e.mime === \"string\"\n ? e.mime\n : typeof e.output_format === \"string\"\n ? `image/${e.output_format}`\n : \"image/png\";\n const ext = extFromMime(mime);\n const path = artifactPath(logId, i, ext);\n\n if (!dirEnsured) {\n mkdirSync(artifactDir(logId), { recursive: true });\n dirEnsured = true;\n }\n await fs.writeFile(path, buf);\n\n // Rewrite the entry: drop the b64 blob, point `url` at our\n // same-origin proxy, and mark it so the FE log viewer knows\n // this URL is a loom-managed artifact (vs an expiring upstream\n // URL). Keeping the rest of the upstream entry intact\n // preserves fields like `revised_prompt`.\n delete e.b64_json;\n e.url = artifactUrl(logId, i);\n e.loom_artifact = true;\n e.bytes = buf.byteLength;\n e.mime = mime;\n\n artifacts.push({\n index: i,\n mime,\n bytes: buf.byteLength,\n path,\n url: artifactUrl(logId, i),\n });\n }\n\n // Top-level convenience array — lets the FE viewer enumerate\n // artifacts without re-walking `data[]`.\n if (artifacts.length > 0) {\n (normalized as Record<string, unknown>).loom_artifacts = artifacts.map((a) => ({\n index: a.index,\n url: a.url,\n mime: a.mime,\n bytes: a.bytes,\n }));\n }\n return artifacts;\n}\n\n/** Filesystem read for the artifact route — performs a path-traversal\n * guard since `index` comes off the URL. */\nexport async function readArtifact(\n logId: string,\n index: number,\n): Promise<{ buf: Buffer; mime: string } | null> {\n // Probe each known extension; cheap (≤4 readFile attempts) and avoids\n // listing the directory just to find the right suffix. The first\n // missing file we hit also implicitly probes the parent dir, so\n // there's no need for a separate existsSync — let ENOENT bubble.\n for (const ext of [\"png\", \"jpg\", \"webp\", \"gif\", \"bin\"]) {\n const path = artifactPath(logId, index, ext);\n try {\n const buf = await fs.readFile(path);\n const mime = ext === \"jpg\" ? \"image/jpeg\" : ext === \"bin\" ? \"application/octet-stream\" : `image/${ext}`;\n return { buf, mime };\n } catch {\n // not this ext (or dir missing); fall through\n }\n }\n return null;\n}\n","import { AppRouteRouteModule } from \"next/dist/esm/server/route-modules/app-route/module.compiled\";\nimport { RouteKind } from \"next/dist/esm/server/route-kind\";\nimport { patchFetch as _patchFetch } from \"next/dist/esm/server/lib/patch-fetch\";\nimport { addRequestMeta, getRequestMeta, setRequestMeta } from \"next/dist/esm/server/request-meta\";\nimport { getTracer, SpanKind } from \"next/dist/esm/server/lib/trace/tracer\";\nimport { setManifestsSingleton } from \"next/dist/esm/server/app-render/manifests-singleton\";\nimport { normalizeAppPath } from \"next/dist/esm/shared/lib/router/utils/app-paths\";\nimport { NodeNextRequest, NodeNextResponse } from \"next/dist/esm/server/base-http/node\";\nimport { NextRequestAdapter, signalFromNodeResponse } from \"next/dist/esm/server/web/spec-extension/adapters/next-request\";\nimport { BaseServerSpan } from \"next/dist/esm/server/lib/trace/constants\";\nimport { getRevalidateReason } from \"next/dist/esm/server/instrumentation/utils\";\nimport { sendResponse } from \"next/dist/esm/server/send-response\";\nimport { fromNodeOutgoingHttpHeaders, toNodeOutgoingHttpHeaders } from \"next/dist/esm/server/web/utils\";\nimport { getCacheControlHeader } from \"next/dist/esm/server/lib/cache-control\";\nimport { INFINITE_CACHE, NEXT_CACHE_TAGS_HEADER } from \"next/dist/esm/lib/constants\";\nimport { NoFallbackError } from \"next/dist/esm/shared/lib/no-fallback-error.external\";\nimport { CachedRouteKind } from \"next/dist/esm/server/response-cache\";\nimport * as userland from \"INNER_APP_ROUTE\";\n// We inject the nextConfigOutput here so that we can use them in the route\n// module.\nconst nextConfigOutput = \"\"\nconst routeModule = new AppRouteRouteModule({\n definition: {\n kind: RouteKind.APP_ROUTE,\n page: \"/api/playground/embedding/route\",\n pathname: \"/api/playground/embedding\",\n filename: \"route\",\n bundlePath: \"\"\n },\n distDir: process.env.__NEXT_RELATIVE_DIST_DIR || '',\n relativeProjectDir: process.env.__NEXT_RELATIVE_PROJECT_DIR || '',\n resolvedPagePath: \"[project]/app/api/playground/embedding/route.ts\",\n nextConfigOutput,\n // The static import is used for initialization (methods, dynamic, etc.).\n userland: userland,\n // In Turbopack dev mode, also provide a getter that calls require() on every\n // request. This re-reads from devModuleCache so HMR updates are picked up,\n // and the async wrapper unwraps async-module Promises (ESM-only\n // serverExternalPackages) automatically.\n ...process.env.TURBOPACK && process.env.__NEXT_DEV_SERVER ? {\n getUserland: ()=>import(\"INNER_APP_ROUTE\")\n } : {}\n});\n// Pull out the exports that we need to expose from the module. This should\n// be eliminated when we've moved the other routes to the new format. These\n// are used to hook into the route.\nconst { workAsyncStorage, workUnitAsyncStorage, serverHooks } = routeModule;\nfunction patchFetch() {\n return _patchFetch({\n workAsyncStorage,\n workUnitAsyncStorage\n });\n}\nexport { routeModule, workAsyncStorage, workUnitAsyncStorage, serverHooks, patchFetch, };\nexport async function handler(req, res, ctx) {\n if (ctx.requestMeta) {\n setRequestMeta(req, ctx.requestMeta);\n }\n if (routeModule.isDev) {\n addRequestMeta(req, 'devRequestTimingInternalsEnd', process.hrtime.bigint());\n }\n let srcPage = \"/api/playground/embedding/route\";\n // turbopack doesn't normalize `/index` in the page name\n // so we need to to process dynamic routes properly\n // TODO: fix turbopack providing differing value from webpack\n if (process.env.TURBOPACK) {\n srcPage = srcPage.replace(/\\/index$/, '') || '/';\n } else if (srcPage === '/index') {\n // we always normalize /index specifically\n srcPage = '/';\n }\n const multiZoneDraftMode = process.env.__NEXT_MULTI_ZONE_DRAFT_MODE;\n const prepareResult = await routeModule.prepare(req, res, {\n srcPage,\n multiZoneDraftMode\n });\n if (!prepareResult) {\n res.statusCode = 400;\n res.end('Bad Request');\n ctx.waitUntil == null ? void 0 : ctx.waitUntil.call(ctx, Promise.resolve());\n return null;\n }\n const { buildId, deploymentId, params, nextConfig, parsedUrl, isDraftMode, prerenderManifest, routerServerContext, isOnDemandRevalidate, revalidateOnlyGenerated, resolvedPathname, clientReferenceManifest, serverActionsManifest } = prepareResult;\n const normalizedSrcPage = normalizeAppPath(srcPage);\n let isIsr = Boolean(prerenderManifest.dynamicRoutes[normalizedSrcPage] || prerenderManifest.routes[resolvedPathname]);\n const render404 = async ()=>{\n // TODO: should route-module itself handle rendering the 404\n if (routerServerContext == null ? void 0 : routerServerContext.render404) {\n await routerServerContext.render404(req, res, parsedUrl, false);\n } else {\n res.end('This page could not be found');\n }\n return null;\n };\n if (isIsr && !isDraftMode) {\n const isPrerendered = Boolean(prerenderManifest.routes[resolvedPathname]);\n const prerenderInfo = prerenderManifest.dynamicRoutes[normalizedSrcPage];\n if (prerenderInfo) {\n if (prerenderInfo.fallback === false && !isPrerendered) {\n if (nextConfig.adapterPath) {\n return await render404();\n }\n throw new NoFallbackError();\n }\n }\n }\n let cacheKey = null;\n if (isIsr && !routeModule.isDev && !isDraftMode) {\n cacheKey = resolvedPathname;\n // ensure /index and / is normalized to one key\n cacheKey = cacheKey === '/index' ? '/' : cacheKey;\n }\n const supportsDynamicResponse = // If we're in development, we always support dynamic HTML\n routeModule.isDev === true || // If this is not SSG or does not have static paths, then it supports\n // dynamic HTML.\n !isIsr;\n // This is a revalidation request if the request is for a static\n // page and it is not being resumed from a postponed render and\n // it is not a dynamic RSC request then it is a revalidation\n // request.\n const isStaticGeneration = isIsr && !supportsDynamicResponse;\n // Before rendering (which initializes component tree modules), we have to\n // set the reference manifests to our global store so Server Action's\n // encryption util can access to them at the top level of the page module.\n if (serverActionsManifest && clientReferenceManifest) {\n setManifestsSingleton({\n page: srcPage,\n clientReferenceManifest,\n serverActionsManifest\n });\n }\n const method = req.method || 'GET';\n const tracer = getTracer();\n const activeSpan = tracer.getActiveScopeSpan();\n const isWrappedByNextServer = Boolean(routerServerContext == null ? void 0 : routerServerContext.isWrappedByNextServer);\n const isMinimalMode = Boolean(getRequestMeta(req, 'minimalMode'));\n const incrementalCache = getRequestMeta(req, 'incrementalCache') || await routeModule.getIncrementalCache(req, nextConfig, prerenderManifest, isMinimalMode);\n incrementalCache == null ? void 0 : incrementalCache.resetRequestCache();\n globalThis.__incrementalCache = incrementalCache;\n const context = {\n params,\n previewProps: prerenderManifest.preview,\n renderOpts: {\n experimental: {\n authInterrupts: Boolean(nextConfig.experimental.authInterrupts)\n },\n cacheComponents: Boolean(nextConfig.cacheComponents),\n supportsDynamicResponse,\n incrementalCache,\n cacheLifeProfiles: nextConfig.cacheLife,\n waitUntil: ctx.waitUntil,\n onClose: (cb)=>{\n res.on('close', cb);\n },\n onAfterTaskError: undefined,\n onInstrumentationRequestError: (error, _request, errorContext, silenceLog)=>routeModule.onRequestError(req, error, errorContext, silenceLog, routerServerContext)\n },\n sharedContext: {\n buildId,\n deploymentId\n }\n };\n const nodeNextReq = new NodeNextRequest(req);\n const nodeNextRes = new NodeNextResponse(res);\n const nextReq = NextRequestAdapter.fromNodeNextRequest(nodeNextReq, signalFromNodeResponse(res));\n try {\n let parentSpan;\n const invokeRouteModule = async (span)=>{\n return routeModule.handle(nextReq, context).finally(()=>{\n if (!span) return;\n span.setAttributes({\n 'http.status_code': res.statusCode,\n 'next.rsc': false\n });\n const rootSpanAttributes = tracer.getRootSpanAttributes();\n // We were unable to get attributes, probably OTEL is not enabled\n if (!rootSpanAttributes) {\n return;\n }\n if (rootSpanAttributes.get('next.span_type') !== BaseServerSpan.handleRequest) {\n console.warn(`Unexpected root span type '${rootSpanAttributes.get('next.span_type')}'. Please report this Next.js issue https://github.com/vercel/next.js`);\n return;\n }\n const route = rootSpanAttributes.get('next.route');\n if (route) {\n const name = `${method} ${route}`;\n span.setAttributes({\n 'next.route': route,\n 'http.route': route,\n 'next.span_name': name\n });\n span.updateName(name);\n // Propagate http.route to the parent span if one exists (e.g.\n // a platform-created HTTP span in adapter deployments).\n if (parentSpan && parentSpan !== span) {\n parentSpan.setAttribute('http.route', route);\n parentSpan.updateName(name);\n }\n } else {\n span.updateName(`${method} ${srcPage}`);\n }\n });\n };\n const handleResponse = async (currentSpan)=>{\n var _cacheEntry_value;\n const responseGenerator = async ({ previousCacheEntry })=>{\n try {\n if (!isMinimalMode && isOnDemandRevalidate && revalidateOnlyGenerated && !previousCacheEntry) {\n res.statusCode = 404;\n // on-demand revalidate always sets this header\n res.setHeader('x-nextjs-cache', 'REVALIDATED');\n res.end('This page could not be found');\n return null;\n }\n const response = await invokeRouteModule(currentSpan);\n req.fetchMetrics = context.renderOpts.fetchMetrics;\n let pendingWaitUntil = context.renderOpts.pendingWaitUntil;\n // Attempt using provided waitUntil if available\n // if it's not we fallback to sendResponse's handling\n if (pendingWaitUntil) {\n if (ctx.waitUntil) {\n ctx.waitUntil(pendingWaitUntil);\n pendingWaitUntil = undefined;\n }\n }\n const cacheTags = context.renderOpts.collectedTags;\n // If the request is for a static response, we can cache it so long\n // as it's not edge.\n if (isIsr) {\n const blob = await response.blob();\n // Copy the headers from the response.\n const headers = toNodeOutgoingHttpHeaders(response.headers);\n if (cacheTags) {\n headers[NEXT_CACHE_TAGS_HEADER] = cacheTags;\n }\n if (!headers['content-type'] && blob.type) {\n headers['content-type'] = blob.type;\n }\n const revalidate = typeof context.renderOpts.collectedRevalidate === 'undefined' || context.renderOpts.collectedRevalidate >= INFINITE_CACHE ? false : context.renderOpts.collectedRevalidate;\n const expire = typeof context.renderOpts.collectedExpire === 'undefined' || context.renderOpts.collectedExpire >= INFINITE_CACHE ? undefined : context.renderOpts.collectedExpire;\n // Create the cache entry for the response.\n const cacheEntry = {\n value: {\n kind: CachedRouteKind.APP_ROUTE,\n status: response.status,\n body: Buffer.from(await blob.arrayBuffer()),\n headers\n },\n cacheControl: {\n revalidate,\n expire\n }\n };\n return cacheEntry;\n } else {\n // send response without caching if not ISR\n await sendResponse(nodeNextReq, nodeNextRes, response, context.renderOpts.pendingWaitUntil);\n return null;\n }\n } catch (err) {\n // if this is a background revalidate we need to report\n // the request error here as it won't be bubbled\n if (previousCacheEntry == null ? void 0 : previousCacheEntry.isStale) {\n const silenceLog = false;\n await routeModule.onRequestError(req, err, {\n routerKind: 'App Router',\n routePath: srcPage,\n routeType: 'route',\n revalidateReason: getRevalidateReason({\n isStaticGeneration,\n isOnDemandRevalidate\n })\n }, silenceLog, routerServerContext);\n }\n throw err;\n }\n };\n const cacheEntry = await routeModule.handleResponse({\n req,\n nextConfig,\n cacheKey,\n routeKind: RouteKind.APP_ROUTE,\n isFallback: false,\n prerenderManifest,\n isRoutePPREnabled: false,\n isOnDemandRevalidate,\n revalidateOnlyGenerated,\n responseGenerator,\n waitUntil: ctx.waitUntil,\n isMinimalMode\n });\n // we don't create a cacheEntry for ISR\n if (!isIsr) {\n return null;\n }\n if ((cacheEntry == null ? void 0 : (_cacheEntry_value = cacheEntry.value) == null ? void 0 : _cacheEntry_value.kind) !== CachedRouteKind.APP_ROUTE) {\n var _cacheEntry_value1;\n throw Object.defineProperty(new Error(`Invariant: app-route received invalid cache entry ${cacheEntry == null ? void 0 : (_cacheEntry_value1 = cacheEntry.value) == null ? void 0 : _cacheEntry_value1.kind}`), \"__NEXT_ERROR_CODE\", {\n value: \"E701\",\n enumerable: false,\n configurable: true\n });\n }\n if (!isMinimalMode) {\n res.setHeader('x-nextjs-cache', isOnDemandRevalidate ? 'REVALIDATED' : cacheEntry.isMiss ? 'MISS' : cacheEntry.isStale ? 'STALE' : 'HIT');\n }\n // Draft mode should never be cached\n if (isDraftMode) {\n res.setHeader('Cache-Control', 'private, no-cache, no-store, max-age=0, must-revalidate');\n }\n const headers = fromNodeOutgoingHttpHeaders(cacheEntry.value.headers);\n if (!(isMinimalMode && isIsr)) {\n headers.delete(NEXT_CACHE_TAGS_HEADER);\n }\n // If cache control is already set on the response we don't\n // override it to allow users to customize it via next.config\n if (cacheEntry.cacheControl && !res.getHeader('Cache-Control') && !headers.get('Cache-Control')) {\n headers.set('Cache-Control', getCacheControlHeader(cacheEntry.cacheControl));\n }\n await sendResponse(nodeNextReq, nodeNextRes, // @ts-expect-error - Argument of type 'Buffer<ArrayBufferLike>' is not assignable to parameter of type 'BodyInit | null | undefined'.\n new Response(cacheEntry.value.body, {\n headers,\n status: cacheEntry.value.status || 200\n }));\n return null;\n };\n // TODO: activeSpan code path is for when wrapped by\n // next-server can be removed when this is no longer used\n if (isWrappedByNextServer && activeSpan) {\n await handleResponse(activeSpan);\n } else {\n parentSpan = tracer.getActiveScopeSpan();\n await tracer.withPropagatedContext(req.headers, ()=>tracer.trace(BaseServerSpan.handleRequest, {\n spanName: `${method} ${srcPage}`,\n kind: SpanKind.SERVER,\n attributes: {\n 'http.method': method,\n 'http.target': req.url\n }\n }, handleResponse), undefined, !isWrappedByNextServer);\n }\n } catch (err) {\n if (!(err instanceof NoFallbackError)) {\n const silenceLog = false;\n await routeModule.onRequestError(req, err, {\n routerKind: 'App Router',\n routePath: normalizedSrcPage,\n routeType: 'route',\n revalidateReason: getRevalidateReason({\n isStaticGeneration,\n isOnDemandRevalidate\n })\n }, silenceLog, routerServerContext);\n }\n // rethrow so that we can handle serving error page\n // If this is during static generation, throw the error again.\n if (isIsr) throw err;\n // Otherwise, send a 500 response.\n await sendResponse(nodeNextReq, nodeNextRes, new Response(null, {\n status: 500\n }));\n return null;\n }\n}\n\n//# sourceMappingURL=app-route.js.map\n","import \"server-only\";\nimport { defineRoute } from \"@/lib/server/route\";\nimport { playgroundEmbeddingSchema } from \"@/lib/schemas/playground\";\nimport { runEmbeddingComparison } from \"@/lib/server/playground\";\n\nexport const POST = defineRoute({\n body: playgroundEmbeddingSchema,\n handler: ({ user, body }) => runEmbeddingComparison(user, body),\n});\n"],"names":["USER_CWD","process","env","LOOM_USER_CWD","cwd","ARTIFACTS_ROOT","extFromMime","mime","toLowerCase","artifactDir","logId","artifactPath","index","ext","artifactUrl","encodeURIComponent","persistImageArtifacts","normalized","data","Array","isArray","artifacts","dirEnsured","i","length","entry","e","b64","b64_json","buf","Buffer","from","output_format","path","recursive","writeFile","url","loom_artifact","bytes","byteLength","push","loom_artifacts","map","a","readArtifact","readFile","POST","body","handler","user"],"mappings":"oGACA,IAAA,EAAA,EAAA,CAAA,CAAA,QACA,EAAA,EAAA,CAAA,CAAA,QAoBA,IAAMA,EAAWC,QAAQC,GAAG,CAACC,aAAa,EAAIF,QAAQG,GAAG,GACnDC,EAAiB,CAAA,EAAA,EAAA,OAAA,AAAO,EAACL,EAAU,OAAQ,iBAwB1C,SAASS,EAAYC,CAAa,EACrC,MAAO,CAAA,EAAA,EAAA,OAAA,AAAO,EAACL,EAAgBK,EACnC,CAEO,SAASC,EAAaD,CAAa,CAAEE,CAAa,CAAEC,CAAW,EAClE,MAAO,CAAA,EAAA,EAAA,OAAA,AAAO,EAACJ,EAAYC,GAAQ,CAAA,EAAGE,EAAM,CAAC,EAAEC,EAAAA,CAAK,CACxD,CAEO,SAASC,EAAYJ,CAAa,CAAEE,CAAa,EACpD,MAAO,CAAC,sBAAsB,EAAEG,mBAAmBL,GAAO,QAAQ,EAAEE,EAAAA,CAAO,AAC/E,CAUO,eAAeI,EAClBN,CAAa,CACbO,CAAmC,EAEnC,IAAMC,EAAQD,EAAkCC,IAAI,CACpD,GAAI,CAACC,MAAMC,OAAO,CAACF,GAAO,MAAO,EAAE,CAEnC,IAAMG,EAAiC,EAAE,CACrCC,GAAa,EAEjB,IAAK,IAAIC,EAAI,EAAGA,EAAIL,EAAKM,MAAM,CAAED,IAAK,CAClC,IAAME,EAAQP,CAAI,CAACK,EAAE,CACrB,GAAI,CAACE,GAAS,AAAiB,iBAAVA,EAAoB,SAEzC,IAAME,EAA4B,UAAtB,OAAOD,EAAEE,QAAQ,CAAgBF,EAAEE,QAAQ,CAAG,KAC1D,GAAI,CAACD,EAAK,SAGV,IAAME,EAAMC,OAAOC,IAAI,CAACJ,EAAK,UACvBpB,EAAyB,UAAlB,OAAOmB,EAAEnB,IAAI,CANhBkB,AAOJC,EAAEnB,IAAI,CACqB,UAA3B,OAAOmB,EAAE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()=>require("next/dist/compiled/next-server/app-page-turbo.runtime.prod.js"))},556704,(e,t,r)=>{t.exports=e.x("next/dist/server/app-render/work-async-storage.external.js",()=>require("next/dist/server/app-render/work-async-storage.external.js"))},832319,(e,t,r)=>{t.exports=e.x("next/dist/server/app-render/work-unit-async-storage.external.js",()=>require("next/dist/server/app-render/work-unit-async-storage.external.js"))},324725,(e,t,r)=>{t.exports=e.x("next/dist/server/app-render/after-task-async-storage.external.js",()=>require("next/dist/server/app-render/after-task-async-storage.external.js"))},193695,(e,t,r)=>{t.exports=e.x("next/dist/shared/lib/no-fallback-error.external.js",()=>require("next/dist/shared/lib/no-fallback-error.external.js"))},666680,(e,t,r)=>{t.exports=e.x("node:crypto",()=>require("node:crypto"))},750227,(e,t,r)=>{t.exports=e.x("node:path",()=>require("node:path"))},814747,(e,t,r)=>{t.exports=e.x("path",()=>require("path"))},59639,(e,t,r)=>{t.exports=e.x("node:process",()=>require("node:process"))},971312,e=>{"use strict";e.i(484032),e.s([])},128930,e=>{"use strict";var t=e.i(747909),r=e.i(174017),a=e.i(996250),n=e.i(759756),s=e.i(561916),o=e.i(174677),i=e.i(869741),l=e.i(316795),d=e.i(487718),u=e.i(995169),p=e.i(47587),c=e.i(666012),h=e.i(570101),v=e.i(626937),x=e.i(10372),R=e.i(193695);e.i(52474);var f=e.i(600220),g=e.i(469719),m=e.i(456315),w=e.i(803028),y=e.i(777987);e.i(971312);var C=e.i(484032);let E=g.z.object({id:g.z.string().min(1)}),A=(0,m.defineRoute)({auth:"admin",params:E,handler:async({req:e,params:t})=>{let r=decodeURIComponent(t.id),a=(0,C.getMcpServer)(r);if(e.headers.get("accept")?.includes("text/event-stream")){var n;return n=a.id,new Response(new ReadableStream({async start(e){try{await (0,y.runMcpCheck)(n,t=>{try{e.enqueue(b.encode(`event: ${t.type}
2
- data: ${JSON.stringify(t)}
3
-
4
- `))}catch{}})}finally{try{e.close()}catch{}}}}),{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}})}let s=await (0,y.checkMcpServer)(a.id);if(!s)throw(0,w.notFound)("MCP server not found");return s}}),b=new TextEncoder;e.s(["POST",0,A],415827);var k=e.i(415827);let q=new t.AppRouteRouteModule({definition:{kind:r.RouteKind.APP_ROUTE,page:"/api/mcp/servers/[id]/check/route",pathname:"/api/mcp/servers/[id]/check",filename:"route",bundlePath:""},distDir:".next",relativeProjectDir:"",resolvedPagePath:"[project]/app/api/mcp/servers/[id]/check/route.ts",nextConfigOutput:"",userland:k,...{}}),{workAsyncStorage:T,workUnitAsyncStorage:P,serverHooks:S}=q;async function N(e,t,a){a.requestMeta&&(0,n.setRequestMeta)(e,a.requestMeta),q.isDev&&(0,n.addRequestMeta)(e,"devRequestTimingInternalsEnd",process.hrtime.bigint());let g="/api/mcp/servers/[id]/check/route";g=g.replace(/\/index$/,"")||"/";let m=await q.prepare(e,t,{srcPage:g,multiZoneDraftMode:!1});if(!m)return t.statusCode=400,t.end("Bad Request"),null==a.waitUntil||a.waitUntil.call(a,Promise.resolve()),null;let{buildId:w,deploymentId:y,params:C,nextConfig:E,parsedUrl:A,isDraftMode:b,prerenderManifest:k,routerServerContext:T,isOnDemandRevalidate:P,revalidateOnlyGenerated:S,resolvedPathname:N,clientReferenceManifest:O,serverActionsManifest:_}=m,M=(0,i.normalizeAppPath)(g),j=!!(k.dynamicRoutes[M]||k.routes[N]),H=async()=>((null==T?void 0:T.render404)?await T.render404(e,t,A,!1):t.end("This page could not be found"),null);if(j&&!b){let e=!!k.routes[N],t=k.dynamicRoutes[M];if(t&&!1===t.fallback&&!e){if(E.adapterPath)return await H();throw new R.NoFallbackError}}let I=null;!j||q.isDev||b||(I="/index"===(I=N)?"/":I);let U=!0===q.isDev||!j,D=j&&!U;_&&O&&(0,o.setManifestsSingleton)({page:g,clientReferenceManifest:O,serverActionsManifest:_});let $=e.method||"GET",F=(0,s.getTracer)(),K=F.getActiveScopeSpan(),B=!!(null==T?void 0:T.isWrappedByNextServer),L=!!(0,n.getRequestMeta)(e,"minimalMode"),X=(0,n.getRequestMeta)(e,"incrementalCache")||await q.getIncrementalCache(e,E,k,L);null==X||X.resetRequestCache(),globalThis.__incrementalCache=X;let z={params:C,previewProps:k.preview,renderOpts:{experimental:{authInterrupts:!!E.experimental.authInterrupts},cacheComponents:!!E.cacheComponents,supportsDynamicResponse:U,incrementalCache:X,cacheLifeProfiles:E.cacheLife,waitUntil:a.waitUntil,onClose:e=>{t.on("close",e)},onAfterTaskError:void 0,onInstrumentationRequestError:(t,r,a,n)=>q.onRequestError(e,t,a,n,T)},sharedContext:{buildId:w,deploymentId:y}},G=new l.NodeNextRequest(e),V=new l.NodeNextResponse(t),W=d.NextRequestAdapter.fromNodeNextRequest(G,(0,d.signalFromNodeResponse)(t));try{let n,o=async e=>q.handle(W,z).finally(()=>{if(!e)return;e.setAttributes({"http.status_code":t.statusCode,"next.rsc":!1});let r=F.getRootSpanAttributes();if(!r)return;if(r.get("next.span_type")!==u.BaseServerSpan.handleRequest)return void console.warn(`Unexpected root span type '${r.get("next.span_type")}'. Please report this Next.js issue https://github.com/vercel/next.js`);let a=r.get("next.route");if(a){let t=`${$} ${a}`;e.setAttributes({"next.route":a,"http.route":a,"next.span_name":t}),e.updateName(t),n&&n!==e&&(n.setAttribute("http.route",a),n.updateName(t))}else e.updateName(`${$} ${g}`)}),i=async n=>{var s,i;let l=async({previousCacheEntry:r})=>{try{if(!L&&P&&S&&!r)return t.statusCode=404,t.setHeader("x-nextjs-cache","REVALIDATED"),t.end("This page could not be found"),null;let s=await o(n);e.fetchMetrics=z.renderOpts.fetchMetrics;let i=z.renderOpts.pendingWaitUntil;i&&a.waitUntil&&(a.waitUntil(i),i=void 0);let l=z.renderOpts.collectedTags;if(!j)return await (0,c.sendResponse)(G,V,s,z.renderOpts.pendingWaitUntil),null;{let e=await s.blob(),t=(0,h.toNodeOutgoingHttpHeaders)(s.headers);l&&(t[x.NEXT_CACHE_TAGS_HEADER]=l),!t["content-type"]&&e.type&&(t["content-type"]=e.type);let r=void 0!==z.renderOpts.collectedRevalidate&&!(z.renderOpts.collectedRevalidate>=x.INFINITE_CACHE)&&z.renderOpts.collectedRevalidate,a=void 0===z.renderOpts.collectedExpire||z.renderOpts.collectedExpire>=x.INFINITE_CACHE?void 0:z.renderOpts.collectedExpire;return{value:{kind:f.CachedRouteKind.APP_ROUTE,status:s.status,body:Buffer.from(await e.arrayBuffer()),headers:t},cacheControl:{revalidate:r,expire:a}}}}catch(t){throw(null==r?void 0:r.isStale)&&await q.onRequestError(e,t,{routerKind:"App Router",routePath:g,routeType:"route",revalidateReason:(0,p.getRevalidateReason)({isStaticGeneration:D,isOnDemandRevalidate:P})},!1,T),t}},d=await q.handleResponse({req:e,nextConfig:E,cacheKey:I,routeKind:r.RouteKind.APP_ROUTE,isFallback:!1,prerenderManifest:k,isRoutePPREnabled:!1,isOnDemandRevalidate:P,revalidateOnlyGenerated:S,responseGenerator:l,waitUntil:a.waitUntil,isMinimalMode:L});if(!j)return null;if((null==d||null==(s=d.value)?void 0:s.kind)!==f.CachedRouteKind.APP_ROUTE)throw Object.defineProperty(Error(`Invariant: app-route received invalid cache entry ${null==d||null==(i=d.value)?void 0:i.kind}`),"__NEXT_ERROR_CODE",{value:"E701",enumerable:!1,configurable:!0});L||t.setHeader("x-nextjs-cache",P?"REVALIDATED":d.isMiss?"MISS":d.isStale?"STALE":"HIT"),b&&t.setHeader("Cache-Control","private, no-cache, no-store, max-age=0, must-revalidate");let u=(0,h.fromNodeOutgoingHttpHeaders)(d.value.headers);return L&&j||u.delete(x.NEXT_CACHE_TAGS_HEADER),!d.cacheControl||t.getHeader("Cache-Control")||u.get("Cache-Control")||u.set("Cache-Control",(0,v.getCacheControlHeader)(d.cacheControl)),await (0,c.sendResponse)(G,V,new Response(d.value.body,{headers:u,status:d.value.status||200})),null};B&&K?await i(K):(n=F.getActiveScopeSpan(),await F.withPropagatedContext(e.headers,()=>F.trace(u.BaseServerSpan.handleRequest,{spanName:`${$} ${g}`,kind:s.SpanKind.SERVER,attributes:{"http.method":$,"http.target":e.url}},i),void 0,!B))}catch(t){if(t instanceof R.NoFallbackError||await q.onRequestError(e,t,{routerKind:"App Router",routePath:M,routeType:"route",revalidateReason:(0,p.getRevalidateReason)({isStaticGeneration:D,isOnDemandRevalidate:P})},!1,T),j)throw t;return await (0,c.sendResponse)(G,V,new Response(null,{status:500})),null}}e.s(["handler",0,N,"patchFetch",0,function(){return(0,a.patchFetch)({workAsyncStorage:T,workUnitAsyncStorage:P})},"routeModule",0,q,"serverHooks",0,S,"workAsyncStorage",0,T,"workUnitAsyncStorage",0,P],128930)},70729,e=>{e.v(e=>Promise.resolve().then(()=>e(666680)))}];
5
-
6
- //# sourceMappingURL=%5Broot-of-the-server%5D__0g3mnim._.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../../lib/server/mcp/index.ts","../../../node_modules/next/dist/esm/build/templates/app-route.js","../../../app/api/mcp/servers/%5Bid%5D/check/route.ts"],"sourcesContent":["export * from \"./service\";\n","import { AppRouteRouteModule } from \"next/dist/esm/server/route-modules/app-route/module.compiled\";\nimport { RouteKind } from \"next/dist/esm/server/route-kind\";\nimport { patchFetch as _patchFetch } from \"next/dist/esm/server/lib/patch-fetch\";\nimport { addRequestMeta, getRequestMeta, setRequestMeta } from \"next/dist/esm/server/request-meta\";\nimport { getTracer, SpanKind } from \"next/dist/esm/server/lib/trace/tracer\";\nimport { setManifestsSingleton } from \"next/dist/esm/server/app-render/manifests-singleton\";\nimport { normalizeAppPath } from \"next/dist/esm/shared/lib/router/utils/app-paths\";\nimport { NodeNextRequest, NodeNextResponse } from \"next/dist/esm/server/base-http/node\";\nimport { NextRequestAdapter, signalFromNodeResponse } from \"next/dist/esm/server/web/spec-extension/adapters/next-request\";\nimport { BaseServerSpan } from \"next/dist/esm/server/lib/trace/constants\";\nimport { getRevalidateReason } from \"next/dist/esm/server/instrumentation/utils\";\nimport { sendResponse } from \"next/dist/esm/server/send-response\";\nimport { fromNodeOutgoingHttpHeaders, toNodeOutgoingHttpHeaders } from \"next/dist/esm/server/web/utils\";\nimport { getCacheControlHeader } from \"next/dist/esm/server/lib/cache-control\";\nimport { INFINITE_CACHE, NEXT_CACHE_TAGS_HEADER } from \"next/dist/esm/lib/constants\";\nimport { NoFallbackError } from \"next/dist/esm/shared/lib/no-fallback-error.external\";\nimport { CachedRouteKind } from \"next/dist/esm/server/response-cache\";\nimport * as userland from \"INNER_APP_ROUTE\";\n// We inject the nextConfigOutput here so that we can use them in the route\n// module.\nconst nextConfigOutput = \"\"\nconst routeModule = new AppRouteRouteModule({\n definition: {\n kind: RouteKind.APP_ROUTE,\n page: \"/api/mcp/servers/[id]/check/route\",\n pathname: \"/api/mcp/servers/[id]/check\",\n filename: \"route\",\n bundlePath: \"\"\n },\n distDir: process.env.__NEXT_RELATIVE_DIST_DIR || '',\n relativeProjectDir: process.env.__NEXT_RELATIVE_PROJECT_DIR || '',\n resolvedPagePath: \"[project]/app/api/mcp/servers/[id]/check/route.ts\",\n nextConfigOutput,\n // The static import is used for initialization (methods, dynamic, etc.).\n userland: userland,\n // In Turbopack dev mode, also provide a getter that calls require() on every\n // request. This re-reads from devModuleCache so HMR updates are picked up,\n // and the async wrapper unwraps async-module Promises (ESM-only\n // serverExternalPackages) automatically.\n ...process.env.TURBOPACK && process.env.__NEXT_DEV_SERVER ? {\n getUserland: ()=>import(\"INNER_APP_ROUTE\")\n } : {}\n});\n// Pull out the exports that we need to expose from the module. This should\n// be eliminated when we've moved the other routes to the new format. These\n// are used to hook into the route.\nconst { workAsyncStorage, workUnitAsyncStorage, serverHooks } = routeModule;\nfunction patchFetch() {\n return _patchFetch({\n workAsyncStorage,\n workUnitAsyncStorage\n });\n}\nexport { routeModule, workAsyncStorage, workUnitAsyncStorage, serverHooks, patchFetch, };\nexport async function handler(req, res, ctx) {\n if (ctx.requestMeta) {\n setRequestMeta(req, ctx.requestMeta);\n }\n if (routeModule.isDev) {\n addRequestMeta(req, 'devRequestTimingInternalsEnd', process.hrtime.bigint());\n }\n let srcPage = \"/api/mcp/servers/[id]/check/route\";\n // turbopack doesn't normalize `/index` in the page name\n // so we need to to process dynamic routes properly\n // TODO: fix turbopack providing differing value from webpack\n if (process.env.TURBOPACK) {\n srcPage = srcPage.replace(/\\/index$/, '') || '/';\n } else if (srcPage === '/index') {\n // we always normalize /index specifically\n srcPage = '/';\n }\n const multiZoneDraftMode = process.env.__NEXT_MULTI_ZONE_DRAFT_MODE;\n const prepareResult = await routeModule.prepare(req, res, {\n srcPage,\n multiZoneDraftMode\n });\n if (!prepareResult) {\n res.statusCode = 400;\n res.end('Bad Request');\n ctx.waitUntil == null ? void 0 : ctx.waitUntil.call(ctx, Promise.resolve());\n return null;\n }\n const { buildId, deploymentId, params, nextConfig, parsedUrl, isDraftMode, prerenderManifest, routerServerContext, isOnDemandRevalidate, revalidateOnlyGenerated, resolvedPathname, clientReferenceManifest, serverActionsManifest } = prepareResult;\n const normalizedSrcPage = normalizeAppPath(srcPage);\n let isIsr = Boolean(prerenderManifest.dynamicRoutes[normalizedSrcPage] || prerenderManifest.routes[resolvedPathname]);\n const render404 = async ()=>{\n // TODO: should route-module itself handle rendering the 404\n if (routerServerContext == null ? void 0 : routerServerContext.render404) {\n await routerServerContext.render404(req, res, parsedUrl, false);\n } else {\n res.end('This page could not be found');\n }\n return null;\n };\n if (isIsr && !isDraftMode) {\n const isPrerendered = Boolean(prerenderManifest.routes[resolvedPathname]);\n const prerenderInfo = prerenderManifest.dynamicRoutes[normalizedSrcPage];\n if (prerenderInfo) {\n if (prerenderInfo.fallback === false && !isPrerendered) {\n if (nextConfig.adapterPath) {\n return await render404();\n }\n throw new NoFallbackError();\n }\n }\n }\n let cacheKey = null;\n if (isIsr && !routeModule.isDev && !isDraftMode) {\n cacheKey = resolvedPathname;\n // ensure /index and / is normalized to one key\n cacheKey = cacheKey === '/index' ? '/' : cacheKey;\n }\n const supportsDynamicResponse = // If we're in development, we always support dynamic HTML\n routeModule.isDev === true || // If this is not SSG or does not have static paths, then it supports\n // dynamic HTML.\n !isIsr;\n // This is a revalidation request if the request is for a static\n // page and it is not being resumed from a postponed render and\n // it is not a dynamic RSC request then it is a revalidation\n // request.\n const isStaticGeneration = isIsr && !supportsDynamicResponse;\n // Before rendering (which initializes component tree modules), we have to\n // set the reference manifests to our global store so Server Action's\n // encryption util can access to them at the top level of the page module.\n if (serverActionsManifest && clientReferenceManifest) {\n setManifestsSingleton({\n page: srcPage,\n clientReferenceManifest,\n serverActionsManifest\n });\n }\n const method = req.method || 'GET';\n const tracer = getTracer();\n const activeSpan = tracer.getActiveScopeSpan();\n const isWrappedByNextServer = Boolean(routerServerContext == null ? void 0 : routerServerContext.isWrappedByNextServer);\n const isMinimalMode = Boolean(getRequestMeta(req, 'minimalMode'));\n const incrementalCache = getRequestMeta(req, 'incrementalCache') || await routeModule.getIncrementalCache(req, nextConfig, prerenderManifest, isMinimalMode);\n incrementalCache == null ? void 0 : incrementalCache.resetRequestCache();\n globalThis.__incrementalCache = incrementalCache;\n const context = {\n params,\n previewProps: prerenderManifest.preview,\n renderOpts: {\n experimental: {\n authInterrupts: Boolean(nextConfig.experimental.authInterrupts)\n },\n cacheComponents: Boolean(nextConfig.cacheComponents),\n supportsDynamicResponse,\n incrementalCache,\n cacheLifeProfiles: nextConfig.cacheLife,\n waitUntil: ctx.waitUntil,\n onClose: (cb)=>{\n res.on('close', cb);\n },\n onAfterTaskError: undefined,\n onInstrumentationRequestError: (error, _request, errorContext, silenceLog)=>routeModule.onRequestError(req, error, errorContext, silenceLog, routerServerContext)\n },\n sharedContext: {\n buildId,\n deploymentId\n }\n };\n const nodeNextReq = new NodeNextRequest(req);\n const nodeNextRes = new NodeNextResponse(res);\n const nextReq = NextRequestAdapter.fromNodeNextRequest(nodeNextReq, signalFromNodeResponse(res));\n try {\n let parentSpan;\n const invokeRouteModule = async (span)=>{\n return routeModule.handle(nextReq, context).finally(()=>{\n if (!span) return;\n span.setAttributes({\n 'http.status_code': res.statusCode,\n 'next.rsc': false\n });\n const rootSpanAttributes = tracer.getRootSpanAttributes();\n // We were unable to get attributes, probably OTEL is not enabled\n if (!rootSpanAttributes) {\n return;\n }\n if (rootSpanAttributes.get('next.span_type') !== BaseServerSpan.handleRequest) {\n console.warn(`Unexpected root span type '${rootSpanAttributes.get('next.span_type')}'. Please report this Next.js issue https://github.com/vercel/next.js`);\n return;\n }\n const route = rootSpanAttributes.get('next.route');\n if (route) {\n const name = `${method} ${route}`;\n span.setAttributes({\n 'next.route': route,\n 'http.route': route,\n 'next.span_name': name\n });\n span.updateName(name);\n // Propagate http.route to the parent span if one exists (e.g.\n // a platform-created HTTP span in adapter deployments).\n if (parentSpan && parentSpan !== span) {\n parentSpan.setAttribute('http.route', route);\n parentSpan.updateName(name);\n }\n } else {\n span.updateName(`${method} ${srcPage}`);\n }\n });\n };\n const handleResponse = async (currentSpan)=>{\n var _cacheEntry_value;\n const responseGenerator = async ({ previousCacheEntry })=>{\n try {\n if (!isMinimalMode && isOnDemandRevalidate && revalidateOnlyGenerated && !previousCacheEntry) {\n res.statusCode = 404;\n // on-demand revalidate always sets this header\n res.setHeader('x-nextjs-cache', 'REVALIDATED');\n res.end('This page could not be found');\n return null;\n }\n const response = await invokeRouteModule(currentSpan);\n req.fetchMetrics = context.renderOpts.fetchMetrics;\n let pendingWaitUntil = context.renderOpts.pendingWaitUntil;\n // Attempt using provided waitUntil if available\n // if it's not we fallback to sendResponse's handling\n if (pendingWaitUntil) {\n if (ctx.waitUntil) {\n ctx.waitUntil(pendingWaitUntil);\n pendingWaitUntil = undefined;\n }\n }\n const cacheTags = context.renderOpts.collectedTags;\n // If the request is for a static response, we can cache it so long\n // as it's not edge.\n if (isIsr) {\n const blob = await response.blob();\n // Copy the headers from the response.\n const headers = toNodeOutgoingHttpHeaders(response.headers);\n if (cacheTags) {\n headers[NEXT_CACHE_TAGS_HEADER] = cacheTags;\n }\n if (!headers['content-type'] && blob.type) {\n headers['content-type'] = blob.type;\n }\n const revalidate = typeof context.renderOpts.collectedRevalidate === 'undefined' || context.renderOpts.collectedRevalidate >= INFINITE_CACHE ? false : context.renderOpts.collectedRevalidate;\n const expire = typeof context.renderOpts.collectedExpire === 'undefined' || context.renderOpts.collectedExpire >= INFINITE_CACHE ? undefined : context.renderOpts.collectedExpire;\n // Create the cache entry for the response.\n const cacheEntry = {\n value: {\n kind: CachedRouteKind.APP_ROUTE,\n status: response.status,\n body: Buffer.from(await blob.arrayBuffer()),\n headers\n },\n cacheControl: {\n revalidate,\n expire\n }\n };\n return cacheEntry;\n } else {\n // send response without caching if not ISR\n await sendResponse(nodeNextReq, nodeNextRes, response, context.renderOpts.pendingWaitUntil);\n return null;\n }\n } catch (err) {\n // if this is a background revalidate we need to report\n // the request error here as it won't be bubbled\n if (previousCacheEntry == null ? void 0 : previousCacheEntry.isStale) {\n const silenceLog = false;\n await routeModule.onRequestError(req, err, {\n routerKind: 'App Router',\n routePath: srcPage,\n routeType: 'route',\n revalidateReason: getRevalidateReason({\n isStaticGeneration,\n isOnDemandRevalidate\n })\n }, silenceLog, routerServerContext);\n }\n throw err;\n }\n };\n const cacheEntry = await routeModule.handleResponse({\n req,\n nextConfig,\n cacheKey,\n routeKind: RouteKind.APP_ROUTE,\n isFallback: false,\n prerenderManifest,\n isRoutePPREnabled: false,\n isOnDemandRevalidate,\n revalidateOnlyGenerated,\n responseGenerator,\n waitUntil: ctx.waitUntil,\n isMinimalMode\n });\n // we don't create a cacheEntry for ISR\n if (!isIsr) {\n return null;\n }\n if ((cacheEntry == null ? void 0 : (_cacheEntry_value = cacheEntry.value) == null ? void 0 : _cacheEntry_value.kind) !== CachedRouteKind.APP_ROUTE) {\n var _cacheEntry_value1;\n throw Object.defineProperty(new Error(`Invariant: app-route received invalid cache entry ${cacheEntry == null ? void 0 : (_cacheEntry_value1 = cacheEntry.value) == null ? void 0 : _cacheEntry_value1.kind}`), \"__NEXT_ERROR_CODE\", {\n value: \"E701\",\n enumerable: false,\n configurable: true\n });\n }\n if (!isMinimalMode) {\n res.setHeader('x-nextjs-cache', isOnDemandRevalidate ? 'REVALIDATED' : cacheEntry.isMiss ? 'MISS' : cacheEntry.isStale ? 'STALE' : 'HIT');\n }\n // Draft mode should never be cached\n if (isDraftMode) {\n res.setHeader('Cache-Control', 'private, no-cache, no-store, max-age=0, must-revalidate');\n }\n const headers = fromNodeOutgoingHttpHeaders(cacheEntry.value.headers);\n if (!(isMinimalMode && isIsr)) {\n headers.delete(NEXT_CACHE_TAGS_HEADER);\n }\n // If cache control is already set on the response we don't\n // override it to allow users to customize it via next.config\n if (cacheEntry.cacheControl && !res.getHeader('Cache-Control') && !headers.get('Cache-Control')) {\n headers.set('Cache-Control', getCacheControlHeader(cacheEntry.cacheControl));\n }\n await sendResponse(nodeNextReq, nodeNextRes, // @ts-expect-error - Argument of type 'Buffer<ArrayBufferLike>' is not assignable to parameter of type 'BodyInit | null | undefined'.\n new Response(cacheEntry.value.body, {\n headers,\n status: cacheEntry.value.status || 200\n }));\n return null;\n };\n // TODO: activeSpan code path is for when wrapped by\n // next-server can be removed when this is no longer used\n if (isWrappedByNextServer && activeSpan) {\n await handleResponse(activeSpan);\n } else {\n parentSpan = tracer.getActiveScopeSpan();\n await tracer.withPropagatedContext(req.headers, ()=>tracer.trace(BaseServerSpan.handleRequest, {\n spanName: `${method} ${srcPage}`,\n kind: SpanKind.SERVER,\n attributes: {\n 'http.method': method,\n 'http.target': req.url\n }\n }, handleResponse), undefined, !isWrappedByNextServer);\n }\n } catch (err) {\n if (!(err instanceof NoFallbackError)) {\n const silenceLog = false;\n await routeModule.onRequestError(req, err, {\n routerKind: 'App Router',\n routePath: normalizedSrcPage,\n routeType: 'route',\n revalidateReason: getRevalidateReason({\n isStaticGeneration,\n isOnDemandRevalidate\n })\n }, silenceLog, routerServerContext);\n }\n // rethrow so that we can handle serving error page\n // If this is during static generation, throw the error again.\n if (isIsr) throw err;\n // Otherwise, send a 500 response.\n await sendResponse(nodeNextReq, nodeNextRes, new Response(null, {\n status: 500\n }));\n return null;\n }\n}\n\n//# sourceMappingURL=app-route.js.map\n","import \"server-only\";\nimport { z } from \"zod\";\nimport { defineRoute } from \"@/lib/server/route\";\nimport { notFound } from \"@/lib/server/response\";\nimport { checkMcpServer, runMcpCheck, type McpCheckEvent } from \"@/lib/server/mcp/checks\";\nimport { getMcpServer } from \"@/lib/server/mcp\";\n\nconst paramsSchema = z.object({ id: z.string().min(1) });\n\nexport const POST = defineRoute({\n auth: \"admin\",\n params: paramsSchema,\n handler: async ({ req, params }) => {\n const id = decodeURIComponent(params.id);\n // Resolve name → id so admins can hit the endpoint with either.\n const server = getMcpServer(id);\n\n // SSE branch — admin's check UI streams stderr in real time so\n // slow `npx`/`uvx` installs aren't silent black boxes. Plain\n // JSON branch kept for scripts and back-compat.\n if (req.headers.get(\"accept\")?.includes(\"text/event-stream\")) {\n return streamCheck(server.id);\n }\n\n const updated = await checkMcpServer(server.id);\n if (!updated) throw notFound(\"MCP server not found\");\n return updated;\n },\n});\n\nconst SSE_ENCODER = new TextEncoder();\n\nfunction streamCheck(serverId: string): Response {\n const stream = new ReadableStream<Uint8Array>({\n async start(controller) {\n const send = (ev: McpCheckEvent) => {\n try {\n controller.enqueue(\n SSE_ENCODER.encode(`event: ${ev.type}\\ndata: ${JSON.stringify(ev)}\\n\\n`),\n );\n } catch { /* stream closed */ }\n };\n try {\n await runMcpCheck(serverId, send);\n } finally {\n try { controller.close(); } catch { /* already closed */ }\n }\n },\n });\n\n return new Response(stream, {\n status: 200,\n headers: {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache, no-transform\",\n \"Connection\": \"keep-alive\",\n \"X-Accel-Buffering\": \"no\",\n },\n });\n}\n"],"names":["id","paramsSchema","object","string","min","POST","auth","params","handler","req","decodeURIComponent","server","headers","get","includes","streamCheck","updated","SSE_ENCODER","TextEncoder","serverId","stream","ReadableStream","start","controller","send","ev","enqueue","encode","type","JSON","stringify","close","Response","status"],"mappings":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,MAAM,EAAe,EADgB,EAGrC,EAAa,EAAO,kBAAkB,GACtC,MAAM,EAAO,qBAAqB,CAAC,EAAI,OAAO,CAAE,IAAI,EAAO,KAAK,CAAC,EAAA,cAAc,CAAC,aAAa,CAAE,CACvF,SAAU,CAAA,EAAG,EAAO,CAAC,EAAE,EAAA,CAAS,CAChC,KAAM,EAAA,QAAQ,CAAC,MAAM,CACrB,WAAY,CACR,cAAe,EACf,cAAe,EAAI,GAAG,AAC1B,CACJ,EAAG,GAAiB,OAAW,CAAC,GAE5C,CAAE,MAAO,EAAK,CAeV,GAdM,aAAe,EAAA,eAAe,EAEhC,CAFmC,KAE7B,EAAY,cAAc,CAAC,EAAK,EAAK,CACvC,WAAY,aACZ,UAAW,EACX,UAAW,QACX,iBAAkB,CAAA,EAAA,EAAA,mBAAA,AAAmB,EAAC,oBAClC,uBACA,CACJ,EACJ,GAAG,AATgB,EASJ,GAIf,EAAO,MAAM,EAKjB,OAHA,MAAM,CAAA,EAAA,EAAA,YAAA,AAAY,EAAC,EAAa,EAAa,IAAI,SAAS,KAAM,CAC5D,OAAQ,GACZ,IACO,IACX,CACJ,mCA5TA,SAAS,EACL,MAAO,CAAA,EAAA,EAAA,UAAA,AAAW,EAAC,kBACf,uBACA,CACJ,EACJ","ignoreList":[1]}
@@ -1,3 +0,0 @@
1
- module.exports=[918622,(e,t,r)=>{t.exports=e.x("next/dist/compiled/next-server/app-page-turbo.runtime.prod.js",()=>require("next/dist/compiled/next-server/app-page-turbo.runtime.prod.js"))},556704,(e,t,r)=>{t.exports=e.x("next/dist/server/app-render/work-async-storage.external.js",()=>require("next/dist/server/app-render/work-async-storage.external.js"))},832319,(e,t,r)=>{t.exports=e.x("next/dist/server/app-render/work-unit-async-storage.external.js",()=>require("next/dist/server/app-render/work-unit-async-storage.external.js"))},324725,(e,t,r)=>{t.exports=e.x("next/dist/server/app-render/after-task-async-storage.external.js",()=>require("next/dist/server/app-render/after-task-async-storage.external.js"))},193695,(e,t,r)=>{t.exports=e.x("next/dist/shared/lib/no-fallback-error.external.js",()=>require("next/dist/shared/lib/no-fallback-error.external.js"))},750227,(e,t,r)=>{t.exports=e.x("node:path",()=>require("node:path"))},666680,(e,t,r)=>{t.exports=e.x("node:crypto",()=>require("node:crypto"))},879781,e=>{"use strict";var t=e.i(747909),r=e.i(174017),a=e.i(996250),n=e.i(759756),s=e.i(561916),i=e.i(174677),o=e.i(869741),l=e.i(316795),u=e.i(487718),d=e.i(995169),p=e.i(47587),c=e.i(666012),h=e.i(570101),m=e.i(626937),f=e.i(10372),x=e.i(193695);e.i(52474);var v=e.i(600220),R=e.i(456315),g=e.i(469719);let _=g.z.object({default_model:g.z.string(),default_summary_model:g.z.string(),default_system_prompt:g.z.string(),default_history_limit:g.z.number().int().positive(),user_name:g.z.string(),user_avatar:g.z.string(),theme_id:g.z.string(),theme_scheme:g.z.enum(["light","dark","system"]),chat_render_mode:g.z.enum(["instant","stream","typewriter"]),typewriter_cps:g.z.number().int().min(20).max(400),chat_bubble_style:g.z.enum(["plain","bubble","minimal"])}),y=_.partial(),w={default_model:"",default_summary_model:"",default_system_prompt:"You are a helpful assistant.",default_history_limit:10,user_name:"",user_avatar:"👤",theme_id:"default",theme_scheme:"system",chat_render_mode:"stream",typewriter_cps:80,chat_bubble_style:"plain"};var b=e.i(875225),E=e.i(846344),C=e.i(401632);function A(e){let t=E.db.select({preferences:C.userPreferences.preferences}).from(C.userPreferences).where((0,b.eq)(C.userPreferences.userId,e)).get(),r=t?.preferences??{},a={...w,...r};return _.parse(a)}let P=(0,R.defineRoute)({handler:({user:e})=>A(e.id)}),T=(0,R.defineRoute)({body:y,handler:({user:e,body:t})=>{var r;let a,n;return r=e.id,a={...A(r),...t},n=new Date().toISOString(),E.db.insert(C.userPreferences).values({userId:r,preferences:a,updatedAt:n}).onConflictDoUpdate({target:C.userPreferences.userId,set:{preferences:a,updatedAt:n}}).run(),a}});e.s(["GET",0,P,"PATCH",0,T],98421);var q=e.i(98421);let N=new t.AppRouteRouteModule({definition:{kind:r.RouteKind.APP_ROUTE,page:"/api/users/me/preferences/route",pathname:"/api/users/me/preferences",filename:"route",bundlePath:""},distDir:".next",relativeProjectDir:"",resolvedPagePath:"[project]/app/api/users/me/preferences/route.ts",nextConfigOutput:"",userland:q,...{}}),{workAsyncStorage:S,workUnitAsyncStorage:k,serverHooks:O}=N;async function I(e,t,a){a.requestMeta&&(0,n.setRequestMeta)(e,a.requestMeta),N.isDev&&(0,n.addRequestMeta)(e,"devRequestTimingInternalsEnd",process.hrtime.bigint());let R="/api/users/me/preferences/route";R=R.replace(/\/index$/,"")||"/";let g=await N.prepare(e,t,{srcPage:R,multiZoneDraftMode:!1});if(!g)return t.statusCode=400,t.end("Bad Request"),null==a.waitUntil||a.waitUntil.call(a,Promise.resolve()),null;let{buildId:_,deploymentId:y,params:w,nextConfig:b,parsedUrl:E,isDraftMode:C,prerenderManifest:A,routerServerContext:P,isOnDemandRevalidate:T,revalidateOnlyGenerated:q,resolvedPathname:S,clientReferenceManifest:k,serverActionsManifest:O}=g,I=(0,o.normalizeAppPath)(R),j=!!(A.dynamicRoutes[I]||A.routes[S]),H=async()=>((null==P?void 0:P.render404)?await P.render404(e,t,E,!1):t.end("This page could not be found"),null);if(j&&!C){let e=!!A.routes[S],t=A.dynamicRoutes[I];if(t&&!1===t.fallback&&!e){if(b.adapterPath)return await H();throw new x.NoFallbackError}}let U=null;!j||N.isDev||C||(U="/index"===(U=S)?"/":U);let D=!0===N.isDev||!j,M=j&&!D;O&&k&&(0,i.setManifestsSingleton)({page:R,clientReferenceManifest:k,serverActionsManifest:O});let z=e.method||"GET",$=(0,s.getTracer)(),F=$.getActiveScopeSpan(),K=!!(null==P?void 0:P.isWrappedByNextServer),B=!!(0,n.getRequestMeta)(e,"minimalMode"),L=(0,n.getRequestMeta)(e,"incrementalCache")||await N.getIncrementalCache(e,b,A,B);null==L||L.resetRequestCache(),globalThis.__incrementalCache=L;let G={params:w,previewProps:A.preview,renderOpts:{experimental:{authInterrupts:!!b.experimental.authInterrupts},cacheComponents:!!b.cacheComponents,supportsDynamicResponse:D,incrementalCache:L,cacheLifeProfiles:b.cacheLife,waitUntil:a.waitUntil,onClose:e=>{t.on("close",e)},onAfterTaskError:void 0,onInstrumentationRequestError:(t,r,a,n)=>N.onRequestError(e,t,a,n,P)},sharedContext:{buildId:_,deploymentId:y}},V=new l.NodeNextRequest(e),W=new l.NodeNextResponse(t),X=u.NextRequestAdapter.fromNodeNextRequest(V,(0,u.signalFromNodeResponse)(t));try{let n,i=async e=>N.handle(X,G).finally(()=>{if(!e)return;e.setAttributes({"http.status_code":t.statusCode,"next.rsc":!1});let r=$.getRootSpanAttributes();if(!r)return;if(r.get("next.span_type")!==d.BaseServerSpan.handleRequest)return void console.warn(`Unexpected root span type '${r.get("next.span_type")}'. Please report this Next.js issue https://github.com/vercel/next.js`);let a=r.get("next.route");if(a){let t=`${z} ${a}`;e.setAttributes({"next.route":a,"http.route":a,"next.span_name":t}),e.updateName(t),n&&n!==e&&(n.setAttribute("http.route",a),n.updateName(t))}else e.updateName(`${z} ${R}`)}),o=async n=>{var s,o;let l=async({previousCacheEntry:r})=>{try{if(!B&&T&&q&&!r)return t.statusCode=404,t.setHeader("x-nextjs-cache","REVALIDATED"),t.end("This page could not be found"),null;let s=await i(n);e.fetchMetrics=G.renderOpts.fetchMetrics;let o=G.renderOpts.pendingWaitUntil;o&&a.waitUntil&&(a.waitUntil(o),o=void 0);let l=G.renderOpts.collectedTags;if(!j)return await (0,c.sendResponse)(V,W,s,G.renderOpts.pendingWaitUntil),null;{let e=await s.blob(),t=(0,h.toNodeOutgoingHttpHeaders)(s.headers);l&&(t[f.NEXT_CACHE_TAGS_HEADER]=l),!t["content-type"]&&e.type&&(t["content-type"]=e.type);let r=void 0!==G.renderOpts.collectedRevalidate&&!(G.renderOpts.collectedRevalidate>=f.INFINITE_CACHE)&&G.renderOpts.collectedRevalidate,a=void 0===G.renderOpts.collectedExpire||G.renderOpts.collectedExpire>=f.INFINITE_CACHE?void 0:G.renderOpts.collectedExpire;return{value:{kind:v.CachedRouteKind.APP_ROUTE,status:s.status,body:Buffer.from(await e.arrayBuffer()),headers:t},cacheControl:{revalidate:r,expire:a}}}}catch(t){throw(null==r?void 0:r.isStale)&&await N.onRequestError(e,t,{routerKind:"App Router",routePath:R,routeType:"route",revalidateReason:(0,p.getRevalidateReason)({isStaticGeneration:M,isOnDemandRevalidate:T})},!1,P),t}},u=await N.handleResponse({req:e,nextConfig:b,cacheKey:U,routeKind:r.RouteKind.APP_ROUTE,isFallback:!1,prerenderManifest:A,isRoutePPREnabled:!1,isOnDemandRevalidate:T,revalidateOnlyGenerated:q,responseGenerator:l,waitUntil:a.waitUntil,isMinimalMode:B});if(!j)return null;if((null==u||null==(s=u.value)?void 0:s.kind)!==v.CachedRouteKind.APP_ROUTE)throw Object.defineProperty(Error(`Invariant: app-route received invalid cache entry ${null==u||null==(o=u.value)?void 0:o.kind}`),"__NEXT_ERROR_CODE",{value:"E701",enumerable:!1,configurable:!0});B||t.setHeader("x-nextjs-cache",T?"REVALIDATED":u.isMiss?"MISS":u.isStale?"STALE":"HIT"),C&&t.setHeader("Cache-Control","private, no-cache, no-store, max-age=0, must-revalidate");let d=(0,h.fromNodeOutgoingHttpHeaders)(u.value.headers);return B&&j||d.delete(f.NEXT_CACHE_TAGS_HEADER),!u.cacheControl||t.getHeader("Cache-Control")||d.get("Cache-Control")||d.set("Cache-Control",(0,m.getCacheControlHeader)(u.cacheControl)),await (0,c.sendResponse)(V,W,new Response(u.value.body,{headers:d,status:u.value.status||200})),null};K&&F?await o(F):(n=$.getActiveScopeSpan(),await $.withPropagatedContext(e.headers,()=>$.trace(d.BaseServerSpan.handleRequest,{spanName:`${z} ${R}`,kind:s.SpanKind.SERVER,attributes:{"http.method":z,"http.target":e.url}},o),void 0,!K))}catch(t){if(t instanceof x.NoFallbackError||await N.onRequestError(e,t,{routerKind:"App Router",routePath:I,routeType:"route",revalidateReason:(0,p.getRevalidateReason)({isStaticGeneration:M,isOnDemandRevalidate:T})},!1,P),j)throw t;return await (0,c.sendResponse)(V,W,new Response(null,{status:500})),null}}e.s(["handler",0,I,"patchFetch",0,function(){return(0,a.patchFetch)({workAsyncStorage:S,workUnitAsyncStorage:k})},"routeModule",0,N,"serverHooks",0,O,"workAsyncStorage",0,S,"workUnitAsyncStorage",0,k],879781)}];
2
-
3
- //# sourceMappingURL=%5Broot-of-the-server%5D__1gon00b._.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../../lib/schemas/preferences.ts","../../../node_modules/next/dist/esm/build/templates/app-route.js","../../../app/api/users/me/preferences/route.ts","../../../lib/server/preferences/service.ts"],"sourcesContent":["import { z } from \"zod\";\n\n/**\n * Cross-device user preferences — stored server-side and fetched per session.\n * Device-only UI preferences (sendOnEnter, showTimestamps, compactMode) live\n * in localStorage via lib/stores/device-settings-store.ts and are NOT here.\n */\n\nexport const userPreferencesDTOSchema = z.object({\n default_model: z.string(),\n default_summary_model: z.string(),\n\n default_system_prompt: z.string(),\n default_history_limit: z.number().int().positive(),\n\n user_name: z.string(),\n user_avatar: z.string(),\n\n // Appearance — drives lib/themes registry + next-themes scheme.\n theme_id: z.string(),\n theme_scheme: z.enum([\"light\", \"dark\", \"system\"]),\n\n // Chat rendering.\n chat_render_mode: z.enum([\"instant\", \"stream\", \"typewriter\"]),\n typewriter_cps: z.number().int().min(20).max(400),\n chat_bubble_style: z.enum([\"plain\", \"bubble\", \"minimal\"]),\n});\n\n/** All fields optional → PATCH semantics. Sent fields replace; unsent stay. */\nexport const userPreferencesUpdateSchema = userPreferencesDTOSchema.partial();\n\nexport const defaultUserPreferences: UserPreferencesDTO = {\n default_model: \"\",\n default_summary_model: \"\",\n default_system_prompt: \"You are a helpful assistant.\",\n default_history_limit: 10,\n user_name: \"\",\n user_avatar: \"👤\",\n theme_id: \"default\",\n theme_scheme: \"system\",\n chat_render_mode: \"stream\",\n typewriter_cps: 80,\n chat_bubble_style: \"plain\",\n};\n\nexport type UserPreferencesDTO = z.infer<typeof userPreferencesDTOSchema>;\nexport type UserPreferencesUpdateInput = z.infer<typeof userPreferencesUpdateSchema>;\n","import { AppRouteRouteModule } from \"next/dist/esm/server/route-modules/app-route/module.compiled\";\nimport { RouteKind } from \"next/dist/esm/server/route-kind\";\nimport { patchFetch as _patchFetch } from \"next/dist/esm/server/lib/patch-fetch\";\nimport { addRequestMeta, getRequestMeta, setRequestMeta } from \"next/dist/esm/server/request-meta\";\nimport { getTracer, SpanKind } from \"next/dist/esm/server/lib/trace/tracer\";\nimport { setManifestsSingleton } from \"next/dist/esm/server/app-render/manifests-singleton\";\nimport { normalizeAppPath } from \"next/dist/esm/shared/lib/router/utils/app-paths\";\nimport { NodeNextRequest, NodeNextResponse } from \"next/dist/esm/server/base-http/node\";\nimport { NextRequestAdapter, signalFromNodeResponse } from \"next/dist/esm/server/web/spec-extension/adapters/next-request\";\nimport { BaseServerSpan } from \"next/dist/esm/server/lib/trace/constants\";\nimport { getRevalidateReason } from \"next/dist/esm/server/instrumentation/utils\";\nimport { sendResponse } from \"next/dist/esm/server/send-response\";\nimport { fromNodeOutgoingHttpHeaders, toNodeOutgoingHttpHeaders } from \"next/dist/esm/server/web/utils\";\nimport { getCacheControlHeader } from \"next/dist/esm/server/lib/cache-control\";\nimport { INFINITE_CACHE, NEXT_CACHE_TAGS_HEADER } from \"next/dist/esm/lib/constants\";\nimport { NoFallbackError } from \"next/dist/esm/shared/lib/no-fallback-error.external\";\nimport { CachedRouteKind } from \"next/dist/esm/server/response-cache\";\nimport * as userland from \"INNER_APP_ROUTE\";\n// We inject the nextConfigOutput here so that we can use them in the route\n// module.\nconst nextConfigOutput = \"\"\nconst routeModule = new AppRouteRouteModule({\n definition: {\n kind: RouteKind.APP_ROUTE,\n page: \"/api/users/me/preferences/route\",\n pathname: \"/api/users/me/preferences\",\n filename: \"route\",\n bundlePath: \"\"\n },\n distDir: process.env.__NEXT_RELATIVE_DIST_DIR || '',\n relativeProjectDir: process.env.__NEXT_RELATIVE_PROJECT_DIR || '',\n resolvedPagePath: \"[project]/app/api/users/me/preferences/route.ts\",\n nextConfigOutput,\n // The static import is used for initialization (methods, dynamic, etc.).\n userland: userland,\n // In Turbopack dev mode, also provide a getter that calls require() on every\n // request. This re-reads from devModuleCache so HMR updates are picked up,\n // and the async wrapper unwraps async-module Promises (ESM-only\n // serverExternalPackages) automatically.\n ...process.env.TURBOPACK && process.env.__NEXT_DEV_SERVER ? {\n getUserland: ()=>import(\"INNER_APP_ROUTE\")\n } : {}\n});\n// Pull out the exports that we need to expose from the module. This should\n// be eliminated when we've moved the other routes to the new format. These\n// are used to hook into the route.\nconst { workAsyncStorage, workUnitAsyncStorage, serverHooks } = routeModule;\nfunction patchFetch() {\n return _patchFetch({\n workAsyncStorage,\n workUnitAsyncStorage\n });\n}\nexport { routeModule, workAsyncStorage, workUnitAsyncStorage, serverHooks, patchFetch, };\nexport async function handler(req, res, ctx) {\n if (ctx.requestMeta) {\n setRequestMeta(req, ctx.requestMeta);\n }\n if (routeModule.isDev) {\n addRequestMeta(req, 'devRequestTimingInternalsEnd', process.hrtime.bigint());\n }\n let srcPage = \"/api/users/me/preferences/route\";\n // turbopack doesn't normalize `/index` in the page name\n // so we need to to process dynamic routes properly\n // TODO: fix turbopack providing differing value from webpack\n if (process.env.TURBOPACK) {\n srcPage = srcPage.replace(/\\/index$/, '') || '/';\n } else if (srcPage === '/index') {\n // we always normalize /index specifically\n srcPage = '/';\n }\n const multiZoneDraftMode = process.env.__NEXT_MULTI_ZONE_DRAFT_MODE;\n const prepareResult = await routeModule.prepare(req, res, {\n srcPage,\n multiZoneDraftMode\n });\n if (!prepareResult) {\n res.statusCode = 400;\n res.end('Bad Request');\n ctx.waitUntil == null ? void 0 : ctx.waitUntil.call(ctx, Promise.resolve());\n return null;\n }\n const { buildId, deploymentId, params, nextConfig, parsedUrl, isDraftMode, prerenderManifest, routerServerContext, isOnDemandRevalidate, revalidateOnlyGenerated, resolvedPathname, clientReferenceManifest, serverActionsManifest } = prepareResult;\n const normalizedSrcPage = normalizeAppPath(srcPage);\n let isIsr = Boolean(prerenderManifest.dynamicRoutes[normalizedSrcPage] || prerenderManifest.routes[resolvedPathname]);\n const render404 = async ()=>{\n // TODO: should route-module itself handle rendering the 404\n if (routerServerContext == null ? void 0 : routerServerContext.render404) {\n await routerServerContext.render404(req, res, parsedUrl, false);\n } else {\n res.end('This page could not be found');\n }\n return null;\n };\n if (isIsr && !isDraftMode) {\n const isPrerendered = Boolean(prerenderManifest.routes[resolvedPathname]);\n const prerenderInfo = prerenderManifest.dynamicRoutes[normalizedSrcPage];\n if (prerenderInfo) {\n if (prerenderInfo.fallback === false && !isPrerendered) {\n if (nextConfig.adapterPath) {\n return await render404();\n }\n throw new NoFallbackError();\n }\n }\n }\n let cacheKey = null;\n if (isIsr && !routeModule.isDev && !isDraftMode) {\n cacheKey = resolvedPathname;\n // ensure /index and / is normalized to one key\n cacheKey = cacheKey === '/index' ? '/' : cacheKey;\n }\n const supportsDynamicResponse = // If we're in development, we always support dynamic HTML\n routeModule.isDev === true || // If this is not SSG or does not have static paths, then it supports\n // dynamic HTML.\n !isIsr;\n // This is a revalidation request if the request is for a static\n // page and it is not being resumed from a postponed render and\n // it is not a dynamic RSC request then it is a revalidation\n // request.\n const isStaticGeneration = isIsr && !supportsDynamicResponse;\n // Before rendering (which initializes component tree modules), we have to\n // set the reference manifests to our global store so Server Action's\n // encryption util can access to them at the top level of the page module.\n if (serverActionsManifest && clientReferenceManifest) {\n setManifestsSingleton({\n page: srcPage,\n clientReferenceManifest,\n serverActionsManifest\n });\n }\n const method = req.method || 'GET';\n const tracer = getTracer();\n const activeSpan = tracer.getActiveScopeSpan();\n const isWrappedByNextServer = Boolean(routerServerContext == null ? void 0 : routerServerContext.isWrappedByNextServer);\n const isMinimalMode = Boolean(getRequestMeta(req, 'minimalMode'));\n const incrementalCache = getRequestMeta(req, 'incrementalCache') || await routeModule.getIncrementalCache(req, nextConfig, prerenderManifest, isMinimalMode);\n incrementalCache == null ? void 0 : incrementalCache.resetRequestCache();\n globalThis.__incrementalCache = incrementalCache;\n const context = {\n params,\n previewProps: prerenderManifest.preview,\n renderOpts: {\n experimental: {\n authInterrupts: Boolean(nextConfig.experimental.authInterrupts)\n },\n cacheComponents: Boolean(nextConfig.cacheComponents),\n supportsDynamicResponse,\n incrementalCache,\n cacheLifeProfiles: nextConfig.cacheLife,\n waitUntil: ctx.waitUntil,\n onClose: (cb)=>{\n res.on('close', cb);\n },\n onAfterTaskError: undefined,\n onInstrumentationRequestError: (error, _request, errorContext, silenceLog)=>routeModule.onRequestError(req, error, errorContext, silenceLog, routerServerContext)\n },\n sharedContext: {\n buildId,\n deploymentId\n }\n };\n const nodeNextReq = new NodeNextRequest(req);\n const nodeNextRes = new NodeNextResponse(res);\n const nextReq = NextRequestAdapter.fromNodeNextRequest(nodeNextReq, signalFromNodeResponse(res));\n try {\n let parentSpan;\n const invokeRouteModule = async (span)=>{\n return routeModule.handle(nextReq, context).finally(()=>{\n if (!span) return;\n span.setAttributes({\n 'http.status_code': res.statusCode,\n 'next.rsc': false\n });\n const rootSpanAttributes = tracer.getRootSpanAttributes();\n // We were unable to get attributes, probably OTEL is not enabled\n if (!rootSpanAttributes) {\n return;\n }\n if (rootSpanAttributes.get('next.span_type') !== BaseServerSpan.handleRequest) {\n console.warn(`Unexpected root span type '${rootSpanAttributes.get('next.span_type')}'. Please report this Next.js issue https://github.com/vercel/next.js`);\n return;\n }\n const route = rootSpanAttributes.get('next.route');\n if (route) {\n const name = `${method} ${route}`;\n span.setAttributes({\n 'next.route': route,\n 'http.route': route,\n 'next.span_name': name\n });\n span.updateName(name);\n // Propagate http.route to the parent span if one exists (e.g.\n // a platform-created HTTP span in adapter deployments).\n if (parentSpan && parentSpan !== span) {\n parentSpan.setAttribute('http.route', route);\n parentSpan.updateName(name);\n }\n } else {\n span.updateName(`${method} ${srcPage}`);\n }\n });\n };\n const handleResponse = async (currentSpan)=>{\n var _cacheEntry_value;\n const responseGenerator = async ({ previousCacheEntry })=>{\n try {\n if (!isMinimalMode && isOnDemandRevalidate && revalidateOnlyGenerated && !previousCacheEntry) {\n res.statusCode = 404;\n // on-demand revalidate always sets this header\n res.setHeader('x-nextjs-cache', 'REVALIDATED');\n res.end('This page could not be found');\n return null;\n }\n const response = await invokeRouteModule(currentSpan);\n req.fetchMetrics = context.renderOpts.fetchMetrics;\n let pendingWaitUntil = context.renderOpts.pendingWaitUntil;\n // Attempt using provided waitUntil if available\n // if it's not we fallback to sendResponse's handling\n if (pendingWaitUntil) {\n if (ctx.waitUntil) {\n ctx.waitUntil(pendingWaitUntil);\n pendingWaitUntil = undefined;\n }\n }\n const cacheTags = context.renderOpts.collectedTags;\n // If the request is for a static response, we can cache it so long\n // as it's not edge.\n if (isIsr) {\n const blob = await response.blob();\n // Copy the headers from the response.\n const headers = toNodeOutgoingHttpHeaders(response.headers);\n if (cacheTags) {\n headers[NEXT_CACHE_TAGS_HEADER] = cacheTags;\n }\n if (!headers['content-type'] && blob.type) {\n headers['content-type'] = blob.type;\n }\n const revalidate = typeof context.renderOpts.collectedRevalidate === 'undefined' || context.renderOpts.collectedRevalidate >= INFINITE_CACHE ? false : context.renderOpts.collectedRevalidate;\n const expire = typeof context.renderOpts.collectedExpire === 'undefined' || context.renderOpts.collectedExpire >= INFINITE_CACHE ? undefined : context.renderOpts.collectedExpire;\n // Create the cache entry for the response.\n const cacheEntry = {\n value: {\n kind: CachedRouteKind.APP_ROUTE,\n status: response.status,\n body: Buffer.from(await blob.arrayBuffer()),\n headers\n },\n cacheControl: {\n revalidate,\n expire\n }\n };\n return cacheEntry;\n } else {\n // send response without caching if not ISR\n await sendResponse(nodeNextReq, nodeNextRes, response, context.renderOpts.pendingWaitUntil);\n return null;\n }\n } catch (err) {\n // if this is a background revalidate we need to report\n // the request error here as it won't be bubbled\n if (previousCacheEntry == null ? void 0 : previousCacheEntry.isStale) {\n const silenceLog = false;\n await routeModule.onRequestError(req, err, {\n routerKind: 'App Router',\n routePath: srcPage,\n routeType: 'route',\n revalidateReason: getRevalidateReason({\n isStaticGeneration,\n isOnDemandRevalidate\n })\n }, silenceLog, routerServerContext);\n }\n throw err;\n }\n };\n const cacheEntry = await routeModule.handleResponse({\n req,\n nextConfig,\n cacheKey,\n routeKind: RouteKind.APP_ROUTE,\n isFallback: false,\n prerenderManifest,\n isRoutePPREnabled: false,\n isOnDemandRevalidate,\n revalidateOnlyGenerated,\n responseGenerator,\n waitUntil: ctx.waitUntil,\n isMinimalMode\n });\n // we don't create a cacheEntry for ISR\n if (!isIsr) {\n return null;\n }\n if ((cacheEntry == null ? void 0 : (_cacheEntry_value = cacheEntry.value) == null ? void 0 : _cacheEntry_value.kind) !== CachedRouteKind.APP_ROUTE) {\n var _cacheEntry_value1;\n throw Object.defineProperty(new Error(`Invariant: app-route received invalid cache entry ${cacheEntry == null ? void 0 : (_cacheEntry_value1 = cacheEntry.value) == null ? void 0 : _cacheEntry_value1.kind}`), \"__NEXT_ERROR_CODE\", {\n value: \"E701\",\n enumerable: false,\n configurable: true\n });\n }\n if (!isMinimalMode) {\n res.setHeader('x-nextjs-cache', isOnDemandRevalidate ? 'REVALIDATED' : cacheEntry.isMiss ? 'MISS' : cacheEntry.isStale ? 'STALE' : 'HIT');\n }\n // Draft mode should never be cached\n if (isDraftMode) {\n res.setHeader('Cache-Control', 'private, no-cache, no-store, max-age=0, must-revalidate');\n }\n const headers = fromNodeOutgoingHttpHeaders(cacheEntry.value.headers);\n if (!(isMinimalMode && isIsr)) {\n headers.delete(NEXT_CACHE_TAGS_HEADER);\n }\n // If cache control is already set on the response we don't\n // override it to allow users to customize it via next.config\n if (cacheEntry.cacheControl && !res.getHeader('Cache-Control') && !headers.get('Cache-Control')) {\n headers.set('Cache-Control', getCacheControlHeader(cacheEntry.cacheControl));\n }\n await sendResponse(nodeNextReq, nodeNextRes, // @ts-expect-error - Argument of type 'Buffer<ArrayBufferLike>' is not assignable to parameter of type 'BodyInit | null | undefined'.\n new Response(cacheEntry.value.body, {\n headers,\n status: cacheEntry.value.status || 200\n }));\n return null;\n };\n // TODO: activeSpan code path is for when wrapped by\n // next-server can be removed when this is no longer used\n if (isWrappedByNextServer && activeSpan) {\n await handleResponse(activeSpan);\n } else {\n parentSpan = tracer.getActiveScopeSpan();\n await tracer.withPropagatedContext(req.headers, ()=>tracer.trace(BaseServerSpan.handleRequest, {\n spanName: `${method} ${srcPage}`,\n kind: SpanKind.SERVER,\n attributes: {\n 'http.method': method,\n 'http.target': req.url\n }\n }, handleResponse), undefined, !isWrappedByNextServer);\n }\n } catch (err) {\n if (!(err instanceof NoFallbackError)) {\n const silenceLog = false;\n await routeModule.onRequestError(req, err, {\n routerKind: 'App Router',\n routePath: normalizedSrcPage,\n routeType: 'route',\n revalidateReason: getRevalidateReason({\n isStaticGeneration,\n isOnDemandRevalidate\n })\n }, silenceLog, routerServerContext);\n }\n // rethrow so that we can handle serving error page\n // If this is during static generation, throw the error again.\n if (isIsr) throw err;\n // Otherwise, send a 500 response.\n await sendResponse(nodeNextReq, nodeNextRes, new Response(null, {\n status: 500\n }));\n return null;\n }\n}\n\n//# sourceMappingURL=app-route.js.map\n","import \"server-only\";\nimport { defineRoute } from \"@/lib/server/route\";\nimport { userPreferencesUpdateSchema } from \"@/lib/schemas/preferences\";\nimport { getPreferences, updatePreferences } from \"@/lib/server/preferences\";\n\nexport const GET = defineRoute({\n handler: ({ user }) => getPreferences(user.id),\n});\n\nexport const PATCH = defineRoute({\n body: userPreferencesUpdateSchema,\n handler: ({ user, body }) => updatePreferences(user.id, body),\n});\n","import \"server-only\";\nimport { eq } from \"drizzle-orm\";\nimport { db } from \"../db\";\nimport { userPreferences } from \"../db/schema\";\nimport {\n defaultUserPreferences,\n userPreferencesDTOSchema,\n type UserPreferencesDTO,\n type UserPreferencesUpdateInput,\n} from \"@/lib/schemas/preferences\";\n\n/**\n * Read the preferences row for a user, merged over server defaults. Always\n * returns a full DTO — fields the user has never set fall back to the\n * defaults defined in lib/schemas/preferences.ts.\n */\nexport function getPreferences(userId: string): UserPreferencesDTO {\n const row = db\n .select({ preferences: userPreferences.preferences })\n .from(userPreferences)\n .where(eq(userPreferences.userId, userId))\n .get();\n\n const stored = (row?.preferences ?? {}) as Partial<UserPreferencesDTO>;\n // Validate stored shape against the schema, falling back to defaults on\n // missing keys or invalid values. Forward-compatible with new fields.\n const merged = { ...defaultUserPreferences, ...stored };\n return userPreferencesDTOSchema.parse(merged);\n}\n\n/**\n * Patch a user's preferences. Provided fields are merged on top of the\n * existing row (upserted as needed). Returns the post-update full DTO.\n */\nexport function updatePreferences(\n userId: string,\n patch: UserPreferencesUpdateInput,\n): UserPreferencesDTO {\n const current = getPreferences(userId);\n const next: UserPreferencesDTO = { ...current, ...patch };\n const now = new Date().toISOString();\n\n db.insert(userPreferences)\n .values({ userId, preferences: next, updatedAt: now })\n .onConflictDoUpdate({\n target: userPreferences.userId,\n set: { preferences: next, updatedAt: now },\n })\n .run();\n\n return next;\n}\n"],"names":["string","userPreferencesDTOSchema","object","default_model","default_summary_model","default_system_prompt","default_history_limit","number","int","positive","user_name","user_avatar","theme_id","theme_scheme","enum","chat_render_mode","typewriter_cps","min","max","chat_bubble_style","userPreferencesUpdateSchema","partial","defaultUserPreferences"],"mappings":"4gCCAA,IAAA,EAAA,EAAA,CAAA,CAAA,QACA,EAAA,EAAA,CAAA,CAAA,QACA,EAAA,EAAA,CAAA,CAAA,QACA,EAAA,EAAA,CAAA,CAAA,QACAA,EAAAA,EAAAA,CAAAA,CAAAA,QACA,EAAA,EAAA,CAAA,CAAA,QACA,EAAA,EAAA,CAAA,CAAA,QACA,EAAA,EAAA,CAAA,CAAA,QACA,EAAA,EAAA,CAAA,CAAA,QACA,EAAA,EAAA,CAAA,CAAA,QACA,EAAA,EAAA,CAAA,CAAA,OACA,EAAA,EAAA,CAAA,CAAA,QACA,EAAA,EAAA,CAAA,CAAA,QACA,EAAA,EAAA,CAAA,CAAA,QACA,EAAA,EAAA,CAAA,CAAA,OACA,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AAY,GAE9E,MAAM,CAAA,EAAA,EAAA,YAAA,AAAY,EAAC,EAAa,EAChC,IAAI,SAAS,EAAW,KAAK,CAAC,IAAI,CAAE,SAChC,EACA,OAAQ,EAAW,KAAK,CAAC,MAAM,EAAI,GACvC,IACO,IACX,EAGI,GAAyB,EACzB,MAAM,EAAe,EADgB,EAGrC,EAAa,EAAO,kBAAkB,GACtC,MAAM,EAAO,qBAAqB,CAAC,EAAI,OAAO,CAAE,IAAI,EAAO,KAAK,CAAC,EAAA,cAAc,CAAC,aAAa,CAAE,CACvF,SAAU,CAAA,EAAG,EAAO,CAAC,EAAE,EAAA,CAAS,CAChC,KAAM,EAAA,QAAQ,CAAC,MAAM,CACrB,WAAY,CACR,cAAe,EACf,cAAe,EAAI,GAAG,AAC1B,CACJ,EAAG,QAAiB,EAAW,CAAC,GAE5C,CAAE,MAAO,EAAK,CAeV,GAdM,aAAe,EAAA,eAAe,EAEhC,CAFmC,KAE7B,EAAY,cAAc,CAAC,EAAK,EAAK,CACvC,WAAY,aACZ,UAAW,EACX,UAAW,QACX,iBAAkB,CAAA,EAAA,EAAA,mBAAA,AAAmB,EAAC,oBAClC,EACA,sBACJ,EACJ,GAAG,AATgB,EASJ,GAIf,EAAO,MAAM,EAKjB,OAHA,MAAM,CAAA,EAAA,EAAA,YAAA,AAAY,EAAC,EAAa,EAAa,IAAI,SAAS,KAAM,CAC5D,OAAQ,GACZ,IACO,IACX,CACJ,mCA5TA,SAAS,EACL,MAAO,CAAA,EAAA,EAAA,UAAA,AAAW,EAAC,kBACf,uBACA,CACJ,EACJ","ignoreList":[1]}
@@ -1,3 +0,0 @@
1
- module.exports=[814747,(e,t,r)=>{t.exports=e.x("path",()=>require("path"))},872031,e=>{"use strict";var t=e.i(902157),r=e.i(750227);let a=process.env.LOOM_USER_CWD||process.cwd(),n=(0,r.resolve)(a,"data","log-artifacts");function i(e){return(0,r.resolve)(n,e)}function o(e,t,a){return(0,r.resolve)(i(e),`${t}.${a}`)}function s(e,t){return`/api/logs/generations/${encodeURIComponent(e)}/images/${t}`}async function l(e,r){let a=r.data;if(!Array.isArray(a))return[];let n=[],l=!1;for(let r=0;r<a.length;r++){let u=a[r];if(!u||"object"!=typeof u)continue;let d="string"==typeof u.b64_json?u.b64_json:null;if(!d)continue;let p=Buffer.from(d,"base64"),c="string"==typeof u.mime?u.mime:"string"==typeof u.output_format?`image/${u.output_format}`:"image/png",h=o(e,r,function(e){switch(e.toLowerCase()){case"image/png":return"png";case"image/jpeg":case"image/jpg":return"jpg";case"image/webp":return"webp";case"image/gif":return"gif";default:return"bin"}}(c));l||((0,t.mkdirSync)(i(e),{recursive:!0}),l=!0),await t.promises.writeFile(h,p),delete u.b64_json,u.url=s(e,r),u.loom_artifact=!0,u.bytes=p.byteLength,u.mime=c,n.push({index:r,mime:c,bytes:p.byteLength,path:h,url:s(e,r)})}return n.length>0&&(r.loom_artifacts=n.map(e=>({index:e.index,url:e.url,mime:e.mime,bytes:e.bytes}))),n}async function u(e,r){for(let a of["png","jpg","webp","gif","bin"]){let n=o(e,r,a);try{let e=await t.promises.readFile(n),r="jpg"===a?"image/jpeg":"bin"===a?"application/octet-stream":`image/${a}`;return{buf:e,mime:r}}catch{}}return null}e.s(["persistImageArtifacts",0,l,"readArtifact",0,u])},59639,(e,t,r)=>{t.exports=e.x("node:process",()=>require("node:process"))},936935,e=>{"use strict";var t=e.i(747909),r=e.i(174017),a=e.i(996250),n=e.i(759756),i=e.i(561916),o=e.i(174677),s=e.i(869741),l=e.i(316795),u=e.i(487718),d=e.i(995169),p=e.i(47587),c=e.i(666012),h=e.i(570101),g=e.i(626937),f=e.i(10372),m=e.i(193695);e.i(52474);var R=e.i(600220),v=e.i(456315),y=e.i(435e3);e.i(867661);var w=e.i(350861);let C=(0,v.defineRoute)({body:y.playgroundChatSchema,handler:({user:e,body:t})=>(0,w.sendPlaygroundChat)(e,t)});e.s(["POST",0,C],443312);var E=e.i(443312);let b=new t.AppRouteRouteModule({definition:{kind:r.RouteKind.APP_ROUTE,page:"/api/playground/chat/route",pathname:"/api/playground/chat",filename:"route",bundlePath:""},distDir:".next",relativeProjectDir:"",resolvedPagePath:"[project]/app/api/playground/chat/route.ts",nextConfigOutput:"",userland:E,...{}}),{workAsyncStorage:x,workUnitAsyncStorage:A,serverHooks:_}=b;async function P(e,t,a){a.requestMeta&&(0,n.setRequestMeta)(e,a.requestMeta),b.isDev&&(0,n.addRequestMeta)(e,"devRequestTimingInternalsEnd",process.hrtime.bigint());let v="/api/playground/chat/route";v=v.replace(/\/index$/,"")||"/";let y=await b.prepare(e,t,{srcPage:v,multiZoneDraftMode:!1});if(!y)return t.statusCode=400,t.end("Bad Request"),null==a.waitUntil||a.waitUntil.call(a,Promise.resolve()),null;let{buildId:w,deploymentId:C,params:E,nextConfig:x,parsedUrl:A,isDraftMode:_,prerenderManifest:P,routerServerContext:S,isOnDemandRevalidate:T,revalidateOnlyGenerated:N,resolvedPathname:O,clientReferenceManifest:q,serverActionsManifest:I}=y,U=(0,s.normalizeAppPath)(v),j=!!(P.dynamicRoutes[U]||P.routes[O]),H=async()=>((null==S?void 0:S.render404)?await S.render404(e,t,A,!1):t.end("This page could not be found"),null);if(j&&!_){let e=!!P.routes[O],t=P.dynamicRoutes[U];if(t&&!1===t.fallback&&!e){if(x.adapterPath)return await H();throw new m.NoFallbackError}}let M=null;!j||b.isDev||_||(M="/index"===(M=O)?"/":M);let $=!0===b.isDev||!j,k=j&&!$;I&&q&&(0,o.setManifestsSingleton)({page:v,clientReferenceManifest:q,serverActionsManifest:I});let D=e.method||"GET",F=(0,i.getTracer)(),L=F.getActiveScopeSpan(),K=!!(null==S?void 0:S.isWrappedByNextServer),B=!!(0,n.getRequestMeta)(e,"minimalMode"),W=(0,n.getRequestMeta)(e,"incrementalCache")||await b.getIncrementalCache(e,x,P,B);null==W||W.resetRequestCache(),globalThis.__incrementalCache=W;let G={params:E,previewProps:P.preview,renderOpts:{experimental:{authInterrupts:!!x.experimental.authInterrupts},cacheComponents:!!x.cacheComponents,supportsDynamicResponse:$,incrementalCache:W,cacheLifeProfiles:x.cacheLife,waitUntil:a.waitUntil,onClose:e=>{t.on("close",e)},onAfterTaskError:void 0,onInstrumentationRequestError:(t,r,a,n)=>b.onRequestError(e,t,a,n,S)},sharedContext:{buildId:w,deploymentId:C}},V=new l.NodeNextRequest(e),X=new l.NodeNextResponse(t),z=u.NextRequestAdapter.fromNodeNextRequest(V,(0,u.signalFromNodeResponse)(t));try{let n,o=async e=>b.handle(z,G).finally(()=>{if(!e)return;e.setAttributes({"http.status_code":t.statusCode,"next.rsc":!1});let r=F.getRootSpanAttributes();if(!r)return;if(r.get("next.span_type")!==d.BaseServerSpan.handleRequest)return void console.warn(`Unexpected root span type '${r.get("next.span_type")}'. Please report this Next.js issue https://github.com/vercel/next.js`);let a=r.get("next.route");if(a){let t=`${D} ${a}`;e.setAttributes({"next.route":a,"http.route":a,"next.span_name":t}),e.updateName(t),n&&n!==e&&(n.setAttribute("http.route",a),n.updateName(t))}else e.updateName(`${D} ${v}`)}),s=async n=>{var i,s;let l=async({previousCacheEntry:r})=>{try{if(!B&&T&&N&&!r)return t.statusCode=404,t.setHeader("x-nextjs-cache","REVALIDATED"),t.end("This page could not be found"),null;let i=await o(n);e.fetchMetrics=G.renderOpts.fetchMetrics;let s=G.renderOpts.pendingWaitUntil;s&&a.waitUntil&&(a.waitUntil(s),s=void 0);let l=G.renderOpts.collectedTags;if(!j)return await (0,c.sendResponse)(V,X,i,G.renderOpts.pendingWaitUntil),null;{let e=await i.blob(),t=(0,h.toNodeOutgoingHttpHeaders)(i.headers);l&&(t[f.NEXT_CACHE_TAGS_HEADER]=l),!t["content-type"]&&e.type&&(t["content-type"]=e.type);let r=void 0!==G.renderOpts.collectedRevalidate&&!(G.renderOpts.collectedRevalidate>=f.INFINITE_CACHE)&&G.renderOpts.collectedRevalidate,a=void 0===G.renderOpts.collectedExpire||G.renderOpts.collectedExpire>=f.INFINITE_CACHE?void 0:G.renderOpts.collectedExpire;return{value:{kind:R.CachedRouteKind.APP_ROUTE,status:i.status,body:Buffer.from(await e.arrayBuffer()),headers:t},cacheControl:{revalidate:r,expire:a}}}}catch(t){throw(null==r?void 0:r.isStale)&&await b.onRequestError(e,t,{routerKind:"App Router",routePath:v,routeType:"route",revalidateReason:(0,p.getRevalidateReason)({isStaticGeneration:k,isOnDemandRevalidate:T})},!1,S),t}},u=await b.handleResponse({req:e,nextConfig:x,cacheKey:M,routeKind:r.RouteKind.APP_ROUTE,isFallback:!1,prerenderManifest:P,isRoutePPREnabled:!1,isOnDemandRevalidate:T,revalidateOnlyGenerated:N,responseGenerator:l,waitUntil:a.waitUntil,isMinimalMode:B});if(!j)return null;if((null==u||null==(i=u.value)?void 0:i.kind)!==R.CachedRouteKind.APP_ROUTE)throw Object.defineProperty(Error(`Invariant: app-route received invalid cache entry ${null==u||null==(s=u.value)?void 0:s.kind}`),"__NEXT_ERROR_CODE",{value:"E701",enumerable:!1,configurable:!0});B||t.setHeader("x-nextjs-cache",T?"REVALIDATED":u.isMiss?"MISS":u.isStale?"STALE":"HIT"),_&&t.setHeader("Cache-Control","private, no-cache, no-store, max-age=0, must-revalidate");let d=(0,h.fromNodeOutgoingHttpHeaders)(u.value.headers);return B&&j||d.delete(f.NEXT_CACHE_TAGS_HEADER),!u.cacheControl||t.getHeader("Cache-Control")||d.get("Cache-Control")||d.set("Cache-Control",(0,g.getCacheControlHeader)(u.cacheControl)),await (0,c.sendResponse)(V,X,new Response(u.value.body,{headers:d,status:u.value.status||200})),null};K&&L?await s(L):(n=F.getActiveScopeSpan(),await F.withPropagatedContext(e.headers,()=>F.trace(d.BaseServerSpan.handleRequest,{spanName:`${D} ${v}`,kind:i.SpanKind.SERVER,attributes:{"http.method":D,"http.target":e.url}},s),void 0,!K))}catch(t){if(t instanceof m.NoFallbackError||await b.onRequestError(e,t,{routerKind:"App Router",routePath:U,routeType:"route",revalidateReason:(0,p.getRevalidateReason)({isStaticGeneration:k,isOnDemandRevalidate:T})},!1,S),j)throw t;return await (0,c.sendResponse)(V,X,new Response(null,{status:500})),null}}e.s(["handler",0,P,"patchFetch",0,function(){return(0,a.patchFetch)({workAsyncStorage:x,workUnitAsyncStorage:A})},"routeModule",0,b,"serverHooks",0,_,"workAsyncStorage",0,x,"workUnitAsyncStorage",0,A],936935)},70729,e=>{e.v(e=>Promise.resolve().then(()=>e(666680)))}];
2
-
3
- //# sourceMappingURL=%5Broot-of-the-server%5D__1xj9qqs._.js.map