@nodetool-ai/kernel 0.8.7 → 0.8.9-beta.1
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/runner.js
CHANGED
|
@@ -1,2127 +1,2 @@
|
|
|
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 { isBoolean, isCallable, isNumber, isObjectValue, isString } from "./predicates.js";
|
|
18
|
-
import { TypeMetadata, missingRuntimeDetailsOf, missingPackDetailsOf, MissingPackError } from "@nodetool-ai/protocol";
|
|
19
|
-
import { ensureBounded, redactValue } from "./supervisor.js";
|
|
20
|
-
// Stryker disable next-line StringLiteral: logger name is a diagnostic label, not a behavioural contract
|
|
21
|
-
const log = createLogger("nodetool.kernel.runner");
|
|
22
|
-
/** Node type that publishes to a variable channel (see runtime VariableChannel). */
|
|
23
|
-
const SET_VARIABLE_NODE_TYPE = "nodetool.variable.SetVariable";
|
|
24
|
-
/**
|
|
25
|
-
* Minimum interval between edge_update emissions per edge. The first message
|
|
26
|
-
* on an edge always emits (it starts the flow animation); afterwards the
|
|
27
|
-
* counter badge is refreshed at most this often, with the exact final count
|
|
28
|
-
* flushed at run end. Keeps audio-rate streams (~50 chunks/s per edge) from
|
|
29
|
-
* flooding the message transport.
|
|
30
|
-
*/
|
|
31
|
-
const EDGE_UPDATE_MIN_INTERVAL_MS = 1000;
|
|
32
|
-
/**
|
|
33
|
-
* Cap on messages retained for RunResult.messages. Long-running streaming
|
|
34
|
-
* jobs would otherwise accumulate messages without bound; when the cap is
|
|
35
|
-
* hit, the oldest half is dropped (block-wise, so the cost amortizes).
|
|
36
|
-
*/
|
|
37
|
-
const MAX_RETAINED_MESSAGES = 10_000;
|
|
38
|
-
/**
|
|
39
|
-
* Cap on lineages retained per node for `read_node_output`. A supervisor reads
|
|
40
|
-
* the failing invocation's own branch, which is recent; a wide fan-out must not
|
|
41
|
-
* turn the cache into a second copy of the run's data.
|
|
42
|
-
*/
|
|
43
|
-
const MAX_RECORDED_LINEAGES_PER_NODE = 64;
|
|
44
|
-
function hasDefinedOwnProperty(record, key) {
|
|
45
|
-
return (Object.prototype.hasOwnProperty.call(record, key) &&
|
|
46
|
-
record[key] !== undefined);
|
|
47
|
-
}
|
|
48
|
-
/** A value that already carries its own control-event envelope. */
|
|
49
|
-
function isControlEventValue(value) {
|
|
50
|
-
return (typeof value === "object" &&
|
|
51
|
-
value !== null &&
|
|
52
|
-
"event_type" in value &&
|
|
53
|
-
typeof value.event_type === "string");
|
|
54
|
-
}
|
|
55
|
-
/** An output_update whose value is a streamed audio chunk (sample payload). */
|
|
56
|
-
function isAudioChunkOutputUpdate(msg) {
|
|
57
|
-
if (msg.type !== "output_update")
|
|
58
|
-
return false;
|
|
59
|
-
const value = msg.value;
|
|
60
|
-
if (!isObjectValue(value))
|
|
61
|
-
return false;
|
|
62
|
-
const v = value;
|
|
63
|
-
return v.type === "chunk" && v.content_type === "audio";
|
|
64
|
-
}
|
|
65
|
-
// Import span helpers from the narrow `/tracing` subpath, not the package root,
|
|
66
|
-
// so thin consumers (e.g. the in-browser workflow runner) don't drag the
|
|
67
|
-
// provider / python-bridge barrel into their bundle.
|
|
68
|
-
import { withWorkflowSpan, SpanStatusCode } from "@nodetool-ai/runtime/tracing";
|
|
69
|
-
import { LOOP_NODE_TYPE, isControlEdge, isDataEdge } from "@nodetool-ai/protocol";
|
|
70
|
-
import { Graph, GraphValidationError } from "./graph.js";
|
|
71
|
-
import { rewriteBypassedNodes } from "./graph-utils.js";
|
|
72
|
-
import { dynamicSlotPropertyTypes } from "./dynamic-slots.js";
|
|
73
|
-
import { NodeInbox } from "./inbox.js";
|
|
74
|
-
import { NodeActor } from "./actor.js";
|
|
75
|
-
import { syntheticEdgeId } from "./edge-ids.js";
|
|
76
|
-
import { analyzeCorrelation, projectLineageKey } from "./correlation-analysis.js";
|
|
77
|
-
import { lineageRelated } from "./run-state.js";
|
|
78
|
-
/**
|
|
79
|
-
* For workflow sink nodes (`nodetool.output.Output`, Preview), the user-facing
|
|
80
|
-
* key is `properties.name` (workflow output / vvvv pin name). The process
|
|
81
|
-
* result still uses internal handles (e.g. `output`). Map those updates to the
|
|
82
|
-
* logical name so WebSocket clients can route values to the right pins.
|
|
83
|
-
*/
|
|
84
|
-
function clientFacingOutputName(node, handle) {
|
|
85
|
-
const t = node.type ?? "";
|
|
86
|
-
const props = node.properties;
|
|
87
|
-
const workflowKey = props && isString(props.name) && props.name.trim().length > 0
|
|
88
|
-
? props.name.trim()
|
|
89
|
-
: undefined;
|
|
90
|
-
if (t === "nodetool.output.Output" || t.endsWith(".output.Output")) {
|
|
91
|
-
return workflowKey ?? handle;
|
|
92
|
-
}
|
|
93
|
-
if (t === "nodetool.workflows.base_node.Preview" ||
|
|
94
|
-
t.endsWith(".workflows.base_node.Preview")) {
|
|
95
|
-
return workflowKey ?? handle;
|
|
96
|
-
}
|
|
97
|
-
return handle;
|
|
98
|
-
}
|
|
99
|
-
// ---------------------------------------------------------------------------
|
|
100
|
-
// WorkflowRunner
|
|
101
|
-
// ---------------------------------------------------------------------------
|
|
102
|
-
export class WorkflowRunner {
|
|
103
|
-
jobId;
|
|
104
|
-
_graph;
|
|
105
|
-
_options;
|
|
106
|
-
/** Per-node inboxes. */
|
|
107
|
-
_inboxes = new Map();
|
|
108
|
-
/** Per-edge message counters (for EdgeUpdate tracking). */
|
|
109
|
-
_edgeCounters = new Map();
|
|
110
|
-
/** Per-edge timestamp of the last emitted edge_update (throttling). */
|
|
111
|
-
_edgeCounterLastEmitMs = new Map();
|
|
112
|
-
/** Edges whose counter advanced since their last emitted edge_update. */
|
|
113
|
-
_edgeCounterDirty = new Set();
|
|
114
|
-
/**
|
|
115
|
-
* Static correlation analysis result. Always populated before actors run.
|
|
116
|
-
*/
|
|
117
|
-
_correlation;
|
|
118
|
-
/**
|
|
119
|
-
* Multi-edge list inputs: nodeId → set of handles that aggregate
|
|
120
|
-
* multiple edges into a list.
|
|
121
|
-
*/
|
|
122
|
-
_multiEdgeListInputs = new Map();
|
|
123
|
-
/** Collected outputs from output nodes. */
|
|
124
|
-
_outputs = new Map();
|
|
125
|
-
/** All emitted messages. */
|
|
126
|
-
_messages = [];
|
|
127
|
-
_missingRuntime;
|
|
128
|
-
_missingPack;
|
|
129
|
-
/** Cancellation flag. */
|
|
130
|
-
_cancelled = false;
|
|
131
|
-
/**
|
|
132
|
-
* Actors spawned and not yet finished (including their completion
|
|
133
|
-
* handling). Exposed via {@link liveActorCount} for leak accounting — after
|
|
134
|
-
* a run this must be back to zero, and a harness that can't measure it
|
|
135
|
-
* can't assert it.
|
|
136
|
-
*/
|
|
137
|
-
_liveActors = 0;
|
|
138
|
-
/** Node ids of actors still running; read by quiescence detection. */
|
|
139
|
-
_liveActorIds = new Set();
|
|
140
|
-
/**
|
|
141
|
-
* Outgoing data edges of streaming input nodes that `finishInputStream`
|
|
142
|
-
* has not closed yet. While any is open, values can still arrive from
|
|
143
|
-
* outside the graph, so the graph is never quiescent.
|
|
144
|
-
*/
|
|
145
|
-
_openExternalStreamEdges = new Set();
|
|
146
|
-
/** Schedules a quiescence check; set only for graphs with a Loop node. */
|
|
147
|
-
_scheduleQuiescenceCheck = null;
|
|
148
|
-
/**
|
|
149
|
-
* Latch set by `cancel()` and never cleared by `_resetRunState`. A cancel
|
|
150
|
-
* that lands between construction and `run()` would otherwise be dropped —
|
|
151
|
-
* the reset clears `_cancelled` and swaps the AbortController. `_runImpl`
|
|
152
|
-
* re-applies this latch after the reset so such a run terminates as
|
|
153
|
-
* "cancelled". §17.
|
|
154
|
-
*/
|
|
155
|
-
_cancelRequested = false;
|
|
156
|
-
/**
|
|
157
|
-
* True while a run is in flight. A second concurrent `run()` on the same
|
|
158
|
-
* instance would clobber all shared run state, so `_runImpl` rejects it. §17.
|
|
159
|
-
*/
|
|
160
|
-
_running = false;
|
|
161
|
-
/**
|
|
162
|
-
* Job id used for `edge_update` emissions during a run. Captured from
|
|
163
|
-
* `request.job_id` at the start of `_runImpl` so edge updates and
|
|
164
|
-
* `job_update` messages carry the same id; before a run starts it defaults
|
|
165
|
-
* to the constructor id. §16.
|
|
166
|
-
*/
|
|
167
|
-
_effectiveJobId;
|
|
168
|
-
/** Run-level cancellation signal source; aborted by `cancel()`. */
|
|
169
|
-
_abortController = new AbortController();
|
|
170
|
-
/**
|
|
171
|
-
* Pending response resolvers for sendControlEvent, FIFO per node. The
|
|
172
|
-
* controlled actor processes control events in order and emits outputs in
|
|
173
|
-
* order, so the oldest waiter matches the next output. A single slot per
|
|
174
|
-
* node would let a burst of concurrent control events (e.g. parallel agent
|
|
175
|
-
* tool calls) overwrite an earlier resolver, leaving its promise unsettled
|
|
176
|
-
* forever.
|
|
177
|
-
*/
|
|
178
|
-
_pendingControlResponses = new Map();
|
|
179
|
-
/**
|
|
180
|
-
* Executor instance per node. Resolved once and reused so that the
|
|
181
|
-
* instance initialized in _initializeGraph is the same one that executes
|
|
182
|
-
* (NodeRegistry.resolve constructs a fresh instance per call).
|
|
183
|
-
*/
|
|
184
|
-
_executors = new Map();
|
|
185
|
-
/**
|
|
186
|
-
* Nodes whose actor has finished running. A control event sent to such a
|
|
187
|
-
* node can never be answered (the actor's run loop is gone), so
|
|
188
|
-
* sendControlEvent rejects instead of registering a promise that hangs
|
|
189
|
-
* forever. This guards against an agent dispatching a burst of control
|
|
190
|
-
* tool calls where the controlled node errors (and terminates) partway
|
|
191
|
-
* through.
|
|
192
|
-
*/
|
|
193
|
-
_completedNodes = new Set();
|
|
194
|
-
/** Errors reported by node actors, keyed by node id. */
|
|
195
|
-
_nodeErrors = new Map();
|
|
196
|
-
/**
|
|
197
|
-
* Edge ids whose source has already been marked done on the target inbox.
|
|
198
|
-
* `markSourceDone` decrements an upstream counter, so marking the same edge
|
|
199
|
-
* twice would over-decrement and could prematurely close a handle that still
|
|
200
|
-
* has other open upstreams. Early per-slot EOS (`outputs.complete`) and the
|
|
201
|
-
* final `_sendEOS` both guard against double-marking via this set.
|
|
202
|
-
*/
|
|
203
|
-
_eosSentEdges = new Set();
|
|
204
|
-
/** Supervisor escalations and their verdicts, in decision order. */
|
|
205
|
-
_interventions = [];
|
|
206
|
-
/**
|
|
207
|
-
* Last output of each node per invocation lineage, for `read_node_output`.
|
|
208
|
-
* Only populated on a supervised run — an unsupervised one keeps nothing.
|
|
209
|
-
* Bounded per node: a 10k-item fan-out must not become a 10k-entry cache.
|
|
210
|
-
*/
|
|
211
|
-
_recordedOutputs = new Map();
|
|
212
|
-
/** Undefined on an unsupervised run, so its `RunResult` is unchanged. */
|
|
213
|
-
_recordedInterventions() {
|
|
214
|
-
return this._interventions.length > 0 ? this._interventions : undefined;
|
|
215
|
-
}
|
|
216
|
-
/**
|
|
217
|
-
* The handle every escalation actually goes through: whatever the caller
|
|
218
|
-
* configured, under the kernel's bounds. Nothing else in the runner reads
|
|
219
|
-
* `_options.supervisor`.
|
|
220
|
-
*/
|
|
221
|
-
_supervisor;
|
|
222
|
-
constructor(jobId, options) {
|
|
223
|
-
this.jobId = jobId;
|
|
224
|
-
this._effectiveJobId = jobId;
|
|
225
|
-
this._options = options;
|
|
226
|
-
this._supervisor = options.supervisor
|
|
227
|
-
? ensureBounded(options.supervisor)
|
|
228
|
-
: undefined;
|
|
229
|
-
}
|
|
230
|
-
// -----------------------------------------------------------------------
|
|
231
|
-
// Public API
|
|
232
|
-
// -----------------------------------------------------------------------
|
|
233
|
-
/**
|
|
234
|
-
* Push a streaming input value into the graph while it is running.
|
|
235
|
-
* The input name matches an input-node's `name` (or `id` fallback).
|
|
236
|
-
*/
|
|
237
|
-
async pushInputValue(inputName, value, sourceHandle) {
|
|
238
|
-
if (!this._graph) {
|
|
239
|
-
throw new Error("Workflow has not been started");
|
|
240
|
-
}
|
|
241
|
-
const inputNodes = this._resolveInputNodes(inputName);
|
|
242
|
-
if (inputNodes.length === 0) {
|
|
243
|
-
throw new Error(`Input node not found: ${inputName}`);
|
|
244
|
-
}
|
|
245
|
-
for (const node of inputNodes) {
|
|
246
|
-
// Run the node's own process() so streamed values transform exactly like
|
|
247
|
-
// start params do in _dispatchInputs (StringInput max_length,
|
|
248
|
-
// DocumentFileInput building a DocumentRef, MessageDeconstructor
|
|
249
|
-
// splitting). Otherwise the same input node behaves differently depending
|
|
250
|
-
// on whether the value arrived as a param or was streamed in. This is a
|
|
251
|
-
// live-stream path, so a process() failure throws rather than silently
|
|
252
|
-
// dropping the value.
|
|
253
|
-
const executor = this._resolveExecutor(node);
|
|
254
|
-
let nodeOutputs;
|
|
255
|
-
try {
|
|
256
|
-
nodeOutputs = await executor.process({ value }, this._options.executionContext);
|
|
257
|
-
}
|
|
258
|
-
catch (err) {
|
|
259
|
-
const message = err instanceof Error ? err.message : String(err);
|
|
260
|
-
throw new Error(`Input node "${node.name ?? node.id}" (${node.type}) failed: ${message}`);
|
|
261
|
-
}
|
|
262
|
-
// Same fallback semantics as _dispatchInputs: raw-value dispatch only
|
|
263
|
-
// when process() produced no defined output at all (the test-double
|
|
264
|
-
// case). Once the record carries any real output, a handle it omits
|
|
265
|
-
// stays silent rather than leaking the raw input value onto it.
|
|
266
|
-
const outputsEmpty = !Object.values(nodeOutputs).some((v) => v !== undefined);
|
|
267
|
-
const outgoing = this._graph
|
|
268
|
-
.findOutgoingEdges(node.id)
|
|
269
|
-
.filter(isDataEdge);
|
|
270
|
-
for (const edge of outgoing) {
|
|
271
|
-
if (sourceHandle && edge.sourceHandle !== sourceHandle) {
|
|
272
|
-
continue;
|
|
273
|
-
}
|
|
274
|
-
const hasHandleValue = Object.hasOwn(nodeOutputs, edge.sourceHandle) &&
|
|
275
|
-
nodeOutputs[edge.sourceHandle] !== undefined;
|
|
276
|
-
if (!outputsEmpty && !hasHandleValue)
|
|
277
|
-
continue;
|
|
278
|
-
const targetInbox = this._inboxes.get(edge.target);
|
|
279
|
-
if (!targetInbox)
|
|
280
|
-
continue;
|
|
281
|
-
const handleValue = hasHandleValue
|
|
282
|
-
? nodeOutputs[edge.sourceHandle]
|
|
283
|
-
: value;
|
|
284
|
-
await targetInbox.put(edge.targetHandle, handleValue, {
|
|
285
|
-
source_edge_id: edge.id ??
|
|
286
|
-
syntheticEdgeId(edge.source, edge.sourceHandle, edge.target, edge.targetHandle)
|
|
287
|
-
});
|
|
288
|
-
this._incrementEdgeCounter(edge);
|
|
289
|
-
}
|
|
290
|
-
}
|
|
291
|
-
}
|
|
292
|
-
/**
|
|
293
|
-
* Signal end-of-stream for an input node so downstream handles can complete.
|
|
294
|
-
*/
|
|
295
|
-
finishInputStream(inputName, sourceHandle) {
|
|
296
|
-
if (!this._graph) {
|
|
297
|
-
throw new Error("Workflow has not been started");
|
|
298
|
-
}
|
|
299
|
-
const inputNodes = this._resolveInputNodes(inputName);
|
|
300
|
-
if (inputNodes.length === 0) {
|
|
301
|
-
throw new Error(`Input node not found: ${inputName}`);
|
|
302
|
-
}
|
|
303
|
-
for (const node of inputNodes) {
|
|
304
|
-
const outgoing = this._graph
|
|
305
|
-
.findOutgoingEdges(node.id)
|
|
306
|
-
.filter(isDataEdge);
|
|
307
|
-
for (const edge of outgoing) {
|
|
308
|
-
if (sourceHandle && edge.sourceHandle !== sourceHandle) {
|
|
309
|
-
continue;
|
|
310
|
-
}
|
|
311
|
-
this._openExternalStreamEdges.delete(edge.id ??
|
|
312
|
-
syntheticEdgeId(edge.source, edge.sourceHandle, edge.target, edge.targetHandle));
|
|
313
|
-
const targetInbox = this._inboxes.get(edge.target);
|
|
314
|
-
if (!targetInbox)
|
|
315
|
-
continue;
|
|
316
|
-
targetInbox.markSourceDone(edge.targetHandle);
|
|
317
|
-
}
|
|
318
|
-
}
|
|
319
|
-
}
|
|
320
|
-
/**
|
|
321
|
-
* Execute a workflow graph.
|
|
322
|
-
*
|
|
323
|
-
* Requires hydrated descriptors: the actor trusts the behavior flags
|
|
324
|
-
* (`is_streaming_input` & co.) to pick the execution mode, so accepting a
|
|
325
|
-
* raw wire graph here would silently run streaming nodes as one-shot
|
|
326
|
-
* process() calls. Hydrate via `Graph.loadFromDict`, node-sdk's
|
|
327
|
-
* `hydrateGraphNodeFlags(graph, registry)`, or — for graphs constructed in
|
|
328
|
-
* code where the author sets the flags — `withExplicitNodeFlags`.
|
|
329
|
-
*/
|
|
330
|
-
async run(request, graphData) {
|
|
331
|
-
return withWorkflowSpan({
|
|
332
|
-
workflowId: request.workflow_id ?? undefined,
|
|
333
|
-
nodeCount: graphData.nodes.length,
|
|
334
|
-
extra: { "workflow.job_id": request.job_id }
|
|
335
|
-
}, async (span) => {
|
|
336
|
-
const result = await this._runImpl(request, graphData);
|
|
337
|
-
if (result.status === "failed" || result.status === "cancelled") {
|
|
338
|
-
span?.setStatus({ code: SpanStatusCode.ERROR });
|
|
339
|
-
}
|
|
340
|
-
return result;
|
|
341
|
-
});
|
|
342
|
-
}
|
|
343
|
-
async _runImpl(request, graphData) {
|
|
344
|
-
// Reject a second concurrent run before touching any shared state — a reset
|
|
345
|
-
// here would wipe the in-flight run's inboxes/outputs/messages. §17.
|
|
346
|
-
if (this._running) {
|
|
347
|
-
throw new Error(`WorkflowRunner "${this.jobId}" is already running; ` +
|
|
348
|
-
"create a new runner instance per job");
|
|
349
|
-
}
|
|
350
|
-
this._running = true;
|
|
351
|
-
this._resetRunState();
|
|
352
|
-
this._effectiveJobId = request.job_id ?? this.jobId;
|
|
353
|
-
// A cancel() that landed before this run started set the latch but was
|
|
354
|
-
// undone by _resetRunState (fresh controller, _cancelled cleared). Re-apply
|
|
355
|
-
// it so the run terminates as "cancelled" rather than silently ignoring the
|
|
356
|
-
// request. §17.
|
|
357
|
-
if (this._cancelRequested) {
|
|
358
|
-
this._cancelled = true;
|
|
359
|
-
this._abortController.abort();
|
|
360
|
-
}
|
|
361
|
-
// Publish this run's cancellation signal on the shared context so nodes
|
|
362
|
-
// reached through process()/genProcess() — which receive no NodeInputs —
|
|
363
|
-
// can abort long-running work (agent loops, provider calls) on cancel().
|
|
364
|
-
// _resetRunState mints a fresh controller per run, so this must be
|
|
365
|
-
// re-published each time rather than wired once at construction.
|
|
366
|
-
if (this._options.executionContext) {
|
|
367
|
-
this._options.executionContext.signal = this._abortController.signal;
|
|
368
|
-
this._options.executionContext.triggerEvent =
|
|
369
|
-
request.trigger_event ?? null;
|
|
370
|
-
}
|
|
371
|
-
try {
|
|
372
|
-
log.info("Workflow started", {
|
|
373
|
-
jobId: request.job_id,
|
|
374
|
-
workflowId: request.workflow_id
|
|
375
|
-
});
|
|
376
|
-
// Emit job_update: running before any validation. A run that dies in
|
|
377
|
-
// graph validation still gets the running acknowledgement first, so
|
|
378
|
-
// clients never see a terminal update for a job they were never told
|
|
379
|
-
// started.
|
|
380
|
-
this._emit({
|
|
381
|
-
type: "job_update",
|
|
382
|
-
status: "running",
|
|
383
|
-
job_id: request.job_id,
|
|
384
|
-
workflow_id: request.workflow_id ?? null
|
|
385
|
-
});
|
|
386
|
-
// Rewrite the graph to route around nodes marked
|
|
387
|
-
// `ui_properties.bypassed === true`. Each outgoing edge of a
|
|
388
|
-
// bypassed node is re-attached to the matching upstream source
|
|
389
|
-
// (by type compatibility); outgoing edges with no compatible
|
|
390
|
-
// upstream are dropped, as is the bypassed node itself.
|
|
391
|
-
const effectiveGraph = rewriteBypassedNodes(graphData);
|
|
392
|
-
this._graph = new Graph(effectiveGraph);
|
|
393
|
-
// Python parity: _filter_invalid_edges — silently remove edges
|
|
394
|
-
// whose source or target node doesn't exist in the graph.
|
|
395
|
-
this._filterInvalidEdges();
|
|
396
|
-
// Static correlation analysis is mandatory. Issues abort the run with
|
|
397
|
-
// a graph validation error before any actor is spawned.
|
|
398
|
-
this._correlation = analyzeCorrelation({
|
|
399
|
-
nodes: this._graph.nodes,
|
|
400
|
-
edges: this._graph.edges
|
|
401
|
-
});
|
|
402
|
-
if (this._correlation.issues.length > 0) {
|
|
403
|
-
const lines = this._correlation.issues.map((i) => ` - ${i.message}`);
|
|
404
|
-
throw new GraphValidationError(`Correlation analysis failed:\n${lines.join("\n")}`, this._correlation.issues
|
|
405
|
-
.filter((i) => !!i.nodeId)
|
|
406
|
-
.map((i) => ({
|
|
407
|
-
nodeId: i.nodeId,
|
|
408
|
-
nodeType: i.nodeType,
|
|
409
|
-
property: i.handle ?? "",
|
|
410
|
-
message: i.message
|
|
411
|
-
})));
|
|
412
|
-
}
|
|
413
|
-
// Validate
|
|
414
|
-
this._graph.validate();
|
|
415
|
-
// Pre-flight node validation: catch missing required fields and
|
|
416
|
-
// unset model selections before spawning any actors.
|
|
417
|
-
this._validateNodes();
|
|
418
|
-
this._validateRequiredInputs(request.params ?? {});
|
|
419
|
-
// Detect multi-edge list inputs
|
|
420
|
-
this._detectMultiEdgeListInputs();
|
|
421
|
-
// Initialize inboxes
|
|
422
|
-
this._initializeInboxes();
|
|
423
|
-
// Initialize all nodes (Python parity: initialize_graph)
|
|
424
|
-
await this._initializeGraph();
|
|
425
|
-
// Dispatch input parameters
|
|
426
|
-
await this._dispatchInputs(request.params ?? {});
|
|
427
|
-
// Bind sendControlEvent to processing context so agent nodes can dispatch
|
|
428
|
-
// control events to controlled nodes and await their results.
|
|
429
|
-
if (this._options.executionContext &&
|
|
430
|
-
isCallable(this._options.executionContext.setSendControlEvent)) {
|
|
431
|
-
this._options.executionContext.setSendControlEvent((targetNodeId, properties) => this.sendControlEvent(targetNodeId, properties));
|
|
432
|
-
}
|
|
433
|
-
// Register Set Variable writers so variable channels know when to close.
|
|
434
|
-
this._registerVariableChannels();
|
|
435
|
-
// Process graph (spawn actors)
|
|
436
|
-
await this._processGraph();
|
|
437
|
-
// Post-completion: drain any edges that still have pending/open state
|
|
438
|
-
this._enforceCleanEdgeDrain(this._drainActiveEdges());
|
|
439
|
-
// A node failure fails the whole job (Python parity). Actors swallow
|
|
440
|
-
// their own errors so sibling branches can finish, but the final
|
|
441
|
-
// status must not report success when any node errored.
|
|
442
|
-
if (!this._cancelled && this._nodeErrors.size > 0) {
|
|
443
|
-
const error = [...this._nodeErrors]
|
|
444
|
-
.map(([nodeId, msg]) => `Node "${nodeId}" failed: ${msg}`)
|
|
445
|
-
.join("; ");
|
|
446
|
-
// Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
|
|
447
|
-
log.error("Workflow failed", { jobId: request.job_id, error });
|
|
448
|
-
const update = {
|
|
449
|
-
type: "job_update",
|
|
450
|
-
status: "failed",
|
|
451
|
-
job_id: request.job_id,
|
|
452
|
-
workflow_id: request.workflow_id ?? null,
|
|
453
|
-
error
|
|
454
|
-
};
|
|
455
|
-
if (this._missingPack) {
|
|
456
|
-
update.missing_pack = this._missingPack;
|
|
457
|
-
}
|
|
458
|
-
this._emit(update);
|
|
459
|
-
const result = {
|
|
460
|
-
outputs: Object.fromEntries(this._outputs),
|
|
461
|
-
messages: this._messages,
|
|
462
|
-
status: "failed",
|
|
463
|
-
error,
|
|
464
|
-
interventions: this._recordedInterventions()
|
|
465
|
-
};
|
|
466
|
-
if (this._missingRuntime) {
|
|
467
|
-
result.missingRuntime = this._missingRuntime;
|
|
468
|
-
}
|
|
469
|
-
if (this._missingPack) {
|
|
470
|
-
result.missingPack = this._missingPack;
|
|
471
|
-
}
|
|
472
|
-
return result;
|
|
473
|
-
}
|
|
474
|
-
const status = this._cancelled ? "cancelled" : "completed";
|
|
475
|
-
// Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
|
|
476
|
-
log.info("Workflow completed", { jobId: request.job_id, status });
|
|
477
|
-
this._emit({
|
|
478
|
-
type: "job_update",
|
|
479
|
-
status,
|
|
480
|
-
job_id: request.job_id,
|
|
481
|
-
workflow_id: request.workflow_id ?? null
|
|
482
|
-
});
|
|
483
|
-
return {
|
|
484
|
-
outputs: Object.fromEntries(this._outputs),
|
|
485
|
-
messages: this._messages,
|
|
486
|
-
status,
|
|
487
|
-
interventions: this._recordedInterventions()
|
|
488
|
-
};
|
|
489
|
-
}
|
|
490
|
-
catch (err) {
|
|
491
|
-
const message = err instanceof Error ? err.message : String(err);
|
|
492
|
-
this._missingRuntime ??= missingRuntimeDetailsOf(err) ?? undefined;
|
|
493
|
-
this._missingPack ??= missingPackDetailsOf(err) ?? undefined;
|
|
494
|
-
// Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
|
|
495
|
-
log.error("Workflow failed", { jobId: request.job_id, error: message });
|
|
496
|
-
// Drain active edges on error for front-end cleanup
|
|
497
|
-
this._drainActiveEdges();
|
|
498
|
-
const validationIssues = err instanceof GraphValidationError && err.issues.length > 0
|
|
499
|
-
? err.issues
|
|
500
|
-
.filter((i) => !!i.nodeId)
|
|
501
|
-
.map((i) => ({
|
|
502
|
-
node_id: i.nodeId,
|
|
503
|
-
node_type: i.nodeType ?? null,
|
|
504
|
-
property: i.property ?? "",
|
|
505
|
-
message: i.message
|
|
506
|
-
}))
|
|
507
|
-
: null;
|
|
508
|
-
const update = {
|
|
509
|
-
type: "job_update",
|
|
510
|
-
status: "failed",
|
|
511
|
-
job_id: request.job_id,
|
|
512
|
-
workflow_id: request.workflow_id ?? null,
|
|
513
|
-
error: message,
|
|
514
|
-
validation_issues: validationIssues
|
|
515
|
-
};
|
|
516
|
-
if (this._missingPack) {
|
|
517
|
-
update.missing_pack = this._missingPack;
|
|
518
|
-
}
|
|
519
|
-
this._emit(update);
|
|
520
|
-
const result = {
|
|
521
|
-
outputs: Object.fromEntries(this._outputs),
|
|
522
|
-
messages: this._messages,
|
|
523
|
-
status: "failed",
|
|
524
|
-
error: message,
|
|
525
|
-
interventions: this._recordedInterventions()
|
|
526
|
-
};
|
|
527
|
-
if (this._missingRuntime) {
|
|
528
|
-
result.missingRuntime = this._missingRuntime;
|
|
529
|
-
}
|
|
530
|
-
if (this._missingPack) {
|
|
531
|
-
result.missingPack = this._missingPack;
|
|
532
|
-
}
|
|
533
|
-
return result;
|
|
534
|
-
}
|
|
535
|
-
finally {
|
|
536
|
-
this._running = false;
|
|
537
|
-
}
|
|
538
|
-
}
|
|
539
|
-
_resetRunState() {
|
|
540
|
-
this._inboxes = new Map();
|
|
541
|
-
this._edgeCounters = new Map();
|
|
542
|
-
this._edgeCounterLastEmitMs = new Map();
|
|
543
|
-
this._edgeCounterDirty = new Set();
|
|
544
|
-
this._multiEdgeListInputs = new Map();
|
|
545
|
-
this._outputs = new Map();
|
|
546
|
-
this._messages = [];
|
|
547
|
-
this._missingRuntime = undefined;
|
|
548
|
-
this._missingPack = undefined;
|
|
549
|
-
this._cancelled = false;
|
|
550
|
-
this._abortController = new AbortController();
|
|
551
|
-
this._pendingControlResponses = new Map();
|
|
552
|
-
this._completedNodes = new Set();
|
|
553
|
-
this._executors = new Map();
|
|
554
|
-
this._nodeErrors = new Map();
|
|
555
|
-
this._correlation = undefined;
|
|
556
|
-
this._eosSentEdges = new Set();
|
|
557
|
-
this._liveActorIds = new Set();
|
|
558
|
-
this._openExternalStreamEdges = new Set();
|
|
559
|
-
this._scheduleQuiescenceCheck = null;
|
|
560
|
-
this._interventions = [];
|
|
561
|
-
this._recordedOutputs = new Map();
|
|
562
|
-
}
|
|
563
|
-
/**
|
|
564
|
-
* The read-only view a supervisor gets of the run in flight. Built from
|
|
565
|
-
* state the runner already holds, so a run without a supervisor pays for
|
|
566
|
-
* none of it. See docs/workflow-supervisor-design.md §6.
|
|
567
|
-
*/
|
|
568
|
-
_runStateReader() {
|
|
569
|
-
return {
|
|
570
|
-
digest: () => this._runStateDigest(),
|
|
571
|
-
readOutput: (nodeId, lineage) => this._readRecordedOutput(nodeId, lineage)
|
|
572
|
-
};
|
|
573
|
-
}
|
|
574
|
-
_runStateDigest() {
|
|
575
|
-
// A node error is raw `err.message` — an HTTP failure echoing its URL
|
|
576
|
-
// carries the key it was called with. The digest goes to the supervisor
|
|
577
|
-
// model, so it is redacted here, where the digest is built, exactly as the
|
|
578
|
-
// actor redacts an escalation's `detail`.
|
|
579
|
-
const secrets = this._options.executionContext?.getResolvedSecretValues?.() ??
|
|
580
|
-
new Set();
|
|
581
|
-
const escalationsPerNode = new Map();
|
|
582
|
-
for (const intervention of this._interventions) {
|
|
583
|
-
const nodeId = intervention.escalation.nodeId;
|
|
584
|
-
escalationsPerNode.set(nodeId, (escalationsPerNode.get(nodeId) ?? 0) + 1);
|
|
585
|
-
}
|
|
586
|
-
const nodes = this._graph.nodes.map((node) => {
|
|
587
|
-
const error = this._nodeErrors.get(node.id);
|
|
588
|
-
const done = this._completedNodes.has(node.id);
|
|
589
|
-
const emissions = this._recordedOutputs.get(node.id)?.size ?? 0;
|
|
590
|
-
const state = {
|
|
591
|
-
nodeId: node.id,
|
|
592
|
-
nodeType: node.type,
|
|
593
|
-
status: error !== undefined
|
|
594
|
-
? "failed"
|
|
595
|
-
: done
|
|
596
|
-
? "completed"
|
|
597
|
-
: emissions > 0
|
|
598
|
-
? "running"
|
|
599
|
-
: "pending",
|
|
600
|
-
emissions,
|
|
601
|
-
escalations: escalationsPerNode.get(node.id) ?? 0
|
|
602
|
-
};
|
|
603
|
-
if (error !== undefined) {
|
|
604
|
-
state.error = String(redactValue(error, secrets));
|
|
605
|
-
}
|
|
606
|
-
return state;
|
|
607
|
-
});
|
|
608
|
-
return {
|
|
609
|
-
jobId: this._effectiveJobId,
|
|
610
|
-
nodes,
|
|
611
|
-
costUsd: this._options.executionContext?.getTotalCost?.() ?? 0
|
|
612
|
-
};
|
|
613
|
-
}
|
|
614
|
-
_readRecordedOutput(nodeId, lineage) {
|
|
615
|
-
const perLineage = this._recordedOutputs.get(nodeId);
|
|
616
|
-
if (!perLineage)
|
|
617
|
-
return null;
|
|
618
|
-
// Most specific first: an entry sharing more of the failing invocation's
|
|
619
|
-
// roots is closer to it causally than a single-fire ancestor.
|
|
620
|
-
let best = null;
|
|
621
|
-
for (const [key, outputs] of perLineage) {
|
|
622
|
-
const recorded = key === "" ? [] : key.split(",");
|
|
623
|
-
if (!lineageRelated(recorded, lineage))
|
|
624
|
-
continue;
|
|
625
|
-
if (best === null || recorded.length > best.lineage.length) {
|
|
626
|
-
best = { nodeId, lineage: recorded, outputs };
|
|
627
|
-
}
|
|
628
|
-
}
|
|
629
|
-
return best;
|
|
630
|
-
}
|
|
631
|
-
/**
|
|
632
|
-
* Remember what a node emitted, keyed by the invocation's lineage, so a
|
|
633
|
-
* supervisor can read a producer's output while deciding a consumer's
|
|
634
|
-
* failure. Off unless the run is supervised.
|
|
635
|
-
*/
|
|
636
|
-
_recordNodeOutput(sourceNodeId, outputs, lineage) {
|
|
637
|
-
const scope = this._correlation?.nodes.get(sourceNodeId)?.invocationScope;
|
|
638
|
-
const key = scope && scope.length > 0 && lineage
|
|
639
|
-
? projectLineageKey(lineage, scope)
|
|
640
|
-
: "";
|
|
641
|
-
let perLineage = this._recordedOutputs.get(sourceNodeId);
|
|
642
|
-
if (!perLineage) {
|
|
643
|
-
perLineage = new Map();
|
|
644
|
-
this._recordedOutputs.set(sourceNodeId, perLineage);
|
|
645
|
-
}
|
|
646
|
-
// Re-inserting moves the key to the end, so the eviction below always
|
|
647
|
-
// drops the least recently emitted lineage rather than a live one.
|
|
648
|
-
perLineage.delete(key);
|
|
649
|
-
perLineage.set(key, outputs);
|
|
650
|
-
while (perLineage.size > MAX_RECORDED_LINEAGES_PER_NODE) {
|
|
651
|
-
const oldest = perLineage.keys().next();
|
|
652
|
-
if (oldest.done)
|
|
653
|
-
break;
|
|
654
|
-
perLineage.delete(oldest.value);
|
|
655
|
-
}
|
|
656
|
-
}
|
|
657
|
-
/** Actors spawned and not yet finished. Zero before and after a run. */
|
|
658
|
-
get liveActorCount() {
|
|
659
|
-
return this._liveActors;
|
|
660
|
-
}
|
|
661
|
-
/** Control-event responses still waiting on an actor, summed over nodes. */
|
|
662
|
-
get pendingControlResponseCount() {
|
|
663
|
-
let count = 0;
|
|
664
|
-
for (const queue of this._pendingControlResponses.values()) {
|
|
665
|
-
count += queue.length;
|
|
666
|
-
}
|
|
667
|
-
return count;
|
|
668
|
-
}
|
|
669
|
-
/**
|
|
670
|
-
* Push property updates into a running node's executor instance (live
|
|
671
|
-
* parameter changes — e.g. turning a synth knob while the patch plays).
|
|
672
|
-
* Returns true when the node's executor exists and supports live updates;
|
|
673
|
-
* false is not an error — the caller's canvas state already holds the new
|
|
674
|
-
* value for the next run.
|
|
675
|
-
*/
|
|
676
|
-
updateNodeProperties(nodeId, properties) {
|
|
677
|
-
const executor = this._executors.get(nodeId);
|
|
678
|
-
if (!executor?.applyProperties)
|
|
679
|
-
return false;
|
|
680
|
-
executor.applyProperties(properties);
|
|
681
|
-
return true;
|
|
682
|
-
}
|
|
683
|
-
cancel() {
|
|
684
|
-
// Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
|
|
685
|
-
log.info("Job cancelled", { jobId: this.jobId });
|
|
686
|
-
// Latch the request so a cancel before run() survives _resetRunState. §17.
|
|
687
|
-
this._cancelRequested = true;
|
|
688
|
-
this._cancelled = true;
|
|
689
|
-
// Stop producing loops (generators, pacers) that never wait on inputs —
|
|
690
|
-
// closing inboxes only unblocks consumers. Nodes observe this via
|
|
691
|
-
// `inputs.signal`.
|
|
692
|
-
this._abortController.abort();
|
|
693
|
-
// Close all inboxes to unblock waiting actors
|
|
694
|
-
for (const inbox of this._inboxes.values()) {
|
|
695
|
-
void inbox.closeAll();
|
|
696
|
-
}
|
|
697
|
-
}
|
|
698
|
-
// -----------------------------------------------------------------------
|
|
699
|
-
// Invalid edge filtering (Python parity: _filter_invalid_edges)
|
|
700
|
-
// -----------------------------------------------------------------------
|
|
701
|
-
/**
|
|
702
|
-
* Remove edges whose source or target node doesn't exist in the graph.
|
|
703
|
-
* Reconstructs the graph without dangling edges.
|
|
704
|
-
*/
|
|
705
|
-
_filterInvalidEdges() {
|
|
706
|
-
const validEdges = this._graph.edges.filter((edge) => this._graph.findNode(edge.source) !== undefined &&
|
|
707
|
-
this._graph.findNode(edge.target) !== undefined);
|
|
708
|
-
if (validEdges.length < this._graph.edges.length) {
|
|
709
|
-
// Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
|
|
710
|
-
log.warn("Filtered invalid edges", {
|
|
711
|
-
// Stryker disable next-line ArithmeticOperator: diagnostic log arg only
|
|
712
|
-
removed: this._graph.edges.length - validEdges.length,
|
|
713
|
-
remaining: validEdges.length
|
|
714
|
-
});
|
|
715
|
-
this._graph = new Graph({
|
|
716
|
-
nodes: [...this._graph.nodes],
|
|
717
|
-
edges: validEdges
|
|
718
|
-
});
|
|
719
|
-
}
|
|
720
|
-
}
|
|
721
|
-
/**
|
|
722
|
-
* Run the optional `validateNode` callback for every node in the graph,
|
|
723
|
-
* passing the set of property handles that have an incoming data edge.
|
|
724
|
-
* Aggregates issues across nodes and throws a single GraphValidationError.
|
|
725
|
-
*/
|
|
726
|
-
_validateNodes() {
|
|
727
|
-
const validator = this._options.validateNode;
|
|
728
|
-
if (!validator)
|
|
729
|
-
return;
|
|
730
|
-
// Build map: nodeId -> set of targetHandles with an incoming data edge.
|
|
731
|
-
const connectedByNode = new Map();
|
|
732
|
-
for (const edge of this._graph.edges) {
|
|
733
|
-
if (!isDataEdge(edge))
|
|
734
|
-
continue;
|
|
735
|
-
let handles = connectedByNode.get(edge.target);
|
|
736
|
-
if (!handles) {
|
|
737
|
-
handles = new Set();
|
|
738
|
-
connectedByNode.set(edge.target, handles);
|
|
739
|
-
}
|
|
740
|
-
handles.add(edge.targetHandle);
|
|
741
|
-
}
|
|
742
|
-
const issues = [];
|
|
743
|
-
for (const node of this._graph.nodes) {
|
|
744
|
-
const handles = connectedByNode.get(node.id) ?? new Set();
|
|
745
|
-
const nodeIssues = validator(node, handles);
|
|
746
|
-
if (nodeIssues && nodeIssues.length > 0) {
|
|
747
|
-
for (const issue of nodeIssues) {
|
|
748
|
-
issues.push({
|
|
749
|
-
nodeId: issue.nodeId ?? node.id,
|
|
750
|
-
nodeType: issue.nodeType ?? node.type,
|
|
751
|
-
property: issue.property,
|
|
752
|
-
message: issue.message
|
|
753
|
-
});
|
|
754
|
-
}
|
|
755
|
-
}
|
|
756
|
-
}
|
|
757
|
-
if (issues.length > 0) {
|
|
758
|
-
const lines = issues.map((issue) => {
|
|
759
|
-
const where = ` on node "${issue.nodeId}"${issue.nodeType ? ` (${issue.nodeType})` : ""}`;
|
|
760
|
-
return ` - ${issue.message}${where}`;
|
|
761
|
-
});
|
|
762
|
-
throw new GraphValidationError(`Graph validation failed with ${issues.length} issue(s):\n${lines.join("\n")}`, issues.map((issue) => ({
|
|
763
|
-
nodeId: issue.nodeId,
|
|
764
|
-
nodeType: issue.nodeType,
|
|
765
|
-
property: issue.property,
|
|
766
|
-
message: issue.message
|
|
767
|
-
})));
|
|
768
|
-
}
|
|
769
|
-
}
|
|
770
|
-
/** Refuse to start when a required workflow input has no supplied value. */
|
|
771
|
-
_validateRequiredInputs(params) {
|
|
772
|
-
const nodesWithIncomingData = new Set();
|
|
773
|
-
const nodesWithIncomingControl = new Set();
|
|
774
|
-
for (const edge of this._graph.edges) {
|
|
775
|
-
if (isDataEdge(edge)) {
|
|
776
|
-
nodesWithIncomingData.add(edge.target);
|
|
777
|
-
}
|
|
778
|
-
else if (isControlEdge(edge)) {
|
|
779
|
-
nodesWithIncomingControl.add(edge.target);
|
|
780
|
-
}
|
|
781
|
-
}
|
|
782
|
-
const missingNames = [];
|
|
783
|
-
const issues = [];
|
|
784
|
-
for (const node of this._graph.nodes) {
|
|
785
|
-
if (!node.type.startsWith("nodetool.input."))
|
|
786
|
-
continue;
|
|
787
|
-
if (node.is_streaming_output)
|
|
788
|
-
continue;
|
|
789
|
-
if (nodesWithIncomingData.has(node.id) ||
|
|
790
|
-
nodesWithIncomingControl.has(node.id)) {
|
|
791
|
-
continue;
|
|
792
|
-
}
|
|
793
|
-
const inputName = this._getExternalInputName(node);
|
|
794
|
-
const properties = isObjectValue(node.properties)
|
|
795
|
-
? node.properties
|
|
796
|
-
: {};
|
|
797
|
-
if (hasDefinedOwnProperty(params, inputName) ||
|
|
798
|
-
hasDefinedOwnProperty(properties, "value")) {
|
|
799
|
-
continue;
|
|
800
|
-
}
|
|
801
|
-
if (!missingNames.includes(inputName)) {
|
|
802
|
-
missingNames.push(inputName);
|
|
803
|
-
}
|
|
804
|
-
issues.push({
|
|
805
|
-
nodeId: node.id,
|
|
806
|
-
nodeType: node.type,
|
|
807
|
-
property: "value",
|
|
808
|
-
message: `Missing required workflow input "${inputName}"`
|
|
809
|
-
});
|
|
810
|
-
}
|
|
811
|
-
if (issues.length > 0) {
|
|
812
|
-
throw new GraphValidationError(`Missing required workflow inputs: ${missingNames.join(", ")}`, issues);
|
|
813
|
-
}
|
|
814
|
-
}
|
|
815
|
-
// -----------------------------------------------------------------------
|
|
816
|
-
// Node initialization
|
|
817
|
-
// -----------------------------------------------------------------------
|
|
818
|
-
/**
|
|
819
|
-
* Initialize every node's executor before any actor runs.
|
|
820
|
-
*
|
|
821
|
-
* A failure here aborts the run before `_processGraph`, so the actors that
|
|
822
|
-
* would normally call `finalize()` never start. Finalize the executors that
|
|
823
|
-
* did initialize, otherwise whatever they opened (python bridge handles,
|
|
824
|
-
* provider clients, file descriptors) leaks for the lifetime of the process.
|
|
825
|
-
* The failure is also re-thrown with the offending node's identity attached —
|
|
826
|
-
* a bare "connect ECONNREFUSED" gives no clue which node to fix.
|
|
827
|
-
*/
|
|
828
|
-
async _initializeGraph() {
|
|
829
|
-
const initialized = [];
|
|
830
|
-
for (const node of this._graph.nodes) {
|
|
831
|
-
const executor = this._resolveExecutor(node);
|
|
832
|
-
if (!executor.initialize)
|
|
833
|
-
continue;
|
|
834
|
-
try {
|
|
835
|
-
await executor.initialize();
|
|
836
|
-
initialized.push(executor);
|
|
837
|
-
}
|
|
838
|
-
catch (err) {
|
|
839
|
-
await this._finalizeExecutors(initialized);
|
|
840
|
-
const message = err instanceof Error ? err.message : String(err);
|
|
841
|
-
throw new Error(`Node "${node.name ?? node.id}" (${node.type}) failed to initialize: ${message}`, { cause: err });
|
|
842
|
-
}
|
|
843
|
-
}
|
|
844
|
-
}
|
|
845
|
-
/** Finalize executors, never letting one failure hide another. */
|
|
846
|
-
async _finalizeExecutors(executors) {
|
|
847
|
-
for (const executor of executors) {
|
|
848
|
-
if (!executor.finalize)
|
|
849
|
-
continue;
|
|
850
|
-
try {
|
|
851
|
-
await executor.finalize();
|
|
852
|
-
}
|
|
853
|
-
catch (err) {
|
|
854
|
-
// Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
|
|
855
|
-
log.warn("Executor finalize failed during initialization rollback", {
|
|
856
|
-
error: err instanceof Error ? err.message : String(err)
|
|
857
|
-
});
|
|
858
|
-
}
|
|
859
|
-
}
|
|
860
|
-
}
|
|
861
|
-
/** Resolve (and cache) the executor instance for a node. */
|
|
862
|
-
_resolveExecutor(node) {
|
|
863
|
-
let executor = this._executors.get(node.id);
|
|
864
|
-
if (!executor) {
|
|
865
|
-
executor = this._options.resolveExecutor(node);
|
|
866
|
-
this._executors.set(node.id, executor);
|
|
867
|
-
}
|
|
868
|
-
return executor;
|
|
869
|
-
}
|
|
870
|
-
// -----------------------------------------------------------------------
|
|
871
|
-
// Inbox initialization
|
|
872
|
-
// -----------------------------------------------------------------------
|
|
873
|
-
_initializeInboxes() {
|
|
874
|
-
for (const node of this._graph.nodes) {
|
|
875
|
-
const inbox = new NodeInbox(this._options.bufferLimit ?? null);
|
|
876
|
-
// Count upstream sources per handle from data edges
|
|
877
|
-
const incomingData = this._graph.findDataEdges(node.id);
|
|
878
|
-
const handleCounts = new Map();
|
|
879
|
-
for (const edge of incomingData) {
|
|
880
|
-
const cur = handleCounts.get(edge.targetHandle) ?? 0;
|
|
881
|
-
handleCounts.set(edge.targetHandle, cur + 1);
|
|
882
|
-
}
|
|
883
|
-
// Also count control edges
|
|
884
|
-
const incomingControl = this._graph
|
|
885
|
-
.findIncomingEdges(node.id)
|
|
886
|
-
.filter(isControlEdge);
|
|
887
|
-
if (incomingControl.length > 0) {
|
|
888
|
-
const uniqueControllerCount = new Set(incomingControl.map((e) => e.source)).size;
|
|
889
|
-
handleCounts.set("__control__", (handleCounts.get("__control__") ?? 0) + uniqueControllerCount);
|
|
890
|
-
}
|
|
891
|
-
for (const [handle, count] of handleCounts) {
|
|
892
|
-
inbox.addUpstream(handle, count);
|
|
893
|
-
}
|
|
894
|
-
this._inboxes.set(node.id, inbox);
|
|
895
|
-
}
|
|
896
|
-
}
|
|
897
|
-
// -----------------------------------------------------------------------
|
|
898
|
-
// Multi-edge list detection
|
|
899
|
-
// -----------------------------------------------------------------------
|
|
900
|
-
_detectMultiEdgeListInputs() {
|
|
901
|
-
// Find handles that receive more than one edge AND whose property type
|
|
902
|
-
// is a list type. Non-list handles with multiple edges should NOT be
|
|
903
|
-
// marked for aggregation (Python parity: _classify_list_inputs).
|
|
904
|
-
const handleEdgeCounts = new Map(); // key = nodeId:handle
|
|
905
|
-
for (const edge of this._graph.edges) {
|
|
906
|
-
if (isControlEdge(edge))
|
|
907
|
-
continue;
|
|
908
|
-
const key = `${edge.target}:${edge.targetHandle}`;
|
|
909
|
-
handleEdgeCounts.set(key, (handleEdgeCounts.get(key) ?? 0) + 1);
|
|
910
|
-
}
|
|
911
|
-
for (const [key, count] of handleEdgeCounts) {
|
|
912
|
-
if (count > 1) {
|
|
913
|
-
const sepIdx = key.lastIndexOf(":");
|
|
914
|
-
const nodeId = key.substring(0, sepIdx);
|
|
915
|
-
const handle = key.substring(sepIdx + 1);
|
|
916
|
-
// Look up the target node to check its property type
|
|
917
|
-
const node = this._graph.findNode(nodeId);
|
|
918
|
-
if (!node)
|
|
919
|
-
continue;
|
|
920
|
-
// Validate that the handle's type is a list type
|
|
921
|
-
const propertyTypes = node.propertyTypes;
|
|
922
|
-
if (propertyTypes) {
|
|
923
|
-
const typeStr = propertyTypes[handle];
|
|
924
|
-
if (typeStr) {
|
|
925
|
-
const meta = TypeMetadata.fromString(typeStr);
|
|
926
|
-
if (!meta.isListType()) {
|
|
927
|
-
// Multiple edges to non-list property — skip aggregation
|
|
928
|
-
continue;
|
|
929
|
-
}
|
|
930
|
-
}
|
|
931
|
-
}
|
|
932
|
-
if (!this._multiEdgeListInputs.has(nodeId)) {
|
|
933
|
-
this._multiEdgeListInputs.set(nodeId, new Set());
|
|
934
|
-
}
|
|
935
|
-
this._multiEdgeListInputs.get(nodeId).add(handle);
|
|
936
|
-
}
|
|
937
|
-
}
|
|
938
|
-
}
|
|
939
|
-
// -----------------------------------------------------------------------
|
|
940
|
-
// Input dispatch
|
|
941
|
-
// -----------------------------------------------------------------------
|
|
942
|
-
/**
|
|
943
|
-
* Deliver input parameters to input nodes (nodes with no incoming data edges).
|
|
944
|
-
* After delivery, mark them as done (EOS) since input nodes produce exactly
|
|
945
|
-
* one value.
|
|
946
|
-
*/
|
|
947
|
-
/** Variable-channel name a Set Variable node publishes to (its `name` prop). */
|
|
948
|
-
_variableChannelName(node) {
|
|
949
|
-
const props = isObjectValue(node.properties) ? node.properties : {};
|
|
950
|
-
const raw = props.name;
|
|
951
|
-
return isString(raw) ? raw.trim() : "";
|
|
952
|
-
}
|
|
953
|
-
/**
|
|
954
|
-
* Tell the context how many Set Variable writers each channel has, before any
|
|
955
|
-
* actor runs. A channel with no writers then closes on first read so readers
|
|
956
|
-
* (Get Variable streams, Prompt awaits) end cleanly instead of hanging.
|
|
957
|
-
*/
|
|
958
|
-
_registerVariableChannels() {
|
|
959
|
-
const ctx = this._options.executionContext;
|
|
960
|
-
if (!ctx || !isCallable(ctx.registerChannelWriters)) {
|
|
961
|
-
return;
|
|
962
|
-
}
|
|
963
|
-
for (const node of this._graph.nodes) {
|
|
964
|
-
if (node.type !== SET_VARIABLE_NODE_TYPE) {
|
|
965
|
-
continue;
|
|
966
|
-
}
|
|
967
|
-
const name = this._variableChannelName(node);
|
|
968
|
-
if (name) {
|
|
969
|
-
ctx.registerChannelWriters(name, 1);
|
|
970
|
-
}
|
|
971
|
-
}
|
|
972
|
-
}
|
|
973
|
-
async _dispatchInputs(params) {
|
|
974
|
-
for (const node of this._graph.nodes) {
|
|
975
|
-
const incoming = this._graph.findDataEdges(node.id);
|
|
976
|
-
if (incoming.length > 0)
|
|
977
|
-
continue; // not an input node
|
|
978
|
-
// A node with an incoming control edge is run by its actor in
|
|
979
|
-
// _processGraph (which only skips actor-spawning when the node has
|
|
980
|
-
// neither data nor control edges). Skipping it here keeps the two
|
|
981
|
-
// predicates in parity — otherwise a controlled input node would be
|
|
982
|
-
// both one-shot dispatched here and spawned as an actor (double run).
|
|
983
|
-
const incomingControl = this._graph
|
|
984
|
-
.findIncomingEdges(node.id)
|
|
985
|
-
.filter(isControlEdge);
|
|
986
|
-
if (incomingControl.length > 0)
|
|
987
|
-
continue;
|
|
988
|
-
if (!this._isExternalInputNode(node))
|
|
989
|
-
continue;
|
|
990
|
-
const inputName = this._getExternalInputName(node);
|
|
991
|
-
const properties = isObjectValue(node.properties)
|
|
992
|
-
? node.properties
|
|
993
|
-
: {};
|
|
994
|
-
const hasRuntimeParam = hasDefinedOwnProperty(params, inputName);
|
|
995
|
-
const hasDefaultValue = hasDefinedOwnProperty(properties, "value");
|
|
996
|
-
// A streaming input keeps its edges open for pushInputValue().
|
|
997
|
-
if (node.is_streaming_output) {
|
|
998
|
-
for (const edge of this._graph.findOutgoingEdges(node.id)) {
|
|
999
|
-
if (!isDataEdge(edge))
|
|
1000
|
-
continue;
|
|
1001
|
-
this._openExternalStreamEdges.add(edge.id ??
|
|
1002
|
-
syntheticEdgeId(edge.source, edge.sourceHandle, edge.target, edge.targetHandle));
|
|
1003
|
-
}
|
|
1004
|
-
}
|
|
1005
|
-
// Streaming output input nodes (e.g. RealtimeAudioInput) should NOT
|
|
1006
|
-
// push empty defaults — real data will arrive later via pushInputValue().
|
|
1007
|
-
// Non-streaming inputs must push their default so downstream nodes can run.
|
|
1008
|
-
// (Python parity: checks is_streaming_output.)
|
|
1009
|
-
if (!hasRuntimeParam && (node.is_streaming_output || !hasDefaultValue)) {
|
|
1010
|
-
continue;
|
|
1011
|
-
}
|
|
1012
|
-
const value = hasRuntimeParam ? params[inputName] : properties.value;
|
|
1013
|
-
// Run the node's own process() so transforming input nodes (e.g.
|
|
1014
|
-
// DocumentFileInput building a DocumentRef, StringInput applying
|
|
1015
|
-
// max_length, MessageDeconstructor splitting a message) emit their
|
|
1016
|
-
// declared per-handle outputs instead of leaking the raw value to
|
|
1017
|
-
// every edge. Uses the cached executor instance initialized in
|
|
1018
|
-
// _initializeGraph. Test doubles whose process() returns an empty
|
|
1019
|
-
// record fall back to raw-value dispatch per handle below; a real
|
|
1020
|
-
// process() failure fails the run rather than leaking the raw value.
|
|
1021
|
-
const executor = this._resolveExecutor(node);
|
|
1022
|
-
let nodeOutputs;
|
|
1023
|
-
try {
|
|
1024
|
-
nodeOutputs = await executor.process({ value }, this._options.executionContext);
|
|
1025
|
-
}
|
|
1026
|
-
catch (err) {
|
|
1027
|
-
const message = err instanceof Error ? err.message : String(err);
|
|
1028
|
-
throw new Error(`Input node "${node.name ?? node.id}" (${node.type}) failed: ${message}`);
|
|
1029
|
-
}
|
|
1030
|
-
// Raw-value fallback only when process() produced no defined output at
|
|
1031
|
-
// all (the documented test-double case, incl. `{}`). Once the record
|
|
1032
|
-
// carries any real output, a handle it legitimately omits (e.g. an input
|
|
1033
|
-
// with no attachments) stays silent instead of leaking the raw input
|
|
1034
|
-
// value onto that edge. §6. Keyed on `!== undefined` to match the
|
|
1035
|
-
// per-handle check below. The EOS pass below still closes every edge so
|
|
1036
|
-
// downstream nodes complete.
|
|
1037
|
-
const outputsEmpty = !Object.values(nodeOutputs).some((v) => v !== undefined);
|
|
1038
|
-
const outgoing = this._graph
|
|
1039
|
-
.findOutgoingEdges(node.id)
|
|
1040
|
-
.filter(isDataEdge);
|
|
1041
|
-
for (const edge of outgoing) {
|
|
1042
|
-
const hasHandleValue = Object.hasOwn(nodeOutputs, edge.sourceHandle) &&
|
|
1043
|
-
nodeOutputs[edge.sourceHandle] !== undefined;
|
|
1044
|
-
if (!outputsEmpty && !hasHandleValue)
|
|
1045
|
-
continue;
|
|
1046
|
-
const targetInbox = this._inboxes.get(edge.target);
|
|
1047
|
-
if (targetInbox) {
|
|
1048
|
-
const handleValue = hasHandleValue
|
|
1049
|
-
? nodeOutputs[edge.sourceHandle]
|
|
1050
|
-
: value;
|
|
1051
|
-
await targetInbox.put(edge.targetHandle, handleValue, {
|
|
1052
|
-
source_edge_id: edge.id ??
|
|
1053
|
-
syntheticEdgeId(edge.source, edge.sourceHandle, edge.target, edge.targetHandle)
|
|
1054
|
-
});
|
|
1055
|
-
}
|
|
1056
|
-
this._incrementEdgeCounter(edge);
|
|
1057
|
-
}
|
|
1058
|
-
// Streaming output input nodes (e.g. RealtimeAudioInput) keep their
|
|
1059
|
-
// downstream inboxes open so that future pushInputValue() calls can
|
|
1060
|
-
// deliver more data. Non-streaming input nodes signal EOS immediately
|
|
1061
|
-
// since they produce exactly one value.
|
|
1062
|
-
// (Python parity: _dispatch_inputs checks is_streaming_output, not
|
|
1063
|
-
// is_streaming_input.)
|
|
1064
|
-
if (!node.is_streaming_output) {
|
|
1065
|
-
for (const edge of outgoing) {
|
|
1066
|
-
const targetInbox = this._inboxes.get(edge.target);
|
|
1067
|
-
if (targetInbox) {
|
|
1068
|
-
targetInbox.markSourceDone(edge.targetHandle);
|
|
1069
|
-
}
|
|
1070
|
-
}
|
|
1071
|
-
}
|
|
1072
|
-
}
|
|
1073
|
-
}
|
|
1074
|
-
// -----------------------------------------------------------------------
|
|
1075
|
-
// Graph processing
|
|
1076
|
-
// -----------------------------------------------------------------------
|
|
1077
|
-
/**
|
|
1078
|
-
* Spawn one NodeActor per node and run them concurrently.
|
|
1079
|
-
* Actors that depend on inputs will block on their inboxes until
|
|
1080
|
-
* upstream actors produce data.
|
|
1081
|
-
*/
|
|
1082
|
-
async _processGraph() {
|
|
1083
|
-
// Before any actor can escalate, the supervisor gets its read-only view.
|
|
1084
|
-
// A handle that throws here is a broken supervisor, and a broken
|
|
1085
|
-
// supervisor must never be worse for the run than no supervisor: it
|
|
1086
|
-
// proceeds without a reader and its decisions degrade to `fail`.
|
|
1087
|
-
try {
|
|
1088
|
-
this._supervisor?.attach?.(this._runStateReader());
|
|
1089
|
-
}
|
|
1090
|
-
catch (error) {
|
|
1091
|
-
// Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
|
|
1092
|
-
log.warn("Supervisor attach failed; running without a run-state view", {
|
|
1093
|
-
error: error instanceof Error ? error.message : String(error)
|
|
1094
|
-
});
|
|
1095
|
-
}
|
|
1096
|
-
this._installQuiescenceDetection();
|
|
1097
|
-
const actorPromises = [];
|
|
1098
|
-
/** Parallel to `actorPromises` — maps a settled index back to its node. */
|
|
1099
|
-
const actorNodeIds = [];
|
|
1100
|
-
for (const node of this._graph.nodes) {
|
|
1101
|
-
// Skip input-only nodes that have no incoming edges
|
|
1102
|
-
// (they were already handled in _dispatchInputs)
|
|
1103
|
-
const incoming = this._graph.findDataEdges(node.id);
|
|
1104
|
-
const incomingControl = this._graph
|
|
1105
|
-
.findIncomingEdges(node.id)
|
|
1106
|
-
.filter(isControlEdge);
|
|
1107
|
-
if (incoming.length === 0 &&
|
|
1108
|
-
incomingControl.length === 0 &&
|
|
1109
|
-
this._isExternalInputNode(node)) {
|
|
1110
|
-
continue; // pure input node, already dispatched
|
|
1111
|
-
}
|
|
1112
|
-
const inbox = this._inboxes.get(node.id);
|
|
1113
|
-
const executor = this._resolveExecutor(node);
|
|
1114
|
-
// Build control context for controller nodes (Python parity:
|
|
1115
|
-
// _is_controller / _build_control_context). This tells the node
|
|
1116
|
-
// which downstream nodes it controls and their available properties.
|
|
1117
|
-
const controlContext = this._buildControlContext(node.id);
|
|
1118
|
-
const actor = new NodeActor({
|
|
1119
|
-
node,
|
|
1120
|
-
inbox,
|
|
1121
|
-
executor,
|
|
1122
|
-
sendOutputs: async (nodeId, outputs, hints) => {
|
|
1123
|
-
await this._sendMessages(nodeId, outputs, hints);
|
|
1124
|
-
},
|
|
1125
|
-
emitMessage: (msg) => {
|
|
1126
|
-
this._emit(msg);
|
|
1127
|
-
},
|
|
1128
|
-
executionContext: this._options.executionContext,
|
|
1129
|
-
listInputHandles: this._multiEdgeListInputs.get(node.id),
|
|
1130
|
-
controlContext,
|
|
1131
|
-
correlation: this._correlation?.nodes.get(node.id),
|
|
1132
|
-
cancelSignal: this._abortController.signal,
|
|
1133
|
-
signalSlotEos: (sourceNodeId, slot) => this._signalSlotEos(sourceNodeId, slot),
|
|
1134
|
-
supervisor: this._supervisor,
|
|
1135
|
-
onIntervention: (intervention) => this._interventions.push(intervention)
|
|
1136
|
-
});
|
|
1137
|
-
actorNodeIds.push(node.id);
|
|
1138
|
-
this._liveActors++;
|
|
1139
|
-
this._liveActorIds.add(node.id);
|
|
1140
|
-
actorPromises.push(actor
|
|
1141
|
-
.run()
|
|
1142
|
-
.then(async (result) => {
|
|
1143
|
-
// Nothing will read this inbox again. Wake any upstream actor parked
|
|
1144
|
-
// on a full buffer so it can finish instead of waiting forever for a
|
|
1145
|
-
// consumer that is gone.
|
|
1146
|
-
inbox.releaseBackpressure();
|
|
1147
|
-
if (result.error !== undefined) {
|
|
1148
|
-
this._nodeErrors.set(node.id, result.error);
|
|
1149
|
-
this._missingPack ??= result.errorDetail?.missing_pack ?? undefined;
|
|
1150
|
-
}
|
|
1151
|
-
// After actor completes, send EOS to all downstream inboxes
|
|
1152
|
-
await this._sendEOS(node.id);
|
|
1153
|
-
// A Set Variable writer finished — when the last writer for a channel
|
|
1154
|
-
// is done, the context closes it so readers (Get Variable / Prompt)
|
|
1155
|
-
// drain and end instead of waiting forever.
|
|
1156
|
-
if (node.type === SET_VARIABLE_NODE_TYPE) {
|
|
1157
|
-
const channelName = this._variableChannelName(node);
|
|
1158
|
-
if (channelName) {
|
|
1159
|
-
this._options.executionContext?.markChannelWriterDone?.(channelName);
|
|
1160
|
-
}
|
|
1161
|
-
}
|
|
1162
|
-
// The actor's run loop is gone — it can no longer answer control
|
|
1163
|
-
// events. Mark it so future sendControlEvent calls reject fast
|
|
1164
|
-
// rather than hang, and reject any response still waiting on it
|
|
1165
|
-
// (the actor finished without producing the awaited output, e.g.
|
|
1166
|
-
// it errored mid-burst).
|
|
1167
|
-
this._completedNodes.add(node.id);
|
|
1168
|
-
const pendingQueue = this._pendingControlResponses.get(node.id);
|
|
1169
|
-
if (pendingQueue) {
|
|
1170
|
-
this._pendingControlResponses.delete(node.id);
|
|
1171
|
-
for (const pending of pendingQueue) {
|
|
1172
|
-
pending.reject(result.errorDetail?.missing_pack ? new MissingPackError(result.errorDetail.missing_pack) : new Error(result.error ??
|
|
1173
|
-
`Controlled node ${node.id} completed without responding`));
|
|
1174
|
-
}
|
|
1175
|
-
}
|
|
1176
|
-
// If this is an output node, collect the result
|
|
1177
|
-
if (this._isOutputNode(node)) {
|
|
1178
|
-
const name = this._outputCollectionKey(node);
|
|
1179
|
-
if (!this._outputs.has(name)) {
|
|
1180
|
-
this._outputs.set(name, []);
|
|
1181
|
-
}
|
|
1182
|
-
if (result.outputs) {
|
|
1183
|
-
for (const val of Object.values(result.outputs)) {
|
|
1184
|
-
this._outputs.get(name).push(val);
|
|
1185
|
-
}
|
|
1186
|
-
}
|
|
1187
|
-
}
|
|
1188
|
-
})
|
|
1189
|
-
// Counts the actor as live until its completion handling (EOS
|
|
1190
|
-
// routing, output collection) is done too — that work can still emit
|
|
1191
|
-
// messages, so an actor is not "gone" before it finishes.
|
|
1192
|
-
.finally(() => {
|
|
1193
|
-
this._liveActors--;
|
|
1194
|
-
this._liveActorIds.delete(node.id);
|
|
1195
|
-
// An actor that exits instead of parking may have been the last
|
|
1196
|
-
// busy one.
|
|
1197
|
-
this._scheduleQuiescenceCheck?.();
|
|
1198
|
-
}));
|
|
1199
|
-
}
|
|
1200
|
-
// Wait for every actor, including post-completion routing. `allSettled`
|
|
1201
|
-
// rather than `all`: a throw in one actor's completion handler (EOS
|
|
1202
|
-
// routing, channel bookkeeping, a message-transport failure) must not
|
|
1203
|
-
// return the run while its siblings are still executing — orphaned actors
|
|
1204
|
-
// would keep writing to inboxes and emitting messages after the runner
|
|
1205
|
-
// reported a terminal status.
|
|
1206
|
-
const settled = await Promise.allSettled(actorPromises);
|
|
1207
|
-
for (const [index, outcome] of settled.entries()) {
|
|
1208
|
-
if (outcome.status !== "rejected")
|
|
1209
|
-
continue;
|
|
1210
|
-
const nodeId = actorNodeIds[index];
|
|
1211
|
-
const message = outcome.reason instanceof Error
|
|
1212
|
-
? outcome.reason.message
|
|
1213
|
-
: String(outcome.reason);
|
|
1214
|
-
// Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
|
|
1215
|
-
log.error("Actor completion handling failed", { nodeId, error: message });
|
|
1216
|
-
if (!this._nodeErrors.has(nodeId)) {
|
|
1217
|
-
this._nodeErrors.set(nodeId, message);
|
|
1218
|
-
}
|
|
1219
|
-
}
|
|
1220
|
-
// Backstop: release any reader still waiting on a channel (e.g. a writer
|
|
1221
|
-
// that errored before publishing). Non-cyclic graphs are already closed by
|
|
1222
|
-
// markChannelWriterDone above.
|
|
1223
|
-
this._options.executionContext?.closeAllChannels?.();
|
|
1224
|
-
// Check for in-flight messages after all actors complete (Python parity: _check_pending_inbox_work)
|
|
1225
|
-
const pendingNodes = this._checkPendingInboxWork();
|
|
1226
|
-
if (pendingNodes.length > 0) {
|
|
1227
|
-
if (this._options.strict && !this._cancelled) {
|
|
1228
|
-
throw new Error(`Strict mode: pending inbox work detected after all actors ` +
|
|
1229
|
-
`completed for node(s): ${pendingNodes.join(", ")}`);
|
|
1230
|
-
}
|
|
1231
|
-
log.warn(
|
|
1232
|
-
// Stryker disable next-line StringLiteral: diagnostic log args only
|
|
1233
|
-
"Pending inbox work detected after all actors completed — possible data loss",
|
|
1234
|
-
// Stryker disable next-line ObjectLiteral: diagnostic log args only
|
|
1235
|
-
{
|
|
1236
|
-
pendingNodes
|
|
1237
|
-
});
|
|
1238
|
-
}
|
|
1239
|
-
// Check for controlled-node control events whose response never arrived
|
|
1240
|
-
// (the target actor completed — or was never reachable — while a
|
|
1241
|
-
// `sendControlEvent` waiter was still registered for it). Every
|
|
1242
|
-
// completion path (actor completion handler, the completion race guard
|
|
1243
|
-
// in `sendControlEvent`) rejects its own waiters, so a non-empty queue
|
|
1244
|
-
// here means a waiter was registered for a node whose actor never ran at
|
|
1245
|
-
// all, or another gap in that bookkeeping — either way, "zero pending
|
|
1246
|
-
// control responses" (§6) is violated.
|
|
1247
|
-
const pendingControlNodes = [...this._pendingControlResponses.entries()]
|
|
1248
|
-
.filter(([, queue]) => queue.length > 0)
|
|
1249
|
-
.map(([nodeId]) => nodeId);
|
|
1250
|
-
if (pendingControlNodes.length > 0) {
|
|
1251
|
-
if (this._options.strict && !this._cancelled) {
|
|
1252
|
-
throw new Error(`Strict mode: pending control-event responses never resolved for ` +
|
|
1253
|
-
`node(s): ${pendingControlNodes.join(", ")}`);
|
|
1254
|
-
}
|
|
1255
|
-
log.warn(
|
|
1256
|
-
// Stryker disable next-line StringLiteral: diagnostic log args only
|
|
1257
|
-
"Pending control-event responses after all actors completed — possible hang",
|
|
1258
|
-
// Stryker disable next-line ObjectLiteral: diagnostic log args only
|
|
1259
|
-
{
|
|
1260
|
-
pendingControlNodes
|
|
1261
|
-
});
|
|
1262
|
-
}
|
|
1263
|
-
}
|
|
1264
|
-
/**
|
|
1265
|
-
* Detect a quiescent graph for Loop nodes (docs/workflow-loops.md).
|
|
1266
|
-
*
|
|
1267
|
-
* A loop body can finish an iteration without feeding anything back (an
|
|
1268
|
-
* `If` routes the value elsewhere, a filter drops it). EOS cannot announce
|
|
1269
|
-
* that, because the body's EOS waits for the loop to close. So when every
|
|
1270
|
-
* live actor is parked on its inbox, no external stream is open, and some
|
|
1271
|
-
* inbox activity happened since the last notice, each Loop is told the
|
|
1272
|
-
* graph is quiescent and ends the runs still waiting for feedback. A parked
|
|
1273
|
-
* actor is not inside a provider call, a timer, or a write, so nothing can
|
|
1274
|
-
* still produce the value those runs wait for.
|
|
1275
|
-
*
|
|
1276
|
-
* Installed only for graphs that contain a Loop node.
|
|
1277
|
-
*/
|
|
1278
|
-
_installQuiescenceDetection() {
|
|
1279
|
-
const loopIds = this._graph.nodes
|
|
1280
|
-
.filter((n) => n.type === LOOP_NODE_TYPE)
|
|
1281
|
-
.map((n) => n.id);
|
|
1282
|
-
if (loopIds.length === 0)
|
|
1283
|
-
return;
|
|
1284
|
-
let checkScheduled = false;
|
|
1285
|
-
let activitySinceNotice = true;
|
|
1286
|
-
const check = () => {
|
|
1287
|
-
checkScheduled = false;
|
|
1288
|
-
if (this._cancelled || !activitySinceNotice)
|
|
1289
|
-
return;
|
|
1290
|
-
if (this._openExternalStreamEdges.size > 0)
|
|
1291
|
-
return;
|
|
1292
|
-
const liveLoops = loopIds.filter((id) => this._liveActorIds.has(id));
|
|
1293
|
-
if (liveLoops.length === 0)
|
|
1294
|
-
return;
|
|
1295
|
-
for (const id of this._liveActorIds) {
|
|
1296
|
-
if (!this._inboxes.get(id)?.isParked())
|
|
1297
|
-
return;
|
|
1298
|
-
}
|
|
1299
|
-
activitySinceNotice = false;
|
|
1300
|
-
for (const id of liveLoops) {
|
|
1301
|
-
this._inboxes.get(id).notifyQuiescent();
|
|
1302
|
-
}
|
|
1303
|
-
};
|
|
1304
|
-
const schedule = () => {
|
|
1305
|
-
if (checkScheduled)
|
|
1306
|
-
return;
|
|
1307
|
-
checkScheduled = true;
|
|
1308
|
-
// After pending I/O and microtasks: an actor that is about to resume
|
|
1309
|
-
// is no longer parked by the time the check runs.
|
|
1310
|
-
setTimeout(check, 0);
|
|
1311
|
-
};
|
|
1312
|
-
this._scheduleQuiescenceCheck = schedule;
|
|
1313
|
-
const observer = {
|
|
1314
|
-
onPark: schedule,
|
|
1315
|
-
onActivity: () => {
|
|
1316
|
-
activitySinceNotice = true;
|
|
1317
|
-
}
|
|
1318
|
-
};
|
|
1319
|
-
for (const inbox of this._inboxes.values()) {
|
|
1320
|
-
inbox.setObserver(observer);
|
|
1321
|
-
}
|
|
1322
|
-
}
|
|
1323
|
-
// -----------------------------------------------------------------------
|
|
1324
|
-
// Output routing (send_messages equivalent)
|
|
1325
|
-
// -----------------------------------------------------------------------
|
|
1326
|
-
/**
|
|
1327
|
-
* Route output values from a node to downstream inboxes.
|
|
1328
|
-
* For control edges: route control events to the __control__ handle.
|
|
1329
|
-
* For data edges: route to the named target handle.
|
|
1330
|
-
*/
|
|
1331
|
-
async _sendMessages(sourceNodeId, outputs, routingHints = {}) {
|
|
1332
|
-
if (this._cancelled)
|
|
1333
|
-
return;
|
|
1334
|
-
if (routingHints.controlError) {
|
|
1335
|
-
const pendingQueue = this._pendingControlResponses.get(sourceNodeId);
|
|
1336
|
-
const pending = pendingQueue?.shift();
|
|
1337
|
-
if (pendingQueue?.length === 0) {
|
|
1338
|
-
this._pendingControlResponses.delete(sourceNodeId);
|
|
1339
|
-
}
|
|
1340
|
-
pending?.reject(new MissingPackError(routingHints.controlError));
|
|
1341
|
-
}
|
|
1342
|
-
if (routingHints.skipInvocation) {
|
|
1343
|
-
this._skipInvocationOutputs(sourceNodeId, routingHints.invocationLineage ?? {});
|
|
1344
|
-
return;
|
|
1345
|
-
}
|
|
1346
|
-
if (this._supervisor) {
|
|
1347
|
-
this._recordNodeOutput(sourceNodeId, outputs, routingHints.invocationLineage);
|
|
1348
|
-
}
|
|
1349
|
-
// Handle __control_output__ from controller nodes (Python parity:
|
|
1350
|
-
// send_messages wraps __control_output__ in RunEvent and routes to
|
|
1351
|
-
// all controlled nodes via control edges).
|
|
1352
|
-
if ("__control_output__" in outputs) {
|
|
1353
|
-
await this._routeControlOutput(sourceNodeId, outputs["__control_output__"]);
|
|
1354
|
-
}
|
|
1355
|
-
const outgoing = this._graph.findOutgoingEdges(sourceNodeId);
|
|
1356
|
-
const outputKeys = Object.keys(outputs).filter((k) => outputs[k] !== undefined);
|
|
1357
|
-
log.debug("_sendMessages", {
|
|
1358
|
-
sourceNodeId,
|
|
1359
|
-
outputKeys,
|
|
1360
|
-
outgoingEdgeCount: outgoing.length,
|
|
1361
|
-
outgoingEdges: outgoing.map((e) => ({
|
|
1362
|
-
sourceHandle: e.sourceHandle,
|
|
1363
|
-
target: e.target,
|
|
1364
|
-
targetHandle: e.targetHandle,
|
|
1365
|
-
isControl: isControlEdge(e)
|
|
1366
|
-
}))
|
|
1367
|
-
});
|
|
1368
|
-
for (const edge of outgoing) {
|
|
1369
|
-
if (isControlEdge(edge)) {
|
|
1370
|
-
// Route control events from controller nodes to controlled nodes.
|
|
1371
|
-
// Try __control__ first, then fall back to __control_output__
|
|
1372
|
-
// (already handled above, skip duplicate routing).
|
|
1373
|
-
const value = outputs[edge.sourceHandle];
|
|
1374
|
-
if (value === undefined)
|
|
1375
|
-
continue;
|
|
1376
|
-
const targetInbox = this._inboxes.get(edge.target);
|
|
1377
|
-
if (!targetInbox)
|
|
1378
|
-
continue;
|
|
1379
|
-
// Ensure the value is a proper ControlEvent with event_type.
|
|
1380
|
-
// Controller nodes output raw property dicts
|
|
1381
|
-
// (e.g. {brightness: 5}) via __control_output__. These must be
|
|
1382
|
-
// wrapped in a RunEvent so the controlled actor's _runControlled()
|
|
1383
|
-
// recognises them. (Python parity: send_messages wraps
|
|
1384
|
-
// __control_output__ in RunEvent.)
|
|
1385
|
-
let controlEvent;
|
|
1386
|
-
if (isControlEventValue(value)) {
|
|
1387
|
-
controlEvent = value;
|
|
1388
|
-
}
|
|
1389
|
-
else if (isObjectValue(value)) {
|
|
1390
|
-
// Raw property dict — wrap as RunEvent
|
|
1391
|
-
const raw = value;
|
|
1392
|
-
// Support nested {properties: {...}} shape from LLM output
|
|
1393
|
-
const properties = "properties" in raw && isObjectValue(raw.properties)
|
|
1394
|
-
? raw.properties
|
|
1395
|
-
: raw;
|
|
1396
|
-
controlEvent = { event_type: "run", properties };
|
|
1397
|
-
}
|
|
1398
|
-
else {
|
|
1399
|
-
continue; // skip non-object values
|
|
1400
|
-
}
|
|
1401
|
-
const ctrlEdgeId = edge.id ??
|
|
1402
|
-
syntheticEdgeId(edge.source, edge.sourceHandle, edge.target, edge.targetHandle);
|
|
1403
|
-
await targetInbox.put("__control__", controlEvent, {
|
|
1404
|
-
source_edge_id: ctrlEdgeId
|
|
1405
|
-
});
|
|
1406
|
-
continue;
|
|
1407
|
-
}
|
|
1408
|
-
// Drop signal: send `lineage_done` to the downstream inbox instead of
|
|
1409
|
-
// delivering a value. §5. The actor sets `lineageDoneSlots` when a
|
|
1410
|
-
// stream node calls `outputs.drop()`.
|
|
1411
|
-
if (routingHints.lineageDoneSlots?.has(edge.sourceHandle)) {
|
|
1412
|
-
const targetInboxDrop = this._inboxes.get(edge.target);
|
|
1413
|
-
if (!targetInboxDrop)
|
|
1414
|
-
continue;
|
|
1415
|
-
const lineage = routingHints.perSlotLineage?.[edge.sourceHandle] ?? {};
|
|
1416
|
-
const edgeId = edge.id ??
|
|
1417
|
-
syntheticEdgeId(edge.source, edge.sourceHandle, edge.target, edge.targetHandle);
|
|
1418
|
-
// Use the downstream input handle's static scope so the projection
|
|
1419
|
-
// keys match the actor's bucket key on that handle.
|
|
1420
|
-
const downstreamScope = this._correlation?.nodes
|
|
1421
|
-
.get(edge.target)
|
|
1422
|
-
?.inputs.get(edge.targetHandle)?.scope ?? [];
|
|
1423
|
-
targetInboxDrop.signalLineageDone(edge.targetHandle, {
|
|
1424
|
-
type: "lineage_done",
|
|
1425
|
-
source_edge_id: edgeId,
|
|
1426
|
-
output: edge.sourceHandle,
|
|
1427
|
-
lineage
|
|
1428
|
-
}, downstreamScope);
|
|
1429
|
-
continue;
|
|
1430
|
-
}
|
|
1431
|
-
const value = outputs[edge.sourceHandle];
|
|
1432
|
-
if (value === undefined) {
|
|
1433
|
-
// Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
|
|
1434
|
-
log.debug("_sendMessages skip edge (no matching output)", {
|
|
1435
|
-
sourceNodeId,
|
|
1436
|
-
sourceHandle: edge.sourceHandle,
|
|
1437
|
-
availableKeys: outputKeys
|
|
1438
|
-
});
|
|
1439
|
-
continue;
|
|
1440
|
-
}
|
|
1441
|
-
const targetInbox = this._inboxes.get(edge.target);
|
|
1442
|
-
if (!targetInbox) {
|
|
1443
|
-
// Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
|
|
1444
|
-
log.debug("_sendMessages skip edge (no target inbox)", {
|
|
1445
|
-
target: edge.target
|
|
1446
|
-
});
|
|
1447
|
-
continue;
|
|
1448
|
-
}
|
|
1449
|
-
// Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
|
|
1450
|
-
log.debug("_sendMessages delivering", {
|
|
1451
|
-
sourceNodeId,
|
|
1452
|
-
sourceHandle: edge.sourceHandle,
|
|
1453
|
-
target: edge.target,
|
|
1454
|
-
targetHandle: edge.targetHandle
|
|
1455
|
-
});
|
|
1456
|
-
const edgeId = edge.id ??
|
|
1457
|
-
syntheticEdgeId(edge.source, edge.sourceHandle, edge.target, edge.targetHandle);
|
|
1458
|
-
const lineage = routingHints.perSlotLineage?.[edge.sourceHandle] ??
|
|
1459
|
-
routingHints.invocationLineage;
|
|
1460
|
-
await targetInbox.put(edge.targetHandle, value, {
|
|
1461
|
-
source_edge_id: edgeId,
|
|
1462
|
-
correlation_lineage: lineage
|
|
1463
|
-
});
|
|
1464
|
-
this._incrementEdgeCounter(edge);
|
|
1465
|
-
}
|
|
1466
|
-
// Emit output_update for each produced output handle.
|
|
1467
|
-
// Skip constant and input nodes: the client already holds their value
|
|
1468
|
-
// as a property (or supplied it as a runtime param), so re-sending it
|
|
1469
|
-
// (often a large image/audio payload) is redundant.
|
|
1470
|
-
// Also skip handles with outgoing data edges: the value travels to its
|
|
1471
|
-
// consumer on the edge, and clients only display terminal (unconnected)
|
|
1472
|
-
// handles — Output/Preview nodes and dangling outputs. Without this,
|
|
1473
|
-
// every intermediate module of a streaming patch firehoses the client
|
|
1474
|
-
// (~50 output_updates/s per handle for realtime audio). Nodes whose
|
|
1475
|
-
// output_updates are part of their UI contract even when patched onward
|
|
1476
|
-
// (e.g. the realtime AudioOutput monitor) opt out via the
|
|
1477
|
-
// `always_emit_output_updates` descriptor flag.
|
|
1478
|
-
const sourceNode = this._graph.findNode(sourceNodeId);
|
|
1479
|
-
if (sourceNode &&
|
|
1480
|
-
!sourceNode.type.startsWith("nodetool.constant.") &&
|
|
1481
|
-
!sourceNode.type.startsWith("nodetool.input.")) {
|
|
1482
|
-
const alwaysEmit = Boolean(sourceNode
|
|
1483
|
-
.always_emit_output_updates);
|
|
1484
|
-
const declaredOutputs = sourceNode.outputs ?? {};
|
|
1485
|
-
for (const [handle, value] of Object.entries(outputs)) {
|
|
1486
|
-
if (value === undefined)
|
|
1487
|
-
continue;
|
|
1488
|
-
if (handle === "__control__" || handle === "__control_output__")
|
|
1489
|
-
continue;
|
|
1490
|
-
if (!alwaysEmit &&
|
|
1491
|
-
this._graph.findEdges(sourceNodeId, handle).some(isDataEdge))
|
|
1492
|
-
continue;
|
|
1493
|
-
const outputName = clientFacingOutputName(sourceNode, handle);
|
|
1494
|
-
this._emit({
|
|
1495
|
-
type: "output_update",
|
|
1496
|
-
node_id: sourceNodeId,
|
|
1497
|
-
node_name: sourceNode.name ?? sourceNodeId,
|
|
1498
|
-
output_name: outputName,
|
|
1499
|
-
value,
|
|
1500
|
-
output_type: declaredOutputs[handle] ?? "any",
|
|
1501
|
-
metadata: {},
|
|
1502
|
-
// RFC §6: live display feed defaults to "append" (chunk-concatenate),
|
|
1503
|
-
// matching today's hardcoded consumer behavior. Artifacts travel on
|
|
1504
|
-
// generation_complete, so this is display-only.
|
|
1505
|
-
disposition: "append"
|
|
1506
|
-
});
|
|
1507
|
-
}
|
|
1508
|
-
}
|
|
1509
|
-
// Resolve the oldest pending sendControlEvent promise for this node.
|
|
1510
|
-
const pendingQueue = this._pendingControlResponses.get(sourceNodeId);
|
|
1511
|
-
if (pendingQueue && pendingQueue.length > 0) {
|
|
1512
|
-
const pending = pendingQueue.shift();
|
|
1513
|
-
if (pendingQueue.length === 0) {
|
|
1514
|
-
this._pendingControlResponses.delete(sourceNodeId);
|
|
1515
|
-
}
|
|
1516
|
-
pending.resolve(outputs);
|
|
1517
|
-
}
|
|
1518
|
-
}
|
|
1519
|
-
/**
|
|
1520
|
-
* A supervisor `skip`: retire one invocation's outputs without emitting.
|
|
1521
|
-
*
|
|
1522
|
-
* Plain non-emission is not enough. Siblings already buffered against the
|
|
1523
|
-
* skipped key would sit at a downstream join forever, and an invocation of an
|
|
1524
|
-
* iteration node would have opened child scopes an aggregate is waiting to
|
|
1525
|
-
* see closed. So both signals go out on every outgoing data edge: the
|
|
1526
|
-
* per-lineage `lineage_done` that unblocks joins, and a `lineage_scope_closed`
|
|
1527
|
-
* per child root the invocation could have minted. Design §5.2.
|
|
1528
|
-
*/
|
|
1529
|
-
_skipInvocationOutputs(sourceNodeId, lineage) {
|
|
1530
|
-
const nodeAnalysis = this._correlation?.nodes.get(sourceNodeId);
|
|
1531
|
-
for (const edge of this._graph.findOutgoingEdges(sourceNodeId)) {
|
|
1532
|
-
if (isControlEdge(edge))
|
|
1533
|
-
continue;
|
|
1534
|
-
const targetInbox = this._inboxes.get(edge.target);
|
|
1535
|
-
if (!targetInbox)
|
|
1536
|
-
continue;
|
|
1537
|
-
const edgeId = edge.id ??
|
|
1538
|
-
syntheticEdgeId(edge.source, edge.sourceHandle, edge.target, edge.targetHandle);
|
|
1539
|
-
for (const root of nodeAnalysis?.outputs.get(edge.sourceHandle)
|
|
1540
|
-
?.possibleChildRoots ?? []) {
|
|
1541
|
-
targetInbox.signalLineageScopeClosed(edge.targetHandle, {
|
|
1542
|
-
type: "lineage_scope_closed",
|
|
1543
|
-
source_edge_id: edgeId,
|
|
1544
|
-
output: edge.sourceHandle,
|
|
1545
|
-
parent_lineage: lineage,
|
|
1546
|
-
closed_root: root
|
|
1547
|
-
},
|
|
1548
|
-
// The parent scope of a minted child root is the invocation scope
|
|
1549
|
-
// the source node fired at — the scope this lineage projects onto.
|
|
1550
|
-
nodeAnalysis?.invocationScope ?? []);
|
|
1551
|
-
}
|
|
1552
|
-
targetInbox.signalLineageDone(edge.targetHandle, {
|
|
1553
|
-
type: "lineage_done",
|
|
1554
|
-
source_edge_id: edgeId,
|
|
1555
|
-
output: edge.sourceHandle,
|
|
1556
|
-
lineage
|
|
1557
|
-
}, this._correlation?.nodes.get(edge.target)?.inputs.get(edge.targetHandle)
|
|
1558
|
-
?.scope ?? []);
|
|
1559
|
-
}
|
|
1560
|
-
}
|
|
1561
|
-
/**
|
|
1562
|
-
* Mark the source of one data edge done on its target inbox at most once.
|
|
1563
|
-
* `markSourceDone` decrements an upstream counter, so calling it twice for
|
|
1564
|
-
* the same edge would over-decrement and could prematurely close a handle
|
|
1565
|
-
* that still has other open upstreams. Both early per-slot EOS
|
|
1566
|
-
* (`_signalSlotEos`) and the final `_sendEOS` route through this guard.
|
|
1567
|
-
* Returns true if the mark was applied (first time), false if skipped.
|
|
1568
|
-
*/
|
|
1569
|
-
_markEdgeSourceDoneOnce(edge) {
|
|
1570
|
-
const edgeId = edge.id ??
|
|
1571
|
-
syntheticEdgeId(edge.source, edge.sourceHandle, edge.target, edge.targetHandle);
|
|
1572
|
-
if (this._eosSentEdges.has(edgeId))
|
|
1573
|
-
return false;
|
|
1574
|
-
this._eosSentEdges.add(edgeId);
|
|
1575
|
-
const targetInbox = this._inboxes.get(edge.target);
|
|
1576
|
-
if (targetInbox) {
|
|
1577
|
-
targetInbox.markSourceDone(edge.targetHandle);
|
|
1578
|
-
}
|
|
1579
|
-
return true;
|
|
1580
|
-
}
|
|
1581
|
-
/**
|
|
1582
|
-
* Signal early end-of-stream for a single output slot of a node, in
|
|
1583
|
-
* response to `outputs.complete(slot)`. Marks every outgoing edge of
|
|
1584
|
-
* `(nodeId, slot)` done on its target inbox immediately, rather than
|
|
1585
|
-
* waiting for the actor to finish. Idempotent with `_sendEOS` via the
|
|
1586
|
-
* `_eosSentEdges` guard so a handle's upstream count is never
|
|
1587
|
-
* double-decremented.
|
|
1588
|
-
*/
|
|
1589
|
-
_signalSlotEos(nodeId, slot) {
|
|
1590
|
-
for (const edge of this._graph.findEdges(nodeId, slot)) {
|
|
1591
|
-
if (isControlEdge(edge))
|
|
1592
|
-
continue;
|
|
1593
|
-
this._markEdgeSourceDoneOnce(edge);
|
|
1594
|
-
}
|
|
1595
|
-
}
|
|
1596
|
-
/**
|
|
1597
|
-
* Signal EOS on all outgoing edges of a completed node.
|
|
1598
|
-
* For control edges: close the __control__ handle of the target.
|
|
1599
|
-
* For data edges: close the named target handle.
|
|
1600
|
-
*/
|
|
1601
|
-
async _sendEOS(nodeId) {
|
|
1602
|
-
const outgoing = this._graph.findOutgoingEdges(nodeId);
|
|
1603
|
-
// _initializeInboxes counts one __control__ upstream per unique
|
|
1604
|
-
// controller, so decrement once per target — not once per control edge.
|
|
1605
|
-
// Parallel control edges to the same target would otherwise drive the
|
|
1606
|
-
// count to zero while other controllers are still running.
|
|
1607
|
-
const controlTargetsDone = new Set();
|
|
1608
|
-
for (const edge of outgoing) {
|
|
1609
|
-
if (isControlEdge(edge)) {
|
|
1610
|
-
// Always mark __control__ source done when the controller finishes,
|
|
1611
|
-
// matching Python parity (_mark_downstream_eos). This unblocks
|
|
1612
|
-
// controlled nodes waiting on iterInput("__control__") regardless
|
|
1613
|
-
// of whether events were routed through the edge or via the manual
|
|
1614
|
-
// sendControlEvent() / dispatchControlEvent() APIs.
|
|
1615
|
-
if (controlTargetsDone.has(edge.target))
|
|
1616
|
-
continue;
|
|
1617
|
-
controlTargetsDone.add(edge.target);
|
|
1618
|
-
const targetInbox = this._inboxes.get(edge.target);
|
|
1619
|
-
if (targetInbox) {
|
|
1620
|
-
targetInbox.markSourceDone("__control__");
|
|
1621
|
-
}
|
|
1622
|
-
continue;
|
|
1623
|
-
}
|
|
1624
|
-
// Mark the source done at most once per edge — early per-slot EOS
|
|
1625
|
-
// (`outputs.complete`) may already have marked it. The rest of the
|
|
1626
|
-
// EOS work (lineage_scope_closed, edge_update) is unconditional.
|
|
1627
|
-
this._markEdgeSourceDoneOnce(edge);
|
|
1628
|
-
const targetInbox = this._inboxes.get(edge.target);
|
|
1629
|
-
const edgeId = edge.id ??
|
|
1630
|
-
syntheticEdgeId(edge.source, edge.sourceHandle, edge.target, edge.targetHandle);
|
|
1631
|
-
// §6 — at source EOS, synthesize `lineage_scope_closed` for every
|
|
1632
|
-
// possible child root the edge could have produced. Downstream
|
|
1633
|
-
// aggregators rely on receiving a close even when zero child tokens
|
|
1634
|
-
// were minted.
|
|
1635
|
-
if (this._correlation && targetInbox) {
|
|
1636
|
-
const nodeAnalysis = this._correlation.nodes.get(nodeId);
|
|
1637
|
-
const outputAnalysis = nodeAnalysis?.outputs.get(edge.sourceHandle);
|
|
1638
|
-
if (outputAnalysis) {
|
|
1639
|
-
for (const root of outputAnalysis.possibleChildRoots) {
|
|
1640
|
-
targetInbox.signalLineageScopeClosed(edge.targetHandle, {
|
|
1641
|
-
type: "lineage_scope_closed",
|
|
1642
|
-
source_edge_id: edgeId,
|
|
1643
|
-
output: edge.sourceHandle,
|
|
1644
|
-
parent_lineage: {},
|
|
1645
|
-
closed_root: root
|
|
1646
|
-
}, []);
|
|
1647
|
-
}
|
|
1648
|
-
}
|
|
1649
|
-
}
|
|
1650
|
-
// This terminal update carries the exact final counter, so clear any
|
|
1651
|
-
// dirty mark: otherwise _flushEdgeCounters at run end would re-emit
|
|
1652
|
-
// status "active" after "completed" for an edge whose counter advanced
|
|
1653
|
-
// within the throttle window just before its source finished. §1.
|
|
1654
|
-
this._edgeCounterDirty.delete(edgeId);
|
|
1655
|
-
this._emit({
|
|
1656
|
-
type: "edge_update",
|
|
1657
|
-
job_id: this._effectiveJobId,
|
|
1658
|
-
edge_id: edgeId,
|
|
1659
|
-
status: "completed",
|
|
1660
|
-
counter: this._edgeCounters.get(edgeId) ?? null
|
|
1661
|
-
});
|
|
1662
|
-
}
|
|
1663
|
-
}
|
|
1664
|
-
/**
|
|
1665
|
-
* Route __control_output__ from controller nodes to all controlled
|
|
1666
|
-
* nodes via control edges. Wraps raw property dicts in a RunEvent.
|
|
1667
|
-
* (Python parity: send_messages special handling of __control_output__.)
|
|
1668
|
-
*/
|
|
1669
|
-
async _routeControlOutput(sourceNodeId, controlOutput) {
|
|
1670
|
-
if (!isObjectValue(controlOutput))
|
|
1671
|
-
return;
|
|
1672
|
-
const controlEdges = this._graph
|
|
1673
|
-
.findOutgoingEdges(sourceNodeId)
|
|
1674
|
-
.filter(isControlEdge);
|
|
1675
|
-
if (controlEdges.length === 0)
|
|
1676
|
-
return;
|
|
1677
|
-
let properties = controlOutput;
|
|
1678
|
-
// Extract properties if nested inside a metadata wrapper
|
|
1679
|
-
if ("properties" in properties &&
|
|
1680
|
-
isObjectValue(properties.properties) &&
|
|
1681
|
-
!Array.isArray(properties.properties)) {
|
|
1682
|
-
properties = properties.properties;
|
|
1683
|
-
}
|
|
1684
|
-
const event = { event_type: "run", properties };
|
|
1685
|
-
for (const edge of controlEdges) {
|
|
1686
|
-
const targetInbox = this._inboxes.get(edge.target);
|
|
1687
|
-
if (!targetInbox)
|
|
1688
|
-
continue;
|
|
1689
|
-
const ctrlEdgeId = edge.id ??
|
|
1690
|
-
syntheticEdgeId(edge.source, edge.sourceHandle, edge.target, edge.targetHandle);
|
|
1691
|
-
await targetInbox.put("__control__", event, {
|
|
1692
|
-
source_edge_id: ctrlEdgeId
|
|
1693
|
-
});
|
|
1694
|
-
}
|
|
1695
|
-
}
|
|
1696
|
-
// -----------------------------------------------------------------------
|
|
1697
|
-
// Control event dispatch
|
|
1698
|
-
// -----------------------------------------------------------------------
|
|
1699
|
-
/**
|
|
1700
|
-
* Broadcast a control event to all controlled nodes.
|
|
1701
|
-
*/
|
|
1702
|
-
async dispatchControlEvent(event) {
|
|
1703
|
-
for (const node of this._graph.getControlledNodes()) {
|
|
1704
|
-
const inbox = this._inboxes.get(node.id);
|
|
1705
|
-
if (inbox) {
|
|
1706
|
-
await inbox.put("__control__", event);
|
|
1707
|
-
}
|
|
1708
|
-
}
|
|
1709
|
-
}
|
|
1710
|
-
/**
|
|
1711
|
-
* Send a control event to a specific target node.
|
|
1712
|
-
*/
|
|
1713
|
-
async dispatchControlEventToTarget(event, targetNodeId) {
|
|
1714
|
-
const inbox = this._inboxes.get(targetNodeId);
|
|
1715
|
-
if (inbox) {
|
|
1716
|
-
await inbox.put("__control__", event);
|
|
1717
|
-
}
|
|
1718
|
-
}
|
|
1719
|
-
/**
|
|
1720
|
-
* Send a run control event to a specific node and await its output.
|
|
1721
|
-
* Returns a promise that resolves with the node's output from the next
|
|
1722
|
-
* output_update message emitted for that node.
|
|
1723
|
-
*/
|
|
1724
|
-
async sendControlEvent(targetNodeId, properties) {
|
|
1725
|
-
const inbox = this._inboxes.get(targetNodeId);
|
|
1726
|
-
if (!inbox) {
|
|
1727
|
-
throw new Error(`Target node not found or no inbox: ${targetNodeId}`);
|
|
1728
|
-
}
|
|
1729
|
-
// The target's actor has already finished — nothing will ever read its
|
|
1730
|
-
// inbox again, so a registered response would hang forever. Reject now.
|
|
1731
|
-
if (this._completedNodes.has(targetNodeId)) {
|
|
1732
|
-
throw new Error(`Target node already completed and cannot handle control events: ${targetNodeId}`);
|
|
1733
|
-
}
|
|
1734
|
-
const entry = { resolve: () => { }, reject: () => { } };
|
|
1735
|
-
const promise = new Promise((resolve, reject) => {
|
|
1736
|
-
entry.resolve = resolve;
|
|
1737
|
-
entry.reject = reject;
|
|
1738
|
-
let queue = this._pendingControlResponses.get(targetNodeId);
|
|
1739
|
-
if (!queue) {
|
|
1740
|
-
queue = [];
|
|
1741
|
-
this._pendingControlResponses.set(targetNodeId, queue);
|
|
1742
|
-
}
|
|
1743
|
-
queue.push(entry);
|
|
1744
|
-
});
|
|
1745
|
-
const event = {
|
|
1746
|
-
event_type: "run",
|
|
1747
|
-
properties
|
|
1748
|
-
};
|
|
1749
|
-
await inbox.put("__control__", event);
|
|
1750
|
-
// The target's actor can finish between the check above and this point —
|
|
1751
|
-
// its completion handler drains `_pendingControlResponses` before this
|
|
1752
|
-
// waiter joined the queue, so nothing would ever settle it. Re-check after
|
|
1753
|
-
// registering and reject rather than hang.
|
|
1754
|
-
if (this._completedNodes.has(targetNodeId)) {
|
|
1755
|
-
const queue = this._pendingControlResponses.get(targetNodeId);
|
|
1756
|
-
const index = queue?.indexOf(entry) ?? -1;
|
|
1757
|
-
if (queue && index >= 0) {
|
|
1758
|
-
queue.splice(index, 1);
|
|
1759
|
-
if (queue.length === 0) {
|
|
1760
|
-
this._pendingControlResponses.delete(targetNodeId);
|
|
1761
|
-
}
|
|
1762
|
-
entry.reject(new Error(`Target node already completed and cannot handle control events: ${targetNodeId}`));
|
|
1763
|
-
}
|
|
1764
|
-
}
|
|
1765
|
-
return promise;
|
|
1766
|
-
}
|
|
1767
|
-
// -----------------------------------------------------------------------
|
|
1768
|
-
// Edge counters
|
|
1769
|
-
// -----------------------------------------------------------------------
|
|
1770
|
-
_incrementEdgeCounter(edge) {
|
|
1771
|
-
const id = edge.id ??
|
|
1772
|
-
syntheticEdgeId(edge.source, edge.sourceHandle, edge.target, edge.targetHandle);
|
|
1773
|
-
const counter = (this._edgeCounters.get(id) ?? 0) + 1;
|
|
1774
|
-
this._edgeCounters.set(id, counter);
|
|
1775
|
-
// Per-message edge_updates only drive UI affordances: the flow animation
|
|
1776
|
-
// needs the first message, and the "N streamed" badge doesn't need more
|
|
1777
|
-
// than a few updates per second. Realtime audio streams cross edges at
|
|
1778
|
-
// chunk rate (~50/s per edge), which would otherwise flood the transport.
|
|
1779
|
-
// Emit the first update immediately, throttle the rest, and flush exact
|
|
1780
|
-
// final counters in _flushEdgeCounters() at run end.
|
|
1781
|
-
const now = Date.now();
|
|
1782
|
-
const last = this._edgeCounterLastEmitMs.get(id);
|
|
1783
|
-
if (last !== undefined && now - last < EDGE_UPDATE_MIN_INTERVAL_MS) {
|
|
1784
|
-
this._edgeCounterDirty.add(id);
|
|
1785
|
-
return;
|
|
1786
|
-
}
|
|
1787
|
-
this._edgeCounterLastEmitMs.set(id, now);
|
|
1788
|
-
this._edgeCounterDirty.delete(id);
|
|
1789
|
-
this._emit({
|
|
1790
|
-
type: "edge_update",
|
|
1791
|
-
job_id: this._effectiveJobId,
|
|
1792
|
-
edge_id: id,
|
|
1793
|
-
status: "active",
|
|
1794
|
-
counter
|
|
1795
|
-
});
|
|
1796
|
-
}
|
|
1797
|
-
/**
|
|
1798
|
-
* Emit the final counter for every edge whose count advanced past its last
|
|
1799
|
-
* throttled edge_update, so the badge ends on the exact total. Called from
|
|
1800
|
-
* _drainActiveEdges (which runs on completion, cancellation and error).
|
|
1801
|
-
*/
|
|
1802
|
-
_flushEdgeCounters() {
|
|
1803
|
-
for (const id of this._edgeCounterDirty) {
|
|
1804
|
-
this._emit({
|
|
1805
|
-
type: "edge_update",
|
|
1806
|
-
job_id: this._effectiveJobId,
|
|
1807
|
-
edge_id: id,
|
|
1808
|
-
status: "active",
|
|
1809
|
-
counter: this._edgeCounters.get(id) ?? null
|
|
1810
|
-
});
|
|
1811
|
-
}
|
|
1812
|
-
this._edgeCounterDirty.clear();
|
|
1813
|
-
}
|
|
1814
|
-
// -----------------------------------------------------------------------
|
|
1815
|
-
// Drain active edges (Python parity: drain_active_edges)
|
|
1816
|
-
// -----------------------------------------------------------------------
|
|
1817
|
-
/**
|
|
1818
|
-
* Post a "drained" EdgeUpdate for any edge whose target handle still has
|
|
1819
|
-
* buffered items or open upstream sources. Called during post-completion
|
|
1820
|
-
* cleanup to ensure front-end consumers stop listening to streams and
|
|
1821
|
-
* clear any spinners.
|
|
1822
|
-
*
|
|
1823
|
-
* Returns the ids of edges found in that leftover state — §6's "zero
|
|
1824
|
-
* pending work" is violated whenever this is non-empty after a normal
|
|
1825
|
-
* (non-error) completion. The caller decides what strict mode does with
|
|
1826
|
-
* that list; this method's own emit-and-continue behavior never changes,
|
|
1827
|
-
* since it also runs on the error/cancellation cleanup path where a
|
|
1828
|
-
* partial graph is expected to have open edges.
|
|
1829
|
-
*/
|
|
1830
|
-
_drainActiveEdges() {
|
|
1831
|
-
const leftoverEdgeIds = [];
|
|
1832
|
-
if (!this._graph || this._graph.edges.length === 0)
|
|
1833
|
-
return leftoverEdgeIds;
|
|
1834
|
-
// Settle the throttled counters first; a "drained" update below may then
|
|
1835
|
-
// override the status for still-open edges.
|
|
1836
|
-
this._flushEdgeCounters();
|
|
1837
|
-
for (const edge of this._graph.edges) {
|
|
1838
|
-
try {
|
|
1839
|
-
const inbox = this._inboxes.get(edge.target);
|
|
1840
|
-
if (!inbox)
|
|
1841
|
-
continue;
|
|
1842
|
-
const edgeId = edge.id ??
|
|
1843
|
-
syntheticEdgeId(edge.source, edge.sourceHandle, edge.target, edge.targetHandle);
|
|
1844
|
-
if (inbox.hasBuffered(edge.targetHandle) ||
|
|
1845
|
-
inbox.isOpen(edge.targetHandle)) {
|
|
1846
|
-
leftoverEdgeIds.push(edgeId);
|
|
1847
|
-
this._emit({
|
|
1848
|
-
type: "edge_update",
|
|
1849
|
-
job_id: this._effectiveJobId,
|
|
1850
|
-
edge_id: edgeId,
|
|
1851
|
-
status: "drained",
|
|
1852
|
-
counter: this._edgeCounters.get(edgeId) ?? null
|
|
1853
|
-
});
|
|
1854
|
-
}
|
|
1855
|
-
}
|
|
1856
|
-
catch {
|
|
1857
|
-
// Best effort — ignore errors during draining
|
|
1858
|
-
}
|
|
1859
|
-
}
|
|
1860
|
-
return leftoverEdgeIds;
|
|
1861
|
-
}
|
|
1862
|
-
/**
|
|
1863
|
-
* Strict-mode gate for `_drainActiveEdges`'s findings (§12). Split out from
|
|
1864
|
-
* its one call site (the success path in `_runImpl`, right after
|
|
1865
|
-
* `_processGraph`) so it is unit-testable without a full graph run: in
|
|
1866
|
-
* practice any leftover edge state this reports was already caught by the
|
|
1867
|
-
* node-level `_checkPendingInboxWork` gate inside `_processGraph` (an
|
|
1868
|
-
* inbox's `hasPendingWork()` covers every handle, edge-targeted ones
|
|
1869
|
-
* included) and would have thrown before this method is ever reached —
|
|
1870
|
-
* this gate exists for the state `_checkPendingInboxWork` cannot see (e.g.
|
|
1871
|
-
* a driver that calls `_drainActiveEdges` directly after bypassing
|
|
1872
|
-
* `_processGraph`) and as a second line of defense should that ordering
|
|
1873
|
-
* ever change.
|
|
1874
|
-
*
|
|
1875
|
-
* A cancelled run, or one with node errors, legitimately
|
|
1876
|
-
* leaves edges mid-flight — that is what the drain reports to the
|
|
1877
|
-
* frontend in every mode. Only a run that is otherwise clean but still has
|
|
1878
|
-
* leftover edge state is a §6 violation ("zero pending work" after a
|
|
1879
|
-
* normal completion).
|
|
1880
|
-
*/
|
|
1881
|
-
_enforceCleanEdgeDrain(leftoverEdgeIds) {
|
|
1882
|
-
if (!this._options.strict ||
|
|
1883
|
-
leftoverEdgeIds.length === 0 ||
|
|
1884
|
-
this._cancelled ||
|
|
1885
|
-
this._nodeErrors.size > 0) {
|
|
1886
|
-
return;
|
|
1887
|
-
}
|
|
1888
|
-
throw new Error(`Strict mode: edge(s) still had buffered/open state after a clean ` +
|
|
1889
|
-
`run completion: ${leftoverEdgeIds.join(", ")}`);
|
|
1890
|
-
}
|
|
1891
|
-
// -----------------------------------------------------------------------
|
|
1892
|
-
// Pending work detection
|
|
1893
|
-
// -----------------------------------------------------------------------
|
|
1894
|
-
_checkPendingInboxWork() {
|
|
1895
|
-
const pending = [];
|
|
1896
|
-
for (const [nodeId, inbox] of this._inboxes) {
|
|
1897
|
-
if (inbox.hasPendingWork())
|
|
1898
|
-
pending.push(nodeId);
|
|
1899
|
-
}
|
|
1900
|
-
return pending;
|
|
1901
|
-
}
|
|
1902
|
-
// -----------------------------------------------------------------------
|
|
1903
|
-
// Helpers
|
|
1904
|
-
// -----------------------------------------------------------------------
|
|
1905
|
-
_isOutputNode(node) {
|
|
1906
|
-
// An output node has no outgoing data edges
|
|
1907
|
-
const outgoing = this._graph.findOutgoingEdges(node.id).filter(isDataEdge);
|
|
1908
|
-
return outgoing.length === 0;
|
|
1909
|
-
}
|
|
1910
|
-
/**
|
|
1911
|
-
* External input nodes are placeholders that receive runtime params/streamed values.
|
|
1912
|
-
* They should not execute as normal source actors.
|
|
1913
|
-
*/
|
|
1914
|
-
_isExternalInputNode(node) {
|
|
1915
|
-
return (node.type.startsWith("nodetool.input.") || node.type === "test.Input");
|
|
1916
|
-
}
|
|
1917
|
-
_getExternalInputName(node) {
|
|
1918
|
-
const properties = isObjectValue(node.properties) ? node.properties : {};
|
|
1919
|
-
const propertyName = isString(properties.name)
|
|
1920
|
-
? properties.name.trim()
|
|
1921
|
-
: "";
|
|
1922
|
-
if (propertyName) {
|
|
1923
|
-
return propertyName;
|
|
1924
|
-
}
|
|
1925
|
-
return node.name ?? node.id;
|
|
1926
|
-
}
|
|
1927
|
-
/**
|
|
1928
|
-
* Key a terminal node's outputs are collected under.
|
|
1929
|
-
*
|
|
1930
|
-
* DSL-authored graphs carry the public name in the Output node's `name`
|
|
1931
|
-
* *property* (`output({ name: "hook", value })`) — the descriptor's
|
|
1932
|
-
* top-level `name` is absent, and the auto-generated node id (`output`,
|
|
1933
|
-
* `output_2`, …) is all that would remain. Promote the property for
|
|
1934
|
-
* output-typed nodes so a run's outputs are keyed by the name the author
|
|
1935
|
-
* asked for. Mirrors `_getExternalInputName` on the input side and the
|
|
1936
|
-
* websocket runner's `require_terminal_result` rewrite; gating on
|
|
1937
|
-
* `nodetool.output.` keeps other terminal sinks keyed by id.
|
|
1938
|
-
*/
|
|
1939
|
-
_outputCollectionKey(node) {
|
|
1940
|
-
if (isString(node.name) && node.name.trim())
|
|
1941
|
-
return node.name;
|
|
1942
|
-
if (node.type.startsWith("nodetool.output.")) {
|
|
1943
|
-
const properties = isObjectValue(node.properties) ? node.properties : {};
|
|
1944
|
-
const propertyName = isString(properties.name)
|
|
1945
|
-
? properties.name.trim()
|
|
1946
|
-
: "";
|
|
1947
|
-
if (propertyName)
|
|
1948
|
-
return propertyName;
|
|
1949
|
-
}
|
|
1950
|
-
return node.id;
|
|
1951
|
-
}
|
|
1952
|
-
_emit(msg) {
|
|
1953
|
-
if (msg.type === "node_update" && msg.error_detail?.missing_runtime) {
|
|
1954
|
-
this._missingRuntime ??= msg.error_detail.missing_runtime;
|
|
1955
|
-
}
|
|
1956
|
-
// Retain for RunResult.messages — except the realtime-audio firehose: a
|
|
1957
|
-
// live synth patch emits ~50 audio-chunk output_updates per node per
|
|
1958
|
-
// second, each holding a sample buffer, so retaining them grows the heap
|
|
1959
|
-
// without bound (~25MB/min for a small patch) and the mounting GC
|
|
1960
|
-
// pressure progressively degrades whichever thread runs the kernel.
|
|
1961
|
-
// Streaming delivery (executionContext.emit) is unaffected. A generous
|
|
1962
|
-
// cap backstops other unbounded streams.
|
|
1963
|
-
if (!isAudioChunkOutputUpdate(msg)) {
|
|
1964
|
-
if (this._messages.length >= MAX_RETAINED_MESSAGES) {
|
|
1965
|
-
this._messages = this._messages.slice(this._messages.length - MAX_RETAINED_MESSAGES / 2);
|
|
1966
|
-
}
|
|
1967
|
-
this._messages.push(msg);
|
|
1968
|
-
}
|
|
1969
|
-
if (this._options.executionContext) {
|
|
1970
|
-
// Message delivery is observation, not execution. A transport that fails
|
|
1971
|
-
// mid-run (a closed WebSocket, a full queue) must not abort the workflow
|
|
1972
|
-
// — `_emit` is called from EOS routing and actor completion handlers,
|
|
1973
|
-
// where a throw would take down the run and orphan sibling actors.
|
|
1974
|
-
try {
|
|
1975
|
-
this._options.executionContext.emit(msg);
|
|
1976
|
-
}
|
|
1977
|
-
catch (err) {
|
|
1978
|
-
// Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
|
|
1979
|
-
log.warn("Message emit failed", {
|
|
1980
|
-
jobId: this.jobId,
|
|
1981
|
-
type: msg.type,
|
|
1982
|
-
error: err instanceof Error ? err.message : String(err)
|
|
1983
|
-
});
|
|
1984
|
-
}
|
|
1985
|
-
}
|
|
1986
|
-
// Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
|
|
1987
|
-
log.debug("Message emitted", { jobId: this.jobId, type: msg.type });
|
|
1988
|
-
}
|
|
1989
|
-
_resolveInputNodes(inputName) {
|
|
1990
|
-
return this._graph
|
|
1991
|
-
.inputNodes()
|
|
1992
|
-
.filter((node) => this._getExternalInputName(node) === inputName ||
|
|
1993
|
-
node.id === inputName);
|
|
1994
|
-
}
|
|
1995
|
-
// -----------------------------------------------------------------------
|
|
1996
|
-
// Control context builder (Python parity: _build_control_context)
|
|
1997
|
-
// -----------------------------------------------------------------------
|
|
1998
|
-
/**
|
|
1999
|
-
* Build control context for a controller node.
|
|
2000
|
-
* Returns null if the node has no outgoing control edges.
|
|
2001
|
-
*
|
|
2002
|
-
* The control context maps controlled node IDs to their metadata
|
|
2003
|
-
* (node_type, properties with current values, types, descriptions).
|
|
2004
|
-
* This is injected as `_control_context` input so agent nodes can
|
|
2005
|
-
* build ControlNodeTool instances for LLM tool-calling.
|
|
2006
|
-
*/
|
|
2007
|
-
_buildControlContext(nodeId) {
|
|
2008
|
-
const outgoingControlEdges = this._graph
|
|
2009
|
-
.findOutgoingEdges(nodeId)
|
|
2010
|
-
.filter(isControlEdge);
|
|
2011
|
-
if (outgoingControlEdges.length === 0)
|
|
2012
|
-
return null;
|
|
2013
|
-
const controlledNodeIds = new Set(outgoingControlEdges.map((e) => e.target));
|
|
2014
|
-
const context = {};
|
|
2015
|
-
for (const targetId of controlledNodeIds) {
|
|
2016
|
-
const targetNode = this._graph.findNode(targetId);
|
|
2017
|
-
if (!targetNode)
|
|
2018
|
-
continue;
|
|
2019
|
-
const properties = {};
|
|
2020
|
-
// Extract property info from the node descriptor
|
|
2021
|
-
if (isObjectValue(targetNode.properties)) {
|
|
2022
|
-
const props = targetNode.properties;
|
|
2023
|
-
const propTypes = targetNode.propertyTypes ?? {};
|
|
2024
|
-
for (const [propName, propValue] of Object.entries(props)) {
|
|
2025
|
-
if (propName.startsWith("_"))
|
|
2026
|
-
continue; // skip private
|
|
2027
|
-
const meta = targetNode.propertyMeta?.[propName];
|
|
2028
|
-
const described = {
|
|
2029
|
-
value: propValue,
|
|
2030
|
-
type: propTypes[propName] ??
|
|
2031
|
-
typeof propValue
|
|
2032
|
-
};
|
|
2033
|
-
if (meta?.description) {
|
|
2034
|
-
described.description = meta.description;
|
|
2035
|
-
}
|
|
2036
|
-
if (meta?.min != null) {
|
|
2037
|
-
described.min = meta.min;
|
|
2038
|
-
}
|
|
2039
|
-
if (meta?.max != null) {
|
|
2040
|
-
described.max = meta.max;
|
|
2041
|
-
}
|
|
2042
|
-
properties[propName] = described;
|
|
2043
|
-
}
|
|
2044
|
-
}
|
|
2045
|
-
context[targetId] = {
|
|
2046
|
-
node_id: targetId,
|
|
2047
|
-
node_type: targetNode.type,
|
|
2048
|
-
node_title: targetNode.name ?? targetId,
|
|
2049
|
-
properties,
|
|
2050
|
-
control_actions: {
|
|
2051
|
-
run: {
|
|
2052
|
-
properties: this._buildControlActionProperties(targetNode)
|
|
2053
|
-
}
|
|
2054
|
-
}
|
|
2055
|
-
};
|
|
2056
|
-
}
|
|
2057
|
-
return Object.keys(context).length > 0 ? context : null;
|
|
2058
|
-
}
|
|
2059
|
-
/**
|
|
2060
|
-
* Build the property schema for a controlled node's "run" action.
|
|
2061
|
-
* Maps property names to JSON-schema-like descriptors for ControlNodeTool.
|
|
2062
|
-
*/
|
|
2063
|
-
_buildControlActionProperties(node) {
|
|
2064
|
-
const result = {};
|
|
2065
|
-
const props = (node.properties ?? {});
|
|
2066
|
-
const slotTypes = dynamicSlotPropertyTypes(node.dynamic_inputs);
|
|
2067
|
-
// Declared dynamic slots type their handles; the registry map wins on a
|
|
2068
|
-
// name collision.
|
|
2069
|
-
const propTypes = {
|
|
2070
|
-
...slotTypes,
|
|
2071
|
-
...(node.propertyTypes ?? {})
|
|
2072
|
-
};
|
|
2073
|
-
// Build the schema from registry-declared property types so the LLM sees
|
|
2074
|
-
// every argument the node accepts, even when the node has no saved values.
|
|
2075
|
-
// Fall back to keys present in `properties` for dynamic nodes whose
|
|
2076
|
-
// registry metadata doesn't enumerate every property.
|
|
2077
|
-
const names = new Set([
|
|
2078
|
-
...Object.keys(propTypes),
|
|
2079
|
-
...Object.keys(props)
|
|
2080
|
-
]);
|
|
2081
|
-
for (const name of names) {
|
|
2082
|
-
if (name.startsWith("_"))
|
|
2083
|
-
continue;
|
|
2084
|
-
const declaredType = propTypes[name];
|
|
2085
|
-
const value = props[name];
|
|
2086
|
-
let jsonType = "string";
|
|
2087
|
-
if (declaredType) {
|
|
2088
|
-
const lower = declaredType.toLowerCase();
|
|
2089
|
-
if (lower === "int" || lower === "integer")
|
|
2090
|
-
jsonType = "integer";
|
|
2091
|
-
else if (lower === "float" || lower === "number")
|
|
2092
|
-
jsonType = "number";
|
|
2093
|
-
else if (lower === "bool" || lower === "boolean")
|
|
2094
|
-
jsonType = "boolean";
|
|
2095
|
-
else if (lower.startsWith("list") || lower === "array")
|
|
2096
|
-
jsonType = "array";
|
|
2097
|
-
else if (lower.startsWith("dict") || lower === "object")
|
|
2098
|
-
jsonType = "object";
|
|
2099
|
-
}
|
|
2100
|
-
else if (isNumber(value)) {
|
|
2101
|
-
jsonType = Number.isInteger(value) ? "integer" : "number";
|
|
2102
|
-
}
|
|
2103
|
-
else if (isBoolean(value)) {
|
|
2104
|
-
jsonType = "boolean";
|
|
2105
|
-
}
|
|
2106
|
-
const slot = node.dynamic_inputs?.[name];
|
|
2107
|
-
const meta = (node.propertyMeta?.[name] ?? slot);
|
|
2108
|
-
const schema = {
|
|
2109
|
-
type: jsonType,
|
|
2110
|
-
description: meta?.description ??
|
|
2111
|
-
`Property '${name}' (${declaredType ?? jsonType})`
|
|
2112
|
-
};
|
|
2113
|
-
if (value !== undefined) {
|
|
2114
|
-
schema.default = value;
|
|
2115
|
-
}
|
|
2116
|
-
if (meta?.min != null) {
|
|
2117
|
-
schema.minimum = meta.min;
|
|
2118
|
-
}
|
|
2119
|
-
if (meta?.max != null) {
|
|
2120
|
-
schema.maximum = meta.max;
|
|
2121
|
-
}
|
|
2122
|
-
result[name] = schema;
|
|
2123
|
-
}
|
|
2124
|
-
return result;
|
|
2125
|
-
}
|
|
2126
|
-
}
|
|
1
|
+
export * from "@nodetool-ai/execution-core/runner";
|
|
2127
2
|
//# sourceMappingURL=runner.js.map
|