Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
2 changes: 1 addition & 1 deletion libs/code/COMMANDS.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ aliases, descriptions, visibility, or hidden-command metadata.
| --- | --- | --- |
| `/agents` | | Browse and switch between available agents |
| `/auth` | `/connect` | Connect and manage provider and service credentials |
| `/auto` | | Switch to Auto approval mode |
| `/auto` | | Switch to Auto approval mode, or pick its classifier model for this session |
| `/auto-update` | | Turn automatic updates on or off |
| `/changelog` | | Open the changelog in a browser |
| `/clear` | | Clear the chat and start a new thread |
Expand Down
12 changes: 10 additions & 2 deletions libs/code/THREAT_MODEL.md
Original file line number Diff line number Diff line change
Expand Up @@ -349,6 +349,7 @@
| T10 | DF24 | DC1 | MCP stdio subprocess env dict accepts arbitrary keys including `PATH`, `LD_PRELOAD`, `PYTHONPATH` without filtering | TB4 | Low | Verified | `mcp_tools._validate_server_config`, `mcp_tools._load_tools_from_config` |
| T12 | DF10 | — | Project `.env` sets shell startup-hook variables (`BASH_ENV`, `ENV`) that run attacker-controlled scripts when `dcode` spawns Bash, before any HITL approval | TB11 | High | Verified | `config._load_dotenv`, `local_context.build_detect_script` |
| T13 | DF7 | — | Configured shell allow-list checks only the first token, so an allow-listed interpreter/wrapper (`python3`, `bash`, `env`, `xargs`, …) runs arbitrary code via its arguments without approval in non-interactive mode | TB2 | Medium | Verified | `config.is_shell_command_allowed`, `config.contains_dangerous_patterns` |
| T14 | DF7, DF9 | — | A weaker model configured for the Auto approval classifier reviews gated actions less reliably, including untrusted text carried in tool arguments and file content | TB2 | Low | Verified | `auto_mode.AutoModeHITLMiddleware._classifier_model`, `config.resolve_auto_classifier_model` |

### Threat Details

Expand Down Expand Up @@ -431,17 +432,23 @@
- **Description**: `is_shell_command_allowed` splits a command on `|`, `;`, `&&`, and `||`, then validates only the *first token* (`tokens[0]`) of each segment against the configured allow-list, after rejecting a set of dangerous patterns (`contains_dangerous_patterns`: command substitution `$(`/backticks, redirects, `${`, bare `$VAR`, background `&`). Because only the executable name is checked, any allow-listed general-purpose interpreter or command wrapper carries arbitrary behavior in its arguments: `python3 -c '<code>'`, `bash script.sh`, `sh -c '<code>'`, `env <cmd>`, `xargs <cmd>`, `uv run <cmd>`, and similar. A user who allow-lists such a program — reasonably believing they have restricted the agent to a "safe" tool — has effectively allowed unrestricted execution, and in headless `-x`/Auto mode those commands run without an approval prompt. This is the same class of weakness as T2 but applies to *normal, non-`all`* allow-lists. The allow-list is an ergonomic auto-approve heuristic, not a security boundary; textual command classification cannot robustly constrain execution.
- **Preconditions**: (1) User configures a shell allow-list (`--shell-allow-list` / `DEEPAGENTS_SHELL_ALLOW_LIST`) that includes an interpreter or wrapper; (2) non-interactive or Auto mode (interactive Manual mode still shows the human the literal command before it runs); (3) for the injected-command variant, successful prompt injection via DF8/DF9. The intended control is HITL approval; OS-native execution sandboxing would be the robust boundary the string allow-list cannot provide.

#### T14: Weaker Auto Classifier Model Weakens Action Review

- **Flow**: DF7 (LLM tool call) → Auto classifier review → C4 Tools
- **Description**: In Auto approval mode, gated tool calls that deterministic policy cannot clear are reviewed by an LLM authorization classifier. That classifier can be pointed at a separate model (`--auto-classifier-model`, `DEEPAGENTS_CODE_AUTO_CLASSIFIER_MODEL`, `[models].auto_classifier`, or `/auto model`) so reviews are cheaper and faster than the main agent model. Review quality then follows the chosen model: a weaker one is likelier to mis-authorize an action, and likelier to be steered by injected instructions in the untrusted material it reads (tool arguments, paths, prior tool output, remote metadata). Choosing the classifier is a user-level decision, so it is restricted to trusted surfaces: shell exports, the global `~/.deepagents/.env`, `~/.deepagents/config.toml`, the CLI flag, and `/auto model`. A *project* `.env` travels with a cloned repo, so `DEEPAGENTS_CODE_AUTO_CLASSIFIER_MODEL` is listed in `config._PROJECT_DOTENV_DENIED_ENV_KEYS` — the same mitigation TB4 applies to the project-MCP trust vars; without that entry a checked-in `.env` could silently downgrade the review on `dcode` startup. With it, this is a self-inflicted weakening of a control rather than an external attack path. Auto's model-independent guards are unchanged by the setting: deterministic allow/deny, the consecutive/total denial counters, batch-replay detection, control-state availability, and the human-fallback thresholds. A classifier model that cannot be constructed (bad spec, missing credentials, uninstalled provider package) never falls back to the main model — the first such batch is marked `classifier_unavailable`, so those calls are denied and do not execute, and the failing spec is latched so every subsequent batch escalates straight to human approval until a review succeeds. A transient failure instead escalates once `_CONSECUTIVE_UNAVAILABLE_FALLBACK` consecutive batches have failed, or immediately when Auto's control state cannot be persisted.
- **Preconditions**: (1) Auto approval mode is active (interactive TUI only, and not under a sandbox); (2) a classifier model is configured through one of the trusted surfaces above — the default reuses the main agent model; (3) for the injected-review variant, untrusted content reaches the classifier through DF8/DF9 and the chosen model follows it. The intended control is that the human remains the fallback for anything the classifier does not affirmatively allow.

---

## Input Source Coverage

| Input Source | Data Flows | Threats | Validation Points | Responsibility | Gaps |
|-----------------------|-----------------------|---------------|----------------------------------------------------------------------------|----------------|----------------------------------------------------------------------------------------------|
| User direct input | DF1, DF2 | None (TB1) | None — prompts accepted verbatim | User | No content filtering — intentional; HITL gates downstream tool calls |
| LLM output | DF6, DF7 | T1, T2, T3, T4, T13| HITL gate; shell allow-list; Unicode/URL warnings on tool args | Project | LLM-generated tool args not scanned for injection beyond Unicode/URL; shell allow-list matches only the command's first token, so allow-listed interpreters/wrappers bypass it (T13) |
| LLM output | DF6, DF7 | T1, T2, T3, T4, T13, T14| HITL gate; shell allow-list; Unicode/URL warnings on tool args; Auto classifier review | Project | LLM-generated tool args not scanned for injection beyond Unicode/URL; shell allow-list matches only the command's first token, so allow-listed interpreters/wrappers bypass it (T13); Auto classifier review quality follows the user-selected classifier model, and the classifier reads untrusted tool arguments and prior output (T14) |
| Tool/function results | DF9, DF11 | T1 | Unicode warning on URL args; `markdownify` HTML conversion | Shared | Tool *results* pass to context without prompt-injection scan |
| URL-fetched content | DF8, DF9 | T1 | `check_url_safety` on URL arg; HTML→markdown conversion | Shared | Markup-embedded instructions survive markdownify; no LLM-layer guardrail |
| Configuration | DF10, DF12, DF15, DF23| T9, T10, T12 | Dotenv shell-env precedence; TOML schema; MCP schema + allow/deny lists; JSON structure check; `class_path` format check | User | Project `.env` can set shell startup-hook vars; `class_path` executes module code before type check; MCP env dict unfiltered |
| Configuration | DF10, DF12, DF15, DF23| T9, T10, T12, T14 | Dotenv shell-env precedence; TOML schema; MCP schema + allow/deny lists; JSON structure check; `class_path` format check; project-`.env` denylist for the Auto classifier model | User | Project `.env` can set shell startup-hook vars; `class_path` executes module code before type check; MCP env dict unfiltered; Auto classifier strength is a user choice with no floor enforced (T14) |
| Session restore | DF14 | T5 | OS file permissions; SQLite | Project | Unencrypted at rest |
| Server IPC (env vars) | DF18 | T6 | `ServerConfig` serialization; parent env passed to child | Project | Provider API keys flow to server subprocess; system prompt in env |
| Host environment | DF19, DF20 | T7 | Static script; exit code check; 30s timeout | Shared | Makefile content injected into system prompt without sanitization |
Expand Down Expand Up @@ -505,3 +512,4 @@ Threats that appear valid in isolation but fall outside project responsibility b
| 2026-07-22 | manual update | Added T13 (first-token shell allow-list bypass via allow-listed interpreters/wrappers) under TB2, distinguishing it from T2's `--shell-allow-list all` sentinel; cross-referenced it from T2 and extended the "LLM output" input-coverage gap to note that allow-list matching only inspects the command's first token |
| 2026-07-24 | manual update | Corrected the out-of-scope hooks row: Hooks v2 defaults are 600s (30s for `UserPromptSubmit`), not a global 5-second timeout; loading is `hooks.loading.load_hooks_config`; project hooks require workspace trust or `--trust-project-hooks` |
| 2026-07-28 | manual update | Extended the out-of-scope hooks row for plugin-contributed hooks: enabled plugins may supply `hooks/hooks.json`, gated by install plus enablement rather than workspace trust, with each handler's environment overlaid only by its own plugin path variables |
| 2026-08-03 | manual update | Added T14 (a weaker Auto classifier model weakens action review) under TB2, covering the selectable classifier (`--auto-classifier-model`, `DEEPAGENTS_CODE_AUTO_CLASSIFIER_MODEL`, `[models].auto_classifier`, `/auto model`), its restriction to trusted config surfaces via `config._PROJECT_DOTENV_DENIED_ENV_KEYS`, and its fail-closed construction behavior (deny, then latch to human approval; never fall back to the main model). Extended the "LLM output" and "Configuration" input-coverage rows with T14 |
32 changes: 32 additions & 0 deletions libs/code/deepagents_code/_cli_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,25 @@
from dataclasses import dataclass, field
from typing import Any, TypedDict

INHERIT_CLASSIFIER_MODEL = "__dcode_inherit_classifier__"
"""Per-run `classifier_model` value meaning "review with the main agent model".

An absent (or `None`) `classifier_model` only says the run carries no
preference, so the classifier keeps whatever the server resolved at startup
(`--auto-classifier-model`, `DEEPAGENTS_CODE_AUTO_CLASSIFIER_MODEL`,
`[models].auto_classifier`). `/auto model clear` needs the stronger statement
that reviews go back to the main agent model, which this sentinel carries.

It cannot collide with a real spec: `create_model` resolves `provider:model`
(or a bare model name) and has no provider or model named `__dcode_...`. A
control character such as a leading NUL would also be collision-proof, but this
value has to survive the trip to a remote deployment intact — the context is
serialized to JSON and may be persisted, and Postgres `text`/`jsonb` rejects NUL
outright. A stripped sentinel would silently read as "no preference" and leave a
startup classifier authorizing actions after the UI reported the clear, so the
sentinel stays plain ASCII.
"""


@dataclass
class CLIContextSchema:
Expand Down Expand Up @@ -39,6 +58,8 @@ class CLIContextSchema:

model_context_limit: int | None = None

classifier_model: str | None = None

approval_mode: str = "manual"

auto_approve: bool = False
Expand Down Expand Up @@ -81,6 +102,17 @@ class CLIContext(TypedDict, total=False):
model_context_limit: int | None
"""Effective context-window limit for profile-aware middleware."""

classifier_model: str | None
"""Model spec the Auto approval classifier should use for this run.

`None` (or absent) expresses no per-run preference, so the classifier keeps
whatever the graph was built with — normally the main agent model, but a
separate model when the session was launched with one.
`INHERIT_CLASSIFIER_MODEL` overrides that startup value back to the main
agent model. Set by `/auto model` so the switch takes effect without
restarting the agent server.
"""

approval_mode: str
"""`manual`, classifier-backed `auto`, or unrestricted `yolo`."""

Expand Down
19 changes: 19 additions & 0 deletions libs/code/deepagents_code/_env_vars.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,25 @@
# Keep alphabetically sorted by constant name.
# ---------------------------------------------------------------------------

AUTO_CLASSIFIER_MODEL = "DEEPAGENTS_CODE_AUTO_CLASSIFIER_MODEL"
"""Model spec (`provider:model`) used by the Auto approval-mode classifier.

Unset (the default) reuses the main agent model, preserving the historical
behavior. A `provider:model` value points the authorization classifier at a
separate — typically faster and cheaper — model without changing the model that
writes code. The classifier is a security control: a model that cannot be
resolved (bad spec, missing credentials, uninstalled provider package) never
falls back to the main model — reviewed actions are denied, and repeated
failures escalate to your approval. Also settable via `[models].auto_classifier`
in config.toml and `--auto-classifier-model`.

This is user-controlled process env, not a repo file: a committed *project*
`.env` cannot set it (see `config._PROJECT_DOTENV_DENIED_ENV_KEYS`), so a cloned
repository cannot point the review that authorizes its own tool calls at a weaker
model. Only the shell, the launch environment, or the global `~/.deepagents/.env`
can.
"""

AUTO_UPDATE = "DEEPAGENTS_CODE_AUTO_UPDATE"
"""Toggle automatic app updates. Enabled by default; set to a falsy value
('0', 'false', 'no', 'off', or empty) to opt out."""
Expand Down
26 changes: 26 additions & 0 deletions libs/code/deepagents_code/_markdown.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
"""Escaping for external text that reaches Rich/Textual markdown source."""

from __future__ import annotations

MARKDOWN_ESCAPES = str.maketrans({char: f"\\{char}" for char in "\\&`*_[]<>|~"})
"""Translation table backing `escape_markdown`.

Covers the inline constructs Rich's markdown parser acts on (emphasis, code
spans, links, autolinks/HTML, HTML entities, strikethrough) plus the `|`
table-cell separator. Block-level punctuation (`#`, `-`, `>`) only has meaning
at the start of a line; line breaks are normalized before translation, and `>`
is escaped anyway because it is cheap.
"""


def escape_markdown(text: str) -> str:
"""Normalize line breaks and escape markdown syntax in external text.

Args:
text: Display string that may contain markdown punctuation.

Returns:
`text` on one line with markdown-significant characters escaped.
"""
normalized = text.replace("\r\n", " ").replace("\r", " ").replace("\n", " ")
return normalized.translate(MARKDOWN_ESCAPES)
14 changes: 14 additions & 0 deletions libs/code/deepagents_code/_server_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,14 @@ class ServerConfig:
rubric_max_iterations: int | None = None
"""Explicit grader iterations per rubric attempt; `None` uses the SDK default."""

auto_classifier_model: str | None = None
"""Classifier model spec for Auto mode (e.g. `'anthropic:claude-haiku-4-5'`).

`None` falls through to `DEEPAGENTS_CODE_AUTO_CLASSIFIER_MODEL`, then
`[models].auto_classifier`, and then to the main agent model. An empty value
round-trips to `None`, so it means "inherit", never "empty spec".
"""

recursion_limit: int | None = None
"""Explicit main-agent LangGraph `recursion_limit` (graph step budget).

Expand Down Expand Up @@ -477,6 +485,7 @@ def to_env(self) -> dict[str, str | None]:
else None
),
"RUBRIC_MODEL": self.rubric_model,
"AUTO_CLASSIFIER_MODEL": self.auto_classifier_model,
"RUBRIC_MAX_ITERATIONS": (
str(self.rubric_max_iterations)
if self.rubric_max_iterations is not None
Expand Down Expand Up @@ -536,6 +545,7 @@ def from_env(cls) -> ServerConfig:
),
allow_fs_tools=_read_env_allow_fs_tools(),
rubric_model=_read_env_str("RUBRIC_MODEL") or None,
auto_classifier_model=_read_env_str("AUTO_CLASSIFIER_MODEL") or None,
rubric_max_iterations=_read_env_int("RUBRIC_MAX_ITERATIONS", default=None),
recursion_limit=_read_env_int("RECURSION_LIMIT", default=None),
sandbox_type=_read_env_str("SANDBOX_TYPE"),
Expand Down Expand Up @@ -577,6 +587,7 @@ def from_cli_args(
allow_fs_tools: list[FsToolName] | None = None,
rubric_model: str | None = None,
rubric_max_iterations: int | None = None,
auto_classifier_model: str | None = None,
recursion_limit: int | None = None,
mcp_config_path: str | None,
no_mcp: bool,
Expand Down Expand Up @@ -618,6 +629,8 @@ def from_cli_args(
rubric_model: Grader model spec; `None` reuses the main model.
rubric_max_iterations: Explicit grader iterations per rubric attempt;
`None` uses the SDK default.
auto_classifier_model: Auto classifier model spec; `None` resolves from
env / `config.toml` and then reuses the main model.
recursion_limit: Explicit main-agent `recursion_limit`; `None` resolves
from env / `config.toml` / default at agent-build time.
mcp_config_path: Path to MCP config.
Expand Down Expand Up @@ -651,6 +664,7 @@ def from_cli_args(
allow_fs_tools=allow_fs_tools,
rubric_model=rubric_model,
rubric_max_iterations=rubric_max_iterations,
auto_classifier_model=auto_classifier_model,
recursion_limit=recursion_limit,
sandbox_type=sandbox_type,
sandbox_id=sandbox_id,
Expand Down
Loading
Loading