@fractal-solutions/qflow 1.0.83 → 2.0.0-canary.4

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 +107 -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
@@ -39,13 +39,14 @@ import { HttpServerNode } from '../nodes/http_server.js';
39
39
  import { InteractiveWebviewNode } from '../nodes/interactive_webview.js';
40
40
  import { WebviewNode } from '../nodes/webview.js';
41
41
  import { NavigatorNode } from '../nodes/navigator.js';
42
- import qflowConfig from '../../qflow.config.js'; // Import the config file
43
- import path from 'path';
44
- import { fileURLToPath } from 'url';
45
- // Get the directory name of the current module
42
+ import qflowConfig from '../../qflow.config.js';
43
+ import { AsyncNode } from '../qflow.js';
44
+ import path from 'node:path';
45
+ import { existsSync } from 'node:fs';
46
+ import { fileURLToPath, pathToFileURL } from 'node:url';
46
47
  const __filename = fileURLToPath(import.meta.url);
47
48
  const __dirname = path.dirname(__filename);
48
- const projectRoot = path.resolve(__dirname, '../../'); // Adjust based on actual project structure
49
+ const packageRoot = path.resolve(__dirname, '../..');
49
50
  const coreToolClasses = [
50
51
  CodeInterpreterNode,
51
52
  DataExtractorNode,
@@ -101,31 +102,48 @@ const coreToolClasses = [
101
102
  NavigatorNode,
102
103
  ];
103
104
  let customToolClasses = [];
104
- // Dynamically import custom nodes from qflow.config.js
105
- if (qflowConfig.customNodePaths && qflowConfig.customNodePaths.length > 0) {
106
- for (const nodePath of qflowConfig.customNodePaths) {
107
- try {
108
- // Resolve the path relative to the project root
109
- const absolutePath = path.resolve(projectRoot, nodePath);
110
- // Dynamic import
111
- const module = await import(absolutePath);
112
- // Assuming the node class is the default export or a named export
113
- // This might need refinement based on how users export their nodes
114
- for (const key in module) {
115
- const ExportedClass = module[key];
116
- if (typeof ExportedClass === 'function' && ExportedClass.prototype instanceof AsyncNode && typeof ExportedClass.getToolDefinition === 'function') {
117
- customToolClasses.push(ExportedClass);
118
- }
119
- }
105
+ // Prefer the consuming project's config. The package-local config is only a fallback.
106
+ let customNodePaths = Array.isArray(qflowConfig.customNodePaths) ? [...qflowConfig.customNodePaths] : [];
107
+ for (const configFile of ['qflow.config.js', 'qflow.config.ts']) {
108
+ const configPath = path.resolve(process.cwd(), configFile);
109
+ if (configPath === path.resolve(packageRoot, 'qflow.config.js'))
110
+ continue;
111
+ if (!existsSync(configPath))
112
+ continue;
113
+ try {
114
+ const userConfig = (await import(pathToFileURL(configPath).href)).default;
115
+ if (Array.isArray(userConfig?.customNodePaths)) {
116
+ customNodePaths = userConfig.customNodePaths.map(p => path.isAbsolute(p) ? p : path.resolve(process.cwd(), p));
117
+ break;
120
118
  }
121
- catch (error) {
122
- console.error(`Failed to load custom node from ${nodePath}:`, error);
119
+ }
120
+ catch (error) {
121
+ console.warn(`[qflow] Could not load ${configFile}: ${error.message}`);
122
+ }
123
+ }
124
+ for (const absolutePath of customNodePaths) {
125
+ try {
126
+ const module = await import(pathToFileURL(absolutePath).href);
127
+ for (const key in module) {
128
+ const ExportedClass = module[key];
129
+ if (typeof ExportedClass === 'function' &&
130
+ ExportedClass.prototype instanceof AsyncNode &&
131
+ typeof ExportedClass.getToolDefinition === 'function' &&
132
+ !customToolClasses.includes(ExportedClass)) {
133
+ customToolClasses.push(ExportedClass);
134
+ }
123
135
  }
124
136
  }
137
+ catch (error) {
138
+ console.warn(`[qflow] Failed to load custom node from ${absolutePath}: ${error.message}`);
139
+ }
140
+ }
141
+ export function getToolClasses() {
142
+ return [...coreToolClasses, ...customToolClasses];
125
143
  }
126
144
  export function getToolDefinitions() {
127
145
  const definitions = [];
128
- const allToolClasses = [...coreToolClasses, ...customToolClasses];
146
+ const allToolClasses = getToolClasses();
129
147
  for (const ToolClass of allToolClasses) {
130
148
  if (typeof ToolClass.getToolDefinition === 'function') {
131
149
  definitions.push(ToolClass.getToolDefinition());
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Resolve a stable approval ID. Templates use `{{sharedKey}}`, so
3
+ * `{{orderId}}` becomes `approval:ord-42`. Without a template the ID is a hash
4
+ * of the prompt and shared state.
5
+ */
6
+ export function resolveApprovalId(template: any, { params, shared, prompt }?: {
7
+ params?: {} | undefined;
8
+ shared?: {} | undefined;
9
+ prompt?: string | undefined;
10
+ }): any;
11
+ export { ApprovalPendingError };
12
+ /**
13
+ * Suspend a durable run until a decision is recorded with
14
+ * `checkpointer.approve(runId, decision, approvalId)` or `reject(...)`.
15
+ *
16
+ * The node is re-entered on resume and reads the recorded decision, so no
17
+ * special hydration of `shared` is needed.
18
+ */
19
+ export class WaitForApprovalNode extends AsyncNode {
20
+ constructor({ approvalId, prompt, promptKey, resultKey, approvalsKey, metadata, }?: {
21
+ approvalId?: null | undefined;
22
+ prompt?: null | undefined;
23
+ promptKey?: string | undefined;
24
+ resultKey?: string | undefined;
25
+ approvalsKey?: string | undefined;
26
+ metadata?: null | undefined;
27
+ });
28
+ approvalId: any;
29
+ prompt: any;
30
+ promptKey: string;
31
+ resultKey: string;
32
+ approvalsKey: string;
33
+ metadata: any;
34
+ prepAsync(shared?: {}): Promise<{
35
+ prompt: string;
36
+ shared: {};
37
+ }>;
38
+ execAsync(prepRes: any, shared?: {}, observer?: {}): Promise<any>;
39
+ postAsync(shared: any, prepRes: any, execRes: any): Promise<any>;
40
+ }
41
+ import { ApprovalPendingError } from './util.js';
42
+ import { AsyncNode } from './qflow.js';
@@ -0,0 +1,86 @@
1
+ import { AsyncNode } from './qflow.js';
2
+ import { ApprovalPendingError, resolveTemplate, stableHash } from './util.js';
3
+ export { ApprovalPendingError };
4
+ /**
5
+ * Resolve a stable approval ID. Templates use `{{sharedKey}}`, so
6
+ * `{{orderId}}` becomes `approval:ord-42`. Without a template the ID is a hash
7
+ * of the prompt and shared state.
8
+ */
9
+ export function resolveApprovalId(template, { params = {}, shared = {}, prompt = '' } = {}) {
10
+ if (typeof template === 'function')
11
+ return String(template({ params, shared, prompt }));
12
+ if (template == null || template === true) {
13
+ return `approval:${stableHash({ prompt, shared })}`;
14
+ }
15
+ const rendered = resolveTemplate(String(template), { ...shared, ...params, params, shared, prompt }).trim();
16
+ if (!rendered)
17
+ return `approval:${stableHash({ prompt, shared })}`;
18
+ return rendered.startsWith('approval:') ? rendered : `approval:${rendered}`;
19
+ }
20
+ /**
21
+ * Suspend a durable run until a decision is recorded with
22
+ * `checkpointer.approve(runId, decision, approvalId)` or `reject(...)`.
23
+ *
24
+ * The node is re-entered on resume and reads the recorded decision, so no
25
+ * special hydration of `shared` is needed.
26
+ */
27
+ export class WaitForApprovalNode extends AsyncNode {
28
+ constructor({ approvalId = null, prompt = null, promptKey = 'approvalPrompt', resultKey = 'approval', approvalsKey = 'approvals', metadata = null, } = {}) {
29
+ super();
30
+ this.approvalId = approvalId;
31
+ this.prompt = prompt;
32
+ this.promptKey = promptKey;
33
+ this.resultKey = resultKey;
34
+ this.approvalsKey = approvalsKey;
35
+ this.metadata = metadata;
36
+ }
37
+ async prepAsync(shared = {}) {
38
+ const promptText = this.params.prompt ?? this.prompt
39
+ ?? shared[this.params.promptKey ?? this.promptKey] ?? '';
40
+ return { prompt: String(promptText), shared };
41
+ }
42
+ async execAsync(prepRes, shared = {}, observer = {}) {
43
+ const checkpointer = this.params.checkpointer ?? observer.checkpointer ?? shared.checkpointer;
44
+ const runId = this.params.runId ?? observer.runId ?? shared.runId;
45
+ if (!checkpointer || typeof checkpointer.requestApproval !== 'function') {
46
+ throw new Error('WaitForApprovalNode requires a checkpointer with requestApproval().');
47
+ }
48
+ if (!runId)
49
+ throw new Error('WaitForApprovalNode requires a durable runId.');
50
+ const id = resolveApprovalId(this.params.approvalId ?? this.approvalId, {
51
+ params: this.params,
52
+ shared,
53
+ prompt: prepRes.prompt,
54
+ });
55
+ const record = checkpointer.requestApproval({
56
+ runId,
57
+ approvalId: id,
58
+ prompt: prepRes.prompt,
59
+ metadata: this.params.metadata ?? this.metadata,
60
+ });
61
+ if (record.status === 'pending') {
62
+ observer.emit?.('approval:requested', { runId, approvalId: id, prompt: prepRes.prompt });
63
+ throw new ApprovalPendingError(id, {
64
+ runId,
65
+ prompt: prepRes.prompt,
66
+ step: observer.step ?? null,
67
+ });
68
+ }
69
+ observer.emit?.('approval:resolved', {
70
+ runId,
71
+ approvalId: id,
72
+ status: record.status,
73
+ });
74
+ return { ...(record.decision ?? {}), approvalId: id, status: record.status };
75
+ }
76
+ async postAsync(shared, prepRes, execRes) {
77
+ shared[this.resultKey] = execRes;
78
+ shared[this.approvalsKey] = {
79
+ ...(shared[this.approvalsKey] ?? {}),
80
+ [execRes.approvalId]: execRes,
81
+ };
82
+ if (!Object.keys(this.successors).length)
83
+ return execRes;
84
+ return execRes.approved === false || execRes.status === 'rejected' ? 'reject' : 'approve';
85
+ }
86
+ }
@@ -0,0 +1,103 @@
1
+ export { BudgetExceededError };
2
+ export const BUDGET_CHECK_EVENT: "budget:check";
3
+ export const BUDGET_EXCEEDED_EVENT: "budget:exceeded";
4
+ /** Accumulates LLM usage and enforces cost/token/latency/step limits. */
5
+ export class BudgetTracker {
6
+ constructor({ maxCost, maxTokens, maxDurationMs, maxSteps, startedAt, }?: {
7
+ maxCost?: number | undefined;
8
+ maxTokens?: number | undefined;
9
+ maxDurationMs?: number | undefined;
10
+ maxSteps?: number | undefined;
11
+ startedAt?: null | undefined;
12
+ });
13
+ limits: {
14
+ maxCost: number;
15
+ maxTokens: number;
16
+ maxDurationMs: number;
17
+ maxSteps: number;
18
+ };
19
+ startedAt: number;
20
+ totalCost: number;
21
+ totalTokens: number;
22
+ calls: number;
23
+ record(usage?: null, cost?: null): {
24
+ cost: number;
25
+ tokens: number;
26
+ calls: number;
27
+ steps: number;
28
+ durationMs: number;
29
+ };
30
+ snapshot({ steps, now }?: {
31
+ steps?: number | undefined;
32
+ now?: number | undefined;
33
+ }): {
34
+ cost: number;
35
+ tokens: number;
36
+ calls: number;
37
+ steps: number;
38
+ durationMs: number;
39
+ };
40
+ check(context?: {}): {
41
+ reasons: string[];
42
+ exceeded: boolean;
43
+ maxCost: number;
44
+ maxTokens: number;
45
+ maxDurationMs: number;
46
+ maxSteps: number;
47
+ cost: number;
48
+ tokens: number;
49
+ calls: number;
50
+ steps: number;
51
+ durationMs: number;
52
+ };
53
+ assertWithin(context?: {}): {
54
+ reasons: string[];
55
+ exceeded: boolean;
56
+ maxCost: number;
57
+ maxTokens: number;
58
+ maxDurationMs: number;
59
+ maxSteps: number;
60
+ cost: number;
61
+ tokens: number;
62
+ calls: number;
63
+ steps: number;
64
+ durationMs: number;
65
+ };
66
+ reset({ startedAt }?: {
67
+ startedAt?: number | undefined;
68
+ }): this;
69
+ }
70
+ /** Route a run to `exceeded` when cost/token/latency/step limits are crossed. */
71
+ export class BudgetNode extends AsyncNode {
72
+ constructor({ maxCost, maxTokens, maxDurationMs, maxSteps, tracker, limitsKey, outputKey, throwOnExceed, }?: {
73
+ maxCost?: number | undefined;
74
+ maxTokens?: number | undefined;
75
+ maxDurationMs?: number | undefined;
76
+ maxSteps?: number | undefined;
77
+ tracker?: null | undefined;
78
+ limitsKey?: string | undefined;
79
+ outputKey?: string | undefined;
80
+ throwOnExceed?: boolean | undefined;
81
+ });
82
+ maxCost: number;
83
+ maxTokens: number;
84
+ maxDurationMs: number;
85
+ maxSteps: number;
86
+ tracker: any;
87
+ limitsKey: string;
88
+ outputKey: string;
89
+ throwOnExceed: boolean;
90
+ prepAsync(shared?: {}): Promise<{
91
+ limits: {
92
+ maxCost: any;
93
+ maxTokens: any;
94
+ maxDurationMs: any;
95
+ maxSteps: any;
96
+ };
97
+ shared: {};
98
+ }>;
99
+ execAsync(prepRes: any, shared?: {}, observer?: {}): Promise<any>;
100
+ postAsync(shared: any, _prepRes: any, execRes: any): Promise<any>;
101
+ }
102
+ import { BudgetExceededError } from './util.js';
103
+ import { AsyncNode } from './qflow.js';
package/dist/budget.js ADDED
@@ -0,0 +1,133 @@
1
+ import { AsyncNode } from './qflow.js';
2
+ import { BudgetExceededError } from './util.js';
3
+ export { BudgetExceededError };
4
+ export const BUDGET_CHECK_EVENT = 'budget:check';
5
+ export const BUDGET_EXCEEDED_EVENT = 'budget:exceeded';
6
+ function finite(value) {
7
+ return typeof value === 'number' && Number.isFinite(value) ? value : 0;
8
+ }
9
+ /** Accumulates LLM usage and enforces cost/token/latency/step limits. */
10
+ export class BudgetTracker {
11
+ constructor({ maxCost = Infinity, maxTokens = Infinity, maxDurationMs = Infinity, maxSteps = Infinity, startedAt = null, } = {}) {
12
+ this.limits = { maxCost, maxTokens, maxDurationMs, maxSteps };
13
+ this.startedAt = startedAt ?? Date.now();
14
+ this.totalCost = 0;
15
+ this.totalTokens = 0;
16
+ this.calls = 0;
17
+ }
18
+ record(usage = null, cost = null) {
19
+ this.totalTokens += finite(usage?.total ?? usage?.total_tokens)
20
+ || finite(usage?.prompt) + finite(usage?.completion);
21
+ this.totalCost += finite(cost ?? usage?.cost);
22
+ this.calls += 1;
23
+ return this.snapshot();
24
+ }
25
+ snapshot({ steps = 0, now = Date.now() } = {}) {
26
+ return {
27
+ cost: this.totalCost,
28
+ tokens: this.totalTokens,
29
+ calls: this.calls,
30
+ steps: finite(steps),
31
+ durationMs: Math.max(0, now - this.startedAt),
32
+ };
33
+ }
34
+ check(context = {}) {
35
+ const snapshot = this.snapshot(context);
36
+ const reasons = [];
37
+ if (snapshot.cost > this.limits.maxCost) {
38
+ reasons.push(`cost ${snapshot.cost} > ${this.limits.maxCost}`);
39
+ }
40
+ if (snapshot.tokens > this.limits.maxTokens) {
41
+ reasons.push(`tokens ${snapshot.tokens} > ${this.limits.maxTokens}`);
42
+ }
43
+ if (snapshot.durationMs > this.limits.maxDurationMs) {
44
+ reasons.push(`duration ${snapshot.durationMs}ms > ${this.limits.maxDurationMs}ms`);
45
+ }
46
+ if (snapshot.steps > this.limits.maxSteps) {
47
+ reasons.push(`steps ${snapshot.steps} > ${this.limits.maxSteps}`);
48
+ }
49
+ return { ...snapshot, ...this.limits, reasons, exceeded: reasons.length > 0 };
50
+ }
51
+ assertWithin(context = {}) {
52
+ const result = this.check(context);
53
+ if (result.exceeded)
54
+ throw new BudgetExceededError(result.reasons, result);
55
+ return result;
56
+ }
57
+ reset({ startedAt = Date.now() } = {}) {
58
+ this.startedAt = startedAt;
59
+ this.totalCost = 0;
60
+ this.totalTokens = 0;
61
+ this.calls = 0;
62
+ return this;
63
+ }
64
+ }
65
+ /** Route a run to `exceeded` when cost/token/latency/step limits are crossed. */
66
+ export class BudgetNode extends AsyncNode {
67
+ constructor({ maxCost = Infinity, maxTokens = Infinity, maxDurationMs = Infinity, maxSteps = Infinity, tracker = null, limitsKey = 'budget', outputKey = 'budget', throwOnExceed = false, } = {}) {
68
+ super();
69
+ this.maxCost = maxCost;
70
+ this.maxTokens = maxTokens;
71
+ this.maxDurationMs = maxDurationMs;
72
+ this.maxSteps = maxSteps;
73
+ this.tracker = tracker;
74
+ this.limitsKey = limitsKey;
75
+ this.outputKey = outputKey;
76
+ this.throwOnExceed = throwOnExceed;
77
+ }
78
+ async prepAsync(shared = {}) {
79
+ const limits = {
80
+ maxCost: this.params.maxCost ?? this.maxCost ?? shared[this.limitsKey]?.maxCost ?? Infinity,
81
+ maxTokens: this.params.maxTokens ?? this.maxTokens ?? shared[this.limitsKey]?.maxTokens ?? Infinity,
82
+ maxDurationMs: this.params.maxDurationMs ?? this.maxDurationMs ?? shared[this.limitsKey]?.maxDurationMs ?? Infinity,
83
+ maxSteps: this.params.maxSteps ?? this.maxSteps ?? shared[this.limitsKey]?.maxSteps ?? Infinity,
84
+ };
85
+ if (shared.budgetStartedAt == null)
86
+ shared.budgetStartedAt = Date.now();
87
+ return { limits, shared };
88
+ }
89
+ async execAsync(prepRes, shared = {}, observer = {}) {
90
+ const { limits } = prepRes;
91
+ const tracker = this.params.tracker ?? this.tracker ?? shared.budgetTracker ?? null;
92
+ const steps = shared.agentFlowSteps ?? shared.steps ?? shared.budgetSteps ?? 0;
93
+ const usage = shared.llmUsage ?? {};
94
+ let snapshot;
95
+ if (tracker && typeof tracker.snapshot === 'function') {
96
+ snapshot = { ...tracker.snapshot({ steps }), limits };
97
+ }
98
+ else {
99
+ snapshot = {
100
+ cost: shared.llmCost ?? shared.budgetCost ?? 0,
101
+ tokens: usage.total ?? usage.total_tokens ?? shared.budgetTokens ?? 0,
102
+ calls: 0,
103
+ steps: finite(steps),
104
+ durationMs: Math.max(0, Date.now() - (shared.budgetStartedAt ?? Date.now())),
105
+ };
106
+ }
107
+ const reasons = [];
108
+ if (snapshot.cost > limits.maxCost)
109
+ reasons.push(`cost ${snapshot.cost} > ${limits.maxCost}`);
110
+ if (snapshot.tokens > limits.maxTokens)
111
+ reasons.push(`tokens ${snapshot.tokens} > ${limits.maxTokens}`);
112
+ if (snapshot.durationMs > limits.maxDurationMs) {
113
+ reasons.push(`duration ${snapshot.durationMs}ms > ${limits.maxDurationMs}ms`);
114
+ }
115
+ if (snapshot.steps > limits.maxSteps)
116
+ reasons.push(`steps ${snapshot.steps} > ${limits.maxSteps}`);
117
+ const result = { ...snapshot, reasons, exceeded: reasons.length > 0 };
118
+ observer.emit?.(BUDGET_CHECK_EVENT, result);
119
+ if (result.exceeded) {
120
+ observer.emit?.(BUDGET_EXCEEDED_EVENT, result);
121
+ if (this.params.throwOnExceed ?? this.throwOnExceed) {
122
+ throw new BudgetExceededError(result.reasons, result);
123
+ }
124
+ }
125
+ return result;
126
+ }
127
+ async postAsync(shared, _prepRes, execRes) {
128
+ shared[this.outputKey] = execRes;
129
+ if (!Object.keys(this.successors).length)
130
+ return execRes;
131
+ return execRes.exceeded ? 'exceeded' : 'continue';
132
+ }
133
+ }
@@ -0,0 +1,119 @@
1
+ /** Run a child process with Bun.spawn and capture stdout/stderr. */
2
+ export class BunSpawnNode extends AsyncNode {
3
+ static getToolDefinition(): {
4
+ name: string;
5
+ description: string;
6
+ parameters: {
7
+ type: string;
8
+ properties: {
9
+ command: {
10
+ type: string;
11
+ description: string;
12
+ };
13
+ args: {
14
+ type: string;
15
+ items: {
16
+ type: string;
17
+ };
18
+ description: string;
19
+ };
20
+ cwd: {
21
+ type: string;
22
+ };
23
+ timeoutMs: {
24
+ type: string;
25
+ };
26
+ };
27
+ required: string[];
28
+ };
29
+ };
30
+ prepAsync(shared?: {}): Promise<{
31
+ command: any;
32
+ }>;
33
+ execAsync(prepRes: any, shared?: {}, observer?: {}): Promise<any>;
34
+ postAsync(shared: any, prepRes: any, execRes: any): Promise<any>;
35
+ }
36
+ /** Query a SQLite database with bun:sqlite, with a cached per-shared handle. */
37
+ export class SQLiteQueryNode extends AsyncNode {
38
+ static getToolDefinition(): {
39
+ name: string;
40
+ description: string;
41
+ parameters: {
42
+ type: string;
43
+ properties: {
44
+ database: {
45
+ type: string;
46
+ description: string;
47
+ };
48
+ sql: {
49
+ type: string;
50
+ description: string;
51
+ };
52
+ params: {
53
+ type: string;
54
+ items: {
55
+ type: string;
56
+ };
57
+ };
58
+ mode: {
59
+ type: string;
60
+ enum: string[];
61
+ };
62
+ };
63
+ required: string[];
64
+ };
65
+ };
66
+ prepAsync(shared?: {}): Promise<{
67
+ db: Database;
68
+ }>;
69
+ execAsync(prepRes: any): Promise<any>;
70
+ postAsync(shared: any, prepRes: any, execRes: any): Promise<any>;
71
+ }
72
+ /** Watch a path and collect file-system events. */
73
+ export class FileWatchNode extends AsyncNode {
74
+ constructor({ eventKey, maxEvents, waitForEvent, timeoutMs }?: {
75
+ eventKey?: string | undefined;
76
+ maxEvents?: number | undefined;
77
+ waitForEvent?: boolean | undefined;
78
+ timeoutMs?: null | undefined;
79
+ });
80
+ eventKey: string;
81
+ maxEvents: number;
82
+ waitForEvent: boolean;
83
+ timeoutMs: any;
84
+ events: any[];
85
+ watcher: any;
86
+ execAsync(prepRes: any, shared?: {}, observer?: {}): Promise<any>;
87
+ close(): void;
88
+ postAsync(shared: any, prepRes: any, execRes: any): Promise<any>;
89
+ }
90
+ /** Compose Web Streams with map/filter/reduce/transform operations. */
91
+ export class StreamTransformNode extends AsyncNode {
92
+ constructor({ transform, mode, outputKey, initialValue }?: {
93
+ transform?: null | undefined;
94
+ mode?: string | undefined;
95
+ outputKey?: string | undefined;
96
+ initialValue?: undefined;
97
+ });
98
+ transform: any;
99
+ mode: string;
100
+ outputKey: string;
101
+ initialValue: any;
102
+ prepAsync(shared?: {}): Promise<any>;
103
+ execAsync(chunks?: any[], shared?: {}, observer?: {}): Promise<{
104
+ items: any[];
105
+ stream: ReadableStream<any>;
106
+ }>;
107
+ postAsync(shared: any, prepRes: any, execRes: any): Promise<any>;
108
+ }
109
+ export class StreamMapNode extends StreamTransformNode {
110
+ constructor(options?: {});
111
+ }
112
+ export class StreamFilterNode extends StreamTransformNode {
113
+ constructor(options?: {});
114
+ }
115
+ export class StreamReduceNode extends StreamTransformNode {
116
+ constructor(options?: {});
117
+ }
118
+ import { AsyncNode } from './qflow.js';
119
+ import { Database } from 'bun:sqlite';