@codemation/core 0.0.5 → 0.0.7

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.
@@ -0,0 +1,3136 @@
1
+ import { createHash } from "node:crypto";
2
+ import "reflect-metadata";
3
+ import { container, delay, inject, injectAll, injectable, instanceCachingFactory, instancePerContainerCachingFactory, predicateAwareClassFactory, registry, singleton } from "tsyringe";
4
+ import { ReadableStream } from "node:stream/web";
5
+
6
+ //#region src/workflow/definition/ConnectionNodeIdFactory.ts
7
+ /**
8
+ * Deterministic ids for workflow connection-owned child nodes (LLM slot, tools, etc.).
9
+ * These are stable across loads.
10
+ */
11
+ var ConnectionNodeIdFactory = class {
12
+ static connectionSegment = "__conn__";
13
+ static languageModelConnectionNodeId(parentNodeId) {
14
+ return `${parentNodeId}${this.connectionSegment}llm`;
15
+ }
16
+ static toolConnectionNodeId(parentNodeId, toolName) {
17
+ const normalized = this.normalizeToolName(toolName);
18
+ return `${parentNodeId}${this.connectionSegment}tool${this.connectionSegment}${normalized}`;
19
+ }
20
+ static isLanguageModelConnectionNodeId(nodeId) {
21
+ return nodeId.endsWith(`${this.connectionSegment}llm`);
22
+ }
23
+ static isToolConnectionNodeId(nodeId) {
24
+ return nodeId.includes(`${this.connectionSegment}tool${this.connectionSegment}`);
25
+ }
26
+ /** True when `nodeId` is a connection-owned child of `parentNodeId` (LLM or tool slot). */
27
+ static isConnectionOwnedDescendantOf(parentNodeId, nodeId) {
28
+ return nodeId.startsWith(`${parentNodeId}${this.connectionSegment}`);
29
+ }
30
+ /** Normalizes a tool display name to a stable id segment. */
31
+ static normalizeToolName(toolName) {
32
+ return toolName.trim().toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "") || "tool";
33
+ }
34
+ };
35
+
36
+ //#endregion
37
+ //#region src/workflow/definition/WorkflowExecutableNodeClassifier.ts
38
+ /**
39
+ * Derives which workflow nodes participate in the main execution graph vs connection-only children.
40
+ */
41
+ var WorkflowExecutableNodeClassifier = class {
42
+ connectionOwnedIds;
43
+ constructor(workflow) {
44
+ this.connectionOwnedIds = this.collectConnectionOwnedIds(workflow);
45
+ }
46
+ isConnectionOwnedNodeId(nodeId) {
47
+ return this.connectionOwnedIds.has(nodeId);
48
+ }
49
+ isExecutableNodeId(nodeId) {
50
+ return !this.connectionOwnedIds.has(nodeId);
51
+ }
52
+ filterExecutableNodeDefinitions(nodes) {
53
+ return nodes.filter((n) => this.isExecutableNodeId(n.id));
54
+ }
55
+ collectConnectionOwnedIds(workflow) {
56
+ const ids = /* @__PURE__ */ new Set();
57
+ for (const connection of workflow.connections ?? []) for (const childId of connection.childNodeIds) ids.add(childId);
58
+ return ids;
59
+ }
60
+ /**
61
+ * Resolves the default start node: first trigger, else first executable node with no incoming edges from executable nodes.
62
+ */
63
+ findDefaultExecutableStartNodeId(workflow) {
64
+ const firstTrigger = workflow.nodes.find((n) => n.kind === "trigger" && this.isExecutableNodeId(n.id))?.id;
65
+ if (firstTrigger) return firstTrigger;
66
+ const incoming = /* @__PURE__ */ new Map();
67
+ for (const n of workflow.nodes) if (this.isExecutableNodeId(n.id)) incoming.set(n.id, 0);
68
+ for (const e of workflow.edges) {
69
+ if (!this.isExecutableNodeId(e.from.nodeId) || !this.isExecutableNodeId(e.to.nodeId)) continue;
70
+ incoming.set(e.to.nodeId, (incoming.get(e.to.nodeId) ?? 0) + 1);
71
+ }
72
+ return workflow.nodes.find((n) => this.isExecutableNodeId(n.id) && (incoming.get(n.id) ?? 0) === 0)?.id ?? workflow.nodes.find((n) => this.isExecutableNodeId(n.id))?.id ?? (() => {
73
+ throw new Error(`Workflow ${workflow.id} has no executable nodes`);
74
+ })();
75
+ }
76
+ firstExecutableNodeIdInDefinitionOrder(workflow) {
77
+ return workflow.nodes.find((n) => this.isExecutableNodeId(n.id))?.id;
78
+ }
79
+ lastExecutableNodeIdInDefinitionOrder(workflow) {
80
+ for (let i = workflow.nodes.length - 1; i >= 0; i--) {
81
+ const n = workflow.nodes[i];
82
+ if (this.isExecutableNodeId(n.id)) return n.id;
83
+ }
84
+ throw new Error(`Workflow ${workflow.id} has no executable nodes`);
85
+ }
86
+ };
87
+
88
+ //#endregion
89
+ //#region src/workflow/definition/WorkflowExecutableNodeClassifierFactory.ts
90
+ var WorkflowExecutableNodeClassifierFactory = class {
91
+ static create(workflow) {
92
+ return new WorkflowExecutableNodeClassifier(workflow);
93
+ }
94
+ };
95
+
96
+ //#endregion
97
+ //#region src/di/CoreTokens.ts
98
+ const CoreTokens = {
99
+ PersistedWorkflowTokenRegistry: Symbol.for("codemation.core.PersistedWorkflowTokenRegistry"),
100
+ CredentialSessionService: Symbol.for("codemation.core.CredentialSessionService"),
101
+ CredentialTypeRegistry: Symbol.for("codemation.core.CredentialTypeRegistry"),
102
+ WorkflowRunnerService: Symbol.for("codemation.core.WorkflowRunnerService"),
103
+ LiveWorkflowRepository: Symbol.for("codemation.core.LiveWorkflowRepository"),
104
+ WorkflowRepository: Symbol.for("codemation.core.WorkflowRepository"),
105
+ NodeResolver: Symbol.for("codemation.core.NodeResolver"),
106
+ WorkflowNodeInstanceFactory: Symbol.for("codemation.core.WorkflowNodeInstanceFactory"),
107
+ RunIdFactory: Symbol.for("codemation.core.RunIdFactory"),
108
+ ActivationIdFactory: Symbol.for("codemation.core.ActivationIdFactory"),
109
+ WorkflowExecutionRepository: Symbol.for("codemation.core.WorkflowExecutionRepository"),
110
+ TriggerSetupStateRepository: Symbol.for("codemation.core.TriggerSetupStateRepository"),
111
+ NodeActivationScheduler: Symbol.for("codemation.core.NodeActivationScheduler"),
112
+ RunDataFactory: Symbol.for("codemation.core.RunDataFactory"),
113
+ ExecutionContextFactory: Symbol.for("codemation.core.ExecutionContextFactory"),
114
+ RunEventBus: Symbol.for("codemation.core.RunEventBus"),
115
+ BinaryStorage: Symbol.for("codemation.core.BinaryStorage"),
116
+ WebhookBasePath: Symbol.for("codemation.core.WebhookBasePath"),
117
+ EngineExecutionLimitsPolicy: Symbol.for("codemation.core.EngineExecutionLimitsPolicy"),
118
+ WorkflowActivationPolicy: Symbol.for("codemation.core.WorkflowActivationPolicy")
119
+ };
120
+
121
+ //#endregion
122
+ //#region src/events/NodeEventPublisher.ts
123
+ /** Publishes node lifecycle snapshots onto the run {@link RunEventBus}. */
124
+ var NodeEventPublisher = class {
125
+ constructor(eventBus) {
126
+ this.eventBus = eventBus;
127
+ }
128
+ async publish(kind, snapshot) {
129
+ if (!this.eventBus) return;
130
+ await this.eventBus.publish({
131
+ kind,
132
+ runId: snapshot.runId,
133
+ workflowId: snapshot.workflowId,
134
+ parent: snapshot.parent,
135
+ at: snapshot.updatedAt,
136
+ snapshot
137
+ });
138
+ }
139
+ };
140
+
141
+ //#endregion
142
+ //#region src/runtime-types/persistedRuntimeTypeModelRegistry.ts
143
+ /** Shared metadata key used to attach persisted runtime-type information to decorated classes. */
144
+ const persistedRuntimeTypeMetadataKey = Symbol.for("codemation.core.persistedRuntimeTypeMetadata");
145
+ /** Normalizes decorator options so persistence metadata has stable defaults. */
146
+ var PersistedRuntimeTypeDecoratorDefaults = class {
147
+ static appPackageName = "app";
148
+ static apply(options) {
149
+ return {
150
+ ...options,
151
+ packageName: options.packageName ?? this.appPackageName
152
+ };
153
+ }
154
+ };
155
+
156
+ //#endregion
157
+ //#region src/runtime-types/PersistedRuntimeTypeNameResolver.ts
158
+ /** Resolves the persisted type name from either an explicit override or the class name itself. */
159
+ var PersistedRuntimeTypeNameResolver = class {
160
+ static resolve(target, override) {
161
+ const resolved = override ?? target.name;
162
+ if (!resolved) throw new Error("Persisted runtime token metadata requires a named class or an explicit decorator name override.");
163
+ return resolved;
164
+ }
165
+ };
166
+
167
+ //#endregion
168
+ //#region src/runtime-types/StackTraceCallSitePathResolver.ts
169
+ var StackTraceCallSitePathResolver = class {
170
+ static resolve(decoratorFileUrl) {
171
+ const stack = (/* @__PURE__ */ new Error()).stack ?? "";
172
+ for (const line of stack.split("\n")) {
173
+ const candidate = this.extractPath(line.trim());
174
+ if (!candidate) continue;
175
+ if (candidate === decoratorFileUrl || candidate.includes("runtimeTypeDecorators")) continue;
176
+ return candidate;
177
+ }
178
+ }
179
+ static extractPath(line) {
180
+ const fileUrlMatch = line.match(/file:\/\/[^\s)]+/);
181
+ if (fileUrlMatch) return fileUrlMatch[0];
182
+ const parenMatch = line.match(/\((\/[^)]+)\)/);
183
+ if (parenMatch) return parenMatch[1];
184
+ return line.match(/at (\/[^\s]+)/)?.[1];
185
+ }
186
+ };
187
+
188
+ //#endregion
189
+ //#region src/runtime-types/PersistedRuntimeTypeMetadataStoreRegistry.ts
190
+ /**
191
+ * Defines and retrieves persisted runtime metadata on decorated classes.
192
+ * The metadata is attached as a non-enumerable property so runtime objects stay serializable.
193
+ */
194
+ var PersistedRuntimeTypeMetadataStore = class {
195
+ static define(target, kind, options, decoratorFileUrl) {
196
+ const normalizedOptions = PersistedRuntimeTypeDecoratorDefaults.apply(options);
197
+ const metadata = {
198
+ persistedName: PersistedRuntimeTypeNameResolver.resolve(target, normalizedOptions.name),
199
+ kind,
200
+ packageName: normalizedOptions.packageName ?? PersistedRuntimeTypeDecoratorDefaults.appPackageName,
201
+ sourceHint: normalizedOptions.moduleUrl ?? StackTraceCallSitePathResolver.resolve(decoratorFileUrl)
202
+ };
203
+ Object.defineProperty(target, persistedRuntimeTypeMetadataKey, {
204
+ configurable: false,
205
+ enumerable: false,
206
+ writable: false,
207
+ value: metadata
208
+ });
209
+ }
210
+ static get(target) {
211
+ if (!target || typeof target !== "function" && typeof target !== "object") return;
212
+ return target[persistedRuntimeTypeMetadataKey];
213
+ }
214
+ };
215
+
216
+ //#endregion
217
+ //#region src/runtime-types/InjectableRuntimeDecoratorComposerRegistry.ts
218
+ /**
219
+ * Applies both tsyringe injectability and persisted runtime metadata in one decorator.
220
+ * This keeps runtime-type decorators thin while still recording enough data for snapshot hydration.
221
+ */
222
+ var InjectableRuntimeDecoratorComposer = class {
223
+ static compose(kind, options, decoratorFileUrl) {
224
+ return (target) => {
225
+ injectable()(target);
226
+ PersistedRuntimeTypeMetadataStore.define(target, kind, options, decoratorFileUrl);
227
+ };
228
+ }
229
+ };
230
+
231
+ //#endregion
232
+ //#region src/runtime-types/runtimeTypeDecorators.types.ts
233
+ /** Reads persisted runtime metadata from a decorated class or object. */
234
+ function getPersistedRuntimeTypeMetadata(target) {
235
+ return PersistedRuntimeTypeMetadataStore.get(target);
236
+ }
237
+ /** Marks a class as a persisted node runtime type and an injectable tsyringe service. */
238
+ function node(options = {}) {
239
+ return InjectableRuntimeDecoratorComposer.compose("node", options, import.meta.url);
240
+ }
241
+ /** Marks a class as a persisted tool runtime type and an injectable tsyringe service. */
242
+ function tool(options = {}) {
243
+ return InjectableRuntimeDecoratorComposer.compose("tool", options, import.meta.url);
244
+ }
245
+ /** Marks a class as a persisted chat-model runtime type and an injectable tsyringe service. */
246
+ function chatModel(options = {}) {
247
+ return InjectableRuntimeDecoratorComposer.compose("chatModel", options, import.meta.url);
248
+ }
249
+
250
+ //#endregion
251
+ //#region src/binaries/DefaultNodeBinaryAttachmentServiceFactory.ts
252
+ var DefaultNodeBinaryAttachmentService = class DefaultNodeBinaryAttachmentService {
253
+ constructor(storage, workflowId, runId, nodeId, activationId, now) {
254
+ this.storage = storage;
255
+ this.workflowId = workflowId;
256
+ this.runId = runId;
257
+ this.nodeId = nodeId;
258
+ this.activationId = activationId;
259
+ this.now = now;
260
+ }
261
+ async attach(args) {
262
+ const attachmentId = this.createAttachmentId();
263
+ const createdAt = this.now().toISOString();
264
+ const storageKey = this.createStorageKey(args, attachmentId);
265
+ const stored = await this.storage.write({
266
+ storageKey,
267
+ body: args.body
268
+ });
269
+ return {
270
+ id: attachmentId,
271
+ storageKey: stored.storageKey,
272
+ mimeType: args.mimeType,
273
+ size: stored.size,
274
+ storageDriver: this.storage.driverName,
275
+ previewKind: args.previewKind ?? this.resolvePreviewKind(args.mimeType),
276
+ createdAt,
277
+ runId: this.runId,
278
+ workflowId: this.workflowId,
279
+ nodeId: this.nodeId,
280
+ activationId: this.activationId,
281
+ filename: args.filename,
282
+ sha256: stored.sha256
283
+ };
284
+ }
285
+ withAttachment(item, name, attachment) {
286
+ return {
287
+ ...item,
288
+ binary: {
289
+ ...item.binary ?? {},
290
+ [name]: attachment
291
+ }
292
+ };
293
+ }
294
+ forNode(args) {
295
+ return new DefaultNodeBinaryAttachmentService(this.storage, this.workflowId, this.runId, args.nodeId, args.activationId, this.now);
296
+ }
297
+ async openReadStream(attachment) {
298
+ return await this.storage.openReadStream(attachment.storageKey);
299
+ }
300
+ createAttachmentId() {
301
+ return DefaultNodeBinaryAttachmentService.createAttachmentIdValue(`${this.activationId}-${this.now().getTime()}`);
302
+ }
303
+ static createAttachmentIdValue(fallbackValue) {
304
+ const cryptoObject = globalThis.crypto;
305
+ if (cryptoObject && typeof cryptoObject.randomUUID === "function") return cryptoObject.randomUUID();
306
+ return fallbackValue;
307
+ }
308
+ createStorageKey(args, attachmentId) {
309
+ const safeName = this.sanitizeSegment(args.name);
310
+ const safeFilename = this.sanitizeFilename(args.filename);
311
+ const filenameSuffix = safeFilename ? `-${safeFilename}` : "";
312
+ return `${this.sanitizeSegment(this.workflowId)}/${this.sanitizeSegment(this.runId)}/${this.sanitizeSegment(this.nodeId)}/${this.sanitizeSegment(this.activationId)}/${attachmentId}-${safeName}${filenameSuffix}`;
313
+ }
314
+ sanitizeSegment(value) {
315
+ const normalized = value.trim();
316
+ if (!normalized) return "item";
317
+ return normalized.replace(/[^a-zA-Z0-9._-]+/g, "_");
318
+ }
319
+ sanitizeFilename(value) {
320
+ if (!value) return;
321
+ const normalized = value.trim().split("/").at(-1)?.split("\\").at(-1) ?? value.trim();
322
+ if (!normalized) return;
323
+ return normalized.replace(/[^a-zA-Z0-9._-]+/g, "_");
324
+ }
325
+ resolvePreviewKind(mimeType) {
326
+ if (mimeType.startsWith("image/")) return "image";
327
+ if (mimeType.startsWith("audio/")) return "audio";
328
+ if (mimeType.startsWith("video/")) return "video";
329
+ return "download";
330
+ }
331
+ };
332
+
333
+ //#endregion
334
+ //#region src/binaries/UnavailableBinaryStorage.ts
335
+ var UnavailableBinaryStorage = class {
336
+ driverName = "unavailable";
337
+ async write() {
338
+ throw new Error("Binary storage is not configured for this runtime.");
339
+ }
340
+ async openReadStream() {}
341
+ async stat() {
342
+ return { exists: false };
343
+ }
344
+ async delete() {}
345
+ };
346
+
347
+ //#endregion
348
+ //#region src/binaries/DefaultExecutionBinaryServiceFactory.ts
349
+ var DefaultExecutionBinaryService = class {
350
+ constructor(storage, workflowId, runId, now) {
351
+ this.storage = storage;
352
+ this.workflowId = workflowId;
353
+ this.runId = runId;
354
+ this.now = now;
355
+ }
356
+ forNode(args) {
357
+ return new DefaultNodeBinaryAttachmentService(this.storage, this.workflowId, this.runId, args.nodeId, args.activationId, this.now);
358
+ }
359
+ async openReadStream(attachment) {
360
+ return await this.storage.openReadStream(attachment.storageKey);
361
+ }
362
+ };
363
+
364
+ //#endregion
365
+ //#region src/execution/NodeExecutionSnapshotFactory.ts
366
+ var NodeExecutionSnapshotFactory = class {
367
+ static queued(args) {
368
+ return {
369
+ runId: args.runId,
370
+ workflowId: args.workflowId,
371
+ nodeId: args.nodeId,
372
+ activationId: args.activationId,
373
+ parent: args.parent,
374
+ status: "queued",
375
+ queuedAt: args.queuedAt,
376
+ updatedAt: args.queuedAt,
377
+ inputsByPort: args.inputsByPort
378
+ };
379
+ }
380
+ static running(args) {
381
+ return {
382
+ runId: args.runId,
383
+ workflowId: args.workflowId,
384
+ nodeId: args.nodeId,
385
+ activationId: args.activationId,
386
+ parent: args.parent,
387
+ status: "running",
388
+ queuedAt: args.previous?.queuedAt,
389
+ startedAt: args.startedAt,
390
+ updatedAt: args.startedAt,
391
+ inputsByPort: args.inputsByPort,
392
+ outputs: args.previous?.outputs,
393
+ error: void 0
394
+ };
395
+ }
396
+ static completed(args) {
397
+ const fromPinnedOutput = args.fromPinnedOutput ?? false;
398
+ const startedAt = fromPinnedOutput ? args.previous?.startedAt ?? args.finishedAt : args.previous?.startedAt;
399
+ return {
400
+ runId: args.runId,
401
+ workflowId: args.workflowId,
402
+ nodeId: args.nodeId,
403
+ activationId: args.activationId,
404
+ parent: args.parent,
405
+ status: "completed",
406
+ queuedAt: args.previous?.queuedAt,
407
+ startedAt,
408
+ finishedAt: args.finishedAt,
409
+ updatedAt: args.finishedAt,
410
+ inputsByPort: args.inputsByPort,
411
+ outputs: args.outputs,
412
+ usedPinnedOutput: fromPinnedOutput,
413
+ error: void 0
414
+ };
415
+ }
416
+ static skipped(args) {
417
+ return {
418
+ runId: args.runId,
419
+ workflowId: args.workflowId,
420
+ nodeId: args.nodeId,
421
+ activationId: args.activationId,
422
+ parent: args.parent,
423
+ status: "skipped",
424
+ queuedAt: args.previous?.queuedAt,
425
+ startedAt: args.previous?.startedAt,
426
+ finishedAt: args.finishedAt,
427
+ updatedAt: args.finishedAt,
428
+ inputsByPort: args.inputsByPort,
429
+ outputs: args.outputs,
430
+ error: void 0
431
+ };
432
+ }
433
+ static failed(args) {
434
+ return {
435
+ runId: args.runId,
436
+ workflowId: args.workflowId,
437
+ nodeId: args.nodeId,
438
+ activationId: args.activationId,
439
+ parent: args.parent,
440
+ status: "failed",
441
+ queuedAt: args.previous?.queuedAt,
442
+ startedAt: args.previous?.startedAt,
443
+ finishedAt: args.finishedAt,
444
+ updatedAt: args.finishedAt,
445
+ inputsByPort: args.inputsByPort,
446
+ outputs: void 0,
447
+ error: {
448
+ message: args.error.message,
449
+ name: args.error.name,
450
+ stack: args.error.stack
451
+ }
452
+ };
453
+ }
454
+ };
455
+
456
+ //#endregion
457
+ //#region src/execution/NodeInputsByPortFactory.ts
458
+ var NodeInputsByPortFactory = class {
459
+ static empty() {
460
+ return {};
461
+ }
462
+ static fromRequest(request) {
463
+ if (request.kind === "multi") return request.inputsByPort;
464
+ return { in: request.input };
465
+ }
466
+ };
467
+
468
+ //#endregion
469
+ //#region src/execution/ActivationEnqueueService.ts
470
+ var ActivationEnqueueService = class {
471
+ constructor(activationScheduler, workflowExecutionRepository, nodeEventPublisher) {
472
+ this.activationScheduler = activationScheduler;
473
+ this.workflowExecutionRepository = workflowExecutionRepository;
474
+ this.nodeEventPublisher = nodeEventPublisher;
475
+ }
476
+ async enqueueActivation(args) {
477
+ const { result, queuedSnapshot } = await this.enqueueActivationWithSnapshot(args);
478
+ await this.nodeEventPublisher.publish("nodeQueued", queuedSnapshot);
479
+ return result;
480
+ }
481
+ async enqueueActivationWithSnapshot(args) {
482
+ const receipt = await this.activationScheduler.enqueue(args.request);
483
+ const inputsByPort = NodeInputsByPortFactory.fromRequest(args.request);
484
+ const itemsIn = args.request.kind === "multi" ? args.planner.sumItemsByPort(args.request.inputsByPort) : args.request.input.length;
485
+ const enqueuedAt = (/* @__PURE__ */ new Date()).toISOString();
486
+ const pending = {
487
+ runId: args.runId,
488
+ activationId: args.request.activationId,
489
+ workflowId: args.workflowId,
490
+ nodeId: args.request.nodeId,
491
+ itemsIn,
492
+ inputsByPort,
493
+ receiptId: receipt.receiptId,
494
+ queue: receipt.queue,
495
+ batchId: args.request.batchId,
496
+ enqueuedAt
497
+ };
498
+ const queuedSnapshot = NodeExecutionSnapshotFactory.queued({
499
+ runId: args.runId,
500
+ workflowId: args.workflowId,
501
+ nodeId: args.request.nodeId,
502
+ activationId: args.request.activationId,
503
+ parent: args.parent,
504
+ queuedAt: enqueuedAt,
505
+ inputsByPort
506
+ });
507
+ await this.workflowExecutionRepository.save({
508
+ runId: args.runId,
509
+ workflowId: args.workflowId,
510
+ startedAt: args.startedAt,
511
+ parent: args.parent,
512
+ executionOptions: args.executionOptions,
513
+ control: args.control,
514
+ workflowSnapshot: args.workflowSnapshot,
515
+ mutableState: args.mutableState,
516
+ policySnapshot: args.policySnapshot,
517
+ engineCounters: args.engineCounters,
518
+ connectionInvocations: args.connectionInvocations ? [...args.connectionInvocations] : [],
519
+ status: "pending",
520
+ pending,
521
+ queue: args.pendingQueue.map((entry) => ({ ...entry })),
522
+ outputsByNode: args.request.ctx.data.dump(),
523
+ nodeSnapshotsByNodeId: {
524
+ ...args.previousNodeSnapshotsByNodeId,
525
+ [args.request.nodeId]: queuedSnapshot
526
+ }
527
+ });
528
+ this.notifyPendingStatePersisted(args.runId);
529
+ return {
530
+ result: {
531
+ runId: args.runId,
532
+ workflowId: args.workflowId,
533
+ startedAt: args.startedAt,
534
+ status: "pending",
535
+ pending
536
+ },
537
+ queuedSnapshot
538
+ };
539
+ }
540
+ notifyPendingStatePersisted(runId) {
541
+ this.activationScheduler.notifyPendingStatePersisted?.(runId);
542
+ }
543
+ };
544
+
545
+ //#endregion
546
+ //#region src/execution/CredentialResolverFactory.ts
547
+ var CredentialResolverFactory = class {
548
+ constructor(credentialSessions) {
549
+ this.credentialSessions = credentialSessions;
550
+ }
551
+ create(workflowId, nodeId, config) {
552
+ const acceptedTypesBySlot = /* @__PURE__ */ new Map();
553
+ for (const requirement of config?.getCredentialRequirements?.() ?? []) acceptedTypesBySlot.set(requirement.slotKey, requirement.acceptedTypes);
554
+ return async (slotKey) => {
555
+ try {
556
+ return await this.credentialSessions.getSession({
557
+ workflowId,
558
+ nodeId,
559
+ slotKey
560
+ });
561
+ } catch (error) {
562
+ const acceptedTypes = acceptedTypesBySlot.get(slotKey) ?? [];
563
+ const message = error instanceof Error ? error.message : String(error);
564
+ const alreadyListsAcceptedTypes = message.includes("Accepted types:") || message.includes("Accepted credential types:") || message.includes("binding points at an unknown type");
565
+ const acceptedTypesSuffix = acceptedTypes.length > 0 && !alreadyListsAcceptedTypes ? ` Accepted types: ${acceptedTypes.join(", ")}.` : "";
566
+ throw new Error(`Failed to resolve credential for workflow ${workflowId} node ${nodeId} slot "${slotKey}". ${message}${acceptedTypesSuffix}`, { cause: error });
567
+ }
568
+ };
569
+ }
570
+ };
571
+
572
+ //#endregion
573
+ //#region src/execution/DefaultAsyncSleeper.ts
574
+ var DefaultAsyncSleeper = class {
575
+ sleep(ms) {
576
+ return new Promise((resolve) => {
577
+ setTimeout(resolve, ms);
578
+ });
579
+ }
580
+ };
581
+
582
+ //#endregion
583
+ //#region src/execution/DefaultExecutionContextFactory.ts
584
+ var DefaultExecutionContextFactory = class {
585
+ constructor(binaryStorage = new UnavailableBinaryStorage(), currentDate = () => /* @__PURE__ */ new Date()) {
586
+ this.binaryStorage = binaryStorage;
587
+ this.currentDate = currentDate;
588
+ }
589
+ create(args) {
590
+ return {
591
+ runId: args.runId,
592
+ workflowId: args.workflowId,
593
+ parent: args.parent,
594
+ subworkflowDepth: args.subworkflowDepth,
595
+ engineMaxNodeActivations: args.engineMaxNodeActivations,
596
+ engineMaxSubworkflowDepth: args.engineMaxSubworkflowDepth,
597
+ now: this.currentDate,
598
+ data: args.data,
599
+ nodeState: args.nodeState,
600
+ binary: new DefaultExecutionBinaryService(this.binaryStorage, args.workflowId, args.runId, this.currentDate),
601
+ getCredential: args.getCredential
602
+ };
603
+ }
604
+ };
605
+
606
+ //#endregion
607
+ //#region src/execution/InProcessRetryRunner.ts
608
+ var InProcessRetryRunner = class InProcessRetryRunner {
609
+ constructor(sleeper) {
610
+ this.sleeper = sleeper;
611
+ }
612
+ async run(policy, work) {
613
+ const spec = InProcessRetryRunner.normalizePolicy(policy);
614
+ let lastError;
615
+ for (let attempt = 1; attempt <= spec.maxAttempts; attempt++) try {
616
+ return await work();
617
+ } catch (error) {
618
+ lastError = error;
619
+ if (attempt >= spec.maxAttempts) break;
620
+ const delayMs = InProcessRetryRunner.delayAfterFailureMs(spec, attempt);
621
+ await this.sleeper.sleep(delayMs);
622
+ }
623
+ throw lastError instanceof Error ? lastError : new Error(String(lastError));
624
+ }
625
+ static delayAfterFailureMs(spec, failedAttempt) {
626
+ if (spec.kind === "none") return 0;
627
+ if (spec.kind === "fixed") return spec.delayMs;
628
+ const exponent = failedAttempt - 1;
629
+ let ms = spec.initialDelayMs * Math.pow(spec.multiplier, exponent);
630
+ if (spec.jitter === true) ms *= 1 + Math.random() * .2;
631
+ if (spec.maxDelayMs !== void 0 && ms > spec.maxDelayMs) ms = spec.maxDelayMs;
632
+ return Math.max(0, Math.floor(ms));
633
+ }
634
+ static normalizePolicy(policy) {
635
+ if (policy === void 0) return {
636
+ kind: "none",
637
+ maxAttempts: 1
638
+ };
639
+ if (typeof policy !== "object" || policy === null) return {
640
+ kind: "none",
641
+ maxAttempts: 1
642
+ };
643
+ const kind = policy.kind;
644
+ if (kind === "none") return {
645
+ kind: "none",
646
+ maxAttempts: 1
647
+ };
648
+ if (kind === "fixed") {
649
+ const p = policy;
650
+ return {
651
+ kind: "fixed",
652
+ maxAttempts: InProcessRetryRunner.assertPositiveInt(p.maxAttempts, "fixed.maxAttempts"),
653
+ delayMs: InProcessRetryRunner.assertNonNegativeFinite(p.delayMs, "fixed.delayMs")
654
+ };
655
+ }
656
+ if (kind === "exponential") {
657
+ const p = policy;
658
+ return {
659
+ kind: "exponential",
660
+ maxAttempts: InProcessRetryRunner.assertPositiveInt(p.maxAttempts, "exponential.maxAttempts"),
661
+ initialDelayMs: InProcessRetryRunner.assertNonNegativeFinite(p.initialDelayMs, "exponential.initialDelayMs"),
662
+ multiplier: InProcessRetryRunner.assertMultiplier(p.multiplier),
663
+ maxDelayMs: p.maxDelayMs === void 0 ? void 0 : InProcessRetryRunner.assertNonNegativeFinite(p.maxDelayMs, "exponential.maxDelayMs"),
664
+ jitter: p.jitter === true
665
+ };
666
+ }
667
+ return {
668
+ kind: "none",
669
+ maxAttempts: 1
670
+ };
671
+ }
672
+ static assertPositiveInt(value, label) {
673
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 1 || !Number.isInteger(value)) throw new Error(`Retry policy ${label} must be a positive integer`);
674
+ return value;
675
+ }
676
+ static assertNonNegativeFinite(value, label) {
677
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) throw new Error(`Retry policy ${label} must be a non-negative finite number`);
678
+ return value;
679
+ }
680
+ static assertMultiplier(value) {
681
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 1) throw new Error(`Retry policy exponential.multiplier must be >= 1`);
682
+ return value;
683
+ }
684
+ };
685
+
686
+ //#endregion
687
+ //#region src/execution/InProcessRetryRunnerFactory.ts
688
+ var InProcessRetryRunnerFactory = class {
689
+ create(defaultAsyncSleeper) {
690
+ return new InProcessRetryRunner(defaultAsyncSleeper);
691
+ }
692
+ };
693
+
694
+ //#endregion
695
+ //#region src/execution/NodeActivationRequestComposer.ts
696
+ /**
697
+ * Builds {@link NodeActivationRequest} values shared by workflow starters and continuation.
698
+ */
699
+ var NodeActivationRequestComposer = class {
700
+ constructor(activationIdFactory, credentialResolverFactory) {
701
+ this.activationIdFactory = activationIdFactory;
702
+ this.credentialResolverFactory = credentialResolverFactory;
703
+ }
704
+ createSingleFromDefinition(args) {
705
+ return this.createSingleFromDefinitionWithActivation({
706
+ ...args,
707
+ activationId: this.activationIdFactory.makeActivationId()
708
+ });
709
+ }
710
+ createSingleFromDefinitionWithActivation(args) {
711
+ const ctx = this.createNodeExecutionContext(args, args.definition, args.activationId);
712
+ return {
713
+ kind: "single",
714
+ runId: args.runId,
715
+ activationId: args.activationId,
716
+ workflowId: args.workflowId,
717
+ nodeId: args.definition.id,
718
+ parent: args.parent,
719
+ executionOptions: args.executionOptions,
720
+ batchId: args.batchId,
721
+ input: args.input,
722
+ ctx
723
+ };
724
+ }
725
+ createFromPlannedActivation(args) {
726
+ const activationId = this.activationIdFactory.makeActivationId();
727
+ const ctx = this.createNodeExecutionContext(args, args.nodeDefinition, activationId);
728
+ if (args.next.kind === "multi") return {
729
+ kind: "multi",
730
+ runId: args.runId,
731
+ activationId,
732
+ workflowId: args.workflowId,
733
+ nodeId: args.nodeDefinition.id,
734
+ parent: args.parent,
735
+ executionOptions: args.executionOptions,
736
+ batchId: args.next.batchId,
737
+ inputsByPort: args.next.inputsByPort,
738
+ ctx
739
+ };
740
+ return {
741
+ kind: "single",
742
+ runId: args.runId,
743
+ activationId,
744
+ workflowId: args.workflowId,
745
+ nodeId: args.nodeDefinition.id,
746
+ parent: args.parent,
747
+ executionOptions: args.executionOptions,
748
+ batchId: args.next.batchId,
749
+ input: args.next.input,
750
+ ctx
751
+ };
752
+ }
753
+ createNodeExecutionContext(args, definition, activationId) {
754
+ return {
755
+ ...args.base,
756
+ data: args.data,
757
+ nodeId: definition.id,
758
+ activationId,
759
+ config: definition.config,
760
+ binary: args.base.binary.forNode({
761
+ nodeId: definition.id,
762
+ activationId
763
+ }),
764
+ getCredential: this.credentialResolverFactory.create(args.workflowId, definition.id, definition.config)
765
+ };
766
+ }
767
+ };
768
+
769
+ //#endregion
770
+ //#region src/execution/NodeExecutor.ts
771
+ var NodeExecutor = class {
772
+ constructor(nodeInstanceFactory, retryRunner) {
773
+ this.nodeInstanceFactory = nodeInstanceFactory;
774
+ this.retryRunner = retryRunner;
775
+ }
776
+ async execute(request) {
777
+ const policy = request.ctx.config.retryPolicy;
778
+ return await this.retryRunner.run(policy, async () => {
779
+ const nodeInstance = this.nodeInstanceFactory.createByType(request.ctx.config.type);
780
+ if (request.kind === "multi") return await this.executeMultiInputNode(request, nodeInstance);
781
+ return await this.executeSingleInputNode(request, nodeInstance);
782
+ });
783
+ }
784
+ async executeMultiInputNode(request, node$1) {
785
+ const multiInputNode = node$1;
786
+ if (typeof multiInputNode.executeMulti !== "function") throw new Error(`Node ${request.nodeId} does not support executeMulti but received multi-input activation`);
787
+ return await multiInputNode.executeMulti(request.inputsByPort, request.ctx);
788
+ }
789
+ async executeSingleInputNode(request, node$1) {
790
+ const singleInputNode = node$1;
791
+ if (typeof singleInputNode.execute !== "function") throw new Error(`Node ${request.nodeId} does not support execute but received single-input activation`);
792
+ return await singleInputNode.execute(request.input, request.ctx);
793
+ }
794
+ };
795
+
796
+ //#endregion
797
+ //#region src/execution/NodeExecutorFactory.ts
798
+ var NodeExecutorFactory = class {
799
+ create(workflowNodeInstanceFactory, retryRunner) {
800
+ return new NodeExecutor(workflowNodeInstanceFactory, retryRunner);
801
+ }
802
+ };
803
+
804
+ //#endregion
805
+ //#region src/workflowSnapshots/MissingRuntimeExecutionMarker.ts
806
+ var MissingRuntimeExecutionMarker = class {
807
+ isMarked(config) {
808
+ return Boolean(config?.missingRuntime);
809
+ }
810
+ };
811
+
812
+ //#endregion
813
+ //#region src/workflowSnapshots/MissingRuntimeNodeToken.ts
814
+ var MissingRuntimeNodeToken = class {};
815
+
816
+ //#endregion
817
+ //#region src/workflowSnapshots/MissingRuntimeNodeConfig.ts
818
+ var MissingRuntimeNodeConfig = class {
819
+ kind = "node";
820
+ type = MissingRuntimeNodeToken;
821
+ constructor(name, missingTokenId, missingRuntime = true) {
822
+ this.name = name;
823
+ this.missingTokenId = missingTokenId;
824
+ this.missingRuntime = missingRuntime;
825
+ }
826
+ };
827
+
828
+ //#endregion
829
+ //#region src/workflowSnapshots/MissingRuntimeTriggerToken.ts
830
+ var MissingRuntimeTriggerToken = class {};
831
+
832
+ //#endregion
833
+ //#region src/workflowSnapshots/MissingRuntimeTriggerConfig.ts
834
+ var MissingRuntimeTriggerConfig = class {
835
+ kind = "trigger";
836
+ type = MissingRuntimeTriggerToken;
837
+ constructor(name, missingTokenId, missingRuntime = true) {
838
+ this.name = name;
839
+ this.missingTokenId = missingTokenId;
840
+ this.missingRuntime = missingRuntime;
841
+ }
842
+ };
843
+
844
+ //#endregion
845
+ //#region src/workflowSnapshots/MissingRuntimeFallbacksFactory.ts
846
+ var MissingRuntimeFallbacks = class {
847
+ createDefinition(snapshotNode) {
848
+ if (snapshotNode.kind === "trigger") return {
849
+ id: snapshotNode.id,
850
+ kind: "trigger",
851
+ name: snapshotNode.name,
852
+ type: MissingRuntimeTriggerToken,
853
+ config: new MissingRuntimeTriggerConfig(snapshotNode.name ?? snapshotNode.id, snapshotNode.nodeTokenId)
854
+ };
855
+ return {
856
+ id: snapshotNode.id,
857
+ kind: "node",
858
+ name: snapshotNode.name,
859
+ type: MissingRuntimeNodeToken,
860
+ config: new MissingRuntimeNodeConfig(snapshotNode.name ?? snapshotNode.id, snapshotNode.nodeTokenId)
861
+ };
862
+ }
863
+ };
864
+
865
+ //#endregion
866
+ //#region src/workflowSnapshots/MissingRuntimeNode.ts
867
+ var MissingRuntimeNode = class {
868
+ kind = "node";
869
+ outputPorts = ["main"];
870
+ async execute(items) {
871
+ return { main: items };
872
+ }
873
+ };
874
+
875
+ //#endregion
876
+ //#region src/workflowSnapshots/MissingRuntimeTrigger.ts
877
+ var MissingRuntimeTrigger = class {
878
+ kind = "trigger";
879
+ outputPorts = ["main"];
880
+ async setup(_ctx) {}
881
+ async execute(items) {
882
+ return { main: items };
883
+ }
884
+ };
885
+
886
+ //#endregion
887
+ //#region src/workflowSnapshots/PersistedRuntimeTypeIdFactory.ts
888
+ var PersistedRuntimeTypeIdFactory = class {
889
+ static fromMetadata(args) {
890
+ const metadata = getPersistedRuntimeTypeMetadata(args.type);
891
+ if (!metadata) return;
892
+ const packageName = metadata.packageName;
893
+ if (!packageName) return;
894
+ return `${packageName}::${metadata.persistedName}`;
895
+ }
896
+ };
897
+
898
+ //#endregion
899
+ //#region src/workflowSnapshots/PersistedWorkflowTokenRegistry.ts
900
+ var PersistedWorkflowTokenRegistry = class {
901
+ tokensById = /* @__PURE__ */ new Map();
902
+ tokenIdsByToken = /* @__PURE__ */ new Map();
903
+ /**
904
+ * Register a token with its package ID. Token ID is inferred as `packageId::tokenName`.
905
+ */
906
+ register(type, packageId, persistedNameOverride) {
907
+ const tokenId = `${packageId}::${persistedNameOverride ?? this.displayNameForTypeToken(type)}`;
908
+ this.tokensById.set(tokenId, type);
909
+ this.tokenIdsByToken.set(type, tokenId);
910
+ return tokenId;
911
+ }
912
+ /**
913
+ * Register all decorated runtime types discovered in workflows.
914
+ */
915
+ registerFromWorkflows(workflows) {
916
+ for (const workflow of workflows) for (const node$1 of workflow.nodes) {
917
+ this.registerDecoratedType(node$1.type);
918
+ this.registerDecoratedType(node$1.config.type);
919
+ this.registerNestedTypes(node$1.config);
920
+ }
921
+ }
922
+ registerDecoratedType(type) {
923
+ if (this.tokenIdsByToken.has(type)) return;
924
+ const tokenId = PersistedRuntimeTypeIdFactory.fromMetadata({ type });
925
+ if (!tokenId) return;
926
+ this.tokensById.set(tokenId, type);
927
+ this.tokenIdsByToken.set(type, tokenId);
928
+ }
929
+ registerNestedTypes(value) {
930
+ if (Array.isArray(value)) {
931
+ for (const entry of value) this.registerNestedTypes(entry);
932
+ return;
933
+ }
934
+ if (!value || typeof value !== "object") return;
935
+ const record = value;
936
+ const type = this.asTypeToken(record.type);
937
+ if (type) this.registerDecoratedType(type);
938
+ for (const v of Object.values(record)) this.registerNestedTypes(v);
939
+ }
940
+ displayNameForTypeToken(token) {
941
+ if (typeof token === "function" && token.name) return token.name;
942
+ if (typeof token === "string") return token;
943
+ return "";
944
+ }
945
+ asTypeToken(value) {
946
+ if (typeof value === "function" || typeof value === "string" || typeof value === "symbol") return value;
947
+ }
948
+ getTokenId(token) {
949
+ const existing = this.tokenIdsByToken.get(token);
950
+ if (existing) return existing;
951
+ const tokenId = PersistedRuntimeTypeIdFactory.fromMetadata({ type: token });
952
+ if (!tokenId) return;
953
+ this.tokensById.set(tokenId, token);
954
+ this.tokenIdsByToken.set(token, tokenId);
955
+ return tokenId;
956
+ }
957
+ resolve(tokenId) {
958
+ return this.tokensById.get(tokenId);
959
+ }
960
+ };
961
+
962
+ //#endregion
963
+ //#region src/workflowSnapshots/WorkflowSnapshotResolver.ts
964
+ var WorkflowSnapshotResolver = class {
965
+ constructor(workflowRepository, tokenRegistry, codec, missingRuntimeFallbacks) {
966
+ this.workflowRepository = workflowRepository;
967
+ this.tokenRegistry = tokenRegistry;
968
+ this.codec = codec;
969
+ this.missingRuntimeFallbacks = missingRuntimeFallbacks;
970
+ }
971
+ resolve(args) {
972
+ const liveWorkflow = this.workflowRepository.get(args.workflowId);
973
+ if (!args.workflowSnapshot) return liveWorkflow;
974
+ if (!liveWorkflow) return this.rebuildWorkflow(args.workflowSnapshot, void 0);
975
+ return this.rebuildWorkflow(args.workflowSnapshot, liveWorkflow);
976
+ }
977
+ rebuildWorkflow(snapshot, liveWorkflow) {
978
+ const liveNodesById = new Map((liveWorkflow?.nodes ?? []).map((node$1) => [node$1.id, node$1]));
979
+ const nodes = snapshot.nodes.map((snapshotNode) => {
980
+ const liveNode = liveNodesById.get(snapshotNode.id);
981
+ if (!this.isCompatibleLiveNode(liveNode, snapshotNode)) return this.missingRuntimeFallbacks.createDefinition(snapshotNode);
982
+ return {
983
+ id: snapshotNode.id,
984
+ kind: snapshotNode.kind,
985
+ name: snapshotNode.name ?? liveNode.name,
986
+ type: liveNode.type,
987
+ config: this.codec.hydrate(snapshotNode, liveNode.config)
988
+ };
989
+ });
990
+ const nodeIds = new Set(nodes.map((node$1) => node$1.id));
991
+ const connectionsFromSnapshot = snapshot.connections?.map((connection) => ({
992
+ ...connection,
993
+ childNodeIds: connection.childNodeIds.filter((childId) => nodeIds.has(childId))
994
+ })).filter((connection) => connection.childNodeIds.length > 0) ?? [];
995
+ return {
996
+ id: snapshot.id,
997
+ name: snapshot.name,
998
+ nodes,
999
+ edges: snapshot.edges.filter((edge) => nodeIds.has(edge.from.nodeId) && nodeIds.has(edge.to.nodeId)),
1000
+ ...connectionsFromSnapshot.length > 0 ? { connections: connectionsFromSnapshot } : {},
1001
+ ...liveWorkflow?.discoveryPathSegments !== void 0 ? { discoveryPathSegments: liveWorkflow.discoveryPathSegments } : {}
1002
+ };
1003
+ }
1004
+ isCompatibleLiveNode(liveNode, snapshotNode) {
1005
+ if (!liveNode || liveNode.kind !== snapshotNode.kind) return false;
1006
+ if (!snapshotNode.nodeTokenId || !snapshotNode.configTokenId) throw new Error(`Persisted workflow snapshot node "${snapshotNode.id}" is missing stable token ids.`);
1007
+ const liveNodeTokenId = this.resolveLiveTokenId(liveNode.type);
1008
+ const liveConfigTokenId = this.resolveLiveTokenId(liveNode.config.type);
1009
+ return liveNodeTokenId === snapshotNode.nodeTokenId && liveConfigTokenId === snapshotNode.configTokenId;
1010
+ }
1011
+ resolveLiveTokenId(type) {
1012
+ const registeredTokenId = this.tokenRegistry.getTokenId(type);
1013
+ if (registeredTokenId) return registeredTokenId;
1014
+ if (typeof type === "function" && type.name) return type.name;
1015
+ if (typeof type === "string") return type;
1016
+ }
1017
+ };
1018
+
1019
+ //#endregion
1020
+ //#region src/execution/NodeInstanceFactory.ts
1021
+ var NodeInstanceFactory = class {
1022
+ constructor(nodeResolver) {
1023
+ this.nodeResolver = nodeResolver;
1024
+ }
1025
+ createNodes(workflow) {
1026
+ const nodeInstances = /* @__PURE__ */ new Map();
1027
+ for (const definition of workflow.nodes) nodeInstances.set(definition.id, this.createNode(definition));
1028
+ return nodeInstances;
1029
+ }
1030
+ createNode(definition) {
1031
+ return this.createByType(definition.type);
1032
+ }
1033
+ createByType(type) {
1034
+ if (type === MissingRuntimeNodeToken) return new MissingRuntimeNode();
1035
+ if (type === MissingRuntimeTriggerToken) return new MissingRuntimeTrigger();
1036
+ return this.nodeResolver.resolve(type);
1037
+ }
1038
+ };
1039
+
1040
+ //#endregion
1041
+ //#region src/execution/NodeInstanceFactoryFactory.ts
1042
+ var NodeInstanceFactoryFactory = class {
1043
+ create(nodeResolver) {
1044
+ return new NodeInstanceFactory(nodeResolver);
1045
+ }
1046
+ };
1047
+
1048
+ //#endregion
1049
+ //#region src/execution/NodeRunStateWriter.ts
1050
+ var NodeRunStateWriter = class {
1051
+ chain = Promise.resolve();
1052
+ constructor(workflowExecutionRepository, runId, workflowId, parent, publishNodeEvent) {
1053
+ this.workflowExecutionRepository = workflowExecutionRepository;
1054
+ this.runId = runId;
1055
+ this.workflowId = workflowId;
1056
+ this.parent = parent;
1057
+ this.publishNodeEvent = publishNodeEvent;
1058
+ }
1059
+ markQueued(args) {
1060
+ return this.enqueue(async () => {
1061
+ const state = await this.loadState();
1062
+ const previous = state.nodeSnapshotsByNodeId?.[args.nodeId];
1063
+ const queuedAt = (/* @__PURE__ */ new Date()).toISOString();
1064
+ const snapshot = NodeExecutionSnapshotFactory.queued({
1065
+ runId: this.runId,
1066
+ workflowId: this.workflowId,
1067
+ nodeId: args.nodeId,
1068
+ activationId: args.activationId ?? previous?.activationId ?? `synthetic_${args.nodeId}`,
1069
+ parent: this.parent,
1070
+ queuedAt,
1071
+ inputsByPort: args.inputsByPort ?? previous?.inputsByPort ?? NodeInputsByPortFactory.empty()
1072
+ });
1073
+ await this.saveSnapshot(state, snapshot);
1074
+ await this.publishNodeEvent("nodeQueued", snapshot);
1075
+ });
1076
+ }
1077
+ markRunning(args) {
1078
+ return this.enqueue(async () => {
1079
+ const state = await this.loadState();
1080
+ const previous = state.nodeSnapshotsByNodeId?.[args.nodeId];
1081
+ const startedAt = (/* @__PURE__ */ new Date()).toISOString();
1082
+ const snapshot = NodeExecutionSnapshotFactory.running({
1083
+ previous,
1084
+ runId: this.runId,
1085
+ workflowId: this.workflowId,
1086
+ nodeId: args.nodeId,
1087
+ activationId: args.activationId ?? previous?.activationId ?? `synthetic_${args.nodeId}`,
1088
+ parent: this.parent,
1089
+ startedAt,
1090
+ inputsByPort: args.inputsByPort ?? previous?.inputsByPort ?? NodeInputsByPortFactory.empty()
1091
+ });
1092
+ await this.saveSnapshot(state, snapshot);
1093
+ await this.publishNodeEvent("nodeStarted", snapshot);
1094
+ });
1095
+ }
1096
+ markCompleted(args) {
1097
+ return this.enqueue(async () => {
1098
+ const state = await this.loadState();
1099
+ const previous = state.nodeSnapshotsByNodeId?.[args.nodeId];
1100
+ const finishedAt = (/* @__PURE__ */ new Date()).toISOString();
1101
+ const snapshot = NodeExecutionSnapshotFactory.completed({
1102
+ previous,
1103
+ runId: this.runId,
1104
+ workflowId: this.workflowId,
1105
+ nodeId: args.nodeId,
1106
+ activationId: args.activationId ?? previous?.activationId ?? `synthetic_${args.nodeId}`,
1107
+ parent: this.parent,
1108
+ finishedAt,
1109
+ inputsByPort: args.inputsByPort ?? previous?.inputsByPort ?? NodeInputsByPortFactory.empty(),
1110
+ outputs: args.outputs ?? previous?.outputs ?? {}
1111
+ });
1112
+ await this.saveSnapshot(state, snapshot);
1113
+ await this.publishNodeEvent("nodeCompleted", snapshot);
1114
+ });
1115
+ }
1116
+ markFailed(args) {
1117
+ return this.enqueue(async () => {
1118
+ const state = await this.loadState();
1119
+ const previous = state.nodeSnapshotsByNodeId?.[args.nodeId];
1120
+ const finishedAt = (/* @__PURE__ */ new Date()).toISOString();
1121
+ const snapshot = NodeExecutionSnapshotFactory.failed({
1122
+ previous,
1123
+ runId: this.runId,
1124
+ workflowId: this.workflowId,
1125
+ nodeId: args.nodeId,
1126
+ activationId: args.activationId ?? previous?.activationId ?? `synthetic_${args.nodeId}`,
1127
+ parent: this.parent,
1128
+ finishedAt,
1129
+ inputsByPort: args.inputsByPort ?? previous?.inputsByPort ?? NodeInputsByPortFactory.empty(),
1130
+ error: args.error
1131
+ });
1132
+ await this.saveSnapshot(state, snapshot);
1133
+ await this.publishNodeEvent("nodeFailed", snapshot);
1134
+ });
1135
+ }
1136
+ appendConnectionInvocation(args) {
1137
+ return this.enqueue(async () => {
1138
+ const state = await this.loadState();
1139
+ const updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1140
+ const record = {
1141
+ invocationId: args.invocationId,
1142
+ runId: this.runId,
1143
+ workflowId: this.workflowId,
1144
+ connectionNodeId: args.connectionNodeId,
1145
+ parentAgentNodeId: args.parentAgentNodeId,
1146
+ parentAgentActivationId: args.parentAgentActivationId,
1147
+ status: args.status,
1148
+ managedInput: args.managedInput,
1149
+ managedOutput: args.managedOutput,
1150
+ error: args.error,
1151
+ queuedAt: args.queuedAt,
1152
+ startedAt: args.startedAt,
1153
+ finishedAt: args.finishedAt,
1154
+ updatedAt
1155
+ };
1156
+ await this.workflowExecutionRepository.save({
1157
+ ...state,
1158
+ connectionInvocations: [...state.connectionInvocations ?? [], record]
1159
+ });
1160
+ });
1161
+ }
1162
+ enqueue(work) {
1163
+ const next = this.chain.then(work);
1164
+ this.chain = next.catch(() => void 0);
1165
+ return next;
1166
+ }
1167
+ async loadState() {
1168
+ const state = await this.workflowExecutionRepository.load(this.runId);
1169
+ if (!state) throw new Error(`Unknown runId: ${this.runId}`);
1170
+ return state;
1171
+ }
1172
+ async saveSnapshot(state, snapshot) {
1173
+ await this.workflowExecutionRepository.save({
1174
+ ...state,
1175
+ nodeSnapshotsByNodeId: {
1176
+ ...state.nodeSnapshotsByNodeId ?? {},
1177
+ [snapshot.nodeId]: snapshot
1178
+ }
1179
+ });
1180
+ }
1181
+ };
1182
+
1183
+ //#endregion
1184
+ //#region src/execution/NodeRunStateWriterFactory.ts
1185
+ var NodeRunStateWriterFactory = class {
1186
+ constructor(workflowExecutionRepository, nodeEventPublisher) {
1187
+ this.workflowExecutionRepository = workflowExecutionRepository;
1188
+ this.nodeEventPublisher = nodeEventPublisher;
1189
+ }
1190
+ create(runId, workflowId, parent) {
1191
+ return new NodeRunStateWriter(this.workflowExecutionRepository, runId, workflowId, parent, async (kind, snapshot) => {
1192
+ await this.nodeEventPublisher.publish(kind, snapshot);
1193
+ });
1194
+ }
1195
+ };
1196
+
1197
+ //#endregion
1198
+ //#region src/execution/PersistedRunStateTerminalBuilder.ts
1199
+ /**
1200
+ * Merges common terminal-run fields onto a loaded {@link PersistedRunState} without repeating object literals.
1201
+ */
1202
+ var PersistedRunStateTerminalBuilder = class {
1203
+ mergeTerminal(args) {
1204
+ return {
1205
+ ...args.state,
1206
+ engineCounters: args.engineCounters,
1207
+ status: args.status,
1208
+ pending: void 0,
1209
+ queue: args.queue,
1210
+ outputsByNode: args.outputsByNode,
1211
+ nodeSnapshotsByNodeId: args.nodeSnapshotsByNodeId
1212
+ };
1213
+ }
1214
+ };
1215
+
1216
+ //#endregion
1217
+ //#region src/execution/RunStateSemantics.ts
1218
+ var RunStateSemantics = class {
1219
+ constructor(missingRuntimeExecutionMarker) {
1220
+ this.missingRuntimeExecutionMarker = missingRuntimeExecutionMarker;
1221
+ }
1222
+ isStopConditionSatisfied(stopCondition, nodeId) {
1223
+ if (!stopCondition || stopCondition.kind === "workflowCompleted") return false;
1224
+ return stopCondition.nodeId === nodeId;
1225
+ }
1226
+ resolveResultOutputs(workflow, stopCondition, outputsByNode) {
1227
+ if (stopCondition?.kind === "nodeCompleted") return outputsByNode[stopCondition.nodeId]?.main ?? [];
1228
+ return outputsByNode[WorkflowExecutableNodeClassifierFactory.create(workflow).lastExecutableNodeIdInDefinitionOrder(workflow)]?.main ?? [];
1229
+ }
1230
+ applySkippedSnapshots(args) {
1231
+ const snapshots = { ...args.currentState.nodeSnapshotsByNodeId };
1232
+ const skippedPinnedNodeIds = new Set(args.preservedPinnedNodeIds.filter((nodeId) => args.skippedNodeIds.includes(nodeId)));
1233
+ for (const nodeId of args.skippedNodeIds) if (args.currentState.mutableState?.nodesById?.[nodeId]?.pinnedOutputsByPort) skippedPinnedNodeIds.add(nodeId);
1234
+ for (const nodeId of skippedPinnedNodeIds) {
1235
+ const previous = snapshots[nodeId];
1236
+ snapshots[nodeId] = NodeExecutionSnapshotFactory.completed({
1237
+ previous,
1238
+ runId: args.runId,
1239
+ workflowId: args.workflowId,
1240
+ nodeId,
1241
+ activationId: previous?.activationId ?? `synthetic_${nodeId}`,
1242
+ parent: args.parent,
1243
+ finishedAt: args.finishedAt,
1244
+ inputsByPort: previous?.inputsByPort ?? NodeInputsByPortFactory.empty(),
1245
+ outputs: args.currentState.outputsByNode[nodeId] ?? {},
1246
+ fromPinnedOutput: true
1247
+ });
1248
+ }
1249
+ return snapshots;
1250
+ }
1251
+ applyPinnedQueueSkips(args) {
1252
+ let changed = true;
1253
+ while (changed) {
1254
+ changed = false;
1255
+ for (let index = 0; index < args.queue.length; index += 1) {
1256
+ const queueEntry = args.queue[index];
1257
+ const pinnedOutputs = args.mutableState?.nodesById?.[queueEntry.nodeId]?.pinnedOutputsByPort;
1258
+ if (!pinnedOutputs) continue;
1259
+ args.queue.splice(index, 1);
1260
+ const previous = args.nodeSnapshotsByNodeId[queueEntry.nodeId];
1261
+ args.nodeSnapshotsByNodeId[queueEntry.nodeId] = NodeExecutionSnapshotFactory.completed({
1262
+ previous,
1263
+ runId: args.runId,
1264
+ workflowId: args.workflowId,
1265
+ nodeId: queueEntry.nodeId,
1266
+ activationId: previous?.activationId ?? `synthetic_${queueEntry.nodeId}`,
1267
+ parent: args.parent,
1268
+ finishedAt: args.finishedAt,
1269
+ inputsByPort: this.resolveQueueEntryInputsByPort(queueEntry),
1270
+ outputs: pinnedOutputs,
1271
+ fromPinnedOutput: true
1272
+ });
1273
+ args.data.setOutputs(queueEntry.nodeId, pinnedOutputs);
1274
+ args.planner.applyOutputs(args.queue, {
1275
+ fromNodeId: queueEntry.nodeId,
1276
+ outputs: pinnedOutputs,
1277
+ batchId: queueEntry.batchId ?? "batch_1"
1278
+ });
1279
+ changed = true;
1280
+ break;
1281
+ }
1282
+ }
1283
+ }
1284
+ createFinishedSnapshot(args) {
1285
+ const definition = args.workflow.nodes.find((node$1) => node$1.id === args.nodeId);
1286
+ if (this.missingRuntimeExecutionMarker.isMarked(definition?.config)) return NodeExecutionSnapshotFactory.skipped(args);
1287
+ return NodeExecutionSnapshotFactory.completed(args);
1288
+ }
1289
+ resolveQueueEntryInputsByPort(queueEntry) {
1290
+ if (queueEntry.collect) return queueEntry.collect.received;
1291
+ return { [queueEntry.toInput ?? "in"]: queueEntry.input };
1292
+ }
1293
+ };
1294
+
1295
+ //#endregion
1296
+ //#region src/execution/WorkflowRunExecutionContextFactory.ts
1297
+ /**
1298
+ * Shared {@link ExecutionContextFactory#create} wiring for workflow runners (base context before node-specific fields).
1299
+ */
1300
+ var WorkflowRunExecutionContextFactory = class {
1301
+ constructor(executionContextFactory, credentialResolverFactory) {
1302
+ this.executionContextFactory = executionContextFactory;
1303
+ this.credentialResolverFactory = credentialResolverFactory;
1304
+ }
1305
+ create(args) {
1306
+ return this.executionContextFactory.create({
1307
+ runId: args.runId,
1308
+ workflowId: args.workflowId,
1309
+ parent: args.parent,
1310
+ subworkflowDepth: args.subworkflowDepth,
1311
+ engineMaxNodeActivations: args.engineMaxNodeActivations,
1312
+ engineMaxSubworkflowDepth: args.engineMaxSubworkflowDepth,
1313
+ data: args.data,
1314
+ nodeState: args.nodeState,
1315
+ getCredential: this.credentialResolverFactory.create(args.workflowId, args.nodeId)
1316
+ });
1317
+ }
1318
+ };
1319
+
1320
+ //#endregion
1321
+ //#region src/planning/WorkflowTopologyPlanner.ts
1322
+ var WorkflowTopology = class WorkflowTopology {
1323
+ constructor(defsById, outgoingByNode, incomingByNode, expectedInputsByNode, rootNodeIds) {
1324
+ this.defsById = defsById;
1325
+ this.outgoingByNode = outgoingByNode;
1326
+ this.incomingByNode = incomingByNode;
1327
+ this.expectedInputsByNode = expectedInputsByNode;
1328
+ this.rootNodeIds = rootNodeIds;
1329
+ }
1330
+ static fromWorkflow(wf) {
1331
+ const classifier = WorkflowExecutableNodeClassifierFactory.create(wf);
1332
+ const defs = /* @__PURE__ */ new Map();
1333
+ for (const n of wf.nodes) if (classifier.isExecutableNodeId(n.id)) defs.set(n.id, n);
1334
+ const outgoing = /* @__PURE__ */ new Map();
1335
+ for (const e of wf.edges) {
1336
+ if (!classifier.isExecutableNodeId(e.from.nodeId) || !classifier.isExecutableNodeId(e.to.nodeId)) continue;
1337
+ const list = outgoing.get(e.from.nodeId) ?? [];
1338
+ list.push({
1339
+ output: e.from.output,
1340
+ to: {
1341
+ nodeId: e.to.nodeId,
1342
+ input: e.to.input
1343
+ }
1344
+ });
1345
+ outgoing.set(e.from.nodeId, list);
1346
+ }
1347
+ const incomingByNode = /* @__PURE__ */ new Map();
1348
+ for (const e of wf.edges) {
1349
+ if (!classifier.isExecutableNodeId(e.from.nodeId) || !classifier.isExecutableNodeId(e.to.nodeId)) continue;
1350
+ const list = incomingByNode.get(e.to.nodeId) ?? [];
1351
+ list.push({
1352
+ from: {
1353
+ nodeId: e.from.nodeId,
1354
+ output: e.from.output
1355
+ },
1356
+ input: e.to.input
1357
+ });
1358
+ incomingByNode.set(e.to.nodeId, list);
1359
+ }
1360
+ const expected = /* @__PURE__ */ new Map();
1361
+ for (const [toNodeId, inputs] of incomingByNode.entries()) {
1362
+ const counts = /* @__PURE__ */ new Map();
1363
+ for (const edge of inputs) counts.set(edge.input, (counts.get(edge.input) ?? 0) + 1);
1364
+ for (const [k, n] of counts.entries()) if (n > 1) throw new Error(`Node ${toNodeId} has multiple edges into input '${k}'. Use a Merge node upstream.`);
1365
+ const order = [];
1366
+ const seen = /* @__PURE__ */ new Set();
1367
+ for (const edge of inputs) {
1368
+ if (seen.has(edge.input)) continue;
1369
+ seen.add(edge.input);
1370
+ order.push(edge.input);
1371
+ }
1372
+ expected.set(toNodeId, order);
1373
+ }
1374
+ return new WorkflowTopology(defs, outgoing, incomingByNode, expected, wf.nodes.filter((node$1) => classifier.isExecutableNodeId(node$1.id) && !incomingByNode.has(node$1.id)).map((node$1) => node$1.id));
1375
+ }
1376
+ };
1377
+
1378
+ //#endregion
1379
+ //#region src/orchestration/RunContinuationService.ts
1380
+ var RunContinuationService = class {
1381
+ constructor(activationIdFactory, workflowExecutionRepository, runDataFactory, runExecutionContextFactory, workflowSnapshotResolver, planningFactory, nodeStatePublisherFactory, credentialResolverFactory, nodeActivationRequestComposer, persistedRunStateTerminalBuilder, activationEnqueueService, nodeEventPublisher, semantics, waiters, policyErrorServices, terminalPersistence, executionLimitsPolicy) {
1382
+ this.activationIdFactory = activationIdFactory;
1383
+ this.workflowExecutionRepository = workflowExecutionRepository;
1384
+ this.runDataFactory = runDataFactory;
1385
+ this.runExecutionContextFactory = runExecutionContextFactory;
1386
+ this.workflowSnapshotResolver = workflowSnapshotResolver;
1387
+ this.planningFactory = planningFactory;
1388
+ this.nodeStatePublisherFactory = nodeStatePublisherFactory;
1389
+ this.credentialResolverFactory = credentialResolverFactory;
1390
+ this.nodeActivationRequestComposer = nodeActivationRequestComposer;
1391
+ this.persistedRunStateTerminalBuilder = persistedRunStateTerminalBuilder;
1392
+ this.activationEnqueueService = activationEnqueueService;
1393
+ this.nodeEventPublisher = nodeEventPublisher;
1394
+ this.semantics = semantics;
1395
+ this.waiters = waiters;
1396
+ this.policyErrorServices = policyErrorServices;
1397
+ this.terminalPersistence = terminalPersistence;
1398
+ this.executionLimitsPolicy = executionLimitsPolicy;
1399
+ }
1400
+ async markNodeRunning(args) {
1401
+ const state = await this.workflowExecutionRepository.load(args.runId);
1402
+ if (!state?.pending) return;
1403
+ if (state.pending.activationId !== args.activationId || state.pending.nodeId !== args.nodeId) return;
1404
+ const startedAt = (/* @__PURE__ */ new Date()).toISOString();
1405
+ const previous = state.nodeSnapshotsByNodeId?.[args.nodeId];
1406
+ const snapshot = NodeExecutionSnapshotFactory.running({
1407
+ previous,
1408
+ runId: state.runId,
1409
+ workflowId: state.workflowId,
1410
+ nodeId: args.nodeId,
1411
+ activationId: args.activationId,
1412
+ parent: state.parent,
1413
+ startedAt,
1414
+ inputsByPort: args.inputsByPort
1415
+ });
1416
+ await this.workflowExecutionRepository.save({
1417
+ ...state,
1418
+ nodeSnapshotsByNodeId: {
1419
+ ...state.nodeSnapshotsByNodeId ?? {},
1420
+ [args.nodeId]: snapshot
1421
+ }
1422
+ });
1423
+ await this.nodeEventPublisher.publish("nodeStarted", snapshot);
1424
+ }
1425
+ async resumeFromNodeResult(args) {
1426
+ const state = await this.workflowExecutionRepository.load(args.runId);
1427
+ if (!state) throw new Error(`Unknown runId: ${args.runId}`);
1428
+ if (state.status !== "pending" || !state.pending) throw new Error(`Run ${args.runId} is not pending`);
1429
+ if (state.pending.activationId !== args.activationId) throw new Error(`activationId mismatch for run ${args.runId}`);
1430
+ if (state.pending.nodeId !== args.nodeId) throw new Error(`nodeId mismatch for run ${args.runId}`);
1431
+ const wf = this.resolvePersistedWorkflow(state);
1432
+ if (!wf) throw new Error(`Unknown workflowId: ${state.workflowId}`);
1433
+ const { topology, planner } = this.planningFactory.create(wf);
1434
+ const data = this.runDataFactory.create(state.outputsByNode);
1435
+ const limits = this.resolveEngineLimitsFromState(state);
1436
+ const base = this.runExecutionContextFactory.create({
1437
+ runId: state.runId,
1438
+ workflowId: state.workflowId,
1439
+ nodeId: args.nodeId,
1440
+ parent: state.parent,
1441
+ subworkflowDepth: state.executionOptions?.subworkflowDepth ?? 0,
1442
+ engineMaxNodeActivations: limits.engineMaxNodeActivations,
1443
+ engineMaxSubworkflowDepth: limits.engineMaxSubworkflowDepth,
1444
+ data,
1445
+ nodeState: this.nodeStatePublisherFactory.create(state.runId, state.workflowId, state.parent)
1446
+ });
1447
+ data.setOutputs(args.nodeId, args.outputs);
1448
+ const completedAt = (/* @__PURE__ */ new Date()).toISOString();
1449
+ const completedSnapshot = this.semantics.createFinishedSnapshot({
1450
+ workflow: wf,
1451
+ previous: state.nodeSnapshotsByNodeId?.[args.nodeId],
1452
+ runId: state.runId,
1453
+ workflowId: state.workflowId,
1454
+ nodeId: args.nodeId,
1455
+ activationId: args.activationId,
1456
+ parent: state.parent,
1457
+ finishedAt: completedAt,
1458
+ inputsByPort: state.pending.inputsByPort,
1459
+ outputs: args.outputs
1460
+ });
1461
+ const completedActivations = (state.engineCounters?.completedNodeActivations ?? 0) + 1;
1462
+ const engineCounters = { completedNodeActivations: completedActivations };
1463
+ const maxNodeActivations = state.executionOptions?.maxNodeActivations ?? Number.MAX_SAFE_INTEGER;
1464
+ if (this.semantics.isStopConditionSatisfied(state.control?.stopCondition, args.nodeId)) {
1465
+ const completedState = this.persistedRunStateTerminalBuilder.mergeTerminal({
1466
+ state,
1467
+ engineCounters,
1468
+ status: "completed",
1469
+ queue: [],
1470
+ outputsByNode: data.dump(),
1471
+ nodeSnapshotsByNodeId: {
1472
+ ...state.nodeSnapshotsByNodeId ?? {},
1473
+ [args.nodeId]: completedSnapshot
1474
+ }
1475
+ });
1476
+ await this.workflowExecutionRepository.save(completedState);
1477
+ await this.nodeEventPublisher.publish("nodeCompleted", completedSnapshot);
1478
+ await this.terminalPersistence.maybeDeleteAfterTerminalState({
1479
+ workflow: wf,
1480
+ state: completedState,
1481
+ finalStatus: "completed",
1482
+ finishedAt: completedAt
1483
+ });
1484
+ const result$1 = {
1485
+ runId: state.runId,
1486
+ workflowId: state.workflowId,
1487
+ startedAt: state.startedAt,
1488
+ status: "completed",
1489
+ outputs: this.semantics.resolveResultOutputs(wf, state.control?.stopCondition, data.dump())
1490
+ };
1491
+ this.waiters.resolveRunCompletion(result$1);
1492
+ return result$1;
1493
+ }
1494
+ const batchId = state.pending.batchId ?? "batch_1";
1495
+ const queue = (state.queue ?? []).map((q) => ({
1496
+ ...q,
1497
+ batchId: q.batchId ?? batchId
1498
+ }));
1499
+ const nextNodeSnapshotsByNodeId = {
1500
+ ...state.nodeSnapshotsByNodeId ?? {},
1501
+ [args.nodeId]: completedSnapshot
1502
+ };
1503
+ planner.applyOutputs(queue, {
1504
+ fromNodeId: args.nodeId,
1505
+ outputs: args.outputs,
1506
+ batchId
1507
+ });
1508
+ this.semantics.applyPinnedQueueSkips({
1509
+ runId: state.runId,
1510
+ workflowId: state.workflowId,
1511
+ parent: state.parent,
1512
+ mutableState: state.mutableState,
1513
+ planner,
1514
+ queue,
1515
+ data,
1516
+ nodeSnapshotsByNodeId: nextNodeSnapshotsByNodeId,
1517
+ finishedAt: completedAt
1518
+ });
1519
+ let next;
1520
+ try {
1521
+ next = planner.nextActivation(queue);
1522
+ } catch (cause) {
1523
+ const completedDefinition = topology.defsById.get(args.nodeId);
1524
+ const completedNodeLabel = this.formatNodeLabel({
1525
+ definition: completedDefinition,
1526
+ nodeId: args.nodeId
1527
+ });
1528
+ const reason = cause instanceof Error ? cause.message : String(cause);
1529
+ throw new Error(`After completing ${completedNodeLabel}, the engine could not plan the next activation. ${reason} Outputs: ${this.formatOutputCounts(args.outputs)}.`, { cause });
1530
+ }
1531
+ if (!next) {
1532
+ const lastNodeId = WorkflowExecutableNodeClassifierFactory.create(wf).lastExecutableNodeIdInDefinitionOrder(wf);
1533
+ const outputs = data.getOutputItems(lastNodeId, "main");
1534
+ const completedState = this.persistedRunStateTerminalBuilder.mergeTerminal({
1535
+ state,
1536
+ engineCounters,
1537
+ status: "completed",
1538
+ queue: [],
1539
+ outputsByNode: data.dump(),
1540
+ nodeSnapshotsByNodeId: nextNodeSnapshotsByNodeId
1541
+ });
1542
+ await this.workflowExecutionRepository.save(completedState);
1543
+ await this.nodeEventPublisher.publish("nodeCompleted", completedSnapshot);
1544
+ await this.terminalPersistence.maybeDeleteAfterTerminalState({
1545
+ workflow: wf,
1546
+ state: completedState,
1547
+ finalStatus: "completed",
1548
+ finishedAt: completedAt
1549
+ });
1550
+ const result$1 = {
1551
+ runId: state.runId,
1552
+ workflowId: state.workflowId,
1553
+ startedAt: state.startedAt,
1554
+ status: "completed",
1555
+ outputs
1556
+ };
1557
+ this.waiters.resolveRunCompletion(result$1);
1558
+ return result$1;
1559
+ }
1560
+ if (completedActivations >= maxNodeActivations) {
1561
+ const message = `Run exceeded maxNodeActivations (${maxNodeActivations}) after ${completedActivations} completed node activations (next would be ${next.nodeId}).`;
1562
+ const failedState = this.persistedRunStateTerminalBuilder.mergeTerminal({
1563
+ state,
1564
+ engineCounters,
1565
+ status: "failed",
1566
+ queue: queue.map((q) => ({ ...q })),
1567
+ outputsByNode: data.dump(),
1568
+ nodeSnapshotsByNodeId: nextNodeSnapshotsByNodeId
1569
+ });
1570
+ await this.workflowExecutionRepository.save(failedState);
1571
+ await this.nodeEventPublisher.publish("nodeCompleted", completedSnapshot);
1572
+ await this.terminalPersistence.maybeDeleteAfterTerminalState({
1573
+ workflow: wf,
1574
+ state: failedState,
1575
+ finalStatus: "failed",
1576
+ finishedAt: completedAt
1577
+ });
1578
+ const result$1 = {
1579
+ runId: state.runId,
1580
+ workflowId: state.workflowId,
1581
+ startedAt: state.startedAt,
1582
+ status: "failed",
1583
+ error: { message }
1584
+ };
1585
+ this.waiters.resolveRunCompletion(result$1);
1586
+ return result$1;
1587
+ }
1588
+ const def = topology.defsById.get(next.nodeId);
1589
+ if (!def || def.kind !== "node") throw new Error(`Node ${next.nodeId} is not a runnable node`);
1590
+ const request = this.nodeActivationRequestComposer.createFromPlannedActivation({
1591
+ next,
1592
+ base,
1593
+ data,
1594
+ runId: state.runId,
1595
+ workflowId: state.workflowId,
1596
+ parent: state.parent,
1597
+ executionOptions: state.executionOptions,
1598
+ nodeDefinition: def
1599
+ });
1600
+ const { queuedSnapshot, result } = await this.activationEnqueueService.enqueueActivationWithSnapshot({
1601
+ runId: state.runId,
1602
+ workflowId: state.workflowId,
1603
+ startedAt: state.startedAt,
1604
+ parent: state.parent,
1605
+ executionOptions: state.executionOptions,
1606
+ control: state.control,
1607
+ workflowSnapshot: state.workflowSnapshot,
1608
+ mutableState: state.mutableState,
1609
+ policySnapshot: state.policySnapshot,
1610
+ pendingQueue: queue,
1611
+ request,
1612
+ previousNodeSnapshotsByNodeId: nextNodeSnapshotsByNodeId,
1613
+ planner,
1614
+ engineCounters,
1615
+ connectionInvocations: state.connectionInvocations ?? []
1616
+ });
1617
+ await this.nodeEventPublisher.publish("nodeCompleted", completedSnapshot);
1618
+ await this.nodeEventPublisher.publish("nodeQueued", queuedSnapshot);
1619
+ return result;
1620
+ }
1621
+ async resumeFromNodeError(args) {
1622
+ const state = await this.workflowExecutionRepository.load(args.runId);
1623
+ if (!state) throw new Error(`Unknown runId: ${args.runId}`);
1624
+ if (state.status !== "pending" || !state.pending) throw new Error(`Run ${args.runId} is not pending`);
1625
+ if (state.pending.activationId !== args.activationId) throw new Error(`activationId mismatch for run ${args.runId}`);
1626
+ if (state.pending.nodeId !== args.nodeId) throw new Error(`nodeId mismatch for run ${args.runId}`);
1627
+ const wf = this.resolvePersistedWorkflow(state);
1628
+ if (!wf) throw new Error(`Unknown workflowId: ${state.workflowId}`);
1629
+ const failedDefinition = WorkflowTopology.fromWorkflow(wf).defsById.get(args.nodeId);
1630
+ const webhookControlSignal = state.executionOptions?.webhook && failedDefinition?.kind === "trigger" ? this.asWebhookControlSignal(args.error) : void 0;
1631
+ if (webhookControlSignal) return await this.resumeFromWebhookControl({
1632
+ state,
1633
+ workflow: wf,
1634
+ args,
1635
+ signal: webhookControlSignal
1636
+ });
1637
+ if (failedDefinition && failedDefinition.kind === "node") {
1638
+ const nodeHandler = this.policyErrorServices.resolveNodeErrorHandler(failedDefinition.config.nodeErrorHandler);
1639
+ if (nodeHandler) try {
1640
+ const ctx = this.buildNodeExecutionContextForPending(state, wf, failedDefinition, args.nodeId);
1641
+ const inputsByPort = state.pending.inputsByPort;
1642
+ const portKeys = Object.keys(inputsByPort);
1643
+ const kind = portKeys.length === 1 && portKeys[0] === "in" ? "single" : "multi";
1644
+ const items = inputsByPort.in ?? [];
1645
+ const recovered = await nodeHandler.handle({
1646
+ kind,
1647
+ items,
1648
+ inputsByPort: kind === "multi" ? inputsByPort : void 0,
1649
+ ctx,
1650
+ error: args.error
1651
+ });
1652
+ return await this.resumeFromNodeResult({
1653
+ runId: args.runId,
1654
+ activationId: args.activationId,
1655
+ nodeId: args.nodeId,
1656
+ outputs: recovered
1657
+ });
1658
+ } catch {}
1659
+ }
1660
+ const finishedAt = (/* @__PURE__ */ new Date()).toISOString();
1661
+ const message = args.error?.message ?? String(args.error);
1662
+ const failedSnapshot = NodeExecutionSnapshotFactory.failed({
1663
+ previous: state.nodeSnapshotsByNodeId?.[args.nodeId],
1664
+ runId: state.runId,
1665
+ workflowId: state.workflowId,
1666
+ nodeId: args.nodeId,
1667
+ activationId: args.activationId,
1668
+ parent: state.parent,
1669
+ finishedAt,
1670
+ inputsByPort: state.pending.inputsByPort,
1671
+ error: args.error
1672
+ });
1673
+ const failedState = this.persistedRunStateTerminalBuilder.mergeTerminal({
1674
+ state,
1675
+ engineCounters: state.engineCounters ?? { completedNodeActivations: 0 },
1676
+ status: "failed",
1677
+ queue: (state.queue ?? []).map((q) => ({ ...q })),
1678
+ outputsByNode: state.outputsByNode,
1679
+ nodeSnapshotsByNodeId: {
1680
+ ...state.nodeSnapshotsByNodeId ?? {},
1681
+ [args.nodeId]: failedSnapshot
1682
+ }
1683
+ });
1684
+ await this.workflowExecutionRepository.save(failedState);
1685
+ await this.nodeEventPublisher.publish("nodeFailed", failedSnapshot);
1686
+ const wfErr = this.policyErrorServices.resolveWorkflowErrorHandler(wf.workflowErrorHandler);
1687
+ if (wfErr) await Promise.resolve(wfErr.onError({
1688
+ runId: state.runId,
1689
+ workflowId: state.workflowId,
1690
+ workflow: wf,
1691
+ failedNodeId: args.nodeId,
1692
+ error: args.error,
1693
+ startedAt: state.startedAt,
1694
+ finishedAt
1695
+ }));
1696
+ await this.terminalPersistence.maybeDeleteAfterTerminalState({
1697
+ workflow: wf,
1698
+ state: failedState,
1699
+ finalStatus: "failed",
1700
+ finishedAt
1701
+ });
1702
+ const result = {
1703
+ runId: state.runId,
1704
+ workflowId: state.workflowId,
1705
+ startedAt: state.startedAt,
1706
+ status: "failed",
1707
+ error: { message }
1708
+ };
1709
+ this.waiters.resolveRunCompletion(result);
1710
+ return result;
1711
+ }
1712
+ async resumeFromStepResult(args) {
1713
+ return await this.resumeFromNodeResult(args);
1714
+ }
1715
+ async resumeFromStepError(args) {
1716
+ return await this.resumeFromNodeError(args);
1717
+ }
1718
+ async waitForCompletion(runId) {
1719
+ const existing = await this.workflowExecutionRepository.load(runId);
1720
+ if (existing?.status === "completed") {
1721
+ const wf = this.resolvePersistedWorkflow(existing);
1722
+ const outputs = wf ? this.semantics.resolveResultOutputs(wf, existing.control?.stopCondition, existing.outputsByNode) : [];
1723
+ return {
1724
+ runId: existing.runId,
1725
+ workflowId: existing.workflowId,
1726
+ startedAt: existing.startedAt,
1727
+ status: "completed",
1728
+ outputs
1729
+ };
1730
+ }
1731
+ if (existing?.status === "failed") return {
1732
+ runId: existing.runId,
1733
+ workflowId: existing.workflowId,
1734
+ startedAt: existing.startedAt,
1735
+ status: "failed",
1736
+ error: { message: "Run failed" }
1737
+ };
1738
+ const result = await this.waiters.waitForCompletion(runId);
1739
+ if (result.status !== "completed" && result.status !== "failed") throw new Error(`Unexpected run completion status: ${result.status}`);
1740
+ return result;
1741
+ }
1742
+ async waitForWebhookResponse(runId) {
1743
+ return await this.waiters.waitForWebhookResponse(runId);
1744
+ }
1745
+ async resumeFromWebhookControl(args) {
1746
+ const data = this.runDataFactory.create(args.state.outputsByNode);
1747
+ const { topology, planner } = this.planningFactory.create(args.workflow);
1748
+ const triggerOutputs = { main: args.signal.kind === "respondNowAndContinue" ? args.signal.continueItems ?? [] : args.signal.responseItems };
1749
+ data.setOutputs(args.args.nodeId, triggerOutputs);
1750
+ const completedSnapshot = this.semantics.createFinishedSnapshot({
1751
+ workflow: args.workflow,
1752
+ previous: args.state.nodeSnapshotsByNodeId?.[args.args.nodeId],
1753
+ runId: args.state.runId,
1754
+ workflowId: args.state.workflowId,
1755
+ nodeId: args.args.nodeId,
1756
+ activationId: args.args.activationId,
1757
+ parent: args.state.parent,
1758
+ finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
1759
+ inputsByPort: args.state.pending?.inputsByPort ?? NodeInputsByPortFactory.empty(),
1760
+ outputs: triggerOutputs
1761
+ });
1762
+ const completedActivations = (args.state.engineCounters?.completedNodeActivations ?? 0) + 1;
1763
+ const engineCounters = { completedNodeActivations: completedActivations };
1764
+ const maxNodeActivations = args.state.executionOptions?.maxNodeActivations ?? Number.MAX_SAFE_INTEGER;
1765
+ if (this.semantics.isStopConditionSatisfied(args.state.control?.stopCondition, args.args.nodeId)) {
1766
+ const completedState = this.persistedRunStateTerminalBuilder.mergeTerminal({
1767
+ state: args.state,
1768
+ engineCounters,
1769
+ status: "completed",
1770
+ queue: [],
1771
+ outputsByNode: data.dump(),
1772
+ nodeSnapshotsByNodeId: {
1773
+ ...args.state.nodeSnapshotsByNodeId ?? {},
1774
+ [args.args.nodeId]: completedSnapshot
1775
+ }
1776
+ });
1777
+ await this.workflowExecutionRepository.save(completedState);
1778
+ await this.nodeEventPublisher.publish("nodeCompleted", completedSnapshot);
1779
+ await this.terminalPersistence.maybeDeleteAfterTerminalState({
1780
+ workflow: args.workflow,
1781
+ state: completedState,
1782
+ finalStatus: "completed",
1783
+ finishedAt: completedSnapshot.finishedAt ?? completedSnapshot.updatedAt
1784
+ });
1785
+ this.waiters.resolveWebhookResponse({
1786
+ runId: args.state.runId,
1787
+ workflowId: args.state.workflowId,
1788
+ startedAt: args.state.startedAt,
1789
+ runStatus: "completed",
1790
+ response: args.signal.responseItems
1791
+ });
1792
+ const result$1 = {
1793
+ runId: args.state.runId,
1794
+ workflowId: args.state.workflowId,
1795
+ startedAt: args.state.startedAt,
1796
+ status: "completed",
1797
+ outputs: this.semantics.resolveResultOutputs(args.workflow, args.state.control?.stopCondition, data.dump())
1798
+ };
1799
+ this.waiters.resolveRunCompletion(result$1);
1800
+ return result$1;
1801
+ }
1802
+ if (args.signal.kind === "respondNow") {
1803
+ const completedState = this.persistedRunStateTerminalBuilder.mergeTerminal({
1804
+ state: args.state,
1805
+ engineCounters,
1806
+ status: "completed",
1807
+ queue: [],
1808
+ outputsByNode: data.dump(),
1809
+ nodeSnapshotsByNodeId: {
1810
+ ...args.state.nodeSnapshotsByNodeId ?? {},
1811
+ [args.args.nodeId]: completedSnapshot
1812
+ }
1813
+ });
1814
+ await this.workflowExecutionRepository.save(completedState);
1815
+ await this.nodeEventPublisher.publish("nodeCompleted", completedSnapshot);
1816
+ await this.terminalPersistence.maybeDeleteAfterTerminalState({
1817
+ workflow: args.workflow,
1818
+ state: completedState,
1819
+ finalStatus: "completed",
1820
+ finishedAt: completedSnapshot.finishedAt ?? completedSnapshot.updatedAt
1821
+ });
1822
+ const result$1 = {
1823
+ runId: args.state.runId,
1824
+ workflowId: args.state.workflowId,
1825
+ startedAt: args.state.startedAt,
1826
+ status: "completed",
1827
+ outputs: args.signal.responseItems
1828
+ };
1829
+ this.waiters.resolveWebhookResponse({
1830
+ runId: args.state.runId,
1831
+ workflowId: args.state.workflowId,
1832
+ startedAt: args.state.startedAt,
1833
+ runStatus: "completed",
1834
+ response: args.signal.responseItems
1835
+ });
1836
+ this.waiters.resolveRunCompletion(result$1);
1837
+ return result$1;
1838
+ }
1839
+ const batchId = args.state.pending?.batchId ?? "batch_1";
1840
+ const queue = (args.state.queue ?? []).map((entry) => ({
1841
+ ...entry,
1842
+ batchId: entry.batchId ?? batchId
1843
+ }));
1844
+ planner.applyOutputs(queue, {
1845
+ fromNodeId: args.args.nodeId,
1846
+ outputs: triggerOutputs,
1847
+ batchId
1848
+ });
1849
+ const next = planner.nextActivation(queue);
1850
+ if (!next) {
1851
+ const lastNodeId = WorkflowExecutableNodeClassifierFactory.create(args.workflow).lastExecutableNodeIdInDefinitionOrder(args.workflow);
1852
+ const outputs = data.getOutputItems(lastNodeId, "main");
1853
+ const completedState = this.persistedRunStateTerminalBuilder.mergeTerminal({
1854
+ state: args.state,
1855
+ engineCounters,
1856
+ status: "completed",
1857
+ queue: [],
1858
+ outputsByNode: data.dump(),
1859
+ nodeSnapshotsByNodeId: {
1860
+ ...args.state.nodeSnapshotsByNodeId ?? {},
1861
+ [args.args.nodeId]: completedSnapshot
1862
+ }
1863
+ });
1864
+ await this.workflowExecutionRepository.save(completedState);
1865
+ await this.nodeEventPublisher.publish("nodeCompleted", completedSnapshot);
1866
+ await this.terminalPersistence.maybeDeleteAfterTerminalState({
1867
+ workflow: args.workflow,
1868
+ state: completedState,
1869
+ finalStatus: "completed",
1870
+ finishedAt: completedSnapshot.finishedAt ?? completedSnapshot.updatedAt
1871
+ });
1872
+ const result$1 = {
1873
+ runId: args.state.runId,
1874
+ workflowId: args.state.workflowId,
1875
+ startedAt: args.state.startedAt,
1876
+ status: "completed",
1877
+ outputs
1878
+ };
1879
+ this.waiters.resolveWebhookResponse({
1880
+ runId: args.state.runId,
1881
+ workflowId: args.state.workflowId,
1882
+ startedAt: args.state.startedAt,
1883
+ runStatus: "completed",
1884
+ response: args.signal.responseItems
1885
+ });
1886
+ this.waiters.resolveRunCompletion(result$1);
1887
+ return result$1;
1888
+ }
1889
+ if (completedActivations >= maxNodeActivations) {
1890
+ const message = `Run exceeded maxNodeActivations (${maxNodeActivations}) after ${completedActivations} completed node activations (next would be ${next.nodeId}).`;
1891
+ const failedState = this.persistedRunStateTerminalBuilder.mergeTerminal({
1892
+ state: args.state,
1893
+ engineCounters,
1894
+ status: "failed",
1895
+ queue: queue.map((q) => ({ ...q })),
1896
+ outputsByNode: data.dump(),
1897
+ nodeSnapshotsByNodeId: {
1898
+ ...args.state.nodeSnapshotsByNodeId ?? {},
1899
+ [args.args.nodeId]: completedSnapshot
1900
+ }
1901
+ });
1902
+ await this.workflowExecutionRepository.save(failedState);
1903
+ await this.nodeEventPublisher.publish("nodeCompleted", completedSnapshot);
1904
+ await this.terminalPersistence.maybeDeleteAfterTerminalState({
1905
+ workflow: args.workflow,
1906
+ state: failedState,
1907
+ finalStatus: "failed",
1908
+ finishedAt: completedSnapshot.finishedAt ?? completedSnapshot.updatedAt
1909
+ });
1910
+ const result$1 = {
1911
+ runId: args.state.runId,
1912
+ workflowId: args.state.workflowId,
1913
+ startedAt: args.state.startedAt,
1914
+ status: "failed",
1915
+ error: { message }
1916
+ };
1917
+ this.waiters.resolveWebhookResponse({
1918
+ runId: args.state.runId,
1919
+ workflowId: args.state.workflowId,
1920
+ startedAt: args.state.startedAt,
1921
+ runStatus: "pending",
1922
+ response: args.signal.responseItems
1923
+ });
1924
+ this.waiters.resolveRunCompletion(result$1);
1925
+ return result$1;
1926
+ }
1927
+ const nextDefinition = topology.defsById.get(next.nodeId);
1928
+ if (!nextDefinition || nextDefinition.kind !== "node") throw new Error(`Node ${next.nodeId} is not a runnable node`);
1929
+ const webhookLimits = this.resolveEngineLimitsFromState(args.state);
1930
+ const base = this.runExecutionContextFactory.create({
1931
+ runId: args.state.runId,
1932
+ workflowId: args.state.workflowId,
1933
+ nodeId: nextDefinition.id,
1934
+ parent: args.state.parent,
1935
+ subworkflowDepth: args.state.executionOptions?.subworkflowDepth ?? 0,
1936
+ engineMaxNodeActivations: webhookLimits.engineMaxNodeActivations,
1937
+ engineMaxSubworkflowDepth: webhookLimits.engineMaxSubworkflowDepth,
1938
+ data,
1939
+ nodeState: this.nodeStatePublisherFactory.create(args.state.runId, args.state.workflowId, args.state.parent)
1940
+ });
1941
+ const request = this.nodeActivationRequestComposer.createFromPlannedActivation({
1942
+ next,
1943
+ base,
1944
+ data,
1945
+ runId: args.state.runId,
1946
+ workflowId: args.state.workflowId,
1947
+ parent: args.state.parent,
1948
+ executionOptions: args.state.executionOptions,
1949
+ nodeDefinition: nextDefinition
1950
+ });
1951
+ const { queuedSnapshot, result } = await this.activationEnqueueService.enqueueActivationWithSnapshot({
1952
+ runId: args.state.runId,
1953
+ workflowId: args.state.workflowId,
1954
+ startedAt: args.state.startedAt,
1955
+ parent: args.state.parent,
1956
+ executionOptions: args.state.executionOptions,
1957
+ control: args.state.control,
1958
+ workflowSnapshot: args.state.workflowSnapshot,
1959
+ mutableState: args.state.mutableState,
1960
+ policySnapshot: args.state.policySnapshot,
1961
+ pendingQueue: queue,
1962
+ request,
1963
+ previousNodeSnapshotsByNodeId: {
1964
+ ...args.state.nodeSnapshotsByNodeId ?? {},
1965
+ [args.args.nodeId]: completedSnapshot
1966
+ },
1967
+ planner,
1968
+ engineCounters,
1969
+ connectionInvocations: args.state.connectionInvocations ?? []
1970
+ });
1971
+ await this.nodeEventPublisher.publish("nodeCompleted", completedSnapshot);
1972
+ await this.nodeEventPublisher.publish("nodeQueued", queuedSnapshot);
1973
+ this.waiters.resolveWebhookResponse({
1974
+ runId: args.state.runId,
1975
+ workflowId: args.state.workflowId,
1976
+ startedAt: args.state.startedAt,
1977
+ runStatus: "pending",
1978
+ response: args.signal.responseItems
1979
+ });
1980
+ return result;
1981
+ }
1982
+ asWebhookControlSignal(error) {
1983
+ const candidate = error;
1984
+ if (!candidate || candidate.__webhookControl !== true) return void 0;
1985
+ if (candidate.kind !== "respondNow" && candidate.kind !== "respondNowAndContinue") return void 0;
1986
+ if (!Array.isArray(candidate.responseItems)) return void 0;
1987
+ return candidate;
1988
+ }
1989
+ resolvePersistedWorkflow(state) {
1990
+ return this.workflowSnapshotResolver.resolve({
1991
+ workflowId: state.workflowId,
1992
+ workflowSnapshot: state.workflowSnapshot
1993
+ });
1994
+ }
1995
+ buildNodeExecutionContextForPending(state, wf, def, nodeId) {
1996
+ const data = this.runDataFactory.create(state.outputsByNode);
1997
+ const limits = this.resolveEngineLimitsFromState(state);
1998
+ const base = this.runExecutionContextFactory.create({
1999
+ runId: state.runId,
2000
+ workflowId: state.workflowId,
2001
+ nodeId,
2002
+ parent: state.parent,
2003
+ subworkflowDepth: state.executionOptions?.subworkflowDepth ?? 0,
2004
+ engineMaxNodeActivations: limits.engineMaxNodeActivations,
2005
+ engineMaxSubworkflowDepth: limits.engineMaxSubworkflowDepth,
2006
+ data,
2007
+ nodeState: this.nodeStatePublisherFactory.create(state.runId, state.workflowId, state.parent)
2008
+ });
2009
+ const activationId = state.pending.activationId;
2010
+ return {
2011
+ ...base,
2012
+ data,
2013
+ nodeId,
2014
+ activationId,
2015
+ config: def.config,
2016
+ binary: base.binary.forNode({
2017
+ nodeId,
2018
+ activationId
2019
+ }),
2020
+ getCredential: this.credentialResolverFactory.create(wf.id, nodeId, def.config)
2021
+ };
2022
+ }
2023
+ resolveEngineLimitsFromState(state) {
2024
+ const fb = this.executionLimitsPolicy.createRootExecutionOptions();
2025
+ return {
2026
+ engineMaxNodeActivations: state.executionOptions?.maxNodeActivations ?? fb.maxNodeActivations,
2027
+ engineMaxSubworkflowDepth: state.executionOptions?.maxSubworkflowDepth ?? fb.maxSubworkflowDepth
2028
+ };
2029
+ }
2030
+ formatNodeLabel(args) {
2031
+ const tokenName = typeof args.definition?.type === "function" ? args.definition.type.name : "Node";
2032
+ return args.definition?.name ? `"${args.definition.name}" (${tokenName}:${args.nodeId})` : `${tokenName}:${args.nodeId}`;
2033
+ }
2034
+ formatOutputCounts(outputs) {
2035
+ const entries = Object.entries(outputs ?? {});
2036
+ if (entries.length === 0) return "no outputs";
2037
+ return entries.map(([port, items]) => `${port}=${items?.length ?? 0}`).join(", ");
2038
+ }
2039
+ };
2040
+
2041
+ //#endregion
2042
+ //#region src/planning/CurrentStateFrontierPlanner.ts
2043
+ var CurrentStateFrontierPlanner = class CurrentStateFrontierPlanner {
2044
+ constructor(topology) {
2045
+ this.topology = topology;
2046
+ }
2047
+ /** Composition-root-friendly factory (avoids `new` at orchestration call sites under ESLint manual-DI rules). */
2048
+ static createFromTopology(topology) {
2049
+ return new CurrentStateFrontierPlanner(topology);
2050
+ }
2051
+ plan(args) {
2052
+ const stopCondition = args.stopCondition ?? { kind: "workflowCompleted" };
2053
+ const baseState = this.cloneCurrentState(args.currentState);
2054
+ const normalizedState = this.overlayPinnedOutputs(baseState);
2055
+ const resetResult = this.applyReset({
2056
+ currentState: normalizedState,
2057
+ reset: args.reset
2058
+ });
2059
+ const requiredNodeIds = this.collectRequiredNodeIds(stopCondition, resetResult.currentState);
2060
+ const satisfiedNodeIds = this.collectSatisfiedNodeIds(resetResult.currentState);
2061
+ const skippedNodeIds = [...new Set([...[...requiredNodeIds].filter((nodeId) => this.isNodeSatisfied(resetResult.currentState, nodeId)), ...resetResult.preservedPinnedNodeIds.filter((nodeId) => requiredNodeIds.has(nodeId))])];
2062
+ const frontierNodeIds = this.collectFrontierNodeIds(requiredNodeIds, resetResult.currentState);
2063
+ const rootNodeIds = frontierNodeIds.filter((nodeId) => (this.topology.incomingByNode.get(nodeId) ?? []).length === 0);
2064
+ if (rootNodeIds.length > 1) throw new Error(`Ambiguous execution frontier. Multiple root nodes require input: ${rootNodeIds.join(", ")}`);
2065
+ if (frontierNodeIds.length === 0) return {
2066
+ queue: [],
2067
+ currentState: resetResult.currentState,
2068
+ stopCondition,
2069
+ satisfiedNodeIds,
2070
+ skippedNodeIds,
2071
+ clearedNodeIds: resetResult.clearedNodeIds,
2072
+ preservedPinnedNodeIds: resetResult.preservedPinnedNodeIds
2073
+ };
2074
+ if (rootNodeIds.length === 1) {
2075
+ const rootNodeId = rootNodeIds[0];
2076
+ const definition = this.topology.defsById.get(rootNodeId);
2077
+ if (!definition) throw new Error(`Unknown frontier nodeId: ${rootNodeId}`);
2078
+ return {
2079
+ rootNodeId,
2080
+ rootNodeInput: this.resolveRootNodeInput({
2081
+ nodeKind: definition.kind,
2082
+ items: args.items
2083
+ }),
2084
+ queue: [],
2085
+ currentState: resetResult.currentState,
2086
+ stopCondition,
2087
+ satisfiedNodeIds,
2088
+ skippedNodeIds,
2089
+ clearedNodeIds: resetResult.clearedNodeIds,
2090
+ preservedPinnedNodeIds: resetResult.preservedPinnedNodeIds
2091
+ };
2092
+ }
2093
+ const queue = [];
2094
+ for (const nodeId of frontierNodeIds) queue.push(...this.buildFrontierQueue(nodeId, resetResult.currentState));
2095
+ return {
2096
+ queue,
2097
+ currentState: resetResult.currentState,
2098
+ stopCondition,
2099
+ satisfiedNodeIds,
2100
+ skippedNodeIds,
2101
+ clearedNodeIds: resetResult.clearedNodeIds,
2102
+ preservedPinnedNodeIds: resetResult.preservedPinnedNodeIds
2103
+ };
2104
+ }
2105
+ cloneCurrentState(currentState) {
2106
+ if (!currentState) return {
2107
+ outputsByNode: {},
2108
+ nodeSnapshotsByNodeId: {},
2109
+ connectionInvocations: [],
2110
+ mutableState: void 0
2111
+ };
2112
+ return {
2113
+ outputsByNode: { ...currentState.outputsByNode },
2114
+ nodeSnapshotsByNodeId: { ...currentState.nodeSnapshotsByNodeId },
2115
+ connectionInvocations: currentState.connectionInvocations ? [...currentState.connectionInvocations] : void 0,
2116
+ mutableState: currentState.mutableState
2117
+ };
2118
+ }
2119
+ overlayPinnedOutputs(currentState) {
2120
+ const outputsByNode = { ...currentState.outputsByNode };
2121
+ for (const [nodeId, nodeState] of Object.entries(currentState.mutableState?.nodesById ?? {})) {
2122
+ const pinnedOutputs = nodeState.pinnedOutputsByPort;
2123
+ if (!pinnedOutputs) continue;
2124
+ outputsByNode[nodeId] = pinnedOutputs;
2125
+ }
2126
+ return {
2127
+ outputsByNode,
2128
+ nodeSnapshotsByNodeId: { ...currentState.nodeSnapshotsByNodeId },
2129
+ connectionInvocations: currentState.connectionInvocations,
2130
+ mutableState: currentState.mutableState
2131
+ };
2132
+ }
2133
+ applyReset(args) {
2134
+ if (!args.reset) return {
2135
+ currentState: args.currentState,
2136
+ clearedNodeIds: [],
2137
+ preservedPinnedNodeIds: []
2138
+ };
2139
+ const outputsByNode = { ...args.currentState.outputsByNode };
2140
+ const nodeSnapshotsByNodeId = { ...args.currentState.nodeSnapshotsByNodeId };
2141
+ const clearedNodeIds = [];
2142
+ const preservedPinnedNodeIds = [];
2143
+ const descendants = this.collectDescendants(args.reset.clearFromNodeId);
2144
+ const runtimeDescendants = this.collectRuntimeDescendants(args.currentState, descendants);
2145
+ const clearedIdSet = new Set([...descendants, ...runtimeDescendants]);
2146
+ for (const nodeId of [...descendants, ...runtimeDescendants]) {
2147
+ const pinnedOutputs = this.getPinnedOutputs(args.currentState, nodeId);
2148
+ if (pinnedOutputs) {
2149
+ outputsByNode[nodeId] = pinnedOutputs;
2150
+ delete nodeSnapshotsByNodeId[nodeId];
2151
+ preservedPinnedNodeIds.push(nodeId);
2152
+ continue;
2153
+ }
2154
+ delete outputsByNode[nodeId];
2155
+ delete nodeSnapshotsByNodeId[nodeId];
2156
+ clearedNodeIds.push(nodeId);
2157
+ }
2158
+ return {
2159
+ currentState: {
2160
+ outputsByNode,
2161
+ nodeSnapshotsByNodeId,
2162
+ connectionInvocations: this.filterConnectionInvocations(args.currentState.connectionInvocations, clearedIdSet),
2163
+ mutableState: args.currentState.mutableState
2164
+ },
2165
+ clearedNodeIds,
2166
+ preservedPinnedNodeIds
2167
+ };
2168
+ }
2169
+ collectSatisfiedNodeIds(currentState) {
2170
+ const satisfiedNodeIds = [];
2171
+ for (const nodeId of this.topology.defsById.keys()) if (this.isNodeSatisfied(currentState, nodeId)) satisfiedNodeIds.push(nodeId);
2172
+ return satisfiedNodeIds;
2173
+ }
2174
+ collectFrontierNodeIds(requiredNodeIds, currentState) {
2175
+ const frontierNodeIds = [];
2176
+ for (const nodeId of this.topology.defsById.keys()) {
2177
+ if (!requiredNodeIds.has(nodeId) || this.isNodeSatisfied(currentState, nodeId)) continue;
2178
+ if ((this.topology.incomingByNode.get(nodeId) ?? []).every((edge) => this.isEdgeSatisfied(currentState, nodeId, edge.input))) frontierNodeIds.push(nodeId);
2179
+ }
2180
+ return frontierNodeIds;
2181
+ }
2182
+ collectRequiredNodeIds(stopCondition, currentState) {
2183
+ const requiredNodeIds = /* @__PURE__ */ new Set();
2184
+ if (stopCondition.kind === "workflowCompleted") {
2185
+ for (const nodeId of this.topology.defsById.keys()) if (!this.isNodeSatisfied(currentState, nodeId)) this.collectRequiredNode(requiredNodeIds, currentState, nodeId);
2186
+ return requiredNodeIds;
2187
+ }
2188
+ if (!this.topology.defsById.has(stopCondition.nodeId)) throw new Error(`Unknown stop nodeId: ${stopCondition.nodeId}`);
2189
+ this.collectRequiredNode(requiredNodeIds, currentState, stopCondition.nodeId);
2190
+ return requiredNodeIds;
2191
+ }
2192
+ collectRequiredNode(requiredNodeIds, currentState, nodeId) {
2193
+ if (requiredNodeIds.has(nodeId)) return;
2194
+ if (this.isNodeSatisfied(currentState, nodeId) && !this.isNodeSatisfiedByOutputsOnly(currentState, nodeId)) return;
2195
+ requiredNodeIds.add(nodeId);
2196
+ for (const edge of this.topology.incomingByNode.get(nodeId) ?? []) if (!this.isEdgeSatisfied(currentState, nodeId, edge.input) || this.isNodeSatisfiedByOutputsOnly(currentState, edge.from.nodeId)) this.collectRequiredNode(requiredNodeIds, currentState, edge.from.nodeId);
2197
+ }
2198
+ buildFrontierQueue(nodeId, currentState) {
2199
+ const incomingEdges = this.topology.incomingByNode.get(nodeId) ?? [];
2200
+ if (incomingEdges.length === 0) return [];
2201
+ const expectedInputs = this.topology.expectedInputsByNode.get(nodeId) ?? [];
2202
+ if (expectedInputs.length !== 1 || expectedInputs[0] !== "in") {
2203
+ const received = {};
2204
+ for (const input$1 of expectedInputs) received[input$1] = this.resolveInput(currentState, nodeId, input$1);
2205
+ return [{
2206
+ nodeId,
2207
+ input: [],
2208
+ batchId: "batch_1",
2209
+ collect: {
2210
+ expectedInputs,
2211
+ received
2212
+ }
2213
+ }];
2214
+ }
2215
+ const input = expectedInputs[0] ?? "in";
2216
+ const incomingEdge = incomingEdges.find((edge) => edge.input === input);
2217
+ return [{
2218
+ nodeId,
2219
+ input: this.resolveInput(currentState, nodeId, input),
2220
+ toInput: input,
2221
+ batchId: "batch_1",
2222
+ from: incomingEdge?.from
2223
+ }];
2224
+ }
2225
+ resolveRootNodeInput(args) {
2226
+ if (args.items) return args.items;
2227
+ if (args.nodeKind === "trigger") return [];
2228
+ return [{ json: {} }];
2229
+ }
2230
+ isNodeSatisfied(currentState, nodeId) {
2231
+ return this.hasOutputs(currentState, nodeId) || this.hasCompletedSnapshot(currentState, nodeId);
2232
+ }
2233
+ isNodeSatisfiedByOutputsOnly(currentState, nodeId) {
2234
+ return this.hasOutputs(currentState, nodeId) && !this.hasCompletedSnapshot(currentState, nodeId);
2235
+ }
2236
+ isEdgeSatisfied(currentState, nodeId, input) {
2237
+ const incomingEdge = (this.topology.incomingByNode.get(nodeId) ?? []).find((edge) => edge.input === input);
2238
+ if (!incomingEdge) return false;
2239
+ return this.hasOutputPort(currentState, incomingEdge.from.nodeId, incomingEdge.from.output);
2240
+ }
2241
+ resolveInput(currentState, nodeId, input) {
2242
+ const incomingEdge = (this.topology.incomingByNode.get(nodeId) ?? []).find((edge) => edge.input === input);
2243
+ if (!incomingEdge) return [];
2244
+ return this.resolveOutputItems(currentState, incomingEdge.from.nodeId, incomingEdge.from.output);
2245
+ }
2246
+ hasOutputs(currentState, nodeId) {
2247
+ return Object.prototype.hasOwnProperty.call(currentState.outputsByNode, nodeId);
2248
+ }
2249
+ hasCompletedSnapshot(currentState, nodeId) {
2250
+ const snapshot = currentState.nodeSnapshotsByNodeId[nodeId];
2251
+ return snapshot?.status === "completed" || snapshot?.status === "skipped";
2252
+ }
2253
+ hasOutputPort(currentState, nodeId, output) {
2254
+ const outputs = currentState.outputsByNode[nodeId];
2255
+ if (!outputs) return false;
2256
+ return Object.prototype.hasOwnProperty.call(outputs, output);
2257
+ }
2258
+ resolveOutputItems(currentState, nodeId, output) {
2259
+ return currentState.outputsByNode[nodeId]?.[output] ?? [];
2260
+ }
2261
+ getPinnedOutputs(currentState, nodeId) {
2262
+ return currentState.mutableState?.nodesById?.[nodeId]?.pinnedOutputsByPort;
2263
+ }
2264
+ filterConnectionInvocations(invocations, clearedIdSet) {
2265
+ if (!invocations || invocations.length === 0) return invocations;
2266
+ const kept = invocations.filter((invocation) => !clearedIdSet.has(invocation.parentAgentNodeId) && !clearedIdSet.has(invocation.connectionNodeId));
2267
+ return kept.length === invocations.length ? invocations : kept;
2268
+ }
2269
+ collectDescendants(startNodeId) {
2270
+ const pendingNodeIds = [startNodeId];
2271
+ const descendants = /* @__PURE__ */ new Set();
2272
+ while (pendingNodeIds.length > 0) {
2273
+ const nodeId = pendingNodeIds.pop();
2274
+ if (!nodeId || descendants.has(nodeId)) continue;
2275
+ descendants.add(nodeId);
2276
+ for (const edge of this.topology.outgoingByNode.get(nodeId) ?? []) pendingNodeIds.push(edge.to.nodeId);
2277
+ }
2278
+ return [...descendants];
2279
+ }
2280
+ collectRuntimeDescendants(currentState, descendantNodeIds) {
2281
+ const descendantSet = new Set(descendantNodeIds);
2282
+ const runtimeNodeIds = /* @__PURE__ */ new Set();
2283
+ for (const nodeId of [
2284
+ ...Object.keys(currentState.outputsByNode),
2285
+ ...Object.keys(currentState.nodeSnapshotsByNodeId),
2286
+ ...Object.keys(currentState.mutableState?.nodesById ?? {})
2287
+ ]) if (this.isRuntimeDescendant(nodeId, descendantSet)) runtimeNodeIds.add(nodeId);
2288
+ return [...runtimeNodeIds];
2289
+ }
2290
+ isRuntimeDescendant(nodeId, descendantNodeIds) {
2291
+ for (const descendantNodeId of descendantNodeIds) {
2292
+ if (nodeId === descendantNodeId) return false;
2293
+ if (ConnectionNodeIdFactory.isConnectionOwnedDescendantOf(descendantNodeId, nodeId)) return true;
2294
+ }
2295
+ return false;
2296
+ }
2297
+ };
2298
+
2299
+ //#endregion
2300
+ //#region src/policies/storage/RunPolicySnapshotFactory.ts
2301
+ var RunPolicySnapshotFactory = class {
2302
+ static create(workflow, defaults) {
2303
+ const prune = workflow.prunePolicy;
2304
+ return {
2305
+ retentionSeconds: prune?.runDataRetentionSeconds ?? defaults?.retentionSeconds,
2306
+ binaryRetentionSeconds: prune?.binaryRetentionSeconds ?? defaults?.binaryRetentionSeconds,
2307
+ storagePolicy: typeof workflow.storagePolicy === "string" ? workflow.storagePolicy : defaults?.storagePolicy ?? "ALL"
2308
+ };
2309
+ }
2310
+ };
2311
+
2312
+ //#endregion
2313
+ //#region src/orchestration/RunStartService.ts
2314
+ var RunStartService = class {
2315
+ constructor(runIdFactory, workflowExecutionRepository, runDataFactory, workflowSnapshotFactory, planningFactory, nodeStatePublisherFactory, runExecutionContextFactory, nodeActivationRequestComposer, activationEnqueueService, semantics, waiters, workflowPolicyRuntimeDefaults, executionLimitsPolicy) {
2316
+ this.runIdFactory = runIdFactory;
2317
+ this.workflowExecutionRepository = workflowExecutionRepository;
2318
+ this.runDataFactory = runDataFactory;
2319
+ this.workflowSnapshotFactory = workflowSnapshotFactory;
2320
+ this.planningFactory = planningFactory;
2321
+ this.nodeStatePublisherFactory = nodeStatePublisherFactory;
2322
+ this.runExecutionContextFactory = runExecutionContextFactory;
2323
+ this.nodeActivationRequestComposer = nodeActivationRequestComposer;
2324
+ this.activationEnqueueService = activationEnqueueService;
2325
+ this.semantics = semantics;
2326
+ this.waiters = waiters;
2327
+ this.workflowPolicyRuntimeDefaults = workflowPolicyRuntimeDefaults;
2328
+ this.executionLimitsPolicy = executionLimitsPolicy;
2329
+ }
2330
+ async runWorkflow(workflow, startAt, items, parent, executionOptions, persistedStateOverrides) {
2331
+ const runId = this.runIdFactory.makeRunId();
2332
+ const startedAt = (/* @__PURE__ */ new Date()).toISOString();
2333
+ const workflowSnapshot = persistedStateOverrides?.workflowSnapshot ?? this.workflowSnapshotFactory.create(workflow);
2334
+ const mutableState = persistedStateOverrides?.mutableState;
2335
+ const policySnapshot = RunPolicySnapshotFactory.create(workflow, this.workflowPolicyRuntimeDefaults);
2336
+ const mergedExecutionOptions = this.executionLimitsPolicy.mergeExecutionOptionsForNewRun(parent, executionOptions);
2337
+ await this.workflowExecutionRepository.createRun({
2338
+ runId,
2339
+ workflowId: workflow.id,
2340
+ startedAt,
2341
+ parent,
2342
+ executionOptions: mergedExecutionOptions,
2343
+ workflowSnapshot,
2344
+ mutableState,
2345
+ policySnapshot,
2346
+ engineCounters: { completedNodeActivations: 0 }
2347
+ });
2348
+ const data = this.runDataFactory.create();
2349
+ const base = this.runExecutionContextFactory.create({
2350
+ runId,
2351
+ workflowId: workflow.id,
2352
+ nodeId: startAt,
2353
+ parent,
2354
+ subworkflowDepth: mergedExecutionOptions.subworkflowDepth ?? 0,
2355
+ engineMaxNodeActivations: mergedExecutionOptions.maxNodeActivations,
2356
+ engineMaxSubworkflowDepth: mergedExecutionOptions.maxSubworkflowDepth,
2357
+ data,
2358
+ nodeState: this.nodeStatePublisherFactory.create(runId, workflow.id, parent)
2359
+ });
2360
+ const { topology, planner } = this.planningFactory.create(workflow);
2361
+ const startDefinition = topology.defsById.get(startAt);
2362
+ if (!startDefinition) throw new Error(`Unknown start nodeId: ${startAt}`);
2363
+ const initialNodeSnapshotsByNodeId = {};
2364
+ if (startDefinition.kind === "trigger") {
2365
+ const request = this.nodeActivationRequestComposer.createSingleFromDefinition({
2366
+ runId,
2367
+ workflowId: workflow.id,
2368
+ definition: startDefinition,
2369
+ parent,
2370
+ executionOptions: mergedExecutionOptions,
2371
+ batchId: "batch_1",
2372
+ input: items,
2373
+ base,
2374
+ data
2375
+ });
2376
+ return await this.activationEnqueueService.enqueueActivation({
2377
+ runId,
2378
+ workflowId: workflow.id,
2379
+ startedAt,
2380
+ parent,
2381
+ executionOptions: mergedExecutionOptions,
2382
+ workflowSnapshot,
2383
+ mutableState,
2384
+ policySnapshot,
2385
+ control: void 0,
2386
+ pendingQueue: [],
2387
+ request,
2388
+ previousNodeSnapshotsByNodeId: initialNodeSnapshotsByNodeId,
2389
+ planner,
2390
+ engineCounters: { completedNodeActivations: 0 },
2391
+ connectionInvocations: []
2392
+ });
2393
+ }
2394
+ const queue = [{
2395
+ nodeId: startAt,
2396
+ input: items,
2397
+ toInput: "in",
2398
+ batchId: "batch_1"
2399
+ }];
2400
+ return await this.scheduleQueuedPlan({
2401
+ runId,
2402
+ workflowId: workflow.id,
2403
+ startedAt,
2404
+ parent,
2405
+ executionOptions: mergedExecutionOptions,
2406
+ control: void 0,
2407
+ workflowSnapshot,
2408
+ mutableState,
2409
+ policySnapshot,
2410
+ workflow,
2411
+ planner,
2412
+ queue,
2413
+ base,
2414
+ data,
2415
+ nodeSnapshotsByNodeId: initialNodeSnapshotsByNodeId,
2416
+ connectionInvocations: []
2417
+ });
2418
+ }
2419
+ async runWorkflowFromState(request) {
2420
+ const runId = this.runIdFactory.makeRunId();
2421
+ const startedAt = (/* @__PURE__ */ new Date()).toISOString();
2422
+ const workflowSnapshot = request.workflowSnapshot ?? this.workflowSnapshotFactory.create(request.workflow);
2423
+ const mutableState = request.mutableState ?? request.currentState?.mutableState;
2424
+ const policySnapshot = RunPolicySnapshotFactory.create(request.workflow, this.workflowPolicyRuntimeDefaults);
2425
+ const control = { stopCondition: request.stopCondition ?? { kind: "workflowCompleted" } };
2426
+ const mergedExecutionOptions = this.executionLimitsPolicy.mergeExecutionOptionsForNewRun(request.parent, request.executionOptions);
2427
+ await this.workflowExecutionRepository.createRun({
2428
+ runId,
2429
+ workflowId: request.workflow.id,
2430
+ startedAt,
2431
+ parent: request.parent,
2432
+ executionOptions: mergedExecutionOptions,
2433
+ control,
2434
+ workflowSnapshot,
2435
+ mutableState,
2436
+ policySnapshot,
2437
+ engineCounters: { completedNodeActivations: 0 }
2438
+ });
2439
+ const { topology, planner } = this.planningFactory.create(request.workflow);
2440
+ const plan = CurrentStateFrontierPlanner.createFromTopology(topology).plan({
2441
+ currentState: this.createRunCurrentState(request.currentState, mutableState),
2442
+ stopCondition: control.stopCondition,
2443
+ reset: request.reset,
2444
+ items: request.items
2445
+ });
2446
+ const data = this.runDataFactory.create(plan.currentState.outputsByNode);
2447
+ const base = this.runExecutionContextFactory.create({
2448
+ runId,
2449
+ workflowId: request.workflow.id,
2450
+ nodeId: WorkflowExecutableNodeClassifierFactory.create(request.workflow).firstExecutableNodeIdInDefinitionOrder(request.workflow) ?? "unknown_node",
2451
+ parent: request.parent,
2452
+ subworkflowDepth: mergedExecutionOptions.subworkflowDepth ?? 0,
2453
+ engineMaxNodeActivations: mergedExecutionOptions.maxNodeActivations,
2454
+ engineMaxSubworkflowDepth: mergedExecutionOptions.maxSubworkflowDepth,
2455
+ data,
2456
+ nodeState: this.nodeStatePublisherFactory.create(runId, request.workflow.id, request.parent)
2457
+ });
2458
+ return await this.scheduleInitialPlan({
2459
+ runId,
2460
+ startedAt,
2461
+ workflow: request.workflow,
2462
+ workflowSnapshot,
2463
+ mutableState,
2464
+ policySnapshot,
2465
+ executionOptions: mergedExecutionOptions,
2466
+ control,
2467
+ parent: request.parent,
2468
+ planner,
2469
+ plan,
2470
+ base,
2471
+ data
2472
+ });
2473
+ }
2474
+ createRunCurrentState(currentState, mutableState) {
2475
+ return {
2476
+ outputsByNode: { ...currentState?.outputsByNode ?? {} },
2477
+ nodeSnapshotsByNodeId: { ...currentState?.nodeSnapshotsByNodeId ?? {} },
2478
+ connectionInvocations: currentState?.connectionInvocations ? [...currentState.connectionInvocations] : void 0,
2479
+ mutableState: mutableState ?? currentState?.mutableState
2480
+ };
2481
+ }
2482
+ async scheduleInitialPlan(args) {
2483
+ const initialNodeSnapshotsByNodeId = this.semantics.applySkippedSnapshots({
2484
+ runId: args.runId,
2485
+ workflowId: args.workflow.id,
2486
+ parent: args.parent,
2487
+ currentState: args.plan.currentState,
2488
+ skippedNodeIds: args.plan.skippedNodeIds,
2489
+ preservedPinnedNodeIds: args.plan.preservedPinnedNodeIds,
2490
+ finishedAt: args.startedAt
2491
+ });
2492
+ if (args.plan.rootNodeId) {
2493
+ const startDef = WorkflowTopology.fromWorkflow(args.workflow).defsById.get(args.plan.rootNodeId);
2494
+ if (!startDef) throw new Error(`Unknown frontier nodeId: ${args.plan.rootNodeId}`);
2495
+ const startItems = args.plan.rootNodeInput ?? [];
2496
+ const request = this.nodeActivationRequestComposer.createSingleFromDefinition({
2497
+ runId: args.runId,
2498
+ workflowId: args.workflow.id,
2499
+ definition: startDef,
2500
+ parent: args.parent,
2501
+ executionOptions: args.executionOptions,
2502
+ batchId: "batch_1",
2503
+ input: startItems,
2504
+ base: args.base,
2505
+ data: args.data
2506
+ });
2507
+ return await this.activationEnqueueService.enqueueActivation({
2508
+ runId: args.runId,
2509
+ workflowId: args.workflow.id,
2510
+ startedAt: args.startedAt,
2511
+ parent: args.parent,
2512
+ executionOptions: args.executionOptions,
2513
+ control: args.control,
2514
+ workflowSnapshot: args.workflowSnapshot,
2515
+ mutableState: args.mutableState,
2516
+ policySnapshot: args.policySnapshot,
2517
+ pendingQueue: [],
2518
+ request,
2519
+ previousNodeSnapshotsByNodeId: initialNodeSnapshotsByNodeId,
2520
+ planner: args.planner,
2521
+ engineCounters: { completedNodeActivations: 0 },
2522
+ connectionInvocations: args.plan.currentState.connectionInvocations ?? []
2523
+ });
2524
+ }
2525
+ return await this.scheduleQueuedPlan({
2526
+ runId: args.runId,
2527
+ workflowId: args.workflow.id,
2528
+ startedAt: args.startedAt,
2529
+ parent: args.parent,
2530
+ executionOptions: args.executionOptions,
2531
+ control: args.control,
2532
+ workflowSnapshot: args.workflowSnapshot,
2533
+ mutableState: args.mutableState,
2534
+ policySnapshot: args.policySnapshot,
2535
+ workflow: args.workflow,
2536
+ planner: args.planner,
2537
+ queue: [...args.plan.queue],
2538
+ base: args.base,
2539
+ data: args.data,
2540
+ nodeSnapshotsByNodeId: initialNodeSnapshotsByNodeId,
2541
+ connectionInvocations: args.plan.currentState.connectionInvocations ?? []
2542
+ });
2543
+ }
2544
+ async scheduleQueuedPlan(args) {
2545
+ this.semantics.applyPinnedQueueSkips({
2546
+ runId: args.runId,
2547
+ workflowId: args.workflowId,
2548
+ parent: args.parent,
2549
+ mutableState: args.mutableState,
2550
+ planner: args.planner,
2551
+ queue: args.queue,
2552
+ data: args.data,
2553
+ nodeSnapshotsByNodeId: args.nodeSnapshotsByNodeId,
2554
+ finishedAt: args.startedAt
2555
+ });
2556
+ const next = args.planner.nextActivation(args.queue);
2557
+ if (!next) return await this.completeRun({
2558
+ runId: args.runId,
2559
+ workflowId: args.workflowId,
2560
+ startedAt: args.startedAt,
2561
+ parent: args.parent,
2562
+ executionOptions: args.executionOptions,
2563
+ control: args.control,
2564
+ workflowSnapshot: args.workflowSnapshot,
2565
+ mutableState: args.mutableState,
2566
+ policySnapshot: args.policySnapshot,
2567
+ workflow: args.workflow,
2568
+ data: args.data,
2569
+ nodeSnapshotsByNodeId: args.nodeSnapshotsByNodeId,
2570
+ connectionInvocations: args.connectionInvocations
2571
+ });
2572
+ const definition = WorkflowTopology.fromWorkflow(args.workflow).defsById.get(next.nodeId);
2573
+ if (!definition || definition.kind !== "node") throw new Error(`Node ${next.nodeId} is not a runnable node`);
2574
+ const request = this.nodeActivationRequestComposer.createFromPlannedActivation({
2575
+ next,
2576
+ base: args.base,
2577
+ data: args.data,
2578
+ runId: args.runId,
2579
+ workflowId: args.workflowId,
2580
+ parent: args.parent,
2581
+ executionOptions: args.executionOptions,
2582
+ nodeDefinition: definition
2583
+ });
2584
+ return await this.activationEnqueueService.enqueueActivation({
2585
+ runId: args.runId,
2586
+ workflowId: args.workflowId,
2587
+ startedAt: args.startedAt,
2588
+ parent: args.parent,
2589
+ executionOptions: args.executionOptions,
2590
+ control: args.control,
2591
+ workflowSnapshot: args.workflowSnapshot,
2592
+ mutableState: args.mutableState,
2593
+ policySnapshot: args.policySnapshot,
2594
+ pendingQueue: args.queue,
2595
+ request,
2596
+ previousNodeSnapshotsByNodeId: args.nodeSnapshotsByNodeId,
2597
+ planner: args.planner,
2598
+ engineCounters: { completedNodeActivations: 0 },
2599
+ connectionInvocations: args.connectionInvocations ?? []
2600
+ });
2601
+ }
2602
+ async completeRun(args) {
2603
+ await this.workflowExecutionRepository.save({
2604
+ runId: args.runId,
2605
+ workflowId: args.workflowId,
2606
+ startedAt: args.startedAt,
2607
+ parent: args.parent,
2608
+ executionOptions: args.executionOptions,
2609
+ control: args.control,
2610
+ workflowSnapshot: args.workflowSnapshot,
2611
+ mutableState: args.mutableState,
2612
+ policySnapshot: args.policySnapshot,
2613
+ engineCounters: { completedNodeActivations: 0 },
2614
+ connectionInvocations: args.connectionInvocations ? [...args.connectionInvocations] : [],
2615
+ status: "completed",
2616
+ pending: void 0,
2617
+ queue: [],
2618
+ outputsByNode: args.data.dump(),
2619
+ nodeSnapshotsByNodeId: args.nodeSnapshotsByNodeId
2620
+ });
2621
+ const result = {
2622
+ runId: args.runId,
2623
+ workflowId: args.workflowId,
2624
+ startedAt: args.startedAt,
2625
+ status: "completed",
2626
+ outputs: this.semantics.resolveResultOutputs(args.workflow, args.control?.stopCondition, args.data.dump())
2627
+ };
2628
+ this.waiters.resolveRunCompletion(result);
2629
+ return result;
2630
+ }
2631
+ };
2632
+
2633
+ //#endregion
2634
+ //#region src/scheduler/ConfigDrivenOffloadPolicy.ts
2635
+ var ConfigDrivenOffloadPolicy = class {
2636
+ defaultMode;
2637
+ constructor(defaultMode = "worker") {
2638
+ this.defaultMode = defaultMode;
2639
+ }
2640
+ decide(args) {
2641
+ const hint = args.config.execution?.hint;
2642
+ const queue = args.config.execution?.queue;
2643
+ if (hint === "local") return { mode: "local" };
2644
+ if (hint === "worker") return {
2645
+ mode: "worker",
2646
+ queue
2647
+ };
2648
+ if (queue) return {
2649
+ mode: "worker",
2650
+ queue
2651
+ };
2652
+ return { mode: this.defaultMode };
2653
+ }
2654
+ };
2655
+
2656
+ //#endregion
2657
+ //#region src/scheduler/DefaultDrivingScheduler.ts
2658
+ var DefaultDrivingScheduler = class {
2659
+ constructor(offloadPolicy, workerScheduler, inline) {
2660
+ this.offloadPolicy = offloadPolicy;
2661
+ this.workerScheduler = workerScheduler;
2662
+ this.inline = inline;
2663
+ }
2664
+ setContinuation(continuation) {
2665
+ this.inline.setContinuation(continuation);
2666
+ }
2667
+ async enqueue(request) {
2668
+ const selection = await this.selectScheduler(request);
2669
+ if (selection.mode === "worker") {
2670
+ if (request.kind === "multi") throw new Error(`Multi-input node ${request.nodeId} cannot be scheduled to worker (insert local placement)`);
2671
+ const workerRequest = {
2672
+ runId: request.runId,
2673
+ activationId: request.activationId,
2674
+ workflowId: request.workflowId,
2675
+ nodeId: request.nodeId,
2676
+ input: request.input,
2677
+ parent: request.parent,
2678
+ queue: selection.queue,
2679
+ executionOptions: request.executionOptions
2680
+ };
2681
+ return {
2682
+ receiptId: (await this.workerScheduler.enqueue(workerRequest)).receiptId,
2683
+ mode: "worker",
2684
+ queue: selection.queue
2685
+ };
2686
+ }
2687
+ return await this.enqueueInline(request);
2688
+ }
2689
+ notifyPendingStatePersisted(runId) {
2690
+ this.inline.notifyPendingStatePersisted(runId);
2691
+ }
2692
+ /**
2693
+ * Scheduler precedence is explicit:
2694
+ * 1. run-intent override (`executionOptions.localOnly`)
2695
+ * 2. node-level execution hint / queue policy
2696
+ * 3. container-default scheduler policy fallback
2697
+ */
2698
+ async selectScheduler(request) {
2699
+ if (request.executionOptions?.localOnly) return {
2700
+ mode: "local",
2701
+ decision: "runIntentOverride"
2702
+ };
2703
+ const decision = this.offloadPolicy.decide({
2704
+ workflowId: request.workflowId,
2705
+ nodeId: request.nodeId,
2706
+ config: request.ctx.config
2707
+ });
2708
+ if (this.hasNodeSchedulingPreference(request)) return {
2709
+ mode: decision.mode,
2710
+ queue: decision.queue,
2711
+ decision: "nodePolicy"
2712
+ };
2713
+ return {
2714
+ mode: decision.mode,
2715
+ queue: decision.queue,
2716
+ decision: "containerDefault"
2717
+ };
2718
+ }
2719
+ hasNodeSchedulingPreference(request) {
2720
+ return request.ctx.config.execution?.hint !== void 0 || request.ctx.config.execution?.queue !== void 0;
2721
+ }
2722
+ async enqueueInline(request) {
2723
+ return {
2724
+ ...await this.inline.enqueue(request),
2725
+ mode: "local"
2726
+ };
2727
+ }
2728
+ };
2729
+
2730
+ //#endregion
2731
+ //#region src/scheduler/HintOnlyOffloadPolicy.ts
2732
+ var HintOnlyOffloadPolicy = class {
2733
+ decide(args) {
2734
+ if (args.config.execution?.hint === "worker") return {
2735
+ mode: "worker",
2736
+ queue: args.config.execution?.queue
2737
+ };
2738
+ return { mode: "local" };
2739
+ }
2740
+ };
2741
+
2742
+ //#endregion
2743
+ //#region src/scheduler/InlineDrivingScheduler.ts
2744
+ var InlineDrivingScheduler = class {
2745
+ continuation;
2746
+ drainingRuns = /* @__PURE__ */ new Set();
2747
+ queuesByRunId = /* @__PURE__ */ new Map();
2748
+ scheduledRuns = /* @__PURE__ */ new Set();
2749
+ seq = 0;
2750
+ constructor(nodeExecutor) {
2751
+ this.nodeExecutor = nodeExecutor;
2752
+ }
2753
+ setContinuation(continuation) {
2754
+ this.continuation = continuation;
2755
+ }
2756
+ async enqueue(request) {
2757
+ const receipt = {
2758
+ receiptId: `inline_${++this.seq}`,
2759
+ mode: "local"
2760
+ };
2761
+ const q = this.queuesByRunId.get(request.runId) ?? [];
2762
+ q.push({
2763
+ request,
2764
+ receipt
2765
+ });
2766
+ this.queuesByRunId.set(request.runId, q);
2767
+ return receipt;
2768
+ }
2769
+ notifyPendingStatePersisted(runId) {
2770
+ if ((this.queuesByRunId.get(runId)?.length ?? 0) === 0) return;
2771
+ this.scheduleDrain(runId);
2772
+ }
2773
+ async drainRun(runId) {
2774
+ if (this.drainingRuns.has(runId)) return;
2775
+ this.drainingRuns.add(runId);
2776
+ this.scheduledRuns.delete(runId);
2777
+ try {
2778
+ const q = this.queuesByRunId.get(runId) ?? [];
2779
+ while (q.length > 0) {
2780
+ const { request } = q.shift();
2781
+ const cont = this.continuation;
2782
+ if (!cont) throw new Error("InlineDrivingScheduler is missing a continuation (setContinuation was not called)");
2783
+ await cont.markNodeRunning({
2784
+ runId: request.runId,
2785
+ activationId: request.activationId,
2786
+ nodeId: request.nodeId,
2787
+ inputsByPort: request.kind === "multi" ? request.inputsByPort : { in: request.input }
2788
+ });
2789
+ let outputs;
2790
+ try {
2791
+ outputs = await this.nodeExecutor.execute(request);
2792
+ } catch (e) {
2793
+ await this.resumeAfterExecutionError(cont, request, this.asError(e));
2794
+ continue;
2795
+ }
2796
+ await this.resumeAfterExecutionResult(cont, request, outputs ?? {});
2797
+ }
2798
+ } finally {
2799
+ if ((this.queuesByRunId.get(runId)?.length ?? 0) === 0) this.queuesByRunId.delete(runId);
2800
+ this.drainingRuns.delete(runId);
2801
+ if ((this.queuesByRunId.get(runId)?.length ?? 0) > 0) this.scheduleDrain(runId);
2802
+ }
2803
+ }
2804
+ scheduleDrain(runId) {
2805
+ if (this.drainingRuns.has(runId) || this.scheduledRuns.has(runId)) return;
2806
+ this.scheduledRuns.add(runId);
2807
+ setTimeout(() => {
2808
+ this.scheduledRuns.delete(runId);
2809
+ this.drainRun(runId);
2810
+ }, 0);
2811
+ }
2812
+ async resumeAfterExecutionResult(continuation, request, outputs) {
2813
+ try {
2814
+ await continuation.resumeFromNodeResult({
2815
+ runId: request.runId,
2816
+ activationId: request.activationId,
2817
+ nodeId: request.nodeId,
2818
+ outputs
2819
+ });
2820
+ } catch (e) {
2821
+ this.rethrowUnlessIgnorableContinuationError(e);
2822
+ }
2823
+ }
2824
+ async resumeAfterExecutionError(continuation, request, error) {
2825
+ try {
2826
+ await continuation.resumeFromNodeError({
2827
+ runId: request.runId,
2828
+ activationId: request.activationId,
2829
+ nodeId: request.nodeId,
2830
+ error
2831
+ });
2832
+ } catch (e) {
2833
+ this.rethrowUnlessIgnorableContinuationError(e);
2834
+ }
2835
+ }
2836
+ asError(e) {
2837
+ return e instanceof Error ? e : new Error(String(e));
2838
+ }
2839
+ rethrowUnlessIgnorableContinuationError(e) {
2840
+ if (this.isIgnorableContinuationError(e)) return;
2841
+ throw this.asError(e);
2842
+ }
2843
+ isIgnorableContinuationError(e) {
2844
+ const message = this.asError(e).message;
2845
+ return message.includes(" is not pending") || message.includes("activationId mismatch") || message.includes("nodeId mismatch");
2846
+ }
2847
+ };
2848
+
2849
+ //#endregion
2850
+ //#region src/scheduler/LocalOnlyScheduler.ts
2851
+ var LocalOnlyScheduler = class {
2852
+ async enqueue(_request) {
2853
+ throw new Error("No worker scheduler configured");
2854
+ }
2855
+ };
2856
+
2857
+ //#endregion
2858
+ //#region src/policies/executionLimits/EngineExecutionLimitsPolicy.ts
2859
+ /** Framework defaults for {@link EngineExecutionLimitsPolicy} (merged with host `runtime.engineExecutionLimits`). */
2860
+ const ENGINE_EXECUTION_LIMITS_DEFAULTS = {
2861
+ defaultMaxNodeActivations: 1e5,
2862
+ hardMaxNodeActivations: 1e5,
2863
+ defaultMaxSubworkflowDepth: 32,
2864
+ hardMaxSubworkflowDepth: 32
2865
+ };
2866
+ /**
2867
+ * Resolves per-run execution limits: defaults, hard ceilings, and subworkflow depth for new runs.
2868
+ */
2869
+ var EngineExecutionLimitsPolicy = class {
2870
+ constructor(config = ENGINE_EXECUTION_LIMITS_DEFAULTS) {
2871
+ this.config = config;
2872
+ }
2873
+ /**
2874
+ * Effective options for a new root run (depth 0): defaults merged with engine ceilings.
2875
+ * Replaces a separate one-method factory for root-run bootstrap.
2876
+ */
2877
+ createRootExecutionOptions() {
2878
+ return this.mergeExecutionOptionsForNewRun(void 0, void 0);
2879
+ }
2880
+ mergeExecutionOptionsForNewRun(parent, user) {
2881
+ const subworkflowDepth = parent === void 0 ? 0 : (parent.subworkflowDepth ?? 0) + 1;
2882
+ const inheritedMaxNode = parent?.engineMaxNodeActivations;
2883
+ const inheritedMaxSub = parent?.engineMaxSubworkflowDepth;
2884
+ const maxNodeActivations = this.capNumber(user?.maxNodeActivations ?? inheritedMaxNode, this.config.defaultMaxNodeActivations, this.config.hardMaxNodeActivations);
2885
+ const maxSubworkflowDepth = this.capNumber(user?.maxSubworkflowDepth ?? inheritedMaxSub, this.config.defaultMaxSubworkflowDepth, this.config.hardMaxSubworkflowDepth);
2886
+ if (subworkflowDepth > maxSubworkflowDepth) throw new Error(`Subworkflow nesting depth ${subworkflowDepth} exceeds maxSubworkflowDepth ${maxSubworkflowDepth} (run would be a child of parent run).`);
2887
+ return {
2888
+ ...user,
2889
+ subworkflowDepth,
2890
+ maxNodeActivations,
2891
+ maxSubworkflowDepth
2892
+ };
2893
+ }
2894
+ capNumber(requested, defaultValue, hardCeiling) {
2895
+ const base = requested === void 0 ? defaultValue : requested;
2896
+ return Math.min(base, hardCeiling);
2897
+ }
2898
+ };
2899
+
2900
+ //#endregion
2901
+ //#region src/runStorage/BinaryBodyBufferReader.ts
2902
+ var BinaryBodyBufferReader = class {
2903
+ async read(body) {
2904
+ if (body instanceof Uint8Array) return body;
2905
+ if (body instanceof ArrayBuffer) return new Uint8Array(body);
2906
+ if (body instanceof ReadableStream) return await this.readReadableStream(body);
2907
+ return await this.readAsyncIterable(body);
2908
+ }
2909
+ async readReadableStream(body) {
2910
+ const reader = body.getReader();
2911
+ const chunks = [];
2912
+ let totalSize = 0;
2913
+ try {
2914
+ while (true) {
2915
+ const result = await reader.read();
2916
+ if (result.done) break;
2917
+ chunks.push(result.value);
2918
+ totalSize += result.value.byteLength;
2919
+ }
2920
+ } finally {
2921
+ reader.releaseLock();
2922
+ }
2923
+ return this.joinChunks(chunks, totalSize);
2924
+ }
2925
+ async readAsyncIterable(body) {
2926
+ const chunks = [];
2927
+ let totalSize = 0;
2928
+ for await (const chunk of body) {
2929
+ chunks.push(chunk);
2930
+ totalSize += chunk.byteLength;
2931
+ }
2932
+ return this.joinChunks(chunks, totalSize);
2933
+ }
2934
+ joinChunks(chunks, totalSize) {
2935
+ const bytes = new Uint8Array(totalSize);
2936
+ let offset = 0;
2937
+ for (const chunk of chunks) {
2938
+ bytes.set(chunk, offset);
2939
+ offset += chunk.byteLength;
2940
+ }
2941
+ return bytes;
2942
+ }
2943
+ };
2944
+
2945
+ //#endregion
2946
+ //#region src/runStorage/BinaryBodyReadableStreamFactory.ts
2947
+ var BinaryBodyReadableStreamFactory = class {
2948
+ constructor(bytes) {
2949
+ this.bytes = bytes;
2950
+ }
2951
+ create() {
2952
+ const value = this.bytes;
2953
+ let consumed = false;
2954
+ return new ReadableStream({ pull(controller) {
2955
+ if (consumed) {
2956
+ controller.close();
2957
+ return;
2958
+ }
2959
+ consumed = true;
2960
+ controller.enqueue(value);
2961
+ controller.close();
2962
+ } });
2963
+ }
2964
+ };
2965
+
2966
+ //#endregion
2967
+ //#region src/runStorage/InMemoryBinaryStorageRegistry.ts
2968
+ var InMemoryBinaryStorage = class {
2969
+ driverName = "memory";
2970
+ values = /* @__PURE__ */ new Map();
2971
+ async write(args) {
2972
+ const bytes = await new BinaryBodyBufferReader().read(args.body);
2973
+ this.values.set(args.storageKey, bytes);
2974
+ return {
2975
+ storageKey: args.storageKey,
2976
+ size: bytes.byteLength,
2977
+ sha256: createHash("sha256").update(bytes).digest("hex")
2978
+ };
2979
+ }
2980
+ async openReadStream(storageKey) {
2981
+ const bytes = this.values.get(storageKey);
2982
+ if (!bytes) return;
2983
+ return {
2984
+ body: new BinaryBodyReadableStreamFactory(bytes).create(),
2985
+ size: bytes.byteLength
2986
+ };
2987
+ }
2988
+ async stat(storageKey) {
2989
+ const bytes = this.values.get(storageKey);
2990
+ if (!bytes) return { exists: false };
2991
+ return {
2992
+ exists: true,
2993
+ size: bytes.byteLength
2994
+ };
2995
+ }
2996
+ async delete(storageKey) {
2997
+ this.values.delete(storageKey);
2998
+ }
2999
+ };
3000
+
3001
+ //#endregion
3002
+ //#region src/runStorage/InMemoryRunData.ts
3003
+ var InMemoryRunData = class {
3004
+ byNode = /* @__PURE__ */ new Map();
3005
+ constructor(initial) {
3006
+ if (initial) for (const [nodeId, outputs] of Object.entries(initial)) this.byNode.set(nodeId, outputs);
3007
+ }
3008
+ setOutputs(nodeId, outputs) {
3009
+ this.byNode.set(nodeId, outputs);
3010
+ }
3011
+ getOutputs(nodeId) {
3012
+ return this.byNode.get(nodeId);
3013
+ }
3014
+ getOutputItems(nodeId, output = "main") {
3015
+ return this.byNode.get(nodeId)?.[output] ?? [];
3016
+ }
3017
+ getOutputItem(nodeId, itemIndex, output = "main") {
3018
+ return this.getOutputItems(nodeId, output)[itemIndex];
3019
+ }
3020
+ dump() {
3021
+ const out = {};
3022
+ for (const [nodeId, outputs] of this.byNode.entries()) out[nodeId] = outputs;
3023
+ return out;
3024
+ }
3025
+ };
3026
+
3027
+ //#endregion
3028
+ //#region src/runStorage/InMemoryRunDataFactory.ts
3029
+ var InMemoryRunDataFactory = class {
3030
+ create(initial) {
3031
+ return new InMemoryRunData(initial);
3032
+ }
3033
+ };
3034
+
3035
+ //#endregion
3036
+ //#region src/contracts/runFinishedAtFactory.ts
3037
+ /** Derives workflow end time from node snapshots for run listings. */
3038
+ var RunFinishedAtFactory = class {
3039
+ static resolveIso(state) {
3040
+ if (state.status === "running" || state.status === "pending") return;
3041
+ let max;
3042
+ for (const snap of Object.values(state.nodeSnapshotsByNodeId)) if (snap?.finishedAt && (!max || snap.finishedAt > max)) max = snap.finishedAt;
3043
+ return max;
3044
+ }
3045
+ };
3046
+
3047
+ //#endregion
3048
+ //#region src/runtime/RunIntentService.ts
3049
+ var RunIntentService = class {
3050
+ constructor(engine, workflowRepository) {
3051
+ this.engine = engine;
3052
+ this.workflowRepository = workflowRepository;
3053
+ }
3054
+ async startWorkflow(args) {
3055
+ if (args.startAt && !args.currentState && !args.stopCondition && !args.reset) return await this.engine.runWorkflow(args.workflow, args.startAt, args.items, args.parent, args.executionOptions, {
3056
+ workflowSnapshot: args.workflowSnapshot,
3057
+ mutableState: args.mutableState
3058
+ });
3059
+ return await this.engine.runWorkflowFromState({
3060
+ workflow: args.workflow,
3061
+ items: args.items,
3062
+ parent: args.parent,
3063
+ executionOptions: args.executionOptions,
3064
+ workflowSnapshot: args.workflowSnapshot,
3065
+ mutableState: args.mutableState,
3066
+ currentState: args.currentState,
3067
+ stopCondition: args.stopCondition ?? { kind: "workflowCompleted" },
3068
+ reset: args.reset
3069
+ });
3070
+ }
3071
+ async rerunFromNode(args) {
3072
+ if (args.items) return await this.engine.runWorkflow(args.workflow, args.nodeId, args.items, args.parent, args.executionOptions, {
3073
+ workflowSnapshot: args.workflowSnapshot,
3074
+ mutableState: args.mutableState
3075
+ });
3076
+ return await this.engine.runWorkflowFromState({
3077
+ workflow: args.workflow,
3078
+ parent: args.parent,
3079
+ executionOptions: args.executionOptions,
3080
+ workflowSnapshot: args.workflowSnapshot,
3081
+ mutableState: args.mutableState,
3082
+ currentState: args.currentState,
3083
+ stopCondition: { kind: "workflowCompleted" },
3084
+ reset: { clearFromNodeId: args.nodeId }
3085
+ });
3086
+ }
3087
+ resolveWebhookTrigger(args) {
3088
+ return this.engine.resolveWebhookTrigger(args);
3089
+ }
3090
+ async runMatchedWebhook(args) {
3091
+ const resolution = this.resolveWebhookTrigger(args);
3092
+ if (resolution.status === "notFound") throw new Error("Unknown webhook endpoint");
3093
+ if (resolution.status === "methodNotAllowed") throw new Error("Method not allowed");
3094
+ return await this.runWebhookMatch({
3095
+ match: resolution.match,
3096
+ requestItem: args.requestItem
3097
+ });
3098
+ }
3099
+ async runWebhookMatch(args) {
3100
+ const workflow = this.workflowRepository.get(args.match.workflowId);
3101
+ if (!workflow) throw new Error(`Unknown workflowId: ${args.match.workflowId}`);
3102
+ const scheduled = await this.engine.runWorkflow(workflow, args.match.nodeId, [args.requestItem], void 0, this.createWebhookExecutionOptions());
3103
+ if (scheduled.status === "failed") throw new Error(scheduled.error.message);
3104
+ if (scheduled.status === "completed") return {
3105
+ runId: scheduled.runId,
3106
+ workflowId: scheduled.workflowId,
3107
+ startedAt: scheduled.startedAt,
3108
+ runStatus: "completed",
3109
+ response: scheduled.outputs
3110
+ };
3111
+ return await Promise.race([this.engine.waitForWebhookResponse(scheduled.runId), this.engine.waitForCompletion(scheduled.runId).then((completed) => {
3112
+ if (completed.status === "failed") throw new Error(completed.error.message);
3113
+ return {
3114
+ runId: completed.runId,
3115
+ workflowId: completed.workflowId,
3116
+ startedAt: completed.startedAt,
3117
+ runStatus: "completed",
3118
+ response: completed.outputs
3119
+ };
3120
+ })]);
3121
+ }
3122
+ /**
3123
+ * Webhook-triggered runs always force inline execution first.
3124
+ * This is the highest-precedence scheduler override: it wins over node hints and container defaults.
3125
+ */
3126
+ createWebhookExecutionOptions() {
3127
+ return {
3128
+ localOnly: true,
3129
+ webhook: true
3130
+ };
3131
+ }
3132
+ };
3133
+
3134
+ //#endregion
3135
+ export { instancePerContainerCachingFactory as $, InProcessRetryRunnerFactory as A, node as B, PersistedWorkflowTokenRegistry as C, NodeExecutorFactory as D, MissingRuntimeExecutionMarker as E, ActivationEnqueueService as F, PersistedRuntimeTypeNameResolver as G, InjectableRuntimeDecoratorComposer as H, DefaultExecutionBinaryService as I, delay as J, NodeEventPublisher as K, UnavailableBinaryStorage as L, DefaultExecutionContextFactory as M, DefaultAsyncSleeper as N, NodeExecutor as O, CredentialResolverFactory as P, instanceCachingFactory as Q, chatModel as R, WorkflowSnapshotResolver as S, MissingRuntimeTriggerToken as T, PersistedRuntimeTypeMetadataStore as U, tool as V, StackTraceCallSitePathResolver as W, injectAll as X, inject as Y, injectable as Z, RunStateSemantics as _, ENGINE_EXECUTION_LIMITS_DEFAULTS as a, WorkflowExecutableNodeClassifier as at, NodeInstanceFactoryFactory as b, InlineDrivingScheduler as c, ConfigDrivenOffloadPolicy as d, predicateAwareClassFactory as et, RunStartService as f, WorkflowRunExecutionContextFactory as g, WorkflowTopology as h, InMemoryBinaryStorage as i, WorkflowExecutableNodeClassifierFactory as it, InProcessRetryRunner as j, NodeActivationRequestComposer as k, HintOnlyOffloadPolicy as l, RunContinuationService as m, RunFinishedAtFactory as n, singleton as nt, EngineExecutionLimitsPolicy as o, ConnectionNodeIdFactory as ot, RunPolicySnapshotFactory as p, container as q, InMemoryRunDataFactory as r, CoreTokens as rt, LocalOnlyScheduler as s, RunIntentService as t, registry as tt, DefaultDrivingScheduler as u, PersistedRunStateTerminalBuilder as v, MissingRuntimeFallbacks as w, NodeInstanceFactory as x, NodeRunStateWriterFactory as y, getPersistedRuntimeTypeMetadata as z };
3136
+ //# sourceMappingURL=RunIntentService-CYnn140t.js.map