deepagents-code
Description
🧠🤖 Deep Agents Code
Quick Install
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
🤔 What is this?
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:
- Interactive TUI — rich terminal interface with streaming responses
- Conversation resume — pick up where you left off across sessions
- Web search — ground responses in live information
- Remote sandboxes — run code in isolated environments (LangSmith, AgentCore, Daytona, Modal, Runloop, & more)
- Persistent memory — agent remembers context across conversations
- Custom skills — extend the agent with your own slash commands
- Headless mode — run non-interactively for scripting and CI
- Human-in-the-loop — approve or reject tool calls before execution
🔒 Security model
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.
📖 Resources
- Documentation
- Changelog
- Source code
- Deep Agents SDK — underlying agent harness
- LangChain Academy — Comprehensive, free courses on LangChain libraries and products, made by the LangChain team.
- Code of Conduct — community guidelines and standards
📕 Releases & Versioning
See our Releases and Versioning policies.
💁 Contributing
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.
🤝 Acknowledgements
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.
Classes
ModelMetadata
Resolved model properties needed by the interactive client.
ServerRuntime
The one-per-process result with named slots to prevent transposition.
ConfigurableModelMiddleware
Swap the model or per-call settings from runtime.context.
Reads two optional keys from the runtime context dict:
'model'— aprovider:modelspec (e.g."openai:gpt-5"). When present and
ServerConfig
Full 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
ChecksumMismatchError
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 (
ManagedToolUnavailableError
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
GoalStateSizeError
Goal/rubric text exceeds a model-visible context budget.
CostBreakdown
Additive token and estimated-cost accounting for one or more requests.
PreparedOperationCost
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,
CostState
Agent state extended with the cumulative thread-cost channel.
CostTrackingMiddleware
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
ExternalEvent
A transport-independent event delivered from outside the TUI.
EventSource
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.
UnixSocketEventSource
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
SubagentMetadata
Metadata for a custom subagent loaded from filesystem.
RepositoryMetadata
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
ExternalEditorError
Raised when an external editor cannot be opened or read.
ProjectContext
Explicit user/project path context for project-sensitive behavior.
DiffStats
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
ApprovalPreview
Data used to render HITL previews.
FileOpMetrics
Line and byte level metrics for a file operation.
FileOperationRecord
Track a single filesystem tool call.
FileOpTracker
Collect file operation metrics during an interaction.
ColdCacheSkip
A known reason to skip a cache prompt, distinct from missing pricing.
CacheActivity
A cache-using request's start time and effective cache identity.
PromptCachePolicy
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
RewarmEstimate
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
ColdCacheWarning
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
AgentServerACP
ACP server that supplies trusted classifier context in Auto mode.
ImageData
Represents a pasted image with its base64 encoding.
VideoData
Represents a pasted video with its base64 encoding.
ActionId
Stable identifiers for notification actions dispatched by the app.
NotificationAction
One button/action row in the notification modal.
MissingDepPayload
Typed payload for a missing-dependency notification.
UpdateAvailablePayload
Typed payload for an update-available notification.
PendingNotification
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
NotificationRegistry
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
WorkspacePayload
JSON-safe workspace descriptor carried in LangGraph runtime context.
WorkspaceBinding
Server-authoritative workspace and resource policy for one thread.
WorkspaceConflictError
A workspace claim or runtime conflicts with server resource policy.
GoalRubricChannels
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
ResumeState
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
ResumeStateMiddleware
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
WorkspaceSnapshot
Versioned, allowlisted policy snapshot persisted beside a binding.
FieldChange
One drifted policy field, reported within the snapshot allowlist.
WorkspaceDiagnostics
Structured, secret-free detail attached to a workspace refusal.
AskUserMiddleware
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
ShadowedDcode
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
DependencyChange
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
ToolRequirementIntrospectionError
Raised when uv tool requested requirements cannot be preserved.
ExtraNotInstalledError
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
ProtectedExtraError
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
CompositeExtraConflictError
Raised when a selected composite still supplies the requested extra.
ExtraInstallOutcome
Result of an attempted optional-extra install.
ExtraRemovalOutcome
Result of an attempted optional-extra removal.
ShellAllowListMiddleware
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
AsyncApprovalHITLMiddleware
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
CostAwareCodeInterpreterMiddleware
Transport cost receipts without caching JavaScript or forwarding state.
CatalogProfile
Displayable model capabilities with override provenance.
CatalogProvider
Provider presentation and readiness, without credential values.
ModelCatalog
Validated catalog from the environment that constructs models.
ReliableRubricState
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
RubricGraderState
Nested-grader state used to scope verification-tool budgets.
ReliableRubricMiddleware
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
Choice
A single choice option for a multiple choice or multi-select question.
Question
A question to ask the user.
AskUserRequest
Request payload sent via interrupt when asking the user questions.
AskUserAuthorizationReceipt
Trusted same-turn authorization recorded after an ask_user response.
AskUserAnswered
Widget result when the user submits answers.
AskUserCancelled
Widget result when the user cancels the prompt.
RepositoryBounds
Path-safety and size limits for read-only repository inspection tools.
DiagnosticItem
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.
DiagnosticSection
A named group of related diagnostic items.
ToolUsePayload
tool.use hook payload (schema documented in hooks).
ToolErrorPayload
tool.error hook payload (schema documented in hooks).
ToolResultPayload
tool.result hook payload (schema documented in hooks).
ToolCallBuffer
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
UnemittedToolCalls
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
ModelStats
Token stats for a single model within a session.
KindStats
Token and cost stats for one UsageKind bucket.
RecordedUsage
Usage returned after recording one streamed model message.
ModelInvocationKey
Stable identity of one model invocation in the usage ledger.
MessageUsageKey
Message identity, optionally scoped to one model attempt.
SessionStats
Stats accumulated over a single agent turn (or full session).
RecordedRequest
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
CLIContextSchema
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.
CLIContext
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
LocalContextState
State for local context middleware.
LocalContextMiddleware
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-
TerminalStderrGuard
Suppress native stderr writes while the TUI owns the terminal.
CharsetMode
Character set mode for TUI display.
Glyphs
Character glyphs for TUI display.
RuntimeState
Mutable metadata for the model active in this process.
CredentialsSnapshot
One complete generation of credentials and project context.
Credentials
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
LangsmithShadowResult
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
TracingStatus
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.
LangSmithLookupError
Base class for typed LangSmith project URL lookup failures.
Concrete subclasses (LangSmithImportError, LangSmithLookupTimeoutError,
LangSmithApiError) let interactive callers like /trace show
LangSmithImportError
The langsmith package is not installed.
LangSmithLookupTimeoutError
The LangSmith project URL lookup exceeded its hard timeout.
LangSmithApiError
The LangSmith SDK call raised — auth, 404, network, etc.
Wraps the underlying SDK exception in __cause__.
LangSmithProjectNotFoundError
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
ModelResult
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
DeterministicIntegrationChatModel
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
ToolCallingIntegrationChatModel
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
GoalCriteriaIntegrationChatModel
Exercise nested criteria generation with a repository read.
DistributionVersion
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
VersionReport
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
ExtrasIntrospectionError
Raised when installed extras cannot be determined safely.
ExtraDependencyStatus
Install status for one optional dependency extra.
InstallHint
Resolved recovery action for a missing provider package.
Exactly one of three outcomes:
extraset,commandNone— prefer installing the extra that declares the package (callers format this
ToolEntry
A single tool's display metadata.
ToolGroup
A named group of tools sharing a source.
UnavailableServer
An MCP server that was discovered but currently exposes no tools.
ToolCatalog
Everything dcode tools list needs to render, in display order.
TerminalTitle
Push the terminal title on start, update it, and pop it on restore.
ManagedMemoryGuardMiddleware
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
AutoDecisionCategory
Classifier denial categories exposed to the agent and TUI.
AutoDecision
One validated verdict bound by the server to its proposed tool call.
AutoDecisionBatch
Server-assembled verdicts for one unresolved action batch.
AutoClassifierTurn
One checkpointed classifier request and its validated response.
AutoClassifierConversation
Bounded provider-neutral classifier history.
AutoModeCounters
Server-owned denial and availability counters for one thread.
PlannedDecision
Checkpoint-safe disposition for one gated call.
AutoDecisionPlan
Private checkpoint record joining model output to after-model routing.
AutoTempArtifact
Server-owned provenance for one exclusively allocated scratch file.
AutoTempArtifactMutation
Reducer update that creates or removes one exact artifact record.
AutoModeState
Agent state carrying private Auto decisions and scratch provenance.
PromptMetadata
Trusted metadata attached by the Textual client to a user message.
ApprovalModeResolution
Server-resolved approval mode and trace-safe diagnostics.
AutoModeHITLMiddleware
Apply deterministic policy, classifier review, and HITL fallback.
HeadlessMCPGuardMiddleware
Reject dynamically gated MCP calls when no approval UI exists.
GoalProposal
Structured proposal returned by the criteria agent.
GoalCreateRequest
A new proposal or a rejection-based regeneration.
feedback/previous_criteria are only present on a rejection retry.
GoalAmendRequest
An amendment to an accepted goal; both extra fields are required.
GoalCriteriaState
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
GoalCriteriaAgentState
Private per-invocation state for the nested criteria agent.
RubricGraderState
Nested-grader state used to scope verification-tool budgets.
GoalCriteriaMiddleware
Run goal-criteria requests entirely inside the main server graph.
MCPBackendMiddleware
Recover failed connections and preserve actionable login errors.
ThemeColors
Complete set of semantic colors for one theme variant.
Every field must be a 7-character hex color string (e.g., '#7AA2F7').
ThemeEntry
Metadata for a registered theme.
InMemoryLogRecord
Structured log record retained by the in-memory debug buffer.
InMemoryLogBuffer
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
ConfigErrorKind
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
ConfigResolutionError
Structured error returned when a login target cannot be resolved.
ConfigResolution
Successful resolution of a merged MCP config for login.
ServerSelection
Resolved server config plus enough context for error messages.
ParsedPastedPathPayload
Unified parse result for dropped-path payload detection.
MediaTracker
Track pasted images and videos in the current conversation.
ThreadInfo
Thread metadata returned by list_threads.
BypassTier
Classification that controls whether a command can skip the message queue.
SlashCommand
A single slash-command definition.
CommandEntry
A single autocomplete entry for the slash-command controller.
ApiKeyCredential
A persisted API key credential.
The type field is the discriminator that lets OAuthCredential (added
later) coexist in the same file without migration.
OAuthCredential
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
WriteOutcome
Result of a credential write that may have warnings to surface.
DeleteOutcome
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
BtwOperation
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
GoalStateProjection
Canonical goal/rubric fields used for notices and fingerprints.
NoticeTextSections
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
GoalStateNoticeInfo
Metadata extracted from a canonical goal-state notice.
TerminalProgressState
OSC 9;4 progress states.
See https://learn.microsoft.com/en-us/windows/terminal/tutorials/progress-bar-sequences.
UnicodeIssue
A dangerous Unicode character found in text.
UrlSafetyResult
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.
DeepAgentsHomeError
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
ContextDoctorRow
One component in the context audit.
ContextDoctorReport
Structured context audit ready for presentation.
ProfilePaths
Paths whose contents belong to one user profile and trust root.
InstallationPaths
Paths owned by the installed tool rather than a selected profile.
ProjectPaths
Project-controlled paths derived from an explicit repository root.
DeepAgentsPathSnapshot
Frozen launch-time profile and installation paths.
PathState
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.
ApprovalMode
Tool-approval policy selected for an interactive thread.
ApprovalModePayload
Stored approval-mode control payload.
PastedContent
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.
SandboxRegistry
Merged view of built-in, entry-point, and config sandbox providers.
CodexAuthStatus
Snapshot of the ChatGPT OAuth login state.
CodexLoginCancelledError
Raised when the user cancels a sign-in flow mid-callback wait.
CodexAuthExpiredError
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
CodexLoginInteraction
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
SandboxInstallHint
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"
SandboxProviderMetadata
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
SandboxError
Base error for sandbox provider operations.
SandboxNotFoundError
Raised when the requested sandbox cannot be found.
SandboxProvider
Interface for creating and deleting sandbox backends.
SandboxProviderConfig
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
SandboxConfig
Parsed [sandboxes] configuration from config.toml.
Instances are immutable once constructed; providers is wrapped in a
MappingProxyType to prevent accidental mutation.
ExtensionRuntimeMiddleware
Expose tools registered after the agent graph was built.
ExtensionLoadResult
Registrations and isolated errors from one load pass.
DiscoveryResult
Authorized sources and non-fatal resolution errors.
TrustPolicy
Default decision for project-authored extension code.
ExtensionSettings
Effective extension configuration for one process.
ExtensionMode
Runtime mode exposed to extensions.
ExtensionAPI
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
GitHubProvider
GitHub-hosted MCP: RFC 8628 Device Authorization Grant.
LoginResult
Outcome of a provider's pre-handshake run_login step.
OAuthProvider
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
GenericProvider
Fallback provider for spec-compliant MCP servers with no quirks.
SlackProvider
Slack-hosted MCP: loopback authorization using the selected app.
MarketplaceError
Raised when a marketplace cannot be loaded.
LocalMarketplaceSource
Local directory or JSON file used as a marketplace source.
RepositoryMarketplaceSource
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.
UrlMarketplaceSource
Marketplace manifest downloaded from an HTTP URL.
PluginManifest
Parsed plugin manifest.
ComponentInventory
Inventory of supported plugin components.
unsupported lists plugin component directories that deepagents-code does
not load (e.g. agents/, commands/).
PluginInstance
A discovered plugin ready to feed dcode adapters.
LocalPluginSource
A plugin stored relative to its marketplace.
GithubPluginSource
A plugin sourced from a GitHub repository.
GitSubdirectoryPluginSource
A plugin sourced from a subdirectory in a Git repository.
UrlPluginSource
A plugin sourced from a Git repository URL.
MarketplacePluginEntry
A catalog entry from a marketplace manifest.
PluginMarketplace
A parsed marketplace manifest.
MarketplaceRecord
Persisted marketplace source record.
InstalledPluginEntry
Install record for a plugin.
version is the value declared by the plugin manifest, if any.
PluginDiscoveryResult
Result from plugin discovery.
PluginManifestError
Raised when a plugin manifest is malformed enough to skip the plugin.
PluginStateError
Raised when existing plugin state cannot be safely modified.
PluginSkillsMiddleware
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
SessionCost
Presentation total derived from the latest independent subtotals.
SessionCostTracker
Retain each source independently so delayed updates cannot erase spend.
ResumeRequest
An explicit -r <id> resume request from the command line.
ResumeTarget
A thread that exists and passes the resume-age policy.
ResumeError
A user-facing reason the requested thread cannot be resumed.
HITLIterationLimitError
Raised when the HITL interrupt loop exceeds _MAX_HITL_ITERATIONS rounds.
InFlightToolCall
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
StreamState
Mutable state accumulated while iterating over the agent stream.
ThreadUrlLookupState
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.
ServerProcess
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
ResolvedOption
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
HookEnvelopeAdapter
Adapt hook invocations and handler output across the wire boundary.
HooksTrustEntry
Persisted trust record for one canonical workspace root.
HooksTrustStore
Versioned on-disk trust store for project-scoped hooks.
WorkspaceTrust
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
HookSessionIdentity
Live client identity projected into every hook invocation.
HookOutcome
Result of a lifecycle hook that may halt the caller.
PromptOutcome
Result of UserPromptSubmit, including its prompt rewrites.
HooksManager
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
TranscriptRecord
One JSONL record in a materialized transcript projection.
TranscriptHandle
Identity of a materialized transcript file.
TranscriptStore
Append-only JSONL transcript projections owned by the client process.
TranscriptRecorder
Collect completed stream messages into a Hooks transcript runtime.
PreparedHookInvocation
Client-only materialization needed to build one hook wire envelope.
HooksRuntime
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
HookHandler
One ordered command handler in a configuration snapshot.
HookMatch
Matched handlers for one invocation.
HooksSnapshot
Immutable, declaration-ordered Hooks v2 runtime configuration.
HooksSource
Origin of the matcher groups contributed by one hooks document.
FileHooksSource
A project or user hooks file, which defines no variables.
PluginHooksSource
Origin and environment for groups one enabled plugin contributed.
LoadedHooksConfig
Validated configuration plus load diagnostics and source paths.
HookFulfillmentLedger
Deduplicate hook fulfillment for one client session.
HookEngine
Execute Hooks v2 invocations against one immutable snapshot.
PermissionReviewDecision
Client approval decision compatible with HITL resume payloads.
PermissionHookOutcome
Normalized result shared by TUI and headless permission handling.
PermissionPlan
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.
HandlerResult
Validated output and diagnostics from one command handler.
ClientHookStopError
Raised when a client-owned hook stops lifecycle processing.
ClientHookContext
Client state required to create a domain hook invocation.
ClientHookService
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
HookInvocationRequest
Request sent for a server-owned hook invocation.
HookInvocationResponse
Response returned for a server-owned hook invocation.
CommandHandlerSpec
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.
MatcherGroup
A matcher and its ordered hook handlers.
HooksConfig
Top-level configuration grouped by hook event.
DeferredToolResultHook
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
RubricEvaluationEnd
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
TextualUIAdapter
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.
PromptRow
One prompt summary row.
Public so its Clicked message resolves to the idiomatic
on_prompt_row_clicked handler; nothing outside this module builds one.
Clicked
Message sent when a prompt row is clicked.
PromptClipboardScreen
Filter, preview, copy, or select a previously submitted prompt.
SessionCostWarningScreen
Keep the session cost warning visible until acknowledged.
ResumeBlockedScreen
Ask whether to start a new session or exit after a blocked resume.
MCPServersScreen
Show a live, scrollable, copyable list of MCP server statuses.
ColdCacheChoice
How to resolve a cold prompt-cache warning.
ColdCacheWarningScreen
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
ResumeCompactPromptScreen
Ask whether to compact a just-resumed thread before the next turn.
BtwTextArea
Side-question editor with the shared multiline and paste conventions.
Submitted
Posted when Enter submits the complete side question.
BtwScreen
Chat independently of the main run with restorable side exchanges.
ModelSwitchWarningScreen
Confirm a model switch that preserves a large conversation context.
CostBreakdownScreen
Modal showing the copyable entire-thread token and cost breakdown.
ThreadNameScreen
Confirm or edit a suggested name without changing the thread yet.
PluginManagerScreen
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
PluginTabSelected
Posted when a plugin manager tab label is clicked.
PluginTabLabel
Mouse-clickable tab label in the plugin manager header.
AutoModeNoticeScreen
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
Region
The closed set of LangSmith region selections in the /auth prompt.
ResolvedEndpoint
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
AuthResult
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
AuthConfirmScreen
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
DeleteCredentialConfirmScreen
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
AuthPromptScreen
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
AuthManagerScreen
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
CredentialSaved
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
CredentialDeleted
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.
InstallPackageConfirmScreen
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
InstallProviderConfirmScreen
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
RestartPromptScreen
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
SnapshotField
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,
DebugConsoleScreen
Modal showing a session snapshot and a live tail of recent log records.
NotificationActionResult
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
NotificationRowClicked
Posted when a notification row is clicked with the mouse.
NotificationSuppressRequested
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
NotificationSettingsRequested
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
NotificationActionRequested
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
NotificationCenterScreen
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
ToolApprovalWidget
Base class for tool approval widgets.
GenericApprovalWidget
Generic approval widget for unknown tools.
WriteFileApprovalWidget
Approval widget for write_file - shows file content with syntax highlighting.
EditFileApprovalWidget
Approval widget for edit_file - shows clean diff with colors.
StartupTip
One startup tip displayed above the chat input.
MCPLoginCancelledError
Raised by MCPLoginScreen.action_cancel when the user cancels the flow.
MCPLoginScreen
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
SubagentPanel
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
YoloModeNoticeResult
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
YoloModeNoticeScreen
In-TUI acknowledgement shown before unrestricted YOLO becomes active.
Dismisses with YoloModeNoticeResult.ACKNOWLEDGE on Enter (acknowledge and
enable), YoloModeNoticeResult.MANUAL on m (switch
PromptFilterInput
Prompt filter with standard modified-Backspace word deletion.
PromptSearchInput
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
AbandonSearch
Posted on Escape or empty-query Backspace, to close the search.
PromptSearchOption
One clickable prompt row in the inline search panel.
Clicked
Message sent when a prompt row is clicked.
PromptSearchPanel
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
RowsChanged
Message sent when the panel's rendered row count changes.
OptionSelected
Message sent when a prompt row is clicked in the panel.
CwdSwitchPromptScreen
Modal asking whether to switch cwd when resuming or switching to a thread.
HookTrustScreen
Ask how project hooks in a newly entered workspace should be trusted.
PasteBurstTextArea
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
CollapsingPasteTextArea
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
GoalStatusPanel
Keep the current goal and lifecycle state visible above the input.
DefaultModelScope
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
ModelOption
A clickable model option in the selector.
Clicked
Message sent when a model option is clicked.
CurrentModelTitle
Selector title whose current-model span copies on click.
ModelSelectorScreen
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
WelcomeBanner
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 `
HistoryManager
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.
AskUserTextArea
Free-form answer input for ask-user questions.
Adds two behaviors over the shared base:
- When the cursor is on the first or last line of a choice question's Other free-text input, Up/Down are han
Submitted
Posted when the user presses Enter to submit an ask-user answer.
AskUserMenu
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"
Answered
Message sent when user submits all answers.
Cancelled
Message sent when user cancels the ask_user prompt.
ThreadAgentSwitchPromptScreen
Ask before changing agents to resume a thread.
CodexAuthScreen
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 credentia
CodexSignedInAction
Outcome 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
CodexSignedInScreen
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 flow
ToolRenderer
Strategy 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
WriteFileRenderer
Renderer for write_file tool - shows full file content.
TaskRenderer
Renderer for task tool — interrupt description provides full context.
DeleteFileRenderer
Renderer for delete tool - shows removed file content when available.
EditFileRenderer
Renderer for edit_file tool - shows unified diff.
GoalReviewAccepted
Widget result when the generated criteria are accepted unchanged.
GoalReviewEdited
Widget result when the user submits revised criteria.
GoalReviewRejected
Widget result when the user rejects criteria with feedback.
GoalReviewCancelled
Widget result when the user cancels the proposal.
GoalReviewTextArea
Text input that keeps goal-review edit keystrokes inside the editor.
Submitted
Posted when the user presses Enter to submit goal-review text.
CancelEdit
Posted when Escape should leave goal criteria edit mode.
GoalReviewMenu
Inline review widget for generated goal acceptance criteria.
Decided
Message sent when the user accepts, edits, or cancels.
Functions
Modules
Types
format_release_age_parenthetical
Return " (released Nd ago)" for version, or "" when unknown.
record_model_usage_event
Record a validated provisional usage event from a nested model call.
resolve_auto_classifier_model
Resolve the model spec the Auto approval classifier should use.
is_safe_file_path
Reject deceptive controls and line separators without rewriting file paths.
get_project_agent_skills_dir
Return the project-level tool-agnostic .agents/skills directory.
read_approval_mode_from_store
Read a live approval mode from the server-side LangGraph Store.
bind_runtime_host_policy
Validate late routes and flag graph-bound registrations for restart.
