@hogsend/engine 0.40.0 → 0.42.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 (69) hide show
  1. package/package.json +11 -8
  2. package/src/buckets/check-membership.ts +6 -1
  3. package/src/campaigns/cohort-sql.ts +198 -0
  4. package/src/campaigns/define-campaign.ts +207 -28
  5. package/src/campaigns/reconcile.ts +105 -11
  6. package/src/campaigns/steps.ts +48 -0
  7. package/src/connectors/define-action.ts +70 -0
  8. package/src/container.ts +124 -42
  9. package/src/destinations/presets/posthog.ts +7 -1
  10. package/src/index.ts +96 -2
  11. package/src/journeys/constants.ts +10 -0
  12. package/src/journeys/define-journey.ts +14 -405
  13. package/src/journeys/execute-journey-run.ts +641 -0
  14. package/src/journeys/graph/build-graph.ts +212 -56
  15. package/src/journeys/journey-boundary.ts +54 -0
  16. package/src/journeys/journey-context.ts +406 -59
  17. package/src/journeys/record-once.ts +110 -0
  18. package/src/lib/blueprint-lock.ts +21 -0
  19. package/src/lib/blueprints.ts +803 -0
  20. package/src/lib/campaign-send-key.ts +58 -0
  21. package/src/lib/connector-actions.ts +203 -19
  22. package/src/lib/contacts.ts +54 -0
  23. package/src/lib/email-service-types.ts +4 -1
  24. package/src/lib/email.ts +13 -2
  25. package/src/lib/event-names.ts +143 -0
  26. package/src/lib/feed.ts +77 -57
  27. package/src/lib/frequency-cap.ts +45 -15
  28. package/src/lib/hatchet-duration.ts +22 -0
  29. package/src/lib/html.ts +1 -0
  30. package/src/lib/ingestion.ts +145 -4
  31. package/src/lib/journey-suppress.ts +87 -0
  32. package/src/lib/links.ts +204 -18
  33. package/src/lib/outbound.ts +20 -0
  34. package/src/lib/preferences.ts +80 -1
  35. package/src/lib/tracked.ts +44 -29
  36. package/src/lib/tracking-event-names.ts +8 -0
  37. package/src/lib/tracking.ts +1 -5
  38. package/src/lib/webhook-signing.ts +6 -1
  39. package/src/lists/channels.ts +75 -0
  40. package/src/lists/define-list.ts +34 -0
  41. package/src/lists/registry.ts +29 -2
  42. package/src/mcp/authoring-guide.ts +160 -0
  43. package/src/mcp/blueprint-tools.ts +390 -0
  44. package/src/middleware/require-admin.ts +13 -0
  45. package/src/routes/admin/api-keys.ts +72 -0
  46. package/src/routes/admin/blueprints.ts +795 -0
  47. package/src/routes/admin/campaigns.ts +179 -3
  48. package/src/routes/admin/emails.ts +13 -0
  49. package/src/routes/admin/events.ts +55 -0
  50. package/src/routes/admin/index.ts +4 -0
  51. package/src/routes/admin/journeys.ts +4 -2
  52. package/src/routes/admin/links.ts +303 -36
  53. package/src/routes/admin/lists.ts +51 -0
  54. package/src/routes/campaigns/index.ts +44 -6
  55. package/src/routes/email/preferences.ts +50 -13
  56. package/src/routes/feed/recipient.ts +2 -43
  57. package/src/routes/index.ts +6 -0
  58. package/src/routes/lists/index.ts +138 -18
  59. package/src/routes/tracking/arrive.ts +260 -0
  60. package/src/routes/tracking/click-pipeline.ts +329 -0
  61. package/src/routes/tracking/click.ts +5 -270
  62. package/src/routes/tracking/index.ts +2 -0
  63. package/src/routes/tracking/vanity.ts +64 -0
  64. package/src/worker.ts +5 -0
  65. package/src/workflows/bucket-backfill.ts +4 -2
  66. package/src/workflows/bucket-reconcile.ts +11 -4
  67. package/src/workflows/check-alerts.ts +130 -1
  68. package/src/workflows/journey-blueprint-interpreter.ts +656 -0
  69. package/src/workflows/send-campaign.ts +574 -180
@@ -32,6 +32,27 @@ export function isReservedListId(id: string): boolean {
32
32
  /** Allowed list-id shape: alphanumerics, dash, underscore (case-insensitive). */
33
33
  const LIST_ID_PATTERN = /^[a-z0-9_-]+$/i;
34
34
 
35
+ /**
36
+ * Reserved list id for the engine's in-app channel list (the notification
37
+ * feed). Unlike {@link RESERVED_LIST_IDS} — which doubles as the template
38
+ * category allowlist in `container.ts` — this id is a channel that IS
39
+ * auto-registered by the engine (`synthesizeChannelLists`), so it gets its own
40
+ * dedicated {@link defineList} guard instead of joining that set (adding it
41
+ * there would change the allowlist's meaning). Kept lowercase; the check is
42
+ * case-insensitive.
43
+ */
44
+ const IN_APP_RESERVED_LIST_ID = "in_app";
45
+
46
+ /**
47
+ * The kind of list. `"topic"` is an author-defined subscription category (the
48
+ * `defineList` output — every manual list is a topic). `"channel"` is an
49
+ * engine-synthesized delivery channel (the in-app feed + one per connector that
50
+ * exposes member-directed actions), minted by `synthesizeChannelLists`, never
51
+ * authored. Read sites treat an absent `kind` as `"topic"` (`meta.kind ??
52
+ * "topic"`) so pre-existing manual `ListMeta` constructions keep compiling.
53
+ */
54
+ export type ListKind = "channel" | "topic";
55
+
35
56
  /**
36
57
  * The validated, fully-defaulted list metadata. `enabled` is always present
37
58
  * after `defineList` (defaults to `true`); authoring input leaves it optional.
@@ -42,6 +63,12 @@ export interface ListMeta<Id extends string = string> {
42
63
  description?: string;
43
64
  defaultOptIn: boolean;
44
65
  enabled: boolean;
66
+ /**
67
+ * Whether this is an author-defined `"topic"` or an engine-synthesized
68
+ * delivery `"channel"`. Optional so existing manual constructions compile;
69
+ * read as `meta.kind ?? "topic"`. `defineList` always stamps `"topic"`.
70
+ */
71
+ kind?: ListKind;
45
72
  }
46
73
 
47
74
  /**
@@ -82,12 +109,19 @@ export function defineList<const Id extends string>(meta: {
82
109
  );
83
110
  }
84
111
 
112
+ if (id.toLowerCase() === IN_APP_RESERVED_LIST_ID) {
113
+ throw new Error(
114
+ `Reserved list id "${id}": it is the engine's in-app channel list, auto-registered for the notification feed.`,
115
+ );
116
+ }
117
+
85
118
  const resolvedMeta: ListMeta<Id> = {
86
119
  id,
87
120
  name,
88
121
  ...(description !== undefined ? { description } : {}),
89
122
  defaultOptIn,
90
123
  enabled: enabled ?? true,
124
+ kind: "topic",
91
125
  };
92
126
 
93
127
  return {
@@ -64,6 +64,15 @@ export class ListRegistry {
64
64
  const defaultOptIn = this.isSubscribedByDefault(id);
65
65
  return defaultOptIn ? categories[id] !== false : categories[id] === true;
66
66
  }
67
+
68
+ /**
69
+ * Is `id` a registered channel (an engine-synthesized delivery channel — the
70
+ * in-app feed or a per-connector opt-out list) rather than an author-defined
71
+ * topic? False for topics, unknown ids, and the built-in categories.
72
+ */
73
+ isChannel(id: string): boolean {
74
+ return this.get(id)?.kind === "channel";
75
+ }
67
76
  }
68
77
 
69
78
  /**
@@ -74,12 +83,21 @@ export class ListRegistry {
74
83
  *
75
84
  * `parseEnabledFilter` (journeys/registry.ts) is reused as-is — `ENABLED_LISTS`
76
85
  * honours the same `"*"`-or-csv contract as `ENABLED_JOURNEYS` /
77
- * `ENABLED_BUCKETS`. Disabled lists (filtered out OR `enabled: false`) are NOT
78
- * registered, so an unknown id resolves to legacy opt-in.
86
+ * `ENABLED_BUCKETS`. Disabled user lists (filtered out OR `enabled: false`) are
87
+ * NOT registered, so an unknown id resolves to legacy opt-in.
88
+ *
89
+ * `channels` (engine-synthesized channel metas from `synthesizeChannelLists`)
90
+ * are registered AFTER the user lists, UNCONDITIONALLY — the `ENABLED_LISTS`
91
+ * filter does NOT apply. A "disabled" channel would hide the catalog entry while
92
+ * opt-out-polarity enforcement silently continued (a confusing half-state), so
93
+ * channels are always on. If a filtered-IN user list id collides with a channel
94
+ * id, we throw an actionable error rather than let one silently shadow the
95
+ * other.
79
96
  */
80
97
  export function buildListRegistry(
81
98
  lists: DefinedList[],
82
99
  enabledFilter?: string,
100
+ channels: ListMeta[] = [],
83
101
  ): ListRegistry {
84
102
  const registry = new ListRegistry();
85
103
  const enabled = parseEnabledFilter(enabledFilter);
@@ -90,6 +108,15 @@ export function buildListRegistry(
90
108
  }
91
109
  }
92
110
 
111
+ for (const channel of channels) {
112
+ if (registry.has(channel.id)) {
113
+ throw new Error(
114
+ `List id "${channel.id}" collides with the auto-registered channel list for the "${channel.id}" connector. Rename your defineList id.`,
115
+ );
116
+ }
117
+ registry.register(channel);
118
+ }
119
+
93
120
  setListRegistry(registry);
94
121
  return registry;
95
122
  }
@@ -0,0 +1,160 @@
1
+ /**
2
+ * Journey Blueprint authoring vocabulary — the shared description text for
3
+ * every agent-facing surface (the in-process tools in `blueprint-tools.ts`
4
+ * and the `@hogsend/mcp` server's authoring-guide resource). One source of
5
+ * truth, so the tool descriptions and the MCP resource can never drift.
6
+ *
7
+ * Two tiers:
8
+ * - `GRAPH_FORMAT` / `ISSUE_LOOP_HINT` — compact one-liners embedded in tool
9
+ * descriptions, paid for on every turn (keep terse).
10
+ * - `BLUEPRINT_AUTHORING_GUIDE` — the full markdown reference, loaded on
11
+ * demand (an MCP resource fetch), so the complete vocabulary doesn't tax
12
+ * every conversation turn.
13
+ *
14
+ * Every factual claim below is cross-checked against the execution-tier
15
+ * schema (`blueprintGraphSchema` + the structural checks,
16
+ * `@hogsend/core/src/journey-graph/blueprint.ts`) and the service-layer input
17
+ * schemas (`lib/blueprints.ts`). Update THIS file when the vocabulary grows.
18
+ */
19
+
20
+ /**
21
+ * The closed executable vocabulary (spec §6/§7), summarized for the model.
22
+ * Kept in the descriptions of every graph-accepting tool so an agent can
23
+ * author without a docs round-trip.
24
+ */
25
+ export const GRAPH_FORMAT =
26
+ "Graph format: { journeyId, nodes[], edges[] }. journeyId IS the blueprint id. " +
27
+ 'Node: { id, type, title, meta? }. Executable node types (closed vocabulary): "start" (exactly one; the entry point), ' +
28
+ '"sleep" (meta.duration: { hours?, minutes?, seconds? }), ' +
29
+ '"wait" (meta: { event, timeout } — wait for the user\'s event or time out; fork with edge kinds "answered"/"timedOut", or use a single unconditional edge), ' +
30
+ '"send" (meta: { template, idempotencyLabel? } — template MUST be a key from list_email_templates), ' +
31
+ '"connector" (meta: { connectorId, action } — must be a registered connector action), ' +
32
+ '"checkpoint", "trigger" (meta: { event } — fires an event through the ingest pipeline), ' +
33
+ '"decision"/"branch" (meta.conditions: ConditionEval[]; exactly two outgoing edges, kinds "conditional-true" and "conditional-false"), ' +
34
+ 'and terminals "end-completed"/"end-exited"/"end-failed". ' +
35
+ 'Edge: { id, source, target, kind? }. The graph must be acyclic, have exactly one start, and every node must be reachable from start; non-forking nodes have at most one outgoing edge. "sleepUntil", "capture", "digest", and "unknown" nodes are NOT executable in a blueprint. ' +
36
+ "Trigger/entryLimit/exitOn/suppress live on the blueprint record, not in the graph.";
37
+
38
+ export const ISSUE_LOOP_HINT =
39
+ "On validation failure you get structured issues [{ nodeId?, edgeId?, path, code, message }] naming exactly what is wrong and where — fix and retry. " +
40
+ "Tip: iterate with validate_journey_blueprint until valid before writing.";
41
+
42
+ /**
43
+ * The full authoring reference — `GRAPH_FORMAT` expanded into a readable
44
+ * markdown document. Served on demand (e.g. as the
45
+ * `hogsend://blueprint-authoring-guide` MCP resource) instead of inlined
46
+ * into every tool description.
47
+ */
48
+ export const BLUEPRINT_AUTHORING_GUIDE = `# Journey Blueprint authoring guide
49
+
50
+ A Journey Blueprint is a lifecycle automation authored as a JSON graph,
51
+ stored in the database, and executed by the engine's generic interpreter —
52
+ no deploy in the loop. The graph is fully validated at save time (schema +
53
+ structure + template/connector registries); an invalid graph is never saved.
54
+
55
+ ## Graph shape
56
+
57
+ \`\`\`
58
+ { "journeyId": "<blueprint id>", "nodes": [...], "edges": [...] }
59
+ \`\`\`
60
+
61
+ - \`journeyId\` IS the blueprint id — one id, one namespace (it must not
62
+ collide with a registered code journey's id, and it is immutable after
63
+ create: an updated graph's \`journeyId\` must equal the blueprint id).
64
+ - Every node: \`{ id, type, title, subtitle?, meta? }\` — \`id\` and
65
+ \`title\` are required strings; \`meta\` requirements depend on \`type\`.
66
+ - Every edge: \`{ id, source, target, label?, kind? }\` — \`source\`/
67
+ \`target\` are node ids. \`kind\` is one of \`"default"\` (same as
68
+ omitted), \`"answered"\`, \`"timedOut"\`, \`"conditional-true"\`,
69
+ \`"conditional-false"\`.
70
+
71
+ ## Node types (closed executable vocabulary)
72
+
73
+ | Type | Required meta | Semantics |
74
+ |---|---|---|
75
+ | \`start\` | — | Exactly one per graph; the entry point. |
76
+ | \`sleep\` | \`duration\` | Durable sleep for a fixed duration. |
77
+ | \`wait\` | \`event\`, \`timeout\` (a duration) | Wait until THIS user emits \`event\` OR \`timeout\` elapses. Fork with one \`answered\` + one \`timedOut\` edge, or use a single unconditional edge. |
78
+ | \`send\` | \`template\`, optional \`idempotencyLabel\` | Send an email. \`template\` MUST be a registered template key (list them first); an unregistered key is rejected at save time. |
79
+ | \`connector\` | \`connectorId\`, \`action\` | Fire a registered connector action (e.g. Discord/Telegram). Rejected at save time if the action isn't registered. |
80
+ | \`checkpoint\` | — | Observability marker; the node id is the label. |
81
+ | \`trigger\` | \`event\` | Push an event through the full ingest pipeline (can enroll other journeys). |
82
+ | \`decision\` / \`branch\` | \`conditions\` (non-empty \`ConditionEval[]\`) | Binary fork: exactly one \`conditional-true\` + one \`conditional-false\` outgoing edge. The conditions array is ANDed — use a single \`composite\` condition for OR. |
83
+ | \`end-completed\` / \`end-exited\` / \`end-failed\` | — | Terminals; no outgoing edges. |
84
+
85
+ NOT executable in a blueprint (display-tier only, rejected with a named
86
+ issue): \`sleepUntil\`, \`capture\`, \`digest\`, \`unknown\`.
87
+
88
+ ## Durations
89
+
90
+ Everywhere a duration appears (\`sleep.meta.duration\`, \`wait.meta.timeout\`,
91
+ \`entryPeriod\`, \`suppress\`):
92
+
93
+ \`\`\`
94
+ { "hours"?: number, "minutes"?: number, "seconds"?: number }
95
+ \`\`\`
96
+
97
+ Keys are strict and values non-negative. At least one key is required
98
+ (except \`suppress\`, where \`{}\` means "disabled"). There is NO \`days\`
99
+ key — \`{ "days": 3 }\` is rejected loudly (write \`{ "hours": 72 }\`).
100
+
101
+ ## Conditions (\`ConditionEval\`)
102
+
103
+ Used by \`decision\`/\`branch\` nodes. Discriminated on \`type\`:
104
+
105
+ - **property** — \`{ type: "property", property, operator, value? }\`.
106
+ Operators: \`eq | neq | gt | gte | lt | lte | exists | not_exists |
107
+ contains\`. \`value\` is a string/number/boolean (omit for
108
+ \`exists\`/\`not_exists\`).
109
+ - **event** — \`{ type: "event", eventName, check, operator?, value?,
110
+ within? }\`. \`check\`: \`exists | not_exists | count\`; for \`count\`,
111
+ pair \`operator\` (\`gt | gte | lt | lte | eq\`) with a numeric \`value\`.
112
+ \`within\` is an optional duration window.
113
+ - **email_engagement** — \`{ type: "email_engagement", templateKey,
114
+ check }\`. \`check\`: \`opened | clicked | not_opened | not_clicked\`.
115
+ - **composite** — \`{ type: "composite", operator: "and" | "or",
116
+ conditions: ConditionEval[] }\` (nestable).
117
+
118
+ \`triggerWhere\` and \`exitOn[].where\` accept ONLY property conditions
119
+ (they evaluate against the incoming event's properties).
120
+
121
+ ## Structural rules (all validated at save time)
122
+
123
+ - Node and edge ids are unique; every edge connects two existing nodes.
124
+ - Exactly one \`start\` node; every node is reachable from it.
125
+ - The graph is acyclic (no loop constructs in v1).
126
+ - Fan-out is unambiguous: only \`decision\`/\`branch\` (one true + one false
127
+ edge) and \`wait\` (one answered + one timedOut, or a single unconditional
128
+ edge) fork; every other node has at most one outgoing edge; \`end-*\`
129
+ nodes have none.
130
+
131
+ ## Record-level fields (on the blueprint, NOT in the graph)
132
+
133
+ - \`name\` (required), \`description?\`.
134
+ - \`status\` — \`draft\` (default) | \`enabled\` | \`disabled\`. Create
135
+ accepts \`draft\`/\`enabled\`; afterwards transitions go through the
136
+ enable/disable operations (enable re-validates the stored graph against
137
+ the CURRENT template/connector registries).
138
+ - \`triggerEvent\` (required) — the event name that enrolls users.
139
+ - \`triggerWhere?\` — property conditions the trigger event's properties
140
+ must satisfy for enrollment.
141
+ - \`entryLimit\` (required) — \`once | once_per_period | unlimited\`; pair
142
+ \`once_per_period\` with \`entryPeriod\` (a duration).
143
+ - \`exitOn?\` — \`[{ event, where? }]\`: events that abort in-flight runs.
144
+ - \`suppress\` (required) — quiet-period duration after a completed run;
145
+ \`{}\` disables suppression.
146
+
147
+ Reserved namespaces \`email.*\`, \`journey.*\`, \`bucket.*\`, \`contact.*\`
148
+ are engine-emitted — do not use them as blueprint trigger events.
149
+
150
+ ## Workflow: validate, iterate, then write
151
+
152
+ Validation returns structured issues \`[{ nodeId?, edgeId?, path, code,
153
+ message }]\` naming exactly what is wrong and where — fix and retry.
154
+ Iterate with the validate (dry-run) surface until the graph is valid, then
155
+ create/update; the same checks run on every write, so nothing invalid is
156
+ ever saved. A \`valid: false\` report is a successful call, not an error.
157
+ Event names are an open vocabulary (prefer an observed/declared name over
158
+ inventing a near-duplicate); template keys and connector actions are closed
159
+ registries — list them before referencing them.
160
+ `;
@@ -0,0 +1,390 @@
1
+ /**
2
+ * Journey Blueprint authoring tools (spec §9, phase 4) — the agent-facing
3
+ * surface for creating, validating, and operating blueprints without a
4
+ * deploy in the loop.
5
+ *
6
+ * Deliberately TRANSPORT-AGNOSTIC: this repo runs no MCP server today, so
7
+ * each tool is a plain `{ name, description, inputSchema, handler }` record
8
+ * rather than a registration against a specific SDK. That shape mounts
9
+ * 1:1 onto whatever hosts it:
10
+ * - an MCP server: `server.registerTool(t.name, { description, inputSchema }, t.handler)`
11
+ * - the Vercel AI SDK (like `buildAgentTools`): `tool({ description, inputSchema, execute: t.handler })`
12
+ * - direct in-process calls (tests, scripts): `await t.handler(input)`
13
+ *
14
+ * Handlers call the SAME service layer the admin routes use
15
+ * (`lib/blueprints.ts`) — in-process function calls, no HTTP round-trip, no
16
+ * parallel auth or storage path (spec §9: "thin wrapper … no parallel auth
17
+ * or storage path"). Authentication is the MOUNTING surface's job, exactly
18
+ * as `adminRouter` middleware is for the routes: do not expose these tools
19
+ * without an auth gate in front of them.
20
+ *
21
+ * Contract: handlers NEVER throw for expected failures. Every result is a
22
+ * discriminated union on `ok` (+ `code` on failures), and graph problems
23
+ * carry the same structured `BlueprintValidationIssue[]` the admin routes
24
+ * return — an authoring agent iterates on an itemized "what's wrong and
25
+ * where" list, not a caught exception's `.message`. Unexpected errors (DB
26
+ * down, …) still throw and are the host's problem.
27
+ */
28
+ import type { BlueprintValidationIssue } from "@hogsend/core";
29
+ import { getTemplateNames } from "@hogsend/email";
30
+ import { z } from "zod";
31
+ import {
32
+ type BlueprintServiceContainer,
33
+ blueprintCreateBaseSchema,
34
+ blueprintPatchFieldsSchema,
35
+ createBlueprint,
36
+ disableBlueprint,
37
+ enableBlueprint,
38
+ findBlueprintRow,
39
+ type SerializedBlueprint,
40
+ serializeBlueprint,
41
+ updateBlueprint,
42
+ validateBlueprintGraphForSave,
43
+ } from "../lib/blueprints.js";
44
+ import { listEventNameVocabulary } from "../lib/event-names.js";
45
+ import { GRAPH_FORMAT, ISSUE_LOOP_HINT } from "./authoring-guide.js";
46
+
47
+ // ---------------------------------------------------------------------------
48
+ // Tool shape
49
+ // ---------------------------------------------------------------------------
50
+
51
+ /** Issue shape shared by input parsing and graph validation failures. */
52
+ export type BlueprintToolIssue = {
53
+ nodeId?: string;
54
+ edgeId?: string;
55
+ path: (string | number)[];
56
+ code: string;
57
+ message: string;
58
+ };
59
+
60
+ /** Returned when the tool call's arguments don't parse against `inputSchema`. */
61
+ export type BlueprintToolInvalidInput = {
62
+ ok: false;
63
+ code: "invalid_input";
64
+ error: string;
65
+ issues: BlueprintToolIssue[];
66
+ };
67
+
68
+ /**
69
+ * One tool: a name, an agent-facing description, a Zod input schema (convert
70
+ * with `z.toJSONSchema` for hosts that speak JSON Schema, e.g. MCP), and a
71
+ * handler. The handler safe-parses its own input (applying defaults), so it
72
+ * is self-contained even when the host doesn't pre-validate.
73
+ */
74
+ export interface BlueprintToolDefinition<S extends z.ZodType, Out> {
75
+ name: string;
76
+ description: string;
77
+ inputSchema: S;
78
+ handler: (input: unknown) => Promise<Out | BlueprintToolInvalidInput>;
79
+ }
80
+
81
+ function defineTool<S extends z.ZodType, Out>(def: {
82
+ name: string;
83
+ description: string;
84
+ inputSchema: S;
85
+ run: (input: z.output<S>) => Promise<Out>;
86
+ }): BlueprintToolDefinition<S, Out> {
87
+ return {
88
+ name: def.name,
89
+ description: def.description,
90
+ inputSchema: def.inputSchema,
91
+ handler: async (input) => {
92
+ const parsed = def.inputSchema.safeParse(input ?? {});
93
+ if (!parsed.success) {
94
+ return {
95
+ ok: false,
96
+ code: "invalid_input",
97
+ error: `Invalid input for ${def.name}`,
98
+ issues: parsed.error.issues.map((issue) => ({
99
+ path: issue.path.filter(
100
+ (p): p is string | number => typeof p !== "symbol",
101
+ ),
102
+ code: issue.code,
103
+ message: issue.message,
104
+ })),
105
+ } satisfies BlueprintToolInvalidInput;
106
+ }
107
+ return def.run(parsed.data);
108
+ },
109
+ };
110
+ }
111
+
112
+ // ---------------------------------------------------------------------------
113
+ // Shared result pieces + description fragments
114
+ // ---------------------------------------------------------------------------
115
+
116
+ type ToolWriteSuccess = { ok: true; blueprint: SerializedBlueprint };
117
+ type ToolNotFound = { ok: false; code: "not_found"; error: string };
118
+ type ToolConflict = { ok: false; code: "conflict"; error: string };
119
+ type ToolPromoted = { ok: false; code: "promoted"; error: string };
120
+ type ToolInFlight = { ok: false; code: "in_flight"; error: string };
121
+ type ToolVersionConflict = {
122
+ ok: false;
123
+ code: "version_conflict";
124
+ error: string;
125
+ };
126
+ type ToolInvalidGraph = {
127
+ ok: false;
128
+ code: "invalid_graph";
129
+ error: string;
130
+ issues: BlueprintValidationIssue[];
131
+ };
132
+
133
+ const okWrite = (blueprint: SerializedBlueprint): ToolWriteSuccess => ({
134
+ ok: true,
135
+ blueprint,
136
+ });
137
+
138
+ // The closed executable vocabulary summary (GRAPH_FORMAT) and the
139
+ // iterate-on-issues hint live in ./authoring-guide.js — shared verbatim with
140
+ // the @hogsend/mcp resource so the two surfaces can never drift.
141
+
142
+ // ---------------------------------------------------------------------------
143
+ // Input schemas
144
+ // ---------------------------------------------------------------------------
145
+
146
+ // Neither `source` NOR `createdBy` is an input — this surface stamps "mcp"
147
+ // itself and binds `createdBy` to the mount identity, so provenance (spec §10
148
+ // Studio oversight) can't be spoofed by a prompt attributing a blueprint to
149
+ // someone else.
150
+ const createInputSchema = blueprintCreateBaseSchema.omit({ createdBy: true });
151
+
152
+ const updateInputSchema = blueprintPatchFieldsSchema
153
+ .extend({ id: z.string().min(1) })
154
+ .refine(
155
+ (body) =>
156
+ Object.entries(body).some(([k, v]) => k !== "id" && v !== undefined),
157
+ { message: "update must set at least one field besides `id`" },
158
+ );
159
+
160
+ const validateInputSchema = z
161
+ .object({
162
+ graph: z.unknown().optional(),
163
+ id: z.string().min(1).optional(),
164
+ })
165
+ .refine((v) => (v.graph !== undefined) !== (v.id !== undefined), {
166
+ message:
167
+ "provide exactly one of `graph` (validate an unsaved graph) or `id` (re-validate a stored blueprint)",
168
+ });
169
+
170
+ const idInputSchema = z.object({ id: z.string().min(1) });
171
+
172
+ const listEventsInputSchema = z.object({
173
+ search: z
174
+ .string()
175
+ .min(1)
176
+ .optional()
177
+ .describe("case-insensitive substring filter on the event name"),
178
+ limit: z.number().int().min(1).max(200).default(100),
179
+ });
180
+
181
+ // ---------------------------------------------------------------------------
182
+ // Factory
183
+ // ---------------------------------------------------------------------------
184
+
185
+ export interface JourneyBlueprintToolsOptions {
186
+ /** The DI client (or a Pick of db/registry/templates/connectorActionRegistry). */
187
+ container: BlueprintServiceContainer;
188
+ /**
189
+ * Actor label stamped into `journey_blueprints.createdBy` for every create —
190
+ * bind the mounting session's identity here (e.g. an MCP session id or
191
+ * operator email) for Studio's post-hoc oversight. It is NOT a tool input:
192
+ * a model cannot attribute a blueprint to anyone, exactly as `source` is
193
+ * stamped by the surface.
194
+ */
195
+ createdBy?: string;
196
+ }
197
+
198
+ /**
199
+ * Build the journey-blueprint tool set (spec §9). See the module docs for
200
+ * the mounting contract; `Object.values(tools)` gives the array form.
201
+ */
202
+ export function createJourneyBlueprintTools(
203
+ options: JourneyBlueprintToolsOptions,
204
+ ) {
205
+ const { container, createdBy: defaultCreatedBy } = options;
206
+
207
+ const create_journey_blueprint = defineTool({
208
+ name: "create_journey_blueprint",
209
+ description:
210
+ "Create a journey blueprint — a lifecycle automation authored as a JSON graph, stored in the database and executed by the generic interpreter (no deploy). " +
211
+ 'The blueprint id is the graph\'s journeyId. Defaults to status "draft"; pass status "enabled" to go live immediately (new matching events start enrolling). ' +
212
+ "The graph is fully validated (schema + structure + template/connector registries) BEFORE anything is written — an invalid graph is never saved. " +
213
+ "triggerEvent (+ optional triggerWhere property conditions) decides enrollment; entryLimit is once | once_per_period (with entryPeriod) | unlimited; " +
214
+ "exitOn lists events that abort in-flight runs; suppress is a quiet-period duration ({} disables). " +
215
+ GRAPH_FORMAT +
216
+ " " +
217
+ ISSUE_LOOP_HINT,
218
+ inputSchema: createInputSchema,
219
+ run: async (
220
+ input,
221
+ ): Promise<ToolWriteSuccess | ToolConflict | ToolInvalidGraph> => {
222
+ const result = await createBlueprint({
223
+ container,
224
+ input: {
225
+ ...input,
226
+ source: "mcp",
227
+ // Mount-bound identity always wins — `createdBy` is not a tool input.
228
+ createdBy: defaultCreatedBy,
229
+ },
230
+ });
231
+ if (!result.ok) return result;
232
+ return okWrite(serializeBlueprint(result.blueprint));
233
+ },
234
+ });
235
+
236
+ const update_journey_blueprint = defineTool({
237
+ name: "update_journey_blueprint",
238
+ description:
239
+ "Partially update a journey blueprint by id. A `graph` change is re-validated exactly like create and bumps `version` by 1, " +
240
+ "but is REJECTED while the blueprint has any active/waiting enrollment (editing a live graph can desync the durable replay journal " +
241
+ "for a run suspended mid-graph) — wait for enrollments to drain, or disable the blueprint and let them finish, first. " +
242
+ "Metadata-only edits (name, triggerEvent, exitOn, …) don't bump and are never blocked. " +
243
+ "The id is immutable — graph.journeyId must equal `id`. Status cannot be set here: use enable_journey_blueprint / disable_journey_blueprint. " +
244
+ "Nullable fields (description, triggerWhere, entryPeriod, exitOn) accept null to clear. " +
245
+ "A blueprint promoted to code is frozen and rejects every update — the code journey is the source of truth. " +
246
+ GRAPH_FORMAT +
247
+ " " +
248
+ ISSUE_LOOP_HINT,
249
+ inputSchema: updateInputSchema,
250
+ run: async ({
251
+ id,
252
+ ...patch
253
+ }): Promise<
254
+ | ToolWriteSuccess
255
+ | ToolNotFound
256
+ | ToolInvalidGraph
257
+ | ToolInFlight
258
+ | ToolVersionConflict
259
+ | ToolPromoted
260
+ > => {
261
+ const result = await updateBlueprint({ container, id, patch });
262
+ if (!result.ok) return result;
263
+ return okWrite(serializeBlueprint(result.blueprint));
264
+ },
265
+ });
266
+
267
+ const validate_journey_blueprint = defineTool({
268
+ name: "validate_journey_blueprint",
269
+ description:
270
+ "Dry-run validation, no write — the iterate-in-a-loop call while authoring. Pass `graph` to validate an unsaved graph, " +
271
+ "or `id` to re-validate a stored blueprint's graph against the CURRENT template/connector registries (useful after registry drift). " +
272
+ "Returns { valid, issues } — a `valid: false` report is a successful call, not an error. Runs the exact checks create/update/enable run. " +
273
+ GRAPH_FORMAT,
274
+ inputSchema: validateInputSchema,
275
+ run: async ({
276
+ graph,
277
+ id,
278
+ }): Promise<
279
+ | { ok: true; valid: boolean; issues: BlueprintValidationIssue[] }
280
+ | ToolNotFound
281
+ > => {
282
+ let target: unknown = graph;
283
+ if (id !== undefined) {
284
+ const row = await findBlueprintRow({ db: container.db, id });
285
+ if (!row) {
286
+ return {
287
+ ok: false,
288
+ code: "not_found",
289
+ error: `Blueprint "${id}" not found`,
290
+ };
291
+ }
292
+ target = row.graph;
293
+ }
294
+ const result = validateBlueprintGraphForSave(target, container);
295
+ return result.valid
296
+ ? { ok: true, valid: true, issues: [] }
297
+ : { ok: true, valid: false, issues: result.issues };
298
+ },
299
+ });
300
+
301
+ const list_email_templates = defineTool({
302
+ name: "list_email_templates",
303
+ description:
304
+ "List the registered email template keys — the ONLY values a blueprint send node's meta.template may use " +
305
+ "(a send of an unregistered key is rejected at save time). Returns each template's key, default subject, and category.",
306
+ inputSchema: z.object({}),
307
+ run: async () => {
308
+ const view = container.templates as Record<
309
+ string,
310
+ { defaultSubject?: string; category?: string }
311
+ >;
312
+ const templates = getTemplateNames(container.templates)
313
+ .map((key) => String(key))
314
+ .sort()
315
+ .map((key) => ({
316
+ key,
317
+ defaultSubject: view[key]?.defaultSubject,
318
+ category: view[key]?.category,
319
+ }));
320
+ return { ok: true as const, templates };
321
+ },
322
+ });
323
+
324
+ const list_events = defineTool({
325
+ name: "list_events",
326
+ description:
327
+ "Best-effort event-name vocabulary for authoring triggers, waits, and exitOn rules. Event names are an OPEN vocabulary " +
328
+ "(no closed registry exists anywhere in the engine — same as code journeys), so this merges: events actually observed in the " +
329
+ "event store (with occurrence counts, most recently seen first) and events referenced as code-journey or blueprint triggers. " +
330
+ "Any other event name is also valid — it just hasn't been seen yet. Prefer a listed name over inventing a near-duplicate.",
331
+ inputSchema: listEventsInputSchema,
332
+ run: async ({ search, limit }) => {
333
+ // Delegates to the shared vocabulary helper (lib/event-names.ts) —
334
+ // the same implementation GET /v1/admin/events/names serves.
335
+ const { note, events } = await listEventNameVocabulary({
336
+ db: container.db,
337
+ registry: container.registry,
338
+ search,
339
+ limit,
340
+ });
341
+ return { ok: true as const, note, events };
342
+ },
343
+ });
344
+
345
+ const enable_journey_blueprint = defineTool({
346
+ name: "enable_journey_blueprint",
347
+ description:
348
+ "Enable a blueprint: new matching events start enrolling on the next ingest. The stored graph is re-validated against the " +
349
+ "CURRENT registries first — a blueprint whose template/connector vanished since save cannot go live (fix it via " +
350
+ "update_journey_blueprint, guided by the returned issues). Idempotent when already enabled. A blueprint promoted to code " +
351
+ "cannot be re-enabled.",
352
+ inputSchema: idInputSchema,
353
+ run: async ({
354
+ id,
355
+ }): Promise<
356
+ ToolWriteSuccess | ToolNotFound | ToolPromoted | ToolInvalidGraph
357
+ > => {
358
+ const result = await enableBlueprint({ container, id });
359
+ if (!result.ok) return result;
360
+ return okWrite(serializeBlueprint(result.blueprint));
361
+ },
362
+ });
363
+
364
+ const disable_journey_blueprint = defineTool({
365
+ name: "disable_journey_blueprint",
366
+ description:
367
+ "Disable a blueprint: new enrollments stop on the next event; in-flight runs keep going to completion " +
368
+ "(same semantics as a code journey with enabled: false). Idempotent when already disabled.",
369
+ inputSchema: idInputSchema,
370
+ run: async ({ id }): Promise<ToolWriteSuccess | ToolNotFound> => {
371
+ const result = await disableBlueprint({ container, id });
372
+ if (!result.ok) return result;
373
+ return okWrite(serializeBlueprint(result.blueprint));
374
+ },
375
+ });
376
+
377
+ return {
378
+ create_journey_blueprint,
379
+ update_journey_blueprint,
380
+ validate_journey_blueprint,
381
+ list_email_templates,
382
+ list_events,
383
+ enable_journey_blueprint,
384
+ disable_journey_blueprint,
385
+ };
386
+ }
387
+
388
+ export type JourneyBlueprintTools = ReturnType<
389
+ typeof createJourneyBlueprintTools
390
+ >;
@@ -9,6 +9,19 @@ import { hasScope, requireApiKey } from "./api-key.js";
9
9
  // path is closed signup (only the first user can register; see app.ts), so any
10
10
  // authenticated session is an intended admin in this single-tenant model.
11
11
  export const requireAdmin = createMiddleware<AppEnv>(async (c, next) => {
12
+ // The Bearer path delegates to requireApiKey, which reads `env`/`db` off the
13
+ // container — and the session path reads `auth`. Now that requireAdmin is a
14
+ // public export a consumer can mount on their own app, a missing container
15
+ // would otherwise surface as an opaque `Cannot destructure 'env' of
16
+ // undefined` 500. Fail loud and named at mount-misuse time instead (this is
17
+ // NOT an auth outcome — do not turn it into a 401).
18
+ if (!c.get("container")) {
19
+ throw new Error(
20
+ "requireAdmin requires the Hogsend container context — mount it on an " +
21
+ "app built by createApp, or set the container variable first",
22
+ );
23
+ }
24
+
12
25
  const header = c.req.header("authorization");
13
26
  if (header?.startsWith("Bearer ")) {
14
27
  // Authenticate the key, then REQUIRE `full-admin` scope. Without this,