Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
13 changes: 6 additions & 7 deletions libs/code/deepagents_code/_cli_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ class CLIContextSchema:

model_context_limit: int | None = None

approval_mode: str = "manual"

auto_approve: bool = False

approval_mode_key: str | None = None
Expand Down Expand Up @@ -73,14 +75,11 @@ class CLIContext(TypedDict, total=False):
model_context_limit: int | None
"""Effective context-window limit for profile-aware middleware."""

auto_approve: bool
"""Whether gated tool calls should skip the human-approval interrupt.
approval_mode: str
"""`manual`, classifier-backed `auto`, or unrestricted `yolo`."""

Sourced from the client session (not graph state) so the model cannot
self-approve by writing state. The `interrupt_on` `when` predicate reads
this to suppress interrupts at the source when "approve always" is on,
avoiding the interrupt-then-auto-resolve round-trip.
"""
auto_approve: bool
"""Compatibility snapshot for clients predating the typed mode field."""

approval_mode_key: str | None
"""Store key for the live approval-mode control record.
Expand Down
253 changes: 181 additions & 72 deletions libs/code/deepagents_code/agent.py

Large diffs are not rendered by default.

311 changes: 232 additions & 79 deletions libs/code/deepagents_code/app.py

Large diffs are not rendered by default.

181 changes: 154 additions & 27 deletions libs/code/deepagents_code/approval_mode.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,54 @@
"""Live approval-mode state shared through the LangGraph Store."""
"""Approval-mode state shared by the Textual client and agent server."""

from __future__ import annotations

import contextlib
import json
import logging
import os
import tempfile
from collections.abc import Mapping
from enum import StrEnum
from hashlib import sha256
from pathlib import Path
from typing import TypedDict

logger = logging.getLogger(__name__)

APPROVAL_MODE_NAMESPACE: tuple[str, str] = ("deepagents_code", "approval_mode")
"""Store namespace for per-thread approval-mode control records."""

YOLO_ACKNOWLEDGEMENT_POLICY_VERSION = "2026-07-14"
"""Version of the unrestricted-mode warning that must be acknowledged."""


class ApprovalMode(StrEnum):
"""Tool-approval policy selected for an interactive thread."""

MANUAL = "manual"
AUTO = "auto"
YOLO = "yolo"


class ApprovalModePayload(TypedDict):
"""Stored approval-mode control payload."""

auto_approve: bool
mode: str


def coerce_approval_mode(value: object) -> ApprovalMode:
"""Return a validated mode, failing closed to `manual`.

Args:
value: Untrusted mode value from config, context, or storage.

Returns:
A validated `ApprovalMode`; invalid values become `ApprovalMode.MANUAL`.
"""
try:
return ApprovalMode(value) if isinstance(value, str) else ApprovalMode.MANUAL
except ValueError:
return ApprovalMode.MANUAL


def approval_mode_key(thread_id: str) -> str:
Expand All @@ -31,41 +63,64 @@ def approval_mode_key(thread_id: str) -> str:
return sha256(thread_id.encode("utf-8")).hexdigest()


def approval_mode_payload(*, auto_approve: bool) -> ApprovalModePayload:
def approval_mode_payload(
*,
mode: ApprovalMode | str | None = None,
auto_approve: bool | None = None,
) -> ApprovalModePayload:
"""Return the stored approval-mode payload.

Args:
auto_approve: Whether gated tool calls should skip HITL approval.
mode: Explicit approval mode.
auto_approve: Compatibility input for callers using the previous Boolean
API. `True` maps to unrestricted `yolo`, and `False` maps to `manual`.

Returns:
JSON-serializable store value.

Raises:
ValueError: If neither or both inputs are supplied, or `mode` is invalid.
"""
return {"auto_approve": auto_approve}
if (mode is None) == (auto_approve is None):
msg = "Provide exactly one of mode or auto_approve"
raise ValueError(msg)
if auto_approve is not None:
resolved = ApprovalMode.YOLO if auto_approve else ApprovalMode.MANUAL
else:
try:
resolved = ApprovalMode(mode)
except (TypeError, ValueError) as exc:
msg = f"Invalid approval mode: {mode!r}"
raise ValueError(msg) from exc
return {"mode": resolved.value}


def _item_value(item: object) -> object:
"""Extract a store item's value from SDK and runtime item shapes.
"""Extract a store item's value.

Args:
item: SDK or runtime store-item shape.

Returns:
The item's stored value, or `None` when the shape is unrecognized.
The stored value, or `None` when the shape is unrecognized.
"""
if isinstance(item, Mapping):
return item.get("value")
return getattr(item, "value", None)


def read_approval_mode_from_store(store: object, key: str | None) -> bool | None:
def read_approval_mode_from_store(
store: object, key: str | None
) -> ApprovalMode | None:
"""Read a live approval mode from the server-side LangGraph Store.

Args:
store: `request.runtime.store` from the graph server.
key: Store key produced by `approval_mode_key`. The `isinstance` guard
below still rejects non-string keys as defense-in-depth, since the
value crosses the JSON/RemoteGraph boundary before reaching here.
key: Store key produced by `approval_mode_key`.

Returns:
`True` or `False` when the store contains a valid mode, otherwise
`None`. Callers should treat `None` as fail-closed.
A validated mode, or `None` when the record cannot be trusted. Callers
must interpret `None` as `manual`.
"""
if store is None:
logger.debug("Approval-mode store is unavailable")
Expand All @@ -89,34 +144,34 @@ def read_approval_mode_from_store(store: object, key: str | None) -> bool | None
return None

value = _item_value(item)
auto_approve = value.get("auto_approve") if isinstance(value, Mapping) else None
if isinstance(auto_approve, bool):
return auto_approve

logger.debug("Approval-mode store item has invalid contents")
raw_mode = value.get("mode") if isinstance(value, Mapping) else None
if isinstance(raw_mode, str):
try:
return ApprovalMode(raw_mode)
except ValueError:
pass

logger.warning("Approval-mode store item has invalid contents")
return None


async def awrite_approval_mode(
agent: object,
thread_id: str,
*,
auto_approve: bool,
mode: ApprovalMode | str | None = None,
auto_approve: bool | None = None,
) -> str | None:
"""Persist approval mode through an agent's remote store client.

Args:
agent: Agent object. Remote agents expose `aput_store_item`; agents
without a writer use run context only.
agent: Agent object. Remote agents expose `aput_store_item`.
thread_id: LangGraph thread id for the active session.
auto_approve: Whether gated tool calls should skip HITL approval.
mode: Explicit approval mode.
auto_approve: Compatibility input for the previous Boolean API.

Returns:
Store key written, or `None` when the agent has no store writer.

Notes:
Remote agents rely on the server-side store being visible to the
running graph before the next gated tool predicate executes.
"""
put = getattr(agent, "aput_store_item", None)
if put is None:
Expand All @@ -126,6 +181,78 @@ async def awrite_approval_mode(
await put(
APPROVAL_MODE_NAMESPACE,
key,
approval_mode_payload(auto_approve=auto_approve),
approval_mode_payload(mode=mode, auto_approve=auto_approve),
)
return key


def yolo_acknowledgement_path() -> Path:
"""Return the installation-local acknowledgement file path.

Returns:
Path under the private dcode state directory.
"""
from deepagents_code.model_config import DEFAULT_STATE_DIR

return DEFAULT_STATE_DIR / "approval.json"


def has_yolo_acknowledgement(path: Path | None = None) -> bool:
"""Return whether the current unrestricted-mode warning was accepted.

Args:
path: Alternate acknowledgement path for tests.

Returns:
`True` only for a valid record matching the current policy version.
"""
target = path or yolo_acknowledgement_path()
try:
data = json.loads(target.read_text(encoding="utf-8"))
except (FileNotFoundError, OSError, UnicodeDecodeError, json.JSONDecodeError):
return False
return (
isinstance(data, dict)
and data.get("version") == 1
and data.get("policy_version") == YOLO_ACKNOWLEDGEMENT_POLICY_VERSION
and data.get("acknowledged") is True
)


def save_yolo_acknowledgement(path: Path | None = None) -> bool:
"""Persist the current unrestricted-mode warning acknowledgement.

Args:
path: Alternate acknowledgement path for tests.

Returns:
`True` when the private atomic write succeeds, otherwise `False`.
"""
target = path or yolo_acknowledgement_path()
payload = {
"version": 1,
"policy_version": YOLO_ACKNOWLEDGEMENT_POLICY_VERSION,
"acknowledged": True,
}
tmp_path: Path | None = None
try:
target.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
if os.name != "nt":
target.parent.chmod(0o700)
fd, raw_tmp_path = tempfile.mkstemp(dir=target.parent, suffix=".tmp")
tmp_path = Path(raw_tmp_path)
with os.fdopen(fd, "w", encoding="utf-8") as handle:
json.dump(payload, handle, separators=(",", ":"))
handle.write("\n")
if os.name != "nt":
tmp_path.chmod(0o600)
tmp_path.replace(target)
if os.name != "nt":
target.chmod(0o600)
except OSError:
logger.warning("Could not persist YOLO acknowledgement", exc_info=True)
if tmp_path is not None:
with contextlib.suppress(OSError):
tmp_path.unlink()
return False
return True
Loading
Loading