observed-js 0.1.0 → 0.3.0

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.
@@ -1,12 +1,165 @@
1
1
  import { ExecutionScheduler } from "../scheduler/index.js";
2
+ import { AsyncLocalStorage } from "node:async_hooks";
3
+ let globalContextWarningOptions;
4
+ export const setContextWarningThreshold = (options) => {
5
+ globalContextWarningOptions = options;
6
+ };
7
+ const resolveContextWarningOptions = (actionOptions) => {
8
+ if (!globalContextWarningOptions && !actionOptions) {
9
+ return undefined;
10
+ }
11
+ const merged = {};
12
+ if (globalContextWarningOptions?.maxAttachmentBytes !== undefined) {
13
+ merged.maxAttachmentBytes = globalContextWarningOptions.maxAttachmentBytes;
14
+ }
15
+ if (globalContextWarningOptions?.maxDepth !== undefined) {
16
+ merged.maxDepth = globalContextWarningOptions.maxDepth;
17
+ }
18
+ if (actionOptions?.maxAttachmentBytes !== undefined) {
19
+ merged.maxAttachmentBytes = actionOptions.maxAttachmentBytes;
20
+ }
21
+ if (actionOptions?.maxDepth !== undefined) {
22
+ merged.maxDepth = actionOptions.maxDepth;
23
+ }
24
+ const onWarning = actionOptions?.onWarning ?? globalContextWarningOptions?.onWarning;
25
+ if (onWarning) {
26
+ merged.onWarning = onWarning;
27
+ }
28
+ return merged;
29
+ };
30
+ const propagationStore = new AsyncLocalStorage();
31
+ const getPropagationContext = () => propagationStore.getStore();
32
+ const buildParentContextSnapshot = (context) => {
33
+ if (context.parentContext) {
34
+ return context.parentContext;
35
+ }
36
+ const snapshot = {
37
+ actionId: context.actionId,
38
+ attachments: context.invocationContext.getAttachments(),
39
+ traceId: context.traceId,
40
+ depth: context.depth,
41
+ parent: context.parent ? buildParentContextSnapshot(context.parent) : undefined
42
+ };
43
+ context.parentContext = snapshot;
44
+ return snapshot;
45
+ };
46
+ const runWithPropagationContext = (context, fn) => {
47
+ return propagationStore.run(context, fn);
48
+ };
49
+ const PRIORITY_VALUES = {
50
+ low: 0,
51
+ normal: 50,
52
+ high: 75,
53
+ critical: 100
54
+ };
55
+ const isPlainObject = (value) => {
56
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
57
+ };
58
+ const isInvokeOptions = (value) => {
59
+ if (!isPlainObject(value)) {
60
+ return false;
61
+ }
62
+ const maybe = value;
63
+ const hasPriority = Object.prototype.hasOwnProperty.call(maybe, 'priority');
64
+ const hasMetadata = Object.prototype.hasOwnProperty.call(maybe, 'metadata');
65
+ if (!hasPriority && !hasMetadata) {
66
+ return false;
67
+ }
68
+ if (hasPriority) {
69
+ const p = maybe.priority;
70
+ if (p !== undefined && typeof p !== 'string' && typeof p !== 'number') {
71
+ return false;
72
+ }
73
+ }
74
+ if (hasMetadata) {
75
+ const m = maybe.metadata;
76
+ if (m !== undefined && !isPlainObject(m)) {
77
+ return false;
78
+ }
79
+ }
80
+ return true;
81
+ };
82
+ const normalizePriority = (priority) => {
83
+ if (priority === undefined) {
84
+ return PRIORITY_VALUES.normal;
85
+ }
86
+ if (typeof priority === 'string') {
87
+ const mapped = PRIORITY_VALUES[priority];
88
+ if (mapped === undefined) {
89
+ throw new Error(`Unknown priority level: ${priority}`);
90
+ }
91
+ return mapped;
92
+ }
93
+ if (typeof priority !== 'number' || !Number.isFinite(priority)) {
94
+ throw new Error('Priority must be a finite number');
95
+ }
96
+ if (priority < 0 || priority > 100) {
97
+ throw new Error('Priority must be in range [0, 100]');
98
+ }
99
+ return priority;
100
+ };
101
+ /**
102
+ * Error thrown when an operation times out
103
+ */
104
+ export class TimeoutError extends Error {
105
+ name = 'TimeoutError';
106
+ duration;
107
+ constructor(duration) {
108
+ super(`Operation timed out after ${duration}ms`);
109
+ this.duration = duration;
110
+ }
111
+ }
112
+ /**
113
+ * Error thrown when an operation is cancelled
114
+ */
115
+ export class CancellationError extends Error {
116
+ name = 'CancellationError';
117
+ reason;
118
+ state;
119
+ constructor(reason, state) {
120
+ super(reason || 'Task was cancelled');
121
+ if (reason !== undefined) {
122
+ this.reason = reason;
123
+ }
124
+ this.state = state || 'running';
125
+ }
126
+ }
2
127
  /**
3
128
  * Internal implementation of InvocationContext
4
129
  */
5
130
  class InvocationContextImpl {
6
131
  actionId;
132
+ traceId;
133
+ depth;
134
+ parent;
7
135
  attachmentsMap = {};
8
- constructor(actionId) {
136
+ childActionIds = [];
137
+ childEvents = [];
138
+ childDuration = 0;
139
+ warningOptions;
140
+ warnedAttachmentSize = false;
141
+ warnedDepth = false;
142
+ // Progress tracking state
143
+ progressTotal = 0;
144
+ progressCompleted = 0;
145
+ progressStartTime = 0;
146
+ lastProgressEmitTime = 0;
147
+ lastProgressPercentage = 0;
148
+ progressRate = 0;
149
+ progressCallback;
150
+ progressThrottle = 100; // ms
151
+ constructor(actionId, progressCallback, progressThrottle, traceId, depth, parent, warningOptions) {
9
152
  this.actionId = actionId;
153
+ this.traceId = traceId;
154
+ this.depth = depth;
155
+ this.parent = parent;
156
+ this.progressCallback = progressCallback;
157
+ if (progressThrottle !== undefined) {
158
+ this.progressThrottle = progressThrottle;
159
+ }
160
+ this.warningOptions = warningOptions;
161
+ this.progressStartTime = Date.now();
162
+ this.checkDepthWarning();
10
163
  }
11
164
  attach(keyOrData, value) {
12
165
  if (typeof keyOrData === 'string') {
@@ -30,6 +183,7 @@ class InvocationContextImpl {
30
183
  // Object - deep merge into root
31
184
  this.deepMerge(this.attachmentsMap, keyOrData);
32
185
  }
186
+ this.checkAttachmentWarning();
33
187
  }
34
188
  deepMerge(target, source) {
35
189
  for (const key in source) {
@@ -53,6 +207,161 @@ class InvocationContextImpl {
53
207
  getAttachments() {
54
208
  return { ...this.attachmentsMap };
55
209
  }
210
+ registerChild(actionId) {
211
+ if (!this.childActionIds.includes(actionId)) {
212
+ this.childActionIds.push(actionId);
213
+ }
214
+ }
215
+ addChildEvent(event) {
216
+ this.childEvents.push(event);
217
+ if (!this.childActionIds.includes(event.actionId)) {
218
+ this.childActionIds.push(event.actionId);
219
+ }
220
+ if (typeof event.duration === 'number') {
221
+ this.childDuration += event.duration;
222
+ }
223
+ }
224
+ getChildActionIds() {
225
+ return [...this.childActionIds];
226
+ }
227
+ getChildEvents() {
228
+ return [...this.childEvents];
229
+ }
230
+ getChildDuration() {
231
+ return this.childDuration;
232
+ }
233
+ checkDepthWarning() {
234
+ if (!this.warningOptions?.maxDepth || this.warnedDepth) {
235
+ return;
236
+ }
237
+ if (this.depth > this.warningOptions.maxDepth) {
238
+ this.warnedDepth = true;
239
+ this.emitWarning({
240
+ type: 'depth',
241
+ message: `Context depth ${this.depth} exceeded warning threshold ${this.warningOptions.maxDepth}`,
242
+ actionId: this.actionId,
243
+ traceId: this.traceId,
244
+ threshold: this.warningOptions.maxDepth,
245
+ depth: this.depth
246
+ });
247
+ }
248
+ }
249
+ checkAttachmentWarning() {
250
+ if (!this.warningOptions?.maxAttachmentBytes || this.warnedAttachmentSize) {
251
+ return;
252
+ }
253
+ try {
254
+ const serialized = JSON.stringify(this.attachmentsMap);
255
+ const size = Buffer.byteLength(serialized, 'utf8');
256
+ if (size > this.warningOptions.maxAttachmentBytes) {
257
+ this.warnedAttachmentSize = true;
258
+ this.emitWarning({
259
+ type: 'attachment-size',
260
+ message: `Attachment size ${size} bytes exceeded warning threshold ${this.warningOptions.maxAttachmentBytes}`,
261
+ actionId: this.actionId,
262
+ traceId: this.traceId,
263
+ currentSize: size,
264
+ threshold: this.warningOptions.maxAttachmentBytes,
265
+ depth: this.depth
266
+ });
267
+ }
268
+ }
269
+ catch (error) {
270
+ // Ignore serialization errors for warnings
271
+ }
272
+ }
273
+ emitWarning(warning) {
274
+ const handler = this.warningOptions?.onWarning ?? console.warn;
275
+ try {
276
+ handler(warning);
277
+ }
278
+ catch (error) {
279
+ console.error('Error in context warning handler:', error);
280
+ }
281
+ }
282
+ setTotal(total) {
283
+ if (total < 0) {
284
+ throw new Error('Progress total must be >= 0');
285
+ }
286
+ this.progressTotal = total;
287
+ // Reset progress when total is set
288
+ this.progressCompleted = 0;
289
+ this.progressStartTime = Date.now();
290
+ this.lastProgressEmitTime = 0;
291
+ this.lastProgressPercentage = 0;
292
+ this.progressRate = 0;
293
+ // Emit initial progress (0%)
294
+ this.emitProgress();
295
+ }
296
+ reportProgress(completed, current) {
297
+ if (completed < 0) {
298
+ throw new Error('Progress completed must be >= 0');
299
+ }
300
+ this.progressCompleted = Math.min(completed, this.progressTotal);
301
+ this.emitProgress(current);
302
+ }
303
+ incrementProgress(current) {
304
+ this.progressCompleted = Math.min(this.progressCompleted + 1, this.progressTotal);
305
+ this.emitProgress(current);
306
+ }
307
+ emitProgress(current) {
308
+ if (!this.progressCallback || this.progressTotal === 0) {
309
+ return;
310
+ }
311
+ const now = Date.now();
312
+ const elapsedTime = now - this.progressStartTime;
313
+ const percentage = this.progressTotal > 0
314
+ ? Math.round((this.progressCompleted / this.progressTotal) * 100)
315
+ : 0;
316
+ // Determine if we should emit
317
+ const isComplete = this.progressCompleted >= this.progressTotal;
318
+ const isStart = this.progressCompleted === 0;
319
+ const timeSinceLastEmit = now - this.lastProgressEmitTime;
320
+ const shouldThrottle = timeSinceLastEmit < this.progressThrottle;
321
+ const significantChange = Math.abs(percentage - this.lastProgressPercentage) >= 5;
322
+ // Always emit on 0% or 100%, or if throttle passed, or significant change
323
+ if (!isStart && !isComplete && shouldThrottle && !significantChange) {
324
+ return;
325
+ }
326
+ // Calculate rate (items per second) with exponential smoothing
327
+ const currentRate = elapsedTime > 0 ? (this.progressCompleted / (elapsedTime / 1000)) : 0;
328
+ if (this.progressRate === 0) {
329
+ this.progressRate = currentRate;
330
+ }
331
+ else {
332
+ this.progressRate = 0.7 * this.progressRate + 0.3 * currentRate;
333
+ }
334
+ // Calculate ETA
335
+ const remaining = this.progressTotal - this.progressCompleted;
336
+ const estimatedTimeRemaining = this.progressRate > 0
337
+ ? Math.round((remaining / this.progressRate) * 1000)
338
+ : undefined;
339
+ const progress = {
340
+ completed: this.progressCompleted,
341
+ total: this.progressTotal,
342
+ percentage,
343
+ ...(current !== undefined ? { current } : {}),
344
+ ...(this.progressRate > 0 ? { rate: Math.round(this.progressRate * 100) / 100 } : {}),
345
+ ...(estimatedTimeRemaining !== undefined ? { estimatedTimeRemaining } : {}),
346
+ startTime: this.progressStartTime,
347
+ elapsedTime
348
+ };
349
+ this.lastProgressEmitTime = now;
350
+ this.lastProgressPercentage = percentage;
351
+ // Fire callback (errors in callback are isolated)
352
+ try {
353
+ this.progressCallback(progress);
354
+ }
355
+ catch (error) {
356
+ console.error('Error in progress callback:', error);
357
+ }
358
+ }
359
+ getProgressState() {
360
+ return {
361
+ completed: this.progressCompleted,
362
+ total: this.progressTotal
363
+ };
364
+ }
56
365
  }
57
366
  export class ActionBuilder {
58
367
  /** The execution scheduler for concurrency and rate limiting */
@@ -65,12 +374,31 @@ export class ActionBuilder {
65
374
  usesContext = false;
66
375
  /** Retry configuration */
67
376
  retryOptions;
377
+ /** Timeout configuration */
378
+ timeoutConfig;
379
+ /** Whether this action uses abort signal (set by withAbortSignal wrapper) */
380
+ usesAbortSignal = false;
381
+ /** Progress callback for all invocations */
382
+ progressCallback;
383
+ /** Progress throttle in milliseconds */
384
+ progressThrottle = 100;
385
+ /** Track all active invocations for cancelAll support */
386
+ activeInvocations = new Map();
387
+ /** Default priority for all invocations (0-100) */
388
+ defaultPriority = PRIORITY_VALUES.normal;
389
+ /** Context warning thresholds for this action */
390
+ contextWarningOptions;
68
391
  constructor(handler) {
69
392
  // Check if handler was wrapped with withContext
70
393
  if (handler.__usesContext && handler.__originalHandler) {
71
394
  this.usesContext = true;
72
395
  this.callbackHandler = handler.__originalHandler;
73
396
  }
397
+ // Check if handler was wrapped with withAbortSignal
398
+ else if (handler.__usesAbortSignal && handler.__originalHandler) {
399
+ this.usesAbortSignal = true;
400
+ this.callbackHandler = handler.__originalHandler;
401
+ }
74
402
  else {
75
403
  this.callbackHandler = handler;
76
404
  }
@@ -92,6 +420,14 @@ export class ActionBuilder {
92
420
  this.scheduler.setRateLimit(rateLimit);
93
421
  return this;
94
422
  }
423
+ /**
424
+ * Set default priority for all invocations of this action.
425
+ * Higher priority executes first; FIFO ordering preserved within same priority.
426
+ */
427
+ setPriority(priority) {
428
+ this.defaultPriority = normalizePriority(priority);
429
+ return this;
430
+ }
95
431
  /**
96
432
  * Configure retry behavior for failed executions
97
433
  * @param options Retry configuration
@@ -110,6 +446,22 @@ export class ActionBuilder {
110
446
  this.retryOptions = options;
111
447
  return this;
112
448
  }
449
+ /**
450
+ * Configure timeout for executions
451
+ * @param options Timeout duration in ms or configuration object
452
+ */
453
+ setTimeout(options) {
454
+ // Normalize to TimeoutOptions
455
+ const config = typeof options === 'number'
456
+ ? { duration: options }
457
+ : options;
458
+ // Validate configuration
459
+ if (config.duration <= 0) {
460
+ throw new Error('Timeout duration must be positive');
461
+ }
462
+ this.timeoutConfig = config;
463
+ return this;
464
+ }
113
465
  /**
114
466
  * Register a callback to receive wide events after each invocation
115
467
  * @param callback Function to receive wide events
@@ -118,6 +470,28 @@ export class ActionBuilder {
118
470
  this.eventCallback = callback;
119
471
  return this;
120
472
  }
473
+ /**
474
+ * Register a callback to receive progress updates
475
+ * @param callback Function to receive progress updates
476
+ * @param options Progress options (throttle)
477
+ */
478
+ onProgress(callback, options) {
479
+ this.progressCallback = callback;
480
+ if (options?.throttle !== undefined) {
481
+ if (options.throttle < 0) {
482
+ throw new Error('Progress throttle must be >= 0');
483
+ }
484
+ this.progressThrottle = options.throttle;
485
+ }
486
+ return this;
487
+ }
488
+ /**
489
+ * Configure context warning thresholds for this action
490
+ */
491
+ setContextWarningThreshold(options) {
492
+ this.contextWarningOptions = options;
493
+ return this;
494
+ }
121
495
  /**
122
496
  * Mark this action as using context (internal - called by withContext)
123
497
  */
@@ -149,20 +523,157 @@ export class ActionBuilder {
149
523
  /**
150
524
  * Execute handler with retry logic
151
525
  */
152
- async executeWithRetry(context, payload, actionId, startedAt, emitIntermediateEvents = false) {
526
+ async executeWithRetry(context, payload, actionId, startedAt, priority, metadata, emitIntermediateEvents = false, signal) {
153
527
  let result;
154
528
  let error;
155
529
  const retryDelays = [];
156
530
  let attemptNumber = 0;
157
531
  const maxAttempts = (this.retryOptions?.maxRetries ?? 0) + 1;
532
+ let timedOut = false;
533
+ let executionTime;
158
534
  while (attemptNumber < maxAttempts) {
535
+ // Check for cancellation before each attempt
536
+ if (signal?.aborted) {
537
+ throw new CancellationError(signal.reason || 'Task was cancelled', attemptNumber === 0 ? 'queued' : 'running');
538
+ }
159
539
  const isRetry = attemptNumber > 0;
540
+ const attemptStartTime = Date.now();
160
541
  try {
161
- if (this.usesContext) {
162
- result = await this.callbackHandler(context, ...payload);
542
+ // Execute with timeout if configured
543
+ if (this.timeoutConfig) {
544
+ const timeoutDuration = this.timeoutConfig.duration;
545
+ const throwOnTimeout = this.timeoutConfig.throwOnTimeout !== false;
546
+ const useAbortSignal = this.timeoutConfig.abortSignal === true;
547
+ if (useAbortSignal && this.usesAbortSignal) {
548
+ // Cooperative cancellation with AbortSignal
549
+ // Create a combined abort controller for timeout + external cancellation
550
+ const timeoutController = new AbortController();
551
+ // Link external cancellation signal to timeout controller
552
+ if (signal) {
553
+ if (signal.aborted) {
554
+ throw new CancellationError(signal.reason || 'Task was cancelled', 'running');
555
+ }
556
+ signal.addEventListener('abort', () => {
557
+ timeoutController.abort(signal.reason);
558
+ }, { once: true });
559
+ }
560
+ const timeoutId = setTimeout(() => {
561
+ timeoutController.abort(new TimeoutError(timeoutDuration));
562
+ }, timeoutDuration);
563
+ try {
564
+ result = await this.callbackHandler(timeoutController.signal, ...payload);
565
+ clearTimeout(timeoutId);
566
+ }
567
+ catch (e) {
568
+ clearTimeout(timeoutId);
569
+ // Check if it was cancelled vs timeout
570
+ if (signal?.aborted) {
571
+ throw new CancellationError(signal.reason || 'Task was cancelled', 'running');
572
+ }
573
+ if (timeoutController.signal.aborted || e instanceof TimeoutError) {
574
+ executionTime = Date.now() - attemptStartTime;
575
+ timedOut = true;
576
+ if (throwOnTimeout) {
577
+ throw new TimeoutError(timeoutDuration);
578
+ }
579
+ }
580
+ else {
581
+ throw e;
582
+ }
583
+ }
584
+ }
585
+ else {
586
+ // Forced cancellation with Promise.race (timeout + cancellation + handler)
587
+ const timeoutPromise = new Promise((_, reject) => {
588
+ setTimeout(() => {
589
+ reject(new TimeoutError(timeoutDuration));
590
+ }, timeoutDuration);
591
+ });
592
+ const cancellationPromise = signal ? new Promise((_, reject) => {
593
+ if (signal.aborted) {
594
+ reject(new CancellationError(signal.reason || 'Task was cancelled', 'running'));
595
+ return;
596
+ }
597
+ signal.addEventListener('abort', () => {
598
+ reject(new CancellationError(signal.reason || 'Task was cancelled', 'running'));
599
+ }, { once: true });
600
+ }) : new Promise(() => { }); // Never resolves if no signal
601
+ let handlerPromise;
602
+ if (this.usesContext) {
603
+ handlerPromise = Promise.resolve(this.callbackHandler(context, ...payload));
604
+ }
605
+ else {
606
+ handlerPromise = Promise.resolve(this.callbackHandler(...payload));
607
+ }
608
+ try {
609
+ result = await Promise.race([handlerPromise, timeoutPromise, cancellationPromise]);
610
+ }
611
+ catch (e) {
612
+ if (e instanceof CancellationError) {
613
+ throw e;
614
+ }
615
+ else if (e instanceof TimeoutError) {
616
+ executionTime = Date.now() - attemptStartTime;
617
+ timedOut = true;
618
+ if (throwOnTimeout) {
619
+ throw e;
620
+ }
621
+ }
622
+ else {
623
+ throw e;
624
+ }
625
+ }
626
+ }
163
627
  }
164
628
  else {
165
- result = await this.callbackHandler(...payload);
629
+ // No timeout configured, execute normally
630
+ // Check for external cancellation
631
+ if (signal) {
632
+ const cancellationPromise = new Promise((_, reject) => {
633
+ if (signal.aborted) {
634
+ reject(new CancellationError(signal.reason || 'Task was cancelled', 'running'));
635
+ return;
636
+ }
637
+ signal.addEventListener('abort', () => {
638
+ reject(new CancellationError(signal.reason || 'Task was cancelled', 'running'));
639
+ }, { once: true });
640
+ });
641
+ let handlerPromise;
642
+ if (this.usesAbortSignal) {
643
+ handlerPromise = Promise.resolve(this.callbackHandler(signal, ...payload));
644
+ }
645
+ else if (this.usesContext) {
646
+ handlerPromise = Promise.resolve(this.callbackHandler(context, ...payload));
647
+ }
648
+ else {
649
+ handlerPromise = Promise.resolve(this.callbackHandler(...payload));
650
+ }
651
+ try {
652
+ result = await Promise.race([handlerPromise, cancellationPromise]);
653
+ }
654
+ catch (e) {
655
+ if (e instanceof CancellationError) {
656
+ throw e;
657
+ }
658
+ else {
659
+ throw e;
660
+ }
661
+ }
662
+ }
663
+ else {
664
+ // No signal, execute directly
665
+ if (this.usesAbortSignal) {
666
+ // Create a dummy signal that never aborts
667
+ const dummyController = new AbortController();
668
+ result = await this.callbackHandler(dummyController.signal, ...payload);
669
+ }
670
+ else if (this.usesContext) {
671
+ result = await this.callbackHandler(context, ...payload);
672
+ }
673
+ else {
674
+ result = await this.callbackHandler(...payload);
675
+ }
676
+ }
166
677
  }
167
678
  // Success!
168
679
  error = undefined;
@@ -196,12 +707,26 @@ export class ActionBuilder {
196
707
  completedAt,
197
708
  duration: completedAt - startedAt,
198
709
  input: payload,
710
+ priority,
711
+ ...(metadata !== undefined ? { metadata } : {}),
199
712
  error,
200
713
  attachments: context.getAttachments(),
714
+ traceId: context.traceId,
715
+ ...(context.parent ? { parentActionId: context.parent.actionId } : {}),
716
+ depth: context.depth,
717
+ childActionIds: context.getChildActionIds(),
718
+ children: context.getChildEvents(),
719
+ childDuration: context.getChildDuration(),
720
+ selfDuration: Math.max(0, (completedAt - startedAt) - context.getChildDuration()),
201
721
  retryAttempt: attemptNumber,
202
722
  isRetry,
203
723
  willRetry: shouldRetry,
204
- retryDelays: [...retryDelays]
724
+ retryDelays: [...retryDelays],
725
+ ...(this.timeoutConfig ? {
726
+ timeout: this.timeoutConfig.duration,
727
+ timedOut,
728
+ ...(executionTime !== undefined ? { executionTime } : {})
729
+ } : {})
205
730
  };
206
731
  try {
207
732
  await this.eventCallback(intermediateEvent);
@@ -211,6 +736,12 @@ export class ActionBuilder {
211
736
  }
212
737
  }
213
738
  if (!shouldRetry) {
739
+ error.__executionDetails = {
740
+ retryAttempt: attemptNumber,
741
+ retryDelays: [...retryDelays],
742
+ timedOut,
743
+ executionTime
744
+ };
214
745
  throw error;
215
746
  }
216
747
  // Calculate and apply retry delay
@@ -218,49 +749,108 @@ export class ActionBuilder {
218
749
  if (attemptNumber < maxAttempts) {
219
750
  const delay = this.calculateRetryDelay(attemptNumber, this.retryOptions);
220
751
  retryDelays.push(delay);
221
- await new Promise(resolve => setTimeout(resolve, delay));
752
+ // Wait for delay with cancellation support
753
+ await new Promise((resolve, reject) => {
754
+ const timeoutId = setTimeout(resolve, delay);
755
+ // Listen for cancellation during retry delay
756
+ if (signal) {
757
+ const abortHandler = () => {
758
+ clearTimeout(timeoutId);
759
+ reject(new CancellationError(signal.reason || 'Task was cancelled', 'retry-delay'));
760
+ };
761
+ if (signal.aborted) {
762
+ clearTimeout(timeoutId);
763
+ reject(new CancellationError(signal.reason || 'Task was cancelled', 'retry-delay'));
764
+ return;
765
+ }
766
+ signal.addEventListener('abort', abortHandler, { once: true });
767
+ }
768
+ });
222
769
  }
223
770
  }
224
771
  }
225
772
  if (!error) {
226
- return { result: result, retryAttempt: attemptNumber, retryDelays };
773
+ return { result: result, retryAttempt: attemptNumber, retryDelays, timedOut, executionTime };
227
774
  }
228
775
  throw error;
229
776
  }
230
- /**
231
- * Invoke the action with the given payload
232
- * Returns immediately with actionId and a promise for the result
233
- */
234
- invoke(...payload) {
777
+ invoke(...payloadAndMaybeOptions) {
778
+ const lastArg = payloadAndMaybeOptions[payloadAndMaybeOptions.length - 1];
779
+ const options = isInvokeOptions(lastArg) ? lastArg : undefined;
780
+ const payload = (options
781
+ ? payloadAndMaybeOptions.slice(0, -1)
782
+ : payloadAndMaybeOptions);
783
+ const invocationMetadata = options?.metadata;
784
+ const priority = normalizePriority(options?.priority ?? this.defaultPriority);
785
+ const parentPropagationContext = getPropagationContext();
786
+ const traceId = parentPropagationContext?.traceId ?? crypto.randomUUID();
787
+ const depth = parentPropagationContext ? parentPropagationContext.depth + 1 : 0;
788
+ const parentContext = parentPropagationContext ? buildParentContextSnapshot(parentPropagationContext) : undefined;
789
+ const warningOptions = resolveContextWarningOptions(this.contextWarningOptions);
235
790
  const actionId = crypto.randomUUID();
236
791
  const startedAt = Date.now();
237
- const context = new InvocationContextImpl(actionId);
792
+ const context = new InvocationContextImpl(actionId, this.progressCallback, this.progressThrottle, traceId, depth, parentContext, warningOptions);
793
+ if (parentPropagationContext) {
794
+ parentPropagationContext.invocationContext.registerChild(actionId);
795
+ }
796
+ const propagationContext = {
797
+ traceId,
798
+ actionId,
799
+ depth,
800
+ parent: parentPropagationContext,
801
+ invocationContext: context,
802
+ parentContext: undefined
803
+ };
238
804
  let eventLoggedResolve;
239
805
  let eventLoggedReject;
240
806
  const eventLogged = new Promise((resolve, reject) => {
241
807
  eventLoggedResolve = resolve;
242
808
  eventLoggedReject = reject;
243
809
  });
244
- const data = this.scheduler.schedule(async () => {
245
- return await this.executeWithRetry(context, payload, actionId, startedAt, true);
810
+ let isCancelled = false;
811
+ let cancellationReason;
812
+ let cancellationState;
813
+ const { promise: data, controller, task } = this.scheduler.schedule(actionId, async (signal) => {
814
+ return await runWithPropagationContext(propagationContext, () => this.executeWithRetry(context, payload, actionId, startedAt, priority, invocationMetadata, true, signal));
815
+ }, { priority });
816
+ // Add catch handler immediately to prevent unhandled rejections
817
+ // This will be overridden by the explicit handlers below
818
+ data.catch(() => {
819
+ // Intentionally empty - errors handled below
246
820
  });
247
821
  // Attach handlers to emit the final wide event
248
822
  data.then(async (execResult) => {
249
823
  // Success path
250
824
  const completedAt = Date.now();
825
+ const childDuration = context.getChildDuration();
251
826
  const wideEvent = {
252
827
  actionId,
253
828
  startedAt,
254
829
  completedAt,
255
830
  duration: completedAt - startedAt,
256
831
  input: payload,
832
+ priority,
833
+ ...(invocationMetadata !== undefined ? { metadata: invocationMetadata } : {}),
257
834
  output: execResult.result,
258
835
  attachments: context.getAttachments(),
836
+ traceId: context.traceId,
837
+ ...(context.parent ? { parentActionId: context.parent.actionId } : {}),
838
+ depth: context.depth,
839
+ childActionIds: context.getChildActionIds(),
840
+ children: context.getChildEvents(),
841
+ childDuration,
842
+ selfDuration: Math.max(0, (completedAt - startedAt) - childDuration),
259
843
  retryAttempt: execResult.retryAttempt,
260
844
  isRetry: execResult.retryAttempt > 0,
261
845
  totalAttempts: execResult.retryAttempt + 1,
262
- retryDelays: execResult.retryDelays
846
+ retryDelays: execResult.retryDelays,
847
+ ...(this.timeoutConfig ? {
848
+ timeout: this.timeoutConfig.duration,
849
+ timedOut: execResult.timedOut,
850
+ ...(execResult.executionTime !== undefined ? { executionTime: execResult.executionTime } : {})
851
+ } : {})
263
852
  };
853
+ parentPropagationContext?.invocationContext.addChildEvent(wideEvent);
264
854
  // Fire event callback (if registered)
265
855
  if (this.eventCallback) {
266
856
  try {
@@ -276,44 +866,193 @@ export class ActionBuilder {
276
866
  eventLoggedResolve();
277
867
  }
278
868
  }, async (error) => {
279
- // Error path - don't emit another event since the last intermediate event
280
- // already covered the final failure
869
+ // Error path - emit cancellation event if cancelled
870
+ const completedAt = Date.now();
871
+ const childDuration = context.getChildDuration();
872
+ const executionDetails = error.__executionDetails;
873
+ const wideEvent = {
874
+ actionId,
875
+ startedAt,
876
+ completedAt,
877
+ duration: completedAt - startedAt,
878
+ input: payload,
879
+ priority,
880
+ ...(invocationMetadata !== undefined ? { metadata: invocationMetadata } : {}),
881
+ error,
882
+ attachments: context.getAttachments(),
883
+ traceId: context.traceId,
884
+ ...(context.parent ? { parentActionId: context.parent.actionId } : {}),
885
+ depth: context.depth,
886
+ childActionIds: context.getChildActionIds(),
887
+ children: context.getChildEvents(),
888
+ childDuration,
889
+ selfDuration: Math.max(0, (completedAt - startedAt) - childDuration),
890
+ ...(executionDetails?.retryAttempt !== undefined ? {
891
+ retryAttempt: executionDetails.retryAttempt,
892
+ isRetry: executionDetails.retryAttempt > 0,
893
+ retryDelays: executionDetails.retryDelays
894
+ } : {}),
895
+ ...(this.timeoutConfig ? {
896
+ timeout: this.timeoutConfig.duration,
897
+ ...(executionDetails?.timedOut !== undefined ? { timedOut: executionDetails.timedOut } : {}),
898
+ ...(executionDetails?.executionTime !== undefined ? { executionTime: executionDetails.executionTime } : {})
899
+ } : {}),
900
+ ...(error instanceof CancellationError ? {
901
+ cancelled: true,
902
+ ...(error.reason !== undefined ? { cancelReason: error.reason } : {}),
903
+ cancelledAt: error.state
904
+ } : {})
905
+ };
906
+ parentPropagationContext?.invocationContext.addChildEvent(wideEvent);
907
+ if (error instanceof CancellationError) {
908
+ if (this.eventCallback) {
909
+ try {
910
+ await this.eventCallback(wideEvent);
911
+ }
912
+ catch (callbackError) {
913
+ console.error('Error in event callback:', callbackError);
914
+ }
915
+ }
916
+ }
281
917
  eventLoggedResolve();
282
918
  });
283
- return {
919
+ // Create cancel function
920
+ const cancel = (reason) => {
921
+ if (isCancelled) {
922
+ return; // Already cancelled
923
+ }
924
+ // Try to cancel via scheduler first
925
+ const wasCancelled = this.scheduler.cancel(actionId, reason);
926
+ if (!wasCancelled) {
927
+ // Task already completed or not found, no-op
928
+ return;
929
+ }
930
+ // Only mark as cancelled if scheduler actually cancelled it
931
+ isCancelled = true;
932
+ cancellationReason = reason;
933
+ };
934
+ // Create the data promise that extracts just the result
935
+ const dataPromise = data.then(r => r.result);
936
+ // Add catch handler to prevent unhandled rejection - caller will handle errors
937
+ dataPromise.catch(() => { });
938
+ const handle = {
284
939
  actionId,
285
- data: data.then(r => r.result),
286
- eventLogged
940
+ data: dataPromise,
941
+ eventLogged,
942
+ cancel,
943
+ get cancelled() {
944
+ return isCancelled || task.cancelled;
945
+ },
946
+ get cancelReason() {
947
+ return cancellationReason || task.cancelReason;
948
+ }
287
949
  };
950
+ // Track invocation
951
+ this.activeInvocations.set(actionId, handle);
952
+ // Remove from tracking when complete
953
+ data.finally(() => {
954
+ this.activeInvocations.delete(actionId);
955
+ });
956
+ return handle;
288
957
  }
289
- /**
290
- * Batch invoke - Promise.all style
291
- * Waits for all invocations to complete and returns results in input order
292
- * Individual failures don't fail the whole batch
293
- */
294
- async invokeAll(payloads) {
958
+ async invokeAll(payloads, options) {
295
959
  if (payloads.length === 0) {
296
960
  return [];
297
961
  }
962
+ const invocationMetadata = options?.metadata;
963
+ const priority = normalizePriority(options?.priority ?? this.defaultPriority);
964
+ const parentPropagationContext = getPropagationContext();
965
+ const traceId = parentPropagationContext?.traceId ?? crypto.randomUUID();
966
+ const depth = parentPropagationContext ? parentPropagationContext.depth + 1 : 0;
967
+ const parentContext = parentPropagationContext ? buildParentContextSnapshot(parentPropagationContext) : undefined;
968
+ const warningOptions = resolveContextWarningOptions(this.contextWarningOptions);
969
+ const batchId = crypto.randomUUID();
970
+ // Create a batch progress tracker if progress callback exists
971
+ let batchCompletedCount = 0;
972
+ const batchStartTime = Date.now();
973
+ let lastBatchProgressEmitTime = 0;
974
+ let lastBatchProgressPercentage = 0;
975
+ let batchProgressRate = 0;
976
+ const emitBatchProgress = () => {
977
+ if (!this.progressCallback) {
978
+ return;
979
+ }
980
+ const now = Date.now();
981
+ const elapsedTime = now - batchStartTime;
982
+ const percentage = Math.round((batchCompletedCount / payloads.length) * 100);
983
+ // Throttle logic
984
+ const isComplete = batchCompletedCount >= payloads.length;
985
+ const isStart = batchCompletedCount === 0;
986
+ const timeSinceLastEmit = now - lastBatchProgressEmitTime;
987
+ const shouldThrottle = timeSinceLastEmit < this.progressThrottle;
988
+ const significantChange = Math.abs(percentage - lastBatchProgressPercentage) >= 5;
989
+ if (!isStart && !isComplete && shouldThrottle && !significantChange) {
990
+ return;
991
+ }
992
+ // Calculate rate with exponential smoothing
993
+ const currentRate = elapsedTime > 0 ? (batchCompletedCount / (elapsedTime / 1000)) : 0;
994
+ if (batchProgressRate === 0) {
995
+ batchProgressRate = currentRate;
996
+ }
997
+ else {
998
+ batchProgressRate = 0.7 * batchProgressRate + 0.3 * currentRate;
999
+ }
1000
+ const remaining = payloads.length - batchCompletedCount;
1001
+ const estimatedTimeRemaining = batchProgressRate > 0
1002
+ ? Math.round((remaining / batchProgressRate) * 1000)
1003
+ : undefined;
1004
+ const progress = {
1005
+ completed: batchCompletedCount,
1006
+ total: payloads.length,
1007
+ percentage,
1008
+ ...(batchProgressRate > 0 ? { rate: Math.round(batchProgressRate * 100) / 100 } : {}),
1009
+ ...(estimatedTimeRemaining !== undefined ? { estimatedTimeRemaining } : {}),
1010
+ startTime: batchStartTime,
1011
+ elapsedTime
1012
+ };
1013
+ lastBatchProgressEmitTime = now;
1014
+ lastBatchProgressPercentage = percentage;
1015
+ try {
1016
+ this.progressCallback(progress);
1017
+ }
1018
+ catch (error) {
1019
+ console.error('Error in progress callback:', error);
1020
+ }
1021
+ };
1022
+ // Emit initial progress (0%)
1023
+ if (this.progressCallback) {
1024
+ emitBatchProgress();
1025
+ }
298
1026
  const tasks = payloads.map((payload, index) => {
299
1027
  const actionId = crypto.randomUUID();
300
1028
  const startedAt = Date.now();
301
- const context = new InvocationContextImpl(actionId);
302
- return {
1029
+ const context = new InvocationContextImpl(actionId, undefined, undefined, traceId, depth, parentContext, warningOptions);
1030
+ if (parentPropagationContext) {
1031
+ parentPropagationContext.invocationContext.registerChild(actionId);
1032
+ }
1033
+ const propagationContext = {
1034
+ traceId,
303
1035
  actionId,
304
- index,
305
- startedAt,
306
- context,
307
- promise: this.scheduler.schedule(async () => {
1036
+ depth,
1037
+ parent: parentPropagationContext,
1038
+ invocationContext: context,
1039
+ parentContext: undefined
1040
+ };
1041
+ const { promise, controller } = this.scheduler.schedule(actionId, async (signal) => {
1042
+ return await runWithPropagationContext(propagationContext, async () => {
308
1043
  let result;
309
1044
  let error;
310
1045
  let retryAttempt = 0;
311
1046
  let retryDelays = [];
1047
+ let timedOut = false;
1048
+ let executionTime;
312
1049
  try {
313
- const execResult = await this.executeWithRetry(context, payload, actionId, startedAt, true);
1050
+ const execResult = await this.executeWithRetry(context, payload, actionId, startedAt, priority, invocationMetadata, true, signal);
314
1051
  result = execResult.result;
315
1052
  retryAttempt = execResult.retryAttempt;
316
1053
  retryDelays = execResult.retryDelays;
1054
+ timedOut = execResult.timedOut;
1055
+ executionTime = execResult.executionTime;
317
1056
  return result;
318
1057
  }
319
1058
  catch (e) {
@@ -321,24 +1060,49 @@ export class ActionBuilder {
321
1060
  throw e;
322
1061
  }
323
1062
  finally {
1063
+ // Update batch progress
1064
+ batchCompletedCount++;
1065
+ emitBatchProgress();
324
1066
  // Emit final wide event
325
1067
  const completedAt = Date.now();
1068
+ const childDuration = context.getChildDuration();
326
1069
  const wideEvent = {
327
1070
  actionId,
328
1071
  startedAt,
329
1072
  completedAt,
330
1073
  duration: completedAt - startedAt,
331
1074
  input: payload,
1075
+ priority,
1076
+ ...(invocationMetadata !== undefined ? { metadata: invocationMetadata } : {}),
332
1077
  output: result,
333
1078
  error,
334
1079
  attachments: context.getAttachments(),
1080
+ traceId: context.traceId,
1081
+ ...(context.parent ? { parentActionId: context.parent.actionId } : {}),
1082
+ depth: context.depth,
1083
+ childActionIds: context.getChildActionIds(),
1084
+ children: context.getChildEvents(),
1085
+ childDuration,
1086
+ selfDuration: Math.max(0, (completedAt - startedAt) - childDuration),
1087
+ batchId,
335
1088
  ...(retryDelays.length > 0 ? {
336
1089
  retryAttempt,
337
1090
  isRetry: retryAttempt > 0,
338
1091
  totalAttempts: retryAttempt + 1,
339
1092
  retryDelays
1093
+ } : {}),
1094
+ ...(this.timeoutConfig ? {
1095
+ timeout: this.timeoutConfig.duration,
1096
+ timedOut,
1097
+ ...(executionTime !== undefined ? { executionTime } : {})
1098
+ } : {}),
1099
+ ...(error instanceof CancellationError ? {
1100
+ cancelled: true,
1101
+ cancelReason: error.reason,
1102
+ cancelledAt: error.state
340
1103
  } : {})
341
1104
  };
1105
+ parentPropagationContext?.invocationContext.addChildEvent(wideEvent);
342
1106
  if (this.eventCallback) {
343
1107
  try {
344
1108
  await this.eventCallback(wideEvent);
@@ -348,7 +1112,15 @@ export class ActionBuilder {
348
1112
  }
349
1113
  }
350
1114
  }
351
- })
1115
+ });
1116
+ }, { priority });
1117
+ return {
1118
+ actionId,
1119
+ index,
1120
+ startedAt,
1121
+ context,
1122
+ promise,
1123
+ controller
352
1124
  };
353
1125
  });
354
1126
  const settledResults = await Promise.allSettled(tasks.map(t => t.promise));
@@ -372,67 +1144,169 @@ export class ActionBuilder {
372
1144
  }
373
1145
  });
374
1146
  }
375
- /**
376
- * Batch invoke - Async iterator style
377
- * Yields results as they complete (not in input order)
378
- * Ideal for processing results as soon as they're available
379
- */
380
- async *invokeStream(payloads) {
1147
+ async *invokeStream(payloads, options) {
381
1148
  if (payloads.length === 0) {
382
1149
  return;
383
1150
  }
1151
+ const invocationMetadata = options?.metadata;
1152
+ const priority = normalizePriority(options?.priority ?? this.defaultPriority);
1153
+ const parentPropagationContext = getPropagationContext();
1154
+ const traceId = parentPropagationContext?.traceId ?? crypto.randomUUID();
1155
+ const depth = parentPropagationContext ? parentPropagationContext.depth + 1 : 0;
1156
+ const parentContext = parentPropagationContext ? buildParentContextSnapshot(parentPropagationContext) : undefined;
1157
+ const warningOptions = resolveContextWarningOptions(this.contextWarningOptions);
1158
+ const batchId = crypto.randomUUID();
1159
+ // Create a batch progress tracker if progress callback exists
1160
+ let batchCompletedCount = 0;
1161
+ const batchStartTime = Date.now();
1162
+ let lastBatchProgressEmitTime = 0;
1163
+ let lastBatchProgressPercentage = 0;
1164
+ let batchProgressRate = 0;
1165
+ const emitBatchProgress = () => {
1166
+ if (!this.progressCallback) {
1167
+ return;
1168
+ }
1169
+ const now = Date.now();
1170
+ const elapsedTime = now - batchStartTime;
1171
+ const percentage = Math.round((batchCompletedCount / payloads.length) * 100);
1172
+ // Throttle logic
1173
+ const isComplete = batchCompletedCount >= payloads.length;
1174
+ const isStart = batchCompletedCount === 0;
1175
+ const timeSinceLastEmit = now - lastBatchProgressEmitTime;
1176
+ const shouldThrottle = timeSinceLastEmit < this.progressThrottle;
1177
+ const significantChange = Math.abs(percentage - lastBatchProgressPercentage) >= 5;
1178
+ if (!isStart && !isComplete && shouldThrottle && !significantChange) {
1179
+ return;
1180
+ }
1181
+ // Calculate rate with exponential smoothing
1182
+ const currentRate = elapsedTime > 0 ? (batchCompletedCount / (elapsedTime / 1000)) : 0;
1183
+ if (batchProgressRate === 0) {
1184
+ batchProgressRate = currentRate;
1185
+ }
1186
+ else {
1187
+ batchProgressRate = 0.7 * batchProgressRate + 0.3 * currentRate;
1188
+ }
1189
+ const remaining = payloads.length - batchCompletedCount;
1190
+ const estimatedTimeRemaining = batchProgressRate > 0
1191
+ ? Math.round((remaining / batchProgressRate) * 1000)
1192
+ : undefined;
1193
+ const progress = {
1194
+ completed: batchCompletedCount,
1195
+ total: payloads.length,
1196
+ percentage,
1197
+ ...(batchProgressRate > 0 ? { rate: Math.round(batchProgressRate * 100) / 100 } : {}),
1198
+ ...(estimatedTimeRemaining !== undefined ? { estimatedTimeRemaining } : {}),
1199
+ startTime: batchStartTime,
1200
+ elapsedTime
1201
+ };
1202
+ lastBatchProgressEmitTime = now;
1203
+ lastBatchProgressPercentage = percentage;
1204
+ try {
1205
+ this.progressCallback(progress);
1206
+ }
1207
+ catch (error) {
1208
+ console.error('Error in progress callback:', error);
1209
+ }
1210
+ };
1211
+ // Emit initial progress (0%)
1212
+ if (this.progressCallback) {
1213
+ emitBatchProgress();
1214
+ }
384
1215
  // Create all tasks with tracking info
385
1216
  const pendingTasks = new Map();
386
1217
  for (let index = 0; index < payloads.length; index++) {
387
1218
  const payload = payloads[index];
388
1219
  const actionId = crypto.randomUUID();
389
1220
  const startedAt = Date.now();
390
- const context = new InvocationContextImpl(actionId);
391
- const taskPromise = this.scheduler.schedule(async () => {
392
- let result;
393
- let error;
394
- let retryAttempt = 0;
395
- let retryDelays = [];
396
- try {
397
- const execResult = await this.executeWithRetry(context, payload, actionId, startedAt, true);
398
- result = execResult.result;
399
- retryAttempt = execResult.retryAttempt;
400
- retryDelays = execResult.retryDelays;
401
- return result;
402
- }
403
- catch (e) {
404
- error = e;
405
- throw e;
406
- }
407
- finally {
408
- // Emit final wide event
409
- const completedAt = Date.now();
410
- const wideEvent = {
411
- actionId,
412
- startedAt,
413
- completedAt,
414
- duration: completedAt - startedAt,
415
- input: payload,
416
- output: result,
417
- error,
418
- attachments: context.getAttachments(),
419
- ...(retryDelays.length > 0 ? {
420
- retryAttempt,
421
- isRetry: retryAttempt > 0,
422
- totalAttempts: retryAttempt + 1,
423
- retryDelays
424
- } : {})
425
- };
426
- if (this.eventCallback) {
427
- try {
428
- await this.eventCallback(wideEvent);
429
- }
430
- catch (callbackError) {
431
- console.error('Error in event callback:', callbackError);
1221
+ const context = new InvocationContextImpl(actionId, undefined, undefined, traceId, depth, parentContext, warningOptions);
1222
+ if (parentPropagationContext) {
1223
+ parentPropagationContext.invocationContext.registerChild(actionId);
1224
+ }
1225
+ const propagationContext = {
1226
+ traceId,
1227
+ actionId,
1228
+ depth,
1229
+ parent: parentPropagationContext,
1230
+ invocationContext: context,
1231
+ parentContext: undefined
1232
+ };
1233
+ const { promise } = this.scheduler.schedule(actionId, async (signal) => {
1234
+ return await runWithPropagationContext(propagationContext, async () => {
1235
+ let result;
1236
+ let error;
1237
+ let retryAttempt = 0;
1238
+ let retryDelays = [];
1239
+ let timedOut = false;
1240
+ let executionTime;
1241
+ try {
1242
+ const execResult = await this.executeWithRetry(context, payload, actionId, startedAt, priority, invocationMetadata, true, signal);
1243
+ result = execResult.result;
1244
+ retryAttempt = execResult.retryAttempt;
1245
+ retryDelays = execResult.retryDelays;
1246
+ timedOut = execResult.timedOut;
1247
+ executionTime = execResult.executionTime;
1248
+ return result;
1249
+ }
1250
+ catch (e) {
1251
+ error = e;
1252
+ throw e;
1253
+ }
1254
+ finally {
1255
+ // Update batch progress
1256
+ batchCompletedCount++;
1257
+ emitBatchProgress();
1258
+ // Emit final wide event
1259
+ const completedAt = Date.now();
1260
+ const childDuration = context.getChildDuration();
1261
+ const wideEvent = {
1262
+ actionId,
1263
+ startedAt,
1264
+ completedAt,
1265
+ duration: completedAt - startedAt,
1266
+ input: payload,
1267
+ priority,
1268
+ ...(invocationMetadata !== undefined ? { metadata: invocationMetadata } : {}),
1269
+ output: result,
1270
+ error,
1271
+ attachments: context.getAttachments(),
1272
+ traceId: context.traceId,
1273
+ ...(context.parent ? { parentActionId: context.parent.actionId } : {}),
1274
+ depth: context.depth,
1275
+ childActionIds: context.getChildActionIds(),
1276
+ children: context.getChildEvents(),
1277
+ childDuration,
1278
+ selfDuration: Math.max(0, (completedAt - startedAt) - childDuration),
1279
+ batchId,
1280
+ ...(retryDelays.length > 0 ? {
1281
+ retryAttempt,
1282
+ isRetry: retryAttempt > 0,
1283
+ totalAttempts: retryAttempt + 1,
1284
+ retryDelays
1285
+ } : {}),
1286
+ ...(this.timeoutConfig ? {
1287
+ timeout: this.timeoutConfig.duration,
1288
+ timedOut,
1289
+ ...(executionTime !== undefined ? { executionTime } : {})
1290
+ } : {}),
1291
+ ...(error instanceof CancellationError ? {
1292
+ cancelled: true,
1293
+ cancelReason: error.reason,
1294
+ cancelledAt: error.state
1295
+ } : {})
1296
+ };
1297
+ parentPropagationContext?.invocationContext.addChildEvent(wideEvent);
1298
+ if (this.eventCallback) {
1299
+ try {
1300
+ await this.eventCallback(wideEvent);
1301
+ }
1302
+ catch (callbackError) {
1303
+ console.error('Error in event callback:', callbackError);
1304
+ }
432
1305
  }
433
1306
  }
434
- }
435
- }).then((data) => ({ actionId, index, data, error: undefined }), (error) => ({ actionId, index, data: undefined, error }));
1307
+ });
1308
+ }, { priority });
1309
+ const taskPromise = promise.then((data) => ({ actionId, index, data, error: undefined }), (error) => ({ actionId, index, data: undefined, error }));
436
1310
  pendingTasks.set(actionId, taskPromise);
437
1311
  }
438
1312
  // Yield results as they complete
@@ -456,6 +1330,34 @@ export class ActionBuilder {
456
1330
  getActiveCount() {
457
1331
  return this.scheduler.getActiveCount();
458
1332
  }
1333
+ /**
1334
+ * Cancel all active invocations of this action
1335
+ * @param reasonOrPredicate Reason string or predicate function to filter invocations
1336
+ */
1337
+ cancelAll(reasonOrPredicate) {
1338
+ let count = 0;
1339
+ const invocations = Array.from(this.activeInvocations.values());
1340
+ for (const invocation of invocations) {
1341
+ if (typeof reasonOrPredicate === 'function') {
1342
+ if (reasonOrPredicate(invocation)) {
1343
+ invocation.cancel('Cancelled by predicate');
1344
+ count++;
1345
+ }
1346
+ }
1347
+ else {
1348
+ invocation.cancel(reasonOrPredicate);
1349
+ count++;
1350
+ }
1351
+ }
1352
+ return count;
1353
+ }
1354
+ /**
1355
+ * Cancel only queued (not running) invocations
1356
+ * @param reason Optional cancellation reason
1357
+ */
1358
+ clearQueue(reason) {
1359
+ return this.scheduler.clearQueue(reason);
1360
+ }
459
1361
  }
460
1362
  // Factory function that infers types from the handler
461
1363
  export function createAction(handler) {
@@ -475,4 +1377,18 @@ export function withContext(handler) {
475
1377
  wrapper.__originalHandler = handler;
476
1378
  return wrapper;
477
1379
  }
1380
+ /**
1381
+ * Wrapper function to enable AbortSignal for a handler
1382
+ * Returns a modified handler that can be used with createAction
1383
+ */
1384
+ export function withAbortSignal(handler) {
1385
+ // Return a wrapper that will be detected by ActionBuilder
1386
+ const wrapper = ((...args) => {
1387
+ // This will never be called directly - ActionBuilder intercepts it
1388
+ throw new Error('withAbortSignal handler should not be called directly');
1389
+ });
1390
+ wrapper.__usesAbortSignal = true;
1391
+ wrapper.__originalHandler = handler;
1392
+ return wrapper;
1393
+ }
478
1394
  //# sourceMappingURL=index.js.map