@apex-inc/mcp-server 0.64.1 → 0.66.0

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 (44) hide show
  1. package/dist/letter-blocks.d.ts +15 -3
  2. package/dist/letter-blocks.d.ts.map +1 -1
  3. package/dist/letter-blocks.js +28 -1
  4. package/dist/letter-blocks.js.map +1 -1
  5. package/dist/setup-catchup-tools.d.ts +130 -4
  6. package/dist/setup-catchup-tools.d.ts.map +1 -1
  7. package/dist/setup-catchup-tools.js +205 -14
  8. package/dist/setup-catchup-tools.js.map +1 -1
  9. package/dist/tool-groups.d.ts.map +1 -1
  10. package/dist/tool-groups.js +12 -1
  11. package/dist/tool-groups.js.map +1 -1
  12. package/dist/tool-shared.d.ts +23 -2
  13. package/dist/tool-shared.d.ts.map +1 -1
  14. package/dist/tool-shared.js +36 -2
  15. package/dist/tool-shared.js.map +1 -1
  16. package/dist/tools/context.d.ts +33 -5
  17. package/dist/tools/context.d.ts.map +1 -1
  18. package/dist/tools/context.js +48 -6
  19. package/dist/tools/context.js.map +1 -1
  20. package/dist/tools/experiments.d.ts +26 -18
  21. package/dist/tools/experiments.d.ts.map +1 -1
  22. package/dist/tools/experiments.js +107 -19
  23. package/dist/tools/experiments.js.map +1 -1
  24. package/dist/tools/letters.d.ts +214 -29
  25. package/dist/tools/letters.d.ts.map +1 -1
  26. package/dist/tools/letters.js +325 -26
  27. package/dist/tools/letters.js.map +1 -1
  28. package/dist/tools/measurement.d.ts +68 -7
  29. package/dist/tools/measurement.d.ts.map +1 -1
  30. package/dist/tools/measurement.js +149 -41
  31. package/dist/tools/measurement.js.map +1 -1
  32. package/dist/tools/people.d.ts +99 -0
  33. package/dist/tools/people.d.ts.map +1 -0
  34. package/dist/tools/people.js +245 -0
  35. package/dist/tools/people.js.map +1 -0
  36. package/dist/tools.d.ts +588 -63
  37. package/dist/tools.d.ts.map +1 -1
  38. package/dist/tools.js +2 -0
  39. package/dist/tools.js.map +1 -1
  40. package/package.json +1 -1
  41. package/skills/apex-communications/SKILL.md +4 -3
  42. package/skills/apex-experimentation/SKILL.md +12 -0
  43. package/skills/apex-integration-cookbook/SKILL.md +1 -1
  44. package/skills/apex-setup/SKILL.md +1 -1
@@ -1,5 +1,5 @@
1
1
  import { z } from "zod";
2
- import { apiGet, apiPost, apiPatch, apiDelete, getActiveWorkspace, } from "../api-client.js";
2
+ import { apiGet, apiPost, apiPatch, apiDelete, apiDeleteJson, getActiveWorkspace, resolveActiveOrg, } from "../api-client.js";
3
3
  import { controlGateGuidanceFor } from "../control-gate-guidance.js";
4
4
  import { notStartedExplanation, publishedExperimentLine } from "../publish-communication-copy.js";
5
5
  import { applyAddJourneyStep } from "../add-journey-step.js";
@@ -8,7 +8,7 @@ import { refuseLiveApexObject } from "../live-test-guard.js";
8
8
  import { composeLetterDocument, letterBlocksFromDocument, letterBlockSchema } from "../letter-blocks.js";
9
9
  import { previewImages } from "../preview-images.js";
10
10
  import { commExperimentCreateBody, commExperimentVariantSchema, } from "../comm-experiment-create.js";
11
- import { APEX, errMsg, appUrl, journeyLink, tenantOk, tenantMismatch, } from "../tool-shared.js";
11
+ import { APEX, errMsg, appUrl, journeyLink, resolveActiveWorkspace, tenantOk, tenantMismatch, } from "../tool-shared.js";
12
12
  const QUIET_CAUSE = {
13
13
  rules: "its rules changed",
14
14
  import: "an import added them",
@@ -146,10 +146,24 @@ export const letterTools = {
146
146
  },
147
147
  },
148
148
  list_communication_themes: {
149
- description: "List workspace communication Themes (the look: fonts, sizes, colors, Title/Body/Button roles). A Theme is not a Template — Templates are the job (event, slots, copy). Activate a Template with no extra theme step; new emails wear the workspace default theme. Apply writes drafts only; the merchant still publishes each email.",
150
- schema: z.object({}),
151
- handler: async () => {
152
- const json = await apiGet("/api/communications/themes");
149
+ description: "List communication Themes (the look: fonts, sizes, colors, Title/Body/Button roles). Defaults to the active workspace's merged list (inherited organization themes marked scope='org' plus any workspace overrides marked overridesOrg=true). Pass scope='org' (with optional org_id) to inspect organization-level themes shared across every workspace. A Theme is not a Template — Templates are the job (event, slots, copy). Activate a Template with no extra theme step; new emails wear the default theme. Apply writes drafts only; the merchant still publishes each email.",
150
+ schema: z.object({
151
+ scope: z.enum(["workspace", "org"]).optional().describe("Default 'workspace' returns merged org + workspace themes. Pass 'org' to read organization-level themes directly."),
152
+ org_id: z.string().optional().describe("Organization ID when scope='org'. Defaults to the active organization."),
153
+ }),
154
+ handler: async (args) => {
155
+ let path = "/api/communications/themes";
156
+ if (args.scope === "org") {
157
+ const orgId = args.org_id?.trim() || (await resolveActiveOrg());
158
+ if (!orgId) {
159
+ return {
160
+ content: [{ type: "text", text: "No active organization. Pass org_id or call switch_org first." }],
161
+ isError: true,
162
+ };
163
+ }
164
+ path = `/api/orgs/${encodeURIComponent(orgId)}/themes`;
165
+ }
166
+ const json = await apiGet(path);
153
167
  return {
154
168
  content: [
155
169
  {
@@ -161,14 +175,64 @@ export const letterTools = {
161
175
  },
162
176
  },
163
177
  create_communication_theme: {
164
- description: "Create a communication Theme (the look). Clone an existing theme with clone_from_id, or pass style/roles. Does not assign other emails. Tell the merchant to publish emails after applying.",
178
+ description: "Create a communication Theme (the look) in the active workspace or at the organization level (scope='org', shared across every workspace). Pass promote_theme_id (and optional promote_from_workspace_key, defaulting to the active workspace) to share an existing workspace theme up to the organization. Or pass name + clone_from_id / style / roles to create a new theme. Does not rewrite existing emails; use apply_communication_theme to update emails.",
165
179
  schema: z.object({
166
- name: z.string().min(1).max(60),
180
+ name: z.string().min(1).max(60).optional().describe("Theme name. Required unless promoting an existing workspace theme via promote_theme_id."),
181
+ scope: z.enum(["workspace", "org"]).optional().describe("Where to create the theme: 'workspace' (default) or 'org' (shared across every workspace in the organization; org owner/admin only)."),
182
+ org_id: z.string().optional().describe("Organization ID when scope='org' or promoting a theme. Defaults to the active organization."),
167
183
  clone_from_id: z.string().optional(),
184
+ promote_theme_id: z.string().optional().describe("Promote an existing workspace theme up to the organization so sibling workspaces inherit it."),
185
+ promote_from_workspace_key: z.string().optional().describe("Source workspace key when using promote_theme_id. Defaults to the active workspace."),
186
+ set_default: z.boolean().optional().describe("When creating/promoting an org theme, also set it as the organization default."),
168
187
  style: z.record(z.string(), z.unknown()).optional(),
169
188
  roles: z.record(z.string(), z.unknown()).optional(),
170
189
  }),
171
190
  handler: async (args) => {
191
+ const isOrg = args.scope === "org" || Boolean(args.promote_theme_id);
192
+ if (isOrg) {
193
+ const orgId = args.org_id?.trim() || (await resolveActiveOrg());
194
+ if (!orgId) {
195
+ return {
196
+ content: [{ type: "text", text: "No active organization. Pass org_id or call switch_org first." }],
197
+ isError: true,
198
+ };
199
+ }
200
+ const sourceWs = args.promote_from_workspace_key?.trim() || getActiveWorkspace();
201
+ if (args.promote_theme_id && !sourceWs) {
202
+ return {
203
+ content: [{ type: "text", text: "Pass promote_from_workspace_key or switch_workspace first so Apex knows which workspace holds that theme." }],
204
+ isError: true,
205
+ };
206
+ }
207
+ if (!args.promote_theme_id && !args.name?.trim()) {
208
+ return {
209
+ content: [{ type: "text", text: "Pass name (or promote_theme_id to promote an existing workspace theme)." }],
210
+ isError: true,
211
+ };
212
+ }
213
+ const data = await apiPost(`/api/orgs/${encodeURIComponent(orgId)}/themes`, {
214
+ ...(args.name ? { name: args.name } : {}),
215
+ ...(args.clone_from_id ? { cloneFromId: args.clone_from_id } : {}),
216
+ ...(args.promote_theme_id
217
+ ? {
218
+ promoteThemeId: args.promote_theme_id,
219
+ promoteFromWorkspaceKey: sourceWs,
220
+ }
221
+ : {}),
222
+ ...(args.set_default !== undefined ? { setDefault: args.set_default } : {}),
223
+ ...(args.style ? { style: args.style } : {}),
224
+ ...(args.roles ? { roles: args.roles } : {}),
225
+ });
226
+ return {
227
+ content: [{ type: "text", text: JSON.stringify(data, null, 2) }],
228
+ };
229
+ }
230
+ if (!args.name?.trim()) {
231
+ return {
232
+ content: [{ type: "text", text: "name is required when creating a workspace theme." }],
233
+ isError: true,
234
+ };
235
+ }
172
236
  const data = await apiPost("/api/communications/themes", {
173
237
  name: args.name,
174
238
  cloneFromId: args.clone_from_id,
@@ -181,15 +245,42 @@ export const letterTools = {
181
245
  },
182
246
  },
183
247
  update_communication_theme: {
184
- description: "Update a communication Theme's name, style tokens, or Title/Body/Button roles. Does not rewrite other emails. Use apply_communication_theme to draft the look onto chosen emails. set_default makes new activations wear this theme.",
248
+ description: "Update a communication Theme's name, style tokens, or Title/Body/Button roles. Default scope='workspace' edits the workspace theme (creating a workspace custom copy if the theme is inherited from the organization). Pass scope='org' (org owner/admin) to update the shared organization theme for every inheriting workspace. Pass reset_to_org=true to drop a workspace custom copy so the workspace inherits the organization's live theme again. Does not rewrite existing emails; use apply_communication_theme to update emails.",
185
249
  schema: z.object({
186
250
  theme_id: z.string(),
251
+ scope: z.enum(["workspace", "org"]).optional().describe("Default 'workspace'. Pass 'org' to update the shared organization theme directly."),
252
+ org_id: z.string().optional().describe("Organization ID when scope='org'. Defaults to the active organization."),
253
+ reset_to_org: z.boolean().optional().describe("Drop a workspace custom override copy of an organization theme so this workspace inherits the organization's live theme again."),
187
254
  name: z.string().min(1).max(60).optional(),
188
255
  style: z.record(z.string(), z.unknown()).optional(),
189
256
  roles: z.record(z.string(), z.unknown()).optional(),
190
257
  set_default: z.boolean().optional(),
191
258
  }),
192
259
  handler: async (args) => {
260
+ if (args.reset_to_org) {
261
+ const data = await apiDelete(`/api/communications/themes/${encodeURIComponent(args.theme_id)}`);
262
+ return {
263
+ content: [{ type: "text", text: JSON.stringify(data, null, 2) }],
264
+ };
265
+ }
266
+ if (args.scope === "org") {
267
+ const orgId = args.org_id?.trim() || (await resolveActiveOrg());
268
+ if (!orgId) {
269
+ return {
270
+ content: [{ type: "text", text: "No active organization. Pass org_id or call switch_org first." }],
271
+ isError: true,
272
+ };
273
+ }
274
+ const data = await apiPatch(`/api/orgs/${encodeURIComponent(orgId)}/themes/${encodeURIComponent(args.theme_id)}`, {
275
+ name: args.name,
276
+ style: args.style,
277
+ roles: args.roles,
278
+ setDefault: args.set_default,
279
+ });
280
+ return {
281
+ content: [{ type: "text", text: JSON.stringify(data, null, 2) }],
282
+ };
283
+ }
193
284
  const data = await apiPatch(`/api/communications/themes/${encodeURIComponent(args.theme_id)}`, {
194
285
  name: args.name,
195
286
  style: args.style,
@@ -222,6 +313,69 @@ export const letterTools = {
222
313
  };
223
314
  },
224
315
  },
316
+ list_email_categories: {
317
+ description: "List optional marketing email categories in the active workspace. Workspaces with zero categories share one unsubscribe list; once categories exist, one-click unsubscribe stops only that category and every published marketing message picks an active category.",
318
+ schema: z.object({
319
+ includeArchived: z.boolean().optional().describe("Include archived categories"),
320
+ }),
321
+ handler: async (args) => {
322
+ const qs = args.includeArchived ? "?includeArchived=true" : "";
323
+ const json = await apiGet(`/api/communications/categories${qs}`);
324
+ return {
325
+ content: [{ type: "text", text: JSON.stringify(json, null, 2) }],
326
+ };
327
+ },
328
+ },
329
+ create_email_category: {
330
+ description: "Create a marketing email category (e.g. Product updates, Promotions). Once a workspace has at least one active category, recipients see topic toggles instead of internal journey names on the preferences page, and one-click unsubscribe stops only that category.",
331
+ schema: z.object({
332
+ name: z.string().describe("Category display name shown to recipients"),
333
+ description: z
334
+ .string()
335
+ .optional()
336
+ .describe("Short description shown on the preferences page"),
337
+ }),
338
+ handler: async (args) => {
339
+ const json = await apiPost("/api/communications/categories", {
340
+ name: args.name,
341
+ ...(args.description !== undefined ? { description: args.description } : {}),
342
+ });
343
+ return {
344
+ content: [{ type: "text", text: JSON.stringify(json, null, 2) }],
345
+ };
346
+ },
347
+ },
348
+ update_email_category: {
349
+ description: "Rename, edit the description of, or restore an archived marketing email category.",
350
+ schema: z.object({
351
+ categoryId: z.string().describe("The email category ID"),
352
+ name: z.string().optional().describe("New category display name"),
353
+ description: z.string().optional().describe("Updated description (empty string clears it)"),
354
+ archived: z.boolean().optional().describe("Set false to restore an archived category"),
355
+ }),
356
+ handler: async (args) => {
357
+ const json = await apiPatch(`/api/communications/categories/${encodeURIComponent(args.categoryId)}`, {
358
+ ...(args.name !== undefined ? { name: args.name } : {}),
359
+ ...(args.description !== undefined ? { description: args.description } : {}),
360
+ ...(args.archived !== undefined ? { archived: args.archived } : {}),
361
+ });
362
+ return {
363
+ content: [{ type: "text", text: JSON.stringify(json, null, 2) }],
364
+ };
365
+ },
366
+ },
367
+ archive_email_category: {
368
+ description: "Archive a marketing email category. Archived categories cannot be selected on new marketing sends and are hidden from the preferences page, while existing opt-outs remain honored.",
369
+ schema: z.object({
370
+ categoryId: z.string().describe("The email category ID to archive"),
371
+ }),
372
+ handler: async (args) => {
373
+ const json = await apiDeleteJson(`/api/communications/categories/${encodeURIComponent(args.categoryId)}`);
374
+ return {
375
+ content: [{ type: "text", text: JSON.stringify(json, null, 2) }],
376
+ };
377
+ },
378
+ },
225
379
  edit_communication: {
226
380
  description: "Update a communication's subject, body, CTA, channels, or status. Pass the communication ID and the fields to update. For blank/builder comms, the headline/body/ctaLabel/ctaUrl slots are synced into the rendered email body — verify with preview_communication.\n\nA communication's Control is protected when it won an experiment or a published journey is sending it. Editing it then requires `intent`: \"compete\" adds your edit as a variant and measures it against the current content (nothing changes for recipients yet); \"replace\" makes your edit what everyone receives and supersedes any prior win. WHEN IN DOUBT, USE \"compete\" — it is recoverable, \"replace\" discards a measured result permanently. The server returns 409 intent_required with both options if you omit it.",
227
381
  schema: z.object({
@@ -251,6 +405,10 @@ export const letterTools = {
251
405
  .boolean()
252
406
  .optional()
253
407
  .describe("Edit a communication that is the treatment in a RUNNING experiment. Marks the numbers untrustworthy: we will not call a winner and we will not learn from mixed counts. Only pass true when they picked an out."),
408
+ categoryId: z
409
+ .string()
410
+ .optional()
411
+ .describe("Optional marketing email category ID (`cat_...`). Required before publishing when the workspace defines email categories; pass empty string to clear."),
254
412
  }),
255
413
  handler: async (args) => {
256
414
  const guard = await refuseLiveApexObject({
@@ -272,6 +430,8 @@ export const letterTools = {
272
430
  body.intent = args.intent;
273
431
  if (args.confirmLiveExperiment)
274
432
  body.confirmLiveExperiment = true;
433
+ if (args.categoryId !== undefined)
434
+ body.categoryId = args.categoryId;
275
435
  const content = {};
276
436
  if (args.subject)
277
437
  content.subject = args.subject;
@@ -478,19 +638,33 @@ export const letterTools = {
478
638
  },
479
639
  },
480
640
  get_communication: {
481
- description: "Read one communication as written: title, status, channels, subject, and its body as the same sections edit_communication takes in `blocks` (heading, text, image, button, html, spacer, divider). Each section has an id. A section these types can't describe (a list of people or items, a product grid) comes back as keep with its kind. Read, change, and pass the sections back to edit_communication, ids and keep sections included, to edit a letter without losing its pictures, lists or layout. The brand header and footer are not listed; edits keep them. Shows the unpublished draft when there is one.",
641
+ description: "Read one communication as written: title, status, channels, subject, its body as the same sections edit_communication takes in `blocks` (heading, text, image, button, stat, html, spacer, divider), and any content variants (for A/B tests). Each section has an id. A section these types can't describe (a list of people or items, a product grid) comes back as keep with its kind. Read, change, and pass the sections back to edit_communication, ids and keep sections included, to edit a letter without losing its pictures, lists or layout. The brand header and footer are not listed; edits keep them. Shows the unpublished draft when there is one.",
482
642
  schema: z.object({
483
643
  communicationId: z.string().describe("The communication ID to read"),
484
644
  }),
485
645
  handler: async (args) => {
486
646
  const comm = await apiGet(`/api/communications/${encodeURIComponent(args.communicationId)}`);
487
- const showing = comm.draftContent ? "draft" : "published";
647
+ const showing = comm.draftContent || comm.status === "draft" ? "draft" : "published";
488
648
  const base = comm.draftContent ?? comm.content;
489
649
  const { blocks } = letterBlocksFromDocument(base?.builderDocument);
650
+ const formatVariants = (list) => (list ?? []).map((v) => ({
651
+ key: v.key,
652
+ label: v.label ?? v.key,
653
+ subject: v.emailSubject ?? null,
654
+ ...(v.pushTitle !== undefined ? { pushTitle: v.pushTitle } : {}),
655
+ ...(v.pushBody !== undefined ? { pushBody: v.pushBody } : {}),
656
+ ...(v.inAppTitle !== undefined ? { inAppTitle: v.inAppTitle } : {}),
657
+ ...(v.inAppBody !== undefined ? { inAppBody: v.inAppBody } : {}),
658
+ blocks: letterBlocksFromDocument(v.emailDoc).blocks,
659
+ }));
660
+ const variants = formatVariants(base?.variants);
661
+ const publishedVariantCount = comm.content?.variants?.length ?? 0;
662
+ const draftVariantCount = comm.draftContent?.variants?.length;
490
663
  const result = {
491
664
  id: comm.id,
492
665
  title: comm.title,
493
666
  status: comm.status,
667
+ ...(comm.kind ? { kind: comm.kind } : {}),
494
668
  channels: comm.channels,
495
669
  pipeline: comm.pipeline,
496
670
  version: comm.version,
@@ -498,6 +672,13 @@ export const letterTools = {
498
672
  subject: base?.subject ?? null,
499
673
  blocks,
500
674
  ...(blocks.length === 0 && base?.slots ? { slots: base.slots } : {}),
675
+ variants,
676
+ ...(draftVariantCount !== undefined && draftVariantCount !== publishedVariantCount
677
+ ? {
678
+ publishedVariantCount,
679
+ draftVariantCount,
680
+ }
681
+ : {}),
501
682
  };
502
683
  return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
503
684
  },
@@ -651,7 +832,7 @@ export const letterTools = {
651
832
  .describe("When true (default), fires a test event with is_test=1 for each event the seed depends on. The wizard's poll loop sees these and advances. Set to false if the agent only wants to read the snippets without writing test data."),
652
833
  }),
653
834
  handler: async ({ seedId, framework = "typescript", fireTestEvent = true, }) => {
654
- const workspaceKey = getActiveWorkspace() || (process.env.APEX_WORKSPACE_KEY || process.env.APEX_PROJECT_KEY);
835
+ const workspaceKey = await resolveActiveWorkspace();
655
836
  if (!workspaceKey) {
656
837
  return {
657
838
  content: [
@@ -740,7 +921,7 @@ export const letterTools = {
740
921
  .describe("When true (default), fires a test event with is_test=1 for each NON-AUTO-FIRED event the audience depends on. Auto-fired events (pageview, click, etc.) are skipped — they're already firing automatically and don't need a synthetic test."),
741
922
  }),
742
923
  handler: async ({ audienceId, framework = "typescript", fireTestEvent = true, }) => {
743
- const workspaceKey = getActiveWorkspace() || (process.env.APEX_WORKSPACE_KEY || process.env.APEX_PROJECT_KEY);
924
+ const workspaceKey = await resolveActiveWorkspace();
744
925
  if (!workspaceKey) {
745
926
  return {
746
927
  content: [
@@ -827,7 +1008,7 @@ export const letterTools = {
827
1008
  .describe("Segment id (the workspace's saved group, not the seed). Use list_segments first to find it."),
828
1009
  }),
829
1010
  handler: async ({ audienceId }) => {
830
- const workspaceKey = getActiveWorkspace() || (process.env.APEX_WORKSPACE_KEY || process.env.APEX_PROJECT_KEY);
1011
+ const workspaceKey = await resolveActiveWorkspace();
831
1012
  if (!workspaceKey) {
832
1013
  return {
833
1014
  content: [
@@ -933,15 +1114,87 @@ export const letterTools = {
933
1114
  },
934
1115
  },
935
1116
  set_journey_trigger: {
936
- description: `${APEX} — Set the entry trigger (what enrolls subjects) on a draft journey's trigger step. Pass event_name (the Apex Spec event, e.g. user_signed_up), or key_event_id (from list_key_events) to start it when someone reaches one of the workspace's key events: every event that reaches it counts, from now on, and people Apex finds in their history never start it. A trig-* contract id is storage-only — prefer the Spec name.`,
1117
+ description: `${APEX} — Set the entry trigger (what enrolls subjects) on a draft journey's trigger step. Pass exactly one of: event_name (the Apex Spec event, e.g. user_signed_up), key_event_id (from list_key_events: starts when someone reaches that key event from now on), segment_id (from list_segments or create_segment: starts when someone enters that segment), or trigger_contract_id (storage-only — prefer event_name).`,
937
1118
  schema: z.object({
938
1119
  journeyId: z.string(),
939
- eventName: z.string().optional().describe("Apex Spec event name that enrolls subjects (e.g. user_signed_up). Preferred."),
1120
+ eventName: z.string().optional().describe("Apex Spec event name that enrolls subjects (e.g. user_signed_up). Preferred for event triggers."),
940
1121
  keyEventId: z.string().optional().describe("Key event id from list_key_events: start when someone reaches it."),
1122
+ segmentId: z.string().optional().describe("Segment id from list_segments or create_segment: start when someone enters that segment."),
941
1123
  triggerContractId: z.string().optional().describe("Storage id from list_trigger_contracts. Prefer event_name."),
942
1124
  }),
943
- handler: async ({ journeyId, eventName, keyEventId, triggerContractId, }) => {
1125
+ handler: async ({ journeyId, eventName, keyEventId, segmentId, triggerContractId, }) => {
944
1126
  try {
1127
+ const providedKinds = [
1128
+ eventName ? "event_name" : null,
1129
+ keyEventId ? "key_event_id" : null,
1130
+ segmentId ? "segment_id" : null,
1131
+ triggerContractId ? "trigger_contract_id" : null,
1132
+ ].filter(Boolean);
1133
+ if (providedKinds.length > 1) {
1134
+ return {
1135
+ content: [
1136
+ {
1137
+ type: "text",
1138
+ text: `${APEX} Pass only one trigger source (got ${providedKinds.join(", ")}). Choose one of event_name, key_event_id, segment_id, or trigger_contract_id.`,
1139
+ },
1140
+ ],
1141
+ isError: true,
1142
+ };
1143
+ }
1144
+ if (segmentId) {
1145
+ let seg = null;
1146
+ try {
1147
+ const raw = await apiGet(`/api/segments/${encodeURIComponent(segmentId)}`);
1148
+ seg = raw?.segment ?? raw?.data ?? raw;
1149
+ }
1150
+ catch {
1151
+ try {
1152
+ const raw = await apiGet(`/api/audiences/${encodeURIComponent(segmentId)}`);
1153
+ seg = raw?.segment ?? raw?.data ?? raw;
1154
+ }
1155
+ catch {
1156
+ seg = null;
1157
+ }
1158
+ }
1159
+ if (!seg || !seg.id) {
1160
+ return {
1161
+ content: [
1162
+ {
1163
+ type: "text",
1164
+ text: `${APEX} Segment "${segmentId}" was not found. Call list_segments to see available segments or create_segment to make one.`,
1165
+ },
1166
+ ],
1167
+ isError: true,
1168
+ };
1169
+ }
1170
+ if (seg.archivedAt) {
1171
+ return {
1172
+ content: [
1173
+ {
1174
+ type: "text",
1175
+ text: `${APEX} Segment "${seg.name ?? segmentId}" is archived and cannot trigger a journey.`,
1176
+ },
1177
+ ],
1178
+ isError: true,
1179
+ };
1180
+ }
1181
+ const j = await apiGet(`/api/journeys/${encodeURIComponent(journeyId)}`);
1182
+ const steps = (j.steps ?? []).map((s) => s.type === "trigger"
1183
+ ? { ...s, trigger: { type: "audience_entry", audienceId: segmentId } }
1184
+ : s);
1185
+ const updated = await apiPatch(`/api/journeys/${encodeURIComponent(journeyId)}`, { steps });
1186
+ if (!tenantOk(updated.workspaceKey))
1187
+ return tenantMismatch();
1188
+ const segLabel = seg.name ? `"${seg.name}" (${segmentId})` : segmentId;
1189
+ return {
1190
+ content: [
1191
+ {
1192
+ type: "text",
1193
+ text: `${APEX} Journey ${journeyId} now starts when someone joins segment ${segLabel}. By default this starts people who join after publish; pass who_starts:"everyone_already_in" to publish_journey (or call start_people_already_in_segment) if you also want to enroll people already in the segment. View it: ${journeyLink(journeyId)}`,
1194
+ },
1195
+ ],
1196
+ };
1197
+ }
945
1198
  if (keyEventId) {
946
1199
  const j = await apiGet(`/api/journeys/${encodeURIComponent(journeyId)}`);
947
1200
  const steps = (j.steps ?? []).map((s) => s.type === "trigger" ? { ...s, trigger: { type: "audience_entry", audienceId: "", keyEventId } } : s);
@@ -971,7 +1224,7 @@ export const letterTools = {
971
1224
  }
972
1225
  if (!resolvedId) {
973
1226
  return {
974
- content: [{ type: "text", text: `${APEX} Pass event_name (preferred) or triggerContractId.` }],
1227
+ content: [{ type: "text", text: `${APEX} Pass event_name, key_event_id, segment_id, or trigger_contract_id.` }],
975
1228
  isError: true,
976
1229
  };
977
1230
  }
@@ -1085,6 +1338,13 @@ export const letterTools = {
1085
1338
  const updated = await apiPatch(`/api/journeys/${encodeURIComponent(args.journeyId)}`, { steps });
1086
1339
  if (!tenantOk(updated.workspaceKey))
1087
1340
  return tenantMismatch();
1341
+ // Promote a blank one-off letter to a template once attached to a
1342
+ // journey so subsequent edits land in draftContent until published.
1343
+ if (args.commId.startsWith("tcomm_blank_")) {
1344
+ await apiPatch(`/api/communications/${encodeURIComponent(args.commId)}`, {
1345
+ kind: "template",
1346
+ }).catch(() => undefined);
1347
+ }
1088
1348
  return {
1089
1349
  content: [{
1090
1350
  type: "text",
@@ -1213,19 +1473,43 @@ export const letterTools = {
1213
1473
  }),
1214
1474
  handler: async ({ journeyId, confirmLive, confirmTreatmentChange, whoStarts, }) => {
1215
1475
  const path = `/api/journeys/${encodeURIComponent(journeyId)}/publish`;
1216
- // Non-blocking coverage warnings ("we couldn't verify these until the
1217
- // journey fires") — surfaced so an agent can preview before publishing.
1476
+ // Non-blocking warnings: unheard events (workspace has never sent the
1477
+ // event yet) and variable-coverage warnings (fields we can't verify
1478
+ // until the journey fires).
1218
1479
  const warnText = (warnings) => {
1219
1480
  const list = Array.isArray(warnings) ? warnings.filter((w) => w?.reason) : [];
1220
1481
  if (list.length === 0)
1221
1482
  return "";
1222
- return (`\n\n${list.length} thing${list.length === 1 ? "" : "s"} we couldn't verify until it fires (preview with example data to check):\n` +
1223
- list.map((w) => ` • ${w.reason}`).join("\n"));
1483
+ const unheard = list.filter((w) => w.kind === "unheard_event");
1484
+ const other = list.filter((w) => w.kind !== "unheard_event");
1485
+ const blocks = [];
1486
+ if (unheard.length > 0) {
1487
+ blocks.push(`\n\n${unheard.length} event warning${unheard.length === 1 ? "" : "s"} (Apex has not received these events in this workspace yet):\n` +
1488
+ unheard.map((w) => ` • ${w.reason}`).join("\n"));
1489
+ }
1490
+ if (other.length > 0) {
1491
+ blocks.push(`\n\n${other.length} thing${other.length === 1 ? "" : "s"} we couldn't verify until it fires (preview with example data to check):\n` +
1492
+ other.map((w) => ` • ${w.reason}`).join("\n"));
1493
+ }
1494
+ return blocks.join("");
1224
1495
  };
1225
1496
  if (!confirmLive) {
1226
1497
  try {
1227
1498
  const dr = await apiPost(`${path}?dryRun=true`, {});
1228
- return { content: [{ type: "text", text: `${APEX} Dry-run passed — journey ${journeyId} is valid and ready.${warnText(dr?.warnings)}\nRe-call with confirmLive:true to publish it to live customers.` }] };
1499
+ const warnings = Array.isArray(dr?.warnings)
1500
+ ? dr.warnings.filter((w) => w?.reason)
1501
+ : [];
1502
+ const headline = warnings.length > 0
1503
+ ? `${APEX} Dry-run passed with ${warnings.length} warning${warnings.length === 1 ? "" : "s"} on journey ${journeyId} — review before publishing:`
1504
+ : `${APEX} Dry-run passed — journey ${journeyId} is valid and ready.`;
1505
+ return {
1506
+ content: [
1507
+ {
1508
+ type: "text",
1509
+ text: `${headline}${warnText(warnings)}\nRe-call with confirmLive:true to publish it to live customers.`,
1510
+ },
1511
+ ],
1512
+ };
1229
1513
  }
1230
1514
  catch (err) {
1231
1515
  // A variable-coverage block arrives here with a plain message like
@@ -1400,12 +1684,27 @@ export const letterTools = {
1400
1684
  .enum(["production", "beta", "dev"])
1401
1685
  .optional()
1402
1686
  .describe("Who this send is for. Default production. Never All or Unclassified."),
1687
+ categoryId: z
1688
+ .string()
1689
+ .optional()
1690
+ .describe("Optional marketing email category ID (`cat_...`) from list_email_categories."),
1403
1691
  }),
1404
- handler: async ({ title, channels, audience_bucket }) => {
1692
+ handler: async ({ title, channels, audience_bucket, categoryId, }) => {
1405
1693
  try {
1406
- const comm = await apiPost("/api/communications/blank", { title, channels });
1694
+ const comm = await apiPost("/api/communications/blank", {
1695
+ title,
1696
+ channels,
1697
+ kind: "template",
1698
+ });
1699
+ const patch = {};
1407
1700
  if (audience_bucket && audience_bucket !== "production") {
1408
- await apiPatch(`/api/communications/${comm.id}`, { audienceBucket: audience_bucket });
1701
+ patch.audienceBucket = audience_bucket;
1702
+ }
1703
+ if (categoryId !== undefined && categoryId.trim()) {
1704
+ patch.categoryId = categoryId.trim();
1705
+ }
1706
+ if (Object.keys(patch).length > 0) {
1707
+ await apiPatch(`/api/communications/${comm.id}`, patch);
1409
1708
  }
1410
1709
  if (!tenantOk(comm.workspaceKey))
1411
1710
  return tenantMismatch();