@fractal-solutions/qflow 1.0.28 → 1.0.30

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 (45) hide show
  1. package/LICENSE +504 -0
  2. package/README.md +172 -30
  3. package/dist/agent/agent.d.ts +13 -2
  4. package/dist/agent/agent.js +191 -70
  5. package/dist/agent/logger.d.ts +1 -0
  6. package/dist/agent/logger.js +2 -1
  7. package/dist/agent/tools.d.ts +3276 -129
  8. package/dist/agent/tools.js +558 -22
  9. package/dist/nodes/browser_control.d.ts +4 -0
  10. package/dist/nodes/browser_control.js +73 -0
  11. package/dist/nodes/data_validation.d.ts +9 -0
  12. package/dist/nodes/data_validation.js +48 -0
  13. package/dist/nodes/display_image.d.ts +4 -0
  14. package/dist/nodes/display_image.js +46 -0
  15. package/dist/nodes/gis.d.ts +37 -0
  16. package/dist/nodes/gis.js +106 -0
  17. package/dist/nodes/git.d.ts +4 -0
  18. package/dist/nodes/git.js +55 -0
  19. package/dist/nodes/hardware_interaction.d.ts +8 -0
  20. package/dist/nodes/hardware_interaction.js +97 -0
  21. package/dist/nodes/image_gallery.d.ts +8 -0
  22. package/dist/nodes/image_gallery.js +99 -0
  23. package/dist/nodes/index.d.ts +14 -0
  24. package/dist/nodes/index.js +14 -0
  25. package/dist/nodes/interactive_input.d.ts +4 -0
  26. package/dist/nodes/interactive_input.js +70 -0
  27. package/dist/nodes/multimedia_processing.d.ts +10 -0
  28. package/dist/nodes/multimedia_processing.js +79 -0
  29. package/dist/nodes/pdf_processor.d.ts +4 -0
  30. package/dist/nodes/pdf_processor.js +75 -0
  31. package/dist/nodes/remote_execution.d.ts +4 -0
  32. package/dist/nodes/remote_execution.js +82 -0
  33. package/dist/nodes/scheduler.d.ts +20 -0
  34. package/dist/nodes/scheduler.js +97 -0
  35. package/dist/nodes/speech_synthesis.d.ts +45 -0
  36. package/dist/nodes/speech_synthesis.js +142 -0
  37. package/dist/nodes/spreadsheet.d.ts +10 -0
  38. package/dist/nodes/spreadsheet.js +241 -0
  39. package/dist/nodes/system_notification.d.ts +4 -0
  40. package/dist/nodes/system_notification.js +49 -0
  41. package/dist/nodes/webhook.d.ts +15 -0
  42. package/dist/nodes/webhook.js +110 -0
  43. package/dist/nodes/websockets.d.ts +4 -0
  44. package/dist/nodes/websockets.js +73 -0
  45. package/package.json +11 -2
@@ -0,0 +1,70 @@
1
+ import { AsyncNode } from '../qflow.js';
2
+ import { exec } from 'child_process';
3
+ import os from 'os';
4
+ export class InteractiveInputNode extends AsyncNode {
5
+ constructor(maxRetries = 1, wait = 0) {
6
+ super(maxRetries, wait);
7
+ }
8
+ async execAsync() {
9
+ const { prompt, title = 'QFlow Input', defaultValue = '' } = this.params;
10
+ if (!prompt) {
11
+ throw new Error('InteractiveInputNode requires a `prompt` parameter.');
12
+ }
13
+ let command = '';
14
+ const platform = os.platform();
15
+ switch (platform) {
16
+ case 'linux':
17
+ let linuxCommand = '';
18
+ try {
19
+ await new Promise((res, rej) => exec('which zenity', (e) => e ? rej(e) : res()));
20
+ linuxCommand = `zenity --entry --title="${title}" --text="${prompt}" --entry-text="${defaultValue}"`;
21
+ }
22
+ catch (e) {
23
+ try {
24
+ await new Promise((res, rej) => exec('which kdialog', (e) => e ? rej(e) : res()));
25
+ linuxCommand = `kdialog --inputbox "${prompt}" "${defaultValue}" --title "${title}"`;
26
+ }
27
+ catch (e2) {
28
+ throw new Error('No GUI input tool (zenity or kdialog) found on Linux. Please install one or use UserInputNode.');
29
+ }
30
+ }
31
+ command = linuxCommand;
32
+ break;
33
+ case 'darwin': // macOS
34
+ // osascript -e 'set T to text returned of (display dialog "PROMPT" default answer "DEFAULT" with title "TITLE")'
35
+ command = `osascript -e 'set T to text returned of (display dialog "${prompt}" default answer "${defaultValue}" with title "${title}")'`;
36
+ break;
37
+ case 'win32': // Windows
38
+ // PowerShell for input box
39
+ // (New-Object -TypeName Microsoft.VisualBasic.Interaction).InputBox("PROMPT", "TITLE", "DEFAULT")
40
+ command = `powershell -Command "(New-Object -TypeName Microsoft.VisualBasic.Interaction).InputBox(\"${prompt}\", \"${title}\", \"${defaultValue}\")"`;
41
+ break;
42
+ default:
43
+ throw new Error(`Unsupported platform for InteractiveInputNode: ${platform}`);
44
+ }
45
+ console.log(`[InteractiveInputNode] Executing: ${command}`);
46
+ return new Promise((resolve, reject) => {
47
+ exec(command, (error, stdout, stderr) => {
48
+ if (error) {
49
+ // User cancelled the dialog or tool not found
50
+ console.error(`InteractiveInputNode error: ${error.message}`);
51
+ // Differentiate between user cancellation and actual error
52
+ if (error.code === 1 && platform === 'linux' && error.message.includes('zenity')) {
53
+ // Zenity returns 1 on cancel
54
+ return resolve(null); // Or reject with a specific message
55
+ }
56
+ if (error.message.includes('User canceled')) { // osascript cancel
57
+ return resolve(null);
58
+ }
59
+ return reject(error);
60
+ }
61
+ if (stderr) {
62
+ console.warn(`InteractiveInputNode stderr: ${stderr}`);
63
+ }
64
+ const userInput = stdout.trim();
65
+ console.log(`User input received: "${userInput}"`);
66
+ resolve(userInput);
67
+ });
68
+ });
69
+ }
70
+ }
@@ -0,0 +1,10 @@
1
+ export class MultimediaProcessingNode extends AsyncNode {
2
+ execAsync(): Promise<{
3
+ status: string;
4
+ action: any;
5
+ outputPath: any;
6
+ stdout: any;
7
+ stderr: any;
8
+ }>;
9
+ }
10
+ import { AsyncNode } from '../qflow.js';
@@ -0,0 +1,79 @@
1
+ import { AsyncNode, AsyncFlow } from '../qflow.js';
2
+ import { ShellCommandNode } from './index.js'; // Assuming ShellCommandNode is available
3
+ import path from 'path';
4
+ import os from 'os';
5
+ import { promises as fs } from 'fs';
6
+ export class MultimediaProcessingNode extends AsyncNode {
7
+ constructor(maxRetries = 1, wait = 0) {
8
+ super(maxRetries, wait);
9
+ }
10
+ async execAsync() {
11
+ const { action, // e.g., 'convert', 'trim', 'extract_audio', 'extract_frame'
12
+ inputPath, // Path to the input multimedia file
13
+ outputPath, // Path for the output file
14
+ // Parameters specific to actions
15
+ format, // For 'convert' (e.g., 'mp4', 'mp3', 'gif')
16
+ startTime, // For 'trim' (e.g., '00:00:10')
17
+ duration, // For 'trim' (e.g., '00:00:05')
18
+ resolution, // For 'convert' video (e.g., '1280x720')
19
+ frameTime, // For 'extract_frame' (e.g., '00:00:05')
20
+ ffmpegArgs // Optional: raw ffmpeg arguments for advanced users
21
+ } = this.params;
22
+ if (!action) {
23
+ throw new Error('MultimediaProcessingNode requires an `action`.');
24
+ }
25
+ if (!inputPath && action !== 'list_codecs') { // list_codecs doesn't need input
26
+ throw new Error('MultimediaProcessingNode requires an `inputPath`.');
27
+ }
28
+ if (!outputPath && !['list_codecs'].includes(action)) { // list_codecs doesn't need output
29
+ throw new Error('MultimediaProcessingNode requires an `outputPath`.');
30
+ }
31
+ let ffmpegCommand = `ffmpeg -y`; // -y to overwrite output files without asking
32
+ switch (action) {
33
+ case 'convert':
34
+ if (!format)
35
+ throw new Error('Convert action requires `format`.');
36
+ ffmpegCommand += ` -i "${inputPath}"`;
37
+ if (resolution)
38
+ ffmpegCommand += ` -vf scale=${resolution}`;
39
+ ffmpegCommand += ` "${outputPath}"`;
40
+ break;
41
+ case 'trim':
42
+ if (!startTime || !duration)
43
+ throw new Error('Trim action requires `startTime` and `duration`.');
44
+ ffmpegCommand += ` -ss ${startTime} -i "${inputPath}" -t ${duration} -c copy "${outputPath}"`;
45
+ break;
46
+ case 'extract_audio':
47
+ if (!format)
48
+ throw new Error('Extract audio requires `format` (e.g., "mp3", "wav").');
49
+ // Re-encode audio to the specified format
50
+ ffmpegCommand += ` -i "${inputPath}" -vn -c:a libmp3lame "${outputPath}"`; // -vn: no video, -c:a libmp3lame: re-encode audio to MP3
51
+ break;
52
+ case 'extract_frame':
53
+ if (!frameTime)
54
+ throw new Error('Extract frame requires `frameTime` (e.g., "00:00:05").');
55
+ ffmpegCommand += ` -ss ${frameTime} -i "${inputPath}" -vframes 1 "${outputPath}"`; // -vframes 1: extract one frame
56
+ break;
57
+ case 'custom': // For advanced users to pass raw ffmpeg arguments
58
+ if (!ffmpegArgs)
59
+ throw new Error('Custom action requires `ffmpegArgs`.');
60
+ ffmpegCommand = `ffmpeg -y ${ffmpegArgs}`;
61
+ break;
62
+ default:
63
+ throw new Error(`Unsupported action: ${action}`);
64
+ }
65
+ console.log(`[MultimediaProcessingNode] Executing: ${ffmpegCommand}`);
66
+ const shellNode = new ShellCommandNode();
67
+ shellNode.setParams({ command: ffmpegCommand });
68
+ try {
69
+ const result = await new AsyncFlow(shellNode).runAsync({});
70
+ if (result.stderr) {
71
+ console.warn(`[MultimediaProcessingNode] ffmpeg warnings/errors: ${result.stderr}`);
72
+ }
73
+ return { status: 'success', action: action, outputPath: outputPath, stdout: result.stdout, stderr: result.stderr };
74
+ }
75
+ catch (e) {
76
+ throw new Error(`Multimedia processing failed: ${e.message}. Ensure ffmpeg is installed and input/output paths are valid.`);
77
+ }
78
+ }
79
+ }
@@ -0,0 +1,4 @@
1
+ export class PDFProcessorNode extends AsyncNode {
2
+ execAsync(): Promise<{}>;
3
+ }
4
+ import { AsyncNode } from '../qflow.js';
@@ -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';