Skip to content

Self-improving AI Employees for everyone

docs: deep cleanup — delete obsolete guides, archive shipped RFC, consolidate scattered explanations

trohitg66489c60821b
diff --git a/CLAUDE.md b/CLAUDE.md
index de377406..0fe7d829 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -14,7 +14,7 @@ This is a React Flow-based workflow automation platform implementing n8n-inspire
| **[Node Allowlist](./docs-internal/node_allowlist.md)** | Single-config UI visibility — `server/config/node_allowlist.json` controls which nodes / credential categories / skill folders show in the UI. Five lists with two enforcement tiers (mode-gated allowlist + absolute blocklist). `useNodeAllowlist` hook exposes `isVisible` / `isBlocked` / `isAllowed` / `isCredentialCategoryDisabled` / `isSkillFolderDisabled`. Adding a new disabled domain = single JSON edit, no code change. |
| **[Theme System](./docs-internal/theme_system.md)** | 10-way visual theme system — 5 utopian (light, dark, 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), shadcn HSL-triplet bridge, action role tokens, 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 10 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. |
| **[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, `google_auth.py`, `triggers.py`). **Wave 11.H added "self-contained plugin folders"** — five generic registries (`ws_handler_registry`, `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). 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, `google_auth.py`, `triggers.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 LangGraph |
@@ -64,72 +64,17 @@ This is a React Flow-based workflow automation platform implementing n8n-inspire
### 0. Adding a new node — the canonical recipe (Wave 11.H)
-**Every plugin is a self-contained folder under `server/nodes/<group>/<plugin>/`.**
-Reference implementation: [`server/nodes/telegram/`](./server/nodes/telegram/).
-
-1. **Create the folder** with one `__init__.py` declaring a
- `BaseNode` / `ActionNode` / `TriggerNode` / `ToolNode` subclass.
- Declare `type`, `display_name`, `group`, `handles`, `Params`,
- `Output`, `credentials`, `task_queue`, and `@Operation`-decorated
- methods. Auto-registers via `BaseNode.__init_subclass__` on import.
- Zero edits anywhere else. For single-class plugins, all the logic
- stays in `__init__.py` — no extra files needed.
- See [server/nodes/README.md](./server/nodes/README.md).
-
-2. **Split into helper modules** (`_service.py` / `_handlers.py` /
- `_credentials.py` / `_filters.py` / `_refresh.py` / `_events.py`)
- only when the plugin owns one or more of:
- - a long-lived stateful object (bot / device / SDK session / subprocess),
- - credentials-modal WebSocket commands beyond Save / Load / Delete,
- - trigger pre-execution checks that need plugin-specific state,
- - a status-refresh callback that runs on WS-client connect.
-
- Multi-file shape (telegram is the reference — one plugin folder
- containing two node classes, `telegram_send` and `telegram_receive`):
- ```
- server/nodes/<group>/<plugin>/
- ├── __init__.py # imports + register_* calls (zero logic)
- ├── icon.svg # co-located plugin icon
- ├── _credentials.py # <Provider>Credential subclass
- ├── _service.py # singleton/service lifecycle
- ├── _handlers.py # WS_HANDLERS dict
- ├── _filters.py # build_<provider>_filter (event_waiter)
- ├── _refresh.py # refresh_*_status + precheck_*_trigger
- ├── <provider>_send.py
- └── <provider>_receive.py
- ```
- Underscore-prefixed files are package-private (the node walker skips
- them). The package `__init__.py` is the single wiring point.
-
-3. **Five generic registries** the package self-registers into. Nothing
- outside the plugin folder hardcodes the plugin's name:
-
- | Concern | Register call | Backed by |
- |---|---|---|
- | Credentials-modal WebSocket commands | `services.ws_handler_registry.register_ws_handlers({type: handler})` | central `_resolve_handler()` in `routers/websocket.py` |
- | Trigger event-filter builder | `services.event_waiter.register_filter_builder(node_type, fn)` | `event_waiter.FILTER_BUILDERS` |
- | Trigger pre-execution check | `services.event_waiter.register_trigger_precheck(node_type, async_fn)` | generic `services/handlers/triggers.py` runs `run_trigger_precheck` before entering the wait loop |
- | Service-status refresh on WS connect | `services.status_broadcaster.register_service_refresh(async_callback)` | `_refresh_all_services` TaskGroup |
- | Output schema | `services.node_output_schemas.register_output_schema(node_type, ModelClass)` | central `NODE_OUTPUT_SCHEMAS` |
-
- All five are idempotent (same callable / class for the same key is a
- no-op; conflicts raise `ValueError`).
-
-4. **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. The 754-line telegram extraction
- from `services/telegram_service.py` (Wave 11.H) changed zero
- frontend code.
-
-5. **What NOT to do**: don't import the plugin folder from `routers/`,
- `services/`, or another `nodes/` subfolder. Don't edit
- `event_waiter.py` / `status_broadcaster.py` / `routers/websocket.py`
- to add a new plugin's handler/filter/refresh — register from the
- plugin's `__init__.py` instead.
-
-Full reference: [docs-internal/plugin_system.md → "Self-contained plugin folders"](./docs-internal/plugin_system.md#self-contained-plugin-folders).
+Every plugin is a self-contained folder under `server/nodes/<group>/<plugin>/` rooted at `__init__.py`. `BaseNode.__init_subclass__` auto-registers metadata, schemas, handlers, and Temporal activity on import — zero edits anywhere else.
+
+**Where to look:**
+- [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)
+
+**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.
+
+**Don't** import the plugin folder from `routers/` / `services/` / another `nodes/` subfolder. **Don't** edit `event_waiter.py` / `status_broadcaster.py` / `routers/websocket.py` to add a plugin's handler / filter / refresh — register from the plugin's `__init__.py` instead.
### 1. Use Existing Patterns - No Tribal Code
- **Never add ad-hoc workarounds** - Use the established patterns documented in DESIGN.md
@@ -585,54 +530,13 @@ The frontend uses a layered cache + slice-subscription model so cold refreshes a
- Applies to `SquareNode`, `AIAgentNode`, `TriggerNode`, `GenericNode`, `ToolkitNode`, `StartNode`, `TeamMonitorNode`. Add new node components the same way.
- Reference: https://reactflow.dev/learn/advanced-use/performance
-### Icon + color — per-plugin folder + visuals.json fallback (post-RFC F1 + F2)
-
-Following the plugin authoring RFC §6.5 / §6.6, icons and colors live co-located in the plugin folder; `visuals.json` is the fallback registry for emoji / library icons and the skill reverse-map.
+### Icon + color — per-plugin folder + visuals.json fallback
-**Icon resolution** (`BaseNode._metadata_dict` → `services/plugin/base.py`):
-1. **Per-node-type icon** — `<plugin_folder>/icon_<nodeType>.svg`. Lets multi-node-per-plugin folders serve distinct icons per node type (whatsapp has `icon_whatsappSend.svg` / `icon_whatsappReceive.svg` / `icon_whatsappDb.svg` in one shared folder).
-2. **Shared plugin icon** — `<plugin_folder>/icon.svg`. The standard Phase 9 contract; one icon for the whole folder (telegram / stripe / browser / search / google / etc.).
-3. Fallback: **`visuals.json` `icon`** field — emoji (`"🤖"`) or `lobehub:<brand>`. Post-F1/F7 there are **zero `asset:<key>` entries** in visuals.json.
+Plugin icons and colors live co-located in the plugin folder; `visuals.json` is the fallback registry for emoji / library icons and the skill reverse-map. Full resolution chain (per-node-type → shared → fallback) is documented in [server/nodes/README.md → Icon + color](./server/nodes/README.md) and [docs-internal/plugin_system.md](./docs-internal/plugin_system.md).
-When tier 1 or 2 hits, `_metadata_dict` emits the URL `/api/schemas/nodes/{type}/icon`. The endpoint serves the SVG with `Content-Type: image/svg+xml` and a long cache header.
+Backend endpoints serve SVGs at `GET /api/schemas/nodes/<type>/icon` (plugin icons) and `GET /api/schemas/credentials/<provider>/icon` (credential brand icons). Frontend resolver at [client/src/assets/icons/index.ts](./client/src/assets/icons/index.ts) dispatches `lib:brand` / URL passthrough / emoji / dead-code `asset:<key>`.
-**Credential icon resolution** (F7 — `Credential.get_icon_path` → `services/plugin/credential.py`):
-1. **Central catalogue** — `server/credentials/icons/<provider>.svg` (10 brand icons today).
-2. **Co-located fallback** — `<credential_class_folder>/credential_<id>.svg` (none today; available for plugin-scoped credentials).
-3. Endpoint `GET /api/schemas/credentials/{provider}/icon` serves the SVG; `credential_providers.json` `icon_ref` entries use the URL form for the 10 migrated providers.
-
-**Color resolution** (F2 — per-plugin `meta.json`):
-1. **Per-plugin `meta.json`** in the plugin folder — `{"color": "#xxxxxx"}`. 113 plugin folders ship this today (mirrors icon co-location).
-2. Fallback: **`visuals.json` `color`** field. Only legacy entries that haven't been migrated rely on this; post-F2 visuals.json has zero `color` fields.
-
-**Files:**
-- [server/nodes/visuals.json](./server/nodes/visuals.json) — fallback registry. Post-F1/F2/F7 shape: `{nodeType: {icon?, skill?}}` (103 entries — **zero color fields, zero `asset:<key>` values**; only emoji + `lobehub:<brand>` icons + skill reverse-map remain).
-- [server/nodes/_visuals.py](./server/nodes/_visuals.py) — `get_icon`, `get_color`, `get_plugin_icon_path` (per-node-type tier + shared fallback), **`get_plugin_meta(node_type, key)`** (F2 resolver).
-- [server/nodes/&lt;group&gt;/&lt;plugin&gt;/icon.svg](./server/nodes/) — shared plugin icon (Phase 9 / RFC §6.5).
-- [server/nodes/&lt;group&gt;/&lt;plugin&gt;/icon_&lt;nodeType&gt;.svg](./server/nodes/whatsapp/) — per-node-type icon (post-F7 closure; whatsapp uses 3).
-- [server/nodes/&lt;group&gt;/&lt;plugin&gt;/meta.json](./server/nodes/) — co-located plugin color (F2 / RFC §6.6).
-- [server/credentials/icons/&lt;provider&gt;.svg](./server/credentials/icons/) — credential brand icons (F7).
-
-**Wire format** (frontend resolver at [client/src/assets/icons/index.ts](./client/src/assets/icons/index.ts)):
-- `/api/schemas/nodes/<type>/icon` — backend-served plugin icon (prefixed with `API_CONFIG.PYTHON_BASE_URL` in dev)
-- `/api/schemas/credentials/<provider>/icon` — backend-served credential icon (F7)
-- `<lib>:<brand>` — NPM icon package, e.g. `lobehub:Claude`
-- `data:` / URL passthrough — inline SVG or remote
-- plain emoji / short text — rendered as-is
-- `asset:<key>` — dead defensive code in the resolver. No `asset:<key>` values exist in visuals.json or `credential_providers.json` after F7 closure; the bundled `client/src/assets/icons/` directory was reduced to the resolver + `themedGlyphs.ts` (30 SVGs + 7 group barrels deleted at commit `f2366db`).
-
-**Latent Phase 6 bug fix (commit `95249a1`):** `BaseNode.__init_subclass__` previously called `_metadata_dict()` BEFORE `register_node_class(cls)`, so `get_plugin_icon_path` couldn't resolve the plugin via `get_node_class()`. The URL emission silently fell through to `visuals.json`'s `asset:<key>`. Swapping the two register calls activates the URL path as intended.
-
-**Frontend rendering:**
-- Single `<NodeIcon icon className />` primitive at [client/src/assets/icons/NodeIcon.tsx](./client/src/assets/icons/NodeIcon.tsx) dispatches lib-component / `<img>` / text branches.
-- Does **not** apply parent `color` — would mono-tint lobehub `.Color` brand SVGs whose paths use `currentColor`. Sites that want a tinted backdrop set `style={{ color: brandColor }}` on the parent + `bg-tint-soft` / `border-tint`.
-- SKILL.md icon/color resolves via `SkillLoader._parse_skill_metadata` from the first node in `allowed-tools` using the same handler chain. Orphan skills (personality, memory operators, autonomous patterns — no node target) keep inline `metadata.icon` and `metadata.color`.
-
-**Do not:**
-- Ship inline data URIs from the backend.
-- Maintain frontend override tables.
-- Declare `icon`/`color` on a node class (use icon.svg + meta.json, or visuals.json for fallback cases).
-- Declare them in SKILL.md when the skill targets a node.
+**Do not** declare `icon` / `color` as class attributes on a node (the override path was removed in F1). Drop `icon.svg` (or `icon_<nodeType>.svg` for multi-node folders like whatsapp) and `meta.json` into the plugin folder. SKILL.md icon/color resolves from the first node in `allowed-tools` — only orphan skills keep inline `metadata.icon` / `metadata.color`.
## Key Files & Components
@@ -1666,28 +1570,17 @@ server/nodes/document/
### Temporal Distributed Execution
-Workflows execute via Temporal for durability and horizontal scaling. Temporal is an always-on service (like WhatsApp) started unconditionally by `npm run start` and `npm run dev`.
-
-**Architecture**: Three dispatch paths, gated by settings flags (see [docs-internal/TEMPORAL_ARCHITECTURE.md](./docs-internal/TEMPORAL_ARCHITECTURE.md)):
-
-| Path | Trigger | Behavior |
-|---|---|---|
-| Legacy single activity (`execute_node_activity`) | Default | Every node routed through one dispatcher; WebSocket round-trip back to FastAPI. |
-| Per-type activity (`node.{type}.v{version}`) | `TEMPORAL_PER_TYPE_DISPATCH=true` (F4.A, commit `8261b05`) | Each plugin gets its own `@activity.defn` via `BaseNode.as_activity()`. Per-plugin retry/timeout/heartbeat configs apply. Direct call to `workflow_service.execute_node()` (no WS round-trip; worker shares FastAPI process). Foundation for future `TemporalWorkerPool` per-queue routing. |
-| Agent-as-child-workflow (`AgentWorkflow`) | `TEMPORAL_AGENT_WORKFLOW_ENABLED=true` (F4.B infra, commit `a4d009e`) | aiAgent / chatAgent / 12 specialized agents / 2 team leads become Temporal child workflows. LLM step = activity. Tool calls = per-type activities. `deep_agent` / `rlm_agent` / `claude_code_agent` keep single-activity execution (externalised loops). |
+Workflows execute via Temporal for durability and horizontal scaling. Three dispatch paths (legacy `execute_node_activity` / per-type `node.{type}.v{version}` (F4.A) / Agent-as-child-workflow (F4.B)) gated by `TEMPORAL_PER_TYPE_DISPATCH` and `TEMPORAL_AGENT_WORKFLOW_ENABLED` settings flags.
-- **Per-node retry** - Failed nodes retry independently (up to 3 attempts)
-- **Per-node timeout** - Long AI nodes don't block short nodes (10 min default)
-- **Horizontal scaling** - Activities distributed across worker pool
-- **Activity heartbeats** - Legacy path: `activity.heartbeat()` on every non-matching WebSocket broadcast in the read loop (`services/temporal/activities.py`). Per-type path: heartbeats at pipeline-stage boundaries inside `BaseNode.as_activity()`. Both keep long-running DeepAgent/browser operations alive past the 2-min `heartbeat_timeout`.
+Full architecture, dispatch matrix, per-node lifecycle, heartbeat semantics, the 15 migrating agent types + 3 bypass agents (deep_agent / rlm_agent / claude_code_agent), the 5 F4.B agent activities (`execute_llm_step.v1` / `persist_turn.v1` / `compact_memory.v1` / `prepare_payload.v1` / `broadcast_progress.v1`), and the future `TemporalWorkerPool` per-queue routing live in [docs-internal/TEMPORAL_ARCHITECTURE.md](./docs-internal/TEMPORAL_ARCHITECTURE.md). Tool-call dispatch under F4.A documented at [docs-internal/tool_building_pipeline.md §9](./docs-internal/tool_building_pipeline.md).
**Configuration** (`.env`):
```env
TEMPORAL_SERVER_ADDRESS=localhost:7233
TEMPORAL_NAMESPACE=default
TEMPORAL_TASK_QUEUE=machina-tasks
-TEMPORAL_PER_TYPE_DISPATCH=false # F4.A flag (default off)
-TEMPORAL_AGENT_WORKFLOW_ENABLED=false # F4.B flag (default off)
+TEMPORAL_PER_TYPE_DISPATCH=true # F4.A flag — per-type activity dispatch
+TEMPORAL_AGENT_WORKFLOW_ENABLED=true # F4.B flag — agent-as-child-workflow
```
**Temporal Server** (`temporal-server` global CLI):
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index b2a8d4cb..3e722936 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -75,16 +75,14 @@ The diagram above shows the full lifecycle of a workflow node from TypeScript de
- Guide: [native_llm_sdk.md](docs-internal/native_llm_sdk.md)
**Add a dual-purpose tool (workflow node + AI tool)**
-- Mark node `group: ['category', 'tool']`
-- Pydantic schema in `server/services/ai.py` (`_get_tool_schema`)
-- Dispatch in `server/services/handlers/tools.py`
-- Guide: [dual_purpose_tool_node_creation.md](docs-internal/dual_purpose_tool_node_creation.md)
+- Plugin folder under `server/nodes/<category>/<name>/` with `group: ['category', 'tool']` and `usable_as_tool = True`
+- Pydantic `Params` doubles as the LLM-visible tool schema (no separate `_get_tool_schema` entry)
+- Guide: [node_creation.md](docs-internal/node_creation.md)
**Add a specialized AI agent**
-- Add the plugin under `server/nodes/agent/` (typically extends the shared specialized-agent base in `server/nodes/agent/_specialized.py`)
+- Add the plugin under `server/nodes/agent/<name>/` (extends `SpecializedAgentBase` from `server/nodes/agent/_specialized.py`)
- Add to `SPECIALIZED_AGENT_TYPES` in `server/constants.py`
-- Register in `server/services/node_executor.py`
-- Guide: [specialized_agent_node_creation.md](docs-internal/specialized_agent_node_creation.md)
+- Guide: [node_creation.md](docs-internal/node_creation.md)
**Add a skill**
- New folder under `server/skills/<category>/`
@@ -136,16 +134,15 @@ Full setup and scripts reference: [SETUP.md](docs-internal/SETUP.md) - [SCRIPTS.
| [claude_code_agent_architecture.md](docs-internal/claude_code_agent_architecture.md) | Claude Code SDK integration as a specialized agent |
| [autonomous_agent_creation.md](docs-internal/autonomous_agent_creation.md) | Autonomous agents with Code Mode patterns |
| [event_waiter_system.md](docs-internal/event_waiter_system.md) | Push-based trigger waiters |
-| [status_broadcaster.md](docs-internal/status_broadcaster.md) | WebSocket broadcaster and 127 handlers |
+| [status_broadcaster.md](docs-internal/status_broadcaster.md) | WebSocket broadcaster (live handler count via `len(MESSAGE_HANDLERS) + len(get_ws_handlers())`) |
| [credentials_encryption.md](docs-internal/credentials_encryption.md) | Fernet + PBKDF2 credentials system |
| [memory_compaction.md](docs-internal/memory_compaction.md) | Token tracking and model-aware compaction |
| [pricing_service.md](docs-internal/pricing_service.md) | LLM and API cost tracking |
| [proxy_service.md](docs-internal/proxy_service.md) | Residential proxy provider management |
| [ci_cd.md](docs-internal/ci_cd.md) | GitHub Actions workflows |
| [node_creation.md](docs-internal/node_creation.md) | How to create new nodes |
-| [ai_tool_node_creation.md](docs-internal/ai_tool_node_creation.md) | Creating dedicated AI Agent tool nodes |
-| [specialized_agent_node_creation.md](docs-internal/specialized_agent_node_creation.md) | Creating specialized AI agent nodes |
-| [dual_purpose_tool_node_creation.md](docs-internal/dual_purpose_tool_node_creation.md) | Dual-purpose workflow + tool nodes |
+| [memory_lifecycle.md](docs-internal/memory_lifecycle.md) | Canonical home for markdown memory format, vector store, claude_code_agent session resume |
+| [tool_building_pipeline.md](docs-internal/tool_building_pipeline.md) | Canonical home for `_build_tool_from_node`, tool discovery, per-type Temporal dispatch |
| [new_service_integration.md](docs-internal/new_service_integration.md) | External service integration guide |
| [cli_services_integration.md](docs-internal/cli_services_integration.md) | CLI service lifecycle management |
| [onboarding.md](docs-internal/onboarding.md) | Welcome wizard and replay |
diff --git a/docs-internal/plugin_authoring_rfc.md b/docs-internal/ARCHIVE/plugin_authoring_rfc.md
similarity index 97%
rename from docs-internal/plugin_authoring_rfc.md
rename to docs-internal/ARCHIVE/plugin_authoring_rfc.md
index 6b1fc1d7..c04387cc 100644
--- a/docs-internal/plugin_authoring_rfc.md
+++ b/docs-internal/ARCHIVE/plugin_authoring_rfc.md
@@ -1,8 +1,16 @@
# RFC: Plugin Authoring Standard — Folder-Default + Temporal Activities + CloudEvents Broadcasts
+> **ARCHIVED — Shipped Sprint Plan.** This RFC's recommendations were shipped across Waves 11.H, F1, F2, F4.A, F4.B, F5, F6, F7 (commits `1e18d3e` through `134e7a8`). Preserved here as a design-rationale record. For current state see:
+>
+> - [TEMPORAL_ARCHITECTURE.md](../TEMPORAL_ARCHITECTURE.md) — three Temporal dispatch paths (legacy / per-type / AgentWorkflow)
+> - [plugin_system.md](../plugin_system.md) — Wave 11 plugin model (BaseNode hierarchy, six generic registries, credentials, Wave 12 event framework)
+> - [server/nodes/README.md](../../server/nodes/README.md) — canonical authoring recipe (folder-per-plugin, icon.svg, meta.json)
+> - [status_broadcaster.md](../status_broadcaster.md) — CloudEvents v1.0 envelope contract (`WorkflowEvent` factories, broadcaster wrappers)
+> - [node_creation.md](../node_creation.md) — decision tree for new plugins
+
| Field | Value |
|---|---|
-| Status | Draft — awaiting approval |
+| Status | Shipped (archived 2026-05-14) |
| Scope | `server/nodes/**`, `server/services/plugin/**`, `server/services/events/**`, `server/services/temporal/**`, `docs-internal/*plugin*.md`, `docs-internal/node_creation.md`, `CLAUDE.md`, `server/nodes/README.md` |
| Authors | Plan generated by Claude Code |
| Date | 2026-05-13 |
diff --git a/docs-internal/DESIGN.md b/docs-internal/DESIGN.md
index 823ac8d2..68785dfa 100644
--- a/docs-internal/DESIGN.md
+++ b/docs-internal/DESIGN.md
@@ -50,21 +50,9 @@ workflow.execute(workflow_id, workflow_data)
### 1. Temporal Distributed (primary production mode)
-When `TEMPORAL_ENABLED=true` and the Temporal server is reachable, every workflow node executes through Temporal. Three dispatch paths coexist (gated by settings flags shipped in F4):
+When `TEMPORAL_ENABLED=true` and the Temporal server is reachable, every workflow node executes through Temporal. Three dispatch paths coexist (legacy `execute_node_activity` / per-type `node.{type}.v{version}` / Agent-as-child-workflow `AgentWorkflow`) gated by `TEMPORAL_PER_TYPE_DISPATCH` and `TEMPORAL_AGENT_WORKFLOW_ENABLED` flags. Per-node retries, per-node timeouts, horizontal scaling via worker pool, and the FIRST_COMPLETED orchestrator pattern.
-| Path | Trigger | Behavior |
-|---|---|---|
-| **Legacy single activity** (`execute_node_activity`) | Default | Every node routes through one dispatcher; WS round-trip back to FastAPI. Stable since Wave 11. |
-| **Per-type activity** (`node.{type}.v{version}`) | `TEMPORAL_PER_TYPE_DISPATCH=true` (F4.A, commit `8261b05`) | Each plugin gets its own `@activity.defn` via `BaseNode.as_activity()`. Per-plugin retry / timeout / heartbeat configs apply. Direct call to `workflow_service.execute_node()` (no WS round-trip; worker shares FastAPI process). |
-| **Agent-as-child-workflow** (`AgentWorkflow`) | `TEMPORAL_AGENT_WORKFLOW_ENABLED=true` (F4.B, commits `a4d009e` + `0459131`) | 15 migrating agent types (aiAgent / chatAgent / 12 specialized / 2 team leads) run as Temporal child workflows. LLM steps + tool calls become activities. `deep_agent` / `rlm_agent` / `claude_code_agent` stay single-activity (externalised session state). |
-
-- Per-node retries (3 attempts by default) and per-node timeouts (10 min default)
-- Horizontal scaling via worker pool
-- Connection pooling via shared `aiohttp` session for WebSocket-based node execution (legacy path only — per-type and AgentWorkflow paths call workflow_service in-process)
-- Pure orchestrator in `services/temporal/workflow.py` using `asyncio.wait(FIRST_COMPLETED)` so dependent nodes start immediately when their specific dependency completes
-- Class-based activities in `services/temporal/activities.py` (legacy) + `services/temporal/agent_activities.py` (5 F4.B activities: `execute_llm_step`, `persist_turn`, `compact_memory`, `prepare_payload`, `broadcast_progress`)
-
-See [TEMPORAL_ARCHITECTURE.md](TEMPORAL_ARCHITECTURE.md) for the full matrix + canonical pseudo-code.
+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)
diff --git a/docs-internal/agent_architecture.md b/docs-internal/agent_architecture.md
index f83faac1..e08131cb 100644
--- a/docs-internal/agent_architecture.md
+++ b/docs-internal/agent_architecture.md
@@ -3,9 +3,9 @@
Detailed architecture reference for how AI Agent (`aiAgent`) and Chat Agent (`chatAgent`) discover skills and tools from connected nodes, inject them into the LLM prompt, and execute tools via LangGraph.
> **Related Documentation:**
-> - [AI Tool Node Guide](./ai_tool_node_creation.md) - Creating dedicated AI Agent tool nodes
-> - [Dual-Purpose Tool Guide](./dual_purpose_tool_node_creation.md) - Nodes that work as workflow nodes AND AI tools
-> - [Specialized Agent Guide](./specialized_agent_node_creation.md) - Creating specialized AI agents
+> - [Node Creation Guide](./node_creation.md) - Canonical plugin recipe (covers tool nodes, dual-purpose nodes, specialized agents)
+> - [Tool Building Pipeline](./tool_building_pipeline.md) - Canonical home for `_build_tool_from_node`, tool discovery, per-type Temporal dispatch
+> - [Memory Lifecycle](./memory_lifecycle.md) - Canonical home for markdown memory format, vector store, session resume
> - [CLAUDE.md](../CLAUDE.md) - Project overview and full node inventory
## Table of Contents
@@ -358,322 +358,24 @@ This text is appended to the system message. The full SKILL.md body (instruction
## Tool Building Pipeline
-### 1. Tool Data Collection
+Tool building + dispatch lives in [tool_building_pipeline.md](./tool_building_pipeline.md). The five stages (DISCOVER edges → BUILD StructuredTool → BIND to LangGraph → INVOKE via LLM tool_calls → DISPATCH through execute_tool) and the dispatch matrix (delegated agents / Android services / dual-purpose plugins / direct tools / search APIs / generic fallback) are documented there. The single-source-of-truth rule — execute_tool owns the tool node lifecycle, parent-agent closures only emit phase broadcasts — is the contract test enforces.
-In `_collect_agent_connections()`, edges targeting `input-tools` are collected:
+Patterns covered in the canonical doc:
-```python
-elif target_handle == 'input-tools':
- tool_params = await database.get_node_parameters(source_node_id)
- tool_entry = {
- 'node_id': source_node_id,
- 'node_type': tool_type, # 'calculatorTool', 'pythonExecutor', etc.
- 'parameters': tool_params,
- 'label': source_node.get('data', {}).get('label', tool_type),
- 'connected_services': [] # Populated for androidTool only
- }
-```
-
-For `androidTool` (toolkit pattern), edges are scanned a second time to find Android service nodes connected to the toolkit, populating `connected_services`.
-
-### 2. Tool Name and Schema Mapping
-
-`_build_tool_from_node()` in `server/services/ai.py` maps each node type:
-
-| Node Type | Tool Name | Pydantic Schema |
-|-----------|-----------|-----------------|
-| `calculatorTool` | `calculator` | `CalculatorSchema(operation, a, b)` |
-| `currentTimeTool` | `get_current_time` | `CurrentTimeSchema(timezone)` |
-| `timer` | `timer` | `TimerSchema(delay, unit)` |
-| `duckduckgoSearch` | `web_search` | `DuckDuckGoSearchSchema(query, max_results)` |
-| `pythonExecutor` | `python_code` | `PythonCodeSchema(code)` |
-| `javascriptExecutor` | `javascript_code` | `JavaScriptCodeSchema(code)` |
-| `httpRequest` | `http_request` | `HttpRequestSchema(url, method, body)` |
-| `whatsappSend` | `whatsapp_send` | `WhatsAppSendSchema(recipient_type, phone, message_type, message, ...)` |
-| `whatsappDb` | `whatsapp_db` | `WhatsAppDbSchema(operation, chat_id, query, limit)` |
-| `braveSearch` | `brave_search` | `BraveSearchSchema(query, max_results, country, safe_search)` |
-| `serperSearch` | `serper_search` | `SerperSearchSchema(query, max_results, search_type, country)` |
-| `perplexitySearch` | `perplexity_search` | `PerplexitySearchSchema(query, model, search_recency_filter)` |
-| `gmaps_locations` | `geocode` | `GeocodeSchema(address)` |
-| `gmaps_nearby_places` | `nearby_places` | `NearbyPlacesSchema(location, type, radius)` |
-| `androidTool` | `android_device` | `AndroidToolSchema(service_id, action, parameters)` |
-| Direct Android services | `android_<service>` | `AndroidServiceSchema(action, parameters)` |
-| `aiAgent` | `delegate_to_ai_agent` | `DelegateToAgentSchema(task, context)` |
-| Specialized agents | `delegate_to_<type>` | `DelegateToAgentSchema(task, context)` |
-
-### 3. StructuredTool Construction
-
-```python
-# Lookup or generate schema
-schema = _get_tool_schema(node_type, schema_params)
-
-# Create LangChain tool with placeholder function
-tool = StructuredTool.from_function(
- name=tool_name,
- description=tool_description,
- func=lambda **kwargs: kwargs, # Placeholder -- actual execution via callback
- args_schema=schema # Pydantic BaseModel subclass
-)
-
-# Store config for execution
-tool_configs[tool.name] = {
- 'node_id': node_id,
- 'node_type': node_type,
- 'parameters': node_params,
- 'connected_services': connected_services
-}
-```
-
-### 4. Database Schema Override
-
-The Tool Schema Editor UI stores custom schemas in the `tool_schemas` table. If a custom schema exists for a node, it takes priority over the default:
-
-```python
-db_schema = await self.database.get_tool_schema(node_id)
-if db_schema:
- tool_name = db_schema.tool_name
- tool_description = db_schema.tool_description
- schema = self._build_schema_from_config(db_schema.schema_config)
-```
-
-### 5. Tool Binding
-
-After all tools are built, they are bound to the LLM model via LangChain:
-
-```python
-model_with_tools = chat_model.bind_tools(tools)
-```
-
-This makes the LLM aware of all available tool schemas during generation. The LLM decides when to call tools based on the user's request and tool descriptions.
+- DEFAULT_TOOL_NAMES map (node_type → LLM-visible tool name)
+- Database tool-schema override via ToolSchema model + Tool Schema Editor UI
+- Gateway-tool pattern (androidTool aggregates connected service nodes)
+- Direct Android service tools (16 entries, skip the toolkit)
+- Agent delegation (`delegate_to_*` fire-and-forget background tasks)
+- Per-type Temporal activity dispatch (F4.A, when TEMPORAL_PER_TYPE_DISPATCH=true)
+- Auto-skill edges (writeTodos, WhatsApp tools bundle a default skill)
---
-## Tool Execution Flow
-
-### 1. Tool Executor Callback
-
-Built as a closure in `execute_agent()` / `execute_chat_agent()`:
-
-```python
-async def tool_executor(tool_name: str, tool_args: Dict) -> Any:
- config = tool_configs.get(tool_name, {})
- tool_node_id = config.get('node_id')
-
- # Broadcast "executing" status to tool node (UI glow animation)
- await broadcaster.update_node_status(tool_node_id, "executing", {...})
-
- # Inject services for nested delegation
- config['ai_service'] = self
- config['database'] = self.database
- config['nodes'] = context.get('nodes', [])
- config['edges'] = context.get('edges', [])
-
- # Dispatch to handler
- result = await execute_tool(tool_name, tool_args, config)
-
- # Broadcast "success" status
- await broadcaster.update_node_status(tool_node_id, "success", {...})
-
- return result
-```
-
-### 2. Dispatch Router
-
-`execute_tool()` in `server/services/handlers/tools.py` routes by `node_type`:
-
-```python
-async def execute_tool(tool_name, tool_args, config):
- node_type = config.get('node_type', '')
-
- if node_type == 'calculatorTool': return await _execute_calculator(tool_args)
- elif node_type == 'pythonExecutor': return await _execute_python_code(tool_args, config['parameters'])
- elif node_type == 'javascriptExecutor': return await _execute_javascript_code(tool_args, config['parameters'])
- elif node_type == 'currentTimeTool': return await _execute_current_time(tool_args)
- elif node_type == 'timer': return await handle_timer(...)
- elif node_type == 'duckduckgoSearch': return await _execute_duckduckgo_search(tool_args)
- elif node_type == 'braveSearch': return await _execute_brave_search_tool(tool_args, config['parameters'])
- elif node_type == 'serperSearch': return await _execute_serper_search_tool(tool_args, config['parameters'])
- elif node_type == 'perplexitySearch': return await _execute_perplexity_search_tool(tool_args, config['parameters'])
- elif node_type == 'whatsappSend': return await _execute_whatsapp_send(tool_args)
- elif node_type == 'whatsappDb': return await _execute_whatsapp_db(tool_args)
- elif node_type == 'androidTool': return await _execute_android_toolkit(tool_args, config)
- elif node_type in ANDROID_SERVICE_TYPES: return await _execute_android_service(tool_args, config)
- elif node_type == 'gmaps_locations': return await _execute_geocoding(tool_args)
- elif node_type == 'gmaps_nearby_places': return await _execute_nearby_places(tool_args)
- elif node_type in DELEGATED_AGENT_TYPES: return await _execute_delegated_agent(tool_args, config)
- else: return await _execute_generic(tool_args, config)
-```
-
-### 3. Status Broadcasting
-
-Three-level broadcasting ensures the UI shows tool execution state:
-
-```
-1. Agent node: "executing_tool" phase with tool_name
-2. Tool node: "executing" status (cyan glow animation on SquareNode)
-3. Completion: "success" or "error" on tool node
-```
-
-For the Android Toolkit, status is broadcast to the **connected service node** (e.g., Battery Monitor), not the toolkit itself -- so the user sees the actual service node glowing.
-
-### 4. Dual-Purpose Tools
-
-Nodes like `pythonExecutor`, `whatsappSend`, `gmaps_locations` work as both workflow nodes and AI tools. The handler prioritizes LLM-provided args, falling back to node parameters:
-
-```python
-async def _execute_python_code(args, node_params):
- # LLM args take priority, node params as fallback
- code = args.get('code', '') or node_params.get('code', '')
-```
-
-### 5. Android Toolkit (Sub-Node Pattern)
-
-```
-[Battery Monitor] --+
-[WiFi Automation] --+--> [Android Toolkit] --(tools)--> [AI Agent]
-[Location] --------+
-```
-
-The LLM sees a single `android_device` tool. It specifies `service_id` to choose which connected service to invoke:
-
-```python
-async def _execute_android_toolkit(args, config):
- service_id = args.get('service_id')
- connected_services = config.get('connected_services', [])
-
- # Find matching service by service_id
- target = next((s for s in connected_services if s['service_id'] == service_id), None)
-
- # Broadcast to connected service node (not toolkit)
- await broadcaster.update_node_status(target['node_id'], "executing", {...})
-
- # Execute via AndroidService
- result = await android_service.execute_service(service_id=service_id, action=action, ...)
-```
-
-### 6. Direct Android Service Tools
-
-Android service nodes can also connect directly to `input-tools` (bypassing the toolkit). The handler maps camelCase node types to snake_case service IDs:
-
-```python
-SERVICE_ID_MAP = {
- 'batteryMonitor': 'battery',
- 'wifiAutomation': 'wifi_automation',
- 'bluetoothAutomation': 'bluetooth_automation',
- 'location': 'location',
- 'appLauncher': 'app_launcher',
- # ... 16 total mappings
-}
-```
-
-### 7. Agent Delegation (Fire-and-Forget)
-
-When an AI Agent or specialized agent is connected to `input-tools`, the parent can delegate tasks:
-
-```python
-async def _execute_delegated_agent(args, config):
- # Inject API key for child agent
- provider = detect_ai_provider(node_type, child_params)
- api_key = await ai_service.auth.get_api_key(provider)
- child_params['api_key'] = api_key
-
- # Build prompt from delegation args
- child_params['prompt'] = f"{args['task']}\n\nContext:\n{args.get('context', '')}"
-
- # Spawn as background task
- async def run_child_agent():
- await broadcaster.update_node_status(node_id, "executing", {...})
- result = await handle_chat_agent(node_id, node_type, child_params, child_context, ...)
- await broadcaster.update_node_status(node_id, "success", {...})
- return result
-
- task = asyncio.create_task(run_child_agent())
- _delegated_tasks[task_id] = task
-
- # Return immediately -- parent continues without waiting
- return {"status": "delegated", "task_id": task_id}
-```
-
-Design decisions:
-- **Memory isolation**: Child uses its own connected memory, not shared with parent
-- **Error isolation**: Child errors don't propagate to parent
-- **Task tracking**: Background tasks in `_delegated_tasks` dict, cleaned up on completion
-
----
## Memory Integration
-### Collection
-
-Memory data collected from `input-memory` handle in `_collect_agent_connections()`:
-
-```python
-if target_handle == 'input-memory':
- memory_params = await database.get_node_parameters(source_node_id)
- memory_data = {
- 'node_id': source_node_id,
- 'session_id': memory_params.get('sessionId', 'default'),
- 'window_size': int(memory_params.get('windowSize', 10)),
- 'memory_content': memory_params.get('memoryContent', ''), # Markdown
- 'long_term_enabled': memory_params.get('longTermEnabled', False),
- 'retrieval_count': int(memory_params.get('retrievalCount', 3))
- }
-```
-
-### Message Construction
-
-```python
-# 1. System message (with skills already injected)
-initial_messages = [SystemMessage(content=system_message)]
-
-# 2. Long-term memory retrieval (if enabled)
-if memory_data.get('long_term_enabled'):
- store = _get_memory_vector_store(session_id) # InMemoryVectorStore per session
- docs = store.similarity_search(prompt, k=retrieval_count)
- initial_messages.append(SystemMessage(content=f"Relevant context:\n{docs}"))
-
-# 3. Short-term conversation history
-history_messages = _parse_memory_markdown(memory_content) # Markdown -> [HumanMessage, AIMessage, ...]
-initial_messages.extend(history_messages)
-
-# 4. Current user prompt
-initial_messages.append(HumanMessage(content=prompt))
-```
-
-### Post-Execution Save
-
-After graph execution completes:
-
-```python
-# Append new exchange
-updated = _append_to_memory_markdown(memory_content, 'human', prompt)
-updated = _append_to_memory_markdown(updated, 'ai', response)
-
-# Trim to window size, get removed texts
-updated, removed = _trim_markdown_window(updated, window_size)
-
-# Archive removed texts to vector store (if enabled)
-if removed and long_term_enabled:
- store = _get_memory_vector_store(session_id)
- store.add_texts(removed)
-
-# Save updated markdown back to node parameters
-await database.save_node_parameters(memory_node_id, {'memoryContent': updated})
-```
-
-### Memory Format
-
-Stored as human-readable markdown:
-
-```markdown
-# Conversation History
-
-### **Human** (2025-01-30 14:23:45)
-What is the weather like today?
-
-### **Assistant** (2025-01-30 14:23:48)
-I don't have access to real-time weather data...
-```
+Memory load + save lives in [memory_lifecycle.md](./memory_lifecycle.md). The agent loop reads `memory_data` from `_collect_agent_connections()` (via the `input-memory` edge), prepends parsed history to the system message + current prompt, runs the graph, then appends the turn + trims the window + archives trimmed text to the vector store. The markdown helpers (`parse_memory_markdown`, `append_to_memory_markdown`, `trim_markdown_window`) and the vector store (`InMemoryVectorStore` with HuggingFace embeddings) are the load-bearing surface — see the canonical doc for signatures, the markdown format, and the engine-specific adapter table (aiAgent / deep_agent / rlm_agent / claude_code_agent native session resume bridge).
---
diff --git a/docs-internal/agent_delegation.md b/docs-internal/agent_delegation.md
index 3ec3c921..21dc6f78 100644
--- a/docs-internal/agent_delegation.md
+++ b/docs-internal/agent_delegation.md
@@ -2,6 +2,8 @@
How memory, parameters, and execution context flow when one AI agent delegates work to another agent connected as a tool.
+> **Related docs:** [tool_building_pipeline.md](./tool_building_pipeline.md) for the underlying `_build_tool_from_node` + `execute_tool` pipeline that backs `delegate_to_*` (delegation tools share the same StructuredTool construction path as other AI tools — what makes them special is the fire-and-forget background task and the `{"status": "delegated"}` lifecycle opt-out documented there).
+
## Overview
AI Agents can delegate tasks to other agents connected to their `input-tools` handle. The parent agent's LLM decides when to call the child agent by invoking a `delegate_to_<agent>` tool. The child spawns as an independent `asyncio.Task` and the parent continues working immediately -- a **fire-and-forget** pattern.
diff --git a/docs-internal/ai_tool_node_creation.md b/docs-internal/ai_tool_node_creation.md
deleted file mode 100644
index fbc322fd..00000000
--- a/docs-internal/ai_tool_node_creation.md
+++ /dev/null
@@ -1,675 +0,0 @@
-# AI Agent Tool Node Creation Guide
-
-> **⚠️ Pre-Wave-11 — historical reference only.**
-> Node authoring now happens on the backend: each node is a Python plugin under `server/nodes/<category>/<node>.py` that emits a `NodeSpec`. The frontend reads specs via [client/src/lib/nodeSpec.ts](../client/src/lib/nodeSpec.ts) + [adapters/nodeSpecToDescription.ts](../client/src/adapters/nodeSpecToDescription.ts). See [plugin_system.md](./plugin_system.md) and [server/nodes/README.md](../server/nodes/README.md) for the current model. The snippets below that reference `client/src/nodeDefinitions/*` are kept for historical context.
-
-This guide provides a complete walkthrough for creating **dedicated AI Agent tool nodes** - nodes that ONLY work as AI tools (passive, no workflow execution). For nodes that work as BOTH workflow nodes AND AI tools, see the [Dual-Purpose Tool Node Guide](./dual_purpose_tool_node_creation.md).
-
-> **Related Documentation:**
-> - [Specialized Agent Guide](./specialized_agent_node_creation.md) - Create specialized AI agents (Android, Coding, Web, Social, Task)
-> - [Dual-Purpose Tool Node Guide](./dual_purpose_tool_node_creation.md) - Nodes that work as workflow nodes AND AI tools
-> - [Node Creation Guide](./node_creation.md) - General node creation patterns
-> - [CLAUDE.md](../CLAUDE.md) - Project overview, toolkit sub-node execution pattern
-
-## Table of Contents
-
-1. [Architecture Overview](#architecture-overview)
-2. [Tool Calling Architecture](#tool-calling-architecture)
-3. [Tool Types](#tool-types)
-4. [Creating a Simple Tool Node](#creating-a-simple-tool-node)
-5. [Backend Implementation](#backend-implementation)
-6. [Status Broadcasting](#status-broadcasting)
-7. [Complete Example: Weather Tool](#complete-example-weather-tool)
-8. [Checklist](#checklist)
-
-> **Note:** For creating **Specialized Agents** (like Android Control Agent, Social Media Agent), see the [Specialized Agent Guide](./specialized_agent_node_creation.md).
-
----
-
-## Architecture Overview
-
-### Tool Execution Flow
-
-```
-User Query → AI Agent → LLM decides to use tool
- ↓
- LangGraph tool binding
- ↓
- Tool executor callback
- ↓
- Status broadcast (executing)
- ↓
- Handler executes tool logic
- ↓
- Status broadcast (success)
- ↓
- Result returned to LLM
- ↓
- LLM continues reasoning
-```
-
-### Key Components
-
-| Component | Location | Purpose |
-|-----------|----------|---------|
-| Tool Node Definition | `client/src/nodeDefinitions/toolNodes.ts` | Frontend node structure |
-| Tool Building | `server/services/ai.py` → `_build_tool_from_node()` | Build LangChain tools from nodes |
-| Tool Schema | `server/services/ai.py` → `_get_tool_schema()` | Pydantic schema for LLM |
-| Tool Handler | `server/services/handlers/tools.py` → `execute_tool()` | Execution dispatch |
-| Constants | `server/constants.py` | Type definitions |
-| Status Broadcaster | `server/services/status_broadcaster.py` | UI updates |
-
----
-
-## Tool Calling Architecture
-
-### Overview
-
-Tool nodes connect to AI Agent's `input-tools` handle. The LLM uses the tool's Pydantic schema to understand parameters and fills them automatically during reasoning.
-
-**Key Principle**: Skills (`input-skill`) provide SKILL.md context only. Actual tool execution happens via nodes connected to `input-tools`.
-
-### Tool Building Pipeline
-
-```
-Tool Node (connected to input-tools)
- ↓
-handle_ai_agent() / handle_chat_agent() collects tool_data
- ↓
-_build_tool_from_node() creates StructuredTool from node config
- ↓
-_get_tool_schema() returns Pydantic schema for LLM
- ↓
-LangGraph binds tools to LLM
- ↓
-LLM decides to call tool with auto-filled arguments
- ↓
-tool_executor callback → execute_tool() in handlers/tools.py
- ↓
-Dispatch to handler: _execute_calculator(), _execute_http_request(), etc.
-```
-
-### Key Functions
-
-| Function | File | Purpose |
-|----------|------|---------|
-| `_build_tool_from_node()` | `ai.py` | Converts node config to LangChain StructuredTool |
-| `_get_tool_schema()` | `ai.py` | Returns Pydantic schema for tool's LLM-visible parameters |
-| `execute_tool()` | `handlers/tools.py` | Dispatches tool execution to appropriate handler |
-
-### Supported Tool Types
-
-All tools use the same schema-based approach:
-
-| Tool Type | Schema | Handler |
-|-----------|--------|---------|
-| `calculatorTool` | `CalculatorSchema` | `_execute_calculator()` |
-| `currentTimeTool` | `CurrentTimeSchema` | `_execute_current_time()` |
-| `duckduckgoSearch` | `DuckDuckGoSearchSchema` | `_execute_duckduckgo_search()` |
-| `braveSearch` | `BraveSearchSchema` | `handle_brave_search()` |
-| `serperSearch` | `SerperSearchSchema` | `handle_serper_search()` |
-| `perplexitySearch` | `PerplexitySearchSchema` | `handle_perplexity_search()` |
-| `httpRequest` | `HttpRequestSchema` | `_execute_http_request()` |
-| `pythonExecutor` | `PythonCodeSchema` | `_execute_python_code()` |
-| `whatsappSend` | `WhatsAppSendSchema` | `_execute_whatsapp_send()` |
-| `whatsappDb` | `WhatsAppDbSchema` | `_execute_whatsapp_db()` |
-| `androidTool` | `AndroidToolSchema` | `_execute_android_toolkit()` |
-| `aiAgent` | `DelegateToAgentSchema` | `_execute_delegated_agent()` |
-| `chatAgent` | `DelegateToAgentSchema` | `_execute_delegated_agent()` |
-| Specialized Agents | `DelegateToAgentSchema` | `_execute_delegated_agent()` |
-
-> **Note:** AI Agents and Specialized Agents can be used as tools by other agents. When connected to `input-tools`, they use the `DelegateToAgentSchema` with `task` and optional `context` fields. Execution is fire-and-forget (async) - the parent agent continues immediately while the child executes in background. See [Specialized Agent Guide](./specialized_agent_node_creation.md#async-agent-delegation) for details.
-
-### Skills vs Tools
-
-| Aspect | Skills (`input-skill`) | Tools (`input-tools`) |
-|--------|------------------------|----------------------|
-| Purpose | Provide context/instructions | Execute actions |
-| Content | SKILL.md markdown loaded into system message | Node configuration with Pydantic schema |
-| Execution | None - context only | LLM calls tool, handler executes |
-| Connection | Connect to `input-skill` handle | Connect to `input-tools` handle |
-| Example | `httpSkill` provides HTTP capability context | `httpRequest` tool actually makes requests |
-
----
-
-## Tool Types
-
-### Simple Tool Nodes
-
-Self-contained tools with all logic in a single handler.
-
-**Examples:** `calculatorTool`, `currentTimeTool`, `duckduckgoSearch`, `braveSearch`, `serperSearch`, `perplexitySearch`
-
-```
-[Calculator Tool] ──────────────────────→ [AI Agent]
- │ │
- └─ Pydantic schema + handler └─ Uses tool during reasoning
-```
-
-> **For Specialized Agents** (like Android Control Agent, Social Media Agent), see the [Specialized Agent Guide](./specialized_agent_node_creation.md).
-
----
-
-## Creating a Simple Tool Node
-
-### Step 1: Frontend Node Definition
-
-Create or update `client/src/nodeDefinitions/toolNodes.ts`:
-
-```typescript
-import { INodeTypeDescription, NodeConnectionType } from '../types/INodeProperties';
-
-// Tool-specific icon (use Unicode symbols for consistency)
-const WEATHER_TOOL_ICON = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
- <circle cx="12" cy="12" r="5"/>
- <path d="M12 1v2M12 21v2M4.22 4.22l1.42 1.42M18.36 18.36l1.42 1.42M1 12h2M21 12h2M4.22 19.78l1.42-1.42M18.36 5.64l1.42-1.42"/>
-</svg>`;
-
-export const toolNodes: Record<string, INodeTypeDescription> = {
- // ... existing tools ...
-
- weatherTool: {
- displayName: 'Weather Tool',
- name: 'weatherTool',
- icon: WEATHER_TOOL_ICON,
- group: ['ai', 'tool'], // CRITICAL: 'tool' marks it as AI tool
- version: 1,
- subtitle: 'Weather Information',
- description: 'Allow AI Agent to get current weather and forecasts',
- defaults: {
- name: 'Weather',
- color: '#3b82f6' // Blue accent
- },
-
- // Tool nodes are passive - no main input
- inputs: [],
-
- // Single output connects to AI Agent's input-tools handle
- outputs: [{
- name: 'tool',
- displayName: 'Tool',
- type: 'main' as NodeConnectionType,
- description: 'Connect to AI Agent tool handle'
- }],
-
- // Tool parameters
- properties: [
- {
- displayName: 'Tool Name',
- name: 'toolName',
- type: 'string',
- default: 'get_weather',
- required: true,
- description: 'Name the AI will use to call this tool'
- },
- {
- displayName: 'Tool Description',
- name: 'toolDescription',
- type: 'string',
- default: 'Get current weather conditions and forecast for a location. Returns temperature, humidity, conditions, and forecast.',
- typeOptions: { rows: 3 },
- description: 'Description helps the AI understand when to use this tool'
- },
- {
- displayName: 'API Provider',
- name: 'apiProvider',
- type: 'options',
- default: 'openweathermap',
- options: [
- { name: 'OpenWeatherMap', value: 'openweathermap' },
- { name: 'WeatherAPI', value: 'weatherapi' }
- ],
- description: 'Weather data provider'
- },
- {
- displayName: 'Units',
- name: 'units',
- type: 'options',
- default: 'metric',
- options: [
- { name: 'Metric (Celsius)', value: 'metric' },
- { name: 'Imperial (Fahrenheit)', value: 'imperial' }
- ]
- }
- ]
- }
-};
-
-// Add to TOOL_NODE_TYPES array
-export const TOOL_NODE_TYPES = [
- 'calculatorTool',
- 'currentTimeTool',
- 'duckduckgoSearch',
- 'androidTool',
- 'weatherTool' // Add new tool here
-];
-```
-
-### Step 2: Register in Node Definitions
-
-Update `client/src/nodeDefinitions.ts`:
-
-```typescript
-import { toolNodes, TOOL_NODE_TYPES } from './nodeDefinitions/toolNodes';
-
-export const nodeDefinitions: Record<string, INodeTypeDescription> = {
- // ... other nodes ...
- ...toolNodes,
-};
-
-export { TOOL_NODE_TYPES };
-```
-
-### Step 3: Add to Constants
-
-Update `server/constants.py`:
-
-```python
-# Tool node types (connect to AI Agent's input-tools handle)
-AI_TOOL_TYPES: FrozenSet[str] = frozenset([
- 'calculatorTool',
- 'currentTimeTool',
- 'duckduckgoSearch',
- 'androidTool',
- 'weatherTool', # Add new tool here
-])
-```
-
----
-
-## Backend Implementation
-
-### Step 4: Add Pydantic Schema to `_get_tool_schema()`
-
-In `server/services/ai.py`, add the tool schema inside the `_get_tool_schema()` method. Schemas are defined inline using Pydantic:
-
-```python
-def _get_tool_schema(self, node_type: str, params: Dict[str, Any]) -> Type[BaseModel]:
- """Get Pydantic schema for tool based on node type."""
-
- # ... existing schemas ...
-
- # Weather tool schema
- if node_type == 'weatherTool':
- class WeatherToolSchema(BaseModel):
- """Schema for weather tool - defines what parameters the LLM can pass."""
- location: str = Field(
- description="City name or coordinates (e.g., 'London', 'New York, US', '51.5,-0.1')"
- )
- include_forecast: bool = Field(
- default=False,
- description="Whether to include 5-day forecast"
- )
-
- return WeatherToolSchema
-
- # Fallback: generic schema
- class GenericSchema(BaseModel):
- input: str = Field(description="Input for the tool")
-
- return GenericSchema
-```
-
-**Important**: Schemas define what the LLM can pass to the tool. Use clear `Field(description=...)` to help the LLM understand each parameter.
-
-### Step 5: Create Tool Handler
-
-In `server/services/handlers/tools.py`, add a handler function and register it in the dispatcher:
-
-```python
-import httpx
-from typing import Dict, Any
-from core.logging import get_logger
-
-logger = get_logger(__name__)
-
-
-async def _execute_weather_tool(
- llm_params: Dict[str, Any],
- tool_params: Dict[str, Any]
-) -> str:
- """Execute weather tool.
-
- Args:
- llm_params: Parameters from LLM (auto-filled based on schema)
- tool_params: Node configuration from frontend (apiProvider, units, etc.)
-
- Returns:
- Weather information as string for LLM
- """
- # LLM-provided parameters (from schema)
- location = llm_params.get('location', '')
- include_forecast = llm_params.get('include_forecast', False)
-
- # Node configuration parameters (from frontend)
- api_provider = tool_params.get('apiProvider', 'openweathermap')
- units = tool_params.get('units', 'metric')
- api_key = tool_params.get('api_key', '')
-
- if not location:
- return "Error: No location provided"
-
- if not api_key:
- return "Error: Weather API key not configured"
-
- try:
- async with httpx.AsyncClient(timeout=10.0) as client:
- if api_provider == 'openweathermap':
- url = "https://api.openweathermap.org/data/2.5/weather"
- params = {'q': location, 'appid': api_key, 'units': units}
- response = await client.get(url, params=params)
- response.raise_for_status()
- data = response.json()
-
- temp_unit = "C" if units == "metric" else "F"
- result = f"""Weather in {data['name']}:
-- Temperature: {data['main']['temp']}{temp_unit}
-- Conditions: {data['weather'][0]['description']}
-- Humidity: {data['main']['humidity']}%"""
-
- if include_forecast:
- forecast_url = "https://api.openweathermap.org/data/2.5/forecast"
- forecast_response = await client.get(forecast_url, params=params)
- if forecast_response.status_code == 200:
- forecast_data = forecast_response.json()
- result += "\n\n5-Day Forecast:"
- for item in forecast_data['list'][:5]:
- result += f"\n- {item['dt_txt']}: {item['main']['temp']}{temp_unit}"
-
- return result
- else:
- return f"Error: Unknown API provider: {api_provider}"
-
- except httpx.HTTPStatusError as e:
- logger.error(f"Weather API error: {e}")
- return f"Error: Weather API returned {e.response.status_code}"
- except Exception as e:
- logger.error(f"Weather tool error: {e}")
- return f"Error fetching weather: {str(e)}"
-```
-
-### Step 6: Register in `execute_tool()` Dispatcher
-
-The `execute_tool()` function dispatches to the appropriate handler based on node type:
-
-```python
-async def execute_tool(
- tool_type: str,
- tool_params: Dict[str, Any],
- llm_params: Dict[str, Any]
-) -> str:
- """Dispatch tool execution to appropriate handler.
-
- Args:
- tool_type: Node type (e.g., 'weatherTool', 'calculatorTool')
- tool_params: Node configuration from frontend
- llm_params: Parameters auto-filled by LLM based on schema
-
- Returns:
- Tool result as string for LLM consumption
- """
- if tool_type == 'calculatorTool':
- return await _execute_calculator(llm_params)
- elif tool_type == 'currentTimeTool':
- return await _execute_current_time(llm_params)
- elif tool_type == 'duckduckgoSearch':
- return await _execute_duckduckgo_search(llm_params, tool_params)
- elif tool_type == 'httpRequest':
- return await _execute_http_request(llm_params, tool_params)
- elif tool_type == 'pythonExecutor':
- return await _execute_python_code(llm_params, tool_params)
- elif tool_type == 'whatsappSend':
- return await _execute_whatsapp_send(llm_params, tool_params)
- elif tool_type == 'whatsappDb':
- return await _execute_whatsapp_db(llm_params, tool_params)
- elif tool_type == 'androidTool':
- return await _execute_android_toolkit(llm_params, tool_params)
- elif tool_type == 'weatherTool':
- return await _execute_weather_tool(llm_params, tool_params)
- else:
- return f"Unknown tool type: {tool_type}"
-```
-
-### Step 7: Add to Default Tool Names/Descriptions
-
-In `server/services/ai.py`, add the tool to `_build_tool_from_node()`:
-
-```python
-DEFAULT_TOOL_NAMES = {
- 'calculatorTool': 'calculator',
- 'currentTimeTool': 'get_current_time',
- 'duckduckgoSearch': 'web_search',
- 'braveSearch': 'brave_search',
- 'serperSearch': 'serper_search',
- 'perplexitySearch': 'perplexity_search',
- 'androidTool': 'android_device',
- 'whatsappSend': 'whatsapp_send',
- 'whatsappDb': 'whatsapp_db',
- 'weatherTool': 'get_weather', # Add new tool
-}
-
-DEFAULT_TOOL_DESCRIPTIONS = {
- 'calculatorTool': 'Perform mathematical calculations.',
- 'currentTimeTool': 'Get the current date and time.',
- 'duckduckgoSearch': 'Search the web using DuckDuckGo (free, no API key).',
- 'braveSearch': 'Search the web using Brave Search.',
- 'serperSearch': 'Search the web using Google via Serper API.',
- 'perplexitySearch': 'Search the web using Perplexity Sonar AI with citations.',
- 'androidTool': 'Control Android device.',
- 'whatsappSend': 'Send WhatsApp messages.',
- 'whatsappDb': 'Query WhatsApp database.',
- 'weatherTool': 'Get current weather and forecasts.', # Add description
-}
-```
-
----
-
-## Status Broadcasting
-
-Tool nodes should show execution status in the UI when the AI Agent calls them.
-
-### Backend: Broadcast Status
-
-In `server/services/ai.py`, the `execute_agent` function broadcasts status:
-
-```python
-async def execute_agent(
- self,
- node_id: str,
- parameters: Dict[str, Any],
- context: Dict[str, Any]
-) -> Dict[str, Any]:
- """Execute AI Agent with tools."""
- workflow_id = context.get('workflow_id')
- broadcaster = get_status_broadcaster()
-
- # Build tool executor with status broadcasting
- async def tool_executor(tool_name: str, tool_args: Dict) -> Any:
- config = tool_configs.get(tool_name, {})
- tool_node_id = config.get('node_id')
- tool_type = config.get('tool_type')
-
- # Broadcast "executing" to tool node
- if tool_node_id and broadcaster:
- await broadcaster.update_node_status(
- tool_node_id,
- "executing",
- {"message": f"Executing {tool_name}", "tool_name": tool_name},
- workflow_id=workflow_id
- )
-
- # Execute tool
- result = await execute_tool(tool_type, config, tool_args)
-
- # Broadcast "success" to tool node
- if tool_node_id and broadcaster:
- await broadcaster.update_node_status(
- tool_node_id,
- "success",
- {"message": f"{tool_name} completed", "result": str(result)[:200]},
- workflow_id=workflow_id
- )
-
- return result
-
- # ... rest of agent execution
-```
-
-### Frontend: Status Display
-
-Tool nodes use the same status mechanism as other nodes via `useNodeStatus`:
-
-```typescript
-// In SquareNode.tsx or custom component
-const nodeStatus = useNodeStatus(id);
-const isExecuting = nodeStatus?.status === 'executing';
-
-// Apply visual effects
-style={{
- animation: isExecuting ? 'pulse 1.5s ease-in-out infinite' : 'none',
- boxShadow: isExecuting ? `0 0 10px ${theme.dracula.cyan}` : 'none'
-}}
-```
-
----
-
-## Complete Example: Weather Tool
-
-Here's a complete implementation checklist:
-
-### Files to Create/Modify
-
-| File | Action | Purpose |
-|------|--------|---------|
-| `client/src/nodeDefinitions/toolNodes.ts` | Modify | Add node definition |
-| `server/constants.py` | Modify | Add to AI_TOOL_TYPES |
-| `server/services/ai.py` | Modify | Add schema + DEFAULT_TOOL_NAMES |
-| `server/services/handlers/tools.py` | Modify | Add handler + dispatcher case |
-
-### Frontend Code
-
-```typescript
-// toolNodes.ts
-weatherTool: {
- displayName: 'Weather Tool',
- name: 'weatherTool',
- icon: '...',
- group: ['ai', 'tool'],
- outputs: [{
- name: 'tool',
- displayName: 'Tool',
- type: 'main' as NodeConnectionType,
- description: 'Connect to AI Agent tool handle'
- }],
- properties: [
- { name: 'toolName', type: 'string', default: 'get_weather' },
- { name: 'toolDescription', type: 'string', default: 'Get weather...' },
- { name: 'apiProvider', type: 'options', default: 'openweathermap', ... },
- { name: 'units', type: 'options', default: 'metric', ... }
- ]
-}
-
-// Add to TOOL_NODE_TYPES
-export const TOOL_NODE_TYPES = [..., 'weatherTool'];
-```
-
-### Backend Code
-
-```python
-# constants.py
-AI_TOOL_TYPES: FrozenSet[str] = frozenset([
- ...,
- 'weatherTool',
-])
-
-# ai.py - in _get_tool_schema()
-if node_type == 'weatherTool':
- class WeatherToolSchema(BaseModel):
- location: str = Field(description="City name or coordinates")
- include_forecast: bool = Field(default=False, description="Include 5-day forecast")
- return WeatherToolSchema
-
-# ai.py - in _build_tool_from_node()
-DEFAULT_TOOL_NAMES = {
- ...,
- 'weatherTool': 'get_weather',
-}
-DEFAULT_TOOL_DESCRIPTIONS = {
- ...,
- 'weatherTool': 'Get current weather conditions and forecast for a location.',
-}
-
-# tools.py - handler function
-async def _execute_weather_tool(llm_params: Dict, tool_params: Dict) -> str:
- location = llm_params.get('location', '')
- include_forecast = llm_params.get('include_forecast', False)
- api_key = tool_params.get('api_key', '')
- # ... implementation ...
-
-# tools.py - in execute_tool() dispatcher
-elif tool_type == 'weatherTool':
- return await _execute_weather_tool(llm_params, tool_params)
-```
-
----
-
-## Checklist
-
-### Tool Node Creation
-
-**Frontend (`client/src/nodeDefinitions/toolNodes.ts`):**
-- [ ] Add node definition
- - [ ] Set `group: ['tool', 'ai']` (CRITICAL: 'tool' marks as AI tool)
- - [ ] Define `toolName` and `toolDescription` properties
- - [ ] Set output with `name: 'tool'` connecting to AI Agent's `input-tools`
-- [ ] Add to `TOOL_NODE_TYPES` array
-- [ ] Verify node appears in Component Palette under "AI Tools" category
-
-**Backend - Constants (`server/constants.py`):**
-- [ ] Add to `AI_TOOL_TYPES` frozenset
-
-**Backend - Schema (`server/services/ai.py`):**
-- [ ] Add Pydantic schema in `_get_tool_schema()` method
-- [ ] Add tool name to `DEFAULT_TOOL_NAMES` dict in `_build_tool_from_node()`
-- [ ] Add tool description to `DEFAULT_TOOL_DESCRIPTIONS` dict
-
-**Backend - Handler (`server/services/handlers/tools.py`):**
-- [ ] Create handler function `_execute_<tool_name>(llm_params, tool_params)`
-- [ ] Add dispatcher case in `execute_tool()` function
-
-**Testing:**
-- [ ] Connect tool to AI Agent's `input-tools` handle
-- [ ] Verify tool appears in agent's available tools (check logs)
-- [ ] Test tool execution via agent query
-- [ ] Verify status broadcast shows execution animation in UI
-
-> **For Specialized Agents**, see the [Specialized Agent Guide](./specialized_agent_node_creation.md#testing).
-
----
-
-## Best Practices
-
-1. **Tool Descriptions**: Write clear, detailed descriptions that help the LLM understand when to use the tool. The `DEFAULT_TOOL_DESCRIPTIONS` in `ai.py` is what the LLM sees.
-
-2. **Schema Fields**: Use descriptive `Field(description=...)` parameters. The LLM reads these to understand what values to provide.
-
-3. **Parameter Separation**:
- - `llm_params`: Values the LLM provides based on schema (e.g., `location`, `query`)
- - `tool_params`: Node configuration from frontend (e.g., `api_key`, `apiProvider`)
-
-4. **Error Handling**: Return clear error messages as strings. The LLM can understand and act on them.
-
-5. **Status Broadcasting**: The AI Agent handles status broadcasting automatically when tools execute.
-
-6. **Logging**: Use structured logging with tool name and parameters:
- ```python
- logger.info(f"[{tool_type}] Executing with params: {llm_params}")
- ```
-
-7. **Timeouts**: Set reasonable timeouts for external API calls (default 10-30 seconds).
-
-8. **API Keys**: Retrieve API keys from `tool_params` (node configuration), not `llm_params`.
-
-9. **Return Strings**: Tool handlers should return strings that the LLM can process. Format results clearly.
-
-10. **Skills Provide Context Only**: Remember that SKILL.md files only provide context to the system message. Actual tool execution happens via nodes connected to `input-tools`.
diff --git a/docs-internal/cli_agent_framework.md b/docs-internal/cli_agent_framework.md
index c8538bf8..30c0d673 100644
--- a/docs-internal/cli_agent_framework.md
+++ b/docs-internal/cli_agent_framework.md
@@ -315,6 +315,8 @@ Lifespan: `main.py` enters `mcp_app.router.lifespan_context()` so `StreamableHTT
## Memory bridge — `simpleMemory` → `claude_code_agent`
+> See [memory_lifecycle.md](./memory_lifecycle.md) for the shared markdown surface (every agent uses the same `parse_memory_markdown` / `append_to_memory_markdown` / `trim_markdown_window` helpers to maintain `simpleMemory.memory_content`). This section documents what's UNIQUE to `claude_code_agent`: the markdown is the UI mirror, not the resume channel.
+
Connecting a `simpleMemory` node to a `claude_code_agent` makes the
spawned `claude -p` resume its prior session natively across runs.
**No system-prompt injection, no JSONL synthesis, no API fallback.**
diff --git a/docs-internal/deep_agent.md b/docs-internal/deep_agent.md
index 44c35867..9c4261d7 100644
--- a/docs-internal/deep_agent.md
+++ b/docs-internal/deep_agent.md
@@ -4,7 +4,9 @@ Specialized agent node powered by [LangChain DeepAgents](https://github.com/lang
> **Related Documentation:**
> - [Agent Architecture](./agent_architecture.md) - LangGraph skill injection and tool execution
-> - [Specialized Agent Guide](./specialized_agent_node_creation.md) - Creating specialized AI agents
+> - [Node Creation Guide](./node_creation.md) - Canonical plugin recipe (covers specialized agents)
+> - [Memory Lifecycle](./memory_lifecycle.md) - Canonical home for memory markdown, vector store, compaction triggers
+> - [Tool Building Pipeline](./tool_building_pipeline.md) - Canonical home for tool schema construction
> - [Agent Delegation](./agent_delegation.md) - Memory, parameters, and execution context flow
## Table of Contents
@@ -96,42 +98,9 @@ ResponseExtractor.extract() -> save memory -> return result
## DeepAgents Package
-### Installation
+MachinaOs depends on `deepagents>=0.4.12` (with `langchain-core`, `langchain`, `langchain-anthropic`, `langchain-google-genai`, `wcmatch`). Upstream API surface (`create_deep_agent`, middleware, sub-agent protocol, backend protocol) is documented at https://github.com/langchain-ai/deepagents — refer there for SDK details.
-```
-pip install deepagents>=0.4.12
-```
-
-**Dependencies:** `langchain-core`, `langchain`, `langchain-anthropic`, `langchain-google-genai`, `wcmatch`
-
-### create_deep_agent()
-
-```python
-from deepagents import create_deep_agent
-
-agent = create_deep_agent(
- model=None, # str ("provider:model") | BaseChatModel | None
- tools=None, # Sequence[BaseTool | Callable | dict]
- system_prompt=None, # str | SystemMessage
- middleware=(), # Sequence[AgentMiddleware]
- subagents=None, # Sequence[SubAgent | CompiledSubAgent | AsyncSubAgent]
- skills=None, # list[str] (paths to skill dirs)
- memory=None, # list[str] (paths to AGENTS.md files)
- response_format=None, # ResponseFormat | type | dict
- context_schema=None, # type[ContextT]
- checkpointer=None, # Checkpointer
- store=None, # BaseStore
- backend=None, # BackendProtocol | BackendFactory
- interrupt_on=None, # dict[str, bool | InterruptOnConfig]
- debug=False, # bool
- name=None, # str
- cache=None, # BaseCache
-)
-```
-
-Returns a **`CompiledStateGraph`** -- a compiled LangGraph graph compatible with streaming, Studio, checkpointers, and all LangGraph features.
-
-**Default model:** `claude-sonnet-4-6` (via `ChatAnthropic`). MachinaOs uses the lower-level `langchain.agents.create_agent()` instead, passing a pre-built `BaseChatModel` instance and no default middleware -- only connected MachinaOs tool nodes are used.
+MachinaOs **does not** call `create_deep_agent()` directly. We use the lower-level `langchain.agents.create_agent()` from the same package, passing a pre-built `BaseChatModel` and no default middleware so only connected MachinaOs tool nodes are used. Filesystem operations route through `LocalShellBackend(root_dir=workspace_dir, virtual_mode=True)` so paths sandbox to the per-workflow workspace.
### Built-in Tools
@@ -268,26 +237,7 @@ The handler passes raw `tool_data` to the service, which calls `ToolAdapter.buil
## Memory Integration
-Deep Agent supports MachinaOs's SimpleMemory node (markdown-based + vector store), following the same lifecycle as `execute_chat_agent`:
-
-### Load (before agent invocation)
-1. Parse markdown via `_parse_memory_markdown()` into LangChain messages
-2. If `long_term_enabled`: retrieve relevant context from `_get_memory_vector_store()` via `similarity_search()`, append to system_message
-3. Prepend history messages to the deepagents input messages list
-
-### Save (after agent invocation)
-1. Append human prompt and AI response via `_append_to_memory_markdown()`
-2. Trim to `window_size` via `_trim_markdown_window()`
-3. Archive removed messages to vector store if `long_term_enabled`
-4. Persist updated markdown to database via `save_node_parameters()`
-
-### Result Metadata
-```python
-result["memory"] = {
- "session_id": session_id,
- "history_loaded": history_count,
-}
-```
+Deep Agent uses MachinaOs's SimpleMemory node like every other agent — the full lifecycle (markdown parse / append / trim, vector store, claude_code_agent native session bridge) lives in [memory_lifecycle.md](./memory_lifecycle.md). Deep-Agent-specific bits: `DeepAgentService.execute()` accepts the parsed history as a LangChain `BaseMessage` list (same shape as aiAgent's input), and the post-execution save attaches a `memory.session_id` / `memory.history_loaded` block to the result envelope. No engine-specific memory format; the markdown is shared across all four agents that use simpleMemory.
---
diff --git a/docs-internal/dual_purpose_tool_node_creation.md b/docs-internal/dual_purpose_tool_node_creation.md
deleted file mode 100644
index 3a0660eb..00000000
--- a/docs-internal/dual_purpose_tool_node_creation.md
+++ /dev/null
@@ -1,1056 +0,0 @@
-# Dual-Purpose Tool Node Creation Guide
-
-> **⚠️ Pre-Wave-11 — historical reference only.**
-> Node authoring now happens on the backend: each node is a Python plugin under `server/nodes/<category>/<node>.py` that emits a `NodeSpec`. The frontend reads specs via [client/src/lib/nodeSpec.ts](../client/src/lib/nodeSpec.ts) + [adapters/nodeSpecToDescription.ts](../client/src/adapters/nodeSpecToDescription.ts). See [plugin_system.md](./plugin_system.md) and [server/nodes/README.md](../server/nodes/README.md) for the current model. The snippets below that reference `client/src/nodeDefinitions/*` are kept for historical context.
-
-This guide provides a complete walkthrough for creating **dual-purpose nodes** - nodes that work both as standalone workflow nodes AND as AI Agent/Zeenie tools. This pattern allows existing workflow nodes to be connected directly to an AI Agent's `input-tools` handle, where the LLM fills in the node's parameter schema.
-
-> **Related Documentation:**
-> - [AI Agent Tool Node Creation Guide](./ai_tool_node_creation.md) - Dedicated tool nodes (passive, tool-only)
-> - [Node Creation Guide](./node_creation.md) - General node creation patterns
-> - [CLAUDE.md](../CLAUDE.md) - Project overview and architecture
-
-## Table of Contents
-
-1. [Architecture Overview](#architecture-overview)
-2. [Dual-Purpose vs Dedicated Tool Nodes](#dual-purpose-vs-dedicated-tool-nodes)
-3. [Creating a Dual-Purpose Tool Node](#creating-a-dual-purpose-tool-node)
-4. [Backend Implementation](#backend-implementation)
-5. [Complete Example: WhatsApp Nodes](#complete-example-whatsapp-nodes)
-6. [Checklist](#checklist)
-
----
-
-## Architecture Overview
-
-### Dual-Purpose Node Design
-
-```
- ┌─────────────────────────────────────────┐
- │ Dual-Purpose Node │
- │ (e.g., whatsappSend) │
- │ │
- Workflow Input ──┤ input-main │
- │ │ │
- │ ▼ │
- │ ┌───────────┐ ┌───────────────────┐ │
- │ │ Parameters│ │ Tool Output │─┼──→ AI Agent input-tools
- │ └───────────┘ └───────────────────┘ │
- │ │ │
- │ ▼ │
- Workflow Output ◄┼── output-main │
- │ │
- └─────────────────────────────────────────┘
-```
-
-### Two Usage Modes
-
-**Mode 1: Workflow Node**
-```
-[Trigger] → [WhatsApp Send] → [Next Node]
- │
- Executes with configured parameters
-```
-
-**Mode 2: AI Tool**
-```
-[WhatsApp Send] ──(tool output)──→ [AI Agent input-tools]
- │
- LLM fills parameter schema
- Tool handler executes
-```
-
-### Key Components
-
-| Component | Location | Purpose |
-|-----------|----------|---------|
-| Node Definition | `client/src/nodeDefinitions/*.ts` | Frontend structure with both outputs |
-| Tool Schema | `server/services/ai.py` | Pydantic schema for LLM |
-| Tool Handler | `server/services/handlers/tools.py` | Tool execution logic |
-| Node Handler | `server/services/handlers/*.py` | Workflow execution logic |
-| Execution Logic | `server/services/execution/models.py` | Dynamic exclusion when used as tool |
-
----
-
-## Dual-Purpose vs Dedicated Tool Nodes
-
-### Dedicated Tool Nodes (Passive)
-
-Nodes that ONLY work as AI tools, not as workflow nodes.
-
-**Characteristics:**
-- `inputs: []` - No main input
-- `outputs: [{ name: 'tool' }]` - Single tool output
-- Added to `AI_TOOL_TYPES` constant
-- Excluded from workflow execution via `CONFIG_NODE_TYPES`
-
-**Examples:** `calculatorTool`, `currentTimeTool`, `duckduckgoSearch`
-
-### Dual-Purpose Tool Nodes (Active)
-
-Nodes that work BOTH as workflow nodes AND as AI tools.
-
-**Characteristics:**
-- Has main input AND main output for workflow data flow
-- Has additional `tool` output for AI Agent connection
-- `group` includes `'tool'` marker
-- NOT in `AI_TOOL_TYPES` (would break workflow execution)
-- Dynamically excluded when connected to `input-tools` handle
-
-**Examples:** `whatsappSend`, `whatsappDb`, `twitterSend`, `twitterSearch`, `twitterUser`, `httpRequest`, `pythonExecutor`, `javascriptExecutor`, `addLocations`, `showNearbyPlaces`, `braveSearch`, `serperSearch`, `perplexitySearch`
-
-### Comparison Table
-
-| Feature | Dedicated Tool | Dual-Purpose Tool |
-|---------|----------------|-------------------|
-| Workflow execution | No | Yes |
-| AI tool usage | Yes | Yes |
-| Main input | No | Yes |
-| Main output | No | Yes |
-| Tool output | Yes | Yes |
-| In `AI_TOOL_TYPES` | Yes | **No** |
-| Group array | `['ai', 'tool']` | `['category', 'tool']` |
-
----
-
-## Creating a Dual-Purpose Tool Node
-
-### Step 1: Frontend Node Definition
-
-Add/modify the node definition with both workflow handles AND tool output:
-
-```typescript
-// client/src/nodeDefinitions/myNodes.ts
-import { INodeTypeDescription, NodeConnectionType } from '../types/INodeProperties';
-
-export const myNodes: Record<string, INodeTypeDescription> = {
- myDualPurposeNode: {
- displayName: 'My Node',
- name: 'myDualPurposeNode',
- icon: '...',
- // CRITICAL: Include 'tool' in group for dual-purpose behavior
- group: ['myCategory', 'tool'],
- version: 1,
- subtitle: 'Description',
- description: 'Works as workflow node and AI tool',
- defaults: { name: 'My Node', color: '#6366f1' },
-
- // Main input for workflow data flow
- inputs: [{
- name: 'main',
- displayName: 'Input',
- type: 'main' as NodeConnectionType,
- description: 'Trigger input'
- }],
-
- // BOTH outputs: main for workflow, tool for AI Agent
- outputs: [
- {
- name: 'main',
- displayName: 'Output',
- type: 'main' as NodeConnectionType,
- description: 'Result output'
- },
- {
- name: 'tool',
- displayName: 'Tool',
- type: 'main' as NodeConnectionType,
- description: 'Connect to AI Agent tool handle'
- }
- ],
-
- // Full parameter schema - LLM will fill these when used as tool
- properties: [
- {
- displayName: 'Action',
- name: 'action',
- type: 'options',
- default: 'default_action',
- options: [
- { name: 'Action 1', value: 'action1' },
- { name: 'Action 2', value: 'action2' }
- ],
- description: 'Action to perform'
- },
- {
- displayName: 'Parameter',
- name: 'param1',
- type: 'string',
- default: '',
- description: 'Required parameter'
- },
- // ... more parameters
- ]
- }
-};
-```
-
-### Step 2: Define Tool Schema (Backend)
-
-In `server/services/ai.py`, add the Pydantic schema in `_get_tool_schema()`:
-
-```python
-from pydantic import BaseModel, Field
-from typing import Optional
-
-def _get_tool_schema(node_type: str) -> Optional[type]:
- """Get Pydantic schema for tool type."""
-
- # ... existing schemas ...
-
- # My dual-purpose node schema
- if node_type == 'myDualPurposeNode':
- class MyNodeSchema(BaseModel):
- """Description for LLM to understand the tool."""
- action: str = Field(
- default="action1",
- description="Action to perform: 'action1' or 'action2'"
- )
- param1: str = Field(
- description="Required parameter description"
- )
- optional_param: Optional[str] = Field(
- default=None,
- description="Optional parameter"
- )
- return MyNodeSchema
-
- return None
-```
-
-**Schema Design Tips:**
-- Use snake_case for field names (LLM convention)
-- Provide clear descriptions with examples
-- Use `Optional` for non-required fields
-- Include validation in Field() where appropriate
-
-### Step 3: Add Tool Handler (Backend)
-
-In `server/services/handlers/tools.py`:
-
-```python
-from typing import Dict, Any
-from core.logging import get_logger
-
-logger = get_logger(__name__)
-
-
-async def _execute_my_dual_purpose_node(
- tool_args: Dict[str, Any],
- node_params: Dict[str, Any]
-) -> Dict[str, Any]:
- """Execute my dual-purpose node as a tool.
-
- Args:
- tool_args: LLM-provided arguments matching the schema
- node_params: Node configuration parameters (from node definition)
-
- Returns:
- Dict with execution result
- """
- # Import the existing node handler
- from services.handlers.my_handlers import handle_my_node
-
- # Map LLM args (snake_case) to node params (camelCase)
- parameters = {
- 'action': tool_args.get('action', 'action1'),
- 'param1': tool_args.get('param1', ''),
- 'optionalParam': tool_args.get('optional_param', ''),
- }
-
- # Validate required fields
- if not parameters['param1']:
- return {"error": "param1 is required"}
-
- logger.info(f"[MyNode Tool] Executing {parameters['action']}...")
-
- try:
- # Call the existing node handler
- result = await handle_my_node(
- node_id="tool_my_node",
- node_type="myDualPurposeNode",
- parameters=parameters,
- context={}
- )
-
- if result.get('success'):
- return {
- "success": True,
- "action": parameters['action'],
- "result": result.get('result', {})
- }
- else:
- return {"error": result.get('error', 'Unknown error')}
-
- except Exception as e:
- logger.error(f"[MyNode Tool] Error: {e}")
- return {"error": f"Execution failed: {str(e)}"}
-```
-
-### Step 4: Register in Tool Dispatcher
-
-In `server/services/handlers/tools.py`, add to `execute_tool()`:
-
-```python
-async def execute_tool(tool_name: str, tool_args: Dict[str, Any],
- config: Dict[str, Any]) -> Dict[str, Any]:
- """Execute a tool by name using the appropriate handler."""
- node_type = config.get('node_type', '')
-
- # ... existing tool handlers ...
-
- # My dual-purpose node (existing node used as tool)
- if node_type == 'myDualPurposeNode':
- return await _execute_my_dual_purpose_node(tool_args, config.get('parameters', {}))
-
- # Generic fallback
- logger.warning(f"[Tool] Unknown tool type: {node_type}")
- return await _execute_generic(tool_args, config)
-```
-
-### Step 5: DO NOT Add to AI_TOOL_TYPES
-
-**Important:** Dual-purpose nodes should NOT be added to `AI_TOOL_TYPES` in `server/constants.py`.
-
-Why? Because `AI_TOOL_TYPES` is included in `CONFIG_NODE_TYPES`, which excludes nodes from independent workflow execution. Adding a dual-purpose node there would break its workflow functionality.
-
-The execution engine dynamically detects when a node is connected to `input-tools` handle and excludes it from parallel execution in that specific workflow only.
-
----
-
-## Backend Execution Logic
-
-### Dynamic Tool Detection
-
-The execution engine in `server/services/execution/models.py` dynamically detects tools:
-
-```python
-# In ExecutionContext.create()
-# Nodes connected to AI Agent/Zeenie config handles are sub-nodes
-# These handles: input-memory, input-tools, input-skill
-if target in ai_agent_node_ids and source and target_handle:
- if target_handle in ('input-memory', 'input-tools', 'input-skill'):
- subnode_ids.add(source)
-
-# Skip toolkit sub-nodes - they execute only via toolkit tool calls
-if node_id in subnode_ids:
- continue
-```
-
-This means:
-1. When `whatsappSend` is used in a normal workflow → executes independently
-2. When `whatsappSend` is connected to AI Agent's `input-tools` → excluded from independent execution, only executes via tool call
-
----
-
-## Complete Example: WhatsApp Nodes
-
-The `whatsappSend` and `whatsappDb` nodes are canonical examples of dual-purpose tools.
-
-### Frontend Definition (whatsappNodes.ts)
-
-```typescript
-whatsappSend: {
- displayName: 'WhatsApp Send',
- name: 'whatsappSend',
- icon: WHATSAPP_SEND_ICON,
- group: ['whatsapp', 'tool'], // Include 'tool' for dual-purpose
- version: 1,
- subtitle: 'Send WhatsApp Message',
- description: 'Send text, media, location, or contact messages via WhatsApp',
- defaults: { name: 'WhatsApp Send', color: '#25D366' },
-
- // Main input for workflow
- inputs: [{
- name: 'main',
- displayName: 'Input',
- type: 'main' as NodeConnectionType,
- description: 'Message input'
- }],
-
- // Both outputs
- outputs: [
- {
- name: 'main',
- displayName: 'Output',
- type: 'main' as NodeConnectionType,
- description: 'Message output'
- },
- {
- name: 'tool',
- displayName: 'Tool',
- type: 'main' as NodeConnectionType,
- description: 'Connect to AI Agent tool handle'
- }
- ],
-
- // Full parameter schema
- properties: [
- {
- displayName: 'Send To',
- name: 'recipientType',
- type: 'options',
- options: [
- { name: 'Phone Number', value: 'phone' },
- { name: 'Group', value: 'group' }
- ],
- default: 'phone'
- },
- {
- displayName: 'Phone Number',
- name: 'phone',
- type: 'string',
- default: '',
- displayOptions: { show: { recipientType: ['phone'] } }
- },
- {
- displayName: 'Message Type',
- name: 'messageType',
- type: 'options',
- options: [
- { name: 'Text', value: 'text' },
- { name: 'Image', value: 'image' },
- { name: 'Location', value: 'location' },
- // ...
- ],
- default: 'text'
- },
- // ... more parameters
- ]
-}
-```
-
-### Backend Schema (ai.py)
-
-```python
-if node_type == 'whatsappSend':
- class WhatsAppSendSchema(BaseModel):
- """Send WhatsApp messages to contacts or groups."""
- recipient_type: str = Field(
- default="phone",
- description="Send to: 'phone' for individual or 'group' for group chat"
- )
- phone: Optional[str] = Field(
- default=None,
- description="Phone number without + prefix (e.g., 1234567890). Required for recipient_type='phone'"
- )
- group_id: Optional[str] = Field(
- default=None,
- description="Group JID (e.g., [email protected]). Required for recipient_type='group'"
- )
- message_type: str = Field(
- default="text",
- description="Message type: 'text', 'image', 'video', 'audio', 'document', 'sticker', 'location', 'contact'"
- )
- message: Optional[str] = Field(
- default=None,
- description="Text message content. Required for message_type='text'"
- )
- media_url: Optional[str] = Field(
- default=None,
- description="URL for media (image/video/audio/document/sticker)"
- )
- caption: Optional[str] = Field(
- default=None,
- description="Caption for media messages"
- )
- latitude: Optional[float] = Field(default=None, description="Latitude for location")
- longitude: Optional[float] = Field(default=None, description="Longitude for location")
- location_name: Optional[str] = Field(default=None, description="Location name")
- address: Optional[str] = Field(default=None, description="Address")
- contact_name: Optional[str] = Field(default=None, description="Contact name")
- vcard: Optional[str] = Field(default=None, description="vCard 3.0 format")
- return WhatsAppSendSchema
-```
-
-### Backend Handler (tools.py)
-
-```python
-async def _execute_whatsapp_send(args: Dict[str, Any],
- node_params: Dict[str, Any]) -> Dict[str, Any]:
- """Send WhatsApp message with full message type support."""
- from services.handlers.whatsapp import handle_whatsapp_send
-
- # Map LLM args (snake_case) to node params (camelCase)
- parameters = {
- 'recipientType': args.get('recipient_type', 'phone'),
- 'phone': args.get('phone', ''),
- 'group_id': args.get('group_id', ''),
- 'messageType': args.get('message_type', 'text'),
- 'message': args.get('message', ''),
- 'mediaSource': 'url' if args.get('media_url') else 'none',
- 'mediaUrl': args.get('media_url', ''),
- 'caption': args.get('caption', ''),
- 'latitude': args.get('latitude'),
- 'longitude': args.get('longitude'),
- 'locationName': args.get('location_name', ''),
- 'address': args.get('address', ''),
- 'contactName': args.get('contact_name', ''),
- 'vcard': args.get('vcard', ''),
- }
-
- # Validate based on message type
- recipient_type = parameters['recipientType']
- message_type = parameters['messageType']
-
- if recipient_type == 'phone' and not parameters['phone']:
- return {"error": "Phone number is required for recipient_type='phone'"}
- if recipient_type == 'group' and not parameters['group_id']:
- return {"error": "Group ID is required for recipient_type='group'"}
- if message_type == 'text' and not parameters['message']:
- return {"error": "Message content is required for message_type='text'"}
- # ... more validation
-
- try:
- result = await handle_whatsapp_send(
- node_id="tool_whatsapp_send",
- node_type="whatsappSend",
- parameters=parameters,
- context={}
- )
-
- if result.get('success'):
- return {
- "success": True,
- "recipient": parameters['phone'] or parameters['group_id'],
- "message_type": message_type,
- "details": result.get('result', {})
- }
- else:
- return {"error": result.get('error', 'Unknown error')}
-
- except Exception as e:
- logger.error(f"[WhatsApp Tool] Error: {e}")
- return {"error": f"WhatsApp send failed: {str(e)}"}
-```
-
-### WhatsApp DB Node (Multi-Operation Pattern)
-
-The `whatsappDb` node demonstrates a multi-operation pattern with 6 different operations in a single dual-purpose node.
-
-**Frontend Definition:**
-```typescript
-whatsappDb: {
- displayName: 'WhatsApp DB',
- name: 'whatsappDb',
- icon: DATABASE_ICON,
- group: ['whatsapp', 'tool'],
- version: 1,
- description: 'Query WhatsApp database - contacts, groups, messages',
-
- inputs: [{ name: 'main', type: 'main' }],
- outputs: [
- { name: 'main', type: 'main', description: 'Query result' },
- { name: 'tool', type: 'main', description: 'Connect to AI Agent tool handle' }
- ],
-
- properties: [
- {
- displayName: 'Operation',
- name: 'operation',
- type: 'options',
- default: 'chat_history',
- options: [
- { name: 'Chat History', value: 'chat_history' },
- { name: 'Search Groups', value: 'search_groups' },
- { name: 'Get Group Info', value: 'get_group_info' },
- { name: 'Get Contact Info', value: 'get_contact_info' },
- { name: 'List Contacts', value: 'list_contacts' },
- { name: 'Check Contacts', value: 'check_contacts' },
- ],
- },
- // Conditional parameters per operation using displayOptions...
- ]
-}
-```
-
-**Backend Schema (ai.py):**
-```python
-if node_type == 'whatsappDb':
- class WhatsAppDbSchema(BaseModel):
- """Query WhatsApp database - contacts, groups, messages."""
- operation: str = Field(
- default="chat_history",
- description="Operation: 'chat_history', 'search_groups', 'get_group_info', 'get_contact_info', 'list_contacts', 'check_contacts'"
- )
- # chat_history params
- chat_type: Optional[str] = Field(default="individual", description="'individual' or 'group'")
- phone: Optional[str] = Field(default=None, description="Phone number for individual chat")
- group_id: Optional[str] = Field(default=None, description="Group JID for group operations")
- limit: Optional[int] = Field(default=50, description="Max messages (1-500)")
- offset: Optional[int] = Field(default=0, description="Pagination offset")
- message_filter: Optional[str] = Field(default="all", description="'all' or 'text_only'")
- # contact params
- query: Optional[str] = Field(default=None, description="Search query for contacts/groups")
- phones: Optional[str] = Field(default=None, description="Comma-separated phones for check_contacts")
- return WhatsAppDbSchema
-```
-
-**Backend Handler (tools.py):**
-```python
-async def _execute_whatsapp_db(args: Dict[str, Any], node_params: Dict[str, Any]) -> Dict[str, Any]:
- """Execute WhatsApp DB query operations."""
- from services.handlers.whatsapp import handle_whatsapp_db
-
- operation = args.get('operation', 'chat_history')
-
- # Map LLM args to node parameters
- parameters = {
- 'operation': operation,
- 'chatType': args.get('chat_type', 'individual'),
- 'phone': args.get('phone', ''),
- 'group_id': args.get('group_id', ''),
- 'limit': args.get('limit', 50),
- 'offset': args.get('offset', 0),
- 'messageFilter': args.get('message_filter', 'all'),
- 'query': args.get('query', ''),
- 'phones': args.get('phones', ''),
- 'groupIdForInfo': args.get('group_id', ''),
- 'contactPhone': args.get('phone', ''),
- }
-
- result = await handle_whatsapp_db(
- node_id="tool_whatsapp_db",
- node_type="whatsappDb",
- parameters=parameters,
- context={}
- )
-
- if result.get('success'):
- return {"success": True, "operation": operation, **result.get('result', {})}
- return {"error": result.get('error', 'Query failed')}
-```
-
-### Skill Documentation (SKILL.md)
-
-Update the skill documentation to reflect tool capabilities:
-
-```markdown
----
-name: whatsapp-skill
-description: Send WhatsApp messages, query contacts/groups, retrieve chat history.
-allowed-tools: whatsapp_send whatsapp_db
-metadata:
- author: machina
- version: "3.0"
- category: messaging
----
-
-# WhatsApp Messaging Skill
-
-## whatsapp_send
-
-Send messages to contacts or groups.
-
-### Parameters
-
-| Parameter | Type | Required | Description |
-|-----------|------|----------|-------------|
-| recipient_type | string | Yes | "phone" or "group" |
-| phone | string | If phone | Phone number without + prefix |
-| group_id | string | If group | Group JID |
-| message_type | string | Yes | "text", "image", "video", etc. |
-| message | string | If text | Text content |
-| media_url | string | If media | URL for media |
-
-## whatsapp_db
-
-Query WhatsApp database - contacts, groups, messages.
-
-### Operations
-
-| Operation | Description |
-|-----------|-------------|
-| chat_history | Retrieve message history |
-| search_groups | Search groups by name |
-| get_group_info | Get group details with participant names |
-| get_contact_info | Get contact info (name, phone, photo) |
-| list_contacts | List all contacts with saved names |
-| check_contacts | Check WhatsApp registration status |
-
-### Examples
-
-**Get chat history:**
-```json
-{
- "operation": "chat_history",
- "chat_type": "individual",
- "phone": "1234567890",
- "limit": 20
-}
-```
-
-**Find contact by name:**
-```json
-{
- "operation": "list_contacts",
- "query": "mom"
-}
-```
-
-**Get group participants:**
-```json
-{
- "operation": "get_group_info",
- "group_id": "[email protected]"
-}
-```
-```
-
----
-
-## Complete Example: Twitter/X Nodes
-
-The `twitterSend`, `twitterSearch`, and `twitterUser` nodes are examples of dual-purpose tools using OAuth 2.0 authentication and the XDK Python SDK.
-
-### Frontend Definition (twitterNodes.ts)
-
-```typescript
-twitterSend: {
- displayName: 'Twitter Send',
- name: 'twitterSend',
- icon: TWITTER_ICON,
- group: ['social', 'tool'], // Include 'tool' for dual-purpose
- version: 1,
- subtitle: 'Post to Twitter/X',
- description: 'Post tweets, reply, retweet, like/unlike, delete',
- defaults: { name: 'Twitter Send', color: '#000000' },
-
- // Main input for workflow
- inputs: [{
- name: 'main',
- displayName: 'Input',
- type: 'main' as NodeConnectionType,
- description: 'Trigger input'
- }],
-
- // Both outputs
- outputs: [
- {
- name: 'main',
- displayName: 'Output',
- type: 'main' as NodeConnectionType,
- description: 'Action result'
- },
- {
- name: 'tool',
- displayName: 'Tool',
- type: 'main' as NodeConnectionType,
- description: 'Connect to AI Agent tool handle'
- }
- ],
-
- properties: [
- {
- displayName: 'Action',
- name: 'action',
- type: 'options',
- default: 'tweet',
- options: [
- { name: 'Post Tweet', value: 'tweet' },
- { name: 'Reply', value: 'reply' },
- { name: 'Retweet', value: 'retweet' },
- { name: 'Like', value: 'like' },
- { name: 'Unlike', value: 'unlike' },
- { name: 'Delete', value: 'delete' }
- ]
- },
- {
- displayName: 'Text',
- name: 'text',
- type: 'string',
- typeOptions: { rows: 4 },
- default: '',
- description: 'Tweet text (max 280 characters)',
- displayOptions: { show: { action: ['tweet', 'reply'] } }
- },
- {
- displayName: 'Tweet ID',
- name: 'tweet_id',
- type: 'string',
- default: '',
- description: 'Target tweet ID',
- displayOptions: { show: { action: ['retweet', 'like', 'unlike', 'delete'] } }
- },
- {
- displayName: 'Reply To ID',
- name: 'reply_to_id',
- type: 'string',
- default: '',
- description: 'Tweet ID to reply to',
- displayOptions: { show: { action: ['reply'] } }
- }
- ]
-}
-```
-
-### Backend Schema (ai.py)
-
-```python
-if node_type == 'twitterSend':
- class TwitterSendSchema(BaseModel):
- """Post tweets, reply, retweet, like/unlike, and delete on Twitter/X."""
- action: str = Field(
- default="tweet",
- description="Action: 'tweet', 'reply', 'retweet', 'like', 'unlike', 'delete'"
- )
- text: Optional[str] = Field(
- default=None,
- description="Tweet text (max 280 chars). Required for 'tweet' and 'reply'"
- )
- tweet_id: Optional[str] = Field(
- default=None,
- description="Target tweet ID. Required for 'retweet', 'like', 'unlike', 'delete'"
- )
- reply_to_id: Optional[str] = Field(
- default=None,
- description="Tweet ID to reply to. Required for 'reply'"
- )
- return TwitterSendSchema
-
-if node_type == 'twitterSearch':
- class TwitterSearchSchema(BaseModel):
- """Search recent tweets on Twitter/X."""
- query: str = Field(
- description="Search query (supports operators: from:, to:, #, @, OR, -exclude, lang:, has:links, has:media)"
- )
- max_results: int = Field(
- default=10,
- description="Maximum results (10-100)"
- )
- return TwitterSearchSchema
-
-if node_type == 'twitterUser':
- class TwitterUserSchema(BaseModel):
- """Look up Twitter/X user profiles and social connections."""
- operation: str = Field(
- default="me",
- description="Operation: 'me', 'by_username', 'by_id', 'followers', 'following'"
- )
- username: Optional[str] = Field(
- default=None,
- description="Twitter username without @ (for 'by_username')"
- )
- user_id: Optional[str] = Field(
- default=None,
- description="Twitter user ID (for 'by_id', 'followers', 'following')"
- )
- max_results: int = Field(
- default=100,
- description="Max results for followers/following (1-1000)"
- )
- return TwitterUserSchema
-```
-
-### Backend Handler (tools.py)
-
-```python
-async def _execute_twitter_send(args: Dict[str, Any], node_params: Dict[str, Any]) -> Dict[str, Any]:
- """Execute Twitter send actions."""
- from services.handlers.twitter import handle_twitter_send
-
- parameters = {
- 'action': args.get('action', 'tweet'),
- 'text': args.get('text', ''),
- 'tweet_id': args.get('tweet_id', ''),
- 'reply_to_id': args.get('reply_to_id', ''),
- }
-
- action = parameters['action']
- if action in ('tweet', 'reply') and not parameters['text']:
- return {"error": "Text is required for tweet/reply actions"}
- if action in ('retweet', 'like', 'unlike', 'delete') and not parameters['tweet_id']:
- return {"error": "tweet_id is required for this action"}
- if action == 'reply' and not parameters['reply_to_id']:
- return {"error": "reply_to_id is required for reply action"}
-
- result = await handle_twitter_send(
- node_id="tool_twitter_send",
- node_type="twitterSend",
- parameters=parameters,
- context={}
- )
-
- if result.get('success'):
- return {"success": True, "action": action, "result": result.get('result', {})}
- return {"error": result.get('error', 'Twitter action failed')}
-
-
-async def _execute_twitter_search(args: Dict[str, Any], node_params: Dict[str, Any]) -> Dict[str, Any]:
- """Execute Twitter search."""
- from services.handlers.twitter import handle_twitter_search
-
- parameters = {
- 'query': args.get('query', ''),
- 'max_results': min(args.get('max_results', 10), 100),
- }
-
- if not parameters['query']:
- return {"error": "Search query is required"}
-
- result = await handle_twitter_search(
- node_id="tool_twitter_search",
- node_type="twitterSearch",
- parameters=parameters,
- context={}
- )
-
- if result.get('success'):
- return result.get('result', {})
- return {"error": result.get('error', 'Search failed')}
-
-
-async def _execute_twitter_user(args: Dict[str, Any], node_params: Dict[str, Any]) -> Dict[str, Any]:
- """Execute Twitter user lookup."""
- from services.handlers.twitter import handle_twitter_user
-
- parameters = {
- 'operation': args.get('operation', 'me'),
- 'username': args.get('username', ''),
- 'user_id': args.get('user_id', ''),
- 'max_results': min(args.get('max_results', 100), 1000),
- }
-
- operation = parameters['operation']
- if operation == 'by_username' and not parameters['username']:
- return {"error": "Username is required for by_username operation"}
- if operation == 'by_id' and not parameters['user_id']:
- return {"error": "user_id is required for by_id operation"}
-
- result = await handle_twitter_user(
- node_id="tool_twitter_user",
- node_type="twitterUser",
- parameters=parameters,
- context={}
- )
-
- if result.get('success'):
- return result.get('result', {})
- return {"error": result.get('error', 'User lookup failed')}
-```
-
-### XDK SDK Authentication Pattern
-
-Twitter nodes use OAuth 2.0 PKCE authentication stored via `auth_service`:
-
-```python
-# In server/services/handlers/twitter.py
-async def _get_twitter_client() -> Client:
- """Get authenticated Twitter client from stored OAuth 2.0 credentials."""
- from core.container import container
- auth_service = container.auth_service()
- access_token = await auth_service.get_api_key("twitter_access_token")
- if not access_token:
- raise ValueError("Twitter not connected. Please authenticate via Credentials.")
- # OAuth 2.0 user token (not bearer_token which is app-only)
- return Client(access_token=access_token)
-```
-
-### Skill Documentation (SKILL.md)
-
-```markdown
----
-name: twitter-send-skill
-description: Post tweets, reply, retweet, like/unlike, delete on Twitter/X.
-allowed-tools: twitter_send
-metadata:
- author: machina
- version: "1.0"
- category: social
----
-
-# Twitter Send Tool
-
-## twitter_send
-
-Post and interact with tweets on Twitter/X.
-
-### Parameters
-
-| Parameter | Type | Required | Description |
-|-----------|------|----------|-------------|
-| action | string | Yes | 'tweet', 'reply', 'retweet', 'like', 'unlike', 'delete' |
-| text | string | If tweet/reply | Tweet text (max 280 chars) |
-| tweet_id | string | If retweet/like/unlike/delete | Target tweet ID |
-| reply_to_id | string | If reply | Tweet ID to reply to |
-
-### Examples
-
-**Post a tweet:**
-```json
-{"action": "tweet", "text": "Hello from AI!"}
-```
-
-**Reply to a tweet:**
-```json
-{"action": "reply", "text": "Great point!", "reply_to_id": "1234567890"}
-```
-
-**Like a tweet:**
-```json
-{"action": "like", "tweet_id": "1234567890"}
-```
-```
-
----
-
-## Checklist
-
-### Frontend
-
-- [ ] Add node definition with both `main` input AND outputs (`main` + `tool`)
-- [ ] Include `'tool'` in the `group` array
-- [ ] Define comprehensive `properties` (LLM will fill these)
-- [ ] Ensure node renders correctly (SquareNode handles multiple outputs)
-- [ ] **Add to `executionService.ts` `isNodeTypeSupported()`** (CRITICAL - enables Run button)
-
-### Backend Schema (ai.py)
-
-- [ ] Create Pydantic schema matching node properties
-- [ ] Use snake_case for field names
-- [ ] Add clear descriptions with examples
-- [ ] Use `Optional` for non-required fields
-- [ ] Add schema to `_get_tool_schema()` function
-
-### Backend Handler (tools.py)
-
-- [ ] Create `_execute_*` handler function
-- [ ] Map LLM args (snake_case) to node params (camelCase)
-- [ ] Add validation for required fields based on options
-- [ ] Call existing node handler (reuse workflow logic)
-- [ ] Return structured result or error
-- [ ] Add dispatcher case in `execute_tool()`
-
-### DO NOT Do
-
-- [ ] Do NOT add to `AI_TOOL_TYPES` in constants.py
-- [ ] Do NOT add to `CONFIG_NODE_TYPES`
-
-### Documentation
-
-- [ ] Update skill SKILL.md with tool parameters and examples
-- [ ] Update CLAUDE.md with new tool capabilities
-
-### Testing
-
-- [ ] Verify node works in normal workflow
-- [ ] Connect node to AI Agent's `input-tools` handle
-- [ ] Verify LLM can call the tool with correct parameters
-- [ ] Verify node is excluded from parallel execution when used as tool
-- [ ] Test all parameter combinations
-
----
-
-## Best Practices
-
-1. **Reuse Existing Handlers**: The tool handler should call the existing node handler, not duplicate logic
-
-2. **Parameter Mapping**: Always map LLM snake_case to node camelCase consistently
-
-3. **Validation**: Validate required parameters based on conditional logic (e.g., phone required if recipient_type='phone')
-
-4. **Error Messages**: Return clear error messages the LLM can understand and act on
-
-5. **Schema Descriptions**: Write detailed Field descriptions with examples for the LLM
-
-6. **Testing Both Modes**: Always test the node in both workflow mode and tool mode
diff --git a/docs-internal/email_service.md b/docs-internal/email_service.md
index 43df9ad4..94bb3f02 100644
--- a/docs-internal/email_service.md
+++ b/docs-internal/email_service.md
@@ -391,8 +391,7 @@ cargo install himalaya
## Related Docs
-- [Node Creation Guide](./node_creation.md) — general pattern for adding workflow nodes
-- [Dual-Purpose Tool Guide](./dual_purpose_tool_node_creation.md) — how `emailSend`/`emailRead` work as both workflow nodes and AI tools
+- [Node Creation Guide](./node_creation.md) — canonical plugin recipe (covers dual-purpose nodes; `emailSend`/`emailRead` are live examples)
- [Event Waiter System](./event_waiter_system.md) — trigger registration for `emailReceive`
- [New Service Integration](./new_service_integration.md) — end-to-end integration pattern (use Google Workspace as a richer OAuth example)
- [Credentials Encryption](./credentials_encryption.md) — how `email_*` keys are encrypted on disk
diff --git a/docs-internal/memory_compaction.md b/docs-internal/memory_compaction.md
index 3a01b391..72fcab6b 100644
--- a/docs-internal/memory_compaction.md
+++ b/docs-internal/memory_compaction.md
@@ -1,5 +1,7 @@
# Memory Compaction, Token Tracking, and Cost Calculation Service
+> **Related docs:** [memory_lifecycle.md](./memory_lifecycle.md) for the markdown / vector-store / state-clear surface. This doc is the SSOT for the **service** (CompactionService API, thresholds, native-API integration, pricing). memory_lifecycle.md is the SSOT for the **flow** (how the markdown moves through an agent turn).
+
## Overview
The compaction service enables automatic memory compaction, token tracking, and **cost calculation** for MachinaOs specialized agents. It uses a hybrid approach leveraging native provider APIs (Anthropic, OpenAI) when available, with comprehensive token and cost tracking for all providers.
diff --git a/docs-internal/memory_lifecycle.md b/docs-internal/memory_lifecycle.md
new file mode 100644
index 00000000..b3640301
--- /dev/null
+++ b/docs-internal/memory_lifecycle.md
@@ -0,0 +1,185 @@
+# Memory Lifecycle
+
+Canonical home for how conversation memory is loaded, appended, trimmed, archived, cleared, and resumed across every MachinaOs agent. Replaces the partial explanations previously scattered across `agent_architecture.md`, `deep_agent.md`, `cli_agent_framework.md`, `rlm_service.md`, and `memory_compaction.md`.
+
+> **Related docs:**
+> - [memory_compaction.md](./memory_compaction.md) — `CompactionService`, token thresholds, pricing
+> - [agent_architecture.md](./agent_architecture.md) — LangGraph agent loop that calls these helpers
+> - [cli_agent_framework.md](./cli_agent_framework.md) — `claude_code_agent` native session bridge
+> - [deep_agent.md](./deep_agent.md) / [rlm_service.md](./rlm_service.md) — engine-specific adapters
+
+## 1. Two storage formats
+
+| Format | File | Used by | Wire shape |
+|---|---|---|---|
+| **Markdown transcript** | [`services/memory/markdown.py`](../server/services/memory/markdown.py) | aiAgent, chatAgent, deep_agent, rlm_agent, claude_code_agent (mirror) | `### **Human/Assistant** (timestamp)` blocks under a top-level `# Conversation History` heading |
+| **Anthropic-Messages JSONL** | [`services/memory/jsonl.py`](../server/services/memory/jsonl.py) | Standalone primitive — not used by any agent today | One JSON object per line: `{"role": "user"|"assistant", "content": str \| [ContentBlock], ...metadata}` |
+
+The markdown format is the visible UI surface — `simpleMemory.memory_content` is rendered as a markdown editor in the parameter panel. The JSONL helpers were prepared for a future SDK migration; the live `claude_code_agent` bridge uses claude's own native session JSONL on disk (see §6) and mirrors the transcript into `memory_content` via the **markdown** helpers for user visibility.
+
+## 2. Markdown helper API
+
+Three pure functions, no I/O, locked by `tests/services/memory/`:
+
+```python
+from services.memory import (
+ parse_memory_markdown, # str -> List[BaseMessage]
+ append_to_memory_markdown, # (content, role: "human"|"ai", message) -> str
+ trim_markdown_window, # (content, window_size_pairs) -> (trimmed, removed_texts)
+)
+```
+
+- **`parse_memory_markdown`** — regex-extracts `### **(Human|Assistant)**[^\n]*\n(body)` blocks; returns LangChain `HumanMessage` / `AIMessage` instances ready to feed an agent loop.
+- **`append_to_memory_markdown`** — drops the empty-state placeholder (`*No messages yet.*`), appends a `### **{label}** (YYYY-MM-DD HH:MM:SS)\n{message}\n` entry. Timestamp comes from `datetime.now()`.
+- **`trim_markdown_window`** — keeps the last `window_size * 2` blocks (N user/assistant pairs); returns `(trimmed_content, removed_texts)`. Removed bodies are returned so the caller can hand them to the long-term vector store (§4).
+
+### Empty-state placeholder
+
+```
+# Conversation History
+
+*No messages yet.*
+```
+
+This is also the value `clear_agent_session_state` resets `memory_content` to (see §5). Defined as `DEFAULT_MEMORY_CONTENT` in [`services/memory/state.py`](../server/services/memory/state.py).
+
+## 3. Known duplication: ai.py inlines its own copies
+
+[`services/ai.py:158-234`](../server/services/ai.py) carries `_parse_memory_markdown`, `_append_to_memory_markdown`, `_trim_markdown_window`, and `_get_memory_vector_store` as private helpers — byte-equivalent reimplementations of the public ones in `services/memory/`. The `services.memory` package was carved out later; existing call sites inside `ai.py` were never switched to import from it. Future cleanup will consolidate; for now both paths exist and produce identical output. Pytest doesn't lock cross-equivalence — treat the `services.memory` package as the canonical surface for **new** code.
+
+Newer call sites (already on the public helpers):
+
+| File | Imports |
+|---|---|
+| `services/temporal/agent_activities.py:251` — `agent.persist_turn.v1` activity (F4.B) | `append_to_memory_markdown`, `trim_markdown_window` |
+| `services/cli_agent/service.py:490` — `_persist_memory` for claude_code_agent | `append_to_memory_markdown`, `trim_markdown_window` |
+| `routers/websocket.py:2167` — `clear_memory` handler | `clear_agent_session_state` |
+
+Older call sites (still on the underscore-prefixed copies inside ai.py):
+
+| File | Symbols |
+|---|---|
+| `services/ai.py:execute_agent` / `execute_chat_agent` | `_parse_memory_markdown`, `_append_to_memory_markdown`, `_trim_markdown_window`, `_memory_vector_stores` |
+
+## 4. Long-term vector store
+
+[`services/memory/vector_store.py`](../server/services/memory/vector_store.py) caches one `InMemoryVectorStore` per `session_id`. Embeddings come from `langchain_huggingface.HuggingFaceEmbeddings(model_name="BAAI/bge-small-en-v1.5")` — lazy-imported; missing dep returns `None` with a warning (long-term archival is best-effort).
+
+```python
+from services.memory import get_memory_vector_store
+store = get_memory_vector_store("user-123")
+if store:
+ store.add_texts(removed_texts) # archive trimmed messages
+ results = store.similarity_search(q) # retrieve for the next turn
+```
+
+**Two caches exist.** The live one used by `services/ai.py:execute_agent` is `services.ai._memory_vector_stores`. The one in `services.memory.vector_store` is a package-private second copy referenced by `clear_agent_session_state` for forward-cleanup. Same caveat as §3: consolidation is future work. The state-clear orchestration deletes from the live `services.ai` cache.
+
+## 5. State clear orchestration
+
+[`services/memory/state.py`](../server/services/memory/state.py) exposes one function:
+
+```python
+await clear_agent_session_state(
+ session_id: str,
+ workflow_id: str = None,
+ clear_long_term: bool = False, # True → drop vector store
+ memory_node_id: str | None = None, # When set → reset memory_content + wipe last_session_id
+) -> {cleared_vector_store, cleared_todo_keys, cleared_memory_node}
+```
+
+Three stores are cleared in one call:
+
+1. **Vector store** (when `clear_long_term=True`) — `del services.ai._memory_vector_stores[session_id]`.
+2. **TodoService** — every candidate key (`workflow_id`, `session_id`, `"default"`) is cleared because [`server/nodes/tool/write_todos.py`](../server/nodes/tool/write_todos.py) uses `ctx.workflow_id or ctx.node_id or "default"` as the storage key and we want to clear whichever fallback the write path actually used.
+3. **simpleMemory node fields** (when `memory_node_id` provided) — `memory_content` → `DEFAULT_MEMORY_CONTENT`; `last_session_id` → `None` (so claude_code_agent starts fresh next run instead of `--resume`-ing into a wiped transcript); orphan `memory_jsonl` field popped if present.
+
+Frontend `clear_memory` WS handler ([`routers/websocket.py:2167`](../server/routers/websocket.py)) calls this; UI presents a Reset Memory button on the simpleMemory parameter panel.
+
+## 6. claude_code_agent native session resume bridge
+
+`claude_code_agent` does **not** inject `memory_content` as a system prompt. It calls claude's CLI with `--resume <UUID>` so claude reads its own native JSONL transcript on disk (`<CLAUDE_CONFIG_DIR>/projects/<project_key>/<session_id>.jsonl`). The bridge has three coupled mechanisms; full plumbing in [cli_agent_framework.md → Memory bridge](./cli_agent_framework.md#memory-bridge--simplememory--claude_code_agent).
+
+| Mechanism | Where | Why |
+|---|---|---|
+| **Stable `cwd=repo_root`** | `AICliSession.cwd()` when `memory_bound=True` | Keeps claude's `project_key = re.sub(r"[^a-zA-Z0-9.-]", "-", str(cwd))` constant so `--resume <UUID>` finds the prior JSONL |
+| **UUID5 first-run / `--resume` thereafter** | `claude_code_agent.execute()` | First run: `uuid5(NAMESPACE_OID, f"{memory_node_id}:{session_id}")` → `--session-id <UUID5>`. Subsequent runs: `simpleMemory.last_session_id` → `--resume <UUID>` |
+| **Auto-clear stale `last_session_id`** | `_persist_memory` in `services/cli_agent/service.py` | When claude returns `No conversation found with session ID: <UUID>`, wipe `last_session_id` (preserve `memory_content`); next run self-heals |
+
+`memory_content` is the UI mirror, not the resume channel. `_persist_memory` ([`services/cli_agent/service.py:446-513`](../server/services/cli_agent/service.py)) appends every successful run's user prompt + assistant response to it via the **same markdown helpers** aiAgent uses, and saves the most recent run's `r.session_id` to `simpleMemory.last_session_id` in one DB write. Always broadcasts `node_parameters_updated` (CloudEvents v1.0 envelope, `source_hint="cli"`) so the simpleMemory parameter panel auto-refetches mid-run.
+
+**Parallel-batch guard.** When memory is wired AND `len(tasks) > 1`, `claude_code_agent` raises `NodeUserError` — concurrent `--resume <UUID>` spawns against one JSONL would race.
+
+## 7. The lifecycle in motion (aiAgent example)
+
+```
+Turn N starts
+ │
+ ▼
+1. handle_ai_agent / handle_chat_agent reads simpleMemory.memory_content from DB
+ │
+ ▼
+2. _parse_memory_markdown(content) → List[BaseMessage]
+ │
+ ▼
+3. (Optional) get_memory_vector_store(session_id).similarity_search(prompt)
+ → prepend retrieved long-term context as a system message
+ │
+ ▼
+4. LangGraph agent loop runs (ainvoke + tool calls)
+ │
+ ▼
+5. _track_token_usage(...) — see memory_compaction.md
+ → if threshold tripped: CompactionService.compact_context(...) → reset messages
+ │
+ ▼
+6. _append_to_memory_markdown(content, "human", prompt)
+ _append_to_memory_markdown(content, "ai", response)
+ │
+ ▼
+7. trimmed_content, removed_texts = _trim_markdown_window(content, window_size)
+ │
+ ▼
+8. (Optional) store.add_texts(removed_texts) — long-term archival
+ │
+ ▼
+9. save_node_parameters(memory_node_id, {"memory_content": trimmed_content, ...})
+ broadcast_node_parameters_updated(...) # CloudEvents source_hint="agent"
+```
+
+F4.B `AgentWorkflow` runs steps 4-9 as separate Temporal activities (`execute_llm_step.v1` / `persist_turn.v1` / `compact_memory.v1`); per-turn persistence means a mid-loop failure doesn't lose progress. F4.A and legacy paths run steps 4-9 inline inside one activity.
+
+## 8. Engine-specific adapters
+
+| Engine | Memory shape on input | Memory shape on output | Notes |
+|---|---|---|---|
+| `aiAgent` / `chatAgent` | LangChain `BaseMessage` list parsed from markdown | Appended pair + trim | Standard path; see §7 |
+| `deep_agent` | Same as aiAgent — `DeepAgentService` accepts `BaseMessage` list | Same | `FilesystemBackend(virtual_mode=True, root_dir=workspace_dir)` is independent of memory; see [deep_agent.md](./deep_agent.md) |
+| `rlm_agent` | Markdown injected as REPL pre-context | Last `FINAL(...)` call's payload | RLM internal recursion uses its own state machine; only entry/exit cross the memory boundary |
+| `claude_code_agent` | `--resume <UUID>` reads native JSONL; `memory_content` ignored on input | Bridge writes markdown mirror + saves `last_session_id` | See §6 |
+
+## 9. Compaction trigger
+
+Compaction is a separate concern documented in [memory_compaction.md](./memory_compaction.md). The trigger point is step 5 in §7. Threshold = `model_context_length * agent.compaction.ratio` (default 0.5; configured in [`server/config/llm_defaults.json`](../server/config/llm_defaults.json)).
+
+The compaction service is the SSOT for thresholds, native-API integration (Anthropic `compact-2026-01-12` beta, OpenAI `context_management.compact_threshold`), and client-side summarization fallback. Memory lifecycle (this doc) is the SSOT for storage shape and helper signatures.
+
+## 10. Pytest invariants
+
+```
+server/tests/services/memory/
+├── test_markdown.py # parse → append → trim round-trips
+├── test_jsonl.py # parse_jsonl + append_message + trim_window
+└── (state.py / vector_store.py have no dedicated test files;
+ coverage rides on test_ai_agents.py + test_status_broadcasts.py)
+```
+
+The CloudEvents `node_parameters_updated` envelope emitted on every memory write is locked by `tests/test_status_broadcasts.py:test_node_parameters_updated_envelope_shape` — see [status_broadcaster.md](./status_broadcaster.md) for the contract.
+
+## 11. What NOT to do
+
+- Don't write to `simpleMemory.memory_content` without broadcasting `node_parameters_updated` — the parameter panel won't refetch and users will see stale content.
+- Don't add new local copies of the markdown helpers. Import from `services.memory` (or from `services.memory.markdown` / `.jsonl` directly).
+- Don't bypass `clear_agent_session_state` to "just delete the markdown" — TodoService and the vector store will leak across sessions.
+- Don't inject `memory_content` as a system prompt for `claude_code_agent` — `--resume <UUID>` is the resume channel; `memory_content` is for the human reader.
+- Don't run claude_code_agent with `memory_bound=True` in parallel batches — the `--resume` guard raises `NodeUserError` and you'll burn a credit.
diff --git a/docs-internal/new_service_integration.md b/docs-internal/new_service_integration.md
index c0055dcb..224200ed 100644
--- a/docs-internal/new_service_integration.md
+++ b/docs-internal/new_service_integration.md
@@ -520,119 +520,11 @@ from services.handlers.{service} import (
## Step 6: Frontend Node Definitions
-Create `client/src/nodeDefinitions/{service}Nodes.ts`:
-
-```typescript
-import { NodeDefinition, INodeProperties, NodeConnectionType } from '../types/INodeProperties';
-
-// Service icon (SVG or emoji)
-const SERVICE_ICON = `<svg>...</svg>`;
-
-// Service color
-const SERVICE_COLOR = '#4285F4';
-
-// Common service properties
-const SERVICE_COMMON_PROPS: INodeProperties[] = [
- {
- displayName: 'Account Mode',
- name: 'account_mode',
- type: 'options',
- options: [
- { name: 'Owner (My Account)', value: 'owner' },
- { name: 'Customer', value: 'customer' },
- ],
- default: 'owner',
- description: 'Whose account to use',
- },
- {
- displayName: 'Customer ID',
- name: 'customer_id',
- type: 'string',
- default: '',
- displayOptions: { show: { account_mode: ['customer'] } },
- description: 'Customer identifier for multi-tenant mode',
- },
-];
-
-export const {service}Nodes: Record<string, NodeDefinition> = {
- {operation1}Node: {
- displayName: '{Operation 1}',
- name: '{operation1}Node',
- icon: SERVICE_ICON,
- group: ['{service}', 'tool'],
- description: 'Description of operation 1',
- defaults: {
- name: '{Operation 1}',
- color: SERVICE_COLOR,
- },
- inputs: [{ name: 'main', displayName: 'Input', type: 'main' as NodeConnectionType }],
- outputs: [{ name: 'main', displayName: 'Output', type: 'main' as NodeConnectionType }],
- properties: [
- ...SERVICE_COMMON_PROPS,
- // Operation-specific properties
- {
- displayName: 'Parameter 1',
- name: 'param1',
- type: 'string',
- default: '',
- required: true,
- description: 'Description of parameter 1',
- },
- ],
- },
-
- // Add more operations...
-};
-
-// Export node type array for constants
-export const {SERVICE}_NODE_TYPES = Object.keys({service}Nodes);
-```
-
-### Register in nodeDefinitions.ts
-
-```typescript
-// client/src/nodeDefinitions.ts
-
-import { {service}Nodes, {SERVICE}_NODE_TYPES } from './nodeDefinitions/{service}Nodes';
-
-export const nodeDefinitions: NodeDefinitionRegistry = {
- // ... existing nodes
- ...{service}Nodes,
-};
-```
-
-### Add to Dashboard.tsx
-
-```typescript
-// In getNodeTypes()
-} else if (type.startsWith('{service}') || {SERVICE}_NODE_TYPES.includes(type)) {
- types[type] = SquareNode;
-}
-```
-
-### Add to executionService.ts (CRITICAL - Enables Run Button)
-
-```typescript
-// client/src/services/executionService.ts
-
-// Import node types
-import { {SERVICE}_NODE_TYPES } from '../nodeDefinitions/{service}Nodes';
-
-// Add to isNodeTypeSupported() supportedTypes array
-static isNodeTypeSupported(nodeType: string): boolean {
- const supportedTypes = [
- // ... existing types
- // {Service} Nodes
- ...{SERVICE}_NODE_TYPES,
- ];
- return supportedTypes.includes(nodeType);
-}
-```
-
-**CRITICAL:** Without this step, the Run button will NOT appear in the parameter panel for your new nodes. This is the execution whitelist - only nodes in this list can be executed via the Run button.
+**No frontend changes required.** Post-Wave-11 nodes are declared as Python plugins (Step 5); the frontend fetches NodeSpec via GET /api/schemas/nodes/{type}/spec.json and renders without per-service TypeScript. The Pydantic Params class doubles as the LLM-visible tool schema; icon goes in <plugin>/icon.svg; color in <plugin>/meta.json. See [node_creation.md](./node_creation.md) and [server/nodes/README.md](../server/nodes/README.md) for the canonical recipe.
---
+
## Step 7: AI Tool Schemas
Add Pydantic schemas in `server/services/ai.py`:
@@ -701,70 +593,13 @@ InputSection consumes these automatically via `GET /api/schemas/nodes/{node_type
## Step 9: Credentials Modal
-Update `client/src/components/CredentialsModal.tsx`:
-
-### Add to CATEGORIES
-
-```typescript
-const CATEGORIES = [
- // ... existing categories
- {
- id: '{service}',
- name: '{Service Name}',
- placeholder: '',
- color: '#4285F4',
- desc: 'Service description',
- CustomIcon: ServiceIcon,
- isSpecial: true,
- panelType: '{service}',
- },
-];
-```
+**No React changes required.** Post-Wave-7 the Credentials Modal renders entirely from `server/config/credential_providers.json` via the catalogue → `useCatalogueQuery` → `ApiKeyPanel` / `OAuthConnect` chain. To add a new provider:
-### Add Icon Component
+1. Add an entry to `server/config/credential_providers.json` with `id`, `name`, `category`, `fields[]` (validation/connect targets + optional secondary fields like Telegram's owner-chat-id), `icon_ref` (URL form `/api/schemas/credentials/<id>/icon`), and `panel_type` (`api_key` / `oauth` / `qr_pairing` / `email_smtp`).
+2. Drop the brand SVG at `server/credentials/icons/<id>.svg` (served by `GET /api/schemas/credentials/<id>/icon`).
+3. Implement the `Credential` subclass in your plugin folder's `_credentials.py` (validation, `_probe(api_key)` for API keys, or OAuth callback router for OAuth flows).
-```typescript
-const ServiceIcon = () => (
- <svg viewBox="0 0 24 24" style={{ width: 20, height: 20 }}>
- {/* SVG path */}
- </svg>
-);
-```
-
-### Add OAuth Panel
-
-```typescript
-const render{Service}Panel = () => (
- <div style={panelStyle}>
- <div style={headerStyle}>
- <ServiceIcon />
- <span>{Service Name}</span>
- {isConnected && <Tag color="green">Connected as {email}</Tag>}
- </div>
-
- {!isConnected ? (
- <>
- <Input
- placeholder="Client ID"
- value={clientId}
- onChange={(e) => setClientId(e.target.value)}
- />
- <Input.Password
- placeholder="Client Secret"
- value={clientSecret}
- onChange={(e) => setClientSecret(e.target.value)}
- />
- <Button onClick={handleSaveCredentials}>Save</Button>
- <Button onClick={handleLogin} disabled={!clientId || !clientSecret}>
- Login with {Service}
- </Button>
- </>
- ) : (
- <Button onClick={handleLogout}>Disconnect</Button>
- )}
- </div>
-);
-```
+See [credentials_encryption.md](./credentials_encryption.md) for the catalogue contract and `Credential` base class details.
---
diff --git a/docs-internal/node-logic-flows/ai_tools/calculatorTool.md b/docs-internal/node-logic-flows/ai_tools/calculatorTool.md
index 0abc899a..e53ccdb1 100644
--- a/docs-internal/node-logic-flows/ai_tools/calculatorTool.md
+++ b/docs-internal/node-logic-flows/ai_tools/calculatorTool.md
@@ -131,4 +131,4 @@ flowchart TD
## Related
- **Sibling tools**: [`currentTimeTool`](./currentTimeTool.md), [`duckduckgoSearch`](./duckduckgoSearch.md), [`taskManager`](./taskManager.md), [`writeTodos`](./writeTodos.md)
-- **Architecture docs**: [Agent Architecture](../../agent_architecture.md), [Dual-Purpose Tool Node Guide](../../dual_purpose_tool_node_creation.md)
+- **Architecture docs**: [Agent Architecture](../../agent_architecture.md), [Tool Building Pipeline](../../tool_building_pipeline.md), [Node Creation Guide](../../node_creation.md)
diff --git a/docs-internal/node_creation.md b/docs-internal/node_creation.md
index ce5b6b1e..3ff26134 100644
--- a/docs-internal/node_creation.md
+++ b/docs-internal/node_creation.md
@@ -10,10 +10,10 @@ this file picks the right entry point based on what you're adding.
| You're adding… | Read this | Boilerplate |
|---|---|---|
-| A simple action node (one HTTP call, no state) | [Quick start](./plugin_system.md#quick-start--adding-a-new-node) | one `<name>.py` file under `server/nodes/<group>/` |
-| A dual-purpose node (workflow node + AI tool) | [Dual-Purpose Tool Guide](./dual_purpose_tool_node_creation.md) | one `<name>.py` with `usable_as_tool = True` |
-| A specialized AI agent | [Specialized Agent Guide](./specialized_agent_node_creation.md) | one `<name>.py` under `server/nodes/agent/` |
-| A standalone AI-tool node (no workflow surface) | [AI Tool Node Guide](./ai_tool_node_creation.md) | one `<name>.py` under `server/nodes/tool/` |
+| A simple action node (one HTTP call, no state) | [Quick start](./plugin_system.md#quick-start--adding-a-new-node) | folder under `server/nodes/<group>/<name>/` with `__init__.py` |
+| A dual-purpose node (workflow node + AI tool) | [plugin_system.md](./plugin_system.md) + whatsapp / twitter / email plugin folders | folder under `server/nodes/<group>/<name>/` with `group: ['category', 'tool']` and `usable_as_tool = True` |
+| A specialized AI agent | [plugin_system.md](./plugin_system.md) + the existing `server/nodes/agent/<name>/` folders | folder under `server/nodes/agent/<name>/` extending `SpecializedAgentBase` |
+| A standalone AI-tool node (no workflow surface) | [Tool Building Pipeline](./tool_building_pipeline.md) | folder under `server/nodes/tool/<name>/` extending `ToolNode` |
| A node that wraps a CLI tool, supervises a daemon, or receives signed webhooks | [Wave 12 event framework](./plugin_system.md#wave-12--generalized-event-framework-servicesevents) (this section is the most important one) | self-contained folder under `server/nodes/<group>/` using `services.events` base classes |
| A polling-based trigger node | [Wave 12 event framework](./plugin_system.md#wave-12--generalized-event-framework-servicesevents) — subclass `PollingEventSource` | new file or folder; framework owns the loop |
| A long-lived service plugin (bot connection, WebSocket bridge, SDK session) | [Self-contained plugin folders (Wave 11.H)](./plugin_system.md#self-contained-plugin-folders) — telegram is the reference | folder with `_credentials.py` / `_service.py` / `_handlers.py` / `_filters.py` / `_refresh.py` |
@@ -217,16 +217,14 @@ walker does on startup), these registrations happen automatically:
| Credentials | `CREDENTIAL_REGISTRY` | `Credential.__init_subclass__` when `_credentials.py` is imported |
| Trigger registry + filter builders | `event_waiter.TRIGGER_REGISTRY`, `FILTER_BUILDERS` | back-fill from `TriggerNode` subclasses on first lookup |
| Temporal activity wrapper | `cls.as_activity()` | first call; pooled into the worker queue declared by `task_queue` |
-| Palette icon + color | `nodes/visuals.json` | central source of truth (frontend resolver reads it) |
+| Palette icon | `<plugin_folder>/icon.svg` (or `icon_<nodeType>.svg` for multi-node folders); served via `GET /api/schemas/nodes/<type>/icon`. `visuals.json` is the fallback for emoji or `lobehub:<brand>` icons. |
+| Palette color | `<plugin_folder>/meta.json` (`{"color": "#xxx"}`); `visuals.json` is the fallback for legacy entries (post-F2 it has zero color fields). |
What you **do** still write:
-- An entry in `server/nodes/visuals.json` for the icon + color
- (unless the node sets them as class attributes, which override).
-- An entry in `server/nodes/groups.py` if you introduce a new
- palette group.
-- An asset in `client/src/assets/icons/<name>.svg` for `asset:<name>`
- icons.
+- Drop `icon.svg` (or `icon_<nodeType>.svg` for multi-node folders) and `meta.json` (`{"color": "#xxx"}`) inside the plugin folder. The class-attribute icon/color override was removed in F1 — declaring `icon` or `color` as class attrs has no effect.
+- An entry in `server/nodes/visuals.json` ONLY if you want an emoji or `lobehub:<brand>` icon (no folder SVG). Post-F1/F7 visuals.json carries zero `asset:<key>` values.
+- An entry in `server/nodes/groups.py` if you introduce a new palette group.
## Where to look next
@@ -239,9 +237,9 @@ What you **do** still write:
| Stripe as the Wave 12 reference plugin (also the canonical CLI-managed-auth + auto-installer reference) | [stripe_service.md](./stripe_service.md) |
| Backend-as-SSOT design (NodeSpec, icons, output schemas) | [schema_source_of_truth_rfc.md](./schema_source_of_truth_rfc.md) |
| JSON workflow format, edge handle conventions | [workflow-schema.md](./workflow-schema.md) |
-| Dual-purpose nodes (workflow node + AI tool) | [dual_purpose_tool_node_creation.md](./dual_purpose_tool_node_creation.md) |
-| Specialized AI agents | [specialized_agent_node_creation.md](./specialized_agent_node_creation.md) |
| Polling triggers + event_waiter mechanics | [event_waiter_system.md](./event_waiter_system.md) |
+| Memory lifecycle (markdown parse/append/trim, vector store, session resume) | [memory_lifecycle.md](./memory_lifecycle.md) |
+| Tool building pipeline (`_build_tool_from_node`, schema, per-type Temporal dispatch) | [tool_building_pipeline.md](./tool_building_pipeline.md) |
| Process supervision (used by `DaemonEventSource`) | [server/services/process_service.py](../server/services/process_service.py) — singleton API |
## Wave summary (current state)
diff --git a/docs-internal/plugin_system.md b/docs-internal/plugin_system.md
index 0b2195f4..4cf1fec0 100644
--- a/docs-internal/plugin_system.md
+++ b/docs-internal/plugin_system.md
@@ -3,8 +3,9 @@
The MachinaOs plugin system is a class-based, declarative node
authoring model inspired by n8n's `INodeType`, Nango's
`providers.yaml`, Pipedream's app/component split, and Temporal's
-activity pattern. One Python file under `server/nodes/<group>/<name>.py`
-= one node. No cross-cutting edits.
+activity pattern. One folder under `server/nodes/<group>/<plugin>/`
+rooted at `__init__.py` = one plugin (one or more node classes).
+No cross-cutting edits.
**Status: shipped.** Plugin classes cover every node type in the
product — live count via `glob server/nodes/**/__init__.py`. Pytest
diff --git a/docs-internal/rlm_service.md b/docs-internal/rlm_service.md
index 60427648..4f0e1512 100644
--- a/docs-internal/rlm_service.md
+++ b/docs-internal/rlm_service.md
@@ -1,5 +1,7 @@
# RLM Service -- Recursive Language Model Agent Integration
+> **Related docs:** [memory_lifecycle.md](./memory_lifecycle.md) for the shared markdown memory format (RLM uses the same simpleMemory surface as aiAgent); [tool_building_pipeline.md](./tool_building_pipeline.md) for how connected tool nodes are bound to the REPL via `ToolBridgeAdapter`.
+
## Overview
The RLM (Recursive Language Models) service integrates the `rlms` library into MachinaOS as a specialized agent node (`rlm_agent`). Unlike other specialized agents that route to `handle_chat_agent` and use LangGraph, the RLM agent uses its own REPL-based code execution loop where the LM writes Python code blocks that are `exec()`-ed in a sandboxed environment.
diff --git a/docs-internal/schema_source_of_truth_rfc.md b/docs-internal/schema_source_of_truth_rfc.md
index 7499f5e8..26a4b208 100644
--- a/docs-internal/schema_source_of_truth_rfc.md
+++ b/docs-internal/schema_source_of_truth_rfc.md
@@ -189,89 +189,35 @@ to this path (the remaining 5 are output-only legacy aliases).
**New node checklist (post-Wave-10):**
```python
-# server/nodes/my_node.py
+# server/nodes/<group>/<plugin>/__init__.py
from typing import Literal
from pydantic import Field
-from models.nodes import BaseNodeParams
-from services.node_registry import register_node
+from services.plugin import ActionNode, NodeContext, Operation
-class MyParams(BaseNodeParams):
- type: Literal["myNode"]
+class MyNodeParams(ActionNode.Params):
query: str = Field(default="", json_schema_extra={"placeholder": "Search..."})
-async def handle_my_node(node_id, node_type, params, context):
- return {"success": True, "result": {...}}
-
-register_node(
- type="myNode",
- metadata={
- "displayName": "My Node",
- # icon + color resolved via server/nodes/visuals.json — add an
- # entry: {"myNode": {"icon": "asset:my_icon", "color": "#8be9fd"}}
- "group": ["tool"],
- "componentKind": "square",
- "handles": [...], # full topology
- "description": "...",
- "version": 1,
- },
- input_model=MyParams,
- handler=handle_my_node,
-)
+class MyNodeOutput(ActionNode.Output):
+ result: dict = {}
+
+class MyNode(ActionNode):
+ type = "myNode"
+ display_name = "My Node"
+ group = ("tool",)
+ component_kind = "square"
+ Params = MyNodeParams
+ Output = MyNodeOutput
+
+ @Operation("run")
+ async def run(self, ctx: NodeContext, params: MyNodeParams) -> MyNodeOutput:
+ return MyNodeOutput(success=True, result={...})
```
-Zero edits elsewhere.
-
-### 10.B — Icon + color: central registry + handler
-
-Every node's icon and color live in **one** file:
-[server/nodes/visuals.json](../server/nodes/visuals.json) —
-`{nodeType: {icon, color, skill?}}`. The handler at
-[server/nodes/_visuals.py](../server/nodes/_visuals.py) exposes
-`get_icon` / `get_color`; `BaseNode._metadata_dict` consults it at
-registration time. Node plugin classes don't carry inline `icon = ...`
-or `color = ...` declarations — a subclass MAY override by setting
-the class attr (explicit value wins) but normal authoring goes
-through visuals.json.
-
-Wire format (resolver at
-[client/src/assets/icons/index.ts](../client/src/assets/icons/index.ts)):
-
-| Prefix | Source | Example |
-|---|---|---|
-| `asset:<key>` | Filesystem SVG; Vite `import.meta.glob` over `client/src/assets/icons/**/*.svg`. Key is filename minus `.svg`. | `asset:gmail` |
-| `<lib>:<brand>` | NPM icon package. `ICON_LIBRARIES` dispatch table with `lobehub` registered. | `lobehub:Claude` |
-| `data:` / `http(s)://` / `/…` | URL passthrough | — |
-| plain text | emoji | `🤖` |
-
-Frontend renders via the single
-[`<NodeIcon>`](../client/src/assets/icons/NodeIcon.tsx) primitive —
-one resolver, four branches (lib component / image / text / fallback).
-It does **not** apply parent color: lobehub `.Color` SVGs use
-`currentColor` for parts of the brand artwork, so wrapping them in
-`style={{ color: brandColor }}` would mono-tint multi-color brand
-marks. Sites that need a tinted backdrop set `style={{ color: brandColor }}`
-on the parent + `bg-tint-soft` / `border-tint`; NodeIcon sits inside
-without contributing to the cascade.
-
-Group-palette metadata follows the same pattern via
-[server/nodes/groups.py](../server/nodes/groups.py): palette groups
-declare `{label, icon, color, visibility}`. Retires the frontend's
-`CATEGORY_ICONS` / `labelMap` / `colorMap` / `SIMPLE_MODE_CATEGORIES`.
-
-**SKILL.md icon/color is auto-resolved from the target node.**
-`SkillLoader._parse_skill_metadata` reads `allowed-tools`, finds the
-first token that resolves to a node in visuals.json, and inherits
-that node's icon and color. Skills with a node target carry no
-inline `metadata.icon` / `metadata.color`. **Orphan skills**
-(personality, memory operators, autonomous patterns — no node
-target) keep inline values inside `metadata` since the resolver
-returns nothing for them. The `allowed-tools` field is snake_case
-(matching Python conventions); node `type` is camelCase (workflow
-JSON contract); the lookup converts at the boundary.
-
-`visuals.json` entries optionally carry a `skill` field pointing at
-the teaching skill folder — a reverse map for the frontend to find
-the skill from a node (e.g. a future "teach this node" button).
+Drop `icon.svg` and `meta.json` (`{"color": "#xxx"}`) into the plugin folder. Zero edits elsewhere.
+
+### 10.B — Icon + color: per-plugin folder + visuals.json fallback
+
+Icons live as `icon.svg` (or `icon_<nodeType>.svg` for multi-node folders like whatsapp) in the plugin folder; colors live in `meta.json`. `visuals.json` is the fallback registry for emoji / `lobehub:<brand>` icons + the skill reverse-map. Full resolution chain + wire format + frontend rendering all documented in [server/nodes/README.md → Icon + color](../server/nodes/README.md). Credential brand icons via `Credential.get_icon_path()` resolve to `server/credentials/icons/<provider>.svg` or co-located `credential_<id>.svg`; served by `GET /api/schemas/credentials/{provider}/icon`.
### 10.G — Parameter panel fully spec-driven
diff --git a/docs-internal/specialized_agent_node_creation.md b/docs-internal/specialized_agent_node_creation.md
deleted file mode 100644
index 1a974c35..00000000
--- a/docs-internal/specialized_agent_node_creation.md
+++ /dev/null
@@ -1,819 +0,0 @@
-# Specialized AI Agent Node Creation Guide
-
-> **⚠️ Pre-Wave-11 — historical reference only.**
-> Node authoring now happens on the backend: each node is a Python plugin under `server/nodes/<category>/<node>.py` that emits a `NodeSpec`. The frontend reads specs via [client/src/lib/nodeSpec.ts](../client/src/lib/nodeSpec.ts) + [adapters/nodeSpecToDescription.ts](../client/src/adapters/nodeSpecToDescription.ts). See [plugin_system.md](./plugin_system.md) and [server/nodes/README.md](../server/nodes/README.md) for the current model. The snippets below that reference `client/src/nodeDefinitions/*` are kept for historical context.
-
-## Overview
-
-Specialized Agent nodes are AI Agents pre-configured for specific domains and use cases. They inherit full AI Agent functionality (provider selection, model configuration, prompt templates, thinking/reasoning) while being tailored for specific capabilities like Android control, coding, web automation, task management, or social messaging.
-
-## Full Capabilities
-
-All specialized agents support:
-
-| Capability | Description |
-|------------|-------------|
-| **LangGraph Execution** | Full StateGraph with iterative tool-calling loop (max 10 iterations) |
-| **6 AI Providers** | OpenAI, Anthropic (Claude), Google (Gemini), Groq, OpenRouter, Cerebras |
-| **Extended Thinking** | Thinking/reasoning for Claude, Gemini, Groq, OpenAI o-series with output available for downstream nodes |
-| **Skill Injection** | Master Skill expansion with `get_registry_prompt()` system message enhancement |
-| **Tool Calling** | Connect tool nodes to `input-tools` for LLM tool invocation |
-| **Two-Tier Memory** | Short-term (markdown window) + long-term (vector store) via `input-memory` |
-| **Task Delegation** | Fire-and-forget async delegation, receive results via `input-task` handle |
-| **Input Auto-Fallback** | Empty prompt extracts text from connected `input-main` nodes |
-| **taskTrigger Integration** | React to child agent completion events via `input-task` handle |
-
-## Architecture
-
-```
-Skill Nodes Specialized Agent Output
-[Android Skill] ----+
- +---> [Android Control Agent] ---> Workflow Output
-Memory Node --------+ (AI Agent)
- +
-Tool Nodes ---------+
-[Battery Monitor]
-[WiFi Automation]
-Task Trigger -------+ (input-task handle)
-```
-
-**Key Characteristics:**
-- **Full AI Agent Inheritance**: Same AI configuration options as base AI Agent (provider, model, prompt, system message, temperature, thinking)
-- **Left Input Handles**: Main input (30%), Memory input (55%), Task input (85%) on the left side
-- **Bottom Handles**: Skill (25%) and Tool (75%) connections at the bottom
-- **Right Output Handle**: Agent output for workflow continuation
-- **Task Input**: Receives task completion events from taskTrigger nodes for delegation result handling
-- **Domain-Specific**: Pre-configured descriptions and use cases for specific capabilities
-
-## Existing Specialized Agents
-
-All agent colors use centralized dracula theme constants from `client/src/styles/theme.ts`.
-
-| Node | Name | Description | Dracula Color |
-|------|------|-------------|---------------|
-| `android_agent` | Android Control Agent | Android device control agent | `dracula.green` |
-| `coding_agent` | Coding Agent | Code execution agent | `dracula.cyan` |
-| `web_agent` | Web Control Agent | Web automation agent | `dracula.pink` |
-| `task_agent` | Task Management Agent | Task automation agent | `dracula.purple` |
-| `social_agent` | Social Media Agent | Social messaging agent | `dracula.green` |
-| `travel_agent` | Travel Agent | Travel planning agent | `dracula.orange` |
-| `tool_agent` | Tool Agent | Tool orchestration agent | `dracula.yellow` |
-| `productivity_agent` | Productivity Agent | Productivity workflows agent | `dracula.cyan` |
-| `payments_agent` | Payments Agent | Payment processing agent | `dracula.green` |
-| `consumer_agent` | Consumer Agent | Consumer interactions agent | `dracula.purple` |
-| `autonomous_agent` | Autonomous Agent | Autonomous operations with Code Mode patterns | `dracula.purple` |
-| `orchestrator_agent` | Orchestrator Agent | Multi-agent coordination and task delegation | `dracula.cyan` |
-| `rlm_agent` | RLM Agent | Recursive Language Model agent with REPL code execution | `dracula.orange` |
-
-**Note:** `rlm_agent` is unique among specialized agents -- it routes to `handle_rlm_agent` -> `RLMService` (not `handle_chat_agent`). It uses RLM's REPL-based execution instead of LangGraph. See `docs-internal/rlm_service.md` for full details.
-
-## Shared AI Agent Properties
-
-All specialized agents share the same AI configuration properties defined in `AI_AGENT_PROPERTIES`:
-
-```typescript
-const AI_AGENT_PROPERTIES: INodeProperties[] = [
- {
- displayName: 'AI Provider',
- name: 'provider',
- type: 'options',
- options: [
- { name: 'OpenAI', value: 'openai' },
- { name: 'Anthropic (Claude)', value: 'anthropic' },
- { name: 'Google (Gemini)', value: 'gemini' },
- { name: 'Groq', value: 'groq' },
- { name: 'OpenRouter', value: 'openrouter' }
- ],
- default: 'openai',
- description: 'The AI provider to use (configure API keys in Credentials)'
- },
- {
- displayName: 'Model',
- name: 'model',
- type: 'string',
- default: '',
- required: true,
- placeholder: 'Select a model...',
- description: 'AI model to use for the agent',
- typeOptions: {
- dynamicOptions: true,
- dependsOn: ['provider']
- }
- },
- {
- displayName: 'Prompt',
- name: 'prompt',
- type: 'string',
- default: '{{ $json.chatInput }}',
- required: true,
- typeOptions: { rows: 4 },
- description: 'The prompt template for the AI agent',
- placeholder: 'Enter your prompt or use template variables...'
- },
- {
- displayName: 'System Message',
- name: 'systemMessage',
- type: 'string',
- default: 'You are a helpful assistant',
- typeOptions: { rows: 3 },
- description: 'Define the behavior and personality of the AI agent'
- },
- {
- displayName: 'Options',
- name: 'options',
- type: 'collection',
- placeholder: 'Add Option',
- default: {},
- options: [
- {
- displayName: 'Temperature',
- name: 'temperature',
- type: 'number',
- default: 0.7,
- typeOptions: { minValue: 0, maxValue: 2, numberStepSize: 0.1 },
- description: 'Controls randomness in responses'
- },
- {
- displayName: 'Maximum Tokens',
- name: 'maxTokens',
- type: 'number',
- default: 1000,
- typeOptions: { minValue: 1, maxValue: 8192 },
- description: 'Maximum number of tokens to generate'
- },
- {
- displayName: 'Thinking/Reasoning',
- name: 'thinkingEnabled',
- type: 'boolean',
- default: false,
- description: 'Enable extended thinking for supported providers'
- },
- {
- displayName: 'Thinking Budget',
- name: 'thinkingBudget',
- type: 'number',
- default: 2048,
- typeOptions: { minValue: 1024, maxValue: 16000 },
- description: 'Token budget for thinking (Claude, Gemini, Cerebras)',
- displayOptions: { show: { thinkingEnabled: [true] } }
- },
- {
- displayName: 'Reasoning Effort',
- name: 'reasoningEffort',
- type: 'options',
- options: [
- { name: 'Low', value: 'low' },
- { name: 'Medium', value: 'medium' },
- { name: 'High', value: 'high' }
- ],
- default: 'medium',
- description: 'Reasoning effort level (OpenAI o-series, Groq)',
- displayOptions: { show: { thinkingEnabled: [true] } }
- }
- ]
- }
-];
-```
-
-## Shared Constants
-
-All specialized agents use shared constants defined in `specializedAgentNodes.ts`:
-
-```typescript
-// Inputs shared by AI Agent and all Specialized Agent nodes
-export const AI_AGENT_INPUTS = [
- { name: 'main', displayName: 'Input', type: 'main' as NodeConnectionType, description: 'Agent input' },
- { name: 'skill', displayName: 'Skill', type: 'main' as NodeConnectionType, description: 'Skill nodes that provide context and instructions' },
- { name: 'memory', displayName: 'Memory', type: 'main' as NodeConnectionType, description: 'Memory node for conversation history' },
- { name: 'tools', displayName: 'Tool', type: 'main' as NodeConnectionType, description: 'Tool nodes for agent capabilities' },
- { name: 'task', displayName: 'Task', type: 'main' as NodeConnectionType, description: 'Task completion events from taskTrigger' },
-];
-
-// Outputs shared by AI Agent and all Specialized Agent nodes
-export const AI_AGENT_OUTPUTS = [
- { name: 'main', displayName: 'Output', type: 'main' as NodeConnectionType, description: 'Agent output' }
-];
-
-// Properties shared by AI Agent and all Specialized Agent nodes
-export const AI_AGENT_PROPERTIES: INodeProperties[] = [
- // Provider, Model, Prompt, System Message, Options (temperature, maxTokens, thinking)
-];
-```
-
-## Creating a New Specialized Agent
-
-### Step 1: Add Node Definition
-
-Add to `client/src/nodeDefinitions/specializedAgentNodes.ts`:
-
-```typescript
-import { dracula } from '../styles/theme';
-
-// Database Agent - AI Agent with database capabilities
-database_agent: {
- displayName: 'Database Agent',
- name: 'database_agent',
- icon: '...',
- group: ['agent', 'ai'], // CRITICAL: 'agent' first for category placement
- version: 1,
- subtitle: 'Data Operations',
- description: 'AI Agent specialized for database operations. Connect skills, memory, and database nodes.',
- defaults: { name: 'Database Agent', color: dracula.cyan }, // Use centralized dracula theme
- inputs: AI_AGENT_INPUTS, // Use shared constant
- outputs: AI_AGENT_OUTPUTS, // Use shared constant
- properties: AI_AGENT_PROPERTIES // Use shared constant
-}
-```
-
-**Important**: Always use the shared constants (`AI_AGENT_INPUTS`, `AI_AGENT_OUTPUTS`, `AI_AGENT_PROPERTIES`) instead of defining inputs/outputs inline. This ensures all agents have consistent handles including the `input-task` handle for delegation.
-
-### Step 1b: Add to SPECIALIZED_AGENT_TYPES
-
-```typescript
-export const SPECIALIZED_AGENT_TYPES = [
- 'android_agent', 'coding_agent', 'web_agent', 'task_agent', 'social_agent',
- 'travel_agent', 'tool_agent', 'productivity_agent', 'payments_agent', 'consumer_agent',
- 'database_agent' // Add new agent
-];
-```
-
-### Step 2 (Legacy Pattern - NOT RECOMMENDED)
-
-The old pattern defined inputs inline:
-
-```typescript
-inputs: [
- {
- name: 'main',
- displayName: 'Input',
- type: 'main' as NodeConnectionType,
- description: 'Agent input'
- },
- // ... more inputs
-],
-outputs: [{
- name: 'main',
- displayName: 'Output',
- type: 'main' as NodeConnectionType,
- description: 'Agent output'
- }],
- properties: AI_AGENT_PROPERTIES // CRITICAL: Use shared properties for full AI configuration
-},
-```
-
-### Step 2: Add to SPECIALIZED_AGENT_TYPES
-
-In the same file, add to the array:
-
-```typescript
-export const SPECIALIZED_AGENT_TYPES = [
- 'android_agent', 'coding_agent', 'web_agent', 'task_agent', 'social_agent',
- 'travel_agent', 'tool_agent', 'productivity_agent', 'payments_agent', 'consumer_agent',
- 'database_agent' // Add new agent here
-];
-```
-
-### Step 3: Add AIAgentNode Config
-
-Add to `client/src/components/AIAgentNode.tsx` in `AGENT_CONFIGS`:
-
-```typescript
-database_agent: {
- icon: <span style={{ fontSize: '28px' }}>...</span>,
- title: 'Database Agent',
- subtitle: 'Data Operations',
- themeColorKey: 'cyan', // References dracula.cyan - resolved at runtime via dracula[config.themeColorKey]
- bottomHandles: [
- { id: 'input-skill', label: 'Skill', position: '25%' },
- { id: 'input-tools', label: 'Tool', position: '75%' },
- ],
- leftHandles: [
- { id: 'input-memory', label: 'Memory', position: '70%' },
- ],
- topOutputHandle: { id: 'output-top', label: 'Output' },
- width: 260,
- height: 160,
-},
-```
-
-### Step 4: Verify Dashboard Mapping
-
-The `Dashboard.tsx` automatically maps specialized agents via `SPECIALIZED_AGENT_TYPES`:
-
-```typescript
-// Pre-register specialized agent nodes explicitly
-SPECIALIZED_AGENT_TYPES.forEach(type => {
- types[type] = AIAgentNode;
-});
-```
-
-No changes needed if you added to `SPECIALIZED_AGENT_TYPES`.
-
-### Step 5: Add to Parameter Panel Arrays
-
-In `client/src/components/parameterPanel/MiddleSection.tsx`, add to `AGENT_WITH_SKILLS_TYPES`:
-```typescript
-const AGENT_WITH_SKILLS_TYPES = [
- 'chatAgent', 'android_agent', 'coding_agent', 'web_agent', 'task_agent', 'social_agent',
- 'travel_agent', 'tool_agent', 'productivity_agent', 'payments_agent', 'consumer_agent',
- 'database_agent' // Add new agent
-];
-```
-
-In `client/src/components/parameterPanel/InputSection.tsx`, add to both arrays:
-- `AGENT_WITH_SKILLS_TYPES` (same as above)
-- `aiAgentTypes` (includes `'aiAgent'` as well)
-
-### Step 6: Backend - Add to Constants
-
-In `server/constants.py`, add to `AI_AGENT_TYPES` frozenset:
-```python
-AI_AGENT_TYPES: FrozenSet[str] = frozenset([
- 'aiAgent', 'chatAgent',
- 'android_agent', 'coding_agent', 'web_agent', 'task_agent', 'social_agent',
- 'travel_agent', 'tool_agent', 'productivity_agent', 'payments_agent', 'consumer_agent',
- 'database_agent', # Add new agent
-])
-```
-
-### Step 7: Backend - Add Handler Registry Entry
-
-In `server/services/node_executor.py`, add to `_build_handler_registry()`:
-```python
-'database_agent': partial(handle_chat_agent, ai_service=self.ai_service, database=self.database),
-```
-
-### Step 8: Backend - Add to Delegation Check
-
-In `server/services/handlers/tools.py`, add to the delegation check tuple in `execute_tool()`:
-```python
-if node_type in ('aiAgent', 'chatAgent', 'android_agent', ..., 'database_agent'):
- return await _execute_delegated_agent(tool_args, config)
-```
-
-### Step 9: Backend - Add Delegation Tool Definitions
-
-In `server/services/ai.py`, add to three locations:
-1. `DEFAULT_TOOL_NAMES`: `'database_agent': 'delegate_to_database_agent'`
-2. `DEFAULT_TOOL_DESCRIPTIONS`: `'database_agent': 'Delegate database tasks to the Database Agent'`
-3. `DelegateToAgentSchema` condition tuple: add `'database_agent'`
-
-## AgentConfig Interface
-
-```typescript
-type ThemeColorKey = 'purple' | 'cyan' | 'green' | 'pink' | 'orange' | 'yellow' | 'red';
-
-interface AgentConfig {
- icon: React.ReactNode; // Emoji with fontSize 28px
- title: string; // Display title
- subtitle: string; // Subtitle below title
- themeColorKey: ThemeColorKey; // Dracula theme color key - resolved via dracula[themeColorKey]
- bottomHandles: Array<{
- id: string; // Handle ID (e.g., 'input-skill')
- label: string; // Handle label
- position: string; // CSS position (e.g., '25%')
- }>;
- leftHandles?: Array<{...}>; // Optional left-side handles (below main input)
- rightHandles?: Array<{...}>; // Optional right-side handles
- topOutputHandle?: {...}; // Optional top output handle
- skipInputHandle?: boolean; // Skip left input handle
- skipRightOutput?: boolean; // Skip right output handle
- width?: number; // Custom width in pixels
- height?: number; // Custom height in pixels
-}
-```
-
-## Visual Design
-
-Specialized agents render as rectangular cards with AI Agent-style handles:
-
-```
-+-------------------------------------------+
-| ... o | (params button, status indicator)
-| |
-| Input o--------- | (left handle at 30%)
-| |
-| ... | (icon - emoji)
-| Database Agent | (title)
-| Data Operations | (subtitle)
-| |
-| Memory <>--------- | (left handle at 70% - diamond)
-| |
-| Skill Tool | (bottom handle labels)
-+-----------<>--------------<>--------------+ (bottom handles - diamond)
- o--- (right output handle)
-```
-
-## Handle Layout
-
-| Handle | Position | ID | Purpose |
-|--------|----------|----|---------|
-| Left Input | 30% from top | `input-main` | Main workflow data input |
-| Left Memory | 70% from top | `input-memory` | Memory node for history |
-| Bottom Skill | 25% from left | `input-skill` | Skill nodes for context |
-| Bottom Tool | 75% from left | `input-tools` | Tool nodes for capabilities |
-| Right Output | Center right | `output-main` | Agent output |
-
-## Handle Styling
-
-All handles use diamond shape (45-degree rotation) with consistent styling:
-
-```typescript
-// Left handles (Input, Memory)
-style={{
- position: 'absolute',
- left: '-6px',
- top: position, // '30%' or '70%'
- width: theme.nodeSize.handle,
- height: theme.nodeSize.handle,
- backgroundColor: theme.colors.background,
- border: `2px solid ${theme.colors.textSecondary}`,
- borderRadius: '0',
- transform: 'translateY(-50%) rotate(45deg)'
-}}
-
-// Handle labels
-style={{
- fontSize: '10px',
- color: theme.colors.text,
- fontWeight: theme.fontWeight.medium,
- opacity: 0.8
-}}
-```
-
-## Component Palette Category
-
-Specialized agents appear in the **AI Agents** category:
-- Group: `['agent', 'ai']` - First element determines category
-- Visible in Normal mode (SIMPLE_MODE_CATEGORIES includes 'agent')
-- Purple color theme (theme.dracula.purple)
-
-## Backend Handler
-
-Specialized agents use the same backend handler as AI Agents since they inherit the same functionality. The handler should:
-
-1. Collect skill data from `input-skill` handle
-2. Collect memory data from `input-memory` handle
-3. Collect tool data from `input-tools` handle
-4. Execute LangGraph agent with collected context
-
-See `server/services/handlers/ai.py` for the `handle_chat_agent()` implementation.
-
-## Supported AI Features
-
-All specialized agents support:
-
-| Feature | Description |
-|---------|-------------|
-| **Multi-Provider** | OpenAI, Anthropic, Google, Groq, OpenRouter, Cerebras |
-| **Dynamic Models** | Model dropdown populated based on selected provider |
-| **Prompt Templates** | Support for `{{ $json.field }}` template variables |
-| **System Message** | Customizable agent personality and behavior |
-| **Temperature** | Response randomness control (0-2) |
-| **Max Tokens** | Output length limit (1-8192) |
-| **Thinking/Reasoning** | Extended thinking for Claude, Gemini, Groq, OpenAI o-series |
-| **Thinking Budget** | Token budget for reasoning (1024-16000) |
-| **Reasoning Effort** | Low/Medium/High for OpenAI o-series and Groq |
-| **Thinking Output** | Thinking content available in Input Data & Variables for downstream nodes |
-| **Async Delegation** | Can be used as tools by parent agents (fire-and-forget) |
-| **Task Completion** | Receive delegated task results via `input-task` handle |
-| **Input Auto-Fallback** | Empty prompt extracts text from connected `input-main` nodes |
-| **Skill Injection** | Skills appended to system message via `get_registry_prompt()` |
-| **Two-Tier Memory** | Short-term (markdown) + long-term (vector store) memory |
-
-### Extended Thinking Details
-
-Thinking content is extracted differently per provider and accumulates across tool-calling iterations:
-
-| Provider | Extraction Method | Notes |
-|----------|------------------|-------|
-| **Claude** | `content_blocks` with `type='thinking'` | Requires `max_tokens > thinkingBudget` |
-| **Gemini** | `response_metadata.candidates[0].content.parts` with `thought=True` | 2.5/Flash Thinking models |
-| **Groq** | `additional_kwargs.reasoning` or `response_metadata.reasoning` | Qwen3/QwQ models, `reasoningFormat='parsed'` |
-| **OpenAI** | Reasoning summaries | o-series, requires org verification |
-
-The accumulated `thinking` content is available in the agent's output for downstream nodes to use via drag-and-drop in Input Data & Variables.
-
-## Async Agent Delegation
-
-Specialized agents can be used as tools by other agents via the `input-tools` handle. This enables hierarchical agent architectures where a parent agent delegates tasks to specialized child agents.
-
-### Architecture
-
-```
-Parent Agent decides to delegate
- |
- v
-calls delegate_to_<agent_type>(task="...", context="...")
- |
- v
-Tool handler spawns child agent via asyncio.create_task()
- |
- v
-Returns immediately: {"status": "delegated", "task_id": "..."}
- |
-Parent Agent continues working
- |
-Child Agent executes independently in background
- |
-Child broadcasts its own status updates
-```
-
-### How It Works
-
-1. **Connect agent as tool**: Connect any specialized agent to a parent agent's `input-tools` handle
-2. **Parent agent calls tool**: LLM decides to delegate using `delegate_to_<agent_type>` tool
-3. **Fire-and-forget**: Child agent spawns as background task, parent continues immediately
-4. **Independent execution**: Child agent uses its own connected skills, memory, and tools
-
-### Tool Schema
-
-When connected as a tool, the agent exposes this schema to the parent's LLM:
-
-```python
-class DelegateToAgentSchema(BaseModel):
- task: str = Field(description="The task to delegate to the child agent")
- context: Optional[str] = Field(
- default=None,
- description="Additional context for the task"
- )
-```
-
-### Example: Parent Delegates to Android Agent
-
-```
-[AI Agent] ←──tools── [Android Control Agent] ←──tools── [Battery Monitor]
- ←──tools── [WiFi Automation]
-```
-
-When the AI Agent needs to control Android devices:
-1. LLM calls `delegate_to_android_agent(task="Check battery and enable WiFi if low")`
-2. Android Agent spawns as background task
-3. AI Agent receives `{"status": "delegated", "task_id": "..."}` immediately
-4. Android Agent executes with its own battery and WiFi tools
-5. Android Agent broadcasts its own status updates
-
-### Key Design Decisions
-
-- **Non-blocking**: Parent doesn't wait for child completion
-- **Memory isolation**: Child uses its own connected memory, not parent's
-- **Independent tools**: Child has access to its own connected tools only
-- **Error isolation**: Child errors don't propagate to parent
-- **Status broadcasting**: Both agents show their own execution status in UI
-
-### Implementation Files
-
-| File | Purpose |
-|------|---------|
-| `server/services/ai.py` | `DelegateToAgentSchema` in `_get_tool_schema()` |
-| `server/services/handlers/tools.py` | `_execute_delegated_agent()` spawns child via `asyncio.create_task()` |
-| `server/services/handlers/ai.py` | Passes `context` for nested agent delegation |
-
-## Task Completion Handling
-
-The `input-task` handle allows specialized agents to receive and react to task completion events from delegated child agents.
-
-### taskTrigger Node Integration
-
-Connect a `taskTrigger` workflow node to the agent's `input-task` handle. When a delegated child agent completes (success or error), the taskTrigger fires and provides the completion data to the parent agent.
-
-```
-[Parent Agent] ←──task── [taskTrigger] ←── (listens for task_completed events)
- ↓
- delegates to
- ↓
-[Child Agent] ──(completes)──→ broadcasts task_completed event
-```
-
-### Task Completion Event Structure
-
-When a delegated child agent completes, it broadcasts a `task_completed` event:
-
-```python
-{
- 'task_id': 'uuid-string',
- 'status': 'completed' | 'error',
- 'agent_name': 'Android Control Agent',
- 'agent_node_id': 'node-id',
- 'parent_node_id': 'parent-node-id',
- 'result': '...', # Present when status='completed'
- 'error': '...', # Present when status='error'
- 'workflow_id': 'workflow-uuid'
-}
-```
-
-### Tool Stripping Behavior
-
-**Critical**: When an agent receives task completion data via `input-task`, ALL tools are stripped from the agent before execution. This prevents confusion where the agent is instructed to "report the result" but still has tools bound that it might try to use.
-
-```python
-# In handlers/ai.py - when task_data is present
-if task_data:
- # Strip all tools - agent's job is to report result, not execute
- tool_data = []
-```
-
-### Use Case: Parent Reacting to Child Completion
-
-1. Parent agent delegates task: `delegate_to_android_agent(task="Check battery")`
-2. Parent continues immediately (fire-and-forget)
-3. Child agent executes and completes
-4. Child broadcasts `task_completed` event
-5. taskTrigger connected to parent's `input-task` fires
-6. Parent agent receives task result via `input-task` handle
-7. Parent agent (with tools stripped) reports the result naturally
-
-## LangGraph Execution
-
-Specialized agents use LangGraph's StateGraph for structured tool-calling execution.
-
-### StateGraph Construction
-
-When tools are connected to `input-tools`, the agent builds a conditional graph:
-
-```python
-# Simplified from server/services/ai.py
-graph = StateGraph(AgentState)
-graph.add_node("agent", call_model)
-graph.add_node("tools", tool_executor)
-
-graph.add_conditional_edges(
- "agent",
- should_continue, # Check if LLM wants to call tools
- {"continue": "tools", "end": END}
-)
-graph.add_edge("tools", "agent") # Loop back after tool execution
-```
-
-### Iterative Tool-Calling Loop
-
-- **Max iterations**: 10 (prevents infinite loops)
-- **Loop pattern**: LLM → tool call → tool execution → LLM → ... → final response
-- **Exit conditions**: LLM returns response without tool calls, or max iterations reached
-
-### Tool-Less Optimization
-
-When no tools are connected to `input-tools`, the agent skips LangGraph entirely for better performance:
-
-```python
-if not tools:
- # Direct LLM invocation without graph overhead
- response = await model.ainvoke(messages)
-else:
- # Full LangGraph execution with tool loop
- response = await graph.ainvoke(state)
-```
-
-## Input Data Auto-Fallback
-
-When the agent's `prompt` parameter is empty, it automatically extracts text from nodes connected to `input-main`.
-
-### Extraction Priority
-
-The agent searches the connected node's output for text in this order:
-1. `message` field
-2. `text` field
-3. `content` field
-4. String representation of entire output
-
-### Use Case
-
-Enables simple workflows like:
-```
-[Chat Trigger] → [Zeenie]
-```
-
-Without manually setting `prompt` to `{{chatTrigger.message}}`, the agent auto-extracts the message.
-
-## Skill Injection
-
-Skills connected to `input-skill` are injected into the agent's system message.
-
-### Master Skill Expansion
-
-When a `masterSkill` node is connected, it expands into individual skill entries based on `skillsConfig`:
-
-```python
-skillsConfig = {
- 'whatsapp-skill': {
- 'enabled': True,
- 'instructions': '...',
- 'isCustomized': False
- },
- 'http-skill': {
- 'enabled': True,
- 'instructions': '...',
- 'isCustomized': True # User modified in UI
- }
-}
-```
-
-### Registry Prompt Generation
-
-The `SkillLoader.get_registry_prompt()` method generates a skill list appended to the system message:
-
-```markdown
-## Available Skills
-
-You have access to the following skills. Use them when appropriate:
-
-- **whatsapp-skill**: Send and receive WhatsApp messages
- - Tools: whatsapp_send, whatsapp_db
-- **http-skill**: Make HTTP requests to external APIs
- - Tools: http-request
-```
-
-### DB-First Pattern
-
-After first activation, skill instructions are stored in and read from the database:
-1. First load: Instructions seeded from SKILL.md file
-2. Subsequent loads: Database is source of truth
-3. User edits: Saved to database only
-4. "Reset to Default": Reloads from SKILL.md file
-
-## Memory Integration
-
-Memory connected to `input-memory` provides conversation history via a two-tier system.
-
-### Short-Term Memory
-
-- **Format**: Markdown with timestamps
-- **Window-based trimming**: Keeps last N message pairs (configurable via `windowSize`)
-- **Auto-append**: New human/AI messages appended after each execution
-
-### Long-Term Memory
-
-- **Optional**: Enable via `longTermEnabled` parameter
-- **Storage**: InMemoryVectorStore per session
-- **Semantic retrieval**: Archived messages retrieved by similarity
-- **Retrieval count**: Configurable via `retrievalCount` parameter
-
-### Memory Lifecycle
-
-1. Load markdown from `memoryContent` parameter
-2. Parse to LangChain messages
-3. Retrieve relevant long-term memories (if enabled)
-4. Execute agent with conversation history
-5. Append new exchange to markdown
-6. Trim to window size, archive removed messages
-7. Save updated markdown back to node parameters
-
-## Architecture Notes
-
-### Shared Handler Routing
-
-All 12 specialized agents route to the same backend handler:
-
-```python
-# In node_executor.py
-'android_agent': partial(handle_chat_agent, ai_service=..., database=...),
-'coding_agent': partial(handle_chat_agent, ai_service=..., database=...),
-# ... all 12 specialized agents use handle_chat_agent
-```
-
-This means specialization is purely UI/configuration, not backend behavioral. All agents share:
-- Same `_collect_agent_connections()` base function
-- Same skill injection pipeline
-- Same tool execution flow
-- Same memory handling
-
-### Database-First Architecture
-
-Node parameters, memory content, and tool schemas come from database first (not `node.data`):
-- Reduces workflow JSON bloat
-- Enables user customization persistence
-- Separates configuration from workflow structure
-
-## Testing
-
-1. Hard refresh browser (Ctrl+Shift+R) after changes
-2. Check React DevTools for node type registration
-3. Verify node appears in Component Palette under "AI Agents"
-4. Test drag-and-drop to canvas
-5. Open parameter panel - verify AI configuration options appear
-6. Test left handle connections (Input, Memory)
-7. Test bottom handle connections (Skill, Tool)
-8. Test right output handle connections
-9. Execute agent and verify output
-
-## Files Reference
-
-### Frontend
-| File | Purpose |
-|------|---------|
-| `client/src/styles/theme.ts` | Centralized dracula theme constants (colors used in node defaults) |
-| `client/src/components/AIAgentNode.tsx` | AGENT_CONFIGS visual configuration with themeColorKey |
-| `client/src/components/parameterPanel/MiddleSection.tsx` | AGENT_WITH_SKILLS_TYPES array |
-| `client/src/components/parameterPanel/InputSection.tsx` | AGENT_WITH_SKILLS_TYPES + aiAgentTypes arrays |
-| `client/src/Dashboard.tsx` | Node type to component mapping (automatic via SPECIALIZED_AGENT_TYPES) |
-| `client/src/components/ui/ComponentPalette.tsx` | Category display (automatic via group) |
-| `client/src/nodeDefinitions.ts` | Main registry (imports specializedAgentNodes) |
-
-### Backend
-| File | Purpose |
-|------|---------|
-| `server/constants.py` | AI_AGENT_TYPES frozenset (provider detection, config node filtering) |
-| `server/services/node_executor.py` | Handler registry mapping agent types to handle_chat_agent |
-| `server/services/handlers/ai.py` | Backend handler (shared with AI Agents) |
-| `server/services/handlers/tools.py` | Delegation check in execute_tool() |
-| `server/services/ai.py` | DEFAULT_TOOL_NAMES, DEFAULT_TOOL_DESCRIPTIONS, DelegateToAgentSchema |
diff --git a/docs-internal/tool_building_pipeline.md b/docs-internal/tool_building_pipeline.md
new file mode 100644
index 00000000..8b61fee5
--- /dev/null
+++ b/docs-internal/tool_building_pipeline.md
@@ -0,0 +1,239 @@
+# Tool Building Pipeline
+
+Canonical home for how AI Agents discover connected tool nodes, build LangChain `StructuredTool` instances, bind them to the LLM, and dispatch tool calls back to the right handler. Replaces the partial explanations previously scattered across `agent_architecture.md`, `agent_delegation.md`, and `deep_agent.md`.
+
+> **Related docs:**
+> - [agent_architecture.md](./agent_architecture.md) — overall LangGraph loop that holds the bound tools
+> - [agent_delegation.md](./agent_delegation.md) — `delegate_to_*` tools + taskTrigger / input-task patterns
+> - [TEMPORAL_ARCHITECTURE.md](./TEMPORAL_ARCHITECTURE.md) — per-type Temporal activity dispatch (F4.A) that backs tool calls when the flag is on
+> - [node_creation.md](./node_creation.md) — recipe for adding a new tool node
+
+## 1. Five stages
+
+```
+1. DISCOVER handlers/ai.py:_collect_agent_connections
+ → reads edges → tool_data list
+ │
+ ▼
+2. BUILD services/ai.py:AIService._build_tool_from_node
+ → tool_data entry → (StructuredTool, config_dict)
+ │
+ ▼
+3. BIND LangGraph create_react_agent(model, tools=...)
+ → llm.bind_tools(tools) under the hood
+ │
+ ▼
+4. INVOKE LLM emits tool_calls in its response
+ → LangGraph ToolNode routes by name
+ │
+ ▼
+5. DISPATCH services/handlers/tools.py:execute_tool
+ → owns node lifecycle broadcasts
+ → _dispatch_tool routes by node_type to a handler
+```
+
+## 2. Stage 1 — Discovery (handlers/ai.py)
+
+[`_collect_agent_connections(node_id, context, database)`](../server/services/handlers/ai.py) walks the workflow edges and returns a 4-tuple per agent:
+
+```
+(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).
+- **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 `delegate_to_*` entries automatically.
+
+## 3. Stage 2 — Build (services/ai.py:_build_tool_from_node)
+
+[`AIService._build_tool_from_node(tool_info)`](../server/services/ai.py#L2609) at line 2609 returns `(StructuredTool, config_dict)` or `(None, None)` on failure.
+
+### 3a. Tool name resolution
+
+The hardcoded `DEFAULT_TOOL_NAMES` map at [`services/ai.py:2622-2691`](../server/services/ai.py#L2622) maps `node_type` → LLM-visible tool name:
+
+| `node_type` | Tool name | Category |
+|---|---|---|
+| `calculatorTool` | `calculator` | Dedicated tool |
+| `currentTimeTool` | `get_current_time` | Dedicated tool |
+| `duckduckgoSearch` | `web_search` | Dedicated tool |
+| `pythonExecutor` | `python_code` | Dual-purpose |
+| `whatsappSend` | `whatsapp_send` | Dual-purpose |
+| `whatsappDb` | `whatsapp_db` | Dual-purpose |
+| `aiAgent` → `delegate_to_ai_agent` | (18 agent types total) | Agent delegation |
+| `batteryMonitor` → `android_battery` | (16 service types) | Direct Android service |
+| ... | | |
+
+Adding a new tool type requires adding a row here. The frontend never reads this map — it's a backend-internal mapping.
+
+### 3b. Schema resolution
+
+```python
+schema = self._get_tool_schema(node_type, schema_params)
+```
+
+[`_get_tool_schema`](../server/services/ai.py#L2888) at line 2888 returns a Pydantic `BaseModel` subclass.
+
+Two paths:
+
+| Path | Source | When |
+|---|---|---|
+| **Database override** (preferred) | `ToolSchema` table (`server/models/database.py`) via `db.get_tool_schema(node_id)` | User customized the schema in the Tool Schema Editor UI |
+| **Dynamic generation** (fallback) | Hardcoded per-type schemas inside `_get_tool_schema` | No DB override; default behavior |
+
+`ToolSchema.schema_config` is JSON of `{description, fields: {name: {type, description, required}}}`. CRUD handlers in [`routers/websocket.py`](../server/routers/websocket.py): `get_tool_schema`, `save_tool_schema`, `delete_tool_schema`, `get_all_tool_schemas`.
+
+### 3c. StructuredTool construction
+
+```python
+tool = StructuredTool.from_function(
+ name=tool_name,
+ description=description,
+ args_schema=schema,
+ func=_make_callback(node_id, node_type, ...), # closure → execute_tool
+ coroutine=_make_callback_async(...),
+)
+config = {
+ "node_id": node_id,
+ "node_type": node_type,
+ "workflow_id": workflow_id,
+ "parameters": parameters,
+ "ai_service": self,
+ "database": database,
+ "nodes": nodes,
+ "edges": edges,
+ # ... per-tool extras (e.g., connected_services for androidTool)
+}
+```
+
+The returned `config` is threaded down to `execute_tool` so handlers can read injected services + graph context without going through globals.
+
+## 4. Stage 3 — Bind (LangGraph)
+
+[`services/ai.py:execute_agent`](../server/services/ai.py) builds the agent graph via `create_react_agent(model, tools=tools)` from `langgraph.prebuilt`. Under the hood this calls `model.bind_tools(tools)` on the LangChain chat model, which uses each tool's `args_schema` to render a JSON Schema in the LLM's tool-use prompt.
+
+Per-provider quirks live in the chat model class, not here — see [native_llm_sdk.md](./native_llm_sdk.md) for the OpenAI / Anthropic / Gemini differences.
+
+## 5. Stage 4 — Invoke (LLM response handling)
+
+When the LLM emits `tool_calls` in its response, LangGraph's `ToolNode` routes each call to the matching `StructuredTool` by name. The tool's async `coroutine` callback fires — this is the `_make_callback_async` closure created in stage 2 — and inside that closure:
+
+1. Broadcast `executing_tool` to the parent agent (phase broadcast, not the tool node's lifecycle).
+2. `from services.handlers.tools import execute_tool`
+3. `result = await execute_tool(tool_name, tool_args, config)` — this owns the tool node's lifecycle.
+4. Broadcast `tool_completed` to the parent agent.
+5. Return `result` to LangGraph → goes back into the LLM as a tool result message.
+
+**Single-source-of-truth rule.** `execute_tool` owns `executing` / `success` / `error` broadcasts for the **tool node**. The parent-agent closure in `services/ai.py` only emits `executing_tool` / `tool_completed` phase events for the **parent agent**. Don't duplicate either.
+
+## 6. Stage 5 — Dispatch (handlers/tools.py)
+
+[`execute_tool(tool_name, tool_args, config)`](../server/services/handlers/tools.py#L73) at line 73:
+
+```python
+1. broadcaster.update_node_status(node_id, "executing", ...)
+2. result = await _dispatch_tool(tool_name, tool_args, config)
+3a. If result.status in {"delegated", "ALREADY_DELEGATED"}: handler owns
+ its own success/error lifecycle (delegated agents broadcast from
+ inside their background task). Skip terminal broadcast.
+3b. Else: broadcaster.update_node_status(node_id, "success", {result})
+4. Return result. Exceptions trigger an "error" broadcast and re-raise.
+```
+
+[`_dispatch_tool`](../server/services/handlers/tools.py#L138) at line 138 is pure routing — no broadcasting. Routes by `config["node_type"]`:
+
+| Pattern | Handler |
+|---|---|
+| `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)
+
+`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.
+
+## 8. Delegation tools (`delegate_to_*`)
+
+Specialized agents connected to an agent's `input-tools` handle become delegation tools. Schema is fixed:
+
+```python
+class DelegateToAgentSchema(BaseModel):
+ task: str
+ context: Optional[str] = None
+```
+
+[`_execute_delegated_agent`](../server/services/handlers/tools.py#L317) at line 317:
+
+1. Generate a `task_id` (`uuid4().hex`).
+2. Spawn `asyncio.create_task(<child agent execute>)` — fire and forget.
+3. Track in `_active_delegated_nodes` so repeated calls during in-flight delegations short-circuit.
+4. Return `{"status": "delegated", "task_id": task_id}` IMMEDIATELY (parent agent continues without waiting).
+5. From inside the background task: broadcast the child's `executing`/`success`/`error` timeline + emit a `task_completed` CloudEvents event when the child finishes (success or error).
+
+Parent agents see results via three paths — see [agent_delegation.md](./agent_delegation.md) for the full pattern matrix.
+
+## 9. Per-type Temporal dispatch (F4.A)
+
+When `TEMPORAL_PER_TYPE_DISPATCH=true` and the run is happening inside a Temporal workflow, tool calls do NOT go through `execute_tool` directly. Instead:
+
+1. `AgentWorkflow` (the F4.B child workflow) gets the LLM's tool_calls list back from `agent.execute_llm_step.v1`.
+2. For each tool call, the workflow schedules `f"node.{node_type}.v{version}"` as a Temporal activity on the plugin's declared `task_queue`.
+3. The per-type activity body in [`server/services/plugin/base.py:as_activity`](../server/services/plugin/base.py) runs the same pipeline `execute_tool` would have — broadcasts, plugin `execute()` call, terminal broadcast — but inside the activity boundary.
+4. Result returns to the workflow, gets appended to the messages history, next LLM step sees it.
+
+This means tool calls inside an agent loop get Temporal's retry / timeout / heartbeat semantics independently of the parent agent's. A `code-exec` task burns its own retries; a `browser` task survives past the parent's `start_to_close_timeout` via its own heartbeat. See [TEMPORAL_ARCHITECTURE.md](./TEMPORAL_ARCHITECTURE.md).
+
+## 10. Auto-skill edges
+
+Some tools bundle a default skill — `writeTodos` ships with `write-todos-skill`, the WhatsApp tools ship with their respective skills. The frontend `useAutoSkillEdges.ts` hook detects these connections at canvas-edit time and auto-creates a phantom skill connection so the LLM gets both the tool schema (for invocation) and the skill instructions (for usage guidance) without the user having to wire two edges.
+
+`MASTER_SKILL_NODE_TYPE` constant resolves via `getCachedNodeSpec(type)?.uiHints?.isMasterSkillEditor === true`, not a hardcoded string match.
+
+## 11. Pytest invariants
+
+```
+server/tests/
+├── test_status_broadcasts.py # locks execute_tool's lifecycle broadcast contract
+├── test_credential_broadcasts.py # auth tools' CloudEvents envelope
+├── nodes/test_ai_agents.py # end-to-end agent + tool exercise
+└── temporal/test_dispatch.py # F4.A per-type activity dispatch (when flag on)
+```
+
+`_LEGACY_RAW_DICT_CALLSITES` in `test_status_broadcasts.py` is closed — new tool implementations cannot emit raw-dict broadcasts. Use `WorkflowEvent` factories + `StatusBroadcaster` wrappers; see [status_broadcaster.md](./status_broadcaster.md).
+
+## 12. Adding a new tool node
+
+The shortest path:
+
+1. Create the plugin folder: `server/nodes/tool/<plugin>/__init__.py` extending `ToolNode` (or `ActionNode` with `usable_as_tool = True` for dual-purpose).
+2. Declare `type`, `display_name`, `Params` (the schema the LLM sees), `Output`, `@Operation`-decorated `execute()`.
+3. Add a row to `DEFAULT_TOOL_NAMES` in `services/ai.py:2622-2691` — `node_type` → LLM-visible tool name.
+4. (Optional) Add a clause to `_get_tool_schema` if the dynamic-generation default isn't what you want.
+5. (Optional) Add a dispatch clause to `_dispatch_tool` if your plugin needs custom handler logic; otherwise the generic per-plugin path runs `cls.execute()` directly.
+
+Steps 3-5 are the only edits OUTSIDE the plugin folder. Steps 4-5 are usually unnecessary — most new tools use the dynamic default.
+
+See [node_creation.md](./node_creation.md) for the broader recipe and [server/nodes/README.md](../server/nodes/README.md) for the 5-minute walkthrough.
+
+## 13. What NOT to do
+
+- Don't broadcast `executing` / `success` / `error` from inside `_dispatch_tool` or a handler — `execute_tool` owns the tool node's lifecycle. Returning `{"status": "delegated"}` is the documented opt-out.
+- Don't bypass `_build_tool_from_node` to hand-craft a `StructuredTool`. The closure shape and `config` dict contents are load-bearing — agents inject services through them.
+- Don't add a new entry to `DEFAULT_TOOL_NAMES` without also handling the schema generation. The tool will register but the LLM will see `{}` for the schema and hallucinate arguments.
+- Don't catch exceptions inside the tool callback and return them as `{"error": ...}` — re-raise so `execute_tool` can broadcast `error`. The LLM-sees-tool-errors-and-continues pattern depends on this.
+- Don't store per-execution state on `AIService` (it's a singleton). Use `config` or per-call closures.