@nodetool-ai/kernel 0.7.0-rc.23 → 0.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/README.md +51 -0
  2. package/dist/.nodetool-build-stamp +1 -0
  3. package/dist/actor.d.ts +387 -20
  4. package/dist/actor.d.ts.map +1 -1
  5. package/dist/actor.js +1658 -187
  6. package/dist/actor.js.map +1 -1
  7. package/dist/correlation-analysis.d.ts +104 -0
  8. package/dist/correlation-analysis.d.ts.map +1 -0
  9. package/dist/correlation-analysis.js +840 -0
  10. package/dist/correlation-analysis.js.map +1 -0
  11. package/dist/durable-inbox.d.ts +9 -0
  12. package/dist/durable-inbox.d.ts.map +1 -1
  13. package/dist/durable-inbox.js +55 -2
  14. package/dist/durable-inbox.js.map +1 -1
  15. package/dist/dynamic-slots.d.ts +73 -0
  16. package/dist/dynamic-slots.d.ts.map +1 -0
  17. package/dist/dynamic-slots.js +192 -0
  18. package/dist/dynamic-slots.js.map +1 -0
  19. package/dist/edge-ids.d.ts +11 -0
  20. package/dist/edge-ids.d.ts.map +1 -0
  21. package/dist/edge-ids.js +15 -0
  22. package/dist/edge-ids.js.map +1 -0
  23. package/dist/graph-utils.d.ts +12 -0
  24. package/dist/graph-utils.d.ts.map +1 -1
  25. package/dist/graph-utils.js +51 -16
  26. package/dist/graph-utils.js.map +1 -1
  27. package/dist/graph.d.ts +60 -9
  28. package/dist/graph.d.ts.map +1 -1
  29. package/dist/graph.js +313 -101
  30. package/dist/graph.js.map +1 -1
  31. package/dist/inbox.d.ts +158 -2
  32. package/dist/inbox.d.ts.map +1 -1
  33. package/dist/inbox.js +253 -11
  34. package/dist/inbox.js.map +1 -1
  35. package/dist/index.d.ts +14 -10
  36. package/dist/index.d.ts.map +1 -1
  37. package/dist/index.js +11 -7
  38. package/dist/index.js.map +1 -1
  39. package/dist/io.d.ts +103 -6
  40. package/dist/io.d.ts.map +1 -1
  41. package/dist/io.js +123 -12
  42. package/dist/io.js.map +1 -1
  43. package/dist/loop.d.ts +36 -0
  44. package/dist/loop.d.ts.map +1 -0
  45. package/dist/loop.js +166 -0
  46. package/dist/loop.js.map +1 -0
  47. package/dist/message-stream.d.ts +32 -0
  48. package/dist/message-stream.d.ts.map +1 -0
  49. package/dist/message-stream.js +64 -0
  50. package/dist/message-stream.js.map +1 -0
  51. package/dist/predicates.d.ts +8 -0
  52. package/dist/predicates.d.ts.map +1 -0
  53. package/dist/predicates.js +8 -0
  54. package/dist/predicates.js.map +1 -0
  55. package/dist/run-state.d.ts +65 -0
  56. package/dist/run-state.d.ts.map +1 -0
  57. package/dist/run-state.js +42 -0
  58. package/dist/run-state.js.map +1 -0
  59. package/dist/runner.d.ts +312 -15
  60. package/dist/runner.d.ts.map +1 -1
  61. package/dist/runner.js +1226 -157
  62. package/dist/runner.js.map +1 -1
  63. package/dist/substitute-validator.d.ts +44 -0
  64. package/dist/substitute-validator.d.ts.map +1 -0
  65. package/dist/substitute-validator.js +169 -0
  66. package/dist/substitute-validator.js.map +1 -0
  67. package/dist/supervisor.d.ts +148 -0
  68. package/dist/supervisor.d.ts.map +1 -0
  69. package/dist/supervisor.js +287 -0
  70. package/dist/supervisor.js.map +1 -0
  71. package/dist/trigger-wakeup.d.ts +74 -5
  72. package/dist/trigger-wakeup.d.ts.map +1 -1
  73. package/dist/trigger-wakeup.js +167 -45
  74. package/dist/trigger-wakeup.js.map +1 -1
  75. package/package.json +27 -9
  76. package/dist/channel.d.ts +0 -46
  77. package/dist/channel.d.ts.map +0 -1
  78. package/dist/channel.js +0 -191
  79. package/dist/channel.js.map +0 -1
  80. package/dist/suspendable.d.ts +0 -68
  81. package/dist/suspendable.d.ts.map +0 -1
  82. package/dist/suspendable.js +0 -108
  83. package/dist/suspendable.js.map +0 -1
  84. package/dist/trigger-manager.d.ts +0 -107
  85. package/dist/trigger-manager.d.ts.map +0 -1
  86. package/dist/trigger-manager.js +0 -214
  87. package/dist/trigger-manager.js.map +0 -1
  88. package/dist/trigger.d.ts +0 -57
  89. package/dist/trigger.d.ts.map +0 -1
  90. package/dist/trigger.js +0 -145
  91. package/dist/trigger.js.map +0 -1
package/dist/actor.js CHANGED
@@ -8,15 +8,147 @@
8
8
  * 2. Streaming input: node drains inbox via iterInput / iterAny.
9
9
  * 3. Streaming output: call genProcess() which yields items.
10
10
  * 4. Controlled: accept control events, cache inputs for replay.
11
+ * 5. Loop: `nodetool.control.Loop`, run by `runLoop` (loop.ts).
11
12
  *
12
13
  * Sync modes:
13
14
  * - on_any: fire when ANY input handle has data.
14
15
  * - zip_all: wait until ALL handles have data (with sticky semantics).
15
16
  */
16
17
  import { createLogger } from "@nodetool-ai/config";
18
+ import { isBoolean, isNumber, isObjectValue, isString } from "./predicates.js";
19
+ import { EMPTY_LINEAGE, LOOP_NODE_TYPE, TypeMetadata, missingRuntimePackageOf } from "@nodetool-ai/protocol";
20
+ // Stryker disable next-line StringLiteral: logger name is a diagnostic label, not a behavioural contract
17
21
  const log = createLogger("nodetool.kernel.actor");
18
- import { withNodeSpan } from "@nodetool-ai/runtime";
22
+ import { createInvocationAccount, inInvocationAccount, isContentFilterRefusal, isRecoverableNodeError, providerFailureDetail } from "@nodetool-ai/runtime";
23
+ import { computeAllowedActions, failureSignature, redactRecord, redactValue } from "./supervisor.js";
24
+ import { hasFullValidatorCoverage, validateSubstituteOutputs } from "./substitute-validator.js";
25
+ // Span helpers via the narrow `/tracing` subpath — keeps the runtime
26
+ // provider / python-bridge barrel out of thin (browser) bundles.
27
+ import { markSpanError, withNodeSpan } from "@nodetool-ai/runtime/tracing";
19
28
  import { NodeInputs, NodeOutputs } from "./io.js";
29
+ import { applyDynamicSlotTypes } from "./dynamic-slots.js";
30
+ import { runLoop } from "./loop.js";
31
+ import { iterationRootId, projectLineageKey, tryProjectLineageKey } from "./correlation-analysis.js";
32
+ /** Returned by the recovery loop when a `skip` verdict retired an invocation. */
33
+ const SKIPPED = Symbol("skipped");
34
+ /**
35
+ * A failure that happened while routing values downstream, not while the node
36
+ * was executing. It never escalates: `sendOutputs` delivers to each outgoing
37
+ * edge in turn, so once edge 1 has the value, re-running the node would deliver
38
+ * to it twice. Design §5.1.
39
+ */
40
+ class RoutingError extends Error {
41
+ cause;
42
+ constructor(cause) {
43
+ super(cause instanceof Error ? cause.message : String(cause));
44
+ this.cause = cause;
45
+ this.name = "RoutingError";
46
+ }
47
+ }
48
+ /**
49
+ * Canonical lineage keys join `root=index` pairs with `,`. To compute the
50
+ * parent key for a shorter scope, take the first `prefixLength` pairs.
51
+ */
52
+ export function trimKey(key, prefixLength) {
53
+ // The three guards below are pure fast-paths: each returns exactly what the
54
+ // final `parts.slice(0, prefixLength).join(",")` would compute, so mutating
55
+ // any of them is equivalent.
56
+ // - prefixLength === 0 → slice(0,0).join("") === ""
57
+ // - key === "" → split gives [""], 1 <= prefixLength → key === ""
58
+ // - parts.length <= prefixLength → slice keeps every part → join === key
59
+ // Stryker disable next-line ConditionalExpression: equivalent fast-path (see above)
60
+ if (prefixLength === 0)
61
+ return "";
62
+ // Stryker disable next-line ConditionalExpression,StringLiteral: equivalent fast-path (see above)
63
+ if (key === "")
64
+ return "";
65
+ const parts = key.split(",");
66
+ // Stryker disable next-line ConditionalExpression,EqualityOperator: equivalent fast-path (see above)
67
+ if (parts.length <= prefixLength)
68
+ return key;
69
+ return parts.slice(0, prefixLength).join(",");
70
+ }
71
+ /**
72
+ * Find every pending max-scope key in `maxBuckets` whose parent (trimmed to
73
+ * `parentLength`) equals `parentKey`. Used when a strict-prefix sticky
74
+ * arrival can unblock pending child firings.
75
+ */
76
+ export function enumerateCandidateKeysForParent(maxBuckets, _dataHandles, _handleClass, _handleScope, _maxLength, parentKey, parentLength) {
77
+ const out = [];
78
+ const seen = new Set();
79
+ for (const buckets of maxBuckets.values()) {
80
+ for (const key of buckets.keys()) {
81
+ if (seen.has(key))
82
+ continue;
83
+ if (trimKey(key, parentLength) === parentKey) {
84
+ seen.add(key);
85
+ out.push(key);
86
+ }
87
+ }
88
+ }
89
+ return out;
90
+ }
91
+ export function enumerateAllPendingKeys(maxBuckets) {
92
+ const seen = new Set();
93
+ const out = [];
94
+ for (const buckets of maxBuckets.values()) {
95
+ for (const key of buckets.keys()) {
96
+ if (seen.has(key))
97
+ continue;
98
+ seen.add(key);
99
+ out.push(key);
100
+ }
101
+ }
102
+ return out;
103
+ }
104
+ /**
105
+ * A resolved model property (`{type: "image_model", id, name, provider}`),
106
+ * reduced to the fields that identify it. Which model ran is the one
107
+ * generation setting that is never a scalar, and without it a saved asset
108
+ * cannot say what produced it.
109
+ */
110
+ function modelReference(value) {
111
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
112
+ return null;
113
+ }
114
+ const ref = value;
115
+ if (!isString(ref.type) || !ref.type.endsWith("_model"))
116
+ return null;
117
+ if (!isString(ref.id) || ref.id.length === 0)
118
+ return null;
119
+ const out = { type: ref.type, id: ref.id };
120
+ if (isString(ref.name))
121
+ out.name = ref.name;
122
+ if (isString(ref.provider))
123
+ out.provider = ref.provider;
124
+ return out;
125
+ }
126
+ /**
127
+ * Pick the persistable input properties from a resolved input dict: scalars
128
+ * (string/number/boolean) plus model references, reduced by
129
+ * {@link modelReference}. Drops every other nested object, array and binary
130
+ * ref so the `generation_complete` event stays small and carries only
131
+ * generation params (prompt, seed, model, …). Reserved keys
132
+ * (`_control_context` and other `_`-prefixed internals) are stripped. Returns
133
+ * `null` when nothing remains.
134
+ */
135
+ function scalarInputProperties(inputs) {
136
+ const out = {};
137
+ for (const [key, value] of Object.entries(inputs)) {
138
+ if (key.startsWith("_"))
139
+ continue;
140
+ if (isString(value) ||
141
+ isNumber(value) ||
142
+ isBoolean(value)) {
143
+ out[key] = value;
144
+ continue;
145
+ }
146
+ const model = modelReference(value);
147
+ if (model)
148
+ out[key] = model;
149
+ }
150
+ return Object.keys(out).length > 0 ? out : null;
151
+ }
20
152
  // ---------------------------------------------------------------------------
21
153
  // NodeActor
22
154
  // ---------------------------------------------------------------------------
@@ -32,16 +164,65 @@ export class NodeActor {
32
164
  _latestResult = null;
33
165
  /** Collected non-null outputs for streaming-output nodes. */
34
166
  _streamingCollectedOutputs = null;
35
- /** Handles that are sticky from the start (non-streaming edges). */
36
- _initialStickyHandles;
167
+ /** Handles where multiple upstream values should be collected into a list. */
168
+ _listInputHandles;
37
169
  /** Callback to route outputs downstream. */
38
170
  _sendOutputs;
171
+ /**
172
+ * Lineage of the current invocation. Set when the actor consumes input(s)
173
+ * under the correlation flag and the inheritance case is unambiguous
174
+ * (single-edge single-input handle).
175
+ */
176
+ _currentInvocationLineage;
177
+ /**
178
+ * A node fed by a streaming handle is invoked once per chunk, so logging
179
+ * every invocation at INFO buries the run: one Preview on an agent's chunk
180
+ * output produced 1112 of 1142 lines in a run whose plan, six tasks and
181
+ * twelve steps took 30. The first invocation is the informative one.
182
+ */
183
+ _executionsLogged = 0;
184
+ /**
185
+ * Most recent envelope consumed per handle during the current gather.
186
+ * Reset before each invocation. Used to compute invocation lineage when
187
+ * the correlation flag is on.
188
+ */
189
+ _lastEnvelopes = new Map();
39
190
  /** Callback to emit processing messages (NodeUpdate, etc.). */
40
191
  _emitMessage;
41
192
  /** Optional execution context passed into node executors. */
42
193
  _executionContext;
43
194
  /** Control context for controller nodes (injected as _control_context input). */
44
195
  _controlContext;
196
+ /**
197
+ * Static correlation analysis for this node, supplied by the runner.
198
+ */
199
+ _correlation;
200
+ /**
201
+ * Per-iteration-root, per-parent-key counter for actor-minted iteration
202
+ * tokens. §2 — counters are scoped by `(root id, exact parent lineage)`
203
+ * and never reset for repeated invocations with the same parent key.
204
+ */
205
+ _iterationCounters = new Map();
206
+ /**
207
+ * Run-level cancellation signal (aborted by `WorkflowRunner.cancel()`),
208
+ * exposed to node code via `NodeInputs.signal`. Defaults to a
209
+ * never-aborted signal for test fixtures.
210
+ */
211
+ _cancelSignal;
212
+ /**
213
+ * Callback wired by the runner to signal early end-of-stream for a single
214
+ * output slot (`outputs.complete(slot)`). Marks the slot's downstream edges
215
+ * done immediately, rather than waiting for the actor to finish.
216
+ */
217
+ _signalSlotEos;
218
+ /**
219
+ * Supervisor for this run, if any. Absent means no escalation is ever
220
+ * constructed and the actor behaves exactly as it did before — a clean run
221
+ * with no supervisor costs nothing, because nothing runs.
222
+ */
223
+ _supervisor;
224
+ /** Records every escalation/verdict pair for `RunResult.interventions`. */
225
+ _onIntervention;
45
226
  constructor(opts) {
46
227
  this.node = opts.node;
47
228
  this.inbox = opts.inbox;
@@ -49,8 +230,13 @@ export class NodeActor {
49
230
  this._sendOutputs = opts.sendOutputs;
50
231
  this._emitMessage = opts.emitMessage;
51
232
  this._executionContext = opts.executionContext;
52
- this._initialStickyHandles = opts.stickyHandles ?? new Set();
233
+ this._listInputHandles = opts.listInputHandles ?? new Set();
53
234
  this._controlContext = opts.controlContext ?? null;
235
+ this._correlation = opts.correlation;
236
+ this._cancelSignal = opts.cancelSignal ?? new AbortController().signal;
237
+ this._signalSlotEos = opts.signalSlotEos;
238
+ this._supervisor = opts.supervisor;
239
+ this._onIntervention = opts.onIntervention;
54
240
  }
55
241
  // -----------------------------------------------------------------------
56
242
  // Main execution entry point
@@ -60,11 +246,16 @@ export class NodeActor {
60
246
  * Returns the last outputs produced.
61
247
  */
62
248
  async run() {
63
- return withNodeSpan({ nodeId: this.node.id, nodeType: this.node.type }, () => this._runImpl());
249
+ return withNodeSpan(
250
+ // Stryker disable next-line ObjectLiteral: OpenTelemetry span attributes are observability, not a behavioural contract
251
+ { nodeId: this.node.id, nodeType: this.node.type }, (span) => this._runImpl(span));
64
252
  }
65
- async _runImpl() {
253
+ async _runImpl(span) {
66
254
  let errorMessage;
255
+ let errorDetail;
256
+ this._executionContext?.clearProviderCost?.();
67
257
  try {
258
+ // Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
68
259
  log.debug("Actor started", {
69
260
  nodeId: this.node.id,
70
261
  type: this.node.type
@@ -73,38 +264,32 @@ export class NodeActor {
73
264
  if (this._executor.preProcess) {
74
265
  await this._executor.preProcess();
75
266
  }
76
- // Determine execution mode
77
- if (this.node.is_streaming_input) {
78
- if (this._executor.run) {
79
- // Streaming input mode with run(): node drains inbox via
80
- // NodeInputs and pushes outputs via NodeOutputs.
81
- const nodeInputs = new NodeInputs(this.inbox);
82
- const nodeOutputs = new NodeOutputs({
83
- sendFn: async (slot, value) => {
84
- await this._sendOutputs(this.node.id, { [slot]: value });
85
- }
86
- });
87
- await this._executor.run(nodeInputs, nodeOutputs, this._executionContext);
88
- this._latestResult = nodeOutputs.collected();
89
- }
90
- else {
91
- // Legacy fallback: call process() once with empty inputs.
92
- const outputs = await this._executor.process({}, this._executionContext);
93
- this._latestResult = outputs;
94
- await this._sendOutputs(this.node.id, outputs);
95
- }
96
- }
97
- else if (this.node.is_controlled) {
98
- // Controlled mode: wait for control events from inbox
99
- await this._runControlled();
100
- }
101
- else {
102
- // Standard buffered or streaming-output mode
103
- await this._runBuffered();
104
- }
267
+ await this._runExecutionMode();
105
268
  }
106
269
  catch (err) {
107
270
  errorMessage = err instanceof Error ? err.message : String(err);
271
+ // The error is returned, not thrown, so `withNodeSpan` cannot see it.
272
+ markSpanError(span, err);
273
+ // A credential failure carries the provider and the key that failed,
274
+ // so the editor can send the user straight to the screen that fixes it
275
+ // instead of asking them to parse the message.
276
+ const failure = providerFailureDetail(err);
277
+ const runtimePackage = missingRuntimePackageOf(err);
278
+ if (failure) {
279
+ errorDetail = {
280
+ code: failure.code,
281
+ provider: failure.provider,
282
+ secret_key: failure.secretKey
283
+ };
284
+ }
285
+ else if (runtimePackage) {
286
+ // The editor offers to install the package in place.
287
+ errorDetail = {
288
+ code: "missing_runtime_package",
289
+ runtime_package: runtimePackage
290
+ };
291
+ }
292
+ // Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
108
293
  log.error("Actor failed", {
109
294
  nodeId: this.node.id,
110
295
  type: this.node.type,
@@ -123,9 +308,10 @@ export class NodeActor {
123
308
  }
124
309
  }
125
310
  if (errorMessage !== undefined) {
126
- this._emitNodeStatus("error", undefined, errorMessage);
311
+ this._emitNodeStatus("error", undefined, errorMessage, errorDetail);
127
312
  return { outputs: {}, error: errorMessage };
128
313
  }
314
+ // Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
129
315
  log.debug("Actor completed", {
130
316
  nodeId: this.node.id,
131
317
  type: this.node.type
@@ -137,61 +323,995 @@ export class NodeActor {
137
323
  this._emitNodeStatus("completed", skipResult ? undefined : (this._latestResult ?? {}));
138
324
  return { outputs: this._latestResult ?? {} };
139
325
  }
326
+ /**
327
+ * Run the node in whichever of the four execution modes applies.
328
+ *
329
+ * Trigger entry comes first: when this run was started by a delivered
330
+ * trigger event targeting this node, the node does not listen — it emits the
331
+ * event payload on its declared outputs via emitTriggerEvent() and
332
+ * completes. Runs without a trigger event (user pressed Run in the editor)
333
+ * fall through to the normal modes below, preserving the in-editor
334
+ * live-test experience.
335
+ */
336
+ async _runExecutionMode() {
337
+ const triggerEvent = this._executionContext?.triggerEvent;
338
+ if (this.node.is_trigger &&
339
+ triggerEvent?.node_id === this.node.id &&
340
+ this._executor.emitTriggerEvent) {
341
+ return this._runTriggerEntry(triggerEvent);
342
+ }
343
+ if (this.node.type === LOOP_NODE_TYPE) {
344
+ return this._runLoopMode();
345
+ }
346
+ if (this.node.is_streaming_input) {
347
+ return this._executor.run
348
+ ? this._runStreamingInputMode()
349
+ : this._runStreamingInputWithoutRun();
350
+ }
351
+ if (this.node.is_controlled) {
352
+ // Controlled mode: wait for control events from inbox
353
+ return this._runControlled();
354
+ }
355
+ if (!this._correlation) {
356
+ throw new Error(`Missing correlation analysis for node "${this.node.id}"`);
357
+ }
358
+ return this._runCorrelated(this._correlation);
359
+ }
360
+ /**
361
+ * Loop mode: the kernel owns iteration, feedback matching, and termination
362
+ * for `nodetool.control.Loop`; the node's process() is never called.
363
+ * docs/workflow-loops.md.
364
+ */
365
+ async _runLoopMode() {
366
+ if (!this._correlation) {
367
+ throw new Error(`Missing correlation analysis for node "${this.node.id}"`);
368
+ }
369
+ const result = {};
370
+ await runLoop({
371
+ node: this.node,
372
+ inbox: this.inbox,
373
+ analysis: this._correlation,
374
+ emit: async (slot, value, lineage) => {
375
+ result[slot] = value;
376
+ await this._route({ [slot]: value }, { perSlotLineage: { [slot]: lineage } });
377
+ },
378
+ closeSlot: (slot) => this._signalSlotEos?.(this.node.id, slot),
379
+ warn: (message) => this._emitNodeStatus("warning", undefined, message)
380
+ });
381
+ this._latestResult = result;
382
+ }
383
+ /**
384
+ * Trigger entry: emit the delivered event's payload on the declared output
385
+ * slots and complete. One committed result per trigger event (RFC §5 site
386
+ * parity with the streaming-input run() path).
387
+ */
388
+ async _runTriggerEntry(event) {
389
+ const nodeOutputs = new NodeOutputs({
390
+ sendFn: async (slot, value) => {
391
+ await this._sendOutputs(this.node.id, { [slot]: value });
392
+ },
393
+ eosCallback: (slot) => {
394
+ this._signalSlotEos?.(this.node.id, slot || "output");
395
+ }
396
+ });
397
+ await this._executor.emitTriggerEvent(event, nodeOutputs);
398
+ this._latestResult = nodeOutputs.collected();
399
+ this._emitGenerationComplete(this._latestResult);
400
+ }
401
+ /**
402
+ * Streaming input mode with run(): the node drains the inbox via NodeInputs
403
+ * and pushes outputs via NodeOutputs. Passing _lastEnvelopes as the tracker
404
+ * lets unmigrated filters that call inputs.stream()+outputs.emit() inherit
405
+ * lineage from the single-edge input automatically — matching the buffered
406
+ * rule.
407
+ */
408
+ async _runStreamingInputMode() {
409
+ const nodeInputs = new NodeInputs(this.inbox, this._lastEnvelopes, this._correlation, this._cancelSignal);
410
+ const nodeOutputs = new NodeOutputs({
411
+ sendFn: async (slot, value, opts) => {
412
+ await this._route({ [slot]: value }, this._streamingEmitHints(slot, opts?.lineage));
413
+ },
414
+ emitGroupFn: async (values, opts) => {
415
+ await this._emitGroup(values, opts?.lineage);
416
+ },
417
+ eosCallback: (slot) => {
418
+ this._signalSlotEos?.(this.node.id, slot || "output");
419
+ },
420
+ dropFn: async (slot, envelope) => {
421
+ // outputs.drop(slot, envelope) → send `lineage_done` on every
422
+ // outgoing edge for `slot` at the envelope's projected key. §5. The
423
+ // drop signal lets downstream joins move past keys that were
424
+ // intentionally filtered out.
425
+ await this._propagateLineageDone(slot, envelope.correlation_lineage);
426
+ }
427
+ });
428
+ await this._runStreamingInput(nodeInputs, nodeOutputs);
429
+ this._latestResult = nodeOutputs.collected();
430
+ // Site #5 (RFC §5): streaming-input run() — one committed result.
431
+ this._emitGenerationComplete(this._latestResult);
432
+ }
433
+ /**
434
+ * Routing hints for one `outputs.emit()` from a streaming-input node.
435
+ *
436
+ * An explicit lineage from the caller wins outright — they own the lineage
437
+ * shape (e.g. forward(), or a source seeding its own root). Otherwise the
438
+ * emit inherits the invocation lineage, and the slot's own
439
+ * `output_correlation` may override it for that one slot: an `aggregate`
440
+ * output collapses a root from the consumed lineage (the static analyzer
441
+ * drops it from the output scope; the runtime lineage must match), an
442
+ * `iteration` output mints a token per (group, parent_key) so
443
+ * `outputs.emit()` still attaches the new root. A slot declares one kind or
444
+ * the other, so at most one of the two applies.
445
+ */
446
+ _streamingEmitHints(slot, callerLineage) {
447
+ if (callerLineage !== undefined) {
448
+ return { perSlotLineage: { [slot]: callerLineage } };
449
+ }
450
+ const hints = {};
451
+ const inherited = this._computeInvocationLineage();
452
+ if (inherited !== undefined) {
453
+ hints.invocationLineage = inherited;
454
+ }
455
+ const perSlot = this._maybeCollapseForSlot(slot, hints) ??
456
+ this._maybeMintForSlot(slot, hints);
457
+ if (perSlot !== undefined) {
458
+ hints.perSlotLineage = { [slot]: perSlot };
459
+ }
460
+ return hints;
461
+ }
462
+ /**
463
+ * Streaming-input node declared without a run() implementation: call
464
+ * process() once with the node's own property values, matching the defaults
465
+ * merge every other execution path applies. process() reads no inbox data,
466
+ * so any value queued on a connected data handle is dropped. Surface that
467
+ * instead of completing silently: the node is misdeclared (registry says
468
+ * is_streaming_input, implementation has no run()). Downgraded to a warning
469
+ * rather than a hard error because existing fixtures rely on the fallback
470
+ * firing with connected inputs.
471
+ */
472
+ async _runStreamingInputWithoutRun() {
473
+ const droppedHandles = this.inbox
474
+ .handles()
475
+ .filter((h) => h !== "__control__");
476
+ if (droppedHandles.length > 0) {
477
+ const warning = `streaming-input node ${this.node.type} has no run() ` +
478
+ `implementation but has connected inputs ` +
479
+ `(${droppedHandles.join(", ")}); data would be silently dropped`;
480
+ // Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
481
+ log.warn(warning, {
482
+ nodeId: this.node.id,
483
+ type: this.node.type
484
+ });
485
+ this._emitNodeStatus("warning", undefined, warning);
486
+ }
487
+ const outputs = await this._executor.process(this._applyDynamicSlots({
488
+ ...(this.node.properties ?? {}),
489
+ ...(this.node.dynamic_properties ?? {})
490
+ }), this._executionContext);
491
+ this._latestResult = outputs;
492
+ await this._sendOutputs(this.node.id, outputs);
493
+ // Site #3 (RFC §5): legacy single process() — one committed result.
494
+ this._emitGenerationComplete(outputs);
495
+ }
140
496
  // -----------------------------------------------------------------------
141
- // Execution modes
497
+ // Correlated buffered scheduler (PR 3 of docs/correlation-design.md)
142
498
  // -----------------------------------------------------------------------
143
499
  /**
144
- * Buffered / streaming-output execution.
145
- * Gathers inputs per sync_mode, then runs process or genProcess.
500
+ * Project an envelope's lineage onto a static scope, returning the
501
+ * canonical key or `null` if the lineage is incomplete for the scope.
146
502
  */
147
- async _runBuffered() {
148
- const syncMode = this.node.sync_mode ?? "zip_all";
149
- const inputHandles = [...this.inbox["_buffers"].keys()].filter((h) => h !== "__control__");
150
- // Source nodes with no data inputs should execute once with empty inputs.
151
- if (inputHandles.length === 0) {
503
+ _projectKey(envelope, scope) {
504
+ return tryProjectLineageKey(envelope.correlation_lineage, scope);
505
+ }
506
+ /**
507
+ * Mint the next token index for `rootId` under `parentKey` and remember it.
508
+ * Counters never reset within one workflow run, matching §2's rule that
509
+ * repeated invocations with the same parent key continue numbering instead
510
+ * of restarting at 0.
511
+ */
512
+ _mintIterationToken(rootId, parentKey) {
513
+ let perRoot = this._iterationCounters.get(rootId);
514
+ if (!perRoot) {
515
+ perRoot = new Map();
516
+ this._iterationCounters.set(rootId, perRoot);
517
+ }
518
+ const next = perRoot.get(parentKey) ?? 0;
519
+ perRoot.set(parentKey, next + 1);
520
+ return next;
521
+ }
522
+ /**
523
+ * Correlated buffered scheduler — replaces `_runBuffered` under
524
+ * correlation.
525
+ *
526
+ * Algorithm (v1 of §4):
527
+ * 1. Classify each connected data handle by its static scope:
528
+ * - max-scope: scope length == invocation scope length → bucket per key
529
+ * - strict-prefix sticky: shorter non-empty scope → sticky per projected
530
+ * parent key
531
+ * - empty: empty scope → single sticky entry
532
+ * 2. Find the repeating driver, if any: at most one max-scope handle may be
533
+ * `repeats_per_key`. Static validation already rejects more than one.
534
+ * 3. Pull envelopes via `iterAnyWithEnvelope`. On each arrival:
535
+ * - record into the right bucket,
536
+ * - re-evaluate the keys that could now be ready.
537
+ * 4. For each ready key, gather values and call `_executeWithInputs`.
538
+ *
539
+ * Source nodes (no connected data handles) fire once with empty inputs.
540
+ */
541
+ async _runCorrelated(analysis) {
542
+ this._inCorrelatedBuffered = true;
543
+ try {
544
+ await this._runCorrelatedImpl(analysis);
545
+ }
546
+ finally {
547
+ this._inCorrelatedBuffered = false;
548
+ }
549
+ }
550
+ async _runCorrelatedImpl(analysis) {
551
+ const dataHandles = this.inbox.handles().filter((h) => h !== "__control__");
552
+ if (dataHandles.length === 0) {
553
+ // Source node: fire once with empty inputs at empty scope.
152
554
  await this._executeWithInputs({});
153
555
  return;
154
556
  }
155
- if (syncMode === "on_any") {
156
- return this._runOnAny(inputHandles);
557
+ const handleScope = new Map();
558
+ const handleClass = new Map();
559
+ const handleRepeats = new Map();
560
+ const invocationScope = analysis.invocationScope;
561
+ for (const h of dataHandles) {
562
+ const info = analysis.inputs.get(h);
563
+ const scope = info?.scope ?? [];
564
+ handleScope.set(h, scope);
565
+ handleRepeats.set(h, info?.repeatsPerKey ?? false);
566
+ // A repeating handle at the invocation scope is always "max" so the
567
+ // driver machinery fires once per envelope — including at root scope
568
+ // (both lengths 0, e.g. a chunk stream consumed at top level), where
569
+ // classifying it "empty" would make every chunk overwrite a single
570
+ // sticky slot and the node fire once with only the last chunk.
571
+ if (scope.length === invocationScope.length &&
572
+ (scope.length > 0 || handleRepeats.get(h))) {
573
+ handleClass.set(h, "max");
574
+ }
575
+ else if (scope.length === 0) {
576
+ handleClass.set(h, "empty");
577
+ }
578
+ else {
579
+ handleClass.set(h, "prefix");
580
+ }
581
+ }
582
+ const driverHandle = (() => {
583
+ for (const h of dataHandles) {
584
+ if (handleClass.get(h) === "max" && handleRepeats.get(h)) {
585
+ return h;
586
+ }
587
+ }
588
+ return null;
589
+ })();
590
+ // Buckets keyed by canonical projected key.
591
+ const maxBuckets = new Map();
592
+ const prefixSticky = new Map();
593
+ const emptySticky = new Map();
594
+ // Handles already warned about empty-scope overwrite (§11): warn once per
595
+ // handle per run so an unmigrated stream collapsing to last-value-wins is
596
+ // visible without flooding the log.
597
+ const emptyStickyWarned = new Set();
598
+ // Multi-edge list inputs accumulate every envelope instead of
599
+ // overwriting; drained as an array when the node fires.
600
+ const emptyListEnvelopes = new Map();
601
+ const prefixListBuckets = new Map();
602
+ const isListInput = (h) => this._listInputHandles.has(h);
603
+ // A list-typed handle's declared element type is itself a list only for
604
+ // deliberate batch-of-batches properties (e.g. "list[list[int]]"); per-edge
605
+ // list values stay nested as one entry each in that case.
606
+ const isNestedListHandle = (h) => {
607
+ const typeStr = this.node.propertyTypes?.[h];
608
+ if (!typeStr)
609
+ return false;
610
+ const meta = TypeMetadata.fromString(typeStr);
611
+ return meta.isListType() && meta.args.length > 0 && meta.args[0].isListType();
612
+ };
613
+ // Aggregate per-edge values into one list for a list-typed handle. A list
614
+ // value arriving on a single edge (e.g. an upstream Image List's Output
615
+ // feeding another Image List's collect input) is spread into the result
616
+ // so its items propagate, rather than nesting the whole list as a single
617
+ // entry — unless the handle's declared type is itself a list of lists.
618
+ const aggregateListValues = (h, items) => {
619
+ if (isNestedListHandle(h))
620
+ return items;
621
+ const out = [];
622
+ for (const item of items) {
623
+ if (Array.isArray(item)) {
624
+ out.push(...item);
625
+ }
626
+ else {
627
+ out.push(item);
628
+ }
629
+ }
630
+ return out;
631
+ };
632
+ for (const h of dataHandles) {
633
+ const cls = handleClass.get(h);
634
+ if (cls === "max")
635
+ maxBuckets.set(h, new Map());
636
+ else if (cls === "prefix") {
637
+ prefixSticky.set(h, new Map());
638
+ if (isListInput(h))
639
+ prefixListBuckets.set(h, new Map());
640
+ }
641
+ else if (cls === "empty" && isListInput(h)) {
642
+ emptyListEnvelopes.set(h, []);
643
+ }
157
644
  }
158
- // zip_all: keep gathering input batches until inbox is drained
159
- while (true) {
160
- const inputs = await this._gatherZipAll();
161
- if (inputs === null)
162
- break;
163
- await this._executeWithInputs(inputs);
164
- if (this.inbox.isFullyDrained())
165
- break;
645
+ const fired = new Set();
646
+ const isReady = (key) => {
647
+ for (const h of dataHandles) {
648
+ const cls = handleClass.get(h);
649
+ if (cls === "max") {
650
+ const bucket = maxBuckets.get(h).get(key);
651
+ if (!bucket || bucket.length === 0) {
652
+ // Not ready. v1 has no side-input sticky at max scope: a
653
+ // non-driver max handle must still have produced for this exact
654
+ // key, so the answer is `false` with or without a repeating
655
+ // driver.
656
+ return false;
657
+ }
658
+ // Multi-edge list inputs aggregate every envelope: wait for the
659
+ // handle to close so we capture the full set.
660
+ if (isListInput(h) && this.inbox.isOpen(h))
661
+ return false;
662
+ }
663
+ else if (cls === "prefix") {
664
+ const parentScope = handleScope.get(h);
665
+ const parentKey = trimKey(key, parentScope.length);
666
+ if (isListInput(h)) {
667
+ // Multi-edge list at prefix scope: wait for close so every
668
+ // envelope routed to this parentKey is captured.
669
+ if (this.inbox.isOpen(h))
670
+ return false;
671
+ const bucket = prefixListBuckets.get(h).get(parentKey);
672
+ if (!bucket || bucket.length === 0)
673
+ return false;
674
+ }
675
+ else {
676
+ const stickyMap = prefixSticky.get(h);
677
+ if (!stickyMap.has(parentKey))
678
+ return false;
679
+ }
680
+ }
681
+ else {
682
+ // empty-scope sticky / list
683
+ if (isListInput(h)) {
684
+ // Multi-edge list at empty scope: wait for close to aggregate.
685
+ if (this.inbox.isOpen(h))
686
+ return false;
687
+ }
688
+ else if (!emptySticky.has(h)) {
689
+ // Allow node properties / dynamic_properties to supply defaults:
690
+ // _executeWithInputs already merges them (and type-checks the
691
+ // ones with a declared slot in dynamic_inputs). So an empty-scope
692
+ // handle without an envelope is treated as "use the node's
693
+ // declared default" if the handle has no open upstream.
694
+ if (this.inbox.isOpen(h))
695
+ return false;
696
+ }
697
+ }
698
+ }
699
+ return true;
700
+ };
701
+ const collect = (key) => {
702
+ const values = {};
703
+ const envelopes = new Map();
704
+ for (const h of dataHandles) {
705
+ const cls = handleClass.get(h);
706
+ if (cls === "max") {
707
+ const bucket = maxBuckets.get(h).get(key);
708
+ if (!bucket || bucket.length === 0)
709
+ continue;
710
+ if (isListInput(h)) {
711
+ // Drain every envelope into a list; pick the last for lineage.
712
+ const drained = bucket.splice(0);
713
+ envelopes.set(h, drained[drained.length - 1]);
714
+ values[h] = aggregateListValues(h, drained.map((e) => e.data));
715
+ maxBuckets.get(h).delete(key);
716
+ }
717
+ else {
718
+ const stickySideInput = driverHandle !== null && h !== driverHandle;
719
+ const env = stickySideInput ? bucket[0] : bucket.shift();
720
+ envelopes.set(h, env);
721
+ values[h] = env.data;
722
+ if (!stickySideInput && bucket.length === 0) {
723
+ maxBuckets.get(h).delete(key);
724
+ }
725
+ }
726
+ }
727
+ else if (cls === "prefix") {
728
+ const parentScope = handleScope.get(h);
729
+ const parentKey = trimKey(key, parentScope.length);
730
+ if (isListInput(h)) {
731
+ const bucket = prefixListBuckets.get(h).get(parentKey);
732
+ if (bucket && bucket.length > 0) {
733
+ envelopes.set(h, bucket[bucket.length - 1]);
734
+ values[h] = aggregateListValues(h, bucket.map((e) => e.data));
735
+ }
736
+ }
737
+ else {
738
+ const env = prefixSticky.get(h).get(parentKey);
739
+ if (env) {
740
+ envelopes.set(h, env);
741
+ values[h] = env.data;
742
+ }
743
+ }
744
+ }
745
+ else {
746
+ if (isListInput(h)) {
747
+ const envs = emptyListEnvelopes.get(h) ?? [];
748
+ if (envs.length > 0) {
749
+ envelopes.set(h, envs[envs.length - 1]);
750
+ values[h] = aggregateListValues(h, envs.map((e) => e.data));
751
+ }
752
+ }
753
+ else {
754
+ const env = emptySticky.get(h);
755
+ if (env) {
756
+ envelopes.set(h, env);
757
+ values[h] = env.data;
758
+ }
759
+ }
760
+ }
761
+ }
762
+ return { values, envelopes };
763
+ };
764
+ const tryFire = async (candidateKeys) => {
765
+ for (const key of candidateKeys) {
766
+ if (driverHandle === null) {
767
+ if (fired.has(key)) {
768
+ // For non-repeating drivers each key fires at most once because
769
+ // bucket consumption strips it. The fired set protects against
770
+ // double-fire when the same key comes from multiple notifications.
771
+ continue;
772
+ }
773
+ if (!isReady(key))
774
+ continue;
775
+ const { values, envelopes } = collect(key);
776
+ // Set per-invocation envelopes so output routing can derive lineage.
777
+ this._lastEnvelopes = envelopes;
778
+ await this._executeWithInputs(values);
779
+ fired.add(key);
780
+ }
781
+ else {
782
+ // Repeating driver: drain the whole backlog for this key, not just
783
+ // one envelope. Envelopes can pile up while a sticky input blocks
784
+ // readiness; firing once per notification would strand the rest in
785
+ // the actor-local bucket (silent data loss). collect() consumes one
786
+ // driver envelope per pass, so this loop terminates.
787
+ while (isReady(key)) {
788
+ const { values, envelopes } = collect(key);
789
+ this._lastEnvelopes = envelopes;
790
+ await this._executeWithInputs(values);
791
+ }
792
+ }
793
+ }
794
+ };
795
+ // Pre-seed: if any handle starts with no upstream (closed), nothing
796
+ // arrives. Continue and let the loop terminate.
797
+ for await (const [handle, envelope] of this.inbox.iterAnyWithEnvelope()) {
798
+ if (handle === "__control__")
799
+ continue;
800
+ const cls = handleClass.get(handle);
801
+ if (cls === undefined)
802
+ continue;
803
+ if (cls === "max") {
804
+ const scope = handleScope.get(handle);
805
+ const key = this._projectKey(envelope, scope) ?? "";
806
+ const handleBuckets = maxBuckets.get(handle);
807
+ let bucket = handleBuckets.get(key);
808
+ if (!bucket) {
809
+ if (handleBuckets.size >= this.inbox.maxPendingKeys) {
810
+ throw new Error(`Inbox for node "${this.node.id}" exceeded max_pending_keys ` +
811
+ `(${this.inbox.maxPendingKeys}) on handle "${handle}". ` +
812
+ `Likely missing upstream close — see docs/correlation-design.md §6.`);
813
+ }
814
+ bucket = [];
815
+ handleBuckets.set(key, bucket);
816
+ }
817
+ if (bucket.length >= this.inbox.maxPendingMessagesPerKey) {
818
+ throw new Error(`Inbox for node "${this.node.id}" exceeded ` +
819
+ `max_pending_messages_per_key (` +
820
+ `${this.inbox.maxPendingMessagesPerKey}) on handle "${handle}" ` +
821
+ `for key "${key}".`);
822
+ }
823
+ bucket.push(envelope);
824
+ await tryFire([key]);
825
+ }
826
+ else if (cls === "prefix") {
827
+ const parentScope = handleScope.get(handle);
828
+ const parentKey = this._projectKey(envelope, parentScope) ?? "";
829
+ if (isListInput(handle)) {
830
+ const handleBuckets = prefixListBuckets.get(handle);
831
+ let bucket = handleBuckets.get(parentKey);
832
+ if (!bucket) {
833
+ bucket = [];
834
+ handleBuckets.set(parentKey, bucket);
835
+ }
836
+ bucket.push(envelope);
837
+ }
838
+ else {
839
+ prefixSticky.get(handle).set(parentKey, envelope);
840
+ }
841
+ // Try firing any max-scope keys whose parent matches this parentKey.
842
+ const candidates = enumerateCandidateKeysForParent(maxBuckets, dataHandles, handleClass, handleScope, invocationScope.length, parentKey, parentScope.length);
843
+ await tryFire(candidates);
844
+ }
845
+ else {
846
+ if (isListInput(handle)) {
847
+ emptyListEnvelopes.get(handle).push(envelope);
848
+ }
849
+ else {
850
+ if (emptySticky.has(handle) && !emptyStickyWarned.has(handle)) {
851
+ emptyStickyWarned.add(handle);
852
+ // Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
853
+ log.warn(`Node "${this.node.id}" handle "${handle}" received multiple ` +
854
+ // Stryker disable next-line StringLiteral: diagnostic log args only
855
+ `values at empty scope; only the last is kept. Declare ` +
856
+ // Stryker disable next-line StringLiteral: diagnostic log args only
857
+ `output_correlation (chunk/iteration) on the upstream output ` +
858
+ // Stryker disable next-line StringLiteral: diagnostic log args only
859
+ `to preserve the stream.`,
860
+ // Stryker disable next-line ObjectLiteral: diagnostic log args only
861
+ { nodeId: this.node.id, handle });
862
+ }
863
+ emptySticky.set(handle, envelope);
864
+ }
865
+ // Empty-scope arrival can unblock any pending max-scope key.
866
+ const candidates = enumerateAllPendingKeys(maxBuckets);
867
+ await tryFire(candidates);
868
+ }
869
+ }
870
+ // After iteration ends, every handle is closed. Multi-edge list inputs
871
+ // gated on close are now ready: re-fire any pending max-scope keys.
872
+ await tryFire(enumerateAllPendingKeys(maxBuckets));
873
+ // If the node has no max-scope inputs (all empty / prefix), fire once.
874
+ if ([...handleClass.values()].every((c) => c !== "max") && !fired.has("")) {
875
+ // Build values from sticky state.
876
+ const values = {};
877
+ const envelopes = new Map();
878
+ let readyOrAllowed = true;
879
+ for (const h of dataHandles) {
880
+ if (handleClass.get(h) === "prefix") {
881
+ if (isListInput(h)) {
882
+ // Aggregate every envelope across all parentKeys.
883
+ const handleBuckets = prefixListBuckets.get(h);
884
+ const drained = [];
885
+ for (const bucket of handleBuckets.values()) {
886
+ drained.push(...bucket);
887
+ }
888
+ if (drained.length === 0)
889
+ continue;
890
+ envelopes.set(h, drained[drained.length - 1]);
891
+ values[h] = aggregateListValues(h, drained.map((e) => e.data));
892
+ }
893
+ else {
894
+ // Use the only sticky entry, if any.
895
+ const sticky = prefixSticky.get(h);
896
+ if (sticky.size === 0) {
897
+ // No value arrived; defaults will apply in _executeWithInputs.
898
+ continue;
899
+ }
900
+ const first = sticky.values().next().value;
901
+ envelopes.set(h, first);
902
+ values[h] = first.data;
903
+ }
904
+ }
905
+ else if (isListInput(h)) {
906
+ const envs = emptyListEnvelopes.get(h) ?? [];
907
+ if (envs.length > 0) {
908
+ envelopes.set(h, envs[envs.length - 1]);
909
+ values[h] = aggregateListValues(h, envs.map((e) => e.data));
910
+ }
911
+ else if (this.inbox.isOpen(h)) {
912
+ readyOrAllowed = false;
913
+ }
914
+ }
915
+ else {
916
+ const env = emptySticky.get(h);
917
+ if (env) {
918
+ envelopes.set(h, env);
919
+ values[h] = env.data;
920
+ }
921
+ else if (this.inbox.isOpen(h)) {
922
+ readyOrAllowed = false;
923
+ }
924
+ }
925
+ }
926
+ // A node wired to data inputs that received nothing on any of them is on
927
+ // an untaken branch: its upstreams all closed without emitting (an `If`
928
+ // emits only the taken handle, a filter can emit nothing at all). Firing
929
+ // it here would run it on its declared defaults — an Agent node with an
930
+ // empty prompt burning a model call, the untaken half of every
931
+ // conditional doing work nobody asked for. Skip instead, which closes
932
+ // this node's outputs with nothing and cascades the skip downstream.
933
+ //
934
+ // Partial input still fires: a node that got a value on one handle and
935
+ // nothing on another runs with defaults for the missing one, as before.
936
+ // Only "wired to something, received nothing" is treated as untaken.
937
+ const receivedNothing = dataHandles.length > 0 && envelopes.size === 0;
938
+ if (receivedNothing) {
939
+ // Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
940
+ log.debug("Skipping node on untaken branch", {
941
+ nodeId: this.node.id,
942
+ type: this.node.type
943
+ });
944
+ }
945
+ else if (readyOrAllowed) {
946
+ this._lastEnvelopes = envelopes;
947
+ await this._executeWithInputs(values);
948
+ fired.add("");
949
+ }
950
+ }
951
+ // Envelopes still stranded in actor-local buckets at close are invisible to
952
+ // the runner's post-run pending-inbox check (they were already popped). §12.
953
+ // With no repeating driver a key fires at most once, so a second max-scope
954
+ // envelope for an already-fired key is dropped silently; a key that never
955
+ // reached readiness keeps its envelopes too. Warn for both so the loss is
956
+ // not silent. Scheduling is unchanged.
957
+ for (const [handle, buckets] of maxBuckets) {
958
+ for (const [key, bucket] of buckets) {
959
+ if (bucket.length === 0)
960
+ continue;
961
+ if (fired.has(key)) {
962
+ // Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
963
+ log.warn(`Node "${this.node.id}" dropped ${bucket.length} envelope(s) on ` +
964
+ // Stryker disable next-line StringLiteral: diagnostic log args only
965
+ `handle "${handle}" for key "${key}" already fired without a ` +
966
+ // Stryker disable next-line StringLiteral: diagnostic log args only
967
+ `repeating driver; declare output_correlation to fan out per ` +
968
+ // Stryker disable next-line StringLiteral: diagnostic log args only
969
+ `item.`,
970
+ // Stryker disable next-line ObjectLiteral: diagnostic log args only
971
+ { nodeId: this.node.id, handle, key, count: bucket.length });
972
+ }
973
+ else {
974
+ // Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
975
+ log.warn(`Node "${this.node.id}" left ${bucket.length} envelope(s) on ` +
976
+ // Stryker disable next-line StringLiteral: diagnostic log args only
977
+ `handle "${handle}" for key "${key}" unfired at close; its ` +
978
+ // Stryker disable next-line StringLiteral: diagnostic log args only
979
+ `inputs never completed for this key.`,
980
+ // Stryker disable next-line ObjectLiteral: diagnostic log args only
981
+ { nodeId: this.node.id, handle, key, count: bucket.length });
982
+ }
983
+ }
166
984
  }
167
985
  }
986
+ // -----------------------------------------------------------------------
987
+ // Correlated invocation lineage and output routing
988
+ // -----------------------------------------------------------------------
168
989
  /**
169
- * on_any execution: wait for all handles to have at least one value,
170
- * then fire. After initial fire, each subsequent item fires immediately.
990
+ * Under the correlated scheduler the invocation lineage is the projected
991
+ * lineage of the consumed max-scope envelopes, written canonically. PR 2's
992
+ * fallback (single non-list handle) still applies when the analyzer is not
993
+ * available.
171
994
  */
172
- async _runOnAny(inputHandles) {
173
- const current = {};
174
- const pendingHandles = new Set(inputHandles);
175
- let initialFired = false;
176
- for await (const [handle, item] of this.inbox.iterAny()) {
177
- if (handle === "__control__")
995
+ _correlatedInvocationLineage() {
996
+ if (!this._correlation)
997
+ return undefined;
998
+ const invocationScope = this._correlation.invocationScope;
999
+ if (invocationScope.length === 0) {
1000
+ // For empty-scope nodes the lineage is also empty.
1001
+ return EMPTY_LINEAGE;
1002
+ }
1003
+ // Build a lineage from the longest projection any consumed envelope
1004
+ // supplies. Max-scope envelopes have the complete projection; prefix
1005
+ // envelopes contribute parent roots only.
1006
+ const out = {};
1007
+ for (const env of this._lastEnvelopes.values()) {
1008
+ for (const root of invocationScope) {
1009
+ if (root in env.correlation_lineage) {
1010
+ out[root] = env.correlation_lineage[root];
1011
+ }
1012
+ }
1013
+ }
1014
+ return out;
1015
+ }
1016
+ /**
1017
+ * Build the per-slot lineage map for an emission. Single/forward/chunk
1018
+ * outputs inherit the invocation lineage; iteration outputs mint a token
1019
+ * per group per frame.
1020
+ */
1021
+ _correlatedOutputLineage(invocationLineage, emittedHandles) {
1022
+ if (!this._correlation)
1023
+ return undefined;
1024
+ const declared = this.node.output_correlation ?? {};
1025
+ const perSlot = {};
1026
+ const groupTokens = new Map();
1027
+ const invocationScope = this._correlation.invocationScope;
1028
+ const parentKey = invocationScope.length
1029
+ ? projectLineageKey(invocationLineage, invocationScope)
1030
+ : "";
1031
+ for (const handle of emittedHandles) {
1032
+ const corr = declared[handle];
1033
+ if (!corr) {
1034
+ perSlot[handle] = invocationLineage;
178
1035
  continue;
179
- current[handle] = item;
180
- if (!initialFired) {
181
- pendingHandles.delete(handle);
182
- if (pendingHandles.size > 0)
183
- continue;
184
- await this._executeWithInputs({ ...current });
185
- initialFired = true;
1036
+ }
1037
+ if (corr.kind === "iteration") {
1038
+ const root = iterationRootId(this.node.id, handle, corr.group);
1039
+ let index = groupTokens.get(root);
1040
+ if (index === undefined) {
1041
+ // Reuse the token already minted for this frame, if any
1042
+ // (`_mintIterationFrameOverrides` mints before _sendOutputs runs).
1043
+ const fromFrame = this._lastMintedFrameTokens.get(root);
1044
+ if (fromFrame !== undefined) {
1045
+ index = fromFrame;
1046
+ }
1047
+ else {
1048
+ index = this._mintIterationToken(root, parentKey);
1049
+ }
1050
+ groupTokens.set(root, index);
1051
+ }
1052
+ perSlot[handle] = { ...invocationLineage, [root]: { index } };
186
1053
  }
187
1054
  else {
188
- await this._executeWithInputs({ ...current });
1055
+ // single/forward/chunk all inherit invocation lineage in v1.
1056
+ // forward outputs route their source envelope's lineage via
1057
+ // outputs.forward(); the static path is invocation lineage.
1058
+ perSlot[handle] = invocationLineage;
189
1059
  }
190
1060
  }
1061
+ return perSlot;
1062
+ }
1063
+ /**
1064
+ * Coerce and check every input that has a declared dynamic slot on this
1065
+ * node (`dynamic_inputs`). Slots without a declaration are untyped and
1066
+ * pass through untouched. Throws on a value that cannot fit its declared
1067
+ * type; the caller's catch turns that into a node error.
1068
+ */
1069
+ _applyDynamicSlots(inputs) {
1070
+ return applyDynamicSlotTypes(this.node, inputs);
1071
+ }
1072
+ /**
1073
+ * Put the node's static list items after the connected items on the handles
1074
+ * the executor names in `appendStaticInputs`. Every other edge input still
1075
+ * replaces the node's own property value.
1076
+ */
1077
+ _appendStaticItems(edgeInputs) {
1078
+ const handles = this._executor.appendStaticInputs;
1079
+ if (!handles || handles.length === 0)
1080
+ return edgeInputs;
1081
+ let result = edgeInputs;
1082
+ for (const handle of handles) {
1083
+ if (!Object.prototype.hasOwnProperty.call(edgeInputs, handle))
1084
+ continue;
1085
+ const staticItems = this.node.properties?.[handle];
1086
+ if (!Array.isArray(staticItems) || staticItems.length === 0)
1087
+ continue;
1088
+ const incoming = edgeInputs[handle];
1089
+ const incomingItems = incoming === null || incoming === undefined
1090
+ ? []
1091
+ : Array.isArray(incoming)
1092
+ ? incoming
1093
+ : [incoming];
1094
+ result = { ...result, [handle]: [...incomingItems, ...staticItems] };
1095
+ }
1096
+ return result;
191
1097
  }
192
1098
  /**
193
1099
  * Execute process or genProcess with the given inputs.
194
1100
  */
1101
+ /**
1102
+ * Run one invocation under the supervisor, if there is one.
1103
+ *
1104
+ * The catch wraps node execution and nothing else. `sendOutputs` routes to
1105
+ * downstream inboxes sequentially, so if edge 1 delivered and edge 2 threw, a
1106
+ * retry would duplicate edge 1's delivery — routing failures therefore fail
1107
+ * the node without escalation. Design §5.1.
1108
+ *
1109
+ * Returns the outputs to route, or `SKIPPED` when the invocation was retired
1110
+ * without emitting.
1111
+ */
1112
+ async _invokeWithRecovery(inputs, invoke) {
1113
+ for (let attempt = 1;; attempt++) {
1114
+ // A fresh account per attempt: what the previous try spent is not what
1115
+ // this one spent.
1116
+ const account = createInvocationAccount();
1117
+ try {
1118
+ return await inInvocationAccount(account, invoke);
1119
+ }
1120
+ catch (err) {
1121
+ if (!this._supervisor) {
1122
+ if (!this._degradeOnContentFilter(err, false))
1123
+ throw err;
1124
+ await this._skipInvocation();
1125
+ return SKIPPED;
1126
+ }
1127
+ const verdict = await this._escalate(err, inputs, attempt, account, {
1128
+ streamingOutput: false,
1129
+ streamingInput: false,
1130
+ emitted: false
1131
+ });
1132
+ switch (verdict.action) {
1133
+ case "retry":
1134
+ continue;
1135
+ // `_escalate` only returns `substitute` for outputs that passed
1136
+ // validation, so what comes back here is ready to route.
1137
+ case "substitute":
1138
+ return verdict.outputs;
1139
+ case "skip":
1140
+ await this._skipInvocation();
1141
+ return SKIPPED;
1142
+ default:
1143
+ throw err;
1144
+ }
1145
+ }
1146
+ }
1147
+ }
1148
+ /**
1149
+ * Build the escalation, ask the supervisor, and enforce the allowed set
1150
+ * against whatever comes back. The schema shown to an agent is UX; this check
1151
+ * is the guarantee — a buggy or third-party handle returning `retry` for an
1152
+ * unsafe node gets `fail`.
1153
+ */
1154
+ async _escalate(err, inputs, attempt, account, mode) {
1155
+ const escalation = this._buildEscalation(err, inputs, attempt, account, mode);
1156
+ this._emitMessage({
1157
+ type: "supervisor_escalation",
1158
+ node_id: this.node.id,
1159
+ node_name: this.node.name ?? this.node.type,
1160
+ escalation
1161
+ });
1162
+ let outcome;
1163
+ try {
1164
+ outcome = await this._supervisor.decide(escalation, this._cancelSignal);
1165
+ }
1166
+ catch {
1167
+ // A failure *of* the supervisor, which is what the bounds exist to
1168
+ // absorb — same class, and so the same label, as a timed-out decision.
1169
+ outcome = { verdict: { action: "fail" }, decidedBy: "bounds" };
1170
+ }
1171
+ // The record has to name who produced the verdict that was *applied*. When
1172
+ // the kernel overrules a handle, crediting the handle would hide exactly
1173
+ // the case worth finding: a buggy or hostile supervisor. A repair whose
1174
+ // values do not match the node's declared outputs is overruled here, not
1175
+ // after the fact: the intervention must record what happened, and a
1176
+ // rejected repair is a `fail`, not a repair.
1177
+ const allowed = escalation.allowedActions.includes(outcome.verdict.action) &&
1178
+ (outcome.verdict.action !== "substitute" ||
1179
+ (await this._validateSubstitute(outcome.verdict.outputs)));
1180
+ const verdict = allowed ? outcome.verdict : { action: "fail" };
1181
+ const decidedBy = allowed ? outcome.decidedBy : "kernel";
1182
+ this._emitMessage({
1183
+ type: "supervisor_decision",
1184
+ node_id: this.node.id,
1185
+ node_name: this.node.name ?? this.node.type,
1186
+ escalation,
1187
+ verdict,
1188
+ decided_by: decidedBy,
1189
+ cost: outcome.costUsd ?? null
1190
+ });
1191
+ this._onIntervention?.({
1192
+ escalation,
1193
+ verdict,
1194
+ decidedBy,
1195
+ costUsd: outcome.costUsd
1196
+ });
1197
+ return verdict;
1198
+ }
1199
+ /**
1200
+ * Mint the escalation record. Redaction happens *here*, not at some later
1201
+ * prompt: `Escalation` is public — it becomes a message, lands in
1202
+ * `RunResult.interventions`, and crosses the websocket — so no unredacted
1203
+ * instance may exist anywhere in the system. Design §6.1.
1204
+ */
1205
+ _buildEscalation(err, inputs, attempt, account, mode) {
1206
+ const secrets = this._executionContext?.getResolvedSecretValues?.() ?? new Set();
1207
+ const lineage = this._currentInvocationLineage ?? EMPTY_LINEAGE;
1208
+ const invocationScope = this._correlation?.invocationScope ?? [];
1209
+ const invocationKey = invocationScope.length
1210
+ ? projectLineageKey(lineage, invocationScope)
1211
+ : "";
1212
+ const recoverable = isRecoverableNodeError(err) ? err : undefined;
1213
+ const candidateOutput = recoverable
1214
+ ? redactValue(recoverable.candidateOutput, secrets)
1215
+ : undefined;
1216
+ const allowedActions = computeAllowedActions({
1217
+ retrySafe: this.node.retry_safe === true,
1218
+ spentCostUsd: account?.costUsd ?? 0,
1219
+ createdAssets: account?.createdAssets ?? false,
1220
+ hasCandidateOutput: recoverable !== undefined,
1221
+ validatorCoverage: hasFullValidatorCoverage(this.node.outputs ?? {},
1222
+ // Resolving a reference against run storage needs a resolver the
1223
+ // kernel does not have yet, so reference-typed outputs are not
1224
+ // substitutable — better than accepting an unresolvable ref.
1225
+ false),
1226
+ ...mode
1227
+ });
1228
+ return {
1229
+ nodeId: this.node.id,
1230
+ nodeType: this.node.type,
1231
+ correlationLineage: invocationKey === "" ? [] : invocationKey.split(","),
1232
+ invocationKey,
1233
+ allowedActions,
1234
+ detail: String(redactValue(err instanceof Error ? err.message : String(err), secrets)),
1235
+ failureSignature: recoverable?.code ?? failureSignature(err),
1236
+ candidateOutput,
1237
+ inputs: redactRecord(inputs, secrets),
1238
+ declaredOutputs: this.node.outputs ?? {},
1239
+ attempt,
1240
+ spentCostUsd: account?.costUsd ?? 0,
1241
+ createdAssets: account?.createdAssets ?? false,
1242
+ retrySafe: this.node.retry_safe === true,
1243
+ emitted: mode.emitted
1244
+ };
1245
+ }
1246
+ /**
1247
+ * A repaired value is type-checked against the node's declared outputs
1248
+ * before it enters the graph. An invalid repair is not a repair.
1249
+ */
1250
+ async _validateSubstitute(outputs) {
1251
+ const declared = this.node.outputs ?? {};
1252
+ const result = await validateSubstituteOutputs(outputs, {
1253
+ declaredOutputs: declared
1254
+ });
1255
+ if (!result.ok) {
1256
+ // Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
1257
+ log.warn("Rejected supervisor substitution", {
1258
+ nodeId: this.node.id,
1259
+ issues: result.issues
1260
+ });
1261
+ }
1262
+ return result.ok;
1263
+ }
1264
+ /**
1265
+ * Retire this invocation without emitting: `lineage_done` plus scope closure
1266
+ * on every outgoing edge, so downstream joins move past the skipped key and
1267
+ * aggregates see the scopes the invocation would have opened get closed.
1268
+ */
1269
+ async _skipInvocation() {
1270
+ await this._sendOutputs(this.node.id, {}, {
1271
+ skipInvocation: true,
1272
+ invocationLineage: this._currentInvocationLineage ?? EMPTY_LINEAGE
1273
+ });
1274
+ }
1275
+ /**
1276
+ * Whether to drop this item instead of the run, after the provider's own
1277
+ * bounded retries failed to get past its content filter. The built-in policy
1278
+ * for an unsupervised run — a supervised one escalates instead, because
1279
+ * putting an agent on the failure path is what `--supervise` is for.
1280
+ *
1281
+ * Veo filtered one shot of a five-shot trailer on an ordinary cinematic
1282
+ * prompt. Failing the node there fails the run and discards the four shots
1283
+ * already generated and paid for, which is worse than delivering a four-shot
1284
+ * cut and saying which shot was refused.
1285
+ *
1286
+ * Only for an invocation that is one item of a fan-out: a non-empty
1287
+ * correlation lineage says an upstream item keyed this invocation, so the
1288
+ * siblings are real work a failure would throw away. A single-shot node has
1289
+ * no siblings to protect and still fails loudly. An invocation that already
1290
+ * emitted is out too — its partial output is downstream, so retiring the
1291
+ * lineage now would tell joins nothing arrived.
1292
+ */
1293
+ _degradeOnContentFilter(err, emitted) {
1294
+ if (emitted || !isContentFilterRefusal(err))
1295
+ return false;
1296
+ const lineage = this._currentInvocationLineage;
1297
+ if (!lineage || Object.keys(lineage).length === 0)
1298
+ return false;
1299
+ const detail = err instanceof Error ? err.message : String(err);
1300
+ // Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
1301
+ log.warn("Dropping content-filtered item", {
1302
+ nodeId: this.node.id,
1303
+ type: this.node.type,
1304
+ detail
1305
+ });
1306
+ this._emitMessage({
1307
+ type: "log_update",
1308
+ node_id: this.node.id,
1309
+ node_name: this.node.name ?? this.node.type,
1310
+ severity: "warning",
1311
+ content: `Dropped one item: the provider's content filter refused it and retrying did not clear it. The rest of the run continues. ${detail}`
1312
+ });
1313
+ return true;
1314
+ }
195
1315
  async _executeWithInputs(inputs) {
196
1316
  // Merge node properties as defaults — edge inputs override.
197
1317
  // This matches Python's behavior where process() always receives
@@ -201,38 +1321,378 @@ export class NodeActor {
201
1321
  inputs = {
202
1322
  ...(this.node.properties ?? {}),
203
1323
  ...(this.node.dynamic_properties ?? {}),
204
- ...inputs
1324
+ ...this._appendStaticItems(inputs)
205
1325
  };
206
1326
  }
1327
+ inputs = this._applyDynamicSlots(inputs);
207
1328
  // Inject _control_context for controller nodes (Python parity:
208
1329
  // process_streaming_node_with_inputs / _is_controller / _build_control_context)
209
1330
  if (this._controlContext) {
210
1331
  inputs = { ...inputs, _control_context: this._controlContext };
211
1332
  }
212
- log.info("Executing node", {
1333
+ // Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
1334
+ (this._executionsLogged === 0 ? log.info : log.debug)("Executing node", {
213
1335
  nodeId: this.node.id,
214
1336
  type: this.node.type,
215
- syncMode: this.node.sync_mode ?? "on_any",
216
- inputHandles: Object.keys(inputs)
1337
+ inputHandles: Object.keys(inputs),
1338
+ invocation: this._executionsLogged + 1
217
1339
  });
1340
+ this._executionsLogged += 1;
1341
+ this._currentInvocationLineage = this._computeInvocationLineage();
218
1342
  if (this.node.is_streaming_output && this._executor.genProcess) {
1343
+ await this._executeStreaming(inputs);
1344
+ return;
1345
+ }
1346
+ const outputs = await this._invokeWithRecovery(inputs, () => this._executor.process(inputs, this._executionContext));
1347
+ if (outputs === SKIPPED)
1348
+ return;
1349
+ this._latestResult = outputs;
1350
+ await this._sendOutputs(this.node.id, outputs, this._currentHints(Object.keys(outputs)));
1351
+ // Site #1 (RFC §5): correlated process() — one per ready key, so N/run
1352
+ // for a generator (the primary 6×-collapse fix).
1353
+ this._emitGenerationComplete(outputs, inputs);
1354
+ }
1355
+ /**
1356
+ * The streaming-output invocation, with its own recovery rules.
1357
+ *
1358
+ * Frames are routed inside the generator loop, so "retry" only means
1359
+ * something before the first emit — after that the coherent choices are
1360
+ * ending the stream (keeping what was produced) or failing. Design §5.4.
1361
+ */
1362
+ async _executeStreaming(inputs) {
1363
+ for (let attempt = 1;; attempt++) {
1364
+ const account = createInvocationAccount();
1365
+ let emitted = false;
219
1366
  this._streamingCollectedOutputs = {};
220
- for await (const partial of this._executor.genProcess(inputs, this._executionContext)) {
221
- const routed = this._filterStreamingPartial(partial);
222
- if (Object.keys(routed).length === 0)
223
- continue;
224
- Object.assign(this._streamingCollectedOutputs, routed);
225
- this._latestResult = { ...this._streamingCollectedOutputs };
226
- await this._sendOutputs(this.node.id, routed);
1367
+ try {
1368
+ await inInvocationAccount(account, async () => {
1369
+ for await (const partial of this._executor.genProcess(inputs, this._executionContext)) {
1370
+ emitted = (await this._routeStreamingFrame(partial)) || emitted;
1371
+ }
1372
+ });
1373
+ }
1374
+ catch (err) {
1375
+ if (err instanceof RoutingError)
1376
+ throw err.cause;
1377
+ if (!this._supervisor) {
1378
+ if (!this._degradeOnContentFilter(err, emitted))
1379
+ throw err;
1380
+ await this._skipInvocation();
1381
+ return;
1382
+ }
1383
+ const verdict = await this._escalate(err, inputs, attempt, account, {
1384
+ streamingOutput: true,
1385
+ streamingInput: false,
1386
+ emitted
1387
+ });
1388
+ switch (verdict.action) {
1389
+ case "retry":
1390
+ continue;
1391
+ case "skip":
1392
+ await this._skipInvocation();
1393
+ return;
1394
+ case "end_stream":
1395
+ this._completeOutputSlots();
1396
+ this._latestResult = { ...(this._streamingCollectedOutputs ?? {}) };
1397
+ // `end_stream` keeps what the stream produced, so the invocation
1398
+ // committed — it just committed early. Skipping the commit marker
1399
+ // would hide those outputs from replay and asset autosave, which
1400
+ // is the "silent data loss dressed as success" the PRD forbids.
1401
+ this._emitGenerationComplete(this._latestResult, inputs);
1402
+ return;
1403
+ default:
1404
+ throw err;
1405
+ }
227
1406
  }
228
1407
  this._latestResult = { ...(this._streamingCollectedOutputs ?? {}) };
1408
+ // Site #4 (RFC §5): genProcess stream-end — ONCE per stream, carrying the
1409
+ // overwrite-merged _streamingCollectedOutputs. Per-yield partials stay on
1410
+ // output_update (chunks); multi-artifact-per-output-slot streaming is OUT
1411
+ // OF SCOPE (RFC §5 invariant / Decision 1 corollary). Under correlation
1412
+ // this branch runs once per ready key → one generation_complete per key.
1413
+ this._emitGenerationComplete(this._latestResult, inputs);
1414
+ return;
1415
+ }
1416
+ }
1417
+ /**
1418
+ * The streaming-input invocation. A `run()` node drains its own inbox and may
1419
+ * have consumed messages long before it threw, across arbitrary lineages —
1420
+ * nothing is replayable and there is no single lineage for a skip to target.
1421
+ * So the verdict set here is exactly `end_stream` · `fail`. Design §5.4.
1422
+ */
1423
+ async _runStreamingInput(nodeInputs, nodeOutputs) {
1424
+ const account = createInvocationAccount();
1425
+ try {
1426
+ await inInvocationAccount(account, () => this._executor.run(nodeInputs, nodeOutputs, this._executionContext));
1427
+ }
1428
+ catch (err) {
1429
+ if (err instanceof RoutingError)
1430
+ throw err.cause;
1431
+ if (!this._supervisor)
1432
+ throw err;
1433
+ const verdict = await this._escalate(err, {}, 1, account, {
1434
+ streamingOutput: false,
1435
+ streamingInput: true,
1436
+ emitted: true
1437
+ });
1438
+ if (verdict.action !== "end_stream")
1439
+ throw err;
1440
+ this._completeOutputSlots();
229
1441
  }
230
- else {
231
- const outputs = await this._executor.process(inputs, this._executionContext);
232
- this._latestResult = outputs;
233
- await this._sendOutputs(this.node.id, outputs);
1442
+ }
1443
+ /** Route one yielded frame. Returns true when anything went downstream. */
1444
+ async _routeStreamingFrame(partial) {
1445
+ const routed = this._filterStreamingPartial(partial);
1446
+ if (Object.keys(routed).length === 0)
1447
+ return false;
1448
+ // Strip actor-reserved `index` from iteration groups before routing
1449
+ // (the actor mints the token index; node code is migrating away from
1450
+ // supplying it). §1 — under the correlation scheduler this becomes
1451
+ // a validation error after migration; for now we warn-and-overwrite.
1452
+ const overrides = this._mintIterationFrameOverrides(routed);
1453
+ this._streamingCollectedOutputs ??= {};
1454
+ Object.assign(this._streamingCollectedOutputs, routed);
1455
+ if (overrides)
1456
+ Object.assign(this._streamingCollectedOutputs, overrides);
1457
+ const emit = overrides ? { ...routed, ...overrides } : routed;
1458
+ this._latestResult = { ...this._streamingCollectedOutputs };
1459
+ await this._route(emit, this._currentHints(Object.keys(emit)));
1460
+ return true;
1461
+ }
1462
+ /**
1463
+ * Route values downstream, tagging any failure as a routing failure so the
1464
+ * recovery loops let it through instead of escalating a delivery problem as
1465
+ * if the node had failed.
1466
+ */
1467
+ async _route(outputs, hints) {
1468
+ try {
1469
+ await this._sendOutputs(this.node.id, outputs, hints);
1470
+ }
1471
+ catch (err) {
1472
+ throw new RoutingError(err);
234
1473
  }
235
1474
  }
1475
+ /**
1476
+ * Close every output slot, keeping whatever the stream already emitted —
1477
+ * the `end_stream` verdict. Slots come from the node's declared outputs,
1478
+ * falling back to what the stream actually produced.
1479
+ */
1480
+ _completeOutputSlots() {
1481
+ const declared = Object.keys(this.node.outputs ?? {});
1482
+ const slots = declared.length
1483
+ ? declared
1484
+ : Object.keys(this._streamingCollectedOutputs ?? {});
1485
+ for (const slot of slots) {
1486
+ this._signalSlotEos?.(this.node.id, slot || "output");
1487
+ }
1488
+ }
1489
+ /**
1490
+ * For each iteration group present in `frame`, mint or reuse a token. If
1491
+ * the frame supplies an `index` value for a group that has an `index`
1492
+ * sibling handle declared, overwrite it with the actor-minted index. §1.
1493
+ *
1494
+ * Returns the override map (only the slots that needed mutation) or null
1495
+ * when no iteration groups are in play.
1496
+ */
1497
+ _mintIterationFrameOverrides(frame) {
1498
+ if (!this._correlation)
1499
+ return null;
1500
+ const declared = this.node.output_correlation;
1501
+ if (!declared)
1502
+ return null;
1503
+ const invocationScope = this._correlation.invocationScope;
1504
+ const parentKey = invocationScope.length && this._currentInvocationLineage
1505
+ ? projectLineageKey(this._currentInvocationLineage, invocationScope)
1506
+ : "";
1507
+ // Collect groups whose handles appear in the frame.
1508
+ const groupHandles = new Map(); // group root → handles
1509
+ for (const handle of Object.keys(frame)) {
1510
+ const corr = declared[handle];
1511
+ if (!corr || corr.kind !== "iteration")
1512
+ continue;
1513
+ const root = iterationRootId(this.node.id, handle, corr.group);
1514
+ let arr = groupHandles.get(root);
1515
+ if (!arr) {
1516
+ arr = [];
1517
+ groupHandles.set(root, arr);
1518
+ }
1519
+ arr.push(handle);
1520
+ }
1521
+ if (groupHandles.size === 0)
1522
+ return null;
1523
+ // Each frame mints fresh tokens; clear last frame's bookkeeping.
1524
+ this._lastMintedFrameTokens.clear();
1525
+ const overrides = {};
1526
+ for (const [root, handles] of groupHandles) {
1527
+ const index = this._mintIterationToken(root, parentKey);
1528
+ for (const handle of handles) {
1529
+ if (handle === "index") {
1530
+ overrides[handle] = index;
1531
+ }
1532
+ }
1533
+ // Stash the minted token so _correlatedOutputLineage reuses it.
1534
+ this._lastMintedFrameTokens.set(root, index);
1535
+ }
1536
+ return Object.keys(overrides).length > 0 ? overrides : null;
1537
+ }
1538
+ /** Tokens minted for the most recent frame, reused by output lineage. */
1539
+ _lastMintedFrameTokens = new Map();
1540
+ /**
1541
+ * Atomically route a frame of values across multiple slots, minting one
1542
+ * shared token per iteration group so sibling handles in the same group
1543
+ * (e.g. Zip's `left` and `right`) end up as one logical item downstream.
1544
+ * §1, §7.
1545
+ *
1546
+ * Algorithm:
1547
+ * 1. Walk every slot in `values` and resolve its `output_correlation`.
1548
+ * 2. For each iteration group present in this frame, mint exactly one
1549
+ * token (per (root, parent_key)) and remember it for the duration of
1550
+ * this emit.
1551
+ * 3. Build a per-slot lineage map that attaches the same token to every
1552
+ * sibling handle in a group. Non-iteration slots inherit the
1553
+ * caller-supplied lineage (or the actor's invocation lineage).
1554
+ * 4. Hand the whole frame to `_sendOutputs` in one call so the runner
1555
+ * routes them as a single atomic delivery.
1556
+ */
1557
+ async _emitGroup(values, callerLineage) {
1558
+ const declared = this.node.output_correlation ?? {};
1559
+ const parentLineage = callerLineage ?? this._computeInvocationLineage() ?? EMPTY_LINEAGE;
1560
+ const parentKey = this._correlation
1561
+ ? projectLineageKey(parentLineage, this._correlation.invocationScope)
1562
+ : "";
1563
+ const groupTokens = new Map(); // root -> minted index
1564
+ const perSlotLineage = {};
1565
+ for (const slot of Object.keys(values)) {
1566
+ const corr = declared[slot];
1567
+ if (corr?.kind === "iteration") {
1568
+ const root = iterationRootId(this.node.id, slot, corr.group);
1569
+ let index = groupTokens.get(root);
1570
+ if (index === undefined) {
1571
+ index = this._mintIterationToken(root, parentKey);
1572
+ groupTokens.set(root, index);
1573
+ }
1574
+ perSlotLineage[slot] = { ...parentLineage, [root]: { index } };
1575
+ }
1576
+ else {
1577
+ perSlotLineage[slot] = parentLineage;
1578
+ }
1579
+ }
1580
+ await this._sendOutputs(this.node.id, values, {
1581
+ invocationLineage: parentLineage,
1582
+ perSlotLineage
1583
+ });
1584
+ }
1585
+ /**
1586
+ * For `aggregate(innermost)` outputs, drop the collapsed root from the
1587
+ * inherited lineage so the emitted envelope sits at the parent scope.
1588
+ * The static analyzer drops the root from the output scope at graph load;
1589
+ * this is the runtime mirror.
1590
+ *
1591
+ * Returns the rewritten lineage, or `undefined` when no collapse applies.
1592
+ */
1593
+ _maybeCollapseForSlot(slot, hints) {
1594
+ const corr = this.node.output_correlation?.[slot];
1595
+ if (!corr || corr.kind !== "aggregate")
1596
+ return undefined;
1597
+ if (corr.collapse !== "innermost")
1598
+ return undefined;
1599
+ if (!this._correlation)
1600
+ return undefined;
1601
+ // The source input handle's scope ends with the root to collapse.
1602
+ const sourceInput = this._correlation.inputs.get(corr.source);
1603
+ if (!sourceInput || sourceInput.scope.length === 0)
1604
+ return undefined;
1605
+ const collapsed = sourceInput.scope[sourceInput.scope.length - 1];
1606
+ const base = hints.invocationLineage ?? EMPTY_LINEAGE;
1607
+ if (!(collapsed in base))
1608
+ return base;
1609
+ const out = { ...base };
1610
+ delete out[collapsed];
1611
+ return out;
1612
+ }
1613
+ /**
1614
+ * For stream-mode iteration outputs (e.g. `Zip.pair`), mint a fresh token
1615
+ * whenever `outputs.emit()` is called without an explicit lineage. Each
1616
+ * emit is a logical item, so the token advances per call. Sibling-handle
1617
+ * reuse within a single frame is handled by genProcess via
1618
+ * `_mintIterationFrameOverrides`, or by `outputs.emitGroup()` in stream
1619
+ * mode — see `_emitGroup` above.
1620
+ */
1621
+ _maybeMintForSlot(slot, hints) {
1622
+ const corr = this.node.output_correlation?.[slot];
1623
+ if (!corr || corr.kind !== "iteration")
1624
+ return undefined;
1625
+ const root = iterationRootId(this.node.id, slot, corr.group);
1626
+ const parentLineage = hints.invocationLineage ?? EMPTY_LINEAGE;
1627
+ const parentKey = this._correlation
1628
+ ? projectLineageKey(parentLineage, this._correlation.invocationScope)
1629
+ : "";
1630
+ const index = this._mintIterationToken(root, parentKey);
1631
+ return { ...parentLineage, [root]: { index } };
1632
+ }
1633
+ /**
1634
+ * For each outgoing edge that consumes `slot`, send `signalLineageDone` to
1635
+ * the downstream inbox with the envelope's projected key. §5/§6.
1636
+ */
1637
+ async _propagateLineageDone(slot, lineage) {
1638
+ // The actor doesn't know the downstream inbox map directly; the runner
1639
+ // owns _sendOutputs. We extend the routing channel by passing a sentinel
1640
+ // value with `__lineage_done__` metadata so the runner can dispatch it.
1641
+ await this._sendOutputs(this.node.id, { [slot]: undefined }, {
1642
+ perSlotLineage: { [slot]: lineage },
1643
+ lineageDoneSlots: new Set([slot])
1644
+ });
1645
+ }
1646
+ /**
1647
+ * True while `_runCorrelated` is the active execution path.
1648
+ */
1649
+ _inCorrelatedBuffered = false;
1650
+ /**
1651
+ * Build routing hints for the current invocation.
1652
+ *
1653
+ * When correlation analysis is available and the invocation emitted handles,
1654
+ * the actor mints per-slot lineage for those outputs and pairs it with the
1655
+ * invocation lineage. Otherwise it forwards just the invocation lineage,
1656
+ * which the runner applies to outputs that inherit the invocation scope.
1657
+ * Returns undefined when no invocation lineage is known.
1658
+ */
1659
+ _currentHints(emittedHandles) {
1660
+ if (this._currentInvocationLineage === undefined)
1661
+ return undefined;
1662
+ if (this._correlation && emittedHandles && emittedHandles.length > 0) {
1663
+ const perSlot = this._correlatedOutputLineage(this._currentInvocationLineage, emittedHandles);
1664
+ if (perSlot) {
1665
+ return {
1666
+ invocationLineage: this._currentInvocationLineage,
1667
+ perSlotLineage: perSlot
1668
+ };
1669
+ }
1670
+ }
1671
+ return { invocationLineage: this._currentInvocationLineage };
1672
+ }
1673
+ /**
1674
+ * Compute the invocation lineage for the current set of consumed
1675
+ * envelopes. Returns undefined when the case is ambiguous.
1676
+ *
1677
+ * In correlated buffered mode the lineage comes from the correlation
1678
+ * scheduler. Otherwise the lineage is taken from the sole consumed data
1679
+ * envelope when exactly one non-control, non-list data handle was consumed;
1680
+ * any other arity is ambiguous and yields undefined.
1681
+ *
1682
+ * The map is NOT cleared here so that streaming-input nodes that emit
1683
+ * multiple times per consumed envelope continue to inherit lineage on
1684
+ * every emit. Buffered gather paths overwrite envelopes per handle on
1685
+ * each iteration, which naturally tracks the latest consumed envelope.
1686
+ */
1687
+ _computeInvocationLineage() {
1688
+ if (this._correlation && this._inCorrelatedBuffered) {
1689
+ return this._correlatedInvocationLineage();
1690
+ }
1691
+ const dataHandles = [...this._lastEnvelopes.keys()].filter((h) => h !== "__control__" && !this._listInputHandles.has(h));
1692
+ if (dataHandles.length !== 1)
1693
+ return undefined;
1694
+ return this._lastEnvelopes.get(dataHandles[0])?.correlation_lineage;
1695
+ }
236
1696
  /**
237
1697
  * Controlled execution: wait for control events on __control__ handle.
238
1698
  *
@@ -243,7 +1703,7 @@ export class NodeActor {
243
1703
  */
244
1704
  async _runControlled() {
245
1705
  // Identify data handles (non-control) that need to be populated
246
- const dataHandles = [...this.inbox["_buffers"].keys()].filter((h) => h !== "__control__");
1706
+ const dataHandles = this.inbox.handles().filter((h) => h !== "__control__");
247
1707
  // Wait for all data handles to have at least one value before
248
1708
  // processing the first control event. This ensures that when an
249
1709
  // upstream node feeds data into the controlled node, the data
@@ -264,15 +1724,19 @@ export class NodeActor {
264
1724
  // Merge node properties as defaults (matching _executeWithInputs behavior)
265
1725
  const baseProps = this.node.properties ?? {};
266
1726
  const dynProps = this.node.dynamic_properties ?? {};
267
- const merged = {
1727
+ const merged = this._applyDynamicSlots({
268
1728
  ...baseProps,
269
1729
  ...dynProps,
270
- ...inputs,
1730
+ ...this._appendStaticItems(inputs),
271
1731
  ...this._currentControlProperties
272
- };
273
- const outputs = await this._executor.process(merged, this._executionContext);
1732
+ });
1733
+ const outputs = await this._invokeWithRecovery(merged, () => this._executor.process(merged, this._executionContext));
1734
+ if (outputs === SKIPPED)
1735
+ continue;
274
1736
  this._latestResult = outputs;
275
1737
  await this._sendOutputs(this.node.id, outputs);
1738
+ // Site #2 (RFC §5): controlled-loop process() — one per "run" event.
1739
+ this._emitGenerationComplete(outputs);
276
1740
  }
277
1741
  }
278
1742
  }
@@ -293,128 +1757,135 @@ export class NodeActor {
293
1757
  this._cacheBufferedDataInputs();
294
1758
  return;
295
1759
  }
296
- // Drain items until all data handles have at least one value
297
- for await (const [handle, item] of this.inbox.iterAny()) {
298
- if (handle === "__control__") {
299
- // Push control events back – they'll be consumed by iterInput later
300
- this.inbox.prepend("__control__", {
301
- data: item,
302
- metadata: {},
303
- timestamp: Date.now(),
304
- event_id: ""
305
- });
306
- continue;
1760
+ // Drain items until every data handle has a value. A handle whose upstream
1761
+ // sources have all closed with nothing buffered can never be satisfied, so
1762
+ // drop it from `pending` and let the node's declared default apply —
1763
+ // mirroring how `_runCorrelatedImpl` treats a closed empty-scope handle.
1764
+ // Without this the wait blocks forever whenever an upstream completes
1765
+ // without emitting on a data handle (filter/conditional output), stranding
1766
+ // held control events and hanging any controller awaiting sendControlEvent.
1767
+ //
1768
+ // A close wakes the inbox's internal waiters but yields no envelope, so this
1769
+ // is a manual loop over `tryPopAnyWithEnvelope()` + `waitForActivity()`
1770
+ // rather than a for-await: the pruning below must re-run on a closure that
1771
+ // arrives while blocked.
1772
+ //
1773
+ // Control events that arrive first are held aside and re-queued after the
1774
+ // wait: prepending them back while still iterating would make the very next
1775
+ // pop return the same event again — an unbounded microtask spin that
1776
+ // starves the event loop and blocks the upstream data put() forever.
1777
+ const heldControlEvents = [];
1778
+ for (;;) {
1779
+ for (const handle of [...pending]) {
1780
+ if (!this.inbox.isOpen(handle) && !this.inbox.hasBuffered(handle)) {
1781
+ pending.delete(handle);
1782
+ }
307
1783
  }
308
- if (!this._cachedInputs)
309
- this._cachedInputs = {};
310
- this._cachedInputs[handle] = item;
311
- pending.delete(handle);
312
1784
  if (pending.size === 0)
313
1785
  break;
314
- }
315
- }
316
- /**
317
- * Drain all buffered data (non-control) inputs and cache them.
318
- * Called before each controlled execution to pick up any data that
319
- * arrived while waiting for the next control event.
320
- */
321
- _cacheBufferedDataInputs() {
322
- const buffers = this.inbox["_buffers"];
323
- for (const [handle, buf] of buffers) {
324
- if (handle === "__control__" || buf.length === 0)
325
- continue;
326
- // Use the latest buffered value for each data handle
327
- while (buf.length > 0) {
328
- const envelope = buf.shift();
1786
+ const popped = this.inbox.tryPopAnyWithEnvelope();
1787
+ if (popped) {
1788
+ const [handle, envelope] = popped;
1789
+ if (handle === "__control__") {
1790
+ heldControlEvents.push(envelope);
1791
+ continue;
1792
+ }
329
1793
  if (!this._cachedInputs)
330
1794
  this._cachedInputs = {};
331
1795
  this._cachedInputs[handle] = envelope.data;
1796
+ pending.delete(handle);
1797
+ continue;
332
1798
  }
1799
+ // Nothing left to pop. A closed inbox accepts no further writes, so the
1800
+ // still-pending handles can never be satisfied — stop waiting and let the
1801
+ // node's declared defaults apply, mirroring the iterators' `_closed`
1802
+ // check. Without this a cancelled run parks here forever: `closeAll()`
1803
+ // leaves `_openCounts` untouched, so the pruning above never fires.
1804
+ if (this.inbox.isClosed())
1805
+ break;
1806
+ await this.inbox.waitForActivity();
1807
+ }
1808
+ // Re-queue held control events at the front, preserving arrival order,
1809
+ // so iterInput("__control__") consumes them next.
1810
+ for (let i = heldControlEvents.length - 1; i >= 0; i--) {
1811
+ this.inbox.prepend("__control__", heldControlEvents[i]);
333
1812
  }
334
1813
  }
335
- // -----------------------------------------------------------------------
336
- // Input gathering (sync modes)
337
- // -----------------------------------------------------------------------
338
1814
  /**
339
- * zip_all: wait until every registered handle has at least one item,
340
- * using "sticky" semantics for handles that have no more upstream.
1815
+ * Drain all buffered data (non-control) inputs and cache them.
1816
+ * Called before each controlled execution to pick up any data that
1817
+ * arrived while waiting for the next control event.
341
1818
  */
342
- _stickyValues = {};
343
- async _gatherZipAll() {
344
- const handles = [...this.inbox["_buffers"].keys()].filter((h) => h !== "__control__");
345
- if (handles.length === 0)
346
- return null;
347
- const result = {};
348
- let gotNew = false;
349
- for (const handle of handles) {
350
- if (this.inbox.hasBuffered(handle)) {
351
- const popped = this._popHandle(handle);
352
- if (popped !== undefined) {
353
- result[handle] = popped;
354
- this._stickyValues[handle] = popped;
355
- gotNew = true;
356
- continue;
357
- }
358
- }
359
- // Use sticky value if handle is closed or marked sticky from streaming analysis
360
- const isSticky = !this.inbox.isOpen(handle) || this._initialStickyHandles.has(handle);
361
- if (isSticky && handle in this._stickyValues) {
362
- result[handle] = this._stickyValues[handle];
1819
+ _cacheBufferedDataInputs() {
1820
+ for (const handle of this.inbox.handles()) {
1821
+ if (handle === "__control__")
363
1822
  continue;
364
- }
365
- // Handle still open but no data yet – wait
366
- if (this.inbox.isOpen(handle)) {
367
- const gen = this.inbox.iterInput(handle);
368
- const next = await gen.next();
369
- if (next.done) {
370
- // EOS – use sticky if available
371
- if (handle in this._stickyValues) {
372
- result[handle] = this._stickyValues[handle];
373
- continue;
374
- }
375
- return null; // no sticky, no data
376
- }
377
- result[handle] = next.value;
378
- this._stickyValues[handle] = next.value;
379
- gotNew = true;
380
- await gen.return(undefined);
1823
+ // Use the latest buffered value for each data handle. drainHandle()
1824
+ // (unlike popping the raw buffer) releases backpressure on producers
1825
+ // blocked in put() and keeps the arrival queue consistent.
1826
+ const drained = this.inbox.drainHandle(handle);
1827
+ if (drained.length === 0)
381
1828
  continue;
382
- }
383
- // Handle closed, no sticky
384
- if (!(handle in this._stickyValues)) {
385
- return null;
386
- }
387
- result[handle] = this._stickyValues[handle];
1829
+ if (!this._cachedInputs)
1830
+ this._cachedInputs = {};
1831
+ this._cachedInputs[handle] = drained[drained.length - 1].data;
388
1832
  }
389
- if (!gotNew)
390
- return null; // all sticky, no new data
391
- return result;
392
- }
393
- /**
394
- * Pop a single item from a specific handle's buffer.
395
- */
396
- _popHandle(handle) {
397
- const buf = this.inbox["_buffers"].get(handle);
398
- if (!buf || buf.length === 0)
399
- return undefined;
400
- const envelope = buf.shift();
401
- return envelope.data;
402
1833
  }
403
1834
  // -----------------------------------------------------------------------
404
1835
  // Status helpers
405
1836
  // -----------------------------------------------------------------------
406
- _emitNodeStatus(status, result, error) {
407
- this._emitMessage({
1837
+ _emitNodeStatus(status, result, error, errorDetail) {
1838
+ const head = {
408
1839
  type: "node_update",
409
1840
  node_id: this.node.id,
410
1841
  node_name: this.node.name ?? this.node.type,
411
1842
  node_type: this.node.type,
412
1843
  status,
413
1844
  result: result ?? null,
414
- error: error ?? null,
415
- properties: this.node.properties && typeof this.node.properties === "object"
1845
+ error: error ?? null
1846
+ };
1847
+ const tail = {
1848
+ properties: isObjectValue(this.node.properties)
416
1849
  ? this.node.properties
417
- : null
1850
+ : null,
1851
+ provider_cost: this._executionContext?.getProviderCost?.() ?? null
1852
+ };
1853
+ // Omitted (not null) when absent: every consumer treats a missing
1854
+ // detail as "no structured cause", and the reliability goldens pin
1855
+ // the node_update wire shape for ordinary runs.
1856
+ this._emitMessage(errorDetail
1857
+ ? { ...head, error_detail: errorDetail, ...tail }
1858
+ : { ...head, ...tail });
1859
+ }
1860
+ /**
1861
+ * Emit a BARE `generation_complete` for one committed `process()` result
1862
+ * (RFC §4.2 / §5). Routes through the same `_emitMessage` path as
1863
+ * `node_update` (runner `_emit`), so it is NEVER edge-suppressed and is
1864
+ * retained for replay. The actor stamps NO `job_id` and NO `index` — both
1865
+ * are backfilled downstream by the relay (RFC Decision 8).
1866
+ *
1867
+ * Skips `nodetool.constant.*` / `nodetool.input.*` (the same set
1868
+ * `_emitNodeStatus`'s `skipResult` rule covers): those nodes have no
1869
+ * generation. List-valued results are carried as-is — no per-element
1870
+ * fan-out happens in the actor (RFC Decision 1).
1871
+ */
1872
+ _emitGenerationComplete(outputs, inputs) {
1873
+ if (this.node.type.startsWith("nodetool.constant.") ||
1874
+ this.node.type.startsWith("nodetool.input.")) {
1875
+ return;
1876
+ }
1877
+ this._emitMessage({
1878
+ type: "generation_complete",
1879
+ node_id: this.node.id,
1880
+ node_name: this.node.name ?? this.node.type,
1881
+ node_type: this.node.type,
1882
+ outputs,
1883
+ // Resolved inputs (prompt, seed, model, …) ride along so the relay can
1884
+ // persist them into auto-saved asset metadata. Filtered to scalars plus
1885
+ // model references to keep the event small — binary refs and every other
1886
+ // nested object are dropped.
1887
+ properties: inputs ? scalarInputProperties(inputs) : null
1888
+ // NO job_id, NO index — the runner relay stamps them downstream.
418
1889
  });
419
1890
  }
420
1891
  _filterStreamingPartial(partial) {