@hogsend/engine 0.41.0 → 0.43.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 (43) hide show
  1. package/package.json +12 -9
  2. package/src/container.ts +192 -4
  3. package/src/env.ts +28 -0
  4. package/src/index.ts +53 -0
  5. package/src/journeys/execute-journey-run.ts +50 -17
  6. package/src/journeys/journey-boundary.ts +5 -1
  7. package/src/journeys/journey-context.ts +58 -0
  8. package/src/lib/blueprint-lock.ts +21 -0
  9. package/src/lib/blueprints.ts +273 -46
  10. package/src/lib/event-names.ts +143 -0
  11. package/src/lib/journey-suppress.ts +33 -2
  12. package/src/lib/outbound.ts +58 -0
  13. package/src/lib/phone.ts +19 -0
  14. package/src/lib/preferences.ts +32 -0
  15. package/src/lib/sms-frequency-cap.ts +47 -0
  16. package/src/lib/sms-inbound.ts +200 -0
  17. package/src/lib/sms-link-tracking.ts +160 -0
  18. package/src/lib/sms-mailer.ts +338 -0
  19. package/src/lib/sms-provider-registry.ts +35 -0
  20. package/src/lib/sms-providers-from-env.ts +100 -0
  21. package/src/lib/sms-service-types.ts +169 -0
  22. package/src/lib/sms-tracked.ts +590 -0
  23. package/src/lib/sms.ts +117 -0
  24. package/src/lib/tracking-event-names.ts +6 -0
  25. package/src/lib/tracking-events.ts +107 -1
  26. package/src/lib/tracking.ts +3 -6
  27. package/src/lib/webhook-signing.ts +17 -1
  28. package/src/lists/channels.ts +21 -0
  29. package/src/mcp/authoring-guide.ts +160 -0
  30. package/src/mcp/blueprint-tools.ts +38 -108
  31. package/src/middleware/require-admin.ts +13 -0
  32. package/src/routes/admin/api-keys.ts +72 -0
  33. package/src/routes/admin/blueprints.ts +94 -10
  34. package/src/routes/admin/events.ts +55 -0
  35. package/src/routes/email/unsubscribe.ts +1 -0
  36. package/src/routes/index.ts +6 -0
  37. package/src/routes/lists/index.ts +54 -7
  38. package/src/routes/tracking/click-pipeline.ts +83 -2
  39. package/src/routes/tracking/short.ts +61 -0
  40. package/src/routes/webhooks/index.ts +5 -1
  41. package/src/routes/webhooks/sms-provider.ts +110 -0
  42. package/src/workflows/import-contacts.ts +61 -4
  43. package/src/workflows/journey-blueprint-interpreter.ts +128 -33
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hogsend/engine",
3
- "version": "0.41.0",
3
+ "version": "0.43.0",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -15,6 +15,7 @@
15
15
  "./worker": "./src/worker.ts",
16
16
  "./auth": "./src/lib/auth.ts",
17
17
  "./create-admin": "./src/lib/create-admin.ts",
18
+ "./mcp/authoring-guide": "./src/mcp/authoring-guide.ts",
18
19
  "./package.json": "./package.json"
19
20
  },
20
21
  "files": [
@@ -31,6 +32,8 @@
31
32
  "@openrouter/ai-sdk-provider": "^2.9.1",
32
33
  "@scalar/hono-api-reference": "^0.10.19",
33
34
  "@t3-oss/env-core": "^0.13.11",
35
+ "@types/papaparse": "^5.5.2",
36
+ "@types/qrcode": "^1.5.6",
34
37
  "acorn": "^8.17.0",
35
38
  "acorn-walk": "^8.3.5",
36
39
  "ai": "^6.0.209",
@@ -46,19 +49,19 @@
46
49
  "svix": "^1.95.1",
47
50
  "winston": "^3.19.0",
48
51
  "zod": "^4.4.3",
49
- "@hogsend/core": "^0.41.0",
50
- "@hogsend/db": "^0.41.0",
51
- "@hogsend/email": "^0.41.0",
52
- "@hogsend/plugin-posthog": "^0.41.0",
53
- "@hogsend/plugin-resend": "^0.41.0"
52
+ "@hogsend/core": "^0.43.0",
53
+ "@hogsend/db": "^0.43.0",
54
+ "@hogsend/email": "^0.43.0",
55
+ "@hogsend/plugin-posthog": "^0.43.0",
56
+ "@hogsend/plugin-resend": "^0.43.0",
57
+ "@hogsend/sms": "^0.43.0"
54
58
  },
55
59
  "optionalDependencies": {
56
- "@hogsend/plugin-postmark": "^0.41.0"
60
+ "@hogsend/plugin-postmark": "^0.43.0",
61
+ "@hogsend/plugin-twilio": "^0.43.0"
57
62
  },
58
63
  "devDependencies": {
59
64
  "@types/node": "^22.15.3",
60
- "@types/papaparse": "^5.5.2",
61
- "@types/qrcode": "^1.5.6",
62
65
  "tsx": "^4.22.3",
63
66
  "@repo/typescript-config": "0.0.0"
64
67
  },
package/src/container.ts CHANGED
@@ -5,6 +5,7 @@ import type {
5
5
  EmailProvider,
6
6
  JourneySourceLocation,
7
7
  PostHogService,
8
+ SmsProvider,
8
9
  TimeZone,
9
10
  } from "@hogsend/core";
10
11
  import type { BucketRegistry, JourneyRegistry } from "@hogsend/core/registry";
@@ -16,6 +17,7 @@ import {
16
17
  type JournalShape,
17
18
  } from "@hogsend/db";
18
19
  import type { TemplateDefinition, TemplateRegistry } from "@hogsend/email";
20
+ import type { SmsTemplateDefinition, SmsTemplateRegistry } from "@hogsend/sms";
19
21
  import { createBucketAccessor } from "./buckets/bucket-access.js";
20
22
  import type { DefinedBucket } from "./buckets/define-bucket.js";
21
23
  import {
@@ -78,6 +80,11 @@ import { createTrackedMailer } from "./lib/mailer.js";
78
80
  import { createRedisSecondaryStorage, getRedis } from "./lib/redis.js";
79
81
  import { sendResetPasswordEmail } from "./lib/reset-email.js";
80
82
  import { seedPostHogDestination } from "./lib/seed-posthog-destination.js";
83
+ import { setSmsService } from "./lib/sms.js";
84
+ import { createTrackedSmsSender } from "./lib/sms-mailer.js";
85
+ import { SmsProviderRegistry } from "./lib/sms-provider-registry.js";
86
+ import { smsProvidersFromEnv } from "./lib/sms-providers-from-env.js";
87
+ import type { SmsService } from "./lib/sms-service-types.js";
81
88
  import { prepareTrackedHtml } from "./lib/tracking.js";
82
89
  import { synthesizeChannelLists } from "./lists/channels.js";
83
90
  import {
@@ -134,6 +141,23 @@ export interface HogsendClient {
134
141
  * templates without going through a send. Empty when no templates are wired.
135
142
  */
136
143
  templates: TemplateRegistry;
144
+ /**
145
+ * The engine-owned tracked SMS sender (the SMS sibling of {@link emailService}).
146
+ * When no SMS provider is configured this is an inert stub whose `send` throws
147
+ * an actionable error — so an existing deploy without Twilio creds boots clean.
148
+ */
149
+ smsService: SmsService;
150
+ /**
151
+ * The container-held registry of SMS providers, keyed by `meta.id`. The
152
+ * `POST /v1/webhooks/sms/:providerId` route resolves the verifying provider
153
+ * out of this. Empty when no SMS provider is configured.
154
+ */
155
+ smsProviders: SmsProviderRegistry;
156
+ /**
157
+ * The single resolved active SMS provider the tracked sender delivers through.
158
+ * Undefined when no SMS provider is configured.
159
+ */
160
+ smsProvider?: SmsProvider;
137
161
  /**
138
162
  * The container-held registry of analytics providers, keyed by `meta.id` —
139
163
  * the analytics sibling of {@link emailProviders}. Built from env presets
@@ -274,6 +298,46 @@ export interface HogsendClientOptions {
274
298
  defaultProvider?: string;
275
299
  templates?: TemplateRegistry;
276
300
  };
301
+ /**
302
+ * SMS is a first-class channel (the SMS sibling of {@link email}). Its config
303
+ * is grouped here; the engine owns the cohesive SMS pipeline (templates →
304
+ * render → preference/suppression checks → `sms_sends` write → STOP handling),
305
+ * and the {@link SmsProvider} (Twilio, …) is only the swappable wire.
306
+ *
307
+ * - `provider` — a single SMS provider. Merged LAST (after env presets and
308
+ * `providers`), so it wins on id collision.
309
+ * - `providers` — register MANY providers into the {@link SmsProviderRegistry}
310
+ * so `POST /v1/webhooks/sms/:providerId` can verify each one's webhooks.
311
+ * - `defaultProvider` — the active provider id the tracked sender delivers
312
+ * through. Resolves as `defaultProvider ?? SMS_PROVIDER ?? "twilio"`. If it
313
+ * names an unregistered provider, the container throws at boot.
314
+ * - `templates` — the app's SMS template registry (key → component +
315
+ * category), threaded into the tracked SMS sender.
316
+ * - `from` — the E.164 default sender (overrides env `SMS_FROM`).
317
+ * - `stopFooter` — the compliance footer appended to non-transactional
318
+ * bodies; `false` disables it, a string overrides the default text.
319
+ * - `optOutReplies` — send STOP/START/HELP confirmation replies (default off;
320
+ * the carrier already replies and a post-STOP send is blocked).
321
+ * - `linkTracking` — rewrite bare URLs in rendered bodies to first-party
322
+ * short tracked links (`/s/:code`). Default true (overrides env
323
+ * `SMS_LINK_TRACKING`).
324
+ * - `linkHost` — the full origin short links are minted under (overrides
325
+ * env `SMS_LINK_HOST`; falls back to `API_PUBLIC_URL`).
326
+ *
327
+ * Omitting `sms` entirely (or configuring no provider) installs an inert stub
328
+ * SMS service — an existing deploy without Twilio creds boots unchanged.
329
+ */
330
+ sms?: {
331
+ provider?: SmsProvider;
332
+ providers?: SmsProvider[];
333
+ defaultProvider?: string;
334
+ templates?: SmsTemplateRegistry;
335
+ from?: string;
336
+ stopFooter?: string | false;
337
+ optOutReplies?: boolean;
338
+ linkTracking?: boolean;
339
+ linkHost?: string;
340
+ };
277
341
  /**
278
342
  * The analytics provider(s) — provider-neutral since the
279
343
  * `AnalyticsProvider` contract (the analytics sibling of `EmailProvider`;
@@ -498,6 +562,33 @@ function validateListCategory(opts: {
498
562
  );
499
563
  }
500
564
 
565
+ /**
566
+ * The inert SMS service installed when no SMS provider is configured. `render`
567
+ * still works (templates need no provider); `send` throws an actionable error;
568
+ * `handleWebhook` is a no-op (a stray webhook can't dispatch without a provider).
569
+ */
570
+ function createStubSmsService(): SmsService {
571
+ const notConfigured = () => {
572
+ throw new Error(
573
+ "No SMS provider configured. Set TWILIO_ACCOUNT_SID/TWILIO_AUTH_TOKEN and SMS_FROM, or pass sms.provider to createHogsendClient.",
574
+ );
575
+ };
576
+ return {
577
+ async send() {
578
+ return notConfigured();
579
+ },
580
+ async sendRaw() {
581
+ return notConfigured();
582
+ },
583
+ async render() {
584
+ return notConfigured();
585
+ },
586
+ async handleWebhook(event) {
587
+ return { type: event.type, handled: false };
588
+ },
589
+ };
590
+ }
591
+
501
592
  export function createHogsendClient(
502
593
  opts: HogsendClientOptions = {},
503
594
  ): HogsendClient {
@@ -563,7 +654,20 @@ export function createHogsendClient(
563
654
  // is available here before the connector-action registry is built, and is
564
655
  // identical in both the API and worker processes — then registered
565
656
  // unconditionally (bypassing ENABLED_LISTS) after the user lists.
566
- const channelLists = synthesizeChannelLists(opts.connectorActions ?? []);
657
+ // Build the SMS provider registry early (before channel synthesis) so the
658
+ // `sms` opt-out channel is minted iff an SMS provider is actually configured.
659
+ // Same merge order as email: env presets FIRST, then `providers`, then the
660
+ // single `provider` LAST (last-writer-wins).
661
+ const smsProviders = new SmsProviderRegistry([
662
+ ...smsProvidersFromEnv(env),
663
+ ...(opts.sms?.providers ?? []),
664
+ ...(opts.sms?.provider ? [opts.sms.provider] : []),
665
+ ]);
666
+ const smsConfigured = smsProviders.count() > 0;
667
+
668
+ const channelLists = synthesizeChannelLists(opts.connectorActions ?? [], {
669
+ sms: smsConfigured,
670
+ });
567
671
  const listRegistry = buildListRegistry(
568
672
  opts.lists ?? [],
569
673
  opts.enabledLists ?? env.ENABLED_LISTS,
@@ -724,6 +828,86 @@ export function createHogsendClient(
724
828
 
725
829
  setEmailService(emailService);
726
830
 
831
+ // --- SMS channel (parallel to the email pipeline above) -------------------
832
+ // Resolve the active SMS provider: `defaultProvider ?? SMS_PROVIDER ?? "twilio"`.
833
+ // An EXPLICITLY-requested id that isn't registered throws (mirrors email's
834
+ // "never silently fall back"). When nothing is configured the registry is
835
+ // empty and `smsProvider` stays undefined — the tracked sender below becomes
836
+ // an inert stub so an existing deploy without Twilio creds boots unchanged.
837
+ const smsTemplates = opts.sms?.templates ?? ({} as SmsTemplateRegistry);
838
+ const smsActiveId = opts.sms?.defaultProvider ?? env.SMS_PROVIDER ?? "twilio";
839
+ const smsExplicit = Boolean(opts.sms?.defaultProvider ?? env.SMS_PROVIDER);
840
+ let smsProvider = smsProviders.get(smsActiveId);
841
+ // DX: when the active id wasn't explicitly requested and the default "twilio"
842
+ // isn't registered but EXACTLY ONE provider is, use that one — so a consumer
843
+ // passing a single `sms.provider` (any id) never has to also set
844
+ // `defaultProvider`. An explicit id that misses still throws below.
845
+ if (!smsProvider && !smsExplicit && smsProviders.count() === 1) {
846
+ smsProvider = smsProviders.getAll()[0];
847
+ }
848
+ if (smsExplicit && !smsProvider) {
849
+ throw new Error(
850
+ `SMS provider "${smsActiveId}" is not registered (registered: ${
851
+ smsProviders
852
+ .getAll()
853
+ .map((p) => p.meta.id)
854
+ .join(", ") || "none"
855
+ }). Set TWILIO_ACCOUNT_SID/TWILIO_AUTH_TOKEN and SMS_FROM, or pass sms.provider.`,
856
+ );
857
+ }
858
+
859
+ // Boot-validate SMS template categories through the SAME fail-closed helper as
860
+ // email templates (a channel/typo/consent-flip category is as dangerous here).
861
+ for (const [templateKey, def] of Object.entries(smsTemplates)) {
862
+ const category = (def as SmsTemplateDefinition | undefined)?.category;
863
+ if (!category) continue;
864
+ validateListCategory({
865
+ owner: `SMS template "${templateKey}"`,
866
+ category,
867
+ listRegistry,
868
+ definedLists,
869
+ logger,
870
+ });
871
+ }
872
+
873
+ const smsService: SmsService = smsProvider
874
+ ? createTrackedSmsSender(
875
+ {
876
+ defaultFrom: opts.sms?.from ?? env.SMS_FROM,
877
+ templates: smsTemplates,
878
+ db,
879
+ frequencyCap: defaults.frequencyCap,
880
+ logger,
881
+ stopFooter: opts.sms?.stopFooter,
882
+ optOutReplies: opts.sms?.optOutReplies,
883
+ // Deploy-wide test-mode coherence: HOGSEND_TEST_MODE is channel-
884
+ // neutral. "true" forces SMS test mode directly; "auto" arms it
885
+ // whenever the EMAIL side's test mode is armed (unverified domain),
886
+ // so a staging deploy that redirects email never live-texts real
887
+ // numbers. SMS has no domain-verification analog of its own, so
888
+ // "auto" with email test mode off keeps live sends (PR behavior).
889
+ testMode: () =>
890
+ env.HOGSEND_TEST_MODE === "true" ||
891
+ (env.HOGSEND_TEST_MODE === "auto" &&
892
+ domainStatus.testModeCached().active),
893
+ testPhone: env.HOGSEND_TEST_PHONE,
894
+ // First-party short-link rewriting (ON by default, mirrors email's
895
+ // always-on tracking). SMS_LINK_HOST swaps in a branded short
896
+ // domain; API_PUBLIC_URL serves out of the box.
897
+ linkTracking:
898
+ opts.sms?.linkTracking ?? env.SMS_LINK_TRACKING !== "false",
899
+ linkHost: (
900
+ opts.sms?.linkHost ??
901
+ env.SMS_LINK_HOST ??
902
+ env.API_PUBLIC_URL
903
+ ).replace(/\/+$/, ""),
904
+ },
905
+ { provider: smsProvider },
906
+ )
907
+ : createStubSmsService();
908
+
909
+ setSmsService(smsService);
910
+
727
911
  // Wire better-auth's secondary storage to the SHARED engine Redis (the same
728
912
  // singleton backing the PostHog cache + worker heartbeat — never a second
729
913
  // pool). Passing `secondaryStorage` flips better-auth's rate-limit store from
@@ -929,11 +1113,12 @@ export function createHogsendClient(
929
1113
  for (const connector of connectorList) {
930
1114
  if (
931
1115
  (connector.meta.transport ?? "webhook") === "webhook" &&
932
- connector.meta.id === "email"
1116
+ (connector.meta.id === "email" || connector.meta.id === "sms")
933
1117
  ) {
934
1118
  throw new Error(
935
- 'Connector id "email" is reserved for the email-provider route ' +
936
- "(POST /v1/webhooks/email/:providerId). Rename the connector.",
1119
+ `Connector id "${connector.meta.id}" is reserved for the ` +
1120
+ "email/SMS-provider routes (POST /v1/webhooks/{email,sms}/:providerId). " +
1121
+ "Rename the connector.",
937
1122
  );
938
1123
  }
939
1124
  }
@@ -991,6 +1176,9 @@ export function createHogsendClient(
991
1176
  emailProvider: provider,
992
1177
  domainStatus,
993
1178
  templates,
1179
+ smsService,
1180
+ smsProviders,
1181
+ smsProvider,
994
1182
  analyticsProviders,
995
1183
  analytics,
996
1184
  identity,
package/src/env.ts CHANGED
@@ -121,6 +121,34 @@ export const env = createEnv({
121
121
  POSTMARK_MESSAGE_STREAM: z.string().min(1).optional(),
122
122
  POSTMARK_WEBHOOK_USER: z.string().min(1).optional(),
123
123
  POSTMARK_WEBHOOK_PASS: z.string().min(1).optional(),
124
+ // --- SMS channel (provider-neutral, BYO SMS provider) ---
125
+ // The active SMS provider id the container resolves from the
126
+ // SmsProviderRegistry. Absent → "twilio" when a provider is registered;
127
+ // with no provider configured the SMS service is an inert throwing stub.
128
+ SMS_PROVIDER: z.string().optional(),
129
+ // Neutral E.164 default-from number the tracked SMS sender uses when a send
130
+ // omits `from` and no messaging-service is pinned.
131
+ SMS_FROM: z.string().optional(),
132
+ // The safe phone every redirected SMS is delivered to under
133
+ // HOGSEND_TEST_MODE=true. When unset while test mode is active, the send is
134
+ // BLOCKED (recorded, never delivered to the real recipient).
135
+ HOGSEND_TEST_PHONE: z.string().optional(),
136
+ // SMS link shortening/tracking is ON by default when SMS is configured.
137
+ // An enum, NOT z.coerce.boolean — an explicit "false" must actually
138
+ // disable (coerce treats the string "false" as true; HOGSEND_TEST_MODE
139
+ // precedent).
140
+ SMS_LINK_TRACKING: z.enum(["true", "false"]).default("true"),
141
+ // Full origin short links are minted under (e.g. https://hs.example.com —
142
+ // a branded short domain routed to this app). Falls back to
143
+ // API_PUBLIC_URL; the /s/:code route serves either way.
144
+ SMS_LINK_HOST: z.string().url().optional(),
145
+ // --- Twilio (default SMS provider, opt-in) ---
146
+ // A preset provider is built only when BOTH SID + token are present (the
147
+ // guarded dynamic import in sms-providers-from-env.ts). One of SMS_FROM /
148
+ // TWILIO_MESSAGING_SERVICE_SID must also be set for sends to succeed.
149
+ TWILIO_ACCOUNT_SID: z.string().min(1).optional(),
150
+ TWILIO_AUTH_TOKEN: z.string().min(1).optional(),
151
+ TWILIO_MESSAGING_SERVICE_SID: z.string().min(1).optional(),
124
152
  // Hatchet connection contract. The @hatchet-dev SDK also reads these straight
125
153
  // from process.env via its own config-loader, so this schema is a presence /
126
154
  // shape check that keeps the contract in one place — the values still flow to
package/src/index.ts CHANGED
@@ -307,6 +307,8 @@ export {
307
307
  type EnableBlueprintResult,
308
308
  enableBlueprint,
309
309
  findBlueprintRow,
310
+ type PromoteBlueprintResult,
311
+ promoteBlueprint,
310
312
  type SerializedBlueprint,
311
313
  serializeBlueprint,
312
314
  type UpdateBlueprintPatch,
@@ -481,6 +483,7 @@ export {
481
483
  type OutboundEventName,
482
484
  type OutboundPayloads,
483
485
  } from "./lib/outbound.js";
486
+ export { isE164, normalizePhone } from "./lib/phone.js";
484
487
  export { getPostHog } from "./lib/posthog.js";
485
488
  // --- PostHog OAuth scopes (front-loaded set; gap-detector source of truth) ---
486
489
  export { EXPECTED_POSTHOG_SCOPES } from "./lib/posthog-scopes.js";
@@ -522,6 +525,42 @@ export {
522
525
  SEMANTIC_BURST_DISTINCT_LINKS,
523
526
  SEMANTIC_BURST_WINDOW_MS,
524
527
  } from "./lib/semantic-click.js";
528
+ // --- SMS ---
529
+ export {
530
+ getSmsService,
531
+ type SendSmsOptions as SendSmsJourneyOptions,
532
+ type SendSmsResult,
533
+ sendSms,
534
+ setSmsService,
535
+ } from "./lib/sms.js";
536
+ // --- SMS inbound consent helpers (phone-track grant/opt-out) ---
537
+ export {
538
+ grantPhoneConsent,
539
+ recordPhoneOptOut,
540
+ } from "./lib/sms-inbound.js";
541
+ // --- SMS link shortening (pure rewriter; the insert rides the send txn) ---
542
+ export {
543
+ generateShortCode,
544
+ isShortCodeCollision,
545
+ type PendingSmsLink,
546
+ planSmsLinkRewrite,
547
+ SHORT_CODE_ALPHABET,
548
+ SHORT_CODE_LENGTH,
549
+ type SmsLinkRewritePlan,
550
+ } from "./lib/sms-link-tracking.js";
551
+ // --- SMS mailer factory (the engine-owned tracked sender; mirrors createTrackedMailer) ---
552
+ export { createTrackedSmsSender } from "./lib/sms-mailer.js";
553
+ // --- SMS provider registry (container-held, keyed by meta.id) ---
554
+ export { SmsProviderRegistry } from "./lib/sms-provider-registry.js";
555
+ // --- SMS service (engine-owned tracked SMS sender) ---
556
+ export type {
557
+ SmsService,
558
+ SmsServiceConfig,
559
+ SmsServiceSendOptions,
560
+ SmsServiceWebhookResult,
561
+ SmsTrackedSendResult,
562
+ } from "./lib/sms-service-types.js";
563
+ export { SMS_CHANNEL_ID } from "./lib/sms-tracked.js";
525
564
  export { type MountStudioResult, mountStudio } from "./lib/studio.js";
526
565
  // --- In-app survey/rating (sendSurvey — producer sugar over sendFeedItem) ---
527
566
  export { type SendSurveyOptions, sendSurvey } from "./lib/survey.js";
@@ -545,6 +584,7 @@ export {
545
584
  rewriteLinks,
546
585
  } from "./lib/tracking.js";
547
586
  export {
587
+ pushSmsTrackingEvent,
548
588
  pushTrackingEvent,
549
589
  resolveEmailSendContext,
550
590
  resolveEmailSendContextByMessageId,
@@ -553,6 +593,7 @@ export {
553
593
  * {@link resolveEmailSendContextByMessageId}.
554
594
  */
555
595
  resolveEmailSendContextByResendId,
596
+ resolveSmsSendContext,
556
597
  } from "./lib/tracking-events.js";
557
598
  /**
558
599
  * Publishable-key `userToken` mint/verify helpers.
@@ -615,6 +656,12 @@ export {
615
656
  resetListRegistry,
616
657
  setListRegistry,
617
658
  } from "./lists/registry-singleton.js";
659
+ // --- Journey blueprints: shared authoring-guide text (tools + @hogsend/mcp) ---
660
+ export {
661
+ BLUEPRINT_AUTHORING_GUIDE,
662
+ GRAPH_FORMAT,
663
+ ISSUE_LOOP_HINT,
664
+ } from "./mcp/authoring-guide.js";
618
665
  // --- Journey blueprints: agent-facing authoring tools (spec §9, phase 4) ---
619
666
  export {
620
667
  type BlueprintToolDefinition,
@@ -624,6 +671,12 @@ export {
624
671
  type JourneyBlueprintTools,
625
672
  type JourneyBlueprintToolsOptions,
626
673
  } from "./mcp/blueprint-tools.js";
674
+ export {
675
+ createRateLimit,
676
+ type RateLimitOptions,
677
+ } from "./middleware/rate-limit.js";
678
+ // --- Middleware (consumer-mounted routes, e.g. the @hogsend/mcp hosted route) ---
679
+ export { requireAdmin } from "./middleware/require-admin.js";
627
680
  // --- Webhook sources ---
628
681
  export {
629
682
  type DefinedWebhookSource,
@@ -18,6 +18,7 @@ import {
18
18
  } from "@hogsend/db";
19
19
  import { and, eq, inArray, notInArray, sql } from "drizzle-orm";
20
20
  import { getAnalytics } from "../lib/analytics-singleton.js";
21
+ import { blueprintGraphLock } from "../lib/blueprint-lock.js";
21
22
  import { getDb } from "../lib/db.js";
22
23
  import {
23
24
  checkEmailPreferences,
@@ -122,24 +123,48 @@ export async function insertEnrollment(opts: {
122
123
  journeyId: string;
123
124
  context: Record<string, unknown>;
124
125
  hatchetRunId?: string;
126
+ /**
127
+ * Blueprint runs serialize this insert against a concurrent GRAPH EDIT via a
128
+ * transaction-scoped advisory lock — `updateBlueprint` takes the SAME lock
129
+ * ({@link blueprintGraphLock}) around its in-flight count + guarded update,
130
+ * so an enrollment cannot become active/waiting in the window between that
131
+ * count and update. Code journeys have no mutable graph, so they insert
132
+ * lock-free (the default).
133
+ */
134
+ serializeWithGraphLock?: boolean;
125
135
  }): Promise<JourneyStateRow | undefined> {
126
- const [row] = await opts.db
127
- .insert(journeyStates)
128
- .values({
129
- userId: opts.userId,
130
- userEmail: opts.userEmail,
131
- journeyId: opts.journeyId,
132
- currentNodeId: "start",
133
- status: "active",
134
- context: opts.context,
135
- hatchetRunId: opts.hatchetRunId,
136
- })
137
- .onConflictDoNothing({
138
- target: [journeyStates.userId, journeyStates.journeyId],
139
- where: sql`status IN ('active', 'waiting')`,
140
- })
141
- .returning();
142
- return row;
136
+ const values = {
137
+ userId: opts.userId,
138
+ userEmail: opts.userEmail,
139
+ journeyId: opts.journeyId,
140
+ currentNodeId: "start",
141
+ status: "active" as const,
142
+ context: opts.context,
143
+ hatchetRunId: opts.hatchetRunId,
144
+ };
145
+ const onConflict = {
146
+ target: [journeyStates.userId, journeyStates.journeyId],
147
+ where: sql`status IN ('active', 'waiting')`,
148
+ };
149
+
150
+ if (!opts.serializeWithGraphLock) {
151
+ const [row] = await opts.db
152
+ .insert(journeyStates)
153
+ .values(values)
154
+ .onConflictDoNothing(onConflict)
155
+ .returning();
156
+ return row;
157
+ }
158
+
159
+ return opts.db.transaction(async (tx) => {
160
+ await tx.execute(blueprintGraphLock(opts.journeyId));
161
+ const [row] = await tx
162
+ .insert(journeyStates)
163
+ .values(values)
164
+ .onConflictDoNothing(onConflict)
165
+ .returning();
166
+ return row;
167
+ });
143
168
  }
144
169
 
145
170
  export interface ExecuteJourneyRunOptions {
@@ -162,6 +187,13 @@ export interface ExecuteJourneyRunOptions {
162
187
  * interpreter pins `__blueprintVersion` here (spec §12).
163
188
  */
164
189
  extraContext?: Record<string, unknown>;
190
+ /**
191
+ * Serialize the enrollment insert against a concurrent blueprint graph edit
192
+ * with a transaction-scoped advisory lock (spec §12). Set by the blueprint
193
+ * interpreter — the blueprint id IS the journeyId, so the lock key matches
194
+ * `updateBlueprint`'s. Code journeys leave it unset (no mutable graph).
195
+ */
196
+ serializeEnrollment?: boolean;
165
197
  /**
166
198
  * Serialize a run failure into `journeyStates.errorMessage`. Defaults to the
167
199
  * error's message; the blueprint interpreter writes the structured
@@ -295,6 +327,7 @@ export async function executeJourneyRun(
295
327
  ? { ...properties, ...options.extraContext }
296
328
  : properties,
297
329
  hatchetRunId: workflowRunId,
330
+ serializeWithGraphLock: options.serializeEnrollment,
298
331
  });
299
332
  if (!state) {
300
333
  return { status: "skipped", reason: "already_active" };
@@ -146,10 +146,14 @@ export function supportsEviction(hatchetCtx: unknown): boolean {
146
146
  }
147
147
 
148
148
  /** The kind of side effect a key is derived for — keeps the namespaces apart. */
149
- export type JourneyKeyKind = "send" | "trigger" | "connector";
149
+ export type JourneyKeyKind = "send" | "smsSend" | "trigger" | "connector";
150
150
 
151
151
  const KEY_PREFIX: Record<JourneyKeyKind, string> = {
152
152
  send: "journeySend",
153
+ // Disjoint from `send` so a `sendEmail("x")` and a `sendSms("x")` under the
154
+ // SAME nearest wait label derive DIFFERENT keys and never collide in
155
+ // registerKey — email + SMS of the same template on one branch is legitimate.
156
+ smsSend: "journeySmsSend",
153
157
  trigger: "journeyTrigger",
154
158
  connector: "journeyConnector",
155
159
  };
@@ -42,6 +42,7 @@ import {
42
42
  type Database,
43
43
  emailSends,
44
44
  journeyStates,
45
+ smsSends,
45
46
  userEvents,
46
47
  } from "@hogsend/db";
47
48
  import {
@@ -1089,6 +1090,38 @@ export function createJourneyContext(
1089
1090
  });
1090
1091
  },
1091
1092
 
1093
+ async exit(reason?: string): Promise<never> {
1094
+ // Terminal "exited": a guarded flip (never clobber an already-terminal
1095
+ // row) plus the SAME JourneyExitedError control-flow signal a mid-wait
1096
+ // exitOn raises — the run lifecycle maps it to { status: "exited" } with
1097
+ // no "failed"/"completed" write and no journey:* event. This is the
1098
+ // single mechanism the blueprint interpreter's end-exited node drives too
1099
+ // (and the form promote-to-code emits), so there is one path, not two.
1100
+ const now = new Date();
1101
+ const [exited] = await db
1102
+ .update(journeyStates)
1103
+ .set({ status: "exited", exitedAt: now, updatedAt: now })
1104
+ .where(
1105
+ and(
1106
+ eq(journeyStates.id, stateId),
1107
+ notInArray(journeyStates.status, [...TERMINAL_STATUSES]),
1108
+ ),
1109
+ )
1110
+ .returning({ id: journeyStates.id });
1111
+ if (exited) {
1112
+ // Fire-and-forget exit transition (best-effort; never affects the run).
1113
+ logTransition({
1114
+ db,
1115
+ journeyStateId: stateId,
1116
+ from: getJourneyBoundary()?.currentLabel ?? null,
1117
+ to: "end-exited",
1118
+ action: "exited",
1119
+ ...(reason ? { detail: { reason } } : {}),
1120
+ });
1121
+ }
1122
+ throw new JourneyExitedError(stateId);
1123
+ },
1124
+
1092
1125
  async now() {
1093
1126
  return refreshNow();
1094
1127
  },
@@ -1180,6 +1213,31 @@ export function createJourneyContext(
1180
1213
  };
1181
1214
  },
1182
1215
 
1216
+ async sms({ phone, template }) {
1217
+ const [result] = await db
1218
+ .select({
1219
+ count: count(),
1220
+ lastSentAt: max(smsSends.sentAt),
1221
+ })
1222
+ .from(smsSends)
1223
+ .where(
1224
+ and(
1225
+ eq(smsSends.toPhone, phone),
1226
+ eq(smsSends.templateKey, template),
1227
+ ),
1228
+ );
1229
+
1230
+ const total = result?.count ?? 0;
1231
+ return {
1232
+ sent: total > 0,
1233
+ lastSentAt:
1234
+ result?.lastSentAt instanceof Date
1235
+ ? result.lastSentAt.toISOString()
1236
+ : null,
1237
+ count: total,
1238
+ };
1239
+ },
1240
+
1183
1241
  async events({
1184
1242
  userId: targetUserId,
1185
1243
  event,
@@ -0,0 +1,21 @@
1
+ import { type SQL, sql } from "drizzle-orm";
2
+
3
+ /**
4
+ * Transaction-scoped advisory lock serializing a blueprint's graph EDIT
5
+ * (`updateBlueprint`'s in-flight count + guarded update) against a new
6
+ * ENROLLMENT insert for the same blueprint (`insertEnrollment` for a blueprint
7
+ * run). Both sides take THIS lock inside their transaction, so the count and
8
+ * the insert cannot interleave: an enrollment either lands before the count
9
+ * (the edit then sees it and rejects with `in_flight`) or after the graph
10
+ * commits (a fresh run walking the NEW graph) — never mid-flight, which is the
11
+ * interleaving that would desync the positional Hatchet replay journal for a
12
+ * run suspended between the count and the update.
13
+ *
14
+ * `hashtext` folds the id into the int4 the single-arg `pg_advisory_xact_lock`
15
+ * overload casts to bigint (same pattern as `contacts.ts`/`boot-api-key.ts`);
16
+ * the `bp-graph:` prefix namespaces it away from the codebase's other advisory
17
+ * locks. Xact-scoped — released on commit/rollback, no manual unlock.
18
+ */
19
+ export function blueprintGraphLock(blueprintId: string): SQL {
20
+ return sql`SELECT pg_advisory_xact_lock(hashtext(${`bp-graph:${blueprintId}`}))`;
21
+ }