@aglyn/plugins-ai 1.0.0-beta.231 → 1.0.0-beta.232

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 (220) hide show
  1. package/package.json +17 -17
  2. package/src/lib/activity/ai-activity-actions.js +8 -4
  3. package/src/lib/activity/ai-activity-actions.js.map +1 -1
  4. package/src/lib/components/ai-job-follow.component.js +1 -0
  5. package/src/lib/components/ai-job-follow.component.js.map +1 -1
  6. package/src/lib/components/ai-job-links.js +13 -0
  7. package/src/lib/components/ai-job-links.js.map +1 -1
  8. package/src/lib/components/ai-jobs-list-page.component.js +1 -0
  9. package/src/lib/components/ai-jobs-list-page.component.js.map +1 -1
  10. package/src/lib/components/ai-media-create.component.d.ts +20 -7
  11. package/src/lib/components/ai-media-create.component.js +107 -55
  12. package/src/lib/components/ai-media-create.component.js.map +1 -1
  13. package/src/lib/components/ai-seo-fields-card.component.js +1 -0
  14. package/src/lib/components/ai-seo-fields-card.component.js.map +1 -1
  15. package/src/lib/components/ai-site-memory-card.component.d.ts +32 -0
  16. package/src/lib/components/ai-site-memory-card.component.js +187 -0
  17. package/src/lib/components/ai-site-memory-card.component.js.map +1 -0
  18. package/src/lib/components/ai-site-start-card.component.js +80 -77
  19. package/src/lib/components/ai-site-start-card.component.js.map +1 -1
  20. package/src/lib/components/ai-theme-proposal-card.component.js +4 -0
  21. package/src/lib/components/ai-theme-proposal-card.component.js.map +1 -1
  22. package/src/lib/components/ai-usage-strip.component.js +1 -0
  23. package/src/lib/components/ai-usage-strip.component.js.map +1 -1
  24. package/src/lib/components/assist-panel.component.d.ts +10 -0
  25. package/src/lib/components/assist-panel.component.js +119 -9
  26. package/src/lib/components/assist-panel.component.js.map +1 -1
  27. package/src/lib/components/assist-signals-page.component.js +2 -0
  28. package/src/lib/components/assist-signals-page.component.js.map +1 -1
  29. package/src/lib/components/billing-ai-allotments.component.js +3 -0
  30. package/src/lib/components/billing-ai-allotments.component.js.map +1 -1
  31. package/src/lib/components/billing-ai-top-users.component.js +1 -0
  32. package/src/lib/components/billing-ai-top-users.component.js.map +1 -1
  33. package/src/lib/components/billing-assist-overage-card.component.js +2 -0
  34. package/src/lib/components/billing-assist-overage-card.component.js.map +1 -1
  35. package/src/lib/components/member-ai-usage-card.component.js +10 -0
  36. package/src/lib/components/member-ai-usage-card.component.js.map +1 -1
  37. package/src/lib/components/staff-org-ai-card.component.js +1 -0
  38. package/src/lib/components/staff-org-ai-card.component.js.map +1 -1
  39. package/src/lib/components/staff-org-ai-conversations.component.d.ts +23 -0
  40. package/src/lib/components/staff-org-ai-conversations.component.js +346 -0
  41. package/src/lib/components/staff-org-ai-conversations.component.js.map +1 -0
  42. package/src/lib/jobs/ai-build-capabilities.d.ts +13 -1
  43. package/src/lib/jobs/ai-build-capabilities.js +101 -7
  44. package/src/lib/jobs/ai-build-capabilities.js.map +1 -1
  45. package/src/lib/jobs/ai-business-profile-prefill.d.ts +29 -0
  46. package/src/lib/jobs/ai-business-profile-prefill.js +85 -0
  47. package/src/lib/jobs/ai-business-profile-prefill.js.map +1 -0
  48. package/src/lib/jobs/ai-job-build-step.js +3 -1
  49. package/src/lib/jobs/ai-job-build-step.js.map +1 -1
  50. package/src/lib/jobs/ai-job-edit-step.d.ts +225 -0
  51. package/src/lib/jobs/ai-job-edit-step.js +631 -0
  52. package/src/lib/jobs/ai-job-edit-step.js.map +1 -0
  53. package/src/lib/jobs/ai-job-insight-step.js +21 -4
  54. package/src/lib/jobs/ai-job-insight-step.js.map +1 -1
  55. package/src/lib/jobs/ai-job-layout-language.d.ts +8 -3
  56. package/src/lib/jobs/ai-job-layout-language.js +8 -2
  57. package/src/lib/jobs/ai-job-layout-language.js.map +1 -1
  58. package/src/lib/jobs/ai-job-layout-step.js +7 -6
  59. package/src/lib/jobs/ai-job-layout-step.js.map +1 -1
  60. package/src/lib/jobs/ai-job-logic-step.d.ts +20 -0
  61. package/src/lib/jobs/ai-job-logic-step.js +87 -6
  62. package/src/lib/jobs/ai-job-logic-step.js.map +1 -1
  63. package/src/lib/jobs/ai-job-page-language.d.ts +52 -7
  64. package/src/lib/jobs/ai-job-page-language.js +72 -9
  65. package/src/lib/jobs/ai-job-page-language.js.map +1 -1
  66. package/src/lib/jobs/ai-job-page-step.js +12 -2
  67. package/src/lib/jobs/ai-job-page-step.js.map +1 -1
  68. package/src/lib/jobs/ai-job-plan-step.d.ts +19 -5
  69. package/src/lib/jobs/ai-job-plan-step.js +54 -20
  70. package/src/lib/jobs/ai-job-plan-step.js.map +1 -1
  71. package/src/lib/jobs/ai-job-site-content.d.ts +163 -0
  72. package/src/lib/jobs/ai-job-site-content.js +443 -0
  73. package/src/lib/jobs/ai-job-site-content.js.map +1 -0
  74. package/src/lib/jobs/ai-job-site-look.d.ts +112 -0
  75. package/src/lib/jobs/ai-job-site-look.js +322 -0
  76. package/src/lib/jobs/ai-job-site-look.js.map +1 -0
  77. package/src/lib/jobs/ai-job-site-step.d.ts +26 -5
  78. package/src/lib/jobs/ai-job-site-step.js +163 -24
  79. package/src/lib/jobs/ai-job-site-step.js.map +1 -1
  80. package/src/lib/jobs/ai-jobs-notify.d.ts +6 -1
  81. package/src/lib/jobs/ai-jobs-notify.js +15 -3
  82. package/src/lib/jobs/ai-jobs-notify.js.map +1 -1
  83. package/src/lib/layout-language/ai-layout-compiler.d.ts +9 -0
  84. package/src/lib/layout-language/ai-layout-compiler.js +120 -33
  85. package/src/lib/layout-language/ai-layout-compiler.js.map +1 -1
  86. package/src/lib/layout-language/ai-layout-frame.js +5 -4
  87. package/src/lib/layout-language/ai-layout-frame.js.map +1 -1
  88. package/src/lib/layout-language/ai-layout-language.d.ts +12 -5
  89. package/src/lib/layout-language/ai-layout-language.js +92 -9
  90. package/src/lib/layout-language/ai-layout-language.js.map +1 -1
  91. package/src/lib/layout-language/ai-layout-pictures.d.ts +144 -0
  92. package/src/lib/layout-language/ai-layout-pictures.js +214 -0
  93. package/src/lib/layout-language/ai-layout-pictures.js.map +1 -0
  94. package/src/lib/layout-language/ai-layout-store.d.ts +2 -0
  95. package/src/lib/layout-language/ai-layout-store.js +7 -1
  96. package/src/lib/layout-language/ai-layout-store.js.map +1 -1
  97. package/src/lib/model/ai-build-progress.js +4 -1
  98. package/src/lib/model/ai-build-progress.js.map +1 -1
  99. package/src/lib/model/ai-edit-job.d.ts +109 -0
  100. package/src/lib/model/ai-edit-job.js +157 -0
  101. package/src/lib/model/ai-edit-job.js.map +1 -0
  102. package/src/lib/model/ai-job-activity.js +1 -0
  103. package/src/lib/model/ai-job-activity.js.map +1 -1
  104. package/src/lib/model/ai-jobs.types.d.ts +3 -1
  105. package/src/lib/model/ai-jobs.types.js.map +1 -1
  106. package/src/lib/model/ai-logic-job.d.ts +18 -1
  107. package/src/lib/model/ai-logic-job.js +24 -3
  108. package/src/lib/model/ai-logic-job.js.map +1 -1
  109. package/src/lib/model/ai-media-credits.d.ts +8 -4
  110. package/src/lib/model/ai-media-credits.js +11 -4
  111. package/src/lib/model/ai-media-credits.js.map +1 -1
  112. package/src/lib/model/ai-media-kinds.d.ts +68 -0
  113. package/src/lib/model/ai-media-kinds.js +98 -0
  114. package/src/lib/model/ai-media-kinds.js.map +1 -0
  115. package/src/lib/model/ai-site-build-progress.d.ts +4 -0
  116. package/src/lib/model/ai-site-build-progress.js +28 -11
  117. package/src/lib/model/ai-site-build-progress.js.map +1 -1
  118. package/src/lib/model/ai-site-context.d.ts +111 -0
  119. package/src/lib/model/ai-site-context.js +222 -0
  120. package/src/lib/model/ai-site-context.js.map +1 -0
  121. package/src/lib/model/ai-site-job.d.ts +10 -2
  122. package/src/lib/model/ai-site-job.js +12 -5
  123. package/src/lib/model/ai-site-job.js.map +1 -1
  124. package/src/lib/model/ai-site-kinds.d.ts +164 -0
  125. package/src/lib/model/ai-site-kinds.js +1942 -0
  126. package/src/lib/model/ai-site-kinds.js.map +1 -0
  127. package/src/lib/model/ai-site-look.d.ts +150 -0
  128. package/src/lib/model/ai-site-look.js +1236 -0
  129. package/src/lib/model/ai-site-look.js.map +1 -0
  130. package/src/lib/model/ai-site-memory.d.ts +80 -0
  131. package/src/lib/model/ai-site-memory.js +171 -0
  132. package/src/lib/model/ai-site-memory.js.map +1 -0
  133. package/src/lib/model/ai-site-start.d.ts +10 -1
  134. package/src/lib/model/ai-site-start.js +16 -2
  135. package/src/lib/model/ai-site-start.js.map +1 -1
  136. package/src/lib/model/assist-follow-up.d.ts +92 -0
  137. package/src/lib/model/assist-follow-up.js +128 -0
  138. package/src/lib/model/assist-follow-up.js.map +1 -0
  139. package/src/lib/plugin-config.js +2 -0
  140. package/src/lib/plugin-config.js.map +1 -1
  141. package/src/lib/plugin.js +20 -1
  142. package/src/lib/plugin.js.map +1 -1
  143. package/src/lib/providers/anthropic.d.ts +9 -1
  144. package/src/lib/providers/anthropic.js +143 -9
  145. package/src/lib/providers/anthropic.js.map +1 -1
  146. package/src/lib/providers/catalog.d.ts +37 -7
  147. package/src/lib/providers/catalog.js +103 -11
  148. package/src/lib/providers/catalog.js.map +1 -1
  149. package/src/lib/providers/contract.d.ts +29 -0
  150. package/src/lib/providers/contract.js.map +1 -1
  151. package/src/lib/providers/image-contract.d.ts +22 -1
  152. package/src/lib/providers/image-contract.js +40 -1
  153. package/src/lib/providers/image-contract.js.map +1 -1
  154. package/src/lib/providers/image-endpoints.d.ts +24 -0
  155. package/src/lib/providers/image-endpoints.js +28 -0
  156. package/src/lib/providers/image-endpoints.js.map +1 -0
  157. package/src/lib/providers/model-choice.js +23 -2
  158. package/src/lib/providers/model-choice.js.map +1 -1
  159. package/src/lib/providers/routing.js +18 -0
  160. package/src/lib/providers/routing.js.map +1 -1
  161. package/src/lib/providers/vertex-image-endpoint.d.ts +48 -0
  162. package/src/lib/providers/vertex-image-endpoint.js +80 -0
  163. package/src/lib/providers/vertex-image-endpoint.js.map +1 -0
  164. package/src/lib/providers/vertex-image.d.ts +13 -27
  165. package/src/lib/providers/vertex-image.js +15 -42
  166. package/src/lib/providers/vertex-image.js.map +1 -1
  167. package/src/lib/runtime/ai-blog-post-generation.d.ts +62 -0
  168. package/src/lib/runtime/ai-blog-post-generation.js +89 -0
  169. package/src/lib/runtime/ai-blog-post-generation.js.map +1 -0
  170. package/src/lib/runtime/ai-dev-env.d.ts +53 -0
  171. package/src/lib/runtime/ai-dev-env.js +72 -0
  172. package/src/lib/runtime/ai-dev-env.js.map +1 -0
  173. package/src/lib/runtime/ai-dev-replay.d.ts +116 -0
  174. package/src/lib/runtime/ai-dev-replay.js +313 -0
  175. package/src/lib/runtime/ai-dev-replay.js.map +1 -0
  176. package/src/lib/runtime/ai-doctrine.js +5 -1
  177. package/src/lib/runtime/ai-doctrine.js.map +1 -1
  178. package/src/lib/runtime/ai-eval-live.js +4 -0
  179. package/src/lib/runtime/ai-eval-live.js.map +1 -1
  180. package/src/lib/runtime/ai-eval.d.ts +13 -1
  181. package/src/lib/runtime/ai-eval.js +84 -1
  182. package/src/lib/runtime/ai-eval.js.map +1 -1
  183. package/src/lib/runtime/ai-live-batch.d.ts +45 -0
  184. package/src/lib/runtime/ai-live-batch.js +89 -0
  185. package/src/lib/runtime/ai-live-batch.js.map +1 -0
  186. package/src/lib/runtime/ai-runtime.js +46 -2
  187. package/src/lib/runtime/ai-runtime.js.map +1 -1
  188. package/src/lib/runtime/site-context.d.ts +58 -0
  189. package/src/lib/runtime/site-context.js +127 -0
  190. package/src/lib/runtime/site-context.js.map +1 -0
  191. package/src/lib/server/ai-admin-conversations.d.ts +22 -0
  192. package/src/lib/server/ai-admin-conversations.js +197 -0
  193. package/src/lib/server/ai-admin-conversations.js.map +1 -0
  194. package/src/lib/server/ai-media-image.d.ts +5 -5
  195. package/src/lib/server/ai-media-image.js +25 -11
  196. package/src/lib/server/ai-media-image.js.map +1 -1
  197. package/src/lib/server/ai-media-raster-prompt.d.ts +34 -0
  198. package/src/lib/server/ai-media-raster-prompt.js +53 -0
  199. package/src/lib/server/ai-media-raster-prompt.js.map +1 -0
  200. package/src/lib/server/assist-chat.d.ts +11 -0
  201. package/src/lib/server/assist-chat.js +57 -18
  202. package/src/lib/server/assist-chat.js.map +1 -1
  203. package/src/lib/server/assist-edit-applied.js +16 -3
  204. package/src/lib/server/assist-edit-applied.js.map +1 -1
  205. package/src/lib/server/assist-view-context.d.ts +19 -1
  206. package/src/lib/server/assist-view-context.js +38 -1
  207. package/src/lib/server/assist-view-context.js.map +1 -1
  208. package/src/lib/server.js +10 -0
  209. package/src/lib/server.js.map +1 -1
  210. package/src/lib/subprocessors.js +17 -1
  211. package/src/lib/subprocessors.js.map +1 -1
  212. package/src/lib/tools/ai-blog-post-tool.d.ts +60 -0
  213. package/src/lib/tools/ai-blog-post-tool.js +175 -0
  214. package/src/lib/tools/ai-blog-post-tool.js.map +1 -0
  215. package/src/lib/usage/assist-usage.d.ts +3 -0
  216. package/src/lib/usage/assist-usage.js +4 -2
  217. package/src/lib/usage/assist-usage.js.map +1 -1
  218. package/src/lib/usage/staff-org-ai-conversations.d.ts +103 -0
  219. package/src/lib/usage/staff-org-ai-conversations.js +152 -0
  220. package/src/lib/usage/staff-org-ai-conversations.js.map +1 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/providers/catalog.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 { PluginSubprocessorDeclaration } from '@aglyn/aglyn/plugin-manager/plugin-subprocessors'\nimport type { AiModelDescriptor, AiUsage } from './contract'\n\n/**\n * The model catalog (AGL-2939): every model id the plugin will route to,\n * with its provider, its display name, its capabilities and its list rates.\n * The ONE place a model id is written outside a provider adapter — the\n * routing table maps a step kind to an id through here, the meter prices\n * usage by id through here, and a settings form offers ids from here.\n *\n * ## Two rates, because one figure was answering two questions\n *\n * Every row carries a PROVIDER rate and a BILLED rate (AGL-3015):\n *\n * - `providerRates` is what the vendor charges us. It is money leaving the\n * company, so cost accounting, the margin surfaces and every staff spend\n * meter price usage through this one and no other.\n * - `billedRates` is what a customer's credits are charged at. The credit\n * meter, the band, the overage ladder and the model selector price usage\n * through this one, because it is the figure a customer's balance moves by.\n *\n * They are equal on nearly every row, and a helper writes the pair from one\n * figure so an unmarked row cannot drift apart by a typo. A row may be\n * billed ABOVE its provider rate deliberately — the markup is carried in the\n * rate rather than in the credit conversion, which keeps a credit a fixed\n * quantity of billed spend on every model and leaves the band, the ladder\n * and the invoice on the one arithmetic they were sized with. A row billed\n * BELOW its provider rate would sell tokens at a loss, and\n * `billed-rate-is-not-provider-cost.spec.ts` refuses one.\n *\n * Both are keyed by model rather than fixed at one model's rates because the\n * default is an env override: a one-line incident swap to a dearer model\n * would otherwise keep reporting the cheaper money, and per-org cost would\n * read as roughly right — the failure mode this whole meter exists to\n * prevent. An unknown id falls back to the most EXPENSIVE known tier on\n * purpose, on both rates: an estimate that errs low is worse than one that\n * errs high, whether the figure is our bill or the customer's.\n */\n\nexport interface AiTokenRates {\n inputPerToken: number\n outputPerToken: number\n cacheReadPerToken: number\n cacheWritePerToken: number\n}\n\n/** List price per MTok → per-token rates, cache read at 0.1x, write 1.25x. */\nexport function aiRatesPerMTok(inputPerMTok: number, outputPerMTok: number): AiTokenRates {\n return {\n inputPerToken: inputPerMTok / 1_000_000,\n outputPerToken: outputPerMTok / 1_000_000,\n cacheReadPerToken: (inputPerMTok * 0.1) / 1_000_000,\n cacheWritePerToken: (inputPerMTok * 1.25) / 1_000_000,\n }\n}\n\n/**\n * The two rate tables a catalog row carries. Separate fields rather than one\n * table and a multiplier: a reader that wants our cost has to name it, and\n * a reader that wants the customer's has to name that, so neither can be\n * reached by accident.\n */\nexport interface AiCatalogRates {\n /** What the provider bills us for this model. */\n providerRates: AiTokenRates\n /** What a customer's credits are charged at for this model. */\n billedRates: AiTokenRates\n}\n\n/**\n * A row billed at exactly the provider's list rate — the usual case, written\n * once so the pair cannot drift.\n */\nexport function aiRatesAtList(\n inputPerMTok: number,\n outputPerMTok: number,\n): AiCatalogRates {\n return {\n providerRates: aiRatesPerMTok(inputPerMTok, outputPerMTok),\n billedRates: aiRatesPerMTok(inputPerMTok, outputPerMTok),\n }\n}\n\nexport interface AiCatalogEntry extends AiModelDescriptor, AiCatalogRates {\n /**\n * The tier a routing decision reads: `fast` for short, constrained\n * answers; `balanced` for the assistant and briefs; `deep` for the\n * dearest, slowest class.\n */\n tier: 'fast' | 'balanced' | 'deep'\n /**\n * The shortest prefix this model's provider will cache (AGL-2937). A\n * request whose cached span falls under it is served with the markers\n * honored and NOTHING cached: no error, no warning, and a usage report\n * that reads as a permanent cache miss.\n *\n * It is a property of the model rather than of the tier or the vendor,\n * and it does not fall as a generation advances — so the number has to be\n * written beside the model, and a door that means to cache has to be held\n * to it (`aiCachedPrefixCaches` in the runtime, and the door table in\n * `runtime/ai-prompt-cache.spec.ts`). Without it, \"this block carries a\n * breakpoint\" is a claim nothing checks, and a prompt can be designed\n * around a cache it never had.\n */\n cacheMinTokens: number\n}\n\n/**\n * The sentinels a docs-only answer is metered under (AGL-2486): not\n * models, but ids the meter sees, priced at zero so a deflected turn lands\n * in the same rollup as a served one and a keyless deployment does not\n * read as the most efficient one on the platform.\n */\nexport const AI_METER_SENTINELS = {\n docsRetrieval: 'docs-retrieval',\n docsLinks: 'docs-links',\n answerCache: 'assist-cache',\n} as const\n\nconst ANTHROPIC = 'anthropic'\nconst OPENAI_COMPATIBLE = 'openai-compatible'\n\n/**\n * A provider's row on the published subprocessor list: every field but the\n * host, which the registered adapter reports as its `endpointHost`.\n * `{apiKeyEnv}` anywhere in the wording stands for the adapter's\n * `apiKeyEnv`, so a credential's name is written in its adapter alone and\n * never in this module, which the browser bundle carries.\n */\nexport type AiProviderSubprocessorWording = Omit<PluginSubprocessorDeclaration, 'host'>\n\n/** A provider the catalog carries models for. */\nexport interface AiCatalogProvider {\n id: string\n /** The name a settings form shows. */\n label: string\n /**\n * The vendor's row on the published subprocessor list, written here and\n * nowhere else: `aiSubprocessors` derives the plugin's declarations from\n * it. Absent for a provider whose endpoint an operator names, which has\n * no fixed recipient to publish.\n */\n subprocessor?: AiProviderSubprocessorWording\n}\n\n/**\n * The Anthropic row's data cell up to its CRM sentence: every door but CRM\n * assistance, worded once for both of the CRM sentences below.\n */\nconst ANTHROPIC_DATA_RECEIVED_LEAD =\n \"What the user submits — a question, instruction or brief, with the earlier messages of the same Assist conversation — and the content of the element, post, section or page being worked on, with the generated response. On Pro and above, the organization's name and the console route and host travel with an Assist question. For an edit the assistant proposes in the besigner, an outline of the open page, component or layout: element and component ids, layer names, shortened setting values and the selected element's styles. For a generation job, the site inventory: the names and addresses of its pages and collections, the names of its components, layouts, templates, forms and datasets with their prop and field names, and the theme's summary, colors and fonts. For a theme change, the site's current theme settings and brand colors as hex values, from the organization's brand settings, the site logo in the media library or a public page the brief links to. For features that review or write search information, the text and structure of the pages concerned. For product copy, the store's name, the product's name, type, description, tags, options and search listing, the store's category names, and the product's first media-library photo as a copy at most 768 px on its longer edge with its metadata stripped; never another media file, a price, stock, an order or a customer. For products, categories and discounts proposed from a brief, the store's name and its existing category names. For an automation drafted from a brief, which of CRM, webhooks and bookings the plan includes; for an explanation, the automation's outline (trigger, conditions, each step's text with the names of the lists, campaigns, workflows, webhooks and datasets it uses and whether each exists, and a workflow's function names and expressions) and, for a failed run, its time, steps and recorded errors, with email addresses removed and never the triggering event's data. For an insight, the figure reports available and aggregate tables: traffic with top page paths, referrers and campaign tags; form views and submissions; revenue, orders and best-selling product names; bookings by service; campaign subjects with delivery, open and click rates; A/B test and variant conversions; and, for a dataset the member can see, field names and types, record and fill counts, number ranges and totals grouped by a value at least three records share. Email addresses and phone numbers are removed, and no individual record is sent. \"\n\n/** What every CRM door adds after its record sentence: drafts and imports. */\nconst ANTHROPIC_DATA_RECEIVED_CRM_DRAFTS_AND_IMPORTS =\n \"An email draft adds the request and the record's merge field names; an import sends the field names and types and each column's header and value kind, never a row.\"\n\n/** How the data cell words CRM assistance: what a record sends, and what never leaves. */\nexport interface AnthropicCrmAssistanceWording {\n record: string\n never: string\n}\n\n/**\n * CRM assistance as `/legal/subprocessors` published it until October 5,\n * 2026: the disclosed fields of a record, with addresses and numbers in its\n * text replaced. It is still what production sends while\n * `release_crm_assist_whole_record` is off, which the published wording\n * covers: the row describes what the CRM can send, not who has it on.\n */\nexport const ANTHROPIC_CRM_ASSISTANCE_DISCLOSED: AnthropicCrmAssistanceWording = {\n record:\n \"For CRM assistance, the opened contact, company, deal or lead as the CRM shows it: its name and, by kind, job title, company, lifecycle stage, tags, capture history and counts, domain, industry, headcount, pipeline stages, status, amount, dates, lost reason, parties and lead status, with its notes, newest timeline entries and open tasks and deals. Email addresses and phone numbers in that text are replaced, and no email, phone or postal field, marketing consent, custom field value, team member or record id is sent.\",\n never: 'No account identifiers, email addresses or authentication tokens.',\n}\n\n/**\n * CRM assistance once the whole record is sent (AGL-3520): the open-ended\n * wording the Subprocessors row and Privacy Policy section 2 were\n * republished with on October 5, 2026 (legal v10), before\n * `release_crm_assist_whole_record` may be turned on. The catalog row below\n * carries it in `dataReceived`.\n */\nexport const ANTHROPIC_CRM_ASSISTANCE_WHOLE_RECORD: AnthropicCrmAssistanceWording = {\n record:\n 'For CRM assistance, the opened record as the CRM shows it, with all of its standard and custom fields, including contact details, notes, timeline and related records.',\n never: 'No account identifiers or authentication tokens, and no email address outside an opened CRM record.',\n}\n\n/** The Anthropic row's data cell, with CRM assistance worded as `crm` words it. */\nexport function anthropicDataReceived(crm: AnthropicCrmAssistanceWording): string {\n return `${ANTHROPIC_DATA_RECEIVED_LEAD}${crm.record} ${ANTHROPIC_DATA_RECEIVED_CRM_DRAFTS_AND_IMPORTS} ${crm.never}`\n}\n\n/**\n * The providers the catalog carries models for, with the name a settings\n * form shows. A form offers providers from here for the reason it offers\n * models from here: nothing outside this folder names a vendor. For the\n * same reason a vendor's subprocessor row is written here too.\n */\nexport const AI_CATALOG_PROVIDERS: readonly AiCatalogProvider[] = [\n {\n id: ANTHROPIC,\n label: 'Anthropic',\n subprocessor: {\n entity: 'Anthropic, PBC',\n region: 'United States',\n purpose:\n \"AI features of the Services, including the Aglyn Assist helper: creating, editing and reviewing content, drafts and settings for a customer’s site, store and CRM, and explaining and summarizing the customer’s own setup and data\",\n publishedOn: '2026-10-07',\n reason:\n \"Reached through the AI plugin's Anthropic adapter (`libs/plugins/ai/src/lib/providers/anthropic.ts`) by the doors that call the AI runtime. `libs/plugins/ai/src/lib/server/assist-chat.ts` is gated by `release_assist` AND the key, and a generation job's text step by `release_ai_generative`; `libs/plugins/ai/src/lib/server/ai-assist.ts` carries NO release flag, so setting `{apiKeyEnv}` in production is by itself what starts this flow. `assist-anthropic-subprocessor-gate.spec.ts` holds the per-door detail and is the deeper guard for this one vendor.\",\n dataReceived: anthropicDataReceived(ANTHROPIC_CRM_ASSISTANCE_WHOLE_RECORD),\n },\n },\n { id: OPENAI_COMPATIBLE, label: 'OpenAI-compatible endpoint' },\n]\n\n/**\n * `vision` is written on every row rather than assumed (AGL-2916): each model\n * below reads a picture in a user turn, in the four formats\n * `AI_IMAGE_MEDIA_TYPES` names, as its vendor documents. A row added without\n * it reads as a model that does not, and is never sent one.\n */\nconst anthropicCapabilities = {\n streaming: true,\n tools: true,\n thinking: true,\n promptCache: true,\n vision: true,\n}\n\nexport const AI_MODEL_CATALOG: readonly AiCatalogEntry[] = [\n {\n id: 'claude-sonnet-5',\n provider: ANTHROPIC,\n label: 'Claude Sonnet 5',\n capabilities: anthropicCapabilities,\n /*\n * THE ONE ROW BILLED ABOVE ITS PROVIDER RATE (AGL-3015).\n *\n * The balanced tier prices most requests, so this markup is most of the\n * platform's AI margin. It is carried in the rate and not in the credit\n * conversion for the reason the module head gives: a credit stays a\n * fixed quantity of billed spend on every model, so the band, the\n * overage ladder and the invoice keep the arithmetic they were sized\n * with, and nothing below has to know which model served a request.\n *\n * Everything that reasons about what we PAY — the margin surfaces, the\n * staff spend meters, the discount guardrail's cost of goods — reads\n * `providerRates`, which is the vendor's published list.\n */\n providerRates: aiRatesPerMTok(2, 10),\n billedRates: aiRatesPerMTok(3, 15),\n tier: 'balanced',\n cacheMinTokens: 1_024,\n },\n {\n id: 'claude-sonnet-4-6',\n provider: ANTHROPIC,\n label: 'Claude Sonnet 4.6',\n capabilities: anthropicCapabilities,\n ...aiRatesAtList(3, 15),\n tier: 'balanced',\n cacheMinTokens: 1_024,\n },\n {\n // Rejects an explicit `thinking` setting; the runtime omits it.\n id: 'claude-haiku-4-5',\n provider: ANTHROPIC,\n label: 'Claude Haiku 4.5',\n capabilities: { ...anthropicCapabilities, thinking: false },\n ...aiRatesAtList(1, 5),\n tier: 'fast',\n // Four times the balanced tier's minimum: the cheapest model per token\n // is the hardest one to cache for, which is why a short prompt moved\n // here can cost more per request than it saved per token.\n cacheMinTokens: 4_096,\n },\n {\n id: 'claude-opus-5',\n provider: ANTHROPIC,\n label: 'Claude Opus 5',\n capabilities: anthropicCapabilities,\n ...aiRatesAtList(5, 25),\n tier: 'deep',\n cacheMinTokens: 512,\n },\n {\n id: 'claude-opus-4-8',\n provider: ANTHROPIC,\n label: 'Claude Opus 4.8',\n capabilities: anthropicCapabilities,\n ...aiRatesAtList(5, 25),\n tier: 'deep',\n cacheMinTokens: 1_024,\n },\n /**\n * The OpenAI-compatible adapter serves whatever the endpoint behind\n * `AI_OPENAI_COMPAT_BASE_URL` serves; these are the ids the routing table\n * may name on it. The figures are the vendor's public list, billed at\n * list: a deployment that reaches its own gateway at a negotiated price\n * is paying less than this says, so its margin reads low rather than\n * high — the direction a cost figure may be wrong in.\n */\n {\n id: 'gpt-5',\n provider: OPENAI_COMPATIBLE,\n label: 'GPT-5',\n capabilities: { streaming: true, tools: true, thinking: false, promptCache: true, vision: true },\n ...aiRatesAtList(1.25, 10),\n tier: 'balanced',\n cacheMinTokens: 1_024,\n },\n {\n id: 'gpt-5-mini',\n provider: OPENAI_COMPATIBLE,\n label: 'GPT-5 mini',\n capabilities: { streaming: true, tools: true, thinking: false, promptCache: true, vision: true },\n ...aiRatesAtList(0.25, 2),\n tier: 'fast',\n cacheMinTokens: 1_024,\n },\n]\n\n/**\n * The IMAGE models (AGL-3602): every model id the Media library's \"Create\n * with AI\" photo mode may route to — Google's Gemini image models on Vertex\n * AI — with a per-picture provider rate and a per-picture billed rate, and the\n * token rates the same request's prompt and thinking are billed at. Kept\n * apart from `AI_MODEL_CATALOG` because nothing that lists text models — the\n * model selector, the routing table, the allotments' allowlists — may ever\n * offer one of these for a conversation.\n *\n * ## The rates\n *\n * Google prices an output picture as image-output tokens: Gemini 3.1 Flash\n * Image writes a 1K picture as 1,120 tokens at $60 per million on the global\n * endpoint, so $0.0672 a picture. Its prompt is input tokens ($0.50 per\n * million) and its thinking is text output ($3.00 per million). Every figure\n * here is the global endpoint's list price, read from Google's Vertex AI\n * pricing page on 2026-10-06; a regional endpoint lists 10% higher, so a\n * deployment that moves off `global` reads its cost low by that much.\n *\n * Every billed figure is the provider figure at `AI_IMAGE_BILLED_MARKUP`:\n * the same ratio the balanced text tier is billed at over its provider rate\n * (Claude Sonnet 5, $3/$15 billed over $2/$10), so a credit buys the same\n * share of margin whether it is spent on words or on pictures. A picture is\n * NEVER billed at provider cost; `billed-rate-is-not-provider-cost.spec.ts`\n * refuses a row that is.\n *\n * A credit is $0.001 of billed spend (`ASSIST_CREDIT_COST_USD`), so the\n * default model's picture is 101 credits before its prompt and thinking.\n */\nexport interface AiImageCatalogEntry extends AiCatalogRates {\n id: string\n /** The image provider the model is served by. */\n provider: string\n label: string\n /** What the provider bills us for one generated picture. */\n providerUsdPerImage: number\n /** What one picture draws from a customer's credits. */\n billedUsdPerImage: number\n}\n\n/**\n * The billed rate over the provider rate: the balanced text tier's own markup\n * (`claude-sonnet-5`, 3 / 2), restated as a number so an image row cannot be\n * written at list by accident.\n */\nexport const AI_IMAGE_BILLED_MARKUP = 1.5\n\n/**\n * An image row's four figures from Google's list prices — USD per output\n * picture, and USD per million input and text-output tokens — each billed at\n * `AI_IMAGE_BILLED_MARKUP`.\n */\nexport function aiImageRatesAtMarkup(\n providerUsdPerImage: number,\n inputPerMTok: number,\n outputPerMTok: number,\n): Pick<\n AiImageCatalogEntry,\n 'providerUsdPerImage' | 'billedUsdPerImage' | 'providerRates' | 'billedRates'\n> {\n return {\n providerUsdPerImage,\n billedUsdPerImage: roundUsd(providerUsdPerImage * AI_IMAGE_BILLED_MARKUP),\n providerRates: aiRatesPerMTok(inputPerMTok, outputPerMTok),\n billedRates: aiRatesPerMTok(\n inputPerMTok * AI_IMAGE_BILLED_MARKUP,\n outputPerMTok * AI_IMAGE_BILLED_MARKUP,\n ),\n }\n}\n\n/** The image model a photo is made with when the operator names none. */\nexport const AI_IMAGE_DEFAULT_MODEL = 'gemini-3.1-flash-image'\n\n/** The image provider's id: Google's models on Vertex AI. */\nexport const AI_IMAGE_VERTEX_PROVIDER_ID = 'google-vertex'\n\nexport const AI_IMAGE_MODEL_CATALOG: readonly AiImageCatalogEntry[] = [\n {\n // The default: Google's own replacement for Imagen 4, which Vertex AI\n // discontinued in 2026.\n id: 'gemini-3.1-flash-image',\n provider: AI_IMAGE_VERTEX_PROVIDER_ID,\n label: 'Gemini 3.1 Flash Image',\n ...aiImageRatesAtMarkup(0.0672, 0.5, 3),\n },\n {\n id: 'gemini-3.1-flash-lite-image',\n provider: AI_IMAGE_VERTEX_PROVIDER_ID,\n label: 'Gemini 3.1 Flash-Lite Image',\n ...aiImageRatesAtMarkup(0.0336, 0.25, 1.5),\n },\n {\n id: 'gemini-3-pro-image',\n provider: AI_IMAGE_VERTEX_PROVIDER_ID,\n label: 'Gemini 3 Pro Image',\n ...aiImageRatesAtMarkup(0.1344, 2, 12),\n },\n]\n\n/**\n * The per-picture rates an unknown image model id is priced at: the dearest\n * row, on both rates, for the reason `AI_FALLBACK_RATES` gives — an estimate\n * that errs low is worse than one that errs high.\n */\nexport const AI_IMAGE_FALLBACK_RATES: Pick<\n AiImageCatalogEntry,\n 'providerUsdPerImage' | 'billedUsdPerImage'\n> = {\n providerUsdPerImage: Math.max(...AI_IMAGE_MODEL_CATALOG.map((row) => row.providerUsdPerImage)),\n billedUsdPerImage: Math.max(...AI_IMAGE_MODEL_CATALOG.map((row) => row.billedUsdPerImage)),\n}\n\n/** The image catalog row for a model id, or `undefined` for an unknown id. */\nexport function aiImageCatalogEntry(modelId: string): AiImageCatalogEntry | undefined {\n return AI_IMAGE_MODEL_CATALOG.find((entry) => entry.id === modelId)\n}\n\n/** What the provider charges us for one picture from `modelId`. */\nexport function aiImageProviderUsdPerImage(modelId: string): number {\n return (aiImageCatalogEntry(modelId) ?? AI_IMAGE_FALLBACK_RATES).providerUsdPerImage\n}\n\n/** What one picture from `modelId` draws from a customer's credits. */\nexport function aiImageBilledUsdPerImage(modelId: string): number {\n return (aiImageCatalogEntry(modelId) ?? AI_IMAGE_FALLBACK_RATES).billedUsdPerImage\n}\n\n/**\n * Usage as the meter prices it: a text exchange's tokens, and, for a door\n * that makes pictures, how many it delivered. `images` is absent on every\n * text exchange, which prices exactly as it always did.\n */\nexport type AiMeteredUsage = AiUsage & { images?: number }\n\n/** Pictures on a usage record: whole, finite, non-negative, else 0. */\nfunction aiImageCount(usage: AiMeteredUsage): number {\n const value = Number(usage.images ?? 0)\n return Number.isFinite(value) && value > 0 ? Math.floor(value) : 0\n}\n\nfunction roundUsd(value: number): number {\n return Math.round(value * 1_000_000) / 1_000_000\n}\n\n/** The dearest known tier, used when a model id is not in the catalog. */\nexport const AI_FALLBACK_RATES: AiTokenRates = aiRatesPerMTok(10, 50)\n\n/**\n * The minimum an unknown model id is assumed to have: the largest one the\n * catalog knows. It errs the way the rate fallback errs — toward the answer\n * that costs more — so an unrecognized id reads as \"this prompt does not\n * cache\" rather than promising a saving nobody measured.\n */\nexport const AI_FALLBACK_CACHE_MIN_TOKENS = 4_096\n\n/** The shortest prefix a model's provider will cache; the dearest assumption for an unknown id. */\nexport function aiModelCacheMinTokens(modelId: string): number {\n return aiCatalogEntry(modelId)?.cacheMinTokens ?? AI_FALLBACK_CACHE_MIN_TOKENS\n}\n\nconst ZERO_RATES = aiRatesPerMTok(0, 0)\n\n/** The catalog row for a model id, or `undefined` for an unknown id. */\nexport function aiCatalogEntry(modelId: string): AiCatalogEntry | undefined {\n return AI_MODEL_CATALOG.find((entry) => entry.id === modelId)\n}\n\nconst isSentinel = (modelId: string): boolean =>\n (Object.values(AI_METER_SENTINELS) as string[]).includes(modelId)\n\n/**\n * What the PROVIDER charges for a model id — our bill. A meter sentinel is\n * free; an image model's prompt and thinking are priced at its image row's\n * token rates (AGL-3602); an unknown id is priced at the dearest tier.\n *\n * The figure every cost and margin surface prices usage at. Answering the\n * customer's question from here would report a margin the platform does not\n * earn, and answering ours from `aiBilledRatesForModel` reports one it does\n * not pay; the two are separate functions so neither is reachable by\n * forgetting which one was meant.\n */\nexport function aiProviderRatesForModel(modelId: string): AiTokenRates {\n if (isSentinel(modelId)) return ZERO_RATES\n return (\n aiCatalogEntry(modelId)?.providerRates ??\n aiImageCatalogEntry(modelId)?.providerRates ??\n AI_FALLBACK_RATES\n )\n}\n\n/**\n * What a CUSTOMER'S CREDITS are charged at for a model id. A meter sentinel\n * is free; an unknown id is priced at the dearest tier.\n *\n * The figure the credit meter, the band and the model selector price usage\n * at. It is at or above `aiProviderRatesForModel` on every row.\n */\nexport function aiBilledRatesForModel(modelId: string): AiTokenRates {\n if (isSentinel(modelId)) return ZERO_RATES\n return (\n aiCatalogEntry(modelId)?.billedRates ??\n aiImageCatalogEntry(modelId)?.billedRates ??\n AI_FALLBACK_RATES\n )\n}\n\nfunction priceUsage(usage: AiUsage, rate: AiTokenRates): number {\n const raw =\n usage.inputTokens * rate.inputPerToken +\n usage.outputTokens * rate.outputPerToken +\n usage.cacheReadTokens * rate.cacheReadPerToken +\n usage.cacheWriteTokens * rate.cacheWritePerToken\n return Math.round(raw * 1_000_000) / 1_000_000\n}\n\n/**\n * What one exchange COST US, at the serving model's provider rates, rounded\n * to 6dp. Real money, and the only figure a margin may be taken against.\n */\nexport function estimateAiProviderCostUsd(usage: AiMeteredUsage, modelId: string): number {\n return roundUsd(\n priceUsage(usage, aiProviderRatesForModel(modelId)) +\n aiImageCount(usage) * aiImageProviderUsdPerImage(modelId),\n )\n}\n\n/**\n * What one exchange DRAWS FROM A CUSTOMER, at the serving model's billed\n * rates, rounded to 6dp — the figure `assistCreditsFromUsd` turns into\n * credits. At or above `estimateAiProviderCostUsd` for the same exchange.\n */\nexport function estimateAiBilledUsd(usage: AiMeteredUsage, modelId: string): number {\n return roundUsd(\n priceUsage(usage, aiBilledRatesForModel(modelId)) +\n aiImageCount(usage) * aiImageBilledUsdPerImage(modelId),\n )\n}\n\n/** Every catalog id a provider serves. */\nexport function aiModelIdsForProvider(providerId: string): string[] {\n return AI_MODEL_CATALOG.filter((entry) => entry.provider === providerId).map(\n (entry) => entry.id,\n )\n}\n\n/**\n * What a step asks for, and what the routing table answers with. Every\n * door names its kind here rather than a model, so a model swap — an\n * incident override, an org's own setting, a cheaper model for a cheap\n * step — is one row rather than a search through the doors (AGL-2937).\n */\nexport type AiStepKind =\n | 'assist.chat'\n | 'copy.element'\n | 'copy.section'\n | 'copy.blog'\n | 'generate.section'\n | 'job.component'\n | 'job.crm'\n | 'job.experiment'\n | 'job.form'\n | 'job.insight'\n | 'job.layout'\n | 'job.logic'\n | 'job.template'\n | 'job.page'\n | 'job.products'\n | 'job.seo'\n | 'job.text'\n | 'job.theme'\n | 'job.plan'\n | 'job.email'\n | 'job.campaign'\n | 'job.workflow'\n\n/** The tier each step kind is served from when no setting overrides it. */\nexport const AI_STEP_TIERS: Record<AiStepKind, AiCatalogEntry['tier']> = {\n 'assist.chat': 'balanced',\n 'copy.element': 'fast',\n 'copy.section': 'balanced',\n 'copy.blog': 'balanced',\n 'generate.section': 'balanced',\n // A reusable component is one structured tree with the typed props it\n // declares, and choosing what becomes a prop is the judgment the step sells.\n 'job.component': 'balanced',\n // CRM by AI (AGL-2917): a record's summary and next step, a deal's stage, a\n // lead's standing, a one-to-one email draft and an import's column matches.\n // Short answers through a strict tool, held to the facts the CRM reports\n // about the record the member opened.\n 'job.crm': 'fast',\n // A/B tests by AI (AGL-2914): variants of one piece of copy, and a\n // result put into words for a verdict code already reached. Short answers\n // through a strict tool, but the judgment a variant sells — which ONE idea\n // to vary so the result says something — is the balanced tier's.\n 'job.experiment': 'balanced',\n // A form is one small tree held to the building rules and to the contract\n // its submissions are read by; a re-ask costs more than the tier saves.\n 'job.form': 'balanced',\n // An insight (AGL-2915) chooses which figures answer a question and says\n // what they show; the trace holds every number, and the judgment of what is\n // worth saying is what the fast tier does worse.\n 'job.insight': 'balanced',\n // A layout or a page template is one structured tree held to every\n // building rule; the fast tier re-asks more than it saves.\n 'job.layout': 'balanced',\n // A site function or variable (AGL-3603): a small structured answer held\n // to the evaluator's grammar, the names it may read and a first run, whose\n // judgment is turning a description into conditions and arithmetic; the\n // fast tier re-asks more than it saves.\n 'job.logic': 'balanced',\n 'job.template': 'balanced',\n // A page section (AGL-2907) is held to the whole page's building rules on\n // every pass, for the same reason.\n 'job.page': 'balanced',\n // A product's copy, a store's first products, or its categories and\n // discounts (AGL-2916): judgment about what a photo shows and what a shopper\n // needs, held to storefront claim rules a re-ask costs more to meet than the\n // tier saves.\n 'job.products': 'balanced',\n // SEO fields, alt text and an audit's fixes (AGL-2910): short answers\n // through a strict tool, held to a length and to the page's own text.\n 'job.seo': 'fast',\n 'job.text': 'balanced',\n // A theme is one structured answer over a small, fixed control set; the\n // judgment is in the color choices, which the fast tier makes worse.\n 'job.theme': 'balanced',\n 'job.plan': 'balanced',\n // An email is one tree held to every building rule, with subject lines\n // whose judgment is the point of asking; the fast tier re-asks more than it\n // saves. A campaign is the same email, drafted into a campaign.\n 'job.email': 'balanced',\n 'job.campaign': 'balanced',\n // An automation is a small structured answer whose judgment is choosing the\n // trigger and steps a description means, and an explanation reads one\n // closely; the fast tier re-asks more than it saves on both (AGL-2919).\n 'job.workflow': 'balanced',\n}\n\n/** The first catalog model of a tier on a provider, or the provider's first model. */\nexport function aiDefaultModelFor(providerId: string, tier: AiCatalogEntry['tier']): string | undefined {\n const onProvider = AI_MODEL_CATALOG.filter((entry) => entry.provider === providerId)\n return (onProvider.find((entry) => entry.tier === tier) ?? onProvider[0])?.id\n}\n"],"names":["aiRatesPerMTok","inputPerMTok","outputPerMTok","inputPerToken","outputPerToken","cacheReadPerToken","cacheWritePerToken","aiRatesAtList","providerRates","billedRates","AI_METER_SENTINELS","docsRetrieval","docsLinks","answerCache","ANTHROPIC","OPENAI_COMPATIBLE","ANTHROPIC_DATA_RECEIVED_LEAD","ANTHROPIC_DATA_RECEIVED_CRM_DRAFTS_AND_IMPORTS","ANTHROPIC_CRM_ASSISTANCE_DISCLOSED","record","never","ANTHROPIC_CRM_ASSISTANCE_WHOLE_RECORD","anthropicDataReceived","crm","AI_CATALOG_PROVIDERS","id","label","subprocessor","entity","region","purpose","publishedOn","reason","dataReceived","anthropicCapabilities","streaming","tools","thinking","promptCache","vision","AI_MODEL_CATALOG","provider","capabilities","tier","cacheMinTokens","AI_IMAGE_BILLED_MARKUP","aiImageRatesAtMarkup","providerUsdPerImage","billedUsdPerImage","roundUsd","AI_IMAGE_DEFAULT_MODEL","AI_IMAGE_VERTEX_PROVIDER_ID","AI_IMAGE_MODEL_CATALOG","AI_IMAGE_FALLBACK_RATES","Math","max","map","row","aiImageCatalogEntry","modelId","find","entry","aiImageProviderUsdPerImage","aiImageBilledUsdPerImage","aiImageCount","usage","value","Number","images","isFinite","floor","round","AI_FALLBACK_RATES","AI_FALLBACK_CACHE_MIN_TOKENS","aiModelCacheMinTokens","aiCatalogEntry","ZERO_RATES","isSentinel","Object","values","includes","aiProviderRatesForModel","aiBilledRatesForModel","priceUsage","rate","raw","inputTokens","outputTokens","cacheReadTokens","cacheWriteTokens","estimateAiProviderCostUsd","estimateAiBilledUsd","aiModelIdsForProvider","providerId","filter","AI_STEP_TIERS","aiDefaultModelFor","onProvider"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAgDD,4EAA4E,GAC5E,OAAO,SAASA,eAAeC,YAAoB,EAAEC,aAAqB;IACxE,OAAO;QACLC,eAAeF,eAAe;QAC9BG,gBAAgBF,gBAAgB;QAChCG,mBAAmB,AAACJ,eAAe,MAAO;QAC1CK,oBAAoB,AAACL,eAAe,OAAQ;IAC9C;AACF;AAeA;;;CAGC,GACD,OAAO,SAASM,cACdN,YAAoB,EACpBC,aAAqB;IAErB,OAAO;QACLM,eAAeR,eAAeC,cAAcC;QAC5CO,aAAaT,eAAeC,cAAcC;IAC5C;AACF;AA0BA;;;;;CAKC,GACD,OAAO,MAAMQ,qBAAqB;IAChCC,eAAe;IACfC,WAAW;IACXC,aAAa;AACf,EAAU;AAEV,MAAMC,YAAY;AAClB,MAAMC,oBAAoB;AAyB1B;;;CAGC,GACD,MAAMC,+BACJ;AAEF,4EAA4E,GAC5E,MAAMC,iDACJ;AAQF;;;;;;CAMC,GACD,OAAO,MAAMC,qCAAoE;IAC/EC,QACE;IACFC,OAAO;AACT,EAAC;AAED;;;;;;CAMC,GACD,OAAO,MAAMC,wCAAuE;IAClFF,QACE;IACFC,OAAO;AACT,EAAC;AAED,iFAAiF,GACjF,OAAO,SAASE,sBAAsBC,GAAkC;IACtE,OAAO,GAAGP,+BAA+BO,IAAIJ,MAAM,CAAC,CAAC,EAAEF,+CAA+C,CAAC,EAAEM,IAAIH,KAAK,EAAE;AACtH;AAEA;;;;;CAKC,GACD,OAAO,MAAMI,uBAAqD;IAChE;QACEC,IAAIX;QACJY,OAAO;QACPC,cAAc;YACZC,QAAQ;YACRC,QAAQ;YACRC,SACE;YACFC,aAAa;YACbC,QACE;YACFC,cAAcX,sBAAsBD;QACtC;IACF;IACA;QAAEI,IA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,kBAAkB;IAClB,0EAA0E;IAC1E,wEAAwE;IACxE,YAAY;IACZ,yEAAyE;IACzE,4EAA4E;IAC5E,iDAAiD;IACjD,eAAe;IACf,mEAAmE;IACnE,2DAA2D;IAC3D,cAAc;IACd,yEAAyE;IACzE,2EAA2E;IAC3E,wEAAwE;IACxE,wCAAwC;IACxC,aAAa;IACb,gBAAgB;IAChB,0EAA0E;IAC1E,mCAAmC;IACnC,YAAY;IACZ,oEAAoE;IACpE,6EAA6E;IAC7E,6EAA6E;IAC7E,cAAc;IACd,gBAAgB;IAChB,sEAAsE;IACtE,sEAAsE;IACtE,WAAW;IACX,YAAY;IACZ,wEAAwE;IACxE,qEAAqE;IACrE,aAAa;IACb,YAAY;IACZ,uEAAuE;IACvE,4EAA4E;IAC5E,gEAAgE;IAChE,aAAa;IACb,gBAAgB;IAChB,4EAA4E;IAC5E,sEAAsE;IACtE,wEAAwE;IACxE,gBAAgB;AAClB,EAAC;AAED,oFAAoF,GACpF,OAAO,SAASC,kBAAkBH,UAAkB,EAAElD,IAA4B;QAExEsD;QAAAA;IADR,MAAMA,aAAazD,iBAAiBsD,MAAM,CAAC,CAACjC,QAAUA,MAAMpB,QAAQ,KAAKoD;IACzE,QAAQI,SAAAA,mBAAAA,WAAWrC,IAAI,CAAC,CAACC,QAAUA,MAAMlB,IAAI,KAAKA,iBAA1CsD,mBAAmDA,UAAU,CAAC,EAAE,qBAAjE,AAACA,MAAmExE,EAAE;AAC/E"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/providers/catalog.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 { PluginSubprocessorDeclaration } from '@aglyn/aglyn/plugin-manager/plugin-subprocessors'\nimport type { AiModelDescriptor, AiUsage } from './contract'\nimport type { AiImageSize } from './image-contract'\n\n/**\n * The model catalog (AGL-2939): every model id the plugin will route to,\n * with its provider, its display name, its capabilities and its list rates.\n * The ONE place a model id is written outside a provider adapter — the\n * routing table maps a step kind to an id through here, the meter prices\n * usage by id through here, and a settings form offers ids from here.\n *\n * ## Two rates, because one figure was answering two questions\n *\n * Every row carries a PROVIDER rate and a BILLED rate (AGL-3015):\n *\n * - `providerRates` is what the vendor charges us. It is money leaving the\n * company, so cost accounting, the margin surfaces and every staff spend\n * meter price usage through this one and no other.\n * - `billedRates` is what a customer's credits are charged at. The credit\n * meter, the band, the overage ladder and the model selector price usage\n * through this one, because it is the figure a customer's balance moves by.\n *\n * They are equal on nearly every row, and a helper writes the pair from one\n * figure so an unmarked row cannot drift apart by a typo. A row may be\n * billed ABOVE its provider rate deliberately — the markup is carried in the\n * rate rather than in the credit conversion, which keeps a credit a fixed\n * quantity of billed spend on every model and leaves the band, the ladder\n * and the invoice on the one arithmetic they were sized with. A row billed\n * BELOW its provider rate would sell tokens at a loss, and\n * `billed-rate-is-not-provider-cost.spec.ts` refuses one.\n *\n * Both are keyed by model rather than fixed at one model's rates because the\n * default is an env override: a one-line incident swap to a dearer model\n * would otherwise keep reporting the cheaper money, and per-org cost would\n * read as roughly right — the failure mode this whole meter exists to\n * prevent. An unknown id falls back to the most EXPENSIVE known tier on\n * purpose, on both rates: an estimate that errs low is worse than one that\n * errs high, whether the figure is our bill or the customer's.\n */\n\nexport interface AiTokenRates {\n inputPerToken: number\n outputPerToken: number\n cacheReadPerToken: number\n cacheWritePerToken: number\n}\n\n/** List price per MTok → per-token rates, cache read at 0.1x, write 1.25x. */\nexport function aiRatesPerMTok(inputPerMTok: number, outputPerMTok: number): AiTokenRates {\n return {\n inputPerToken: inputPerMTok / 1_000_000,\n outputPerToken: outputPerMTok / 1_000_000,\n cacheReadPerToken: (inputPerMTok * 0.1) / 1_000_000,\n cacheWritePerToken: (inputPerMTok * 1.25) / 1_000_000,\n }\n}\n\n/**\n * The two rate tables a catalog row carries. Separate fields rather than one\n * table and a multiplier: a reader that wants our cost has to name it, and\n * a reader that wants the customer's has to name that, so neither can be\n * reached by accident.\n */\nexport interface AiCatalogRates {\n /** What the provider bills us for this model. */\n providerRates: AiTokenRates\n /** What a customer's credits are charged at for this model. */\n billedRates: AiTokenRates\n}\n\n/**\n * A row billed at exactly the provider's list rate — the usual case, written\n * once so the pair cannot drift.\n */\nexport function aiRatesAtList(\n inputPerMTok: number,\n outputPerMTok: number,\n): AiCatalogRates {\n return {\n providerRates: aiRatesPerMTok(inputPerMTok, outputPerMTok),\n billedRates: aiRatesPerMTok(inputPerMTok, outputPerMTok),\n }\n}\n\n/** {@link aiRatesAtList} for a model whose cache read is not a tenth of its input price. */\nexport function aiRatesAtListWithCacheRead(\n inputPerMTok: number,\n outputPerMTok: number,\n cacheReadPerMTok: number,\n): AiCatalogRates {\n const rates = { ...aiRatesPerMTok(inputPerMTok, outputPerMTok), cacheReadPerToken: cacheReadPerMTok / 1_000_000 }\n return { providerRates: rates, billedRates: { ...rates } }\n}\n\nexport interface AiCatalogEntry extends AiModelDescriptor, AiCatalogRates {\n /**\n * The tier a routing decision reads: `fast` for short, constrained\n * answers; `balanced` for the assistant and briefs; `deep` for the\n * dearest, slowest class.\n */\n tier: 'fast' | 'balanced' | 'deep'\n /**\n * The shortest prefix this model's provider will cache (AGL-2937). A\n * request whose cached span falls under it is served with the markers\n * honored and NOTHING cached: no error, no warning, and a usage report\n * that reads as a permanent cache miss.\n *\n * It is a property of the model rather than of the tier or the vendor,\n * and it does not fall as a generation advances — so the number has to be\n * written beside the model, and a door that means to cache has to be held\n * to it (`aiCachedPrefixCaches` in the runtime, and the door table in\n * `runtime/ai-prompt-cache.spec.ts`). Without it, \"this block carries a\n * breakpoint\" is a claim nothing checks, and a prompt can be designed\n * around a cache it never had.\n */\n cacheMinTokens: number\n}\n\n/**\n * The sentinels a docs-only answer is metered under (AGL-2486): not\n * models, but ids the meter sees, priced at zero so a deflected turn lands\n * in the same rollup as a served one and a keyless deployment does not\n * read as the most efficient one on the platform.\n */\nexport const AI_METER_SENTINELS = {\n docsRetrieval: 'docs-retrieval',\n docsLinks: 'docs-links',\n answerCache: 'assist-cache',\n} as const\n\nconst ANTHROPIC = 'anthropic'\nconst OPENAI_COMPATIBLE = 'openai-compatible'\n\n/**\n * A provider's row on the published subprocessor list: every field but the\n * host, which the registered adapter reports as its `endpointHost`.\n * `{apiKeyEnv}` anywhere in the wording stands for the adapter's\n * `apiKeyEnv`, so a credential's name is written in its adapter alone and\n * never in this module, which the browser bundle carries.\n */\nexport type AiProviderSubprocessorWording = Omit<PluginSubprocessorDeclaration, 'host'>\n\n/** A provider the catalog carries models for. */\nexport interface AiCatalogProvider {\n id: string\n /** The name a settings form shows. */\n label: string\n /**\n * The vendor's row on the published subprocessor list, written here and\n * nowhere else: `aiSubprocessors` derives the plugin's declarations from\n * it. Absent for a provider whose endpoint an operator names, which has\n * no fixed recipient to publish.\n */\n subprocessor?: AiProviderSubprocessorWording\n}\n\n/**\n * The Anthropic row's data cell up to its CRM sentence: every door but CRM\n * assistance, worded once for both of the CRM sentences below.\n */\nconst ANTHROPIC_DATA_RECEIVED_LEAD =\n \"What the user submits — a question, instruction or brief, with the earlier messages of the same Assist conversation — and the content of the element, post, section or page being worked on, with the generated response. On Pro and above, the organization's name and the console route and host travel with an Assist question. For an edit the assistant proposes in the besigner, an outline of the open page, component or layout: element and component ids, layer names, shortened setting values and the selected element's styles. For a generation job, the site inventory: the names and addresses of its pages and collections, the names of its components, layouts, templates, forms and datasets with their prop and field names, and the theme's summary, colors and fonts. For a theme change, the site's current theme settings and brand colors as hex values, from the organization's brand settings, the site logo in the media library or a public page the brief links to. For features that review or write search information, the text and structure of the pages concerned. For product copy, the store's name, the product's name, type, description, tags, options and search listing, the store's category names, and the product's first media-library photo as a copy at most 768 px on its longer edge with its metadata stripped; never another media file, a price, stock, an order or a customer. For products, categories and discounts proposed from a brief, the store's name and its existing category names. For an automation drafted from a brief, which of CRM, webhooks and bookings the plan includes; for an explanation, the automation's outline (trigger, conditions, each step's text with the names of the lists, campaigns, workflows, webhooks and datasets it uses and whether each exists, and a workflow's function names and expressions) and, for a failed run, its time, steps and recorded errors, with email addresses removed and never the triggering event's data. For an insight, the figure reports available and aggregate tables: traffic with top page paths, referrers and campaign tags; form views and submissions; revenue, orders and best-selling product names; bookings by service; campaign subjects with delivery, open and click rates; A/B test and variant conversions; and, for a dataset the member can see, field names and types, record and fill counts, number ranges and totals grouped by a value at least three records share. Email addresses and phone numbers are removed, and no individual record is sent. \"\n\n/** What every CRM door adds after its record sentence: drafts and imports. */\nconst ANTHROPIC_DATA_RECEIVED_CRM_DRAFTS_AND_IMPORTS =\n \"An email draft adds the request and the record's merge field names; an import sends the field names and types and each column's header and value kind, never a row.\"\n\n/** How the data cell words CRM assistance: what a record sends, and what never leaves. */\nexport interface AnthropicCrmAssistanceWording {\n record: string\n never: string\n}\n\n/**\n * CRM assistance as `/legal/subprocessors` published it until October 5,\n * 2026: the disclosed fields of a record, with addresses and numbers in its\n * text replaced. It is still what production sends while\n * `release_crm_assist_whole_record` is off, which the published wording\n * covers: the row describes what the CRM can send, not who has it on.\n */\nexport const ANTHROPIC_CRM_ASSISTANCE_DISCLOSED: AnthropicCrmAssistanceWording = {\n record:\n \"For CRM assistance, the opened contact, company, deal or lead as the CRM shows it: its name and, by kind, job title, company, lifecycle stage, tags, capture history and counts, domain, industry, headcount, pipeline stages, status, amount, dates, lost reason, parties and lead status, with its notes, newest timeline entries and open tasks and deals. Email addresses and phone numbers in that text are replaced, and no email, phone or postal field, marketing consent, custom field value, team member or record id is sent.\",\n never: 'No account identifiers, email addresses or authentication tokens.',\n}\n\n/**\n * CRM assistance once the whole record is sent (AGL-3520): the open-ended\n * wording the Subprocessors row and Privacy Policy section 2 were\n * republished with on October 5, 2026 (legal v10), before\n * `release_crm_assist_whole_record` may be turned on. The catalog row below\n * carries it in `dataReceived`.\n */\nexport const ANTHROPIC_CRM_ASSISTANCE_WHOLE_RECORD: AnthropicCrmAssistanceWording = {\n record:\n 'For CRM assistance, the opened record as the CRM shows it, with all of its standard and custom fields, including contact details, notes, timeline and related records.',\n never: 'No account identifiers or authentication tokens, and no email address outside an opened CRM record.',\n}\n\n/** The Anthropic row's data cell, with CRM assistance worded as `crm` words it. */\nexport function anthropicDataReceived(crm: AnthropicCrmAssistanceWording): string {\n return `${ANTHROPIC_DATA_RECEIVED_LEAD}${crm.record} ${ANTHROPIC_DATA_RECEIVED_CRM_DRAFTS_AND_IMPORTS} ${crm.never}`\n}\n\n/**\n * The providers the catalog carries models for, with the name a settings\n * form shows. A form offers providers from here for the reason it offers\n * models from here: nothing outside this folder names a vendor. For the\n * same reason a vendor's subprocessor row is written here too.\n */\nexport const AI_CATALOG_PROVIDERS: readonly AiCatalogProvider[] = [\n {\n id: ANTHROPIC,\n label: 'Anthropic',\n subprocessor: {\n entity: 'Anthropic, PBC',\n region: 'United States',\n purpose:\n \"AI features of the Services, including the Aglyn Assist helper: creating, editing and reviewing content, drafts and settings for a customer’s site, store and CRM, and explaining and summarizing the customer’s own setup and data\",\n publishedOn: '2026-10-07',\n reason:\n \"Reached through the AI plugin's Anthropic adapter (`libs/plugins/ai/src/lib/providers/anthropic.ts`) by the doors that call the AI runtime. `libs/plugins/ai/src/lib/server/assist-chat.ts` is gated by `release_assist` AND the key, and a generation job's text step by `release_ai_generative`; `libs/plugins/ai/src/lib/server/ai-assist.ts` carries NO release flag, so setting `{apiKeyEnv}` in production is by itself what starts this flow. `assist-anthropic-subprocessor-gate.spec.ts` holds the per-door detail and is the deeper guard for this one vendor.\",\n dataReceived: anthropicDataReceived(ANTHROPIC_CRM_ASSISTANCE_WHOLE_RECORD),\n },\n },\n { id: OPENAI_COMPATIBLE, label: 'OpenAI-compatible endpoint' },\n]\n\n/**\n * `vision` is written on every row rather than assumed (AGL-2916): each model\n * below reads a picture in a user turn, in the four formats\n * `AI_IMAGE_MEDIA_TYPES` names, as its vendor documents. A row added without\n * it reads as a model that does not, and is never sent one.\n */\nconst anthropicCapabilities = {\n streaming: true,\n tools: true,\n thinking: true,\n promptCache: true,\n vision: true,\n}\n\nexport const AI_MODEL_CATALOG: readonly AiCatalogEntry[] = [\n {\n // THE BALANCED TIER'S DEFAULT (AGL-3660): the first balanced row is what\n // `aiDefaultModelFor` answers, so Free, \"Auto\" and every step routed to\n // balanced run here. Rejects `thinking: {type: \"disabled\"}` and forced\n // tool choice: the adapter sends thinking off as `between_tools` and\n // every tool call with `tool_choice: auto`.\n id: 'claude-sonnet-5-5',\n provider: ANTHROPIC,\n label: 'Claude Sonnet 5.5',\n capabilities: anthropicCapabilities,\n /*\n * THE ROWS BILLED ABOVE THEIR PROVIDER RATE (AGL-3015).\n *\n * The balanced tier prices most requests, so this markup is most of the\n * platform's AI margin. It is carried in the rate and not in the credit\n * conversion for the reason the module head gives: a credit stays a\n * fixed quantity of billed spend on every model, so the band, the\n * overage ladder and the invoice keep the arithmetic they were sized\n * with, and nothing below has to know which model served a request.\n *\n * Everything that reasons about what we PAY — the margin surfaces, the\n * staff spend meters, the discount guardrail's cost of goods — reads\n * `providerRates`, which is the vendor's published list. Sonnet 5.5's\n * list is Sonnet 5's, except a cache read: $0.10/MTok, a twentieth of\n * input. A customer is billed exactly what Sonnet 5 billed, so the\n * balanced tier's prices do not move when its default does.\n */\n providerRates: { ...aiRatesPerMTok(2, 10), cacheReadPerToken: 0.1 / 1_000_000 },\n billedRates: aiRatesPerMTok(3, 15),\n tier: 'balanced',\n cacheMinTokens: 512,\n },\n {\n // The balanced default until AGL-3660, kept so a workspace that chose it\n // and every recording that names it still resolve, at the same rates.\n id: 'claude-sonnet-5',\n provider: ANTHROPIC,\n label: 'Claude Sonnet 5',\n capabilities: anthropicCapabilities,\n providerRates: aiRatesPerMTok(2, 10),\n billedRates: aiRatesPerMTok(3, 15),\n tier: 'balanced',\n cacheMinTokens: 1_024,\n },\n {\n id: 'claude-sonnet-4-6',\n provider: ANTHROPIC,\n label: 'Claude Sonnet 4.6',\n capabilities: anthropicCapabilities,\n ...aiRatesAtList(3, 15),\n tier: 'balanced',\n cacheMinTokens: 1_024,\n },\n {\n // Rejects an explicit `thinking` setting; the runtime omits it.\n id: 'claude-haiku-4-5',\n provider: ANTHROPIC,\n label: 'Claude Haiku 4.5',\n capabilities: { ...anthropicCapabilities, thinking: false },\n ...aiRatesAtList(1, 5),\n tier: 'fast',\n // Four times the balanced tier's minimum: the cheapest model per token\n // is the hardest one to cache for, which is why a short prompt moved\n // here can cost more per request than it saved per token.\n cacheMinTokens: 4_096,\n },\n {\n id: 'claude-opus-5',\n provider: ANTHROPIC,\n label: 'Claude Opus 5',\n capabilities: anthropicCapabilities,\n ...aiRatesAtList(5, 25),\n tier: 'deep',\n cacheMinTokens: 512,\n },\n {\n // Listed for a side-by-side comparison (AGL-3660); the deep tier's\n // default stays claude-opus-5 above. Thinking cannot be disabled and its\n // effort defaults to medium, so the adapter omits thinking where a step\n // asks for it off and names effort high where a step names none — Opus\n // 5's own default. Forced tool choice is refused; the adapter sends auto.\n id: 'claude-opus-5-5',\n provider: ANTHROPIC,\n label: 'Claude Opus 5.5',\n capabilities: anthropicCapabilities,\n // At list, like its deep-tier siblings. A cache read is $0.20/MTok, a\n // twentieth of input rather than the usual tenth.\n ...aiRatesAtListWithCacheRead(4, 20, 0.2),\n tier: 'deep',\n cacheMinTokens: 512,\n },\n {\n id: 'claude-opus-4-8',\n provider: ANTHROPIC,\n label: 'Claude Opus 4.8',\n capabilities: anthropicCapabilities,\n ...aiRatesAtList(5, 25),\n tier: 'deep',\n cacheMinTokens: 1_024,\n },\n /**\n * The OpenAI-compatible adapter serves whatever the endpoint behind\n * `AI_OPENAI_COMPAT_BASE_URL` serves; these are the ids the routing table\n * may name on it. The figures are the vendor's public list, billed at\n * list: a deployment that reaches its own gateway at a negotiated price\n * is paying less than this says, so its margin reads low rather than\n * high — the direction a cost figure may be wrong in.\n */\n {\n id: 'gpt-5',\n provider: OPENAI_COMPATIBLE,\n label: 'GPT-5',\n capabilities: { streaming: true, tools: true, thinking: false, promptCache: true, vision: true },\n ...aiRatesAtList(1.25, 10),\n tier: 'balanced',\n cacheMinTokens: 1_024,\n },\n {\n id: 'gpt-5-mini',\n provider: OPENAI_COMPATIBLE,\n label: 'GPT-5 mini',\n capabilities: { streaming: true, tools: true, thinking: false, promptCache: true, vision: true },\n ...aiRatesAtList(0.25, 2),\n tier: 'fast',\n cacheMinTokens: 1_024,\n },\n]\n\n/**\n * The IMAGE models (AGL-3602): every model id the Media library's \"Create\n * with AI\" photo mode may route to — Google's Gemini image models on Vertex\n * AI — with a per-picture provider rate and a per-picture billed rate, and the\n * token rates the same request's prompt and thinking are billed at. Kept\n * apart from `AI_MODEL_CATALOG` because nothing that lists text models — the\n * model selector, the routing table, the allotments' allowlists — may ever\n * offer one of these for a conversation.\n *\n * ## The rates\n *\n * Google prices an output picture as image-output tokens: Gemini 3.1 Flash\n * Image writes a 1K picture as 1,120 tokens at $60 per million on the global\n * endpoint, so $0.0672 a picture. Its prompt is input tokens ($0.50 per\n * million) and its thinking is text output ($3.00 per million). Every figure\n * here is the global endpoint's list price, read from Google's Vertex AI\n * pricing page on 2026-10-06; a regional endpoint lists 10% higher, so a\n * deployment that moves off `global` reads its cost low by that much.\n *\n * Every billed figure is the provider figure at `AI_IMAGE_BILLED_MARKUP`:\n * the same ratio the balanced text tier is billed at over its provider rate\n * (Claude Sonnet 5, $3/$15 billed over $2/$10), so a credit buys the same\n * share of margin whether it is spent on words or on pictures. A picture is\n * NEVER billed at provider cost; `billed-rate-is-not-provider-cost.spec.ts`\n * refuses a row that is.\n *\n * A credit is $0.001 of billed spend (`ASSIST_CREDIT_COST_USD`), so the\n * default model's picture is 101 credits before its prompt and thinking.\n *\n * Every per-picture figure on a row is the 1K picture's. A 512 px picture —\n * what the Free plan makes — is written as fewer image tokens at the same\n * per-token rate (`AI_IMAGE_SIZE_OUTPUT_TOKENS`), so it is priced at the 1K\n * figure scaled by its share of tokens: $0.04482 from the provider and\n * $0.06723 billed on the default model, before its prompt and thinking.\n */\nexport interface AiImageCatalogEntry extends AiCatalogRates {\n id: string\n /** The image provider the model is served by. */\n provider: string\n label: string\n /** What the provider bills us for one generated picture. */\n providerUsdPerImage: number\n /** What one picture draws from a customer's credits. */\n billedUsdPerImage: number\n}\n\n/**\n * The billed rate over the provider rate: the balanced text tier's own markup\n * (`claude-sonnet-5`, 3 / 2), restated as a number so an image row cannot be\n * written at list by accident.\n */\nexport const AI_IMAGE_BILLED_MARKUP = 1.5\n\n/**\n * An image row's four figures from Google's list prices — USD per output\n * picture, and USD per million input and text-output tokens — each billed at\n * `AI_IMAGE_BILLED_MARKUP`.\n */\nexport function aiImageRatesAtMarkup(\n providerUsdPerImage: number,\n inputPerMTok: number,\n outputPerMTok: number,\n): Pick<\n AiImageCatalogEntry,\n 'providerUsdPerImage' | 'billedUsdPerImage' | 'providerRates' | 'billedRates'\n> {\n return {\n providerUsdPerImage,\n billedUsdPerImage: roundUsd(providerUsdPerImage * AI_IMAGE_BILLED_MARKUP),\n providerRates: aiRatesPerMTok(inputPerMTok, outputPerMTok),\n billedRates: aiRatesPerMTok(\n inputPerMTok * AI_IMAGE_BILLED_MARKUP,\n outputPerMTok * AI_IMAGE_BILLED_MARKUP,\n ),\n }\n}\n\n/**\n * The image-output tokens Google writes a picture as, by size (AGL-3602),\n * read from the usage of real Gemini 3.1 Flash Image answers on 2026-10-07:\n * 747 at 512 px and 1,120 at 1K. A row's per-picture figures are the 1K\n * picture's; a 512 px picture is priced at its share of them.\n */\nexport const AI_IMAGE_SIZE_OUTPUT_TOKENS: Readonly<Record<AiImageSize, number>> = {\n '512': 747,\n '1K': 1_120,\n}\n\n/** A 1K per-picture figure at `size`, by the size's share of image tokens. */\nfunction atImageSize(usdAt1K: number, size: AiImageSize | undefined): number {\n const tokens = AI_IMAGE_SIZE_OUTPUT_TOKENS[size ?? '1K'] ?? AI_IMAGE_SIZE_OUTPUT_TOKENS['1K']\n return roundUsd((usdAt1K * tokens) / AI_IMAGE_SIZE_OUTPUT_TOKENS['1K'])\n}\n\n/** The image model a photo is made with when the operator names none. */\nexport const AI_IMAGE_DEFAULT_MODEL = 'gemini-3.1-flash-image'\n\n/** The image provider's id: Google's models on Vertex AI. */\nexport const AI_IMAGE_VERTEX_PROVIDER_ID = 'google-vertex'\n\n/**\n * The image providers' rows on the published subprocessor list, kept apart\n * from `AI_CATALOG_PROVIDERS` for the reason the image catalog is kept apart\n * from the text one: a settings form offers text providers from that list,\n * and an image provider answers no conversation. The host is the adapter's\n * published endpoint (`VERTEX_IMAGE_PUBLISHED_HOST`).\n *\n * Google's row is dated to its change-log entry on `/legal/subprocessors`,\n * published with the Privacy Policy §2 sentence naming Google for image\n * generation (legal v12).\n */\nexport const AI_IMAGE_CATALOG_PROVIDERS: readonly AiCatalogProvider[] = [\n {\n id: AI_IMAGE_VERTEX_PROVIDER_ID,\n label: 'Google Vertex AI',\n subprocessor: {\n entity: 'Google LLC (Google Cloud Vertex AI)',\n // The global endpoint, which Google documents as routing and\n // processing a request anywhere in the world, with no data residency\n // guarantee: Google, not Aglyn, chooses the location.\n region: 'Global — Google selects where requests are processed',\n purpose:\n \"AI image generation: creating images for a customer's media library from a description a user writes\",\n publishedOn: '2026-10-08',\n reason:\n \"Reached through the AI plugin's Vertex AI image adapter (`libs/plugins/ai/src/lib/providers/vertex-image.ts`) by the Media library's Create with AI door (`libs/plugins/ai/src/lib/server/ai-media-image.ts`) for every kind that is not drawn as SVG, as the platform's own service account. Off unless `AI_IMAGE_VERTEX_PROJECT` names a Google Cloud project; the console offers those kinds only where `NEXT_PUBLIC_AI_IMAGE_PHOTOS` is `on`. The request carries the description and the kind's fixed style wording, the shape and fixed settings, and nothing else.\",\n dataReceived:\n \"The description the user writes and the shape requested, and the generated image returned. No account identifiers, email addresses, or other content of the customer's site.\",\n },\n },\n]\n\nexport const AI_IMAGE_MODEL_CATALOG: readonly AiImageCatalogEntry[] = [\n {\n // The default: Google's own replacement for Imagen 4, which Vertex AI\n // discontinued in 2026.\n id: 'gemini-3.1-flash-image',\n provider: AI_IMAGE_VERTEX_PROVIDER_ID,\n label: 'Gemini 3.1 Flash Image',\n ...aiImageRatesAtMarkup(0.0672, 0.5, 3),\n },\n {\n id: 'gemini-3.1-flash-lite-image',\n provider: AI_IMAGE_VERTEX_PROVIDER_ID,\n label: 'Gemini 3.1 Flash-Lite Image',\n ...aiImageRatesAtMarkup(0.0336, 0.25, 1.5),\n },\n {\n id: 'gemini-3-pro-image',\n provider: AI_IMAGE_VERTEX_PROVIDER_ID,\n label: 'Gemini 3 Pro Image',\n ...aiImageRatesAtMarkup(0.1344, 2, 12),\n },\n]\n\n/**\n * The per-picture rates an unknown image model id is priced at: the dearest\n * row, on both rates, for the reason `AI_FALLBACK_RATES` gives — an estimate\n * that errs low is worse than one that errs high.\n */\nexport const AI_IMAGE_FALLBACK_RATES: Pick<\n AiImageCatalogEntry,\n 'providerUsdPerImage' | 'billedUsdPerImage'\n> = {\n providerUsdPerImage: Math.max(...AI_IMAGE_MODEL_CATALOG.map((row) => row.providerUsdPerImage)),\n billedUsdPerImage: Math.max(...AI_IMAGE_MODEL_CATALOG.map((row) => row.billedUsdPerImage)),\n}\n\n/** The image catalog row for a model id, or `undefined` for an unknown id. */\nexport function aiImageCatalogEntry(modelId: string): AiImageCatalogEntry | undefined {\n return AI_IMAGE_MODEL_CATALOG.find((entry) => entry.id === modelId)\n}\n\n/** What the provider charges us for one picture from `modelId`, at `size` (1K when absent). */\nexport function aiImageProviderUsdPerImage(modelId: string, size?: AiImageSize): number {\n return atImageSize((aiImageCatalogEntry(modelId) ?? AI_IMAGE_FALLBACK_RATES).providerUsdPerImage, size)\n}\n\n/** What one picture from `modelId` at `size` (1K when absent) draws from a customer's credits. */\nexport function aiImageBilledUsdPerImage(modelId: string, size?: AiImageSize): number {\n return atImageSize((aiImageCatalogEntry(modelId) ?? AI_IMAGE_FALLBACK_RATES).billedUsdPerImage, size)\n}\n\n/**\n * Usage as the meter prices it: a text exchange's tokens, and, for a door\n * that makes pictures, how many it delivered and at what size (1K when\n * absent). `images` is absent on every text exchange, which prices exactly\n * as it always did.\n */\nexport type AiMeteredUsage = AiUsage & { images?: number; imageSize?: AiImageSize }\n\n/** Pictures on a usage record: whole, finite, non-negative, else 0. */\nfunction aiImageCount(usage: AiMeteredUsage): number {\n const value = Number(usage.images ?? 0)\n return Number.isFinite(value) && value > 0 ? Math.floor(value) : 0\n}\n\nfunction roundUsd(value: number): number {\n return Math.round(value * 1_000_000) / 1_000_000\n}\n\n/** The dearest known tier, used when a model id is not in the catalog. */\nexport const AI_FALLBACK_RATES: AiTokenRates = aiRatesPerMTok(10, 50)\n\n/**\n * The minimum an unknown model id is assumed to have: the largest one the\n * catalog knows. It errs the way the rate fallback errs — toward the answer\n * that costs more — so an unrecognized id reads as \"this prompt does not\n * cache\" rather than promising a saving nobody measured.\n */\nexport const AI_FALLBACK_CACHE_MIN_TOKENS = 4_096\n\n/** The shortest prefix a model's provider will cache; the dearest assumption for an unknown id. */\nexport function aiModelCacheMinTokens(modelId: string): number {\n return aiCatalogEntry(modelId)?.cacheMinTokens ?? AI_FALLBACK_CACHE_MIN_TOKENS\n}\n\nconst ZERO_RATES = aiRatesPerMTok(0, 0)\n\n/** The catalog row for a model id, or `undefined` for an unknown id. */\nexport function aiCatalogEntry(modelId: string): AiCatalogEntry | undefined {\n return AI_MODEL_CATALOG.find((entry) => entry.id === modelId)\n}\n\nconst isSentinel = (modelId: string): boolean =>\n (Object.values(AI_METER_SENTINELS) as string[]).includes(modelId)\n\n/**\n * What the PROVIDER charges for a model id — our bill. A meter sentinel is\n * free; an image model's prompt and thinking are priced at its image row's\n * token rates (AGL-3602); an unknown id is priced at the dearest tier.\n *\n * The figure every cost and margin surface prices usage at. Answering the\n * customer's question from here would report a margin the platform does not\n * earn, and answering ours from `aiBilledRatesForModel` reports one it does\n * not pay; the two are separate functions so neither is reachable by\n * forgetting which one was meant.\n */\nexport function aiProviderRatesForModel(modelId: string): AiTokenRates {\n if (isSentinel(modelId)) return ZERO_RATES\n return (\n aiCatalogEntry(modelId)?.providerRates ??\n aiImageCatalogEntry(modelId)?.providerRates ??\n AI_FALLBACK_RATES\n )\n}\n\n/**\n * What a CUSTOMER'S CREDITS are charged at for a model id. A meter sentinel\n * is free; an unknown id is priced at the dearest tier.\n *\n * The figure the credit meter, the band and the model selector price usage\n * at. It is at or above `aiProviderRatesForModel` on every row.\n */\nexport function aiBilledRatesForModel(modelId: string): AiTokenRates {\n if (isSentinel(modelId)) return ZERO_RATES\n return (\n aiCatalogEntry(modelId)?.billedRates ??\n aiImageCatalogEntry(modelId)?.billedRates ??\n AI_FALLBACK_RATES\n )\n}\n\nfunction priceUsage(usage: AiUsage, rate: AiTokenRates): number {\n const raw =\n usage.inputTokens * rate.inputPerToken +\n usage.outputTokens * rate.outputPerToken +\n usage.cacheReadTokens * rate.cacheReadPerToken +\n usage.cacheWriteTokens * rate.cacheWritePerToken\n return Math.round(raw * 1_000_000) / 1_000_000\n}\n\n/**\n * What one exchange COST US, at the serving model's provider rates, rounded\n * to 6dp. Real money, and the only figure a margin may be taken against.\n */\nexport function estimateAiProviderCostUsd(usage: AiMeteredUsage, modelId: string): number {\n return roundUsd(\n priceUsage(usage, aiProviderRatesForModel(modelId)) +\n aiImageCount(usage) * aiImageProviderUsdPerImage(modelId, usage.imageSize),\n )\n}\n\n/**\n * What one exchange DRAWS FROM A CUSTOMER, at the serving model's billed\n * rates, rounded to 6dp — the figure `assistCreditsFromUsd` turns into\n * credits. At or above `estimateAiProviderCostUsd` for the same exchange.\n */\nexport function estimateAiBilledUsd(usage: AiMeteredUsage, modelId: string): number {\n return roundUsd(\n priceUsage(usage, aiBilledRatesForModel(modelId)) +\n aiImageCount(usage) * aiImageBilledUsdPerImage(modelId, usage.imageSize),\n )\n}\n\n/** Every catalog id a provider serves. */\nexport function aiModelIdsForProvider(providerId: string): string[] {\n return AI_MODEL_CATALOG.filter((entry) => entry.provider === providerId).map(\n (entry) => entry.id,\n )\n}\n\n/**\n * What a step asks for, and what the routing table answers with. Every\n * door names its kind here rather than a model, so a model swap — an\n * incident override, an org's own setting, a cheaper model for a cheap\n * step — is one row rather than a search through the doors (AGL-2937).\n */\nexport type AiStepKind =\n | 'assist.chat'\n | 'copy.element'\n | 'copy.section'\n | 'copy.blog'\n | 'generate.section'\n | 'job.component'\n | 'job.crm'\n | 'job.edit'\n | 'job.experiment'\n | 'job.form'\n | 'job.insight'\n | 'job.layout'\n | 'job.logic'\n | 'job.template'\n | 'job.page'\n | 'job.products'\n | 'job.seo'\n | 'job.text'\n | 'job.theme'\n | 'job.plan'\n | 'job.email'\n | 'job.campaign'\n | 'job.workflow'\n\n/** The tier each step kind is served from when no setting overrides it. */\nexport const AI_STEP_TIERS: Record<AiStepKind, AiCatalogEntry['tier']> = {\n 'assist.chat': 'balanced',\n 'copy.element': 'fast',\n 'copy.section': 'balanced',\n 'copy.blog': 'balanced',\n 'generate.section': 'balanced',\n // A reusable component is one structured tree with the typed props it\n // declares, and choosing what becomes a prop is the judgment the step sells.\n 'job.component': 'balanced',\n // CRM by AI (AGL-2917): a record's summary and next step, a deal's stage, a\n // lead's standing, a one-to-one email draft and an import's column matches.\n // Short answers through a strict tool, held to the facts the CRM reports\n // about the record the member opened.\n 'job.crm': 'fast',\n // A change to a page or a layout the site has (AGL-3616): the Assist edit\n // rung's protocol run as a job, held to the closed world of the document's\n // own element ids and to the palette validators. Finding the element a\n // request means, and changing only it, is the judgment; the chat door that\n // proposes the same edits runs on this tier.\n 'job.edit': 'balanced',\n // A/B tests by AI (AGL-2914): variants of one piece of copy, and a\n // result put into words for a verdict code already reached. Short answers\n // through a strict tool, but the judgment a variant sells — which ONE idea\n // to vary so the result says something — is the balanced tier's.\n 'job.experiment': 'balanced',\n // A form is one small tree held to the building rules and to the contract\n // its submissions are read by; a re-ask costs more than the tier saves.\n 'job.form': 'balanced',\n // An insight (AGL-2915) chooses which figures answer a question and says\n // what they show; the trace holds every number, and the judgment of what is\n // worth saying is what the fast tier does worse.\n 'job.insight': 'balanced',\n // A layout or a page template is one structured tree held to every\n // building rule; the fast tier re-asks more than it saves.\n 'job.layout': 'balanced',\n // A site function or variable (AGL-3603): a small structured answer held\n // to the evaluator's grammar, the names it may read and a first run, whose\n // judgment is turning a description into conditions and arithmetic; the\n // fast tier re-asks more than it saves.\n 'job.logic': 'balanced',\n 'job.template': 'balanced',\n // A page section (AGL-2907) is held to the whole page's building rules on\n // every pass, for the same reason.\n 'job.page': 'balanced',\n // A product's copy, a store's first products, or its categories and\n // discounts (AGL-2916): judgment about what a photo shows and what a shopper\n // needs, held to storefront claim rules a re-ask costs more to meet than the\n // tier saves.\n 'job.products': 'balanced',\n // SEO fields, alt text and an audit's fixes (AGL-2910): short answers\n // through a strict tool, held to a length and to the page's own text.\n 'job.seo': 'fast',\n 'job.text': 'balanced',\n // A theme is one structured answer over a small, fixed control set; the\n // judgment is in the color choices, which the fast tier makes worse.\n 'job.theme': 'balanced',\n 'job.plan': 'balanced',\n // An email is one tree held to every building rule, with subject lines\n // whose judgment is the point of asking; the fast tier re-asks more than it\n // saves. A campaign is the same email, drafted into a campaign.\n 'job.email': 'balanced',\n 'job.campaign': 'balanced',\n // An automation is a small structured answer whose judgment is choosing the\n // trigger and steps a description means, and an explanation reads one\n // closely; the fast tier re-asks more than it saves on both (AGL-2919).\n 'job.workflow': 'balanced',\n}\n\n/** The first catalog model of a tier on a provider, or the provider's first model. */\nexport function aiDefaultModelFor(providerId: string, tier: AiCatalogEntry['tier']): string | undefined {\n const onProvider = AI_MODEL_CATALOG.filter((entry) => entry.provider === providerId)\n return (onProvider.find((entry) => entry.tier === tier) ?? onProvider[0])?.id\n}\n"],"names":["aiRatesPerMTok","inputPerMTok","outputPerMTok","inputPerToken","outputPerToken","cacheReadPerToken","cacheWritePerToken","aiRatesAtList","providerRates","billedRates","aiRatesAtListWithCacheRead","cacheReadPerMTok","rates","AI_METER_SENTINELS","docsRetrieval","docsLinks","answerCache","ANTHROPIC","OPENAI_COMPATIBLE","ANTHROPIC_DATA_RECEIVED_LEAD","ANTHROPIC_DATA_RECEIVED_CRM_DRAFTS_AND_IMPORTS","ANTHROPIC_CRM_ASSISTANCE_DISCLOSED","record","never","ANTHROPIC_CRM_ASSISTANCE_WHOLE_RECORD","anthropicDataReceived","crm","AI_CATALOG_PROVIDERS","id","label","subprocessor","entity","region","purpose","publishedOn","reason","dataReceived","anthropicCapabilities","streaming","tools","thinking","promptCache","vision","AI_MODEL_CATALOG","provider","capabilities","tier","cacheMinTokens","AI_IMAGE_BILLED_MARKUP","aiImageRatesAtMarkup","providerUsdPerImage","billedUsdPerImage","roundUsd","AI_IMAGE_SIZE_OUTPUT_TOKENS","atImageSize","usdAt1K","size","tokens","AI_IMAGE_DEFAULT_MODEL","AI_IMAGE_VERTEX_PROVIDER_ID","AI_IMAGE_CATALOG_PROVIDERS","AI_IMAGE_MODEL_CATALOG","AI_IMAGE_FALLBACK_RATES","Math","max","map","row","aiImageCatalogEntry","modelId","find","entry","aiImageProviderUsdPerImage","aiImageBilledUsdPerImage","aiImageCount","usage","value","Number","images","isFinite","floor","round","AI_FALLBACK_RATES","AI_FALLBACK_CACHE_MIN_TOKENS","aiModelCacheMinTokens","aiCatalogEntry","ZERO_RATES","isSentinel","Object","values","includes","aiProviderRatesForModel","aiBilledRatesForModel","priceUsage","rate","raw","inputTokens","outputTokens","cacheReadTokens","cacheWriteTokens","estimateAiProviderCostUsd","imageSize","estimateAiBilledUsd","aiModelIdsForProvider","providerId","filter","AI_STEP_TIERS","aiDefaultModelFor","onProvider"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAiDD,4EAA4E,GAC5E,OAAO,SAASA,eAAeC,YAAoB,EAAEC,aAAqB;IACxE,OAAO;QACL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;IACZ,yEAAyE;IACzE,4EAA4E;IAC5E,iDAAiD;IACjD,eAAe;IACf,mEAAmE;IACnE,2DAA2D;IAC3D,cAAc;IACd,yEAAyE;IACzE,2EAA2E;IAC3E,wEAAwE;IACxE,wCAAwC;IACxC,aAAa;IACb,gBAAgB;IAChB,0EAA0E;IAC1E,mCAAmC;IACnC,YAAY;IACZ,oEAAoE;IACpE,6EAA6E;IAC7E,6EAA6E;IAC7E,cAAc;IACd,gBAAgB;IAChB,sEAAsE;IACtE,sEAAsE;IACtE,WAAW;IACX,YAAY;IACZ,wEAAwE;IACxE,qEAAqE;IACrE,aAAa;IACb,YAAY;IACZ,uEAAuE;IACvE,4EAA4E;IAC5E,gEAAgE;IAChE,aAAa;IACb,gBAAgB;IAChB,4EAA4E;IAC5E,sEAAsE;IACtE,wEAAwE;IACxE,gBAAgB;AAClB,EAAC;AAED,oFAAoF,GACpF,OAAO,SAASC,kBAAkBH,UAAkB,EAAEzD,IAA4B;QAExE6D;QAAAA;IADR,MAAMA,aAAahE,iBAAiB6D,MAAM,CAAC,CAAClC,QAAUA,MAAM1B,QAAQ,KAAK2D;IACzE,QAAQI,SAAAA,mBAAAA,WAAWtC,IAAI,CAAC,CAACC,QAAUA,MAAMxB,IAAI,KAAKA,iBAA1C6D,mBAAmDA,UAAU,CAAC,EAAE,qBAAjE,AAACA,MAAmE/E,EAAE;AAC/E"}
@@ -73,11 +73,18 @@ import { UpstreamServiceError } from '@aglyn/shared-util-errors';
73
73
  * One system block. `cacheBreakpoint` marks the end of a cacheable prefix;
74
74
  * `volatile` declares that the text carries a per-request or per-org byte
75
75
  * and therefore may never sit inside one.
76
+ *
77
+ * `site` declares a block that describes ONE site (AGL-3661): its business
78
+ * profile, status and remembered preferences. As a breakpoint it is cached
79
+ * once per site, so it must close the cached span — every platform-wide
80
+ * block sits ahead of it, where every workspace still shares one entry —
81
+ * and the runtime refuses a request that puts another breakpoint after it.
76
82
  */
77
83
  export interface AiSystemBlock {
78
84
  text: string;
79
85
  cacheBreakpoint?: true;
80
86
  volatile?: true;
87
+ site?: true;
81
88
  }
82
89
  /** A structured-output tool. `strict` is required, not optional. */
83
90
  export interface AiTool {
@@ -205,6 +212,14 @@ export interface AiRequestBase {
205
212
  effort?: AiEffort;
206
213
  thinking?: AiThinking;
207
214
  signal?: AbortSignal;
215
+ /**
216
+ * How long a cache entry the breakpoints write should live, where the
217
+ * provider offers a choice: the provider's default (five minutes on the
218
+ * Messages API) when absent. Only a development run asks for `1h`
219
+ * (`runtime/ai-dev-replay.ts`); it changes no answer, only what a second
220
+ * request within the hour pays for the prefix.
221
+ */
222
+ cacheTtl?: '1h';
208
223
  }
209
224
  /** The request an adapter receives: the runtime has already validated it. */
210
225
  export interface AiProviderRequest extends AiRequestBase {
@@ -458,6 +473,20 @@ export interface AiProvider {
458
473
  * door can still send a plain error status and hand back its reservation.
459
474
  */
460
475
  stream(request: AiProviderRequest): Promise<AsyncIterable<AiStreamEvent>>;
476
+ /**
477
+ * Many requests answered together, asynchronously, at the provider's batch
478
+ * discount, where it has one: each entry is that request's result, or the
479
+ * error it failed with, in the order asked. Only a development run's live
480
+ * eval calls it (`runtime/ai-live-batch.ts`); no door does.
481
+ */
482
+ completeBatch?(requests: readonly AiProviderRequest[], options?: AiBatchOptions): Promise<Array<AiResult | Error>>;
483
+ }
484
+ /** How a batch is waited on. */
485
+ export interface AiBatchOptions {
486
+ /** Between two looks at a batch still processing; 10 s when absent. */
487
+ pollMs?: number;
488
+ /** The most a batch is waited for before every request in it fails; an hour when absent. */
489
+ timeoutMs?: number;
461
490
  }
462
491
  /** A count off the wire: finite, non-negative, whole; anything else is 0. */
463
492
  export declare function aiTokenCount(value: unknown): number;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/providers/contract.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 { UpstreamServiceError } from '@aglyn/shared-util-errors'\n\n/**\n * The provider contract (AGL-2939): the one shape every AI door speaks, and\n * the one thing an adapter has to implement. The runtime, the gate, the\n * jobs, the doctrine and the usage code import this and never a vendor\n * URL, header or model literal — Anthropic is one adapter behind it, and\n * an OpenAI-compatible endpoint is the second, which is what proves the\n * seam holds.\n *\n * ── Prompt caching, by construction ───────────────────────────────────────\n *\n * `system` is an ordered list of blocks, and caching is a PREFIX match: a\n * breakpoint covers every block before it, and one byte that differs per\n * request anywhere inside that prefix gives every distinct value its own\n * copy of it. The AGL-2352 rule is that no per-org byte may sit inside a\n * cached prefix — a white-label brand name interpolated into a cached block\n * multiplies the prefix count by the number of brands, each written off its\n * own traffic and expired before it is read. So a block marked `volatile`\n * may not sit at or before the last `cacheBreakpoint`, and the runtime\n * refuses the request before a byte leaves the process. A provider with no\n * cache honors the order and ignores the markers.\n *\n * ── Structured output ─────────────────────────────────────────────────────\n *\n * A `tools` entry is sent strict, with additional properties forbidden on\n * its schema, so a tool call's `input` validates against the schema\n * exactly. Tool choice stays automatic — forced tool use is not portable\n * across models — and the caller's system text names the tool it wants. An\n * adapter delivers `input` as an object; a stream assembles it from\n * fragments and parses the whole once, at the block's end. Nothing\n * string-matches the serialized form: models differ in how they escape it.\n * A provider bounds how much strict schema one request may carry, and an\n * adapter declares those bounds as `toolSchemaLimits`: three bounds a vendor\n * publishes and counts, and a fourth, the size of the grammar the schemas\n * compile to, that none publishes and only a live request settles.\n *\n * ── Thinking ──────────────────────────────────────────────────────────────\n *\n * `thinking: 'off'` and `'adaptive'` are sent when the provider has the\n * control; an omitted field sends NOTHING, leaving the model's own default\n * in force. The omission is deliberate rather than a gap: some models\n * reject an explicit setting, and the copy assistant serves its element\n * mode on such a model. `effort` rides the same rule.\n *\n * ── Pictures ──────────────────────────────────────────────────────────────\n *\n * A user turn may carry pictures beside its text (AGL-2916): `content` is\n * then an ordered list of parts, and a turn with nothing but text stays a\n * string, which every adapter passes through as it always has. A picture is\n * base64 bytes of one of `AI_IMAGE_MEDIA_TYPES`, never a URL, so no provider\n * fetches anything on the platform's behalf. The runtime refuses a picture\n * on an assistant turn, a picture for a model whose descriptor does not say\n * `vision`, and a picture past the size or count bounds, all before any\n * network is touched. Each adapter maps the parts onto its vendor's shape.\n */\n\n/**\n * One system block. `cacheBreakpoint` marks the end of a cacheable prefix;\n * `volatile` declares that the text carries a per-request or per-org byte\n * and therefore may never sit inside one.\n */\nexport interface AiSystemBlock {\n text: string\n cacheBreakpoint?: true\n volatile?: true\n}\n\n/** A structured-output tool. `strict` is required, not optional. */\nexport interface AiTool {\n name: string\n description: string\n /** A JSON schema of `type: 'object'`; `additionalProperties` is forced off. */\n inputSchema: Record<string, unknown>\n strict: true\n}\n\n/**\n * How much of a request's strict tools a provider can compile (AGL-3096). A\n * provider that constrains decoding to a tool's schema compiles every strict\n * schema of a request together, before the model runs, and refuses a request\n * whose schemas are past its bounds. That refusal is permanent: the schema is\n * the same on every retry. Each bound is a TOTAL over every strict tool one\n * request sends, as `aiToolSchemaCounts` counts them. A bound left out is one\n * the provider does not state.\n *\n * A provider may also refuse a request whose schemas compile to too large a\n * grammar, which none of the published counts can see: a request counting 1\n * strict tool, 0 optional parameters and 1 union was refused for exactly that\n * (AGL-3096). `compiledSchemaBytes` stands in for it, on live evidence.\n */\nexport interface AiToolSchemaLimits {\n /** The most strict tools one request may send. */\n strictTools?: number\n /** The most properties, across every strict schema, left out of their object's `required`. */\n optionalParameters?: number\n /** The most schemas, across every strict schema, that are a union: an `anyOf` or `oneOf`, or a list of types. */\n unionParameters?: number\n /**\n * The most bytes of schema a request's grammar may be compiled from, as\n * `aiToolSchemaCompiledBytes` measures them.\n *\n * Unlike the bounds above, this one is EMPIRICAL. A provider refuses a\n * request whose compiled grammar is too large without publishing the size,\n * so the number here is not read off a vendor's page: it is the largest a\n * live request has been watched to carry, and every number above it is\n * unknown rather than safe. Raising it on an offline measurement alone\n * puts the guard back where it could not see the break.\n */\n compiledSchemaBytes?: number\n}\n\n/** A request's strict tools, counted on the measures `AiToolSchemaLimits` bounds. */\nexport type AiToolSchemaCounts = Required<AiToolSchemaLimits>\n\n/**\n * One schema as a grammar compiler reads it: every local `$ref` written out\n * at each place it is used, and every description, title and `$defs` dropped,\n * since none of them constrains a single token. A schema that refers to\n * itself is written out once around and then left as the reference it is.\n */\nfunction compiledForm(node: unknown, root: Record<string, unknown>, resolving: ReadonlySet<string>): unknown {\n if (Array.isArray(node)) return node.map((entry) => compiledForm(entry, root, resolving))\n if (!isSchemaObject(node)) return node\n const ref = node['$ref']\n if (typeof ref === 'string') {\n if (resolving.has(ref)) return { $ref: ref }\n return compiledForm(localSchemaAt(root, ref), root, new Set([...resolving, ref]))\n }\n const written: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(node)) {\n if (key === 'description' || key === 'title' || key === '$defs') continue\n written[key] = compiledForm(value, root, resolving)\n }\n return written\n}\n\n/**\n * The bytes of schema a request's grammar is compiled from, over all its\n * strict tools. It is a stand-in for the size of the grammar itself, which\n * nothing outside the provider can measure, and it errs toward more: a `$ref`\n * counts at each place it is used, because a compiler that writes it out\n * there pays for it there.\n */\nexport function aiToolSchemaCompiledBytes(tools: readonly AiTool[]): number {\n return tools.reduce(\n (bytes, tool) => bytes + JSON.stringify(compiledForm(tool.inputSchema, tool.inputSchema, new Set())).length,\n 0,\n )\n}\n\nfunction isSchemaObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/** The schema a local `$ref` (`#/…`) points at, or `undefined`. */\nfunction localSchemaAt(root: Record<string, unknown>, ref: string): unknown {\n if (!ref.startsWith('#/')) return undefined\n return ref\n .slice(2)\n .split('/')\n .map((key) => key.replace(/~1/g, '/').replace(/~0/g, '~'))\n .reduce<unknown>((node, key) => (isSchemaObject(node) ? node[key] : undefined), root)\n}\n\nfunction countSchema(\n node: unknown,\n root: Record<string, unknown>,\n counts: AiToolSchemaCounts,\n resolving: ReadonlySet<string>,\n): void {\n if (!isSchemaObject(node)) return\n if (Array.isArray(node['anyOf']) || Array.isArray(node['oneOf']) || Array.isArray(node['type'])) {\n counts.unionParameters += 1\n }\n const ref = node['$ref']\n if (typeof ref === 'string' && !resolving.has(ref)) {\n countSchema(localSchemaAt(root, ref), root, counts, new Set([...resolving, ref]))\n }\n const properties = node['properties']\n if (isSchemaObject(properties)) {\n const required = Array.isArray(node['required']) ? node['required'] : []\n for (const [key, property] of Object.entries(properties)) {\n if (!required.includes(key)) counts.optionalParameters += 1\n countSchema(property, root, counts, resolving)\n }\n }\n const items = node['items']\n for (const item of Array.isArray(items) ? items : [items]) countSchema(item, root, counts, resolving)\n for (const key of ['anyOf', 'allOf', 'oneOf']) {\n const branches = node[key]\n if (Array.isArray(branches)) for (const branch of branches) countSchema(branch, root, counts, resolving)\n }\n}\n\n/**\n * The strict tools of one request, counted on each measure a provider bounds.\n * Every tool the contract sends is strict. Each schema is walked whole: every\n * property, every `items`, every branch of an `anyOf`, `allOf` or `oneOf`, and\n * a local `$ref` at each place it is used. A union nested in an array's items\n * or in another union's branch counts on its own, as it does for a provider\n * that compiles it; a `$ref` counted where it is used errs toward more.\n */\nexport function aiToolSchemaCounts(tools: readonly AiTool[]): AiToolSchemaCounts {\n const counts: AiToolSchemaCounts = {\n strictTools: tools.length,\n optionalParameters: 0,\n unionParameters: 0,\n compiledSchemaBytes: aiToolSchemaCompiledBytes(tools),\n }\n for (const tool of tools) countSchema(tool.inputSchema, tool.inputSchema, counts, new Set())\n return counts\n}\n\n/**\n * Each bound, as one, as many, and where its number comes from — a published\n * bound reads as the provider's own, a measured one as what has been proved.\n */\nconst TOOL_SCHEMA_MEASURES: ReadonlyArray<[keyof AiToolSchemaLimits, string, string, string]> = [\n ['strictTools', 'strict tool', 'strict tools', 'the provider compiles'],\n ['optionalParameters', 'optional parameter', 'optional parameters', 'the provider compiles'],\n ['unionParameters', 'union-typed parameter', 'union-typed parameters', 'the provider compiles'],\n ['compiledSchemaBytes', 'byte of compiled schema', 'bytes of compiled schema', 'a live request has proved'],\n]\n\n/** Each bound a request's tools are past, as a sentence; empty when every one holds. */\nexport function aiToolSchemaBreaches(\n tools: readonly AiTool[],\n limits: AiToolSchemaLimits | undefined,\n): string[] {\n if (!limits) return []\n const counts = aiToolSchemaCounts(tools)\n return TOOL_SCHEMA_MEASURES.flatMap(([measure, one, many, source]) => {\n const limit = limits[measure]\n const count = counts[measure]\n return limit !== undefined && count > limit\n ? [`${count} ${count === 1 ? one : many} in one request, over the ${limit} ${source}`]\n : []\n })\n}\n\nexport type AiEffort = 'low' | 'medium' | 'high'\nexport type AiThinking = 'off' | 'adaptive'\n\n/**\n * The picture formats a request may carry (AGL-2916): the four every model\n * the catalog marks as reading images accepts. A door converts anything else\n * — an AVIF, an SVG — before it attaches the picture, or attaches none.\n */\nexport const AI_IMAGE_MEDIA_TYPES = ['image/jpeg', 'image/png', 'image/webp', 'image/gif'] as const\nexport type AiImageMediaType = (typeof AI_IMAGE_MEDIA_TYPES)[number]\n\n/**\n * The largest picture one part may carry, in decoded bytes: the ceiling the\n * providers behind the contract accept for one image. A door that attaches a\n * picture resizes it far below this; the runtime refuses anything above it\n * before a byte leaves the process, rather than letting the provider do it\n * after the request was paid for in time.\n */\nexport const AI_IMAGE_MAX_BYTES = 5 * 1024 * 1024\n\n/** The most pictures one request may carry. */\nexport const AI_REQUEST_MAX_IMAGES = 8\n\n/** Text in a message made of parts. */\nexport interface AiTextPart {\n type: 'text'\n text: string\n}\n\n/**\n * A picture in a message (AGL-2916): its bytes, base64-encoded, and their\n * format. Only a USER turn carries one, and only to a model whose descriptor\n * says it reads images; the runtime refuses any other request before a byte\n * leaves the process, so a door cannot send a picture by accident to a model\n * that would reject it, or to a turn the model wrote.\n */\nexport interface AiImagePart {\n type: 'image'\n mediaType: AiImageMediaType\n /** The picture's bytes, base64-encoded, with no `data:` prefix. */\n data: string\n}\n\nexport type AiMessagePart = AiTextPart | AiImagePart\n\nexport interface AiMessage {\n role: 'user' | 'assistant'\n /**\n * The turn's text, or its parts in order — text and pictures — for a door\n * that shows the model an image. A door with nothing but text sends a\n * string, which every adapter passes through as it always has.\n */\n content: string | readonly AiMessagePart[]\n}\n\n/** A message's text: its parts' text joined, with every picture left out. */\nexport function aiMessageText(message: Pick<AiMessage, 'content'>): string {\n if (typeof message.content === 'string') return message.content\n return message.content\n .filter((part): part is AiTextPart => part.type === 'text')\n .map((part) => part.text)\n .join('\\n\\n')\n}\n\n/** Every picture a list of messages carries, in order. */\nexport function aiMessageImages(messages: readonly Pick<AiMessage, 'content'>[]): AiImagePart[] {\n return messages.flatMap((message) =>\n typeof message.content === 'string'\n ? []\n : message.content.filter((part): part is AiImagePart => part.type === 'image'),\n )\n}\n\n/** The decoded size of a base64 string, without decoding it. */\nexport function aiBase64Bytes(data: string): number {\n const padding = data.endsWith('==') ? 2 : data.endsWith('=') ? 1 : 0\n return Math.max(0, Math.floor((data.length * 3) / 4) - padding)\n}\n\n/** What every door hands the runtime; `provider` and `model` resolve there. */\nexport interface AiRequestBase {\n model: string\n system: AiSystemBlock[]\n messages: AiMessage[]\n tools?: AiTool[]\n maxTokens: number\n effort?: AiEffort\n thinking?: AiThinking\n signal?: AbortSignal\n}\n\n/** The request an adapter receives: the runtime has already validated it. */\nexport interface AiProviderRequest extends AiRequestBase {\n /** The provider's own key, resolved by the runtime from the environment or the org's setting. */\n apiKey: string\n}\n\n/**\n * Token usage in the meter's shape. Cache reads and writes are separate\n * because they are priced separately; a provider with no cache reports 0.\n */\nexport interface AiUsage {\n inputTokens: number\n outputTokens: number\n cacheReadTokens: number\n cacheWriteTokens: number\n /**\n * How many of `outputTokens` the model spent thinking, where the provider\n * reports it; absent where it does not (AGL-3143).\n *\n * Inside `outputTokens`, never beside it: a rate table prices the four\n * figures above and would charge these twice if it read this one.\n *\n * It is here because it is the figure that says where a generation's\n * output went. A tool call that comes back far smaller than the tokens it\n * cost has three shapes, and only this separates the first from the other\n * two: the model thought and then answered briefly, which is a model\n * working as asked; a runaway string the partial parse discarded; or\n * decoding that wrote nothing usable. Kept on every answer, because a\n * generation burns its budget thinking without ever reaching its ceiling,\n * and `rawOutput` is only there when it does.\n */\n thinkingTokens?: number\n}\n\nexport interface AiToolUse {\n name: string\n input: Record<string, unknown>\n}\n\n/** A completed, non-streaming answer. */\nexport interface AiCompletion {\n kind: 'completion'\n /** Every text block, joined. */\n text: string\n toolUse: AiToolUse[]\n usage: AiUsage\n /**\n * The exchange at the serving model's BILLED rates — what a customer's\n * credits are drawn from, and never a margin's cost side (AGL-3015). What\n * the same exchange cost us is `estimateAiProviderCostUsd`, recorded by\n * the meter; a result travels no further than the credit path, so it\n * carries the one figure that path needs.\n */\n estCostUsd: number\n stopReason: string | null\n /**\n * WHERE THE OUTPUT WENT (AGL-3143). The provider's own output for this\n * call, as it answered it, kept ONLY when the call stopped at its ceiling\n * and cut to `AI_RAW_OUTPUT_MAX_CHARS`.\n *\n * A tool call truncated mid-answer reaches `toolUse` as whatever the\n * provider could still parse, and the parsed input alone cannot say where\n * the tokens went: a runaway string the partial parse discarded and a\n * decoding stall that wrote nothing usable both leave a small input\n * against a spent ceiling. This is what tells them apart. These are the\n * model's own words, so they belong to the trace alone: never to a reader,\n * and never to a log, which carries the figures that separate the two\n * shapes — `outputTokens`, `parsedChars`, `rawChars`.\n */\n rawOutput?: string\n}\n\n/**\n * Whether a model call stopped because it reached the output ceiling it was\n * asked for (AGL-3042). `max_tokens` is the contract's word, and the\n * OpenAI-compatible adapter maps its endpoint's `length` onto it; `length` is\n * read as well, for an adapter that passes its provider's own word through.\n */\nexport function aiStoppedAtCeiling(stopReason: string | null): boolean {\n return stopReason === 'max_tokens' || stopReason === 'length'\n}\n\n/** The most characters of raw output a call cut off at its ceiling keeps. */\nexport const AI_RAW_OUTPUT_MAX_CHARS = 20_000\n\n/**\n * A cut-off call's output as the trace keeps it: what the provider answered,\n * serialized where it is not already text, and cut to the bound with an\n * ellipsis so a reader can tell a cut trace from a short answer.\n */\nexport function aiRawOutputOf(output: unknown): string {\n const text = typeof output === 'string' ? output : (JSON.stringify(output) ?? '')\n return text.length > AI_RAW_OUTPUT_MAX_CHARS ? `${text.slice(0, AI_RAW_OUTPUT_MAX_CHARS)}…` : text\n}\n\n/**\n * WHERE THE OUTPUT WENT, as a log may carry it (AGL-3143): the figures that\n * separate the shapes a call cut off at its ceiling comes in, and nothing\n * else.\n *\n * Thinking accounts for the spend first, because the thinking budget is\n * drawn from the same ceiling as the answer: a call can spend nearly all of\n * one thinking and still be cut off with a correct, tiny tool input, which\n * is a ceiling to raise rather than a decoder to fix. What thinking does not\n * account for is told apart by how much was written — long, and a runaway\n * string the partial parse discarded; short, and decoding wrote nothing\n * usable.\n *\n * It takes the raw output rather than a count on purpose. The bytes are the\n * model's own words and therefore the site's content, so they belong to the\n * trace alone and never to a log; passing them through one function that can\n * only ever return their LENGTH is what holds that rule at every door,\n * instead of asking each one to remember it.\n */\nexport function aiCutOffFigures(call: {\n usage: AiUsage\n /** The tool input that still parsed, or null where none did. */\n parsed: unknown\n rawOutput: string | null | undefined\n}): {\n outputTokens: number\n thinkingTokens: number | null\n parsedChars: number\n rawChars: number | null\n} {\n const parsed =\n call.parsed === null || call.parsed === undefined ? '' : (JSON.stringify(call.parsed) ?? '')\n return {\n outputTokens: call.usage.outputTokens,\n thinkingTokens: call.usage.thinkingTokens ?? null,\n parsedChars: parsed.length,\n rawChars: call.rawOutput?.length ?? null,\n }\n}\n\n/**\n * The model declined. Tokens were spent, so the usage is real and the\n * caller meters it; the text is whatever partial answer preceded the stop,\n * usually nothing. Every adapter maps its provider's own decline signal —\n * a refusal stop, a content filter — onto this one kind.\n */\nexport interface AiRefusal {\n kind: 'refusal'\n text: string\n usage: AiUsage\n estCostUsd: number\n stopReason: 'refusal'\n}\n\nexport type AiResult = AiCompletion | AiRefusal\n\nexport type AiStreamEvent =\n | { type: 'delta'; text: string }\n | { type: 'tool'; name: string; input: Record<string, unknown> }\n /**\n * The provider's in-stream error. The stream is still open and ends with\n * `done`, so the caller decides what the reader is told; the provider's\n * own words went to the log, not here.\n */\n | { type: 'error'; retryable: boolean }\n | {\n type: 'done'\n usage: AiUsage\n estCostUsd: number\n stopReason: string | null\n /**\n * WHERE THE OUTPUT WENT, for a stream (AGL-3143): the bytes the\n * stream's tool calls were written in, kept ONLY when the stream\n * stopped at its ceiling and cut to `AI_RAW_OUTPUT_MAX_CHARS`. The\n * streaming counterpart of `AiCompletion.rawOutput`.\n *\n * A `tool` event carries what `aiToolInputOf` could still parse, which\n * for a call cut mid-answer is a prefix of the object or nothing at\n * all; the fragments those events were assembled from are the only\n * record of what the model actually emitted, and without them a\n * runaway string and a decoding stall look identical from the\n * outside. These are the model's own words, so they belong to the\n * trace alone: never to a reader, and never to a log, which carries\n * the figures that separate the two shapes.\n */\n rawOutput?: string\n }\n\n/** What a provider says about one of its models; the catalog carries both rates. */\nexport interface AiModelDescriptor {\n id: string\n /** The provider id the model is served by. */\n provider: string\n label: string\n capabilities: {\n streaming: boolean\n tools: boolean\n /** Whether the provider accepts an explicit `thinking` setting for this model. */\n thinking: boolean\n /** Whether the provider caches a system prefix for this model. */\n promptCache: boolean\n /**\n * Whether the model reads a picture in a user turn (AGL-2916). Absent\n * reads as no, so a provider registered before the field existed is never\n * sent an image it did not say it can read.\n */\n vision?: boolean\n }\n}\n\n/** The one sentence a customer may read when a provider fails. */\nexport const AI_UPSTREAM_FAILURE_COPY = 'The AI request failed — try again.'\n\n/**\n * A non-2xx answer from the provider. `message` is the fixed customer-safe\n * sentence; the provider's payload is in the log under `requestId`.\n */\nexport class AiUpstreamError extends UpstreamServiceError {\n override readonly name = 'AiUpstreamError'\n /**\n * A failure about the PLATFORM's account with the provider rather than the\n * request (AGL-3377): the key was refused, or the account is out of\n * credit. Every AI feature on the install fails until the operator fixes\n * it, so the runtime tells them. Each adapter classifies its own vendor's\n * answers; absent is an ordinary failure.\n */\n readonly accountProblem: AiAccountProblem | null\n\n constructor(\n status: number | null,\n retryable: boolean,\n requestId: string | null,\n accountProblem: AiAccountProblem | null = null,\n ) {\n super(AI_UPSTREAM_FAILURE_COPY, { status, retryable, requestId })\n this.accountProblem = accountProblem\n }\n}\n\n/** See {@link AiUpstreamError.accountProblem}. */\nexport type AiAccountProblem = 'credentials' | 'credit'\n\n/**\n * A request the runtime refuses to send. Thrown synchronously before any\n * network is touched, and it names the block at fault: this is a\n * programming error in the caller's prompt assembly, not a condition to\n * handle at runtime.\n */\nexport class AiRequestShapeError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'AiRequestShapeError'\n }\n}\n\n/**\n * A provider: one vendor's wire protocol behind the contract. `id` is the\n * routing key (`anthropic`, `openai-compatible`); `models` is what the\n * provider can serve; `complete` and `stream` are the two shapes every door\n * uses. An adapter maps its vendor's errors onto `AiUpstreamError` and its\n * declines onto `AiRefusal`, and reports usage in the meter's shape.\n */\nexport interface AiProvider {\n readonly id: string\n readonly label: string\n /** The environment variable that carries this provider's key, for operator messages. */\n readonly apiKeyEnv: string\n /**\n * The key from the server environment, or `undefined` when the provider\n * is not configured to answer. Each adapter reads its own variable by\n * name in its own module, so every key read is one the key-exposure\n * guard can see (AGL-2240) and no door names a vendor's variable.\n */\n readApiKey(): string | undefined\n /** The host the provider is reached at, for the subprocessor inventory. */\n readonly endpointHost: string\n /**\n * How much of one request's strict tools this provider compiles, where it\n * states a bound. The doors never read it: a spec holds every tool set a\n * door sends to every registered provider's limits, so a schema a provider\n * would refuse is red before it ships rather than a 400 on every request.\n */\n readonly toolSchemaLimits?: AiToolSchemaLimits\n models(): readonly AiModelDescriptor[]\n complete(request: AiProviderRequest): Promise<AiResult>\n /**\n * Resolves once the provider has ACCEPTED the request — after the\n * headers, before the first token — with an iterator of events. A non-2xx\n * answer rejects with `AiUpstreamError` before the iterator exists, so a\n * door can still send a plain error status and hand back its reservation.\n */\n stream(request: AiProviderRequest): Promise<AsyncIterable<AiStreamEvent>>\n}\n\n/** A count off the wire: finite, non-negative, whole; anything else is 0. */\nexport function aiTokenCount(value: unknown): number {\n const parsed = Number(value ?? 0)\n return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : 0\n}\n\n/**\n * A tool call's `input` as an object. A provider sends an object or, for\n * the one shape a stream assembles by hand, a JSON string.\n *\n * A string that does not parse to an object is an EMPTY input, not a throw.\n * The case that produces one is a stream cut off mid-call by the output\n * ceiling, and a throw there would end the stream before its `done` event —\n * the event that carries the usage a door must meter for tokens already\n * spent. An empty input is one every door's own validation refuses.\n */\nexport function aiToolInputOf(value: unknown): Record<string, unknown> {\n if (typeof value === 'string') {\n if (!value.trim()) return {}\n try {\n const parsed: unknown = JSON.parse(value)\n return parsed && typeof parsed === 'object' && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : {}\n } catch {\n return {}\n }\n }\n return value && typeof value === 'object' ? (value as Record<string, unknown>) : {}\n}\n"],"names":["UpstreamServiceError","compiledForm","node","root","resolving","Array","isArray","map","entry","isSchemaObject","ref","has","$ref","localSchemaAt","Set","written","key","value","Object","entries","aiToolSchemaCompiledBytes","tools","reduce","bytes","tool","JSON","stringify","inputSchema","length","startsWith","undefined","slice","split","replace","countSchema","counts","unionParameters","properties","required","property","includes","optionalParameters","items","item","branches","branch","aiToolSchemaCounts","strictTools","compiledSchemaBytes","TOOL_SCHEMA_MEASURES","aiToolSchemaBreaches","limits","flatMap","measure","one","many","source","limit","count","AI_IMAGE_MEDIA_TYPES","AI_IMAGE_MAX_BYTES","AI_REQUEST_MAX_IMAGES","aiMessageText","message","content","filter","part","type","text","join","aiMessageImages","messages","aiBase64Bytes","data","padding","endsWith","Math","max","floor","aiStoppedAtCeiling","stopReason","AI_RAW_OUTPUT_MAX_CHARS","aiRawOutputOf","output","aiCutOffFigures","call","parsed","outputTokens","usage","thinkingTokens","parsedChars","rawChars","rawOutput","AI_UPSTREAM_FAILURE_COPY","AiUpstreamError","status","retryable","requestId","accountProblem","name","AiRequestShapeError","Error","aiTokenCount","Number","isFinite","aiToolInputOf","trim","parse"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,oBAAoB,QAAQ,4BAA2B;AAmHhE;;;;;CAKC,GACD,SAASC,aAAaC,IAAa,EAAEC,IAA6B,EAAEC,SAA8B;IAChG,IAAIC,MAAMC,OAAO,CAACJ,OAAO,OAAOA,KAAKK,GAAG,CAAC,CAACC,QAAUP,aAAaO,OAAOL,MAAMC;IAC9E,IAAI,CAACK,eAAeP,OAAO,OAAOA;IAClC,MAAMQ,MAAMR,IAAI,CAAC,OAAO;IACxB,IAAI,OAAOQ,QAAQ,UAAU;QAC3B,IAAIN,UAAUO,GAAG,CAACD,MAAM,OAAO;YAAEE,MAAMF;QAAI;QAC3C,OAAOT,aAAaY,cAAcV,MAAMO,MAAMP,MAAM,IAAIW,IAAI;eAAIV;YAAWM;SAAI;IACjF;IACA,MAAMK,UAAmC,CAAC;IAC1C,KAAK,MAAM,CAACC,KAAKC,MAAM,IAAIC,OAAOC,OAAO,CAACjB,MAAO;QAC/C,IAAIc,QAAQ,iBAAiBA,QAAQ,WAAWA,QAAQ,SAAS;QACjED,OAAO,CAACC,IAAI,GAAGf,aAAagB,OAAOd,MAAMC;IAC3C;IACA,OAAOW;AACT;AAEA;;;;;;CAMC,GACD,OAAO,SAASK,0BAA0BC,KAAwB;IAChE,OAAOA,MAAMC,MAAM,CACjB,CAACC,OAAOC,OAASD,QAAQE,KAAKC,SAAS,CAACzB,aAAauB,KAAKG,WAAW,EAAEH,KAAKG,WAAW,EAAE,IAAIb,QAAQc,MAAM,EAC3G;AAEJ;AAEA,SAASnB,eAAeQ,KAAc;IACpC,OAAO,OAAOA,UAAU,YAAYA,UAAU,QAAQ,CAACZ,MAAMC,OAAO,CA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AAU;AACtE;AAEA;;;;;;;;;CASC,GACD,OAAO,SAASmB,cAAcxF,KAAc;IAC1C,IAAI,OAAOA,UAAU,UAAU;QAC7B,IAAI,CAACA,MAAMyF,IAAI,IAAI,OAAO,CAAC;QAC3B,IAAI;YACF,MAAMpB,SAAkB7D,KAAKkF,KAAK,CAAC1F;YACnC,OAAOqE,UAAU,OAAOA,WAAW,YAAY,CAACjF,MAAMC,OAAO,CAACgF,UACzDA,SACD,CAAC;QACP,EAAE,eAAM;YACN,OAAO,CAAC;QACV;IACF;IACA,OAAOrE,SAAS,OAAOA,UAAU,WAAYA,QAAoC,CAAC;AACpF"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/providers/contract.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 { UpstreamServiceError } from '@aglyn/shared-util-errors'\n\n/**\n * The provider contract (AGL-2939): the one shape every AI door speaks, and\n * the one thing an adapter has to implement. The runtime, the gate, the\n * jobs, the doctrine and the usage code import this and never a vendor\n * URL, header or model literal — Anthropic is one adapter behind it, and\n * an OpenAI-compatible endpoint is the second, which is what proves the\n * seam holds.\n *\n * ── Prompt caching, by construction ───────────────────────────────────────\n *\n * `system` is an ordered list of blocks, and caching is a PREFIX match: a\n * breakpoint covers every block before it, and one byte that differs per\n * request anywhere inside that prefix gives every distinct value its own\n * copy of it. The AGL-2352 rule is that no per-org byte may sit inside a\n * cached prefix — a white-label brand name interpolated into a cached block\n * multiplies the prefix count by the number of brands, each written off its\n * own traffic and expired before it is read. So a block marked `volatile`\n * may not sit at or before the last `cacheBreakpoint`, and the runtime\n * refuses the request before a byte leaves the process. A provider with no\n * cache honors the order and ignores the markers.\n *\n * ── Structured output ─────────────────────────────────────────────────────\n *\n * A `tools` entry is sent strict, with additional properties forbidden on\n * its schema, so a tool call's `input` validates against the schema\n * exactly. Tool choice stays automatic — forced tool use is not portable\n * across models — and the caller's system text names the tool it wants. An\n * adapter delivers `input` as an object; a stream assembles it from\n * fragments and parses the whole once, at the block's end. Nothing\n * string-matches the serialized form: models differ in how they escape it.\n * A provider bounds how much strict schema one request may carry, and an\n * adapter declares those bounds as `toolSchemaLimits`: three bounds a vendor\n * publishes and counts, and a fourth, the size of the grammar the schemas\n * compile to, that none publishes and only a live request settles.\n *\n * ── Thinking ──────────────────────────────────────────────────────────────\n *\n * `thinking: 'off'` and `'adaptive'` are sent when the provider has the\n * control; an omitted field sends NOTHING, leaving the model's own default\n * in force. The omission is deliberate rather than a gap: some models\n * reject an explicit setting, and the copy assistant serves its element\n * mode on such a model. `effort` rides the same rule.\n *\n * ── Pictures ──────────────────────────────────────────────────────────────\n *\n * A user turn may carry pictures beside its text (AGL-2916): `content` is\n * then an ordered list of parts, and a turn with nothing but text stays a\n * string, which every adapter passes through as it always has. A picture is\n * base64 bytes of one of `AI_IMAGE_MEDIA_TYPES`, never a URL, so no provider\n * fetches anything on the platform's behalf. The runtime refuses a picture\n * on an assistant turn, a picture for a model whose descriptor does not say\n * `vision`, and a picture past the size or count bounds, all before any\n * network is touched. Each adapter maps the parts onto its vendor's shape.\n */\n\n/**\n * One system block. `cacheBreakpoint` marks the end of a cacheable prefix;\n * `volatile` declares that the text carries a per-request or per-org byte\n * and therefore may never sit inside one.\n *\n * `site` declares a block that describes ONE site (AGL-3661): its business\n * profile, status and remembered preferences. As a breakpoint it is cached\n * once per site, so it must close the cached span — every platform-wide\n * block sits ahead of it, where every workspace still shares one entry —\n * and the runtime refuses a request that puts another breakpoint after it.\n */\nexport interface AiSystemBlock {\n text: string\n cacheBreakpoint?: true\n volatile?: true\n site?: true\n}\n\n/** A structured-output tool. `strict` is required, not optional. */\nexport interface AiTool {\n name: string\n description: string\n /** A JSON schema of `type: 'object'`; `additionalProperties` is forced off. */\n inputSchema: Record<string, unknown>\n strict: true\n}\n\n/**\n * How much of a request's strict tools a provider can compile (AGL-3096). A\n * provider that constrains decoding to a tool's schema compiles every strict\n * schema of a request together, before the model runs, and refuses a request\n * whose schemas are past its bounds. That refusal is permanent: the schema is\n * the same on every retry. Each bound is a TOTAL over every strict tool one\n * request sends, as `aiToolSchemaCounts` counts them. A bound left out is one\n * the provider does not state.\n *\n * A provider may also refuse a request whose schemas compile to too large a\n * grammar, which none of the published counts can see: a request counting 1\n * strict tool, 0 optional parameters and 1 union was refused for exactly that\n * (AGL-3096). `compiledSchemaBytes` stands in for it, on live evidence.\n */\nexport interface AiToolSchemaLimits {\n /** The most strict tools one request may send. */\n strictTools?: number\n /** The most properties, across every strict schema, left out of their object's `required`. */\n optionalParameters?: number\n /** The most schemas, across every strict schema, that are a union: an `anyOf` or `oneOf`, or a list of types. */\n unionParameters?: number\n /**\n * The most bytes of schema a request's grammar may be compiled from, as\n * `aiToolSchemaCompiledBytes` measures them.\n *\n * Unlike the bounds above, this one is EMPIRICAL. A provider refuses a\n * request whose compiled grammar is too large without publishing the size,\n * so the number here is not read off a vendor's page: it is the largest a\n * live request has been watched to carry, and every number above it is\n * unknown rather than safe. Raising it on an offline measurement alone\n * puts the guard back where it could not see the break.\n */\n compiledSchemaBytes?: number\n}\n\n/** A request's strict tools, counted on the measures `AiToolSchemaLimits` bounds. */\nexport type AiToolSchemaCounts = Required<AiToolSchemaLimits>\n\n/**\n * One schema as a grammar compiler reads it: every local `$ref` written out\n * at each place it is used, and every description, title and `$defs` dropped,\n * since none of them constrains a single token. A schema that refers to\n * itself is written out once around and then left as the reference it is.\n */\nfunction compiledForm(node: unknown, root: Record<string, unknown>, resolving: ReadonlySet<string>): unknown {\n if (Array.isArray(node)) return node.map((entry) => compiledForm(entry, root, resolving))\n if (!isSchemaObject(node)) return node\n const ref = node['$ref']\n if (typeof ref === 'string') {\n if (resolving.has(ref)) return { $ref: ref }\n return compiledForm(localSchemaAt(root, ref), root, new Set([...resolving, ref]))\n }\n const written: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(node)) {\n if (key === 'description' || key === 'title' || key === '$defs') continue\n written[key] = compiledForm(value, root, resolving)\n }\n return written\n}\n\n/**\n * The bytes of schema a request's grammar is compiled from, over all its\n * strict tools. It is a stand-in for the size of the grammar itself, which\n * nothing outside the provider can measure, and it errs toward more: a `$ref`\n * counts at each place it is used, because a compiler that writes it out\n * there pays for it there.\n */\nexport function aiToolSchemaCompiledBytes(tools: readonly AiTool[]): number {\n return tools.reduce(\n (bytes, tool) => bytes + JSON.stringify(compiledForm(tool.inputSchema, tool.inputSchema, new Set())).length,\n 0,\n )\n}\n\nfunction isSchemaObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/** The schema a local `$ref` (`#/…`) points at, or `undefined`. */\nfunction localSchemaAt(root: Record<string, unknown>, ref: string): unknown {\n if (!ref.startsWith('#/')) return undefined\n return ref\n .slice(2)\n .split('/')\n .map((key) => key.replace(/~1/g, '/').replace(/~0/g, '~'))\n .reduce<unknown>((node, key) => (isSchemaObject(node) ? node[key] : undefined), root)\n}\n\nfunction countSchema(\n node: unknown,\n root: Record<string, unknown>,\n counts: AiToolSchemaCounts,\n resolving: ReadonlySet<string>,\n): void {\n if (!isSchemaObject(node)) return\n if (Array.isArray(node['anyOf']) || Array.isArray(node['oneOf']) || Array.isArray(node['type'])) {\n counts.unionParameters += 1\n }\n const ref = node['$ref']\n if (typeof ref === 'string' && !resolving.has(ref)) {\n countSchema(localSchemaAt(root, ref), root, counts, new Set([...resolving, ref]))\n }\n const properties = node['properties']\n if (isSchemaObject(properties)) {\n const required = Array.isArray(node['required']) ? node['required'] : []\n for (const [key, property] of Object.entries(properties)) {\n if (!required.includes(key)) counts.optionalParameters += 1\n countSchema(property, root, counts, resolving)\n }\n }\n const items = node['items']\n for (const item of Array.isArray(items) ? items : [items]) countSchema(item, root, counts, resolving)\n for (const key of ['anyOf', 'allOf', 'oneOf']) {\n const branches = node[key]\n if (Array.isArray(branches)) for (const branch of branches) countSchema(branch, root, counts, resolving)\n }\n}\n\n/**\n * The strict tools of one request, counted on each measure a provider bounds.\n * Every tool the contract sends is strict. Each schema is walked whole: every\n * property, every `items`, every branch of an `anyOf`, `allOf` or `oneOf`, and\n * a local `$ref` at each place it is used. A union nested in an array's items\n * or in another union's branch counts on its own, as it does for a provider\n * that compiles it; a `$ref` counted where it is used errs toward more.\n */\nexport function aiToolSchemaCounts(tools: readonly AiTool[]): AiToolSchemaCounts {\n const counts: AiToolSchemaCounts = {\n strictTools: tools.length,\n optionalParameters: 0,\n unionParameters: 0,\n compiledSchemaBytes: aiToolSchemaCompiledBytes(tools),\n }\n for (const tool of tools) countSchema(tool.inputSchema, tool.inputSchema, counts, new Set())\n return counts\n}\n\n/**\n * Each bound, as one, as many, and where its number comes from — a published\n * bound reads as the provider's own, a measured one as what has been proved.\n */\nconst TOOL_SCHEMA_MEASURES: ReadonlyArray<[keyof AiToolSchemaLimits, string, string, string]> = [\n ['strictTools', 'strict tool', 'strict tools', 'the provider compiles'],\n ['optionalParameters', 'optional parameter', 'optional parameters', 'the provider compiles'],\n ['unionParameters', 'union-typed parameter', 'union-typed parameters', 'the provider compiles'],\n ['compiledSchemaBytes', 'byte of compiled schema', 'bytes of compiled schema', 'a live request has proved'],\n]\n\n/** Each bound a request's tools are past, as a sentence; empty when every one holds. */\nexport function aiToolSchemaBreaches(\n tools: readonly AiTool[],\n limits: AiToolSchemaLimits | undefined,\n): string[] {\n if (!limits) return []\n const counts = aiToolSchemaCounts(tools)\n return TOOL_SCHEMA_MEASURES.flatMap(([measure, one, many, source]) => {\n const limit = limits[measure]\n const count = counts[measure]\n return limit !== undefined && count > limit\n ? [`${count} ${count === 1 ? one : many} in one request, over the ${limit} ${source}`]\n : []\n })\n}\n\nexport type AiEffort = 'low' | 'medium' | 'high'\nexport type AiThinking = 'off' | 'adaptive'\n\n/**\n * The picture formats a request may carry (AGL-2916): the four every model\n * the catalog marks as reading images accepts. A door converts anything else\n * — an AVIF, an SVG — before it attaches the picture, or attaches none.\n */\nexport const AI_IMAGE_MEDIA_TYPES = ['image/jpeg', 'image/png', 'image/webp', 'image/gif'] as const\nexport type AiImageMediaType = (typeof AI_IMAGE_MEDIA_TYPES)[number]\n\n/**\n * The largest picture one part may carry, in decoded bytes: the ceiling the\n * providers behind the contract accept for one image. A door that attaches a\n * picture resizes it far below this; the runtime refuses anything above it\n * before a byte leaves the process, rather than letting the provider do it\n * after the request was paid for in time.\n */\nexport const AI_IMAGE_MAX_BYTES = 5 * 1024 * 1024\n\n/** The most pictures one request may carry. */\nexport const AI_REQUEST_MAX_IMAGES = 8\n\n/** Text in a message made of parts. */\nexport interface AiTextPart {\n type: 'text'\n text: string\n}\n\n/**\n * A picture in a message (AGL-2916): its bytes, base64-encoded, and their\n * format. Only a USER turn carries one, and only to a model whose descriptor\n * says it reads images; the runtime refuses any other request before a byte\n * leaves the process, so a door cannot send a picture by accident to a model\n * that would reject it, or to a turn the model wrote.\n */\nexport interface AiImagePart {\n type: 'image'\n mediaType: AiImageMediaType\n /** The picture's bytes, base64-encoded, with no `data:` prefix. */\n data: string\n}\n\nexport type AiMessagePart = AiTextPart | AiImagePart\n\nexport interface AiMessage {\n role: 'user' | 'assistant'\n /**\n * The turn's text, or its parts in order — text and pictures — for a door\n * that shows the model an image. A door with nothing but text sends a\n * string, which every adapter passes through as it always has.\n */\n content: string | readonly AiMessagePart[]\n}\n\n/** A message's text: its parts' text joined, with every picture left out. */\nexport function aiMessageText(message: Pick<AiMessage, 'content'>): string {\n if (typeof message.content === 'string') return message.content\n return message.content\n .filter((part): part is AiTextPart => part.type === 'text')\n .map((part) => part.text)\n .join('\\n\\n')\n}\n\n/** Every picture a list of messages carries, in order. */\nexport function aiMessageImages(messages: readonly Pick<AiMessage, 'content'>[]): AiImagePart[] {\n return messages.flatMap((message) =>\n typeof message.content === 'string'\n ? []\n : message.content.filter((part): part is AiImagePart => part.type === 'image'),\n )\n}\n\n/** The decoded size of a base64 string, without decoding it. */\nexport function aiBase64Bytes(data: string): number {\n const padding = data.endsWith('==') ? 2 : data.endsWith('=') ? 1 : 0\n return Math.max(0, Math.floor((data.length * 3) / 4) - padding)\n}\n\n/** What every door hands the runtime; `provider` and `model` resolve there. */\nexport interface AiRequestBase {\n model: string\n system: AiSystemBlock[]\n messages: AiMessage[]\n tools?: AiTool[]\n maxTokens: number\n effort?: AiEffort\n thinking?: AiThinking\n signal?: AbortSignal\n /**\n * How long a cache entry the breakpoints write should live, where the\n * provider offers a choice: the provider's default (five minutes on the\n * Messages API) when absent. Only a development run asks for `1h`\n * (`runtime/ai-dev-replay.ts`); it changes no answer, only what a second\n * request within the hour pays for the prefix.\n */\n cacheTtl?: '1h'\n}\n\n/** The request an adapter receives: the runtime has already validated it. */\nexport interface AiProviderRequest extends AiRequestBase {\n /** The provider's own key, resolved by the runtime from the environment or the org's setting. */\n apiKey: string\n}\n\n/**\n * Token usage in the meter's shape. Cache reads and writes are separate\n * because they are priced separately; a provider with no cache reports 0.\n */\nexport interface AiUsage {\n inputTokens: number\n outputTokens: number\n cacheReadTokens: number\n cacheWriteTokens: number\n /**\n * How many of `outputTokens` the model spent thinking, where the provider\n * reports it; absent where it does not (AGL-3143).\n *\n * Inside `outputTokens`, never beside it: a rate table prices the four\n * figures above and would charge these twice if it read this one.\n *\n * It is here because it is the figure that says where a generation's\n * output went. A tool call that comes back far smaller than the tokens it\n * cost has three shapes, and only this separates the first from the other\n * two: the model thought and then answered briefly, which is a model\n * working as asked; a runaway string the partial parse discarded; or\n * decoding that wrote nothing usable. Kept on every answer, because a\n * generation burns its budget thinking without ever reaching its ceiling,\n * and `rawOutput` is only there when it does.\n */\n thinkingTokens?: number\n}\n\nexport interface AiToolUse {\n name: string\n input: Record<string, unknown>\n}\n\n/** A completed, non-streaming answer. */\nexport interface AiCompletion {\n kind: 'completion'\n /** Every text block, joined. */\n text: string\n toolUse: AiToolUse[]\n usage: AiUsage\n /**\n * The exchange at the serving model's BILLED rates — what a customer's\n * credits are drawn from, and never a margin's cost side (AGL-3015). What\n * the same exchange cost us is `estimateAiProviderCostUsd`, recorded by\n * the meter; a result travels no further than the credit path, so it\n * carries the one figure that path needs.\n */\n estCostUsd: number\n stopReason: string | null\n /**\n * WHERE THE OUTPUT WENT (AGL-3143). The provider's own output for this\n * call, as it answered it, kept ONLY when the call stopped at its ceiling\n * and cut to `AI_RAW_OUTPUT_MAX_CHARS`.\n *\n * A tool call truncated mid-answer reaches `toolUse` as whatever the\n * provider could still parse, and the parsed input alone cannot say where\n * the tokens went: a runaway string the partial parse discarded and a\n * decoding stall that wrote nothing usable both leave a small input\n * against a spent ceiling. This is what tells them apart. These are the\n * model's own words, so they belong to the trace alone: never to a reader,\n * and never to a log, which carries the figures that separate the two\n * shapes — `outputTokens`, `parsedChars`, `rawChars`.\n */\n rawOutput?: string\n}\n\n/**\n * Whether a model call stopped because it reached the output ceiling it was\n * asked for (AGL-3042). `max_tokens` is the contract's word, and the\n * OpenAI-compatible adapter maps its endpoint's `length` onto it; `length` is\n * read as well, for an adapter that passes its provider's own word through.\n */\nexport function aiStoppedAtCeiling(stopReason: string | null): boolean {\n return stopReason === 'max_tokens' || stopReason === 'length'\n}\n\n/** The most characters of raw output a call cut off at its ceiling keeps. */\nexport const AI_RAW_OUTPUT_MAX_CHARS = 20_000\n\n/**\n * A cut-off call's output as the trace keeps it: what the provider answered,\n * serialized where it is not already text, and cut to the bound with an\n * ellipsis so a reader can tell a cut trace from a short answer.\n */\nexport function aiRawOutputOf(output: unknown): string {\n const text = typeof output === 'string' ? output : (JSON.stringify(output) ?? '')\n return text.length > AI_RAW_OUTPUT_MAX_CHARS ? `${text.slice(0, AI_RAW_OUTPUT_MAX_CHARS)}…` : text\n}\n\n/**\n * WHERE THE OUTPUT WENT, as a log may carry it (AGL-3143): the figures that\n * separate the shapes a call cut off at its ceiling comes in, and nothing\n * else.\n *\n * Thinking accounts for the spend first, because the thinking budget is\n * drawn from the same ceiling as the answer: a call can spend nearly all of\n * one thinking and still be cut off with a correct, tiny tool input, which\n * is a ceiling to raise rather than a decoder to fix. What thinking does not\n * account for is told apart by how much was written — long, and a runaway\n * string the partial parse discarded; short, and decoding wrote nothing\n * usable.\n *\n * It takes the raw output rather than a count on purpose. The bytes are the\n * model's own words and therefore the site's content, so they belong to the\n * trace alone and never to a log; passing them through one function that can\n * only ever return their LENGTH is what holds that rule at every door,\n * instead of asking each one to remember it.\n */\nexport function aiCutOffFigures(call: {\n usage: AiUsage\n /** The tool input that still parsed, or null where none did. */\n parsed: unknown\n rawOutput: string | null | undefined\n}): {\n outputTokens: number\n thinkingTokens: number | null\n parsedChars: number\n rawChars: number | null\n} {\n const parsed =\n call.parsed === null || call.parsed === undefined ? '' : (JSON.stringify(call.parsed) ?? '')\n return {\n outputTokens: call.usage.outputTokens,\n thinkingTokens: call.usage.thinkingTokens ?? null,\n parsedChars: parsed.length,\n rawChars: call.rawOutput?.length ?? null,\n }\n}\n\n/**\n * The model declined. Tokens were spent, so the usage is real and the\n * caller meters it; the text is whatever partial answer preceded the stop,\n * usually nothing. Every adapter maps its provider's own decline signal —\n * a refusal stop, a content filter — onto this one kind.\n */\nexport interface AiRefusal {\n kind: 'refusal'\n text: string\n usage: AiUsage\n estCostUsd: number\n stopReason: 'refusal'\n}\n\nexport type AiResult = AiCompletion | AiRefusal\n\nexport type AiStreamEvent =\n | { type: 'delta'; text: string }\n | { type: 'tool'; name: string; input: Record<string, unknown> }\n /**\n * The provider's in-stream error. The stream is still open and ends with\n * `done`, so the caller decides what the reader is told; the provider's\n * own words went to the log, not here.\n */\n | { type: 'error'; retryable: boolean }\n | {\n type: 'done'\n usage: AiUsage\n estCostUsd: number\n stopReason: string | null\n /**\n * WHERE THE OUTPUT WENT, for a stream (AGL-3143): the bytes the\n * stream's tool calls were written in, kept ONLY when the stream\n * stopped at its ceiling and cut to `AI_RAW_OUTPUT_MAX_CHARS`. The\n * streaming counterpart of `AiCompletion.rawOutput`.\n *\n * A `tool` event carries what `aiToolInputOf` could still parse, which\n * for a call cut mid-answer is a prefix of the object or nothing at\n * all; the fragments those events were assembled from are the only\n * record of what the model actually emitted, and without them a\n * runaway string and a decoding stall look identical from the\n * outside. These are the model's own words, so they belong to the\n * trace alone: never to a reader, and never to a log, which carries\n * the figures that separate the two shapes.\n */\n rawOutput?: string\n }\n\n/** What a provider says about one of its models; the catalog carries both rates. */\nexport interface AiModelDescriptor {\n id: string\n /** The provider id the model is served by. */\n provider: string\n label: string\n capabilities: {\n streaming: boolean\n tools: boolean\n /** Whether the provider accepts an explicit `thinking` setting for this model. */\n thinking: boolean\n /** Whether the provider caches a system prefix for this model. */\n promptCache: boolean\n /**\n * Whether the model reads a picture in a user turn (AGL-2916). Absent\n * reads as no, so a provider registered before the field existed is never\n * sent an image it did not say it can read.\n */\n vision?: boolean\n }\n}\n\n/** The one sentence a customer may read when a provider fails. */\nexport const AI_UPSTREAM_FAILURE_COPY = 'The AI request failed — try again.'\n\n/**\n * A non-2xx answer from the provider. `message` is the fixed customer-safe\n * sentence; the provider's payload is in the log under `requestId`.\n */\nexport class AiUpstreamError extends UpstreamServiceError {\n override readonly name = 'AiUpstreamError'\n /**\n * A failure about the PLATFORM's account with the provider rather than the\n * request (AGL-3377): the key was refused, or the account is out of\n * credit. Every AI feature on the install fails until the operator fixes\n * it, so the runtime tells them. Each adapter classifies its own vendor's\n * answers; absent is an ordinary failure.\n */\n readonly accountProblem: AiAccountProblem | null\n\n constructor(\n status: number | null,\n retryable: boolean,\n requestId: string | null,\n accountProblem: AiAccountProblem | null = null,\n ) {\n super(AI_UPSTREAM_FAILURE_COPY, { status, retryable, requestId })\n this.accountProblem = accountProblem\n }\n}\n\n/** See {@link AiUpstreamError.accountProblem}. */\nexport type AiAccountProblem = 'credentials' | 'credit'\n\n/**\n * A request the runtime refuses to send. Thrown synchronously before any\n * network is touched, and it names the block at fault: this is a\n * programming error in the caller's prompt assembly, not a condition to\n * handle at runtime.\n */\nexport class AiRequestShapeError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'AiRequestShapeError'\n }\n}\n\n/**\n * A provider: one vendor's wire protocol behind the contract. `id` is the\n * routing key (`anthropic`, `openai-compatible`); `models` is what the\n * provider can serve; `complete` and `stream` are the two shapes every door\n * uses. An adapter maps its vendor's errors onto `AiUpstreamError` and its\n * declines onto `AiRefusal`, and reports usage in the meter's shape.\n */\nexport interface AiProvider {\n readonly id: string\n readonly label: string\n /** The environment variable that carries this provider's key, for operator messages. */\n readonly apiKeyEnv: string\n /**\n * The key from the server environment, or `undefined` when the provider\n * is not configured to answer. Each adapter reads its own variable by\n * name in its own module, so every key read is one the key-exposure\n * guard can see (AGL-2240) and no door names a vendor's variable.\n */\n readApiKey(): string | undefined\n /** The host the provider is reached at, for the subprocessor inventory. */\n readonly endpointHost: string\n /**\n * How much of one request's strict tools this provider compiles, where it\n * states a bound. The doors never read it: a spec holds every tool set a\n * door sends to every registered provider's limits, so a schema a provider\n * would refuse is red before it ships rather than a 400 on every request.\n */\n readonly toolSchemaLimits?: AiToolSchemaLimits\n models(): readonly AiModelDescriptor[]\n complete(request: AiProviderRequest): Promise<AiResult>\n /**\n * Resolves once the provider has ACCEPTED the request — after the\n * headers, before the first token — with an iterator of events. A non-2xx\n * answer rejects with `AiUpstreamError` before the iterator exists, so a\n * door can still send a plain error status and hand back its reservation.\n */\n stream(request: AiProviderRequest): Promise<AsyncIterable<AiStreamEvent>>\n /**\n * Many requests answered together, asynchronously, at the provider's batch\n * discount, where it has one: each entry is that request's result, or the\n * error it failed with, in the order asked. Only a development run's live\n * eval calls it (`runtime/ai-live-batch.ts`); no door does.\n */\n completeBatch?(requests: readonly AiProviderRequest[], options?: AiBatchOptions): Promise<Array<AiResult | Error>>\n}\n\n/** How a batch is waited on. */\nexport interface AiBatchOptions {\n /** Between two looks at a batch still processing; 10 s when absent. */\n pollMs?: number\n /** The most a batch is waited for before every request in it fails; an hour when absent. */\n timeoutMs?: number\n}\n\n/** A count off the wire: finite, non-negative, whole; anything else is 0. */\nexport function aiTokenCount(value: unknown): number {\n const parsed = Number(value ?? 0)\n return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : 0\n}\n\n/**\n * A tool call's `input` as an object. A provider sends an object or, for\n * the one shape a stream assembles by hand, a JSON string.\n *\n * A string that does not parse to an object is an EMPTY input, not a throw.\n * The case that produces one is a stream cut off mid-call by the output\n * ceiling, and a throw there would end the stream before its `done` event —\n * the event that carries the usage a door must meter for tokens already\n * spent. An empty input is one every door's own validation refuses.\n */\nexport function aiToolInputOf(value: unknown): Record<string, unknown> {\n if (typeof value === 'string') {\n if (!value.trim()) return {}\n try {\n const parsed: unknown = JSON.parse(value)\n return parsed && typeof parsed === 'object' && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : {}\n } catch {\n return {}\n }\n }\n return value && typeof value === 'object' ? (value as Record<string, unknown>) : {}\n}\n"],"names":["UpstreamServiceError","compiledForm","node","root","resolving","Array","isArray","map","entry","isSchemaObject","ref","has","$ref","localSchemaAt","Set","written","key","value","Object","entries","aiToolSchemaCompiledBytes","tools","reduce","bytes","tool","JSON","stringify","inputSchema","length","startsWith","undefined","slice","split","replace","countSchema","counts","unionParameters","properties","required","property","includes","optionalParameters","items","item","branches","branch","aiToolSchemaCounts","strictTools","compiledSchemaBytes","TOOL_SCHEMA_MEASURES","aiToolSchemaBreaches","limits","flatMap","measure","one","many","source","limit","count","AI_IMAGE_MEDIA_TYPES","AI_IMAGE_MAX_BYTES","AI_REQUEST_MAX_IMAGES","aiMessageText","message","content","filter","part","type","text","join","aiMessageImages","messages","aiBase64Bytes","data","padding","endsWith","Math","max","floor","aiStoppedAtCeiling","stopReason","AI_RAW_OUTPUT_MAX_CHARS","aiRawOutputOf","output","aiCutOffFigures","call","parsed","outputTokens","usage","thinkingTokens","parsedChars","rawChars","rawOutput","AI_UPSTREAM_FAILURE_COPY","AiUpstreamError","status","retryable","requestId","accountProblem","name","AiRequestShapeError","Error","aiTokenCount","Number","isFinite","aiToolInputOf","trim","parse"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,oBAAoB,QAAQ,4BAA2B;AA0HhE;;;;;CAKC,GACD,SAASC,aAAaC,IAAa,EAAEC,IAA6B,EAAEC,SAA8B;IAChG,IAAIC,MAAMC,OAAO,CAACJ,OAAO,OAAOA,KAAKK,GAAG,CAAC,CAACC,QAAUP,aAAaO,OAAOL,MAAMC;IAC9E,IAAI,CAACK,eAAeP,OAAO,OAAOA;IAClC,MAAMQ,MAAMR,IAAI,CAAC,OAAO;IACxB,IAAI,OAAOQ,QAAQ,UAAU;QAC3B,IAAIN,UAAUO,GAAG,CAACD,MAAM,OAAO;YAAEE,MAAMF;QAAI;QAC3C,OAAOT,aAAaY,cAAcV,MAAMO,MAAMP,MAAM,IAAIW,IAAI;eAAIV;YAAWM;SAAI;IACjF;IACA,MAAMK,UAAmC,CAAC;IAC1C,KAAK,MAAM,CAACC,KAAKC,MAAM,IAAIC,OAAOC,OAAO,CAACjB,MAAO;QAC/C,IAAIc,QAAQ,iBAAiBA,QAAQ,WAAWA,QAAQ,SAAS;QACjED,OAAO,CAACC,IAAI,GAAGf,aAAagB,OAAOd,MAAMC;IAC3C;IACA,OAAOW;AACT;AAEA;;;;;;CAMC,GACD,OAAO,SAASK,0BAA0BC,KAAwB;IAChE,OAAOA,MAAMC,MAAM,CACjB,CAACC,OAAOC,OAASD,QAAQE,KAAKC,SAAS,CAACzB,aAAauB,KAAKG,WAAW,EAAEH,KAAKG,WAAW,EAAE,IAAIb,QAAQc,MAAM,EAC3G;AAEJ;AAEA,SAASnB,eAAeQ,KAAc;IACpC,OAAO,OAAOA,UAAU,YAAYA,UAAU,QAAQ,CAACZ,MAAMC,OAAO,CAACW;AACvE;AAEA,i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;;;;;;;;CASC,GACD,OAAO,SAASmB,cAAcxF,KAAc;IAC1C,IAAI,OAAOA,UAAU,UAAU;QAC7B,IAAI,CAACA,MAAMyF,IAAI,IAAI,OAAO,CAAC;QAC3B,IAAI;YACF,MAAMpB,SAAkB7D,KAAKkF,KAAK,CAAC1F;YACnC,OAAOqE,UAAU,OAAOA,WAAW,YAAY,CAACjF,MAAMC,OAAO,CAACgF,UACzDA,SACD,CAAC;QACP,EAAE,eAAM;YACN,OAAO,CAAC;QACV;IACF;IACA,OAAOrE,SAAS,OAAOA,UAAU,WAAYA,QAAoC,CAAC;AACpF"}
@@ -29,6 +29,15 @@ import type { AiUsage } from './contract';
29
29
  /** The shapes a picture may be asked for, as the dialog offers them. */
30
30
  export declare const AI_IMAGE_ASPECT_RATIOS: readonly ["1:1", "4:3", "3:4", "16:9", "9:16"];
31
31
  export type AiImageAspectRatio = (typeof AI_IMAGE_ASPECT_RATIOS)[number];
32
+ /**
33
+ * The sizes a picture is made at (AGL-3602): 512 px on the Free plan and 1K
34
+ * on every paid plan. The door chooses from the workspace's plan
35
+ * (`aiImageSizeForPlan`); nothing a request sends can choose it.
36
+ */
37
+ export declare const AI_IMAGE_SIZES: readonly ["512", "1K"];
38
+ export type AiImageSize = (typeof AI_IMAGE_SIZES)[number];
39
+ /** The size a picture is made at for a workspace on the Free plan, or on a paid one. */
40
+ export declare function aiImageSizeForPlan(free: boolean): AiImageSize;
32
41
  /** The most pictures one request makes. */
33
42
  export declare const AI_IMAGE_MAX_COUNT = 4;
34
43
  /** The longest description a request carries, in characters. */
@@ -36,13 +45,23 @@ export declare const AI_IMAGE_PROMPT_MAX_CHARS = 1000;
36
45
  /**
37
46
  * The two ways the Media dialog makes a picture (AGL-3602): a `photo` from
38
47
  * the image provider, and an `illustration` drawn as SVG by the text
39
- * provider every other AI door already uses.
48
+ * provider every other AI door already uses. `photo` is the image provider's
49
+ * mode whatever the kind — a watercolor is made there too — and is stored on
50
+ * every picture's record, so the value is never renamed.
40
51
  */
41
52
  export declare const AI_IMAGE_MODES: readonly ["photo", "illustration"];
42
53
  export type AiImageMode = (typeof AI_IMAGE_MODES)[number];
43
54
  /** What an illustration is: a scene, an icon, a tileable pattern or a simple mark. */
44
55
  export declare const AI_SVG_STYLES: readonly ["illustration", "icon", "pattern", "logo"];
45
56
  export type AiSvgStyle = (typeof AI_SVG_STYLES)[number];
57
+ /**
58
+ * What a picture from the image provider is (AGL-3602): `photo` leaves the
59
+ * style to the description, and every other kind adds its own fixed style
60
+ * wording to it — a photographic genre, an art style or a design asset.
61
+ */
62
+ export declare const AI_RASTER_STYLES: readonly ["photo", "natural", "product", "lifestyle", "architecture", "food", "aerial", "render-3d", "watercolor", "oil-painting", "flat-art", "line-drawing", "cartoon", "background", "banner", "social", "mockup"];
63
+ export type AiRasterStyle = (typeof AI_RASTER_STYLES)[number];
64
+ export declare function isAiRasterStyle(value: unknown): value is AiRasterStyle;
46
65
  /** The most colors a person may name for an illustration. */
47
66
  export declare const AI_SVG_MAX_COLORS = 6;
48
67
  /**
@@ -60,6 +79,8 @@ export interface AiImageRequest {
60
79
  model: string;
61
80
  prompt: string;
62
81
  aspectRatio: AiImageAspectRatio;
82
+ /** The size, chosen by the door from the workspace's plan. */
83
+ size: AiImageSize;
63
84
  /** 1 to `AI_IMAGE_MAX_COUNT`. */
64
85
  count: number;
65
86
  }
@@ -30,12 +30,25 @@
30
30
  '16:9',
31
31
  '9:16'
32
32
  ];
33
+ /**
34
+ * The sizes a picture is made at (AGL-3602): 512 px on the Free plan and 1K
35
+ * on every paid plan. The door chooses from the workspace's plan
36
+ * (`aiImageSizeForPlan`); nothing a request sends can choose it.
37
+ */ export const AI_IMAGE_SIZES = [
38
+ '512',
39
+ '1K'
40
+ ];
41
+ /** The size a picture is made at for a workspace on the Free plan, or on a paid one. */ export function aiImageSizeForPlan(free) {
42
+ return free ? '512' : '1K';
43
+ }
33
44
  /** The most pictures one request makes. */ export const AI_IMAGE_MAX_COUNT = 4;
34
45
  /** The longest description a request carries, in characters. */ export const AI_IMAGE_PROMPT_MAX_CHARS = 1000;
35
46
  /**
36
47
  * The two ways the Media dialog makes a picture (AGL-3602): a `photo` from
37
48
  * the image provider, and an `illustration` drawn as SVG by the text
38
- * provider every other AI door already uses.
49
+ * provider every other AI door already uses. `photo` is the image provider's
50
+ * mode whatever the kind — a watercolor is made there too — and is stored on
51
+ * every picture's record, so the value is never renamed.
39
52
  */ export const AI_IMAGE_MODES = [
40
53
  'photo',
41
54
  'illustration'
@@ -46,6 +59,32 @@
46
59
  'pattern',
47
60
  'logo'
48
61
  ];
62
+ /**
63
+ * What a picture from the image provider is (AGL-3602): `photo` leaves the
64
+ * style to the description, and every other kind adds its own fixed style
65
+ * wording to it — a photographic genre, an art style or a design asset.
66
+ */ export const AI_RASTER_STYLES = [
67
+ 'photo',
68
+ 'natural',
69
+ 'product',
70
+ 'lifestyle',
71
+ 'architecture',
72
+ 'food',
73
+ 'aerial',
74
+ 'render-3d',
75
+ 'watercolor',
76
+ 'oil-painting',
77
+ 'flat-art',
78
+ 'line-drawing',
79
+ 'cartoon',
80
+ 'background',
81
+ 'banner',
82
+ 'social',
83
+ 'mockup'
84
+ ];
85
+ export function isAiRasterStyle(value) {
86
+ return AI_RASTER_STYLES.includes(value);
87
+ }
49
88
  /** The most colors a person may name for an illustration. */ export const AI_SVG_MAX_COLORS = 6;
50
89
  /**
51
90
  * Whether this deployment offers the photo mode, as its build says: a