Skip to content

Self-improving AI Employees for everyone

docs(claude-code): correct pool, permission and MCP descriptions

trohitg097ba1d36564
diff --git a/docs-internal/claude_code_interactive_mode.md b/docs-internal/claude_code_interactive_mode.md
index f98289e2..069c5670 100644
--- a/docs-internal/claude_code_interactive_mode.md
+++ b/docs-internal/claude_code_interactive_mode.md
@@ -20,13 +20,14 @@ and parsed NDJSON events on stdout. Two reasons to leave `-p`:
1. **Anthropic billing change (2026-06-15).** Per
[`code.claude.com/docs/en/headless`](https://code.claude.com/docs/en/headless),
subscription plans bill `claude -p` and Agent-SDK usage from a
- separate "monthly Agent SDK credit." The interactive entrypoint
- (`claude-vscode`, not `sdk-cli`) stays on the subscription's
- interactive bucket. Dropping `-p` puts us in the user's interactive
- bucket when they supply their own API key.
+ separate "monthly Agent SDK credit." The expectation was that the
+ interactive entrypoint (`claude-vscode`, not `sdk-cli`) stays on the
+ subscription's interactive bucket once `-p` is dropped. **This is
+ unverified:** nothing in OpenCompany checks which entrypoint or
+ billing bucket the CLI reports for these spawns.
2. **Match how Anthropic itself drives `claude` programmatically.** The
- VSCode extension at
- `C:/Users/Tgroh/.vscode/extensions/anthropic.claude-code-2.1.140-win32-x64/extension.js:156`
+ VSCode extension (`$VSCODE_EXT_DIR/anthropic.claude-code-2.1.140-<platform>/extension.js`,
+ line 156)
spawns claude with exactly four flags (`--output-format stream-json
--input-format stream-json --verbose --ide`) and never emits `-p`.
That's the wire we reuse.
@@ -103,7 +104,7 @@ Notable absences (intentional):
|---|---|
| `-p` / `--print` | Drops us into the SDK billing bucket; the whole point of the cutover. |
| Positional prompt (`-- "<text>"`) | Prompt arrives via stdin in stream-json input mode; an argv positional would double-send the first turn. `interactive_argv`'s `include_prompt` parameter is kept for back-compat but ignored. |
-| `--continue` | The CLI reference says it skips sessions created non-interactively (`-p` / stream-json input), which is exactly what the pool spawns, so it never found the prior conversation. Memory-bound runs pass `--resume <last_session_id>` instead (the UUID persisted on the memory node by `_persist_memory`). |
+| `--continue` | Not set by the node's own continuity logic. The CLI reference says it skips sessions created non-interactively (`-p` / stream-json input), which is exactly what the pool spawns, so it never found the prior conversation. Memory-bound runs pass `--resume <last_session_id>` instead (the UUID persisted on the memory node by `_persist_memory`). It is still emitted when a task in the node's `tasks` list sets `continue_session: true`, because `ClaudeTaskSpec` keeps the field. |
| `--include-partial-messages`, `--include-hook-events`, `--max-turns`, `--max-budget-usd`, `--fallback-model` | All `-p`-only. `ClaudeTaskSpec` keeps the fields for back-compat; they're silently dropped here. External cost / turn caps are a Phase 2 follow-up. |
Emitted for session identity:
@@ -115,63 +116,73 @@ Emitted for session identity:
`--permission-mode dontAsk` is the documented mode for *"only
pre-approved tools, no prompts"* per
-[`code.claude.com/docs/en/permission-modes`](https://code.claude.com/docs/en/permission-modes).
-It gates `--allowedTools` strictly — anything not in the allowlist
-returns a permission denial without surfacing a TUI prompt
-(non-interactive automation has no human at the keyboard to click
-"Allow"). The earlier `bypassPermissions` default *"skips the
+[`code.claude.com/docs/en/permission-modes`](https://code.claude.com/docs/en/permission-modes):
+a call that would otherwise prompt is denied instead (non-interactive
+automation has no human at the keyboard to click "Allow"). Only calls
+matching `--allowedTools` run, plus read-only Bash commands, which the
+same doc says run without a rule. `--allowedTools` pre-approves; it
+does not remove Claude's other built-ins from the model's context
+(`--tools` / `--disallowedTools` do that, and neither is emitted by
+default), so the model can still call `Read`, `Bash` and the rest and
+receive a denial. The earlier `bypassPermissions` default *"skips the
permission layer entirely"* (same doc, §"Skip all checks"), which
turned `--allowedTools` / `--disallowedTools` into documentation-only
fields and let claude's built-in `Read` / `Edit` / `Bash` /
`Glob` / `Grep` / `Write` / `Skill` / `WebSearch` / `WebFetch` fire
regardless of wiring. `acceptEdits` was the prior config default but
would prompt for any non-Edit tool — hanging the headless agent.
-`dontAsk` is the only mode that combines no-prompts with a strict
-allowlist gate.
+`dontAsk` is the mode that combines no prompts with denial of
+everything not pre-approved.
## Session pool — warm-process reuse
[`ClaudeSessionPool`](../server/nodes/agent/claude_code_agent/_pool.py) is
keyed by the RFC-0002 conversation key `context_bridge.pool_key`
(`(workflow_id, agent_node_id, generation)`), falling back to the legacy
-`simpleMemory.node_id` only on `input-memory` graphs
-(`services/cli_agent/service.py:359-363`). Each entry is a
+`simpleMemory.node_id` only on `input-memory` graphs (`bound_key` in
+`AICliService.run_batch`). Each entry is a
`PooledClaudeSession` carrying the live `asyncio.subprocess.Process`,
-the captured session UUID (filled in from the first event that has
-one), the MCP bearer token embedded in the spawn argv, a per-session
-`asyncio.Lock`, an `asyncio.Event` signalled by the stdout reader on
-`result`, and a per-turn event buffer.
+the session UUID (set at spawn from the `--session-id` the pool mints
+or the `--resume` UUID; filled in from the first event that has one
+only when neither flag was passed, i.e. a task forced `--continue`),
+the MCP bearer token embedded in the spawn argv, a `turn_lease` and a
+narrower `lock` (both `asyncio.Lock`), an `asyncio.Event` signalled by
+the stdout reader on `result`, and a per-turn event buffer.
| Operation | Behaviour |
|---|---|
-| `acquire(memory_node_id, ...)` | Live + healthy entry → return as-is (warm reuse). Live + dead entry → drop, capture its UUID, spawn fresh with `--resume <UUID>` so the same JSONL keeps growing. No entry → cold spawn. At cap → LRU evict (skipping in-flight). |
+| `acquire(memory_node_id, ...)` | For a Context key `(workflow_id, agent_node_id, generation)`, first terminates any entry for the same workflow and agent with a different generation (reason `generation_changed`), so a Reset's generation bump fences the old process. Then: live + healthy entry → wait for its `turn_lease`, re-check it is still the pooled entry, and warm-reuse it (`_prepare_warm_reuse` rebinds the MCP `BatchContext` and applies the skill diff). Live + dead entry → drop, capture its UUID, spawn fresh with `--resume <UUID>` so the same JSONL keeps growing. No entry → cold spawn. At cap → LRU evict (skipping entries whose `lock` or `turn_lease` is held). Returns with the `turn_lease` held. |
| `send_turn(session, prompt, ...)` | Holds `session.lock`. Clears `result_event` + `events_this_turn`. Writes one stream-json line to `proc.stdin`, awaits `result_event` (timeout = 600s default). Returns a `SessionResult` built from the per-turn event buffer. Persists `result.session_id` onto `session.current_session_uuid`. |
-| `clear(session, ...)` | Kill the subprocess, drop the captured UUID. Next `acquire` spawns fresh with no continuity flag (claude assigns a new UUID). Emits `claude.session.cleared`. |
-| `release(session)` | Updates `last_used_at` so the reaper measures idle from now. |
+| `clear(session, ...)` | Kill the subprocess, drop the captured UUID. Next `acquire` spawns fresh with a newly minted `--session-id`. Emits `claude.session.cleared`. Has no production caller today. |
+| `release(session)` | Releases the `turn_lease` and updates `last_used_at` so the reaper measures idle from now. |
| `terminate(memory_node_id)` | Force-drop a specific entry: close stdin → 2s grace → `proc.kill()` → cancel reader/drain tasks. |
+| `terminate_conversations(workflow_id, ...)` | Terminate the Context-keyed entries of a workflow (optionally one agent); the Context panel's Clear calls it (reason `conversation_cleared`). |
| `shutdown_all()` | Stop the reaper + terminate every entry. Wire into FastAPI's lifespan `shutdown`. |
Lifecycle policy:
- **Idle TTL** 30 min (`_DEFAULT_IDLE_TTL`). Background reaper task
- terminates pooled sessions whose `last_used_at` exceeds the cap AND
- aren't currently locked.
+ terminates pooled sessions whose `last_used_at` exceeds the cap and
+ whose `lock` and `turn_lease` are both free.
- **Max size** 16 (`_DEFAULT_MAX_SIZE`). LRU eviction at cap (skipping
in-flight entries).
-- **Concurrency** — per-key `asyncio.Lock` serialises turns against
- the same pooled subprocess so two `send_turn` calls can't interleave
- their stream-json lines on stdin. `lock.locked()` doubles as the
- reaper's in-flight detector.
+- **Concurrency** — the `turn_lease` is held from `acquire` through
+ the context rebind, `send_turn` and `release`, so a second batch
+ cannot rebind the MCP `BatchContext` after the first batch acquired
+ the session but before its turn ran. The narrower `lock` is held
+ inside `send_turn` so two calls can't interleave their stream-json
+ lines on stdin.
## Stream-json event dispatch
`_handle_stream_event` has three concerns:
-1. **UUID capture.** Any event carrying `session_id` (or `sessionId`)
- seeds `session.current_session_uuid` if it isn't already set —
- `system/init` fires this for fresh spawns, `result` carries the
- authoritative value at turn end. Crash-recovery respawns read this
- field to emit `--resume <UUID>`.
+1. **UUID capture.** The UUID is normally known from spawn (the minted
+ `--session-id` or the `--resume` UUID). Any event carrying
+ `session_id` (or `sessionId`) seeds `session.current_session_uuid`
+ only if it is still empty (a `--continue` spawn), and `send_turn`
+ overwrites it with the `result` event's value at turn end.
+ Crash-recovery respawns read this field to emit `--resume <UUID>`.
2. **Per-turn buffering.** Every event is appended to
`events_this_turn`. When `provider.is_final_event(event)` returns
True (i.e. `event.type == "result"`), `result_event` is set and
@@ -200,6 +211,13 @@ The pool's continuity model is two-layered:
memory node after the previous successful run). If `acquire` finds the
pooled subprocess has died, it splices `--resume <current_session_uuid>`
into the spec so the new subprocess continues the same on-disk JSONL.
+- **Idle reap / LRU eviction / generation change.** `_terminate_locked`
+ pops the entry, and its UUID goes with it, so the next `acquire` is a
+ plain cold spawn with a new `--session-id`. Memory-bound runs still
+ resume through the memory node's `last_session_id`. Context-bound runs
+ store no session UUID anywhere, so they start a fresh Claude session
+ and keep only the text the context bridge renders into the prompt
+ (see "Known gaps").
`ClaudeTaskSpec` carries `session_id`, `resume_session_id` and
`continue_session`; precedence in argv is resume, then continue, then
@@ -254,10 +272,11 @@ reads `ctx.connected_tools` at call time — so even if claude's
frozen `--allowedTools` argv still lists a tool that's since been
disconnected, the handler returns
`{"error": "...not connected to this batch", "status": 403}`.
-Combined with `--permission-mode dontAsk` (strict allowlist gate on
-the claude side) this gives a double-lock: the tool surface visible
-to claude is what the batch wired, no more no less, even across
-warm-reuse turns.
+On the claude side, `--permission-mode dontAsk` denies a call to any
+tool that is not pre-approved. The `--allowedTools` list is frozen in
+the spawn argv, though: a tool wired after the warm process started is
+exposed over MCP by the rebind but is not pre-approved, so claude
+denies it until the process is respawned (see "Known gaps").
## CloudEvents broadcasts
@@ -271,7 +290,7 @@ methods on
|---|---|
| `com.opencompany.claude.session.spawned` | Cold spawn (new subprocess) |
| `com.opencompany.claude.session.cleared` | Explicit `pool.clear` → new UUID on next acquire |
-| `com.opencompany.claude.session.terminated` | Pool terminate (reason: `idle` / `crashed` / `evicted` / `shutdown` / `explicit`) |
+| `com.opencompany.claude.session.terminated` | Pool terminate (reason: `idle` / `evicted` / `crashed` / `generation_changed` / `conversation_cleared` / `acquire_failed` / `shutdown` / `explicit`) |
| `com.opencompany.claude.session.usage` | Each `result` event (per-turn cost + tokens + duration + num_turns) |
The usage event is the source of truth for the simpleMemory usage panel
@@ -282,19 +301,22 @@ store that renders the panel.
## Tools and skills
-**Tools (MCP) — strict allowlist, no claude built-ins.** Spawn argv
+**Tools (MCP) — pre-approved allowlist, no claude built-ins
+pre-approved.** Spawn argv
carries `--mcp-config <json>` (HTTP transport, bearer header) +
`--strict-mcp-config` so the spawned claude only loads OpenCompany's
FastMCP server. The `mcpServers.opencompany` block sets `alwaysLoad:
true` to opt out of MCP tool-search deferral so all
`mcp__opencompany__*` tools enter context at session start.
-`--allowedTools` is the explicit allowlist, and it does NOT include
-claude's built-in escape hatches (`Read`, `Edit`, `Bash`, `Glob`,
-`Grep`, `Write`, `WebSearch`, `WebFetch`) — every workflow already
-wires the equivalents (`fileRead`, `fileModify`, `fsSearch`,
+`--allowedTools` is the explicit pre-approval list, and it does NOT
+include claude's built-in escape hatches (`Read`, `Edit`, `Bash`,
+`Glob`, `Grep`, `Write`, `WebSearch`, `WebFetch`) — every workflow
+already wires the equivalents (`fileRead`, `fileModify`, `fsSearch`,
`shell`, `browser`, `perplexitySearch`, …) as MCP tools, and the
built-ins were the leakage path that let the agent invoke
-capabilities the workflow didn't explicitly grant. The default
+capabilities the workflow didn't explicitly grant. The built-ins stay
+in the model's context, though: calling them is denied under
+`dontAsk`, except read-only Bash commands, which run. The default
allowlist is:
- `mcp__opencompany__<node_type>` per node connected to the agent's
@@ -304,16 +326,17 @@ allowlist is:
least one skill is wired through the agent's `input-skill`
handle. Paired with the `materialise_skills` helper (below)
which writes the connected SKILL.md trees under
- `<cwd>/.claude/skills/` so the built-in skill loader has
- something to discover. The one exception to the
+ `<workspace_dir>/.claude/skills/` (reached through `--add-dir`) so
+ the built-in skill loader has something to discover. The one exception to the
"no claude built-ins" rule, because the alternative (forcing the
agent to load every skill through the `getSkill` MCP round-trip)
is materially worse UX for the common case where the workflow
pre-wired which skills should be on the table.
-- The seven OpenCompany MCP infrastructure tools — `getWorkspaceFiles`,
+- The OpenCompany MCP infrastructure tools — `getWorkspaceFiles`,
`listSkills`, `getSkill`, `readSkillResource`, `searchSkillResource`,
- `getCredential`, `broadcastLog` (`_provider.py:275-283`; defined in
- `services/cli_agent/mcp_server.py:359-560`) — which are how the agent
+ `getCredential`, `broadcastLog` (listed in
+ `AnthropicClaudeProvider.interactive_argv`; defined in
+ `mcp_server._build_tools`) — which are how the agent
reads its workspace, discovers connected skills (when no wiring is
present), pages through and searches a loaded skill's declared
resources, fetches scoped credentials, and surfaces intermediate
@@ -322,9 +345,9 @@ allowlist is:
Callers wanting specific claude built-ins back in opt in per-task via
`ClaudeTaskSpec.allowed_tools` (the field is honored verbatim — no
auto-merge with workflow tools). Default value: empty string.
-Combined with `--permission-mode dontAsk`, the strict allowlist is
-actually enforced (see "argv shape" above for why `bypassPermissions`
-was the wrong default).
+Combined with `--permission-mode dontAsk`, anything not pre-approved
+is denied apart from read-only Bash commands (see "argv shape" above
+for why `bypassPermissions` was the wrong default).
**Skills — per-workflow workspace, live-watched, diff-based.**
[`nodes/agent/claude_code_agent/_skills.py::materialise_skills`](../server/nodes/agent/claude_code_agent/_skills.py)
@@ -391,8 +414,8 @@ claude: sessions spawn in a git worktree under
otherwise), which does not see files dropped by upstream nodes
(`fileDownloader`,
`documentParser`, code executors, etc.). Mirrors the ai_agent
-pattern ([`services/ai.py:1186`](../server/services/ai.py) in
-`execute_agent`, `:1924` in `execute_chat_agent` —
+pattern (the tool config built in `AIService.execute_agent` and
+`execute_chat_agent` in [`services/ai.py`](../server/services/ai.py) —
`config["workspace_dir"] = context.get("workspace_dir", "")`) but
uses claude's native `--add-dir` instead of MCP-tool-config injection
because claude has its own filesystem tools (`Read`, `Edit`, `Glob`,
@@ -415,6 +438,50 @@ claude's `Read` tool inside a pooled turn.
`CompactionService.record(...)` so the local-threshold path doesn't
double-fire on claude's native auto-compaction.
+## Known gaps
+
+Recorded from the code; none is fixed yet, because each fix changes how
+the agent runs.
+
+- **Context-bound runs lose Claude's own session after a reap, an
+ eviction or a generation change.** The pool entry and its UUID are
+ dropped and no UUID is stored for Context-bound runs, so the next run
+ is a fresh Claude session. What survives is the stored conversation,
+ which holds only each turn's original prompt and final response
+ (`SpecializedAgentContextBridge.record_turn`), not tool calls or
+ their results.
+- **The stored transcript is sent again on every turn.** `run_batch`
+ renders the whole stored conversation into the prompt
+ (`augment_prompt`) for every Context-bound run, warm or cold. A warm
+ process already holds the earlier turns, so it sees each earlier
+ exchange again inside every new prompt, and the repeated part grows
+ with the conversation. A crash-recovery `--resume` spawn gets the same
+ duplication.
+- **`--ide` is passed with no lockfile, and the spawn inherits the
+ backend's environment.** `_run_pooled_turn` copies `os.environ` whole
+ and adds only `PYTHONUNBUFFERED`, `CLAUDE_CONFIG_DIR` and the
+ parent-run ids. When the backend was started from an editor's
+ terminal, that editor's variables (including any IDE-integration
+ variables) reach the CLI, where `--ide` may act on them. Not verified
+ at runtime.
+- **`getCredential` and `broadcastLog` are visible to the model and
+ pre-approved.** `getCredential` returns the plaintext value of any
+ credential named in the node's hidden `allowed_credentials` parameter
+ (empty by default, so every call gets a 403); a prompt injection could
+ ask for such a key. `broadcastLog` lets the model write lines into the
+ Terminal panel. See R5 in
+ [cli_agent_canonical_patterns_rfc.md](./cli_agent_canonical_patterns_rfc.md).
+- **Warm reuse keeps the spawn-time flags.** `_prepare_warm_reuse`
+ rebinds only the MCP `BatchContext` and the materialised skill files.
+ `--model`, `--allowedTools` (including whether `Skill` is on it),
+ `--permission-mode`, `--append-system-prompt`, `--add-dir` and
+ `--effort` stay as they were at spawn until the process is reaped,
+ evicted or fenced. A tool, or a first skill, wired after the spawn is
+ exposed but not pre-approved, so `dontAsk` denies it. The rebind also
+ leaves `connected_skill_descriptors` unchanged, so `getSkill`,
+ `readSkillResource` and `searchSkillResource` can work from stale
+ skill descriptors.
+
## What changed (historical note)
The previous iteration of this doc described a PTY transport
diff --git a/docs-internal/cli_agent_canonical_patterns_rfc.md b/docs-internal/cli_agent_canonical_patterns_rfc.md
index 9ad45f34..25c55859 100644
--- a/docs-internal/cli_agent_canonical_patterns_rfc.md
+++ b/docs-internal/cli_agent_canonical_patterns_rfc.md
@@ -241,7 +241,8 @@ Across the official documentation:
> **I-6. Native session continuity needs stable cwd + `--resume <UUID>`.**
> Claude stores per-session JSONL under
> `<CLAUDE_CONFIG_DIR>/projects/<project_key>/<session_id>.jsonl` where
-> `project_key = re.sub(r"[^a-zA-Z0-9.-]", "-", str(cwd))`. Verified
+> `project_key = re.sub(r"[^a-zA-Z0-9-]", "-", str(cwd))` (dots become
+> `-` too; `_PROJECT_KEY_RE` in `session.py`, GitHub issue #132). Verified
> against on-disk dir names: a worktree path of
> `D:\startup\projects\OpenCompany\server\...\wt_t_af48d0a7` produces
> `D--startup-projects-OpenCompany-server-...-wt-t-af48d0a7`.
@@ -293,9 +294,11 @@ stream-json`, `--verbose`, `--ide`, `--model`, `--permission-mode`,
each other and with `--continue`), `--append-system-prompt`,
`--effort`, `--add-dir`, `--disallowedTools`, `--agent`.
-**Never emitted** (`_provider.py:316-320`): `--max-turns`,
-`--max-budget-usd`, `--fallback-model` — all `-p`-only. `ClaudeTaskSpec`
-keeps the fields for back-compat and `interactive_argv` silently drops them.
+**Never emitted** (see the comment above the optional overrides in
+`interactive_argv`): `--max-turns`, `--max-budget-usd`,
+`--fallback-model` — all `-p`-only. `ClaudeTaskSpec` keeps the fields
+for back-compat and `interactive_argv` silently drops them.
+`--continue` is emitted only when a task sets `continue_session: true`.
### 4.2 `--mcp-config` JSON shape
@@ -338,17 +341,22 @@ mcp__opencompany__getCredential,
mcp__opencompany__broadcastLog
```
-(`_provider.py:275-283`.)
+(The infrastructure entries are the literal list at the end of the
+allowlist block in `interactive_argv`.)
-**Post-cutover: strict MCP-only allowlist (gated by `--permission-mode
-dontAsk`).** Claude's built-in escape hatches (`Read`, `Edit`, `Bash`,
+**Post-cutover: MCP-only pre-approval list, under `--permission-mode
+dontAsk`.** Claude's built-in escape hatches (`Read`, `Edit`, `Bash`,
`Glob`, `Grep`, `Write`, `WebSearch`, `WebFetch`) are intentionally NOT
in the default allowlist — equivalent capability is wired explicitly via
the `fileRead` / `fileModify` / `fsSearch` / `shell` / `browser` /
-`perplexitySearch` workflow tools. The built-in `Skill` tool is added
+`perplexitySearch` workflow tools. `--allowedTools` pre-approves; it
+does not remove the built-ins from the model's context, so the model can
+still call them. Under `dontAsk` such a call is denied, except read-only
+Bash commands, which the permission-modes doc says run without a rule.
+The built-in `Skill` tool is added
**conditionally**, only when at least one skill is connected through
`input-skill` (paired with SKILL.md materialisation under
-`<cwd>/.claude/skills/`). Callers can opt specific built-ins back in
+`<workspace_dir>/.claude/skills/`, reached through `--add-dir`). Callers can opt specific built-ins back in
per-task via `ClaudeTaskSpec.allowed_tools`. This reverses the earlier
"WebSearch/WebFetch missing → agent gets denied" gap: the framework now
routes every capability through explicitly wired MCP tools rather than
@@ -359,7 +367,7 @@ built-in fallbacks. Locked by
### 4.4 IDE lockfile
-[`lockfile.py:64-79`](../server/services/cli_agent/lockfile.py): writes
+[`lockfile.py`](../server/services/cli_agent/lockfile.py) (`write_ide_lockfile`): writes
```json
{"port": <int>,
@@ -372,22 +380,23 @@ built-in fallbacks. Locked by
```
**Spec note.** The lockfile is for IDE-host scenarios (VSCode publishes
-this so a spawned `claude` can discover the IDE). The pool path now
-emits `--ide` in its argv, so claude does discover and connect to the
-lockfile's MCP endpoint at spawn time. `transport: "http"` stays —
-that matches what our FastMCP sub-app at `/mcp/ide` actually speaks
-(streamable HTTP). The `"ws"` upgrade (matching what Claude's VSCode
-extension publishes in its own lockfile per the live extension dump
-in [#16434](https://github.com/anthropics/claude-code/issues/16434))
-is **deferred** — `"http"` is interoperable and unblocks the pool
-path today.
+this so a spawned `claude` can discover the IDE). The pool path emits
+`--ide` but writes no lockfile and sets no `CLAUDE_IDE_LOCK`, so there
+is nothing of ours for `--ide` to discover: the MCP connection comes
+only from `--mcp-config`. Only `AICliSession._pre_spawn` writes a
+lockfile, and Claude never runs through it. `transport: "http"` stays
+in the writer — that matches what our FastMCP sub-app at `/mcp/ide`
+speaks (streamable HTTP). The `"ws"` upgrade (matching what Claude's
+VSCode extension publishes in its own lockfile per the live extension
+dump in [#16434](https://github.com/anthropics/claude-code/issues/16434))
+is **deferred**.
### 4.5 FastMCP server tools
[`mcp_server.py`](../server/services/cli_agent/mcp_server.py),
[`workflow_tools.py`](../server/services/cli_agent/workflow_tools.py):
-7 built-in (`mcp_server.py:359-560`): `getWorkspaceFiles`, `listSkills`,
+Built-in (`mcp_server._build_tools`): `getWorkspaceFiles`, `listSkills`,
`getSkill`, `readSkillResource`, `searchSkillResource`, `getCredential`,
`broadcastLog`. The three skill tools dispatch through
`skill_runtime.execute_skill_tool` (`load` / `read_resource` /
@@ -404,10 +413,15 @@ the agent never calls them.
### 4.6 Spawn env
-[`session.py`](../server/services/cli_agent/session.py):
-`PYTHONUNBUFFERED=1`, `CLAUDE_CONFIG_DIR=<OPENCOMPANY_CLAUDE_DIR>` (claude only),
-`<provider.ide_lock_env_var>=<lockfile_path>`,
-`OPENCOMPANY_PARENT_RUN_ID=<workflow_id>:<node_id>:<token[:8]>`.
+For Claude the env is built in
+[`AICliService._run_pooled_turn`](../server/services/cli_agent/service.py):
+the backend's whole `os.environ`, plus `PYTHONUNBUFFERED=1`,
+`CLAUDE_CONFIG_DIR=<OPENCOMPANY_CLAUDE_DIR>` and
+`OPENCOMPANY_PARENT_RUN_ID=<workflow_id>:<session_key>:<token[:8]>`
+(also written as the legacy `MACHINA_PARENT_RUN_ID`). No IDE-lock
+variable is set. The generic `AICliSession.env()` in
+[`session.py`](../server/services/cli_agent/session.py) additionally sets
+`<provider.ide_lock_env_var>=<lockfile_path>` when it wrote a lockfile.
**Spec consideration.** Setting `ENABLE_TOOL_SEARCH=false` here would
disable tool-search deferral globally — alternative to per-server
@@ -433,7 +447,9 @@ The UUID5/`--session-id` prose below is retained for historical context.
**Project-key derivation verified empirically** by listing
`<DATA_DIR>/claude/projects/` on disk and reproducing each name from
-its source cwd via `re.sub(r"[^a-zA-Z0-9.-]", "-", str(cwd))`. Three
+its source cwd via `re.sub(r"[^a-zA-Z0-9-]", "-", str(cwd))` (the
+original check used `[^a-zA-Z0-9.-]`; none of these samples contains a
+dot, and GitHub issue #132 later showed dots are replaced too). Three
sample names matched byte-for-byte:
| cwd | project_key |
@@ -481,41 +497,45 @@ claude wrote on its previous turn stays findable.
### 4.7 Worktree contents
-[`session.py:_pre_spawn`](../server/services/cli_agent/session.py): only
-the git-worktree directory + the IDE lockfile in
-`provider.ide_lockfile_dir`. **No `.claude/skills/`, no `CLAUDE.md`, no
-`AGENTS.md`.**
+*Audit-time finding, since resolved.* At the time of the audit,
+[`session.py:_pre_spawn`](../server/services/cli_agent/session.py)
+created only the git worktree and the IDE lockfile, with no
+`.claude/skills/`, `CLAUDE.md` or `AGENTS.md`.
-**Spec gap (I-1).** Materialise `<worktree>/.claude/skills/<name>/SKILL.md`
-for each connected skill in `_pre_spawn`. Optional: write a synthesised
-`<worktree>/CLAUDE.md` with the connected-tool list — not strictly required
-since `--append-system-prompt` covers it, but `CLAUDE.md` is the
-documented project-instruction surface.
+Today connected skills are materialised under
+`<workspace_dir>/.claude/skills/<name>/SKILL.md` (not inside the
+worktree) by `claude_code_agent/_skills.py::materialise_skills`, called
+from `ClaudeSessionPool._spawn` and `_prepare_warm_reuse`, and reached
+by claude through `--add-dir <workspace_dir>`. No `CLAUDE.md` is
+synthesised.
## 5. Alignment matrix
| Invariant | Status | Action |
|---|---|---|
-| **I-1** Skills as files | **DONE.** [`claude_code_agent/_skills.py::materialise_skills`](../server/nodes/agent/claude_code_agent/_skills.py) writes connected skills to `<cwd>/.claude/skills/<name>/`, invoked from both the pool spawn ([`_pool.py`](../server/nodes/agent/claude_code_agent/_pool.py)) and the non-pool `session.py::_pre_spawn` (via the `get_skill_materialiser` registry in [`services/cli_agent/factory.py`](../server/services/cli_agent/factory.py)). `mcp__opencompany__listSkills` / `getSkill` retained as a transitional fallback. | Drop `getSkill`/`listSkills` MCP tools after one release. |
+| **I-1** Skills as files | **DONE.** [`claude_code_agent/_skills.py::materialise_skills`](../server/nodes/agent/claude_code_agent/_skills.py) writes connected skills to `<workspace_dir>/.claude/skills/<name>/` (reached through `--add-dir`), invoked from the pool's cold spawn and warm reuse ([`_pool.py`](../server/nodes/agent/claude_code_agent/_pool.py)) and from `session.py::_pre_spawn` (via the `get_skill_materialiser` registry in [`services/cli_agent/factory.py`](../server/services/cli_agent/factory.py)), which Claude no longer uses. `mcp__opencompany__listSkills` / `getSkill` retained as a transitional fallback. | Drop `getSkill`/`listSkills` MCP tools after one release. |
| **I-2** MCP transport | **Aligned.** Streamable-HTTP via `--mcp-config`. | None. |
| **I-3** `list_changed` notification | **DONE (`b40011e`).** [`workflow_tools._schedule_list_changed_notify`](../server/services/cli_agent/workflow_tools.py) fires after each `add_tool` / `remove_tool` since FastMCP doesn't emit it automatically. | Optional: unit test asserting `session.send_tool_list_changed` is called. |
| **I-4** Tool-search deferral | **DONE.** `"alwaysLoad": true` set on the `opencompany` server entry in [`claude_code_agent/_provider.py::interactive_argv`](../server/nodes/agent/claude_code_agent/_provider.py). | None. |
-| **I-5** Visible-tool filtering | **Gap.** All 7 built-in OpenCompany MCP tools (including `getCredential`, `broadcastLog`) are visible to the model. | Mark internal-only tools `_meta["anthropic/alwaysLoad"]: false` or filter via FastMCP middleware. **Defer** — not breaking today. |
-| **I-6** Native session continuity | **DONE.** [`session.py`](../server/services/cli_agent/session.py) keeps a stable cwd for memory-bound spawns; the warm-subprocess pool at [`claude_code_agent/_pool.py`](../server/nodes/agent/claude_code_agent/_pool.py) preserves the session across turns. [`claude_code_agent/__init__.py`](../server/nodes/agent/claude_code_agent/__init__.py) sets `resume_session_id = memory_data["last_session_id"]`; argv emits a host-minted `--session-id <uuid4>` on first cold spawn (`_pool.py`) and `--resume <UUID>` on later cold spawns and crash recovery. `--continue` is never emitted; the `continue_session` arm in `_provider.py` is unreachable from the plugin. [`service.py:_persist_memory`](../server/services/cli_agent/service.py) appends turns to `memory_content`, saves `last_session_id` (display-only), broadcasts `node_parameters_updated`, and auto-clears stale UUIDs via `_clear_stale_session_id`. See §4.8. | Markdown `memory_content` remains the UI mirror, not the resume channel. |
-| **System-prompt directive** (Cursor / `CLAUDE.md` pattern) | **DONE (`b40011e`).** Second `--append-system-prompt` listing connected `mcp__opencompany__*` tools. | None. |
-| `--allowedTools` strict MCP-only allowlist | **DONE (superseded R3).** Built-in escape hatches (`Read`/`Edit`/`Bash`/`Glob`/`Grep`/`Write`/`WebSearch`/`WebFetch`) are NOT in the default allowlist; `Skill` is added conditionally (only when a skill is wired). `default_allowed_tools: ""` in [`ai_cli_providers.json`](../server/config/ai_cli_providers.json); allowlist assembled in [`_provider.py::interactive_argv`](../server/nodes/agent/claude_code_agent/_provider.py). Gated by `--permission-mode dontAsk`. | None. |
+| **I-5** Visible-tool filtering | **Gap, still open.** Every built-in OpenCompany MCP tool, including `getCredential` and `broadcastLog`, is visible to the model and pre-approved in `--allowedTools`. | Filter `tools/list` in FastMCP middleware (R5). `_meta["anthropic/alwaysLoad"]: false` would not help: it only defers a tool behind `ToolSearch`, it does not hide it. **Deferred.** |
+| **I-6** Native session continuity | **DONE.** [`AICliService.run_batch`](../server/services/cli_agent/service.py) runs bound sessions in one stable worktree per agent node (`<workspace>/<node>/wt_session`); the warm-subprocess pool at [`claude_code_agent/_pool.py`](../server/nodes/agent/claude_code_agent/_pool.py) preserves the session across turns. [`claude_code_agent/__init__.py`](../server/nodes/agent/claude_code_agent/__init__.py) sets `resume_session_id = memory_data["last_session_id"]`; argv emits a host-minted `--session-id <uuid4>` on first cold spawn (`_pool.py`) and `--resume <UUID>` on later cold spawns and crash recovery. The node's continuity logic never sets `--continue`; a task in the node's `tasks` list that sets `continue_session: true` still gets it. [`service.py:_persist_memory`](../server/services/cli_agent/service.py) appends turns to `memory_content` and saves `last_session_id` (the resume handle the next run reads) in one `append_memory_turns_atomic` write, broadcasts `node_parameters_updated`, and auto-clears stale UUIDs via `_clear_stale_session_id`. See §4.8. | Markdown `memory_content` remains the UI mirror, not the resume channel. |
+| **System-prompt directive** (Cursor / `CLAUDE.md` pattern) | **Not present.** `interactive_argv` emits `--append-system-prompt` only for the task's own `system_prompt`; no directive listing the connected `mcp__opencompany__*` tools is added. | Decide whether it is still wanted now that `alwaysLoad: true` puts the tools in context. |
+| `--allowedTools` MCP-only pre-approval list | **DONE (superseded R3).** Built-in escape hatches (`Read`/`Edit`/`Bash`/`Glob`/`Grep`/`Write`/`WebSearch`/`WebFetch`) are NOT in the default allowlist; `Skill` is added conditionally (only when a skill is wired). `default_allowed_tools: ""` in [`ai_cli_providers.json`](../server/config/ai_cli_providers.json); allowlist assembled in [`_provider.py::interactive_argv`](../server/nodes/agent/claude_code_agent/_provider.py). Under `--permission-mode dontAsk` anything not pre-approved is denied, apart from read-only Bash commands; the built-ins stay visible to the model. | None. |
| Composio-style server-side credentials | **Aligned.** `getCredential` allowlist + `auth_service.get_api_key`. | None. |
| Hermes-style `provider_data` envelope | **Aligned.** [`protocol.py:SessionResult.provider_data`](../server/services/cli_agent/protocol.py). | None. |
| Composio-style parent-run-id | **Aligned.** `OPENCOMPANY_PARENT_RUN_ID` env var. | None. |
## 6. Recommendations (mapped to the spec)
-**R1 (DONE in `b40011e`). Skills materialised into `<cwd>/.claude/skills/<name>/`
-on `_pre_spawn` (Closes I-1).** Uses
+**R1 (DONE in `b40011e`, since moved). Skills materialised as files
+(Closes I-1).** Uses
[`skill_loader.load_skill_async(name)`](../server/services/skill_loader.py).
-For memory-bound runs the cwd is `repo_root` so skills land at
-`<repo_root>/.claude/skills/`; for non-memory runs they go under the
-per-task worktree. MCP `listSkills` / `getSkill` retained as a fallback.
+Today they land under `<workspace_dir>/.claude/skills/<name>/`, written
+by `claude_code_agent/_skills.py::materialise_skills` from the pool's
+cold spawn and warm reuse and found by claude through
+`--add-dir <workspace_dir>`; the cwd is a worktree (`wt_session` for
+bound runs), never the repo root. MCP `listSkills` / `getSkill`
+retained as a fallback.
**R2 (DONE in `b40011e`). `"alwaysLoad": true` set on the `opencompany`
entry in `--mcp-config` (Closes I-4).** Per §2.4: *"…also blocks startup
@@ -528,16 +548,18 @@ The current design instead ships a strict **MCP-only** allowlist:
`default_allowed_tools: ""` in
[`ai_cli_providers.json`](../server/config/ai_cli_providers.json), and
[`_provider.py::interactive_argv`](../server/nodes/agent/claude_code_agent/_provider.py)
-assembles `mcp__opencompany__<node_type>` per wired tool + the 7 infra MCP
+assembles `mcp__opencompany__<node_type>` per wired tool + the infra MCP
tools + the built-in `Skill` (conditionally, when a skill is wired),
-gated by `--permission-mode dontAsk`. `WebSearch`/`WebFetch`/`Bash`/etc.
+under `--permission-mode dontAsk`. `WebSearch`/`WebFetch`/`Bash`/etc.
are intentionally excluded — equivalent capability is wired explicitly
via workflow tools. `ToolSearch` intentionally NOT added — it's
permission-free.
-**R4 (DONE in `b40011e`). System-prompt directive when MCP tools are
-wired (the `CLAUDE.md` / Cursor-rules pattern).** Second
-`--append-system-prompt` listing connected `mcp__opencompany__*` tools.
+**R4 (not present today). System-prompt directive when MCP tools are
+wired (the `CLAUDE.md` / Cursor-rules pattern).** A second
+`--append-system-prompt` listing the connected `mcp__opencompany__*`
+tools is not emitted: `interactive_argv` appends only the task's own
+`system_prompt`.
**R5 (followup).** Filter `getCredential` and `broadcastLog` from the
model-visible tool list — they're host-internal RPC, the model has no
@@ -547,10 +569,13 @@ business calling them. Use FastMCP middleware on `tools/list`.
**R6 (DONE in `ecbe69b`). Native session continuity for memory-bound
runs (Closes I-6).** Three coupled mechanisms:
-1. **Stable cwd.** [`AICliSession.cwd()`](../server/services/cli_agent/session.py)
- returns `self._repo_root` when `memory_bound=True`. `_pre_spawn`
- skips `git worktree add`; `cleanup` skips `git worktree remove`.
- Confirms claude's `project_key` is constant across runs.
+1. **Stable cwd.** As originally shipped,
+ [`AICliSession.cwd()`](../server/services/cli_agent/session.py)
+ returned `self._repo_root` when `memory_bound=True`. Claude no longer
+ runs through `AICliSession`: `AICliService.run_batch` spawns bound
+ pooled sessions in one stable worktree per agent node
+ (`<workspace>/<node>/wt_session`), never the repo root, so claude's
+ `project_key` is constant across runs.
2. **`--session-id` first-run / warm-subprocess multi-turn / `--resume`
later runs and crash recovery.**
@@ -576,7 +601,7 @@ runs (Closes I-6).** Three coupled mechanisms:
recovers automatically.
4. **Live UI refresh.** `_persist_memory` broadcasts
- `node_parameters_updated` after `save_node_parameters` so the
+ `node_parameters_updated` after its `append_memory_turns_atomic` write so the
simpleMemory parameter panel refetches the moment the run
completes — mirrors the manual save broadcast in
[`routers/websocket.py:handle_save_node_parameters`](../server/routers/websocket.py).
@@ -595,9 +620,8 @@ runs (Closes I-6).** Three coupled mechanisms:
Markdown is the UI mirror. The `simpleMemory.memory_content` field
keeps mirroring conversation turns via
-[`services.memory.append_to_memory_markdown`](../server/services/memory/markdown.py)
-+ [`trim_markdown_window`](../server/services/memory/markdown.py) for
-human readability. **It is not the resume channel** — claude reads its
+`services.memory.runtime.append_memory_turns_atomic` for human
+readability. **It is not the resume channel** — claude reads its
own JSONL via `--resume`. User edits to `memory_content` do not
influence claude's next response; the canonical record lives in
claude's on-disk JSONL.
diff --git a/docs-internal/cli_agent_framework.md b/docs-internal/cli_agent_framework.md
index e9e5d910..1a74a9b7 100644
--- a/docs-internal/cli_agent_framework.md
+++ b/docs-internal/cli_agent_framework.md
@@ -5,7 +5,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 | Shared-tree install + spawn (`nodes/agent/claude_code_agent/_oauth.py:run_claude_login`) |
-| OpenAI Codex (`@openai/codex`) | shipping (no login flow yet) | User runs `codex login` manually; UI returns a graceful "not yet wired" error |
+| OpenAI Codex (`@openai/codex`) | **fails on every run** (see Risks); 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` |
Browser automation has its own runtime (the installed Chrome/Edge/Chromium by default, plus a uv-installed browser-use CLI); it is not installed into this bun package tree. See [browser.md](./browser.md) and [browser_workspace.md](./browser_workspace.md) for its lifecycle and live control surface.
@@ -26,13 +26,14 @@ AICliService.run_batch(provider, tasks, *, node_id, workflow_id, workspace_dir)
│ or wt_<run>_<i> per task (ephemeral, removed after the batch)
│ pool.acquire(): cold spawn over stdio pipes, or warm reuse
│ argv: --mcp-config <json> (MCP bearer) ... --ide (no lockfile written)
- │ env: CLAUDE_CONFIG_DIR + OPENCOMPANY_PARENT_RUN_ID
+ │ env: the backend's os.environ + CLAUDE_CONFIG_DIR + OPENCOMPANY_PARENT_RUN_ID
│ pool.send_turn(): stream-json line on stdin, wait for `result` on stdout
│
└──► codex (no session pool) → AICliSession (BaseProcessSupervisor + CodexProvider)
- _pre_spawn(): git worktree add (lockfile only if the provider declares
- `ide_lockfile`; Codex does not)
- wait_for_completion(timeout); cleanup(): terminate_then_kill(5s) + worktree remove
+ _do_start(): binary check, then _pre_spawn() (git worktree add; lockfile
+ only if the provider declares `ide_lockfile`, Codex does not),
+ then raises for every provider except claude, so the run fails
+ cleanup(): terminate_then_kill(5s) + worktree remove
│
│ ◄──── CLI calls back via MCP/HTTP at /mcp/ide/mcp
│ Authorization: Bearer <batch-token> (per-batch isolation)
@@ -43,15 +44,18 @@ BatchResult { tasks: [SessionResult, ...], n_succeeded, n_failed, total_cost_usd
│ token deregistered in finally (non-pool path; a pooled session keeps its
│ spawn-time token until _terminate_locked)
▼
-existing Temporal heartbeat fires per WS broadcast (services/temporal/activities.py:259)
-existing tool-result envelope truncates response at 4000 chars (services/handlers/tools.py:993)
+Temporal keeps the long run alive with activity heartbeats (the per-type activity's periodic
+ heartbeat in BaseNode; the legacy execute_node_activity path heartbeats while waiting in
+ NodeExecutionActivities._execute_via_websocket)
+SessionResult.response is truncated to 4000 chars where the result is built
+ (ClaudeSessionPool._build_result_from_events; AICliSession does the same)
```
Reuses (do not duplicate):
- `services/_supervisor/{base,process,util}.py` — `BaseProcessSupervisor` (locked start/stop, `kill_tree`, `terminate_then_kill(5s)`, drain tasks, Windows `CTRL_BREAK_EVENT`)
- `services/llm/{protocol,registry,config}.py` — Protocol + lazy `register_provider(ProviderSpec)` registry + JSON config blueprint (the old `llm/factory.py` was removed)
-- `services/handlers/tools.py:993` — 4000-char truncation
+- `services/handlers/tools.py` — `_execute_check_delegated_tasks` applies the same 4000-char cut to delegated-agent results
- `services/status_broadcaster.py` — `update_node_status`, `broadcast_terminal_log`
- `services/skill_loader.py` — `scan_skills` / `load_skill` consumed by MCP `listSkills` / `getSkill`
- `services/auth.py` — `AuthService.get_api_key` consumed by MCP `getCredential`
@@ -92,17 +96,18 @@ class AICliProvider(Protocol):
### Claude argv (`AnthropicClaudeProvider.interactive_argv`)
Spawned per task — the binary path comes from
-`nodes.agent.claude_code_agent._oauth.claude_binary_path()` (`_oauth.py:82`;
-the same project-local install the credentials Login button uses) and `CLAUDE_CONFIG_DIR` is
+`nodes.agent.claude_code_agent._oauth.claude_binary_path()` (the same
+project-local install the credentials Login button uses) and `CLAUDE_CONFIG_DIR` is
injected on the spawn env so the agent shares one credential store with
the auth surface.
The pooled path (`ClaudeSessionPool`) spawns claude as a plain
subprocess with stdio pipes — no PTY — and drives it over the
VSCode-extension protocol: prompts written as stream-json to
-`proc.stdin`, events read as stream-json off `proc.stdout`. Stays in
-the interactive billing bucket (entrypoint `claude-vscode`, NOT
-`sdk-cli`) since `-p` / `--print` is never emitted.
+`proc.stdin`, events read as stream-json off `proc.stdout`. `-p` /
+`--print` is never emitted. The expectation that this keeps usage in
+the interactive billing bucket (entrypoint `claude-vscode`, not
+`sdk-cli`) is unverified.
```
~/.opencompany/packages/node_modules/.bin/claude[.exe] # bun's bin shim; runs on bun
@@ -111,7 +116,7 @@ the interactive billing bucket (entrypoint `claude-vscode`, NOT
--verbose # required with stream-json for full event detail
--ide # matches the VSCode extension; no lockfile is written, MCP rides --mcp-config
--model <model>
- [--session-id <UUID> | --resume <UUID>] # mutually exclusive
+ [--resume <UUID> | --continue | --session-id <UUID>] # mutually exclusive, in that precedence
--allowedTools <csv>
--permission-mode <mode>
[--append-system-prompt <text>]
@@ -143,8 +148,10 @@ that path never wrote the prompt (GitHub issues #133 / #134).
Session identity follows the CLI reference: a cold spawn mints
`--session-id <uuid4>` so the UUID is known before the first event;
memory-bound runs pass `--resume <last_session_id>` (persisted on the
-memory node by `_persist_memory`). `--continue` is not used because the
-CLI skips non-interactively created sessions when resolving it. A child
+memory node by `_persist_memory`). The node's continuity logic never
+uses `--continue`, because the CLI skips non-interactively created
+sessions when resolving it; it is still emitted if a task in the node's
+`tasks` list sets `continue_session: true`. A child
that exits without a `result` event wakes `send_turn` on stdout EOF and
reports the exit code instead of burning the turn timeout.
@@ -155,7 +162,7 @@ calls `register_provider(name, factory)` on import (claude from
existing name raises:
```python
-# server/services/cli_agent/factory.py:84-106
+# server/services/cli_agent/factory.py (create_cli_provider)
def create_cli_provider(name: str) -> AICliProvider:
factory = _PROVIDER_REGISTRY.get(name)
if factory is not None:
@@ -187,6 +194,7 @@ class ClaudeTaskSpec(BaseAICliTaskSpec):
provider: Literal["claude"] = "claude"
session_id: Optional[str] = None
resume_session_id: Optional[str] = None
+ continue_session: bool = False # emits --continue; see Session identity
max_turns: Optional[int] = None
max_budget_usd: Optional[float] = None
allowed_tools: Optional[str] = None # default: "" — see "Strict allowlist"
@@ -217,7 +225,7 @@ AICliTaskSpec = Annotated[
]
```
-Each plugin's `Params.tasks` is hard-typed to one variant — the LLM tool-schema plugin fast-path in `_get_tool_schema` (`services/ai.py:2584`) produces a clean per-provider schema (no `$defs`/`$ref`).
+Each plugin's `Params.tasks` is hard-typed to one variant — the LLM tool-schema plugin fast-path in `_get_tool_schema` (`services/ai.py`) produces a clean per-provider schema (no `$defs`/`$ref`).
## Auth model — Stripe-style CLI-managed OAuth
@@ -250,13 +258,13 @@ Steps:
**Codex login**: not yet wired. The handler returns a graceful error pointing the user at `bun add -g @openai/codex` + `codex login` manual flow (the provider itself falls back to `bun x @openai/codex` when no system `codex` is on PATH). Follow-up: mirror `nodes/agent/claude_code_agent/_oauth.py` for codex with a `HOME=<DATA_DIR>/codex/` env redirect (Codex has no `CONFIG_DIR` equivalent).
-**Frontend**: no changes. The existing `client/src/components/credentials/primitives/OAuthConnect.tsx:42-44` already documents and supports the Stripe-style fieldless-CLI case (`config.fields = []`, `kind: "oauth"`, `stored` flag drives Connected state).
+**Frontend**: no changes. The existing `client/src/components/credentials/primitives/OAuthConnect.tsx` already documents and supports the Stripe-style fieldless-CLI case (`config.fields = []`, `kind: "oauth"`, `stored` flag drives Connected state).
## VSCode-style IDE MCP server
-Spawned CLI sessions auto-discover OpenCompany over MCP via the lockfile pattern VSCode's Claude Code extension uses. No custom IPC.
+Claude reaches OpenCompany's MCP server through the `--mcp-config` entry in its argv (URL plus bearer header). No custom IPC.
-Lockfile path: `<DATA_DIR>/claude/ide/<pid>.lock` (Claude — `AnthropicClaudeProvider.ide_lockfile_dir = OPENCOMPANY_CLAUDE_DIR / "ide"`, so it sits under the isolated `CLAUDE_CONFIG_DIR`, not the user's `~/.claude/`) or `<tmpdir>/gemini/ide/gemini-ide-server-<pid>-<port>.json` (Gemini, v2). Format mirrors VSCode (`lockfile.py:64-79`):
+The VSCode-style lockfile (`lockfile.py`) is written only by `AICliSession._pre_spawn`, and only for a provider that declares `ide_lockfile`. Claude declares it but never runs through `AICliSession`, Codex does not declare it, and Gemini is a stub, so in practice no lockfile is written today. For reference, the path is `<DATA_DIR>/claude/ide/<pid>.lock` (Claude — `AnthropicClaudeProvider.ide_lockfile_dir = OPENCOMPANY_CLAUDE_DIR / "ide"`, so it sits under the isolated `CLAUDE_CONFIG_DIR`, not the user's `~/.claude/`) or `<tmpdir>/gemini/ide/gemini-ide-server-<pid>-<port>.json` (Gemini, v2). Format mirrors VSCode (`write_ide_lockfile` in `lockfile.py`):
```json
{
@@ -270,7 +278,7 @@ Lockfile path: `<DATA_DIR>/claude/ide/<pid>.lock` (Claude — `AnthropicClaudePr
}
```
-Two fields are load-bearing. The `url` MUST end in `/mcp/ide/mcp`: FastMCP's `streamable_http_app()` registers the JSON-RPC route at `/mcp` of the sub-app and `main.py` mounts the sub-app at `/mcp/ide`, so the older `/mcp/ide` form silently 404'd before the request reached the bearer-token middleware (`lockfile.py:64-70`). `ideName` is the provider name (`session.py:281` passes `self._provider.name`, which is `"claude"`), not `"opencompany"`.
+Two fields are load-bearing. The `url` MUST end in `/mcp/ide/mcp`: FastMCP's `streamable_http_app()` registers the JSON-RPC route at `/mcp` of the sub-app and `main.py` mounts the sub-app at `/mcp/ide`, so the older `/mcp/ide` form silently 404'd before the request reached the bearer-token middleware. `ideName` is the provider name (`AICliSession._pre_spawn` passes `self._provider.name`), not `"opencompany"`. The same `/mcp/ide/mcp` URL is what the Claude pool puts in `--mcp-config` (`AICliService._run_pooled_turn`).
Bearer-token middleware (`mcp_server.py:_BearerAuthMiddleware`) validates each request against an in-memory per-batch `BatchContext` registry. **Non-pool path**: tokens registered at `AICliService.run_batch()` entry, unregistered in `finally` so 401s flip immediately when a batch settles. **Pool path** (`use_pool=True`, see [Claude Code Interactive Mode](./claude_code_interactive_mode.md#mcp-bearer-token-lifecycle) for the full lifecycle): claude bakes the bearer into argv (`--mcp-config`) at spawn time and can't rotate without respawning, so the pool stashes the spawn-time token on `PooledClaudeSession.batch_token` and rebinds the `BatchContext` in place on warm reuse via `rebind_batch(token, connected_tools=..., ...)` — closes the "disconnected tool still works" leak by (a) diffing `connected_tools` and decrementing FastMCP refcounts for tools dropped between batches, and (b) updating the per-handler scope check's data so `workflow_tools._build_handler` returns 403 for stale tools. `_terminate_locked` calls `unregister_batch(session.batch_token)` so refcounts drain on pool eviction / `clear` / `shutdown_all`.
@@ -302,10 +310,10 @@ Shared by every CLI provider plugin. Imports nothing from `nodes/`.
| `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 mounted at `/mcp/ide` (JSON-RPC endpoint `/mcp/ide/mcp`) with bearer-token middleware + 7 infrastructure tools (`getWorkspaceFiles`, `listSkills`, `getSkill`, `readSkillResource`, `searchSkillResource`, `getCredential`, `broadcastLog`) + `rebind_batch` for warm-reuse context updates. |
+| `mcp_server.py` | FastMCP sub-app mounted at `/mcp/ide` (JSON-RPC endpoint `/mcp/ide/mcp`) with bearer-token middleware + the infrastructure tools (`getWorkspaceFiles`, `listSkills`, `getSkill`, `readSkillResource`, `searchSkillResource`, `getCredential`, `broadcastLog`) + `rebind_batch` for warm-reuse context updates. |
| `context_bridge.py` | `SpecializedAgentContextBridge` — RFC-0002 Context continuity for specialized providers (`resolve` / `augment_prompt` / `record_turn`); shared with RLM and Vertex. |
| `workflow_tools.py` | Per-batch MCP tool exposure (`mcp__opencompany__<node_type>`) + handler scope check + `tools/list_changed` notify. |
-| `session.py` | `AICliSession(BaseProcessSupervisor)` — generic PTY + JSONL path for non-claude providers; not used for claude. |
+| `session.py` | `AICliSession(BaseProcessSupervisor)` — PTY + JSONL path. Not used for claude; `run_batch` uses it for a provider with no session pool (Codex), but `_do_start` raises for every provider except claude, so those runs fail. |
| `service.py` | `AICliService.run_batch()` — dispatcher; every claude task goes to the pool via `factory.get_session_pool(provider_name)` (warm keyed session when bound, ephemeral per-task session otherwise). |
| `_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. |
@@ -395,10 +403,11 @@ key doesn't drift.
### Why native resume needs a stable cwd
-Claude derives `project_key` from cwd via `re.sub(r"[^a-zA-Z0-9.-]", "-", str(cwd))`
-— every `:`, `\`, `/`, `_` becomes `-`. Verified against the on-disk
-`~/.opencompany/claude/projects/` listing — Python reproduces three
-encoded directory names byte-for-byte. The pre-bridge per-task
+Claude derives `project_key` from cwd via `re.sub(r"[^a-zA-Z0-9-]", "-", str(cwd))`
+(`_PROJECT_KEY_RE` in `session.py`) — every `:`, `\`, `/`, `_` and `.`
+becomes `-`. An earlier version kept `.` and watched a directory the
+CLI never wrote to (GitHub issue #132); the fix was checked against the
+on-disk `~/.opencompany/claude/projects/` listing. The pre-bridge per-task
worktree (`<workspace>/<node_id>/wt_t_<random_8hex>`) changed cwd on
every spawn → fresh project_key every run → `--resume <UUID>` looked
under a brand-new directory with zero prior JSONL ("No conversation
@@ -418,7 +427,8 @@ would otherwise ride into every session.
| First cold spawn, no stored session | `--session-id <uuid4>` | `ClaudeSessionPool._spawn` mints the UUID so it is known before the first event; `_persist_memory` stores it on the memory node as `last_session_id`. |
| Cold spawn under a memory-wired node with a stored session | `--resume <last_session_id>` | Resume by UUID, never `--continue`: per [code.claude.com/docs/en/cli-reference](https://code.claude.com/docs/en/cli-reference) `--continue` skips sessions created non-interactively (`-p` / stream-json), which is every session the pool creates. |
| Subsequent turn, SAME warm subprocess | nothing argv-level — stream-json line on `proc.stdin` | The pool keeps the subprocess alive between turns. Claude maintains the conversation in-process; same `session_id` across turns (verified end-to-end). |
-| 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`. |
+| 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 (the stable `<workspace>/<node>/wt_session` worktree) → same `project_key` → claude finds the same JSONL it was writing before the crash. Mutually exclusive with `--continue`. |
+| Idle reap or LRU eviction | `--session-id <new uuid4>`, or `--resume <last_session_id>` when memory-bound | The pool entry and its UUID are dropped. Memory-bound runs resume through the memory node; Context-bound runs start a fresh Claude session and keep only the rendered transcript (see [claude_code_interactive_mode.md → Known gaps](./claude_code_interactive_mode.md#known-gaps)). |
Argv emission lives in
[`nodes/agent/claude_code_agent/_provider.py:interactive_argv`](../server/nodes/agent/claude_code_agent/_provider.py).
@@ -435,21 +445,22 @@ rejects a UUID already in use).
### Plumbing
```
-ClaudeCodeAgentNode.execute_op (__init__.py:263-330)
+ClaudeCodeAgentNode.execute_op (claude_code_agent/__init__.py)
├─ collect_agent_connections() → context_data (first tuple element)
│ ├─ Context node wired: a Context descriptor (kind == "context") → context_descriptor,
│ │ handed to AICliService as connected_context and bridged through
│ │ SpecializedAgentContextBridge; memory_data stays None
│ └─ legacy input-memory graphs: the recorded Memory descriptor → memory_data
│ {node_id, session_id, memory_content, window_size,
- │ long_term_enabled, last_session_id (display-only)}
+ │ long_term_enabled, last_session_id (read on every run)}
├─ resume_session_id = memory_data.get("last_session_id")
- ├─ ClaudeTaskSpec(..., continue_session=continue_session,
- │ resume_session_id=None)
+ ├─ ClaudeTaskSpec(..., resume_session_id=resume_session_id)
+ │ (a task from params.tasks gets it too, unless it set continue_session
+ │ or its own resume_session_id)
└─ AICliService.run_batch(..., connected_memory=memory_data,
broadcaster=...)
└─ For context/memory-wired single-task runs, route through ClaudeSessionPool
- (service.py:357-363 — use_pool = the provider registered a session pool;
+ (run_batch: use_pool = the provider registered a session pool;
bound_key = context_bridge.pool_key, else connected_memory["node_id"],
else None. Unbound batches still run pooled, one ephemeral session per task.)
├─ pool.acquire(session_key, spec, cwd=<workspace>/<node>/wt_session, env, ...)
@@ -473,11 +484,11 @@ ClaudeCodeAgentNode.execute_op (__init__.py:263-330)
│ when claude emits `result`)
├─ pool.release(session) ← marks idle for the reaper
└─ _persist_memory(connected_memory, results, broadcaster):
- ├─ saves params["last_session_id"] = most_recent.session_id
- │ (display-only — claude_code_agent no longer reads it)
- ├─ appends user/assistant turns to params["memory_content"]
- │ via append_to_memory_markdown + trim_markdown_window
- ├─ database.save_node_parameters(memory_node_id, params)
+ ├─ append_memory_turns_atomic(db, memory_node_id, turns,
+ │ window_size=..., parameter_updates={"last_session_id": ...})
+ │ one write: appends the user/assistant turns to
+ │ params["memory_content"] and stores last_session_id, which the
+ │ next run reads for --resume
└─ broadcaster.broadcast_node_parameters_updated(
memory_node_id,
parameters=params,
@@ -515,7 +526,7 @@ a **display mirror**, not the resume channel. Claude's own JSONL on
disk is what `--resume` loads from; `last_session_id` on the memory
node is the resume handle. `_persist_memory`
appends each successful run's prompt + response to `memory_content`
-via `append_to_memory_markdown` so the UI shows the conversation grow
+via `append_memory_turns_atomic` so the UI shows the conversation grow
live. User edits to `memory_content` do NOT influence claude's next
response.
@@ -559,11 +570,11 @@ On a crash-recovery path the trace shows:
| Phase | When | Payload |
|---|---|---|
| `batch_started` | `run_batch` entry | `{provider, n_tasks, max_parallel, isolation:"worktree"}` |
-| `ai_cli_subtask` | per-task partial (NDJSON event) | `{task_id, provider, status:"running", message, cost_usd?, num_turns?}` |
-| `ai_cli_subtask` | per-task final | `{task_id, provider, status:"succeeded"|"failed", cost_usd?, duration_ms, num_turns?, error?}` |
+| `ai_cli_subtask` | per-task partial (NDJSON event); `AICliSession` only | `{task_id, provider, status:"running", message, cost_usd?, num_turns?}` |
+| `ai_cli_subtask` | per-task final; `AICliSession` only | `{task_id, provider, status:"succeeded"|"failed", cost_usd?, duration_ms, num_turns?, error?}` |
| `batch_complete` | aggregator finish | `{provider, n_succeeded, n_failed, total_cost_usd?, wall_clock_ms}` |
-Plus `broadcast_terminal_log(source=f"{provider}:{task_id}", level)` on every NDJSON line — surfaced in the Terminal tab.
+`AICliSession` also calls `broadcast_terminal_log(source=f"{provider}:{task_id}", level)` on every event line for the Terminal tab. The Claude pool emits neither `ai_cli_subtask` nor terminal-log lines: a Claude run surfaces through `batch_started` / `batch_complete`, the node status the plugin sets, and the `claude.session.*` CloudEvents (see [claude_code_interactive_mode.md](./claude_code_interactive_mode.md#cloudevents-broadcasts)).
## Plugin contract — adding a new CLI provider
@@ -594,15 +605,16 @@ Live verification (needs a real Claude install + auth):
1. Empty `~/.opencompany/claude/` + `~/.opencompany/packages/`. Open Credentials Modal → click "Login with Claude Code CLI". Confirm the `bun add` runs (visible in backend logs), `~/.opencompany/packages/node_modules/.bin/claude[.exe]` appears, browser opens for Anthropic OAuth. Modal flips Connected within ~2s of CLI exit (background `claude auth status` poll detects success). The browser tab should render the CLI's own "Signed in" success page (this needs the `stdin=PIPE` spawn — without it the native binary exits early and the tab is left on the bare `localhost/callback` URL).
2. Refresh the page. Modal stays Connected (`auth_service.get_oauth_tokens("claude_code")` still returns the marker; idempotent re-click also stays Connected).
3. Click Disconnect. Modal flips Disconnected (`claude auth logout` clears CLI creds + marker dropped).
-4. Add a `claude_code_agent` node, set `tasks=[{prompt:"echo A"},{prompt:"echo B"},{prompt:"echo C"}]`, run. Three distinct `claude:<task_id>` Terminal streams interleaved. Three distinct session_ids. Three worktrees created and removed. `summary.wall_clock_ms < sum(duration_ms)` (proves parallelism).
-5. With a Claude task running, `cat ~/.opencompany/claude/ide/<pid>.lock` and confirm format. Stream-json shows an `mcp__opencompany__*` tool invocation.
+4. Add a `claude_code_agent` node, set `tasks=[{prompt:"echo A"},{prompt:"echo B"},{prompt:"echo C"}]`, run. Three distinct session_ids. Three `wt_<run>_<i>` worktrees created and removed. `summary.wall_clock_ms < sum(duration_ms)` (proves parallelism).
+5. With a Claude task running that calls a wired tool, the backend log shows `[CC-Agent MCP auth] POST ... -> OK (node=... wf=... token=...)` for MCP requests carrying the `--mcp-config` bearer, and the task result's `tool_calls` is non-zero. No IDE lockfile is written.
6. `curl -H "Authorization: Bearer <wrong>" http://127.0.0.1:${PYTHON_BACKEND_PORT}/mcp/ide/mcp` → 401.
## Risks / open considerations
- **Codex login not yet wired.** v1 returns a graceful error directing the user to `bun add -g @openai/codex` + `codex login`. Follow-up: a codex `_oauth.py` mirroring `nodes/agent/claude_code_agent/_oauth.py` with a `HOME=<DATA_DIR>/codex/` env redirect (Codex has no `CONFIG_DIR` env; `HOME` redirect is risky on Windows, so Windows may need a different strategy or accept user-global Codex auth).
- **Gemini deferred.** `factory.create_cli_provider("gemini")` raises `NotImplementedError` (the one name-specific branch left in the factory, kept so the dropdown can grey it out). v2 work: implement the provider, register it from a `nodes/agent/gemini_cli_agent/` plugin folder, and drop that branch. ~430 LoC. No abstraction changes needed.
-- **`--include-partial-messages`** assumes a recent Claude CLI; older versions fall back gracefully via the parser's `parse_event` returning `None` for unknown shapes.
+- **Codex fails on every run.** No session pool is registered for Codex, so `run_batch` runs it through `AICliSession`, and `AICliSession._do_start` raises for every provider except `claude`. The task comes back failed with `worktree_setup_failed: AICliSession (interactive PTY+JSONL) currently only supports the 'claude' provider ...` (or `cli_not_installed` when the Codex binary is missing). A Codex session class or pool is needed before the node can work.
+- **Claude pool gaps.** Context-bound runs lose Claude's own session after a reap or eviction, the stored transcript is re-sent on every warm turn, the spawn inherits the backend's environment while passing `--ide`, `getCredential` / `broadcastLog` are model-visible, and warm reuse keeps the spawn-time flags and skill descriptors. Details in [claude_code_interactive_mode.md → Known gaps](./claude_code_interactive_mode.md#known-gaps).
- **Native-binary stdin sensitivity.** claude-code >= 2.1.162 ships a native binary that reads stdin during `auth login`. We spawn it with `stdin=asyncio.subprocess.PIPE` (never written) so the read blocks and the OAuth callback server stays alive; an inherited/closed stdin EOFs the binary into an early exit that drops the browser callback. If a future CLI version changes its stdin contract this is the spot to revisit.
- **Marker token written without verifying CLI is actually functional** — we trust `claude auth status`'s exit code. If Anthropic invalidates the token server-side and the CLI hasn't re-checked, the modal still shows Connected until the next session attempt's `detect_auth_error` catches it.
- **MCP SDK is pre-1.0-stable.** Pinned at `mcp>=1.0.0`. The surface is isolated in `mcp_server.py` so an SDK breaking change touches one file.
diff --git a/server/nodes/agent/claude_code_agent/_provider.py b/server/nodes/agent/claude_code_agent/_provider.py
index 47531d8e..0d47e732 100644
--- a/server/nodes/agent/claude_code_agent/_provider.py
+++ b/server/nodes/agent/claude_code_agent/_provider.py
@@ -28,11 +28,14 @@ stream-json --verbose --ide [--mcp-config ...] [--strict-mcp-config]
``ClaudeSessionPool._prepare_warm_reuse``; ``Skill`` enters
``--allowedTools`` iff at least one skill is wired.
-**Permission mode**: ``dontAsk`` (the config default) runs without a
-TUI prompt and denies anything outside ``--allowedTools``, so the
-strict allowlist is actually enforced — non-interactive automation has
-no human at the keyboard to click "Allow." See
-``code.claude.com/docs/en/permission-modes``.
+**Permission mode**: ``dontAsk`` (the config default) never shows a
+prompt: a call that would prompt is denied instead, unless it matches
+``--allowedTools``. Per ``code.claude.com/docs/en/permission-modes``,
+read-only Bash commands still run without a matching rule.
+``--allowedTools`` pre-approves tools; it does not remove Claude's
+other built-ins from the model's context (that is ``--tools`` /
+``--disallowedTools``, neither emitted by default), so the model can
+still call them and gets a denial.
Session identity: a cold spawn with no continuity flag gets a
host-minted ``--session-id <UUID>`` (``ClaudeSessionPool._spawn``) so the
@@ -133,8 +136,7 @@ class AnthropicClaudeProvider:
Spawned as a regular subprocess with stdio pipes — NOT a PTY.
Matches the invocation Anthropic's own VSCode extension uses
- (verified in
- ``C:\\Users\\Tgroh\\.vscode\\extensions\\anthropic.claude-code-2.1.140-win32-x64\\extension.js``
+ (read from ``$VSCODE_EXT_DIR/anthropic.claude-code-2.1.140-<platform>/extension.js``
line 156):
``claude --output-format stream-json --input-format stream-json
@@ -149,10 +151,11 @@ class AnthropicClaudeProvider:
Critically NOT emitted:
- - ``-p`` / ``--print``: keeps us in the interactive billing
- bucket (entrypoint ``claude-vscode``, NOT ``sdk-cli``). The
- VSCode extension confirms this exact pattern works without
- ``--print``.
+ - ``-p`` / ``--print``: the VSCode extension drives the CLI
+ without it. The expectation that this keeps usage in the
+ interactive billing bucket (entrypoint ``claude-vscode``,
+ not ``sdk-cli``) is unverified: nothing here checks the
+ entrypoint the CLI reports.
- The positional prompt (``-- "<prompt>"``): the prompt
arrives via ``proc.stdin`` in stream-json input mode.
``include_prompt`` is kept for back-compat but ignored.
@@ -161,7 +164,7 @@ class AnthropicClaudeProvider:
emitted as ``--mcp-config <json>`` so the spawned claude
registers OpenCompany's FastMCP server. Tools allowlist
(``--allowedTools``) lists every wired ``mcp__opencompany__*``
- plus OpenCompany's seven MCP infrastructure tools, the built-in
+ plus OpenCompany's MCP infrastructure tools, the built-in
``Skill`` only when a skill is wired, and any built-ins the task's
``allowed_tools`` opts in. Skills are materialised under
``<workspace_dir>/.claude/skills/`` by the pool before spawn.
@@ -243,11 +246,14 @@ class AnthropicClaudeProvider:
elif task.session_id:
argv += ["--session-id", task.session_id]
- # Allowed tools — STRICTLY scoped to what the operator wired
- # through ``input-tools`` plus OpenCompany's own MCP infrastructure
+ # Allowed tools — pre-approves what the operator wired through
+ # ``input-tools`` plus OpenCompany's own MCP infrastructure
# tools. Claude's built-in escape hatches (Read, Edit, Bash,
# Glob, Grep, Write, Skill, WebSearch, WebFetch) are intentionally
- # NOT in the default allowlist: they let the agent invoke
+ # NOT pre-approved (they stay in the model's context, since this
+ # flag does not remove tools; under ``dontAsk`` calling them is
+ # denied, except read-only Bash commands, which the CLI runs
+ # anyway): they let the agent invoke
# capabilities the workflow didn't explicitly grant — equivalent
# filesystem / shell / search functionality is wired via the
# ``fileRead`` / ``fileModify`` / ``fsSearch`` / ``shell`` /
@@ -298,17 +304,18 @@ class AnthropicClaudeProvider:
# Permission mode — ``dontAsk`` is the documented mode for
# "only pre-approved tools, no prompts"
- # (https://code.claude.com/docs/en/permission-modes), which is
- # what we want for non-interactive automation with a STRICT
- # tool allowlist. The prior ``bypassPermissions`` default
- # "skips the permission layer entirely" — meaning
- # ``--allowedTools`` and ``--disallowedTools`` become
- # documentation-only and claude's built-in Read / Edit / Bash /
- # Glob / Grep / Write / Skill / WebSearch / WebFetch remain
- # invocable even when not in the allowlist. ``acceptEdits``
- # would prompt for non-Edit tools, hanging the headless agent.
- # ``dontAsk`` is the correct middle: no prompts AND strict
- # allowlist gating. Per-task override still honoured.
+ # (https://code.claude.com/docs/en/permission-modes): a call that
+ # would prompt is denied instead, unless ``--allowedTools``
+ # matches it; read-only Bash commands still run. The prior
+ # ``bypassPermissions`` default "skips the permission layer
+ # entirely" — meaning ``--allowedTools`` and
+ # ``--disallowedTools`` become documentation-only and claude's
+ # built-in Read / Edit / Bash / Glob / Grep / Write / Skill /
+ # WebSearch / WebFetch remain invocable even when not in the
+ # allowlist. ``acceptEdits`` would prompt for non-Edit tools,
+ # hanging the headless agent. ``dontAsk`` is the middle: no
+ # prompts, and a denial for anything not pre-approved (apart
+ # from read-only Bash). Per-task override still honoured.
perm = task.permission_mode or defaults.get(
"default_permission_mode",
self._defaults.get("default_permission_mode", "dontAsk"),
diff --git a/server/services/cli_agent/mcp_server.py b/server/services/cli_agent/mcp_server.py
index d177b667..bebbc873 100644
--- a/server/services/cli_agent/mcp_server.py
+++ b/server/services/cli_agent/mcp_server.py
@@ -1,16 +1,21 @@
"""OpenCompany MCP server (VSCode pattern, no custom IPC).
-Hosts a `FastMCP` ASGI sub-app at ``/mcp/ide`` that spawned CLI sessions
-auto-discover via the lockfile written by ``lockfile.py``. Each session
+Hosts a `FastMCP` ASGI sub-app at ``/mcp/ide``. Claude reaches it through
+the ``--mcp-config`` entry the provider puts on its argv (URL + bearer);
+the IDE lockfile written by ``lockfile.py`` is used only by the generic
+``AICliSession`` path. Each session
gets a per-batch bearer token; the middleware validates it and binds the
matching ``BatchContext`` into a contextvar so tool implementations can
scope to the calling session's workspace_dir / connected_skill_names /
allowed_credentials without explicit plumbing.
-Tools (5 in v1, mirroring Claude Code's progressive-disclosure pattern):
- - ``getWorkspaceFiles`` — glob/read inside the session's worktree
+Infrastructure tools (registered in :func:`_build_tools`, mirroring
+Claude Code's progressive-disclosure pattern):
+ - ``getWorkspaceFiles`` — glob/read inside the batch's workspace_dir
- ``listSkills`` — metadata for skills connected to the parent agent
- - ``getSkill`` — full skill markdown + scripts + references
+ - ``getSkill`` — load a connected skill (instructions + resource manifest)
+ - ``readSkillResource`` / ``searchSkillResource`` — page through or
+ search a loaded skill's declared resources
- ``getCredential`` — gated by per-batch allowlist
- ``broadcastLog`` — write to OpenCompany Terminal tab
@@ -65,9 +70,10 @@ class BatchContext:
allowed_credentials: Set[str] = field(default_factory=set)
# Connected ``input-tools`` nodes (entries from
# ``services.plugin.edge_walker.collect_agent_connections``). Each
- # dict: ``{node_id, node_type, label, parameters, ...}``. Drives the
- # ``listOpenCompanyTools`` / ``callOpenCompanyTool`` MCP tools so the
- # CLI agent sees the same tool surface the AI Agent does.
+ # dict: ``{node_id, node_type, label, parameters, ...}``. Each entry
+ # is exposed as its own ``mcp__opencompany__<name>`` tool (see
+ # ``workflow_tools``) so the CLI agent sees the same tool surface the
+ # AI Agent does.
connected_tools: List[Dict[str, Any]] = field(default_factory=list)
# Optional broadcaster for `broadcastLog`. Lazily resolved from the
# global container if None.
@@ -307,8 +313,8 @@ class _BearerAuthMiddleware(BaseHTTPMiddleware):
ua = request.headers.get("user-agent", "")
logger.warning(
"[CC-Agent MCP auth] %s %s -> 401 (no Bearer token; "
- "auth_header=%r ua=%r) — claude CLI either didn't read the "
- "lockfile or is hitting the wrong URL.",
+ "auth_header=%r ua=%r) — the CLI sent no bearer from its "
+ "--mcp-config entry, or is hitting the wrong URL.",
method,
path,
auth,
@@ -354,7 +360,7 @@ class _BearerAuthMiddleware(BaseHTTPMiddleware):
def _build_tools(mcp: Any) -> None: # FastMCP type
- """Register the 5 v1 tools on a `FastMCP` instance."""
+ """Register the infrastructure tools on a `FastMCP` instance."""
@mcp.tool(
name="getWorkspaceFiles",
diff --git a/server/services/cli_agent/service.py b/server/services/cli_agent/service.py
index c91e9ca1..a8379e0f 100644
--- a/server/services/cli_agent/service.py
+++ b/server/services/cli_agent/service.py
@@ -748,10 +748,10 @@ class AICliService:
mutation_id: Optional[str] = None,
) -> None:
"""Append each successful run's user prompt + assistant response
- to ``simpleMemory.memory_content`` (markdown). Mirrors aiAgent /
- chatAgent / rlm_agent's persistence pattern exactly
- — same helpers (``append_to_memory_markdown``,
- ``trim_markdown_window``), same field. One DB write.
+ to ``simpleMemory.memory_content`` (markdown) and store the most
+ recent ``session_id`` as ``last_session_id``, which the next run
+ resumes with ``--resume``. Both go through one
+ ``append_memory_turns_atomic`` call (one DB write).
"""
successful = [r for r in results if r.success]
logger.info(
diff --git a/server/services/cli_agent/session.py b/server/services/cli_agent/session.py
index 71880c89..fe6d49ad 100644
--- a/server/services/cli_agent/session.py
+++ b/server/services/cli_agent/session.py
@@ -3,8 +3,10 @@
**Not used for Claude.** ``AICliService.run_batch`` routes every Claude
task through ``ClaudeSessionPool`` (plain pipes + stream-json): a PTY
stdin makes the CLI reject ``--input-format stream-json``, and this
-class never wrote the prompt to the child (GitHub #133 / #134). It
-remains the generic PTY + JSONL path for other providers.
+class never wrote the prompt to the child (GitHub #133 / #134). It is
+still what ``run_batch`` uses for a provider with no registered session
+pool (Codex), but ``_do_start`` raises for every provider except
+``claude``, so those runs fail (reported as ``worktree_setup_failed``).
Each session is bound to:
- one provider (Claude or Codex)
@@ -134,7 +136,7 @@ class AICliSession(BaseProcessSupervisor):
# path (https://code.claude.com/docs/en/skills#where-skills-live).
self._connected_skill_names: List[str] = list(connected_skill_names or [])
# Memory-bound runs use ``cwd=repo_root`` so claude's project_key
- # (derived from cwd via `[^a-zA-Z0-9.-] -> -`) stays stable
+ # (derived from cwd via ``_PROJECT_KEY_RE``) stays stable
# across spawns. With a stable project_key, ``--resume <UUID>``
# finds the prior session JSONL claude wrote on its previous
# turn under ``<CLAUDE_CONFIG_DIR>/projects/<key>/<UUID>.jsonl``.
@@ -326,8 +328,8 @@ class AICliSession(BaseProcessSupervisor):
)
# Where claude will write its session JSONL. The project_key is
- # derived from cwd by the algorithm verified in the memory
- # bridge research (every non-`[a-zA-Z0-9.-]` char → `-`).
+ # derived from cwd by ``_PROJECT_KEY_RE`` (every char outside
+ # ``[a-zA-Z0-9-]`` becomes ``-``, dots included).
project_dir = self._project_dir()
try:
project_dir.mkdir(parents=True, exist_ok=True)
diff --git a/server/tests/services/cli_agent/test_providers.py b/server/tests/services/cli_agent/test_providers.py
index 348c5fe8..8e933a40 100644
--- a/server/tests/services/cli_agent/test_providers.py
+++ b/server/tests/services/cli_agent/test_providers.py
@@ -89,7 +89,7 @@ class TestClaudeArgv:
in_idx = argv.index("--input-format")
assert argv[in_idx + 1] == "stream-json"
assert "--verbose" in argv # required for stream-json detail
- assert "--ide" in argv # lockfile auto-discovery
+ assert "--ide" in argv # matches the VSCode extension argv; no lockfile is written
# The prompt is NEVER a positional in stream-json mode — it goes
# over ``proc.stdin``. ``--`` separator is gone.
assert "--" not in argv