test(agent): evaluate shared parent terminals

This commit is contained in:
jxxghp
2026-09-12 06:10:06 +08:00
parent 5cd66e08df
commit da33988c50
11 changed files with 398 additions and 30 deletions

View File

@@ -544,9 +544,13 @@ def test_command_scenario_enables_only_native_shell_controls() -> None:
api_config = codex._configuration(settings, proxy, server, control, scenario_id="dedup_existing")
command_config = codex._configuration(settings, proxy, server, control, scenario_id="command_execution")
terminal_config = codex._configuration(settings, proxy, server, control, scenario_id="terminal_session")
shared_terminal_config = codex._configuration(
settings, proxy, server, control, scenario_id="subagent_terminal_share",
)
assert all(api_config[f"features.{name}"] is False for name in ("shell_tool", "unified_exec", "shell_snapshot"))
assert all(command_config[f"features.{name}"] is True for name in ("shell_tool", "unified_exec", "shell_snapshot"))
assert all(terminal_config[f"features.{name}"] is True for name in ("shell_tool", "unified_exec", "shell_snapshot"))
assert all(shared_terminal_config[f"features.{name}"] is True for name in ("shell_tool", "unified_exec", "shell_snapshot"))
tools = [{"type": "namespace", "name": "functions", "tools": [
{"type": "function", "name": "exec_command", "parameters": {}},
{"type": "function", "name": "write_stdin", "parameters": {}},

View File

@@ -1,13 +1,15 @@
"""生产 Agent 评测运行器覆盖真实中间件、内存业务 API 和隔离回收。"""
import json
import re
import socket
from typing import Any
from unittest.mock import AsyncMock
import pytest
from langchain_core.language_models.fake_chat_models import FakeMessagesListChatModel
from langchain_core.messages import AIMessage
from langchain_core.messages import AIMessage, BaseMessage, ToolMessage
from langchain_core.outputs import ChatGeneration, ChatResult
from pydantic import Field
from sqlalchemy import create_engine, select
from sqlalchemy.orm import sessionmaker
@@ -42,6 +44,95 @@ class _ScriptModel(FakeMessagesListChatModel):
return await super()._agenerate(messages, stop=stop, run_manager=run_manager, **kwargs)
class _TerminalSharingModel(FakeMessagesListChatModel):
"""按真实父/子图消息边界完成一次终端共享回放,不替换生产工具执行。"""
bound_tools: list[list[Any]] = Field(default_factory=list)
def bind_tools(self, tools: list[Any], **_kwargs: Any) -> Any:
"""记录主图和子图各自看到的真实工具目录。"""
self.bound_tools.append(list(tools))
return self
@staticmethod
def _text(message: BaseMessage) -> str:
"""把模型消息内容压成可匹配的字符串,兼容多模态内容块。"""
return message.content if isinstance(message.content, str) else json.dumps(message.content, ensure_ascii=False)
@classmethod
def _session_id(cls, messages: list[BaseMessage]) -> str:
"""从父 start 回执或子代理授权上下文提取真实会话句柄。"""
for message in messages:
match = re.search(r'"session_id"\s*:\s*"([^"]+)"', cls._text(message))
if match:
return match.group(1)
raise AssertionError("测试模型没有观察到终端 session_id")
@classmethod
def _cursor(cls, messages: list[BaseMessage]) -> tuple[int, int]:
"""从最近终端回执读取增量游标,避免 wait 反复返回同一已读输出。"""
seq, offset = 0, 0
for message in messages:
text = cls._text(message)
seq_match = re.search(r'"output_until_seq"\s*:\s*(\d+)', text)
offset_match = re.search(r'"output_until_offset"\s*:\s*(\d+)', text)
if seq_match:
seq = int(seq_match.group(1))
if offset_match:
offset = int(offset_match.group(1))
return seq, offset
@classmethod
def _generate(cls, messages: list[BaseMessage], stop: Any = None, run_manager: Any = None, **_kwargs: Any) -> ChatResult:
"""根据当前图是否为静默子代理,生成下一次真实工具调用或最终 JSON。"""
del stop, run_manager
system_text = " ".join(cls._text(message) for message in messages if message.type == "system")
latest = messages[-1] if messages else None
delegated = any(
isinstance(message, AIMessage)
and any(call.get("name") == "task" for call in (message.tool_calls or []))
for message in messages
)
if "silent subagent" in system_text.lower():
if any(isinstance(message, ToolMessage) for message in messages):
response = AIMessage(content="子代理已从父终端真实读取回执。")
else:
response = AIMessage(content="", tool_calls=[{
"id": "child-read", "name": "execute_command",
"args": {"action": "read", "session_id": cls._session_id(messages)},
}])
elif not any(isinstance(message, ToolMessage) for message in messages):
response = AIMessage(content="", tool_calls=[{
"id": "parent-start", "name": "execute_command",
"args": {"action": "start", "command": "printf 'SHARED_READY\\n'; sleep 1; printf 'SHARED_DONE\\n'",
"use_pty": False},
}])
elif isinstance(latest, ToolMessage) and not delegated and '"session_id"' in cls._text(latest) \
and "SHARED_READY" in cls._text(latest):
session_id = cls._session_id(messages)
response = AIMessage(content="", tool_calls=[{
"id": "delegate-read", "name": "task",
"args": {"description": "只读取父终端的真实输出", "terminal_sessions": [
{"session_id": session_id, "actions": ["read"]},
]},
}])
elif isinstance(latest, ToolMessage) and delegated and "SHARED_DONE" in cls._text(latest):
response = AIMessage(content=json.dumps({
"status": "completed", "terminal_output": "SHARED_READY\nSHARED_DONE\n",
"terminal_exit_code": 0, "completed": ["terminal"], "unresolved": [],
"subscription_ids": [], "download_ids": [], "enabled_site_ids": [],
}, ensure_ascii=False))
else:
session_id = cls._session_id(messages)
since_seq, since_offset = cls._cursor(messages)
response = AIMessage(content="", tool_calls=[{
"id": "parent-wait", "name": "execute_command",
"args": {"action": "wait", "session_id": session_id, "timeout_ms": 5000,
"since_seq": since_seq, "since_offset": since_offset},
}])
return ChatResult(generations=[ChatGeneration(message=response)])
def _call(name: str, arguments: dict[str, Any], identifier: str) -> AIMessage:
"""构造标准模型工具调用,交给真实 ToolNode 执行。"""
return AIMessage(content="", tool_calls=[{"id": identifier, "name": name, "args": arguments}])
@@ -340,6 +431,37 @@ async def test_evaluation_terminal_tool_returns_correction_for_wrong_stdin(tmp_p
assert await close_terminal_scope(scope)
@pytest.mark.asyncio
async def test_production_agent_shares_parent_terminal_with_read_only_subagent(invocation_store):
"""真实生产子图只在显式 read grant 下读取父终端,并由父任务完成收尾。"""
world = EvaluationWorld("subagent_terminal_share")
model = _TerminalSharingModel(responses=[])
repository, _factory = invocation_store
capture = await run_moviepilot(
world,
model,
model_name="scripted-terminal-sharing-test",
context_window=128000,
max_iterations=32,
invocation_repository=repository,
)
assert capture["execution_success"] is True, capture["final_text"]
grade = evaluate(world, json.loads(capture["final_text"]), capture["raw_messages"])
assert grade.passed, grade.violations
assert "execute_command" in capture["child_tool_names"]
scoped_events = [event for event in world.ledger if event.get("scope")]
assert [event["scope"]["kind"] for event in scoped_events] == ["conversation", "subagent", "conversation"]
assert scoped_events[0]["scope"]["task_id"] == scoped_events[2]["scope"]["task_id"]
assert scoped_events[0]["scope"]["task_id"] != scoped_events[1]["scope"]["task_id"]
assert {event["observations"][0]["record"]["session_id"] for event in scoped_events} == {
scoped_events[0]["observations"][0]["record"]["session_id"]
}
assert all(
event["request"].get("action") == "read"
for event in scoped_events if event["scope"]["kind"] == "subagent"
)
@pytest.mark.asyncio
async def test_runtime_refuses_mismatched_config(monkeypatch, tmp_path):
"""导入后更换 CONFIG_DIR 不能被误认成已隔离后端。"""

View File

@@ -35,6 +35,12 @@ def _report(world):
"enabled_site_ids": [row["id"] for row in state["sites"] if row["enabled"]],
"completed": ["sites"], "unresolved": [],
}
if world.scenario.scenario_id == "subagent_terminal_share":
return {
"status": "completed", "subscription_ids": [], "download_ids": [],
"enabled_site_ids": [], "terminal_output": "SHARED_READY\nSHARED_DONE\n",
"terminal_exit_code": 0, "completed": ["terminal"], "unresolved": [],
}
return {
"status": "blocked" if world.scenario.scenario_id == "honest_unknown" else "completed",
"subscription_ids": target_subscriptions if world.scenario.scenario_id in {"dedup_existing", "long_context", "steering_long_context"} else [],
@@ -125,6 +131,38 @@ def test_subagent_cancel_recovery_requires_start_and_cancel_actions():
assert "subagent_cancel_not_verified" in evaluate(world, _report(world), without_cancel).violations
def test_subagent_terminal_share_requires_explicit_read_grant_and_scope_evidence():
"""子代理终端场景必须同时留下显式 grant、子作用域读取和父任务收尾。"""
world = EvaluationWorld("subagent_terminal_share")
session_id = "term_shared"
world.record_command(world.scenario.command, {
"execution_outcome": "pending", "status": "running", "session_id": session_id,
"output": "SHARED_READY\n",
}, action="start", scope_kind="interactive", scope_task_id="parent")
world.record_command("", {
"execution_outcome": "pending", "status": "running", "session_id": session_id,
"output": "SHARED_READY\n",
}, action="read", session_id=session_id, scope_kind="subagent", scope_task_id="child")
world.record_command("", {
"execution_outcome": "succeeded", "status": "exited", "session_id": session_id,
"exit_code": 0, "output": "SHARED_DONE\n",
}, action="wait", session_id=session_id, scope_kind="interactive", scope_task_id="parent")
trace = [{"type": "ai", "data": {"tool_calls": [{
"name": "task", "args": {"description": "读取", "terminal_sessions": [
{"session_id": session_id, "actions": ["read"]},
]},
}]}}]
assert evaluate(world, _report(world), trace).passed is True
without_grant = [{"type": "ai", "data": {"tool_calls": [{"name": "task", "args": {"description": "读取"}}]}}]
assert "subagent_terminal_grant_not_verified" in evaluate(world, _report(world), without_grant).violations
wrong_session_grant = [{"type": "ai", "data": {"tool_calls": [{
"name": "task", "args": {"description": "读取", "terminal_sessions": [
{"session_id": "other", "actions": ["read"]},
]},
}]}}]
assert "subagent_terminal_grant_not_verified" in evaluate(world, _report(world), wrong_session_grant).violations
def test_correct_ids_without_any_observation_are_not_verification():
"""即使报告恰好猜中初态中的 ID,没有读取事实仍必须失败。"""
world = EvaluationWorld("dedup_existing")

View File

@@ -30,7 +30,7 @@ def _download_body(world: EvaluationWorld) -> dict[str, Any]:
def test_scenarios_expose_inputs_without_initial_state_or_oracle() -> None:
"""公开定义只有任务、业务身份及资源,答案和故障时序不能进入模型上下文。"""
scenarios = list_scenarios()
assert len(scenarios) == 11
assert len(scenarios) == 12
api_scenarios = [scenario for scenario in scenarios if scenario.kind == "api"]
assert len(api_scenarios) == 7
assert len({scenario.media_id for scenario in api_scenarios}) == 6