refactor(tools): tool_result_storage/backend_helpers/output_limits/spill_safety — unify .env lookup (_dotenv_value), alias normalize_modal_mode, collapse branches, compact docstrings
This commit is contained in:
+13
-22
@@ -1,21 +1,16 @@
|
||||
"""Symlink-safe creation helpers for spill/cache files.
|
||||
|
||||
Spill files (terminal output, hook context, subagent summaries, web_extract
|
||||
text) live in predictable directories under ``~/.hermes``; a plain
|
||||
Spill files live in predictable directories under ``~/.hermes``; a plain
|
||||
``open(path, "w")`` there would follow a pre-planted symlink and let a local
|
||||
process redirect the write onto ``~/.bashrc``, ``authorized_keys``, etc.
|
||||
|
||||
Every helper refuses symlinks by construction: new files use
|
||||
``O_CREAT | O_EXCL`` (fails on ANY existing path, including a dangling link);
|
||||
overwrites ``lstat`` + ``unlink`` the existing path first (removes the link,
|
||||
never its target) and then create exclusively, so the pair can't be raced.
|
||||
|
||||
Privacy tiers: ``private=True`` (default) forces ``0o700`` dirs / ``0o600``
|
||||
files for spills that may hold pre-redaction secrets; ``private=False`` keeps
|
||||
umask-default perms for cache dirs bind-mounted into remote terminal backends
|
||||
(``credential_files._CACHE_DIRS``), where a non-root container UID must read them.
|
||||
|
||||
Disk failures are the caller's concern: helpers raise ``OSError``.
|
||||
process redirect the write onto ``~/.bashrc``, ``authorized_keys``, etc. Every
|
||||
helper refuses symlinks by construction: new files use ``O_CREAT | O_EXCL``
|
||||
(fails on ANY existing path, including a dangling link); overwrites ``lstat`` +
|
||||
``unlink`` the existing path first (removes the link, never its target), then
|
||||
create exclusively, so the pair can't be raced. ``private=True`` (default)
|
||||
forces ``0o700`` dirs / ``0o600`` files for spills that may hold pre-redaction
|
||||
secrets; ``private=False`` keeps umask perms for cache dirs bind-mounted into
|
||||
remote backends (``credential_files._CACHE_DIRS``) where a non-root container
|
||||
UID must read them. Disk failures are the caller's concern: helpers raise ``OSError``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -38,10 +33,8 @@ _O_NOFOLLOW = getattr(os, "O_NOFOLLOW", 0)
|
||||
|
||||
def ensure_spill_dir(path: Path, *, private: bool = True) -> Path:
|
||||
"""Create ``path`` (and parents) as a directory, refusing symlinks.
|
||||
|
||||
``private=True`` creates the leaf ``0o700`` and tightens an existing leaf to
|
||||
``0o700``. Raises ``OSError`` if the leaf is not a real directory.
|
||||
"""
|
||||
``private=True`` creates the leaf ``0o700`` and tightens an existing leaf.
|
||||
Raises ``OSError`` if the leaf is not a real directory."""
|
||||
path = Path(path)
|
||||
path.mkdir(mode=0o700 if private else 0o777, parents=True, exist_ok=True)
|
||||
st = os.lstat(path)
|
||||
@@ -61,11 +54,9 @@ def open_exclusive(
|
||||
errors: str = "strict",
|
||||
) -> IO[str]:
|
||||
"""Open ``path`` for writing via exclusive create; never follows a link.
|
||||
|
||||
``overwrite=True`` first unlinks an existing path (``lstat``-checked, so only
|
||||
the link itself is removed and directories are refused), then creates
|
||||
exclusively — the overwrite path cannot be redirected through a symlink either.
|
||||
"""
|
||||
exclusively — the overwrite path cannot be redirected through a symlink either."""
|
||||
path = Path(path)
|
||||
if overwrite:
|
||||
try:
|
||||
|
||||
@@ -19,12 +19,10 @@ _VALID_MODAL_MODES = {"auto", "direct", "managed"}
|
||||
|
||||
def managed_nous_tools_enabled(*, force_fresh: bool = False) -> bool:
|
||||
"""True when the user is entitled to the Nous Tool Gateway (coarse gate:
|
||||
paid Portal service access OR a live free tool pool — "is ANY managed tool usable").
|
||||
|
||||
Fails closed on unknown/error entitlement — never blocks startup.
|
||||
Per-category coverage is narrowed by callers via ``tool_gateway_entitled_for``.
|
||||
``force_fresh=True`` is for interactive flows that must see a just-purchased grant.
|
||||
"""
|
||||
paid Portal service access OR a live free tool pool). Fails closed on
|
||||
unknown/error entitlement — never blocks startup. Per-category coverage is
|
||||
narrowed by callers via ``tool_gateway_entitled_for``. ``force_fresh=True``
|
||||
is for interactive flows that must see a just-purchased grant."""
|
||||
try:
|
||||
from hermes_cli.nous_account import get_nous_portal_account_info
|
||||
|
||||
@@ -50,10 +48,7 @@ def nous_tool_gateway_unavailable_message(
|
||||
)
|
||||
|
||||
account_info = get_nous_portal_account_info(force_fresh=force_fresh)
|
||||
message = format_nous_portal_entitlement_message(
|
||||
account_info,
|
||||
capability=capability,
|
||||
)
|
||||
message = format_nous_portal_entitlement_message(account_info, capability=capability)
|
||||
if message:
|
||||
return message
|
||||
except Exception:
|
||||
@@ -76,9 +71,7 @@ def coerce_modal_mode(value: object | None) -> str:
|
||||
return mode if mode in _VALID_MODAL_MODES else _DEFAULT_MODAL_MODE
|
||||
|
||||
|
||||
def normalize_modal_mode(value: object | None) -> str:
|
||||
"""Return a normalized modal execution mode."""
|
||||
return coerce_modal_mode(value)
|
||||
normalize_modal_mode = coerce_modal_mode
|
||||
|
||||
|
||||
def has_direct_modal_credentials() -> bool:
|
||||
@@ -105,8 +98,6 @@ def resolve_modal_backend_state(
|
||||
requested_mode = coerce_modal_mode(modal_mode)
|
||||
if managed_enabled is None:
|
||||
managed_enabled = managed_nous_tools_enabled()
|
||||
managed_mode_blocked = requested_mode == "managed" and not managed_enabled
|
||||
|
||||
managed_ok = managed_enabled and managed_ready
|
||||
if requested_mode == "managed":
|
||||
selected_backend = "managed" if managed_ok else None
|
||||
@@ -114,13 +105,12 @@ def resolve_modal_backend_state(
|
||||
selected_backend = "direct" if has_direct else None
|
||||
else:
|
||||
selected_backend = "managed" if managed_ok else "direct" if has_direct else None
|
||||
|
||||
return {
|
||||
"requested_mode": requested_mode,
|
||||
"mode": requested_mode,
|
||||
"has_direct": has_direct,
|
||||
"managed_ready": managed_ready,
|
||||
"managed_mode_blocked": managed_mode_blocked,
|
||||
"managed_mode_blocked": requested_mode == "managed" and not managed_enabled,
|
||||
"selected_backend": selected_backend,
|
||||
}
|
||||
|
||||
@@ -137,6 +127,16 @@ def _scoped_credential(name: str) -> str:
|
||||
return (os.getenv(name, "") or "").strip()
|
||||
|
||||
|
||||
def _dotenv_value(env_var: str) -> str:
|
||||
"""``.env`` value via ``hermes_cli.config.get_env_value`` (``""`` when unavailable)."""
|
||||
try:
|
||||
from hermes_cli.config import get_env_value
|
||||
|
||||
return str(get_env_value(env_var) or "").strip()
|
||||
except Exception: # pragma: no cover — config is in-repo
|
||||
return ""
|
||||
|
||||
|
||||
def resolve_provider_secret(
|
||||
env_var: str,
|
||||
provider_id: str,
|
||||
@@ -154,11 +154,9 @@ def resolve_provider_secret(
|
||||
value = str(config_value or "").strip()
|
||||
if value:
|
||||
return value
|
||||
|
||||
key = _scoped_credential(env_var)
|
||||
if key:
|
||||
return key
|
||||
|
||||
try:
|
||||
from agent.secret_scope import is_multiplex_active
|
||||
|
||||
@@ -166,21 +164,9 @@ def resolve_provider_secret(
|
||||
return ""
|
||||
except Exception: # pragma: no cover — secret_scope is in-repo
|
||||
pass
|
||||
|
||||
if env_getter is not None:
|
||||
key = str(env_getter(env_var) or "").strip()
|
||||
else:
|
||||
try:
|
||||
from hermes_cli.config import get_env_value
|
||||
|
||||
key = str(get_env_value(env_var) or "").strip()
|
||||
except ImportError: # pragma: no cover — config is in-repo
|
||||
key = ""
|
||||
if key:
|
||||
key = str(env_getter(env_var) or "").strip() if env_getter is not None else _dotenv_value(env_var)
|
||||
if key or not provider_id:
|
||||
return key
|
||||
|
||||
if not provider_id:
|
||||
return ""
|
||||
try:
|
||||
from agent.credential_pool import load_pool
|
||||
|
||||
@@ -193,9 +179,7 @@ def resolve_provider_secret(
|
||||
if entry is None:
|
||||
continue
|
||||
key = str(
|
||||
getattr(entry, "runtime_api_key", "")
|
||||
or getattr(entry, "access_token", "")
|
||||
or ""
|
||||
getattr(entry, "runtime_api_key", "") or getattr(entry, "access_token", "") or ""
|
||||
).strip()
|
||||
if key:
|
||||
return key
|
||||
@@ -207,8 +191,7 @@ def resolve_provider_secret(
|
||||
def resolve_openai_audio_api_key() -> str:
|
||||
"""Prefer VOICE_TOOLS_OPENAI_KEY, else OPENAI_API_KEY (scope-aware, with
|
||||
credential-pool fallback for the latter). Must go through the secret scope:
|
||||
a raw ``os.environ`` read could bill another profile's account under multiplex.
|
||||
"""
|
||||
a raw ``os.environ`` read could bill another profile's account under multiplex."""
|
||||
return (
|
||||
resolve_provider_secret("VOICE_TOOLS_OPENAI_KEY", "")
|
||||
or resolve_provider_secret("OPENAI_API_KEY", "openai-api")
|
||||
@@ -216,10 +199,7 @@ def resolve_openai_audio_api_key() -> str:
|
||||
|
||||
|
||||
def prefers_gateway(config_section: str) -> bool:
|
||||
"""Return True when the user opted into the Tool Gateway for this tool.
|
||||
|
||||
Reads ``<section>.use_gateway`` from config.yaml. Never raises.
|
||||
"""
|
||||
"""True when ``<section>.use_gateway`` is set in config.yaml. Never raises."""
|
||||
try:
|
||||
from hermes_cli.config import load_config
|
||||
section = (load_config() or {}).get(config_section)
|
||||
@@ -273,10 +253,8 @@ def read_selection(section: str) -> str | None:
|
||||
raw = _raw_section(section)
|
||||
if raw is None:
|
||||
return None
|
||||
|
||||
if "use_gateway" in raw and is_truthy_value(raw.get("use_gateway"), default=False):
|
||||
return NOUS_MANAGED_PROVIDER
|
||||
|
||||
for key in _SELECTION_NAME_KEYS.get(section, _DEFAULT_NAME_KEYS):
|
||||
value = raw.get(key)
|
||||
if value is not None:
|
||||
@@ -302,27 +280,22 @@ def selection_exists(section: str) -> bool:
|
||||
|
||||
# Backends that once shipped in-tree but were removed. A config still pointing at
|
||||
# one would otherwise fail silently at the FIRST tool call with a generic "no
|
||||
# registered provider has that name" — no migration, no startup notice. Consulted
|
||||
# by the startup config check and selection_error() so the user gets a real message.
|
||||
# Add removals here, never as one-off string checks at call sites, e.g.
|
||||
# registered provider has that name". Consulted by the startup config check and
|
||||
# selection_error(). Add removals here, never as one-off string checks, e.g.
|
||||
# "web": {"<name>": "the <Name> backend was removed in vX.Y.Z (...)"},
|
||||
REMOVED_BACKENDS: Dict[str, Dict[str, str]] = {}
|
||||
|
||||
|
||||
def removed_backend_note(section: str, name: str) -> Optional[str]:
|
||||
"""Explanation for a backend that used to ship in-tree, or None.
|
||||
|
||||
``name`` tolerates the quoted form callers pass to selection_error().
|
||||
"""
|
||||
``name`` tolerates the quoted form callers pass to selection_error()."""
|
||||
normalized = (name or "").strip().strip("'\"").lower()
|
||||
return REMOVED_BACKENDS.get(section, {}).get(normalized)
|
||||
|
||||
|
||||
def selection_error(section: str, selection_name: str, failure: str) -> str:
|
||||
"""The uniform honest-error contract for a selected-but-broken provider."""
|
||||
note = removed_backend_note(section, selection_name)
|
||||
if note:
|
||||
failure = note
|
||||
failure = removed_backend_note(section, selection_name) or failure
|
||||
return (
|
||||
f"{section} is configured to use {selection_name} (set via hermes "
|
||||
f"tools), but {failure}. Run 'hermes tools' to change it."
|
||||
@@ -333,12 +306,4 @@ def fal_key_is_configured() -> bool:
|
||||
"""True when FAL_KEY is set (scope/env, else ``.env`` for CLI paths that
|
||||
run before dotenv loads) to a non-whitespace value — so tool-side and CLI
|
||||
setup-time checks agree; whitespace-only counts as unset everywhere."""
|
||||
value = _scoped_credential("FAL_KEY") or None
|
||||
if value is None:
|
||||
try:
|
||||
from hermes_cli.config import get_env_value
|
||||
|
||||
value = get_env_value("FAL_KEY")
|
||||
except Exception:
|
||||
value = None
|
||||
return bool(value and value.strip())
|
||||
return bool(_scoped_credential("FAL_KEY") or _dotenv_value("FAL_KEY"))
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
"""Configurable tool-output truncation limits (``tool_output`` in config.yaml).
|
||||
|
||||
Centralises the caps previously hardcoded in ``terminal_tool`` (``max_bytes``)
|
||||
and ``file_operations`` (``max_lines`` / ``max_line_length``). Defaults equal
|
||||
the old constants, so behaviour is unchanged when the section is absent, and
|
||||
the reader never raises — any config error falls back to the defaults.
|
||||
Ported from anomalyco/opencode PR #23770. Example::
|
||||
Centralises the caps once hardcoded in ``terminal_tool`` (``max_bytes``) and
|
||||
``file_operations`` (``max_lines`` / ``max_line_length``). Defaults equal the
|
||||
old constants and the reader never raises, so behaviour is unchanged when the
|
||||
section is absent or malformed::
|
||||
|
||||
tool_output:
|
||||
max_bytes: 100000 # terminal output cap (chars)
|
||||
@@ -39,11 +38,8 @@ def _coerce_positive_int(value: Any, default: int) -> int:
|
||||
|
||||
|
||||
def get_tool_output_limits() -> Dict[str, int]:
|
||||
"""Return resolved limits ``{max_bytes, max_lines, max_line_length}``; never raises.
|
||||
|
||||
Cached for the process lifetime — ``_reset_tool_output_limits_cache()``
|
||||
forces a fresh read after config changes.
|
||||
"""
|
||||
"""Resolved ``{max_bytes, max_lines, max_line_length}``; never raises. Cached
|
||||
for the process — ``_reset_tool_output_limits_cache()`` forces a fresh read."""
|
||||
global _cached_limits
|
||||
if _cached_limits is not None:
|
||||
return _cached_limits
|
||||
@@ -55,13 +51,10 @@ def get_tool_output_limits() -> Dict[str, int]:
|
||||
section = {}
|
||||
except Exception:
|
||||
section = {}
|
||||
|
||||
_cached_limits = {
|
||||
"max_bytes": _coerce_positive_int(section.get("max_bytes"), DEFAULT_MAX_BYTES),
|
||||
"max_lines": _coerce_positive_int(section.get("max_lines"), DEFAULT_MAX_LINES),
|
||||
"max_line_length": _coerce_positive_int(
|
||||
section.get("max_line_length"), DEFAULT_MAX_LINE_LENGTH
|
||||
),
|
||||
"max_line_length": _coerce_positive_int(section.get("max_line_length"), DEFAULT_MAX_LINE_LENGTH),
|
||||
}
|
||||
return _cached_limits
|
||||
|
||||
|
||||
+56
-114
@@ -1,23 +1,14 @@
|
||||
"""Tool result persistence -- preserves large outputs instead of truncating.
|
||||
|
||||
Three layers of defense against context-window overflow:
|
||||
|
||||
1. **Per-tool output cap** (inside each tool, e.g. search_files pre-truncates).
|
||||
2. **Per-result persistence** (``maybe_persist_tool_result``): output over the
|
||||
tool's registered threshold is persisted and replaced in-context by a
|
||||
preview + file path. The canonical home is ALWAYS host-side,
|
||||
``$HERMES_HOME/cache/spillover/{tool_use_id}.txt``, so it works for sessions
|
||||
that never ran a terminal (MCP-only, cron, gateway). Local backend / no env:
|
||||
the model sees the host path. Remote backends (docker/ssh/modal/daytona):
|
||||
``cache/spillover`` is in the auto-mounted/synced cache-dir list
|
||||
(tools/credential_files.py), so the model sees the translated in-sandbox
|
||||
path — probed for readability first, falling back to a copy written into
|
||||
the sandbox temp dir (e.g. a persistent container created before spillover
|
||||
joined the mount list). The dir is pruned hourly by gateway housekeeping
|
||||
and once per process on first spill (CLI-only installs never run housekeeping).
|
||||
3. **Per-turn aggregate budget** (``enforce_turn_budget``): if all tool results
|
||||
in one turn exceed the turn budget, the largest non-persisted results are
|
||||
spilled until under budget.
|
||||
Three layers against context-window overflow: (1) per-tool output caps inside
|
||||
each tool; (2) ``maybe_persist_tool_result`` — output over the tool's threshold
|
||||
is persisted and replaced in-context by a preview + path. The canonical home is
|
||||
ALWAYS host-side ``$HERMES_HOME/cache/spillover/{tool_use_id}.txt`` (works for
|
||||
MCP-only/cron/gateway sessions that never ran a terminal); remote backends see
|
||||
the translated in-sandbox path (``cache/spillover`` is in the auto-mounted cache
|
||||
list), probed for readability, else a copy written into the sandbox temp dir.
|
||||
(3) ``enforce_turn_budget`` — spills the largest results of a turn until the
|
||||
aggregate fits.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
@@ -57,10 +48,7 @@ def get_spillover_dir():
|
||||
|
||||
def cleanup_spillover_cache(max_age_hours: int = SPILLOVER_MAX_AGE_HOURS) -> int:
|
||||
"""Delete spillover files older than *max_age_hours*; returns count removed.
|
||||
|
||||
Same contract as the ``cleanup_*_cache`` helpers in ``gateway.platforms.base``
|
||||
so the gateway housekeeping loop can prune this dir on the hourly cadence.
|
||||
"""
|
||||
Same contract as the ``cleanup_*_cache`` helpers the gateway housekeeping loop prunes hourly."""
|
||||
cutoff = time.time() - (max_age_hours * 3600)
|
||||
removed = 0
|
||||
try:
|
||||
@@ -93,11 +81,9 @@ def _prune_spillover_once() -> None:
|
||||
|
||||
|
||||
def _is_host_side_env(env) -> bool:
|
||||
"""True when this process should write the spill file directly.
|
||||
|
||||
``env=None`` (no sandbox yet) and the local backend qualify; remote backends
|
||||
resolve ``read_file`` inside the sandbox, so the spill must be written there.
|
||||
"""
|
||||
"""True when this process should write the spill file directly: ``env=None``
|
||||
(no sandbox yet) or the local backend. Remote backends resolve ``read_file``
|
||||
inside the sandbox, so the spill must be written there."""
|
||||
if env is None:
|
||||
return True
|
||||
try:
|
||||
@@ -123,13 +109,10 @@ def _write_to_spillover(content: str, filename: str):
|
||||
|
||||
|
||||
def _sandbox_visible_spillover_path(host_path: str, env) -> str | None:
|
||||
"""Return the path where a remote backend can read *host_path*, or None.
|
||||
|
||||
Translates via the same helper the image tools use, forces a sync for synced
|
||||
backends, then PROBES readability — a persistent docker container created
|
||||
before spillover joined the mount list lacks the bind mount and must fall
|
||||
back to the in-sandbox write.
|
||||
"""
|
||||
"""Path where a remote backend can read *host_path*, or None. Translates via
|
||||
the image tools' helper, forces a sync for synced backends, then PROBES
|
||||
readability — a persistent container created before spillover joined the
|
||||
mount list lacks the bind mount and must fall back to the in-sandbox write."""
|
||||
try:
|
||||
from tools.credential_files import to_agent_visible_cache_path
|
||||
|
||||
@@ -137,14 +120,12 @@ def _sandbox_visible_spillover_path(host_path: str, env) -> str | None:
|
||||
except Exception as exc:
|
||||
logger.debug("Spillover path translation failed: %s", exc)
|
||||
return None
|
||||
|
||||
sync_manager = getattr(env, "_sync_manager", None)
|
||||
if sync_manager is not None:
|
||||
try:
|
||||
sync_manager.sync(force=True)
|
||||
except Exception as exc:
|
||||
logger.debug("Spillover sync failed: %s", exc)
|
||||
|
||||
try:
|
||||
result = env.execute(f"test -r {shlex.quote(visible)}", timeout=15)
|
||||
if result.get("returncode", 1) == 0:
|
||||
@@ -156,17 +137,15 @@ def _sandbox_visible_spillover_path(host_path: str, env) -> str | None:
|
||||
|
||||
def _resolve_storage_dir(env) -> str:
|
||||
"""Return the best temp-backed storage dir for this environment."""
|
||||
if env is not None:
|
||||
get_temp_dir = getattr(env, "get_temp_dir", None)
|
||||
if callable(get_temp_dir):
|
||||
try:
|
||||
temp_dir = get_temp_dir()
|
||||
except Exception as exc:
|
||||
logger.debug("Could not resolve env temp dir: %s", exc)
|
||||
else:
|
||||
if temp_dir:
|
||||
temp_dir = temp_dir.rstrip("/") or "/"
|
||||
return f"{temp_dir}/hermes-results"
|
||||
get_temp_dir = getattr(env, "get_temp_dir", None)
|
||||
if callable(get_temp_dir):
|
||||
try:
|
||||
temp_dir = get_temp_dir()
|
||||
except Exception as exc:
|
||||
logger.debug("Could not resolve env temp dir: %s", exc)
|
||||
else:
|
||||
if temp_dir:
|
||||
return f"{temp_dir.rstrip('/') or '/'}/hermes-results"
|
||||
return STORAGE_DIR
|
||||
|
||||
|
||||
@@ -175,16 +154,13 @@ def _safe_result_filename(tool_use_id: str) -> str:
|
||||
raw_id = str(tool_use_id or "tool_result")
|
||||
safe_stem = _UNSAFE_RESULT_FILENAME_CHARS.sub("_", raw_id).strip("._-")
|
||||
changed = safe_stem != raw_id
|
||||
|
||||
if not safe_stem:
|
||||
safe_stem = "tool_result"
|
||||
changed = True
|
||||
|
||||
if changed or len(safe_stem) > _MAX_RESULT_FILENAME_STEM:
|
||||
digest = hashlib.sha256(raw_id.encode("utf-8")).hexdigest()[:12]
|
||||
safe_stem = safe_stem[:_MAX_RESULT_FILENAME_STEM].rstrip("._-") or "tool_result"
|
||||
safe_stem = f"{safe_stem}_{digest}"
|
||||
|
||||
return f"{safe_stem}.txt"
|
||||
|
||||
|
||||
@@ -201,11 +177,9 @@ def generate_preview(content: str, max_chars: int = DEFAULT_PREVIEW_SIZE_CHARS)
|
||||
|
||||
def _write_to_sandbox(content: str, remote_path: str, env) -> bool:
|
||||
"""Write content into the sandbox via env.execute(). Returns True on success.
|
||||
|
||||
Content goes through stdin, not the command string: Linux ``MAX_ARG_STRLEN``
|
||||
caps a single argv element at 128 KB, so a heredoc-in-command silently failed
|
||||
for exactly the oversized results persistence exists to handle.
|
||||
"""
|
||||
caps one argv element at 128 KB, so a heredoc-in-command silently failed
|
||||
for exactly the oversized results persistence exists to handle."""
|
||||
storage_dir = os.path.dirname(remote_path)
|
||||
cmd = f"mkdir -p {shlex.quote(storage_dir)} && cat > {shlex.quote(remote_path)}"
|
||||
result = env.execute(cmd, timeout=30, stdin_data=content)
|
||||
@@ -221,33 +195,27 @@ def _build_persisted_message(
|
||||
"""Build the <persisted-output> replacement block."""
|
||||
size_kb = original_size / 1024
|
||||
size_str = f"{size_kb / 1024:.1f} MB" if size_kb >= 1024 else f"{size_kb:.1f} KB"
|
||||
|
||||
msg = f"{PERSISTED_OUTPUT_TAG}\n"
|
||||
msg += f"This tool result was too large ({original_size:,} characters, {size_str}).\n"
|
||||
msg += f"Full output saved to: {file_path}\n"
|
||||
msg += "Use the read_file tool with offset and limit to access specific sections of this output.\n"
|
||||
msg += (
|
||||
return (
|
||||
f"{PERSISTED_OUTPUT_TAG}\n"
|
||||
f"This tool result was too large ({original_size:,} characters, {size_str}).\n"
|
||||
f"Full output saved to: {file_path}\n"
|
||||
"Use the read_file tool with offset and limit to access specific sections of this output.\n"
|
||||
"Recovery: page through the saved file with read_file (offset/limit) or "
|
||||
"process it with execute_code — do NOT re-request the same data from the "
|
||||
"remote API; the full result is already on disk.\n\n"
|
||||
f"Preview (first {len(preview)} chars):\n"
|
||||
+ preview + ("\n..." if has_more else "")
|
||||
+ f"\n{PERSISTED_OUTPUT_CLOSING_TAG}"
|
||||
)
|
||||
msg += f"Preview (first {len(preview)} chars):\n"
|
||||
msg += preview
|
||||
if has_more:
|
||||
msg += "\n..."
|
||||
msg += f"\n{PERSISTED_OUTPUT_CLOSING_TAG}"
|
||||
return msg
|
||||
|
||||
|
||||
_PERSISTED_PATH_RE = re.compile(r"^Full output saved to: (.+)$", re.MULTILINE)
|
||||
|
||||
|
||||
def extract_persisted_path(content: str) -> str | None:
|
||||
"""Return the file path from a <persisted-output> block, or None.
|
||||
|
||||
Lets the result-reference stubbing guard (agent/tool_guardrails.py) carry
|
||||
the spillover path in a stub instead of leaving it dangling.
|
||||
"""
|
||||
"""Return the file path from a <persisted-output> block, or None. Lets the
|
||||
result-reference stubbing guard (agent/tool_guardrails.py) carry the
|
||||
spillover path in a stub instead of leaving it dangling."""
|
||||
if not isinstance(content, str) or PERSISTED_OUTPUT_TAG not in content:
|
||||
return None
|
||||
match = _PERSISTED_PATH_RE.search(content)
|
||||
@@ -263,16 +231,10 @@ def maybe_persist_tool_result(
|
||||
threshold: int | float | None = None,
|
||||
) -> str:
|
||||
"""Layer 2: persist an oversized result, return preview + path.
|
||||
|
||||
``threshold`` overrides ``config.resolve_threshold(tool_name)``. Falls back
|
||||
to inline truncation when no write location succeeds.
|
||||
"""
|
||||
to inline truncation when no write location succeeds."""
|
||||
effective_threshold = threshold if threshold is not None else config.resolve_threshold(tool_name)
|
||||
|
||||
if effective_threshold == float("inf"):
|
||||
return content
|
||||
|
||||
if len(content) <= effective_threshold:
|
||||
if effective_threshold == float("inf") or len(content) <= effective_threshold:
|
||||
return content
|
||||
|
||||
filename = _safe_result_filename(tool_use_id)
|
||||
@@ -285,22 +247,19 @@ def maybe_persist_tool_result(
|
||||
)
|
||||
return _build_persisted_message(preview, has_more, len(content), path)
|
||||
|
||||
# Always persist host-side first: cache/spillover is the single canonical
|
||||
# home for spilled results regardless of backend.
|
||||
# Always persist host-side first: cache/spillover is the single canonical home.
|
||||
host_path = _write_to_spillover(content, filename)
|
||||
|
||||
if _is_host_side_env(env):
|
||||
if host_path is not None:
|
||||
return _persisted(host_path)
|
||||
elif env is not None:
|
||||
# Remote backend: reference the mounted/synced path when the sandbox
|
||||
# can actually read it ...
|
||||
else:
|
||||
# Remote backend: reference the mounted/synced path when the sandbox can
|
||||
# actually read it, else write into the sandbox temp dir (pre-existing
|
||||
# containers without the spillover mount, translation/probe failures).
|
||||
if host_path is not None:
|
||||
visible = _sandbox_visible_spillover_path(host_path, env)
|
||||
if visible is not None:
|
||||
return _persisted(visible, f" [host: {host_path}]")
|
||||
# ... else write into the sandbox temp dir (pre-existing containers
|
||||
# without the spillover mount, translation/probe failures).
|
||||
remote_path = f"{_resolve_storage_dir(env)}/{filename}"
|
||||
try:
|
||||
if _write_to_sandbox(content, remote_path, env):
|
||||
@@ -324,47 +283,30 @@ def enforce_turn_budget(
|
||||
env=None,
|
||||
config: BudgetConfig = DEFAULT_BUDGET,
|
||||
) -> list[dict]:
|
||||
"""Layer 3: enforce the aggregate budget across all tool results in a turn.
|
||||
|
||||
Persists the largest non-persisted results first until under budget.
|
||||
Mutates the list in-place and returns it.
|
||||
"""
|
||||
"""Layer 3: persist the largest non-persisted results first until the turn's
|
||||
aggregate is under budget. Mutates the list in-place and returns it."""
|
||||
candidates = []
|
||||
total_size = 0
|
||||
for i, msg in enumerate(tool_messages):
|
||||
content = msg.get("content", "")
|
||||
size = len(content)
|
||||
size = len(msg.get("content", ""))
|
||||
total_size += size
|
||||
if PERSISTED_OUTPUT_TAG not in content:
|
||||
if PERSISTED_OUTPUT_TAG not in msg.get("content", ""):
|
||||
candidates.append((i, size))
|
||||
|
||||
if total_size <= config.turn_budget:
|
||||
return tool_messages
|
||||
|
||||
candidates.sort(key=lambda x: x[1], reverse=True)
|
||||
|
||||
for idx, size in candidates:
|
||||
if total_size <= config.turn_budget:
|
||||
break
|
||||
msg = tool_messages[idx]
|
||||
content = msg["content"]
|
||||
tool_use_id = msg.get("tool_call_id", f"budget_{idx}")
|
||||
|
||||
content = tool_messages[idx]["content"]
|
||||
tool_use_id = tool_messages[idx].get("tool_call_id", f"budget_{idx}")
|
||||
replacement = maybe_persist_tool_result(
|
||||
content=content,
|
||||
tool_name=_BUDGET_TOOL_NAME,
|
||||
tool_use_id=tool_use_id,
|
||||
env=env,
|
||||
config=config,
|
||||
threshold=0,
|
||||
content=content, tool_name=_BUDGET_TOOL_NAME, tool_use_id=tool_use_id,
|
||||
env=env, config=config, threshold=0,
|
||||
)
|
||||
if replacement != content:
|
||||
total_size -= size
|
||||
total_size += len(replacement)
|
||||
total_size += len(replacement) - size
|
||||
tool_messages[idx]["content"] = replacement
|
||||
logger.info(
|
||||
"Budget enforcement: persisted tool result %s (%d chars)",
|
||||
tool_use_id, size,
|
||||
)
|
||||
|
||||
logger.info("Budget enforcement: persisted tool result %s (%d chars)", tool_use_id, size)
|
||||
return tool_messages
|
||||
|
||||
Reference in New Issue
Block a user