@nodetool-ai/kernel 0.8.8 → 0.8.9-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/dist/.nodetool-build-stamp +1 -1
  2. package/dist/actor.d.ts +1 -479
  3. package/dist/actor.d.ts.map +1 -1
  4. package/dist/actor.js +1 -1911
  5. package/dist/actor.js.map +1 -1
  6. package/dist/correlation-analysis.d.ts +1 -103
  7. package/dist/correlation-analysis.d.ts.map +1 -1
  8. package/dist/correlation-analysis.js +1 -845
  9. package/dist/correlation-analysis.js.map +1 -1
  10. package/dist/durable-inbox.d.ts +1 -90
  11. package/dist/durable-inbox.d.ts.map +1 -1
  12. package/dist/durable-inbox.js +1 -210
  13. package/dist/durable-inbox.js.map +1 -1
  14. package/dist/dynamic-slots.d.ts +1 -72
  15. package/dist/dynamic-slots.d.ts.map +1 -1
  16. package/dist/dynamic-slots.js +1 -191
  17. package/dist/dynamic-slots.js.map +1 -1
  18. package/dist/edge-ids.d.ts +1 -10
  19. package/dist/edge-ids.d.ts.map +1 -1
  20. package/dist/edge-ids.js +1 -14
  21. package/dist/edge-ids.js.map +1 -1
  22. package/dist/graph-utils.d.ts +1 -71
  23. package/dist/graph-utils.d.ts.map +1 -1
  24. package/dist/graph-utils.js +1 -283
  25. package/dist/graph-utils.js.map +1 -1
  26. package/dist/graph.d.ts +1 -203
  27. package/dist/graph.d.ts.map +1 -1
  28. package/dist/graph.js +1 -867
  29. package/dist/graph.js.map +1 -1
  30. package/dist/inbox.d.ts +1 -264
  31. package/dist/inbox.d.ts.map +1 -1
  32. package/dist/inbox.js +1 -551
  33. package/dist/inbox.js.map +1 -1
  34. package/dist/index.d.ts +1 -19
  35. package/dist/index.d.ts.map +1 -1
  36. package/dist/index.js +1 -19
  37. package/dist/index.js.map +1 -1
  38. package/dist/io.d.ts +1 -188
  39. package/dist/io.d.ts.map +1 -1
  40. package/dist/io.js +1 -238
  41. package/dist/io.js.map +1 -1
  42. package/dist/loop.d.ts +1 -35
  43. package/dist/loop.d.ts.map +1 -1
  44. package/dist/loop.js +1 -165
  45. package/dist/loop.js.map +1 -1
  46. package/dist/message-stream.d.ts +1 -31
  47. package/dist/message-stream.d.ts.map +1 -1
  48. package/dist/message-stream.js +1 -63
  49. package/dist/message-stream.js.map +1 -1
  50. package/dist/predicates.d.ts +1 -7
  51. package/dist/predicates.d.ts.map +1 -1
  52. package/dist/predicates.js +1 -7
  53. package/dist/predicates.js.map +1 -1
  54. package/dist/run-state.d.ts +1 -64
  55. package/dist/run-state.d.ts.map +1 -1
  56. package/dist/run-state.js +1 -41
  57. package/dist/run-state.js.map +1 -1
  58. package/dist/runner.d.ts +1 -523
  59. package/dist/runner.d.ts.map +1 -1
  60. package/dist/runner.js +1 -2126
  61. package/dist/runner.js.map +1 -1
  62. package/dist/substitute-validator.d.ts +1 -43
  63. package/dist/substitute-validator.d.ts.map +1 -1
  64. package/dist/substitute-validator.js +1 -168
  65. package/dist/substitute-validator.js.map +1 -1
  66. package/dist/supervisor.d.ts +1 -147
  67. package/dist/supervisor.d.ts.map +1 -1
  68. package/dist/supervisor.js +1 -286
  69. package/dist/supervisor.js.map +1 -1
  70. package/dist/trigger-wakeup.d.ts +1 -122
  71. package/dist/trigger-wakeup.d.ts.map +1 -1
  72. package/dist/trigger-wakeup.js +1 -220
  73. package/dist/trigger-wakeup.js.map +1 -1
  74. package/package.json +4 -4
@@ -1,287 +1,2 @@
1
- /**
2
- * Workflow Supervisor — the kernel half.
3
- *
4
- * A failing node invocation raises an `Escalation`; a `SupervisorHandle`
5
- * returns a `Verdict`. The kernel defines the interface, computes the set of
6
- * verdicts an escalation may legally receive, redacts everything the escalation
7
- * carries, and enforces the allowed set against whatever the handle returns.
8
- * The LLM-backed implementation lives in `@nodetool-ai/agents`; the dependency
9
- * arrow stays `kernel ← agents`.
10
- *
11
- * See docs/workflow-supervisor-design.md §5.
12
- */
13
- import { isBoolean, isNonEmptyString, isNumber, isObjectValue, isString } from "./predicates.js";
14
- /**
15
- * The default, and what every failure of a supervisor degrades to: today's
16
- * behavior. A runner without a supervisor never constructs an escalation at
17
- * all, so this exists for callers that want the seam wired but inert.
18
- */
19
- export class FailClosedHandle {
20
- async decide() {
21
- return { verdict: { action: "fail" }, decidedBy: "default" };
22
- }
23
- close() { }
24
- }
25
- // ---------------------------------------------------------------------------
26
- // Redaction
27
- // ---------------------------------------------------------------------------
28
- /**
29
- * Field names whose values never leave the actor, whatever they contain.
30
- * Matched case-insensitively against whole names and name fragments, so
31
- * `authorization`, `Auth-Token`, and `api_key` all hit.
32
- */
33
- const SENSITIVE_NAME_PATTERN = /(password|passwd|secret|token|api[-_]?key|apikey|authorization|auth|credential|private[-_]?key|session[-_]?id|cookie|bearer)/i;
34
- const MASK = "«redacted»";
35
- /** Per-value cap on redacted payloads. Truncation is size, not safety. */
36
- export const MAX_ESCALATION_VALUE_CHARS = 2000;
37
- /**
38
- * Mask every known secret value inside a string, wherever it appears —
39
- * headers, URLs, bodies, stringified errors.
40
- */
41
- function maskSecrets(text, secrets) {
42
- let out = text;
43
- for (const secret of secrets) {
44
- if (!secret)
45
- continue;
46
- out = out.split(secret).join(MASK);
47
- }
48
- return out;
49
- }
50
- function truncate(text) {
51
- return text.length > MAX_ESCALATION_VALUE_CHARS
52
- ? `${text.slice(0, MAX_ESCALATION_VALUE_CHARS)}…[truncated]`
53
- : text;
54
- }
55
- export function redactValue(value, secrets, depth = 0) {
56
- if (value === null || value === undefined)
57
- return value;
58
- if (isString(value))
59
- return truncate(maskSecrets(value, secrets));
60
- if (isNumber(value) || isBoolean(value)) {
61
- return value;
62
- }
63
- if (depth >= 6)
64
- return MASK;
65
- if (Array.isArray(value)) {
66
- return value
67
- .slice(0, 100)
68
- .map((item) => redactValue(item, secrets, depth + 1));
69
- }
70
- if (isObjectValue(value)) {
71
- const proto = Object.getPrototypeOf(value);
72
- if (proto === Object.prototype || proto === null) {
73
- const out = {};
74
- for (const [key, item] of Object.entries(value)) {
75
- out[key] = SENSITIVE_NAME_PATTERN.test(key)
76
- ? MASK
77
- : redactValue(item, secrets, depth + 1);
78
- }
79
- return out;
80
- }
81
- if (value instanceof Uint8Array)
82
- return `«${value.byteLength} bytes»`;
83
- }
84
- return truncate(maskSecrets(String(value), secrets));
85
- }
86
- export function redactRecord(record, secrets) {
87
- const out = {};
88
- for (const [key, value] of Object.entries(record)) {
89
- if (key.startsWith("_"))
90
- continue; // actor-internal, e.g. _control_context
91
- out[key] = SENSITIVE_NAME_PATTERN.test(key)
92
- ? MASK
93
- : redactValue(value, secrets);
94
- }
95
- return out;
96
- }
97
- // ---------------------------------------------------------------------------
98
- // Failure signatures
99
- // ---------------------------------------------------------------------------
100
- /**
101
- * A signature is a stable categorical code — an HTTP status, a provider error
102
- * code, a validation path. It is what lets one verdict resolve the other six
103
- * identical failures in a 200-item batch without waking the agent again.
104
- *
105
- * A plain `Error` gets none. Error class alone is not a category (every generic
106
- * throw would collide), and message text carries request-specific values, so
107
- * matching on it would make one item's verdict stick to an unrelated failure.
108
- * No signature simply means no stickiness: each such failure escalates on its
109
- * own.
110
- */
111
- export function failureSignature(err) {
112
- if (!isObjectValue(err))
113
- return undefined;
114
- const e = err;
115
- if (isNonEmptyString(e.code))
116
- return `code:${e.code}`;
117
- const status = isNumber(e.status)
118
- ? e.status
119
- : isNumber(e.statusCode)
120
- ? e.statusCode
121
- : isNumber(e.response?.status)
122
- ? e.response.status
123
- : undefined;
124
- if (status !== undefined)
125
- return `http:${status}`;
126
- if (isString(e.errno) || isNumber(e.errno)) {
127
- return `errno:${e.errno}`;
128
- }
129
- return undefined;
130
- }
131
- /**
132
- * The kernel's answer to "what may this escalation legally receive". It shapes
133
- * the agent's verdict schema *and* is enforced independently by the actor: the
134
- * schema is UX, this is the guarantee.
135
- *
136
- * Design §5.3 (retry safety) and §5.4 (streaming).
137
- */
138
- export function computeAllowedActions(input) {
139
- // A `run()` node consumed inbox messages that are gone, across arbitrary
140
- // lineages — nothing is replayable and no single lineage exists for a skip
141
- // to target. Design §5.4.
142
- if (input.streamingInput)
143
- return ["end_stream", "fail"];
144
- const retryOk = input.retrySafe && input.spentCostUsd === 0 && !input.createdAssets;
145
- if (input.streamingOutput) {
146
- if (input.emitted)
147
- return ["end_stream", "fail"];
148
- // No `substitute` for a stream in either state: there is no single
149
- // invocation value for a substitution to stand in for.
150
- return retryOk ? ["retry", "skip", "fail"] : ["skip", "fail"];
151
- }
152
- const actions = [];
153
- if (retryOk)
154
- actions.push("retry");
155
- if (input.hasCandidateOutput && input.validatorCoverage) {
156
- actions.push("substitute");
157
- }
158
- actions.push("skip", "fail");
159
- return actions;
160
- }
161
- export const DEFAULT_SUPERVISOR_BOUNDS = {
162
- maxDecisions: 10,
163
- maxRetriesPerNode: 2,
164
- decisionTimeoutMs: 60_000
165
- };
166
- /**
167
- * Wraps a handle with everything that must hold whoever wrote it: decision and
168
- * retry ceilings, a per-decision timeout derived from the run signal, and the
169
- * sticky-verdict cache. Every boundary resolves as `fail` — degradation is
170
- * deterministic, never a cheaper model.
171
- */
172
- export class BoundedHandle {
173
- bounded = true;
174
- _inner;
175
- _bounds;
176
- _decisions = 0;
177
- _retries = new Map();
178
- /** `(nodeId, failureSignature)` → verdict, for `skip`/`fail` only. */
179
- _sticky = new Map();
180
- /** Serializes decisions: the agent sees consecutive failures in order. */
181
- _queue = Promise.resolve();
182
- constructor(inner, opts = {}) {
183
- this._inner = inner;
184
- this._bounds = { ...DEFAULT_SUPERVISOR_BOUNDS, ...stripUndefined(opts) };
185
- }
186
- attach(reader) {
187
- this._inner.attach?.(reader);
188
- }
189
- async decide(e, signal) {
190
- const run = this._queue.then(() => this._decideSerial(e, signal));
191
- // Keep the chain alive even when one decision rejects; `_decideSerial`
192
- // never throws, but a handle replaced in a test could.
193
- this._queue = run.catch(() => undefined);
194
- return run;
195
- }
196
- async _decideSerial(e, runSignal) {
197
- if (e.failureSignature !== undefined) {
198
- const hit = this._sticky.get(stickyKey(e));
199
- // A cached verdict is only a shortcut for a decision this escalation
200
- // could have received anyway. Replaying one the escalation does not
201
- // allow buys nothing: the actor overrules it to `fail`. Decide afresh.
202
- if (hit && e.allowedActions.includes(hit.action)) {
203
- return { verdict: hit, decidedBy: "sticky" };
204
- }
205
- }
206
- if (this._decisions >= this._bounds.maxDecisions) {
207
- return { verdict: { action: "fail" }, decidedBy: "bounds" };
208
- }
209
- // Cancel is free, not merely fast. Decisions are serialized, so a cancel
210
- // during a slow decision leaves a queue behind it; calling the handle for
211
- // each of those would spend real money deciding the fate of a run that is
212
- // already over.
213
- if (runSignal.aborted) {
214
- return { verdict: { action: "fail" }, decidedBy: "bounds" };
215
- }
216
- // The decision signal is the run signal plus a timeout, so an in-flight
217
- // decision is killed rather than un-awaited.
218
- const timeout = new AbortController();
219
- const onRunAbort = () => timeout.abort();
220
- runSignal.addEventListener("abort", onRunAbort, { once: true });
221
- const timer = setTimeout(() => timeout.abort(), this._bounds.decisionTimeoutMs);
222
- let decision;
223
- try {
224
- this._decisions++;
225
- decision = await this._inner.decide(e, timeout.signal);
226
- if (timeout.signal.aborted) {
227
- // A handle that resolves after its signal fired decided against a run
228
- // that is already over. Design §5.5.
229
- decision = { verdict: { action: "fail" }, decidedBy: "bounds" };
230
- }
231
- }
232
- catch {
233
- // Any failure *of* the supervisor resolves as today's behavior.
234
- decision = { verdict: { action: "fail" }, decidedBy: "bounds" };
235
- }
236
- finally {
237
- clearTimeout(timer);
238
- runSignal.removeEventListener("abort", onRunAbort);
239
- }
240
- decision = this._applyRetryBudget(e, decision);
241
- this._remember(e, decision.verdict);
242
- return decision;
243
- }
244
- _applyRetryBudget(e, decision) {
245
- if (decision.verdict.action !== "retry")
246
- return decision;
247
- const key = `${e.nodeId}\u0000${e.invocationKey}`;
248
- const used = this._retries.get(key) ?? 0;
249
- if (used >= this._bounds.maxRetriesPerNode) {
250
- return { verdict: { action: "fail" }, decidedBy: "bounds" };
251
- }
252
- this._retries.set(key, used + 1);
253
- return decision;
254
- }
255
- _remember(e, verdict) {
256
- // Only `skip` and `fail` may stick. A sticky `retry` or `substitute` would
257
- // blindly replay a decision made against different inputs.
258
- if (verdict.action !== "skip" && verdict.action !== "fail")
259
- return;
260
- if (verdict.applyTo !== "signature")
261
- return;
262
- if (e.failureSignature === undefined)
263
- return;
264
- this._sticky.set(stickyKey(e), verdict);
265
- }
266
- close() {
267
- this._inner.close();
268
- }
269
- }
270
- /**
271
- * Bound a handle, once. `WorkflowRunnerOptions.supervisor` takes any
272
- * `SupervisorHandle`, and an unbounded one — a handle that answers `retry`
273
- * forever, or whose `decide()` never resolves — spins or parks an actor for
274
- * the life of the process. The ceilings are the kernel's, not the caller's,
275
- * so the runner applies them itself; a handle its caller already bounded is
276
- * returned untouched.
277
- */
278
- export function ensureBounded(handle, opts = {}) {
279
- return handle.bounded === true ? handle : new BoundedHandle(handle, opts);
280
- }
281
- function stickyKey(e) {
282
- return `${e.nodeId}\u0000${e.failureSignature}`;
283
- }
284
- function stripUndefined(obj) {
285
- return Object.fromEntries(Object.entries(obj).filter(([, v]) => v !== undefined));
286
- }
1
+ export * from "@nodetool-ai/execution-core/supervisor";
287
2
  //# sourceMappingURL=supervisor.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"supervisor.js","sourceRoot":"","sources":["../src/supervisor.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AASH,OAAO,EACL,SAAS,EACT,gBAAgB,EAChB,QAAQ,EACR,aAAa,EACb,QAAQ,EACT,MAAM,iBAAiB,CAAC;AA+BzB;;;;GAIG;AACH,MAAM,OAAO,gBAAgB;IAC3B,KAAK,CAAC,MAAM;QACV,OAAO,EAAE,OAAO,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,EAAE,SAAS,EAAE,SAAS,EAAE,CAAC;IAC/D,CAAC;IACD,KAAK,KAAU,CAAC;CACjB;AAED,8EAA8E;AAC9E,YAAY;AACZ,8EAA8E;AAE9E;;;;GAIG;AACH,MAAM,sBAAsB,GAC1B,+HAA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,CAC3B,MAAwB,EACxB,IAAI,GAAqB,EAAE;IAE3B,OAAO,MAAM,CAAC,OAAO,KAAK,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,aAAa,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;AAC5E,CAAC;AAED,SAAS,SAAS,CAAC,CAAa;IAC9B,OAAO,GAAG,CAAC,CAAC,MAAM,SAAS,CAAC,CAAC,gBAAgB,EAAE,CAAC;AAClD,CAAC;AAED,SAAS,cAAc,CAAmB,GAAM;IAC9C,OAAO,MAAM,CAAC,WAAW,CACvB,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,KAAK,SAAS,CAAC,CACzC,CAAC;AAClB,CAAC"}
1
+ {"version":3,"file":"supervisor.js","sourceRoot":"","sources":["../src/supervisor.ts"],"names":[],"mappings":"AAAA,cAAc,wCAAwC,CAAC"}
@@ -1,123 +1,2 @@
1
- /**
2
- * Trigger wakeup service for managing suspended trigger workflows.
3
- *
4
- * Port of src/nodetool/workflows/trigger_wakeup_service.py.
5
- *
6
- * Stores trigger inputs, tracks suspended triggers, and coordinates
7
- * wakeup of suspended workflows when events arrive.
8
- */
9
- import { type DurableInboxStore } from "./durable-inbox.js";
10
- export interface TriggerInput {
11
- runId: string;
12
- nodeId: string;
13
- inputId: string;
14
- payload: unknown;
15
- cursor?: string;
16
- processed: boolean;
17
- createdAt: Date;
18
- processedAt?: Date;
19
- }
20
- /**
21
- * Storage backend for trigger inputs.
22
- *
23
- * Methods may answer synchronously (the in-memory store) or asynchronously (a
24
- * database-backed store), so callers written against the interface must await.
25
- * The kernel stays store-agnostic: DB-backed implementations live in the
26
- * server package, which is the only layer allowed to depend on the models.
27
- */
28
- export interface TriggerInputStore {
29
- /** Whether an input with this id was already stored (processed or not). */
30
- has(inputId: string): boolean | Promise<boolean>;
31
- /** Store an input; false when one with the same inputId already exists. */
32
- insertIfAbsent(input: TriggerInput): boolean | Promise<boolean>;
33
- /** Unprocessed inputs for a (run, node), oldest first. */
34
- findUnprocessed(runId: string, nodeId: string, limit?: number): TriggerInput[] | Promise<TriggerInput[]>;
35
- /** Mark an input processed. Unknown ids are a no-op. */
36
- markProcessed(inputId: string): void | Promise<void>;
37
- /** Drop processed inputs older than the cutoff; returns how many went. */
38
- cleanupProcessed(runId: string, nodeId: string, olderThanHours?: number): number | Promise<number>;
39
- /** Whether any input (processed or not) remains for a (run, node). */
40
- hasInputsFor(runId: string, nodeId: string): boolean | Promise<boolean>;
41
- /** Drop every input belonging to a run. */
42
- deleteRun(runId: string): void | Promise<void>;
43
- }
44
- /**
45
- * In-memory trigger input store — the default, and all a single-process run
46
- * needs. Its methods answer synchronously; the interface allows that, and
47
- * `TriggerWakeupService` awaits either way.
48
- */
49
- export declare class MemoryTriggerInputStore implements TriggerInputStore {
50
- private _inputs;
51
- /** Whether an input with this id was already stored. */
52
- has(inputId: string): boolean;
53
- insertIfAbsent(input: TriggerInput): boolean;
54
- findUnprocessed(runId: string, nodeId: string, limit?: number): TriggerInput[];
55
- markProcessed(inputId: string): void;
56
- cleanupProcessed(runId: string, nodeId: string, olderThanHours?: number): number;
57
- /** Whether any input (processed or not) remains for a (run, node). */
58
- hasInputsFor(runId: string, nodeId: string): boolean;
59
- /** Drop every input belonging to a run. */
60
- deleteRun(runId: string): void;
61
- }
62
- /**
63
- * Service for delivering trigger events and waking suspended workflows.
64
- * Stores trigger inputs durably and coordinates wakeup.
65
- *
66
- * Both stores are injectable and default to the in-memory implementations. The
67
- * whole public API is `async` because a database-backed store cannot answer
68
- * synchronously — callers must await even when the memory stores are in use.
69
- */
70
- export declare class TriggerWakeupService {
71
- private _store;
72
- private _inboxStore;
73
- /**
74
- * One DurableInbox per (runId, nodeId). DurableInbox.append() serializes its
75
- * read-modify-write (getMaxSeq → save) per *instance* via a promise chain, so
76
- * concurrent deliveries for the same (run, node) must share one instance or
77
- * they each read the same maxSeq and persist duplicate seq values. The key is
78
- * `JSON.stringify([runId, nodeId])` because runId/nodeId are arbitrary
79
- * strings — a plain `:` join would let ("a:b","c") collide with ("a","b:c").
80
- */
81
- private _inboxes;
82
- /**
83
- * inputIds whose durable append is in flight. Recorded before the `await` so
84
- * two concurrent deliveries of the same inputId dedupe against each other
85
- * (the in-memory `_inputs` marker is only written after a successful append,
86
- * so it can't cover the concurrent window). Cleared once the append settles.
87
- */
88
- private _inflightInputIds;
89
- constructor(inboxStore?: DurableInboxStore, inputStore?: TriggerInputStore);
90
- private _inboxFor;
91
- /**
92
- * Deliver a trigger input to a node (idempotent by inputId).
93
- * Also appends it as an inbox message for the trigger node.
94
- *
95
- * @returns true if newly created, false if already existed
96
- */
97
- deliverTriggerInput(opts: {
98
- runId: string;
99
- nodeId: string;
100
- inputId: string;
101
- payload: unknown;
102
- cursor?: string;
103
- }): Promise<boolean>;
104
- /**
105
- * Get pending (unprocessed) trigger inputs for a node.
106
- */
107
- getPendingInputs(runId: string, nodeId: string, limit?: number): Promise<TriggerInput[]>;
108
- /**
109
- * Mark a trigger input as processed.
110
- */
111
- markProcessed(inputId: string): Promise<void>;
112
- /**
113
- * Clean up processed trigger inputs older than specified hours.
114
- */
115
- cleanupProcessed(runId: string, nodeId: string, olderThanHours?: number): Promise<number>;
116
- /**
117
- * Release all in-memory state for a finished run: its trigger inputs and any
118
- * cached DurableInbox instances. Call when a run terminates so a long-lived
119
- * service does not accumulate per-run state indefinitely.
120
- */
121
- disposeRun(runId: string): Promise<void>;
122
- }
1
+ export * from "@nodetool-ai/execution-core/trigger-wakeup";
123
2
  //# sourceMappingURL=trigger-wakeup.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"trigger-wakeup.d.ts","sourceRoot":"","sources":["../src/trigger-wakeup.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAGH,OAAO,EAEL,KAAK,iBAAiB,EAEvB,MAAM,oBAAoB,CAAC;AAK5B,MAAM,WAAW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IAED;;OAEG;IACG,aAAa,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAIlD;IAED;;OAEG;IACG,gBAAgB,CACpB,KAAK,EAAE,MAAM,EACb,MAAM,EAAE,MAAM,EACd,cAAc,SAAK,GAClB,OAAO,CAAC,MAAM,CAAC,CAsBjB;IAED;;;;OAIG;IACG,UAAU,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAQ7C;CACF"}
1
+ {"version":3,"file":"trigger-wakeup.d.ts","sourceRoot":"","sources":["../src/trigger-wakeup.ts"],"names":[],"mappings":"AAAA,cAAc,4CAA4C,CAAC"}
@@ -1,221 +1,2 @@
1
- /**
2
- * Trigger wakeup service for managing suspended trigger workflows.
3
- *
4
- * Port of src/nodetool/workflows/trigger_wakeup_service.py.
5
- *
6
- * Stores trigger inputs, tracks suspended triggers, and coordinates
7
- * wakeup of suspended workflows when events arrive.
8
- */
9
- import { createLogger } from "@nodetool-ai/config";
10
- import { DurableInbox, MemoryDurableInboxStore } from "./durable-inbox.js";
11
- // Stryker disable next-line StringLiteral: logger name is a diagnostic label, not a behavioural contract
12
- const log = createLogger("nodetool.kernel.trigger-wakeup");
13
- /**
14
- * In-memory trigger input store — the default, and all a single-process run
15
- * needs. Its methods answer synchronously; the interface allows that, and
16
- * `TriggerWakeupService` awaits either way.
17
- */
18
- export class MemoryTriggerInputStore {
19
- // Stryker disable next-line ArrayDeclaration: a non-empty seed is equivalent — a bogus entry matches no runId/nodeId/inputId and is excluded by every query/filter
20
- _inputs = [];
21
- /** Whether an input with this id was already stored. */
22
- has(inputId) {
23
- return this._inputs.some((i) => i.inputId === inputId);
24
- }
25
- insertIfAbsent(input) {
26
- if (this.has(input.inputId))
27
- return false;
28
- this._inputs.push(input);
29
- return true;
30
- }
31
- findUnprocessed(runId, nodeId, limit = 100) {
32
- return this._inputs
33
- .filter((i) => i.runId === runId && i.nodeId === nodeId && !i.processed)
34
- .slice(0, limit);
35
- }
36
- markProcessed(inputId) {
37
- const input = this._inputs.find((i) => i.inputId === inputId);
38
- if (input) {
39
- input.processed = true;
40
- input.processedAt = new Date();
41
- }
42
- }
43
- cleanupProcessed(runId, nodeId, olderThanHours = 24) {
44
- const cutoff = Date.now() - olderThanHours * 60 * 60 * 1000;
45
- const before = this._inputs.length;
46
- this._inputs = this._inputs.filter((i) => !(i.runId === runId &&
47
- i.nodeId === nodeId &&
48
- i.processed &&
49
- i.processedAt &&
50
- i.processedAt.getTime() < cutoff));
51
- return before - this._inputs.length;
52
- }
53
- /** Whether any input (processed or not) remains for a (run, node). */
54
- hasInputsFor(runId, nodeId) {
55
- return this._inputs.some((i) => i.runId === runId && i.nodeId === nodeId);
56
- }
57
- /** Drop every input belonging to a run. */
58
- deleteRun(runId) {
59
- this._inputs = this._inputs.filter((i) => i.runId !== runId);
60
- }
61
- }
62
- /**
63
- * Service for delivering trigger events and waking suspended workflows.
64
- * Stores trigger inputs durably and coordinates wakeup.
65
- *
66
- * Both stores are injectable and default to the in-memory implementations. The
67
- * whole public API is `async` because a database-backed store cannot answer
68
- * synchronously — callers must await even when the memory stores are in use.
69
- */
70
- export class TriggerWakeupService {
71
- _store;
72
- _inboxStore;
73
- /**
74
- * One DurableInbox per (runId, nodeId). DurableInbox.append() serializes its
75
- * read-modify-write (getMaxSeq → save) per *instance* via a promise chain, so
76
- * concurrent deliveries for the same (run, node) must share one instance or
77
- * they each read the same maxSeq and persist duplicate seq values. The key is
78
- * `JSON.stringify([runId, nodeId])` because runId/nodeId are arbitrary
79
- * strings — a plain `:` join would let ("a:b","c") collide with ("a","b:c").
80
- */
81
- _inboxes = new Map();
82
- /**
83
- * inputIds whose durable append is in flight. Recorded before the `await` so
84
- * two concurrent deliveries of the same inputId dedupe against each other
85
- * (the in-memory `_inputs` marker is only written after a successful append,
86
- * so it can't cover the concurrent window). Cleared once the append settles.
87
- */
88
- _inflightInputIds = new Set();
89
- constructor(inboxStore, inputStore) {
90
- this._inboxStore = inboxStore ?? new MemoryDurableInboxStore();
91
- this._store = inputStore ?? new MemoryTriggerInputStore();
92
- }
93
- _inboxFor(runId, nodeId) {
94
- const key = JSON.stringify([runId, nodeId]);
95
- let inbox = this._inboxes.get(key);
96
- if (!inbox) {
97
- inbox = new DurableInbox(runId, nodeId, this._inboxStore);
98
- this._inboxes.set(key, inbox);
99
- }
100
- return inbox;
101
- }
102
- /**
103
- * Deliver a trigger input to a node (idempotent by inputId).
104
- * Also appends it as an inbox message for the trigger node.
105
- *
106
- * @returns true if newly created, false if already existed
107
- */
108
- async deliverTriggerInput(opts) {
109
- // Idempotency, part one: a concurrent delivery of the same inputId whose
110
- // durable append is still in flight. This check and the matching `add` are
111
- // the synchronous prefix of the method — nothing may await between them, or
112
- // two concurrent deliveries both pass and both store an entry.
113
- if (this._inflightInputIds.has(opts.inputId)) {
114
- // Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
115
- log.debug("Trigger input already exists (idempotent)", {
116
- inputId: opts.inputId
117
- });
118
- return false;
119
- }
120
- this._inflightInputIds.add(opts.inputId);
121
- try {
122
- // Idempotency, part two: the committed marker in the store. With a
123
- // database store this is the check that survives a restart.
124
- if (await this._store.has(opts.inputId)) {
125
- // Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
126
- log.debug("Trigger input already exists (idempotent)", {
127
- inputId: opts.inputId
128
- });
129
- return false;
130
- }
131
- const input = {
132
- runId: opts.runId,
133
- nodeId: opts.nodeId,
134
- inputId: opts.inputId,
135
- payload: opts.payload,
136
- cursor: opts.cursor,
137
- processed: false,
138
- createdAt: new Date()
139
- };
140
- // Durable append FIRST, then record the idempotency marker in the store.
141
- // Recording the marker before the append meant a transient append failure
142
- // left the marker behind, so the caller's retry hit the idempotency check
143
- // and returned early WITHOUT ever writing the durable message — the event
144
- // was lost. The inbox dedupes by message id (`trigger-<inputId>`), so a
145
- // concurrent double-append is safe. Reuse a cached DurableInbox per (run,
146
- // node) so its per-instance append serialization applies across concurrent
147
- // deliveries — a fresh instance per call would defeat it (see finding #9).
148
- // The in-flight marker covers the whole await window; on failure it is
149
- // cleared so a retry is not short-circuited.
150
- const inbox = this._inboxFor(opts.runId, opts.nodeId);
151
- await inbox.append("trigger", opts.payload, `trigger-${opts.inputId}`);
152
- await this._store.insertIfAbsent(input);
153
- const logFields = {
154
- inputId: opts.inputId,
155
- runId: opts.runId,
156
- nodeId: opts.nodeId
157
- };
158
- // Stryker disable next-line ConditionalExpression: diagnostic log field only
159
- if (opts.cursor) {
160
- logFields.cursor = opts.cursor;
161
- }
162
- // Stryker disable next-line StringLiteral: diagnostic log message only
163
- log.info("Stored trigger input", logFields);
164
- return true;
165
- }
166
- finally {
167
- this._inflightInputIds.delete(opts.inputId);
168
- }
169
- }
170
- /**
171
- * Get pending (unprocessed) trigger inputs for a node.
172
- */
173
- async getPendingInputs(runId, nodeId, limit = 100) {
174
- return this._store.findUnprocessed(runId, nodeId, limit);
175
- }
176
- /**
177
- * Mark a trigger input as processed.
178
- */
179
- async markProcessed(inputId) {
180
- await this._store.markProcessed(inputId);
181
- // Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
182
- log.debug("Marked trigger input as processed", { inputId });
183
- }
184
- /**
185
- * Clean up processed trigger inputs older than specified hours.
186
- */
187
- async cleanupProcessed(runId, nodeId, olderThanHours = 24) {
188
- const removed = await this._store.cleanupProcessed(runId, nodeId, olderThanHours);
189
- // Stryker disable next-line ConditionalExpression,EqualityOperator,BlockStatement: the guard only gates a diagnostic log; `removed` is returned regardless
190
- if (removed > 0) {
191
- // Stryker disable next-line StringLiteral,ObjectLiteral: diagnostic log args only
192
- log.info("Cleaned up processed trigger inputs", {
193
- count: removed,
194
- runId,
195
- nodeId
196
- });
197
- }
198
- // Evict the cached DurableInbox once no inputs remain for this (run, node),
199
- // otherwise _inboxes grows by one entry per run for the process lifetime
200
- // (runId is unique per run) even after cleanupProcessed purges the inputs.
201
- if (!(await this._store.hasInputsFor(runId, nodeId))) {
202
- this._inboxes.delete(JSON.stringify([runId, nodeId]));
203
- }
204
- return removed;
205
- }
206
- /**
207
- * Release all in-memory state for a finished run: its trigger inputs and any
208
- * cached DurableInbox instances. Call when a run terminates so a long-lived
209
- * service does not accumulate per-run state indefinitely.
210
- */
211
- async disposeRun(runId) {
212
- await this._store.deleteRun(runId);
213
- for (const key of [...this._inboxes.keys()]) {
214
- const [keyRunId] = JSON.parse(key);
215
- if (keyRunId === runId) {
216
- this._inboxes.delete(key);
217
- }
218
- }
219
- }
220
- }
1
+ export * from "@nodetool-ai/execution-core/trigger-wakeup";
221
2
  //# sourceMappingURL=trigger-wakeup.js.map