@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
@@ -1,6 +1,5 @@
1
1
  import { AsyncNode, AsyncFlow } from '../qflow.js';
2
- // You would need to install the 'node-cron' library: npm install node-cron
3
- import * as cron from 'node-cron';
2
+ import { loadOptional } from '../optional.js';
4
3
  import { log } from '../logger.js';
5
4
  export class SchedulerNode extends AsyncNode {
6
5
  static getToolDefinition() {
@@ -64,6 +63,7 @@ export class SchedulerNode extends AsyncNode {
64
63
  }
65
64
  let task;
66
65
  if (typeof schedule === 'string') { // Cron string
66
+ const cron = await loadOptional('node-cron');
67
67
  task = cron.schedule(schedule, async () => {
68
68
  log(`[SchedulerNode] Scheduled cron task triggered for ID: ${id}`, this.params.logging);
69
69
  try {
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * Performs a web search using DuckDuckGo's HTML-only interface.
3
- * This node does not require an API key and is designed for reliability without heavy dependencies.
3
+ * This node does not require an API key. HTML parsing uses the optional `cheerio` package.
4
4
  * @param {object} params - The parameters for the node.
5
5
  * @param {string} params.query - The search query.
6
6
  * @returns {Promise<object[]>} A promise that resolves to an array of search result objects.
@@ -1,9 +1,9 @@
1
1
  import { AsyncNode } from '../qflow.js';
2
- import * as cheerio from 'cheerio';
2
+ import { loadOptional } from '../optional.js';
3
3
  import { log } from '../logger.js';
4
4
  /**
5
5
  * Performs a web search using DuckDuckGo's HTML-only interface.
6
- * This node does not require an API key and is designed for reliability without heavy dependencies.
6
+ * This node does not require an API key. HTML parsing uses the optional `cheerio` package.
7
7
  * @param {object} params - The parameters for the node.
8
8
  * @param {string} params.query - The search query.
9
9
  * @returns {Promise<object[]>} A promise that resolves to an array of search result objects.
@@ -37,6 +37,7 @@ export class DuckDuckGoSearchNode extends AsyncNode {
37
37
  throw new Error(`DuckDuckGo HTML search failed with status ${response.status}`);
38
38
  }
39
39
  const html = await response.text();
40
+ const cheerio = await loadOptional('cheerio');
40
41
  const $ = cheerio.load(html);
41
42
  const results = [];
42
43
  $('.result__body').each((i, el) => {
@@ -1,5 +1,6 @@
1
1
  import { AsyncNode, AsyncFlow } from '../qflow.js';
2
- import { ShellCommandNode, HttpRequestNode } from './index.js'; // Assuming these are available
2
+ import { ShellCommandNode } from './shell.js';
3
+ import { HttpRequestNode } from './http.js';
3
4
  import path from 'path';
4
5
  import os from 'os';
5
6
  import { promises as fs } from 'fs';
@@ -50,12 +50,6 @@ export class SpreadsheetNode extends AsyncNode {
50
50
  required: string[];
51
51
  };
52
52
  };
53
- execAsync(): Promise<any[] | {
54
- sheets: string[];
55
- message?: undefined;
56
- } | {
57
- message: string;
58
- sheets?: undefined;
59
- }>;
53
+ execAsync(): Promise<any>;
60
54
  }
61
55
  import { AsyncNode } from '../qflow.js';
@@ -1,7 +1,7 @@
1
1
  import { AsyncNode } from '../qflow.js';
2
2
  import { promises as fs } from 'fs';
3
3
  import path from 'path';
4
- import * as XLSX from 'xlsx'; // npm install xlsx
4
+ import { loadOptional } from '../optional.js';
5
5
  export class SpreadsheetNode extends AsyncNode {
6
6
  static getToolDefinition() {
7
7
  return {
@@ -79,6 +79,7 @@ export class SpreadsheetNode extends AsyncNode {
79
79
  throw new Error('SpreadsheetNode requires a valid `action`.');
80
80
  }
81
81
  const fileExtension = path.extname(filePath).toLowerCase();
82
+ const XLSX = await loadOptional('xlsx');
82
83
  let workbook;
83
84
  let result;
84
85
  // Helper to read workbook (for read/list_sheets/modify)
@@ -0,0 +1,51 @@
1
+ /** OpenAI-compatible LLM node that emits `llm:delta` flow events while generating. */
2
+ export class StreamingLLMNode extends AsyncNode {
3
+ static getToolDefinition(): {
4
+ name: string;
5
+ description: string;
6
+ parameters: {
7
+ type: string;
8
+ properties: {
9
+ prompt: {
10
+ type: string;
11
+ description: string;
12
+ };
13
+ messages: {
14
+ type: string;
15
+ items: {
16
+ type: string;
17
+ };
18
+ description: string;
19
+ };
20
+ apiKey: {
21
+ type: string;
22
+ description: string;
23
+ };
24
+ model: {
25
+ type: string;
26
+ description: string;
27
+ };
28
+ baseUrl: {
29
+ type: string;
30
+ description: string;
31
+ };
32
+ max_tokens: {
33
+ type: string;
34
+ description: string;
35
+ };
36
+ temperature: {
37
+ type: string;
38
+ description: string;
39
+ };
40
+ };
41
+ required: string[];
42
+ };
43
+ };
44
+ resolveMessages(): any[];
45
+ execAsync(prepRes: any, shared: any, observer?: {}): Promise<any>;
46
+ postAsync(shared: any, prepRes: any, execRes: any): Promise<any>;
47
+ }
48
+ /** Streaming LLM node that reads the agent's stringified conversation history. */
49
+ export class AgentStreamingLLMNode extends StreamingLLMNode {
50
+ }
51
+ import { AsyncNode } from '../qflow.js';
@@ -0,0 +1,120 @@
1
+ import { AsyncNode } from '../qflow.js';
2
+ import { LLM_DELTA_EVENT, LLM_DONE_EVENT, LLM_REASONING_EVENT, streamChatCompletions, } from '../streaming.js';
3
+ const INTERNAL_PARAMS = new Set([
4
+ 'prompt',
5
+ 'messages',
6
+ 'apiKey',
7
+ 'model',
8
+ 'baseUrl',
9
+ 'headers',
10
+ 'logging',
11
+ 'keyword',
12
+ 'signal',
13
+ 'abortSignal',
14
+ ]);
15
+ /** OpenAI-compatible LLM node that emits `llm:delta` flow events while generating. */
16
+ export class StreamingLLMNode extends AsyncNode {
17
+ static getToolDefinition() {
18
+ return {
19
+ name: 'streaming_llm',
20
+ description: 'Generates text via an OpenAI-compatible chat API, streaming each token as a flow event.',
21
+ parameters: {
22
+ type: 'object',
23
+ properties: {
24
+ prompt: { type: 'string', description: 'The prompt to send to the language model.' },
25
+ messages: { type: 'array', items: { type: 'object' }, description: 'Optional chat messages array (takes precedence over prompt).' },
26
+ apiKey: { type: 'string', description: 'API key for the provider.' },
27
+ model: { type: 'string', description: 'Model identifier.' },
28
+ baseUrl: { type: 'string', description: "Provider base URL. Defaults to 'https://api.openai.com/v1'." },
29
+ max_tokens: { type: 'number', description: 'Optional maximum number of tokens to generate.' },
30
+ temperature: { type: 'number', description: 'Optional sampling temperature.' },
31
+ },
32
+ required: ['prompt', 'apiKey', 'model'],
33
+ },
34
+ };
35
+ }
36
+ resolveMessages() {
37
+ const { prompt, messages } = this.params;
38
+ if (messages) {
39
+ if (!Array.isArray(messages)) {
40
+ throw new Error('StreamingLLMNode requires `messages` to be an array.');
41
+ }
42
+ return messages;
43
+ }
44
+ if (!prompt) {
45
+ throw new Error('StreamingLLMNode requires a `prompt` or `messages`.');
46
+ }
47
+ return [{ role: 'user', content: prompt }];
48
+ }
49
+ async execAsync(prepRes, shared, observer = {}) {
50
+ const { apiKey, model, baseUrl = 'https://api.openai.com/v1', headers = {}, signal, abortSignal, } = this.params;
51
+ if (!apiKey)
52
+ throw new Error('StreamingLLMNode requires an `apiKey`.');
53
+ if (!model)
54
+ throw new Error('StreamingLLMNode requires a `model`.');
55
+ const emit = typeof observer.emit === 'function' ? observer.emit : null;
56
+ const metadata = {
57
+ flowId: observer.flowId,
58
+ nodeClass: this.constructor.name,
59
+ model,
60
+ };
61
+ const providerOptions = Object.fromEntries(Object.entries(this.params).filter(([key]) => !INTERNAL_PARAMS.has(key)));
62
+ const result = await streamChatCompletions({
63
+ url: `${baseUrl.replace(/\/+$/, '')}/chat/completions`,
64
+ apiKey,
65
+ model,
66
+ messages: this.resolveMessages(),
67
+ headers,
68
+ body: providerOptions,
69
+ signal: signal ?? abortSignal,
70
+ onDelta: entry => emit?.(LLM_DELTA_EVENT, { ...metadata, ...entry }),
71
+ onReasoning: entry => emit?.(LLM_REASONING_EVENT, { ...metadata, ...entry }),
72
+ });
73
+ emit?.(LLM_DONE_EVENT, {
74
+ ...metadata,
75
+ text: result.text,
76
+ reasoning: result.reasoning,
77
+ finishReason: result.finishReason,
78
+ usage: result.usage,
79
+ });
80
+ return result.text;
81
+ }
82
+ async postAsync(shared, prepRes, execRes) {
83
+ return execRes;
84
+ }
85
+ }
86
+ /** Streaming LLM node that reads the agent's stringified conversation history. */
87
+ export class AgentStreamingLLMNode extends StreamingLLMNode {
88
+ static getToolDefinition() {
89
+ return {
90
+ ...super.getToolDefinition(),
91
+ name: 'agent_streaming_llm',
92
+ description: 'Streams agent reasoning from a stringified chat history.',
93
+ };
94
+ }
95
+ resolveMessages() {
96
+ const { messages } = this.params;
97
+ if (messages)
98
+ return super.resolveMessages();
99
+ const { prompt } = this.params;
100
+ if (!prompt) {
101
+ throw new Error('AgentStreamingLLMNode requires a `prompt` with stringified chat history.');
102
+ }
103
+ let parsed;
104
+ try {
105
+ parsed = JSON.parse(prompt);
106
+ }
107
+ catch (error) {
108
+ throw new Error(`AgentStreamingLLMNode: invalid chat history JSON: ${error.message}`);
109
+ }
110
+ if (!Array.isArray(parsed) || !parsed.every(message => message?.role && message?.content !== undefined)) {
111
+ throw new Error('AgentStreamingLLMNode: expected a JSON array of { role, content } messages.');
112
+ }
113
+ return parsed;
114
+ }
115
+ async postAsync(shared, prepRes, execRes) {
116
+ if (shared)
117
+ shared.llmResponse = execRes;
118
+ return execRes;
119
+ }
120
+ }
@@ -37,11 +37,7 @@ export class WebHookNode extends AsyncNode {
37
37
  flowToTrigger: AsyncFlow | null;
38
38
  webhookPath: any;
39
39
  sharedSecret: any;
40
- execAsync(): Promise<{
41
- status: string;
42
- port: any;
43
- path: any;
44
- }>;
40
+ execAsync(prepRes: any, shared?: {}, observer?: {}): Promise<any>;
45
41
  postAsync(shared: any, prepRes: any, execRes: any): Promise<any>;
46
42
  }
47
43
  import { AsyncNode } from '../qflow.js';
@@ -3,6 +3,7 @@ import http from 'http';
3
3
  import { URL } from 'url'; // Node.js built-in
4
4
  import crypto from 'crypto'; // Node.js built-in
5
5
  import { log } from '../logger.js';
6
+ import { withReplaySafeSideEffect } from '../side_effects.js';
6
7
  export class WebHookNode extends AsyncNode {
7
8
  static getToolDefinition() {
8
9
  return {
@@ -47,107 +48,119 @@ export class WebHookNode extends AsyncNode {
47
48
  this.webhookPath = null;
48
49
  this.sharedSecret = null;
49
50
  }
50
- async execAsync() {
51
- const { port = 3000, // Port to listen on
52
- path = '/webhook', // URL path for the webhook
53
- flow, // The qflow AsyncFlow instance to trigger
54
- sharedSecret, // Optional: for HMAC verification
55
- responseStatus = 200, // HTTP status to send back
56
- responseBody = { status: 'received' }, // HTTP body to send back
57
- waitForFlow = false // Whether to wait for the flow to complete
58
- } = this.params;
59
- if (!flow || !(flow instanceof AsyncFlow)) {
60
- throw new Error('WebHookNode requires a `flow` parameter of type AsyncFlow to trigger.');
61
- }
62
- this.flowToTrigger = flow;
63
- this.webhookPath = path;
64
- this.sharedSecret = sharedSecret;
65
- // Ensure server is not already running
66
- if (this.server && this.server.listening) {
67
- log(`[WebHookNode] Server already listening on port ${port}. Reusing existing server.`, this.params.logging, { type: 'warn' });
68
- return { status: 'server_already_running', port, path };
69
- }
70
- this.server = http.createServer(async (req, res) => {
71
- const requestUrl = new URL(req.url, `http://${req.headers.host}`);
72
- if (req.method === 'POST' && requestUrl.pathname === this.webhookPath) {
73
- let body = '';
74
- req.on('data', chunk => {
75
- body += chunk.toString();
76
- });
77
- req.on('end', async () => {
78
- let payload;
79
- try {
80
- payload = JSON.parse(body);
81
- }
82
- catch (e) {
83
- log('[WebHookNode] Failed to parse webhook body as JSON:', this.params.logging, { type: 'error' });
84
- res.writeHead(400, { 'Content-Type': 'application/json' });
85
- res.end(JSON.stringify({ error: 'Invalid JSON payload' }));
86
- return;
87
- }
88
- // --- Security: HMAC Verification (if sharedSecret is provided) ---
89
- if (this.sharedSecret) {
90
- const signature = req.headers['x-hub-signature-256'] || req.headers['x-webhook-signature']; // Common headers
91
- if (!signature) {
92
- log('[WebHookNode] Webhook received without signature, but sharedSecret is configured.', this.params.logging, { type: 'warn' });
93
- res.writeHead(401, { 'Content-Type': 'application/json' });
94
- res.end(JSON.stringify({ error: 'Missing signature' }));
95
- return;
51
+ async execAsync(prepRes, shared = {}, observer = {}) {
52
+ const execute = async () => {
53
+ const { port = 3000, // Port to listen on
54
+ path = '/webhook', // URL path for the webhook
55
+ flow, // The qflow AsyncFlow instance to trigger
56
+ sharedSecret, // Optional: for HMAC verification
57
+ responseStatus = 200, // HTTP status to send back
58
+ responseBody = { status: 'received' }, // HTTP body to send back
59
+ waitForFlow = false // Whether to wait for the flow to complete
60
+ } = this.params;
61
+ if (!flow || !(flow instanceof AsyncFlow)) {
62
+ throw new Error('WebHookNode requires a `flow` parameter of type AsyncFlow to trigger.');
63
+ }
64
+ this.flowToTrigger = flow;
65
+ this.webhookPath = path;
66
+ this.sharedSecret = sharedSecret;
67
+ // Ensure server is not already running
68
+ if (this.server && this.server.listening) {
69
+ log(`[WebHookNode] Server already listening on port ${port}. Reusing existing server.`, this.params.logging, { type: 'warn' });
70
+ return { status: 'server_already_running', port, path };
71
+ }
72
+ this.server = http.createServer(async (req, res) => {
73
+ const requestUrl = new URL(req.url, `http://${req.headers.host}`);
74
+ if (req.method === 'POST' && requestUrl.pathname === this.webhookPath) {
75
+ let body = '';
76
+ req.on('data', chunk => {
77
+ body += chunk.toString();
78
+ });
79
+ req.on('end', async () => {
80
+ let payload;
81
+ try {
82
+ payload = JSON.parse(body);
96
83
  }
97
- const hmac = crypto.createHmac('sha256', this.sharedSecret);
98
- hmac.update(body);
99
- const digest = `sha256=${hmac.digest('hex')}`; // Format might vary (e.g., 'v1=...')
100
- if (digest !== signature) { // Simple comparison, real-world might need more robust parsing
101
- log('[WebHookNode] Webhook signature mismatch. Request rejected.', this.params.logging, { type: 'warn' });
102
- res.writeHead(403, { 'Content-Type': 'application/json' });
103
- res.end(JSON.stringify({ error: 'Invalid signature' }));
84
+ catch (e) {
85
+ log('[WebHookNode] Failed to parse webhook body as JSON:', this.params.logging, { type: 'error' });
86
+ res.writeHead(400, { 'Content-Type': 'application/json' });
87
+ res.end(JSON.stringify({ error: 'Invalid JSON payload' }));
104
88
  return;
105
89
  }
106
- log('[WebHookNode] Webhook signature verified.', this.params.logging);
107
- }
108
- log(`[WebHookNode] Webhook received on ${this.webhookPath}. Triggering flow...`, this.params.logging);
109
- const triggeredFlowShared = { webhook: { headers: req.headers, payload: payload, method: req.method, path: requestUrl.pathname } };
110
- if (this.params.waitForFlow) {
111
- try {
112
- const flowResult = await this.flowToTrigger.runAsync(triggeredFlowShared);
113
- log('[WebHookNode] Triggered flow completed successfully:', this.params.logging);
114
- res.writeHead(this.params.responseStatus || 200, { 'Content-Type': 'application/json' });
115
- res.end(JSON.stringify(flowResult));
90
+ // --- Security: HMAC Verification (if sharedSecret is provided) ---
91
+ if (this.sharedSecret) {
92
+ const signature = req.headers['x-hub-signature-256'] || req.headers['x-webhook-signature']; // Common headers
93
+ if (!signature) {
94
+ log('[WebHookNode] Webhook received without signature, but sharedSecret is configured.', this.params.logging, { type: 'warn' });
95
+ res.writeHead(401, { 'Content-Type': 'application/json' });
96
+ res.end(JSON.stringify({ error: 'Missing signature' }));
97
+ return;
98
+ }
99
+ const hmac = crypto.createHmac('sha256', this.sharedSecret);
100
+ hmac.update(body);
101
+ const digest = `sha256=${hmac.digest('hex')}`; // Format might vary (e.g., 'v1=...')
102
+ if (digest !== signature) { // Simple comparison, real-world might need more robust parsing
103
+ log('[WebHookNode] Webhook signature mismatch. Request rejected.', this.params.logging, { type: 'warn' });
104
+ res.writeHead(403, { 'Content-Type': 'application/json' });
105
+ res.end(JSON.stringify({ error: 'Invalid signature' }));
106
+ return;
107
+ }
108
+ log('[WebHookNode] Webhook signature verified.', this.params.logging);
116
109
  }
117
- catch (flowError) {
118
- log('[WebHookNode] Triggered flow failed:', this.params.logging, { type: 'error' });
119
- res.writeHead(500, { 'Content-Type': 'application/json' });
120
- res.end(JSON.stringify({ error: 'Flow execution failed' }));
110
+ log(`[WebHookNode] Webhook received on ${this.webhookPath}. Triggering flow...`, this.params.logging);
111
+ const triggeredFlowShared = { webhook: { headers: req.headers, payload: payload, method: req.method, path: requestUrl.pathname } };
112
+ if (this.params.waitForFlow) {
113
+ try {
114
+ const flowResult = await this.flowToTrigger.runAsync(triggeredFlowShared);
115
+ log('[WebHookNode] Triggered flow completed successfully:', this.params.logging);
116
+ res.writeHead(this.params.responseStatus || 200, { 'Content-Type': 'application/json' });
117
+ res.end(JSON.stringify(flowResult));
118
+ }
119
+ catch (flowError) {
120
+ log('[WebHookNode] Triggered flow failed:', this.params.logging, { type: 'error' });
121
+ res.writeHead(500, { 'Content-Type': 'application/json' });
122
+ res.end(JSON.stringify({ error: 'Flow execution failed' }));
123
+ }
121
124
  }
122
- }
123
- else {
124
- this.flowToTrigger.runAsync(triggeredFlowShared)
125
- .then(flowResult => {
126
- log('[WebHookNode] Triggered flow completed successfully:', this.params.logging);
127
- })
128
- .catch(flowError => {
129
- log('[WebHookNode] Triggered flow failed:', this.params.logging, { type: 'error' });
130
- });
131
- // Send response back to webhook sender
132
- res.writeHead(this.params.responseStatus || 200, { 'Content-Type': 'application/json' });
133
- res.end(JSON.stringify(this.params.responseBody || { status: 'received' }));
134
- }
125
+ else {
126
+ this.flowToTrigger.runAsync(triggeredFlowShared)
127
+ .then(flowResult => {
128
+ log('[WebHookNode] Triggered flow completed successfully:', this.params.logging);
129
+ })
130
+ .catch(flowError => {
131
+ log('[WebHookNode] Triggered flow failed:', this.params.logging, { type: 'error' });
132
+ });
133
+ // Send response back to webhook sender
134
+ res.writeHead(this.params.responseStatus || 200, { 'Content-Type': 'application/json' });
135
+ res.end(JSON.stringify(this.params.responseBody || { status: 'received' }));
136
+ }
137
+ });
138
+ }
139
+ else {
140
+ res.writeHead(404, { 'Content-Type': 'text/plain' });
141
+ res.end('Not Found');
142
+ }
143
+ });
144
+ await new Promise(resolve => {
145
+ this.server.listen(port, () => {
146
+ log(`[WebHookNode] Listening for webhooks on http://localhost:${port}${this.webhookPath}`, this.params.logging);
147
+ resolve();
135
148
  });
136
- }
137
- else {
138
- res.writeHead(404, { 'Content-Type': 'text/plain' });
139
- res.end('Not Found');
140
- }
141
- });
142
- await new Promise(resolve => {
143
- this.server.listen(port, () => {
144
- log(`[WebHookNode] Listening for webhooks on http://localhost:${port}${this.webhookPath}`, this.params.logging);
145
- resolve();
146
149
  });
150
+ // This node returns immediately after starting the server.
151
+ // The flow continues, and the server runs in the background.
152
+ return { status: 'listening', port, path: this.webhookPath };
153
+ };
154
+ const outcome = await withReplaySafeSideEffect({
155
+ params: this.params,
156
+ shared,
157
+ observer,
158
+ kind: 'webhook',
159
+ operationId: this.params.operationId,
160
+ onPending: this.params.onPendingSideEffect ?? 'error',
161
+ execute,
147
162
  });
148
- // This node returns immediately after starting the server.
149
- // The flow continues, and the server runs in the background.
150
- return { status: 'listening', port, path: this.webhookPath };
163
+ return outcome.result;
151
164
  }
152
165
  // Cleanup: Ensure the server is closed when the node's flow completes or is cancelled
153
166
  async postAsync(shared, prepRes, execRes) {
@@ -1,5 +1,5 @@
1
1
  import { AsyncNode } from '../qflow.js';
2
- import WebSocket from 'ws';
2
+ import { loadOptional } from '../optional.js';
3
3
  export class WebSocketsNode extends AsyncNode {
4
4
  static getToolDefinition() {
5
5
  return {
@@ -30,13 +30,15 @@ export class WebSocketsNode extends AsyncNode {
30
30
  const { action, url, message, timeout = 5000, // 5-second timeout
31
31
  } = this.params;
32
32
  const connection = shared.webSocketConnection;
33
+ if (action === 'connect' && !url) {
34
+ throw new Error('`url` parameter is required for `connect` action.');
35
+ }
36
+ const WebSocket = action === 'connect' ? (await loadOptional('ws')).default : null;
33
37
  return new Promise(async (resolve, reject) => {
34
38
  const timer = setTimeout(() => reject(new Error(`WebSocket action '${action}' timed out after ${timeout}ms`)), timeout);
35
39
  try {
36
40
  switch (action) {
37
41
  case 'connect':
38
- if (!url)
39
- throw new Error('`url` parameter is required for `connect` action.');
40
42
  const ws = new WebSocket(url);
41
43
  ws.on('open', () => {
42
44
  clearTimeout(timer);
@@ -1,5 +1,5 @@
1
1
  import { AsyncNode } from '../qflow.js';
2
- import { Webview, SizeHint } from 'webview-bun';
2
+ import { loadOptional } from '../optional.js';
3
3
  import { log } from '../logger.js';
4
4
  /**
5
5
  * A node that displays a webview window with the given HTML content.
@@ -44,9 +44,10 @@ export class WebviewNode extends AsyncNode {
44
44
  throw new Error('WebviewNode requires an `html` parameter.');
45
45
  }
46
46
  log(`[WebviewNode] Creating webview window with title: "${title}"`, this.params.logging);
47
+ const { Webview, SizeHint } = await loadOptional('webview-bun');
47
48
  const webview = new Webview();
48
49
  webview.title = title;
49
- webview.size = { width, height, hint: 0 /* SizeHint.NONE */ };
50
+ webview.size = { width, height, hint: SizeHint.NONE };
50
51
  webview.setHTML(html);
51
52
  webview.run();
52
53
  log(`[WebviewNode] Webview window closed.`, this.params.logging);
@@ -0,0 +1,32 @@
1
+ /** Friendly install command for a given optional package. */
2
+ export function optionalInstallCommand(name: any): string;
3
+ /** Create the actionable error thrown when an optional package is unavailable. */
4
+ export function optionalDependencyError(name: any, cause: any): Error;
5
+ /**
6
+ * Dynamically import an optional package, caching the resolved module.
7
+ * Import failures are reported with the exact Bun command needed to fix them.
8
+ */
9
+ export function loadOptional(name: any): any;
10
+ /** Clear cached modules. Useful in tests or after installing a package at runtime. */
11
+ export function clearOptionalDependencyCache(name: any): void;
12
+ /**
13
+ * Optional integration packages and a single loader for them.
14
+ *
15
+ * Core qflow imports never load these packages. A node calls `loadOptional()`
16
+ * only when its action actually needs the integration, so consumers install
17
+ * just the capabilities they use.
18
+ */
19
+ export const OPTIONAL_DEPENDENCIES: Readonly<{
20
+ '@serialport/parser-readline': "@serialport/parser-readline";
21
+ ajv: "ajv";
22
+ 'ajv-formats': "ajv-formats";
23
+ cheerio: "cheerio";
24
+ 'node-cron': "node-cron";
25
+ playwright: "playwright";
26
+ serialport: "serialport";
27
+ 'simple-git': "simple-git";
28
+ ssh2: "ssh2";
29
+ 'webview-bun': "webview-bun";
30
+ ws: "ws";
31
+ xlsx: "xlsx";
32
+ }>;
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Optional integration packages and a single loader for them.
3
+ *
4
+ * Core qflow imports never load these packages. A node calls `loadOptional()`
5
+ * only when its action actually needs the integration, so consumers install
6
+ * just the capabilities they use.
7
+ */
8
+ export const OPTIONAL_DEPENDENCIES = Object.freeze({
9
+ '@serialport/parser-readline': '@serialport/parser-readline',
10
+ ajv: 'ajv',
11
+ 'ajv-formats': 'ajv-formats',
12
+ cheerio: 'cheerio',
13
+ 'node-cron': 'node-cron',
14
+ playwright: 'playwright',
15
+ serialport: 'serialport',
16
+ 'simple-git': 'simple-git',
17
+ ssh2: 'ssh2',
18
+ 'webview-bun': 'webview-bun',
19
+ ws: 'ws',
20
+ xlsx: 'xlsx',
21
+ });
22
+ /** Friendly install command for a given optional package. */
23
+ export function optionalInstallCommand(name) {
24
+ const packageName = OPTIONAL_DEPENDENCIES[name] ?? name;
25
+ return `bun add --optional ${packageName}`;
26
+ }
27
+ /** Create the actionable error thrown when an optional package is unavailable. */
28
+ export function optionalDependencyError(name, cause) {
29
+ const error = new Error(`[qflow] Optional dependency '${name}' is not installed. ` +
30
+ `Install it with: ${optionalInstallCommand(name)}`);
31
+ error.name = 'OptionalDependencyError';
32
+ error.code = 'QFLOW_OPTIONAL_DEPENDENCY_MISSING';
33
+ error.dependency = name;
34
+ error.installCommand = optionalInstallCommand(name);
35
+ if (cause !== undefined)
36
+ error.cause = cause;
37
+ return error;
38
+ }
39
+ const loaders = new Map();
40
+ /**
41
+ * Dynamically import an optional package, caching the resolved module.
42
+ * Import failures are reported with the exact Bun command needed to fix them.
43
+ */
44
+ export function loadOptional(name) {
45
+ if (!loaders.has(name)) {
46
+ const loader = import(name).catch(cause => {
47
+ loaders.delete(name);
48
+ throw optionalDependencyError(name, cause);
49
+ });
50
+ loaders.set(name, loader);
51
+ }
52
+ return loaders.get(name);
53
+ }
54
+ /** Clear cached modules. Useful in tests or after installing a package at runtime. */
55
+ export function clearOptionalDependencyCache(name) {
56
+ if (name == null) {
57
+ loaders.clear();
58
+ return;
59
+ }
60
+ loaders.delete(name);
61
+ }