Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
refactor(ai): replace LangGraph with plain async loop; drop deep_agent
trohitg5335188b130a
diff --git a/CLAUDE.md b/CLAUDE.mdindex 2e399432..ea27bba3 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -17,7 +17,7 @@ This is a React Flow-based workflow automation platform implementing n8n-inspire| **[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 |+| **[Agent Architecture](./docs-internal/agent_architecture.md)** | How AI Agent and Chat Agent discover skills/tools, inject them into LLM prompts, and execute via the plain-async `_run_agent_loop` || **[Agent Delegation](./docs-internal/agent_delegation.md)** | How memory, parameters, and execution context flow when one AI agent delegates work to another agent connected as a tool || **[Agent Teams](./docs-internal/agent_teams.md)** | Claude SDK Agent Teams pattern - AI Employee and Orchestrator nodes with input-teammates handle for multi-agent coordination || **[Memory Compaction](./docs-internal/memory_compaction.md)** | Token tracking and model-aware memory compaction using native provider APIs (Anthropic, OpenAI) with threshold = 50% of context window |@@ -54,7 +54,6 @@ This is a React Flow-based workflow automation platform implementing n8n-inspire| **[Claude Code Permission Modes (snapshot)](./docs-internal/claude_code_permission_modes_reference.md)** | Verbatim [code.claude.com/docs/en/permission-modes](https://code.claude.com/docs/en/permission-modes) — `default` / `acceptEdits` / `plan` / `auto` / `dontAsk` / `bypassPermissions` semantics, Shift+Tab cycle, protected paths. MachinaOs default is `acceptEdits`. || **[Claude Code Headless / Print Mode (snapshot)](./docs-internal/claude_code_headless_reference.md)** | Verbatim [code.claude.com/docs/en/headless](https://code.claude.com/docs/en/headless) — `claude -p`, `--output-format` (`text` / `json` / `stream-json`), `--input-format`, `--bare`, stream-json event schema (`system/init`, `system/api_retry`, `system/plugin_install`). MachinaOs no longer uses `-p`; the pool path emits `--output-format stream-json --input-format stream-json --verbose --ide` over stdio pipes (interactive billing). The event schema is the contract `services/cli_agent/session_pool.py` parses off `proc.stdout`. || **[Claude Code Skills (snapshot)](./docs-internal/claude_code_skills_reference.md)** | Verbatim [code.claude.com/docs/en/skills](https://code.claude.com/docs/en/skills) — `SKILL.md` frontmatter spec, discovery paths, content lifecycle, `context: fork`, dynamic context injection via `` !`<command>` ``. The spec MachinaOs materialises connected skills against in `_pre_spawn`. |-| **[Deep Agent](./docs-internal/deep_agent.md)** | LangChain DeepAgents integration with filesystem tools, sub-agent delegation, auto-summarization, and planning || **[Autonomous Agent Creation](./docs-internal/autonomous_agent_creation.md)** | Creating autonomous agents with Code Mode patterns and agentic loops || **[Polyglot Server](../polyglot-server/ARCHITECTURE.md)** | Plugin registry microservice with MCP gateway (optional integration) |@@ -140,11 +139,6 @@ server/services/│ ├── openai.py # OpenAIProvider (openai SDK)│ ├── gemini.py # GeminiProvider (google-genai SDK)│ └── openrouter.py # OpenRouterProvider (extends OpenAIProvider)-├── agents/ # Deep Agent execution engine (deepagents package)-│ ├── __init__.py # Exports DeepAgentService-│ ├── service.py # Orchestration: graph creation + invocation-│ ├── adapters.py # ToolAdapter, SubAgentAdapter, ResponseExtractor-│ └── constants.py # PROVIDER_PREFIX, DEFAULT_MAX_TURNS├── proxy/ # Residential proxy provider management│ ├── __init__.py # Exports get_proxy_service, ProxyService│ ├── service.py # ProxyService singleton - provider selection, URL generation@@ -185,7 +179,7 @@ server/models/└── database.py # ConversationMessage, NodeParameter, ToolSchema, ChatMessage, TokenUsageMetric, APIUsageMetric, CompactionEvent, SessionTokenState, UserSettings, ProviderDefaults, AgentTeam, TeamMember, TeamTask, AgentMessage tablesserver/config/-├── llm_defaults.json # Per-provider defaults (model, base_url, max_output_tokens, context_length, temperature_range, reasoning_models, thinking_type, ...) AND a top-level `agent` block (recursion_limit, default_temperature, compaction.ratio) that drives the LangGraph agent loop and CompactionService — no env-var defaults; this is the source of truth.+├── llm_defaults.json # Per-provider defaults (model, base_url, max_output_tokens, context_length, temperature_range, reasoning_models, thinking_type, ...) AND a top-level `agent` block (recursion_limit, default_temperature, compaction.ratio) that drives the agent loop and CompactionService — no env-var defaults; this is the source of truth.├── model_registry.json # Cached model data from OpenRouter (auto-refreshed)├── pricing.json # LLM and API pricing config├── google_apis.json # Google Workspace API endpoints, scopes, OAuth callback paths@@ -701,11 +695,11 @@ The project uses WebSocket as the primary communication method between frontend- **groqChatModel**: Groq ultra-fast inference with Llama, Qwen3, and GPT-OSS models. Qwen3-32b supports reasoning_format.- **cerebrasChatModel**: Cerebras ultra-fast inference on custom AI hardware with Llama and Qwen models- **deepseekChatModel**: DeepSeek V3 models (deepseek-chat, deepseek-reasoner). Reasoner has always-on Chain-of-Thought with reasoning_content in response. 128K context, up to 64K output.-- **kimiChatModel**: Kimi K2 models by Moonshot AI (kimi-k2.5, kimi-k2-thinking). 256K context, 96K output. Thinking on by default for k2.5 (explicitly disabled for LangGraph agent compatibility). Fixed temperature: 0.6 (instant) / 1.0 (thinking).+- **kimiChatModel**: Kimi K2 models by Moonshot AI (kimi-k2.5, kimi-k2-thinking). 256K context, 96K output. Thinking on by default for k2.5 (explicitly disabled for tool-calling agent compatibility). Fixed temperature: 0.6 (instant) / 1.0 (thinking).- **mistralChatModel**: Mistral AI models (mistral-large-latest, mistral-small-latest, codestral-latest). Up to 256K context. No thinking support. Temperature 0-1.5.### AI Agents & Memory (3 nodes)-- **aiAgent**: Advanced AI agent with tool calling, memory input handle, and iterative reasoning. Uses LangGraph for structured execution. Parameters: Provider, Model, Prompt, System Message, Options.+- **aiAgent**: Advanced AI agent with tool calling, memory input handle, and iterative reasoning. Uses the plain-async `_run_agent_loop` for structured execution. Parameters: Provider, Model, Prompt, System Message, Options.- **chatAgent**: Conversational AI agent with memory and skill support for multi-turn chat interactions. Parameters: Provider, Model, Prompt (supports `{{chatTrigger.message}}` template or auto-fallback from connected input), System Message. Behavior extended by connected skills.### AI Agent Tool Nodes (6 dedicated + 10 dual-purpose)Tool nodes connect to AI Agent's `input-tools` handle to provide capabilities the agent can invoke during reasoning. Both `masterSkill` and `simpleMemory` are in the AI Tools category.@@ -961,11 +955,10 @@ Specialized agents are AI Agents pre-configured for specific domains. They inher- **autonomous_agent**: Autonomous Agent - AI agent for autonomous operations using Code Mode patterns. Uses agentic loops, progressive discovery, error recovery, and multi-tool orchestration for 81-98% token savings. Connect autonomous skills via Master Skill.- **orchestrator_agent**: Orchestrator Agent - Team lead agent for coordinating multiple agents. Connect specialized agents via `input-teammates` handle; they become `delegate_to_*` tools the AI can invoke.- **ai_employee**: AI Employee - Team lead agent similar to orchestrator_agent. Connect specialized agents via `input-teammates` handle for intelligent task delegation.-- **rlm_agent**: RLM Agent - Recursive Language Model agent using REPL-based code execution with recursive LM calls. Replaces LangGraph tool-calling with RLM's `exec()` REPL loop (`llm_query()`, `rlm_query()`, `FINAL()`). Routes to dedicated `handle_rlm_agent` handler and `RLMService` (not `handle_chat_agent`). Connect AI chat model nodes as small LMs for depth>=1 calls. See `docs-internal/rlm_service.md`.-- **deep_agent**: Deep Agent - AI agent powered by LangChain DeepAgents with built-in filesystem tools (read, write, edit, glob, grep, execute), sub-agent delegation, auto-summarization, and todo planning. Routes to dedicated `handle_deep_agent` handler and `DeepAgentService` (not `handle_chat_agent`). Supports memory, skills, connected tools, and teammate delegation via `input-teammates`. See `docs-internal/deep_agent.md`.+- **rlm_agent**: RLM Agent - Recursive Language Model agent using REPL-based code execution with recursive LM calls. Replaces the standard tool-calling loop with RLM's `exec()` REPL loop (`llm_query()`, `rlm_query()`, `FINAL()`). Routes to dedicated `handle_rlm_agent` handler and `RLMService` (not `handle_chat_agent`). Connect AI chat model nodes as small LMs for depth>=1 calls. See `docs-internal/rlm_service.md`.**Backend Routing:**-Specialized agents are detected by `SPECIALIZED_AGENT_TYPES` and dispatched through `BaseNode.execute()` via the node registry (Wave 11). Dedicated engines: `rlm_agent` -> `RLMService`, `deep_agent` -> `DeepAgentService` (`services/agents/`).+Specialized agents are detected by `SPECIALIZED_AGENT_TYPES` and dispatched through `BaseNode.execute()` via the node registry (Wave 11). Dedicated engine: `rlm_agent` -> `RLMService`.```pythonSPECIALIZED_AGENT_TYPES = {'android_agent', 'coding_agent', 'web_agent', 'task_agent', 'social_agent',@@ -979,7 +972,6 @@ Team leads (`orchestrator_agent`, `ai_employee`) have a special `input-teammates```python# In handlers/ai.pyTEAM_LEAD_TYPES = {'orchestrator_agent', 'ai_employee'}-# deep_agent collects teammates in handle_deep_agent and converts to deepagents SubAgent dicts# Teammates become delegate_to_* tools automaticallyif node_type in TEAM_LEAD_TYPES:@@ -1637,7 +1629,7 @@ server/nodes/document/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.-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).+Full architecture, dispatch matrix, per-node lifecycle, heartbeat semantics, the 14 migrating agent types + 2 bypass agents (rlm_agent / claude_code_agent), the 6 F4.B agent activities (`prepare_payload.v1` / `execute_llm_step.v1` / `persist_turn.v1` / `compact_memory.v1` / `store_output.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@@ -2050,10 +2042,9 @@ workspace_base_dir: str = Field(default="data/workspaces", env="WORKSPACE_BASE_D|------|-------------|| `server/core/config.py` | `workspace_base_dir` setting || `server/services/workflow.py` | `_get_workspace_dir()`, injects into context |-| `server/services/agents/service.py` | `FilesystemBackend(root_dir=workspace_dir, virtual_mode=True)` |-| `server/services/handlers/deep_agent.py` | Passes `workspace_dir` from context to service || `server/services/handlers/document.py` | `fileDownloader` uses workspace for downloads || `server/services/handlers/code.py` | `workspace_dir` available in Python/JS/TS execution |+| `server/nodes/filesystem/_backend.py` | `NushellBackend(root_dir=workspace_dir, virtual_mode=True)` for the file/shell plugins |### Execution System- **Supported Components**: AI models, location services, Android automation, WhatsApp messaging, HTTP requests, webhooks@@ -2106,7 +2097,7 @@ deploy_workflow() -> Sets up triggers, returns immediately**Dual-path execution architecture:**- **Native SDK path** (`execute_chat()`, `fetch_models()`): OpenAI, Anthropic, Gemini, OpenRouter, xAI, DeepSeek, Kimi, Mistral, Ollama, LM Studio use the `openai` Python SDK via `services/llm/` layer with config-driven `base_url`. Local providers (Ollama, LM Studio) ride the same OpenAI-compat path — `OpenAIProvider` is constructed with `base_url={user-stored URL}` so requests stay on `http://localhost:…` and never hit api.openai.com. Factory: `create_provider(name, api_key)` with lazy imports.-- **LangChain agent path** (`execute_agent()`, `execute_chat_agent()`): All providers use `ChatOpenAI` with `base_url` from `llm_defaults.json` + LangGraph for tool calling. OpenAI-compatible providers (DeepSeek, Kimi, Mistral) pass `max_tokens` via `extra_body` to bypass LangChain's `max_completion_tokens` conversion.+- **LangChain agent path** (`execute_agent()`, `execute_chat_agent()`): All providers use `ChatOpenAI` with `base_url` from `llm_defaults.json` + `chat_model.bind_tools` for tool calling, driven by the plain-async `_run_agent_loop`. OpenAI-compatible providers (DeepSeek, Kimi, Mistral) pass `max_tokens` via `extra_body` to bypass LangChain's `max_completion_tokens` conversion.- **LangChain fallback** (`execute_chat()`): Groq, Cerebras still use LangChain `create_model()` + `chat_model.invoke()`.- Native types aliased in ai.py: `NativeMessage`, `NativeThinkingConfig`, `LLMResponse` to avoid naming conflicts with LangChain's `ThinkingConfig`.- Provider configs (base_url, models_endpoint, supported_params, temperature constraints) are driven by `server/config/llm_defaults.json` -- no hardcoded URLs in Python code.@@ -2305,7 +2296,7 @@ _AGENT_TYPES = ['aiAgent', 'chatAgent', 'android_agent', 'coding_agent','web_agent', 'task_agent', 'social_agent', 'travel_agent','tool_agent', 'productivity_agent', 'payments_agent','consumer_agent', 'autonomous_agent', 'orchestrator_agent',- 'ai_employee', 'rlm_agent', 'claude_code_agent', 'deep_agent']+ 'ai_employee', 'rlm_agent', 'claude_code_agent']_CHAT_MODEL_TYPES = ['openaiChatModel', 'anthropicChatModel', 'geminiChatModel', ...]NODE_OUTPUT_SCHEMAS = {**{t: AIAgentOutput for t in _AGENT_TYPES},@@ -2329,12 +2320,12 @@ Adding a new node type's output shape: define one Pydantic model, register it in## AI Agent Node Architecture-### LangGraph Loop Termination-The standard agent path (`build_agent_graph` in `services/ai.py`) routes purely on `pending_tool_calls` — no custom iteration counter. Termination is bounded by LangGraph's built-in `recursion_limit`, sourced from `agent.recursion_limit` in `llm_defaults.json` (currently 500 — generous backstop, not the load-bearing termination signal).+### Agent Loop Termination+The standard agent path (`_run_agent_loop` in `services/ai.py`) routes purely on `response.tool_calls` — no custom iteration counter beyond `max_iterations`. The cap is sourced from `agent.recursion_limit` in `llm_defaults.json` (currently 500 — generous backstop, not the load-bearing termination signal).The token-based compaction threshold (`agent.compaction.ratio` × context_length, ≈100K for claude-sonnet-4-6) is the real termination signal: `_track_token_usage` runs after each agent turn, and when cumulative tokens cross the threshold it invokes `CompactionService.compact_context` to summarise the transcript before the next turn.-If the recursion cap is ever hit anyway, the `GraphRecursionError` handler appends a terminal `AIMessage` carrying a truncation note so `_extract_text_content` returns a usable partial response and the workflow continues — `_track_token_usage` and any post-loop persistence still run.+If the iteration cap is ever hit anyway, `_run_agent_loop` appends a terminal `AIMessage` carrying a truncation note and returns `truncated=True` so `_extract_text_content` returns a usable partial response and the workflow continues — `_track_token_usage` and any post-loop persistence still run.### Spec-driven component design (Wave 10.D)@@ -2378,7 +2369,7 @@ The dispatch keys off `spec.componentKind` (a backend-declared string), never `s| Feature | AI Agent | Zeenie ||---------|----------|------------|-| Tool Calling | Yes (LangGraph) | Yes (LangGraph) |+| Tool Calling | Yes (agent loop) | Yes (agent loop) || Memory Support | Yes | Yes || Skill Support | Yes | Yes || Task Input | Yes (input-task) | Yes (input-task) |@@ -2403,7 +2394,7 @@ Handler collects tool_data: {node_id, node_type, parameters, label, connected_se↓AIService._build_tool_from_node() → creates schema-only StructuredTool↓-LangGraph binds tools to LLM+_run_agent_loop binds tools via chat_model.bind_tools(tools)↓LLM decides to call tool with arguments↓@@ -2442,7 +2433,7 @@ Chat Trigger → Zeenie ← HTTP Skill (SKILL.md context)The Zeenie will:- Load SKILL.md instructions from connected skill nodes- Build tools from connected tool nodes (httpRequest, calculatorTool, etc.)-- Use LangGraph for tool execution when tools are connected+- Use `_run_agent_loop` for tool execution when tools are connected### Backend HandlersWave 11: `handle_ai_agent` / `handle_chat_agent` were deleted. Agent execution now flows through `BaseNode.execute()` + `NodeContext.from_legacy()` via the node registry (`server/nodes/agent/`). Connection collection is handled by the agent node classes, which internally call `_collect_agent_connections()` to:@@ -2451,8 +2442,8 @@ Wave 11: `handle_ai_agent` / `handle_chat_agent` were deleted. Agent execution n- Handles MasterSkill expansion into individual skill entriesBoth call corresponding AI service methods:-- `AIService.execute_agent()` - Full LangGraph execution with tool binding-- `AIService.execute_chat_agent()` - LangGraph execution with skills providing context + tools+- `AIService.execute_agent()` - Runs `_run_agent_loop` with tool binding+- `AIService.execute_chat_agent()` - Runs `_run_agent_loop` (when tools) or single `ainvoke` (no tools), with skills providing context + tools### Async Agent Delegation (Nested Agents)@@ -3439,7 +3430,7 @@ I don't have access to real-time weather data...- `services/memory/vector_store.py` — `get_memory_vector_store` + per-session `InMemoryVectorStore` cache- `services/memory/state.py` — `clear_agent_session_state(session_id, workflow_id, clear_long_term, memory_node_id)`; when `memory_node_id` is supplied it resets `memory_content` to the default placeholder AND wipes `last_session_id` server-side (single DB write)- `services/memory/__init__.py` — re-exports the full surface so existing `from services.memory import …` callers keep working-- **AI Integration (aiAgent / chatAgent / deep_agent / rlm_agent)**: `server/services/ai.py` — `execute_agent` / `execute_chat_agent` consume `memory_data`, call the markdown helpers via the package re-exports+- **AI Integration (aiAgent / chatAgent / rlm_agent)**: `server/services/ai.py` — `execute_agent` / `execute_chat_agent` consume `memory_data`, call the markdown helpers via the package re-exports- **CLI bridge (`claude_code_agent`)**: `server/services/cli_agent/service.py:_persist_memory` — appends turns to `memory_content` via the same markdown helpers AND saves `simpleMemory.last_session_id` from the most recent successful run's `r.session_id`. Always broadcasts `node_parameters_updated` so the simpleMemory parameter panel refetches live (no page reload needed).- **Edge walker**: `server/services/plugin/edge_walker.py:_build_memory_entry` — surfaces `memory_content` + `window_size` + `long_term_enabled` + `retrieval_count` + `last_session_id` to every consuming agent@@ -3864,7 +3855,7 @@ Tool nodes provide capabilities that AI Agents can invoke during reasoning. Each```Tool Node (calculatorTool) → (tool output) → AI Agent (input-tools handle)↓- LangGraph builds tools from schemas+ _run_agent_loop builds tools from schemas↓LLM decides when to call tools↓@@ -3876,7 +3867,7 @@ Tool Node (calculatorTool) → (tool output) → AI Agent (input-tools handle)### Tool Execution Flow1. **Tool Discovery**: AI Agent scans edges for nodes connected to `input-tools` handle2. **Schema Building**: `_get_tool_schema()` in `ai.py` creates Pydantic schema for each tool type-3. **Tool Binding**: LangGraph binds tools to the LLM model+3. **Tool Binding**: `_run_agent_loop` binds tools via `chat_model.bind_tools(tools)`4. **LLM Decision**: LLM decides when to call tools based on user query5. **Status Broadcast**: `executing_tool` status broadcast with tool_name for UI animation6. **Tool Execution**: `execute_tool()` in `tools.py` dispatches to appropriate handler@@ -4974,7 +4965,7 @@ Updated `client_left` and presence handlers use `has_real_android_devices()` ins| `android_status` | Android device connection update || `node_status` | Node execution status change || `node_output` | Node execution output data |-| `agent_progress` | CloudEvents v1.0 envelope (type=`agent.progress`) — per-step LangGraph iteration count, drives the live "N / max" badge on AI Agent canvas nodes |+| `agent_progress` | CloudEvents v1.0 envelope (type=`agent.progress`) — per-step agent-loop iteration count, drives the live "N / max" badge on AI Agent canvas nodes || `variable_update` | Single variable value change || `workflow_status` | Workflow execution progress || `api_key_status` | API key validation status |@@ -5214,7 +5205,7 @@ This function:- **Onboarding Service**: 5-step welcome wizard (Welcome, Concepts, API Keys, Canvas Tour, Get Started) using Ant Design Steps/Card/Button/Typography. Database-backed via `UserSettings.onboarding_completed` + `onboarding_step`. Existing users auto-skip (migration marks `examples_loaded=1` as completed). Replayable from Settings "Help" section. No new WebSocket handlers needed. See [Onboarding Service](./docs-internal/onboarding.md) for details.- **Node.js Code Executor**: Persistent Node.js server (Express + tsx) at port 3020 for JavaScript/TypeScript execution, replacing subprocess spawning per execution. Handlers in `server/services/handlers/code.py` call `NodeJSClient` which makes HTTP requests to the Node.js server. All config via environment variables (`NODEJS_EXECUTOR_URL`, `NODEJS_EXECUTOR_PORT`, etc.).- **writeTodos Tool Node**: Dedicated AI tool for task planning connecting to any agent's `input-tools` handle. `TodoService` singleton (`server/services/todo_service.py`) stores JSON-based per-session todo state keyed by workflow_id. Handler broadcasts `phase: "todo_update"` via WebSocket on each update for real-time UI; `formatTodoOutput()` in `OutputDisplayPanel.tsx` renders the result as a checklist with `[ ]` / `[~]` / `[x]` icons. Schema uses `TodoItem`/`TodoStatus` Pydantic enum. Skill at `server/skills/assistant/write-todos-skill/SKILL.md` teaches the plan-work-update loop.-- **Temporal Activity Heartbeats**: Activities send `activity.heartbeat()` on every non-matching WebSocket broadcast inside the read loop in `services/temporal/activities.py`. This keeps long-running DeepAgent and browser operations alive past the 2-minute `heartbeat_timeout`. Start/end heartbeats alone were causing `TIMEOUT_TYPE_HEARTBEAT` failures on ops taking 5-10 minutes. Connection config: `heartbeat=30`, `receive_timeout=540` (fits within 10-min `start_to_close_timeout`).+- **Temporal Activity Heartbeats**: Activities send `activity.heartbeat()` on every non-matching WebSocket broadcast inside the read loop in `services/temporal/activities.py`. This keeps long-running browser and claude_code_agent operations alive past the 2-minute `heartbeat_timeout`. Start/end heartbeats alone were causing `TIMEOUT_TYPE_HEARTBEAT` failures on ops taking 5-10 minutes. Connection config: `heartbeat=30`, `receive_timeout=540` (fits within 10-min `start_to_close_timeout`).- **WebSocket `_safe_send` Guard**: `server/routers/websocket.py` checks `websocket.client_state.name != "CONNECTED"` before sending and logs at `debug` level (not `error`) on failure. Prevents "ASGI message after websocket.close" errors when broadcasts race with disconnects.- **Claude Code CLI Flag**: `server/services/claude_code_service.py` uses `--max-budget-usd <amount>` (previously incorrectly `--max-cost`, which caused "unknown option" errors on every run).- **Persisted-prefix cache contract**: `PersistQueryClientProvider` hydrates entries with the QueryClient's *default* options, so any prefix in `PERSISTED_KEY_PREFIXES` (`client/src/lib/queryPersist.ts`) MUST also have a matching `queryClient.setQueryDefaults(['<prefix>'], { staleTime: FOREVER, gcTime: FOREVER })` declaration in `client/src/lib/queryClient.ts`. Per-call options don't apply on hydration. Canonical set: `nodeSpec`, `nodeGroups`, `skillContent`. `credentialValues` was previously persisted here but was removed per OWASP HTML5 Security Cheat Sheet / ASVS V9.9 — decrypted API keys must never live in `localStorage`. The in-memory TanStack Query cache (`gcTime: ∞`) keeps the credentials form populated for the session lifetime; on reload the panel refetches via WS. `credentialCatalogue` has its own `idb-keyval` warm-start path so it is intentionally not in either list.diff --git a/docs-internal/DESIGN.md b/docs-internal/DESIGN.mdindex 68785dfa..35c70d02 100644--- a/docs-internal/DESIGN.md+++ b/docs-internal/DESIGN.md@@ -76,7 +76,7 @@ When neither Temporal nor Redis is available, workflow execution falls back to a`rlm_agent` is the only agent node type that does not go through `handle_chat_agent`. It has a dedicated handler `handle_rlm_agent` that routes to `RLMService` in `services/rlm_service.py`.-The Recursive Language Model pattern replaces LangGraph's tool-calling loop with a Python REPL (`exec()`) where the agent writes code that can call:+The Recursive Language Model pattern replaces the standard tool-calling loop with a Python REPL (`exec()`) where the agent writes code that can call:- `llm_query(prompt)` - invoke the small model connected to `input-model`- `rlm_query(prompt)` - recursively invoke the agent itselfdiff --git a/docs-internal/TEMPORAL_ARCHITECTURE.md b/docs-internal/TEMPORAL_ARCHITECTURE.mdindex 7ed2eaf7..5ece843d 100644--- a/docs-internal/TEMPORAL_ARCHITECTURE.md+++ b/docs-internal/TEMPORAL_ARCHITECTURE.md@@ -8,9 +8,9 @@ Each workflow node executes as a **Temporal activity** with its own isolated con|---|---|---|| **Legacy single activity** (`execute_node_activity`) | Default | Every node routed through one dispatcher activity. WebSocket round-trip back to the FastAPI server. Stable since Wave 11. || **Per-type activity** (`node.{type}.v{version}`) | `TEMPORAL_PER_TYPE_DISPATCH=true` | Each plugin gets its own `@activity.defn`. Per-plugin retry / timeout / heartbeat configs apply. Worker pool can later specialise per `cls.task_queue` (browser / code-exec / ai-heavy / ...). Shipped in F4.A (commit `8261b05`). |-| **Agent-as-child-workflow** (`AgentWorkflow`) | `TEMPORAL_AGENT_WORKFLOW_ENABLED=true` | AI Agents (aiAgent, chatAgent, 12 specialized agents, 2 team leads) run as Temporal child workflows. Each LLM turn = activity; each tool call = per-type activity. Mirrors Temporal's AI Cookbook canonical pattern. F4.B infrastructure shipped (commit `a4d009e`); per-agent migrations follow. |+| **Agent-as-child-workflow** (`AgentWorkflow`) | `TEMPORAL_AGENT_WORKFLOW_ENABLED=true` | AI Agents (aiAgent, chatAgent, 11 specialized agents, 2 team leads) run as Temporal child workflows. Each LLM turn = activity; each tool call = per-type activity. Mirrors Temporal's AI Cookbook canonical pattern. F4.B infrastructure shipped (commit `a4d009e`); per-agent migrations follow. |-`deep_agent`, `rlm_agent`, `claude_code_agent` are intentionally excluded from AgentWorkflow — their externalised loops (deepagents package / RLM REPL / Claude CLI `--resume`) require single-process state continuity.+`rlm_agent`, `claude_code_agent` are intentionally excluded from AgentWorkflow — their externalised loops (RLM REPL / Claude CLI `--resume`) require single-process state continuity.## System Architecture@@ -187,7 +187,7 @@ async def _node_activity(context: Dict[str, Any]) -> Dict[str, Any]:**Heartbeat strategy (critical for long-running activities):**-The 2-minute `heartbeat_timeout` would kill DeepAgent or browser activities that routinely run 5-10 minutes. Both dispatch paths emit `activity.heartbeat()` at progress points — legacy on every non-matching WebSocket message, per-type at the start of each pipeline stage.+The 2-minute `heartbeat_timeout` would kill browser or claude_code_agent activities that routinely run 5-10 minutes. Both dispatch paths emit `activity.heartbeat()` at progress points — legacy on every non-matching WebSocket message, per-type at the start of each pipeline stage.In the legacy path the server broadcasts status updates, tool-glow events, and progress messages continuously during execution, so the WS-read-loop heartbeats keep the activity alive for as long as anything is happening. Start/end heartbeats alone are not enough — any operation longer than 2 minutes would trigger `TIMEOUT_TYPE_HEARTBEAT` and Temporal would retry (or fail) the activity.@@ -323,11 +323,11 @@ AgentWorkflow.run(context):`emit_phase(phase, status?)` is a thin helper that schedules `agent.broadcast_progress.v1`. The activity emits `WorkflowEvent.agent_progress` (CloudEvents v1.0, `type="com.machinaos.agent.progress"`) for FE consumers; when `status` is supplied it also drives a raw-dict `update_node_status` for the canvas-glow color (executing / success / error). Same dual-channel pattern F4.A's `_node_activity` uses.-Each LLM step is one activity, each tool call is one per-type activity (the same activities F4.A registered). Failures of tool activities surface as error messages back to the LLM (matching today's LangGraph behaviour); the agent loop continues.+Each LLM step is one activity, each tool call is one per-type activity (the same activities F4.A registered). Failures of tool activities surface as error messages back to the LLM (matching the in-process agent loop behaviour); the agent loop continues.**Broadcasts inside the loop** wrap `WorkflowEvent` (CloudEvents v1.0) per RFC §6.4: `agent_progress` events (`com.machinaos.agent.progress`) and `node_parameters_updated` events (`com.machinaos.node.parameters.updated`) flow through the `StatusBroadcaster.broadcast_agent_progress` and `StatusBroadcaster.broadcast_node_parameters_updated` wrappers respectively. The latter is reused by the legacy `routers/websocket.py:handle_save_node_parameters` (user-source) and `services/cli_agent/service.py:_persist_memory` (cli-source) — all three emission sites share the same envelope, distinguished by `source_hint` (`"user"` / `"cli"` / `"agent"`).-`deep_agent`, `rlm_agent`, `claude_code_agent` are NOT migrated — their internal session state (`deepagents` package / RLM REPL / Claude CLI `--resume` with stable `cwd`) requires single-process continuity and would break across activity boundaries.+`rlm_agent`, `claude_code_agent` are NOT migrated — their internal session state (RLM REPL / Claude CLI `--resume` with stable `cwd`) requires single-process continuity and would break across activity boundaries.References: [Temporal AI Cookbook](https://docs.temporal.io/ai-cookbook), [`temporal-community/temporal-ai-agent`](https://github.com/temporal-community/temporal-ai-agent), [`temporalio.contrib.openai_agents`](https://github.com/temporalio/sdk-python/tree/main/temporalio/contrib/openai_agents).diff --git a/docs-internal/agent_architecture.md b/docs-internal/agent_architecture.mdindex e08131cb..0da80d49 100644--- a/docs-internal/agent_architecture.md+++ b/docs-internal/agent_architecture.md@@ -1,6 +1,6 @@# AI Agent Architecture: Skill Injection & Tool Execution-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.+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 the plain-async agent loop.> **Related Documentation:**> - [Node Creation Guide](./node_creation.md) - Canonical plugin recipe (covers tool nodes, dual-purpose nodes, specialized agents)@@ -11,7 +11,7 @@ Detailed architecture reference for how AI Agent (`aiAgent`) and Chat Agent (`ch## Table of Contents1. [End-to-End Data Flow](#end-to-end-data-flow)-2. [LangGraph Agent Graph](#langgraph-agent-graph)+2. [Agent Loop](#agent-loop)3. [Skill Injection Pipeline](#skill-injection-pipeline)4. [Tool Building Pipeline](#tool-building-pipeline)5. [Tool Execution Flow](#tool-execution-flow)@@ -56,14 +56,13 @@ _collect_agent_connections() server/services/handlers/ai.pyAIService.execute_agent() server/services/ai.py1. Inject skills into system message2. Build LangChain StructuredTools from tool_data- 3. Construct LangGraph with agent + tools nodes- 4. Run graph with initial messages- 5. Save memory, return result+ 3. Call _run_agent_loop() (plain async while loop)+ 4. Save memory, return result|v-LangGraph StateGraph execution- agent node <-> tool node loop- LLM decides when to call tools+_run_agent_loop() execution+ invoke LLM -> if tool_calls: dispatch each via tool_executor -> loop+ Return on final response (no tool_calls) or max_iterations cap.|vResult broadcast via WebSocket@@ -78,123 +77,60 @@ Result broadcast via WebSocket| `server/services/workflow.py` | Facade, builds context, delegates to NodeExecutor || `server/services/node_executor.py` | Handler registry, dispatches via `functools.partial` || `server/services/handlers/ai.py` | `_collect_agent_connections()`, `handle_ai_agent()`, `handle_chat_agent()` |-| `server/services/ai.py` | `AIService` -- LangGraph construction, skill injection, tool building |+| `server/services/ai.py` | `AIService` -- `_run_agent_loop`, skill injection, tool building || `server/services/handlers/tools.py` | `execute_tool()` -- dispatch router for all tool types || `server/services/skill_loader.py` | `SkillLoader` -- filesystem/DB skill discovery and loading |----## LangGraph Agent Graph+## Agent Loop-### AgentState Schema+The agent loop is a plain `for iteration in range(max_iterations):` async function in `server/services/ai.py:_run_agent_loop`. No state machine, no graph DSL — each iteration:-Defined in `server/services/ai.py:386-402`:+1. Optional `progress_callback(iteration)` so consumers (UI iteration badge) get a per-turn tick.+2. `filter_empty_messages(messages)` strips empty `HumanMessage` content (Gemini / Claude reject them).+3. `response = await chat_model.ainvoke(filtered)` — single LLM call. The full assistant message is appended to `messages` verbatim so provider-specific metadata survives (Gemini `thought_signature`, Anthropic cache markers, OpenAI `reasoning_content`).+4. `extract_thinking_from_response(response)` — accumulates thinking across iterations with the `--- Iteration N ---` separator (multi-step reasoning).+5. If `response.tool_calls` is empty → return `{messages, iteration, thinking_content, truncated: False}`.+6. Otherwise dispatch each `tool_call` via the supplied `tool_executor`, wrap each result as a `ToolMessage`, append, and loop.-```python-class AgentState(TypedDict):- messages: Annotated[Sequence[BaseMessage], operator.add] # Accumulates via operator.add- tool_outputs: Dict[str, Any]- pending_tool_calls: List[Dict[str, Any]]- iteration: int- max_iterations: int- should_continue: bool- thinking_content: Optional[str] # Accumulated across iterations-```--Key design: `Annotated[..., operator.add]` on messages means new messages are **appended** to state, not replaced.--### Graph Topology--Built by `build_agent_graph()` in `server/services/ai.py:646-709`:+On hitting `max_iterations`, append a terminal `AIMessage` with a truncation note (same behaviour the old `GraphRecursionError` handler synthesised) and return `truncated: True`.-```-WITH TOOLS:- START --> agent --> should_continue() --> tools --> agent --> ... --> END- |- +--> END (no tool calls or max iterations)--WITHOUT TOOLS:- START --> agent --> END-```+### Signature```python-def build_agent_graph(chat_model, tools=None, tool_executor=None):- graph = StateGraph(AgentState)-- # Bind tools to model (makes LLM aware of tool schemas)- model_with_tools = chat_model- if tools:- model_with_tools = chat_model.bind_tools(tools)-- # Add nodes- graph.add_node("agent", create_agent_node(model_with_tools))- graph.set_entry_point("agent")-- if tools and tool_executor:- graph.add_node("tools", create_tool_node(tool_executor))- graph.add_conditional_edges("agent", should_continue, {"tools": "tools", "end": END})- graph.add_edge("tools", "agent") # Loop back-- return graph.compile()+async def _run_agent_loop(+ chat_model,+ initial_messages: List[BaseMessage],+ *,+ tools: Optional[List[Any]] = None,+ tool_executor: Optional[Callable] = None,+ max_iterations: int = 500,+ progress_callback: Optional[Callable[[int], Any]] = None,+) -> Dict[str, Any]:+ """Returns {messages, iteration, thinking_content, truncated}."""```-### Agent Node--`create_agent_node()` in `server/services/ai.py:509-584`:--1. Receives `state["messages"]` (accumulated conversation)-2. Filters empty messages (prevents API errors for Gemini/Claude)-3. Invokes LLM: `response = chat_model.invoke(filtered_messages)`-4. Extracts thinking content (Claude content_blocks, Gemini metadata, Groq additional_kwargs)-5. Checks `response.tool_calls` -- if present, sets `should_continue=True`-6. Returns updated state with `[response]` appended via `operator.add`--### Tool Node+Tools bind once at the top via `chat_model.bind_tools(tools)`; the same provider-unified LangChain method every chat model honours.-`create_tool_node()` in `server/services/ai.py:587-631`:+### Termination-```python-async def tool_node(state: AgentState) -> Dict[str, Any]:- tool_messages = []- for tool_call in state.get("pending_tool_calls", []):- tool_name = tool_call.get("name")- tool_args = tool_call.get("args", {})- tool_id = tool_call.get("id", "")-- try:- result = await tool_executor(tool_name, tool_args)- except Exception as e:- result = {"error": str(e)}-- tool_messages.append(ToolMessage(- content=json.dumps(result, default=str),- tool_call_id=tool_id,- name=tool_name- ))-- return {"messages": tool_messages, "pending_tool_calls": []}-```+| Trigger | What happens |+|---|---|+| LLM emits no `tool_calls` | Return with `truncated: False`. This is the normal exit. |+| `tool_executor` is `None` but LLM emits tool calls | WARN + return (treat as final). |+| `iteration` reaches `max_iterations` | Append synthetic terminal `AIMessage` + return with `truncated: True`. |-- Iterates all pending tool calls from the LLM-- Calls the `tool_executor` callback (closure built in `execute_agent()`)-- Wraps results as `ToolMessage` objects with matching `tool_call_id`-- Errors are caught and returned as `{"error": ...}` -- the LLM sees the error and can retry or respond+`max_iterations` defaults to 500 (sourced from `llm_defaults.json:agent.recursion_limit`). It's a backstop, not the load-bearing signal — compaction (token-based, post-turn) is the actual termination control.-### Routing Logic+### Where it's called-`should_continue()` in `server/services/ai.py:634-643`:+Two callsites in `server/services/ai.py`:-```python-def should_continue(state: AgentState) -> str:- if state.get("should_continue", False):- if state.get("iteration", 0) < state.get("max_iterations", 10):- return "tools"- return "end"-```+- `execute_agent` — for `aiAgent` plugins.+- `execute_chat_agent` — for `chatAgent` + all specialized agents + team leads.-Routes to `"tools"` when:-- LLM returned tool calls (`should_continue=True`)-- AND iteration count < `max_iterations` (default 10)+Both build `initial_messages` (system + memory history + current prompt + skill injection), build tools via `_build_tool_from_node`, then call `_run_agent_loop` and extract the final assistant message + accumulated thinking + iteration count from the returned dict.---@@ -358,7 +294,7 @@ This text is appended to the system message. The full SKILL.md body (instruction## Tool Building Pipeline-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.+Tool building + dispatch lives in [tool_building_pipeline.md](./tool_building_pipeline.md). The five stages (DISCOVER edges → BUILD StructuredTool → BIND via `chat_model.bind_tools` → 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.Patterns covered in the canonical doc:@@ -375,7 +311,7 @@ Patterns covered in the canonical doc:## Memory Integration-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).+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 `_run_agent_loop`, 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 / rlm_agent / claude_code_agent native session resume bridge).---@@ -385,14 +321,14 @@ Both methods live in `server/services/ai.py` and follow the same general pattern| Aspect | `execute_agent()` | `execute_chat_agent()` ||--------|-------------------|----------------------|-| **Graph construction** | Always builds full LangGraph StateGraph | Conditional: LangGraph if tools, simple `ainvoke()` if no tools |-| **Tool failure** | Re-raises exceptions (LangGraph handles) | Returns `{"error": str(e)}` (softer handling) |-| **No-tool path** | N/A -- always uses graph | `response = await chat_model.ainvoke(messages)` (no graph overhead) |+| **Loop call** | Always calls `_run_agent_loop` (even with zero tools — single-turn happy path returns immediately) | Conditional: calls `_run_agent_loop` if tools, simple `await chat_model.ainvoke(messages)` if no tools |+| **Tool failure** | Re-raises exceptions (the loop wraps them as `{"error": ...}` ToolMessages on retry) | Returns `{"error": str(e)}` (softer handling) |+| **No-tool path** | N/A -- always uses the loop | `response = await chat_model.ainvoke(messages)` (skips loop overhead) || **Result metadata** | `agent_type: "agent"` | `agent_type: "chat" / "chat_with_skills" / "chat_with_tools" / "chat_with_skills_and_tools"` |### Specialized Agent Routing-There are **15 specialized agents**. Most route to `handle_chat_agent`; `rlm_agent` and `claude_code_agent` have dedicated handlers:+There are **11 specialized agents** plus 2 team leads. Most route to `handle_chat_agent`; `rlm_agent` and `claude_code_agent` have dedicated handlers:```python# server/services/node_executor.py@@ -403,11 +339,11 @@ SPECIALIZED_AGENT_TYPES = {# rlm_agent and claude_code_agent are handled by dedicated handlers, not handle_chat_agent}-# Most specialized agents map to handle_chat_agent+# Most specialized agents map to handle_chat_agent (uses _run_agent_loop)for agent_type in SPECIALIZED_AGENT_TYPES:registry[agent_type] = partial(handle_chat_agent, ai_service=self.ai_service, database=self.database)-# Dedicated handlers for agents that do not use LangGraph tool-calling+# Dedicated handlers for agents with externalised session stateregistry['rlm_agent'] = partial(handle_rlm_agent, ai_service=self.ai_service, database=self.database)registry['claude_code_agent'] = partial(handle_claude_code_agent, ...)```@@ -419,7 +355,7 @@ Two settings flags route agent execution through different Temporal paths (see [| Flag | Off (default) | On ||---|---|---|| `TEMPORAL_PER_TYPE_DISPATCH` | Every node routes through the legacy `execute_node_activity` single dispatcher (WS round-trip to the FastAPI handler). | Each node routes through its per-type activity `node.{type}.v{version}` registered via `BaseNode.as_activity()`. Per-plugin retry / timeout / heartbeat configs apply. |-| `TEMPORAL_AGENT_WORKFLOW_ENABLED` | All 15 specialized + 2 base agents (`aiAgent` / `chatAgent`) run inside `execute_node_activity` (LangGraph loop in-activity). | The 15 migrating agent types become Temporal **child workflows** (`AgentWorkflow`). LLM steps + tool calls become activities; `agent.prepare_payload.v1` resolves the DB-backed payload as the workflow's first step. `deep_agent` / `rlm_agent` / `claude_code_agent` stay on the F4.A per-type activity path (externalised session state). |+| `TEMPORAL_AGENT_WORKFLOW_ENABLED` | All 11 specialized + 2 team leads + 2 base agents (`aiAgent` / `chatAgent`) run inside `execute_node_activity` (`_run_agent_loop` in-activity). | The 14 migrating agent types become Temporal **child workflows** (`AgentWorkflow`). LLM steps + tool calls become activities; `agent.prepare_payload.v1` resolves the DB-backed payload as the workflow's first step. `rlm_agent` / `claude_code_agent` stay on the F4.A per-type activity path (externalised session state). |Today both flags default to `false`; the wiring is shipped (F4.A at `8261b05`, F4.B infrastructure at `a4d009e`, per-agent dispatch at `0459131`) but production rollout awaits canary verification on a Temporal dev cluster.@@ -427,7 +363,7 @@ Today both flags default to `false`; the wiring is shipped (F4.A at `8261b05`, F### RLM Agent Pattern-`rlm_agent` replaces LangGraph tool-calling with a Python REPL executing LM calls recursively. Instead of paying one network round-trip per tool call, the RLM agent writes a code block that orchestrates many model invocations at once:+`rlm_agent` replaces the standard tool-calling loop with a Python REPL executing LM calls recursively. Instead of paying one network round-trip per tool call, the RLM agent writes a code block that orchestrates many model invocations at once:```python# The LLM generates code like this, executed by RLMService@@ -453,17 +389,22 @@ registry['rlm_agent'] = partial(handle_rlm_agent, ai_service=self.ai_service, da`handle_rlm_agent` delegates to `RLMService` in `server/services/rlm_service.py`. See [rlm_service.md](rlm_service.md) for full details.-### Chat Agent Conditional Graph+### Chat Agent Conditional Loop```python# In execute_chat_agent():if all_tools:- # Full LangGraph with tool execution loop- agent_graph = build_agent_graph(chat_model, tools=all_tools, tool_executor=executor)- final_state = await agent_graph.ainvoke(initial_state)+ # Run the agent loop with bound tools+ final_state = await _run_agent_loop(+ chat_model, messages,+ tools=all_tools,+ tool_executor=chat_tool_executor,+ max_iterations=recursion_limit,+ progress_callback=_emit_progress if broadcaster else None,+ )else:- # Simple invoke -- no graph, no tool overhead+ # Simple invoke -- no loop overheadresponse = await chat_model.ainvoke(messages)```-This optimization means tool-less Chat Agent conversations skip LangGraph entirely for faster response times.+This optimisation means tool-less Chat Agent conversations skip `_run_agent_loop` entirely for faster response times.diff --git a/docs-internal/agent_delegation.md b/docs-internal/agent_delegation.mdindex 21dc6f78..bbb7072a 100644--- a/docs-internal/agent_delegation.md+++ b/docs-internal/agent_delegation.md@@ -233,7 +233,7 @@ return {```Inside `run_child_agent()` (line 1208-1267), the child handler is selected based on node_type:-- `aiAgent` -> `handle_ai_agent()` (LangGraph state machine)+- `aiAgent` -> `handle_ai_agent()` (agent loop with tools)- All others -> `handle_chat_agent()` (direct LLM invoke)---diff --git a/docs-internal/agent_teams.md b/docs-internal/agent_teams.mdindex 47ab38b9..942a4918 100644--- a/docs-internal/agent_teams.md+++ b/docs-internal/agent_teams.md@@ -217,7 +217,7 @@ Connect Team Monitor to a team lead's output to visualize team activity.1. **AI-Driven Delegation**: The team lead's AI decides when to delegate, not automatic forwarding to all teammates-2. **Tool-Based Pattern**: Teammates become `delegate_to_*` tools, leveraging existing LangGraph tool calling+2. **Tool-Based Pattern**: Teammates become `delegate_to_*` tools, leveraging the existing agent-loop tool calling3. **Fire-and-Forget**: Delegated agents run as background tasks; team lead can check status via `check_delegated_tasks`diff --git a/docs-internal/deep_agent.md b/docs-internal/deep_agent.mddeleted file mode 100644index 9c4261d7..00000000--- a/docs-internal/deep_agent.md+++ /dev/null@@ -1,372 +0,0 @@-# Deep Agent: LangChain DeepAgents Integration--Specialized agent node powered by [LangChain DeepAgents](https://github.com/langchain-ai/deepagents) -- a batteries-included agent harness with built-in filesystem tools, sub-agent delegation, auto-summarization, and todo planning.--> **Related Documentation:**-> - [Agent Architecture](./agent_architecture.md) - LangGraph skill injection and tool execution-> - [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--1. [Overview](#overview)-2. [Architecture](#architecture)-3. [DeepAgents Package](#deepagents-package)-4. [MachinaOs Integration](#machinaos-integration)-5. [Tool Execution](#tool-execution)-6. [Memory Integration](#memory-integration)-7. [Node Definition](#node-definition)-8. [Key Files](#key-files)-9. [Comparison with Other Agent Types](#comparison-with-other-agent-types)-------## Overview--Deep Agent uses `langchain.agents.create_agent()` (the lower-level function from the `deepagents` package) to create a LangGraph agent that uses **only MachinaOs connected tool nodes** -- no built-in middleware tools. This ensures all tool executions show glow effects on the canvas.--**How it differs from chatAgent:**-- Uses `langchain.agents.create_agent()` instead of `build_agent_graph()` for graph creation-- Supports `PatchToolCallsMiddleware` for tool call formatting-- 4 dedicated filesystem/shell tool nodes (fileRead, fileModify, shell, fsSearch) delegate to `deepagents.backends.LocalShellBackend`--**What MachinaOs provides:**-- Provider/model selection from `llm_defaults.json` (9 providers)-- Executable tool node connections with glow effects (fileRead, fileModify, shell, fsSearch, calculator, search, WhatsApp, Android, etc.)-- Skill injection from Master Skill / SKILL.md files-- Memory via Simple Memory node (markdown + vector store)-- Teammate delegation via `input-teammates` handle-- Real-time status broadcasting via WebSocket-------## Architecture--```-User clicks "Run" on Deep Agent- |- v-NodeExecutor._dispatch() server/services/node_executor.py- Registry: 'deep_agent' -> handle_deep_agent (via partial)- |- v-handle_deep_agent() server/services/handlers/deep_agent.py- 1. _collect_agent_connections() [REUSE from handlers/ai.py]- - input-memory -> memory_data- - input-skill -> skill_data[]- - input-tools -> tool_data[]- - input-main -> input_data- - input-task -> task_data- 2. _format_task_context() [REUSE from handlers/ai.py]- 3. Auto-prompt fallback [same pattern as handle_rlm_agent]- 4. _collect_teammate_connections() [REUSE from handlers/ai.py]- 5. Passes raw tool_data + build_tool_fn to service- |- v-DeepAgentService.execute() server/services/agents/service.py- Orchestration only -- delegates to adapters and shared helpers:- - _build_skill_system_prompt() [ai.py] -> system_message- - is_model_valid_for_provider() [ai.py] -> model validation- - self._create_model() [ai.py] -> pre-built BaseChatModel- - ToolAdapter.build_tools() [agents/adapters.py] -> executable tools- - SubAgentAdapter.convert() [agents/adapters.py] -> deepagents SubAgent dicts- - _parse_memory_markdown() [ai.py] -> memory load- - langchain.agents.create_agent() [langchain] -> graph creation- - agent.ainvoke() -> graph execution- - ResponseExtractor.extract() [agents/adapters.py] -> response + thinking- - _append_to_memory_markdown() [ai.py] -> memory save- |- v-langchain.agents.create_agent() langchain package (lower-level)- model = pre-built BaseChatModel (API key baked in)- tools = ONLY MachinaOs connected tools (with glow effects via ToolAdapter)- system_prompt = system_message (includes skills + long-term memory context)- middleware = [PatchToolCallsMiddleware()] only (no built-in filesystem/todo)- |- v-agent.ainvoke(messages) LangGraph CompiledStateGraph- messages = history from SimpleMemory + current prompt- No built-in middleware tools -- uses only connected MachinaOs tool nodes- |- v-ResponseExtractor.extract() -> save memory -> return result-```-------## DeepAgents Package--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.--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--| Tool | Middleware | Description |-|------|-----------|-------------|-| `write_todos` | TodoListMiddleware | Task breakdown and progress tracking |-| `read_file` | FilesystemMiddleware | Read file contents with offset/limit |-| `write_file` | FilesystemMiddleware | Write/create files |-| `edit_file` | FilesystemMiddleware | Edit files with string replacement |-| `ls` | FilesystemMiddleware | List directory contents |-| `glob` | FilesystemMiddleware | Glob pattern file matching |-| `grep` | FilesystemMiddleware | Search file contents with regex |-| `execute` | FilesystemMiddleware | Run shell commands (requires SandboxBackendProtocol) |-| `task` | SubAgentMiddleware | Delegate work to sub-agents with isolated context |--### Middleware Stack (default order)--1. **TodoListMiddleware** -- Planning tool (`write_todos`)-2. **SkillsMiddleware** (conditional) -- Load skills from file paths-3. **FilesystemMiddleware** -- File operations + shell execution-4. **SubAgentMiddleware** -- Sub-agent spawning via `task` tool-5. **SummarizationMiddleware** -- Auto-summarization when conversations grow long-6. **PatchToolCallsMiddleware** -- Tool call patching-7. **AnthropicPromptCachingMiddleware** -- Prompt caching (Anthropic models only)-8. **MemoryMiddleware** (conditional) -- Persistent memory from AGENTS.md files--Custom tools passed via `tools=` parameter are added alongside (not replacing) the built-in tools. deepagents uses LangGraph's `ToolNode` which calls `tool.ainvoke()` directly -- tools must have real executor functions.--### Backends--Backends control where filesystem tools operate. MachinaOs uses `FilesystemBackend` with `virtual_mode=True` pointed at a per-workflow workspace directory.--| Backend | Description |-|---------|-------------|-| `StateBackend` | Default. Ephemeral files in LangGraph state (in-memory) |-| `FilesystemBackend` | Direct local filesystem under `root_dir`. `virtual_mode=True` sandboxes paths |-| `LocalShellBackend` | Extends FilesystemBackend with `execute` tool (unrestricted shell) |-| `StoreBackend` | Persistent cross-thread storage via LangGraph BaseStore |-| `CompositeBackend` | Route paths to different backends by prefix |--**MachinaOs configuration** (in `services/agents/service.py`):-```python-from deepagents.backends import FilesystemBackend--workspace_dir = parameters.get('workspace_dir') # From execution context-backend = FilesystemBackend(root_dir=workspace_dir, virtual_mode=True)--agent = create_deep_agent(- model=chat_model,- backend=backend,- ...-)-```--The workspace directory is created per workflow at `data/workspaces/<workflow_id>/`. Nodes (fileDownloader, code executors) save output files there, and the Deep Agent's filesystem tools operate within it. `virtual_mode=True` prevents path traversal outside the workspace.--### Sub-Agent Types--| Type | Description |-|------|-------------|-| `SubAgent` | Declarative spec: name, description, system_prompt, optional tools/model |-| `CompiledSubAgent` | Pre-built runnable (any LangGraph/LangChain Runnable) |-| `AsyncSubAgent` | Remote/background agent via graph_id + url |-------## MachinaOs Integration--### Execution Path--Deep Agent has a **dedicated handler and modular service package** following the RLMService pattern:--- **Handler** (`handlers/deep_agent.py`): Thin wrapper that collects connections, passes raw `tool_data` to service-- **Service package** (`services/agents/`): Modular execution engine split into:- - `service.py` -- Orchestration: calls adapters and shared helpers- - `adapters.py` -- Protocol translation: `ToolAdapter`, `SubAgentAdapter`, `ResponseExtractor`- - `constants.py` -- Provider mappings and defaults-- **Composition**: `AIService.__init__` creates `self.deep_agent_service = DeepAgentService(auth=self.auth, model_factory=self.create_model)`--```-server/services/agents/ (mirrors services/rlm/)- __init__.py - Public API: exports DeepAgentService- service.py - Orchestration only- adapters.py - ToolAdapter, SubAgentAdapter, ResponseExtractor- constants.py - PROVIDER_PREFIX, DEFAULT_MAX_TURNS-```--### Reused Helpers (from ai.py)--| Helper | Used For |-|--------|----------|-| `_build_skill_system_prompt()` | Skill injection into system_message |-| `_build_tool_from_node()` | Schema-only tool stubs from tool_data |-| `is_model_valid_for_provider()` | Model validation against provider |-| `get_default_model_async()` | Default model from llm_defaults.json |-| `_resolve_max_tokens()` | Max tokens from model registry |-| `_resolve_temperature()` | Temperature clamped to provider range |-| `self.create_model()` | Pre-built BaseChatModel with API key |-| `_parse_memory_markdown()` | Parse SimpleMemory markdown to messages |-| `_get_memory_vector_store()` | Long-term vector store retrieval |-| `_append_to_memory_markdown()` | Append exchange to memory |-| `_trim_markdown_window()` | Trim + archive removed messages |-| `extract_thinking_from_response()` | Extract thinking/reasoning content |-| `log_execution_time()`, `log_api_call()` | Metrics tracking |-------## Tool Execution--### Problem-`_build_tool_from_node()` returns schema-only stubs with `placeholder_func` that echo kwargs back. deepagents' `ToolNode` calls `tool.ainvoke()` directly, so these stubs fail silently.--### Solution-`ToolAdapter` (in `agents/adapters.py`) wraps each schema-only stub with a real async coroutine:--```python-# agents/adapters.py - ToolAdapter._wrap()-async def _execute(**kwargs):- from services.handlers.tools import execute_tool- result = await execute_tool(tool_name, kwargs, config)- return result--return StructuredTool.from_function(- coroutine=_execute,- args_schema=tool.get_input_schema(),-)-```--This follows the deepagents pattern: `StructuredTool.from_function(coroutine=async_fn, args_schema=...)`.--The handler passes raw `tool_data` to the service, which calls `ToolAdapter.build_tools()` to build executable tools. Connected MachinaOs tools (calculator, search, WhatsApp, etc.) execute via `handlers/tools.py execute_tool()`, with real-time glow effects broadcast to tool nodes.-------## Memory Integration--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.-------## Node Definition--### Properties--Inherits all `AI_AGENT_PROPERTIES` via spread:-- **AI Provider** (options: openai, anthropic, gemini, openrouter)-- **Model** (dynamic options based on provider)-- **Prompt** (string, multiline)-- **System Message** (string, multiline)-- **Options** (collection: temperature, maxTokens, thinkingEnabled, thinkingBudget, reasoningEffort)--Plus one additional property:-- **Max Turns** (number, default: 25, range: 1-100) -- Maximum agentic loop iterations--### Input Handles--| Handle | Position | Description |-|--------|----------|-------------|-| `input-main` | Left 30% | Primary input (auto-prompt fallback) |-| `input-memory` | Left 65% | Simple Memory node for conversation history |-| `input-task` | Left 85% | Task completion events from taskTrigger |-| `input-skill` | Bottom 20% | Skill nodes (Master Skill) |-| `input-teammates` | Bottom 50% | Agents for sub-agent delegation |-| `input-tools` | Bottom 80% | Tool nodes for LLM tool calling |--### Output Handle--| Handle | Position | Description |-|--------|----------|-------------|-| `output-top` | Top | Agent output |--### Visual Config--- **Icon:** Brain (U+1F9E0)-- **Theme color:** `dracula.green`-- **Dimensions:** 300x200px-- **Component:** `AIAgentNode` (shared with all specialized agents)--### Output Schema--Matches `execute_chat_agent` format for frontend compatibility:-```python-{- "response": str, # AI text response- "thinking": str | None, # Extracted thinking/reasoning- "thinking_enabled": bool,- "model": str, "provider": str,- "agent_type": str, # "deep_agent", "deep_agent_with_tools", etc.- "iterations": int, # Tool-call loop count- "messages_count": int,- "finish_reason": "stop",- "timestamp": str,- "input": {"prompt": str, "system_message": str},- "memory": {"session_id": str, "history_loaded": int}, # if connected- "skills": {"connected": [str], "count": int}, # if connected- "tools": {"connected": [str], "count": int}, # if connected-}-```-------## Key Files--### Service Package (`server/services/agents/`)-| File | Description |-|------|-------------|-| `server/services/agents/__init__.py` | Public API: exports `DeepAgentService` |-| `server/services/agents/service.py` | Orchestration: calls adapters, shared helpers, `langchain.agents.create_agent()` |-| `server/services/agents/adapters.py` | `ToolAdapter`, `SubAgentAdapter`, `ResponseExtractor` |-| `server/services/agents/constants.py` | `PROVIDER_PREFIX`, `DEFAULT_MAX_TURNS` |--### Handler and Wiring-| File | Description |-|------|-------------|-| `server/services/handlers/deep_agent.py` | Thin handler: collects connections, passes raw tool_data |-| `server/services/handlers/__init__.py` | Import/export `handle_deep_agent` |-| `server/services/ai.py` | AIService.__init__ composes `self.deep_agent_service` |-| `server/services/node_executor.py` | Handler registry entry |-| `server/services/handlers/tools.py` | Delegation tuple |-| `server/constants.py` | `AI_AGENT_TYPES` |--### Frontend-| File | Description |-|------|-------------|-| `client/src/components/AIAgentNode.tsx` | `AGENT_CONFIGS` visual entry |-| `client/src/components/parameterPanel/MiddleSection.tsx` | `AGENT_WITH_SKILLS_TYPES` |-| `client/src/components/parameterPanel/InputSection.tsx` | `AGENT_WITH_SKILLS_TYPES` + `aiAgentTypes` |-| `client/src/contexts/WebSocketContext.tsx` | `LONG_RUNNING_NODE_TYPES` |--### Dependencies-| File | Description |-|------|-------------|-| `server/requirements.txt` | `deepagents>=0.4.12` |-| `server/pyproject.toml` | `deepagents>=0.4.12` |-------## Filesystem & Shell Tool Nodes--MachinaOs provides 4 dual-purpose tool nodes that delegate to `deepagents.backends.LocalShellBackend`:--| Node | Tool Name | Description |-|------|-----------|-------------|-| `fileRead` | `file_read` | Read file contents with pagination |-| `fileModify` | `file_modify` | Write new files or edit existing files (string replacement) |-| `shell` | `shell_execute` | Execute shell commands with timeout |-| `fsSearch` | `fs_search` | List directories, glob pattern match, or grep file contents |--These work as standalone workflow nodes AND as AI agent tools when connected to any agent's `input-tools` handle. Defined as backend plugins under `server/nodes/filesystem/*.py`.-------## Comparison with Other Agent Types--| Aspect | chatAgent | deep_agent | claude_code_agent | rlm_agent |-|--------|-----------|------------|-------------------|-----------|-| **Handler** | `handle_chat_agent` | `handle_deep_agent` | `handle_claude_code_agent` | `handle_rlm_agent` |-| **Service** | `AIService.execute_chat_agent()` | `DeepAgentService.execute()` | `ClaudeCodeService.execute()` | `RLMService.execute()` |-| **Graph creation** | `build_agent_graph()` | `langchain.agents.create_agent()` | Claude Code CLI | RLM REPL loop |-| **Built-in tools** | None | None (uses only connected nodes) | 6 (Read, Edit, Bash, etc.) | 3 (llm_query, rlm_query, FINAL) |-| **Connected tools** | Yes | Yes (executable, with glow) | No | Yes (bridged) |-| **Skills** | Yes | Yes | Yes (prompt only) | Yes |-| **Memory** | Yes (markdown + vector) | Yes (markdown + vector) | No | Yes (context only) |-| **Teammates** | Team leads only | Yes | No | No |-| **Providers** | All 9 | All 9 | Anthropic only | All 9 |-| **Middleware** | None | PatchToolCallsMiddleware only | None | None |-| **Auto-summarization** | No | No | No | No |-| **Planning** | No | No | No | No |-| **Tool glow effects** | Yes | Yes | No | No |diff --git a/docs-internal/memory_compaction.md b/docs-internal/memory_compaction.mdindex 72fcab6b..357e038d 100644--- a/docs-internal/memory_compaction.md+++ b/docs-internal/memory_compaction.md@@ -138,7 +138,7 @@ class TokenUsageMetric(SQLModel, table=True):cache_read_tokens: int = 0 # Anthropic cache hitreasoning_tokens: int = 0 # OpenAI o-series reasoning- iteration: int = 1 # LangGraph iteration number+ iteration: int = 1 # Agent loop iteration numberexecution_id: Optional[str] # Workflow execution IDcreated_at: Optional[datetime]```@@ -392,7 +392,7 @@ usage = response.usage_metadata# 'output_token_details': {'reasoning': 256}# }-# Aggregate across LangGraph iterations+# Aggregate across agent-loop iterationstotal_usage = Nonefor msg in final_state["messages"]:if hasattr(msg, 'usage_metadata') and msg.usage_metadata:@@ -404,7 +404,7 @@ for msg in final_state["messages"]:In `server/services/ai.py`, after agent execution:```python-# After LangGraph execution, before memory save+# After agent-loop execution, before memory saveif memory_data and memory_data.get('session_id'):from services.compaction import get_compaction_servicesvc = get_compaction_service()diff --git a/docs-internal/memory_lifecycle.md b/docs-internal/memory_lifecycle.mdindex ba3f0813..3492703b 100644--- a/docs-internal/memory_lifecycle.md+++ b/docs-internal/memory_lifecycle.md@@ -1,18 +1,18 @@# 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`.+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`, `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+> - [agent_architecture.md](./agent_architecture.md) — 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+> - [rlm_service.md](./rlm_service.md) — `rlm_agent` engine-specific adapter## 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 |+| **Markdown transcript** | [`services/memory/markdown.py`](../server/services/memory/markdown.py) | aiAgent, chatAgent, 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.@@ -126,7 +126,7 @@ Turn N starts→ prepend retrieved long-term context as a system message│▼-4. LangGraph agent loop runs (ainvoke + tool calls)+4. Agent loop runs (_run_agent_loop: ainvoke + tool calls)│▼5. _track_token_usage(...) — see memory_compaction.md@@ -154,7 +154,6 @@ F4.B `AgentWorkflow` runs steps 4-9 as separate Temporal activities (`prepare_pa| 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 |diff --git a/docs-internal/native_llm_sdk.md b/docs-internal/native_llm_sdk.mdindex 848bd5e4..dfd3badd 100644--- a/docs-internal/native_llm_sdk.md+++ b/docs-internal/native_llm_sdk.md@@ -3,7 +3,7 @@> **⚠️ 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.-MachinaOS uses a hybrid LLM architecture: a native SDK layer in `server/services/llm/` for direct chat completions and model fetching, and a LangChain + LangGraph path in `server/services/ai.py` for agent tool-calling. This document describes the native layer, its design, and how both paths coexist.+MachinaOS uses a hybrid LLM architecture: a native SDK layer in `server/services/llm/` for direct chat completions and model fetching, and a LangChain-backed agent loop in `server/services/ai.py` (the plain `_run_agent_loop` async function) for agent tool-calling. This document describes the native layer, its design, and how both paths coexist.## Why a Native Layer@@ -188,8 +188,8 @@ No new provider class, no new import. The factory's fallback branch picks up `ba```execute_chat(parameters, node_id, node_type) -> native SDK where possible-execute_agent(parameters, node_id) -> LangChain + LangGraph-execute_chat_agent(parameters, node_id) -> LangChain + LangGraph+execute_agent(parameters, node_id) -> LangChain chat model + _run_agent_loop+execute_chat_agent(parameters, node_id) -> LangChain chat model + _run_agent_loop```**`execute_chat()` routing:**@@ -207,7 +207,7 @@ is_native_provider(provider)?**`execute_agent()` and `execute_chat_agent()` routing:**-All providers go through `create_model()` which returns a LangChain `ChatOpenAI` / `ChatAnthropic` / `ChatGoogleGenerativeAI` / `ChatGroq` / `ChatCerebras` instance. The agent then builds a LangGraph `StateGraph` with `bind_tools()` for tool calling. This path is used because LangGraph's agent loop, checkpointer, and tool-execution callback layer do not have a native-layer equivalent today.+All providers go through `create_model()` which returns a LangChain `ChatOpenAI` / `ChatAnthropic` / `ChatGoogleGenerativeAI` / `ChatGroq` / `ChatCerebras` instance. The agent then calls `chat_model.bind_tools(tools)` and runs `_run_agent_loop` (plain async while loop, ~140 LOC). LangChain's chat-model classes are used because they unify `bind_tools` + `usage_metadata` + `content_blocks` extraction across all providers; the native-SDK layer doesn't yet have provider-unified tool binding.OpenAI-compatible providers like DeepSeek/Kimi/Mistral still use `ChatOpenAI` with `base_url` from `llm_defaults.json` in the agent path, and pass `max_tokens` via `extra_body` to bypass LangChain's `max_completion_tokens` conversion.diff --git a/docs-internal/node-logic-flows/README.md b/docs-internal/node-logic-flows/README.mdindex f9814879..be3cac92 100644--- a/docs-internal/node-logic-flows/README.md+++ b/docs-internal/node-logic-flows/README.md@@ -100,7 +100,6 @@ match its doc here, and each doc must still describe what the code does.- [Claude Code Agent (`claude_code_agent`)](./specialized_agents/claudeCodeAgent.md)- [Coding Agent (`coding_agent`)](./specialized_agents/codingAgent.md)- [Consumer Agent (`consumer_agent`)](./specialized_agents/consumerAgent.md)-- [Deep Agent (`deep_agent`)](./specialized_agents/deepAgent.md)- [Orchestrator Agent (`orchestrator_agent`)](./specialized_agents/orchestratorAgent.md)- [Payments Agent (`payments_agent`)](./specialized_agents/paymentsAgent.md)- [Productivity Agent (`productivity_agent`)](./specialized_agents/productivityAgent.md)diff --git a/docs-internal/node-logic-flows/ai_agents/aiAgent.md b/docs-internal/node-logic-flows/ai_agents/aiAgent.mdindex 1be5df8f..4e912f5b 100644--- a/docs-internal/node-logic-flows/ai_agents/aiAgent.md+++ b/docs-internal/node-logic-flows/ai_agents/aiAgent.md@@ -10,10 +10,10 @@## Purpose-`aiAgent` is the general-purpose LangGraph-backed agent node. It reads a prompt+`aiAgent` is the general-purpose tool-calling agent node. It reads a promptand system message, optionally merges conversation history from a connected`simpleMemory`, loads instructions from connected skill nodes, binds tool nodes-as LangGraph tools, and runs the tool-calling loop until the LLM produces a+via `chat_model.bind_tools`, and runs the tool-calling loop until the LLM produces afinal answer. All of the heavy lifting (LLM invocation, tool execution, memorypersistence) lives in `AIService.execute_agent`; the handler's job is purelyto gather the connected-node payloads via `_collect_agent_connections` and@@ -141,7 +141,7 @@ flowchart TD(`<provider>_proxy` API key) for Ollama-style local routing.- **Services**: `AIService`, `Database`, `StatusBroadcaster`, `CompactionService`,`PricingService`, `SkillLoader` (for `masterSkill` expansion).-- **Python packages**: `langchain-core`, `langgraph`, `langchain-openai`,+- **Python packages**: `langchain-core`, `langchain-openai`,`langchain-anthropic`, provider SDKs (`anthropic`, `openai`, `google-genai`).- **Environment variables**: none read directly by the handler.diff --git a/docs-internal/node-logic-flows/ai_agents/chatAgent.md b/docs-internal/node-logic-flows/ai_agents/chatAgent.mdindex 793f0832..73157d65 100644--- a/docs-internal/node-logic-flows/ai_agents/chatAgent.md+++ b/docs-internal/node-logic-flows/ai_agents/chatAgent.md@@ -29,7 +29,7 @@ the node registry wires all of those to `handle_chat_agent` via| `input-main` | main | no | Upstream data. Auto-prompt fallback when `prompt` is empty. || `input-skill` | main | no | Skill nodes (including `masterSkill` aggregation). || `input-memory` | main | no | `simpleMemory` node for conversation history. |-| `input-tools` | main | no | Tool nodes bound to the LLM via LangGraph. |+| `input-tools` | main | no | Tool nodes bound to the LLM via `chat_model.bind_tools`. || `input-task` | main | no | `taskTrigger` output - formatted and prepended to the prompt. || `input-teammates` | main | no | **Team-lead only** (`orchestrator_agent`, `ai_employee`). Agents on this handle become `delegate_to_<name>` tools. |@@ -125,9 +125,8 @@ flowchart TD- **Empty `teammates` on a team-lead is benign** - the handler simply runswithout delegation tools, so an `orchestrator_agent` with nothing wired to`input-teammates` behaves exactly like `chatAgent`.-- **`rlm_agent` and `deep_agent` do NOT route here** - they have dedicated- handlers (`handle_rlm_agent`, `handle_deep_agent`). All other specialized- agents do.+- **`rlm_agent` and `claude_code_agent` do NOT route here** - they have dedicated+ handlers. All other specialized agents do.## Relateddiff --git a/docs-internal/node-logic-flows/ai_chat_models/kimiChatModel.md b/docs-internal/node-logic-flows/ai_chat_models/kimiChatModel.mdindex db2efbb7..d46ecbde 100644--- a/docs-internal/node-logic-flows/ai_chat_models/kimiChatModel.md+++ b/docs-internal/node-logic-flows/ai_chat_models/kimiChatModel.md@@ -28,7 +28,7 @@ Kimi K2 models by Moonshot AI (`kimi-k2.5`, `kimi-k2-thinking`). 256K context, 9| `model` | string | injected | no | - | `kimi-k2.5` (instant) or `kimi-k2-thinking` || `temperature` | number | **fixed** | no | - | Fixed at 0.6 (instant) or 1.0 (thinking). Input is ignored. || `maxTokens` | number | up to 96K | no | - | |-| `thinkingEnabled` | boolean | true for k2.5 | no | - | ON by default for k2.5; explicitly disabled for LangGraph agents |+| `thinkingEnabled` | boolean | true for k2.5 | no | - | ON by default for k2.5; explicitly disabled for tool-calling agents || `apiKey` | string | injected | no | - | `auth_service.get_api_key('kimi', 'default')` |## Outputs (handles)@@ -74,7 +74,7 @@ flowchart TD- **Validation**: missing api_key / empty prompt -> error envelope.- **Provider routing**: `detect_ai_provider` matches `'kimi' in node_type.lower()`. Ordering guarantees it lands in the kimi lane before groq / openrouter / anthropic / gemini.- **Fixed temperature**: `native_resolve_temperature` ignores user input for Kimi and forces 0.6 (instant) or 1.0 (thinking).-- **Thinking default-on for k2.5**: if user leaves `thinkingEnabled` unset, k2.5 still thinks. To disable, must pass `thinkingEnabled=false`. This is done explicitly for the LangGraph agent integration (where thinking streams break tool-call parsing).+- **Thinking default-on for k2.5**: if user leaves `thinkingEnabled` unset, k2.5 still thinks. To disable, must pass `thinkingEnabled=false`. This is done explicitly for the tool-calling agent integration (where thinking streams break tool-call parsing).- **Native path**: uses the OpenAI SDK with Moonshot base_url from `llm_defaults.json`.## Side Effects@@ -96,7 +96,7 @@ flowchart TD- **Temperature is non-configurable**: any user-supplied `temperature` is overridden. Documented in the prompt help text but easy to miss.- **Thinking default is ON** for k2.5: contrast with every other chat model, which defaults thinking OFF.-- **Agent compatibility quirk**: when Kimi is used as the LangGraph agent model, `thinkingEnabled` is explicitly forced False because streamed thinking tokens corrupt tool-call JSON. This is handled in the agent path, not here.+- **Agent compatibility quirk**: when Kimi is used as a tool-calling agent model, `thinkingEnabled` is explicitly forced False because streamed thinking tokens corrupt tool-call JSON. This is handled in the agent path, not here.- **256K context / 96K output**: largest of the native providers.- **Errors swallowed into envelope**.diff --git a/docs-internal/node-logic-flows/specialized_agents/_pattern.md b/docs-internal/node-logic-flows/specialized_agents/_pattern.mdindex 0ca2a73b..b077c7e4 100644--- a/docs-internal/node-logic-flows/specialized_agents/_pattern.md+++ b/docs-internal/node-logic-flows/specialized_agents/_pattern.md@@ -7,10 +7,10 @@ agent nodes that route to the same backend handler:`travel_agent`, `tool_agent`, `productivity_agent`, `payments_agent`,`consumer_agent`, `autonomous_agent`, `orchestrator_agent`, `ai_employee`.-All 13 nodes use the `handle_chat_agent` handler wired in-`server/services/node_executor.py` (lines 134-146). They differ only in-frontend presentation (icon, theme color, default skills) and intended use-case. The three agents with **dedicated** handlers (`deep_agent`, `rlm_agent`,+All specialized nodes use the `handle_chat_agent` handler wired in+`server/services/node_executor.py`. They differ only in frontend+presentation (icon, theme color, default skills) and intended use case.+The two agents with **dedicated** handlers (`rlm_agent`,`claude_code_agent`) are documented separately.| Field | Value |@@ -44,7 +44,7 @@ All 13 agents share these input handles.| `input-main` | main | no | Upstream data; auto-prompt fallback when `prompt` param is empty || `input-skill` | main | no | Skill node(s) providing SKILL.md context || `input-memory` | main | no | `simpleMemory` node for conversation history |-| `input-tools` | main | no | Tool nodes exposed to the LLM via LangGraph |+| `input-tools` | main | no | Tool nodes exposed to the LLM via `chat_model.bind_tools` || `input-task` | main | no | `taskTrigger` events from delegated child agents || `input-teammates` | main | no | **Only on `orchestrator_agent` and `ai_employee`** -- connected agents become `delegate_to_*` tools |@@ -143,7 +143,7 @@ flowchart TD`error`), plus `executing_tool` fired on connected tool nodes when the LLMinvokes them.- **External API calls**: one or more calls to the configured LLM provider- (see `services/ai.py::execute_chat_agent` -> LangChain / LangGraph).+ (see `services/ai.py::execute_chat_agent` -> LangChain chat model + `_run_agent_loop`).- **Subprocess / file I/O**: none directly in the handler; tools invoked bythe LLM may trigger those themselves.@@ -153,7 +153,7 @@ flowchart TDconfigured LLM provider.- **Services**: `AIService.execute_chat_agent`, `CompactionService`,`PricingService`, `StatusBroadcaster`.-- **Python packages**: `langchain-core`, `langgraph`, plus provider SDKs.+- **Python packages**: `langchain-core`, plus provider SDKs.## Edge cases & known limitsdiff --git a/docs-internal/node-logic-flows/specialized_agents/deepAgent.md b/docs-internal/node-logic-flows/specialized_agents/deepAgent.mddeleted file mode 100644index 248a2083..00000000--- a/docs-internal/node-logic-flows/specialized_agents/deepAgent.md+++ /dev/null@@ -1,128 +0,0 @@-# Deep Agent (`deep_agent`)--| Field | Value |-|------|-------|-| **Category** | specialized_agents |-| **Backend handler** | [`server/services/handlers/deep_agent.py::handle_deep_agent`](../../../server/services/handlers/deep_agent.py) |-| **Backend service** | [`server/services/agents/service.py::DeepAgentService.execute`](../../../server/services/agents/service.py) |-| **Theme color** | `dracula.green` |-| **Icon** | brain (U+1F9E0) |-| **Team lead** | yes -- teammates become deepagents `SubAgent` dicts |-| **Tests** | [`server/tests/nodes/test_specialized_agents.py::TestDeepAgent`](../../../server/tests/nodes/test_specialized_agents.py) |--## Purpose--AI agent backed by LangChain [DeepAgents](https://github.com/langchain-ai/deepagents)-rather than the stock LangGraph loop. Provides built-in filesystem tools-(read, write, edit, glob, grep, execute), sub-agent delegation,-auto-summarization, and todo planning, all operating on a sandboxed-per-workflow workspace (`data/workspaces/<workflow_id>/`).--## Inputs (handles)--Same 5 shared handles as the generic specialized agents plus an-`input-teammates` handle used to seed deepagents sub-agents.--| Handle | Purpose |-|--------|---------|-| `input-main` | Auto-prompt fallback |-| `input-skill` | Skill instructions merged into system prompt |-| `input-memory` | `simpleMemory` conversation history |-| `input-tools` | Tools exposed to the deep-agent graph |-| `input-task` | `taskTrigger` completion events |-| `input-teammates` | Teammate agents converted to `SubAgent` dicts |--## Parameters--Standard `AI_AGENT_PROPERTIES` plus deepagents-specific options read by-`DeepAgentService` (`recursionLimit`, etc.).--## Outputs (handles)--| Handle | Shape | Description |-|--------|-------|-------------|-| `output-main` | object | Standard agent envelope with `response`, `model`, `provider` |--## Logic Flow--```mermaid-flowchart TD- A[handle_deep_agent] --> B[_collect_agent_connections]- B --> C{task_data present?}- C -- completed/error --> D[prepend task context<br/>strip tools]- C -- no --> E{prompt empty<br/>and input_data?}- D --> E- E -- yes --> F[prompt = input_data.message/text/content]- E -- no --> G[_collect_teammate_connections]- F --> G- G --> H[workspace_dir from context<br/>injected into parameters]- H --> I[ai_service.deep_agent_service.execute]- I --> J[FilesystemBackend root=workspace_dir<br/>virtual_mode=True]- J --> K[DeepAgentService builds LangGraph<br/>via create_deep_agent]- K --> L[Graph invocation]- L --> M[Return envelope]-```--## Decision Logic--- **Same connection-collection short-circuits** as `handle_chat_agent`:- task completion strips tools; empty prompt falls back to upstream- message/text/content.-- **Workspace injection**: `context['workspace_dir']` is copied into- `parameters['workspace_dir']` so `DeepAgentService` can pass it to- `FilesystemBackend(root_dir=workspace_dir, virtual_mode=True)`.-- **Teammates become deepagents sub-agents**: passed as a list to- `service.execute(..., teammates=teammates)`; the service constructs- deepagents `SubAgent` dicts and injects them into- `create_deep_agent(subagents=...)`.-- **Tool building**: the handler passes `build_tool_fn=ai_service._build_tool_from_node`- so the service layer can convert raw `tool_data` into LangChain- `StructuredTool` instances inside the deepagents graph.--## Side Effects--- **Database reads**: `database.get_node_parameters(source_id)` for every- connected skill, memory, tool, and teammate node.-- **Database writes**: token usage and compaction rows via- `DeepAgentService` -> `AIService` helpers.-- **Broadcasts**: `StatusBroadcaster.update_node_status` (executing,- success, error), plus `executing_tool` for tools invoked during the- deepagents run.-- **File I/O**: reads and writes within `data/workspaces/<workflow_id>/`- via the sandboxed `FilesystemBackend`.-- **External API calls**: LLM provider calls inside the deepagents graph- (one per planning / tool / summarization step).--## External Dependencies--- **Credentials**: `auth_service.get_api_key(<provider>)`.-- **Services**: `DeepAgentService`, `StatusBroadcaster`,- `PricingService`, `CompactionService`, `FilesystemBackend`.-- **Python packages**: `deepagents`, `langchain-core`, `langgraph`,- provider SDKs.-- **Filesystem**: writable `data/workspaces/<workflow_id>/` directory.--## Edge cases & known limits--- **Missing workspace**: if `context['workspace_dir']` is absent- (`None`), no injection happens; `DeepAgentService` falls back to- `Settings().workspace_base_dir`. The handler logs `workspace_dir from- context: None` at INFO but does not short-circuit.-- **Missing `deepagents` package**: `DeepAgentService.execute` raises an- `ImportError` which the handler's surrounding `NodeExecutor.execute`- wrapper converts into a failure envelope. There is no explicit- preflight check in the handler itself.-- **Teammate filtering**: uses `_collect_teammate_connections` which- filters to `AI_AGENT_TYPES`; non-agent nodes on `input-teammates` are- silently skipped.-- **No task-context tool rename**: unlike `handle_chat_agent` where the- stripped tools are replaced by delegate_to_* tools for team leads, the- deep_agent task-completion branch strips all tools outright. A- subsequent user turn must re-trigger a fresh execution to restore them.--## Related--- **Pattern siblings**: [`rlmAgent`](./rlmAgent.md), [`claudeCodeAgent`](./claudeCodeAgent.md)-- **Generic pattern**: [`_pattern.md`](./_pattern.md) (for the shared- `_collect_agent_connections` helper)-- **Architecture**: [Deep Agent](../../deep_agent.md)diff --git a/docs-internal/node-logic-flows/specialized_agents/rlmAgent.md b/docs-internal/node-logic-flows/specialized_agents/rlmAgent.mdindex b322b4ba..a85ddf0a 100644--- a/docs-internal/node-logic-flows/specialized_agents/rlmAgent.md+++ b/docs-internal/node-logic-flows/specialized_agents/rlmAgent.md@@ -11,7 +11,7 @@## Purpose-Recursive Language Model agent. Instead of LangGraph tool-calling, the+Recursive Language Model agent. Instead of the standard tool-calling loop, theLLM is prompted to emit Python code that is executed in a REPL and mayrecursively call `llm_query()` or `rlm_query()` and end with `FINAL(...)`to return a result. See [RLM Service](../../rlm_service.md).diff --git a/docs-internal/performance.md b/docs-internal/performance.mdindex 16203f54..d1d6596f 100644--- a/docs-internal/performance.md+++ b/docs-internal/performance.md@@ -194,7 +194,7 @@ Tracked but explicitly **not** in any active plan.| Item | Estimated saving | Notes ||---|---|---|| Plugin walker lazy-loading | ~0.5-0.8 s on server-ready | Would need to defer registration until first NodeSpec request rather than at module-import time. Touches every `BaseNode` subclass — biggest blast radius of the candidates. |-| `BaseMessage`-free `AgentState` (move LangGraph state schema off the `Annotated` form) | ~0.3-0.5 s | Removes the only remaining eager LangChain import in `services/ai.py`. Requires understanding how LangGraph resolves `Annotated[Sequence[BaseMessage], operator.add]` reducers. |+| `BaseMessage`-free agent loop (drop the only eager `langchain_core.messages` import in `services/ai.py`) | ~0.3-0.5 s | Native-SDK provider classes already use their own message types; `_run_agent_loop` could be retyped against them and the eager import dropped. || `+5 s` HTTP-ready → first-WS-connect gap | up to 5 s | Diagnostics needed (see "remaining +5 s gap"). May reveal nothing actionable. || Standalone Nuitka / PyOxidizer release binary | full Python interpreter init (~0.4 s) + `.pyc` regeneration on cold disk | User explicitly declined when scoping the build pipeline; revisit if "ship a single binary" becomes a product requirement. |diff --git a/docs-internal/plugin_system.md b/docs-internal/plugin_system.mdindex 4cf1fec0..e2ff57f4 100644--- a/docs-internal/plugin_system.md+++ b/docs-internal/plugin_system.md@@ -469,11 +469,10 @@ agents (`android_agent`, `coding_agent`, `web_agent`, `task_agent`,`payments_agent`, `consumer_agent`, `autonomous_agent`), 2 teamleads (`orchestrator_agent`, `ai_employee`).-**Agents that stay as single activities** (3): `deep_agent`,-`rlm_agent`, `claude_code_agent`. Their internal session state-(deepagents package / RLM REPL / Claude CLI `--resume` with stable-`cwd`) requires single-process continuity that would break across-activity boundaries.+**Agents that stay as single activities** (2): `rlm_agent`,+`claude_code_agent`. Their internal session state (RLM REPL / Claude+CLI `--resume` with stable `cwd`) requires single-process continuity+that would break across activity boundaries.Queue distribution (live count via`distinct_task_queues()` and `len(_NODE_CLASS_REGISTRY)`):@@ -807,9 +806,9 @@ All Wave 10 invariants in `test_node_spec.py` still run; Wave 11 invariants in ``services/whatsapp_service.py`, dedup'd `TRIGGER_NODE_TYPES`.- Wave 11.E.3 — Inlined the last per-domain handler bodies intoplugins. Deleted 8 fully-orphan handler files (search, code,- telegram, http, filesystem, email, process, todo) and 5- still-referenced ones (browser, android, claude_code, rlm,- deep_agent) by inlining into their plugins. Split `handlers/ai.py`+ telegram, http, filesystem, email, process, todo) and 4+ still-referenced ones (browser, android, claude_code, rlm) by+ inlining into their plugins. Split `handlers/ai.py`4 ways: `handle_ai_chat_model` → `ChatModelBase.chat`,`handle_simple_memory` → `SimpleMemoryNode.read`,`handle_ai_agent` / `handle_chat_agent` → deleted entirely.diff --git a/docs-internal/rlm_service.md b/docs-internal/rlm_service.mdindex 4f0e1512..e8884aa7 100644--- a/docs-internal/rlm_service.md+++ b/docs-internal/rlm_service.md@@ -4,19 +4,19 @@## 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.+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 the standard agent loop, 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.**Library**: [rlms](https://pypi.org/project/rlms/) (pip install rlms)**Paper**: https://arxiv.org/abs/2512.24601**Docs**: https://alexzhang13.github.io/rlm/-### How RLM Differs from LangGraph Agents+### How RLM Differs from Standard Agents-| Aspect | LangGraph Agents (aiAgent, chatAgent, etc.) | RLM Agent (rlm_agent) |-|--------|----------------------------------------------|----------------------|+| Aspect | Standard Agents (aiAgent, chatAgent, etc.) | RLM Agent (rlm_agent) |+|--------|---------------------------------------------|----------------------|| Execution model | LLM -> tool call -> LLM -> tool call | LLM -> `\`\`\`repl` code block -> exec() -> stdout -> LLM || Tool interface | LangChain StructuredTool with Pydantic schemas | Python functions injected into REPL namespace |-| State management | LangGraph StateGraph with message accumulation | Python variables in REPL namespace + `context` variable |+| State management | Message accumulation in `_run_agent_loop` | Python variables in REPL namespace + `context` variable || Completion signal | LLM stops making tool calls | LLM calls `FINAL(answer)` or `FINAL_VAR(variable_name)` || Recursion | Agent delegation (fire-and-forget) | `rlm_query()` spawns child RLM with own REPL || Strengths | Structured tool calling, provider-agnostic | Complex reasoning, code-driven decomposition, recursive sub-problems |diff --git a/docs-internal/status_broadcaster.md b/docs-internal/status_broadcaster.mdindex 71aad469..008a6ba0 100644--- a/docs-internal/status_broadcaster.md+++ b/docs-internal/status_broadcaster.md@@ -139,7 +139,7 @@ Broadcasts are sent to all connected clients without a request-response correlat| `api_key_status` | Credential validation result; also fired by `delete_api_key` to clear `apiKeyStatuses[provider]` | `{provider, data: {valid, hasKey, models, message, timestamp}}` || `credential_catalogue_updated` | Credential mutation (save / delete / oauth-disconnect) — wraps `WorkflowEvent` (CloudEvents v1.0) from `services/events/envelope.py`. Outer `type` stays this string for FE back-compat; body's `type` follows `credential.<area>.<action>` (e.g. `credential.api_key.saved`). Frontend `WebSocketContext` invalidates `useCatalogueQuery` via the 300 ms `invalidateCatalogue` debounce. | `{specversion: "1.0", id, source: "machinaos://services/credentials", type, subject: provider, time, data: {provider, customer_id?}}` || `node_parameters_updated` | Parameters saved by parameter-panel user, Claude CLI memory bridge, or AgentWorkflow per-turn memory append — wraps `WorkflowEvent` (CloudEvents v1.0) from `services/events/envelope.py`. Body's `type` is `com.machinaos.node.parameters.updated`. `data.source` (`"user"` / `"cli"` / `"agent"`) distinguishes the three emission sites. Replaces the legacy raw-dict broadcast at commit `7c9e873`. Locked by `tests/test_cloudevents_node_parameters.py`. | `{specversion: "1.0", id, source: "machinaos://services/parameters", type: "com.machinaos.node.parameters.updated", subject: node_id, time, data: {node_id, parameters, version, source}}` |-| `agent_progress` | LangGraph / AgentWorkflow lifecycle phase (canvas badge "N / max" + phase indicator) — wraps `WorkflowEvent.agent_progress` (CloudEvents v1.0). Emitted from `services/ai.py:execute_agent` (legacy) and via the `agent.broadcast_progress.v1` Temporal activity (F4.B). F4.B fires the full phase set: `starting` (entry, drives `node_status="executing"`), `llm_step` (per iteration), `executing_tool` + `tool_completed` (around each per-type tool activity), `completed` (final, drives `node_status="success"`). The activity optionally drives a raw-dict `update_node_status` alongside the CloudEvents envelope so the canvas-glow color follows the lifecycle without a separate handler — same dual-channel pattern F4.A's `_node_activity` uses. | `{specversion: "1.0", id, source: "machinaos://services/agent", type: "com.machinaos.agent.progress", subject: node_id, time, data: {node_id, iteration, max_iterations, phase?, tool_name?}}` |+| `agent_progress` | Agent-loop / AgentWorkflow lifecycle phase (canvas badge "N / max" + phase indicator) — wraps `WorkflowEvent.agent_progress` (CloudEvents v1.0). Emitted from `services/ai.py:execute_agent` (legacy) and via the `agent.broadcast_progress.v1` Temporal activity (F4.B). F4.B fires the full phase set: `starting` (entry, drives `node_status="executing"`), `llm_step` (per iteration), `executing_tool` + `tool_completed` (around each per-type tool activity), `completed` (final, drives `node_status="success"`). The activity optionally drives a raw-dict `update_node_status` alongside the CloudEvents envelope so the canvas-glow color follows the lifecycle without a separate handler — same dual-channel pattern F4.A's `_node_activity` uses. | `{specversion: "1.0", id, source: "machinaos://services/agent", type: "com.machinaos.agent.progress", subject: node_id, time, data: {node_id, iteration, max_iterations, phase?, tool_name?}}` || `token_usage_update` | AI execution updates token counters | `{session_id, data: {total, threshold, needs_compaction}}` || `compaction_starting` | Memory compaction begins | `{session_id, node_id}` || `compaction_completed` | Memory compaction ends | `{session_id, success, tokens_before, tokens_after}` |diff --git a/docs-internal/tool_building_pipeline.md b/docs-internal/tool_building_pipeline.mdindex 8b61fee5..18a3d643 100644--- a/docs-internal/tool_building_pipeline.md+++ b/docs-internal/tool_building_pipeline.md@@ -1,9 +1,9 @@# 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`.+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` and `agent_delegation.md`.> **Related docs:**-> - [agent_architecture.md](./agent_architecture.md) — overall LangGraph loop that holds the bound tools+> - [agent_architecture.md](./agent_architecture.md) — overall agent 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@@ -19,12 +19,12 @@ Canonical home for how AI Agents discover connected tool nodes, build LangChain→ tool_data entry → (StructuredTool, config_dict)│▼-3. BIND LangGraph create_react_agent(model, tools=...)- → llm.bind_tools(tools) under the hood+3. BIND services/ai.py:_run_agent_loop+ → chat_model.bind_tools(tools)│▼4. INVOKE LLM emits tool_calls in its response- → LangGraph ToolNode routes by name+ → loop dispatches each via tool_executor│▼5. DISPATCH services/handlers/tools.py:execute_tool@@ -108,21 +108,21 @@ config = {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)+## 4. Stage 3 — Bind (`_run_agent_loop`)-[`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.+[`services/ai.py:execute_agent`](../server/services/ai.py) calls `_run_agent_loop(chat_model, ...)`, which does `chat_model.bind_tools(tools)` once at the top before the iteration loop. `bind_tools` reads 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:+When the LLM emits `tool_calls` in its response, `_run_agent_loop` iterates them and dispatches each via the supplied `tool_executor` callback — 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.+5. Return `result` to the loop → wrapped as a `ToolMessage`, appended to `messages`, fed back to the LLM on the next turn.**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.diff --git a/docs-internal/workflow-schema.md b/docs-internal/workflow-schema.mdindex e966a5a8..b641d857 100644--- a/docs-internal/workflow-schema.md+++ b/docs-internal/workflow-schema.md@@ -83,7 +83,7 @@ A workflow JSON document contains:- `mistralChatModel` - Mistral Large / Small / Codestral### AI Agents and Memory (3 nodes)-- `aiAgent` - LangGraph-based agent with tool calling+- `aiAgent` - Tool-calling agent loop- `chatAgent` - Conversational agent (Zeenie) with skill support- `simpleMemory` - Markdown-based conversation memory with optional vector DBdiff --git a/package.json b/package.jsonindex 7854f6b4..5d610ea2 100644--- a/package.json+++ b/package.json@@ -9,7 +9,6 @@"react-flow","ai-agent","langchain",- "langgraph","n8n","whatsapp","android",diff --git a/server/constants.py b/server/constants.pyindex b5780fd1..0d22cecf 100644--- a/server/constants.py+++ b/server/constants.py@@ -44,7 +44,6 @@ AI_AGENT_TYPES: FrozenSet[str] = frozenset(['ai_employee','rlm_agent','claude_code_agent',- 'deep_agent',])AI_MEMORY_TYPES: FrozenSet[str] = frozenset([diff --git a/server/core/config.py b/server/core/config.pyindex 848cf1ce..44324d40 100644--- a/server/core/config.py+++ b/server/core/config.py@@ -59,12 +59,12 @@ class Settings(BaseSettings):# behave identically; flip via TEMPORAL_PER_TYPE_DISPATCH=true.temporal_per_type_dispatch: bool = Field(default=False, env="TEMPORAL_PER_TYPE_DISPATCH")# F4.B: agent-as-child-workflow. When True, MachinaWorkflow.run() schedules- # AgentWorkflow (child workflow) for the 15 migrating agent types- # (aiAgent / chatAgent / 12 specialized agents / 2 team leads) instead of+ # AgentWorkflow (child workflow) for the 14 migrating agent types+ # (aiAgent / chatAgent / 11 specialized agents / 2 team leads) instead of# an activity. Tool calls inside the agent become per-type Temporal- # activities. `deep_agent`, `rlm_agent`, `claude_code_agent` continue to- # run as F4.A per-type activities (NOT migrated -- their external session- # state would break across activity boundaries). Default off. Implies+ # activities. `rlm_agent`, `claude_code_agent` continue to run as F4.A+ # per-type activities (NOT migrated -- their external session state would+ # break across activity boundaries). Default off. Implies# temporal_per_type_dispatch=True.temporal_agent_workflow_enabled: bool = Field(default=False, env="TEMPORAL_AGENT_WORKFLOW_ENABLED",diff --git a/server/nodes/agent/_handles.py b/server/nodes/agent/_handles.pyindex a90575f8..89df3cd1 100644--- a/server/nodes/agent/_handles.py+++ b/server/nodes/agent/_handles.py@@ -41,15 +41,3 @@ def team_lead_agent_handles() -> tuple:)-def deep_agent_handles() -> tuple:- """Skill / Teammates / Tool bottom — used by deep_agent only."""- return (- {"name": "input-skill", "kind": "input", "position": "bottom", "offset": "30%", "label": "Skill", "role": "skill"},- {"name": "input-teammates", "kind": "input", "position": "bottom", "offset": "55%", "label": "Team", "role": "teammates"},- {"name": "input-tools", "kind": "input", "position": "bottom", "offset": "80%", "label": "Tool", "role": "tools"},- {"name": "input-main", "kind": "input", "position": "left", "offset": "25%", "label": "Input", "role": "main"},- {"name": "input-memory", "kind": "input", "position": "left", "offset": "50%", "label": "Memory","role": "memory"},- {"name": "input-task", "kind": "input", "position": "left", "offset": "75%", "label": "Task", "role": "task"},- {"name": "output-main", "kind": "output", "position": "right", "offset": "50%", "label": "Output","role": "main"},- {"name": "output-top", "kind": "output", "position": "top", "label": "Output","role": "main"},- )diff --git a/server/nodes/agent/_specialized.py b/server/nodes/agent/_specialized.pyindex ed6e7328..994231a4 100644--- a/server/nodes/agent/_specialized.py+++ b/server/nodes/agent/_specialized.py@@ -1,12 +1,12 @@"""Specialized agent base — subclass + set 5 attrs to mint a new agent.-13 specialized agents (android / coding / web / task / social / travel-/ tool / productivity / payments / consumer / autonomous / rlm /-claude_code) all share the LangGraph-via-handle_chat_agent execution-path. The only differences are display name, icon, colour, subtitle,-description. Each agent gets its own file under ``nodes/agent/`` so-the user can find ``android_agent.py`` directly — but the body lives-here so changing the dispatch path is a one-file edit.+All specialized agents (android / coding / web / task / social / travel+/ tool / productivity / payments / consumer / autonomous) share the+``handle_chat_agent`` execution path. The only differences are display+name, icon, colour, subtitle, description. Each agent gets its own file+under ``nodes/agent/`` so the user can find ``android_agent.py``+directly — but the body lives here so changing the dispatch path is a+one-file edit."""from __future__ import annotationsdiff --git a/server/nodes/agent/ai_agent/__init__.py b/server/nodes/agent/ai_agent/__init__.pyindex 7d20d0b0..f4fc9b1c 100644--- a/server/nodes/agent/ai_agent/__init__.py+++ b/server/nodes/agent/ai_agent/__init__.py@@ -1,8 +1,8 @@-"""AI Agent — Wave 11.C migration (LangGraph agent).+"""AI Agent — Wave 11.C migration (tool-calling agent).-Tool-calling LangGraph agent with memory, skills, and iterative+Tool-calling agent with memory, skills, and iterativereasoning. Delegates execution to ``handlers/ai.handle_ai_agent`` —-that body owns the LangGraph graph construction + tool binding ++that body owns the agent-loop construction + tool binding +streaming + memory persistence + delegation."""@@ -98,9 +98,9 @@ class AIAgentOutput(BaseModel):class AIAgentNode(ActionNode):type = "aiAgent"display_name = "AI Agent"- subtitle = "LangGraph Agent"+ subtitle = "AI Agent"group = ("agent",)- description = "LangGraph agent with tool calling, memory, and iterative reasoning"+ description = "AI agent with tool calling, memory, and iterative reasoning"component_kind = "agent"handles = std_agent_handles()ui_hints = STD_AGENT_HINTS@@ -117,8 +117,8 @@ class AIAgentNode(ActionNode):Pre-dispatch flow (edge walk + task inject + prompt fallback)lives in :mod:`nodes.agent._inline`. This method just calls``AIService.execute_agent`` with the prepared kwargs. The- underlying LangGraph orchestration + tool binding + memory- I/O + streaming hooks stay in AIService.+ underlying agent loop + tool binding + memory I/O + streaming+ hooks stay in AIService."""from services.plugin.deps import get_ai_service, get_databasediff --git a/server/nodes/agent/chat_agent/__init__.py b/server/nodes/agent/chat_agent/__init__.pyindex 62bea88d..440537da 100644--- a/server/nodes/agent/chat_agent/__init__.py+++ b/server/nodes/agent/chat_agent/__init__.py@@ -1,6 +1,6 @@"""Chat Agent (Zeenie) — Wave 11.C migration.-Conversational LangGraph agent with skills + memory. Distinct from+Conversational agent with skills + memory. Distinct from:class:`AIAgentNode` because it uses ``handle_chat_agent`` whichapplies a different default system message + skill prompt assembly."""diff --git a/server/nodes/agent/deep_agent/__init__.py b/server/nodes/agent/deep_agent/__init__.pydeleted file mode 100644index 8bd3d8a3..00000000--- a/server/nodes/agent/deep_agent/__init__.py+++ /dev/null@@ -1,103 +0,0 @@-"""Deep Agent — Wave 11.E.3 inlined.--LangChain DeepAgents with filesystem tools + sub-agent delegation.-Distinct from the generic chat agent: different bottom-handle ordering-(Skill / Team / Tool) for the team-delegation UX, and dispatches via-``ai_service.deep_agent_service.execute``.-"""--from __future__ import annotations--from typing import Any--from core.logging import get_logger-from services.plugin import ActionNode, NodeContext, Operation, TaskQueue-from services.plugin.edge_walker import (- collect_agent_connections, collect_teammate_connections, format_task_context,-)--from .._handles import STD_AGENT_HINTS, deep_agent_handles-from .._specialized import SpecializedAgentOutput, SpecializedAgentParams--logger = get_logger(__name__)---class DeepAgentNode(ActionNode):- type = "deep_agent"- display_name = "Deep Agent"- subtitle = "LangChain DeepAgents"- group = ("agent",)- description = "LangChain DeepAgents with filesystem tools and sub-agent delegation"- component_kind = "agent"- handles = deep_agent_handles()- ui_hints = STD_AGENT_HINTS- annotations = {"destructive": True, "readonly": False, "open_world": True}- task_queue = TaskQueue.AI_HEAVY-- Params = SpecializedAgentParams- Output = SpecializedAgentOutput-- @Operation("execute", cost={"service": "deep_agent", "action": "run", "count": 1})- async def execute_op(self, ctx: NodeContext, params: SpecializedAgentParams) -> Any:- from services.plugin.deps import get_ai_service, get_database- from services.status_broadcaster import get_status_broadcaster-- ai_service = get_ai_service()- database = get_database()- node_id = ctx.node_id- workflow_id = ctx.workflow_id- payload = params.model_dump()-- # 1. Edge-walk for memory / skill / tool / input / task connections.- memory_data, skill_data, tool_data, input_data, task_data = await collect_agent_connections(- node_id, ctx.raw, database, log_prefix="[Deep Agent]",- )-- # 2. Inject task-completion context into the prompt; strip tools- # if the parent task is already done/errored.- if task_data:- payload = {- **payload,- 'prompt': f"{format_task_context(task_data)}\n\n{payload.get('prompt', '')}",- }- if task_data.get('status') in ('completed', 'error') and tool_data:- tool_data = []-- # 3. Auto-prompt fallback from connected input.- if not payload.get('prompt') and input_data:- payload = {- **payload,- 'prompt': (- input_data.get('message')- or input_data.get('text')- or input_data.get('content')- or str(input_data)- ),- }-- # 4. Teammates (sub-agents wired to input-teammates).- teammates = await collect_teammate_connections(node_id, ctx.raw, database)-- # 5. Pass the per-workflow workspace dir through so DeepAgents'- # filesystem tools confine themselves correctly.- workspace_dir = ctx.raw.get('workspace_dir')- logger.info("[Deep Agent] workspace_dir from context: %s", workspace_dir)- if workspace_dir:- payload = {**payload, 'workspace_dir': workspace_dir}-- # 6. Delegate to DeepAgentService — service builds tools via the- # ToolAdapter using ai_service._build_tool_from_node.- response = await ai_service.deep_agent_service.execute(- node_id, payload,- memory_data=memory_data if memory_data else None,- skill_data=skill_data if skill_data else None,- tool_data=tool_data if tool_data else None,- teammates=teammates if teammates else None,- build_tool_fn=ai_service._build_tool_from_node,- broadcaster=get_status_broadcaster(),- workflow_id=workflow_id,- database=database,- )- if response.get("success") is False:- raise RuntimeError(response.get("error") or "deep_agent execution failed")- return response.get("result") or responsediff --git a/server/nodes/agent/deep_agent/meta.json b/server/nodes/agent/deep_agent/meta.jsondeleted file mode 100644index aa33b4b5..00000000--- a/server/nodes/agent/deep_agent/meta.json+++ /dev/null@@ -1,3 +0,0 @@-{- "color": "#50fa7b"-}diff --git a/server/nodes/agent/rlm_agent/__init__.py b/server/nodes/agent/rlm_agent/__init__.pyindex d021fef3..dfc657f4 100644--- a/server/nodes/agent/rlm_agent/__init__.py+++ b/server/nodes/agent/rlm_agent/__init__.py@@ -1,7 +1,7 @@"""RLM Agent — Wave 11.E.3 inlined.-Recursive Language Model agent. Distinct from the standard LangGraph-chat agent — spins a recursive LM loop inside a REPL sandbox via+Recursive Language Model agent. Distinct from the standard chat+agent — spins a recursive LM loop inside a REPL sandbox via``ai_service.rlm_service.execute``."""diff --git a/server/nodes/tool/agent_builder/__init__.py b/server/nodes/tool/agent_builder/__init__.pyindex 1ff6a1bc..0f392a9c 100644--- a/server/nodes/tool/agent_builder/__init__.py+++ b/server/nodes/tool/agent_builder/__init__.py@@ -21,8 +21,8 @@ The five operations are pure canvas mutations:Each mutation pushes a ``workflow_ops_apply`` event via the plugin's``_events.broadcast_workflow_ops`` wrapper so the live canvas updates.-LangGraph binds tools at graph compile time, so a mutation made-mid-run does NOT add a callable tool to the current run; the+The agent loop binds tools at the start of each turn, so a mutation+made mid-run does NOT add a callable tool to the current turn; theagent's NEXT invocation rediscovers it. Each summary string endswith "Available on your next turn" so the LLM doesn't loop tryingto call something that isn't there yet.@@ -58,7 +58,7 @@ _TOOL_OUTPUT_HANDLE = "output-main"_MASTER_SKILL_TYPE = "masterSkill"_MASTER_SKILL_LABEL = "Master Skill"_AGENT_BUILDER_TYPE = "agentBuilder"-_TEAM_LEAD_TYPES = frozenset({"orchestrator_agent", "ai_employee", "deep_agent"})+_TEAM_LEAD_TYPES = frozenset({"orchestrator_agent", "ai_employee"})_DENIED_TOOL_TYPES = frozenset({_AGENT_BUILDER_TYPE, _MASTER_SKILL_TYPE})_KEY_PARAM_FIELDS = ("provider", "model", "operation", "url", "query")_SKILLS_DIR = Path(__file__).resolve().parents[2] / "skills"@@ -245,7 +245,7 @@ class AgentBuilderParams(BaseModel):"For add_subagent: agent node type to spawn (e.g. ""'coding_agent', 'web_agent'). Must be component_kind='agent' ""and not a team-lead. Caller must itself be a team-lead "- "(orchestrator_agent / ai_employee / deep_agent)."+ "(orchestrator_agent / ai_employee)."),json_schema_extra={"displayOptions": {"show": {"operation": ["add_subagent"]}}},)diff --git a/server/nodes/visuals.json b/server/nodes/visuals.jsonindex af511252..e71c33e7 100644--- a/server/nodes/visuals.json+++ b/server/nodes/visuals.json@@ -92,9 +92,6 @@"currentTimeTool": {"icon": "🕐"},- "deep_agent": {- "icon": "🧠"- },"deepseekChatModel": {"icon": "lobehub:deepseek"},diff --git a/server/pyproject.toml b/server/pyproject.tomlindex 3307b302..5d04ff5f 100644--- a/server/pyproject.toml+++ b/server/pyproject.toml@@ -68,7 +68,6 @@ dependencies = [# HTMLHeaderTextSplitter SSRF advisory; the 1.1 line requires# langchain-core>=1.3, which we now satisfy."langchain-text-splitters==1.1.2",- "langgraph==1.1.6","deepagents==0.5.2",# Pydantic 2.13 changed validator ordering; pin to main's 2.12 linediff --git a/server/requirements.txt b/server/requirements.txtindex 4486ee5c..436341df 100644--- a/server/requirements.txt+++ b/server/requirements.txt@@ -48,9 +48,6 @@ langchain-google-genai>=3.1.0langchain-groq>=0.1.0langchain-cerebras>=0.1.0-# LangGraph - State machine for AI agents-langgraph>=1.0.6-# DeepAgents - Batteries-included agent harness (LangChain)deepagents>=0.4.12diff --git a/server/services/agents/__init__.py b/server/services/agents/__init__.pydeleted file mode 100644index a24917cf..00000000--- a/server/services/agents/__init__.py+++ /dev/null@@ -1,9 +0,0 @@-"""DeepAgent service module.--Provides DeepAgentService for executing deep agent completions-via LangChain deepagents package within MachinaOS.-"""--from .service import DeepAgentService--__all__ = ["DeepAgentService"]diff --git a/server/services/agents/adapters.py b/server/services/agents/adapters.pydeleted file mode 100644index f17a23e2..00000000--- a/server/services/agents/adapters.py+++ /dev/null@@ -1,199 +0,0 @@-"""Deep Agent adapters -- protocol translation between MachinaOs and deepagents.--Follows the same pattern as rlm/adapters.py:-- ToolAdapter: wraps schema-only tools with real executors-- SubAgentAdapter: converts teammates to deepagents SubAgent dicts-- ResponseExtractor: extracts response + thinking from multi-format messages-"""--from typing import Any, Dict, List, Optional--from langchain_core.tools import StructuredTool-from core.logging import get_logger--logger = get_logger(__name__)---class ToolAdapter:- """Wraps schema-only StructuredTools with real async executors.-- _build_tool_from_node() returns tools with placeholder_func (schema only).- deepagents' ToolNode calls tool.ainvoke() directly, so each tool needs- a real coroutine calling execute_tool() from handlers/tools.py.- """-- @staticmethod- def build_tools(- tool_data: List[Dict[str, Any]],- build_tool_fn,- workflow_id: str = None,- broadcaster=None,- workspace_dir: str = "",- ) -> List[StructuredTool]:- """Build executable tools from raw tool_data.-- Args:- tool_data: Raw tool info dicts from _collect_agent_connections.- build_tool_fn: AIService._build_tool_from_node (async).- workflow_id: For scoped status broadcasts.- broadcaster: For tool node glow effects.- workspace_dir: Per-workflow workspace path for filesystem tools.-- Returns:- List of StructuredTools with real async executors.- """- # Return coroutine - must be awaited- return ToolAdapter._build_tools_async(tool_data, build_tool_fn, workflow_id, broadcaster, workspace_dir)-- @staticmethod- async def _build_tools_async(tool_data, build_tool_fn, workflow_id, broadcaster, workspace_dir=""):- executable = []- for tool_info in tool_data:- try:- tool, config = await build_tool_fn(tool_info)- if tool and config:- if workspace_dir:- config['workspace_dir'] = workspace_dir- executable.append(- ToolAdapter._wrap(tool, config, workflow_id, broadcaster)- )- logger.info("[DeepAgent] Built tool: %s (node=%s, type=%s)",- tool.name, config.get('node_id'), tool_info.get('node_type'))- except Exception as e:- logger.warning("[DeepAgent] Failed to build tool from %s: %s",- tool_info.get("node_type"), e)- logger.info("[DeepAgent] %d tool(s) ready", len(executable))- return executable-- @staticmethod- def _wrap(tool: StructuredTool, config: Dict, workflow_id: str, broadcaster) -> StructuredTool:- """Replace placeholder func with a real async executor.-- Tool-node status lifecycle (executing/success/error) is owned by- ``handlers.tools.execute_tool`` — the same single source of- truth that ``services.ai`` uses. We only emit DeepAgent-side- timing logs here.- """- tool_name = tool.name- tool_node_type = config.get('node_type', '')-- # ``broadcaster`` is intentionally unused now — kept in the- # signature for call-site compatibility until DeepAgentService- # stops passing it.- del broadcaster # noqa: F841-- async def _execute(**kwargs) -> Any:- import time- from services.handlers.tools import execute_tool-- logger.info("[DeepAgent] Tool call: %s (type=%s) args=%s",- tool_name, tool_node_type, {k: str(v)[:200] for k, v in kwargs.items()})- t0 = time.time()-- cfg = {**config, 'workflow_id': workflow_id}- try:- result = await execute_tool(tool_name, kwargs, cfg)- elapsed = time.time() - t0- if isinstance(result, dict):- success = result.get('success', 'error' not in result)- else:- success = True- logger.info("[DeepAgent] Tool done: %s (%.2fs) success=%s",- tool_name, elapsed, success)- return result- except Exception as e:- elapsed = time.time() - t0- logger.error("[DeepAgent] Tool failed: %s (%.2fs) error=%s", tool_name, elapsed, e)- return {"error": str(e)}-- return StructuredTool.from_function(- name=tool.name,- description=tool.description,- coroutine=_execute,- args_schema=tool.get_input_schema(),- )---class SubAgentAdapter:- """Converts MachinaOs teammate dicts to deepagents SubAgent format."""-- @staticmethod- def convert(teammates: List[Dict[str, Any]]) -> List[Dict[str, Any]]:- subagents = []- seen: set = set()- for tm in teammates:- params = tm.get("parameters", {})- label = tm.get("label", tm.get("node_type", "agent"))- name = label.lower().replace(" ", "-")- while name in seen:- name = f"{name}_{len(seen)}"- seen.add(name)- system_prompt = params.get("system_message", "")- subagents.append({- "name": name,- "description": f"Delegate tasks to {label}",- "system_prompt": system_prompt or f"You are {label}.",- })- return subagents---class ResponseExtractor:- """Extracts response text, thinking content, and iteration count from messages."""-- @staticmethod- def extract(messages: list) -> Dict[str, Any]:- """Extract response, thinking, and iterations from deepagents result messages.-- Returns:- Dict with keys: response, thinking, iterations- """- response_content = ""- thinking_content = None- iterations = 0-- # Count iterations (tool-call messages indicate agent loops)- for msg in messages:- if getattr(msg, "type", None) == "ai" and getattr(msg, "tool_calls", None):- iterations += 1-- # Log all messages for debugging- for i, msg in enumerate(messages):- msg_type = getattr(msg, "type", "?")- has_tools = bool(getattr(msg, "tool_calls", None))- content_preview = str(getattr(msg, "content", ""))[:150]- logger.info("[DeepAgent] msg[%d] type=%s tool_calls=%s content=%s", i, msg_type, has_tools, content_preview)-- # Extract final AI response- for msg in reversed(messages):- if getattr(msg, "type", None) == "ai" and hasattr(msg, "content"):- raw = msg.content-- # Handle list content (Gemini format)- if isinstance(raw, list):- parts = []- for block in raw:- if isinstance(block, dict) and block.get("type") == "text":- parts.append(block.get("text", ""))- elif isinstance(block, str):- parts.append(block)- response_content = "\n".join(parts)- elif isinstance(raw, str):- response_content = raw- else:- response_content = str(raw)-- # Extract thinking- from services.ai import extract_thinking_from_response- _, thinking_content = extract_thinking_from_response(msg)- break-- logger.info("[DeepAgent] Extracted: response_len=%d thinking=%s iterations=%d",- len(response_content), thinking_content is not None, max(iterations, 1))- if not response_content:- logger.warning("[DeepAgent] Empty response extracted from %d messages", len(messages))-- return {- "response": response_content,- "thinking": thinking_content,- "iterations": max(iterations, 1),- }diff --git a/server/services/agents/constants.py b/server/services/agents/constants.pydeleted file mode 100644index a342d7c6..00000000--- a/server/services/agents/constants.py+++ /dev/null@@ -1,10 +0,0 @@-"""Deep Agent constants and provider mappings."""--# MachinaOs provider -> deepagents model prefix.-# deepagents uses "provider:model" strings (see deepagents.utils.resolve_model).-# Only gemini differs; all others use their MachinaOs name directly.-PROVIDER_PREFIX = {- "gemini": "google_genai",-}--DEFAULT_MAX_TURNS = 200diff --git a/server/services/agents/service.py b/server/services/agents/service.pydeleted file mode 100644index 0b93a411..00000000--- a/server/services/agents/service.py+++ /dev/null@@ -1,297 +0,0 @@-"""DeepAgent execution service -- orchestration only.--Delegates to adapters for protocol translation and reuses-shared helpers from ai.py for config resolution and memory.-"""--import os-import time-import warnings-from datetime import datetime-from typing import Dict, Any, List, Optional--warnings.filterwarnings("ignore", category=DeprecationWarning, module="deepagents.middleware.subagents")--from core.logging import get_logger, log_execution_time, log_api_call-from .adapters import ToolAdapter, SubAgentAdapter, ResponseExtractor-from .constants import DEFAULT_MAX_TURNS--logger = get_logger(__name__)---class DeepAgentService:- """Dedicated service for Deep Agent execution.-- Injected into AIService via composition,- following the same pattern as RLMService.- """-- def __init__(self, auth=None, model_factory=None, token_tracker=None):- self.auth = auth- self._create_model = model_factory- self._track_token_usage = token_tracker-- async def execute(- self,- node_id: str,- parameters: Dict[str, Any],- memory_data: Optional[Dict[str, Any]] = None,- skill_data: Optional[List[Dict[str, Any]]] = None,- tool_data: Optional[List[Dict[str, Any]]] = None,- teammates: Optional[List[Dict[str, Any]]] = None,- build_tool_fn=None,- broadcaster=None,- workflow_id: Optional[str] = None,- database=None,- ) -> Dict[str, Any]:- """Execute Deep Agent via deepagents.create_deep_agent().-- Receives raw tool_data (not pre-built tools). Builds executable- tools via ToolAdapter, converts teammates via SubAgentAdapter,- extracts response via ResponseExtractor.- """- start_time = time.time()- provider = 'unknown'- model = 'unknown'-- async def broadcast_status(phase: str, details: Dict[str, Any] = None):- if broadcaster:- await broadcaster.update_node_status(node_id, "executing", {- "phase": phase, "agent_type": "deep_agent", **(details or {})- }, workflow_id=workflow_id)-- try:- # === Parameter extraction + skill injection ===- from services.ai import _build_skill_system_prompt- prompt = parameters.get('prompt', '')- system_message = parameters.get('system_message', 'You are a helpful assistant')-- skill_prompt, has_personality = _build_skill_system_prompt(skill_data, log_prefix="[DeepAgent]")- if skill_prompt:- system_message = skill_prompt if has_personality else f"{system_message}\n\n{skill_prompt}"-- # === Provider/model/API key resolution ===- from services.ai import (- is_model_valid_for_provider, get_default_model_async,- _resolve_max_tokens, _resolve_temperature, ThinkingConfig,- )- options = parameters.get('options', {})- flattened = {**parameters, **options}-- provider = parameters.get('provider', 'openai')- model = parameters.get('model', '')- if model.startswith('[FREE] '):- model = model[7:]- if not model or not is_model_valid_for_provider(model, provider):- model = await get_default_model_async(provider, database)-- api_key = flattened.get('api_key')- if not api_key and self.auth:- api_key = await self.auth.get_api_key(provider)- if not api_key:- raise ValueError(f"API key required for Deep Agent (provider: {provider})")-- max_tokens = _resolve_max_tokens(flattened, model, provider)- thinking_config = None- if flattened.get('thinking_enabled'):- thinking_config = ThinkingConfig(- enabled=True,- budget=int(flattened.get('thinking_budget', 2048)),- effort=flattened.get('reasoning_effort', 'medium'),- level=flattened.get('thinking_level', 'medium'),- format=flattened.get('reasoning_format', 'parsed'),- )- temperature = _resolve_temperature(flattened, model, provider, bool(thinking_config and thinking_config.enabled))- proxy_url = await self.auth.get_api_key(f"{provider}_proxy") if self.auth else None-- await broadcast_status("initializing", {"message": f"Initializing Deep Agent with {provider}/{model}", "provider": provider, "model": model})-- # === Model creation ===- chat_model = self._create_model(provider, api_key, model, temperature, max_tokens, thinking_config, proxy_url)-- # === Build tools via ToolAdapter ===- executable_tools = []- if tool_data and build_tool_fn:- await broadcast_status("building_tools", {"message": f"Building {len(tool_data)} tool(s)..."})- # Each agent gets its own subfolder: {workspace}/{node_id}/- base_workspace = parameters.get('workspace_dir', '')- workspace_dir = os.path.join(base_workspace, node_id) if base_workspace else ''- if workspace_dir:- os.makedirs(workspace_dir, exist_ok=True)- executable_tools = await ToolAdapter._build_tools_async(tool_data, build_tool_fn, workflow_id, broadcaster, workspace_dir)-- # If write_todos tool is connected, add planning instructions to system message- has_todos = any(t.get('node_type') == 'writeTodos' for t in (tool_data or []))- if has_todos:- system_message += (- "\n\nYou have a `write_todos` tool. For any task with 3+ steps, "- "ALWAYS call write_todos first to plan, then update it after each step "- "(mark completed, set next in_progress). The user sees your progress live."- )-- # === Convert teammates via SubAgentAdapter ===- subagents = SubAgentAdapter.convert(teammates) if teammates else None-- # === Load memory ===- from services.ai import _parse_memory_markdown, _get_memory_vector_store- session_id = None- history_count = 0- memory_content = None- input_messages = []-- if memory_data and memory_data.get('node_id'):- session_id = memory_data.get('session_id', 'default')- memory_content = memory_data.get('memory_content', '# Conversation History\n\n*No messages yet.*\n')-- await broadcast_status("loading_memory", {"message": "Loading conversation history...", "session_id": session_id})-- history_messages = _parse_memory_markdown(memory_content)- history_count = len(history_messages)-- if memory_data.get('long_term_enabled'):- store = _get_memory_vector_store(session_id)- if store:- try:- docs = store.similarity_search(prompt, k=memory_data.get('retrieval_count', 3))- if docs:- system_message = f"{system_message}\n\nRelevant past context:\n" + "\n---\n".join(d.page_content for d in docs)- except Exception as e:- logger.debug("[DeepAgent Memory] Long-term retrieval skipped: %s", e)-- for msg in history_messages:- input_messages.append({"role": getattr(msg, "type", "user"), "content": msg.content})-- input_messages.append({"role": "user", "content": prompt})-- # === Create and invoke agent ===- # Use langchain.agents.create_agent directly (not create_deep_agent)- # to avoid built-in middleware (filesystem, todo, subagent) that bypasses- # MachinaOs tool nodes. Only connected MachinaOs tools are used.- from langchain.agents import create_agent- from deepagents.middleware.patch_tool_calls import PatchToolCallsMiddleware-- max_turns = int(parameters.get('max_turns', DEFAULT_MAX_TURNS))-- await broadcast_status("executing", {- "message": f"Running Deep Agent ({provider}/{model})...",- "tool_count": len(executable_tools),- "workspace": parameters.get('workspace_dir', ''),- })-- middleware_list = [PatchToolCallsMiddleware()]- if subagents:- from deepagents.middleware.subagents import SubAgentMiddleware- middleware_list.append(SubAgentMiddleware(- default_model=chat_model,- default_tools=executable_tools or [],- subagents=subagents,- ))-- agent = create_agent(- model=chat_model,- tools=executable_tools or [],- system_prompt=system_message,- middleware=middleware_list,- )- result = await agent.ainvoke(- {"messages": input_messages},- config={"recursion_limit": max_turns * 2},- )-- # === Extract response via ResponseExtractor ===- messages = result.get("messages", [])- extracted = ResponseExtractor.extract(messages)-- # === Track token usage (same as execute_chat_agent) ===- compaction_result = None- if session_id and self._track_token_usage:- # Find last AI message for usage_metadata- ai_response = None- for msg in reversed(messages):- if getattr(msg, "type", None) == "ai":- ai_response = msg- break- if ai_response:- compaction_result = await self._track_token_usage(- session_id=session_id,- node_id=node_id,- provider=provider,- model=model,- ai_response=ai_response,- all_messages=messages,- broadcaster=broadcaster,- workflow_id=workflow_id,- memory_content=memory_content,- api_key=api_key,- memory_node_id=memory_data.get('node_id') if memory_data else None,- )-- # === Save memory ===- from services.ai import _append_to_memory_markdown, _trim_markdown_window, is_valid_message_content- if memory_data and memory_data.get('node_id') and is_valid_message_content(prompt) and is_valid_message_content(extracted["response"]):- await broadcast_status("saving_memory", {"message": "Saving to conversation memory...", "session_id": session_id})-- # If compaction happened, use compacted summary as base- if compaction_result and compaction_result.get('success') and compaction_result.get('summary'):- updated = compaction_result['summary']- else:- updated = memory_content or '# Conversation History\n\n*No messages yet.*\n'- updated = _append_to_memory_markdown(updated, 'human', prompt)- updated = _append_to_memory_markdown(updated, 'ai', extracted["response"])- updated, removed = _trim_markdown_window(updated, memory_data.get('window_size', 10))-- if removed and memory_data.get('long_term_enabled'):- store = _get_memory_vector_store(session_id)- if store:- try:- store.add_texts(removed)- except Exception as e:- logger.warning("[DeepAgent Memory] Failed to archive: %s", e)-- if database:- params = await database.get_node_parameters(memory_data['node_id']) or {}- # Schema-canonical key. Drop any pre-migration- # camelCase mirror so the saved params stay clean.- params['memory_content'] = updated- params.pop('memoryContent', None)- await database.save_node_parameters(memory_data['node_id'], params)-- log_execution_time(logger, "deep_agent", start_time, time.time())- log_api_call(logger, provider, model, "deep_agent", True)-- # === Build result (matches execute_chat_agent format) ===- agent_type = "deep_agent"- if skill_data and executable_tools:- agent_type = "deep_agent_with_skills_and_tools"- elif skill_data:- agent_type = "deep_agent_with_skills"- elif executable_tools:- agent_type = "deep_agent_with_tools"-- result_data = {- "response": extracted["response"],- "thinking": extracted["thinking"],- "thinking_enabled": thinking_config.enabled if thinking_config else False,- "model": model, "provider": provider,- "agent_type": agent_type,- "iterations": extracted["iterations"],- "messages_count": len(messages),- "finish_reason": "stop",- "timestamp": datetime.now().isoformat(),- "input": {"prompt": prompt, "system_message": system_message},- }- if session_id:- result_data["memory"] = {"session_id": session_id, "history_loaded": history_count}- if skill_data:- result_data["skills"] = {"connected": [s.get('skill_name', s.get('node_type', '')) for s in skill_data], "count": len(skill_data)}- if executable_tools:- result_data["tools"] = {"connected": [t.name for t in executable_tools], "count": len(executable_tools)}- if subagents:- result_data["subagents"] = {"connected": [s["name"] for s in subagents], "count": len(subagents)}-- return {"success": True, "node_id": node_id, "node_type": "deep_agent", "result": result_data, "execution_time": time.time() - start_time}-- except Exception as e:- logger.error("[DeepAgent] Execution failed", node_id=node_id, error=str(e))- log_api_call(logger, provider, model, "deep_agent", False, error=str(e))- return {"success": False, "node_id": node_id, "node_type": "deep_agent", "error": str(e), "execution_time": time.time() - start_time, "timestamp": datetime.now().isoformat()}diff --git a/server/services/ai.py b/server/services/ai.pyindex 38423170..886fc3ba 100644--- a/server/services/ai.py+++ b/server/services/ai.py@@ -1,4 +1,4 @@-"""AI service for managing language models with LangGraph state machine support."""+"""AI service: LangChain-based chat-model construction + plain async agent loop."""from __future__ import annotations@@ -8,37 +8,29 @@ import timeimport httpxfrom dataclasses import dataclassfrom datetime import datetime-from typing import Dict, Any, List, Optional, Callable, Type, TypedDict, Annotated, Sequence, TYPE_CHECKING-import operator+from typing import Dict, Any, List, Optional, Callable, Type, TYPE_CHECKING# ---------------------------------------------------------------------------# LangChain imports — fully lazy except for ``BaseMessage``.## Cold-start measurement (Windows, fresh disk):# ``from langchain_openai import ChatOpenAI`` ~20.8s (pulls openai SDK + tiktoken)-# ``from langchain_core.tools/langgraph/pydantic`` ~3.0s (langgraph state-graph init)-# Total eager cost was ~23.8s on first launch.+# Deferring the heavy imports until the first agent run trims server-ready time.## ``services/llm/`` (the native LLM SDK layer) handles ``execute_chat()`` and# ``fetch_models()`` without LangChain. LangChain is only needed on the agent-# execution path (``execute_agent`` / ``execute_chat_agent``). Deferring the-# imports until the first agent run trims that 23.8s off server-ready time.+# execution path (``execute_agent`` / ``execute_chat_agent``) for the per-+# provider ``ChatOpenAI`` / ``ChatAnthropic`` / ``ChatGoogleGenerativeAI``+# instances and ``chat_model.bind_tools()`` provider-unified tool calling.#-# Only ``BaseMessage`` stays eager: ``AgentState`` (a module-level TypedDict)-# carries ``Annotated[Sequence[BaseMessage], operator.add]``, which LangGraph-# resolves via ``typing.get_type_hints()`` when ``StateGraph(AgentState)`` is-# constructed. ``get_type_hints`` ``eval()``s the string annotations against-# this module's globals, and ``module.__getattr__`` is NOT consulted by-# ``eval``, so ``BaseMessage`` must live in the real namespace. Importing-# ``langchain_core.messages`` standalone is cheap (it doesn't pull tiktoken-# or the openai SDK).-#-# Everything else is resolved via ``@functools.cache``'d helpers or local-# imports inside the function/method that needs them. Python's ``sys.modules``-# cache makes repeated local imports microsecond-cheap after the first.+# ``BaseMessage`` stays eager because ``_run_agent_loop`` type-hints it in+# its signature; the import is cheap (no tiktoken / openai SDK pull) and+# keeps type checkers happy. Everything else is lazy via+# ``@functools.cache``'d helpers or local imports inside the methods that+# need them.# ----------------------------------------------------------------------------from langchain_core.messages import BaseMessage # eager: needed for AgentState type resolution+from langchain_core.messages import BaseMessage # eager: type hint for _run_agent_loopimport json# Eager imports — both are tiny and read on every chat/agent execution@@ -54,8 +46,6 @@ if TYPE_CHECKING:from langchain_openai import ChatOpenAI # noqa: F401from langchain_core.messages import HumanMessage, SystemMessage, AIMessage, ToolMessage # noqa: F401from langchain_core.tools import StructuredTool # noqa: F401- from langgraph.graph import StateGraph, END # noqa: F401- from langgraph.errors import GraphRecursionError # noqa: F401from pydantic import BaseModel, Field, create_model # noqa: F401from langchain_anthropic import ChatAnthropic # noqa: F401from langchain_groq import ChatGroq # noqa: F401@@ -552,7 +542,7 @@ def is_valid_message_content(content: Any) -> bool:return bool(content)-def filter_empty_messages(messages: Sequence[BaseMessage]) -> List[BaseMessage]:+def filter_empty_messages(messages: List[BaseMessage]) -> List[BaseMessage]:"""Filter out messages with empty content to prevent API errors.This is a standardized utility that handles empty message filtering for all@@ -579,7 +569,7 @@ def filter_empty_messages(messages: Sequence[BaseMessage]) -> List[BaseMessage]:filtered = []for m in messages:- # ToolMessage - always keep (contains tool execution results from LangGraph)+ # ToolMessage - always keep (contains tool execution results)if isinstance(m, ToolMessage):filtered.append(m)continue@@ -624,29 +614,6 @@ def filter_empty_messages(messages: Sequence[BaseMessage]) -> List[BaseMessage]:return filtered-# =============================================================================-# LANGGRAPH STATE MACHINE DEFINITIONS-# =============================================================================--class AgentState(TypedDict):- """State for the LangGraph agent workflow.-- Uses Annotated with operator.add to accumulate messages over steps.- This is the core pattern from LangGraph for stateful conversations.- """- messages: Annotated[Sequence[BaseMessage], operator.add]- # Tool outputs storage- tool_outputs: Dict[str, Any]- # Tool calling support- pending_tool_calls: List[Dict[str, Any]] # Tool calls from LLM to execute- # Agent metadata- iteration: int- max_iterations: int- should_continue: bool- # Thinking/reasoning content accumulated across iterations- thinking_content: Optional[str]--def extract_thinking_from_response(response) -> tuple:"""Extract text and thinking content from LLM response.@@ -751,213 +718,136 @@ def extract_thinking_from_response(response) -> tuple:return text, thinking-def create_agent_node(chat_model):- """Create the agent node function for LangGraph.-- The agent node:- 1. Receives current state with messages- 2. Invokes the LLM- 3. Extracts thinking content if present- 4. Checks for tool calls in response- 5. Returns updated state with new AI message, thinking, and pending tool calls+async def _run_agent_loop(+ chat_model,+ initial_messages: List[BaseMessage],+ *,+ tools: Optional[List[Any]] = None,+ tool_executor: Optional[Callable] = None,+ max_iterations: int = 500,+ progress_callback: Optional[Callable[[int], Any]] = None,+) -> Dict[str, Any]:+ """Drive an LLM agent loop with optional tool calling.++ Plain-async ``while iteration < max:`` loop. Each iteration:++ 1. Invoke ``chat_model.ainvoke(filtered_messages)`` and append the+ returned assistant message verbatim. Appending the message object+ itself preserves Gemini ``thought_signature``, Anthropic cache+ markers, OpenAI ``reasoning_content``, etc.+ 2. Extract thinking content; accumulate across iterations with the+ ``--- Iteration N ---`` separator.+ 3. If the response carries ``tool_calls``, dispatch each via the+ supplied ``tool_executor`` and append a ``ToolMessage`` per call.+ Executor failures get surfaced to the model as an error JSON so+ the loop can recover rather than abort.+ 4. If no tool calls, return.++ On hitting ``max_iterations``, append a terminal ``AIMessage`` with+ a truncation note so downstream extraction has a usable response —+ same shape the old ``GraphRecursionError`` handler synthesised.++ ``progress_callback(iteration)`` is awaited at the top of each turn+ (replaces the per-snapshot broadcast inside ``astream``).++ Returns ``{messages, iteration, thinking_content, truncated}``.+ ``messages`` is the full accumulated list (system + history ++ interleaved AI / Tool messages); callers extract the last AIMessage+ as the final response."""- def agent_node(state: AgentState) -> Dict[str, Any]:- """Process messages through the LLM and return response."""- messages = state["messages"]- iteration = state.get("iteration", 0)- max_iterations = state.get("max_iterations", 10)- existing_thinking = state.get("thinking_content") or ""-- logger.debug(f"[LangGraph] Agent node invoked, iteration={iteration}, messages={len(messages)}")+ from langchain_core.messages import AIMessage, ToolMessage- # Filter out messages with empty content using standardized utility- # Prevents API errors/warnings from Gemini, Claude, and other providers- filtered_messages = filter_empty_messages(messages)+ model = chat_model.bind_tools(tools) if tools else chat_model+ messages: List[BaseMessage] = list(initial_messages)+ thinking_accumulated = ""+ iteration = 0- if len(filtered_messages) != len(messages):- logger.debug(f"[LangGraph] Filtered out {len(messages) - len(filtered_messages)} empty messages")-- # Invoke the model- response = chat_model.invoke(filtered_messages)+ for iteration in range(1, max_iterations + 1):+ if progress_callback is not None:+ try:+ await progress_callback(iteration)+ except Exception as e:+ logger.debug(f"[Agent loop] progress_callback raised: {e}")- logger.debug(f"[LangGraph] LLM response type: {type(response).__name__}")+ filtered = filter_empty_messages(messages)+ response = await model.ainvoke(filtered)+ messages.append(response)- # Extract thinking content from response_, new_thinking = extract_thinking_from_response(response)-- # Accumulate thinking across iterations (for multi-step tool usage)- accumulated_thinking = existing_thinkingif new_thinking:- if accumulated_thinking:- accumulated_thinking = f"{accumulated_thinking}\n\n--- Iteration {iteration + 1} ---\n{new_thinking}"+ if thinking_accumulated:+ thinking_accumulated = (+ f"{thinking_accumulated}\n\n--- Iteration {iteration} ---\n{new_thinking}"+ )else:- accumulated_thinking = new_thinking- logger.debug(f"[LangGraph] Extracted thinking content ({len(new_thinking)} chars)")-- # Check for Gemini-specific response attributes (safety ratings, block reason)- if hasattr(response, 'response_metadata'):- meta = response.response_metadata- if meta.get('finish_reason') == 'SAFETY':- logger.warning("[LangGraph] Gemini response blocked by safety filters")- if meta.get('block_reason'):- logger.warning(f"[LangGraph] Gemini block reason: {meta.get('block_reason')}")-- # Check for tool calls in the response- pending_tool_calls = []- should_continue = False-- if hasattr(response, 'tool_calls') and response.tool_calls:- # Model wants to use tools- pending_tool_calls = response.tool_calls- should_continue = True- logger.debug(f"[LangGraph] Agent requesting {len(pending_tool_calls)} tool call(s)")- # Debug: log raw tool calls to diagnose empty args issue- for tc in pending_tool_calls:- logger.debug(f"[LangGraph] Raw tool_call object: {tc}")- logger.debug(f"[LangGraph] Tool call type: {type(tc)}, keys: {tc.keys() if hasattr(tc, 'keys') else 'N/A'}")-- return {- "messages": [response], # Will be appended via operator.add- "tool_outputs": {},- "pending_tool_calls": pending_tool_calls,- "iteration": iteration + 1,- "max_iterations": max_iterations,- "should_continue": should_continue,- "thinking_content": accumulated_thinking or None- }-- return agent_node---def create_tool_node(tool_executor: Callable):- """Create an async tool execution node for LangGraph.-- The tool node:- 1. Receives pending tool calls from agent- 2. Executes each tool via the async tool_executor callback- 3. Returns ToolMessages with results for the agent-- Note: This returns an async function for use with ainvoke().- LangGraph supports async node functions natively.- """- from langchain_core.messages import ToolMessage- async def tool_node(state: AgentState) -> Dict[str, Any]:- """Execute pending tool calls and return results as ToolMessages."""- tool_messages = []-- for tool_call in state.get("pending_tool_calls", []):- tool_name = tool_call.get("name", "unknown")- tool_args = tool_call.get("args", {})- tool_id = tool_call.get("id", "")+ thinking_accumulated = new_thinking++ # Gemini occasionally returns a blocked / safety-stopped response;+ # surface the same warning the legacy agent_node did so operators+ # can spot the cause in the logs.+ if hasattr(response, "response_metadata"):+ meta = response.response_metadata or {}+ if meta.get("finish_reason") == "SAFETY":+ logger.warning("[Agent loop] Gemini response blocked by safety filters")+ if meta.get("block_reason"):+ logger.warning(f"[Agent loop] Gemini block reason: {meta.get('block_reason')}")++ tool_calls = getattr(response, "tool_calls", None) or []+ if not tool_calls:+ return {+ "messages": messages,+ "iteration": iteration,+ "thinking_content": thinking_accumulated or None,+ "truncated": False,+ }- logger.debug(f"[LangGraph] Executing tool: {tool_name} (args={tool_args})")+ if tool_executor is None:+ logger.warning(+ "[Agent loop] LLM emitted %d tool_call(s) but no tool_executor "+ "configured; treating response as final",+ len(tool_calls),+ )+ return {+ "messages": messages,+ "iteration": iteration,+ "thinking_content": thinking_accumulated or None,+ "truncated": False,+ }+ for call in tool_calls:+ tool_name = call.get("name", "")+ tool_args = call.get("args", {}) or {}+ tool_id = call.get("id", "")try:- # Directly await the async tool executor (proper async pattern)result = await tool_executor(tool_name, tool_args)- logger.debug(f"[LangGraph] Tool {tool_name} returned: {str(result)[:100]}")except Exception as e:- logger.error(f"[LangGraph] Tool execution failed: {tool_name}", error=str(e))+ logger.error(f"[Agent loop] Tool {tool_name!r} raised: {e}")result = {"error": str(e)}-- # Create ToolMessage with result- tool_messages.append(ToolMessage(+ messages.append(ToolMessage(content=json.dumps(result, default=str),tool_call_id=tool_id,- name=tool_name+ name=tool_name,))- logger.debug(f"[LangGraph] Tool {tool_name} completed, result added to messages")-- return {- "messages": tool_messages,- "pending_tool_calls": [], # Clear pending after execution- }-- return tool_node---def should_continue(state: AgentState) -> str:- """Conditional edge: route to ``tools`` when the LLM emitted tool calls,- otherwise terminate the graph.-- The previous implementation tracked a custom ``iteration`` counter to cap- the loop. That counter shared a name with LangGraph internals and was- being mutated unexpectedly, causing the edge to return ``"end"`` on the- first tool call. The standard LangGraph pattern is to route purely on- pending tool calls and rely on ``recursion_limit`` (passed via- ``ainvoke(config=...)``) as the safety net.- """- if state.get("pending_tool_calls"):- return "tools"- return "end"---def build_agent_graph(chat_model, tools: List = None, tool_executor: Callable = None):- """Build the LangGraph agent workflow with optional tool support.-- Architecture (with tools):- START -> agent -> (conditional) -> tools -> agent -> ... -> END- |- +-> END (no tool calls)-- Architecture (without tools):- START -> agent -> END-- Args:- chat_model: The LangChain chat model- tools: Optional list of LangChain tools to bind to the model- tool_executor: Optional async callback to execute tools- """- from langgraph.graph import StateGraph, END- # Create the graph with our state schema- graph = StateGraph(AgentState)-- # Bind tools to model if provided- model_with_tools = chat_model- if tools:- model_with_tools = chat_model.bind_tools(tools)- logger.debug(f"[LangGraph] Bound {len(tools)} tools to model")-- # Add the agent node- agent_fn = create_agent_node(model_with_tools)- graph.add_node("agent", agent_fn)-- # Set entry point- graph.set_entry_point("agent")-- if tools and tool_executor:- # Add tool execution node- tool_fn = create_tool_node(tool_executor)- graph.add_node("tools", tool_fn)-- # Conditional routing: agent -> tools or end- graph.add_conditional_edges(- "agent",- should_continue,- {- "tools": "tools",- "end": END- }- )-- # Tools always route back to agent- graph.add_edge("tools", "agent")-- logger.debug("[LangGraph] Built graph with tool execution loop")- else:- # Simple graph without tools- graph.add_conditional_edges(- "agent",- should_continue,- {- "tools": "agent", # Fallback loop (shouldn't happen without tools)- "end": END- }- )-- # Compile the graph- return graph.compile()+ # Loop exited without returning -- hit max_iterations. Append a+ # terminal AIMessage so downstream extraction (and post-loop token+ # tracking / memory persistence) still have a usable state, matching+ # the legacy ``GraphRecursionError`` handler.+ messages.append(AIMessage(content=(+ f"[Recursion limit reached: {max_iterations} iterations. "+ f"Adjust agent.recursion_limit in llm_defaults.json or "+ f"simplify the task.]"+ )))+ logger.warning(+ f"[Agent loop] max_iterations hit ({max_iterations}); "+ f"returning partial response with {len(messages)} message(s)"+ )+ return {+ "messages": messages,+ "iteration": iteration,+ "thinking_content": thinking_accumulated or None,+ "truncated": True,+ }def _build_skill_system_prompt(skill_data: List[Dict[str, Any]], log_prefix: str = "[Agent]") -> tuple:@@ -1029,9 +919,6 @@ class AIService:# RLM service (lazy import to avoid circular deps)from services.rlm import RLMServiceself.rlm_service = RLMService(auth=self.auth)- # Deep Agent service (deepagents package)- from services.agents import DeepAgentService- self.deep_agent_service = DeepAgentService(auth=self.auth, model_factory=self.create_model, token_tracker=self._track_token_usage)def detect_provider(self, model: str) -> str:"""Detect AI provider from model name."""@@ -1070,7 +957,7 @@ class AIService:if extracted.strip():return extracted# List was present but no text extracted- logger.warning(f"[LangGraph] Content was list but no text extracted: {content}")+ logger.warning(f"[Agent] Content was list but no text extracted: {content}")# Handle string contentif isinstance(content, str) and content.strip():@@ -1129,13 +1016,13 @@ class AIService:# Generic empty response - log full response details for debuggingif ai_response:- logger.warning(f"[LangGraph] Empty response debug - content_blocks: {getattr(ai_response, 'content_blocks', None)}")- logger.warning(f"[LangGraph] Empty response debug - additional_kwargs: {getattr(ai_response, 'additional_kwargs', {})}")+ logger.warning(f"[Agent] Empty response debug - content_blocks: {getattr(ai_response, 'content_blocks', None)}")+ logger.warning(f"[Agent] Empty response debug - additional_kwargs: {getattr(ai_response, 'additional_kwargs', {})}")if hasattr(ai_response, 'response_metadata'):meta = ai_response.response_metadata- logger.warning(f"[LangGraph] Empty response debug - finish_reason: {meta.get('finish_reason')}")- logger.warning(f"[LangGraph] Empty response debug - token_usage: {meta.get('token_usage')}")- logger.warning(f"[LangGraph] Empty response with no error details. Content type: {type(content)}, value: {repr(content)}")+ logger.warning(f"[Agent] Empty response debug - finish_reason: {meta.get('finish_reason')}")+ logger.warning(f"[Agent] Empty response debug - token_usage: {meta.get('token_usage')}")+ logger.warning(f"[Agent] Empty response with no error details. Content type: {type(content)}, value: {repr(content)}")raise ValueError("AI generated empty response. Try rephrasing your prompt or using a different model.")async def _track_token_usage(@@ -1646,12 +1533,15 @@ class AIService:workflow_id: Optional[str] = None,context: Optional[Dict[str, Any]] = None,database = None) -> Dict[str, Any]:- """Execute AI Agent using LangGraph state machine.+ """Execute AI Agent via the plain-async agent loop.++ Drives :func:`_run_agent_loop` with the LangChain chat model returned by+ :meth:`create_model`. Each iteration: invoke the model, dispatch any+ ``tool_calls`` through the supplied closure, append ``ToolMessage`` results,+ loop until a final response (or the configured recursion limit hits).- This method uses LangGraph for structured agent execution with:- - State management via TypedDict- - Tool calling via bind_tools and tool execution node- - Message accumulation via operator.add pattern+ Features:+ - Tool calling via ``chat_model.bind_tools`` + the shared tool dispatcher- Real-time status broadcasts for UI animationsArgs:@@ -1666,7 +1556,6 @@ class AIService:context: Optional execution context with nodes, edges for nested agent delegation"""from langchain_core.messages import HumanMessage, SystemMessage, AIMessage- from langgraph.errors import GraphRecursionErrorstart_time = time.time()provider = 'unknown'model = 'unknown'@@ -1685,7 +1574,7 @@ class AIService:if broadcaster:await broadcaster.update_node_status(node_id, "executing", {"phase": phase,- "agent_type": "langgraph",+ "agent_type": "loop",**(details or {})}, workflow_id=workflow_id)@@ -1713,7 +1602,7 @@ class AIService:if model.startswith('[FREE] '):model = model[7:]- logger.debug(f"[LangGraph] Agent: {provider}/{model}, tools={len(tool_data) if tool_data else 0}")+ logger.debug(f"[Agent] Agent: {provider}/{model}, tools={len(tool_data) if tool_data else 0}")# If no model specified or model doesn't match provider, use default (DB > config)if not model or not is_model_valid_for_provider(model, provider):@@ -1740,7 +1629,7 @@ class AIService:level=flattened.get('thinking_level', 'medium'),format=flattened.get('reasoning_format', 'parsed'),)- logger.debug(f"[LangGraph] Thinking enabled: budget={thinking_config.budget}, effort={thinking_config.effort}")+ logger.debug(f"[Agent] Thinking enabled: budget={thinking_config.budget}, effort={thinking_config.effort}")temperature = _resolve_temperature(flattened, model, provider, bool(thinking_config and thinking_config.enabled))@@ -1755,7 +1644,7 @@ class AIService:proxy_url = await self.auth.get_api_key(f"{provider}_proxy")# Create LLM using the provider from node configuration- logger.debug(f"[LangGraph] Creating {provider} model: {model}")+ logger.debug(f"[Agent] Creating {provider} model: {model}")chat_model = self.create_model(provider, api_key, model, temperature, max_tokens, thinking_config, proxy_url)# Build initial messages for state. The SystemMessage is@@ -1798,14 +1687,14 @@ class AIService:if docs:context = "\n---\n".join(d.page_content for d in docs)initial_messages.append(SystemMessage(content=f"Relevant past context:\n{context}"))- logger.info(f"[LangGraph Memory] Retrieved {len(docs)} relevant memories from long-term store")+ logger.info(f"[Agent Memory] Retrieved {len(docs)} relevant memories from long-term store")except Exception as e:- logger.debug(f"[LangGraph Memory] Long-term retrieval skipped: {e}")+ logger.debug(f"[Agent Memory] Long-term retrieval skipped: {e}")# Add parsed history messagesinitial_messages.extend(history_messages)- logger.info(f"[LangGraph Memory] Loaded {history_count} messages from markdown")+ logger.info(f"[Agent Memory] Loaded {history_count} messages from markdown")# Broadcast: Memory loadedawait broadcast_status("memory_loaded", {@@ -1832,9 +1721,9 @@ class AIService:if tool:tools.append(tool)tool_configs[tool.name] = config- logger.debug(f"[LangGraph] Registered tool: name={tool.name}, node_id={config.get('node_id')}")+ logger.debug(f"[Agent] Registered tool: name={tool.name}, node_id={config.get('node_id')}")- logger.debug(f"[LangGraph] Built {len(tools)} tools")+ logger.debug(f"[Agent] Built {len(tools)} tools")# Auto-inject check_delegated_tasks tool when delegation tools presentif any(name.startswith('delegate_to_') for name in tool_configs):@@ -1848,7 +1737,7 @@ class AIService:if check_tool:tools.append(check_tool)tool_configs[check_tool.name] = check_config- logger.debug("[LangGraph] Auto-injected check_delegated_tasks tool")+ logger.debug("[Agent] Auto-injected check_delegated_tasks tool")# Add delegation guidance to system messagedelegate_names = [n for n in tool_configs if n.startswith('delegate_to_')]@@ -1877,8 +1766,8 @@ class AIService:config = tool_configs.get(tool_name, {})tool_node_id = config.get('node_id')- logger.debug(f"[LangGraph] Executing tool: {tool_name} (args={tool_args})")- logger.debug(f"[LangGraph] Tool node_id={tool_node_id}, workflow_id={workflow_id}")+ logger.debug(f"[Agent] Executing tool: {tool_name} (args={tool_args})")+ logger.debug(f"[Agent] Tool node_id={tool_node_id}, workflow_id={workflow_id}")# Parent-agent phase broadcast (does not touch tool node).await broadcast_status("executing_tool", {@@ -1911,40 +1800,21 @@ class AIService:except Exception as e:error_msg = str(e)- logger.error(f"[LangGraph] Tool execution failed: {tool_name}", error=error_msg)+ logger.error(f"[Agent] Tool execution failed: {tool_name}", error=error_msg)- # Re-raise to let LangGraph handle the error+ # Re-raise to let _run_agent_loop surface the error to the LLMraise- # Broadcast: Building graph+ # Broadcast: Building agentawait broadcast_status("building_graph", {- "message": "Building LangGraph agent...",+ "message": "Building agent...","message_count": len(initial_messages),"has_memory": bool(session_id),"history_count": history_count,"tool_count": len(tools)})- # Build and execute LangGraph agent- logger.debug(f"[LangGraph] Building agent graph with {len(initial_messages)} messages")- agent_graph = build_agent_graph(- chat_model,- tools=tools if tools else None,- tool_executor=tool_executor if tools else None- )-- # Create initial state with thinking_content for reasoning models- initial_state: AgentState = {- "messages": initial_messages,- "tool_outputs": {},- "pending_tool_calls": [],- "iteration": 0,- "max_iterations": 10,- "should_continue": False,- "thinking_content": None- }-- # Broadcast: Executing graph+ # Broadcast: Invoking LLMawait broadcast_status("invoking_llm", {"message": f"Invoking {provider} LLM...","provider": provider,@@ -1954,49 +1824,33 @@ class AIService:"history_count": history_count})- # Execute the graph. ``recursion_limit`` (cap on agent/tool- # supersteps) is sourced from llm_defaults.json so deployments- # tune it without code changes. On hit, synthesise a terminal- # AIMessage from whatever the agent produced before stopping- # so downstream extraction returns a usable partial response- # instead of failing the workflow.+ # Run the agent loop. ``recursion_limit`` (read from+ # llm_defaults.json:agent.recursion_limit) is the hard cap on+ # how many LLM turns the loop will run. The real termination+ # signal is the LLM returning a final response without tool+ # calls; this cap is the safety backstop. On hit, the loop+ # appends a synthetic terminal AIMessage so downstream+ # extraction returns a usable partial response.from services.model_registry import get_model_registryrecursion_limit = int(get_model_registry().get_agent_defaults()["recursion_limit"])- final_state = None- try:- async for snapshot in agent_graph.astream(- initial_state,- config={"recursion_limit": recursion_limit},- stream_mode="values",- ):- final_state = snapshot- # Per-step iteration broadcast (CloudEvents envelope- # via broadcast_agent_progress -> wire key- # `agent_progress`). The FE updates nodeStatusStore- # so the AI agent body shows live "iteration / max".- if broadcaster:- iter_count = snapshot.get("iteration", 0) if isinstance(snapshot, dict) else 0- await broadcaster.broadcast_agent_progress(- node_id,- workflow_id=workflow_id,- iteration=iter_count,- max_iterations=recursion_limit,- )- except GraphRecursionError:- # Append a terminal AIMessage so downstream extraction (and- # the post-loop _track_token_usage / compact_context call)- # still has a usable state instead of a half-built one.- msgs = list((final_state or {}).get("messages") or [])- msgs.append(AIMessage(content=(- f"[Recursion limit reached: {recursion_limit} supersteps. "- f"Adjust agent.recursion_limit in llm_defaults.json or "- f"simplify the task.]"- )))- final_state = {**(final_state or {}), "messages": msgs}- logger.warning(- f"[LangGraph] Recursion limit hit ({recursion_limit}); "- f"returning partial response with {len(msgs)} message(s)"- )++ async def _emit_progress(iter_count: int) -> None:+ if broadcaster:+ await broadcaster.broadcast_agent_progress(+ node_id,+ workflow_id=workflow_id,+ iteration=iter_count,+ max_iterations=recursion_limit,+ )++ final_state = await _run_agent_loop(+ chat_model,+ initial_messages,+ tools=tools if tools else None,+ tool_executor=tool_executor if tools else None,+ max_iterations=recursion_limit,+ progress_callback=_emit_progress if broadcaster else None,+ )# Extract the AI response (last message in the accumulated messages)all_messages = final_state["messages"]@@ -2013,7 +1867,7 @@ class AIService:# Get accumulated thinking content from statethinking_content = final_state.get("thinking_content")- logger.info(f"[LangGraph] Agent completed in {iterations} iteration(s), thinking={'yes' if thinking_content else 'no'}")+ logger.info(f"[Agent] Agent completed in {iterations} iteration(s), thinking={'yes' if thinking_content else 'no'}")# Track token usage if memory connected (for compaction service)# Also triggers compaction if threshold exceeded@@ -2050,7 +1904,7 @@ class AIService:updated_content = compaction_result['summary']updated_content = _append_to_memory_markdown(updated_content, 'human', prompt)updated_content = _append_to_memory_markdown(updated_content, 'ai', response_content)- logger.info("[LangGraph Memory] Using compacted summary as new base")+ logger.info("[Agent Memory] Using compacted summary as new base")else:# Normal flow: append to existing memoryupdated_content = memory_data.get('memory_content', '# Conversation History\n\n*No messages yet.*\n')@@ -2067,9 +1921,9 @@ class AIService:if store:try:store.add_texts(removed_texts)- logger.info(f"[LangGraph Memory] Archived {len(removed_texts)} messages to long-term store")+ logger.info(f"[Agent Memory] Archived {len(removed_texts)} messages to long-term store")except Exception as e:- logger.warning(f"[LangGraph Memory] Failed to archive to vector store: {e}")+ logger.warning(f"[Agent Memory] Failed to archive to vector store: {e}")# Save updated markdown to node parameters. Schema-# canonical key is snake_case; drop any pre-migration@@ -2079,7 +1933,7 @@ class AIService:current_params['memory_content'] = updated_contentcurrent_params.pop('memoryContent', None)await self.database.save_node_parameters(memory_node_id, current_params)- logger.info(f"[LangGraph Memory] Saved markdown to memory node '{memory_node_id}'")+ logger.info(f"[Agent Memory] Saved markdown to memory node '{memory_node_id}'")result = {"response": response_content,@@ -2087,7 +1941,7 @@ class AIService:"thinking_enabled": thinking_config.enabled if thinking_config else False,"model": model,"provider": provider,- "agent_type": "langgraph",+ "agent_type": "loop","iterations": iterations,"finish_reason": "stop","timestamp": datetime.now().isoformat(),@@ -2104,7 +1958,7 @@ class AIService:"history_loaded": history_count}- log_execution_time(logger, "ai_agent_langgraph", start_time, time.time())+ log_execution_time(logger, "ai_agent_loop", start_time, time.time())log_api_call(logger, provider, model, "agent", True)return {@@ -2123,7 +1977,7 @@ class AIService:raise NodeUserError(str(e)) from eexcept Exception as e:- logger.error("[LangGraph] AI agent execution failed", node_id=node_id, error=str(e))+ logger.error("[Agent] AI agent execution failed", node_id=node_id, error=str(e))log_api_call(logger, provider, model, "agent", False, error=str(e))return {@@ -2148,7 +2002,7 @@ class AIService:Chat Agent supports:- Memory (input-memory): Markdown-based conversation history (same as AI Agent)- Skills (input-skill): Provide context/instructions via SKILL.md- - Tools (input-tools): Tool nodes (httpRequest, etc.) for LangGraph tool calling+ - Tools (input-tools): Tool nodes (httpRequest, etc.) for agent tool callingArgs:node_id: The node identifier@@ -2161,7 +2015,6 @@ class AIService:context: Optional execution context with nodes, edges for nested agent delegation"""from langchain_core.messages import HumanMessage, SystemMessage, AIMessage- from langgraph.errors import GraphRecursionErrorstart_time = time.time()provider = 'unknown'model = 'unknown'@@ -2356,8 +2209,8 @@ class AIService:iterations = 1if all_tools:- # Use LangGraph for tool execution (like AI Agent)- logger.debug(f"[ChatAgent] Using LangGraph with {len(all_tools)} tools")+ # Use the agent loop for tool execution (like AI Agent)+ logger.debug(f"[ChatAgent] Using agent loop with {len(all_tools)} tools")# Create tool executor callback. Tool-node status lifecycle# is owned by ``handlers.tools.execute_tool`` (single source@@ -2391,60 +2244,31 @@ class AIService:logger.error(f"[ChatAgent] Tool execution failed: {tool_name}", error=str(e))return {"error": str(e)}- # Build LangGraph agent with all tools- agent_graph = build_agent_graph(- chat_model,- tools=all_tools,- tool_executor=chat_tool_executor- )-- # Create initial state- initial_state: AgentState = {- "messages": messages,- "tool_outputs": {},- "pending_tool_calls": [],- "iteration": 0,- "max_iterations": 10,- "should_continue": False,- "thinking_content": None- }-- # Execute the graph. ``recursion_limit`` is sourced from- # llm_defaults.json; see ``execute_agent`` for the rationale.+ # Run the agent loop. See ``execute_agent`` for the+ # rationale on ``recursion_limit`` + the truncation+ # behaviour on hit.from services.model_registry import get_model_registryrecursion_limit = int(get_model_registry().get_agent_defaults()["recursion_limit"])- final_state = None- try:- async for snapshot in agent_graph.astream(- initial_state,- config={"recursion_limit": recursion_limit},- stream_mode="values",- ):- final_state = snapshot- # Per-step iteration broadcast — see execute_agent- # for the rationale.- if broadcaster:- iter_count = snapshot.get("iteration", 0) if isinstance(snapshot, dict) else 0- await broadcaster.broadcast_agent_progress(- node_id,- workflow_id=workflow_id,- iteration=iter_count,- max_iterations=recursion_limit,- )- except GraphRecursionError:- msgs = list((final_state or {}).get("messages") or [])- msgs.append(AIMessage(content=(- f"[Recursion limit reached: {recursion_limit} supersteps. "- f"Adjust agent.recursion_limit in llm_defaults.json or "- f"simplify the task.]"- )))- final_state = {**(final_state or {}), "messages": msgs}- logger.warning(- f"[LangGraph] Recursion limit hit ({recursion_limit}); "- f"returning partial response with {len(msgs)} message(s)"- )++ async def _emit_progress(iter_count: int) -> None:+ if broadcaster:+ await broadcaster.broadcast_agent_progress(+ node_id,+ workflow_id=workflow_id,+ iteration=iter_count,+ max_iterations=recursion_limit,+ )++ final_state = await _run_agent_loop(+ chat_model,+ messages,+ tools=all_tools,+ tool_executor=chat_tool_executor,+ max_iterations=recursion_limit,+ progress_callback=_emit_progress if broadcaster else None,+ )# Extract responseall_messages = final_state["messages"]@@ -2664,7 +2488,6 @@ class AIService:'ai_employee': 'delegate_to_ai_employee','rlm_agent': 'delegate_to_rlm_agent','claude_code_agent': 'delegate_to_claude_code_agent',- 'deep_agent': 'delegate_to_deep_agent',# Android service nodes (direct tool usage)'batteryMonitor': 'android_battery','networkMonitor': 'android_network',@@ -2798,7 +2621,7 @@ class AIService:if db_schema:# Use database schema as source of truth- logger.debug(f"[LangGraph] Using DB schema for tool node {node_id}")+ logger.debug(f"[Agent] Using DB schema for tool node {node_id}")tool_name = db_schema.get('tool_name', DEFAULT_TOOL_NAMES.get(node_type, f"tool_{node_label}"))tool_description = db_schema.get('tool_description', DEFAULT_TOOL_DESCRIPTIONS.get(node_type, f"Execute {node_label}"))# Use stored connected_services if available (for toolkit nodes)@@ -2843,7 +2666,7 @@ class AIService:f"This agent has the following capabilities:\n{capabilities_text}\n"f"Call ONCE per task, returns task_id. Agent works in background.")- logger.info(f"[LangGraph] Enhanced tool description for {node_type} with {len(child_tools)} child tools")+ logger.info(f"[Agent] Enhanced tool description for {node_type} with {len(child_tools)} child tools")# Clean tool name (LangChain requires alphanumeric + underscores)import re@@ -2878,11 +2701,11 @@ class AIService:'connected_services': connected_services # Pass through for execution}- logger.debug(f"[LangGraph] Built tool '{tool_name}' with node_id={node_id}")+ logger.debug(f"[Agent] Built tool '{tool_name}' with node_id={node_id}")return tool, configexcept Exception as e:- logger.error(f"[LangGraph] Failed to build tool from node: {e}")+ logger.error(f"[Agent] Failed to build tool from node: {e}")return None, Nonedef _get_tool_schema(self, node_type: str, params: Dict[str, Any]) -> Type[BaseModel]:@@ -2913,7 +2736,7 @@ class AIService:'task_agent', 'social_agent', 'travel_agent', 'tool_agent','productivity_agent', 'payments_agent', 'consumer_agent','autonomous_agent', 'orchestrator_agent', 'ai_employee',- 'rlm_agent', 'claude_code_agent', 'deep_agent',+ 'rlm_agent', 'claude_code_agent',)if node_type in _AGENT_DELEGATION_TYPES:agent_label = params.get('label', node_type)diff --git a/server/services/events/envelope.py b/server/services/events/envelope.pyindex 1e8c322d..9b7cc749 100644--- a/server/services/events/envelope.py+++ b/server/services/events/envelope.py@@ -222,13 +222,12 @@ class WorkflowEvent(BaseModel):phase: Optional[str] = None,data: Optional[Mapping[str, Any]] = None,) -> "WorkflowEvent":- """Live LangGraph supervised-loop progress for one agent node.+ """Live agent-loop progress for one agent node.- Emitted from inside the ``astream`` loop in+ Emitted from inside the agent loop in``services/ai.py:execute_agent`` and ``execute_chat_agent`` after- each super-step. ``iteration`` advances on every ``agent_node``- invocation; ``max_iterations`` mirrors the LangGraph- ``recursion_limit`` (sourced from+ each LLM turn. ``iteration`` advances on every model invocation;+ ``max_iterations`` mirrors the loop's hard cap (sourced from``llm_defaults.json:agent.recursion_limit``).``subject`` carries the executing node id so the FE routes thediff --git a/server/services/handlers/tools.py b/server/services/handlers/tools.pyindex 599e706c..8f670f88 100644--- a/server/services/handlers/tools.py+++ b/server/services/handlers/tools.py@@ -147,7 +147,7 @@ async def _dispatch_tool(tool_name: str, tool_args: Dict[str, Any],# Execution context for tool handlers. Includes canvas state# (nodes/edges/workflow_id) that callers (chat_tool_executor in- # ai.py / rlm adapter / deepagents adapter) plumb in via `config`.+ # ai.py / rlm adapter) plumb in via `config`.# Tools that need canvas awareness (e.g. agentBuilder.inspect_canvas)# read these via NodeContext.nodes / .edges / .workflow_id; tools# that don't simply ignore them.diff --git a/server/services/memory/__init__.py b/server/services/memory/__init__.pyindex d0737f90..56808193 100644--- a/server/services/memory/__init__.py+++ b/server/services/memory/__init__.py@@ -4,7 +4,7 @@ Reorganised from the single-file ``services/memory.py`` so eachstorage format / concern owns its own module:- :mod:`services.memory.markdown` — markdown parse/append/trim- (used by aiAgent / chatAgent / deep_agent / rlm_agent)+ (used by aiAgent / chatAgent / rlm_agent)- :mod:`services.memory.jsonl` — Anthropic Messages JSONLparse/append/trim (used by claude_code_agent's session bridge)- :mod:`services.memory.vector_store` — per-session@@ -35,7 +35,7 @@ from services.memory.jsonl import (__all__ = [# Markdown helpers — used by every agent bridge (aiAgent /- # chatAgent / deep_agent / rlm_agent / claude_code_agent).+ # chatAgent / rlm_agent / claude_code_agent)."parse_memory_markdown","append_to_memory_markdown","trim_markdown_window",diff --git a/server/services/memory/markdown.py b/server/services/memory/markdown.pyindex f0a783f9..54a8c1ee 100644--- a/server/services/memory/markdown.py+++ b/server/services/memory/markdown.py@@ -2,8 +2,8 @@Parse, append, and trim conversation history stored in the bespoke``### **Human/Assistant** (timestamp)`` markdown format. Used by-aiAgent, chatAgent, deep_agent, and rlm_agent for persistent memory-across turns. The claude_code_agent bridge uses the JSONL helpers in+aiAgent, chatAgent, and rlm_agent for persistent memory across turns.+The claude_code_agent bridge uses the JSONL helpers in:mod:`services.memory.jsonl` instead."""diff --git a/server/services/model_registry.py b/server/services/model_registry.pyindex 1c25aaf5..958fbbc7 100644--- a/server/services/model_registry.py+++ b/server/services/model_registry.py@@ -562,7 +562,7 @@ class ModelRegistryService:def get_agent_defaults(self) -> Dict[str, Any]:"""Return the ``agent`` block from ``llm_defaults.json``.- Holds runtime defaults shared across the LangGraph executor and+ Holds runtime defaults shared across the agent executor andcompaction layer (e.g. ``recursion_limit``, ``compaction.ratio``).Callers should ``.get(...)`` with their own fallback so the systemstill boots if the JSON is missing or partial.diff --git a/server/services/node_output_schemas.py b/server/services/node_output_schemas.pyindex 65b5cc90..48068275 100644--- a/server/services/node_output_schemas.py+++ b/server/services/node_output_schemas.py@@ -732,7 +732,6 @@ _AGENT_TYPES = ["ai_employee","rlm_agent","claude_code_agent",- "deep_agent",]_CHAT_MODEL_TYPES = [diff --git a/server/services/plugin/edge_walker.py b/server/services/plugin/edge_walker.pyindex 331b8ab4..09885051 100644--- a/server/services/plugin/edge_walker.py+++ b/server/services/plugin/edge_walker.py@@ -3,8 +3,8 @@Pure functions extracted from ``services/handlers/ai.py`` so everyagent plugin can call them without depending on the legacy handlermodule. Used by :class:`AIAgentNode`, :class:`ChatAgentNode`,-:class:`SpecializedAgentBase`, :class:`DeepAgentNode`,-:class:`RLMAgentNode`, :class:`ClaudeCodeAgentNode`.+:class:`SpecializedAgentBase`, :class:`RLMAgentNode`,+:class:`ClaudeCodeAgentNode`.Three helpers:@@ -14,7 +14,7 @@ Three helpers:``masterSkill`` expansion + the ``androidTool`` Sub-Node pattern +child-agent tool discovery.- :func:`collect_teammate_connections` — walks ``input-teammates``- edges (orchestrator / ai_employee / deep_agent team-lead pattern).+ edges (orchestrator / ai_employee team-lead pattern).- :func:`format_task_context` — renders ``taskTrigger`` payload as aprompt prepend block.@@ -417,7 +417,7 @@ async def collect_teammate_connections() -> List[Dict[str, Any]]:"""Walk ``input-teammates`` edges and return connected agents.- Used by ``orchestrator_agent`` / ``ai_employee`` / ``deep_agent``.+ Used by ``orchestrator_agent`` / ``ai_employee``."""nodes = context.get("nodes", [])edges = context.get("edges", [])diff --git a/server/services/rlm/service.py b/server/services/rlm/service.pyindex 99032299..182b471c 100644--- a/server/services/rlm/service.py+++ b/server/services/rlm/service.py@@ -1,7 +1,7 @@"""RLM execution service.Follows the same interface as AIService.execute_agent() / execute_chat_agent()-but replaces LangGraph with RLM's REPL-based execution loop.+but replaces the agent loop with RLM's REPL-based execution."""import asynciodiff --git a/server/services/temporal/activities.py b/server/services/temporal/activities.pyindex 34f1f0fc..73f404c6 100644--- a/server/services/temporal/activities.py+++ b/server/services/temporal/activities.py@@ -177,8 +177,8 @@ class NodeExecutionActivities:avoiding race conditions when multiple activities run concurrently.Heartbeats are sent both on incoming non-matching messages AND on a- 30-second timer. This is critical for long-running nodes (DeepAgent,- browser, AI multi-tool) where the backend may be processing internally+ 30-second timer. This is critical for long-running nodes (browser,+ AI multi-tool, claude_code_agent) where the backend may be processing internallywithout broadcasting any WS messages for minutes. Without the periodictimer, the 2-minute heartbeat_timeout would cancel the activity eventhough the node is actively executing.diff --git a/server/services/temporal/agent_activities.py b/server/services/temporal/agent_activities.pyindex 275d9265..c959e2d8 100644--- a/server/services/temporal/agent_activities.py+++ b/server/services/temporal/agent_activities.py@@ -1,10 +1,10 @@"""F4.B: per-turn agent activities for ``AgentWorkflow``.-The legacy ``execute_agent`` / ``execute_chat_agent`` in ``services/ai.py``-run an entire LangGraph loop inside a single Temporal activity. F4.B-splits that loop across Temporal workflow boundaries so tool calls can-land as separate activities on per-type worker pools (per RFC §6.3-plus the F4 deferred follow-up). Activities defined here:+The in-process ``execute_agent`` / ``execute_chat_agent`` in+``services/ai.py`` run the entire agent loop inside a single Temporal+activity. F4.B splits that loop across Temporal workflow boundaries so+tool calls can land as separate activities on per-type worker pools (per+RFC §6.3 plus the F4 deferred follow-up). Activities defined here:- :func:`execute_llm_step` — one ``chat_model.ainvoke()`` turn. Returnseither ``{"kind": "final", ...}`` (no tool calls) or@@ -313,8 +313,8 @@ async def broadcast_agent_progress(payload: Dict[str, Any]) -> Dict[str, Any]:cannot call broadcaster methods directly — they have to go throughan activity).- Wire-format key ``agent_progress`` is the same channel the legacy- LangGraph path uses (services/ai.py:execute_agent), and the inner+ Wire-format key ``agent_progress`` is the same channel the in-process+ agent-loop path uses (services/ai.py:execute_agent), and the innerpayload is a CloudEvents v1.0 ``WorkflowEvent`` with``type="com.machinaos.agent.progress"``. The FE routes``data.iteration`` / ``data.max_iterations`` into@@ -408,7 +408,8 @@ async def prepare_agent_payload(context: Dict[str, Any]) -> Dict[str, Any]:workflow is scheduled and returns the fully-resolved payload.Mirrors the prep half of ``services.ai.AIService.execute_agent``,- minus the LangGraph loop (which now lives in ``AgentWorkflow.run``):+ minus the agent loop (which lives in ``AgentWorkflow.run`` for the+ F4.B Temporal path and ``services.ai._run_agent_loop`` in-process):1. Read node parameters from DB via ``database.get_node_parameters``.2. Walk edges via ``services.plugin.edge_walker.collect_agent_connections``diff --git a/server/services/temporal/agent_workflow.py b/server/services/temporal/agent_workflow.pyindex 36c4b27b..0583c360 100644--- a/server/services/temporal/agent_workflow.py+++ b/server/services/temporal/agent_workflow.py@@ -1,10 +1,10 @@"""F4.B: ``AgentWorkflow`` — Temporal child workflow for AI agent loops.-Replaces the inline LangGraph loop inside ``services/ai.py:execute_agent``-with a workflow-orchestrated loop: each LLM turn is an activity, each-tool call is a per-type activity (registered via-``BaseNode.as_activity()``, F4.A), and memory persistence happens per-turn so a workflow failure mid-loop doesn't lose progress.+Workflow-orchestrated alternative to the in-process ``_run_agent_loop``+inside ``services/ai.py``: each LLM turn is an activity, each tool call+is a per-type activity (registered via ``BaseNode.as_activity()``,+F4.A), and memory persistence happens per turn so a workflow failure+mid-loop doesn't lose progress.Architecture (matches Temporal's AI Cookbook canonical pattern):@@ -22,14 +22,14 @@ Architecture (matches Temporal's AI Cookbook canonical pattern):User decisions baked in (plan §15):- **Path 1** (agent-as-child-workflow), confirmed.-- ``deep_agent``, ``rlm_agent``, ``claude_code_agent`` are NOT migrated- here. Their loops are externalised (deepagents / RLM REPL / Claude- CLI ``--resume`` session) and live in single Temporal activities via- the F4.A per-type dispatch path. They never enter ``AgentWorkflow``.+- ``rlm_agent``, ``claude_code_agent`` are NOT migrated here. Their+ loops are externalised (RLM REPL / Claude CLI ``--resume`` session)+ and live in single Temporal activities via the F4.A per-type+ dispatch path. They never enter ``AgentWorkflow``.- Memory appends per turn (not on completion).- Tool activity failure (after retries) returns an error to the LLM as- a ``ToolMessage`` and the agent continues — matches today's LangGraph- behaviour.+ a ``ToolMessage`` and the agent continues — matches the in-process+ ``_run_agent_loop`` behaviour.Determinism:- ``sandboxed=False`` so we can import frozen registry dicts@@ -90,8 +90,8 @@ class AgentWorkflow:- the node type is in the migrating set (``aiAgent``,``chatAgent``, 12 specialized agents, 2 team leads).- ``deep_agent`` / ``rlm_agent`` / ``claude_code_agent`` skip this- workflow and stay as F4.A per-type activities.+ ``rlm_agent`` / ``claude_code_agent`` skip this workflow and stay+ as F4.A per-type activities."""@workflow.run@@ -224,7 +224,7 @@ class AgentWorkflow:)# CloudEvents-shaped agent_progress per LLM turn. Mirrors the- # legacy LangGraph path's super-step broadcast (RFC §6.4).+ # the in-process agent loop's per-turn broadcast (RFC §6.4).# FE consumes the typed envelope and updates the canvas# node's "N / max" iteration badge live.await self._emit_phase(@@ -356,7 +356,7 @@ class AgentWorkflow:except Exception as e: # noqa: BLE001 — Temporal handles retries# After all retries exhausted, surface the error to# the LLM (per user decision: LLM sees error and- # continues — matches LangGraph today).+ # continues — matches the in-process agent loop).workflow.logger.warning(f"AgentWorkflow tool {tool_info['node_type']!r} failed: {e}")diff --git a/server/services/temporal/workflow.py b/server/services/temporal/workflow.pyindex 05780d58..4446b282 100644--- a/server/services/temporal/workflow.py+++ b/server/services/temporal/workflow.py@@ -44,10 +44,10 @@ SKILL_NODE_TYPES = {# AgentWorkflow for these node types instead of an activity. Tool calls# inside the agent loop become per-type activities (F4.A path).#-# Excluded: ``deep_agent``, ``rlm_agent``, ``claude_code_agent``. Their-# internal session state (deepagents package / RLM REPL / Claude CLI-# --resume with stable cwd) requires single-process continuity and breaks-# across activity boundaries. They continue via F4.A per-type activities.+# Excluded: ``rlm_agent``, ``claude_code_agent``. Their internal session+# state (RLM REPL / Claude CLI --resume with stable cwd) requires+# single-process continuity and breaks across activity boundaries. They+# continue via F4.A per-type activities.AGENT_WORKFLOW_TYPES = frozenset(["aiAgent","chatAgent",diff --git a/server/tests/nodes/test_specialized_agents.py b/server/tests/nodes/test_specialized_agents.pyindex a277e381..fdee70be 100644--- a/server/tests/nodes/test_specialized_agents.py+++ b/server/tests/nodes/test_specialized_agents.py@@ -5,7 +5,7 @@ Covers:(android_agent, coding_agent, web_agent, task_agent, social_agent,travel_agent, tool_agent, productivity_agent, payments_agent,consumer_agent, autonomous_agent, orchestrator_agent, ai_employee)-- 3 dedicated-handler agents (deep_agent, rlm_agent, claude_code_agent)+- 2 dedicated-handler agents (rlm_agent, claude_code_agent)These freeze the input -> output behaviour documented in`docs-internal/node-logic-flows/specialized_agents/`. A refactor that breaks@@ -259,121 +259,6 @@ class TestGenericSpecializedAgents:assert result["error"] == "model unavailable"-# ============================================================================-# Deep Agent-# ============================================================================---class TestDeepAgent:- def _wire_deep_agent_service(self, harness, response=None):- """Attach a mock deep_agent_service.execute to the harness AI service."""- deep_service = MagicMock(name="DeepAgentService")- deep_service.execute = AsyncMock(- return_value=response- or {- "success": True,- "result": {- "response": "deep done",- "model": "claude-sonnet-4-6",- "provider": "anthropic",- },- }- )- harness.ai_service.deep_agent_service = deep_service- # _build_tool_from_node is passed through as build_tool_fn kwarg.- harness.ai_service._build_tool_from_node = MagicMock(return_value=None)- return deep_service-- async def test_happy_path_delegates_to_deep_agent_service(self, harness):- deep_service = self._wire_deep_agent_service(harness)-- with patched_container(auth_api_keys={"anthropic": "tk"}), patched_broadcaster():- result = await harness.execute(- "deep_agent",- {- "provider": "anthropic",- "model": "claude-sonnet-4-6",- "prompt": "plan something",- },- )-- harness.assert_envelope(result, success=True)- assert result["result"]["response"] == "deep done"- assert deep_service.execute.await_count == 1-- async def test_workspace_dir_injected_into_parameters(self, harness):- deep_service = self._wire_deep_agent_service(harness)-- ctx = harness.build_context(workspace_dir="/tmp/fake_workspace")-- with patched_container(auth_api_keys={"anthropic": "tk"}), patched_broadcaster():- await harness.execute(- "deep_agent",- {- "provider": "anthropic",- "model": "claude-sonnet-4-6",- "prompt": "x",- },- context=ctx,- )-- args, kwargs = deep_service.execute.await_args- # args[1] is the parameters dict that the handler built.- assert args[1]["workspace_dir"] == "/tmp/fake_workspace"-- async def test_missing_deep_agent_service_surfaces_as_failure(self, harness):- """When deep_agent_service is absent, the executor wraps the- AttributeError into a failure envelope via its generic try/except."""- # Do NOT attach deep_agent_service. Accessing it on a MagicMock- # returns a new child mock, so we need to explicitly break it.- bad_service = MagicMock(spec=[]) # no attributes at all- harness.ai_service.deep_agent_service = bad_service-- with patched_container(auth_api_keys={"anthropic": "tk"}), patched_broadcaster():- result = await harness.execute(- "deep_agent",- {- "provider": "anthropic",- "model": "claude-sonnet-4-6",- "prompt": "x",- },- )-- harness.assert_envelope(result, success=False)-- async def test_teammate_handle_collected_for_deep_agent(self, harness):- deep_service = self._wire_deep_agent_service(harness)-- nodes = [- {"id": "mate-1", "type": "coding_agent", "data": {"label": "coder"}},- {"id": "deep-1", "type": "deep_agent"},- ]- edges = [- {- "source": "mate-1",- "target": "deep-1",- "targetHandle": "input-teammates",- },- ]- ctx = harness.build_context(nodes=nodes, edges=edges)-- with patched_container(auth_api_keys={"anthropic": "tk"}), patched_broadcaster():- await harness.execute(- "deep_agent",- {- "provider": "anthropic",- "model": "claude-sonnet-4-6",- "prompt": "x",- },- node_id="deep-1",- context=ctx,- )-- _, kwargs = deep_service.execute.await_args- teammates = kwargs.get("teammates") or []- assert any(t["node_id"] == "mate-1" for t in teammates)--# ============================================================================# RLM Agent# ============================================================================diff --git a/server/tests/temporal/test_dispatch.py b/server/tests/temporal/test_dispatch.pyindex 2c448e97..50143215 100644--- a/server/tests/temporal/test_dispatch.py+++ b/server/tests/temporal/test_dispatch.py@@ -106,8 +106,8 @@ class TestResolveActivityFlagOn:class TestAgentWorkflowDispatch:"""F4.B: when the agent-workflow flag is on AND the node type is inAGENT_WORKFLOW_TYPES, dispatch must route through the child workflow- instead of an activity. Excluded types (deep_agent / rlm_agent /- claude_code_agent) keep using the activity path."""+ instead of an activity. Excluded types (rlm_agent / claude_code_agent)+ keep using the activity path."""def _set_flags(self, *, per_type: bool, agent_wf: bool):from types import SimpleNamespace@@ -141,10 +141,10 @@ class TestAgentWorkflowDispatch:)def test_excluded_agents_stay_on_activity_path(self, workflow_instance):- """deep_agent / rlm_agent / claude_code_agent are NOT migrated- (externalised session state). They must use the per-type activity- path even when F4.B is on."""- for t in ("deep_agent", "rlm_agent", "claude_code_agent"):+ """rlm_agent / claude_code_agent are NOT migrated (externalised+ session state). They must use the per-type activity path even+ when F4.B is on."""+ for t in ("rlm_agent", "claude_code_agent"):with self._set_flags(per_type=True, agent_wf=True):dispatch = workflow_instance._resolve_dispatch(t)assert dispatch["kind"] == "activity", (diff --git a/server/tests/test_node_spec.py b/server/tests/test_node_spec.pyindex c793894a..5a69dc2a 100644--- a/server/tests/test_node_spec.py+++ b/server/tests/test_node_spec.py@@ -74,8 +74,8 @@ class TestInputSchemas:assert schema["groups"]["options"]["placeholder"] == "Add Option"def test_specialized_agents_share_schema(self):- # All 16 specialized agents go through SpecializedAgentParams- for agent_type in ["android_agent", "coding_agent", "deep_agent"]:+ # Specialized agents go through SpecializedAgentParams+ for agent_type in ["android_agent", "coding_agent", "web_agent"]:assert get_node_input_schema(agent_type) is not Nonedef test_android_service_nodes_covered(self):@@ -224,7 +224,7 @@ class TestPhase3cCoverage:"social_agent", "travel_agent", "tool_agent", "productivity_agent","payments_agent", "consumer_agent", "autonomous_agent","orchestrator_agent", "ai_employee", "rlm_agent",- "claude_code_agent", "deep_agent",+ "claude_code_agent",# Chat models (9)"openaiChatModel", "anthropicChatModel", "geminiChatModel","openrouterChatModel", "groqChatModel", "cerebrasChatModel",@@ -872,9 +872,9 @@ class TestPluginContractInvariants:)def test_agent_kind_has_skill_tool_memory_handles(self):- # Contract: anything registered as a LangGraph-style agent must- # accept skill, tools, memory, and task inputs (the core n8n- # AIAgent handle set). Keeps the AIAgentNode renderer honest.+ # Contract: anything registered as an agent must accept skill,+ # tools, memory, and task inputs (the core n8n AIAgent handle+ # set). Keeps the AIAgentNode renderer honest.for t in self._plugin_types():spec = get_node_spec(t)if spec.get("componentKind") != "agent":