@nodetool-ai/kernel 0.7.0-rc.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/dist/actor.d.ts +110 -0
  2. package/dist/actor.d.ts.map +1 -0
  3. package/dist/actor.js +430 -0
  4. package/dist/actor.js.map +1 -0
  5. package/dist/channel.d.ts +46 -0
  6. package/dist/channel.d.ts.map +1 -0
  7. package/dist/channel.js +191 -0
  8. package/dist/channel.js.map +1 -0
  9. package/dist/durable-inbox.d.ts +82 -0
  10. package/dist/durable-inbox.d.ts.map +1 -0
  11. package/dist/durable-inbox.js +158 -0
  12. package/dist/durable-inbox.js.map +1 -0
  13. package/dist/graph-utils.d.ts +60 -0
  14. package/dist/graph-utils.d.ts.map +1 -0
  15. package/dist/graph-utils.js +249 -0
  16. package/dist/graph-utils.js.map +1 -0
  17. package/dist/graph.d.ts +153 -0
  18. package/dist/graph.d.ts.map +1 -0
  19. package/dist/graph.js +656 -0
  20. package/dist/graph.js.map +1 -0
  21. package/dist/inbox.d.ts +109 -0
  22. package/dist/inbox.d.ts.map +1 -0
  23. package/dist/inbox.js +310 -0
  24. package/dist/inbox.js.map +1 -0
  25. package/dist/index.d.ts +16 -0
  26. package/dist/index.d.ts.map +1 -0
  27. package/dist/index.js +16 -0
  28. package/dist/index.js.map +1 -0
  29. package/dist/io.d.ts +92 -0
  30. package/dist/io.d.ts.map +1 -0
  31. package/dist/io.js +128 -0
  32. package/dist/io.js.map +1 -0
  33. package/dist/runner.d.ts +221 -0
  34. package/dist/runner.d.ts.map +1 -0
  35. package/dist/runner.js +1018 -0
  36. package/dist/runner.js.map +1 -0
  37. package/dist/suspendable.d.ts +68 -0
  38. package/dist/suspendable.d.ts.map +1 -0
  39. package/dist/suspendable.js +108 -0
  40. package/dist/suspendable.js.map +1 -0
  41. package/dist/trigger-manager.d.ts +107 -0
  42. package/dist/trigger-manager.d.ts.map +1 -0
  43. package/dist/trigger-manager.js +214 -0
  44. package/dist/trigger-manager.js.map +1 -0
  45. package/dist/trigger-wakeup.d.ts +54 -0
  46. package/dist/trigger-wakeup.d.ts.map +1 -0
  47. package/dist/trigger-wakeup.js +99 -0
  48. package/dist/trigger-wakeup.js.map +1 -0
  49. package/dist/trigger.d.ts +57 -0
  50. package/dist/trigger.d.ts.map +1 -0
  51. package/dist/trigger.js +145 -0
  52. package/dist/trigger.js.map +1 -0
  53. package/package.json +49 -0
package/dist/graph.js ADDED
@@ -0,0 +1,656 @@
1
+ /**
2
+ * Graph model and validation.
3
+ *
4
+ * Port of src/nodetool/workflows/graph.py:
5
+ * - Node/edge lookup with O(1) indexing
6
+ * - Edge type validation
7
+ * - Control edge validation with cycle detection
8
+ * - Topological sort (Kahn's algorithm)
9
+ * - Streaming upstream computation
10
+ */
11
+ import { createLogger } from "@nodetool-ai/config";
12
+ const log = createLogger("nodetool.kernel.graph");
13
+ import { isControlEdge, isDataEdge, TypeMetadata } from "@nodetool-ai/protocol";
14
+ export class GraphValidationError extends Error {
15
+ issues;
16
+ constructor(message, issues = []) {
17
+ super(message);
18
+ this.name = "GraphValidationError";
19
+ this.issues = issues;
20
+ }
21
+ }
22
+ // ---------------------------------------------------------------------------
23
+ // Helpers
24
+ // ---------------------------------------------------------------------------
25
+ function nodeTypeToJsonSchema(typeStr) {
26
+ if (!typeStr)
27
+ return "string";
28
+ switch (typeStr) {
29
+ case "int":
30
+ case "float":
31
+ case "number":
32
+ return "number";
33
+ case "str":
34
+ case "string":
35
+ return "string";
36
+ case "bool":
37
+ case "boolean":
38
+ return "boolean";
39
+ default:
40
+ return "string";
41
+ }
42
+ }
43
+ function resolveNodeTypeWith(resolver, nodeType) {
44
+ if (typeof resolver === "function") {
45
+ return resolver(nodeType);
46
+ }
47
+ return resolver.resolveNodeType(nodeType);
48
+ }
49
+ // ---------------------------------------------------------------------------
50
+ // Graph
51
+ // ---------------------------------------------------------------------------
52
+ export class Graph {
53
+ nodes;
54
+ edges;
55
+ /** O(1) node lookup by id */
56
+ _nodeIndex;
57
+ /** Edges keyed by target node id */
58
+ _incomingEdges;
59
+ /** Edges keyed by source node id */
60
+ _outgoingEdges;
61
+ /** Edges keyed by `${source}:${sourceHandle}` for O(1) lookup */
62
+ _outgoingByHandle;
63
+ /** Cache: nodes that have streaming upstream */
64
+ _streamingUpstream = null;
65
+ constructor(data) {
66
+ this.nodes = data.nodes;
67
+ this.edges = data.edges;
68
+ this._nodeIndex = new Map();
69
+ this._incomingEdges = new Map();
70
+ this._outgoingEdges = new Map();
71
+ this._outgoingByHandle = new Map();
72
+ this._buildIndices();
73
+ // Auto-detect is_controlled from incoming control edges (Python parity:
74
+ // BaseNode.is_controlled() checks graph edges at runtime).
75
+ this._detectControlledNodes();
76
+ }
77
+ /**
78
+ * Create a Graph from a plain object, validating the input shape.
79
+ * Throws GraphValidationError if nodes or edges are missing or not arrays.
80
+ */
81
+ static fromDict(data, options = {}) {
82
+ const { skipErrors = true, allowUndefinedProperties = true, validateNodeType } = options;
83
+ if (!data || typeof data !== "object") {
84
+ throw new GraphValidationError("Graph data must be an object");
85
+ }
86
+ const obj = data;
87
+ if (!("nodes" in obj) || !("edges" in obj)) {
88
+ throw new GraphValidationError("Graph data must have 'nodes' and 'edges' fields");
89
+ }
90
+ if (!Array.isArray(obj.nodes)) {
91
+ throw new GraphValidationError("'nodes' must be an array");
92
+ }
93
+ if (!Array.isArray(obj.edges)) {
94
+ throw new GraphValidationError("'edges' must be an array");
95
+ }
96
+ const propertiesWithEdges = new Map();
97
+ for (const edge of obj.edges) {
98
+ if (!edge || typeof edge !== "object") {
99
+ if (skipErrors)
100
+ continue;
101
+ throw new GraphValidationError("Edge entries must be objects");
102
+ }
103
+ const edgeObj = edge;
104
+ const targetId = typeof edgeObj.target === "string" ? edgeObj.target : undefined;
105
+ const targetHandle = typeof edgeObj.targetHandle === "string"
106
+ ? edgeObj.targetHandle
107
+ : undefined;
108
+ if (!targetId || !targetHandle)
109
+ continue;
110
+ let handles = propertiesWithEdges.get(targetId);
111
+ if (!handles) {
112
+ handles = new Set();
113
+ propertiesWithEdges.set(targetId, handles);
114
+ }
115
+ handles.add(targetHandle);
116
+ }
117
+ const validNodes = [];
118
+ const validNodeIds = new Set();
119
+ for (const node of obj.nodes) {
120
+ if (!node || typeof node !== "object") {
121
+ if (skipErrors)
122
+ continue;
123
+ throw new GraphValidationError("Node entries must be objects");
124
+ }
125
+ const nodeObj = { ...node };
126
+ const id = typeof nodeObj.id === "string" ? nodeObj.id : undefined;
127
+ const type = typeof nodeObj.type === "string" ? nodeObj.type : undefined;
128
+ if (!id || !type) {
129
+ if (skipErrors)
130
+ continue;
131
+ throw new GraphValidationError("Each node must have string 'id' and 'type' fields");
132
+ }
133
+ if (validateNodeType && !validateNodeType(type)) {
134
+ if (skipErrors)
135
+ continue;
136
+ throw new GraphValidationError(`Invalid node type: ${type}`);
137
+ }
138
+ const rawProperties = nodeObj.properties && typeof nodeObj.properties === "object"
139
+ ? { ...nodeObj.properties }
140
+ : nodeObj.data && typeof nodeObj.data === "object"
141
+ ? { ...nodeObj.data }
142
+ : {};
143
+ // Merge dynamic_properties into the node's properties so that
144
+ // dynamic nodes (e.g. WorkflowNode) receive user-provided values
145
+ // for inputs that aren't connected via edges.
146
+ if (nodeObj.dynamic_properties &&
147
+ typeof nodeObj.dynamic_properties === "object") {
148
+ Object.assign(rawProperties, nodeObj.dynamic_properties);
149
+ }
150
+ if (!allowUndefinedProperties) {
151
+ // Only validate against propertyTypes when it is explicitly provided.
152
+ // Using properties itself as a source of truth would defeat the purpose
153
+ // of this check, since every property key would always be "defined".
154
+ const hasPropertyTypes = nodeObj.propertyTypes != null &&
155
+ typeof nodeObj.propertyTypes === "object" &&
156
+ Object.keys(nodeObj.propertyTypes).length >
157
+ 0;
158
+ if (hasPropertyTypes) {
159
+ const definedProperties = new Set(Object.keys(nodeObj.propertyTypes));
160
+ for (const key of Object.keys(rawProperties)) {
161
+ if (!definedProperties.has(key)) {
162
+ if (skipErrors) {
163
+ delete rawProperties[key];
164
+ }
165
+ else {
166
+ throw new GraphValidationError(`Property ${key} does not exist on node ${id}`);
167
+ }
168
+ }
169
+ }
170
+ }
171
+ }
172
+ for (const handle of propertiesWithEdges.get(id) ?? []) {
173
+ delete rawProperties[handle];
174
+ }
175
+ nodeObj.properties = rawProperties;
176
+ delete nodeObj.data;
177
+ validNodes.push(nodeObj);
178
+ validNodeIds.add(id);
179
+ }
180
+ const validEdges = [];
181
+ for (const edge of obj.edges) {
182
+ if (!edge || typeof edge !== "object") {
183
+ if (skipErrors)
184
+ continue;
185
+ throw new GraphValidationError("Edge entries must be objects");
186
+ }
187
+ const edgeObj = edge;
188
+ const hasRequiredFields = typeof edgeObj.source === "string" &&
189
+ typeof edgeObj.sourceHandle === "string" &&
190
+ typeof edgeObj.target === "string" &&
191
+ typeof edgeObj.targetHandle === "string";
192
+ if (!hasRequiredFields) {
193
+ if (skipErrors)
194
+ continue;
195
+ throw new GraphValidationError("Each edge must have string 'source', 'sourceHandle', 'target', and 'targetHandle' fields");
196
+ }
197
+ const source = edgeObj.source;
198
+ const target = edgeObj.target;
199
+ if (skipErrors &&
200
+ (!validNodeIds.has(source) || !validNodeIds.has(target))) {
201
+ continue;
202
+ }
203
+ validEdges.push(edgeObj);
204
+ }
205
+ return new Graph({ nodes: validNodes, edges: validEdges });
206
+ }
207
+ static async loadFromDict(data, options) {
208
+ const { resolver, skipErrors = true, allowUndefinedProperties = true } = options;
209
+ const normalized = Graph.fromDict(data, {
210
+ skipErrors,
211
+ allowUndefinedProperties: true
212
+ });
213
+ const resolvedNodes = [];
214
+ const validNodeIds = new Set();
215
+ for (const node of normalized.nodes) {
216
+ const resolved = await resolveNodeTypeWith(resolver, node.type);
217
+ if (!resolved) {
218
+ if (skipErrors)
219
+ continue;
220
+ throw new GraphValidationError(`Invalid node type: ${node.type}`);
221
+ }
222
+ const resolvedPropertyTypes = resolved.propertyTypes ?? {};
223
+ const allowedProperties = new Set(Object.keys(resolvedPropertyTypes));
224
+ const mergedProperties = {
225
+ ...(node.properties ?? {})
226
+ };
227
+ const effectiveAllowUndefined = resolved.isDynamic || allowUndefinedProperties;
228
+ if (!effectiveAllowUndefined) {
229
+ for (const key of Object.keys(mergedProperties)) {
230
+ if (!allowedProperties.has(key)) {
231
+ if (skipErrors) {
232
+ delete mergedProperties[key];
233
+ }
234
+ else {
235
+ throw new GraphValidationError(`Property ${key} does not exist on node ${node.id}`);
236
+ }
237
+ }
238
+ }
239
+ }
240
+ const descriptorDefaults = resolved.descriptorDefaults ?? {};
241
+ const hydratedNode = {
242
+ ...descriptorDefaults,
243
+ ...node,
244
+ type: resolved.nodeType,
245
+ properties: mergedProperties,
246
+ propertyTypes: {
247
+ ...resolvedPropertyTypes,
248
+ ...(node.propertyTypes ?? {})
249
+ },
250
+ outputs: {
251
+ ...(resolved.outputs ?? {}),
252
+ ...(node.outputs ?? {})
253
+ },
254
+ sync_mode: node.sync_mode ??
255
+ node.properties
256
+ ?.sync_mode ??
257
+ descriptorDefaults.sync_mode ??
258
+ "on_any",
259
+ // Streaming/control flags: registry metadata (descriptorDefaults) is
260
+ // the source of truth. Saved graph data may have stale or missing
261
+ // values, so always prefer the registry if it declares true.
262
+ is_streaming_input: descriptorDefaults.is_streaming_input ||
263
+ node.is_streaming_input ||
264
+ false,
265
+ is_streaming_output: descriptorDefaults.is_streaming_output ||
266
+ node.is_streaming_output ||
267
+ false,
268
+ is_controlled: descriptorDefaults.is_controlled || node.is_controlled || false
269
+ };
270
+ resolvedNodes.push(hydratedNode);
271
+ validNodeIds.add(hydratedNode.id);
272
+ }
273
+ const validEdges = normalized.edges.filter((edge) => validNodeIds.has(edge.source) && validNodeIds.has(edge.target));
274
+ return new Graph({ nodes: resolvedNodes, edges: validEdges });
275
+ }
276
+ // -----------------------------------------------------------------------
277
+ // Index building
278
+ // -----------------------------------------------------------------------
279
+ _buildIndices() {
280
+ for (const node of this.nodes) {
281
+ this._nodeIndex.set(node.id, node);
282
+ }
283
+ for (const edge of this.edges) {
284
+ // incoming
285
+ const incoming = this._incomingEdges.get(edge.target);
286
+ if (incoming) {
287
+ incoming.push(edge);
288
+ }
289
+ else {
290
+ this._incomingEdges.set(edge.target, [edge]);
291
+ }
292
+ // outgoing
293
+ const outgoing = this._outgoingEdges.get(edge.source);
294
+ if (outgoing) {
295
+ outgoing.push(edge);
296
+ }
297
+ else {
298
+ this._outgoingEdges.set(edge.source, [edge]);
299
+ }
300
+ // outgoing by handle
301
+ const handleKey = `${edge.source}:${edge.sourceHandle}`;
302
+ const byHandle = this._outgoingByHandle.get(handleKey);
303
+ if (byHandle) {
304
+ byHandle.push(edge);
305
+ }
306
+ else {
307
+ this._outgoingByHandle.set(handleKey, [edge]);
308
+ }
309
+ }
310
+ }
311
+ /**
312
+ * Auto-detect is_controlled from incoming control edges.
313
+ * In Python, BaseNode.is_controlled() is a runtime method that checks
314
+ * the graph context. In TS, we set the flag on the descriptor so that
315
+ * the actor knows to use _runControlled().
316
+ */
317
+ _detectControlledNodes() {
318
+ for (const edge of this.edges) {
319
+ if (!isControlEdge(edge))
320
+ continue;
321
+ const target = this._nodeIndex.get(edge.target);
322
+ if (target && !target.is_controlled) {
323
+ // NodeDescriptor is readonly in the type, but we own the instances
324
+ target.is_controlled = true;
325
+ }
326
+ }
327
+ }
328
+ // -----------------------------------------------------------------------
329
+ // Lookups
330
+ // -----------------------------------------------------------------------
331
+ findNode(id) {
332
+ return this._nodeIndex.get(id);
333
+ }
334
+ /**
335
+ * Return all edges where target == nodeId (incoming edges).
336
+ */
337
+ findIncomingEdges(nodeId) {
338
+ return this._incomingEdges.get(nodeId) ?? [];
339
+ }
340
+ /**
341
+ * Return all edges where source == nodeId (outgoing edges).
342
+ */
343
+ findOutgoingEdges(nodeId) {
344
+ return this._outgoingEdges.get(nodeId) ?? [];
345
+ }
346
+ /**
347
+ * Return edges matching a specific (source, sourceHandle) pair. O(1) lookup.
348
+ * Mirrors Python's find_edges(source, source_handle).
349
+ */
350
+ findEdges(source, sourceHandle) {
351
+ return this._outgoingByHandle.get(`${source}:${sourceHandle}`) ?? [];
352
+ }
353
+ /**
354
+ * Return data (non-control) edges targeting a node.
355
+ */
356
+ findDataEdges(nodeId) {
357
+ return this.findIncomingEdges(nodeId).filter(isDataEdge);
358
+ }
359
+ getControlEdges(targetId) {
360
+ return this.edges.filter((edge) => isControlEdge(edge) &&
361
+ (targetId === undefined || edge.target === targetId));
362
+ }
363
+ getControllerNodes(targetId) {
364
+ const ids = new Set((targetId === undefined
365
+ ? this.getControlEdges()
366
+ : this.getControlEdges(targetId)).map((e) => e.source));
367
+ return this.nodes.filter((n) => ids.has(n.id));
368
+ }
369
+ getControlledNodes(sourceId) {
370
+ if (sourceId !== undefined) {
371
+ return this.edges
372
+ .filter((edge) => isControlEdge(edge) && edge.source === sourceId)
373
+ .map((edge) => edge.target);
374
+ }
375
+ const ids = new Set(this.getControlEdges().map((e) => e.target));
376
+ return this.nodes.filter((n) => ids.has(n.id));
377
+ }
378
+ // -----------------------------------------------------------------------
379
+ // Input / Output nodes
380
+ // -----------------------------------------------------------------------
381
+ /**
382
+ * Return nodes that have no incoming data edges (source nodes).
383
+ */
384
+ inputNodes() {
385
+ return this.nodes.filter((n) => this.findDataEdges(n.id).length === 0);
386
+ }
387
+ /**
388
+ * Return nodes that have no outgoing data edges (sink nodes).
389
+ */
390
+ outputNodes() {
391
+ return this.nodes.filter((n) => this.findOutgoingEdges(n.id).filter(isDataEdge).length === 0);
392
+ }
393
+ // -----------------------------------------------------------------------
394
+ // Streaming upstream detection
395
+ // -----------------------------------------------------------------------
396
+ /**
397
+ * Check whether a node has streaming upstream (i.e. is downstream
398
+ * of a streaming-output node via data edges).
399
+ */
400
+ hasStreamingUpstream(nodeId) {
401
+ if (!this._streamingUpstream) {
402
+ this._streamingUpstream = this._computeStreamingUpstream();
403
+ }
404
+ return this._streamingUpstream.has(nodeId);
405
+ }
406
+ _computeStreamingUpstream() {
407
+ const result = new Set();
408
+ // BFS from every streaming-output node along data edges
409
+ const streamingSources = this.nodes.filter((n) => n.is_streaming_output);
410
+ const queue = [];
411
+ for (const src of streamingSources) {
412
+ for (const edge of this.findOutgoingEdges(src.id)) {
413
+ if (isDataEdge(edge) && !result.has(edge.target)) {
414
+ result.add(edge.target);
415
+ queue.push(edge.target);
416
+ }
417
+ }
418
+ }
419
+ while (queue.length > 0) {
420
+ const nodeId = queue.shift();
421
+ for (const edge of this.findOutgoingEdges(nodeId)) {
422
+ if (isDataEdge(edge) && !result.has(edge.target)) {
423
+ result.add(edge.target);
424
+ queue.push(edge.target);
425
+ }
426
+ }
427
+ }
428
+ return result;
429
+ }
430
+ // -----------------------------------------------------------------------
431
+ // Topological sort (Kahn's algorithm) – returns levels
432
+ // -----------------------------------------------------------------------
433
+ /**
434
+ * Returns nodes grouped into execution levels.
435
+ * Nodes in the same level have no inter-dependencies and can run
436
+ * concurrently. Only data edges define the ordering.
437
+ */
438
+ topologicalSort(parentId = null) {
439
+ const groupNodeIds = parentId === null
440
+ ? new Set(this.nodes
441
+ .filter((node) => node.type === "GroupNode" || node.type.endsWith(".GroupNode"))
442
+ .map((node) => node.id))
443
+ : new Set();
444
+ const filteredNodes = this.nodes.filter((node) => (node.parent_id ?? null) === parentId ||
445
+ (node.parent_id != null && groupNodeIds.has(node.parent_id)));
446
+ const filteredNodeIds = new Set(filteredNodes.map((node) => node.id));
447
+ const filteredEdges = this.edges.filter((edge) => filteredNodeIds.has(edge.source) && filteredNodeIds.has(edge.target));
448
+ // In-degree count across filtered edges.
449
+ const inDeg = new Map();
450
+ for (const node of filteredNodes) {
451
+ inDeg.set(node.id, 0);
452
+ }
453
+ for (const edge of filteredEdges) {
454
+ inDeg.set(edge.target, (inDeg.get(edge.target) ?? 0) + 1);
455
+ }
456
+ // Seed with zero-in-degree nodes
457
+ let currentLevel = [];
458
+ for (const [id, deg] of inDeg) {
459
+ if (deg === 0)
460
+ currentLevel.push(id);
461
+ }
462
+ const levels = [];
463
+ const visited = new Set();
464
+ while (currentLevel.length > 0) {
465
+ const levelNodes = [];
466
+ const nextLevel = [];
467
+ for (const id of currentLevel) {
468
+ visited.add(id);
469
+ const node = this.findNode(id);
470
+ if (node)
471
+ levelNodes.push(node);
472
+ for (const edge of filteredEdges) {
473
+ if (edge.source !== id)
474
+ continue;
475
+ const newDeg = (inDeg.get(edge.target) ?? 1) - 1;
476
+ inDeg.set(edge.target, newDeg);
477
+ if (newDeg === 0 && !visited.has(edge.target)) {
478
+ nextLevel.push(edge.target);
479
+ }
480
+ }
481
+ }
482
+ if (levelNodes.length > 0)
483
+ levels.push(levelNodes);
484
+ currentLevel = nextLevel;
485
+ }
486
+ if (visited.size !== filteredNodes.length) {
487
+ log.warn("Graph contains at least one cycle", {
488
+ visited: visited.size,
489
+ total: filteredNodes.length
490
+ });
491
+ }
492
+ return levels;
493
+ }
494
+ // -----------------------------------------------------------------------
495
+ // Input / Output schema (T-MSG-5)
496
+ // -----------------------------------------------------------------------
497
+ /**
498
+ * Build a JSON Schema object from input nodes (type contains "Input").
499
+ * Each input node contributes a property named after node.name (or node.id).
500
+ */
501
+ getInputSchema() {
502
+ return this._buildSchema((n) => n.type.includes("Input"));
503
+ }
504
+ /**
505
+ * Build a JSON Schema object from output nodes (type contains "Output").
506
+ */
507
+ getOutputSchema() {
508
+ return this._buildSchema((n) => n.type.includes("Output"));
509
+ }
510
+ _buildSchema(filter) {
511
+ const properties = {};
512
+ const required = [];
513
+ for (const node of this.nodes) {
514
+ if (!filter(node))
515
+ continue;
516
+ const name = node.name || node.id;
517
+ // Use the first output type to determine the JSON Schema type
518
+ const outputType = node.outputs
519
+ ? Object.values(node.outputs)[0]
520
+ : undefined;
521
+ properties[name] = { type: nodeTypeToJsonSchema(outputType) };
522
+ required.push(name);
523
+ }
524
+ return { properties, required };
525
+ }
526
+ // -----------------------------------------------------------------------
527
+ // Validation
528
+ // -----------------------------------------------------------------------
529
+ /**
530
+ * Validate the graph structure.
531
+ * Throws GraphValidationError on problems.
532
+ */
533
+ validate() {
534
+ this.validateEdgeEndpoints();
535
+ this.validateControlEdges();
536
+ this.validateEdgeTypes();
537
+ }
538
+ /**
539
+ * Verify that every edge references existing nodes.
540
+ */
541
+ validateEdgeEndpoints() {
542
+ for (const edge of this.edges) {
543
+ if (!this._nodeIndex.has(edge.source)) {
544
+ log.error("Edge references unknown source node", {
545
+ source: edge.source
546
+ });
547
+ throw new GraphValidationError(`Edge references unknown source node: ${edge.source}`);
548
+ }
549
+ if (!this._nodeIndex.has(edge.target)) {
550
+ log.error("Edge references unknown target node", {
551
+ target: edge.target
552
+ });
553
+ throw new GraphValidationError(`Edge references unknown target node: ${edge.target}`);
554
+ }
555
+ }
556
+ }
557
+ /**
558
+ * Validate control edges:
559
+ * - Source and target must exist.
560
+ * - Target handle must be "__control__".
561
+ * - No cycles in control edges.
562
+ */
563
+ validateControlEdges() {
564
+ const controlEdges = this.getControlEdges();
565
+ for (const edge of controlEdges) {
566
+ if (edge.targetHandle !== "__control__") {
567
+ throw new GraphValidationError(`Control edge target handle must be "__control__", ` +
568
+ `got "${edge.targetHandle}" on edge ${edge.id ?? "(no id)"}`);
569
+ }
570
+ }
571
+ // Cycle detection in control edges (DFS)
572
+ this._checkCircularControl(controlEdges);
573
+ }
574
+ /**
575
+ * Validate type compatibility between connected edge endpoints.
576
+ * For each data edge, checks if the source output type is compatible
577
+ * with the target input type. Compatible means: same type, one is "any",
578
+ * or numeric widening (int -> float).
579
+ */
580
+ validateEdgeTypes() {
581
+ for (const edge of this.edges) {
582
+ if (isControlEdge(edge))
583
+ continue;
584
+ const sourceNode = this._nodeIndex.get(edge.source);
585
+ const targetNode = this._nodeIndex.get(edge.target);
586
+ if (!sourceNode || !targetNode)
587
+ continue;
588
+ // Get source output type from node.outputs[sourceHandle]
589
+ const sourceType = sourceNode.outputs?.[edge.sourceHandle];
590
+ if (!sourceType)
591
+ continue; // no type info, skip
592
+ // Get target input type from node.properties[targetHandle].type
593
+ const targetProp = targetNode.properties?.[edge.targetHandle];
594
+ let targetType;
595
+ if (typeof targetProp === "object" &&
596
+ targetProp !== null &&
597
+ "type" in targetProp) {
598
+ targetType = targetProp.type;
599
+ }
600
+ else if (typeof targetProp === "string") {
601
+ targetType = targetProp;
602
+ }
603
+ if (!targetType)
604
+ continue; // no type info, skip
605
+ // Use TypeMetadata for full compatibility check (handles list[X], union, numeric widening)
606
+ const sourceMeta = TypeMetadata.fromString(sourceType);
607
+ const targetMeta = TypeMetadata.fromString(targetType);
608
+ if (!sourceMeta.isCompatibleWith(targetMeta)) {
609
+ log.warn("Type mismatch on edge", {
610
+ source: edge.source,
611
+ target: edge.target,
612
+ sourceType,
613
+ targetType
614
+ });
615
+ throw new GraphValidationError(`Type mismatch on edge ${edge.id ?? `${edge.source}:${edge.sourceHandle}->${edge.target}:${edge.targetHandle}`}: ` +
616
+ `source outputs "${sourceType}" but target expects "${targetType}"`);
617
+ }
618
+ }
619
+ }
620
+ _checkCircularControl(controlEdges) {
621
+ // Build adjacency list for control edges only
622
+ const adj = new Map();
623
+ for (const edge of controlEdges) {
624
+ const targets = adj.get(edge.source);
625
+ if (targets) {
626
+ targets.push(edge.target);
627
+ }
628
+ else {
629
+ adj.set(edge.source, [edge.target]);
630
+ }
631
+ }
632
+ const WHITE = 0, GRAY = 1, BLACK = 2;
633
+ const color = new Map();
634
+ const dfs = (node) => {
635
+ color.set(node, GRAY);
636
+ for (const neighbor of adj.get(node) ?? []) {
637
+ const c = color.get(neighbor) ?? WHITE;
638
+ if (c === GRAY)
639
+ return true; // back edge → cycle
640
+ if (c === WHITE && dfs(neighbor))
641
+ return true;
642
+ }
643
+ color.set(node, BLACK);
644
+ return false;
645
+ };
646
+ for (const node of adj.keys()) {
647
+ if ((color.get(node) ?? WHITE) === WHITE) {
648
+ if (dfs(node)) {
649
+ log.error("Graph contains a cycle in control edges");
650
+ throw new GraphValidationError("Graph contains a cycle in control edges");
651
+ }
652
+ }
653
+ }
654
+ }
655
+ }
656
+ //# sourceMappingURL=graph.js.map