curl -LsSf https://langch.in/dcode | bash
# With model provider extras
# OpenAI, Anthropic, and Gemini are included by default
curl -LsSf https://langch.in/dcode | DEEPAGENTS_CODE_EXTRAS="nvidia,ollama" bash
Run:
dcode
The fastest way to start using Deep Agents. deepagents-code is a pre-built coding agent in your terminal — similar to Claude Code or Cursor — powered by any LLM that supports tool calling. One install command and you're up and running, no code required.
What deepagents-code adds on top of the SDK:
By default, dcode trusts the directory you run it in. Human-in-the-loop approval gates model-requested tool calls, but project artifacts are read before any approval prompt.
Do not run dcode in a directory you do not trust without a sandbox backend. For untrusted repositories, use a remote sandbox so execution is isolated from your machine. Running dcode in a directory lets that directory's files shape execution. See THREAT_MODEL.md for details.
See our Releases and Versioning policies.
As an open-source project in a rapidly developing field, we are extremely open to contributions, whether it be in the form of a new feature, improved infrastructure, or better documentation.
For local setup, see the Development Guide. For contribution policy, see the Contributing Guide.
This project was primarily inspired by Claude Code, and initially was largely an attempt to see what made Claude Code general purpose, and make it even more so.
Resolved model properties needed by the interactive client.
The one-per-process result with named slots to prevent transposition.
Swap the model or per-call settings from runtime.context.
Reads two optional keys from the runtime context dict:
'model' — a provider:model spec (e.g. "openai:gpt-5").
When present andFull configuration payload passed from the app to the server subprocess.
Serialized to/from DEEPAGENTS_CODE_SERVER_* environment variables so
that the server graph (which runs in a separate Python
Raised when a downloaded archive fails SHA-256 verification.
Distinct from generic install failure so callers can surface a loud, user-visible notice — a checksum mismatch is a supply-chain anomaly (
Raised when no managed helper binary is available for this system.
Distinct from transient network/download failures so callers can tell users whether retrying can help or whether they need a differe
Goal/rubric text exceeds a model-visible context budget.
Additive token and estimated-cost accounting for one or more requests.
A priced side-operation delta pending checkpoint persistence.
Use exactly once: every prepare must be either committed (its update
persisted) or rolled back. _drain_recorded_costs is destructive,
Agent state extended with the cumulative thread-cost channel.
Own the thread's cumulative _session_cost_usd checkpoint value.
The main agent owns the thread total. Nested instances checkpoint local deltas before an interrupt can pause their graph, then transf
A transport-independent event delivered from outside the TUI.
Source of external events for the Textual app.
Implementations must be safe to stop() even when start() failed
partway through; the app always invokes stop() from a finally block.
Line-delimited JSON event source over a local Unix domain socket.
The listener creates its parent directory with mode 0o700 and binds the
socket inside it under a transient umask(0o077) so the so
Metadata for a custom subagent loaded from filesystem.
Parsed origin remote attribution for coding-agent-v1 traces.
A NamedTuple so callers can still unpack positionally or index, while the
field names keep the slot order from being load-bearing at e
Raised when an external editor cannot be opened or read.
Explicit user/project path context for project-sensitive behavior.
Line counts for a change, named so the pair cannot be swapped silently.
Keyword-only and frozen so that claim holds at construction as well as in transit: a positional pair is exactly the transpositi
Data used to render HITL previews.
Line and byte level metrics for a file operation.
Track a single filesystem tool call.
Collect file operation metrics during an interaction.
A known reason to skip a cache prompt, distinct from missing pricing.
A cache-using request's start time and effective cache identity.
Prompt-cache behavior needed to decide and price a warning.
Keyword-only because window_seconds and minimum_tokens are adjacent
bare ints: positionally, transposing them builds a plausible-lookin
Estimated input cost for a cold prefix and its warm-cache delta.
Both figures are USD, non-negative, and finite; incremental_cost_usd is
the part of cold_cost_usd that a cache hit would have avoi
Validated data needed to render one advisory warning.
Constructed only after every gate has passed -- a policy resolved, the prefix cleared the provider's cache minimum, and the priced delta reached
ACP server that supplies trusted classifier context in Auto mode.
Represents a pasted image with its base64 encoding.
Represents a pasted video with its base64 encoding.
Stable identifiers for notification actions dispatched by the app.
One button/action row in the notification modal.
Typed payload for a missing-dependency notification.
Typed payload for an update-available notification.
A single notice waiting for user action.
Immutable value object: the registry owns the
key-to-toast-identity binding (see NotificationRegistry) so
external callers cannot corrupt click-routing indi
In-memory store of pending notifications.
Instance-scoped (one per app) so test apps don't pollute each other. Owns the bidirectional key-to-toast-identity binding so callers cannot accidentally desy
JSON-safe workspace descriptor carried in LangGraph runtime context.
Server-authoritative workspace and resource policy for one thread.
A workspace claim or runtime conflicts with server resource policy.
Goal/rubric state channels shared by every schema that touches them.
Declared once here so each schema that carries these channels —
ResumeState and goal_tools.GoalToolState — inherits the same
Extends agent state with per-checkpoint facts restored on resume.
Inherits the shared goal/rubric channels from GoalRubricChannels and adds
the channels unique to resume: the after-model token/spec
Persists per-checkpoint resume facts after each model call.
See the module docstring for why this rides the model node's checkpoint
instead of a separate aupdate_state (avoids a standalone `UpdateS
Versioned, allowlisted policy snapshot persisted beside a binding.
One drifted policy field, reported within the snapshot allowlist.
Structured, secret-free detail attached to a workspace refusal.
Middleware that provides an ask_user tool for interactive questioning.
This middleware adds an ask_user tool that allows agents to ask the user
questions during execution. Questions can be free-for
A different dcode entry point is winning on PATH than the one we upgraded.
Returned by detect_shadowed_dcode after a successful upgrade so the user
can be warned that a manually launched dcode
A single package version change parsed from uv's environment-diff output.
Emitted by both uv tool upgrade and uv tool install -U (the
dependency-refresh path), so the wording stays command-agnost
Raised when uv tool requested requirements cannot be preserved.
Raised when an extra cannot be removed from this install.
Covers both "not selected on the tool requirement" and refusal subclasses. Callers distinguish them because only the base class is an idempot
Raised when an uninstall targets a required base-dependency extra.
A subclass so callers that only care about "cannot remove" can catch the base class, while the CLI and TUI can report a refusal sepa
Raised when a selected composite still supplies the requested extra.
Result of an attempted optional-extra install.
Result of an attempted optional-extra removal.
Validate shell commands against an allow-list without HITL interrupts.
When the agent invokes the execute shell tool, this middleware checks
the command against the configured allow-list **before e
Stock HITL routing with an async live-mode read after model completion.
The transient routing marker is added only to a shallow state copy passed directly into stock HITL routing. It is neither check
Transport cost receipts without caching JavaScript or forwarding state.
Displayable model capabilities with override provenance.
Provider presentation and readiness, without credential values.
Validated catalog from the environment that constructs models.
Rubric state carrying dcode's private runtime model selections.
These three channels are declared a second time here, because this
middleware's state_schema must list every channel it reads. Each
a
Nested-grader state used to scope verification-tool budgets.
Run a context-aware nested grader with CLI verification middleware.
The nested grader receives Deep Agents Code's verification middleware and runtime context without requiring those application-speci
A single choice option for a multiple choice or multi-select question.
A question to ask the user.
Request payload sent via interrupt when asking the user questions.
Trusted same-turn authorization recorded after an ask_user response.
Widget result when the user submits answers.
Widget result when the user cancels the prompt.
Path-safety and size limits for read-only repository inspection tools.
A single labeled diagnostic fact.
ok is False only for genuine problems (e.g. a missing dependency), not
for informational states such as an available update.
A named group of related diagnostic items.
tool.use hook payload (schema documented in hooks).
tool.error hook payload (schema documented in hooks).
tool.result hook payload (schema documented in hooks).
In-progress state for a single streamed tool call.
args and args_parts are two representations of the arguments used one at
a time, depending on whether the provider delivers the value whole or i
Counts of buffered tool calls that never emitted a tool.use.
A NamedTuple so callers can still unpack positionally while the field names
keep the two same-typed slots from being load-bearing at e
Token stats for a single model within a session.
Token and cost stats for one UsageKind bucket.
Usage returned after recording one streamed model message.
Stable identity of one model invocation in the usage ledger.
Message identity, optionally scoped to one model attempt.
Stats accumulated over a single agent turn (or full session).
What a stream consumer last recorded for one request.
Held so a later chunk of the same request can retract that exact contribution and re-record the running totals, keeping one API call to one reque
Declared context_schema for the agent graph.
Registered via context_schema= when the graph is built, so LangGraph
coerces each run's context= payload into this dataclass — in-process,
`runtime.
Client-facing builder for the per-run graph context payload.
Callers populate this and pass it via context= to astream/ainvoke.
ConfigurableModelMiddleware and the interrupt_on when predi
State for local context middleware.
Inject local context (git state, project structure, etc.) into the system prompt.
Runs a bash detection script via backend.execute() on first interaction
and stores that snapshot for stable system-
Suppress native stderr writes while the TUI owns the terminal.
Character set mode for TUI display.
Character glyphs for TUI display.
Mutable metadata for the model active in this process.
One complete generation of credentials and project context.
Stable owner of the active credential and project-context snapshot.
Reloads construct a complete immutable CredentialsSnapshot and publish it
with one reference assignment. Callers that need a cons
Why /trace found no LangSmith key, when an empty override is involved.
Distinguishes the three states the caller renders differently: a specific empty override is suppressing an available key (`sha
Offline snapshot of LangSmith tracing configuration for diagnostics.
Carries only presence/identity facts — never API keys or other secret
values — so it is safe to render in dcode doctor output.
Base class for typed LangSmith project URL lookup failures.
Concrete subclasses (LangSmithImportError, LangSmithLookupTimeoutError,
LangSmithApiError) let interactive callers like /trace show
The langsmith package is not installed.
The LangSmith project URL lookup exceeded its hard timeout.
The LangSmith SDK call raised — auth, 404, network, etc.
Wraps the underlying SDK exception in __cause__.
The LangSmith project does not exist yet (lookup returned 404).
Projects are created lazily on the first ingested trace, so this is expected before any run has flushed and should be surfaced as an in
Result of creating a chat model, bundling the model with its metadata.
This separates model creation from runtime-state mutation so callers can decide when to commit the metadata to process-wide stat
Deterministic chat model for integration tests.
This subclasses _ToolBindingFakeModel (itself a GenericFakeChatModel) so
the implementation stays aligned with the core fake-chat-model test surfac
Deterministic tool-calling model for auto-approve integration tests.
Generation is driven entirely by prompt markers (the module-level DCA_*
constants), so output is restart-safe and independent of
Exercise nested criteria generation with a repository read.
Structured version facts for a single installed distribution.
Separates three facts that are easily conflated: the live version read from the running source, whether imported or parsed (`source_versi
Network-free snapshot of the version facts diagnostics need.
Bundles the running CLI and installed SDK version facts with the result of
comparing the deepagents requirement that deepagents-code d
Raised when installed extras cannot be determined safely.
Install status for one optional dependency extra.
Resolved recovery action for a missing provider package.
Exactly one of three outcomes:
extra set, command None — prefer installing the extra that declares
the package (callers format thisA single tool's display metadata.
A named group of tools sharing a source.
An MCP server that was discovered but currently exposes no tools.
Everything dcode tools list needs to render, in display order.
Push the terminal title on start, update it, and pop it on restore.
Revert agent edits to the managed onboarding-name memory block.
Guards the managed onboarding-name block in a fixed set of memory files. A
write_file/edit_file that leaves the managed block untou
Classifier denial categories exposed to the agent and TUI.
One validated verdict bound by the server to its proposed tool call.
Server-assembled verdicts for one unresolved action batch.
One checkpointed classifier request and its validated response.
Bounded provider-neutral classifier history.
Server-owned denial and availability counters for one thread.
Checkpoint-safe disposition for one gated call.
Private checkpoint record joining model output to after-model routing.
Server-owned provenance for one exclusively allocated scratch file.
Reducer update that creates or removes one exact artifact record.
Agent state carrying private Auto decisions and scratch provenance.
Trusted metadata attached by the Textual client to a user message.
Server-resolved approval mode and trace-safe diagnostics.
Apply deterministic policy, classifier review, and HITL fallback.
Reject dynamically gated MCP calls when no approval UI exists.
Structured proposal returned by the criteria agent.
A new proposal or a rejection-based regeneration.
feedback/previous_criteria are only present on a rejection retry.
An amendment to an accepted goal; both extra fields are required.
Main-agent state carrying a criteria request until it is cleared.
This intentionally uses normal last-value state: earlier middleware can
consume an ephemeral channel before GoalCriteriaMiddleware
Private per-invocation state for the nested criteria agent.
Nested-grader state used to scope verification-tool budgets.
Run goal-criteria requests entirely inside the main server graph.
Recover failed connections and preserve actionable login errors.
Complete set of semantic colors for one theme variant.
Every field must be a 7-character hex color string (e.g., '#7AA2F7').
Metadata for a registered theme.
Structured log record retained by the in-memory debug buffer.
Logging handler retaining the most recent structured records in memory.
Retention is partitioned by level: each recognized level name (see
LOG_LEVELS) keeps its own bounded deque of capacity re
Discriminator for ConfigResolutionError reasons.
Only NO_CONFIG_FOUND maps to exit code 2 in the mcp login CLI
handlers (run_mcp_login, run_mcp_login_list); all other kinds map to
exit code
Structured error returned when a login target cannot be resolved.
Successful resolution of a merged MCP config for login.
Resolved server config plus enough context for error messages.
Unified parse result for dropped-path payload detection.
Track pasted images and videos in the current conversation.
Thread metadata returned by list_threads.
Classification that controls whether a command can skip the message queue.
A single slash-command definition.
A single autocomplete entry for the slash-command controller.
A persisted API key credential.
The type field is the discriminator that lets OAuthCredential (added
later) coexist in the same file without migration.
A persisted OAuth subscription credential.
Stub kept here so the StoredCredential discriminated union narrows
correctly today and the OAuth implementation lands as a pure addition.
No code path pro
Result of a credential write that may have warnings to surface.
Result of a credential delete that may have warnings to surface.
A delete rewrites the whole store, so it can hit the same chmod failures as
a write. warnings carries them symmetrically with `Write
Capture effective main-call context and answer tool-free side questions.
Register after middleware that modifies the model, prompt, or settings,
including extensions. ConfigurableModelMiddleware re
Canonical goal/rubric fields used for notices and fingerprints.
The three user-controlled text sections a goal-state notice can embed.
Named rather than a bare tuple[str | None, str | None, str | None]: all five
call sites unpack positionally and immediately re
Metadata extracted from a canonical goal-state notice.
OSC 9;4 progress states.
See https://learn.microsoft.com/en-us/windows/terminal/tutorials/progress-bar-sequences.
A dangerous Unicode character found in text.
Safety analysis output for a URL string.
A result may have safe=True with non-empty warnings when
informational warnings (e.g. punycode decoding) are present without
suspicious patterns.
Raised when the launch-time profile location cannot be resolved.
Covers an unsupported DEEPAGENTS_HOME value and a launch home that
cannot be determined or is itself unusable. It is a ValueError
One component in the context audit.
Structured context audit ready for presentation.
Paths whose contents belong to one user profile and trust root.
Paths owned by the installed tool rather than a selected profile.
Project-controlled paths derived from an explicit repository root.
Frozen launch-time profile and installation paths.
Whether a probed path exists, is absent, or could not be read.
A StrEnum so the value serializes directly to JSON without a custom
encoder.
Tool-approval policy selected for an interactive thread.
Stored approval-mode control payload.
Stored content for a collapsed paste.
The paste's numeric identifier is the key under which this record is stored in the input's paste map, so it is not duplicated on the record.
Merged view of built-in, entry-point, and config sandbox providers.
Snapshot of the ChatGPT OAuth login state.
Raised when the user cancels a sign-in flow mid-callback wait.
Raised when a stored ChatGPT token cannot be refreshed.
Distinct from a missing token (FileNotFoundError): a token exists on
disk but its refresh token was revoked or expired, so an automatic
refre
UI hooks for the browser loopback sign-in flow.
Implementations decide how to surface the authorize URL and whether to auto-open a browser. The Textual screen subclasses this; CLI / headless callers
How to install the package that provides a sandbox backend.
Built-in providers ship as deepagents-code extras (kind="extra");
third-party providers install as arbitrary packages (kind="package"
Static description of a sandbox provider used by the registry.
Lets the CLI and registry describe built-in and config providers without instantiating them (which may require credentials or optional d
Base error for sandbox provider operations.
Raised when the requested sandbox cannot be found.
Interface for creating and deleting sandbox backends.
Configuration for a single config-declared sandbox provider.
Setting class_path executes arbitrary Python code imported from the
user's config file. This has the same trust mod
Parsed [sandboxes] configuration from config.toml.
Instances are immutable once constructed; providers is wrapped in a
MappingProxyType to prevent accidental mutation.
Expose tools registered after the agent graph was built.
Registrations and isolated errors from one load pass.
Authorized sources and non-fatal resolution errors.
Default decision for project-authored extension code.
Effective extension configuration for one process.
Runtime mode exposed to extensions.
Factory-scoped registrar and read-only session context.
Each extension receives a dedicated instance, which attributes every registration to the extension's source without exposing mutable dcode appl
GitHub-hosted MCP: RFC 8628 Device Authorization Grant.
Outcome of a provider's pre-handshake run_login step.
Base class for provider-specific OAuth dispatch.
Subclasses override matches plus whichever of client_metadata
and run_login they customize. The default implementations cover
the spec-compliant
Fallback provider for spec-compliant MCP servers with no quirks.
Slack-hosted MCP: loopback Authorization Code with a public client.
Raised when a marketplace cannot be loaded.
Local directory or JSON file used as a marketplace source.
GitHub or Git repository used as a marketplace source.
ref selects an optional branch or tag. Commit SHA checkout is not part of
the shallow-clone flow.
Marketplace manifest downloaded from an HTTP URL.
Parsed plugin manifest.
Inventory of supported plugin components.
unsupported lists plugin component directories that deepagents-code does
not load (e.g. agents/, commands/).
A discovered plugin ready to feed dcode adapters.
A plugin stored relative to its marketplace.
A plugin sourced from a GitHub repository.
A plugin sourced from a subdirectory in a Git repository.
A plugin sourced from a Git repository URL.
A catalog entry from a marketplace manifest.
A parsed marketplace manifest.
Persisted marketplace source record.
Install record for a plugin.
version is the value declared by the plugin manifest, if any.
Result from plugin discovery.
Raised when a plugin manifest is malformed enough to skip the plugin.
Raised when existing plugin state cannot be safely modified.
Load namespaced plugin skills without extending the SDK source API.
Wraps the SDK SkillsMiddleware. Sources without a namespace load exactly
as the SDK loads them. Sources carrying a plugin namespa
Presentation total derived from the latest independent subtotals.
Retain each source independently so delayed updates cannot erase spend.
Raised when the HITL interrupt loop exceeds _MAX_HITL_ITERATIONS rounds.
A tool call whose tool.use has fired but whose result has not arrived.
Bundling the name and args into one record keeps them structurally in
lock-step: a single dict[str, InFlightToolCall] cannot
Mutable state accumulated while iterating over the agent stream.
Best-effort background LangSmith thread URL lookup state.
Thread safety: the background thread sets url then calls done.set().
Consumers must check done.is_set() before reading url.
Manages a langgraph dev server subprocess.
Focuses on subprocess lifecycle (start, stop, restart) and health checking. Env-var management for restarts (e.g. configuration changes requiring a full r
An option paired with its resolved effective value, for display.
Bundles the four values that always travel together through the render helpers as one named record, so they can't be reordered or misa
Adapt hook invocations and handler output across the wire boundary.
Persisted trust record for one canonical workspace root.
Versioned on-disk trust store for project-scoped hooks.
Decides whether project-scoped hooks may run in a given directory.
Trust is a property of the workspace, not of the session, so it must be re-resolved every time the working directory moves. A sessio
Live client identity projected into every hook invocation.
Result of a lifecycle hook that may halt the caller.
Result of UserPromptSubmit, including its prompt rewrites.
Owns the Hooks v2 runtime, presenter, hook service, and transcripts.
The presenter is the manager's, not the runtime's: one instance is created once and handed to every runtime the manager loads, so
One JSONL record in a materialized transcript projection.
Identity of a materialized transcript file.
Append-only JSONL transcript projections owned by the client process.
Collect completed stream messages into a Hooks transcript runtime.
Client-only materialization needed to build one hook wire envelope.
Client-owned session runtime around an immutable Hooks snapshot.
Owns configuration snapshot identity, transcript materialization, and the
HookEngine. Server-owned lifecycle events reach this runti
One ordered command handler in a configuration snapshot.
Matched handlers for one invocation.
Immutable, declaration-ordered Hooks v2 runtime configuration.
Origin of the matcher groups contributed by one hooks document.
A project or user hooks file, which defines no variables.
Origin and environment for groups one enabled plugin contributed.
Validated configuration plus load diagnostics and source paths.
Deduplicate hook fulfillment for one client session.
Execute Hooks v2 invocations against one immutable snapshot.
Client approval decision compatible with HITL resume payloads.
Normalized result shared by TUI and headless permission handling.
How one batch of gated tool calls was resolved by hooks.
Indices refer to positions in the originating action_requests list, so a
caller can line outcomes back up with its own UI rows.
Validated output and diagnostics from one command handler.
Raised when a client-owned hook stops lifecycle processing.
Client state required to create a domain hook invocation.
Execute client-owned events and apply their common side effects.
User-facing output goes through the runtime's presenter, which the owning
HooksManager also holds. The service never wraps or replac
Request sent for a server-owned hook invocation.
Response returned for a server-owned hook invocation.
Configuration for a synchronous command hook.
Currently only type: "command" is supported. Additional handler types
remain a discriminated-union extension point and are rejected until
implemented.
A matcher and its ordered hook handlers.
Top-level configuration grouped by hook event.
A tool.result payload held back until the authoritative result arrives.
Used for an answered ask_user: the middleware owns the final status, and the
hook body must be the sanitized summary rather
A validated rubric_evaluation_end event forwarded to the caller.
Bundling the two fields as named attributes (rather than two positional strings) makes the grading-run correlation self-documenting
Adapter for rendering agent output to Textual widgets.
This adapter provides an abstraction layer between the agent execution and the Textual UI, allowing streaming output to be rendered as widgets.
One prompt summary row.
Public so its Clicked message resolves to the idiomatic
on_prompt_row_clicked handler; nothing outside this module builds one.
Message sent when a prompt row is clicked.
Filter, preview, copy, or select a previously submitted prompt.
Keep the session cost warning visible until acknowledged.
Ask whether to start a new session or exit after a blocked resume.
Show a live, scrollable, copyable list of MCP server statuses.
How to resolve a cold prompt-cache warning.
Offer actions for a turn whose prompt cache may be cold.
Dismisses with the chosen ColdCacheChoice, or None on a
programmatic pop. Esc is mapped to CANCEL so the user is never
forced into a spe
Ask whether to compact a just-resumed thread before the next turn.
Side-question editor with the shared multiline and paste conventions.
Posted when Enter submits the complete side question.
Chat independently of the main run with restorable side exchanges.
Confirm a model switch that preserves a large conversation context.
Modal showing the copyable entire-thread token and cost breakdown.
Confirm or edit a suggested name without changing the thread yet.
Arrow-key navigable plugin manager for /plugins.
Closing runs the optional check_reload_required callback while this screen
stays mounted. Changed plugin state transitions in place to a reload pr
Posted when a plugin manager tab label is clicked.
Mouse-clickable tab label in the plugin manager header.
In-TUI first-run notice describing what Auto mode does.
Dismisses with True on Enter (confirm switch to Auto) and False on
Esc (cancel, stay in current mode). Programmatic dismiss may yield `None
The closed set of LangSmith region selections in the /auth prompt.
Outcome of resolving the region selector to an endpoint to persist.
endpoint is the canonical URL to store (empty for the US SaaS default);
error is a user-facing message when a Custom URL is mis
Outcome of an AuthPromptScreen interaction.
The three outcomes need to stay distinguishable because callers in the
recovery path retry the original failing operation only on SAVED —
retrying afte
Confirm before launching an authentication flow for a model.
A provider-agnostic gate shown when a selected model needs credentials that aren't detected, and starting the auth flow is disruptive enou
Confirmation overlay shown before clearing a stored credential.
Patterned on DeleteThreadConfirmScreen so the destructive prompt feels
consistent across the app. Always dismisses with True on con
Modal that captures and persists an API key for one provider.
Dismissal values are members of AuthResult so callers in the recovery
path can distinguish "user just saved a key — retry the failed
op
Modal that lists configured providers and lets the user manage keys.
Reachable via the /auth slash command. Always dismisses with None;
state changes are persisted by AuthPromptScreen and refle
Posted when a key prompt successfully persists credentials.
Carries the /auth config key that was saved so the app can react to
credentials that gate spawn-time behavior — e.g. a Tavily key that
en
Posted when a key prompt deletes stored credentials.
Carries the /auth config key that was deleted so the app can clear
any in-memory state derived from the now-removed credential.
Confirmation overlay for installing an arbitrary --package.
Dismisses with True when the user confirms and False when the user
cancels. Esc is treated as cancel so the user is never forced into
Confirmation overlay for installing a model provider's extra.
Shown from the model selector when the user picks a model whose provider
integration package is not installed. Dismisses with True to i
Modal asking whether to restart the server for a spawn-time change.
Serves both the post-install offer and the post-/auth web-search offer;
the caller supplies the title verb and body copy.
Di
A single row in the console's session snapshot.
The four named fields keep the display strings and their interaction metadata
explicit at construction sites. copyable opts a row into click-to-copy,
Modal showing a session snapshot and a live tail of recent log records.
Dismissal payload identifying which action the user picked.
The screen returns this via dismiss() when the user drills into
a notification and selects an action; it returns None when the
user can
Posted when a notification row is clicked with the mouse.
Posted when the user picks SUPPRESS from a notification's detail modal.
The center does not dismiss on SUPPRESS because the remaining notifications should still be reachable in place. The app handles
Posted when the user toggles the settings disclosure row.
The app responds by refreshing the open center's settings state from config; the center also handles the message itself so toggles stay respo
Posted for an action that opens a follow-up modal in place.
Some actions (those in IN_PLACE_ACTIONS, currently ENTER_API_KEY)
push another modal, such as the API-key prompt, on top of the
still-o
Shared hub for pending notifications and warning preferences.
Each PendingNotification is a single row followed by a settings
disclosure row. Up/Down (or j/k) moves the cursor; Enter or click drill
Base class for tool approval widgets.
Generic approval widget for unknown tools.
Approval widget for write_file - shows file content with syntax highlighting.
Approval widget for edit_file - shows clean diff with colors.
One startup tip displayed above the chat input.
Raised by MCPLoginScreen.action_cancel when the user cancels the flow.
Modal that renders the OAuth login flow and collects user input.
Implements the OAuthInteraction Protocol structurally so a
mcp_auth.login(..., ui=screen) call drives the same modal. Each
interac
Docked two-pane panel visualizing js_eval subagent fan-out by phase.
Hidden until the first spawn event. Phases (one per js_eval) list on the
left and the selected phase's subagents render as a s
Outcome of the YOLO first-enable notice.
ACKNOWLEDGE enables YOLO (and records the acknowledgement); MANUAL
switches to Manual instead; CANCEL keeps the previous mode. A
programmatic dismiss ma
In-TUI acknowledgement shown before unrestricted YOLO becomes active.
Dismisses with YoloModeNoticeResult.ACKNOWLEDGE on Enter (acknowledge and
enable), YoloModeNoticeResult.MANUAL on m (switch
Prompt filter with standard modified-Backspace word deletion.
Query field for the inline prompt search panel.
Plain Input apart from the class name, which lets ChatInput filter
Input.Changed / Input.Submitted messages down to this field, plus
bindings f
Posted on Escape or empty-query Backspace, to close the search.
One clickable prompt row in the inline search panel.
Message sent when a prompt row is clicked.
Inline prompt history search rendered above the input row.
Display-only: ChatInput owns the query, filtered snapshot, and
selection, drives key handling, and re-opens the modal tier. The panel
mirr
Message sent when the panel's rendered row count changes.
Message sent when a prompt row is clicked in the panel.
Modal asking whether to switch cwd when resuming or switching to a thread.
Ask how project hooks in a newly entered workspace should be trusted.
TextArea that detects paste-like keystroke bursts.
Subclasses drive the state machine from their own _on_key by calling the
helper methods here, and override the policy hooks
(`in_slash_command
Paste-aware text area that collapses large pastes into placeholders.
The full pasted text is stored off-screen in _pasted_contents and a
compact [Pasted text #N] placeholder is shown in its place
Keep the current goal and lifecycle state visible above the input.
Which stored preference Ctrl+S toggles, and how the footer names it.
The selector is reused for pickers that choose something other than the
main agent model (for example the /auto classifier), whe
A clickable model option in the selector.
Message sent when a model option is clicked.
Selector title whose current-model span copies on click.
Full-screen modal for model selection.
Displays available models grouped by provider with keyboard navigation and search filtering. Current model is highlighted.
Returns (model_spec, provider) tuple
Compact welcome banner shown at startup.
Renders a bordered box with the product title and optional version. A
(debug enabled) tag appears when DEEPAGENTS_CODE_DEBUG is enabled
(truthy), and an `
Manages command history with file persistence.
Uses append-only writes for concurrent safety. Multiple agents can safely write to the same history file without corruption.
Free-form answer input for ask-user questions.
Adds two behaviors over the shared base:
Posted when the user presses Enter to submit an ask-user answer.
Interactive widget for asking the user questions.
Supports text input, multiple choice (pick exactly one), and multi-select (toggle one or more) questions. Choice questions always include an "Other"
Message sent when user submits all answers.
Message sent when user cancels the ask_user prompt.
Ask before changing agents to resume a thread.
Run the ChatGPT OAuth Authorization Code Flow with PKCE inline.
Dismissal value:
True: a token was saved (caller should refresh provider lists /
retry the operation that needed the credentiaOutcome of the CodexSignedInScreen quick-action overlay.
Encoded as an enum (mirroring AuthResult) rather than bare strings so a
typo in either the producing action_* method or the consuming di
Quick-action overlay shown when openai_codex is already signed in.
Dismissal values:
CodexSignedInAction.SIGN_OUT: delete the stored token.CodexSignedInAction.REAUTH: open the OAuth flowStrategy for building a tool's HITL approval widget.
Each renderer maps a tool name to a (widget_class, data) pair that
controls what the user sees in the approval box. Tools not registered
in `_RE
Renderer for write_file tool - shows full file content.
Renderer for task tool — interrupt description provides full context.
Renderer for delete tool - shows removed file content when available.
Renderer for edit_file tool - shows unified diff.
Widget result when the generated criteria are accepted unchanged.
Widget result when the user submits revised criteria.
Widget result when the user rejects criteria with feedback.
Widget result when the user cancels the proposal.
Text input that keeps goal-review edit keystrokes inside the editor.
Posted when the user presses Enter to submit goal-review text.
Posted when Escape should leave goal criteria edit mode.
Inline review widget for generated goal acceptance criteria.
Message sent when the user accepts, edits, or cancels.
Captured stdout printed during a js_eval evaluation.
A successful js_eval evaluation result.
An error raised during a js_eval evaluation.
Modal asking whether to restart the server after an MCP login.
Dismisses with "reconnect" when the user accepts the restart and
"later" when the user defers. Esc is treated as "later" so the
user
Modal asking whether to reconnect after /mcp disable/enable toggles.
Shown when the user closes the /mcp viewer with pending F2
disable-state changes but without pressing Ctrl+R, so the toggl
Confirmation overlay for /mcp reconnect --force with no pending login.
Guards a fat-fingered force-restart when nothing is actually queued.
One-time choice for how Auto mode handles generated goal criteria.
Onboarding screen that asks for the user's name.
Dismissal values:
"" when the user submits an empty input (continue, but skip naOnboarding screen that summarizes installed optional integrations.
Approval menu using standard Textual patterns.
Key design decisions (following mistral-vibe reference):
Message sent when user makes a decision.
Modal visualization of the current model context window.
Confirmation overlay before /update --deps upgrades dcode itself.
Dismisses with True when the user chooses the app update first and False
when they prefer to refresh dependencies for the curre
Confirmation overlay for a dependency refresh.
Dismisses with True when the user confirms and False when the user
cancels. Esc is treated as cancel so the user is never forced into a refresh
they
Approval overlay for a skill resolving outside trusted directories.
Dismisses with True when the user allows the resolved target and False
when the user declines. Esc is treated as deny so the us
Animated spinner using charset-appropriate frames.
Animated loading indicator with status text and elapsed time.
Displays:
A clickable thread option in the selector.
Message sent when a thread option is clicked.
Emit scroll changes so the parent can refresh the overflow indicator.
Message sent when the controls pane scroll position changes.
Confirmation modal shown before deleting a thread.
Options dropdown overlay that consumes option navigation while focused.
Options dropdown that keeps focus contained while its menu is open.
Modal dialog for browsing and resuming threads.
Displays recent threads with keyboard navigation, fuzzy search, configurable columns, and delete support.
Returns a thread_id string on selection, o
Modal dialog for switching between available agents.
Displays agent profiles from ~/.deepagents/ (directories that contain an
AGENTS.md marker) in an OptionList. Returns the selected agent name
Modal dialog for theme selection with live preview.
Displays available themes in an OptionList. Navigating the option list
applies a live preview by swapping the app theme. Returns the selected
the
Result of handling a key event in the completion system.
Protocol for views that can display completion suggestions.
Protocol for completion controllers.
Controller for / slash command completion.
Controller for @@ thread completion from local session metadata.
Controller for @ file completion with fuzzy matching from current cwd.
Manages multiple completion controllers, delegating to the active one.
Types of messages in the chat.
Status of a tool call.
In-memory message data for virtualization.
This dataclass holds all information needed to recreate a message widget. It is designed to be lightweight so that thousands of messages can be stored witho
Manages message data and widget window for virtualization.
This class stores all messages as data and manages a sliding window of widgets that are actually mounted in the DOM.
Posted when the changelog row is clicked with the mouse.
Modal dedicated to the update-available notification.
Renders the entry's title and body, a "View changelog" row, and
one row per configured action. Dismisses with the selected
ActionId, or None
A selectable tool item in the MCP viewer.
Read-only modal for a failed MCP server's error details.
A selectable server-header row in the MCP viewer.
Cursor-selectable so users can navigate to every server — even those
in unauthenticated or error states which have no tool rows by the
`MCPServer
Modal viewer for active MCP servers and their tools.
Displays servers grouped by name with transport type and tool count. Navigate with arrow keys, Enter to expand/collapse tool descriptions, start i
A label that displays a model name with smart truncation.
When the full provider:model text doesn't fit, the provider is dropped
first. If the bare model name still doesn't fit, it is left-truncate
A label that displays the working directory, condensed to fit.
The tail of a path is the part users read, so directory components are
collapsed from the middle outward (see :func:condense_path) rat
A label that displays the git branch with glyph-aware truncation.
Unlike CSS text-overflow: ellipsis (which always uses the Unicode
ellipsis character), this widget truncates manually in :meth:`ren
A bullet-separated chain of session metrics.
Segments are supplied pre-styled and in priority order. When the chain is wider than the bar, trailing segments are dropped one at a time (so the least im
Two-line status bar for session identity and runtime metrics.
Posted when an _ActionOption is clicked with the mouse.
Modal displaying a single notification's title, body, and actions.
Activation returns the chosen ActionId via dismiss(); Esc
returns None so the caller can keep the underlying notification
cent
Modal that shows self-update progress and a bounded log tail.
A clickable completion option in the autocomplete popup.
Message sent when a completion option is clicked.
Small clickable button shown at the right edge of the chat input row.
Provides discoverable mouse alternatives to keyboard shortcuts for
clearing ([ X ]) and copying ([ COPY ]) the current draft.
Message sent when an input action button is clicked.
Popup widget that displays completion suggestions as clickable options.
Message sent when the popup's visible row count changes.
Deduplicated by the sender, so receiving this always means the rendered row count actually moved.
Message sent when a completion option is clicked.
TextArea subclass with custom key handling for chat input.
Modifier-Enter / Ctrl+J newline bindings and the VSCode backslash+enter
fallback are inherited from PasteBurstTextArea.
Message sent when text is submitted.
Request previous history entry.
Request next history entry.
Posted when the user presses a printable key or backspace.
Relayed by ChatInput as ChatInput.Typing for the app to track
typing activity.
Bordered box that owns the chat composer size.
Sizing is either automatic (content-driven, the default) or manual, and
_requested_height is the discriminator: None means automatic.
A manual size
Drag target docked over the chat input's top border.
Only the background is transparent: the handle sits on the layer above the
box's border and would blank the line it covers, so render repaints t
Message sent when a resize drag begins.
Message sent with the current drag delta.
Message sent when a resize drag stops, however it stopped.
Message sent when resize hover feedback changes.
Message sent when expanded sizing should be toggled.
Chat input widget with prompt, multi-line text, autocomplete, and history.
Features:
config.newline_shortcut)Message sent when input is submitted.
Message sent when input mode changes.
Posted when the user presses a printable key or backspace in the input.
The app uses this to delay approval widgets while the user is actively
typing, preventing accidental key presses (e.g. y, n
Modal dialog for selecting a reasoning effort level.
Interrupt payload asking the user to trust a skill's directory.
The client answers with {"approved": bool}. Any other answer is a deny.
Outcome of a revoke_skill_dir_trust call.
Distinguishing NOT_FOUND from REMOVED lets the CLI print an honest
message instead of a false success when the target was never trusted (a
plain bool c
Extended skill metadata for CLI display, adds source tracking.
Structured prompt and checkpoint metadata for a skill invocation.
Where managed policy is read from, and whether that location is certain.
fallback holds why the path is a guess, or None when the path is
authoritative. A failed registry query leaves the lookup
Outcome of one user config transaction.
Configuration consumed by CodeInterpreterMiddleware.
Managed and user TOML snapshots from one resolution generation.
Raised when an enforced managed source cannot be read safely.
Raised when managed policy declares a value that cannot be enforced.
The file parses, so provider health is OK; the policy it states is what
cannot be applied. A subclass of ManagedConfigError so
Provider health and policy enforceability from one managed snapshot.
Format an auth manager badge for a provider.
Used by the /auth manager, where each provider renders a bracketed,
styled badge (e.g. [stored], [env set: ANTHROPIC_API_KEY], [missing]).
Format a model selector provider-header indicator.
Used by /model, where the indicator is plain text shown next to the
provider name. Returns an empty string for CONFIGURED providers, which
need
Return non-agent directory names reserved by the app under the profile root.
These directories are created by the app for its own use and must never appear in the agent picker — even if they contain
Report whether name resolves onto an app-owned profile directory.
Use this instead of name in reserved_agent_dir_names() wherever the
input is a user-supplied agent name: the membership test is e
Return resources shared by the graph and dcode operation routes.
Builds once and caches. A construction failure is converted into a startup-error marker (scraped by the parent app process) before `sy
Return the graph after validating execution workspace context.
Argparse type for integer arguments that must be >= 1.
Argparse type for integer arguments that must be >= 0.
Argparse type that validates a shell allow-list without normalizing it.
Show top-level help information.
Show help information for the list subcommand.
Invoked via the -h argparse action or directly from cli_main.
Show help information for the agents subcommand.
Show help information for the reset subcommand.
Show help information for the skills subcommand.
Invoked via the -h argparse action or directly from
execute_skills_command when no subcommand is given.
Show help information for the plugin / plugins subcommand.
Show help information for the skills list subcommand.
Show help information for the skills create subcommand.
Show help information for the skills info subcommand.
Show help information for the skills delete subcommand.
Show help information for the skills trust subcommand.
Show help information for the update subcommand.
Show help information for the doctor subcommand.
Show help information for the tools subcommand.
Show help information for the tools list subcommand.
Show help information for the tools install subcommand.
Show help information for the install subcommand.
Show help information for the uninstall subcommand.
Show help information for the mcp subcommand.
Show help information for the mcp login subcommand.
Show help information for the mcp config subcommand.
Show help information for the config command.
Invoked via the -h argparse action. Kept import-light so help remains on
the startup fast path.
Show help information for the auth subcommand.
Invoked via the -h argparse action, the startup fast-path, or
run_auth_command when no auth subcommand is given. Kept import-light so
it stays on
Show help information for the threads subcommand.
Invoked via the -h argparse action or directly from cli_main
when no threads subcommand is given.
Show help information for the threads delete subcommand.
Show help information for the threads list subcommand.
Classify every ServerConfig field for the policy/runtime split.
Every dataclass field must land in exactly one bucket so the fingerprint split cannot silently drop a setting. A field missing from a
Return the server names disabled by the user or by managed config.
Return True when server_name is in the disabled set.
Add or remove server_name from the persistent disabled set.
Refuses to write when the existing config cannot be parsed so a corrupt or permission-denied file is not silently overwritten — that woul
Return whether the attached terminal should be treated as kitty-aware.
Detection is side-effect free: it never writes escape sequences or reads queued input bytes. That means it may under-detect some
Drop empty-string values for optional MCP tool params.
Some MCP servers (e.g. Slack's slack_search_public_and_private) validate
optional ID-typed params with value is not a channel ID when the mo
Build the middleware wrapping every MCP tool call.
Return both managed bin locations in preference order.
Read from the module globals on each call rather than frozen into a
constant, so a test (or a future runtime override) that patches BIN_DIR
is
Return the managed ripgrep filename for this platform.
Return the managed ripgrep binary path (.exe on Windows).
Return whether managed-tool downloads are disabled via env var.
Return the configured ripgrep installer mode.
Reads RIPGREP_INSTALLER and normalizes it to INSTALLER_MANAGED or
INSTALLER_SYSTEM, falling back to INSTALLER_MANAGED for unset or
unrecognized v
Return whether the user opted into the system ripgrep installer.
In system mode ripgrep is provisioned by the OS package manager or an
existing PATH entry rather than the managed download.
Idempotently expose managed ripgrep through os.environ["PATH"].
Safe to call on every startup. The installation-scoped directory is prepended directly. A verified profile fallback is exposed throug
Ensure a usable rg binary is available, installing if necessary.
Resolution order:
system installer is selected, return a non-managed rg
found on PATH, or None when only theReturn the shell command that refreshes this editable environment.
Workspace sibling editables are included explicitly because resolving only
libs/code would let --upgrade replace them with PyPI
Build the full advisory: one line per violation plus the refresh command.
Return whether this checkout's muted fingerprint matches fingerprint.
Reads without taking the store lock. Writes land via an atomic
Path.replace, so a concurrent mute is either wholly visible or
Persist fingerprint as this checkout's muted mismatch.
Print the stale-dependency warning to stderr for non-TUI launches.
Skips silently when there are no violations or the exact mismatch was muted for this checkout. This is strictly best-effort: any une
Block on a refresh/continue/mute/abort prompt for a stale interactive launch.
Prompts only when violations exist and the exact mismatch was not muted for this checkout. The prompt itself is implement
Reject a goal objective that cannot fit its persistent context budget.
This checks raw length only. HTML escaping can still expand the text fivefold, so a caller about to run criteria generation shou
Reject criteria that cannot fit their persistent context budget.
Validate an objective and its generated criteria as one application.
Validate only the combined budget, not either field's own limit.
Split out because the two kinds of overshoot need opposite handling in the criteria agent's structured-output loop: a per-field oversh
Validate the escaped size an accepted pair will occupy in the notice.
Split from validate_goal_application_total because the two budgets answer
different questions. The raw combined check shares it
Reject an objective whose escaped text alone cannot fit a notice.
Reject a goal status note that cannot fit its persistent context budget.
Validate every user-controlled section of a goal-state notice.
Return normalized cache reads and generic, 5m, and 1h writes.
Report whether genai-prices is currently able to price a request.
Note that True also covers "not yet attempted", so callers must only
consult this after pricing has been tried -- otherwise a ses
Estimate one model request's total cost in USD.
Preserves the established public interface while the private structured estimate powers checkpointed debugger detail.
Resolve the model and provider attached to a streamed model message.
Price model calls made by a server operation without committing them.
The caller must persist PreparedOperationCost.update atomically with the
operation state, or call rollback() if that write fa
Build the plain-text output for the --version CLI flag.
Includes the CLI and SDK versions and any installed optional dependencies. For editable installs it also reports the source path and the reso
Check if optional dependencies are installed.
Check for recommended external tools and return missing tool names.
Skips tools that the user has suppressed via
[warnings].suppress in config.toml.
Build a PendingNotification for a missing optional tool.
The returned entry carries the install hint (or URL) in a typed payload so the notification center action handler can copy it / open it with
Format a missing-tool warning for non-interactive console output.
Parse command line arguments.
Run the Textual TUI interface (async version).
Starts a LangGraph server in a subprocess and connects the TUI to it via the
langgraph-sdk client.
Read piped stdin and merge it into the parsed CLI arguments.
When stdin is not a TTY (i.e. input is piped), reads all available text and applies it to the argument namespace. If stdin is a TTY or the
Block on a refresh / continue / mute / abort picker for stale dependencies.
Lives here (not in _dep_floor_check) beside the other pre-TUI trust
prompts so the picker implementation is shared. The p
Entry point for console script.
Resolve the configured runtime logging level.
Configure runtime logging and register target for per-thread files.
Route configured debug loggers to the active thread's log file.
Return the path of the active debug log file, or None if not logging.
Reflects the file handler actually attached by configure_debug_logging,
not the current DEEPAGENTS_CODE_DEBUG env value. Th
Return the default per-process Unix socket path.
Prefers XDG_RUNTIME_DIR (per-user, tmpfs-backed, auto-cleaned on
logout) and falls back to the system temp dir when the runtime
directory is unset.
Decode one newline-delimited JSON external event.
List subagents from user and/or project directories.
Scans for subagent definitions in the provided directories. Project subagents override user subagents with the same name.
Locate the effective git metadata directory for a path.
Locate the repository root for a path.
Resolve a validated identity shared by one repository's Git worktrees.
A normal checkout uses its in-tree .git directory. A linked worktree is
accepted only when its administration directory lives
Read the current git branch from repository metadata.
Fall back to git rev-parse for unusual repository layouts.
Resolve the current git branch with a filesystem-first strategy.
Read the current HEAD commit SHA from repository metadata.
Resolves a symbolic HEAD (ref: refs/heads/<branch>) by reading the
loose ref file, then packed-refs. A detached HEAD already conta
Fall back to git rev-parse HEAD for unusual repository layouts.
Resolve the current HEAD commit SHA, filesystem-first.
Read the origin remote URL from the repository config file.
Fall back to git config --get remote.origin.url.
Resolve the origin remote URL, filesystem-first.
Derive repository attribution from an origin remote URL.
Handles both HTTPS (https://github.com/org/repo.git) and scp-style SSH
(git@github.com:org/repo.git) remotes, normalizing the URL to its
Resolve editor command from environment.
Checks $VISUAL, then $EDITOR, then falls back to platform default.
Return a safe configured editor name for user-facing hints.
Open current_text in an external editor.
Creates a temp .md file, launches the editor, and reads back the result.
Read the server project context from environment transport data.
Find the project root by looking for git metadata.
Find project-specific AGENTS.md file(s).
Checks two locations and returns ALL that exist:
Both files will be loaded and combined if bo
Bind web search to one workspace credential.
The schema is taken from web_search via functools.wraps so the built-in
and workspace-bound variants can never present different arguments. The two
al
Return whether candidate is a built-in or workspace-bound search tool.
Get the current Deep Agents thread ID for LangSmith or MCP tooling.
Search the web for current information.
Fetch a URL and return the page content as markdown.
Return whether a diff line is the truncation marker.
One predicate for both readers, which previously disagreed: the renderer stripped, the recount compared exactly.
Exact, deliberately. `compute_un
Split a unified diff back into the lines it was assembled from.
Deliberately not splitlines(). Every diff reaching this function is
"\n"-joined from lines that themselves came from splitlines()
Locate paired file headers immediately preceding a hunk.
A ---/+++ pair is only a file header when it appears outside a hunk
body — a diff of a file that itself contains such lines would otherw
Count added and removed lines in unified-diff lines.
Return what a successful file operation could not show, if anything.
Every case here leaves the caveat as the user's only account of a change the transcript cannot render, so each has to name what is
Return display_caveat for a successful completed record.
An untrusted pre-image describes what a successful operation could not verify. It is not a property of a failed tool call: showing its succe
Compute a unified diff between before and after content.
Convert a virtual/relative path to a physical filesystem path.
Return whether a path points at a credential/secret file.
Best-effort, filename-based, case-insensitive heuristic. It matches .env
and its variants (e.g. .env.local), well-known credential filena
Format a path for display.
Collect summary info and diff for HITL approvals.
Validate a checkpointed cache activity record.
Build the placeholder policy used by DEEPAGENTS_CODE_DEBUG_COLD_CACHE.
Keeps the modal reachable on providers with no documented cache policy. Lives here rather than in the caller so the Anthropic
Return a stable identity for the endpoint that owns a prompt cache.
A missing endpoint means the provider's default API. Only scheme, host, port, path and a digest of the query are significant; every
Read [warnings].trusted_cache_endpoints as a set of hostnames.
Entries declare that an alternate endpoint forwards cache-affecting request
fields (cache_control, prompt_cache_key, `prompt_cache
Resolve a documented cache policy for one effective model invocation.
Policies apply only when the endpoint is the provider's official API or a user-declared trusted endpoint (see `load_trusted_cache
Project the params that participate in prompt-cache identity.
Estimate cold input spend and the incremental cost over a cache hit.
Prices are derived by running two synthetic usage payloads through the
ordinary estimate_cost path -- one billed as a full cache
Parse a persisted UTC timestamp, rejecting malformed or naive values.
Format elapsed cache age for compact modal copy.
Format a provider cache window for compact modal copy.
Read launch metadata without binding or validating a conversation thread.
Resolve metadata without committing a model switch or running inference.
Discover selectable models in a thread's bound inference environment.
Remove display-only media placeholders from user text.
Placeholders like [image 1] are inserted into the terminal input purely for
display; the actual media travels as structured content blocks. Th
Attempt to read an image from the system clipboard.
Supports macOS via pngpaste or osascript.
Read and encode an image file from disk.
Read and encode a video file from disk.
Return whether a path's extension is a known image or video extension.
This is a cheap, extension-only check (no file read or decode). Use it to classify a dropped file path as media without loading
Try to load a file as an image first, then as a video.
Encode raw bytes to a base64 string.
Create multimodal message content with text, images, and videos.
Move legacy state entries from config_dir into state_dir.
Idempotent: each entry is skipped when the destination already exists (the migration ran on a prior invocation) or when the source does n
Return bounded canonical JSON and its SHA-256 fingerprint.
Fingerprint value with the canonical workspace serialization.
Resolve a client-supplied cwd into a canonical workspace binding.
cwd is untrusted and is validated here. workspace_config is not: every
caller passes server-resolved policy. A client claim is ve
Read the persisted comparison snapshot recorded for a binding.
Name the project-scoped fields that drifted from their binding.
The refusal these feed is safe either way, but it is not diagnosable without the field names: the resolution reads the extension trust
Atomically create or verify a thread workspace binding.
Read a thread's durable workspace binding.
Validate run context against the durable workspace binding.
Return the ordered reasoning effort levels supported by model_spec.
Return profile efforts compatible with the effective thinking mode.
Return the profile's reasoning effort default independently of its levels.
Return whether effort is a supported level for model_spec.
Return whether canonical or native effort parameters are present.
Read canonical or native effort settings using integration precedence.
This compatibility reader does not modify the supplied parameters. It only
reports settings that may come from --model-params,
Remove canonical and native effort settings without changing siblings.
Replace existing effort settings with the standard flat parameter.
Resolve ${VAR} references in one MCP server's supported fields.
Interpolates the command, url, args, env, and headers
fields (see _interpolate_env for the reference syntax); every other
Narrow a persisted model-spec channel to a usable value.
Shared by _rubric_model_spec and _model_spec. INHERIT_RUBRIC_MODEL
passes through unchanged; callers compare the result against it thems
Narrow a persisted proposal kind to a known value.
Narrow a persisted goal-status value to a known GoalStatus.
A corrupt or forward-version checkpoint can carry an unexpected status
string (or a non-string). Coercing to None rather than passing t
Extract the allowlisted, reportable policy snapshot from a payload.
Build the snapshot persisted with a workspace binding.
Compare a persisted snapshot against the current one.
Fields present in the snapshots are compared with values; fields named in
changed_names (e.g. fingerprint-only or path-valued fields detected b
Join Content lines with newlines (Content.join is instance-level).
Render workspace refusal diagnostics as markup-safe TUI content.
Every dynamic value (field names, allowlisted values) flows through
Content.from_markup $var substitution, so square brackets in a
Mark a graph invocation as an interrupt-resume round when it is one.
A turn's initial run stays untagged, so the tag identifies continuations rather than the turn itself. Keep that asymmetry: tagging
Return whether installed package metadata is at least version.
Read the currently installed deepagents-code distribution version.
Unlike __version__, this does not come from the module this process
imported at launch: it reads the running tool environment's
Return cached pre-release-pin status, or None without a fresh answer.
Check for updates using only a fresh local cache entry.
This is the startup fast path: it never contacts PyPI. Stale, missing, corrupt, or unparsable cache data is treated as "no cached update answer
Return the epoch time of the last PyPI update check, or None.
Reads the checked_at stamp recorded in CACHE_FILE when the update cache
is written (primarily by get_latest_version; also seeded
Return whether a recorded check stamp is still within CACHE_TTL.
Lets status surfaces tell "the cache expired" apart from "the cache is current but holds no usable answer for this install" — states
Fetch the latest deepagents-code version from PyPI, with caching.
Results are cached to CACHE_FILE to avoid repeated network calls.
The cache stores both the latest stable and pre-release versions
Return the targeted pre-release pins installing version requires.
A stable deepagents-code release may mandate an exact pre-release
dependency (for example deepagents==0.7.0a7). This resolves t
Return whether installing version needs uv pre-release admission.
Boolean view over release_prerelease_pins, kept for display-only callers
that only decide whether to show a pre-release-aware u
Return the cached ISO-8601 upload time for version, or None.
Only versions captured during a prior get_latest_version call are
available; unknown versions, or a None input, return None.
Return a human-readable age for version (e.g., 'released 3d ago').
Returns an empty string when the upload time is unknown (cache entry
lacks release_times for this version, or a None version
Return ", released Nd ago" for version, or "" when unknown.
The ", " separator is included so callers can splice the age into a
parenthetical unconditionally — if the age is unknown, the empt
Return " (released Nd ago)" for version, or "" when unknown.
Return " (N days old)" for installed versions at least a week old.
Return whole days since the installed version's release, or None.
Cache-only (get_release_time), so it never blocks on the network.
Returns None when the release time is unknown (cold cache or
Return whether an older installed version should warn about updating.
True only when a fresh cache says an update is available and the installed
version's release is at least `INSTALLED_STALE_NOTIC
Return the ISO-8601 upload time for deepagents SDK version.
Reads from CACHE_FILE under sdk_release_times, falling back to a
single PyPI fetch on cache miss and writing the result back so
sub
Return a human-readable age for SDK version (e.g., 'released 3d ago').
May trigger a single PyPI fetch on cache miss (3s timeout). Returns an empty string on any failure so callers can concatenat
Return ", released Nd ago" for SDK version, or "" when unknown.
The ", " separator is included so callers can splice the age into a
line unconditionally — if the age is unknown, the empty str
Return whether a resumed session is still in its update grace period.
The first resumed launch starts a fixed grace period. Later resumes do not extend it, so a resume-only workflow eventually follow
Reset the resume grace period after a normal interactive launch.
Return whether startup auto-update should skip a recently failed version.
Persist a same-version startup auto-update retry cooldown marker.
Clear a startup auto-update failure marker for version if present.
Return whether the user should be notified about version latest.
Throttles notifications to at most once per CACHE_TTL period for a
given version, preventing repeated banners every session.
Record that the user was notified about version latest.
Writes into the shared update state file so a subsequent
should_notify_update call can suppress duplicate banners.
Clear the "already notified" marker so the update modal re-opens next launch.
Removes both notified_at and notified_version from the shared
update state file.
Check whether a newer version of deepagents-code is available.
When the installed version is a pre-release (e.g. 0.0.35a1),
pre-release versions on PyPI are included in the comparison so alpha
test
Detect how deepagents-code was installed.
Checks sys.prefix against known paths for uv and Homebrew.
Return the shell command to upgrade deepagents-code.
Falls back to the documented uv command for display-only guidance.
Return whether pre-release upgrades are supported for the install method.
Pre-release channel switching is only safe for uv tool installs, where
uv tool upgrade --prerelease allow re-resolves aga
Return whether a dependency-only refresh is possible for the install.
A dependency refresh reinstalls the current deepagents-code version with
upgraded dependency resolution (`uv tool install -U
Return the shadowing dcode entry point on the user's PATH, if any.
After a successful uv tool upgrade, the upgraded binary only takes effect
on the next manual launch if the user's PATH resolves
Best-effort detect_shadowed_dcode that never raises.
The shadow check only ever runs to decorate an already-successful upgrade, so a defect in detection — or an unexpected error escaping the narrow
Render a user-facing warning for a shadowed-dcode situation.
Shared by the /update slash command, the update-notification "Install
now" action, and the pre-launch auto-update path so the wording st
Return a session-scoped shell command to prefer the upgraded shim.
The command targets the shell that matches the current platform: PowerShell
on Windows (where _uv_tool_bin_dir can resolve `%USERP
Remove old update logs while preserving the newest recent logs.
Return a new timestamped update log path and clean stale logs.
Create an empty update log file and return its path.
Callers that advertise the log to a user — "Update log: tail -f create_update_log_path, which only compute
Return a copy-pasteable command for following a log file as it is written.
Try to claim the exclusive right to self-upgrade dcode.
Startup auto-update, dcode update, /update, and the update notification
all replace the same installed package, so concurrently launched te
Attempt to upgrade deepagents-code using the detected install method.
Only tries the detected method — does not fall back to other package managers to avoid cross-environment contamination.
Refresh dependencies while keeping deepagents-code on this version.
Runs uv tool install -U deepagents-code==<current> instead of
uv tool upgrade deepagents-code, so compatible dependency relea
Resolve a dependency refresh plan without mutating the tool environment.
uv tool install has no --dry-run, so this targets the running tool
environment with `uv pip install --dry-run --python <sy
Parse package version changes from uv's environment-diff output.
uv reports environment changes as paired - pkg==old / + pkg==new
lines; this collapses them into one DependencyChange per pack
Render dependency changes as an aligned, human-readable block.
Return whether extra is safe to embed in package-extra syntax.
Return whether package is safe to embed in a --with install command.
Return the uv command that upgrades dcode while clearing stale pins.
Built specifically to avoid the uv tool upgrade receipt-pin trap: when
the tool was originally installed via `uv tool install de
Return the uv command that refreshes deps for the current dcode version.
Return the uv command that plans a dependency refresh without installing.
Return the shell command that adds a package to the dcode tool env.
The result is built for execution (via perform_install_package), not for
display — surfacing raw uv tool invocations to the u
Return the install-script command that installs dcode extras.
Return the install-script command that adds extra to dcode.
The promoted install path is the install script (see scripts/install.sh).
This helper is display-only and avoids uv receipt introspecti
Return a manual recovery command for the current install method.
uv-managed installs can preserve the uv receipt's Python interpreter and
--with requirements, so their recovery command uses the sam
Return a manual recovery command, never raising.
Wraps install_extra_recovery_command so recovery-hint call sites never
let a second failure (validation, uv-receipt introspection, or unexpected
met
Return the selected extras this install can actually remove.
Shared by the CLI and TUI uninstall help so both list the same set:
receipt-selected extras minus targets removal refuses.
A directly s
Return the receipt-preserving command that removes one selected extra.
Return the action hint for removing an extra from an editable install.
The result embeds a literal deepagents-code[<extra>], so callers that print
it through Rich markup must escape it first — the
Return why the install method cannot remove extra, if applicable.
The editable check is separate from detect_install_method: an editable
checkout installed under a uv tool prefix is reported as `
Return the canonical action hint for editable installs missing an extra.
Shared by every site that detects an editable install and points the user
at the correct uv tool install --editable invocati
Return the canonical action hint for editable installs needing a package.
Editable installs can't have packages added automatically, so this points the user at adding it to their own development envi
Add extra to the installed dcode tool environment.
Runs uv tool install --reinstall -U 'deepagents-code[<extras>]==<current>' --prerelease allow, preserving any extras that are already installed.
Remove extra by rebuilding the current uv-managed tool environment.
The install lock covers both receipt inspection and uv execution, so a concurrent upgrade, install, or removal cannot rebuild fro
Add an arbitrary package to the installed dcode tool environment.
Runs uv tool install --reinstall -U 'deepagents-code[<extras>]==<current>' --with <package> --prerelease allow, the escape hatch
Return whether update checks are enabled.
Managed config decides first: [update].check in managed_config.toml
outranks both layers below, and a managed file that cannot be parsed
forces False.
Return whether auto-update is enabled.
Editable installs are always disabled, before any layer is consulted.
Otherwise managed config decides first: [update].auto_update in
managed_config.toml ou
Persist the auto-update preference to config.toml.
Writes [update].auto_update so the setting survives across sessions.
Return whether an explicit auto-update preference is in force.
True when managed policy decides the value, when
DEEPAGENTS_CODE_AUTO_UPDATE holds a recognized boolean, or when
`[update].auto_upda
Return whether to show the one-time auto-update default migration notice.
True when no explicit env/config preference is set (so auto-update is on
only implicitly, via the opt-out default) and th
Record that the one-time auto-update default migration notice was shown.
Return the last version the user saw the "what's new" banner for.
Record that the user has seen the "what's new" banner for version.
Return True if this is the first launch on a newer version.
Load async subagent definitions from config.toml.
Reads the [async_subagents] section where each sub-table defines a remote
LangGraph deployment:
[async_subagents.researcher]
description
Return a sorted list of available agent names from ~/.deepagents/.
Scans the user's .deepagents directory and returns each real
subdirectory that contains the AGENTS.md agent marker and is not
List all available agents.
Reset an agent to default or copy from another agent.
Build the ### Model Identity section for the system prompt.
Get the base system prompt for the agent.
Loads the base system prompt template from system_prompt.md and
interpolates dynamic sections (model identity, working directory,
skills path, and executio
Return ordered skill sources for PluginSkillsMiddleware and audit tooling.
Lowest to highest precedence: built-in -> plugins -> user .deepagents -> user .agents -> project .deepagents -> project .age
Create a CLI-configured agent with flexible options.
This is the main entry point for creating a Deep Agents Code agent, usable both internally and from external code (e.g., benchmarking frameworks).
Persist one local node delta before its graph update returns.
Discover models in the caller's active environment without constructing them.
Encode the selected values of a multi_select answer for the wire.
The answer stays one string so answers: list[str] keeps one slot per
question, positionally matched. JSON is self-delimiting, so
Decode a multi_select answer produced by encode_multi_select_answer.
Return whether an ask_user answer counts as "no answer".
The single definition of emptiness for an answer, shared by the TUI (which blocks submitting a required question) and by the Auto authorizat
Render the placeholder answer recorded for every question on failure.
Render questions and answers as the Q:/A: transcript.
This is the text the ask_user tool returns to the model and persists in the
thread. The TUI renders that authoritative text literally, exce
Re-render a transcript with multi_select answers unpacked for a human.
The transcript is built for the model, where a multi_select answer is a
JSON array. A person reading the same text sees the
Format a duration in seconds into a human-readable string.
Read macOS's "24-Hour Time" preference (AppleICUForce24HourTime).
macOS exposes the clock style as a global preference that does not surface
through the POSIX LC_TIME locale (libc %X is 24-hour
Whether the system is configured for a 24-hour clock.
On macOS the clock style lives in the AppleICUForce24HourTime system
preference rather than the POSIX locale, so that is consulted first (see
`
Format a message timestamp for display.
Shows only the time of day for messages from the current local date and prefixes the date otherwise. The 12- versus 24-hour clock follows the system configurat
Gather every diagnostic section in display order.
Run dcode doctor, printing diagnostics as text or JSON.
Map a raw ToolMessage.status to the two-value hook domain, fail-closed.
"error" and "success" pass through. Any other present value — a future
provider status, an explicit None, or a typo —
Compute a stable key for buffering an in-progress streamed tool call.
Prefers the streaming index (stable across fragments of one call), then
the tool-call id, falling back to a positional placeh
Classify buffered tool calls that never emitted a tool.use.
Both surfaces log the same end-of-stream diagnostic for tool calls still in their buffer map when the stream ends: those whose args never
Build the tool.use hook payload (schema documented in hooks).
Build the tool.error hook payload (schema documented in hooks).
Build the tool.result hook payload (schema documented in hooks).
tool_output is capped to HOOK_TOOL_OUTPUT_LIMIT here so both surfaces
apply the identical cap regardless of where the raw outp
Erase spend in the caller's thread-deletion transaction.
Retain only an ID tombstone to discard pending retries and late provider completions, including answers that have not written their first char
Retry pending settlements and read the durable subtotal.
Save completed usage before delivering an answer or finishing cancellation.
Classify a streamed model request for cost and usage breakdowns.
Finalize canonical records and expose message aliases for unscoped replay.
Record usage attached to one streamed model message.
A request is entered in recorded_requests only once usable token metadata
has been recorded for it. Callers retain that ledger across stream rou
Report whether a custom-stream payload is a nested model-usage event.
Lets a client consume its own event whatever record_model_usage_event made
of it. A duplicate of a request the message stream a
Record a validated provisional usage event from a nested model call.
Format a token count into a human-readable short string.
Format an estimated USD cost for compact display.
Format a speculative USD cost as a rounded, approximate upper bound.
Used where the figure is a worst-case estimate rather than recorded spend (e.g. the cold-cache warning modal, whose cache may be p
Return whether the session usage table should be rendered.
Controlled by [ui].show_usage_stats or DEEPAGENTS_CODE_SHOW_USAGE_STATS.
Both the TUI teardown and the headless run call this rather tha
Print a model-usage stats table to a Rich console.
Each row shows the serving provider alongside the model name. When the session spans multiple models each gets its own row with a totals row appende
Return whether offload history is routed to non-persistent storage.
True when the persistent ~/.deepagents location was unwritable and the
most recent _offload_fallback_root fell back to a temp
Delete conversation-history archives older than the configured retention.
Remove a thread's compaction archive and handoff recovery snapshots.
Deletes the per-thread markdown file written by the local-mode
conversation_history backend (`{root}/conversation_history/{threa
Concatenate all section functions into the full detection script.
Independent sections run as parallel background jobs writing to temp files, then results are concatenated in the original display ord
Return a Textual Unix driver class that renders through stdout.
Textual's LinuxDriver writes every frame to sys.__stderr__, while
TerminalStderrGuard points fd 2 at /dev/null — so under an ac
Return the construction-scoped environment or the live process environment.
Bind an immutable environment snapshot for the duration of the block.
The binding is a ContextVar, so it is copied into asyncio.to_thread
workers, and it ends when the block exits. Anything that
Resolve a LangSmith endpoint shorthand to its canonical URL.
Maps the case-insensitive region aliases us/eu to the LangSmith SaaS
endpoints so the CLI --base-url flag and the TUI /auth prompt
Return whether value is a non-empty http/https URL with a host.
Guards the LangSmith endpoint so a stored API key is never paired with a non-HTTP, malformed, or schemeless value that could rout
Publish a workspace's tracing settings to the process environment.
Redaction and project naming decide from the active workspace snapshot, but
the LangSmith SDK reads os.environ directly. Left to d
Return and clear the pending orphaned-tracing notice, if any.
Extract caller API keys from the validated LangSmith settings carrier.
Restore launch and project-dotenv LangSmith settings for user commands.
Precedence, highest first: the launch shell the user started dcode from,
then the project .env. The global profile .env i
Apply a /auth-stored LangSmith key, tracing, and redaction now.
Return the longest mode prefix and mode for text, if any.
Longer prefixes win so multi-character triggers like !! are matched
before their single-character prefixes (!).
Get the glyph set for the current charset mode.
Reset the glyphs and charset-mode caches (for testing).
Check whether the terminal is in ASCII charset mode.
Convenience wrapper so widgets can branch on charset without importing
both _detect_charset_mode and CharsetMode.
Return the terminal-appropriate label for the newline keyboard shortcut.
Prefers Shift+Enter when the terminal is known to support the kitty
keyboard protocol, either via conservative terminal-iden
Get the appropriate banner for the current charset mode.
Build the shared coding-agent-v1 trace-metadata block.
Implements the coding-agent-v1 contract for Deep Agents Code:
one helper that stamps the identity block, plugin/runtime versions, turn
markers
Build the LangGraph stream config dict.
Stamps the shared coding-agent-v1 trace-metadata contract via
build_coding_agent_metadata — identity block, plugin/runtime versions,
turn markers, and repo
Parse shell allow-list from string.
Parse an already-split shell allow-list.
Unlike parse_shell_allow_list, this takes separate elements so no comma
reparsing occurs — a command name containing a comma (valid on POSIX)
survives intac
Return retry diagnostics and the retry kwarg dcode will force.
Return the managed-policy block notice a reload reported, if any.
Check if a command contains dangerous shell patterns.
These patterns can be used to bypass allow-list validation by embedding arbitrary commands within seemingly safe commands. The check includes bot
Check if a shell command is in the allow-list.
The allow-list matches against the first token of the command (the executable name). This allows read-only commands like ls, cat, grep, etc. to be auto-
Resolve the LangSmith project name if tracing is configured.
Checks for the required API key and tracing environment variables. When both are present, resolves the project name with priority: `creden
Report an empty prefixed override that is suppressing a LangSmith key.
/trace shows a generic "not configured" hint whenever no key resolves, but
a common footgun is exporting `DEEPAGENTS_CODE_LANG
Return whether the app-specific tracing override explicitly opts out.
Return whether LangSmith secret redaction is enabled for agent traces.
Return whether the agent should proactively save learnings to memory.
Resolves the memory.auto_save option from env/config.toml, defaulting to
enabled. When disabled, memory is still loaded into
Return whether Shift+Tab may enter unrestricted YOLO mode.
Resolves the startup.yolo_switcher option from env/config.toml,
defaulting to enabled. When disabled, the interactive cycle stays Manual
Return whether OpenAI model calls should carry a per-thread cache key.
Resolves the models.openai_prompt_cache_key option from env/config.toml,
defaulting to enabled. When disabled, `Configurable
Resolve the Auto classifier spec and any reason it was ignored.
Reads the models.auto_classifier option from managed policy, then env,
then config.toml. None means the classifier inherits the m
Return the default Auto classifier model for a main-model provider.
Resolve an unset Auto classifier after the main provider is known.
Resolve the model spec the Auto approval classifier should use.
Resolve whether Auto mode applies generated goal criteria without review.
Install the LangSmith SDK secret anonymizer for active agent tracing.
This is a fail-closed security control: when redaction is requested but the redacting client cannot be installed, tracing is disa
Extra LangSmith project names to dual-write agent traces to.
Parses DEEPAGENTS_CODE_LANGSMITH_REPLICA_PROJECTS (comma-separated) into a
de-duplicated, order-preserving list.
The single extra LangSmith project to mirror agent runs to, if configured.
dcode agent runs execute inside the LangGraph server subprocess, so the only way to mirror them to another project is the se
Summarize LangSmith tracing configuration for diagnostics.
Reads only the local environment and the active LangSmith profile; never contacts the network and never exposes secret values. All fields ar
Fetch the LangSmith project URL, raising on any failure.
Successful results are cached at module level so repeated calls do not make additional network requests.
The network call runs in a daemon th
Fetch the LangSmith project URL, returning None on any failure.
Thin back-compat wrapper around fetch_langsmith_project_url_or_raise
for passive callers (status banners, non-interactive output) tha
Build a full LangSmith thread URL if tracing is configured.
Combines get_langsmith_project_name and fetch_langsmith_project_url
into a single convenience helper.
Build a LangSmith thread URL only when its project URL is cached.
This non-blocking variant lets transient UI surfaces render a previously resolved link immediately without repeating or scheduling an
Reset the LangSmith URL cache (for testing).
Get the default coding agent instructions.
These are the immutable base instructions that cannot be modified by the agent. Long-term memory (AGENTS.md) is handled separately by the middleware.
Auto-detect provider from model name.
Intentionally duplicates a subset of LangChain's
_attempt_infer_model_provider because we need to resolve the provider
before calling init_chat_model in
Translate an argument/env-name table into explicit constructor kwargs.
The first name that lookup resolves to a non-empty value wins.
Create a chat model.
Uses init_chat_model for standard providers, or imports a custom
BaseChatModel subclass when the provider has a class_path in config.
Supports provider:model format (e.g
Validate that the model has required capabilities for deepagents.
Checks the model's profile (if available) to ensure it supports tool calling, which is required for agent functionality. Issues war
Collect version facts for the running deepagents-code distribution.
Collect version facts for the installed deepagents SDK distribution.
Editable SDK installs prefer the source tree's _version.py; everything
else reports the installed metadata version. Distinguis
Return the base deepagents requirement declared by deepagents-code.
Reads the installed distribution's Requires-Dist metadata and parses each
entry with packaging.Requirement, returning the a
Collect the offline version report used by --version, /version, and doctor.
Return the source/metadata drift annotation for the CLI version line.
Editable status is surfaced separately by every caller (the dedicated
Editable install: line on --version//version, and the
Return the workspace/editable/drift/mismatch SDK version annotation.
Resolve the diagnostic deepagents SDK version.
Compatibility wrapper for callers that only need one SDK version string and
lookup status. Every editable install carries an +editable local segment
Return the composite extras that expand to extra.
Render the installable extras grouped by category as plain text.
Drives the no-argument /install slash-command help so users can
discover valid extras without consulting pyproject.toml. Sourced f
Return ready optional dependencies grouped by extra.
Reads Requires-Dist metadata from the named distribution, groups the
entries gated by extra == "..." markers under their extra name, and
resol
Return extras with at least one installed dependency.
Deliberately looser than get_extras_status, which requires every declared
package to be present. Callers here rebuild install commands, so a pa
Return installed and missing optional dependencies grouped by extra.
Return the installable extra that declares a package.
Resolves recovery hints from the package that is actually missing instead of guessing from a provider identifier. For example, `langchain-google-
Resolve how to recover from a missing provider package.
Centralizes the extra_for_package -> install_package_command fallback so
the TUI startup hint and the model-initialization error path rende
Check that langchain-quickjs is installed for the interpreter.
Uses importlib.util.find_spec for a lightweight check with no actual
imports. Call this in the app process before spawning the ser
Render an ExtrasStatus mapping as column-aligned plain text.
Suitable for stdout in non-interactive contexts (e.g. the --version
CLI flag) where a markdown renderer is unavailable.
Return (package, version) pairs for the core ecosystem dependencies.
Render core ecosystem dependency versions as column-aligned plain text.
Suitable for stdout in non-interactive contexts (e.g. the --version
CLI flag) where a markdown renderer is unavailable.
Render core ecosystem dependency versions as a markdown fragment.
Render an ExtrasStatus mapping as a markdown fragment.
Return the (status_label, detail) display pair for an unavailable server.
Shared by the CLI (client.commands.tools._print_unavailable_servers) and
TUI (app._render_tool_catalog) renderers so bo
Enumerate the built-in tools the agent binds by default.
Compiles the agent with an offline placeholder model and reads the bound tool node. Memory and skills are disabled because they contribute no
Read tools from a local compiled agent when its graph is inspectable.
LangGraph does not expose a public tool-enumeration API, so this reaches through the compiled graph's conventional `nodes["tools"
Discover MCP servers, split into tool groups and unavailable servers.
Best-effort: if discovery itself raises (no config, offline, load error), the technical detail is logged and a generic `mcp_error
Split loaded MCP server metadata into tool groups and unavailable servers.
Pure function shared by the CLI discovery path (collect_mcp_catalog) and
the interactive /tools command, which passes th
Assemble a ToolCatalog from pre-collected built-in tools and live MCP info.
The interactive /tools command entry point: it avoids the asyncio.run
MCP discovery reached via collect_catalog (th
Collect everything dcode tools list renders.
Classify a raw env-var string as a truthy, falsy, or unrecognized token.
The single source of truth for which strings count as boolean on/off
values; is_env_truthy and the config resolver both buil
Return whether env var name is set to a recognizably truthy value.
Unlike bool(os.environ.get(name)), this does not treat "0" or
"false" as enabled. Use this for on/off flags where the user w
Generate a safe name using the selected model without conversation callbacks.
Cancellation waits for model initialization, which can update process-wide provider settings, even if the generation time
Return the first-run onboarding marker path.
Return whether the user has completed onboarding.
Persist that onboarding has completed.
Return the goal criteria preference prompt marker path.
Return whether the goal criteria preference prompt was answered.
Persist that the goal criteria preference prompt was answered.
Persist the optional onboarding name into user agent memory.
Empty or whitespace-only names are skipped (no file is written).
Return the managed onboarding name block (markers included) if present.
Remove every onboarding-name marker occurrence from text.
A partial edit can leave a lone start or end marker behind. Stripping all marker strings before re-inserting the managed block keeps re-ins
Return whether onboarding should open at interactive startup.
DEEPAGENTS_CODE_ONBOARDING overrides the marker in both directions: a
truthy value forces the flow open on every startup, and a falsy v
Truncate a string value if it exceeds max_length.
Identify skill-file reads.
Format tool calls for display with tool-specific smart formatting.
Shows the most relevant information for each tool type rather than all arguments.
Convert ToolMessage content into a printable string.
Return the command name this process was launched with.
Cached: sys.argv[0] and the launch environment are fixed for the life of
the process. Tests that vary either must call `invoked_name.cache_cl
Note a non-standard launch name in the Debug Console, once per process.
Cached so repeated calls cannot repeat the note; tests that vary the launch environment must call `log_nonstandard_invoked_name
Build trusted classifier metadata for a client-created user message.
Return whether an MCP tool has coherent read-only annotations.
Return whether a tool carries dcode's MCP wrapper marker.
Return MCP names that require Manual or Auto review.
Return a compact reason safe for persistence, logs, and UI rendering.
Build a safe agent/UI reason for a failed auto classifier call.
Provider exception text stays out of the reason (it can carry secrets or noisy HTML). Only real local deadline expiry (`_ClassifierDead
Create a private OS-temp text file for this request.
Use this instead of write_file when a command needs a temporary input
file, such as a pull-request body passed with --body-file. Dcode chooses
Delete one exact OS-temp artifact created for this request.
Create the ephemeral server-side criteria agent graph.
Create the goal-only fallback agent for criteria generation.
This agent has no context tools, repository access, or HITL: it drafts acceptance criteria from the goal message alone. `GoalCriteriaMiddl
Restore iTerm2 cursor guide when launch-time profile state required it.
Return the read-only theme registry, building it on first access.
Lazy so that theme.py can be imported on the deepagents --help cold
path without pulling in textual.theme.BUILTIN_THEMES (which
Rebuild the theme registry from disk.
Re-reads ~/.deepagents/config.toml for user-defined themes so that
/reload can pick up config changes without restarting the app.
Return custom CSS variable defaults for the given mode.
Most styling is handled by Textual's built-in CSS variables ($primary,
$text-muted, $error-muted, etc.). This function only returns
app-
Return the ThemeColors for the active Textual theme.
For custom themes (LangChain-branded and user-defined), the pre-built
ThemeColors from the registry is returned directly. For Textual built-i
Return the bounded retention bucket key for a log level name.
Attach the in-memory buffer handler to target (idempotent).
Lowers target's level to at most INFO so the console shows a useful tail
even when DEEPAGENTS_CODE_DEBUG is off; never raises the l
Return the installed buffer handler.
Resolve an MCP config dict for login without printing anything.
Pull server out of a resolved config and validate its shape.
Build the CLI-style hint for an unreadable user trust policy.
Surfaced by dcode mcp login so a config.toml read failure is never
swallowed just because a user-level config or an env-enabled serve
Build the CLI-style hint string for skipped project server entries.
Build the CLI-style hint for servers dropped by the legacy-key removal.
Mirrors the resolve_and_load_mcp_tools migration message so
non-interactive dcode mcp login explains why a previously allow
Build the CLI-style hint for the renamed, now-ignored env var.
Mirrors format_legacy_ignored_notice for the env surface so a user who
still exports DEEPAGENTS_CODE_ENABLED_PROJECT_MCP_SERVERS lea
Build the CLI-style hint for dropped malformed saved approvals.
Mirrors format_legacy_ignored_notice so non-interactive dcode mcp login
explains why a previously-approved server stopped loading (
Build the CLI-style hint for discovered configs that failed to load.
Surfaced by dcode mcp login on a partially successful resolution so a
broken .mcp.json is reported instead of silently dropped
Extract @file mentions and return the text with resolved file paths.
Parses @file mentions from the input text and resolves them to absolute
file paths. Files that do not exist or cannot be resol
Parse a paste payload that may contain dragged-and-dropped file paths.
The parser is strict on purpose: it only returns paths when the entire paste payload can be interpreted as one or more existing
Parse dropped-path payload variants through one entrypoint.
Parsing order is:
parse_pasted_file_paths)Return whether a payload has the shape a terminal uses for a file drop.
Terminals deliver a dragged file as an absolute path (POSIX or Windows
drive/UNC), a ~/ path, or a file:// URL, so requirin
Return resolved file paths from a payload that looks like a file drop.
Applies parse_pasted_path_payload — the same parser the chat input's drop
handling uses, which only resolves paths that exist
Parse and resolve a single pasted path payload.
Unlike parse_pasted_file_paths, this helper only accepts one path token
and is intended for fallback handling when a paste event carries a
single pat
Extract and resolve a leading pasted path token from input text.
This is used for submit-time recovery when a user message starts with a path token followed by additional prompt text.
Normalize pasted text that may represent a single filesystem path.
Supports:
file:// URLsExtract renderable reasoning text from a content block.
Add a --json flag to an argparse parser.
Write a JSON envelope to stdout and flush.
The envelope is a single-line JSON object with a stable schema:
{"schema_version": 1, "command": "...", "data": ...}Format ISO timestamp for display (e.g., 'dec 05, 6:10pm').
Format ISO timestamp as relative time (e.g., '5m ago', '2h ago').
Format a filesystem path for display.
Paths under the user's home directory are shown relative to ~.
All other paths are returned as-is.
Get path to global database.
The result is cached after the first successful call to avoid repeated filesystem operations.
Generate a new thread ID as a full UUID7 string.
List threads from checkpoints table.
Populate checkpoint-derived fields for an existing thread list.
This is used by the /threads modal to enrich rows in one background pass,
so the latest checkpoint is fetched and deserialized at mos
Prewarm thread selector cache for faster /threads open.
Fetches a bounded list of recent threads and populates checkpoint-derived fields for currently visible columns into the in-memory cache. Inte
Get cached recent threads, if available.
Apply cached message counts onto thread rows when freshness matches.
Apply cached initial prompts onto thread rows when freshness matches.
Get the most recent thread, optionally agent-filtered and/or excluding a thread.
List distinct threads in checkpoint recency order, optionally agent-filtered.
Get the latest stored update timestamp for a thread.
Advance local discovery metadata after reading remote model activity.
Only the latest root checkpoint is updated, preserving historical metadata and any newer timestamp already written by a shared se
Get agent_name for a thread.
Get the most recently stored cwd for a thread.
Check if a thread exists in checkpoints.
Find threads whose IDs start with the given prefix.
Validate a thread name.
Read a thread's durable name independently of checkpoint revisions.
Atomically name an existing thread without mutating its conversation.
Delete thread checkpoints, side-question costs, and offloaded history.
Removes the thread's checkpoint/write rows, then makes a best-effort attempt to remove the per-thread compaction archive and han
Get a checkpointer requiring live thread ownership for database writes.
Index a remote handoff locally with its initial summary and resume metadata.
Only seed an absent thread; never replace shared server checkpoints. Thread history still loads from the connected agent,
Persist discovery and resume metadata on a newly checkpointed thread.
The remote state-update API does not forward config metadata. Stamp the saved checkpoints before exposing a newly seeded thread t
Read the thread listing limit from the environment.
CLI handler for deepagents threads list.
Fetches and displays a table of recent conversation threads, optionally filtered by agent name, git branch, or working directory.
CLI handler for: deepagents threads delete.
Return autocomplete entries for slash commands.
Extract skill name and args from a /skill:<name> command.
Build autocomplete entries for discovered skills.
Each skill becomes a /skill:<name> entry with its description
and the skill name as a hidden keyword for fuzzy matching. Plugin skills
keep their n
Copy text to the system clipboard.
Copy text to the clipboard and surface the outcome as a toast.
Centralizes the copy-then-notify pattern shared by the Ctrl+C and
[ COPY ] paths so the success/failure messaging stays consistent.
Copy selected text from one screen's widgets to the clipboard.
Selections live on the screen that owns them (Screen.selections) and
survive a modal being pushed on top, so a scan has to target exac
Return the resolved path to the credential store (auth.json).
Resolved at call time (not import time) so tests can redirect storage by monkeypatching `deepagents_code.model_config.DEFAULT_STATE_DIR
Return all stored credentials keyed by provider name.
Return the stored API key for provider, or None if unset.
Returns None for stored OAuth credentials too — callers that need
OAuth tokens should read load_credentials() directly and narrow on
Return the base URL paired with provider's stored key, or None.
Returns None both when no key is stored and when a key is stored without
an accompanying base URL (the user left the field blank,
Return the LangSmith project paired with provider's stored key, or None.
Returns None when no key is stored and when a key is stored without a
custom project (the user left the field blank, mea
Persist an API key for provider.
Empty / whitespace-only keys are rejected so callers don't accidentally
write a sentinel that masks a working environment variable (see
apply_stored_credentials i
Remove a stored credential for provider.
Return providers that currently have a stored credential, sorted.
Return ordinary text from a local or serialized message.
Return message metadata from a local or serialized message.
Return a message's lc_source value when present.
Return whether a local or serialized message has the human role.
Return whether a message is a goal-state notice or continuation.
Return whether a message claims to be a goal-state notice.
Return whether the latest human turn carries an unsaved goal fallback.
Return whether a message should be omitted from derived transcripts.
Return whether a message is hidden from user-facing session history.
Return whether a message carries SDK-pinned skill instructions.
The SDK appends this message after the user prompt that requested the pin, so lookups for the latest user turn must skip it.
Build a one-time goal continuation.
Return a valid absolute cutoff index from a summarization event.
This is the canonical explanation of the cutoff rule; the notice predicates
and the /offload accounting point here rather than resta
Return the absolute cutoff index of a _summarization_event.
The degrading variant of validated_summarization_cutoff, which documents the
rule and why an out-of-bounds cutoff is rejected rather th
Record that a restored summarization event was discarded.
Dropping the event also drops its summary_message, so the next request
re-sends the whole untrimmed history. That is a large, silent token
Project authoritative channels into deterministic notice state.
Serialize authoritative notice state with canonical JSON formatting.
Return a stable digest for authoritative goal/rubric state.
Return whether state contains a goal or an active rubric.
Select the user-controlled text a notice built from projected embeds.
The objective and status note are withheld unless the goal is actionable, while criteria are embedded whenever a rubric is acti
Return why state cannot render as a safe notice, or None when it can.
Collapses the project-then-validate sequence its callers each performed separately. Their correctness depended on all of them
Build one canonical append-only goal/rubric state notice.
Return validated canonical notice metadata from a message.
Return the newest valid notice and its raw-history index.
Return the newest goal-state source index, including invalid messages.
Return whether embedded goal-state text violates current size limits.
Build a bounded same-index stand-in for an oversized prior notice.
An oversized notice must stop being model-visible, but it cannot be removed from a model request. The summarizer picks its cutoff fr
Best-effort write of a terminal control sequence.
Prefers /dev/tty so the sequence reaches the terminal even when stdout
or stderr are redirected. Falls back to sys.__stderr__ only if it is a
TTY
Write an OSC <command>;<payload> sequence.
Set the terminal's OSC 9;4 progress indicator.
Fires unconditionally — terminals that don't recognize OSC 9;4 silently
ignore the sequence. Set DEEPAGENTS_CODE_NO_TERMINAL_ESCAPE=1 to opt out
e
Clear the terminal's progress indicator.
Emits OSC 9;4;0;0.
Set the terminal's dynamic default background color with OSC 11.
This is cosmetic and intentionally best-effort. Terminals that don't
support OSC 11 ignore it. OSC 111 restores the default back
Reset the terminal's dynamic default background color with OSC 111.
This is a no-op when set_terminal_background never succeeded, so the app
does not send a restore for a background it did not ch
Detect deceptive or hidden Unicode code points in text.
Remove known dangerous/invisible Unicode characters from text.
Neutralize control characters and deceptive Unicode in untrusted text.
Untrusted strings (MCP server errors, config-file contents, tool output) can carry ANSI escape sequences, other control characte
Render hidden Unicode characters as explicit markers.
Example output: abc<U+202E RIGHT-TO-LEFT OVERRIDE>def.
Summarize Unicode issues for warning messages.
Deduplicates by code point. When more than max_items unique entries exist,
the summary is truncated with a +N more entries suffix.
Join safety warnings into a display string with overflow indicator.
Check a URL for suspicious Unicode and domain spoofing patterns.
Flatten nested dict/list structures into key-path/string pairs.
Return whether a key path suggests URL-like content.
Normalize line breaks and escape markdown syntax in external text.
Estimate tokens using the same four-characters-per-token rule as whip.
Approximate the memory fragment after middleware strips HTML comments.
Format skills locations matching SkillsMiddleware display.
Approximate the progressive-disclosure skill index sent to the model.
Build a fresh-session audit and reconcile it with live usage when available.
Render a plain-text report.
Restore a typed recovery error, falling back to the ordinary log summary.
Report a server graph startup failure to the parent app process.
Emits the full traceback for logs/debugging, then a
single-line {STARTUP_ERROR_MARKER}{type}: {summary} line that
`server._extract_s
Return project-controlled paths for an explicit repository root.
Return the immutable launch-time user profile root.
Return the validated profile directory for an agent name.
Create the validated profile directory for an agent.
Return the user-level AGENTS.md path for an agent profile.
Return existing project-level AGENTS.md paths.
Return the user-level skills directory for an agent profile.
Create the user-level skills directory for an agent.
Return the project-level dcode skills directory, when in a project.
Create the project-level dcode skills directory.
Return the custom-subagent directory for an agent profile.
Return the project-level custom-subagent directory, when available.
Return the launch user's tool-agnostic ~/.agents directory.
Return the launch user's tool-agnostic ~/.agents/skills directory.
Return the project-level tool-agnostic .agents/skills directory.
Return the launch user's experimental ~/.claude/skills directory.
Return the project's experimental .claude/skills directory.
Return the directory containing skills bundled with dcode.
Classify a path as existing, missing, or unreadable.
Create directory and prove the process can write files inside it.
mkdir(exist_ok=True) only proves the directory exists; it succeeds on a
pre-existing root-owned directory. Creating a file is the
Return the first candidate directory that accepts a file.
Shared by the managed-bin and update-lock resolvers, which both walk a preferred-then-fallback pair. Callers keep their own "fell back" warni
Create a state directory and restrict it to its owner.
The state directory holds sessions.db and history.jsonl, which hold
full conversation content and are written with the default file mode. Th
Pin the resolved profile selection into a child environment.
Writes the resolved root, then sets or clears the defaulted/configured marker, so a child reconstructs the same snapshot the parent captur
Return the immutable launch-time user profile root.
Return a validated mode, failing closed to manual.
Return the next Shift+Tab approval mode for the active session.
The cycle is Manual → Auto → YOLO → Manual when both Auto and the YOLO switcher entry are available. Auto is omitted when `auto_eligibl
Return the store key for a thread's live approval mode.
Return the stored approval-mode payload.
Read a live approval mode from the server-side LangGraph Store.
Asynchronously read a live approval mode from a LangGraph Store.
The graph server supplies an async batched Store whose synchronous methods
reject calls from the event-loop thread. Prefer aget() fo
Persist approval mode through an agent's remote store client.
Return the installation-local acknowledgement file path.
Return whether the current unrestricted-mode warning was accepted.
Persist the current unrestricted-mode warning acknowledgement.
Merges into any existing approval state so first-run Auto notice fields are preserved. Concurrent saves are serialized with a cross-proc
Return whether the current Auto first-enable notice was already shown.
The notice self-versions on auto_notice_version and deliberately does not
gate on the top-level version (unlike `has_yolo_ac
Persist that the Auto first-enable notice was shown.
Merges into any existing approval state so YOLO acknowledgement fields are preserved. Concurrent saves are serialized with a cross-process lock. C
Return the number of newline characters in text.
Return whether text should be collapsed into a placeholder.
Collapses when the text exceeds the character threshold or the line threshold.
Format a paste placeholder reference string.
Replace all paste placeholders in text with their full content.
Placeholders whose IDs are not in pasted_contents are left unchanged.
Create or connect to a sandbox of the specified provider.
This is the unified interface for sandbox creation using the provider abstraction.
Get the default working directory for a given sandbox provider.
Check that the required packages for a sandbox provider are installed.
Uses importlib.util.find_spec for a lightweight check with no actual
imports. Call this in the app's process before spawning
Return the ChatGPT OAuth token store path.
Stored under Deep Agents' own state dir
(~/.deepagents/.state/chatgpt-auth.json) so the credential lives
alongside the rest of the app's state rather than
Return the current ChatGPT OAuth sign-in state.
Reads the on-disk token without triggering a refresh (a passive
inspect, suitable for switcher labels and the /auth manager). If a
refresh is neede
Return whether a ChatGPT OAuth token is stored on disk.
Delete the stored ChatGPT OAuth token.
Run the ChatGPT OAuth Authorization Code Flow with PKCE.
Reimplements the upstream langchain_openai.chatgpt_oauth browser
sign-in flow over its lower-level helpers, but routes the authorize-URL
dis
Construct a _ChatOpenAICodex model wired to the on-disk token store.
Return whether extension execution is trusted for a project.
Persist extension execution trust for a project.
Reject a backend route that violates host storage boundaries.
The sandbox check is deliberately shallow. Wrapping a filesystem backend
in another BackendProtocol implementation changes who owns tha
Validate late routes and flag graph-bound registrations for restart.
Load every authorized extension while isolating failures.
Retain the server-owned extension runtime for lifespan teardown.
Return sanitized metadata for the local provenance endpoint.
Run teardown callbacks while isolating individual failures.
Release server-owned extensions on the persistent event loop.
Return the user-wide loose-file extension directory.
Return the extension directory beneath project_root.
Resolve all authorized sources in deterministic load order.
Parse a project extension trust policy.
Resolve extension settings through the shared config generation.
Load one extension transactionally.
Return the provider policy that owns server_url.
Build environment variables exposed to plugin subprocesses.
Substitute plugin path variables in a string.
Substitute plugin variables throughout a JSON-compatible value.
Return a marketplace source safe for display.
Redact credentials from every HTTP URL embedded in text.
Parse a user-provided marketplace source.
Load a marketplace source and return its local install location.
Load a marketplace from either a cached directory or JSON file.
Return a marketplace manifest path under root, if present.
Resolve or materialize a marketplace plugin entry to a plugin root.
Explain why materialize_plugin_source produced no plugin root.
A rejected path and an unsupported source type both yield None, and
saying "unsupported source" for the first sends readers looking
Load a marketplace manifest from a root directory.
Split a plugin id in {plugin}@{marketplace} form.
Normalize a decoded value to the supported JSON type.
Normalize a decoded value to a JSON object.
Return the first supported manifest path under root, if present.
Resolve one path declared relative to plugin_root.
Plugin manifest component fields must start with ./. Marketplace source
paths must not, because the marketplace format also accepts a bare relat
Load an Agent Plugins, Claude, or Codex plugin manifest.
Build component inventory for a plugin.
Add a local marketplace to dcode state.
Add a marketplace from a pasted source string.
Remove a marketplace and every plugin installed from it.
Local marketplace source directories are never deleted. Managed marketplace clones and installed plugin caches are removed.
Set the enabled state of an installed plugin.
Uninstall a plugin (disable, clear records, delete orphaned cache).
Install a marketplace plugin into the versioned cache and enable it.
Copies the plugin source into plugins/cache/{marketplace}/{plugin}/{version}/,
writes installed_plugins.json, and enables the
Resolve whether plugin auto-updates are enabled and from which source.
Stage updated versions of enabled remote marketplace plugins.
Unversioned plugins are skipped so the running session's shared cache is not replaced.
Discover enabled marketplace plugins from their install cache paths.
List plugins from configured marketplaces.
Return plugin ids that have install records.
Return the plugin storage root directory.
Serialize plugin mutations across threads and dcode processes.
The lock is reentrant within one thread so compound operations such as marketplace removal can call the normal uninstall path while hold
Return the data directory path for a plugin id without creating it.
Return the lazily-created data directory for a plugin id.
Return a bounded, collision-resistant filesystem key.
Return a cache key that cannot disclose source credentials.
Return the marketplace cache directory.
Return the versioned plugin install cache root.
Return the versioned cache path for a plugin id.
Load persisted marketplace records.
Persist a marketplace record.
Remove a marketplace record.
Load enabled plugin ids.
Persist a plugin enablement value.
Load installed plugin records.
Add or replace the record for plugin_id in installed_plugins.json.
Return the install entry for a plugin id.
Remove the install record for a plugin.
Copy a plugin into the versioned cache and register the install.
Disable a plugin, remove install records, and delete orphaned cache dirs.
Set up the plugin CLI parser.
Execute a plugin management command.
Return (skill_dir, subfolders) pairs found under source_path.
Walks the source tree, treating any directory that directly contains a
SKILL.md as a skill directory (a recursion leaf, like a plug
Async counterpart of discover_skill_dirs.
Load and namespace every skill found under a plugin source.
Reads each discovered skill directory's SKILL.md directly, since the SDK
loader only scans one level below a source and would not read a
Async counterpart of load_namespaced_skills.
Namespace a plugin-declared MCP server's name under its plugin id.
Plugin identifiers may contain characters rejected by dcode's MCP loader.
Use __ as the namespace separator so names stay unique a
List plugin MCP servers as (label, scoped_name, needs_login) tuples.
label is the unscoped name from the plugin config (for UI). scoped_name
is what dcode registers after namespacing.
Return scoped MCP server names without preparing plugin runtime state.
Discover enabled plugins and compose their MCP config layers.
Build MCP config layers for enabled plugins.
Default .mcp.json files are loaded before manifest mcpServers, so manifest
entries win on server-name conflicts.
Build hook sources from enabled or already-discovered plugins.
List the hook events a plugin declares, for display before it loads.
Only events Hooks v2 recognizes are returned, so the plugin manager never advertises a hook that the loader will later reject.
Run a single task non-interactively and exit.
The agent is created with interactive=False, which tailors the system
prompt for autonomous headless execution (no clarification questions,
reasonable
Build the server base URL.
Generate a langgraph.json config file for langgraph dev.
Registers the interactive agent graph and dcode's custom HTTP operations,
which opt into LangGraph's route-auth layer (`enable_custom_ro
Poll a LangGraph server health endpoint until it responds.
Print every pending debug-preserved server-log path to stderr, once each.
Deferred out of _stop_process_locked so the interactive TUI can surface
the paths after Textual restores the terminal. Call
Start a LangGraph server and return a connected remote agent client.
Async context manager that starts a server and guarantees cleanup.
Wraps start_server_and_get_agent so callers don't need to duplicate the
try/finally pattern for stopping the server.
Register the dcode auth command group.
Dispatch a parsed dcode auth invocation.
Dispatch a dcode tools subcommand.
Register the dcode mcp command group.
List configured OAuth servers without stored tokens.
Servers are drawn from the same trust-gated resolution as run_mcp_login,
so untrusted project-level entries are excluded from the scan.
A serve
Handle dcode mcp login <server>.
When config_path is omitted, auto-discovered MCP configs are merged in
the same precedence order as the runtime loader, with matching trust
gating: user-level con
Handle dcode mcp config.
Prints the MCP config discovery paths in precedence order with a marker showing which exist on disk. Stat-only; never opens config files, so config-trust prompts are not tr
Dispatch dcode uninstall <name>.
Remove one selected optional extra from the dcode tool environment.
Shared by dcode uninstall NAME and the dcode --uninstall NAME alias.
Dispatch dcode install <name>.
Install an optional extra or an arbitrary package via uv --with.
Shared by dcode install and the legacy dcode --install flag.
Register the dcode config command group.
Dispatch a parsed config invocation.
Return whether project hooks are trusted for a canonical workspace root.
Persist project-hook trust for a workspace root.
Resolve the workspace root that governs hook trust for a directory.
Format a compatible MCP wire tool name.
Map a native tool name to the compatible wire tool name.
Map native tool arguments to the compatible wire input object.
Project a native tool call into compatible wire name and input.
Redact secret-like strings inside transcript content.
Reduce ordered handler results into an event-specific decision.
Return value when it is composed only of allowlisted sequences.
Allowed tokens are OSC 0/1/2/9/99/777 (BEL or ST terminated)
and bare BEL. Any other escape or control content rejects th
Build an inherited environment safe to pass to hook subprocesses.
Strips values whose names look like secrets. Hooks are user-authored trusted code, but secret values should not be ambiently availabl
Project a native hook invocation into the compatible wire contract.
Serialize a hook invocation as validated compatible JSON.
Return the compatible notification matcher and wire value.
Convert legacy dotted-event hook entries into Hooks v2 configuration.
Each distinct legacy event name becomes its own matcher group so a single
entry subscribed to both session.start and `user.prom
Return whether data looks like the legacy list-shaped hooks document.
Return the project-scoped hooks configuration path.
Return the user-scoped hooks configuration path.
Load, validate, merge, and hash Hooks v2 configuration.
Return the canonical SHA-256 snapshot id for config.
Serialize configuration into a stable byte representation.
Decode one hooks document and fingerprint the exact bytes read.
Attach Hooks v2 snapshot identity and server event gates to context.
Fire matching hook commands with payload serialized as JSON on stdin.
The event name is automatically injected into the payload under the
"event" key so callers don't need to duplicate it.
The
Schedule dispatch_hook as a background task with a strong reference.
Use this instead of bare create_task(dispatch_hook(...)) to prevent the
task from being garbage collected before completion.
Return whether fire-and-forget hook tasks are still in flight.
Await all in-flight fire-and-forget hook tasks.
Call this before the event loop tears down (e.g. at the end of a headless
run driven by asyncio.run) so background dispatches — most importantly the
Execute a server-owned hook request and return a resume payload.
Fulfill a raw interrupt value when it is a hook invocation.
Fulfill pending hook interrupts into a resume map keyed by interrupt id.
Translate a hook permission decision into a client review outcome.
Interleave hook decisions with human decisions in request order.
Run one hook command with bounded time and captured output.
Execute a task with output directed to Textual UI.
This is the Textual-compatible version of execute_task() that uses the TextualUIAdapter for all UI operations.
Build the navigation hint for modals whose Tab keys move the cursor.
Only for screens where Tab and Shift+Tab step the selection. A modal that binds Tab to something else writes its own line rather t
Build the copyable entire-thread estimated token/cost table.
Open the live breakdown without stacking duplicate modals.
Describe the reviewing model in the Auto notice body.
Return a human-readable provider label.
Shared by the auth UI and the model selector so a provider is labeled
identically in both. (The install prompt reuses the underlying
PROVIDER_DISPLAY_NAMES m
Return a compact brand label for a provider.
For space-constrained UI (e.g. the /model Recent tag). Resolution order:
a configured short_name, then the built-in PROVIDER_SHORT_NAMES map,
then t
Build the style that marks a span as click-to-copy.
Return the copy text and field label from a span style, if any.
Coerce arbitrary tool-arg content into a displayable string.
Strings pass through unchanged; other values are JSON-formatted for
readability, falling back to str() when serialization fails.
Return whether startup tips should be shown.
Build the footer line for the current charset mode.
The Ctrl+R mention is what makes the modal tier discoverable. The line is
kept short enough to wrap within PROMPT_SEARCH_MAX_HINT_ROWS at the
nar
Return a prompt's first non-empty line for a one-row summary.
Return prompts containing the query, case-insensitively.
Open the ChatGPT account page in the user's browser.
Used by /auth to let signed-in users jump to chatgpt.com (e.g., to
change account, manage billing).
Get the renderer for a tool by name.
Condense path so it renders within width terminal cells.
Directory components are replaced by a single ellipsis, growing outward from the middle of the component list, because the tail of a path
Reverse the XML escaping applied by the js_eval wire format.
The REPL escapes &, <, and > inside result/error blocks; order matters
so & is restored last to avoid double-unescaping.
Parse js_eval output into structured display blocks.
Parses the wire format structurally rather than scanning for any tag-like
substring: the trailing <result>/<error> block is anchored to the
Return selection shifted past a diff row's gutter, if one is set.
Every form a selection can take over a single-line row covers the gutter unless its start is moved past it:
Yield syntax-highlighted widgets for a unified diff.
Format addition/deletion counts as styled +N -M content.
Takes the pair as a DiffStats rather than two ints so the counts cannot be
transposed on the way to the places the user reads them — the `
Keep the bounded source prefixes needed to highlight a diff.
Idempotent, and rehydration depends on it: DiffMessage.__init__ calls this
on whatever it is handed, which is the full file from the liv
Return whether the style under the mouse points to a clickable link.
Detects both Rich Style(link=...) (OSC 8) hyperlinks and the
@click=link(...) meta actions that Textual's Markdown widget at
Open a URL after applying the shared URL safety check.
Open url in a browser and toast on failure.
Runs webbrowser.open in a thread, catches the platform errors
that can arise when no browser backend is available, and posts a
warning toast containing t
Open the URL from a Rich link style on click, if present.
Rich Style(link=...) embeds OSC 8 terminal hyperlinks, but Textual's
mouse capture intercepts normal clicks before the terminal can act on
Return value as a skill trust request, or None if it is not one.
Check whether a resolved skill directory has been trusted.
Persist trust for a resolved skill directory.
Remove trust for a skill directory.
Matches on both the approved (expanduser-only) key form that
trust_skill_dir stores and the fully-resolved form, so a caller can
revoke either by the path they s
Remove all trusted skill directories.
Return the sorted list of trusted skill directory paths.
Return trusted directories paired with their approval timestamps.
The audit surface for the trusted_at metadata that trust_skill_dir
records: list_trusted_skill_dirs returns only paths (all enf
Return verified trusted skill directories as canonical Path objects.
Used to extend the containment allowlist passed to load_skill_content.
Stored entries are the exact canonical directory the u
List skills from built-in, user, and/or project directories.
This is a dcode-specific wrapper around the prebuilt middleware's skill loading
functionality. It uses FilesystemBackend to load skills
Read the full raw SKILL.md content for a skill.
Returns the complete file content including any YAML frontmatter. Callers are responsible for parsing or stripping frontmatter if needed.
When `allowe
Setup the skills subcommand parser with all its subcommands.
Each subcommand gets a dedicated help screen so that
deepagents skills -h shows skills-specific help, not the
global help.
Execute skills subcommands based on parsed arguments.
Discover skills and build pre-resolved containment roots.
Return configured extra and user-approved skill roots.
Return the instructions the SDK pins for skill.
The SDK skips a skill it cannot pin. The agent server raises instead, so a skill the user invoked never runs silently without its instructions.
Build the user request and persisted metadata for SDK skill pinning.
The agent server resolves, trust-checks, and reads the skill, so only the name the user typed is sent.
Return the skill a pinned-skill message carries.
Return the custom stream payload for errors.
Return the errors of a skills load-error event.
Return the user notice for unreadable skill sources.
Return the fixed managed-config path and whether it is authoritative.
What the snapshot loader reads. Callers that report health need this rather
than managed_config_path, so a guessed path is neve
Return the fixed managed-config path for the current operating system.
For display and error messages. Anything that decides whether policy is
enforceable wants resolve_managed_path.
Serialize a read-modify-write of the user config and replace it atomically.
Writes the user tier only. The managed path is refused rather than trusted to be unreachable.
A committed write to the def
Make a committed write visible to the shared process resolver.
Only the default path is refreshed. get_config_resolver is keyed on
DEFAULT_CONFIG_PATH, so reloading it after a write to an overrid
Resolve a user-supplied theme name to a canonical registry key.
Accepts the registry key or the human-readable label, case-insensitive on both, with surrounding whitespace stripped - config values (e
Return value as a TOML table when it has the expected runtime shape.
tomllib parses TOML tables as string-keyed dicts, which ty cannot infer
from a runtime dict check. Keep the cast at this b
Resolve [ui.terminal_themes][TERM_PROGRAM] to a registered theme.
Centralizes both the lookup and the misconfiguration warnings, which are logged exactly once per call. Three callers now share that
Return UNION_PATHS rebased onto a subtree rooted at prefix.
merge_toml_tables matches paths relative to where it starts. A merge of
one option's own subtree therefore never matches an absolute
Return whether managed policy decided a value with this source label.
A structured option merges both layers and reports a combined label, so
source == MANAGED_SOURCE is the wrong test and silently
Merge managed policy over user config with this project's precedence.
The single statement of managed-over-user precedence. It was assembled by hand at three call sites, two carrying "must match" com
Return whether a managed scalar has the declared type for its path.
Unknown and structured paths retain the deep-merger's existing behavior; their dedicated readers own validation. Manifest-backed sc
Classify what managed policy says at one manifest path.
Return managed settings whose declaration cannot be safely applied.
A key is a violation when an enforced managed policy declaration cannot be applied, when a known managed section has a non-table va
Resolve one manifest option and retain its rank-keyed managed result.
Return manifest keys managed policy declares whose value was dropped.
Not a launch failure: only ENFORCED_MANAGED_KEYS stops a launch, and every
other rejected managed value deliberately falls thro
Return known managed sections declared as non-table values.
Unknown leaf keys remain forward compatible. Every parent path of a manifest-backed option is known to be a table, however, as are the stru
Return the process snapshot, or an isolated snapshot for an explicit path.
A reload that cannot parse the file never evicts policy that parsed cleanly earlier. An unusable snapshot carries `data == {
Return the status of the last refresh that produced no policy.
A failed refresh does not change what the process enforces: the last enforceable generation keeps resolving, which is what fail-closed r
Load one user snapshot and the current managed snapshot.
Managed policy is included exactly when user_path is None, which is
what every production caller passes. Reading an explicit path is a
tes
Drop the cached managed snapshot and the shared process resolver.
Test-only. Production reloads pass refresh=True instead, which keeps the
last snapshot that parsed cleanly if the new one fails; cl
Return managed policy only when it can be enforced.
A file that parses is not necessarily enforceable: a privilege-affecting key can carry a value the manifest rejects, or a known section can be a sc
Fail startup when present managed policy cannot be parsed or enforced.
Propagates from get_healthy_managed_snapshot: ManagedConfigError when
a managed file is present but unreadable, and `Managed
Return managed provider health for diagnostics and config inspection.
Return both halves of exit 78 for one managed snapshot.
Reading health and violations as two calls is a live bug, not a style
choice. get_managed_snapshot declines to cache a candidate it cannot
en
Evaluate provider health and policy diagnostics for one snapshot.
Deep Agents Code - Interactive AI coding assistant.
Shared provider auth status formatting.
Provider-independent model metadata exchanged with the server.
Server-side graph entry point for langgraph dev.
This module is referenced by the generated langgraph.json and exposes a graph
factory that the LangGraph server can load and serve.
The graph is
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() withou
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.
Persistent store of MCP server names the user has disabled.
Disabled servers are skipped at config merge time so their tools never reach the agent and no connection is attempted. State lives under `[
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 ke
Agent middleware covering what MCP tools need around every call.
The tools themselves come out of langchain.mcp unmodified. Everything this
app wants on top — an argument quirk, and translating a d
Auto-install pinned upstream binaries for optional tools.
Today this only manages ripgrep. The SDK shells out to rg via PATH,
so installing inside the dcode tool environment and prepending that
Shared size limits and status vocabulary for model-visible goal state.
Estimate and persist cumulative model cost for each thread.
The graph owns the durable total. CostTrackingMiddleware writes ordinary graph
deltas, while prepare_operation_cost gives server-owned
Main entry point and loop.
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 runnin
Subagent loader for app.
Loads custom subagent definitions from the filesystem. Subagents are defined as markdown files with YAML frontmatter in the agents/ directory.
External editor support for composing prompts.
Utilities for project root detection and project-specific configuration.
Custom tools for the agent.
Shared unified-diff helpers.
Every diff passing through this module is "\n"-joined from lines that came
from splitlines() or split("\n"), so no element can contain a line boundary.
That is what
Helpers for tracking file operations and computing diffs for display.
Provider policy and pricing helpers for cold prompt-cache warnings.
Dcode-specific ACP approval-mode adapter.
Launch metadata and workspace-bound model resolution in the server process.
Utilities for handling image and video media from clipboard and files.
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, keybi
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. `mc
Durable, server-authoritative thread workspace bindings.
Reasoning effort support for /effort.
Supported levels and defaults come from LangChain model profiles. Provider
integrations translate the standard reasoning_effort constructor parameter
into th
Validation and environment-variable expansion for MCP server config.
Resolves ${VAR} and ${VAR:-default} references in the supported
configuration fields (command, url, args, env, `header
Schema and middleware for per-checkpoint state restored when resuming.
ResumeState declares several checkpointed, schema-private channels. They fall
into two groups with different write paths:
W
Safe, structured diagnostics for workspace binding and runtime rejections.
When the server refuses to bind or run a thread's workspace, the user sees only a one-line refusal. This module defines the
Ask user middleware for interactive question-answering during agent execution.
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
Agent management and creation.
Model discovery data shared by the inference host and model pickers.
CLI-specific rubric middleware customizations.
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.
The dcode doctor command: report install health and diagnostics.
Inspired by claude doctor, this prints a grouped, tree-style summary of the
running install, update status, and configuration loca
Persist side-question and naming spend outside the graph's checkpoints.
The sessions database owns this subtotal. Readers add it to the graph's total; it is never fed back into the graph's cost recor
Storage paths for offloaded conversation history.
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
Configuration, constants, and model creation.
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 re
Enumerate the tools available to the agent.
Backs two entry points: the dcode tools list CLI command (_run_tools_list)
and the interactive /tools slash command (app._handle_tools_command).
T
Bounded, isolated conversation title generation.
First-run onboarding state for the interactive TUI.
Terminal tab titles that strip control characters and restore on exit.
Restoring depends on the terminal's title stack (XTWINOPS 22/23). Terminals without one keep the last title after exit.
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
Protect machine-managed memory blocks from agent edits.
The onboarding flow writes the user's preferred name into the user AGENTS.md
inside a marker-delimited block (see `onboarding.ONBOARDING_NAME
Classifier-backed approval policy for local TUI and ACP runtimes.
Server-side helpers for drafting acceptance criteria from goal objectives.
iTerm2 cursor guide workaround for Textual alternate-screen rendering.
Backend recovery at the proxy boundary, before errors reach the wire.
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
UI-agnostic helpers for resolving an MCP login target.
The MCP login flow historically inlined config discovery, trust gating,
shape validation, and print()-based error reporting. The TUI cannot
co
Input handling utilities including image/video tracking and file mention parsing.
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.
Thread management using LangGraph's built-in checkpoint persistence.
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
Clipboard utilities.
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 credent
Tool-free side answers from a snapshot of the main conversation.
Canonical internal model-context messages for goal state and continuation.
Goal context is represented as a HumanMessage so it participates in the
provider's normal turn ordering. Its lc_source m
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 clipb
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.
Estimated context audit for the /context-doctor command.
Approval-mode state shared by the Textual client and agent server.
Large paste collapsing for the chat input.
When the user pastes text exceeding a size or line threshold, the full text
is stored off-screen and a compact [Pasted text #N +M lines] placeholder
is in
Integrations for external systems used by the Deep Agents Code.
Discovery and instantiation of sandbox providers.
Merges three provider sources into one registry:
deepagents-code
extras).Sandbox lifecycle management with provider abstraction.
ChatGPT OAuth integration for the openai_codex model provider.
Thin orchestration layer over langchain_openai.chatgpt_oauth. Reuses the
upstream PKCE/token primitives directly (`_generate_pkce_pa
Sandbox provider interface used by Deep Agents Code.
Parsing for the [sandboxes] section of ~/.deepagents/config.toml.
Parallels the [models] provider configuration in model_config.py. Config
providers declare a class_path (same trust model a
Public contract for dcode Python extensions.
Persist project-extension trust decisions.
Host startup and runtime extension registrations.
Discover, load, and tear down Python extensions.
Resolve authorized Python extension sources into entry files.
Resolve extension configuration from user config and environment.
Public registrar passed to Python extension factories.
Import and initialize Python extension factories.
Provider-specific MCP OAuth dispatch.
resolve_provider(url) returns the registered policy whose matches
predicate fires for url, with GenericProvider as the fallback.
GitHub-hosted MCP OAuth provider.
GitHub's remote MCP at api.githubcopilot.com authenticates via RFC
8628 Device Authorization Grant — the app runs the device flow,
persists the resulting token plu
Policy interface for provider-specific MCP OAuth quirks.
Each concrete provider module (e.g. slack, github) subclasses
OAuthProvider to encode its own URL match rule, client metadata, and
any p
Slack-hosted MCP OAuth provider.
Slack's hosted MCP endpoint uses the Authorization Code flow with a hardcoded public client ID and a fixed pre-registered loopback redirect URI (`http://localhost:311
Plugin support for dcode.
Variable substitution for plugin-provided configuration.
Marketplace parsing for plugins.
Data models for plugins.
Plugin manifest parsing for plugins.
Plugin discovery, install, and enablement helpers.
State storage for dcode plugin marketplaces, installs, and enablement.
CLI helpers for plugin management.
Plugin subsystem adapters.
Code-local skills middleware adapter for plugin namespaces.
Adapter from plugin MCP declarations to dcode MCP config dictionaries.
Adapter from plugin hook declarations to Hooks v2 configuration sources.
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.
Client-side transport and headless execution for Deep Agents Code.
Combine independently reported main-task and side-question usage for display.
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 in
Local LangGraph server launch helpers for Deep Agents Code clients.
LangGraph server lifecycle management for the app.
Handles starting/stopping a langgraph dev server process and generating the
required langgraph.json configuration file.
Server lifecycle orchestration for the app.
Provides start_server_and_get_agent which handles the full flow of:
ServerConfig from application argumentsClient-facing CLI command implementations.
CLI commands for the auth group: manage stored provider credentials.
These subcommands mirror the in-TUI /auth modal verbs so credentials can be
managed non-interactively (dotfile bootstrap, CI,
The dcode tools command group: provision managed external tools.
dcode tools install fetches the pinned, SHA-256-verified ripgrep binary into
the dcode installation (the same managed path used on
CLI commands of the MCP module.
CLI install path for optional deepagents-code extras.
dcode install <name> installs a curated optional extra (for example a sandbox
or model-provider dependency) into the current dcode environmen
CLI commands for inspecting the configuration surface.
Bare config resolves each option against the app credential store (for
credentials), the live environment, and config.toml, reporting the ef
Hook contracts and compatibility dispatch.
This package contains two hook systems: Hooks v2 (current) and legacy hooks (deprecated, removal September 1, 2026).
To write a new hook integration, use t
Canonical boundary between hook domain and wire models.
Persistent workspace trust for project-scoped hooks.
Single-owner coordinator for client-side Hooks v2 state.
HooksManager is the only place in the client that builds or holds a
HooksRuntime. The Textual app, the Textual stream adapter, and the hea
Native dcode tool vocabulary mapped to compatible wire names.
Client-owned conversation transcript projections for Hooks v2.
Materializes versioned per-thread and per-subagent JSONL files that hook
commands can read via transcript_path / `agent_transcript_pat
Event-aware reduction for Hooks v2 command output.
Terminal escape-sequence validation for hook output.
Sanitized subprocess environments for Hooks v2 command handlers.
Session-scoped client facade for the Hooks v2 runtime.
Immutable runtime snapshots for Hooks v2 configuration.
Projection from Hooks v2 domain invocations to compatible wire input.
Legacy dotted-event migration helpers for Hooks v2 configuration.
Legacy documents are converted by the loader so lifecycle call sites dispatch only canonical events and do not duplicate old dotted-e
Validated Hooks v2 configuration loading, merging, and hashing.
Precedence (highest first, earlier in reduction order):
{project_root}/.deepagents/hooks.jsonHelpers for attaching Hooks v2 session identity to graph context.
Lightweight hook dispatch for external tool integration.
DEPRECATED: This is the legacy hook system, kept for backward compatibility until September 1, 2026. New integrations should use Hooks v2 — se
Client-side fulfillment for server-owned Hooks v2 interrupts.
Standalone orchestration for the Hooks v2 execution engine.
Translation between PermissionRequest decisions and HITL review payloads.
Shared by the Textual and headless approval paths so both surfaces resolve hook-driven permission decisions identically.
Bounded asynchronous command execution for Hooks v2.
Client-owned Hooks v2 lifecycle facade.
Typed contracts for the hooks system.
Versioned hook invocation transport models.
Cached runtime validators for hook model boundaries.
Validated hook configuration models.
Textual user interface package for deepagents-code.
Textual UI adapter for agent execution.
Shared keyboard hints for terminal UI components.
Modal footers advertise the same navigation keys in a dozen screens. Keeping the wording here means a binding change is edited once instead of being
Screen UI components.
Modal UI components.
Searchable local prompt history modal.
Persistent warning when a session exceeds its configured cost threshold.
Action modal shown when policy blocks a launch-time thread resume.
Read-only MCP server details for the debug console.
Modal for a cold prompt cache: send-time confirmation or expiry handoff.
Prompt for compacting a large resumed thread.
Side conversation with follow-ups and app-owned history.
Confirmation modal for switching models with a large context.
Detailed token and estimated-cost breakdown modal.
Editable confirmation for a generated thread name.
Interactive plugin manager screen.
Pure plugin manager content builders.
Clickable tab labels for the plugin manager header.
Plugin manager view models.
Plugin manager state loading.
Textual widgets for deepagents-code.
Import directly from submodules, e.g.:
from deepagents_code.tui.widgets.chat_input import ChatInput
from deepagents_code.tui.widgets.mess
First-enable confirmation modal for Auto mode.
Shown at most once per install (per notice version) before Auto activates. Enter confirms the switch and records the notice; Esc cancels and leaves the
TUI screens for managing stored model-provider credentials.
AuthPromptScreen accepts an API key for a single provider, persists it via
auth_store, and is the sole place that deletes existing cred
Confirmation modal for /install <package> --package in the TUI.
Arbitrary packages have no curated allowlist to vet against, so installing one pulls in third-party code. Rather than forcing the use
Confirmation modal offered when a change needs an owned-server respawn.
Some changes take effect only when the app-owned LangGraph server subprocess
spawns: provider/sandbox extras and --package in
Read-only in-app Debug Console modal.
Toggled with Ctrl+\ (or the hidden /debug command), this overlay shows a
live session/runtime snapshot plus a live tail of recent
deepagents_code.* log rec
Notification hub for pending notices and warning preferences.
Surfaces PendingNotification entries as single-line rows plus an expandable
settings section, including when no notices are pending. Se
Tool-specific approval widgets for HITL display.
Startup tip widget shown above the chat input.
In-TUI MCP OAuth login modal.
MCPLoginScreen is both a Textual ModalScreen and an implementation of
OAuthInteraction. The login worker awaits its interaction methods while
the user sees and act
Live panel showing subagents fanned out from within js_eval calls.
When the agent writes code that calls the top-level task() global, each
dispatch runs as a subagent inside a single js_eval
First-enable confirmation modal before Shift+Tab enters YOLO.
Shown when the user cycles into unrestricted YOLO without a persisted acknowledgement. Enter acknowledges YOLO and records the policy ver
Inline prompt history search panel for the chat composer.
Opened by a first Ctrl+R; a second Ctrl+R escalates to the full
PromptClipboardScreen modal. Key handling lives on ChatInput
(`_prompt_se
Prompt for switching cwd when resuming or switching threads.
Persistent inline display for the current goal.
Interactive model selector screen for /model command.
Welcome banner widget.
Command history manager for input persistence.
Ask user widget for interactive questions during agent execution.
Confirmation prompt for resuming a thread owned by another agent.
ChatGPT OAuth sign-in screen, reachable via /auth -> openai_codex.
Mirrors the MCP loopback flow in mcp_auth from the user's POV: a modal
shows progress, surfaces the authorize URL inline (so h
Tool renderers for approval widgets - registry pattern.
Goal acceptance-criteria review widget.
Confirmation modals for MCP changes that need a server restart.
Restarting the LangGraph server is required for newly minted MCP tokens
and for /mcp disable/enable toggles to take effect, but auto-
Onboarding screens for the interactive TUI.
Approval widget for HITL - using standard Textual patterns.
Color-coded context-window visualization for /context.
Confirmation modals for /update dependency-refresh flows in the TUI.
When deepagents-code itself is already on the latest release, /update can
still re-resolve its dependencies to the newest ve
Trust prompt for skills that resolve outside trusted skill directories.
When a /skill:<name> invocation reads a SKILL.md whose resolved path (via
symlink) falls outside every trusted skill root,
Loading widget with animated spinner for agent activity.
Interactive thread selector screen for /threads command.
Interactive agent selector screen for /agents command.
Interactive theme selector screen for /theme command.
Renderers turning a unified diff into one Static per row.
Rows carry a line-number gutter, a +/- marker, syntax highlighting lifted
from whole-file lexer state, and word-level emphasis on the s
Autocomplete system for @ mentions and / commands.
This is a custom implementation that handles trigger-based completion for slash commands (/) and file mentions (@).
Message store for virtualized chat history.
This module provides data structures and management for message virtualization, allowing the TUI to handle large message histories efficiently by keeping o
Dedicated modal for the update-available notification.
Shown automatically at startup when a newer version of
deepagents-code is available on PyPI. Surfaces the same actions the
notification center
Read-only MCP server and tool viewer modal.
Status bar widget.
Warning-toggle definitions for the notification hub's settings section.
Generic detail modal for a single pending notification.
Used by NotificationCenterScreen when the user drills into an entry
whose payload does not have a dedicated modal (e.g. missing-dependency
no
Progress modal for app self-update installs.
Chat input widget for deepagents-code with autocomplete and history support.
Interactive reasoning effort selector for /effort.
Skills module for Deep Agents Code.
Public API:
Trust store for skill directories that resolve outside trusted roots.
load_skill_content refuses to read a SKILL.md whose resolved path falls
outside every trusted skill root — this stops a symli
Skill loader for CLI commands.
This module provides filesystem-based skill discovery for CLI operations (list, create, info, delete). It wraps the prebuilt middleware functionality from deepagents.mi
CLI commands for skill management.
Helpers for loading and formatting skill invocations.
Stream event that tells the user about unreadable skill sources.
The SDK shows skill load errors only to the model. PluginSkillsMiddleware
also streams the errors for skill directories that exist b
Managed and user configuration: paths, providers, and merge.
Writes live in deepagents_code.configuration.writer and are imported from
there directly, so no writer symbol is re-exported here.
Fixed operating-system paths for managed configuration.
User-config-only atomic TOML writes.
Lightweight theme preference coercion shared by config providers and the UI.
Resolver-backed interpreter configuration snapshots.
Process-local snapshots for managed and user TOML configuration.
Discriminated union for the ask_user widget Future result.
Key for buffering an in-progress streamed tool call.
The streaming index (an int) when present, else the tool-call id (a
str), else a unique placeholder string (see tool_call_buffer_key). E
A whole tool-call arguments value delivered by a provider in one chunk.
Usually a dict; rarely a bare scalar or list. None means no whole value has
arrived yet (the args may instead be streaming
Spinner display text, or None to hide.
Deliberately unconstrained rather than the closed Literal set it replaced:
retry status text is generated per attempt by model_retry.format_retry_status.
Model run identities and message aliases for recorded requests.
Tagged union of every persisted credential shape, narrowed by type.
Element type of HITLResponse["decisions"].
Value the plugin manager dismisses with.
None means no action is needed: the close check found no pending changes, or
no checker was wired. Textual also produces None for a bare dismiss(), so
h