@ricajs/rica 0.0.0-stage → 0.1.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 (340) hide show
  1. package/LICENSE +661 -0
  2. package/README.md +153 -2
  3. package/admin/assets/CharacterWorkspace-1DS1hQyt.css +1 -0
  4. package/admin/assets/CharacterWorkspace-wPK725zl.js +2 -0
  5. package/admin/assets/ConsoleHome-BWG64JGc.js +1 -0
  6. package/admin/assets/ConsoleHome-Du2ctyD4.css +1 -0
  7. package/admin/assets/CreateAccount-VB0Hg0Oo.js +1 -0
  8. package/admin/assets/CreateAccount-YfoCfhgR.css +1 -0
  9. package/admin/assets/GrowthWorkspace-C10PHKpZ.css +1 -0
  10. package/admin/assets/GrowthWorkspace-Kds9pNFQ.js +1 -0
  11. package/admin/assets/KnowledgeWorkspace-BMA6nsqJ.js +1 -0
  12. package/admin/assets/KnowledgeWorkspace-DhWn2l8R.css +1 -0
  13. package/admin/assets/MembershipWorkspace-o0Vnc47u.js +1 -0
  14. package/admin/assets/MetricsWorkspace-B7hX9jVB.js +1 -0
  15. package/admin/assets/MetricsWorkspace-__TjvlTz.css +1 -0
  16. package/admin/assets/PlanningWorkspace-C5fInwML.css +1 -0
  17. package/admin/assets/PlanningWorkspace-Dg1mJGKs.js +1 -0
  18. package/admin/assets/PluginWorkspace-9j4kXV6x.js +1 -0
  19. package/admin/assets/PluginWorkspace-OgCPHMeV.css +1 -0
  20. package/admin/assets/SecuritySettings-C4GyRpMq.js +1 -0
  21. package/admin/assets/SecuritySettings-DBa2VRXZ.css +1 -0
  22. package/admin/assets/SystemHealth-KyjDkMwy.css +1 -0
  23. package/admin/assets/SystemHealth-rJD8Lfj2.js +1 -0
  24. package/admin/assets/TimeZoneSelect-DjKgHHLQ.js +1 -0
  25. package/admin/assets/UiBadge-BfJoDO3X.js +1 -0
  26. package/admin/assets/UiCombobox-CoLq4WY2.js +1 -0
  27. package/admin/assets/UiDialog-BJTTfzWz.js +3 -0
  28. package/admin/assets/UiField-B8YKSMrG.js +2 -0
  29. package/admin/assets/UiSpinner-CsMdV4kc.js +1 -0
  30. package/admin/assets/console-Bj81RrGj.css +1 -0
  31. package/admin/assets/console-Da8k64eY.js +1 -0
  32. package/admin/assets/console-data-BuMSzMgF.js +1 -0
  33. package/admin/assets/dist-BjB-W5oC.js +57 -0
  34. package/admin/assets/index-CkMVftFK.js +4 -0
  35. package/admin/assets/index-DeJZoKJC.css +1 -0
  36. package/admin/assets/management-Ci5Yl-iD.js +1 -0
  37. package/admin/assets/plugin-integrations-C9DuWlXS.css +1 -0
  38. package/admin/assets/plugin-integrations-VFsmCvor.js +1 -0
  39. package/admin/assets/plugin-status-DvTwmog1.js +1 -0
  40. package/admin/index.html +25 -0
  41. package/apps/api/admin-auth-routes.d.ts +8 -0
  42. package/apps/api/admin-auth-routes.js +280 -0
  43. package/apps/api/admin-auth.d.ts +41 -0
  44. package/apps/api/admin-auth.js +74 -0
  45. package/apps/api/app.d.ts +7 -0
  46. package/apps/api/app.js +20 -0
  47. package/apps/api/main.d.ts +1 -0
  48. package/apps/api/main.js +107 -0
  49. package/apps/api/management.d.ts +25 -0
  50. package/apps/api/management.js +952 -0
  51. package/apps/auto-review.js +17 -0
  52. package/apps/deployment-plugin-contracts.js +24 -0
  53. package/apps/deployment-plugins.js +84 -0
  54. package/apps/plugin-observation.js +83 -0
  55. package/apps/plugin-releases.js +55 -0
  56. package/apps/plugin-status-view.js +14 -0
  57. package/apps/runtime-plugins.js +85 -0
  58. package/apps/worker/main.d.ts +1 -0
  59. package/apps/worker/main.js +84 -0
  60. package/apps/worker/outbox.d.ts +13 -0
  61. package/apps/worker/outbox.js +201 -0
  62. package/apps/worker/retention.d.ts +1 -0
  63. package/apps/worker/retention.js +16 -0
  64. package/apps/worker/runtime-retention.d.ts +2 -0
  65. package/apps/worker/runtime-retention.js +5 -0
  66. package/apps/worker/simulation.d.ts +1 -0
  67. package/apps/worker/simulation.js +51 -0
  68. package/bin/rica.js +33 -0
  69. package/compose.yaml +27 -0
  70. package/env.example +15 -0
  71. package/package.json +43 -3
  72. package/prisma/migrations/20261109000000_init/migration.sql +6544 -0
  73. package/prisma/migrations/20261109010000_console_simulation/migration.sql +62 -0
  74. package/prisma/migrations/20261109020000_run_audit/migration.sql +15 -0
  75. package/prisma/migrations/20261109030000_connector_queue/migration.sql +6 -0
  76. package/prisma/migrations/20261109040000_console_run_filters/migration.sql +30 -0
  77. package/prisma/migrations/20261109050000_console_run_timeline/migration.sql +34 -0
  78. package/prisma/migrations/20261109060000_connector_read_status/migration.sql +58 -0
  79. package/prisma/migrations/20261109070000_console_knowledge/migration.sql +7 -0
  80. package/prisma/migrations/20261109080000_platform_account_pool/migration.sql +22 -0
  81. package/prisma/migrations/20261109090000_identity_writing_prompt/migration.sql +28 -0
  82. package/prisma/migrations/20261111000000_collaborative_plans/migration.sql +77 -0
  83. package/prisma/migrations/20261111010000_commitment_details/migration.sql +49 -0
  84. package/prisma/migrations/20261111020000_simulation_follow_up/migration.sql +91 -0
  85. package/prisma/migrations/20261111030000_collaborative_ai_follow_up/migration.sql +146 -0
  86. package/prisma/migrations/20261111040000_console_simulation_transcript/migration.sql +105 -0
  87. package/prisma/migrations/20261114000000_newbi_runtime_connection/migration.sql +2 -0
  88. package/prisma/migrations/20261114010000_shared_runtime_database/migration.sql +2 -0
  89. package/prisma/migrations/20261114020000_newbi_account_credentials/migration.sql +32 -0
  90. package/prisma/migrations/20261114030000_remove_unlinked_accounts/migration.sql +1 -0
  91. package/prisma/migrations/20261114040000_newbi_account_profiles/migration.sql +1 -0
  92. package/prisma/migrations/20261115000000_local_user_management/migration.sql +55 -0
  93. package/prisma/migrations/20261115010000_administrator_only_membership/migration.sql +15 -0
  94. package/prisma/migrations/20261115020000_manage_own_passkeys/migration.sql +32 -0
  95. package/prisma/migrations/20261115030000_change_own_password/migration.sql +30 -0
  96. package/prisma/migrations/20261115040000_system_administrators/migration.sql +55 -0
  97. package/prisma/migrations/20261117000000_identity_draft_model_profile/migration.sql +30 -0
  98. package/prisma/migrations/20261118000000_auto_review/migration.sql +9 -0
  99. package/prisma/migrations/20261118010000_internal_core_prompt/migration.sql +62 -0
  100. package/prisma/migrations/20261118020000_hosted_model_usage/migration.sql +42 -0
  101. package/prisma/migrations/migration_lock.toml +1 -0
  102. package/prisma/schema.prisma +1019 -0
  103. package/prisma.config.js +7 -0
  104. package/scripts/admin-user.js +51 -0
  105. package/scripts/plugin-release-manifest.js +17 -0
  106. package/source/.env.example +15 -0
  107. package/source/LICENSE +661 -0
  108. package/source/README.en.md +123 -0
  109. package/source/README.md +154 -0
  110. package/source/apps/admin/index.html +12 -0
  111. package/source/apps/admin/src/app/App.vue +197 -0
  112. package/source/apps/admin/src/app/ConsoleNavigation.vue +56 -0
  113. package/source/apps/admin/src/app/ReviewDesk.vue +825 -0
  114. package/source/apps/admin/src/app/appearance.ts +38 -0
  115. package/source/apps/admin/src/app/console-location.ts +50 -0
  116. package/source/apps/admin/src/app/plugin-integrations.ts +73 -0
  117. package/source/apps/admin/src/features/access/AuditWorkspace.vue +139 -0
  118. package/source/apps/admin/src/features/access/CreateAccount.vue +64 -0
  119. package/source/apps/admin/src/features/access/MembershipWorkspace.vue +54 -0
  120. package/source/apps/admin/src/features/access/SecuritySettings.vue +219 -0
  121. package/source/apps/admin/src/features/characters/CharacterWorkspace.vue +736 -0
  122. package/source/apps/admin/src/features/health/SystemHealth.vue +162 -0
  123. package/source/apps/admin/src/features/home/ConsoleHome.vue +220 -0
  124. package/source/apps/admin/src/features/knowledge/GrowthWorkspace.vue +57 -0
  125. package/source/apps/admin/src/features/knowledge/IdentityGrowth.vue +276 -0
  126. package/source/apps/admin/src/features/knowledge/KnowledgeWorkspace.vue +294 -0
  127. package/source/apps/admin/src/features/knowledge/MemoryGrantWorkspace.vue +199 -0
  128. package/source/apps/admin/src/features/planning/CollaborativePlans.vue +240 -0
  129. package/source/apps/admin/src/features/planning/CommitmentWorkspace.vue +327 -0
  130. package/source/apps/admin/src/features/planning/PlanningWorkspace.vue +155 -0
  131. package/source/apps/admin/src/features/plugins/PluginWorkspace.vue +268 -0
  132. package/source/apps/admin/src/features/plugins/plugin-status.ts +32 -0
  133. package/source/apps/admin/src/features/review/AutoReviewSettings.vue +152 -0
  134. package/source/apps/admin/src/features/runs/MetricsWorkspace.vue +128 -0
  135. package/source/apps/admin/src/features/runs/RunOperations.vue +224 -0
  136. package/source/apps/admin/src/features/runs/SimulationReconciliation.vue +111 -0
  137. package/source/apps/admin/src/features/runs/SimulationWorkspace.vue +476 -0
  138. package/source/apps/admin/src/features/runs/simulation-accounts.ts +13 -0
  139. package/source/apps/admin/src/main.ts +5 -0
  140. package/source/apps/admin/src/shared/TimeZoneSelect.vue +25 -0
  141. package/source/apps/admin/src/styles/console-layout.css +53 -0
  142. package/source/apps/admin/src/styles/console-theme.css +95 -0
  143. package/source/apps/admin/src/vite-env.d.ts +3 -0
  144. package/source/apps/admin/uno.config.ts +8 -0
  145. package/source/apps/admin/vite.config.ts +33 -0
  146. package/source/apps/api/admin-auth-routes.ts +269 -0
  147. package/source/apps/api/admin-auth.test.ts +22 -0
  148. package/source/apps/api/admin-auth.ts +88 -0
  149. package/source/apps/api/app.test.ts +21 -0
  150. package/source/apps/api/app.ts +27 -0
  151. package/source/apps/api/main.ts +105 -0
  152. package/source/apps/api/management-plugins.test.ts +67 -0
  153. package/source/apps/api/management.ts +1055 -0
  154. package/source/apps/api/plugin-releases.test.ts +21 -0
  155. package/source/apps/auto-review.ts +18 -0
  156. package/source/apps/deployment-plugin-contracts.ts +29 -0
  157. package/source/apps/deployment-plugins.ts +87 -0
  158. package/source/apps/plugin-observation.ts +88 -0
  159. package/source/apps/plugin-releases.ts +52 -0
  160. package/source/apps/plugin-status-view.ts +15 -0
  161. package/source/apps/runtime-plugins.ts +105 -0
  162. package/source/apps/worker/main.ts +84 -0
  163. package/source/apps/worker/outbox.ts +201 -0
  164. package/source/apps/worker/retention.ts +16 -0
  165. package/source/apps/worker/runtime-retention.ts +7 -0
  166. package/source/apps/worker/simulation.ts +50 -0
  167. package/source/bin/rica.js +33 -0
  168. package/source/compose.yaml +27 -0
  169. package/source/package.json +77 -0
  170. package/source/packages/console-shared/console-data.ts +83 -0
  171. package/source/packages/console-shared/health.ts +2 -0
  172. package/source/packages/console-shared/package.json +34 -0
  173. package/source/packages/console-shared/request.ts +13 -0
  174. package/source/packages/console-shared/ui/UiAlert.vue +10 -0
  175. package/source/packages/console-shared/ui/UiBadge.vue +7 -0
  176. package/source/packages/console-shared/ui/UiButton.vue +19 -0
  177. package/source/packages/console-shared/ui/UiCheckbox.vue +8 -0
  178. package/source/packages/console-shared/ui/UiCombobox.vue +55 -0
  179. package/source/packages/console-shared/ui/UiDialog.vue +42 -0
  180. package/source/packages/console-shared/ui/UiEmpty.vue +7 -0
  181. package/source/packages/console-shared/ui/UiField.vue +11 -0
  182. package/source/packages/console-shared/ui/UiSpinner.vue +3 -0
  183. package/source/packages/console-shared/ui/index.ts +9 -0
  184. package/source/packages/console-shared/ui/ui.css +113 -0
  185. package/source/packages/contracts/action-review.ts +45 -0
  186. package/source/packages/contracts/auto-review.ts +22 -0
  187. package/source/packages/contracts/commitments.ts +39 -0
  188. package/source/packages/contracts/deployment-plugins.ts +4 -0
  189. package/source/packages/contracts/health.ts +4 -0
  190. package/source/packages/contracts/local-users.ts +8 -0
  191. package/source/packages/contracts/management.ts +246 -0
  192. package/source/packages/contracts/memory.ts +15 -0
  193. package/source/packages/contracts/model-provider.ts +29 -0
  194. package/source/packages/contracts/package.json +43 -0
  195. package/source/packages/contracts/plans.ts +22 -0
  196. package/source/packages/contracts/platform-reader.ts +27 -0
  197. package/source/packages/contracts/platform-reply-executor.ts +10 -0
  198. package/source/packages/contracts/plugin-status.ts +67 -0
  199. package/source/packages/contracts/run-continuity.ts +60 -0
  200. package/source/packages/contracts/schedules.ts +22 -0
  201. package/source/packages/contracts/simulation-follow-up.ts +35 -0
  202. package/source/packages/contracts/simulation-observability.ts +94 -0
  203. package/source/packages/contracts/simulation-platform.ts +39 -0
  204. package/source/packages/persistence/action-review.ts +188 -0
  205. package/source/packages/persistence/auto-review.ts +21 -0
  206. package/source/packages/persistence/client.ts +17 -0
  207. package/source/packages/persistence/console-knowledge.ts +78 -0
  208. package/source/packages/persistence/identity-reflection.ts +13 -0
  209. package/source/packages/persistence/inbound.ts +118 -0
  210. package/source/packages/persistence/management-http.ts +54 -0
  211. package/source/packages/persistence/management.ts +899 -0
  212. package/source/packages/persistence/memory-snapshot.ts +111 -0
  213. package/source/packages/persistence/memory.ts +161 -0
  214. package/source/packages/persistence/package.json +50 -0
  215. package/source/packages/persistence/plans.ts +132 -0
  216. package/source/packages/persistence/run-context.ts +113 -0
  217. package/source/packages/persistence/run-continuity.ts +30 -0
  218. package/source/packages/persistence/simulated-draft.ts +313 -0
  219. package/source/packages/persistence/simulation-execution.ts +203 -0
  220. package/source/packages/persistence/simulation-observability.ts +119 -0
  221. package/source/packages/persistence/simulation-reconciliation.ts +35 -0
  222. package/source/packages/persistence/simulation-retention.ts +8 -0
  223. package/source/packages/persistence/simulation-schedules.ts +87 -0
  224. package/source/packages/plugin-host/package.json +20 -0
  225. package/source/packages/plugin-host/plugin-registry.ts +107 -0
  226. package/source/packages/runtime/config.ts +23 -0
  227. package/source/packages/runtime/memory-ranking.test.ts +45 -0
  228. package/source/packages/runtime/memory-ranking.ts +92 -0
  229. package/source/packages/runtime/package.json +30 -0
  230. package/source/packages/runtime/plugin-registry.test.ts +75 -0
  231. package/source/packages/runtime/settings-directory.ts +10 -0
  232. package/source/packages/runtime/write-settings.ts +20 -0
  233. package/source/packages/runtime/writing-prompts.ts +8 -0
  234. package/source/plugins/hosted-models/README.md +52 -0
  235. package/source/plugins/hosted-models/index.ts +3 -0
  236. package/source/plugins/hosted-models/package.json +44 -0
  237. package/source/plugins/hosted-models/providers/catalog.ts +9 -0
  238. package/source/plugins/hosted-models/providers/client.ts +142 -0
  239. package/source/plugins/hosted-models/providers/config.ts +40 -0
  240. package/source/plugins/hosted-models/providers/usage.ts +49 -0
  241. package/source/plugins/hosted-models/rica/console/ModelSettings.vue +299 -0
  242. package/source/plugins/hosted-models/rica/console/ModelUsage.vue +243 -0
  243. package/source/plugins/hosted-models/rica/console/cards.ts +22 -0
  244. package/source/plugins/hosted-models/rica/console/health.ts +38 -0
  245. package/source/plugins/hosted-models/rica/console/index.ts +3 -0
  246. package/source/plugins/hosted-models/rica/console/labels.ts +11 -0
  247. package/source/plugins/hosted-models/rica/identity.ts +1 -0
  248. package/source/plugins/hosted-models/rica/management/check.ts +42 -0
  249. package/source/plugins/hosted-models/rica/management/contracts.ts +54 -0
  250. package/source/plugins/hosted-models/rica/management/routes.ts +150 -0
  251. package/source/plugins/hosted-models/rica/management/settings.ts +116 -0
  252. package/source/plugins/hosted-models/rica/management/usage-contracts.ts +20 -0
  253. package/source/plugins/hosted-models/rica/model.ts +90 -0
  254. package/source/plugins/hosted-models/rica/persistence/usage.ts +37 -0
  255. package/source/plugins/hosted-models/rica/shared.ts +3 -0
  256. package/source/plugins/hosted-models/tests/model-settings.test.ts +226 -0
  257. package/source/plugins/hosted-models/tests/providers.test.ts +129 -0
  258. package/source/plugins/newbi/README.md +63 -0
  259. package/source/plugins/newbi/agent-api/client.ts +192 -0
  260. package/source/plugins/newbi/agent-api/connection.ts +15 -0
  261. package/source/plugins/newbi/index.ts +4 -0
  262. package/source/plugins/newbi/package.json +42 -0
  263. package/source/plugins/newbi/rica/console/AccountConnectionForm.vue +25 -0
  264. package/source/plugins/newbi/rica/console/ConnectorAccountStatus.vue +186 -0
  265. package/source/plugins/newbi/rica/console/ConnectorReview.vue +393 -0
  266. package/source/plugins/newbi/rica/console/NewbiAccountLabel.vue +21 -0
  267. package/source/plugins/newbi/rica/console/NewbiSettings.vue +29 -0
  268. package/source/plugins/newbi/rica/console/account-integration.ts +104 -0
  269. package/source/plugins/newbi/rica/console/accounts.ts +13 -0
  270. package/source/plugins/newbi/rica/console/card.ts +38 -0
  271. package/source/plugins/newbi/rica/console/health.ts +27 -0
  272. package/source/plugins/newbi/rica/console/index.ts +5 -0
  273. package/source/plugins/newbi/rica/console/labels.ts +16 -0
  274. package/source/plugins/newbi/rica/console/review.ts +27 -0
  275. package/source/plugins/newbi/rica/deployment/catalog.ts +13 -0
  276. package/source/plugins/newbi/rica/deployment/settings.ts +57 -0
  277. package/source/plugins/newbi/rica/integration.md +39 -0
  278. package/source/plugins/newbi/rica/management/api.md +156 -0
  279. package/source/plugins/newbi/rica/management/contracts.ts +95 -0
  280. package/source/plugins/newbi/rica/management/operations.ts +38 -0
  281. package/source/plugins/newbi/rica/management/routes.ts +286 -0
  282. package/source/plugins/newbi/rica/persistence/accounts.ts +40 -0
  283. package/source/plugins/newbi/rica/persistence/database.ts +49 -0
  284. package/source/plugins/newbi/rica/persistence/events.ts +59 -0
  285. package/source/plugins/newbi/rica/persistence/execution.ts +73 -0
  286. package/source/plugins/newbi/rica/persistence/management.ts +256 -0
  287. package/source/plugins/newbi/rica/persistence/retention.ts +3 -0
  288. package/source/plugins/newbi/rica/runtime/agent-adapter.ts +34 -0
  289. package/source/plugins/newbi/rica/runtime/executor.ts +30 -0
  290. package/source/plugins/newbi/rica/runtime/identity.ts +11 -0
  291. package/source/plugins/newbi/rica/runtime/reader.ts +48 -0
  292. package/source/plugins/newbi/rica/shared.ts +6 -0
  293. package/source/plugins/newbi/tests/management.integration.test.ts +938 -0
  294. package/source/plugins/newbi/tests/settings.test.ts +112 -0
  295. package/source/plugins/simulated-model/index.ts +38 -0
  296. package/source/plugins/simulated-model/package.json +24 -0
  297. package/source/plugins/simulated-platforms/index.ts +70 -0
  298. package/source/plugins/simulated-platforms/package.json +24 -0
  299. package/source/pnpm-lock.yaml +4386 -0
  300. package/source/pnpm-workspace.yaml +9 -0
  301. package/source/prisma/migrations/20261109000000_init/migration.sql +6544 -0
  302. package/source/prisma/migrations/20261109010000_console_simulation/migration.sql +62 -0
  303. package/source/prisma/migrations/20261109020000_run_audit/migration.sql +15 -0
  304. package/source/prisma/migrations/20261109030000_connector_queue/migration.sql +6 -0
  305. package/source/prisma/migrations/20261109040000_console_run_filters/migration.sql +30 -0
  306. package/source/prisma/migrations/20261109050000_console_run_timeline/migration.sql +34 -0
  307. package/source/prisma/migrations/20261109060000_connector_read_status/migration.sql +58 -0
  308. package/source/prisma/migrations/20261109070000_console_knowledge/migration.sql +7 -0
  309. package/source/prisma/migrations/20261109080000_platform_account_pool/migration.sql +22 -0
  310. package/source/prisma/migrations/20261109090000_identity_writing_prompt/migration.sql +28 -0
  311. package/source/prisma/migrations/20261111000000_collaborative_plans/migration.sql +77 -0
  312. package/source/prisma/migrations/20261111010000_commitment_details/migration.sql +49 -0
  313. package/source/prisma/migrations/20261111020000_simulation_follow_up/migration.sql +91 -0
  314. package/source/prisma/migrations/20261111030000_collaborative_ai_follow_up/migration.sql +146 -0
  315. package/source/prisma/migrations/20261111040000_console_simulation_transcript/migration.sql +105 -0
  316. package/source/prisma/migrations/20261114000000_newbi_runtime_connection/migration.sql +2 -0
  317. package/source/prisma/migrations/20261114010000_shared_runtime_database/migration.sql +2 -0
  318. package/source/prisma/migrations/20261114020000_newbi_account_credentials/migration.sql +32 -0
  319. package/source/prisma/migrations/20261114030000_remove_unlinked_accounts/migration.sql +1 -0
  320. package/source/prisma/migrations/20261114040000_newbi_account_profiles/migration.sql +1 -0
  321. package/source/prisma/migrations/20261115000000_local_user_management/migration.sql +55 -0
  322. package/source/prisma/migrations/20261115010000_administrator_only_membership/migration.sql +15 -0
  323. package/source/prisma/migrations/20261115020000_manage_own_passkeys/migration.sql +32 -0
  324. package/source/prisma/migrations/20261115030000_change_own_password/migration.sql +30 -0
  325. package/source/prisma/migrations/20261115040000_system_administrators/migration.sql +55 -0
  326. package/source/prisma/migrations/20261117000000_identity_draft_model_profile/migration.sql +30 -0
  327. package/source/prisma/migrations/20261118000000_auto_review/migration.sql +9 -0
  328. package/source/prisma/migrations/20261118010000_internal_core_prompt/migration.sql +62 -0
  329. package/source/prisma/migrations/20261118020000_hosted_model_usage/migration.sql +42 -0
  330. package/source/prisma/migrations/migration_lock.toml +1 -0
  331. package/source/prisma/schema.prisma +1019 -0
  332. package/source/prisma.config.ts +8 -0
  333. package/source/scripts/admin-user.ts +47 -0
  334. package/source/scripts/inbound.integration.test.ts +1515 -0
  335. package/source/scripts/management.integration.test.ts +3516 -0
  336. package/source/scripts/outbox-smoke.ts +122 -0
  337. package/source/scripts/pack-release.mjs +88 -0
  338. package/source/scripts/plugin-release-manifest.ts +20 -0
  339. package/source/tsconfig.json +23 -0
  340. package/source/tsconfig.server.json +12 -0
@@ -0,0 +1,142 @@
1
+ import { z } from 'zod'
2
+ import type { HostedModel } from './catalog.js'
3
+ import type { HostedModelConfig } from './config.js'
4
+ import { readTokenUsage, type HostedUsageRecord, type RecordHostedUsage } from './usage.js'
5
+
6
+ export class HostedApiError extends Error {
7
+ constructor(readonly code: 'REQUEST_FAILED' | 'HTTP_ERROR' | 'INVALID_OUTPUT', readonly status?: number) {
8
+ super(code)
9
+ }
10
+ }
11
+
12
+ const chatResult = z.object({
13
+ choices: z.array(z.object({
14
+ finish_reason: z.literal('stop'),
15
+ message: z.object({ content: z.string(), refusal: z.null().optional() }),
16
+ })).length(1),
17
+ })
18
+ const claudeResult = z.object({
19
+ stop_reason: z.literal('end_turn'),
20
+ content: z.array(z.object({ type: z.string(), text: z.string().optional() })),
21
+ })
22
+ const geminiResult = z.object({
23
+ candidates: z.array(z.object({
24
+ finishReason: z.literal('STOP'),
25
+ content: z.object({ parts: z.array(z.object({ thought: z.boolean().optional(), text: z.string().optional() })) }),
26
+ })).length(1),
27
+ })
28
+ const maxTokens = 2048
29
+
30
+ function request(id: HostedModel['id'], { url, model, key }: HostedModelConfig, system: string, input: string): {
31
+ url: string
32
+ headers: Record<string, string>
33
+ body: object
34
+ } {
35
+ const message = { role: 'user', content: input }
36
+ if (id === 'anthropic') {
37
+ return {
38
+ url, headers: { 'x-api-key': key, 'anthropic-version': '2023-06-01' },
39
+ body: { model, max_tokens: maxTokens, system, messages: [message] },
40
+ }
41
+ }
42
+ if (id === 'gemini') {
43
+ return {
44
+ url: url + encodeURIComponent(model) + ':generateContent',
45
+ headers: { 'x-goog-api-key': key },
46
+ body: {
47
+ systemInstruction: { parts: [{ text: system }] },
48
+ contents: [{ role: 'user', parts: [{ text: input }] }],
49
+ generationConfig: { maxOutputTokens: maxTokens },
50
+ },
51
+ }
52
+ }
53
+ return {
54
+ url, headers: { Authorization: 'Bearer ' + key },
55
+ body: {
56
+ model,
57
+ ...(id === 'openai' ? { max_completion_tokens: maxTokens, store: false } : { max_tokens: maxTokens }),
58
+ ...(id === 'deepseek' ? { thinking: { type: 'disabled' } } : {}),
59
+ messages: [{ role: id === 'openai' ? 'developer' : 'system', content: system }, message],
60
+ },
61
+ }
62
+ }
63
+
64
+ function replyText(id: HostedModel['id'], result: unknown) {
65
+ if (id === 'anthropic') {
66
+ const parsed = claudeResult.safeParse(result)
67
+ return parsed.success ? parsed.data.content.filter(({ type }) => type === 'text').map(({ text }) => text).join('') : undefined
68
+ }
69
+ if (id === 'gemini') {
70
+ const parsed = geminiResult.safeParse(result)
71
+ return parsed.success ? parsed.data.candidates[0].content.parts.filter(({ thought }) => !thought).map(({ text }) => text).join('') : undefined
72
+ }
73
+ const parsed = chatResult.safeParse(result)
74
+ return parsed.success ? parsed.data.choices[0].message.content : undefined
75
+ }
76
+
77
+ export async function requestHostedReply(id: HostedModel['id'], config: HostedModelConfig, system: string, input: string, signal: AbortSignal,
78
+ usage?: Pick<HostedUsageRecord, 'attribution' | 'purpose'> & { record: RecordHostedUsage },
79
+ ) {
80
+ const { url, headers, body } = request(id, config, system, input)
81
+ const payload = JSON.stringify(body)
82
+ const day = new Date().toISOString().slice(0, 10)
83
+ const started = performance.now()
84
+ const metric: HostedUsageRecord = {
85
+ day, provider: id, model: config.model, purpose: usage?.purpose ?? 'DRAFT', attribution: usage?.attribution,
86
+ sentBytes: 0, receivedBytes: 0, outcome: 'CONNECTION_FAILED', elapsedMs: 0,
87
+ }
88
+ async function readBody(response: Response) {
89
+ const reader = response.body?.getReader()
90
+ if (!reader) return
91
+ const chunks: Uint8Array[] = []
92
+ try {
93
+ for (;;) {
94
+ const chunk = await reader.read()
95
+ if (chunk.done) break
96
+ metric.receivedBytes += chunk.value.byteLength
97
+ if (metric.receivedBytes > 4 * 1024 * 1024) {
98
+ await reader.cancel()
99
+ return
100
+ }
101
+ chunks.push(chunk.value)
102
+ }
103
+ return JSON.parse(Buffer.concat(chunks).toString('utf8')) as unknown
104
+ } catch {
105
+ return
106
+ } finally {
107
+ reader.releaseLock()
108
+ }
109
+ }
110
+ try {
111
+ let response: Response
112
+ try {
113
+ signal.throwIfAborted()
114
+ metric.sentBytes = Buffer.byteLength(payload)
115
+ response = await fetch(url, {
116
+ method: 'POST', headers: { ...headers, 'Content-Type': 'application/json' },
117
+ body: payload, signal, redirect: 'error',
118
+ })
119
+ } catch {
120
+ if (signal.aborted) metric.outcome = 'TIMED_OUT'
121
+ throw new HostedApiError('REQUEST_FAILED')
122
+ }
123
+ const result = await readBody(response)
124
+ metric.tokens = readTokenUsage(id, result)
125
+ if (!response.ok) {
126
+ metric.outcome = response.status === 429 ? 'RATE_LIMITED' : 'HTTP_ERROR'
127
+ throw new HostedApiError('HTTP_ERROR', response.status)
128
+ }
129
+ const reply = replyText(id, result)?.trim()
130
+ if (!reply) {
131
+ metric.outcome = signal.aborted ? 'TIMED_OUT' : 'INVALID_OUTPUT'
132
+ throw new HostedApiError('INVALID_OUTPUT')
133
+ }
134
+ metric.outcome = 'OK'
135
+ return reply
136
+ } finally {
137
+ metric.elapsedMs = Math.round(performance.now() - started)
138
+ if (usage) await usage.record(metric).catch(() => {
139
+ console.warn(JSON.stringify({ service: 'hosted-models', event: 'usage_record_failed' }))
140
+ })
141
+ }
142
+ }
@@ -0,0 +1,40 @@
1
+ import { z } from 'zod'
2
+ import type { HostedModel } from './catalog.js'
3
+
4
+ const providers = {
5
+ openai: 'https://api.openai.com/v1/chat/completions',
6
+ anthropic: 'https://api.anthropic.com/v1/messages',
7
+ gemini: 'https://generativelanguage.googleapis.com/v1beta/models/',
8
+ deepseek: 'https://api.deepseek.com/chat/completions',
9
+ 'openai-compatible': undefined,
10
+ } as const
11
+
12
+ const model = z.string().trim().min(1).max(160).regex(/^[\w./:-]+$/)
13
+ const apiKey = z.string().trim().min(1).max(4096).regex(/^[\x21-\x7e]+$/)
14
+ const baseUrl = z.url({ protocol: /^https$/ }).max(2048).refine((value) => {
15
+ if (!URL.canParse(value)) return false
16
+ const url = new URL(value)
17
+ return !url.username && !url.password && !url.search && !url.hash
18
+ }).transform((value) => new URL(value).href.replace(/\/+$/, ''))
19
+
20
+ export const modelSettingsFields = {
21
+ model: model.optional(),
22
+ apiKey: apiKey.optional(),
23
+ baseUrl: baseUrl.optional(),
24
+ }
25
+
26
+ const configSchema = z.object({
27
+ ...modelSettingsFields,
28
+ model: modelSettingsFields.model.unwrap(),
29
+ apiKey: modelSettingsFields.apiKey.unwrap(),
30
+ })
31
+
32
+ export type HostedModelConfig = { model: string; key: string; url: string }
33
+
34
+ export function parseHostedModelConfig({ id, requiresBaseUrl }: HostedModel, config: unknown): HostedModelConfig {
35
+ const { model, apiKey: key, baseUrl } = configSchema.parse(config)
36
+ if (requiresBaseUrl !== (baseUrl !== undefined)) throw new Error('Invalid base URL configuration')
37
+ const url = baseUrl === undefined ? providers[id] : baseUrl + '/chat/completions'
38
+ if (!url) throw new Error('Missing model endpoint')
39
+ return { model, key, url }
40
+ }
@@ -0,0 +1,49 @@
1
+ import { z } from 'zod'
2
+ import type { ModelAttribution } from '@ricajs/contracts/model-provider'
3
+ import type { HostedModel } from './catalog.js'
4
+
5
+ export type UsagePurpose = 'DRAFT' | 'REVIEW' | 'CHECK'
6
+ export type UsageOutcome = 'OK' | 'HTTP_ERROR' | 'RATE_LIMITED' | 'TIMED_OUT' | 'CONNECTION_FAILED' | 'INVALID_OUTPUT'
7
+ export type TokenUsage = { inputTokens: number; outputTokens: number; totalTokens: number }
8
+ export type HostedUsageRecord = {
9
+ day: string; provider: HostedModel['id']; model: string; purpose: UsagePurpose; outcome: UsageOutcome
10
+ attribution?: ModelAttribution; sentBytes: number; receivedBytes: number; elapsedMs: number; tokens?: TokenUsage
11
+ }
12
+ export type RecordHostedUsage = (record: HostedUsageRecord) => Promise<void>
13
+
14
+ const count = z.number().int().nonnegative().max(1_000_000_000)
15
+ const chatUsage = z.object({ usage: z.object({
16
+ prompt_tokens: count, completion_tokens: count, total_tokens: count.optional(),
17
+ }) })
18
+ const claudeUsage = z.object({ usage: z.object({
19
+ input_tokens: count, output_tokens: count, cache_creation_input_tokens: count.nullish(), cache_read_input_tokens: count.nullish(),
20
+ }) })
21
+ const geminiUsage = z.object({ usageMetadata: z.object({
22
+ promptTokenCount: count, candidatesTokenCount: count.optional(), totalTokenCount: count,
23
+ thoughtsTokenCount: count.optional(), toolUsePromptTokenCount: count.optional(),
24
+ }) })
25
+
26
+ export function readTokenUsage(provider: HostedModel['id'], response: unknown): TokenUsage | undefined {
27
+ if (provider === 'anthropic') {
28
+ const parsed = claudeUsage.safeParse(response)
29
+ if (!parsed.success) return
30
+ const usage = parsed.data.usage
31
+ const inputTokens = usage.input_tokens + (usage.cache_creation_input_tokens ?? 0) + (usage.cache_read_input_tokens ?? 0)
32
+ return { inputTokens, outputTokens: usage.output_tokens, totalTokens: inputTokens + usage.output_tokens }
33
+ }
34
+ if (provider === 'gemini') {
35
+ const parsed = geminiUsage.safeParse(response)
36
+ if (!parsed.success) return
37
+ const usage = parsed.data.usageMetadata
38
+ return {
39
+ inputTokens: usage.promptTokenCount + (usage.toolUsePromptTokenCount ?? 0),
40
+ outputTokens: (usage.candidatesTokenCount ?? 0) + (usage.thoughtsTokenCount ?? 0),
41
+ totalTokens: usage.totalTokenCount,
42
+ }
43
+ }
44
+ const parsed = chatUsage.safeParse(response)
45
+ if (!parsed.success) return
46
+ const usage = parsed.data.usage
47
+ return { inputTokens: usage.prompt_tokens, outputTokens: usage.completion_tokens,
48
+ totalTokens: usage.total_tokens ?? usage.prompt_tokens + usage.completion_tokens }
49
+ }
@@ -0,0 +1,299 @@
1
+ <script setup lang="ts">
2
+ import { computed, nextTick, onMounted, reactive, ref } from 'vue'
3
+ import { UiAlert, UiBadge, UiButton, UiDialog, UiEmpty, UiField, UiSpinner } from '@ricajs/console-shared/ui'
4
+ import { useConsoleTask } from '@ricajs/console-shared/console-data'
5
+ import { request } from '@ricajs/console-shared/request'
6
+ import { hostedModelCatalog } from '../../providers/catalog.js'
7
+ import { modelSettingsContracts, type ModelCheckResult, type ModelSettingsView } from '../management/contracts.js'
8
+ import { modelCheckLabels } from './labels.js'
9
+
10
+ const props = defineProps<{ busy: boolean; canStartSimulation: boolean }>()
11
+ const emit = defineEmits<{ expired: []; saved: []; simulate: [] }>()
12
+ type Profile = ModelSettingsView['profiles'][number]
13
+
14
+ const { active, busy, error, notice, run } = useConsoleTask(() => emit('expired'))
15
+ const path = '/v1/model-settings'
16
+ const current = ref<ModelSettingsView>()
17
+ const editing = ref<string | null>(null)
18
+ const removing = ref<string>()
19
+ const checkResult = ref<ModelCheckResult>()
20
+ const pending = ref<'save' | 'check' | 'default' | 'remove'>()
21
+ const form = reactive({ name: '', provider: '', model: '', baseUrl: '', apiKey: '' })
22
+ const heading = ref<HTMLElement>()
23
+ const addButton = ref<InstanceType<typeof UiButton>>()
24
+ const blocked = computed(() => props.busy || busy.value)
25
+ const saved = computed(() => current.value?.profiles.find(({ id }) => id === editing.value))
26
+ const removeTarget = computed(() => current.value?.profiles.find(({ id }) => id === removing.value))
27
+ const rows = computed(() => [...(current.value?.profiles ?? []), ...(editing.value === '' ? [null] : [])])
28
+ const option = computed(() => hostedModelCatalog.find(({ id }) => id === form.provider))
29
+ const providerName = (id: string) => hostedModelCatalog.find((p) => p.id === id)?.name ?? id
30
+ const reuseKey = computed(() => saved.value?.hasKey && saved.value.provider === form.provider
31
+ && (!option.value?.requiresBaseUrl || saved.value.baseUrl === form.baseUrl.trim().replace(/\/+$/, '')))
32
+ const canCheck = computed(() => reuseKey.value && !form.apiKey && saved.value?.model === form.model.trim()
33
+ && saved.value?.name === form.name.trim())
34
+
35
+ function load() {
36
+ void run(async () => {
37
+ const value = await request<ModelSettingsView>(path)
38
+ if (!active()) return
39
+ current.value = value
40
+ if (editing.value && !value.profiles.some(({ id }) => id === editing.value)) closeForm()
41
+ })
42
+ }
43
+
44
+ function edit(profile?: Profile) {
45
+ editing.value = profile?.id ?? ''
46
+ Object.assign(form, { name: profile?.name ?? '', provider: profile?.provider ?? '',
47
+ model: profile?.model ?? '', baseUrl: profile?.baseUrl ?? '', apiKey: '' })
48
+ checkResult.value = undefined
49
+ error.value = ''
50
+ notice.value = ''
51
+ void nextTick(() => document.getElementById('model-config-name')?.focus())
52
+ }
53
+
54
+ function closeForm() {
55
+ const id = editing.value
56
+ editing.value = null
57
+ form.apiKey = ''
58
+ checkResult.value = undefined
59
+ error.value = ''
60
+ notice.value = ''
61
+ void nextTick(() => {
62
+ const target = (id && document.getElementById('edit-model-profile-' + id)) || addButton.value?.$el
63
+ target?.focus()
64
+ })
65
+ }
66
+
67
+ function changeProvider() {
68
+ Object.assign(form, { model: '', baseUrl: '', apiKey: '' })
69
+ error.value = ''
70
+ }
71
+
72
+ function update(kind: 'save' | 'default', endpoint: string, payload: object, version: number, apply: (value: ModelSettingsView) => void) {
73
+ pending.value = kind
74
+ void run(async () => {
75
+ const value = await request<ModelSettingsView>(endpoint, {
76
+ method: 'PUT',
77
+ headers: { 'Content-Type': 'application/json', 'If-Match': '"' + version + '"' },
78
+ body: JSON.stringify(payload),
79
+ })
80
+ if (!active()) return
81
+ current.value = value
82
+ apply(value)
83
+ emit('saved')
84
+ }).finally(() => { pending.value = undefined })
85
+ }
86
+
87
+ function save() {
88
+ if (!current.value || !option.value || editing.value === null || blocked.value) return
89
+ const parsed = modelSettingsContracts.modelProfileInput.safeParse({
90
+ id: saved.value?.id, name: form.name, provider: option.value.id, model: form.model, apiKey: form.apiKey || undefined,
91
+ baseUrl: option.value.requiresBaseUrl ? form.baseUrl.trim() : undefined,
92
+ })
93
+ if (!parsed.success || (!parsed.data.apiKey && !reuseKey.value)) {
94
+ error.value = '请核对配置名称、模型 ID、API 密钥和 HTTPS API 地址。'
95
+ return
96
+ }
97
+ const knownIds = new Set(current.value.profiles.map(({ id }) => id))
98
+ update('save', path, parsed.data, current.value.version, (value) => {
99
+ const profile = value.profiles.find(({ id }) => id === parsed.data.id || !knownIds.has(id))
100
+ if (profile) edit(profile)
101
+ notice.value = '已保存模型配置。'
102
+ })
103
+ }
104
+
105
+ function setDefault(id: string | null) {
106
+ if (!current.value || blocked.value) return
107
+ update('default', path + '/active', { id }, current.value.version, () => {
108
+ notice.value = id ? '已设为默认草稿模型。' : '默认草稿已切回本地模型。'
109
+ })
110
+ }
111
+
112
+ function confirmRemoval(profile: Profile) {
113
+ error.value = ''
114
+ notice.value = ''
115
+ removing.value = profile.id
116
+ }
117
+
118
+ function cancelRemoval() {
119
+ removing.value = undefined
120
+ error.value = ''
121
+ }
122
+
123
+ function removeProfile() {
124
+ if (!current.value || !removeTarget.value || blocked.value) return
125
+ const { id } = removeTarget.value
126
+ const version = current.value.version
127
+ let removed = false
128
+ pending.value = 'remove'
129
+ void run(async () => {
130
+ const value = await request<ModelSettingsView>(path + '/' + encodeURIComponent(id), {
131
+ method: 'DELETE', headers: { 'If-Match': '"' + version + '"' },
132
+ })
133
+ if (!active()) return
134
+ current.value = value
135
+ removing.value = undefined
136
+ if (editing.value === id) closeForm()
137
+ notice.value = '已移除模型配置。'
138
+ removed = true
139
+ emit('saved')
140
+ }).finally(() => {
141
+ pending.value = undefined
142
+ if (removed) void nextTick(() => addButton.value?.$el.focus())
143
+ })
144
+ }
145
+
146
+ function testModel() {
147
+ if (!current.value || !saved.value || !canCheck.value || blocked.value) return
148
+ const payload = { id: saved.value.id, version: current.value.version }
149
+ pending.value = 'check'
150
+ checkResult.value = undefined
151
+ void run(async () => {
152
+ const result = await request<ModelCheckResult>(path + '/check', {
153
+ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload),
154
+ })
155
+ if (active()) {
156
+ checkResult.value = result
157
+ emit('saved')
158
+ }
159
+ }).finally(() => { pending.value = undefined })
160
+ }
161
+
162
+ onMounted(() => { heading.value?.focus(); load() })
163
+ </script>
164
+
165
+ <template>
166
+ <section class="model-settings" aria-labelledby="model-settings-heading">
167
+ <div class="console-section-heading model-settings-toolbar">
168
+ <h3 id="model-settings-heading" ref="heading" tabindex="-1">模型配置</h3>
169
+ <div v-if="current" class="console-actions">
170
+ <UiButton v-if="current.defaultProfileId" size="small" variant="quiet" :disabled="blocked"
171
+ :loading="pending === 'default'" @click="setDefault(null)">默认使用本地模型</UiButton>
172
+ <UiButton ref="addButton" size="small" :tone="editing === '' ? 'default' : 'primary'"
173
+ :variant="editing === '' ? 'soft' : 'solid'" :disabled="blocked" :aria-expanded="editing === ''"
174
+ :aria-controls="editing === '' ? 'model-settings-form' : undefined"
175
+ @click="editing === '' ? closeForm() : edit()">
176
+ {{ editing === '' ? '取消添加' : '添加模型' }}
177
+ </UiButton>
178
+ </div>
179
+ </div>
180
+ <UiSpinner v-if="busy && !current" aria-label="正在读取模型配置" />
181
+ <template v-if="current">
182
+ <ul v-if="rows.length" class="model-profile-list">
183
+ <li v-for="profile in rows" :key="profile?.id ?? 'new'" class="model-profile"
184
+ :class="{ 'model-profile-open': editing === (profile?.id ?? '') }">
185
+ <div v-if="profile" class="model-profile-row">
186
+ <div class="model-profile-label">
187
+ <strong>{{ profile.name }}</strong>
188
+ <span class="model-settings-detail">{{ providerName(profile.provider) }} · {{ profile.model }}</span>
189
+ </div>
190
+ <div class="console-actions">
191
+ <UiBadge v-if="profile.id === current.defaultProfileId" tone="success">部署默认</UiBadge>
192
+ <UiButton :id="'edit-model-profile-' + profile.id" size="small" variant="quiet"
193
+ :disabled="blocked" :aria-expanded="editing === profile.id"
194
+ :aria-controls="editing === profile.id ? 'model-settings-form' : undefined"
195
+ :aria-label="(editing === profile.id ? '收起模型配置 ' : '编辑模型配置 ') + profile.name"
196
+ @click="editing === profile.id ? closeForm() : edit(profile)">
197
+ {{ editing === profile.id ? '收起' : '编辑' }}
198
+ </UiButton>
199
+ <UiButton size="small" variant="quiet" tone="error" :disabled="blocked"
200
+ :aria-label="'移除模型配置 ' + profile.name" @click="confirmRemoval(profile)">移除</UiButton>
201
+ </div>
202
+ </div>
203
+
204
+ <form v-if="editing === (profile?.id ?? '')" id="model-settings-form" class="model-settings-form"
205
+ :aria-label="profile ? '编辑 ' + profile.name : '添加模型配置'" @submit.prevent="save">
206
+ <div class="model-form-fields">
207
+ <UiField label="配置名称" for="model-config-name">
208
+ <input id="model-config-name" class="ui-control" v-model="form.name"
209
+ :disabled="blocked" required maxlength="80" />
210
+ </UiField>
211
+ <UiField v-if="!profile" label="模型提供方" for="model-config-provider">
212
+ <select id="model-config-provider" class="ui-control" v-model="form.provider" :disabled="blocked" required
213
+ @change="changeProvider">
214
+ <option value="" disabled>选择模型提供方</option>
215
+ <option v-for="item in hostedModelCatalog" :key="item.id" :value="item.id">{{ item.name }}</option>
216
+ </select>
217
+ </UiField>
218
+ <UiField label="模型 ID" for="model-config-model">
219
+ <input id="model-config-model" class="ui-control" v-model="form.model" :disabled="blocked" required maxlength="160" />
220
+ </UiField>
221
+ <UiField label="API 密钥" for="model-config-key">
222
+ <input id="model-config-key" class="ui-control" v-model="form.apiKey" type="password" :disabled="blocked"
223
+ :placeholder="reuseKey ? '留空继续使用已保存的密钥' : undefined" autocomplete="new-password" :required="!reuseKey" />
224
+ </UiField>
225
+ <UiField v-if="option?.requiresBaseUrl" label="API 基础地址" for="model-config-url">
226
+ <input id="model-config-url" class="ui-control" v-model="form.baseUrl" :disabled="blocked"
227
+ placeholder="https://provider.example/v1" required />
228
+ </UiField>
229
+ </div>
230
+ <div class="console-actions">
231
+ <UiButton tone="primary" type="submit" :disabled="blocked" :loading="pending === 'save'">保存配置</UiButton>
232
+ <UiButton v-if="saved" type="button" :disabled="blocked || !canCheck"
233
+ :loading="pending === 'check'" aria-describedby="model-form-test-note" @click="testModel">测试连接</UiButton>
234
+ <UiButton v-if="saved && saved.id !== current.defaultProfileId" type="button" variant="quiet"
235
+ :disabled="blocked || !canCheck" :loading="pending === 'default'" @click="setDefault(saved.id)">设为部署默认</UiButton>
236
+ </div>
237
+ <p v-if="saved" id="model-form-test-note" class="model-settings-detail">
238
+ 修改将应用于引用此配置的身份。连接测试会发送固定消息,可能消耗模型额度。
239
+ </p>
240
+ <UiAlert v-if="notice" tone="success" role="status">{{ notice }}</UiAlert>
241
+ <UiAlert v-if="error && !removeTarget" tone="error" role="alert">
242
+ {{ error }}
243
+ <UiButton type="button" size="small" variant="quiet" :disabled="blocked" @click="load">重新读取配置</UiButton>
244
+ </UiAlert>
245
+ <UiAlert v-if="checkResult && canCheck" :tone="checkResult.status === 'OK' ? 'success' : 'error'" role="status">
246
+ {{ modelCheckLabels[checkResult.status] }}
247
+ <p v-if="checkResult.reply" class="console-payload">{{ checkResult.reply }}</p>
248
+ <UiButton v-if="checkResult.status === 'OK' && canStartSimulation && saved?.id === current.defaultProfileId"
249
+ type="button" size="small" variant="soft" @click="emit('simulate')">发起模拟验证</UiButton>
250
+ </UiAlert>
251
+ </form>
252
+ </li>
253
+ </ul>
254
+ <UiEmpty v-else description="暂无外部模型配置。" />
255
+ </template>
256
+ <UiAlert v-if="editing === null && notice" tone="success" role="status">{{ notice }}</UiAlert>
257
+ <UiAlert v-if="editing === null && error && !removeTarget" tone="error" role="alert">
258
+ {{ error }}
259
+ <UiButton size="small" variant="quiet" :disabled="blocked" @click="load">重新读取配置</UiButton>
260
+ </UiAlert>
261
+ <UiDialog :open="!!removeTarget" title="移除模型配置" :busy="blocked"
262
+ @update:open="open => { if (!open) cancelRemoval() }">
263
+ <div class="model-removal-content">
264
+ <p v-if="removeTarget" class="model-settings-detail model-removal-description">
265
+ 移除「{{ removeTarget.name }}」会删除它保存的 API 密钥。引用它的身份后续将使用本地模型。
266
+ <template v-if="removeTarget.id === current?.defaultProfileId">部署默认也会切回本地模型。</template>
267
+ </p>
268
+ <UiAlert v-if="error" tone="error" role="alert">
269
+ {{ error }}
270
+ <UiButton type="button" size="small" variant="quiet" :disabled="blocked" @click="load">重新读取配置</UiButton>
271
+ </UiAlert>
272
+ <div class="console-actions model-removal-actions">
273
+ <UiButton type="button" :disabled="blocked" @click="cancelRemoval">取消</UiButton>
274
+ <UiButton type="button" tone="error" :disabled="blocked" :loading="pending === 'remove'" @click="removeProfile">确认移除</UiButton>
275
+ </div>
276
+ </div>
277
+ </UiDialog>
278
+ </section>
279
+ </template>
280
+
281
+ <style scoped>
282
+ .model-settings { display: grid; gap: .75rem; min-inline-size: 0; }
283
+ .model-settings-toolbar { margin: 0; align-items: center; flex-wrap: wrap; }
284
+ .model-profile-list { list-style: none; padding: 0; margin: 0; border: 1px solid var(--console-line); border-radius: .5rem; }
285
+ .model-profile + .model-profile { border-block-start: 1px solid var(--console-line); }
286
+ .model-profile-row { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: .5rem; padding: .625rem .875rem; }
287
+ .model-profile-label { display: grid; gap: .125rem; min-inline-size: 0; overflow-wrap: anywhere; }
288
+ .model-settings-detail { margin: 0; color: var(--console-muted); font-size: .8125rem; overflow-wrap: anywhere; }
289
+ .model-profile-open > .model-profile-row { background: var(--console-hover); }
290
+ .model-profile-open:first-child > .model-profile-row { border-start-start-radius: .5rem; border-start-end-radius: .5rem; }
291
+ .model-profile-row + .model-settings-form { border-block-start: 1px solid var(--console-line); }
292
+ .model-settings-form { display: grid; gap: .75rem; padding: .875rem; }
293
+ .model-settings-form > * { max-inline-size: 48rem; }
294
+ .model-form-fields { display: grid; gap: .75rem 1rem; grid-template-columns: repeat(auto-fit, minmax(min(100%, 20rem), 1fr)); }
295
+ .model-form-fields :deep(.ui-field) { padding-block-end: 0; }
296
+ .model-removal-content { display: grid; gap: 1rem; }
297
+ .model-removal-description { font-size: .875rem; line-height: 1.6; }
298
+ .model-removal-actions { justify-content: flex-end; border-block-start: 1px solid var(--console-line); padding-block-start: .875rem; }
299
+ </style>