Skip to content
35 changes: 26 additions & 9 deletions libs/acp/deepagents_acp/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

import json
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, TypeAlias, TypeGuard
from typing import TYPE_CHECKING, Any, TypeAlias, TypeGuard, cast
from uuid import uuid4

from acp import (
Expand Down Expand Up @@ -84,6 +84,15 @@
McpServer: TypeAlias = HttpMcpServer | SseMcpServer | McpServerStdio
"""Type alias for ACP MCP server configuration variants."""

PromptBlock: TypeAlias = (
TextContentBlock
| ImageContentBlock
| AudioContentBlock
| ResourceContentBlock
| EmbeddedResourceContentBlock
)
"""Content blocks accepted by an ACP prompt."""

_MCP_SERVER_TYPES = (HttpMcpServer, SseMcpServer, McpServerStdio)
"""Runtime MCP server classes used to detect legacy positional `new_session` calls."""

Expand Down Expand Up @@ -143,6 +152,9 @@ def __init__(
*,
modes: SessionModeState | None = None,
models: list[dict[str, str]] | None = None,
context_factory: Callable[[str, list[PromptBlock]], object] | None = None,
message_factory: Callable[[str, list[PromptBlock], Sequence[str | dict[Any, Any]]], object]
| None = None,
) -> None:
"""Initialize the ACP agent server with the given agent factory or compiled graph.

Expand All @@ -151,10 +163,14 @@ def __init__(
modes: Optional mode configuration (deprecated, use config_options instead)
models: Optional list of available models with 'value', 'name', and optionally
'description'
context_factory: Optional per-prompt LangGraph context builder.
message_factory: Optional LangGraph user-message builder.
"""
super().__init__()
self._cwd = ""
self._agent_factory = agent
self._context_factory = context_factory
self._message_factory = message_factory
self._agent: CompiledStateGraph | None = None

if isinstance(agent, CompiledStateGraph):
Expand Down Expand Up @@ -634,13 +650,7 @@ def _reset_agent(self, session_id: str) -> None:

async def prompt( # noqa: C901, PLR0912, PLR0915 # Complex streaming protocol handler with many branches
self,
prompt: list[
TextContentBlock
| ImageContentBlock
| AudioContentBlock
| ResourceContentBlock
| EmbeddedResourceContentBlock
],
prompt: list[PromptBlock],
session_id: str,
message_id: str | None = None, # noqa: ARG002 # ACP protocol interface parameter
**kwargs: Any, # noqa: ARG002 # ACP protocol interface parameter
Expand Down Expand Up @@ -678,6 +688,12 @@ async def prompt( # noqa: C901, PLR0912, PLR0915 # Complex streaming protocol
content_blocks.extend(convert_embedded_resource_block_to_content_blocks(block))
# Stream the deep agent response with multimodal content
config: RunnableConfig = {"configurable": {"thread_id": session_id}}
context = self._context_factory(session_id, prompt) if self._context_factory else None
user_message = (
self._message_factory(session_id, prompt, content_blocks)
if self._message_factory
else {"role": "user", "content": content_blocks}
)

# Track active tool calls and accumulate chunks by index
active_tool_calls = {}
Expand All @@ -696,8 +712,9 @@ async def prompt( # noqa: C901, PLR0912, PLR0915 # Complex streaming protocol
async for stream_chunk in agent.astream(
Command(resume={"decisions": user_decisions})
if user_decisions
else {"messages": [{"role": "user", "content": content_blocks}]},
else {"messages": [user_message]},
config=config,
context=cast("Any", context),
stream_mode=["messages", "updates"],
subgraphs=True,
):
Expand Down
38 changes: 38 additions & 0 deletions libs/acp/tests/test_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,44 @@ async def test_acp_agent_prompt_streams_text() -> None:
assert texts == ["Hello!"]


async def test_acp_agent_forwards_custom_context_and_message() -> None:
class Graph:
checkpointer = MemorySaver()

def __init__(self) -> None:
self.calls: list[dict[str, Any]] = []

async def astream(self, value: Any, **kwargs: Any):
self.calls.append({"value": value, **kwargs})
return
yield

async def aget_state(self, config: Any) -> Any:
return type("State", (), {"next": (), "interrupts": []})()

graph = Graph()
context = object()
message = object()
agent = AgentServerACP(
agent=create_deep_agent(
model=GenericFakeChatModel(
messages=iter([AIMessage(content="ok")]), stream_delimiter=None
),
checkpointer=MemorySaver(),
),
context_factory=lambda _session_id, _prompt: context,
message_factory=lambda _session_id, _prompt, _content: message,
)
agent._agent = graph # type: ignore[assignment]
agent.on_connect(FakeACPClient()) # type: ignore[arg-type]
session = await agent.new_session(cwd="/tmp", mcp_servers=[])

await agent.prompt([TextContentBlock(type="text", text="Hi")], session_id=session.session_id)

assert graph.calls[0]["value"] == {"messages": [message]}
assert graph.calls[0]["context"] is context


async def test_acp_agent_cancel_stops_prompt() -> None:
model = GenericFakeChatModel(messages=iter([AIMessage(content="Should not appear")]))
graph = create_deep_agent(model=model, checkpointer=MemorySaver())
Expand Down
13 changes: 8 additions & 5 deletions libs/code/deepagents_code/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
from langgraph.prebuilt.tool_node import ToolCallRequest
from langgraph.pregel import Pregel
from langgraph.runtime import Runtime
from langgraph.store.base import BaseStore
from langgraph.types import Command

from deepagents_code.mcp_tools import MCPServerInfo
Expand Down Expand Up @@ -2203,6 +2204,7 @@ def create_cli_agent(
auto_classifier_model: str | BaseChatModel | None = None,
recursion_limit: int | None = None,
checkpointer: BaseCheckpointSaver | None = None,
store: BaseStore | None = None,
mcp_server_info: list[MCPServerInfo] | None = None,
cwd: str | Path | None = None,
project_context: ProjectContext | None = None,
Expand Down Expand Up @@ -2254,8 +2256,8 @@ def create_cli_agent(

If `False`, tools pause for user confirmation via the approval menu.
See `_add_interrupt_on` for the full list of gated tools.
auto_mode_enabled: Install classifier-backed Auto for the local Textual
runtime. Callers must leave this disabled for headless, remote, and
auto_mode_enabled: Install classifier-backed Auto for local TUI or ACP
runtimes. Callers must leave this disabled for headless and
sandbox-backed graphs.
interrupt_shell_only: If `True`, all HITL interrupts are disabled;
shell commands are validated inline by `ShellAllowListMiddleware`
Expand Down Expand Up @@ -2342,6 +2344,7 @@ def create_cli_agent(
in `config.toml`, then the default via `resolve_recursion_limit`.
checkpointer: Optional checkpointer for session persistence.
When `None`, the graph is compiled without a checkpointer.
store: Optional LangGraph Store for runtime approval state.
mcp_server_info: MCP server metadata to surface in the system prompt.
cwd: Override the working directory for the agent's filesystem backend
and system prompt.
Expand Down Expand Up @@ -2372,10 +2375,9 @@ def create_cli_agent(
"""
tools = tools or []
mcp_tools = tuple(mcp_tools or ())
if auto_mode_enabled and (not interactive or sandbox is not None):
if auto_mode_enabled and sandbox is not None:
logger.warning(
"Classifier-backed Auto is unavailable outside the local interactive "
"runtime; using Manual HITL"
"Classifier-backed Auto is unavailable with a sandbox; using Manual HITL"
)
auto_mode_enabled = False
effective_cwd = (
Expand Down Expand Up @@ -3071,6 +3073,7 @@ def _subagent_cli_middleware(
interrupt_on=interrupt_on,
context_schema=CLIContextSchema,
checkpointer=checkpointer,
store=store,
subagents=all_subagents or None,
name=_sanitize_agent_message_name(assistant_id),
).with_config({**config, "recursion_limit": effective_recursion_limit})
Expand Down
4 changes: 2 additions & 2 deletions libs/code/deepagents_code/auto_mode.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"""Classifier-backed approval policy for the local interactive TUI."""
"""Classifier-backed approval policy for local TUI and ACP runtimes."""

from __future__ import annotations

Expand Down Expand Up @@ -1815,7 +1815,7 @@ def __init__(
trusted_ask_user_tool: BaseTool | None = None,
trusted_compaction_tool: BaseTool | None = None,
) -> None:
"""Initialize the local interactive Auto policy.
"""Initialize the local Auto policy.

Args:
interrupt_on: Shared Manual interrupt map.
Expand Down
Loading