Skip to content

Self-improving AI Employees for everyone

docs: sync docs and comments with code (counts, retired paths, security)

trohitg5447c3171823
diff --git a/CLAUDE.md b/CLAUDE.md
index 5961038e..84a28447 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -16,7 +16,7 @@ This is a React Flow-based workflow automation platform implementing n8n-inspire
| **[Theme System](./docs-internal/theme_system.md)** | 12-way visual theme system — 2 base (light, dark) + 5 utopian (renaissance, greek, edo, steampunk, atomic) + 5 dystopian (cyber, wasteland, rot, plague, surveillance) — driven by `<html data-theme>` + per-theme CSS files in `client/src/themes/`. Token taxonomy (surface / fg / border / accent / typography / motion) in **hex + `color-mix()`**; `@theme inline` bridge maps `--color-X: var(--X)` (no `hsl()` wrapper); per-theme files own the colour hex, base.css owns the shared `--tint-*` alpha scale; action role tokens (incl. `-ink` readable text), **per-theme `--code-*` syntax tokens** (tier 6 — the code editor, console/output JSON viewers, and chat code blocks paint in each theme's own palette: keyword→trigger, string→success, number→agent, function→model, on an adaptive dark/light code surface; replaced the global dracula `--prism-*` block + dead `getPrismTokenCSS`; the `OutputPanel` JSON viewer reads the same vars), per-theme `--pulse-keyframe` animation system + `.opencompany-*` helpers in `animations.css`, decorative-layer wrappers (`.app-frame` / `.canvas-host` / `.modal-frame`), per-component decorative ornaments (panel textures + canvas decorations + node pseudo-element overlays + theme-specific keyframes), **canvas-node visual contract via `--node-color` CSS custom property** (no inline `background` / `border` on node components — base.css + per-theme CSS owns visuals; `NodeStyle` helper type at [types/NodeTypes.ts](./client/src/types/NodeTypes.ts) makes the inline custom-prop typecheck-clean), **`--node-pulse-color` separate from `--node-color`** so executing-node glow uses each theme's highest-contrast accent regardless of plugin accent (Cyber neon cyan, Surveillance REC red, Renaissance ultramarine, etc.), **`data-page-hidden` animation pause** (toggled by Dashboard's `visibilitychange` listener; base.css declares `html[data-page-hidden] *, *::before, *::after { animation-play-state: paused !important }` to prevent compositor stall on tab return), **per-theme icon glyph system** (290 SVGs across 29 keys × 10 themes via [themedGlyphs.ts](./client/src/assets/icons/themedGlyphs.ts) + theme-aware [NodeIcon.tsx](./client/src/assets/icons/NodeIcon.tsx)), **per-theme canvas-grid + custom cursors** via `--canvas-grid` / `--cursor-default` slots, **decorative HTML primitives** (`<SvgFilterDefs>` mounting `#ink-blot` / `#noise` / `#crt` filter IDs at app root, `<DropCap>` wrapper for Renaissance ornament rule), **parameter panel migrated to Tailwind tokens** (no `useAppTheme()` reads; section headers carry the display-typography triplet; raw `<Button>` swapped to `<ActionButton intent>`), **per-theme scrollbar webkit rules** in all 12 themes, 9-event WebAudio sound system (10 packs via `--sound-pack` token + `useSound()` hook + global hover delegate + sonner toast monkey-patch + `withSound()` HOC + `Sounds.unlock()` gesture-unlock for AudioContext autoplay-policy compliance), `@media (prefers-reduced-motion: reduce)` accessibility, 30 ms throttle on `type` / `hover`, migration recipe, anti-patterns. Read this before adding a new theme, migrating a component to the new contract, or adding a canvas-node component. |
| **[Design System Bundle](./docs-internal/design-system/IMPLEMENTATION.md)** | Canonical, vendored design-system reference (extracted from this repo; see its `IMPLEMENTATION.md` for the contract). Tokens are **hex + `color-mix()`** (`tokens/{colors,typography,spacing,motion,fonts,base}.css`) — the format the live codebase standardizes on. Includes 34 reference components (`components/`, inline-style reference only — recreate in Tailwind/shadcn idioms), full-app UI kit (`ui_kits/opencompany/index.html`), and 12-theme docs (`guidelines/THEMES.md`, `reference/themes/`). Copy token values verbatim; do not re-derive by eye. Pairs with [Theme System](./docs-internal/theme_system.md). |
| **[Schema Source of Truth RFC](./docs-internal/schema_source_of_truth_rfc.md)** | Backend is SSOT for node schemas, visual metadata, handlers, palette metadata, icons. Plugin pattern: one `BaseNode` subclass in `server/nodes/<group>/<plugin>/__init__.py`. Wire format: `asset:<key>` / `<lib>:<brand>` / URL / emoji. Endpoint: `/api/schemas/nodes/{type}/spec.json`. Live invariant total via `pytest --collect-only`. |
-| **[Plugin System (Wave 11)](./docs-internal/plugin_system.md)** | Class-based plugin-first architecture. `BaseNode` / `ActionNode` / `TriggerNode` / `ToolNode` + `@Operation` decorator. Pydantic `Params`/`Output`. Declarative `Routing` DSL + `Connection` facade (Nango pattern). 18 `Credential` subclasses live in each node folder's `_credentials.py` (or inline for single-use). `TaskQueue` constants route to Temporal worker pools. Plugins live across 9 queues (live count via `glob server/nodes/**/__init__.py`); handler bodies fully inlined (`services/handlers/` shrank 12.8K → 1.1K LOC across 16 → 4 files; only cross-cutting orchestration remains: `tools.py` AI-tool dispatch + agent delegation, `triggers.py` generic trigger-node handler, `todo.py` writeTodos shim — `google_auth.py` was retired into `nodes/google/_auth_helper.py`). **Wave 11.H added "self-contained plugin folders"** — up to six generic registries (`ws_handler_registry`, `register_router`, `event_waiter.{register_filter_builder,register_trigger_precheck}`, `status_broadcaster.register_service_refresh`, `node_output_schemas.register_output_schema`) so rich plugins like telegram own their entire surface area without core-services edits. |
+| **[Plugin System (Wave 11)](./docs-internal/plugin_system.md)** | Class-based plugin-first architecture. `BaseNode` / `ActionNode` / `TriggerNode` / `ToolNode` + `@Operation` decorator. Pydantic `Params`/`Output`. Declarative `Routing` DSL + `Connection` facade (Nango pattern). 25 `Credential` subclasses live in each node folder's `_credentials.py` (or inline for single-use). `TaskQueue` constants route to Temporal worker pools. Plugins live across 9 queues (live count via `glob server/nodes/**/__init__.py`); handler bodies fully inlined (`services/handlers/` shrank 12.8K → 1.1K LOC across 16 → 4 files; only cross-cutting orchestration remains: `tools.py` AI-tool dispatch + agent delegation, `triggers.py` generic trigger-node handler, `todo.py` writeTodos shim — `google_auth.py` was retired into `nodes/google/_auth_helper.py`). **Wave 11.H added "self-contained plugin folders"** — up to six generic registries (`ws_handler_registry`, `register_router`, `event_waiter.{register_filter_builder,register_trigger_precheck}`, `status_broadcaster.register_service_refresh`, `node_output_schemas.register_output_schema`) so rich plugins like telegram own their entire surface area without core-services edits. |
| **[Nodes Cookbook](./server/nodes/README.md)** | 5-minute recipe + folder map + shared helpers (`_base.py` / `_inline.py` per domain) + shared credentials + **canonical folder-per-plugin shape (telegram is the reference implementation)** + contract invariants + common pitfalls. Lives next to the plugin files. |
| **[Node Creation Guide](./docs-internal/node_creation.md)** | Canonical plugin recipe — one self-contained folder per plugin under `server/nodes/<group>/<plugin>/`, rooted at `__init__.py`. Multi-file split (`_service.py` / `_handlers.py` / etc.) when the plugin owns long-lived state. Zero frontend edits, zero core-services edits. Auto-registers via `BaseNode.__init_subclass__` + the six `register_*` hooks. Covers tool nodes, dual-purpose nodes (workflow + AI tool), and specialized agents as variations of the same recipe. |
| **[Agent Architecture](./docs-internal/agent_architecture.md)** | How AI Agent and Chat Agent discover skills/tools, inject them into LLM prompts, and execute via the plain-async `_run_agent_loop` |
@@ -81,7 +81,7 @@ Every plugin is a self-contained folder under `server/nodes/<group>/<plugin>/` r
- [server/nodes/README.md](./server/nodes/README.md) — 5-minute walkthrough with the canonical folder template
- [docs-internal/plugin_system.md → Self-contained plugin folders](./docs-internal/plugin_system.md#self-contained-plugin-folders) — full reference, plus the **up-to-six generic registries** plugins self-wire into (`register_ws_handlers`, `register_router`, `register_filter_builder`, `register_trigger_precheck`, `register_service_refresh`, `register_output_schema`)
- [docs-internal/node_creation.md](./docs-internal/node_creation.md) — decision tree for action / trigger / tool / dual-purpose / specialized-agent nodes
-- [server/nodes/telegram/](./server/nodes/telegram/) — reference implementation of the multi-file split (`_service.py` / `_handlers.py` / `_filters.py` / `_refresh.py` / `_credentials.py` / two node files)
+- [server/nodes/telegram/](./server/nodes/telegram/) — reference implementation of the multi-file split (`_service.py` / `_handlers.py` / `_filters.py` / `_refresh.py` / `_credentials.py` / `_events.py` / two node files)
**Wire format is the contract — not module paths.** The frontend identifies plugin commands by WebSocket message-type strings (`telegram_connect`, `telegram_status`, …). Moving handler bodies between Python files is invisible to the frontend so long as the registered keys stay the same.
@@ -90,7 +90,7 @@ Every plugin is a self-contained folder under `server/nodes/<group>/<plugin>/` r
### 1. Use Existing Patterns - No Tribal Code
- **Never add ad-hoc workarounds** - Use the established patterns documented in DESIGN.md
- **Conductor Decide Pattern** - All orchestration goes through `_workflow_decide()` loop
-- **Fork/Join Parallelism** - Use `asyncio.gather()` for concurrent node execution
+- **Continuous Scheduling** - Dependent nodes start immediately via `asyncio.wait(FIRST_COMPLETED)`; the layer-barrier Fork/Join helper (`_execute_parallel_nodes`) was removed
- **Prefect Task Caching** - Cache results via `hash_inputs()` and `generate_cache_key()`
- **Distributed Locking** - Use Redis SETNX pattern for concurrent access control
@@ -134,7 +134,7 @@ server/services/
│ # nodes/agent/claude_code_agent/_oauth.py — CLAUDE_CONFIG_DIR=<DATA_DIR>/claude/)
├── tracked_http.py # HTTPX event hooks for automatic API cost tracking
├── whatsapp_service.py # WhatsApp RPC proxy helpers (used by nodes/whatsapp/*, not an APIRouter)
-├── handlers/ # Cross-cutting orchestration only (Wave 11: 16 → 3 files, 12.8K → 1.1K LOC)
+├── handlers/ # Cross-cutting orchestration only (Wave 11: 16 → 4 files, 12.8K → 1.1K LOC)
│ ├── tools.py # AI-tool dispatch + agent delegation (~821 LOC)
│ ├── triggers.py # Generic event-trigger handler
│ ├── todo.py # writeTodos execution shim (used by every agent)
@@ -143,7 +143,6 @@ server/services/
│ ├── __init__.py # Public API exports
│ ├── protocol.py # ThinkingConfig, Message, LLMResponse, LLMProvider Protocol
│ ├── config.py # ProviderConfig, resolve_max_tokens, resolve_temperature
-│ ├── factory.py # create_provider() lazy-import factory
│ ├── registry.py # ProviderSpec + register_provider — sdk_exception_refs are LAZY "module:Class" strings resolved via pkgutil.resolve_name at except/read time; NEVER import an SDK at registration (locked by tests/llm/test_lazy_sdk_imports.py)
│ ├── unifier.py # ChatUnifier facade — routes chat/fetch_models, translates typed SDK errors → NodeUserError, applies incompatible_models filter
│ ├── vertex.py # Vertex / Agent-Platform key handling
@@ -225,8 +224,8 @@ Persistent Node.js server for JavaScript/TypeScript code execution, replacing su
│ ▲ │
│ │ │
│ ┌──────┴─────────┐ │
-│ │ code.py │ │
-│ │ handlers │ │
+│ │ nodes/code/ │ │
+│ │ plugins │ │
│ └────────────────┘ │
└─────────────────────────────────────────────────────────────┘
```
@@ -242,9 +241,9 @@ server/nodejs/
└── package.json
server/services/
-├── nodejs_client.py # Async HTTP client for Node.js server
-└── handlers/
- └── code.py # handle_javascript_executor, handle_typescript_executor
+└── nodejs_client.py # Async HTTP client for Node.js server
+
+server/nodes/code/ # Executor plugins (javascript_executor, typescript_executor)
```
**Endpoints:**
@@ -688,7 +687,7 @@ Node groups (palette categories): agent, model, skill, tool, trigger, workflow,
### Temporal Distributed Execution
-Workflows execute via Temporal for durability and horizontal scaling, gated by `TEMPORAL_ENABLED`. Three dispatch paths exist — legacy single `execute_node_activity` (fallback), per-type `node.{type}.v{version}` activities (F4.A, `TEMPORAL_PER_TYPE_DISPATCH=true`), and Agent-as-child-workflow (F4.B, `TEMPORAL_AGENT_WORKFLOW_ENABLED=true`) — with `rlm_agent`/`claude_code_agent` always bypassing AgentWorkflow. **Per-queue activity routing is production-default (Wave 16)**: a `TemporalWorkerPool` runs one activity-only worker per plugin-declared `cls.task_queue` (ai-heavy / browser / code-exec / rest-api / messaging / ...) with per-queue concurrency + rate limits + resource-based tuning for ai-heavy/browser; rollback via `TEMPORAL_WORKER_POOL_ENABLED=false`. Resilience knobs (Waves 17-18): `DEPLOYMENT_MODE` (local halves concurrency; sizes the sticky cache), one-shot retry on `agent.execute_llm_step.v1` (LLM calls are not idempotent), observability interceptors (`activity_retry` WARN on re-dispatch), 30s periodic heartbeat during long activity bodies, cron `catchup_window=24h`, poller autoscaling. Execution routing falls back Temporal → Redis-parallel → sequential; the Temporal dev server + embedded worker are managed in-process under `server/services/temporal/` (pooch-downloaded CLI, single `temporal server start-dev` process, gRPC 7233 + Web UI 8080, SQLite at `~/.opencompany/temporal.db`). Full architecture, dispatch matrix, per-node + agent-loop lifecycle, the 7 F4.B `agent.*.v1` activities, heartbeat semantics, delegation input contract, resumption toggle (`TEMPORAL_TERMINATE_RUNNING_ON_STARTUP`), the worker tuning recipe, and all `.env` tunables live in [docs-internal/TEMPORAL_ARCHITECTURE.md](./docs-internal/TEMPORAL_ARCHITECTURE.md).
+Workflows execute via Temporal for durability and horizontal scaling, gated by `TEMPORAL_ENABLED`. Three dispatch paths exist — legacy single `execute_node_activity` (fallback), per-type `node.{type}.v{version}` activities (F4.A, `TEMPORAL_PER_TYPE_DISPATCH=true`), and Agent-as-child-workflow (F4.B, `TEMPORAL_AGENT_WORKFLOW_ENABLED=true`) — with `rlm_agent`/`claude_code_agent` always bypassing AgentWorkflow. **Per-queue activity routing is production-default (Wave 16)**: a `TemporalWorkerPool` runs one activity-only worker per plugin-declared `cls.task_queue` (ai-heavy / browser / code-exec / rest-api / messaging / ...) with per-queue concurrency + rate limits + resource-based tuning for ai-heavy/browser; rollback via `TEMPORAL_WORKER_POOL_ENABLED=false`. Resilience knobs (Waves 17-18): `DEPLOYMENT_MODE` (local halves concurrency; sizes the sticky cache), one-shot retry on `agent.execute_llm_step.v1` (LLM calls are not idempotent), observability interceptors (`activity_retry` WARN on re-dispatch), 30s periodic heartbeat during long activity bodies, cron `catchup_window=24h`, poller autoscaling. Execution routing falls back Temporal → sequential; the Temporal dev server + embedded worker are managed in-process under `server/services/temporal/` (pooch-downloaded CLI, single `temporal server start-dev` process, gRPC 7233 + Web UI 8080, SQLite at `~/.opencompany/temporal.db`). Full architecture, dispatch matrix, per-node + agent-loop lifecycle, the 7 F4.B `agent.*.v1` activities, heartbeat semantics, delegation input contract, resumption toggle (`TEMPORAL_TERMINATE_RUNNING_ON_STARTUP`), the worker tuning recipe, and all `.env` tunables live in [docs-internal/TEMPORAL_ARCHITECTURE.md](./docs-internal/TEMPORAL_ARCHITECTURE.md).
**Temporal tracing ownership is strict.** Register the SDK `TracingInterceptor` exactly once on the shared `Client.connect(...)`; the Python SDK automatically prepends compatible client interceptors to every worker. Never repeat `TracingInterceptor` in `Worker(..., interceptors=...)`. Worker lists contain the distinct `ObservabilityWorkerInterceptor` and plugin-specific worker interceptors only. Exact paired `StartActivity` / `RunActivity` / `CompleteWorkflow` console spans with identical Temporal identities indicate duplicate instrumentation, not duplicate execution; use Temporal Event History and the `node.<type>.execute` application span to verify actual attempts. See the tracing and debugging sections in [TEMPORAL_ARCHITECTURE.md](./docs-internal/TEMPORAL_ARCHITECTURE.md) and [errors.md](./docs-internal/errors.md).
@@ -707,31 +706,16 @@ company help # Show all commands
### npm Scripts
```bash
-# Core
-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
-
-# Docker (development)
-npm run docker:up # Start dev stack
-npm run docker:down # Stop dev stack
-npm run docker:build # Build images
-npm run docker:logs # View logs
-
-# Docker (production)
-npm run docker:prod:up # Start production
-npm run docker:prod:down # Stop production
-npm run deploy # Deploy to server
+# Core (thin wrappers over the Python CLI)
+npm run start # Start all services (python -m cli start)
+npm run stop # Stop all services (python -m cli stop)
+npm run build # Build for production (python -m cli build)
+npm run clean # Clean build artifacts (python -m cli clean)
+npm run deploy # Self-deploy to a cloud VM (python -m cli deploy)
```
### Cross-Platform Scripts
-All scripts in `scripts/` are cross-platform Node.js (Windows, macOS, Linux, WSL, Git Bash):
-- `start.js` - Starts services, auto-installs deps, frees ports
-- `stop.js` - Kills processes on configured ports
-- `build.js` - Full production build (client, Python, WhatsApp)
-- `clean.js` - Removes node_modules, dist, .venv
-- `docker.js` - Docker Compose wrapper with v2 detection and Redis profile support
+Service orchestration lives in the Python CLI (`company start/dev/stop/build/clean/serve/daemon/deploy/docs/version` — see `cli/`). The `scripts/` directory retains only the npm install lifecycle helpers (`install.js`, `preinstall.js`, `postinstall.js`) and `serve-client.js`.
See **[Scripts Reference](./docs-internal/SCRIPTS.md)** for full documentation.
@@ -1157,6 +1141,8 @@ VM (new deployments use the `opencompany` resource id), firewall, artifact bucke
account, and a cloud-init startup script that installs Node 22 + uv + the package and runs
`company serve` under systemd. Login gate = built-in auth (`VITE_AUTH_ENABLED=true`,
`AUTH_MODE=single`) with the owner credential generated at deploy time and seeded on first boot.
+`build_app_env` (`cli/commands/deploy/_secrets.py`) also sets `DEPLOYMENT_MODE=cloud` on
+deployed VMs and mints fresh `JWT_SECRET_KEY` / `SECRET_KEY` / `API_KEY_ENCRYPTION_KEY` per deploy.
```bash
company deploy up --provider gcp --owner-email [email protected] # provision + install + print URL/creds
@@ -1459,11 +1445,10 @@ Tool nodes display execution status via the standard node status system:
| braveSearch | BraveSearchSchema | `handle_brave_search()` | Brave Search API web results |
| serperSearch | SerperSearchSchema | `handle_serper_search()` | Google SERP via Serper API |
| perplexitySearch | PerplexitySearchSchema | `handle_perplexity_search()` | AI-powered search with citations |
-| androidTool | AndroidToolSchema | `_execute_android_toolkit()` | Android device control via connected services |
| Android service nodes | Per-service schema | `_execute_android_service()` | Direct Android service tools (see below) |
### Direct Android Service Tools
-Android service nodes (batteryMonitor, wifiAutomation, etc.) can be connected directly to any agent's `input-tools` handle without using the androidTool aggregator. The `execute_tool()` function detects these via `ANDROID_SERVICE_NODE_TYPES` and routes to `_execute_android_service()`.
+Android service nodes (batteryMonitor, wifiAutomation, etc.) connect directly to any agent's `input-tools` handle — this is the only Android tool path (the former `androidTool` aggregator was retired; legacy graphs are migrated on load by `workflow_migrations.normalize_legacy_android_toolkit`). The `execute_tool()` function detects these via `ANDROID_SERVICE_NODE_TYPES` and routes to `_execute_android_service()`.
**Service ID Mapping** (camelCase node type -> snake_case service ID):
```python
@@ -1487,31 +1472,15 @@ service_id_map = {
}
```
-### Android Toolkit Pattern
-The androidTool follows n8n Sub-Node and LangChain Toolkit patterns:
-- **Gateway Pattern**: Single tool node aggregates multiple Android service nodes
-- **Dynamic Schema**: Schema built at runtime from connected services only
-- **Service Routing**: Tool execution routes to appropriate connected Android node
-
-```
-[Battery Monitor] --+
- +--> [Android Toolkit] --> [AI Agent]
-[WiFi Automation] --+
-```
+### Android Toolkit Pattern (retired)
+The former `androidTool` gateway node (single `android_device` tool aggregating multiple Android service nodes, n8n Sub-Node / LangChain Toolkit pattern) no longer exists. Android service nodes connect straight to `input-tools`, and sub-node exclusion keys solely on AI-agent config handles (`input-memory` / `input-tools` / `input-skill` / `input-teammates`) — the `TOOLKIT_NODE_TYPES` constant was deleted along with all its usage sites. Legacy `service -> androidTool -> agent` graphs are rewritten on load by `services/workflow_migrations.normalize_legacy_android_toolkit`.
-The AI sees a single `android_device` tool with schema showing only connected services:
-- `service_id`: Which service to use (e.g., "battery", "wifi_automation")
-- `action`: Action to perform (e.g., "status", "enable", "disable")
-- `parameters`: Action-specific parameters
-
-### Tool Schema Editor
-The Android Toolkit node includes a schema editor UI for customizing the LLM-visible schema of connected services.
+### Tool Schemas (per-service customization)
+Custom LLM-visible schemas for Android service tools persist in the `tool_schemas` table and are read by the AI service at execution time. (The `ToolSchemaEditor.tsx` UI component shipped with the retired Android Toolkit node and was removed with it; the `useToolSchema` hook, WebSocket handlers, and database CRUD remain.)
#### Architecture
```
-ToolSchemaEditor Component
- ↓
- useToolSchema Hook (WebSocket CRUD)
+useToolSchema Hook (WebSocket CRUD)
↓
Database (tool_schemas table)
↓
@@ -1521,7 +1490,6 @@ ToolSchemaEditor Component
#### Key Files
| File | Description |
|------|-------------|
-| `client/src/components/parameterPanel/ToolSchemaEditor.tsx` | Schema editor UI component |
| `client/src/hooks/useToolSchema.ts` | WebSocket hook for schema CRUD operations |
| `server/models/database.py` | `ToolSchema` SQLModel table definition |
| `server/core/database.py` | Database CRUD methods for tool schemas |
@@ -1535,15 +1503,9 @@ class ToolSchema(SQLModel, table=True):
tool_name: str # Display name (e.g., "Battery Monitor")
tool_description: str # Description shown to LLM
schema_config: Dict # Schema fields and types (JSON)
- connected_services: Optional[Dict] # For toolkit aggregation
+ connected_services: Optional[Dict] # Legacy field from the retired toolkit aggregation
```
-#### UI Features
-- **Service Selector**: Dropdown showing only Android service nodes connected to the toolkit
-- **Schema Fields Editor**: Add/remove/edit fields with name, type, description, required flag
-- **Per-Service Schema**: Each connected service has its own independent schema stored by service node ID
-- **Save/Reset**: Changes tracked locally, saved to database on demand
-
#### WebSocket Messages
| Message Type | Description |
|--------------|-------------|
@@ -1649,48 +1611,11 @@ The `isConfigNode` flag is **auto-derived on the backend** by `_derive_auto_ui_h
2. Use `input-<type>` naming for the target handle on the parent node.
3. Input inheritance and filtering work automatically — the frontend reads `definition.uiHints.isConfigNode`, never the group strings.
-### Toolkit Sub-Node Execution Pattern
-
-Toolkit nodes (like `androidTool`) aggregate sub-nodes that should only execute when called via the toolkit's tool interface, not as independent workflow nodes.
-
-**Problem**: In parallel execution mode, Kahn's algorithm schedules nodes with in-degree 0 first. Sub-nodes connect TO the toolkit (not from it), so they have in-degree 0 and would be incorrectly scheduled in layer 0.
+### Sub-Node Execution Exclusion
-**Solution**: The executor detects and excludes toolkit sub-nodes from execution layers.
+Sub-nodes (tools, memory, skills, teammates) connect TO an agent, not from it, so in parallel execution mode Kahn's algorithm would see them with in-degree 0 and incorrectly schedule them in layer 0. The executor excludes them: any node whose edge targets an AI-agent config handle (`input-memory`, `input-tools`, `input-skill`, `input-teammates`) is detected as a sub-node in `ExecutionContext.create()` / `_compute_execution_layers()` and skipped from execution layers — it executes only when the agent invokes it (e.g. as an AI tool).
-**Key Constants** (`server/constants.py`):
-```python
-# Toolkit node types that aggregate sub-nodes
-TOOLKIT_NODE_TYPES: FrozenSet[str] = frozenset([
- 'androidTool', # Aggregates Android service nodes
-])
-
-# Config nodes excluded from execution (includes tool nodes)
-CONFIG_NODE_TYPES: FrozenSet[str] = (
- AI_MEMORY_TYPES | AI_TOOL_TYPES | AI_CHAT_MODEL_TYPES
-)
-```
-
-**Detection Logic** (in `ExecutionContext.create()` and `_compute_execution_layers()`):
-```python
-# Find toolkit sub-nodes (nodes that connect TO a toolkit)
-toolkit_node_ids = {n.get("id") for n in nodes if n.get("type") in TOOLKIT_NODE_TYPES}
-subnode_ids: set = set()
-for edge in edges:
- source = edge.get("source")
- target = edge.get("target")
- # Any node that connects TO a toolkit is a sub-node
- if target in toolkit_node_ids and source:
- subnode_ids.add(source)
-```
-
-**Example Workflow**:
-```
-[WhatsApp Trigger] → [AI Agent] ← [Android Toolkit] ← [Battery Monitor]
- ← [Location]
-```
-- `Battery Monitor` and `Location` connect TO `Android Toolkit`
-- They are detected as sub-nodes and excluded from execution layers
-- They only execute when AI Agent calls the toolkit's tool interface
+Toolkit aggregator nodes (the former `androidTool` and its `TOOLKIT_NODE_TYPES` constant) were retired; Android service nodes now connect directly to the agent's `input-tools` handle. Legacy `service -> androidTool -> agent` graphs are migrated on load by `services/workflow_migrations.normalize_legacy_android_toolkit` (pure, idempotent: services re-wire directly to each agent, orphaned toolkits are removed with a warning).
## Android Services Development Guide
@@ -1721,7 +1646,7 @@ Adding a new Android service:
shared ADB infrastructure lives in `AndroidService`.
### Key Files
-- **Shared base**: `server/nodes/android/_base.py` — `AndroidServiceBase`, `SERVICE_ID_MAP`, `execute_android_toolkit`, `execute_android_service_tool`
+- **Shared base**: `server/nodes/android/_base.py` — `AndroidServiceBase`, `SERVICE_ID_MAP`, `execute_android_service_tool`
- **Backend Router**: `server/routers/android.py` - API endpoints for Android operations
- **Workflow Handler**: `server/services/workflow.py` - Execution logic for all nodes
- **Execution Service**: `src/services/executionService.ts` - Routes Android nodes to Python backend
@@ -2711,11 +2636,7 @@ This function:
- `server/models/cache.py` - CacheEntry SQLModel for SQLite persistence
- `server/core/database.py` - Cache CRUD methods (get/set/delete/cleanup)
- Supports TTL expiration and automatic cleanup of expired entries
-- **Conditional Redis with Docker Profiles**: Redis container only starts when explicitly enabled
- - Uses Docker Compose profiles: Redis service has `profiles: [redis]`
- - `scripts/docker.js` wrapper auto-adds `--profile redis` when `REDIS_ENABLED=true` in `.env`
- - npm scripts (`docker:up`, `docker:down`, etc.) use the wrapper for seamless handling
- - Backend no longer depends on Redis - depends only on WhatsApp service
+- **Conditional Redis (historical)**: the Docker Compose topology (Redis profiles, `scripts/docker.js` wrapper) is historical — see [docs-internal/deployment_legacy.md](./docs-internal/deployment_legacy.md)
- **WebSocket Reconnect via PartySocket** (`partysocket/ws` from Cloudflare): native-WS-compatible class handles jittered exponential backoff, message replay (`maxEnqueuedMessages: 200`), and intentional-close (RFC 6455 §7.4.1 code 1000) automatically. Replaces the previous flat 3 s `setTimeout(connect, 3000)` loop. Reconnect envelope (`MIN_DELAY_MS: 250`, `MAX_DELAY_MS: 8000`, `GROW_FACTOR: 1.3`) lives in `client/src/lib/connectionConfig.ts`. The +12 s WS-drop-and-reconnect cycle observed under React Strict Mode is gone — verified across two consecutive cold launches with zero `Client disconnected` events through 130+ s of activity. See `docs-internal/performance.md` for measurements.
- **Docker Backend Fix**: Backend container uses Python uvicorn directly
- Changed from `npm run start` (failed - npm not in Python image) to `python -m uvicorn`
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index d2075ecd..c85ac9a4 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -22,13 +22,13 @@ At a glance:
- **Specialized AI agents** with the Agent Teams delegation pattern — SSOT is the `AI_AGENT_TYPES` frozenset in `server/constants.py`, which spans the base/specialized/team-lead agents plus the CLI-backed (`claude_code_agent`, `rlm_agent`) and Vertex-hosted (`vertex_managed_agent`) variants; `codex_agent` is a sibling CLI-agent plugin
- **WebSocket-first API** replacing most REST endpoints (live handler count = `MESSAGE_HANDLERS` + plugin registries)
- **65+ built-in skills**, editable in-UI with SKILL.md defaults on disk (live count: glob `server/skills/**/SKILL.md`)
-- **Three execution modes** with automatic fallback: Temporal distributed, Redis parallel, sequential
+- **Two execution modes** with automatic fallback: Temporal distributed, sequential
## How Workflows Execute
[![Execution Flow](docs/diagrams/execution-flow.svg)](https://raw.githubusercontent.com/zeenie-ai/OpenCompany/main/docs/diagrams/execution-flow.svg)
-[WorkflowService](server/services/workflow.py) is a thin facade that routes each run through one of three execution modes. Every run has an isolated `ExecutionContext` with no shared global state, orchestrated by Conductor's decide pattern (`_workflow_decide` under a Redis `SETNX` lock). Layers are computed via Kahn's algorithm and each layer runs via `asyncio.gather()`. Results are cached by input hash (Prefect pattern), failed nodes go to a Dead Letter Queue, and a `RecoverySweeper` handles crashes via heartbeats.
+[WorkflowService](server/services/workflow.py) is a thin facade that routes each run through Temporal when available, falling back to a plain sequential walk otherwise. Every run has an isolated `ExecutionContext` with no shared global state. Nodes are scheduled continuously — when any node completes, its newly-ready dependents start immediately (`FIRST_COMPLETED` pattern) instead of waiting for a whole layer to finish.
Deep dives: [DESIGN.md](docs-internal/DESIGN.md) - [TEMPORAL_ARCHITECTURE.md](docs-internal/TEMPORAL_ARCHITECTURE.md) - [event_framework.md](docs-internal/event_framework.md)
@@ -74,7 +74,7 @@ The diagram above shows the full lifecycle of a workflow node: one self-containe
**Add an LLM provider**
- Guide: [native_llm_sdk.md](docs-internal/native_llm_sdk.md) → "Adding a New Provider"
- OpenAI-compatible (DeepSeek, Kimi, Mistral pattern): config-only in `server/config/llm_defaults.json` + the compat list in `services/llm/providers/_compat.py`
-- Custom-SDK provider: new file in `server/services/llm/providers/` that calls `register_provider(ProviderSpec(...))` at module bottom (lazy factory + `sdk_exception_refs`; never touch the legacy `factory.py`)
+- Custom-SDK provider: new file in `server/services/llm/providers/` that calls `register_provider(ProviderSpec(...))` at module bottom (lazy factory + `sdk_exception_refs`; the legacy `factory.py` was removed — `register_provider` is the only entry point)
- Chat-model node plugin: `server/nodes/model/<provider>_chat_model/__init__.py`; for agent-dropdown exposure also extend the `provider` Literal in `nodes/agent/{ai_agent,chat_agent,_specialized}` and `detect_ai_provider` in `server/constants.py`
**Add a dual-purpose tool (workflow node + AI tool)**
diff --git a/client/src/contexts/WebSocketContext.tsx b/client/src/contexts/WebSocketContext.tsx
index 7f5a0fe3..c2be66ec 100644
--- a/client/src/contexts/WebSocketContext.tsx
+++ b/client/src/contexts/WebSocketContext.tsx
@@ -333,10 +333,11 @@ interface WebSocketContextValue {
// Connection state
isConnected: boolean;
/**
- * `true` once the socket is open AND the post-open init burst has
- * settled (api-key probes, terminal/chat/console history). Queries
- * that depend on backend-served data should gate on this rather
- * than `isConnected` so they fire once instead of racing the burst.
+ * `true` once the socket is open and the pending-send queue has
+ * drained (Wave 32: flips immediately on open — history restores run
+ * as background fire-and-forget; the api-key probe loop was removed).
+ * Queries that depend on backend-served data should gate on this
+ * rather than `isConnected` so queued sends replay first.
*/
isReady: boolean;
reconnecting: boolean;
diff --git a/docs-internal/DESIGN.md b/docs-internal/DESIGN.md
index 1fb6ecd0..5135e4c2 100644
--- a/docs-internal/DESIGN.md
+++ b/docs-internal/DESIGN.md
@@ -21,7 +21,7 @@ Related docs:
## Execution Modes
-`WorkflowService` in `server/services/workflow.py` is a thin facade (~460 lines) that routes every workflow run through one of three execution modes. Selection is based on available infrastructure:
+`WorkflowService` in `server/services/workflow.py` is a thin facade (~460 lines) that routes every workflow run based on available infrastructure. In every shipped configuration the effective routing is Temporal -> sequential:
```
workflow.execute(workflow_id, workflow_data)
@@ -33,20 +33,9 @@ workflow.execute(workflow_id, workflow_data)
+---------------------+ v
| no TemporalExecutor
v (per-node activities,
- +---------------------+ retries, horizontal scaling)
- | Redis available? |
- +---------------------+
- | yes --> _execute_parallel()
- | |
- v v
- | WorkflowExecutor
- | (decide loop, Kahn layers,
- | distributed locking)
- |
- | no --> _execute_sequential()
- v
- Sequential fallback
- (simple topological walk)
+ _execute_sequential() retries, horizontal scaling)
+ Sequential fallback
+ (simple topological walk)
```
### 1. Temporal Distributed (primary production mode)
@@ -55,21 +44,21 @@ When `TEMPORAL_ENABLED=true` and the Temporal server is reachable, every workflo
Full dispatch matrix + activity inventory (legacy + per-type + the 5 F4.B agent activities) + worker configuration + heartbeat semantics live in [TEMPORAL_ARCHITECTURE.md](TEMPORAL_ARCHITECTURE.md). Tool-call dispatch under F4.A: [tool_building_pipeline.md §9](./tool_building_pipeline.md).
-### 2. Parallel Local (Redis)
+### 2. Sequential Fallback
+
+When Temporal is not available, workflow execution falls back to a simple topological walk with no parallelism, no caching, and no retry. Intended only for minimal environments and CI smoke tests.
-When Temporal is not enabled but Redis is available, workflows use `WorkflowExecutor` in `services/execution/executor.py`:
+### Redis-parallel branch (unreachable in shipped configs)
+
+`workflow.py` still contains a `_execute_parallel()` branch that routes to `WorkflowExecutor` in `services/execution/executor.py` when Redis is enabled:
- Conductor's decide pattern in `_workflow_decide()` under distributed Redis SETNX locks
-- Fork/join via `asyncio.gather()` for concurrent node execution
+- Continuous scheduling via `asyncio.wait(FIRST_COMPLETED)` (`_execute_with_continuous_scheduling` — the only scheduling implementation; the legacy Fork/Join `_execute_parallel_nodes` helper was removed)
- Prefect-style result caching keyed by `hash_inputs()` (see `services/execution/cache.py`)
- Crash recovery via `RecoverySweeper` with heartbeats
- Dead Letter Queue for failed nodes (`services/execution/dlq.py`)
-This is the local-development default when `REDIS_ENABLED=true` is set in `server/.env`.
-
-### 3. Sequential Fallback
-
-When neither Temporal nor Redis is available, workflow execution falls back to a simple topological walk with no parallelism, no caching, and no retry. Intended only for minimal environments and CI smoke tests.
+No shipped configuration sets `REDIS_ENABLED=true`, so this branch is unreachable in practice; treat Temporal -> sequential as the routing contract.
---
@@ -144,17 +133,12 @@ async def _workflow_decide(self, ctx: ExecutionContext):
if not ready_nodes:
return # All done or stuck
- # 2. Execute batch (parallel if multiple)
- if len(ready_nodes) > 1:
- await self._execute_parallel_nodes(ctx, ready_nodes)
- else:
- await self._execute_single_node(ctx, ready_nodes[0])
+ # 2. Execute with continuous scheduling -- newly-ready
+ # dependents start as soon as their dependency completes
+ await self._execute_with_continuous_scheduling(ctx, ready_nodes)
# 3. Checkpoint and persist
await self.cache.save_execution_state(ctx)
-
- # 4. Recurse for next batch
- await self._decide_iteration(ctx)
```
**Benefits**:
@@ -163,27 +147,28 @@ async def _workflow_decide(self, ctx: ExecutionContext):
- Natural support for parallel execution
- Easy to add features (retries, timeouts)
-### 2. Fork/Join Parallel Execution
+### 2. Continuous Scheduling (Temporal/Conductor Pattern)
-**Source**: Netflix Conductor + Java ForkJoinPool
+**Source**: Temporal + Netflix Conductor
-Independent nodes (no dependencies on each other) execute in parallel using `asyncio.gather()`.
+Independent nodes execute in parallel, and each completion immediately unlocks its dependents — no layer barrier. `_execute_with_continuous_scheduling` is the only scheduling implementation (the earlier layer-based Fork/Join helper `_execute_parallel_nodes`, which `asyncio.gather()`-ed a whole batch and waited for all of it, was removed as dead code).
```python
-async def _execute_parallel_nodes(self, ctx, nodes):
- """Fork/Join pattern with asyncio.gather."""
- tasks = [
- self._execute_node_with_caching(ctx, node)
- for node in nodes
- ]
-
- # True parallelism - all tasks run concurrently
- results = await asyncio.gather(*tasks, return_exceptions=True)
-
- # Join - process all results
- for node, result in zip(nodes, results):
- if isinstance(result, Exception):
- ctx.status = WorkflowStatus.FAILED
+async def _execute_with_continuous_scheduling(self, ctx, initial_nodes):
+ """When any node completes, immediately start newly-ready dependents."""
+ task_to_node = {
+ asyncio.create_task(self._execute_node_with_caching(ctx, n)): n
+ for n in initial_nodes
+ }
+
+ while task_to_node:
+ done, _ = await asyncio.wait(task_to_node, return_when=asyncio.FIRST_COMPLETED)
+ for task in done:
+ node = task_to_node.pop(task)
+ # ... record result, then start any newly-ready dependents
+ for ready in self._find_ready_nodes(ctx):
+ task_to_node[asyncio.create_task(
+ self._execute_node_with_caching(ctx, ready))] = ready
```
**DAG Layer Computation** (Kahn's Algorithm):
diff --git a/docs-internal/ROADMAP.md b/docs-internal/ROADMAP.md
index c6d8b4b6..cc4c0e86 100644
--- a/docs-internal/ROADMAP.md
+++ b/docs-internal/ROADMAP.md
@@ -19,7 +19,7 @@ This document tracks the implementation status of the robust workflow execution
### Phase 2: Decide Pattern + Parallel Execution
- [x] `workflow_decide()` with distributed locking (Conductor pattern)
-- [x] `execute_parallel_nodes()` using `asyncio.gather()` for Fork/Join
+- [x] `execute_parallel_nodes()` using `asyncio.gather()` for Fork/Join (since removed; superseded by continuous scheduling via `asyncio.wait(FIRST_COMPLETED)`)
- [x] `_compute_execution_layers()` for DAG topological sort
- [x] `_find_ready_nodes()` to detect nodes with satisfied dependencies
- [x] Redis distributed locks via SETNX with TTL
@@ -322,7 +322,7 @@ class DLQEntry:
- `_execute_node_with_retry()` - Wraps node execution with retry loop
- `_add_to_dlq()` - Adds failed nodes to DLQ after exhausted retries
- `replay_dlq_entry()` - Re-execute failed node from DLQ
-- `_execute_parallel_nodes()` - Updated to use retry wrapper
+- `_execute_parallel_nodes()` - Updated to use retry wrapper (helper since removed; continuous scheduling is the only implementation)
- `_execute_single_node()` - Updated to use retry wrapper
#### WebSocket API Handlers (`server/routers/websocket.py`)
@@ -388,8 +388,9 @@ TEMPORAL_TASK_QUEUE=machina-tasks
#### 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)
+2. Else -> `_execute_sequential()` (fallback)
+
+(The Redis-parallel `_execute_parallel()` branch is unreachable in all shipped configs; effective routing is Temporal -> sequential.)
---
@@ -407,7 +408,7 @@ TEMPORAL_TASK_QUEUE=machina-tasks
| AI Chat Models | 6 | openai, anthropic, gemini, openrouter, groq, cerebras |
| AI Agents & Memory | 3 | aiAgent, chatAgent, simpleMemory |
| AI Skills | 9 | claude, whatsapp, memory, maps, http, scheduler, android, code, custom |
-| AI Tools | 4 | calculator, currentTime, webSearch, androidTool |
+| AI Tools | 4 | calculator, currentTime, webSearch, androidTool (androidTool since retired; services connect directly to `input-tools`) |
| Android Services | 16 | battery, network, system, location, apps(2), automation(6), sensors(2), media(2) |
| Android Device | 1 | androidDeviceSetup |
| WhatsApp | 4 | send, connect, receive, chatHistory |
diff --git a/docs-internal/SCRIPTS.md b/docs-internal/SCRIPTS.md
index ab74ba9f..0a64403f 100644
--- a/docs-internal/SCRIPTS.md
+++ b/docs-internal/SCRIPTS.md
@@ -24,7 +24,7 @@ deprecation warning; kept for upgrade compatibility).
| `company dev` | Start in dev mode (Vite HMR + uvicorn + temporal). `--force` re-bundles Vite deps (recovers "Outdated Optimize Dep"); `--daemon` binds backend to 0.0.0.0 |
| `company serve` | Single-port production runtime (uvicorn serves API + WS + built SPA + Node sidecar) — the systemd `ExecStart` on deployed VMs |
| `company stop` | Stop all services and free configured ports |
-| `company build` | Full production build (pnpm install → client → sidecar → uv sync → bytecode → temporal binary) |
+| `company build` | Full production build (pnpm install → client → sidecar → uv sync → bytecode → temporal binary). Step [0/6] scaffolds `.env` from `.env.template` when missing, generating fresh random secrets (`secrets.token_hex(24)`) for `SECRET_KEY` / `JWT_SECRET_KEY` / `API_KEY_ENCRYPTION_KEY` instead of the dev placeholders; an existing `.env` is untouched |
| `company clean` | Stop services, then remove build artifacts, node_modules, `.venv`, repo-local state (preserves `.opencompany/{workflows,deploy,packages}`) |
| `company deploy up/status/destroy` | Self-deploy a login-gated VM (gcloud preflight + Terraform; see `cli/commands/deploy/`) |
| `company daemon start/stop/status/restart` | Detached backend management (PID file under user data dir) |
diff --git a/docs-internal/SETUP.md b/docs-internal/SETUP.md
index a9ac49d5..eb760337 100644
--- a/docs-internal/SETUP.md
+++ b/docs-internal/SETUP.md
@@ -102,6 +102,8 @@ Copy the example environment file:
cp .env.example .env
```
+Alternatively, `company build` scaffolds `.env` from `.env.template` automatically when it is missing (step `[0/6]`) and generates fresh random secrets for `SECRET_KEY` / `JWT_SECRET_KEY` / `API_KEY_ENCRYPTION_KEY` instead of the dev placeholders. An existing `.env` is never modified. If you copy the template by hand and later enable auth (or set `DEPLOYMENT_MODE` to anything other than `local`), the server logs a non-fatal error banner at startup until the placeholder secrets are replaced.
+
### Key Settings
| Variable | Default | Description |
diff --git a/docs-internal/TEMPORAL_ARCHITECTURE.md b/docs-internal/TEMPORAL_ARCHITECTURE.md
index 3d8399b8..348f8340 100644
--- a/docs-internal/TEMPORAL_ARCHITECTURE.md
+++ b/docs-internal/TEMPORAL_ARCHITECTURE.md
@@ -20,11 +20,12 @@ Each workflow node executes as a **Temporal activity** with its own isolated con
## Execution Routing & Running
-`WorkflowService.execute_workflow` picks one of three executors in priority order (`server/services/workflow.py`):
+`WorkflowService.execute_workflow` routes each run (`server/services/workflow.py`):
1. If `TEMPORAL_ENABLED=true` and Temporal is configured → `_execute_temporal()` (the distributed path documented in this file).
-2. Else if Redis is available → `_execute_parallel()` (local parallel orchestration via `WorkflowExecutor`).
-3. Else → `_execute_sequential()` (single-threaded fallback).
+2. Else → `_execute_sequential()` (single-threaded fallback).
+
+(The Redis-backed `_execute_parallel()` branch still exists in the facade but is unreachable in all shipped configs — no shipped configuration enables Redis — so the effective routing is Temporal → sequential.)
**Running with Temporal** — the Temporal server and the embedded worker start automatically with every launch script:
@@ -298,7 +299,7 @@ Pre-flight invariants live in `server/tests/test_task_queue_coverage.py` (every
### Worker Performance Tuning (Waves 17-18)
-All knobs live in `services/temporal/worker.py`; every default is env-overridable. `DEPLOYMENT_MODE` (`local` / `cloud` / `self_hosted`) is the topology hint (`core/config.py`).
+All knobs live in `services/temporal/worker.py`; every default is env-overridable. `DEPLOYMENT_MODE` (`local` / `cloud` / `self_hosted`) is the topology hint (`core/config.py`) and also feeds the dev-placeholder-secret startup guard (`dev_secret_offenders()` warns when placeholders survive outside `local`). `company deploy` sets `DEPLOYMENT_MODE=cloud` on deployed VMs (`cli/commands/deploy/_secrets.py::build_app_env`).
| Queue | Concurrency (cloud) | Concurrency (local = halved, floor 1) | Rate limit (act/s) | Slot sizing |
|---|---|---|---|---|
@@ -560,7 +561,7 @@ The Temporal binary + persistence are managed in-process by the plugin-folder pa
| Setting | Env var | `.env.template` default | Purpose |
|---|---|---|---|
-| `temporal_enabled` | `TEMPORAL_ENABLED` | `true` | Master toggle. When false, `WorkflowService` falls back to parallel/sequential executor. |
+| `temporal_enabled` | `TEMPORAL_ENABLED` | `true` | Master toggle. When false, `WorkflowService` falls back to the sequential executor. |
| `temporal_server_address` | `TEMPORAL_SERVER_ADDRESS` | `localhost:7233` | Address the Python SDK client connects to. |
| `temporal_namespace` | `TEMPORAL_NAMESPACE` | `default` | Bootstrapped at server start. |
| `temporal_task_queue` | `TEMPORAL_TASK_QUEUE` | `machina-tasks` | Default task queue for the embedded worker. |
diff --git a/docs-internal/authentication.md b/docs-internal/authentication.md
index 8e23d99c..451c1c51 100644
--- a/docs-internal/authentication.md
+++ b/docs-internal/authentication.md
@@ -149,7 +149,12 @@ JWT_COOKIE_SAMESITE=lax
```
`core/config.py` carries the `vite_auth_enabled` field (required because
-Pydantic Settings uses `extra="forbid"`).
+Pydantic Settings uses `extra="forbid"`). It also exposes `DEV_SECRET_LITERALS`
+and `dev_secret_offenders()`: server startup (lifespan) logs a non-fatal error
+banner when `SECRET_KEY` / `JWT_SECRET_KEY` / `API_KEY_ENCRYPTION_KEY` still
+carry the dev template placeholders while auth is enabled or `DEPLOYMENT_MODE`
+is not `local`. A `company build`-scaffolded `.env` avoids this by generating
+fresh `secrets.token_hex(24)` values at scaffold time.
## Race Condition Handling (TanStack Query bootstrap)
The frontend starts before the backend is ready during cold launch, so the
diff --git a/docs-internal/credentials_encryption.md b/docs-internal/credentials_encryption.md
index b1af5cb5..58ecd9e7 100644
--- a/docs-internal/credentials_encryption.md
+++ b/docs-internal/credentials_encryption.md
@@ -183,6 +183,8 @@ AWS_REGION=us-east-1
If `API_KEY_ENCRYPTION_KEY` is missing or changed, existing ciphertext becomes undecryptable. There is no key-rotation mechanism today: users re-enter their keys after a key change. This is a deliberate simplification inherited from the n8n pattern.
+When `company build` scaffolds `.env` from `.env.template` (step `[0/6]`), it generates a fresh `secrets.token_hex(24)` value for `API_KEY_ENCRYPTION_KEY` (and `SECRET_KEY` / `JWT_SECRET_KEY`) instead of copying the dev placeholder; an existing `.env` is never touched. If the dev placeholder survives while auth is enabled or `DEPLOYMENT_MODE != local`, startup logs a non-fatal error banner (`dev_secret_offenders()` in `core/config.py`).
+
## Security Properties
- **Server-scoped key**: not tied to user login sessions. JWT cookies expire, but the encryption key survives across restarts.
diff --git a/docs-internal/deployment_legacy.md b/docs-internal/deployment_legacy.md
index 070fb1c0..e3abc779 100644
--- a/docs-internal/deployment_legacy.md
+++ b/docs-internal/deployment_legacy.md
@@ -20,7 +20,9 @@ One command provisions a login-gated OpenCompany VM on a cloud provider. Two sta
script that installs Node 22 + uv + the package and runs `company serve` under systemd.
Login gate = built-in auth (`VITE_AUTH_ENABLED=true`, `AUTH_MODE=single`) with the owner
-credential generated at deploy time and seeded on first boot.
+credential generated at deploy time and seeded on first boot. `build_app_env`
+(`cli/commands/deploy/_secrets.py`) also sets `DEPLOYMENT_MODE=cloud` on the VM and mints
+fresh `JWT_SECRET_KEY` / `SECRET_KEY` / `API_KEY_ENCRYPTION_KEY` per deploy.
```bash
company deploy up --provider gcp --owner-email [email protected] # provision + install + print URL/creds
diff --git a/docs-internal/design-system/assets/diagrams/system-overview.svg b/docs-internal/design-system/assets/diagrams/system-overview.svg
index 5c255d38..f2708010 100644
--- a/docs-internal/design-system/assets/diagrams/system-overview.svg
+++ b/docs-internal/design-system/assets/diagrams/system-overview.svg
@@ -70,7 +70,7 @@
<rect class="box p-purple" x="250" y="558" width="920" height="64" rx="8"/>
<text class="h2" x="710" y="584" text-anchor="middle">Execution engine</text>
- <text class="sub" x="710" y="607" text-anchor="middle">Temporal -&gt; Redis-parallel -&gt; sequential (auto-fallback)</text>
+ <text class="sub" x="710" y="607" text-anchor="middle">Temporal -&gt; sequential (auto-fallback)</text>
<!-- Backend -> Sidecars -->
<path class="conn" d="M 710 646 L 710 722" marker-end="url(#arrow)"/>
diff --git a/docs-internal/event_waiter_system.md b/docs-internal/event_waiter_system.md
index 06f79170..8f79cc79 100644
--- a/docs-internal/event_waiter_system.md
+++ b/docs-internal/event_waiter_system.md
@@ -13,7 +13,6 @@ Before this system, each trigger had its own ad-hoc waiting code. That meant:
- No common cancel path
- No common filter semantics
-- No way to persist waits across Temporal worker restarts
- No way to debug which triggers were active
A single waiter module replaces all of that. Adding a new trigger now means adding one entry to the registry and one filter builder.
@@ -31,7 +30,6 @@ class Waiter:
node_id: str # workflow node waiting
node_type: str # 'whatsappReceive', 'webhookTrigger', ...
event_type: str # 'whatsapp_message_received', ...
- params: Dict # node parameters (filter provenance)
filter_fn: Callable[[Dict], bool]
future: Optional[asyncio.Future] # resolved by dispatch() on match
cancelled: bool
@@ -143,7 +141,7 @@ Users can cancel a waiting trigger from the UI (Cancel button on the trigger nod
## Debugging
-`event_waiter.get_active_waiters()` returns a list of all currently active waiters with age, backend mode, and done/cancelled status. The `get_active_waiters` WebSocket handler exposes this to the frontend for the active-triggers debug view.
+`event_waiter.get_active_waiters()` returns a list of all currently active waiters with age and done/cancelled status. The `get_active_waiters` WebSocket handler exposes this to the frontend for the active-triggers debug view. (`get_backend_mode()` still exists for compatibility but always returns `"memory"` — the Redis-Streams backend was retired in Wave 15.3.)
```python
{
@@ -154,7 +152,7 @@ Users can cancel a waiting trigger from the UI (Cancel button on the trigger nod
"done": False,
"cancelled": False,
"age_seconds": 142.3,
- "mode": "redis" # or "memory"
+ "mode": "memory" # always "memory" since Wave 15.3
}
```
@@ -201,4 +199,4 @@ No changes are needed in the execution engine, cancel path, or deployment manage
- [DESIGN.md](DESIGN.md) - how triggers fit into execution
- [workflow-schema.md](workflow-schema.md) - trigger node catalog
-- [TEMPORAL_ARCHITECTURE.md](TEMPORAL_ARCHITECTURE.md) - why Redis mode exists for Temporal workers
+- [TEMPORAL_ARCHITECTURE.md](TEMPORAL_ARCHITECTURE.md) - how deployed triggers get durability from Temporal
diff --git a/docs-internal/gcp_vm_deploy_runbook.md b/docs-internal/gcp_vm_deploy_runbook.md
index d4526b49..7e893a41 100644
--- a/docs-internal/gcp_vm_deploy_runbook.md
+++ b/docs-internal/gcp_vm_deploy_runbook.md
@@ -125,6 +125,7 @@ HOST=0.0.0.0
DATA_DIR=/var/lib/opencompany
WORKSPACE_BASE_DIR=workspaces
VITE_AUTH_ENABLED=true
+DEPLOYMENT_MODE=cloud
AUTH_MODE=single
JWT_COOKIE_SECURE=true
JWT_COOKIE_SAMESITE=lax
diff --git a/docs-internal/litellm_router_migration_rfc.md b/docs-internal/litellm_router_migration_rfc.md
index 96689742..185a3025 100644
--- a/docs-internal/litellm_router_migration_rfc.md
+++ b/docs-internal/litellm_router_migration_rfc.md
@@ -621,10 +621,11 @@ natively by LiteLLM *and* enforced by our adapter regardless.)
**Phase 3 — delete dead code.**
- Delete: `providers/openai.py` (200), `anthropic.py` (203), `gemini.py` (268 — minus
the AQ. fallback if the contingency fired), `openrouter.py` (99), `_compat.py` (109),
- provider imports in `providers/__init__.py`, `factory.py` (75), the flag + legacy
- branch in `unifier.py`, and the `create_provider` / `is_native_provider` /
- `NATIVE_PROVIDERS` exports.
-- Tests: delete `test_providers.py` + `test_factory.py`; rewrite
+ provider imports in `providers/__init__.py`, the flag + legacy
+ branch in `unifier.py`. (`factory.py` and its `create_provider` /
+ `is_native_provider` / `NATIVE_PROVIDERS` exports were already deleted
+ independently of this RFC — ChatUnifier + registry is the only dispatch layer.)
+- Tests: delete `test_providers.py` (`test_factory.py` is already gone with `factory.py`); rewrite
`test_provider_self_registration.py` (data-driven registration) and the
provider-construction halves of `test_vertex_key.py` (detection + curated-list halves
survive); update `test_plugin_shape.py` grep-guards. Surviving unchanged:
diff --git a/docs-internal/native_llm_sdk.md b/docs-internal/native_llm_sdk.md
index 92e947d8..318ba626 100644
--- a/docs-internal/native_llm_sdk.md
+++ b/docs-internal/native_llm_sdk.md
@@ -26,7 +26,6 @@ server/services/llm/
|-- unifier.py ChatUnifier — the dispatch facade execute_chat delegates every provider to;
| translates typed SDK errors -> NodeUserError
|-- vertex.py Vertex / Agent-Platform key handling
-|-- factory.py LEGACY — create_provider()/NATIVE_PROVIDERS no longer consulted by ai.py
|-- messages.py filter_empty_messages, is_valid_message_content
`-- providers/
|-- __init__.py
@@ -61,7 +60,7 @@ The native layer currently supports **12 providers**, grouped by implementation:
| `groq` | `providers/_compat.py` + base_url | `openai` | OpenAI-compatible (chat-path LangChain fallback retired in Phase D) |
| `cerebras` | `providers/_compat.py` + base_url | `openai` | OpenAI-compatible (chat-path LangChain fallback retired in Phase D) |
-Source of truth for this list: `server/config/llm_defaults.json` (the `providers` dict) and the `register_provider(ProviderSpec(...))` calls in `server/services/llm/providers/` (each provider module registers itself at import; `factory.py` is legacy and no longer consulted by `ai.py`).
+Source of truth for this list: `server/config/llm_defaults.json` (the `providers` dict) and the `register_provider(ProviderSpec(...))` calls in `server/services/llm/providers/` (each provider module registers itself at import; the legacy `factory.py` was removed).
### Native chat path vs agent dropdown — two different counts
@@ -179,9 +178,9 @@ also owns error translation: typed SDK exceptions (resolved lazily from
with a user-correctable message. There is no per-provider branch anywhere
in `ai.py`.
-`factory.py` (`create_provider` / `is_native_provider` / `NATIVE_PROVIDERS`)
-is **legacy** — it still exists on disk but is no longer consulted by
-`ai.py`; do not extend it.
+The legacy `factory.py` (`create_provider` / `is_native_provider` /
+`NATIVE_PROVIDERS`) was **removed** — `ChatUnifier` + `registry.py` is the
+only dispatch layer.
## Config-Driven Base URLs
@@ -429,7 +428,7 @@ the plugin folder or add a `visuals.json` entry (`"openrouterChatModel":
- Create `services/llm/providers/<name>.py` implementing the `LLMProvider` protocol.
- At module bottom call `register_provider(ProviderSpec(name=..., factory=..., sdk_exception_refs=("sdk_module:ErrorClass",)))` — the lazy factory + string exception refs keep the SDK unimported until first use (never import the SDK at registration; locked by `tests/llm/test_lazy_sdk_imports.py`).
- Add a config entry in `llm_defaults.json` (no `base_url` needed if the SDK handles URLs itself).
- - Do NOT touch `factory.py` — it is legacy and no longer consulted.
+ - There is no `factory.py` to touch — the legacy factory module was removed; registration via `register_provider` is the only entry point.
3. **Credentials + agent exposure:**
- Add a `Credential` subclass in `server/nodes/model/_credentials.py` — surfaces in the Credentials Modal automatically.
diff --git a/docs-internal/node-logic-flows/ai_chat_models/anthropicChatModel.md b/docs-internal/node-logic-flows/ai_chat_models/anthropicChatModel.md
index 47c410b1..f6eab0ba 100644
--- a/docs-internal/node-logic-flows/ai_chat_models/anthropicChatModel.md
+++ b/docs-internal/node-logic-flows/ai_chat_models/anthropicChatModel.md
@@ -71,7 +71,7 @@ flowchart TD
E -- yes --> F[detect_ai_provider -> 'anthropic']
F --> G[Build NativeThinkingConfig if thinkingEnabled<br/>budget from thinkingBudget]
G --> H[Lookup anthropic_proxy credential]
- H --> I[Native path: create_provider anthropic<br/>await provider.chat with thinking]
+ H --> I[ChatUnifier.chat -> registry.get_provider anthropic<br/>await provider.chat with thinking]
I --> J[Return success envelope with response + thinking]
I -- Exception --> X
```
@@ -80,7 +80,7 @@ flowchart TD
- **Validation**: missing api_key or empty prompt -> error envelope.
- **Provider routing**: `detect_ai_provider` matches `'anthropic'` on `'anthropic' in node_type.lower()` branch.
-- **Native provider**: `is_native_provider('anthropic')` is True - uses the `anthropic` Python SDK.
+- **Native provider**: `ChatUnifier` resolves the self-registered `anthropic` spec - uses the `anthropic` Python SDK.
- **Model ID scrubbing**: strips `[FREE] ` prefix; strips `owner/` prefix for non-OpenRouter providers.
- **Temperature override**: when `thinkingEnabled=true`, temperature is auto-forced to 1 by `native_resolve_temperature`.
- **Thinking config**: `NativeThinkingConfig(enabled=True, budget=int(thinkingBudget))` forwarded to the SDK, which maps to Anthropic's `thinking={type: "enabled", budget_tokens: N}`.
diff --git a/docs-internal/node-logic-flows/ai_chat_models/cerebrasChatModel.md b/docs-internal/node-logic-flows/ai_chat_models/cerebrasChatModel.md
index 385cff46..fde458bd 100644
--- a/docs-internal/node-logic-flows/ai_chat_models/cerebrasChatModel.md
+++ b/docs-internal/node-logic-flows/ai_chat_models/cerebrasChatModel.md
@@ -11,7 +11,7 @@
## Purpose
-Ultra-fast inference on Cerebras' custom AI hardware. Models include Llama 3.1, GPT-OSS-120b, Qwen-3-235b. The `ChatModelBase.chat` operation calls `AIService.execute_chat`. Like Groq, routes through the **LangChain fallback** (`is_native_provider('cerebras')` is False).
+Ultra-fast inference on Cerebras' custom AI hardware. Models include Llama 3.1, GPT-OSS-120b, Qwen-3-235b. The `ChatModelBase.chat` operation calls `AIService.execute_chat`, which routes through `ChatUnifier`. Like Groq, Cerebras is one of the eight OpenAI-compatible providers registered in `providers/_compat.py` (the chat-path LangChain fallback was retired; LangChain `ChatCerebras` remains only on the agent path).
## Inputs (handles)
@@ -67,18 +67,18 @@ flowchart TD
D -- no --> X[error envelope]
D -- yes --> E[detect_ai_provider -> 'cerebras']
E --> F[Strip 'owner/' prefix]
- F --> G[LangChain fallback path]
- G --> H[ChatOpenAI w/ base_url=api.cerebras.ai/v1]
- H --> I[invoke messages]
+ F --> G[ChatUnifier.chat provider='cerebras']
+ G --> H[registry.get_provider cerebras<br/>_compat.py spec: OpenAIProvider + base_url=api.cerebras.ai/v1]
+ H --> I[await provider.chat -> LLMResponse]
I --> J[success envelope]
- H -- Exception --> X
+ H -- typed SDK error --> X
```
## Decision Logic
- **Validation**: missing api_key / empty prompt -> error envelope.
- **Provider routing**: `detect_ai_provider` matches `'cerebras' in node_type.lower()` **before** the groq branch, so routing is unambiguous.
-- **LangChain fallback**: `is_native_provider('cerebras')` False. Uses `ChatOpenAI` with Cerebras base_url.
+- **Native OpenAI-compatible path**: `ChatUnifier` resolves the `cerebras` spec registered in `providers/_compat.py` (reuses `OpenAIProvider` with the Cerebras base_url). No LangChain on the chat path.
- **Reasoning**: same parsed/hidden mechanism as Groq Qwen - only the Qwen-3-235b variant honors it.
- **Temperature range**: narrower (0-1.5 clamp) than OpenAI/Groq. `_resolve_temperature` applies the clamp.
@@ -86,20 +86,19 @@ flowchart TD
- **Database writes**: none on bare chat path.
- **Broadcasts**: none.
-- **External API calls**: `POST https://api.cerebras.ai/v1/chat/completions` via LangChain `ChatOpenAI` with `base_url` override.
+- **External API calls**: `POST https://api.cerebras.ai/v1/chat/completions` via the native `openai` SDK with `base_url` override.
- **File I/O**: none.
- **Subprocess**: none.
## External Dependencies
- **Credentials**: `auth_service.get_api_key('cerebras', 'default')` plus optional `cerebras_proxy`.
-- **Services**: `langchain_openai.ChatOpenAI`.
-- **Python packages**: `langchain-openai`.
+- **Services**: `ChatUnifier` + `OpenAIProvider` (base_url-ed) on the chat path; `langchain_cerebras.ChatCerebras` on the agent path.
+- **Python packages**: `openai` (chat path), `langchain-cerebras` (agent path, optional on Python >= 3.13).
- **Environment variables**: none.
## Edge cases & known limits
-- **LangChain path, not native** (same as Groq).
- **Temperature capped at 1.5**, not 2.
- **Reasoning only on Qwen-3-235b**.
- **Small max output**: 8K for most models; exceeding this surfaces as a provider-side error in the envelope.
diff --git a/docs-internal/node-logic-flows/ai_chat_models/deepseekChatModel.md b/docs-internal/node-logic-flows/ai_chat_models/deepseekChatModel.md
index 4c5ae5c7..67c44fc3 100644
--- a/docs-internal/node-logic-flows/ai_chat_models/deepseekChatModel.md
+++ b/docs-internal/node-logic-flows/ai_chat_models/deepseekChatModel.md
@@ -66,7 +66,7 @@ flowchart TD
D -- no --> X[error envelope]
D -- yes --> E[detect_ai_provider -> 'deepseek']
E --> F[Strip 'owner/' prefix]
- F --> G[Native path: create_provider deepseek<br/>OpenAI SDK w/ DeepSeek base_url]
+ F --> G[ChatUnifier.chat -> registry.get_provider deepseek<br/>OpenAI SDK w/ DeepSeek base_url]
G --> H[provider.chat]
H --> I[success envelope]
G -- Exception --> X
diff --git a/docs-internal/node-logic-flows/ai_chat_models/geminiChatModel.md b/docs-internal/node-logic-flows/ai_chat_models/geminiChatModel.md
index 9df2c6c1..5112fae4 100644
--- a/docs-internal/node-logic-flows/ai_chat_models/geminiChatModel.md
+++ b/docs-internal/node-logic-flows/ai_chat_models/geminiChatModel.md
@@ -68,7 +68,7 @@ flowchart TD
D -- no --> X[error envelope]
D -- yes --> E[detect_ai_provider -> 'gemini']
E --> F[Build NativeThinkingConfig w/ budget]
- F --> G[Native path: create_provider gemini<br/>google.genai.Client]
+ F --> G[ChatUnifier.chat -> registry.get_provider gemini<br/>google.genai.Client]
G --> H[provider.chat -> LLMResponse]
H --> I[success envelope]
G -- Exception --> X
diff --git a/docs-internal/node-logic-flows/ai_chat_models/groqChatModel.md b/docs-internal/node-logic-flows/ai_chat_models/groqChatModel.md
index 70268fbb..bec6068d 100644
--- a/docs-internal/node-logic-flows/ai_chat_models/groqChatModel.md
+++ b/docs-internal/node-logic-flows/ai_chat_models/groqChatModel.md
@@ -11,7 +11,7 @@
## Purpose
-Ultra-fast inference via Groq's LPU hardware. Models include Llama 3.x / 4, Qwen3-32b, GPT-OSS. The `ChatModelBase.chat` operation calls `AIService.execute_chat`; unlike OpenAI/Anthropic/Gemini, Groq routes through the **LangChain fallback** (`create_model` + `chat_model.invoke`) because `is_native_provider('groq')` returns False.
+Ultra-fast inference via Groq's LPU hardware. Models include Llama 3.x / 4, Qwen3-32b, GPT-OSS. The `ChatModelBase.chat` operation calls `AIService.execute_chat`, which routes every provider through `ChatUnifier`; Groq is one of the eight OpenAI-compatible providers registered in `providers/_compat.py` (the chat-path LangChain fallback was retired — LangChain `ChatGroq` remains only on the agent path).
## Inputs (handles)
@@ -66,44 +66,41 @@ flowchart TD
D -- no --> X[error envelope]
D -- yes --> E[detect_ai_provider -> 'groq']
E --> F[Strip 'owner/' prefix from model<br/>non-OpenRouter]
- F --> G[is_native_provider groq? NO]
- G --> H[LangChain fallback:<br/>self.create_model groq + ChatOpenAI-compatible]
- H --> I[chat_model.invoke messages]
- I --> J[extract_thinking_from_response<br/>reads additional_kwargs.reasoning]
- J --> K[success envelope]
- H -- Exception --> X
+ F --> G[ChatUnifier.chat provider='groq']
+ G --> H[registry.get_provider groq<br/>_compat.py spec: OpenAIProvider + Groq base_url]
+ H --> I[await provider.chat -> LLMResponse]
+ I --> K[success envelope]
+ H -- typed SDK error --> X
```
## Decision Logic
- **Validation**: missing api_key / empty prompt -> error envelope.
- **Provider routing**: matches `'groq' in node_type.lower()`. Note the ordering in `detect_ai_provider`: deepseek/kimi/mistral/cerebras checked first, so none of those accidentally resolve to groq.
-- **LangChain fallback**: `is_native_provider('groq')` is False -> goes through `create_model` -> `chat_model.invoke`. The model's `base_url` is loaded from `llm_defaults.json`.
+- **Native OpenAI-compatible path**: `ChatUnifier` resolves the `groq` spec registered in `providers/_compat.py` (reuses `OpenAIProvider` with the `base_url` from `llm_defaults.json`). No LangChain on the chat path.
- **Reasoning**: only Qwen3-32b actually honors `reasoningFormat`. Non-Qwen models ignore the flag.
- **Model string scrubbing**: `[FREE] ` prefix stripped; `owner/` prefix stripped (non-OpenRouter).
-- **Finish reason**: hardcoded to `"stop"` on the LangChain path (no fine-grained mapping).
## Side Effects
- **Database writes**: none on bare chat path.
- **Broadcasts**: none.
-- **External API calls**: `POST https://api.groq.com/openai/v1/chat/completions` via LangChain's `ChatOpenAI` with `base_url` override.
+- **External API calls**: `POST https://api.groq.com/openai/v1/chat/completions` via the native `openai` SDK with `base_url` override.
- **File I/O**: none.
- **Subprocess**: none.
## External Dependencies
- **Credentials**: `auth_service.get_api_key('groq', 'default')` plus optional `groq_proxy`.
-- **Services**: `langchain_openai.ChatOpenAI` (base_url-ed), `AIService.create_model`.
-- **Python packages**: `langchain-openai`.
+- **Services**: `ChatUnifier` + `OpenAIProvider` (base_url-ed) on the chat path; `langchain_groq.ChatGroq` on the agent path.
+- **Python packages**: `openai` (chat path), `langchain-groq` (agent path).
- **Environment variables**: none.
## Edge cases & known limits
-- **LangChain path, not native SDK**: unlike OpenAI/Anthropic/Gemini/OpenRouter, Groq goes through LangChain. This means model fetching also uses the curated list via httpx, not the native `fetch_models`.
- **Reasoning only on Qwen3-32b**: QwQ has been removed from Groq. Other models ignore `reasoningFormat`.
- **`reasoningFormat=hidden` suppresses `thinking`**: response contains only the final answer.
-- **Finish reason always `"stop"`**: fine-grained reasons (length, content_filter, tool_calls) are flattened.
+- **Finish reason**: passed through from the API response (`"stop"` fallback when absent).
- **Errors swallowed into envelope**.
## Related
diff --git a/docs-internal/node-logic-flows/ai_chat_models/kimiChatModel.md b/docs-internal/node-logic-flows/ai_chat_models/kimiChatModel.md
index 2e62dea1..f19fa91c 100644
--- a/docs-internal/node-logic-flows/ai_chat_models/kimiChatModel.md
+++ b/docs-internal/node-logic-flows/ai_chat_models/kimiChatModel.md
@@ -66,7 +66,7 @@ flowchart TD
D -- yes --> E[detect_ai_provider -> 'kimi']
E --> F[Strip 'owner/' prefix]
F --> G[native_resolve_temperature<br/>forces 0.6 or 1.0 based on model + thinking]
- G --> H[Native path: create_provider kimi<br/>OpenAI SDK w/ Moonshot base_url]
+ G --> H[ChatUnifier.chat -> registry.get_provider kimi<br/>OpenAI SDK w/ Moonshot base_url]
H --> I[provider.chat]
I --> J[success envelope]
H -- Exception --> X
diff --git a/docs-internal/node-logic-flows/ai_chat_models/lmstudioChatModel.md b/docs-internal/node-logic-flows/ai_chat_models/lmstudioChatModel.md
index 438a089f..ce4ea720 100644
--- a/docs-internal/node-logic-flows/ai_chat_models/lmstudioChatModel.md
+++ b/docs-internal/node-logic-flows/ai_chat_models/lmstudioChatModel.md
@@ -11,7 +11,7 @@
## Purpose
-Run local LLMs through LM Studio's OpenAI-compatible server (default `http://localhost:1234/v1`). The existing OpenAI-compatible fallback in `services/llm/factory.py` routes it through `OpenAIProvider` with `base_url` from `llm_defaults.json` — same path as deepseek/kimi/mistral/ollama. The user's custom server URL is stored as the `lmstudio_proxy` credential. `LMStudioChatModelNode` uses the shared `ChatModelParams` unchanged. The `ChatModelBase.chat` operation calls `AIService.execute_chat`.
+Run local LLMs through LM Studio's OpenAI-compatible server (default `http://localhost:1234/v1`). The OpenAI-compatible spec registered in `services/llm/providers/_compat.py` routes it through `OpenAIProvider` with `base_url` from `llm_defaults.json` — same path as deepseek/kimi/mistral/ollama. The user's custom server URL is stored as the `lmstudio_proxy` credential. `LMStudioChatModelNode` uses the shared `ChatModelParams` unchanged. The `ChatModelBase.chat` operation calls `AIService.execute_chat`.
## Inputs (handles)
@@ -66,7 +66,7 @@ flowchart TD
D -- no --> X[error envelope]
D -- yes --> E[detect_ai_provider -> 'lmstudio']
E --> F[Lookup lmstudio_proxy credential -> base_url override]
- F --> G[create_provider lmstudio -> OpenAIProvider<br/>base_url=user server, api_key='ollama']
+ F --> G[ChatUnifier.chat -> registry.get_provider lmstudio -> OpenAIProvider<br/>base_url=user server, api_key='ollama']
G --> H[provider.chat]
H --> I[success envelope]
G -- Exception --> X
diff --git a/docs-internal/node-logic-flows/ai_chat_models/mistralChatModel.md b/docs-internal/node-logic-flows/ai_chat_models/mistralChatModel.md
index ab423a24..1a380dd8 100644
--- a/docs-internal/node-logic-flows/ai_chat_models/mistralChatModel.md
+++ b/docs-internal/node-logic-flows/ai_chat_models/mistralChatModel.md
@@ -64,7 +64,7 @@ flowchart TD
D -- no --> X[error envelope]
D -- yes --> E[detect_ai_provider -> 'mistral']
E --> F[Strip 'owner/' prefix]
- F --> G[Native path: create_provider mistral<br/>OpenAI SDK w/ Mistral base_url]
+ F --> G[ChatUnifier.chat -> registry.get_provider mistral<br/>OpenAI SDK w/ Mistral base_url]
G --> H[provider.chat - thinking ignored]
H --> I[success envelope, thinking=null]
G -- Exception --> X
diff --git a/docs-internal/node-logic-flows/ai_chat_models/ollamaChatModel.md b/docs-internal/node-logic-flows/ai_chat_models/ollamaChatModel.md
index 54c22253..436ee2a0 100644
--- a/docs-internal/node-logic-flows/ai_chat_models/ollamaChatModel.md
+++ b/docs-internal/node-logic-flows/ai_chat_models/ollamaChatModel.md
@@ -11,7 +11,7 @@
## Purpose
-Run local LLMs (llama, mistral, qwen, deepseek-r1, ...) through a locally-running Ollama server. Ollama exposes an OpenAI-shaped `/v1` endpoint, so the existing OpenAI-compatible fallback in `services/llm/factory.py` hands it to `OpenAIProvider` with `base_url` from `llm_defaults.json` — same path as deepseek/kimi/mistral. The user's custom server URL (if not localhost) is stored as the `ollama_proxy` credential and flows through the same `proxy_url` parameter cloud providers already use for Ollama-style auth delegation. `OllamaChatModelNode` uses the shared `ChatModelParams` unchanged. The `ChatModelBase.chat` operation calls `AIService.execute_chat`.
+Run local LLMs (llama, mistral, qwen, deepseek-r1, ...) through a locally-running Ollama server. Ollama exposes an OpenAI-shaped `/v1` endpoint, so the OpenAI-compatible spec registered in `services/llm/providers/_compat.py` hands it to `OpenAIProvider` with `base_url` from `llm_defaults.json` — same path as deepseek/kimi/mistral. The user's custom server URL (if not localhost) is stored as the `ollama_proxy` credential and flows through the same `proxy_url` parameter cloud providers already use for Ollama-style auth delegation. `OllamaChatModelNode` uses the shared `ChatModelParams` unchanged. The `ChatModelBase.chat` operation calls `AIService.execute_chat`.
## Inputs (handles)
@@ -66,7 +66,7 @@ flowchart TD
D -- no --> X[error envelope]
D -- yes --> E[detect_ai_provider -> 'ollama']
E --> F[Lookup ollama_proxy credential -> base_url override]
- F --> G[create_provider ollama -> OpenAIProvider<br/>base_url=user server, api_key='ollama']
+ F --> G[ChatUnifier.chat -> registry.get_provider ollama -> OpenAIProvider<br/>base_url=user server, api_key='ollama']
G --> H[provider.chat]
H --> I[success envelope]
G -- Exception --> X
diff --git a/docs-internal/node-logic-flows/ai_chat_models/openaiChatModel.md b/docs-internal/node-logic-flows/ai_chat_models/openaiChatModel.md
index 5248b23d..1290578d 100644
--- a/docs-internal/node-logic-flows/ai_chat_models/openaiChatModel.md
+++ b/docs-internal/node-logic-flows/ai_chat_models/openaiChatModel.md
@@ -76,8 +76,8 @@ flowchart TD
G -- yes --> H[detect_ai_provider -> 'openai']
H --> I[Build NativeThinkingConfig if thinkingEnabled]
I --> J[Lookup openai_proxy credential]
- J --> K{is_native_provider?}
- K -- yes for openai --> L[Native path:<br/>create_provider openai + OpenAI SDK<br/>await provider.chat]
+ J --> K[ChatUnifier.chat provider='openai']
+ K --> L[registry.get_provider openai + OpenAI SDK<br/>await provider.chat]
L --> M[Build response dict<br/>response / thinking / model / provider / finish_reason]
M --> N[Return success envelope]
L -- Exception --> X
@@ -87,7 +87,7 @@ flowchart TD
- **Validation**: missing `api_key` -> ValueError; empty/whitespace `prompt` (via `is_valid_message_content`) -> ValueError. Both produce a `success=false` envelope.
- **Provider routing**: `detect_ai_provider(node_type)` returns `'openai'` for this node; falls through the else branch in `constants.detect_ai_provider`.
-- **Native vs LangChain**: `is_native_provider('openai')` is True, so the native `openai` SDK is used via `create_provider('openai', api_key, proxy_url=...)`.
+- **Native path**: `ChatUnifier` resolves the self-registered `openai` spec, so the native `openai` SDK is used via `spec.factory(api_key, proxy_url=...)`. (LangChain is agent-path only.)
- **Model string scrubbing**: strips `[FREE] ` prefix if present. For non-OpenRouter providers (like this one), any `provider/model` slash prefix is stripped so the OpenAI API sees a flat ID.
- **Thinking config**: only built when `thinkingEnabled` is truthy; passed through to the provider's `chat()` method.
- **System prompt**: accepts `system_prompt`, `systemMessage`, or `systemPrompt`. Only prepended as a `SystemMessage` when non-empty (`is_valid_message_content`).
diff --git a/docs-internal/node-logic-flows/ai_chat_models/openrouterChatModel.md b/docs-internal/node-logic-flows/ai_chat_models/openrouterChatModel.md
index 83e7731d..6c9504c6 100644
--- a/docs-internal/node-logic-flows/ai_chat_models/openrouterChatModel.md
+++ b/docs-internal/node-logic-flows/ai_chat_models/openrouterChatModel.md
@@ -70,7 +70,7 @@ flowchart TD
E -- no --> X[error envelope]
E -- yes --> F[detect_ai_provider -> 'openrouter']
F --> G[DO NOT strip 'owner/' prefix<br/>provider == openrouter]
- G --> H[Native path: create_provider openrouter<br/>OpenAI SDK w/ base_url=openrouter.ai/api/v1]
+ G --> H[ChatUnifier.chat -> registry.get_provider openrouter<br/>OpenAI SDK w/ base_url=openrouter.ai/api/v1]
H --> I[provider.chat -> response]
I --> J[success envelope]
H -- Exception --> X
diff --git a/docs-internal/node-logic-flows/android/_pattern.md b/docs-internal/node-logic-flows/android/_pattern.md
index bdae38c0..4fba4e0c 100644
--- a/docs-internal/node-logic-flows/android/_pattern.md
+++ b/docs-internal/node-logic-flows/android/_pattern.md
@@ -193,8 +193,8 @@ preserved.
- Android service infrastructure: [`server/nodes/android/`](../../../server/nodes/android/)
- Status broadcaster (two-state model): [Status Broadcaster](../../status_broadcaster.md)
- Android-agent skills: [`server/skills/android_agent/`](../../../server/skills/android_agent/)
-- AI-tool dispatch (`androidTool` aggregator + direct service tools):
- `execute_android_toolkit` and `execute_android_service_tool` in
+- AI-tool dispatch (direct service tools; the `androidTool` aggregator was
+ retired): `execute_android_service_tool` in
[`server/nodes/android/_base.py`](../../../server/nodes/android/_base.py),
called from
[`server/services/handlers/tools.py::execute_tool`](../../../server/services/handlers/tools.py)
diff --git a/docs-internal/plugin_system.md b/docs-internal/plugin_system.md
index f8ef6939..7dd37ac8 100644
--- a/docs-internal/plugin_system.md
+++ b/docs-internal/plugin_system.md
@@ -509,12 +509,13 @@ themselves** into those registries from their package `__init__.py`.
```
server/nodes/telegram/
-├── __init__.py # imports + 5 register_* calls covering 5 registries (no logic)
+├── __init__.py # imports + register_* calls covering six registries (no logic)
├── _credentials.py # TelegramCredential (ApiKeyCredential)
├── _service.py # TelegramService singleton (bot lifecycle)
├── _handlers.py # WebSocket handlers + WS_HANDLERS dict
├── _filters.py # build_telegram_filter (event_waiter filter)
├── _refresh.py # refresh_telegram_status + precheck_telegram_trigger
+├── _events.py # typed CloudEvents factory + broadcast_telegram_status
├── telegram_send.py # ActionNode + AI tool
└── telegram_receive.py # TriggerNode
```
@@ -782,10 +783,11 @@ All Wave 10 invariants in `test_node_spec.py` still run; Wave 11 invariants in `
- F4.B — `AgentWorkflow` child workflow + 3 agent activities behind
`TEMPORAL_AGENT_WORKFLOW_ENABLED` flag (commit `a4d009e`). Tool
calls inside AI agents become per-type activities.
-- Wave 11.E — Declarative credentials: 18 `Credential` subclasses
+- Wave 11.E — Declarative credentials: 25 `Credential` subclasses
(GoogleCredential + GoogleMapsCredential + TwitterCredential +
- TelegramCredential + ApifyCredential + 10 LLM providers + 3 inline
- search credentials). 29 plugins now declare `credentials = (...)`.
+ TelegramCredential + ApifyCredential + 12 LLM providers + 3 inline
+ search credentials + Stripe / Vercel / GitHub / Cloudflare /
+ WhatsApp). 29 plugins now declare `credentials = (...)`.
Agents stay poly-provider (empty tuple).
- Wave 11.E.1 — Modularised credentials into per-domain
`nodes/<group>/_credentials.py` files. `server/credentials/`
@@ -815,7 +817,9 @@ All Wave 10 invariants in `test_node_spec.py` still run; Wave 11 invariants in `
execute_android_service_tool}` with a single canonical
`SERVICE_ID_MAP` and a shared `_execute_with_broadcast` helper
(previously duplicated in `tools.py`). `tools.py` from 1,255 → 821
- LOC.
+ LOC. (`execute_android_toolkit` has since been removed along with the
+ `androidTool` aggregator node; only `execute_android_service_tool`
+ remains.)
- Wave 11.G — Nodes cookbook (`server/nodes/README.md`) + CLAUDE.md
plugin section + this file refreshed to match shipped state.
- Wave 11.H — Self-contained plugin folders. Six generic registries
@@ -1137,7 +1141,11 @@ Drop-in HMAC schemes covering the major providers:
| `HmacVerifier` | configurable header + prefix | HMAC-SHA256 over body | generic fallback |
Each verifier raises `ValueError` on mismatch; `WebhookSource.handle`
-catches it and returns HTTP 400.
+catches it and returns HTTP 400. When a verifier is declared but no
+signing secret resolves, `handle` fails closed: HTTP 503 with
+`Retry-After: 5` (the provider retries the delivery once the secret
+lands). The legacy generic `/webhook/{path}` route used by
+`webhookTrigger` is unaffected.
### Wiring helpers
diff --git a/docs-internal/release_build_pipeline.md b/docs-internal/release_build_pipeline.md
index 54caee62..1670ba62 100644
--- a/docs-internal/release_build_pipeline.md
+++ b/docs-internal/release_build_pipeline.md
@@ -71,6 +71,10 @@ Two halves (both required; see [performance.md](performance.md) for the
The npm tarball still excludes `__pycache__/` per `package.json` `files` (cross-Python-minor pyc fragility) — `compileall` runs on the user's machine via `company build` or `scripts/install.js` post-install.
+### 4a-bis. `.env` scaffolding with fresh secrets (step `[0/6]`)
+
+- When no `.env` exists, `company build` step `[0/6]` scaffolds it from `.env.template` and replaces the dev placeholder values of `SECRET_KEY` / `JWT_SECRET_KEY` / `API_KEY_ENCRYPTION_KEY` with fresh `secrets.token_hex(24)` values (`_scaffold_env_secrets` in `cli/commands/build.py`). An existing `.env` is never modified. The placeholder literals themselves are the SSOT frozenset `DEV_SECRET_LITERALS` in `server/core/config.py`; server startup logs a non-fatal error banner via `dev_secret_offenders()` when placeholders are detected with auth enabled or `DEPLOYMENT_MODE != local`.
+
### 4b. Temporal binary fetch + DATA_DIR parity
- Step `[6/6]` runs `uv run python -m services.temporal._install`, which pooch-downloads the official `temporal` CLI into `<DATA_DIR>/packages/temporal/` (= `~/.opencompany/packages/temporal/` by default). Pre-fetching at build time turns the ~114 MB download into a sub-second cache hit on first `company start`. The download uses an explicit `HTTPDownloader(timeout=300)` (per-socket-read timeout — slow links can finish; pooch's 30 s default aborted them). Fatality differs by entry point: `company build` keeps the step **fatal** (locked by `test_temporal_install_is_fatal_on_failure`), while npm postinstall (`scripts/install.js`) wraps it in a **non-fatal** try/catch because `TemporalServerRuntime._pre_spawn()` re-downloads lazily on first `company start`. The cache survives `company clean` (`packages` ∈ `_OPENCOMPANY_KEEP`), so clean+build cycles don't re-download.
diff --git a/docs-internal/schema_source_of_truth_rfc.md b/docs-internal/schema_source_of_truth_rfc.md
index c91124c1..f48b6e15 100644
--- a/docs-internal/schema_source_of_truth_rfc.md
+++ b/docs-internal/schema_source_of_truth_rfc.md
@@ -342,7 +342,7 @@ bulk files + dead dispatcher fallbacks is complete (Wave 11.D.13).
- **11.E.1** — credentials modularised into per-domain
`server/nodes/<group>/_credentials.py` files (or inline for
single-use). **Central `server/credentials/` directory deleted.**
- 18 `Credential` subclasses total.
+ 18 `Credential` subclasses at the time (25 concrete subclasses today).
- **11.E.2 / E.3 / E.4** — credential polish + doc sync.
- **11.F** — per-plugin Temporal activities
(`cls.as_activity()` named `node.{type}.v{version}`),
diff --git a/docs-internal/server-readme.md b/docs-internal/server-readme.md
index 4f2b086c..f9b5a788 100644
--- a/docs-internal/server-readme.md
+++ b/docs-internal/server-readme.md
@@ -7,6 +7,8 @@
cp .env.template .env
```
+(If you run `company build` instead, its step [0/6] scaffolds `.env` from `.env.template` automatically and generates fresh random secrets — `secrets.token_hex(24)` — for `SECRET_KEY`, `JWT_SECRET_KEY`, and `API_KEY_ENCRYPTION_KEY` instead of copying the dev placeholders. An existing `.env` is never touched.)
+
2. Edit `.env` and add your API keys:
```bash
# Required for remote Android devices
@@ -48,11 +50,13 @@ The `.env.template` file contains development-safe defaults.
For production:
1. Change `DEBUG=false`
-2. Generate new secure `SECRET_KEY` and `API_KEY_ENCRYPTION_KEY`
+2. Generate new secure `SECRET_KEY` and `API_KEY_ENCRYPTION_KEY` (a `company build`-scaffolded `.env` already has fresh random values; a hand-copied template does not)
3. Set `RATE_LIMIT_ENABLED=true`
4. Configure proper CORS origins
5. Consider enabling Redis caching
+The server also guards against placeholder secrets at startup: `server/core/config.py` exposes `DEV_SECRET_LITERALS` + `dev_secret_offenders()`, and the lifespan logs a non-fatal error banner if dev placeholder secrets are detected while auth is enabled or `DEPLOYMENT_MODE` is not `local`.
+
## Authentication & Encryption
### Authentication Toggle
diff --git a/docs-internal/stripe_service.md b/docs-internal/stripe_service.md
index 7dca4fac..918e3e5f 100644
--- a/docs-internal/stripe_service.md
+++ b/docs-internal/stripe_service.md
@@ -567,9 +567,11 @@ implements [Stripe's webhook signature scheme](https://stripe.com/docs/webhooks/
Verifier raises `ValueError` on mismatch; `WebhookSource.handle`
catches it and returns HTTP 400. If the signing secret hasn't been
captured yet (race between first webhook and the `whsec_…` banner),
-the framework logs a warning and accepts the event without
-verification — this only happens during the first ~5 seconds of
-daemon startup.
+the framework **fails closed**: it logs a warning and rejects the
+event with HTTP 503 + `Retry-After: 5` instead of accepting it
+unverified. Stripe retries the delivery, so events arriving during
+the first ~5 seconds of daemon startup are re-delivered once the
+secret lands.
## Status broadcasting — marker token + generic catalogue invalidation
@@ -779,11 +781,12 @@ its own credentials at `~/.config/stripe/config.toml` (or
The first ~5 seconds after `stripe_connect`, the secret-capture task
hasn't yet matched the `whsec_…` line in stderr. If a webhook arrives
-during that window, the framework logs a warning and accepts the
-event without verification. In practice this is benign because Stripe
-won't deliver real events until the daemon is fully ready, but
-synthetic events triggered via `stripe_trigger` immediately after
-connect can hit this path.
+during that window, the framework fails closed: it logs a warning and
+rejects the event with HTTP 503 + `Retry-After: 5` (no unverified
+acceptance). Stripe retries the delivery, so real events are simply
+re-delivered once the secret lands; synthetic events triggered via
+`stripe_trigger` immediately after connect can hit the 503 and are
+retried by the CLI the same way.
### Single global daemon
diff --git a/docs-internal/tool_building_pipeline.md b/docs-internal/tool_building_pipeline.md
index 91f00389..e1158b0d 100644
--- a/docs-internal/tool_building_pipeline.md
+++ b/docs-internal/tool_building_pipeline.md
@@ -40,7 +40,7 @@ Canonical home for how AI Agents discover connected tool nodes, build LangChain
(memory_data, skill_data, tool_data, input_data, task_data)
```
-- **`tool_data`** is a list of dicts. Each entry: `{node_id, node_type, parameters, label, connected_services?}`. The `connected_services` field is only populated for `androidTool` (the gateway-tool pattern — see §6).
+- **`tool_data`** is a list of dicts. Each entry: `{node_id, node_type, parameters, label}`. (The `connected_services` extra belonged to the retired `androidTool` gateway tool — see §7.)
- **MasterSkill expansion** runs at discovery time: a single `masterSkill` connection with `skillsConfig` expands into N individual skill entries, one per enabled skill key.
- **Team-lead expansion** (`orchestrator_agent` / `ai_employee`): agents connected
to `input-teammates` become authorized descriptors. Internal `delegate_to_*`
@@ -105,7 +105,7 @@ config = {
"database": database,
"nodes": nodes,
"edges": edges,
- # ... per-tool extras (e.g., connected_services for androidTool)
+ # ... per-tool extras
}
```
@@ -150,25 +150,14 @@ When the LLM emits `tool_calls` in its response, `_run_agent_loop` iterates them
| `aiAgent` / `chatAgent` / `<specialized>_agent` | `_execute_delegated_agent` (fire-and-forget background task) |
| `_builtin_check_delegated_tasks` | `_execute_check_delegated_tasks` |
| `batteryMonitor` / `wifiAutomation` / ... (16 service types) | `_execute_android_service` (snake_case service ID via SERVICE_ID_MAP) |
-| `androidTool` (gateway) | `_execute_android_toolkit` (dispatches to a connected Android service) |
| `whatsappSend` / `whatsappDb` / `pythonExecutor` / ... | Per-plugin `usable_as_tool=True` handler (the plugin's own `execute()` method) |
| `calculatorTool` / `currentTimeTool` / `taskManager` / `writeTodos` | `_execute_<name>` direct implementations |
| `braveSearch` / `serperSearch` / `perplexitySearch` | `handle_<provider>_search` (httpx async, credential resolution, usage tracking) |
| All else | `_execute_generic` (catch-all) |
-## 7. Gateway-tool pattern (Android Toolkit)
+## 7. Gateway-tool pattern (retired)
-`androidTool` is the only **gateway tool** today — a single `StructuredTool` that the LLM sees as `android_device`, but which fans out to multiple connected Android service nodes:
-
-```
-[Battery Monitor] ──┐
-[WiFi Automation] ──┼──► [Android Toolkit] ──► [AI Agent]
-[Location] ──┘
-```
-
-The LLM sees one tool with `{service_id, action, parameters}` arguments. `_execute_android_toolkit` looks up the matching connected service, asserts it's actually connected to this toolkit instance, and forwards to the service handler. The toolkit's `connected_services` list (populated during stage 1) drives schema generation in `_get_tool_schema` so the LLM only sees actions for services that are present.
-
-Direct Android service tools (16 individual entries in `DEFAULT_TOOL_NAMES`) are an alternative path — connect a service node directly to `input-tools` without using the toolkit aggregator. Both paths exist; the toolkit is preferred when you want one cohesive `android_device` tool.
+`androidTool` was the only **gateway tool** — a single `StructuredTool` the LLM saw as `android_device` that fanned out to multiple connected Android service nodes via a `connected_services` list. The node no longer exists: Android service tools are the 16 individual entries in `DEFAULT_TOOL_NAMES`, connected directly to `input-tools`. Legacy `service -> androidTool -> agent` graphs are rewritten on load by `services/workflow_migrations.normalize_legacy_android_toolkit`, and sub-node exclusion keys solely on the AI-agent config handles (`input-memory` / `input-tools` / `input-skill` / `input-teammates`) — the `TOOLKIT_NODE_TYPES` constant is gone.
## 8. Internal delegation identities (`delegate_to_*`)
diff --git a/docs/diagrams/system-overview.svg b/docs/diagrams/system-overview.svg
index 5c255d38..f2708010 100644
--- a/docs/diagrams/system-overview.svg
+++ b/docs/diagrams/system-overview.svg
@@ -70,7 +70,7 @@
<rect class="box p-purple" x="250" y="558" width="920" height="64" rx="8"/>
<text class="h2" x="710" y="584" text-anchor="middle">Execution engine</text>
- <text class="sub" x="710" y="607" text-anchor="middle">Temporal -&gt; Redis-parallel -&gt; sequential (auto-fallback)</text>
+ <text class="sub" x="710" y="607" text-anchor="middle">Temporal -&gt; sequential (auto-fallback)</text>
<!-- Backend -> Sidecars -->
<path class="conn" d="M 710 646 L 710 722" marker-end="url(#arrow)"/>
diff --git a/server/nodes/README.md b/server/nodes/README.md
index d7855d47..79cd6789 100644
--- a/server/nodes/README.md
+++ b/server/nodes/README.md
@@ -147,7 +147,7 @@ these first before writing new code:
| `agent/` | `_specialized.SpecializedAgentBase` | Base for 13 specialized agents |
| `model/` | `_base.ChatModelBase` | 11 chat models inherit → same `@Operation("chat")` body that calls `ai_service.execute_chat` |
| `android/` | `_base.AndroidServiceBase` | 16 Android services inherit; payload translation + `SERVICE_ID_MAP` lives on this base |
-| `android/` | `_base.execute_android_toolkit` / `execute_android_service_tool` | AI-tool dispatchers — called from `services/handlers/tools.py` for the toolkit aggregator + direct service tool branches |
+| `android/` | `_base.execute_android_service_tool` | AI-tool dispatcher — called from `services/handlers/tools.py` for direct service tools (the `androidTool` aggregator + `execute_android_toolkit` were retired) |
| `code/` | `_base.CodeExecutorBase` + `_nodejs.NodeJSClient` | Python/JS/TS executors; `monty_executor/` is sandboxed Python via `pydantic-monty` (enforced limits + opt-in capabilities) |
| `google/` | `_base.build_google_service` / `track_google_usage` | 7 Google plugins (OAuth + API) |
| `google/` | `_gmail.fetch_email_details` / `mark_email_as_read` | gmail + gmail_receive |
@@ -244,12 +244,13 @@ similar plugin.
```
server/nodes/telegram/
-├── __init__.py # imports + 5 register_* calls covering 5 registries (zero logic)
+├── __init__.py # imports + register_* calls covering six registries (zero logic)
├── _credentials.py # TelegramCredential subclass
├── _service.py # singleton bot lifecycle (connect / send / poll)
├── _handlers.py # WS_HANDLERS dict (telegram_connect, …)
├── _filters.py # build_telegram_filter (event_waiter filter)
├── _refresh.py # WS-connect refresh + trigger precheck
+├── _events.py # typed CloudEvents factory + broadcast_telegram_status
├── telegram_send.py # ActionNode + AI tool
└── telegram_receive.py # TriggerNode
```
diff --git a/server/nodes/telegram/__init__.py b/server/nodes/telegram/__init__.py
index 70fd9592..72927acc 100644
--- a/server/nodes/telegram/__init__.py
+++ b/server/nodes/telegram/__init__.py
@@ -14,12 +14,14 @@ waiter, trigger handler) read at dispatch time:
telegram_send.py workflow ActionNode + AI tool
telegram_receive.py workflow TriggerNode
-On import, this package self-registers four callbacks:
+On import, this package self-registers six callbacks:
- 1. WS handlers -> services.ws_handler_registry
- 2. Event filter -> services.event_waiter.FILTER_BUILDERS
- 3. Trigger precheck-> services.event_waiter._TRIGGER_PRECHECKS
- 4. Status refresh -> services.status_broadcaster._SERVICE_REFRESH_CALLBACKS
+ 1. WS handlers -> services.ws_handler_registry
+ 2. Event filter -> services.event_waiter.FILTER_BUILDERS
+ 3. Trigger precheck -> services.event_waiter._TRIGGER_PRECHECKS
+ 4. Status refresh -> services.status_broadcaster._SERVICE_REFRESH_CALLBACKS
+ 5. Output schemas -> services.node_output_schemas (telegramReceive + telegramSend)
+ 6. Canary trigger -> services.deployment.canary_registry (telegramReceive)
Adding a new plugin folder follows the same shape -- consumers do not
need to learn its name.
diff --git a/server/services/llm/providers/_compat.py b/server/services/llm/providers/_compat.py
index 55dba8b8..2834ecdd 100644
--- a/server/services/llm/providers/_compat.py
+++ b/server/services/llm/providers/_compat.py
@@ -1,16 +1,15 @@
"""OpenAI-compatible provider registrations.
-Six providers (``xai`` / ``deepseek`` / ``kimi`` / ``mistral`` / ``ollama`` /
-``lmstudio``) all ride the OpenAI Python SDK with a custom ``base_url``,
+Eight providers (``xai`` / ``deepseek`` / ``kimi`` / ``mistral`` / ``ollama`` /
+``lmstudio`` / ``groq`` / ``cerebras``) all ride the OpenAI Python SDK with a custom ``base_url``,
so they share one factory (``OpenAIProvider``) and one typed-exception
tuple (``openai.OpenAIError``). The per-provider differences live in
``llm_defaults.json`` (``base_url``, plus the provider quirks block
added in Phase C) — there is no per-provider Python here.
Adding a new OpenAI-compat provider is a JSON edit + one entry in
-``_COMPAT_PROVIDERS`` below. Groq + Cerebras stay behind the LangChain
-fallback in ``ai.py`` until Phase D deletes the fallback; they will
-register here at that point.
+``_COMPAT_PROVIDERS`` below. Groq + Cerebras registered here in
+Phase D (see the ``_COMPAT_PROVIDERS`` comment below).
"""
from __future__ import annotations
diff --git a/server/services/temporal/activities.py b/server/services/temporal/activities.py
index 075de6ac..0724edd2 100644
--- a/server/services/temporal/activities.py
+++ b/server/services/temporal/activities.py
@@ -68,8 +68,10 @@ class NodeExecutionActivities:
async def execute_node_activity(self, context: Dict[str, Any]) -> Dict[str, Any]:
"""Execute a single workflow node with isolated context.
- This activity can run on ANY worker in the cluster, enabling
- horizontal scaling and multi-tenant distribution.
+ This activity delegates execution over WebSocket back to the
+ originating FastAPI server (ws://{host}:{port}/ws/internal per
+ _resolve_urls), so any worker running it must be able to reach
+ that server -- it is not freely relocatable across a cluster.
Each node execution is independent - if it fails, Temporal will retry
on the same or different worker without affecting other nodes.
diff --git a/server/services/temporal/worker.py b/server/services/temporal/worker.py
index e275f282..02819e3f 100644
--- a/server/services/temporal/worker.py
+++ b/server/services/temporal/worker.py
@@ -153,10 +153,11 @@ class TemporalWorkerManager:
# workflow.py:_resolve_activity picks one of the two paths per node
# based on the temporal_per_type_dispatch flag; both must be served
# by the worker. Per-type activities register WITHOUT a task_queue
- # filter (cls.task_queue is the *declared* preference; the single
- # worker actually polls self.task_queue regardless). When
- # TemporalWorkerPool is wired (future enhancement), per-queue
- # filtering will move there. Registration cost: ~1.6s startup;
+ # filter here (cls.task_queue is the *declared* preference; this
+ # framework worker polls self.task_queue regardless). Per-queue
+ # filtering lives in TemporalWorkerPool (below in this file),
+ # which is default-on (Wave 16.4) and runs one activity-only
+ # worker per declared queue. Registration cost: ~1.6s startup;
# zero runtime cost when the flag is off (orchestrator routes to
# execute_node_activity, per-type entries sit idle).
#