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

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 (72) hide show
  1. package/package.json +17 -17
  2. package/src/lib/components/ai-job-plan.component.js +1 -4
  3. package/src/lib/components/ai-job-plan.component.js.map +1 -1
  4. package/src/lib/jobs/ai-job-crm-step.d.ts +44 -3
  5. package/src/lib/jobs/ai-job-crm-step.js +298 -8
  6. package/src/lib/jobs/ai-job-crm-step.js.map +1 -1
  7. package/src/lib/jobs/ai-job-page-sections.d.ts +33 -1
  8. package/src/lib/jobs/ai-job-page-sections.js +55 -1
  9. package/src/lib/jobs/ai-job-page-sections.js.map +1 -1
  10. package/src/lib/jobs/ai-job-page-step.js +20 -11
  11. package/src/lib/jobs/ai-job-page-step.js.map +1 -1
  12. package/src/lib/jobs/ai-job-plan-step.js +6 -2
  13. package/src/lib/jobs/ai-job-plan-step.js.map +1 -1
  14. package/src/lib/jobs/ai-job-seo-step.js +52 -15
  15. package/src/lib/jobs/ai-job-seo-step.js.map +1 -1
  16. package/src/lib/jobs/ai-job-site-step.js +6 -0
  17. package/src/lib/jobs/ai-job-site-step.js.map +1 -1
  18. package/src/lib/jobs/ai-job-workflow-step.js +8 -7
  19. package/src/lib/jobs/ai-job-workflow-step.js.map +1 -1
  20. package/src/lib/jobs/ai-workflow-records.d.ts +2 -2
  21. package/src/lib/jobs/ai-workflow-records.js +2 -2
  22. package/src/lib/jobs/ai-workflow-records.js.map +1 -1
  23. package/src/lib/jobs/fixtures/ai-free-page-built-recording.js +1 -0
  24. package/src/lib/jobs/fixtures/ai-free-page-built-recording.js.map +1 -1
  25. package/src/lib/jobs/fixtures/ai-free-page-recording.js +2 -0
  26. package/src/lib/jobs/fixtures/ai-free-page-recording.js.map +1 -1
  27. package/src/lib/jobs/fixtures/ai-page-briefs.js +2 -0
  28. package/src/lib/jobs/fixtures/ai-page-briefs.js.map +1 -1
  29. package/src/lib/model/ai-automation-draft.d.ts +4 -4
  30. package/src/lib/model/ai-automation-draft.js +15 -10
  31. package/src/lib/model/ai-automation-draft.js.map +1 -1
  32. package/src/lib/model/ai-automation-format.d.ts +139 -0
  33. package/src/lib/model/ai-automation-format.js +42 -0
  34. package/src/lib/model/ai-automation-format.js.map +1 -0
  35. package/src/lib/model/ai-automation-outline.d.ts +4 -4
  36. package/src/lib/model/ai-automation-outline.js +10 -8
  37. package/src/lib/model/ai-automation-outline.js.map +1 -1
  38. package/src/lib/model/ai-build-plan.d.ts +39 -2
  39. package/src/lib/model/ai-build-plan.js +80 -3
  40. package/src/lib/model/ai-build-plan.js.map +1 -1
  41. package/src/lib/model/ai-site-inventory.d.ts +5 -0
  42. package/src/lib/model/ai-site-inventory.js.map +1 -1
  43. package/src/lib/model/ai-workflow-job.js +2 -2
  44. package/src/lib/model/ai-workflow-job.js.map +1 -1
  45. package/src/lib/providers/catalog.d.ts +23 -0
  46. package/src/lib/providers/catalog.js +29 -1
  47. package/src/lib/providers/catalog.js.map +1 -1
  48. package/src/lib/runtime/ai-doctrine-validators.d.ts +8 -0
  49. package/src/lib/runtime/ai-doctrine-validators.js +34 -3
  50. package/src/lib/runtime/ai-doctrine-validators.js.map +1 -1
  51. package/src/lib/runtime/ai-doctrine.js +1 -1
  52. package/src/lib/runtime/ai-doctrine.js.map +1 -1
  53. package/src/lib/runtime/ai-eval.d.ts +2 -2
  54. package/src/lib/runtime/ai-eval.js +3 -3
  55. package/src/lib/runtime/ai-eval.js.map +1 -1
  56. package/src/lib/runtime/ai-palette.generated.js +8 -1
  57. package/src/lib/runtime/ai-palette.generated.js.map +1 -1
  58. package/src/lib/runtime/seo-audit.d.ts +5 -2
  59. package/src/lib/runtime/seo-audit.js +16 -7
  60. package/src/lib/runtime/seo-audit.js.map +1 -1
  61. package/src/lib/runtime/site-inventory.js +10 -3
  62. package/src/lib/runtime/site-inventory.js.map +1 -1
  63. package/src/lib/testing/stand-in-dataset-index.js +31 -5
  64. package/src/lib/testing/stand-in-dataset-index.js.map +1 -1
  65. package/src/lib/tools/ai-seo-tool.d.ts +5 -1
  66. package/src/lib/tools/ai-seo-tool.js +6 -2
  67. package/src/lib/tools/ai-seo-tool.js.map +1 -1
  68. package/src/lib/tools/ai-workflow-tool.d.ts +15 -4
  69. package/src/lib/tools/ai-workflow-tool.js +70 -12
  70. package/src/lib/tools/ai-workflow-tool.js.map +1 -1
  71. package/src/lib/usage-axes.js +14 -1
  72. package/src/lib/usage-axes.js.map +1 -1
@@ -14,10 +14,11 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
14
14
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
15
  * See the License for the specific language governing permissions and
16
16
  * limitations under the License.
17
- */ import { ACTION_MAX_CONDITIONS, ACTION_MAX_STEPS, CONTACT_TAG_MAX_LENGTH, FLOW_TIMED_OUT_FIELD, FLOW_WAIT_MAX_MINUTES, FLOW_WAIT_MIN_MINUTES, HOST_ACTION_STEP_LABELS, TRIGGER_COMBINATORS, TRIGGER_CONDITION_OPS } from "@aglyn/aglyn/app-utils/actions";
18
- import { CONTACT_LIFECYCLE_STAGE_LABELS, CONTACT_LIFECYCLE_STAGES, CRM_ACTIVITY_KINDS, CRM_TASK_KINDS, CRM_TASK_MAX_DUE_DAYS } from "@aglyn/aglyn/app-utils/crm";
17
+ */ import { ACTION_MAX_CONDITIONS, ACTION_MAX_STEPS, TRIGGER_COMBINATORS, TRIGGER_CONDITION_OPS } from "@aglyn/aglyn/app-utils/site-interactions";
18
+ import { CONTACT_LIFECYCLE_STAGE_LABELS, CONTACT_LIFECYCLE_STAGES, CONTACT_TAG_MAX_LENGTH, CRM_ACTIVITY_DIRECTIONS, CRM_ACTIVITY_KINDS, CRM_TASK_KINDS, CRM_TASK_MAX_DUE_DAYS } from "@aglyn/aglyn/app-utils/crm";
19
19
  import { HOST_EVENT_PAYLOAD_KEYS, HOST_EVENT_TYPES } from "@aglyn/aglyn/app-utils/host-events";
20
20
  import { AI_AUTOMATION_NEED_LABELS, AI_AUTOMATION_STEP_NEEDS, AI_AUTOMATION_STEP_TYPES, AI_AUTOMATION_TRIGGER_NEEDS, AI_AUTOMATION_UNSUPPORTED, AI_AUTOMATION_UNSUPPORTED_NEED, aiAutomationTriggerLabel } from "../model/ai-workflow-job.js";
21
+ import { AI_AUTOMATION_TIMED_OUT_FIELD, AI_AUTOMATION_WAIT_MINUTES, aiStepLabel } from "../model/ai-automation-format.js";
21
22
  import { HOSTILE_TEXT } from "../runtime/ai-node-tree.js";
22
23
  /**
23
24
  * The two tools a `workflow` job answers through (AGL-2919).
@@ -52,8 +53,15 @@ import { HOSTILE_TEXT } from "../runtime/ai-node-tree.js";
52
53
  * - a variant serves every step type that carries the same fields, named for
53
54
  * what they hold: the six steps that name a record share `reference`, and
54
55
  * the three that carry one line share `text`;
55
- * - every field stays required and every vocabulary stays an enum, so the
56
- * model is still decoded into the Actions editor's words.
56
+ * - every field stays required and every vocabulary but one stays an enum,
57
+ * so the model is still decoded into the Actions editor's words. The one
58
+ * is the event a waitForEvent step waits for: the trigger's `event` already
59
+ * compiles the host events' enum, and a second copy of it is what a task's
60
+ * priority and a logged call's direction cost (AGL-3538). It is a string
61
+ * described as one of the trigger events, and the reader refuses any
62
+ * other naming every event, so the one re-ask can fix it;
63
+ * - a description is free: a compiler drops it (`aiToolSchemaCompiledBytes`),
64
+ * so the words a field needs go there and never into the grammar.
57
65
  *
58
66
  * Ten variants carry all seventeen step types, and the reader below maps the
59
67
  * shared fields back onto the step's own key.
@@ -84,6 +92,18 @@ const SEVERITIES = [
84
92
  'warning',
85
93
  'error'
86
94
  ];
95
+ /** A task's priorities, by meaning — the runner stores the org's label for each (AGL-3517). */ const TASK_PRIORITIES = [
96
+ 'low',
97
+ 'normal',
98
+ 'high'
99
+ ];
100
+ /** Every direction any activity takes, and `''` for a kind that takes none (AGL-3538). */ const ACTIVITY_DIRECTIONS = [
101
+ '',
102
+ ...new Set(Object.values(CRM_ACTIVITY_DIRECTIONS).flatMap((directions)=>[
103
+ ...directions != null ? directions : []
104
+ ]))
105
+ ];
106
+ /** The events a waitForEvent step may wait for, as its refusal names them. */ const WAITABLE_EVENTS = HOST_EVENT_TYPES.join(', ');
87
107
  /**
88
108
  * What the schema defines once and refers to where it is used: a condition,
89
109
  * which the trigger and every step's guard share, and the guard itself.
@@ -165,7 +185,7 @@ const SEVERITIES = [
165
185
  };
166
186
  const minutes = (what)=>({
167
187
  type: 'integer',
168
- description: `${what}, in whole minutes from ${FLOW_WAIT_MIN_MINUTES} to ${FLOW_WAIT_MAX_MINUTES}; an hour is 60 and a day 1440.`
188
+ description: `${what}, in whole minutes from ${AI_AUTOMATION_WAIT_MINUTES.min} to ${AI_AUTOMATION_WAIT_MINUTES.max}; an hour is 60 and a day 1440.`
169
189
  });
170
190
  /**
171
191
  * One variant of the steps' union: the step types it serves, and the fields
@@ -245,8 +265,10 @@ const minutes = (what)=>({
245
265
  stepVariant([
246
266
  'waitForEvent'
247
267
  ], {
268
+ // A string, not the events' enum again — see the header.
248
269
  event: {
249
- $ref: '#/$defs/event'
270
+ type: 'string',
271
+ description: 'One of the trigger events.'
250
272
  },
251
273
  minutes: minutes('When to give up')
252
274
  }),
@@ -276,6 +298,12 @@ const minutes = (what)=>({
276
298
  ...CRM_TASK_KINDS
277
299
  ]
278
300
  },
301
+ priority: {
302
+ type: 'string',
303
+ enum: [
304
+ ...TASK_PRIORITIES
305
+ ]
306
+ },
279
307
  dueInDays: {
280
308
  type: 'integer',
281
309
  description: `Days from the run, 0 for today, at most ${CRM_TASK_MAX_DUE_DAYS}.`
@@ -290,6 +318,13 @@ const minutes = (what)=>({
290
318
  ...CRM_ACTIVITY_KINDS
291
319
  ]
292
320
  },
321
+ direction: {
322
+ type: 'string',
323
+ enum: [
324
+ ...ACTIVITY_DIRECTIONS
325
+ ],
326
+ description: 'A call: outbound, inbound or internal. An email: outbound or inbound. Else empty.'
327
+ },
293
328
  text: {
294
329
  type: 'string',
295
330
  description: 'What happened.'
@@ -483,7 +518,7 @@ function readCondition(reader, raw, path, event, guard) {
483
518
  }
484
519
  // A step's guard may also read whether the wait before it ran out of time.
485
520
  const readable = fieldsFor(event);
486
- if (readable && !readable.includes(field) && !(guard && field === FLOW_TIMED_OUT_FIELD)) {
521
+ if (readable && !readable.includes(field) && !(guard && field === AI_AUTOMATION_TIMED_OUT_FIELD)) {
487
522
  refuse(reader, 'automation-condition', `The trigger "${aiAutomationTriggerLabel(event)}" does not carry "${field}". It carries: ${readable.join(', ')}.`, path, raw);
488
523
  return null;
489
524
  }
@@ -557,7 +592,7 @@ function readStep(reader, raw, index, event, capabilities) {
557
592
  return null;
558
593
  }
559
594
  const stepType = type;
560
- const what = `Step ${index + 1} (${HOST_ACTION_STEP_LABELS[stepType]})`;
595
+ const what = `Step ${index + 1} (${aiStepLabel(stepType)})`;
561
596
  const need = AI_AUTOMATION_STEP_NEEDS[stepType];
562
597
  if (need && !capabilities[need]) {
563
598
  refuse(reader, 'automation-plan', `${what} needs ${AI_AUTOMATION_NEED_LABELS[need]}, which this workspace does not have. Leave it out, or answer with unsupported "needs-${need}".`, path, fields);
@@ -584,8 +619,10 @@ function readStep(reader, raw, index, event, capabilities) {
584
619
  tag: null,
585
620
  owner: null,
586
621
  taskKind: null,
622
+ priority: null,
587
623
  dueInDays: null,
588
- activityKind: null
624
+ activityKind: null,
625
+ direction: null
589
626
  };
590
627
  // A step's `when` is a list of at most one condition; a lone condition, or
591
628
  // none, reads as the list it stands for.
@@ -646,15 +683,15 @@ function readStep(reader, raw, index, event, capabilities) {
646
683
  case 'waitForEvent':
647
684
  {
648
685
  const minutes = wholeNumber(fields['minutes']);
649
- if (minutes === null || minutes < FLOW_WAIT_MIN_MINUTES || minutes > FLOW_WAIT_MAX_MINUTES) {
650
- refuse(reader, 'automation-step-field', `${what} needs minutes, a whole number from ${FLOW_WAIT_MIN_MINUTES} to ${FLOW_WAIT_MAX_MINUTES}.`, path, fields);
686
+ if (minutes === null || minutes < AI_AUTOMATION_WAIT_MINUTES.min || minutes > AI_AUTOMATION_WAIT_MINUTES.max) {
687
+ refuse(reader, 'automation-step-field', `${what} needs minutes, a whole number from ${AI_AUTOMATION_WAIT_MINUTES.min} to ${AI_AUTOMATION_WAIT_MINUTES.max}.`, path, fields);
651
688
  } else {
652
689
  step.minutes = minutes;
653
690
  }
654
691
  if (stepType === 'waitForEvent') {
655
692
  const waited = fields['event'];
656
693
  if (!HOST_EVENT_TYPES.includes(waited)) {
657
- refuse(reader, 'automation-step-field', `${what} needs the event it waits for.`, path, fields);
694
+ refuse(reader, 'automation-step-field', `${what} needs the event it waits for, one of: ${WAITABLE_EVENTS}.`, path, fields);
658
695
  } else {
659
696
  step.event = waited;
660
697
  }
@@ -696,6 +733,13 @@ function readStep(reader, raw, index, event, capabilities) {
696
733
  } else {
697
734
  step.taskKind = kind;
698
735
  }
736
+ // Absent reads as normal, which the runner writes when none is named.
737
+ const priority = fields['priority'];
738
+ if (priority !== undefined && !TASK_PRIORITIES.includes(priority)) {
739
+ refuse(reader, 'automation-step-field', `${what} needs priority: low, normal or high.`, path, fields);
740
+ } else if (priority !== undefined) {
741
+ step.priority = priority;
742
+ }
699
743
  if (due === null || due < 0 || due > CRM_TASK_MAX_DUE_DAYS) {
700
744
  refuse(reader, 'automation-step-field', `${what} needs dueInDays, from 0 to ${CRM_TASK_MAX_DUE_DAYS}.`, path, fields);
701
745
  } else {
@@ -709,7 +753,21 @@ function readStep(reader, raw, index, event, capabilities) {
709
753
  if (!CRM_ACTIVITY_KINDS.includes(kind)) {
710
754
  refuse(reader, 'automation-step-field', `${what} needs activityKind.`, path, fields);
711
755
  } else {
756
+ var _CRM_ACTIVITY_DIRECTIONS_kind, _fields_direction;
712
757
  step.activityKind = kind;
758
+ /*
759
+ * The direction is the kind's own: a call goes outbound, inbound or
760
+ * internal, an email outbound or inbound, and every other kind
761
+ * carries none (AGL-3538).
762
+ */ const allowed = (_CRM_ACTIVITY_DIRECTIONS_kind = CRM_ACTIVITY_DIRECTIONS[kind]) != null ? _CRM_ACTIVITY_DIRECTIONS_kind : [];
763
+ // Absent reads as empty: no direction.
764
+ const raw = (_fields_direction = fields['direction']) != null ? _fields_direction : '';
765
+ const direction = typeof raw === 'string' ? raw : null;
766
+ if (direction === null || (direction ? !allowed.includes(direction) : false)) {
767
+ refuse(reader, 'automation-step-field', allowed.length ? `${what} needs direction: ${allowed.join(', ')}, or empty.` : `${what} takes no direction: leave it empty for a ${String(kind)}.`, path, fields);
768
+ } else if (direction) {
769
+ step.direction = direction;
770
+ }
713
771
  }
714
772
  step.body = requireText(reader, text, 'text', AI_AUTOMATION_TEXT_MAX_CHARS, path, what);
715
773
  break;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/tools/ai-workflow-tool.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 ACTION_MAX_CONDITIONS,\n ACTION_MAX_STEPS,\n CONTACT_TAG_MAX_LENGTH,\n FLOW_TIMED_OUT_FIELD,\n FLOW_WAIT_MAX_MINUTES,\n FLOW_WAIT_MIN_MINUTES,\n HOST_ACTION_STEP_LABELS,\n TRIGGER_COMBINATORS,\n TRIGGER_CONDITION_OPS,\n type TriggerCombinator,\n type TriggerConditionOp,\n} from '@aglyn/aglyn/app-utils/actions'\nimport {\n CONTACT_LIFECYCLE_STAGE_LABELS,\n CONTACT_LIFECYCLE_STAGES,\n CRM_ACTIVITY_KINDS,\n CRM_TASK_KINDS,\n CRM_TASK_MAX_DUE_DAYS,\n type ContactLifecycleStage,\n type CrmActivityKind,\n type CrmTaskKind,\n} from '@aglyn/aglyn/app-utils/crm'\nimport {\n HOST_EVENT_PAYLOAD_KEYS,\n HOST_EVENT_TYPES,\n type HostEventType,\n} from '@aglyn/aglyn/app-utils/host-events'\nimport {\n AI_AUTOMATION_NEED_LABELS,\n AI_AUTOMATION_STEP_NEEDS,\n AI_AUTOMATION_STEP_TYPES,\n AI_AUTOMATION_TRIGGER_NEEDS,\n AI_AUTOMATION_UNSUPPORTED,\n AI_AUTOMATION_UNSUPPORTED_NEED,\n aiAutomationTriggerLabel,\n type AiAutomationCapabilities,\n type AiAutomationStepType,\n type AiAutomationUnsupported,\n} from '../model/ai-workflow-job'\nimport type { AiTool } from '../providers/contract'\nimport type { AiGenerationCheckResult } from '../runtime/ai-doctrine'\nimport type { AiDoctrineViolation } from '../runtime/ai-doctrine-validators'\nimport { HOSTILE_TEXT } from '../runtime/ai-node-tree'\n\n/**\n * The two tools a `workflow` job answers through (AGL-2919).\n *\n * `submit_automation` carries one automation in the Actions editor's own\n * vocabulary — a trigger from the host events, conditions over the fields the\n * trigger carries, and steps from the automation step types — with every\n * record it names written as WORDS. The step resolves those words against the\n * site after the answer, so the model is never shown the site's lists,\n * campaigns, workflows, webhooks or pipeline stages, and never writes an id it\n * could only have invented.\n *\n * `submit_explanation` carries a plain-words account of one automation, or of\n * why one of its runs failed.\n *\n * Both schemas are strict: every object forbids extra keys and requires every\n * key it has, and nothing in either is a `null`. Where a step may go without\n * something, the absence is an empty list or an empty string: a step that\n * always runs has an empty `when`, a notEmpty condition compares against\n * nothing, and an answer that builds an automation leaves `unsupported`\n * empty. Bounds a strict schema cannot state are stated in the descriptions\n * and held by the readers below, whose refusals name the field so the one\n * re-ask can fix it.\n *\n * A provider that constrains decoding compiles every strict schema of a\n * request into a grammar, and refuses one whose grammar grows past its size\n * (`AiToolSchemaLimits`). So the steps' union carries as little repetition as\n * a grammar can be made to hold:\n *\n * - a step is its guard and its action, `{ when, action }`, so the condition\n * is compiled once for the whole union instead of once per variant;\n * - a variant serves every step type that carries the same fields, named for\n * what they hold: the six steps that name a record share `reference`, and\n * the three that carry one line share `text`;\n * - every field stays required and every vocabulary stays an enum, so the\n * model is still decoded into the Actions editor's words.\n *\n * Ten variants carry all seventeen step types, and the reader below maps the\n * shared fields back onto the step's own key.\n */\n\nexport const AI_AUTOMATION_TOOL_NAME = 'submit_automation'\nexport const AI_WORKFLOW_EXPLANATION_TOOL_NAME = 'submit_explanation'\n\n/** The longest automation name the Actions editor stores. */\nexport const AI_AUTOMATION_NAME_MAX_CHARS = 60\n/** The longest subject the executor sends. */\nexport const AI_AUTOMATION_SUBJECT_MAX_CHARS = 200\n/** The longest email text the executor sends. */\nexport const AI_AUTOMATION_BODY_MAX_CHARS = 5_000\n/** The longest title, message or record name a step carries. */\nexport const AI_AUTOMATION_TEXT_MAX_CHARS = 300\n/** The longest words naming a record. */\nexport const AI_AUTOMATION_REFERENCE_MAX_CHARS = 100\n/** The longest condition value. */\nexport const AI_AUTOMATION_VALUE_MAX_CHARS = 200\n/** The most notes an answer keeps, and the longest. */\nexport const AI_AUTOMATION_NOTES_MAX = 3\nexport const AI_AUTOMATION_NOTE_MAX_CHARS = 300\n/**\n * The longest a whole answer may be, written out as JSON: what the routing\n * ceiling for `job.workflow` holds at three characters a token with as much\n * again to think in (`ai-job-workflow-step.spec.ts` measures it). Ten steps\n * with two emails of a paragraph or two each come to about 2,400, each step\n * carrying only its own fields.\n */\nexport const AI_AUTOMATION_ANSWER_MAX_CHARS = 6_000\n\n/** The explanation's bounds. */\nexport const AI_WORKFLOW_SUMMARY_MAX_CHARS = 400\nexport const AI_WORKFLOW_POINTS_MAX = 8\nexport const AI_WORKFLOW_SUGGESTIONS_MAX = 4\nexport const AI_WORKFLOW_LINE_MAX_CHARS = 300\n\nconst SEVERITIES = ['info', 'success', 'warning', 'error'] as const\ntype Severity = (typeof SEVERITIES)[number]\n\ntype Schema = Record<string, unknown>\n\n/**\n * What the schema defines once and refers to where it is used: a condition,\n * which the trigger and every step's guard share, and the guard itself.\n */\nconst DEFINITIONS: Schema = {\n condition: {\n type: 'object',\n additionalProperties: false,\n required: ['field', 'op', 'value'],\n properties: {\n field: {\n type: 'string',\n description: 'The field of the event the condition reads, as the trigger lists its fields.',\n },\n op: { type: 'string', enum: [...TRIGGER_CONDITION_OPS] },\n value: {\n type: 'string',\n description: 'What equals or contains compares against; empty for notEmpty.',\n },\n },\n },\n event: {\n type: 'string',\n enum: [...HOST_EVENT_TYPES],\n description: 'One of the things that happen on a site.',\n },\n // A list rather than a condition or `null`: a step goes without one by an\n // empty list, which costs no union.\n when: {\n type: 'array',\n description: 'At most one condition: the step runs only when it holds. Empty when the step always runs.',\n items: { $ref: '#/$defs/condition' },\n },\n}\n\n/** The steps that name one of the site's records, which they all name the same way. */\nconst REFERENCE_STEPS = [\n 'enrollList',\n 'assignCampaign',\n 'runWorkflow',\n 'datasetAppend',\n 'updateDataset',\n 'webhookPost',\n] as const satisfies readonly AiAutomationStepType[]\n\n/** The steps whose only field is the one line they carry. */\nconst TEXT_STEPS = [\n 'notifyAdmins',\n 'addContactTag',\n 'assignContactOwner',\n] as const satisfies readonly AiAutomationStepType[]\n\n/** The key each `reference` step fills in the answer the reader gives back. */\nconst REFERENCE_KEY = {\n enrollList: 'list',\n assignCampaign: 'campaign',\n runWorkflow: 'workflow',\n datasetAppend: 'dataset',\n updateDataset: 'dataset',\n webhookPost: 'webhook',\n} as const satisfies Readonly<Record<(typeof REFERENCE_STEPS)[number], keyof AiAutomationAnswerStep>>\n\n/**\n * The key each step's one line fills in the answer the reader gives back. Six\n * step types carry one line between them, so the schema asks for all six\n * under `text` and the reader puts each back where the automation keeps it.\n */\nconst TEXT_KEY = {\n notifyAdmins: 'title',\n addContactTag: 'tag',\n assignContactOwner: 'owner',\n siteAlert: 'message',\n createCrmTask: 'title',\n logCrmActivity: 'body',\n} as const satisfies Readonly<Partial<Record<AiAutomationStepType, keyof AiAutomationAnswerStep>>>\n\nconst minutes = (what: string): Schema => ({\n type: 'integer',\n description: `${what}, in whole minutes from ${FLOW_WAIT_MIN_MINUTES} to ${FLOW_WAIT_MAX_MINUTES}; an hour is 60 and a day 1440.`,\n})\n\n/**\n * One variant of the steps' union: the step types it serves, and the fields\n * every one of them carries, each required and never nullable. A type belongs\n * to exactly one variant, so the type a step names settles which fields it\n * writes.\n */\nfunction stepVariant(\n types: readonly AiAutomationStepType[],\n fields: Readonly<Record<string, Schema>>,\n): Schema {\n return {\n type: 'object',\n additionalProperties: false,\n required: ['type', ...Object.keys(fields)],\n properties: { type: { type: 'string', enum: [...types] }, ...fields },\n }\n}\n\n/** Every step type an automation may carry, grouped by the fields it needs. */\nexport const AI_AUTOMATION_STEP_VARIANTS: readonly Schema[] = [\n stepVariant([...REFERENCE_STEPS], {\n reference: {\n type: 'string',\n description:\n 'The record the step acts on — the email list, campaign, workflow, dataset or outbound webhook — in the words of the description, such as \"newsletter\". Never an id.',\n },\n }),\n stepVariant([...TEXT_STEPS], {\n text: {\n type: 'string',\n description: `The one line the step carries: for notifyAdmins what the admins read, for addContactTag the tag (at most ${CONTACT_TAG_MAX_LENGTH} characters), and for assignContactOwner \"round robin\" or the teammate’s email address the description gives.`,\n },\n }),\n stepVariant(['sendEmail'], {\n subject: { type: 'string', description: 'The subject line.' },\n body: { type: 'string', description: 'The email, as plain text.' },\n toField: {\n type: 'string',\n description: 'The event field holding the address: \"email\" unless the description names another.',\n },\n }),\n stepVariant(['siteAlert'], {\n text: { type: 'string', description: 'What the visitor reads.' },\n severity: { type: 'string', enum: [...SEVERITIES] },\n }),\n stepVariant(['wait'], { minutes: minutes('How long to wait') }),\n stepVariant(['waitForEvent'], {\n event: { $ref: '#/$defs/event' },\n minutes: minutes('When to give up'),\n }),\n stepVariant(['exitFlow'], {}),\n stepVariant(['setContactStage'], { stage: { type: 'string', enum: [...CONTACT_LIFECYCLE_STAGES] } }),\n stepVariant(['createCrmTask'], {\n text: { type: 'string', description: 'The task.' },\n taskKind: { type: 'string', enum: [...CRM_TASK_KINDS] },\n dueInDays: {\n type: 'integer',\n description: `Days from the run, 0 for today, at most ${CRM_TASK_MAX_DUE_DAYS}.`,\n },\n }),\n stepVariant(['logCrmActivity'], {\n activityKind: { type: 'string', enum: [...CRM_ACTIVITY_KINDS] },\n text: { type: 'string', description: 'What happened.' },\n }),\n]\n\n/** The automation tool. The same bytes on every request, so it sits inside the cached prefix. */\nexport function aiAutomationTool(): AiTool {\n return {\n name: AI_AUTOMATION_TOOL_NAME,\n description: `Submit one automation: its trigger, the conditions on it, and its steps in order. Written out, the whole automation is at most ${AI_AUTOMATION_ANSWER_MAX_CHARS} characters, so keep its emails short.`,\n strict: true,\n inputSchema: {\n type: 'object',\n additionalProperties: false,\n required: ['name', 'trigger', 'steps', 'notes', 'unsupported'],\n properties: {\n name: {\n type: 'string',\n description: `A short name for the automation, at most ${AI_AUTOMATION_NAME_MAX_CHARS} characters.`,\n },\n trigger: {\n type: 'object',\n additionalProperties: false,\n required: ['event', 'conditions', 'combinator'],\n properties: {\n event: { $ref: '#/$defs/event' },\n conditions: {\n type: 'array',\n description: `What the event must meet: at most ${ACTION_MAX_CONDITIONS} conditions, empty when it runs every time.`,\n items: { $ref: '#/$defs/condition' },\n },\n combinator: { type: 'string', enum: [...TRIGGER_COMBINATORS] },\n },\n },\n steps: {\n type: 'array',\n description: `The steps in order, at most ${ACTION_MAX_STEPS}. Each is when it runs and what it does, and the action carries only the fields its type takes. Empty only with unsupported.`,\n items: {\n type: 'object',\n additionalProperties: false,\n required: ['when', 'action'],\n properties: {\n when: { $ref: '#/$defs/when' },\n action: { anyOf: AI_AUTOMATION_STEP_VARIANTS },\n },\n },\n },\n notes: {\n type: 'array',\n description: `What the person must decide that the automation cannot hold; at most ${AI_AUTOMATION_NOTES_MAX} short sentences.`,\n items: { type: 'string' },\n },\n unsupported: {\n type: 'string',\n enum: ['', ...AI_AUTOMATION_UNSUPPORTED],\n description: 'Why no automation can be built from this description; empty when one is built.',\n },\n },\n $defs: DEFINITIONS,\n },\n }\n}\n\n/** The explanation tool. */\nexport function aiWorkflowExplanationTool(): AiTool {\n return {\n name: AI_WORKFLOW_EXPLANATION_TOOL_NAME,\n description: 'Submit the explanation, in plain words for someone who does not write code.',\n strict: true,\n inputSchema: {\n type: 'object',\n additionalProperties: false,\n required: ['summary', 'points', 'suggestions'],\n properties: {\n summary: {\n type: 'string',\n description: `One or two sentences, at most ${AI_WORKFLOW_SUMMARY_MAX_CHARS} characters.`,\n },\n points: {\n type: 'array',\n description: `At most ${AI_WORKFLOW_POINTS_MAX}, one sentence each.`,\n items: { type: 'string' },\n },\n suggestions: {\n type: 'array',\n description: `At most ${AI_WORKFLOW_SUGGESTIONS_MAX}, one sentence each; empty when there is nothing to suggest.`,\n items: { type: 'string' },\n },\n },\n },\n }\n}\n\n// ── Reading an automation ─────────────────────────────────────────────────\n\nexport interface AiAutomationCondition {\n field: string\n op: TriggerConditionOp\n /** `null` for `notEmpty`. */\n value: string | null\n}\n\n/** One step as the reader gives it back, every field the step does not use `null`. */\nexport interface AiAutomationAnswerStep {\n type: AiAutomationStepType\n when: AiAutomationCondition | null\n list: string | null\n campaign: string | null\n workflow: string | null\n webhook: string | null\n dataset: string | null\n subject: string | null\n body: string | null\n toField: string | null\n title: string | null\n message: string | null\n severity: Severity | null\n minutes: number | null\n event: HostEventType | null\n stage: ContactLifecycleStage | null\n tag: string | null\n owner: string | null\n taskKind: CrmTaskKind | null\n dueInDays: number | null\n activityKind: CrmActivityKind | null\n}\n\nexport interface AiAutomationAnswer {\n name: string\n trigger: {\n event: HostEventType\n conditions: AiAutomationCondition[]\n combinator: TriggerCombinator\n }\n steps: AiAutomationAnswerStep[]\n notes: string[]\n unsupported: AiAutomationUnsupported | null\n}\n\n/** The codes that say an answer could not be read as an automation at all. */\nexport const AI_AUTOMATION_UNREADABLE_CODES: readonly string[] = [\n 'automation-shape',\n 'automation-trigger',\n 'automation-step-type',\n]\n\n/** The codes that say an answer is larger than an automation may be. */\nexport const AI_AUTOMATION_OVERSIZE_CODES: readonly string[] = [\n 'automation-too-many-steps',\n 'automation-too-many-conditions',\n 'automation-too-long',\n]\n\n/** The address field a step reads when it names none. */\nconst DEFAULT_TO_FIELD = 'email'\nconst FIELD_NAME = /^[A-Za-z_][A-Za-z0-9_.-]{0,63}$/\nconst EMAIL_ADDRESS = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\nconst ROUND_ROBIN = /^\\s*round[\\s-]*robin\\s*$/i\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/** A string trimmed to one space between words, or `null` for none. */\nfunction textOf(value: unknown): string | null {\n if (typeof value !== 'string') return null\n const clean = value.replace(/[ \\t]+/g, ' ').trim()\n return clean ? clean : null\n}\n\n/** The fields a trigger's conditions and its steps' guards may read. */\nfunction fieldsFor(event: HostEventType): readonly string[] | null {\n // A form submission carries every field the form collects, which no fixed\n // list names, so any field name is readable on it.\n if (event === 'formSubmission') return null\n const keys = HOST_EVENT_PAYLOAD_KEYS[event]\n return keys?.length ? keys : null\n}\n\ninterface Reader {\n violations: AiDoctrineViolation[]\n offending: Array<[string, unknown]>\n}\n\nfunction refuse(\n reader: Reader,\n code: string,\n message: string,\n path: string,\n value: unknown,\n): void {\n reader.violations.push({ rule: null, code, message, paths: [path] })\n if (reader.offending.length < 6) reader.offending.push([path, value])\n}\n\nfunction readCondition(\n reader: Reader,\n raw: unknown,\n path: string,\n event: HostEventType,\n guard: boolean,\n): AiAutomationCondition | null {\n if (!isRecord(raw)) {\n refuse(reader, 'automation-shape', 'A condition is not an object with a field, an op and a value.', path, raw)\n return null\n }\n const field = textOf(raw['field'])\n const op = raw['op']\n if (!field || !FIELD_NAME.test(field)) {\n refuse(reader, 'automation-condition', 'Name the event field the condition reads.', path, raw)\n return null\n }\n if (!(TRIGGER_CONDITION_OPS as readonly unknown[]).includes(op)) {\n refuse(reader, 'automation-condition', `The condition on \"${field}\" needs equals, contains or notEmpty.`, path, raw)\n return null\n }\n if (event === 'formSubmission' && field === 'formId') {\n refuse(\n reader,\n 'automation-condition',\n 'A form submission names its form by formName, the form’s name as the site lists it.',\n path,\n raw,\n )\n return null\n }\n // A step's guard may also read whether the wait before it ran out of time.\n const readable = fieldsFor(event)\n if (readable && !readable.includes(field) && !(guard && field === FLOW_TIMED_OUT_FIELD)) {\n refuse(\n reader,\n 'automation-condition',\n `The trigger \"${aiAutomationTriggerLabel(event)}\" does not carry \"${field}\". It carries: ${readable.join(', ')}.`,\n path,\n raw,\n )\n return null\n }\n const value = textOf(raw['value'])\n if (op !== 'notEmpty' && !value) {\n refuse(reader, 'automation-condition', `The condition on \"${field}\" needs the value it compares against.`, path, raw)\n return null\n }\n if (value && value.length > AI_AUTOMATION_VALUE_MAX_CHARS) {\n refuse(reader, 'automation-too-long', `The value the condition on \"${field}\" compares against is too long.`, path, raw)\n return null\n }\n if (field === 'lifecycleStage' || field === 'previousStage') {\n const stage = value ? lifecycleStageOf(value) : null\n if (op !== 'notEmpty' && !stage) {\n refuse(\n reader,\n 'automation-condition',\n `A lifecycle stage is one of: ${CONTACT_LIFECYCLE_STAGES.join(', ')}.`,\n path,\n raw,\n )\n return null\n }\n return { field, op: op as TriggerConditionOp, value: op === 'notEmpty' ? null : stage }\n }\n return { field, op: op as TriggerConditionOp, value: op === 'notEmpty' ? null : value }\n}\n\n/** A lifecycle stage by its id or its label, case aside. */\nexport function lifecycleStageOf(value: string): ContactLifecycleStage | null {\n const wanted = value.trim().toLowerCase()\n return (\n CONTACT_LIFECYCLE_STAGES.find(\n (stage) => stage === wanted || CONTACT_LIFECYCLE_STAGE_LABELS[stage].toLowerCase() === wanted,\n ) ?? null\n )\n}\n\nfunction requireText(\n reader: Reader,\n step: Record<string, unknown>,\n key: string,\n max: number,\n path: string,\n what: string,\n): string | null {\n const value = textOf(step[key])\n if (!value) {\n refuse(reader, 'automation-step-field', `${what} needs ${key}.`, path, step)\n return null\n }\n if (value.length > max) {\n refuse(reader, 'automation-too-long', `${what}: ${key} is longer than ${max} characters.`, path, step)\n return null\n }\n if (HOSTILE_TEXT.test(value)) {\n refuse(reader, 'automation-markup', `${what}: write ${key} as plain text, with no HTML or script.`, path, step)\n return null\n }\n return value\n}\n\nfunction wholeNumber(value: unknown): number | null {\n return typeof value === 'number' && Number.isInteger(value) ? value : null\n}\n\nfunction readStep(\n reader: Reader,\n raw: unknown,\n index: number,\n event: HostEventType,\n capabilities: AiAutomationCapabilities,\n): AiAutomationAnswerStep | null {\n const path = `steps[${index}]`\n if (!isRecord(raw)) {\n refuse(reader, 'automation-shape', `Step ${index + 1} is not an object.`, path, raw)\n return null\n }\n // A step is its guard and its action: `{ when, action }`. An answer that\n // writes the action's own fields beside `when` reads the same, so a model\n // that flattens the step does not spend the one re-ask.\n const action = raw['action']\n const fields: Record<string, unknown> = isRecord(action) ? { ...action, when: raw['when'] } : raw\n const type = fields['type']\n if (!(AI_AUTOMATION_STEP_TYPES as readonly unknown[]).includes(type)) {\n refuse(\n reader,\n 'automation-step-type',\n `Step ${index + 1} is not one of the steps offered: ${AI_AUTOMATION_STEP_TYPES.join(', ')}.`,\n path,\n fields,\n )\n return null\n }\n const stepType = type as AiAutomationStepType\n const what = `Step ${index + 1} (${HOST_ACTION_STEP_LABELS[stepType]})`\n const need = AI_AUTOMATION_STEP_NEEDS[stepType]\n if (need && !capabilities[need]) {\n refuse(\n reader,\n 'automation-plan',\n `${what} needs ${AI_AUTOMATION_NEED_LABELS[need]}, which this workspace does not have. Leave it out, or answer with unsupported \"needs-${need}\".`,\n path,\n fields,\n )\n return null\n }\n const before = reader.violations.length\n const step: AiAutomationAnswerStep = {\n type: stepType,\n when: null,\n list: null,\n campaign: null,\n workflow: null,\n webhook: null,\n dataset: null,\n subject: null,\n body: null,\n toField: null,\n title: null,\n message: null,\n severity: null,\n minutes: null,\n event: null,\n stage: null,\n tag: null,\n owner: null,\n taskKind: null,\n dueInDays: null,\n activityKind: null,\n }\n // A step's `when` is a list of at most one condition; a lone condition, or\n // none, reads as the list it stands for.\n const when = fields['when']\n const guards = Array.isArray(when) ? when : when === null || when === undefined ? [] : [when]\n if (guards.length > 1) {\n refuse(reader, 'automation-condition', `${what}: when holds one condition at most.`, `${path}.when`, when)\n } else if (guards.length === 1) {\n step.when = readCondition(reader, guards[0], `${path}.when`, event, true)\n }\n // The six steps that name a record share `reference`, and the three that\n // carry one line share `text`; an answer that writes the step's own key\n // instead — `list`, `tag`, `owner` — reads the same.\n const shared = (key: 'reference' | 'text', own: keyof AiAutomationAnswerStep): unknown =>\n fields[key] ?? fields[own]\n const own = TEXT_KEY[stepType as keyof typeof TEXT_KEY]\n const text: Record<string, unknown> = own ? { text: shared('text', own) } : fields\n switch (stepType) {\n case 'sendEmail': {\n step.subject = requireText(reader, fields, 'subject', AI_AUTOMATION_SUBJECT_MAX_CHARS, path, what)\n step.body = requireText(reader, fields, 'body', AI_AUTOMATION_BODY_MAX_CHARS, path, what)\n const toField = textOf(fields['toField'])\n if (toField && !FIELD_NAME.test(toField)) {\n refuse(reader, 'automation-step-field', `${what}: toField names the event field holding the address.`, path, fields)\n } else {\n step.toField = toField && toField !== DEFAULT_TO_FIELD ? toField : null\n }\n break\n }\n case 'notifyAdmins':\n step.title = requireText(reader, text, 'text', AI_AUTOMATION_SUBJECT_MAX_CHARS, path, what)\n break\n case 'enrollList':\n case 'assignCampaign':\n case 'runWorkflow':\n case 'webhookPost':\n case 'datasetAppend':\n case 'updateDataset':\n step[REFERENCE_KEY[stepType]] = requireText(\n reader,\n { reference: shared('reference', REFERENCE_KEY[stepType]) },\n 'reference',\n AI_AUTOMATION_REFERENCE_MAX_CHARS,\n path,\n what,\n )\n break\n case 'siteAlert': {\n step.message = requireText(reader, text, 'text', AI_AUTOMATION_TEXT_MAX_CHARS, path, what)\n const severity = fields['severity']\n step.severity = (SEVERITIES as readonly unknown[]).includes(severity) ? (severity as Severity) : 'info'\n break\n }\n case 'wait':\n case 'waitForEvent': {\n const minutes = wholeNumber(fields['minutes'])\n if (minutes === null || minutes < FLOW_WAIT_MIN_MINUTES || minutes > FLOW_WAIT_MAX_MINUTES) {\n refuse(\n reader,\n 'automation-step-field',\n `${what} needs minutes, a whole number from ${FLOW_WAIT_MIN_MINUTES} to ${FLOW_WAIT_MAX_MINUTES}.`,\n path,\n fields,\n )\n } else {\n step.minutes = minutes\n }\n if (stepType === 'waitForEvent') {\n const waited = fields['event']\n if (!(HOST_EVENT_TYPES as readonly unknown[]).includes(waited)) {\n refuse(reader, 'automation-step-field', `${what} needs the event it waits for.`, path, fields)\n } else {\n step.event = waited as HostEventType\n }\n }\n break\n }\n case 'exitFlow':\n break\n case 'setContactStage': {\n const stage = fields['stage']\n if (!(CONTACT_LIFECYCLE_STAGES as readonly unknown[]).includes(stage)) {\n refuse(reader, 'automation-step-field', `${what} needs the lifecycle stage to set.`, path, fields)\n } else {\n step.stage = stage as ContactLifecycleStage\n }\n break\n }\n case 'addContactTag':\n step.tag = requireText(reader, text, 'text', CONTACT_TAG_MAX_LENGTH, path, what)\n break\n case 'assignContactOwner': {\n const owner = textOf(text['text'])\n if (!owner || !(ROUND_ROBIN.test(owner) || EMAIL_ADDRESS.test(owner))) {\n refuse(\n reader,\n 'automation-owner',\n `${what}: give the owner as \"round robin\", or as the teammate’s email address the description gives. A teammate named without one goes in notes, not in a step.`,\n path,\n fields,\n )\n } else {\n step.owner = ROUND_ROBIN.test(owner) ? 'round robin' : owner\n }\n break\n }\n case 'createCrmTask': {\n step.title = requireText(reader, text, 'text', AI_AUTOMATION_SUBJECT_MAX_CHARS, path, what)\n const kind = fields['taskKind']\n const due = wholeNumber(fields['dueInDays'])\n if (!(CRM_TASK_KINDS as readonly unknown[]).includes(kind)) {\n refuse(reader, 'automation-step-field', `${what} needs taskKind.`, path, fields)\n } else {\n step.taskKind = kind as CrmTaskKind\n }\n if (due === null || due < 0 || due > CRM_TASK_MAX_DUE_DAYS) {\n refuse(reader, 'automation-step-field', `${what} needs dueInDays, from 0 to ${CRM_TASK_MAX_DUE_DAYS}.`, path, fields)\n } else {\n step.dueInDays = due\n }\n break\n }\n case 'logCrmActivity': {\n const kind = fields['activityKind']\n if (!(CRM_ACTIVITY_KINDS as readonly unknown[]).includes(kind)) {\n refuse(reader, 'automation-step-field', `${what} needs activityKind.`, path, fields)\n } else {\n step.activityKind = kind as CrmActivityKind\n }\n step.body = requireText(reader, text, 'text', AI_AUTOMATION_TEXT_MAX_CHARS, path, what)\n break\n }\n }\n return reader.violations.length === before ? step : null\n}\n\n/**\n * The automation tool's answer read and held to the vocabulary and to what\n * this workspace can run — the check the doctrine's loop runs on each answer,\n * beside rule 13. `value` is the automation when nothing is refused.\n */\nexport function readAiAutomationAnswer(\n answer: Record<string, unknown>,\n capabilities: AiAutomationCapabilities,\n): AiGenerationCheckResult<AiAutomationAnswer> {\n const reader: Reader = { violations: [], offending: [] }\n const done = (value: AiAutomationAnswer | null): AiGenerationCheckResult<AiAutomationAnswer> => ({\n value: reader.violations.length ? null : value,\n violations: reader.violations,\n ...(reader.offending.length ? { offending: Object.fromEntries(reader.offending) } : {}),\n })\n const notes = (Array.isArray(answer['notes']) ? answer['notes'] : [])\n .map(textOf)\n .filter((note): note is string => note !== null && !HOSTILE_TEXT.test(note))\n .slice(0, AI_AUTOMATION_NOTES_MAX)\n .map((note) => note.slice(0, AI_AUTOMATION_NOTE_MAX_CHARS))\n const name = (textOf(answer['name']) ?? '').slice(0, AI_AUTOMATION_NAME_MAX_CHARS)\n const written = JSON.stringify(answer).length\n if (written > AI_AUTOMATION_ANSWER_MAX_CHARS) {\n refuse(\n reader,\n 'automation-too-long',\n `Written out, the automation is ${written} characters, over the ${AI_AUTOMATION_ANSWER_MAX_CHARS} it may be. Shorten its emails and messages, or use fewer steps.`,\n 'steps',\n written,\n )\n return done(null)\n }\n\n // An answer that builds an automation leaves `unsupported` empty, which the\n // schema states as an empty string rather than a `null`.\n const unsupported = answer['unsupported']\n if (unsupported !== null && unsupported !== undefined && unsupported !== '') {\n if (!(AI_AUTOMATION_UNSUPPORTED as readonly unknown[]).includes(unsupported)) {\n refuse(reader, 'automation-shape', 'unsupported is empty, or one of the reasons offered.', 'unsupported', unsupported)\n return done(null)\n }\n const need = AI_AUTOMATION_UNSUPPORTED_NEED[unsupported as AiAutomationUnsupported]\n if (need && capabilities[need]) {\n refuse(\n reader,\n 'automation-unsupported',\n `This workspace has ${AI_AUTOMATION_NEED_LABELS[need]}: build the automation with it.`,\n 'unsupported',\n unsupported,\n )\n return done(null)\n }\n return done({\n name,\n trigger: { event: HOST_EVENT_TYPES[0], conditions: [], combinator: 'and' },\n steps: [],\n notes,\n unsupported: unsupported as AiAutomationUnsupported,\n })\n }\n\n const trigger = answer['trigger']\n const steps = answer['steps']\n if (!isRecord(trigger) || !Array.isArray(steps)) {\n refuse(reader, 'automation-shape', 'The answer has no trigger and steps.', 'trigger', trigger)\n return done(null)\n }\n const event = trigger['event']\n if (!(HOST_EVENT_TYPES as readonly unknown[]).includes(event)) {\n refuse(reader, 'automation-trigger', 'The trigger is not one of the events offered.', 'trigger.event', event)\n return done(null)\n }\n const hostEvent = event as HostEventType\n const need = AI_AUTOMATION_TRIGGER_NEEDS[hostEvent]\n if (need && !capabilities[need]) {\n refuse(\n reader,\n 'automation-plan',\n `The trigger \"${aiAutomationTriggerLabel(hostEvent)}\" needs ${AI_AUTOMATION_NEED_LABELS[need]}, which this workspace does not have. Pick another trigger, or answer with unsupported \"needs-${need}\".`,\n 'trigger.event',\n event,\n )\n return done(null)\n }\n const rawConditions = Array.isArray(trigger['conditions']) ? trigger['conditions'] : []\n if (rawConditions.length > ACTION_MAX_CONDITIONS) {\n refuse(\n reader,\n 'automation-too-many-conditions',\n `A trigger holds at most ${ACTION_MAX_CONDITIONS} conditions.`,\n 'trigger.conditions',\n rawConditions.length,\n )\n }\n const conditions = rawConditions\n .slice(0, ACTION_MAX_CONDITIONS)\n .map((raw, index) => readCondition(reader, raw, `trigger.conditions[${index}]`, hostEvent, false))\n .filter((condition): condition is AiAutomationCondition => condition !== null)\n const combinator = (TRIGGER_COMBINATORS as readonly unknown[]).includes(trigger['combinator'])\n ? (trigger['combinator'] as TriggerCombinator)\n : 'and'\n\n if (!steps.length) {\n refuse(reader, 'automation-shape', 'An automation has at least one step; answer unsupported when none fits.', 'steps', steps)\n }\n if (steps.length > ACTION_MAX_STEPS) {\n refuse(reader, 'automation-too-many-steps', `An automation holds at most ${ACTION_MAX_STEPS} steps.`, 'steps', steps.length)\n }\n const read = steps\n .slice(0, ACTION_MAX_STEPS)\n .map((raw, index) => readStep(reader, raw, index, hostEvent, capabilities))\n .filter((step): step is AiAutomationAnswerStep => step !== null)\n\n return done({\n name,\n trigger: { event: hostEvent, conditions, combinator },\n steps: read,\n notes,\n unsupported: null,\n })\n}\n\n// ── Reading an explanation ────────────────────────────────────────────────\n\nexport interface AiWorkflowExplanation {\n summary: string\n points: string[]\n suggestions: string[]\n}\n\n/** Whether a line carries an email address, which nothing an explanation was shown holds. */\nconst CARRIES_ADDRESS = /[^\\s@]+@[^\\s@]+\\.[^\\s@]+/\n\nfunction lines(value: unknown, max: number): string[] {\n return (Array.isArray(value) ? value : [])\n .map(textOf)\n .filter((line): line is string => line !== null)\n .slice(0, max)\n .map((line) => line.slice(0, AI_WORKFLOW_LINE_MAX_CHARS))\n}\n\n/**\n * The explanation tool's answer: a summary, and at most so many points and\n * suggestions, each cut to a line. Refused when it has no summary, or carries\n * markup or an address — plain words for a person, about a record whose\n * personal details were removed before the model saw it.\n */\nexport function readAiWorkflowExplanation(\n answer: Record<string, unknown>,\n): AiGenerationCheckResult<AiWorkflowExplanation> {\n const summary = (textOf(answer['summary']) ?? '').slice(0, AI_WORKFLOW_SUMMARY_MAX_CHARS)\n const value: AiWorkflowExplanation = {\n summary,\n points: lines(answer['points'], AI_WORKFLOW_POINTS_MAX),\n suggestions: lines(answer['suggestions'], AI_WORKFLOW_SUGGESTIONS_MAX),\n }\n const violations: AiDoctrineViolation[] = []\n if (!summary) {\n violations.push({ rule: null, code: 'explanation-shape', message: 'The explanation has no summary.' })\n }\n const all = [value.summary, ...value.points, ...value.suggestions]\n if (all.some((line) => HOSTILE_TEXT.test(line))) {\n violations.push({\n rule: null,\n code: 'explanation-markup',\n message: 'Write the explanation as plain text, with no HTML or script.',\n })\n }\n if (all.some((line) => CARRIES_ADDRESS.test(line))) {\n violations.push({\n rule: null,\n code: 'explanation-address',\n message: 'The explanation names an email address. Describe the person or the teammate instead.',\n })\n }\n return { value: violations.length ? null : value, violations }\n}\n"],"names":["ACTION_MAX_CONDITIONS","ACTION_MAX_STEPS","CONTACT_TAG_MAX_LENGTH","FLOW_TIMED_OUT_FIELD","FLOW_WAIT_MAX_MINUTES","FLOW_WAIT_MIN_MINUTES","HOST_ACTION_STEP_LABELS","TRIGGER_COMBINATORS","TRIGGER_CONDITION_OPS","CONTACT_LIFECYCLE_STAGE_LABELS","CONTACT_LIFECYCLE_STAGES","CRM_ACTIVITY_KINDS","CRM_TASK_KINDS","CRM_TASK_MAX_DUE_DAYS","HOST_EVENT_PAYLOAD_KEYS","HOST_EVENT_TYPES","AI_AUTOMATION_NEED_LABELS","AI_AUTOMATION_STEP_NEEDS","AI_AUTOMATION_STEP_TYPES","AI_AUTOMATION_TRIGGER_NEEDS","AI_AUTOMATION_UNSUPPORTED","AI_AUTOMATION_UNSUPPORTED_NEED","aiAutomationTriggerLabel","HOSTILE_TEXT","AI_AUTOMATION_TOOL_NAME","AI_WORKFLOW_EXPLANATION_TOOL_NAME","AI_AUTOMATION_NAME_MAX_CHARS","AI_AUTOMATION_SUBJECT_MAX_CHARS","AI_AUTOMATION_BODY_MAX_CHARS","AI_AUTOMATION_TEXT_MAX_CHARS","AI_AUTOMATION_REFERENCE_MAX_CHARS","AI_AUTOMATION_VALUE_MAX_CHARS","AI_AUTOMATION_NOTES_MAX","AI_AUTOMATION_NOTE_MAX_CHARS","AI_AUTOMATION_ANSWER_MAX_CHARS","AI_WORKFLOW_SUMMARY_MAX_CHARS","AI_WORKFLOW_POINTS_MAX","AI_WORKFLOW_SUGGESTIONS_MAX","AI_WORKFLOW_LINE_MAX_CHARS","SEVERITIES","DEFINITIONS","condition","type","additionalProperties","required","properties","field","description","op","enum","value","event","when","items","$ref","REFERENCE_STEPS","TEXT_STEPS","REFERENCE_KEY","enrollList","assignCampaign","runWorkflow","datasetAppend","updateDataset","webhookPost","TEXT_KEY","notifyAdmins","addContactTag","assignContactOwner","siteAlert","createCrmTask","logCrmActivity","minutes","what","stepVariant","types","fields","Object","keys","AI_AUTOMATION_STEP_VARIANTS","reference","text","subject","body","toField","severity","stage","taskKind","dueInDays","activityKind","aiAutomationTool","name","strict","inputSchema","trigger","conditions","combinator","steps","action","anyOf","notes","unsupported","$defs","aiWorkflowExplanationTool","summary","points","suggestions","AI_AUTOMATION_UNREADABLE_CODES","AI_AUTOMATION_OVERSIZE_CODES","DEFAULT_TO_FIELD","FIELD_NAME","EMAIL_ADDRESS","ROUND_ROBIN","isRecord","Array","isArray","textOf","clean","replace","trim","fieldsFor","length","refuse","reader","code","message","path","violations","push","rule","paths","offending","readCondition","raw","guard","test","includes","readable","join","lifecycleStageOf","wanted","toLowerCase","find","requireText","step","key","max","wholeNumber","Number","isInteger","readStep","index","capabilities","stepType","need","before","list","campaign","workflow","webhook","dataset","title","tag","owner","guards","undefined","shared","own","waited","kind","due","readAiAutomationAnswer","answer","done","fromEntries","map","filter","note","slice","written","JSON","stringify","hostEvent","rawConditions","read","CARRIES_ADDRESS","lines","line","readAiWorkflowExplanation","all","some"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,qBAAqB,EACrBC,gBAAgB,EAChBC,sBAAsB,EACtBC,oBAAoB,EACpBC,qBAAqB,EACrBC,qBAAqB,EACrBC,uBAAuB,EACvBC,mBAAmB,EACnBC,qBAAqB,QAGhB,iCAAgC;AACvC,SACEC,8BAA8B,EAC9BC,wBAAwB,EACxBC,kBAAkB,EAClBC,cAAc,EACdC,qBAAqB,QAIh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ASqJ,0BACdhB,MAA+B;QAEdxD;IAAjB,MAAMZ,UAAU,EAACY,UAAAA,OAAOwD,MAAM,CAAC,UAAU,aAAxBxD,UAA6B,IAAI8D,KAAK,CAAC,GAAG9I;IAC3D,MAAMe,QAA+B;QACnCqD;QACAC,QAAQiF,MAAMd,MAAM,CAAC,SAAS,EAAEvI;QAChCqE,aAAagF,MAAMd,MAAM,CAAC,cAAc,EAAEtI;IAC5C;IACA,MAAMyF,aAAoC,EAAE;IAC5C,IAAI,CAACvB,SAAS;QACZuB,WAAWC,IAAI,CAAC;YAAEC,MAAM;YAAML,MAAM;YAAqBC,SAAS;QAAkC;IACtG;IACA,MAAMgE,MAAM;QAAC1I,MAAMqD,OAAO;WAAKrD,MAAMsD,MAAM;WAAKtD,MAAMuD,WAAW;KAAC;IAClE,IAAImF,IAAIC,IAAI,CAAC,CAACH,OAASnK,aAAa+G,IAAI,CAACoD,QAAQ;QAC/C5D,WAAWC,IAAI,CAAC;YACdC,MAAM;YACNL,MAAM;YACNC,SAAS;QACX;IACF;IACA,IAAIgE,IAAIC,IAAI,CAAC,CAACH,OAASF,gBAAgBlD,IAAI,CAACoD,QAAQ;QAClD5D,WAAWC,IAAI,CAAC;YACdC,MAAM;YACNL,MAAM;YACNC,SAAS;QACX;IACF;IACA,OAAO;QAAE1E,OAAO4E,WAAWN,MAAM,GAAG,OAAOtE;QAAO4E;IAAW;AAC/D"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/tools/ai-workflow-tool.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 ACTION_MAX_CONDITIONS,\n ACTION_MAX_STEPS,\n TRIGGER_COMBINATORS,\n TRIGGER_CONDITION_OPS,\n type TriggerCombinator,\n type TriggerConditionOp,\n} from '@aglyn/aglyn/app-utils/site-interactions'\nimport {\n CONTACT_LIFECYCLE_STAGE_LABELS,\n CONTACT_LIFECYCLE_STAGES,\n CONTACT_TAG_MAX_LENGTH,\n CRM_ACTIVITY_DIRECTIONS,\n CRM_ACTIVITY_KINDS,\n CRM_TASK_KINDS,\n CRM_TASK_MAX_DUE_DAYS,\n type ContactLifecycleStage,\n type CrmActivityDirection,\n type CrmActivityKind,\n type CrmTaskKind,\n type CrmTaskPriority,\n} from '@aglyn/aglyn/app-utils/crm'\nimport {\n HOST_EVENT_PAYLOAD_KEYS,\n HOST_EVENT_TYPES,\n type HostEventType,\n} from '@aglyn/aglyn/app-utils/host-events'\nimport {\n AI_AUTOMATION_NEED_LABELS,\n AI_AUTOMATION_STEP_NEEDS,\n AI_AUTOMATION_STEP_TYPES,\n AI_AUTOMATION_TRIGGER_NEEDS,\n AI_AUTOMATION_UNSUPPORTED,\n AI_AUTOMATION_UNSUPPORTED_NEED,\n aiAutomationTriggerLabel,\n type AiAutomationCapabilities,\n type AiAutomationStepType,\n type AiAutomationUnsupported,\n} from '../model/ai-workflow-job'\nimport {\n AI_AUTOMATION_TIMED_OUT_FIELD,\n AI_AUTOMATION_WAIT_MINUTES,\n aiStepLabel,\n} from '../model/ai-automation-format'\nimport type { AiTool } from '../providers/contract'\nimport type { AiGenerationCheckResult } from '../runtime/ai-doctrine'\nimport type { AiDoctrineViolation } from '../runtime/ai-doctrine-validators'\nimport { HOSTILE_TEXT } from '../runtime/ai-node-tree'\n\n/**\n * The two tools a `workflow` job answers through (AGL-2919).\n *\n * `submit_automation` carries one automation in the Actions editor's own\n * vocabulary — a trigger from the host events, conditions over the fields the\n * trigger carries, and steps from the automation step types — with every\n * record it names written as WORDS. The step resolves those words against the\n * site after the answer, so the model is never shown the site's lists,\n * campaigns, workflows, webhooks or pipeline stages, and never writes an id it\n * could only have invented.\n *\n * `submit_explanation` carries a plain-words account of one automation, or of\n * why one of its runs failed.\n *\n * Both schemas are strict: every object forbids extra keys and requires every\n * key it has, and nothing in either is a `null`. Where a step may go without\n * something, the absence is an empty list or an empty string: a step that\n * always runs has an empty `when`, a notEmpty condition compares against\n * nothing, and an answer that builds an automation leaves `unsupported`\n * empty. Bounds a strict schema cannot state are stated in the descriptions\n * and held by the readers below, whose refusals name the field so the one\n * re-ask can fix it.\n *\n * A provider that constrains decoding compiles every strict schema of a\n * request into a grammar, and refuses one whose grammar grows past its size\n * (`AiToolSchemaLimits`). So the steps' union carries as little repetition as\n * a grammar can be made to hold:\n *\n * - a step is its guard and its action, `{ when, action }`, so the condition\n * is compiled once for the whole union instead of once per variant;\n * - a variant serves every step type that carries the same fields, named for\n * what they hold: the six steps that name a record share `reference`, and\n * the three that carry one line share `text`;\n * - every field stays required and every vocabulary but one stays an enum,\n * so the model is still decoded into the Actions editor's words. The one\n * is the event a waitForEvent step waits for: the trigger's `event` already\n * compiles the host events' enum, and a second copy of it is what a task's\n * priority and a logged call's direction cost (AGL-3538). It is a string\n * described as one of the trigger events, and the reader refuses any\n * other naming every event, so the one re-ask can fix it;\n * - a description is free: a compiler drops it (`aiToolSchemaCompiledBytes`),\n * so the words a field needs go there and never into the grammar.\n *\n * Ten variants carry all seventeen step types, and the reader below maps the\n * shared fields back onto the step's own key.\n */\n\nexport const AI_AUTOMATION_TOOL_NAME = 'submit_automation'\nexport const AI_WORKFLOW_EXPLANATION_TOOL_NAME = 'submit_explanation'\n\n/** The longest automation name the Actions editor stores. */\nexport const AI_AUTOMATION_NAME_MAX_CHARS = 60\n/** The longest subject the executor sends. */\nexport const AI_AUTOMATION_SUBJECT_MAX_CHARS = 200\n/** The longest email text the executor sends. */\nexport const AI_AUTOMATION_BODY_MAX_CHARS = 5_000\n/** The longest title, message or record name a step carries. */\nexport const AI_AUTOMATION_TEXT_MAX_CHARS = 300\n/** The longest words naming a record. */\nexport const AI_AUTOMATION_REFERENCE_MAX_CHARS = 100\n/** The longest condition value. */\nexport const AI_AUTOMATION_VALUE_MAX_CHARS = 200\n/** The most notes an answer keeps, and the longest. */\nexport const AI_AUTOMATION_NOTES_MAX = 3\nexport const AI_AUTOMATION_NOTE_MAX_CHARS = 300\n/**\n * The longest a whole answer may be, written out as JSON: what the routing\n * ceiling for `job.workflow` holds at three characters a token with as much\n * again to think in (`ai-job-workflow-step.spec.ts` measures it). Ten steps\n * with two emails of a paragraph or two each come to about 2,400, each step\n * carrying only its own fields.\n */\nexport const AI_AUTOMATION_ANSWER_MAX_CHARS = 6_000\n\n/** The explanation's bounds. */\nexport const AI_WORKFLOW_SUMMARY_MAX_CHARS = 400\nexport const AI_WORKFLOW_POINTS_MAX = 8\nexport const AI_WORKFLOW_SUGGESTIONS_MAX = 4\nexport const AI_WORKFLOW_LINE_MAX_CHARS = 300\n\nconst SEVERITIES = ['info', 'success', 'warning', 'error'] as const\ntype Severity = (typeof SEVERITIES)[number]\n\n/** A task's priorities, by meaning — the runner stores the org's label for each (AGL-3517). */\nconst TASK_PRIORITIES = ['low', 'normal', 'high'] as const satisfies readonly CrmTaskPriority[]\n\n/** Every direction any activity takes, and `''` for a kind that takes none (AGL-3538). */\nconst ACTIVITY_DIRECTIONS = [\n '',\n ...new Set(Object.values(CRM_ACTIVITY_DIRECTIONS).flatMap((directions) => [...(directions ?? [])])),\n] as const\n\n/** The events a waitForEvent step may wait for, as its refusal names them. */\nconst WAITABLE_EVENTS = HOST_EVENT_TYPES.join(', ')\n\ntype Schema = Record<string, unknown>\n\n/**\n * What the schema defines once and refers to where it is used: a condition,\n * which the trigger and every step's guard share, and the guard itself.\n */\nconst DEFINITIONS: Schema = {\n condition: {\n type: 'object',\n additionalProperties: false,\n required: ['field', 'op', 'value'],\n properties: {\n field: {\n type: 'string',\n description: 'The field of the event the condition reads, as the trigger lists its fields.',\n },\n op: { type: 'string', enum: [...TRIGGER_CONDITION_OPS] },\n value: {\n type: 'string',\n description: 'What equals or contains compares against; empty for notEmpty.',\n },\n },\n },\n event: {\n type: 'string',\n enum: [...HOST_EVENT_TYPES],\n description: 'One of the things that happen on a site.',\n },\n // A list rather than a condition or `null`: a step goes without one by an\n // empty list, which costs no union.\n when: {\n type: 'array',\n description: 'At most one condition: the step runs only when it holds. Empty when the step always runs.',\n items: { $ref: '#/$defs/condition' },\n },\n}\n\n/** The steps that name one of the site's records, which they all name the same way. */\nconst REFERENCE_STEPS = [\n 'enrollList',\n 'assignCampaign',\n 'runWorkflow',\n 'datasetAppend',\n 'updateDataset',\n 'webhookPost',\n] as const satisfies readonly AiAutomationStepType[]\n\n/** The steps whose only field is the one line they carry. */\nconst TEXT_STEPS = [\n 'notifyAdmins',\n 'addContactTag',\n 'assignContactOwner',\n] as const satisfies readonly AiAutomationStepType[]\n\n/** The key each `reference` step fills in the answer the reader gives back. */\nconst REFERENCE_KEY = {\n enrollList: 'list',\n assignCampaign: 'campaign',\n runWorkflow: 'workflow',\n datasetAppend: 'dataset',\n updateDataset: 'dataset',\n webhookPost: 'webhook',\n} as const satisfies Readonly<Record<(typeof REFERENCE_STEPS)[number], keyof AiAutomationAnswerStep>>\n\n/**\n * The key each step's one line fills in the answer the reader gives back. Six\n * step types carry one line between them, so the schema asks for all six\n * under `text` and the reader puts each back where the automation keeps it.\n */\nconst TEXT_KEY = {\n notifyAdmins: 'title',\n addContactTag: 'tag',\n assignContactOwner: 'owner',\n siteAlert: 'message',\n createCrmTask: 'title',\n logCrmActivity: 'body',\n} as const satisfies Readonly<Partial<Record<AiAutomationStepType, keyof AiAutomationAnswerStep>>>\n\nconst minutes = (what: string): Schema => ({\n type: 'integer',\n description: `${what}, in whole minutes from ${AI_AUTOMATION_WAIT_MINUTES.min} to ${AI_AUTOMATION_WAIT_MINUTES.max}; an hour is 60 and a day 1440.`,\n})\n\n/**\n * One variant of the steps' union: the step types it serves, and the fields\n * every one of them carries, each required and never nullable. A type belongs\n * to exactly one variant, so the type a step names settles which fields it\n * writes.\n */\nfunction stepVariant(\n types: readonly AiAutomationStepType[],\n fields: Readonly<Record<string, Schema>>,\n): Schema {\n return {\n type: 'object',\n additionalProperties: false,\n required: ['type', ...Object.keys(fields)],\n properties: { type: { type: 'string', enum: [...types] }, ...fields },\n }\n}\n\n/** Every step type an automation may carry, grouped by the fields it needs. */\nexport const AI_AUTOMATION_STEP_VARIANTS: readonly Schema[] = [\n stepVariant([...REFERENCE_STEPS], {\n reference: {\n type: 'string',\n description:\n 'The record the step acts on — the email list, campaign, workflow, dataset or outbound webhook — in the words of the description, such as \"newsletter\". Never an id.',\n },\n }),\n stepVariant([...TEXT_STEPS], {\n text: {\n type: 'string',\n description: `The one line the step carries: for notifyAdmins what the admins read, for addContactTag the tag (at most ${CONTACT_TAG_MAX_LENGTH} characters), and for assignContactOwner \"round robin\" or the teammate’s email address the description gives.`,\n },\n }),\n stepVariant(['sendEmail'], {\n subject: { type: 'string', description: 'The subject line.' },\n body: { type: 'string', description: 'The email, as plain text.' },\n toField: {\n type: 'string',\n description: 'The event field holding the address: \"email\" unless the description names another.',\n },\n }),\n stepVariant(['siteAlert'], {\n text: { type: 'string', description: 'What the visitor reads.' },\n severity: { type: 'string', enum: [...SEVERITIES] },\n }),\n stepVariant(['wait'], { minutes: minutes('How long to wait') }),\n stepVariant(['waitForEvent'], {\n // A string, not the events' enum again — see the header.\n event: { type: 'string', description: 'One of the trigger events.' },\n minutes: minutes('When to give up'),\n }),\n stepVariant(['exitFlow'], {}),\n stepVariant(['setContactStage'], { stage: { type: 'string', enum: [...CONTACT_LIFECYCLE_STAGES] } }),\n stepVariant(['createCrmTask'], {\n text: { type: 'string', description: 'The task.' },\n taskKind: { type: 'string', enum: [...CRM_TASK_KINDS] },\n priority: { type: 'string', enum: [...TASK_PRIORITIES] },\n dueInDays: {\n type: 'integer',\n description: `Days from the run, 0 for today, at most ${CRM_TASK_MAX_DUE_DAYS}.`,\n },\n }),\n stepVariant(['logCrmActivity'], {\n activityKind: { type: 'string', enum: [...CRM_ACTIVITY_KINDS] },\n direction: {\n type: 'string',\n enum: [...ACTIVITY_DIRECTIONS],\n description: 'A call: outbound, inbound or internal. An email: outbound or inbound. Else empty.',\n },\n text: { type: 'string', description: 'What happened.' },\n }),\n]\n\n/** The automation tool. The same bytes on every request, so it sits inside the cached prefix. */\nexport function aiAutomationTool(): AiTool {\n return {\n name: AI_AUTOMATION_TOOL_NAME,\n description: `Submit one automation: its trigger, the conditions on it, and its steps in order. Written out, the whole automation is at most ${AI_AUTOMATION_ANSWER_MAX_CHARS} characters, so keep its emails short.`,\n strict: true,\n inputSchema: {\n type: 'object',\n additionalProperties: false,\n required: ['name', 'trigger', 'steps', 'notes', 'unsupported'],\n properties: {\n name: {\n type: 'string',\n description: `A short name for the automation, at most ${AI_AUTOMATION_NAME_MAX_CHARS} characters.`,\n },\n trigger: {\n type: 'object',\n additionalProperties: false,\n required: ['event', 'conditions', 'combinator'],\n properties: {\n event: { $ref: '#/$defs/event' },\n conditions: {\n type: 'array',\n description: `What the event must meet: at most ${ACTION_MAX_CONDITIONS} conditions, empty when it runs every time.`,\n items: { $ref: '#/$defs/condition' },\n },\n combinator: { type: 'string', enum: [...TRIGGER_COMBINATORS] },\n },\n },\n steps: {\n type: 'array',\n description: `The steps in order, at most ${ACTION_MAX_STEPS}. Each is when it runs and what it does, and the action carries only the fields its type takes. Empty only with unsupported.`,\n items: {\n type: 'object',\n additionalProperties: false,\n required: ['when', 'action'],\n properties: {\n when: { $ref: '#/$defs/when' },\n action: { anyOf: AI_AUTOMATION_STEP_VARIANTS },\n },\n },\n },\n notes: {\n type: 'array',\n description: `What the person must decide that the automation cannot hold; at most ${AI_AUTOMATION_NOTES_MAX} short sentences.`,\n items: { type: 'string' },\n },\n unsupported: {\n type: 'string',\n enum: ['', ...AI_AUTOMATION_UNSUPPORTED],\n description: 'Why no automation can be built from this description; empty when one is built.',\n },\n },\n $defs: DEFINITIONS,\n },\n }\n}\n\n/** The explanation tool. */\nexport function aiWorkflowExplanationTool(): AiTool {\n return {\n name: AI_WORKFLOW_EXPLANATION_TOOL_NAME,\n description: 'Submit the explanation, in plain words for someone who does not write code.',\n strict: true,\n inputSchema: {\n type: 'object',\n additionalProperties: false,\n required: ['summary', 'points', 'suggestions'],\n properties: {\n summary: {\n type: 'string',\n description: `One or two sentences, at most ${AI_WORKFLOW_SUMMARY_MAX_CHARS} characters.`,\n },\n points: {\n type: 'array',\n description: `At most ${AI_WORKFLOW_POINTS_MAX}, one sentence each.`,\n items: { type: 'string' },\n },\n suggestions: {\n type: 'array',\n description: `At most ${AI_WORKFLOW_SUGGESTIONS_MAX}, one sentence each; empty when there is nothing to suggest.`,\n items: { type: 'string' },\n },\n },\n },\n }\n}\n\n// ── Reading an automation ─────────────────────────────────────────────────\n\nexport interface AiAutomationCondition {\n field: string\n op: TriggerConditionOp\n /** `null` for `notEmpty`. */\n value: string | null\n}\n\n/** One step as the reader gives it back, every field the step does not use `null`. */\nexport interface AiAutomationAnswerStep {\n type: AiAutomationStepType\n when: AiAutomationCondition | null\n list: string | null\n campaign: string | null\n workflow: string | null\n webhook: string | null\n dataset: string | null\n subject: string | null\n body: string | null\n toField: string | null\n title: string | null\n message: string | null\n severity: Severity | null\n minutes: number | null\n event: HostEventType | null\n stage: ContactLifecycleStage | null\n tag: string | null\n owner: string | null\n taskKind: CrmTaskKind | null\n /** A created task's priority, by meaning (AGL-3538). */\n priority: CrmTaskPriority | null\n dueInDays: number | null\n activityKind: CrmActivityKind | null\n /** Which way a logged call or email went (AGL-3538); `null` for every other kind. */\n direction: CrmActivityDirection | null\n}\n\nexport interface AiAutomationAnswer {\n name: string\n trigger: {\n event: HostEventType\n conditions: AiAutomationCondition[]\n combinator: TriggerCombinator\n }\n steps: AiAutomationAnswerStep[]\n notes: string[]\n unsupported: AiAutomationUnsupported | null\n}\n\n/** The codes that say an answer could not be read as an automation at all. */\nexport const AI_AUTOMATION_UNREADABLE_CODES: readonly string[] = [\n 'automation-shape',\n 'automation-trigger',\n 'automation-step-type',\n]\n\n/** The codes that say an answer is larger than an automation may be. */\nexport const AI_AUTOMATION_OVERSIZE_CODES: readonly string[] = [\n 'automation-too-many-steps',\n 'automation-too-many-conditions',\n 'automation-too-long',\n]\n\n/** The address field a step reads when it names none. */\nconst DEFAULT_TO_FIELD = 'email'\nconst FIELD_NAME = /^[A-Za-z_][A-Za-z0-9_.-]{0,63}$/\nconst EMAIL_ADDRESS = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\nconst ROUND_ROBIN = /^\\s*round[\\s-]*robin\\s*$/i\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/** A string trimmed to one space between words, or `null` for none. */\nfunction textOf(value: unknown): string | null {\n if (typeof value !== 'string') return null\n const clean = value.replace(/[ \\t]+/g, ' ').trim()\n return clean ? clean : null\n}\n\n/** The fields a trigger's conditions and its steps' guards may read. */\nfunction fieldsFor(event: HostEventType): readonly string[] | null {\n // A form submission carries every field the form collects, which no fixed\n // list names, so any field name is readable on it.\n if (event === 'formSubmission') return null\n const keys = HOST_EVENT_PAYLOAD_KEYS[event]\n return keys?.length ? keys : null\n}\n\ninterface Reader {\n violations: AiDoctrineViolation[]\n offending: Array<[string, unknown]>\n}\n\nfunction refuse(\n reader: Reader,\n code: string,\n message: string,\n path: string,\n value: unknown,\n): void {\n reader.violations.push({ rule: null, code, message, paths: [path] })\n if (reader.offending.length < 6) reader.offending.push([path, value])\n}\n\nfunction readCondition(\n reader: Reader,\n raw: unknown,\n path: string,\n event: HostEventType,\n guard: boolean,\n): AiAutomationCondition | null {\n if (!isRecord(raw)) {\n refuse(reader, 'automation-shape', 'A condition is not an object with a field, an op and a value.', path, raw)\n return null\n }\n const field = textOf(raw['field'])\n const op = raw['op']\n if (!field || !FIELD_NAME.test(field)) {\n refuse(reader, 'automation-condition', 'Name the event field the condition reads.', path, raw)\n return null\n }\n if (!(TRIGGER_CONDITION_OPS as readonly unknown[]).includes(op)) {\n refuse(reader, 'automation-condition', `The condition on \"${field}\" needs equals, contains or notEmpty.`, path, raw)\n return null\n }\n if (event === 'formSubmission' && field === 'formId') {\n refuse(\n reader,\n 'automation-condition',\n 'A form submission names its form by formName, the form’s name as the site lists it.',\n path,\n raw,\n )\n return null\n }\n // A step's guard may also read whether the wait before it ran out of time.\n const readable = fieldsFor(event)\n if (readable && !readable.includes(field) && !(guard && field === AI_AUTOMATION_TIMED_OUT_FIELD)) {\n refuse(\n reader,\n 'automation-condition',\n `The trigger \"${aiAutomationTriggerLabel(event)}\" does not carry \"${field}\". It carries: ${readable.join(', ')}.`,\n path,\n raw,\n )\n return null\n }\n const value = textOf(raw['value'])\n if (op !== 'notEmpty' && !value) {\n refuse(reader, 'automation-condition', `The condition on \"${field}\" needs the value it compares against.`, path, raw)\n return null\n }\n if (value && value.length > AI_AUTOMATION_VALUE_MAX_CHARS) {\n refuse(reader, 'automation-too-long', `The value the condition on \"${field}\" compares against is too long.`, path, raw)\n return null\n }\n if (field === 'lifecycleStage' || field === 'previousStage') {\n const stage = value ? lifecycleStageOf(value) : null\n if (op !== 'notEmpty' && !stage) {\n refuse(\n reader,\n 'automation-condition',\n `A lifecycle stage is one of: ${CONTACT_LIFECYCLE_STAGES.join(', ')}.`,\n path,\n raw,\n )\n return null\n }\n return { field, op: op as TriggerConditionOp, value: op === 'notEmpty' ? null : stage }\n }\n return { field, op: op as TriggerConditionOp, value: op === 'notEmpty' ? null : value }\n}\n\n/** A lifecycle stage by its id or its label, case aside. */\nexport function lifecycleStageOf(value: string): ContactLifecycleStage | null {\n const wanted = value.trim().toLowerCase()\n return (\n CONTACT_LIFECYCLE_STAGES.find(\n (stage) => stage === wanted || CONTACT_LIFECYCLE_STAGE_LABELS[stage].toLowerCase() === wanted,\n ) ?? null\n )\n}\n\nfunction requireText(\n reader: Reader,\n step: Record<string, unknown>,\n key: string,\n max: number,\n path: string,\n what: string,\n): string | null {\n const value = textOf(step[key])\n if (!value) {\n refuse(reader, 'automation-step-field', `${what} needs ${key}.`, path, step)\n return null\n }\n if (value.length > max) {\n refuse(reader, 'automation-too-long', `${what}: ${key} is longer than ${max} characters.`, path, step)\n return null\n }\n if (HOSTILE_TEXT.test(value)) {\n refuse(reader, 'automation-markup', `${what}: write ${key} as plain text, with no HTML or script.`, path, step)\n return null\n }\n return value\n}\n\nfunction wholeNumber(value: unknown): number | null {\n return typeof value === 'number' && Number.isInteger(value) ? value : null\n}\n\nfunction readStep(\n reader: Reader,\n raw: unknown,\n index: number,\n event: HostEventType,\n capabilities: AiAutomationCapabilities,\n): AiAutomationAnswerStep | null {\n const path = `steps[${index}]`\n if (!isRecord(raw)) {\n refuse(reader, 'automation-shape', `Step ${index + 1} is not an object.`, path, raw)\n return null\n }\n // A step is its guard and its action: `{ when, action }`. An answer that\n // writes the action's own fields beside `when` reads the same, so a model\n // that flattens the step does not spend the one re-ask.\n const action = raw['action']\n const fields: Record<string, unknown> = isRecord(action) ? { ...action, when: raw['when'] } : raw\n const type = fields['type']\n if (!(AI_AUTOMATION_STEP_TYPES as readonly unknown[]).includes(type)) {\n refuse(\n reader,\n 'automation-step-type',\n `Step ${index + 1} is not one of the steps offered: ${AI_AUTOMATION_STEP_TYPES.join(', ')}.`,\n path,\n fields,\n )\n return null\n }\n const stepType = type as AiAutomationStepType\n const what = `Step ${index + 1} (${aiStepLabel(stepType)})`\n const need = AI_AUTOMATION_STEP_NEEDS[stepType]\n if (need && !capabilities[need]) {\n refuse(\n reader,\n 'automation-plan',\n `${what} needs ${AI_AUTOMATION_NEED_LABELS[need]}, which this workspace does not have. Leave it out, or answer with unsupported \"needs-${need}\".`,\n path,\n fields,\n )\n return null\n }\n const before = reader.violations.length\n const step: AiAutomationAnswerStep = {\n type: stepType,\n when: null,\n list: null,\n campaign: null,\n workflow: null,\n webhook: null,\n dataset: null,\n subject: null,\n body: null,\n toField: null,\n title: null,\n message: null,\n severity: null,\n minutes: null,\n event: null,\n stage: null,\n tag: null,\n owner: null,\n taskKind: null,\n priority: null,\n dueInDays: null,\n activityKind: null,\n direction: null,\n }\n // A step's `when` is a list of at most one condition; a lone condition, or\n // none, reads as the list it stands for.\n const when = fields['when']\n const guards = Array.isArray(when) ? when : when === null || when === undefined ? [] : [when]\n if (guards.length > 1) {\n refuse(reader, 'automation-condition', `${what}: when holds one condition at most.`, `${path}.when`, when)\n } else if (guards.length === 1) {\n step.when = readCondition(reader, guards[0], `${path}.when`, event, true)\n }\n // The six steps that name a record share `reference`, and the three that\n // carry one line share `text`; an answer that writes the step's own key\n // instead — `list`, `tag`, `owner` — reads the same.\n const shared = (key: 'reference' | 'text', own: keyof AiAutomationAnswerStep): unknown =>\n fields[key] ?? fields[own]\n const own = TEXT_KEY[stepType as keyof typeof TEXT_KEY]\n const text: Record<string, unknown> = own ? { text: shared('text', own) } : fields\n switch (stepType) {\n case 'sendEmail': {\n step.subject = requireText(reader, fields, 'subject', AI_AUTOMATION_SUBJECT_MAX_CHARS, path, what)\n step.body = requireText(reader, fields, 'body', AI_AUTOMATION_BODY_MAX_CHARS, path, what)\n const toField = textOf(fields['toField'])\n if (toField && !FIELD_NAME.test(toField)) {\n refuse(reader, 'automation-step-field', `${what}: toField names the event field holding the address.`, path, fields)\n } else {\n step.toField = toField && toField !== DEFAULT_TO_FIELD ? toField : null\n }\n break\n }\n case 'notifyAdmins':\n step.title = requireText(reader, text, 'text', AI_AUTOMATION_SUBJECT_MAX_CHARS, path, what)\n break\n case 'enrollList':\n case 'assignCampaign':\n case 'runWorkflow':\n case 'webhookPost':\n case 'datasetAppend':\n case 'updateDataset':\n step[REFERENCE_KEY[stepType]] = requireText(\n reader,\n { reference: shared('reference', REFERENCE_KEY[stepType]) },\n 'reference',\n AI_AUTOMATION_REFERENCE_MAX_CHARS,\n path,\n what,\n )\n break\n case 'siteAlert': {\n step.message = requireText(reader, text, 'text', AI_AUTOMATION_TEXT_MAX_CHARS, path, what)\n const severity = fields['severity']\n step.severity = (SEVERITIES as readonly unknown[]).includes(severity) ? (severity as Severity) : 'info'\n break\n }\n case 'wait':\n case 'waitForEvent': {\n const minutes = wholeNumber(fields['minutes'])\n if (minutes === null || minutes < AI_AUTOMATION_WAIT_MINUTES.min || minutes > AI_AUTOMATION_WAIT_MINUTES.max) {\n refuse(\n reader,\n 'automation-step-field',\n `${what} needs minutes, a whole number from ${AI_AUTOMATION_WAIT_MINUTES.min} to ${AI_AUTOMATION_WAIT_MINUTES.max}.`,\n path,\n fields,\n )\n } else {\n step.minutes = minutes\n }\n if (stepType === 'waitForEvent') {\n const waited = fields['event']\n if (!(HOST_EVENT_TYPES as readonly unknown[]).includes(waited)) {\n refuse(\n reader,\n 'automation-step-field',\n `${what} needs the event it waits for, one of: ${WAITABLE_EVENTS}.`,\n path,\n fields,\n )\n } else {\n step.event = waited as HostEventType\n }\n }\n break\n }\n case 'exitFlow':\n break\n case 'setContactStage': {\n const stage = fields['stage']\n if (!(CONTACT_LIFECYCLE_STAGES as readonly unknown[]).includes(stage)) {\n refuse(reader, 'automation-step-field', `${what} needs the lifecycle stage to set.`, path, fields)\n } else {\n step.stage = stage as ContactLifecycleStage\n }\n break\n }\n case 'addContactTag':\n step.tag = requireText(reader, text, 'text', CONTACT_TAG_MAX_LENGTH, path, what)\n break\n case 'assignContactOwner': {\n const owner = textOf(text['text'])\n if (!owner || !(ROUND_ROBIN.test(owner) || EMAIL_ADDRESS.test(owner))) {\n refuse(\n reader,\n 'automation-owner',\n `${what}: give the owner as \"round robin\", or as the teammate’s email address the description gives. A teammate named without one goes in notes, not in a step.`,\n path,\n fields,\n )\n } else {\n step.owner = ROUND_ROBIN.test(owner) ? 'round robin' : owner\n }\n break\n }\n case 'createCrmTask': {\n step.title = requireText(reader, text, 'text', AI_AUTOMATION_SUBJECT_MAX_CHARS, path, what)\n const kind = fields['taskKind']\n const due = wholeNumber(fields['dueInDays'])\n if (!(CRM_TASK_KINDS as readonly unknown[]).includes(kind)) {\n refuse(reader, 'automation-step-field', `${what} needs taskKind.`, path, fields)\n } else {\n step.taskKind = kind as CrmTaskKind\n }\n // Absent reads as normal, which the runner writes when none is named.\n const priority = fields['priority']\n if (priority !== undefined && !(TASK_PRIORITIES as readonly unknown[]).includes(priority)) {\n refuse(reader, 'automation-step-field', `${what} needs priority: low, normal or high.`, path, fields)\n } else if (priority !== undefined) {\n step.priority = priority as CrmTaskPriority\n }\n if (due === null || due < 0 || due > CRM_TASK_MAX_DUE_DAYS) {\n refuse(reader, 'automation-step-field', `${what} needs dueInDays, from 0 to ${CRM_TASK_MAX_DUE_DAYS}.`, path, fields)\n } else {\n step.dueInDays = due\n }\n break\n }\n case 'logCrmActivity': {\n const kind = fields['activityKind']\n if (!(CRM_ACTIVITY_KINDS as readonly unknown[]).includes(kind)) {\n refuse(reader, 'automation-step-field', `${what} needs activityKind.`, path, fields)\n } else {\n step.activityKind = kind as CrmActivityKind\n /*\n * The direction is the kind's own: a call goes outbound, inbound or\n * internal, an email outbound or inbound, and every other kind\n * carries none (AGL-3538).\n */\n const allowed: readonly string[] = CRM_ACTIVITY_DIRECTIONS[kind as CrmActivityKind] ?? []\n // Absent reads as empty: no direction.\n const raw = fields['direction'] ?? ''\n const direction = typeof raw === 'string' ? raw : null\n if (direction === null || (direction ? !allowed.includes(direction) : false)) {\n refuse(\n reader,\n 'automation-step-field',\n allowed.length\n ? `${what} needs direction: ${allowed.join(', ')}, or empty.`\n : `${what} takes no direction: leave it empty for a ${String(kind)}.`,\n path,\n fields,\n )\n } else if (direction) {\n step.direction = direction as CrmActivityDirection\n }\n }\n step.body = requireText(reader, text, 'text', AI_AUTOMATION_TEXT_MAX_CHARS, path, what)\n break\n }\n }\n return reader.violations.length === before ? step : null\n}\n\n/**\n * The automation tool's answer read and held to the vocabulary and to what\n * this workspace can run — the check the doctrine's loop runs on each answer,\n * beside rule 13. `value` is the automation when nothing is refused.\n */\nexport function readAiAutomationAnswer(\n answer: Record<string, unknown>,\n capabilities: AiAutomationCapabilities,\n): AiGenerationCheckResult<AiAutomationAnswer> {\n const reader: Reader = { violations: [], offending: [] }\n const done = (value: AiAutomationAnswer | null): AiGenerationCheckResult<AiAutomationAnswer> => ({\n value: reader.violations.length ? null : value,\n violations: reader.violations,\n ...(reader.offending.length ? { offending: Object.fromEntries(reader.offending) } : {}),\n })\n const notes = (Array.isArray(answer['notes']) ? answer['notes'] : [])\n .map(textOf)\n .filter((note): note is string => note !== null && !HOSTILE_TEXT.test(note))\n .slice(0, AI_AUTOMATION_NOTES_MAX)\n .map((note) => note.slice(0, AI_AUTOMATION_NOTE_MAX_CHARS))\n const name = (textOf(answer['name']) ?? '').slice(0, AI_AUTOMATION_NAME_MAX_CHARS)\n const written = JSON.stringify(answer).length\n if (written > AI_AUTOMATION_ANSWER_MAX_CHARS) {\n refuse(\n reader,\n 'automation-too-long',\n `Written out, the automation is ${written} characters, over the ${AI_AUTOMATION_ANSWER_MAX_CHARS} it may be. Shorten its emails and messages, or use fewer steps.`,\n 'steps',\n written,\n )\n return done(null)\n }\n\n // An answer that builds an automation leaves `unsupported` empty, which the\n // schema states as an empty string rather than a `null`.\n const unsupported = answer['unsupported']\n if (unsupported !== null && unsupported !== undefined && unsupported !== '') {\n if (!(AI_AUTOMATION_UNSUPPORTED as readonly unknown[]).includes(unsupported)) {\n refuse(reader, 'automation-shape', 'unsupported is empty, or one of the reasons offered.', 'unsupported', unsupported)\n return done(null)\n }\n const need = AI_AUTOMATION_UNSUPPORTED_NEED[unsupported as AiAutomationUnsupported]\n if (need && capabilities[need]) {\n refuse(\n reader,\n 'automation-unsupported',\n `This workspace has ${AI_AUTOMATION_NEED_LABELS[need]}: build the automation with it.`,\n 'unsupported',\n unsupported,\n )\n return done(null)\n }\n return done({\n name,\n trigger: { event: HOST_EVENT_TYPES[0], conditions: [], combinator: 'and' },\n steps: [],\n notes,\n unsupported: unsupported as AiAutomationUnsupported,\n })\n }\n\n const trigger = answer['trigger']\n const steps = answer['steps']\n if (!isRecord(trigger) || !Array.isArray(steps)) {\n refuse(reader, 'automation-shape', 'The answer has no trigger and steps.', 'trigger', trigger)\n return done(null)\n }\n const event = trigger['event']\n if (!(HOST_EVENT_TYPES as readonly unknown[]).includes(event)) {\n refuse(reader, 'automation-trigger', 'The trigger is not one of the events offered.', 'trigger.event', event)\n return done(null)\n }\n const hostEvent = event as HostEventType\n const need = AI_AUTOMATION_TRIGGER_NEEDS[hostEvent]\n if (need && !capabilities[need]) {\n refuse(\n reader,\n 'automation-plan',\n `The trigger \"${aiAutomationTriggerLabel(hostEvent)}\" needs ${AI_AUTOMATION_NEED_LABELS[need]}, which this workspace does not have. Pick another trigger, or answer with unsupported \"needs-${need}\".`,\n 'trigger.event',\n event,\n )\n return done(null)\n }\n const rawConditions = Array.isArray(trigger['conditions']) ? trigger['conditions'] : []\n if (rawConditions.length > ACTION_MAX_CONDITIONS) {\n refuse(\n reader,\n 'automation-too-many-conditions',\n `A trigger holds at most ${ACTION_MAX_CONDITIONS} conditions.`,\n 'trigger.conditions',\n rawConditions.length,\n )\n }\n const conditions = rawConditions\n .slice(0, ACTION_MAX_CONDITIONS)\n .map((raw, index) => readCondition(reader, raw, `trigger.conditions[${index}]`, hostEvent, false))\n .filter((condition): condition is AiAutomationCondition => condition !== null)\n const combinator = (TRIGGER_COMBINATORS as readonly unknown[]).includes(trigger['combinator'])\n ? (trigger['combinator'] as TriggerCombinator)\n : 'and'\n\n if (!steps.length) {\n refuse(reader, 'automation-shape', 'An automation has at least one step; answer unsupported when none fits.', 'steps', steps)\n }\n if (steps.length > ACTION_MAX_STEPS) {\n refuse(reader, 'automation-too-many-steps', `An automation holds at most ${ACTION_MAX_STEPS} steps.`, 'steps', steps.length)\n }\n const read = steps\n .slice(0, ACTION_MAX_STEPS)\n .map((raw, index) => readStep(reader, raw, index, hostEvent, capabilities))\n .filter((step): step is AiAutomationAnswerStep => step !== null)\n\n return done({\n name,\n trigger: { event: hostEvent, conditions, combinator },\n steps: read,\n notes,\n unsupported: null,\n })\n}\n\n// ── Reading an explanation ────────────────────────────────────────────────\n\nexport interface AiWorkflowExplanation {\n summary: string\n points: string[]\n suggestions: string[]\n}\n\n/** Whether a line carries an email address, which nothing an explanation was shown holds. */\nconst CARRIES_ADDRESS = /[^\\s@]+@[^\\s@]+\\.[^\\s@]+/\n\nfunction lines(value: unknown, max: number): string[] {\n return (Array.isArray(value) ? value : [])\n .map(textOf)\n .filter((line): line is string => line !== null)\n .slice(0, max)\n .map((line) => line.slice(0, AI_WORKFLOW_LINE_MAX_CHARS))\n}\n\n/**\n * The explanation tool's answer: a summary, and at most so many points and\n * suggestions, each cut to a line. Refused when it has no summary, or carries\n * markup or an address — plain words for a person, about a record whose\n * personal details were removed before the model saw it.\n */\nexport function readAiWorkflowExplanation(\n answer: Record<string, unknown>,\n): AiGenerationCheckResult<AiWorkflowExplanation> {\n const summary = (textOf(answer['summary']) ?? '').slice(0, AI_WORKFLOW_SUMMARY_MAX_CHARS)\n const value: AiWorkflowExplanation = {\n summary,\n points: lines(answer['points'], AI_WORKFLOW_POINTS_MAX),\n suggestions: lines(answer['suggestions'], AI_WORKFLOW_SUGGESTIONS_MAX),\n }\n const violations: AiDoctrineViolation[] = []\n if (!summary) {\n violations.push({ rule: null, code: 'explanation-shape', message: 'The explanation has no summary.' })\n }\n const all = [value.summary, ...value.points, ...value.suggestions]\n if (all.some((line) => HOSTILE_TEXT.test(line))) {\n violations.push({\n rule: null,\n code: 'explanation-markup',\n message: 'Write the explanation as plain text, with no HTML or script.',\n })\n }\n if (all.some((line) => CARRIES_ADDRESS.test(line))) {\n violations.push({\n rule: null,\n code: 'explanation-address',\n message: 'The explanation names an email address. Describe the person or the teammate instead.',\n })\n }\n return { value: violations.length ? null : value, violations }\n}\n"],"names":["ACTION_MAX_CONDITIONS","ACTION_MAX_STEPS","TRIGGER_COMBINATORS","TRIGGER_CONDITION_OPS","CONTACT_LIFECYCLE_STAGE_LABELS","CONTACT_LIFECYCLE_STAGES","CONTACT_TAG_MAX_LENGTH","CRM_ACTIVITY_DIRECTIONS","CRM_ACTIVITY_KINDS","CRM_TASK_KINDS","CRM_TASK_MAX_DUE_DAYS","HOST_EVENT_PAYLOAD_KEYS","HOST_EVENT_TYPES","AI_AUTOMATION_NEED_LABELS","AI_AUTOMATION_STEP_NEEDS","AI_AUTOMATION_STEP_TYPES","AI_AUTOMATION_TRIGGER_NEEDS","AI_AUTOMATION_UNSUPPORTED","AI_AUTOMATION_UNSUPPORTED_NEED","aiAutomationTriggerLabel","AI_AUTOMATION_TIMED_OUT_FIELD","AI_AUTOMATION_WAIT_MINUTES","aiStepLabel","HOSTILE_TEXT","AI_AUTOMATION_TOOL_NAME","AI_WORKFLOW_EXPLANATION_TOOL_NAME","AI_AUTOMATION_NAME_MAX_CHARS","AI_AUTOMATION_SUBJECT_MAX_CHARS","AI_AUTOMATION_BODY_MAX_CHARS","AI_AUTOMATION_TEXT_MAX_CHARS","AI_AUTOMATION_REFERENCE_MAX_CHARS","AI_AUTOMATION_VALUE_MAX_CHARS","AI_AUTOMATION_NOTES_MAX","AI_AUTOMATION_NOTE_MAX_CHARS","AI_AUTOMATION_ANSWER_MAX_CHARS","AI_WORKFLOW_SUMMARY_MAX_CHARS","AI_WORKFLOW_POINTS_MAX","AI_WORKFLOW_SUGGESTIONS_MAX","AI_WORKFLOW_LINE_MAX_CHARS","SEVERITIES","TASK_PRIORITIES","ACTIVITY_DIRECTIONS","Set","Object","values","flatMap","directions","WAITABLE_EVENTS","join","DEFINITIONS","condition","type","additionalProperties","required","properties","field","description","op","enum","value","event","when","items","$ref","REFERENCE_STEPS","TEXT_STEPS","REFERENCE_KEY","enrollList","assignCampaign","runWorkflow","datasetAppend","updateDataset","webhookPost","TEXT_KEY","notifyAdmins","addContactTag","assignContactOwner","siteAlert","createCrmTask","logCrmActivity","minutes","what","min","max","stepVariant","types","fields","keys","AI_AUTOMATION_STEP_VARIANTS","reference","text","subject","body","toField","severity","stage","taskKind","priority","dueInDays","activityKind","direction","aiAutomationTool","name","strict","inputSchema","trigger","conditions","combinator","steps","action","anyOf","notes","unsupported","$defs","aiWorkflowExplanationTool","summary","points","suggestions","AI_AUTOMATION_UNREADABLE_CODES","AI_AUTOMATION_OVERSIZE_CODES","DEFAULT_TO_FIELD","FIELD_NAME","EMAIL_ADDRESS","ROUND_ROBIN","isRecord","Array","isArray","textOf","clean","replace","trim","fieldsFor","length","refuse","reader","code","message","path","violations","push","rule","paths","offending","readCondition","raw","guard","test","includes","readable","lifecycleStageOf","wanted","toLowerCase","find","requireText","step","key","wholeNumber","Number","isInteger","readStep","index","capabilities","stepType","need","before","list","campaign","workflow","webhook","dataset","title","tag","owner","guards","undefined","shared","own","waited","kind","due","allowed","String","readAiAutomationAnswer","answer","done","fromEntries","map","filter","note","slice","written","JSON","stringify","hostEvent","rawConditions","read","CARRIES_ADDRESS","lines","line","readAiWorkflowExplanation","all","some"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,qBAAqB,EACrBC,gBAAgB,EAChBC,mBAAmB,EACnBC,qBAAqB,QAGhB,2CAA0C;AACjD,SACEC,8BAA8B,EAC9BC,wBAAwB,EACxBC,sBAAsB,EACtBC,uBAAuB,EACvBC,kBAAkB,EAClBC,cAAc,EACdC,qBAAqB,QAMhB,6BAA4B;AACnC,SACEC,uBAAuB,EACvBC,gBAAgB,QAEX,qCAAoC;AAC3C,SACEC,yBAAyB,EACzBC,wBAAwB,EACxBC,wBAAwB,EACxBC,2BAA2B,EAC3BC,yBAAyB,EACzBC,8BAA8B,EAC9BC,wBAAwB,QAInB,8BAA0B;AACjC,SACEC,6BAA6B,EAC7BC,0BAA0B,EAC1BC,WAAW,QACN,mCAA+B;AAItC,SAASC,YAAY,QAAQ,6BAAyB;AAEtD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6CC,GAED,OAAO,MAAMC,0BAA0B,oBAAmB;AAC1D,OAAO,MAAMC,oCAAoC,qBAAoB;AAErE,2DAA2D,GAC3D,OAA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;QACnCwD;QACAC,QAAQiF,MAAMd,MAAM,CAAC,SAAS,EAAEnJ;QAChCiF,aAAagF,MAAMd,MAAM,CAAC,cAAc,EAAElJ;IAC5C;IACA,MAAMqG,aAAoC,EAAE;IAC5C,IAAI,CAACvB,SAAS;QACZuB,WAAWC,IAAI,CAAC;YAAEC,MAAM;YAAML,MAAM;YAAqBC,SAAS;QAAkC;IACtG;IACA,MAAMgE,MAAM;QAAC7I,MAAMwD,OAAO;WAAKxD,MAAMyD,MAAM;WAAKzD,MAAM0D,WAAW;KAAC;IAClE,IAAImF,IAAIC,IAAI,CAAC,CAACH,OAAS/K,aAAa2H,IAAI,CAACoD,QAAQ;QAC/C5D,WAAWC,IAAI,CAAC;YACdC,MAAM;YACNL,MAAM;YACNC,SAAS;QACX;IACF;IACA,IAAIgE,IAAIC,IAAI,CAAC,CAACH,OAASF,gBAAgBlD,IAAI,CAACoD,QAAQ;QAClD5D,WAAWC,IAAI,CAAC;YACdC,MAAM;YACNL,MAAM;YACNC,SAAS;QACX;IACF;IACA,OAAO;QAAE7E,OAAO+E,WAAWN,MAAM,GAAG,OAAOzE;QAAO+E;IAAW;AAC/D"}
@@ -79,7 +79,20 @@ export function aiUsageAxes() {
79
79
  'assistCostUsd'
80
80
  ],
81
81
  entitlement: 'assistCreditsPerMonth',
82
- unitCostUsd: ASSIST_CREDIT_COST_USD
82
+ unitCostUsd: ASSIST_CREDIT_COST_USD,
83
+ // The console's quota banner (AGL-2898): the credits route answers the
84
+ // standing in credits and whether the band stops or bills past, by
85
+ // the reservation's own predicate (`assistBandRefuses`).
86
+ consoleWarning: {
87
+ standing: '/api/ai/billing/credits',
88
+ member: 'credits',
89
+ approach: "You're above 80% of your included AI assist credits.",
90
+ reached: {
91
+ stops: "You've used your included AI assist credits — AI assist stops " + 'until next month or an upgrade, and nothing is billed for it.',
92
+ bills: "You've used your included AI assist credits — extra credits are " + 'billed at your plan’s rate unless you set a stop under ' + 'Billing → Usage.'
93
+ },
94
+ linksUsage: true
95
+ }
83
96
  }
84
97
  ],
85
98
  meters: [
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../libs/plugins/ai/src/lib/usage-axes.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 { PluginUsageAxesDeclaration } from '@aglyn/aglyn/plugin-manager/plugin-usage-axes'\nimport { AI_USAGE_METER_ID } from './constants'\nimport {\n ASSIST_CREDIT_COST_USD,\n ASSIST_PROVIDER_COST_FIELD,\n} from './usage/assist-credits'\n\n/**\n * THE AI PLUGIN'S METER (AGL-3080): provider spend, in the platform's cost\n * model and against the credit band in its utilization table. Compiled into\n * core by the manifest generator (`register.usageAxes`).\n *\n * The rollup records `assistCostUsd` — what the month's tokens cost US, at\n * the provider's rates (AGL-3015) — so the axis enters the cost model at ×1\n * and names no rate. It is the one line on the platform whose unit cost is\n * real money paid to a third party, and the only one that can clear the\n * $2/site floor on its own, which is why a margin surface that could not see\n * it would rate a token-heavy workspace exactly as it rates an idle one.\n *\n * LIVE, because the rollup is a snapshot from when the cron ran and assist\n * keeps spending after it: a reader that fetches the month's\n * `assistUsage/{month}` document takes the provider figure, or the billed\n * one on a month closed before the two were split, over the snapshot.\n *\n * The band is sold in credits, and a credit is `ASSIST_CREDIT_COST_USD` of\n * spend, so what was used is the dollars over that — rounded up, the one\n * conversion the customer's own meter uses.\n *\n * On the usage BUDGET the month's spend is the billed figure (`estCostUsd`),\n * shown to the customer in credits and never in dollars: the dollars are our\n * cost, and publishing them would put our model choice and our margin on a\n * billing page. It counts toward the budget only from the month\n * `BILL_ASSIST_TOKENS_FROM` names, because assist is a plan entitlement with\n * no per-token price until then, and a budget that added it would be a\n * surprise bill invented by a notification.\n */\n/** The AI plugin's line of a workspace's monthly spend, by the id it declares. */\nexport const AI_ASSIST_SPEND_LINE_ID = 'assist'\n\nexport function aiUsageAxes(): PluginUsageAxesDeclaration {\n return {\n costAxes: [\n {\n id: 'assist',\n order: 80,\n fields: ['assistCostUsd'],\n // The month's credit draw and the overage that entered `billedCents`\n // (AGL-2930), which the usage sweep writes beside the spend: the\n // staff usage table's AI columns, `null` on a rollup written before\n // the sweep recorded credits, and never a cost.\n staffFields: ['assistCredits', 'assistOverageUsd'],\n live: {\n collection: 'assistUsage',\n fields: [ASSIST_PROVIDER_COST_FIELD, 'estCostUsd'],\n },\n },\n ],\n bands: [\n {\n id: 'assistCredits',\n label: 'Assist credits',\n order: 90,\n fields: ['assistCostUsd'],\n entitlement: 'assistCreditsPerMonth',\n unitCostUsd: ASSIST_CREDIT_COST_USD,\n },\n ],\n meters: [{ id: AI_USAGE_METER_ID }],\n spendLines: [\n {\n id: AI_ASSIST_SPEND_LINE_ID,\n label: 'Assist',\n live: { collection: 'assistUsage', field: 'estCostUsd' },\n billedFromEnv: 'BILL_ASSIST_TOKENS_FROM',\n unit: { costUsd: ASSIST_CREDIT_COST_USD, label: 'Assist credits' },\n },\n ],\n }\n}\n"],"names":["AI_USAGE_METER_ID","ASSIST_CREDIT_COST_USD","ASSIST_PROVIDER_COST_FIELD","AI_ASSIST_SPEND_LINE_ID","aiUsageAxes","costAxes","id","order","fields","staffFields","live","collection","bands","label","entitlement","unitCostUsd","meters","spendLines","field","billedFromEnv","unit","costUsd"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAGD,SAASA,iBAAiB,QAAQ,iBAAa;AAC/C,SACEC,sBAAsB,EACtBC,0BAA0B,QACrB,4BAAwB;AAE/B;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA4BC,GACD,gFAAgF,GAChF,OAAO,MAAMC,0BAA0B,SAAQ;AAE/C,OAAO,SAASC;IACd,OAAO;QACLC,UAAU;YACR;gBACEC,IAAI;gBACJC,OAAO;gBACPC,QAAQ;oBAAC;iBAAgB;gBACzB,qEAAqE;gBACrE,iEAAiE;gBACjE,oEAAoE;gBACpE,gDAAgD;gBAChDC,aAAa;oBAAC;oBAAiB;iBAAmB;gBAClDC,MAAM;oBACJC,YAAY;oBACZH,QAAQ;wBAACN;wBAA4B;qBAAa;gBACpD;YACF;SACD;QACDU,OAAO;YACL;gBACEN,IAAI;gBACJO,OAAO;gBACPN,OAAO;gBACPC,QAAQ;oBAAC;iBAAgB;gBACzBM,aAAa;gBACbC,aAAad;YACf;SACD;QACDe,QAAQ;YAAC;gBAAEV,IAAIN;YAAkB;SAAE;QACnCiB,YAAY;YACV;gBACEX,IAAIH;gBACJU,OAAO;gBACPH,MAAM;oBAAEC,YAAY;oBAAeO,OAAO;gBAAa;gBACvDC,eAAe;gBACfC,MAAM;oBAAEC,SAASpB;oBAAwBY,OAAO;gBAAiB;YACnE;SACD;IACH;AACF"}
1
+ {"version":3,"sources":["../../../../../../libs/plugins/ai/src/lib/usage-axes.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 { PluginUsageAxesDeclaration } from '@aglyn/aglyn/plugin-manager/plugin-usage-axes'\nimport { AI_USAGE_METER_ID } from './constants'\nimport {\n ASSIST_CREDIT_COST_USD,\n ASSIST_PROVIDER_COST_FIELD,\n} from './usage/assist-credits'\n\n/**\n * THE AI PLUGIN'S METER (AGL-3080): provider spend, in the platform's cost\n * model and against the credit band in its utilization table. Compiled into\n * core by the manifest generator (`register.usageAxes`).\n *\n * The rollup records `assistCostUsd` — what the month's tokens cost US, at\n * the provider's rates (AGL-3015) — so the axis enters the cost model at ×1\n * and names no rate. It is the one line on the platform whose unit cost is\n * real money paid to a third party, and the only one that can clear the\n * $2/site floor on its own, which is why a margin surface that could not see\n * it would rate a token-heavy workspace exactly as it rates an idle one.\n *\n * LIVE, because the rollup is a snapshot from when the cron ran and assist\n * keeps spending after it: a reader that fetches the month's\n * `assistUsage/{month}` document takes the provider figure, or the billed\n * one on a month closed before the two were split, over the snapshot.\n *\n * The band is sold in credits, and a credit is `ASSIST_CREDIT_COST_USD` of\n * spend, so what was used is the dollars over that — rounded up, the one\n * conversion the customer's own meter uses.\n *\n * On the usage BUDGET the month's spend is the billed figure (`estCostUsd`),\n * shown to the customer in credits and never in dollars: the dollars are our\n * cost, and publishing them would put our model choice and our margin on a\n * billing page. It counts toward the budget only from the month\n * `BILL_ASSIST_TOKENS_FROM` names, because assist is a plan entitlement with\n * no per-token price until then, and a budget that added it would be a\n * surprise bill invented by a notification.\n */\n/** The AI plugin's line of a workspace's monthly spend, by the id it declares. */\nexport const AI_ASSIST_SPEND_LINE_ID = 'assist'\n\nexport function aiUsageAxes(): PluginUsageAxesDeclaration {\n return {\n costAxes: [\n {\n id: 'assist',\n order: 80,\n fields: ['assistCostUsd'],\n // The month's credit draw and the overage that entered `billedCents`\n // (AGL-2930), which the usage sweep writes beside the spend: the\n // staff usage table's AI columns, `null` on a rollup written before\n // the sweep recorded credits, and never a cost.\n staffFields: ['assistCredits', 'assistOverageUsd'],\n live: {\n collection: 'assistUsage',\n fields: [ASSIST_PROVIDER_COST_FIELD, 'estCostUsd'],\n },\n },\n ],\n bands: [\n {\n id: 'assistCredits',\n label: 'Assist credits',\n order: 90,\n fields: ['assistCostUsd'],\n entitlement: 'assistCreditsPerMonth',\n unitCostUsd: ASSIST_CREDIT_COST_USD,\n // The console's quota banner (AGL-2898): the credits route answers the\n // standing in credits and whether the band stops or bills past, by\n // the reservation's own predicate (`assistBandRefuses`).\n consoleWarning: {\n standing: '/api/ai/billing/credits',\n member: 'credits',\n approach: \"You're above 80% of your included AI assist credits.\",\n reached: {\n stops:\n \"You've used your included AI assist credits — AI assist stops \" +\n 'until next month or an upgrade, and nothing is billed for it.',\n bills:\n \"You've used your included AI assist credits — extra credits are \" +\n 'billed at your plan’s rate unless you set a stop under ' +\n 'Billing → Usage.',\n },\n linksUsage: true,\n },\n },\n ],\n meters: [{ id: AI_USAGE_METER_ID }],\n spendLines: [\n {\n id: AI_ASSIST_SPEND_LINE_ID,\n label: 'Assist',\n live: { collection: 'assistUsage', field: 'estCostUsd' },\n billedFromEnv: 'BILL_ASSIST_TOKENS_FROM',\n unit: { costUsd: ASSIST_CREDIT_COST_USD, label: 'Assist credits' },\n },\n ],\n }\n}\n"],"names":["AI_USAGE_METER_ID","ASSIST_CREDIT_COST_USD","ASSIST_PROVIDER_COST_FIELD","AI_ASSIST_SPEND_LINE_ID","aiUsageAxes","costAxes","id","order","fields","staffFields","live","collection","bands","label","entitlement","unitCostUsd","consoleWarning","standing","member","approach","reached","stops","bills","linksUsage","meters","spendLines","field","billedFromEnv","unit","costUsd"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAGD,SAASA,iBAAiB,QAAQ,iBAAa;AAC/C,SACEC,sBAAsB,EACtBC,0BAA0B,QACrB,4BAAwB;AAE/B;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA4BC,GACD,gFAAgF,GAChF,OAAO,MAAMC,0BAA0B,SAAQ;AAE/C,OAAO,SAASC;IACd,OAAO;QACLC,UAAU;YACR;gBACEC,IAAI;gBACJC,OAAO;gBACPC,QAAQ;oBAAC;iBAAgB;gBACzB,qEAAqE;gBACrE,iEAAiE;gBACjE,oEAAoE;gBACpE,gDAAgD;gBAChDC,aAAa;oBAAC;oBAAiB;iBAAmB;gBAClDC,MAAM;oBACJC,YAAY;oBACZH,QAAQ;wBAACN;wBAA4B;qBAAa;gBACpD;YACF;SACD;QACDU,OAAO;YACL;gBACEN,IAAI;gBACJO,OAAO;gBACPN,OAAO;gBACPC,QAAQ;oBAAC;iBAAgB;gBACzBM,aAAa;gBACbC,aAAad;gBACb,uEAAuE;gBACvE,mEAAmE;gBACnE,yDAAyD;gBACzDe,gBAAgB;oBACdC,UAAU;oBACVC,QAAQ;oBACRC,UAAU;oBACVC,SAAS;wBACPC,OACE,mEACA;wBACFC,OACE,qEACA,4DACA;oBACJ;oBACAC,YAAY;gBACd;YACF;SACD;QACDC,QAAQ;YAAC;gBAAElB,IAAIN;YAAkB;SAAE;QACnCyB,YAAY;YACV;gBACEnB,IAAIH;gBACJU,OAAO;gBACPH,MAAM;oBAAEC,YAAY;oBAAee,OAAO;gBAAa;gBACvDC,eAAe;gBACfC,MAAM;oBAAEC,SAAS5B;oBAAwBY,OAAO;gBAAiB;YACnE;SACD;IACH;AACF"}