ReMe/reme/components/agent_wrapper/as_agent_wrapper.py
jinliyl 54fa3381d7
Some checks failed
CI and Release / Docker / Build and test / amd64 (push) Has been cancelled
CI and Release / Docker / Build and test / arm64 (push) Has been cancelled
Security / CodeQL / Analyze python (push) Has been cancelled
CI / Python quality / Pre-commit (push) Has been cancelled
CI / Python tests / Unit Tests - py3.12 (push) Has been cancelled
CI / Python tests / Unit Tests - py3.13 (push) Has been cancelled
CI / Python tests / Unit Tests - py3.14 (push) Has been cancelled
CI / Python packages / Build and verify distributions (push) Has been cancelled
CI / Python quality / GitHub Actions (push) Has been cancelled
CI / Python tests / Hermes embedded - ubuntu-latest (push) Has been cancelled
CI / Python tests / Hermes embedded - windows-latest (push) Has been cancelled
CI / Python tests / Unit Tests - py3.11 (push) Has been cancelled
CI / ReMe Studio / Studio checks (push) Has been cancelled
Deploy / Documentation / Build documentation (push) Has been cancelled
CI / Windows / CLI smoke - py3.11 (push) Has been cancelled
Security / CodeQL / Analyze javascript-typescript (push) Has been cancelled
CI and Release / Docker / Publish multi-platform tags (push) Has been cancelled
Deploy / Documentation / deploy (push) Has been cancelled
refactor(core): reorganize the ReMe runtime and shared helpers (#769)
* refactor(core): reorganize the ReMe runtime and shared helpers

* test(status): import the base component from its canonical module

* test: remove redundant unit checks

* refactor(core): use canonical runtime imports and shared CLI discovery

Restore evolve behavior to the base branch and update its imports. Use Application as the runtime entry point and encode SSE in the HTTP service.

* fix(cli): honor caller config when service replay is incomplete

Use partial startup overrides for port probes and resolve named configs before requesting the service process working directory.
2026-11-20 22:06:46 +08:00

633 lines
27 KiB
Python

"""AgentScope backend for the unified agent wrapper."""
import asyncio
import os
import signal
import subprocess
import sys
import time
from collections.abc import AsyncGenerator
from contextlib import aclosing, asynccontextmanager, suppress
from pathlib import Path
from typing import Any, Literal, TYPE_CHECKING
from uuid import uuid4
from agentscope.agent import Agent, ContextConfig, ReActConfig
from agentscope.agent._config import ModelConfig
from agentscope.event import (
DataBlockDeltaEvent,
DataBlockEndEvent,
DataBlockStartEvent,
ExceedMaxItersEvent,
ModelCallEndEvent,
ModelCallStartEvent,
ReplyEndEvent,
ReplyStartEvent,
ThinkingBlockDeltaEvent,
ThinkingBlockEndEvent,
ThinkingBlockStartEvent,
TextBlockDeltaEvent,
TextBlockEndEvent,
TextBlockStartEvent,
ToolCallDeltaEvent,
ToolCallEndEvent,
ToolCallStartEvent,
ToolResultDataDeltaEvent,
ToolResultEndEvent,
ToolResultStartEvent,
ToolResultTextDeltaEvent,
)
from agentscope.message import Msg, TextBlock, ToolResultState, UserMsg
from agentscope.permission import PermissionBehavior, PermissionContext, PermissionDecision, PermissionMode
from agentscope.state import AgentState
from agentscope.tool import (
Bash,
Edit,
ExecResult,
FunctionTool,
Glob,
Grep,
LocalBackend,
Read,
ToolBase,
ToolChunk,
Toolkit,
Write,
)
from .base_agent_wrapper import BaseAgentWrapper
from .as_session_store import AsSessionStore, record_chunk, record_end, record_inputs
from ..as_llm import BaseAsLLM
from ...core.registry import R
from ...enumeration import ChunkEnum
from ...schema import AgentReply, SessionMessage, SessionSnapshot, SessionStatus, StreamChunk, TokenUsage
from ...schema.stream_chunk import stream_status
from ...utils.async_utils import finish_cleanup
from .as_state_io import AsStateHandler
if TYPE_CHECKING:
from ..job.base_job import BaseJob
class WorkspaceBackend(LocalBackend):
"""Local backend pinned to the agent cwd and configured environment.
Some AgentScope builtin tools use ``backend.getcwd()`` for default search
paths or safety checks. Pinning it here keeps those operations aligned with
the cwd passed to Bash. Tools that require absolute file paths still keep
their own validation behavior. Subprocesses receive the startup environment
captured in ``ApplicationConfig.environment`` in addition to the parent
process environment.
"""
def __init__(self, cwd: str, environment: dict[str, str] | None = None) -> None:
super().__init__()
self._workspace_cwd = cwd
self._environment = {**os.environ, **(environment or {})}
async def getcwd(self) -> str:
"""Return the configured workspace directory."""
return self._workspace_cwd
async def exec_shell(
self,
command: list[str],
*,
cwd: str | None = None,
timeout: float | None = None,
) -> ExecResult:
"""Run a local subprocess with the configured agent environment."""
kwargs: dict[str, Any] = {
"env": self._environment,
"stderr": asyncio.subprocess.PIPE,
"stdout": asyncio.subprocess.PIPE,
}
if cwd is not None:
kwargs["cwd"] = cwd
if os.name == "nt":
kwargs["creationflags"] = getattr(subprocess, "CREATE_NO_WINDOW", 0x08000000)
else:
kwargs["start_new_session"] = True
try:
process = await asyncio.create_subprocess_exec(*command, **kwargs)
except (FileNotFoundError, NotADirectoryError, OSError) as exc:
return ExecResult(exit_code=127, stdout=b"", stderr=str(exc).encode("utf-8"))
async def stop():
with suppress(ProcessLookupError):
if os.name == "nt":
process.kill()
else:
os.killpg(process.pid, signal.SIGKILL)
await process.communicate()
try:
stdout, stderr = await asyncio.wait_for(process.communicate(), timeout=timeout)
except (asyncio.TimeoutError, asyncio.CancelledError) as exc:
await finish_cleanup(stop())
if isinstance(exc, asyncio.CancelledError):
raise
return ExecResult(exit_code=-1, stdout=b"", stderr=b"timed out")
return ExecResult(exit_code=process.returncode or 0, stdout=stdout, stderr=stderr)
class BypassAnalysisBash(Bash):
"""Bash variant that delegates permission decisions to PermissionEngine.
AgentScope's built-in Bash performs bypass-immune static analysis before
the engine can apply `permission_mode: bypass`. For this app we want the
configured permission mode to be authoritative.
"""
async def check_permissions(
self,
_tool_input: dict[str, Any],
_context: PermissionContext,
) -> PermissionDecision:
"""Bypass Bash static analysis and let the permission engine decide."""
return PermissionDecision(
behavior=PermissionBehavior.PASSTHROUGH,
message="Bash static analysis skipped; delegating to permission engine.",
)
@R.register("agentscope")
class AsAgentWrapper(BaseAgentWrapper):
"""Agent wrapper backed by AgentScope framework."""
SDK_PACKAGE = "agentscope"
@staticmethod
def _agentscope_usage(usage: Any) -> TokenUsage:
"""Normalize AgentScope's portable input/output usage."""
return TokenUsage.from_provider(usage)
def __init__(self, as_llm: str = "default", session_retention_days: int = 10, **kwargs):
super().__init__(**kwargs)
self.as_llm = self.bind(as_llm, BaseAsLLM, optional=False)
self.session_retention_days = int(session_retention_days)
self._session_cleanup_done = False
self._session_store: AsSessionStore | None = None
@classmethod
def _make_tool(
cls,
job: "BaseJob",
tool_context_id: str | None = None,
injected_job_kwargs: dict[str, Any] | None = None,
) -> FunctionTool:
injected = cls._resolve_injected_job_kwargs(
{"tool_context_id": tool_context_id, "injected_job_kwargs": injected_job_kwargs},
)
async def run_job(**kwargs) -> ToolChunk:
response = await job(**cls._merge_injected_job_kwargs(kwargs, injected))
state = ToolResultState.SUCCESS if response.success else ToolResultState.ERROR
return ToolChunk(content=[TextBlock(text=str(response.answer))], state=state)
tool = FunctionTool(func=run_job, name=job.name, description=job.description, is_concurrency_safe=False)
if parameters := cls._strip_injected_parameters(job.parameters, injected):
tool.input_schema = parameters
return tool
def _builtin_tools(
self,
names: list[str] | str | bool | None = "all",
*,
sequential_tool_calls: bool = False,
) -> list[ToolBase]:
"""Return selected AgentScope built-in tools rooted at ``self.cwd``."""
cwd = str(self.cwd)
backend = WorkspaceBackend(cwd, self.bash_environment)
factories = {
"bash": lambda: BypassAnalysisBash(cwd=cwd, backend=backend),
"edit": lambda: Edit(backend=backend),
"glob": lambda: Glob(backend=backend),
"grep": lambda: Grep(backend=backend),
"read": lambda: Read(backend=backend),
"write": lambda: Write(backend=backend),
}
if names is False:
selected_names = []
elif names is True or names is None or names == "all":
selected_names = list(factories)
elif names in ("none", "no", "false"):
selected_names = []
elif isinstance(names, str):
selected_names = [names]
else:
selected_names = names
tools: list[ToolBase] = []
for name in selected_names:
key = name.lower()
if key not in factories:
allowed = ", ".join(factories)
raise ValueError(f"Unknown builtin tool {name!r}; expected one of: {allowed}")
tools.append(factories[key]())
if sequential_tool_calls:
for tool in tools:
tool.is_concurrency_safe = False
return tools
@property
def session_path(self) -> Path:
"""Directory used for persisted AgentScope sessions."""
if self.app_context is None:
return self.workspace_path / "mem_session" / "agentscope"
return self.workspace_path / self.app_context.app_config.mem_session_dir / "agentscope"
@property
def _sessions(self) -> AsSessionStore:
"""Share one owner across wrappers targeting the same application session directory."""
if self.app_context is not None:
stores = self.app_context.metadata.setdefault("__agentscope_session_stores", {})
key = str(self.session_path.resolve())
if key not in stores:
stores[key] = AsSessionStore(self.session_path)
return stores[key]
if self._session_store is None:
self._session_store = AsSessionStore(self.session_path)
return self._session_store
def _cleanup_expired_sessions(self) -> None:
"""Delete persisted session files older than ``session_retention_days``."""
if self._session_cleanup_done or self.session_retention_days <= 0:
self._session_cleanup_done = True
return
session_path = self._sessions.path(str(uuid4())).parent
if not session_path.is_dir():
self._session_cleanup_done = True
return
cutoff = time.time() - self.session_retention_days * 24 * 60 * 60
removed = 0
for path in session_path.glob("*.jsonl"):
try:
if self._sessions.in_use(path.stem):
continue
if path.is_file() and path.stat().st_mtime < cutoff:
history = AsStateHandler(path).history_path()
path.unlink()
history.unlink(missing_ok=True)
removed += 1
except (OSError, ValueError) as exc:
self.logger.warning(f"Failed to clean expired AgentScope session {path}: {exc}")
if removed:
self.logger.info(
f"Cleaned {removed} AgentScope session(s) older than {self.session_retention_days} day(s)",
)
self._session_cleanup_done = True
def _resolve_skills(self, skills: list[str] | str | None) -> list[str]:
"""Resolve configured skill names to AgentScope local skill directories."""
return [str(path) for path in self._resolve_project_skills(skills).values()]
def _create_agent(self, *, options: dict[str, Any], **kwargs: Any) -> Agent:
"""Construct the SDK agent while subclasses reuse ReMe's tool and session wiring."""
del options
return Agent(**kwargs)
async def _build_agent(self, inputs: Any, *, state: AgentState | None = None, **kwargs) -> tuple[Agent, Any]:
"""Build an Agent instance from kwargs. Returns (agent, processed_inputs)."""
model = self.as_llm.model if self.as_llm else None
if model is None:
raise ValueError("AsAgentWrapper requires a bound as_llm component with a valid model.")
self._cleanup_expired_sessions()
system_prompt = kwargs.get("system_prompt") or ""
job_tools: list[str] = kwargs.get("job_tools", [])
resolved_jobs = self._resolve_job_tools(job_tools)
skills = self._resolve_skills(kwargs.get("skills"))
tool_context_id = kwargs.get("tool_context_id")
sequential_tool_calls = bool(kwargs.get("sequential_tool_calls", True))
builtin_tools = kwargs.get("builtin_tools", [])
if "builtin_tools" not in kwargs and bool(kwargs.get("use_builtin_tools", False)):
builtin_tools = "all"
tools: list[ToolBase] = []
native_tools = self._builtin_tools(builtin_tools, sequential_tool_calls=sequential_tool_calls)
read_only = kwargs.get("sandbox") == "read-only"
if read_only:
# AgentScope has no Codex-style command sandbox; omit write/exec
# builtins and retain only the explicitly bound framework tools.
native_tools = [tool for tool in native_tools if isinstance(tool, (Read, Glob, Grep))]
tools.extend(native_tools)
tools.extend(self._make_tool(job, tool_context_id, kwargs.get("injected_job_kwargs")) for job in resolved_jobs)
toolkit = (None if read_only else kwargs.get("toolkit")) or Toolkit(
tools=tools,
skills_or_loaders=skills,
)
if state is None:
options = self._sessions.options(kwargs)
async with self._sessions.open(options, PermissionMode(kwargs.get("permission_mode", "bypass"))) as session:
state = session.state
agent = self._create_agent(
options=kwargs,
name=self.name,
system_prompt=system_prompt,
model=model,
toolkit=toolkit,
state=state,
model_config=ModelConfig(**(kwargs.get("model_config") or {})),
context_config=ContextConfig(**(kwargs.get("context_config") or {})),
react_config=ReActConfig(**(kwargs.get("react_config") or {})),
)
if isinstance(inputs, str):
inputs = UserMsg(name="user", content=inputs)
return agent, inputs
async def _finish_reply(self, agent: Agent, last_msg: Msg, kwargs: dict) -> AgentReply:
"""Preserve the native message and optional structured-model response."""
usage = self._agentscope_usage(last_msg.usage) if last_msg.usage is not None else None
message = last_msg.model_dump(mode="json")
raw = {"message": message}
reason = message["finished_reason"]
status = "completed"
error = None
if reason is None:
status = "waiting"
elif reason == "interrupted":
status = "interrupted"
elif reason != "completed":
status = "failed"
error = (message.get("error") or {}).get("message") or f"AgentScope reply ended: {reason}"
structured_output = message.get("structured_output")
if usage is None:
self.logger.error("AgentScope did not return token usage; token accounting is unavailable for this reply.")
try:
output_schema: dict | None = kwargs.get("output_schema")
if status == "completed" and output_schema is not None:
assert self.as_llm is not None, "AsAgentWrapper requires a bound as_llm component with a valid model."
model = self.as_llm.model
assert model is not None, "AsAgentWrapper requires a bound as_llm component with a valid model."
res = await model.generate_structured_output(
messages=agent.state.context,
structured_model=output_schema,
)
raw["structured_response"] = self._serialize(res)
structured_output = res.content
if raw["structured_response"]["finished_reason"] == "interrupted":
status = "interrupted"
if res.usage is None:
usage = None
self.logger.error(
"AgentScope did not return structured-output token usage; token accounting is unavailable.",
)
elif usage is not None:
usage = TokenUsage.combine([usage, self._agentscope_usage(res.usage)])
finally:
if usage is not None:
self._record_token_usage(usage)
task = asyncio.current_task()
if task is not None and task.cancelling():
raise asyncio.CancelledError()
return self._reply_result(
session_id=agent.state.session_id,
result=last_msg.get_text_content(),
structured_output=structured_output,
usage=usage,
status=status,
error=error,
raw=raw,
)
async def create_session(self, **kwargs) -> str:
"""Persist a fresh state or independent live snapshot without calling a model."""
kwargs = self._sessions.options(self._merged_kwargs(kwargs))
options = {key: kwargs[key] for key in ("session_id", "resume", "fork_session") if key in kwargs}
async with self._sessions.open(options, PermissionMode(kwargs.get("permission_mode", "bypass"))) as session:
if not options.get("resume") and self._sessions.path(session.state.session_id).exists():
raise FileExistsError(f"AgentScope session already exists: {session.state.session_id}")
await self._sessions.save(session)
return session.state.session_id
async def session_exists(self, session_id: str) -> bool:
"""Check stored or active sessions without constructing an Agent."""
return await self._sessions.exists(self._sessions.validate_id(session_id))
async def get_session_path(self, session_id: str) -> Path:
"""Resolve the contained native state file, including before its first write."""
return self._sessions.path(session_id)
async def read_session(self, session_id: str) -> SessionSnapshot:
"""Read stored or live display history without waiting behind generation."""
return await self._sessions.snapshot(session_id)
async def get_session_status(self, session_id: str) -> SessionStatus:
"""Report application-owned execution and SDK approval/execution waits."""
return await self._sessions.get_status(session_id)
@asynccontextmanager
async def session_guard(self, session_id: str, *, expected_revision: str):
"""Protect a decision against generation and queued observation writers."""
async with self._sessions.guard(session_id, expected_revision):
yield
async def append_session(
self,
session_id: str,
content: str,
*,
message_id: str,
role: Literal["user", "assistant"] = "assistant",
timeout: float = 30,
expected_turn_id: str | None = None,
expected_revision: str | None = None,
delivery: str = "idle",
) -> SessionMessage:
"""Append an idempotent user or assistant observation without generating a reply."""
return await self._sessions.append(
session_id,
content,
message_id=message_id,
role=role,
timeout=timeout,
expected_turn_id=expected_turn_id,
expected_revision=expected_revision,
delivery=delivery,
name=self.name,
)
async def compact_session(self, session_id: str) -> None:
"""Force compression of an AgentScope session."""
kwargs = self._sessions.options(self._merged_kwargs({"resume": session_id}))
async with self._sessions.open(
kwargs,
PermissionMode(kwargs.get("permission_mode", "bypass")),
active=True,
) as session:
agent, _ = await self._build_agent(None, state=session.state, **kwargs)
config = {**(kwargs.get("context_config") or {}), "trigger_ratio": 1e-9}
try:
await agent.compress_context(ContextConfig(**config))
finally:
self._sessions.finish(session)
await finish_cleanup(self._sessions.drain(session, agent))
await finish_cleanup(self._sessions.save(session))
# ----- StreamChunk conversion -------------------------------------------
@classmethod
# pylint: disable=too-many-return-statements
def _event_to_chunk(cls, event: Any) -> StreamChunk:
"""Normalize block operations while retaining native fields and unknown events."""
native = event.model_dump(mode="json")
operation = (
"start" if str(event.type).endswith("START") else "end" if str(event.type).endswith("END") else "delta"
)
metadata = {"native": native}
common = {
"event": operation,
"turn_id": getattr(event, "reply_id", None),
"message_id": getattr(event, "reply_id", None),
"chunk": None,
"metadata": metadata,
}
if isinstance(event, ReplyStartEvent):
return cls._chunk(ChunkEnum.REPLY_START, **common, session_id=event.session_id, status="running")
if isinstance(event, ReplyEndEvent):
metadata["finished_reason"] = native["finished_reason"]
metadata["error"] = (native.get("error") or {}).get("message")
return cls._chunk(
ChunkEnum.REPLY_END,
**common,
session_id=event.session_id,
status=stream_status(event.finished_reason) or "waiting",
)
for classes, chunk_type in (
((TextBlockStartEvent, TextBlockDeltaEvent, TextBlockEndEvent), ChunkEnum.CONTENT),
((ThinkingBlockStartEvent, ThinkingBlockDeltaEvent, ThinkingBlockEndEvent), ChunkEnum.THINK),
((DataBlockStartEvent, DataBlockDeltaEvent, DataBlockEndEvent), ChunkEnum.DATA),
((ToolCallStartEvent, ToolCallDeltaEvent, ToolCallEndEvent), ChunkEnum.TOOL_CALL),
(
(ToolResultStartEvent, ToolResultTextDeltaEvent, ToolResultDataDeltaEvent, ToolResultEndEvent),
ChunkEnum.TOOL_RESULT,
),
):
if isinstance(event, classes):
common["chunk"] = getattr(event, "delta", getattr(event, "text", getattr(event, "data", None)))
if getattr(event, "url", None):
common["chunk"] = {"url": event.url}
return cls._chunk(
chunk_type,
**common,
block_id=getattr(event, "block_id", None),
tool_call_id=getattr(event, "tool_call_id", None),
tool_call_name=getattr(event, "tool_call_name", None),
media_type=getattr(event, "media_type", None),
status=stream_status(getattr(event, "state", None)),
)
if isinstance(event, ModelCallStartEvent):
return cls._chunk(ChunkEnum.USAGE, **common)
if isinstance(event, ModelCallEndEvent):
usage = TokenUsage(input_tokens=event.input_tokens, output_tokens=event.output_tokens)
common["chunk"] = usage.model_dump()
metadata["usage"] = usage.model_dump()
return cls._chunk(
ChunkEnum.USAGE,
**common,
input_tokens=usage.input_tokens,
output_tokens=usage.output_tokens,
)
if isinstance(event, ExceedMaxItersEvent):
common["chunk"] = "Exceeded max iterations"
return cls._chunk(ChunkEnum.ERROR, **common)
common["chunk"] = native
common["event"] = "end"
approval = str(event.type) in {"REQUIRE_USER_CONFIRM", "REQUIRE_EXTERNAL_EXECUTION"}
return cls._chunk(
ChunkEnum.APPROVAL if approval else ChunkEnum.DATA,
**common,
status="waiting" if approval else None,
)
async def reply_stream(self, inputs: Any, **kwargs) -> AsyncGenerator[StreamChunk, None]:
"""Execute once, streaming native events followed by the complete outcome."""
kwargs = self._sessions.options(self._merged_kwargs(kwargs))
async with self._sessions.open(
kwargs,
PermissionMode(kwargs.get("permission_mode", "bypass")),
active=True,
) as session:
agent, inputs = await self._build_agent(inputs, state=session.state, **kwargs)
last_msg, terminal = None, None
turn_id = None
inputs_recorded = False
model_usages = []
finishing = False
result = None
try:
async with aclosing(agent.reply_stream(inputs, yield_final_msg=True)) as stream:
async for event in stream:
if not inputs_recorded:
record_inputs(session, inputs)
inputs_recorded = True
if isinstance(event, Msg):
last_msg = event
continue
if isinstance(event, (ModelCallStartEvent, ReplyEndEvent)):
await finish_cleanup(self._sessions.drain(session, agent))
if isinstance(event, ModelCallEndEvent):
model_usages.append(self._agentscope_usage(event))
chunk = self._event_to_chunk(event)
chunk.session_id = chunk.session_id or agent.state.session_id
turn_id = chunk.turn_id or turn_id
if isinstance(event, ReplyEndEvent):
terminal = chunk
else:
record_chunk(session, chunk)
yield chunk
if last_msg is None:
raise RuntimeError("AgentScope final message not received")
if terminal is None:
if last_msg.finished_reason is not None:
raise RuntimeError("AgentScope reply_end not received")
terminal = self._chunk(
ChunkEnum.REPLY_END,
event="end",
chunk=None,
session_id=agent.state.session_id,
turn_id=last_msg.id,
status="waiting",
)
finishing = True
result = await self._finish_reply(agent, last_msg, kwargs)
terminal.chunk = {key: value for key, value in result.items() if key != "events"}
terminal.status = result["status"]
terminal.metadata["error"] = result["error"]
finally:
if not inputs_recorded:
accepted = {message.id for message in agent.state.context}
messages = [inputs] if isinstance(inputs, Msg) else inputs if isinstance(inputs, list) else []
record_inputs(session, [msg for msg in messages if isinstance(msg, Msg) and msg.id in accepted])
if not finishing and model_usages:
self._record_token_usage(TokenUsage.combine(model_usages))
if result is None:
interrupted = isinstance(sys.exception(), (asyncio.CancelledError, GeneratorExit))
terminal = self._chunk(
ChunkEnum.REPLY_END,
event="end",
chunk=None,
turn_id=turn_id,
session_id=agent.state.session_id,
status="interrupted" if interrupted else "failed",
)
self._sessions.finish(session)
record_end(session, terminal, last_msg)
await finish_cleanup(self._sessions.drain(session, agent))
await finish_cleanup(self._sessions.save(session))
yield terminal