Skip to content

Self-improving AI Employees for everyone

fix: prevent taskTrigger from blocking Temporal workflow execution

trohitg96cf88037f35
diff --git a/CLAUDE.md b/CLAUDE.md
index 738d45b6..a6991a50 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -29,6 +29,8 @@ This is a React Flow-based workflow automation platform implementing n8n-inspire
| **[Skill Creation Guide](./server/skills/GUIDE.md)** | How to create new skills (folder structure, SKILL.md format, metadata, supporting files) |
| **[New Service Integration](./docs-internal/new_service_integration.md)** | Complete guide for integrating external services (OAuth, database, handlers, nodes, AI tools) - use Google Workspace as reference |
| **[Onboarding Service](./docs-internal/onboarding.md)** | First-launch welcome wizard with 5 steps, database persistence, and replay from Settings |
+| **[CLI Services Integration](./docs-internal/cli_services_integration.md)** | Guide for integrating CLI-based services (Temporal, etc.) with proper lifecycle management |
+| **[Temporal Architecture](./docs-internal/TEMPORAL_ARCHITECTURE.md)** | Distributed workflow execution: activities, FIRST_COMPLETED scheduling, horizontal scaling |
| **[Polyglot Server](../polyglot-server/ARCHITECTURE.md)** | Plugin registry microservice with MCP gateway (optional integration) |
## Design Principles & Standards
@@ -1306,9 +1308,9 @@ client/src/nodeDefinitions/
**Result**: Frontend and backend run independently, uvicorn reloads don't cascade
-### Temporal Distributed Execution (Optional)
+### Temporal Distributed Execution
-When `TEMPORAL_ENABLED=true`, workflows execute via Temporal for durability and horizontal scaling.
+Workflows execute via Temporal for durability and horizontal scaling. Temporal is an always-on service (like WhatsApp) started unconditionally by `npm run start` and `npm run dev`.
**Architecture**: Each workflow node executes as an independent Temporal activity:
- **Per-node retry** - Failed nodes retry independently (up to 3 attempts)
@@ -1318,33 +1320,55 @@ When `TEMPORAL_ENABLED=true`, workflows execute via Temporal for durability and
**Configuration** (`.env`):
```env
-TEMPORAL_ENABLED=true
TEMPORAL_SERVER_ADDRESS=localhost:7233
TEMPORAL_NAMESPACE=default
TEMPORAL_TASK_QUEUE=machina-tasks
```
-**Start Temporal Server**:
+**Temporal Server** (npm package `temporal-server` v0.0.6):
+The `temporal-server` npm package bundles the official Temporal CLI binary for local dev server with SQLite persistence.
+
+**Ports:**
+| Service | Port | URL |
+|-----------|------|------------------------|
+| gRPC | 7233 | localhost:7233 |
+| HTTP API | 8233 | http://localhost:8233 |
+| Web UI | 8080 | http://localhost:8080 |
+| Metrics | 9090 | http://localhost:9090 |
+
+**CLI commands** (globally installed `temporal-server`):
+```bash
+temporal-server start # Start in background (daemon mode)
+temporal-server api # Start in foreground (blocks)
+temporal-server stop # Stop server
+temporal-server status # Show status (all 4 ports)
+temporal-server restart # Restart server
+temporal-server clean # Stop + remove bin/, data/
+```
+
+**Global install** (required for CLI access from scripts):
```bash
-docker run -d --name temporal-sqlite \
- -p 7233:7233 -p 8233:8233 \
- -v "d:/startup/projects/temporal/data:/data" \
- temporalio/temporal:latest server start-dev \
- --ip 0.0.0.0 --db-filename /data/temporal.db
+npm install -g temporal-server
```
+**Start script integration** (`scripts/start.js`):
+The start script checks `temporal-server status` via CLI before building the concurrently service list. If Temporal is already running, it skips adding it to concurrently (prevents `--kill-others` cascade when `temporal-server api` exits immediately with "Already running"). If not running, adds `npm:temporal:start` (`temporal-server api` in foreground mode) to the service list.
+
+**Port management**: Temporal manages its own ports (7233, 8233, 8080, 9090). These ports are NOT included in MachinaOS `allPorts` and are NOT killed during port-freeing. Temporal lifecycle is managed exclusively through its own CLI (`temporal-server start/stop/status`).
+
**Execution Routing** (`workflow.py`):
1. If `TEMPORAL_ENABLED=true` and Temporal configured → `_execute_temporal()`
2. Else if Redis available → `_execute_parallel()` (local parallel)
3. Else → `_execute_sequential()` (fallback)
**Running with Temporal**:
-The launch scripts auto-detect `TEMPORAL_ENABLED` from `.env`:
+Temporal server and embedded worker start automatically with all launch scripts:
```bash
-npm run start # Auto-starts temporal worker if TEMPORAL_ENABLED=true
-npm run start:temporal # Explicit: sets TEMPORAL_ENABLED=true
-npm run stop # Also kills Temporal worker processes
+npm run start # Starts Temporal server + all services
+npm run dev # Starts Temporal server + all services (dev mode)
+npm run stop # Stops all services including Temporal
```
+The embedded Temporal worker runs inside the Python backend (`main.py` lifespan via `TemporalWorkerManager`), not as a separate process.
**Standalone Worker** (horizontal scaling):
```bash
@@ -1352,6 +1376,11 @@ cd server
python -m services.temporal.worker
```
+**Node Filtering** (`workflow.py`):
+- Config nodes filtered by handle: `CONFIG_HANDLES = {input-tools, input-memory, input-model, input-skill, input-task, input-teammates}`
+- Trigger nodes (`TRIGGER_NODE_TYPES`) auto-completed if not pre-executed (prevents blocking on event waiter)
+- Android service nodes and skill nodes filtered by type
+
**Key Files**:
- `services/temporal/workflow.py` - MachinaWorkflow orchestrator (FIRST_COMPLETED pattern)
- `services/temporal/activities.py` - Class-based activities with aiohttp pooling
@@ -1361,7 +1390,7 @@ python -m services.temporal.worker
**Runtime Configuration**: Worker heartbeating is disabled via `Runtime(worker_heartbeat_interval=None)` to avoid warnings on older Temporal server versions.
-**Temporal UI**: http://localhost:8233
+**Temporal UI**: http://localhost:8080 (Web UI), http://localhost:8233 (HTTP API)
## Development Commands
@@ -1378,8 +1407,7 @@ npx machina help # Show all commands
### npm Scripts
```bash
# Core
-npm run start # Start all services (client, backend, WhatsApp)
-npm run start:temporal # Start with Temporal worker
+npm run start # Start all services (client, backend, WhatsApp, Temporal)
npm run stop # Stop all services
npm run build # Build for production
npm run clean # Clean build artifacts
@@ -1700,7 +1728,7 @@ deploy_workflow() -> Sets up triggers, returns immediately
- **Execution Run**: Each trigger event spawns an independent, isolated run
- **Concurrent Runs**: Multiple runs execute simultaneously without interference
- **No Iteration Loop**: Purely event-driven, not polling or sequential iterations
-- **Pre-Executed Triggers**: Trigger nodes are marked complete before downstream execution
+- **Pre-Executed Triggers**: The firing trigger is marked complete before downstream execution. All other trigger nodes in the run are also marked `_pre_executed` with `{not_triggered: True}` to prevent them from blocking as event waiters
**Implementation Files:**
- `server/services/workflow.py`: Thin facade (~460 lines) delegating to specialized modules
@@ -3907,8 +3935,13 @@ Config handles follow the pattern `input-<type>` where type is NOT 'main':
- `input-memory` - Memory/context nodes
- `input-tools` - Tool nodes
- `input-model` - Model configuration nodes
+- `input-skill` - Skill nodes
+- `input-task` - Task completion trigger nodes
+- `input-teammates` - Team member agent nodes
- `input-main` - Main data flow (NOT a config handle)
+**Note**: Trigger nodes (e.g., `taskTrigger`) connecting via config handles are excluded from downstream inclusion in `_get_downstream_nodes()` to prevent them from blocking as event waiters.
+
### Config Node Detection
Nodes are identified as config nodes by their `group` array in the node definition:
```typescript
diff --git a/docs-internal/SCRIPTS.md b/docs-internal/SCRIPTS.md
index eeb78ee1..be55d245 100644
--- a/docs-internal/SCRIPTS.md
+++ b/docs-internal/SCRIPTS.md
@@ -43,7 +43,7 @@ Run with `npm run <script>` from the project root.
| Script | Command | Description |
|--------|---------|-------------|
| `start` | `node scripts/start.js` | Start all services concurrently |
-| `start:temporal` | `cross-env TEMPORAL_ENABLED=true node scripts/start.js` | Start with Temporal worker |
+| `start:temporal` | `cross-env TEMPORAL_ENABLED=true node scripts/start.js` | Start with Temporal enabled |
| `stop` | `node scripts/stop.js` | Stop all running services |
| `build` | `node scripts/build.js` | Build entire project |
| `clean` | `node scripts/clean.js` | Remove build artifacts |
@@ -59,7 +59,10 @@ Run with `npm run <script>` from the project root.
| `whatsapp:stop` | `cd server/whatsapp-rpc && npm stop` | Stop WhatsApp service |
| `whatsapp:status` | `cd server/whatsapp-rpc && npm run status` | Check WhatsApp status |
| `whatsapp:build` | `cd server/whatsapp-rpc && npm run build` | Build WhatsApp Go binary |
-| `temporal:worker` | `cd server && uv run python -m services.temporal.worker` | Start Temporal worker |
+| `temporal:start` | `temporal-server api` | Start Temporal server (foreground) |
+| `temporal:stop` | `temporal-server stop` | Stop Temporal server |
+| `temporal:status` | `temporal-server status` | Check Temporal server status |
+| `temporal:worker` | `cd server && uv run python -m services.temporal.worker` | Start standalone Temporal worker |
### Docker Scripts (Development)
@@ -98,14 +101,17 @@ Run with `npm run <script>` from the project root.
Cross-platform start script that runs all services concurrently.
**What it does:**
-1. Creates `.env` from `.env.template` if missing
-2. Installs client dependencies if `client/node_modules` doesn't exist
-3. Frees configured ports by killing existing processes
-4. Starts services via `concurrently`:
- - `npm:client:start` - React frontend (Vite dev server)
- - `npm:python:start` - Python backend (uvicorn with hot reload)
- - `npm:whatsapp:api` - WhatsApp API server
- - `npm:temporal:worker` - Temporal worker (if `TEMPORAL_ENABLED=true`)
+1. Validates build artifacts exist
+2. Creates `.env` from `.env.template` if missing
+3. Checks if Temporal is already running via `temporal-server status` CLI
+4. Frees configured app ports (client, backend, WhatsApp, Node.js executor)
+5. Starts services via `concurrently` with `--kill-others`:
+ - Static client server (`serve-client.js`)
+ - Python backend (uvicorn)
+ - WhatsApp API server (unless `--skip-whatsapp`)
+ - Temporal server via `npm:temporal:start` (unless already running)
+
+**Temporal handling:** If `temporal-server status` reports the server is already running, Temporal is skipped in the concurrently service list. This prevents `temporal-server api` from exiting immediately with "Already running", which would trigger `--kill-others` and cascade-kill all services.
**Ports (configurable in .env):**
- `VITE_CLIENT_PORT` - Frontend (default: 3000)
@@ -148,7 +154,7 @@ Cross-platform stop script that kills all MachinaOS processes.
3. Kills processes including child processes
4. Verifies processes are stopped
5. Retries stubborn processes with force kill
-6. Kills Temporal workers if enabled
+6. Kills Temporal processes via `killByPattern('temporal')`
**Platform-specific commands:**
| Platform | Find processes | Kill process |
diff --git a/docs-internal/SETUP.md b/docs-internal/SETUP.md
index 1f38a655..034c7aa4 100644
--- a/docs-internal/SETUP.md
+++ b/docs-internal/SETUP.md
@@ -78,6 +78,14 @@ Services will be available at:
- Message send/receive via JSON-RPC
- Port configurable via `--port` flag, `PORT` or `WHATSAPP_RPC_PORT` env vars
+### Temporal Server (Distributed Execution)
+- Provides durable workflow execution with per-node retry and horizontal scaling
+- Installed globally: `npm install -g temporal-server`
+- Managed via CLI: `temporal-server start/stop/status`
+- Ports: gRPC 7233, HTTP API 8233, Web UI 8080, Metrics 9090
+- Embedded worker runs inside Python backend (`TemporalWorkerManager` in `main.py`)
+- See [Temporal Architecture](./TEMPORAL_ARCHITECTURE.md) and [CLI Services Guide](./cli_services_integration.md)
+
### Database (SQLite)
- **workflows** - Workflow definitions
- **node_parameters** - Node parameter storage
diff --git a/docs-internal/TEMPORAL_ARCHITECTURE.md b/docs-internal/TEMPORAL_ARCHITECTURE.md
index 6cf6d6ce..c9d49207 100644
--- a/docs-internal/TEMPORAL_ARCHITECTURE.md
+++ b/docs-internal/TEMPORAL_ARCHITECTURE.md
@@ -118,6 +118,13 @@ while True:
ready = self._find_ready_nodes(deps, completed, running, node_map)
for node_id in ready:
+ node_type = node_map[node_id].get("type", "unknown")
+
+ # Safety: auto-complete trigger nodes that weren't pre-executed
+ if node_type in TRIGGER_NODE_TYPES and not node.get("_pre_executed"):
+ completed.add(node_id)
+ continue
+
handle = workflow.start_activity(
"execute_node_activity",
args=[context],
@@ -230,7 +237,14 @@ Certain nodes provide configuration rather than executing:
```python
# Config handles - nodes connecting via these are filtered out
-CONFIG_HANDLES = {"input-tools", "input-memory", "input-model"}
+CONFIG_HANDLES = {"input-tools", "input-memory", "input-model", "input-skill", "input-task", "input-teammates"}
+
+# Trigger node types - event listeners, never scheduled as blocking activities
+TRIGGER_NODE_TYPES = frozenset([
+ "start", "cronScheduler", "webhookTrigger", "whatsappReceive",
+ "workflowTrigger", "chatTrigger", "taskTrigger",
+ "twitterReceive", "gmailReceive", "telegramReceive",
+])
# Android service types (connect to androidTool)
ANDROID_SERVICE_TYPES = {
@@ -244,6 +258,11 @@ Config nodes are:
- Their configuration is passed to target nodes via node_data
- Not scheduled as activities
+Trigger nodes that aren't the firing trigger are:
+- Auto-completed with `{not_triggered: True}` output
+- Never scheduled as blocking activities (would wait indefinitely for events)
+- Marked `_pre_executed` in deployment runs by `_execute_from_trigger()`
+
## Retry & Fault Tolerance
| Scenario | Behavior |
@@ -313,6 +332,23 @@ runtime = Runtime(
client = await Client.connect(server_address, namespace=namespace, runtime=runtime)
```
+## Server Management
+
+`temporal-server` is installed globally (`npm install -g temporal-server`) and managed via CLI:
+
+```bash
+temporal-server start # Start in background (daemon)
+temporal-server stop # Stop server
+temporal-server status # Show status (all 4 ports)
+temporal-server api # Start in foreground (blocks)
+temporal-server restart # Restart server
+temporal-server clean # Stop + remove bin/, data/
+```
+
+**Port management**: Temporal owns its ports (7233, 8233, 8080, 9090). They are NOT in MachinaOS `allPorts` and NOT killed during port-freeing. Use `temporal-server stop` to stop Temporal.
+
+**Start script integration**: `scripts/start.js` checks `temporal-server status` before building the concurrently service list. If already running, skips adding Temporal (prevents `--kill-others` cascade kill). `scripts/dev.js` always includes Temporal (no `--kill-others`, so early exit is harmless).
+
## Debugging
```bash
@@ -325,6 +361,9 @@ curl "http://localhost:8233/api/v1/namespaces/default/workflows"
# Get workflow history
curl "http://localhost:8233/api/v1/namespaces/default/workflows/{id}/history"
-# Temporal UI
+# Temporal Web UI
+open http://localhost:8080
+
+# Temporal HTTP API
open http://localhost:8233
```
diff --git a/docs-internal/cli_services_integration.md b/docs-internal/cli_services_integration.md
new file mode 100644
index 00000000..bec3d9ad
--- /dev/null
+++ b/docs-internal/cli_services_integration.md
@@ -0,0 +1,164 @@
+# CLI-Based Services Integration Guide
+
+MachinaOS integrates external services that manage their own lifecycle via CLI tools. These services own their ports, data directories, and processes -- MachinaOS does not manage them directly.
+
+## Principles
+
+1. **Install globally** -- CLI tools must be available system-wide (`npm install -g <package>`)
+2. **Use the CLI** -- Check status, start, stop via the package's own commands. No port-sniffing, no TCP socket checks, no hardcoded port detection.
+3. **Don't manage their ports** -- External service ports are NOT added to `allPorts` in `utils.js`. MachinaOS only kills ports it owns (client, backend, WhatsApp, Node.js executor).
+4. **Handle "already running"** -- Before adding a service to `concurrently`, check if it's already up. If it is, skip it. This prevents `--kill-others` cascade kills in `start.js`.
+5. **Keep dependencies in package.json** -- Even if installed globally, keep the package in `dependencies` so npm scripts (`npm run temporal:start`) work.
+
+## Integrated CLI Services
+
+### Temporal Server (`temporal-server`)
+
+Bundles the official Temporal CLI binary with SQLite persistence for local development.
+
+**Install:**
+```bash
+npm install -g temporal-server
+```
+
+**CLI:**
+```bash
+temporal-server start # Daemon (background)
+temporal-server api # Foreground (blocks)
+temporal-server stop # Stop
+temporal-server status # Show status
+temporal-server restart # Restart
+temporal-server clean # Stop + remove data
+```
+
+**Ports (managed by temporal-server, NOT by MachinaOS):**
+| Service | Port |
+|----------|------|
+| gRPC | 7233 |
+| HTTP API | 8233 |
+| Web UI | 8080 |
+| Metrics | 9090 |
+
+**npm scripts:**
+```json
+{
+ "temporal:start": "temporal-server api",
+ "temporal:stop": "temporal-server stop",
+ "temporal:status": "temporal-server status"
+}
+```
+
+**Integration in start.js:**
+```javascript
+// Check CLI status before building service list
+let temporalRunning = false;
+try {
+ const status = execSync('temporal-server status', {
+ encoding: 'utf-8', timeout: 5000, stdio: 'pipe'
+ });
+ temporalRunning = /running|UP/i.test(status);
+} catch {
+ temporalRunning = false;
+}
+
+// Only add to concurrently if NOT already running
+if (!temporalRunning) services.push('npm:temporal:start');
+```
+
+**Integration in dev.js:**
+No status check needed -- `dev.js` does not use `--kill-others`, so `temporal-server api` exiting early (because it's already running) is harmless.
+
+**Integration in stop.js:**
+```javascript
+// Kill temporal processes by name pattern (not by port)
+const temporalPids = await killByPattern('temporal');
+```
+
+**Embedded worker:**
+The Temporal worker runs inside the Python backend via `TemporalWorkerManager` in `main.py` lifespan. No separate worker process needed for single-server deployments. For horizontal scaling, run standalone workers:
+```bash
+cd server && python -m services.temporal.worker
+```
+
+---
+
+## Adding a New CLI Service
+
+Follow this pattern when integrating a new external CLI service:
+
+### 1. Install globally and add to dependencies
+
+```bash
+npm install -g <service-package>
+npm install <service-package>
+```
+
+### 2. Add npm scripts in package.json
+
+```json
+{
+ "<service>:start": "<service-cli> start",
+ "<service>:stop": "<service-cli> stop",
+ "<service>:status": "<service-cli> status"
+}
+```
+
+### 3. Integrate in start.js (with --kill-others protection)
+
+```javascript
+let serviceRunning = false;
+try {
+ const status = execSync('<service-cli> status', {
+ encoding: 'utf-8', timeout: 5000, stdio: 'pipe'
+ });
+ serviceRunning = /running|UP/i.test(status);
+} catch {
+ serviceRunning = false;
+}
+
+if (serviceRunning) {
+ log('<Service> already running, skipping');
+}
+
+// Add to services list only if not running
+if (!serviceRunning) services.push('npm:<service>:start');
+
+// Add ready-detection pattern only if not running
+if (!serviceRunning) {
+ readyPatterns.push({
+ name: '<Service>',
+ pattern: /<service>.*started|<service>.*ready/i
+ });
+}
+```
+
+### 4. Integrate in stop.js
+
+```javascript
+// Kill by process name pattern -- NOT by port
+const pids = await killByPattern('<service>');
+if (pids.length > 0) {
+ console.log(`Killed ${pids.length} <service> processes`);
+}
+```
+
+### 5. Do NOT add ports to allPorts
+
+The service manages its own ports. Do not add them to `loadEnvConfig().allPorts` in `utils.js`.
+
+### 6. dev.js -- usually no special handling needed
+
+`dev.js` does not use `--kill-others`, so services exiting early is harmless. Just add `npm:<service>:start` to the services list unconditionally.
+
+---
+
+## Common Mistakes to Avoid
+
+| Mistake | Why it's wrong | Correct approach |
+|---------|---------------|-----------------|
+| TCP socket check (`net.connect(port)`) | Fragile, races with other services, hardcodes ports | Use `<service-cli> status` |
+| Adding service ports to `allPorts` | `killPort()` would kill the service during startup | Service manages its own ports |
+| Resolving `node_modules/.bin/<cli>` path | Breaks if not in PATH, tribal workaround | Install globally |
+| Using `npx <service-cli>` in `execSync` | Slow, may use wrong version, npx overhead | Install globally, call directly |
+| Wrapping CLI in a JS script | Unnecessary indirection | Use CLI commands directly |
+| Hardcoding port numbers for detection | Breaks if service config changes | Use CLI status command |
diff --git a/docs-internal/node_creation.md b/docs-internal/node_creation.md
index 5ed6febb..f8127840 100644
--- a/docs-internal/node_creation.md
+++ b/docs-internal/node_creation.md
@@ -877,6 +877,12 @@ def build_my_filter(params: Dict) -> Callable[[Dict], bool]:
FILTER_BUILDERS['myTrigger'] = build_my_filter
```
+### Temporal/Deployment Safety
+
+Trigger nodes connecting via config handles (e.g., `input-task`) are excluded from downstream inclusion in `_get_downstream_nodes()` (`server/services/deployment/manager.py`). Non-firing trigger nodes in a deployment run are automatically marked `_pre_executed` with `{not_triggered: True}` to prevent them from blocking as event waiters.
+
+The Temporal workflow (`server/services/temporal/workflow.py`) has a safety net: any trigger node reaching the scheduling loop without `_pre_executed` is auto-completed instead of being scheduled as a blocking activity. The trigger type set `TRIGGER_NODE_TYPES` in `workflow.py` must be kept in sync with `WORKFLOW_TRIGGER_TYPES` in `constants.py`.
+
### Dispatch Events
From your event source (webhook, WebSocket, etc.):
diff --git a/package-lock.json b/package-lock.json
index 668d0a70..79d35259 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -16,7 +16,7 @@
"concurrently": "^9.2.1",
"cross-env": "^7.0.3",
"rimraf": "^6.0.1",
- "temporal-server": "^0.0.4",
+ "temporal-server": "^0.0.6",
"whatsapp-rpc": "^0.0.12"
},
"bin": {
@@ -11625,9 +11625,9 @@
}
},
"node_modules/temporal-server": {
- "version": "0.0.4",
- "resolved": "https://registry.npmjs.org/temporal-server/-/temporal-server-0.0.4.tgz",
- "integrity": "sha512-rWmV3RfHJdsBq6rrIxnSv8Gbw/JSK9/9VGRqqFTqceDYsZEE8NQKOLKTjG8+edbj1cTKdibzpbB5M6gPbVZS6Q==",
+ "version": "0.0.6",
+ "resolved": "https://registry.npmjs.org/temporal-server/-/temporal-server-0.0.6.tgz",
+ "integrity": "sha512-pk5TR8BQ3kpTJO6LvoI2ryfr89SVlNn6zvM/cY8lBe6pNnVT4gKOq01o7u0nheRaBidY7CsxetjQmUCK8gisfQ==",
"hasInstallScript": true,
"license": "MIT",
"dependencies": {
diff --git a/package.json b/package.json
index 8cc44102..3248681c 100644
--- a/package.json
+++ b/package.json
@@ -66,7 +66,7 @@
"client:start": "cd client && npm run start",
"python:start": "cd server && uv run uvicorn main:app --host 127.0.0.1 --port 3010 --log-level warning",
"python:daemon": "cd server && uv run uvicorn main:app --host 0.0.0.0 --port 3010 --log-level warning",
- "temporal:start": "node -e \"require('fs').mkdirSync(require('path').join(require('path').dirname(require.resolve('temporal-server/package.json')),'data'),{recursive:true})\" && temporal-server start --foreground",
+ "temporal:start": "temporal-server api",
"temporal:stop": "temporal-server stop",
"temporal:status": "temporal-server status",
"temporal:worker": "cd server && uv run python -m services.temporal.worker",
@@ -105,7 +105,7 @@
"concurrently": "^9.2.1",
"cross-env": "^7.0.3",
"rimraf": "^6.0.1",
- "temporal-server": "^0.0.4",
+ "temporal-server": "^0.0.6",
"whatsapp-rpc": "^0.0.12"
}
}
diff --git a/scripts/dev.js b/scripts/dev.js
index 256ab8f0..00b60efd 100644
--- a/scripts/dev.js
+++ b/scripts/dev.js
@@ -40,7 +40,7 @@ async function main() {
log(`Platform: ${getPlatformName()}`);
log(`Mode: ${isDaemonMode ? 'Daemon (uvicorn)' : 'Development (uvicorn)'}`);
log(`Ports: ${config.allPorts.join(', ')}`);
- log(`Temporal: ${config.temporalEnabled ? 'enabled' : 'disabled'}`);
+ log(`Temporal: enabled`);
log(`WhatsApp: ${skipWhatsApp ? 'skipped' : 'enabled'}`);
// Create .env if not exists
@@ -87,10 +87,8 @@ async function main() {
}
services.push(isDaemonMode ? 'npm:python:daemon' : 'npm:python:start');
if (!skipWhatsApp) services.push('npm:whatsapp:api');
- if (config.temporalEnabled) {
- services.push('npm:temporal:start');
- // Worker runs embedded in the backend (main.py TemporalWorkerManager)
- }
+ services.push('npm:temporal:start');
+ // Worker runs embedded in the backend (main.py TemporalWorkerManager)
// Ready-detection patterns for each service
const readyPatterns = [
@@ -100,6 +98,7 @@ async function main() {
if (!skipWhatsApp) {
readyPatterns.push({ name: 'WhatsApp', pattern: /listening on|WhatsApp.*ready|API.*started|:9400/i });
}
+ readyPatterns.push({ name: 'Temporal', pattern: /\[Temporal\] Worker started|temporal.*server.*started/i });
const readySet = new Set();
const totalExpected = readyPatterns.length;
diff --git a/scripts/start.js b/scripts/start.js
index 2f5c1af3..1670696a 100755
--- a/scripts/start.js
+++ b/scripts/start.js
@@ -4,7 +4,7 @@
* Clean output by default, --verbose for full logs.
* Usage: machina start [--verbose|-v] [--skip-whatsapp]
*/
-import { spawn } from 'child_process';
+import { spawn, execSync } from 'child_process';
import { existsSync, readFileSync } from 'fs';
import { resolve } from 'path';
import {
@@ -48,7 +48,22 @@ async function main() {
process.env.PYTHONUTF8 = '1';
ensureEnvFile();
- // Free ports
+ // Check if Temporal is already running via CLI
+ // (temporal-server api exits immediately if already up, which triggers
+ // --kill-others and kills all services)
+ let temporalRunning = false;
+ try {
+ const status = execSync('temporal-server status', { encoding: 'utf-8', timeout: 5000, stdio: 'pipe' });
+ temporalRunning = /running|UP/i.test(status);
+ } catch {
+ temporalRunning = false;
+ }
+
+ if (temporalRunning) {
+ log('Temporal already running, skipping');
+ }
+
+ // Free app ports
log('Freeing ports...');
for (const port of config.allPorts) {
await killPort(port);
@@ -60,10 +75,8 @@ async function main() {
services.push(`"node ${resolve(ROOT, 'scripts', 'serve-client.js').replace(/\\/g, '/')}"`);
services.push((isWindows || isWSL) ? 'npm:python:start' : 'npm:python:daemon');
if (!skipWhatsApp) services.push('npm:whatsapp:api');
- if (config.temporalEnabled) {
- services.push('npm:temporal:start');
- // Worker runs embedded in the backend (main.py TemporalWorkerManager)
- }
+ if (!temporalRunning) services.push('npm:temporal:start');
+ // Worker runs embedded in the backend (main.py TemporalWorkerManager)
// Ready-detection patterns for each service
const readyPatterns = [
@@ -73,6 +86,9 @@ async function main() {
if (!skipWhatsApp) {
readyPatterns.push({ name: 'WhatsApp', pattern: /listening on|WhatsApp.*ready|API.*started|:9400/i });
}
+ if (!temporalRunning) {
+ readyPatterns.push({ name: 'Temporal', pattern: /\[Temporal\] Worker started|temporal.*server.*started/i });
+ }
const readySet = new Set();
const totalExpected = readyPatterns.length;
@@ -116,9 +132,7 @@ async function main() {
const serviceNames = ['client', 'server'];
if (!skipWhatsApp) serviceNames.push('whatsapp');
- if (config.temporalEnabled) {
- serviceNames.push('temporal-server');
- }
+ if (!temporalRunning) serviceNames.push('temporal');
const proc = spawn('npx', [
'concurrently', '--kill-others',
@@ -133,7 +147,7 @@ async function main() {
});
// Show only essential output: errors, ready messages, warnings
- const essential = /error|fatal|exception|failed|started|ready|listening|running|address already in use|application startup complete/i;
+ const essential = /error|fatal|exception|failed|started|ready|listening|running|address already in use|application startup complete|\[Temporal\]/i;
proc.stdout.on('data', (data) => {
const text = data.toString();
diff --git a/scripts/stop.js b/scripts/stop.js
index 152b3f00..79da7b79 100755
--- a/scripts/stop.js
+++ b/scripts/stop.js
@@ -18,7 +18,7 @@ async function main() {
console.log('Stopping MachinaOS services...\n');
console.log(`Platform: ${getPlatformName()}`);
console.log(`Ports: ${config.allPorts.join(', ')}`);
- console.log(`Temporal: ${config.temporalEnabled ? 'enabled' : 'disabled'}\n`);
+ console.log(`Temporal: enabled\n`);
let allStopped = true;
@@ -36,11 +36,9 @@ async function main() {
if (!result.portFree) allStopped = false;
}
- if (config.temporalEnabled) {
- const temporalPids = await killByPattern('temporal');
- if (temporalPids.length > 0) {
- console.log(`[OK] Temporal: Killed ${temporalPids.length} process(es)`);
- }
+ const temporalPids = await killByPattern('temporal');
+ if (temporalPids.length > 0) {
+ console.log(`[OK] Temporal: Killed ${temporalPids.length} process(es)`);
}
// Kill orphaned MachinaOs processes (may hold DB locks after crash)
diff --git a/server/config/model_registry.json b/server/config/model_registry.json
index 0591c818..37ba2b61 100644
--- a/server/config/model_registry.json
+++ b/server/config/model_registry.json
@@ -1,8 +1,184 @@
{
- "_generated": "2026-03-11T10:02:14.102765+00:00",
+ "_generated": "2026-03-17T07:47:31.993086+00:00",
"_source": "openrouter",
- "_model_count": 339,
+ "_model_count": 345,
"models": {
+ "z-ai/glm-5-turbo": {
+ "id": "z-ai/glm-5-turbo",
+ "name": "Z.ai: GLM 5 Turbo",
+ "provider": "z-ai",
+ "local_id": "glm-5-turbo",
+ "context_length": 202752,
+ "max_output_tokens": 131072,
+ "input_price_per_mtok": 0.96,
+ "output_price_per_mtok": 3.2,
+ "supports_thinking": false,
+ "thinking_type": "none",
+ "temperature_range": [
+ 0.0,
+ 2.0
+ ],
+ "is_reasoning_model": false,
+ "supported_parameters": [
+ "include_reasoning",
+ "max_tokens",
+ "reasoning",
+ "response_format",
+ "temperature",
+ "tool_choice",
+ "tools",
+ "top_p"
+ ]
+ },
+ "xai/grok-4.20-multi-agent-beta": {
+ "id": "x-ai/grok-4.20-multi-agent-beta",
+ "name": "xAI: Grok 4.20 Multi-Agent Beta",
+ "provider": "xai",
+ "local_id": "grok-4.20-multi-agent-beta",
+ "context_length": 2000000,
+ "max_output_tokens": 0,
+ "input_price_per_mtok": 2.0,
+ "output_price_per_mtok": 6.0,
+ "supports_thinking": false,
+ "thinking_type": "none",
+ "temperature_range": [
+ 0.0,
+ 2.0
+ ],
+ "is_reasoning_model": false,
+ "supported_parameters": [
+ "include_reasoning",
+ "logprobs",
+ "max_tokens",
+ "reasoning",
+ "response_format",
+ "seed",
+ "structured_outputs",
+ "temperature",
+ "top_logprobs",
+ "top_p"
+ ]
+ },
+ "xai/grok-4.20-beta": {
+ "id": "x-ai/grok-4.20-beta",
+ "name": "xAI: Grok 4.20 Beta",
+ "provider": "xai",
+ "local_id": "grok-4.20-beta",
+ "context_length": 2000000,
+ "max_output_tokens": 0,
+ "input_price_per_mtok": 2.0,
+ "output_price_per_mtok": 6.0,
+ "supports_thinking": false,
+ "thinking_type": "none",
+ "temperature_range": [
+ 0.0,
+ 2.0
+ ],
+ "is_reasoning_model": false,
+ "supported_parameters": [
+ "include_reasoning",
+ "logprobs",
+ "max_tokens",
+ "reasoning",
+ "response_format",
+ "seed",
+ "structured_outputs",
+ "temperature",
+ "tool_choice",
+ "tools",
+ "top_logprobs",
+ "top_p"
+ ]
+ },
+ "openrouter/hunter-alpha": {
+ "id": "openrouter/hunter-alpha",
+ "name": "Hunter Alpha",
+ "provider": "openrouter",
+ "local_id": "hunter-alpha",
+ "context_length": 1048576,
+ "max_output_tokens": 32000,
+ "input_price_per_mtok": 0.0,
+ "output_price_per_mtok": 0.0,
+ "supports_thinking": false,
+ "thinking_type": "none",
+ "temperature_range": [
+ 0.0,
+ 2.0
+ ],
+ "is_reasoning_model": false,
+ "supported_parameters": [
+ "frequency_penalty",
+ "include_reasoning",
+ "max_tokens",
+ "presence_penalty",
+ "reasoning",
+ "response_format",
+ "stop",
+ "temperature",
+ "tool_choice",
+ "tools",
+ "top_p"
+ ]
+ },
+ "openrouter/healer-alpha": {
+ "id": "openrouter/healer-alpha",
+ "name": "Healer Alpha",
+ "provider": "openrouter",
+ "local_id": "healer-alpha",
+ "context_length": 262144,
+ "max_output_tokens": 32000,
+ "input_price_per_mtok": 0.0,
+ "output_price_per_mtok": 0.0,
+ "supports_thinking": false,
+ "thinking_type": "none",
+ "temperature_range": [
+ 0.0,
+ 2.0
+ ],
+ "is_reasoning_model": false,
+ "supported_parameters": [
+ "frequency_penalty",
+ "include_reasoning",
+ "max_tokens",
+ "presence_penalty",
+ "reasoning",
+ "response_format",
+ "stop",
+ "temperature",
+ "tool_choice",
+ "tools",
+ "top_p"
+ ]
+ },
+ "nvidia/nemotron-3-super-120b-a12b:free": {
+ "id": "nvidia/nemotron-3-super-120b-a12b:free",
+ "name": "NVIDIA: Nemotron 3 Super (free)",
+ "provider": "nvidia",
+ "local_id": "nemotron-3-super-120b-a12b:free",
+ "context_length": 262144,
+ "max_output_tokens": 262144,
+ "input_price_per_mtok": 0.0,
+ "output_price_per_mtok": 0.0,
+ "supports_thinking": false,
+ "thinking_type": "none",
+ "temperature_range": [
+ 0.0,
+ 2.0
+ ],
+ "is_reasoning_model": false,
+ "supported_parameters": [
+ "include_reasoning",
+ "max_tokens",
+ "reasoning",
+ "response_format",
+ "seed",
+ "structured_outputs",
+ "temperature",
+ "tool_choice",
+ "tools",
+ "top_p"
+ ]
+ },
"bytedance-seed/seed-2.0-lite": {
"id": "bytedance-seed/seed-2.0-lite",
"name": "ByteDance Seed: Seed-2.0-Lite",
@@ -38,9 +214,9 @@
"name": "Qwen: Qwen3.5-9B",
"provider": "qwen",
"local_id": "qwen3.5-9b",
- "context_length": 262144,
+ "context_length": 256000,
"max_output_tokens": 0,
- "input_price_per_mtok": 0.1,
+ "input_price_per_mtok": 0.05,
"output_price_per_mtok": 0.15,
"supports_thinking": false,
"thinking_type": "none",
@@ -53,6 +229,7 @@
"frequency_penalty",
"include_reasoning",
"logit_bias",
+ "logprobs",
"max_tokens",
"min_p",
"presence_penalty",
@@ -65,6 +242,7 @@
"tool_choice",
"tools",
"top_k",
+ "top_logprobs",
"top_p"
]
},
@@ -85,20 +263,14 @@
],
"is_reasoning_model": false,
"supported_parameters": [
- "frequency_penalty",
"include_reasoning",
- "logit_bias",
- "logprobs",
"max_tokens",
- "presence_penalty",
"reasoning",
"response_format",
"seed",
- "stop",
"structured_outputs",
"tool_choice",
- "tools",
- "top_logprobs"
+ "tools"
]
},
"openai/gpt-5.4": {
@@ -118,20 +290,14 @@
],
"is_reasoning_model": false,
"supported_parameters": [
- "frequency_penalty",
"include_reasoning",
- "logit_bias",
- "logprobs",
"max_tokens",
- "presence_penalty",
"reasoning",
"response_format",
"seed",
- "stop",
"structured_outputs",
"tool_choice",
- "tools",
- "top_logprobs"
+ "tools"
]
},
"inception/mercury-2": {
@@ -179,18 +345,12 @@
],
"is_reasoning_model": false,
"supported_parameters": [
- "frequency_penalty",
- "logit_bias",
- "logprobs",
"max_tokens",
- "presence_penalty",
"response_format",
"seed",
- "stop",
"structured_outputs",
"tool_choice",
- "tools",
- "top_logprobs"
+ "tools"
]
},
"gemini/gemini-3.1-flash-lite-preview": {
@@ -402,8 +562,8 @@
"local_id": "qwen3.5-flash-02-23",
"context_length": 1000000,
"max_output_tokens": 65536,
- "input_price_per_mtok": 0.1,
- "output_price_per_mtok": 0.4,
+ "input_price_per_mtok": 0.065,
+ "output_price_per_mtok": 0.26,
"supports_thinking": false,
"thinking_type": "none",
"temperature_range": [
@@ -662,15 +822,42 @@
"top_p"
]
},
+ "minimax/minimax-m2.5:free": {
+ "id": "minimax/minimax-m2.5:free",
+ "name": "MiniMax: MiniMax M2.5 (free)",
+ "provider": "minimax",
+ "local_id": "minimax-m2.5:free",
+ "context_length": 196608,
+ "max_output_tokens": 196608,
+ "input_price_per_mtok": 0.0,
+ "output_price_per_mtok": 0.0,
+ "supports_thinking": false,
+ "thinking_type": "none",
+ "temperature_range": [
+ 0.0,
+ 2.0
+ ],
+ "is_reasoning_model": false,
+ "supported_parameters": [
+ "include_reasoning",
+ "max_tokens",
+ "reasoning",
+ "response_format",
+ "seed",
+ "stop",
+ "temperature",
+ "tools"
+ ]
+ },
"minimax/minimax-m2.5": {
"id": "minimax/minimax-m2.5",
"name": "MiniMax: MiniMax M2.5",
"provider": "minimax",
"local_id": "minimax-m2.5",
"context_length": 196608,
- "max_output_tokens": 0,
- "input_price_per_mtok": 0.27,
- "output_price_per_mtok": 0.95,
+ "max_output_tokens": 196608,
+ "input_price_per_mtok": 0.25,
+ "output_price_per_mtok": 1.2,
"supports_thinking": false,
"thinking_type": "none",
"temperature_range": [
@@ -976,7 +1163,6 @@
"parallel_tool_calls",
"presence_penalty",
"reasoning",
- "reasoning_effort",
"repetition_penalty",
"response_format",
"seed",
@@ -1943,8 +2129,10 @@
"is_reasoning_model": false,
"supported_parameters": [
"frequency_penalty",
+ "logprobs",
"max_tokens",
"presence_penalty",
+ "repetition_penalty",
"response_format",
"seed",
"stop",
@@ -1952,6 +2140,7 @@
"temperature",
"tool_choice",
"tools",
+ "top_logprobs",
"top_p"
]
},
@@ -2006,8 +2195,10 @@
"is_reasoning_model": false,
"supported_parameters": [
"frequency_penalty",
+ "logprobs",
"max_tokens",
"presence_penalty",
+ "repetition_penalty",
"response_format",
"seed",
"stop",
@@ -2015,6 +2206,7 @@
"temperature",
"tool_choice",
"tools",
+ "top_logprobs",
"top_p"
]
},
@@ -2146,9 +2338,9 @@
"provider": "deepseek",
"local_id": "deepseek-v3.2",
"context_length": 163840,
- "max_output_tokens": 65536,
- "input_price_per_mtok": 0.25,
- "output_price_per_mtok": 0.4,
+ "max_output_tokens": 0,
+ "input_price_per_mtok": 0.26,
+ "output_price_per_mtok": 0.38,
"supports_thinking": false,
"thinking_type": "none",
"temperature_range": [
@@ -3289,8 +3481,8 @@
"local_id": "qwen3-vl-30b-a3b-thinking",
"context_length": 131072,
"max_output_tokens": 32768,
- "input_price_per_mtok": 0.0,
- "output_price_per_mtok": 0.0,
+ "input_price_per_mtok": 0.13,
+ "output_price_per_mtok": 1.56,
"supports_thinking": false,
"thinking_type": "none",
"temperature_range": [
@@ -3500,10 +3692,8 @@
"max_tokens",
"presence_penalty",
"repetition_penalty",
- "response_format",
"seed",
"stop",
- "structured_outputs",
"temperature",
"top_k",
"top_p"
@@ -3568,8 +3758,8 @@
"local_id": "qwen3-vl-235b-a22b-thinking",
"context_length": 131072,
"max_output_tokens": 32768,
- "input_price_per_mtok": 0.0,
- "output_price_per_mtok": 0.0,
+ "input_price_per_mtok": 0.26,
+ "output_price_per_mtok": 2.6,
"supports_thinking": false,
"thinking_type": "none",
"temperature_range": [
@@ -3614,6 +3804,7 @@
"supported_parameters": [
"frequency_penalty",
"logit_bias",
+ "logprobs",
"max_tokens",
"min_p",
"presence_penalty",
@@ -3626,6 +3817,7 @@
"tool_choice",
"tools",
"top_k",
+ "top_logprobs",
"top_p"
]
},
@@ -3636,8 +3828,8 @@
"local_id": "qwen3-max",
"context_length": 262144,
"max_output_tokens": 32768,
- "input_price_per_mtok": 1.2,
- "output_price_per_mtok": 6.0,
+ "input_price_per_mtok": 0.78,
+ "output_price_per_mtok": 3.9,
"supports_thinking": false,
"thinking_type": "none",
"temperature_range": [
@@ -3846,10 +4038,10 @@
"name": "Qwen: Qwen3 Next 80B A3B Thinking",
"provider": "qwen",
"local_id": "qwen3-next-80b-a3b-thinking",
- "context_length": 128000,
- "max_output_tokens": 0,
- "input_price_per_mtok": 0.15,
- "output_price_per_mtok": 1.2,
+ "context_length": 131072,
+ "max_output_tokens": 32768,
+ "input_price_per_mtok": 0.0975,
+ "output_price_per_mtok": 0.78,
"supports_thinking": false,
"thinking_type": "none",
"temperature_range": [
@@ -7612,8 +7804,8 @@
"local_id": "qwen-vl-max",
"context_length": 131072,
"max_output_tokens": 32768,
- "input_price_per_mtok": 0.8,
- "output_price_per_mtok": 3.2,
+ "input_price_per_mtok": 0.52,
+ "output_price_per_mtok": 2.08,
"supports_thinking": false,
"thinking_type": "none",
"temperature_range": [
@@ -7697,8 +7889,8 @@
"local_id": "qwen-plus",
"context_length": 1000000,
"max_output_tokens": 32768,
- "input_price_per_mtok": 0.4,
- "output_price_per_mtok": 1.2,
+ "input_price_per_mtok": 0.26,
+ "output_price_per_mtok": 0.78,
"supports_thinking": false,
"thinking_type": "none",
"temperature_range": [
@@ -8401,9 +8593,9 @@
"provider": "qwen",
"local_id": "qwen-2.5-coder-32b-instruct",
"context_length": 32768,
- "max_output_tokens": 8192,
- "input_price_per_mtok": 0.2,
- "output_price_per_mtok": 0.2,
+ "max_output_tokens": 0,
+ "input_price_per_mtok": 0.66,
+ "output_price_per_mtok": 1.0,
"supports_thinking": false,
"thinking_type": "none",
"temperature_range": [
@@ -8413,13 +8605,10 @@
"is_reasoning_model": false,
"supported_parameters": [
"frequency_penalty",
- "logit_bias",
"max_tokens",
- "min_p",
"presence_penalty",
"repetition_penalty",
"seed",
- "stop",
"temperature",
"top_k",
"top_p"
@@ -9158,7 +9347,6 @@
"is_reasoning_model": false,
"supported_parameters": [
"frequency_penalty",
- "logit_bias",
"logprobs",
"max_tokens",
"min_p",
@@ -9176,40 +9364,6 @@
"top_p"
]
},
- "meta/llama-3.1-405b-instruct": {
- "id": "meta-llama/llama-3.1-405b-instruct",
- "name": "Meta: Llama 3.1 405B Instruct",
- "provider": "meta",
- "local_id": "llama-3.1-405b-instruct",
- "context_length": 131000,
- "max_output_tokens": 0,
- "input_price_per_mtok": 4.0,
- "output_price_per_mtok": 4.0,
- "supports_thinking": false,
- "thinking_type": "none",
- "temperature_range": [
- 0.0,
- 2.0
- ],
- "is_reasoning_model": false,
- "supported_parameters": [
- "frequency_penalty",
- "logit_bias",
- "max_tokens",
- "min_p",
- "presence_penalty",
- "repetition_penalty",
- "response_format",
- "seed",
- "stop",
- "structured_outputs",
- "temperature",
- "tool_choice",
- "tools",
- "top_k",
- "top_p"
- ]
- },
"meta/llama-3.1-70b-instruct": {
"id": "meta-llama/llama-3.1-70b-instruct",
"name": "Meta: Llama 3.1 70B Instruct",
diff --git a/server/main.py b/server/main.py
index 2b4d2375..4d90d8e0 100644
--- a/server/main.py
+++ b/server/main.py
@@ -189,6 +189,7 @@ async def lifespan(app: FastAPI):
# Initialize Temporal if enabled
temporal_worker_manager = None
if settings.temporal_enabled:
+ _startup_log(f"[Temporal] Connecting to {settings.temporal_server_address}...")
from services.temporal import TemporalClientWrapper, TemporalExecutor
from services.temporal.worker import TemporalWorkerManager
@@ -199,9 +200,9 @@ async def lifespan(app: FastAPI):
task_queue=settings.temporal_task_queue,
)
- # Connect Temporal client (retries 3 times, then falls back)
+ # Connect Temporal client (retries up to 10 times to allow temporal-server startup)
temporal_client_wrapper = container.temporal_client()
- temporal_client = await temporal_client_wrapper.connect(retries=3, delay=2.0)
+ temporal_client = await temporal_client_wrapper.connect(retries=10, delay=3.0)
if temporal_client is not None:
# Create and set the Temporal executor on WorkflowService
@@ -218,8 +219,10 @@ async def lifespan(app: FastAPI):
)
await temporal_worker_manager.start()
+ _startup_log("[Temporal] Worker started, execution engine ready")
logger.info("Temporal integration initialized successfully")
else:
+ _startup_log("[Temporal] Server not reachable, using local execution")
logger.warning(
f"Temporal server not reachable at {settings.temporal_server_address}. "
"Falling back to local parallel/sequential execution. "
@@ -227,6 +230,8 @@ async def lifespan(app: FastAPI):
)
# Start background reconnect loop (tries every 30s)
await temporal_client_wrapper.start_background_reconnect(interval=30.0)
+ else:
+ _startup_log("[Temporal] Disabled")
_startup_log("All services initialized")
print("Application startup complete", flush=True)
diff --git a/server/models/nodes.py b/server/models/nodes.py
index 78ee2aca..bd4a2667 100644
--- a/server/models/nodes.py
+++ b/server/models/nodes.py
@@ -25,6 +25,7 @@ from constants import (
TEXT_TYPES,
WORKFLOW_CONTROL_TYPES,
TRIGGER_TYPES,
+ POLLING_TRIGGER_TYPES,
)
@@ -246,6 +247,39 @@ class WorkflowTriggerParams(BaseNodeParams):
type: Literal["workflowTrigger"]
+class TaskTriggerParams(BaseNodeParams):
+ """Parameters for task trigger node (fires on delegated agent completion)."""
+ type: Literal["taskTrigger"]
+ task_id: str = Field(default="", alias="taskId")
+ agent_name: str = Field(default="", alias="agentName")
+ status_filter: Literal["all", "completed", "error"] = Field(default="all", alias="statusFilter")
+ parent_node_id: str = Field(default="", alias="parentNodeId")
+
+
+class ChatTriggerParams(BaseNodeParams):
+ """Parameters for chat trigger node."""
+ type: Literal["chatTrigger"]
+
+
+class TelegramReceiveParams(BaseNodeParams):
+ """Parameters for Telegram receive trigger node."""
+ type: Literal["telegramReceive"]
+ sender_filter: str = Field(default="all", alias="senderFilter")
+
+
+class TwitterReceiveParams(BaseNodeParams):
+ """Parameters for Twitter receive trigger node."""
+ type: Literal["twitterReceive"]
+
+
+class GmailReceiveParams(BaseNodeParams):
+ """Parameters for Gmail receive polling trigger node."""
+ type: Literal["gmailReceive"]
+ filter_query: str = Field(default="is:unread", alias="filterQuery")
+ label_filter: str = Field(default="INBOX", alias="labelFilter")
+ poll_interval: int = Field(default=60, alias="pollInterval", ge=10, le=3600)
+
+
# =============================================================================
# TEXT NODE MODELS
# =============================================================================
@@ -316,7 +350,8 @@ HttpNodeParams = Annotated[
# Workflow Control Nodes
WorkflowNodeParams = Annotated[
- Union[StartNodeParams, CronSchedulerParams, WorkflowTriggerParams],
+ Union[StartNodeParams, CronSchedulerParams, WorkflowTriggerParams, TaskTriggerParams,
+ ChatTriggerParams, TelegramReceiveParams, TwitterReceiveParams, GmailReceiveParams],
Field(discriminator="type")
]
@@ -347,6 +382,8 @@ KnownNodeParams = Annotated[
HttpRequestParams, WebhookTriggerParams, WebhookResponseParams,
# Workflow
StartNodeParams, CronSchedulerParams, WorkflowTriggerParams,
+ # Triggers
+ TaskTriggerParams, ChatTriggerParams, TelegramReceiveParams, TwitterReceiveParams, GmailReceiveParams,
# Text
TextGeneratorParams, FileHandlerParams,
# Chat
@@ -453,5 +490,6 @@ def get_all_node_types() -> set:
HTTP_TYPES |
TEXT_TYPES |
WORKFLOW_CONTROL_TYPES |
- TRIGGER_TYPES
+ TRIGGER_TYPES |
+ POLLING_TRIGGER_TYPES
)
diff --git a/server/services/deployment/manager.py b/server/services/deployment/manager.py
index d83a66c6..a5e1448c 100644
--- a/server/services/deployment/manager.py
+++ b/server/services/deployment/manager.py
@@ -558,9 +558,15 @@ class DeploymentManager:
if node['id'] not in run_filter:
continue
node_copy = node.copy()
+ node_type = node.get('type', '')
if node['id'] == trigger_node_id:
node_copy['_pre_executed'] = True
node_copy['_trigger_output'] = trigger_output
+ elif node_type in WORKFLOW_TRIGGER_TYPES:
+ # Non-firing triggers: pre-execute to prevent blocking as event waiters
+ node_copy['_pre_executed'] = True
+ node_copy['_trigger_output'] = {'not_triggered': True}
+ logger.debug(f"[Run] Marking non-firing trigger as pre-executed: {node['id']} ({node_type})")
filtered_nodes.append(node_copy)
filtered_edges = [
@@ -608,10 +614,11 @@ class DeploymentManager:
target_type = node_types.get(target_id, '')
is_trigger = target_type in WORKFLOW_TRIGGER_TYPES
- has_inputs = target_id in nodes_with_inputs
- # Stop at independent triggers (no inputs)
- if is_trigger and not has_inputs:
+ # Stop at trigger nodes — they are independent event listeners,
+ # not regular execution nodes. Each trigger spawns its own
+ # execution run when its event fires (n8n pattern).
+ if is_trigger:
continue
downstream_ids.add(target_id)
@@ -627,6 +634,11 @@ class DeploymentManager:
is_config = handle and handle.startswith('input-') and handle != 'input-main'
if is_config and target in downstream_ids and source not in downstream_ids:
+ # Never include trigger nodes as config dependencies -
+ # they are event listeners, not configuration providers
+ source_type = node_types.get(source, '')
+ if source_type in WORKFLOW_TRIGGER_TYPES:
+ continue
downstream_ids.add(source)
# Include sub-nodes connected to toolkit nodes (n8n Sub-Node pattern)
diff --git a/server/services/deployment/triggers.py b/server/services/deployment/triggers.py
index bfc60cf0..69af9f9b 100644
--- a/server/services/deployment/triggers.py
+++ b/server/services/deployment/triggers.py
@@ -348,14 +348,16 @@ class TriggerManager:
@staticmethod
def find_trigger_nodes(nodes: list, edges: list) -> tuple:
- """Find trigger nodes, split into start nodes and event triggers."""
- # Nodes with incoming edges
- nodes_with_inputs = {e.get('target') for e in edges if e.get('target')}
+ """Find trigger nodes, split into start nodes and event triggers.
+ All trigger nodes are independent event listeners that spawn their own
+ execution runs — including downstream triggers (e.g., taskTrigger connected
+ after an AI agent). Each trigger listens for its event type and, when fired,
+ executes its downstream subgraph independently.
+ """
trigger_types_no_cron = WORKFLOW_TRIGGER_TYPES - {'cronScheduler'}
triggers = [n for n in nodes
- if n.get('type') in trigger_types_no_cron
- and n.get('id') not in nodes_with_inputs]
+ if n.get('type') in trigger_types_no_cron]
start_nodes = [n for n in triggers if n.get('type') == 'start']
event_triggers = [n for n in triggers if n.get('type') != 'start']
diff --git a/server/services/temporal/client.py b/server/services/temporal/client.py
index 892612e0..9943dd49 100644
--- a/server/services/temporal/client.py
+++ b/server/services/temporal/client.py
@@ -6,7 +6,7 @@ Manages the Temporal client connection lifecycle with retry support.
import asyncio
from typing import Optional
from temporalio.client import Client
-from temporalio.runtime import Runtime, TelemetryConfig
+from temporalio.runtime import LoggingConfig, Runtime, TelemetryConfig
from core.logging import get_logger
@@ -45,7 +45,9 @@ class TemporalClientWrapper:
# Create runtime once (reusable across reconnects)
if self._runtime is None:
self._runtime = Runtime(
- telemetry=TelemetryConfig(),
+ telemetry=TelemetryConfig(
+ logging=LoggingConfig(filter="ERROR"),
+ ),
worker_heartbeat_interval=None,
)
@@ -61,15 +63,18 @@ class TemporalClientWrapper:
namespace=self.namespace,
runtime=self._runtime,
)
+ print(f"[Temporal] Connected to {self.server_address}", flush=True)
logger.info("Connected to Temporal server")
return self._client
except Exception as e:
+ print(f"[Temporal] Connection attempt {attempt}/{retries} failed: {e}", flush=True)
logger.warning(
f"Temporal connection attempt {attempt}/{retries} failed: {e}"
)
if attempt < retries:
await asyncio.sleep(delay)
+ print(f"[Temporal] Failed to connect after {retries} attempts", flush=True)
logger.error(
f"Failed to connect to Temporal server at {self.server_address} after {retries} attempts"
)
diff --git a/server/services/temporal/worker.py b/server/services/temporal/worker.py
index b20e7e0f..17da53b8 100644
--- a/server/services/temporal/worker.py
+++ b/server/services/temporal/worker.py
@@ -20,7 +20,7 @@ from typing import Optional
import aiohttp
from temporalio.client import Client
-from temporalio.runtime import Runtime, TelemetryConfig
+from temporalio.runtime import LoggingConfig, Runtime, TelemetryConfig
from temporalio.worker import Worker
from core.logging import get_logger
@@ -40,7 +40,9 @@ def create_runtime() -> Runtime:
the warning on older Temporal server versions that don't support it.
"""
return Runtime(
- telemetry=TelemetryConfig(),
+ telemetry=TelemetryConfig(
+ logging=LoggingConfig(filter="ERROR"),
+ ),
worker_heartbeat_interval=None, # Disable runtime heartbeating
)
@@ -102,6 +104,7 @@ class TemporalWorkerManager:
max_concurrent_workflow_tasks=10,
)
+ print(f"[Temporal] Worker started (queue={self.task_queue}, pool={self.pool_size})", flush=True)
logger.info(
"Starting Temporal worker",
task_queue=self.task_queue,
diff --git a/server/services/temporal/workflow.py b/server/services/temporal/workflow.py
index fb25fb4e..5586568e 100644
--- a/server/services/temporal/workflow.py
+++ b/server/services/temporal/workflow.py
@@ -18,9 +18,17 @@ from temporalio import workflow
from temporalio.common import RetryPolicy
# Config handles - nodes connecting via these are config nodes (not executed)
-# AI Agent handles: input-memory, input-tools, input-model
+# AI Agent handles: input-memory, input-tools, input-model, input-task, input-teammates
# Zeenie handles: input-skill, input-tools
-CONFIG_HANDLES = {"input-tools", "input-memory", "input-model", "input-skill"}
+CONFIG_HANDLES = {"input-tools", "input-memory", "input-model", "input-skill", "input-task", "input-teammates"}
+
+# Trigger node types - event listeners that should never be scheduled as blocking activities
+# Must be kept in sync with constants.WORKFLOW_TRIGGER_TYPES
+TRIGGER_NODE_TYPES = frozenset([
+ "start", "cronScheduler", "webhookTrigger", "whatsappReceive",
+ "workflowTrigger", "chatTrigger", "taskTrigger",
+ "twitterReceive", "gmailReceive", "telegramReceive",
+])
# Android service types (connect to androidTool, not executed directly)
ANDROID_SERVICE_TYPES = {
@@ -133,6 +141,23 @@ class MachinaWorkflow:
# Start activities for ready nodes
for node_id in ready:
node = node_map[node_id]
+ node_type = node.get("type", "unknown")
+
+ # Safety: auto-complete trigger nodes that weren't pre-executed.
+ # Trigger nodes are event listeners - scheduling them as activities
+ # would block indefinitely waiting for external events.
+ if node_type in TRIGGER_NODE_TYPES and not node.get("_pre_executed"):
+ workflow.logger.warning(
+ f"Skipping non-pre-executed trigger: {node_id} ({node_type})"
+ )
+ outputs[node_id] = {
+ "success": True,
+ "result": {"not_triggered": True},
+ "skipped_trigger": True,
+ }
+ completed.add(node_id)
+ execution_trace.append(node_id)
+ continue
# Build immutable context for this node
context = {