@aglyn/plugins-ai 1.8.0 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/package.json +17 -17
  2. package/src/lib/activity/ai-activity.js +4 -2
  3. package/src/lib/activity/ai-activity.js.map +1 -1
  4. package/src/lib/components/ai-credits-card.component.d.ts +4 -3
  5. package/src/lib/components/ai-credits-card.component.js +13 -12
  6. package/src/lib/components/ai-credits-card.component.js.map +1 -1
  7. package/src/lib/components/ai-site-import-job.component.js +14 -5
  8. package/src/lib/components/ai-site-import-job.component.js.map +1 -1
  9. package/src/lib/components/ai-upsell-dialog.component.d.ts +2 -2
  10. package/src/lib/components/ai-upsell-dialog.component.js +3 -3
  11. package/src/lib/components/ai-upsell-dialog.component.js.map +1 -1
  12. package/src/lib/components/staff-org-ai-card.component.js +2 -2
  13. package/src/lib/components/staff-org-ai-card.component.js.map +1 -1
  14. package/src/lib/declarations.d.ts +2 -2
  15. package/src/lib/declarations.js +10 -9
  16. package/src/lib/declarations.js.map +1 -1
  17. package/src/lib/jobs/ai-site-import-compile.js +3 -0
  18. package/src/lib/jobs/ai-site-import-compile.js.map +1 -1
  19. package/src/lib/jobs/ai-site-import-document.js +6 -1
  20. package/src/lib/jobs/ai-site-import-document.js.map +1 -1
  21. package/src/lib/layout-language/ai-layout-compiler.js +38 -13
  22. package/src/lib/layout-language/ai-layout-compiler.js.map +1 -1
  23. package/src/lib/layout-language/ai-layout-language.d.ts +2 -0
  24. package/src/lib/layout-language/ai-layout-language.js.map +1 -1
  25. package/src/lib/model/ai-site-import-view.js +4 -3
  26. package/src/lib/model/ai-site-import-view.js.map +1 -1
  27. package/src/lib/model/ai-site-import.d.ts +2 -0
  28. package/src/lib/model/ai-site-import.js.map +1 -1
  29. package/src/lib/model/ai-upsell-copy.js +4 -3
  30. package/src/lib/model/ai-upsell-copy.js.map +1 -1
  31. package/src/lib/plan-entitlements.d.ts +3 -3
  32. package/src/lib/plan-entitlements.js +1 -1
  33. package/src/lib/plan-entitlements.js.map +1 -1
  34. package/src/lib/providers/model-choice.d.ts +6 -3
  35. package/src/lib/providers/model-choice.js +8 -4
  36. package/src/lib/providers/model-choice.js.map +1 -1
  37. package/src/lib/site-import/fixtures/site-import-fidelity-replay.d.ts +1 -1
  38. package/src/lib/site-import/fixtures/site-import-fidelity-replay.js +5 -1
  39. package/src/lib/site-import/fixtures/site-import-fidelity-replay.js.map +1 -1
  40. package/src/lib/site-import/site-import-layout.js +5 -1
  41. package/src/lib/site-import/site-import-layout.js.map +1 -1
  42. package/src/lib/usage/assist-credits.d.ts +5 -4
  43. package/src/lib/usage/assist-credits.js +5 -4
  44. package/src/lib/usage/assist-credits.js.map +1 -1
  45. package/src/lib/usage/staff-org-ai-view.js +6 -6
  46. package/src/lib/usage/staff-org-ai-view.js.map +1 -1
  47. package/src/lib/usage/staff-org-ai.d.ts +4 -4
  48. package/src/lib/usage/staff-org-ai.js +8 -7
  49. package/src/lib/usage/staff-org-ai.js.map +1 -1
  50. package/src/lib/usage/staff-org-usage-ai.js +2 -2
  51. package/src/lib/usage/staff-org-usage-ai.js.map +1 -1
@@ -26,10 +26,10 @@ import { useEffect, useState } from "react";
26
26
  import { AI_UPSELL_COPY, AI_UPSELL_CREATE_LABEL, aiUpsellLabel, aiUpsellOffer } from "../model/ai-upsell-copy.js";
27
27
  /**
28
28
  * "Create with AI" where generation is switched off for a workspace that
29
- * could buy an Aglyn AI tier (AGL-3601, AGL-3965). Since AGL-3965 every paid
29
+ * could buy Aglyn AI credits (AGL-3601, AGL-4144). Since AGL-3965 every paid
30
30
  * plan's own credits pay for generation, so this is reached only where a
31
31
  * per-org setting closed it. The shell mounts the entry with
32
- * `entitled={false}` only where a tier is sold to this workspace, and the
32
+ * `entitled={false}` only where credit blocks are sold to this workspace, and the
33
33
  * jobs route has said that is the one thing missing; the entry then keeps its
34
34
  * place on the page and opens this instead of the brief.
35
35
  */ // The entries' words are the model's, which the native apps' door reads too
@@ -37,7 +37,7 @@ import { AI_UPSELL_COPY, AI_UPSELL_CREATE_LABEL, aiUpsellLabel, aiUpsellOffer }
37
37
  export { AI_UPSELL_COPY, AI_UPSELL_CREATE_LABEL, aiUpsellLabel, aiUpsellOffer };
38
38
  /** The add-on's own section of the Create with AI guide (AGL-3660). */ const aiUpsellHelp = ()=>pluginDocsHelp('aiCreate', {
39
39
  anchor: '#without-the-add-on',
40
- excerpt: `On every paid plan, Create with AI runs on the AI credits the plan includes. Where it is switched off for a workspace, an ${aiAddonName()} tier switches it on; an owner or admin chooses one in Billing.`
40
+ excerpt: `On every paid plan, Create with AI runs on the AI credits the plan includes. Where it is switched off for a workspace, ${aiAddonName()} credits switch it on; an owner or admin adds them in Billing.`
41
41
  });
42
42
  export function AiUpsellDialog({ kind, open, onClose, upgrade }) {
43
43
  const copy = AI_UPSELL_COPY[kind];
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/components/ai-upsell-dialog.component.tsx"],"sourcesContent":["'use client'\n\n/**\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 { aiAddonName } from '@aglyn/aglyn'\nimport { trackEvent } from '@aglyn/aglyn/app-utils/analytics-events'\nimport type { ConsoleWidgetUpgrade } from '@aglyn/aglyn/plugin-manager/feature-plugins'\nimport { mdiCreation } from '@aglyn/shared-data-mdi'\nimport { pluginDocsHelp } from '@aglyn/aglyn/app-utils/docs-help'\nimport { HelpTip, MdiIcon } from '@aglyn/shared-ui-jsx'\nimport {\n Button,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n Stack,\n Typography,\n} from '@mui/material'\nimport { useEffect, useState, type ReactNode } from 'react'\nimport {\n AI_UPSELL_COPY,\n AI_UPSELL_CREATE_LABEL,\n aiUpsellLabel,\n aiUpsellOffer,\n type AiUpsellKind,\n} from '../model/ai-upsell-copy'\n\n/**\n * \"Create with AI\" where generation is switched off for a workspace that\n * could buy an Aglyn AI tier (AGL-3601, AGL-3965). Since AGL-3965 every paid\n * plan's own credits pay for generation, so this is reached only where a\n * per-org setting closed it. The shell mounts the entry with\n * `entitled={false}` only where a tier is sold to this workspace, and the\n * jobs route has said that is the one thing missing; the entry then keeps its\n * place on the page and opens this instead of the brief.\n */\n\n// The entries' words are the model's, which the native apps' door reads too\n// (AGL-3854); re-exported for this dialog's existing readers.\nexport { AI_UPSELL_COPY, AI_UPSELL_CREATE_LABEL, aiUpsellLabel, aiUpsellOffer }\nexport type { AiUpsellCopy, AiUpsellKind } from '../model/ai-upsell-copy'\n\nexport interface AiUpsellDialogProps {\n kind: AiUpsellKind\n open: boolean\n onClose: () => void\n upgrade: ConsoleWidgetUpgrade\n}\n\n/** The add-on's own section of the Create with AI guide (AGL-3660). */\nconst aiUpsellHelp = () =>\n pluginDocsHelp('aiCreate', {\n anchor: '#without-the-add-on',\n excerpt: `On every paid plan, Create with AI runs on the AI credits the plan includes. Where it is switched off for a workspace, an ${aiAddonName()} tier switches it on; an owner or admin chooses one in Billing.`,\n })\n\nexport function AiUpsellDialog({ kind, open, onClose, upgrade }: AiUpsellDialogProps) {\n const copy = AI_UPSELL_COPY[kind]\n const { canManageBilling, billingHref } = upgrade\n\n // Counted once per opening: the denominator the click is a rate against.\n useEffect(() => {\n if (open) trackEvent('ai_upsell_shown', { kind, can_manage: canManageBilling })\n }, [open, kind, canManageBilling])\n\n return (\n <Dialog open={open} onClose={onClose} fullWidth maxWidth=\"xs\">\n <DialogTitle sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>\n {copy.title}\n <HelpTip {...aiUpsellHelp()} />\n </DialogTitle>\n <DialogContent>\n <Stack spacing={2}>\n <Typography variant=\"body2\">{copy.does}</Typography>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {aiUpsellOffer(canManageBilling, kind === 'insight' ? copy.title : AI_UPSELL_CREATE_LABEL)}\n </Typography>\n </Stack>\n </DialogContent>\n <DialogActions>\n <Button onClick={onClose}>{canManageBilling ? 'Not now' : 'Close'}</Button>\n {canManageBilling ? (\n <Button\n variant=\"contained\"\n href={billingHref}\n onClick={() => trackEvent('ai_upsell_clicked', { kind })}\n >\n {`Add ${aiAddonName()}`}\n </Button>\n ) : null}\n </DialogActions>\n </Dialog>\n )\n}\n\n/**\n * The entry itself on a plan without the add-on: the same button, label and\n * icon as the entitled entry, opening {@link AiUpsellDialog}. Every entry that\n * draws it renders from the shell's client-side gates alone and asks the\n * server nothing until it is used (AGL-3601).\n */\nexport function AiUpsellButton({\n kind,\n upgrade,\n label,\n}: {\n kind: AiUpsellKind\n upgrade: ConsoleWidgetUpgrade\n /** The entitled entry's own label, when it is not the kind's. */\n label?: string\n}): ReactNode {\n const [open, setOpen] = useState(false)\n return (\n <>\n <Button\n size=\"small\"\n variant=\"outlined\"\n startIcon={<MdiIcon path={mdiCreation.path} />}\n onClick={() => setOpen(true)}\n >\n {label ?? aiUpsellLabel(kind)}\n </Button>\n <AiUpsellDialog kind={kind} open={open} onClose={() => setOpen(false)} upgrade={upgrade} />\n </>\n )\n}\n"],"names":["aiAddonName","trackEvent","mdiCreation","pluginDocsHelp","HelpTip","MdiIcon","Button","Dialog","DialogActions","DialogContent","DialogTitle","Stack","Typography","useEffect","useState","AI_UPSELL_COPY","AI_UPSELL_CREATE_LABEL","aiUpsellLabel","aiUpsellOffer","aiUpsellHelp","anchor","excerpt","AiUpsellDialog","kind","open","onClose","upgrade","copy","canManageBilling","billingHref","can_manage","fullWidth","maxWidth","sx","display","alignItems","gap","title","spacing","variant","does","color","onClick","href","AiUpsellButton","label","setOpen","size","startIcon","path"],"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AA,MAACE;oBAAM2B,SAAS;;sCACd,KAAC1B;4BAAW2B,SAAQ;sCAASZ,KAAKa,IAAI;;sCACtC,KAAC5B;4BAAW2B,SAAQ;4BAAQE,OAAM;sCAC/BvB,cAAcU,kBAAkBL,SAAS,YAAYI,KAAKU,KAAK,GAAGrB;;;;;0BAIzE,MAACR;;kCACC,KAACF;wBAAOoC,SAASjB;kCAAUG,mBAAmB,YAAY;;oBACzDA,iCACC,KAACtB;wBACCiC,SAAQ;wBACRI,MAAMd;wBACNa,SAAS,IAAMzC,WAAW,qBAAqB;gCAAEsB;4BAAK;kCAErD,CAAC,IAAI,EAAEvB,eAAe;yBAEvB;;;;;AAIZ;AAEA;;;;;CAKC,GACD,OAAO,SAAS4C,eAAe,EAC7BrB,IAAI,EACJG,OAAO,EACPmB,KAAK,EAMN;IACC,MAAM,CAACrB,MAAMsB,QAAQ,GAAGhC,SAAS;IACjC,qBACE;;0BACE,KAACR;gBACCyC,MAAK;gBACLR,SAAQ;gBACRS,yBAAW,KAAC3C;oBAAQ4C,MAAM/C,YAAY+C,IAAI;;gBAC1CP,SAAS,IAAMI,QAAQ;0BAEtBD,gBAAAA,QAAS5B,cAAcM;;0BAE1B,KAACD;gBAAeC,MAAMA;gBAAMC,MAAMA;gBAAMC,SAAS,IAAMqB,QAAQ;gBAAQpB,SAASA;;;;AAGtF"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/components/ai-upsell-dialog.component.tsx"],"sourcesContent":["'use client'\n\n/**\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 { aiAddonName } from '@aglyn/aglyn'\nimport { trackEvent } from '@aglyn/aglyn/app-utils/analytics-events'\nimport type { ConsoleWidgetUpgrade } from '@aglyn/aglyn/plugin-manager/feature-plugins'\nimport { mdiCreation } from '@aglyn/shared-data-mdi'\nimport { pluginDocsHelp } from '@aglyn/aglyn/app-utils/docs-help'\nimport { HelpTip, MdiIcon } from '@aglyn/shared-ui-jsx'\nimport {\n Button,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n Stack,\n Typography,\n} from '@mui/material'\nimport { useEffect, useState, type ReactNode } from 'react'\nimport {\n AI_UPSELL_COPY,\n AI_UPSELL_CREATE_LABEL,\n aiUpsellLabel,\n aiUpsellOffer,\n type AiUpsellKind,\n} from '../model/ai-upsell-copy'\n\n/**\n * \"Create with AI\" where generation is switched off for a workspace that\n * could buy Aglyn AI credits (AGL-3601, AGL-4144). Since AGL-3965 every paid\n * plan's own credits pay for generation, so this is reached only where a\n * per-org setting closed it. The shell mounts the entry with\n * `entitled={false}` only where credit blocks are sold to this workspace, and the\n * jobs route has said that is the one thing missing; the entry then keeps its\n * place on the page and opens this instead of the brief.\n */\n\n// The entries' words are the model's, which the native apps' door reads too\n// (AGL-3854); re-exported for this dialog's existing readers.\nexport { AI_UPSELL_COPY, AI_UPSELL_CREATE_LABEL, aiUpsellLabel, aiUpsellOffer }\nexport type { AiUpsellCopy, AiUpsellKind } from '../model/ai-upsell-copy'\n\nexport interface AiUpsellDialogProps {\n kind: AiUpsellKind\n open: boolean\n onClose: () => void\n upgrade: ConsoleWidgetUpgrade\n}\n\n/** The add-on's own section of the Create with AI guide (AGL-3660). */\nconst aiUpsellHelp = () =>\n pluginDocsHelp('aiCreate', {\n anchor: '#without-the-add-on',\n excerpt: `On every paid plan, Create with AI runs on the AI credits the plan includes. Where it is switched off for a workspace, ${aiAddonName()} credits switch it on; an owner or admin adds them in Billing.`,\n })\n\nexport function AiUpsellDialog({ kind, open, onClose, upgrade }: AiUpsellDialogProps) {\n const copy = AI_UPSELL_COPY[kind]\n const { canManageBilling, billingHref } = upgrade\n\n // Counted once per opening: the denominator the click is a rate against.\n useEffect(() => {\n if (open) trackEvent('ai_upsell_shown', { kind, can_manage: canManageBilling })\n }, [open, kind, canManageBilling])\n\n return (\n <Dialog open={open} onClose={onClose} fullWidth maxWidth=\"xs\">\n <DialogTitle sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>\n {copy.title}\n <HelpTip {...aiUpsellHelp()} />\n </DialogTitle>\n <DialogContent>\n <Stack spacing={2}>\n <Typography variant=\"body2\">{copy.does}</Typography>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {aiUpsellOffer(canManageBilling, kind === 'insight' ? copy.title : AI_UPSELL_CREATE_LABEL)}\n </Typography>\n </Stack>\n </DialogContent>\n <DialogActions>\n <Button onClick={onClose}>{canManageBilling ? 'Not now' : 'Close'}</Button>\n {canManageBilling ? (\n <Button\n variant=\"contained\"\n href={billingHref}\n onClick={() => trackEvent('ai_upsell_clicked', { kind })}\n >\n {`Add ${aiAddonName()}`}\n </Button>\n ) : null}\n </DialogActions>\n </Dialog>\n )\n}\n\n/**\n * The entry itself on a plan without the add-on: the same button, label and\n * icon as the entitled entry, opening {@link AiUpsellDialog}. Every entry that\n * draws it renders from the shell's client-side gates alone and asks the\n * server nothing until it is used (AGL-3601).\n */\nexport function AiUpsellButton({\n kind,\n upgrade,\n label,\n}: {\n kind: AiUpsellKind\n upgrade: ConsoleWidgetUpgrade\n /** The entitled entry's own label, when it is not the kind's. */\n label?: string\n}): ReactNode {\n const [open, setOpen] = useState(false)\n return (\n <>\n <Button\n size=\"small\"\n variant=\"outlined\"\n startIcon={<MdiIcon path={mdiCreation.path} />}\n onClick={() => setOpen(true)}\n >\n {label ?? aiUpsellLabel(kind)}\n </Button>\n <AiUpsellDialog kind={kind} open={open} onClose={() => setOpen(false)} upgrade={upgrade} />\n </>\n )\n}\n"],"names":["aiAddonName","trackEvent","mdiCreation","pluginDocsHelp","HelpTip","MdiIcon","Button","Dialog","DialogActions","DialogContent","DialogTitle","Stack","Typography","useEffect","useState","AI_UPSELL_COPY","AI_UPSELL_CREATE_LABEL","aiUpsellLabel","aiUpsellOffer","aiUpsellHelp","anchor","excerpt","AiUpsellDialog","kind","open","onClose","upgrade","copy","canManageBilling","billingHref","can_manage","fullWidth","maxWidth","sx","display","alignItems","gap","title","spacing","variant","does","color","onClick","href","AiUpsellButton","label","setOpen","size","startIcon","path"],"mappings":"AAAA;;;AAEA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,WAAW,QAAQ,eAAc;AAC1C,SAASC,UAAU,QAAQ,0CAAyC;AAEpE,SAASC,WAAW,QAAQ,yBAAwB;AACpD,SAASC,cAAc,QAAQ,mCAAkC;AACjE,SAASC,OAAO,EAAEC,OAAO,QAAQ,uBAAsB;AACvD,SACEC,MAAM,EACNC,MAAM,EACNC,aAAa,EACbC,aAAa,EACbC,WAAW,EACXC,KAAK,EACLC,UAAU,QACL,gBAAe;AACtB,SAASC,SAAS,EAAEC,QAAQ,QAAwB,QAAO;AAC3D,SACEC,cAAc,EACdC,sBAAsB,EACtBC,aAAa,EACbC,aAAa,QAER,6BAAyB;AAEhC;;;;;;;;CAQC,GAED,4EAA4E;AAC5E,8DAA8D;AAC9D,SAASH,cAAc,EAAEC,sBAAsB,EAAEC,aAAa,EAAEC,aAAa,GAAE;AAU/E,qEAAqE,GACrE,MAAMC,eAAe,IACnBhB,eAAe,YAAY;QACzBiB,QAAQ;QACRC,SAAS,CAAC,uHAAuH,EAAErB,cAAc,8DAA8D,CAAC;IAClN;AAEF,OAAO,SAASsB,eAAe,EAAEC,IAAI,EAAEC,IAAI,EAAEC,OAAO,EAAEC,OAAO,EAAuB;IAClF,MAAMC,OAAOZ,cAAc,CAACQ,KAAK;IACjC,MAAM,EAAEK,gBAAgB,EAAEC,WAAW,EAAE,GAAGH;IAE1C,yEAAyE;IACzEb,UAAU;QACR,IAAIW,MAAMvB,WAAW,mBAAmB;YAAEsB;YAAMO,YAAY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19
- import { AI_TIERS } from "@aglyn/aglyn/app-utils/plan-entitlements";
19
+ import { aiCreditBlocksLabel } from "@aglyn/aglyn/app-utils/ai-credit-blocks";
20
20
  import { buildRoute, Route } from "@aglyn/aglyn/app-utils/console-routes";
21
21
  import { pluginDocsHelp } from "@aglyn/aglyn/app-utils/docs-help";
22
22
  import { mdiOpenInNew } from "@aglyn/shared-data-mdi";
@@ -566,7 +566,7 @@ const StaffOrgAiCard = ({ orgId })=>{
566
566
  /*#__PURE__*/ _jsx(Chip, {
567
567
  size: "small",
568
568
  color: data.addon.on ? 'primary' : 'default',
569
- label: data.addon.on ? `${name}${data.addon.tier ? ` ${AI_TIERS[data.addon.tier].label}` : ''} on` : `${name} off`
569
+ label: data.addon.on ? `${name}${data.addon.blocks > 0 ? ` credits, ${aiCreditBlocksLabel(data.addon.blocks)}` : ''} on` : `${name} off`
570
570
  }),
571
571
  data.addon.priceUsd !== null ? /*#__PURE__*/ _jsx(Typography, {
572
572
  variant: "body2",
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/components/staff-org-ai-card.component.tsx"],"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'use client'\n\nimport { aiAddonName } from '@aglyn/aglyn'\nimport { AI_TIERS } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport { buildRoute, Route } from '@aglyn/aglyn/app-utils/console-routes'\nimport { pluginDocsHelp } from '@aglyn/aglyn/app-utils/docs-help'\nimport { mdiOpenInNew } from '@aglyn/shared-data-mdi'\nimport { AppLink, CardDisplay } from '@aglyn/shared-ui-jsx'\nimport {\n ListRowActions,\n ListTable,\n listActionsColumn,\n} from '@aglyn/shared-ui-jsx/components/list-table.component'\nimport { ScrollTable } from '@aglyn/shared-ui-jsx/components/scroll-table.component'\nimport { TABLE_ROW_HEIGHT } from '@aglyn/shared-ui-jsx/const/table-pagination'\nimport { useUser } from '@aglyn/tenant-feature-instance'\nimport { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\nimport {\n Alert,\n Chip,\n Stack,\n TableBody,\n TableCell,\n TableHead,\n TableRow,\n Typography,\n} from '@mui/material'\nimport type { GridColDef } from '@mui/x-data-grid'\nimport { useRouter } from 'next/navigation'\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport type {\n StaffOrgAiJob,\n StaffOrgAiJobs,\n StaffOrgAiRefusals,\n StaffOrgAiResponse,\n StaffOrgAiTokens,\n StaffOrgAiUser,\n} from '../usage/staff-org-ai'\nimport {\n allowanceSentence,\n credits,\n marginTone,\n overageStateSentence,\n poolPartsSentence,\n rate,\n refusalChips,\n tokenCount,\n usd,\n JOB_CHIP_STATUSES,\n} from '../usage/staff-org-ai-view'\nimport {\n StaffCreditReturnActions,\n StaffCreditReturnDialog,\n} from './staff-ai-credit-return.component'\n\n/**\n * THE STAFF AI CARD (AGL-2930): everything about one org's AI usage on the\n * page staff already open to look at that org.\n *\n * Read through `/api/ai/admin/org`, one request on mount. Every figure on it\n * is the route's, and every figure the route serves is composed from the\n * same helpers the meter refuses with — see `usage/staff-org-ai.ts`. This\n * file only lays them out.\n *\n * ## What each section is for\n *\n * - **Add-on** — is the org paying for AI, at what, since when.\n * - **Credit pool** — the band as three NAMED parts, because \"why does\n * this org have 13,000 credits\" has three answers (the plan, an override,\n * the add-on) and a single total cannot say which.\n * - **Overage** — what is past the band, what it is sold at, and the two\n * controls the org itself holds over it.\n * - **Refusals** — how often, and why, the gate said no this month.\n * - **Jobs** and **Top users** — the generative and per-person halves,\n * each of which says plainly when its rollup has nothing yet.\n * - **Tokens** — what each kind of request costs per request, what it\n * sends and generates, and how much of its prompt the cache served.\n * - **Margin** — spend against what AI brings in, red when it is over.\n * - **Actions** — where the override editor and the AI pause live.\n *\n * The header carries the card's two acts (AGL-3595): give credits back to\n * the band (and, on a Free workspace, to the owner's allowance), or reset\n * the month — and each recent job offers the same give-back, prefilled with\n * that job's spend.\n */\n\nconst when = (iso: string | null): string =>\n iso ? new Date(iso).toLocaleDateString() : '—'\n\nfunction RefusalsRow({ refusals }: { refusals: StaffOrgAiRefusals }) {\n return (\n <Stack direction=\"row\" spacing={1} useFlexGap sx={{ flexWrap: 'wrap' }}>\n {refusalChips(refusals).map((chip) => (\n <Chip\n key={chip.label}\n size=\"small\"\n variant={chip.count > 0 ? 'filled' : 'outlined'}\n color={chip.count > 0 ? 'warning' : 'default'}\n label={`${chip.label} ${chip.count.toLocaleString()}`}\n />\n ))}\n </Stack>\n )\n}\n\nfunction JobsSection({\n jobs,\n onGiveBack,\n}: {\n jobs: StaffOrgAiJobs | null\n onGiveBack: (job: StaffOrgAiJob) => void\n}) {\n const columns = useMemo(() => jobColumns(onGiveBack), [onGiveBack])\n if (jobs === null) {\n return (\n <Alert severity=\"warning\">\n {'Could not read the generation jobs — a failed read, not an idle org.'}\n </Alert>\n )\n }\n const total = Object.values(jobs.counts).reduce((sum, n) => sum + n, 0)\n if (total === 0) {\n return (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'No generation jobs yet.'}\n </Typography>\n )\n }\n return (\n <Stack spacing={1}>\n <Stack direction=\"row\" spacing={1} useFlexGap sx={{ flexWrap: 'wrap' }}>\n {JOB_CHIP_STATUSES.map((status) => (\n <Chip\n key={status}\n size=\"small\"\n color={\n status === 'failed' && jobs.counts[status] > 0\n ? 'error'\n : (status === 'needs_input' || status === 'needs_review') &&\n jobs.counts[status] > 0\n ? 'warning'\n : 'default'\n }\n label={`${status.replace('_', ' ')} ${jobs.counts[status]}`}\n />\n ))}\n <Chip size=\"small\" variant=\"outlined\" label={`done ${jobs.counts.done}`} />\n </Stack>\n {jobs.truncated ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Counted from the newest jobs only — these counts are a floor.'}\n </Typography>\n ) : null}\n {/* A record list: the grid scrolls its own columns, so a job id and a\n starter's uid never push the card's content past its edge. */}\n <ListTable\n rows={jobs.recent}\n columns={columns}\n getRowId={(job: StaffOrgAiJob) => job.id}\n rowHeight={TABLE_ROW_HEIGHT}\n noRowsLabel=\"No recent jobs\"\n // The route's ten newest jobs: a bounded readout, so no filter over\n // the rows it holds (AGL-3321).\n disableColumnFilter\n quickFilter={false}\n />\n </Stack>\n )\n}\n\n/**\n * The recent jobs, one column per fact. Who started a job is a column of\n * its own rather than a link tucked beside the date, so it sorts like the\n * rest; the credits sort by what was SPENT, which is the figure the\n * pool was charged. The row's action gives that spend back (AGL-3595).\n */\nconst jobColumns = (\n onGiveBack: (job: StaffOrgAiJob) => void,\n): GridColDef<StaffOrgAiJob>[] => [\n {\n field: 'id',\n headerName: 'Job',\n flex: 1,\n minWidth: 200,\n renderCell: ({ row }) => (\n <Typography variant=\"body2\" noWrap title={row.id} sx={{ fontFamily: 'monospace' }}>\n {row.id}\n </Typography>\n ),\n },\n {\n field: 'kind',\n headerName: 'Kind',\n width: 120,\n valueFormatter: (value: string) => value || '—',\n },\n {\n field: 'status',\n headerName: 'Status',\n width: 130,\n valueFormatter: (value: string) => String(value ?? '').replace('_', ' '),\n },\n {\n field: 'creditsSpent',\n headerName: 'Credits',\n type: 'number',\n align: 'right',\n headerAlign: 'right',\n width: 140,\n valueFormatter: (value: number, row) =>\n `${credits(value)} / ${credits(row.creditsReserved)}`,\n },\n {\n field: 'createdAt',\n headerName: 'Started',\n width: 120,\n valueFormatter: (value: string | null) => when(value),\n },\n {\n field: 'createdBy',\n headerName: 'Started by',\n flex: 1,\n minWidth: 240,\n renderCell: ({ row }) =>\n row.createdBy ? (\n <AppLink\n href={buildRoute(Route.ADMIN_USER_DETAIL, { uid: row.createdBy })}\n variant=\"body2\"\n underline=\"hover\"\n noWrap\n sx={{ fontFamily: 'monospace' }}\n >\n {row.createdBy}\n </AppLink>\n ) : (\n '—'\n ),\n },\n listActionsColumn((row: StaffOrgAiJob) => (\n <ListRowActions\n label={row.id}\n items={[\n {\n key: 'give-back',\n label: 'Give back this job’s credits',\n disabled: row.creditsSpent <= 0,\n disabledReason: row.creditsSpent <= 0 ? 'This job spent no credits.' : undefined,\n onClick: () => onGiveBack(row),\n },\n ]}\n />\n )),\n]\n\n/** The month's tokens, and what each kind of request spends of them (AGL-2937). */\nfunction TokensSection({ tokens }: { tokens: StaffOrgAiTokens }) {\n const { total } = tokens\n return (\n <Stack spacing={1}>\n <Stack direction=\"row\" spacing={1} useFlexGap sx={{ alignItems: 'center', flexWrap: 'wrap' }}>\n <Typography variant=\"body2\">\n {`${tokenCount(total.input)} sent · ${tokenCount(total.cached)} read from cache · ${tokenCount(total.cacheWrite)} written to cache · ${tokenCount(total.output)} generated`}\n </Typography>\n <Chip\n size=\"small\"\n color={tokens.cacheHitRate != null && tokens.cacheHitRate >= 0.5 ? 'success' : 'default'}\n label={`cache hit rate ${rate(tokens.cacheHitRate)}`}\n />\n </Stack>\n {tokens.kinds.length === 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'No model requests recorded by kind this month.'}\n </Typography>\n ) : (\n <ScrollTable size=\"small\">\n <TableHead>\n <TableRow>\n <TableCell>{'Kind'}</TableCell>\n <TableCell align=\"right\">{'Requests'}</TableCell>\n <TableCell align=\"right\">{'Per request'}</TableCell>\n <TableCell align=\"right\">{'Sent'}</TableCell>\n <TableCell align=\"right\">{'From cache'}</TableCell>\n <TableCell align=\"right\">{'Generated'}</TableCell>\n <TableCell align=\"right\">{'Cache hit'}</TableCell>\n </TableRow>\n </TableHead>\n <TableBody>\n {tokens.kinds.map((row) => (\n <TableRow key={row.kind}>\n <TableCell>{row.kind}</TableCell>\n <TableCell align=\"right\">{row.requests.toLocaleString()}</TableCell>\n <TableCell align=\"right\">{usd(row.costPerRequestUsd)}</TableCell>\n <TableCell align=\"right\">{tokenCount(row.tokens.input)}</TableCell>\n <TableCell align=\"right\">{tokenCount(row.tokens.cached)}</TableCell>\n <TableCell align=\"right\">{tokenCount(row.tokens.output)}</TableCell>\n <TableCell align=\"right\">{rate(row.cacheHitRate)}</TableCell>\n </TableRow>\n ))}\n </TableBody>\n </ScrollTable>\n )}\n </Stack>\n )\n}\n\n/**\n * The month's top spenders, one row per person. The row opens the account;\n * the uid rides beneath the roster's name because two people can share one.\n */\nfunction TopUsersSection({ users }: { users: StaffOrgAiUser[] }) {\n const router = useRouter()\n const columns = useMemo<GridColDef<StaffOrgAiUser>[]>(\n () => [\n {\n field: 'name',\n headerName: 'Person',\n flex: 1,\n minWidth: 220,\n renderCell: ({ row }) => (\n <Stack sx={{ minWidth: 0 }}>\n <Typography variant=\"body2\" noWrap title={row.name}>\n {row.name}\n </Typography>\n {row.name !== row.uid ? (\n <Typography\n variant=\"caption\"\n color=\"text.secondary\"\n noWrap\n sx={{ fontFamily: 'monospace' }}\n >\n {row.uid}\n </Typography>\n ) : null}\n </Stack>\n ),\n },\n {\n field: 'credits',\n headerName: 'Credits',\n type: 'number',\n align: 'right',\n headerAlign: 'right',\n width: 110,\n valueFormatter: (value: number) => credits(value),\n },\n {\n field: 'share',\n headerName: 'Share',\n type: 'number',\n align: 'right',\n headerAlign: 'right',\n width: 90,\n valueFormatter: (value: number) => `${Math.round(value * 100)}%`,\n },\n {\n field: 'estCostUsd',\n headerName: 'Provider $',\n type: 'number',\n align: 'right',\n headerAlign: 'right',\n width: 120,\n valueFormatter: (value: number) => usd(value),\n },\n {\n field: 'requests',\n headerName: 'Requests',\n type: 'number',\n align: 'right',\n headerAlign: 'right',\n width: 110,\n valueFormatter: (value: number) => value.toLocaleString(),\n },\n {\n field: 'refusals',\n headerName: 'Refusals',\n type: 'number',\n align: 'right',\n headerAlign: 'right',\n width: 110,\n valueFormatter: (value: number) => value.toLocaleString(),\n },\n listActionsColumn((row: StaffOrgAiUser) => (\n <ListRowActions\n label={row.name}\n quick={{\n icon: mdiOpenInNew.path,\n label: 'View account',\n newTab: true,\n to: buildRoute(Route.ADMIN_USER_DETAIL, { uid: row.uid }),\n }}\n items={[]}\n />\n )),\n ],\n [],\n )\n return (\n <ListTable\n rows={users}\n columns={columns}\n getRowId={(row: StaffOrgAiUser) => row.uid}\n rowHeight={TABLE_ROW_HEIGHT}\n onOpen={(uid) => router.push(buildRoute(Route.ADMIN_USER_DETAIL, { uid }))}\n // The route's ten dearest members: a bounded readout, so no filter\n // over the rows it holds (AGL-3321).\n disableColumnFilter\n quickFilter={false}\n />\n )\n}\n\nconst StaffOrgAiCard = ({ orgId }: { orgId: string }) => {\n const { data: user } = useUser()\n // Keyed on who is signed in, not on the user object's identity.\n const signedInUid = user?.uid ?? null\n const userRef = useRef(user)\n userRef.current = user\n const [data, setData] = useState<StaffOrgAiResponse | null>(null)\n const [ready, setReady] = useState(false)\n const [error, setError] = useState<string | null>(null)\n // Bumped after a give-back, so the card re-reads the figures it changed.\n const [version, setVersion] = useState(0)\n const [notice, setNotice] = useState<string | null>(null)\n const [returning, setReturning] = useState<{\n mode: 'give' | 'reset'\n jobId?: string\n jobCredits?: number\n } | null>(null)\n const giveBackJob = useCallback(\n (job: StaffOrgAiJob) =>\n setReturning({ mode: 'give', jobId: job.id, jobCredits: job.creditsSpent }),\n [],\n )\n\n useEffect(() => {\n // Mounted only for a confirmed staff reader — the `staffOrg` zone sits\n // inside the page's `StaffOnly`, which renders nothing while the claim\n // loads — because the route records an access row on every successful\n // open, and an open the page did not mean to make would be an access\n // nobody made.\n const user = userRef.current\n if (!orgId || !signedInUid || !user) return undefined\n let active = true\n setReady(false)\n setError(null)\n void (async () => {\n try {\n const response = await authorizedFetch(\n user,\n `/api/ai/admin/org?orgId=${encodeURIComponent(orgId)}`,\n )\n const payload = await response.json().catch(() => null)\n if (!active) return\n if (!response.ok) {\n setError(payload?.error ?? 'AI lookup failed')\n setData(null)\n } else {\n setData(payload as StaffOrgAiResponse)\n }\n } catch {\n if (active) {\n setError('AI lookup failed')\n setData(null)\n }\n } finally {\n if (active) setReady(true)\n }\n })()\n return () => {\n active = false\n }\n }, [orgId, signedInUid, version])\n\n const name = aiAddonName()\n return (\n <CardDisplay\n header={name}\n help={pluginDocsHelp('aiMonitoring', {\n anchor: '#the-ai-card',\n excerpt:\n 'The add-on, the credit pool and its parts, this month’s overage and refusals, generation jobs, tokens and the cache hit rate by kind, the people spending the most, and the margin — for this organization.',\n })}\n HeaderProps={{\n action: (\n <StaffCreditReturnActions\n disabled={!data}\n onGive={() => setReturning({ mode: 'give' })}\n onReset={() => setReturning({ mode: 'reset' })}\n />\n ),\n }}\n contentGutterX\n contentGutterY\n >\n {data ? (\n <StaffCreditReturnDialog\n open={returning !== null}\n mode={returning?.mode ?? 'give'}\n target={{ orgId }}\n workspace={{ used: data.pool.usedCredits, limit: data.pool.totalCredits }}\n account={\n data.account\n ? { used: data.account.usedCredits, limit: data.account.limitCredits }\n : null\n }\n jobId={returning?.jobId ?? null}\n jobCredits={returning?.jobCredits ?? null}\n onClose={() => setReturning(null)}\n onReturned={(message) => {\n setReturning(null)\n setNotice(message)\n setVersion((current) => current + 1)\n }}\n />\n ) : null}\n {notice ? (\n <Alert severity=\"success\" onClose={() => setNotice(null)} sx={{ mb: 2 }}>\n {notice}\n </Alert>\n ) : null}\n {!ready ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Loading…'}\n </Typography>\n ) : error || !data ? (\n <Alert severity=\"warning\">\n {`Could not read this organization’s AI usage — ${error ?? 'a failed read'}, not zero usage.`}\n </Alert>\n ) : (\n <Stack spacing={2}>\n {/* Add-on */}\n <Stack spacing={0.5}>\n <Typography variant=\"overline\" color=\"text.secondary\">\n {'Add-on'}\n </Typography>\n <Stack useFlexGap direction=\"row\" spacing={1} sx={{ alignItems: 'center', flexWrap: 'wrap' }}>\n <Chip\n size=\"small\"\n color={data.addon.on ? 'primary' : 'default'}\n label={\n data.addon.on\n ? `${name}${data.addon.tier ? ` ${AI_TIERS[data.addon.tier].label}` : ''} on`\n : `${name} off`\n }\n />\n {data.addon.priceUsd !== null ? (\n <Typography variant=\"body2\">\n {`${usd(data.addon.priceUsd)}/mo`}\n </Typography>\n ) : null}\n {data.addon.on ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {data.addon.since\n ? `since ${when(data.addon.since)}`\n : data.addon.sinceSource === 'unavailable'\n ? 'since — (Stripe not reachable)'\n : 'since — (no subscription item)'}\n </Typography>\n ) : null}\n </Stack>\n </Stack>\n\n {/* Credit pool */}\n <Stack spacing={0.5}>\n <Typography variant=\"overline\" color=\"text.secondary\">\n {`Credit pool · ${data.month}`}\n </Typography>\n {data.pool.totalCredits === null && data.pool.uncapped ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Uncapped staff comp — no AI credit band. Bounded only by the message cap and an operator’s explicit spend ceiling.'}\n </Typography>\n ) : data.pool.totalCredits === null ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'No AI credit band on this plan — bounded by the message cap and the operator backstop.'}\n </Typography>\n ) : (\n <Typography variant=\"body2\">\n {`${credits(data.pool.totalCredits)} credits = ${poolPartsSentence(data.pool, name)}`}\n </Typography>\n )}\n <Typography variant=\"body2\">\n {`Used ${credits(data.pool.usedCredits)} credits (${usd(data.pool.providerUsd)} provider spend)`}\n {data.pool.remainingCredits !== null\n ? ` · ${credits(data.pool.remainingCredits)} remaining`\n : ''}\n </Typography>\n {data.pool.returnedCredits ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {`${credits(data.pool.returnedCredits)} credits given back this month — already taken off the figure above.`}\n </Typography>\n ) : null}\n {data.account ? (\n <Typography variant=\"body2\">{allowanceSentence(data.account, 'org')}</Typography>\n ) : null}\n <Typography variant=\"body2\" color=\"text.secondary\">\n {`Projected month-end at this pace: ${credits(data.pool.projectedCredits)} credits (${usd(data.pool.projectedUsd)}) · ${data.pool.messages.toLocaleString()} model turns, ${data.pool.deflected.toLocaleString()} answered from the docs`}\n </Typography>\n </Stack>\n\n {/* Overage */}\n <Stack spacing={0.5}>\n <Typography variant=\"overline\" color=\"text.secondary\">\n {'Overage'}\n </Typography>\n <Typography variant=\"body2\">\n {`${credits(data.overage.overageCredits)} credits over the band · ${usd(data.overage.accruedUsd)} accrued`}\n </Typography>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {overageStateSentence(data.overage, data.pool.uncapped === true)}\n </Typography>\n </Stack>\n\n {/* Refusals */}\n <Stack spacing={0.5}>\n <Typography variant=\"overline\" color=\"text.secondary\">\n {`Refusals this month · ${data.refusals.total.toLocaleString()}`}\n </Typography>\n <RefusalsRow refusals={data.refusals} />\n </Stack>\n\n {/* Jobs */}\n <Stack spacing={0.5}>\n <Typography variant=\"overline\" color=\"text.secondary\">\n {'Generation jobs'}\n </Typography>\n <JobsSection jobs={data.jobs} onGiveBack={giveBackJob} />\n </Stack>\n\n {/* Tokens — absent from a route older than the card */}\n {data.tokens ? (\n <Stack spacing={0.5}>\n <Typography variant=\"overline\" color=\"text.secondary\">\n {`Tokens · ${data.month}`}\n </Typography>\n <TokensSection tokens={data.tokens} />\n </Stack>\n ) : null}\n\n {/* Top users */}\n <Stack spacing={0.5}>\n <Typography variant=\"overline\" color=\"text.secondary\">\n {'Top users this month'}\n </Typography>\n {data.users.length === 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'No AI usage attributed to a person this month.'}\n </Typography>\n ) : (\n <TopUsersSection users={data.users} />\n )}\n </Stack>\n\n {/* Margin */}\n <Stack spacing={0.5}>\n <Typography variant=\"overline\" color=\"text.secondary\">\n {'Margin'}\n </Typography>\n <Alert severity={marginTone(data.margin)}>\n {`Spend ${usd(data.margin.spendUsd)} against ${usd(data.margin.revenueUsd)} in — ` +\n `${usd(data.margin.addonRevenueUsd)} add-on, ${usd(data.margin.planAssistShareUsd)} plan assist share, ` +\n `${usd(data.margin.overageRevenueUsd)} overage.`}\n {data.margin.underwater\n ? ' Spend exceeds the add-on plus the plan’s assist share.'\n : ''}\n {data.margin.multiple >= 1\n ? ` ${data.margin.multiple}× the ${usd(data.margin.thresholdUsd)} staff review threshold.`\n : ''}\n </Alert>\n {data.margin.contribution.marginPct !== null ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {`Whole-org contribution margin ${Math.round(data.margin.contribution.marginPct * 100)}% on the ${data.margin.contribution.month} rollup with this month’s AI spend.`}\n </Typography>\n ) : null}\n </Stack>\n\n {/* Actions */}\n <Stack spacing={0.5}>\n <Typography variant=\"overline\" color=\"text.secondary\">\n {'Actions'}\n </Typography>\n <Typography variant=\"body2\">\n {'Credit override and feature toggles: '}\n <AppLink href={buildRoute(Route.ADMIN_ORGS)} underline=\"hover\">\n {'the entitlement override editor'}\n </AppLink>\n {' (also under Staff actions above). Pause AI for this org: '}\n <AppLink href={buildRoute(Route.ADMIN_LOCKDOWN)} underline=\"hover\">\n {'Lockdown'}\n </AppLink>\n {', feature keys ai-assist and ai-generate scoped to the org.'}\n </Typography>\n </Stack>\n </Stack>\n )}\n </CardDisplay>\n )\n}\nStaffOrgAiCard.displayName = 'StaffOrgAiCard'\n\nexport default StaffOrgAiCard\n"],"names":["aiAddonName","AI_TIERS","buildRoute","Route","pluginDocsHelp","mdiOpenInNew","AppLink","CardDisplay","ListRowActions","ListTable","listActionsColumn","ScrollTable","TABLE_ROW_HEIGHT","useUser","authorizedFetch","Alert","Chip","Stack","TableBody","TableCell","TableHead","TableRow","Typography","useRouter","useCallback","useEffect","useMemo","useRef","useState","allowanceSentence","credits","marginTone","overageStateSentence","poolPartsSentence","rate","refusalChips","tokenCount","usd","JOB_CHIP_STATUSES","StaffCreditReturnActions","StaffCreditReturnDialog","when","iso","Date","toLocaleDateString","RefusalsRow","refusals","direction","spacing","useFlexGap","sx","flexWrap","map","chip","size","variant","count","color","label","toLocaleString","JobsSection","jobs","onGiveBack","columns","jobColumns","severity","total","Object","values","counts","reduce","sum","n","status","replace","done","truncated","rows","recent","getRowId","job","id","rowHeight","noRowsLabel","disableColumnFilter","quickFilter","field","headerName","flex","minWidth","renderCell","row","noWrap","title","fontFamily","width","valueFormatter","value","String","type","align","headerAlign","creditsReserved","createdBy","href","ADMIN_USER_DETAIL","uid","underline","items","key","disabled","creditsSpent","disabledReason","undefined","onClick","TokensSection","tokens","alignItems","input","cached","cacheWrite","output","cacheHitRate","kinds","length","kind","requests","costPerRequestUsd","TopUsersSection","users","router","name","Math","round","quick","icon","path","newTab","to","onOpen","push","StaffOrgAiCard","orgId","data","user","signedInUid","userRef","current","setData","ready","setReady","error","setError","version","setVersion","notice","setNotice","returning","setReturning","giveBackJob","mode","jobId","jobCredits","active","response","encodeURIComponent","payload","json","catch","ok","header","help","anchor","excerpt","HeaderProps","action","onGive","onReset","contentGutterX","contentGutterY","open","target","workspace","used","pool","usedCredits","limit","totalCredits","account","limitCredits","onClose","onReturned","message","mb","addon","on","tier","priceUsd","since","sinceSource","month","uncapped","providerUsd","remainingCredits","returnedCredits","projectedCredits","projectedUsd","messages","deflected","overage","overageCredits","accruedUsd","margin","spendUsd","revenueUsd","addonRevenueUsd","planAssistShareUsd","overageRevenueUsd","underwater","multiple","thresholdUsd","contribution","marginPct","ADMIN_ORGS","ADMIN_LOCKDOWN","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAEA,SAASA,WAAW,QAAQ,eAAc;AAC1C,SAASC,QAAQ,QAAQ,2CAA0C;AACnE,SAASC,UAAU,EAAEC,KAAK,QAAQ,wCAAuC;AACzE,SAASC,cAAc,QAAQ,mCAAkC;AACjE,SAASC,YAAY,QAAQ,yBAAwB;AACrD,SAASC,OAAO,EAAEC,WAAW,QAAQ,uBAAsB;AAC3D,SACEC,cAAc,EACdC,SAAS,EACTC,iBAAiB,QACZ,uDAAsD;AAC7D,SAASC,WAAW,QAAQ,yDAAwD;AACpF,SAASC,gBAAgB,QAAQ,8CAA6C;AAC9E,SAASC,OAAO,QAAQ,iCAAgC;AACxD,SAASC,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E,SAAS,EAAElL,IAAI0G,KAAKqE,MAAM,CAACI,kBAAkB,EAAE,oBAAoB,CAAC,GACxG,GAAGnL,IAAI0G,KAAKqE,MAAM,CAACK,iBAAiB,EAAE,SAAS,CAAC;oCACjD1E,KAAKqE,MAAM,CAACM,UAAU,GACnB,4DACA;oCACH3E,KAAKqE,MAAM,CAACO,QAAQ,IAAI,IACrB,CAAC,CAAC,EAAE5E,KAAKqE,MAAM,CAACO,QAAQ,CAAC,MAAM,EAAEtL,IAAI0G,KAAKqE,MAAM,CAACQ,YAAY,EAAE,wBAAwB,CAAC,GACxF;;;4BAEL7E,KAAKqE,MAAM,CAACS,YAAY,CAACC,SAAS,KAAK,qBACtC,KAACxM;gCAAWiC,SAAQ;gCAAUE,OAAM;0CACjC,CAAC,8BAA8B,EAAE2E,KAAKC,KAAK,CAACU,KAAKqE,MAAM,CAACS,YAAY,CAACC,SAAS,GAAG,KAAK,SAAS,EAAE/E,KAAKqE,MAAM,CAACS,YAAY,CAACrB,KAAK,CAAC,mCAAmC,CAAC;iCAErK;;;kCAIN,MAACvL;wBAAM+B,SAAS;;0CACd,KAAC1B;gCAAWiC,SAAQ;gCAAWE,OAAM;0CAClC;;0CAEH,MAACnC;gCAAWiC,SAAQ;;oCACjB;kDACD,KAACjD;wCAAQkG,MAAMtG,WAAWC,MAAM4N,UAAU;wCAAGpH,WAAU;kDACpD;;oCAEF;kDACD,KAACrG;wCAAQkG,MAAMtG,WAAWC,MAAM6N,cAAc;wCAAGrH,WAAU;kDACxD;;oCAEF;;;;;;;;;AAOf;AACAkC,eAAeoF,WAAW,GAAG;AAE7B,eAAepF,eAAc"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/components/staff-org-ai-card.component.tsx"],"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'use client'\n\nimport { aiAddonName } from '@aglyn/aglyn'\nimport { aiCreditBlocksLabel } from '@aglyn/aglyn/app-utils/ai-credit-blocks'\nimport { buildRoute, Route } from '@aglyn/aglyn/app-utils/console-routes'\nimport { pluginDocsHelp } from '@aglyn/aglyn/app-utils/docs-help'\nimport { mdiOpenInNew } from '@aglyn/shared-data-mdi'\nimport { AppLink, CardDisplay } from '@aglyn/shared-ui-jsx'\nimport {\n ListRowActions,\n ListTable,\n listActionsColumn,\n} from '@aglyn/shared-ui-jsx/components/list-table.component'\nimport { ScrollTable } from '@aglyn/shared-ui-jsx/components/scroll-table.component'\nimport { TABLE_ROW_HEIGHT } from '@aglyn/shared-ui-jsx/const/table-pagination'\nimport { useUser } from '@aglyn/tenant-feature-instance'\nimport { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\nimport {\n Alert,\n Chip,\n Stack,\n TableBody,\n TableCell,\n TableHead,\n TableRow,\n Typography,\n} from '@mui/material'\nimport type { GridColDef } from '@mui/x-data-grid'\nimport { useRouter } from 'next/navigation'\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport type {\n StaffOrgAiJob,\n StaffOrgAiJobs,\n StaffOrgAiRefusals,\n StaffOrgAiResponse,\n StaffOrgAiTokens,\n StaffOrgAiUser,\n} from '../usage/staff-org-ai'\nimport {\n allowanceSentence,\n credits,\n marginTone,\n overageStateSentence,\n poolPartsSentence,\n rate,\n refusalChips,\n tokenCount,\n usd,\n JOB_CHIP_STATUSES,\n} from '../usage/staff-org-ai-view'\nimport {\n StaffCreditReturnActions,\n StaffCreditReturnDialog,\n} from './staff-ai-credit-return.component'\n\n/**\n * THE STAFF AI CARD (AGL-2930): everything about one org's AI usage on the\n * page staff already open to look at that org.\n *\n * Read through `/api/ai/admin/org`, one request on mount. Every figure on it\n * is the route's, and every figure the route serves is composed from the\n * same helpers the meter refuses with — see `usage/staff-org-ai.ts`. This\n * file only lays them out.\n *\n * ## What each section is for\n *\n * - **Add-on** — is the org paying for AI, at what, since when.\n * - **Credit pool** — the band as three NAMED parts, because \"why does\n * this org have 13,000 credits\" has three answers (the plan, an override,\n * the add-on) and a single total cannot say which.\n * - **Overage** — what is past the band, what it is sold at, and the two\n * controls the org itself holds over it.\n * - **Refusals** — how often, and why, the gate said no this month.\n * - **Jobs** and **Top users** — the generative and per-person halves,\n * each of which says plainly when its rollup has nothing yet.\n * - **Tokens** — what each kind of request costs per request, what it\n * sends and generates, and how much of its prompt the cache served.\n * - **Margin** — spend against what AI brings in, red when it is over.\n * - **Actions** — where the override editor and the AI pause live.\n *\n * The header carries the card's two acts (AGL-3595): give credits back to\n * the band (and, on a Free workspace, to the owner's allowance), or reset\n * the month — and each recent job offers the same give-back, prefilled with\n * that job's spend.\n */\n\nconst when = (iso: string | null): string =>\n iso ? new Date(iso).toLocaleDateString() : '—'\n\nfunction RefusalsRow({ refusals }: { refusals: StaffOrgAiRefusals }) {\n return (\n <Stack direction=\"row\" spacing={1} useFlexGap sx={{ flexWrap: 'wrap' }}>\n {refusalChips(refusals).map((chip) => (\n <Chip\n key={chip.label}\n size=\"small\"\n variant={chip.count > 0 ? 'filled' : 'outlined'}\n color={chip.count > 0 ? 'warning' : 'default'}\n label={`${chip.label} ${chip.count.toLocaleString()}`}\n />\n ))}\n </Stack>\n )\n}\n\nfunction JobsSection({\n jobs,\n onGiveBack,\n}: {\n jobs: StaffOrgAiJobs | null\n onGiveBack: (job: StaffOrgAiJob) => void\n}) {\n const columns = useMemo(() => jobColumns(onGiveBack), [onGiveBack])\n if (jobs === null) {\n return (\n <Alert severity=\"warning\">\n {'Could not read the generation jobs — a failed read, not an idle org.'}\n </Alert>\n )\n }\n const total = Object.values(jobs.counts).reduce((sum, n) => sum + n, 0)\n if (total === 0) {\n return (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'No generation jobs yet.'}\n </Typography>\n )\n }\n return (\n <Stack spacing={1}>\n <Stack direction=\"row\" spacing={1} useFlexGap sx={{ flexWrap: 'wrap' }}>\n {JOB_CHIP_STATUSES.map((status) => (\n <Chip\n key={status}\n size=\"small\"\n color={\n status === 'failed' && jobs.counts[status] > 0\n ? 'error'\n : (status === 'needs_input' || status === 'needs_review') &&\n jobs.counts[status] > 0\n ? 'warning'\n : 'default'\n }\n label={`${status.replace('_', ' ')} ${jobs.counts[status]}`}\n />\n ))}\n <Chip size=\"small\" variant=\"outlined\" label={`done ${jobs.counts.done}`} />\n </Stack>\n {jobs.truncated ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Counted from the newest jobs only — these counts are a floor.'}\n </Typography>\n ) : null}\n {/* A record list: the grid scrolls its own columns, so a job id and a\n starter's uid never push the card's content past its edge. */}\n <ListTable\n rows={jobs.recent}\n columns={columns}\n getRowId={(job: StaffOrgAiJob) => job.id}\n rowHeight={TABLE_ROW_HEIGHT}\n noRowsLabel=\"No recent jobs\"\n // The route's ten newest jobs: a bounded readout, so no filter over\n // the rows it holds (AGL-3321).\n disableColumnFilter\n quickFilter={false}\n />\n </Stack>\n )\n}\n\n/**\n * The recent jobs, one column per fact. Who started a job is a column of\n * its own rather than a link tucked beside the date, so it sorts like the\n * rest; the credits sort by what was SPENT, which is the figure the\n * pool was charged. The row's action gives that spend back (AGL-3595).\n */\nconst jobColumns = (\n onGiveBack: (job: StaffOrgAiJob) => void,\n): GridColDef<StaffOrgAiJob>[] => [\n {\n field: 'id',\n headerName: 'Job',\n flex: 1,\n minWidth: 200,\n renderCell: ({ row }) => (\n <Typography variant=\"body2\" noWrap title={row.id} sx={{ fontFamily: 'monospace' }}>\n {row.id}\n </Typography>\n ),\n },\n {\n field: 'kind',\n headerName: 'Kind',\n width: 120,\n valueFormatter: (value: string) => value || '—',\n },\n {\n field: 'status',\n headerName: 'Status',\n width: 130,\n valueFormatter: (value: string) => String(value ?? '').replace('_', ' '),\n },\n {\n field: 'creditsSpent',\n headerName: 'Credits',\n type: 'number',\n align: 'right',\n headerAlign: 'right',\n width: 140,\n valueFormatter: (value: number, row) =>\n `${credits(value)} / ${credits(row.creditsReserved)}`,\n },\n {\n field: 'createdAt',\n headerName: 'Started',\n width: 120,\n valueFormatter: (value: string | null) => when(value),\n },\n {\n field: 'createdBy',\n headerName: 'Started by',\n flex: 1,\n minWidth: 240,\n renderCell: ({ row }) =>\n row.createdBy ? (\n <AppLink\n href={buildRoute(Route.ADMIN_USER_DETAIL, { uid: row.createdBy })}\n variant=\"body2\"\n underline=\"hover\"\n noWrap\n sx={{ fontFamily: 'monospace' }}\n >\n {row.createdBy}\n </AppLink>\n ) : (\n '—'\n ),\n },\n listActionsColumn((row: StaffOrgAiJob) => (\n <ListRowActions\n label={row.id}\n items={[\n {\n key: 'give-back',\n label: 'Give back this job’s credits',\n disabled: row.creditsSpent <= 0,\n disabledReason: row.creditsSpent <= 0 ? 'This job spent no credits.' : undefined,\n onClick: () => onGiveBack(row),\n },\n ]}\n />\n )),\n]\n\n/** The month's tokens, and what each kind of request spends of them (AGL-2937). */\nfunction TokensSection({ tokens }: { tokens: StaffOrgAiTokens }) {\n const { total } = tokens\n return (\n <Stack spacing={1}>\n <Stack direction=\"row\" spacing={1} useFlexGap sx={{ alignItems: 'center', flexWrap: 'wrap' }}>\n <Typography variant=\"body2\">\n {`${tokenCount(total.input)} sent · ${tokenCount(total.cached)} read from cache · ${tokenCount(total.cacheWrite)} written to cache · ${tokenCount(total.output)} generated`}\n </Typography>\n <Chip\n size=\"small\"\n color={tokens.cacheHitRate != null && tokens.cacheHitRate >= 0.5 ? 'success' : 'default'}\n label={`cache hit rate ${rate(tokens.cacheHitRate)}`}\n />\n </Stack>\n {tokens.kinds.length === 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'No model requests recorded by kind this month.'}\n </Typography>\n ) : (\n <ScrollTable size=\"small\">\n <TableHead>\n <TableRow>\n <TableCell>{'Kind'}</TableCell>\n <TableCell align=\"right\">{'Requests'}</TableCell>\n <TableCell align=\"right\">{'Per request'}</TableCell>\n <TableCell align=\"right\">{'Sent'}</TableCell>\n <TableCell align=\"right\">{'From cache'}</TableCell>\n <TableCell align=\"right\">{'Generated'}</TableCell>\n <TableCell align=\"right\">{'Cache hit'}</TableCell>\n </TableRow>\n </TableHead>\n <TableBody>\n {tokens.kinds.map((row) => (\n <TableRow key={row.kind}>\n <TableCell>{row.kind}</TableCell>\n <TableCell align=\"right\">{row.requests.toLocaleString()}</TableCell>\n <TableCell align=\"right\">{usd(row.costPerRequestUsd)}</TableCell>\n <TableCell align=\"right\">{tokenCount(row.tokens.input)}</TableCell>\n <TableCell align=\"right\">{tokenCount(row.tokens.cached)}</TableCell>\n <TableCell align=\"right\">{tokenCount(row.tokens.output)}</TableCell>\n <TableCell align=\"right\">{rate(row.cacheHitRate)}</TableCell>\n </TableRow>\n ))}\n </TableBody>\n </ScrollTable>\n )}\n </Stack>\n )\n}\n\n/**\n * The month's top spenders, one row per person. The row opens the account;\n * the uid rides beneath the roster's name because two people can share one.\n */\nfunction TopUsersSection({ users }: { users: StaffOrgAiUser[] }) {\n const router = useRouter()\n const columns = useMemo<GridColDef<StaffOrgAiUser>[]>(\n () => [\n {\n field: 'name',\n headerName: 'Person',\n flex: 1,\n minWidth: 220,\n renderCell: ({ row }) => (\n <Stack sx={{ minWidth: 0 }}>\n <Typography variant=\"body2\" noWrap title={row.name}>\n {row.name}\n </Typography>\n {row.name !== row.uid ? (\n <Typography\n variant=\"caption\"\n color=\"text.secondary\"\n noWrap\n sx={{ fontFamily: 'monospace' }}\n >\n {row.uid}\n </Typography>\n ) : null}\n </Stack>\n ),\n },\n {\n field: 'credits',\n headerName: 'Credits',\n type: 'number',\n align: 'right',\n headerAlign: 'right',\n width: 110,\n valueFormatter: (value: number) => credits(value),\n },\n {\n field: 'share',\n headerName: 'Share',\n type: 'number',\n align: 'right',\n headerAlign: 'right',\n width: 90,\n valueFormatter: (value: number) => `${Math.round(value * 100)}%`,\n },\n {\n field: 'estCostUsd',\n headerName: 'Provider $',\n type: 'number',\n align: 'right',\n headerAlign: 'right',\n width: 120,\n valueFormatter: (value: number) => usd(value),\n },\n {\n field: 'requests',\n headerName: 'Requests',\n type: 'number',\n align: 'right',\n headerAlign: 'right',\n width: 110,\n valueFormatter: (value: number) => value.toLocaleString(),\n },\n {\n field: 'refusals',\n headerName: 'Refusals',\n type: 'number',\n align: 'right',\n headerAlign: 'right',\n width: 110,\n valueFormatter: (value: number) => value.toLocaleString(),\n },\n listActionsColumn((row: StaffOrgAiUser) => (\n <ListRowActions\n label={row.name}\n quick={{\n icon: mdiOpenInNew.path,\n label: 'View account',\n newTab: true,\n to: buildRoute(Route.ADMIN_USER_DETAIL, { uid: row.uid }),\n }}\n items={[]}\n />\n )),\n ],\n [],\n )\n return (\n <ListTable\n rows={users}\n columns={columns}\n getRowId={(row: StaffOrgAiUser) => row.uid}\n rowHeight={TABLE_ROW_HEIGHT}\n onOpen={(uid) => router.push(buildRoute(Route.ADMIN_USER_DETAIL, { uid }))}\n // The route's ten dearest members: a bounded readout, so no filter\n // over the rows it holds (AGL-3321).\n disableColumnFilter\n quickFilter={false}\n />\n )\n}\n\nconst StaffOrgAiCard = ({ orgId }: { orgId: string }) => {\n const { data: user } = useUser()\n // Keyed on who is signed in, not on the user object's identity.\n const signedInUid = user?.uid ?? null\n const userRef = useRef(user)\n userRef.current = user\n const [data, setData] = useState<StaffOrgAiResponse | null>(null)\n const [ready, setReady] = useState(false)\n const [error, setError] = useState<string | null>(null)\n // Bumped after a give-back, so the card re-reads the figures it changed.\n const [version, setVersion] = useState(0)\n const [notice, setNotice] = useState<string | null>(null)\n const [returning, setReturning] = useState<{\n mode: 'give' | 'reset'\n jobId?: string\n jobCredits?: number\n } | null>(null)\n const giveBackJob = useCallback(\n (job: StaffOrgAiJob) =>\n setReturning({ mode: 'give', jobId: job.id, jobCredits: job.creditsSpent }),\n [],\n )\n\n useEffect(() => {\n // Mounted only for a confirmed staff reader — the `staffOrg` zone sits\n // inside the page's `StaffOnly`, which renders nothing while the claim\n // loads — because the route records an access row on every successful\n // open, and an open the page did not mean to make would be an access\n // nobody made.\n const user = userRef.current\n if (!orgId || !signedInUid || !user) return undefined\n let active = true\n setReady(false)\n setError(null)\n void (async () => {\n try {\n const response = await authorizedFetch(\n user,\n `/api/ai/admin/org?orgId=${encodeURIComponent(orgId)}`,\n )\n const payload = await response.json().catch(() => null)\n if (!active) return\n if (!response.ok) {\n setError(payload?.error ?? 'AI lookup failed')\n setData(null)\n } else {\n setData(payload as StaffOrgAiResponse)\n }\n } catch {\n if (active) {\n setError('AI lookup failed')\n setData(null)\n }\n } finally {\n if (active) setReady(true)\n }\n })()\n return () => {\n active = false\n }\n }, [orgId, signedInUid, version])\n\n const name = aiAddonName()\n return (\n <CardDisplay\n header={name}\n help={pluginDocsHelp('aiMonitoring', {\n anchor: '#the-ai-card',\n excerpt:\n 'The add-on, the credit pool and its parts, this month’s overage and refusals, generation jobs, tokens and the cache hit rate by kind, the people spending the most, and the margin — for this organization.',\n })}\n HeaderProps={{\n action: (\n <StaffCreditReturnActions\n disabled={!data}\n onGive={() => setReturning({ mode: 'give' })}\n onReset={() => setReturning({ mode: 'reset' })}\n />\n ),\n }}\n contentGutterX\n contentGutterY\n >\n {data ? (\n <StaffCreditReturnDialog\n open={returning !== null}\n mode={returning?.mode ?? 'give'}\n target={{ orgId }}\n workspace={{ used: data.pool.usedCredits, limit: data.pool.totalCredits }}\n account={\n data.account\n ? { used: data.account.usedCredits, limit: data.account.limitCredits }\n : null\n }\n jobId={returning?.jobId ?? null}\n jobCredits={returning?.jobCredits ?? null}\n onClose={() => setReturning(null)}\n onReturned={(message) => {\n setReturning(null)\n setNotice(message)\n setVersion((current) => current + 1)\n }}\n />\n ) : null}\n {notice ? (\n <Alert severity=\"success\" onClose={() => setNotice(null)} sx={{ mb: 2 }}>\n {notice}\n </Alert>\n ) : null}\n {!ready ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Loading…'}\n </Typography>\n ) : error || !data ? (\n <Alert severity=\"warning\">\n {`Could not read this organization’s AI usage — ${error ?? 'a failed read'}, not zero usage.`}\n </Alert>\n ) : (\n <Stack spacing={2}>\n {/* Add-on */}\n <Stack spacing={0.5}>\n <Typography variant=\"overline\" color=\"text.secondary\">\n {'Add-on'}\n </Typography>\n <Stack useFlexGap direction=\"row\" spacing={1} sx={{ alignItems: 'center', flexWrap: 'wrap' }}>\n <Chip\n size=\"small\"\n color={data.addon.on ? 'primary' : 'default'}\n label={\n data.addon.on\n ? `${name}${data.addon.blocks > 0 ? ` credits, ${aiCreditBlocksLabel(data.addon.blocks)}` : ''} on`\n : `${name} off`\n }\n />\n {data.addon.priceUsd !== null ? (\n <Typography variant=\"body2\">\n {`${usd(data.addon.priceUsd)}/mo`}\n </Typography>\n ) : null}\n {data.addon.on ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {data.addon.since\n ? `since ${when(data.addon.since)}`\n : data.addon.sinceSource === 'unavailable'\n ? 'since — (Stripe not reachable)'\n : 'since — (no subscription item)'}\n </Typography>\n ) : null}\n </Stack>\n </Stack>\n\n {/* Credit pool */}\n <Stack spacing={0.5}>\n <Typography variant=\"overline\" color=\"text.secondary\">\n {`Credit pool · ${data.month}`}\n </Typography>\n {data.pool.totalCredits === null && data.pool.uncapped ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Uncapped staff comp — no AI credit band. Bounded only by the message cap and an operator’s explicit spend ceiling.'}\n </Typography>\n ) : data.pool.totalCredits === null ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'No AI credit band on this plan — bounded by the message cap and the operator backstop.'}\n </Typography>\n ) : (\n <Typography variant=\"body2\">\n {`${credits(data.pool.totalCredits)} credits = ${poolPartsSentence(data.pool, name)}`}\n </Typography>\n )}\n <Typography variant=\"body2\">\n {`Used ${credits(data.pool.usedCredits)} credits (${usd(data.pool.providerUsd)} provider spend)`}\n {data.pool.remainingCredits !== null\n ? ` · ${credits(data.pool.remainingCredits)} remaining`\n : ''}\n </Typography>\n {data.pool.returnedCredits ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {`${credits(data.pool.returnedCredits)} credits given back this month — already taken off the figure above.`}\n </Typography>\n ) : null}\n {data.account ? (\n <Typography variant=\"body2\">{allowanceSentence(data.account, 'org')}</Typography>\n ) : null}\n <Typography variant=\"body2\" color=\"text.secondary\">\n {`Projected month-end at this pace: ${credits(data.pool.projectedCredits)} credits (${usd(data.pool.projectedUsd)}) · ${data.pool.messages.toLocaleString()} model turns, ${data.pool.deflected.toLocaleString()} answered from the docs`}\n </Typography>\n </Stack>\n\n {/* Overage */}\n <Stack spacing={0.5}>\n <Typography variant=\"overline\" color=\"text.secondary\">\n {'Overage'}\n </Typography>\n <Typography variant=\"body2\">\n {`${credits(data.overage.overageCredits)} credits over the band · ${usd(data.overage.accruedUsd)} accrued`}\n </Typography>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {overageStateSentence(data.overage, data.pool.uncapped === true)}\n </Typography>\n </Stack>\n\n {/* Refusals */}\n <Stack spacing={0.5}>\n <Typography variant=\"overline\" color=\"text.secondary\">\n {`Refusals this month · ${data.refusals.total.toLocaleString()}`}\n </Typography>\n <RefusalsRow refusals={data.refusals} />\n </Stack>\n\n {/* Jobs */}\n <Stack spacing={0.5}>\n <Typography variant=\"overline\" color=\"text.secondary\">\n {'Generation jobs'}\n </Typography>\n <JobsSection jobs={data.jobs} onGiveBack={giveBackJob} />\n </Stack>\n\n {/* Tokens — absent from a route older than the card */}\n {data.tokens ? (\n <Stack spacing={0.5}>\n <Typography variant=\"overline\" color=\"text.secondary\">\n {`Tokens · ${data.month}`}\n </Typography>\n <TokensSection tokens={data.tokens} />\n </Stack>\n ) : null}\n\n {/* Top users */}\n <Stack spacing={0.5}>\n <Typography variant=\"overline\" color=\"text.secondary\">\n {'Top users this month'}\n </Typography>\n {data.users.length === 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'No AI usage attributed to a person this month.'}\n </Typography>\n ) : (\n <TopUsersSection users={data.users} />\n )}\n </Stack>\n\n {/* Margin */}\n <Stack spacing={0.5}>\n <Typography variant=\"overline\" color=\"text.secondary\">\n {'Margin'}\n </Typography>\n <Alert severity={marginTone(data.margin)}>\n {`Spend ${usd(data.margin.spendUsd)} against ${usd(data.margin.revenueUsd)} in — ` +\n `${usd(data.margin.addonRevenueUsd)} add-on, ${usd(data.margin.planAssistShareUsd)} plan assist share, ` +\n `${usd(data.margin.overageRevenueUsd)} overage.`}\n {data.margin.underwater\n ? ' Spend exceeds the add-on plus the plan’s assist share.'\n : ''}\n {data.margin.multiple >= 1\n ? ` ${data.margin.multiple}× the ${usd(data.margin.thresholdUsd)} staff review threshold.`\n : ''}\n </Alert>\n {data.margin.contribution.marginPct !== null ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {`Whole-org contribution margin ${Math.round(data.margin.contribution.marginPct * 100)}% on the ${data.margin.contribution.month} rollup with this month’s AI spend.`}\n </Typography>\n ) : null}\n </Stack>\n\n {/* Actions */}\n <Stack spacing={0.5}>\n <Typography variant=\"overline\" color=\"text.secondary\">\n {'Actions'}\n </Typography>\n <Typography variant=\"body2\">\n {'Credit override and feature toggles: '}\n <AppLink href={buildRoute(Route.ADMIN_ORGS)} underline=\"hover\">\n {'the entitlement override editor'}\n </AppLink>\n {' (also under Staff actions above). Pause AI for this org: '}\n <AppLink href={buildRoute(Route.ADMIN_LOCKDOWN)} underline=\"hover\">\n {'Lockdown'}\n </AppLink>\n {', feature keys ai-assist and ai-generate scoped to the org.'}\n </Typography>\n </Stack>\n </Stack>\n )}\n </CardDisplay>\n )\n}\nStaffOrgAiCard.displayName = 'StaffOrgAiCard'\n\nexport default StaffOrgAiCard\n"],"names":["aiAddonName","aiCreditBlocksLabel","buildRoute","Route","pluginDocsHelp","mdiOpenInNew","AppLink","CardDisplay","ListRowActions","ListTable","listActionsColumn","ScrollTable","TABLE_ROW_HEIGHT","useUser","authorizedFetch","Alert","Chip","Stack","TableBody","TableCell","TableHead","TableRow","Typography","useRouter","useCallback","useEffect","useMemo","useRef","useState","allowanceSentence","credits","marginTone","overageStateSentence","poolPartsSentence","rate","refusalChips","tokenCount","usd","JOB_CHIP_STATUSES","StaffCreditReturnActions","StaffCreditReturnDialog","when","iso","Date","toLocaleDateString","RefusalsRow","refusals","direction","spacing","useFlexGap","sx","flexWrap","map","chip","size","variant","count","color","label","toLocaleString","JobsSection","jobs","onGiveBack","columns","jobColumns","severity","total","Object","values","counts","reduce","sum","n","status","replace","done","truncated","rows","recent","getRowId","job","id","rowHeight","noRowsLabel","disableColumnFilter","quickFilter","field","headerName","flex","minWidth","renderCell","row","noWrap","title","fontFamily","width","valueFormatter","value","String","type","align","headerAlign","creditsReserved","createdBy","href","ADMIN_USER_DETAIL","uid","underline","items","key","disabled","creditsSpent","disabledReason","undefined","onClick","TokensSection","tokens","alignItems","input","cached","cacheWrite","output","cacheHitRate","kinds","length","kind","requests","costPerRequestUsd","TopUsersSection","users","router","name","Math","round","quick","icon","path","newTab","to","onOpen","push","StaffOrgAiCard","orgId","data","user","signedInUid","userRef","current","setData","ready","setReady","error","setError","version","setVersion","notice","setNotice","returning","setReturning","giveBackJob","mode","jobId","jobCredits","active","response","encodeURIComponent","payload","json","catch","ok","header","help","anchor","excerpt","HeaderProps","action","onGive","onReset","contentGutterX","contentGutterY","open","target","workspace","used","pool","usedCredits","limit","totalCredits","account","limitCredits","onClose","onReturned","message","mb","addon","on","blocks","priceUsd","since","sinceSource","month","uncapped","providerUsd","remainingCredits","returnedCredits","projectedCredits","projectedUsd","messages","deflected","overage","overageCredits","accruedUsd","margin","spendUsd","revenueUsd","addonRevenueUsd","planAssistShareUsd","overageRevenueUsd","underwater","multiple","thresholdUsd","contribution","marginPct","ADMIN_ORGS","ADMIN_LOCKDOWN","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;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AU;wCAAGpH,WAAU;kDACpD;;oCAEF;kDACD,KAACrG;wCAAQkG,MAAMtG,WAAWC,MAAM6N,cAAc;wCAAGrH,WAAU;kDACxD;;oCAEF;;;;;;;;;AAOf;AACAkC,eAAeoF,WAAW,GAAG;AAE7B,eAAepF,eAAc"}
@@ -27,8 +27,8 @@ import { type PluginEntitlementRegistration } from '@aglyn/aglyn/plugin-manager/
27
27
  * reaches a provider, Firestore or React.
28
28
  *
29
29
  * The plan tables keep the per-plan defaults for `aiGenerative` and
30
- * `aiAssist`, and `AI_TIERS` keeps each tier's price and credits, so this
31
- * names keys and restates no figure.
30
+ * `aiAssist`, and `ai-credit-blocks.ts` keeps the credit block's price and
31
+ * credits, so this names keys and restates no figure.
32
32
  *
33
33
  * `ai-assist` and `ai-generate` are separate levers because the two doors
34
34
  * spend at different rates and an incident on one need not stop the other
@@ -16,7 +16,8 @@
16
16
  */ // Named modules rather than the `@aglyn/aglyn` barrel: both apps load this
17
17
  // on the server at boot, and the full barrel carries client-only contexts
18
18
  // (AGL-405).
19
- import { aiTierQuotaPerUnit, planSellsAiTiers } from "@aglyn/aglyn/app-utils/plan-entitlements";
19
+ import { aiCreditsQuotaPerUnit, planSellsAiCredits } from "@aglyn/aglyn/app-utils/plan-entitlements";
20
+ import { AI_CREDIT_BLOCKS_MAX } from "@aglyn/aglyn/app-utils/ai-credit-blocks";
20
21
  import { registerPluginConfigSchema } from "@aglyn/aglyn/plugin-manager/plugin-config";
21
22
  import { registerPluginEntitlements } from "@aglyn/aglyn/plugin-manager/plugin-entitlements";
22
23
  import { AI_PLUGIN_ID } from "./constants.js";
@@ -35,8 +36,8 @@ import { registerAiActivityActions } from "./activity/ai-activity-actions.js";
35
36
  * reaches a provider, Firestore or React.
36
37
  *
37
38
  * The plan tables keep the per-plan defaults for `aiGenerative` and
38
- * `aiAssist`, and `AI_TIERS` keeps each tier's price and credits, so this
39
- * names keys and restates no figure.
39
+ * `aiAssist`, and `ai-credit-blocks.ts` keeps the credit block's price and
40
+ * credits, so this names keys and restates no figure.
40
41
  *
41
42
  * `ai-assist` and `ai-generate` are separate levers because the two doors
42
43
  * spend at different rates and an incident on one need not stop the other
@@ -49,19 +50,19 @@ import { registerAiActivityActions } from "./activity/ai-activity-actions.js";
49
50
  {
50
51
  key: 'aiAddon',
51
52
  label: 'AI add-on',
52
- maxUnits: 1,
53
- // The purchased tier's credits on top of the plan's included band
54
- // (AGL-3965): one pool, widened by what was bought rather than by
55
- // which plan bought it.
53
+ // Credits by the block (AGL-4144): 0 to 30 blocks, each adding 5,000
54
+ // credits to the plan's included band — one pool, widened by what was
55
+ // bought rather than by which plan bought it.
56
+ maxUnits: AI_CREDIT_BLOCKS_MAX,
56
57
  quota: {
57
58
  key: 'assistCreditsPerMonth',
58
- perUnit: aiTierQuotaPerUnit
59
+ perUnit: aiCreditsQuotaPerUnit
59
60
  },
60
61
  features: [
61
62
  'aiGenerative',
62
63
  'aiAssist'
63
64
  ],
64
- soldOn: planSellsAiTiers
65
+ soldOn: planSellsAiCredits
65
66
  }
66
67
  ],
67
68
  features: [
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../libs/plugins/ai/src/lib/declarations.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Named modules rather than the `@aglyn/aglyn` barrel: both apps load this\n// on the server at boot, and the full barrel carries client-only contexts\n// (AGL-405).\nimport {\n aiTierQuotaPerUnit,\n planSellsAiTiers,\n} from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport { registerPluginConfigSchema } from '@aglyn/aglyn/plugin-manager/plugin-config'\nimport {\n registerPluginEntitlements,\n type PluginEntitlementRegistration,\n} from '@aglyn/aglyn/plugin-manager/plugin-entitlements'\nimport { AI_PLUGIN_ID } from './constants'\nimport { AI_ORG_PERMISSIONS, AI_WORKSPACE_PERMISSIONS } from './model/ai-permissions'\nimport { AI_CONFIG_SCHEMA } from './plugin-config'\nimport { registerAiActivityActions } from './activity/ai-activity-actions'\n\n/**\n * The plugin's DECLARATIONS (AGL-2939): what core must know about this\n * plugin before any of its surfaces load — its billing and access keys,\n * the AI permission keys it adds to the org catalog (AGL-2984), its\n * activity codes, its settings schema. Loaded eagerly by both apps\n * through the generated declarations manifest, at boot on the server and\n * with the plugin loader on the client, so a core billing route folds the\n * add-on and the staff lockdown page lists the levers whether or not a\n * request has touched the plugin yet. Light by construction: nothing here\n * reaches a provider, Firestore or React.\n *\n * The plan tables keep the per-plan defaults for `aiGenerative` and\n * `aiAssist`, and `AI_TIERS` keeps each tier's price and credits, so this\n * names keys and restates no figure.\n *\n * `ai-assist` and `ai-generate` are separate levers because the two doors\n * spend at different rates and an incident on one need not stop the other\n * (AGL-2903). Both grant the staff bypass: a provider incident is verified\n * recovered by staff making one real call, not by lifting the lock and\n * watching customers find out.\n */\nexport const AI_PLUGIN_ENTITLEMENTS: PluginEntitlementRegistration = {\n pluginId: AI_PLUGIN_ID,\n seatAddons: [\n {\n key: 'aiAddon',\n label: 'AI add-on',\n maxUnits: 1,\n // The purchased tier's credits on top of the plan's included band\n // (AGL-3965): one pool, widened by what was bought rather than by\n // which plan bought it.\n quota: {\n key: 'assistCreditsPerMonth',\n perUnit: aiTierQuotaPerUnit,\n },\n features: ['aiGenerative', 'aiAssist'],\n soldOn: planSellsAiTiers,\n },\n ],\n features: [\n { key: 'aiAssist', label: 'AI assist' },\n { key: 'aiGenerative', label: 'AI generation' },\n ],\n lockdownFeatures: [\n {\n key: 'ai-assist',\n label: 'AI assist',\n customerName: 'AI assist',\n staffBypass: true,\n notice: {\n title: 'AI assist is temporarily unavailable',\n body: 'AI assist is temporarily unavailable. Your content is unaffected — please try again shortly.',\n },\n // Gated even while the route 501s without a provider key — the switch\n // predates the key on purpose.\n apiPaths: { exact: ['ai/assist', 'assist/chat'] },\n },\n {\n key: 'ai-generate',\n label: 'AI generation',\n customerName: 'AI generation',\n staffBypass: true,\n notice: {\n title: 'AI generation is temporarily unavailable',\n body: 'Generating sections, pages and automations with AI is temporarily unavailable. Everything already built is unaffected — please try again shortly.',\n },\n // `ai/seo` (AGL-2910) applies a finished audit's drafts; it spends\n // nothing, and it is still a generative door the switch stops.\n apiPaths: { prefixes: ['ai/generate', 'ai/jobs', 'ai/seo'] },\n },\n ],\n orgPermissions: [...AI_ORG_PERMISSIONS, ...AI_WORKSPACE_PERMISSIONS],\n}\n\nlet declared = false\n\n/**\n * Registers everything above, and the activity codes. Idempotent: the\n * declarations manifest runs it once per process, and a surface's register\n * fn may call it again. The codes are a call rather than an import made\n * for what the module does as it loads, because the browser's manifest\n * reaches that module through nothing else, and a bundler honoring this\n * package's `sideEffects` deletes such an import (AGL-3025).\n */\nexport function registerAiDeclarations(): void {\n if (declared) return\n declared = true\n registerPluginEntitlements(AI_PLUGIN_ENTITLEMENTS)\n registerPluginConfigSchema(AI_CONFIG_SCHEMA)\n registerAiActivityActions()\n}\n\nregisterAiDeclarations()\n"],"names":["aiTierQuotaPerUnit","planSellsAiTiers","registerPluginConfigSchema","registerPluginEntitlements","AI_PLUGIN_ID","AI_ORG_PERMISSIONS","AI_WORKSPACE_PERMISSIONS","AI_CONFIG_SCHEMA","registerAiActivityActions","AI_PLUGIN_ENTITLEMENTS","pluginId","seatAddons","key","label","maxUnits","quota","perUnit","features","soldOn","lockdownFeatures","customerName","staffBypass","notice","title","body","apiPaths","exact","prefixes","orgPermissions","declared","registerAiDeclarations"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,2EAA2E;AAC3E,0EAA0E;AAC1E,aAAa;AACb,SACEA,kBAAkB,EAClBC,gBAAgB,QACX,2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../../../libs/plugins/ai/src/lib/declarations.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Named modules rather than the `@aglyn/aglyn` barrel: both apps load this\n// on the server at boot, and the full barrel carries client-only contexts\n// (AGL-405).\nimport {\n aiCreditsQuotaPerUnit,\n planSellsAiCredits,\n} from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport { AI_CREDIT_BLOCKS_MAX } from '@aglyn/aglyn/app-utils/ai-credit-blocks'\nimport { registerPluginConfigSchema } from '@aglyn/aglyn/plugin-manager/plugin-config'\nimport {\n registerPluginEntitlements,\n type PluginEntitlementRegistration,\n} from '@aglyn/aglyn/plugin-manager/plugin-entitlements'\nimport { AI_PLUGIN_ID } from './constants'\nimport { AI_ORG_PERMISSIONS, AI_WORKSPACE_PERMISSIONS } from './model/ai-permissions'\nimport { AI_CONFIG_SCHEMA } from './plugin-config'\nimport { registerAiActivityActions } from './activity/ai-activity-actions'\n\n/**\n * The plugin's DECLARATIONS (AGL-2939): what core must know about this\n * plugin before any of its surfaces load — its billing and access keys,\n * the AI permission keys it adds to the org catalog (AGL-2984), its\n * activity codes, its settings schema. Loaded eagerly by both apps\n * through the generated declarations manifest, at boot on the server and\n * with the plugin loader on the client, so a core billing route folds the\n * add-on and the staff lockdown page lists the levers whether or not a\n * request has touched the plugin yet. Light by construction: nothing here\n * reaches a provider, Firestore or React.\n *\n * The plan tables keep the per-plan defaults for `aiGenerative` and\n * `aiAssist`, and `ai-credit-blocks.ts` keeps the credit block's price and\n * credits, so this names keys and restates no figure.\n *\n * `ai-assist` and `ai-generate` are separate levers because the two doors\n * spend at different rates and an incident on one need not stop the other\n * (AGL-2903). Both grant the staff bypass: a provider incident is verified\n * recovered by staff making one real call, not by lifting the lock and\n * watching customers find out.\n */\nexport const AI_PLUGIN_ENTITLEMENTS: PluginEntitlementRegistration = {\n pluginId: AI_PLUGIN_ID,\n seatAddons: [\n {\n key: 'aiAddon',\n label: 'AI add-on',\n // Credits by the block (AGL-4144): 0 to 30 blocks, each adding 5,000\n // credits to the plan's included band — one pool, widened by what was\n // bought rather than by which plan bought it.\n maxUnits: AI_CREDIT_BLOCKS_MAX,\n quota: {\n key: 'assistCreditsPerMonth',\n perUnit: aiCreditsQuotaPerUnit,\n },\n features: ['aiGenerative', 'aiAssist'],\n soldOn: planSellsAiCredits,\n },\n ],\n features: [\n { key: 'aiAssist', label: 'AI assist' },\n { key: 'aiGenerative', label: 'AI generation' },\n ],\n lockdownFeatures: [\n {\n key: 'ai-assist',\n label: 'AI assist',\n customerName: 'AI assist',\n staffBypass: true,\n notice: {\n title: 'AI assist is temporarily unavailable',\n body: 'AI assist is temporarily unavailable. Your content is unaffected — please try again shortly.',\n },\n // Gated even while the route 501s without a provider key — the switch\n // predates the key on purpose.\n apiPaths: { exact: ['ai/assist', 'assist/chat'] },\n },\n {\n key: 'ai-generate',\n label: 'AI generation',\n customerName: 'AI generation',\n staffBypass: true,\n notice: {\n title: 'AI generation is temporarily unavailable',\n body: 'Generating sections, pages and automations with AI is temporarily unavailable. Everything already built is unaffected — please try again shortly.',\n },\n // `ai/seo` (AGL-2910) applies a finished audit's drafts; it spends\n // nothing, and it is still a generative door the switch stops.\n apiPaths: { prefixes: ['ai/generate', 'ai/jobs', 'ai/seo'] },\n },\n ],\n orgPermissions: [...AI_ORG_PERMISSIONS, ...AI_WORKSPACE_PERMISSIONS],\n}\n\nlet declared = false\n\n/**\n * Registers everything above, and the activity codes. Idempotent: the\n * declarations manifest runs it once per process, and a surface's register\n * fn may call it again. The codes are a call rather than an import made\n * for what the module does as it loads, because the browser's manifest\n * reaches that module through nothing else, and a bundler honoring this\n * package's `sideEffects` deletes such an import (AGL-3025).\n */\nexport function registerAiDeclarations(): void {\n if (declared) return\n declared = true\n registerPluginEntitlements(AI_PLUGIN_ENTITLEMENTS)\n registerPluginConfigSchema(AI_CONFIG_SCHEMA)\n registerAiActivityActions()\n}\n\nregisterAiDeclarations()\n"],"names":["aiCreditsQuotaPerUnit","planSellsAiCredits","AI_CREDIT_BLOCKS_MAX","registerPluginConfigSchema","registerPluginEntitlements","AI_PLUGIN_ID","AI_ORG_PERMISSIONS","AI_WORKSPACE_PERMISSIONS","AI_CONFIG_SCHEMA","registerAiActivityActions","AI_PLUGIN_ENTITLEMENTS","pluginId","seatAddons","key","label","maxUnits","quota","perUnit","features","soldOn","lockdownFeatures","customerName","staffBypass","notice","title","body","apiPaths","exact","prefixes","orgPermissions","declared","registerAiDeclarations"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,2EAA2E;AAC3E,0EAA0E;AAC1E,aAAa;AACb,SACEA,qBAAqB,EACrBC,kBAAkB,QACb,2CAA0C;AACjD,SAASC,oBAAoB,QAAQ,0CAAyC;AAC9E,SAASC,0BAA0B,QAAQ,4CAA2C;AACtF,SACEC,0BAA0B,QAErB,kDAAiD;AACxD,SAASC,YAAY,QAAQ,iBAAa;AAC1C,SAASC,kBAAkB,EAAEC,wBAAwB,QAAQ,4BAAwB;AACrF,SAASC,gBAAgB,QAAQ,qBAAiB;AAClD,SAASC,yBAAyB,QAAQ,oCAAgC;AAE1E;;;;;;;;;;;;;;;;;;;;CAoBC,GACD,OAAO,MAAMC,yBAAwD;IACnEC,UAAUN;IACVO,YAAY;QACV;YACEC,KAAK;YACLC,OAAO;YACP,qEAAqE;YACrE,sEAAsE;YACtE,8CAA8C;YAC9CC,UAAUb;YACVc,OAAO;gBACLH,KAAK;gBACLI,SAASjB;YACX;YACAkB,UAAU;gBAAC;gBAAgB;aAAW;YACtCC,QAAQlB;QACV;KACD;IACDiB,UAAU;QACR;YAAEL,KAAK;YAAYC,OAAO;QAAY;QACtC;YAAED,KAAK;YAAgBC,OAAO;QAAgB;KAC/C;IACDM,kBAAkB;QAChB;YACEP,KAAK;YACLC,OAAO;YACPO,cAAc;YACdC,aAAa;YACbC,QAAQ;gBACNC,OAAO;gBACPC,MAAM;YACR;YACA,sEAAsE;YACtE,+BAA+B;YAC/BC,UAAU;gBAAEC,OAAO;oBAAC;oBAAa;iBAAc;YAAC;QAClD;QACA;YACEd,KAAK;YACLC,OAAO;YACPO,cAAc;YACdC,aAAa;YACbC,QAAQ;gBACNC,OAAO;gBACPC,MAAM;YACR;YACA,mEAAmE;YACnE,+DAA+D;YAC/DC,UAAU;gBAAEE,UAAU;oBAAC;oBAAe;oBAAW;iBAAS;YAAC;QAC7D;KACD;IACDC,gBAAgB;WAAIvB;WAAuBC;KAAyB;AACtE,EAAC;AAED,IAAIuB,WAAW;AAEf;;;;;;;CAOC,GACD,OAAO,SAASC;IACd,IAAID,UAAU;IACdA,WAAW;IACX1B,2BAA2BM;IAC3BP,2BAA2BK;IAC3BC;AACF;AAEAsB"}
@@ -420,6 +420,9 @@ const num = (value)=>value === undefined ? Number.NaN : Number.parseFloat(value)
420
420
  if (fit == null ? void 0 : fit.objectFit) out.objectFit = fit.objectFit;
421
421
  if ((fit == null ? void 0 : fit.radius) !== undefined && fit.radius >= ROUNDED_PX && fit.radius < 999) out.rounded = true;
422
422
  if (fit == null ? void 0 : fit.shadow) out.shadow = true;
423
+ // The width the source holds it to, as the theme's breakpoint nearest it; the widest is no hold at all.
424
+ const measure = siteImportWidthOf(fit == null ? void 0 : fit.measure);
425
+ if (measure && measure !== 'xl') out.measure = measure;
423
426
  return Object.keys(out).length ? out : undefined;
424
427
  }
425
428
  /** A picture line as the library holds it; marks it taken, and missing where the library holds none. */ function takePicture(scope, ref, href, fit) {