libre-webui 0.44.0 → 0.45.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 (228) hide show
  1. package/backend/dist/index.d.ts.map +1 -1
  2. package/backend/dist/index.js +2 -0
  3. package/backend/dist/index.js.map +1 -1
  4. package/backend/dist/routes/chat.d.ts.map +1 -1
  5. package/backend/dist/routes/chat.js +10 -2
  6. package/backend/dist/routes/chat.js.map +1 -1
  7. package/backend/dist/routes/decisions.d.ts +3 -0
  8. package/backend/dist/routes/decisions.d.ts.map +1 -0
  9. package/backend/dist/routes/decisions.js +148 -0
  10. package/backend/dist/routes/decisions.js.map +1 -0
  11. package/backend/dist/services/agentCliService.d.ts.map +1 -1
  12. package/backend/dist/services/agentCliService.js +2 -0
  13. package/backend/dist/services/agentCliService.js.map +1 -1
  14. package/backend/dist/services/apiTokenService.d.ts.map +1 -1
  15. package/backend/dist/services/apiTokenService.js +2 -0
  16. package/backend/dist/services/apiTokenService.js.map +1 -1
  17. package/backend/dist/services/authorizationService.d.ts +1 -1
  18. package/backend/dist/services/authorizationService.d.ts.map +1 -1
  19. package/backend/dist/services/authorizationService.js +8 -1
  20. package/backend/dist/services/authorizationService.js.map +1 -1
  21. package/backend/dist/services/chatGenerationService.d.ts +24 -2
  22. package/backend/dist/services/chatGenerationService.d.ts.map +1 -1
  23. package/backend/dist/services/chatGenerationService.js +72 -4
  24. package/backend/dist/services/chatGenerationService.js.map +1 -1
  25. package/backend/dist/services/chatRequestService.d.ts +11 -3
  26. package/backend/dist/services/chatRequestService.d.ts.map +1 -1
  27. package/backend/dist/services/chatRequestService.js +19 -3
  28. package/backend/dist/services/chatRequestService.js.map +1 -1
  29. package/backend/dist/services/contextCompactionService.d.ts.map +1 -1
  30. package/backend/dist/services/contextCompactionService.js +8 -0
  31. package/backend/dist/services/contextCompactionService.js.map +1 -1
  32. package/backend/dist/services/decisionAccessService.d.ts +16 -0
  33. package/backend/dist/services/decisionAccessService.d.ts.map +1 -0
  34. package/backend/dist/services/decisionAccessService.js +71 -0
  35. package/backend/dist/services/decisionAccessService.js.map +1 -0
  36. package/backend/dist/services/decisionService.d.ts +128 -0
  37. package/backend/dist/services/decisionService.d.ts.map +1 -0
  38. package/backend/dist/services/decisionService.js +515 -0
  39. package/backend/dist/services/decisionService.js.map +1 -0
  40. package/backend/dist/services/durableChatGenerationService.d.ts.map +1 -1
  41. package/backend/dist/services/durableChatGenerationService.js +13 -2
  42. package/backend/dist/services/durableChatGenerationService.js.map +1 -1
  43. package/backend/dist/services/ollamaService.d.ts +6 -0
  44. package/backend/dist/services/ollamaService.d.ts.map +1 -1
  45. package/backend/dist/services/ollamaService.js +13 -0
  46. package/backend/dist/services/ollamaService.js.map +1 -1
  47. package/backend/dist/types/index.d.ts +38 -1
  48. package/backend/dist/types/index.d.ts.map +1 -1
  49. package/backend/dist/types/index.js.map +1 -1
  50. package/backend/dist/utils/decisionProtocol.d.ts +164 -0
  51. package/backend/dist/utils/decisionProtocol.d.ts.map +1 -0
  52. package/backend/dist/utils/decisionProtocol.js +755 -0
  53. package/backend/dist/utils/decisionProtocol.js.map +1 -0
  54. package/backend/dist/utils/ollamaLibrary.d.ts.map +1 -1
  55. package/backend/dist/utils/ollamaLibrary.js +26 -7
  56. package/backend/dist/utils/ollamaLibrary.js.map +1 -1
  57. package/backend/dist/utils/pluginChatAdapter.d.ts.map +1 -1
  58. package/backend/dist/utils/pluginChatAdapter.js +31 -9
  59. package/backend/dist/utils/pluginChatAdapter.js.map +1 -1
  60. package/backend/dist/utils/pluginDefinitionTrust.d.ts.map +1 -1
  61. package/backend/dist/utils/pluginDefinitionTrust.js +53 -9
  62. package/backend/dist/utils/pluginDefinitionTrust.js.map +1 -1
  63. package/backend/dist/utils/pluginModelCatalog.d.ts +4 -2
  64. package/backend/dist/utils/pluginModelCatalog.d.ts.map +1 -1
  65. package/backend/dist/utils/pluginModelCatalog.js +12 -2
  66. package/backend/dist/utils/pluginModelCatalog.js.map +1 -1
  67. package/backend/dist/websocketServer.d.ts.map +1 -1
  68. package/backend/dist/websocketServer.js +23 -6
  69. package/backend/dist/websocketServer.js.map +1 -1
  70. package/backend/package.json +2 -2
  71. package/frontend/dist/artifact-runtime/.build-fingerprint +1 -1
  72. package/frontend/dist/artifact-runtime/babel.js +172 -172
  73. package/frontend/dist/artifact-runtime/framer-motion.js +2 -2
  74. package/frontend/dist/artifact-runtime/lucide-react.js +1 -1
  75. package/frontend/dist/artifact-runtime/papaparse.js +2 -2
  76. package/frontend/dist/artifact-runtime/plotly.js +5 -5
  77. package/frontend/dist/artifact-runtime/tailwind.js +16 -16
  78. package/frontend/dist/assets/index-C2A5Ko4-.js +59 -0
  79. package/frontend/dist/assets/index-FrFgrp5E.css +2 -0
  80. package/frontend/dist/index.html +28 -28
  81. package/frontend/dist/js/{ArtifactContainer-C7EEweSP.js → ArtifactContainer-DCCcjK16.js} +1 -1
  82. package/frontend/dist/js/{ArtifactDemoPage-B3yjn6Dw.js → ArtifactDemoPage-C-1acgxJ.js} +1 -1
  83. package/frontend/dist/js/{ArtifactSandboxFrame-DGC1hgTq.js → ArtifactSandboxFrame-BXWNhmtI.js} +1 -1
  84. package/frontend/dist/js/{ArtifactSlideOutPanel-xamxqotB.js → ArtifactSlideOutPanel-CvfdP_o2.js} +1 -1
  85. package/frontend/dist/js/{AutomationModal-Dj0E2mSl.js → AutomationModal-D7qiRMhj.js} +1 -1
  86. package/frontend/dist/js/{AutomationsPage-MTqU8Ap9.js → AutomationsPage-v98Ucl9p.js} +1 -1
  87. package/frontend/dist/js/{AvatarUpload-CrNLFoIi.js → AvatarUpload-W41SCHKE.js} +1 -1
  88. package/frontend/dist/js/{Button-BGE6ZJv5.js → Button-D6d7HYoa.js} +1 -1
  89. package/frontend/dist/js/{CalendarPage-BciFDr0S.js → CalendarPage-DkAa61Pa.js} +1 -1
  90. package/frontend/dist/js/ChannelsPage-0Vnfpgdr.js +1 -0
  91. package/frontend/dist/js/ChatPage-iyMY-uoE.js +14 -0
  92. package/frontend/dist/js/{ConnectModels-BPwpeVsJ.js → ConnectModels-CpWO6ALS.js} +1 -1
  93. package/frontend/dist/js/{EvaluationsPage-CT7EAYaj.js → EvaluationsPage-C7WHA1MJ.js} +1 -1
  94. package/frontend/dist/js/{FirstTimeSetup-BXkaFkvk.js → FirstTimeSetup-B8wcelBc.js} +1 -1
  95. package/frontend/dist/js/{GalleryPage-BPUY12kj.js → GalleryPage-u7dYKl3q.js} +1 -1
  96. package/frontend/dist/js/{HomePage-16KFuUir.js → HomePage-Cjlt3b9n.js} +1 -1
  97. package/frontend/dist/js/{LanguageSwitcher-MlITAZf6.js → LanguageSwitcher-gbTZY15P.js} +1 -1
  98. package/frontend/dist/js/{Logo-GlNrhpKp.js → Logo-DhV6D_3q.js} +1 -1
  99. package/frontend/dist/js/{LogoMark-rgOHhWo-.js → LogoMark-CmF1lHXT.js} +1 -1
  100. package/frontend/dist/js/{ModelManagerModals-inYMmqa4.js → ModelManagerModals-12hL-b-U.js} +1 -1
  101. package/frontend/dist/js/{NotesPage-kYFIBBCu.js → NotesPage-BQWBA5li.js} +2 -2
  102. package/frontend/dist/js/{PasswordStrengthMeter-ppDWQU9P.js → PasswordStrengthMeter-DdqX0FXA.js} +1 -1
  103. package/frontend/dist/js/PersonasPage-B8mFdWcX.js +13 -0
  104. package/frontend/dist/js/{PluginUsagePage-DQvsXxpI.js → PluginUsagePage-Uz6aHPIp.js} +1 -1
  105. package/frontend/dist/js/{RichMessageContent-BW9UvzYw.js → RichMessageContent-CVk-fp0N.js} +1 -1
  106. package/frontend/dist/js/{RichMessageContent-BraVuu1Q.js → RichMessageContent-DwMoWuR_.js} +1 -1
  107. package/frontend/dist/js/SettingsModal-CfjxNSmJ.js +19 -0
  108. package/frontend/dist/js/{SettingsToggle-BT6cbOnw.js → SettingsToggle-CNUeo6DO.js} +1 -1
  109. package/frontend/dist/js/{ShareDialog-CmgHPnKg.js → ShareDialog-NwirTDLR.js} +1 -1
  110. package/frontend/dist/js/{StrandsPage-Dg55juWQ.js → StrandsPage-ddHNdb6J.js} +1 -1
  111. package/frontend/dist/js/{SystemPage-PZhbWJCh.js → SystemPage-C_1exwI7.js} +1 -1
  112. package/frontend/dist/js/UserManagementPanel-hg7ztEtL.js +1 -0
  113. package/frontend/dist/js/{WhatsNewModal-DunfwUe9.js → WhatsNewModal-yYk7N4KY.js} +1 -1
  114. package/frontend/dist/js/WorkPage-i7yYRAuj.js +7 -0
  115. package/frontend/dist/js/api-BU13N8gU.js +1 -0
  116. package/frontend/dist/js/{api-DG2AKSTU.js → api-Dasm8tVY.js} +1 -1
  117. package/frontend/dist/js/{appNavigation-DXonlffV.js → appNavigation-DqP7fTWU.js} +1 -1
  118. package/frontend/dist/js/{appStore-DMmgXb-0.js → appStore-DCIUnT8X.js} +2 -2
  119. package/frontend/dist/js/appVersion-PJGaVilS.js +1 -0
  120. package/frontend/dist/js/ar-CsCftCVF.js +2 -0
  121. package/frontend/dist/js/authStore-Bp17zKvS.js +1 -0
  122. package/frontend/dist/js/{authStore-C89vePrB.js → authStore-ac5-hjOH.js} +3 -3
  123. package/frontend/dist/js/babel-C4LPTjCL.js +16 -0
  124. package/frontend/dist/js/bn-CvxUTZ9a.js +2 -0
  125. package/frontend/dist/js/chatStore-GhucyjJu.js +3 -0
  126. package/frontend/dist/js/{client-D05vqJPO.js → client-DxPoTB_C.js} +2 -2
  127. package/frontend/dist/js/{config-DCQ2-rvE.js → config-CQJEcQtz.js} +1 -1
  128. package/frontend/dist/js/cs-BovmMwcD.js +2 -0
  129. package/frontend/dist/js/da-Dof1gmsv.js +2 -0
  130. package/frontend/dist/js/de-CF9CXojW.js +2 -0
  131. package/frontend/dist/js/decisionsApi-BWB64EGn.js +1 -0
  132. package/frontend/dist/js/decisionsApi-CoJtg4PZ.js +1 -0
  133. package/frontend/dist/js/es-BXCt50HZ.js +2 -0
  134. package/frontend/dist/js/estree-DCoUd_wj.js +44 -0
  135. package/frontend/dist/js/{evaluationsApi-oCNxDBZ4.js → evaluationsApi-CBqKkjmI.js} +1 -1
  136. package/frontend/dist/js/fr-B5QcCDIw.js +2 -0
  137. package/frontend/dist/js/hi-BXYwSyKl.js +2 -0
  138. package/frontend/dist/js/html-DMnBrAcs.js +25 -0
  139. package/frontend/dist/js/id-BV3mY5L7.js +2 -0
  140. package/frontend/dist/js/is-BDK4LrQC.js +2 -0
  141. package/frontend/dist/js/it-DAeWl1Fm.js +2 -0
  142. package/frontend/dist/js/ja-DIJV01rA.js +2 -0
  143. package/frontend/dist/js/ko-Btr9-64X.js +2 -0
  144. package/frontend/dist/js/markdown-CQ4enQcD.js +70 -0
  145. package/frontend/dist/js/{messageCodeStyles-tSFFCV6k.js → messageCodeStyles-BugWE4s5.js} +2 -2
  146. package/frontend/dist/js/ms-DgVmv5zF.js +2 -0
  147. package/frontend/dist/js/nl-Dz5HpdLi.js +2 -0
  148. package/frontend/dist/js/pl-CIATY2b0.js +2 -0
  149. package/frontend/dist/js/postcss-CZstCllf.js +62 -0
  150. package/frontend/dist/js/pt-lrDXX76Y.js +2 -0
  151. package/frontend/dist/js/ru-_zovUYcg.js +2 -0
  152. package/frontend/dist/js/standalone-CttwqOis.js +29 -0
  153. package/frontend/dist/js/{strandsApi-Fs6zV4CA.js → strandsApi-Ck7FrcHH.js} +1 -1
  154. package/frontend/dist/js/sv-TkRDWCb8.js +2 -0
  155. package/frontend/dist/js/{teamEventStream-DD_ASSs5.js → teamEventStream-O3qGbUZz.js} +1 -1
  156. package/frontend/dist/js/th-CQyavDiP.js +2 -0
  157. package/frontend/dist/js/tr-CBcFl4_Z.js +2 -0
  158. package/frontend/dist/js/typescript-h2bi7nrV.js +22 -0
  159. package/frontend/dist/js/{ui-DATtlADq.js → ui-DxaHE9GD.js} +2 -2
  160. package/frontend/dist/js/{ui-vendor-WdvBNwsu.js → ui-vendor-DsURZnZt.js} +1 -1
  161. package/frontend/dist/js/uk-BNn1cUt8.js +2 -0
  162. package/frontend/dist/js/{useChat-RXTiCFz0.js → useChat-1HyAPpCk.js} +1 -1
  163. package/frontend/dist/js/useDictation-B3vNgs5D.js +1 -0
  164. package/frontend/dist/js/{useQuery-DCqz3UJt.js → useQuery-Cs76KYuP.js} +1 -1
  165. package/frontend/dist/js/useTranslation-CKqEdZ8j.js +1 -0
  166. package/frontend/dist/js/utils-BXRzbHJC.js +1 -0
  167. package/frontend/dist/js/{utils-vendor-CsC5rH1J.js → utils-vendor-B4bGLP5p.js} +1 -1
  168. package/frontend/dist/js/vi-Be8GO7e_.js +2 -0
  169. package/frontend/dist/js/{workApi-CbFQfwRZ.js → workApi-BNGRSv7q.js} +1 -1
  170. package/frontend/dist/js/workApi-C5jw1ra6.js +1 -0
  171. package/frontend/dist/js/yaml-CBt8G4BX.js +150 -0
  172. package/frontend/dist/js/zh-9CUKyYw5.js +2 -0
  173. package/package.json +4 -4
  174. package/plugins/anthropic.json +1 -0
  175. package/plugins/baseten.json +17 -0
  176. package/plugins/gemini.json +9 -0
  177. package/plugins/llama-cpp.json +13 -0
  178. package/plugins/meta.json +1 -0
  179. package/plugins/openai.json +13 -0
  180. package/plugins/openrouter.json +26 -0
  181. package/frontend/dist/assets/index-BM0txgxR.css +0 -2
  182. package/frontend/dist/assets/index-CekTqSoE.js +0 -67
  183. package/frontend/dist/js/ChannelsPage-De96Q63V.js +0 -1
  184. package/frontend/dist/js/ChatPage-CTRKLQly.js +0 -14
  185. package/frontend/dist/js/PersonasPage-mzAft_NC.js +0 -13
  186. package/frontend/dist/js/SettingsModal-B-5JP50i.js +0 -19
  187. package/frontend/dist/js/UserManagementPanel-DBwIOSOw.js +0 -1
  188. package/frontend/dist/js/WorkPage-DQlsa18h.js +0 -7
  189. package/frontend/dist/js/api-DdDgFM-F.js +0 -1
  190. package/frontend/dist/js/appVersion-Bl_QXi35.js +0 -1
  191. package/frontend/dist/js/ar-yKmq_nxn.js +0 -2
  192. package/frontend/dist/js/authStore-ByVF8A2u.js +0 -1
  193. package/frontend/dist/js/babel-BaOs8qJH.js +0 -16
  194. package/frontend/dist/js/bn-DAJjz2xA.js +0 -2
  195. package/frontend/dist/js/chatStore-BooPA4cg.js +0 -3
  196. package/frontend/dist/js/cs-BcctV9SN.js +0 -2
  197. package/frontend/dist/js/da-YtnjzG18.js +0 -2
  198. package/frontend/dist/js/de-BMQofu0d.js +0 -2
  199. package/frontend/dist/js/es-8oFYsnHw.js +0 -2
  200. package/frontend/dist/js/estree-Cw-tQG5d.js +0 -44
  201. package/frontend/dist/js/fr-CnGTnuJK.js +0 -2
  202. package/frontend/dist/js/hi-Ct5Inbp9.js +0 -2
  203. package/frontend/dist/js/html-Drt7kOJE.js +0 -25
  204. package/frontend/dist/js/id-CSqCL3hQ.js +0 -2
  205. package/frontend/dist/js/is-Bg68TmSt.js +0 -2
  206. package/frontend/dist/js/it-ZngXlxOR.js +0 -2
  207. package/frontend/dist/js/ja-DfQEoeFi.js +0 -2
  208. package/frontend/dist/js/ko-IifYVGBy.js +0 -2
  209. package/frontend/dist/js/markdown-C7cnJl_Q.js +0 -70
  210. package/frontend/dist/js/ms-C8jQLzkg.js +0 -2
  211. package/frontend/dist/js/nl-BFEa3rgC.js +0 -2
  212. package/frontend/dist/js/pl-BiPrQGU-.js +0 -2
  213. package/frontend/dist/js/postcss-DB_e0nkW.js +0 -62
  214. package/frontend/dist/js/pt-BziWZm5q.js +0 -2
  215. package/frontend/dist/js/ru-oTAEePGS.js +0 -2
  216. package/frontend/dist/js/standalone-YobQElH8.js +0 -29
  217. package/frontend/dist/js/sv-1_et6OWH.js +0 -2
  218. package/frontend/dist/js/th-DjyLzIKs.js +0 -2
  219. package/frontend/dist/js/tr-CCga9CbK.js +0 -2
  220. package/frontend/dist/js/typescript-2anSzo_N.js +0 -22
  221. package/frontend/dist/js/uk-h80KE68A.js +0 -2
  222. package/frontend/dist/js/useDictation-YyALwnw6.js +0 -1
  223. package/frontend/dist/js/useTranslation-D-_KTORQ.js +0 -1
  224. package/frontend/dist/js/utils-DsCVr_wG.js +0 -1
  225. package/frontend/dist/js/vi-CQxzmgwi.js +0 -2
  226. package/frontend/dist/js/workApi-CmH9c1xh.js +0 -1
  227. package/frontend/dist/js/yaml-Breo7DWT.js +0 -154
  228. package/frontend/dist/js/zh-CS3_ndbP.js +0 -2
@@ -0,0 +1,755 @@
1
+ /*
2
+ * Libre WebUI
3
+ * Copyright (C) 2025 Kroonen AI, Inc.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at:
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ /**
18
+ * The tightest limits any supported provider documents, so a request that
19
+ * passes here is not rejected for its shape by any of them. Ollama's cloud
20
+ * takes at most 64 questions named with ASCII letters, digits, `_`, `.`, or
21
+ * `-` and 4 images of 4 MiB (8 MiB in all); a choice takes at most 255
22
+ * options everywhere and a score 2 to 10 levels.
23
+ */
24
+ export const DECISION_LIMITS = {
25
+ maxQuestions: 64,
26
+ maxQuestionNameLength: 100,
27
+ minChoiceOptions: 2,
28
+ maxChoiceOptions: 255,
29
+ minScoreLevels: 2,
30
+ maxScoreLevels: 10,
31
+ maxInstructionsLength: 8000,
32
+ maxCriterionLength: 4000,
33
+ maxStateBytes: 512 * 1024,
34
+ maxImages: 4,
35
+ maxImageBytes: 4 * 1024 * 1024,
36
+ maxTotalImageBytes: 8 * 1024 * 1024,
37
+ };
38
+ const QUESTION_NAME = /^[A-Za-z0-9_.-]+$/;
39
+ const IMAGE_DATA_URL = /^data:(image\/[a-z0-9.+-]+);base64,(.*)$/is;
40
+ const BASE64 = /^[A-Za-z0-9+/]*={0,2}$/;
41
+ export class DecisionValidationError extends Error {
42
+ constructor(message) {
43
+ super(message);
44
+ this.name = 'DecisionValidationError';
45
+ }
46
+ }
47
+ /** A provider answered with an error status or a shape we cannot read. */
48
+ export class DecisionProviderError extends Error {
49
+ constructor(message, status) {
50
+ super(message);
51
+ this.status = status;
52
+ this.name = 'DecisionProviderError';
53
+ }
54
+ }
55
+ const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
56
+ const nonEmptyText = (value) => typeof value === 'string' && value.trim().length > 0;
57
+ function readText(value, label, max) {
58
+ if (!nonEmptyText(value)) {
59
+ throw new DecisionValidationError(`${label} must be a non-empty string.`);
60
+ }
61
+ const text = value.trim();
62
+ if (text.length > max) {
63
+ throw new DecisionValidationError(`${label} must be at most ${max} characters.`);
64
+ }
65
+ return text;
66
+ }
67
+ function readQuestion(name, raw) {
68
+ if (!isRecord(raw)) {
69
+ throw new DecisionValidationError(`Question "${name}" must be an object.`);
70
+ }
71
+ const instructions = readText(raw.instructions, `The instructions of "${name}"`, DECISION_LIMITS.maxInstructionsLength);
72
+ const type = raw.type === 'yesno' ? 'noul' : raw.type;
73
+ if (type === 'choice') {
74
+ if (!isRecord(raw.criteria)) {
75
+ throw new DecisionValidationError(`Choice "${name}" needs criteria: option names mapped to descriptions.`);
76
+ }
77
+ const entries = Object.entries(raw.criteria);
78
+ if (entries.length < DECISION_LIMITS.minChoiceOptions ||
79
+ entries.length > DECISION_LIMITS.maxChoiceOptions) {
80
+ throw new DecisionValidationError(`Choice "${name}" needs ${DECISION_LIMITS.minChoiceOptions} to ${DECISION_LIMITS.maxChoiceOptions} options.`);
81
+ }
82
+ const criteria = {};
83
+ for (const [option, description] of entries) {
84
+ const key = option.trim();
85
+ if (!key || key.length > DECISION_LIMITS.maxQuestionNameLength) {
86
+ throw new DecisionValidationError(`Choice "${name}" has an option without a usable name.`);
87
+ }
88
+ if (Object.prototype.hasOwnProperty.call(criteria, key)) {
89
+ throw new DecisionValidationError(`Choice "${name}" lists the option "${key}" twice.`);
90
+ }
91
+ criteria[key] =
92
+ description === null || description === undefined
93
+ ? null
94
+ : nonEmptyText(description)
95
+ ? readText(description, `The description of "${key}"`, DECISION_LIMITS.maxCriterionLength)
96
+ : null;
97
+ }
98
+ return { type: 'choice', instructions, criteria };
99
+ }
100
+ if (type === 'noul') {
101
+ if (raw.criteria === undefined || raw.criteria === null) {
102
+ return { type: 'noul', instructions };
103
+ }
104
+ if (!isRecord(raw.criteria)) {
105
+ throw new DecisionValidationError(`Yes/no "${name}" criteria must describe "true" and "false".`);
106
+ }
107
+ const extra = Object.keys(raw.criteria).filter(key => key !== 'true' && key !== 'false');
108
+ if (extra.length > 0) {
109
+ throw new DecisionValidationError(`Yes/no "${name}" criteria take only "true" and "false".`);
110
+ }
111
+ const criteria = {};
112
+ for (const key of ['true', 'false']) {
113
+ if (nonEmptyText(raw.criteria[key])) {
114
+ criteria[key] = readText(raw.criteria[key], `The "${key}" description of "${name}"`, DECISION_LIMITS.maxCriterionLength);
115
+ }
116
+ }
117
+ return Object.keys(criteria).length > 0
118
+ ? { type: 'noul', instructions, criteria }
119
+ : { type: 'noul', instructions };
120
+ }
121
+ if (type === 'score') {
122
+ if (!Array.isArray(raw.criteria)) {
123
+ throw new DecisionValidationError(`Score "${name}" needs criteria: levels from lowest to highest.`);
124
+ }
125
+ if (raw.criteria.length < DECISION_LIMITS.minScoreLevels ||
126
+ raw.criteria.length > DECISION_LIMITS.maxScoreLevels) {
127
+ throw new DecisionValidationError(`Score "${name}" needs ${DECISION_LIMITS.minScoreLevels} to ${DECISION_LIMITS.maxScoreLevels} levels.`);
128
+ }
129
+ const criteria = raw.criteria.map((level, index) => readText(level, `Level ${index} of "${name}"`, DECISION_LIMITS.maxCriterionLength));
130
+ return { type: 'score', instructions, criteria };
131
+ }
132
+ throw new DecisionValidationError(`Question "${name}" must be of type choice, noul, or score.`);
133
+ }
134
+ /** Validates a question set, keeping its order. */
135
+ export function parseDecisionQuestions(raw) {
136
+ if (!isRecord(raw)) {
137
+ throw new DecisionValidationError('questions must be an object of named questions.');
138
+ }
139
+ const names = Object.keys(raw);
140
+ if (names.length === 0) {
141
+ throw new DecisionValidationError('Ask at least one question.');
142
+ }
143
+ if (names.length > DECISION_LIMITS.maxQuestions) {
144
+ throw new DecisionValidationError(`Ask at most ${DECISION_LIMITS.maxQuestions} questions at once.`);
145
+ }
146
+ const questions = {};
147
+ for (const name of names) {
148
+ if (name.length > DECISION_LIMITS.maxQuestionNameLength ||
149
+ !QUESTION_NAME.test(name)) {
150
+ throw new DecisionValidationError(`Question names use letters, digits, "_", ".", or "-" (at most ${DECISION_LIMITS.maxQuestionNameLength}): "${name}".`);
151
+ }
152
+ questions[name] = readQuestion(name, raw[name]);
153
+ }
154
+ return questions;
155
+ }
156
+ /** Like parseDecisionQuestions, but an empty set is allowed. */
157
+ export function parseOptionalDecisionQuestions(raw) {
158
+ if (raw === undefined || raw === null)
159
+ return undefined;
160
+ if (isRecord(raw) && Object.keys(raw).length === 0)
161
+ return undefined;
162
+ return parseDecisionQuestions(raw);
163
+ }
164
+ export function parseDecisionState(raw) {
165
+ let state;
166
+ if (typeof raw === 'string') {
167
+ if (!raw.trim()) {
168
+ throw new DecisionValidationError('state must not be empty.');
169
+ }
170
+ state = raw;
171
+ }
172
+ else if (Array.isArray(raw) || isRecord(raw)) {
173
+ if ((Array.isArray(raw) && raw.length === 0) ||
174
+ (isRecord(raw) && Object.keys(raw).length === 0)) {
175
+ throw new DecisionValidationError('state must not be empty.');
176
+ }
177
+ state = raw;
178
+ }
179
+ else {
180
+ throw new DecisionValidationError('state must be text, a JSON object, or a JSON array.');
181
+ }
182
+ const bytes = Buffer.byteLength(typeof state === 'string' ? state : JSON.stringify(state), 'utf8');
183
+ if (bytes > DECISION_LIMITS.maxStateBytes) {
184
+ throw new DecisionValidationError(`state must be at most ${DECISION_LIMITS.maxStateBytes} bytes.`);
185
+ }
186
+ return state;
187
+ }
188
+ function sniffImageMimeType(bytes) {
189
+ if (bytes.length >= 8 &&
190
+ bytes
191
+ .subarray(0, 8)
192
+ .equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) {
193
+ return 'image/png';
194
+ }
195
+ if (bytes.length >= 3 &&
196
+ bytes[0] === 0xff &&
197
+ bytes[1] === 0xd8 &&
198
+ bytes[2] === 0xff) {
199
+ return 'image/jpeg';
200
+ }
201
+ if (bytes.length >= 12 &&
202
+ bytes.subarray(0, 4).toString('latin1') === 'RIFF' &&
203
+ bytes.subarray(8, 12).toString('latin1') === 'WEBP') {
204
+ return 'image/webp';
205
+ }
206
+ return null;
207
+ }
208
+ /**
209
+ * Images as data URLs or bare base64. The format is read from the bytes,
210
+ * not trusted from the prefix: decision APIs take PNG, JPEG, and WebP only.
211
+ */
212
+ export function parseDecisionImages(raw) {
213
+ if (raw === undefined || raw === null)
214
+ return [];
215
+ if (!Array.isArray(raw)) {
216
+ throw new DecisionValidationError('images must be an array.');
217
+ }
218
+ if (raw.length > DECISION_LIMITS.maxImages) {
219
+ throw new DecisionValidationError(`Send at most ${DECISION_LIMITS.maxImages} images.`);
220
+ }
221
+ let total = 0;
222
+ return raw.map((entry, index) => {
223
+ if (typeof entry !== 'string' || entry.length === 0) {
224
+ throw new DecisionValidationError(`Image ${index + 1} is empty.`);
225
+ }
226
+ const match = IMAGE_DATA_URL.exec(entry.trim());
227
+ const data = (match ? match[2] : entry).replace(/\s+/g, '');
228
+ if (!BASE64.test(data)) {
229
+ throw new DecisionValidationError(`Image ${index + 1} must be base64 or a base64 data URL.`);
230
+ }
231
+ const bytes = Buffer.from(data, 'base64');
232
+ if (bytes.length > DECISION_LIMITS.maxImageBytes) {
233
+ throw new DecisionValidationError(`Image ${index + 1} is larger than ${DECISION_LIMITS.maxImageBytes / (1024 * 1024)} MiB.`);
234
+ }
235
+ total += bytes.length;
236
+ if (total > DECISION_LIMITS.maxTotalImageBytes) {
237
+ throw new DecisionValidationError(`Images may total at most ${DECISION_LIMITS.maxTotalImageBytes / (1024 * 1024)} MiB.`);
238
+ }
239
+ const mimeType = sniffImageMimeType(bytes);
240
+ if (!mimeType) {
241
+ throw new DecisionValidationError(`Image ${index + 1} must be a PNG, JPEG, or WebP file.`);
242
+ }
243
+ return { mimeType, data };
244
+ });
245
+ }
246
+ export function parseDecisionInput(raw) {
247
+ return {
248
+ state: parseDecisionState(raw.state),
249
+ images: parseDecisionImages(raw.images),
250
+ questions: parseDecisionQuestions(raw.questions),
251
+ };
252
+ }
253
+ const dataUrl = (image) => `data:${image.mimeType};base64,${image.data}`;
254
+ const stateText = (state) => typeof state === 'string' ? state : JSON.stringify(state, null, 2);
255
+ function systemOneState(input, imageInput) {
256
+ if (input.images.length === 0)
257
+ return { state: input.state };
258
+ switch (imageInput) {
259
+ case 'images':
260
+ return { state: input.state, images: input.images.map(i => i.data) };
261
+ case 'images-data-url':
262
+ return { state: input.state, images: input.images.map(dataUrl) };
263
+ case 'state-messages':
264
+ return {
265
+ state: {
266
+ messages: [
267
+ {
268
+ role: 'user',
269
+ content: [
270
+ { type: 'text', text: stateText(input.state) },
271
+ ...input.images.map(image => ({
272
+ type: 'image_url',
273
+ image_url: { url: dataUrl(image) },
274
+ })),
275
+ ],
276
+ },
277
+ ],
278
+ },
279
+ };
280
+ case 'state-parts':
281
+ return {
282
+ state: [
283
+ stateText(input.state),
284
+ ...input.images.map(image => ({
285
+ type: 'image_url',
286
+ image_url: { url: dataUrl(image) },
287
+ })),
288
+ ],
289
+ };
290
+ case 'none':
291
+ default:
292
+ throw new DecisionValidationError('This provider does not take images with decisions.');
293
+ }
294
+ }
295
+ function openAIInput(input) {
296
+ const textPart = () => {
297
+ if (typeof input.state === 'string') {
298
+ return { type: 'input_text', text: input.state };
299
+ }
300
+ // input_json takes an object or an array of objects; anything else is
301
+ // read as text.
302
+ const objectsOnly = isRecord(input.state) ||
303
+ (Array.isArray(input.state) && input.state.every(isRecord));
304
+ return objectsOnly
305
+ ? { type: 'input_json', data: input.state }
306
+ : { type: 'input_text', text: stateText(input.state) };
307
+ };
308
+ if (typeof input.state === 'string' && input.images.length === 0) {
309
+ return input.state;
310
+ }
311
+ return [
312
+ {
313
+ role: 'user',
314
+ content: [
315
+ textPart(),
316
+ ...input.images.map(image => ({
317
+ type: 'input_image',
318
+ image_url: dataUrl(image),
319
+ })),
320
+ ],
321
+ },
322
+ ];
323
+ }
324
+ function openAIQuestions(questions) {
325
+ return Object.entries(questions).map(([name, question]) => {
326
+ if (question.type === 'choice') {
327
+ return {
328
+ type: 'choice',
329
+ name,
330
+ instructions: question.instructions,
331
+ choices: Object.entries(question.criteria).map(([value, description]) => description ? { value, description } : { value }),
332
+ };
333
+ }
334
+ if (question.type === 'score') {
335
+ return {
336
+ type: 'score',
337
+ name,
338
+ instructions: question.instructions,
339
+ levels: question.criteria.map(label => ({ label })),
340
+ };
341
+ }
342
+ // A predicate has no criteria of its own; what true and false mean
343
+ // becomes part of the statement.
344
+ const meanings = [
345
+ question.criteria?.true ? `True means: ${question.criteria.true}` : '',
346
+ question.criteria?.false ? `False means: ${question.criteria.false}` : '',
347
+ ].filter(Boolean);
348
+ return {
349
+ type: 'predicate',
350
+ name,
351
+ instructions: [question.instructions, ...meanings].join('\n'),
352
+ };
353
+ });
354
+ }
355
+ function geminiInput(input) {
356
+ if (input.images.length === 0)
357
+ return stateText(input.state);
358
+ return [
359
+ { type: 'text', text: stateText(input.state) },
360
+ ...input.images.map(image => ({
361
+ type: 'image',
362
+ data: image.data,
363
+ mime_type: image.mimeType,
364
+ })),
365
+ ];
366
+ }
367
+ function geminiQuestions(questions) {
368
+ const out = {};
369
+ for (const [name, question] of Object.entries(questions)) {
370
+ if (question.type === 'choice') {
371
+ out[name] = {
372
+ type: 'choice',
373
+ instructions: question.instructions,
374
+ criteria: Object.fromEntries(Object.entries(question.criteria).map(([option, description]) => [
375
+ option,
376
+ description ?? option,
377
+ ])),
378
+ };
379
+ }
380
+ else if (question.type === 'score') {
381
+ out[name] = {
382
+ type: 'score',
383
+ instructions: question.instructions,
384
+ criteria: question.criteria,
385
+ };
386
+ }
387
+ else {
388
+ out[name] = {
389
+ type: 'noul',
390
+ instructions: question.instructions,
391
+ ...(question.criteria
392
+ ? {
393
+ criteria: {
394
+ ...(question.criteria.true
395
+ ? { true_description: question.criteria.true }
396
+ : {}),
397
+ ...(question.criteria.false
398
+ ? { false_description: question.criteria.false }
399
+ : {}),
400
+ },
401
+ }
402
+ : {}),
403
+ };
404
+ }
405
+ }
406
+ return out;
407
+ }
408
+ /** The request body one provider expects for a validated decision. */
409
+ export function buildDecisionRequestBody(api, imageInput, model, input) {
410
+ if (api === 'openai') {
411
+ return {
412
+ model,
413
+ input: openAIInput(input),
414
+ questions: openAIQuestions(input.questions),
415
+ };
416
+ }
417
+ if (api === 'gemini') {
418
+ return {
419
+ model,
420
+ input: geminiInput(input),
421
+ questions: geminiQuestions(input.questions),
422
+ };
423
+ }
424
+ const { state, images } = systemOneState(input, imageInput);
425
+ return {
426
+ model,
427
+ state,
428
+ ...(images ? { images } : {}),
429
+ questions: input.questions,
430
+ };
431
+ }
432
+ const probability = (value) => typeof value === 'number' && Number.isFinite(value)
433
+ ? Math.min(1, Math.max(0, value))
434
+ : undefined;
435
+ const count = (value) => typeof value === 'number' && Number.isFinite(value) && value >= 0
436
+ ? Math.round(value)
437
+ : undefined;
438
+ function readProbabilityMap(value) {
439
+ const out = {};
440
+ if (!isRecord(value))
441
+ return out;
442
+ for (const [key, entry] of Object.entries(value)) {
443
+ const p = probability(entry);
444
+ if (p !== undefined)
445
+ out[key] = p;
446
+ }
447
+ return out;
448
+ }
449
+ function scoreLegend(question) {
450
+ return question?.type === 'score'
451
+ ? Object.fromEntries(question.criteria.map((level, i) => [String(i), level]))
452
+ : {};
453
+ }
454
+ function readKeyedAnswer(raw, question) {
455
+ if (!isRecord(raw))
456
+ return undefined;
457
+ const type = raw.type ?? question?.type;
458
+ const confidence = probability(raw.confidence);
459
+ if (type === 'refusal')
460
+ return { type: 'refusal' };
461
+ if (type === 'noul') {
462
+ const noul = probability(raw.noul);
463
+ if (noul === undefined)
464
+ return undefined;
465
+ return confidence === undefined
466
+ ? { type: 'noul', noul }
467
+ : { type: 'noul', noul, confidence };
468
+ }
469
+ if (type === 'choice') {
470
+ const probabilities = readProbabilityMap(raw.probabilities);
471
+ const choice = typeof raw.choice === 'string'
472
+ ? raw.choice
473
+ : Object.entries(probabilities).sort((a, b) => b[1] - a[1])[0]?.[0];
474
+ if (choice === undefined)
475
+ return undefined;
476
+ return {
477
+ type: 'choice',
478
+ choice,
479
+ probabilities,
480
+ ...(confidence !== undefined ? { confidence } : {}),
481
+ };
482
+ }
483
+ if (type === 'score') {
484
+ const score = typeof raw.score === 'number' && Number.isFinite(raw.score)
485
+ ? raw.score
486
+ : undefined;
487
+ if (score === undefined)
488
+ return undefined;
489
+ const legend = isRecord(raw.legend)
490
+ ? Object.fromEntries(Object.entries(raw.legend).filter((entry) => typeof entry[1] === 'string'))
491
+ : scoreLegend(question);
492
+ return {
493
+ type: 'score',
494
+ score,
495
+ legend: Object.keys(legend).length > 0 ? legend : scoreLegend(question),
496
+ probabilities: readProbabilityMap(raw.probabilities),
497
+ ...(confidence !== undefined ? { confidence } : {}),
498
+ };
499
+ }
500
+ return undefined;
501
+ }
502
+ function readOpenAIAnswer(raw, question) {
503
+ const confidence = probability(raw.confidence);
504
+ if (raw.type === 'refusal')
505
+ return { type: 'refusal' };
506
+ if (raw.type === 'predicate') {
507
+ const noul = probability(raw.probability);
508
+ return noul === undefined ? undefined : { type: 'noul', noul };
509
+ }
510
+ if (raw.type === 'choice') {
511
+ const probabilities = {};
512
+ if (Array.isArray(raw.probabilities)) {
513
+ for (const entry of raw.probabilities) {
514
+ if (!isRecord(entry))
515
+ continue;
516
+ const p = probability(entry.probability);
517
+ if (p !== undefined)
518
+ probabilities[String(entry.value)] = p;
519
+ }
520
+ }
521
+ if (raw.choice === undefined || raw.choice === null)
522
+ return undefined;
523
+ return {
524
+ type: 'choice',
525
+ choice: String(raw.choice),
526
+ probabilities,
527
+ ...(confidence !== undefined ? { confidence } : {}),
528
+ };
529
+ }
530
+ if (raw.type === 'score') {
531
+ if (typeof raw.score !== 'number' || !Number.isFinite(raw.score)) {
532
+ return undefined;
533
+ }
534
+ const probabilities = {};
535
+ const legend = scoreLegend(question);
536
+ if (Array.isArray(raw.probabilities)) {
537
+ for (const entry of raw.probabilities) {
538
+ if (!isRecord(entry))
539
+ continue;
540
+ const index = String(entry.value);
541
+ const p = probability(entry.probability);
542
+ if (p !== undefined)
543
+ probabilities[index] = p;
544
+ if (typeof entry.label === 'string' && !legend[index]) {
545
+ legend[index] = entry.label;
546
+ }
547
+ }
548
+ }
549
+ return {
550
+ type: 'score',
551
+ score: raw.score,
552
+ legend,
553
+ probabilities,
554
+ ...(confidence !== undefined ? { confidence } : {}),
555
+ };
556
+ }
557
+ return undefined;
558
+ }
559
+ /** A provider's error body as one line of text. */
560
+ export function readDecisionProviderError(body) {
561
+ if (typeof body === 'string')
562
+ return body.trim().slice(0, 500) || undefined;
563
+ if (!isRecord(body))
564
+ return undefined;
565
+ const error = body.error;
566
+ if (typeof error === 'string' && error.trim())
567
+ return error.trim();
568
+ if (isRecord(error)) {
569
+ if (typeof error.message === 'string' && error.message.trim()) {
570
+ return error.message.trim();
571
+ }
572
+ }
573
+ if (typeof body.message === 'string' && body.message.trim()) {
574
+ return body.message.trim();
575
+ }
576
+ return undefined;
577
+ }
578
+ /**
579
+ * Reads one provider's answer into the neutral shape. Every question must
580
+ * come back; a provider that drops one has not answered the request.
581
+ */
582
+ export function parseDecisionResponse(api, body, questions, requestedModel) {
583
+ if (!isRecord(body)) {
584
+ throw new DecisionProviderError('The decision provider returned an unexpected response.');
585
+ }
586
+ if (api === 'gemini' && isRecord(body.prompt_feedback)) {
587
+ const reason = body.prompt_feedback.block_reason;
588
+ if (typeof reason === 'string' && reason) {
589
+ const message = body.prompt_feedback.block_reason_message;
590
+ throw new DecisionProviderError(`The provider blocked this request (${reason})${typeof message === 'string' && message ? `: ${message}` : '.'}`);
591
+ }
592
+ }
593
+ const answers = {};
594
+ if (api === 'openai') {
595
+ const list = Array.isArray(body.answers) ? body.answers : [];
596
+ const names = Object.keys(questions);
597
+ list.forEach((entry, index) => {
598
+ if (!isRecord(entry))
599
+ return;
600
+ const name = typeof entry.name === 'string' && entry.name
601
+ ? entry.name
602
+ : names[index];
603
+ if (!name)
604
+ return;
605
+ const answer = readOpenAIAnswer(entry, questions[name]);
606
+ if (answer)
607
+ answers[name] = answer;
608
+ });
609
+ }
610
+ else if (isRecord(body.answers)) {
611
+ for (const [name, entry] of Object.entries(body.answers)) {
612
+ const answer = readKeyedAnswer(entry, questions[name]);
613
+ if (answer)
614
+ answers[name] = answer;
615
+ }
616
+ }
617
+ const missing = Object.keys(questions).filter(name => !answers[name]);
618
+ if (missing.length > 0) {
619
+ throw new DecisionProviderError(`The decision provider did not answer: ${missing.join(', ')}.`);
620
+ }
621
+ const usage = {};
622
+ const rawUsage = isRecord(body.usage) ? body.usage : {};
623
+ if (api === 'gemini') {
624
+ usage.inputTokens = count(rawUsage.total_input_tokens);
625
+ usage.outputTokens = count(rawUsage.total_output_tokens);
626
+ usage.cachedTokens = count(rawUsage.total_cached_tokens);
627
+ }
628
+ else {
629
+ usage.inputTokens = count(rawUsage.input_tokens);
630
+ usage.outputTokens = count(rawUsage.output_tokens);
631
+ const details = isRecord(rawUsage.input_tokens_details)
632
+ ? rawUsage.input_tokens_details
633
+ : {};
634
+ usage.cachedTokens = count(details.cached_tokens);
635
+ if (typeof rawUsage.cost === 'number' && Number.isFinite(rawUsage.cost)) {
636
+ usage.costUsd = rawUsage.cost;
637
+ }
638
+ }
639
+ for (const key of Object.keys(usage)) {
640
+ if (usage[key] === undefined)
641
+ delete usage[key];
642
+ }
643
+ return {
644
+ model: typeof body.model === 'string' && body.model
645
+ ? body.model
646
+ : requestedModel,
647
+ answers,
648
+ usage,
649
+ };
650
+ }
651
+ const CLEAR_COMMAND = '/clear';
652
+ export function resolveDecisionChatTurn(messages, savedQuestions) {
653
+ const userMessages = messages.filter(message => message.role === 'user');
654
+ const latest = userMessages[userMessages.length - 1];
655
+ if (!latest) {
656
+ throw new DecisionValidationError('Send a message to decide about.');
657
+ }
658
+ if (savedQuestions && Object.keys(savedQuestions).length > 0) {
659
+ const images = parseDecisionImages(latest.images);
660
+ const text = latest.content.trim();
661
+ if (!text && images.length === 0) {
662
+ throw new DecisionValidationError('Send a message to decide about.');
663
+ }
664
+ return {
665
+ kind: 'decide',
666
+ mode: 'questions',
667
+ input: {
668
+ // Images alone still need a state; it holds the context.
669
+ state: text || 'The attached image.',
670
+ images,
671
+ questions: savedQuestions,
672
+ },
673
+ };
674
+ }
675
+ if (latest.content.trim() === CLEAR_COMMAND)
676
+ return { kind: 'cleared' };
677
+ let stateMessage;
678
+ const asked = [];
679
+ for (const message of userMessages) {
680
+ if (message.content.trim() === CLEAR_COMMAND) {
681
+ stateMessage = undefined;
682
+ asked.length = 0;
683
+ continue;
684
+ }
685
+ if (!stateMessage)
686
+ stateMessage = message;
687
+ else
688
+ asked.push(message);
689
+ }
690
+ if (!stateMessage || asked.length === 0)
691
+ return { kind: 'state' };
692
+ const lines = latest.content
693
+ .split(/\r?\n/)
694
+ .map(line => line.trim())
695
+ .filter(Boolean);
696
+ if (lines.length === 0) {
697
+ throw new DecisionValidationError('Ask a yes/no question about the first message, one per line.');
698
+ }
699
+ if (lines.length > DECISION_LIMITS.maxQuestions) {
700
+ throw new DecisionValidationError(`Ask at most ${DECISION_LIMITS.maxQuestions} questions at once.`);
701
+ }
702
+ const questions = {};
703
+ lines.forEach((line, index) => {
704
+ questions[`q${index + 1}`] = {
705
+ type: 'noul',
706
+ instructions: readText(line, `Question ${index + 1}`, DECISION_LIMITS.maxInstructionsLength),
707
+ };
708
+ });
709
+ const images = parseDecisionImages(stateMessage.images);
710
+ const text = stateMessage.content.trim();
711
+ return {
712
+ kind: 'decide',
713
+ mode: 'interactive',
714
+ input: {
715
+ state: text || 'The attached image.',
716
+ images,
717
+ questions,
718
+ },
719
+ };
720
+ }
721
+ const percent = (value) => `${(Math.round(value * 1000) / 10).toFixed(1)}%`;
722
+ const escapeCell = (value) => value.replace(/\|/g, '\\|').replace(/\r?\n/g, ' ');
723
+ /**
724
+ * The answers as a Markdown table. The chat shows its own rendering from the
725
+ * structured result; this text is what exports, the API, and search see.
726
+ */
727
+ export function renderDecisionMarkdown(questions, result) {
728
+ const rows = Object.entries(questions).map(([name, question]) => {
729
+ const answer = result.answers[name];
730
+ const asked = escapeCell(question.instructions);
731
+ if (!answer || answer.type === 'refusal') {
732
+ return `| ${asked} | declined | |`;
733
+ }
734
+ if (answer.type === 'noul') {
735
+ const yes = answer.noul >= 0.5;
736
+ return `| ${asked} | ${yes ? 'yes' : 'no'} | ${percent(yes ? answer.noul : 1 - answer.noul)} |`;
737
+ }
738
+ if (answer.type === 'choice') {
739
+ const p = answer.probabilities[answer.choice];
740
+ return `| ${asked} | ${escapeCell(answer.choice)} | ${p === undefined ? '' : percent(p)} |`;
741
+ }
742
+ const levels = question.type === 'score'
743
+ ? question.criteria.length
744
+ : Object.keys(answer.legend).length;
745
+ const top = Object.entries(answer.probabilities).sort((a, b) => b[1] - a[1])[0];
746
+ const label = top ? (answer.legend[top[0]] ?? top[0]) : '';
747
+ return `| ${asked} | ${escapeCell(label)} (${(answer.score + 1).toFixed(2)} of ${levels}) | ${top ? percent(top[1]) : ''} |`;
748
+ });
749
+ return [
750
+ '| Question | Answer | Probability |',
751
+ '| --- | --- | --- |',
752
+ ...rows,
753
+ ].join('\n');
754
+ }
755
+ //# sourceMappingURL=decisionProtocol.js.map