Skip to content

Self-improving AI Employees for everyone

docs: cli_agent plugin-folder layout — paths + file tables

trohitg5c695d38b832
diff --git a/CLAUDE.md b/CLAUDE.md
index 3193d342..e47a80b6 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -46,13 +46,13 @@ This is a React Flow-based workflow automation platform implementing n8n-inspire
| **[Status Broadcaster](./docs-internal/status_broadcaster.md)** | WebSocket-first communication: StatusBroadcaster singleton, live count via `len(MESSAGE_HANDLERS) + len(get_ws_handlers())`, broadcast message types, Android two-state model |
| **[RLM Service](./docs-internal/rlm_service.md)** | Recursive Language Model agent with REPL-based execution (llm_query, rlm_query, FINAL) |
| **[Claude Code Agent](./docs-internal/claude_code_agent_architecture.md)** | Claude Code integration internals (LangGraph reference; companion to `cli_agent_framework.md`) |
-| **[CLI Agent Framework](./docs-internal/cli_agent_framework.md)** | Multi-provider CLI runtime (Claude Code / Codex / Gemini): `AICliService.run_batch`, per-task worktree isolation, FastMCP bridge, **memory bridge** (`--continue` for first run + intra-process stream-json multi-turn + `--resume <UUID>` for crash recovery, all on a stable `cwd=repo_root`; `node_parameters_updated` broadcast on every successful turn). |
+| **[CLI Agent Framework](./docs-internal/cli_agent_framework.md)** | Multi-provider CLI runtime (Claude Code / Codex / Gemini): `AICliService.run_batch`, per-task worktree isolation, FastMCP bridge, **memory bridge** (`--continue` for first run + intra-process stream-json multi-turn + `--resume <UUID>` for crash recovery, all on a stable `cwd=repo_root`; `node_parameters_updated` broadcast on every successful turn). **Plugin-folder layout** (post-cutover): all claude-specific code lives in [`server/nodes/agent/claude_code_agent/`](./server/nodes/agent/claude_code_agent/) — `_provider.py`, `_pool.py`, `_skills.py`, `_oauth.py`, `_handlers.py` — and self-registers via three `factory.py` registries (`register_provider` / `register_session_pool` / `register_skill_materialiser`) plus `register_ws_handlers`. The generic framework at `services/cli_agent/` imports nothing from `nodes/`. |
| **[Claude Code Interactive Mode](./docs-internal/claude_code_interactive_mode.md)** | The interactive-mode cutover: MachinaOs no longer uses `claude -p` headless. `ClaudeSessionPool` (keyed by `simpleMemory.node_id`) spawns `claude` as a plain subprocess with stdio pipes — **no PTY** — and drives it over the VSCode-extension protocol: `--output-format stream-json --input-format stream-json --verbose --ide`. User prompts written as JSON to `proc.stdin` (`{"type":"user","message":{"role":"user","content":"..."}}\n`); `system/init` / `assistant` / `result` / `system/compact_boundary` events stream back on `proc.stdout` (parsed by a background `stdout_reader_task` — the on-disk JSONL is persistence-only, not the runtime contract, because `result` events are stdout-only in stream-json mode). Cross-platform via plain pipes (the earlier PTY pattern was broken on Windows because pywinpty/ConPTY's emulated stdin never reached claude's Ink TUI keystroke handler). Stays in interactive billing — entrypoint `claude-vscode`, NOT `sdk-cli`. Multi-turn within one warm subprocess preserves the session UUID (verified end-to-end); cross-batch continuity via `--continue` (first run) or `--resume <UUID>` (crash recovery). Four typed CloudEvents (`claude.session.{spawned,cleared,terminated,usage}`) fire from the pool. `/compact` events forward to `CompactionService`. The non-pooled `AICliSession` path (one-shot prompt-in-argv runs) still uses PTY (out of scope for this refactor; works on POSIX). |
| **[CLI Agent Canonical Patterns RFC](./docs-internal/cli_agent_canonical_patterns_rfc.md)** | Audit of MachinaOs's `services/cli_agent` against the official Claude Code spec — six invariants (skills-as-files, MCP-only transport, `list_changed`, deferral, visible-tool filtering, native-session-continuity-via-stable-cwd) with current implementation status. |
-| **[Claude Code CLI Reference (snapshot)](./docs-internal/claude_code_cli_reference.md)** | Verbatim snapshot of [code.claude.com/docs/en/cli-reference](https://code.claude.com/docs/en/cli-reference) — every CLI subcommand + flag + system-prompt-flag matrix + the subset we emit from `services/cli_agent/providers/anthropic_claude.py`. Fetched 2026-05-11. |
+| **[Claude Code CLI Reference (snapshot)](./docs-internal/claude_code_cli_reference.md)** | Verbatim snapshot of [code.claude.com/docs/en/cli-reference](https://code.claude.com/docs/en/cli-reference) — every CLI subcommand + flag + system-prompt-flag matrix + the subset we emit from `nodes/agent/claude_code_agent/_provider.py`. Fetched 2026-05-11. |
| **[Claude Code Env Vars (snapshot)](./docs-internal/claude_code_env_vars_reference.md)** | Categorised [code.claude.com/docs/en/env-vars](https://code.claude.com/docs/en/env-vars) snapshot — auth, Bedrock/Vertex, model, bash, MCP, telemetry, session/debug, paths. Documents `CLAUDE_CONFIG_DIR`, `MAX_MCP_OUTPUT_TOKENS`, `ENABLE_TOOL_SEARCH` which we touch directly. |
| **[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 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 `nodes/agent/claude_code_agent/_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`. |
| **[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) |
@@ -3476,7 +3476,7 @@ When `simpleMemory` is connected to `claude_code_agent`, memory continuity is ha
1. **Stable cwd.** The pool keeps `cwd = repo_root` for every memory-bound spawn (no per-task worktree carving). Same cwd every run → claude's `project_key` is constant → `--continue` / `--resume <UUID>` resolve against the same JSONL across batches.
2. **`--continue` first, intra-process thereafter.** [`claude_code_agent.execute_op`](./server/nodes/agent/claude_code_agent/__init__.py) sets `spec.continue_session = bool(memory_data)` so the first cold spawn for a memory-wired run emits `--continue` (claude auto-loads the most recent conversation under the cwd's `project_key`, per [code.claude.com/docs/en/cli-reference](https://code.claude.com/docs/en/cli-reference)). Subsequent turns are written as stream-json to the SAME warm subprocess's `proc.stdin` — claude keeps the conversation in-process with the same `session_id` (verified: turn 1 + turn 2 share UUID within one process).
-3. **`--resume <UUID>` crash recovery.** If the warm subprocess dies between batches, [`ClaudeSessionPool.acquire`](./server/services/cli_agent/session_pool.py) detects `process.returncode is not None`, captures the dead session's `current_session_uuid` (last seen on a `result` event), and respawns with `--resume <captured_uuid>` so the same on-disk JSONL keeps growing. Mutually exclusive with `--continue` in `providers/anthropic_claude.py:interactive_argv`.
+3. **`--resume <UUID>` crash recovery.** If the warm subprocess dies between batches, [`ClaudeSessionPool.acquire`](./server/nodes/agent/claude_code_agent/_pool.py) detects `process.returncode is not None`, captures the dead session's `current_session_uuid` (last seen on a `result` event), and respawns with `--resume <captured_uuid>` so the same on-disk JSONL keeps growing. Mutually exclusive with `--continue` in `nodes/agent/claude_code_agent/_provider.py:interactive_argv`.
**`memory_content` is the UI mirror, not the resume channel.** Claude reads its own JSONL via `--continue` / `--resume`. The markdown in `memory_content` is appended every successful run (same `append_to_memory_markdown` + `trim_markdown_window` helpers aiAgent uses) so the human reader sees the conversation. User edits to `memory_content` do not influence claude's next response.
@@ -3492,7 +3492,7 @@ When `simpleMemory` is connected to `claude_code_agent`, memory continuity is ha
**Strict tool allowlist — no claude built-ins (except conditional `Skill`), gated by `--permission-mode dontAsk`.** The spawn argv emits `--permission-mode dontAsk` (documented as *"only pre-approved tools, no prompts"* per [code.claude.com/docs/en/permission-modes](https://code.claude.com/docs/en/permission-modes)) so `--allowedTools` is actually enforced. The previous default `bypassPermissions` *"skips the permission layer entirely"* — same doc — which turned the allowlist into documentation-only and let claude's built-in `Read` / `Edit` / `Bash` / `Glob` / `Grep` / `Write` / `Skill` / `WebSearch` / `WebFetch` fire regardless of wiring. The new `--allowedTools` list contains exactly: (a) one `mcp__machinaos__<node_type>` per node wired through the agent's `input-tools` handle, (b) the claude built-in `Skill` **conditionally** — only when at least one skill is wired through `input-skill` (paired with the materialisation helper below; never enabled when no skill is connected), (c) the five MachinaOs MCP infrastructure tools (`getWorkspaceFiles`, `listSkills`, `getSkill`, `getCredential`, `broadcastLog`). Every filesystem / shell / web operation flows through wired MCP tools (`fileRead` / `fileModify` / `fsSearch` / `shell` / `browser` / `perplexitySearch`) — explicit wiring, no built-in escape hatches. Defaults live in [`server/config/ai_cli_providers.json`](./server/config/ai_cli_providers.json) (`default_allowed_tools: ""`, `default_permission_mode: "dontAsk"`); per-task override via `ClaudeTaskSpec.allowed_tools` is honored verbatim (no auto-merge).
-**Skill materialisation — per-workflow workspace, live-watched, diff-based.** [`services/cli_agent/_skills.py::materialise_skills`](./server/services/cli_agent/_skills.py) writes connected-AND-enabled SKILL.md trees under `<workspace_dir>/.claude/skills/<name>/` where `workspace_dir = data/workspaces/<workflow_id>/`. The workspace is passed via `--add-dir`, and claude scans `.claude/skills/` inside every `--add-dir` path per [the skills spec's "Automatic discovery from parent and nested directories" rule](https://code.claude.com/docs/en/skills#automatic-discovery-from-parent-and-nested-directories) — gives us per-workflow isolation (workflow A's skills can't bleed into workflow B's subprocess even when both spawn with `cwd=repo_root`). Pool tracks the materialised set in `PooledClaudeSession.materialised_skills: frozenset[str]`; on warm reuse, `acquire` calls `materialise_skills(workspace_dir, new_set, previous_skill_names=session.materialised_skills)` and the helper applies only the diff — `rmtree`'d skills disappear from claude's registry, new ones become invocable, all without respawning. Claude's [live filesystem watcher](https://code.claude.com/docs/en/skills#live-change-detection) picks up both edge events. Same helper drives both pool path and `AICliSession._pre_spawn` (non-pool) — uniform behaviour across transports. **Migration note**: pre-cutover the pool path wrote into `<repo_root>/.claude/skills/` so SKILL.md trees accumulated in the user's actual repo (gitignored but visible). Run `rm -rf .claude/skills/` once from the repo root to clean accumulated trees; future runs only write into per-workflow workspaces. We deliberately do NOT auto-prune because the repo's `.claude/` may contain user-authored skills outside the MachinaOs registry. **Architecture rationale**: surveyed alternatives — MCP `resources`/`prompts` require `@mention`/`/command` (not auto-loaded), hooks fire after skill discovery, `settings.json` doesn't expose per-session paths. Anthropic's own [Agent SDK Skills](https://code.claude.com/docs/en/agent-sdk/skills) uses the same filesystem-first pattern. Workspace-dir + live-watch is canonical.
+**Skill materialisation — per-workflow workspace, live-watched, diff-based.** [`nodes/agent/claude_code_agent/_skills.py::materialise_skills`](./server/nodes/agent/claude_code_agent/_skills.py) writes connected-AND-enabled SKILL.md trees under `<workspace_dir>/.claude/skills/<name>/` where `workspace_dir = data/workspaces/<workflow_id>/`. The workspace is passed via `--add-dir`, and claude scans `.claude/skills/` inside every `--add-dir` path per [the skills spec's "Automatic discovery from parent and nested directories" rule](https://code.claude.com/docs/en/skills#automatic-discovery-from-parent-and-nested-directories) — gives us per-workflow isolation (workflow A's skills can't bleed into workflow B's subprocess even when both spawn with `cwd=repo_root`). Pool tracks the materialised set in `PooledClaudeSession.materialised_skills: frozenset[str]`; on warm reuse, `acquire` calls `materialise_skills(workspace_dir, new_set, previous_skill_names=session.materialised_skills)` and the helper applies only the diff — `rmtree`'d skills disappear from claude's registry, new ones become invocable, all without respawning. Claude's [live filesystem watcher](https://code.claude.com/docs/en/skills#live-change-detection) picks up both edge events. Same helper drives both pool path and `AICliSession._pre_spawn` (non-pool) — uniform behaviour across transports. **Migration note**: pre-cutover the pool path wrote into `<repo_root>/.claude/skills/` so SKILL.md trees accumulated in the user's actual repo (gitignored but visible). Run `rm -rf .claude/skills/` once from the repo root to clean accumulated trees; future runs only write into per-workflow workspaces. We deliberately do NOT auto-prune because the repo's `.claude/` may contain user-authored skills outside the MachinaOs registry. **Architecture rationale**: surveyed alternatives — MCP `resources`/`prompts` require `@mention`/`/command` (not auto-loaded), hooks fire after skill discovery, `settings.json` doesn't expose per-session paths. Anthropic's own [Agent SDK Skills](https://code.claude.com/docs/en/agent-sdk/skills) uses the same filesystem-first pattern. Workspace-dir + live-watch is canonical.
**Warm-subprocess tool-surface rebind — no respawn cost.** Claude bakes the MCP bearer token into argv (`--mcp-config`) at spawn time and can't rotate without respawning. The pool stashes the spawn-time token on `PooledClaudeSession.batch_token` so subsequent batches can rebind the same persistent `BatchContext` in place. On warm reuse, `ClaudeSessionPool.acquire` calls [`rebind_batch(existing.batch_token, connected_tools=new_ctx.connected_tools, ...)`](./server/services/cli_agent/mcp_server.py) — diffs old vs new tool lists, calls `unexpose_workflow_tools(removed)` to decrement FastMCP refcounts (so a disconnected `duckduckgoSearch` falls off the tool list when its refcount hits zero), `expose_workflow_tools(added)` for newly-wired ones, then unregisters the redundant new token. `_terminate_locked` calls `unregister_batch(session.batch_token)` so refcounts drain on pool eviction / `clear` / `shutdown_all` (closes the long-standing leak where every pooled run permanently incremented every wired tool's refcount). The per-handler scope check in `workflow_tools._build_handler` reads `ctx.connected_tools` at call time, so even if claude's frozen `--allowedTools` argv still references a now-disconnected tool, the handler returns `{"error": "...not connected to this batch", "status": 403}` — double-lock against tool leakage across warm-reuse turns.
diff --git a/docs-internal/claude_code_interactive_mode.md b/docs-internal/claude_code_interactive_mode.md
index e254f99d..2c1ee62b 100644
--- a/docs-internal/claude_code_interactive_mode.md
+++ b/docs-internal/claude_code_interactive_mode.md
@@ -45,21 +45,35 @@ A background `stdout_reader_task` parses each line and dispatches via
| **Context reset (`/clear` equivalent)** | kill subprocess + drop captured UUID — stream-json input has no slash-command path (confirmed in VSCode extension source) |
| **Crash recovery** | `acquire()` checks `process.returncode`; respawns with `--resume <captured_uuid>` so the same on-disk JSONL keeps growing |
-### Code layout (`server/services/cli_agent/`)
+### Code layout
+
+Per the canonical plugin-folder pattern, every claude-specific
+module lives under `server/nodes/agent/claude_code_agent/`. The
+generic framework under `server/services/cli_agent/` owns only
+the shared dispatcher + per-provider registries that the plugin
+self-registers into on import.
```
-cli_agent/
-├── providers/
-│ └── anthropic_claude.py # interactive_argv — emits the four VSCode-pattern flags
-├── jsonl_watcher.py # still used by the non-pooled AICliSession; NOT used by the pool
-├── session.py # AICliSession — one-shot non-pooled path (PTY on POSIX; out of scope for this refactor)
-├── session_pool.py # ClaudeSessionPool — subprocess-based warm-process reuse
-└── service.py # AICliService.run_batch — entry point; routes to pool when memory-bound
+server/nodes/agent/claude_code_agent/
+├── __init__.py # plugin class + 4 self-registration lines (provider, pool, materialiser, ws handlers)
+├── _provider.py # AnthropicClaudeProvider — interactive_argv emits the four VSCode-pattern flags
+├── _pool.py # ClaudeSessionPool — subprocess-based warm-process reuse
+├── _skills.py # materialise_skills — per-workflow SKILL.md materialisation + live diff
+├── _oauth.py # claude_binary_path, claude_auth_* — project-local install + the documented CLI subcommands
+└── _handlers.py # claude_code_login / claude_code_logout WS handlers
+
+server/services/cli_agent/ (generic framework — shared by all CLI plugins)
+├── factory.py # register_provider / register_session_pool / register_skill_materialiser registries
+├── service.py # AICliService.run_batch — dispatcher; routes to pool when memory-bound (registry lookup)
+├── session.py # AICliSession — one-shot non-pooled path (still PTY on POSIX; out of scope)
+├── mcp_server.py # BatchContext + FastMCP bridge (shared by every CLI provider)
+├── workflow_tools.py / lockfile.py / jsonl_watcher.py / config.py / protocol.py / types.py / _cli_auth.py
+└── _handlers.py # codex WS handlers only (will move once codex_agent migrates)
```
## argv shape
-Built by [`AnthropicClaudeProvider.interactive_argv`](../server/services/cli_agent/providers/anthropic_claude.py).
+Built by [`AnthropicClaudeProvider.interactive_argv`](../server/nodes/agent/claude_code_agent/_provider.py).
Stable head, task-driven tail:
```
@@ -107,7 +121,7 @@ allowlist gate.
## Session pool — warm-process reuse
-[`ClaudeSessionPool`](../server/services/cli_agent/session_pool.py) is
+[`ClaudeSessionPool`](../server/nodes/agent/claude_code_agent/_pool.py) is
keyed by `simpleMemory.node_id`. Each entry is a
`PooledClaudeSession` carrying the live `asyncio.subprocess.Process`,
the captured session UUID (filled in from the first event that has
@@ -187,7 +201,7 @@ ferried UUID).
lifetime of its process — the JSON blob (token included) is frozen
into argv and can never be rotated without respawning. The pool
stashes the spawn-time token on
-[`PooledClaudeSession.batch_token`](../server/services/cli_agent/session_pool.py)
+[`PooledClaudeSession.batch_token`](../server/nodes/agent/claude_code_agent/_pool.py)
so subsequent batches can find and update its bound `BatchContext`.
Token lifecycle, three phases:
@@ -294,7 +308,7 @@ actually enforced (see "argv shape" above for why `bypassPermissions`
was the wrong default).
**Skills — per-workflow workspace, live-watched, diff-based.**
-[`services/cli_agent/_skills.py::materialise_skills`](../server/services/cli_agent/_skills.py)
+[`nodes/agent/claude_code_agent/_skills.py::materialise_skills`](../server/nodes/agent/claude_code_agent/_skills.py)
writes one `SKILL.md` tree per connected-and-enabled skill under
`<workspace_dir>/.claude/skills/<name>/`. The workspace dir
(`data/workspaces/<workflow_id>/`) is already passed via
diff --git a/docs-internal/cli_agent_framework.md b/docs-internal/cli_agent_framework.md
index a427241f..09b2bd3b 100644
--- a/docs-internal/cli_agent_framework.md
+++ b/docs-internal/cli_agent_framework.md
@@ -4,7 +4,7 @@ Multi-instance, multi-provider runtime for AI CLI agents (Claude Code, Codex, Ge
| Provider | Status | Login flow |
|---|---|---|
-| Claude Code (`@anthropic-ai/claude-code`) | shipping | Local-install + spawn (`services/claude_oauth.py:initiate_claude_oauth`) |
+| Claude Code (`@anthropic-ai/claude-code`) | shipping | Local-install + spawn (`nodes/agent/claude_code_agent/_oauth.py:initiate_claude_oauth`) |
| OpenAI Codex (`@openai/codex`) | shipping (no login flow yet) | User runs `codex login` manually; UI returns a graceful "not yet wired" error |
| Google Gemini (`@google/gemini-cli`) | v2 stub | factory raises `NotImplementedError` |
@@ -49,7 +49,7 @@ Reuses (do not duplicate):
- `services/skill_loader.py` — `scan_skills` / `load_skill` consumed by MCP `listSkills` / `getSkill`
- `services/auth.py` — `AuthService.get_api_key` consumed by MCP `getCredential`
- `services/credential_registry.py` — deep-merge `extends` for `_cli_base` entry
-- `services/claude_oauth.py` — Claude `auth login` / `auth status` / `auth logout` wrappers, project-local npm install at `<repo>/data/claude-machina/npm/`, inherited stdio so the CLI opens the browser itself
+- `nodes/agent/claude_code_agent/_oauth.py` — Claude `auth login` / `auth status` / `auth logout` wrappers, project-local npm install at `<repo>/data/claude-machina/npm/`, inherited stdio so the CLI opens the browser itself
- `nodes/stripe/_handlers.py` — pattern reference for marker-token + catalogue broadcast
## Provider abstraction (mirrors `services/llm/`)
@@ -263,30 +263,55 @@ Lifespan: `main.py` enters `mcp_app.router.lifespan_context()` so `StreamableHTT
## Files (current state)
+### Generic framework — `server/services/cli_agent/`
+
+Shared by every CLI provider plugin. Imports nothing from `nodes/`.
+
+| File | Purpose |
+|---|---|
+| `__init__.py` | Imports `_handlers.py` (codex WS handlers) + registers codex provider; framework-level self-registration only. Claude self-registers from its own plugin folder. |
+| `protocol.py` | `AICliProvider` Protocol + `CanonicalUsage` / `SessionResult` / `BatchResult` dataclasses. |
+| `types.py` | Pydantic discriminated-union task specs + `BatchResultModel` for serialisation. |
+| `config.py` | Loads `server/config/ai_cli_providers.json` (binary, package, defaults, supports flags per provider). |
+| `factory.py` | Three registries (`register_provider`, `register_session_pool`, `register_skill_materialiser`) + lookups + `create_cli_provider(name)`. |
+| `lockfile.py` | VSCode-style IDE lockfile read/write/sweep. |
+| `mcp_server.py` | FastMCP sub-app at `/mcp/ide` with bearer-token middleware + 5 tools + `rebind_batch` for warm-reuse context updates. |
+| `workflow_tools.py` | Per-batch MCP tool exposure (`mcp__machinaos__<node_type>`) + handler scope check + `tools/list_changed` notify. |
+| `session.py` | `AICliSession(BaseProcessSupervisor)` — generic non-pool path (still PTY on POSIX). |
+| `service.py` | `AICliService.run_batch()` — dispatcher; routes to pool when memory-bound via `factory.get_session_pool(provider_name)`. |
+| `_cli_auth.py` | CLI-agnostic `mark_logged_in` / `mark_logged_out` / `broadcast_credential_event` + `"cli-managed"` marker token. Shared by claude + codex handlers. |
+| `_handlers.py` | Codex WS handlers (`codex_cli_login` / `codex_cli_logout`). Claude's moved to the plugin folder. |
+| `providers/openai_codex.py` | Codex provider — sandbox-first, no session continuity. Will move when codex_agent adopts the per-folder layout. |
+| `providers/google_gemini.py` | v2 stub. |
+| `jsonl_watcher.py` | Still used by the non-pooled `AICliSession` (out-of-scope path). |
+
+### Claude plugin — `server/nodes/agent/claude_code_agent/`
+
+Self-contained per the canonical plugin-folder pattern (telegram is
+the reference implementation). Four self-registration calls in
+`__init__.py` wire it into the framework — zero changes to
+`services/cli_agent/` when claude internals change.
+
+| File | Purpose |
+|---|---|
+| `__init__.py` | `ClaudeCodeAgentNode(ActionNode)` + 4 self-registration calls: `register_provider`, `register_session_pool`, `register_skill_materialiser`, `register_ws_handlers`. |
+| `_provider.py` | `AnthropicClaudeProvider` — full claude argv builder + stream-json event parsers + ide_lockfile_dir derivation. |
+| `_pool.py` | `ClaudeSessionPool` — subprocess + stream-json warm-reuse pool, MCP rebind on acquire, skill diff on warm reuse. |
+| `_skills.py` | `materialise_skills(workspace_dir, names, previous_skill_names)` — per-workflow SKILL.md materialisation + diff-based add/remove. |
+| `_oauth.py` | `MACHINA_CLAUDE_DIR`, `claude_binary_path`, `claude_auth_*` — project-local install + the documented CLI subcommands. |
+| `_handlers.py` | `claude_code_login` / `claude_code_logout` WS handlers (registered from `__init__.py` via `register_ws_handlers`). |
+
+### Other touchpoints
+
| File | Purpose |
|---|---|
-| `server/services/cli_agent/__init__.py` | Public re-exports + self-registers WS handlers via `services.ws_handler_registry` (telegram-style plugin-folder pattern). |
-| `server/services/cli_agent/protocol.py` | `AICliProvider` Protocol + `CanonicalUsage` / `SessionResult` / `BatchResult` dataclasses. |
-| `server/services/cli_agent/types.py` | Pydantic discriminated-union task specs + `BatchResultModel` for serialisation. |
-| `server/services/cli_agent/config.py` | Loads `server/config/ai_cli_providers.json` (binary, package, defaults, supports flags per provider). |
-| `server/services/cli_agent/factory.py` | `create_cli_provider(name)` lazy-import factory. |
-| `server/services/cli_agent/lockfile.py` | VSCode-style IDE lockfile read/write/sweep. |
-| `server/services/cli_agent/mcp_server.py` | FastMCP sub-app at `/mcp/ide` with bearer-token middleware + 5 tools. |
-| `server/services/cli_agent/session.py` | `AICliSession(BaseProcessSupervisor)` per task — heart of framework. |
-| `server/services/cli_agent/service.py` | `AICliService.run_batch()` — `asyncio.gather` under `Semaphore(5)` (no separate pool class), cancel hooks. |
-| `server/services/cli_agent/_handlers.py` | Per-provider login/logout WS handlers (`claude_code_*`, `codex_cli_*`). |
-| `server/services/cli_agent/providers/anthropic_claude.py` | Reference Claude provider — full feature surface. |
-| `server/services/cli_agent/providers/openai_codex.py` | Codex provider — sandbox-first. |
-| `server/services/cli_agent/providers/google_gemini.py` | v2 stub. |
-| `server/config/ai_cli_providers.json` | Per-provider config (binary names, npm packages, login/auth_status argvs, lockfile dirs, supports flags). |
-| `server/nodes/agent/claude_code_agent.py` | Refactored — `Params.tasks: list[ClaudeTaskSpec]` + legacy single-prompt fallback. |
-| `server/nodes/agent/codex_agent.py` | New plugin — `Params.tasks: list[CodexTaskSpec]` + sandbox-focused defaults. |
+| `server/config/ai_cli_providers.json` | Per-provider config (binary names, npm packages, login/auth_status argvs, supports flags). |
+| `server/nodes/agent/codex_agent/__init__.py` | Codex node plugin — `Params.tasks: list[CodexTaskSpec]`. (Provider class still lives in `services/cli_agent/providers/openai_codex.py` until this folder adopts the per-folder layout.) |
| `server/nodes/visuals.json` | `claude_code_agent` + `codex_agent` icon/color entries. |
| `server/config/credential_providers.json` | `_cli_base` abstract + `claude_code` + `codex_cli` entries. |
-| `server/services/claude_code_service.py` | Slimmed to a back-compat shim that builds one `ClaudeTaskSpec` and calls `AICliService.run_batch("claude", ...)`. Kept for legacy callers; eventually deletable. |
-| `server/services/claude_oauth.py` | Unchanged. The new framework's Claude login handler reuses this directly. |
-| `server/services/workflow.py` | `cancel_deployment` also calls `get_ai_cli_service().cancel_workflow(workflow_id)`. |
-| `server/main.py` | Mounts `/mcp/ide` sub-app, composes its lifespan, runs stale-lockfile sweep on startup. Side-effect imports `services.cli_agent` so its WS handlers self-register. |
+| `server/services/claude_code_service.py` | Slimmed back-compat shim — builds one `ClaudeTaskSpec` and calls `AICliService.run_batch("claude", ...)`. Eventually deletable. |
+| `server/services/workflow.py` | `cancel_deployment` calls `get_ai_cli_service().cancel_workflow(workflow_id)`. |
+| `server/main.py` | Mounts `/mcp/ide` sub-app, composes its lifespan, runs stale-lockfile sweep on startup. Side-effect imports `services.cli_agent` so its WS handlers self-register. Claude's plugin folder is discovered separately by the node registry. |
| `server/routers/websocket.py` | No CLI handlers inline — discovered via `services.ws_handler_registry.get_ws_handlers()`. |
## Output contract
@@ -365,7 +390,7 @@ finds its own JSONL.
| Crash recovery (subprocess died between batches) | `--resume <captured_uuid>` | `ClaudeSessionPool.acquire` detects `process.returncode is not None`, captures the dead session's `current_session_uuid`, and respawns with `--resume`. Same `cwd=repo_root` → same `project_key` → claude finds the same JSONL it was writing before the crash. Mutually exclusive with `--continue`. |
Argv emission lives in
-[`providers/anthropic_claude.py:interactive_argv`](../server/services/cli_agent/providers/anthropic_claude.py).
+[`nodes/agent/claude_code_agent/_provider.py:interactive_argv`](../server/nodes/agent/claude_code_agent/_provider.py).
The `ClaudeTaskSpec` carries `continue_session: bool` and
`resume_session_id: Optional[str]`. `claude_code_agent.execute_op` sets
`continue_session = bool(memory_data)` for the cold-spawn case; the