@nodetool-ai/kernel 0.8.8 → 0.8.9-beta.2
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/dist/.nodetool-build-stamp +1 -1
- package/dist/actor.d.ts +1 -479
- package/dist/actor.d.ts.map +1 -1
- package/dist/actor.js +1 -1911
- package/dist/actor.js.map +1 -1
- package/dist/correlation-analysis.d.ts +1 -103
- package/dist/correlation-analysis.d.ts.map +1 -1
- package/dist/correlation-analysis.js +1 -845
- package/dist/correlation-analysis.js.map +1 -1
- package/dist/durable-inbox.d.ts +1 -90
- package/dist/durable-inbox.d.ts.map +1 -1
- package/dist/durable-inbox.js +1 -210
- package/dist/durable-inbox.js.map +1 -1
- package/dist/dynamic-slots.d.ts +1 -72
- package/dist/dynamic-slots.d.ts.map +1 -1
- package/dist/dynamic-slots.js +1 -191
- package/dist/dynamic-slots.js.map +1 -1
- package/dist/edge-ids.d.ts +1 -10
- package/dist/edge-ids.d.ts.map +1 -1
- package/dist/edge-ids.js +1 -14
- package/dist/edge-ids.js.map +1 -1
- package/dist/graph-utils.d.ts +1 -71
- package/dist/graph-utils.d.ts.map +1 -1
- package/dist/graph-utils.js +1 -283
- package/dist/graph-utils.js.map +1 -1
- package/dist/graph.d.ts +1 -203
- package/dist/graph.d.ts.map +1 -1
- package/dist/graph.js +1 -867
- package/dist/graph.js.map +1 -1
- package/dist/inbox.d.ts +1 -264
- package/dist/inbox.d.ts.map +1 -1
- package/dist/inbox.js +1 -551
- package/dist/inbox.js.map +1 -1
- package/dist/index.d.ts +1 -19
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -19
- package/dist/index.js.map +1 -1
- package/dist/io.d.ts +1 -188
- package/dist/io.d.ts.map +1 -1
- package/dist/io.js +1 -238
- package/dist/io.js.map +1 -1
- package/dist/loop.d.ts +1 -35
- package/dist/loop.d.ts.map +1 -1
- package/dist/loop.js +1 -165
- package/dist/loop.js.map +1 -1
- package/dist/message-stream.d.ts +1 -31
- package/dist/message-stream.d.ts.map +1 -1
- package/dist/message-stream.js +1 -63
- package/dist/message-stream.js.map +1 -1
- package/dist/predicates.d.ts +1 -7
- package/dist/predicates.d.ts.map +1 -1
- package/dist/predicates.js +1 -7
- package/dist/predicates.js.map +1 -1
- package/dist/run-state.d.ts +1 -64
- package/dist/run-state.d.ts.map +1 -1
- package/dist/run-state.js +1 -41
- package/dist/run-state.js.map +1 -1
- package/dist/runner.d.ts +1 -523
- package/dist/runner.d.ts.map +1 -1
- package/dist/runner.js +1 -2126
- package/dist/runner.js.map +1 -1
- package/dist/substitute-validator.d.ts +1 -43
- package/dist/substitute-validator.d.ts.map +1 -1
- package/dist/substitute-validator.js +1 -168
- package/dist/substitute-validator.js.map +1 -1
- package/dist/supervisor.d.ts +1 -147
- package/dist/supervisor.d.ts.map +1 -1
- package/dist/supervisor.js +1 -286
- package/dist/supervisor.js.map +1 -1
- package/dist/trigger-wakeup.d.ts +1 -122
- package/dist/trigger-wakeup.d.ts.map +1 -1
- package/dist/trigger-wakeup.js +1 -220
- package/dist/trigger-wakeup.js.map +1 -1
- package/package.json +4 -4
package/dist/graph.js
CHANGED
|
@@ -1,868 +1,2 @@
|
|
|
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
|
-
// Stryker disable next-line StringLiteral: logger name is a diagnostic label, not a behavioural contract
|
|
13
|
-
const log = createLogger("nodetool.kernel.graph");
|
|
14
|
-
import { isControlEdge, isDataEdge, isLoopBackEdge, migrateGraphNodeTypes, TypeMetadata } from "@nodetool-ai/protocol";
|
|
15
|
-
import { syntheticEdgeId } from "./edge-ids.js";
|
|
16
|
-
import { dynamicSlotPropertyTypes, mergeDerivedSlots } from "./dynamic-slots.js";
|
|
17
|
-
import { isCallable, isObjectValue, isString } from "./predicates.js";
|
|
18
|
-
export class GraphValidationError extends Error {
|
|
19
|
-
issues;
|
|
20
|
-
constructor(message, issues = []) {
|
|
21
|
-
super(message);
|
|
22
|
-
this.name = "GraphValidationError";
|
|
23
|
-
this.issues = issues;
|
|
24
|
-
}
|
|
25
|
-
}
|
|
26
|
-
// ---------------------------------------------------------------------------
|
|
27
|
-
// Helpers
|
|
28
|
-
// ---------------------------------------------------------------------------
|
|
29
|
-
function nodeTypeToJsonSchema(typeStr) {
|
|
30
|
-
// Stryker disable next-line ConditionalExpression: equivalent — a falsy typeStr falls through to the default case, which also returns "string"
|
|
31
|
-
if (!typeStr)
|
|
32
|
-
return "string";
|
|
33
|
-
switch (typeStr) {
|
|
34
|
-
case "int":
|
|
35
|
-
case "float":
|
|
36
|
-
case "number":
|
|
37
|
-
return "number";
|
|
38
|
-
// Stryker disable StringLiteral: equivalent — both labels return "string", the same value as the default branch
|
|
39
|
-
case "str":
|
|
40
|
-
case "string":
|
|
41
|
-
// Stryker restore StringLiteral
|
|
42
|
-
return "string";
|
|
43
|
-
case "bool":
|
|
44
|
-
case "boolean":
|
|
45
|
-
return "boolean";
|
|
46
|
-
default:
|
|
47
|
-
return "string";
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
function resolveNodeTypeWith(resolver, nodeType) {
|
|
51
|
-
if (isCallable(resolver)) {
|
|
52
|
-
return resolver(nodeType);
|
|
53
|
-
}
|
|
54
|
-
return resolver.resolveNodeType(nodeType);
|
|
55
|
-
}
|
|
56
|
-
// ---------------------------------------------------------------------------
|
|
57
|
-
// Graph
|
|
58
|
-
// ---------------------------------------------------------------------------
|
|
59
|
-
/**
|
|
60
|
-
* Mark a code-constructed graph as hydrated by defaulting absent behavior
|
|
61
|
-
* flags to false. For graphs built in code (tests, DSL output) where the
|
|
62
|
-
* author already set the flags that matter. NOT a substitute for registry
|
|
63
|
-
* hydration of client/wire graphs — there an absent flag means "unknown",
|
|
64
|
-
* not "off"; use `Graph.loadFromDict` or node-sdk's `hydrateGraphNodeFlags`.
|
|
65
|
-
*/
|
|
66
|
-
export function withExplicitNodeFlags(graph) {
|
|
67
|
-
return {
|
|
68
|
-
nodes: graph.nodes.map((node) => ({
|
|
69
|
-
...node,
|
|
70
|
-
is_streaming_input: node.is_streaming_input ?? false,
|
|
71
|
-
is_streaming_output: node.is_streaming_output ?? false,
|
|
72
|
-
is_controlled: node.is_controlled ?? false,
|
|
73
|
-
is_join_node: node.is_join_node ?? false,
|
|
74
|
-
// Here — unlike `loadFromDict` — the descriptor's author is code, not a
|
|
75
|
-
// saved file, so a declared `retry_safe` is the class's own declaration.
|
|
76
|
-
retry_safe: node.retry_safe ?? false
|
|
77
|
-
})),
|
|
78
|
-
edges: [...graph.edges]
|
|
79
|
-
};
|
|
80
|
-
}
|
|
81
|
-
export class Graph {
|
|
82
|
-
nodes;
|
|
83
|
-
edges;
|
|
84
|
-
/** O(1) node lookup by id */
|
|
85
|
-
_nodeIndex;
|
|
86
|
-
/** Edges keyed by target node id */
|
|
87
|
-
_incomingEdges;
|
|
88
|
-
/** Edges keyed by source node id */
|
|
89
|
-
_outgoingEdges;
|
|
90
|
-
/** Edges keyed by `${source}:${sourceHandle}` for O(1) lookup */
|
|
91
|
-
_outgoingByHandle;
|
|
92
|
-
/** Cache: nodes that have streaming upstream */
|
|
93
|
-
_streamingUpstream = null;
|
|
94
|
-
constructor(data) {
|
|
95
|
-
// Auto-detect is_controlled from incoming control edges (Python parity:
|
|
96
|
-
// BaseNode.is_controlled() checks graph edges at runtime). Affected nodes
|
|
97
|
-
// are replaced with shallow copies rather than mutated in place, so a
|
|
98
|
-
// WorkflowRunner.run() never writes back onto the caller's graph data.
|
|
99
|
-
this.nodes = Graph._withControlledFlags(data.nodes, data.edges);
|
|
100
|
-
this.edges = data.edges;
|
|
101
|
-
this._nodeIndex = new Map();
|
|
102
|
-
this._incomingEdges = new Map();
|
|
103
|
-
this._outgoingEdges = new Map();
|
|
104
|
-
this._outgoingByHandle = new Map();
|
|
105
|
-
this._buildIndices();
|
|
106
|
-
}
|
|
107
|
-
/**
|
|
108
|
-
* Create a Graph from a plain object, validating the input shape.
|
|
109
|
-
* Throws GraphValidationError if nodes or edges are missing or not arrays.
|
|
110
|
-
*/
|
|
111
|
-
static fromDict(data, options = {}) {
|
|
112
|
-
const { skipErrors = true, allowUndefinedProperties = true, validateNodeType } = options;
|
|
113
|
-
if (!isObjectValue(data)) {
|
|
114
|
-
throw new GraphValidationError("Graph data must be an object");
|
|
115
|
-
}
|
|
116
|
-
const obj = data;
|
|
117
|
-
if (!("nodes" in obj) || !("edges" in obj)) {
|
|
118
|
-
throw new GraphValidationError("Graph data must have 'nodes' and 'edges' fields");
|
|
119
|
-
}
|
|
120
|
-
if (!Array.isArray(obj.nodes)) {
|
|
121
|
-
throw new GraphValidationError("'nodes' must be an array");
|
|
122
|
-
}
|
|
123
|
-
if (!Array.isArray(obj.edges)) {
|
|
124
|
-
throw new GraphValidationError("'edges' must be an array");
|
|
125
|
-
}
|
|
126
|
-
// Rewrite removed node types (e.g. FormatText -> Prompt) before validation
|
|
127
|
-
// so legacy workflows keep loading. See NODE_TYPE_MIGRATIONS in protocol.
|
|
128
|
-
const migrated = migrateGraphNodeTypes(obj);
|
|
129
|
-
const migratedNodes = migrated.nodes;
|
|
130
|
-
const migratedEdges = migrated.edges;
|
|
131
|
-
const validNodes = [];
|
|
132
|
-
const validNodeIds = new Set();
|
|
133
|
-
for (const node of migratedNodes) {
|
|
134
|
-
// Stryker disable next-line ConditionalExpression,LogicalOperator: the typeof/operator variants are equivalent — a non-object node yields {} after the spread below and is then dropped by the id/type guard
|
|
135
|
-
if (!isObjectValue(node)) {
|
|
136
|
-
if (skipErrors)
|
|
137
|
-
continue;
|
|
138
|
-
throw new GraphValidationError("Node entries must be objects");
|
|
139
|
-
}
|
|
140
|
-
const nodeObj = { ...node };
|
|
141
|
-
const id = isString(nodeObj.id) ? nodeObj.id : undefined;
|
|
142
|
-
const type = isString(nodeObj.type) ? nodeObj.type : undefined;
|
|
143
|
-
if (!id || !type) {
|
|
144
|
-
if (skipErrors)
|
|
145
|
-
continue;
|
|
146
|
-
throw new GraphValidationError("Each node must have string 'id' and 'type' fields");
|
|
147
|
-
}
|
|
148
|
-
if (validateNodeType && !validateNodeType(type)) {
|
|
149
|
-
if (skipErrors)
|
|
150
|
-
continue;
|
|
151
|
-
throw new GraphValidationError(`Invalid node type: ${type}`);
|
|
152
|
-
}
|
|
153
|
-
const rawProperties =
|
|
154
|
-
// Stryker disable next-line ConditionalExpression,LogicalOperator: equivalent — a non-object properties value spreads to {}, the same as falling through to data/{}
|
|
155
|
-
isObjectValue(nodeObj.properties)
|
|
156
|
-
? { ...nodeObj.properties }
|
|
157
|
-
: // Stryker disable next-line ConditionalExpression,LogicalOperator: equivalent — a non-object data value spreads to {}
|
|
158
|
-
isObjectValue(nodeObj.data)
|
|
159
|
-
? { ...nodeObj.data }
|
|
160
|
-
: {};
|
|
161
|
-
// Merge dynamic_properties into the node's properties so that
|
|
162
|
-
// dynamic nodes (e.g. WorkflowNode) receive user-provided values
|
|
163
|
-
// for inputs that aren't connected via edges.
|
|
164
|
-
if (isObjectValue(nodeObj.dynamic_properties)) {
|
|
165
|
-
Object.assign(rawProperties, nodeObj.dynamic_properties);
|
|
166
|
-
}
|
|
167
|
-
// Declared dynamic slots are real, typed handles: register their type
|
|
168
|
-
// in propertyTypes so the undefined-property guard below keeps them and
|
|
169
|
-
// downstream type lookups see a type instead of `any`. Only merged into
|
|
170
|
-
// an existing non-empty map — synthesizing propertyTypes here would
|
|
171
|
-
// switch the guard on for a node that had no type map at all.
|
|
172
|
-
const slotTypes = dynamicSlotPropertyTypes(nodeObj.dynamic_inputs);
|
|
173
|
-
if (Object.keys(slotTypes).length > 0 &&
|
|
174
|
-
isObjectValue(nodeObj.propertyTypes) &&
|
|
175
|
-
Object.keys(nodeObj.propertyTypes).length > 0) {
|
|
176
|
-
nodeObj.propertyTypes = {
|
|
177
|
-
...slotTypes,
|
|
178
|
-
...nodeObj.propertyTypes
|
|
179
|
-
};
|
|
180
|
-
}
|
|
181
|
-
if (!allowUndefinedProperties) {
|
|
182
|
-
// Only validate against propertyTypes when it is explicitly provided.
|
|
183
|
-
// Using properties itself as a source of truth would defeat the purpose
|
|
184
|
-
// of this check, since every property key would always be "defined".
|
|
185
|
-
const hasPropertyTypes = isObjectValue(nodeObj.propertyTypes) &&
|
|
186
|
-
Object.keys(nodeObj.propertyTypes).length >
|
|
187
|
-
0;
|
|
188
|
-
if (hasPropertyTypes) {
|
|
189
|
-
const definedProperties = new Set(Object.keys(nodeObj.propertyTypes));
|
|
190
|
-
for (const key of Object.keys(rawProperties)) {
|
|
191
|
-
if (!definedProperties.has(key)) {
|
|
192
|
-
if (skipErrors) {
|
|
193
|
-
delete rawProperties[key];
|
|
194
|
-
}
|
|
195
|
-
else {
|
|
196
|
-
throw new GraphValidationError(`Property ${key} does not exist on node ${id}`);
|
|
197
|
-
}
|
|
198
|
-
}
|
|
199
|
-
}
|
|
200
|
-
}
|
|
201
|
-
}
|
|
202
|
-
nodeObj.properties = rawProperties;
|
|
203
|
-
delete nodeObj.data;
|
|
204
|
-
// SAFETY: `properties` was just set, and `id`/`type` were proved to be
|
|
205
|
-
// strings by the guard above; they are re-stated so the compiler sees it.
|
|
206
|
-
validNodes.push({ ...nodeObj, id, type });
|
|
207
|
-
validNodeIds.add(id);
|
|
208
|
-
}
|
|
209
|
-
const validEdges = [];
|
|
210
|
-
for (const edge of migratedEdges) {
|
|
211
|
-
if (!isObjectValue(edge)) {
|
|
212
|
-
if (skipErrors)
|
|
213
|
-
continue;
|
|
214
|
-
throw new GraphValidationError("Edge entries must be objects");
|
|
215
|
-
}
|
|
216
|
-
const edgeObj = edge;
|
|
217
|
-
const hasRequiredFields = isString(edgeObj.source) &&
|
|
218
|
-
isString(edgeObj.sourceHandle) &&
|
|
219
|
-
isString(edgeObj.target) &&
|
|
220
|
-
isString(edgeObj.targetHandle);
|
|
221
|
-
if (!hasRequiredFields) {
|
|
222
|
-
if (skipErrors)
|
|
223
|
-
continue;
|
|
224
|
-
throw new GraphValidationError("Each edge must have string 'source', 'sourceHandle', 'target', and 'targetHandle' fields");
|
|
225
|
-
}
|
|
226
|
-
const source = edgeObj.source;
|
|
227
|
-
const target = edgeObj.target;
|
|
228
|
-
if (skipErrors &&
|
|
229
|
-
(!validNodeIds.has(source) || !validNodeIds.has(target))) {
|
|
230
|
-
continue;
|
|
231
|
-
}
|
|
232
|
-
// SAFETY: `hasRequiredFields` above proved source/sourceHandle/target/
|
|
233
|
-
// targetHandle are all strings.
|
|
234
|
-
validEdges.push(edgeObj);
|
|
235
|
-
}
|
|
236
|
-
return new Graph({ nodes: validNodes, edges: validEdges });
|
|
237
|
-
}
|
|
238
|
-
static async loadFromDict(data, options) {
|
|
239
|
-
const { resolver, skipErrors = true, allowUndefinedProperties = true } = options;
|
|
240
|
-
const normalized = Graph.fromDict(data, {
|
|
241
|
-
skipErrors,
|
|
242
|
-
// Stryker disable next-line BooleanLiteral: must stay true — property validation happens later against the RESOLVED types, not the saved cache (see comment in loadFromDict)
|
|
243
|
-
allowUndefinedProperties: true
|
|
244
|
-
});
|
|
245
|
-
const resolvedNodes = [];
|
|
246
|
-
const validNodeIds = new Set();
|
|
247
|
-
for (const node of normalized.nodes) {
|
|
248
|
-
const resolved = await resolveNodeTypeWith(resolver, node.type);
|
|
249
|
-
if (!resolved) {
|
|
250
|
-
if (skipErrors)
|
|
251
|
-
continue;
|
|
252
|
-
throw new GraphValidationError(`Invalid node type: ${node.type}`);
|
|
253
|
-
}
|
|
254
|
-
const resolvedPropertyTypes = resolved.propertyTypes ?? {};
|
|
255
|
-
const allowedProperties = new Set(Object.keys(resolvedPropertyTypes));
|
|
256
|
-
const mergedProperties = {
|
|
257
|
-
...(node.properties ?? {})
|
|
258
|
-
};
|
|
259
|
-
const effectiveAllowUndefined = resolved.supportsDynamicInputs || allowUndefinedProperties;
|
|
260
|
-
if (!effectiveAllowUndefined) {
|
|
261
|
-
for (const key of Object.keys(mergedProperties)) {
|
|
262
|
-
if (!allowedProperties.has(key)) {
|
|
263
|
-
if (skipErrors) {
|
|
264
|
-
delete mergedProperties[key];
|
|
265
|
-
}
|
|
266
|
-
else {
|
|
267
|
-
throw new GraphValidationError(`Property ${key} does not exist on node ${node.id}`);
|
|
268
|
-
}
|
|
269
|
-
}
|
|
270
|
-
}
|
|
271
|
-
}
|
|
272
|
-
const descriptorDefaults = resolved.descriptorDefaults ?? {};
|
|
273
|
-
// A per-instance answer, when the resolver has one for this type, is read
|
|
274
|
-
// from the node as saved — the same properties the node will run with.
|
|
275
|
-
const instanceFlags = resolved.resolveInstanceFlags?.(node) ?? {};
|
|
276
|
-
const derivedSlots = resolved.resolveInstanceSlots?.(node);
|
|
277
|
-
const dynamicInputs = mergeDerivedSlots(derivedSlots?.dynamic_inputs, node.dynamic_inputs);
|
|
278
|
-
const dynamicOutputs = mergeDerivedSlots(derivedSlots?.dynamic_outputs, node.dynamic_outputs);
|
|
279
|
-
const hydratedNode = {
|
|
280
|
-
...descriptorDefaults,
|
|
281
|
-
...node,
|
|
282
|
-
...(dynamicInputs && { dynamic_inputs: dynamicInputs }),
|
|
283
|
-
...(dynamicOutputs && { dynamic_outputs: dynamicOutputs }),
|
|
284
|
-
type: resolved.nodeType,
|
|
285
|
-
properties: mergedProperties,
|
|
286
|
-
propertyTypes: {
|
|
287
|
-
...resolvedPropertyTypes,
|
|
288
|
-
// Declared dynamic slots type their handles, but never shadow a
|
|
289
|
-
// static property the registry already declares.
|
|
290
|
-
...Object.fromEntries(Object.entries(dynamicSlotPropertyTypes(dynamicInputs)).filter(([name]) => !Object.hasOwn(resolvedPropertyTypes, name))),
|
|
291
|
-
...(node.propertyTypes ?? {})
|
|
292
|
-
},
|
|
293
|
-
outputs: {
|
|
294
|
-
...(resolved.outputs ?? {}),
|
|
295
|
-
...(node.outputs ?? {})
|
|
296
|
-
},
|
|
297
|
-
// Streaming/control flags: registry metadata (descriptorDefaults) is
|
|
298
|
-
// authoritative when it speaks. An explicit registry boolean — true OR
|
|
299
|
-
// false — wins; the saved value applies only when the resolver omits
|
|
300
|
-
// the flag (undefined), e.g. for unresolved/dynamic types. OR-ing here
|
|
301
|
-
// would let a stale saved `true` survive a registry that migrated the
|
|
302
|
-
// type to buffered/uncontrolled, silently running the wrong mode.
|
|
303
|
-
// A per-instance answer takes the slot the per-type default holds: it
|
|
304
|
-
// was resolved from this node's own properties, so it is the more
|
|
305
|
-
// specific registry opinion, not a saved claim.
|
|
306
|
-
is_streaming_input: instanceFlags.is_streaming_input ??
|
|
307
|
-
descriptorDefaults.is_streaming_input ??
|
|
308
|
-
node.is_streaming_input ??
|
|
309
|
-
false,
|
|
310
|
-
is_streaming_output: descriptorDefaults.is_streaming_output ??
|
|
311
|
-
node.is_streaming_output ??
|
|
312
|
-
false,
|
|
313
|
-
// Correlation metadata is authoritative from the registry. Saved JSON
|
|
314
|
-
// is treated as a cache and overwritten — including when the resolver
|
|
315
|
-
// intentionally returns undefined for a node type that no longer
|
|
316
|
-
// declares correlation. See docs/correlation-design.md §1.
|
|
317
|
-
input_mode: descriptorDefaults.input_mode,
|
|
318
|
-
output_correlation: descriptorDefaults.output_correlation,
|
|
319
|
-
is_controlled: descriptorDefaults.is_controlled ?? node.is_controlled ?? false,
|
|
320
|
-
is_join_node: descriptorDefaults.is_join_node ?? node.is_join_node ?? false,
|
|
321
|
-
// Without this the flag is dropped, because saved workflow JSON never
|
|
322
|
-
// carries it and only the registry knows. `actor.ts` gates the trigger
|
|
323
|
-
// entry point on `node.is_trigger`, so a webhook/manual/file-watch
|
|
324
|
-
// event delivered to a graph hydrated here was accepted and then
|
|
325
|
-
// silently ignored — the node fell through to `genProcess()`, waited
|
|
326
|
-
// for a live adapter that a delivered-event run does not have, and
|
|
327
|
-
// emitted nothing. Every host that passes `resolveNodeType` took this
|
|
328
|
-
// path, including the websocket server.
|
|
329
|
-
is_trigger: descriptorDefaults.is_trigger ?? node.is_trigger ?? false,
|
|
330
|
-
// Retry safety comes from the registry or not at all — note there is
|
|
331
|
-
// no `?? node.retry_safe` here, unlike every flag above. Whether
|
|
332
|
-
// re-running a node duplicates a payment or a publish is a property of
|
|
333
|
-
// its implementation, not of a file: a saved graph asserting
|
|
334
|
-
// `retry_safe: true` for a node whose class never declared it would
|
|
335
|
-
// hand the supervisor a retry on a side-effecting node. An unresolved
|
|
336
|
-
// type therefore gets no retry rather than the saved claim.
|
|
337
|
-
retry_safe: descriptorDefaults.retry_safe ?? false
|
|
338
|
-
};
|
|
339
|
-
resolvedNodes.push(hydratedNode);
|
|
340
|
-
validNodeIds.add(hydratedNode.id);
|
|
341
|
-
}
|
|
342
|
-
const validEdges = normalized.edges.filter((edge) => validNodeIds.has(edge.source) && validNodeIds.has(edge.target));
|
|
343
|
-
// Sound: resolvedNodes were built as HydratedNodeDescriptor above.
|
|
344
|
-
return new Graph({
|
|
345
|
-
nodes: resolvedNodes,
|
|
346
|
-
edges: validEdges
|
|
347
|
-
});
|
|
348
|
-
}
|
|
349
|
-
// -----------------------------------------------------------------------
|
|
350
|
-
// Index building
|
|
351
|
-
// -----------------------------------------------------------------------
|
|
352
|
-
_buildIndices() {
|
|
353
|
-
for (const node of this.nodes) {
|
|
354
|
-
this._nodeIndex.set(node.id, node);
|
|
355
|
-
}
|
|
356
|
-
for (const edge of this.edges) {
|
|
357
|
-
// incoming
|
|
358
|
-
const incoming = this._incomingEdges.get(edge.target);
|
|
359
|
-
if (incoming) {
|
|
360
|
-
incoming.push(edge);
|
|
361
|
-
}
|
|
362
|
-
else {
|
|
363
|
-
this._incomingEdges.set(edge.target, [edge]);
|
|
364
|
-
}
|
|
365
|
-
// outgoing
|
|
366
|
-
const outgoing = this._outgoingEdges.get(edge.source);
|
|
367
|
-
if (outgoing) {
|
|
368
|
-
outgoing.push(edge);
|
|
369
|
-
}
|
|
370
|
-
else {
|
|
371
|
-
this._outgoingEdges.set(edge.source, [edge]);
|
|
372
|
-
}
|
|
373
|
-
// outgoing by handle
|
|
374
|
-
const handleKey = `${edge.source}:${edge.sourceHandle}`;
|
|
375
|
-
const byHandle = this._outgoingByHandle.get(handleKey);
|
|
376
|
-
if (byHandle) {
|
|
377
|
-
byHandle.push(edge);
|
|
378
|
-
}
|
|
379
|
-
else {
|
|
380
|
-
this._outgoingByHandle.set(handleKey, [edge]);
|
|
381
|
-
}
|
|
382
|
-
}
|
|
383
|
-
}
|
|
384
|
-
/**
|
|
385
|
-
* Return the node list with is_controlled set on every control-edge target.
|
|
386
|
-
* In Python, BaseNode.is_controlled() is a runtime method that checks the
|
|
387
|
-
* graph context; in TS we set the flag on the descriptor so the actor knows
|
|
388
|
-
* to use _runControlled(). Node objects are caller-owned (the runner passes
|
|
389
|
-
* `graphData.nodes` straight through), so a target lacking the flag is
|
|
390
|
-
* replaced with a shallow copy — the original is left untouched. Every other
|
|
391
|
-
* node keeps its identity.
|
|
392
|
-
*/
|
|
393
|
-
static _withControlledFlags(nodes, edges) {
|
|
394
|
-
const controlledIds = new Set();
|
|
395
|
-
for (const edge of edges) {
|
|
396
|
-
if (isControlEdge(edge))
|
|
397
|
-
controlledIds.add(edge.target);
|
|
398
|
-
}
|
|
399
|
-
// Stryker disable next-line ConditionalExpression: equivalent — with no control edges the map below returns every node unchanged, so the early return only avoids allocating a new array
|
|
400
|
-
if (controlledIds.size === 0)
|
|
401
|
-
return nodes;
|
|
402
|
-
return nodes.map((node) =>
|
|
403
|
-
// Stryker disable next-line ConditionalExpression,LogicalOperator,BooleanLiteral: equivalent — re-copying an already-controlled node yields the same is_controlled value; the guard only preserves object identity (a micro-optimization)
|
|
404
|
-
controlledIds.has(node.id) && !node.is_controlled
|
|
405
|
-
? { ...node, is_controlled: true }
|
|
406
|
-
: node);
|
|
407
|
-
}
|
|
408
|
-
// -----------------------------------------------------------------------
|
|
409
|
-
// Lookups
|
|
410
|
-
// -----------------------------------------------------------------------
|
|
411
|
-
findNode(id) {
|
|
412
|
-
return this._nodeIndex.get(id);
|
|
413
|
-
}
|
|
414
|
-
/**
|
|
415
|
-
* Return all edges where target == nodeId (incoming edges).
|
|
416
|
-
*/
|
|
417
|
-
findIncomingEdges(nodeId) {
|
|
418
|
-
return this._incomingEdges.get(nodeId) ?? [];
|
|
419
|
-
}
|
|
420
|
-
/**
|
|
421
|
-
* Return all edges where source == nodeId (outgoing edges).
|
|
422
|
-
*/
|
|
423
|
-
findOutgoingEdges(nodeId) {
|
|
424
|
-
return this._outgoingEdges.get(nodeId) ?? [];
|
|
425
|
-
}
|
|
426
|
-
/**
|
|
427
|
-
* Return edges matching a specific (source, sourceHandle) pair. O(1) lookup.
|
|
428
|
-
* Mirrors Python's find_edges(source, source_handle).
|
|
429
|
-
*/
|
|
430
|
-
findEdges(source, sourceHandle) {
|
|
431
|
-
return this._outgoingByHandle.get(`${source}:${sourceHandle}`) ?? [];
|
|
432
|
-
}
|
|
433
|
-
/**
|
|
434
|
-
* Return data (non-control) edges targeting a node.
|
|
435
|
-
*/
|
|
436
|
-
findDataEdges(nodeId) {
|
|
437
|
-
return this.findIncomingEdges(nodeId).filter(isDataEdge);
|
|
438
|
-
}
|
|
439
|
-
getControlEdges(targetId) {
|
|
440
|
-
return this.edges.filter((edge) => isControlEdge(edge) &&
|
|
441
|
-
(targetId === undefined || edge.target === targetId));
|
|
442
|
-
}
|
|
443
|
-
getControllerNodes(targetId) {
|
|
444
|
-
const controlEdges =
|
|
445
|
-
// Stryker disable next-line ConditionalExpression: redundant ternary — getControlEdges(undefined) already returns all control edges, identical to getControlEdges()
|
|
446
|
-
targetId === undefined
|
|
447
|
-
? this.getControlEdges()
|
|
448
|
-
: this.getControlEdges(targetId);
|
|
449
|
-
const ids = new Set(controlEdges.map((e) => e.source));
|
|
450
|
-
return this.nodes.filter((n) => ids.has(n.id));
|
|
451
|
-
}
|
|
452
|
-
getControlledNodes(sourceId) {
|
|
453
|
-
if (sourceId !== undefined) {
|
|
454
|
-
return this.edges
|
|
455
|
-
.filter((edge) => isControlEdge(edge) && edge.source === sourceId)
|
|
456
|
-
.map((edge) => edge.target);
|
|
457
|
-
}
|
|
458
|
-
const ids = new Set(this.getControlEdges().map((e) => e.target));
|
|
459
|
-
return this.nodes.filter((n) => ids.has(n.id));
|
|
460
|
-
}
|
|
461
|
-
// -----------------------------------------------------------------------
|
|
462
|
-
// Input / Output nodes
|
|
463
|
-
// -----------------------------------------------------------------------
|
|
464
|
-
/**
|
|
465
|
-
* Return nodes that have no incoming data edges (source nodes).
|
|
466
|
-
*/
|
|
467
|
-
inputNodes() {
|
|
468
|
-
const hasIncomingData = new Set();
|
|
469
|
-
for (const edge of this.edges) {
|
|
470
|
-
if (isDataEdge(edge)) {
|
|
471
|
-
hasIncomingData.add(edge.target);
|
|
472
|
-
}
|
|
473
|
-
}
|
|
474
|
-
return this.nodes.filter((n) => !hasIncomingData.has(n.id));
|
|
475
|
-
}
|
|
476
|
-
/**
|
|
477
|
-
* Return nodes that have no outgoing data edges (sink nodes).
|
|
478
|
-
*/
|
|
479
|
-
outputNodes() {
|
|
480
|
-
const hasOutgoingData = new Set();
|
|
481
|
-
for (const edge of this.edges) {
|
|
482
|
-
if (isDataEdge(edge)) {
|
|
483
|
-
hasOutgoingData.add(edge.source);
|
|
484
|
-
}
|
|
485
|
-
}
|
|
486
|
-
return this.nodes.filter((n) => !hasOutgoingData.has(n.id));
|
|
487
|
-
}
|
|
488
|
-
// -----------------------------------------------------------------------
|
|
489
|
-
// Streaming upstream detection
|
|
490
|
-
// -----------------------------------------------------------------------
|
|
491
|
-
/**
|
|
492
|
-
* Check whether a node has streaming upstream (i.e. is downstream
|
|
493
|
-
* of a streaming-output node via data edges).
|
|
494
|
-
*/
|
|
495
|
-
hasStreamingUpstream(nodeId) {
|
|
496
|
-
// Stryker disable next-line ConditionalExpression: caching optimization — recomputing yields the same set
|
|
497
|
-
if (!this._streamingUpstream) {
|
|
498
|
-
this._streamingUpstream = this._computeStreamingUpstream();
|
|
499
|
-
}
|
|
500
|
-
return this._streamingUpstream.has(nodeId);
|
|
501
|
-
}
|
|
502
|
-
_computeStreamingUpstream() {
|
|
503
|
-
const result = new Set();
|
|
504
|
-
// BFS from every streaming-output node along data edges
|
|
505
|
-
const streamingSources = this.nodes.filter((n) => n.is_streaming_output);
|
|
506
|
-
// Stryker disable next-line ArrayDeclaration: a non-empty seed is equivalent — a bogus node id has no outgoing edges, so BFS adds nothing
|
|
507
|
-
const queue = [];
|
|
508
|
-
for (const src of streamingSources) {
|
|
509
|
-
for (const edge of this.findOutgoingEdges(src.id)) {
|
|
510
|
-
if (isDataEdge(edge) && !result.has(edge.target)) {
|
|
511
|
-
result.add(edge.target);
|
|
512
|
-
queue.push(edge.target);
|
|
513
|
-
}
|
|
514
|
-
}
|
|
515
|
-
}
|
|
516
|
-
while (queue.length > 0) {
|
|
517
|
-
const nodeId = queue.shift();
|
|
518
|
-
for (const edge of this.findOutgoingEdges(nodeId)) {
|
|
519
|
-
if (isDataEdge(edge) && !result.has(edge.target)) {
|
|
520
|
-
result.add(edge.target);
|
|
521
|
-
queue.push(edge.target);
|
|
522
|
-
}
|
|
523
|
-
}
|
|
524
|
-
}
|
|
525
|
-
return result;
|
|
526
|
-
}
|
|
527
|
-
// -----------------------------------------------------------------------
|
|
528
|
-
// Topological sort (Kahn's algorithm) – returns levels
|
|
529
|
-
// -----------------------------------------------------------------------
|
|
530
|
-
/**
|
|
531
|
-
* Returns nodes grouped into execution levels.
|
|
532
|
-
* Nodes in the same level have no inter-dependencies and can run
|
|
533
|
-
* concurrently. Only data edges define the ordering.
|
|
534
|
-
*/
|
|
535
|
-
topologicalSort(parentId = null) {
|
|
536
|
-
const groupNodeIds = parentId === null
|
|
537
|
-
? new Set(this.nodes
|
|
538
|
-
.filter((node) => node.type === "GroupNode" || node.type.endsWith(".GroupNode"))
|
|
539
|
-
.map((node) => node.id))
|
|
540
|
-
: new Set();
|
|
541
|
-
const isInScope = (node) => {
|
|
542
|
-
const directlyInScope = (node.parent_id ?? null) === parentId;
|
|
543
|
-
const inScopedGroup =
|
|
544
|
-
// Stryker disable next-line ConditionalExpression: the `!= null` guard is redundant — groupNodeIds only holds real node-id strings, so has(null/undefined) is already false
|
|
545
|
-
node.parent_id != null && groupNodeIds.has(node.parent_id);
|
|
546
|
-
return directlyInScope || inScopedGroup;
|
|
547
|
-
};
|
|
548
|
-
const filteredNodes = this.nodes.filter(isInScope);
|
|
549
|
-
const filteredNodeIds = new Set(filteredNodes.map((node) => node.id));
|
|
550
|
-
// Only data edges define the ordering (see docstring). Including control
|
|
551
|
-
// edges would turn a legal data-A→B + control-B→A controller feedback
|
|
552
|
-
// pattern into a mixed cycle, silently dropping both nodes from the
|
|
553
|
-
// returned levels.
|
|
554
|
-
// Loop back edges close the only cycles a graph may contain; leaving them
|
|
555
|
-
// out keeps loop bodies in the levels (docs/workflow-loops.md).
|
|
556
|
-
const nodeTypeOf = (id) => this.findNode(id)?.type;
|
|
557
|
-
const filteredEdges = this.edges.filter((edge) => isDataEdge(edge) &&
|
|
558
|
-
!isLoopBackEdge(edge, nodeTypeOf) &&
|
|
559
|
-
filteredNodeIds.has(edge.source) &&
|
|
560
|
-
filteredNodeIds.has(edge.target));
|
|
561
|
-
// In-degree count across filtered edges.
|
|
562
|
-
const inDeg = new Map();
|
|
563
|
-
for (const node of filteredNodes) {
|
|
564
|
-
inDeg.set(node.id, 0);
|
|
565
|
-
}
|
|
566
|
-
for (const edge of filteredEdges) {
|
|
567
|
-
// Stryker disable next-line LogicalOperator: equivalent — same-level nodes are all processed before the next level, so an off-by-one in-degree count does not change the produced levels
|
|
568
|
-
inDeg.set(edge.target, (inDeg.get(edge.target) ?? 0) + 1);
|
|
569
|
-
}
|
|
570
|
-
// Seed with zero-in-degree nodes
|
|
571
|
-
// Stryker disable next-line ArrayDeclaration: a non-empty seed is equivalent — a bogus id matches no node/edge and is dropped
|
|
572
|
-
let currentLevel = [];
|
|
573
|
-
for (const [id, deg] of inDeg) {
|
|
574
|
-
if (deg === 0)
|
|
575
|
-
currentLevel.push(id);
|
|
576
|
-
}
|
|
577
|
-
const levels = [];
|
|
578
|
-
const visited = new Set();
|
|
579
|
-
while (currentLevel.length > 0) {
|
|
580
|
-
const levelNodes = [];
|
|
581
|
-
const nextLevel = [];
|
|
582
|
-
for (const id of currentLevel) {
|
|
583
|
-
visited.add(id);
|
|
584
|
-
const node = this.findNode(id);
|
|
585
|
-
// Stryker disable next-line ConditionalExpression: equivalent — ids come from filteredNodes, so findNode always returns a node
|
|
586
|
-
if (node)
|
|
587
|
-
levelNodes.push(node);
|
|
588
|
-
for (const edge of filteredEdges) {
|
|
589
|
-
if (edge.source !== id)
|
|
590
|
-
continue;
|
|
591
|
-
// Stryker disable next-line LogicalOperator: equivalent — every edge target was seeded in inDeg, and same-level processing means the decrement order does not change the produced levels
|
|
592
|
-
const newDeg = (inDeg.get(edge.target) ?? 1) - 1;
|
|
593
|
-
inDeg.set(edge.target, newDeg);
|
|
594
|
-
if (newDeg === 0 && !visited.has(edge.target)) {
|
|
595
|
-
nextLevel.push(edge.target);
|
|
596
|
-
}
|
|
597
|
-
}
|
|
598
|
-
}
|
|
599
|
-
// Stryker disable next-line ConditionalExpression,EqualityOperator: equivalent — currentLevel ids all resolve to nodes, so levelNodes is never empty when currentLevel is non-empty
|
|
600
|
-
if (levelNodes.length > 0)
|
|
601
|
-
levels.push(levelNodes);
|
|
602
|
-
currentLevel = nextLevel;
|
|
603
|
-
}
|
|
604
|
-
// Stryker disable next-line ConditionalExpression,EqualityOperator,BlockStatement: this only emits a diagnostic warning; the returned levels are unaffected
|
|
605
|
-
if (visited.size !== filteredNodes.length) {
|
|
606
|
-
// Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
|
|
607
|
-
log.warn("Graph contains at least one cycle", {
|
|
608
|
-
visited: visited.size,
|
|
609
|
-
total: filteredNodes.length
|
|
610
|
-
});
|
|
611
|
-
}
|
|
612
|
-
return levels;
|
|
613
|
-
}
|
|
614
|
-
// -----------------------------------------------------------------------
|
|
615
|
-
// Input / Output schema (T-MSG-5)
|
|
616
|
-
// -----------------------------------------------------------------------
|
|
617
|
-
/**
|
|
618
|
-
* Build a JSON Schema object from input nodes (type contains "Input").
|
|
619
|
-
* Each input node contributes a property named after node.name (or node.id).
|
|
620
|
-
*/
|
|
621
|
-
getInputSchema() {
|
|
622
|
-
// Match the input-node namespace, not any type merely CONTAINING "Input":
|
|
623
|
-
// a loose substring pulled in mid-graph nodes like
|
|
624
|
-
// `nodetool.test.StreamingInputProcessor` (phantom required input) and
|
|
625
|
-
// missed real ones like `nodetool.input.MessageDeconstructor`.
|
|
626
|
-
return this._buildSchema((n) => n.type.startsWith("nodetool.input."));
|
|
627
|
-
}
|
|
628
|
-
/**
|
|
629
|
-
* Build a JSON Schema object from output nodes (`nodetool.output.*`).
|
|
630
|
-
*/
|
|
631
|
-
getOutputSchema() {
|
|
632
|
-
// Namespace match, not a substring: `nodetool.generators.
|
|
633
|
-
// StructuredOutputGenerator` / `nodetool.audio.realtime.AudioOutput`
|
|
634
|
-
// contain "Output" but are not workflow output nodes.
|
|
635
|
-
return this._buildSchema((n) => n.type.startsWith("nodetool.output."));
|
|
636
|
-
}
|
|
637
|
-
_buildSchema(filter) {
|
|
638
|
-
const properties = {};
|
|
639
|
-
const required = [];
|
|
640
|
-
for (const node of this.nodes) {
|
|
641
|
-
if (!filter(node))
|
|
642
|
-
continue;
|
|
643
|
-
const name = node.name || node.id;
|
|
644
|
-
// Use the first output type to determine the JSON Schema type
|
|
645
|
-
const outputType = node.outputs
|
|
646
|
-
? Object.values(node.outputs)[0]
|
|
647
|
-
: undefined;
|
|
648
|
-
properties[name] = { type: nodeTypeToJsonSchema(outputType) };
|
|
649
|
-
required.push(name);
|
|
650
|
-
}
|
|
651
|
-
return { properties, required };
|
|
652
|
-
}
|
|
653
|
-
// -----------------------------------------------------------------------
|
|
654
|
-
// Validation
|
|
655
|
-
// -----------------------------------------------------------------------
|
|
656
|
-
/**
|
|
657
|
-
* Validate the graph structure.
|
|
658
|
-
* Throws GraphValidationError on problems.
|
|
659
|
-
*/
|
|
660
|
-
validate() {
|
|
661
|
-
this.validateEdgeEndpoints();
|
|
662
|
-
this.validateDataEdgeSourceHandles();
|
|
663
|
-
this.validateControlEdges();
|
|
664
|
-
this.validateEdgeTypes();
|
|
665
|
-
}
|
|
666
|
-
/**
|
|
667
|
-
* Verify that every data edge's `sourceHandle` is a declared output of its
|
|
668
|
-
* source node. Without this, an edge wired to a nonexistent output handle
|
|
669
|
-
* passes validation and then silently never delivers a value at runtime
|
|
670
|
-
* (`validateEdgeTypes` skips it for lack of a source type), leaving the
|
|
671
|
-
* target node waiting forever.
|
|
672
|
-
*
|
|
673
|
-
* Only enforced when the source node declares a non-empty static `outputs`
|
|
674
|
-
* map and does not produce dynamic outputs (whose handles aren't known
|
|
675
|
-
* statically). Nodes without output metadata are left untouched.
|
|
676
|
-
*/
|
|
677
|
-
validateDataEdgeSourceHandles() {
|
|
678
|
-
for (const edge of this.edges) {
|
|
679
|
-
if (!isDataEdge(edge))
|
|
680
|
-
continue;
|
|
681
|
-
const sourceNode = this._nodeIndex.get(edge.source);
|
|
682
|
-
// Endpoint existence is enforced by validateEdgeEndpoints().
|
|
683
|
-
if (!sourceNode)
|
|
684
|
-
continue;
|
|
685
|
-
const outputs = sourceNode.outputs;
|
|
686
|
-
if (!outputs || Object.keys(outputs).length === 0)
|
|
687
|
-
continue;
|
|
688
|
-
if (sourceNode.dynamic_outputs &&
|
|
689
|
-
Object.keys(sourceNode.dynamic_outputs).length > 0) {
|
|
690
|
-
continue;
|
|
691
|
-
}
|
|
692
|
-
// Own-property check, not `in`: `in` walks the prototype chain, so a
|
|
693
|
-
// sourceHandle named after an Object.prototype member ("toString",
|
|
694
|
-
// "constructor", …) would spuriously pass this guard and then hang at
|
|
695
|
-
// runtime when the source node emits nothing on that handle.
|
|
696
|
-
if (!Object.hasOwn(outputs, edge.sourceHandle)) {
|
|
697
|
-
throw new GraphValidationError(`Edge ${edge.id ?? syntheticEdgeId(edge.source, edge.sourceHandle, edge.target, edge.targetHandle)} ` +
|
|
698
|
-
`references unknown output "${edge.sourceHandle}" on node "${edge.source}"` +
|
|
699
|
-
`${sourceNode.type ? ` (${sourceNode.type})` : ""}`, [
|
|
700
|
-
{
|
|
701
|
-
nodeId: edge.source,
|
|
702
|
-
nodeType: sourceNode.type,
|
|
703
|
-
property: edge.sourceHandle,
|
|
704
|
-
message: `Unknown output "${edge.sourceHandle}"`
|
|
705
|
-
}
|
|
706
|
-
]);
|
|
707
|
-
}
|
|
708
|
-
}
|
|
709
|
-
}
|
|
710
|
-
/**
|
|
711
|
-
* Verify that every edge references existing nodes.
|
|
712
|
-
*/
|
|
713
|
-
validateEdgeEndpoints() {
|
|
714
|
-
for (const edge of this.edges) {
|
|
715
|
-
// Self-loops pass control-cycle detection and deadlock at runtime:
|
|
716
|
-
// the node waits on an input handle that only the node itself can
|
|
717
|
-
// close. The correlation analyzer reports data self-loops as cycles;
|
|
718
|
-
// this guard also covers direct validate() callers and control edges.
|
|
719
|
-
if (edge.source === edge.target) {
|
|
720
|
-
throw new GraphValidationError(`Edge ${edge.id ?? syntheticEdgeId(edge.source, edge.sourceHandle, edge.target, edge.targetHandle)} ` +
|
|
721
|
-
`connects node "${edge.source}" to itself; self-loop edges are not supported`, [
|
|
722
|
-
{
|
|
723
|
-
nodeId: edge.source,
|
|
724
|
-
property: edge.targetHandle,
|
|
725
|
-
message: "Self-loop edges are not supported"
|
|
726
|
-
}
|
|
727
|
-
]);
|
|
728
|
-
}
|
|
729
|
-
if (!this._nodeIndex.has(edge.source)) {
|
|
730
|
-
// Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
|
|
731
|
-
log.error("Edge references unknown source node", {
|
|
732
|
-
source: edge.source
|
|
733
|
-
});
|
|
734
|
-
throw new GraphValidationError(`Edge references unknown source node: ${edge.source}`);
|
|
735
|
-
}
|
|
736
|
-
if (!this._nodeIndex.has(edge.target)) {
|
|
737
|
-
// Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
|
|
738
|
-
log.error("Edge references unknown target node", {
|
|
739
|
-
target: edge.target
|
|
740
|
-
});
|
|
741
|
-
throw new GraphValidationError(`Edge references unknown target node: ${edge.target}`);
|
|
742
|
-
}
|
|
743
|
-
}
|
|
744
|
-
}
|
|
745
|
-
/**
|
|
746
|
-
* Validate control edges:
|
|
747
|
-
* - Source and target must exist.
|
|
748
|
-
* - Target handle must be "__control__".
|
|
749
|
-
* - No cycles in control edges.
|
|
750
|
-
*/
|
|
751
|
-
validateControlEdges() {
|
|
752
|
-
const controlEdges = this.getControlEdges();
|
|
753
|
-
for (const edge of controlEdges) {
|
|
754
|
-
if (edge.targetHandle !== "__control__") {
|
|
755
|
-
throw new GraphValidationError(`Control edge target handle must be "__control__", ` +
|
|
756
|
-
`got "${edge.targetHandle}" on edge ${edge.id ?? "(no id)"}`);
|
|
757
|
-
}
|
|
758
|
-
}
|
|
759
|
-
// Cycle detection in control edges (DFS)
|
|
760
|
-
this._checkCircularControl(controlEdges);
|
|
761
|
-
}
|
|
762
|
-
/**
|
|
763
|
-
* Validate type compatibility between connected edge endpoints.
|
|
764
|
-
* For each data edge, checks if the source output type is compatible
|
|
765
|
-
* with the target input type. Compatible means: same type, one is "any",
|
|
766
|
-
* or numeric widening (int -> float).
|
|
767
|
-
*/
|
|
768
|
-
validateEdgeTypes() {
|
|
769
|
-
for (const edge of this.edges) {
|
|
770
|
-
// Stryker disable next-line ConditionalExpression: equivalent — a control edge has no source output type for its handle and is skipped by the !sourceType guard below anyway
|
|
771
|
-
if (isControlEdge(edge))
|
|
772
|
-
continue;
|
|
773
|
-
const sourceNode = this._nodeIndex.get(edge.source);
|
|
774
|
-
const targetNode = this._nodeIndex.get(edge.target);
|
|
775
|
-
if (!sourceNode || !targetNode)
|
|
776
|
-
continue;
|
|
777
|
-
// Get source output type from node.outputs[sourceHandle]. Own-property
|
|
778
|
-
// guard: a prototype-named handle ("toString", "constructor", …) would
|
|
779
|
-
// otherwise read an inherited Object.prototype member (a truthy function)
|
|
780
|
-
// and pass it to TypeMetadata.fromString, crashing on a runnable graph.
|
|
781
|
-
const sourceType = sourceNode.outputs &&
|
|
782
|
-
Object.hasOwn(sourceNode.outputs, edge.sourceHandle)
|
|
783
|
-
? sourceNode.outputs[edge.sourceHandle]
|
|
784
|
-
: undefined;
|
|
785
|
-
if (!sourceType)
|
|
786
|
-
continue; // no type info, skip
|
|
787
|
-
// Get target input type: propertyTypes is the authoritative map after
|
|
788
|
-
// graph load. Fall back to a property value carrying an explicit
|
|
789
|
-
// `type` descriptor for raw payloads. Plain string property values
|
|
790
|
-
// are runtime data (e.g. saved literals), never type names.
|
|
791
|
-
let targetType = targetNode.propertyTypes &&
|
|
792
|
-
Object.hasOwn(targetNode.propertyTypes, edge.targetHandle)
|
|
793
|
-
? targetNode.propertyTypes[edge.targetHandle]
|
|
794
|
-
: undefined;
|
|
795
|
-
if (!targetType) {
|
|
796
|
-
const targetProp = targetNode.properties?.[edge.targetHandle];
|
|
797
|
-
if (isObjectValue(targetProp) &&
|
|
798
|
-
"type" in targetProp &&
|
|
799
|
-
isString(targetProp.type)) {
|
|
800
|
-
targetType = targetProp.type;
|
|
801
|
-
}
|
|
802
|
-
}
|
|
803
|
-
if (!targetType)
|
|
804
|
-
continue; // no type info, skip
|
|
805
|
-
// Use TypeMetadata for full compatibility check (handles list[X], union, numeric widening)
|
|
806
|
-
const sourceMeta = TypeMetadata.fromString(sourceType);
|
|
807
|
-
const targetMeta = TypeMetadata.fromString(targetType);
|
|
808
|
-
// Scalar-into-list aggregation: a value edge may feed a list-typed
|
|
809
|
-
// input (multi-edge list inputs collect items into a list, and a
|
|
810
|
-
// single item edge wraps). Accept when the source is compatible with
|
|
811
|
-
// the list's element type.
|
|
812
|
-
const elementCompatible = targetMeta.isListType() &&
|
|
813
|
-
!sourceMeta.isListType() &&
|
|
814
|
-
(targetMeta.args.length === 0 ||
|
|
815
|
-
sourceMeta.isCompatibleWith(targetMeta.args[0]));
|
|
816
|
-
if (!sourceMeta.isCompatibleWith(targetMeta) && !elementCompatible) {
|
|
817
|
-
// Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
|
|
818
|
-
log.warn("Type mismatch on edge", {
|
|
819
|
-
source: edge.source,
|
|
820
|
-
target: edge.target,
|
|
821
|
-
sourceType,
|
|
822
|
-
targetType
|
|
823
|
-
});
|
|
824
|
-
throw new GraphValidationError(`Type mismatch on edge ${edge.id ?? syntheticEdgeId(edge.source, edge.sourceHandle, edge.target, edge.targetHandle)}: ` +
|
|
825
|
-
`source outputs "${sourceType}" but target expects "${targetType}"`);
|
|
826
|
-
}
|
|
827
|
-
}
|
|
828
|
-
}
|
|
829
|
-
_checkCircularControl(controlEdges) {
|
|
830
|
-
// Build adjacency list for control edges only
|
|
831
|
-
const adj = new Map();
|
|
832
|
-
for (const edge of controlEdges) {
|
|
833
|
-
const targets = adj.get(edge.source);
|
|
834
|
-
if (targets) {
|
|
835
|
-
targets.push(edge.target);
|
|
836
|
-
}
|
|
837
|
-
else {
|
|
838
|
-
adj.set(edge.source, [edge.target]);
|
|
839
|
-
}
|
|
840
|
-
}
|
|
841
|
-
const WHITE = 0, GRAY = 1, BLACK = 2;
|
|
842
|
-
const color = new Map();
|
|
843
|
-
const dfs = (node) => {
|
|
844
|
-
color.set(node, GRAY);
|
|
845
|
-
for (const neighbor of adj.get(node) ?? []) {
|
|
846
|
-
const c = color.get(neighbor) ?? WHITE;
|
|
847
|
-
if (c === GRAY)
|
|
848
|
-
return true; // back edge → cycle
|
|
849
|
-
// Stryker disable next-line ConditionalExpression,EqualityOperator: the `c === WHITE` guard only avoids redundant re-visits; cycles are still caught by the GRAY check above, so the detection result is unchanged
|
|
850
|
-
if (c === WHITE && dfs(neighbor))
|
|
851
|
-
return true;
|
|
852
|
-
}
|
|
853
|
-
color.set(node, BLACK);
|
|
854
|
-
return false;
|
|
855
|
-
};
|
|
856
|
-
for (const node of adj.keys()) {
|
|
857
|
-
// Stryker disable next-line ConditionalExpression: equivalent — re-running dfs on an already-coloured node is redundant work with the same cycle-detection result
|
|
858
|
-
if ((color.get(node) ?? WHITE) === WHITE) {
|
|
859
|
-
if (dfs(node)) {
|
|
860
|
-
// Stryker disable next-line StringLiteral: diagnostic log message only
|
|
861
|
-
log.error("Graph contains a cycle in control edges");
|
|
862
|
-
throw new GraphValidationError("Graph contains a cycle in control edges");
|
|
863
|
-
}
|
|
864
|
-
}
|
|
865
|
-
}
|
|
866
|
-
}
|
|
867
|
-
}
|
|
1
|
+
export * from "@nodetool-ai/execution-core/graph";
|
|
868
2
|
//# sourceMappingURL=graph.js.map
|