@aglyn/plugins-ai 1.0.0-beta.219 → 1.0.0-beta.220

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 (181) hide show
  1. package/package.json +18 -18
  2. package/src/lib/billing/ai-month-meter.d.ts +51 -0
  3. package/src/lib/billing/ai-month-meter.js +89 -0
  4. package/src/lib/billing/ai-month-meter.js.map +1 -0
  5. package/src/lib/billing/ai-overage-close.d.ts +11 -33
  6. package/src/lib/billing/ai-overage-close.js +4 -3
  7. package/src/lib/billing/ai-overage-close.js.map +1 -1
  8. package/src/lib/billing/ai-overage-cutover.d.ts +28 -12
  9. package/src/lib/billing/ai-overage-cutover.js +1 -28
  10. package/src/lib/billing/ai-overage-cutover.js.map +1 -1
  11. package/src/lib/billing/ai-overage-ledger.js +1 -1
  12. package/src/lib/billing/ai-overage-ledger.js.map +1 -1
  13. package/src/lib/billing/ai-overage-standing.js +1 -1
  14. package/src/lib/billing/ai-overage-standing.js.map +1 -1
  15. package/src/lib/components/ai-allotment-editor.component.js +1 -1
  16. package/src/lib/components/ai-allotment-editor.component.js.map +1 -1
  17. package/src/lib/components/ai-assist-provider.component.js +3 -2
  18. package/src/lib/components/ai-assist-provider.component.js.map +1 -1
  19. package/src/lib/components/ai-automation-zones.d.ts +63 -0
  20. package/src/lib/components/ai-automation-zones.js +31 -0
  21. package/src/lib/components/ai-automation-zones.js.map +1 -0
  22. package/src/lib/components/ai-describe-automation.component.d.ts +1 -1
  23. package/src/lib/components/ai-describe-automation.component.js.map +1 -1
  24. package/src/lib/components/ai-describe-button.component.d.ts +6 -3
  25. package/src/lib/components/ai-describe-button.component.js +4 -1
  26. package/src/lib/components/ai-describe-button.component.js.map +1 -1
  27. package/src/lib/components/ai-explain-automation.component.d.ts +1 -1
  28. package/src/lib/components/ai-explain-automation.component.js.map +1 -1
  29. package/src/lib/components/billing-ai-allotments.component.js +1 -1
  30. package/src/lib/components/billing-ai-allotments.component.js.map +1 -1
  31. package/src/lib/components/billing-assist-overage-card.component.js +1 -1
  32. package/src/lib/components/billing-assist-overage-card.component.js.map +1 -1
  33. package/src/lib/constants.d.ts +5 -0
  34. package/src/lib/constants.js +4 -0
  35. package/src/lib/constants.js.map +1 -1
  36. package/src/lib/declarations.js +2 -0
  37. package/src/lib/declarations.js.map +1 -1
  38. package/src/lib/declarations.server.js +24 -10
  39. package/src/lib/declarations.server.js.map +1 -1
  40. package/src/lib/insights/ai-dataset-catalog.d.ts +49 -0
  41. package/src/lib/insights/ai-dataset-catalog.js +57 -0
  42. package/src/lib/insights/ai-dataset-catalog.js.map +1 -0
  43. package/src/lib/insights/ai-figure-readers.d.ts +6 -39
  44. package/src/lib/insights/ai-figure-readers.js +2 -391
  45. package/src/lib/insights/ai-figure-readers.js.map +1 -1
  46. package/src/lib/insights/ai-insight-digest.d.ts +10 -1
  47. package/src/lib/insights/ai-insight-digest.js +16 -4
  48. package/src/lib/insights/ai-insight-digest.js.map +1 -1
  49. package/src/lib/insights/ai-insight-readers.d.ts +1 -1
  50. package/src/lib/insights/ai-insight-readers.js.map +1 -1
  51. package/src/lib/jobs/ai-job-component-step.d.ts +6 -1
  52. package/src/lib/jobs/ai-job-component-step.js +23 -6
  53. package/src/lib/jobs/ai-job-component-step.js.map +1 -1
  54. package/src/lib/jobs/ai-job-draft-ids.js +11 -0
  55. package/src/lib/jobs/ai-job-draft-ids.js.map +1 -1
  56. package/src/lib/jobs/ai-job-email-step.d.ts +5 -1
  57. package/src/lib/jobs/ai-job-email-step.js +10 -1
  58. package/src/lib/jobs/ai-job-email-step.js.map +1 -1
  59. package/src/lib/jobs/ai-job-form-step.d.ts +17 -1
  60. package/src/lib/jobs/ai-job-form-step.js +60 -8
  61. package/src/lib/jobs/ai-job-form-step.js.map +1 -1
  62. package/src/lib/jobs/ai-job-generation.d.ts +21 -0
  63. package/src/lib/jobs/ai-job-generation.js +53 -1
  64. package/src/lib/jobs/ai-job-generation.js.map +1 -1
  65. package/src/lib/jobs/ai-job-insight-step.js +1 -1
  66. package/src/lib/jobs/ai-job-insight-step.js.map +1 -1
  67. package/src/lib/jobs/ai-job-layout-step.d.ts +15 -4
  68. package/src/lib/jobs/ai-job-layout-step.js +45 -12
  69. package/src/lib/jobs/ai-job-layout-step.js.map +1 -1
  70. package/src/lib/jobs/ai-job-plan-conformance.d.ts +5 -0
  71. package/src/lib/jobs/ai-job-plan-conformance.js +7 -1
  72. package/src/lib/jobs/ai-job-plan-conformance.js.map +1 -1
  73. package/src/lib/jobs/ai-job-plan-creations.d.ts +80 -0
  74. package/src/lib/jobs/ai-job-plan-creations.js +199 -0
  75. package/src/lib/jobs/ai-job-plan-creations.js.map +1 -0
  76. package/src/lib/jobs/ai-job-plan-step.d.ts +8 -2
  77. package/src/lib/jobs/ai-job-plan-step.js +20 -6
  78. package/src/lib/jobs/ai-job-plan-step.js.map +1 -1
  79. package/src/lib/jobs/ai-job-site-step.d.ts +2 -0
  80. package/src/lib/jobs/ai-job-site-step.js +6 -6
  81. package/src/lib/jobs/ai-job-site-step.js.map +1 -1
  82. package/src/lib/jobs/ai-job-template-step.d.ts +9 -6
  83. package/src/lib/jobs/ai-job-template-step.js +72 -15
  84. package/src/lib/jobs/ai-job-template-step.js.map +1 -1
  85. package/src/lib/jobs/ai-jobs.js +1 -1
  86. package/src/lib/jobs/ai-jobs.js.map +1 -1
  87. package/src/lib/jobs/ai-workflow-records.d.ts +5 -4
  88. package/src/lib/jobs/ai-workflow-records.js +26 -22
  89. package/src/lib/jobs/ai-workflow-records.js.map +1 -1
  90. package/src/lib/model/ai-allotments.d.ts +16 -3
  91. package/src/lib/model/ai-allotments.js +34 -11
  92. package/src/lib/model/ai-allotments.js.map +1 -1
  93. package/src/lib/model/ai-job-creations.d.ts +55 -0
  94. package/src/lib/model/ai-job-creations.js +85 -0
  95. package/src/lib/model/ai-job-creations.js.map +1 -0
  96. package/src/lib/model/ai-page-job.d.ts +3 -2
  97. package/src/lib/model/ai-page-job.js +4 -3
  98. package/src/lib/model/ai-page-job.js.map +1 -1
  99. package/src/lib/model/ai-site-job.d.ts +4 -2
  100. package/src/lib/model/ai-site-job.js +8 -4
  101. package/src/lib/model/ai-site-job.js.map +1 -1
  102. package/src/lib/model/ai-template-subjects.d.ts +10 -0
  103. package/src/lib/model/ai-template-subjects.js +14 -0
  104. package/src/lib/model/ai-template-subjects.js.map +1 -1
  105. package/src/lib/model/ai-tokens.js +1 -1
  106. package/src/lib/model/ai-tokens.js.map +1 -1
  107. package/src/lib/model/ai-usage-by-user.js +1 -1
  108. package/src/lib/model/ai-usage-by-user.js.map +1 -1
  109. package/src/lib/providers/catalog.js +1 -1
  110. package/src/lib/providers/catalog.js.map +1 -1
  111. package/src/lib/providers/model-choice.js +1 -1
  112. package/src/lib/providers/model-choice.js.map +1 -1
  113. package/src/lib/runtime/ai-device-audit.d.ts +1 -1
  114. package/src/lib/runtime/ai-device-audit.js +1 -1
  115. package/src/lib/runtime/ai-device-audit.js.map +1 -1
  116. package/src/lib/runtime/ai-eval-live.js +1 -1
  117. package/src/lib/runtime/ai-eval-live.js.map +1 -1
  118. package/src/lib/runtime/ai-eval.d.ts +1 -1
  119. package/src/lib/runtime/ai-eval.js.map +1 -1
  120. package/src/lib/runtime/ai-gate.js +1 -1
  121. package/src/lib/runtime/ai-gate.js.map +1 -1
  122. package/src/lib/runtime/ai-palette.d.ts +1 -1
  123. package/src/lib/runtime/ai-palette.generated.d.ts +1 -1
  124. package/src/lib/runtime/ai-palette.generated.js +1 -1
  125. package/src/lib/runtime/ai-palette.generated.js.map +1 -1
  126. package/src/lib/runtime/ai-palette.js.map +1 -1
  127. package/src/lib/runtime/site-inventory.js +28 -22
  128. package/src/lib/runtime/site-inventory.js.map +1 -1
  129. package/src/lib/server/ai-admin-org.js +1 -1
  130. package/src/lib/server/ai-admin-org.js.map +1 -1
  131. package/src/lib/server/ai-admin-orgs-spend.js +1 -1
  132. package/src/lib/server/ai-admin-orgs-spend.js.map +1 -1
  133. package/src/lib/server/ai-admin-signals.js +1 -1
  134. package/src/lib/server/ai-admin-signals.js.map +1 -1
  135. package/src/lib/server/ai-allotments.js +1 -1
  136. package/src/lib/server/ai-allotments.js.map +1 -1
  137. package/src/lib/server/ai-assist.js +2 -2
  138. package/src/lib/server/ai-assist.js.map +1 -1
  139. package/src/lib/server/assist-chat.d.ts +1 -1
  140. package/src/lib/server/assist-chat.js +2 -2
  141. package/src/lib/server/assist-chat.js.map +1 -1
  142. package/src/lib/server/billing-credits.d.ts +5 -0
  143. package/src/lib/server/billing-credits.js +8 -2
  144. package/src/lib/server/billing-credits.js.map +1 -1
  145. package/src/lib/server/billing-overage.js +2 -2
  146. package/src/lib/server/billing-overage.js.map +1 -1
  147. package/src/lib/testing/stand-in-dataset-index.d.ts +20 -0
  148. package/src/lib/testing/stand-in-dataset-index.js +80 -0
  149. package/src/lib/testing/stand-in-dataset-index.js.map +1 -0
  150. package/src/lib/usage/ai-allotment-alerts.d.ts +10 -7
  151. package/src/lib/usage/ai-allotment-alerts.js +31 -14
  152. package/src/lib/usage/ai-allotment-alerts.js.map +1 -1
  153. package/src/lib/usage/ai-quota-checks.d.ts +37 -0
  154. package/src/lib/usage/ai-quota-checks.js +69 -0
  155. package/src/lib/usage/ai-quota-checks.js.map +1 -0
  156. package/src/lib/usage/ai-usage-alerts.js +22 -10
  157. package/src/lib/usage/ai-usage-alerts.js.map +1 -1
  158. package/src/lib/usage/ai-usage-by-user.js +1 -1
  159. package/src/lib/usage/ai-usage-by-user.js.map +1 -1
  160. package/src/lib/usage/assist-ceiling.d.ts +2 -2
  161. package/src/lib/usage/assist-ceiling.js +4 -4
  162. package/src/lib/usage/assist-ceiling.js.map +1 -1
  163. package/src/lib/usage/assist-credits.d.ts +494 -0
  164. package/src/lib/usage/assist-credits.js +524 -0
  165. package/src/lib/usage/assist-credits.js.map +1 -0
  166. package/src/lib/usage/assist-free-taste.d.ts +1 -1
  167. package/src/lib/usage/assist-free-taste.js +1 -1
  168. package/src/lib/usage/assist-free-taste.js.map +1 -1
  169. package/src/lib/usage/assist-signal-mining.js +1 -1
  170. package/src/lib/usage/assist-signal-mining.js.map +1 -1
  171. package/src/lib/usage/assist-spend-guards.d.ts +153 -0
  172. package/src/lib/usage/assist-spend-guards.js +182 -0
  173. package/src/lib/usage/assist-spend-guards.js.map +1 -0
  174. package/src/lib/usage/assist-usage.d.ts +1 -1
  175. package/src/lib/usage/assist-usage.js +1 -1
  176. package/src/lib/usage/assist-usage.js.map +1 -1
  177. package/src/lib/usage/staff-org-ai.js +1 -1
  178. package/src/lib/usage/staff-org-ai.js.map +1 -1
  179. package/src/lib/usage-axes.d.ts +10 -0
  180. package/src/lib/usage-axes.js +40 -2
  181. package/src/lib/usage-axes.js.map +1 -1
@@ -15,11 +15,10 @@
15
15
  * limitations under the License.
16
16
  */ import { _ as _extends } from "@swc/helpers/_/_extends";
17
17
  import { actionRunResult } from "@aglyn/aglyn/app-utils/activity-presenter";
18
- import { datasetDisplayName } from "@aglyn/aglyn/app-utils/datasets";
19
18
  import { isFormArchived } from "@aglyn/aglyn/app-utils/forms";
20
19
  import { pluginRecordIndex } from "@aglyn/aglyn/plugin-manager/plugin-record-index";
21
- import { campaignPlacedOnHost } from "@aglyn/shared-ui-email-campaigns/model/campaign-container";
22
- import { scopedToHost } from "@aglyn/tenant-data-admin/server/organizations";
20
+ import { visibleToHost } from "@aglyn/aglyn/app-utils/scope-tokens";
21
+ import { listOrgContainers } from "@aglyn/tenant-data-admin/server/org-containers";
23
22
  /** Records of one kind a lookup reads: the Actions editor's picker window. */ export const AI_WORKFLOW_RECORDS_WINDOW = 100;
24
23
  /** Pipelines a stage lookup reads. */ export const AI_WORKFLOW_PIPELINES_WINDOW = 20;
25
24
  function text(value) {
@@ -39,16 +38,22 @@ async function named(query, fields, keep, nameOf) {
39
38
  })).filter((record)=>record.name);
40
39
  }
41
40
  const live = (data)=>data['deletedAt'] == null;
41
+ /** The org's live campaigns placed on the site, named, in the editor's window. */ async function placedCampaigns(firestore, orgId, hostId) {
42
+ const containers = await listOrgContainers(firestore, 'campaign', orgId, AI_WORKFLOW_RECORDS_WINDOW);
43
+ return containers.filter((container)=>container.live && container.name && visibleToHost(container.visibleTo, hostId)).map((container)=>({
44
+ id: container.id,
45
+ name: container.name
46
+ }));
47
+ }
42
48
  /**
43
49
  * The live records of a kind another plugin keeps, through its index, in the
44
50
  * editor's window; none where no plugin keeps the kind here.
45
- */ async function indexed(kind, hostId, keep = ()=>true) {
51
+ */ async function indexed(kind, scope, keep = ()=>true) {
46
52
  const owner = pluginRecordIndex(kind);
47
53
  if (!owner) return [];
48
- const { records } = await owner.index.list({
49
- hostId,
54
+ const { records } = await owner.index.list(_extends({}, scope, {
50
55
  limit: AI_WORKFLOW_RECORDS_WINDOW
51
- });
56
+ }));
52
57
  return records.filter(keep).map(({ id, name })=>({
53
58
  id,
54
59
  name
@@ -81,28 +86,27 @@ const live = (data)=>data['deletedAt'] == null;
81
86
  const none = Promise.resolve([]);
82
87
  const [forms, datasets, lists, campaigns, workflows, webhooks, stages] = await Promise.all([
83
88
  !wanted('forms') ? Promise.resolve([]) : readForms(host),
84
- !wanted('datasets') ? none : named(scopedToHost(org.collection('datasets'), input.hostId), [
85
- 'displayName',
86
- 'name',
87
- 'deletedAt'
88
- ], live, (data, id)=>datasetDisplayName(data) || id),
89
+ // The org's datasets shared with this site, as the data plugin indexes them.
90
+ !wanted('datasets') ? none : indexed('dataset', {
91
+ orgId: input.orgId,
92
+ hostId: input.hostId
93
+ }),
89
94
  !wanted('lists') ? none : named(org.collection('lists'), [
90
95
  'name',
91
96
  'deletedAt'
92
97
  ], live, (data)=>text(data['name'])),
93
98
  // The org's campaigns placed on this site: the set the automation's
94
- // `assignCampaign` step accepts when it runs here.
95
- !wanted('campaigns') ? none : named(org.collection('emailCampaigns'), [
96
- 'name',
97
- 'deletedAt',
98
- 'visibleTo'
99
- ], (data)=>live(data) && campaignPlacedOnHost({
100
- visibleTo: data['visibleTo']
101
- }, input.hostId), (data)=>text(data['name'])),
102
- !wanted('workflows') ? none : indexed('workflow', input.hostId),
99
+ // `assignCampaign` step accepts when it runs here. Read as the `campaign`
100
+ // container kind, where its declaration says the containers are stored.
101
+ !wanted('campaigns') ? none : placedCampaigns(firestore, input.orgId, input.hostId),
102
+ !wanted('workflows') ? none : indexed('workflow', {
103
+ hostId: input.hostId
104
+ }),
103
105
  // Only a webhook that posts OUT is a step's target; an inbound one is an
104
106
  // endpoint that runs a workflow.
105
- !wanted('webhooks') ? none : indexed('webhook', input.hostId, (record)=>record.facts['direction'] === 'outbound'),
107
+ !wanted('webhooks') ? none : indexed('webhook', {
108
+ hostId: input.hostId
109
+ }, (record)=>record.facts['direction'] === 'outbound'),
106
110
  input.crm && wanted('stages') ? readStages(input.orgId, input.hostId) : none
107
111
  ]);
108
112
  return {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-workflow-records.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { HostAction } from '@aglyn/aglyn/app-utils/actions'\nimport { actionRunResult } from '@aglyn/aglyn/app-utils/activity-presenter'\nimport { datasetDisplayName } from '@aglyn/aglyn/app-utils/datasets'\nimport { isFormArchived } from '@aglyn/aglyn/app-utils/forms'\nimport {\n pluginRecordIndex,\n type PluginIndexedRecord,\n} from '@aglyn/aglyn/plugin-manager/plugin-record-index'\nimport { campaignPlacedOnHost } from '@aglyn/shared-ui-email-campaigns/model/campaign-container'\nimport { scopedToHost } from '@aglyn/tenant-data-admin/server/organizations'\nimport type {\n AiAutomationForm,\n AiAutomationNamedRecord,\n AiAutomationRecords,\n} from '../model/ai-automation-draft'\nimport type { AiIndexedWorkflow, AiRunRecord } from '../model/ai-automation-outline'\nimport type { AiWorkflowTargetType } from '../model/ai-workflow-job'\n\n/**\n * What a `workflow` job reads (AGL-2919), scoped to the job's own site and\n * org: the records a drafted automation's words are looked up among, the\n * automation an explanation reads, and the run it explains. Every read is\n * windowed the way the Actions editor's pickers are, so a lookup never reads\n * more than the editor would offer.\n *\n * The site's workflows, webhooks and saved actions are the workflows plugin's\n * records, so they are read through the indexes that plugin publishes\n * (`workflow`, `webhook`, `action` — AGL-3080), never from its collections:\n * where no plugin keeps a kind, there are none to name. The rest are read\n * through the Admin SDK as projections of the fields named here.\n */\n\ntype Firestore = FirebaseFirestore.Firestore\ntype Data = Record<string, unknown>\n\n/** Records of one kind a lookup reads: the Actions editor's picker window. */\nexport const AI_WORKFLOW_RECORDS_WINDOW = 100\n\n/** Pipelines a stage lookup reads. */\nexport const AI_WORKFLOW_PIPELINES_WINDOW = 20\n\nfunction text(value: unknown): string {\n return typeof value === 'string' ? value.trim() : ''\n}\n\nasync function named(\n query: FirebaseFirestore.Query,\n fields: string[],\n keep: (data: Data) => boolean,\n nameOf: (data: Data, id: string) => string,\n): Promise<AiAutomationNamedRecord[]> {\n const snapshot = await query\n .select(...fields)\n .limit(AI_WORKFLOW_RECORDS_WINDOW)\n .get()\n return snapshot.docs\n .map((doc) => ({ data: (doc.data() ?? {}) as Data, id: doc.id }))\n .filter(({ data }) => keep(data))\n .map(({ data, id }) => ({ id, name: nameOf(data, id) }))\n .filter((record) => record.name)\n}\n\nconst live = (data: Data) => data['deletedAt'] == null\n\n/**\n * The live records of a kind another plugin keeps, through its index, in the\n * editor's window; none where no plugin keeps the kind here.\n */\nasync function indexed(\n kind: string,\n hostId: string,\n keep: (record: PluginIndexedRecord) => boolean = () => true,\n): Promise<AiAutomationNamedRecord[]> {\n const owner = pluginRecordIndex(kind)\n if (!owner) return []\n const { records } = await owner.index.list({ hostId, limit: AI_WORKFLOW_RECORDS_WINDOW })\n return records.filter(keep).map(({ id, name }) => ({ id, name }))\n}\n\n/** The site's forms that are not archived, with the field names their submissions carry. */\nasync function readForms(host: FirebaseFirestore.DocumentReference): Promise<AiAutomationForm[]> {\n const snapshot = await host\n .collection('forms')\n .select('displayName', 'slug', 'fields', 'archivedAt')\n .limit(AI_WORKFLOW_RECORDS_WINDOW)\n .get()\n return snapshot.docs\n .filter((doc) => !isFormArchived((doc.data() ?? {}) as { archivedAt?: unknown }))\n .map((doc) => {\n const data = (doc.data() ?? {}) as Data\n return {\n id: doc.id,\n name: text(data['displayName']) || text(data['slug']) || doc.id,\n fields: (Array.isArray(data['fields']) ? (data['fields'] as Data[]) : [])\n .map((field) => text(field?.['fieldName']))\n .filter(Boolean),\n }\n })\n}\n\n/**\n * The site's records a drafted automation may name. Stages are read only for\n * a workspace with the CRM, whose pipelines they are; a site without it has\n * no stage a condition could name. `only`, when given, names the kinds to\n * read, and every other kind is answered empty without a read.\n */\nexport async function readAiAutomationRecords(\n firestore: Firestore,\n input: { orgId: string; hostId: string; crm: boolean; only?: ReadonlyArray<keyof AiAutomationRecords> },\n): Promise<AiAutomationRecords> {\n const host = firestore.collection('hosts').doc(input.hostId)\n const org = firestore.collection('orgs').doc(input.orgId)\n const wanted = (kind: keyof AiAutomationRecords) => !input.only || input.only.includes(kind)\n const none = Promise.resolve([] as AiAutomationNamedRecord[])\n const [forms, datasets, lists, campaigns, workflows, webhooks, stages] = await Promise.all([\n !wanted('forms') ? Promise.resolve([] as AiAutomationForm[]) : readForms(host),\n !wanted('datasets')\n ? none\n : named(\n scopedToHost(org.collection('datasets'), input.hostId),\n ['displayName', 'name', 'deletedAt'],\n live,\n (data, id) => datasetDisplayName(data) || id,\n ),\n !wanted('lists') ? none : named(org.collection('lists'), ['name', 'deletedAt'], live, (data) => text(data['name'])),\n // The org's campaigns placed on this site: the set the automation's\n // `assignCampaign` step accepts when it runs here.\n !wanted('campaigns')\n ? none\n : named(\n org.collection('emailCampaigns'),\n ['name', 'deletedAt', 'visibleTo'],\n (data) =>\n live(data) &&\n campaignPlacedOnHost({ visibleTo: data['visibleTo'] as string[] | undefined }, input.hostId),\n (data) => text(data['name']),\n ),\n !wanted('workflows') ? none : indexed('workflow', input.hostId),\n // Only a webhook that posts OUT is a step's target; an inbound one is an\n // endpoint that runs a workflow.\n !wanted('webhooks')\n ? none\n : indexed('webhook', input.hostId, (record) => record.facts['direction'] === 'outbound'),\n input.crm && wanted('stages') ? readStages(input.orgId, input.hostId) : none,\n ])\n return { forms, datasets, lists, campaigns, workflows, webhooks, stages }\n}\n\n/**\n * The stages of the pipelines the site can see, asked of the plugin that keeps\n * pipelines (its `pipeline` record index), never read from its collection. No\n * index means no plugin keeps pipelines in this process: no stage to name.\n */\nasync function readStages(orgId: string, hostId: string): Promise<AiAutomationNamedRecord[]> {\n const pipelines = pluginRecordIndex('pipeline')\n if (!pipelines) return []\n const { records } = await pipelines.index.list({ orgId, hostId, limit: AI_WORKFLOW_PIPELINES_WINDOW })\n return records\n .flatMap((record) => (Array.isArray(record.facts['stages']) ? (record.facts['stages'] as Data[]) : []))\n .map((stage) => ({ id: text(stage?.['id']), name: text(stage?.['name']) }))\n .filter((stage) => stage.id && stage.name)\n}\n\n/** The site's functions, for a workflow outline that says which of its calls still resolve. */\nexport async function readAiWorkflowFunctions(\n firestore: Firestore,\n hostId: string,\n): Promise<AiAutomationNamedRecord[]> {\n return named(\n firestore.collection('hosts').doc(hostId).collection('functions'),\n ['name', 'deletedAt'],\n live,\n (data) => text(data['name']),\n )\n}\n\nexport type AiWorkflowTarget =\n | { type: 'action'; id: string; name: string; action: HostAction }\n | { type: 'workflow'; id: string; name: string; workflow: AiIndexedWorkflow }\n\n/**\n * A saved automation of the site, read through the index of the plugin that\n * keeps it, or `null` for one that does not exist, was deleted, or that no\n * plugin here keeps.\n */\nexport async function readAiWorkflowTarget(\n input: { hostId: string; type: AiWorkflowTargetType; id: string },\n): Promise<AiWorkflowTarget | null> {\n const owner = pluginRecordIndex(input.type)\n const record = owner ? await owner.index.get({ hostId: input.hostId, id: input.id }) : null\n if (!record) return null\n const stored = { name: record.name, ...record.facts }\n return input.type === 'action'\n ? { type: 'action', id: record.id, name: record.name, action: stored as unknown as HostAction }\n : { type: 'workflow', id: record.id, name: record.name, workflow: stored as unknown as AiIndexedWorkflow }\n}\n\nexport type AiWorkflowRunRead =\n | { ok: true; run: AiRunRecord }\n | { ok: false; reason: 'gone' | 'not-failed' }\n\n/**\n * One run of an automation, as the site's activity log recorded it: gone when\n * there is no such entry or it belongs to another automation, and refused\n * when it did not fail. Only what the run history shows is read — never the\n * event's payload.\n */\nexport async function readAiWorkflowRun(\n firestore: Firestore,\n input: { hostId: string; targetId: string; runId: string },\n): Promise<AiWorkflowRunRead> {\n const snapshot = await firestore\n .collection('hosts')\n .doc(input.hostId)\n .collection('activity')\n .doc(input.runId)\n .get()\n const data = snapshot.exists ? ((snapshot.data() ?? {}) as Data) : null\n const target = data?.['target'] as { id?: unknown } | undefined\n if (!data || target?.id !== input.targetId) return { ok: false, reason: 'gone' }\n const run: AiRunRecord = {\n result: data['result'],\n trigger: data['trigger'],\n summary: data['summary'],\n action: data['action'],\n createdAt: data['createdAt'],\n }\n return actionRunResult(run as never) === 'failed' ? { ok: true, run } : { ok: false, reason: 'not-failed' }\n}\n"],"names":["actionRunResult","datasetDisplayName","isFormArchived","pluginRecordIndex","campaignPlacedOnHost","scopedToHost","AI_WORKFLOW_RECORDS_WINDOW","AI_WORKFLOW_PIPELINES_WINDOW","text","value","trim","named","query","fields","keep","nameOf","snapshot","select","limit","get","docs","map","doc","data","id","filter","name","record","live","indexed","kind","hostId","owner","records","index","list","readForms","host","collection","Array","isArray","field","Boolean","readAiAutomationRecords","firestore","input","org","orgId","wanted","only","includes","none","Promise","resolve","forms","datasets","lists","campaigns","workflows","webhooks","stages","all","visibleTo","facts","crm","readStages","pipelines","flatMap","stage","readAiWorkflowFunctions","readAiWorkflowTarget","type","stored","action","workflow","readAiWorkflowRun","runId","exists","target","targetId","ok","reason","run","result","trigger","summary","createdAt"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAGD,SAASA,eAAe,QAAQ,4CAA2C;AAC3E,SAASC,kBAAkB,QAAQ,kCAAiC;AACpE,SAASC,cAAc,QAAQ,+BAA8B;AAC7D,SACEC,iBAAiB,QAEZ,kDAAiD;AACxD,SAASC,oBAAoB,QAAQ,4DAA2D;AAChG,SAASC,YAAY,QAAQ,gDAA+C;AA0B5E,4EAA4E,GAC5E,OAAO,MAAMC,6BAA6B,IAAG;AAE7C,oCAAoC,GACpC,OAAO,MAAMC,+BAA+B,GAAE;AAE9C,SAASC,KAAKC,KAAc;IAC1B,OAAO,OAAOA,UAAU,WAAWA,MAAMC,IAAI,KAAK;AACpD;AAEA,eAAeC,MACbC,KAA8B,EAC9BC,MAAgB,EAChBC,IAA6B,EAC7BC,MAA0C;IAE1C,MAAMC,WAAW,MAAMJ,MACpBK,MAAM,IAAIJ,QACVK,KAAK,CAACZ,4BACNa,GAAG;IACN,OAAOH,SAASI,IAAI,CACjBC,GAAG,CAAC,CAACC;YAAkBA;eAAT;YAAEC,IAAI,GAAGD,YAAAA,IAAIC,IAAI,cAARD,YAAc,CAAC;YAAYE,IAAIF,IAAIE,EAAE;QAAC;OAC7DC,MAAM,CAAC,CAAC,EAAEF,IAAI,EAAE,GAAKT,KAAKS,OAC1BF,GAAG,CAAC,CAAC,EAAEE,IAAI,EAAEC,EAAE,EAAE,GAAM,CAAA;YAAEA;YAAIE,MAAMX,OAAOQ,MAAMC;QAAI,CAAA,GACpDC,MAAM,CAAC,CAACE,SAAWA,OAAOD,IAAI;AACnC;AAEA,MAAME,OAAO,CAACL,OAAeA,IAAI,CAAC,YAAY,IAAI;AAElD;;;CAGC,GACD,eAAeM,QACbC,IAAY,EACZC,MAAc,EACdjB,OAAiD,IAAM,IAAI;IAE3D,MAAMkB,QAAQ7B,kBAAkB2B;IA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0B,IAAI,KAAK,WAClB;QAAEA,MAAM;QAAU/C,IAAIG,OAAOH,EAAE;QAAEE,MAAMC,OAAOD,IAAI;QAAE+C,QAAQD;IAAgC,IAC5F;QAAED,MAAM;QAAY/C,IAAIG,OAAOH,EAAE;QAAEE,MAAMC,OAAOD,IAAI;QAAEgD,UAAUF;IAAuC;AAC7G;AAMA;;;;;CAKC,GACD,OAAO,eAAeG,kBACpB/B,SAAoB,EACpBC,KAA0D;QAQzB7B;IANjC,MAAMA,WAAW,MAAM4B,UACpBN,UAAU,CAAC,SACXhB,GAAG,CAACuB,MAAMd,MAAM,EAChBO,UAAU,CAAC,YACXhB,GAAG,CAACuB,MAAM+B,KAAK,EACfzD,GAAG;IACN,MAAMI,OAAOP,SAAS6D,MAAM,IAAK7D,iBAAAA,SAASO,IAAI,cAAbP,iBAAmB,CAAC,IAAc;IACnE,MAAM8D,SAASvD,wBAAAA,IAAM,CAAC,SAAS;IAC/B,IAAI,CAACA,QAAQuD,CAAAA,0BAAAA,OAAQtD,EAAE,MAAKqB,MAAMkC,QAAQ,EAAE,OAAO;QAAEC,IAAI;QAAOC,QAAQ;IAAO;IAC/E,MAAMC,MAAmB;QACvBC,QAAQ5D,IAAI,CAAC,SAAS;QACtB6D,SAAS7D,IAAI,CAAC,UAAU;QACxB8D,SAAS9D,IAAI,CAAC,UAAU;QACxBkD,QAAQlD,IAAI,CAAC,SAAS;QACtB+D,WAAW/D,IAAI,CAAC,YAAY;IAC9B;IACA,OAAOvB,gBAAgBkF,SAAkB,WAAW;QAAEF,IAAI;QAAME;IAAI,IAAI;QAAEF,IAAI;QAAOC,QAAQ;IAAa;AAC5G"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/jobs/ai-workflow-records.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { HostAction } from '@aglyn/aglyn/app-utils/actions'\nimport { actionRunResult } from '@aglyn/aglyn/app-utils/activity-presenter'\nimport { isFormArchived } from '@aglyn/aglyn/app-utils/forms'\nimport {\n pluginRecordIndex,\n type PluginIndexedRecord,\n} from '@aglyn/aglyn/plugin-manager/plugin-record-index'\nimport { visibleToHost } from '@aglyn/aglyn/app-utils/scope-tokens'\nimport { listOrgContainers } from '@aglyn/tenant-data-admin/server/org-containers'\nimport type {\n AiAutomationForm,\n AiAutomationNamedRecord,\n AiAutomationRecords,\n} from '../model/ai-automation-draft'\nimport type { AiIndexedWorkflow, AiRunRecord } from '../model/ai-automation-outline'\nimport type { AiWorkflowTargetType } from '../model/ai-workflow-job'\n\n/**\n * What a `workflow` job reads (AGL-2919), scoped to the job's own site and\n * org: the records a drafted automation's words are looked up among, the\n * automation an explanation reads, and the run it explains. Every read is\n * windowed the way the Actions editor's pickers are, so a lookup never reads\n * more than the editor would offer.\n *\n * The site's workflows, webhooks and saved actions are the workflows plugin's\n * records, and the org's datasets the data plugin's, so they are read through\n * the indexes those plugins publish (`workflow`, `webhook`, `action`,\n * `dataset` — AGL-3080), never from their collections: where no plugin keeps a\n * kind, there are none to name. The rest are read through the Admin SDK as\n * projections of the fields named here.\n */\n\ntype Firestore = FirebaseFirestore.Firestore\ntype Data = Record<string, unknown>\n\n/** Records of one kind a lookup reads: the Actions editor's picker window. */\nexport const AI_WORKFLOW_RECORDS_WINDOW = 100\n\n/** Pipelines a stage lookup reads. */\nexport const AI_WORKFLOW_PIPELINES_WINDOW = 20\n\nfunction text(value: unknown): string {\n return typeof value === 'string' ? value.trim() : ''\n}\n\nasync function named(\n query: FirebaseFirestore.Query,\n fields: string[],\n keep: (data: Data) => boolean,\n nameOf: (data: Data, id: string) => string,\n): Promise<AiAutomationNamedRecord[]> {\n const snapshot = await query\n .select(...fields)\n .limit(AI_WORKFLOW_RECORDS_WINDOW)\n .get()\n return snapshot.docs\n .map((doc) => ({ data: (doc.data() ?? {}) as Data, id: doc.id }))\n .filter(({ data }) => keep(data))\n .map(({ data, id }) => ({ id, name: nameOf(data, id) }))\n .filter((record) => record.name)\n}\n\nconst live = (data: Data) => data['deletedAt'] == null\n\n/** The org's live campaigns placed on the site, named, in the editor's window. */\nasync function placedCampaigns(\n firestore: Firestore,\n orgId: string,\n hostId: string,\n): Promise<AiAutomationNamedRecord[]> {\n const containers = await listOrgContainers(firestore, 'campaign', orgId, AI_WORKFLOW_RECORDS_WINDOW)\n return containers\n .filter((container) => container.live && container.name && visibleToHost(container.visibleTo, hostId))\n .map((container) => ({ id: container.id, name: container.name }))\n}\n\n/**\n * The live records of a kind another plugin keeps, through its index, in the\n * editor's window; none where no plugin keeps the kind here.\n */\nasync function indexed(\n kind: string,\n scope: { orgId?: string; hostId: string },\n keep: (record: PluginIndexedRecord) => boolean = () => true,\n): Promise<AiAutomationNamedRecord[]> {\n const owner = pluginRecordIndex(kind)\n if (!owner) return []\n const { records } = await owner.index.list({ ...scope, limit: AI_WORKFLOW_RECORDS_WINDOW })\n return records.filter(keep).map(({ id, name }) => ({ id, name }))\n}\n\n/** The site's forms that are not archived, with the field names their submissions carry. */\nasync function readForms(host: FirebaseFirestore.DocumentReference): Promise<AiAutomationForm[]> {\n const snapshot = await host\n .collection('forms')\n .select('displayName', 'slug', 'fields', 'archivedAt')\n .limit(AI_WORKFLOW_RECORDS_WINDOW)\n .get()\n return snapshot.docs\n .filter((doc) => !isFormArchived((doc.data() ?? {}) as { archivedAt?: unknown }))\n .map((doc) => {\n const data = (doc.data() ?? {}) as Data\n return {\n id: doc.id,\n name: text(data['displayName']) || text(data['slug']) || doc.id,\n fields: (Array.isArray(data['fields']) ? (data['fields'] as Data[]) : [])\n .map((field) => text(field?.['fieldName']))\n .filter(Boolean),\n }\n })\n}\n\n/**\n * The site's records a drafted automation may name. Stages are read only for\n * a workspace with the CRM, whose pipelines they are; a site without it has\n * no stage a condition could name. `only`, when given, names the kinds to\n * read, and every other kind is answered empty without a read.\n */\nexport async function readAiAutomationRecords(\n firestore: Firestore,\n input: { orgId: string; hostId: string; crm: boolean; only?: ReadonlyArray<keyof AiAutomationRecords> },\n): Promise<AiAutomationRecords> {\n const host = firestore.collection('hosts').doc(input.hostId)\n const org = firestore.collection('orgs').doc(input.orgId)\n const wanted = (kind: keyof AiAutomationRecords) => !input.only || input.only.includes(kind)\n const none = Promise.resolve([] as AiAutomationNamedRecord[])\n const [forms, datasets, lists, campaigns, workflows, webhooks, stages] = await Promise.all([\n !wanted('forms') ? Promise.resolve([] as AiAutomationForm[]) : readForms(host),\n // The org's datasets shared with this site, as the data plugin indexes them.\n !wanted('datasets') ? none : indexed('dataset', { orgId: input.orgId, hostId: input.hostId }),\n !wanted('lists') ? none : named(org.collection('lists'), ['name', 'deletedAt'], live, (data) => text(data['name'])),\n // The org's campaigns placed on this site: the set the automation's\n // `assignCampaign` step accepts when it runs here. Read as the `campaign`\n // container kind, where its declaration says the containers are stored.\n !wanted('campaigns') ? none : placedCampaigns(firestore, input.orgId, input.hostId),\n !wanted('workflows') ? none : indexed('workflow', { hostId: input.hostId }),\n // Only a webhook that posts OUT is a step's target; an inbound one is an\n // endpoint that runs a workflow.\n !wanted('webhooks')\n ? none\n : indexed('webhook', { hostId: input.hostId }, (record) => record.facts['direction'] === 'outbound'),\n input.crm && wanted('stages') ? readStages(input.orgId, input.hostId) : none,\n ])\n return { forms, datasets, lists, campaigns, workflows, webhooks, stages }\n}\n\n/**\n * The stages of the pipelines the site can see, asked of the plugin that keeps\n * pipelines (its `pipeline` record index), never read from its collection. No\n * index means no plugin keeps pipelines in this process: no stage to name.\n */\nasync function readStages(orgId: string, hostId: string): Promise<AiAutomationNamedRecord[]> {\n const pipelines = pluginRecordIndex('pipeline')\n if (!pipelines) return []\n const { records } = await pipelines.index.list({ orgId, hostId, limit: AI_WORKFLOW_PIPELINES_WINDOW })\n return records\n .flatMap((record) => (Array.isArray(record.facts['stages']) ? (record.facts['stages'] as Data[]) : []))\n .map((stage) => ({ id: text(stage?.['id']), name: text(stage?.['name']) }))\n .filter((stage) => stage.id && stage.name)\n}\n\n/** The site's functions, for a workflow outline that says which of its calls still resolve. */\nexport async function readAiWorkflowFunctions(\n firestore: Firestore,\n hostId: string,\n): Promise<AiAutomationNamedRecord[]> {\n return named(\n firestore.collection('hosts').doc(hostId).collection('functions'),\n ['name', 'deletedAt'],\n live,\n (data) => text(data['name']),\n )\n}\n\nexport type AiWorkflowTarget =\n | { type: 'action'; id: string; name: string; action: HostAction }\n | { type: 'workflow'; id: string; name: string; workflow: AiIndexedWorkflow }\n\n/**\n * A saved automation of the site, read through the index of the plugin that\n * keeps it, or `null` for one that does not exist, was deleted, or that no\n * plugin here keeps.\n */\nexport async function readAiWorkflowTarget(\n input: { hostId: string; type: AiWorkflowTargetType; id: string },\n): Promise<AiWorkflowTarget | null> {\n const owner = pluginRecordIndex(input.type)\n const record = owner ? await owner.index.get({ hostId: input.hostId, id: input.id }) : null\n if (!record) return null\n const stored = { name: record.name, ...record.facts }\n return input.type === 'action'\n ? { type: 'action', id: record.id, name: record.name, action: stored as unknown as HostAction }\n : { type: 'workflow', id: record.id, name: record.name, workflow: stored as unknown as AiIndexedWorkflow }\n}\n\nexport type AiWorkflowRunRead =\n | { ok: true; run: AiRunRecord }\n | { ok: false; reason: 'gone' | 'not-failed' }\n\n/**\n * One run of an automation, as the site's activity log recorded it: gone when\n * there is no such entry or it belongs to another automation, and refused\n * when it did not fail. Only what the run history shows is read — never the\n * event's payload.\n */\nexport async function readAiWorkflowRun(\n firestore: Firestore,\n input: { hostId: string; targetId: string; runId: string },\n): Promise<AiWorkflowRunRead> {\n const snapshot = await firestore\n .collection('hosts')\n .doc(input.hostId)\n .collection('activity')\n .doc(input.runId)\n .get()\n const data = snapshot.exists ? ((snapshot.data() ?? {}) as Data) : null\n const target = data?.['target'] as { id?: unknown } | undefined\n if (!data || target?.id !== input.targetId) return { ok: false, reason: 'gone' }\n const run: AiRunRecord = {\n result: data['result'],\n trigger: data['trigger'],\n summary: data['summary'],\n action: data['action'],\n createdAt: data['createdAt'],\n }\n return actionRunResult(run as never) === 'failed' ? { ok: true, run } : { ok: false, reason: 'not-failed' }\n}\n"],"names":["actionRunResult","isFormArchived","pluginRecordIndex","visibleToHost","listOrgContainers","AI_WORKFLOW_RECORDS_WINDOW","AI_WORKFLOW_PIPELINES_WINDOW","text","value","trim","named","query","fields","keep","nameOf","snapshot","select","limit","get","docs","map","doc","data","id","filter","name","record","live","placedCampaigns","firestore","orgId","hostId","containers","container","visibleTo","indexed","kind","scope","owner","records","index","list","readForms","host","collection","Array","isArray","field","Boolean","readAiAutomationRecords","input","org","wanted","only","includes","none","Promise","resolve","forms","datasets","lists","campaigns","workflows","webhooks","stages","all","facts","crm","readStages","pipelines","flatMap","stage","readAiWorkflowFunctions","readAiWorkflowTarget","type","stored","action","workflow","readAiWorkflowRun","runId","exists","target","targetId","ok","reason","run","result","trigger","summary","createdAt"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAGD,SAASA,eAAe,QAAQ,4CAA2C;AAC3E,SAASC,cAAc,QAAQ,+BAA8B;AAC7D,SACEC,iBAAiB,QAEZ,kDAAiD;AACxD,SAASC,aAAa,QAAQ,sCAAqC;AACnE,SAASC,iBAAiB,QAAQ,iDAAgD;AA2BlF,4EAA4E,GAC5E,OAAO,MAAMC,6BAA6B,IAAG;AAE7C,oCAAoC,GACpC,OAAO,MAAMC,+BAA+B,GAAE;AAE9C,SAASC,KAAKC,KAAc;IAC1B,OAAO,OAAOA,UAAU,WAAWA,MAAMC,IAAI,KAAK;AACpD;AAEA,eAAeC,MACbC,KAA8B,EAC9BC,MAAgB,EAChBC,IAA6B,EAC7BC,MAA0C;IAE1C,MAAMC,WAAW,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B,MAAM,EAChBa,UAAU,CAAC,YACXvB,GAAG,CAAC6B,MAAM6B,KAAK,EACf7D,GAAG;IACN,MAAMI,OAAOP,SAASiE,MAAM,IAAKjE,iBAAAA,SAASO,IAAI,cAAbP,iBAAmB,CAAC,IAAc;IACnE,MAAMkE,SAAS3D,wBAAAA,IAAM,CAAC,SAAS;IAC/B,IAAI,CAACA,QAAQ2D,CAAAA,0BAAAA,OAAQ1D,EAAE,MAAK2B,MAAMgC,QAAQ,EAAE,OAAO;QAAEC,IAAI;QAAOC,QAAQ;IAAO;IAC/E,MAAMC,MAAmB;QACvBC,QAAQhE,IAAI,CAAC,SAAS;QACtBiE,SAASjE,IAAI,CAAC,UAAU;QACxBkE,SAASlE,IAAI,CAAC,UAAU;QACxBsD,QAAQtD,IAAI,CAAC,SAAS;QACtBmE,WAAWnE,IAAI,CAAC,YAAY;IAC9B;IACA,OAAOtB,gBAAgBqF,SAAkB,WAAW;QAAEF,IAAI;QAAME;IAAI,IAAI;QAAEF,IAAI;QAAOC,QAAQ;IAAa;AAC5G"}
@@ -14,7 +14,7 @@
14
14
  * See the License for the specific language governing permissions and
15
15
  * limitations under the License.
16
16
  */
17
- import { type AssistRefusedBy } from '@aglyn/aglyn/app-utils/assist-credits';
17
+ import { type AssistRefusedBy } from '../usage/assist-credits';
18
18
  /**
19
19
  * AI ALLOTMENTS (AGL-2942): the pure half.
20
20
  *
@@ -45,7 +45,7 @@ import { type AssistRefusedBy } from '@aglyn/aglyn/app-utils/assist-credits';
45
45
  *
46
46
  * A HARD allotment refuses the request that finds the subject at or past it.
47
47
  * A SOFT one admits it and tells the subject and the workspace's billing
48
- * contacts at 80% and again at 100%. Both are measured against what the
48
+ * contacts at 75, 80, 90 and 100%. Both are measured against what the
49
49
  * subject already drew this month, before the request — the same shape the
50
50
  * band is measured in, so a request that starts under the line may finish
51
51
  * past it, and the next one is the one refused.
@@ -202,14 +202,27 @@ export declare function aiAllotmentRefusalText(scope: AiCreditAllotmentScope | n
202
202
  /**
203
203
  * The words a soft allotment's alert carries, for BOTH channels — the
204
204
  * console notification and the email — so the two cannot say different
205
- * things about one crossing. `name` is the member's name or the site's.
205
+ * things about one crossing.
206
+ *
207
+ * The email is plain text with no heading, so the body opens by saying whose
208
+ * AI credits, how many of how many, and in which workspace (and on which site,
209
+ * for a collaborator): a figure on its own reads as a bill. The managers'
210
+ * copy says how to stop the subject at the line; the person's own copy does
211
+ * not, because they cannot open Billing.
206
212
  */
207
213
  export declare function aiAllotmentAlertCopy(input: {
208
214
  scope: AiCreditAllotmentScope;
209
215
  threshold: AiAllotmentThreshold;
210
216
  used: number;
211
217
  credits: number;
218
+ /** The member's name, or the site's for a site allotment. */
212
219
  name: string;
220
+ /** The workspace the allotment is drawn from. */
221
+ workspace: string;
222
+ /** The site a collaborator's allotment is on. */
223
+ site?: string;
224
+ /** The workspace's managers (the default), or the person it is for. */
225
+ reader?: 'managers' | 'subject';
213
226
  }): {
214
227
  title: string;
215
228
  body: string;
@@ -13,7 +13,7 @@
13
13
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
14
  * See the License for the specific language governing permissions and
15
15
  * limitations under the License.
16
- */ import { ASSIST_HARD_CAP_CONTROL_LOCATION } from "@aglyn/aglyn/app-utils/assist-credits";
16
+ */ import { ASSIST_HARD_CAP_CONTROL_LOCATION } from "../usage/assist-credits.js";
17
17
  import { ORG_PERMISSIONS } from "@aglyn/aglyn/app-utils/org-permissions";
18
18
  /**
19
19
  * AI ALLOTMENTS (AGL-2942): the pure half.
@@ -45,7 +45,7 @@ import { ORG_PERMISSIONS } from "@aglyn/aglyn/app-utils/org-permissions";
45
45
  *
46
46
  * A HARD allotment refuses the request that finds the subject at or past it.
47
47
  * A SOFT one admits it and tells the subject and the workspace's billing
48
- * contacts at 80% and again at 100%. Both are measured against what the
48
+ * contacts at 75, 80, 90 and 100%. Both are measured against what the
49
49
  * subject already drew this month, before the request — the same shape the
50
50
  * band is measured in, so a request that starts under the line may finish
51
51
  * past it, and the next one is the one refused.
@@ -265,21 +265,44 @@ const scopeRank = (scope)=>SCOPE_ORDER.indexOf(scope);
265
265
  /**
266
266
  * The words a soft allotment's alert carries, for BOTH channels — the
267
267
  * console notification and the email — so the two cannot say different
268
- * things about one crossing. `name` is the member's name or the site's.
268
+ * things about one crossing.
269
+ *
270
+ * The email is plain text with no heading, so the body opens by saying whose
271
+ * AI credits, how many of how many, and in which workspace (and on which site,
272
+ * for a collaborator): a figure on its own reads as a bill. The managers'
273
+ * copy says how to stop the subject at the line; the person's own copy does
274
+ * not, because they cannot open Billing.
269
275
  */ export function aiAllotmentAlertCopy(input) {
270
- const who = input.scope === 'host' ? `The ${input.name} site` : input.name;
271
- const whose = input.scope === 'host' ? 'its' : 'their';
272
- const where = input.scope === 'collab' ? ' on its site' : '';
273
- const figures = `${input.used.toLocaleString('en-US')} of ` + `${input.credits.toLocaleString('en-US')} credits used this month.`;
274
- if (input.threshold >= 100) {
276
+ const { scope, threshold, name, workspace } = input;
277
+ const used = input.used.toLocaleString('en-US');
278
+ const credits = input.credits.toLocaleString('en-US');
279
+ const reached = threshold >= 100;
280
+ const onSite = scope === 'collab' && input.site ? ` on the ${input.site} site` : '';
281
+ const amount = reached ? `all ${credits} AI credits` : `${used} of the ${credits} AI credits`;
282
+ const tail = reached ? ` this month (${used} so far).` : ` this month, past the ${threshold}% mark.`;
283
+ if (input.reader === 'subject' && scope !== 'host') {
284
+ const where = scope === 'collab' ? onSite : ` in ${workspace}`;
285
+ const whoCanChange = scope === 'collab' ? 'The site’s admin or a workspace admin can raise or change it.' : 'A workspace admin can raise or change it.';
286
+ return {
287
+ title: reached ? `You’ve used your whole AI allotment${where}` : `You’re past ${threshold}% of your AI allotment${where}`,
288
+ body: `You’ve used ${amount} ${workspace} allotted you${onSite}${tail} ` + 'It’s a soft allotment, so it does not stop your AI requests.' + (reached ? ` ${whoCanChange}` : '')
289
+ };
290
+ }
291
+ const who = scope === 'host' ? `The ${name} site` : name;
292
+ const whose = scope === 'host' ? 'its' : 'their';
293
+ const them = scope === 'host' ? 'it' : 'them';
294
+ const requests = scope === 'host' ? 'AI requests on the site' : `${name}’s AI requests`;
295
+ const where = scope === 'collab' ? onSite : scope === 'member' ? ` in ${workspace}` : '';
296
+ const opening = `${who} has used ${amount} allotted to ${them}${onSite} in ${workspace}${tail}`;
297
+ if (reached) {
275
298
  return {
276
299
  title: `${who} has used ${whose} whole AI allotment${where}`,
277
- body: `${figures} The allotment is soft, so requests keep working and ` + 'draw on the workspace’s pool. Raise it or make it hard under ' + `${ASSIST_HARD_CAP_CONTROL_LOCATION}.`
300
+ body: `${opening} It’s a soft allotment, so it does not stop ${requests}; ` + 'they keep drawing on the workspace’s AI credits, and crossing it ' + `charges nothing by itself. To stop ${them} at the line, make it hard ` + `under ${ASSIST_HARD_CAP_CONTROL_LOCATION}; to give ${them} more, ` + 'raise it there.'
278
301
  };
279
302
  }
280
303
  return {
281
- title: `${who} is past ${input.threshold}% of ${whose} AI allotment${where}`,
282
- body: `${figures} The allotment is soft, so nothing stops at the line.`
304
+ title: `${who} is past ${threshold}% of ${whose} AI allotment${where}`,
305
+ body: `${opening} It’s a soft allotment, so it does not stop ${requests}; ` + 'they draw on the workspace’s AI credits like everyone else’s.'
283
306
  };
284
307
  }
285
308
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/model/ai-allotments.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 {\n ASSIST_HARD_CAP_CONTROL_LOCATION,\n type AssistRefusedBy,\n} from '@aglyn/aglyn/app-utils/assist-credits'\nimport { ORG_PERMISSIONS } from '@aglyn/aglyn/app-utils/org-permissions'\n\n/**\n * AI ALLOTMENTS (AGL-2942): the pure half.\n *\n * The workspace's AI pool is one band. An allotment is a manager's decision\n * about how much of that band one SUBJECT may draw in a calendar month (UTC),\n * so one client site, one contractor or one teammate cannot spend what the\n * others were counting on:\n *\n * orgs/{orgId}/aiAllotments/{subject}\n * { subject, scope, uid, hostId, credits, mode, models, setBy,\n * updatedAt, alerted }\n *\n * where `subject` is one of\n *\n * member:{uid} a team member, across every site\n * collab:{hostId}:{uid} a site collaborator, on that site\n * host:{hostId} a whole site, across everyone who works on it\n * org the org-wide model restriction (no credits)\n *\n * ## An allotment never grants\n *\n * The org band stays the outer wall: the reservation decides the workspace's\n * own ceilings first and consults an allotment only once they admitted the\n * request. So an allotment larger than the band is not an error and not a\n * grant — it is a line the workspace reaches after the band.\n *\n * ## Hard and soft\n *\n * A HARD allotment refuses the request that finds the subject at or past it.\n * A SOFT one admits it and tells the subject and the workspace's billing\n * contacts at 80% and again at 100%. Both are measured against what the\n * subject already drew this month, before the request — the same shape the\n * band is measured in, so a request that starts under the line may finish\n * past it, and the next one is the one refused.\n *\n * Everything here is dependency-light so the gate, the routes and the console\n * cards read one definition of a subject, a standing and a refusal sentence.\n */\n\n/** `orgs/{orgId}/{this}/{subject}`. */\nexport const AI_ALLOTMENTS_COLLECTION = 'aiAllotments'\n\n/** The subject id of the org-wide model restriction. */\nexport const AI_ALLOTMENT_ORG_SUBJECT = 'org'\n\nexport type AiAllotmentMode = 'hard' | 'soft'\n\nexport type AiAllotmentScope = 'member' | 'collab' | 'host' | 'org'\n\n/** The scopes an allotment of CREDITS can have; `org` carries models only. */\nexport type AiCreditAllotmentScope = Exclude<AiAllotmentScope, 'org'>\n\n/**\n * Why a reservation refused: the meter's own ceilings, and an allotment.\n *\n * Widened here rather than in core's `AssistRefusedBy`, because an allotment\n * is the plugin's rung: core names the ceilings core's billing sells.\n */\nexport type AiRefusedBy = AssistRefusedBy | 'allotment'\n\n/**\n * The steps a soft allotment announces — the same 75, 80, 90 and 100 every\n * usage quota steps through (AGL-3431). Only the highest step reached is\n * sent, each once a month.\n */\nexport const AI_ALLOTMENT_ALERT_BANDS = [75, 80, 90, 100] as const\nexport type AiAllotmentThreshold = (typeof AI_ALLOTMENT_ALERT_BANDS)[number]\n\n/** The share of an allotment at which the strip warns and a soft one alerts. */\nexport const AI_ALLOTMENT_WARN_SHARE = 0.8\n\n/**\n * The largest monthly allotment a write may carry. A bound on a typing\n * mistake, not a product limit: a billion credits is a million dollars of\n * provider spend, far past any band the platform sells.\n */\nexport const AI_ALLOTMENT_MAX_CREDITS = 1_000_000_000\n\n/** The most catalog ids one allowlist may name. */\nexport const AI_ALLOTMENT_MAX_MODELS = 20\n\nconst ID_SEGMENT = /^[A-Za-z0-9_-]{1,128}$/\n\nexport interface AiAllotmentSubject {\n id: string\n scope: AiAllotmentScope\n uid: string | null\n hostId: string | null\n}\n\nexport type AiAllotmentSubjectInput =\n | { scope: 'member'; uid: string }\n | { scope: 'collab'; hostId: string; uid: string }\n | { scope: 'host'; hostId: string }\n | { scope: 'org' }\n\n/** The document id for a subject. Throws on a segment that is not an id. */\nexport function aiAllotmentSubjectId(input: AiAllotmentSubjectInput): string {\n const segment = (value: string): string => {\n if (!ID_SEGMENT.test(value)) throw new Error(`not an id segment: ${value}`)\n return value\n }\n switch (input.scope) {\n case 'member':\n return `member:${segment(input.uid)}`\n case 'collab':\n return `collab:${segment(input.hostId)}:${segment(input.uid)}`\n case 'host':\n return `host:${segment(input.hostId)}`\n default:\n return AI_ALLOTMENT_ORG_SUBJECT\n }\n}\n\n/** A subject id read back, or `null` for anything that is not one. */\nexport function parseAiAllotmentSubject(value: unknown): AiAllotmentSubject | null {\n if (typeof value !== 'string') return null\n if (value === AI_ALLOTMENT_ORG_SUBJECT) {\n return { id: value, scope: 'org', uid: null, hostId: null }\n }\n const parts = value.split(':')\n if (parts.some((part) => !ID_SEGMENT.test(part))) return null\n if (parts.length === 2 && parts[0] === 'member') {\n return { id: value, scope: 'member', uid: parts[1], hostId: null }\n }\n if (parts.length === 2 && parts[0] === 'host') {\n return { id: value, scope: 'host', uid: null, hostId: parts[1] }\n }\n if (parts.length === 3 && parts[0] === 'collab') {\n return { id: value, scope: 'collab', uid: parts[2], hostId: parts[1] }\n }\n return null\n}\n\n/** One allotment as every reader hands it on. */\nexport interface AiAllotment {\n subject: string\n scope: AiAllotmentScope\n uid: string | null\n hostId: string | null\n /**\n * Credits a month, or `null` for an allotment that bounds models alone —\n * and always `null` on the org-wide restriction.\n */\n credits: number | null\n mode: AiAllotmentMode\n /** Catalog ids the subject may run on, or `null` for no restriction. */\n models: string[] | null\n setBy: string | null\n /** The last threshold announced, and the month it was announced in. */\n alerted: { month: string; threshold: AiAllotmentThreshold } | null\n}\n\n/** A finite positive whole number of credits, else `null`. */\nexport function aiAllotmentCredits(value: unknown): number | null {\n const parsed = typeof value === 'number' ? value : Number.NaN\n if (!Number.isFinite(parsed) || parsed <= 0) return null\n return Math.min(AI_ALLOTMENT_MAX_CREDITS, Math.floor(parsed))\n}\n\n/** An allowlist read back: unique strings, bounded; empty reads as none. */\nexport function aiAllotmentModels(value: unknown): string[] | null {\n if (!Array.isArray(value)) return null\n const models = [\n ...new Set(\n value\n .filter((entry): entry is string => typeof entry === 'string')\n .map((entry) => entry.trim())\n .filter(Boolean),\n ),\n ].slice(0, AI_ALLOTMENT_MAX_MODELS)\n return models.length ? models : null\n}\n\n/**\n * A stored allotment as a complete record, or `null` when the id is not a\n * subject. The scope, uid and site are read off the ID, never off the\n * fields: the id is what the gate addresses, so it is the only claim about\n * who the document is for that can be trusted.\n *\n * `mode` defaults to `hard`: a document whose mode was lost is a cap, which\n * is the reading that cannot spend more than a manager set.\n */\nexport function aiAllotmentFrom(\n raw: Record<string, unknown> | null | undefined,\n id: string,\n): AiAllotment | null {\n const subject = parseAiAllotmentSubject(id)\n if (!subject || !raw) return null\n const alertedRaw = raw['alerted'] as { month?: unknown; threshold?: unknown } | null\n const threshold = Number(alertedRaw?.threshold)\n return {\n subject: subject.id,\n scope: subject.scope,\n uid: subject.uid,\n hostId: subject.hostId,\n credits: subject.scope === 'org' ? null : aiAllotmentCredits(raw['credits']),\n mode: raw['mode'] === 'soft' ? 'soft' : 'hard',\n models: aiAllotmentModels(raw['models']),\n setBy: typeof raw['setBy'] === 'string' ? (raw['setBy'] as string) : null,\n alerted:\n typeof alertedRaw?.month === 'string' && (threshold === 80 || threshold === 100)\n ? { month: alertedRaw.month, threshold }\n : null,\n }\n}\n\n/** One allotment of credits measured against what its subject drew. */\nexport interface AiAllotmentStanding {\n subject: string\n scope: AiCreditAllotmentScope\n uid: string | null\n hostId: string | null\n credits: number\n /** Credits drawn this month before the request being decided. */\n used: number\n mode: AiAllotmentMode\n}\n\nexport type AiAllotmentState = 'ok' | 'warn' | 'reached'\n\n/** `reached` at or past the allotment, `warn` from 80% of it. */\nexport function aiAllotmentState(used: number, credits: number): AiAllotmentState {\n if (!(credits > 0)) return 'ok'\n if (used >= credits) return 'reached'\n if (used >= credits * AI_ALLOTMENT_WARN_SHARE) return 'warn'\n return 'ok'\n}\n\n/**\n * The highest step a standing has reached, for the alert pipeline — compared\n * as `used × 100 ≥ step × credits`, so 9 of 10 is exactly 90%.\n */\nexport function aiAllotmentThreshold(\n used: number,\n credits: number,\n): AiAllotmentThreshold | null {\n if (!(credits > 0) || !Number.isFinite(used) || used < 0) return null\n for (let index = AI_ALLOTMENT_ALERT_BANDS.length - 1; index >= 0; index -= 1) {\n const band = AI_ALLOTMENT_ALERT_BANDS[index]\n if (used * 100 >= band * credits) return band\n }\n return null\n}\n\n/**\n * Whether a standing admits a request.\n *\n * A soft allotment always does. A hard one admits while the subject is under\n * it — and, for a caller that knows what the request will cost before it\n * starts (a job's estimate), while the estimate still fits: a 100-credit job\n * at 0 of 100 is admitted, one at 1 of 100 is not.\n */\nexport function aiAllotmentAdmits(\n standing: Pick<AiAllotmentStanding, 'credits' | 'used' | 'mode'>,\n estimateCredits = 0,\n): boolean {\n if (standing.mode === 'soft') return true\n const estimate = Number.isFinite(estimateCredits) && estimateCredits > 0 ? estimateCredits : 0\n return estimate > 0\n ? standing.used + estimate <= standing.credits\n : standing.used < standing.credits\n}\n\n/**\n * Which subject a refusal names when more than one allotment is spent: the\n * narrowest first — the person on this site, then the person, then the site.\n */\nconst SCOPE_ORDER: readonly AiCreditAllotmentScope[] = ['collab', 'member', 'host']\n\nconst scopeRank = (scope: AiCreditAllotmentScope): number => SCOPE_ORDER.indexOf(scope)\n\nexport interface AiAllotmentVerdict {\n /** The hard allotment that refuses the request, or `null`. */\n refusal: AiAllotmentStanding | null\n /** The allotment with the least left, for the usage strip; `null` for none. */\n binding: AiAllotmentStanding | null\n /** Soft allotments at a threshold, for the alert pipeline. */\n alerts: Array<{ standing: AiAllotmentStanding; threshold: AiAllotmentThreshold }>\n}\n\n/** The verdict over every allotment that applies to one request. */\nexport function aiAllotmentVerdict(\n standings: readonly AiAllotmentStanding[],\n estimateCredits = 0,\n): AiAllotmentVerdict {\n const ordered = [...standings].sort((a, b) => scopeRank(a.scope) - scopeRank(b.scope))\n const refusal =\n ordered.find((standing) => !aiAllotmentAdmits(standing, estimateCredits)) ?? null\n let binding: AiAllotmentStanding | null = null\n for (const standing of ordered) {\n if (!binding || standing.credits - standing.used < binding.credits - binding.used) {\n binding = standing\n }\n }\n const alerts = ordered.flatMap((standing) => {\n if (standing.mode !== 'soft') return []\n const threshold = aiAllotmentThreshold(standing.used, standing.credits)\n return threshold ? [{ standing, threshold }] : []\n })\n return { refusal, binding, alerts }\n}\n\n/**\n * The allowlists that apply to a request, intersected — `null` when none of\n * the allotments names one. An empty result is a real answer: two lists that\n * share no model leave nothing to pick, and the model choice falls back to\n * the routing table rather than turning AI off for a mistake in a list.\n */\nexport function aiAllotmentModelsAllowed(\n allotments: ReadonlyArray<Pick<AiAllotment, 'models'> | null | undefined>,\n): string[] | null {\n const lists = allotments\n .map((allotment) => allotment?.models)\n .filter((models): models is string[] => Array.isArray(models) && models.length > 0)\n if (!lists.length) return null\n return lists.reduce((kept, list) => kept.filter((id) => list.includes(id)))\n}\n\n/** The catalog label for `billing.manage`, the word a sentence names it by. */\nexport function billingManageLabel(): string {\n return (\n ORG_PERMISSIONS.find((definition) => definition.key === 'billing.manage')?.label ??\n 'Manage billing'\n )\n}\n\n/**\n * The sentence a refused request is told, naming who can raise the\n * allotment and where. No figures: the strip beside it carries those, and a\n * refusal that quoted a count would be stale the moment someone raised it.\n */\nexport function aiAllotmentRefusalText(\n scope: AiCreditAllotmentScope | null | undefined,\n): string {\n const managers = `an organization admin with the \"${billingManageLabel()}\" permission`\n switch (scope) {\n case 'collab':\n return (\n 'You have used your AI allotment on this site for this month. ' +\n `The site's admin, or ${managers}, can raise it on the site's Users card.`\n )\n case 'host':\n return (\n 'This site has used its AI allotment for this month. ' +\n `Ask ${managers} to raise it under ${ASSIST_HARD_CAP_CONTROL_LOCATION}.`\n )\n default:\n return (\n 'You have used your AI allotment for this month. ' +\n `Ask ${managers} to raise it under ${ASSIST_HARD_CAP_CONTROL_LOCATION}.`\n )\n }\n}\n\n/**\n * The words a soft allotment's alert carries, for BOTH channels — the\n * console notification and the email — so the two cannot say different\n * things about one crossing. `name` is the member's name or the site's.\n */\nexport function aiAllotmentAlertCopy(input: {\n scope: AiCreditAllotmentScope\n threshold: AiAllotmentThreshold\n used: number\n credits: number\n name: string\n}): { title: string; body: string } {\n const who =\n input.scope === 'host' ? `The ${input.name} site` : input.name\n const whose = input.scope === 'host' ? 'its' : 'their'\n const where = input.scope === 'collab' ? ' on its site' : ''\n const figures =\n `${input.used.toLocaleString('en-US')} of ` +\n `${input.credits.toLocaleString('en-US')} credits used this month.`\n if (input.threshold >= 100) {\n return {\n title: `${who} has used ${whose} whole AI allotment${where}`,\n body:\n `${figures} The allotment is soft, so requests keep working and ` +\n 'draw on the workspace’s pool. Raise it or make it hard under ' +\n `${ASSIST_HARD_CAP_CONTROL_LOCATION}.`,\n }\n }\n return {\n title: `${who} is past ${input.threshold}% of ${whose} AI allotment${where}`,\n body: `${figures} The allotment is soft, so nothing stops at the line.`,\n }\n}\n"],"names":["ASSIST_HARD_CAP_CONTROL_LOCATION","ORG_PERMISSIONS","AI_ALLOTMENTS_COLLECTION","AI_ALLOTMENT_ORG_SUBJECT","AI_ALLOTMENT_ALERT_BANDS","AI_ALLOTMENT_WARN_SHARE","AI_ALLOTMENT_MAX_CREDITS","AI_ALLOTMENT_MAX_MODELS","ID_SEGMENT","aiAllotmentSubjectId","input","segment","value","test","Error","scope","uid","hostId","parseAiAllotmentSubject","id","parts","split","some","part","length","aiAllotmentCredits","parsed","Number","NaN","isFinite","Math","min","floor","aiAllotmentModels","Array","isArray","models","Set","filter","entry","map","trim","Boolean","slice","aiAllotmentFrom","raw","subject","alertedRaw","threshold","credits","mode","setBy","alerted","month","aiAllotmentState","used","aiAllotmentThreshold","index","band","aiAllotmentAdmits","standing","estimateCredits","estimate","SCOPE_ORDER","scopeRank","indexOf","aiAllotmentVerdict","standings","ordered","sort","a","b","refusal","find","binding","alerts","flatMap","aiAllotmentModelsAllowed","allotments","lists","allotment","reduce","kept","list","includes","billingManageLabel","definition","key","label","aiAllotmentRefusalText","managers","aiAllotmentAlertCopy","who","name","whose","where","figures","toLocaleString","title","body"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,gCAAgC,QAE3B,wCAAuC;AAC9C,SAASC,eAAe,QAAQ,yCAAwC;AAExE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAqCC,GAED,qCAAqC,GACrC,OAAO,MAAMC,2BAA2B,eAAc;AAEtD,sDAAsD,GACtD,OAAO,MAAMC,2BAA2B,MAAK;AAiB7C;;;;CAIC,GACD,OAAO,MAAMC,2BAA2B;IAAC;IAAI;IAAI;IAAI;CAAI,CAAS;AAGlE,8EAA8E,GAC9E,OAAO,MAAMC,0BAA0B,IAAG;AAE1C;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AAGN,IAAI,SAAS,EAAElF,MAAMsC,SAAS,CAAC,KAAK,EAAE8C,MAAM,aAAa,EAAEC,OAAO;QAC5EI,MAAM,GAAGH,QAAQ,qDAAqD,CAAC;IACzE;AACF"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/model/ai-allotments.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 {\n ASSIST_HARD_CAP_CONTROL_LOCATION,\n type AssistRefusedBy,\n} from '../usage/assist-credits'\nimport { ORG_PERMISSIONS } from '@aglyn/aglyn/app-utils/org-permissions'\n\n/**\n * AI ALLOTMENTS (AGL-2942): the pure half.\n *\n * The workspace's AI pool is one band. An allotment is a manager's decision\n * about how much of that band one SUBJECT may draw in a calendar month (UTC),\n * so one client site, one contractor or one teammate cannot spend what the\n * others were counting on:\n *\n * orgs/{orgId}/aiAllotments/{subject}\n * { subject, scope, uid, hostId, credits, mode, models, setBy,\n * updatedAt, alerted }\n *\n * where `subject` is one of\n *\n * member:{uid} a team member, across every site\n * collab:{hostId}:{uid} a site collaborator, on that site\n * host:{hostId} a whole site, across everyone who works on it\n * org the org-wide model restriction (no credits)\n *\n * ## An allotment never grants\n *\n * The org band stays the outer wall: the reservation decides the workspace's\n * own ceilings first and consults an allotment only once they admitted the\n * request. So an allotment larger than the band is not an error and not a\n * grant — it is a line the workspace reaches after the band.\n *\n * ## Hard and soft\n *\n * A HARD allotment refuses the request that finds the subject at or past it.\n * A SOFT one admits it and tells the subject and the workspace's billing\n * contacts at 75, 80, 90 and 100%. Both are measured against what the\n * subject already drew this month, before the request — the same shape the\n * band is measured in, so a request that starts under the line may finish\n * past it, and the next one is the one refused.\n *\n * Everything here is dependency-light so the gate, the routes and the console\n * cards read one definition of a subject, a standing and a refusal sentence.\n */\n\n/** `orgs/{orgId}/{this}/{subject}`. */\nexport const AI_ALLOTMENTS_COLLECTION = 'aiAllotments'\n\n/** The subject id of the org-wide model restriction. */\nexport const AI_ALLOTMENT_ORG_SUBJECT = 'org'\n\nexport type AiAllotmentMode = 'hard' | 'soft'\n\nexport type AiAllotmentScope = 'member' | 'collab' | 'host' | 'org'\n\n/** The scopes an allotment of CREDITS can have; `org` carries models only. */\nexport type AiCreditAllotmentScope = Exclude<AiAllotmentScope, 'org'>\n\n/**\n * Why a reservation refused: the meter's own ceilings, and an allotment.\n *\n * Widened here rather than in core's `AssistRefusedBy`, because an allotment\n * is the plugin's rung: core names the ceilings core's billing sells.\n */\nexport type AiRefusedBy = AssistRefusedBy | 'allotment'\n\n/**\n * The steps a soft allotment announces — the same 75, 80, 90 and 100 every\n * usage quota steps through (AGL-3431). Only the highest step reached is\n * sent, each once a month.\n */\nexport const AI_ALLOTMENT_ALERT_BANDS = [75, 80, 90, 100] as const\nexport type AiAllotmentThreshold = (typeof AI_ALLOTMENT_ALERT_BANDS)[number]\n\n/** The share of an allotment at which the strip warns and a soft one alerts. */\nexport const AI_ALLOTMENT_WARN_SHARE = 0.8\n\n/**\n * The largest monthly allotment a write may carry. A bound on a typing\n * mistake, not a product limit: a billion credits is a million dollars of\n * provider spend, far past any band the platform sells.\n */\nexport const AI_ALLOTMENT_MAX_CREDITS = 1_000_000_000\n\n/** The most catalog ids one allowlist may name. */\nexport const AI_ALLOTMENT_MAX_MODELS = 20\n\nconst ID_SEGMENT = /^[A-Za-z0-9_-]{1,128}$/\n\nexport interface AiAllotmentSubject {\n id: string\n scope: AiAllotmentScope\n uid: string | null\n hostId: string | null\n}\n\nexport type AiAllotmentSubjectInput =\n | { scope: 'member'; uid: string }\n | { scope: 'collab'; hostId: string; uid: string }\n | { scope: 'host'; hostId: string }\n | { scope: 'org' }\n\n/** The document id for a subject. Throws on a segment that is not an id. */\nexport function aiAllotmentSubjectId(input: AiAllotmentSubjectInput): string {\n const segment = (value: string): string => {\n if (!ID_SEGMENT.test(value)) throw new Error(`not an id segment: ${value}`)\n return value\n }\n switch (input.scope) {\n case 'member':\n return `member:${segment(input.uid)}`\n case 'collab':\n return `collab:${segment(input.hostId)}:${segment(input.uid)}`\n case 'host':\n return `host:${segment(input.hostId)}`\n default:\n return AI_ALLOTMENT_ORG_SUBJECT\n }\n}\n\n/** A subject id read back, or `null` for anything that is not one. */\nexport function parseAiAllotmentSubject(value: unknown): AiAllotmentSubject | null {\n if (typeof value !== 'string') return null\n if (value === AI_ALLOTMENT_ORG_SUBJECT) {\n return { id: value, scope: 'org', uid: null, hostId: null }\n }\n const parts = value.split(':')\n if (parts.some((part) => !ID_SEGMENT.test(part))) return null\n if (parts.length === 2 && parts[0] === 'member') {\n return { id: value, scope: 'member', uid: parts[1], hostId: null }\n }\n if (parts.length === 2 && parts[0] === 'host') {\n return { id: value, scope: 'host', uid: null, hostId: parts[1] }\n }\n if (parts.length === 3 && parts[0] === 'collab') {\n return { id: value, scope: 'collab', uid: parts[2], hostId: parts[1] }\n }\n return null\n}\n\n/** One allotment as every reader hands it on. */\nexport interface AiAllotment {\n subject: string\n scope: AiAllotmentScope\n uid: string | null\n hostId: string | null\n /**\n * Credits a month, or `null` for an allotment that bounds models alone —\n * and always `null` on the org-wide restriction.\n */\n credits: number | null\n mode: AiAllotmentMode\n /** Catalog ids the subject may run on, or `null` for no restriction. */\n models: string[] | null\n setBy: string | null\n /** The last threshold announced, and the month it was announced in. */\n alerted: { month: string; threshold: AiAllotmentThreshold } | null\n}\n\n/** A finite positive whole number of credits, else `null`. */\nexport function aiAllotmentCredits(value: unknown): number | null {\n const parsed = typeof value === 'number' ? value : Number.NaN\n if (!Number.isFinite(parsed) || parsed <= 0) return null\n return Math.min(AI_ALLOTMENT_MAX_CREDITS, Math.floor(parsed))\n}\n\n/** An allowlist read back: unique strings, bounded; empty reads as none. */\nexport function aiAllotmentModels(value: unknown): string[] | null {\n if (!Array.isArray(value)) return null\n const models = [\n ...new Set(\n value\n .filter((entry): entry is string => typeof entry === 'string')\n .map((entry) => entry.trim())\n .filter(Boolean),\n ),\n ].slice(0, AI_ALLOTMENT_MAX_MODELS)\n return models.length ? models : null\n}\n\n/**\n * A stored allotment as a complete record, or `null` when the id is not a\n * subject. The scope, uid and site are read off the ID, never off the\n * fields: the id is what the gate addresses, so it is the only claim about\n * who the document is for that can be trusted.\n *\n * `mode` defaults to `hard`: a document whose mode was lost is a cap, which\n * is the reading that cannot spend more than a manager set.\n */\nexport function aiAllotmentFrom(\n raw: Record<string, unknown> | null | undefined,\n id: string,\n): AiAllotment | null {\n const subject = parseAiAllotmentSubject(id)\n if (!subject || !raw) return null\n const alertedRaw = raw['alerted'] as { month?: unknown; threshold?: unknown } | null\n const threshold = Number(alertedRaw?.threshold)\n return {\n subject: subject.id,\n scope: subject.scope,\n uid: subject.uid,\n hostId: subject.hostId,\n credits: subject.scope === 'org' ? null : aiAllotmentCredits(raw['credits']),\n mode: raw['mode'] === 'soft' ? 'soft' : 'hard',\n models: aiAllotmentModels(raw['models']),\n setBy: typeof raw['setBy'] === 'string' ? (raw['setBy'] as string) : null,\n alerted:\n typeof alertedRaw?.month === 'string' && (threshold === 80 || threshold === 100)\n ? { month: alertedRaw.month, threshold }\n : null,\n }\n}\n\n/** One allotment of credits measured against what its subject drew. */\nexport interface AiAllotmentStanding {\n subject: string\n scope: AiCreditAllotmentScope\n uid: string | null\n hostId: string | null\n credits: number\n /** Credits drawn this month before the request being decided. */\n used: number\n mode: AiAllotmentMode\n}\n\nexport type AiAllotmentState = 'ok' | 'warn' | 'reached'\n\n/** `reached` at or past the allotment, `warn` from 80% of it. */\nexport function aiAllotmentState(used: number, credits: number): AiAllotmentState {\n if (!(credits > 0)) return 'ok'\n if (used >= credits) return 'reached'\n if (used >= credits * AI_ALLOTMENT_WARN_SHARE) return 'warn'\n return 'ok'\n}\n\n/**\n * The highest step a standing has reached, for the alert pipeline — compared\n * as `used × 100 ≥ step × credits`, so 9 of 10 is exactly 90%.\n */\nexport function aiAllotmentThreshold(\n used: number,\n credits: number,\n): AiAllotmentThreshold | null {\n if (!(credits > 0) || !Number.isFinite(used) || used < 0) return null\n for (let index = AI_ALLOTMENT_ALERT_BANDS.length - 1; index >= 0; index -= 1) {\n const band = AI_ALLOTMENT_ALERT_BANDS[index]\n if (used * 100 >= band * credits) return band\n }\n return null\n}\n\n/**\n * Whether a standing admits a request.\n *\n * A soft allotment always does. A hard one admits while the subject is under\n * it — and, for a caller that knows what the request will cost before it\n * starts (a job's estimate), while the estimate still fits: a 100-credit job\n * at 0 of 100 is admitted, one at 1 of 100 is not.\n */\nexport function aiAllotmentAdmits(\n standing: Pick<AiAllotmentStanding, 'credits' | 'used' | 'mode'>,\n estimateCredits = 0,\n): boolean {\n if (standing.mode === 'soft') return true\n const estimate = Number.isFinite(estimateCredits) && estimateCredits > 0 ? estimateCredits : 0\n return estimate > 0\n ? standing.used + estimate <= standing.credits\n : standing.used < standing.credits\n}\n\n/**\n * Which subject a refusal names when more than one allotment is spent: the\n * narrowest first — the person on this site, then the person, then the site.\n */\nconst SCOPE_ORDER: readonly AiCreditAllotmentScope[] = ['collab', 'member', 'host']\n\nconst scopeRank = (scope: AiCreditAllotmentScope): number => SCOPE_ORDER.indexOf(scope)\n\nexport interface AiAllotmentVerdict {\n /** The hard allotment that refuses the request, or `null`. */\n refusal: AiAllotmentStanding | null\n /** The allotment with the least left, for the usage strip; `null` for none. */\n binding: AiAllotmentStanding | null\n /** Soft allotments at a threshold, for the alert pipeline. */\n alerts: Array<{ standing: AiAllotmentStanding; threshold: AiAllotmentThreshold }>\n}\n\n/** The verdict over every allotment that applies to one request. */\nexport function aiAllotmentVerdict(\n standings: readonly AiAllotmentStanding[],\n estimateCredits = 0,\n): AiAllotmentVerdict {\n const ordered = [...standings].sort((a, b) => scopeRank(a.scope) - scopeRank(b.scope))\n const refusal =\n ordered.find((standing) => !aiAllotmentAdmits(standing, estimateCredits)) ?? null\n let binding: AiAllotmentStanding | null = null\n for (const standing of ordered) {\n if (!binding || standing.credits - standing.used < binding.credits - binding.used) {\n binding = standing\n }\n }\n const alerts = ordered.flatMap((standing) => {\n if (standing.mode !== 'soft') return []\n const threshold = aiAllotmentThreshold(standing.used, standing.credits)\n return threshold ? [{ standing, threshold }] : []\n })\n return { refusal, binding, alerts }\n}\n\n/**\n * The allowlists that apply to a request, intersected — `null` when none of\n * the allotments names one. An empty result is a real answer: two lists that\n * share no model leave nothing to pick, and the model choice falls back to\n * the routing table rather than turning AI off for a mistake in a list.\n */\nexport function aiAllotmentModelsAllowed(\n allotments: ReadonlyArray<Pick<AiAllotment, 'models'> | null | undefined>,\n): string[] | null {\n const lists = allotments\n .map((allotment) => allotment?.models)\n .filter((models): models is string[] => Array.isArray(models) && models.length > 0)\n if (!lists.length) return null\n return lists.reduce((kept, list) => kept.filter((id) => list.includes(id)))\n}\n\n/** The catalog label for `billing.manage`, the word a sentence names it by. */\nexport function billingManageLabel(): string {\n return (\n ORG_PERMISSIONS.find((definition) => definition.key === 'billing.manage')?.label ??\n 'Manage billing'\n )\n}\n\n/**\n * The sentence a refused request is told, naming who can raise the\n * allotment and where. No figures: the strip beside it carries those, and a\n * refusal that quoted a count would be stale the moment someone raised it.\n */\nexport function aiAllotmentRefusalText(\n scope: AiCreditAllotmentScope | null | undefined,\n): string {\n const managers = `an organization admin with the \"${billingManageLabel()}\" permission`\n switch (scope) {\n case 'collab':\n return (\n 'You have used your AI allotment on this site for this month. ' +\n `The site's admin, or ${managers}, can raise it on the site's Users card.`\n )\n case 'host':\n return (\n 'This site has used its AI allotment for this month. ' +\n `Ask ${managers} to raise it under ${ASSIST_HARD_CAP_CONTROL_LOCATION}.`\n )\n default:\n return (\n 'You have used your AI allotment for this month. ' +\n `Ask ${managers} to raise it under ${ASSIST_HARD_CAP_CONTROL_LOCATION}.`\n )\n }\n}\n\n/**\n * The words a soft allotment's alert carries, for BOTH channels — the\n * console notification and the email — so the two cannot say different\n * things about one crossing.\n *\n * The email is plain text with no heading, so the body opens by saying whose\n * AI credits, how many of how many, and in which workspace (and on which site,\n * for a collaborator): a figure on its own reads as a bill. The managers'\n * copy says how to stop the subject at the line; the person's own copy does\n * not, because they cannot open Billing.\n */\nexport function aiAllotmentAlertCopy(input: {\n scope: AiCreditAllotmentScope\n threshold: AiAllotmentThreshold\n used: number\n credits: number\n /** The member's name, or the site's for a site allotment. */\n name: string\n /** The workspace the allotment is drawn from. */\n workspace: string\n /** The site a collaborator's allotment is on. */\n site?: string\n /** The workspace's managers (the default), or the person it is for. */\n reader?: 'managers' | 'subject'\n}): { title: string; body: string } {\n const { scope, threshold, name, workspace } = input\n const used = input.used.toLocaleString('en-US')\n const credits = input.credits.toLocaleString('en-US')\n const reached = threshold >= 100\n const onSite = scope === 'collab' && input.site ? ` on the ${input.site} site` : ''\n const amount = reached\n ? `all ${credits} AI credits`\n : `${used} of the ${credits} AI credits`\n const tail = reached ? ` this month (${used} so far).` : ` this month, past the ${threshold}% mark.`\n\n if (input.reader === 'subject' && scope !== 'host') {\n const where = scope === 'collab' ? onSite : ` in ${workspace}`\n const whoCanChange =\n scope === 'collab'\n ? 'The site’s admin or a workspace admin can raise or change it.'\n : 'A workspace admin can raise or change it.'\n return {\n title: reached\n ? `You’ve used your whole AI allotment${where}`\n : `You’re past ${threshold}% of your AI allotment${where}`,\n body:\n `You’ve used ${amount} ${workspace} allotted you${onSite}${tail} ` +\n 'It’s a soft allotment, so it does not stop your AI requests.' +\n (reached ? ` ${whoCanChange}` : ''),\n }\n }\n\n const who = scope === 'host' ? `The ${name} site` : name\n const whose = scope === 'host' ? 'its' : 'their'\n const them = scope === 'host' ? 'it' : 'them'\n const requests = scope === 'host' ? 'AI requests on the site' : `${name}’s AI requests`\n const where = scope === 'collab' ? onSite : scope === 'member' ? ` in ${workspace}` : ''\n const opening =\n `${who} has used ${amount} allotted to ${them}${onSite} in ${workspace}${tail}`\n if (reached) {\n return {\n title: `${who} has used ${whose} whole AI allotment${where}`,\n body:\n `${opening} It’s a soft allotment, so it does not stop ${requests}; ` +\n 'they keep drawing on the workspace’s AI credits, and crossing it ' +\n `charges nothing by itself. To stop ${them} at the line, make it hard ` +\n `under ${ASSIST_HARD_CAP_CONTROL_LOCATION}; to give ${them} more, ` +\n 'raise it there.',\n }\n }\n return {\n title: `${who} is past ${threshold}% of ${whose} AI allotment${where}`,\n body:\n `${opening} It’s a soft allotment, so it does not stop ${requests}; ` +\n 'they draw on the workspace’s AI credits like everyone else’s.',\n }\n}\n"],"names":["ASSIST_HARD_CAP_CONTROL_LOCATION","ORG_PERMISSIONS","AI_ALLOTMENTS_COLLECTION","AI_ALLOTMENT_ORG_SUBJECT","AI_ALLOTMENT_ALERT_BANDS","AI_ALLOTMENT_WARN_SHARE","AI_ALLOTMENT_MAX_CREDITS","AI_ALLOTMENT_MAX_MODELS","ID_SEGMENT","aiAllotmentSubjectId","input","segment","value","test","Error","scope","uid","hostId","parseAiAllotmentSubject","id","parts","split","some","part","length","aiAllotmentCredits","parsed","Number","NaN","isFinite","Math","min","floor","aiAllotmentModels","Array","isArray","models","Set","filter","entry","map","trim","Boolean","slice","aiAllotmentFrom","raw","subject","alertedRaw","threshold","credits","mode","setBy","alerted","month","aiAllotmentState","used","aiAllotmentThreshold","index","band","aiAllotmentAdmits","standing","estimateCredits","estimate","SCOPE_ORDER","scopeRank","indexOf","aiAllotmentVerdict","standings","ordered","sort","a","b","refusal","find","binding","alerts","flatMap","aiAllotmentModelsAllowed","allotments","lists","allotment","reduce","kept","list","includes","billingManageLabel","definition","key","label","aiAllotmentRefusalText","managers","aiAllotmentAlertCopy","name","workspace","toLocaleString","reached","onSite","site","amount","tail","reader","where","whoCanChange","title","body","who","whose","them","requests","opening"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,S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AI,UAAU,EAAEC,MAAM,mBAAmB,EAAEL,OAAO;YAC5DG,MACE,GAAGK,QAAQ,4CAA4C,EAAED,SAAS,EAAE,CAAC,GACrE,sEACA,CAAC,mCAAmC,EAAED,KAAK,2BAA2B,CAAC,GACvE,CAAC,MAAM,EAAE3G,iCAAiC,UAAU,EAAE2G,KAAK,OAAO,CAAC,GACnE;QACJ;IACF;IACA,OAAO;QACLJ,OAAO,GAAGE,IAAI,SAAS,EAAEzD,UAAU,KAAK,EAAE0D,MAAM,aAAa,EAAEL,OAAO;QACtEG,MACE,GAAGK,QAAQ,4CAA4C,EAAED,SAAS,EAAE,CAAC,GACrE;IACJ;AACF"}
@@ -0,0 +1,55 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ import type { AiBuildPlan, AiBuildPlanCreate, AiBuildPlanCreateKind } from './ai-build-plan';
18
+ import type { AiJobKind } from './ai-jobs.types';
19
+ /**
20
+ * What a job that builds ONE record builds of the rest of its plan
21
+ * (AGL-3143 §15): a template, a layout, a component, a form or an email
22
+ * design.
23
+ *
24
+ * Each of those steps builds the first creation of its own kind and nothing
25
+ * else, so a plan that also created something left it unbuilt and the job
26
+ * still reported `Done`. Measured live on 2026-10-01 (job `2xD9Y7NayF`): a
27
+ * template plan the member confirmed read "Creates the component
28
+ * related-article-card", and no such component was ever made.
29
+ *
30
+ * Such a job now builds the other creations the way a page job does
31
+ * (AGL-3031): each before its own record, one a pass, by the step that builds
32
+ * that kind, and then its own record against what was built. It builds only
33
+ * what its own record can PLACE — a component instance or a saved form, on
34
+ * the trees that admit one — because a creation nothing places is the same
35
+ * broken promise one step later. A form's tree and an email's place neither,
36
+ * so those two build only their own. The plan step is told this list before it
37
+ * answers, and the plan rules refuse a creation outside it with the one
38
+ * re-ask every rule gets.
39
+ *
40
+ * Model only: this module imports nothing at runtime, so the plan step, the
41
+ * doors, the estimate and the proposal read one list.
42
+ */
43
+ export declare const AI_JOB_CREATE_KINDS: Readonly<Partial<Record<AiJobKind, readonly AiBuildPlanCreateKind[]>>>;
44
+ /** A job of each of those kinds as a refusal names it: "a template job". */
45
+ export declare const AI_JOB_CREATE_NOUNS: Readonly<Partial<Record<AiJobKind, string>>>;
46
+ /**
47
+ * The creations a job of `kind` builds before its own record: every creation
48
+ * the plan names that the kind builds, less the one the kind's step builds
49
+ * itself — the first of the kind's own — in plan order. Empty for a kind that
50
+ * builds only its own record.
51
+ */
52
+ export declare function aiJobOtherCreations(kind: AiJobKind, plan: Pick<AiBuildPlan, 'create'>): Array<{
53
+ creation: AiBuildPlanCreate;
54
+ index: number;
55
+ }>;
@@ -0,0 +1,85 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */ /**
17
+ * What a job that builds ONE record builds of the rest of its plan
18
+ * (AGL-3143 §15): a template, a layout, a component, a form or an email
19
+ * design.
20
+ *
21
+ * Each of those steps builds the first creation of its own kind and nothing
22
+ * else, so a plan that also created something left it unbuilt and the job
23
+ * still reported `Done`. Measured live on 2026-10-01 (job `2xD9Y7NayF`): a
24
+ * template plan the member confirmed read "Creates the component
25
+ * related-article-card", and no such component was ever made.
26
+ *
27
+ * Such a job now builds the other creations the way a page job does
28
+ * (AGL-3031): each before its own record, one a pass, by the step that builds
29
+ * that kind, and then its own record against what was built. It builds only
30
+ * what its own record can PLACE — a component instance or a saved form, on
31
+ * the trees that admit one — because a creation nothing places is the same
32
+ * broken promise one step later. A form's tree and an email's place neither,
33
+ * so those two build only their own. The plan step is told this list before it
34
+ * answers, and the plan rules refuse a creation outside it with the one
35
+ * re-ask every rule gets.
36
+ *
37
+ * Model only: this module imports nothing at runtime, so the plan step, the
38
+ * doors, the estimate and the proposal read one list.
39
+ */ export const AI_JOB_CREATE_KINDS = {
40
+ template: [
41
+ 'template',
42
+ 'form',
43
+ 'component'
44
+ ],
45
+ layout: [
46
+ 'layout',
47
+ 'form',
48
+ 'component'
49
+ ],
50
+ component: [
51
+ 'component',
52
+ 'form'
53
+ ],
54
+ form: [
55
+ 'form'
56
+ ],
57
+ email: [
58
+ 'email'
59
+ ]
60
+ };
61
+ /** A job of each of those kinds as a refusal names it: "a template job". */ export const AI_JOB_CREATE_NOUNS = {
62
+ template: 'a template job',
63
+ layout: 'a layout job',
64
+ component: 'a component job',
65
+ form: 'a form job',
66
+ email: 'an email job'
67
+ };
68
+ /**
69
+ * The creations a job of `kind` builds before its own record: every creation
70
+ * the plan names that the kind builds, less the one the kind's step builds
71
+ * itself — the first of the kind's own — in plan order. Empty for a kind that
72
+ * builds only its own record.
73
+ */ export function aiJobOtherCreations(kind, plan) {
74
+ const creates = AI_JOB_CREATE_KINDS[kind];
75
+ if (!creates) return [];
76
+ const own = plan.create.findIndex((entry)=>entry.kind === kind);
77
+ return plan.create.flatMap((creation, index)=>index !== own && creates.includes(creation.kind) ? [
78
+ {
79
+ creation,
80
+ index
81
+ }
82
+ ] : []);
83
+ }
84
+
85
+ //# sourceMappingURL=ai-job-creations.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/model/ai-job-creations.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { AiBuildPlan, AiBuildPlanCreate, AiBuildPlanCreateKind } from './ai-build-plan'\nimport type { AiJobKind } from './ai-jobs.types'\n\n/**\n * What a job that builds ONE record builds of the rest of its plan\n * (AGL-3143 §15): a template, a layout, a component, a form or an email\n * design.\n *\n * Each of those steps builds the first creation of its own kind and nothing\n * else, so a plan that also created something left it unbuilt and the job\n * still reported `Done`. Measured live on 2026-10-01 (job `2xD9Y7NayF`): a\n * template plan the member confirmed read \"Creates the component\n * related-article-card\", and no such component was ever made.\n *\n * Such a job now builds the other creations the way a page job does\n * (AGL-3031): each before its own record, one a pass, by the step that builds\n * that kind, and then its own record against what was built. It builds only\n * what its own record can PLACE — a component instance or a saved form, on\n * the trees that admit one — because a creation nothing places is the same\n * broken promise one step later. A form's tree and an email's place neither,\n * so those two build only their own. The plan step is told this list before it\n * answers, and the plan rules refuse a creation outside it with the one\n * re-ask every rule gets.\n *\n * Model only: this module imports nothing at runtime, so the plan step, the\n * doors, the estimate and the proposal read one list.\n */\nexport const AI_JOB_CREATE_KINDS: Readonly<Partial<Record<AiJobKind, readonly AiBuildPlanCreateKind[]>>> = {\n template: ['template', 'form', 'component'],\n layout: ['layout', 'form', 'component'],\n component: ['component', 'form'],\n form: ['form'],\n email: ['email'],\n}\n\n/** A job of each of those kinds as a refusal names it: \"a template job\". */\nexport const AI_JOB_CREATE_NOUNS: Readonly<Partial<Record<AiJobKind, string>>> = {\n template: 'a template job',\n layout: 'a layout job',\n component: 'a component job',\n form: 'a form job',\n email: 'an email job',\n}\n\n/**\n * The creations a job of `kind` builds before its own record: every creation\n * the plan names that the kind builds, less the one the kind's step builds\n * itself — the first of the kind's own — in plan order. Empty for a kind that\n * builds only its own record.\n */\nexport function aiJobOtherCreations(\n kind: AiJobKind,\n plan: Pick<AiBuildPlan, 'create'>,\n): Array<{ creation: AiBuildPlanCreate; index: number }> {\n const creates = AI_JOB_CREATE_KINDS[kind]\n if (!creates) return []\n const own = plan.create.findIndex((entry) => entry.kind === kind)\n return plan.create.flatMap((creation, index) =>\n index !== own && creates.includes(creation.kind) ? [{ creation, index }] : [],\n )\n}\n"],"names":["AI_JOB_CREATE_KINDS","template","layout","component","form","email","AI_JOB_CREATE_NOUNS","aiJobOtherCreations","kind","plan","creates","own","create","findIndex","entry","flatMap","creation","index","includes"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAKD;;;;;;;;;;;;;;;;;;;;;;;CAuBC,GACD,OAAO,MAAMA,sBAA8F;IACzGC,UAAU;QAAC;QAAY;QAAQ;KAAY;IAC3CC,QAAQ;QAAC;QAAU;QAAQ;KAAY;IACvCC,WAAW;QAAC;QAAa;KAAO;IAChCC,MAAM;QAAC;KAAO;IACdC,OAAO;QAAC;KAAQ;AAClB,EAAC;AAED,0EAA0E,GAC1E,OAAO,MAAMC,sBAAoE;IAC/EL,UAAU;IACVC,QAAQ;IACRC,WAAW;IACXC,MAAM;IACNC,OAAO;AACT,EAAC;AAED;;;;;CAKC,GACD,OAAO,SAASE,oBACdC,IAAe,EACfC,IAAiC;IAEjC,MAAMC,UAAUV,mBAAmB,CAACQ,KAAK;IACzC,IAAI,CAACE,SAAS,OAAO,EAAE;IACvB,MAAMC,MAAMF,KAAKG,MAAM,CAACC,SAAS,CAAC,CAACC,QAAUA,MAAMN,IAAI,KAAKA;IAC5D,OAAOC,KAAKG,MAAM,CAACG,OAAO,CAAC,CAACC,UAAUC,QACpCA,UAAUN,OAAOD,QAAQQ,QAAQ,CAACF,SAASR,IAAI,IAAI;YAAC;gBAAEQ;gBAAUC;YAAM;SAAE,GAAG,EAAE;AAEjF"}
@@ -87,6 +87,7 @@ export declare function aiPagePlanRefusal(plan: AiBuildPlan): string | null;
87
87
  * in a sentence a member reads when confirming it: what the workspace's plan
88
88
  * does not include, or what the site has no room left for. The plan step was
89
89
  * told what could be created, so this is the site changing between the plan
90
- * and its confirmation.
90
+ * and its confirmation. `noun` names what the job builds, for a template,
91
+ * layout, component, form or email job held the same way (AGL-3143 §15).
91
92
  */
92
- export declare function aiPageCreationRefusal(refused: readonly AiPlanUncreatable[]): string | null;
93
+ export declare function aiPageCreationRefusal(refused: readonly AiPlanUncreatable[], noun?: string): string | null;
@@ -148,12 +148,13 @@ const PAGE_TYPE_BY_ID = new Map(AI_PAGE_TYPES.map((type)=>[
148
148
  * in a sentence a member reads when confirming it: what the workspace's plan
149
149
  * does not include, or what the site has no room left for. The plan step was
150
150
  * told what could be created, so this is the site changing between the plan
151
- * and its confirmation.
152
- */ export function aiPageCreationRefusal(refused) {
151
+ * and its confirmation. `noun` names what the job builds, for a template,
152
+ * layout, component, form or email job held the same way (AGL-3143 §15).
153
+ */ export function aiPageCreationRefusal(refused, noun = 'page') {
153
154
  if (!refused.length) return null;
154
155
  const parts = refused.map(({ kind, name, reason })=>`the ${AI_BUILD_PLAN_CREATION_NOUNS[kind].noun} “${name}”, because ${reason}`);
155
156
  const listed = parts.length === 1 ? parts[0] : `${parts.slice(0, -1).join('; ')}; and ${parts[parts.length - 1]}`;
156
- return `This page cannot be built as planned: it creates ${listed}. Describe the page again.`;
157
+ return `This ${noun} cannot be built as planned: it creates ${listed}. Describe the ${noun} again.`;
157
158
  }
158
159
 
159
160
  //# sourceMappingURL=ai-page-job.js.map