@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
@@ -0,0 +1,176 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { OxygenError } from "@oxygen/shared/cli-result";
3
+ import { sequenceContentStep, withSequenceStepBodyDocument } from "@oxygen/shared/sequences";
4
+ import { Command } from "commander";
5
+ import { parseJsonValue } from "./command-support.js";
6
+ import { requestOxygen } from "./http-client.js";
7
+ import { isRecord, readOption } from "./util.js";
8
+ export function readRevisionFlag(value, flag) {
9
+ if (value === undefined)
10
+ return undefined;
11
+ const revision = Number(value);
12
+ if (!Number.isInteger(revision) || revision < 1)
13
+ throw new OxygenError("invalid_request", `${flag} must be a positive integer.`, { exitCode: 2 });
14
+ return revision;
15
+ }
16
+ function readTextFile(path, flag) {
17
+ try {
18
+ return readFileSync(path, "utf8");
19
+ }
20
+ catch {
21
+ throw new OxygenError("invalid_request", `${flag} could not be read.`, { details: { flag, path }, exitCode: 2 });
22
+ }
23
+ }
24
+ /** The document fields a set call sends: from --html-file or a --json-file export, with optional text and preview overrides. */
25
+ export function contentBody(options) {
26
+ let exported = {};
27
+ if (options.jsonFile) {
28
+ const parsed = parseJsonValue(readTextFile(options.jsonFile, "--json-file"), "--json-file");
29
+ if (!isRecord(parsed) || typeof parsed.html !== "string") {
30
+ throw new OxygenError("invalid_request", "--json-file must hold a JSON object with html (and optional text, preview_text, editor_json).", { exitCode: 2 });
31
+ }
32
+ exported = parsed;
33
+ }
34
+ // Flags override the export field by field; one object, no self-spreads.
35
+ const html = options.htmlFile ? readTextFile(options.htmlFile, "--html-file") : exported.html;
36
+ const text = options.textFile ? readTextFile(options.textFile, "--text-file") : exported.text;
37
+ const previewText = options.previewText ?? exported.preview_text;
38
+ const name = readOption(options.name);
39
+ return {
40
+ html,
41
+ ...(text !== undefined ? { text } : {}),
42
+ ...(previewText !== undefined ? { preview_text: previewText } : {}),
43
+ ...(exported.editor_json !== undefined ? { editor_json: exported.editor_json } : {}),
44
+ ...(name ? { name } : {}),
45
+ };
46
+ }
47
+ /** A step's content links to its Sequence's web home (a newsletter's composer), not the document's. */
48
+ function sequenceLink(read) {
49
+ return read.web_url ? { web_url: read.web_url, deepLink: read.web_url } : {};
50
+ }
51
+ export async function readSequence(sequence) {
52
+ const read = await requestOxygen(`/api/cli/sequences/${encodeURIComponent(sequence)}`);
53
+ const loaded = read.sequence;
54
+ if (!loaded?.id || !loaded.definition) {
55
+ throw new OxygenError("sequence_not_found", "Sequence not found.", { details: { sequence }, exitCode: 4 });
56
+ }
57
+ return {
58
+ sequence: { ...loaded, id: loaded.id, definition: loaded.definition },
59
+ ...(read.sequence_revision ? { sequence_revision: read.sequence_revision } : {}),
60
+ ...(read.web_url ? { web_url: read.web_url } : {}),
61
+ };
62
+ }
63
+ async function contentGet(sequence, options) {
64
+ const stepId = readOption(options.step);
65
+ if (!stepId)
66
+ throw new OxygenError("invalid_request", "--step is required.", { exitCode: 2 });
67
+ const read = await readSequence(sequence);
68
+ const { step, bodyDocument } = sequenceContentStep(read.sequence.definition, stepId);
69
+ if (!bodyDocument) {
70
+ return {
71
+ sequence_id: read.sequence.id, step_id: stepId, body_document: null,
72
+ body_template: step.body_template ?? "", body_html_template: step.body_html_template ?? null,
73
+ next_step: `Give this step a designed body: oxygen sequences content set ${read.sequence.id} --step ${stepId} --html-file <file>`,
74
+ ...sequenceLink(read),
75
+ };
76
+ }
77
+ const query = bodyDocument.revision ? `?revision=${bodyDocument.revision}` : "";
78
+ const document = await requestOxygen(`/api/cli/email-documents/${encodeURIComponent(bodyDocument.id)}${query}`);
79
+ return { sequence_id: read.sequence.id, step_id: stepId, body_document: bodyDocument, ...document, ...sequenceLink(read) };
80
+ }
81
+ async function contentSet(sequence, options) {
82
+ const stepId = readOption(options.step);
83
+ if (!stepId)
84
+ throw new OxygenError("invalid_request", "--step is required.", { exitCode: 2 });
85
+ const fromDocument = readOption(options.fromDocument);
86
+ const fromStarter = readOption(options.fromStarter);
87
+ const sources = [fromDocument, fromStarter, options.htmlFile || options.jsonFile].filter(Boolean).length;
88
+ if (sources > 1) {
89
+ throw new OxygenError("conflicting_flags", "Pass one of --from-document, --from-starter or --html-file/--json-file.", { exitCode: 2 });
90
+ }
91
+ if (sources === 0) {
92
+ throw new OxygenError("invalid_request", "Pass --html-file, --json-file, --from-document or --from-starter.", { exitCode: 2 });
93
+ }
94
+ const revision = readRevisionFlag(options.revision, "--revision");
95
+ const expectedRevision = readRevisionFlag(options.expectedRevision, "--expected-revision");
96
+ if (revision !== undefined && !fromDocument)
97
+ throw new OxygenError("invalid_request", "--revision applies to --from-document.", { exitCode: 2 });
98
+ const body = fromDocument || fromStarter ? {} : contentBody(options);
99
+ const read = await readSequence(sequence);
100
+ const { bodyDocument } = sequenceContentStep(read.sequence.definition, stepId);
101
+ if (read.sequence.status && read.sequence.status !== "draft") {
102
+ throw new OxygenError("sequence_journey_locked", "A started sequence keeps the content it went live with. Duplicate it to a new draft to change the email.", {
103
+ details: { sequence_id: read.sequence.id, status: read.sequence.status, next_step: `oxygen sequences duplicate ${read.sequence.id}` }, exitCode: 1,
104
+ });
105
+ }
106
+ let saved;
107
+ if (fromDocument) {
108
+ saved = await requestOxygen(`/api/cli/email-documents/${encodeURIComponent(fromDocument)}`, {
109
+ method: "POST", body: {
110
+ action: "duplicate", role: "step",
111
+ ...(revision !== undefined ? { revision } : {}),
112
+ ...(readOption(options.name) ? { name: readOption(options.name) } : {}),
113
+ },
114
+ });
115
+ }
116
+ else if (fromStarter) {
117
+ saved = await requestOxygen("/api/cli/email-documents", {
118
+ method: "POST", body: { role: "step", starter_id: fromStarter, name: readOption(options.name) ?? `${read.sequence.name ?? "Sequence"}: ${stepId}` },
119
+ });
120
+ }
121
+ else if (bodyDocument) {
122
+ saved = await requestOxygen(`/api/cli/email-documents/${encodeURIComponent(bodyDocument.id)}`, {
123
+ method: "PATCH", body: { ...body, ...(expectedRevision !== undefined ? { expected_revision: expectedRevision } : {}) },
124
+ });
125
+ }
126
+ else {
127
+ saved = await requestOxygen("/api/cli/email-documents", {
128
+ method: "POST", body: { role: "step", name: `${read.sequence.name ?? "Sequence"}: ${stepId}`, ...body },
129
+ });
130
+ }
131
+ const documentId = saved.document?.id;
132
+ if (!documentId)
133
+ throw new OxygenError("unexpected_response", "The email was saved but its id was not returned; run sequences content get.", { exitCode: 1 });
134
+ const definition = withSequenceStepBodyDocument({ steps: read.sequence.definition.steps ?? [] }, stepId, documentId);
135
+ if (definition) {
136
+ await requestOxygen(`/api/cli/sequences/${encodeURIComponent(read.sequence.id)}`, {
137
+ method: "PATCH", body: { definition, ...(read.sequence_revision ? { expected_revision: read.sequence_revision } : {}) },
138
+ });
139
+ }
140
+ return { ...saved, sequence_id: read.sequence.id, step_id: stepId, body_document: { id: documentId }, definition_updated: definition !== null, ...sequenceLink(read) };
141
+ }
142
+ export function sequencesContentCommand(handleAsyncAction) {
143
+ return new Command("content")
144
+ .description("A newsletter step's designed email body (HTML up to 100 KB), stored as a revisioned email document the step references. Sends through a sending domain; merge tags render per recipient with HTML escaping; {{unsubscribe_url}} places the unsubscribe link (else a footer is added).")
145
+ .addCommand(new Command("get")
146
+ .description("Show an email step's content: its email document (HTML, text, preview text, revision, size against the 100 KB limit), or its plain body when it has none.")
147
+ .argument("<sequence>", "Sequence id or slug.")
148
+ .requiredOption("--step <id>", "The email_send step id.")
149
+ .option("--json", "Print a JSON envelope.")
150
+ .action(async (sequence, options) => {
151
+ await handleAsyncAction("sequences content get", options, () => contentGet(sequence, options));
152
+ }))
153
+ .addCommand(new Command("set")
154
+ .description("Set a draft sequence's email step body from an HTML file or an editor JSON export: saves a new revision of the step's email document (creating it on first use) and points the step at it. Scripts and event handlers are removed; HTML above 100 KB is refused.")
155
+ .argument("<sequence>", "Sequence id or slug (a draft).")
156
+ .requiredOption("--step <id>", "The email_send step id.")
157
+ .option("--html-file <path>", "The email HTML.")
158
+ .option("--json-file <path>", "A JSON object { html, text?, preview_text?, editor_json? }, e.g. the editor's export.")
159
+ .option("--text-file <path>", "The plain-text part. Default: derived from the HTML.")
160
+ .option("--preview-text <text>", "The inbox preview line shown after the subject.")
161
+ .option("--name <name>", "Document name.")
162
+ .option("--from-document <id>", "Start from a copy of this email document or template instead of a file.")
163
+ .option("--from-starter <id>", "Start from a copy of a built-in starter template (ids: `oxygen email-templates list`).")
164
+ .option("--revision <n>", "With --from-document: copy this revision (default its current one).")
165
+ .option("--expected-revision <n>", "Refuse the save if the step's document is no longer at this revision (another edit landed).")
166
+ .option("--json", "Print a JSON envelope.")
167
+ .action(async (sequence, options) => {
168
+ await handleAsyncAction("sequences content set", options, () => contentSet(sequence, options));
169
+ }))
170
+ .addCommand(new Command("templates")
171
+ .description("List the workspace's email templates and the built-in starters (no content); start a step from one with `sequences content set --from-document <id>` or `--from-starter <id>`. Manage them with `oxygen email-templates`.")
172
+ .option("--json", "Print a JSON envelope.")
173
+ .action(async (options) => {
174
+ await handleAsyncAction("sequences content templates", options, () => requestOxygen("/api/cli/email-documents?role=template"));
175
+ }));
176
+ }
@@ -0,0 +1,6 @@
1
+ import { Command } from "commander";
2
+ /** Validated `--interval`; undefined when absent. */
3
+ export declare function readNewsletterIntervalFlag(value: string | undefined): string | undefined;
4
+ /** The newsletter block of `sequences stats` (empty for a mailbox Sequence). */
5
+ export declare function formatNewsletterStatsLines(value: unknown): string[];
6
+ export declare function sequencesRecipientsCommand(): Command;
@@ -0,0 +1,108 @@
1
+ import { OxygenError } from "@oxygen/shared/cli-result";
2
+ import { NEWSLETTER_RECIPIENT_STATUSES, NEWSLETTER_TIMELINE_INTERVALS, isNewsletterRecipientStatus, isNewsletterTimelineInterval, } from "@oxygen/shared/newsletter-analytics";
3
+ import { Command } from "commander";
4
+ import { handleReadActionWithLens, renderTextTable } from "./command-support.js";
5
+ import { requestOxygen } from "./http-client.js";
6
+ import { isRecord } from "./util.js";
7
+ /**
8
+ * Newsletter analytics on the CLI: the `newsletter` block `sequences stats`
9
+ * prints for a sending-domain Sequence, its `--interval` flag, and
10
+ * `oxygen sequences recipients`. MCP twin: `oxygen_newsletters` stats / recipients.
11
+ */
12
+ const record = (value) => (isRecord(value) ? value : {});
13
+ const count = (value) => (typeof value === "number" && Number.isFinite(value) ? value : 0);
14
+ const percent = (value) => (typeof value === "number" && Number.isFinite(value) ? `${(value * 100).toFixed(1)}%` : "—");
15
+ /** Validated `--interval`; undefined when absent. */
16
+ export function readNewsletterIntervalFlag(value) {
17
+ if (value === undefined)
18
+ return undefined;
19
+ if (!isNewsletterTimelineInterval(value)) {
20
+ throw new OxygenError("invalid_request", `--interval must be one of ${NEWSLETTER_TIMELINE_INTERVALS.join(", ")}.`, { exitCode: 2 });
21
+ }
22
+ return value;
23
+ }
24
+ /** The newsletter block of `sequences stats` (empty for a mailbox Sequence). */
25
+ export function formatNewsletterStatsLines(value) {
26
+ if (!isRecord(value))
27
+ return [];
28
+ const opens = record(value.opens);
29
+ const clicks = record(value.clicks);
30
+ const bounces = record(value.bounces);
31
+ const rates = record(value.rates);
32
+ const lines = [
33
+ "",
34
+ "Newsletter (SES)",
35
+ `Targeted ${count(value.recipients_targeted)} · sent ${count(value.sent)} · delivered ${count(value.delivered)} · suppressed ${count(value.suppressed)}`,
36
+ ...renderTextTable(["METRIC", "UNIQUE", "TOTAL", "RATE"], [
37
+ ["Opens (estimated)", String(count(opens.unique)), String(count(opens.total)), percent(rates.open_rate)],
38
+ ["Clicks", String(count(clicks.unique)), String(count(clicks.total)), percent(rates.click_rate)],
39
+ ["Hard bounces", String(count(bounces.hard)), "", percent(rates.bounce_rate)],
40
+ ["Soft bounces", String(count(bounces.soft)), "", ""],
41
+ ["Complaints", String(count(value.complaints)), "", percent(rates.complaint_rate)],
42
+ ["Unsubscribes", String(count(value.unsubscribes)), "", percent(rates.unsubscribe_rate)],
43
+ ]),
44
+ "Opens are estimated (Apple Mail Privacy Protection and scanners open mail); bot events are excluded. Rates are over delivered, bounces over sent.",
45
+ ];
46
+ const links = Array.isArray(value.links) ? value.links.filter(isRecord) : [];
47
+ if (links.length > 0) {
48
+ lines.push("", ...renderTextTable(["LINK", "UNIQUE", "TOTAL"], links.map((link) => [
49
+ String(link.link ?? ""), String(count(link.unique_clicks)), String(count(link.total_clicks)),
50
+ ])));
51
+ }
52
+ return lines;
53
+ }
54
+ function formatRecipients(data) {
55
+ const recipients = Array.isArray(data.recipients) ? data.recipients.filter(isRecord) : [];
56
+ const total = count(data.total);
57
+ const offset = count(data.offset);
58
+ const lines = [
59
+ `${typeof data.name === "string" ? data.name : "Newsletter"}: ${total} ${data.status ? `${String(data.status)} ` : ""}recipient${total === 1 ? "" : "s"}`
60
+ + (recipients.length > 0 ? ` (showing ${offset + 1}-${offset + recipients.length})` : ""),
61
+ ];
62
+ if (recipients.length > 0) {
63
+ lines.push("", ...renderTextTable(["EMAIL", "STATUS", "OPENS", "CLICKS", "LAST EVENT"], recipients.map((row) => [
64
+ String(row.email ?? ""), String(row.status ?? ""), String(count(row.opens)), String(count(row.clicks)),
65
+ typeof row.last_event_at === "string" ? row.last_event_at : "—",
66
+ ])));
67
+ }
68
+ if (typeof data.next_offset === "number")
69
+ lines.push("", `Next page: --offset ${data.next_offset}`);
70
+ const link = typeof data.web_url === "string" ? data.web_url : null;
71
+ if (link)
72
+ lines.push("", link);
73
+ return `${lines.join("\n")}\n`;
74
+ }
75
+ function wholeFlag(value, flag) {
76
+ if (value === undefined)
77
+ return undefined;
78
+ if (!/^\d+$/.test(value.trim()))
79
+ throw new OxygenError("invalid_request", `${flag} must be a non-negative whole number.`, { exitCode: 2 });
80
+ return value.trim();
81
+ }
82
+ export function sequencesRecipientsCommand() {
83
+ return new Command("recipients")
84
+ .description(`A newsletter's (sending-domain Sequence's) recipients, one row per message with its status (${NEWSLETTER_RECIPIENT_STATUSES.join(", ")}), opens, clicks and last event, newest activity first. Paged by --offset. Opens are estimated; bot events are excluded. 0 credits.`)
85
+ .argument("<sequence>", "Sequence id or slug.")
86
+ .option("--status <status>", `Only recipients with this status: ${NEWSLETTER_RECIPIENT_STATUSES.join(", ")}.`)
87
+ .option("--limit <n>", "Rows per page (1-200, default 50).")
88
+ .option("--offset <n>", "Skip this many rows (pass next_offset from the previous page).")
89
+ .option("--json", "Print a JSON envelope.")
90
+ .action(async (sequence, options) => {
91
+ await handleReadActionWithLens("sequences recipients", options, () => {
92
+ if (options.status !== undefined && !isNewsletterRecipientStatus(options.status)) {
93
+ throw new OxygenError("invalid_request", `--status must be one of ${NEWSLETTER_RECIPIENT_STATUSES.join(", ")}.`, { exitCode: 2 });
94
+ }
95
+ const params = new URLSearchParams();
96
+ if (options.status)
97
+ params.set("status", options.status);
98
+ const limit = wholeFlag(options.limit, "--limit");
99
+ if (limit !== undefined)
100
+ params.set("limit", limit);
101
+ const offset = wholeFlag(options.offset, "--offset");
102
+ if (offset !== undefined)
103
+ params.set("offset", offset);
104
+ const query = params.toString();
105
+ return requestOxygen(`/api/cli/sequences/${encodeURIComponent(sequence)}/recipients${query ? `?${query}` : ""}`);
106
+ }, formatRecipients);
107
+ });
108
+ }
@@ -0,0 +1,3 @@
1
+ import { Command } from "commander";
2
+ import type { ExtractedCommandActionHandler } from "./command-support.js";
3
+ export declare function sequencesTestSendCommand(handleAsyncAction: ExtractedCommandActionHandler): Command;
@@ -0,0 +1,47 @@
1
+ import { OxygenError } from "@oxygen/shared/cli-result";
2
+ import { NEWSLETTER_TEST_MAX_RECIPIENTS } from "@oxygen/shared/newsletter-test-send";
3
+ import { Command } from "commander";
4
+ import { parseJsonValue } from "./command-support.js";
5
+ import { requestOxygen } from "./http-client.js";
6
+ import { isRecord, readOption } from "./util.js";
7
+ async function testSend(sequence, options) {
8
+ if (options.listRecipients) {
9
+ if (options.to || options.sampleLead) {
10
+ throw new OxygenError("conflicting_flags", "--list-recipients takes no --to or --sample-lead.", { exitCode: 2 });
11
+ }
12
+ return requestOxygen(`/api/cli/sequences/${encodeURIComponent(sequence)}/test-send`);
13
+ }
14
+ const stepId = readOption(options.step);
15
+ if (!stepId)
16
+ throw new OxygenError("invalid_request", "--step is required.", { exitCode: 2 });
17
+ const to = (options.to ?? "").split(",").map((entry) => entry.trim()).filter(Boolean);
18
+ if (to.length === 0)
19
+ throw new OxygenError("invalid_request", "--to is required: one or more member email addresses, comma-separated.", { exitCode: 2 });
20
+ if (to.length > NEWSLETTER_TEST_MAX_RECIPIENTS) {
21
+ throw new OxygenError("invalid_request", `--to takes at most ${NEWSLETTER_TEST_MAX_RECIPIENTS} addresses.`, { exitCode: 2 });
22
+ }
23
+ let sampleLead;
24
+ if (options.sampleLead !== undefined) {
25
+ const parsed = parseJsonValue(options.sampleLead, "--sample-lead");
26
+ if (!isRecord(parsed))
27
+ throw new OxygenError("invalid_request", "--sample-lead must be a JSON object of merge values.", { exitCode: 2 });
28
+ sampleLead = parsed;
29
+ }
30
+ return requestOxygen(`/api/cli/sequences/${encodeURIComponent(sequence)}/test-send`, {
31
+ method: "POST",
32
+ body: { step_id: stepId, to, ...(sampleLead ? { sample_lead: sampleLead } : {}) },
33
+ });
34
+ }
35
+ export function sequencesTestSendCommand(handleAsyncAction) {
36
+ return new Command("test-send")
37
+ .description(`Send a test copy of a newsletter (sending-domain) email step to up to ${NEWSLETTER_TEST_MAX_RECIPIENTS} verified addresses of this workspace's members, rendered as delivery renders it with the subject prefixed "[Test]". Costs 0.05 credits per email; 20 test sends per workspace per day. Writes no Sequence activity and is left out of analytics.`)
38
+ .argument("<sequence>", "Sequence id or slug.")
39
+ .option("--step <id>", "The email_send step id.")
40
+ .option("--to <emails>", "Member email addresses, comma-separated.")
41
+ .option("--sample-lead <json>", "Merge values as a JSON object. Default: the first enrolled lead's values, else each tag's fallback.")
42
+ .option("--list-recipients", "List the member addresses a test may go to instead of sending.")
43
+ .option("--json", "Print a JSON envelope.")
44
+ .action(async (sequence, options) => {
45
+ await handleAsyncAction("sequences test-send", options, () => testSend(sequence, options));
46
+ });
47
+ }
@@ -1,7 +1,7 @@
1
1
  import { OxygenError } from "@oxygen/shared/cli-result";
2
2
  import { evaluateNoveltyScore } from "./refactor-internals/novelty-score.js";
3
3
  import { CROSS_ROW_FUNCTIONS, parseFormulaExpression, } from "./expression.js";
4
- import { FORMULA_FUNCTION_REGISTRY, checkFormulaFunctionArity, compareFormulaValues, formulaExpressionError, formulaValuesEqual, readFormulaNumber, toFormulaBoolean, } from "./formula-functions.js";
4
+ import { FORMULA_FUNCTION_REGISTRY, checkFormulaFunctionArity, compareFormulaValues, unsupportedFormulaFunctionError, formulaExpressionError, formulaValuesEqual, readFormulaNumber, toFormulaBoolean, } from "./formula-functions.js";
5
5
  export function evaluateFormulaInScope(expression, scope, options = {}) {
6
6
  return evaluateFormulaAst(parseFormulaExpression(expression, options), scope);
7
7
  }
@@ -37,9 +37,7 @@ function evaluateFormulaAstWithMode(node, scope, resolutionMode) {
37
37
  if (spec?.evaluate) {
38
38
  return spec.evaluate(node.args.map(evaluateArgument));
39
39
  }
40
- throw formulaExpressionError("Unsupported formula function.", {
41
- function: node.name,
42
- });
40
+ throw unsupportedFormulaFunctionError(node.name);
43
41
  }
44
42
  }
45
43
  }
@@ -19,11 +19,6 @@ export type FormulaAst = {
19
19
  name: string;
20
20
  args: FormulaAst[];
21
21
  };
22
- /**
23
- * Functions evaluated against the whole column rather than the current scope.
24
- * They are intercepted before registry dispatch (the registry entry carries
25
- * metadata only) because they need a corpus the scope supplies.
26
- */
27
22
  export declare const CROSS_ROW_FUNCTIONS: ReadonlySet<string>;
28
23
  /**
29
24
  * How to tokenize. One flag today, and it is deliberately opt-in: a table formula
@@ -62,6 +57,13 @@ export declare function validateFormulaAst(ast: FormulaAst): void;
62
57
  * for days with received_length 290 against the old 256 cap.
63
58
  */
64
59
  export declare function validateFormulaRegexLiterals(ast: FormulaAst): void;
60
+ /**
61
+ * SAVE-TIME ONLY, like validateFormulaRegexLiterals: refuse `||` next to a text
62
+ * literal. `||` is logical or here, so SQL's `first_name || ' ' || last_name`
63
+ * parses and stores, then fills every row with `true`. Stored columns keep
64
+ * reading; only a new write is refused, with the concat form to use instead.
65
+ */
66
+ export declare function validateFormulaTextJoin(expression: string): void;
65
67
  /** Validate syntax, supported functions, and arity without evaluating any data. */
66
68
  export declare function validateFormulaExpression(expression: string, options?: ParseOptions): void;
67
69
  export declare function walkExpression(node: FormulaAst, visit: (node: FormulaAst) => void): void;
@@ -1,9 +1,11 @@
1
- import { FORMULA_FUNCTION_REGISTRY, MAX_FORMULA_REGEX_PATTERN_LENGTH, checkFormulaFunctionArity, formulaExpressionError, } from "./formula-functions.js";
1
+ import { FORMULA_FUNCTION_REGISTRY, MAX_FORMULA_REGEX_PATTERN_LENGTH, checkFormulaFunctionArity, formulaExpressionError, unsupportedFormulaFunctionError, } from "./formula-functions.js";
2
2
  /**
3
3
  * Functions evaluated against the whole column rather than the current scope.
4
4
  * They are intercepted before registry dispatch (the registry entry carries
5
5
  * metadata only) because they need a corpus the scope supplies.
6
6
  */
7
+ /** SQL an author pasted: `case when`, `cast(x as type)` or `x::type`. */
8
+ const SQL_SYNTAX_PATTERN = /\bcase\s+when\b|\bcast\s*\([^)]*\bas\b|::/i;
7
9
  export const CROSS_ROW_FUNCTIONS = new Set(["novelty_score"]);
8
10
  export function parseFormulaExpression(expression, options = {}) {
9
11
  const parser = new FormulaParser(tokenize(expression, options), expression);
@@ -30,9 +32,7 @@ export function validateFormulaAst(ast) {
30
32
  }
31
33
  const spec = FORMULA_FUNCTION_REGISTRY.get(normalized);
32
34
  if (!spec) {
33
- throw formulaExpressionError("Unsupported formula function.", {
34
- function: node.name,
35
- });
35
+ throw unsupportedFormulaFunctionError(node.name);
36
36
  }
37
37
  checkFormulaFunctionArity(spec, node.args.length);
38
38
  });
@@ -78,6 +78,22 @@ export function validateFormulaRegexLiterals(ast) {
78
78
  });
79
79
  });
80
80
  }
81
+ /**
82
+ * SAVE-TIME ONLY, like validateFormulaRegexLiterals: refuse `||` next to a text
83
+ * literal. `||` is logical or here, so SQL's `first_name || ' ' || last_name`
84
+ * parses and stores, then fills every row with `true`. Stored columns keep
85
+ * reading; only a new write is refused, with the concat form to use instead.
86
+ */
87
+ export function validateFormulaTextJoin(expression) {
88
+ const tokens = tokenize(expression);
89
+ tokens.forEach((token, index) => {
90
+ if (token.type !== "operator" || token.value !== "||")
91
+ return;
92
+ if (tokens[index - 1]?.type !== "string" && tokens[index + 1]?.type !== "string")
93
+ return;
94
+ throw formulaExpressionError("|| is logical or in formulas, not text joining; join text with concat(first_name, \" \", last_name).", { position: token.position, expression, hint: "Use concat(a, b, ...) to join text; || and or compare truth values." });
95
+ });
96
+ }
81
97
  /** Validate syntax, supported functions, and arity without evaluating any data. */
82
98
  export function validateFormulaExpression(expression, options = {}) {
83
99
  validateFormulaAst(parseFormulaExpression(expression, options));
@@ -310,6 +326,9 @@ class FormulaParser {
310
326
  return formulaExpressionError(message, {
311
327
  position: token.position,
312
328
  expression: this.expression,
329
+ ...(SQL_SYNTAX_PATTERN.test(this.expression)
330
+ ? { hint: "SQL CASE/CAST is not formula syntax: use if(condition, then, else), switch(value, case1, result1, ..., default) and number(value)." }
331
+ : {}),
313
332
  });
314
333
  }
315
334
  }
@@ -423,6 +442,9 @@ function tokenize(expression, options = {}) {
423
442
  position: index,
424
443
  character: char,
425
444
  expression,
445
+ ...(char === "[" || char === "]"
446
+ ? { hint: "Formulas have no [index] access: use first(list), last(list), path(value, \"0\") or email_domain(email)." }
447
+ : {}),
426
448
  });
427
449
  }
428
450
  tokens.push({ type: "eof", position: expression.length });
@@ -50,6 +50,12 @@ export declare function readFormulaJsonPath(value: unknown, rawPath: string): un
50
50
  export declare function checkFormulaFunctionArity(spec: FormulaFunctionMeta, received: number): void;
51
51
  export declare const FORMULA_DATE_UNITS: readonly ["seconds", "minutes", "hours", "days", "weeks", "months", "years"];
52
52
  export declare const FORMULA_FUNCTION_REGISTRY: ReadonlyMap<string, FormulaFunctionSpec>;
53
+ /**
54
+ * The refusal for a call to a function the formula language does not have:
55
+ * the likely intended function (`did_you_mean`) and every supported name, so the
56
+ * author corrects the call without another lookup.
57
+ */
58
+ export declare function unsupportedFormulaFunctionError(name: string): OxygenError;
53
59
  export declare const FORMULA_FUNCTION_CATEGORIES: readonly FormulaFunctionCategory[];
54
60
  export declare function listFormulaFunctions(category?: FormulaFunctionCategory): FormulaFunctionMeta[];
55
61
  /** Operators the expression language supports, for the discovery surfaces. */
@@ -1204,6 +1204,61 @@ const SPECS = [
1204
1204
  }),
1205
1205
  ];
1206
1206
  export const FORMULA_FUNCTION_REGISTRY = new Map(SPECS.map((entry) => [entry.name, entry]));
1207
+ /**
1208
+ * Names authors bring from spreadsheets, SQL and JavaScript, mapped to the
1209
+ * function here that does that job. Keys are normalized (lowercase, no `_`).
1210
+ */
1211
+ const FORMULA_FUNCTION_ALIASES = {
1212
+ tonumber: "number", parseint: "number", parsefloat: "number", int: "number", float: "number", value: "number", cast: "number", numeric: "number",
1213
+ tostring: "text", str: "text", string: "text",
1214
+ regexpreplace: "regex_replace", regexreplace: "regex_replace", regexpextract: "regex_extract", regexpsubstr: "regex_extract",
1215
+ regexextract: "regex_extract", regexpmatch: "regex_match", regexplike: "regex_match", regexmatch: "regex_match", match: "regex_match",
1216
+ splitpart: "split", indexof: "contains", includes: "contains", instr: "contains", strpos: "contains", position: "contains", find: "contains", search: "contains",
1217
+ substr: "substring", mid: "substring", len: "length", charlength: "length", lengthb: "length",
1218
+ tolowercase: "lower", lcase: "lower", touppercase: "upper", ucase: "upper", proper: "title_case", initcap: "title_case",
1219
+ iif: "if", ifs: "switch", case: "switch", ifnull: "coalesce", nvl: "coalesce", isnull: "is_blank", isblank: "is_blank", isempty: "is_blank",
1220
+ datediff: "date_diff", dateadd: "date_add", datevalue: "date_parse", todate: "date_parse", formatdate: "date_format", textjoin: "join",
1221
+ startswith: "starts_with", endswith: "ends_with", average: "avg", mean: "avg", size: "count", domain: "email_domain",
1222
+ };
1223
+ /**
1224
+ * The refusal for a call to a function the formula language does not have:
1225
+ * the likely intended function (`did_you_mean`) and every supported name, so the
1226
+ * author corrects the call without another lookup.
1227
+ */
1228
+ export function unsupportedFormulaFunctionError(name) {
1229
+ const suggestions = suggestFormulaFunctions(name);
1230
+ const supported = [...FORMULA_FUNCTION_REGISTRY.keys()].sort();
1231
+ return formulaExpressionError(suggestions.length > 0
1232
+ ? `Unsupported formula function ${name}; did you mean ${suggestions.join(" or ")}?`
1233
+ : `Unsupported formula function ${name}; use one of details.supported_functions.`, {
1234
+ function: name,
1235
+ ...(suggestions.length > 0 ? { did_you_mean: suggestions } : {}),
1236
+ supported_functions: supported,
1237
+ next_step: "Read signatures and examples with `oxygen formulas functions` (MCP oxygen_formulas_list).",
1238
+ });
1239
+ }
1240
+ function suggestFormulaFunctions(name) {
1241
+ const key = name.toLowerCase().replace(/_/g, "");
1242
+ const alias = FORMULA_FUNCTION_ALIASES[key];
1243
+ if (alias)
1244
+ return [alias];
1245
+ const ranked = [...FORMULA_FUNCTION_REGISTRY.keys()]
1246
+ .map((candidate) => ({ candidate, distance: editDistance(key, candidate.replace(/_/g, "")) }))
1247
+ .filter((entry) => entry.distance <= Math.max(1, Math.floor(key.length / 4)))
1248
+ .sort((a, b) => a.distance - b.distance || a.candidate.localeCompare(b.candidate));
1249
+ return ranked.slice(0, 2).map((entry) => entry.candidate);
1250
+ }
1251
+ function editDistance(a, b) {
1252
+ let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
1253
+ for (let i = 1; i <= a.length; i += 1) {
1254
+ const current = [i];
1255
+ for (let j = 1; j <= b.length; j += 1) {
1256
+ current[j] = Math.min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
1257
+ }
1258
+ previous = current;
1259
+ }
1260
+ return previous[b.length];
1261
+ }
1207
1262
  export const FORMULA_FUNCTION_CATEGORIES = [
1208
1263
  "logic",
1209
1264
  "string",
@@ -64,14 +64,14 @@ export declare const CREDITS_PER_USD = 100;
64
64
  */
65
65
  export declare function creditTopupUsdCentsPer100(options?: RepricingOptions): number;
66
66
  export declare const CREDIT_TOPUP_MIN_CREDITS = 800;
67
- export declare const CREDIT_TOPUP_MAX_CREDITS = 100000;
67
+ export declare const CREDIT_TOPUP_MAX_CREDITS = 769200;
68
68
  export declare const CREDIT_TOPUP_STEP_CREDITS = 100;
69
69
  export declare const CREDIT_TOPUP_DEFAULT_CREDITS = 2000;
70
70
  export declare function isValidCreditTopupCredits(credits: number): boolean;
71
71
  /**
72
72
  * A shortfall expressed as an amount `oxygen billing topup` will actually SELL:
73
73
  * rounded up onto CREDIT_TOPUP_STEP_CREDITS (100) and clamped into the purchasable
74
- * [CREDIT_TOPUP_MIN_CREDITS .. CREDIT_TOPUP_MAX_CREDITS] band (800 .. 100,000). A next_action (or an alert email) naming a number the
74
+ * [CREDIT_TOPUP_MIN_CREDITS .. CREDIT_TOPUP_MAX_CREDITS] band. A next_action (or an alert email) naming a number the
75
75
  * top-up route refuses with `invalid_topup_amount` is not a next action, it is a
76
76
  * second dead end during the incident it exists to end.
77
77
  *
@@ -63,13 +63,11 @@ export const CREDITS_PER_USD = SNAPSHOT_CREDITS_PER_USD;
63
63
  export function creditTopupUsdCentsPer100(options = {}) {
64
64
  return repricedValue(TOPUP_RATE_REPRICING, options);
65
65
  }
66
- // On-demand purchases run from 800 to 100,000 credits in any 100-credit
67
- // increment ($10.00 to $1,250 at $1.25 per 100; $10.40 to $1,300 at $1.30). The
68
- // ceiling is a single-checkout guard rail, not a spend cap: a workspace that
69
- // needs more tops up again (purchased credits never expire). The range and step
70
- // are unchanged by the 2026-09 repricing (proposal P-7).
66
+ // On-demand purchases run in 100-credit increments up to $10,000 before tax.
67
+ // At $1.30 per 100, the largest whole increment is 769,200 credits ($9,999.60).
68
+ // The ceiling is per checkout; purchased credits never expire.
71
69
  export const CREDIT_TOPUP_MIN_CREDITS = 800;
72
- export const CREDIT_TOPUP_MAX_CREDITS = 100_000;
70
+ export const CREDIT_TOPUP_MAX_CREDITS = 769_200;
73
71
  export const CREDIT_TOPUP_STEP_CREDITS = 100;
74
72
  export const CREDIT_TOPUP_DEFAULT_CREDITS = 2_000;
75
73
  export function isValidCreditTopupCredits(credits) {
@@ -81,7 +79,7 @@ export function isValidCreditTopupCredits(credits) {
81
79
  /**
82
80
  * A shortfall expressed as an amount `oxygen billing topup` will actually SELL:
83
81
  * rounded up onto CREDIT_TOPUP_STEP_CREDITS (100) and clamped into the purchasable
84
- * [CREDIT_TOPUP_MIN_CREDITS .. CREDIT_TOPUP_MAX_CREDITS] band (800 .. 100,000). A next_action (or an alert email) naming a number the
82
+ * [CREDIT_TOPUP_MIN_CREDITS .. CREDIT_TOPUP_MAX_CREDITS] band. A next_action (or an alert email) naming a number the
85
83
  * top-up route refuses with `invalid_topup_amount` is not a next action, it is a
86
84
  * second dead end during the incident it exists to end.
87
85
  *