@aglyn/plugins-ai 1.0.0-beta.228 → 1.0.0-beta.230

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 (274) hide show
  1. package/README.md +3 -3
  2. package/package.json +17 -17
  3. package/src/lib/activity/ai-activity-actions.js +7 -1
  4. package/src/lib/activity/ai-activity-actions.js.map +1 -1
  5. package/src/lib/components/ai-automation-zones.d.ts +38 -0
  6. package/src/lib/components/ai-automation-zones.js +5 -1
  7. package/src/lib/components/ai-automation-zones.js.map +1 -1
  8. package/src/lib/components/ai-brief-dialog.component.d.ts +20 -2
  9. package/src/lib/components/ai-brief-dialog.component.js +87 -8
  10. package/src/lib/components/ai-brief-dialog.component.js.map +1 -1
  11. package/src/lib/components/ai-campaign-create.component.d.ts +54 -0
  12. package/src/lib/components/ai-campaign-create.component.js +270 -0
  13. package/src/lib/components/ai-campaign-create.component.js.map +1 -0
  14. package/src/lib/components/ai-describe-automation.component.d.ts +8 -3
  15. package/src/lib/components/ai-describe-automation.component.js +15 -6
  16. package/src/lib/components/ai-describe-automation.component.js.map +1 -1
  17. package/src/lib/components/ai-describe-button.component.d.ts +20 -8
  18. package/src/lib/components/ai-describe-button.component.js +19 -36
  19. package/src/lib/components/ai-describe-button.component.js.map +1 -1
  20. package/src/lib/components/ai-describe-email.component.d.ts +31 -0
  21. package/src/lib/components/ai-describe-email.component.js +22 -0
  22. package/src/lib/components/ai-describe-email.component.js.map +1 -0
  23. package/src/lib/components/ai-describe-org-automation.component.d.ts +36 -0
  24. package/src/lib/components/ai-describe-org-automation.component.js +238 -0
  25. package/src/lib/components/ai-describe-org-automation.component.js.map +1 -0
  26. package/src/lib/components/ai-experiment-cards.component.d.ts +9 -1
  27. package/src/lib/components/ai-experiment-cards.component.js +104 -18
  28. package/src/lib/components/ai-experiment-cards.component.js.map +1 -1
  29. package/src/lib/components/ai-explain-automation.component.js +1 -5
  30. package/src/lib/components/ai-explain-automation.component.js.map +1 -1
  31. package/src/lib/components/ai-funnel-zones.component.d.ts +61 -0
  32. package/src/lib/components/ai-funnel-zones.component.js +178 -0
  33. package/src/lib/components/ai-funnel-zones.component.js.map +1 -0
  34. package/src/lib/components/ai-insight-card.component.d.ts +42 -0
  35. package/src/lib/components/ai-insight-card.component.js +137 -0
  36. package/src/lib/components/ai-insight-card.component.js.map +1 -0
  37. package/src/lib/components/ai-insight-dialog.component.d.ts +6 -0
  38. package/src/lib/components/ai-insight-dialog.component.js +9 -3
  39. package/src/lib/components/ai-insight-dialog.component.js.map +1 -1
  40. package/src/lib/components/ai-job-plan.component.d.ts +7 -2
  41. package/src/lib/components/ai-job-plan.component.js +35 -5
  42. package/src/lib/components/ai-job-plan.component.js.map +1 -1
  43. package/src/lib/components/ai-job-requests.d.ts +17 -1
  44. package/src/lib/components/ai-job-requests.js +39 -3
  45. package/src/lib/components/ai-job-requests.js.map +1 -1
  46. package/src/lib/components/ai-jobs-list-page.component.js +12 -1
  47. package/src/lib/components/ai-jobs-list-page.component.js.map +1 -1
  48. package/src/lib/components/ai-logic-zones.d.ts +64 -0
  49. package/src/lib/components/ai-logic-zones.js +18 -0
  50. package/src/lib/components/ai-logic-zones.js.map +1 -0
  51. package/src/lib/components/ai-logic.component.d.ts +77 -0
  52. package/src/lib/components/ai-logic.component.js +553 -0
  53. package/src/lib/components/ai-logic.component.js.map +1 -0
  54. package/src/lib/components/ai-marketing-insight.component.d.ts +30 -0
  55. package/src/lib/components/ai-marketing-insight.component.js +80 -0
  56. package/src/lib/components/ai-marketing-insight.component.js.map +1 -0
  57. package/src/lib/components/ai-media-create.component.d.ts +55 -0
  58. package/src/lib/components/ai-media-create.component.js +433 -0
  59. package/src/lib/components/ai-media-create.component.js.map +1 -0
  60. package/src/lib/components/ai-overlay-cards.component.d.ts +83 -0
  61. package/src/lib/components/ai-overlay-cards.component.js +505 -0
  62. package/src/lib/components/ai-overlay-cards.component.js.map +1 -0
  63. package/src/lib/components/ai-product-zones.d.ts +5 -0
  64. package/src/lib/components/ai-product-zones.js +1 -1
  65. package/src/lib/components/ai-product-zones.js.map +1 -1
  66. package/src/lib/components/ai-products-create-button.component.d.ts +42 -0
  67. package/src/lib/components/ai-products-create-button.component.js +67 -0
  68. package/src/lib/components/ai-products-create-button.component.js.map +1 -0
  69. package/src/lib/components/ai-products-hub-card.component.js +100 -81
  70. package/src/lib/components/ai-products-hub-card.component.js.map +1 -1
  71. package/src/lib/components/ai-revise-automation.component.d.ts +16 -0
  72. package/src/lib/components/ai-revise-automation.component.js +207 -0
  73. package/src/lib/components/ai-revise-automation.component.js.map +1 -0
  74. package/src/lib/components/ai-site-build-page.component.d.ts +1 -1
  75. package/src/lib/components/ai-site-build-page.component.js +177 -20
  76. package/src/lib/components/ai-site-build-page.component.js.map +1 -1
  77. package/src/lib/components/ai-site-start-card.component.d.ts +10 -1
  78. package/src/lib/components/ai-site-start-card.component.js +7 -4
  79. package/src/lib/components/ai-site-start-card.component.js.map +1 -1
  80. package/src/lib/components/ai-upsell-dialog.component.d.ts +53 -0
  81. package/src/lib/components/ai-upsell-dialog.component.js +177 -0
  82. package/src/lib/components/ai-upsell-dialog.component.js.map +1 -0
  83. package/src/lib/components/assist-build-card.component.d.ts +42 -0
  84. package/src/lib/components/assist-build-card.component.js +183 -0
  85. package/src/lib/components/assist-build-card.component.js.map +1 -0
  86. package/src/lib/components/assist-edit-canvas.d.ts +2 -0
  87. package/src/lib/components/assist-edit-canvas.js +56 -1
  88. package/src/lib/components/assist-edit-canvas.js.map +1 -1
  89. package/src/lib/components/assist-jobs-drawer.component.d.ts +11 -0
  90. package/src/lib/components/assist-jobs-drawer.component.js +85 -4
  91. package/src/lib/components/assist-jobs-drawer.component.js.map +1 -1
  92. package/src/lib/components/assist-panel.component.js +51 -2
  93. package/src/lib/components/assist-panel.component.js.map +1 -1
  94. package/src/lib/components/use-ai-job-run.d.ts +3 -14
  95. package/src/lib/components/use-ai-job-run.js +0 -50
  96. package/src/lib/components/use-ai-job-run.js.map +1 -1
  97. package/src/lib/jobs/ai-build-capabilities.d.ts +58 -0
  98. package/src/lib/jobs/ai-build-capabilities.js +256 -0
  99. package/src/lib/jobs/ai-build-capabilities.js.map +1 -0
  100. package/src/lib/jobs/ai-build-unit-outcome.d.ts +52 -0
  101. package/src/lib/jobs/ai-build-unit-outcome.js +138 -0
  102. package/src/lib/jobs/ai-build-unit-outcome.js.map +1 -0
  103. package/src/lib/jobs/ai-job-build-step.d.ts +144 -0
  104. package/src/lib/jobs/ai-job-build-step.js +657 -0
  105. package/src/lib/jobs/ai-job-build-step.js.map +1 -0
  106. package/src/lib/jobs/ai-job-draft-ids.js +9 -1
  107. package/src/lib/jobs/ai-job-draft-ids.js.map +1 -1
  108. package/src/lib/jobs/ai-job-drafts.d.ts +14 -4
  109. package/src/lib/jobs/ai-job-drafts.js +25 -4
  110. package/src/lib/jobs/ai-job-drafts.js.map +1 -1
  111. package/src/lib/jobs/ai-job-layout-site-pages.d.ts +70 -0
  112. package/src/lib/jobs/ai-job-layout-site-pages.js +216 -0
  113. package/src/lib/jobs/ai-job-layout-site-pages.js.map +1 -0
  114. package/src/lib/jobs/ai-job-layout-step.d.ts +2 -2
  115. package/src/lib/jobs/ai-job-layout-step.js +19 -1
  116. package/src/lib/jobs/ai-job-layout-step.js.map +1 -1
  117. package/src/lib/jobs/ai-job-logic-step.d.ts +107 -0
  118. package/src/lib/jobs/ai-job-logic-step.js +395 -0
  119. package/src/lib/jobs/ai-job-logic-step.js.map +1 -0
  120. package/src/lib/jobs/ai-job-overlay-copy.d.ts +70 -0
  121. package/src/lib/jobs/ai-job-overlay-copy.js +178 -0
  122. package/src/lib/jobs/ai-job-overlay-copy.js.map +1 -0
  123. package/src/lib/jobs/ai-job-page-step.js +6 -6
  124. package/src/lib/jobs/ai-job-page-step.js.map +1 -1
  125. package/src/lib/jobs/ai-job-plan-step.d.ts +26 -1
  126. package/src/lib/jobs/ai-job-plan-step.js +79 -11
  127. package/src/lib/jobs/ai-job-plan-step.js.map +1 -1
  128. package/src/lib/jobs/ai-job-site-step.d.ts +15 -1
  129. package/src/lib/jobs/ai-job-site-step.js +207 -58
  130. package/src/lib/jobs/ai-job-site-step.js.map +1 -1
  131. package/src/lib/jobs/ai-job-text-step.d.ts +22 -1
  132. package/src/lib/jobs/ai-job-text-step.js +12 -0
  133. package/src/lib/jobs/ai-job-text-step.js.map +1 -1
  134. package/src/lib/jobs/ai-job-workflow-step.d.ts +54 -4
  135. package/src/lib/jobs/ai-job-workflow-step.js +318 -13
  136. package/src/lib/jobs/ai-job-workflow-step.js.map +1 -1
  137. package/src/lib/jobs/ai-jobs.d.ts +90 -2
  138. package/src/lib/jobs/ai-jobs.js +495 -61
  139. package/src/lib/jobs/ai-jobs.js.map +1 -1
  140. package/src/lib/jobs/ai-logic-records.d.ts +40 -0
  141. package/src/lib/jobs/ai-logic-records.js +55 -0
  142. package/src/lib/jobs/ai-logic-records.js.map +1 -0
  143. package/src/lib/jobs/ai-site-publish.d.ts +7 -0
  144. package/src/lib/jobs/ai-site-publish.js +9 -0
  145. package/src/lib/jobs/ai-site-publish.js.map +1 -1
  146. package/src/lib/jobs/ai-workflow-records.d.ts +4 -0
  147. package/src/lib/jobs/ai-workflow-records.js +40 -1
  148. package/src/lib/jobs/ai-workflow-records.js.map +1 -1
  149. package/src/lib/model/ai-automation-draft.d.ts +18 -0
  150. package/src/lib/model/ai-automation-draft.js +86 -0
  151. package/src/lib/model/ai-automation-draft.js.map +1 -1
  152. package/src/lib/model/ai-build-job.d.ts +201 -0
  153. package/src/lib/model/ai-build-job.js +471 -0
  154. package/src/lib/model/ai-build-job.js.map +1 -0
  155. package/src/lib/model/ai-build-plan.d.ts +61 -0
  156. package/src/lib/model/ai-build-plan.js +154 -9
  157. package/src/lib/model/ai-build-plan.js.map +1 -1
  158. package/src/lib/model/ai-build-progress.d.ts +56 -0
  159. package/src/lib/model/ai-build-progress.js +128 -0
  160. package/src/lib/model/ai-build-progress.js.map +1 -0
  161. package/src/lib/model/ai-insight.d.ts +20 -10
  162. package/src/lib/model/ai-insight.js +72 -9
  163. package/src/lib/model/ai-insight.js.map +1 -1
  164. package/src/lib/model/ai-job-activity.js +3 -1
  165. package/src/lib/model/ai-job-activity.js.map +1 -1
  166. package/src/lib/model/ai-job-failure-copy.d.ts +20 -1
  167. package/src/lib/model/ai-job-failure-copy.js +28 -1
  168. package/src/lib/model/ai-job-failure-copy.js.map +1 -1
  169. package/src/lib/model/ai-job-notice.d.ts +3 -0
  170. package/src/lib/model/ai-job-notice.js +11 -2
  171. package/src/lib/model/ai-job-notice.js.map +1 -1
  172. package/src/lib/model/ai-jobs.types.d.ts +87 -2
  173. package/src/lib/model/ai-jobs.types.js +3 -1
  174. package/src/lib/model/ai-jobs.types.js.map +1 -1
  175. package/src/lib/model/ai-logic-job.d.ts +108 -0
  176. package/src/lib/model/ai-logic-job.js +327 -0
  177. package/src/lib/model/ai-logic-job.js.map +1 -0
  178. package/src/lib/model/ai-media-credits.d.ts +52 -0
  179. package/src/lib/model/ai-media-credits.js +61 -0
  180. package/src/lib/model/ai-media-credits.js.map +1 -0
  181. package/src/lib/model/ai-overlay-copy.d.ts +114 -0
  182. package/src/lib/model/ai-overlay-copy.js +175 -0
  183. package/src/lib/model/ai-overlay-copy.js.map +1 -0
  184. package/src/lib/model/ai-site-build-progress.d.ts +28 -3
  185. package/src/lib/model/ai-site-build-progress.js +231 -17
  186. package/src/lib/model/ai-site-build-progress.js.map +1 -1
  187. package/src/lib/model/ai-site-start-seo.d.ts +16 -0
  188. package/src/lib/model/ai-site-start-seo.js +54 -4
  189. package/src/lib/model/ai-site-start-seo.js.map +1 -1
  190. package/src/lib/model/ai-site-start.d.ts +14 -0
  191. package/src/lib/model/ai-site-start.js +43 -0
  192. package/src/lib/model/ai-site-start.js.map +1 -1
  193. package/src/lib/model/ai-svg.d.ts +69 -0
  194. package/src/lib/model/ai-svg.js +265 -0
  195. package/src/lib/model/ai-svg.js.map +1 -0
  196. package/src/lib/model/ai-usage-by-user.d.ts +3 -2
  197. package/src/lib/model/ai-usage-by-user.js.map +1 -1
  198. package/src/lib/model/ai-workflow-job.d.ts +92 -4
  199. package/src/lib/model/ai-workflow-job.js +124 -7
  200. package/src/lib/model/ai-workflow-job.js.map +1 -1
  201. package/src/lib/model/assist-build.d.ts +58 -0
  202. package/src/lib/model/assist-build.js +52 -0
  203. package/src/lib/model/assist-build.js.map +1 -0
  204. package/src/lib/model/assist-edit.d.ts +48 -3
  205. package/src/lib/model/assist-edit.js +48 -4
  206. package/src/lib/model/assist-edit.js.map +1 -1
  207. package/src/lib/plugin-config.js +2 -0
  208. package/src/lib/plugin-config.js.map +1 -1
  209. package/src/lib/plugin.js +240 -11
  210. package/src/lib/plugin.js.map +1 -1
  211. package/src/lib/providers/catalog.d.ts +81 -4
  212. package/src/lib/providers/catalog.js +80 -9
  213. package/src/lib/providers/catalog.js.map +1 -1
  214. package/src/lib/providers/image-contract.d.ts +116 -0
  215. package/src/lib/providers/image-contract.js +74 -0
  216. package/src/lib/providers/image-contract.js.map +1 -0
  217. package/src/lib/providers/model-choice.js +11 -0
  218. package/src/lib/providers/model-choice.js.map +1 -1
  219. package/src/lib/providers/routing.js +18 -0
  220. package/src/lib/providers/routing.js.map +1 -1
  221. package/src/lib/providers/vertex-image.d.ts +121 -0
  222. package/src/lib/providers/vertex-image.js +312 -0
  223. package/src/lib/providers/vertex-image.js.map +1 -0
  224. package/src/lib/runtime/ai-doctrine-validators.d.ts +19 -0
  225. package/src/lib/runtime/ai-doctrine-validators.js +89 -0
  226. package/src/lib/runtime/ai-doctrine-validators.js.map +1 -1
  227. package/src/lib/runtime/ai-doctrine.d.ts +6 -0
  228. package/src/lib/runtime/ai-doctrine.js +16 -6
  229. package/src/lib/runtime/ai-doctrine.js.map +1 -1
  230. package/src/lib/runtime/ai-eval-live.js +4 -0
  231. package/src/lib/runtime/ai-eval-live.js.map +1 -1
  232. package/src/lib/runtime/ai-eval.d.ts +15 -1
  233. package/src/lib/runtime/ai-eval.js +52 -1
  234. package/src/lib/runtime/ai-eval.js.map +1 -1
  235. package/src/lib/runtime/experiment-variant-copy.d.ts +34 -0
  236. package/src/lib/runtime/experiment-variant-copy.js +102 -0
  237. package/src/lib/runtime/experiment-variant-copy.js.map +1 -0
  238. package/src/lib/server/ai-experiment-versions.d.ts +51 -0
  239. package/src/lib/server/ai-experiment-versions.js +270 -0
  240. package/src/lib/server/ai-experiment-versions.js.map +1 -0
  241. package/src/lib/server/ai-jobs-resume.js +74 -4
  242. package/src/lib/server/ai-jobs-resume.js.map +1 -1
  243. package/src/lib/server/ai-media-image.d.ts +66 -0
  244. package/src/lib/server/ai-media-image.js +521 -0
  245. package/src/lib/server/ai-media-image.js.map +1 -0
  246. package/src/lib/server/ai-media-svg.d.ts +91 -0
  247. package/src/lib/server/ai-media-svg.js +186 -0
  248. package/src/lib/server/ai-media-svg.js.map +1 -0
  249. package/src/lib/server/assist-build.d.ts +54 -0
  250. package/src/lib/server/assist-build.js +121 -0
  251. package/src/lib/server/assist-build.js.map +1 -0
  252. package/src/lib/server/assist-chat.js +108 -12
  253. package/src/lib/server/assist-chat.js.map +1 -1
  254. package/src/lib/server/assist-edit.js +213 -3
  255. package/src/lib/server/assist-edit.js.map +1 -1
  256. package/src/lib/server/assist-view-context.js +242 -4
  257. package/src/lib/server/assist-view-context.js.map +1 -1
  258. package/src/lib/server.js +26 -0
  259. package/src/lib/server.js.map +1 -1
  260. package/src/lib/tools/ai-logic-tool.d.ts +27 -0
  261. package/src/lib/tools/ai-logic-tool.js +207 -0
  262. package/src/lib/tools/ai-logic-tool.js.map +1 -0
  263. package/src/lib/tools/ai-overlay-tool.d.ts +35 -0
  264. package/src/lib/tools/ai-overlay-tool.js +107 -0
  265. package/src/lib/tools/ai-overlay-tool.js.map +1 -0
  266. package/src/lib/tools/ai-workflow-tool.d.ts +11 -0
  267. package/src/lib/tools/ai-workflow-tool.js +31 -0
  268. package/src/lib/tools/ai-workflow-tool.js.map +1 -1
  269. package/src/lib/usage/assist-job-refund.d.ts +31 -3
  270. package/src/lib/usage/assist-job-refund.js +46 -10
  271. package/src/lib/usage/assist-job-refund.js.map +1 -1
  272. package/src/lib/usage/assist-usage.d.ts +5 -0
  273. package/src/lib/usage/assist-usage.js +2 -0
  274. package/src/lib/usage/assist-usage.js.map +1 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/server/ai-media-image.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// lockdown-423: via libs/plugins/ai/src/lib/runtime/ai-gate.ts\n// The POST climbs `aiGateLadder`, whose lockdown rung is the verdict, and\n// every stored picture also passes the upload route's.\n\nimport { mediaFilterKeys } from '@aglyn/aglyn/app-utils/media-metadata'\nimport { MEDIA_ALT_MAX_LENGTH } from '@aglyn/aglyn/app-utils/media-alt'\nimport { aiMediaCreditsPerPicture } from '../model/ai-media-credits'\nimport { aiSvgThemePalette, isAiSvgColor } from '../model/ai-svg'\nimport { estimateAiBilledUsd } from '../providers/catalog'\nimport { AI_UPSTREAM_FAILURE_COPY, AiUpstreamError, type AiUsage } from '../providers/contract'\nimport {\n AI_IMAGE_ASPECT_RATIOS,\n AI_IMAGE_MAX_COUNT,\n AI_IMAGE_PROMPT_MAX_CHARS,\n AI_SVG_MAX_COLORS,\n AI_SVG_STYLES,\n AiImageSafetyRefusal,\n isAiImageAspectRatio,\n type AiImageAspectRatio,\n type AiImageMode,\n type AiImageProvider,\n type AiSvgStyle,\n} from '../providers/image-contract'\nimport { vertexImageProvider } from '../providers/vertex-image'\nimport { aiGateLadder, type AiGateContext } from '../runtime/ai-gate'\nimport { aiInventoryTheme } from '../runtime/site-inventory'\nimport { assistBandRefuses, assistCreditsFromUsd } from '../usage/assist-credits'\nimport {\n publicAssistQuota,\n recordAssistCost,\n releaseAssistMessage,\n} from '../usage/assist-usage'\nimport { aiMediaSvgModel, generateAiMediaSvg, type AiMediaSvgOutcome } from './ai-media-svg'\n\n/**\n * \"Create with AI\" in Media (AGL-3602): pictures from a description, stored\n * in the library that asked.\n *\n * `POST /api/ai/media/images { orgId, library, hostId?, folderId?, mode,\n * prompt, aspectRatio, count, style?, palette? }` answers\n * `{ mediaIds, filtered, failed, credits, warning? }`.\n *\n * Two modes:\n *\n * - `photo` — Google's image models on Vertex AI (`vertex-image.ts`). Off\n * unless the deployment configured them; the door answers 404 with a\n * sentence the dialog shows.\n * - `illustration` — an SVG drawn by the text provider every other AI door\n * uses (`ai-media-svg.ts`): an illustration, an icon, a tileable pattern or\n * a simple logo mark, in the site's theme colors or the person's own. No\n * new vendor, so it runs wherever text AI does.\n *\n * There is no GET: the button draws from the shell's own gates, and this door\n * decides when someone asks for a picture.\n *\n * ## A request, not a job\n *\n * Both modes answer inside the request, the way \"Save as a component with\n * AI\" does, and are metered on the same meter every door uses.\n *\n * ## The money, in order\n *\n * 1. `aiGateLadder` RESERVES before anything is spent: the `aiGenerative`\n * entitlement, `release_ai_generative`, the `ai-generate` kill switch,\n * `ai.generate` on the site, the per-account and per-address windows, the\n * Free taste's own rungs and the band.\n * 2. A workspace whose band is a wall (Free, or a hard cap) is refused before\n * the provider is called when the pictures' estimate is more than it has\n * left.\n * 3. The provider is called. A fault of ours or the provider's hands the\n * reservation back and charges nothing. A declined description charges\n * only what the decline spent, recorded as a declined request (which a\n * Free workspace is never charged for, and which its daily refusal pause\n * counts).\n * 4. Each picture is stored, and only what was stored is SETTLED, at billed\n * rates above the provider's: a photo per picture plus its prompt and\n * thinking, an illustration as the tokens that drew it. A picture held\n * back, one the library refused, and an illustration that failed its\n * safety check twice are never charged — that last one is ours.\n *\n * ## Stored the way any upload is stored\n *\n * Each picture is posted to the console's own `/api/media/upload` with the\n * caller's credential, so the scope, the uploads lockdown, the structural\n * inspection, SVG sanitizing, the quarantine list, the storage band, the CDN\n * variants and the storage counter all apply exactly as they do to a file\n * the person dropped in. This door writes no media document of its own; it\n * only adds, to the documents that route made, the alt text and the record\n * of how the picture was made.\n */\n\n/** The per-account window: a person makes a few sets a minute, not dozens. */\nconst RATE_LIMIT = { key: 'ai-media-image', limit: 6, windowMs: 60_000 }\n\n/** What a person reads when a picture failed on our side. */\nexport const AI_MEDIA_OURS_COPY =\n \"This one's on us — you weren't charged. The picture didn't come out right; try again, or describe it a little differently.\"\n\n/** What the door answers on a deployment that makes no photos. */\nexport const AI_MEDIA_NO_PHOTOS_COPY =\n \"Photos aren't available here yet. Choose Illustration to draw one instead.\"\n\n/** The provider photos come from; a spec stands one in through jest. */\nfunction imageProvider(): AiImageProvider {\n return vertexImageProvider\n}\n\n/** Every control character as a space, squeezed, trimmed and cut. */\nexport function cleanAiImagePrompt(value: unknown): string {\n let out = ''\n for (const char of String(value ?? '')) {\n const code = char.charCodeAt(0)\n out += code < 32 || code === 127 || code === 0x2028 || code === 0x2029 ? ' ' : char\n }\n return out.replace(/\\s+/g, ' ').trim().slice(0, AI_IMAGE_PROMPT_MAX_CHARS)\n}\n\n/**\n * The alt text a picture is stored with: the sentence given, as a sentence,\n * cut at a word inside the library's alt limit. A person edits it like any\n * other.\n */\nexport function aiImageAltText(text: string): string {\n const clean = text.replace(/\\s+/g, ' ').trim()\n if (!clean) return ''\n const sentence = clean.charAt(0).toUpperCase() + clean.slice(1)\n if (sentence.length <= MEDIA_ALT_MAX_LENGTH) return sentence\n const cut = sentence.slice(0, MEDIA_ALT_MAX_LENGTH - 1)\n const space = cut.lastIndexOf(' ')\n return `${(space > 40 ? cut.slice(0, space) : cut).trim()}…`\n}\n\nconst EXTENSIONS: Readonly<Record<string, string>> = {\n 'image/png': 'png',\n 'image/jpeg': 'jpg',\n 'image/webp': 'webp',\n 'image/svg+xml': 'svg',\n}\n\n/** A file name from the description's first words: `ai-a-red-barn-2.png`. */\nexport function aiImageFileName(prompt: string, index: number, mimeType: string): string {\n const words = prompt\n .toLowerCase()\n .normalize('NFKD')\n .replace(/[^a-z0-9\\s-]/g, ' ')\n .split(/\\s+/)\n .filter(Boolean)\n .slice(0, 6)\n .join('-')\n .slice(0, 60)\n .replace(/-+$/, '')\n return `ai-${words || 'image'}-${index + 1}.${EXTENSIONS[mimeType] ?? 'png'}`\n}\n\n/** What the library asked for, read and bounded. */\nexport interface AiMediaImageInput {\n orgId: string\n library: 'host' | 'org'\n /** The site whose library this is, or the site on screen for the org's. */\n hostId: string | null\n folderId: string | null\n mode: AiImageMode\n prompt: string\n aspectRatio: string\n count: number\n /** An illustration's kind; unread for a photo. */\n style: string\n /** An illustration's colors: the site theme's, or these. */\n palette: { source: 'theme' } | { source: 'custom'; colors: string[] }\n}\n\nexport function parseAiMediaImageInput(body: Record<string, unknown> | null): AiMediaImageInput {\n const text = (key: string, limit = 128) => {\n const value = body?.[key]\n return typeof value === 'string' ? value.trim().slice(0, limit) : ''\n }\n const count = Math.floor(Number(body?.['count'] ?? 1))\n const palette = body?.['palette'] as Record<string, unknown> | undefined\n const colors = Array.isArray(palette?.['colors']) ? (palette?.['colors'] as unknown[]) : []\n return {\n orgId: text('orgId'),\n library: body?.['library'] === 'org' ? 'org' : 'host',\n hostId: text('hostId') || null,\n folderId: text('folderId', 64) || null,\n mode: body?.['mode'] === 'illustration' ? 'illustration' : 'photo',\n prompt: cleanAiImagePrompt(body?.['prompt']),\n aspectRatio: text('aspectRatio', 8),\n count: Number.isFinite(count) ? count : 0,\n style: text('style', 24) || 'illustration',\n palette:\n palette?.['source'] === 'custom'\n ? {\n source: 'custom',\n colors: colors\n .map((color) => String(color ?? '').trim().toLowerCase())\n .slice(0, AI_SVG_MAX_COLORS + 1),\n }\n : { source: 'theme' },\n }\n}\n\n/** One stored picture, or the upload route's refusal. */\ntype StoreOutcome = { mediaId: string } | { error: string; status: number }\n\n/**\n * Posts one picture to the console's own upload route, as the caller. The\n * same body the library's Upload button sends, so the route cannot tell the\n * two apart and applies every check it applies to that one.\n */\nasync function storeThroughUploadRoute(\n request: Request,\n input: AiMediaImageInput,\n image: { base64: string; mimeType: string },\n fileName: string,\n): Promise<StoreOutcome> {\n const scope =\n input.library === 'org'\n ? { orgId: input.orgId, ...(input.hostId ? { forHostId: input.hostId } : {}) }\n : { hostId: input.hostId }\n let response: Response\n try {\n response = await fetch(new URL('/api/media/upload', request.url), {\n method: 'POST',\n headers: {\n Authorization: request.headers.get('authorization') ?? '',\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n ...scope,\n fileName,\n contentType: image.mimeType,\n folderId: input.folderId,\n data: image.base64,\n }),\n })\n } catch {\n return { error: 'The picture could not be saved to the media library.', status: 502 }\n }\n const payload = (await response.json().catch(() => ({}))) as Record<string, unknown>\n const mediaId = typeof payload['mediaId'] === 'string' ? payload['mediaId'] : ''\n if (response.ok && mediaId) return { mediaId }\n return {\n error:\n typeof payload['error'] === 'string'\n ? payload['error']\n : 'The picture could not be saved to the media library.',\n status: response.ok ? 502 : response.status,\n }\n}\n\n/** The record a generated picture keeps of how it was made. */\nexport interface AiMediaProvenance {\n model: string\n prompt: string\n mode: AiImageMode\n /** An illustration's kind; absent on a photo. */\n style?: AiSvgStyle\n aspectRatio: string\n /** The meter's signal id for the request that made it. */\n signalId: string | null\n generatedBy: string\n}\n\n/**\n * Adds the alt text and the provenance to a document the upload route made.\n * An `update`, which cannot mint a document: the route minted it.\n */\nasync function annotateStoredImage(\n gate: AiGateContext,\n input: AiMediaImageInput,\n mediaId: string,\n alt: string,\n provenance: AiMediaProvenance,\n): Promise<void> {\n const scopeRef =\n input.library === 'org'\n ? gate.firestore.collection('orgs').doc(input.orgId)\n : gate.firestore.collection('hosts').doc(String(input.hostId))\n const mediaRef = scopeRef.collection('media').doc(mediaId)\n const stored = ((await mediaRef.get()).data() ?? {}) as Parameters<typeof mediaFilterKeys>[0]\n await mediaRef.update({\n alt,\n description: 'Created with AI from a description.',\n aiGenerated: { ...provenance, createdAt: new Date() },\n // What the library filters by, restamped with the alt now set: the upload\n // route wrote \"Alt text is missing\" before the alt existed.\n ...mediaFilterKeys({ ...stored, alt }),\n })\n}\n\n/** The colors an illustration is drawn in. */\nasync function illustrationPalette(\n gate: AiGateContext,\n input: AiMediaImageInput,\n): Promise<string[]> {\n if (input.palette.source === 'custom') return input.palette.colors\n if (!input.hostId) return []\n const snapshot = await gate.firestore.collection('hosts').doc(input.hostId).get()\n return aiSvgThemePalette(aiInventoryTheme(snapshot.exists ? snapshot.data() ?? null : null)?.colors)\n}\n\nconst ZERO_USAGE: AiUsage = { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0 }\n\nconst sumUsage = (usages: readonly AiUsage[]): AiUsage =>\n usages.reduce<AiUsage>(\n (sum, usage) => ({\n inputTokens: sum.inputTokens + usage.inputTokens,\n outputTokens: sum.outputTokens + usage.outputTokens,\n cacheReadTokens: sum.cacheReadTokens + usage.cacheReadTokens,\n cacheWriteTokens: sum.cacheWriteTokens + usage.cacheWriteTokens,\n }),\n ZERO_USAGE,\n )\n\n/** A picture made, before it is stored. */\ninterface MadePicture {\n base64: string\n mimeType: string\n alt: string\n /** What making it spent, charged only once it is stored. */\n usage: AiUsage\n}\n\nexport async function POST(request: Request): Promise<Response> {\n let body: Record<string, unknown> | null\n try {\n body = (await request.json()) as Record<string, unknown>\n } catch {\n body = null\n }\n const input = parseAiMediaImageInput(body)\n const provider = imageProvider()\n const svgModel = input.mode === 'illustration' ? aiMediaSvgModel() : undefined\n // A deployment that makes no pictures of this kind has no such door, so\n // nothing about the caller or the workspace is read first.\n if (input.mode === 'photo' && !provider.configured()) {\n return Response.json({ error: AI_MEDIA_NO_PHOTOS_COPY, reason: 'unavailable' }, { status: 404 })\n }\n if (input.mode === 'illustration' && !svgModel) {\n return Response.json({ error: 'Not found' }, { status: 404 })\n }\n\n const gate = await aiGateLadder(\n { request, orgId: input.orgId, hostId: input.hostId },\n {\n feature: 'aiGenerative',\n releaseFlag: 'release_ai_generative',\n lockdownFeature: 'ai-generate',\n permission: 'ai.generate',\n rateLimit: RATE_LIMIT,\n },\n )\n if (gate instanceof Response) return gate\n // Nothing is spent until a provider answers, so every exit before it\n // hands the reservation back.\n const release = () =>\n releaseAssistMessage(gate.firestore, gate.orgId, gate.reservation).catch(() => undefined)\n const refuse = async (error: string, status: number, extra: Record<string, unknown> = {}) => {\n await release()\n return Response.json({ error, ...extra }, { status })\n }\n\n if (input.library === 'host' && !input.hostId) {\n return refuse('Open the site whose media library the pictures go in.', 400)\n }\n if (!input.prompt) return refuse('Describe the picture you want first.', 400)\n if (!isAiImageAspectRatio(input.aspectRatio)) {\n return refuse(`Choose a shape: ${AI_IMAGE_ASPECT_RATIOS.join(', ')}.`, 400)\n }\n const aspectRatio: AiImageAspectRatio = input.aspectRatio\n if (input.count < 1 || input.count > AI_IMAGE_MAX_COUNT) {\n return refuse(`Make between 1 and ${AI_IMAGE_MAX_COUNT} pictures at a time.`, 400)\n }\n if (input.mode === 'illustration') {\n if (!(AI_SVG_STYLES as readonly string[]).includes(input.style)) {\n return refuse('Choose an illustration, an icon, a pattern or a logo mark.', 400)\n }\n if (\n input.palette.source === 'custom' &&\n (!input.palette.colors.length ||\n input.palette.colors.length > AI_SVG_MAX_COLORS ||\n !input.palette.colors.every(isAiSvgColor))\n ) {\n return refuse(`Give between 1 and ${AI_SVG_MAX_COLORS} colors as hex values, such as #1a73e8.`, 400)\n }\n }\n\n const model = input.mode === 'photo' ? provider.defaultModel() : (svgModel as string)\n const perPicture = aiMediaCreditsPerPicture(input.mode, model)\n const estimate = perPicture * input.count\n const credits = publicAssistQuota(gate.reservation).credits\n if (credits && assistBandRefuses(gate.org) && credits.remaining < estimate) {\n return refuse(\n credits.remaining < perPicture\n ? 'This workspace has used its AI credits for the month.'\n : `That needs about ${estimate} credits and this workspace has ${credits.remaining} left this month. Make fewer pictures.`,\n 429,\n { reason: 'quota', quota: publicAssistQuota(gate.reservation) },\n )\n }\n\n /** Records what a decline spent: a declined request, never a picture. */\n const recordDecline = (usage: AiUsage, declinedModel: string) =>\n recordAssistCost(gate.firestore, gate.orgId, {\n route: '/api/ai/media/images',\n hostId: input.hostId,\n model: declinedModel,\n tier: 'entitled',\n usage: { ...usage, images: 0 },\n docsPaths: [],\n stopReason: 'refusal',\n free: gate.reservation.free ?? null,\n uid: gate.uid,\n kind: 'image',\n }).catch((meterError) =>\n console.error('ai media refusal not recorded', { orgId: gate.orgId, meterError }),\n )\n\n let made: MadePicture[]\n /** Pictures asked for and not made: held back, declined or failed on our side. */\n let unmade: number\n /** Tokens a photo request spent beside its pictures, charged once any is stored. */\n let photoUsage: AiUsage = ZERO_USAGE\n let declineReason: string | null = null\n let style: AiSvgStyle | undefined\n\n if (input.mode === 'photo') {\n try {\n const result = await provider.generate({\n model,\n prompt: input.prompt,\n aspectRatio,\n count: input.count,\n })\n photoUsage = result.usage\n unmade = result.filtered\n made = result.images.map((image) => ({\n ...image,\n alt: aiImageAltText(input.prompt),\n usage: ZERO_USAGE,\n }))\n } catch (error) {\n if (error instanceof AiImageSafetyRefusal) {\n // Declined, not failed: no picture is charged, and the request is\n // recorded as a declined one so the Free taste's refusal pause\n // counts it.\n await recordDecline(ZERO_USAGE, model)\n return Response.json({ error: error.message, reason: 'safety' }, { status: 422 })\n }\n await release()\n console.error('ai photo generation failed', { orgId: gate.orgId, error })\n const status = error instanceof AiUpstreamError && error.accountProblem ? 503 : 502\n return Response.json({ error: AI_UPSTREAM_FAILURE_COPY }, { status })\n }\n } else {\n style = input.style as AiSvgStyle\n const palette = await illustrationPalette(gate, input)\n const settled = await Promise.allSettled(\n Array.from({ length: input.count }, (_unused, variant) =>\n generateAiMediaSvg({\n model,\n prompt: input.prompt,\n style: style as AiSvgStyle,\n aspectRatio,\n palette,\n variant,\n count: input.count,\n }),\n ),\n )\n const outcomes = settled.flatMap((entry) =>\n entry.status === 'fulfilled' ? [entry.value] : [],\n )\n if (!outcomes.length) {\n await release()\n console.error('ai illustration generation failed', {\n orgId: gate.orgId,\n error: (settled[0] as PromiseRejectedResult | undefined)?.reason,\n })\n return Response.json({ error: AI_UPSTREAM_FAILURE_COPY }, { status: 502 })\n }\n const drawn = outcomes.filter(\n (outcome): outcome is Extract<AiMediaSvgOutcome, { kind: 'drawn' }> => outcome.kind === 'drawn',\n )\n const declined = outcomes.filter((outcome) => outcome.kind === 'declined')\n unmade = input.count - drawn.length\n declineReason =\n (declined[0] as Extract<AiMediaSvgOutcome, { kind: 'declined' }> | undefined)?.reason ?? null\n made = drawn.map((outcome) => ({\n base64: Buffer.from(outcome.svg, 'utf8').toString('base64'),\n mimeType: 'image/svg+xml',\n alt: aiImageAltText(outcome.alt || input.prompt),\n usage: outcome.usage,\n }))\n if (!made.length) {\n if (declined.length) {\n // The model declined: what it spent is a declined request.\n await recordDecline(sumUsage(declined.map((outcome) => outcome.usage)), model)\n return Response.json({ error: declineReason, reason: 'safety' }, { status: 422 })\n }\n // Every picture failed its check twice. Ours, so nothing is charged.\n await release()\n return Response.json({ error: AI_MEDIA_OURS_COPY, reason: 'ours' }, { status: 502 })\n }\n }\n\n const stored: Array<{ mediaId: string; picture: MadePicture }> = []\n let refusal: { error: string; status: number } | null = null\n for (const [index, picture] of made.entries()) {\n const outcome = await storeThroughUploadRoute(\n request,\n input,\n picture,\n aiImageFileName(input.prompt, index, picture.mimeType),\n )\n if ('mediaId' in outcome) stored.push({ mediaId: outcome.mediaId, picture })\n else refusal ??= outcome\n }\n\n if (!stored.length) {\n // Made and not kept: the library refused every picture (its storage\n // band, a lockdown, a permission), so nothing is charged.\n await release()\n return Response.json(\n { error: refusal?.error ?? 'The pictures could not be saved.' },\n { status: refusal?.status ?? 502 },\n )\n }\n\n // Only what was stored is settled: a photo's pictures at the per-picture\n // rate with the request's prompt and thinking, an illustration's tokens.\n const usage =\n input.mode === 'photo'\n ? { ...photoUsage, images: stored.length }\n : sumUsage(stored.map((entry) => entry.picture.usage))\n let signalId: string | null = null\n try {\n signalId = await recordAssistCost(gate.firestore, gate.orgId, {\n route: '/api/ai/media/images',\n hostId: input.hostId,\n model,\n tier: 'entitled',\n usage,\n docsPaths: [],\n stopReason: 'end_turn',\n free: gate.reservation.free ?? null,\n uid: gate.uid,\n kind: 'image',\n })\n } catch (error) {\n // The pictures are in the library and were paid for by us; a meter\n // that could not be written is not a reason to hide them.\n console.error('ai media usage not recorded', { orgId: gate.orgId, error })\n }\n\n await Promise.all(\n stored.map(({ mediaId, picture }) =>\n annotateStoredImage(gate, input, mediaId, picture.alt, {\n model,\n prompt: input.prompt,\n mode: input.mode,\n ...(style ? { style } : {}),\n aspectRatio,\n signalId,\n generatedBy: gate.uid,\n }).catch((error) => console.error('ai media alt text not written', { mediaId, error })),\n ),\n )\n\n const warning =\n refusal?.error ??\n (declineReason && unmade > 0 ? declineReason : unmade > 0 && input.mode === 'illustration'\n ? AI_MEDIA_OURS_COPY\n : null)\n return Response.json({\n mediaIds: stored.map((entry) => entry.mediaId),\n filtered: unmade,\n failed: made.length - stored.length,\n // What was charged, as the meter priced it.\n credits: assistCreditsFromUsd(estimateAiBilledUsd(usage, model)),\n ...(warning ? { warning } : {}),\n })\n}\n"],"names":["mediaFilterKeys","MEDIA_ALT_MAX_LENGTH","aiMediaCreditsPerPicture","aiSvgThemePalette","isAiSvgColor","estimateAiBilledUsd","AI_UPSTREAM_FAILURE_COPY","AiUpstreamError","AI_IMAGE_ASPECT_RATIOS","AI_IMAGE_MAX_COUNT","AI_IMAGE_PROMPT_MAX_CHARS","AI_SVG_MAX_COLORS","AI_SVG_STYLES","AiImageSafetyRefusal","isAiImageAspectRatio","vertexImageProvider","aiGateLadder","aiInventoryTheme","assistBandRefuses","assistCreditsFromUsd","publicAssistQuota","recordAssistCost","releaseAssistMessage","aiMediaSvgModel","generateAiMediaSvg","RATE_LIMIT","key","limit","windowMs","AI_MEDIA_OURS_COPY","AI_MEDIA_NO_PHOTOS_COPY","imageProvider","cleanAiImagePrompt","value","out","char","String","code","charCodeAt","replace","trim","slice","aiImageAltText","text","clean","sentence","charAt","toUpperCase","length","cut","space","lastIndexOf","EXTENSIONS","aiImageFileName","prompt","index","mimeType","words","toLowerCase","normalize","split","filter","Boolean","join","parseAiMediaImageInput","body","count","Math","floor","Number","palette","colors","Array","isArray","orgId","library","hostId","folderId","mode","aspectRatio","isFinite","style","source","map","color","storeThroughUploadRoute","request","input","image","fileName","scope","forHostId","response","fetch","URL","url","method","headers","Authorization","get","JSON","stringify","contentType","data","base64","error","status","payload","json","catch","mediaId","ok","annotateStoredImage","gate","alt","provenance","scopeRef","firestore","collection","doc","mediaRef","stored","update","description","aiGenerated","createdAt","Date","illustrationPalette","snapshot","exists","ZERO_USAGE","inputTokens","outputTokens","cacheReadTokens","cacheWriteTokens","sumUsage","usages","reduce","sum","usage","POST","provider","svgModel","undefined","configured","Response","reason","feature","releaseFlag","lockdownFeature","permission","rateLimit","release","reservation","refuse","extra","includes","every","model","defaultModel","perPicture","estimate","credits","org","remaining","quota","recordDecline","declinedModel","route","tier","images","docsPaths","stopReason","free","uid","kind","meterError","console","made","unmade","photoUsage","declineReason","result","generate","filtered","message","accountProblem","declined","settled","Promise","allSettled","from","_unused","variant","outcomes","flatMap","entry","drawn","outcome","Buffer","svg","toString","refusal","picture","entries","push","signalId","all","generatedBy","warning","mediaIds","failed"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,+DAA+D;AAC/D,0EAA0E;AAC1E,uDAAuD;AAEvD,SAASA,eAAe,QAAQ,wCAAuC;AACvE,SAASC,oBAAoB,QAAQ,mCAAkC;AACvE,SAASC,wBAAwB,QAAQ,+BAA2B;AACpE,SAASC,iBAAiB,EAAEC,YAAY,QAAQ,qBAAiB;AACjE,SAASC,mBAAmB,QAAQ,0BAAsB;AAC1D,SAASC,wBAAwB,EAAEC,eAAe,QAA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KlI,MAAM,GAAGyE,OAAOzE,MAAM;QACnC,4CAA4C;QAC5CkH,SAAS/I,qBAAqBd,oBAAoBsI,OAAOmB;OACrDmD,UAAU;QAAEA;IAAQ,IAAI,CAAC;AAEjC"}
@@ -0,0 +1,91 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
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
+ import type { AiSystemBlock, AiTool, AiUsage } from '../providers/contract';
18
+ import type { AiImageAspectRatio, AiSvgStyle } from '../providers/image-contract';
19
+ import { type AiGenerationCheckResult } from '../runtime/ai-doctrine';
20
+ /**
21
+ * Illustrations in Media (AGL-3602): an SVG drawn by the TEXT provider every
22
+ * other AI door uses — the same registry, the same meter, the same data flow
23
+ * the published subprocessor row for the text provider already describes —
24
+ * so this mode needs no new vendor and runs wherever text AI does.
25
+ *
26
+ * One generation per picture, through `runValidatedGeneration`: the answer
27
+ * arrives through a strict tool, `checkAiSvgMarkup` is its check, and an
28
+ * answer with a problem is sent back once with what to fix. A second answer
29
+ * with a problem is not stored and, being our failure, not charged.
30
+ *
31
+ * It runs on the provider's fast tier: an SVG is a few thousand tokens of
32
+ * markup and the door answers inside one request, so the model that writes
33
+ * them quickest is the one that fits.
34
+ */
35
+ /** The doctrine kind the generation runs under; it reads no site tree. */
36
+ export declare const AI_MEDIA_SVG_KIND = "media-svg";
37
+ /** The name of the tool the picture arrives through. */
38
+ export declare const AI_MEDIA_SVG_TOOL_NAME = "submit_svg";
39
+ /** The answer ceiling: room for a compact picture and a re-ask's worth of care. */
40
+ export declare const AI_MEDIA_SVG_MAX_TOKENS = 6000;
41
+ export declare const AI_MEDIA_SVG_INSTRUCTIONS: AiSystemBlock[];
42
+ export declare function aiMediaSvgTool(): AiTool;
43
+ /** The question one picture is asked as. */
44
+ export declare function aiMediaSvgPrompt(input: {
45
+ prompt: string;
46
+ style: AiSvgStyle;
47
+ aspectRatio: AiImageAspectRatio;
48
+ palette: readonly string[];
49
+ variant: number;
50
+ count: number;
51
+ }): string;
52
+ /** What one picture's answer holds once it is read. */
53
+ export type AiMediaSvgAnswer = {
54
+ svg: string;
55
+ alt: string;
56
+ } | {
57
+ declined: string;
58
+ };
59
+ /** The check one answer is held to: the SVG gate, or a decline. */
60
+ export declare function checkAiMediaSvgAnswer(answer: Record<string, unknown>, aspectRatio: AiImageAspectRatio, style: AiSvgStyle): AiGenerationCheckResult<AiMediaSvgAnswer>;
61
+ /** The model an illustration runs on: the text provider's fast tier. */
62
+ export declare function aiMediaSvgModel(): string | undefined;
63
+ /** One picture's outcome. */
64
+ export type AiMediaSvgOutcome = {
65
+ kind: 'drawn';
66
+ svg: string;
67
+ alt: string;
68
+ usage: AiUsage;
69
+ model: string;
70
+ } | {
71
+ kind: 'declined';
72
+ reason: string;
73
+ usage: AiUsage;
74
+ model: string;
75
+ }
76
+ /** The re-ask still failed the gate, or the model stopped: ours, never charged. */
77
+ | {
78
+ kind: 'failed';
79
+ usage: AiUsage;
80
+ model: string;
81
+ };
82
+ /** Draws one picture. A provider fault propagates for the door to answer. */
83
+ export declare function generateAiMediaSvg(input: {
84
+ model: string;
85
+ prompt: string;
86
+ style: AiSvgStyle;
87
+ aspectRatio: AiImageAspectRatio;
88
+ palette: readonly string[];
89
+ variant: number;
90
+ count: number;
91
+ }): Promise<AiMediaSvgOutcome>;
@@ -0,0 +1,186 @@
1
+ import { _ as _extends } from "@swc/helpers/_/_extends";
2
+ /**
3
+ * @license
4
+ * Copyright 2026 Aglyn LLC
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */ import { aiDefaultModelFor } from "../providers/catalog.js";
18
+ import { resolveAiProvider } from "../providers/routing.js";
19
+ import { AI_SVG_MAX_BYTES, AI_SVG_VIEWBOX, checkAiSvgMarkup } from "../model/ai-svg.js";
20
+ import { runValidatedGeneration } from "../runtime/ai-doctrine.js";
21
+ /**
22
+ * Illustrations in Media (AGL-3602): an SVG drawn by the TEXT provider every
23
+ * other AI door uses — the same registry, the same meter, the same data flow
24
+ * the published subprocessor row for the text provider already describes —
25
+ * so this mode needs no new vendor and runs wherever text AI does.
26
+ *
27
+ * One generation per picture, through `runValidatedGeneration`: the answer
28
+ * arrives through a strict tool, `checkAiSvgMarkup` is its check, and an
29
+ * answer with a problem is sent back once with what to fix. A second answer
30
+ * with a problem is not stored and, being our failure, not charged.
31
+ *
32
+ * It runs on the provider's fast tier: an SVG is a few thousand tokens of
33
+ * markup and the door answers inside one request, so the model that writes
34
+ * them quickest is the one that fits.
35
+ */ /** The doctrine kind the generation runs under; it reads no site tree. */ export const AI_MEDIA_SVG_KIND = 'media-svg';
36
+ /** The name of the tool the picture arrives through. */ export const AI_MEDIA_SVG_TOOL_NAME = 'submit_svg';
37
+ /** The answer ceiling: room for a compact picture and a re-ask's worth of care. */ export const AI_MEDIA_SVG_MAX_TOKENS = 6000;
38
+ /** What each kind of illustration is, in the words the model is given. */ const STYLE_BRIEF = {
39
+ illustration: 'A spot illustration or small scene: flat or lightly shaded vector shapes, clear silhouettes, no photographic detail.',
40
+ icon: 'A single icon: bold, simple geometry centered with even padding, in ONE color, or two tones of the palette at most. Readable at 24 pixels.',
41
+ pattern: 'A seamless, tileable background pattern: every shape that leaves one edge re-enters at the opposite edge, so tiles join without a seam. Low contrast, suitable behind text.',
42
+ logo: "A simple abstract logo MARK: a symbol made of a few shapes, with no lettering at all. Never a real company's logo, a trademark, a brand's symbol or anything imitating one."
43
+ };
44
+ const INSTRUCTIONS = [
45
+ 'You draw SVG pictures for a website owner. You receive what to draw, which kind of picture it is, its shape and the colors to use, and you answer through the submit_svg tool.',
46
+ '',
47
+ 'The SVG you write must:',
48
+ '- be exactly one <svg> element with xmlns="http://www.w3.org/2000/svg" and the viewBox you are given, and no width or height attributes;',
49
+ '- use only shapes, paths, groups, gradients, clipPaths and masks drawn in the document itself: never <image>, <foreignObject>, <script>, <a>, animation elements, event attributes, or a href or url(...) pointing anywhere but #ids in the same SVG;',
50
+ '- use no web fonts, @import or @font-face; prefer no text at all, and use only generic font families (sans-serif, serif) when text is essential;',
51
+ `- stay compact: well under ${Math.round(AI_SVG_MAX_BYTES / 1024 / 4)} KB, with few paths and coordinates rounded to at most one decimal place;`,
52
+ '- use the colors given, plus white, black and transparency, and no others.',
53
+ '',
54
+ 'Write alt text: one plain sentence describing what the picture shows, for someone who cannot see it.',
55
+ '',
56
+ "Decline instead of drawing — set declined to one short sentence and leave svg and alt empty — when you are asked for a real company's or organization's logo, a trademark, a recognizable brand symbol or anything imitating one; for a real, named person; or for anything sexual, hateful, violent or otherwise unsafe. Otherwise set declined to an empty string."
57
+ ].join('\n');
58
+ export const AI_MEDIA_SVG_INSTRUCTIONS = [
59
+ {
60
+ text: INSTRUCTIONS,
61
+ cacheBreakpoint: true
62
+ }
63
+ ];
64
+ export function aiMediaSvgTool() {
65
+ return {
66
+ name: AI_MEDIA_SVG_TOOL_NAME,
67
+ description: 'Submit the SVG picture and its alt text, or decline.',
68
+ strict: true,
69
+ inputSchema: {
70
+ type: 'object',
71
+ additionalProperties: false,
72
+ required: [
73
+ 'svg',
74
+ 'alt',
75
+ 'declined'
76
+ ],
77
+ properties: {
78
+ svg: {
79
+ type: 'string',
80
+ description: 'The whole SVG document, starting with <svg and ending with </svg>.'
81
+ },
82
+ alt: {
83
+ type: 'string',
84
+ description: 'One plain sentence describing the picture.'
85
+ },
86
+ declined: {
87
+ type: 'string',
88
+ description: 'Empty, or one short sentence saying why this picture is not drawn.'
89
+ }
90
+ }
91
+ }
92
+ };
93
+ }
94
+ /** The question one picture is asked as. */ export function aiMediaSvgPrompt(input) {
95
+ const colors = input.palette.length ? `Colors: ${input.palette.join(', ')}.` : 'Colors: a restrained palette of three to five colors of your choice.';
96
+ const lines = [
97
+ `Kind: ${input.style}. ${STYLE_BRIEF[input.style]}`,
98
+ `Shape: ${input.aspectRatio}, viewBox="${AI_SVG_VIEWBOX[input.aspectRatio]}".`,
99
+ colors
100
+ ];
101
+ if (input.count > 1) {
102
+ lines.push(`This is version ${input.variant + 1} of ${input.count}: make it a distinct take on the same description.`);
103
+ }
104
+ lines.push('', 'Draw:', input.prompt);
105
+ return lines.join('\n');
106
+ }
107
+ /** The check one answer is held to: the SVG gate, or a decline. */ export function checkAiMediaSvgAnswer(answer, aspectRatio, style) {
108
+ const declined = typeof answer['declined'] === 'string' ? answer['declined'].trim() : '';
109
+ if (declined) return {
110
+ value: {
111
+ declined: declined.slice(0, 300)
112
+ },
113
+ violations: []
114
+ };
115
+ const result = checkAiSvgMarkup(answer['svg'], aspectRatio, style);
116
+ const alt = typeof answer['alt'] === 'string' ? answer['alt'].replace(/\s+/g, ' ').trim().slice(0, 300) : '';
117
+ if (result.svg) return {
118
+ value: {
119
+ svg: result.svg,
120
+ alt
121
+ },
122
+ violations: []
123
+ };
124
+ const violations = result.problems.map((problem)=>({
125
+ rule: null,
126
+ code: `svg-${problem.code}`,
127
+ message: 'The picture could not be drawn safely.',
128
+ detail: problem.detail
129
+ }));
130
+ return {
131
+ value: {
132
+ svg: '',
133
+ alt
134
+ },
135
+ violations,
136
+ offending: {
137
+ svg: '(see the problems listed)'
138
+ }
139
+ };
140
+ }
141
+ /** The model an illustration runs on: the text provider's fast tier. */ export function aiMediaSvgModel() {
142
+ const provider = resolveAiProvider();
143
+ return provider ? aiDefaultModelFor(provider.id, 'fast') : undefined;
144
+ }
145
+ /** Draws one picture. A provider fault propagates for the door to answer. */ export async function generateAiMediaSvg(input) {
146
+ const generation = {
147
+ model: input.model,
148
+ instructions: AI_MEDIA_SVG_INSTRUCTIONS,
149
+ inventory: undefined,
150
+ messages: [
151
+ {
152
+ role: 'user',
153
+ content: aiMediaSvgPrompt(input)
154
+ }
155
+ ],
156
+ tool: aiMediaSvgTool(),
157
+ maxTokens: AI_MEDIA_SVG_MAX_TOKENS,
158
+ check: (answer)=>checkAiMediaSvgAnswer(answer, input.aspectRatio, input.style)
159
+ };
160
+ const result = await runValidatedGeneration(AI_MEDIA_SVG_KIND, generation);
161
+ const spent = {
162
+ usage: result.usage,
163
+ model: result.model
164
+ };
165
+ if (result.status === 'ok') {
166
+ return 'declined' in result.value ? _extends({
167
+ kind: 'declined',
168
+ reason: result.value.declined
169
+ }, spent) : _extends({
170
+ kind: 'drawn',
171
+ svg: result.value.svg,
172
+ alt: result.value.alt
173
+ }, spent);
174
+ }
175
+ if (result.status === 'refused') {
176
+ return _extends({
177
+ kind: 'declined',
178
+ reason: 'The assistant would not draw this.'
179
+ }, spent);
180
+ }
181
+ return _extends({
182
+ kind: 'failed'
183
+ }, spent);
184
+ }
185
+
186
+ //# sourceMappingURL=ai-media-svg.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/server/ai-media-svg.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { aiDefaultModelFor } from '../providers/catalog'\nimport type { AiSystemBlock, AiTool, AiUsage } from '../providers/contract'\nimport type { AiImageAspectRatio, AiSvgStyle } from '../providers/image-contract'\nimport { resolveAiProvider } from '../providers/routing'\nimport { AI_SVG_MAX_BYTES, AI_SVG_VIEWBOX, checkAiSvgMarkup } from '../model/ai-svg'\nimport type { AiDoctrineViolation } from '../runtime/ai-doctrine-validators'\nimport {\n runValidatedGeneration,\n type AiCustomGenerationInput,\n type AiGenerationCheckResult,\n type AiValidatedGeneration,\n} from '../runtime/ai-doctrine'\n\n/**\n * Illustrations in Media (AGL-3602): an SVG drawn by the TEXT provider every\n * other AI door uses — the same registry, the same meter, the same data flow\n * the published subprocessor row for the text provider already describes —\n * so this mode needs no new vendor and runs wherever text AI does.\n *\n * One generation per picture, through `runValidatedGeneration`: the answer\n * arrives through a strict tool, `checkAiSvgMarkup` is its check, and an\n * answer with a problem is sent back once with what to fix. A second answer\n * with a problem is not stored and, being our failure, not charged.\n *\n * It runs on the provider's fast tier: an SVG is a few thousand tokens of\n * markup and the door answers inside one request, so the model that writes\n * them quickest is the one that fits.\n */\n\n/** The doctrine kind the generation runs under; it reads no site tree. */\nexport const AI_MEDIA_SVG_KIND = 'media-svg'\n\n/** The name of the tool the picture arrives through. */\nexport const AI_MEDIA_SVG_TOOL_NAME = 'submit_svg'\n\n/** The answer ceiling: room for a compact picture and a re-ask's worth of care. */\nexport const AI_MEDIA_SVG_MAX_TOKENS = 6_000\n\n/** What each kind of illustration is, in the words the model is given. */\nconst STYLE_BRIEF: Readonly<Record<AiSvgStyle, string>> = {\n illustration:\n 'A spot illustration or small scene: flat or lightly shaded vector shapes, clear silhouettes, no photographic detail.',\n icon: 'A single icon: bold, simple geometry centered with even padding, in ONE color, or two tones of the palette at most. Readable at 24 pixels.',\n pattern:\n 'A seamless, tileable background pattern: every shape that leaves one edge re-enters at the opposite edge, so tiles join without a seam. Low contrast, suitable behind text.',\n logo: \"A simple abstract logo MARK: a symbol made of a few shapes, with no lettering at all. Never a real company's logo, a trademark, a brand's symbol or anything imitating one.\",\n}\n\nconst INSTRUCTIONS = [\n 'You draw SVG pictures for a website owner. You receive what to draw, which kind of picture it is, its shape and the colors to use, and you answer through the submit_svg tool.',\n '',\n 'The SVG you write must:',\n '- be exactly one <svg> element with xmlns=\"http://www.w3.org/2000/svg\" and the viewBox you are given, and no width or height attributes;',\n '- use only shapes, paths, groups, gradients, clipPaths and masks drawn in the document itself: never <image>, <foreignObject>, <script>, <a>, animation elements, event attributes, or a href or url(...) pointing anywhere but #ids in the same SVG;',\n '- use no web fonts, @import or @font-face; prefer no text at all, and use only generic font families (sans-serif, serif) when text is essential;',\n `- stay compact: well under ${Math.round(AI_SVG_MAX_BYTES / 1024 / 4)} KB, with few paths and coordinates rounded to at most one decimal place;`,\n '- use the colors given, plus white, black and transparency, and no others.',\n '',\n 'Write alt text: one plain sentence describing what the picture shows, for someone who cannot see it.',\n '',\n \"Decline instead of drawing — set declined to one short sentence and leave svg and alt empty — when you are asked for a real company's or organization's logo, a trademark, a recognizable brand symbol or anything imitating one; for a real, named person; or for anything sexual, hateful, violent or otherwise unsafe. Otherwise set declined to an empty string.\",\n].join('\\n')\n\nexport const AI_MEDIA_SVG_INSTRUCTIONS: AiSystemBlock[] = [{ text: INSTRUCTIONS, cacheBreakpoint: true }]\n\nexport function aiMediaSvgTool(): AiTool {\n return {\n name: AI_MEDIA_SVG_TOOL_NAME,\n description: 'Submit the SVG picture and its alt text, or decline.',\n strict: true,\n inputSchema: {\n type: 'object',\n additionalProperties: false,\n required: ['svg', 'alt', 'declined'],\n properties: {\n svg: { type: 'string', description: 'The whole SVG document, starting with <svg and ending with </svg>.' },\n alt: { type: 'string', description: 'One plain sentence describing the picture.' },\n declined: {\n type: 'string',\n description: 'Empty, or one short sentence saying why this picture is not drawn.',\n },\n },\n },\n }\n}\n\n/** The question one picture is asked as. */\nexport function aiMediaSvgPrompt(input: {\n prompt: string\n style: AiSvgStyle\n aspectRatio: AiImageAspectRatio\n palette: readonly string[]\n variant: number\n count: number\n}): string {\n const colors = input.palette.length\n ? `Colors: ${input.palette.join(', ')}.`\n : 'Colors: a restrained palette of three to five colors of your choice.'\n const lines = [\n `Kind: ${input.style}. ${STYLE_BRIEF[input.style]}`,\n `Shape: ${input.aspectRatio}, viewBox=\"${AI_SVG_VIEWBOX[input.aspectRatio]}\".`,\n colors,\n ]\n if (input.count > 1) {\n lines.push(\n `This is version ${input.variant + 1} of ${input.count}: make it a distinct take on the same description.`,\n )\n }\n lines.push('', 'Draw:', input.prompt)\n return lines.join('\\n')\n}\n\n/** What one picture's answer holds once it is read. */\nexport type AiMediaSvgAnswer = { svg: string; alt: string } | { declined: string }\n\n/** The check one answer is held to: the SVG gate, or a decline. */\nexport function checkAiMediaSvgAnswer(\n answer: Record<string, unknown>,\n aspectRatio: AiImageAspectRatio,\n style: AiSvgStyle,\n): AiGenerationCheckResult<AiMediaSvgAnswer> {\n const declined = typeof answer['declined'] === 'string' ? answer['declined'].trim() : ''\n if (declined) return { value: { declined: declined.slice(0, 300) }, violations: [] }\n const result = checkAiSvgMarkup(answer['svg'], aspectRatio, style)\n const alt = typeof answer['alt'] === 'string' ? answer['alt'].replace(/\\s+/g, ' ').trim().slice(0, 300) : ''\n if (result.svg) return { value: { svg: result.svg, alt }, violations: [] }\n const violations: AiDoctrineViolation[] = result.problems.map((problem) => ({\n rule: null,\n code: `svg-${problem.code}`,\n message: 'The picture could not be drawn safely.',\n detail: problem.detail,\n }))\n return { value: { svg: '', alt }, violations, offending: { svg: '(see the problems listed)' } }\n}\n\n/** The model an illustration runs on: the text provider's fast tier. */\nexport function aiMediaSvgModel(): string | undefined {\n const provider = resolveAiProvider()\n return provider ? aiDefaultModelFor(provider.id, 'fast') : undefined\n}\n\n/** One picture's outcome. */\nexport type AiMediaSvgOutcome =\n | { kind: 'drawn'; svg: string; alt: string; usage: AiUsage; model: string }\n | { kind: 'declined'; reason: string; usage: AiUsage; model: string }\n /** The re-ask still failed the gate, or the model stopped: ours, never charged. */\n | { kind: 'failed'; usage: AiUsage; model: string }\n\n/** Draws one picture. A provider fault propagates for the door to answer. */\nexport async function generateAiMediaSvg(input: {\n model: string\n prompt: string\n style: AiSvgStyle\n aspectRatio: AiImageAspectRatio\n palette: readonly string[]\n variant: number\n count: number\n}): Promise<AiMediaSvgOutcome> {\n const generation: AiCustomGenerationInput<AiMediaSvgAnswer> = {\n model: input.model,\n instructions: AI_MEDIA_SVG_INSTRUCTIONS,\n inventory: undefined,\n messages: [{ role: 'user', content: aiMediaSvgPrompt(input) }],\n tool: aiMediaSvgTool(),\n maxTokens: AI_MEDIA_SVG_MAX_TOKENS,\n check: (answer) => checkAiMediaSvgAnswer(answer, input.aspectRatio, input.style),\n }\n const result = (await runValidatedGeneration(\n AI_MEDIA_SVG_KIND,\n generation,\n )) as AiValidatedGeneration<AiMediaSvgAnswer>\n const spent = { usage: result.usage, model: result.model }\n if (result.status === 'ok') {\n return 'declined' in result.value\n ? { kind: 'declined', reason: result.value.declined, ...spent }\n : { kind: 'drawn', svg: result.value.svg, alt: result.value.alt, ...spent }\n }\n if (result.status === 'refused') {\n return { kind: 'declined', reason: 'The assistant would not draw this.', ...spent }\n }\n return { kind: 'failed', ...spent }\n}\n"],"names":["aiDefaultModelFor","resolveAiProvider","AI_SVG_MAX_BYTES","AI_SVG_VIEWBOX","checkAiSvgMarkup","runValidatedGeneration","AI_MEDIA_SVG_KIND","AI_MEDIA_SVG_TOOL_NAME","AI_MEDIA_SVG_MAX_TOKENS","STYLE_BRIEF","illustration","icon","pattern","logo","INSTRUCTIONS","Math","round","join","AI_MEDIA_SVG_INSTRUCTIONS","text","cacheBreakpoint","aiMediaSvgTool","name","description","strict","inputSchema","type","additionalProperties","required","properties","svg","alt","declined","aiMediaSvgPrompt","input","colors","palette","length","lines","style","aspectRatio","count","push","variant","prompt","checkAiMediaSvgAnswer","answer","trim","value","slice","violations","result","replace","problems","map","problem","rule","code","message","detail","offending","aiMediaSvgModel","provider","id","undefined","generateAiMediaSvg","generation","model","instructions","inventory","messages","role","content","tool","maxTokens","check","spent","usage","status","kind","reason"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,iBAAiB,QAAQ,0BAAsB;AAGxD,SAASC,iBAAiB,QAAQ,0BAAsB;AACxD,SAASC,gBAAgB,EAAEC,cAAc,EAAEC,gBAAgB,QAAQ,qBAAiB;AAEpF,SACEC,sBAAsB,QAIjB,4BAAwB;AAE/B;;;;;;;;;;;;;;CAcC,GAED,wEAAwE,GACxE,OAAO,MAAMC,oBAAoB,YAAW;AAE5C,sDAAsD,GACtD,OAAO,MAAMC,yBAAyB,aAAY;AAElD,iFAAiF,GACjF,OAAO,MAAMC,0BAA0B,KAAK;AAE5C,wEAAwE,GACxE,MAAMC,cAAoD;IACxDC,cACE;IACFC,MAAM;IACNC,SACE;IACFC,MAAM;AACR;AAEA,MAAMC,eAAe;IACnB;IACA;IACA;IACA;IACA;IACA;IACA,CAAC,2BAA2B,EAAEC,KAAKC,KAAK,CAACd,mBAAmB,OAAO,GAAG,yEAAyE,CAAC;IAChJ;IACA;IACA;IACA;IACA;CACD,CAACe,IAAI,CAAC;AAEP,OAAO,MAAMC,4BAA6C;IAAC;QAAEC,MAAML;QAAcM,iBAAiB;IAAK;CAAE,CAAA;AAEzG,OAAO,SAASC;IACd,OAAO;QACLC,MAAMf;QACNgB,aAAa;QACbC,QAAQ;QACRC,aAAa;YACXC,MAAM;YACNC,sBAAsB;YACtBC,UAAU;gBAAC;gBAAO;gBAAO;aAAW;YACpCC,YAAY;gBACVC,KAAK;oBAAEJ,MAAM;oBAAUH,aAAa;gBAAqE;gBACzGQ,KAAK;oBAAEL,MAAM;oBAAUH,aAAa;gBAA6C;gBACjFS,UAAU;oBACRN,MAAM;oBACNH,aAAa;gBACf;YACF;QACF;IACF;AACF;AAEA,0CAA0C,GAC1C,OAAO,SAASU,iBAAiBC,KAOhC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AAyCJ;IAC9E;IACA,OAAO;QAAEG,MAAM;OAAaH;AAC9B"}
@@ -0,0 +1,54 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
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
+ import { type AssistBuildProposal } from '../model/assist-build';
18
+ import type { AiTool } from '../providers/contract';
19
+ import { aiBuildOps } from '../jobs/ai-build-capabilities';
20
+ /** The strict tool the model proposes a build through. */
21
+ export declare function assistBuildTool(): AiTool;
22
+ /**
23
+ * The build protocol — the same for every site, so it sits inside the cached
24
+ * prefix. What a build can make on THIS site is per site and rides
25
+ * `assistBuildIntentsBlock`, after every breakpoint.
26
+ */
27
+ export declare function assistBuildBlock(): string;
28
+ /** What a build can make on this site, in each owner's own words. Per site: volatile. */
29
+ export declare function assistBuildIntentsBlock(intents: readonly string[]): string;
30
+ /**
31
+ * The tool call held to what a build job accepts, or `null` when it is
32
+ * unusable. The site is the request's own, never the model's; the brief is
33
+ * clamped to the job door's limit, with a line naming the console page it
34
+ * was asked from so the plan step can read "this page" against it.
35
+ */
36
+ export declare function resolveAssistBuild(input: Record<string, unknown> | null, scope: {
37
+ hostId: string;
38
+ screen: string | null;
39
+ }): AssistBuildProposal | null;
40
+ export interface AssistBuildIntentsDeps {
41
+ ops?: typeof aiBuildOps;
42
+ hasBuildRunner?: () => boolean;
43
+ }
44
+ /**
45
+ * What a build may make on this site, or `null` where none can be built: a
46
+ * deployment that has not loaded the build kind, or a site where no
47
+ * operation passes its owner's gates. The same operations the build's plan
48
+ * step offers, so the chat never offers what the plan cannot make.
49
+ */
50
+ export declare function assistBuildIntents(firestore: FirebaseFirestore.Firestore, input: {
51
+ orgId: string;
52
+ hostId: string;
53
+ org: Record<string, unknown>;
54
+ }, deps?: AssistBuildIntentsDeps): Promise<string[] | null>;
@@ -0,0 +1,121 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
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
+ */ import { ASSIST_BUILD_ACTION_ID, ASSIST_BUILD_SUMMARY_MAX_CHARS, ASSIST_BUILD_TOOL_NAME } from "../model/assist-build.js";
17
+ import { aiBuildIntents, aiBuildOps } from "../jobs/ai-build-capabilities.js";
18
+ import { aiBuildFreeTaste } from "../jobs/ai-job-build-step.js";
19
+ import { AI_JOB_BRIEF_MAX_CHARS } from "../jobs/ai-job-text-step.js";
20
+ import { aiJobStepRunnerFor } from "../jobs/ai-jobs.js";
21
+ /**
22
+ * The chat's build rung (AGL-3616): on a site, a request that names things
23
+ * to make — "a few new pages, a booking form and a contact form, then an
24
+ * about page" — is proposed as ONE build through a strict tool. The tool
25
+ * carries the request, not a plan: planning is the build job's own plan
26
+ * step, against the site's real inventory, with its re-ask and its limits.
27
+ * The panel starts that job and shows its plan card with one price; nothing
28
+ * is built until the person confirms it, and what is built is a draft unless
29
+ * they asked to publish and tick the card's box.
30
+ */ const STRING = {
31
+ type: 'string'
32
+ };
33
+ /** The strict tool the model proposes a build through. */ export function assistBuildTool() {
34
+ return {
35
+ name: ASSIST_BUILD_TOOL_NAME,
36
+ description: 'Propose building what the user asked for on this site: pages, a header ' + 'and footer, forms and the other things listed. The user sees a plan with ' + 'its price and confirms it before anything is made. Call at most once per ' + 'message, with the whole request.',
37
+ inputSchema: {
38
+ type: 'object',
39
+ properties: {
40
+ summary: STRING,
41
+ brief: STRING,
42
+ publish: {
43
+ type: 'boolean'
44
+ }
45
+ },
46
+ required: [
47
+ 'summary',
48
+ 'brief',
49
+ 'publish'
50
+ ],
51
+ additionalProperties: false
52
+ },
53
+ strict: true
54
+ };
55
+ }
56
+ /**
57
+ * The build protocol — the same for every site, so it sits inside the cached
58
+ * prefix. What a build can make on THIS site is per site and rides
59
+ * `assistBuildIntentsBlock`, after every breakpoint.
60
+ */ export function assistBuildBlock() {
61
+ return [
62
+ 'Building on this site:',
63
+ `- When the user asks you to make or set up things on their site — pages, a header and footer, forms, or anything listed in the "A build here can make" block — write one or two sentences saying what you will plan, then call the ${ASSIST_BUILD_TOOL_NAME} tool once with the whole request. Write no JSON in your message.`,
64
+ '- brief: everything they asked for, in their words, with each page, form and other part named and what each is for. Include what the conversation already settled. Do not invent parts they did not ask for beyond what their request plainly needs (a page that shows a form needs that form).',
65
+ '- publish: true only when they asked for the new pages to go live or be published; otherwise false. New work is an unpublished draft by default.',
66
+ '- summary: one short sentence, such as "Plan three pages, a contact form and a booking service".',
67
+ '- Nothing is built when you call the tool: the user is shown a plan with its price and confirms it. Never say anything is made, and never quote a price.',
68
+ '- Only offer what the "A build here can make" block lists. If they ask for something it does not list, say plainly it cannot be built here from the chat and build the rest.',
69
+ '- A question, or a change to the canvas the user has open, is not a build: answer it, or use the canvas edit tool where it is offered.'
70
+ ].join('\n');
71
+ }
72
+ /** What a build can make on this site, in each owner's own words. Per site: volatile. */ export function assistBuildIntentsBlock(intents) {
73
+ return [
74
+ 'A build here can make:',
75
+ ...intents.map((intent)=>`- ${intent}`)
76
+ ].join('\n');
77
+ }
78
+ /**
79
+ * The tool call held to what a build job accepts, or `null` when it is
80
+ * unusable. The site is the request's own, never the model's; the brief is
81
+ * clamped to the job door's limit, with a line naming the console page it
82
+ * was asked from so the plan step can read "this page" against it.
83
+ */ export function resolveAssistBuild(input, scope) {
84
+ if (!input) return null;
85
+ const asked = typeof input['brief'] === 'string' ? input['brief'].trim() : '';
86
+ if (!asked) return null;
87
+ const where = scope.screen ? `\nAsked from the console page: ${scope.screen}` : '';
88
+ const brief = `${asked.slice(0, AI_JOB_BRIEF_MAX_CHARS - where.length)}${where}`.trim();
89
+ const summary = typeof input['summary'] === 'string' && input['summary'].trim() ? input['summary'].trim().slice(0, ASSIST_BUILD_SUMMARY_MAX_CHARS) : 'Plan what you asked for';
90
+ return {
91
+ id: ASSIST_BUILD_ACTION_ID,
92
+ hostId: scope.hostId,
93
+ brief,
94
+ publish: input['publish'] === true,
95
+ summary
96
+ };
97
+ }
98
+ /**
99
+ * What a build may make on this site, or `null` where none can be built: a
100
+ * deployment that has not loaded the build kind, or a site where no
101
+ * operation passes its owner's gates. The same operations the build's plan
102
+ * step offers, so the chat never offers what the plan cannot make.
103
+ */ export async function assistBuildIntents(firestore, input, deps = {}) {
104
+ var _deps_hasBuildRunner, _data, _deps_ops;
105
+ const hasBuildRunner = (_deps_hasBuildRunner = deps.hasBuildRunner) != null ? _deps_hasBuildRunner : ()=>aiJobStepRunnerFor('build') !== null;
106
+ if (!hasBuildRunner()) return null;
107
+ const host = (_data = (await firestore.collection('hosts').doc(input.hostId).get()).data()) != null ? _data : null;
108
+ if (!host) return null;
109
+ const org = input.org;
110
+ const ops = await ((_deps_ops = deps.ops) != null ? _deps_ops : aiBuildOps)({
111
+ orgId: input.orgId,
112
+ hostId: input.hostId,
113
+ org,
114
+ host,
115
+ freeTaste: aiBuildFreeTaste(org)
116
+ });
117
+ const intents = aiBuildIntents(ops);
118
+ return intents.length ? intents : null;
119
+ }
120
+
121
+ //# sourceMappingURL=assist-build.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/server/assist-build.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { AglynOrgBilling } from '@aglyn/aglyn/foundation/definitions/org-billing.types'\nimport {\n ASSIST_BUILD_ACTION_ID,\n ASSIST_BUILD_SUMMARY_MAX_CHARS,\n ASSIST_BUILD_TOOL_NAME,\n type AssistBuildProposal,\n} from '../model/assist-build'\nimport type { AiTool } from '../providers/contract'\nimport { aiBuildIntents, aiBuildOps } from '../jobs/ai-build-capabilities'\nimport { aiBuildFreeTaste } from '../jobs/ai-job-build-step'\nimport { AI_JOB_BRIEF_MAX_CHARS } from '../jobs/ai-job-text-step'\nimport { aiJobStepRunnerFor } from '../jobs/ai-jobs'\n\n/**\n * The chat's build rung (AGL-3616): on a site, a request that names things\n * to make — \"a few new pages, a booking form and a contact form, then an\n * about page\" — is proposed as ONE build through a strict tool. The tool\n * carries the request, not a plan: planning is the build job's own plan\n * step, against the site's real inventory, with its re-ask and its limits.\n * The panel starts that job and shows its plan card with one price; nothing\n * is built until the person confirms it, and what is built is a draft unless\n * they asked to publish and tick the card's box.\n */\n\nconst STRING = { type: 'string' } as const\n\n/** The strict tool the model proposes a build through. */\nexport function assistBuildTool(): AiTool {\n return {\n name: ASSIST_BUILD_TOOL_NAME,\n description:\n 'Propose building what the user asked for on this site: pages, a header ' +\n 'and footer, forms and the other things listed. The user sees a plan with ' +\n 'its price and confirms it before anything is made. Call at most once per ' +\n 'message, with the whole request.',\n inputSchema: {\n type: 'object',\n properties: {\n summary: STRING,\n brief: STRING,\n publish: { type: 'boolean' },\n },\n required: ['summary', 'brief', 'publish'],\n additionalProperties: false,\n },\n strict: true,\n }\n}\n\n/**\n * The build protocol — the same for every site, so it sits inside the cached\n * prefix. What a build can make on THIS site is per site and rides\n * `assistBuildIntentsBlock`, after every breakpoint.\n */\nexport function assistBuildBlock(): string {\n return [\n 'Building on this site:',\n `- When the user asks you to make or set up things on their site — pages, a header and footer, forms, or anything listed in the \"A build here can make\" block — write one or two sentences saying what you will plan, then call the ${ASSIST_BUILD_TOOL_NAME} tool once with the whole request. Write no JSON in your message.`,\n '- brief: everything they asked for, in their words, with each page, form and other part named and what each is for. Include what the conversation already settled. Do not invent parts they did not ask for beyond what their request plainly needs (a page that shows a form needs that form).',\n '- publish: true only when they asked for the new pages to go live or be published; otherwise false. New work is an unpublished draft by default.',\n '- summary: one short sentence, such as \"Plan three pages, a contact form and a booking service\".',\n '- Nothing is built when you call the tool: the user is shown a plan with its price and confirms it. Never say anything is made, and never quote a price.',\n '- Only offer what the \"A build here can make\" block lists. If they ask for something it does not list, say plainly it cannot be built here from the chat and build the rest.',\n '- A question, or a change to the canvas the user has open, is not a build: answer it, or use the canvas edit tool where it is offered.',\n ].join('\\n')\n}\n\n/** What a build can make on this site, in each owner's own words. Per site: volatile. */\nexport function assistBuildIntentsBlock(intents: readonly string[]): string {\n return ['A build here can make:', ...intents.map((intent) => `- ${intent}`)].join('\\n')\n}\n\n/**\n * The tool call held to what a build job accepts, or `null` when it is\n * unusable. The site is the request's own, never the model's; the brief is\n * clamped to the job door's limit, with a line naming the console page it\n * was asked from so the plan step can read \"this page\" against it.\n */\nexport function resolveAssistBuild(\n input: Record<string, unknown> | null,\n scope: { hostId: string; screen: string | null },\n): AssistBuildProposal | null {\n if (!input) return null\n const asked = typeof input['brief'] === 'string' ? input['brief'].trim() : ''\n if (!asked) return null\n const where = scope.screen ? `\\nAsked from the console page: ${scope.screen}` : ''\n const brief = `${asked.slice(0, AI_JOB_BRIEF_MAX_CHARS - where.length)}${where}`.trim()\n const summary =\n typeof input['summary'] === 'string' && input['summary'].trim()\n ? input['summary'].trim().slice(0, ASSIST_BUILD_SUMMARY_MAX_CHARS)\n : 'Plan what you asked for'\n return {\n id: ASSIST_BUILD_ACTION_ID,\n hostId: scope.hostId,\n brief,\n publish: input['publish'] === true,\n summary,\n }\n}\n\nexport interface AssistBuildIntentsDeps {\n ops?: typeof aiBuildOps\n hasBuildRunner?: () => boolean\n}\n\n/**\n * What a build may make on this site, or `null` where none can be built: a\n * deployment that has not loaded the build kind, or a site where no\n * operation passes its owner's gates. The same operations the build's plan\n * step offers, so the chat never offers what the plan cannot make.\n */\nexport async function assistBuildIntents(\n firestore: FirebaseFirestore.Firestore,\n input: { orgId: string; hostId: string; org: Record<string, unknown> },\n deps: AssistBuildIntentsDeps = {},\n): Promise<string[] | null> {\n const hasBuildRunner = deps.hasBuildRunner ?? (() => aiJobStepRunnerFor('build') !== null)\n if (!hasBuildRunner()) return null\n const host = ((await firestore.collection('hosts').doc(input.hostId).get()).data() ?? null) as Record<\n string,\n unknown\n > | null\n if (!host) return null\n const org = input.org as Partial<AglynOrgBilling>\n const ops = await (deps.ops ?? aiBuildOps)({\n orgId: input.orgId,\n hostId: input.hostId,\n org,\n host,\n freeTaste: aiBuildFreeTaste(org),\n })\n const intents = aiBuildIntents(ops)\n return intents.length ? intents : null\n}\n"],"names":["ASSIST_BUILD_ACTION_ID","ASSIST_BUILD_SUMMARY_MAX_CHARS","ASSIST_BUILD_TOOL_NAME","aiBuildIntents","aiBuildOps","aiBuildFreeTaste","AI_JOB_BRIEF_MAX_CHARS","aiJobStepRunnerFor","STRING","type","assistBuildTool","name","description","inputSchema","properties","summary","brief","publish","required","additionalProperties","strict","assistBuildBlock","join","assistBuildIntentsBlock","intents","map","intent","resolveAssistBuild","input","scope","asked","trim","where","screen","slice","length","id","hostId","assistBuildIntents","firestore","deps","hasBuildRunner","host","collection","doc","get","data","org","ops","orgId","freeTaste"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAGD,SACEA,sBAAsB,EACtBC,8BAA8B,EAC9BC,sBAAsB,QAEjB,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