@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/runner.js ADDED
@@ -0,0 +1,1018 @@
1
+ /**
2
+ * WorkflowRunner – DAG orchestration.
3
+ *
4
+ * Port of src/nodetool/workflows/workflow_runner.py.
5
+ *
6
+ * Responsibilities:
7
+ * - Graph validation and initialization.
8
+ * - Inbox creation with upstream counts.
9
+ * - Input value dispatch to input nodes.
10
+ * - Actor spawning with concurrent execution.
11
+ * - Output routing via send_messages.
12
+ * - Edge counter tracking for EOS propagation.
13
+ * - Control event dispatch.
14
+ * - Completion detection.
15
+ */
16
+ import { createLogger } from "@nodetool-ai/config";
17
+ import { TypeMetadata } from "@nodetool-ai/protocol";
18
+ const log = createLogger("nodetool.kernel.runner");
19
+ import { withWorkflowSpan } from "@nodetool-ai/runtime";
20
+ import { isControlEdge, isDataEdge } from "@nodetool-ai/protocol";
21
+ import { Graph, GraphValidationError } from "./graph.js";
22
+ import { rewriteBypassedNodes } from "./graph-utils.js";
23
+ import { NodeInbox } from "./inbox.js";
24
+ import { NodeActor } from "./actor.js";
25
+ // ---------------------------------------------------------------------------
26
+ // WorkflowRunner
27
+ // ---------------------------------------------------------------------------
28
+ export class WorkflowRunner {
29
+ jobId;
30
+ _graph;
31
+ _options;
32
+ /** Per-node inboxes. */
33
+ _inboxes = new Map();
34
+ /** Per-edge message counters (for EdgeUpdate tracking). */
35
+ _edgeCounters = new Map();
36
+ /** Per-edge streaming flag (true if on a streaming path). */
37
+ _streamingEdges = new Map();
38
+ /** Control edges that have routed at least one event (used for diagnostics). */
39
+ _controlEdgesRouted = new Set();
40
+ /**
41
+ * Multi-edge list inputs: nodeId → set of handles that aggregate
42
+ * multiple edges into a list.
43
+ */
44
+ _multiEdgeListInputs = new Map();
45
+ /** Collected outputs from output nodes. */
46
+ _outputs = new Map();
47
+ /** All emitted messages. */
48
+ _messages = [];
49
+ /** Cancellation flag. */
50
+ _cancelled = false;
51
+ /** Pending response resolvers for sendControlEvent. nodeId → resolver */
52
+ _pendingControlResponses = new Map();
53
+ constructor(jobId, options) {
54
+ this.jobId = jobId;
55
+ this._options = options;
56
+ }
57
+ // -----------------------------------------------------------------------
58
+ // Public API
59
+ // -----------------------------------------------------------------------
60
+ /**
61
+ * Push a streaming input value into the graph while it is running.
62
+ * The input name matches an input-node's `name` (or `id` fallback).
63
+ */
64
+ async pushInputValue(inputName, value, sourceHandle) {
65
+ if (!this._graph) {
66
+ throw new Error("Workflow has not been started");
67
+ }
68
+ const inputNodes = this._resolveInputNodes(inputName);
69
+ if (inputNodes.length === 0) {
70
+ throw new Error(`Input node not found: ${inputName}`);
71
+ }
72
+ for (const node of inputNodes) {
73
+ const outgoing = this._graph
74
+ .findOutgoingEdges(node.id)
75
+ .filter(isDataEdge);
76
+ for (const edge of outgoing) {
77
+ if (sourceHandle && edge.sourceHandle !== sourceHandle) {
78
+ continue;
79
+ }
80
+ const targetInbox = this._inboxes.get(edge.target);
81
+ if (!targetInbox)
82
+ continue;
83
+ await targetInbox.put(edge.targetHandle, value);
84
+ this._incrementEdgeCounter(edge);
85
+ }
86
+ }
87
+ }
88
+ /**
89
+ * Signal end-of-stream for an input node so downstream handles can complete.
90
+ */
91
+ finishInputStream(inputName, sourceHandle) {
92
+ if (!this._graph) {
93
+ throw new Error("Workflow has not been started");
94
+ }
95
+ const inputNodes = this._resolveInputNodes(inputName);
96
+ if (inputNodes.length === 0) {
97
+ throw new Error(`Input node not found: ${inputName}`);
98
+ }
99
+ for (const node of inputNodes) {
100
+ const outgoing = this._graph
101
+ .findOutgoingEdges(node.id)
102
+ .filter(isDataEdge);
103
+ for (const edge of outgoing) {
104
+ if (sourceHandle && edge.sourceHandle !== sourceHandle) {
105
+ continue;
106
+ }
107
+ const targetInbox = this._inboxes.get(edge.target);
108
+ if (!targetInbox)
109
+ continue;
110
+ targetInbox.markSourceDone(edge.targetHandle);
111
+ }
112
+ }
113
+ }
114
+ /**
115
+ * Execute a workflow graph.
116
+ */
117
+ async run(request, graphData) {
118
+ return withWorkflowSpan({
119
+ workflowId: request.workflow_id ?? undefined,
120
+ nodeCount: graphData.nodes.length,
121
+ extra: { "workflow.job_id": request.job_id }
122
+ }, () => this._runImpl(request, graphData));
123
+ }
124
+ async _runImpl(request, graphData) {
125
+ this._resetRunState();
126
+ try {
127
+ log.info("Workflow started", {
128
+ jobId: request.job_id,
129
+ workflowId: request.workflow_id
130
+ });
131
+ // Rewrite the graph to route around nodes marked
132
+ // `ui_properties.bypassed === true`. Each outgoing edge of a
133
+ // bypassed node is re-attached to the matching upstream source
134
+ // (by type compatibility); outgoing edges with no compatible
135
+ // upstream are dropped, as is the bypassed node itself.
136
+ const effectiveGraph = rewriteBypassedNodes(graphData);
137
+ this._graph = new Graph(effectiveGraph);
138
+ // Python parity: _filter_invalid_edges — silently remove edges
139
+ // whose source or target node doesn't exist in the graph.
140
+ this._filterInvalidEdges();
141
+ // Analyze streaming paths (Python parity: _analyze_streaming)
142
+ this._analyzeStreaming();
143
+ // Validate
144
+ this._graph.validate();
145
+ // Pre-flight node validation: catch missing required fields and
146
+ // unset model selections before spawning any actors.
147
+ this._validateNodes();
148
+ // Emit job_update: running
149
+ this._emit({
150
+ type: "job_update",
151
+ status: "running",
152
+ job_id: request.job_id,
153
+ workflow_id: request.workflow_id ?? null
154
+ });
155
+ // Detect multi-edge list inputs
156
+ this._detectMultiEdgeListInputs();
157
+ // Initialize inboxes
158
+ this._initializeInboxes();
159
+ // Initialize all nodes (Python parity: initialize_graph)
160
+ await this._initializeGraph();
161
+ // Dispatch input parameters
162
+ await this._dispatchInputs(request.params ?? {});
163
+ // Bind sendControlEvent to processing context so agent nodes can dispatch
164
+ // control events to controlled nodes and await their results.
165
+ if (this._options.executionContext &&
166
+ typeof this._options.executionContext.setSendControlEvent === "function") {
167
+ this._options.executionContext.setSendControlEvent((targetNodeId, properties) => this.sendControlEvent(targetNodeId, properties));
168
+ }
169
+ // Process graph (spawn actors)
170
+ await this._processGraph();
171
+ // Post-completion: drain any edges that still have pending/open state
172
+ this._drainActiveEdges();
173
+ const status = this._cancelled ? "cancelled" : "completed";
174
+ log.info("Workflow completed", { jobId: request.job_id, status });
175
+ this._emit({
176
+ type: "job_update",
177
+ status,
178
+ job_id: request.job_id,
179
+ workflow_id: request.workflow_id ?? null
180
+ });
181
+ return {
182
+ outputs: Object.fromEntries(this._outputs),
183
+ messages: this._messages,
184
+ status
185
+ };
186
+ }
187
+ catch (err) {
188
+ const message = err instanceof Error ? err.message : String(err);
189
+ log.error("Workflow failed", { jobId: request.job_id, error: message });
190
+ // Drain active edges on error for front-end cleanup
191
+ this._drainActiveEdges();
192
+ const validationIssues = err instanceof GraphValidationError && err.issues.length > 0
193
+ ? err.issues
194
+ .filter((i) => !!i.nodeId)
195
+ .map((i) => ({
196
+ node_id: i.nodeId,
197
+ node_type: i.nodeType ?? null,
198
+ property: i.property ?? "",
199
+ message: i.message
200
+ }))
201
+ : null;
202
+ this._emit({
203
+ type: "job_update",
204
+ status: "failed",
205
+ job_id: request.job_id,
206
+ workflow_id: request.workflow_id ?? null,
207
+ error: message,
208
+ validation_issues: validationIssues
209
+ });
210
+ return {
211
+ outputs: Object.fromEntries(this._outputs),
212
+ messages: this._messages,
213
+ status: "failed",
214
+ error: message
215
+ };
216
+ }
217
+ }
218
+ _resetRunState() {
219
+ this._inboxes = new Map();
220
+ this._edgeCounters = new Map();
221
+ this._streamingEdges = new Map();
222
+ this._controlEdgesRouted = new Set();
223
+ this._multiEdgeListInputs = new Map();
224
+ this._outputs = new Map();
225
+ this._messages = [];
226
+ this._cancelled = false;
227
+ this._pendingControlResponses = new Map();
228
+ }
229
+ /**
230
+ * Cancel the running workflow.
231
+ */
232
+ cancel() {
233
+ log.info("Job cancelled", { jobId: this.jobId });
234
+ this._cancelled = true;
235
+ // Close all inboxes to unblock waiting actors
236
+ for (const inbox of this._inboxes.values()) {
237
+ void inbox.closeAll();
238
+ }
239
+ }
240
+ // -----------------------------------------------------------------------
241
+ // Invalid edge filtering (Python parity: _filter_invalid_edges)
242
+ // -----------------------------------------------------------------------
243
+ /**
244
+ * Remove edges whose source or target node doesn't exist in the graph.
245
+ * Reconstructs the graph without dangling edges.
246
+ */
247
+ _filterInvalidEdges() {
248
+ const validEdges = this._graph.edges.filter((edge) => this._graph.findNode(edge.source) !== undefined &&
249
+ this._graph.findNode(edge.target) !== undefined);
250
+ if (validEdges.length < this._graph.edges.length) {
251
+ log.warn("Filtered invalid edges", {
252
+ removed: this._graph.edges.length - validEdges.length,
253
+ remaining: validEdges.length
254
+ });
255
+ this._graph = new Graph({
256
+ nodes: [...this._graph.nodes],
257
+ edges: validEdges
258
+ });
259
+ }
260
+ }
261
+ /**
262
+ * Run the optional `validateNode` callback for every node in the graph,
263
+ * passing the set of property handles that have an incoming data edge.
264
+ * Aggregates issues across nodes and throws a single GraphValidationError.
265
+ */
266
+ _validateNodes() {
267
+ const validator = this._options.validateNode;
268
+ if (!validator)
269
+ return;
270
+ // Build map: nodeId -> set of targetHandles with an incoming data edge.
271
+ const connectedByNode = new Map();
272
+ for (const edge of this._graph.edges) {
273
+ if (!isDataEdge(edge))
274
+ continue;
275
+ let handles = connectedByNode.get(edge.target);
276
+ if (!handles) {
277
+ handles = new Set();
278
+ connectedByNode.set(edge.target, handles);
279
+ }
280
+ handles.add(edge.targetHandle);
281
+ }
282
+ const issues = [];
283
+ for (const node of this._graph.nodes) {
284
+ const handles = connectedByNode.get(node.id) ?? new Set();
285
+ const nodeIssues = validator(node, handles);
286
+ if (nodeIssues && nodeIssues.length > 0) {
287
+ for (const issue of nodeIssues) {
288
+ issues.push({
289
+ nodeId: issue.nodeId ?? node.id,
290
+ nodeType: issue.nodeType ?? node.type,
291
+ property: issue.property,
292
+ message: issue.message
293
+ });
294
+ }
295
+ }
296
+ }
297
+ if (issues.length > 0) {
298
+ const lines = issues.map((issue) => {
299
+ const where = ` on node "${issue.nodeId}"${issue.nodeType ? ` (${issue.nodeType})` : ""}`;
300
+ return ` - ${issue.message}${where}`;
301
+ });
302
+ throw new GraphValidationError(`Graph validation failed with ${issues.length} issue(s):\n${lines.join("\n")}`, issues.map((issue) => ({
303
+ nodeId: issue.nodeId,
304
+ nodeType: issue.nodeType,
305
+ property: issue.property,
306
+ message: issue.message
307
+ })));
308
+ }
309
+ }
310
+ // -----------------------------------------------------------------------
311
+ // Node initialization
312
+ // -----------------------------------------------------------------------
313
+ async _initializeGraph() {
314
+ for (const node of this._graph.nodes) {
315
+ const executor = this._options.resolveExecutor(node);
316
+ if (executor.initialize) {
317
+ await executor.initialize();
318
+ }
319
+ }
320
+ }
321
+ // -----------------------------------------------------------------------
322
+ // Inbox initialization
323
+ // -----------------------------------------------------------------------
324
+ _initializeInboxes() {
325
+ for (const node of this._graph.nodes) {
326
+ const inbox = new NodeInbox(this._options.bufferLimit ?? null);
327
+ // Count upstream sources per handle from data edges
328
+ const incomingData = this._graph.findDataEdges(node.id);
329
+ const handleCounts = new Map();
330
+ for (const edge of incomingData) {
331
+ const cur = handleCounts.get(edge.targetHandle) ?? 0;
332
+ handleCounts.set(edge.targetHandle, cur + 1);
333
+ }
334
+ // Also count control edges
335
+ const incomingControl = this._graph
336
+ .findIncomingEdges(node.id)
337
+ .filter(isControlEdge);
338
+ if (incomingControl.length > 0) {
339
+ const uniqueControllerCount = new Set(incomingControl.map((e) => e.source)).size;
340
+ handleCounts.set("__control__", (handleCounts.get("__control__") ?? 0) + uniqueControllerCount);
341
+ }
342
+ for (const [handle, count] of handleCounts) {
343
+ inbox.addUpstream(handle, count);
344
+ }
345
+ this._inboxes.set(node.id, inbox);
346
+ }
347
+ }
348
+ // -----------------------------------------------------------------------
349
+ // Multi-edge list detection
350
+ // -----------------------------------------------------------------------
351
+ _detectMultiEdgeListInputs() {
352
+ // Find handles that receive more than one edge AND whose property type
353
+ // is a list type. Non-list handles with multiple edges should NOT be
354
+ // marked for aggregation (Python parity: _classify_list_inputs).
355
+ const handleEdgeCounts = new Map(); // key = nodeId:handle
356
+ for (const edge of this._graph.edges) {
357
+ if (isControlEdge(edge))
358
+ continue;
359
+ const key = `${edge.target}:${edge.targetHandle}`;
360
+ handleEdgeCounts.set(key, (handleEdgeCounts.get(key) ?? 0) + 1);
361
+ }
362
+ for (const [key, count] of handleEdgeCounts) {
363
+ if (count > 1) {
364
+ const sepIdx = key.lastIndexOf(":");
365
+ const nodeId = key.substring(0, sepIdx);
366
+ const handle = key.substring(sepIdx + 1);
367
+ // Look up the target node to check its property type
368
+ const node = this._graph.findNode(nodeId);
369
+ if (!node)
370
+ continue;
371
+ // Validate that the handle's type is a list type
372
+ const propertyTypes = node.propertyTypes;
373
+ if (propertyTypes) {
374
+ const typeStr = propertyTypes[handle];
375
+ if (typeStr) {
376
+ const meta = TypeMetadata.fromString(typeStr);
377
+ if (!meta.isListType()) {
378
+ // Multiple edges to non-list property — skip aggregation
379
+ continue;
380
+ }
381
+ }
382
+ }
383
+ if (!this._multiEdgeListInputs.has(nodeId)) {
384
+ this._multiEdgeListInputs.set(nodeId, new Set());
385
+ }
386
+ this._multiEdgeListInputs.get(nodeId).add(handle);
387
+ }
388
+ }
389
+ }
390
+ // -----------------------------------------------------------------------
391
+ // Input dispatch
392
+ // -----------------------------------------------------------------------
393
+ /**
394
+ * Deliver input parameters to input nodes (nodes with no incoming data edges).
395
+ * After delivery, mark them as done (EOS) since input nodes produce exactly
396
+ * one value.
397
+ */
398
+ async _dispatchInputs(params) {
399
+ for (const node of this._graph.nodes) {
400
+ const incoming = this._graph.findDataEdges(node.id);
401
+ if (incoming.length > 0)
402
+ continue; // not an input node
403
+ if (!this._isExternalInputNode(node))
404
+ continue;
405
+ const inputName = this._getExternalInputName(node);
406
+ const properties = node.properties && typeof node.properties === "object"
407
+ ? node.properties
408
+ : {};
409
+ const hasRuntimeParam = Object.prototype.hasOwnProperty.call(params, inputName);
410
+ const hasDefaultValue = Object.prototype.hasOwnProperty.call(properties, "value");
411
+ // Streaming output input nodes (e.g. RealtimeAudioInput) should NOT
412
+ // push empty defaults — real data will arrive later via pushInputValue().
413
+ // Non-streaming inputs must push their default so downstream nodes can run.
414
+ // (Python parity: checks is_streaming_output.)
415
+ if (!hasRuntimeParam && (node.is_streaming_output || !hasDefaultValue)) {
416
+ continue;
417
+ }
418
+ const value = hasRuntimeParam ? params[inputName] : properties.value;
419
+ const outgoing = this._graph
420
+ .findOutgoingEdges(node.id)
421
+ .filter(isDataEdge);
422
+ for (const edge of outgoing) {
423
+ const targetInbox = this._inboxes.get(edge.target);
424
+ if (targetInbox) {
425
+ await targetInbox.put(edge.targetHandle, value);
426
+ }
427
+ this._incrementEdgeCounter(edge);
428
+ }
429
+ // Streaming output input nodes (e.g. RealtimeAudioInput) keep their
430
+ // downstream inboxes open so that future pushInputValue() calls can
431
+ // deliver more data. Non-streaming input nodes signal EOS immediately
432
+ // since they produce exactly one value.
433
+ // (Python parity: _dispatch_inputs checks is_streaming_output, not
434
+ // is_streaming_input.)
435
+ if (!node.is_streaming_output) {
436
+ for (const edge of outgoing) {
437
+ const targetInbox = this._inboxes.get(edge.target);
438
+ if (targetInbox) {
439
+ targetInbox.markSourceDone(edge.targetHandle);
440
+ }
441
+ }
442
+ }
443
+ }
444
+ }
445
+ // -----------------------------------------------------------------------
446
+ // Graph processing
447
+ // -----------------------------------------------------------------------
448
+ /**
449
+ * Spawn one NodeActor per node and run them concurrently.
450
+ * Actors that depend on inputs will block on their inboxes until
451
+ * upstream actors produce data.
452
+ */
453
+ async _processGraph() {
454
+ const actorPromises = [];
455
+ for (const node of this._graph.nodes) {
456
+ // Skip input-only nodes that have no incoming edges
457
+ // (they were already handled in _dispatchInputs)
458
+ const incoming = this._graph.findDataEdges(node.id);
459
+ const incomingControl = this._graph
460
+ .findIncomingEdges(node.id)
461
+ .filter(isControlEdge);
462
+ if (incoming.length === 0 &&
463
+ incomingControl.length === 0 &&
464
+ this._isExternalInputNode(node)) {
465
+ continue; // pure input node, already dispatched
466
+ }
467
+ const inbox = this._inboxes.get(node.id);
468
+ const executor = this._options.resolveExecutor(node);
469
+ // Compute sticky handles: handles fed by non-streaming edges
470
+ // are sticky from the start (Python parity: _analyze_streaming).
471
+ const stickyHandles = new Set();
472
+ for (const edge of incoming) {
473
+ if (!this.edgeStreams(edge)) {
474
+ stickyHandles.add(edge.targetHandle);
475
+ }
476
+ }
477
+ // Build control context for controller nodes (Python parity:
478
+ // _is_controller / _build_control_context). This tells the node
479
+ // which downstream nodes it controls and their available properties.
480
+ const controlContext = this._buildControlContext(node.id);
481
+ const actor = new NodeActor({
482
+ node,
483
+ inbox,
484
+ executor,
485
+ sendOutputs: async (nodeId, outputs) => {
486
+ await this._sendMessages(nodeId, outputs);
487
+ },
488
+ emitMessage: (msg) => {
489
+ this._emit(msg);
490
+ },
491
+ executionContext: this._options.executionContext,
492
+ stickyHandles,
493
+ controlContext
494
+ });
495
+ actorPromises.push(actor.run().then(async (result) => {
496
+ // After actor completes, send EOS to all downstream inboxes
497
+ await this._sendEOS(node.id);
498
+ // Reject any pending sendControlEvent promise if the actor errored
499
+ if (result.error) {
500
+ const pending = this._pendingControlResponses.get(node.id);
501
+ if (pending) {
502
+ this._pendingControlResponses.delete(node.id);
503
+ pending.reject(new Error(result.error));
504
+ }
505
+ }
506
+ // If this is an output node, collect the result
507
+ if (this._isOutputNode(node)) {
508
+ const name = node.name ?? node.id;
509
+ if (!this._outputs.has(name)) {
510
+ this._outputs.set(name, []);
511
+ }
512
+ if (result.outputs) {
513
+ for (const val of Object.values(result.outputs)) {
514
+ this._outputs.get(name).push(val);
515
+ }
516
+ }
517
+ }
518
+ }));
519
+ }
520
+ // Wait for all actors to complete
521
+ await Promise.all(actorPromises);
522
+ // Check for in-flight messages after all actors complete (Python parity: _check_pending_inbox_work)
523
+ const pendingNodes = this._checkPendingInboxWork();
524
+ if (pendingNodes.length > 0) {
525
+ log.warn("Pending inbox work detected after all actors completed — possible data loss", {
526
+ pendingNodes
527
+ });
528
+ }
529
+ }
530
+ // -----------------------------------------------------------------------
531
+ // Output routing (send_messages equivalent)
532
+ // -----------------------------------------------------------------------
533
+ /**
534
+ * Route output values from a node to downstream inboxes.
535
+ * For control edges: route control events to the __control__ handle.
536
+ * For data edges: route to the named target handle.
537
+ */
538
+ async _sendMessages(sourceNodeId, outputs) {
539
+ if (this._cancelled)
540
+ return;
541
+ // Handle __control_output__ from controller nodes (Python parity:
542
+ // send_messages wraps __control_output__ in RunEvent and routes to
543
+ // all controlled nodes via control edges).
544
+ if ("__control_output__" in outputs) {
545
+ await this._routeControlOutput(sourceNodeId, outputs["__control_output__"]);
546
+ }
547
+ const outgoing = this._graph.findOutgoingEdges(sourceNodeId);
548
+ const outputKeys = Object.keys(outputs).filter((k) => outputs[k] !== undefined);
549
+ log.debug("_sendMessages", {
550
+ sourceNodeId,
551
+ outputKeys,
552
+ outgoingEdgeCount: outgoing.length,
553
+ outgoingEdges: outgoing.map((e) => ({
554
+ sourceHandle: e.sourceHandle,
555
+ target: e.target,
556
+ targetHandle: e.targetHandle,
557
+ isControl: isControlEdge(e)
558
+ }))
559
+ });
560
+ for (const edge of outgoing) {
561
+ if (isControlEdge(edge)) {
562
+ // Route control events from controller nodes to controlled nodes.
563
+ // Try __control__ first, then fall back to __control_output__
564
+ // (already handled above, skip duplicate routing).
565
+ const value = outputs[edge.sourceHandle];
566
+ if (value === undefined)
567
+ continue;
568
+ const targetInbox = this._inboxes.get(edge.target);
569
+ if (!targetInbox)
570
+ continue;
571
+ // Ensure the value is a proper ControlEvent with event_type.
572
+ // Controller nodes output raw property dicts
573
+ // (e.g. {brightness: 5}) via __control_output__. These must be
574
+ // wrapped in a RunEvent so the controlled actor's _runControlled()
575
+ // recognises them. (Python parity: send_messages wraps
576
+ // __control_output__ in RunEvent.)
577
+ let controlEvent;
578
+ if (typeof value === "object" &&
579
+ value !== null &&
580
+ "event_type" in value &&
581
+ typeof value.event_type === "string") {
582
+ controlEvent = value;
583
+ }
584
+ else if (typeof value === "object" && value !== null) {
585
+ // Raw property dict — wrap as RunEvent
586
+ const raw = value;
587
+ // Support nested {properties: {...}} shape from LLM output
588
+ const properties = "properties" in raw &&
589
+ typeof raw.properties === "object" &&
590
+ raw.properties !== null
591
+ ? raw.properties
592
+ : raw;
593
+ controlEvent = { event_type: "run", properties };
594
+ }
595
+ else {
596
+ continue; // skip non-object values
597
+ }
598
+ await targetInbox.put("__control__", controlEvent);
599
+ // Track that this edge has routed at least one event
600
+ const ctrlEdgeId = edge.id ??
601
+ `${edge.source}:${edge.sourceHandle}->${edge.target}:${edge.targetHandle}`;
602
+ this._controlEdgesRouted.add(ctrlEdgeId);
603
+ continue;
604
+ }
605
+ const value = outputs[edge.sourceHandle];
606
+ if (value === undefined) {
607
+ log.debug("_sendMessages skip edge (no matching output)", {
608
+ sourceNodeId,
609
+ sourceHandle: edge.sourceHandle,
610
+ availableKeys: outputKeys
611
+ });
612
+ continue;
613
+ }
614
+ const targetInbox = this._inboxes.get(edge.target);
615
+ if (!targetInbox) {
616
+ log.debug("_sendMessages skip edge (no target inbox)", {
617
+ target: edge.target
618
+ });
619
+ continue;
620
+ }
621
+ log.debug("_sendMessages delivering", {
622
+ sourceNodeId,
623
+ sourceHandle: edge.sourceHandle,
624
+ target: edge.target,
625
+ targetHandle: edge.targetHandle
626
+ });
627
+ await targetInbox.put(edge.targetHandle, value);
628
+ this._incrementEdgeCounter(edge);
629
+ }
630
+ // Emit output_update for each produced output handle.
631
+ // Skip constant and input nodes: the client already holds their value
632
+ // as a property (or supplied it as a runtime param), so re-sending it
633
+ // (often a large image/audio payload) is redundant.
634
+ const sourceNode = this._graph.findNode(sourceNodeId);
635
+ if (sourceNode &&
636
+ !sourceNode.type.startsWith("nodetool.constant.") &&
637
+ !sourceNode.type.startsWith("nodetool.input.")) {
638
+ const declaredOutputs = sourceNode.outputs ?? {};
639
+ for (const [handle, value] of Object.entries(outputs)) {
640
+ if (value === undefined)
641
+ continue;
642
+ if (handle === "__control__" || handle === "__control_output__")
643
+ continue;
644
+ this._emit({
645
+ type: "output_update",
646
+ node_id: sourceNodeId,
647
+ node_name: sourceNode.name ?? sourceNodeId,
648
+ output_name: handle,
649
+ value,
650
+ output_type: declaredOutputs[handle] ?? "any",
651
+ metadata: {}
652
+ });
653
+ }
654
+ }
655
+ // Resolve pending sendControlEvent promise if one exists for this node
656
+ const pending = this._pendingControlResponses.get(sourceNodeId);
657
+ if (pending) {
658
+ this._pendingControlResponses.delete(sourceNodeId);
659
+ pending.resolve(outputs);
660
+ }
661
+ }
662
+ /**
663
+ * Signal EOS on all outgoing edges of a completed node.
664
+ * For control edges: close the __control__ handle of the target.
665
+ * For data edges: close the named target handle.
666
+ */
667
+ async _sendEOS(nodeId) {
668
+ const outgoing = this._graph.findOutgoingEdges(nodeId);
669
+ for (const edge of outgoing) {
670
+ if (isControlEdge(edge)) {
671
+ // Always mark __control__ source done when the controller finishes,
672
+ // matching Python parity (_mark_downstream_eos). This unblocks
673
+ // controlled nodes waiting on iterInput("__control__") regardless
674
+ // of whether events were routed through the edge or via the manual
675
+ // sendControlEvent() / dispatchControlEvent() APIs.
676
+ const targetInbox = this._inboxes.get(edge.target);
677
+ if (targetInbox) {
678
+ targetInbox.markSourceDone("__control__");
679
+ }
680
+ continue;
681
+ }
682
+ const targetInbox = this._inboxes.get(edge.target);
683
+ if (targetInbox) {
684
+ targetInbox.markSourceDone(edge.targetHandle);
685
+ }
686
+ const edgeId = edge.id ??
687
+ `${edge.source}:${edge.sourceHandle}->${edge.target}:${edge.targetHandle}`;
688
+ this._emit({
689
+ type: "edge_update",
690
+ workflow_id: this.jobId,
691
+ edge_id: edgeId,
692
+ status: "completed",
693
+ counter: this._edgeCounters.get(edgeId) ?? null
694
+ });
695
+ }
696
+ }
697
+ /**
698
+ * Route __control_output__ from controller nodes to all controlled
699
+ * nodes via control edges. Wraps raw property dicts in a RunEvent.
700
+ * (Python parity: send_messages special handling of __control_output__.)
701
+ */
702
+ async _routeControlOutput(sourceNodeId, controlOutput) {
703
+ if (!controlOutput || typeof controlOutput !== "object")
704
+ return;
705
+ const controlEdges = this._graph
706
+ .findOutgoingEdges(sourceNodeId)
707
+ .filter(isControlEdge);
708
+ if (controlEdges.length === 0)
709
+ return;
710
+ let properties = controlOutput;
711
+ // Extract properties if nested inside a metadata wrapper
712
+ if ("properties" in properties &&
713
+ properties.properties &&
714
+ typeof properties.properties === "object" &&
715
+ !Array.isArray(properties.properties)) {
716
+ properties = properties.properties;
717
+ }
718
+ const event = { event_type: "run", properties };
719
+ for (const edge of controlEdges) {
720
+ const targetInbox = this._inboxes.get(edge.target);
721
+ if (!targetInbox)
722
+ continue;
723
+ await targetInbox.put("__control__", event);
724
+ const ctrlEdgeId = edge.id ??
725
+ `${edge.source}:${edge.sourceHandle}->${edge.target}:${edge.targetHandle}`;
726
+ this._controlEdgesRouted.add(ctrlEdgeId);
727
+ }
728
+ }
729
+ // -----------------------------------------------------------------------
730
+ // Control event dispatch
731
+ // -----------------------------------------------------------------------
732
+ /**
733
+ * Broadcast a control event to all controlled nodes.
734
+ */
735
+ async dispatchControlEvent(event) {
736
+ for (const node of this._graph.getControlledNodes()) {
737
+ const inbox = this._inboxes.get(node.id);
738
+ if (inbox) {
739
+ await inbox.put("__control__", event);
740
+ }
741
+ }
742
+ }
743
+ /**
744
+ * Send a control event to a specific target node.
745
+ */
746
+ async dispatchControlEventToTarget(event, targetNodeId) {
747
+ const inbox = this._inboxes.get(targetNodeId);
748
+ if (inbox) {
749
+ await inbox.put("__control__", event);
750
+ }
751
+ }
752
+ /**
753
+ * Send a run control event to a specific node and await its output.
754
+ * Returns a promise that resolves with the node's output from the next
755
+ * output_update message emitted for that node.
756
+ */
757
+ async sendControlEvent(targetNodeId, properties) {
758
+ const inbox = this._inboxes.get(targetNodeId);
759
+ if (!inbox) {
760
+ throw new Error(`Target node not found or no inbox: ${targetNodeId}`);
761
+ }
762
+ const promise = new Promise((resolve, reject) => {
763
+ this._pendingControlResponses.set(targetNodeId, { resolve, reject });
764
+ });
765
+ const event = {
766
+ event_type: "run",
767
+ properties
768
+ };
769
+ await inbox.put("__control__", event);
770
+ return promise;
771
+ }
772
+ // -----------------------------------------------------------------------
773
+ // Edge counters
774
+ // -----------------------------------------------------------------------
775
+ _incrementEdgeCounter(edge) {
776
+ const id = edge.id ??
777
+ `${edge.source}:${edge.sourceHandle}->${edge.target}:${edge.targetHandle}`;
778
+ const counter = (this._edgeCounters.get(id) ?? 0) + 1;
779
+ this._edgeCounters.set(id, counter);
780
+ this._emit({
781
+ type: "edge_update",
782
+ workflow_id: this.jobId,
783
+ edge_id: id,
784
+ status: "active",
785
+ counter
786
+ });
787
+ }
788
+ // -----------------------------------------------------------------------
789
+ // Drain active edges (Python parity: drain_active_edges)
790
+ // -----------------------------------------------------------------------
791
+ /**
792
+ * Post a "drained" EdgeUpdate for any edge whose target handle still has
793
+ * buffered items or open upstream sources. Called during post-completion
794
+ * cleanup to ensure front-end consumers stop listening to streams and
795
+ * clear any spinners.
796
+ */
797
+ _drainActiveEdges() {
798
+ if (!this._graph || this._graph.edges.length === 0)
799
+ return;
800
+ for (const edge of this._graph.edges) {
801
+ try {
802
+ const inbox = this._inboxes.get(edge.target);
803
+ if (!inbox)
804
+ continue;
805
+ const edgeId = edge.id ??
806
+ `${edge.source}:${edge.sourceHandle}->${edge.target}:${edge.targetHandle}`;
807
+ if (inbox.hasBuffered(edge.targetHandle) ||
808
+ inbox.isOpen(edge.targetHandle)) {
809
+ this._emit({
810
+ type: "edge_update",
811
+ workflow_id: this.jobId,
812
+ edge_id: edgeId,
813
+ status: "drained",
814
+ counter: this._edgeCounters.get(edgeId) ?? null
815
+ });
816
+ }
817
+ }
818
+ catch {
819
+ // Best effort — ignore errors during draining
820
+ }
821
+ }
822
+ }
823
+ // -----------------------------------------------------------------------
824
+ // Streaming analysis
825
+ // -----------------------------------------------------------------------
826
+ _edgeKey(edge) {
827
+ return (edge.id ??
828
+ `${edge.source}:${edge.sourceHandle}->${edge.target}:${edge.targetHandle}`);
829
+ }
830
+ _analyzeStreaming() {
831
+ this._streamingEdges.clear();
832
+ const adjacency = new Map();
833
+ for (const edge of this._graph.edges) {
834
+ if (isControlEdge(edge))
835
+ continue;
836
+ const key = this._edgeKey(edge);
837
+ this._streamingEdges.set(key, false);
838
+ const arr = adjacency.get(edge.source) ?? [];
839
+ arr.push(edge);
840
+ adjacency.set(edge.source, arr);
841
+ }
842
+ const queue = [];
843
+ const visited = new Set();
844
+ for (const node of this._graph.nodes) {
845
+ if (node.is_streaming_output) {
846
+ queue.push(node.id);
847
+ visited.add(node.id);
848
+ }
849
+ }
850
+ while (queue.length > 0) {
851
+ const current = queue.shift();
852
+ for (const edge of adjacency.get(current) ?? []) {
853
+ this._streamingEdges.set(this._edgeKey(edge), true);
854
+ if (!visited.has(edge.target)) {
855
+ visited.add(edge.target);
856
+ queue.push(edge.target);
857
+ }
858
+ }
859
+ }
860
+ }
861
+ /** Returns true if the given edge is on a streaming path. */
862
+ edgeStreams(edge) {
863
+ return this._streamingEdges.get(this._edgeKey(edge)) ?? false;
864
+ }
865
+ // -----------------------------------------------------------------------
866
+ // Pending work detection
867
+ // -----------------------------------------------------------------------
868
+ _checkPendingInboxWork() {
869
+ const pending = [];
870
+ for (const [nodeId, inbox] of this._inboxes) {
871
+ if (inbox.hasPendingWork())
872
+ pending.push(nodeId);
873
+ }
874
+ return pending;
875
+ }
876
+ // -----------------------------------------------------------------------
877
+ // Helpers
878
+ // -----------------------------------------------------------------------
879
+ _isOutputNode(node) {
880
+ // An output node has no outgoing data edges
881
+ const outgoing = this._graph.findOutgoingEdges(node.id).filter(isDataEdge);
882
+ return outgoing.length === 0;
883
+ }
884
+ /**
885
+ * External input nodes are placeholders that receive runtime params/streamed values.
886
+ * They should not execute as normal source actors.
887
+ */
888
+ _isExternalInputNode(node) {
889
+ return (node.type.startsWith("nodetool.input.") || node.type === "test.Input");
890
+ }
891
+ _getExternalInputName(node) {
892
+ const properties = node.properties && typeof node.properties === "object"
893
+ ? node.properties
894
+ : {};
895
+ const propertyName = typeof properties.name === "string" ? properties.name.trim() : "";
896
+ if (propertyName) {
897
+ return propertyName;
898
+ }
899
+ return node.name ?? node.id;
900
+ }
901
+ _emit(msg) {
902
+ this._messages.push(msg);
903
+ if (this._options.executionContext) {
904
+ this._options.executionContext.emit(msg);
905
+ }
906
+ log.debug("Message emitted", { jobId: this.jobId, type: msg.type });
907
+ }
908
+ _resolveInputNodes(inputName) {
909
+ return this._graph
910
+ .inputNodes()
911
+ .filter((node) => this._getExternalInputName(node) === inputName ||
912
+ node.id === inputName);
913
+ }
914
+ // -----------------------------------------------------------------------
915
+ // Control context builder (Python parity: _build_control_context)
916
+ // -----------------------------------------------------------------------
917
+ /**
918
+ * Build control context for a controller node.
919
+ * Returns null if the node has no outgoing control edges.
920
+ *
921
+ * The control context maps controlled node IDs to their metadata
922
+ * (node_type, properties with current values, types, descriptions).
923
+ * This is injected as `_control_context` input so agent nodes can
924
+ * build ControlNodeTool instances for LLM tool-calling.
925
+ */
926
+ _buildControlContext(nodeId) {
927
+ const outgoingControlEdges = this._graph
928
+ .findOutgoingEdges(nodeId)
929
+ .filter(isControlEdge);
930
+ if (outgoingControlEdges.length === 0)
931
+ return null;
932
+ const controlledNodeIds = new Set(outgoingControlEdges.map((e) => e.target));
933
+ const context = {};
934
+ for (const targetId of controlledNodeIds) {
935
+ const targetNode = this._graph.findNode(targetId);
936
+ if (!targetNode)
937
+ continue;
938
+ const properties = {};
939
+ // Extract property info from the node descriptor
940
+ if (targetNode.properties && typeof targetNode.properties === "object") {
941
+ const props = targetNode.properties;
942
+ const propTypes = targetNode.propertyTypes ?? {};
943
+ for (const [propName, propValue] of Object.entries(props)) {
944
+ if (propName.startsWith("_"))
945
+ continue; // skip private
946
+ const meta = targetNode.propertyMeta?.[propName];
947
+ properties[propName] = {
948
+ value: propValue,
949
+ type: propTypes[propName] ??
950
+ typeof propValue,
951
+ ...(meta?.description ? { description: meta.description } : {}),
952
+ ...(meta?.min != null ? { min: meta.min } : {}),
953
+ ...(meta?.max != null ? { max: meta.max } : {})
954
+ };
955
+ }
956
+ }
957
+ context[targetId] = {
958
+ node_id: targetId,
959
+ node_type: targetNode.type,
960
+ node_title: targetNode.name ?? targetId,
961
+ properties,
962
+ control_actions: {
963
+ run: {
964
+ properties: this._buildControlActionProperties(targetNode)
965
+ }
966
+ }
967
+ };
968
+ }
969
+ return Object.keys(context).length > 0 ? context : null;
970
+ }
971
+ /**
972
+ * Build the property schema for a controlled node's "run" action.
973
+ * Maps property names to JSON-schema-like descriptors for ControlNodeTool.
974
+ */
975
+ _buildControlActionProperties(node) {
976
+ const result = {};
977
+ if (!node.properties || typeof node.properties !== "object")
978
+ return result;
979
+ const props = node.properties;
980
+ const propTypes = node.propertyTypes ?? {};
981
+ for (const [name, value] of Object.entries(props)) {
982
+ if (name.startsWith("_"))
983
+ continue;
984
+ const declaredType = propTypes[name];
985
+ let jsonType = "string";
986
+ if (declaredType) {
987
+ const lower = declaredType.toLowerCase();
988
+ if (lower === "int" || lower === "integer")
989
+ jsonType = "integer";
990
+ else if (lower === "float" || lower === "number")
991
+ jsonType = "number";
992
+ else if (lower === "bool" || lower === "boolean")
993
+ jsonType = "boolean";
994
+ else if (lower.startsWith("list") || lower === "array")
995
+ jsonType = "array";
996
+ else if (lower.startsWith("dict") || lower === "object")
997
+ jsonType = "object";
998
+ }
999
+ else if (typeof value === "number") {
1000
+ jsonType = Number.isInteger(value) ? "integer" : "number";
1001
+ }
1002
+ else if (typeof value === "boolean") {
1003
+ jsonType = "boolean";
1004
+ }
1005
+ const meta = node.propertyMeta?.[name];
1006
+ result[name] = {
1007
+ type: jsonType,
1008
+ description: meta?.description ??
1009
+ `Property '${name}' (${declaredType ?? jsonType})`,
1010
+ default: value,
1011
+ ...(meta?.min != null ? { minimum: meta.min } : {}),
1012
+ ...(meta?.max != null ? { maximum: meta.max } : {})
1013
+ };
1014
+ }
1015
+ return result;
1016
+ }
1017
+ }
1018
+ //# sourceMappingURL=runner.js.map