@hogsend/engine 0.39.0 → 0.41.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.
- package/package.json +9 -7
- package/src/buckets/check-membership.ts +6 -1
- package/src/campaigns/cohort-sql.ts +198 -0
- package/src/campaigns/define-campaign.ts +301 -0
- package/src/campaigns/reconcile.ts +391 -0
- package/src/campaigns/steps.ts +48 -0
- package/src/connectors/define-action.ts +70 -0
- package/src/container.ts +144 -42
- package/src/destinations/presets/posthog.ts +7 -1
- package/src/env.ts +14 -0
- package/src/index.ts +98 -3
- package/src/journeys/constants.ts +10 -0
- package/src/journeys/define-journey.ts +14 -405
- package/src/journeys/execute-journey-run.ts +608 -0
- package/src/journeys/graph/build-graph.ts +212 -56
- package/src/journeys/journey-boundary.ts +54 -0
- package/src/journeys/journey-context.ts +374 -59
- package/src/journeys/record-once.ts +110 -0
- package/src/lib/auth.ts +33 -1
- package/src/lib/blueprints.ts +576 -0
- package/src/lib/campaign-send-key.ts +58 -0
- package/src/lib/connector-actions.ts +203 -19
- package/src/lib/contacts.ts +54 -0
- package/src/lib/email-service-types.ts +4 -1
- package/src/lib/email.ts +13 -2
- package/src/lib/feed.ts +77 -57
- package/src/lib/frequency-cap.ts +45 -15
- package/src/lib/hatchet-duration.ts +22 -0
- package/src/lib/html.ts +1 -0
- package/src/lib/ingestion.ts +145 -4
- package/src/lib/journey-suppress.ts +87 -0
- package/src/lib/links.ts +204 -18
- package/src/lib/outbound.ts +20 -0
- package/src/lib/preferences.ts +80 -1
- package/src/lib/tracked.ts +44 -29
- package/src/lib/tracking-event-names.ts +8 -0
- package/src/lib/webhook-signing.ts +6 -1
- package/src/lists/channels.ts +75 -0
- package/src/lists/define-list.ts +34 -0
- package/src/lists/registry.ts +29 -2
- package/src/mcp/blueprint-tools.ts +460 -0
- package/src/routes/admin/blueprints.ts +711 -0
- package/src/routes/admin/campaigns.ts +341 -0
- package/src/routes/admin/emails.ts +13 -0
- package/src/routes/admin/index.ts +6 -0
- package/src/routes/admin/journeys.ts +4 -2
- package/src/routes/admin/links.ts +303 -36
- package/src/routes/admin/lists.ts +51 -0
- package/src/routes/campaigns/index.ts +297 -50
- package/src/routes/email/preferences.ts +50 -13
- package/src/routes/feed/recipient.ts +2 -43
- package/src/routes/index.ts +6 -0
- package/src/routes/lists/index.ts +138 -18
- package/src/routes/tracking/arrive.ts +260 -0
- package/src/routes/tracking/click-pipeline.ts +329 -0
- package/src/routes/tracking/click.ts +5 -270
- package/src/routes/tracking/index.ts +2 -0
- package/src/routes/tracking/vanity.ts +64 -0
- package/src/worker.ts +27 -0
- package/src/workflows/bucket-backfill.ts +4 -2
- package/src/workflows/bucket-reconcile.ts +11 -4
- package/src/workflows/check-alerts.ts +130 -1
- package/src/workflows/journey-blueprint-interpreter.ts +561 -0
- package/src/workflows/send-campaign.ts +673 -127
|
@@ -0,0 +1,460 @@
|
|
|
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 { journeyBlueprints, userEvents } from "@hogsend/db";
|
|
30
|
+
import { getTemplateNames } from "@hogsend/email";
|
|
31
|
+
import { count, desc, ilike, max } from "drizzle-orm";
|
|
32
|
+
import { z } from "zod";
|
|
33
|
+
import {
|
|
34
|
+
type BlueprintServiceContainer,
|
|
35
|
+
blueprintCreateBaseSchema,
|
|
36
|
+
blueprintPatchFieldsSchema,
|
|
37
|
+
createBlueprint,
|
|
38
|
+
disableBlueprint,
|
|
39
|
+
enableBlueprint,
|
|
40
|
+
findBlueprintRow,
|
|
41
|
+
type SerializedBlueprint,
|
|
42
|
+
serializeBlueprint,
|
|
43
|
+
updateBlueprint,
|
|
44
|
+
validateBlueprintGraphForSave,
|
|
45
|
+
} from "../lib/blueprints.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 ToolInvalidGraph = {
|
|
122
|
+
ok: false;
|
|
123
|
+
code: "invalid_graph";
|
|
124
|
+
error: string;
|
|
125
|
+
issues: BlueprintValidationIssue[];
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
const okWrite = (blueprint: SerializedBlueprint): ToolWriteSuccess => ({
|
|
129
|
+
ok: true,
|
|
130
|
+
blueprint,
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* The closed executable vocabulary (spec §6/§7), summarized for the model.
|
|
135
|
+
* Kept in the descriptions of every graph-accepting tool so an agent can
|
|
136
|
+
* author without a docs round-trip.
|
|
137
|
+
*/
|
|
138
|
+
const GRAPH_FORMAT =
|
|
139
|
+
"Graph format: { journeyId, nodes[], edges[] }. journeyId IS the blueprint id. " +
|
|
140
|
+
'Node: { id, type, title, meta? }. Executable node types (closed vocabulary): "start" (exactly one; the entry point), ' +
|
|
141
|
+
'"sleep" (meta.duration: { hours?, minutes?, seconds? }), ' +
|
|
142
|
+
'"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), ' +
|
|
143
|
+
'"send" (meta: { template, idempotencyLabel? } — template MUST be a key from list_email_templates), ' +
|
|
144
|
+
'"connector" (meta: { connectorId, action } — must be a registered connector action), ' +
|
|
145
|
+
'"checkpoint", "trigger" (meta: { event } — fires an event through the ingest pipeline), ' +
|
|
146
|
+
'"decision"/"branch" (meta.conditions: ConditionEval[]; exactly two outgoing edges, kinds "conditional-true" and "conditional-false"), ' +
|
|
147
|
+
'and terminals "end-completed"/"end-exited"/"end-failed". ' +
|
|
148
|
+
'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. ' +
|
|
149
|
+
"Trigger/entryLimit/exitOn/suppress live on the blueprint record, not in the graph.";
|
|
150
|
+
|
|
151
|
+
const ISSUE_LOOP_HINT =
|
|
152
|
+
"On validation failure you get structured issues [{ nodeId?, edgeId?, path, code, message }] naming exactly what is wrong and where — fix and retry. " +
|
|
153
|
+
"Tip: iterate with validate_journey_blueprint until valid before writing.";
|
|
154
|
+
|
|
155
|
+
// ---------------------------------------------------------------------------
|
|
156
|
+
// Input schemas
|
|
157
|
+
// ---------------------------------------------------------------------------
|
|
158
|
+
|
|
159
|
+
// `source` is NOT an input — this surface stamps "mcp" itself, so provenance
|
|
160
|
+
// (spec §10 Studio oversight) can't be spoofed by a prompt.
|
|
161
|
+
const createInputSchema = blueprintCreateBaseSchema;
|
|
162
|
+
|
|
163
|
+
const updateInputSchema = blueprintPatchFieldsSchema
|
|
164
|
+
.extend({ id: z.string().min(1) })
|
|
165
|
+
.refine(
|
|
166
|
+
(body) =>
|
|
167
|
+
Object.entries(body).some(([k, v]) => k !== "id" && v !== undefined),
|
|
168
|
+
{ message: "update must set at least one field besides `id`" },
|
|
169
|
+
);
|
|
170
|
+
|
|
171
|
+
const validateInputSchema = z
|
|
172
|
+
.object({
|
|
173
|
+
graph: z.unknown().optional(),
|
|
174
|
+
id: z.string().min(1).optional(),
|
|
175
|
+
})
|
|
176
|
+
.refine((v) => (v.graph !== undefined) !== (v.id !== undefined), {
|
|
177
|
+
message:
|
|
178
|
+
"provide exactly one of `graph` (validate an unsaved graph) or `id` (re-validate a stored blueprint)",
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
const idInputSchema = z.object({ id: z.string().min(1) });
|
|
182
|
+
|
|
183
|
+
const listEventsInputSchema = z.object({
|
|
184
|
+
search: z
|
|
185
|
+
.string()
|
|
186
|
+
.min(1)
|
|
187
|
+
.optional()
|
|
188
|
+
.describe("case-insensitive substring filter on the event name"),
|
|
189
|
+
limit: z.number().int().min(1).max(200).default(100),
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
// ---------------------------------------------------------------------------
|
|
193
|
+
// Factory
|
|
194
|
+
// ---------------------------------------------------------------------------
|
|
195
|
+
|
|
196
|
+
export interface JourneyBlueprintToolsOptions {
|
|
197
|
+
/** The DI client (or a Pick of db/registry/templates/connectorActionRegistry). */
|
|
198
|
+
container: BlueprintServiceContainer;
|
|
199
|
+
/**
|
|
200
|
+
* Actor label stamped into `journey_blueprints.createdBy` when a call
|
|
201
|
+
* doesn't provide one — bind the mounting session's identity here (e.g.
|
|
202
|
+
* an MCP session id or operator email) for Studio's post-hoc oversight.
|
|
203
|
+
*/
|
|
204
|
+
createdBy?: string;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Build the journey-blueprint tool set (spec §9). See the module docs for
|
|
209
|
+
* the mounting contract; `Object.values(tools)` gives the array form.
|
|
210
|
+
*/
|
|
211
|
+
export function createJourneyBlueprintTools(
|
|
212
|
+
options: JourneyBlueprintToolsOptions,
|
|
213
|
+
) {
|
|
214
|
+
const { container, createdBy: defaultCreatedBy } = options;
|
|
215
|
+
|
|
216
|
+
const create_journey_blueprint = defineTool({
|
|
217
|
+
name: "create_journey_blueprint",
|
|
218
|
+
description:
|
|
219
|
+
"Create a journey blueprint — a lifecycle automation authored as a JSON graph, stored in the database and executed by the generic interpreter (no deploy). " +
|
|
220
|
+
'The blueprint id is the graph\'s journeyId. Defaults to status "draft"; pass status "enabled" to go live immediately (new matching events start enrolling). ' +
|
|
221
|
+
"The graph is fully validated (schema + structure + template/connector registries) BEFORE anything is written — an invalid graph is never saved. " +
|
|
222
|
+
"triggerEvent (+ optional triggerWhere property conditions) decides enrollment; entryLimit is once | once_per_period (with entryPeriod) | unlimited; " +
|
|
223
|
+
"exitOn lists events that abort in-flight runs; suppress is a quiet-period duration ({} disables). " +
|
|
224
|
+
GRAPH_FORMAT +
|
|
225
|
+
" " +
|
|
226
|
+
ISSUE_LOOP_HINT,
|
|
227
|
+
inputSchema: createInputSchema,
|
|
228
|
+
run: async (
|
|
229
|
+
input,
|
|
230
|
+
): Promise<ToolWriteSuccess | ToolConflict | ToolInvalidGraph> => {
|
|
231
|
+
const result = await createBlueprint({
|
|
232
|
+
container,
|
|
233
|
+
input: {
|
|
234
|
+
...input,
|
|
235
|
+
source: "mcp",
|
|
236
|
+
createdBy: input.createdBy ?? defaultCreatedBy,
|
|
237
|
+
},
|
|
238
|
+
});
|
|
239
|
+
if (!result.ok) return result;
|
|
240
|
+
return okWrite(serializeBlueprint(result.blueprint));
|
|
241
|
+
},
|
|
242
|
+
});
|
|
243
|
+
|
|
244
|
+
const update_journey_blueprint = defineTool({
|
|
245
|
+
name: "update_journey_blueprint",
|
|
246
|
+
description:
|
|
247
|
+
"Partially update a journey blueprint by id. A `graph` change is re-validated exactly like create and bumps `version` by 1, " +
|
|
248
|
+
"but is REJECTED while the blueprint has any active/waiting enrollment (editing a live graph can desync the durable replay journal " +
|
|
249
|
+
"for a run suspended mid-graph) — wait for enrollments to drain, or disable the blueprint and let them finish, first. " +
|
|
250
|
+
"Metadata-only edits (name, triggerEvent, exitOn, …) don't bump and are never blocked. " +
|
|
251
|
+
"The id is immutable — graph.journeyId must equal `id`. Status cannot be set here: use enable_journey_blueprint / disable_journey_blueprint. " +
|
|
252
|
+
"Nullable fields (description, triggerWhere, entryPeriod, exitOn) accept null to clear. " +
|
|
253
|
+
GRAPH_FORMAT +
|
|
254
|
+
" " +
|
|
255
|
+
ISSUE_LOOP_HINT,
|
|
256
|
+
inputSchema: updateInputSchema,
|
|
257
|
+
run: async ({
|
|
258
|
+
id,
|
|
259
|
+
...patch
|
|
260
|
+
}): Promise<
|
|
261
|
+
ToolWriteSuccess | ToolNotFound | ToolInvalidGraph | ToolInFlight
|
|
262
|
+
> => {
|
|
263
|
+
const result = await updateBlueprint({ container, id, patch });
|
|
264
|
+
if (!result.ok) return result;
|
|
265
|
+
return okWrite(serializeBlueprint(result.blueprint));
|
|
266
|
+
},
|
|
267
|
+
});
|
|
268
|
+
|
|
269
|
+
const validate_journey_blueprint = defineTool({
|
|
270
|
+
name: "validate_journey_blueprint",
|
|
271
|
+
description:
|
|
272
|
+
"Dry-run validation, no write — the iterate-in-a-loop call while authoring. Pass `graph` to validate an unsaved graph, " +
|
|
273
|
+
"or `id` to re-validate a stored blueprint's graph against the CURRENT template/connector registries (useful after registry drift). " +
|
|
274
|
+
"Returns { valid, issues } — a `valid: false` report is a successful call, not an error. Runs the exact checks create/update/enable run. " +
|
|
275
|
+
GRAPH_FORMAT,
|
|
276
|
+
inputSchema: validateInputSchema,
|
|
277
|
+
run: async ({
|
|
278
|
+
graph,
|
|
279
|
+
id,
|
|
280
|
+
}): Promise<
|
|
281
|
+
| { ok: true; valid: boolean; issues: BlueprintValidationIssue[] }
|
|
282
|
+
| ToolNotFound
|
|
283
|
+
> => {
|
|
284
|
+
let target: unknown = graph;
|
|
285
|
+
if (id !== undefined) {
|
|
286
|
+
const row = await findBlueprintRow({ db: container.db, id });
|
|
287
|
+
if (!row) {
|
|
288
|
+
return {
|
|
289
|
+
ok: false,
|
|
290
|
+
code: "not_found",
|
|
291
|
+
error: `Blueprint "${id}" not found`,
|
|
292
|
+
};
|
|
293
|
+
}
|
|
294
|
+
target = row.graph;
|
|
295
|
+
}
|
|
296
|
+
const result = validateBlueprintGraphForSave(target, container);
|
|
297
|
+
return result.valid
|
|
298
|
+
? { ok: true, valid: true, issues: [] }
|
|
299
|
+
: { ok: true, valid: false, issues: result.issues };
|
|
300
|
+
},
|
|
301
|
+
});
|
|
302
|
+
|
|
303
|
+
const list_email_templates = defineTool({
|
|
304
|
+
name: "list_email_templates",
|
|
305
|
+
description:
|
|
306
|
+
"List the registered email template keys — the ONLY values a blueprint send node's meta.template may use " +
|
|
307
|
+
"(a send of an unregistered key is rejected at save time). Returns each template's key, default subject, and category.",
|
|
308
|
+
inputSchema: z.object({}),
|
|
309
|
+
run: async () => {
|
|
310
|
+
const view = container.templates as Record<
|
|
311
|
+
string,
|
|
312
|
+
{ defaultSubject?: string; category?: string }
|
|
313
|
+
>;
|
|
314
|
+
const templates = getTemplateNames(container.templates)
|
|
315
|
+
.map((key) => String(key))
|
|
316
|
+
.sort()
|
|
317
|
+
.map((key) => ({
|
|
318
|
+
key,
|
|
319
|
+
defaultSubject: view[key]?.defaultSubject,
|
|
320
|
+
category: view[key]?.category,
|
|
321
|
+
}));
|
|
322
|
+
return { ok: true as const, templates };
|
|
323
|
+
},
|
|
324
|
+
});
|
|
325
|
+
|
|
326
|
+
const list_events = defineTool({
|
|
327
|
+
name: "list_events",
|
|
328
|
+
description:
|
|
329
|
+
"Best-effort event-name vocabulary for authoring triggers, waits, and exitOn rules. Event names are an OPEN vocabulary " +
|
|
330
|
+
"(no closed registry exists anywhere in the engine — same as code journeys), so this merges: events actually observed in the " +
|
|
331
|
+
"event store (with occurrence counts, most recently seen first) and events referenced as code-journey or blueprint triggers. " +
|
|
332
|
+
"Any other event name is also valid — it just hasn't been seen yet. Prefer a listed name over inventing a near-duplicate.",
|
|
333
|
+
inputSchema: listEventsInputSchema,
|
|
334
|
+
run: async ({ search, limit }) => {
|
|
335
|
+
type EventEntry = {
|
|
336
|
+
name: string;
|
|
337
|
+
occurrences: number;
|
|
338
|
+
lastSeenAt: string | null;
|
|
339
|
+
usedBy: string[];
|
|
340
|
+
};
|
|
341
|
+
|
|
342
|
+
// Observed vocabulary — grouped scan of user_events, recency-first.
|
|
343
|
+
// ilike special chars are escaped so a search of "100%" matches
|
|
344
|
+
// literally instead of becoming a wildcard.
|
|
345
|
+
const escaped = search?.replace(/[\\%_]/g, (m) => `\\${m}`);
|
|
346
|
+
const lastSeen = max(userEvents.occurredAt);
|
|
347
|
+
const observed = await container.db
|
|
348
|
+
.select({
|
|
349
|
+
name: userEvents.event,
|
|
350
|
+
occurrences: count(),
|
|
351
|
+
lastSeenAt: lastSeen,
|
|
352
|
+
})
|
|
353
|
+
.from(userEvents)
|
|
354
|
+
.where(escaped ? ilike(userEvents.event, `%${escaped}%`) : undefined)
|
|
355
|
+
.groupBy(userEvents.event)
|
|
356
|
+
.orderBy(desc(lastSeen))
|
|
357
|
+
.limit(limit);
|
|
358
|
+
|
|
359
|
+
const byName = new Map<string, EventEntry>();
|
|
360
|
+
for (const row of observed) {
|
|
361
|
+
byName.set(row.name, {
|
|
362
|
+
name: row.name,
|
|
363
|
+
occurrences: Number(row.occurrences),
|
|
364
|
+
lastSeenAt: row.lastSeenAt?.toISOString() ?? null,
|
|
365
|
+
usedBy: [],
|
|
366
|
+
});
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
const matches = (name: string) =>
|
|
370
|
+
!search || name.toLowerCase().includes(search.toLowerCase());
|
|
371
|
+
const entryFor = (name: string): EventEntry => {
|
|
372
|
+
const existing = byName.get(name);
|
|
373
|
+
if (existing) return existing;
|
|
374
|
+
const created: EventEntry = {
|
|
375
|
+
name,
|
|
376
|
+
occurrences: 0,
|
|
377
|
+
lastSeenAt: null,
|
|
378
|
+
usedBy: [],
|
|
379
|
+
};
|
|
380
|
+
byName.set(name, created);
|
|
381
|
+
return created;
|
|
382
|
+
};
|
|
383
|
+
|
|
384
|
+
// Declared vocabulary — code-journey triggers (never observed rows if
|
|
385
|
+
// nothing fired yet) and blueprint triggers, labeled by consumer.
|
|
386
|
+
for (const journey of container.registry.getAll()) {
|
|
387
|
+
const event = journey.trigger?.event;
|
|
388
|
+
if (!event || !matches(event)) continue;
|
|
389
|
+
entryFor(event).usedBy.push(`journey:${journey.id}`);
|
|
390
|
+
}
|
|
391
|
+
const blueprintRows = await container.db
|
|
392
|
+
.select({
|
|
393
|
+
id: journeyBlueprints.id,
|
|
394
|
+
triggerEvent: journeyBlueprints.triggerEvent,
|
|
395
|
+
status: journeyBlueprints.status,
|
|
396
|
+
})
|
|
397
|
+
.from(journeyBlueprints);
|
|
398
|
+
for (const bp of blueprintRows) {
|
|
399
|
+
if (!matches(bp.triggerEvent)) continue;
|
|
400
|
+
entryFor(bp.triggerEvent).usedBy.push(
|
|
401
|
+
`blueprint:${bp.id} (${bp.status})`,
|
|
402
|
+
);
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
return {
|
|
406
|
+
ok: true as const,
|
|
407
|
+
note:
|
|
408
|
+
"Event names are an open vocabulary — this is observed + declared usage, not a closed registry. " +
|
|
409
|
+
"Reserved namespaces (email.*, journey.*, bucket.*, contact.*) are engine-emitted; don't use them as blueprint trigger events.",
|
|
410
|
+
events: [...byName.values()],
|
|
411
|
+
};
|
|
412
|
+
},
|
|
413
|
+
});
|
|
414
|
+
|
|
415
|
+
const enable_journey_blueprint = defineTool({
|
|
416
|
+
name: "enable_journey_blueprint",
|
|
417
|
+
description:
|
|
418
|
+
"Enable a blueprint: new matching events start enrolling on the next ingest. The stored graph is re-validated against the " +
|
|
419
|
+
"CURRENT registries first — a blueprint whose template/connector vanished since save cannot go live (fix it via " +
|
|
420
|
+
"update_journey_blueprint, guided by the returned issues). Idempotent when already enabled. A blueprint promoted to code " +
|
|
421
|
+
"cannot be re-enabled.",
|
|
422
|
+
inputSchema: idInputSchema,
|
|
423
|
+
run: async ({
|
|
424
|
+
id,
|
|
425
|
+
}): Promise<
|
|
426
|
+
ToolWriteSuccess | ToolNotFound | ToolPromoted | ToolInvalidGraph
|
|
427
|
+
> => {
|
|
428
|
+
const result = await enableBlueprint({ container, id });
|
|
429
|
+
if (!result.ok) return result;
|
|
430
|
+
return okWrite(serializeBlueprint(result.blueprint));
|
|
431
|
+
},
|
|
432
|
+
});
|
|
433
|
+
|
|
434
|
+
const disable_journey_blueprint = defineTool({
|
|
435
|
+
name: "disable_journey_blueprint",
|
|
436
|
+
description:
|
|
437
|
+
"Disable a blueprint: new enrollments stop on the next event; in-flight runs keep going to completion " +
|
|
438
|
+
"(same semantics as a code journey with enabled: false). Idempotent when already disabled.",
|
|
439
|
+
inputSchema: idInputSchema,
|
|
440
|
+
run: async ({ id }): Promise<ToolWriteSuccess | ToolNotFound> => {
|
|
441
|
+
const result = await disableBlueprint({ container, id });
|
|
442
|
+
if (!result.ok) return result;
|
|
443
|
+
return okWrite(serializeBlueprint(result.blueprint));
|
|
444
|
+
},
|
|
445
|
+
});
|
|
446
|
+
|
|
447
|
+
return {
|
|
448
|
+
create_journey_blueprint,
|
|
449
|
+
update_journey_blueprint,
|
|
450
|
+
validate_journey_blueprint,
|
|
451
|
+
list_email_templates,
|
|
452
|
+
list_events,
|
|
453
|
+
enable_journey_blueprint,
|
|
454
|
+
disable_journey_blueprint,
|
|
455
|
+
};
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
export type JourneyBlueprintTools = ReturnType<
|
|
459
|
+
typeof createJourneyBlueprintTools
|
|
460
|
+
>;
|