@fractal-solutions/qflow 1.0.84 → 2.0.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.
Files changed (114) hide show
  1. package/CHANGELOG.md +119 -0
  2. package/LICENSE +21 -504
  3. package/MIGRATION.md +1130 -0
  4. package/README.md +1432 -823
  5. package/dist/agent/agent.d.ts +4 -22
  6. package/dist/agent/agent.js +4 -364
  7. package/dist/agent/base_agent.d.ts +8 -20
  8. package/dist/agent/base_agent.js +8 -205
  9. package/dist/agent/control_nodes.d.ts +61 -0
  10. package/dist/agent/control_nodes.js +164 -0
  11. package/dist/agent/engine.d.ts +45 -0
  12. package/dist/agent/engine.js +415 -0
  13. package/dist/agent/flow.d.ts +77 -0
  14. package/dist/agent/flow.js +148 -0
  15. package/dist/agent/index.d.ts +12 -0
  16. package/dist/agent/index.js +12 -0
  17. package/dist/agent/lpavrl_agent.d.ts +1 -2
  18. package/dist/agent/lpavrl_agent.js +2 -175
  19. package/dist/agent/ooda_agent.d.ts +1 -2
  20. package/dist/agent/ooda_agent.js +2 -164
  21. package/dist/agent/pema_agent.d.ts +1 -2
  22. package/dist/agent/pema_agent.js +2 -168
  23. package/dist/agent/raor_agent.d.ts +1 -2
  24. package/dist/agent/raor_agent.js +2 -161
  25. package/dist/agent/strategies.d.ts +126 -0
  26. package/dist/agent/strategies.js +159 -0
  27. package/dist/agent/tools.d.ts +1 -0
  28. package/dist/agent/tools.js +42 -24
  29. package/dist/approval.d.ts +42 -0
  30. package/dist/approval.js +86 -0
  31. package/dist/budget.d.ts +103 -0
  32. package/dist/budget.js +133 -0
  33. package/dist/bun_nodes.d.ts +119 -0
  34. package/dist/bun_nodes.js +331 -0
  35. package/dist/contracts.d.ts +30 -0
  36. package/dist/contracts.js +103 -0
  37. package/dist/durable.d.ts +278 -0
  38. package/dist/durable.js +730 -0
  39. package/dist/eval.d.ts +165 -0
  40. package/dist/eval.js +263 -0
  41. package/dist/graph.d.ts +157 -0
  42. package/dist/graph.js +330 -0
  43. package/dist/llm/index.d.ts +359 -0
  44. package/dist/llm/index.js +924 -0
  45. package/dist/logger.js +7 -3
  46. package/dist/mcp/client.d.ts +55 -0
  47. package/dist/mcp/client.js +145 -0
  48. package/dist/mcp/index.d.ts +2 -0
  49. package/dist/mcp/index.js +2 -0
  50. package/dist/mcp/server.d.ts +106 -0
  51. package/dist/mcp/server.js +154 -0
  52. package/dist/mcp/stdio.d.ts +2 -0
  53. package/dist/mcp/stdio.js +3 -0
  54. package/dist/memory.d.ts +101 -0
  55. package/dist/memory.js +217 -0
  56. package/dist/nodes/browser_control.js +5 -4
  57. package/dist/nodes/data_extractor.js +2 -1
  58. package/dist/nodes/data_validation.d.ts +3 -3
  59. package/dist/nodes/data_validation.js +19 -5
  60. package/dist/nodes/database.d.ts +2 -1
  61. package/dist/nodes/database.js +71 -58
  62. package/dist/nodes/gis.js +1 -1
  63. package/dist/nodes/git.d.ts +1 -1
  64. package/dist/nodes/git.js +65 -51
  65. package/dist/nodes/github.d.ts +1 -0
  66. package/dist/nodes/hardware_interaction.d.ts +2 -4
  67. package/dist/nodes/hardware_interaction.js +4 -3
  68. package/dist/nodes/http.d.ts +1 -7
  69. package/dist/nodes/http.js +46 -33
  70. package/dist/nodes/image_gallery.js +45 -45
  71. package/dist/nodes/index.d.ts +8 -0
  72. package/dist/nodes/index.js +8 -0
  73. package/dist/nodes/interactive_webview.d.ts +1 -2
  74. package/dist/nodes/interactive_webview.js +217 -216
  75. package/dist/nodes/multimedia_processing.js +1 -1
  76. package/dist/nodes/navigator.d.ts +7 -0
  77. package/dist/nodes/navigator.js +48 -8
  78. package/dist/nodes/pdf_processor.js +2 -1
  79. package/dist/nodes/remote_execution.js +2 -2
  80. package/dist/nodes/s3.d.ts +1 -0
  81. package/dist/nodes/scheduler.js +2 -2
  82. package/dist/nodes/search.d.ts +1 -1
  83. package/dist/nodes/search.js +3 -2
  84. package/dist/nodes/speech_synthesis.js +2 -1
  85. package/dist/nodes/spreadsheet.d.ts +1 -7
  86. package/dist/nodes/spreadsheet.js +2 -1
  87. package/dist/nodes/streaming_llm.d.ts +51 -0
  88. package/dist/nodes/streaming_llm.js +120 -0
  89. package/dist/nodes/webhook.d.ts +1 -5
  90. package/dist/nodes/webhook.js +106 -93
  91. package/dist/nodes/websockets.js +5 -3
  92. package/dist/nodes/webview.js +3 -2
  93. package/dist/optional.d.ts +32 -0
  94. package/dist/optional.js +61 -0
  95. package/dist/qflow.d.ts +25 -14
  96. package/dist/qflow.js +140 -49
  97. package/dist/schedule.d.ts +41 -0
  98. package/dist/schedule.js +149 -0
  99. package/dist/side_effects.d.ts +50 -0
  100. package/dist/side_effects.js +94 -0
  101. package/dist/streaming.d.ts +35 -0
  102. package/dist/streaming.js +199 -0
  103. package/dist/testing.d.ts +47 -0
  104. package/dist/testing.js +130 -0
  105. package/dist/tool_spec.d.ts +76 -0
  106. package/dist/tool_spec.js +321 -0
  107. package/dist/trace.d.ts +28 -0
  108. package/dist/trace.js +190 -0
  109. package/dist/util.d.ts +57 -0
  110. package/dist/util.js +122 -0
  111. package/package.json +153 -67
  112. package/qflow.config.js +18 -18
  113. package/scripts/postinstall.js +50 -0
  114. package/scripts/verify-package.js +114 -0
package/dist/qflow.d.ts CHANGED
@@ -22,8 +22,10 @@ export class BatchNode extends Node {
22
22
  _exec(items: any): any;
23
23
  }
24
24
  export class Flow extends BaseNode {
25
- constructor(start?: null);
25
+ constructor(start?: null, options?: {});
26
26
  startNode: any;
27
+ maxSteps: any;
28
+ errorNode: any;
27
29
  start(startNode: any): any;
28
30
  getNextNode(curr: any, action: any): any;
29
31
  _orch(shared: any, params?: {}): any;
@@ -31,31 +33,40 @@ export class Flow extends BaseNode {
31
33
  export class BatchFlow extends Flow {
32
34
  }
33
35
  export class AsyncNode extends Node {
34
- prepAsync(shared: any): Promise<void>;
35
- execAsync(prepRes: any): Promise<void>;
36
+ prepAsync(shared: any, observer?: {}): Promise<void>;
37
+ execAsync(prepRes: any, shared: any, observer?: {}): Promise<void>;
36
38
  execFallbackAsync(prepRes: any, error: any): Promise<void>;
37
- postAsync(shared: any, prepRes: any, execRes: any): Promise<void>;
39
+ postAsync(shared: any, prepRes: any, execRes: any, observer?: {}): Promise<void>;
38
40
  _exec(prepRes: any, shared: any, observer?: {}): Promise<void>;
39
- runAsync(shared: any): Promise<void>;
40
- _runAsync(shared: any): Promise<void>;
41
+ runAsync(shared: any, observer?: {}): Promise<void>;
42
+ _runAsync(shared: any, observer?: {}): Promise<void>;
41
43
  _run(): void;
42
44
  }
43
45
  export class AsyncBatchNode extends AsyncNode {
44
- _exec(items: any, shared: any, observer: any): Promise<void[]>;
46
+ _exec(items: any, shared: any, observer?: {}): Promise<void[]>;
45
47
  }
46
48
  export class AsyncParallelBatchNode extends AsyncNode {
47
- _exec(items: any, shared: any, observer: any): Promise<any[]>;
49
+ _exec(items: any, shared: any, observer?: {}): Promise<any[]>;
48
50
  }
49
51
  export class AsyncFlow extends Flow {
50
52
  listeners: {};
51
- on(eventName: any, callback: any): void;
53
+ timeout: any;
54
+ on(eventName: any, callback: any): this;
55
+ /** Listen to every event; callbacks receive `{ event, payload }`. */
56
+ onAny(callback: any): this;
52
57
  emit(eventName: any, payload: any): void;
53
- prepAsync(shared: any): Promise<void>;
54
- postAsync(shared: any, prepRes: any, execRes: any): Promise<any>;
55
- _orchAsync(flowId: any, shared: any, params?: {}, initialNode?: any): Promise<any>;
56
- _runAsync(shared: any): Promise<any>;
58
+ _createFlowObserver(flowId: any, parentObserver?: {}): {
59
+ emit: (eventName: any, payload: any) => void;
60
+ flowId: any;
61
+ parentFlowId: any;
62
+ };
63
+ prepAsync(shared: any, observer?: {}): Promise<void>;
64
+ postAsync(shared: any, prepRes: any, execRes: any, observer?: {}): Promise<any>;
65
+ _orchAsync(flowId: any, shared: any, params?: {}, initialNode?: any, observer?: {}): Promise<any>;
66
+ _runAsync(shared: any, parentObserver?: {}): Promise<any>;
67
+ _executeRun(shared: any, parentObserver?: {}): Promise<any>;
57
68
  run(): void;
58
- runAsync(shared?: {}): Promise<any>;
69
+ runAsync(shared?: {}, observer?: {}): Promise<any>;
59
70
  }
60
71
  export class AsyncBatchFlow extends AsyncFlow {
61
72
  }
package/dist/qflow.js CHANGED
@@ -74,9 +74,11 @@ class BatchNode extends Node {
74
74
  }
75
75
  }
76
76
  class Flow extends BaseNode {
77
- constructor(start = null) {
77
+ constructor(start = null, options = {}) {
78
78
  super();
79
79
  this.startNode = start;
80
+ this.maxSteps = options.maxSteps ?? Infinity;
81
+ this.errorNode = options.onError ?? null;
80
82
  }
81
83
  start(startNode) {
82
84
  this.startNode = startNode;
@@ -92,11 +94,24 @@ class Flow extends BaseNode {
92
94
  _orch(shared, params = {}) {
93
95
  let curr = this.startNode;
94
96
  let lastAction = null;
97
+ let steps = 0;
95
98
  let p = { ...this.params, ...params };
96
99
  while (curr) {
97
- curr.setParams(p);
98
- lastAction = curr._run(shared);
99
- curr = this.getNextNode(curr, lastAction);
100
+ if (steps >= this.maxSteps) {
101
+ throw new Error(`Flow exceeded maxSteps (${this.maxSteps}).`);
102
+ }
103
+ steps++;
104
+ try {
105
+ curr.setParams(p);
106
+ lastAction = curr._run(shared);
107
+ curr = this.getNextNode(curr, lastAction);
108
+ }
109
+ catch (error) {
110
+ if (!this.errorNode)
111
+ throw error;
112
+ shared.error = { message: error.message, stack: error.stack };
113
+ curr = this.errorNode;
114
+ }
100
115
  }
101
116
  return lastAction;
102
117
  }
@@ -121,12 +136,12 @@ class BatchFlow extends Flow {
121
136
  }
122
137
  // ----------- ASYNC VERSIONS ------------
123
138
  class AsyncNode extends Node {
124
- async prepAsync(shared) { }
125
- async execAsync(prepRes) { }
139
+ async prepAsync(shared, observer = {}) { }
140
+ async execAsync(prepRes, shared, observer = {}) { }
126
141
  async execFallbackAsync(prepRes, error) {
127
142
  throw error;
128
143
  }
129
- async postAsync(shared, prepRes, execRes) { }
144
+ async postAsync(shared, prepRes, execRes, observer = {}) { }
130
145
  async _exec(prepRes, shared, observer = {}) {
131
146
  const { emit, flowId } = observer;
132
147
  const nodeClass = this.constructor.name;
@@ -144,7 +159,7 @@ class AsyncNode extends Node {
144
159
  try {
145
160
  for (let i = 0; i < this.maxRetries; i++) {
146
161
  try {
147
- finalResult = await this.execAsync(prepRes, shared);
162
+ finalResult = await this.execAsync(prepRes, shared, observer);
148
163
  finalError = null; // Succeeded, clear any error from previous attempt
149
164
  break; // Exit retry loop
150
165
  }
@@ -191,23 +206,23 @@ class AsyncNode extends Node {
191
206
  }
192
207
  return finalResult;
193
208
  }
194
- async runAsync(shared) {
209
+ async runAsync(shared, observer = {}) {
195
210
  if (Object.keys(this.successors).length) {
196
211
  console.warn("Node won't run successors. Use AsyncFlow.");
197
212
  }
198
- return await this._runAsync(shared);
213
+ return await this._runAsync(shared, observer);
199
214
  }
200
- async _runAsync(shared) {
201
- const prepRes = await this.prepAsync(shared);
202
- const execRes = await this._exec(prepRes, shared);
203
- return await this.postAsync(shared, prepRes, execRes);
215
+ async _runAsync(shared, observer = {}) {
216
+ const prepRes = await this.prepAsync(shared, observer);
217
+ const execRes = await this._exec(prepRes, shared, observer);
218
+ return await this.postAsync(shared, prepRes, execRes, observer);
204
219
  }
205
220
  _run() {
206
221
  throw new Error("Use runAsync instead.");
207
222
  }
208
223
  }
209
224
  class AsyncBatchNode extends AsyncNode {
210
- async _exec(items, shared, observer) {
225
+ async _exec(items, shared, observer = {}) {
211
226
  const results = [];
212
227
  for (const item of items) {
213
228
  results.push(await super._exec(item, shared, observer));
@@ -216,63 +231,137 @@ class AsyncBatchNode extends AsyncNode {
216
231
  }
217
232
  }
218
233
  class AsyncParallelBatchNode extends AsyncNode {
219
- async _exec(items, shared, observer) {
234
+ async _exec(items, shared, observer = {}) {
220
235
  return await Promise.all(items.map(item => super._exec(item, shared, observer)));
221
236
  }
222
237
  }
223
238
  class AsyncFlow extends Flow {
224
- constructor(start = null) {
225
- super(start);
239
+ constructor(start = null, options = {}) {
240
+ super(start, options);
226
241
  this.listeners = {};
242
+ this.timeout = options.timeout ?? null;
227
243
  }
228
244
  on(eventName, callback) {
229
245
  if (!this.listeners[eventName]) {
230
246
  this.listeners[eventName] = [];
231
247
  }
232
248
  this.listeners[eventName].push(callback);
249
+ return this;
250
+ }
251
+ /** Listen to every event; callbacks receive `{ event, payload }`. */
252
+ onAny(callback) {
253
+ return this.on('*', callback);
233
254
  }
234
255
  emit(eventName, payload) {
235
- if (this.listeners[eventName]) {
236
- for (const callback of this.listeners[eventName]) {
256
+ for (const callback of this.listeners[eventName] ?? []) {
257
+ try {
258
+ callback(payload);
259
+ }
260
+ catch (e) {
261
+ console.error(`Error in event listener for '${eventName}':`, e);
262
+ }
263
+ }
264
+ if (eventName !== '*') {
265
+ for (const callback of this.listeners['*'] ?? []) {
237
266
  try {
238
- callback(payload);
267
+ callback({ event: eventName, payload });
239
268
  }
240
269
  catch (e) {
241
- console.error(`Error in event listener for '${eventName}':`, e);
270
+ console.error(`Error in event listener for '*':`, e);
242
271
  }
243
272
  }
244
273
  }
245
274
  }
246
- async prepAsync(shared) { }
247
- async postAsync(shared, prepRes, execRes) {
275
+ _createFlowObserver(flowId, parentObserver = {}) {
276
+ const emit = (eventName, payload) => {
277
+ const event = { ...payload, flowId: payload?.flowId ?? flowId };
278
+ this.emit(eventName, event);
279
+ if (typeof parentObserver.emit === 'function') {
280
+ parentObserver.emit(eventName, {
281
+ ...event,
282
+ parentFlowId: parentObserver.flowId ?? null,
283
+ nested: true,
284
+ });
285
+ }
286
+ };
287
+ return {
288
+ ...parentObserver,
289
+ emit,
290
+ flowId,
291
+ parentFlowId: parentObserver.flowId ?? null,
292
+ };
293
+ }
294
+ async prepAsync(shared, observer = {}) { }
295
+ async postAsync(shared, prepRes, execRes, observer = {}) {
248
296
  return execRes;
249
297
  }
250
- async _orchAsync(flowId, shared, params = {}, initialNode = this.startNode) {
298
+ async _orchAsync(flowId, shared, params = {}, initialNode = this.startNode, observer = {}) {
251
299
  let curr = initialNode;
252
300
  let lastAction = null;
253
301
  let lastExecRes = null;
302
+ let steps = 0;
254
303
  let p = { ...this.params, ...params };
304
+ const observerContext = {
305
+ ...observer,
306
+ emit: typeof observer.emit === 'function' ? observer.emit : this.emit.bind(this),
307
+ flowId: observer.flowId ?? flowId,
308
+ };
309
+ const signal = observerContext.signal;
255
310
  while (curr) {
256
- curr.setParams(p);
257
- const observerContext = { emit: this.emit.bind(this), flowId };
258
- const prepRes = curr instanceof AsyncNode ? await curr.prepAsync(shared) : curr.prep(shared);
259
- const execRes = curr instanceof AsyncNode ? await curr._exec(prepRes, shared, observerContext) : curr._exec(prepRes, shared);
260
- lastAction = curr instanceof AsyncNode ? await curr.postAsync(shared, prepRes, execRes) : curr.post(shared, prepRes, execRes);
261
- lastExecRes = execRes;
262
- curr = this.getNextNode(curr, lastAction);
311
+ if (signal?.aborted)
312
+ throw signal.reason ?? new Error('Flow aborted.');
313
+ if (steps >= this.maxSteps) {
314
+ throw new Error(`Flow exceeded maxSteps (${this.maxSteps}).`);
315
+ }
316
+ steps++;
317
+ try {
318
+ curr.setParams(p);
319
+ const prepRes = curr instanceof AsyncNode ? await curr.prepAsync(shared, observerContext) : curr.prep(shared);
320
+ const execRes = curr instanceof AsyncNode ? await curr._exec(prepRes, shared, observerContext) : curr._exec(prepRes, shared);
321
+ lastAction = curr instanceof AsyncNode ? await curr.postAsync(shared, prepRes, execRes, observerContext) : curr.post(shared, prepRes, execRes);
322
+ lastExecRes = execRes;
323
+ curr = this.getNextNode(curr, lastAction);
324
+ }
325
+ catch (error) {
326
+ if (!this.errorNode)
327
+ throw error;
328
+ shared.error = { message: error.message, stack: error.stack };
329
+ curr = this.errorNode;
330
+ lastExecRes = null;
331
+ }
263
332
  }
264
333
  return lastExecRes;
265
334
  }
266
- async _runAsync(shared) {
267
- const flowId = crypto.randomUUID();
335
+ async _runAsync(shared, parentObserver = {}) {
336
+ if (!this.timeout)
337
+ return await this._executeRun(shared, parentObserver);
338
+ const controller = new AbortController();
339
+ const timeoutError = new Error(`Flow timed out after ${this.timeout}ms.`);
340
+ timeoutError.name = 'TimeoutError';
341
+ const timer = setTimeout(() => controller.abort(timeoutError), this.timeout);
342
+ try {
343
+ return await Promise.race([
344
+ this._executeRun(shared, { ...parentObserver, signal: controller.signal }),
345
+ new Promise((resolve, reject) => {
346
+ controller.signal.addEventListener('abort', () => reject(timeoutError), { once: true });
347
+ }),
348
+ ]);
349
+ }
350
+ finally {
351
+ clearTimeout(timer);
352
+ }
353
+ }
354
+ async _executeRun(shared, parentObserver = {}) {
355
+ const flowObserver = this._createFlowObserver(crypto.randomUUID(), parentObserver);
356
+ const flowId = flowObserver.flowId;
268
357
  const flowStartTime = performance.now();
269
- this.emit('flow:start', { flowId, startTime: Date.now() });
358
+ flowObserver.emit('flow:start', { flowId, startTime: Date.now(), parentFlowId: flowObserver.parentFlowId });
270
359
  let result;
271
360
  let flowError = null;
272
361
  try {
273
- const prepRes = await this.prepAsync(shared);
274
- result = await this._orchAsync(flowId, shared);
275
- return await this.postAsync(shared, prepRes, result);
362
+ const prepRes = await this.prepAsync(shared, flowObserver);
363
+ result = await this._orchAsync(flowId, shared, {}, this.startNode, flowObserver);
364
+ return await this.postAsync(shared, prepRes, result, flowObserver);
276
365
  }
277
366
  catch (e) {
278
367
  flowError = e;
@@ -280,7 +369,7 @@ class AsyncFlow extends Flow {
280
369
  }
281
370
  finally {
282
371
  const flowEndTime = performance.now();
283
- this.emit('flow:end', {
372
+ flowObserver.emit('flow:end', {
284
373
  flowId,
285
374
  endTime: Date.now(),
286
375
  duration: flowEndTime - flowStartTime,
@@ -292,29 +381,31 @@ class AsyncFlow extends Flow {
292
381
  run() {
293
382
  throw new Error("Use runAsync instead.");
294
383
  }
295
- async runAsync(shared = {}) {
296
- return await this._runAsync(shared);
384
+ async runAsync(shared = {}, observer = {}) {
385
+ return await this._runAsync(shared, observer);
297
386
  }
298
387
  }
299
388
  class AsyncBatchFlow extends AsyncFlow {
300
- async _runAsync(shared) {
301
- const prepResults = await this.prepAsync(shared) || [];
389
+ async _runAsync(shared, parentObserver = {}) {
390
+ const flowObserver = this._createFlowObserver(crypto.randomUUID(), parentObserver);
391
+ const prepResults = await this.prepAsync(shared, flowObserver) || [];
302
392
  const results = [];
303
393
  for (const bp of prepResults) {
304
- results.push(await this._orchAsync(crypto.randomUUID(), shared, { ...this.params, ...bp }));
394
+ results.push(await this._orchAsync(flowObserver.flowId, shared, { ...this.params, ...bp }, this.startNode, flowObserver));
305
395
  }
306
- return await this.postAsync(shared, prepResults, results);
396
+ return await this.postAsync(shared, prepResults, results, flowObserver);
307
397
  }
308
398
  }
309
399
  class AsyncParallelBatchFlow extends AsyncFlow {
310
- async _runAsync(shared) {
311
- const prepResults = await this.prepAsync(shared) || [];
400
+ async _runAsync(shared, parentObserver = {}) {
401
+ const flowObserver = this._createFlowObserver(crypto.randomUUID(), parentObserver);
402
+ const prepResults = await this.prepAsync(shared, flowObserver) || [];
312
403
  const results = await Promise.all(prepResults.map(bp => {
313
404
  const newStartNode = new this.startNode.constructor();
314
405
  Object.assign(newStartNode.successors, this.startNode.successors);
315
- return this._orchAsync(crypto.randomUUID(), shared, { ...this.params, ...bp }, newStartNode);
406
+ return this._orchAsync(flowObserver.flowId, shared, { ...this.params, ...bp }, newStartNode, flowObserver);
316
407
  }));
317
- return await this.postAsync(shared, prepResults, results);
408
+ return await this.postAsync(shared, prepResults, results, flowObserver);
318
409
  }
319
410
  }
320
411
  export { BaseNode, Node, BatchNode, Flow, BatchFlow, AsyncNode, AsyncBatchNode, AsyncParallelBatchNode, AsyncFlow, AsyncBatchFlow, AsyncParallelBatchFlow, ConditionalTransition };
@@ -0,0 +1,41 @@
1
+ /** Next epoch-ms matching a standard five-field cron expression. */
2
+ export function nextCronTime(expression: any, from?: Date): number;
3
+ export { SchedulePendingError };
4
+ /**
5
+ * Suspend a durable run until a due time. On first execution it persists the
6
+ * resolved due time into `shared`; on resume it re-checks that same time.
7
+ *
8
+ * Use `checkpointer.listScheduledRuns()` to discover suspended runs whose
9
+ * `dueAt` has passed, then call `flow.runDurable({ runId, resume: true })`.
10
+ */
11
+ export class ScheduleNode extends AsyncNode {
12
+ constructor({ at, delayMs, cron, scheduleId, dueAtKey, scheduleIdKey, resultKey, }?: {
13
+ at?: null | undefined;
14
+ delayMs?: null | undefined;
15
+ cron?: null | undefined;
16
+ scheduleId?: null | undefined;
17
+ dueAtKey?: string | undefined;
18
+ scheduleIdKey?: string | undefined;
19
+ resultKey?: string | undefined;
20
+ });
21
+ at: any;
22
+ delayMs: any;
23
+ cron: any;
24
+ scheduleId: any;
25
+ dueAtKey: string;
26
+ scheduleIdKey: string;
27
+ resultKey: string;
28
+ prepAsync(shared?: {}): Promise<{
29
+ dueAt: number | null;
30
+ scheduleId: any;
31
+ shared: {};
32
+ }>;
33
+ execAsync(prepRes: any, _shared?: {}, observer?: {}): Promise<{
34
+ scheduleId: any;
35
+ dueAt: any;
36
+ firedAt: any;
37
+ }>;
38
+ postAsync(shared: any, _prepRes: any, execRes: any): Promise<any>;
39
+ }
40
+ import { SchedulePendingError } from './util.js';
41
+ import { AsyncNode } from './qflow.js';
@@ -0,0 +1,149 @@
1
+ import { AsyncNode } from './qflow.js';
2
+ import { SchedulePendingError, stableHash } from './util.js';
3
+ export { SchedulePendingError };
4
+ function parseCronField(field, min, max) {
5
+ const values = new Set();
6
+ for (const part of String(field).split(',')) {
7
+ const [rangePart, stepPart] = part.split('/');
8
+ const step = stepPart == null ? 1 : Number(stepPart);
9
+ if (!Number.isFinite(step) || step < 1)
10
+ throw new Error(`Invalid cron step '${stepPart}'.`);
11
+ let start;
12
+ let end;
13
+ if (rangePart === '*') {
14
+ start = min;
15
+ end = max;
16
+ }
17
+ else if (rangePart.includes('-')) {
18
+ const [from, to] = rangePart.split('-');
19
+ start = Number(from);
20
+ end = Number(to);
21
+ }
22
+ else {
23
+ start = Number(rangePart);
24
+ end = stepPart == null ? start : max;
25
+ }
26
+ if (!Number.isFinite(start) || !Number.isFinite(end) || start > end) {
27
+ throw new Error(`Invalid cron field '${field}'.`);
28
+ }
29
+ for (let value = start; value <= end; value += step)
30
+ values.add(value);
31
+ }
32
+ return values;
33
+ }
34
+ /** Next epoch-ms matching a standard five-field cron expression. */
35
+ export function nextCronTime(expression, from = new Date()) {
36
+ const fields = String(expression ?? '').trim().split(/\s+/);
37
+ if (fields.length !== 5)
38
+ throw new Error("Cron expression must have 5 fields: 'minute hour day month weekday'.");
39
+ const minutes = parseCronField(fields[0], 0, 59);
40
+ const hours = parseCronField(fields[1], 0, 23);
41
+ const days = parseCronField(fields[2], 1, 31);
42
+ const months = parseCronField(fields[3], 1, 12);
43
+ const weekdays = new Set([...parseCronField(fields[4], 0, 7)].map(value => value % 7));
44
+ const dayRestricted = fields[2] !== '*';
45
+ const weekdayRestricted = fields[4] !== '*';
46
+ const cursor = new Date(from instanceof Date ? from.getTime() : Number(from));
47
+ if (Number.isNaN(cursor.getTime()))
48
+ throw new Error('nextCronTime requires a valid start date.');
49
+ cursor.setSeconds(0, 0);
50
+ cursor.setMinutes(cursor.getMinutes() + 1);
51
+ const limit = cursor.getTime() + 366 * 24 * 60 * 60 * 1000;
52
+ while (cursor.getTime() <= limit) {
53
+ if (!months.has(cursor.getMonth() + 1)) {
54
+ cursor.setMonth(cursor.getMonth() + 1, 1);
55
+ cursor.setHours(0, 0, 0, 0);
56
+ continue;
57
+ }
58
+ const dayMatches = dayRestricted && weekdayRestricted
59
+ ? days.has(cursor.getDate()) || weekdays.has(cursor.getDay())
60
+ : dayRestricted
61
+ ? days.has(cursor.getDate())
62
+ : weekdayRestricted
63
+ ? weekdays.has(cursor.getDay())
64
+ : true;
65
+ if (!dayMatches) {
66
+ cursor.setDate(cursor.getDate() + 1);
67
+ cursor.setHours(0, 0, 0, 0);
68
+ continue;
69
+ }
70
+ if (!hours.has(cursor.getHours())) {
71
+ cursor.setHours(cursor.getHours() + 1, 0, 0, 0);
72
+ continue;
73
+ }
74
+ if (!minutes.has(cursor.getMinutes())) {
75
+ cursor.setMinutes(cursor.getMinutes() + 1, 0, 0);
76
+ continue;
77
+ }
78
+ return cursor.getTime();
79
+ }
80
+ throw new Error(`No future time matches cron '${expression}'.`);
81
+ }
82
+ /**
83
+ * Suspend a durable run until a due time. On first execution it persists the
84
+ * resolved due time into `shared`; on resume it re-checks that same time.
85
+ *
86
+ * Use `checkpointer.listScheduledRuns()` to discover suspended runs whose
87
+ * `dueAt` has passed, then call `flow.runDurable({ runId, resume: true })`.
88
+ */
89
+ export class ScheduleNode extends AsyncNode {
90
+ constructor({ at = null, delayMs = null, cron = null, scheduleId = null, dueAtKey = 'scheduledAt', scheduleIdKey = 'scheduleId', resultKey = 'scheduleResult', } = {}) {
91
+ super();
92
+ this.at = at;
93
+ this.delayMs = delayMs;
94
+ this.cron = cron;
95
+ this.scheduleId = scheduleId;
96
+ this.dueAtKey = dueAtKey;
97
+ this.scheduleIdKey = scheduleIdKey;
98
+ this.resultKey = resultKey;
99
+ }
100
+ async prepAsync(shared = {}) {
101
+ const at = this.params.at ?? this.at ?? shared[this.dueAtKey];
102
+ let dueAt = null;
103
+ if (at != null) {
104
+ dueAt = at instanceof Date ? at.getTime() : Number(new Date(at));
105
+ if (Number.isNaN(dueAt))
106
+ dueAt = Number(at);
107
+ }
108
+ else if (this.params.delayMs ?? this.delayMs) {
109
+ dueAt = Date.now() + Number(this.params.delayMs ?? this.delayMs);
110
+ }
111
+ else if (this.params.cron ?? this.cron) {
112
+ dueAt = nextCronTime(this.params.cron ?? this.cron, new Date());
113
+ }
114
+ if (!Number.isFinite(dueAt))
115
+ throw new Error('ScheduleNode requires at, delayMs or cron (or a saved scheduledAt).');
116
+ const key = this.params.dueAtKey ?? this.dueAtKey;
117
+ shared[key] = dueAt;
118
+ const id = this.params.scheduleId ?? this.scheduleId ?? shared[this.scheduleIdKey]
119
+ ?? `schedule:${stableHash({ dueAt, node: this.constructor.name })}`;
120
+ shared[this.scheduleIdKey] = id;
121
+ return { dueAt, scheduleId: id, shared };
122
+ }
123
+ async execAsync(prepRes, _shared = {}, observer = {}) {
124
+ const now = this.params.now instanceof Date
125
+ ? this.params.now.getTime()
126
+ : this.params.now ?? Date.now();
127
+ if (now < prepRes.dueAt) {
128
+ observer.emit?.('schedule:waiting', {
129
+ scheduleId: prepRes.scheduleId,
130
+ dueAt: prepRes.dueAt,
131
+ runId: observer.runId,
132
+ });
133
+ throw new SchedulePendingError(prepRes.scheduleId, {
134
+ runId: observer.runId,
135
+ dueAt: prepRes.dueAt,
136
+ step: observer.step ?? null,
137
+ });
138
+ }
139
+ return {
140
+ scheduleId: prepRes.scheduleId,
141
+ dueAt: prepRes.dueAt,
142
+ firedAt: now,
143
+ };
144
+ }
145
+ async postAsync(shared, _prepRes, execRes) {
146
+ shared[this.resultKey] = execRes;
147
+ return Object.keys(this.successors).length ? 'due' : execRes;
148
+ }
149
+ }
@@ -0,0 +1,50 @@
1
+ export function resolveOperationId(operationId: any, { params, shared, kind }?: {
2
+ params?: {} | undefined;
3
+ shared?: {} | undefined;
4
+ kind?: string | undefined;
5
+ }): Promise<string>;
6
+ /**
7
+ * Run an external side effect at most once per operation ID per durable run.
8
+ * Completed operations return their recorded result; reserved-but-unfinished
9
+ * operations raise `SideEffectUncertainError` instead of running twice.
10
+ */
11
+ export function withReplaySafeSideEffect({ params, shared, observer, execute, kind, operationId, onPending, workerId, leaseMs, }: {
12
+ params?: {} | undefined;
13
+ shared?: {} | undefined;
14
+ observer?: {} | undefined;
15
+ execute: any;
16
+ kind?: string | undefined;
17
+ operationId?: null | undefined;
18
+ onPending?: string | undefined;
19
+ workerId?: null | undefined;
20
+ leaseMs?: null | undefined;
21
+ }): Promise<any>;
22
+ /** Generic node wrapper for any side effect that should be replay-safe. */
23
+ export class ReplaySafeNode extends AsyncNode {
24
+ constructor({ execute, operationId, kind, resultKey, inputKey, onPending, workerId, leaseMs, maxRetries, wait, }?: {
25
+ operationId?: boolean | undefined;
26
+ kind?: string | undefined;
27
+ resultKey?: string | undefined;
28
+ inputKey?: string | undefined;
29
+ onPending?: string | undefined;
30
+ workerId?: null | undefined;
31
+ leaseMs?: null | undefined;
32
+ maxRetries?: number | undefined;
33
+ wait?: number | undefined;
34
+ });
35
+ execute: any;
36
+ operationId: boolean;
37
+ kind: string;
38
+ resultKey: string;
39
+ inputKey: string;
40
+ onPending: string;
41
+ workerId: any;
42
+ leaseMs: any;
43
+ prepAsync(shared?: {}): Promise<any>;
44
+ execAsync(prepRes: any, shared?: {}, observer?: {}): Promise<any>;
45
+ postAsync(shared: any, prepRes: any, execRes: any): Promise<any>;
46
+ }
47
+ import { SideEffectClaimedError } from './util.js';
48
+ import { SideEffectUncertainError } from './util.js';
49
+ import { AsyncNode } from './qflow.js';
50
+ export { SideEffectClaimedError, SideEffectUncertainError };