@promptowl/contextnest-community 1.9.0 → 1.10.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/CONFIGURATION.md +29 -2
- package/dist/{chunk-TIO5XOFD.js → chunk-7PQREKSM.js} +1 -1
- package/dist/{chunk-DPHV6Q26.js → chunk-BC6KFUZH.js} +205 -22
- package/dist/{chunk-BYS4HDME.js → chunk-KFGZIECB.js} +73 -26
- package/dist/{chunk-HRQWNRVI.js → chunk-UHUU3VAK.js} +1 -1
- package/dist/{chunk-VC3QNHHB.js → chunk-ZM4F7MY7.js} +685 -6
- package/dist/{client-GI74NPIW.js → client-VZLX4THW.js} +1 -1
- package/dist/{grants-service-MDLRPMZR.js → grants-service-6H4WUA2F.js} +2 -2
- package/dist/index.js +1953 -521
- package/dist/{migrations.postgres-ORSV7UFJ.js → migrations.postgres-4XYY3CTF.js} +100 -2
- package/dist/{review-service-A3XFQTJH.js → review-service-VLSUT6KK.js} +5 -4
- package/dist/{stewardship-service-3KCVVXCW.js → stewardship-service-D5PDWXBR.js} +2 -2
- package/dist/{version-service-6J4OWQL6.js → version-service-A2YAKYQW.js} +2 -2
- package/dist/web3/assets/index-B2PkvzmY.js +1007 -0
- package/dist/web3/assets/index-C-tX933G.css +1 -0
- package/dist/web3/index.html +2 -2
- package/package.json +3 -2
- package/dist/web3/assets/index-CHavHPIT.css +0 -1
- package/dist/web3/assets/index-DyvOBH92.js +0 -934
|
@@ -1,14 +1,29 @@
|
|
|
1
|
+
import {
|
|
2
|
+
grantCoversNode,
|
|
3
|
+
listUserGrants,
|
|
4
|
+
resolveNodeGrant
|
|
5
|
+
} from "./chunk-7PQREKSM.js";
|
|
1
6
|
import {
|
|
2
7
|
createVersion,
|
|
8
|
+
getApprovedVersion,
|
|
3
9
|
setApprovedVersion
|
|
4
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-UHUU3VAK.js";
|
|
5
11
|
import {
|
|
6
12
|
buildDocContext,
|
|
7
13
|
buildTitleMap,
|
|
14
|
+
canUserAccess,
|
|
8
15
|
canUserApprove,
|
|
16
|
+
describeNode,
|
|
9
17
|
engineCache,
|
|
18
|
+
isPublicReader,
|
|
19
|
+
isStewardshipEnabled,
|
|
10
20
|
resolveStewardsForNode
|
|
11
|
-
} from "./chunk-
|
|
21
|
+
} from "./chunk-KFGZIECB.js";
|
|
22
|
+
import {
|
|
23
|
+
ConflictError,
|
|
24
|
+
NotFoundError,
|
|
25
|
+
ValidationError
|
|
26
|
+
} from "./chunk-3JTODC3Y.js";
|
|
12
27
|
import {
|
|
13
28
|
insertOrReplace,
|
|
14
29
|
nowExpr
|
|
@@ -16,10 +31,593 @@ import {
|
|
|
16
31
|
import {
|
|
17
32
|
config,
|
|
18
33
|
getDb
|
|
19
|
-
} from "./chunk-
|
|
34
|
+
} from "./chunk-BC6KFUZH.js";
|
|
20
35
|
|
|
21
36
|
// src/governance/review-service.ts
|
|
37
|
+
import { v4 as uuid3 } from "uuid";
|
|
38
|
+
|
|
39
|
+
// src/governance/notify-service.ts
|
|
22
40
|
import { v4 as uuid } from "uuid";
|
|
41
|
+
async function listWatchers(nestId, nodeId) {
|
|
42
|
+
return await getDb().all(
|
|
43
|
+
`SELECT id, node_id, user_email, created_by, created_at
|
|
44
|
+
FROM watchers WHERE nest_id = ? AND node_id = ? ORDER BY created_at`,
|
|
45
|
+
[nestId, nodeId]
|
|
46
|
+
);
|
|
47
|
+
}
|
|
48
|
+
async function addWatcher(nestId, nodeId, userEmail, createdBy) {
|
|
49
|
+
await getDb().run(
|
|
50
|
+
`INSERT INTO watchers (id, nest_id, node_id, user_email, created_by, created_at)
|
|
51
|
+
VALUES (?, ?, ?, ?, ?, ?)
|
|
52
|
+
ON CONFLICT(nest_id, node_id, user_email) DO NOTHING`,
|
|
53
|
+
[uuid(), nestId, nodeId, userEmail.toLowerCase(), createdBy, (/* @__PURE__ */ new Date()).toISOString()]
|
|
54
|
+
);
|
|
55
|
+
}
|
|
56
|
+
async function removeWatcher(nestId, nodeId, userEmail) {
|
|
57
|
+
const db = getDb();
|
|
58
|
+
const row = await db.get(
|
|
59
|
+
"SELECT id FROM watchers WHERE nest_id = ? AND node_id = ? AND LOWER(user_email) = LOWER(?)",
|
|
60
|
+
[nestId, nodeId, userEmail]
|
|
61
|
+
);
|
|
62
|
+
if (!row) return false;
|
|
63
|
+
await db.run("DELETE FROM watchers WHERE id = ?", [row.id]);
|
|
64
|
+
return true;
|
|
65
|
+
}
|
|
66
|
+
async function notifyReviewRequested(params) {
|
|
67
|
+
const { nestId, nodeId, requestedBy, reviewId } = params;
|
|
68
|
+
const db = getDb();
|
|
69
|
+
try {
|
|
70
|
+
const rows = await db.all(
|
|
71
|
+
`SELECT DISTINCT w.user_email, w.node_id AS via
|
|
72
|
+
FROM watchers w
|
|
73
|
+
WHERE w.nest_id = ?
|
|
74
|
+
AND (w.node_id = ?
|
|
75
|
+
OR w.node_id IN (
|
|
76
|
+
SELECT e.from_node FROM edges e
|
|
77
|
+
JOIN edge_types t ON t.id = e.type_id
|
|
78
|
+
WHERE e.nest_id = ? AND e.to_node = ? AND t.is_flow = 1
|
|
79
|
+
))`,
|
|
80
|
+
[nestId, nodeId, nestId, nodeId]
|
|
81
|
+
);
|
|
82
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
83
|
+
let created = 0;
|
|
84
|
+
for (const r of rows) {
|
|
85
|
+
if (r.user_email.toLowerCase() === requestedBy.toLowerCase()) continue;
|
|
86
|
+
await db.run(
|
|
87
|
+
`INSERT INTO notifications (id, nest_id, user_email, kind, subject_id, message, created_at)
|
|
88
|
+
VALUES (?, ?, ?, 'review_requested', ?, ?, ?)`,
|
|
89
|
+
[
|
|
90
|
+
uuid(),
|
|
91
|
+
nestId,
|
|
92
|
+
r.user_email.toLowerCase(),
|
|
93
|
+
reviewId,
|
|
94
|
+
r.via === nodeId ? `"${nodeId}" has a new version awaiting review (submitted by ${requestedBy})` : `Agent "${r.via}" produced output on "${nodeId}" \u2014 awaiting review`,
|
|
95
|
+
now
|
|
96
|
+
]
|
|
97
|
+
);
|
|
98
|
+
created++;
|
|
99
|
+
}
|
|
100
|
+
return created;
|
|
101
|
+
} catch (err) {
|
|
102
|
+
console.error("[notify] review fan-out failed", nestId, nodeId, err);
|
|
103
|
+
return 0;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
async function notifyReviewResolved(params) {
|
|
107
|
+
const { nestId, nodeId, status, resolvedBy, requestedBy, reviewId } = params;
|
|
108
|
+
const db = getDb();
|
|
109
|
+
try {
|
|
110
|
+
const rows = await db.all(
|
|
111
|
+
`SELECT DISTINCT w.user_email
|
|
112
|
+
FROM watchers w
|
|
113
|
+
WHERE w.nest_id = ?
|
|
114
|
+
AND (w.node_id = ?
|
|
115
|
+
OR w.node_id IN (
|
|
116
|
+
SELECT e.from_node FROM edges e
|
|
117
|
+
JOIN edge_types t ON t.id = e.type_id
|
|
118
|
+
WHERE e.nest_id = ? AND e.to_node = ? AND t.is_flow = 1
|
|
119
|
+
))`,
|
|
120
|
+
[nestId, nodeId, nestId, nodeId]
|
|
121
|
+
);
|
|
122
|
+
const recipients = new Set(rows.map((r) => r.user_email.toLowerCase()));
|
|
123
|
+
recipients.add(requestedBy.toLowerCase());
|
|
124
|
+
recipients.delete(resolvedBy.toLowerCase());
|
|
125
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
126
|
+
let created = 0;
|
|
127
|
+
for (const email of recipients) {
|
|
128
|
+
await db.run(
|
|
129
|
+
`INSERT INTO notifications (id, nest_id, user_email, kind, subject_id, message, created_at)
|
|
130
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
|
131
|
+
[
|
|
132
|
+
uuid(),
|
|
133
|
+
nestId,
|
|
134
|
+
email,
|
|
135
|
+
`review_${status}`,
|
|
136
|
+
reviewId,
|
|
137
|
+
`"${nodeId}" was ${status} by ${resolvedBy}`,
|
|
138
|
+
now
|
|
139
|
+
]
|
|
140
|
+
);
|
|
141
|
+
created++;
|
|
142
|
+
}
|
|
143
|
+
return created;
|
|
144
|
+
} catch (err) {
|
|
145
|
+
console.error("[notify] resolution fan-out failed", nestId, nodeId, err);
|
|
146
|
+
return 0;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
async function listNotifications(userEmail, opts = {}) {
|
|
150
|
+
const limit = Math.min(opts.limit ?? 50, 200);
|
|
151
|
+
return await getDb().all(
|
|
152
|
+
`SELECT id, nest_id, kind, subject_id, message, created_at, read_at
|
|
153
|
+
FROM notifications
|
|
154
|
+
WHERE LOWER(user_email) = LOWER(?)${opts.unreadOnly ? " AND read_at IS NULL" : ""}
|
|
155
|
+
ORDER BY created_at DESC LIMIT ${limit}`,
|
|
156
|
+
[userEmail]
|
|
157
|
+
);
|
|
158
|
+
}
|
|
159
|
+
async function markNotificationsRead(userEmail, ids) {
|
|
160
|
+
const db = getDb();
|
|
161
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
162
|
+
if (ids === "all") {
|
|
163
|
+
await db.run(
|
|
164
|
+
"UPDATE notifications SET read_at = ? WHERE LOWER(user_email) = LOWER(?) AND read_at IS NULL",
|
|
165
|
+
[now, userEmail]
|
|
166
|
+
);
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
for (const id of ids.slice(0, 200)) {
|
|
170
|
+
await db.run(
|
|
171
|
+
"UPDATE notifications SET read_at = ? WHERE id = ? AND LOWER(user_email) = LOWER(?)",
|
|
172
|
+
[now, id, userEmail]
|
|
173
|
+
);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// src/workflow/env-routes.ts
|
|
178
|
+
import { Hono as Hono2 } from "hono";
|
|
179
|
+
|
|
180
|
+
// src/governance/access-guard.ts
|
|
181
|
+
async function resolveCallerEmail(userId) {
|
|
182
|
+
if (!userId) return "admin@localhost";
|
|
183
|
+
const db = getDb();
|
|
184
|
+
const row = await db.get(
|
|
185
|
+
"SELECT email FROM users WHERE id = ?",
|
|
186
|
+
[userId]
|
|
187
|
+
);
|
|
188
|
+
return row?.email || "admin@localhost";
|
|
189
|
+
}
|
|
190
|
+
async function canReadNode(nestId, nodeId, userId, userEmail) {
|
|
191
|
+
if (await isPublicReader(nestId, userId)) {
|
|
192
|
+
return await getApprovedVersion(nestId, nodeId) !== null;
|
|
193
|
+
}
|
|
194
|
+
if (!await isStewardshipEnabled(nestId)) return true;
|
|
195
|
+
if ((await canUserAccess(nestId, nodeId, userEmail)).allowed) return true;
|
|
196
|
+
return await resolveNodeGrant(nestId, userId, nodeId) !== null;
|
|
197
|
+
}
|
|
198
|
+
async function filterAccessible(nestId, userId, userEmail, nodes) {
|
|
199
|
+
if (await isPublicReader(nestId, userId)) {
|
|
200
|
+
const filtered = [];
|
|
201
|
+
for (const n of nodes) {
|
|
202
|
+
if (await getApprovedVersion(nestId, n.id) !== null) {
|
|
203
|
+
filtered.push(n);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
return filtered;
|
|
207
|
+
}
|
|
208
|
+
if (!await isStewardshipEnabled(nestId)) return nodes;
|
|
209
|
+
const grants = await listUserGrants(nestId, userId);
|
|
210
|
+
const accessible = [];
|
|
211
|
+
for (const n of nodes) {
|
|
212
|
+
if ((await canUserAccess(nestId, n.id, userEmail)).allowed || grantCoversNode(grants, n.id)) {
|
|
213
|
+
accessible.push(n);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
return accessible;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// src/workflow/edge-type-routes.ts
|
|
220
|
+
import { Hono } from "hono";
|
|
221
|
+
import { v4 as uuid2 } from "uuid";
|
|
222
|
+
|
|
223
|
+
// src/shared/json.ts
|
|
224
|
+
var safeJson = (s) => {
|
|
225
|
+
if (!s) return null;
|
|
226
|
+
try {
|
|
227
|
+
return JSON.parse(s);
|
|
228
|
+
} catch {
|
|
229
|
+
return null;
|
|
230
|
+
}
|
|
231
|
+
};
|
|
232
|
+
|
|
233
|
+
// src/workflow/flow-graph.ts
|
|
234
|
+
async function assertFlowGraphAcyclic(nestId, extraFlowTypeId) {
|
|
235
|
+
const db = getDb();
|
|
236
|
+
const rows = await db.all(
|
|
237
|
+
`SELECT e.from_node, e.to_node FROM edges e
|
|
238
|
+
JOIN edge_types t ON t.id = e.type_id
|
|
239
|
+
WHERE e.nest_id = ? AND (t.is_flow = 1 OR t.id = ?)`,
|
|
240
|
+
[nestId, extraFlowTypeId ?? ""]
|
|
241
|
+
);
|
|
242
|
+
const adj = /* @__PURE__ */ new Map();
|
|
243
|
+
const indeg = /* @__PURE__ */ new Map();
|
|
244
|
+
const nodes = /* @__PURE__ */ new Set();
|
|
245
|
+
for (const r of rows) {
|
|
246
|
+
if (r.from_node === r.to_node) {
|
|
247
|
+
throw new ConflictError(
|
|
248
|
+
`cycle: ["${r.from_node}"] \u2014 a flow edge cannot be a self-loop`
|
|
249
|
+
);
|
|
250
|
+
}
|
|
251
|
+
nodes.add(r.from_node);
|
|
252
|
+
nodes.add(r.to_node);
|
|
253
|
+
(adj.get(r.from_node) ?? adj.set(r.from_node, []).get(r.from_node)).push(
|
|
254
|
+
r.to_node
|
|
255
|
+
);
|
|
256
|
+
indeg.set(r.to_node, (indeg.get(r.to_node) ?? 0) + 1);
|
|
257
|
+
if (!indeg.has(r.from_node)) indeg.set(r.from_node, 0);
|
|
258
|
+
}
|
|
259
|
+
const queue = [...nodes].filter((n) => (indeg.get(n) ?? 0) === 0);
|
|
260
|
+
let removed = 0;
|
|
261
|
+
while (queue.length) {
|
|
262
|
+
const cur = queue.shift();
|
|
263
|
+
removed++;
|
|
264
|
+
for (const nb of adj.get(cur) ?? []) {
|
|
265
|
+
indeg.set(nb, (indeg.get(nb) ?? 0) - 1);
|
|
266
|
+
if ((indeg.get(nb) ?? 0) === 0) queue.push(nb);
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
if (removed < nodes.size) {
|
|
270
|
+
throw new ConflictError(
|
|
271
|
+
"cycle: enabling flow on this edge type would create a cycle in the flow graph \u2014 flow edges must form a DAG"
|
|
272
|
+
);
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
// src/workflow/edge-type-routes.ts
|
|
277
|
+
var requireWorkflowPlane = async (c, next) => {
|
|
278
|
+
if (!config.FEATURE_WORKFLOW_PLANE) {
|
|
279
|
+
return c.json(
|
|
280
|
+
{
|
|
281
|
+
error: "The workflow plane is not enabled on this server. An admin can turn it on with FEATURE_WORKFLOW_PLANE=true."
|
|
282
|
+
},
|
|
283
|
+
404
|
|
284
|
+
);
|
|
285
|
+
}
|
|
286
|
+
return next();
|
|
287
|
+
};
|
|
288
|
+
async function seedDefaultEdgeTypes(nestId) {
|
|
289
|
+
const db = getDb();
|
|
290
|
+
const existing = await db.get(
|
|
291
|
+
"SELECT COUNT(*) as c FROM edge_types WHERE nest_id = ?",
|
|
292
|
+
[nestId]
|
|
293
|
+
);
|
|
294
|
+
if (existing.c > 0) return;
|
|
295
|
+
const owner = await db.get(
|
|
296
|
+
"SELECT u.email FROM nests n JOIN users u ON u.id = n.user_id WHERE n.id = ?",
|
|
297
|
+
[nestId]
|
|
298
|
+
);
|
|
299
|
+
const createdBy = owner?.email ?? "admin@localhost";
|
|
300
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
301
|
+
const defaults = [
|
|
302
|
+
["next", "Unconditional flow: after the source completes, run the target.", 1, "#16a34a"],
|
|
303
|
+
["on-success", "Follow only when the source step succeeded.", 1, "#16a34a"],
|
|
304
|
+
["on-failure", "Follow only when the source step failed.", 1, "#ef4444"],
|
|
305
|
+
["depends-on", "The source requires the target (ordering/lineage; not conditional flow).", 0, "#3b82f6"],
|
|
306
|
+
["owned-by", "Ownership: the target person/team is accountable for the source node.", 0, "#64748b"]
|
|
307
|
+
];
|
|
308
|
+
for (const [name, description, isFlow, color] of defaults) {
|
|
309
|
+
await db.run(
|
|
310
|
+
`INSERT INTO edge_types
|
|
311
|
+
(id, nest_id, name, description, direction, is_flow, condition_schema, color, created_by, created_at, updated_at)
|
|
312
|
+
VALUES (?, ?, ?, ?, 'directed', ?, NULL, ?, ?, ?, ?)
|
|
313
|
+
ON CONFLICT DO NOTHING`,
|
|
314
|
+
[uuid2(), nestId, name, description, isFlow, color, createdBy, now, now]
|
|
315
|
+
);
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
function parseConditionSchema(raw) {
|
|
319
|
+
if (raw === void 0 || raw === null || raw === "") return null;
|
|
320
|
+
const obj = typeof raw === "string" ? safeJson(raw) : raw;
|
|
321
|
+
if (!obj || typeof obj !== "object" || !Array.isArray(obj.params) || !obj.params.every((p) => typeof p === "string")) {
|
|
322
|
+
throw new ValidationError(
|
|
323
|
+
'condition_schema must be {"params": [string\u2026], "mode_default"?: "structured"|"nl"|"open"}'
|
|
324
|
+
);
|
|
325
|
+
}
|
|
326
|
+
const mode = obj.mode_default;
|
|
327
|
+
if (mode !== void 0 && !["structured", "nl", "open"].includes(mode)) {
|
|
328
|
+
throw new ValidationError(
|
|
329
|
+
"condition_schema.mode_default must be structured | nl | open"
|
|
330
|
+
);
|
|
331
|
+
}
|
|
332
|
+
return JSON.stringify({ params: obj.params, mode_default: mode ?? "structured" });
|
|
333
|
+
}
|
|
334
|
+
var edgeTypeToResponse = (r) => ({
|
|
335
|
+
...r,
|
|
336
|
+
is_flow: !!r.is_flow,
|
|
337
|
+
condition_schema: r.condition_schema ? safeJson(r.condition_schema) : null
|
|
338
|
+
});
|
|
339
|
+
var edgeTypeRoutes = new Hono();
|
|
340
|
+
edgeTypeRoutes.get("/", requireWorkflowPlane, async (c) => {
|
|
341
|
+
const nestId = c.req.param("nestId");
|
|
342
|
+
await seedDefaultEdgeTypes(nestId);
|
|
343
|
+
const rows = await getDb().all(
|
|
344
|
+
"SELECT * FROM edge_types WHERE nest_id = ? ORDER BY LOWER(name)",
|
|
345
|
+
[nestId]
|
|
346
|
+
);
|
|
347
|
+
return c.json({ count: rows.length, edge_types: rows.map(edgeTypeToResponse) });
|
|
348
|
+
});
|
|
349
|
+
edgeTypeRoutes.post("/", requireWorkflowPlane, async (c) => {
|
|
350
|
+
const nestId = c.req.param("nestId");
|
|
351
|
+
const body = await c.req.json();
|
|
352
|
+
if (typeof body.name !== "string" || !body.name.trim()) {
|
|
353
|
+
throw new ValidationError("name is required");
|
|
354
|
+
}
|
|
355
|
+
if (typeof body.description !== "string" || !body.description.trim()) {
|
|
356
|
+
throw new ValidationError("description (the articulation) is required");
|
|
357
|
+
}
|
|
358
|
+
const name = body.name.trim();
|
|
359
|
+
if (name.length > 100 || !/^[a-z0-9][a-z0-9-]*$/i.test(name)) {
|
|
360
|
+
throw new ValidationError(
|
|
361
|
+
"name must be alphanumeric-with-dashes, 100 chars max (e.g. escalates-when)"
|
|
362
|
+
);
|
|
363
|
+
}
|
|
364
|
+
const direction = String(body.direction ?? "directed");
|
|
365
|
+
if (!["directed", "undirected"].includes(direction)) {
|
|
366
|
+
throw new ValidationError("direction must be directed | undirected");
|
|
367
|
+
}
|
|
368
|
+
const conditionSchema = parseConditionSchema(body.condition_schema);
|
|
369
|
+
const isFlow = body.is_flow === true ? 1 : 0;
|
|
370
|
+
let color = null;
|
|
371
|
+
if (body.color !== void 0 && body.color !== null && body.color !== "") {
|
|
372
|
+
if (typeof body.color !== "string" || !/^#[0-9a-f]{6}$/i.test(body.color)) {
|
|
373
|
+
throw new ValidationError("color must be a 6-digit hex, e.g. #16a34a");
|
|
374
|
+
}
|
|
375
|
+
color = body.color;
|
|
376
|
+
}
|
|
377
|
+
const db = getDb();
|
|
378
|
+
const definedBy = await resolveCallerEmail(c.get("userId"));
|
|
379
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
380
|
+
await seedDefaultEdgeTypes(nestId);
|
|
381
|
+
let created = false;
|
|
382
|
+
await db.transaction(async (tx) => {
|
|
383
|
+
const existing = await tx.get(
|
|
384
|
+
"SELECT id, is_flow FROM edge_types WHERE nest_id = ? AND LOWER(name) = LOWER(?)",
|
|
385
|
+
[nestId, name]
|
|
386
|
+
);
|
|
387
|
+
if (existing && !existing.is_flow && isFlow) {
|
|
388
|
+
await assertFlowGraphAcyclic(nestId, existing.id);
|
|
389
|
+
}
|
|
390
|
+
if (existing) {
|
|
391
|
+
await tx.run(
|
|
392
|
+
`UPDATE edge_types SET name = ?, description = ?, direction = ?, is_flow = ?,
|
|
393
|
+
condition_schema = ?, color = ?, updated_at = ? WHERE id = ?`,
|
|
394
|
+
[name, body.description.trim(), direction, isFlow, conditionSchema, color, now, existing.id]
|
|
395
|
+
);
|
|
396
|
+
} else {
|
|
397
|
+
created = true;
|
|
398
|
+
await tx.run(
|
|
399
|
+
`INSERT INTO edge_types
|
|
400
|
+
(id, nest_id, name, description, direction, is_flow, condition_schema, color, created_by, created_at, updated_at)
|
|
401
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
402
|
+
[uuid2(), nestId, name, body.description.trim(), direction, isFlow, conditionSchema, color, definedBy, now, now]
|
|
403
|
+
);
|
|
404
|
+
}
|
|
405
|
+
});
|
|
406
|
+
const row = await db.get(
|
|
407
|
+
"SELECT * FROM edge_types WHERE nest_id = ? AND LOWER(name) = LOWER(?)",
|
|
408
|
+
[nestId, name]
|
|
409
|
+
);
|
|
410
|
+
return c.json({ edge_type: edgeTypeToResponse(row) }, created ? 201 : 200);
|
|
411
|
+
});
|
|
412
|
+
edgeTypeRoutes.delete("/:id", requireWorkflowPlane, async (c) => {
|
|
413
|
+
const nestId = c.req.param("nestId");
|
|
414
|
+
const id = c.req.param("id");
|
|
415
|
+
await getDb().transaction(async (tx) => {
|
|
416
|
+
const row = await tx.get(
|
|
417
|
+
"SELECT id FROM edge_types WHERE id = ? AND nest_id = ?",
|
|
418
|
+
[id, nestId]
|
|
419
|
+
);
|
|
420
|
+
if (!row) throw new NotFoundError("Edge type not found");
|
|
421
|
+
const inUse = await tx.get(
|
|
422
|
+
"SELECT COUNT(*) as c FROM edges WHERE type_id = ?",
|
|
423
|
+
[id]
|
|
424
|
+
);
|
|
425
|
+
if (inUse.c > 0) {
|
|
426
|
+
throw new ValidationError(
|
|
427
|
+
`Edge type is in use by ${inUse.c} edge${inUse.c === 1 ? "" : "s"} \u2014 delete those first.`
|
|
428
|
+
);
|
|
429
|
+
}
|
|
430
|
+
await tx.run("DELETE FROM edge_types WHERE id = ?", [id]);
|
|
431
|
+
});
|
|
432
|
+
return c.json({ deleted: true });
|
|
433
|
+
});
|
|
434
|
+
|
|
435
|
+
// src/workflow/env-routes.ts
|
|
436
|
+
var KEY_RE = /^[A-Z][A-Z0-9_]{0,63}$/;
|
|
437
|
+
var mask = (v) => v.length <= 4 ? "\u2022\u2022\u2022\u2022" : `\u2022\u2022\u2022\u2022${v.slice(-4)}`;
|
|
438
|
+
var envRoutes = new Hono2();
|
|
439
|
+
envRoutes.get("/", requireWorkflowPlane, async (c) => {
|
|
440
|
+
const nestId = c.req.param("nestId");
|
|
441
|
+
const rows = await getDb().all(
|
|
442
|
+
"SELECT key, value, updated_by, updated_at FROM nest_env WHERE nest_id = ? ORDER BY key",
|
|
443
|
+
[nestId]
|
|
444
|
+
);
|
|
445
|
+
return c.json({
|
|
446
|
+
count: rows.length,
|
|
447
|
+
env: rows.map((r) => ({
|
|
448
|
+
key: r.key,
|
|
449
|
+
value_masked: mask(r.value),
|
|
450
|
+
updated_by: r.updated_by,
|
|
451
|
+
updated_at: r.updated_at
|
|
452
|
+
}))
|
|
453
|
+
});
|
|
454
|
+
});
|
|
455
|
+
envRoutes.put("/", requireWorkflowPlane, async (c) => {
|
|
456
|
+
const nestId = c.req.param("nestId");
|
|
457
|
+
const body = await c.req.json();
|
|
458
|
+
const key = typeof body.key === "string" ? body.key.trim() : "";
|
|
459
|
+
if (!KEY_RE.test(key)) {
|
|
460
|
+
throw new ValidationError(
|
|
461
|
+
"key must look like an env var: A-Z, digits, underscores (e.g. SLACK_TOKEN)"
|
|
462
|
+
);
|
|
463
|
+
}
|
|
464
|
+
if (typeof body.value !== "string" || !body.value) {
|
|
465
|
+
throw new ValidationError("value is required");
|
|
466
|
+
}
|
|
467
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
468
|
+
const by = await resolveCallerEmail(c.get("userId"));
|
|
469
|
+
const db = getDb();
|
|
470
|
+
await db.run(
|
|
471
|
+
`INSERT INTO nest_env (nest_id, key, value, updated_by, updated_at)
|
|
472
|
+
VALUES (?, ?, ?, ?, ?)
|
|
473
|
+
ON CONFLICT(nest_id, key) DO UPDATE SET value = ?, updated_by = ?, updated_at = ?`,
|
|
474
|
+
[nestId, key, body.value, by, now, body.value, by, now]
|
|
475
|
+
);
|
|
476
|
+
return c.json({ key, value_masked: mask(body.value) }, 201);
|
|
477
|
+
});
|
|
478
|
+
envRoutes.delete("/:key", requireWorkflowPlane, async (c) => {
|
|
479
|
+
const nestId = c.req.param("nestId");
|
|
480
|
+
const key = c.req.param("key");
|
|
481
|
+
const db = getDb();
|
|
482
|
+
const row = await db.get(
|
|
483
|
+
"SELECT key FROM nest_env WHERE nest_id = ? AND key = ?",
|
|
484
|
+
[nestId, key]
|
|
485
|
+
);
|
|
486
|
+
if (!row) throw new NotFoundError("No such env key");
|
|
487
|
+
await db.run("DELETE FROM nest_env WHERE nest_id = ? AND key = ?", [nestId, key]);
|
|
488
|
+
return c.json({ deleted: true });
|
|
489
|
+
});
|
|
490
|
+
async function envValues(nestId) {
|
|
491
|
+
const rows = await getDb().all(
|
|
492
|
+
"SELECT key, value FROM nest_env WHERE nest_id = ?",
|
|
493
|
+
[nestId]
|
|
494
|
+
);
|
|
495
|
+
const base = {};
|
|
496
|
+
if (process.env.ANTHROPIC_API_KEY) base.ANTHROPIC_API_KEY = process.env.ANTHROPIC_API_KEY;
|
|
497
|
+
return { ...base, ...Object.fromEntries(rows.map((r) => [r.key, r.value])) };
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
// src/notify/dispatch.ts
|
|
501
|
+
function escapeMrkdwn(s) {
|
|
502
|
+
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
503
|
+
}
|
|
504
|
+
var EVENT_EMOJI = {
|
|
505
|
+
review_requested: ":memo:",
|
|
506
|
+
review_approved: ":white_check_mark:",
|
|
507
|
+
review_rejected: ":x:",
|
|
508
|
+
run_failed: ":rotating_light:"
|
|
509
|
+
};
|
|
510
|
+
function formatBody(channel, nestName, ev) {
|
|
511
|
+
const line = `[${nestName}] ${ev.message}`;
|
|
512
|
+
if (channel === "slack") {
|
|
513
|
+
return { text: escapeMrkdwn(`${EVENT_EMOJI[ev.kind] ?? ""} *[${nestName}]* ${ev.message}`) };
|
|
514
|
+
}
|
|
515
|
+
if (channel === "teams") {
|
|
516
|
+
return { text: line };
|
|
517
|
+
}
|
|
518
|
+
return {
|
|
519
|
+
kind: ev.kind,
|
|
520
|
+
nest_id: ev.nestId,
|
|
521
|
+
nest_name: nestName,
|
|
522
|
+
message: ev.message,
|
|
523
|
+
subject_id: ev.subjectId ?? null,
|
|
524
|
+
actor: ev.actor ?? null,
|
|
525
|
+
at: (/* @__PURE__ */ new Date()).toISOString()
|
|
526
|
+
};
|
|
527
|
+
}
|
|
528
|
+
function isForbiddenConnectorHost(hostname) {
|
|
529
|
+
const h = hostname.toLowerCase().replace(/^\[|\]$/g, "");
|
|
530
|
+
if (h === "localhost" || h.endsWith(".localhost") || h.endsWith(".local") || h.endsWith(".internal"))
|
|
531
|
+
return true;
|
|
532
|
+
if (h === "::1" || h === "0.0.0.0" || h.startsWith("fe80:") || h.startsWith("fc") || h.startsWith("fd"))
|
|
533
|
+
return true;
|
|
534
|
+
const m = h.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);
|
|
535
|
+
if (!m) return false;
|
|
536
|
+
const [a, b] = [Number(m[1]), Number(m[2])];
|
|
537
|
+
if (a === 127 || a === 10 || a === 0) return true;
|
|
538
|
+
if (a === 172 && b >= 16 && b <= 31) return true;
|
|
539
|
+
if (a === 192 && b === 168) return true;
|
|
540
|
+
if (a === 169 && b === 254) return true;
|
|
541
|
+
return false;
|
|
542
|
+
}
|
|
543
|
+
function isSafeConnectorUrl(raw) {
|
|
544
|
+
if (!/^https:\/\//i.test(raw)) return false;
|
|
545
|
+
try {
|
|
546
|
+
return !isForbiddenConnectorHost(new URL(raw).hostname);
|
|
547
|
+
} catch {
|
|
548
|
+
return false;
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
async function resolveUrl(nestId, raw) {
|
|
552
|
+
if (raw.startsWith("env:")) {
|
|
553
|
+
const key = raw.slice(4).trim();
|
|
554
|
+
const env = await envValues(nestId);
|
|
555
|
+
const v = env[key];
|
|
556
|
+
return v && isSafeConnectorUrl(v) ? v : null;
|
|
557
|
+
}
|
|
558
|
+
return isSafeConnectorUrl(raw) ? raw : null;
|
|
559
|
+
}
|
|
560
|
+
var warned = /* @__PURE__ */ new Set();
|
|
561
|
+
async function post(url, body, who) {
|
|
562
|
+
try {
|
|
563
|
+
const ctrl = new AbortController();
|
|
564
|
+
const timer = setTimeout(() => ctrl.abort(), 3e3);
|
|
565
|
+
try {
|
|
566
|
+
await fetch(url, {
|
|
567
|
+
method: "POST",
|
|
568
|
+
headers: { "Content-Type": "application/json" },
|
|
569
|
+
body: JSON.stringify(body),
|
|
570
|
+
signal: ctrl.signal
|
|
571
|
+
});
|
|
572
|
+
} finally {
|
|
573
|
+
clearTimeout(timer);
|
|
574
|
+
}
|
|
575
|
+
} catch (err) {
|
|
576
|
+
if (!warned.has(who)) {
|
|
577
|
+
warned.add(who);
|
|
578
|
+
console.warn(
|
|
579
|
+
`[connectors] delivery failed for ${who} (muting further warnings):`,
|
|
580
|
+
err instanceof Error ? err.message : err
|
|
581
|
+
);
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
async function dispatchEvent(ev) {
|
|
586
|
+
const db = getDb();
|
|
587
|
+
let nestName = ev.nestId;
|
|
588
|
+
try {
|
|
589
|
+
const row = await db.get("SELECT name FROM nests WHERE id = ?", [ev.nestId]);
|
|
590
|
+
if (row?.name) nestName = row.name;
|
|
591
|
+
} catch {
|
|
592
|
+
}
|
|
593
|
+
if (config.SLACK_WEBHOOK_URL) {
|
|
594
|
+
void post(
|
|
595
|
+
config.SLACK_WEBHOOK_URL,
|
|
596
|
+
formatBody("slack", nestName, ev),
|
|
597
|
+
"server-slack"
|
|
598
|
+
);
|
|
599
|
+
}
|
|
600
|
+
let rows = [];
|
|
601
|
+
try {
|
|
602
|
+
rows = await db.all(
|
|
603
|
+
"SELECT id, channel, url, events, enabled FROM connectors WHERE nest_id = ? AND enabled = 1",
|
|
604
|
+
[ev.nestId]
|
|
605
|
+
);
|
|
606
|
+
} catch {
|
|
607
|
+
return;
|
|
608
|
+
}
|
|
609
|
+
for (const r of rows) {
|
|
610
|
+
let kinds = [];
|
|
611
|
+
try {
|
|
612
|
+
kinds = JSON.parse(r.events);
|
|
613
|
+
} catch {
|
|
614
|
+
}
|
|
615
|
+
if (!kinds.includes("*") && !kinds.includes(ev.kind)) continue;
|
|
616
|
+
const url = await resolveUrl(ev.nestId, r.url);
|
|
617
|
+
if (!url) continue;
|
|
618
|
+
void post(url, formatBody(r.channel, nestName, ev), `connector:${r.id}`);
|
|
619
|
+
}
|
|
620
|
+
}
|
|
23
621
|
|
|
24
622
|
// src/notify/slack.ts
|
|
25
623
|
var warnedOnce = false;
|
|
@@ -35,7 +633,7 @@ async function notifySlackForNest(nestId, message) {
|
|
|
35
633
|
}
|
|
36
634
|
return notifySlack(`*[${nestName}]* ${message}`);
|
|
37
635
|
}
|
|
38
|
-
function
|
|
636
|
+
function escapeMrkdwn2(s) {
|
|
39
637
|
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
40
638
|
}
|
|
41
639
|
async function notifySlack(text) {
|
|
@@ -48,7 +646,7 @@ async function notifySlack(text) {
|
|
|
48
646
|
await fetch(url, {
|
|
49
647
|
method: "POST",
|
|
50
648
|
headers: { "Content-Type": "application/json" },
|
|
51
|
-
body: JSON.stringify({ text:
|
|
649
|
+
body: JSON.stringify({ text: escapeMrkdwn2(text) }),
|
|
52
650
|
signal: ctrl.signal
|
|
53
651
|
});
|
|
54
652
|
} finally {
|
|
@@ -237,6 +835,25 @@ function withTimeouts(url) {
|
|
|
237
835
|
if (missing.length === 0) return url;
|
|
238
836
|
return url + (url.includes("?") ? "&" : "?") + missing.join("&");
|
|
239
837
|
}
|
|
838
|
+
async function verifySmtp(url) {
|
|
839
|
+
let transporter = null;
|
|
840
|
+
try {
|
|
841
|
+
const nodemailer = await import("nodemailer");
|
|
842
|
+
transporter = nodemailer.default.createTransport(withTimeouts(url), {
|
|
843
|
+
disableFileAccess: true,
|
|
844
|
+
disableUrlAccess: true
|
|
845
|
+
});
|
|
846
|
+
await transporter.verify();
|
|
847
|
+
return { ok: true };
|
|
848
|
+
} catch (err) {
|
|
849
|
+
return { ok: false, error: err instanceof Error ? err.message : String(err) };
|
|
850
|
+
} finally {
|
|
851
|
+
try {
|
|
852
|
+
transporter?.close?.();
|
|
853
|
+
} catch {
|
|
854
|
+
}
|
|
855
|
+
}
|
|
856
|
+
}
|
|
240
857
|
async function getTransporter() {
|
|
241
858
|
const url = config.SMTP_URL;
|
|
242
859
|
if (!url) return null;
|
|
@@ -373,7 +990,7 @@ async function submitForReview(params) {
|
|
|
373
990
|
if (existing) {
|
|
374
991
|
throw new Error("A review is already pending for this node");
|
|
375
992
|
}
|
|
376
|
-
const id =
|
|
993
|
+
const id = uuid3();
|
|
377
994
|
await db.run(
|
|
378
995
|
`INSERT INTO review_requests
|
|
379
996
|
(id, nest_id, node_id, version, requested_by, request_note, priority)
|
|
@@ -393,6 +1010,13 @@ async function submitForReview(params) {
|
|
|
393
1010
|
[params.nestId, params.nodeId, params.version]
|
|
394
1011
|
);
|
|
395
1012
|
const reviewCtx = await buildDocContext(params.nestId, params.nodeId, params.baseUrl);
|
|
1013
|
+
void dispatchEvent({
|
|
1014
|
+
kind: "review_requested",
|
|
1015
|
+
nestId: params.nestId,
|
|
1016
|
+
subjectId: params.nodeId,
|
|
1017
|
+
actor: params.requestedBy,
|
|
1018
|
+
message: `Review requested on *${reviewCtx.label}* (v${params.version}) by ${params.requestedBy}${params.note ? ` \u2014 "${params.note}"` : ""}`
|
|
1019
|
+
});
|
|
396
1020
|
void notifyNestEvent(
|
|
397
1021
|
params.nestId,
|
|
398
1022
|
`:memo: Review requested on *${reviewCtx.label}* (v${params.version}) by ${params.requestedBy}${params.note ? ` \u2014 "${params.note}"` : ""}`,
|
|
@@ -406,6 +1030,12 @@ async function submitForReview(params) {
|
|
|
406
1030
|
note: params.note || null
|
|
407
1031
|
}
|
|
408
1032
|
);
|
|
1033
|
+
await notifyReviewRequested({
|
|
1034
|
+
nestId: params.nestId,
|
|
1035
|
+
nodeId: params.nodeId,
|
|
1036
|
+
requestedBy: params.requestedBy,
|
|
1037
|
+
reviewId: id
|
|
1038
|
+
});
|
|
409
1039
|
return await getReviewRequest(id);
|
|
410
1040
|
}
|
|
411
1041
|
async function approve(params) {
|
|
@@ -434,6 +1064,21 @@ async function approve(params) {
|
|
|
434
1064
|
WHERE id = ?`,
|
|
435
1065
|
[params.approvedBy, params.note || null, params.override ? 1 : 0, pending.id]
|
|
436
1066
|
);
|
|
1067
|
+
void dispatchEvent({
|
|
1068
|
+
kind: "review_approved",
|
|
1069
|
+
nestId: params.nestId,
|
|
1070
|
+
subjectId: params.nodeId,
|
|
1071
|
+
actor: params.approvedBy,
|
|
1072
|
+
message: `*${await describeNode(params.nestId, params.nodeId)}* v${params.version} approved by ${params.approvedBy}`
|
|
1073
|
+
});
|
|
1074
|
+
await notifyReviewResolved({
|
|
1075
|
+
nestId: params.nestId,
|
|
1076
|
+
nodeId: params.nodeId,
|
|
1077
|
+
status: "approved",
|
|
1078
|
+
resolvedBy: params.approvedBy,
|
|
1079
|
+
requestedBy: pending.requested_by,
|
|
1080
|
+
reviewId: pending.id
|
|
1081
|
+
});
|
|
437
1082
|
await db.run(
|
|
438
1083
|
"UPDATE node_versions SET status = 'published' WHERE nest_id = ? AND node_id = ? AND version = ?",
|
|
439
1084
|
[params.nestId, params.nodeId, params.version]
|
|
@@ -524,6 +1169,13 @@ async function reject(params) {
|
|
|
524
1169
|
[params.nestId, params.nodeId, params.version]
|
|
525
1170
|
);
|
|
526
1171
|
const rejectCtx = await buildDocContext(params.nestId, params.nodeId, params.baseUrl);
|
|
1172
|
+
void dispatchEvent({
|
|
1173
|
+
kind: "review_rejected",
|
|
1174
|
+
nestId: params.nestId,
|
|
1175
|
+
subjectId: params.nodeId,
|
|
1176
|
+
actor: params.rejectedBy,
|
|
1177
|
+
message: `*${rejectCtx.label}* v${params.version} rejected by ${params.rejectedBy}${params.note ? ` \u2014 "${params.note}"` : ""}`
|
|
1178
|
+
});
|
|
527
1179
|
void notifyNestEvent(
|
|
528
1180
|
params.nestId,
|
|
529
1181
|
`:x: *${rejectCtx.label}* v${params.version} rejected by ${params.rejectedBy} \u2014 "${params.note}"`,
|
|
@@ -537,6 +1189,14 @@ async function reject(params) {
|
|
|
537
1189
|
note: params.note || null
|
|
538
1190
|
}
|
|
539
1191
|
);
|
|
1192
|
+
await notifyReviewResolved({
|
|
1193
|
+
nestId: params.nestId,
|
|
1194
|
+
nodeId: params.nodeId,
|
|
1195
|
+
status: "rejected",
|
|
1196
|
+
resolvedBy: params.rejectedBy,
|
|
1197
|
+
requestedBy: pending.requested_by,
|
|
1198
|
+
reviewId: pending.id
|
|
1199
|
+
});
|
|
540
1200
|
return await getReviewRequest(pending.id);
|
|
541
1201
|
}
|
|
542
1202
|
async function cancelReview(params) {
|
|
@@ -653,6 +1313,25 @@ function rowToReviewRequest(row) {
|
|
|
653
1313
|
|
|
654
1314
|
export {
|
|
655
1315
|
safePublishDocument,
|
|
1316
|
+
listWatchers,
|
|
1317
|
+
addWatcher,
|
|
1318
|
+
removeWatcher,
|
|
1319
|
+
listNotifications,
|
|
1320
|
+
markNotificationsRead,
|
|
1321
|
+
resolveCallerEmail,
|
|
1322
|
+
canReadNode,
|
|
1323
|
+
filterAccessible,
|
|
1324
|
+
safeJson,
|
|
1325
|
+
requireWorkflowPlane,
|
|
1326
|
+
seedDefaultEdgeTypes,
|
|
1327
|
+
parseConditionSchema,
|
|
1328
|
+
edgeTypeToResponse,
|
|
1329
|
+
edgeTypeRoutes,
|
|
1330
|
+
envRoutes,
|
|
1331
|
+
envValues,
|
|
1332
|
+
isSafeConnectorUrl,
|
|
1333
|
+
dispatchEvent,
|
|
1334
|
+
verifySmtp,
|
|
656
1335
|
notifyNestEvent,
|
|
657
1336
|
submitForReview,
|
|
658
1337
|
approve,
|