@aglyn/plugins-ai 1.0.0-beta.250 → 1.0.0-beta.252

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 (94) hide show
  1. package/package.json +17 -17
  2. package/src/lib/components/ai-brief-dialog.component.js +15 -1
  3. package/src/lib/components/ai-brief-dialog.component.js.map +1 -1
  4. package/src/lib/components/ai-job-links.js +1 -1
  5. package/src/lib/components/ai-job-links.js.map +1 -1
  6. package/src/lib/components/ai-job-plan.component.js +20 -2
  7. package/src/lib/components/ai-job-plan.component.js.map +1 -1
  8. package/src/lib/components/ai-jobs-store.d.ts +11 -0
  9. package/src/lib/components/ai-jobs-store.js +22 -0
  10. package/src/lib/components/ai-jobs-store.js.map +1 -1
  11. package/src/lib/jobs/ai-job-crm-step.js +7 -4
  12. package/src/lib/jobs/ai-job-crm-step.js.map +1 -1
  13. package/src/lib/jobs/ai-job-drafts.d.ts +24 -0
  14. package/src/lib/jobs/ai-job-drafts.js +46 -0
  15. package/src/lib/jobs/ai-job-drafts.js.map +1 -1
  16. package/src/lib/jobs/ai-job-experiment-step.js +6 -1
  17. package/src/lib/jobs/ai-job-experiment-step.js.map +1 -1
  18. package/src/lib/jobs/ai-job-form-reuse.d.ts +78 -0
  19. package/src/lib/jobs/ai-job-form-reuse.js +136 -0
  20. package/src/lib/jobs/ai-job-form-reuse.js.map +1 -0
  21. package/src/lib/jobs/ai-job-form-step.d.ts +17 -0
  22. package/src/lib/jobs/ai-job-form-step.js +63 -11
  23. package/src/lib/jobs/ai-job-form-step.js.map +1 -1
  24. package/src/lib/jobs/ai-job-insight-step.js +6 -1
  25. package/src/lib/jobs/ai-job-insight-step.js.map +1 -1
  26. package/src/lib/jobs/ai-job-plan-step.d.ts +19 -0
  27. package/src/lib/jobs/ai-job-plan-step.js +39 -1
  28. package/src/lib/jobs/ai-job-plan-step.js.map +1 -1
  29. package/src/lib/jobs/ai-job-seo-step.js +5 -3
  30. package/src/lib/jobs/ai-job-seo-step.js.map +1 -1
  31. package/src/lib/jobs/ai-job-site-content.d.ts +7 -5
  32. package/src/lib/jobs/ai-job-site-content.js +7 -5
  33. package/src/lib/jobs/ai-job-site-content.js.map +1 -1
  34. package/src/lib/jobs/ai-job-text-step.js +6 -3
  35. package/src/lib/jobs/ai-job-text-step.js.map +1 -1
  36. package/src/lib/jobs/ai-layout-stock-photos.d.ts +11 -7
  37. package/src/lib/jobs/ai-layout-stock-photos.js +25 -10
  38. package/src/lib/jobs/ai-layout-stock-photos.js.map +1 -1
  39. package/src/lib/jobs/ai-stock-business-nouns.d.ts +62 -0
  40. package/src/lib/jobs/ai-stock-business-nouns.js +264 -0
  41. package/src/lib/jobs/ai-stock-business-nouns.js.map +1 -0
  42. package/src/lib/model/ai-build-plan.d.ts +7 -3
  43. package/src/lib/model/ai-build-plan.js +11 -1
  44. package/src/lib/model/ai-build-plan.js.map +1 -1
  45. package/src/lib/model/ai-credit-estimate.d.ts +32 -18
  46. package/src/lib/model/ai-credit-estimate.js +36 -18
  47. package/src/lib/model/ai-credit-estimate.js.map +1 -1
  48. package/src/lib/model/ai-job-activity.d.ts +30 -0
  49. package/src/lib/model/ai-job-activity.js +35 -0
  50. package/src/lib/model/ai-job-activity.js.map +1 -1
  51. package/src/lib/model/ai-media-credits.d.ts +5 -3
  52. package/src/lib/model/ai-media-credits.js +7 -5
  53. package/src/lib/model/ai-media-credits.js.map +1 -1
  54. package/src/lib/model/ai-site-job.js +6 -3
  55. package/src/lib/model/ai-site-job.js.map +1 -1
  56. package/src/lib/model/ai-site-store-pages.d.ts +5 -0
  57. package/src/lib/model/ai-site-store-pages.js +2 -0
  58. package/src/lib/model/ai-site-store-pages.js.map +1 -1
  59. package/src/lib/plugin-config.js +2 -2
  60. package/src/lib/plugin-config.js.map +1 -1
  61. package/src/lib/providers/anthropic-crm-wording-superseded.d.ts +29 -0
  62. package/src/lib/providers/anthropic-crm-wording-superseded.js +31 -0
  63. package/src/lib/providers/anthropic-crm-wording-superseded.js.map +1 -0
  64. package/src/lib/providers/catalog.d.ts +24 -17
  65. package/src/lib/providers/catalog.js +63 -30
  66. package/src/lib/providers/catalog.js.map +1 -1
  67. package/src/lib/providers/model-choice.d.ts +1 -1
  68. package/src/lib/providers/model-choice.js +39 -30
  69. package/src/lib/providers/model-choice.js.map +1 -1
  70. package/src/lib/providers/routing.d.ts +20 -1
  71. package/src/lib/providers/routing.js +47 -8
  72. package/src/lib/providers/routing.js.map +1 -1
  73. package/src/lib/runtime/ai-dev-env.d.ts +37 -1
  74. package/src/lib/runtime/ai-dev-env.js +59 -6
  75. package/src/lib/runtime/ai-dev-env.js.map +1 -1
  76. package/src/lib/runtime/ai-doctrine-validators.js +3 -1
  77. package/src/lib/runtime/ai-doctrine-validators.js.map +1 -1
  78. package/src/lib/runtime/ai-doctrine.js +8 -4
  79. package/src/lib/runtime/ai-doctrine.js.map +1 -1
  80. package/src/lib/runtime/ai-eval-live.d.ts +8 -0
  81. package/src/lib/runtime/ai-eval-live.js +34 -8
  82. package/src/lib/runtime/ai-eval-live.js.map +1 -1
  83. package/src/lib/runtime/ai-palette.generated.js +4 -0
  84. package/src/lib/runtime/ai-palette.generated.js.map +1 -1
  85. package/src/lib/runtime/ai-runtime.js +17 -2
  86. package/src/lib/runtime/ai-runtime.js.map +1 -1
  87. package/src/lib/runtime/seo-fields.js +4 -3
  88. package/src/lib/runtime/seo-fields.js.map +1 -1
  89. package/src/lib/server/ai-assist.js +3 -2
  90. package/src/lib/server/ai-assist.js.map +1 -1
  91. package/src/lib/server/ai-media-svg.js +4 -0
  92. package/src/lib/server/ai-media-svg.js.map +1 -1
  93. package/src/lib/usage/ai-allotment-alerts.js +2 -5
  94. package/src/lib/usage/ai-allotment-alerts.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/server/ai-media-svg.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { aiDefaultModelFor } from '../providers/catalog'\nimport type { AiSystemBlock, AiTool, AiUsage } from '../providers/contract'\nimport type { AiImageAspectRatio, AiSvgStyle } from '../providers/image-contract'\nimport { resolveAiProvider } from '../providers/routing'\nimport { AI_SVG_MAX_BYTES, AI_SVG_VIEWBOX, checkAiSvgMarkup } from '../model/ai-svg'\nimport type { AiDoctrineViolation } from '../runtime/ai-doctrine-validators'\nimport {\n runValidatedGeneration,\n type AiCustomGenerationInput,\n type AiGenerationCheckResult,\n type AiValidatedGeneration,\n} from '../runtime/ai-doctrine'\n\n/**\n * Illustrations in Media (AGL-3602): an SVG drawn by the TEXT provider every\n * other AI door uses — the same registry, the same meter, the same data flow\n * the published subprocessor row for the text provider already describes —\n * so this mode needs no new vendor and runs wherever text AI does.\n *\n * One generation per picture, through `runValidatedGeneration`: the answer\n * arrives through a strict tool, `checkAiSvgMarkup` is its check, and an\n * answer with a problem is sent back once with what to fix. A second answer\n * with a problem is not stored and, being our failure, not charged.\n *\n * It runs on the provider's fast tier: an SVG is a few thousand tokens of\n * markup and the door answers inside one request, so the model that writes\n * them quickest is the one that fits.\n */\n\n/** The doctrine kind the generation runs under; it reads no site tree. */\nexport const AI_MEDIA_SVG_KIND = 'media-svg'\n\n/** The name of the tool the picture arrives through. */\nexport const AI_MEDIA_SVG_TOOL_NAME = 'submit_svg'\n\n/** The answer ceiling: room for a compact picture and a re-ask's worth of care. */\nexport const AI_MEDIA_SVG_MAX_TOKENS = 6_000\n\n/** What each kind of illustration is, in the words the model is given. */\nconst STYLE_BRIEF: Readonly<Record<AiSvgStyle, string>> = {\n illustration:\n 'A spot illustration or small scene: flat or lightly shaded vector shapes, clear silhouettes, no photographic detail.',\n icon: 'A single icon: bold, simple geometry centered with even padding, in ONE color, or two tones of the palette at most. Readable at 24 pixels.',\n pattern:\n 'A seamless, tileable background pattern: every shape that leaves one edge re-enters at the opposite edge, so tiles join without a seam. Low contrast, suitable behind text.',\n logo: \"A simple abstract logo MARK: a symbol made of a few shapes, with no lettering at all. Never a real company's logo, a trademark, a brand's symbol or anything imitating one.\",\n}\n\nconst INSTRUCTIONS = [\n 'You draw SVG pictures for a website owner. You receive what to draw, which kind of picture it is, its shape and the colors to use, and you answer through the submit_svg tool.',\n '',\n 'The SVG you write must:',\n '- be exactly one <svg> element with xmlns=\"http://www.w3.org/2000/svg\" and the viewBox you are given, and no width or height attributes;',\n '- use only shapes, paths, groups, gradients, clipPaths and masks drawn in the document itself: never <image>, <foreignObject>, <script>, <a>, animation elements, event attributes, or a href or url(...) pointing anywhere but #ids in the same SVG;',\n '- use no web fonts, @import or @font-face; prefer no text at all, and use only generic font families (sans-serif, serif) when text is essential;',\n `- stay compact: well under ${Math.round(AI_SVG_MAX_BYTES / 1024 / 4)} KB, with few paths and coordinates rounded to at most one decimal place;`,\n '- use the colors given, plus white, black and transparency, and no others.',\n '',\n 'Write alt text: one plain sentence describing what the picture shows, for someone who cannot see it.',\n '',\n \"Decline instead of drawing — set declined to one short sentence and leave svg and alt empty — when you are asked for a real company's or organization's logo, a trademark, a recognizable brand symbol or anything imitating one; for a real, named person; or for anything sexual, hateful, violent or otherwise unsafe. Otherwise set declined to an empty string.\",\n].join('\\n')\n\nexport const AI_MEDIA_SVG_INSTRUCTIONS: AiSystemBlock[] = [{ text: INSTRUCTIONS, cacheBreakpoint: true }]\n\nexport function aiMediaSvgTool(): AiTool {\n return {\n name: AI_MEDIA_SVG_TOOL_NAME,\n description: 'Submit the SVG picture and its alt text, or decline.',\n strict: true,\n inputSchema: {\n type: 'object',\n additionalProperties: false,\n required: ['svg', 'alt', 'declined'],\n properties: {\n svg: { type: 'string', description: 'The whole SVG document, starting with <svg and ending with </svg>.' },\n alt: { type: 'string', description: 'One plain sentence describing the picture.' },\n declined: {\n type: 'string',\n description: 'Empty, or one short sentence saying why this picture is not drawn.',\n },\n },\n },\n }\n}\n\n/** The question one picture is asked as. */\nexport function aiMediaSvgPrompt(input: {\n prompt: string\n style: AiSvgStyle\n aspectRatio: AiImageAspectRatio\n palette: readonly string[]\n variant: number\n count: number\n}): string {\n const colors = input.palette.length\n ? `Colors: ${input.palette.join(', ')}.`\n : 'Colors: a restrained palette of three to five colors of your choice.'\n const lines = [\n `Kind: ${input.style}. ${STYLE_BRIEF[input.style]}`,\n `Shape: ${input.aspectRatio}, viewBox=\"${AI_SVG_VIEWBOX[input.aspectRatio]}\".`,\n colors,\n ]\n if (input.count > 1) {\n lines.push(\n `This is version ${input.variant + 1} of ${input.count}: make it a distinct take on the same description.`,\n )\n }\n lines.push('', 'Draw:', input.prompt)\n return lines.join('\\n')\n}\n\n/** What one picture's answer holds once it is read. */\nexport type AiMediaSvgAnswer = { svg: string; alt: string } | { declined: string }\n\n/** The check one answer is held to: the SVG gate, or a decline. */\nexport function checkAiMediaSvgAnswer(\n answer: Record<string, unknown>,\n aspectRatio: AiImageAspectRatio,\n style: AiSvgStyle,\n): AiGenerationCheckResult<AiMediaSvgAnswer> {\n const declined = typeof answer['declined'] === 'string' ? answer['declined'].trim() : ''\n if (declined) return { value: { declined: declined.slice(0, 300) }, violations: [] }\n const result = checkAiSvgMarkup(answer['svg'], aspectRatio, style)\n const alt = typeof answer['alt'] === 'string' ? answer['alt'].replace(/\\s+/g, ' ').trim().slice(0, 300) : ''\n if (result.svg) return { value: { svg: result.svg, alt }, violations: [] }\n const violations: AiDoctrineViolation[] = result.problems.map((problem) => ({\n rule: null,\n code: `svg-${problem.code}`,\n message: 'The picture could not be drawn safely.',\n detail: problem.detail,\n }))\n return { value: { svg: '', alt }, violations, offending: { svg: '(see the problems listed)' } }\n}\n\n/** The model an illustration runs on: the text provider's fast tier. */\nexport function aiMediaSvgModel(): string | undefined {\n const provider = resolveAiProvider()\n return provider ? aiDefaultModelFor(provider.id, 'fast') : undefined\n}\n\n/** One picture's outcome. */\nexport type AiMediaSvgOutcome =\n | { kind: 'drawn'; svg: string; alt: string; usage: AiUsage; model: string }\n | { kind: 'declined'; reason: string; usage: AiUsage; model: string }\n /** The re-ask still failed the gate, or the model stopped: ours, never charged. */\n | { kind: 'failed'; usage: AiUsage; model: string }\n\n/** Draws one picture. A provider fault propagates for the door to answer. */\nexport async function generateAiMediaSvg(input: {\n model: string\n prompt: string\n style: AiSvgStyle\n aspectRatio: AiImageAspectRatio\n palette: readonly string[]\n variant: number\n count: number\n}): Promise<AiMediaSvgOutcome> {\n const generation: AiCustomGenerationInput<AiMediaSvgAnswer> = {\n model: input.model,\n instructions: AI_MEDIA_SVG_INSTRUCTIONS,\n inventory: undefined,\n messages: [{ role: 'user', content: aiMediaSvgPrompt(input) }],\n tool: aiMediaSvgTool(),\n maxTokens: AI_MEDIA_SVG_MAX_TOKENS,\n check: (answer) => checkAiMediaSvgAnswer(answer, input.aspectRatio, input.style),\n }\n const result = (await runValidatedGeneration(\n AI_MEDIA_SVG_KIND,\n generation,\n )) as AiValidatedGeneration<AiMediaSvgAnswer>\n const spent = { usage: result.usage, model: result.model }\n if (result.status === 'ok') {\n return 'declined' in result.value\n ? { kind: 'declined', reason: result.value.declined, ...spent }\n : { kind: 'drawn', svg: result.value.svg, alt: result.value.alt, ...spent }\n }\n if (result.status === 'refused') {\n return { kind: 'declined', reason: 'The assistant would not draw this.', ...spent }\n }\n return { kind: 'failed', ...spent }\n}\n"],"names":["aiDefaultModelFor","resolveAiProvider","AI_SVG_MAX_BYTES","AI_SVG_VIEWBOX","checkAiSvgMarkup","runValidatedGeneration","AI_MEDIA_SVG_KIND","AI_MEDIA_SVG_TOOL_NAME","AI_MEDIA_SVG_MAX_TOKENS","STYLE_BRIEF","illustration","icon","pattern","logo","INSTRUCTIONS","Math","round","join","AI_MEDIA_SVG_INSTRUCTIONS","text","cacheBreakpoint","aiMediaSvgTool","name","description","strict","inputSchema","type","additionalProperties","required","properties","svg","alt","declined","aiMediaSvgPrompt","input","colors","palette","length","lines","style","aspectRatio","count","push","variant","prompt","checkAiMediaSvgAnswer","answer","trim","value","slice","violations","result","replace","problems","map","problem","rule","code","message","detail","offending","aiMediaSvgModel","provider","id","undefined","generateAiMediaSvg","generation","model","instructions","inventory","messages","role","content","tool","maxTokens","check","spent","usage","status","kind","reason"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,iBAAiB,QAAQ,0BAAsB;AAGxD,SAASC,iBAAiB,QAAQ,0BAAsB;AACxD,SAASC,gBAAgB,EAAEC,cAAc,EAAEC,gBAAgB,QAAQ,qBAAiB;AAEpF,SACEC,sBAAsB,QAIjB,4BAAwB;AAE/B;;;;;;;;;;;;;;CAcC,GAED,wEAAwE,GACxE,OAAO,MAAMC,oBAAoB,YAAW;AAE5C,sDAAsD,GACtD,OAAO,MAAMC,yBAAyB,aAAY;AAElD,iFAAiF,GACjF,OAAO,MAAMC,0BAA0B,KAAK;AAE5C,wEAAwE,GACxE,MAAMC,cAAoD;IACxDC,cACE;IACFC,MAAM;IACNC,SACE;IACFC,MAAM;AACR;AAEA,MAAMC,eAAe;IACnB;IACA;IACA;IACA;IACA;IACA;IACA,CAAC,2BAA2B,EAAEC,KAAKC,KAAK,CAACd,mBAAmB,OAAO,GAAG,yEAAyE,CAAC;IAChJ;IACA;IACA;IACA;IACA;CACD,CAACe,IAAI,CAAC;AAEP,OAAO,MAAMC,4BAA6C;IAAC;QAAEC,MAAML;QAAcM,iBAAiB;IAAK;CAAE,CAAA;AAEzG,OAAO,SAASC;IACd,OAAO;QACLC,MAAMf;QACNgB,aAAa;QACbC,QAAQ;QACRC,aAAa;YACXC,MAAM;YACNC,sBAAsB;YACtBC,UAAU;gBAAC;gBAAO;gBAAO;aAAW;YACpCC,YAAY;gBACVC,KAAK;oBAAEJ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ACtD;YAAEG,MAAM;YAASjD,KAAKqB,OAAOH,KAAK,CAAClB,GAAG;YAAEC,KAAKoB,OAAOH,KAAK,CAACjB,GAAG;WAAK6C;IACxE;IACA,IAAIzB,OAAO2B,MAAM,KAAK,WAAW;QAC/B,OAAO;YAAEC,MAAM;YAAYC,QAAQ;WAAyCJ;IAC9E;IACA,OAAO;QAAEG,MAAM;OAAaH;AAC9B"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/server/ai-media-svg.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { aiDefaultModelFor } from '../providers/catalog'\nimport type { AiSystemBlock, AiTool, AiUsage } from '../providers/contract'\nimport type { AiImageAspectRatio, AiSvgStyle } from '../providers/image-contract'\nimport { resolveAiProvider } from '../providers/routing'\nimport { AI_SVG_MAX_BYTES, AI_SVG_VIEWBOX, checkAiSvgMarkup } from '../model/ai-svg'\nimport type { AiDoctrineViolation } from '../runtime/ai-doctrine-validators'\nimport {\n runValidatedGeneration,\n type AiCustomGenerationInput,\n type AiGenerationCheckResult,\n type AiValidatedGeneration,\n} from '../runtime/ai-doctrine'\n\n/**\n * Illustrations in Media (AGL-3602): an SVG drawn by the TEXT provider every\n * other AI door uses — the same registry, the same meter, the same data flow\n * the published subprocessor row for the text provider already describes —\n * so this mode needs no new vendor and runs wherever text AI does.\n *\n * One generation per picture, through `runValidatedGeneration`: the answer\n * arrives through a strict tool, `checkAiSvgMarkup` is its check, and an\n * answer with a problem is sent back once with what to fix. A second answer\n * with a problem is not stored and, being our failure, not charged.\n *\n * It runs on the provider's fast tier: an SVG is a few thousand tokens of\n * markup and the door answers inside one request, so the model that writes\n * them quickest is the one that fits.\n */\n\n/** The doctrine kind the generation runs under; it reads no site tree. */\nexport const AI_MEDIA_SVG_KIND = 'media-svg'\n\n/** The name of the tool the picture arrives through. */\nexport const AI_MEDIA_SVG_TOOL_NAME = 'submit_svg'\n\n/** The answer ceiling: room for a compact picture and a re-ask's worth of care. */\nexport const AI_MEDIA_SVG_MAX_TOKENS = 6_000\n\n/** What each kind of illustration is, in the words the model is given. */\nconst STYLE_BRIEF: Readonly<Record<AiSvgStyle, string>> = {\n illustration:\n 'A spot illustration or small scene: flat or lightly shaded vector shapes, clear silhouettes, no photographic detail.',\n icon: 'A single icon: bold, simple geometry centered with even padding, in ONE color, or two tones of the palette at most. Readable at 24 pixels.',\n pattern:\n 'A seamless, tileable background pattern: every shape that leaves one edge re-enters at the opposite edge, so tiles join without a seam. Low contrast, suitable behind text.',\n logo: \"A simple abstract logo MARK: a symbol made of a few shapes, with no lettering at all. Never a real company's logo, a trademark, a brand's symbol or anything imitating one.\",\n}\n\nconst INSTRUCTIONS = [\n 'You draw SVG pictures for a website owner. You receive what to draw, which kind of picture it is, its shape and the colors to use, and you answer through the submit_svg tool.',\n '',\n 'The SVG you write must:',\n '- be exactly one <svg> element with xmlns=\"http://www.w3.org/2000/svg\" and the viewBox you are given, and no width or height attributes;',\n '- use only shapes, paths, groups, gradients, clipPaths and masks drawn in the document itself: never <image>, <foreignObject>, <script>, <a>, animation elements, event attributes, or a href or url(...) pointing anywhere but #ids in the same SVG;',\n '- use no web fonts, @import or @font-face; prefer no text at all, and use only generic font families (sans-serif, serif) when text is essential;',\n `- stay compact: well under ${Math.round(AI_SVG_MAX_BYTES / 1024 / 4)} KB, with few paths and coordinates rounded to at most one decimal place;`,\n '- use the colors given, plus white, black and transparency, and no others.',\n '',\n 'Write alt text: one plain sentence describing what the picture shows, for someone who cannot see it.',\n '',\n \"Decline instead of drawing — set declined to one short sentence and leave svg and alt empty — when you are asked for a real company's or organization's logo, a trademark, a recognizable brand symbol or anything imitating one; for a real, named person; or for anything sexual, hateful, violent or otherwise unsafe. Otherwise set declined to an empty string.\",\n].join('\\n')\n\nexport const AI_MEDIA_SVG_INSTRUCTIONS: AiSystemBlock[] = [{ text: INSTRUCTIONS, cacheBreakpoint: true }]\n\nexport function aiMediaSvgTool(): AiTool {\n return {\n name: AI_MEDIA_SVG_TOOL_NAME,\n description: 'Submit the SVG picture and its alt text, or decline.',\n strict: true,\n inputSchema: {\n type: 'object',\n additionalProperties: false,\n required: ['svg', 'alt', 'declined'],\n properties: {\n svg: { type: 'string', description: 'The whole SVG document, starting with <svg and ending with </svg>.' },\n alt: { type: 'string', description: 'One plain sentence describing the picture.' },\n declined: {\n type: 'string',\n description: 'Empty, or one short sentence saying why this picture is not drawn.',\n },\n },\n },\n }\n}\n\n/** The question one picture is asked as. */\nexport function aiMediaSvgPrompt(input: {\n prompt: string\n style: AiSvgStyle\n aspectRatio: AiImageAspectRatio\n palette: readonly string[]\n variant: number\n count: number\n}): string {\n const colors = input.palette.length\n ? `Colors: ${input.palette.join(', ')}.`\n : 'Colors: a restrained palette of three to five colors of your choice.'\n const lines = [\n `Kind: ${input.style}. ${STYLE_BRIEF[input.style]}`,\n `Shape: ${input.aspectRatio}, viewBox=\"${AI_SVG_VIEWBOX[input.aspectRatio]}\".`,\n colors,\n ]\n if (input.count > 1) {\n lines.push(\n `This is version ${input.variant + 1} of ${input.count}: make it a distinct take on the same description.`,\n )\n }\n lines.push('', 'Draw:', input.prompt)\n return lines.join('\\n')\n}\n\n/** What one picture's answer holds once it is read. */\nexport type AiMediaSvgAnswer = { svg: string; alt: string } | { declined: string }\n\n/** The check one answer is held to: the SVG gate, or a decline. */\nexport function checkAiMediaSvgAnswer(\n answer: Record<string, unknown>,\n aspectRatio: AiImageAspectRatio,\n style: AiSvgStyle,\n): AiGenerationCheckResult<AiMediaSvgAnswer> {\n const declined = typeof answer['declined'] === 'string' ? answer['declined'].trim() : ''\n if (declined) return { value: { declined: declined.slice(0, 300) }, violations: [] }\n const result = checkAiSvgMarkup(answer['svg'], aspectRatio, style)\n const alt = typeof answer['alt'] === 'string' ? answer['alt'].replace(/\\s+/g, ' ').trim().slice(0, 300) : ''\n if (result.svg) return { value: { svg: result.svg, alt }, violations: [] }\n const violations: AiDoctrineViolation[] = result.problems.map((problem) => ({\n rule: null,\n code: `svg-${problem.code}`,\n message: 'The picture could not be drawn safely.',\n detail: problem.detail,\n }))\n return { value: { svg: '', alt }, violations, offending: { svg: '(see the problems listed)' } }\n}\n\n/** The model an illustration runs on: the text provider's fast tier. */\nexport function aiMediaSvgModel(): string | undefined {\n const provider = resolveAiProvider()\n return provider ? aiDefaultModelFor(provider.id, 'fast') : undefined\n}\n\n/** One picture's outcome. */\nexport type AiMediaSvgOutcome =\n | { kind: 'drawn'; svg: string; alt: string; usage: AiUsage; model: string }\n | { kind: 'declined'; reason: string; usage: AiUsage; model: string }\n /** The re-ask still failed the gate, or the model stopped: ours, never charged. */\n | { kind: 'failed'; usage: AiUsage; model: string }\n\n/** Draws one picture. A provider fault propagates for the door to answer. */\nexport async function generateAiMediaSvg(input: {\n model: string\n prompt: string\n style: AiSvgStyle\n aspectRatio: AiImageAspectRatio\n palette: readonly string[]\n variant: number\n count: number\n}): Promise<AiMediaSvgOutcome> {\n const generation: AiCustomGenerationInput<AiMediaSvgAnswer> = {\n model: input.model,\n instructions: AI_MEDIA_SVG_INSTRUCTIONS,\n inventory: undefined,\n messages: [{ role: 'user', content: aiMediaSvgPrompt(input) }],\n tool: aiMediaSvgTool(),\n maxTokens: AI_MEDIA_SVG_MAX_TOKENS,\n // The ceiling holds the drawing alone, as it did on a fast tier that\n // could not think; the fast tier's model now thinks unless told not to\n // (AGL-3781).\n thinking: 'off',\n check: (answer) => checkAiMediaSvgAnswer(answer, input.aspectRatio, input.style),\n }\n const result = (await runValidatedGeneration(\n AI_MEDIA_SVG_KIND,\n generation,\n )) as AiValidatedGeneration<AiMediaSvgAnswer>\n const spent = { usage: result.usage, model: result.model }\n if (result.status === 'ok') {\n return 'declined' in result.value\n ? { kind: 'declined', reason: result.value.declined, ...spent }\n : { kind: 'drawn', svg: result.value.svg, alt: result.value.alt, ...spent }\n }\n if (result.status === 'refused') {\n return { kind: 'declined', reason: 'The assistant would not draw this.', ...spent }\n }\n return { kind: 'failed', ...spent }\n}\n"],"names":["aiDefaultModelFor","resolveAiProvider","AI_SVG_MAX_BYTES","AI_SVG_VIEWBOX","checkAiSvgMarkup","runValidatedGeneration","AI_MEDIA_SVG_KIND","AI_MEDIA_SVG_TOOL_NAME","AI_MEDIA_SVG_MAX_TOKENS","STYLE_BRIEF","illustration","icon","pattern","logo","INSTRUCTIONS","Math","round","join","AI_MEDIA_SVG_INSTRUCTIONS","text","cacheBreakpoint","aiMediaSvgTool","name","description","strict","inputSchema","type","additionalProperties","required","properties","svg","alt","declined","aiMediaSvgPrompt","input","colors","palette","length","lines","style","aspectRatio","count","push","variant","prompt","checkAiMediaSvgAnswer","answer","trim","value","slice","violations","result","replace","problems","map","problem","rule","code","message","detail","offending","aiMediaSvgModel","provider","id","undefined","generateAiMediaSvg","generation","model","instructions","inventory","messages","role","content","tool","maxTokens","thinking","check","spent","usage","status","kind","reason"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,iBAAiB,QAAQ,0BAAsB;AAGxD,SAASC,iBAAiB,QAAQ,0BAAsB;AACxD,SAASC,gBAAgB,EAAEC,cAAc,EAAEC,gBAAgB,QAAQ,qBAAiB;AAEpF,SACEC,sBAAsB,QAIjB,4BAAwB;AAE/B;;;;;;;;;;;;;;CAcC,GAED,wEAAwE,GACxE,OAAO,MAAMC,oBAAoB,YAAW;AAE5C,sDAAsD,GACtD,OAAO,MAAMC,yBAAyB,aAAY;AAElD,iFAAiF,GACjF,OAAO,MAAMC,0BAA0B,KAAK;AAE5C,wEAAwE,GACxE,MAAMC,cAAoD;IACxDC,cACE;IACFC,MA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WL;QACXM,UAAU;YAAC;gBAAEC,MAAM;gBAAQC,SAASvC,iBAAiBC;YAAO;SAAE;QAC9DuC,MAAMpD;QACNqD,WAAWlE;QACX,qEAAqE;QACrE,uEAAuE;QACvE,cAAc;QACdmE,UAAU;QACVC,OAAO,CAAC9B,SAAWD,sBAAsBC,QAAQZ,MAAMM,WAAW,EAAEN,MAAMK,KAAK;IACjF;IACA,MAAMY,SAAU,MAAM9C,uBACpBC,mBACA4D;IAEF,MAAMW,QAAQ;QAAEC,OAAO3B,OAAO2B,KAAK;QAAEX,OAAOhB,OAAOgB,KAAK;IAAC;IACzD,IAAIhB,OAAO4B,MAAM,KAAK,MAAM;QAC1B,OAAO,cAAc5B,OAAOH,KAAK,GAC7B;YAAEgC,MAAM;YAAYC,QAAQ9B,OAAOH,KAAK,CAAChB,QAAQ;WAAK6C,SACtD;YAAEG,MAAM;YAASlD,KAAKqB,OAAOH,KAAK,CAAClB,GAAG;YAAEC,KAAKoB,OAAOH,KAAK,CAACjB,GAAG;WAAK8C;IACxE;IACA,IAAI1B,OAAO4B,MAAM,KAAK,WAAW;QAC/B,OAAO;YAAEC,MAAM;YAAYC,QAAQ;WAAyCJ;IAC9E;IACA,OAAO;QAAEG,MAAM;OAAaH;AAC9B"}
@@ -16,6 +16,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
16
16
  * limitations under the License.
17
17
  */ import { buildRoute, Route } from "@aglyn/aglyn/app-utils/console-routes";
18
18
  import { usageNotificationLevel } from "@aglyn/aglyn/app-utils/notifications";
19
+ import { platformConsoleOrigin } from "@aglyn/aglyn/app-utils/platform-brand";
19
20
  import { sendEmail } from "@aglyn/shared-util-email";
20
21
  import { withoutMailWithheldAccounts } from "@aglyn/tenant-data-admin/server/account-mail";
21
22
  import { meterPlatformEmail } from "@aglyn/tenant-data-admin/server/email-metering";
@@ -30,10 +31,6 @@ const DEFAULT_CHANNELS = {
30
31
  meter: meterPlatformEmail,
31
32
  reachable: withoutMailWithheldAccounts
32
33
  };
33
- /** The console's absolute origin for an email link, or `''` when unset. */ function consoleOrigin() {
34
- var _process_env_NEXT_PUBLIC_CONSOLE_URL;
35
- return ((_process_env_NEXT_PUBLIC_CONSOLE_URL = process.env.NEXT_PUBLIC_CONSOLE_URL) != null ? _process_env_NEXT_PUBLIC_CONSOLE_URL : '').trim().replace(/\/+$/, '');
36
- }
37
34
  /** Take the marker for `threshold` this month; `false` when it was taken. */ export async function claimAiAllotmentAlert(firestore, orgId, subject, month, threshold) {
38
35
  const ref = aiAllotmentRef(firestore.collection('orgs').doc(orgId), subject);
39
36
  return firestore.runTransaction(async (tx)=>{
@@ -151,7 +148,7 @@ async function recipientsFor(firestore, orgId, standing, reachable) {
151
148
  skipEmail: true
152
149
  });
153
150
  }
154
- const origin = consoleOrigin();
151
+ const origin = platformConsoleOrigin();
155
152
  const managerText = link && origin ? `${copy.body}\n\n${origin}${link}` : copy.body;
156
153
  const managers = await filter(recipients.managerEmails);
157
154
  if (managers.length) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/usage/ai-allotment-alerts.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 { buildRoute, Route } from '@aglyn/aglyn/app-utils/console-routes'\nimport { usageNotificationLevel } from '@aglyn/aglyn/app-utils/notifications'\nimport { sendEmail } from '@aglyn/shared-util-email'\nimport { withoutMailWithheldAccounts } from '@aglyn/tenant-data-admin/server/account-mail'\nimport { meterPlatformEmail } from '@aglyn/tenant-data-admin/server/email-metering'\nimport { filterSuppressedEmails } from '@aglyn/tenant-data-admin/server/email-suppression'\nimport { notifyUsers } from '@aglyn/tenant-data-admin/server/notifications'\nimport {\n aiAllotmentAlertCopy,\n type AiAllotmentStanding,\n type AiAllotmentThreshold,\n} from '../model/ai-allotments'\nimport { aiAllotmentRef } from './ai-allotments'\n\n/**\n * A SOFT allotment's 75, 80, 90 and 100% steps (AGL-2942, AGL-3431),\n * through the alert pipeline's two channels: the console notification every\n * usage threshold writes (`billing.usage`, to `users/{uid}/notifications`)\n * and the email beside it, sent past the platform suppression list and\n * metered as platform mail — the same primitives the usage-alert sweep\n * composes.\n *\n * Told when the request that finds the subject at a threshold is admitted,\n * rather than on the next daily sweep: an allotment is a line a manager drew\n * for one person or one site, and a day's delay is most of what a soft line\n * is for. The sweep is untouched.\n *\n * ## Who is told\n *\n * The workspace's owners and admins — the audience of every usage alert —\n * and, for a member's or a collaborator's allotment, the person it is for.\n * The person gets their own words, in the second person and without the\n * Billing link or the \"make it hard\" step, neither of which they can use.\n * Both name the workspace, and a collaborator's the site, because an owner\n * of two workspaces cannot tell from a figure which one it is about.\n *\n * ## Once per threshold per month\n *\n * The marker is `alerted: { month, threshold }` on the allotment itself,\n * claimed in a transaction before anything is sent, so two requests at the\n * line cannot both announce it. A write to the allotment clears the marker,\n * so a raised allotment announces its own next crossing.\n */\n\n/** A crossing to announce, as the reservation measured it. */\nexport interface AiAllotmentAlertInput {\n orgId: string\n /** The workspace's slug, for the Billing link; `null` omits the link. */\n orgSlug: string | null\n month: string\n alerts: ReadonlyArray<{ standing: AiAllotmentStanding; threshold: AiAllotmentThreshold }>\n}\n\n/** The pipeline's primitives, replaceable in a spec. */\nexport interface AiAllotmentAlertChannels {\n notify: typeof notifyUsers\n send: typeof sendEmail\n filter: typeof filterSuppressedEmails\n meter: typeof meterPlatformEmail\n /** The uids given, minus locked or disabled accounts (AGL-3418). */\n reachable: typeof withoutMailWithheldAccounts\n}\n\nconst DEFAULT_CHANNELS: AiAllotmentAlertChannels = {\n notify: notifyUsers,\n send: sendEmail,\n filter: filterSuppressedEmails,\n meter: meterPlatformEmail,\n reachable: withoutMailWithheldAccounts,\n}\n\n/** The console's absolute origin for an email link, or `''` when unset. */\nfunction consoleOrigin(): string {\n return (process.env.NEXT_PUBLIC_CONSOLE_URL ?? '').trim().replace(/\\/+$/, '')\n}\n\n/** Take the marker for `threshold` this month; `false` when it was taken. */\nexport async function claimAiAllotmentAlert(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n subject: string,\n month: string,\n threshold: AiAllotmentThreshold,\n): Promise<boolean> {\n const ref = aiAllotmentRef(firestore.collection('orgs').doc(orgId), subject)\n return firestore.runTransaction(async (tx) => {\n const snapshot = await tx.get(ref)\n if (!snapshot.exists) return false\n const alerted = snapshot.get('alerted') as { month?: unknown; threshold?: unknown } | null\n if (alerted?.month === month && Number(alerted?.threshold) >= threshold) return false\n tx.set(ref, { alerted: { month, threshold } }, { merge: true })\n return true\n })\n}\n\ninterface Recipients {\n managerUids: string[]\n managerEmails: string[]\n subjectUid: string | null\n subjectEmail: string | null\n subjectName: string\n /** The workspace's name, for the copy. */\n workspaceName: string\n /** The site a collaborator's allotment is on, for the copy. */\n siteName: string\n}\n\n/** The name a site's managers know it by, then its address, then its id. */\nasync function siteName(\n firestore: FirebaseFirestore.Firestore,\n hostId: string,\n): Promise<string> {\n const host = await firestore.collection('hosts').doc(hostId).get()\n return (\n String(host.get('displayName') ?? '').trim() ||\n String(host.get('subdomain') ?? '').trim() ||\n hostId\n )\n}\n\nasync function recipientsFor(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n standing: AiAllotmentStanding,\n reachable: AiAllotmentAlertChannels['reachable'],\n): Promise<Recipients> {\n const orgRef = firestore.collection('orgs').doc(orgId)\n const [org, members] = await Promise.all([orgRef.get(), orgRef.collection('members').get()])\n // A locked or disabled account is told nothing, by either channel; it is\n // still named when the alert is about it.\n const open = new Set(await reachable(members.docs.map((member) => member.id)))\n const managerUids: string[] = []\n const managerEmails: string[] = []\n let subjectEmail: string | null = null\n let subjectName = ''\n for (const member of members.docs) {\n const role = member.get('role')\n const email = String(member.get('email') ?? '').trim()\n if ((role === 'owner' || role === 'admin') && open.has(member.id)) {\n managerUids.push(member.id)\n if (email.includes('@')) managerEmails.push(email)\n }\n if (standing.uid && member.id === standing.uid) {\n subjectEmail = email.includes('@') && open.has(member.id) ? email : null\n subjectName = String(member.get('displayName') ?? '').trim() || email\n }\n }\n const site = standing.hostId ? await siteName(firestore, standing.hostId) : ''\n if (standing.scope === 'host') subjectName = site\n return {\n managerUids,\n managerEmails,\n subjectUid:\n standing.scope === 'host' || !standing.uid || !open.has(standing.uid)\n ? null\n : standing.uid,\n subjectEmail: standing.scope === 'host' ? null : subjectEmail,\n subjectName: subjectName || (standing.scope === 'host' ? 'A site' : 'A member'),\n workspaceName:\n String(org.get('name') ?? '').trim() ||\n String(org.get('slug') ?? '').trim() ||\n 'your workspace',\n siteName: site,\n }\n}\n\n/**\n * Announce every crossing the reservation found. Never throws, and answers\n * how many were announced — one failing crossing does not stop the next.\n */\nexport async function announceAiAllotmentAlerts(\n firestore: FirebaseFirestore.Firestore,\n input: AiAllotmentAlertInput,\n channels: Partial<AiAllotmentAlertChannels> = {},\n): Promise<number> {\n const { notify, send, filter, meter, reachable } = { ...DEFAULT_CHANNELS, ...channels }\n let announced = 0\n for (const { standing, threshold } of input.alerts) {\n try {\n const claimed = await claimAiAllotmentAlert(\n firestore,\n input.orgId,\n standing.subject,\n input.month,\n threshold,\n )\n if (!claimed) continue\n const recipients = await recipientsFor(firestore, input.orgId, standing, reachable)\n const words = {\n scope: standing.scope,\n threshold,\n used: standing.used,\n credits: standing.credits,\n name: recipients.subjectName,\n workspace: recipients.workspaceName,\n site: recipients.siteName,\n }\n const copy = aiAllotmentAlertCopy(words)\n const ownCopy = aiAllotmentAlertCopy({ ...words, reader: 'subject' })\n const link = input.orgSlug\n ? `${buildRoute(Route.MANAGE_BILLING_USAGE, { orgSlug: input.orgSlug })}#ai-allotments`\n : null\n // `skipEmail`: the email below is this crossing's email, so the\n // per-person channel does not send a second one to anybody who switched\n // billing email on (AGL-3431).\n await notify(\n recipients.managerUids,\n {\n type: 'billing.usage',\n title: copy.title,\n body: copy.body,\n level: usageNotificationLevel(threshold),\n orgId: input.orgId,\n ...(link ? { link } : {}),\n },\n { skipEmail: true },\n )\n if (recipients.subjectUid && !recipients.managerUids.includes(recipients.subjectUid)) {\n await notify(\n [recipients.subjectUid],\n {\n type: 'billing.usage',\n title: ownCopy.title,\n body: ownCopy.body,\n level: usageNotificationLevel(threshold),\n orgId: input.orgId,\n },\n { skipEmail: true },\n )\n }\n const origin = consoleOrigin()\n const managerText = link && origin ? `${copy.body}\\n\\n${origin}${link}` : copy.body\n const managers = await filter(recipients.managerEmails)\n if (managers.length) {\n const result = await send({\n to: managers,\n subject: copy.title,\n text: managerText,\n context: 'ai-allotment-alert',\n })\n if (result.sent) await meter().catch(() => undefined)\n }\n const subjectAddress = recipients.subjectEmail\n ? (await filter([recipients.subjectEmail])).filter(\n (address) => !managers.includes(address),\n )\n : []\n if (subjectAddress.length) {\n const result = await send({\n to: subjectAddress,\n subject: ownCopy.title,\n text: ownCopy.body,\n context: 'ai-allotment-alert',\n })\n if (result.sent) await meter().catch(() => undefined)\n }\n announced += 1\n } catch (error) {\n console.error('[ai-allotments] announcing a crossing failed', input.orgId, standing.subject, error)\n }\n }\n return announced\n}\n"],"names":["buildRoute","Route","usageNotificationLevel","sendEmail","withoutMailWithheldAccounts","meterPlatformEmail","filterSuppressedEmails","notifyUsers","aiAllotmentAlertCopy","aiAllotmentRef","DEFAULT_CHANNELS","notify","send","filter","meter","reachable","consoleOrigin","process","env","NEXT_PUBLIC_CONSOLE_URL","trim","replace","claimAiAllotmentAlert","firestore","orgId","subject","month","threshold","ref","collection","doc","runTransaction","tx","snapshot","get","exists","alerted","Number","set","merge","siteName","hostId","host","String","recipientsFor","standing","org","orgRef","members","Promise","all","open","Set","docs","map","member","id","managerUids","managerEmails","subjectEmail","subjectName","role","email","has","push","includes","uid","site","scope","subjectUid","workspaceName","announceAiAllotmentAlerts","input","channels","announced","alerts","claimed","recipients","words","used","credits","name","workspace","copy","ownCopy","reader","link","orgSlug","MANAGE_BILLING_USAGE","type","title","body","level","skipEmail","origin","managerText","managers","length","result","to","text","context","sent","catch","undefined","subjectAddress","address","error","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,UAAU,EAAEC,KAAK,QAAQ,wCAAuC;AACzE,SAASC,sBAAsB,QAAQ,uCAAsC;AAC7E,SAASC,SAAS,QAAQ,2BAA0B;AACpD,SAASC,2BAA2B,QAAQ,+CAA8C;AAC1F,SAASC,kBAAkB,QAAQ,iDAAgD;AACnF,SAASC,sBAAsB,QAAQ,oDAAmD;AAC1F,SAASC,WAAW,QAAQ,gDAA+C;AAC3E,SACEC,oBAAoB,QAGf,4BAAwB;AAC/B,SAASC,cAAc,QAAQ,qBAAiB;AAmDhD,MAAMC,mBAA6C;IACjDC,QAAQJ;IACRK,MAAMT;IACNU,QAAQP;IACRQ,OAAOT;IACPU,WAAWX;AACb;AAEA,yEAAyE,GACzE,SAASY;QACCC;IAAR,OAAO,EAACA,uCAAAA,QAAQC,GAAG,CAACC,uBAAuB,YAAnCF,uCAAuC,IAAIG,IAAI,GAAGC,OAAO,CAAC,QAAQ;AAC5E;AAEA,2EAA2E,GAC3E,OAAO,eAAeC,sBACpBC,SAAsC,EACtCC,KAAa,EACbC,OAAe,EACfC,KAAa,EACbC,SAA+B;IAE/B,MAAMC,MAAMnB,eAAec,UAAUM,UAAU,CAAC,QAAQC,GAAG,CAACN,QAAQC;IACpE,OAAOF,UAAUQ,cAAc,CAAC,OAAOC;QACrC,MAAMC,WAAW,MAAMD,GAAGE,GAAG,CAACN;QAC9B,IAAI,CAACK,SAASE,MAAM,EAAE,OAAO;QAC7B,MAAMC,UAAUH,SAASC,GAAG,CAAC;QAC7B,IAAIE,CAAAA,2BAAAA,QAASV,KAAK,MAAKA,SAASW,OAA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IAAI;oBAClBC,OAAO1F,uBAAuByB;oBAC9BH,OAAOgD,MAAMhD,KAAK;gBACpB,GACA;oBAAEqE,WAAW;gBAAK;YAEtB;YACA,MAAMC,SAAS9E;YACf,MAAM+E,cAAcT,QAAQQ,SAAS,GAAGX,KAAKQ,IAAI,CAAC,IAAI,EAAEG,SAASR,MAAM,GAAGH,KAAKQ,IAAI;YACnF,MAAMK,WAAW,MAAMnF,OAAOgE,WAAWnB,aAAa;YACtD,IAAIsC,SAASC,MAAM,EAAE;gBACnB,MAAMC,SAAS,MAAMtF,KAAK;oBACxBuF,IAAIH;oBACJvE,SAAS0D,KAAKO,KAAK;oBACnBU,MAAML;oBACNM,SAAS;gBACX;gBACA,IAAIH,OAAOI,IAAI,EAAE,MAAMxF,QAAQyF,KAAK,CAAC,IAAMC;YAC7C;YACA,MAAMC,iBAAiB5B,WAAWlB,YAAY,GAC1C,AAAC,CAAA,MAAM9C,OAAO;gBAACgE,WAAWlB,YAAY;aAAC,CAAA,EAAG9C,MAAM,CAC9C,CAAC6F,UAAY,CAACV,SAAS/B,QAAQ,CAACyC,YAElC,EAAE;YACN,IAAID,eAAeR,MAAM,EAAE;gBACzB,MAAMC,SAAS,MAAMtF,KAAK;oBACxBuF,IAAIM;oBACJhF,SAAS2D,QAAQM,KAAK;oBACtBU,MAAMhB,QAAQO,IAAI;oBAClBU,SAAS;gBACX;gBACA,IAAIH,OAAOI,IAAI,EAAE,MAAMxF,QAAQyF,KAAK,CAAC,IAAMC;YAC7C;YACA9B,aAAa;QACf,EAAE,OAAOiC,OAAO;YACdC,QAAQD,KAAK,CAAC,gDAAgDnC,MAAMhD,KAAK,EAAEqB,SAASpB,OAAO,EAAEkF;QAC/F;IACF;IACA,OAAOjC;AACT"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/usage/ai-allotment-alerts.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 { buildRoute, Route } from '@aglyn/aglyn/app-utils/console-routes'\nimport { usageNotificationLevel } from '@aglyn/aglyn/app-utils/notifications'\nimport { platformConsoleOrigin } from '@aglyn/aglyn/app-utils/platform-brand'\nimport { sendEmail } from '@aglyn/shared-util-email'\nimport { withoutMailWithheldAccounts } from '@aglyn/tenant-data-admin/server/account-mail'\nimport { meterPlatformEmail } from '@aglyn/tenant-data-admin/server/email-metering'\nimport { filterSuppressedEmails } from '@aglyn/tenant-data-admin/server/email-suppression'\nimport { notifyUsers } from '@aglyn/tenant-data-admin/server/notifications'\nimport {\n aiAllotmentAlertCopy,\n type AiAllotmentStanding,\n type AiAllotmentThreshold,\n} from '../model/ai-allotments'\nimport { aiAllotmentRef } from './ai-allotments'\n\n/**\n * A SOFT allotment's 75, 80, 90 and 100% steps (AGL-2942, AGL-3431),\n * through the alert pipeline's two channels: the console notification every\n * usage threshold writes (`billing.usage`, to `users/{uid}/notifications`)\n * and the email beside it, sent past the platform suppression list and\n * metered as platform mail — the same primitives the usage-alert sweep\n * composes.\n *\n * Told when the request that finds the subject at a threshold is admitted,\n * rather than on the next daily sweep: an allotment is a line a manager drew\n * for one person or one site, and a day's delay is most of what a soft line\n * is for. The sweep is untouched.\n *\n * ## Who is told\n *\n * The workspace's owners and admins — the audience of every usage alert —\n * and, for a member's or a collaborator's allotment, the person it is for.\n * The person gets their own words, in the second person and without the\n * Billing link or the \"make it hard\" step, neither of which they can use.\n * Both name the workspace, and a collaborator's the site, because an owner\n * of two workspaces cannot tell from a figure which one it is about.\n *\n * ## Once per threshold per month\n *\n * The marker is `alerted: { month, threshold }` on the allotment itself,\n * claimed in a transaction before anything is sent, so two requests at the\n * line cannot both announce it. A write to the allotment clears the marker,\n * so a raised allotment announces its own next crossing.\n */\n\n/** A crossing to announce, as the reservation measured it. */\nexport interface AiAllotmentAlertInput {\n orgId: string\n /** The workspace's slug, for the Billing link; `null` omits the link. */\n orgSlug: string | null\n month: string\n alerts: ReadonlyArray<{ standing: AiAllotmentStanding; threshold: AiAllotmentThreshold }>\n}\n\n/** The pipeline's primitives, replaceable in a spec. */\nexport interface AiAllotmentAlertChannels {\n notify: typeof notifyUsers\n send: typeof sendEmail\n filter: typeof filterSuppressedEmails\n meter: typeof meterPlatformEmail\n /** The uids given, minus locked or disabled accounts (AGL-3418). */\n reachable: typeof withoutMailWithheldAccounts\n}\n\nconst DEFAULT_CHANNELS: AiAllotmentAlertChannels = {\n notify: notifyUsers,\n send: sendEmail,\n filter: filterSuppressedEmails,\n meter: meterPlatformEmail,\n reachable: withoutMailWithheldAccounts,\n}\n\n\n/** Take the marker for `threshold` this month; `false` when it was taken. */\nexport async function claimAiAllotmentAlert(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n subject: string,\n month: string,\n threshold: AiAllotmentThreshold,\n): Promise<boolean> {\n const ref = aiAllotmentRef(firestore.collection('orgs').doc(orgId), subject)\n return firestore.runTransaction(async (tx) => {\n const snapshot = await tx.get(ref)\n if (!snapshot.exists) return false\n const alerted = snapshot.get('alerted') as { month?: unknown; threshold?: unknown } | null\n if (alerted?.month === month && Number(alerted?.threshold) >= threshold) return false\n tx.set(ref, { alerted: { month, threshold } }, { merge: true })\n return true\n })\n}\n\ninterface Recipients {\n managerUids: string[]\n managerEmails: string[]\n subjectUid: string | null\n subjectEmail: string | null\n subjectName: string\n /** The workspace's name, for the copy. */\n workspaceName: string\n /** The site a collaborator's allotment is on, for the copy. */\n siteName: string\n}\n\n/** The name a site's managers know it by, then its address, then its id. */\nasync function siteName(\n firestore: FirebaseFirestore.Firestore,\n hostId: string,\n): Promise<string> {\n const host = await firestore.collection('hosts').doc(hostId).get()\n return (\n String(host.get('displayName') ?? '').trim() ||\n String(host.get('subdomain') ?? '').trim() ||\n hostId\n )\n}\n\nasync function recipientsFor(\n firestore: FirebaseFirestore.Firestore,\n orgId: string,\n standing: AiAllotmentStanding,\n reachable: AiAllotmentAlertChannels['reachable'],\n): Promise<Recipients> {\n const orgRef = firestore.collection('orgs').doc(orgId)\n const [org, members] = await Promise.all([orgRef.get(), orgRef.collection('members').get()])\n // A locked or disabled account is told nothing, by either channel; it is\n // still named when the alert is about it.\n const open = new Set(await reachable(members.docs.map((member) => member.id)))\n const managerUids: string[] = []\n const managerEmails: string[] = []\n let subjectEmail: string | null = null\n let subjectName = ''\n for (const member of members.docs) {\n const role = member.get('role')\n const email = String(member.get('email') ?? '').trim()\n if ((role === 'owner' || role === 'admin') && open.has(member.id)) {\n managerUids.push(member.id)\n if (email.includes('@')) managerEmails.push(email)\n }\n if (standing.uid && member.id === standing.uid) {\n subjectEmail = email.includes('@') && open.has(member.id) ? email : null\n subjectName = String(member.get('displayName') ?? '').trim() || email\n }\n }\n const site = standing.hostId ? await siteName(firestore, standing.hostId) : ''\n if (standing.scope === 'host') subjectName = site\n return {\n managerUids,\n managerEmails,\n subjectUid:\n standing.scope === 'host' || !standing.uid || !open.has(standing.uid)\n ? null\n : standing.uid,\n subjectEmail: standing.scope === 'host' ? null : subjectEmail,\n subjectName: subjectName || (standing.scope === 'host' ? 'A site' : 'A member'),\n workspaceName:\n String(org.get('name') ?? '').trim() ||\n String(org.get('slug') ?? '').trim() ||\n 'your workspace',\n siteName: site,\n }\n}\n\n/**\n * Announce every crossing the reservation found. Never throws, and answers\n * how many were announced — one failing crossing does not stop the next.\n */\nexport async function announceAiAllotmentAlerts(\n firestore: FirebaseFirestore.Firestore,\n input: AiAllotmentAlertInput,\n channels: Partial<AiAllotmentAlertChannels> = {},\n): Promise<number> {\n const { notify, send, filter, meter, reachable } = { ...DEFAULT_CHANNELS, ...channels }\n let announced = 0\n for (const { standing, threshold } of input.alerts) {\n try {\n const claimed = await claimAiAllotmentAlert(\n firestore,\n input.orgId,\n standing.subject,\n input.month,\n threshold,\n )\n if (!claimed) continue\n const recipients = await recipientsFor(firestore, input.orgId, standing, reachable)\n const words = {\n scope: standing.scope,\n threshold,\n used: standing.used,\n credits: standing.credits,\n name: recipients.subjectName,\n workspace: recipients.workspaceName,\n site: recipients.siteName,\n }\n const copy = aiAllotmentAlertCopy(words)\n const ownCopy = aiAllotmentAlertCopy({ ...words, reader: 'subject' })\n const link = input.orgSlug\n ? `${buildRoute(Route.MANAGE_BILLING_USAGE, { orgSlug: input.orgSlug })}#ai-allotments`\n : null\n // `skipEmail`: the email below is this crossing's email, so the\n // per-person channel does not send a second one to anybody who switched\n // billing email on (AGL-3431).\n await notify(\n recipients.managerUids,\n {\n type: 'billing.usage',\n title: copy.title,\n body: copy.body,\n level: usageNotificationLevel(threshold),\n orgId: input.orgId,\n ...(link ? { link } : {}),\n },\n { skipEmail: true },\n )\n if (recipients.subjectUid && !recipients.managerUids.includes(recipients.subjectUid)) {\n await notify(\n [recipients.subjectUid],\n {\n type: 'billing.usage',\n title: ownCopy.title,\n body: ownCopy.body,\n level: usageNotificationLevel(threshold),\n orgId: input.orgId,\n },\n { skipEmail: true },\n )\n }\n const origin = platformConsoleOrigin()\n const managerText = link && origin ? `${copy.body}\\n\\n${origin}${link}` : copy.body\n const managers = await filter(recipients.managerEmails)\n if (managers.length) {\n const result = await send({\n to: managers,\n subject: copy.title,\n text: managerText,\n context: 'ai-allotment-alert',\n })\n if (result.sent) await meter().catch(() => undefined)\n }\n const subjectAddress = recipients.subjectEmail\n ? (await filter([recipients.subjectEmail])).filter(\n (address) => !managers.includes(address),\n )\n : []\n if (subjectAddress.length) {\n const result = await send({\n to: subjectAddress,\n subject: ownCopy.title,\n text: ownCopy.body,\n context: 'ai-allotment-alert',\n })\n if (result.sent) await meter().catch(() => undefined)\n }\n announced += 1\n } catch (error) {\n console.error('[ai-allotments] announcing a crossing failed', input.orgId, standing.subject, error)\n }\n }\n return announced\n}\n"],"names":["buildRoute","Route","usageNotificationLevel","platformConsoleOrigin","sendEmail","withoutMailWithheldAccounts","meterPlatformEmail","filterSuppressedEmails","notifyUsers","aiAllotmentAlertCopy","aiAllotmentRef","DEFAULT_CHANNELS","notify","send","filter","meter","reachable","claimAiAllotmentAlert","firestore","orgId","subject","month","threshold","ref","collection","doc","runTransaction","tx","snapshot","get","exists","alerted","Number","set","merge","siteName","hostId","host","String","trim","recipientsFor","standing","org","orgRef","members","Promise","all","open","Set","docs","map","member","id","managerUids","managerEmails","subjectEmail","subjectName","role","email","has","push","includes","uid","site","scope","subjectUid","workspaceName","announceAiAllotmentAlerts","input","channels","announced","alerts","claimed","recipients","words","used","credits","name","workspace","copy","ownCopy","reader","link","orgSlug","MANAGE_BILLING_USAGE","type","title","body","level","skipEmail","origin","managerText","managers","length","result","to","text","context","sent","catch","undefined","subjectAddress","address","error","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,UAAU,EAAEC,KAAK,QAAQ,wCAAuC;AACzE,SAASC,sBAAsB,QAAQ,uCAAsC;AAC7E,SAASC,qBAAqB,QAAQ,wCAAuC;AAC7E,SAASC,SAAS,QAAQ,2BAA0B;AACpD,SAASC,2BAA2B,QAAQ,+CAA8C;AAC1F,SAASC,kBAAkB,QAAQ,iDAAgD;AACnF,SAASC,sBAAsB,QAAQ,oDAAmD;AAC1F,SAASC,WAAW,QAAQ,gDAA+C;AAC3E,SACEC,oBAAoB,QAGf,4BAAwB;AAC/B,SAASC,cAAc,QAAQ,qBAAiB;AAmDhD,MAAMC,mBAA6C;IACjDC,QAAQJ;IACRK,MAAMT;IACNU,QAAQP;IACRQ,OAAOT;IACPU,WAAWX;AACb;AAGA,2EAA2E,GAC3E,OAAO,eAAeY,sBACpBC,SAAsC,EACtCC,KAAa,EACbC,OAAe,EACfC,KAAa,EACbC,SAA+B;IAE/B,MAAMC,MAAMb,eAAeQ,UAAUM,UAAU,CAAC,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