@fractal-solutions/qflow 1.0.29 → 1.0.31

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 (37) hide show
  1. package/LICENSE +504 -0
  2. package/README.md +182 -52
  3. package/dist/agent/tools.d.ts +3114 -181
  4. package/dist/agent/tools.js +492 -0
  5. package/dist/nodes/browser_control.d.ts +4 -0
  6. package/dist/nodes/browser_control.js +73 -0
  7. package/dist/nodes/data_validation.d.ts +9 -0
  8. package/dist/nodes/data_validation.js +48 -0
  9. package/dist/nodes/display_image.d.ts +4 -0
  10. package/dist/nodes/display_image.js +46 -0
  11. package/dist/nodes/gis.d.ts +37 -0
  12. package/dist/nodes/gis.js +106 -0
  13. package/dist/nodes/git.d.ts +4 -0
  14. package/dist/nodes/git.js +55 -0
  15. package/dist/nodes/hardware_interaction.d.ts +8 -0
  16. package/dist/nodes/hardware_interaction.js +97 -0
  17. package/dist/nodes/image_gallery.d.ts +8 -0
  18. package/dist/nodes/image_gallery.js +99 -0
  19. package/dist/nodes/index.d.ts +12 -0
  20. package/dist/nodes/index.js +12 -0
  21. package/dist/nodes/multimedia_processing.d.ts +10 -0
  22. package/dist/nodes/multimedia_processing.js +79 -0
  23. package/dist/nodes/pdf_processor.d.ts +4 -0
  24. package/dist/nodes/pdf_processor.js +75 -0
  25. package/dist/nodes/remote_execution.d.ts +4 -0
  26. package/dist/nodes/remote_execution.js +82 -0
  27. package/dist/nodes/scheduler.d.ts +20 -0
  28. package/dist/nodes/scheduler.js +97 -0
  29. package/dist/nodes/speech_synthesis.d.ts +45 -0
  30. package/dist/nodes/speech_synthesis.js +142 -0
  31. package/dist/nodes/spreadsheet.d.ts +10 -0
  32. package/dist/nodes/spreadsheet.js +241 -0
  33. package/dist/nodes/webhook.d.ts +15 -0
  34. package/dist/nodes/webhook.js +110 -0
  35. package/dist/nodes/websockets.d.ts +4 -0
  36. package/dist/nodes/websockets.js +73 -0
  37. package/package.json +11 -2
@@ -0,0 +1,75 @@
1
+ import { AsyncNode, AsyncFlow } from '../qflow.js';
2
+ import { ShellCommandNode, ReadFileNode } from './index.js'; // Assuming these are in the same nodes directory
3
+ import path from 'path';
4
+ import os from 'os';
5
+ import { promises as fs } from 'fs';
6
+ export class PDFProcessorNode extends AsyncNode {
7
+ constructor(maxRetries = 1, wait = 0) {
8
+ super(maxRetries, wait);
9
+ }
10
+ async execAsync() {
11
+ const { filePath, action, outputDir, pageRange, password } = this.params;
12
+ if (!filePath) {
13
+ throw new Error('PDFProcessorNode requires a `filePath` parameter.');
14
+ }
15
+ if (!action || !['extract_text', 'extract_images'].includes(action)) {
16
+ throw new Error('PDFProcessorNode requires an `action` parameter: "extract_text" or "extract_images".');
17
+ }
18
+ const tempOutputDir = outputDir || path.join(os.tmpdir(), `qflow_pdf_output_${Date.now()}`);
19
+ await fs.mkdir(tempOutputDir, { recursive: true });
20
+ let command = '';
21
+ let result = {};
22
+ switch (action) {
23
+ case 'extract_text':
24
+ // Requires 'pdftotext' (from poppler-utils)
25
+ const outputTextFilePath = path.join(tempOutputDir, `${path.basename(filePath, path.extname(filePath))}.txt`);
26
+ command = `pdftotext "${filePath}" "${outputTextFilePath}"`;
27
+ if (pageRange)
28
+ command += ` -f ${pageRange.start} -l ${pageRange.end}`;
29
+ if (password)
30
+ command += ` -opw "${password}"`; // Owner password
31
+ // User password: -upw "password"
32
+ try {
33
+ const shellNode = new ShellCommandNode();
34
+ shellNode.setParams({ command: command });
35
+ await new AsyncFlow(shellNode).runAsync({});
36
+ const readNode = new ReadFileNode();
37
+ readNode.setParams({ filePath: outputTextFilePath });
38
+ const textContent = await new AsyncFlow(readNode).runAsync({});
39
+ result = { text: textContent, outputFilePath: outputTextFilePath };
40
+ }
41
+ catch (e) {
42
+ throw new Error(`Failed to extract text using pdftotext: ${e.message}. Is pdftotext installed and in your PATH?`);
43
+ }
44
+ break;
45
+ case 'extract_images':
46
+ // Requires 'pdfimages' (from poppler-utils)
47
+ const imagePrefix = path.join(tempOutputDir, path.basename(filePath, path.extname(filePath)));
48
+ command = `pdfimages -png "${filePath}" "${imagePrefix}"`; // -png for PNG format
49
+ if (pageRange)
50
+ command += ` -f ${pageRange.start} -l ${pageRange.end}`;
51
+ if (password)
52
+ command += ` -opw "${password}"`;
53
+ try {
54
+ const shellNode = new ShellCommandNode();
55
+ shellNode.setParams({ command: command });
56
+ await new AsyncFlow(shellNode).runAsync({});
57
+ const extractedImages = await fs.readdir(tempOutputDir);
58
+ const imageFiles = extractedImages.filter(file => file.startsWith(path.basename(filePath, path.extname(filePath))) && (file.endsWith('.png') || file.endsWith('.jpg')));
59
+ result = { imageCount: imageFiles.length, outputDirectory: tempOutputDir, imageFiles: imageFiles.map(f => path.join(tempOutputDir, f)) };
60
+ }
61
+ catch (e) {
62
+ throw new Error(`Failed to extract images using pdfimages: ${e.message}. Is pdfimages installed and in your PATH?`);
63
+ }
64
+ break;
65
+ default:
66
+ throw new Error(`Unsupported action: ${action}`);
67
+ }
68
+ // Clean up temporary directory if it was created by this node and not specified by user
69
+ if (!outputDir) {
70
+ // Consider adding a cleanup mechanism or making it explicit for the user
71
+ // For now, we'll leave it for inspection.
72
+ }
73
+ return result;
74
+ }
75
+ }
@@ -0,0 +1,4 @@
1
+ export class RemoteExecutionNode extends AsyncNode {
2
+ execAsync(): Promise<{}>;
3
+ }
4
+ import { AsyncNode } from '../qflow.js';
@@ -0,0 +1,82 @@
1
+ import { AsyncNode } from '../qflow.js';
2
+ // You would need to install the 'ssh2' library: npm install ssh2
3
+ import { Client } from 'ssh2';
4
+ export class RemoteExecutionNode extends AsyncNode {
5
+ constructor(maxRetries = 1, wait = 0) {
6
+ super(maxRetries, wait);
7
+ }
8
+ async execAsync() {
9
+ const { host, port = 22, username, password, // Use with caution, prefer privateKey
10
+ privateKey, // Path to private key file or content
11
+ passphrase, // For encrypted private key
12
+ action, // 'execute_command'
13
+ command, // Command to execute
14
+ timeout = 30000 // Timeout for command execution
15
+ } = this.params;
16
+ if (!host || !username) {
17
+ throw new Error('RemoteExecutionNode requires `host` and `username`.');
18
+ }
19
+ if (!action || action !== 'execute_command') {
20
+ throw new Error('RemoteExecutionNode currently only supports `action: "execute_command"`.');
21
+ }
22
+ if (!command) {
23
+ throw new Error('RemoteExecutionNode `execute_command` action requires a `command`.');
24
+ }
25
+ if (!password && !privateKey) {
26
+ throw new Error('RemoteExecutionNode requires either `password` or `privateKey` for authentication.');
27
+ }
28
+ const conn = new Client();
29
+ let result = {};
30
+ try {
31
+ await new Promise((resolve, reject) => {
32
+ conn.on('ready', () => {
33
+ console.log(`[RemoteExecutionNode] Connected to ${username}@${host}:${port}`);
34
+ resolve();
35
+ }).on('error', (err) => {
36
+ reject(new Error(`SSH connection error: ${err.message}`));
37
+ }).connect({
38
+ host: host,
39
+ port: port,
40
+ username: username,
41
+ password: password,
42
+ privateKey: privateKey ? (privateKey.startsWith('/') ? require('fs').readFileSync(privateKey) : privateKey) : undefined, // Read from file if path, else use content
43
+ passphrase: passphrase,
44
+ readyTimeout: timeout // Timeout for connection to become ready
45
+ });
46
+ });
47
+ // Execute command
48
+ await new Promise((resolve, reject) => {
49
+ conn.exec(command, { pty: false, x11: false, env: {} }, (err, stream) => {
50
+ if (err)
51
+ return reject(new Error(`SSH command execution error: ${err.message}`));
52
+ let stdout = '';
53
+ let stderr = '';
54
+ let exitCode = null;
55
+ let signal = null;
56
+ stream.on('data', (data) => {
57
+ stdout += data.toString();
58
+ }).stderr.on('data', (data) => {
59
+ stderr += data.toString();
60
+ }).on('close', (code, sig) => {
61
+ exitCode = code;
62
+ signal = sig;
63
+ resolve();
64
+ }).on('end', () => {
65
+ // Stream ended
66
+ });
67
+ });
68
+ });
69
+ result = { status: 'command_executed', command: command, stdout: stdout, stderr: stderr, exitCode: exitCode, signal: signal };
70
+ }
71
+ catch (e) {
72
+ throw new Error(`Remote execution failed: ${e.message}`);
73
+ }
74
+ finally {
75
+ if (conn && conn.connected) {
76
+ conn.end();
77
+ console.log(`[RemoteExecutionNode] Disconnected from ${host}`);
78
+ }
79
+ }
80
+ return result;
81
+ }
82
+ }
@@ -0,0 +1,20 @@
1
+ export class SchedulerNode extends AsyncNode {
2
+ static activeTasks: Map<any, any>;
3
+ execAsync(): Promise<{
4
+ status: string;
5
+ type: string;
6
+ schedule: string;
7
+ id: any;
8
+ } | {
9
+ status: string;
10
+ type: string;
11
+ schedule: number;
12
+ id: any;
13
+ } | {
14
+ status: string;
15
+ id: any;
16
+ type?: undefined;
17
+ schedule?: undefined;
18
+ } | undefined>;
19
+ }
20
+ import { AsyncNode } from '../qflow.js';
@@ -0,0 +1,97 @@
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';
4
+ export class SchedulerNode extends AsyncNode {
5
+ // Static map to hold all active scheduled tasks
6
+ static activeTasks = new Map();
7
+ constructor(maxRetries = 1, wait = 0) {
8
+ super(maxRetries, wait);
9
+ }
10
+ async execAsync() {
11
+ const { schedule, flow, flowParams, action, id = `qflow_scheduled_task_${Math.random().toString(16).substr(2, 8)}` // Generate ID if not provided
12
+ } = this.params;
13
+ if (!action || !['start', 'stop'].includes(action)) {
14
+ throw new Error('SchedulerNode requires an `action`: "start" or "stop".');
15
+ }
16
+ if (action === 'start') {
17
+ if (!schedule) {
18
+ throw new Error('SchedulerNode "start" action requires a `schedule`.');
19
+ }
20
+ // Flow can be an AsyncFlow instance or a string (name from flowRegistry)
21
+ if (!flow) {
22
+ throw new Error('SchedulerNode "start" action requires a `flow` parameter.');
23
+ }
24
+ // Stop any existing task with the same ID
25
+ if (SchedulerNode.activeTasks.has(id)) {
26
+ const existingTask = SchedulerNode.activeTasks.get(id);
27
+ existingTask.stop();
28
+ SchedulerNode.activeTasks.delete(id);
29
+ console.log(`[SchedulerNode] Stopped existing task with ID: ${id}`);
30
+ }
31
+ let task;
32
+ if (typeof schedule === 'string') { // Cron string
33
+ task = cron.schedule(schedule, async () => {
34
+ console.log(`[SchedulerNode] Scheduled cron task triggered for ID: ${id}`);
35
+ try {
36
+ // If flow is a string, assume it's a flow name from a global registry
37
+ // This would require the SchedulerNode to have access to the flowRegistry
38
+ // For now, assume 'flow' is an AsyncFlow instance directly passed.
39
+ const flowInstance = flow; // Assuming flow is an AsyncFlow instance
40
+ const taskShared = { ...flowParams };
41
+ const result = await flowInstance.runAsync(taskShared);
42
+ console.log(`[SchedulerNode] Scheduled flow (ID: ${id}) completed successfully. Result:`, result);
43
+ }
44
+ catch (e) {
45
+ console.error(`[SchedulerNode] Scheduled flow (ID: ${id}) failed:`, e);
46
+ }
47
+ }, {
48
+ scheduled: true,
49
+ timezone: 'America/New_York' // Example timezone
50
+ });
51
+ console.log(`[SchedulerNode] Started cron job (ID: ${id}) with schedule: ${schedule}`);
52
+ SchedulerNode.activeTasks.set(id, task);
53
+ return { status: 'scheduled', type: 'cron', schedule: schedule, id: id };
54
+ }
55
+ else if (typeof schedule === 'number') { // Milliseconds for setTimeout
56
+ const timerId = setTimeout(async () => {
57
+ console.log(`[SchedulerNode] Scheduled one-time task triggered for ID: ${id}`);
58
+ try {
59
+ const flowInstance = flow; // Assuming flow is an AsyncFlow instance
60
+ const taskShared = { ...flowParams };
61
+ const result = await flowInstance.runAsync(taskShared);
62
+ console.log(`[SchedulerNode] Scheduled flow (ID: ${id}) completed successfully. Result:`, result);
63
+ }
64
+ catch (e) {
65
+ console.error(`[SchedulerNode] Scheduled flow (ID: ${id}) failed:`, e);
66
+ }
67
+ finally {
68
+ SchedulerNode.activeTasks.delete(id); // Remove one-time task after execution
69
+ }
70
+ }, schedule);
71
+ task = { id: id, stop: () => clearTimeout(timerId) }; // Simple wrapper for setTimeout
72
+ console.log(`[SchedulerNode] Started one-time task (ID: ${id}) in ${schedule}ms`);
73
+ SchedulerNode.activeTasks.set(id, task);
74
+ return { status: 'scheduled', type: 'timeout', schedule: schedule, id: id };
75
+ }
76
+ else {
77
+ throw new Error('Invalid schedule type. Must be a cron string or a number (milliseconds).');
78
+ }
79
+ }
80
+ else if (action === 'stop') {
81
+ if (!id) {
82
+ throw new Error('SchedulerNode "stop" action requires an `id` to identify the task to stop.');
83
+ }
84
+ if (SchedulerNode.activeTasks.has(id)) {
85
+ const taskToStop = SchedulerNode.activeTasks.get(id);
86
+ taskToStop.stop();
87
+ SchedulerNode.activeTasks.delete(id);
88
+ console.log(`[SchedulerNode] Stopped task with ID: ${id}`);
89
+ return { status: 'stopped', id: id };
90
+ }
91
+ else {
92
+ console.warn(`[SchedulerNode] No active task found with ID: ${id}`);
93
+ return { status: 'not_found', id: id };
94
+ }
95
+ }
96
+ }
97
+ }
@@ -0,0 +1,45 @@
1
+ export class SpeechSynthesisNode extends AsyncNode {
2
+ providers: {
3
+ macos: MacOSSayProvider;
4
+ linux: LinuxEspeakProvider;
5
+ windows: WindowsSAPIProvider;
6
+ google: GoogleCloudTTSProvider;
7
+ };
8
+ execAsync(): Promise<{
9
+ status: string;
10
+ filePath?: undefined;
11
+ } | {
12
+ status: string;
13
+ filePath: any;
14
+ }>;
15
+ }
16
+ import { AsyncNode } from '../qflow.js';
17
+ declare class MacOSSayProvider {
18
+ synthesize(text: any, voice: any): Promise<{
19
+ command: string;
20
+ type: string;
21
+ }>;
22
+ }
23
+ declare class LinuxEspeakProvider {
24
+ synthesize(text: any, voice: any): Promise<{
25
+ command: string;
26
+ type: string;
27
+ }>;
28
+ }
29
+ declare class WindowsSAPIProvider {
30
+ synthesize(text: any, voice: any): Promise<void>;
31
+ }
32
+ declare class GoogleCloudTTSProvider {
33
+ constructor(apiKey: any);
34
+ apiKey: any;
35
+ baseUrl: string;
36
+ synthesize(text: any, voiceConfig?: {
37
+ languageCode: string;
38
+ name: string;
39
+ ssmlGender: string;
40
+ }): Promise<{
41
+ filePath: string;
42
+ type: string;
43
+ }>;
44
+ }
45
+ export {};
@@ -0,0 +1,142 @@
1
+ import { AsyncNode, AsyncFlow } from '../qflow.js';
2
+ import { ShellCommandNode, HttpRequestNode } from './index.js'; // Assuming these are available
3
+ import path from 'path';
4
+ import os from 'os';
5
+ import { promises as fs } from 'fs';
6
+ // --- Provider Implementations ---
7
+ // macOS 'say' command provider
8
+ class MacOSSayProvider {
9
+ async synthesize(text, voice) {
10
+ let command = `say "${text}"`;
11
+ if (voice)
12
+ command += ` -v "${voice}"`;
13
+ return { command: command, type: 'shell' };
14
+ }
15
+ }
16
+ // Linux 'espeak' command provider
17
+ class LinuxEspeakProvider {
18
+ async synthesize(text, voice) {
19
+ let command = `espeak "${text}"`;
20
+ if (voice)
21
+ command += ` -v "${voice}"`; // espeak voices are different (e.g., 'en-us', 'en-gb')
22
+ return { command: command, type: 'shell' };
23
+ }
24
+ }
25
+ // Windows PowerShell/SAPI provider (conceptual)
26
+ class WindowsSAPIProvider {
27
+ async synthesize(text, voice) {
28
+ // This is more complex. Requires PowerShell script to use System.Speech.Synthesis.SpeechSynthesizer
29
+ // and save to file, then play. Or directly play.
30
+ // For simplicity, we'll just throw an error for now.
31
+ throw new Error("Windows SAPI synthesis not implemented directly via shell command for this node.");
32
+ }
33
+ }
34
+ // Google Cloud Text-to-Speech Provider (conceptual - requires API key)
35
+ class GoogleCloudTTSProvider {
36
+ constructor(apiKey) {
37
+ this.apiKey = apiKey;
38
+ this.baseUrl = "https://texttospeech.googleapis.com/v1/text:synthesize";
39
+ }
40
+ async synthesize(text, voiceConfig = { languageCode: 'en-US', name: 'en-US-Wavenet-D', ssmlGender: 'NEUTRAL' }) {
41
+ if (!this.apiKey) {
42
+ throw new Error("Google Cloud TTS API Key is not configured.");
43
+ }
44
+ const payload = {
45
+ input: { text: text },
46
+ voice: voiceConfig,
47
+ audioConfig: { audioEncoding: 'MP3' } // Or LINEAR16 for WAV
48
+ };
49
+ const url = `${this.baseUrl}?key=${this.apiKey}`;
50
+ const httpRequest = new HttpRequestNode();
51
+ httpRequest.setParams({
52
+ url: url,
53
+ method: 'POST',
54
+ headers: { 'Content-Type': 'application/json' },
55
+ body: payload
56
+ });
57
+ const response = await new AsyncFlow(httpRequest).runAsync({});
58
+ if (response.status === 200 && response.body && response.body.audioContent) {
59
+ // Google returns base64 encoded audio
60
+ const audioBuffer = Buffer.from(response.body.audioContent, 'base64');
61
+ const tempAudioPath = path.join(os.tmpdir(), `qflow_tts_${Date.now()}.mp3`);
62
+ await fs.writeFile(tempAudioPath, audioBuffer);
63
+ return { filePath: tempAudioPath, type: 'file' };
64
+ }
65
+ else {
66
+ throw new Error(`Google Cloud TTS failed: ${response.status} - ${JSON.stringify(response.body)}`);
67
+ }
68
+ }
69
+ }
70
+ export class SpeechSynthesisNode extends AsyncNode {
71
+ constructor(maxRetries = 1, wait = 0) {
72
+ super(maxRetries, wait);
73
+ this.providers = {
74
+ macos: new MacOSSayProvider(),
75
+ linux: new LinuxEspeakProvider(),
76
+ windows: new WindowsSAPIProvider(), // Placeholder for Windows
77
+ google: new GoogleCloudTTSProvider(process.env.GOOGLE_TTS_API_KEY), // Requires API key
78
+ // Add other providers here
79
+ };
80
+ }
81
+ async execAsync() {
82
+ const { text, provider, voice, outputFilePath } = this.params;
83
+ if (!text) {
84
+ throw new Error('SpeechSynthesisNode requires `text` to synthesize.');
85
+ }
86
+ let selectedProvider;
87
+ let audioOutput;
88
+ // Determine provider based on OS or explicit parameter
89
+ if (provider) {
90
+ selectedProvider = this.providers[provider];
91
+ if (!selectedProvider) {
92
+ throw new Error(`Specified provider '${provider}' not supported or configured.`);
93
+ }
94
+ }
95
+ else {
96
+ // Default to OS-specific provider
97
+ const platform = os.platform();
98
+ if (platform === 'darwin')
99
+ selectedProvider = this.providers.macos;
100
+ else if (platform === 'linux')
101
+ selectedProvider = this.providers.linux;
102
+ else if (platform === 'win32')
103
+ selectedProvider = this.providers.windows;
104
+ else
105
+ throw new Error(`Speech synthesis not supported on platform: ${platform}`);
106
+ }
107
+ // Synthesize speech
108
+ const synthesisResult = await selectedProvider.synthesize(text, voice);
109
+ // Handle audio output (play or save to file)
110
+ if (synthesisResult.type === 'shell') {
111
+ // Directly execute the shell command to play audio
112
+ const shellNode = new ShellCommandNode();
113
+ shellNode.setParams({ command: synthesisResult.command });
114
+ await new AsyncFlow(shellNode).runAsync({});
115
+ audioOutput = { status: 'played_via_shell' };
116
+ }
117
+ else if (synthesisResult.type === 'file') {
118
+ // Audio is saved to a file, now play it
119
+ const audioFilePath = outputFilePath || synthesisResult.filePath;
120
+ if (!outputFilePath) { // If not saving to a specific path, play it
121
+ const playCommand = os.platform() === 'darwin' ? `afplay "${audioFilePath}"` :
122
+ os.platform() === 'linux' ? `aplay "${audioFilePath}"` : // Requires aplay (alsa-utils)
123
+ os.platform() === 'win32' ? `start "" "${audioFilePath}"` : // Plays with default player
124
+ null;
125
+ if (!playCommand)
126
+ throw new Error(`Audio playback not supported on platform: ${os.platform()}`);
127
+ const shellNode = new ShellCommandNode();
128
+ shellNode.setParams({ command: playCommand });
129
+ await new AsyncFlow(shellNode).runAsync({});
130
+ audioOutput = { status: 'played_from_file', filePath: audioFilePath };
131
+ }
132
+ else {
133
+ // If outputFilePath was provided, just return the path
134
+ audioOutput = { status: 'saved_to_file', filePath: audioFilePath };
135
+ }
136
+ }
137
+ else {
138
+ throw new Error('Unsupported synthesis result type.');
139
+ }
140
+ return audioOutput;
141
+ }
142
+ }
@@ -0,0 +1,10 @@
1
+ export class SpreadsheetNode extends AsyncNode {
2
+ execAsync(): Promise<any[] | {
3
+ sheets: string[];
4
+ message?: undefined;
5
+ } | {
6
+ message: string;
7
+ sheets?: undefined;
8
+ }>;
9
+ }
10
+ import { AsyncNode } from '../qflow.js';