@oxygen-agent/cli 1.1014.1696 → 1.1014.1870

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 (112) hide show
  1. package/README.md +1 -1
  2. package/dist/admin-primary-providers-render.js +7 -2
  3. package/dist/command-families/program.js +4 -0
  4. package/dist/command-families/tables/register-relations.js +3 -2
  5. package/dist/command-manifest.js +14 -2
  6. package/dist/command-support.js +1 -1
  7. package/dist/commands/admin.js +82 -1
  8. package/dist/commands/billing.js +1 -1
  9. package/dist/commands/columns.js +2 -1
  10. package/dist/commands/copilot.js +29 -7
  11. package/dist/commands/domains.js +7 -0
  12. package/dist/commands/email-assets.d.ts +3 -0
  13. package/dist/commands/email-assets.js +78 -0
  14. package/dist/commands/email-templates.d.ts +3 -0
  15. package/dist/commands/email-templates.js +101 -0
  16. package/dist/commands/enrich-column.js +2 -1
  17. package/dist/commands/managed-inboxes.js +26 -1
  18. package/dist/commands/sequences.js +47 -12
  19. package/dist/commands/subscriptions.d.ts +2 -4
  20. package/dist/commands/subscriptions.js +297 -51
  21. package/dist/commands/table-runs.js +2 -1
  22. package/dist/sequence-start-at.d.ts +7 -0
  23. package/dist/sequence-start-at.js +21 -0
  24. package/dist/sequences-brand-kit-command.d.ts +28 -0
  25. package/dist/sequences-brand-kit-command.js +83 -0
  26. package/dist/sequences-content-commands.d.ts +28 -0
  27. package/dist/sequences-content-commands.js +176 -0
  28. package/dist/sequences-newsletter-commands.d.ts +6 -0
  29. package/dist/sequences-newsletter-commands.js +108 -0
  30. package/dist/sequences-test-send-command.d.ts +3 -0
  31. package/dist/sequences-test-send-command.js +47 -0
  32. package/node_modules/@oxygen/formula/dist/evaluate.js +2 -4
  33. package/node_modules/@oxygen/formula/dist/expression.d.ts +7 -5
  34. package/node_modules/@oxygen/formula/dist/expression.js +26 -4
  35. package/node_modules/@oxygen/formula/dist/formula-functions.d.ts +6 -0
  36. package/node_modules/@oxygen/formula/dist/formula-functions.js +55 -0
  37. package/node_modules/@oxygen/shared/dist/billing.d.ts +2 -2
  38. package/node_modules/@oxygen/shared/dist/billing.js +5 -7
  39. package/node_modules/@oxygen/shared/dist/bulk-email-pacing.d.ts +105 -0
  40. package/node_modules/@oxygen/shared/dist/bulk-email-pacing.js +125 -0
  41. package/node_modules/@oxygen/shared/dist/capability-discovery.d.ts +29 -0
  42. package/node_modules/@oxygen/shared/dist/capability-discovery.js +174 -10
  43. package/node_modules/@oxygen/shared/dist/contracts/clay-migration.d.ts +1 -0
  44. package/node_modules/@oxygen/shared/dist/contracts/clay-migration.js +28 -2
  45. package/node_modules/@oxygen/shared/dist/contracts/copilot-attachment-read.d.ts +24 -0
  46. package/node_modules/@oxygen/shared/dist/contracts/copilot-attachment-read.js +7 -0
  47. package/node_modules/@oxygen/shared/dist/contracts/teammates.js +6 -1
  48. package/node_modules/@oxygen/shared/dist/diagnostic-spool.js +90 -14
  49. package/node_modules/@oxygen/shared/dist/email-brand-kit.d.ts +108 -0
  50. package/node_modules/@oxygen/shared/dist/email-brand-kit.js +214 -0
  51. package/node_modules/@oxygen/shared/dist/email-delivery.d.ts +10 -0
  52. package/node_modules/@oxygen/shared/dist/email-delivery.js +14 -0
  53. package/node_modules/@oxygen/shared/dist/email-documents.d.ts +61 -0
  54. package/node_modules/@oxygen/shared/dist/email-documents.js +143 -0
  55. package/node_modules/@oxygen/shared/dist/email-dsn.js +52 -10
  56. package/node_modules/@oxygen/shared/dist/email-html-sanitize.d.ts +23 -0
  57. package/node_modules/@oxygen/shared/dist/email-html-sanitize.js +96 -0
  58. package/node_modules/@oxygen/shared/dist/email-subscriptions.d.ts +63 -1
  59. package/node_modules/@oxygen/shared/dist/email-subscriptions.js +149 -1
  60. package/node_modules/@oxygen/shared/dist/email-unsubscribe-token.d.ts +41 -2
  61. package/node_modules/@oxygen/shared/dist/email-unsubscribe-token.js +50 -1
  62. package/node_modules/@oxygen/shared/dist/external-write-policy.js +5 -1
  63. package/node_modules/@oxygen/shared/dist/group-commit-queue.d.ts +34 -0
  64. package/node_modules/@oxygen/shared/dist/group-commit-queue.js +103 -0
  65. package/node_modules/@oxygen/shared/dist/listed-website-platforms.d.ts +2 -0
  66. package/node_modules/@oxygen/shared/dist/listed-website-platforms.js +26 -0
  67. package/node_modules/@oxygen/shared/dist/newsletter-analytics.d.ts +90 -0
  68. package/node_modules/@oxygen/shared/dist/newsletter-analytics.js +28 -0
  69. package/node_modules/@oxygen/shared/dist/newsletter-test-send.d.ts +20 -0
  70. package/node_modules/@oxygen/shared/dist/newsletter-test-send.js +46 -0
  71. package/node_modules/@oxygen/shared/dist/object-storage.d.ts +11 -0
  72. package/node_modules/@oxygen/shared/dist/object-storage.js +12 -0
  73. package/node_modules/@oxygen/shared/dist/plan-band.d.ts +9 -0
  74. package/node_modules/@oxygen/shared/dist/plan-band.js +17 -0
  75. package/node_modules/@oxygen/shared/dist/plan-capabilities.d.ts +4 -2
  76. package/node_modules/@oxygen/shared/dist/plan-capabilities.js +12 -1
  77. package/node_modules/@oxygen/shared/dist/plan-limits-view.d.ts +2 -0
  78. package/node_modules/@oxygen/shared/dist/plan-limits-view.js +3 -0
  79. package/node_modules/@oxygen/shared/dist/pricing-snapshot.generated.d.ts +5 -0
  80. package/node_modules/@oxygen/shared/dist/pricing-snapshot.generated.js +5 -0
  81. package/node_modules/@oxygen/shared/dist/product-analytics-events.d.ts +29 -0
  82. package/node_modules/@oxygen/shared/dist/product-analytics-events.js +29 -0
  83. package/node_modules/@oxygen/shared/dist/provider-balance-signal.js +7 -0
  84. package/node_modules/@oxygen/shared/dist/sending-domain-faults.d.ts +21 -0
  85. package/node_modules/@oxygen/shared/dist/sending-domain-faults.js +53 -0
  86. package/node_modules/@oxygen/shared/dist/sending-domain-rollout.d.ts +24 -1
  87. package/node_modules/@oxygen/shared/dist/sending-domain-rollout.js +51 -4
  88. package/node_modules/@oxygen/shared/dist/sequence-failures.d.ts +10 -1
  89. package/node_modules/@oxygen/shared/dist/sequence-failures.js +68 -6
  90. package/node_modules/@oxygen/shared/dist/sequence-lifecycle.d.ts +34 -3
  91. package/node_modules/@oxygen/shared/dist/sequence-lifecycle.js +57 -4
  92. package/node_modules/@oxygen/shared/dist/sequence-template.d.ts +17 -0
  93. package/node_modules/@oxygen/shared/dist/sequence-template.js +0 -0
  94. package/node_modules/@oxygen/shared/dist/sequences.d.ts +41 -0
  95. package/node_modules/@oxygen/shared/dist/sequences.js +86 -4
  96. package/node_modules/@oxygen/shared/dist/ses-identity-policy.d.ts +19 -0
  97. package/node_modules/@oxygen/shared/dist/ses-identity-policy.js +54 -0
  98. package/node_modules/@oxygen/shared/dist/skill-play-routing.d.ts +22 -0
  99. package/node_modules/@oxygen/shared/dist/skill-play-routing.js +75 -0
  100. package/node_modules/@oxygen/shared/dist/skill-plays.generated.d.ts +5 -0
  101. package/node_modules/@oxygen/shared/dist/skill-plays.generated.js +269 -0
  102. package/node_modules/@oxygen/shared/dist/spend-safety.d.ts +7 -0
  103. package/node_modules/@oxygen/shared/dist/spend-safety.js +7 -0
  104. package/node_modules/@oxygen/shared/dist/table-limits.d.ts +6 -4
  105. package/node_modules/@oxygen/shared/dist/table-limits.js +6 -4
  106. package/node_modules/@oxygen/shared/dist/teammates.js +2 -1
  107. package/node_modules/@oxygen/shared/dist/user-capability-routing.js +15 -1
  108. package/node_modules/@oxygen/shared/dist/version.generated.d.ts +1 -1
  109. package/node_modules/@oxygen/shared/dist/version.generated.js +1 -1
  110. package/node_modules/@oxygen/shared/dist/workspace-event-catalog.js +2 -2
  111. package/node_modules/@oxygen/shared/package.json +5 -0
  112. package/package.json +2 -2
@@ -1,5 +1,5 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { mkdir, open, readFile, readdir, rename, stat, unlink, utimes } from "node:fs/promises";
2
+ import { mkdir, open, readFile, readdir, rename, stat, unlink, utimes, writeFile } from "node:fs/promises";
3
3
  import { join } from "node:path";
4
4
  import { DIAGNOSTIC_MAX_BYTES, diagnosticId } from "./diagnostics.js";
5
5
  import { acquireDiagnosticStorageLock } from "./diagnostic-storage-lock.js";
@@ -8,6 +8,10 @@ import { log } from "./log.js";
8
8
  import { recordTelemetryCounter } from "./telemetry.js";
9
9
  const admissions = new Map();
10
10
  const RECEIPT_MAX_BYTES = 512;
11
+ /** A full scan bounds ledger drift (a crashed owner, a pre-ledger writer) and enforces expiry. */
12
+ const LEDGER_MAX_AGE_MS = 15_000;
13
+ /** This process's last full listing supplies retry candidates between scans. */
14
+ const inspections = new Map();
11
15
  /** Admit durable content plus bounded receipt bytes; acknowledge only after publication. */
12
16
  export async function admitDiagnosticSpool(directory, record, compressed) {
13
17
  await storageStage("mkdir", () => mkdir(directory, { recursive: true, mode: 0o700 }));
@@ -52,6 +56,7 @@ async function drainAdmissions(directory, queue) {
52
56
  while (queue.pending.length) {
53
57
  const batch = queue.pending.splice(0, 32);
54
58
  let release = null;
59
+ let published;
55
60
  try {
56
61
  // Bound actual cross-process contention, not local queue/inspection time (#5810).
57
62
  release = await storageStage("lock", () => acquireDiagnosticStorageLock(join(directory, ".admission.lock"), 5_000));
@@ -60,25 +65,47 @@ async function drainAdmissions(directory, queue) {
60
65
  const started = performance.now();
61
66
  const reservedOnly = batch.every(admission => admission.progress && admission.reservation);
62
67
  let files = queue.files ?? [];
68
+ let scanned = false;
63
69
  if (!reservedOnly) {
64
- const inspected = await storageStage("inspect", () => inspectDiagnosticSpool(directory));
65
- queue.used = inspected.used;
66
- queue.files = files = inspected.files;
70
+ // A fresh shared ledger stands in for the full scan, which held this
71
+ // cross-process mutex ~1 s per batch at 24k retained files (2026-10-23).
72
+ const ledger = await readAdmissionLedger(directory, batch.reduce((sum, admission) => sum + admissionBytes(admission), 0));
73
+ if (ledger) {
74
+ queue.used = ledger.used;
75
+ queue.scannedAt = ledger.scanned_at;
76
+ queue.files = files = ledger.files;
77
+ }
78
+ else {
79
+ const inspected = await storageStage("inspect", () => inspectDiagnosticSpool(directory));
80
+ queue.used = inspected.used;
81
+ queue.files = files = inspected.files;
82
+ queue.scannedAt = Date.now();
83
+ scanned = true;
84
+ }
67
85
  }
68
86
  const scanMs = performance.now() - started;
69
87
  // Captures arriving during inspection share its protected byte count,
70
88
  // avoiding another scan while keeping the 32-record batch bound.
71
- if (!reservedOnly)
89
+ if (scanned)
72
90
  batch.push(...queue.pending.splice(0, 32 - batch.length));
91
+ const refused = new Set();
92
+ for (const admission of batch) {
93
+ const required = admissionBytes(admission);
94
+ if (required && (queue.used === undefined || queue.used + required > DIAGNOSTIC_MAX_BYTES)) {
95
+ refused.add(admission);
96
+ continue;
97
+ }
98
+ // Reserve conservatively even if cleanup of a failed partial write fails.
99
+ if (queue.used !== undefined)
100
+ queue.used += required;
101
+ }
102
+ // Publish before writing: a crash mid-batch leaves the ledger above the spool, never below.
103
+ if (queue.used !== undefined && queue.scannedAt !== undefined)
104
+ await writeAdmissionLedger(directory, published = queue.used, queue.scannedAt);
73
105
  for (const admission of batch) {
74
106
  try {
75
- // Include an upload receipt and its atomic replacement in admission.
76
- const required = admission.reservation ? 0 : admission.progress ? RECEIPT_MAX_BYTES : admission.encoded.compressed.length + 2 * RECEIPT_MAX_BYTES;
77
- if (required && (queue.used === undefined || queue.used + required > DIAGNOSTIC_MAX_BYTES))
107
+ if (refused.has(admission))
78
108
  throw new StorageFailure("capacity", { code: "spool_full" });
79
- // Reserve conservatively even if cleanup of a failed partial write fails.
80
- if (queue.used !== undefined)
81
- queue.used += required;
82
109
  if (admission.progress) {
83
110
  await writeUploadProgress(directory, admission.record, admission.progress, admission.reservation);
84
111
  admission.resolve(join(directory, `${admission.record.id}.receipt.json`));
@@ -90,17 +117,23 @@ async function drainAdmissions(directory, queue) {
90
117
  admission.reject(error);
91
118
  }
92
119
  }
93
- if (!reservedOnly)
120
+ // Ledger batches are about one per capture; log them only when they waited.
121
+ const waitMs = performance.now() - batch[0].enqueuedAt;
122
+ if (!reservedOnly && (scanned || waitMs >= 1_000))
94
123
  log("info", "diagnostics.spool_admitted", { queue_role: diagnosticRole(), batch_records: batch.length, spool_files: files.length,
95
- spool_bytes: queue.used, scan_ms: scanMs, admission_wait_ms: performance.now() - batch[0].enqueuedAt });
124
+ spool_bytes: queue.used, scan_ms: scanMs, admission_wait_ms: waitMs, inspection: scanned ? "scan" : "ledger" });
96
125
  }
97
126
  catch (error) {
98
127
  for (const admission of batch)
99
128
  admission.reject(error);
100
129
  }
101
130
  finally {
131
+ const used = queue.used;
102
132
  delete queue.used;
103
133
  await Promise.allSettled([...queue.progressWrites]);
134
+ // Receipts reserved beside the batch are published before the mutex is released.
135
+ if (used !== undefined && used !== published && queue.scannedAt !== undefined)
136
+ await writeAdmissionLedger(directory, used, queue.scannedAt);
104
137
  await release?.();
105
138
  }
106
139
  }
@@ -113,6 +146,43 @@ async function drainAdmissions(directory, queue) {
113
146
  admissions.delete(directory);
114
147
  }
115
148
  }
149
+ /** Include an upload receipt and its atomic replacement in admission. */
150
+ function admissionBytes(admission) {
151
+ return admission.reservation ? 0 : admission.progress ? RECEIPT_MAX_BYTES : admission.encoded.compressed.length + 2 * RECEIPT_MAX_BYTES;
152
+ }
153
+ /**
154
+ * Caller owns the admission mutex. Every ledger-aware owner publishes its
155
+ * reservations before writing them, and unlinks outside the mutex only shrink
156
+ * the spool, so the ledger never undercounts those owners. It replaces a scan
157
+ * only while recent and within half the budget, so a pre-ledger writer during
158
+ * a rollout cannot carry the spool past its limit unseen.
159
+ */
160
+ async function readAdmissionLedger(directory, required) {
161
+ const local = inspections.get(directory);
162
+ if (!local || Date.now() - local.at >= 4 * LEDGER_MAX_AGE_MS)
163
+ return null;
164
+ try {
165
+ const value = JSON.parse(await readFile(join(directory, ".admission.ledger"), "utf8"));
166
+ const age = Date.now() - value.scanned_at;
167
+ if (!Number.isSafeInteger(value.used) || value.used < 0 || !(age >= 0 && age < LEDGER_MAX_AGE_MS))
168
+ return null;
169
+ return value.used + required <= DIAGNOSTIC_MAX_BYTES / 2 ? { used: value.used, scanned_at: value.scanned_at, files: local.files } : null;
170
+ }
171
+ catch {
172
+ return null;
173
+ }
174
+ }
175
+ /** Only the admission mutex owner reads or writes; a torn write parses as absent and forces a scan. */
176
+ async function writeAdmissionLedger(directory, used, scannedAt) {
177
+ const path = join(directory, ".admission.ledger");
178
+ try {
179
+ await writeFile(path, JSON.stringify({ used, scanned_at: scannedAt }), { mode: 0o600 });
180
+ }
181
+ catch {
182
+ // A ledger that may now undercount must not admit; the next owner scans.
183
+ await unlink(path).catch(() => undefined);
184
+ }
185
+ }
116
186
  async function writeDiagnosticSpool(directory, id, compressed) {
117
187
  const path = join(directory, `${id}.json.gz`);
118
188
  const temporary = join(directory, `${id}.${randomUUID()}.tmp`);
@@ -305,8 +375,12 @@ export async function retryDiagnosticSpool(directory, storeFingerprint, upload)
305
375
  if (!admission)
306
376
  return;
307
377
  try {
378
+ const scannedAt = Date.now();
308
379
  const inspected = await storageStage("inspect", () => inspectDiagnosticSpool(directory));
309
380
  ({ files, reservation } = await reserveRetryBatch(directory, inspected.files.slice(0, 20), inspected.used));
381
+ // Unreserved, any existing ledger still covers the spool; skip the extra mutex hold.
382
+ if (reservation)
383
+ await writeAdmissionLedger(directory, inspected.used + files.length * 2 * RECEIPT_MAX_BYTES, scannedAt);
310
384
  }
311
385
  finally {
312
386
  await admission();
@@ -374,5 +448,7 @@ async function inspectDiagnosticSpool(directory) {
374
448
  }
375
449
  }
376
450
  }
377
- return { used, files: retained.sort((a, b) => a.mtimeMs - b.mtimeMs || a.name.localeCompare(b.name)).map(file => file.name) };
451
+ const files = retained.sort((a, b) => a.mtimeMs - b.mtimeMs || a.name.localeCompare(b.name)).map(file => file.name);
452
+ inspections.set(directory, { files, at: Date.now() });
453
+ return { used, files };
378
454
  }
@@ -0,0 +1,108 @@
1
+ /**
2
+ * The workspace's newsletter brand kit (tenant table ox_sequencer.email_brand_kit,
3
+ * migration 0559): the logo, colours, width and font newsletters are designed
4
+ * with, the company name and postal address every bulk email carries in its
5
+ * footer, social links and the preference page's title.
6
+ *
7
+ * One parser serves the `/api/cli/sequencer/brand-kit` route (web, CLI, MCP):
8
+ * a patch names only the fields it changes, `null` clears one (a colour, width
9
+ * or font falls back to its default). Pure and browser-safe.
10
+ */
11
+ export declare const EMAIL_BRAND_FONT_FAMILIES: readonly ["system", "georgia", "arial", "helvetica", "verdana"];
12
+ export type EmailBrandFontFamily = typeof EMAIL_BRAND_FONT_FAMILIES[number];
13
+ export declare const EMAIL_BRAND_FONT_LABELS: Record<EmailBrandFontFamily, string>;
14
+ /** The CSS font stack each allowlisted family renders with in an email. */
15
+ export declare const EMAIL_BRAND_FONT_STACKS: Record<EmailBrandFontFamily, string>;
16
+ export declare const EMAIL_BRAND_SOCIAL_NETWORKS: readonly ["website", "linkedin", "x", "facebook", "instagram", "youtube", "tiktok", "github"];
17
+ export type EmailBrandSocialNetwork = typeof EMAIL_BRAND_SOCIAL_NETWORKS[number];
18
+ export declare const EMAIL_BRAND_COLOR_FIELDS: readonly ["background_color", "content_background_color", "text_color", "link_color", "button_color", "button_text_color"];
19
+ export type EmailBrandColorField = typeof EMAIL_BRAND_COLOR_FIELDS[number];
20
+ export declare const EMAIL_BRAND_LIMITS: {
21
+ readonly containerWidthMin: 480;
22
+ readonly containerWidthMax: 800;
23
+ readonly logoWidthMin: 40;
24
+ readonly logoWidthMax: 600;
25
+ readonly urlMax: 2048;
26
+ readonly companyNameMax: 120;
27
+ readonly postalAddressMax: 500;
28
+ readonly socialLinksMax: 10;
29
+ readonly preferencePageTitleMax: 120;
30
+ readonly preferencePageDescriptionMax: 500;
31
+ };
32
+ export type EmailBrandSocialLink = {
33
+ network: EmailBrandSocialNetwork;
34
+ url: string;
35
+ };
36
+ /** The kit as every surface reads it (snake_case wire shape), defaults applied. */
37
+ export type EmailBrandKit = {
38
+ logo_url: string | null;
39
+ logo_width: number | null;
40
+ background_color: string;
41
+ content_background_color: string;
42
+ text_color: string;
43
+ link_color: string;
44
+ button_color: string;
45
+ button_text_color: string;
46
+ container_width: number;
47
+ font_family: EmailBrandFontFamily;
48
+ company_name: string | null;
49
+ postal_address: string | null;
50
+ social_links: EmailBrandSocialLink[];
51
+ preference_page_title: string | null;
52
+ preference_page_description: string | null;
53
+ updated_by: string | null;
54
+ updated_at: string | null;
55
+ };
56
+ export declare const DEFAULT_EMAIL_BRAND_COLORS: Record<EmailBrandColorField, string>;
57
+ export declare const DEFAULT_EMAIL_BRAND_KIT: EmailBrandKit;
58
+ /** Every editable field; a patch names a subset. */
59
+ export declare const EMAIL_BRAND_KIT_FIELDS: readonly ["logo_url", "logo_width", "background_color", "content_background_color", "text_color", "link_color", "button_color", "button_text_color", "container_width", "font_family", "company_name", "postal_address", "social_links", "preference_page_title", "preference_page_description"];
60
+ export type EmailBrandKitField = typeof EMAIL_BRAND_KIT_FIELDS[number];
61
+ /** A validated change: a present key is written, `null` clears it. */
62
+ export type EmailBrandKitPatch = {
63
+ logo_url?: string | null;
64
+ logo_width?: number | null;
65
+ background_color?: string | null;
66
+ content_background_color?: string | null;
67
+ text_color?: string | null;
68
+ link_color?: string | null;
69
+ button_color?: string | null;
70
+ button_text_color?: string | null;
71
+ container_width?: number | null;
72
+ font_family?: EmailBrandFontFamily | null;
73
+ company_name?: string | null;
74
+ postal_address?: string | null;
75
+ social_links?: EmailBrandSocialLink[] | null;
76
+ preference_page_title?: string | null;
77
+ preference_page_description?: string | null;
78
+ };
79
+ export declare class EmailBrandKitInputError extends Error {
80
+ readonly field: string;
81
+ readonly code = "invalid_brand_kit";
82
+ constructor(field: string, message: string);
83
+ }
84
+ /** `#rrggbb` lowercase from `#rrggbb`, `rrggbb` or `#rgb`; throws on anything else. */
85
+ export declare function normalizeBrandColor(value: unknown, field: string): string;
86
+ /** An absolute https URL; email clients block or warn on plain http images and links. */
87
+ export declare function normalizeBrandUrl(value: unknown, field: string): string;
88
+ export declare function isEmailBrandFontFamily(value: unknown): value is EmailBrandFontFamily;
89
+ /**
90
+ * Validate a brand kit change. Only the named fields are returned; `null` (or
91
+ * an empty string for text) clears one. Throws `EmailBrandKitInputError` naming
92
+ * the field, and refuses a body that names no field.
93
+ */
94
+ export declare function parseEmailBrandKitPatch(body: Record<string, unknown>): EmailBrandKitPatch;
95
+ /** A newsletter may go live only once the kit carries a postal address. */
96
+ export declare function brandKitHasPostalAddress(kit: Pick<EmailBrandKit, "postal_address"> | null | undefined): boolean;
97
+ /** The email editor's global styles, as the composer and its preview consume them. */
98
+ export type EmailBrandGlobalStyles = {
99
+ background: string;
100
+ contentBackground: string;
101
+ text: string;
102
+ link: string;
103
+ button: string;
104
+ buttonText: string;
105
+ containerWidth: number;
106
+ fontFamily: string;
107
+ };
108
+ export declare function brandKitGlobalStyles(kit: Partial<EmailBrandKit> | null | undefined): EmailBrandGlobalStyles;
@@ -0,0 +1,214 @@
1
+ /**
2
+ * The workspace's newsletter brand kit (tenant table ox_sequencer.email_brand_kit,
3
+ * migration 0559): the logo, colours, width and font newsletters are designed
4
+ * with, the company name and postal address every bulk email carries in its
5
+ * footer, social links and the preference page's title.
6
+ *
7
+ * One parser serves the `/api/cli/sequencer/brand-kit` route (web, CLI, MCP):
8
+ * a patch names only the fields it changes, `null` clears one (a colour, width
9
+ * or font falls back to its default). Pure and browser-safe.
10
+ */
11
+ export const EMAIL_BRAND_FONT_FAMILIES = ["system", "georgia", "arial", "helvetica", "verdana"];
12
+ export const EMAIL_BRAND_FONT_LABELS = {
13
+ system: "System sans",
14
+ georgia: "Georgia",
15
+ arial: "Arial",
16
+ helvetica: "Helvetica",
17
+ verdana: "Verdana",
18
+ };
19
+ /** The CSS font stack each allowlisted family renders with in an email. */
20
+ export const EMAIL_BRAND_FONT_STACKS = {
21
+ system: "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif",
22
+ georgia: "Georgia, 'Times New Roman', Times, serif",
23
+ arial: "Arial, Helvetica, sans-serif",
24
+ helvetica: "Helvetica, Arial, sans-serif",
25
+ verdana: "Verdana, Geneva, sans-serif",
26
+ };
27
+ export const EMAIL_BRAND_SOCIAL_NETWORKS = [
28
+ "website", "linkedin", "x", "facebook", "instagram", "youtube", "tiktok", "github",
29
+ ];
30
+ export const EMAIL_BRAND_COLOR_FIELDS = [
31
+ "background_color", "content_background_color", "text_color", "link_color", "button_color", "button_text_color",
32
+ ];
33
+ export const EMAIL_BRAND_LIMITS = {
34
+ containerWidthMin: 480,
35
+ containerWidthMax: 800,
36
+ logoWidthMin: 40,
37
+ logoWidthMax: 600,
38
+ urlMax: 2048,
39
+ companyNameMax: 120,
40
+ postalAddressMax: 500,
41
+ socialLinksMax: 10,
42
+ preferencePageTitleMax: 120,
43
+ preferencePageDescriptionMax: 500,
44
+ };
45
+ export const DEFAULT_EMAIL_BRAND_COLORS = {
46
+ background_color: "#f4f4f5",
47
+ content_background_color: "#ffffff",
48
+ text_color: "#18181b",
49
+ link_color: "#2563eb",
50
+ button_color: "#18181b",
51
+ button_text_color: "#ffffff",
52
+ };
53
+ export const DEFAULT_EMAIL_BRAND_KIT = {
54
+ logo_url: null,
55
+ logo_width: null,
56
+ ...DEFAULT_EMAIL_BRAND_COLORS,
57
+ container_width: 600,
58
+ font_family: "system",
59
+ company_name: null,
60
+ postal_address: null,
61
+ social_links: [],
62
+ preference_page_title: null,
63
+ preference_page_description: null,
64
+ updated_by: null,
65
+ updated_at: null,
66
+ };
67
+ /** Every editable field; a patch names a subset. */
68
+ export const EMAIL_BRAND_KIT_FIELDS = [
69
+ "logo_url", "logo_width", ...EMAIL_BRAND_COLOR_FIELDS, "container_width", "font_family", "company_name",
70
+ "postal_address", "social_links", "preference_page_title", "preference_page_description",
71
+ ];
72
+ export class EmailBrandKitInputError extends Error {
73
+ field;
74
+ code = "invalid_brand_kit";
75
+ constructor(field, message) {
76
+ super(message);
77
+ this.field = field;
78
+ this.name = "EmailBrandKitInputError";
79
+ }
80
+ }
81
+ const HEX_RE = /^#?([0-9a-f]{6}|[0-9a-f]{3})$/i;
82
+ /** `#rrggbb` lowercase from `#rrggbb`, `rrggbb` or `#rgb`; throws on anything else. */
83
+ export function normalizeBrandColor(value, field) {
84
+ const raw = typeof value === "string" ? value.trim() : "";
85
+ const match = HEX_RE.exec(raw);
86
+ if (!match)
87
+ throw new EmailBrandKitInputError(field, `${field} must be a hex colour such as #1a2b3c.`);
88
+ const hex = match[1].toLowerCase();
89
+ return `#${hex.length === 3 ? hex.split("").map((char) => char + char).join("") : hex}`;
90
+ }
91
+ /** An absolute https URL; email clients block or warn on plain http images and links. */
92
+ export function normalizeBrandUrl(value, field) {
93
+ const raw = typeof value === "string" ? value.trim() : "";
94
+ let parsed = null;
95
+ try {
96
+ parsed = raw ? new URL(raw) : null;
97
+ }
98
+ catch {
99
+ parsed = null;
100
+ }
101
+ if (!parsed || parsed.protocol !== "https:" || !parsed.hostname || raw.length > EMAIL_BRAND_LIMITS.urlMax) {
102
+ throw new EmailBrandKitInputError(field, `${field} must be an https:// URL.`);
103
+ }
104
+ return parsed.toString();
105
+ }
106
+ function boundedInteger(value, field, min, max) {
107
+ if (typeof value !== "number" || !Number.isInteger(value) || value < min || value > max) {
108
+ throw new EmailBrandKitInputError(field, `${field} must be a whole number from ${min} to ${max}.`);
109
+ }
110
+ return value;
111
+ }
112
+ function boundedText(value, field, max, options = {}) {
113
+ if (typeof value !== "string")
114
+ throw new EmailBrandKitInputError(field, `${field} must be text.`);
115
+ const lines = value.replace(/\r\n?/g, "\n").split("\n").map((line) => line.replace(/\s+/g, " ").trim());
116
+ const text = options.multiline ? lines.filter(Boolean).join("\n") : lines.filter(Boolean).join(" ");
117
+ if (!text)
118
+ return null;
119
+ if (text.length > max)
120
+ throw new EmailBrandKitInputError(field, `${field} must be at most ${max} characters.`);
121
+ return text;
122
+ }
123
+ export function isEmailBrandFontFamily(value) {
124
+ return typeof value === "string" && EMAIL_BRAND_FONT_FAMILIES.includes(value);
125
+ }
126
+ function parseSocialLinks(value) {
127
+ if (!Array.isArray(value))
128
+ throw new EmailBrandKitInputError("social_links", "social_links must be a list of { network, url }.");
129
+ if (value.length > EMAIL_BRAND_LIMITS.socialLinksMax) {
130
+ throw new EmailBrandKitInputError("social_links", `At most ${EMAIL_BRAND_LIMITS.socialLinksMax} social links.`);
131
+ }
132
+ return value.map((entry, index) => {
133
+ const record = entry && typeof entry === "object" && !Array.isArray(entry) ? entry : {};
134
+ const network = typeof record.network === "string" ? record.network.trim().toLowerCase() : "";
135
+ if (!EMAIL_BRAND_SOCIAL_NETWORKS.includes(network)) {
136
+ throw new EmailBrandKitInputError(`social_links[${index}].network`, `network must be one of ${EMAIL_BRAND_SOCIAL_NETWORKS.join(", ")}.`);
137
+ }
138
+ return { network: network, url: normalizeBrandUrl(record.url, `social_links[${index}].url`) };
139
+ });
140
+ }
141
+ /**
142
+ * Validate a brand kit change. Only the named fields are returned; `null` (or
143
+ * an empty string for text) clears one. Throws `EmailBrandKitInputError` naming
144
+ * the field, and refuses a body that names no field.
145
+ */
146
+ export function parseEmailBrandKitPatch(body) {
147
+ const patch = {};
148
+ const has = (field) => Object.hasOwn(body, field) && body[field] !== undefined;
149
+ const cleared = (field) => body[field] === null || body[field] === "";
150
+ if (has("logo_url"))
151
+ patch.logo_url = cleared("logo_url") ? null : normalizeBrandUrl(body.logo_url, "logo_url");
152
+ if (has("logo_width")) {
153
+ patch.logo_width = cleared("logo_width") ? null
154
+ : boundedInteger(body.logo_width, "logo_width", EMAIL_BRAND_LIMITS.logoWidthMin, EMAIL_BRAND_LIMITS.logoWidthMax);
155
+ }
156
+ for (const field of EMAIL_BRAND_COLOR_FIELDS) {
157
+ if (has(field))
158
+ patch[field] = cleared(field) ? null : normalizeBrandColor(body[field], field);
159
+ }
160
+ if (has("container_width")) {
161
+ patch.container_width = cleared("container_width") ? null
162
+ : boundedInteger(body.container_width, "container_width", EMAIL_BRAND_LIMITS.containerWidthMin, EMAIL_BRAND_LIMITS.containerWidthMax);
163
+ }
164
+ if (has("font_family")) {
165
+ const font = typeof body.font_family === "string" ? body.font_family.trim().toLowerCase() : body.font_family;
166
+ if (cleared("font_family"))
167
+ patch.font_family = null;
168
+ else if (isEmailBrandFontFamily(font))
169
+ patch.font_family = font;
170
+ else
171
+ throw new EmailBrandKitInputError("font_family", `font_family must be one of ${EMAIL_BRAND_FONT_FAMILIES.join(", ")}.`);
172
+ }
173
+ if (has("company_name")) {
174
+ patch.company_name = body.company_name === null ? null : boundedText(body.company_name, "company_name", EMAIL_BRAND_LIMITS.companyNameMax);
175
+ }
176
+ if (has("postal_address")) {
177
+ patch.postal_address = body.postal_address === null ? null
178
+ : boundedText(body.postal_address, "postal_address", EMAIL_BRAND_LIMITS.postalAddressMax, { multiline: true });
179
+ }
180
+ if (has("social_links"))
181
+ patch.social_links = body.social_links === null ? null : parseSocialLinks(body.social_links);
182
+ if (has("preference_page_title")) {
183
+ patch.preference_page_title = body.preference_page_title === null ? null
184
+ : boundedText(body.preference_page_title, "preference_page_title", EMAIL_BRAND_LIMITS.preferencePageTitleMax);
185
+ }
186
+ if (has("preference_page_description")) {
187
+ patch.preference_page_description = body.preference_page_description === null ? null
188
+ : boundedText(body.preference_page_description, "preference_page_description", EMAIL_BRAND_LIMITS.preferencePageDescriptionMax, { multiline: true });
189
+ }
190
+ if (Object.keys(patch).length === 0) {
191
+ throw new EmailBrandKitInputError("brand_kit", `Pass at least one of ${EMAIL_BRAND_KIT_FIELDS.join(", ")}.`);
192
+ }
193
+ return patch;
194
+ }
195
+ /** A newsletter may go live only once the kit carries a postal address. */
196
+ export function brandKitHasPostalAddress(kit) {
197
+ return typeof kit?.postal_address === "string" && kit.postal_address.trim().length > 0;
198
+ }
199
+ export function brandKitGlobalStyles(kit) {
200
+ const merged = { ...DEFAULT_EMAIL_BRAND_KIT, ...stripNullish(kit ?? {}) };
201
+ return {
202
+ background: merged.background_color,
203
+ contentBackground: merged.content_background_color,
204
+ text: merged.text_color,
205
+ link: merged.link_color,
206
+ button: merged.button_color,
207
+ buttonText: merged.button_text_color,
208
+ containerWidth: merged.container_width,
209
+ fontFamily: EMAIL_BRAND_FONT_STACKS[merged.font_family] ?? EMAIL_BRAND_FONT_STACKS.system,
210
+ };
211
+ }
212
+ function stripNullish(value) {
213
+ return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== null && entry !== undefined));
214
+ }
@@ -25,6 +25,14 @@ export type SendingDomainEmailDelivery = {
25
25
  export type SequenceEmailDelivery = {
26
26
  mode: "inboxes";
27
27
  } | SendingDomainEmailDelivery;
28
+ /**
29
+ * The opt-out line of a cold email sent as plain text, when its Sequence turned the
30
+ * visible unsubscribe on without writing its own `reply_to_stop_text`. Plain text
31
+ * shows a line, never the signed URL (Plain T-317). Any reply stops the lead's
32
+ * enrollment in that Sequence, and opt-out wording ("not interested") puts the
33
+ * address on do-not-contact unless the workspace lowered `email_optout_phrase`.
34
+ */
35
+ export declare const DEFAULT_PLAIN_TEXT_OPT_OUT = "Not interested? Just reply and I won't follow up.";
28
36
  export declare class EmailDeliverySettingError extends Error {
29
37
  readonly field: string;
30
38
  constructor(field: string, message: string);
@@ -120,6 +128,8 @@ export declare function sendingDomainRemainingCapacity(input: {
120
128
  export declare function bulkSendIntervalMs(maxSendRate: number): number;
121
129
  /** Estimated AWS cost of a send count, USD rounded up to the cent. */
122
130
  export declare function estimateSesCostUsd(sends: number): number;
131
+ /** Credits for newsletter emails sent through a sending domain (`send.bulk_email`, 5x AWS). */
132
+ export declare function bulkEmailCredits(emails: number): number;
123
133
  export declare const RELEASE_SLICE_FRACTION = 0.05;
124
134
  export declare const RELEASE_SLICE_MINIMUM = 50;
125
135
  export declare const RELEASE_SLICE_HOLD_MS: number;
@@ -12,7 +12,16 @@
12
12
  * Pure and browser-safe: the web Delivery control, the CLI/MCP contracts, the
13
13
  * tenant settings validator and the dispatcher all read the same parser.
14
14
  */
15
+ import { BULK_EMAIL_CREDITS_PER_EMAIL } from "./pricing-snapshot.generated.js";
15
16
  export const SEQUENCE_EMAIL_DELIVERY_MODES = ["inboxes", "sending_domain"];
17
+ /**
18
+ * The opt-out line of a cold email sent as plain text, when its Sequence turned the
19
+ * visible unsubscribe on without writing its own `reply_to_stop_text`. Plain text
20
+ * shows a line, never the signed URL (Plain T-317). Any reply stops the lead's
21
+ * enrollment in that Sequence, and opt-out wording ("not interested") puts the
22
+ * address on do-not-contact unless the workspace lowered `email_optout_phrase`.
23
+ */
24
+ export const DEFAULT_PLAIN_TEXT_OPT_OUT = "Not interested? Just reply and I won't follow up.";
16
25
  export class EmailDeliverySettingError extends Error {
17
26
  field;
18
27
  constructor(field, message) {
@@ -205,6 +214,11 @@ export function estimateSesCostUsd(sends) {
205
214
  const count = Math.max(0, Math.floor(sends));
206
215
  return Math.ceil(count * SES_USD_PER_THOUSAND * 100 / 1000) / 100;
207
216
  }
217
+ /** Credits for newsletter emails sent through a sending domain (`send.bulk_email`, 5x AWS). */
218
+ export function bulkEmailCredits(emails) {
219
+ const count = Number.isFinite(emails) ? Math.max(0, Math.floor(emails)) : 0;
220
+ return Math.round(count * BULK_EMAIL_CREDITS_PER_EMAIL * 1000) / 1000;
221
+ }
208
222
  // ---------------------------------------------------------------------------
209
223
  // Release slice (clean-room). The first live start of a sending-domain Sequence
210
224
  // sends a small slice, holds, and releases the rest only when the slice's hard
@@ -0,0 +1,61 @@
1
+ /** Gmail clips a message above ~102 KB; the server refuses a revision above this. */
2
+ export declare const EMAIL_DOCUMENT_MAX_HTML_BYTES = 102400;
3
+ /** The editor's size meter warns from here. */
4
+ export declare const EMAIL_DOCUMENT_WARN_HTML_BYTES = 81920;
5
+ export declare const EMAIL_DOCUMENT_MAX_TEXT_CHARS = 102400;
6
+ export declare const EMAIL_DOCUMENT_MAX_PREVIEW_TEXT_CHARS = 500;
7
+ export declare const EMAIL_DOCUMENT_MAX_NAME_CHARS = 200;
8
+ /** The editor's JSON tree; generous, but bounded so a revision row stays small. */
9
+ export declare const EMAIL_DOCUMENT_MAX_EDITOR_JSON_BYTES = 512000;
10
+ export declare const EMAIL_DOCUMENT_ROLES: readonly ["step", "template"];
11
+ export type EmailDocumentRole = typeof EMAIL_DOCUMENT_ROLES[number];
12
+ export declare const EMAIL_DOCUMENT_KINDS: readonly ["visual", "html"];
13
+ export type EmailDocumentKind = typeof EMAIL_DOCUMENT_KINDS[number];
14
+ /** A step's reference to its body. Without `revision` it follows the current one until the Sequence goes live. */
15
+ export type EmailDocumentRef = {
16
+ id: string;
17
+ revision?: number;
18
+ };
19
+ export declare function isEmailDocumentId(value: unknown): value is string;
20
+ /** UTF-8 byte length, the unit Gmail clips on. */
21
+ export declare function emailHtmlByteLength(html: string): number;
22
+ /** A refused document input: a fixed sentence naming the field (ADR 0023 validation copy). */
23
+ export declare class EmailDocumentInputError extends Error {
24
+ readonly code: string;
25
+ readonly field: string;
26
+ readonly details: Record<string, unknown>;
27
+ constructor(code: string, field: string, message: string, details?: Record<string, unknown>);
28
+ }
29
+ export type EmailDocumentContentInput = {
30
+ html: string;
31
+ text: string;
32
+ previewText: string | null;
33
+ editorJson: unknown | null;
34
+ htmlBytes: number;
35
+ /** True when the save removed scripts, handlers or unsafe links from raw HTML. */
36
+ sanitized: boolean;
37
+ removed: {
38
+ elements: number;
39
+ handlers: number;
40
+ urls: number;
41
+ };
42
+ };
43
+ /**
44
+ * A readable plain-text part from email HTML, for a revision saved without one.
45
+ * Links keep their target (`label (https://...)`); merge tags pass through.
46
+ */
47
+ export declare function emailHtmlToPlainText(html: string): string;
48
+ /**
49
+ * Validate one revision's content: raw HTML is cleaned of active content,
50
+ * text is derived when absent, and the 100 KB HTML ceiling is enforced on the
51
+ * cleaned bytes. Throws EmailDocumentInputError; never truncates.
52
+ */
53
+ export declare function normalizeEmailDocumentContent(input: {
54
+ html: unknown;
55
+ text?: unknown;
56
+ previewText?: unknown;
57
+ editorJson?: unknown;
58
+ }): EmailDocumentContentInput;
59
+ export declare function normalizeEmailDocumentName(value: unknown, fallback: string): string;
60
+ export declare function isEmailDocumentRole(value: unknown): value is EmailDocumentRole;
61
+ export declare function isEmailDocumentKind(value: unknown): value is EmailDocumentKind;