Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
docs: correct the Context/Memory model and the statements that were false
trohitg7d17d1962aa3
diff --git a/CLAUDE.md b/CLAUDE.mdindex 340d748e..1e9b3a97 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -16,7 +16,7 @@ This is a React Flow-based workflow automation platform implementing n8n-inspire| **[Theme System](./docs-internal/theme_system.md)** | 12-way visual theme system — 2 base (light, dark) + 5 utopian (renaissance, greek, edo, steampunk, atomic) + 5 dystopian (cyber, wasteland, rot, plague, surveillance) — driven by `<html data-theme>` + per-theme CSS files in `client/src/themes/`. Token taxonomy (surface / fg / border / accent / typography / motion) in **hex + `color-mix()`**; `@theme inline` bridge maps `--color-X: var(--X)` (no `hsl()` wrapper); per-theme files own the colour hex, base.css owns the shared `--tint-*` alpha scale; action role tokens (incl. `-ink` readable text), **per-theme `--code-*` syntax tokens** (tier 6 — the code editor, console/output JSON viewers, and chat code blocks paint in each theme's own palette: keyword→trigger, string→success, number→agent, function→model, on an adaptive dark/light code surface; replaced the global dracula `--prism-*` block + dead `getPrismTokenCSS`; the `OutputPanel` JSON viewer reads the same vars), per-theme `--pulse-keyframe` animation system + `.opencompany-*` helpers in `animations.css`, decorative-layer wrappers (`.app-frame` / `.canvas-host` / `.modal-frame`), per-component decorative ornaments (panel textures + canvas decorations + node pseudo-element overlays + theme-specific keyframes), **canvas-node visual contract via `--node-color` CSS custom property** (no inline `background` / `border` on node components — base.css + per-theme CSS owns visuals; `NodeStyle` helper type at [types/NodeTypes.ts](./client/src/types/NodeTypes.ts) makes the inline custom-prop typecheck-clean), **`--node-pulse-color` separate from `--node-color`** so executing-node glow uses each theme's highest-contrast accent regardless of plugin accent (Cyber neon cyan, Surveillance REC red, Renaissance ultramarine, etc.), **`data-page-hidden` animation pause** (toggled by Dashboard's `visibilitychange` listener; base.css declares `html[data-page-hidden] *, *::before, *::after { animation-play-state: paused !important }` to prevent compositor stall on tab return), **per-theme icon glyph system** (290 SVGs across 29 keys × 10 themes via [themedGlyphs.ts](./client/src/assets/icons/themedGlyphs.ts) + theme-aware [NodeIcon.tsx](./client/src/assets/icons/NodeIcon.tsx)), **per-theme canvas-grid + custom cursors** via `--canvas-grid` / `--cursor-default` slots, **decorative HTML primitives** (`<SvgFilterDefs>` mounting `#ink-blot` / `#noise` / `#crt` filter IDs at app root, `<DropCap>` wrapper for Renaissance ornament rule), **parameter panel migrated to Tailwind tokens** (no `useAppTheme()` reads; section headers carry the display-typography triplet; raw `<Button>` swapped to `<ActionButton intent>`), **per-theme scrollbar webkit rules** in all 12 themes, 9-event WebAudio sound system (10 packs via `--sound-pack` token + `useSound()` hook + global hover delegate + sonner toast monkey-patch + `withSound()` HOC + `Sounds.unlock()` gesture-unlock for AudioContext autoplay-policy compliance), `@media (prefers-reduced-motion: reduce)` accessibility, 30 ms throttle on `type` / `hover`, migration recipe, anti-patterns. Read this before adding a new theme, migrating a component to the new contract, or adding a canvas-node component. || **[Design System Bundle](./docs-internal/design-system/IMPLEMENTATION.md)** | Canonical, vendored design-system reference (extracted from this repo; see its `IMPLEMENTATION.md` for the contract). Tokens are **hex + `color-mix()`** (`tokens/{colors,typography,spacing,motion,fonts,base}.css`) — the format the live codebase standardizes on. Includes 34 reference components (`components/`, inline-style reference only — recreate in Tailwind/shadcn idioms), full-app UI kit (`ui_kits/opencompany/index.html`), and 12-theme docs (`guidelines/THEMES.md`, `reference/themes/`). Copy token values verbatim; do not re-derive by eye. Pairs with [Theme System](./docs-internal/theme_system.md). || **[Schema Source of Truth RFC](./docs-internal/schema_source_of_truth_rfc.md)** | Backend is SSOT for node schemas, visual metadata, handlers, palette metadata, icons. Plugin pattern: one `BaseNode` subclass in `server/nodes/<group>/<plugin>/__init__.py`. Wire format: `asset:<key>` / `<lib>:<brand>` / URL / emoji. Endpoint: `/api/schemas/nodes/{type}/spec.json`. Live invariant total via `pytest --collect-only`. |-| **[Plugin System (Wave 11)](./docs-internal/plugin_system.md)** | Class-based plugin-first architecture. `BaseNode` / `ActionNode` / `TriggerNode` / `ToolNode` + `@Operation` decorator. Pydantic `Params`/`Output`. Declarative `Routing` DSL + `Connection` facade (Nango pattern; `request()` supports `json` / `data` / `files` — the last for multipart uploads, threaded through the auth-retry rebuild). `Credential` subclasses live in each node folder's `_credentials.py` (or inline for single-use); live count via `len(services.plugin.credential.CREDENTIAL_REGISTRY)` — 30 at time of writing, do not hand-maintain. `TaskQueue` constants route to Temporal worker pools. Plugins live across 9 queues (live count via `glob server/nodes/**/__init__.py`); handler bodies fully inlined (`services/handlers/` shrank 12.8K → 1.1K LOC across 16 → 4 files; only cross-cutting orchestration remains: `tools.py` AI-tool dispatch + agent delegation, `triggers.py` generic trigger-node handler, `todo.py` writeTodos shim — `google_auth.py` was retired into `nodes/google/_auth_helper.py`). **Wave 11.H added "self-contained plugin folders"** — up to six generic registries (`ws_handler_registry`, `register_router`, `event_waiter.{register_filter_builder,register_trigger_precheck}`, `status_broadcaster.register_service_refresh`, `node_output_schemas.register_output_schema`) so rich plugins like telegram own their entire surface area without core-services edits. |+| **[Plugin System (Wave 11)](./docs-internal/plugin_system.md)** | Class-based plugin-first architecture. `BaseNode` / `ActionNode` / `TriggerNode` / `ToolNode` + `@Operation` decorator. Pydantic `Params`/`Output`. Declarative `Routing` DSL + `Connection` facade (Nango pattern; `request()` supports `json` / `data` / `files` — the last for multipart uploads, threaded through the auth-retry rebuild). `Credential` subclasses live in each node folder's `_credentials.py` (or inline for single-use); live count via `len(services.plugin.credential.CREDENTIAL_REGISTRY)` — 30 at time of writing, do not hand-maintain. `TaskQueue` constants route to Temporal worker pools. Plugins live across 9 queues (live count via `glob server/nodes/**/__init__.py`); handler bodies fully inlined (`services/handlers/` shrank 12.8K → 1.1K LOC across 16 → 4 files; only cross-cutting orchestration remains: `tools.py` AI-tool dispatch + agent delegation, `triggers.py` generic trigger-node handler, `todo.py` writeTodos shim — `google_auth.py` was retired into `nodes/google/_auth_helper.py`). **Wave 11.H added "self-contained plugin folders"** — up to seven 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`, `edge_walker.register_agent_context_builder`) 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 through the provider-neutral `run_native_agent_loop` |@@ -69,7 +69,7 @@ This is a React Flow-based workflow automation platform implementing n8n-inspire| **[Polyglot Server](../polyglot-server/ARCHITECTURE.md)** | Plugin registry microservice with MCP gateway (optional integration) || **[Authentication](./docs-internal/authentication.md)** | JWT/cookie auth: toggle, single/multi mode, backend + frontend, middleware, startup retry. || **[Credentials Panel](./docs-internal/credentials_panel.md)** | CredentialsModal.tsx logic-flow reference (state taxonomy, per-provider panels, invariants). |-| **[Memory Lifecycle](./docs-internal/memory_lifecycle.md)** | Canonical conversation-memory lifecycle: load/append/trim/archive/clear/resume across all agents. |+| **[Memory Lifecycle](./docs-internal/memory_lifecycle.md)** | **Stale — pre-RFC-0002.** Documents the retired `input-memory` markdown model. The `services/memory/` helper API, vector store and `claude_code_agent` session bridge sections still hold; the lifecycle and state-clear sections do not. See "Context and Memory (RFC-0002)" below. || **[Node Parameter Panel](./docs-internal/node_panels.md)** | Three-section node config UI (Input / Parameters / Output) logic-flow reference. || **[Deployment (legacy reference)](./docs-internal/deployment_legacy.md)** | `company deploy` CLI summary + the historical Docker Compose topology. || **[GCP VM Deploy Runbook](./docs-internal/gcp_vm_deploy_runbook.md)** | Manual gcloud + Cloudflare runbook for deploying the released npm package (non-Terraform path). |@@ -84,7 +84,7 @@ Every plugin is a self-contained folder under `server/nodes/<group>/<plugin>/` r**Where to look:**- [server/nodes/README.md](./server/nodes/README.md) — 5-minute walkthrough with the canonical folder template-- [docs-internal/plugin_system.md → Self-contained plugin folders](./docs-internal/plugin_system.md#self-contained-plugin-folders) — full reference, plus the **up-to-six generic registries** plugins self-wire into (`register_ws_handlers`, `register_router`, `register_filter_builder`, `register_trigger_precheck`, `register_service_refresh`, `register_output_schema`)+- [docs-internal/plugin_system.md → Self-contained plugin folders](./docs-internal/plugin_system.md#self-contained-plugin-folders) — full reference, plus the **up-to-seven generic registries** plugins self-wire into (`register_ws_handlers`, `register_router`, `register_filter_builder`, `register_trigger_precheck`, `register_service_refresh`, `register_output_schema`, `register_agent_context_builder`)- [docs-internal/node_creation.md](./docs-internal/node_creation.md) — decision tree for action / trigger / tool / dual-purpose / specialized-agent nodes- [server/nodes/telegram/](./server/nodes/telegram/) — reference implementation of the multi-file split (`_service.py` / `_handlers.py` / `_filters.py` / `_refresh.py` / `_credentials.py` / `_events.py` / two node files)@@ -740,7 +740,7 @@ Node groups (palette categories): agent, model, skill, tool, trigger, workflow,### Temporal Distributed Execution-Workflows execute via Temporal for durability and horizontal scaling, gated by `TEMPORAL_ENABLED`. Three dispatch paths exist — legacy single `execute_node_activity` (fallback), per-type `node.{type}.v{version}` activities (F4.A, `TEMPORAL_PER_TYPE_DISPATCH=true`), and Agent-as-child-workflow (F4.B, `TEMPORAL_AGENT_WORKFLOW_ENABLED=true`) — with `rlm_agent`/`claude_code_agent` always bypassing AgentWorkflow. **Per-queue activity routing is production-default (Wave 16)**: a `TemporalWorkerPool` runs one activity-only worker per plugin-declared `cls.task_queue` (ai-heavy / browser / code-exec / rest-api / messaging / ...) with per-queue concurrency + rate limits + resource-based tuning for ai-heavy/browser; rollback via `TEMPORAL_WORKER_POOL_ENABLED=false`. Resilience knobs (Waves 17-18): `DEPLOYMENT_MODE` (local halves concurrency; sizes the sticky cache), one-shot retry on `agent.execute_llm_step.v1` (LLM calls are not idempotent), observability interceptors (`activity_retry` WARN on re-dispatch), 30s periodic heartbeat during long activity bodies, cron `catchup_window=24h`, poller autoscaling. Execution routing falls back Temporal → sequential; the Temporal dev server + embedded worker are managed in-process under `server/services/temporal/` (pooch-downloaded CLI, single `temporal server start-dev` process, gRPC `TEMPORAL_FRONTEND_GRPC_PORT` + Web UI `TEMPORAL_UI_PORT`, SQLite at `~/.opencompany/temporal.db`). Full architecture, dispatch matrix, per-node + agent-loop lifecycle, all 16 F4.B `agent.*.v1` activities, heartbeat semantics, delegation input contract, the worker tuning recipe, and all `.env` tunables live in [docs-internal/TEMPORAL_ARCHITECTURE.md](./docs-internal/TEMPORAL_ARCHITECTURE.md).+Workflows execute via Temporal for durability and horizontal scaling, gated by `TEMPORAL_ENABLED`. Three dispatch paths exist — legacy single `execute_node_activity` (fallback), per-type `node.{type}.v{version}` activities (F4.A, `TEMPORAL_PER_TYPE_DISPATCH=true`), and Agent-as-child-workflow (F4.B, `TEMPORAL_AGENT_WORKFLOW_ENABLED=true`) — with `rlm_agent`/`claude_code_agent` always bypassing AgentWorkflow. **Per-queue activity routing is production-default (Wave 16)**: a `TemporalWorkerPool` runs one activity-only worker per plugin-declared `cls.task_queue` (ai-heavy / browser / code-exec / rest-api / messaging / ...) with per-queue concurrency + rate limits + resource-based tuning for ai-heavy/browser; rollback via `TEMPORAL_WORKER_POOL_ENABLED=false`. Resilience knobs (Waves 17-18): `DEPLOYMENT_MODE` (local halves concurrency; sizes the sticky cache), one-shot retry on `agent.execute_llm_step` (LLM calls are not idempotent), observability interceptors (`activity_retry` WARN on re-dispatch), 30s periodic heartbeat during long activity bodies, cron `catchup_window=24h`, poller autoscaling. Execution routing falls back Temporal → sequential; the Temporal dev server + embedded worker are managed in-process under `server/services/temporal/` (pooch-downloaded CLI, single `temporal server start-dev` process, gRPC `TEMPORAL_FRONTEND_GRPC_PORT` + Web UI `TEMPORAL_UI_PORT`, SQLite at `~/.opencompany/temporal.db`). Full architecture, dispatch matrix, per-node + agent-loop lifecycle, the F4.B `agent.*` activities (unsuffixed since the V1/V2 fold; read the live set from `collect_agent_activities()` rather than a hardcoded count), heartbeat semantics, delegation input contract, the worker tuning recipe, and all `.env` tunables live in [docs-internal/TEMPORAL_ARCHITECTURE.md](./docs-internal/TEMPORAL_ARCHITECTURE.md).**Months-long durability contract (July 2026).** Running and paused deployments survive backend restarts, are never auto-terminated, and keep executing for months. Load-bearing invariants: (1) `TEMPORAL_TERMINATE_RUNNING_ON_STARTUP` stays `false` (debug-only sweep; even enabled, any control row in the shared `WORKFLOW_CONTROL_ACTIVE_STATES` — including `resetting` — vetoes it). (2) New child workflow starts carry **no** `execution_timeout`/`run_timeout` — Temporal's timeout timers keep ticking through a cooperative pause, so lifetime caps silently terminated paused runs; liveness comes from activity heartbeats (30s beat / 2min timeout), never from workflow lifetime caps. Removing/adding start options or retry policies on recorded commands requires a `workflow.patched(...)` guard (see the `*-unbounded-*` / `*-history-bounded-can-*` markers). (3) Every long-lived workflow loop must continue-as-new under history pressure (`is_continue_as_new_suggested()` + a soft cap) — Temporal hard-terminates around ~51,200 history events; `WorkflowControlWorkflow` carries triggers/queued events/seen-ids/control state across rollovers, so controller handles are addressed **by workflow id only, never run_id-pinned**. (4) `dispatch.emit` skips controllers whose `ControlEventTypes` Search Attribute doesn't match the event (absent attribute = legacy match-all). (5) The Temporal lifecycle is owned by [services/temporal/lifecycle.py](./server/services/temporal/lifecycle.py) (`main.py` only schedules it): dev-server supervision + resident watchdog (`TEMPORAL_HEALTH_MONITOR_INTERVAL_SECONDS`), worker crash-restarts that REBUILD the single-use SDK `Worker` per attempt (manager + every pool queue worker), and the boot-time `reconcile_active_controls_on_boot` pass (converges crash-stranded `starting` rows, re-arms running/paused generations from the persisted graph snapshot). (6) **Recovery policies** (env-driven, defaults in `.env.template`; full semantics in [temporal-workflow-control.md → Recovery policies](./docs-internal/temporal-workflow-control.md)): `WORKFLOW_CONTROL_CRASH_RECOVERY=pause` — after a kill/crash (dirty-bit marker cleared only by graceful teardown) boot recovers running generations as **paused** so the user consciously resumes; `WORKFLOW_CONTROL_MISSING_CONTROLLER=pause` — a killed/vanished controller converges the generation to paused and **Resume rebuilds the controller** (`WorkflowIdConflictPolicy.USE_EXISTING`, re-arm from snapshot) instead of forcing a state-archiving Reset; `WORKFLOW_CONTROL_PAUSE_ON_FAILURE=true` — repeatedly-failing trigger-spawned runs pause their deployment via the `workflow_control.pause_on_failure.v1` activity (circuit breaker; trips only after `WORKFLOW_CONTROL_PAUSE_ON_FAILURE_THRESHOLD` (default 3) failures inside a rolling `_WINDOW_SECONDS` (default 600) so one node hiccup never pauses anything; Resume resets the streak; manual canvas runs never qualify). Temporal's native Pause/Unpause (server 1.28+) is deliberately NOT used — no Python SDK surface, and it halts workflow-task dispatch so a natively-paused controller couldn't process the resume Update. (7) **Workflow-scoped event delivery**: an envelope whose `workflow_id` is set by its producer's call site reaches only that workflow's consumers (`dispatch.emit` narrows both Visibility clauses by `EventWorkflowId`); chat is the first scoped producer — the decision lives in `routers/websocket.py`, the narrowing in core dispatch, and plugin `_events.py` factories only plumb the field (see [event_framework.md](./docs-internal/event_framework.md)). (8) **Canvas editability is the server-owned `can_edit` capability** emitted by `serialize_control` (paused = editable; starting/running/transitional = locked); the FE renders it via `lib/canvasLock.ts` + Dashboard's `guardCanvasEdit` and never re-derives the rule from state strings (see [temporal-workflow-control.md → Canvas editability](./docs-internal/temporal-workflow-control.md)). Locked by `tests/temporal/test_durability_hardening.py` + `test_worker_restart.py`.@@ -1085,7 +1085,7 @@ Single source of truth: [`server/services/workflow_naming.py`](./server/services| Per-firing run (child of listener) | `<slug>-<trigger_label>-<event_id>` | `AI_Assistant_1-chatTrigger-evt-abc` || Cron Schedule | `<slug>-<trigger_label>` | `AI_Assistant_1-cronScheduler` || Cron firing (per-tick child) | `<slug>-<trigger_label>-<ScheduledStartTime>` | `AI_Assistant_1-cronScheduler-2026-05-27T12:00:00Z` |-| Agent child workflow | `<slug>-<agent_label>` | `AI_Assistant_1-aiAgent` (or `AI_Assistant_1-Bot` after F2 rename) |+| Agent child workflow | `<root_temporal_workflow_id>-agent-<node_id>` | `AI_Assistant_1-Chat_Trigger-<event>-agent-1:aiAgent:1`. Uses the IMMUTABLE node id and does carry a middle `-agent-` tag, unlike every other row. The label-derived `<slug>-<agent_label>` form survives only for histories recorded before the `machina-agent-child-id-v2` patch. || Direct MachinaWorkflow exec | `<slug>-<uuid8>` | `AI_Assistant_1-a1b2c3d4` || Per-node activity (inside MachinaWorkflow) | `activity_id = <node_id>` | `chatTrigger-1779...-47c2f5` |@@ -1142,7 +1142,7 @@ deploy_workflow() -> Sets up triggers, returns immediately### AI Chat Model System (5-Layer Architecture)-Chat-model nodes (`openaiChatModel`, `anthropicChatModel`, ...) render through `SquareNode` from the backend NodeSpec. Direct chat and every new agent execution route through the native SDK facade (`ChatUnifier` in `services/llm/`); the 12-provider surface is 10 cloud providers plus Ollama and LM Studio. Eleven providers have standalone chat-model nodes, while xAI is selected directly from agent parameters. Model params (max output, context length, thinking type, temperature range) come from `ModelRegistryService`. The provider architecture, proxy/local-LLM routing, and the per-provider model + thinking/reasoning matrix (budget / effort / format) all live in **[Native LLM SDK](./docs-internal/native_llm_sdk.md)**. A Temporal history recorded before the native cutover carries no `llm_engine` marker and messages in a retired wire format; `agent.execute_llm_step.v1` refuses it with a non-retryable `InvalidAgentLLMEngine` rather than misreading it, and the deployment must be Reset. The runtime output schema (`thinking` field for downstream nodes) is backend-served per [Schema Source of Truth RFC](./docs-internal/schema_source_of_truth_rfc.md).+Chat-model nodes (`openaiChatModel`, `anthropicChatModel`, ...) render through `SquareNode` from the backend NodeSpec. Direct chat and every new agent execution route through the native SDK facade (`ChatUnifier` in `services/llm/`); the 12-provider surface is 10 cloud providers plus Ollama and LM Studio. Eleven providers have standalone chat-model nodes, while xAI is selected directly from agent parameters. Model params (max output, context length, thinking type, temperature range) come from `ModelRegistryService`. The provider architecture, proxy/local-LLM routing, and the per-provider model + thinking/reasoning matrix (budget / effort / format) all live in **[Native LLM SDK](./docs-internal/native_llm_sdk.md)**. A Temporal history recorded before the native cutover carries no `llm_engine` marker and messages in a retired wire format; `agent.execute_llm_step` refuses it with a non-retryable `InvalidAgentLLMEngine` rather than misreading it, and the deployment must be Reset. The runtime output schema (`thinking` field for downstream nodes) is backend-served per [Schema Source of Truth RFC](./docs-internal/schema_source_of_truth_rfc.md).## AI Agent Node Architecture@@ -1370,9 +1370,19 @@ Multi-step welcome wizard shown on first launch — database-backed (`UserSettinA new chat-model provider is one self-contained folder under `server/nodes/model/<provider>_chat_model/` with `__init__.py` declaring a `ChatModelBase` subclass (auto-registers via `BaseNode.__init_subclass__`; the frontend renders it through `SquareNode` from the NodeSpec with zero TS changes). Credentials live in `server/nodes/model/_credentials.py`. The full recipe — native provider registration under `services/llm/providers/`, `llm_defaults.json` configuration, the `_COMPAT_PROVIDERS` entry required for OpenAI-compatible endpoints, and the per-provider implementation-file map — is in **[Native LLM SDK](./docs-internal/native_llm_sdk.md)**.-## Simple Memory System+## Context and Memory (RFC-0002)-The Simple Memory node (`simpleMemory`, plugin `server/nodes/skill/simple_memory/`) provides markdown-based conversation history on the agent's `input-memory` handle: window-based trimming, an editable markdown view, and optional long-term vector retrieval. Memory is loaded/parsed/appended/trimmed via the helpers in `server/services/memory/`. The full lifecycle (two storage formats, the markdown helper API, vector store, the `claude_code_agent` native-session bridge, clearing/resume) is the canonical **[Memory Lifecycle](./docs-internal/memory_lifecycle.md)**; token tracking + compaction thresholds are in **[Memory Compaction](./docs-internal/memory_compaction.md)**.+Two different things, deliberately separated. Read [RFC-0002](./RFC-0002-AGENT-CONTEXT-AND-MEMORY.md) before touching either.++**Context** is the backend-owned execution journal — what the agent actually sent and received. The `context` node (`server/nodes/context/`, `input-context` handle) is a **read-only observation surface onto it**. Load-bearing invariant, learned the hard way: *attaching a Context node must never change what the agent sends.* It once did — `context_ref` in the LLM payload selected a second implementation that rebuilt the request from the journal instead of sending `messages`, and the rebuilt transcript dropped the user's prompt, so connecting a Context node made the agent answer an empty question. There is now exactly one LLM step; `context_ref` only says *where to record*.++The journal records, it never reconstructs. `agent.execute_llm_step` writes each turn from the exact message list it hands to `ChatUnifier.chat` (`_journal_llm_turn`), immediately after the call returns. `agent.prepare_context` deliberately journals nothing — it runs before the request exists, so anything it wrote would be assembled from configuration. Journal operation ids derive from the per-firing `context_execution_id`, **not** `execution_id`: the latter is generation-scoped, so every message in a generation minted identical ids and the store's idempotency guard silently discarded every turn after the first.++A Context thread exists only under an admitted generation (`generation > 0`), which only Start assigns — manual canvas Runs journal nothing by design. Each generation gets its own thread, so conversation does not carry across a Stop/Start. Workflow Reset rotates the thread to a fresh epoch and leaves prior events as archived history; the panel's journal view is scoped to the live epoch, or a reset looks like it did nothing.++**Memory** (`simpleMemory`, plugin `server/nodes/tool/simple_memory/`) is a `ToolNode` on `input-tools` — durable facts the agent explicitly remembers, recalls, updates and forgets. It is not conversation history and has no markdown surface; `SimpleMemoryParams` declares only `reset_policy` (with `extra="ignore"`, so leftover legacy keys on migrated graphs are inert). `reset_policy` is in `server_controlled_fields`, which stops the **model** overriding it through tool arguments — it does not stop the operator editing it.++Lifecycle helpers live in `server/services/memory/`; token tracking and compaction thresholds are in **[Memory Compaction](./docs-internal/memory_compaction.md)**. **[Memory Lifecycle](./docs-internal/memory_lifecycle.md)** still documents the pre-RFC-0002 markdown model and is stale.## Memory Compaction, Token Tracking, and Cost Calculation@@ -1548,7 +1558,7 @@ service_id_map = {```### Android Toolkit Pattern (retired)-The former `androidTool` gateway node (single `android_device` tool aggregating multiple Android service nodes, n8n Sub-Node / LangChain Toolkit pattern) no longer exists. Android service nodes connect straight to `input-tools`, and sub-node exclusion keys solely on AI-agent config handles (`input-memory` / `input-tools` / `input-skill` / `input-teammates`) — the `TOOLKIT_NODE_TYPES` constant was deleted along with all its usage sites. Legacy `service -> androidTool -> agent` graphs are rewritten on load by `services/workflow_migrations.normalize_legacy_android_toolkit`.+The former `androidTool` gateway node (single `android_device` tool aggregating multiple Android service nodes, n8n Sub-Node / LangChain Toolkit pattern) no longer exists. Android service nodes connect straight to `input-tools`, and sub-node exclusion keys solely on AI-agent config handles (`input-context` / `input-tools` / `input-skill` / `input-teammates`) — the `TOOLKIT_NODE_TYPES` constant was deleted along with all its usage sites. Legacy `service -> androidTool -> agent` graphs are rewritten on load by `services/workflow_migrations.normalize_legacy_android_toolkit`.### Tool Schemas (per-service customization)Custom LLM-visible schemas for Android service tools persist in the `tool_schemas` table and are read by the AI service at execution time. (The `ToolSchemaEditor.tsx` UI component shipped with the retired Android Toolkit node and was removed with it; the `useToolSchema` hook, WebSocket handlers, and database CRUD remain.)@@ -1624,17 +1634,18 @@ All handlers fetch API keys via `auth_service.get_api_key()` and track usage via## Config Node Architecture### Overview-Config nodes (memory, tools, models) connect to parent nodes via special "config handles" (e.g., `input-memory`, `input-tools`). These are auxiliary connections for configuration, not main data flow. The UI intelligently handles visibility of connected inputs based on this architecture.+Config nodes (context, tools, models) connect to parent nodes via special "config handles" (e.g., `input-context`, `input-tools`). These are auxiliary connections for configuration, not main data flow. The UI intelligently handles visibility of connected inputs based on this architecture.### Config Handle ConventionConfig handles follow the pattern `input-<type>` where type is NOT 'main':-- `input-memory` - Memory/context nodes-- `input-tools` - Tool nodes+- `input-context` - Context node (RFC-0002; observation surface onto the journal)+- `input-tools` - Tool nodes (including `simpleMemory`, which is a ToolNode)- `input-model` - Model configuration nodes- `input-skill` - Skill nodes- `input-task` - Task completion trigger nodes- `input-teammates` - Team member agent nodes- `input-main` - Main data flow (NOT a config handle)+- `input-memory` - **retired.** Kept only so immutable V1 graph snapshots replay; no agent declares it. `normalize_workflow_graph` rewrites legacy `simpleMemory -> input-memory` edges into a Context node plus an ordinary tool edge.**Note**: Trigger nodes (e.g., `taskTrigger`) connecting via config handles are excluded from downstream inclusion in `_get_downstream_nodes()` to prevent them from blocking as event waiters.@@ -1688,7 +1699,7 @@ The `isConfigNode` flag is **auto-derived on the backend** by `_derive_auto_ui_h### Sub-Node Execution Exclusion-Sub-nodes (tools, memory, skills, teammates) connect TO an agent, not from it, so in parallel execution mode Kahn's algorithm would see them with in-degree 0 and incorrectly schedule them in layer 0. The executor excludes them: any node whose edge targets an AI-agent config handle (`input-memory`, `input-tools`, `input-skill`, `input-teammates`) is detected as a sub-node in `ExecutionContext.create()` / `_compute_execution_layers()` and skipped from execution layers — it executes only when the agent invokes it (e.g. as an AI tool).+Sub-nodes (tools, memory, skills, teammates) connect TO an agent, not from it, so in parallel execution mode Kahn's algorithm would see them with in-degree 0 and incorrectly schedule them in layer 0. The executor excludes them: any node whose edge targets an AI-agent config handle (`input-context`, `input-tools`, `input-skill`, `input-teammates`) is detected as a sub-node in `ExecutionContext.create()` / `_compute_execution_layers()` and skipped from execution layers — it executes only when the agent invokes it (e.g. as an AI tool).Toolkit aggregator nodes (the former `androidTool` and its `TOOLKIT_NODE_TYPES` constant) were retired; Android service nodes now connect directly to the agent's `input-tools` handle. Legacy `service -> androidTool -> agent` graphs are migrated on load by `services/workflow_migrations.normalize_legacy_android_toolkit` (pure, idempotent: services re-wire directly to each agent, orphaned toolkits are removed with a warning).@@ -2733,7 +2744,7 @@ This function:- **Credentials: DB as single source of truth + symmetric broadcasts + cache dedup**: `CredentialsDatabase` (encrypted SQLite) is canonical; every other layer is a derived cache with explicit invalidation. Backend `AuthService._memory_cache + _models_cache` collapsed into one `_api_key_cache: Dict[str, ApiKeyCacheEntry]` dataclass — single write/evict site. Per RFC 9700 (OAuth 2.0 BCP, 2024) the `_oauth_cache` no longer carries `refresh_token`; new `get_oauth_refresh_token(provider, customer)` reads from the encrypted DB on every call. `validate_api_key`, `save_api_key`, `delete_api_key`, `twitter_logout`, `google_logout` now broadcast symmetrically: `update_api_key_status` (in-memory map) + `broadcast_credential_event(...)` (refetch signal) wrapping `WorkflowEvent` (CloudEvents v1.0 from `services/events/envelope.py`, the same envelope the Wave 12 EventSource framework uses). The dead-letter `credential_catalogue_updated` event is finally emitted by the backend. Frontend retired the 200-LOC `client/src/components/credentials/providers.tsx` static fallback — `useCatalogueQuery` is the only source; cold-boot renders `<Skeleton>`, server-unreachable shows an explicit error state. `ApiKeyStatus.hasKey` mirror dropped (duplicated catalogue's `provider.stored`); two new selector hooks (`useProviderStored`, `useStoredProviderCount`) read the catalogue. Pytest invariant `test_credential_broadcasts.py` (14 tests) locks the broadcast contract via `inspect.getsource` introspection + the CloudEvents v1.0 envelope shape + AuthService DB-write-then-cache-update ordering + the no-refresh-token-in-cache rule.- **Local-LLM provider routing + per-model context**: Ollama and LM Studio are first-class providers (12 total for agents: 10 cloud + 2 local). Provider detection is driven by `detect_ai_provider` in `server/constants.py` plus the `provider` Literal in `nodes/agent/{ai_agent,chat_agent,_specialized}.py` — both MUST list `ollama` / `lmstudio` or chat-model nodes / agent dropdowns silently fall through to `'openai'` and `execute_chat` calls api.openai.com with the placeholder key. The validator at `nodes/model/_local_validator.py` probes via the official SDKs (`ollama.AsyncClient.ps()` for typed `ProcessResponse.Model`, `lmstudio.AsyncClient.llm.list_loaded()` for typed `LlmInstanceInfo`) — reads only typed fields (`context_length`, `max_context_length`, `vision`, `trained_for_tool_use`, `architecture`, `params_string`, `format`, plus Ollama's `details.{family,parameter_size,quantization_level}`). No regex, no Modelfile-parameters parsing, no `/api/show` modelinfo dict-key hunting. Per-model params persist in `EncryptedAPIKey.models["model_params"]` (via `save_api_key(model_params=...)`) AND in `model_registry.json` via `register_local_model()` — sync `get_context_length()` / `get_max_output_tokens()` find real values without async DB lookups, and entries survive process restart. `is_model_valid_for_provider` returns `True` for open-world providers (`openrouter` / `ollama` / `lmstudio`) so local model names like `qwen/qwen3.6-27b` aren't rejected by the cloud-style pattern check. Runtime path uses `OpenAIProvider(base_url={user_proxy_url}, api_key="ollama")` — traffic stays on `localhost`.- **Typed SDK error → `LLMError` → `NodeUserError`**: Native providers normalize SDK failures into structured `LLMError` values carrying category, retryability, HTTP status, provider code, request ID, and retry-after metadata. `ChatUnifier` translates them at the execution boundary into a user-safe `NodeUserError`; `BaseNode.execute()` logs that at WARN with one line and no stack trace. Unexpected exceptions retain the full-traceback path. In-process agent turns retry only errors marked retryable, while Temporal owns activity retries and disables the inner retry loop.-- **Plugin extraction (Wave 11.I)**: every plugin's WS handlers, OAuth client, FastAPI router, and lifecycle service live entirely under `nodes/<plugin>/`. Eight plugin domains migrated this round (whatsapp / twitter / google-workspace / android / browser / email / code / credential-validation-scaffold for maps+apify+ollama+lmstudio) follow the telegram pattern. `routers/websocket.py` shrunk from ~3,785 to ~2,977 LOC (-808). Three plugin routers (`routers/twitter.py`, `routers/google.py`, `routers/android.py`) moved into `nodes/<plugin>/_router.py` and mount via the plugin-router loop in `main.py`; the explicit `app.include_router(<plugin>.router)` calls and `from routers import <plugin>` imports in `main.py` are gone. **`register_router(router, name=...)` is the new sibling helper to `register_ws_handlers` (same file: `services/ws_handler_registry.py`)** — six generic registries total now (ws_handlers, router, filter_builder, trigger_precheck, service_refresh, output_schema). **`Credential.validate(data) -> dict` + `Credential._probe(api_key) -> ProbeResult` is the new shared validator scaffold** in `services/plugin/credential.py` — replaces the per-router `_SPECIAL_PROVIDER_VALIDATORS` dict; one `_LLMApiKey._probe` method serves all 10 cloud LLM providers, dedicated `_probe` overrides handle Maps + Apify, `_LocalLLM.validate` overrides for Ollama / LM Studio's 2-storage edge case. **`tests/test_plugin_self_containment.py` locks the contract** with 7 invariant classes (forbidden-imports / no-router-outside-nodes / per-plugin self-registration / registry-API sanity / stale-paths-absent / main.py-does-not-mount / WS_HANDLERS-non-empty); same `inspect.getsource` introspection style as `test_credential_broadcasts.py`. Wire format unchanged — frontend WS message-type strings (`whatsapp_status`, `twitter_oauth_login`, `google_oauth_status`, `android_relay_connect`, etc.) and HTTP route paths (`/api/twitter/callback`, `/api/google/callback`, `/api/android/*`) are byte-identical post-migration.+- **Plugin extraction (Wave 11.I)**: every plugin's WS handlers, OAuth client, FastAPI router, and lifecycle service live entirely under `nodes/<plugin>/`. Eight plugin domains migrated this round (whatsapp / twitter / google-workspace / android / browser / email / code / credential-validation-scaffold for maps+apify+ollama+lmstudio) follow the telegram pattern. `routers/websocket.py` shrunk from ~3,785 to ~2,977 LOC (-808). Three plugin routers (`routers/twitter.py`, `routers/google.py`, `routers/android.py`) moved into `nodes/<plugin>/_router.py` and mount via the plugin-router loop in `main.py`; the explicit `app.include_router(<plugin>.router)` calls and `from routers import <plugin>` imports in `main.py` are gone. **`register_router(router, name=...)` is the new sibling helper to `register_ws_handlers` (same file: `services/ws_handler_registry.py`)** — seven generic registries total now (ws_handlers, router, filter_builder, trigger_precheck, service_refresh, output_schema, agent_context_builder). **`Credential.validate(data) -> dict` + `Credential._probe(api_key) -> ProbeResult` is the new shared validator scaffold** in `services/plugin/credential.py` — replaces the per-router `_SPECIAL_PROVIDER_VALIDATORS` dict; one `_LLMApiKey._probe` method serves all 10 cloud LLM providers, dedicated `_probe` overrides handle Maps + Apify, `_LocalLLM.validate` overrides for Ollama / LM Studio's 2-storage edge case. **`tests/test_plugin_self_containment.py` locks the contract** with 7 invariant classes (forbidden-imports / no-router-outside-nodes / per-plugin self-registration / registry-API sanity / stale-paths-absent / main.py-does-not-mount / WS_HANDLERS-non-empty); same `inspect.getsource` introspection style as `test_credential_broadcasts.py`. Wire format unchanged — frontend WS message-type strings (`whatsapp_status`, `twitter_oauth_login`, `google_oauth_status`, `android_relay_connect`, etc.) and HTTP route paths (`/api/twitter/callback`, `/api/google/callback`, `/api/android/*`) are byte-identical post-migration.- **Typed CloudEvents factory pattern for new broadcasts** (b6aecd3): every new server→FE lifecycle broadcast follows the recipe locked by `broadcast_credential_event`, `broadcast_agent_progress`, and `broadcast_agent_capability`. (1) Add a typed factory — convention: `source = "opencompany://services/<area>"`, reverse-DNS `type = "com.opencompany.<area>.<event>"`, and `subject = <exact primary entity id>`. Put snake_case workflow/execution scope inside `data`; CloudEvents extension attribute names MUST be lowercase-alphanumeric, so the historical top-level `workflow_id`/`trigger_node_id`/`correlation_id` fields are compatibility debt and are forbidden on new contracts. (2) Add a broadcaster wrapper that emits `broadcast({type: "<wire_key>", data: event.model_dump(mode="json", exclude_none=True)})`. (3) FE validates `specversion`, ID/source/type, subject ownership, and event-specific payload invariants, deduplicates by `(source,id)`, then writes only the exact scoped entity. (4) Add contract tests in `test_events.py` and keep `tests/test_status_broadcasts.py`'s raw-callsite allowlist empty. Raw `node_status` remains allowed only as the established high-frequency latest-state/reconnect projection paired with a typed lifecycle occurrence; it is not the event of record.- **Plugin-folder location for plugin-specific CloudEvents factories** (RFC §6.4): when a typed event is owned by one plugin (telegram, whatsapp, android, email, google, master_skill, agent_builder, webhook_trigger, chat_trigger, agent), the factory + `broadcast_<event>` wrapper live in [`server/nodes/<plugin>/_events.py`](./server/nodes), NOT on `WorkflowEvent` / `StatusBroadcaster` directly. Telegram's [`_events.py`](./server/nodes/telegram/_events.py) is the canonical template — `broadcast_telegram_status` constructs the envelope via a plain factory function and calls `get_status_broadcaster().broadcast(...)` itself. Latest example: [`server/nodes/skill/master_skill/_events.py`](./server/nodes/skill/master_skill/_events.py) (`broadcast_skill_lifecycle("created" \| "updated" \| "deleted" \| "content_saved", name=..., **data_extra)`) — replaces four raw-dict broadcasts in `handle_create_user_skill` / `handle_update_user_skill` / `handle_delete_user_skill` / `handle_save_skill_content` (the last one was previously silent). FE routes wire key `skill_lifecycle` to invalidate `userSkills` + `folderSkills` queries and drop the `skillContent` cache on delete + content_saved so the Master Skill panel refreshes live across every connected client. Cross-cutting events (credential, workflow_lifecycle, agent_progress, agent_capability, node_parameters_updated) keep their `WorkflowEvent` classmethods + `StatusBroadcaster` wrappers — only plugin-scoped events move to the plugin folder.- **Operator-metadata fields in credential panels** (f746ddf): when a credential panel needs a non-credential follow-up field (e.g. Telegram bot token + owner chat id), declare it as a second entry in the provider's `fields` array in `server/config/credential_providers.json`. The first field stays the validate/connect target; subsequent fields render below as plain text inputs via `SecondaryFieldRow` in `ApiKeyPanel.tsx` (shadcn `Input` + `Label` + `<ActionButton intent="save">`). Each field carries an optional `help` slot (`FieldDef.help` / `ServerFieldDef.help`) for always-visible explanatory text under the input. Save writes via `panel.actions.save(field.key, value)` → `auth_service.store_api_key` (which is permissive about provider string). The credential class must declare the new key in `extra_fields` (`Credential` subclass attribute) so the storage layer accepts it. Reference: `telegram_owner_chat_id` field.diff --git a/RFC-0002-AGENT-CONTEXT-AND-MEMORY.md b/RFC-0002-AGENT-CONTEXT-AND-MEMORY.mdindex f23c0ed4..378dc0cd 100644--- a/RFC-0002-AGENT-CONTEXT-AND-MEMORY.md+++ b/RFC-0002-AGENT-CONTEXT-AND-MEMORY.md@@ -237,28 +237,38 @@ embedding projections are rebuildable accelerators.Memory does not automatically inject prompts, recall vectors, persisttranscripts, own provider identity, or compact Context.-## 10. Temporal V2--New identities isolate deterministic histories:--```text-AgentWorkflowV2-agent.prepare_context.v2-agent.execute_llm_step.v2-agent.append_context.v2-agent.compact_context.v2-```--The child workflow carries only `AgentContextRef`, operation IDs/hashes,-iteration state, and pending tool identities. Activities load payloads from-the Context store. Provider messages and large tool results do not enter Event-History. The LLM activity retains the existing one-attempt retry policy;-database commits retry idempotently. An ambiguous provider outcome is recorded-and surfaced rather than silently rebilled.--`AgentWorkflowV2` uses Continue-As-New with a bounded Context reference and-pending state. Existing V1 native histories keep their recorded command-sequence. Pre-native histories still require Reset.+## 10. Temporal++**Superseded.** This section originally specified a parallel `…V2` identity set+(`AgentWorkflowV2`, `agent.*.v2`) so V1 and V2 histories could run side by side.+That split was never needed — history back-compatibility is not a requirement+here — and it has been folded away. There is one workflow class, `AgentWorkflow`,+and one unsuffixed activity per concern: `agent.prepare_context`,+`agent.execute_llm_step`, `agent.append_context`, `agent.compact_context`.++What still holds: the child workflow carries only `AgentContextRef`, operation+IDs/hashes and iteration state, so provider messages and large tool results stay+out of Event History. The LLM activity keeps its one-attempt retry policy while+database commits retry idempotently, so an ambiguous provider outcome is recorded+rather than silently rebilled. `AgentWorkflow` uses Continue-As-New with a+bounded Context reference.++**Corrected by implementation — the Context journal does not feed the request.**+This RFC's replay-first framing led to an LLM step that reconstructed its request+from the journal whenever a Context node was attached. That is wrong in kind: the+Context node is an observation surface, and a node whose purpose is to *show* the+agent's state must not change what the agent sends. It also failed in practice —+the reconstruction dropped the user's prompt, so connecting a Context node made+the agent answer an empty question.++The rule is now inverted and load-bearing: **the request is always built from+`messages`; the journal records what was sent.** `agent.execute_llm_step` writes+each turn from the exact list it hands to `ChatUnifier.chat`, after the call+returns. `agent.prepare_context` journals nothing, because it runs before a+request exists and could only fabricate one. Journal operation ids derive from+the per-firing `context_execution_id`; deriving them from the generation-scoped+`execution_id` made every turn in a generation collide on idempotency and+silently discarded all but the first.## 11. Graph normalization and lifecyclediff --git a/docs-internal/TEMPORAL_ARCHITECTURE.md b/docs-internal/TEMPORAL_ARCHITECTURE.mdindex b20ba4a1..d6f57f13 100644--- a/docs-internal/TEMPORAL_ARCHITECTURE.md+++ b/docs-internal/TEMPORAL_ARCHITECTURE.md@@ -323,7 +323,7 @@ Env overrides: `TEMPORAL_<QUEUE>_CONCURRENCY` (int) and `TEMPORAL_<QUEUE>_RATE_L- **Application observability interceptor** (Wave 17.3, `services/temporal/_interceptors.py`): workers explicitly register `ObservabilityWorkerInterceptor` for `activity_retry` WARN logs when `activity.info().attempt > 1` — the "worker died and Temporal re-dispatched" signal — and replay-guarded `workflow_start` logs. This is separate from SDK tracing and remains worker-owned.- **Periodic activity heartbeat** (Wave 17.6, `plugin/base.py::as_activity`): 30s background beat during long bodies so a laptop-sleep crash is detected within one `heartbeat_timeout` (2 min) instead of `start_to_close` (10 min).- **Cron catch-up bound** (Wave 17.1, `services/temporal/schedules.py`): `SchedulePolicy(catchup_window=24h)` + `SKIP` overlap — a laptop offline a week does not replay 168 hourly ticks on wake.-- **One-shot LLM-step retry** (Wave 17.2): `LLM_STEP_RETRY(maximum_attempts=1)` on `agent.execute_llm_step.v1` — LLM calls are not idempotent; the workflow surfaces the failure instead of silently re-billing the prompt. `agent.refresh_tools.v1` deliberately keeps 3 attempts (idempotent canvas rebuild).+- **One-shot LLM-step retry** (Wave 17.2): `LLM_STEP_RETRY(maximum_attempts=1)` on `agent.execute_llm_step` — LLM calls are not idempotent; the workflow surfaces the failure instead of silently re-billing the prompt. `agent.refresh_tools` deliberately keeps 3 attempts (idempotent canvas rebuild).**Metric watchlist** (Temporal Web UI / metrics endpoint): `schedule_to_start_latency` (elevated = raise pollers or slots), `worker_task_slots_available` (0 = raise concurrency or add hosts), `poll_success_rate` (target >= 90%), `sticky_cache_evictions` (persistent growth = raise `max_cached_workflows`).@@ -335,7 +335,7 @@ When `TEMPORAL_AGENT_WORKFLOW_ENABLED=true` and the node type is in the migratin```AgentWorkflow.run(context):- 0. execute_activity("agent.prepare_payload.v1")+ 0. execute_activity("agent.prepare_payload")resolves the DB-backed payload from the canvas context — runsworkflow_service._param_resolver.resolve so {{node.field}}templates in prompt / system_message become real values BEFORE@@ -348,7 +348,7 @@ AgentWorkflow.run(context):emit_phase("starting", status="executing")loop until "final" or max_iterations:1. emit_phase("llm_step", iteration=N)- 2. execute_activity("agent.execute_llm_step.v1")+ 2. execute_activity("agent.execute_llm_step")returns {kind, assistant_message, calls?, content?, usage}.assistant_message is MessageWireV2: ordered text/reasoning/toolblocks plus JSON-safe provider continuation state (Gemini thought@@ -382,7 +382,7 @@ AgentWorkflow.run(context):4. for each tool result with an ``operations`` field(canvas-mutating tools — today only ``agentBuilder``):if payload["auto_rebind_tools"] is True:- execute_activity("agent.refresh_tools.v1", {operations: …})+ execute_activity("agent.refresh_tools", {operations: …})translates add_node ops with component_kind=="tool" ORusable_as_tool=True (minus chat-model plugins) into thesame tool_payload shape prepare_agent_payload emits.@@ -391,15 +391,15 @@ AgentWorkflow.run(context):tools.extend(refresh_result["tools"])tool_index.update(...)# next execute_llm_step.v1 sees the new tools.- 5. execute_activity("agent.persist_turn.v1")+ 5. execute_activity("agent.persist_turn")append_to_memory_markdown(content, "human", prompt) +(content, "ai", response); trim window; broadcastnode_parameters_updated CloudEvents (source_hint="agent").6. if token_total >= compaction_threshold:- execute_activity("agent.compact_memory.v1")+ execute_activity("agent.compact_memory")null-guarded against worker-bootstrap race; replaces messageswith summary only when result.success is True.- execute_activity("agent.store_output.v1")+ execute_activity("agent.store_output")wraps workflow_service.store_node_output for output_main /output_top / output_0 — same writes NodeExecutor.execute doesat services/node_executor.py:197-199, so downstream nodes@@ -407,19 +407,19 @@ AgentWorkflow.run(context):emit_phase("completed", status="success")```-The `agent.prepare_payload.v1` result is recorded in history and therefore+The `agent.prepare_payload` result is recorded in history and thereforeacts as the deterministic engine selector. New executions default to`llm_engine="native"` with Message Wire V2 and use `ChatUnifier` plus thenative provider SDKs for every turn. Histories whose recorded prepare resulthas no engine marker are pre-cutover histories: their messages are in a retired-wire format the native reader cannot interpret, so `agent.execute_llm_step.v1`+wire format the native reader cannot interpret, so `agent.execute_llm_step`refuses them with a non-retryable`ApplicationError(type="InvalidAgentLLMEngine")` rather than misreading them.The operator fix is to Reset the deployment, which starts a fresh generation.Changing the environment cannot change an execution after it starts,and a native run never falls back after a provider request starts.-`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.opencompany.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. When this workflow is itself a delegated child (`context["parent_node_id"]` set), every `emit_phase` call ALSO schedules a second broadcast against the parent's `node_id` with `phase="delegating"` — the parent's canvas badge then advances in real time while the child loops, instead of freezing at "executing" glow until the child completes.+`emit_phase(phase, status?)` is a thin helper that schedules `agent.broadcast_progress`. The activity emits `WorkflowEvent.agent_progress` (CloudEvents v1.0, `type="com.opencompany.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. When this workflow is itself a delegated child (`context["parent_node_id"]` set), every `emit_phase` call ALSO schedules a second broadcast against the parent's `node_id` with `phase="delegating"` — the parent's canvas badge then advances in real time while the child loops, instead of freezing at "executing" glow until the child completes.Each LLM step is one activity and each ordinary tool call is one per-type activity. Team-lead Task Manager assignments are different: persistence happens first, then the lead starts a deterministic detached `DelegatedTaskWorkflow` with `ParentClosePolicy.ABANDON` and receives `queued` immediately. The runner owns the root-wide permit, claim, child `AgentWorkflow`, terminal result/usage persistence, `taskTrigger`, and permit release, so the assigning lead can return without polling. Direct non-team delegation retains the child-workflow path. Non-agent tools and excluded types (`rlm_agent`, `claude_code_agent`) still go through `execute_activity`. Failures surface as durable task failures and trigger review rather than being lost when the lead invocation closes.@@ -434,13 +434,13 @@ core loop activities:| Activity | Purpose ||---|---|-| `agent.prepare_payload.v1` | Resolves the DB-backed payload (provider / model / system_message / user_prompt / `AgentToolSpec`-derived tool definitions / memory_node_id / memory_content / memory_window_size / max_iterations / thinking_config / compaction_threshold / auto_rebind_tools), records `llm_engine` + `message_wire_version`, and leaves credential resolution at the LLM activity boundary. Reads `UserSettings.agent_recursion_limit` + `UserSettings.auto_rebind_tools_after_canvas_change`. Applies the optional `invocation` field (delegation children) after config resolution — per-invocation input always beats stored parameters. |-| `agent.execute_llm_step.v1` | One LLM turn. The native branch decodes Message Wire V2, rebuilds `ToolDef` values, calls `run_native_llm_step(ChatUnifier, ...)` with SDK retries disabled, heartbeats while awaiting the provider, and returns the exact assistant message + tool calls + normalized usage. Guards against un-invokable payloads: post-filter system-only message lists raise `ApplicationError(type="EmptyAgentPrompt", non_retryable=True)`. |-| `agent.refresh_tools.v1` | Translates `workflow_ops` add_node ops (`component_kind="tool"` OR `usable_as_tool=True`) into fresh `AgentToolSpec`-derived `tool_payload` entries via `_build_tool_from_node`. Workflow extends `tools` + `tool_index` from the result. |-| `agent.persist_turn.v1` | Appends the latest human/assistant exchange to memory markdown, trims the window, broadcasts `node.parameters.updated`. |-| `agent.compact_memory.v1` | Context-pressure compaction when cumulative active-context tokens hit the threshold. Best-effort: continues with un-compacted history on failure; it is not an agent termination control. |-| `agent.store_output.v1` | Writes `output_main` / `output_top` / `output_0` so downstream nodes resolve `{{aiAgent.response}}` via `ParameterResolver`. |-| `agent.broadcast_progress.v1` | Emits `WorkflowEvent.agent_progress` (CloudEvents v1.0) + optional raw-dict `update_node_status` for canvas-glow color. Single helper drives every phase emit. |+| `agent.prepare_payload` | Resolves the DB-backed payload (provider / model / system_message / user_prompt / `AgentToolSpec`-derived tool definitions / memory_node_id / memory_content / memory_window_size / max_iterations / thinking_config / compaction_threshold / auto_rebind_tools), records `llm_engine` + `message_wire_version`, and leaves credential resolution at the LLM activity boundary. Reads `UserSettings.agent_recursion_limit` + `UserSettings.auto_rebind_tools_after_canvas_change`. Applies the optional `invocation` field (delegation children) after config resolution — per-invocation input always beats stored parameters. |+| `agent.execute_llm_step` | One LLM turn. The native branch decodes Message Wire V2, rebuilds `ToolDef` values, calls `run_native_llm_step(ChatUnifier, ...)` with SDK retries disabled, heartbeats while awaiting the provider, and returns the exact assistant message + tool calls + normalized usage. Guards against un-invokable payloads: post-filter system-only message lists raise `ApplicationError(type="EmptyAgentPrompt", non_retryable=True)`. |+| `agent.refresh_tools` | Translates `workflow_ops` add_node ops (`component_kind="tool"` OR `usable_as_tool=True`) into fresh `AgentToolSpec`-derived `tool_payload` entries via `_build_tool_from_node`. Workflow extends `tools` + `tool_index` from the result. |+| `agent.persist_turn` | Appends the latest human/assistant exchange to memory markdown, trims the window, broadcasts `node.parameters.updated`. |+| `agent.compact_memory` | Context-pressure compaction when cumulative active-context tokens hit the threshold. Best-effort: continues with un-compacted history on failure; it is not an agent termination control. |+| `agent.store_output` | Writes `output_main` / `output_top` / `output_0` so downstream nodes resolve `{{aiAgent.response}}` via `ParameterResolver`. |+| `agent.broadcast_progress` | Emits `WorkflowEvent.agent_progress` (CloudEvents v1.0) + optional raw-dict `update_node_status` for canvas-glow color. Single helper drives every phase emit. |The other nine support skills and durable delegation:@@ -448,13 +448,13 @@ The other nine support skills and durable delegation:|---|---|| `agent.skill.invoke.v1` | Executes one progressive skill action with a history-recorded, retry-safe result. || `agent.skill.clear.v1` | Clears the agent's turn-scoped skill state. |-| `agent.begin_delegation.v1` | Idempotently persists and claims a direct delegation before child startup. |-| `agent.queue_delegation.v1` | Persists a team task before it waits for a root-wide concurrency permit. |-| `agent.acquire_subagent_permit.v1` | Heartbeats while polling the durable root coordinator for a subagent permit. |-| `agent.release_subagent_permit.v1` | Idempotently releases a root-wide subagent permit. |-| `agent.register_task_execution.v1` | Persists the runner and child Temporal identities for trace inspection. |-| `agent.finish_delegation.v1` | Idempotently records a delegated child's terminal result and usage. |-| `agent.finalize_team.v1` | Finalizes a team after its required tasks reach accepted or terminal states. |+| `agent.begin_delegation` | Idempotently persists and claims a direct delegation before child startup. |+| `agent.queue_delegation` | Persists a team task before it waits for a root-wide concurrency permit. |+| `agent.acquire_subagent_permit` | Heartbeats while polling the durable root coordinator for a subagent permit. |+| `agent.release_subagent_permit` | Idempotently releases a root-wide subagent permit. |+| `agent.register_task_execution` | Persists the runner and child Temporal identities for trace inspection. |+| `agent.finish_delegation` | Idempotently records a delegated child's terminal result and usage. |+| `agent.finalize_team` | Finalizes a team after its required tasks reach accepted or terminal states. |The F4.B compaction threshold is prepared from the model context length andthe ratio configuration. It currently does not read@@ -519,7 +519,7 @@ server/services/temporal/│ └── _execute_via_websocket() # WebSocket execution├── plugin_activities.py # collect_plugin_activities() -> per-type node.{type}.v{ver} activities (F4.A)├── agent_workflow.py # AgentWorkflow loop + detached DelegatedTaskWorkflow-├── agent_activities.py # collect_agent_activities() -> 16 agent.*.v1 activities (F4.B)+├── agent_activities.py # collect_agent_activities() -> the agent.* activities (F4.B)├── workflow.py # MachinaWorkflow class│ ├── run() # Main orchestrator│ ├── _filter_executable_graph() # Config node filteringdiff --git a/docs-internal/agent_architecture.md b/docs-internal/agent_architecture.mdindex 3582f800..03973054 100644--- a/docs-internal/agent_architecture.md+++ b/docs-internal/agent_architecture.md@@ -52,7 +52,7 @@ collect_agent_connections() server/services/plugin/edge_walker.pyScans edges where target == node_idGroups by targetHandle into 5 buckets (returns a 5-tuplememory_data, skill_data, tool_data, input_data, task_data):- input-memory -> memory_data+ input-context -> context_datainput-skill -> skill_data[]input-tools -> tool_data[]input-main / input-chat -> input_data@@ -192,7 +192,7 @@ Closure responsibilities:`tool_executor` can dispatch the new call.- The closure is gated on the user toggle: `UserSettings.auto_rebind_tools_after_canvas_change` (default `True`). When off, the LLM is told "Available on your next turn" in the operation summary and the closure isn't wired.-For the F4.B Temporal path, the in-process closure is replaced by the `agent.refresh_tools.v1` activity; see [TEMPORAL_ARCHITECTURE.md](TEMPORAL_ARCHITECTURE.md).+For the F4.B Temporal path, the in-process closure is replaced by the `agent.refresh_tools` activity; see [TEMPORAL_ARCHITECTURE.md](TEMPORAL_ARCHITECTURE.md).### Where it's called@@ -507,14 +507,14 @@ Two settings flags route agent execution through different Temporal paths (see [| Flag | Off | On (default) ||---|---|---|| `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 specialized + team leads + base agents (`aiAgent` / `chatAgent`) run inside `execute_node_activity` using the in-process native loop. | The 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; `agent.refresh_tools.v1` refreshes the native tool surface after canvas mutations. `rlm_agent` / `claude_code_agent` stay on the F4.A per-type activity path (externalised session state). |+| `TEMPORAL_AGENT_WORKFLOW_ENABLED` | All specialized + team leads + base agents (`aiAgent` / `chatAgent`) run inside `execute_node_activity` using the in-process native loop. | The migrating agent types become Temporal **child workflows** (`AgentWorkflow`). LLM steps + tool calls become activities; `agent.prepare_payload` resolves the DB-backed payload as the workflow's first step; `agent.refresh_tools` refreshes the native tool surface after canvas mutations. `rlm_agent` / `claude_code_agent` stay on the F4.A per-type activity path (externalised session state). |Both flags default to `true` in `.env.template`.New `AgentWorkflow` executions record `llm_engine="native"` and-`message_wire_version=2` in the `agent.prepare_payload.v1` result by default.+`message_wire_version=2` in the `agent.prepare_payload` result by default.Recorded histories whose prepare result predates those markers cannot run:-`agent.execute_llm_step.v1` refuses them with a non-retryable+`agent.execute_llm_step` refuses them with a non-retryable`InvalidAgentLLMEngine`, because their messages are in a retired wire format.Marker-bearingnative executions never fall back after a provider request starts, and changing@@ -648,7 +648,7 @@ Handle layouts are declared in `server/nodes/agent/_handles.py` (local to `nodes| `input-skill` | input | bottom | 25% | skill || `input-tools` | input | bottom | 75% | tools || `input-main` | input | left | 25% | main |-| `input-memory` | input | left | 50% | memory |+| `input-context` | input | left | 50% | context || `input-task` | input | left | 75% | task || `output-main` | output | right | 50% | main || `output-top` | output | top | — | main |diff --git a/docs-internal/agent_delegation.md b/docs-internal/agent_delegation.mdindex 3d35abf4..7ca71554 100644--- a/docs-internal/agent_delegation.md+++ b/docs-internal/agent_delegation.md@@ -309,7 +309,7 @@ For each matching edge, it checks the target handle:| Handle | Action ||--------|--------|-| `input-memory` | Loads markdown memory content from child's connected `simpleMemory` node |+| `input-context` | Resolves the child's Context thread (RFC-0002). Memory is now an ordinary tool on `input-tools`. || `input-skill` | Loads skill instructions; expands masterSkill into individual enabled skills || `input-tools` | Discovers directly connected tool nodes, including Android services || `input-main` / `input-chat` | Reads upstream node output for auto-prompt fallback |@@ -728,7 +728,7 @@ Please report this error to the user and suggest next steps if appropriate.Post-Wave-11 the frontend `specializedAgentNodes.ts` definition file no longer exists — handle topology is declared on the backend plugin classes and the frontend renders it from each NodeSpec via `useNodeSpec(type)`. Every specialized agent subclasses `SpecializedAgentBase` (`server/nodes/agent/_specialized.py`), which provides the standard handle set through `std_agent_handles()` (declared in `server/nodes/agent/_handles.py`):-- **Left**: `input-main` (Input), `input-memory` (Memory), `input-task` (Task)+- **Left**: `input-main` (Input), `input-context` (Context), `input-task` (Task)- **Bottom**: `input-skill` (Skill), `input-tools` (Tool)- **Top**: `output-top` (Output)diff --git a/docs-internal/authentication.md b/docs-internal/authentication.mdindex 64d58bf6..2021222d 100644--- a/docs-internal/authentication.md+++ b/docs-internal/authentication.md@@ -194,13 +194,25 @@ accepts.Recorded explicitly because each of these is easy to assume is handled.- **`AUTH_MODE=multi` provides authentication, not isolation.**- `middleware/auth.py` writes `request.state.user_id` / `user_email` /- `is_owner`, and **no file in `server/` reads them** — the only `user_id` in- the data layer is the literal `"default"`. Every registered user therefore- shares one workflow store and one credential store, and `is_owner` is- decorative. Real per-user scoping touches the whole data layer and needs its- own design pass; until then treat `multi` as "several people who fully trust- each other".+ The identity is now *resolved* — `services/authz/ws_surface.py`+ (`execution_principal`) reads the handshake identity and decides what a given+ execution runs as, and cron/deploy carry the deployer's `user_id` through to+ every spawned run. What is still missing is *enforcement*: there is no+ ownership check on workflow get / list / delete, and the checks that exist on+ the Context and Memory panels are fail-open (`if stored_owner and+ stored_owner != caller`), so a row with an empty `owner_id` — every legacy+ row, and every row written through the REST path — authorizes everyone.+ `get_all_workflows` returns every tenant's rows unfiltered. `is_owner` is+ still decorative. Until ownership moves to an indexed column with scoped+ accessors, treat `multi` as "several people who fully trust each other".+- **`/ws/internal` is unauthenticated by design and must stay narrow.** It is in+ `PUBLIC_PATHS` and performs no handshake, yet it dispatched through the same+ registry as the authenticated socket — which made `save_workflow`,+ `delete_workflow` and all six Memory handlers reachable without credentials.+ `services/authz/ws_surface.py` now holds a deny-by-default allowlist+ (`INTERNAL_SOCKET_HANDLERS`); refusal is deliberately indistinguishable from+ an unknown message type so the socket cannot be probed. Its test is generated+ from the live registry, so a newly added handler is closed by default.- **No CSRF token.** The API is cookie-authenticated and `SameSite` is the onlydefence. Mitigated by every mutating endpoint being `POST` under `/api/` andby `SameSite=none` + insecure being rejected at startup. A real double-submitdiff --git a/docs-internal/frontend_architecture.md b/docs-internal/frontend_architecture.mdindex ac58d594..dd7bf6c0 100644--- a/docs-internal/frontend_architecture.md+++ b/docs-internal/frontend_architecture.md@@ -500,7 +500,11 @@ Defined on `INodeTypeDescription.uiHints` ([client/src/types/INodeProperties.ts]| `hideRunButton` | `ParameterPanel` | Hide the Run button (skill / memory / tool nodes) || `hasCodeEditor` | `MiddleSection` | Give the params block extra flex space for an embedded code editor || `isMasterSkillEditor` | `MiddleSection`, `Dashboard` (component dispatch), `useAutoSkillEdges` | Render the MasterSkillEditor split panel; route to `ToolkitNode` on the canvas; identify Master Skill aggregators in the auto-skill edge dispatcher |-| `isMemoryPanel` | `MiddleSection` | Render the memory markdown panel + token usage stats |+| `isMemoryPanel` | `MiddleSection` | **Legacy.** The pre-RFC-0002 combined markdown/transcript panel. `simpleMemory` no longer declares it; kept while `normalize_workflow_graph` upgrades `input-memory` graphs |+| `isMemoryToolPanel` | `MiddleSection` | Render the durable Memory item browser (search, edit, forget, clear). Declared by `simpleMemory`, and selected *before* `isMemoryPanel` |+| `isContextPanel` | `MiddleSection` | Render the Context inspector (journal, active replay, fork/export/clear). Read-only: it observes the agent's journal and must never alter execution |+| `requiresContext` | backend graph normalization | Declared in `STD_AGENT_HINTS`. Not a rendering flag — `normalize_workflow_graph` pairs every plugin carrying it with a Context companion, and `workflow_validator` enforces the topology |+| `systemManaged` | canvas | Marks the auto-created Context companion. The backend owns its lifecycle; the user does not add or delete it directly || `isToolPanel` | `MiddleSection` | Surface the ToolSchemaEditor for connected services || `isMonitorPanel` | `MiddleSection`, `ParameterPanel` | Render the team-monitor panel || `isTodoEditor` | `MiddleSection` | Render the editable Current Todos manager (`writeTodos`) instead of the plain params list |diff --git a/docs-internal/memory_compaction.md b/docs-internal/memory_compaction.mdindex d2507bc5..25a5e02f 100644--- a/docs-internal/memory_compaction.md+++ b/docs-internal/memory_compaction.md@@ -41,7 +41,7 @@ native agent loop└─ Temporal AgentWorkflow├─ returns aggregate usage in the workflow result└─ when its context counter reaches the prepared threshold:- agent.compact_memory.v1 → compact_context()+ agent.compact_memory → compact_context()compact_context()└─ run_native_llm_step(ChatUnifier, selected provider/model)@@ -261,7 +261,7 @@ path-dependent:- `custom_threshold` is honored by `track()` and `stats()` on the in-processpath.- `AgentWorkflow` (F4.B) calculates a ratio-based threshold during- `agent.prepare_payload.v1`; it does not read `custom_threshold`.+ `agent.prepare_payload`; it does not read `custom_threshold`.- `compaction_enabled` is stored but is not consulted by `track()` or F4.B.Only the global `COMPACTION_ENABLED` value controls `track()` today, and F4.Bdoes not currently honor that global enabled flag when it extracts the@@ -519,8 +519,8 @@ if tracking.get('needs_compaction') and memory_content and api_key:F4.B performs a parallel check inside `AgentWorkflow` using the workflow'sactive-context usage counter and the ratio-based threshold recorded by-`agent.prepare_payload.v1`. It invokes the same `compact_context()` method-through `agent.compact_memory.v1`.+`agent.prepare_payload`. It invokes the same `compact_context()` method+through `agent.compact_memory`.### AI Service Wiringdiff --git a/docs-internal/memory_lifecycle.md b/docs-internal/memory_lifecycle.mdindex 37658a07..bea03818 100644--- a/docs-internal/memory_lifecycle.md+++ b/docs-internal/memory_lifecycle.md@@ -1,5 +1,27 @@# Memory Lifecycle+> ## ⚠ Partly superseded by RFC-0002+>+> This document describes the pre-RFC-0002 model, in which `simpleMemory` hung+> off an agent's `input-memory` handle and held the conversation transcript as+> Markdown. **That model no longer exists.** Conversation state is now the+> backend-owned Context journal (`server/nodes/context/`, `input-context`), and+> `simpleMemory` is a `ToolNode` on `input-tools` holding durable facts the+> agent explicitly remembers — it has no transcript and no markdown surface.+>+> **Still accurate here:** §2 (the `services/memory/` markdown + JSONL helper+> API), §3 (`services.memory` canonicality, `append_memory_turns_atomic`), §4+> (vector store), §6 (the `claude_code_agent` stable-`cwd` session bridge), §9,+> and §10.+>+> **Stale here:** §1's framing, §5 (state-clear orchestration — `memory_content`+> is gone and `clear_memory` moved to `services/skills/handlers.py`), §7 (the+> seven-step lifecycle), §8 (per-agent memory shapes), and §11's warning about+> writing to `simpleMemory.memory_content`.+>+> For the current model see "Context and Memory (RFC-0002)" in `CLAUDE.md` and+> [RFC-0002](../RFC-0002-AGENT-CONTEXT-AND-MEMORY.md).+Canonical home for how conversation memory is loaded, appended, trimmed, archived, cleared, and resumed across every OpenCompany agent. Replaces the partial explanations previously scattered across `agent_architecture.md`, `cli_agent_framework.md`, `rlm_service.md`, and `memory_compaction.md`.> **Related docs:**diff --git a/docs-internal/plugin_system.md b/docs-internal/plugin_system.mdindex f5fb8f88..49780c0b 100644--- a/docs-internal/plugin_system.md+++ b/docs-internal/plugin_system.md@@ -481,14 +481,14 @@ flips agent dispatch from activity to **child workflow**. The```AgentWorkflow.run(payload):loop until "final" or max_iterations:- 1. execute_activity("agent.execute_llm_step.v1") -> kind + content/calls+ 1. execute_activity("agent.execute_llm_step") -> kind + content/calls2. if kind == "tool_calls":for each call: execute_activity(f"node.{tool_type}.v{version}")- 3. execute_activity("agent.persist_turn.v1") # append memory per turn- 4. if compaction threshold: execute_activity("agent.compact_memory.v1")+ 3. execute_activity("agent.persist_turn") # append memory per turn+ 4. if compaction threshold: execute_activity("agent.compact_memory")```-The worker registers 16 `agent.*.v1` activities alongside the per-type+The worker registers the `agent.*` activities alongside the per-typeactivities. The three shown above are the core model/persistence/compactionsteps; the remainder cover payload preparation, progress and outputpersistence, tool/skill refresh, delegation lifecycle, and team finalization.@@ -549,7 +549,7 @@ themselves** into those registries from their package `__init__.py`.```server/nodes/telegram/-├── __init__.py # imports + register_* calls covering six registries (no logic)+├── __init__.py # imports + register_* calls covering seven registries (no logic)├── _credentials.py # TelegramCredential (ApiKeyCredential)├── _service.py # TelegramService singleton (bot lifecycle)├── _handlers.py # WebSocket handlers + WS_HANDLERS dict@@ -564,7 +564,7 @@ Underscore-prefixed files are package-private; the `nodes` walkerskips them. The two non-underscore files are the plugin classes (oneper node type) — same pattern as every other folder.-### Up to six cross-cutting registries — use only what your plugin needs+### Up to seven cross-cutting registries — use only what your plugin needs| Concern | Registry module | Register from plugin via ||---|---|---|@@ -574,6 +574,7 @@ per node type) — same pattern as every other folder.| Service-status refresh on WebSocket connect | `services.status_broadcaster` | `register_service_refresh(callback)` || Per-node output schema (when not auto-derivable) | `services.node_output_schemas` | `register_output_schema(node_type, ModelClass)` || FastAPI HTTP router (OAuth callbacks, webhook receivers, etc.) | `services.ws_handler_registry` | `register_router(router, name='<plugin>')` — Wave 11.I; declare a `_router.py` exposing an `APIRouter` and call from `__init__.py`. Discovered at startup via `services.ws_handler_registry.get_routers()`. |+| Agent Context descriptor (node connected on `input-context`) | `services.plugin.edge_walker` | `register_agent_context_builder(async_fn)` — RFC-0002; the framework walks the edge but owns no knowledge of the descriptor's keys or thread-selection rules. Reference: `nodes/context/_descriptor.py`. |All accept idempotent re-imports (same callable / class for thesame key is a no-op; conflicts raise `ValueError`).@@ -862,7 +863,7 @@ All Wave 10 invariants in `test_node_spec.py` still run; Wave 11 invariants in `remains.)- Wave 11.G — Nodes cookbook (`server/nodes/README.md`) + CLAUDE.mdplugin section + this file refreshed to match shipped state.-- Wave 11.H — Self-contained plugin folders. Six generic registries+- Wave 11.H — Self-contained plugin folders. Seven generic registriesreplace per-plugin hardcoding in core services:`services.ws_handler_registry.register_ws_handlers` (WebSocketcommands), `services.ws_handler_registry.register_router` (FastAPIdiff --git a/server/nodes/README.md b/server/nodes/README.mdindex c4df714a..c0fcc178 100644--- a/server/nodes/README.md+++ b/server/nodes/README.md@@ -257,7 +257,7 @@ similar plugin.```server/nodes/telegram/-├── __init__.py # imports + register_* calls covering six registries (zero logic)+├── __init__.py # imports + register_* calls covering seven registries (zero logic)├── _credentials.py # TelegramCredential subclass├── _service.py # singleton bot lifecycle (connect / send / poll)├── _handlers.py # WS_HANDLERS dict (telegram_connect, …)@@ -314,7 +314,7 @@ Four ideas worth stealing wholesale:See [Multi-credential nodes](../../docs-internal/plugin_system.md#multi-credential-nodes)for the `ctx.connection(id)` contract and the `routing=` trap that comes with it.-### Six generic registries to plug into+### Seven generic registries to plug intoTelegram's `__init__.py` is the canonical wiring example. Adding anyof these concerns to your plugin is one `register_*` call from your@@ -328,11 +328,12 @@ package's `__init__.py` — the consumer never imports your folder.| Trigger pre-execution check | `services.event_waiter.register_trigger_precheck(node_type, async_fn)` | Generic `triggers.py` handler runs `run_trigger_precheck` before entering the wait loop || Service-status refresh on WS connect | `services.status_broadcaster.register_service_refresh(async_callback)` | Callback runs once per `_refresh_all_services` cycle || Output schema | `services.node_output_schemas.register_output_schema(node_type, ModelClass)` | Avoids declaring a duplicate `Output` class in the central schema file |+| Agent Context descriptor | `services.plugin.edge_walker.register_agent_context_builder(async_fn)` | Turns a node connected on `input-context` into the descriptor the agent runtime consumes. The framework walks the edge but knows nothing about the descriptor's shape — see `nodes/context/_descriptor.py` |-All six are idempotent (same callable / class for the same key is a+All seven are idempotent (same callable / class for the same key is ano-op; conflicts raise `ValueError`).-These six are the core self-contained-folder set; newer concerns have+These seven are the core self-contained-folder set; newer concerns havetheir own generic `register_*` entrypoints in the same spirit —`services.events.register_webhook_source`,`services.ws_handler_registry.register_option_loader` /