Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 82 additions & 17 deletions omnigent/inner/acp_executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -392,6 +392,9 @@ def __init__(
# :meth:`close`). ``_omnigent_tools`` is captured each turn for the relay.
self._mcp = OmnigentAcpMcp(label=config.name)
self._omnigent_tools: list[ToolSpec] = []
# Tool names the agent can use to reach the Omnigent MCP bridge, snapshotted
# from what session/new advertised. Empty means nothing is a bridge call.
self._bridge_tool_aliases: frozenset[str] = frozenset()

# ------------------------------------------------------------------
# Low-level ACP transport
Expand Down Expand Up @@ -693,17 +696,10 @@ async def _ensure_session(self) -> str:

params: _AcpJsonObject = {
"cwd": self._cwd,
# ACP requires this field even when no per-session MCP servers are
# configured. Keep it empty when Omnigent MCP is disabled.
"mcpServers": [],
# ACP requires this field even with no per-session MCP servers; the
# helper returns [] when Omnigent MCP is disabled.
"mcpServers": self._session_mcp_servers(),
}
if self._config.omnigent_mcp:
params["mcpServers"] = self._mcp.session_new_servers(
tools=self._omnigent_tools,
tool_executor=getattr(self, "_tool_executor", None),
loop=asyncio.get_event_loop(),
enabled=True,
)
client_id: str | None = None
if self._config.session_id_mode == "client":
client_id = secrets.token_urlsafe(16)
Expand All @@ -726,6 +722,39 @@ async def _ensure_session(self) -> str:
self._session_id = session_id
return self._session_id

def _session_mcp_servers(self) -> list[_AcpJsonObject]:
"""Build ``session/new.mcpServers`` and snapshot the bridge aliases.

Relay creation and tool-call classification happen here together so they
cannot drift apart. No entries means no aliases, so with Omnigent MCP
disabled every call classifies as agent-native.
"""
mcp_servers: list[_AcpJsonObject] = []
if self._config.omnigent_mcp:
mcp_servers = self._mcp.session_new_servers(
tools=self._omnigent_tools,
tool_executor=getattr(self, "_tool_executor", None),
loop=asyncio.get_event_loop(),
enabled=True,
)
servers = {str(s.get("name", "")) for s in mcp_servers if isinstance(s, dict)}
servers.discard("")
tools = {
name
for name in (spec.get("name") for spec in (self._omnigent_tools or []))
if isinstance(name, str) and name
}
# Agents name a bridged tool one of several ways; accept every shape we have
# seen, plus the bare name for agents that report it unprefixed.
aliases = set(tools) if servers else set()
for server in servers:
for tool in tools:
aliases.update(
(f"mcp_{server}_{tool}", f"mcp__{server}__{tool}", f"{server}__{tool}")
)
self._bridge_tool_aliases = frozenset(aliases)
return mcp_servers

# ------------------------------------------------------------------
# Server-initiated requests (agent → client)
# ------------------------------------------------------------------
Expand Down Expand Up @@ -1178,6 +1207,39 @@ def _usage_from_result(result: _AcpJsonObject) -> dict[str, int] | None:
out[omni_key] = value
return out or None

def _is_bridge_tool_call(self, name: str, update: _AcpJsonObject) -> bool:
"""True when this tool call reaches Omnigent through the MCP bridge.

Candidates are the reported name plus the machine names some agents carry
beside a humanized title. An unrecognized shape reads as agent-native,
which may duplicate a card but cannot corrupt dispatch correlation.
"""
if not self._bridge_tool_aliases:
return False
raw = update.get("rawInput")
raw_tool = str(raw.get("tool", "")) if isinstance(raw, dict) else ""
# Goose reports the machine name under ``_meta.goose.toolCall.toolName``;
# older builds used the flatter ``_meta.goose.toolName``. Read both.
meta = update.get("_meta")
goose = meta.get("goose") if isinstance(meta, dict) else None
meta_tool = ""
if isinstance(goose, dict):
inner = goose.get("toolCall")
meta_tool = str(
(inner.get("toolName", "") if isinstance(inner, dict) else "")
or goose.get("toolName", "")
)
candidates = {c for c in (name, raw_tool, meta_tool) if c}
return not self._bridge_tool_aliases.isdisjoint(candidates)

def _reset_session_state(self) -> None:
"""Forget state that is only valid for the current ACP session."""
self._session_id = None
self._system_prompt_sent = False
self._tool_names.clear()
self._tool_inputs.clear()
self._bridge_tool_aliases = frozenset()

def _handle_session_update(self, update: _AcpJsonObject) -> list[ExecutorEvent]:
"""Translate one ``session/update`` payload into ExecutorEvents.

Expand Down Expand Up @@ -1236,9 +1298,13 @@ def _handle_session_update(self, update: _AcpJsonObject) -> list[ExecutorEvent]:
if isinstance(call_id, str) and call_id:
self._tool_names[call_id] = str(name)
self._tool_inputs[call_id] = args
events.append(
ToolCallRequest(name=str(name), args=args, metadata={"call_id": call_id})
)
metadata: _AcpJsonObject = {"call_id": call_id}
# An agent-native tool ran inside the agent's own loop and never
# round-trips Omnigent dispatch. Leaving its id in the correlation
# queue would mis-pair the next bridge completion.
if not self._is_bridge_tool_call(str(name), update):
metadata["internally_executed"] = True
events.append(ToolCallRequest(name=str(name), args=args, metadata=metadata))
elif update_type == _UPDATE_TOOL_CALL_UPDATE:
call_id = update.get("toolCallId")
status = update.get("status")
Expand Down Expand Up @@ -1490,15 +1556,13 @@ async def run_turn(
response = fut.result()
except Exception as exc:
logger.exception("ACP process response retrieval failed")
self._session_id = None
self._system_prompt_sent = False
self._reset_session_state()
yield ExecutorError(message=f"ACP process error: {exc}", retryable=True)
return
if "error" in response:
error_msg = response["error"].get("message", "Unknown ACP error")
if "Session not found" in error_msg:
self._session_id = None
self._system_prompt_sent = False
self._reset_session_state()
yield ExecutorError(message=error_msg, retryable=True)
return
result = response.get("result", {}) if isinstance(response, dict) else {}
Expand Down Expand Up @@ -1557,6 +1621,7 @@ async def close_session(self, session_key: str) -> None:

async def close(self) -> None:
"""Terminate the agent subprocess and clean up."""
self._reset_session_state()
# Tear down the Omnigent MCP relay HTTP server + its bridge dir first.
with contextlib.suppress(Exception):
self._mcp.close()
Expand Down
158 changes: 157 additions & 1 deletion tests/inner/test_acp_executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,8 @@ def test_tool_call_and_update_emit_cards() -> None:
assert len(started) == 1
req = started[0]
assert isinstance(req, ToolCallRequest)
assert req.name == "shell" and req.metadata == {"call_id": "c1"}
assert req.name == "shell"
assert req.metadata == {"call_id": "c1", "internally_executed": True}
assert ex._tool_names["c1"] == "shell"

done = ex._handle_session_update(
Expand Down Expand Up @@ -474,6 +475,161 @@ def test_claimed_completion_frame_emits_no_spurious_parent_card() -> None:
assert not any(isinstance(e, ToolCallComplete) for e in events)


# ---------------------------------------------------------------------------
# Agent-native vs MCP-bridge classification
# ---------------------------------------------------------------------------


@pytest.mark.parametrize(
("update", "is_bridge"),
[
({"title": "sys_session_get_info", "rawInput": {}}, True),
(
{"title": "Session info", "rawInput": {"tool": "mcp_omnigent_sys_session_get_info"}},
True,
),
(
{"title": "Session info", "rawInput": {"tool": "mcp__omnigent__sys_session_get_info"}},
True,
),
(
{
"title": "omnigent: sys session get info",
"rawInput": {"session_id": ""},
"_meta": {"goose": {"toolCall": {"toolName": "omnigent__sys_session_get_info"}}},
},
True,
),
({"title": "GitHub comments", "rawInput": {"tool": "github__list_comments"}}, False),
({"title": "shell: git status", "rawInput": {"command": "git status"}}, False),
],
)
def test_only_advertised_bridge_aliases_enter_dispatch_correlation(
update: dict[str, object], is_bridge: bool
) -> None:
"""A call the bridge never advertised must not claim a dispatch slot."""
ex = AcpExecutor(AcpAgentConfig(command="x"))
ex._bridge_tool_aliases = frozenset(
{
"sys_session_get_info",
"mcp_omnigent_sys_session_get_info",
"mcp__omnigent__sys_session_get_info",
"omnigent__sys_session_get_info",
}
)

event = ex._handle_session_update(
{"sessionUpdate": "tool_call", "toolCallId": "c1", **update}
)[0]

assert isinstance(event, ToolCallRequest)
assert ("internally_executed" not in event.metadata) is is_bridge


def test_no_advertised_bridge_classifies_every_call_as_native() -> None:
"""Tools alone are not enough: without a served relay there is no bridge."""
ex = AcpExecutor(AcpAgentConfig(command="x"))
ex._omnigent_tools = [{"name": "sys_session_get_info"}]

event = ex._handle_session_update(
{"sessionUpdate": "tool_call", "toolCallId": "c1", "title": "sys_session_get_info"}
)[0]

assert isinstance(event, ToolCallRequest)
assert event.metadata == {"call_id": "c1", "internally_executed": True}


@pytest.mark.asyncio
async def test_bridge_aliases_hold_until_the_session_resets(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""The agent keeps the tools sent at session/new, so classify against those."""
ex = AcpExecutor(AcpAgentConfig(command="x"))
ex._rpc = AsyncMock(return_value={"result": {"sessionId": "s1"}}) # type: ignore[method-assign]
monkeypatch.setattr(ex._mcp, "session_new_servers", lambda **_: [{"name": "omnigent"}])

ex._omnigent_tools = [{"name": "sys_session_get_info"}]
await ex._ensure_session()
ex._omnigent_tools = [{"name": "web_search"}]

assert "sys_session_get_info" in ex._bridge_tool_aliases
assert "web_search" not in ex._bridge_tool_aliases

ex._reset_session_state()
ex._rpc = AsyncMock(return_value={"result": {"sessionId": "s2"}}) # type: ignore[method-assign]
await ex._ensure_session()

assert "web_search" in ex._bridge_tool_aliases
assert "sys_session_get_info" not in ex._bridge_tool_aliases


def test_session_reset_drops_in_flight_tool_state() -> None:
ex = AcpExecutor(AcpAgentConfig(command="x"))
ex._handle_session_update(
{
"sessionUpdate": "tool_call",
"toolCallId": "pending",
"title": "shell",
"rawInput": {"command": "sleep 10"},
}
)

ex._reset_session_state()

assert ex._tool_names == {}
assert ex._tool_inputs == {}
assert ex._bridge_tool_aliases == frozenset()


class _RecordingCtx:
"""Minimal ``TurnContext`` stand-in: the surface the adapter touches.

A typed stub rather than MagicMock, so a call to a method that does not
exist fails loud instead of silently returning another mock.
"""

def __init__(self, response_id: str = "resp_acp") -> None:
self.response_id = response_id
self.emitted: list[object] = []

def emit(self, event: object) -> None:
self.emitted.append(event)


@pytest.mark.asyncio
async def test_native_call_before_a_bridge_call_keeps_each_call_id(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""The reported defect: a native call ahead of a bridge call stole its id."""
import omnigent.runtime.harnesses._executor_adapter as adapter_module
from omnigent.runtime.harnesses._executor_adapter import ExecutorAdapter

ex = AcpExecutor(AcpAgentConfig(command="x"))
ex._bridge_tool_aliases = frozenset({"sys_session_get_info"})
adapter = ExecutorAdapter(executor_factory=lambda: ex)
ctx = _RecordingCtx()
adapter._current_ctx = ctx # type: ignore[assignment]
adapter._current_agent = "test-model"

for call_id, title in (("native-1", "terminal: date"), ("bridge-1", "sys_session_get_info")):
for event in ex._handle_session_update(
{"sessionUpdate": "tool_call", "toolCallId": call_id, "title": title, "rawInput": {}}
):
adapter._translate_event(event, ctx) # type: ignore[arg-type]

dispatched: dict[str, str] = {}

async def fake_bridge(*_args: object, call_id: str, **_kw: object) -> dict[str, object]:
dispatched["call_id"] = call_id
return {"ok": True}

monkeypatch.setattr(adapter_module, "_bridge_one_dispatch", fake_bridge)
await adapter._stable_tool_executor("sys_session_get_info", {})

assert dispatched["call_id"] == "bridge-1"
assert list(adapter._pending_mcp_call_ids) == []


# ---------------------------------------------------------------------------
# Permission decision (policy + elicitation gates)
# ---------------------------------------------------------------------------
Expand Down
Loading