@alwith/module-chat 0.5.19 → 0.5.20

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 (482) hide show
  1. package/README.md +240 -1
  2. package/THIRD_PARTY_NOTICES.md +13 -0
  3. package/assets/catalogs/alwith/models.json +72 -0
  4. package/assets/catalogs/custom/models.json +604 -0
  5. package/assets/catalogs/custom/sources.json +168 -0
  6. package/assets/catalogs/deepseek/models.json +139 -0
  7. package/assets/catalogs/openrouter/models.json +231 -0
  8. package/assets/catalogs/qwen/models.json +253 -0
  9. package/assets/catalogs/xai/models.json +129 -0
  10. package/assets/provider-catalog.json +127 -0
  11. package/dist/activity-host.js +1 -1
  12. package/dist/approval/choice-elicitation-form.js +1 -1
  13. package/dist/approval/choice-schema.js +1 -1
  14. package/dist/approval/permission-options.js +1 -1
  15. package/dist/approval/permission-view.js +1 -1
  16. package/dist/approval/schema-elicitation-form.js +1 -1
  17. package/dist/approval/url-elicitation-card.js +1 -1
  18. package/dist/chunk-0643swd4.js +2 -0
  19. package/dist/chunk-06zh85wp.js +3 -0
  20. package/dist/chunk-0p6y2t9b.js +2 -0
  21. package/dist/{chunk-tzyc5myt.js → chunk-0wa9yjg3.js} +2 -2
  22. package/dist/chunk-0whxm2f0.js +2 -0
  23. package/dist/chunk-11484wvv.js +2 -0
  24. package/dist/{chunk-5n4mefej.js → chunk-1fggcrvs.js} +2 -2
  25. package/dist/chunk-1k21j77z.js +2 -0
  26. package/dist/chunk-1k697ncv.js +2 -0
  27. package/dist/chunk-1mn2t6ga.js +2 -0
  28. package/dist/chunk-1qyxrh0n.js +3 -0
  29. package/dist/chunk-1r25anvg.js +2 -0
  30. package/dist/chunk-1rg3nab3.js +2 -0
  31. package/dist/chunk-20k9syde.js +1 -0
  32. package/dist/chunk-28f3zv6v.js +2 -0
  33. package/dist/{chunk-h3antqdd.js → chunk-2f9vjmxz.js} +2 -2
  34. package/dist/{chunk-k9mbpf0g.js → chunk-2t9j90mw.js} +2 -2
  35. package/dist/{chunk-2hk04fh3.js → chunk-36m8zstj.js} +2 -2
  36. package/dist/chunk-3gk86w24.js +2 -0
  37. package/dist/chunk-3ka3bt0t.js +2 -0
  38. package/dist/{chunk-210b2kk6.js → chunk-3s94ekrs.js} +2 -2
  39. package/dist/chunk-3vsc49pt.js +2 -0
  40. package/dist/{chunk-9ej4c7a8.js → chunk-3yxjh7b1.js} +2 -2
  41. package/dist/{chunk-dj4e0q7k.js → chunk-42atrgm1.js} +2 -2
  42. package/dist/{chunk-fgzq0ktw.js → chunk-48fj5m0p.js} +2 -2
  43. package/dist/{chunk-jx1cngyb.js → chunk-4bb6dzzs.js} +2 -2
  44. package/dist/chunk-4d853988.js +2 -0
  45. package/dist/chunk-4gyd9hx9.js +2 -0
  46. package/dist/chunk-4p6svs37.js +2 -0
  47. package/dist/chunk-4ygyb91q.js +2 -0
  48. package/dist/{chunk-ekd97p2x.js → chunk-581e33tz.js} +2 -2
  49. package/dist/{chunk-m2hpfdch.js → chunk-5a6xc345.js} +2 -2
  50. package/dist/chunk-5ap6fvrp.js +2 -0
  51. package/dist/chunk-5m7vc4s6.js +2 -0
  52. package/dist/{chunk-yjhypkmc.js → chunk-615a0yhh.js} +2 -2
  53. package/dist/chunk-62jm1gct.js +2 -0
  54. package/dist/{chunk-6p41wmgs.js → chunk-667z0pac.js} +2 -2
  55. package/dist/chunk-6syhjege.js +2 -0
  56. package/dist/{chunk-jt8h82c2.js → chunk-6t5war9h.js} +2 -2
  57. package/dist/{chunk-4xhvh2dn.js → chunk-7z4gtfkd.js} +2 -2
  58. package/dist/{chunk-f8wzz84b.js → chunk-855w49k0.js} +2 -2
  59. package/dist/chunk-8akwfgkq.js +2 -0
  60. package/dist/chunk-8c8ncw1m.js +2 -0
  61. package/dist/chunk-8mgypdap.js +2 -0
  62. package/dist/chunk-95mynf7q.js +1289 -0
  63. package/dist/chunk-9jp5t3qq.js +5 -0
  64. package/dist/chunk-9mky3b7v.js +2 -0
  65. package/dist/chunk-a63k8tht.js +2 -0
  66. package/dist/chunk-acb8t4jt.js +2 -0
  67. package/dist/chunk-adk7aeyt.js +2 -0
  68. package/dist/{chunk-0vy6cqmw.js → chunk-agqnt7xq.js} +2 -2
  69. package/dist/chunk-annzfgfq.js +4 -0
  70. package/dist/{chunk-9ebnn34t.js → chunk-azfmr99x.js} +2 -2
  71. package/dist/chunk-b12v22de.js +2 -0
  72. package/dist/{chunk-fcy4sv9f.js → chunk-b18zr059.js} +2 -2
  73. package/dist/chunk-bbyscgdd.js +2 -0
  74. package/dist/chunk-bfhfbrzt.js +2 -0
  75. package/dist/{chunk-jc52024g.js → chunk-bg03czcx.js} +2 -2
  76. package/dist/chunk-bvgqsaey.js +2 -0
  77. package/dist/chunk-c32z3wjq.js +2 -0
  78. package/dist/{chunk-ww223tm5.js → chunk-ckyat78p.js} +2 -2
  79. package/dist/chunk-cvz3k5gk.js +2 -0
  80. package/dist/chunk-d0vhdr07.js +2 -0
  81. package/dist/chunk-d257n8gj.js +2 -0
  82. package/dist/chunk-dfgak1md.js +2 -0
  83. package/dist/{chunk-e44hny11.js → chunk-drhzcs6e.js} +2 -2
  84. package/dist/{chunk-a4wrn6ep.js → chunk-dte0n4kf.js} +2 -2
  85. package/dist/chunk-erjscd1r.js +4 -0
  86. package/dist/{chunk-kjswq0tx.js → chunk-f1x483c9.js} +2 -2
  87. package/dist/chunk-f2w2sct6.js +2 -0
  88. package/dist/{chunk-0zp04d1m.js → chunk-f5gsffbv.js} +2 -2
  89. package/dist/chunk-feg5rp9g.js +2 -0
  90. package/dist/chunk-ffspd86m.js +2 -0
  91. package/dist/chunk-fh3pjhe6.js +2 -0
  92. package/dist/{chunk-rsfwc38x.js → chunk-fnpf84rf.js} +3 -3
  93. package/dist/chunk-g2qcyqc6.js +2 -0
  94. package/dist/chunk-g44hhdha.js +2 -0
  95. package/dist/chunk-g9t2d8hg.js +2 -0
  96. package/dist/chunk-g9yg36dh.js +3 -0
  97. package/dist/{chunk-nkqe2e8s.js → chunk-gha517v4.js} +2 -2
  98. package/dist/chunk-grr1k5zn.js +2 -0
  99. package/dist/chunk-gsfgdnfp.js +2 -0
  100. package/dist/chunk-h491shsg.js +2 -0
  101. package/dist/chunk-ha46rhzj.js +2 -0
  102. package/dist/chunk-hd7bk591.js +2 -0
  103. package/dist/{chunk-a9s3m9fs.js → chunk-heyqzkxq.js} +2 -2
  104. package/dist/chunk-hp4a0e8c.js +2 -0
  105. package/dist/{chunk-qmc18ejg.js → chunk-j69t1f4a.js} +2 -2
  106. package/dist/chunk-j8v3sfpv.js +2 -0
  107. package/dist/{chunk-z5tstgsh.js → chunk-jgd6dcgy.js} +2 -2
  108. package/dist/chunk-jmb8r6aj.js +2 -0
  109. package/dist/chunk-jwt7q6yx.js +4 -0
  110. package/dist/chunk-jxntqarp.js +2 -0
  111. package/dist/chunk-k64wvbbc.js +2 -0
  112. package/dist/{chunk-eeq8d3x7.js → chunk-k7ye738q.js} +2 -2
  113. package/dist/chunk-kbeme4w0.js +3 -0
  114. package/dist/{chunk-cdrmg9jj.js → chunk-kc56dhwd.js} +2 -2
  115. package/dist/{chunk-9xkp5x7h.js → chunk-kmdag4vy.js} +2 -2
  116. package/dist/chunk-kq48hbd5.js +2 -0
  117. package/dist/chunk-ktvh4yb5.js +2 -0
  118. package/dist/{chunk-c2h76vnt.js → chunk-kz1kjzmq.js} +2 -2
  119. package/dist/{chunk-eyf9bxyx.js → chunk-m271yxxm.js} +2 -2
  120. package/dist/chunk-mj7094yh.js +2 -0
  121. package/dist/chunk-mr6k70s4.js +2 -0
  122. package/dist/chunk-mv51zgj1.js +2 -0
  123. package/dist/{chunk-gcx4fk1a.js → chunk-mvs2dzyt.js} +2 -2
  124. package/dist/chunk-mz8a6292.js +2 -0
  125. package/dist/chunk-n5v1h0sk.js +2 -0
  126. package/dist/{chunk-01rfnabj.js → chunk-n66yy1m1.js} +2 -2
  127. package/dist/chunk-n9gq2wbz.js +3 -0
  128. package/dist/chunk-nxyrrmz8.js +2 -0
  129. package/dist/chunk-p7dd93e5.js +2 -0
  130. package/dist/chunk-p8g927x6.js +2 -0
  131. package/dist/chunk-pk2rvqd0.js +2 -0
  132. package/dist/{chunk-hwh88n0v.js → chunk-pprt7ntb.js} +4 -4
  133. package/dist/{chunk-gr1nnczz.js → chunk-pwjz3yxb.js} +2 -2
  134. package/dist/{chunk-sf1z4r7v.js → chunk-px1ehzwc.js} +2 -2
  135. package/dist/chunk-pzjag1mt.js +4 -0
  136. package/dist/chunk-q2gfd4jk.js +2 -0
  137. package/dist/chunk-q9ef9n7b.js +2 -0
  138. package/dist/chunk-q9zawfn1.js +2 -0
  139. package/dist/{chunk-b53ky6rb.js → chunk-qd1z91fm.js} +2 -2
  140. package/dist/chunk-qdg5zphd.js +2 -0
  141. package/dist/chunk-qn6ppn0r.js +2 -0
  142. package/dist/{chunk-09r35ts9.js → chunk-qwfw4xpn.js} +2 -2
  143. package/dist/chunk-r7s7kx38.js +3 -0
  144. package/dist/chunk-r9sweaq4.js +2 -0
  145. package/dist/chunk-rbv1scqm.js +2 -0
  146. package/dist/{chunk-yjtq166b.js → chunk-rjkpe1fw.js} +3 -3
  147. package/dist/{chunk-0zph0gwq.js → chunk-rjw63t34.js} +3 -3
  148. package/dist/chunk-rkfq0c0p.js +2 -0
  149. package/dist/chunk-rq5e0922.js +2 -0
  150. package/dist/chunk-s4wjckd1.js +7 -0
  151. package/dist/chunk-s8s65pj2.js +2 -0
  152. package/dist/chunk-ssxbxanb.js +2 -0
  153. package/dist/{chunk-qy2prx7m.js → chunk-swpy2b9a.js} +2 -2
  154. package/dist/chunk-t7drk9ja.js +2 -0
  155. package/dist/chunk-tpbqg729.js +2 -0
  156. package/dist/chunk-ttn8ss6b.js +2 -0
  157. package/dist/chunk-tv0fwt2g.js +2 -0
  158. package/dist/chunk-v5pbaf9x.js +2 -0
  159. package/dist/chunk-vbab9hc4.js +2 -0
  160. package/dist/{chunk-5nj2fjej.js → chunk-vfhxerxt.js} +2 -2
  161. package/dist/chunk-vnsgjnp3.js +2 -0
  162. package/dist/{chunk-kvx8fv1e.js → chunk-vt6cyes7.js} +2 -2
  163. package/dist/chunk-vzgv360q.js +2 -0
  164. package/dist/{chunk-5e10bzg2.js → chunk-wccx911q.js} +2 -2
  165. package/dist/{chunk-q4q4f03j.js → chunk-wgrmjfyp.js} +2 -2
  166. package/dist/chunk-wvry7t79.js +2 -0
  167. package/dist/chunk-x2nemdjf.js +2 -0
  168. package/dist/chunk-x99fyd88.js +2 -0
  169. package/dist/chunk-xdm2are3.js +2 -0
  170. package/dist/chunk-xft0s40a.js +3 -0
  171. package/dist/chunk-y0q6jwq4.js +2 -0
  172. package/dist/chunk-y6kzbbya.js +2 -0
  173. package/dist/chunk-y97ne5kj.js +2 -0
  174. package/dist/chunk-yakar0e2.js +2 -0
  175. package/dist/chunk-yg3xhn5m.js +2 -0
  176. package/dist/chunk-z3nybrbb.js +2 -0
  177. package/dist/codex/activity-group.js +1 -1
  178. package/dist/codex/assistant-message.js +1 -1
  179. package/dist/codex/async-question-card.js +1 -1
  180. package/dist/codex/disclosure-state.js +1 -1
  181. package/dist/codex/edited-files-card.js +1 -1
  182. package/dist/codex/image-view-activity.js +1 -1
  183. package/dist/codex/markdown-renderer.js +1 -1
  184. package/dist/codex/navigation-audio.js +1 -1
  185. package/dist/codex/navigation-preview.js +1 -1
  186. package/dist/codex/navigation-rail.js +1 -1
  187. package/dist/codex/patch-view.js +1 -1
  188. package/dist/codex/plan.js +1 -1
  189. package/dist/codex/timeline-virtualizer.js +1 -1
  190. package/dist/codex/turn-activity.js +1 -1
  191. package/dist/codex/user-message.js +1 -1
  192. package/dist/codex/virtualized-turn-list.js +1 -1
  193. package/dist/collections/collection-emoji.d.ts +4 -0
  194. package/dist/collections/collection-emoji.js +1 -0
  195. package/dist/collections/collection-menu.d.ts +15 -0
  196. package/dist/collections/collection-menu.js +1 -0
  197. package/dist/collections/collection-panel.d.ts +11 -0
  198. package/dist/collections/collection-panel.js +1 -0
  199. package/dist/collections/collections.d.ts +6 -0
  200. package/dist/collections/collections.js +1 -0
  201. package/dist/collections/host.d.ts +19 -0
  202. package/dist/collections/host.js +1 -0
  203. package/dist/collections/locales.d.ts +71 -0
  204. package/dist/collections/locales.js +1 -0
  205. package/dist/collections/model.d.ts +95 -0
  206. package/dist/collections/model.js +1 -0
  207. package/dist/collections/store.d.ts +30 -0
  208. package/dist/collections/store.js +1 -0
  209. package/dist/composer/completion-filter.js +1 -1
  210. package/dist/composer/completion-menu.js +1 -1
  211. package/dist/composer/completion-trigger.js +1 -1
  212. package/dist/composer/effort-slider.js +1 -1
  213. package/dist/composer/menu-radio.js +1 -1
  214. package/dist/composer/model-select.js +1 -1
  215. package/dist/composer/permission-mode-select.js +1 -1
  216. package/dist/composer/prompt-input-attachments.js +1 -1
  217. package/dist/composer/prompt-input-clipboard.js +1 -1
  218. package/dist/composer/prompt-input-context.js +1 -1
  219. package/dist/composer/prompt-input-textarea.js +1 -1
  220. package/dist/composer/prompt-input.js +1 -1
  221. package/dist/conversation/action-card.js +1 -1
  222. package/dist/conversation/composer/composer.js +1 -1
  223. package/dist/conversation/composer/config-options.js +1 -1
  224. package/dist/conversation/composer/context.js +1 -1
  225. package/dist/conversation/composer/drafts.js +1 -1
  226. package/dist/conversation/composer/file-items.js +1 -1
  227. package/dist/conversation/composer/long-text.js +1 -1
  228. package/dist/conversation/composer/mention-chips.js +1 -1
  229. package/dist/conversation/composer/mention-uri.js +1 -1
  230. package/dist/conversation/composer/model-menu.js +1 -1
  231. package/dist/conversation/composer/pasted-text-attachment.js +1 -1
  232. package/dist/conversation/composer/permission-mode-menu.js +1 -1
  233. package/dist/conversation/composer/prediction.js +1 -1
  234. package/dist/conversation/composer/slash-command-button.js +1 -1
  235. package/dist/conversation/composer/submit-button.js +1 -1
  236. package/dist/conversation/composer/usage-meter.js +1 -1
  237. package/dist/conversation/connection-notice.d.ts +8 -0
  238. package/dist/conversation/connection-notice.js +1 -0
  239. package/dist/conversation/context.js +1 -1
  240. package/dist/conversation/conversation-body.js +1 -1
  241. package/dist/conversation/conversation-search.d.ts +8 -0
  242. package/dist/conversation/conversation-search.js +1 -0
  243. package/dist/conversation/conversation-view.d.ts +1 -0
  244. package/dist/conversation/conversation-view.js +1 -1
  245. package/dist/conversation/conversation.d.ts +3 -0
  246. package/dist/conversation/conversation.js +1 -1
  247. package/dist/conversation/diff-modal.js +1 -1
  248. package/dist/conversation/draft-project-picker.d.ts +7 -0
  249. package/dist/conversation/draft-project-picker.js +1 -0
  250. package/dist/conversation/session-actions.js +1 -1
  251. package/dist/conversation/subagent-sessions.js +1 -1
  252. package/dist/conversation/types.d.ts +6 -1
  253. package/dist/image-lightbox.js +1 -1
  254. package/dist/image-preview-dialog.js +1 -1
  255. package/dist/lib/code-highlighter.js +1 -1
  256. package/dist/lib/fuzzy.js +1 -1
  257. package/dist/lib/group-blocks.js +1 -1
  258. package/dist/lib/image-encode.js +1 -1
  259. package/dist/lib/limits.js +1 -1
  260. package/dist/lib/markdown-parser.js +1 -1
  261. package/dist/lib/markdown-rules.js +1 -1
  262. package/dist/lib/model-name.js +1 -1
  263. package/dist/lib/pointer-centered-zoom.js +1 -1
  264. package/dist/lib/prepare-prompt-files.js +1 -1
  265. package/dist/lib/stream-style.js +1 -1
  266. package/dist/lib/streaming-markdown.js +1 -1
  267. package/dist/locales.d.ts +1914 -0
  268. package/dist/locales.js +1 -1
  269. package/dist/plugins/catalog-header.d.ts +6 -0
  270. package/dist/plugins/catalog-header.js +1 -0
  271. package/dist/plugins/catalog-skeleton.d.ts +3 -0
  272. package/dist/plugins/catalog-skeleton.js +1 -0
  273. package/dist/plugins/host.d.ts +49 -0
  274. package/dist/plugins/host.js +1 -0
  275. package/dist/plugins/locales.d.ts +1136 -0
  276. package/dist/plugins/locales.js +1 -0
  277. package/dist/plugins/new-chat-directory.d.ts +2 -0
  278. package/dist/plugins/new-chat-directory.js +1 -0
  279. package/dist/plugins/pane.d.ts +12 -0
  280. package/dist/plugins/pane.js +1 -0
  281. package/dist/plugins/panel-item.d.ts +8 -0
  282. package/dist/plugins/panel-item.js +1 -0
  283. package/dist/plugins/plugin-detail-page.d.ts +5 -0
  284. package/dist/plugins/plugin-detail-page.js +1 -0
  285. package/dist/plugins/plugin-icon.d.ts +7 -0
  286. package/dist/plugins/plugin-icon.js +1 -0
  287. package/dist/plugins/plugin-icons.d.ts +1 -0
  288. package/dist/plugins/plugin-icons.js +1 -0
  289. package/dist/plugins/plugins-page.d.ts +12 -0
  290. package/dist/plugins/plugins-page.js +1 -0
  291. package/dist/plugins/plugins.css +199 -0
  292. package/dist/plugins/plugins.d.ts +14 -0
  293. package/dist/plugins/plugins.js +1 -0
  294. package/dist/plugins/read-skill-document.d.ts +2 -0
  295. package/dist/plugins/read-skill-document.js +1 -0
  296. package/dist/plugins/skill-document.d.ts +7 -0
  297. package/dist/plugins/skill-document.js +1 -0
  298. package/dist/plugins/skills-tab.d.ts +6 -0
  299. package/dist/plugins/skills-tab.js +1 -0
  300. package/dist/plugins/store.d.ts +62 -0
  301. package/dist/plugins/store.js +1 -0
  302. package/dist/plugins/toolbox-layout.d.ts +7 -0
  303. package/dist/plugins/toolbox-layout.js +1 -0
  304. package/dist/search/chat-search.css +9 -0
  305. package/dist/search/chat-search.d.ts +1 -0
  306. package/dist/search/chat-search.js +1 -1
  307. package/dist/search/codex-source-matches.d.ts +4 -0
  308. package/dist/search/codex-source-matches.js +1 -0
  309. package/dist/search/dom-matches.js +1 -1
  310. package/dist/search/find-bar.js +1 -1
  311. package/dist/search/literal-matches.js +1 -1
  312. package/dist/session-list/account-menu.d.ts +26 -0
  313. package/dist/session-list/account-menu.js +1 -0
  314. package/dist/session-list/activity-list.d.ts +11 -0
  315. package/dist/session-list/activity-list.js +1 -0
  316. package/dist/session-list/archived-sessions.js +1 -1
  317. package/dist/session-list/help-menu.d.ts +5 -0
  318. package/dist/session-list/help-menu.js +1 -0
  319. package/dist/session-list/highlight.js +1 -1
  320. package/dist/session-list/host.d.ts +2 -0
  321. package/dist/session-list/host.js +1 -1
  322. package/dist/session-list/hover-info-card.js +1 -1
  323. package/dist/session-list/locales.d.ts +91 -0
  324. package/dist/session-list/locales.js +1 -1
  325. package/dist/session-list/navigation-header.d.ts +14 -0
  326. package/dist/session-list/navigation-header.js +1 -0
  327. package/dist/session-list/navigation-store.d.ts +19 -0
  328. package/dist/session-list/navigation-store.js +1 -0
  329. package/dist/session-list/navigation-tabs.d.ts +20 -0
  330. package/dist/session-list/navigation-tabs.js +1 -0
  331. package/dist/session-list/navigation.js +1 -1
  332. package/dist/session-list/overflow-marquee.js +1 -1
  333. package/dist/session-list/platform.d.ts +2 -0
  334. package/dist/session-list/platform.js +1 -0
  335. package/dist/session-list/row-stop-button.js +1 -1
  336. package/dist/session-list/session-groups.js +1 -1
  337. package/dist/session-list/session-info-card.js +1 -1
  338. package/dist/session-list/session-list.d.ts +10 -0
  339. package/dist/session-list/session-list.js +1 -1
  340. package/dist/session-list/session-row.js +1 -1
  341. package/dist/session-list/session-state-dot.js +1 -1
  342. package/dist/session-list/session-state-menu.js +1 -1
  343. package/dist/session-list/shortcut-hint.d.ts +14 -0
  344. package/dist/session-list/shortcut-hint.js +1 -0
  345. package/dist/session-list/shortcut.d.ts +2 -0
  346. package/dist/session-list/shortcut.js +1 -0
  347. package/dist/session-list/sidebar-overlay.js +1 -1
  348. package/dist/session-list/trailing-swap.js +1 -1
  349. package/dist/session-list/use-activity-notification.d.ts +1 -0
  350. package/dist/session-list/use-activity-notification.js +1 -0
  351. package/dist/session-list/use-activity-preview.js +1 -1
  352. package/dist/session-list/use-cmd-held.d.ts +1 -0
  353. package/dist/session-list/use-cmd-held.js +1 -0
  354. package/dist/session-list/use-project-sessions.js +1 -1
  355. package/dist/session-list/virtual-session-rows.js +1 -1
  356. package/dist/session-timeline/activity-group.js +1 -1
  357. package/dist/session-timeline/activity-projection.js +1 -1
  358. package/dist/session-timeline/assistant-content.js +1 -1
  359. package/dist/session-timeline/assistant-turn.js +1 -1
  360. package/dist/session-timeline/async-questions.js +1 -1
  361. package/dist/session-timeline/edited-files-card.js +1 -1
  362. package/dist/session-timeline/history-timeline.js +1 -1
  363. package/dist/session-timeline/host.js +1 -1
  364. package/dist/session-timeline/navigation-rail.js +1 -1
  365. package/dist/session-timeline/plan.js +1 -1
  366. package/dist/session-timeline/question-reply.js +1 -1
  367. package/dist/session-timeline/resource-content.js +1 -1
  368. package/dist/session-timeline/session-timeline.js +1 -1
  369. package/dist/session-timeline/timeline-registry.js +1 -1
  370. package/dist/session-timeline/turn-activity.js +1 -1
  371. package/dist/session-timeline/turn-error.js +1 -1
  372. package/dist/session-timeline/turn-retry.js +1 -1
  373. package/dist/session-timeline/turn-time.js +1 -1
  374. package/dist/session-timeline/turns.js +1 -1
  375. package/dist/session-timeline/use-timeline-scroll.js +1 -1
  376. package/dist/session-timeline/user-message.js +1 -1
  377. package/dist/settings/codex-account-card.d.ts +18 -0
  378. package/dist/settings/codex-account-card.js +1 -0
  379. package/dist/settings/login-card.d.ts +6 -0
  380. package/dist/settings/login-card.js +1 -0
  381. package/dist/settings/model-alias-settings.d.ts +6 -0
  382. package/dist/settings/model-alias-settings.js +1 -0
  383. package/dist/settings/model-aliases.d.ts +17 -0
  384. package/dist/settings/model-aliases.js +1 -0
  385. package/dist/settings/provider-logos.d.ts +5 -0
  386. package/dist/settings/provider-logos.js +1 -0
  387. package/dist/settings/provider-section.d.ts +52 -0
  388. package/dist/settings/provider-section.js +1 -0
  389. package/dist/settings/providers-port.d.ts +32 -0
  390. package/dist/settings/providers-port.js +1 -0
  391. package/dist/settings/providers.d.ts +92 -0
  392. package/dist/settings/providers.js +1 -0
  393. package/dist/settings/settings-bridge.d.ts +39 -0
  394. package/dist/settings/settings-bridge.js +1 -0
  395. package/dist/settings/settings.d.ts +9 -0
  396. package/dist/settings/settings.js +1 -0
  397. package/dist/stage.d.ts +1 -0
  398. package/dist/stage.js +1 -1
  399. package/emojibase/LICENSE +21 -0
  400. package/emojibase/en/data.json +51183 -0
  401. package/emojibase/en/messages.json +124 -0
  402. package/emojibase/zh/data.json +48992 -0
  403. package/emojibase/zh/messages.json +124 -0
  404. package/licenses/_dnd-kit_core-LICENSE +21 -0
  405. package/licenses/_dnd-kit_sortable-LICENSE +21 -0
  406. package/licenses/_dnd-kit_utilities-LICENSE +21 -0
  407. package/licenses/_solar-icons_react-LICENSE +11 -0
  408. package/licenses/_solar-icons_react-LICENSE-THIRD-PARTY +14 -0
  409. package/licenses/frimousse-LICENSE +21 -0
  410. package/package.json +35 -3
  411. package/rust/Cargo.lock +3844 -0
  412. package/rust/Cargo.toml +29 -0
  413. package/rust/build.rs +16 -0
  414. package/rust/permissions/autogenerated/reference.md +296 -0
  415. package/rust/permissions/default.toml +20 -0
  416. package/rust/permissions/schemas/schema.json +292 -0
  417. package/rust/src/lib.rs +79 -0
  418. package/rust/src/providers/managed.rs +801 -0
  419. package/rust/src/providers/tests.rs +681 -0
  420. package/rust/src/providers.rs +984 -0
  421. package/rust/src/skills.rs +130 -0
  422. package/dist/chunk-04mj5ftg.js +0 -7
  423. package/dist/chunk-0jvfabsq.js +0 -2
  424. package/dist/chunk-107y8e8x.js +0 -2
  425. package/dist/chunk-22h5rh2h.js +0 -2
  426. package/dist/chunk-31yt34hy.js +0 -2
  427. package/dist/chunk-3hp5t5wf.js +0 -2
  428. package/dist/chunk-3jcx1ns0.js +0 -2
  429. package/dist/chunk-3jjc06nd.js +0 -3
  430. package/dist/chunk-3z8ajtxp.js +0 -2
  431. package/dist/chunk-4b3g7acq.js +0 -2
  432. package/dist/chunk-4jkg9p4g.js +0 -2
  433. package/dist/chunk-4xmbve71.js +0 -4
  434. package/dist/chunk-50mckd2p.js +0 -2
  435. package/dist/chunk-54qxv3er.js +0 -2
  436. package/dist/chunk-5bz1bzsw.js +0 -2
  437. package/dist/chunk-5dk4xga8.js +0 -2
  438. package/dist/chunk-5my9w4vd.js +0 -2
  439. package/dist/chunk-5tqygmg9.js +0 -2
  440. package/dist/chunk-7dd374an.js +0 -2
  441. package/dist/chunk-7s7txz2j.js +0 -2
  442. package/dist/chunk-8hbwf0qe.js +0 -2
  443. package/dist/chunk-8yj3q7n2.js +0 -2
  444. package/dist/chunk-9eqezb4k.js +0 -2
  445. package/dist/chunk-9xfv8jdn.js +0 -2
  446. package/dist/chunk-a3s36z4s.js +0 -3
  447. package/dist/chunk-a414w7ah.js +0 -3
  448. package/dist/chunk-am6tss41.js +0 -2
  449. package/dist/chunk-b65w6x23.js +0 -2
  450. package/dist/chunk-cv2j9sjp.js +0 -2
  451. package/dist/chunk-d1trg76g.js +0 -2
  452. package/dist/chunk-d6c0mnth.js +0 -2
  453. package/dist/chunk-dgm4gxkj.js +0 -2
  454. package/dist/chunk-e6ddpdxn.js +0 -2
  455. package/dist/chunk-e92r4g3v.js +0 -2
  456. package/dist/chunk-e9znmqdj.js +0 -2
  457. package/dist/chunk-eyfdn4p3.js +0 -2
  458. package/dist/chunk-fcqwzmkd.js +0 -2
  459. package/dist/chunk-fkwafga0.js +0 -2
  460. package/dist/chunk-gap8n0vv.js +0 -5
  461. package/dist/chunk-j5rd55qs.js +0 -3
  462. package/dist/chunk-j9q2s4kq.js +0 -2
  463. package/dist/chunk-jnena0v6.js +0 -2
  464. package/dist/chunk-kkps1qd4.js +0 -4
  465. package/dist/chunk-mpnv2rht.js +0 -2
  466. package/dist/chunk-mtydzse4.js +0 -2
  467. package/dist/chunk-mw9k08ky.js +0 -3
  468. package/dist/chunk-px6nrr87.js +0 -2
  469. package/dist/chunk-pzmd5d3m.js +0 -2
  470. package/dist/chunk-q5az5kp2.js +0 -4
  471. package/dist/chunk-qqm07rfv.js +0 -2
  472. package/dist/chunk-qv7kkv47.js +0 -2
  473. package/dist/chunk-rq04p6pn.js +0 -3
  474. package/dist/chunk-rx9sdjtn.js +0 -2
  475. package/dist/chunk-s0b5g8nc.js +0 -2
  476. package/dist/chunk-syp06z39.js +0 -2
  477. package/dist/chunk-t6cfjn19.js +0 -2
  478. package/dist/chunk-vsff9djs.js +0 -2
  479. package/dist/chunk-vvq50011.js +0 -2
  480. package/dist/chunk-wkvm8f2e.js +0 -2
  481. package/dist/chunk-x0tbzjqc.js +0 -2
  482. package/dist/chunk-x480gyp7.js +0 -2
@@ -0,0 +1,984 @@
1
+ //! Application-owned provider credentials. Webviews receive only configured/region metadata.
2
+ //! Independent provider changes apply under Runtime admission; busy session routing stays pinned.
3
+ pub mod managed;
4
+
5
+ use crate::RuntimeAccess;
6
+ use alwith_api::{ResponseError, RuntimeClient};
7
+ use serde::{Deserialize, Serialize};
8
+ use serde_json::{Value, json};
9
+ use std::{
10
+ collections::{BTreeMap, BTreeSet},
11
+ io::Write,
12
+ path::{Path, PathBuf},
13
+ sync::Arc,
14
+ time::Instant,
15
+ };
16
+ use tauri::{AppHandle, Emitter, Manager, State};
17
+
18
+ /// Every snapshot change; the payload is a [`Snapshot`].
19
+ pub const CHANGED_EVENT: &str = "providers:changed";
20
+ /// The file in the application data directory holding credentials, custom providers and the account cache.
21
+ pub const STORE_FILE: &str = "runtime-providers.json";
22
+ /// The directory in the application data directory the bundled model catalogs are written to.
23
+ pub const CATALOG_DIRECTORY: &str = "model-catalogs";
24
+
25
+ const PROVIDER_CATALOG: &str = include_str!("../../assets/provider-catalog.json");
26
+ /// Bundled Codex model catalogs, by the relative path `provider-catalog.json` names them with.
27
+ const MODEL_CATALOGS: &[(&str, &str)] = &[
28
+ ("alwith/models.json", include_str!("../../assets/catalogs/alwith/models.json")),
29
+ ("custom/models.json", include_str!("../../assets/catalogs/custom/models.json")),
30
+ ("deepseek/models.json", include_str!("../../assets/catalogs/deepseek/models.json")),
31
+ ("openrouter/models.json", include_str!("../../assets/catalogs/openrouter/models.json")),
32
+ ("qwen/models.json", include_str!("../../assets/catalogs/qwen/models.json")),
33
+ ("xai/models.json", include_str!("../../assets/catalogs/xai/models.json")),
34
+ ];
35
+
36
+ fn bundled_catalog(relative: &str) -> &'static str {
37
+ MODEL_CATALOGS.iter().find(|(path, _)| *path == relative).map(|(_, contents)| *contents).expect("bundled catalog")
38
+ }
39
+
40
+ #[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
41
+ #[serde(rename_all = "camelCase")]
42
+ struct Credential {
43
+ api_key: String,
44
+ region: Option<String>,
45
+ #[serde(default, skip_serializing_if = "Option::is_none")]
46
+ base_url: Option<String>,
47
+ }
48
+ #[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
49
+ #[serde(rename_all = "camelCase", deny_unknown_fields)]
50
+ pub struct CustomModel {
51
+ label: String,
52
+ #[serde(rename = "api_id")]
53
+ api_id: String,
54
+ #[serde(default, skip_serializing_if = "Option::is_none")]
55
+ context_window: Option<u64>,
56
+ #[serde(default, skip_serializing_if = "Option::is_none")]
57
+ description: Option<String>,
58
+ }
59
+ #[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
60
+ #[serde(rename_all = "camelCase")]
61
+ struct CustomProvider {
62
+ id: String,
63
+ name: String,
64
+ base_url: String,
65
+ models: Vec<CustomModel>,
66
+ api_key: String,
67
+ }
68
+ #[derive(Clone, Default, Debug, Deserialize, Serialize)]
69
+ struct Saved {
70
+ revision: u64,
71
+ #[serde(default)]
72
+ credentials: BTreeMap<String, Credential>,
73
+ #[serde(default)]
74
+ custom_providers: BTreeMap<String, CustomProvider>,
75
+ #[serde(default)]
76
+ managed: Option<managed::Cache>,
77
+ }
78
+ #[derive(Clone, Serialize)]
79
+ #[serde(rename_all = "camelCase")]
80
+ pub struct Snapshot {
81
+ revision: u64,
82
+ applied_revision: Option<u64>,
83
+ providers: BTreeMap<String, Metadata>,
84
+ custom_providers: Vec<PublicCustomProvider>,
85
+ #[serde(skip_serializing_if = "Vec::is_empty")]
86
+ managed_providers: Vec<PublicCustomProvider>,
87
+ status: &'static str,
88
+ error: Option<String>,
89
+ }
90
+ #[derive(Clone, Serialize)]
91
+ pub struct Metadata {
92
+ configured: bool,
93
+ region: Option<String>,
94
+ base_url: Option<String>,
95
+ }
96
+ #[derive(Clone, Serialize)]
97
+ #[serde(rename_all = "camelCase")]
98
+ pub struct PublicCustomProvider {
99
+ id: String,
100
+ name: String,
101
+ base_url: String,
102
+ models: Vec<CustomModel>,
103
+ }
104
+ struct Inner {
105
+ managed_active: bool,
106
+ saved: Saved,
107
+ applied: BTreeMap<String, AppliedProvider>,
108
+ applied_revision: Option<u64>,
109
+ error: Option<String>,
110
+ }
111
+ /// The plugin's managed state.
112
+ pub struct Providers {
113
+ runtime: Arc<dyn RuntimeAccess>,
114
+ catalogs: PathBuf,
115
+ managed: managed::State,
116
+ auxiliary: tokio::sync::Mutex<BTreeMap<String, Inner>>,
117
+ path: PathBuf,
118
+ inner: tokio::sync::Mutex<Inner>,
119
+ }
120
+ #[derive(Deserialize)]
121
+ #[serde(rename_all = "camelCase", deny_unknown_fields)]
122
+ pub struct Input {
123
+ #[serde(default)]
124
+ api_key: Option<String>,
125
+ #[serde(default)]
126
+ region: Option<String>,
127
+ #[serde(default)]
128
+ base_url: Option<String>,
129
+ }
130
+ #[derive(Deserialize)]
131
+ #[serde(rename_all = "camelCase", deny_unknown_fields)]
132
+ pub struct CustomInput {
133
+ #[serde(default)]
134
+ id: Option<String>,
135
+ name: String,
136
+ #[serde(default)]
137
+ api_key: Option<String>,
138
+ base_url: String,
139
+ models: Vec<CustomModel>,
140
+ }
141
+ #[derive(Clone, PartialEq)]
142
+ enum AppliedProvider {
143
+ BuiltIn(Credential),
144
+ Custom(CustomProvider),
145
+ }
146
+ #[derive(Serialize)]
147
+ #[serde(rename_all = "camelCase")]
148
+ pub struct TestResult {
149
+ ok: bool,
150
+ code: &'static str,
151
+ message: String,
152
+ status: Option<u16>,
153
+ latency_ms: Option<u128>,
154
+ }
155
+
156
+ impl Providers {
157
+ pub(crate) fn load(app: &AppHandle, runtime: Arc<dyn RuntimeAccess>) -> Result<Self, Box<dyn std::error::Error>> {
158
+ let data = app.path().app_data_dir()?;
159
+ let path = data.join(STORE_FILE);
160
+ let saved = match std::fs::read(&path) {
161
+ Ok(bytes) => serde_json::from_slice(&bytes)?,
162
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => Saved::default(),
163
+ Err(error) => return Err(error.into()),
164
+ };
165
+ let catalogs = data.join(CATALOG_DIRECTORY);
166
+ write_model_catalogs(&catalogs)?;
167
+ Ok(Self {
168
+ runtime,
169
+ catalogs,
170
+ managed: managed::State::default(),
171
+ auxiliary: tokio::sync::Mutex::new(BTreeMap::new()),
172
+ path,
173
+ inner: tokio::sync::Mutex::new(Inner {
174
+ managed_active: false,
175
+ saved,
176
+ applied: BTreeMap::new(),
177
+ applied_revision: None,
178
+ error: None,
179
+ }),
180
+ })
181
+ }
182
+ /// Forget what the previous Runtime applied; call when the Runtime (re)starts.
183
+ pub async fn reset(&self) {
184
+ self.managed.gate.lock().unwrap().targets.remove(MAIN_AGENT);
185
+ let mut inner = self.inner.lock().await;
186
+ inner.applied.clear();
187
+ inner.applied_revision = None;
188
+ inner.error = None;
189
+ }
190
+ }
191
+ impl Inner {
192
+ fn snapshot(&self) -> Snapshot {
193
+ Snapshot {
194
+ revision: self.saved.revision,
195
+ applied_revision: self.applied_revision,
196
+ providers: self
197
+ .saved
198
+ .credentials
199
+ .iter()
200
+ .map(|(id, key)| {
201
+ (
202
+ id.clone(),
203
+ Metadata { configured: true, region: key.region.clone(), base_url: key.base_url.clone() },
204
+ )
205
+ })
206
+ .collect(),
207
+ custom_providers: self
208
+ .saved
209
+ .custom_providers
210
+ .values()
211
+ .map(|provider| PublicCustomProvider {
212
+ id: provider.id.clone(),
213
+ name: provider.name.clone(),
214
+ base_url: provider.base_url.clone(),
215
+ models: provider.models.clone(),
216
+ })
217
+ .collect(),
218
+ managed_providers: self
219
+ .saved
220
+ .managed
221
+ .as_ref()
222
+ .filter(|_| self.managed_active)
223
+ .and_then(|cache| cache.provider.as_ref())
224
+ .map(|provider| {
225
+ vec![PublicCustomProvider {
226
+ id: provider.id.clone(),
227
+ name: provider.name.clone(),
228
+ base_url: provider.base_url.clone(),
229
+ models: provider.models.clone(),
230
+ }]
231
+ })
232
+ .unwrap_or_default(),
233
+ status: if self.error.is_some() {
234
+ "failed"
235
+ } else if self.applied_revision == Some(self.saved.revision) {
236
+ "applied"
237
+ } else {
238
+ "pending"
239
+ },
240
+ error: self.error.clone(),
241
+ }
242
+ }
243
+ }
244
+
245
+ fn emit(app: &AppHandle, snapshot: &Snapshot) {
246
+ if let Err(error) = app.emit(CHANGED_EVENT, snapshot) {
247
+ log::warn!("Provider catalog: cannot emit {CHANGED_EVENT}: {error}");
248
+ }
249
+ }
250
+
251
+ /// The Codex agent the main conversation runs on.
252
+ pub const MAIN_AGENT: &str = "codex";
253
+
254
+ /// Writes the bundled model catalogs under `directory` (unchanged files are left alone).
255
+ fn write_model_catalogs(directory: &Path) -> Result<(), String> {
256
+ for (relative, contents) in MODEL_CATALOGS {
257
+ let path = directory.join(relative);
258
+ if std::fs::read(&path).is_ok_and(|current| current == contents.as_bytes()) {
259
+ continue;
260
+ }
261
+ let parent = path.parent().ok_or("Model catalog path has no directory")?;
262
+ std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
263
+ let mut file = tempfile::NamedTempFile::new_in(parent).map_err(|e| e.to_string())?;
264
+ file.write_all(contents.as_bytes()).map_err(|e| e.to_string())?;
265
+ file.persist(&path).map_err(|e| e.error.to_string())?;
266
+ }
267
+ Ok(())
268
+ }
269
+
270
+ /// Provider model catalogs for a Codex bootstrap that merges them before Codex starts (U's
271
+ /// `CODEX_ACP_MODEL_CATALOGS`). Gateway entries remain hidden in the native catalog; the adapter
272
+ /// advertises only the models registered by configured providers.
273
+ pub fn bundled_model_catalogs(app: &AppHandle) -> Result<Vec<PathBuf>, String> {
274
+ catalog_paths(&app.state::<Providers>().catalogs)
275
+ }
276
+
277
+ fn catalog_paths(directory: &Path) -> Result<Vec<PathBuf>, String> {
278
+ catalog()
279
+ .iter()
280
+ .filter_map(|provider| provider["catalog"].as_str())
281
+ .chain(std::iter::once("custom/models.json"))
282
+ .map(|relative| {
283
+ let path = directory.join(relative);
284
+ if path.is_file() { Ok(path) } else { Err(format!("Model catalog missing at {}", path.display())) }
285
+ })
286
+ .collect()
287
+ }
288
+
289
+ fn catalog() -> Vec<Value> {
290
+ serde_json::from_str(PROVIDER_CATALOG).expect("bundled provider catalog")
291
+ }
292
+ fn managed_definition() -> Value {
293
+ catalog()
294
+ .into_iter()
295
+ .find(|provider| provider["id"] == managed::ID && provider["source"] == "account")
296
+ .expect("bundled ALwith account configuration")
297
+ }
298
+
299
+ fn apply_managed_model_overrides(models: &mut Value) {
300
+ let definition = managed_definition();
301
+ let catalog: Value =
302
+ serde_json::from_str(bundled_catalog("alwith/models.json")).expect("bundled ALwith model catalog");
303
+ for model in models.as_array_mut().expect("provider models") {
304
+ if let Some(configured) =
305
+ definition["models"].as_array().expect("configured models").iter().find(|entry| entry["id"] == model["id"])
306
+ {
307
+ model["label"] = configured["label"].clone();
308
+ }
309
+ if let Some(entry) =
310
+ catalog["models"].as_array().expect("catalog models").iter().find(|entry| entry["slug"] == model["id"])
311
+ {
312
+ model["contextWindow"] = entry["context_window"].clone();
313
+ }
314
+ }
315
+ }
316
+
317
+ fn has_custom_model_metadata(provider: &CustomProvider) -> bool {
318
+ let catalog: Value =
319
+ serde_json::from_str(bundled_catalog("custom/models.json")).expect("bundled custom model catalog");
320
+ provider.models.iter().any(|model| {
321
+ catalog["models"].as_array().expect("catalog models").iter().any(|entry| entry["slug"] == model.api_id)
322
+ })
323
+ }
324
+
325
+ fn definition(id: &str) -> Result<Value, String> {
326
+ catalog().into_iter().find(|v| v["id"] == id && v["source"] != "account").ok_or("Unknown provider".into())
327
+ }
328
+ fn update(saved: &Saved, id: String, input: Option<Input>, expected_revision: u64) -> Result<Saved, String> {
329
+ if saved.revision != expected_revision {
330
+ return Err("Provider settings changed in another window; reload and retry".into());
331
+ }
332
+ let provider = definition(&id)?;
333
+ let mut credentials = saved.credentials.clone();
334
+ if let Some(input) = input {
335
+ let region = if let Some(regions) = provider["regions"].as_array() {
336
+ let selected = input.region.as_deref().unwrap_or_else(|| regions[0]["id"].as_str().expect("region id"));
337
+ if !regions.iter().any(|r| r["id"] == selected) {
338
+ return Err("Unknown provider region".into());
339
+ }
340
+ Some(selected.to_string())
341
+ } else {
342
+ None
343
+ };
344
+ let api_key = match input.api_key {
345
+ Some(key) if !key.trim().is_empty() => key.trim().to_string(),
346
+ Some(_) => return Err("API key cannot be empty".into()),
347
+ None => credentials.get(&id).ok_or("Configure an API key first")?.api_key.clone(),
348
+ };
349
+ let base_url = match input.base_url {
350
+ Some(value) if !value.trim().is_empty() => Some(normalize_base_url(&value)?),
351
+ Some(_) => None,
352
+ None => credentials.get(&id).and_then(|current| current.base_url.clone()),
353
+ };
354
+ credentials.insert(id, Credential { api_key, region, base_url });
355
+ } else {
356
+ credentials.remove(&id);
357
+ }
358
+ Ok(Saved {
359
+ managed: saved.managed.clone(),
360
+ revision: saved.revision.checked_add(1).ok_or("Provider revision exhausted")?,
361
+ credentials,
362
+ custom_providers: saved.custom_providers.clone(),
363
+ })
364
+ }
365
+
366
+ fn normalize_base_url(value: &str) -> Result<String, String> {
367
+ let mut url = reqwest::Url::parse(value.trim()).map_err(|_| "API base URL is invalid".to_string())?;
368
+ let local_http = url.scheme() == "http" && matches!(url.host_str(), Some("localhost" | "127.0.0.1" | "::1"));
369
+ if url.scheme() != "https" && !local_http {
370
+ return Err("API base URL must use HTTPS (HTTP is allowed only for localhost)".into());
371
+ }
372
+ if url.query().is_some() || url.fragment().is_some() || !url.username().is_empty() || url.password().is_some() {
373
+ return Err("API base URL cannot contain credentials, query parameters, or a fragment".into());
374
+ }
375
+ let trimmed = url.path().trim_end_matches('/').to_string();
376
+ url.set_path(if trimmed.is_empty() { "" } else { &trimmed });
377
+ Ok(url.to_string().trim_end_matches('/').to_string())
378
+ }
379
+
380
+ fn update_custom(saved: &Saved, input: CustomInput, expected_revision: u64) -> Result<Saved, String> {
381
+ if saved.revision != expected_revision {
382
+ return Err("Provider settings changed in another window; reload and retry".into());
383
+ }
384
+ let id = input.id.unwrap_or_else(|| format!("custom_{}", uuid::Uuid::new_v4().simple()));
385
+ if !id.starts_with("custom_") {
386
+ return Err("Custom provider ID is invalid".into());
387
+ }
388
+ let name = input.name.trim();
389
+ if name.is_empty() {
390
+ return Err("Provider name cannot be empty".into());
391
+ }
392
+ if input.models.is_empty() {
393
+ return Err("Add at least one model".into());
394
+ }
395
+ let mut ids = BTreeSet::new();
396
+ let models = input
397
+ .models
398
+ .into_iter()
399
+ .map(|mut model| {
400
+ model.label = model.label.trim().to_string();
401
+ model.api_id = model.api_id.trim().to_string();
402
+ if model.label.is_empty() || model.api_id.is_empty() {
403
+ return Err("Model label and API ID cannot be empty".to_string());
404
+ }
405
+ if !ids.insert(model.api_id.clone()) {
406
+ return Err("Model IDs must be unique".to_string());
407
+ }
408
+ if model.context_window == Some(0) {
409
+ return Err("Model context window must be greater than zero".to_string());
410
+ }
411
+ Ok(model)
412
+ })
413
+ .collect::<Result<Vec<_>, _>>()?;
414
+ let mut custom_providers = saved.custom_providers.clone();
415
+ let api_key = match input.api_key {
416
+ Some(value) if !value.trim().is_empty() => value.trim().to_string(),
417
+ Some(_) => return Err("API key cannot be empty".into()),
418
+ None => custom_providers.get(&id).ok_or("Configure an API key first")?.api_key.clone(),
419
+ };
420
+ custom_providers.insert(
421
+ id.clone(),
422
+ CustomProvider { id, name: name.to_string(), base_url: normalize_base_url(&input.base_url)?, models, api_key },
423
+ );
424
+ Ok(Saved {
425
+ managed: saved.managed.clone(),
426
+ revision: saved.revision.checked_add(1).ok_or("Provider revision exhausted")?,
427
+ credentials: saved.credentials.clone(),
428
+ custom_providers,
429
+ })
430
+ }
431
+
432
+ fn remove_custom(saved: &Saved, id: &str, expected_revision: u64) -> Result<Saved, String> {
433
+ if saved.revision != expected_revision {
434
+ return Err("Provider settings changed in another window; reload and retry".into());
435
+ }
436
+ let mut custom_providers = saved.custom_providers.clone();
437
+ if custom_providers.remove(id).is_none() {
438
+ return Err("Unknown custom provider".into());
439
+ }
440
+ Ok(Saved {
441
+ managed: saved.managed.clone(),
442
+ revision: saved.revision.checked_add(1).ok_or("Provider revision exhausted")?,
443
+ credentials: saved.credentials.clone(),
444
+ custom_providers,
445
+ })
446
+ }
447
+
448
+ fn classify_response_failure(status: u16, body: &str, secret: &str) -> TestResult {
449
+ let code = match status {
450
+ 401 | 403 => "unauthorized",
451
+ 404 => "not_found",
452
+ 429 => "rate_limited",
453
+ 400..=499 => "request_rejected",
454
+ _ => "server_error",
455
+ };
456
+ let parsed = serde_json::from_str::<Value>(body).ok();
457
+ let detail = parsed
458
+ .as_ref()
459
+ .and_then(|value| {
460
+ value.pointer("/error/message").or_else(|| value.get("message")).or_else(|| value.get("detail"))
461
+ })
462
+ .and_then(Value::as_str)
463
+ .unwrap_or("The provider rejected the connection test");
464
+ let mut message = detail.replace(secret, "[redacted]");
465
+ message.truncate(message.floor_char_boundary(300));
466
+ TestResult { ok: false, code, message, status: Some(status), latency_ms: None }
467
+ }
468
+
469
+ fn classify_success_response(status: u16, body: &str, latency_ms: u128) -> TestResult {
470
+ let parsed = serde_json::from_str::<Value>(body).ok();
471
+ let valid = parsed.as_ref().is_some_and(|value| {
472
+ value["object"] == "response"
473
+ && matches!(value["status"].as_str(), Some("completed" | "incomplete"))
474
+ && value.get("error").is_none_or(Value::is_null)
475
+ });
476
+ if !valid {
477
+ return TestResult {
478
+ ok: false,
479
+ code: "invalid_response",
480
+ message: "The endpoint did not return a successful Responses API result".into(),
481
+ status: Some(status),
482
+ latency_ms: Some(latency_ms),
483
+ };
484
+ }
485
+ TestResult {
486
+ ok: true,
487
+ code: "ok",
488
+ message: "Connection succeeded".into(),
489
+ status: Some(status),
490
+ latency_ms: Some(latency_ms),
491
+ }
492
+ }
493
+ fn persist(path: &Path, saved: &Saved) -> Result<(), String> {
494
+ let directory = path.parent().ok_or("Provider path has no directory")?;
495
+ std::fs::create_dir_all(directory).map_err(|e| e.to_string())?;
496
+ // NamedTempFile is private (0600 on Unix); replacement never exposes a partially written key.
497
+ let mut file = tempfile::NamedTempFile::new_in(directory).map_err(|e| e.to_string())?;
498
+ file.write_all(&serde_json::to_vec(saved).map_err(|e| e.to_string())?).map_err(|e| e.to_string())?;
499
+ file.as_file().sync_all().map_err(|e| e.to_string())?;
500
+ file.persist(path).map_err(|e| e.error.to_string())?;
501
+ Ok(())
502
+ }
503
+ #[tauri::command]
504
+ pub(crate) async fn providers_read(state: State<'_, Providers>) -> Result<Snapshot, String> {
505
+ Ok(state.inner.lock().await.snapshot())
506
+ }
507
+ #[tauri::command]
508
+ pub(crate) async fn providers_save(
509
+ app: AppHandle, state: State<'_, Providers>, provider_id: String, input: Option<Input>, expected_revision: u64,
510
+ ) -> Result<Snapshot, String> {
511
+ let _admission = state.runtime.admission(&app).lock().await;
512
+ {
513
+ let mut inner = state.inner.lock().await;
514
+ let next = update(&inner.saved, provider_id, input, expected_revision)?;
515
+ persist(&state.path, &next)?;
516
+ inner.saved = next;
517
+ inner.error = None;
518
+ }
519
+ if let Ok(client) = state.runtime.current(&app) {
520
+ let _ = apply_locked(&app, &client).await;
521
+ }
522
+ let snapshot = state.inner.lock().await.snapshot();
523
+ emit(&app, &snapshot);
524
+ Ok(snapshot)
525
+ }
526
+ #[tauri::command]
527
+ pub(crate) async fn providers_save_custom(
528
+ app: AppHandle, state: State<'_, Providers>, input: CustomInput, expected_revision: u64,
529
+ ) -> Result<Snapshot, String> {
530
+ let _admission = state.runtime.admission(&app).lock().await;
531
+ {
532
+ let mut inner = state.inner.lock().await;
533
+ let next = update_custom(&inner.saved, input, expected_revision)?;
534
+ persist(&state.path, &next)?;
535
+ inner.saved = next;
536
+ inner.error = None;
537
+ }
538
+ if let Ok(client) = state.runtime.current(&app) {
539
+ let _ = apply_locked(&app, &client).await;
540
+ }
541
+ let snapshot = state.inner.lock().await.snapshot();
542
+ emit(&app, &snapshot);
543
+ Ok(snapshot)
544
+ }
545
+ #[tauri::command]
546
+ pub(crate) async fn providers_remove_custom(
547
+ app: AppHandle, state: State<'_, Providers>, provider_id: String, expected_revision: u64,
548
+ ) -> Result<Snapshot, String> {
549
+ let _admission = state.runtime.admission(&app).lock().await;
550
+ {
551
+ let mut inner = state.inner.lock().await;
552
+ let next = remove_custom(&inner.saved, &provider_id, expected_revision)?;
553
+ persist(&state.path, &next)?;
554
+ inner.saved = next;
555
+ inner.error = None;
556
+ }
557
+ if let Ok(client) = state.runtime.current(&app) {
558
+ let _ = apply_locked(&app, &client).await;
559
+ }
560
+ let snapshot = state.inner.lock().await.snapshot();
561
+ emit(&app, &snapshot);
562
+ Ok(snapshot)
563
+ }
564
+
565
+ #[tauri::command]
566
+ pub(crate) async fn providers_test(state: State<'_, Providers>, provider_id: String) -> Result<TestResult, String> {
567
+ let config = {
568
+ let inner = state.inner.lock().await;
569
+ test_config(&inner.saved, &provider_id)?
570
+ };
571
+ Ok(test_connection(config).await)
572
+ }
573
+ #[tauri::command]
574
+ pub(crate) async fn providers_apply(app: AppHandle, state: State<'_, Providers>) -> Result<Snapshot, String> {
575
+ // Draft preparation can use the applied catalog while another admission is pending.
576
+ // The admission owner schedules reconciliation when it releases the lock.
577
+ let _admission = try_apply_admission(state.runtime.admission(&app))?;
578
+ let client = state.runtime.current(&app)?;
579
+ apply_locked(&app, &client).await?;
580
+ Ok(state.inner.lock().await.snapshot())
581
+ }
582
+ fn try_apply_admission(admission: &tokio::sync::Mutex<()>) -> Result<tokio::sync::MutexGuard<'_, ()>, String> {
583
+ admission.try_lock().map_err(|_| PROVIDERS_PENDING.to_owned())
584
+ }
585
+
586
+ /// Configures a newly created auxiliary agent (U's Gamepad AI) with the saved providers;
587
+ /// credentials never leave the native host. The host validates which window and agent may ask.
588
+ /// Auxiliary agents are dedicated: ALwith account cleanup may stop them instead of interrupting
589
+ /// the main conversation.
590
+ pub async fn prepare_agent(app: &AppHandle, agent_id: &str) -> Result<(), String> {
591
+ if agent_id == MAIN_AGENT {
592
+ return Err("The main agent is configured by apply".into());
593
+ }
594
+ let providers = app.state::<Providers>();
595
+ let _admission = providers.runtime.admission(app).lock().await;
596
+ let client = providers.runtime.current(app)?;
597
+ if !client.agents().await.map_err(request_error)?.iter().any(|agent| agent["agentId"] == agent_id) {
598
+ return Err("Agent is not running".into());
599
+ }
600
+ let inner = providers.inner.lock().await;
601
+ let saved = inner.saved.clone();
602
+ let managed_active = inner.managed_active && providers.managed.gate.lock().unwrap().account.is_some();
603
+ if managed_active {
604
+ providers.managed.gate.lock().unwrap().targets.insert(agent_id.to_string());
605
+ }
606
+ drop(inner);
607
+ let mut auxiliary = providers.auxiliary.lock().await;
608
+ let ephemeral = auxiliary.entry(agent_id.to_string()).or_insert_with(|| Inner {
609
+ managed_active,
610
+ saved: saved.clone(),
611
+ applied: BTreeMap::new(),
612
+ applied_revision: None,
613
+ error: None,
614
+ });
615
+ ephemeral.saved = saved;
616
+ if ephemeral.managed_active != managed_active {
617
+ ephemeral.applied_revision = None;
618
+ }
619
+ ephemeral.managed_active = managed_active;
620
+ reconcile_target(ephemeral, &client, &providers.catalogs, agent_id).await
621
+ }
622
+
623
+ /// Applies the saved revision once the current admission owner releases the lock: call it when
624
+ /// the Runtime reports a session idle or after a Runtime restart. A failure is recorded in the
625
+ /// snapshot (`status: "failed"`); nothing is repeated automatically.
626
+ pub fn schedule_apply(app: &AppHandle) {
627
+ let app = app.clone();
628
+ tauri::async_runtime::spawn(async move {
629
+ let providers = app.state::<Providers>();
630
+ if let Ok(_transition) = providers.managed.transition.try_lock()
631
+ && let Err(error) = managed::cleanup(&app).await
632
+ {
633
+ let mut inner = providers.inner.lock().await;
634
+ inner.error = Some(error);
635
+ emit(&app, &inner.snapshot());
636
+ return;
637
+ }
638
+ // The last idle notification may arrive while another admission still owns the lock;
639
+ // wait for it so a saved revision cannot remain pending.
640
+ let _admission = providers.runtime.admission(&app).lock().await;
641
+ if let Ok(client) = providers.runtime.current(&app) {
642
+ let _ = apply_locked(&app, &client).await;
643
+ }
644
+ });
645
+ }
646
+ /// Applies the saved revision to the main agent and every prepared auxiliary agent. The caller
647
+ /// holds the Runtime admission lock.
648
+ pub async fn apply_locked(app: &AppHandle, client: &Arc<RuntimeClient>) -> Result<(), String> {
649
+ let state = app.state::<Providers>();
650
+ let mut inner = state.inner.lock().await;
651
+ if state.managed.gate.lock().unwrap().account.is_none() && inner.managed_active {
652
+ inner.managed_active = false;
653
+ inner.applied_revision = None;
654
+ }
655
+ if inner.managed_active && inner.saved.managed.as_ref().is_some_and(|cache| cache.provider.is_some()) {
656
+ state.managed.gate.lock().unwrap().targets.insert(MAIN_AGENT.into());
657
+ }
658
+ let outcome = reconcile(&mut inner, client, &state.catalogs).await;
659
+ emit(app, &inner.snapshot());
660
+ let saved = inner.saved.clone();
661
+ let active = inner.managed_active;
662
+ drop(inner);
663
+ let mut auxiliary = state.auxiliary.lock().await;
664
+ if !auxiliary.is_empty() {
665
+ let live = client.agents().await.map_err(request_error)?;
666
+ auxiliary.retain(|id, _| live.iter().any(|agent| agent["agentId"] == *id));
667
+ for (id, target) in auxiliary.iter_mut() {
668
+ target.saved = saved.clone();
669
+ if target.managed_active != active {
670
+ target.applied_revision = None;
671
+ }
672
+ target.managed_active = active;
673
+ if active {
674
+ state.managed.gate.lock().unwrap().targets.insert(id.clone());
675
+ }
676
+ reconcile_target(target, client, &state.catalogs, id).await?;
677
+ }
678
+ }
679
+ outcome
680
+ }
681
+
682
+ fn request_error(error: ResponseError) -> String {
683
+ let details = error.data.filter(|data| !data.is_null()).map(|data| format!("; data: {data}")).unwrap_or_default();
684
+ format!("Runtime request failed ({}): {}{details}", error.code, error.message)
685
+ }
686
+
687
+ fn custom_model_catalog(models: &[CustomModel]) -> Result<PathBuf, String> {
688
+ use sha2::{Digest, Sha256};
689
+ // Reuse the app's generic coding instructions, with explicit custom endpoint capabilities.
690
+ let template: Value = serde_json::from_str(bundled_catalog("qwen/models.json")).map_err(|e| e.to_string())?;
691
+ let entries: Vec<Value> = models
692
+ .iter()
693
+ .map(|model| {
694
+ json!({
695
+ "slug": model.api_id, "display_name": model.label, "description": model.description,
696
+ "base_instructions": template["models"][0]["base_instructions"],
697
+ "supported_reasoning_levels": [], "shell_type": "shell_command",
698
+ "visibility": "list", "supported_in_api": true, "priority": 0,
699
+ "support_verbosity": false, "supports_reasoning_summary_parameter": false,
700
+ "truncation_policy": {"mode": "bytes", "limit": 10000},
701
+ "experimental_supported_tools": [], "input_modalities": ["text"],
702
+ "context_window": model.context_window, "max_context_window": model.context_window,
703
+ "apply_patch_tool_type": "freeform", "tool_mode": "direct",
704
+ "include_apps_usage_instructions": false
705
+ })
706
+ })
707
+ .collect();
708
+ let bytes = serde_json::to_vec(&json!({"models": entries})).map_err(|e| e.to_string())?;
709
+ let path = std::env::temp_dir().join(format!("alwith-model-catalog-{}.json", hex::encode(Sha256::digest(&bytes))));
710
+ let mut file = tempfile::NamedTempFile::new_in(std::env::temp_dir()).map_err(|e| e.to_string())?;
711
+ file.write_all(&bytes).map_err(|e| e.to_string())?;
712
+ file.persist(&path).map_err(|e| e.to_string())?;
713
+ Ok(path)
714
+ }
715
+
716
+ async fn reconcile(inner: &mut Inner, client: &RuntimeClient, catalogs: &Path) -> Result<(), String> {
717
+ reconcile_target(inner, client, catalogs, MAIN_AGENT).await
718
+ }
719
+
720
+ async fn reconcile_target(
721
+ inner: &mut Inner, client: &RuntimeClient, catalogs: &Path, agent_id: &str,
722
+ ) -> Result<(), String> {
723
+ if inner.applied_revision == Some(inner.saved.revision) {
724
+ return Ok(());
725
+ }
726
+ // The adapter owns session routing and rejects only changes affecting busy sessions.
727
+ // A global Runtime idle check would also block unrelated provider additions.
728
+ let mut pending = false;
729
+ let mut failures = Vec::new();
730
+ let desired: BTreeMap<String, AppliedProvider> = inner
731
+ .saved
732
+ .credentials
733
+ .iter()
734
+ .map(|(id, key)| (id.clone(), AppliedProvider::BuiltIn(key.clone())))
735
+ .chain(
736
+ inner
737
+ .saved
738
+ .custom_providers
739
+ .iter()
740
+ .map(|(id, provider)| (id.clone(), AppliedProvider::Custom(provider.clone()))),
741
+ )
742
+ .chain(
743
+ inner
744
+ .saved
745
+ .managed
746
+ .as_ref()
747
+ .filter(|_| inner.managed_active)
748
+ .and_then(|cache| cache.provider.as_ref())
749
+ .map(|provider| (managed::ID.to_string(), AppliedProvider::Custom(provider.clone()))),
750
+ )
751
+ .collect();
752
+ // A revision without catalog changes does not need an idle boundary.
753
+ if inner.applied == desired {
754
+ inner.applied_revision = Some(inner.saved.revision);
755
+ inner.error = None;
756
+ return Ok(());
757
+ }
758
+ let outcome: Result<(), String> = async {
759
+ for (id, selected) in &desired {
760
+ if inner.applied.get(id) == Some(selected) { continue; }
761
+ let runtime_id = runtime_provider_id(id);
762
+ let (name, base_url, bearer_token, mut models, mut config, bundled_catalog) = match selected {
763
+ AppliedProvider::BuiltIn(key) => {
764
+ let provider = definition(id)?;
765
+ let default_url = match key.region.as_deref() {
766
+ Some(region) => provider["regions"].as_array().and_then(|regions| regions.iter().find(|r| r["id"] == region)).map(|r| r["baseUrl"].clone()).ok_or("Unknown provider region")?,
767
+ None => provider["baseUrl"].clone(),
768
+ };
769
+ (provider["name"].clone(), key.base_url.clone().map(Value::String).unwrap_or(default_url), key.api_key.clone(), provider["models"].clone(), provider.get("config").cloned().unwrap_or(json!({})), provider["catalog"].as_str().map(str::to_string))
770
+ }
771
+ AppliedProvider::Custom(provider) => {
772
+ let known = has_custom_model_metadata(provider);
773
+ (
774
+ Value::String(provider.name.clone()),
775
+ Value::String(provider.base_url.clone()),
776
+ provider.api_key.clone(),
777
+ Value::Array(provider.models.iter().map(|model| json!({
778
+ "id": model.api_id,
779
+ "label": model.label,
780
+ "description": model.description,
781
+ "contextWindow": model.context_window,
782
+ })).collect()),
783
+ // Uncatalogued Responses endpoints use direct tools; catalogued models keep their declared capabilities.
784
+ if known { json!({"web_search": "disabled", "model_reasoning_summary": "none"}) } else { json!({"features": {"code_mode": false, "code_mode_only": false}}) },
785
+ known.then(|| "custom/models.json".to_string()),
786
+ )},
787
+ };
788
+ let bundled_catalog = if id == managed::ID {
789
+ let definition = managed_definition();
790
+ apply_managed_model_overrides(&mut models);
791
+ config = definition["config"].clone();
792
+ definition["catalog"].as_str().map(str::to_string)
793
+ } else {
794
+ bundled_catalog
795
+ };
796
+ if let Some(catalog) = bundled_catalog {
797
+ config["model_catalog_json"] = json!(catalogs.join(catalog));
798
+ } else if let AppliedProvider::Custom(provider) = selected {
799
+ config["model_catalog_json"] = json!(custom_model_catalog(&provider.models)?);
800
+ }
801
+ let result = client.acp_request(agent_id, "providers/set", json!({"providerId":"openai", "apiType":"openai", "baseUrl":base_url,
802
+ "_meta":{"codex":{"id":runtime_id,"name":name,"mode":"catalog","bearerToken":bearer_token,"config":config}, "alwith":{"models":models}}}), None, None)
803
+ ;
804
+ let result = tokio::time::timeout(std::time::Duration::from_secs(10), result).await
805
+ .unwrap_or_else(|_| Err(ResponseError::runtime("Provider configuration timed out")));
806
+ if let Err(error) = result {
807
+ record_application_error(id, "apply", &error, &mut pending, &mut failures);
808
+ continue;
809
+ }
810
+ inner.applied.insert(id.clone(), selected.clone());
811
+ }
812
+ let removed: Vec<_> = inner.applied.keys().filter(|id| !desired.contains_key(*id)).cloned().collect();
813
+ for id in removed {
814
+ let result = client.acp_request(agent_id, "providers/disable", json!({"providerId":"openai","_meta":{"codex":{"id":runtime_provider_id(&id)}}}), None, None)
815
+ ;
816
+ let result = tokio::time::timeout(std::time::Duration::from_secs(10), result).await
817
+ .unwrap_or_else(|_| Err(ResponseError::runtime("Provider configuration timed out")));
818
+ if let Err(error) = result {
819
+ record_application_error(&id, "remove", &error, &mut pending, &mut failures);
820
+ continue;
821
+ }
822
+ inner.applied.remove(&id);
823
+ }
824
+ Ok(())
825
+ }.await;
826
+ inner.error = outcome.err().or_else(|| (!failures.is_empty()).then(|| failures.join("; ")));
827
+ if inner.error.is_none() && !pending {
828
+ inner.applied_revision = Some(inner.saved.revision);
829
+ }
830
+ log::info!(
831
+ "Provider catalog: agent={agent_id} saved_revision={} applied_revision={:?} status={} pending_affected_sessions={pending}",
832
+ inner.saved.revision,
833
+ inner.applied_revision,
834
+ inner.snapshot().status
835
+ );
836
+ if let Some(error) = &inner.error {
837
+ Err(error.clone())
838
+ } else if pending {
839
+ Err(PROVIDERS_PENDING.into())
840
+ } else {
841
+ Ok(())
842
+ }
843
+ }
844
+
845
+ const PROVIDERS_PENDING: &str = "Provider settings are pending; waiting for affected sessions to finish";
846
+
847
+ /// Whether an apply error only means that busy sessions hold the remaining changes.
848
+ pub fn application_pending(error: &str) -> bool {
849
+ error == PROVIDERS_PENDING
850
+ }
851
+
852
+ fn record_application_error(
853
+ id: &str, operation: &str, error: &ResponseError, pending: &mut bool, failures: &mut Vec<String>,
854
+ ) {
855
+ // Match the installed adapter's busy response exactly; other invalid requests are failures.
856
+ let busy = error.code == -32600
857
+ && error.message == "Invalid request: Wait for affected sessions to finish before changing their provider";
858
+ log::warn!("Provider catalog: provider={id} operation={operation} code={} waiting_for_sessions={busy}", error.code);
859
+ if busy {
860
+ *pending = true;
861
+ } else {
862
+ failures.push(format!("Provider {id} could not {operation} ({}); retry to apply saved settings", error.code));
863
+ }
864
+ }
865
+
866
+ /// Preserve saved IDs while encoding custom IDs without collisions for the adapter's [a-z0-9-]+ grammar.
867
+ /// Keep this mapping aligned with gatewayModelId in src/settings/providers.ts.
868
+ fn runtime_provider_id(id: &str) -> String {
869
+ if id.starts_with("custom_") {
870
+ format!("custom-{}", id.bytes().map(|byte| format!("{byte:02x}")).collect::<String>())
871
+ } else {
872
+ id.to_string()
873
+ }
874
+ }
875
+
876
+ #[derive(Clone)]
877
+ struct TestConfig {
878
+ base_url: String,
879
+ api_key: String,
880
+ model: String,
881
+ }
882
+
883
+ fn test_config(saved: &Saved, id: &str) -> Result<TestConfig, String> {
884
+ if let Some(provider) = saved.custom_providers.get(id) {
885
+ return Ok(TestConfig {
886
+ base_url: provider.base_url.clone(),
887
+ api_key: provider.api_key.clone(),
888
+ model: provider.models.first().ok_or("Add at least one model")?.api_id.clone(),
889
+ });
890
+ }
891
+ let key = saved.credentials.get(id).ok_or("Configure and save this provider first")?;
892
+ let provider = definition(id)?;
893
+ let base_url = if let Some(url) = &key.base_url {
894
+ url.clone()
895
+ } else if let Some(region) = key.region.as_deref() {
896
+ provider["regions"]
897
+ .as_array()
898
+ .and_then(|regions| regions.iter().find(|item| item["id"] == region))
899
+ .and_then(|item| item["baseUrl"].as_str())
900
+ .ok_or("Unknown provider region")?
901
+ .to_string()
902
+ } else {
903
+ provider["baseUrl"].as_str().ok_or("Provider has no API base URL")?.to_string()
904
+ };
905
+ let model = provider["models"]
906
+ .as_array()
907
+ .and_then(|models| models.first())
908
+ .and_then(|model| model["id"].as_str())
909
+ .ok_or("Provider has no models")?
910
+ .to_string();
911
+ Ok(TestConfig { base_url, api_key: key.api_key.clone(), model })
912
+ }
913
+
914
+ async fn test_connection(config: TestConfig) -> TestResult {
915
+ let started = Instant::now();
916
+ let client = match reqwest::Client::builder().timeout(std::time::Duration::from_secs(20)).build() {
917
+ Ok(client) => client,
918
+ Err(error) => {
919
+ return TestResult {
920
+ ok: false,
921
+ code: "network",
922
+ message: error.to_string(),
923
+ status: None,
924
+ latency_ms: None,
925
+ };
926
+ }
927
+ };
928
+ let request = match build_test_request(&client, &config) {
929
+ Ok(request) => request,
930
+ Err(error) => {
931
+ return TestResult {
932
+ ok: false,
933
+ code: "request_failed",
934
+ message: error.to_string(),
935
+ status: None,
936
+ latency_ms: None,
937
+ };
938
+ }
939
+ };
940
+ let response = client.execute(request).await;
941
+ match response {
942
+ Ok(response) if response.status().is_success() => {
943
+ let status = response.status().as_u16();
944
+ match response.text().await {
945
+ Ok(body) => classify_success_response(status, &body, started.elapsed().as_millis()),
946
+ Err(error) => TestResult {
947
+ ok: false,
948
+ code: "invalid_response",
949
+ message: error.to_string(),
950
+ status: Some(status),
951
+ latency_ms: Some(started.elapsed().as_millis()),
952
+ },
953
+ }
954
+ }
955
+ Ok(response) => {
956
+ let status = response.status().as_u16();
957
+ let body = response.text().await.unwrap_or_default();
958
+ classify_response_failure(status, &body, &config.api_key)
959
+ }
960
+ Err(error) => {
961
+ let code = if error.is_timeout() {
962
+ "timeout"
963
+ } else if error.is_connect() {
964
+ "network"
965
+ } else {
966
+ "request_failed"
967
+ };
968
+ let mut message = error.to_string().replace(&config.api_key, "[redacted]");
969
+ message.truncate(message.floor_char_boundary(300));
970
+ TestResult { ok: false, code, message, status: None, latency_ms: None }
971
+ }
972
+ }
973
+ }
974
+
975
+ fn build_test_request(client: &reqwest::Client, config: &TestConfig) -> Result<reqwest::Request, reqwest::Error> {
976
+ client
977
+ .post(format!("{}/responses", config.base_url.trim_end_matches('/')))
978
+ .bearer_auth(&config.api_key)
979
+ .json(&json!({"model": config.model, "input": "Reply with OK.", "max_output_tokens": 16, "store": false}))
980
+ .build()
981
+ }
982
+
983
+ #[cfg(test)]
984
+ mod tests;