@cadenza.io/core 3.14.0 → 3.15.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -1000,6 +1000,7 @@ declare class Task extends SignalEmitter implements Graph {
1000
1000
  * @return {any[]} An array containing the results of applying the callback function to each predecessor task.
1001
1001
  */
1002
1002
  mapPrevious(callback: (task: Task) => any): any[];
1003
+ makeRoutine(name: string, description: string): this;
1003
1004
  /**
1004
1005
  * Adds the specified signals to the current instance, making it observe them.
1005
1006
  * If the instance is already observing a signal, it will be skipped.
@@ -1027,11 +1028,10 @@ declare class Task extends SignalEmitter implements Graph {
1027
1028
  /**
1028
1029
  * Attaches a signal to the current context and emits metadata if the register flag is set.
1029
1030
  *
1030
- * @param {string} signal - The name of the signal to attach.
1031
- * @param {boolean} [isOnFail=false] - Indicates if the signal should be marked as "on fail".
1031
+ * @param {...string} signals - The names of the signals to attach.
1032
1032
  * @return {void} This method does not return a value.
1033
1033
  */
1034
- attachSignal(signal: string, isOnFail?: boolean): void;
1034
+ attachSignal(...signals: string[]): Task;
1035
1035
  /**
1036
1036
  * Unsubscribes the current instance from the specified signals.
1037
1037
  * This method removes the signals from the observedSignals set, unsubscribes
@@ -1358,7 +1358,6 @@ declare class GraphRunner extends SignalEmitter {
1358
1358
  * @edge Creates 'Start run' meta-task chained to registry gets.
1359
1359
  */
1360
1360
  constructor(isMeta?: boolean);
1361
- init(): void;
1362
1361
  /**
1363
1362
  * Adds tasks or routines to the current execution pipeline. Supports both individual tasks,
1364
1363
  * routines, or arrays of tasks and routines. Handles metadata and execution context management.
@@ -1405,7 +1404,6 @@ declare class GraphRunner extends SignalEmitter {
1405
1404
  * @return {void}
1406
1405
  */
1407
1406
  setStrategy(strategy: GraphRunStrategy): void;
1408
- startRun(context: AnyObject, emit: (signal: string, ctx: AnyObject) => void): boolean;
1409
1407
  }
1410
1408
 
1411
1409
  /**
@@ -1432,7 +1430,6 @@ declare class SignalBroker {
1432
1430
  runner: GraphRunner | undefined;
1433
1431
  metaRunner: GraphRunner | undefined;
1434
1432
  debouncedEmitters: Map<string, any>;
1435
- clearSignalsTask: Task | undefined;
1436
1433
  getSignalsTask: Task | undefined;
1437
1434
  registerSignalTask: Task | undefined;
1438
1435
  signalObservers: Map<string, {
@@ -1440,7 +1437,7 @@ declare class SignalBroker {
1440
1437
  tasks: Set<Task | GraphRoutine>;
1441
1438
  registered: boolean;
1442
1439
  }>;
1443
- emitStacks: Map<string, Map<string, AnyObject>>;
1440
+ emittedSignalsRegistry: Set<string>;
1444
1441
  constructor();
1445
1442
  /**
1446
1443
  * Initializes with runners.
@@ -1461,6 +1458,7 @@ declare class SignalBroker {
1461
1458
  * @edge Duplicates ignored; supports wildcards for broad listening.
1462
1459
  */
1463
1460
  observe(signal: string, routineOrTask: Task | GraphRoutine): void;
1461
+ registerEmittedSignal(signal: string): void;
1464
1462
  /**
1465
1463
  * Unsubscribes a routine/task from a signal.
1466
1464
  * @param signal The signal.
@@ -1534,6 +1532,7 @@ declare class SignalBroker {
1534
1532
  * @returns Array of signals.
1535
1533
  */
1536
1534
  listObservedSignals(): string[];
1535
+ listEmittedSignals(): string[];
1537
1536
  reset(): void;
1538
1537
  }
1539
1538
 
package/dist/index.d.ts CHANGED
@@ -1000,6 +1000,7 @@ declare class Task extends SignalEmitter implements Graph {
1000
1000
  * @return {any[]} An array containing the results of applying the callback function to each predecessor task.
1001
1001
  */
1002
1002
  mapPrevious(callback: (task: Task) => any): any[];
1003
+ makeRoutine(name: string, description: string): this;
1003
1004
  /**
1004
1005
  * Adds the specified signals to the current instance, making it observe them.
1005
1006
  * If the instance is already observing a signal, it will be skipped.
@@ -1027,11 +1028,10 @@ declare class Task extends SignalEmitter implements Graph {
1027
1028
  /**
1028
1029
  * Attaches a signal to the current context and emits metadata if the register flag is set.
1029
1030
  *
1030
- * @param {string} signal - The name of the signal to attach.
1031
- * @param {boolean} [isOnFail=false] - Indicates if the signal should be marked as "on fail".
1031
+ * @param {...string} signals - The names of the signals to attach.
1032
1032
  * @return {void} This method does not return a value.
1033
1033
  */
1034
- attachSignal(signal: string, isOnFail?: boolean): void;
1034
+ attachSignal(...signals: string[]): Task;
1035
1035
  /**
1036
1036
  * Unsubscribes the current instance from the specified signals.
1037
1037
  * This method removes the signals from the observedSignals set, unsubscribes
@@ -1358,7 +1358,6 @@ declare class GraphRunner extends SignalEmitter {
1358
1358
  * @edge Creates 'Start run' meta-task chained to registry gets.
1359
1359
  */
1360
1360
  constructor(isMeta?: boolean);
1361
- init(): void;
1362
1361
  /**
1363
1362
  * Adds tasks or routines to the current execution pipeline. Supports both individual tasks,
1364
1363
  * routines, or arrays of tasks and routines. Handles metadata and execution context management.
@@ -1405,7 +1404,6 @@ declare class GraphRunner extends SignalEmitter {
1405
1404
  * @return {void}
1406
1405
  */
1407
1406
  setStrategy(strategy: GraphRunStrategy): void;
1408
- startRun(context: AnyObject, emit: (signal: string, ctx: AnyObject) => void): boolean;
1409
1407
  }
1410
1408
 
1411
1409
  /**
@@ -1432,7 +1430,6 @@ declare class SignalBroker {
1432
1430
  runner: GraphRunner | undefined;
1433
1431
  metaRunner: GraphRunner | undefined;
1434
1432
  debouncedEmitters: Map<string, any>;
1435
- clearSignalsTask: Task | undefined;
1436
1433
  getSignalsTask: Task | undefined;
1437
1434
  registerSignalTask: Task | undefined;
1438
1435
  signalObservers: Map<string, {
@@ -1440,7 +1437,7 @@ declare class SignalBroker {
1440
1437
  tasks: Set<Task | GraphRoutine>;
1441
1438
  registered: boolean;
1442
1439
  }>;
1443
- emitStacks: Map<string, Map<string, AnyObject>>;
1440
+ emittedSignalsRegistry: Set<string>;
1444
1441
  constructor();
1445
1442
  /**
1446
1443
  * Initializes with runners.
@@ -1461,6 +1458,7 @@ declare class SignalBroker {
1461
1458
  * @edge Duplicates ignored; supports wildcards for broad listening.
1462
1459
  */
1463
1460
  observe(signal: string, routineOrTask: Task | GraphRoutine): void;
1461
+ registerEmittedSignal(signal: string): void;
1464
1462
  /**
1465
1463
  * Unsubscribes a routine/task from a signal.
1466
1464
  * @param signal The signal.
@@ -1534,6 +1532,7 @@ declare class SignalBroker {
1534
1532
  * @returns Array of signals.
1535
1533
  */
1536
1534
  listObservedSignals(): string[];
1535
+ listEmittedSignals(): string[];
1537
1536
  reset(): void;
1538
1537
  }
1539
1538
 
package/dist/index.js CHANGED
@@ -295,14 +295,13 @@ var debounce_default = debounce;
295
295
 
296
296
  // src/engine/SignalBroker.ts
297
297
  var SignalBroker = class _SignalBroker {
298
- // execId -> emitted signals
299
298
  constructor() {
300
299
  this.debug = false;
301
300
  this.verbose = false;
302
301
  this.debouncedEmitters = /* @__PURE__ */ new Map();
303
302
  // TODO: Signals should be a class with a the observers, registered flag and other data.
304
303
  this.signalObservers = /* @__PURE__ */ new Map();
305
- this.emitStacks = /* @__PURE__ */ new Map();
304
+ this.emittedSignalsRegistry = /* @__PURE__ */ new Set();
306
305
  this.addSignal("meta.signal_broker.added");
307
306
  }
308
307
  static get instance() {
@@ -361,20 +360,6 @@ var SignalBroker = class _SignalBroker {
361
360
  * @return {void} This method does not return a value.
362
361
  */
363
362
  init() {
364
- this.clearSignalsTask = Cadenza.createDebounceMetaTask(
365
- "Execute and clear queued signals",
366
- () => {
367
- for (const [id, signals] of this.emitStacks.entries()) {
368
- signals.forEach((context, signal) => {
369
- this.execute(signal, context);
370
- signals.delete(signal);
371
- });
372
- this.emitStacks.delete(id);
373
- }
374
- return true;
375
- },
376
- "Executes queued signals and clears the stack"
377
- ).doOn("meta.process_signal_queue_requested").emits("meta.signal_broker.queue_empty");
378
363
  this.getSignalsTask = Cadenza.createMetaTask("Get signals", (ctx) => {
379
364
  const uniqueSignals = Array.from(this.signalObservers.keys()).filter(
380
365
  (s) => !s.includes(":")
@@ -408,6 +393,9 @@ var SignalBroker = class _SignalBroker {
408
393
  this.addSignal(signal);
409
394
  this.signalObservers.get(signal).tasks.add(routineOrTask);
410
395
  }
396
+ registerEmittedSignal(signal) {
397
+ this.emittedSignalsRegistry.add(signal);
398
+ }
411
399
  /**
412
400
  * Unsubscribes a routine/task from a signal.
413
401
  * @param signal The signal.
@@ -515,19 +503,9 @@ var SignalBroker = class _SignalBroker {
515
503
  * @return {void} This method does not return a value.
516
504
  */
517
505
  emit(signal, context = {}) {
518
- const execId = context.__routineExecId || "global";
519
506
  delete context.__routineExecId;
520
- if (!this.emitStacks.has(execId)) this.emitStacks.set(execId, /* @__PURE__ */ new Map());
521
- const stack = this.emitStacks.get(execId);
522
- stack.set(signal, context);
523
507
  this.addSignal(signal);
524
- let executed = false;
525
- try {
526
- executed = this.execute(signal, context);
527
- } finally {
528
- if (executed) stack.delete(signal);
529
- if (stack.size === 0) this.emitStacks.delete(execId);
530
- }
508
+ this.execute(signal, context);
531
509
  }
532
510
  /**
533
511
  * Executes a signal by emitting events, updating context, and invoking listeners.
@@ -683,14 +661,17 @@ var SignalBroker = class _SignalBroker {
683
661
  listObservedSignals() {
684
662
  return Array.from(this.signalObservers.keys());
685
663
  }
664
+ listEmittedSignals() {
665
+ return Array.from(this.emittedSignalsRegistry);
666
+ }
686
667
  reset() {
687
- this.emitStacks.clear();
688
668
  this.signalObservers.clear();
669
+ this.emittedSignalsRegistry.clear();
689
670
  }
690
671
  };
691
672
 
692
673
  // src/engine/GraphRunner.ts
693
- var import_uuid6 = require("uuid");
674
+ var import_uuid5 = require("uuid");
694
675
 
695
676
  // src/engine/GraphRun.ts
696
677
  var import_uuid2 = require("uuid");
@@ -2195,8 +2176,178 @@ var GraphRoutine = class extends SignalEmitter {
2195
2176
  }
2196
2177
  };
2197
2178
 
2179
+ // src/engine/GraphRunner.ts
2180
+ var GraphRunner = class extends SignalEmitter {
2181
+ /**
2182
+ * Constructs a runner.
2183
+ * @param isMeta Meta flag (default false).
2184
+ * @edge Creates 'Start run' meta-task chained to registry gets.
2185
+ */
2186
+ constructor(isMeta = false) {
2187
+ super(isMeta);
2188
+ this.debug = false;
2189
+ this.verbose = false;
2190
+ this.isRunning = false;
2191
+ this.isMeta = false;
2192
+ this.isMeta = isMeta;
2193
+ this.strategy = Cadenza.runStrategy.PARALLEL;
2194
+ this.currentRun = new GraphRun(this.strategy);
2195
+ }
2196
+ /**
2197
+ * Adds tasks or routines to the current execution pipeline. Supports both individual tasks,
2198
+ * routines, or arrays of tasks and routines. Handles metadata and execution context management.
2199
+ *
2200
+ * @param {Task|GraphRoutine|(Task|GraphRoutine)[]} tasks - The task(s) or routine(s) to be added.
2201
+ * It can be a single task, a single routine, or an array of tasks and routines.
2202
+ * @param {AnyObject} [context={}] - Optional context object to provide execution trace and metadata.
2203
+ * Used to propagate information across task or routine executions.
2204
+ * @return {void} - This method does not return a value.
2205
+ */
2206
+ addTasks(tasks, context = {}) {
2207
+ let _tasks = Array.isArray(tasks) ? tasks : [tasks];
2208
+ if (_tasks.length === 0) {
2209
+ console.warn("No tasks/routines to add.");
2210
+ return;
2211
+ }
2212
+ let routineName = _tasks.map((t) => t.name).join(" | ");
2213
+ let routineVersion = null;
2214
+ let isMeta = _tasks.every((t) => t.isMeta);
2215
+ const allTasks = _tasks.flatMap((t) => {
2216
+ if (t instanceof GraphRoutine) {
2217
+ routineName = t.name;
2218
+ routineVersion = t.version;
2219
+ isMeta = t.isMeta;
2220
+ const routineTasks = [];
2221
+ t.forEachTask((task) => routineTasks.push(task));
2222
+ return routineTasks;
2223
+ }
2224
+ return t;
2225
+ });
2226
+ const isSubMeta = allTasks.some((t) => t.isSubMeta) || !!context.__isSubMeta;
2227
+ context.__isSubMeta = isSubMeta;
2228
+ const isNewTrace = !context.__routineExecId && !context.__metadata?.__executionTraceId && !context.__executionTraceId;
2229
+ const executionTraceId = context.__metadata?.__executionTraceId ?? context.__executionTraceId ?? (0, import_uuid5.v4)();
2230
+ context.__executionTraceId = executionTraceId;
2231
+ const routineExecId = context.__routineExecId ?? (0, import_uuid5.v4)();
2232
+ context.__routineExecId = routineExecId;
2233
+ const ctx = new GraphContext(context || {});
2234
+ if (!isSubMeta) {
2235
+ const contextData = ctx.export();
2236
+ if (isNewTrace) {
2237
+ this.emitMetrics("meta.runner.new_trace", {
2238
+ data: {
2239
+ uuid: executionTraceId,
2240
+ issuer_type: "service",
2241
+ // TODO: Add issuer type
2242
+ issuer_id: context.__metadata?.__issuerId ?? context.__issuerId ?? null,
2243
+ issued_at: formatTimestamp(Date.now()),
2244
+ intent: context.__metadata?.__intent ?? context.__intent ?? null,
2245
+ context: contextData,
2246
+ is_meta: isMeta
2247
+ },
2248
+ __metadata: {
2249
+ __executionTraceId: executionTraceId
2250
+ }
2251
+ });
2252
+ }
2253
+ this.emitMetrics("meta.runner.added_tasks", {
2254
+ data: {
2255
+ uuid: routineExecId,
2256
+ name: routineName,
2257
+ routineVersion,
2258
+ isMeta,
2259
+ executionTraceId,
2260
+ context: isNewTrace ? contextData.id : contextData,
2261
+ previousRoutineExecution: context.__localRoutineExecId ?? context.__metadata?.__routineExecId ?? null,
2262
+ created: formatTimestamp(Date.now())
2263
+ },
2264
+ __metadata: {
2265
+ __executionTraceId: executionTraceId
2266
+ }
2267
+ });
2268
+ }
2269
+ allTasks.forEach(
2270
+ (task) => this.currentRun.addNode(
2271
+ new GraphNode(task, ctx, routineExecId, [], this.debug, this.verbose)
2272
+ )
2273
+ );
2274
+ }
2275
+ /**
2276
+ * Executes the provided tasks or routines. Maintains the execution state
2277
+ * and handles synchronous or asynchronous processing.
2278
+ *
2279
+ * @param {Task|GraphRoutine|(Task|GraphRoutine)[]} [tasks] - A single task, a single routine, or an array of tasks or routines to execute. Optional.
2280
+ * @param {AnyObject} [context] - An optional context object to be used during task execution.
2281
+ * @return {GraphRun|Promise<GraphRun>} - Returns a `GraphRun` instance if the execution is synchronous, or a `Promise` resolving to a `GraphRun` for asynchronous execution.
2282
+ */
2283
+ run(tasks, context) {
2284
+ if (tasks) {
2285
+ this.addTasks(tasks, context ?? {});
2286
+ }
2287
+ if (this.isRunning) {
2288
+ return this.currentRun;
2289
+ }
2290
+ if (this.currentRun) {
2291
+ this.isRunning = true;
2292
+ const runResult = this.currentRun.run();
2293
+ if (runResult instanceof Promise) {
2294
+ return this.runAsync(runResult);
2295
+ }
2296
+ }
2297
+ return this.reset();
2298
+ }
2299
+ /**
2300
+ * Executes the provided asynchronous operation and resets the state afterwards.
2301
+ *
2302
+ * @param {Promise<void>} run - A promise representing the asynchronous operation to execute.
2303
+ * @return {Promise<GraphRun>} A promise that resolves to the result of the reset operation after the asynchronous operation completes.
2304
+ */
2305
+ async runAsync(run) {
2306
+ await run;
2307
+ return this.reset();
2308
+ }
2309
+ /**
2310
+ * Resets the current state of the graph, creating a new GraphRun instance
2311
+ * and returning the previous run instance.
2312
+ * If the debug mode is not enabled, it will destroy the existing resources.
2313
+ *
2314
+ * @return {GraphRun} The last GraphRun instance before the reset.
2315
+ */
2316
+ reset() {
2317
+ this.isRunning = false;
2318
+ const lastRun = this.currentRun;
2319
+ if (!this.debug) {
2320
+ this.destroy();
2321
+ }
2322
+ this.currentRun = new GraphRun(this.strategy);
2323
+ return lastRun;
2324
+ }
2325
+ setDebug(value) {
2326
+ this.debug = value;
2327
+ }
2328
+ setVerbose(value) {
2329
+ this.verbose = value;
2330
+ }
2331
+ destroy() {
2332
+ this.currentRun.destroy();
2333
+ }
2334
+ /**
2335
+ * Sets the strategy to be used for running the graph and initializes
2336
+ * the current run with the provided strategy if no process is currently running.
2337
+ *
2338
+ * @param {GraphRunStrategy} strategy - The strategy to use for running the graph.
2339
+ * @return {void}
2340
+ */
2341
+ setStrategy(strategy) {
2342
+ this.strategy = strategy;
2343
+ if (!this.isRunning) {
2344
+ this.currentRun = new GraphRun(this.strategy);
2345
+ }
2346
+ }
2347
+ };
2348
+
2198
2349
  // src/graph/definition/Task.ts
2199
- var import_uuid5 = require("uuid");
2350
+ var import_uuid6 = require("uuid");
2200
2351
 
2201
2352
  // src/graph/iterators/TaskIterator.ts
2202
2353
  var TaskIterator = class {
@@ -2345,7 +2496,7 @@ var Task = class _Task extends SignalEmitter {
2345
2496
  }
2346
2497
  clone(traverse = false, includeSignals = false) {
2347
2498
  const clonedTask = new _Task(
2348
- `${this.name} (clone ${(0, import_uuid5.v4)().slice(0, 8)})`,
2499
+ `${this.name} (clone ${(0, import_uuid6.v4)().slice(0, 8)})`,
2349
2500
  this.taskFunction,
2350
2501
  this.description,
2351
2502
  this.concurrency,
@@ -2830,6 +2981,14 @@ var Task = class _Task extends SignalEmitter {
2830
2981
  mapPrevious(callback) {
2831
2982
  return Array.from(this.predecessorTasks).map(callback);
2832
2983
  }
2984
+ makeRoutine(name, description) {
2985
+ if (this.isMeta) {
2986
+ Cadenza.createMetaRoutine(name, [this], description);
2987
+ } else {
2988
+ Cadenza.createRoutine(name, [this], description);
2989
+ }
2990
+ return this;
2991
+ }
2833
2992
  /**
2834
2993
  * Adds the specified signals to the current instance, making it observe them.
2835
2994
  * If the instance is already observing a signal, it will be skipped.
@@ -2886,29 +3045,33 @@ var Task = class _Task extends SignalEmitter {
2886
3045
  emitsOnFail(...signals) {
2887
3046
  signals.forEach((signal) => {
2888
3047
  this.signalsToEmitOnFail.add(signal);
2889
- this.attachSignal(signal, true);
3048
+ this.attachSignal(signal);
2890
3049
  });
2891
3050
  return this;
2892
3051
  }
2893
3052
  /**
2894
3053
  * Attaches a signal to the current context and emits metadata if the register flag is set.
2895
3054
  *
2896
- * @param {string} signal - The name of the signal to attach.
2897
- * @param {boolean} [isOnFail=false] - Indicates if the signal should be marked as "on fail".
3055
+ * @param {...string} signals - The names of the signals to attach.
2898
3056
  * @return {void} This method does not return a value.
2899
3057
  */
2900
- attachSignal(signal, isOnFail = false) {
2901
- this.emitsSignals.add(signal);
2902
- if (this.register) {
2903
- this.emitWithMetadata("meta.task.attached_signal", {
2904
- data: {
2905
- signalName: signal.split(":")[0],
2906
- taskName: this.name,
2907
- taskVersion: this.version,
2908
- isOnFail
2909
- }
2910
- });
2911
- }
3058
+ attachSignal(...signals) {
3059
+ signals.forEach((signal) => {
3060
+ this.emitsSignals.add(signal);
3061
+ Cadenza.broker.registerEmittedSignal(signal);
3062
+ if (this.register) {
3063
+ const isOnFail = this.signalsToEmitOnFail.has(signal);
3064
+ this.emitWithMetadata("meta.task.attached_signal", {
3065
+ data: {
3066
+ signalName: signal.split(":")[0],
3067
+ taskName: this.name,
3068
+ taskVersion: this.version,
3069
+ isOnFail
3070
+ }
3071
+ });
3072
+ }
3073
+ });
3074
+ return this;
2912
3075
  }
2913
3076
  /**
2914
3077
  * Unsubscribes the current instance from the specified signals.
@@ -3288,205 +3451,6 @@ var GraphRegistry = class _GraphRegistry {
3288
3451
  }
3289
3452
  };
3290
3453
 
3291
- // src/engine/GraphRunner.ts
3292
- var GraphRunner = class extends SignalEmitter {
3293
- /**
3294
- * Constructs a runner.
3295
- * @param isMeta Meta flag (default false).
3296
- * @edge Creates 'Start run' meta-task chained to registry gets.
3297
- */
3298
- constructor(isMeta = false) {
3299
- super(isMeta);
3300
- this.debug = false;
3301
- this.verbose = false;
3302
- this.isRunning = false;
3303
- this.isMeta = false;
3304
- this.isMeta = isMeta;
3305
- this.strategy = Cadenza.runStrategy.PARALLEL;
3306
- this.currentRun = new GraphRun(this.strategy);
3307
- }
3308
- init() {
3309
- if (this.isMeta) return;
3310
- Cadenza.createMetaTask(
3311
- "Start run",
3312
- this.startRun.bind(this),
3313
- "Starts a run"
3314
- ).doAfter(
3315
- GraphRegistry.instance.getTaskByName,
3316
- GraphRegistry.instance.getRoutineByName
3317
- );
3318
- }
3319
- /**
3320
- * Adds tasks or routines to the current execution pipeline. Supports both individual tasks,
3321
- * routines, or arrays of tasks and routines. Handles metadata and execution context management.
3322
- *
3323
- * @param {Task|GraphRoutine|(Task|GraphRoutine)[]} tasks - The task(s) or routine(s) to be added.
3324
- * It can be a single task, a single routine, or an array of tasks and routines.
3325
- * @param {AnyObject} [context={}] - Optional context object to provide execution trace and metadata.
3326
- * Used to propagate information across task or routine executions.
3327
- * @return {void} - This method does not return a value.
3328
- */
3329
- addTasks(tasks, context = {}) {
3330
- let _tasks = Array.isArray(tasks) ? tasks : [tasks];
3331
- if (_tasks.length === 0) {
3332
- console.warn("No tasks/routines to add.");
3333
- return;
3334
- }
3335
- let routineName = _tasks.map((t) => t.name).join(" | ");
3336
- let routineVersion = null;
3337
- let isMeta = _tasks.every((t) => t.isMeta);
3338
- const allTasks = _tasks.flatMap((t) => {
3339
- if (t instanceof GraphRoutine) {
3340
- routineName = t.name;
3341
- routineVersion = t.version;
3342
- isMeta = t.isMeta;
3343
- const routineTasks = [];
3344
- t.forEachTask((task) => routineTasks.push(task));
3345
- return routineTasks;
3346
- }
3347
- return t;
3348
- });
3349
- const isSubMeta = allTasks.some((t) => t.isSubMeta) || !!context.__isSubMeta;
3350
- context.__isSubMeta = isSubMeta;
3351
- const isNewTrace = !context.__routineExecId && !context.__metadata?.__executionTraceId && !context.__executionTraceId;
3352
- const executionTraceId = context.__metadata?.__executionTraceId ?? context.__executionTraceId ?? (0, import_uuid6.v4)();
3353
- context.__executionTraceId = executionTraceId;
3354
- const routineExecId = context.__routineExecId ?? (0, import_uuid6.v4)();
3355
- context.__routineExecId = routineExecId;
3356
- const ctx = new GraphContext(context || {});
3357
- if (!isSubMeta) {
3358
- const contextData = ctx.export();
3359
- if (isNewTrace) {
3360
- this.emitMetrics("meta.runner.new_trace", {
3361
- data: {
3362
- uuid: executionTraceId,
3363
- issuer_type: "service",
3364
- // TODO: Add issuer type
3365
- issuer_id: context.__metadata?.__issuerId ?? context.__issuerId ?? null,
3366
- issued_at: formatTimestamp(Date.now()),
3367
- intent: context.__metadata?.__intent ?? context.__intent ?? null,
3368
- context: contextData,
3369
- is_meta: isMeta
3370
- },
3371
- __metadata: {
3372
- __executionTraceId: executionTraceId
3373
- }
3374
- });
3375
- }
3376
- this.emitMetrics("meta.runner.added_tasks", {
3377
- data: {
3378
- uuid: routineExecId,
3379
- name: routineName,
3380
- routineVersion,
3381
- isMeta,
3382
- executionTraceId,
3383
- context: isNewTrace ? contextData.id : contextData,
3384
- previousRoutineExecution: context.__localRoutineExecId ?? context.__metadata?.__routineExecId ?? null,
3385
- // TODO: There is a chance this is not added to the database yet...
3386
- created: formatTimestamp(Date.now())
3387
- },
3388
- __metadata: {
3389
- __executionTraceId: executionTraceId
3390
- }
3391
- });
3392
- }
3393
- allTasks.forEach(
3394
- (task) => this.currentRun.addNode(
3395
- new GraphNode(task, ctx, routineExecId, [], this.debug, this.verbose)
3396
- )
3397
- );
3398
- }
3399
- /**
3400
- * Executes the provided tasks or routines. Maintains the execution state
3401
- * and handles synchronous or asynchronous processing.
3402
- *
3403
- * @param {Task|GraphRoutine|(Task|GraphRoutine)[]} [tasks] - A single task, a single routine, or an array of tasks or routines to execute. Optional.
3404
- * @param {AnyObject} [context] - An optional context object to be used during task execution.
3405
- * @return {GraphRun|Promise<GraphRun>} - Returns a `GraphRun` instance if the execution is synchronous, or a `Promise` resolving to a `GraphRun` for asynchronous execution.
3406
- */
3407
- run(tasks, context) {
3408
- if (tasks) {
3409
- this.addTasks(tasks, context ?? {});
3410
- }
3411
- if (this.isRunning) {
3412
- return this.currentRun;
3413
- }
3414
- if (this.currentRun) {
3415
- this.isRunning = true;
3416
- const runResult = this.currentRun.run();
3417
- if (runResult instanceof Promise) {
3418
- return this.runAsync(runResult);
3419
- }
3420
- }
3421
- return this.reset();
3422
- }
3423
- /**
3424
- * Executes the provided asynchronous operation and resets the state afterwards.
3425
- *
3426
- * @param {Promise<void>} run - A promise representing the asynchronous operation to execute.
3427
- * @return {Promise<GraphRun>} A promise that resolves to the result of the reset operation after the asynchronous operation completes.
3428
- */
3429
- async runAsync(run) {
3430
- await run;
3431
- return this.reset();
3432
- }
3433
- /**
3434
- * Resets the current state of the graph, creating a new GraphRun instance
3435
- * and returning the previous run instance.
3436
- * If the debug mode is not enabled, it will destroy the existing resources.
3437
- *
3438
- * @return {GraphRun} The last GraphRun instance before the reset.
3439
- */
3440
- reset() {
3441
- this.isRunning = false;
3442
- const lastRun = this.currentRun;
3443
- if (!this.debug) {
3444
- this.destroy();
3445
- }
3446
- this.currentRun = new GraphRun(this.strategy);
3447
- return lastRun;
3448
- }
3449
- setDebug(value) {
3450
- this.debug = value;
3451
- }
3452
- setVerbose(value) {
3453
- this.verbose = value;
3454
- }
3455
- destroy() {
3456
- this.currentRun.destroy();
3457
- }
3458
- /**
3459
- * Sets the strategy to be used for running the graph and initializes
3460
- * the current run with the provided strategy if no process is currently running.
3461
- *
3462
- * @param {GraphRunStrategy} strategy - The strategy to use for running the graph.
3463
- * @return {void}
3464
- */
3465
- setStrategy(strategy) {
3466
- this.strategy = strategy;
3467
- if (!this.isRunning) {
3468
- this.currentRun = new GraphRun(this.strategy);
3469
- }
3470
- }
3471
- // TODO This should not live here. This is deputy related.
3472
- startRun(context, emit) {
3473
- if (context.task || context.routine) {
3474
- const routine = context.task ?? context.routine;
3475
- delete context.task;
3476
- delete context.routine;
3477
- context.__routineExecId = context.__metadata?.__deputyExecId ?? null;
3478
- context.__isDeputy = true;
3479
- this.run(routine, context);
3480
- return true;
3481
- } else {
3482
- context.errored = true;
3483
- context.__error = "No routine or task defined.";
3484
- emit("meta.runner.failed", context);
3485
- return false;
3486
- }
3487
- }
3488
- };
3489
-
3490
3454
  // src/graph/definition/DebounceTask.ts
3491
3455
  var DebounceTask = class extends Task {
3492
3456
  constructor(name, task, description = "", debounceTime = 1e3, leading = false, trailing = true, maxWait = 0, concurrency = 0, timeout = 0, register = true, isUnique = false, isMeta = false, isSubMeta = false, isHidden = false, inputSchema = void 0, validateInputSchema = false, outputSchema = void 0, validateOutputSchema = false) {
@@ -4445,8 +4409,6 @@ var Cadenza = class {
4445
4409
  }
4446
4410
  this.registry = GraphRegistry.instance;
4447
4411
  this.broker.init();
4448
- this.runner.init();
4449
- this.metaRunner.init();
4450
4412
  }
4451
4413
  /**
4452
4414
  * Retrieves the available strategies for running graphs.