Deep Agents CLI - Interactive AI coding assistant.
Textual UI application.
Non-interactive execution mode.
Provides run_non_interactive which runs a single user task against the
agent graph, streams results to stdout, and exits with an appropriate code.
The agent runs inside a langgraph dev server subprocess, connected via
the RemoteAgent client (see server_manager.server_session).
Shell commands are gated by an optional allow-list (--shell-allow-list):
recommended or explicit list → shell enabled, commands validated
against the list; non-shell tools approved unconditionally.all → shell enabled, any command allowed, all tools auto-approved.An optional quiet mode (--quiet / -q) redirects all console output to
stderr, leaving stdout exclusively for the agent's response text.
OAuth login flow and token storage for MCP servers.
Note: mcp.shared.auth.OAuthToken is a pydantic model whose default
repr includes the access and refresh token strings verbatim. Never
log one via %r, str(), f-string interpolation, or
logger.exception/exc_info on an exception that wraps one — the
tokens will land in stdout, log files, and error-reporting
pipelines. Pass only structural facts ("refreshed token for
server X") rather than the token itself.
Business logic for the /offload command.
Extracts the core offload workflow from the UI layer so it can be tested independently of the Textual app.
Main entry point and loop.
Unified slash-command registry.
Every slash command is declared once as a SlashCommand entry in COMMANDS.
Bypass-tier frozensets and autocomplete entries are derived automatically — no
other file should hard-code command metadata.
Trust store for project-level MCP server configurations.
Manages persistent approval of project-level MCP configs that contain stdio servers (which execute local commands). Trust is fingerprint-based: if the config content changes, the user must re-approve.
Trust entries are stored in ~/.deepagents/config.toml under
[mcp_trust.projects].
Remote agent client — thin wrapper around LangGraph's RemoteGraph.
Delegates streaming, state management, and SSE handling to
langgraph.pregel.remote.RemoteGraph. This wrapper converts streamed message
dicts into LangChain message objects for the app's Textual adapter, but leaves
state snapshots in the server's serialized form.
Middleware for injecting local context into system prompt.
Detects git state, project structure, package managers, runtimes, and directory layout by running a bash script via the backend. Because the script executes inside the backend (local shell or remote sandbox), the same detection logic works regardless of where the agent runs.
Utilities for project root detection and project-specific configuration.
MCP (Model Context Protocol) tools loader.
This module provides async functions to load and manage MCP servers using
langchain-mcp-adapters, supporting Claude Desktop style JSON configs.
It also supports automatic discovery of .mcp.json files from user-level
and project-level locations.
Server-side graph entry point for langgraph dev.
This module is referenced by the generated langgraph.json and exposes the
agent graph as a module-level variable that the LangGraph server can load
and serve.
The graph is created at module import time via make_graph(), which reads
configuration from ServerConfig.from_env() — the same dataclass the CLI uses
to write the configuration via ServerConfig.to_env(). This shared schema
ensures the two sides stay in sync.
One-time migration of legacy state files into ~/.deepagents/.state/.
Earlier versions wrote internal state directly under ~/.deepagents/,
mixing it with user-facing agent directories (so e.g. mcp-tokens/
showed up in deepagents agents list). State now lives in a dedicated
.state/ subdirectory; this module moves any legacy files into place
on startup.
The migration is best-effort and idempotent: it skips entries whose destination already exists, logs and continues on per-entry failures, and never blocks startup on I/O errors.
Clipboard utilities.
iTerm2 cursor guide workaround for Textual alternate-screen rendering.
Middleware for runtime model selection via LangGraph runtime context.
Allows switching the model per invocation by passing a CLIContext via
context= on agent.astream() / agent.invoke() without recompiling
the graph.
External event ingress for the Textual app.
Exposes a small EventSource protocol plus a Unix-domain-socket implementation
that lets local processes push commands, prompts, and signals into a running
session over a newline-delimited JSON wire protocol.
The wire format and configuration env vars may change without semver guarantees while this surface stabilizes.
Middleware that adds a _context_tokens channel to the graph state.
The field is checkpointed (survives across sessions) but not passed to the
model (PrivateStateAttr). The app writes the latest total-context token
count here after every LLM response and context offload, and reads it back
when resuming a thread so that /tokens and the status bar show accurate
values immediately.
Machine-readable JSON output helpers for CLI subcommands.
This module deliberately stays stdlib-only so it can be imported from CLI startup paths without pulling in unnecessary dependency trees.
CLI commands of the MCP module.
Subagent loader for app.
Loads custom subagent definitions from the filesystem. Subagents are defined as markdown files with YAML frontmatter in the agents/ directory.
LangGraph server lifecycle management for the app.
Handles starting/stopping a langgraph dev server process and generating the
required langgraph.json configuration file.
Custom tools for the agent.
Utilities for handling image and video media from clipboard and files.
Help screens and argparse utilities for the app.
This module is imported at app startup to wire -h actions into the
argparse tree. It must stay lightweight — no SDK or langchain imports.
Lightweight hook dispatch for external tool integration.
Loads hook configuration from ~/.deepagents/hooks.json and fires matching
commands with JSON payloads on stdin. Subprocess work is offloaded to a
background thread so the caller's event loop is never stalled. Failures are
logged but never bubble up to the caller.
Config format (~/.deepagents/hooks.json):
{"hooks": [{"command": ["bash", "adapter.sh"], "events": ["session.start"]}]}
If events is omitted or empty the hook receives all events.
Onboarding emits user.name.set with {"name": "...", "assistant_id": "..."}
after the user submits a non-empty preferred name.
Server lifecycle orchestration for the app.
Provides start_server_and_get_agent which handles the full flow of:
ServerConfig from application argumentsServerConfig.to_env()langgraph dev serverRemoteAgent clientAlso provides server_session, an async context manager that wraps
server startup and guaranteed cleanup so callers don't need to
duplicate try/finally teardown.
LangChain brand colors and semantic constants for the app.
Single source of truth for color values used in Python code (Rich markup,
Content.styled, Content.from_markup). CSS-side styling should reference
Textual CSS variables: built-in variables
($primary, $background, $text-muted, $error-muted, etc.) are set via
register_theme() in DeepAgentsApp.__init__, while the few app-specific
variables ($mode-bash, $mode-command, $mode-incognito, $skill,
$skill-hover, $tool, $tool-hover) are backed by these constants via
App.get_theme_variable_defaults().
Code that needs custom CSS variable values should call
get_css_variable_defaults(dark=...). For the full semantic color palette, look
up the ThemeColors instance via get_registry().
Users can define custom themes in ~/.deepagents/config.toml under
[themes.<name>] sections. Each new theme section must include label (str);
dark (bool) defaults to False if omitted (set to True for dark themes).
Color fields are optional and fall back to the built-in dark/light palette based
on the dark flag. Sections whose name matches a built-in theme override its
colors without replacing it. See _load_user_themes() for details.
Registry of pending actionable notifications.
Stores plain data for notices the user can act on from a dedicated modal screen. The registry is deliberately UI-agnostic: UI routing (toast click, keybinds) lives in the app layer.
Best-effort writer for terminal escape/control sequences.
Centralizes the "fire and forget" pattern the app uses for cosmetic terminal
control (OSC 9;4 taskbar progress today; eventually OSC 52 clipboard and the
iTerm2 cursor guide). Writes prefer /dev/tty so output reaches the terminal
even when stdout/stderr are redirected, fall back to sys.__stderr__, and
never raise — cosmetic control output must not crash the app.
Set DEEPAGENTS_CODE_NO_TERMINAL_ESCAPE=1 to disable all output (useful for
unsupported terminals or noisy logs).
External editor support for composing prompts.
Lightweight text-formatting helpers.
Keep this module free of heavy dependencies so it can be imported anywhere in the app without pulling in large frameworks.
User-level credential storage for model providers.
Persists API keys (and, in the future, OAuth tokens) under
~/.deepagents/.state/auth.json (file mode 0600, parent 0700) so users can
enter credentials directly in the TUI rather than exporting environment
variables before launch.
Security notes:
ApiKeyCredential.key) must never be logged, formatted
via %r/!r, or interpolated into exception messages — every helper here
reports only structural facts ("set credential for provider X").O_EXCL | 0o600 to a temp path, then atomically
replaced. A second chmod 0600 runs on the final path so filesystems that
ignore the create-mode argument still end up with private perms. Permission
failures are reported back to the caller in WriteOutcome.warnings so the
UI can surface them to the user — logger.warning alone is invisible
inside a Textual TUI session.Update lifecycle for deepagents-code.
Handles version checking against PyPI (with caching), install-method detection, auto-upgrade execution, config-driven opt-in/out, notification throttling, and "what's new" tracking.
Most public entry points absorb errors and return sentinel values.
set_auto_update raises on write failures so callers can surface
actionable feedback.
Model configuration management.
Handles loading and saving model configuration from TOML files, providing a structured way to define available models and providers.
Terminal capability detection.
Detect optional terminal features without reading from stdin.
The app only uses kitty-keyboard-protocol support to choose a user-facing newline shortcut label. To keep startup safe on remote or high-latency PTYs, detection is conservative and relies on side-effect-free terminal identity signals plus an explicit environment-variable override.
Unicode security helpers for deceptive text and URL checks.
This module is intentionally lightweight so it can be imported in display and approval paths without affecting startup performance.
Configuration, constants, and model creation.
Textual UI adapter for agent execution.
Formatting utilities for tool call display in the app.
This module handles rendering tool calls and tool messages for the TUI.
Imported at module level by textual_adapter (itself deferred from the startup
path). Heavy SDK dependencies (e.g., backends) are deferred to function bodies.
Ask user middleware for interactive question-answering during agent execution.
Helpers for tracking file operations and computing diffs for display.
Inspect optional-dependency install status for the running distribution.
Reads Requires-Dist metadata to report which packages declared under
[project.optional-dependencies] are installed, and renders that status
in either plain text (for stdout) or markdown (for rich UI contexts).
Input handling utilities including image/video tracking and file mention parsing.
First-run onboarding state for the interactive TUI.
Agent management and creation.
Thread management using LangGraph's built-in checkpoint persistence.
Textual widgets for deepagents-code.
Import directly from submodules, e.g.:
from deepagents_code.widgets.chat_input import ChatInput
from deepagents_code.widgets.messages import AssistantMessageSkills module for Deep Agents Code.
Public API:
All other components are internal implementation details.
Provider-specific MCP OAuth dispatch.
resolve_provider(url) returns the registered policy whose matches
predicate fires for url, with GenericProvider as the fallback.
Built-in skills that ship with the Deep Agents Code.
These skills are always available at the lowest precedence level. User and project skills with the same name will override them.
Integrations for external systems used by the Deep Agents Code.