@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
@@ -0,0 +1,64 @@
1
+ /** Queued messages allowed to pile up before the stream gives up. */
2
+ export const DEFAULT_MESSAGE_BUFFER_LIMIT = 10_000;
3
+ export class MessageStream {
4
+ queue = [];
5
+ waiter = null;
6
+ closed = false;
7
+ overflowedAt = null;
8
+ limit;
9
+ unsubscribe;
10
+ /** `limit` of 0 (or a negative number) means unbounded. */
11
+ constructor(context, limit = DEFAULT_MESSAGE_BUFFER_LIMIT) {
12
+ this.limit = limit > 0 ? limit : Number.POSITIVE_INFINITY;
13
+ this.unsubscribe = context.addMessageListener((message) => {
14
+ if (this.queue.length >= this.limit) {
15
+ if (this.overflowedAt === null) {
16
+ this.overflowedAt = this.queue.length;
17
+ this.unsubscribe();
18
+ }
19
+ return;
20
+ }
21
+ this.queue.push(message);
22
+ this.wake();
23
+ });
24
+ }
25
+ wake() {
26
+ const w = this.waiter;
27
+ this.waiter = null;
28
+ w?.();
29
+ }
30
+ /** Stop feeding new messages into the queue. Already-queued messages still drain. */
31
+ close() {
32
+ if (this.closed)
33
+ return;
34
+ this.closed = true;
35
+ this.unsubscribe();
36
+ this.wake();
37
+ }
38
+ async *[Symbol.asyncIterator]() {
39
+ for (;;) {
40
+ // Drain batches so a large backlog does not shift an array per message.
41
+ const batch = this.queue.splice(0);
42
+ for (const message of batch) {
43
+ yield message;
44
+ }
45
+ if (this.overflowedAt !== null) {
46
+ throw new Error(`Workflow message stream overflowed after ${this.overflowedAt} ` +
47
+ `queued messages (limit ${this.limit}) — the consumer fell behind, ` +
48
+ "so messages past that point were dropped rather than retained. " +
49
+ "Iterate `session.messages` as the run progresses, or raise " +
50
+ "`limits.messageBufferLimit`.");
51
+ }
52
+ // Messages can arrive (and the stream can close) while the consumer
53
+ // holds a yield above. Drain them before deciding to stop or wait.
54
+ if (this.queue.length > 0)
55
+ continue;
56
+ if (this.closed)
57
+ return;
58
+ await new Promise((resolve) => {
59
+ this.waiter = resolve;
60
+ });
61
+ }
62
+ }
63
+ }
64
+ //# sourceMappingURL=message-stream.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"message-stream.js","sourceRoot":"","sources":["../src/message-stream.ts"],"names":[],"mappings":"AAcA,qEAAqE;AACrE,MAAM,CAAC,MAAM,4BAA4B,GAAG,MAAM,CAAC;AAEnD,MAAM,OAAO,aAAa;IACP,KAAK,GAAwB,EAAE,CAAC;IACzC,MAAM,GAAwB,IAAI,CAAC;IACnC,MAAM,GAAG,KAAK,CAAC;IACf,YAAY,GAAkB,IAAI,CAAC;IAC1B,KAAK,CAAS;IACd,WAAW,CAAa;IAEzC,2DAA2D;IAC3D,YACE,OAIC,EACD,KAAK,GAAG,4BAA4B;QAEpC,IAAI,CAAC,KAAK,GAAG,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,iBAAiB,CAAC;QAC1D,IAAI,CAAC,WAAW,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAAC,OAAO,EAAE,EAAE;YACxD,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC;gBACpC,IAAI,IAAI,CAAC,YAAY,KAAK,IAAI,EAAE,CAAC;oBAC/B,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC;oBACtC,IAAI,CAAC,WAAW,EAAE,CAAC;gBACrB,CAAC;gBACD,OAAO;YACT,CAAC;YACD,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;YACzB,IAAI,CAAC,IAAI,EAAE,CAAC;QACd,CAAC,CAAC,CAAC;IACL,CAAC;IAEO,IAAI;QACV,MAAM,CAAC,GAAG,IAAI,CAAC,MAAM,CAAC;QACtB,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC;QACnB,CAAC,EAAE,EAAE,CAAC;IACR,CAAC;IAED,qFAAqF;IACrF,KAAK;QACH,IAAI,IAAI,CAAC,MAAM;YAAE,OAAO;QACxB,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC;QACnB,IAAI,CAAC,WAAW,EAAE,CAAC;QACnB,IAAI,CAAC,IAAI,EAAE,CAAC;IACd,CAAC;IAED,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,aAAa,CAAC;QAC3B,SAAS,CAAC;YACR,wEAAwE;YACxE,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;YACnC,KAAK,MAAM,OAAO,IAAI,KAAK,EAAE,CAAC;gBAC5B,MAAM,OAAO,CAAC;YAChB,CAAC;YACD,IAAI,IAAI,CAAC,YAAY,KAAK,IAAI,EAAE,CAAC;gBAC/B,MAAM,IAAI,KAAK,CACb,4CAA4C,IAAI,CAAC,YAAY,GAAG;oBAC9D,0BAA0B,IAAI,CAAC,KAAK,gCAAgC;oBACpE,iEAAiE;oBACjE,6DAA6D;oBAC7D,8BAA8B,CACjC,CAAC;YACJ,CAAC;YACD,oEAAoE;YACpE,mEAAmE;YACnE,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC;gBAAE,SAAS;YACpC,IAAI,IAAI,CAAC,MAAM;gBAAE,OAAO;YACxB,MAAM,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,EAAE;gBAClC,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC;YACxB,CAAC,CAAC,CAAC;QACL,CAAC;IACH,CAAC;CACF"}
@@ -0,0 +1,8 @@
1
+ /**
2
+ * The workspace's named type predicates, re-exported for the runner's call
3
+ * sites. The definitions live in `@nodetool-ai/protocol`.
4
+ */
5
+ export { isBoolean, isCallable, isNonEmptyString, isNumber, isString,
6
+ /** An object value. Arrays pass — the sites that care test `Array.isArray`. */
7
+ isObjectLike as isObjectValue } from "@nodetool-ai/protocol";
8
+ //# sourceMappingURL=predicates.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"predicates.d.ts","sourceRoot":"","sources":["../src/predicates.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EACL,SAAS,EACT,UAAU,EACV,gBAAgB,EAChB,QAAQ,EACR,QAAQ;AACR,+EAA+E;AAC/E,YAAY,IAAI,aAAa,EAC9B,MAAM,uBAAuB,CAAC"}
@@ -0,0 +1,8 @@
1
+ /**
2
+ * The workspace's named type predicates, re-exported for the runner's call
3
+ * sites. The definitions live in `@nodetool-ai/protocol`.
4
+ */
5
+ export { isBoolean, isCallable, isNonEmptyString, isNumber, isString,
6
+ /** An object value. Arrays pass — the sites that care test `Array.isArray`. */
7
+ isObjectLike as isObjectValue } from "@nodetool-ai/protocol";
8
+ //# sourceMappingURL=predicates.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"predicates.js","sourceRoot":"","sources":["../src/predicates.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EACL,SAAS,EACT,UAAU,EACV,gBAAgB,EAChB,QAAQ,EACR,QAAQ;AACR,+EAA+E;AAC/E,YAAY,IAAI,aAAa,EAC9B,MAAM,uBAAuB,CAAC"}
@@ -0,0 +1,65 @@
1
+ /**
2
+ * What a supervisor may read about a run in flight.
3
+ *
4
+ * The design's two supervisor tools (`get_run_state`, `read_node_output`) are
5
+ * pull-based on purpose: the runner already holds this state, so there is no
6
+ * observation pipeline to feed and a clean run costs nothing. This module is
7
+ * the read side of that — the runner implements it, the agent package consumes
8
+ * it, and the dependency arrow stays `kernel ← agents`.
9
+ *
10
+ * See docs/workflow-supervisor-design.md §6.
11
+ */
12
+ /** Per-node summary in the run digest. */
13
+ export interface NodeRunState {
14
+ nodeId: string;
15
+ nodeType: string;
16
+ /**
17
+ * `pending` — spawned, nothing emitted yet; `running` — emitted at least
18
+ * once and still live; `completed` / `failed` — the actor is gone.
19
+ */
20
+ status: "pending" | "running" | "completed" | "failed";
21
+ /** Invocations that produced output. */
22
+ emissions: number;
23
+ /** Escalations raised by this node so far, including the current one. */
24
+ escalations: number;
25
+ /** The node's terminal error, once it has one. Redacted at construction. */
26
+ error?: string;
27
+ }
28
+ export interface RunStateDigest {
29
+ jobId: string;
30
+ nodes: NodeRunState[];
31
+ /** Provider spend recorded for the whole run so far, in USD. */
32
+ costUsd: number;
33
+ }
34
+ /** One node's recorded output for a single invocation. */
35
+ export interface NodeOutputRead {
36
+ nodeId: string;
37
+ /** The lineage the recorded invocation ran under, as `root=index` pairs. */
38
+ lineage: string[];
39
+ outputs: Record<string, unknown>;
40
+ }
41
+ /**
42
+ * Read-only view of a run, handed to a `SupervisorHandle` when the run starts.
43
+ */
44
+ export interface RunStateReader {
45
+ digest(): RunStateDigest;
46
+ /**
47
+ * The most recent output of `nodeId` on an invocation causally related to
48
+ * `lineage` — same fan-out roots, same indices. A sibling item's output is
49
+ * not related to the failing one, so it is refused (`null`) rather than
50
+ * handed over as repair material. Design §6.
51
+ */
52
+ readOutput(nodeId: string, lineage: readonly string[]): NodeOutputRead | null;
53
+ }
54
+ /**
55
+ * Whether `recorded` belongs to the same causal branch as `lineage`.
56
+ *
57
+ * A producer upstream of the failing invocation ran under a lineage that is a
58
+ * subset of it: every fan-out root it carries also appears downstream, with the
59
+ * same index. Two conditions therefore refuse a read — an index that disagrees
60
+ * (a sibling item) and a root the failing invocation never entered (an
61
+ * unrelated fan-out). An empty recorded lineage is a single-fire node, which is
62
+ * upstream of everything.
63
+ */
64
+ export declare function lineageRelated(recorded: readonly string[], lineage: readonly string[]): boolean;
65
+ //# sourceMappingURL=run-state.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run-state.d.ts","sourceRoot":"","sources":["../src/run-state.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,0CAA0C;AAC1C,MAAM,WAAW,YAAY;IAC3B,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;IACjB;;;OAGG;IACH,MAAM,EAAE,SAAS,GAAG,SAAS,GAAG,WAAW,GAAG,QAAQ,CAAC;IACvD,wCAAwC;IACxC,SAAS,EAAE,MAAM,CAAC;IAClB,yEAAyE;IACzE,WAAW,EAAE,MAAM,CAAC;IACpB,4EAA4E;IAC5E,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,cAAc;IAC7B,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,YAAY,EAAE,CAAC;IACtB,gEAAgE;IAChE,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,0DAA0D;AAC1D,MAAM,WAAW,cAAc;IAC7B,MAAM,EAAE,MAAM,CAAC;IACf,4EAA4E;IAC5E,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAClC;AAED;;GAEG;AACH,MAAM,WAAW,cAAc;IAC7B,MAAM,IAAI,cAAc,CAAC;IACzB;;;;;OAKG;IACH,UAAU,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,SAAS,MAAM,EAAE,GAAG,cAAc,GAAG,IAAI,CAAC;CAC/E;AAED;;;;;;;;;GASG;AACH,wBAAgB,cAAc,CAC5B,QAAQ,EAAE,SAAS,MAAM,EAAE,EAC3B,OAAO,EAAE,SAAS,MAAM,EAAE,GACzB,OAAO,CAeT"}
@@ -0,0 +1,42 @@
1
+ /**
2
+ * What a supervisor may read about a run in flight.
3
+ *
4
+ * The design's two supervisor tools (`get_run_state`, `read_node_output`) are
5
+ * pull-based on purpose: the runner already holds this state, so there is no
6
+ * observation pipeline to feed and a clean run costs nothing. This module is
7
+ * the read side of that — the runner implements it, the agent package consumes
8
+ * it, and the dependency arrow stays `kernel ← agents`.
9
+ *
10
+ * See docs/workflow-supervisor-design.md §6.
11
+ */
12
+ /**
13
+ * Whether `recorded` belongs to the same causal branch as `lineage`.
14
+ *
15
+ * A producer upstream of the failing invocation ran under a lineage that is a
16
+ * subset of it: every fan-out root it carries also appears downstream, with the
17
+ * same index. Two conditions therefore refuse a read — an index that disagrees
18
+ * (a sibling item) and a root the failing invocation never entered (an
19
+ * unrelated fan-out). An empty recorded lineage is a single-fire node, which is
20
+ * upstream of everything.
21
+ */
22
+ export function lineageRelated(recorded, lineage) {
23
+ if (recorded.length === 0)
24
+ return true;
25
+ const scope = new Map();
26
+ for (const pair of lineage) {
27
+ const eq = pair.indexOf("=");
28
+ if (eq === -1)
29
+ continue;
30
+ scope.set(pair.slice(0, eq), pair.slice(eq + 1));
31
+ }
32
+ for (const pair of recorded) {
33
+ const eq = pair.indexOf("=");
34
+ if (eq === -1)
35
+ return false;
36
+ const root = pair.slice(0, eq);
37
+ if (scope.get(root) !== pair.slice(eq + 1))
38
+ return false;
39
+ }
40
+ return true;
41
+ }
42
+ //# sourceMappingURL=run-state.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run-state.js","sourceRoot":"","sources":["../src/run-state.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAgDH;;;;;;;;;GASG;AACH,MAAM,UAAU,cAAc,CAC5B,QAA2B,EAC3B,OAA0B;IAE1B,IAAI,QAAQ,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,IAAI,CAAC;IACvC,MAAM,KAAK,GAAG,IAAI,GAAG,EAAkB,CAAC;IACxC,KAAK,MAAM,IAAI,IAAI,OAAO,EAAE,CAAC;QAC3B,MAAM,EAAE,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;QAC7B,IAAI,EAAE,KAAK,CAAC,CAAC;YAAE,SAAS;QACxB,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC;IACnD,CAAC;IACD,KAAK,MAAM,IAAI,IAAI,QAAQ,EAAE,CAAC;QAC5B,MAAM,EAAE,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;QAC7B,IAAI,EAAE,KAAK,CAAC,CAAC;YAAE,OAAO,KAAK,CAAC;QAC5B,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;QAC/B,IAAI,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,IAAI,CAAC,KAAK,CAAC,EAAE,GAAG,CAAC,CAAC;YAAE,OAAO,KAAK,CAAC;IAC3D,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC"}
package/dist/runner.d.ts CHANGED
@@ -13,9 +13,37 @@
13
13
  * - Control event dispatch.
14
14
  * - Completion detection.
15
15
  */
16
- import type { NodeDescriptor, Edge, ProcessingMessage, ControlEvent } from "@nodetool-ai/protocol";
16
+ import type { NodeDescriptor, HydratedGraphData, ProcessingMessage, ControlEvent, CorrelationLineage, Intervention } from "@nodetool-ai/protocol";
17
+ import type { SupervisorHandle } from "./supervisor.js";
17
18
  import type { ProcessingContext } from "@nodetool-ai/runtime";
18
19
  import { type NodeExecutor } from "./actor.js";
20
+ /**
21
+ * Hints from the actor about how to route an invocation's outputs.
22
+ *
23
+ * `invocationLineage` is applied to outputs that inherit the invocation scope.
24
+ * `perSlotLineage` overrides it per slot (e.g. minted iteration lineage or
25
+ * `outputs.forward()` calls). `lineageDoneSlots` marks slots the node dropped,
26
+ * for which the runner sends `signalLineageDone` instead of a value.
27
+ */
28
+ export interface OutputRoutingHints {
29
+ /** Lineage carried by the consumed envelope when the node had exactly one. */
30
+ invocationLineage?: CorrelationLineage;
31
+ /** Explicit per-slot lineage overrides (e.g. from outputs.forward). */
32
+ perSlotLineage?: Record<string, CorrelationLineage>;
33
+ /**
34
+ * Slots being dropped for the given lineage. The runner sends
35
+ * `signalLineageDone` to downstream inboxes for these slots instead of
36
+ * delivering a value. §5.
37
+ */
38
+ lineageDoneSlots?: Set<string>;
39
+ /**
40
+ * A supervisor `skip` verdict: this invocation produced nothing. The runner
41
+ * sends `lineage_done` on every outgoing data edge at `invocationLineage`,
42
+ * *and* `lineage_scope_closed` for every child root the invocation would have
43
+ * opened. Design §5.2.
44
+ */
45
+ skipInvocation?: boolean;
46
+ }
19
47
  /**
20
48
  * Issue reported by a node validator. Mirrors the shape of
21
49
  * `@nodetool-ai/node-sdk`'s `NodePropertyValidationIssue`, redeclared here to
@@ -43,6 +71,19 @@ export interface RunJobRequest {
43
71
  params?: Record<string, unknown>;
44
72
  /** Optional parent workflow ID for sub-graph execution. */
45
73
  parent_id?: string;
74
+ /**
75
+ * Wake-up payload for a trigger-driven run. Mirrors
76
+ * `@nodetool-ai/protocol`'s `RunJobRequest.trigger_event`, redeclared here
77
+ * (like {@link NodeValidationIssue}) to avoid a circular dependency. When
78
+ * present, propagated onto `WorkflowRunnerOptions.executionContext` as
79
+ * `triggerEvent` at the start of the run so actors can read it via
80
+ * `ProcessingContext`.
81
+ */
82
+ trigger_event?: {
83
+ node_id: string;
84
+ payload: unknown;
85
+ input_id: string;
86
+ };
46
87
  }
47
88
  export interface WorkflowRunnerOptions {
48
89
  /**
@@ -63,6 +104,27 @@ export interface WorkflowRunnerOptions {
63
104
  * a callback compatible with this signature.
64
105
  */
65
106
  validateNode?: NodeValidator;
107
+ /**
108
+ * Strict mode (docs/RELIABILITY_ARCHITECTURE.md §12: "strict mode is a
109
+ * kernel flag, not a fork"). Default `false` (advisory-only, current
110
+ * behavior).
111
+ *
112
+ * When `true`, the checks that are otherwise logged as advisory warnings —
113
+ * `_checkPendingInboxWork` finding undelivered messages, a controlled node
114
+ * completing with pending `sendControlEvent` responses still unresolved,
115
+ * and `_drainActiveEdges` finding an edge still buffered/open after the
116
+ * graph settled — throw an `Error` instead. The error is caught by the
117
+ * same top-level handler that reports node/graph failures, so a strict
118
+ * violation surfaces as `RunResult.status === "failed"` with a message
119
+ * naming every offending node/edge, exactly like any other run failure.
120
+ */
121
+ strict?: boolean;
122
+ /**
123
+ * Turns a failing node invocation into a decision instead of a dead run.
124
+ * Absent — the default — means no escalation is ever constructed and the run
125
+ * behaves exactly as it does today. See docs/workflow-supervisor-design.md.
126
+ */
127
+ supervisor?: SupervisorHandle;
66
128
  }
67
129
  export interface RunResult {
68
130
  /** Outputs collected from output nodes, keyed by node name/id. */
@@ -73,6 +135,13 @@ export interface RunResult {
73
135
  status: "completed" | "failed" | "cancelled";
74
136
  /** Error message if status is 'failed'. */
75
137
  error?: string;
138
+ /**
139
+ * Every supervisor escalation and the verdict it received, in order. A
140
+ * completed run with a non-empty list is "Completed — supervised": a derived
141
+ * display state, not a fifth status, so existing `status` consumers keep
142
+ * working.
143
+ */
144
+ interventions?: Intervention[];
76
145
  }
77
146
  export declare class WorkflowRunner {
78
147
  readonly jobId: string;
@@ -82,10 +151,14 @@ export declare class WorkflowRunner {
82
151
  private _inboxes;
83
152
  /** Per-edge message counters (for EdgeUpdate tracking). */
84
153
  private _edgeCounters;
85
- /** Per-edge streaming flag (true if on a streaming path). */
86
- private _streamingEdges;
87
- /** Control edges that have routed at least one event (used for diagnostics). */
88
- private _controlEdgesRouted;
154
+ /** Per-edge timestamp of the last emitted edge_update (throttling). */
155
+ private _edgeCounterLastEmitMs;
156
+ /** Edges whose counter advanced since their last emitted edge_update. */
157
+ private _edgeCounterDirty;
158
+ /**
159
+ * Static correlation analysis result. Always populated before actors run.
160
+ */
161
+ private _correlation;
89
162
  /**
90
163
  * Multi-edge list inputs: nodeId → set of handles that aggregate
91
164
  * multiple edges into a list.
@@ -97,8 +170,95 @@ export declare class WorkflowRunner {
97
170
  private _messages;
98
171
  /** Cancellation flag. */
99
172
  private _cancelled;
100
- /** Pending response resolvers for sendControlEvent. nodeId → resolver */
173
+ /**
174
+ * Actors spawned and not yet finished (including their completion
175
+ * handling). Exposed via {@link liveActorCount} for leak accounting — after
176
+ * a run this must be back to zero, and a harness that can't measure it
177
+ * can't assert it.
178
+ */
179
+ private _liveActors;
180
+ /** Node ids of actors still running; read by quiescence detection. */
181
+ private _liveActorIds;
182
+ /**
183
+ * Outgoing data edges of streaming input nodes that `finishInputStream`
184
+ * has not closed yet. While any is open, values can still arrive from
185
+ * outside the graph, so the graph is never quiescent.
186
+ */
187
+ private _openExternalStreamEdges;
188
+ /** Schedules a quiescence check; set only for graphs with a Loop node. */
189
+ private _scheduleQuiescenceCheck;
190
+ /**
191
+ * Latch set by `cancel()` and never cleared by `_resetRunState`. A cancel
192
+ * that lands between construction and `run()` would otherwise be dropped —
193
+ * the reset clears `_cancelled` and swaps the AbortController. `_runImpl`
194
+ * re-applies this latch after the reset so such a run terminates as
195
+ * "cancelled". §17.
196
+ */
197
+ private _cancelRequested;
198
+ /**
199
+ * True while a run is in flight. A second concurrent `run()` on the same
200
+ * instance would clobber all shared run state, so `_runImpl` rejects it. §17.
201
+ */
202
+ private _running;
203
+ /**
204
+ * Job id used for `edge_update` emissions during a run. Captured from
205
+ * `request.job_id` at the start of `_runImpl` so edge updates and
206
+ * `job_update` messages carry the same id; before a run starts it defaults
207
+ * to the constructor id. §16.
208
+ */
209
+ private _effectiveJobId;
210
+ /** Run-level cancellation signal source; aborted by `cancel()`. */
211
+ private _abortController;
212
+ /**
213
+ * Pending response resolvers for sendControlEvent, FIFO per node. The
214
+ * controlled actor processes control events in order and emits outputs in
215
+ * order, so the oldest waiter matches the next output. A single slot per
216
+ * node would let a burst of concurrent control events (e.g. parallel agent
217
+ * tool calls) overwrite an earlier resolver, leaving its promise unsettled
218
+ * forever.
219
+ */
101
220
  private _pendingControlResponses;
221
+ /**
222
+ * Executor instance per node. Resolved once and reused so that the
223
+ * instance initialized in _initializeGraph is the same one that executes
224
+ * (NodeRegistry.resolve constructs a fresh instance per call).
225
+ */
226
+ private _executors;
227
+ /**
228
+ * Nodes whose actor has finished running. A control event sent to such a
229
+ * node can never be answered (the actor's run loop is gone), so
230
+ * sendControlEvent rejects instead of registering a promise that hangs
231
+ * forever. This guards against an agent dispatching a burst of control
232
+ * tool calls where the controlled node errors (and terminates) partway
233
+ * through.
234
+ */
235
+ private _completedNodes;
236
+ /** Errors reported by node actors, keyed by node id. */
237
+ private _nodeErrors;
238
+ /**
239
+ * Edge ids whose source has already been marked done on the target inbox.
240
+ * `markSourceDone` decrements an upstream counter, so marking the same edge
241
+ * twice would over-decrement and could prematurely close a handle that still
242
+ * has other open upstreams. Early per-slot EOS (`outputs.complete`) and the
243
+ * final `_sendEOS` both guard against double-marking via this set.
244
+ */
245
+ private _eosSentEdges;
246
+ /** Supervisor escalations and their verdicts, in decision order. */
247
+ private _interventions;
248
+ /**
249
+ * Last output of each node per invocation lineage, for `read_node_output`.
250
+ * Only populated on a supervised run — an unsupervised one keeps nothing.
251
+ * Bounded per node: a 10k-item fan-out must not become a 10k-entry cache.
252
+ */
253
+ private _recordedOutputs;
254
+ /** Undefined on an unsupervised run, so its `RunResult` is unchanged. */
255
+ private _recordedInterventions;
256
+ /**
257
+ * The handle every escalation actually goes through: whatever the caller
258
+ * configured, under the kernel's bounds. Nothing else in the runner reads
259
+ * `_options.supervisor`.
260
+ */
261
+ private readonly _supervisor;
102
262
  constructor(jobId: string, options: WorkflowRunnerOptions);
103
263
  /**
104
264
  * Push a streaming input value into the graph while it is running.
@@ -111,16 +271,43 @@ export declare class WorkflowRunner {
111
271
  finishInputStream(inputName: string, sourceHandle?: string): void;
112
272
  /**
113
273
  * Execute a workflow graph.
274
+ *
275
+ * Requires hydrated descriptors: the actor trusts the behavior flags
276
+ * (`is_streaming_input` & co.) to pick the execution mode, so accepting a
277
+ * raw wire graph here would silently run streaming nodes as one-shot
278
+ * process() calls. Hydrate via `Graph.loadFromDict`, node-sdk's
279
+ * `hydrateGraphNodeFlags(graph, registry)`, or — for graphs constructed in
280
+ * code where the author sets the flags — `withExplicitNodeFlags`.
114
281
  */
115
- run(request: RunJobRequest, graphData: {
116
- nodes: NodeDescriptor[];
117
- edges: Edge[];
118
- }): Promise<RunResult>;
282
+ run(request: RunJobRequest, graphData: HydratedGraphData): Promise<RunResult>;
119
283
  private _runImpl;
120
284
  private _resetRunState;
121
285
  /**
122
- * Cancel the running workflow.
286
+ * The read-only view a supervisor gets of the run in flight. Built from
287
+ * state the runner already holds, so a run without a supervisor pays for
288
+ * none of it. See docs/workflow-supervisor-design.md §6.
289
+ */
290
+ private _runStateReader;
291
+ private _runStateDigest;
292
+ private _readRecordedOutput;
293
+ /**
294
+ * Remember what a node emitted, keyed by the invocation's lineage, so a
295
+ * supervisor can read a producer's output while deciding a consumer's
296
+ * failure. Off unless the run is supervised.
297
+ */
298
+ private _recordNodeOutput;
299
+ /** Actors spawned and not yet finished. Zero before and after a run. */
300
+ get liveActorCount(): number;
301
+ /** Control-event responses still waiting on an actor, summed over nodes. */
302
+ get pendingControlResponseCount(): number;
303
+ /**
304
+ * Push property updates into a running node's executor instance (live
305
+ * parameter changes — e.g. turning a synth knob while the patch plays).
306
+ * Returns true when the node's executor exists and supports live updates;
307
+ * false is not an error — the caller's canvas state already holds the new
308
+ * value for the next run.
123
309
  */
310
+ updateNodeProperties(nodeId: string, properties: Record<string, unknown>): boolean;
124
311
  cancel(): void;
125
312
  /**
126
313
  * Remove edges whose source or target node doesn't exist in the graph.
@@ -133,7 +320,23 @@ export declare class WorkflowRunner {
133
320
  * Aggregates issues across nodes and throws a single GraphValidationError.
134
321
  */
135
322
  private _validateNodes;
323
+ /** Refuse to start when a required workflow input has no supplied value. */
324
+ private _validateRequiredInputs;
325
+ /**
326
+ * Initialize every node's executor before any actor runs.
327
+ *
328
+ * A failure here aborts the run before `_processGraph`, so the actors that
329
+ * would normally call `finalize()` never start. Finalize the executors that
330
+ * did initialize, otherwise whatever they opened (python bridge handles,
331
+ * provider clients, file descriptors) leaks for the lifetime of the process.
332
+ * The failure is also re-thrown with the offending node's identity attached —
333
+ * a bare "connect ECONNREFUSED" gives no clue which node to fix.
334
+ */
136
335
  private _initializeGraph;
336
+ /** Finalize executors, never letting one failure hide another. */
337
+ private _finalizeExecutors;
338
+ /** Resolve (and cache) the executor instance for a node. */
339
+ private _resolveExecutor;
137
340
  private _initializeInboxes;
138
341
  private _detectMultiEdgeListInputs;
139
342
  /**
@@ -141,6 +344,14 @@ export declare class WorkflowRunner {
141
344
  * After delivery, mark them as done (EOS) since input nodes produce exactly
142
345
  * one value.
143
346
  */
347
+ /** Variable-channel name a Set Variable node publishes to (its `name` prop). */
348
+ private _variableChannelName;
349
+ /**
350
+ * Tell the context how many Set Variable writers each channel has, before any
351
+ * actor runs. A channel with no writers then closes on first read so readers
352
+ * (Get Variable streams, Prompt awaits) end cleanly instead of hanging.
353
+ */
354
+ private _registerVariableChannels;
144
355
  private _dispatchInputs;
145
356
  /**
146
357
  * Spawn one NodeActor per node and run them concurrently.
@@ -148,12 +359,56 @@ export declare class WorkflowRunner {
148
359
  * upstream actors produce data.
149
360
  */
150
361
  private _processGraph;
362
+ /**
363
+ * Detect a quiescent graph for Loop nodes (docs/workflow-loops.md).
364
+ *
365
+ * A loop body can finish an iteration without feeding anything back (an
366
+ * `If` routes the value elsewhere, a filter drops it). EOS cannot announce
367
+ * that, because the body's EOS waits for the loop to close. So when every
368
+ * live actor is parked on its inbox, no external stream is open, and some
369
+ * inbox activity happened since the last notice, each Loop is told the
370
+ * graph is quiescent and ends the runs still waiting for feedback. A parked
371
+ * actor is not inside a provider call, a timer, or a write, so nothing can
372
+ * still produce the value those runs wait for.
373
+ *
374
+ * Installed only for graphs that contain a Loop node.
375
+ */
376
+ private _installQuiescenceDetection;
151
377
  /**
152
378
  * Route output values from a node to downstream inboxes.
153
379
  * For control edges: route control events to the __control__ handle.
154
380
  * For data edges: route to the named target handle.
155
381
  */
156
382
  private _sendMessages;
383
+ /**
384
+ * A supervisor `skip`: retire one invocation's outputs without emitting.
385
+ *
386
+ * Plain non-emission is not enough. Siblings already buffered against the
387
+ * skipped key would sit at a downstream join forever, and an invocation of an
388
+ * iteration node would have opened child scopes an aggregate is waiting to
389
+ * see closed. So both signals go out on every outgoing data edge: the
390
+ * per-lineage `lineage_done` that unblocks joins, and a `lineage_scope_closed`
391
+ * per child root the invocation could have minted. Design §5.2.
392
+ */
393
+ private _skipInvocationOutputs;
394
+ /**
395
+ * Mark the source of one data edge done on its target inbox at most once.
396
+ * `markSourceDone` decrements an upstream counter, so calling it twice for
397
+ * the same edge would over-decrement and could prematurely close a handle
398
+ * that still has other open upstreams. Both early per-slot EOS
399
+ * (`_signalSlotEos`) and the final `_sendEOS` route through this guard.
400
+ * Returns true if the mark was applied (first time), false if skipped.
401
+ */
402
+ private _markEdgeSourceDoneOnce;
403
+ /**
404
+ * Signal early end-of-stream for a single output slot of a node, in
405
+ * response to `outputs.complete(slot)`. Marks every outgoing edge of
406
+ * `(nodeId, slot)` done on its target inbox immediately, rather than
407
+ * waiting for the actor to finish. Idempotent with `_sendEOS` via the
408
+ * `_eosSentEdges` guard so a handle's upstream count is never
409
+ * double-decremented.
410
+ */
411
+ private _signalSlotEos;
157
412
  /**
158
413
  * Signal EOS on all outgoing edges of a completed node.
159
414
  * For control edges: close the __control__ handle of the target.
@@ -181,17 +436,46 @@ export declare class WorkflowRunner {
181
436
  */
182
437
  sendControlEvent(targetNodeId: string, properties: Record<string, unknown>): Promise<Record<string, unknown>>;
183
438
  private _incrementEdgeCounter;
439
+ /**
440
+ * Emit the final counter for every edge whose count advanced past its last
441
+ * throttled edge_update, so the badge ends on the exact total. Called from
442
+ * _drainActiveEdges (which runs on completion, cancellation and error).
443
+ */
444
+ private _flushEdgeCounters;
184
445
  /**
185
446
  * Post a "drained" EdgeUpdate for any edge whose target handle still has
186
447
  * buffered items or open upstream sources. Called during post-completion
187
448
  * cleanup to ensure front-end consumers stop listening to streams and
188
449
  * clear any spinners.
450
+ *
451
+ * Returns the ids of edges found in that leftover state — §6's "zero
452
+ * pending work" is violated whenever this is non-empty after a normal
453
+ * (non-error) completion. The caller decides what strict mode does with
454
+ * that list; this method's own emit-and-continue behavior never changes,
455
+ * since it also runs on the error/cancellation cleanup path where a
456
+ * partial graph is expected to have open edges.
189
457
  */
190
458
  private _drainActiveEdges;
191
- private _edgeKey;
192
- private _analyzeStreaming;
193
- /** Returns true if the given edge is on a streaming path. */
194
- edgeStreams(edge: Edge): boolean;
459
+ /**
460
+ * Strict-mode gate for `_drainActiveEdges`'s findings (§12). Split out from
461
+ * its one call site (the success path in `_runImpl`, right after
462
+ * `_processGraph`) so it is unit-testable without a full graph run: in
463
+ * practice any leftover edge state this reports was already caught by the
464
+ * node-level `_checkPendingInboxWork` gate inside `_processGraph` (an
465
+ * inbox's `hasPendingWork()` covers every handle, edge-targeted ones
466
+ * included) and would have thrown before this method is ever reached —
467
+ * this gate exists for the state `_checkPendingInboxWork` cannot see (e.g.
468
+ * a driver that calls `_drainActiveEdges` directly after bypassing
469
+ * `_processGraph`) and as a second line of defense should that ordering
470
+ * ever change.
471
+ *
472
+ * A cancelled run, or one with node errors, legitimately
473
+ * leaves edges mid-flight — that is what the drain reports to the
474
+ * frontend in every mode. Only a run that is otherwise clean but still has
475
+ * leftover edge state is a §6 violation ("zero pending work" after a
476
+ * normal completion).
477
+ */
478
+ private _enforceCleanEdgeDrain;
195
479
  private _checkPendingInboxWork;
196
480
  private _isOutputNode;
197
481
  /**
@@ -200,6 +484,19 @@ export declare class WorkflowRunner {
200
484
  */
201
485
  private _isExternalInputNode;
202
486
  private _getExternalInputName;
487
+ /**
488
+ * Key a terminal node's outputs are collected under.
489
+ *
490
+ * DSL-authored graphs carry the public name in the Output node's `name`
491
+ * *property* (`output({ name: "hook", value })`) — the descriptor's
492
+ * top-level `name` is absent, and the auto-generated node id (`output`,
493
+ * `output_2`, …) is all that would remain. Promote the property for
494
+ * output-typed nodes so a run's outputs are keyed by the name the author
495
+ * asked for. Mirrors `_getExternalInputName` on the input side and the
496
+ * websocket runner's `require_terminal_result` rewrite; gating on
497
+ * `nodetool.output.` keeps other terminal sinks keyed by id.
498
+ */
499
+ private _outputCollectionKey;
203
500
  private _emit;
204
501
  private _resolveInputNodes;
205
502
  /**