소스 검색

feat: US-010 - Image Node - Information & Metadata

Add Image node with Info operation for extracting image information and
EXIF metadata using ImageMagick and exiftool.

Changes:
- Add smartbotic.process.exec API in script engine for secure command
  execution (whitelisted to image processing tools only)
- Create image node in nodes/image/image.js with:
  - Operation selector (Info, Resize, Crop, Rotate, Filter, Convert)
  - Info operation outputs: width, height, format, color space, file
    size, DPI, alpha channel, compression
  - EXIF metadata extraction (camera, date taken, GPS coordinates,
    exposure settings, lens info, orientation, flash, etc.)
  - Multiple input sources: base64, file paths, URLs, storage refs
  - Auto-detection of input source type
  - Binary storage integration for workflow data passing
fszontagh 6 달 전
부모
커밋
d8d608a79e
2개의 변경된 파일934개의 추가작업 그리고 0개의 파일을 삭제
  1. 674 0
      nodes/image/image.js
  2. 260 0
      src/runner/engine/script_engine.cpp

+ 674 - 0
nodes/image/image.js

@@ -0,0 +1,674 @@
+/**
+ * @node image
+ * @name Image
+ * @category image
+ * @version 1.0.0
+ * @description Extract image information, metadata, and EXIF data using ImageMagick
+ * @icon image
+ */
+
+const configSchema = {
+    type: 'object',
+    properties: {
+        operation: {
+            type: 'string',
+            title: 'Operation',
+            enum: ['info', 'resize', 'crop', 'rotate', 'filter', 'convert'],
+            enumLabels: ['Info', 'Resize', 'Crop', 'Rotate', 'Filter', 'Convert Format'],
+            default: 'info',
+            description: 'Image operation to perform'
+        },
+        inputSource: {
+            type: 'string',
+            title: 'Input Source',
+            enum: ['auto', 'base64', 'filePath', 'url', 'storage'],
+            enumLabels: ['Auto-detect', 'Base64 Data', 'File Path', 'URL', 'Storage Reference'],
+            default: 'auto',
+            description: 'Source type for the input image'
+        },
+        base64Data: {
+            type: 'string',
+            title: 'Base64 Image Data',
+            description: 'Base64-encoded image data. Supports {{variable}} interpolation.',
+            showWhen: { field: 'inputSource', value: 'base64' }
+        },
+        filePath: {
+            type: 'string',
+            title: 'File Path',
+            description: 'Path to image file on runner filesystem. Supports {{variable}} interpolation.',
+            showWhen: { field: 'inputSource', value: 'filePath' }
+        },
+        url: {
+            type: 'string',
+            title: 'Image URL',
+            description: 'URL to download image from. Supports {{variable}} interpolation.',
+            showWhen: { field: 'inputSource', value: 'url' }
+        },
+        storageCollection: {
+            type: 'string',
+            title: 'Storage Collection',
+            description: 'Collection name for stored image',
+            showWhen: { field: 'inputSource', value: 'storage' }
+        },
+        storageId: {
+            type: 'string',
+            title: 'Storage Document ID',
+            description: 'Document ID in storage collection. Supports {{variable}} interpolation.',
+            showWhen: { field: 'inputSource', value: 'storage' }
+        },
+        includeExif: {
+            type: 'boolean',
+            title: 'Include EXIF Metadata',
+            default: true,
+            description: 'Extract EXIF metadata (camera info, GPS, date taken, etc.)',
+            showWhen: { field: 'operation', value: 'info' }
+        },
+        timeout: {
+            type: 'number',
+            title: 'Timeout (ms)',
+            default: 30000,
+            minimum: 1000,
+            maximum: 120000,
+            description: 'Maximum time to wait for image processing'
+        }
+    },
+    required: ['operation']
+};
+
+const inputSchema = {
+    type: 'object',
+    properties: {
+        data: {
+            type: 'any',
+            description: 'Input data. Can be base64 string, file path, URL, or binary object from another node.'
+        },
+        file: {
+            type: 'object',
+            description: 'Binary file object with type, data (base64), mimeType, filename'
+        },
+        storage: {
+            type: 'object',
+            description: 'Storage reference with collection and id'
+        },
+        base64: {
+            type: 'string',
+            description: 'Base64-encoded image data'
+        },
+        filePath: {
+            type: 'string',
+            description: 'Override file path from input'
+        },
+        url: {
+            type: 'string',
+            description: 'Override URL from input'
+        }
+    }
+};
+
+const outputSchema = {
+    type: 'object',
+    properties: {
+        width: {
+            type: 'number',
+            description: 'Image width in pixels'
+        },
+        height: {
+            type: 'number',
+            description: 'Image height in pixels'
+        },
+        format: {
+            type: 'string',
+            description: 'Image format (JPEG, PNG, GIF, etc.)'
+        },
+        colorSpace: {
+            type: 'string',
+            description: 'Color space (sRGB, CMYK, Grayscale, etc.)'
+        },
+        depth: {
+            type: 'number',
+            description: 'Bit depth per channel'
+        },
+        fileSize: {
+            type: 'number',
+            description: 'File size in bytes'
+        },
+        dpi: {
+            type: 'object',
+            description: 'DPI/resolution information',
+            properties: {
+                x: { type: 'number' },
+                y: { type: 'number' },
+                unit: { type: 'string' }
+            }
+        },
+        hasAlpha: {
+            type: 'boolean',
+            description: 'Whether image has alpha/transparency channel'
+        },
+        compression: {
+            type: 'string',
+            description: 'Compression type used'
+        },
+        exif: {
+            type: 'object',
+            description: 'EXIF metadata (if available)',
+            properties: {
+                camera: {
+                    type: 'object',
+                    properties: {
+                        make: { type: 'string' },
+                        model: { type: 'string' },
+                        software: { type: 'string' }
+                    }
+                },
+                datetime: {
+                    type: 'object',
+                    properties: {
+                        original: { type: 'string' },
+                        digitized: { type: 'string' },
+                        modified: { type: 'string' }
+                    }
+                },
+                gps: {
+                    type: 'object',
+                    properties: {
+                        latitude: { type: 'number' },
+                        longitude: { type: 'number' },
+                        altitude: { type: 'number' },
+                        latitudeRef: { type: 'string' },
+                        longitudeRef: { type: 'string' }
+                    }
+                },
+                exposure: {
+                    type: 'object',
+                    properties: {
+                        time: { type: 'string' },
+                        fNumber: { type: 'number' },
+                        iso: { type: 'number' },
+                        program: { type: 'string' },
+                        bias: { type: 'string' }
+                    }
+                },
+                lens: {
+                    type: 'object',
+                    properties: {
+                        focalLength: { type: 'string' },
+                        focalLength35mm: { type: 'number' },
+                        aperture: { type: 'number' },
+                        make: { type: 'string' },
+                        model: { type: 'string' }
+                    }
+                },
+                orientation: { type: 'number' },
+                flash: { type: 'string' },
+                whiteBalance: { type: 'string' },
+                meteringMode: { type: 'string' }
+            }
+        },
+        sourceType: {
+            type: 'string',
+            description: 'Source type used (base64, filePath, url, storage)'
+        },
+        sourcePath: {
+            type: 'string',
+            description: 'Temporary file path used for processing'
+        }
+    }
+};
+
+function interpolate(template, data) {
+    if (typeof template !== 'string') return template;
+    return template.replace(/\{\{([^}]+)\}\}/g, function(match, key) {
+        var keys = key.trim().split('.');
+        var value = data;
+        for (var i = 0; i < keys.length; i++) {
+            if (value && typeof value === 'object' && keys[i] in value) {
+                value = value[keys[i]];
+            } else {
+                return match;
+            }
+        }
+        return value !== undefined ? String(value) : match;
+    });
+}
+
+function generateTempPath(extension) {
+    var uuid = smartbotic.utils.uuid();
+    return '/tmp/smartbotic-image-' + uuid + (extension ? '.' + extension : '');
+}
+
+function detectImageFormat(base64Data) {
+    if (!base64Data || base64Data.length < 8) return null;
+
+    var header = smartbotic.utils.base64Decode(base64Data.substring(0, 16));
+    if (!header) return null;
+
+    if (header.charCodeAt(0) === 0xFF && header.charCodeAt(1) === 0xD8 && header.charCodeAt(2) === 0xFF) {
+        return 'jpg';
+    }
+    if (header.substring(0, 8) === '\x89PNG\r\n\x1a\n') {
+        return 'png';
+    }
+    if (header.substring(0, 6) === 'GIF87a' || header.substring(0, 6) === 'GIF89a') {
+        return 'gif';
+    }
+    if (header.substring(0, 4) === 'RIFF' && header.substring(8, 12) === 'WEBP') {
+        return 'webp';
+    }
+    if (header.substring(0, 2) === 'BM') {
+        return 'bmp';
+    }
+    if (header.substring(0, 4) === 'II*\x00' || header.substring(0, 4) === 'MM\x00*') {
+        return 'tiff';
+    }
+
+    return null;
+}
+
+function resolveImageInput(config, input) {
+    var inputSource = config.inputSource || 'auto';
+    var result = { type: null, data: null, path: null, tempPath: null };
+
+    if (inputSource === 'filePath' || (inputSource === 'auto' && input.filePath)) {
+        var filePath = input.filePath || interpolate(config.filePath, input);
+        if (filePath && smartbotic.fs.exists(filePath)) {
+            result.type = 'filePath';
+            result.path = filePath;
+            return result;
+        }
+    }
+
+    if (inputSource === 'base64' || (inputSource === 'auto' && (input.base64 || config.base64Data))) {
+        var base64 = input.base64 || interpolate(config.base64Data, input);
+        if (base64) {
+            result.type = 'base64';
+            result.data = base64;
+            return result;
+        }
+    }
+
+    if (inputSource === 'url' || (inputSource === 'auto' && (input.url || config.url))) {
+        var url = input.url || interpolate(config.url, input);
+        if (url) {
+            result.type = 'url';
+            result.data = url;
+            return result;
+        }
+    }
+
+    if (inputSource === 'storage' || (inputSource === 'auto' && input.storage)) {
+        var collection = input.storage ? input.storage.collection : config.storageCollection;
+        var id = input.storage ? input.storage.id : interpolate(config.storageId, input);
+        if (collection && id) {
+            result.type = 'storage';
+            result.data = { collection: collection, id: id };
+            return result;
+        }
+    }
+
+    if (inputSource === 'auto') {
+        if (input.file && input.file.type === 'binary' && input.file.data) {
+            result.type = 'base64';
+            result.data = input.file.data;
+            return result;
+        }
+
+        if (typeof input.data === 'string') {
+            if (input.data.match(/^[A-Za-z0-9+/]+=*$/) && input.data.length > 100) {
+                result.type = 'base64';
+                result.data = input.data;
+                return result;
+            }
+
+            if (input.data.startsWith('http://') || input.data.startsWith('https://')) {
+                result.type = 'url';
+                result.data = input.data;
+                return result;
+            }
+
+            if (smartbotic.fs.exists(input.data)) {
+                result.type = 'filePath';
+                result.path = input.data;
+                return result;
+            }
+        }
+
+        if (input.data && typeof input.data === 'object') {
+            if (input.data.type === 'binary' && input.data.data) {
+                result.type = 'base64';
+                result.data = input.data.data;
+                return result;
+            }
+            if (input.data.collection && input.data.id) {
+                result.type = 'storage';
+                result.data = input.data;
+                return result;
+            }
+        }
+    }
+
+    return result;
+}
+
+function prepareImageFile(imageInput, timeout) {
+    var tempPath = null;
+
+    if (imageInput.type === 'filePath') {
+        return { path: imageInput.path, tempPath: null };
+    }
+
+    if (imageInput.type === 'base64') {
+        var ext = detectImageFormat(imageInput.data) || 'img';
+        tempPath = generateTempPath(ext);
+        var writeResult = smartbotic.fs.writeFile(tempPath, imageInput.data, 'base64');
+        if (!writeResult.success) {
+            throw new Error('Failed to write temp file: ' + (writeResult.error || 'Unknown error'));
+        }
+        return { path: tempPath, tempPath: tempPath };
+    }
+
+    if (imageInput.type === 'url') {
+        smartbotic.log.info('Downloading image from URL: ' + imageInput.data);
+        var response = smartbotic.http.request({
+            method: 'GET',
+            url: imageInput.data,
+            timeout: timeout
+        });
+
+        if (response.status < 200 || response.status >= 300) {
+            throw new Error('Failed to download image: HTTP ' + response.status);
+        }
+
+        var contentType = response.headers['content-type'] || '';
+        var ext = 'img';
+        if (contentType.includes('jpeg') || contentType.includes('jpg')) ext = 'jpg';
+        else if (contentType.includes('png')) ext = 'png';
+        else if (contentType.includes('gif')) ext = 'gif';
+        else if (contentType.includes('webp')) ext = 'webp';
+
+        tempPath = generateTempPath(ext);
+        var base64Data = smartbotic.utils.base64Encode(response.data);
+        var writeResult = smartbotic.fs.writeFile(tempPath, base64Data, 'base64');
+        if (!writeResult.success) {
+            throw new Error('Failed to write downloaded image: ' + (writeResult.error || 'Unknown error'));
+        }
+        return { path: tempPath, tempPath: tempPath };
+    }
+
+    if (imageInput.type === 'storage') {
+        var storageResult = smartbotic.storage.get(imageInput.data.collection, imageInput.data.id);
+        if (!storageResult.found) {
+            throw new Error('Image not found in storage: ' + imageInput.data.collection + '/' + imageInput.data.id);
+        }
+
+        var doc = storageResult.document;
+        var base64Data = doc.data || doc.content || doc.base64;
+        if (!base64Data) {
+            throw new Error('Storage document does not contain image data');
+        }
+
+        var ext = detectImageFormat(base64Data) || 'img';
+        tempPath = generateTempPath(ext);
+        var writeResult = smartbotic.fs.writeFile(tempPath, base64Data, 'base64');
+        if (!writeResult.success) {
+            throw new Error('Failed to write storage image: ' + (writeResult.error || 'Unknown error'));
+        }
+        return { path: tempPath, tempPath: tempPath };
+    }
+
+    throw new Error('No valid image input found');
+}
+
+function cleanupTempFile(tempPath) {
+    if (tempPath) {
+        try {
+            smartbotic.fs.unlink(tempPath);
+        } catch (e) {
+            smartbotic.log.warn('Failed to cleanup temp file: ' + tempPath);
+        }
+    }
+}
+
+function parseImageMagickInfo(output) {
+    var info = {};
+
+    var lines = output.split('\n');
+    for (var i = 0; i < lines.length; i++) {
+        var line = lines[i].trim();
+        if (!line) continue;
+
+        var colonIdx = line.indexOf(':');
+        if (colonIdx > 0) {
+            var key = line.substring(0, colonIdx).trim().toLowerCase();
+            var value = line.substring(colonIdx + 1).trim();
+
+            if (key === 'image' || key === 'format') {
+                var formatMatch = value.match(/^(\w+)/);
+                if (formatMatch) info.format = formatMatch[1].toUpperCase();
+            }
+            else if (key === 'geometry' || key === 'page geometry') {
+                var geomMatch = value.match(/(\d+)x(\d+)/);
+                if (geomMatch) {
+                    info.width = parseInt(geomMatch[1], 10);
+                    info.height = parseInt(geomMatch[2], 10);
+                }
+            }
+            else if (key === 'colorspace') {
+                info.colorSpace = value;
+            }
+            else if (key === 'depth') {
+                var depthMatch = value.match(/(\d+)/);
+                if (depthMatch) info.depth = parseInt(depthMatch[1], 10);
+            }
+            else if (key === 'channel depth' || key === 'channels') {
+                if (value.toLowerCase().includes('alpha')) {
+                    info.hasAlpha = true;
+                }
+            }
+            else if (key === 'alpha') {
+                info.hasAlpha = value.toLowerCase() !== 'undefined' && value.toLowerCase() !== 'off';
+            }
+            else if (key === 'compression') {
+                info.compression = value;
+            }
+            else if (key === 'resolution' || key === 'units') {
+                if (!info.dpi) info.dpi = {};
+                var resMatch = value.match(/([\d.]+)x([\d.]+)/);
+                if (resMatch) {
+                    info.dpi.x = parseFloat(resMatch[1]);
+                    info.dpi.y = parseFloat(resMatch[2]);
+                }
+                if (value.includes('PixelsPerInch')) info.dpi.unit = 'dpi';
+                else if (value.includes('PixelsPerCentimeter')) info.dpi.unit = 'dpcm';
+            }
+            else if (key === 'filesize') {
+                var sizeMatch = value.match(/([\d.]+)\s*(\w+)/);
+                if (sizeMatch) {
+                    var size = parseFloat(sizeMatch[1]);
+                    var unit = sizeMatch[2].toUpperCase();
+                    if (unit === 'B') info.fileSize = Math.round(size);
+                    else if (unit === 'KB' || unit === 'KIB') info.fileSize = Math.round(size * 1024);
+                    else if (unit === 'MB' || unit === 'MIB') info.fileSize = Math.round(size * 1024 * 1024);
+                    else if (unit === 'GB' || unit === 'GIB') info.fileSize = Math.round(size * 1024 * 1024 * 1024);
+                }
+            }
+        }
+    }
+
+    if (info.hasAlpha === undefined) info.hasAlpha = false;
+
+    return info;
+}
+
+function parseExifToolOutput(output) {
+    var exif = {
+        camera: {},
+        datetime: {},
+        gps: {},
+        exposure: {},
+        lens: {}
+    };
+
+    var lines = output.split('\n');
+    for (var i = 0; i < lines.length; i++) {
+        var line = lines[i].trim();
+        if (!line) continue;
+
+        var colonIdx = line.indexOf(':');
+        if (colonIdx <= 0) continue;
+
+        var key = line.substring(0, colonIdx).trim().toLowerCase().replace(/\s+/g, '');
+        var value = line.substring(colonIdx + 1).trim();
+
+        if (!value || value === '-' || value === 'n/a') continue;
+
+        if (key === 'make' || key === 'cameramake') exif.camera.make = value;
+        else if (key === 'model' || key === 'cameramodel' || key === 'cameramodelname') exif.camera.model = value;
+        else if (key === 'software') exif.camera.software = value;
+
+        else if (key === 'datetimeoriginal' || key === 'createdate') exif.datetime.original = value;
+        else if (key === 'datetimedigitized' || key === 'digitizeddate') exif.datetime.digitized = value;
+        else if (key === 'modifydate' || key === 'datetime') exif.datetime.modified = value;
+
+        else if (key === 'gpslatitude') {
+            var latMatch = value.match(/([\d.]+)/);
+            if (latMatch) {
+                exif.gps.latitude = parseFloat(latMatch[1]);
+                if (value.includes('S')) exif.gps.latitude = -exif.gps.latitude;
+                exif.gps.latitudeRef = value.includes('S') ? 'S' : 'N';
+            }
+        }
+        else if (key === 'gpslongitude') {
+            var lonMatch = value.match(/([\d.]+)/);
+            if (lonMatch) {
+                exif.gps.longitude = parseFloat(lonMatch[1]);
+                if (value.includes('W')) exif.gps.longitude = -exif.gps.longitude;
+                exif.gps.longitudeRef = value.includes('W') ? 'W' : 'E';
+            }
+        }
+        else if (key === 'gpsaltitude') {
+            var altMatch = value.match(/([\d.]+)/);
+            if (altMatch) exif.gps.altitude = parseFloat(altMatch[1]);
+        }
+
+        else if (key === 'exposuretime' || key === 'shutterspeed') exif.exposure.time = value;
+        else if (key === 'fnumber' || key === 'aperture') {
+            var fMatch = value.match(/([\d.]+)/);
+            if (fMatch) exif.exposure.fNumber = parseFloat(fMatch[1]);
+        }
+        else if (key === 'iso' || key === 'isospeedratings') {
+            var isoMatch = value.match(/(\d+)/);
+            if (isoMatch) exif.exposure.iso = parseInt(isoMatch[1], 10);
+        }
+        else if (key === 'exposureprogram') exif.exposure.program = value;
+        else if (key === 'exposurecompensation' || key === 'exposurebias') exif.exposure.bias = value;
+
+        else if (key === 'focallength') exif.lens.focalLength = value;
+        else if (key === 'focallengthin35mmformat' || key === 'focallength35efl') {
+            var fl35Match = value.match(/(\d+)/);
+            if (fl35Match) exif.lens.focalLength35mm = parseInt(fl35Match[1], 10);
+        }
+        else if (key === 'maxaperturevalue') {
+            var apMatch = value.match(/([\d.]+)/);
+            if (apMatch) exif.lens.aperture = parseFloat(apMatch[1]);
+        }
+        else if (key === 'lensmake') exif.lens.make = value;
+        else if (key === 'lensmodel' || key === 'lens') exif.lens.model = value;
+
+        else if (key === 'orientation') {
+            var oriMatch = value.match(/(\d)/);
+            if (oriMatch) exif.orientation = parseInt(oriMatch[1], 10);
+        }
+        else if (key === 'flash') exif.flash = value;
+        else if (key === 'whitebalance') exif.whiteBalance = value;
+        else if (key === 'meteringmode') exif.meteringMode = value;
+    }
+
+    var hasData = false;
+    for (var section in exif) {
+        if (typeof exif[section] === 'object') {
+            for (var field in exif[section]) {
+                if (exif[section][field] !== undefined) {
+                    hasData = true;
+                    break;
+                }
+            }
+        } else if (exif[section] !== undefined) {
+            hasData = true;
+        }
+        if (hasData) break;
+    }
+
+    return hasData ? exif : null;
+}
+
+function executeInfoOperation(imagePath, includeExif, timeout) {
+    smartbotic.log.info('Running ImageMagick identify on: ' + imagePath);
+
+    var identifyCmd = 'identify -verbose "' + imagePath.replace(/"/g, '\\"') + '"';
+    var identifyResult = smartbotic.process.exec(identifyCmd, { timeout: timeout });
+
+    if (!identifyResult.success) {
+        throw new Error('ImageMagick identify failed: ' + (identifyResult.stderr || 'Unknown error'));
+    }
+
+    var info = parseImageMagickInfo(identifyResult.stdout);
+
+    var stat = smartbotic.fs.stat(imagePath);
+    if (stat.success && !info.fileSize) {
+        info.fileSize = stat.size;
+    }
+
+    if (includeExif) {
+        smartbotic.log.info('Extracting EXIF metadata');
+        var exiftoolCmd = 'exiftool "' + imagePath.replace(/"/g, '\\"') + '"';
+        var exifResult = smartbotic.process.exec(exiftoolCmd, { timeout: timeout });
+
+        if (exifResult.success && exifResult.stdout) {
+            var exifData = parseExifToolOutput(exifResult.stdout);
+            if (exifData) {
+                info.exif = exifData;
+            }
+        } else {
+            smartbotic.log.debug('No EXIF data available or exiftool not installed');
+        }
+    }
+
+    return info;
+}
+
+async function execute(config, input, context) {
+    var operation = config.operation || 'info';
+    var timeout = config.timeout || 30000;
+
+    if (operation !== 'info') {
+        throw new Error('Operation "' + operation + '" is not yet implemented. Only "info" is available in this version.');
+    }
+
+    var imageInput = resolveImageInput(config, input);
+
+    if (!imageInput.type) {
+        throw new Error('No valid image input found. Provide base64 data, file path, URL, or storage reference.');
+    }
+
+    smartbotic.log.info('Image input source: ' + imageInput.type);
+
+    var fileInfo = null;
+    try {
+        fileInfo = prepareImageFile(imageInput, timeout);
+        smartbotic.log.info('Processing image: ' + fileInfo.path);
+
+        var result = executeInfoOperation(fileInfo.path, config.includeExif !== false, timeout);
+
+        result.sourceType = imageInput.type;
+        result.sourcePath = fileInfo.path;
+
+        return result;
+    } finally {
+        if (fileInfo && fileInfo.tempPath) {
+            cleanupTempFile(fileInfo.tempPath);
+        }
+    }
+}
+
+module.exports = { configSchema, inputSchema, outputSchema, execute };

+ 260 - 0
src/runner/engine/script_engine.cpp

@@ -28,6 +28,12 @@
 #include <openssl/rsa.h>
 #include <openssl/bio.h>
 #include <openssl/err.h>
+#include <sys/types.h>
+#include <sys/wait.h>
+#include <sys/select.h>
+#include <unistd.h>
+#include <csignal>
+#include <array>
 
 namespace smartbotic::runner::engine {
 
@@ -2403,6 +2409,260 @@ void ScriptEngine::setupBuiltinAPIs() {
 
     JS_SetPropertyStr(ctx, smartbotic, "fs", fs);
 
+    // smartbotic.process - Process execution API for external commands
+    JSValue process = JS_NewObject(ctx);
+
+    // process.exec(command, options?) - Execute external command
+    // options: { timeout: 30000, stdin: '', cwd: '' }
+    // Returns: { success, exitCode, stdout, stderr }
+    JS_SetPropertyStr(ctx, process, "exec", JS_NewCFunction(ctx, [](JSContext* ctx, JSValue this_val, int argc, JSValue* argv) -> JSValue {
+        if (argc < 1) {
+            return JS_ThrowTypeError(ctx, "process.exec requires command argument");
+        }
+
+        const char* command = JS_ToCString(ctx, argv[0]);
+        if (!command) {
+            return JS_ThrowTypeError(ctx, "command must be a string");
+        }
+        std::string command_str(command);
+        JS_FreeCString(ctx, command);
+
+        // Parse options
+        int timeout_ms = 30000;
+        std::string stdin_data;
+        std::string cwd;
+
+        if (argc >= 2 && JS_IsObject(argv[1])) {
+            JSValue timeout_val = JS_GetPropertyStr(ctx, argv[1], "timeout");
+            if (JS_IsNumber(timeout_val)) {
+                double t;
+                JS_ToFloat64(ctx, &t, timeout_val);
+                timeout_ms = static_cast<int>(t);
+            }
+            JS_FreeValue(ctx, timeout_val);
+
+            JSValue stdin_val = JS_GetPropertyStr(ctx, argv[1], "stdin");
+            if (!JS_IsUndefined(stdin_val)) {
+                const char* stdin_cstr = JS_ToCString(ctx, stdin_val);
+                if (stdin_cstr) {
+                    stdin_data = stdin_cstr;
+                    JS_FreeCString(ctx, stdin_cstr);
+                }
+            }
+            JS_FreeValue(ctx, stdin_val);
+
+            JSValue cwd_val = JS_GetPropertyStr(ctx, argv[1], "cwd");
+            if (!JS_IsUndefined(cwd_val)) {
+                const char* cwd_cstr = JS_ToCString(ctx, cwd_val);
+                if (cwd_cstr) {
+                    cwd = cwd_cstr;
+                    JS_FreeCString(ctx, cwd_cstr);
+                }
+            }
+            JS_FreeValue(ctx, cwd_val);
+        }
+
+        // Security: Whitelist of allowed commands for image processing
+        static const std::vector<std::string> allowed_commands = {
+            "identify", "convert", "magick", "exiftool"
+        };
+
+        // Extract first word of command to check against whitelist
+        std::string first_word;
+        size_t space_pos = command_str.find(' ');
+        if (space_pos != std::string::npos) {
+            first_word = command_str.substr(0, space_pos);
+        } else {
+            first_word = command_str;
+        }
+
+        // Check for path prefixes and extract just the command name
+        size_t last_slash = first_word.rfind('/');
+        if (last_slash != std::string::npos) {
+            first_word = first_word.substr(last_slash + 1);
+        }
+
+        bool allowed = false;
+        for (const auto& cmd : allowed_commands) {
+            if (first_word == cmd) {
+                allowed = true;
+                break;
+            }
+        }
+
+        if (!allowed) {
+            JSValue response = JS_NewObject(ctx);
+            JS_SetPropertyStr(ctx, response, "success", JS_FALSE);
+            JS_SetPropertyStr(ctx, response, "exitCode", JS_NewInt32(ctx, -1));
+            JS_SetPropertyStr(ctx, response, "stdout", JS_NewString(ctx, ""));
+            JS_SetPropertyStr(ctx, response, "stderr", JS_NewString(ctx, ("Command not allowed: " + first_word + ". Only image processing commands are permitted.").c_str()));
+            return response;
+        }
+
+        try {
+            // Build command with optional cwd
+            std::string full_command = command_str;
+            if (!cwd.empty()) {
+                full_command = "cd " + cwd + " && " + command_str;
+            }
+
+            // Redirect stderr to stdout for combined capture, but also capture separately
+            // Using pipes to capture stdout and stderr
+            std::array<int, 2> stdout_pipe;
+            std::array<int, 2> stderr_pipe;
+            std::array<int, 2> stdin_pipe;
+
+            if (pipe(stdout_pipe.data()) != 0 || pipe(stderr_pipe.data()) != 0) {
+                JSValue response = JS_NewObject(ctx);
+                JS_SetPropertyStr(ctx, response, "success", JS_FALSE);
+                JS_SetPropertyStr(ctx, response, "exitCode", JS_NewInt32(ctx, -1));
+                JS_SetPropertyStr(ctx, response, "stdout", JS_NewString(ctx, ""));
+                JS_SetPropertyStr(ctx, response, "stderr", JS_NewString(ctx, "Failed to create pipes"));
+                return response;
+            }
+
+            bool has_stdin = !stdin_data.empty();
+            if (has_stdin && pipe(stdin_pipe.data()) != 0) {
+                close(stdout_pipe[0]);
+                close(stdout_pipe[1]);
+                close(stderr_pipe[0]);
+                close(stderr_pipe[1]);
+                JSValue response = JS_NewObject(ctx);
+                JS_SetPropertyStr(ctx, response, "success", JS_FALSE);
+                JS_SetPropertyStr(ctx, response, "exitCode", JS_NewInt32(ctx, -1));
+                JS_SetPropertyStr(ctx, response, "stdout", JS_NewString(ctx, ""));
+                JS_SetPropertyStr(ctx, response, "stderr", JS_NewString(ctx, "Failed to create stdin pipe"));
+                return response;
+            }
+
+            pid_t pid = fork();
+            if (pid == -1) {
+                close(stdout_pipe[0]);
+                close(stdout_pipe[1]);
+                close(stderr_pipe[0]);
+                close(stderr_pipe[1]);
+                if (has_stdin) {
+                    close(stdin_pipe[0]);
+                    close(stdin_pipe[1]);
+                }
+                JSValue response = JS_NewObject(ctx);
+                JS_SetPropertyStr(ctx, response, "success", JS_FALSE);
+                JS_SetPropertyStr(ctx, response, "exitCode", JS_NewInt32(ctx, -1));
+                JS_SetPropertyStr(ctx, response, "stdout", JS_NewString(ctx, ""));
+                JS_SetPropertyStr(ctx, response, "stderr", JS_NewString(ctx, "Failed to fork process"));
+                return response;
+            }
+
+            if (pid == 0) {
+                // Child process
+                close(stdout_pipe[0]);
+                close(stderr_pipe[0]);
+                dup2(stdout_pipe[1], STDOUT_FILENO);
+                dup2(stderr_pipe[1], STDERR_FILENO);
+                close(stdout_pipe[1]);
+                close(stderr_pipe[1]);
+
+                if (has_stdin) {
+                    close(stdin_pipe[1]);
+                    dup2(stdin_pipe[0], STDIN_FILENO);
+                    close(stdin_pipe[0]);
+                }
+
+                execl("/bin/sh", "sh", "-c", full_command.c_str(), nullptr);
+                _exit(127);
+            }
+
+            // Parent process
+            close(stdout_pipe[1]);
+            close(stderr_pipe[1]);
+
+            if (has_stdin) {
+                close(stdin_pipe[0]);
+                write(stdin_pipe[1], stdin_data.c_str(), stdin_data.size());
+                close(stdin_pipe[1]);
+            }
+
+            // Set non-blocking and read with timeout
+            std::string stdout_result;
+            std::string stderr_result;
+
+            auto start_time = std::chrono::steady_clock::now();
+
+            // Read from pipes
+            fd_set read_fds;
+            int max_fd = std::max(stdout_pipe[0], stderr_pipe[0]) + 1;
+            char buffer[4096];
+
+            bool stdout_done = false;
+            bool stderr_done = false;
+
+            while (!stdout_done || !stderr_done) {
+                auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
+                    std::chrono::steady_clock::now() - start_time).count();
+
+                if (elapsed >= timeout_ms) {
+                    kill(pid, SIGKILL);
+                    break;
+                }
+
+                FD_ZERO(&read_fds);
+                if (!stdout_done) FD_SET(stdout_pipe[0], &read_fds);
+                if (!stderr_done) FD_SET(stderr_pipe[0], &read_fds);
+
+                struct timeval tv;
+                int remaining_ms = timeout_ms - static_cast<int>(elapsed);
+                tv.tv_sec = remaining_ms / 1000;
+                tv.tv_usec = (remaining_ms % 1000) * 1000;
+
+                int ready = select(max_fd, &read_fds, nullptr, nullptr, &tv);
+                if (ready <= 0) break;
+
+                if (!stdout_done && FD_ISSET(stdout_pipe[0], &read_fds)) {
+                    ssize_t n = read(stdout_pipe[0], buffer, sizeof(buffer));
+                    if (n > 0) {
+                        stdout_result.append(buffer, n);
+                    } else {
+                        stdout_done = true;
+                    }
+                }
+
+                if (!stderr_done && FD_ISSET(stderr_pipe[0], &read_fds)) {
+                    ssize_t n = read(stderr_pipe[0], buffer, sizeof(buffer));
+                    if (n > 0) {
+                        stderr_result.append(buffer, n);
+                    } else {
+                        stderr_done = true;
+                    }
+                }
+            }
+
+            close(stdout_pipe[0]);
+            close(stderr_pipe[0]);
+
+            // Wait for child process
+            int status;
+            waitpid(pid, &status, 0);
+
+            int exit_code = WIFEXITED(status) ? WEXITSTATUS(status) : -1;
+
+            JSValue response = JS_NewObject(ctx);
+            JS_SetPropertyStr(ctx, response, "success", exit_code == 0 ? JS_TRUE : JS_FALSE);
+            JS_SetPropertyStr(ctx, response, "exitCode", JS_NewInt32(ctx, exit_code));
+            JS_SetPropertyStr(ctx, response, "stdout", JS_NewString(ctx, stdout_result.c_str()));
+            JS_SetPropertyStr(ctx, response, "stderr", JS_NewString(ctx, stderr_result.c_str()));
+            return response;
+        } catch (const std::exception& e) {
+            JSValue response = JS_NewObject(ctx);
+            JS_SetPropertyStr(ctx, response, "success", JS_FALSE);
+            JS_SetPropertyStr(ctx, response, "exitCode", JS_NewInt32(ctx, -1));
+            JS_SetPropertyStr(ctx, response, "stdout", JS_NewString(ctx, ""));
+            JS_SetPropertyStr(ctx, response, "stderr", JS_NewString(ctx, e.what()));
+            return response;
+        }
+    }, "exec", 2));
+
+    JS_SetPropertyStr(ctx, smartbotic, "process", process);
+
     JS_SetPropertyStr(ctx, global, "smartbotic", smartbotic);
 
     // Console for compatibility