mirror of
https://github.com/agentscope-ai/ReMe.git
synced 2026-11-29 00:38:33 +00:00
* Add sandboxed Python execution and home AutoBash plugin * Harden read-only shell commands and filesystem sandboxes * Group file sandbox backends in one package * Fix macOS file sandbox isolation and runtime access * Refine file sandbox limits and executor checks * Harden AutoBash policy and macOS sandbox supervision * fix(home): require ReMe release with file sandbox * refactor(home): simplify sandbox calls and redundant tests * fix(execution): bound output and clean up cancelled sandbox startup * fix(tests): mock Seatbelt platform requirements on Linux * fix(home): block Git help helpers and harden sandbox cleanup * Fix sandbox runtime links and subprocess cleanup * ci: cover Home plugin tests * test: wait for pipeline descendants to exit after cancellation * fix: align Home dependencies and preserve cleanup cancellation Require ReMe 0.4.2.1 and verify isolated Home wheel installation in package CI. Share cancellation-safe cleanup with thread calls, retain AnyIO cancellation semantics, and record Bubblewrap mount targets during argument construction. * feat(home): prepare self-evolution workspaces and benchmark inputs * fix(home): load only selected cases for debug derivation * feat(home): evaluate candidates with benchmark judges and prepare workspace docs * refactor(home): organize workflows and unify debug evaluation mode * fix(home): align Docker runtime and preserve evaluation failures * refactor(home): align evaluation summaries with dev_meta * feat(home): migrate agent, sampling and evidence inspection tooling * feat(home): add case-study agent and query evidence tracing tools - Add home_case_study job with CaseStudyAgentWrapper and a read-only sandboxed investigation step for per-case diagnostic reports - Add home_trace_query_evidence job/step to locate a query's source evidence sessions, memory checkpoints and answer/score previews - Compact evaluation summaries: record per-query failure errors, round scores to four decimals, expose scoring_enabled and observed means - Slim run manifests: drop schema_version and trusted_judge fingerprint, exclude debug/sampling_policy options, keep construction_source only for query-only replay - Simplify history index internals and update guide docs and tests * feat(home): support multi-case case-study runs with dedicated LLM and Git sandbox - Allow home_case_study to investigate up to eight ordered cases per invocation with a shared focus, one isolated agent per case, while keeping the legacy single-case selector as a deprecated alias - Configure a dedicated home_case_study LLM component instead of the shared judge backend - Wrap ReMe's OS file sandbox with a Home-specific Git runtime grant (developer directory on macOS) and argv-based child environment - Tighten case-study prompts around evidence certainty, code-tool path scoping, citation form, and unresolved-cause reporting - Extend evidence tracing and expand case-study/sandbox tests and docs * feat(home): run case studies with bounded concurrency and fix sandbox test * feat(home): guard repeated evaluations and preserve retry selections * feat(home): migrate optimization workflows and evaluation budgets * feat(home): add candidate admission gate and construction-equivalence replay Add host-side candidate gate agent that reviews committed changes before sampling, and construction-equivalence agent that compares a candidate against its nearest reusable ancestor to select query-only replay with 60% probability when construction is unchanged. Wire both into plugin.yaml application defaults, update optimizer prompt to explain the new host behaviors, extend snapshot/evaluation components with reuse support, and add focused tests. * feat(home): add structured-report agent and gate/equivalence test coverage Add StructuredReportAgent wrapper selectable via the _structured_report_model option in BoundedAgentWrapper, plus its dedicated unit tests. Extend candidate gate, construction equivalence, evaluation history, sampling, and validation budget tests, and document the new behavior in the plugin README. * feat(home): add standalone benchmark test evaluation and fix compression recovery * fix(home): preserve top-level answer failure classification * refactor(home): rename max_validations to max_evaluations * refactor(home): extract shared review_report workflow helper and bump version to 0.4.2.2 * fix(home): load runner credentials and localize dataset evaluation * fix(benchmark): propagate Home sandbox memory limits * refactor(home): consolidate Git exports and candidate validation * fix(home): clarify branch and diff tool parameter contracts * feat(home): bound case-study reports and migrate draft tools * fix(home): align benchmark report limits with plugin defaults * Fix Home evaluation recovery and cancellation boundaries * fix(home): tolerate fenced optimizer results and finalize exhausted budgets * fix(benchmark): align Docker runtime with AgentScope 2.0.11 * fix(home): unify history writes and cancellation cleanup * refactor(home): reuse structured report parsing * ci: remove redundant Home compatibility install check * fix(home): preserve literal formatting in structured reports * fix(home): continue optimization after baseline question errors * fix(sandbox): require explicit file write grants * test(home): verify host network isolation with connection probes * fix(sandbox): write to the validated canonical target * refactor(home): simplify optimizer evidence validation * feat(home): add targeted evaluation and controlled memory replay Expose optional case/question targets with bounded sampling and ignored invalid IDs. Reuse reviewed memory per case, preserve paired replay without targets, and sample every direct child of init. Restore the persistent optimizer overview and document optional targeted checks. Add regression coverage for selection, partial reuse, provenance, and frozen retries. * feat(home): preserve evaluated commits and compare validation evidence Add compact paired score and token comparisons, protected evaluated branches, and unique commit-prefix selection. Reveal comparison guidance during final selection and update optimizer tools, documentation, and regression tests. * feat(home): expand debug cases and diversify smoke questions * feat(home): prioritize reusable memory in targeted evaluation * fix(ci): limit coverage collection to repository sources * chore(home): remove legacy Meta-ReMe references * fix(home): harden evaluation and bound targeted reuse Normalize benchmark inputs while preserving standalone judge contracts. Protect initial baselines and completed evaluations, and scope targeted memory reuse to the selected sample. Simplify HoMe usage and agent documentation. * docs(home): explain how to use custom datasets * fix(home): validate explicit replay artifacts before sampling * fix(home): validate replay inputs before selection * fix(home): pin candidate admission and compact replay metadata * fix(home): address evaluation and preparation review findings Select baseline retries by attempt order and keep archive preflight outside the workspace lock. Base candidate admission on usable budgeted ancestors and validate normalized dataset IDs before publishing preparation. * docs(home): consolidate benchmark experiment guides Document the shared HoMe workflow and keep dataset setup, splits, and results in the BEAM and LongMemEval guides. * fix(home): resolve release and evaluation review findings Validate artifact IDs against the published runtime contract, cover the minimum ReMe wheel and Docker backend in CI, and keep sampling budgets and observations consistent when evaluation results are archived or restored. * test(home): seed durable validation history in optimizer fixtures * fix(ci): align Home wheel smoke test with minimum ReMe release * fix(ci): resolve unreleased minimum runtime from built wheels * fix(home): enforce full init baselines and retain replay evidence * docs: reorganize bilingual BEAM and LME benchmark guides * fix(home): bind optimizer sampling to the evaluated checkout * Validate retained replay configuration and pin explicit snapshots * docs(home): clarify final replay validation requirements --------- Co-authored-by: jinli.yl <jinli.yl@alibaba-inc.com>
167 lines
7.3 KiB
Python
167 lines
7.3 KiB
Python
"""Common contract and path validation for subprocess file sandboxes."""
|
|
|
|
import asyncio
|
|
import os
|
|
import sys
|
|
from abc import abstractmethod
|
|
from collections import deque
|
|
from pathlib import Path
|
|
|
|
from agentscope.tool import ExecResult
|
|
|
|
from ..local_backend import LocalProcessBackend
|
|
|
|
|
|
def contains(root: str, path: str) -> bool:
|
|
"""Whether a path is inside a configured root."""
|
|
return os.path.commonpath((root, path)) == root
|
|
|
|
|
|
class FileSandboxBackend(LocalProcessBackend):
|
|
"""Execute subprocesses with explicit host-path read and write access."""
|
|
|
|
def __init__(self, *, cwd: str | os.PathLike[str], read_only_paths: list[str], writable_paths: list[str]) -> None:
|
|
self._cwd = self._validate_path(os.fspath(cwd))
|
|
if not os.path.isdir(self._cwd):
|
|
raise ValueError("sandbox working directory must be a directory")
|
|
self._read_only_paths = self._validate_paths(read_only_paths, "read_only_paths")
|
|
self._writable_paths = self._validate_paths(writable_paths, "writable_paths")
|
|
if not any(contains(path, self._cwd) for path in self._read_only_paths + self._writable_paths):
|
|
self._read_only_paths.append(self._cwd)
|
|
# A virtual environment can point outside sys.prefix to its base
|
|
# interpreter and standard library (notably with Homebrew Python).
|
|
for runtime in (sys.prefix, sys.base_prefix, sys.executable):
|
|
path = os.path.realpath(runtime)
|
|
if path in ("/", "/usr", "/usr/local") or path.startswith("/usr/"):
|
|
continue
|
|
if not any(contains(root, path) for root in self._read_only_paths + self._writable_paths):
|
|
self._read_only_paths.append(self._validate_path(path))
|
|
paths = self._read_only_paths + self._writable_paths
|
|
if len(set(paths)) != len(paths):
|
|
raise ValueError("sandbox paths must not contain duplicates")
|
|
self._path_identities = {path: self._identity(path) for path in paths}
|
|
|
|
@staticmethod
|
|
def _runtime_paths() -> tuple[set[str], set[str]]:
|
|
"""Collect runtime symlinks and traversal paths without exposing parent trees."""
|
|
links = set()
|
|
metadata = set()
|
|
for runtime in (sys.prefix, sys.base_prefix, sys.executable):
|
|
pending = deque(Path(runtime).parts)
|
|
current = "/"
|
|
followed = 0
|
|
while pending:
|
|
part = pending.popleft()
|
|
if part == "/":
|
|
current = "/"
|
|
continue
|
|
if part == "..":
|
|
current = os.path.dirname(current)
|
|
continue
|
|
path = os.path.join(current, part)
|
|
if os.path.islink(path):
|
|
followed += 1
|
|
if followed > 40:
|
|
raise RuntimeError(f"too many runtime symlinks: {runtime}")
|
|
links.add(path)
|
|
pending.extendleft(reversed(Path(os.readlink(path)).parts))
|
|
else:
|
|
metadata.add(path)
|
|
current = path
|
|
return links, metadata
|
|
|
|
@staticmethod
|
|
def _identity(path: str) -> tuple[int, int]:
|
|
info = os.stat(path, follow_symlinks=False)
|
|
return info.st_dev, info.st_ino
|
|
|
|
@staticmethod
|
|
def _validate_path(raw: str) -> str:
|
|
if not isinstance(raw, str) or not raw or not os.path.isabs(raw):
|
|
raise ValueError("sandbox paths must be non-empty absolute paths")
|
|
path = os.path.normpath(raw)
|
|
if path == "/" or not os.path.exists(path) or os.path.realpath(path) != path:
|
|
raise ValueError(f"sandbox path must exist without symlinks and cannot be root: {raw}")
|
|
return path
|
|
|
|
@classmethod
|
|
def _validate_paths(cls, raw: list[str], name: str) -> list[str]:
|
|
if not isinstance(raw, list) or any(not isinstance(item, str) for item in raw):
|
|
raise ValueError(f"{name} must be a list of absolute paths")
|
|
return [cls._validate_path(path) for path in raw]
|
|
|
|
def _check_paths(self, cwd: str) -> None:
|
|
if not any(contains(path, cwd) for path in self._read_only_paths + self._writable_paths):
|
|
raise ValueError("command working directory must be inside a sandbox path")
|
|
for path, identity in self._path_identities.items():
|
|
if not os.path.exists(path) or os.path.realpath(path) != path or self._identity(path) != identity:
|
|
raise RuntimeError(f"sandbox path changed before execution: {path}")
|
|
|
|
async def getcwd(self) -> str:
|
|
"""Return the host-identical sandbox working directory."""
|
|
return self._cwd
|
|
|
|
@abstractmethod
|
|
async def _start_process(self, command: list[str], cwd: str, *, stdin=asyncio.subprocess.DEVNULL):
|
|
"""Start one sandboxed process, never falling back to host execution."""
|
|
|
|
async def exec_shell(
|
|
self,
|
|
command: list[str],
|
|
*,
|
|
cwd: str | None = None,
|
|
timeout: float | None = None,
|
|
raise_errors: bool = False,
|
|
) -> ExecResult:
|
|
"""Execute inside the sandbox; raise_errors preserves output in ProcessTimeout."""
|
|
return await self._run_job(command, cwd or self._cwd, data=None, timeout=timeout, raise_errors=raise_errors)
|
|
|
|
async def _run_job(
|
|
self,
|
|
command: list[str],
|
|
cwd: str,
|
|
*,
|
|
data: bytes | None,
|
|
timeout: float | None,
|
|
raise_errors: bool = False,
|
|
) -> ExecResult:
|
|
"""Run with optional stdin; platform backends may own a different job lifecycle."""
|
|
process = await self._start_process(
|
|
command,
|
|
cwd,
|
|
stdin=asyncio.subprocess.PIPE if data is not None else asyncio.subprocess.DEVNULL,
|
|
)
|
|
return await self._communicate(process, data=data, timeout=timeout, raise_errors=raise_errors)
|
|
|
|
async def read_file(self, path: str) -> bytes:
|
|
"""Read through a sandboxed command so file rules still apply."""
|
|
result = await self.exec_shell(["cat", path])
|
|
if not result.ok():
|
|
raise OSError(result.stderr.decode(errors="replace"))
|
|
return result.stdout
|
|
|
|
async def write_file(self, path: str, data: bytes) -> None:
|
|
"""Write through a sandboxed command so file rules still apply."""
|
|
if not isinstance(data, bytes):
|
|
raise TypeError("data must be bytes")
|
|
# Private sandbox tmpfs paths can accept writes without touching the
|
|
# host. File helpers must still report writes outside explicit grants
|
|
# as errors, rather than silently writing a disposable shadow file.
|
|
target = os.path.realpath(os.path.join(self._cwd, path))
|
|
grants = [
|
|
(root, writable)
|
|
for roots, writable in ((self._read_only_paths, False), (self._writable_paths, True))
|
|
for root in roots
|
|
if contains(root, target)
|
|
]
|
|
if not grants or not max(grants, key=lambda grant: len(grant[0]))[1]:
|
|
raise PermissionError(f"Sandbox path is not writable: {path}")
|
|
script = 'mkdir -p -- "$(dirname -- "$1")" && cat > "$1"'
|
|
result = await self._run_job(
|
|
["/bin/sh", "-c", script, "sh", target],
|
|
self._cwd,
|
|
data=data,
|
|
timeout=None,
|
|
)
|
|
if not result.ok():
|
|
raise OSError(result.stderr.decode(errors="replace"))
|