@aglyn/plugins-outreach 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 (116) hide show
  1. package/package.json +14 -14
  2. package/src/lib/components/do-not-contact-domains.d.ts +6 -2
  3. package/src/lib/components/do-not-contact-domains.js +73 -11
  4. package/src/lib/components/do-not-contact-domains.js.map +1 -1
  5. package/src/lib/components/enrollments-table.d.ts +6 -0
  6. package/src/lib/components/enrollments-table.js +77 -4
  7. package/src/lib/components/enrollments-table.js.map +1 -1
  8. package/src/lib/components/sequence-detail.js +3 -1
  9. package/src/lib/components/sequence-detail.js.map +1 -1
  10. package/src/lib/components/sequence-report-card.js +7 -3
  11. package/src/lib/components/sequence-report-card.js.map +1 -1
  12. package/src/lib/components/use-outreach-crm.d.ts +18 -15
  13. package/src/lib/components/use-outreach-crm.js +118 -87
  14. package/src/lib/components/use-outreach-crm.js.map +1 -1
  15. package/src/lib/components/use-outreach-data.d.ts +2 -2
  16. package/src/lib/components/use-outreach-data.js.map +1 -1
  17. package/src/lib/constants/transfer-resources.d.ts +33 -0
  18. package/src/lib/constants/transfer-resources.js +38 -0
  19. package/src/lib/constants/transfer-resources.js.map +1 -0
  20. package/src/lib/declarations.console-server.d.ts +7 -1
  21. package/src/lib/declarations.console-server.js +66 -1
  22. package/src/lib/declarations.console-server.js.map +1 -1
  23. package/src/lib/engine/click-tracking.js +1 -1
  24. package/src/lib/engine/click-tracking.js.map +1 -1
  25. package/src/lib/engine/ip-range.d.ts +26 -0
  26. package/src/lib/engine/ip-range.js +78 -0
  27. package/src/lib/engine/ip-range.js.map +1 -0
  28. package/src/lib/engine/open-source.d.ts +24 -0
  29. package/src/lib/engine/open-source.js +130 -0
  30. package/src/lib/engine/open-source.js.map +1 -0
  31. package/src/lib/engine/open-tracking.d.ts +15 -2
  32. package/src/lib/engine/open-tracking.js +59 -16
  33. package/src/lib/engine/open-tracking.js.map +1 -1
  34. package/src/lib/engine/outreach-access.d.ts +47 -0
  35. package/src/lib/engine/outreach-access.js +56 -0
  36. package/src/lib/engine/outreach-access.js.map +1 -0
  37. package/src/lib/enrollment/enroll-people.d.ts +10 -10
  38. package/src/lib/enrollment/enroll-people.js +30 -25
  39. package/src/lib/enrollment/enroll-people.js.map +1 -1
  40. package/src/lib/enrollment/gate-lookups.js +30 -15
  41. package/src/lib/enrollment/gate-lookups.js.map +1 -1
  42. package/src/lib/enrollment/message-templates.d.ts +24 -0
  43. package/src/lib/enrollment/message-templates.js +35 -0
  44. package/src/lib/enrollment/message-templates.js.map +1 -0
  45. package/src/lib/model/enrollment-engagement.d.ts +16 -0
  46. package/src/lib/model/enrollment-engagement.js +16 -0
  47. package/src/lib/model/enrollment-engagement.js.map +1 -1
  48. package/src/lib/model/enrollment-history.d.ts +8 -1
  49. package/src/lib/model/enrollment-history.js +17 -5
  50. package/src/lib/model/enrollment-history.js.map +1 -1
  51. package/src/lib/model/enrollment-timeline.d.ts +3 -0
  52. package/src/lib/model/enrollment-timeline.js +15 -4
  53. package/src/lib/model/enrollment-timeline.js.map +1 -1
  54. package/src/lib/model/outreach.types.d.ts +12 -3
  55. package/src/lib/model/outreach.types.js +12 -1
  56. package/src/lib/model/outreach.types.js.map +1 -1
  57. package/src/lib/model/sequence-report.d.ts +14 -7
  58. package/src/lib/model/sequence-report.js +12 -8
  59. package/src/lib/model/sequence-report.js.map +1 -1
  60. package/src/lib/plugin.js +18 -0
  61. package/src/lib/plugin.js.map +1 -1
  62. package/src/lib/routes/curate-routes.js +4 -6
  63. package/src/lib/routes/curate-routes.js.map +1 -1
  64. package/src/lib/routes/enroll-routes.d.ts +0 -12
  65. package/src/lib/routes/enroll-routes.js +52 -92
  66. package/src/lib/routes/enroll-routes.js.map +1 -1
  67. package/src/lib/routes/platform-deps.d.ts +4 -16
  68. package/src/lib/routes/platform-deps.js +5 -25
  69. package/src/lib/routes/platform-deps.js.map +1 -1
  70. package/src/lib/routes/preview-routes.js +25 -13
  71. package/src/lib/routes/preview-routes.js.map +1 -1
  72. package/src/lib/routes/register-routes.js +7 -5
  73. package/src/lib/routes/register-routes.js.map +1 -1
  74. package/src/lib/routes/route-gate.js +6 -17
  75. package/src/lib/routes/route-gate.js.map +1 -1
  76. package/src/lib/routes/sequence-routes.d.ts +46 -0
  77. package/src/lib/routes/sequence-routes.js +155 -63
  78. package/src/lib/routes/sequence-routes.js.map +1 -1
  79. package/src/lib/runtime/click-events.js +8 -8
  80. package/src/lib/runtime/click-events.js.map +1 -1
  81. package/src/lib/runtime/click-route.js +5 -2
  82. package/src/lib/runtime/click-route.js.map +1 -1
  83. package/src/lib/runtime/lead-records.d.ts +18 -10
  84. package/src/lib/runtime/lead-records.js +14 -60
  85. package/src/lib/runtime/lead-records.js.map +1 -1
  86. package/src/lib/runtime/open-events.d.ts +8 -0
  87. package/src/lib/runtime/open-events.js +10 -3
  88. package/src/lib/runtime/open-events.js.map +1 -1
  89. package/src/lib/runtime/platform-runtime-deps.d.ts +9 -5
  90. package/src/lib/runtime/platform-runtime-deps.js +31 -24
  91. package/src/lib/runtime/platform-runtime-deps.js.map +1 -1
  92. package/src/lib/runtime/send-job.js +20 -17
  93. package/src/lib/runtime/send-job.js.map +1 -1
  94. package/src/lib/runtime/sync-job.js +10 -5
  95. package/src/lib/runtime/sync-job.js.map +1 -1
  96. package/src/lib/storage/do-not-contact-store.d.ts +8 -0
  97. package/src/lib/storage/do-not-contact-store.js +13 -0
  98. package/src/lib/storage/do-not-contact-store.js.map +1 -1
  99. package/src/lib/testing/stand-in-record-system.d.ts +54 -0
  100. package/src/lib/testing/stand-in-record-system.js +243 -0
  101. package/src/lib/testing/stand-in-record-system.js.map +1 -0
  102. package/src/lib/transfer/do-not-contact-transfer.d.ts +129 -0
  103. package/src/lib/transfer/do-not-contact-transfer.js +801 -0
  104. package/src/lib/transfer/do-not-contact-transfer.js.map +1 -0
  105. package/src/lib/transfer/plan-gate.d.ts +25 -0
  106. package/src/lib/transfer/plan-gate.js +35 -0
  107. package/src/lib/transfer/plan-gate.js.map +1 -0
  108. package/src/lib/transfer/platform-transfer-deps.d.ts +24 -0
  109. package/src/lib/transfer/platform-transfer-deps.js +39 -0
  110. package/src/lib/transfer/platform-transfer-deps.js.map +1 -0
  111. package/src/lib/transfer/sequences-package.d.ts +48 -0
  112. package/src/lib/transfer/sequences-package.js +93 -0
  113. package/src/lib/transfer/sequences-package.js.map +1 -0
  114. package/src/lib/transfer/sequences-package.server.d.ts +31 -0
  115. package/src/lib/transfer/sequences-package.server.js +207 -0
  116. package/src/lib/transfer/sequences-package.server.js.map +1 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/outreach/src/lib/runtime/send-job.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 { consentGroupForHost } from '@aglyn/aglyn/app-utils/consent-groups'\nimport { CRM_COLLECTIONS } from '@aglyn/aglyn/app-utils/crm'\nimport { normalizeCrmEmailTemplate } from '@aglyn/aglyn/app-utils/crm-email-templates'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { randomUUID } from 'node:crypto'\nimport { composeOutreachEmail } from '../engine/compose'\nimport { outreachEmailDomain } from '../engine/do-not-contact-domain'\nimport { planOutreachStepCompletion, type OutreachEnrollmentEvent } from '../engine/enrollment-state'\nimport { evaluateOutreachGates, type OutreachGateBlock, type OutreachGateLookups } from '../engine/gates'\nimport {\n outreachSentToday,\n outreachTickAllowance,\n selectDueOutreachEnrollments,\n type OutreachDueCandidate,\n} from '../engine/sending-capacity'\nimport { readOutreachEnrollCandidates, type OutreachEnrollCandidate } from '../enrollment/enroll-people'\nimport { readOutreachGateLookups } from '../enrollment/gate-lookups'\nimport { mailboxRef } from '../mailboxes/mailbox-credentials'\nimport { outreachEffectiveDailyCap, outreachLocalDay } from '../mailboxes/mailbox-settings'\nimport type { OpenedOutreachMailbox } from '../mailboxes/mailbox-transport'\nimport { effectiveOutreachAllowedCountries } from '../model/compliance-settings'\nimport {\n OUTREACH_COLLECTIONS,\n type OutreachComplianceSettingsDocument,\n type OutreachEnrollment,\n type OutreachMailbox,\n type OutreachSequence,\n type OutreachStepRecord,\n type OutreachTaskStep,\n} from '../model/outreach.types'\nimport { readOutreachComplianceSettingsDoc } from '../storage/compliance-settings-store'\nimport { outreachMailboxSendingDomain, recordOutreachGatewayOutcome } from '../storage/domain-intel-store'\nimport {\n outreachEnrollmentLink,\n outreachEnrollmentPerson,\n outreachOrgCollection,\n readStoredOutreachEnrollment,\n readStoredOutreachMailbox,\n readStoredOutreachSequence,\n} from '../storage/outreach-records'\nimport { GmailTransportError, isReconnectRequired } from '../transport/gmail-errors'\nimport { Rfc5322MessageError } from '../transport/rfc5322'\nimport { sendComposedOutreachEmail } from '../transport/send-message'\nimport { creditOutreachFirstSend } from './campaign-credit'\nimport {\n newOutreachLinkId,\n outreachStoredLink,\n outreachStoredOpen,\n type OutreachStoredLink,\n type OutreachStoredOpen,\n} from './click-link'\nimport { applyOutreachEvent } from './enrollment-events'\nimport { outreachSiteHeld } from './host-suspension'\nimport { markOutreachLeadNurturing } from './lead-records'\nimport { outreachSendDigest, withRecentSend } from './mailbox-health-store'\nimport { noteOutreachMailboxReconnectRequired } from './mailbox-notices'\nimport type { OutreachRuntimeDeps } from './runtime-deps'\nimport { fileOutreachEmail, fileOutreachTask, OUTREACH_TASK_KIND_TO_RECORD } from './timeline'\nimport { outreachListUnsubscribe } from './unsubscribe-link'\n\n/*==========================================\n * THE SEND JOB (AGL-2981): every fifteen minutes, on the console.\n *\n * ## What comes due\n *\n * One collection-group read finds every active enrollment whose next step\n * is due, oldest first, bounded per run. They are grouped by workspace and\n * mailbox, and each group is judged before anything is sent:\n *\n * - the workspace: Outreach switched on, entitled and released to it;\n * - the mailbox: an enrollment whose mailbox is gone, disconnected, or whose\n * member left the organization is STOPPED — nothing will ever send it, and\n * leaving it active would show a sequence that is not running. A paused\n * mailbox, or one waiting to be reconnected, holds its enrollments;\n * - the member it sends as: a lockdown of the platform, the workspace or the\n * member holds everything.\n *\n * ## How much goes\n *\n * The engine's per-run allowance — the day's cap and ramp, spread across\n * the window, at most five a run — picks the enrollments (follow-ups first);\n * a task step is due whenever its time comes and spends no allowance.\n *\n * ## One send, exactly once\n *\n * Each email is CLAIMED before it is sent: a transaction over the enrollment\n * and its mailbox checks the enrollment is still active on the same step\n * with no live claim, and that the mailbox's day has room under its cap,\n * then writes the claim and reserves the day's count. Two runs racing for\n * one enrollment write one claim; two racing for one mailbox's last slot\n * reserve it once. The claim carries the `Message-ID` minted for the send,\n * so a claim a run died holding is settled by finding the message in the\n * mailbox rather than by sending it a second time. A send that fails hands\n * its reservation back.\n *\n * Before it is claimed, every gate is asked again — the do-not-contact\n * list, the suppression lists, the sales topic, the roster, the other\n * sequences — because a person enrolled on Monday can unsubscribe by\n * Thursday. A lookup that could not be made holds the send; a gate that\n * refuses stops the enrollment, saying why.\n *==========================================*/\n\nexport { OUTREACH_SEND_JOB_ID } from '../constants/runtime-jobs'\n\n/** The most due enrollments one run reads. */\nexport const OUTREACH_SEND_SCAN_LIMIT = 300\n\n/** How long a claim holds before a later run settles it. */\nexport const OUTREACH_CLAIM_STALE_MS = 10 * 60_000\n\n/** What one run did, for the tick's answer. */\nexport interface OutreachSendReport {\n [key: string]: number\n due: number\n sent: number\n tasks: number\n /** Stopped by a gate or an unusable mailbox. */\n stopped: number\n /** Paused for the rep to fix, or failed for good. */\n failed: number\n /** Due, and left for a later run: the allowance, a lookup, a hold. */\n held: number\n /** Claims a dead run left, settled. */\n recovered: number\n}\n\ntype Firestore = FirebaseFirestore.Firestore\n\ninterface MailboxRun {\n orgId: string\n org: Record<string, unknown>\n mailbox: OutreachMailbox\n settings: OutreachComplianceSettingsDocument\n report: OutreachSendReport\n deadlineMs: number\n opened: OpenedOutreachMailbox | null\n /** Set once the mailbox itself cannot send this run. */\n stopped: boolean\n templates: Map<string, string | null>\n /**\n * The click-tracking origin for this mailbox's sending domain (AGL-3306):\n * `undefined` until a tracked send first asks, then the verified\n * `https://links.<domain>` or `null` for the console's own address.\n */\n linkOrigin?: string | null\n}\n\nconst blankReport = (): OutreachSendReport => ({\n due: 0,\n sent: 0,\n tasks: 0,\n stopped: 0,\n failed: 0,\n held: 0,\n recovered: 0,\n})\n\n/** Runs the send job once — see the module note. */\nexport async function runOutreachSendJob(\n deps: OutreachRuntimeDeps,\n context: { nowMs: number; deadlineMs: number },\n): Promise<OutreachSendReport> {\n const firestore = deps.firestore()\n const report = blankReport()\n const due = await firestore\n .collectionGroup(OUTREACH_COLLECTIONS.enrollments)\n .where('status', '==', 'active')\n .where('nextDueAtMs', '<=', context.nowMs)\n .orderBy('nextDueAtMs')\n .limit(OUTREACH_SEND_SCAN_LIMIT)\n .get()\n report.due = due.size\n const byOrg = new Map<string, Map<string, OutreachEnrollment[]>>()\n for (const doc of due.docs) {\n const orgId = doc.ref.parent.parent?.id\n const enrollment = readStoredOutreachEnrollment(doc.id, doc.data())\n if (!orgId || !enrollment) continue\n const mailboxes = byOrg.get(orgId) ?? new Map<string, OutreachEnrollment[]>()\n mailboxes.set(enrollment.mailboxId, [...(mailboxes.get(enrollment.mailboxId) ?? []), enrollment])\n byOrg.set(orgId, mailboxes)\n }\n\n for (const [orgId, mailboxes] of byOrg) {\n const waiting = [...mailboxes.values()].reduce((sum, list) => sum + list.length, 0)\n if (deps.now() >= context.deadlineMs) {\n report.held += waiting\n continue\n }\n const orgSnapshot = await firestore.collection('orgs').doc(orgId).get()\n const org = (orgSnapshot.exists ? orgSnapshot.data() : null) as Record<string, unknown> | null\n if (!org || (await deps.orgRefusal(orgId, org))) {\n report.held += waiting\n continue\n }\n const settings = await readOutreachComplianceSettingsDoc(firestore, orgId)\n for (const [mailboxId, enrollments] of mailboxes) {\n await runMailbox(deps, firestore, { orgId, org, mailboxId, enrollments, settings, report, context })\n }\n }\n return report\n}\n\n/** The reason an unusable mailbox stops an enrollment, or `null` for a usable one. */\nasync function unusableMailbox(\n firestore: Firestore,\n orgId: string,\n mailbox: OutreachMailbox | null,\n): Promise<string | null> {\n if (!mailbox) return 'The mailbox this sequence sends from was removed.'\n if (mailbox.status === 'disconnected') return 'The mailbox this sequence sends from was disconnected.'\n const member = await firestore.collection('orgs').doc(orgId).collection('members').doc(mailbox.connectedByUid).get()\n return member.exists\n ? null\n : 'The member who connected the mailbox this sequence sends from is no longer in the organization.'\n}\n\nasync function runMailbox(\n deps: OutreachRuntimeDeps,\n firestore: Firestore,\n input: {\n orgId: string\n org: Record<string, unknown>\n mailboxId: string\n enrollments: OutreachEnrollment[]\n settings: OutreachComplianceSettingsDocument\n report: OutreachSendReport\n context: { nowMs: number; deadlineMs: number }\n },\n): Promise<void> {\n const { orgId, org, report, context } = input\n const nowMs = context.nowMs\n const snapshot = await mailboxRef(firestore, orgId, input.mailboxId).get()\n const mailbox = readStoredOutreachMailbox(input.mailboxId, snapshot.exists ? snapshot.data() : undefined)\n const unusable = await unusableMailbox(firestore, orgId, mailbox)\n if (unusable || !mailbox) {\n for (const enrollment of input.enrollments) {\n const outcome = await applyOutreachEvent(firestore, {\n orgId,\n enrollmentId: enrollment.id,\n event: { type: 'stop', atMs: nowMs, byUid: null, reason: 'gate', detail: unusable },\n nowMs,\n })\n if (outcome.changed) report.stopped += 1\n }\n return\n }\n if (mailbox.status !== 'connected' || (await deps.sendRefusal({ orgId, org, uid: mailbox.connectedByUid }))) {\n report.held += input.enrollments.length\n return\n }\n\n const run: MailboxRun = {\n orgId,\n org,\n mailbox,\n settings: input.settings,\n report,\n deadlineMs: context.deadlineMs,\n opened: null,\n stopped: false,\n templates: new Map(),\n }\n const sequenceIds = [...new Set(input.enrollments.map((enrollment) => enrollment.sequenceId))]\n const sequenceSnapshots = await firestore.getAll(\n ...sequenceIds.map((id) => outreachOrgCollection(firestore, orgId, 'sequences').doc(id)),\n )\n const sequences = new Map<string, OutreachSequence>()\n sequenceSnapshots.forEach((sequenceSnapshot, index) => {\n const sequence = readStoredOutreachSequence(\n sequenceIds[index],\n sequenceSnapshot.exists ? sequenceSnapshot.data() : undefined,\n )\n if (sequence) sequences.set(sequence.id, sequence)\n })\n\n const candidates: OutreachDueCandidate[] = []\n for (const enrollment of input.enrollments) {\n const sequence = sequences.get(enrollment.sequenceId)\n const claim = enrollment.sendClaim\n if (claim && nowMs - claim.atMs < OUTREACH_CLAIM_STALE_MS) continue\n if (claim && sequence) {\n if (await recoverClaim(deps, firestore, run, enrollment, sequence)) report.recovered += 1\n continue\n }\n if (sequence) candidates.push({ enrollment, sequence })\n }\n\n const allowance = outreachTickAllowance({ mailbox, nowMs })\n const selection = selectDueOutreachEnrollments({ candidates, mailbox, nowMs, allowance: allowance.allowance })\n report.held += selection.deferred.length\n\n for (const candidate of selection.tasks) {\n if (deps.now() >= context.deadlineMs) {\n report.held += 1\n continue\n }\n if (await runTaskStep(deps, firestore, run, candidate)) report.tasks += 1\n }\n if (!selection.emails.length) return\n\n // The people behind the emails, read once per site: the contact and its\n // company, and every lookup the gates decide on.\n const people = new Map<string, OutreachEnrollCandidate>()\n const lookups = new Map<string, OutreachGateLookups>()\n const byHost = new Map<string, OutreachEnrollment[]>()\n for (const candidate of selection.emails) {\n const enrollment = candidate.enrollment as OutreachEnrollment\n byHost.set(enrollment.hostId, [...(byHost.get(enrollment.hostId) ?? []), enrollment])\n }\n const siteNames = new Map<string, string>()\n const siteDocs = new Map<string, Record<string, unknown> | null>()\n // Sites under a staff suspension (AGL-3356): their people are held, not\n // stamped, so the step sends on the first run after the lift.\n const heldSites = new Set<string>()\n for (const [hostId, enrollments] of byHost) {\n const consentGroup = consentGroupForHost(org, hostId)\n const contactGroupId = consentGroup.groupId\n // Each by the record it names — the contact, or the lead while the\n // person is one (AGL-3234) — keyed by that record's id.\n const [candidatesRead, lookupsRead, host] = await Promise.all([\n readOutreachEnrollCandidates(firestore, {\n orgId,\n hostId,\n contactGroupId,\n people: enrollments.map(outreachEnrollmentPerson),\n }),\n readOutreachGateLookups(firestore, {\n orgId,\n hostId,\n consentHostIds: consentGroup.hostIds,\n consentAwaitsConfirmation: consentGroup.awaitsConfirmation,\n gateway: {\n resolveMx: deps.resolveMx,\n resolveAddress: deps.resolveAddress,\n nowMs,\n sendingDomain: outreachMailboxSendingDomain(mailbox),\n },\n people: enrollments.map((enrollment) => {\n const person = outreachEnrollmentPerson(enrollment)\n return {\n personId: person.id,\n contactId: person.kind === 'contact' ? person.id : null,\n leadId: person.kind === 'lead' ? person.id : null,\n email: enrollment.email,\n }\n }),\n }),\n firestore.collection('hosts').doc(hostId).get(),\n ])\n for (const person of candidatesRead) people.set(person.personId, person)\n for (const [personId, answer] of lookupsRead) lookups.set(personId, answer)\n siteNames.set(hostId, host.exists ? String(host.get('name') ?? '') : '')\n siteDocs.set(hostId, host.exists ? ((host.data() as Record<string, unknown>) ?? null) : null)\n if (host.exists && outreachSiteHeld(host.data() as Record<string, unknown>, nowMs)) {\n heldSites.add(hostId)\n }\n }\n\n for (const candidate of selection.emails) {\n if (run.stopped || deps.now() >= context.deadlineMs) {\n report.held += 1\n continue\n }\n const enrollment = candidate.enrollment as OutreachEnrollment\n if (heldSites.has(enrollment.hostId)) {\n report.held += 1\n continue\n }\n const personId = outreachEnrollmentPerson(enrollment).id\n await runEmailStep(deps, firestore, run, {\n enrollment,\n sequence: candidate.sequence as OutreachSequence,\n person: people.get(personId) ?? null,\n lookups: lookups.get(personId) ?? null,\n siteName: siteNames.get(enrollment.hostId) ?? '',\n site: siteDocs.get(enrollment.hostId) ?? null,\n })\n }\n}\n\n/** Any lookup the runtime could not make: the send waits for a run that can. */\nfunction uncheckable(lookups: OutreachGateLookups | null): boolean {\n return !lookups || Object.values(lookups).some((value) => value === null)\n}\n\n/** The event a gate's refusal ends an enrollment with. */\nfunction gateEvent(blocks: readonly OutreachGateBlock[], atMs: number): OutreachEnrollmentEvent {\n const optedOut = blocks.find((block) => block.code === 'do_not_contact' || block.code === 'sales_opted_out')\n if (optedOut) return { type: 'opt_out', atMs, reason: 'do_not_contact', detail: optedOut.reason }\n return { type: 'stop', atMs, byUid: null, reason: 'gate', detail: blocks.map((block) => block.reason).join(' ') }\n}\n\n/**\n * The click-tracking origin for mail sent as `senderAddress`, or `null` for\n * the console's own address — which is also what a failed lookup reads as: a\n * link on the app address still counts the click, so no send waits on it.\n */\nasync function trackingLinkOrigin(\n deps: OutreachRuntimeDeps,\n orgId: string,\n senderAddress: string,\n): Promise<string | null> {\n if (!deps.clickLinkOrigin) return null\n try {\n return await deps.clickLinkOrigin({ orgId, senderAddress })\n } catch (error) {\n console.warn('[outreach] the click-tracking host could not be read; links use the app address', error)\n return null\n }\n}\n\n/** The sender line a mailbox's mail goes out with. */\nconst senderOf = (mailbox: OutreachMailbox) => ({\n address: mailbox.sendAs || mailbox.email,\n name: mailbox.displayName || null,\n})\n\nasync function openClient(deps: OutreachRuntimeDeps, run: MailboxRun) {\n const opened = (run.opened ??= await deps.openMailbox(run.mailbox.id))\n if (opened.ok === true) return opened.client\n run.stopped = true\n if (opened.reason !== 'not-configured') {\n await noteOutreachMailboxReconnectRequired(deps, {\n orgId: run.orgId,\n mailboxId: run.mailbox.id,\n errorCode: opened.reason,\n nowMs: deps.now(),\n })\n }\n return null\n}\n\n/**\n * Claims one step: the enrollment still active on the same step with no\n * live claim, and — for an email — a slot under the mailbox's cap today,\n * reserved in the same transaction.\n */\nasync function claimStep(\n deps: OutreachRuntimeDeps,\n firestore: Firestore,\n run: MailboxRun,\n enrollment: OutreachEnrollment,\n messageId: string | null,\n): Promise<'claimed' | 'taken' | 'cap'> {\n const enrollmentRef = outreachOrgCollection(firestore, run.orgId, 'enrollments').doc(enrollment.id)\n const boxRef = mailboxRef(firestore, run.orgId, run.mailbox.id)\n const nowMs = deps.now()\n return firestore.runTransaction(async (transaction) => {\n const [current, box] = await Promise.all([transaction.get(enrollmentRef), transaction.get(boxRef)])\n const stored = readStoredOutreachEnrollment(enrollment.id, current.exists ? current.data() : undefined)\n const claim = stored?.sendClaim\n if (\n !stored ||\n stored.status !== 'active' ||\n stored.stepIndex !== enrollment.stepIndex ||\n stored.nextDueAtMs === null ||\n stored.nextDueAtMs > nowMs ||\n (claim && nowMs - claim.atMs < OUTREACH_CLAIM_STALE_MS)\n ) {\n return 'taken'\n }\n if (messageId) {\n const mailbox = readStoredOutreachMailbox(run.mailbox.id, box.exists ? box.data() : undefined)\n if (!mailbox || mailbox.status !== 'connected') return 'taken'\n const sent = outreachSentToday(mailbox.health, nowMs, mailbox.timezone)\n if (sent >= outreachEffectiveDailyCap(mailbox, nowMs)) return 'cap'\n transaction.update(boxRef, {\n 'health.sentToday': sent + 1,\n 'health.sentOnDay': outreachLocalDay(nowMs, mailbox.timezone),\n })\n }\n transaction.update(enrollmentRef, {\n sendClaim: { token: randomUUID(), atMs: nowMs, stepIndex: enrollment.stepIndex, messageId },\n updatedAtMs: nowMs,\n })\n return 'claimed'\n })\n}\n\n/** Drops a claim, and hands an email's reservation back to the mailbox's day. */\nasync function releaseClaim(\n deps: OutreachRuntimeDeps,\n firestore: Firestore,\n run: MailboxRun,\n enrollment: Pick<OutreachEnrollment, 'id'>,\n reserved: boolean,\n event: OutreachEnrollmentEvent | null = null,\n): Promise<void> {\n const nowMs = deps.now()\n await applyOutreachEvent(firestore, {\n orgId: run.orgId,\n enrollmentId: enrollment.id,\n event,\n extra: () => ({ sendClaim: null }),\n nowMs,\n })\n if (!reserved) return\n const boxRef = mailboxRef(firestore, run.orgId, run.mailbox.id)\n await firestore.runTransaction(async (transaction) => {\n const box = await transaction.get(boxRef)\n const mailbox = readStoredOutreachMailbox(run.mailbox.id, box.exists ? box.data() : undefined)\n if (!mailbox || mailbox.health?.sentOnDay !== outreachLocalDay(nowMs, mailbox.timezone)) return\n transaction.update(boxRef, { 'health.sentToday': Math.max(0, (Number(mailbox.health.sentToday) || 0) - 1) })\n })\n}\n\n/**\n * Records a step that ran: the engine's completion patch, the claim\n * cleared, the step's record kept — and for an email the mailbox's send on\n * its day, its last-sent time and its window of recent sends. Refuses\n * (answers false) when the claim is no longer this run's.\n */\nasync function completeStep(\n deps: OutreachRuntimeDeps,\n firestore: Firestore,\n run: MailboxRun,\n input: {\n enrollment: OutreachEnrollment\n sequence: OutreachSequence\n record: OutreachStepRecord\n sent: { messageId: string; threadId: string; subject: string } | null\n claimMessageId: string | null\n },\n): Promise<boolean> {\n const enrollmentRef = outreachOrgCollection(firestore, run.orgId, 'enrollments').doc(input.enrollment.id)\n const boxRef = mailboxRef(firestore, run.orgId, run.mailbox.id)\n const nowMs = deps.now()\n /*\n * Whether this is the FIRST email this person has had from the sequence\n * (AGL-3239), decided from the same read the step is recorded against and\n * so re-decided on every transaction retry. It is what `stats.people`\n * counts: the denominator of every engagement rate, and the thing\n * `stats.sent` is not, since one person takes several steps.\n */\n let firstEmail = false\n // The first email of this person's to carry a tracking image (AGL-3395):\n // what `stats.openPeople`, the open rate's denominator, counts.\n let firstOpenTracked = false\n const completed = await firestore.runTransaction(async (transaction) => {\n const [current, box] = await Promise.all([\n transaction.get(enrollmentRef),\n input.sent ? transaction.get(boxRef) : Promise.resolve(null),\n ])\n const stored = readStoredOutreachEnrollment(input.enrollment.id, current.exists ? current.data() : undefined)\n if (!stored?.sendClaim || stored.sendClaim.messageId !== input.claimMessageId) return false\n if (stored.stepIndex !== input.enrollment.stepIndex) return false\n // The step RAN, whatever happened to the enrollment while it did — a\n // member paused it, a reply stopped it — so it is recorded as run, and a\n // resume never sends it twice.\n firstEmail =\n input.sent !== null &&\n !(stored.stepRecords ?? []).some((record) => record.kind === 'email')\n firstOpenTracked =\n input.sent !== null &&\n input.record.openTracked === true &&\n !(stored.stepRecords ?? []).some((record) => record.openTracked === true)\n const plan = planOutreachStepCompletion({\n enrollment: { ...stored, status: 'active' },\n sequence: input.sequence,\n mailbox: run.mailbox,\n completedAtMs: nowMs,\n sent: input.sent,\n random: deps.random,\n })\n const patch: Record<string, unknown> = {\n sendClaim: null,\n stepRecords: [...(stored.stepRecords ?? []), input.record].slice(-20),\n updatedAtMs: nowMs,\n ...(plan.patch ?? {}),\n }\n if (stored.status !== 'active') {\n patch['status'] = stored.status\n if (stored.status !== 'paused') patch['nextDueAtMs'] = null\n }\n transaction.update(enrollmentRef, patch)\n if (input.sent && box?.exists) {\n const mailbox = readStoredOutreachMailbox(run.mailbox.id, box.data())\n if (mailbox) {\n const day = outreachLocalDay(nowMs, mailbox.timezone)\n const counts = mailbox.health?.daily?.[day] ?? { sent: 0, bounces: 0, replies: 0 }\n transaction.update(boxRef, {\n 'health.lastSentAtMs': nowMs,\n 'health.lastErrorAtMs': null,\n 'health.lastErrorCode': null,\n [`health.daily.${day}`]: { ...counts, sent: (Number(counts.sent) || 0) + 1 },\n 'health.recentSends': withRecentSend(mailbox.health?.recentSends, {\n id: outreachSendDigest(input.sent.messageId),\n atMs: nowMs,\n bounced: false,\n }),\n updatedAtMs: nowMs,\n })\n }\n }\n return true\n })\n if (completed && input.sent) {\n await bumpOutreachSequenceStats(firestore, {\n orgId: run.orgId,\n sequenceId: input.sequence.id,\n firstEmail,\n trackedLinks: input.record.links?.length ?? 0,\n openTracked: input.record.openTracked === true,\n firstOpenTracked,\n })\n }\n return completed\n}\n\n/**\n * The sequence's send counters (AGL-3239), written outside the enrollment's\n * transaction.\n *\n * One sequence holds every enrollment, so a transaction over it would\n * serialise every recipient against every other; `FieldValue.increment` is a\n * blind write with nothing to contend on. It is bookkeeping beside the act,\n * so a failure is logged and the send stands — the email has already left.\n *\n * `clickTracked` is stamped by the first send that actually carried a\n * rewritten link, never by the SETTING: a sequence with the setting on whose\n * emails have no links in them measured nothing, and the report must say\n * \"not measured\" for it rather than publish a 0% click rate.\n */\nasync function bumpOutreachSequenceStats(\n firestore: Firestore,\n input: {\n orgId: string\n sequenceId: string\n firstEmail: boolean\n trackedLinks: number\n openTracked?: boolean\n firstOpenTracked?: boolean\n },\n): Promise<void> {\n if (!input.sequenceId) return\n await outreachOrgCollection(firestore, input.orgId, 'sequences')\n .doc(input.sequenceId)\n .update({\n 'stats.sent': FieldValue.increment(1),\n ...(input.firstEmail ? { 'stats.people': FieldValue.increment(1) } : {}),\n ...(input.trackedLinks > 0 ? { 'stats.clickTracked': true } : {}),\n // Stamped by a send that carried the image, never by the setting, for\n // `clickTracked`'s reason (AGL-3395).\n ...(input.openTracked ? { 'stats.openTracked': true } : {}),\n ...(input.firstOpenTracked ? { 'stats.openPeople': FieldValue.increment(1) } : {}),\n })\n .catch((error: unknown) => {\n console.warn('[outreach] a send could not be counted on its sequence', error)\n })\n}\n\n/** One task step: the rep's task on the contact, then the step recorded. */\nasync function runTaskStep(\n deps: OutreachRuntimeDeps,\n firestore: Firestore,\n run: MailboxRun,\n candidate: OutreachDueCandidate,\n): Promise<boolean> {\n const enrollment = candidate.enrollment as OutreachEnrollment\n const sequence = candidate.sequence as OutreachSequence\n const step = sequence.steps[enrollment.stepIndex] as OutreachTaskStep\n if ((await claimStep(deps, firestore, run, enrollment, null)) !== 'claimed') return false\n const nowMs = deps.now()\n let taskId: string | null\n try {\n const written = await fileOutreachTask(deps, {\n orgId: run.orgId,\n hostId: enrollment.hostId,\n link: outreachEnrollmentLink(enrollment),\n dedupeKey: `step:${enrollment.id}:${step.id}`,\n title: step.title,\n notes: `From sequence step ${enrollment.stepIndex + 1}.`,\n kind: OUTREACH_TASK_KIND_TO_RECORD[step.taskKind] ?? 'todo',\n dueAtMs: nowMs,\n assigneeUid: run.mailbox.connectedByUid,\n })\n taskId = written?.ok ? written.id : null\n if (written?.ok === false) console.warn(`[outreach] a task step's task was not filed: ${written.error}`)\n } catch (error) {\n // The record system failed rather than refused: the step waits for a\n // run that can file its task.\n console.error('[outreach] filing a task step failed; the step waits', error)\n await releaseClaim(deps, firestore, run, enrollment, false)\n return false\n }\n return completeStep(deps, firestore, run, {\n enrollment,\n sequence,\n record: { stepIndex: enrollment.stepIndex, stepId: step.id, kind: 'task', atMs: nowMs, taskId },\n sent: null,\n claimMessageId: null,\n })\n}\n\n/** A CRM template's body, read once per run. */\nasync function templateBody(firestore: Firestore, run: MailboxRun, templateId: string): Promise<string | null> {\n if (!run.templates.has(templateId)) {\n const snapshot = await firestore\n .collection('orgs')\n .doc(run.orgId)\n .collection(CRM_COLLECTIONS.emailTemplates)\n .doc(templateId)\n .get()\n run.templates.set(\n templateId,\n snapshot.exists ? normalizeCrmEmailTemplate(snapshot.data() as Record<string, unknown>).body : null,\n )\n }\n return run.templates.get(templateId) ?? null\n}\n\nasync function runEmailStep(\n deps: OutreachRuntimeDeps,\n firestore: Firestore,\n run: MailboxRun,\n input: {\n enrollment: OutreachEnrollment\n sequence: OutreachSequence\n person: OutreachEnrollCandidate | null\n lookups: OutreachGateLookups | null\n siteName: string\n /** The site's document, for the phishing screen (AGL-3356). */\n site?: Record<string, unknown> | null\n },\n): Promise<void> {\n const { enrollment, sequence, person } = input\n const { report, mailbox } = run\n const nowMs = deps.now()\n const stop = async (event: OutreachEnrollmentEvent, counter: 'stopped' | 'failed') => {\n const outcome = await applyOutreachEvent(firestore, { orgId: run.orgId, enrollmentId: enrollment.id, event, nowMs })\n if (outcome.changed) report[counter] += 1\n }\n\n // Every gate again, on the person as they stand now.\n if (!person?.contact) {\n return stop(\n {\n type: 'stop',\n atMs: nowMs,\n byUid: null,\n reason: 'gate',\n detail:\n enrollment.target === 'lead'\n ? \"This lead no longer exists in the sequence's site's CRM.\"\n : 'This contact no longer exists in the CRM.',\n },\n 'stopped',\n )\n }\n if (person.convertedContactId && enrollment.target === 'lead') {\n // The lead converted and the enrollment has not followed it yet: the\n // conversion's listener re-points it, and the next run sends as the contact.\n report.held += 1\n return\n }\n if (!person.visible) {\n return stop(\n { type: 'stop', atMs: nowMs, byUid: null, reason: 'gate', detail: \"This contact is no longer in the sequence's site's CRM.\" },\n 'stopped',\n )\n }\n if (uncheckable(input.lookups)) {\n report.held += 1\n return\n }\n const contactGroupId = consentGroupForHost(run.org, enrollment.hostId).groupId\n const gate = evaluateOutreachGates({\n email: enrollment.email,\n contact: person.contact,\n contactGroupId,\n company: person.company,\n settings: {\n ...sequence.settings,\n allowedCountries: effectiveOutreachAllowedCountries(\n sequence.settings.allowedCountries,\n run.settings.allowedCountries,\n ),\n },\n personalLine: enrollment.personalLine,\n attestations: enrollment.attestations,\n enrollmentId: enrollment.id,\n gatewayHoldReleased: typeof enrollment.gatewayHold?.releasedAtMs === 'number',\n lookups: input.lookups as OutreachGateLookups,\n })\n if (!gate.allowed) return stop(gateEvent(gate.blocks, nowMs), 'stopped')\n if (gate.hold) {\n // The gateway refused this organization twice lately and delivered\n // nothing (AGL-3326): the send is held, as a pause a member resumes\n // from the enrollment row, and nothing goes into it until they do.\n const hold = gate.hold\n const outcome = await applyOutreachEvent(firestore, {\n orgId: run.orgId,\n enrollmentId: enrollment.id,\n event: { type: 'pause', atMs: nowMs, byUid: null, reason: 'gateway_blocked_here', detail: hold.reason },\n extra: () => ({\n gatewayHold: { gateway: hold.gateway, heldAtMs: nowMs, releasedByUid: null, releasedAtMs: null },\n }),\n nowMs,\n })\n if (outcome.changed) report.held += 1\n return\n }\n\n /*\n * The email, with its way out. The footer's \"reply 'no'\" line and the\n * postal address are always there (compose refuses without them). The\n * `List-Unsubscribe` header is the sequence's own setting (AGL-3296), read\n * here per send like click tracking, and absent reads as off.\n */\n const unsubscribe = outreachListUnsubscribe({\n enabled: sequence.settings.listUnsubscribe,\n mintUrl: () => deps.unsubscribeUrl({ orgId: run.orgId, enrollmentId: enrollment.id }),\n mailboxEmail: mailbox.email,\n })\n if (unsubscribe.status === 'unavailable') {\n // On, but no link can be minted — no secret, or no HTTPS console origin\n // — and an email without the way out its sequence promised does not leave.\n console.error('[outreach] no unsubscribe link could be minted; nothing sends until one can')\n run.stopped = true\n report.held += 1\n return\n }\n const step = sequence.steps[enrollment.stepIndex]\n const sender = senderOf(mailbox)\n /*\n * Click tracking is the sequence's own setting (AGL-3239) and is read\n * here, per send, rather than once per run: a member turning it off\n * applies to the next email, not to the next hour. Each link becomes a\n * short link (AGL-3297) whose document is written below, before the email\n * leaves; a link that cannot be made is left exactly as the step wrote it.\n */\n if ((sequence.settings.trackClicks || sequence.settings.countOpens) && run.linkOrigin === undefined) {\n run.linkOrigin = await trackingLinkOrigin(deps, run.orgId, sender.address)\n }\n const shortLinks: Array<{ id: string; doc: OutreachStoredLink }> = []\n const rewriteLink = sequence.settings.trackClicks\n ? (link: { url: string; index: number }) => {\n const doc = outreachStoredLink(\n {\n orgId: run.orgId,\n enrollmentId: enrollment.id,\n stepIndex: enrollment.stepIndex,\n linkIndex: link.index,\n url: link.url,\n },\n nowMs,\n )\n const id = newOutreachLinkId()\n const url = doc ? deps.clickLinkUrl(id, run.linkOrigin ?? null) : null\n if (!doc || !url) return null\n shortLinks.push({ id, doc })\n return url\n }\n : null\n /*\n * The tracking image (AGL-3395), for a sequence that counts opens: a short\n * link of kind `open` on the same host, stored with the links below. None\n * minted — no HTTPS origin — and the email goes out as plain text alone.\n */\n let pixel: { id: string; doc: OutreachStoredOpen; url: string } | null = null\n if (sequence.settings.countOpens) {\n const doc = outreachStoredOpen(\n { orgId: run.orgId, enrollmentId: enrollment.id, stepIndex: enrollment.stepIndex },\n nowMs,\n )\n const id = newOutreachLinkId()\n const url = doc ? deps.clickLinkUrl(id, run.linkOrigin ?? null) : null\n if (doc && url) pixel = { id, doc, url }\n }\n const composed = composeOutreachEmail({\n sequence,\n enrollment,\n orgSettings: run.settings,\n rewriteLink,\n openPixelUrl: pixel?.url ?? null,\n merge: {\n // For a lead, the contact-shaped view of it (`leadAsContact`), so a\n // step written with `{{contact.*}}` reads the lead; `{{lead.*}}` reads\n // the lead's own document beside it.\n contact: person.contact,\n contactGroupId,\n lead: person.lead,\n sender: { name: mailbox.displayName, email: sender.address },\n site: { name: input.siteName },\n },\n templateBody: step?.kind === 'email' && step.templateId ? await templateBody(firestore, run, step.templateId) : null,\n listUnsubscribeUrl: unsubscribe.status === 'ready' ? unsubscribe.url : null,\n listUnsubscribeMailto: unsubscribe.status === 'ready' ? unsubscribe.mailto : null,\n })\n if (composed.error || !composed.email) {\n const code = composed.error?.code\n if (code === 'missing_postal_address' || code === 'missing_legal_name') {\n // The organization's footer: nothing of theirs sends until it is set.\n run.stopped = true\n report.held += 1\n return\n }\n if (code === 'invalid_recipient' || code === 'missing_thread' || code === 'not_an_email_step') {\n return stop({ type: 'send_failed', atMs: nowMs, detail: composed.error?.message }, 'failed')\n }\n // The sequence's own words: the rep fixes the step and resumes.\n return stop({ type: 'pause', atMs: nowMs, byUid: null, detail: composed.error?.message }, 'failed')\n }\n if (composed.unresolvedFields.length) {\n const fields = composed.unresolvedFields.map((field) => `{{${field}}}`).join(', ')\n return stop(\n {\n type: 'pause',\n atMs: nowMs,\n byUid: null,\n detail: `Paused before sending: this contact has nothing for ${fields}. Fill it in and resume.`,\n },\n 'failed',\n )\n }\n\n /*\n * THE PHISHING SCREEN (AGL-3356): the same one every tenant message\n * passes, asked of the email as composed and before anything is claimed,\n * stored or sent. A hold pauses this enrollment with the reason; staff\n * decide it in the abuse queue, and a member resumes it once released.\n */\n if (deps.screenMessage) {\n const held = await deps.screenMessage({\n orgId: run.orgId,\n org: run.org,\n hostId: enrollment.hostId,\n host: input.site ?? null,\n subject: composed.email.subject,\n text: composed.email.text,\n fromName: mailbox.displayName ?? null,\n fromAddress: sender.address,\n })\n if (held) return stop({ type: 'pause', atMs: nowMs, byUid: null, detail: held }, 'failed')\n }\n\n /*\n * The short links' documents, before anything is claimed or sent: a link\n * in an email that already left must resolve on the first click. A write\n * that fails holds the send for the next run, which mints new ones — an\n * orphaned document is inert, an email whose links go nowhere is not.\n */\n if (shortLinks.length || (pixel && composed.email.html)) {\n try {\n const batch = firestore.batch()\n for (const link of shortLinks) {\n batch.create(firestore.collection(OUTREACH_COLLECTIONS.links).doc(link.id), link.doc)\n }\n if (pixel && composed.email.html) {\n batch.create(firestore.collection(OUTREACH_COLLECTIONS.links).doc(pixel.id), pixel.doc)\n }\n await batch.commit()\n } catch (error) {\n console.error('[outreach] the short links could not be stored; the send waits for the next run', error)\n report.held += 1\n return\n }\n }\n\n // Claimed, then sent, then recorded.\n const domain = sender.address.slice(sender.address.lastIndexOf('@') + 1)\n const local = randomUUID()\n const messageId = `<${local}@${domain}>`\n const claimed = await claimStep(deps, firestore, run, enrollment, messageId)\n if (claimed !== 'claimed') {\n if (claimed === 'cap') run.stopped = true\n report.held += 1\n return\n }\n const client = await openClient(deps, run)\n if (!client) {\n await releaseClaim(deps, firestore, run, enrollment, true)\n report.held += 1\n return\n }\n let sent: Awaited<ReturnType<typeof sendComposedOutreachEmail>>\n try {\n sent = await sendComposedOutreachEmail(client, composed.email, sender, {\n messageIdLocalPart: local,\n messageIdDomain: domain,\n })\n } catch (error) {\n if (error instanceof Rfc5322MessageError || (error instanceof GmailTransportError && error.code === 'invalid_request')) {\n await releaseClaim(deps, firestore, run, enrollment, true, {\n type: 'send_failed',\n atMs: deps.now(),\n detail: `Gmail refused the email: ${error.message}`,\n })\n report.failed += 1\n return\n }\n await releaseClaim(deps, firestore, run, enrollment, true)\n report.held += 1\n run.stopped = true\n const code = error instanceof GmailTransportError ? error.code : 'unexpected'\n if (isReconnectRequired(error)) {\n await noteOutreachMailboxReconnectRequired(deps, {\n orgId: run.orgId,\n mailboxId: mailbox.id,\n errorCode: code,\n nowMs: deps.now(),\n })\n } else {\n await mailboxRef(firestore, run.orgId, mailbox.id)\n .update({ 'health.lastErrorAtMs': deps.now(), 'health.lastErrorCode': code })\n .catch(() => undefined)\n }\n console.error(`[outreach] a send from a mailbox failed (${code}); its sends wait for the next run`)\n return\n }\n\n const record: OutreachStepRecord = {\n stepIndex: enrollment.stepIndex,\n stepId: step?.id ?? '',\n kind: 'email',\n atMs: deps.now(),\n gmailMessageId: sent.gmailMessageId,\n gmailThreadId: sent.threadId,\n messageId: sent.messageId,\n subject: sent.subject,\n ...(composed.email.trackedLinks.length ? { links: composed.email.trackedLinks } : {}),\n ...(composed.email.html ? { openTracked: true } : {}),\n // Sent as this person's own copy of the step (AGL-3324), and whose words.\n ...(composed.override ? { curated: composed.override.source } : {}),\n }\n await completeStep(deps, firestore, run, {\n enrollment,\n sequence,\n record,\n sent: { messageId: sent.messageId, threadId: sent.threadId, subject: sent.subject },\n claimMessageId: messageId,\n })\n report.sent += 1\n // The gateway ledger (AGL-3326): one more send into the domain's gateway,\n // which the sync credits as delivered a day from now if nothing bounces.\n const standing = (input.lookups as OutreachGateLookups).gateway\n const recipientDomain = outreachEmailDomain(enrollment.email)\n if (standing && recipientDomain) {\n await recordOutreachGatewayOutcome(firestore, run.orgId, {\n sendingDomain: outreachMailboxSendingDomain(mailbox),\n gateway: standing.gateway,\n outcome: 'sent',\n atMs: record.atMs,\n })\n }\n await fileOutreachEmail(deps, {\n orgId: run.orgId,\n hostId: enrollment.hostId,\n link: outreachEnrollmentLink(enrollment),\n direction: 'outbound',\n subject: sent.subject,\n from: sender.address,\n to: composed.email.to,\n messageId: sent.messageId,\n inReplyTo: composed.email.inReplyTo ?? null,\n body: composed.email.text,\n atMs: record.atMs,\n byUid: mailbox.connectedByUid,\n byName: mailbox.displayName || null,\n })\n // The first email is the touch (AGL-3254): `sent` on the sequence's\n // campaigns, and the person's record credited to the first of them.\n // Judged on the enrollment as it was read, before this step's record.\n await creditOutreachFirstSend(deps, { enrollment, atMs: record.atMs })\n await nurtureEnrolledLead(firestore, run, enrollment)\n}\n\n/**\n * A lead an email step reached is no longer untouched (AGL-3446): New moves\n * to Nurturing. Called only once a send is recorded, so an enrollment whose\n * steps never go out leaves its lead where it stood.\n */\nasync function nurtureEnrolledLead(\n firestore: Firestore,\n run: MailboxRun,\n enrollment: OutreachEnrollment,\n): Promise<void> {\n if (enrollment.target !== 'lead' || !enrollment.leadId) return\n await markOutreachLeadNurturing(firestore, { orgId: run.orgId, leadId: enrollment.leadId })\n}\n\n/**\n * Settles a claim a run died holding. A task step's claim is dropped and\n * the step runs again (its task is filed once however often it is asked).\n * An email's claim looks for the message it minted in the mailbox: found,\n * the send happened and is recorded; not found, it did not, and the claim\n * and its reservation are handed back for the next run.\n */\nasync function recoverClaim(\n deps: OutreachRuntimeDeps,\n firestore: Firestore,\n run: MailboxRun,\n enrollment: OutreachEnrollment,\n sequence: OutreachSequence,\n): Promise<boolean> {\n const claim = enrollment.sendClaim\n if (!claim) return false\n if (!claim.messageId) {\n await releaseClaim(deps, firestore, run, enrollment, false)\n return true\n }\n const client = await openClient(deps, run)\n if (!client) return false\n const bare = claim.messageId.replace(/^<|>$/g, '')\n const found = await client.listMessages({ q: `rfc822msgid:${bare}`, maxResults: 1, includeSpamTrash: true })\n const hit = found.messages[0]\n if (!hit) {\n await releaseClaim(deps, firestore, run, enrollment, true)\n return true\n }\n const message = await client.getMessage(hit.id, { metadataHeaders: ['Subject'] })\n const subject = message.headers.find((header) => header.name.toLowerCase() === 'subject')?.value ?? ''\n const step = sequence.steps[enrollment.stepIndex]\n const atMs = deps.now()\n const completed = await completeStep(deps, firestore, run, {\n enrollment,\n sequence,\n record: {\n stepIndex: enrollment.stepIndex,\n stepId: step?.id ?? '',\n kind: 'email',\n atMs,\n gmailMessageId: hit.id,\n gmailThreadId: hit.threadId,\n messageId: claim.messageId,\n subject,\n },\n sent: { messageId: claim.messageId, threadId: hit.threadId, subject },\n claimMessageId: claim.messageId,\n })\n // A recovered first email is still the first email (AGL-3254).\n if (completed) {\n await creditOutreachFirstSend(deps, { enrollment, atMs })\n await nurtureEnrolledLead(firestore, run, enrollment)\n }\n return completed\n}\n"],"names":["consentGroupForHost","CRM_COLLECTIONS","normalizeCrmEmailTemplate","FieldValue","randomUUID","composeOutreachEmail","outreachEmailDomain","planOutreachStepCompletion","evaluateOutreachGates","outreachSentToday","outreachTickAllowance","selectDueOutreachEnrollments","readOutreachEnrollCandidates","readOutreachGateLookups","mailboxRef","outreachEffectiveDailyCap","outreachLocalDay","effectiveOutreachAllowedCountries","OUTREACH_COLLECTIONS","readOutreachComplianceSettingsDoc","outreachMailboxSendingDomain","recordOutreachGatewayOutcome","outreachEnrollmentLink","outreachEnrollmentPerson","outreachOrgCollection","readStoredOutreachEnrollment","readStoredOutreachMailbox","readStoredOutreachSequence","GmailTransportError","isReconnectRequired","Rfc5322MessageError","sendComposedOutreachEmail","creditOutreachFirstSend","newOutreachLinkId","outreachStoredLink","outreachStoredOpen","applyOutreachEvent","outreachSiteHeld","markOutreachLeadNurturing","outreachSendDigest","withRecentSend","noteOutreachMailboxReconnectRequired","fileOutreachEmail","fileOutreachTask","OUTREACH_TASK_KIND_TO_RECORD","outreachListUnsubscribe","OUTREACH_SEND_JOB_ID","OUTREACH_SEND_SCAN_LIMIT","OUTREACH_CLAIM_STALE_MS","blankReport","due","sent","tasks","stopped","failed","held","recovered","runOutreachSendJob","deps","context","firestore","report","collectionGroup","enrollments","where","nowMs","orderBy","limit","get","size","byOrg","Map","doc","docs","mailboxes","orgId","ref","parent","id","enrollment","data","set","mailboxId","waiting","values","reduce","sum","list","length","now","deadlineMs","orgSnapshot","collection","org","exists","orgRefusal","settings","runMailbox","unusableMailbox","mailbox","status","member","connectedByUid","input","snapshot","undefined","unusable","outcome","enrollmentId","event","type","atMs","byUid","reason","detail","changed","sendRefusal","uid","run","opened","templates","sequenceIds","Set","map","sequenceId","sequenceSnapshots","getAll","sequences","forEach","sequenceSnapshot","index","sequence","candidates","claim","sendClaim","recoverClaim","push","allowance","selection","deferred","candidate","runTaskStep","emails","people","lookups","byHost","hostId","siteNames","siteDocs","heldSites","host","consentGroup","contactGroupId","groupId","candidatesRead","lookupsRead","Promise","all","consentHostIds","hostIds","consentAwaitsConfirmation","awaitsConfirmation","gateway","resolveMx","resolveAddress","sendingDomain","person","personId","contactId","kind","leadId","email","answer","String","add","has","runEmailStep","siteName","site","uncheckable","Object","some","value","gateEvent","blocks","optedOut","find","block","code","join","trackingLinkOrigin","senderAddress","clickLinkOrigin","error","console","warn","senderOf","address","sendAs","name","displayName","openClient","openMailbox","ok","client","errorCode","claimStep","messageId","enrollmentRef","boxRef","runTransaction","transaction","current","box","stored","stepIndex","nextDueAtMs","health","timezone","update","token","updatedAtMs","releaseClaim","reserved","extra","sentOnDay","Math","max","Number","sentToday","completeStep","firstEmail","firstOpenTracked","completed","plan","resolve","claimMessageId","stepRecords","record","openTracked","completedAtMs","random","patch","slice","day","counts","daily","bounces","replies","recentSends","bounced","bumpOutreachSequenceStats","trackedLinks","links","increment","catch","step","steps","taskId","written","link","dedupeKey","title","notes","taskKind","dueAtMs","assigneeUid","stepId","templateBody","templateId","emailTemplates","body","composed","stop","counter","contact","target","convertedContactId","visible","gate","company","allowedCountries","personalLine","attestations","gatewayHoldReleased","gatewayHold","releasedAtMs","allowed","hold","heldAtMs","releasedByUid","unsubscribe","enabled","listUnsubscribe","mintUrl","unsubscribeUrl","mailboxEmail","sender","trackClicks","countOpens","linkOrigin","shortLinks","rewriteLink","linkIndex","url","clickLinkUrl","pixel","orgSettings","openPixelUrl","merge","lead","listUnsubscribeUrl","listUnsubscribeMailto","mailto","message","unresolvedFields","fields","field","screenMessage","subject","text","fromName","fromAddress","html","batch","create","commit","domain","lastIndexOf","local","claimed","messageIdLocalPart","messageIdDomain","gmailMessageId","gmailThreadId","threadId","override","curated","source","standing","recipientDomain","direction","from","to","inReplyTo","byName","nurtureEnrolledLead","bare","replace","found","listMessages","q","maxResults","includeSpamTrash","hit","messages","getMessage","metadataHeaders","headers","header","toLowerCase"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,mBAAmB,QAAQ,wCAAuC;AAC3E,SAASC,eAAe,QAAQ,6BAA4B;AAC5D,SAASC,yBAAyB,QAAQ,6CAA4C;AACtF,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAASC,UAAU,QAAQ,cAAa;AACxC,S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AQ,CAAC,EAAE;IAC7B,IAAI,CAACD,KAAK;QACR,MAAMpI,aAAapK,MAAME,WAAW0D,KAAKvC,YAAY;QACrD,OAAO;IACT;IACA,MAAM2O,UAAU,MAAM9G,OAAOwJ,UAAU,CAACF,IAAIpR,EAAE,EAAE;QAAEuR,iBAAiB;YAAC;SAAU;IAAC;IAC/E,MAAMtC,mBAAUL,wBAAAA,QAAQ4C,OAAO,CAAC5K,IAAI,CAAC,CAAC6K,SAAWA,OAAOhK,IAAI,CAACiK,WAAW,OAAO,+BAA/D9C,sBAA2EpI,KAAK,mBAAI;IACpG,MAAM0E,OAAO7H,SAAS8H,KAAK,CAAClL,WAAWwI,SAAS,CAAC;IACjD,MAAMxG,OAAOrD,KAAK+B,GAAG;IACrB,MAAMgJ,YAAY,MAAMH,aAAa5K,MAAME,WAAW0D,KAAK;QACzDvC;QACAoD;QACA2G,QAAQ;YACNvB,WAAWxI,WAAWwI,SAAS;YAC/BoD,MAAM,WAAEX,wBAAAA,KAAMlL,EAAE,oBAAI;YACpB2F,MAAM;YACN1D;YACA8N,gBAAgBqB,IAAIpR,EAAE;YACtBgQ,eAAeoB,IAAInB,QAAQ;YAC3BhI,WAAW1E,MAAM0E,SAAS;YAC1BgH;QACF;QACA5Q,MAAM;YAAE4J,WAAW1E,MAAM0E,SAAS;YAAEgI,UAAUmB,IAAInB,QAAQ;YAAEhB;QAAQ;QACpEnF,gBAAgBvG,MAAM0E,SAAS;IACjC;IACA,+DAA+D;IAC/D,IAAI0B,WAAW;QACb,MAAMzM,wBAAwB0B,MAAM;YAAEqB;YAAYgC;QAAK;QACvD,MAAM2O,oBAAoB9R,WAAW0D,KAAKvC;IAC5C;IACA,OAAO0J;AACT"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/outreach/src/lib/runtime/send-job.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 { consentGroupForHost } from '@aglyn/aglyn/app-utils/consent-groups'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { randomUUID } from 'node:crypto'\nimport { composeOutreachEmail } from '../engine/compose'\nimport { outreachEmailDomain } from '../engine/do-not-contact-domain'\nimport { planOutreachStepCompletion, type OutreachEnrollmentEvent } from '../engine/enrollment-state'\nimport { evaluateOutreachGates, type OutreachGateBlock, type OutreachGateLookups } from '../engine/gates'\nimport {\n outreachSentToday,\n outreachTickAllowance,\n selectDueOutreachEnrollments,\n type OutreachDueCandidate,\n} from '../engine/sending-capacity'\nimport { readOutreachEnrollCandidates, type OutreachEnrollCandidate } from '../enrollment/enroll-people'\nimport { readOutreachTemplateBody } from '../enrollment/message-templates'\nimport { readOutreachGateLookups } from '../enrollment/gate-lookups'\nimport { mailboxRef } from '../mailboxes/mailbox-credentials'\nimport { outreachEffectiveDailyCap, outreachLocalDay } from '../mailboxes/mailbox-settings'\nimport type { OpenedOutreachMailbox } from '../mailboxes/mailbox-transport'\nimport { effectiveOutreachAllowedCountries } from '../model/compliance-settings'\nimport {\n OUTREACH_COLLECTIONS,\n type OutreachComplianceSettingsDocument,\n type OutreachEnrollment,\n type OutreachMailbox,\n type OutreachSequence,\n type OutreachStepRecord,\n type OutreachTaskStep,\n} from '../model/outreach.types'\nimport { readOutreachComplianceSettingsDoc } from '../storage/compliance-settings-store'\nimport { outreachMailboxSendingDomain, recordOutreachGatewayOutcome } from '../storage/domain-intel-store'\nimport {\n outreachEnrollmentLink,\n outreachEnrollmentPerson,\n outreachOrgCollection,\n readStoredOutreachEnrollment,\n readStoredOutreachMailbox,\n readStoredOutreachSequence,\n} from '../storage/outreach-records'\nimport { GmailTransportError, isReconnectRequired } from '../transport/gmail-errors'\nimport { Rfc5322MessageError } from '../transport/rfc5322'\nimport { sendComposedOutreachEmail } from '../transport/send-message'\nimport { creditOutreachFirstSend } from './campaign-credit'\nimport {\n newOutreachLinkId,\n outreachStoredLink,\n outreachStoredOpen,\n type OutreachStoredLink,\n type OutreachStoredOpen,\n} from './click-link'\nimport { applyOutreachEvent } from './enrollment-events'\nimport { outreachSiteHeld } from './host-suspension'\nimport { stampRecordEmailReach } from '@aglyn/aglyn/plugin-manager/plugin-record-email-state'\nimport { outreachSendDigest, withRecentSend } from './mailbox-health-store'\nimport { noteOutreachMailboxReconnectRequired } from './mailbox-notices'\nimport type { OutreachRuntimeDeps } from './runtime-deps'\nimport { fileOutreachEmail, fileOutreachTask, OUTREACH_TASK_KIND_TO_RECORD } from './timeline'\nimport { outreachListUnsubscribe } from './unsubscribe-link'\n\n/*==========================================\n * THE SEND JOB (AGL-2981): every fifteen minutes, on the console.\n *\n * ## What comes due\n *\n * One collection-group read finds every active enrollment whose next step\n * is due, oldest first, bounded per run. They are grouped by workspace and\n * mailbox, and each group is judged before anything is sent:\n *\n * - the workspace: Outreach switched on, entitled and released to it;\n * - the mailbox: an enrollment whose mailbox is gone, disconnected, or whose\n * member left the organization is STOPPED — nothing will ever send it, and\n * leaving it active would show a sequence that is not running. A paused\n * mailbox, or one waiting to be reconnected, holds its enrollments;\n * - the member it sends as: a lockdown of the platform, the workspace or the\n * member holds everything.\n *\n * ## How much goes\n *\n * The engine's per-run allowance — the day's cap and ramp, spread across\n * the window, at most five a run — picks the enrollments (follow-ups first);\n * a task step is due whenever its time comes and spends no allowance.\n *\n * ## One send, exactly once\n *\n * Each email is CLAIMED before it is sent: a transaction over the enrollment\n * and its mailbox checks the enrollment is still active on the same step\n * with no live claim, and that the mailbox's day has room under its cap,\n * then writes the claim and reserves the day's count. Two runs racing for\n * one enrollment write one claim; two racing for one mailbox's last slot\n * reserve it once. The claim carries the `Message-ID` minted for the send,\n * so a claim a run died holding is settled by finding the message in the\n * mailbox rather than by sending it a second time. A send that fails hands\n * its reservation back.\n *\n * Before it is claimed, every gate is asked again — the do-not-contact\n * list, the suppression lists, the sales topic, the roster, the other\n * sequences — because a person enrolled on Monday can unsubscribe by\n * Thursday. A lookup that could not be made holds the send; a gate that\n * refuses stops the enrollment, saying why.\n *==========================================*/\n\nexport { OUTREACH_SEND_JOB_ID } from '../constants/runtime-jobs'\n\n/** The most due enrollments one run reads. */\nexport const OUTREACH_SEND_SCAN_LIMIT = 300\n\n/** How long a claim holds before a later run settles it. */\nexport const OUTREACH_CLAIM_STALE_MS = 10 * 60_000\n\n/** What one run did, for the tick's answer. */\nexport interface OutreachSendReport {\n [key: string]: number\n due: number\n sent: number\n tasks: number\n /** Stopped by a gate or an unusable mailbox. */\n stopped: number\n /** Paused for the rep to fix, or failed for good. */\n failed: number\n /** Due, and left for a later run: the allowance, a lookup, a hold. */\n held: number\n /** Claims a dead run left, settled. */\n recovered: number\n}\n\ntype Firestore = FirebaseFirestore.Firestore\n\ninterface MailboxRun {\n orgId: string\n org: Record<string, unknown>\n mailbox: OutreachMailbox\n settings: OutreachComplianceSettingsDocument\n report: OutreachSendReport\n deadlineMs: number\n opened: OpenedOutreachMailbox | null\n /** Set once the mailbox itself cannot send this run. */\n stopped: boolean\n templates: Map<string, string | null>\n /**\n * The click-tracking origin for this mailbox's sending domain (AGL-3306):\n * `undefined` until a tracked send first asks, then the verified\n * `https://links.<domain>` or `null` for the console's own address.\n */\n linkOrigin?: string | null\n}\n\nconst blankReport = (): OutreachSendReport => ({\n due: 0,\n sent: 0,\n tasks: 0,\n stopped: 0,\n failed: 0,\n held: 0,\n recovered: 0,\n})\n\n/** Runs the send job once — see the module note. */\nexport async function runOutreachSendJob(\n deps: OutreachRuntimeDeps,\n context: { nowMs: number; deadlineMs: number },\n): Promise<OutreachSendReport> {\n const firestore = deps.firestore()\n const report = blankReport()\n const due = await firestore\n .collectionGroup(OUTREACH_COLLECTIONS.enrollments)\n .where('status', '==', 'active')\n .where('nextDueAtMs', '<=', context.nowMs)\n .orderBy('nextDueAtMs')\n .limit(OUTREACH_SEND_SCAN_LIMIT)\n .get()\n report.due = due.size\n const byOrg = new Map<string, Map<string, OutreachEnrollment[]>>()\n for (const doc of due.docs) {\n const orgId = doc.ref.parent.parent?.id\n const enrollment = readStoredOutreachEnrollment(doc.id, doc.data())\n if (!orgId || !enrollment) continue\n const mailboxes = byOrg.get(orgId) ?? new Map<string, OutreachEnrollment[]>()\n mailboxes.set(enrollment.mailboxId, [...(mailboxes.get(enrollment.mailboxId) ?? []), enrollment])\n byOrg.set(orgId, mailboxes)\n }\n\n for (const [orgId, mailboxes] of byOrg) {\n const waiting = [...mailboxes.values()].reduce((sum, list) => sum + list.length, 0)\n if (deps.now() >= context.deadlineMs) {\n report.held += waiting\n continue\n }\n const orgSnapshot = await firestore.collection('orgs').doc(orgId).get()\n const org = (orgSnapshot.exists ? orgSnapshot.data() : null) as Record<string, unknown> | null\n if (!org || (await deps.orgRefusal(orgId, org))) {\n report.held += waiting\n continue\n }\n const settings = await readOutreachComplianceSettingsDoc(firestore, orgId)\n for (const [mailboxId, enrollments] of mailboxes) {\n await runMailbox(deps, firestore, { orgId, org, mailboxId, enrollments, settings, report, context })\n }\n }\n return report\n}\n\n/** The reason an unusable mailbox stops an enrollment, or `null` for a usable one. */\nasync function unusableMailbox(\n firestore: Firestore,\n orgId: string,\n mailbox: OutreachMailbox | null,\n): Promise<string | null> {\n if (!mailbox) return 'The mailbox this sequence sends from was removed.'\n if (mailbox.status === 'disconnected') return 'The mailbox this sequence sends from was disconnected.'\n const member = await firestore.collection('orgs').doc(orgId).collection('members').doc(mailbox.connectedByUid).get()\n return member.exists\n ? null\n : 'The member who connected the mailbox this sequence sends from is no longer in the organization.'\n}\n\nasync function runMailbox(\n deps: OutreachRuntimeDeps,\n firestore: Firestore,\n input: {\n orgId: string\n org: Record<string, unknown>\n mailboxId: string\n enrollments: OutreachEnrollment[]\n settings: OutreachComplianceSettingsDocument\n report: OutreachSendReport\n context: { nowMs: number; deadlineMs: number }\n },\n): Promise<void> {\n const { orgId, org, report, context } = input\n const nowMs = context.nowMs\n const snapshot = await mailboxRef(firestore, orgId, input.mailboxId).get()\n const mailbox = readStoredOutreachMailbox(input.mailboxId, snapshot.exists ? snapshot.data() : undefined)\n const unusable = await unusableMailbox(firestore, orgId, mailbox)\n if (unusable || !mailbox) {\n for (const enrollment of input.enrollments) {\n const outcome = await applyOutreachEvent(firestore, {\n orgId,\n enrollmentId: enrollment.id,\n event: { type: 'stop', atMs: nowMs, byUid: null, reason: 'gate', detail: unusable },\n nowMs,\n })\n if (outcome.changed) report.stopped += 1\n }\n return\n }\n if (mailbox.status !== 'connected' || (await deps.sendRefusal({ orgId, org, uid: mailbox.connectedByUid }))) {\n report.held += input.enrollments.length\n return\n }\n\n const run: MailboxRun = {\n orgId,\n org,\n mailbox,\n settings: input.settings,\n report,\n deadlineMs: context.deadlineMs,\n opened: null,\n stopped: false,\n templates: new Map(),\n }\n const sequenceIds = [...new Set(input.enrollments.map((enrollment) => enrollment.sequenceId))]\n const sequenceSnapshots = await firestore.getAll(\n ...sequenceIds.map((id) => outreachOrgCollection(firestore, orgId, 'sequences').doc(id)),\n )\n const sequences = new Map<string, OutreachSequence>()\n sequenceSnapshots.forEach((sequenceSnapshot, index) => {\n const sequence = readStoredOutreachSequence(\n sequenceIds[index],\n sequenceSnapshot.exists ? sequenceSnapshot.data() : undefined,\n )\n if (sequence) sequences.set(sequence.id, sequence)\n })\n\n const candidates: OutreachDueCandidate[] = []\n for (const enrollment of input.enrollments) {\n const sequence = sequences.get(enrollment.sequenceId)\n const claim = enrollment.sendClaim\n if (claim && nowMs - claim.atMs < OUTREACH_CLAIM_STALE_MS) continue\n if (claim && sequence) {\n if (await recoverClaim(deps, firestore, run, enrollment, sequence)) report.recovered += 1\n continue\n }\n if (sequence) candidates.push({ enrollment, sequence })\n }\n\n const allowance = outreachTickAllowance({ mailbox, nowMs })\n const selection = selectDueOutreachEnrollments({ candidates, mailbox, nowMs, allowance: allowance.allowance })\n report.held += selection.deferred.length\n\n for (const candidate of selection.tasks) {\n if (deps.now() >= context.deadlineMs) {\n report.held += 1\n continue\n }\n if (await runTaskStep(deps, firestore, run, candidate)) report.tasks += 1\n }\n if (!selection.emails.length) return\n\n // The people behind the emails, read once per site: the contact and its\n // company, and every lookup the gates decide on.\n const people = new Map<string, OutreachEnrollCandidate>()\n const lookups = new Map<string, OutreachGateLookups>()\n const byHost = new Map<string, OutreachEnrollment[]>()\n for (const candidate of selection.emails) {\n const enrollment = candidate.enrollment as OutreachEnrollment\n byHost.set(enrollment.hostId, [...(byHost.get(enrollment.hostId) ?? []), enrollment])\n }\n const siteNames = new Map<string, string>()\n const siteDocs = new Map<string, Record<string, unknown> | null>()\n // Sites under a staff suspension (AGL-3356): their people are held, not\n // stamped, so the step sends on the first run after the lift.\n const heldSites = new Set<string>()\n for (const [hostId, enrollments] of byHost) {\n const consentGroup = consentGroupForHost(org, hostId)\n const contactGroupId = consentGroup.groupId\n // Each by the record it names — the contact, or the lead while the\n // person is one (AGL-3234) — keyed by that record's id.\n const [candidatesRead, lookupsRead, host] = await Promise.all([\n readOutreachEnrollCandidates({\n orgId,\n hostId,\n contactGroupId,\n people: enrollments.map(outreachEnrollmentPerson),\n }),\n readOutreachGateLookups(firestore, {\n orgId,\n hostId,\n consentHostIds: consentGroup.hostIds,\n consentAwaitsConfirmation: consentGroup.awaitsConfirmation,\n gateway: {\n resolveMx: deps.resolveMx,\n resolveAddress: deps.resolveAddress,\n nowMs,\n sendingDomain: outreachMailboxSendingDomain(mailbox),\n },\n people: enrollments.map((enrollment) => {\n const person = outreachEnrollmentPerson(enrollment)\n return {\n personId: person.id,\n contactId: person.kind === 'contact' ? person.id : null,\n leadId: person.kind === 'lead' ? person.id : null,\n email: enrollment.email,\n }\n }),\n }),\n firestore.collection('hosts').doc(hostId).get(),\n ])\n for (const person of candidatesRead) people.set(person.personId, person)\n for (const [personId, answer] of lookupsRead) lookups.set(personId, answer)\n siteNames.set(hostId, host.exists ? String(host.get('name') ?? '') : '')\n siteDocs.set(hostId, host.exists ? ((host.data() as Record<string, unknown>) ?? null) : null)\n if (host.exists && outreachSiteHeld(host.data() as Record<string, unknown>, nowMs)) {\n heldSites.add(hostId)\n }\n }\n\n for (const candidate of selection.emails) {\n if (run.stopped || deps.now() >= context.deadlineMs) {\n report.held += 1\n continue\n }\n const enrollment = candidate.enrollment as OutreachEnrollment\n if (heldSites.has(enrollment.hostId)) {\n report.held += 1\n continue\n }\n const personId = outreachEnrollmentPerson(enrollment).id\n await runEmailStep(deps, firestore, run, {\n enrollment,\n sequence: candidate.sequence as OutreachSequence,\n person: people.get(personId) ?? null,\n lookups: lookups.get(personId) ?? null,\n siteName: siteNames.get(enrollment.hostId) ?? '',\n site: siteDocs.get(enrollment.hostId) ?? null,\n })\n }\n}\n\n/** Any lookup the runtime could not make: the send waits for a run that can. */\nfunction uncheckable(lookups: OutreachGateLookups | null): boolean {\n return !lookups || Object.values(lookups).some((value) => value === null)\n}\n\n/** The event a gate's refusal ends an enrollment with. */\nfunction gateEvent(blocks: readonly OutreachGateBlock[], atMs: number): OutreachEnrollmentEvent {\n const optedOut = blocks.find((block) => block.code === 'do_not_contact' || block.code === 'sales_opted_out')\n if (optedOut) return { type: 'opt_out', atMs, reason: 'do_not_contact', detail: optedOut.reason }\n return { type: 'stop', atMs, byUid: null, reason: 'gate', detail: blocks.map((block) => block.reason).join(' ') }\n}\n\n/**\n * The click-tracking origin for mail sent as `senderAddress`, or `null` for\n * the console's own address — which is also what a failed lookup reads as: a\n * link on the app address still counts the click, so no send waits on it.\n */\nasync function trackingLinkOrigin(\n deps: OutreachRuntimeDeps,\n orgId: string,\n senderAddress: string,\n): Promise<string | null> {\n if (!deps.clickLinkOrigin) return null\n try {\n return await deps.clickLinkOrigin({ orgId, senderAddress })\n } catch (error) {\n console.warn('[outreach] the click-tracking host could not be read; links use the app address', error)\n return null\n }\n}\n\n/** The sender line a mailbox's mail goes out with. */\nconst senderOf = (mailbox: OutreachMailbox) => ({\n address: mailbox.sendAs || mailbox.email,\n name: mailbox.displayName || null,\n})\n\nasync function openClient(deps: OutreachRuntimeDeps, run: MailboxRun) {\n const opened = (run.opened ??= await deps.openMailbox(run.mailbox.id))\n if (opened.ok === true) return opened.client\n run.stopped = true\n if (opened.reason !== 'not-configured') {\n await noteOutreachMailboxReconnectRequired(deps, {\n orgId: run.orgId,\n mailboxId: run.mailbox.id,\n errorCode: opened.reason,\n nowMs: deps.now(),\n })\n }\n return null\n}\n\n/**\n * Claims one step: the enrollment still active on the same step with no\n * live claim, and — for an email — a slot under the mailbox's cap today,\n * reserved in the same transaction.\n */\nasync function claimStep(\n deps: OutreachRuntimeDeps,\n firestore: Firestore,\n run: MailboxRun,\n enrollment: OutreachEnrollment,\n messageId: string | null,\n): Promise<'claimed' | 'taken' | 'cap'> {\n const enrollmentRef = outreachOrgCollection(firestore, run.orgId, 'enrollments').doc(enrollment.id)\n const boxRef = mailboxRef(firestore, run.orgId, run.mailbox.id)\n const nowMs = deps.now()\n return firestore.runTransaction(async (transaction) => {\n const [current, box] = await Promise.all([transaction.get(enrollmentRef), transaction.get(boxRef)])\n const stored = readStoredOutreachEnrollment(enrollment.id, current.exists ? current.data() : undefined)\n const claim = stored?.sendClaim\n if (\n !stored ||\n stored.status !== 'active' ||\n stored.stepIndex !== enrollment.stepIndex ||\n stored.nextDueAtMs === null ||\n stored.nextDueAtMs > nowMs ||\n (claim && nowMs - claim.atMs < OUTREACH_CLAIM_STALE_MS)\n ) {\n return 'taken'\n }\n if (messageId) {\n const mailbox = readStoredOutreachMailbox(run.mailbox.id, box.exists ? box.data() : undefined)\n if (!mailbox || mailbox.status !== 'connected') return 'taken'\n const sent = outreachSentToday(mailbox.health, nowMs, mailbox.timezone)\n if (sent >= outreachEffectiveDailyCap(mailbox, nowMs)) return 'cap'\n transaction.update(boxRef, {\n 'health.sentToday': sent + 1,\n 'health.sentOnDay': outreachLocalDay(nowMs, mailbox.timezone),\n })\n }\n transaction.update(enrollmentRef, {\n sendClaim: { token: randomUUID(), atMs: nowMs, stepIndex: enrollment.stepIndex, messageId },\n updatedAtMs: nowMs,\n })\n return 'claimed'\n })\n}\n\n/** Drops a claim, and hands an email's reservation back to the mailbox's day. */\nasync function releaseClaim(\n deps: OutreachRuntimeDeps,\n firestore: Firestore,\n run: MailboxRun,\n enrollment: Pick<OutreachEnrollment, 'id'>,\n reserved: boolean,\n event: OutreachEnrollmentEvent | null = null,\n): Promise<void> {\n const nowMs = deps.now()\n await applyOutreachEvent(firestore, {\n orgId: run.orgId,\n enrollmentId: enrollment.id,\n event,\n extra: () => ({ sendClaim: null }),\n nowMs,\n })\n if (!reserved) return\n const boxRef = mailboxRef(firestore, run.orgId, run.mailbox.id)\n await firestore.runTransaction(async (transaction) => {\n const box = await transaction.get(boxRef)\n const mailbox = readStoredOutreachMailbox(run.mailbox.id, box.exists ? box.data() : undefined)\n if (!mailbox || mailbox.health?.sentOnDay !== outreachLocalDay(nowMs, mailbox.timezone)) return\n transaction.update(boxRef, { 'health.sentToday': Math.max(0, (Number(mailbox.health.sentToday) || 0) - 1) })\n })\n}\n\n/**\n * Records a step that ran: the engine's completion patch, the claim\n * cleared, the step's record kept — and for an email the mailbox's send on\n * its day, its last-sent time and its window of recent sends. Refuses\n * (answers false) when the claim is no longer this run's.\n */\nasync function completeStep(\n deps: OutreachRuntimeDeps,\n firestore: Firestore,\n run: MailboxRun,\n input: {\n enrollment: OutreachEnrollment\n sequence: OutreachSequence\n record: OutreachStepRecord\n sent: { messageId: string; threadId: string; subject: string } | null\n claimMessageId: string | null\n },\n): Promise<boolean> {\n const enrollmentRef = outreachOrgCollection(firestore, run.orgId, 'enrollments').doc(input.enrollment.id)\n const boxRef = mailboxRef(firestore, run.orgId, run.mailbox.id)\n const nowMs = deps.now()\n /*\n * Whether this is the FIRST email this person has had from the sequence\n * (AGL-3239), decided from the same read the step is recorded against and\n * so re-decided on every transaction retry. It is what `stats.people`\n * counts: the denominator of every engagement rate, and the thing\n * `stats.sent` is not, since one person takes several steps.\n */\n let firstEmail = false\n // The first email of this person's to carry a tracking image (AGL-3395):\n // what `stats.openPeople`, the open rate's denominator, counts.\n let firstOpenTracked = false\n const completed = await firestore.runTransaction(async (transaction) => {\n const [current, box] = await Promise.all([\n transaction.get(enrollmentRef),\n input.sent ? transaction.get(boxRef) : Promise.resolve(null),\n ])\n const stored = readStoredOutreachEnrollment(input.enrollment.id, current.exists ? current.data() : undefined)\n if (!stored?.sendClaim || stored.sendClaim.messageId !== input.claimMessageId) return false\n if (stored.stepIndex !== input.enrollment.stepIndex) return false\n // The step RAN, whatever happened to the enrollment while it did — a\n // member paused it, a reply stopped it — so it is recorded as run, and a\n // resume never sends it twice.\n firstEmail =\n input.sent !== null &&\n !(stored.stepRecords ?? []).some((record) => record.kind === 'email')\n firstOpenTracked =\n input.sent !== null &&\n input.record.openTracked === true &&\n !(stored.stepRecords ?? []).some((record) => record.openTracked === true)\n const plan = planOutreachStepCompletion({\n enrollment: { ...stored, status: 'active' },\n sequence: input.sequence,\n mailbox: run.mailbox,\n completedAtMs: nowMs,\n sent: input.sent,\n random: deps.random,\n })\n const patch: Record<string, unknown> = {\n sendClaim: null,\n stepRecords: [...(stored.stepRecords ?? []), input.record].slice(-20),\n updatedAtMs: nowMs,\n ...(plan.patch ?? {}),\n }\n if (stored.status !== 'active') {\n patch['status'] = stored.status\n if (stored.status !== 'paused') patch['nextDueAtMs'] = null\n }\n transaction.update(enrollmentRef, patch)\n if (input.sent && box?.exists) {\n const mailbox = readStoredOutreachMailbox(run.mailbox.id, box.data())\n if (mailbox) {\n const day = outreachLocalDay(nowMs, mailbox.timezone)\n const counts = mailbox.health?.daily?.[day] ?? { sent: 0, bounces: 0, replies: 0 }\n transaction.update(boxRef, {\n 'health.lastSentAtMs': nowMs,\n 'health.lastErrorAtMs': null,\n 'health.lastErrorCode': null,\n [`health.daily.${day}`]: { ...counts, sent: (Number(counts.sent) || 0) + 1 },\n 'health.recentSends': withRecentSend(mailbox.health?.recentSends, {\n id: outreachSendDigest(input.sent.messageId),\n atMs: nowMs,\n bounced: false,\n }),\n updatedAtMs: nowMs,\n })\n }\n }\n return true\n })\n if (completed && input.sent) {\n await bumpOutreachSequenceStats(firestore, {\n orgId: run.orgId,\n sequenceId: input.sequence.id,\n firstEmail,\n trackedLinks: input.record.links?.length ?? 0,\n openTracked: input.record.openTracked === true,\n firstOpenTracked,\n })\n }\n return completed\n}\n\n/**\n * The sequence's send counters (AGL-3239), written outside the enrollment's\n * transaction.\n *\n * One sequence holds every enrollment, so a transaction over it would\n * serialise every recipient against every other; `FieldValue.increment` is a\n * blind write with nothing to contend on. It is bookkeeping beside the act,\n * so a failure is logged and the send stands — the email has already left.\n *\n * `clickTracked` is stamped by the first send that actually carried a\n * rewritten link, never by the SETTING: a sequence with the setting on whose\n * emails have no links in them measured nothing, and the report must say\n * \"not measured\" for it rather than publish a 0% click rate.\n */\nasync function bumpOutreachSequenceStats(\n firestore: Firestore,\n input: {\n orgId: string\n sequenceId: string\n firstEmail: boolean\n trackedLinks: number\n openTracked?: boolean\n firstOpenTracked?: boolean\n },\n): Promise<void> {\n if (!input.sequenceId) return\n await outreachOrgCollection(firestore, input.orgId, 'sequences')\n .doc(input.sequenceId)\n .update({\n 'stats.sent': FieldValue.increment(1),\n ...(input.firstEmail ? { 'stats.people': FieldValue.increment(1) } : {}),\n ...(input.trackedLinks > 0 ? { 'stats.clickTracked': true } : {}),\n // Stamped by a send that carried the image, never by the setting, for\n // `clickTracked`'s reason (AGL-3395).\n ...(input.openTracked ? { 'stats.openTracked': true } : {}),\n ...(input.firstOpenTracked ? { 'stats.openPeople': FieldValue.increment(1) } : {}),\n })\n .catch((error: unknown) => {\n console.warn('[outreach] a send could not be counted on its sequence', error)\n })\n}\n\n/** One task step: the rep's task on the contact, then the step recorded. */\nasync function runTaskStep(\n deps: OutreachRuntimeDeps,\n firestore: Firestore,\n run: MailboxRun,\n candidate: OutreachDueCandidate,\n): Promise<boolean> {\n const enrollment = candidate.enrollment as OutreachEnrollment\n const sequence = candidate.sequence as OutreachSequence\n const step = sequence.steps[enrollment.stepIndex] as OutreachTaskStep\n if ((await claimStep(deps, firestore, run, enrollment, null)) !== 'claimed') return false\n const nowMs = deps.now()\n let taskId: string | null\n try {\n const written = await fileOutreachTask(deps, {\n orgId: run.orgId,\n hostId: enrollment.hostId,\n link: outreachEnrollmentLink(enrollment),\n dedupeKey: `step:${enrollment.id}:${step.id}`,\n title: step.title,\n notes: `From sequence step ${enrollment.stepIndex + 1}.`,\n kind: OUTREACH_TASK_KIND_TO_RECORD[step.taskKind] ?? 'todo',\n dueAtMs: nowMs,\n assigneeUid: run.mailbox.connectedByUid,\n })\n taskId = written?.ok ? written.id : null\n if (written?.ok === false) console.warn(`[outreach] a task step's task was not filed: ${written.error}`)\n } catch (error) {\n // The record system failed rather than refused: the step waits for a\n // run that can file its task.\n console.error('[outreach] filing a task step failed; the step waits', error)\n await releaseClaim(deps, firestore, run, enrollment, false)\n return false\n }\n return completeStep(deps, firestore, run, {\n enrollment,\n sequence,\n record: { stepIndex: enrollment.stepIndex, stepId: step.id, kind: 'task', atMs: nowMs, taskId },\n sent: null,\n claimMessageId: null,\n })\n}\n\n/** A template's body, read through the record system once per run. */\nasync function templateBody(run: MailboxRun, templateId: string): Promise<string | null> {\n if (!run.templates.has(templateId)) {\n run.templates.set(templateId, await readOutreachTemplateBody(run.orgId, templateId))\n }\n return run.templates.get(templateId) ?? null\n}\n\nasync function runEmailStep(\n deps: OutreachRuntimeDeps,\n firestore: Firestore,\n run: MailboxRun,\n input: {\n enrollment: OutreachEnrollment\n sequence: OutreachSequence\n person: OutreachEnrollCandidate | null\n lookups: OutreachGateLookups | null\n siteName: string\n /** The site's document, for the phishing screen (AGL-3356). */\n site?: Record<string, unknown> | null\n },\n): Promise<void> {\n const { enrollment, sequence, person } = input\n const { report, mailbox } = run\n const nowMs = deps.now()\n const stop = async (event: OutreachEnrollmentEvent, counter: 'stopped' | 'failed') => {\n const outcome = await applyOutreachEvent(firestore, { orgId: run.orgId, enrollmentId: enrollment.id, event, nowMs })\n if (outcome.changed) report[counter] += 1\n }\n\n // Every gate again, on the person as they stand now.\n if (!person?.contact) {\n return stop(\n {\n type: 'stop',\n atMs: nowMs,\n byUid: null,\n reason: 'gate',\n detail:\n enrollment.target === 'lead'\n ? \"This lead no longer exists in the sequence's site's CRM.\"\n : 'This contact no longer exists in the CRM.',\n },\n 'stopped',\n )\n }\n if (person.convertedContactId && enrollment.target === 'lead') {\n // The lead converted and the enrollment has not followed it yet: the\n // conversion's listener re-points it, and the next run sends as the contact.\n report.held += 1\n return\n }\n if (!person.visible) {\n return stop(\n { type: 'stop', atMs: nowMs, byUid: null, reason: 'gate', detail: \"This contact is no longer in the sequence's site's CRM.\" },\n 'stopped',\n )\n }\n if (uncheckable(input.lookups)) {\n report.held += 1\n return\n }\n const contactGroupId = consentGroupForHost(run.org, enrollment.hostId).groupId\n const gate = evaluateOutreachGates({\n email: enrollment.email,\n contact: person.contact,\n contactGroupId,\n company: person.company,\n settings: {\n ...sequence.settings,\n allowedCountries: effectiveOutreachAllowedCountries(\n sequence.settings.allowedCountries,\n run.settings.allowedCountries,\n ),\n },\n personalLine: enrollment.personalLine,\n attestations: enrollment.attestations,\n enrollmentId: enrollment.id,\n gatewayHoldReleased: typeof enrollment.gatewayHold?.releasedAtMs === 'number',\n lookups: input.lookups as OutreachGateLookups,\n })\n if (!gate.allowed) return stop(gateEvent(gate.blocks, nowMs), 'stopped')\n if (gate.hold) {\n // The gateway refused this organization twice lately and delivered\n // nothing (AGL-3326): the send is held, as a pause a member resumes\n // from the enrollment row, and nothing goes into it until they do.\n const hold = gate.hold\n const outcome = await applyOutreachEvent(firestore, {\n orgId: run.orgId,\n enrollmentId: enrollment.id,\n event: { type: 'pause', atMs: nowMs, byUid: null, reason: 'gateway_blocked_here', detail: hold.reason },\n extra: () => ({\n gatewayHold: { gateway: hold.gateway, heldAtMs: nowMs, releasedByUid: null, releasedAtMs: null },\n }),\n nowMs,\n })\n if (outcome.changed) report.held += 1\n return\n }\n\n /*\n * The email, with its way out. The footer's \"reply 'no'\" line and the\n * postal address are always there (compose refuses without them). The\n * `List-Unsubscribe` header is the sequence's own setting (AGL-3296), read\n * here per send like click tracking, and absent reads as off.\n */\n const unsubscribe = outreachListUnsubscribe({\n enabled: sequence.settings.listUnsubscribe,\n mintUrl: () => deps.unsubscribeUrl({ orgId: run.orgId, enrollmentId: enrollment.id }),\n mailboxEmail: mailbox.email,\n })\n if (unsubscribe.status === 'unavailable') {\n // On, but no link can be minted — no secret, or no HTTPS console origin\n // — and an email without the way out its sequence promised does not leave.\n console.error('[outreach] no unsubscribe link could be minted; nothing sends until one can')\n run.stopped = true\n report.held += 1\n return\n }\n const step = sequence.steps[enrollment.stepIndex]\n const sender = senderOf(mailbox)\n /*\n * Click tracking is the sequence's own setting (AGL-3239) and is read\n * here, per send, rather than once per run: a member turning it off\n * applies to the next email, not to the next hour. Each link becomes a\n * short link (AGL-3297) whose document is written below, before the email\n * leaves; a link that cannot be made is left exactly as the step wrote it.\n */\n if ((sequence.settings.trackClicks || sequence.settings.countOpens) && run.linkOrigin === undefined) {\n run.linkOrigin = await trackingLinkOrigin(deps, run.orgId, sender.address)\n }\n const shortLinks: Array<{ id: string; doc: OutreachStoredLink }> = []\n const rewriteLink = sequence.settings.trackClicks\n ? (link: { url: string; index: number }) => {\n const doc = outreachStoredLink(\n {\n orgId: run.orgId,\n enrollmentId: enrollment.id,\n stepIndex: enrollment.stepIndex,\n linkIndex: link.index,\n url: link.url,\n },\n nowMs,\n )\n const id = newOutreachLinkId()\n const url = doc ? deps.clickLinkUrl(id, run.linkOrigin ?? null) : null\n if (!doc || !url) return null\n shortLinks.push({ id, doc })\n return url\n }\n : null\n /*\n * The tracking image (AGL-3395), for a sequence that counts opens: a short\n * link of kind `open` on the same host, stored with the links below. None\n * minted — no HTTPS origin — and the email goes out as plain text alone.\n */\n let pixel: { id: string; doc: OutreachStoredOpen; url: string } | null = null\n if (sequence.settings.countOpens) {\n const doc = outreachStoredOpen(\n { orgId: run.orgId, enrollmentId: enrollment.id, stepIndex: enrollment.stepIndex },\n nowMs,\n )\n const id = newOutreachLinkId()\n const url = doc ? deps.clickLinkUrl(id, run.linkOrigin ?? null) : null\n if (doc && url) pixel = { id, doc, url }\n }\n const composed = composeOutreachEmail({\n sequence,\n enrollment,\n orgSettings: run.settings,\n rewriteLink,\n openPixelUrl: pixel?.url ?? null,\n merge: {\n // For a lead, the contact-shaped view of it (`leadAsContact`), so a\n // step written with `{{contact.*}}` reads the lead; `{{lead.*}}` reads\n // the lead's own document beside it.\n contact: person.contact,\n contactGroupId,\n lead: person.lead,\n sender: { name: mailbox.displayName, email: sender.address },\n site: { name: input.siteName },\n },\n templateBody: step?.kind === 'email' && step.templateId ? await templateBody(run, step.templateId) : null,\n listUnsubscribeUrl: unsubscribe.status === 'ready' ? unsubscribe.url : null,\n listUnsubscribeMailto: unsubscribe.status === 'ready' ? unsubscribe.mailto : null,\n })\n if (composed.error || !composed.email) {\n const code = composed.error?.code\n if (code === 'missing_postal_address' || code === 'missing_legal_name') {\n // The organization's footer: nothing of theirs sends until it is set.\n run.stopped = true\n report.held += 1\n return\n }\n if (code === 'invalid_recipient' || code === 'missing_thread' || code === 'not_an_email_step') {\n return stop({ type: 'send_failed', atMs: nowMs, detail: composed.error?.message }, 'failed')\n }\n // The sequence's own words: the rep fixes the step and resumes.\n return stop({ type: 'pause', atMs: nowMs, byUid: null, detail: composed.error?.message }, 'failed')\n }\n if (composed.unresolvedFields.length) {\n const fields = composed.unresolvedFields.map((field) => `{{${field}}}`).join(', ')\n return stop(\n {\n type: 'pause',\n atMs: nowMs,\n byUid: null,\n detail: `Paused before sending: this contact has nothing for ${fields}. Fill it in and resume.`,\n },\n 'failed',\n )\n }\n\n /*\n * THE PHISHING SCREEN (AGL-3356): the same one every tenant message\n * passes, asked of the email as composed and before anything is claimed,\n * stored or sent. A hold pauses this enrollment with the reason; staff\n * decide it in the abuse queue, and a member resumes it once released.\n */\n if (deps.screenMessage) {\n const held = await deps.screenMessage({\n orgId: run.orgId,\n org: run.org,\n hostId: enrollment.hostId,\n host: input.site ?? null,\n subject: composed.email.subject,\n text: composed.email.text,\n fromName: mailbox.displayName ?? null,\n fromAddress: sender.address,\n })\n if (held) return stop({ type: 'pause', atMs: nowMs, byUid: null, detail: held }, 'failed')\n }\n\n /*\n * The short links' documents, before anything is claimed or sent: a link\n * in an email that already left must resolve on the first click. A write\n * that fails holds the send for the next run, which mints new ones — an\n * orphaned document is inert, an email whose links go nowhere is not.\n */\n if (shortLinks.length || (pixel && composed.email.html)) {\n try {\n const batch = firestore.batch()\n for (const link of shortLinks) {\n batch.create(firestore.collection(OUTREACH_COLLECTIONS.links).doc(link.id), link.doc)\n }\n if (pixel && composed.email.html) {\n batch.create(firestore.collection(OUTREACH_COLLECTIONS.links).doc(pixel.id), pixel.doc)\n }\n await batch.commit()\n } catch (error) {\n console.error('[outreach] the short links could not be stored; the send waits for the next run', error)\n report.held += 1\n return\n }\n }\n\n // Claimed, then sent, then recorded.\n const domain = sender.address.slice(sender.address.lastIndexOf('@') + 1)\n const local = randomUUID()\n const messageId = `<${local}@${domain}>`\n const claimed = await claimStep(deps, firestore, run, enrollment, messageId)\n if (claimed !== 'claimed') {\n if (claimed === 'cap') run.stopped = true\n report.held += 1\n return\n }\n const client = await openClient(deps, run)\n if (!client) {\n await releaseClaim(deps, firestore, run, enrollment, true)\n report.held += 1\n return\n }\n let sent: Awaited<ReturnType<typeof sendComposedOutreachEmail>>\n try {\n sent = await sendComposedOutreachEmail(client, composed.email, sender, {\n messageIdLocalPart: local,\n messageIdDomain: domain,\n })\n } catch (error) {\n if (error instanceof Rfc5322MessageError || (error instanceof GmailTransportError && error.code === 'invalid_request')) {\n await releaseClaim(deps, firestore, run, enrollment, true, {\n type: 'send_failed',\n atMs: deps.now(),\n detail: `Gmail refused the email: ${error.message}`,\n })\n report.failed += 1\n return\n }\n await releaseClaim(deps, firestore, run, enrollment, true)\n report.held += 1\n run.stopped = true\n const code = error instanceof GmailTransportError ? error.code : 'unexpected'\n if (isReconnectRequired(error)) {\n await noteOutreachMailboxReconnectRequired(deps, {\n orgId: run.orgId,\n mailboxId: mailbox.id,\n errorCode: code,\n nowMs: deps.now(),\n })\n } else {\n await mailboxRef(firestore, run.orgId, mailbox.id)\n .update({ 'health.lastErrorAtMs': deps.now(), 'health.lastErrorCode': code })\n .catch(() => undefined)\n }\n console.error(`[outreach] a send from a mailbox failed (${code}); its sends wait for the next run`)\n return\n }\n\n const record: OutreachStepRecord = {\n stepIndex: enrollment.stepIndex,\n stepId: step?.id ?? '',\n kind: 'email',\n atMs: deps.now(),\n gmailMessageId: sent.gmailMessageId,\n gmailThreadId: sent.threadId,\n messageId: sent.messageId,\n subject: sent.subject,\n ...(composed.email.trackedLinks.length ? { links: composed.email.trackedLinks } : {}),\n ...(composed.email.html ? { openTracked: true } : {}),\n // Sent as this person's own copy of the step (AGL-3324), and whose words.\n ...(composed.override ? { curated: composed.override.source } : {}),\n }\n await completeStep(deps, firestore, run, {\n enrollment,\n sequence,\n record,\n sent: { messageId: sent.messageId, threadId: sent.threadId, subject: sent.subject },\n claimMessageId: messageId,\n })\n report.sent += 1\n // The gateway ledger (AGL-3326): one more send into the domain's gateway,\n // which the sync credits as delivered a day from now if nothing bounces.\n const standing = (input.lookups as OutreachGateLookups).gateway\n const recipientDomain = outreachEmailDomain(enrollment.email)\n if (standing && recipientDomain) {\n await recordOutreachGatewayOutcome(firestore, run.orgId, {\n sendingDomain: outreachMailboxSendingDomain(mailbox),\n gateway: standing.gateway,\n outcome: 'sent',\n atMs: record.atMs,\n })\n }\n await fileOutreachEmail(deps, {\n orgId: run.orgId,\n hostId: enrollment.hostId,\n link: outreachEnrollmentLink(enrollment),\n direction: 'outbound',\n subject: sent.subject,\n from: sender.address,\n to: composed.email.to,\n messageId: sent.messageId,\n inReplyTo: composed.email.inReplyTo ?? null,\n body: composed.email.text,\n atMs: record.atMs,\n byUid: mailbox.connectedByUid,\n byName: mailbox.displayName || null,\n })\n // The first email is the touch (AGL-3254): `sent` on the sequence's\n // campaigns, and the person's record credited to the first of them.\n // Judged on the enrollment as it was read, before this step's record.\n await creditOutreachFirstSend(deps, { enrollment, atMs: record.atMs })\n await nurtureEnrolledLead(run, enrollment)\n}\n\n/**\n * A lead an email step reached is no longer untouched (AGL-3446): the record\n * system hears the send was delivered, and moves a New lead to Nurturing\n * through the record email-state seam's `reached` (AGL-3080). Called only\n * once a send is recorded, so an enrollment whose steps never go out leaves\n * its lead where it stood. Never throws.\n */\nasync function nurtureEnrolledLead(run: MailboxRun, enrollment: OutreachEnrollment): Promise<void> {\n if (enrollment.target !== 'lead' || !enrollment.leadId || !enrollment.email) return\n await stampRecordEmailReach({ orgId: run.orgId, hostId: enrollment.hostId, emails: [enrollment.email] })\n}\n\n/**\n * Settles a claim a run died holding. A task step's claim is dropped and\n * the step runs again (its task is filed once however often it is asked).\n * An email's claim looks for the message it minted in the mailbox: found,\n * the send happened and is recorded; not found, it did not, and the claim\n * and its reservation are handed back for the next run.\n */\nasync function recoverClaim(\n deps: OutreachRuntimeDeps,\n firestore: Firestore,\n run: MailboxRun,\n enrollment: OutreachEnrollment,\n sequence: OutreachSequence,\n): Promise<boolean> {\n const claim = enrollment.sendClaim\n if (!claim) return false\n if (!claim.messageId) {\n await releaseClaim(deps, firestore, run, enrollment, false)\n return true\n }\n const client = await openClient(deps, run)\n if (!client) return false\n const bare = claim.messageId.replace(/^<|>$/g, '')\n const found = await client.listMessages({ q: `rfc822msgid:${bare}`, maxResults: 1, includeSpamTrash: true })\n const hit = found.messages[0]\n if (!hit) {\n await releaseClaim(deps, firestore, run, enrollment, true)\n return true\n }\n const message = await client.getMessage(hit.id, { metadataHeaders: ['Subject'] })\n const subject = message.headers.find((header) => header.name.toLowerCase() === 'subject')?.value ?? ''\n const step = sequence.steps[enrollment.stepIndex]\n const atMs = deps.now()\n const completed = await completeStep(deps, firestore, run, {\n enrollment,\n sequence,\n record: {\n stepIndex: enrollment.stepIndex,\n stepId: step?.id ?? '',\n kind: 'email',\n atMs,\n gmailMessageId: hit.id,\n gmailThreadId: hit.threadId,\n messageId: claim.messageId,\n subject,\n },\n sent: { messageId: claim.messageId, threadId: hit.threadId, subject },\n claimMessageId: claim.messageId,\n })\n // A recovered first email is still the first email (AGL-3254).\n if (completed) {\n await creditOutreachFirstSend(deps, { enrollment, atMs })\n await nurtureEnrolledLead(run, enrollment)\n }\n return completed\n}\n"],"names":["consentGroupForHost","FieldValue","randomUUID","composeOutreachEmail","outreachEmailDomain","planOutreachStepCompletion","evaluateOutreachGates","outreachSentToday","outreachTickAllowance","selectDueOutreachEnrollments","readOutreachEnrollCandidates","readOutreachTemplateBody","readOutreachGateLookups","mailboxRef","outreachEffectiveDailyCap","outreachLocalDay","effectiveOutreachAllowedCountries","OUTREACH_COLLECTIONS","readOutreachComplianceSettingsDoc","outreachMailboxSendingDomain","recordOutreachGatewayOutcome","outreachEnrollmentLink","outreachEnrollmentPerson","outreachOrgCollection","readStoredOutreachEnrollment","readStoredOutreachMailbox","readStoredOutreachSequence","GmailTransportError","isReconnectRequired","Rfc5322MessageError","sendComposedOutreachEmail","creditOutreachFirstSend","newOutreachLinkId","outreachStoredLink","outreachStoredOpen","applyOutreachEvent","outreachSiteHeld","stampRecordEmailReach","outreachSendDigest","withRecentSend","noteOutreachMailboxReconnectRequired","fileOutreachEmail","fileOutreachTask","OUTREACH_TASK_KIND_TO_RECORD","outreachListUnsubscribe","OUTREACH_SEND_JOB_ID","OUTREACH_SEND_SCAN_LIMIT","OUTREACH_CLAIM_STALE_MS","blankReport","due","sent","tasks","stopped","failed","held","recovered","runOutreachSendJob","deps","context","firestore","report","collectionGroup","enrollments","where","nowMs","orderBy","limit","get","size","byOrg","Map","doc","docs","mailboxes","orgId","ref","parent","id","enrollment","data","set","mailboxId","waiting","values","reduce","sum","list","length","now","deadlineMs","orgSnapshot","collection","org","exists","orgRefusal","settings","runMailbox","unusableMailbox","mailbox","status","member","connectedByUid","input","snapshot","undefined","unusable","outcome","enrollmentId","event","type","atMs","byUid","reason","detail","changed","sendRefusal","uid","run","opened","templates","sequenceIds","Set","map","sequenceId","sequenceSnapshots","getAll","sequences","forEach","sequenceSnapshot","index","sequence","candidates","claim","sendClaim","recoverClaim","push","allowance","selection","deferred","candidate","runTaskStep","emails","people","lookups","byHost","hostId","siteNames","siteDocs","heldSites","host","consentGroup","contactGroupId","groupId","candidatesRead","lookupsRead","Promise","all","consentHostIds","hostIds","consentAwaitsConfirmation","awaitsConfirmation","gateway","resolveMx","resolveAddress","sendingDomain","person","personId","contactId","kind","leadId","email","answer","String","add","has","runEmailStep","siteName","site","uncheckable","Object","some","value","gateEvent","blocks","optedOut","find","block","code","join","trackingLinkOrigin","senderAddress","clickLinkOrigin","error","console","warn","senderOf","address","sendAs","name","displayName","openClient","openMailbox","ok","client","errorCode","claimStep","messageId","enrollmentRef","boxRef","runTransaction","transaction","current","box","stored","stepIndex","nextDueAtMs","health","timezone","update","token","updatedAtMs","releaseClaim","reserved","extra","sentOnDay","Math","max","Number","sentToday","completeStep","firstEmail","firstOpenTracked","completed","plan","resolve","claimMessageId","stepRecords","record","openTracked","completedAtMs","random","patch","slice","day","counts","daily","bounces","replies","recentSends","bounced","bumpOutreachSequenceStats","trackedLinks","links","increment","catch","step","steps","taskId","written","link","dedupeKey","title","notes","taskKind","dueAtMs","assigneeUid","stepId","templateBody","templateId","composed","stop","counter","contact","target","convertedContactId","visible","gate","company","allowedCountries","personalLine","attestations","gatewayHoldReleased","gatewayHold","releasedAtMs","allowed","hold","heldAtMs","releasedByUid","unsubscribe","enabled","listUnsubscribe","mintUrl","unsubscribeUrl","mailboxEmail","sender","trackClicks","countOpens","linkOrigin","shortLinks","rewriteLink","linkIndex","url","clickLinkUrl","pixel","orgSettings","openPixelUrl","merge","lead","listUnsubscribeUrl","listUnsubscribeMailto","mailto","message","unresolvedFields","fields","field","screenMessage","subject","text","fromName","fromAddress","html","batch","create","commit","domain","lastIndexOf","local","claimed","messageIdLocalPart","messageIdDomain","gmailMessageId","gmailThreadId","threadId","override","curated","source","standing","recipientDomain","direction","from","to","inReplyTo","body","byName","nurtureEnrolledLead","bare","replace","found","listMessages","q","maxResults","includeSpamTrash","hit","messages","getMessage","metadataHeaders","headers","header","toLowerCase"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,mBAAmB,QAAQ,wCAAuC;AAC3E,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAASC,UAAU,QAAQ,cAAa;AACxC,SAASC,oBAAoB,QAAQ,uBAAmB;AACxD,SAASC,mBAAmB,QAAQ,qCAAiC;AACrE,SAASC,0BAA0B,QAAsC,gCAA4B;AACrG,SAASC,qBAAqB,QAA0D,qBAAiB;AACzG,SACEC,iBAAiB,EACjBC,qBAAqB,EACrBC,4BAA4B,QAEvB,gCAA4B;AACnC,SAASC,4BAA4B,QAAsC,iCAA6B;AACxG,SAASC,wBAAwB,QAAQ,qCAAiC;AAC1E,SAASC,uBAAuB,QAAQ,gCAA4B;AACpE,SAASC,UAAU,QAAQ,sCAAkC;AAC7D,SAASC,yBAAyB,EAAEC,gBAAgB,QAAQ,mCAA+B;AAE3F,SAASC,iCAAiC,QAAQ,kCAA8B;AAChF,SACEC,oBAAoB,QAOf,6BAAyB;AAChC,SAASC,iCAAiC,QAAQ,0CAAsC;AACxF,SAASC,4BAA4B,EAAEC,4BAA4B,QAAQ,mCAA+B;AAC1G,SACEC,sBAAsB,EACtBC,wBAAwB,EACxBC,qBAAqB,EACrBC,4BAA4B,EAC5BC,yBAAyB,EACzBC,0BAA0B,QACrB,iCAA6B;AACpC,SAASC,mBAAmB,EAAEC,mBAAmB,QAAQ,+BAA2B;AACpF,SAASC,mBAAmB,QAAQ,0BAAsB;AAC1D,SAASC,yBAAyB,QAAQ,+BAA2B;AACrE,SAASC,uB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,MAAMzM,wBAAwB0B,MAAM;YAAEqB;YAAYgC;QAAK;QACvD,MAAM0O,oBAAoBnO,KAAKvC;IACjC;IACA,OAAO0J;AACT"}
@@ -35,7 +35,7 @@ import { creditOutreachGatewayDeliveries, recordOutreachGatewayBlock } from "./g
35
35
  import { outreachMailboxSendingDomain } from "../storage/domain-intel-store.js";
36
36
  import { applyOutreachMailboxHealth, emptyOutreachHealthDelta } from "./mailbox-health-store.js";
37
37
  import { noteOutreachMailboxReconnectRequired } from "./mailbox-notices.js";
38
- import { markOutreachLeadWorking } from "./lead-records.js";
38
+ import { stampRecordEmailReply } from "@aglyn/aglyn/plugin-manager/plugin-record-email-state";
39
39
  import { fileOutreachEmail, fileOutreachNote, fileOutreachTask, markOutreachEmailDelivery } from "./timeline.js";
40
40
  import { outreachUnsubscribeMailbox } from "./unsubscribe-link.js";
41
41
  /*==========================================
@@ -454,11 +454,16 @@ async function syncMailbox(deps, firestore, input) {
454
454
  console.error('[outreach] the reply task could not be filed', error);
455
455
  }
456
456
  }
457
- // A lead somebody wrote back to is being worked (AGL-3234).
458
- if (enrollment.target === 'lead' && enrollment.leadId) {
459
- await markOutreachLeadWorking(firestore, {
457
+ // A lead somebody wrote back to is being worked (AGL-3234): the record
458
+ // system hears of the reply, and moves a lead nobody had worked to
459
+ // Working (AGL-3080). Never throws.
460
+ if (enrollment.target === 'lead' && enrollment.leadId && enrollment.email) {
461
+ await stampRecordEmailReply({
460
462
  orgId: context.orgId,
461
- leadId: enrollment.leadId
463
+ hostId: enrollment.hostId,
464
+ emails: [
465
+ enrollment.email
466
+ ]
462
467
  });
463
468
  }
464
469
  context.delta.replies += 1;