Skip to content

Self-improving AI Employees for everyone

Add Temporal worker to launch scripts, fix runtime heartbeat warning

trohitg3d6fe93ff378
diff --git a/package.json b/package.json
index 963d25d9..6bfde232 100644
--- a/package.json
+++ b/package.json
@@ -8,6 +8,8 @@
],
"scripts": {
"dev": "concurrently --raw --kill-others-on-fail \"npm:client:dev\" \"npm:python:dev\" \"npm:whatsapp:api\"",
+ "dev:temporal": "concurrently --raw --kill-others-on-fail \"npm:client:dev\" \"npm:python:dev\" \"npm:whatsapp:api\" \"npm:temporal:worker\"",
+ "temporal:worker": "cd server && python -m services.temporal.worker",
"client:dev": "cd client && set NO_COLOR=1&& npm run dev",
"python:dev": "cd server && python -m uvicorn main:app --host 127.0.0.1 --port 3010 --reload --reload-dir . --reload-exclude \"*.pyc\" --reload-exclude \"__pycache__\" --log-level warning",
"whatsapp:start": "cd server/whatsapp-rpc && npm start",
diff --git a/scripts/docker.js b/scripts/docker.js
index f2d37ce0..51993df1 100644
--- a/scripts/docker.js
+++ b/scripts/docker.js
@@ -18,18 +18,11 @@ function ensureEnvFile() {
const envPath = resolve(ROOT, '.env');
if (existsSync(envPath)) return true;
- // Try root .env.template first, then server/.env.template
- const templates = [
- resolve(ROOT, '.env.template'),
- resolve(ROOT, 'server', '.env.template')
- ];
-
- for (const templatePath of templates) {
- if (existsSync(templatePath)) {
- console.log(`[Docker] Creating .env from ${templatePath.replace(ROOT, '.')}`);
- copyFileSync(templatePath, envPath);
- return true;
- }
+ const templatePath = resolve(ROOT, '.env.template');
+ if (existsSync(templatePath)) {
+ console.log('[Docker] Creating .env from .env.template');
+ copyFileSync(templatePath, envPath);
+ return true;
}
console.warn('[Docker] Warning: No .env or .env.template found');
diff --git a/scripts/start.js b/scripts/start.js
index acaa7656..b38b9d23 100644
--- a/scripts/start.js
+++ b/scripts/start.js
@@ -17,23 +17,32 @@ const isMac = process.platform === 'darwin';
const elapsed = () => `${((Date.now() - START) / 1000).toFixed(2)}s`;
const log = (msg) => console.log(`[${elapsed()}] ${msg}`);
-// Load ports from .env
-function loadPorts() {
+// Load env config
+function loadEnvConfig() {
const envPath = existsSync(resolve(ROOT, '.env')) ? resolve(ROOT, '.env') : resolve(ROOT, '.env.template');
- if (!existsSync(envPath)) return [3000, 3010, 9400];
- const content = readFileSync(envPath, 'utf-8');
const env = {};
- for (const line of content.split('\n')) {
- const match = line.match(/^([^#=]+)=(.*)$/);
- if (match) {
- env[match[1].trim()] = match[2].trim();
+ if (existsSync(envPath)) {
+ const content = readFileSync(envPath, 'utf-8');
+ for (const line of content.split('\n')) {
+ const match = line.match(/^([^#=]+)=(.*)$/);
+ if (match) {
+ env[match[1].trim()] = match[2].trim();
+ }
}
}
- return [
- parseInt(env.VITE_CLIENT_PORT) || 3000,
- parseInt(env.PYTHON_BACKEND_PORT) || 3010,
- parseInt(env.WHATSAPP_RPC_PORT) || 9400
- ];
+ return {
+ ports: [
+ parseInt(env.VITE_CLIENT_PORT) || 3000,
+ parseInt(env.PYTHON_BACKEND_PORT) || 3010,
+ parseInt(env.WHATSAPP_RPC_PORT) || 9400
+ ],
+ temporalEnabled: env.TEMPORAL_ENABLED?.toLowerCase() === 'true'
+ };
+}
+
+// Legacy function for backwards compatibility
+function loadPorts() {
+ return loadEnvConfig().ports;
}
// Execute command and return output (suppressing errors)
@@ -147,13 +156,15 @@ function killPort(port) {
return remainingPids.length === 0;
}
-const PORTS = loadPorts();
+const config = loadEnvConfig();
+const PORTS = config.ports;
process.env.PYTHONUTF8 = '1';
console.log('\n=== MachinaOS Starting ===\n');
const platformName = isWindows ? 'Windows' : isGitBash ? 'Git Bash' : isMac ? 'macOS' : 'Linux';
log(`Platform: ${platformName}`);
log(`Ports: ${PORTS.join(', ')}`);
+log(`Temporal: ${config.temporalEnabled ? 'enabled' : 'disabled'}`);
// Step 1: Create .env if not exists
const envPath = resolve(ROOT, '.env');
@@ -191,6 +202,9 @@ log('Starting services...');
log('Press Ctrl+C to stop (use npm run stop to kill all services)');
log('');
+// Build the dev command - conditionally include Temporal worker
+const devCommand = config.temporalEnabled ? 'npm run dev:temporal' : 'npm run dev';
+
// On Git Bash/mintty, Ctrl+C doesn't propagate properly to Node.js child processes
// due to Cygwin pseudo-terminal limitations. The workaround is to run concurrently
// directly without a Node.js wrapper.
@@ -204,7 +218,7 @@ if (isGitBash) {
const { execFileSync } = await import('child_process');
try {
// Use bash -c to run npm, replacing this process
- execFileSync('bash', ['-c', 'exec npm run dev'], {
+ execFileSync('bash', ['-c', `exec ${devCommand}`], {
cwd: ROOT,
stdio: 'inherit',
windowsHide: false
@@ -215,7 +229,7 @@ if (isGitBash) {
} else {
// For native Windows cmd or Unix: execSync works fine
try {
- execSync('npm run dev', { cwd: ROOT, stdio: 'inherit' });
+ execSync(devCommand, { cwd: ROOT, stdio: 'inherit' });
} catch {
// Ctrl+C causes non-zero exit, which is normal
}
diff --git a/scripts/stop.js b/scripts/stop.js
index 5701f585..040f683e 100644
--- a/scripts/stop.js
+++ b/scripts/stop.js
@@ -12,23 +12,32 @@ const isGitBash = process.platform === 'win32' && (process.env.MSYSTEM || proces
const isWindows = process.platform === 'win32' && !isGitBash;
const isMac = process.platform === 'darwin';
-// Load ports from .env
-function loadPorts() {
+// Load env config
+function loadEnvConfig() {
const envPath = existsSync(resolve(ROOT, '.env')) ? resolve(ROOT, '.env') : resolve(ROOT, '.env.template');
- if (!existsSync(envPath)) return [3000, 3010, 9400];
- const content = readFileSync(envPath, 'utf-8');
const env = {};
- for (const line of content.split('\n')) {
- const match = line.match(/^([^#=]+)=(.*)$/);
- if (match) {
- env[match[1].trim()] = match[2].trim();
+ if (existsSync(envPath)) {
+ const content = readFileSync(envPath, 'utf-8');
+ for (const line of content.split('\n')) {
+ const match = line.match(/^([^#=]+)=(.*)$/);
+ if (match) {
+ env[match[1].trim()] = match[2].trim();
+ }
}
}
- return [
- parseInt(env.VITE_CLIENT_PORT) || 3000,
- parseInt(env.PYTHON_BACKEND_PORT) || 3010,
- parseInt(env.WHATSAPP_RPC_PORT) || 9400
- ];
+ return {
+ ports: [
+ parseInt(env.VITE_CLIENT_PORT) || 3000,
+ parseInt(env.PYTHON_BACKEND_PORT) || 3010,
+ parseInt(env.WHATSAPP_RPC_PORT) || 9400
+ ],
+ temporalEnabled: env.TEMPORAL_ENABLED?.toLowerCase() === 'true'
+ };
+}
+
+// Legacy function for backwards compatibility
+function loadPorts() {
+ return loadEnvConfig().ports;
}
// Execute command and return output (suppressing errors)
@@ -252,13 +261,43 @@ function killPort(port) {
};
}
+// Kill Temporal worker processes by command line pattern
+function killTemporalWorkers() {
+ const killedPids = [];
+
+ if (isWindows) {
+ // Find Python processes running temporal worker
+ const wmicOutput = exec('wmic process where "CommandLine like \'%services.temporal.worker%\'" get ProcessId 2>nul');
+ for (const line of wmicOutput.split('\n')) {
+ const pid = line.trim();
+ if (pid && /^\d+$/.test(pid)) {
+ exec(`taskkill /PID ${pid} /F 2>nul`);
+ killedPids.push(pid);
+ }
+ }
+ } else {
+ // Unix: Use pgrep to find temporal worker processes
+ const pgrepOutput = exec('pgrep -f "services.temporal.worker" 2>/dev/null');
+ for (const pid of pgrepOutput.split('\n')) {
+ if (pid.trim() && /^\d+$/.test(pid.trim())) {
+ exec(`kill -9 ${pid.trim()} 2>/dev/null`);
+ killedPids.push(pid.trim());
+ }
+ }
+ }
+
+ return killedPids;
+}
+
// Main execution
-const PORTS = loadPorts();
+const config = loadEnvConfig();
+const PORTS = config.ports;
console.log('Stopping MachinaOs services...\n');
const platformName = isWindows ? 'Windows' : isGitBash ? 'Git Bash' : isMac ? 'macOS' : 'Linux';
console.log(`Platform: ${platformName}`);
-console.log(`Ports: ${PORTS.join(', ')}\n`);
+console.log(`Ports: ${PORTS.join(', ')}`);
+console.log(`Temporal: ${config.temporalEnabled ? 'enabled' : 'disabled'}\n`);
let allStopped = true;
@@ -274,6 +313,17 @@ for (const port of PORTS) {
}
}
+// Kill Temporal workers if enabled
+if (config.temporalEnabled) {
+ const temporalPids = killTemporalWorkers();
+ if (temporalPids.length > 0) {
+ console.log(`[OK] Temporal worker: Killed ${temporalPids.length} process(es)`);
+ console.log(` PIDs: ${temporalPids.join(', ')}`);
+ } else {
+ console.log(`[OK] Temporal worker: Not running`);
+ }
+}
+
console.log('');
if (allStopped) {
console.log('All services stopped successfully.');
diff --git a/server/.env.example b/server/.env.example
deleted file mode 100644
index 90181017..00000000
--- a/server/.env.example
+++ /dev/null
@@ -1,62 +0,0 @@
-# Server Configuration
-HOST=0.0.0.0
-PORT=3010
-DEBUG=false
-WORKERS=1
-
-# Security (REQUIRED - Generate secure keys for production)
-SECRET_KEY=your-secret-key-32-characters-minimum-length
-API_KEY_ENCRYPTION_KEY=your-encryption-key-32-characters-minimum
-
-# CORS Configuration
-CORS_ORIGINS=http://localhost:3000,http://127.0.0.1:3000
-
-# Database Configuration
-DATABASE_URL=sqlite+aiosqlite:///./data/workflow.db
-DATABASE_ECHO=false
-DATABASE_POOL_SIZE=20
-DATABASE_MAX_OVERFLOW=30
-
-# Cache Configuration (Optional - Redis for production)
-REDIS_URL=redis://localhost:6379/0
-REDIS_ENABLED=false
-CACHE_TTL=3600
-
-# WebSocket Configuration (For remote Android device connections)
-WEBSOCKET_URL=
-WEBSOCKET_API_KEY=
-ANDROID_RELAY_URL=
-
-# WhatsApp Service URL
-WHATSAPP_SERVICE_URL=http://localhost:5000
-
-# External API Keys (Optional - Set only if you have them)
-# These are user-managed through the UI, but you can set defaults here
-# GOOGLE_MAPS_API_KEY=your-google-maps-api-key
-# OPENAI_API_KEY=your-openai-api-key
-# ANTHROPIC_API_KEY=your-anthropic-api-key
-# GOOGLE_AI_API_KEY=your-google-ai-api-key
-
-# API Key Management
-API_KEY_CACHE_TTL=2592000
-
-# Logging
-LOG_LEVEL=INFO
-LOG_FORMAT=json
-# LOG_FILE=./logs/app.log
-
-# Rate Limiting
-RATE_LIMIT_ENABLED=true
-RATE_LIMIT_REQUESTS=100
-RATE_LIMIT_WINDOW=60
-
-# Service Timeouts
-AI_TIMEOUT=30
-AI_MAX_RETRIES=3
-AI_RETRY_DELAY=1.0
-
-MAPS_TIMEOUT=10
-MAPS_MAX_RPS=50
-
-# Health Check
-HEALTH_CHECK_INTERVAL=30
\ No newline at end of file
diff --git a/server/.env.template b/server/.env.template
deleted file mode 100644
index 4967624c..00000000
--- a/server/.env.template
+++ /dev/null
@@ -1,78 +0,0 @@
-# Server Configuration
-HOST=127.0.0.1
-PORT=3010
-DEBUG=true
-WORKERS=1
-
-# Service Ports (used by start.js and vite)
-VITE_CLIENT_PORT=3000
-PYTHON_BACKEND_PORT=3010
-WHATSAPP_RPC_PORT=9400
-
-# Security (Development keys - MUST CHANGE FOR PRODUCTION)
-SECRET_KEY=dev-secret-key-12345678901234567890123456789012
-API_KEY_ENCRYPTION_KEY=dev-encryption-key-12345678901234567890123456
-
-# Authentication
-# AUTH_MODE: "single" (local deploy - first user is owner) or "multi" (cloud - open registration)
-AUTH_MODE=single
-JWT_SECRET_KEY=dev-jwt-secret-key-12345678901234567890
-JWT_EXPIRE_MINUTES=10080
-JWT_COOKIE_NAME=machina_token
-JWT_COOKIE_SECURE=false
-JWT_COOKIE_SAMESITE=lax
-
-# CORS Configuration - Allow all common dev ports
-CORS_ORIGINS=["http://localhost:3000","http://localhost:3001","http://localhost:3002","http://localhost:3003","http://localhost:3004","http://localhost:3005","http://localhost:3006","http://127.0.0.1:3000","http://127.0.0.1:3001","http://127.0.0.1:3002","http://127.0.0.1:3003","http://127.0.0.1:3004","http://127.0.0.1:3005","http://127.0.0.1:3006","http://localhost:5173"]
-
-# Database Configuration
-DATABASE_URL=sqlite+aiosqlite:///./data/workflow.db
-DATABASE_ECHO=false
-DATABASE_POOL_SIZE=5
-DATABASE_MAX_OVERFLOW=10
-
-# Cache Configuration (Disabled for development)
-REDIS_ENABLED=false
-CACHE_TTL=300
-
-# Temporal Configuration (Disabled by default)
-# Enable for durable workflow execution with automatic retries
-TEMPORAL_ENABLED=false
-TEMPORAL_SERVER_ADDRESS=localhost:7233
-TEMPORAL_NAMESPACE=default
-TEMPORAL_TASK_QUEUE=machina-tasks
-
-# Logging
-LOG_LEVEL=DEBUG
-LOG_FORMAT=text
-
-# Rate Limiting (Relaxed for development)
-RATE_LIMIT_ENABLED=false
-RATE_LIMIT_REQUESTS=1000
-RATE_LIMIT_WINDOW=60
-
-# Service Timeouts (Extended for debugging)
-AI_TIMEOUT=60
-AI_MAX_RETRIES=1
-AI_RETRY_DELAY=0.5
-
-MAPS_TIMEOUT=30
-
-# Health Check
-HEALTH_CHECK_INTERVAL=60
-
-# WebSocket Configuration (For remote Android device connections)
-# Set your Android relay server URL and API key
-WEBSOCKET_URL=
-WEBSOCKET_API_KEY=
-ANDROID_RELAY_URL=
-
-# WhatsApp Service URL
-WHATSAPP_SERVICE_URL=http://localhost:5000
-
-# External API Keys
-# Set these to your actual API keys (managed through UI, these are optional defaults)
-OPENAI_API_KEY=
-GOOGLE_MAPS_API_KEY=
-ANTHROPIC_API_KEY=
-GOOGLE_AI_API_KEY=
diff --git a/server/services/temporal/client.py b/server/services/temporal/client.py
index 084263af..d9b55d67 100644
--- a/server/services/temporal/client.py
+++ b/server/services/temporal/client.py
@@ -5,6 +5,7 @@ Manages the Temporal client connection lifecycle.
from typing import Optional
from temporalio.client import Client
+from temporalio.runtime import Runtime, TelemetryConfig
from core.logging import get_logger
@@ -24,6 +25,7 @@ class TemporalClientWrapper:
self.server_address = server_address
self.namespace = namespace
self._client: Optional[Client] = None
+ self._runtime: Optional[Runtime] = None
@property
def client(self) -> Optional[Client]:
@@ -50,9 +52,16 @@ class TemporalClientWrapper:
namespace=self.namespace,
)
+ # Create runtime with worker heartbeating disabled to avoid warning on older servers
+ self._runtime = Runtime(
+ telemetry=TelemetryConfig(),
+ worker_heartbeat_interval=None,
+ )
+
self._client = await Client.connect(
self.server_address,
namespace=self.namespace,
+ runtime=self._runtime,
)
logger.info("Connected to Temporal server")
diff --git a/server/services/temporal/worker.py b/server/services/temporal/worker.py
index 2958c38c..7e3102f0 100644
--- a/server/services/temporal/worker.py
+++ b/server/services/temporal/worker.py
@@ -20,6 +20,7 @@ from typing import Optional
import aiohttp
from temporalio.client import Client
+from temporalio.runtime import Runtime, TelemetryConfig
from temporalio.worker import Worker
from core.logging import get_logger
@@ -34,6 +35,18 @@ from .activities import (
logger = get_logger(__name__)
+def create_runtime() -> Runtime:
+ """Create a Temporal runtime with worker heartbeating disabled.
+
+ Disables the runtime-level worker heartbeating feature to avoid
+ the warning on older Temporal server versions that don't support it.
+ """
+ return Runtime(
+ telemetry=TelemetryConfig(),
+ worker_heartbeat_interval=None, # Disable runtime heartbeating
+ )
+
+
class TemporalWorkerManager:
"""Manages the Temporal worker lifecycle with shared resources.
@@ -173,7 +186,9 @@ async def run_standalone_worker(
print(f"[Worker] Task Queue: {task_queue}")
print(f"[Worker] Pool Size: {pool_size}")
- client = await Client.connect(server_address, namespace=namespace)
+ # Use custom runtime with heartbeating disabled to avoid warning on older servers
+ runtime = create_runtime()
+ client = await Client.connect(server_address, namespace=namespace, runtime=runtime)
# Create shared session and activities
session = await create_shared_session(pool_size)