@hogsend/engine 0.41.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.
- package/package.json +10 -9
- package/src/index.ts +14 -0
- package/src/journeys/execute-journey-run.ts +50 -17
- package/src/journeys/journey-context.ts +32 -0
- package/src/lib/blueprint-lock.ts +21 -0
- package/src/lib/blueprints.ts +273 -46
- package/src/lib/event-names.ts +143 -0
- package/src/lib/tracking.ts +1 -5
- package/src/mcp/authoring-guide.ts +160 -0
- package/src/mcp/blueprint-tools.ts +38 -108
- package/src/middleware/require-admin.ts +13 -0
- package/src/routes/admin/api-keys.ts +72 -0
- package/src/routes/admin/blueprints.ts +94 -10
- package/src/routes/admin/events.ts +55 -0
- package/src/workflows/journey-blueprint-interpreter.ts +128 -33
|
@@ -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
|
+
`;
|
|
@@ -26,9 +26,7 @@
|
|
|
26
26
|
* down, …) still throw and are the host's problem.
|
|
27
27
|
*/
|
|
28
28
|
import type { BlueprintValidationIssue } from "@hogsend/core";
|
|
29
|
-
import { journeyBlueprints, userEvents } from "@hogsend/db";
|
|
30
29
|
import { getTemplateNames } from "@hogsend/email";
|
|
31
|
-
import { count, desc, ilike, max } from "drizzle-orm";
|
|
32
30
|
import { z } from "zod";
|
|
33
31
|
import {
|
|
34
32
|
type BlueprintServiceContainer,
|
|
@@ -43,6 +41,8 @@ import {
|
|
|
43
41
|
updateBlueprint,
|
|
44
42
|
validateBlueprintGraphForSave,
|
|
45
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
46
|
|
|
47
47
|
// ---------------------------------------------------------------------------
|
|
48
48
|
// Tool shape
|
|
@@ -118,6 +118,11 @@ type ToolNotFound = { ok: false; code: "not_found"; error: string };
|
|
|
118
118
|
type ToolConflict = { ok: false; code: "conflict"; error: string };
|
|
119
119
|
type ToolPromoted = { ok: false; code: "promoted"; error: string };
|
|
120
120
|
type ToolInFlight = { ok: false; code: "in_flight"; error: string };
|
|
121
|
+
type ToolVersionConflict = {
|
|
122
|
+
ok: false;
|
|
123
|
+
code: "version_conflict";
|
|
124
|
+
error: string;
|
|
125
|
+
};
|
|
121
126
|
type ToolInvalidGraph = {
|
|
122
127
|
ok: false;
|
|
123
128
|
code: "invalid_graph";
|
|
@@ -130,35 +135,19 @@ const okWrite = (blueprint: SerializedBlueprint): ToolWriteSuccess => ({
|
|
|
130
135
|
blueprint,
|
|
131
136
|
});
|
|
132
137
|
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
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.";
|
|
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.
|
|
154
141
|
|
|
155
142
|
// ---------------------------------------------------------------------------
|
|
156
143
|
// Input schemas
|
|
157
144
|
// ---------------------------------------------------------------------------
|
|
158
145
|
|
|
159
|
-
// `source` is
|
|
160
|
-
//
|
|
161
|
-
|
|
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 });
|
|
162
151
|
|
|
163
152
|
const updateInputSchema = blueprintPatchFieldsSchema
|
|
164
153
|
.extend({ id: z.string().min(1) })
|
|
@@ -197,9 +186,11 @@ export interface JourneyBlueprintToolsOptions {
|
|
|
197
186
|
/** The DI client (or a Pick of db/registry/templates/connectorActionRegistry). */
|
|
198
187
|
container: BlueprintServiceContainer;
|
|
199
188
|
/**
|
|
200
|
-
* Actor label stamped into `journey_blueprints.createdBy`
|
|
201
|
-
*
|
|
202
|
-
*
|
|
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.
|
|
203
194
|
*/
|
|
204
195
|
createdBy?: string;
|
|
205
196
|
}
|
|
@@ -233,7 +224,8 @@ export function createJourneyBlueprintTools(
|
|
|
233
224
|
input: {
|
|
234
225
|
...input,
|
|
235
226
|
source: "mcp",
|
|
236
|
-
createdBy
|
|
227
|
+
// Mount-bound identity always wins — `createdBy` is not a tool input.
|
|
228
|
+
createdBy: defaultCreatedBy,
|
|
237
229
|
},
|
|
238
230
|
});
|
|
239
231
|
if (!result.ok) return result;
|
|
@@ -250,6 +242,7 @@ export function createJourneyBlueprintTools(
|
|
|
250
242
|
"Metadata-only edits (name, triggerEvent, exitOn, …) don't bump and are never blocked. " +
|
|
251
243
|
"The id is immutable — graph.journeyId must equal `id`. Status cannot be set here: use enable_journey_blueprint / disable_journey_blueprint. " +
|
|
252
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. " +
|
|
253
246
|
GRAPH_FORMAT +
|
|
254
247
|
" " +
|
|
255
248
|
ISSUE_LOOP_HINT,
|
|
@@ -258,7 +251,12 @@ export function createJourneyBlueprintTools(
|
|
|
258
251
|
id,
|
|
259
252
|
...patch
|
|
260
253
|
}): Promise<
|
|
261
|
-
|
|
254
|
+
| ToolWriteSuccess
|
|
255
|
+
| ToolNotFound
|
|
256
|
+
| ToolInvalidGraph
|
|
257
|
+
| ToolInFlight
|
|
258
|
+
| ToolVersionConflict
|
|
259
|
+
| ToolPromoted
|
|
262
260
|
> => {
|
|
263
261
|
const result = await updateBlueprint({ container, id, patch });
|
|
264
262
|
if (!result.ok) return result;
|
|
@@ -332,83 +330,15 @@ export function createJourneyBlueprintTools(
|
|
|
332
330
|
"Any other event name is also valid — it just hasn't been seen yet. Prefer a listed name over inventing a near-duplicate.",
|
|
333
331
|
inputSchema: listEventsInputSchema,
|
|
334
332
|
run: async ({ search, limit }) => {
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
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
|
-
};
|
|
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 };
|
|
412
342
|
},
|
|
413
343
|
});
|
|
414
344
|
|
|
@@ -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,
|
|
@@ -20,6 +20,50 @@ const apiKeySchema = z.object({
|
|
|
20
20
|
createdAt: z.string(),
|
|
21
21
|
});
|
|
22
22
|
|
|
23
|
+
// The authenticated credential's identity, discriminated on how the request
|
|
24
|
+
// authenticated. The Bearer path echoes the key requireAdmin already resolved
|
|
25
|
+
// (id/name/scopes only — NEVER the key material); the cookie path echoes the
|
|
26
|
+
// session user.
|
|
27
|
+
const selfApiKeyActorSchema = z.object({
|
|
28
|
+
actor: z.literal("api-key"),
|
|
29
|
+
id: z.string(),
|
|
30
|
+
name: z.string(),
|
|
31
|
+
scopes: z.array(z.string()),
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
const selfSessionActorSchema = z.object({
|
|
35
|
+
actor: z.literal("session"),
|
|
36
|
+
email: z.string(),
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
const selfRoute = createRoute({
|
|
40
|
+
method: "get",
|
|
41
|
+
path: "/self",
|
|
42
|
+
tags: ["Admin — API Keys"],
|
|
43
|
+
summary: "Identify the authenticated credential",
|
|
44
|
+
description:
|
|
45
|
+
"Returns the identity this request authenticated as — the resolved API " +
|
|
46
|
+
"key (id, name, scopes; never the key material) for Bearer auth, or the " +
|
|
47
|
+
"session user's email for cookie auth.",
|
|
48
|
+
responses: {
|
|
49
|
+
200: {
|
|
50
|
+
content: {
|
|
51
|
+
"application/json": {
|
|
52
|
+
schema: z.discriminatedUnion("actor", [
|
|
53
|
+
selfApiKeyActorSchema,
|
|
54
|
+
selfSessionActorSchema,
|
|
55
|
+
]),
|
|
56
|
+
},
|
|
57
|
+
},
|
|
58
|
+
description: "The authenticated credential's identity",
|
|
59
|
+
},
|
|
60
|
+
401: {
|
|
61
|
+
content: { "application/json": { schema: errorSchema } },
|
|
62
|
+
description: "No resolved credential on the request",
|
|
63
|
+
},
|
|
64
|
+
},
|
|
65
|
+
});
|
|
66
|
+
|
|
23
67
|
const listRoute = createRoute({
|
|
24
68
|
method: "get",
|
|
25
69
|
path: "/",
|
|
@@ -152,6 +196,34 @@ function serializeKey(row: typeof apiKeys.$inferSelect) {
|
|
|
152
196
|
}
|
|
153
197
|
|
|
154
198
|
export const apiKeysRouter = new OpenAPIHono<AppEnv>()
|
|
199
|
+
// Registered before any param route so a literal "self" can never be
|
|
200
|
+
// captured as an {id}.
|
|
201
|
+
.openapi(selfRoute, (c) => {
|
|
202
|
+
const apiKey = c.get("apiKey");
|
|
203
|
+
if (apiKey) {
|
|
204
|
+
return c.json(
|
|
205
|
+
{
|
|
206
|
+
actor: "api-key" as const,
|
|
207
|
+
id: apiKey.id,
|
|
208
|
+
name: apiKey.name,
|
|
209
|
+
scopes: apiKey.scopes,
|
|
210
|
+
},
|
|
211
|
+
200,
|
|
212
|
+
);
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
const sessionUser = c.get("user");
|
|
216
|
+
if (sessionUser) {
|
|
217
|
+
return c.json(
|
|
218
|
+
{ actor: "session" as const, email: sessionUser.email },
|
|
219
|
+
200,
|
|
220
|
+
);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// requireAdmin always resolves one of the two before this handler runs —
|
|
224
|
+
// defensive fallback only.
|
|
225
|
+
return c.json({ error: "Unauthorized" }, 401);
|
|
226
|
+
})
|
|
155
227
|
.openapi(listRoute, async (c) => {
|
|
156
228
|
const { db } = c.get("container");
|
|
157
229
|
const { limit, offset, includeRevoked } = c.req.valid("query");
|
|
@@ -13,7 +13,8 @@
|
|
|
13
13
|
* Result → status mapping (uniform across handlers):
|
|
14
14
|
* - `invalid_graph` → 422 with the structured `BlueprintValidationIssue[]`
|
|
15
15
|
* verbatim (never a caught exception message)
|
|
16
|
-
* - `not_found` → 404, `conflict`/`promoted`/`in_flight`
|
|
16
|
+
* - `not_found` → 404, `conflict`/`promoted`/`already_promoted`/`in_flight`
|
|
17
|
+
* → 409
|
|
17
18
|
*
|
|
18
19
|
* A graph-changing update is REJECTED (`in_flight` → 409) while the
|
|
19
20
|
* blueprint has any active/waiting `journeyStates` rows — Hatchet's durable
|
|
@@ -40,6 +41,7 @@ import {
|
|
|
40
41
|
disableBlueprint,
|
|
41
42
|
enableBlueprint,
|
|
42
43
|
findBlueprintRow,
|
|
44
|
+
promoteBlueprint,
|
|
43
45
|
serializeBlueprint,
|
|
44
46
|
serializedBlueprintSchema,
|
|
45
47
|
updateBlueprint,
|
|
@@ -77,6 +79,24 @@ const invalidGraphSchema = z.object({
|
|
|
77
79
|
issues: z.array(validationIssueSchema),
|
|
78
80
|
});
|
|
79
81
|
|
|
82
|
+
/**
|
|
83
|
+
* 409 body: the neutral error message PLUS the machine-readable service `code`
|
|
84
|
+
* (`conflict` | `in_flight` | `promoted` | `already_promoted` |
|
|
85
|
+
* `version_conflict`). A programmatic caller (e.g. `@hogsend/mcp`) branches on
|
|
86
|
+
* `code` instead of sniffing the message. `error` stays present and unchanged
|
|
87
|
+
* for existing consumers.
|
|
88
|
+
*/
|
|
89
|
+
const conflictSchema = z.object({
|
|
90
|
+
error: z.string(),
|
|
91
|
+
code: z.enum([
|
|
92
|
+
"conflict",
|
|
93
|
+
"in_flight",
|
|
94
|
+
"promoted",
|
|
95
|
+
"already_promoted",
|
|
96
|
+
"version_conflict",
|
|
97
|
+
]),
|
|
98
|
+
});
|
|
99
|
+
|
|
80
100
|
/** The dry-run validate report — 200 either way (a failed validation is a
|
|
81
101
|
* successful validation CALL; this is the agent's iterate-in-a-loop surface). */
|
|
82
102
|
const validationReportSchema = z.object({
|
|
@@ -173,7 +193,7 @@ const createRouteDef = createRoute({
|
|
|
173
193
|
description: "Blueprint created",
|
|
174
194
|
},
|
|
175
195
|
409: {
|
|
176
|
-
content: { "application/json": { schema:
|
|
196
|
+
content: { "application/json": { schema: conflictSchema } },
|
|
177
197
|
description:
|
|
178
198
|
"Blueprint id already exists, or collides with a registered code journey",
|
|
179
199
|
},
|
|
@@ -247,7 +267,9 @@ const patchRouteDef = createRoute({
|
|
|
247
267
|
"blueprint has any active/waiting enrollment, since a graph edit can " +
|
|
248
268
|
"desync Hatchet's replay journal for a run suspended mid-graph. " +
|
|
249
269
|
"Metadata-only edits do not bump and are never blocked. Status " +
|
|
250
|
-
"transitions go through /enable and /disable, not PATCH."
|
|
270
|
+
"transitions go through /enable and /disable, not PATCH. A blueprint " +
|
|
271
|
+
"promoted to code (see /promote) is frozen and rejects every update " +
|
|
272
|
+
"(409) — the code journey is the source of truth.",
|
|
251
273
|
request: {
|
|
252
274
|
params: z.object({ id: z.string() }),
|
|
253
275
|
body: {
|
|
@@ -268,9 +290,11 @@ const patchRouteDef = createRoute({
|
|
|
268
290
|
description: "Blueprint not found",
|
|
269
291
|
},
|
|
270
292
|
409: {
|
|
271
|
-
content: { "application/json": { schema:
|
|
293
|
+
content: { "application/json": { schema: conflictSchema } },
|
|
272
294
|
description:
|
|
273
|
-
"Graph change rejected — the blueprint has active/waiting
|
|
295
|
+
"Graph change rejected — the blueprint has active/waiting " +
|
|
296
|
+
"enrollments, was promoted to code, or was edited concurrently " +
|
|
297
|
+
"(version conflict — re-read and retry)",
|
|
274
298
|
},
|
|
275
299
|
422: {
|
|
276
300
|
content: { "application/json": { schema: invalidGraphSchema } },
|
|
@@ -330,7 +354,7 @@ const enableRouteDef = createRoute({
|
|
|
330
354
|
description: "Blueprint not found",
|
|
331
355
|
},
|
|
332
356
|
409: {
|
|
333
|
-
content: { "application/json": { schema:
|
|
357
|
+
content: { "application/json": { schema: conflictSchema } },
|
|
334
358
|
description:
|
|
335
359
|
"Blueprint was promoted to code — the code journey is the source of truth",
|
|
336
360
|
},
|
|
@@ -369,6 +393,47 @@ const disableRouteDef = createRoute({
|
|
|
369
393
|
},
|
|
370
394
|
});
|
|
371
395
|
|
|
396
|
+
const promoteRouteDef = createRoute({
|
|
397
|
+
method: "post",
|
|
398
|
+
path: "/{id}/promote",
|
|
399
|
+
tags: ["Admin — Blueprints"],
|
|
400
|
+
summary: "Mark a blueprint as promoted to a code journey",
|
|
401
|
+
description:
|
|
402
|
+
"Records that a generated code journey is now the source of truth " +
|
|
403
|
+
"(spec §11): stamps `promotedAt`/`promotedToJourneyId` and disables the " +
|
|
404
|
+
"blueprint in one update. A promoted blueprint can never be re-enabled. " +
|
|
405
|
+
"This is ONLY the DB state transition — codegen (blueprint → " +
|
|
406
|
+
"`defineJourney()` file) happens in the CLI, not here.",
|
|
407
|
+
request: {
|
|
408
|
+
params: z.object({ id: z.string() }),
|
|
409
|
+
body: {
|
|
410
|
+
content: {
|
|
411
|
+
"application/json": {
|
|
412
|
+
schema: z.object({ journeyId: z.string().min(1) }),
|
|
413
|
+
},
|
|
414
|
+
},
|
|
415
|
+
},
|
|
416
|
+
},
|
|
417
|
+
responses: {
|
|
418
|
+
200: {
|
|
419
|
+
content: {
|
|
420
|
+
"application/json": {
|
|
421
|
+
schema: z.object({ blueprint: blueprintSchema }),
|
|
422
|
+
},
|
|
423
|
+
},
|
|
424
|
+
description: "Blueprint promoted and disabled",
|
|
425
|
+
},
|
|
426
|
+
404: {
|
|
427
|
+
content: { "application/json": { schema: errorSchema } },
|
|
428
|
+
description: "Blueprint not found",
|
|
429
|
+
},
|
|
430
|
+
409: {
|
|
431
|
+
content: { "application/json": { schema: conflictSchema } },
|
|
432
|
+
description: "Blueprint was already promoted",
|
|
433
|
+
},
|
|
434
|
+
},
|
|
435
|
+
});
|
|
436
|
+
|
|
372
437
|
// Byte-identical response shape to GET /v1/admin/journeys/{id}/graph — the
|
|
373
438
|
// SAME Studio flow-view component renders either without modification
|
|
374
439
|
// (spec §3/§9). `templateKey` needs no resolution cascade here: a blueprint
|
|
@@ -496,7 +561,7 @@ blueprintsRouter.openapi(createRouteDef, async (c) => {
|
|
|
496
561
|
if (result.code === "invalid_graph") {
|
|
497
562
|
return c.json({ error: result.error, issues: result.issues }, 422);
|
|
498
563
|
}
|
|
499
|
-
return c.json({ error: result.error }, 409);
|
|
564
|
+
return c.json({ error: result.error, code: result.code }, 409);
|
|
500
565
|
}
|
|
501
566
|
return c.json({ blueprint: serializeBlueprint(result.blueprint) }, 201);
|
|
502
567
|
});
|
|
@@ -568,8 +633,12 @@ blueprintsRouter.openapi(patchRouteDef, async (c) => {
|
|
|
568
633
|
if (result.code === "invalid_graph") {
|
|
569
634
|
return c.json({ error: result.error, issues: result.issues }, 422);
|
|
570
635
|
}
|
|
571
|
-
if (
|
|
572
|
-
|
|
636
|
+
if (
|
|
637
|
+
result.code === "in_flight" ||
|
|
638
|
+
result.code === "promoted" ||
|
|
639
|
+
result.code === "version_conflict"
|
|
640
|
+
) {
|
|
641
|
+
return c.json({ error: result.error, code: result.code }, 409);
|
|
573
642
|
}
|
|
574
643
|
return c.json({ error: result.error }, 404);
|
|
575
644
|
}
|
|
@@ -604,7 +673,7 @@ blueprintsRouter.openapi(enableRouteDef, async (c) => {
|
|
|
604
673
|
return c.json({ error: result.error, issues: result.issues }, 422);
|
|
605
674
|
}
|
|
606
675
|
if (result.code === "promoted") {
|
|
607
|
-
return c.json({ error: result.error }, 409);
|
|
676
|
+
return c.json({ error: result.error, code: result.code }, 409);
|
|
608
677
|
}
|
|
609
678
|
return c.json({ error: result.error }, 404);
|
|
610
679
|
}
|
|
@@ -622,6 +691,21 @@ blueprintsRouter.openapi(disableRouteDef, async (c) => {
|
|
|
622
691
|
return c.json({ blueprint: serializeBlueprint(result.blueprint) }, 200);
|
|
623
692
|
});
|
|
624
693
|
|
|
694
|
+
blueprintsRouter.openapi(promoteRouteDef, async (c) => {
|
|
695
|
+
const container = c.get("container");
|
|
696
|
+
const { id } = c.req.valid("param");
|
|
697
|
+
const { journeyId } = c.req.valid("json");
|
|
698
|
+
|
|
699
|
+
const result = await promoteBlueprint({ container, id, journeyId });
|
|
700
|
+
if (!result.ok) {
|
|
701
|
+
if (result.code === "already_promoted") {
|
|
702
|
+
return c.json({ error: result.error, code: result.code }, 409);
|
|
703
|
+
}
|
|
704
|
+
return c.json({ error: result.error }, 404);
|
|
705
|
+
}
|
|
706
|
+
return c.json({ blueprint: serializeBlueprint(result.blueprint) }, 200);
|
|
707
|
+
});
|
|
708
|
+
|
|
625
709
|
blueprintsRouter.openapi(graphRouteDef, async (c) => {
|
|
626
710
|
const { db, templates } = c.get("container");
|
|
627
711
|
const { id } = c.req.valid("param");
|