dreadnode.capabilities
API reference for the dreadnode.capabilities module.
Dreadnode capabilities.
Load capability directories that extend agent functionality with agents, tools, skills, and MCP servers.
AgentDef
Section titled “AgentDef”AgentDef( name: str, description: str, model: str = "inherit", system_prompt: str = "", tools: dict[str, bool] = dict(), skills: list[str] = list(), metadata: dict[str, Any] | None = None, capability: str | None = None,)Agent definition resolved from markdown frontmatter.
AgentLinkDef
Section titled “AgentLinkDef”AgentLinkDef( kind: Literal["delegate", "subagent", "handoff"], source: str, target: str,)Synthetic capability link between agents.
Capability
Section titled “Capability”Capability( capability: str | Path, *, cwd: Path | None = None, storage: Storage | None = None, capability_dirs: list[str | Path] | None = None, bundled: bool = False,)Resolved capability ready for SDK and runtime use.
bundled
Section titled “bundled”bundled: boolWhether this capability is the SDK-internal bundled platform capability.
Set by the loader (via load_capability(path, bundled=True)) for
exactly the capability shipped in dreadnode/builtin_capabilities.
Not a manifest field; not author-settable (CAP-IDENT-004/005).
worker_defs
Section titled “worker_defs”worker_defs: list[WorkerDef]Parsed worker entries from capability.yaml (CAP-WRK-001).
Module import is deferred to the WorkerLifecycleManager, which
evaluates the gate (CAP-WRK-007) before importing.
discover
Section titled “discover”discover( *, cwd: Path | None = None, storage: Storage | None = None, capability_dirs: list[str | Path] | None = None, workspace_dir: Path | None = None, host: str = "local",) -> DiscoverResultDiscover capabilities for a specific host type.
flag_env_vars
Section titled “flag_env_vars”flag_env_vars() -> dict[str, str]Build CAPABILITY_FLAG__* env vars from resolved flags (CAP-FLAG-020).
list( *, cwd: Path | None = None, storage: Storage | None = None, capability_dirs: list[str | Path] | None = None,) -> builtins.list[str]List capability names visible from the configured search paths.
resolve_flags
Section titled “resolve_flags”resolve_flags( persisted: dict[str, bool] | None = None, env_overrides: dict[str, bool] | None = None, cli_overrides: dict[str, bool] | None = None,) -> NoneResolve effective flag state from the four-layer override stack.
CapabilityManifest
Section titled “CapabilityManifest”Capability manifest stored in OCI config and on disk.
CapabilitySyncClient
Section titled “CapabilitySyncClient”CapabilitySyncClient( api: ApiClient, org: str, workspace: str, cache_dir: Path, runtime_id: str,)Downloads runtime capabilities from the platform into a local cache.
CAP-LOAD-010: sync before runtime starts. CAP-LOAD-012: cache is runtime-managed. CAP-LOAD-013: produces same directory layout the loader expects.
sync() -> SyncResultSync runtime capabilities from the platform.
Downloads enabled capabilities into the cache directory. Uses digest-based caching to skip unchanged capabilities.
DiscoverResult
Section titled “DiscoverResult”DiscoverResult( capabilities: dict[str, Capability] = dict(), disabled: dict[str, Capability] = dict(), failures: list[dict[str, Any]] = list(),)Result of capability discovery for a single host type.
LoadFailure
Section titled “LoadFailure”LoadFailure(name: str, path: Path, error: str)A capability that failed to load.
LoadOptions
Section titled “LoadOptions”LoadOptions(base_dir: Path | None = None)Options for loading a capability.
LoadResult
Section titled “LoadResult”LoadResult( capabilities: list[Capability] = list(), failures: list[LoadFailure] = list(),)Result of loading capabilities from search paths.
MCPServerDef
Section titled “MCPServerDef”MCPServerDef( name: str, transport: Literal["stdio", "streamable-http"], command: str | None = None, args: list[str] = list(), env: dict[str, str] | None = None, cwd: str | Path | None = None, url: str | None = None, headers: dict[str, str] | None = None, timeout: float | None = None, init_timeout: float | None = None, when: list[str] | None = None, source: Literal["inline", "file"] | None = None,)Parsed MCP server definition from a capability manifest.
CAP-MCP-002: transport is inferred from fields (command -> stdio, url -> streamable-http).
to_server_config
Section titled “to_server_config”to_server_config() -> t.AnyConvert to an MCPClient-compatible ServerConfig.
Resolves ${VAR} and ${VAR:-default} env placeholders at this point (connect time), not at capability load time, so that capabilities can be loaded/packaged without every secret being present.
SyncError
Section titled “SyncError”SyncError(name: str, error: str)A capability that failed to sync.
SyncResult
Section titled “SyncResult”SyncResult( synced: list[str] = list(), cached: list[str] = list(), removed: list[str] = list(), errors: list[SyncError] = list(), bindings: list[dict[str, Any]] = list(),)Result of runtime sync operation.
Worker
Section titled “Worker”Worker(name: str | None = None)Capability worker — long-running background component.
Constructed at module level in a capability’s workers/ directory.
Handler decorators register callables that the runtime dispatches during
the worker’s lifetime. Workers interact with the runtime exclusively
through a :class:RuntimeClient instance passed to each handler.
Construct a Worker (CAP-WAPI-001).
When loaded via a capability manifest, the manifest key is authoritative. If name is omitted, the loader assigns the key; if provided, it must match the key (mismatch is a validation error). Standalone workers (CAP-WTOP-002) must provide name.
arun() -> NoneAsync peer of :meth:run: install signal handlers, then drive the worker.
Factored from :meth:_run_until so tests can drive the lifecycle
without touching process-wide signal state.
every( *, seconds: float | None = None, minutes: float | None = None, cron: str | None = None,) -> t.Callable[[ClientHandler], ClientHandler]Register a recurring schedule handler (CAP-WAPI-006).
Exactly one of seconds, minutes, or cron must be provided.
Handler signature: async def handler(client) -> None.
on_event
Section titled “on_event”on_event( kind: str,) -> t.Callable[[EventHandler], EventHandler]Register an event handler (CAP-WAPI-005).
Returns a decorator. The decorated function is invoked for each
broker event whose kind field matches kind exactly.
Handler signature: async def handler(event, client) -> None.
on_shutdown
Section titled “on_shutdown”on_shutdown(fn: ClientHandler) -> ClientHandlerRegister a shutdown handler (CAP-WAPI-004).
Called once during worker stop, before the client is closed. Receives the runtime client as its first argument.
on_startup
Section titled “on_startup”on_startup(fn: ClientHandler) -> ClientHandlerRegister a startup handler (CAP-WAPI-003).
Called once when the worker starts, before any other handlers are active. Receives the runtime client as its first argument.
run() -> NoneLaunch this worker as a standalone process (CAP-WTOP-002).
Reads DREADNODE_RUNTIME_* env vars (CAP-WENV-001..003) via
:class:RuntimeClient, runs the worker until SIGTERM/SIGINT.
Intended use::
if __name__ == "__main__": worker.run()Use :meth:arun if you already have a running event loop.
task(fn: ClientHandler) -> ClientHandlerRegister a supervised long-running task (CAP-WAPI-007).
The decorated function runs for the worker’s lifetime. If it
returns or raises (except CancelledError), it is restarted
with exponential backoff.
Handler signature: async def handler(client) -> None.
get_default_capabilities_dir
Section titled “get_default_capabilities_dir”get_default_capabilities_dir() -> PathGet the default user capabilities directory.
list_capabilities
Section titled “list_capabilities”list_capabilities( directory: str | Path | None = None,) -> list[dict[str, t.Any]]List available capabilities without fully loading them.
load_capabilities
Section titled “load_capabilities”load_capabilities( directory: str | Path | None = None, options: LoadOptions | None = None, source: Literal["runtime", "local"] = "local",) -> LoadResultLoad all capabilities from a directory.
load_capabilities_from_search_paths
Section titled “load_capabilities_from_search_paths”load_capabilities_from_search_paths( search_paths: list[Path], options: LoadOptions | None = None, source: Literal["runtime", "local"] = "local",) -> LoadResultLoad capabilities from search paths.
If the same capability name appears in multiple directories, the first one wins.
load_capability
Section titled “load_capability”load_capability( path: str | Path, options: LoadOptions | None = None, source: Literal["runtime", "local"] = "local", *, bundled: bool = False,) -> t.AnyLoad a capability from a directory.
bundled is a loader-gated flag the SDK sets only for the built-in
platform capability shipped in dreadnode/builtin_capabilities. Authors
cannot set it; the manifest contract has no corresponding field. Under
CAP-IDENT-004/005, bundled capabilities are exempt from wire-name
qualification and keep their bare tool names.
merge_capabilities
Section titled “merge_capabilities”merge_capabilities( capabilities: list[Any],) -> MergedCapabilitiesMerge multiple capabilities into one.
resolve_search_paths
Section titled “resolve_search_paths”resolve_search_paths( *, capability_dirs: list[str | Path] | None = None, cwd: Path | None = None, user_dir: str | Path | None = None,) -> list[Path]Resolve capability discovery search paths (CAP-LOAD-001).
Precedence:
- Project-local .dreadnode/capabilities
- User-local ~/.dreadnode/capabilities
- Explicit dirs (CLI flags)
- DREADNODE_CAPABILITY_DIRS env list High-level resolved capability object.
Capability
Section titled “Capability”Capability( capability: str | Path, *, cwd: Path | None = None, storage: Storage | None = None, capability_dirs: list[str | Path] | None = None, bundled: bool = False,)Resolved capability ready for SDK and runtime use.
bundled
Section titled “bundled”bundled: boolWhether this capability is the SDK-internal bundled platform capability.
Set by the loader (via load_capability(path, bundled=True)) for
exactly the capability shipped in dreadnode/builtin_capabilities.
Not a manifest field; not author-settable (CAP-IDENT-004/005).
worker_defs
Section titled “worker_defs”worker_defs: list[WorkerDef]Parsed worker entries from capability.yaml (CAP-WRK-001).
Module import is deferred to the WorkerLifecycleManager, which
evaluates the gate (CAP-WRK-007) before importing.
discover
Section titled “discover”discover( *, cwd: Path | None = None, storage: Storage | None = None, capability_dirs: list[str | Path] | None = None, workspace_dir: Path | None = None, host: str = "local",) -> DiscoverResultDiscover capabilities for a specific host type.
flag_env_vars
Section titled “flag_env_vars”flag_env_vars() -> dict[str, str]Build CAPABILITY_FLAG__* env vars from resolved flags (CAP-FLAG-020).
list( *, cwd: Path | None = None, storage: Storage | None = None, capability_dirs: list[str | Path] | None = None,) -> builtins.list[str]List capability names visible from the configured search paths.
resolve_flags
Section titled “resolve_flags”resolve_flags( persisted: dict[str, bool] | None = None, env_overrides: dict[str, bool] | None = None, cli_overrides: dict[str, bool] | None = None,) -> NoneResolve effective flag state from the four-layer override stack.
DiscoverResult
Section titled “DiscoverResult”DiscoverResult( capabilities: dict[str, Capability] = dict(), disabled: dict[str, Capability] = dict(), failures: list[dict[str, Any]] = list(),)Result of capability discovery for a single host type.
read_local_capability_records
Section titled “read_local_capability_records”read_local_capability_records( path: Path,) -> dict[str, dict[str, t.Any]]Read persisted local capability records keyed by bare capability name.
read_local_capability_state
Section titled “read_local_capability_state”read_local_capability_state(path: Path) -> dict[str, bool]Read persisted local capability state keyed by bare capability name.
write_local_capability_records
Section titled “write_local_capability_records”write_local_capability_records( path: Path, state: dict[str, dict[str, Any]]) -> NonePersist structured local capability records keyed by bare capability name.
write_local_capability_state
Section titled “write_local_capability_state”write_local_capability_state( path: Path, state: dict[str, bool]) -> NonePersist local capability state keyed by bare capability name. Capability loader — v1 spec.
Load capabilities from disk, validate against the v1 contract, and prepare for use.
See specs/capabilities/ for the canonical spec.
get_default_capabilities_dir
Section titled “get_default_capabilities_dir”get_default_capabilities_dir() -> PathGet the default user capabilities directory.
list_capabilities
Section titled “list_capabilities”list_capabilities( directory: str | Path | None = None,) -> list[dict[str, t.Any]]List available capabilities without fully loading them.
load_capabilities
Section titled “load_capabilities”load_capabilities( directory: str | Path | None = None, options: LoadOptions | None = None, source: Literal["runtime", "local"] = "local",) -> LoadResultLoad all capabilities from a directory.
load_capabilities_from_search_paths
Section titled “load_capabilities_from_search_paths”load_capabilities_from_search_paths( search_paths: list[Path], options: LoadOptions | None = None, source: Literal["runtime", "local"] = "local",) -> LoadResultLoad capabilities from search paths.
If the same capability name appears in multiple directories, the first one wins.
load_capability
Section titled “load_capability”load_capability( path: str | Path, options: LoadOptions | None = None, source: Literal["runtime", "local"] = "local", *, bundled: bool = False,) -> t.AnyLoad a capability from a directory.
bundled is a loader-gated flag the SDK sets only for the built-in
platform capability shipped in dreadnode/builtin_capabilities. Authors
cannot set it; the manifest contract has no corresponding field. Under
CAP-IDENT-004/005, bundled capabilities are exempt from wire-name
qualification and keep their bare tool names.
load_worker_from_def
Section titled “load_worker_from_def”load_worker_from_def( worker_def: WorkerDef, capability_path: Path, capability_name: str,) -> t.AnyImport a worker module on behalf of the lifecycle manager (CAP-WRK-002, CAP-WRK-007).
Only called when the worker’s gate is satisfied. Enforces exactly one
Worker instance per file. Assigns the manifest key as the worker’s
name when the constructor omitted it; validates equality when provided.
Raises ImportError on module import failure or ValueError when
the file exposes zero or multiple Worker instances, or when the
constructor name conflicts with the manifest key.
merge_capabilities
Section titled “merge_capabilities”merge_capabilities( capabilities: list[Any],) -> MergedCapabilitiesMerge multiple capabilities into one.
parse_mcp_servers
Section titled “parse_mcp_servers”parse_mcp_servers( mcp: dict[str, Any] | None, capability_path: Path, component_health: list[dict[str, Any]] | None = None, *, declared_flags: set[str] | None = None, manifest_path: Path | None = None,) -> list[MCPServerDef]Parse MCP server definitions from a capability manifest.
CAP-MCP-001: files and inline servers are merged, inline wins on name conflict. Returns empty list for mcp={} (explicit disable). Auto-discovers .mcp.json and mcp.json when mcp is None.
parse_workers
Section titled “parse_workers”parse_workers( workers: dict[str, Any] | None, capability_path: Path, component_health: list[dict[str, Any]] | None = None, *, declared_flags: set[str] | None = None, manifest_path: Path | None = None,) -> list[WorkerDef]Parse worker entries from a capability manifest (CAP-WRK-001).
Returns an empty list when workers is None or \{\}. Validates each
entry’s name, path, and optional when: predicate. Paths that fail
validation produce a component_health error entry but don’t abort
the rest of the capability load (mirrors CAP-MCP-007).
resolve_search_paths
Section titled “resolve_search_paths”resolve_search_paths( *, capability_dirs: list[str | Path] | None = None, cwd: Path | None = None, user_dir: str | Path | None = None,) -> list[Path]Resolve capability discovery search paths (CAP-LOAD-001).
Precedence:
- Project-local .dreadnode/capabilities
- User-local ~/.dreadnode/capabilities
- Explicit dirs (CLI flags)
- DREADNODE_CAPABILITY_DIRS env list Capability sync — downloads capabilities from the platform.
See specs/capabilities/runtime.md (CAP-LOAD-010..013).
CapabilitySyncClient
Section titled “CapabilitySyncClient”CapabilitySyncClient( api: ApiClient, org: str, workspace: str, cache_dir: Path, runtime_id: str,)Downloads runtime capabilities from the platform into a local cache.
CAP-LOAD-010: sync before runtime starts. CAP-LOAD-012: cache is runtime-managed. CAP-LOAD-013: produces same directory layout the loader expects.
sync() -> SyncResultSync runtime capabilities from the platform.
Downloads enabled capabilities into the cache directory. Uses digest-based caching to skip unchanged capabilities.
LocalInstallClient
Section titled “LocalInstallClient”LocalInstallClient( api: ApiClient, org: str, local_dir: Path, state_path: Path,)Install registry-backed capabilities into the local user store.
LocalInstallResult
Section titled “LocalInstallResult”LocalInstallResult( installed_name: str, source: str, overwritten: bool = False,)Result of a local registry-backed capability install.
SyncError
Section titled “SyncError”SyncError(name: str, error: str)A capability that failed to sync.
SyncResult
Section titled “SyncResult”SyncResult( synced: list[str] = list(), cached: list[str] = list(), removed: list[str] = list(), errors: list[SyncError] = list(), bindings: list[dict[str, Any]] = list(),)Result of runtime sync operation.
bare_capability_name
Section titled “bare_capability_name”bare_capability_name(qualified_name: str) -> strExtract the bare name from an org-qualified capability name.
e.g., ‘acme/github’ -> ‘github’ If no ’/’ present, returns the name as-is.
decode_capability_dirname
Section titled “decode_capability_dirname”decode_capability_dirname(dirname: str) -> strDecode a directory name back to a capability name.
Replaces the first ’_’ with ’/’ (canonical names have exactly one ’/’). e.g., ‘acme_github’ -> ‘acme/github’
encode_capability_dirname
Section titled “encode_capability_dirname”encode_capability_dirname(name: str) -> strEncode a capability name for use as a directory name.
Replaces ’/’ with ’_’ to avoid nested directories. This is bijective because capability name parts follow [a-z0-9][a-z0-9-]* (no underscores). e.g., ‘acme/github’ -> ‘acme_github’
install_local
Section titled “install_local”install_local( *, source_path: Path, local_dir: Path, state_path: Path, name: str, version: str, overwrite: bool, copy: bool = False,) -> LocalInstallResultInstall a capability from a local directory into the user store.
By default, creates a symlink so edits to the source are live.
Pass copy=True to create a frozen snapshot instead.
The caller is responsible for validating the capability before calling
this function (e.g. via Capability(source_path)).
Capability type definitions — v1 spec.
See specs/capabilities/contract.md for the canonical schema.
AgentDef
Section titled “AgentDef”AgentDef( name: str, description: str, model: str = "inherit", system_prompt: str = "", tools: dict[str, bool] = dict(), skills: list[str] = list(), metadata: dict[str, Any] | None = None, capability: str | None = None,)Agent definition resolved from markdown frontmatter.
AgentLinkDef
Section titled “AgentLinkDef”AgentLinkDef( kind: Literal["delegate", "subagent", "handoff"], source: str, target: str,)Synthetic capability link between agents.
DependencySpec
Section titled “DependencySpec”DependencySpec( python: list[str] = list(), packages: list[str] = list(), scripts: list[str] = list(),)Declared runtime dependencies from capability.yaml.
These fields are sandbox-specific — they describe what a managed sandbox (E2B/Docker) needs. Ignored for local installs.
HealthCheck
Section titled “HealthCheck”HealthCheck(name: str, command: str)Pre-flight check definition from capability.yaml.
Runs on load for enabled capabilities. Exit code 0 = pass, non-zero = fail. Failed checks produce a component_health entry with kind=“check”.
LoadFailure
Section titled “LoadFailure”LoadFailure(name: str, path: Path, error: str)A capability that failed to load.
LoadOptions
Section titled “LoadOptions”LoadOptions(base_dir: Path | None = None)Options for loading a capability.
LoadResult
Section titled “LoadResult”LoadResult( capabilities: list[Capability] = list(), failures: list[LoadFailure] = list(),)Result of loading capabilities from search paths.
MCPServerDef
Section titled “MCPServerDef”MCPServerDef( name: str, transport: Literal["stdio", "streamable-http"], command: str | None = None, args: list[str] = list(), env: dict[str, str] | None = None, cwd: str | Path | None = None, url: str | None = None, headers: dict[str, str] | None = None, timeout: float | None = None, init_timeout: float | None = None, when: list[str] | None = None, source: Literal["inline", "file"] | None = None,)Parsed MCP server definition from a capability manifest.
CAP-MCP-002: transport is inferred from fields (command -> stdio, url -> streamable-http).
to_server_config
Section titled “to_server_config”to_server_config() -> t.AnyConvert to an MCPClient-compatible ServerConfig.
Resolves ${VAR} and ${VAR:-default} env placeholders at this point (connect time), not at capability load time, so that capabilities can be loaded/packaged without every secret being present.
WorkerDef
Section titled “WorkerDef”WorkerDef( name: str, path: Path | None = None, command: str | None = None, args: list[str] = list(), env: dict[str, str] = dict(), when: list[str] | None = None,)Parsed worker entry from a capability manifest.
Two kinds, mutually exclusive (CAP-WTOP-004):
- In-process Python worker — populates :attr:
path; the runtime imports the module and drives the :class:Workerinstance viaWorkerRunner. - Subprocess worker — populates :attr:
command(with optional :attr:args/ :attr:env); the runtime spawns and supervises it, injecting theDREADNODE_RUNTIME_*env contract (CAP-WENV-001..003).
See CAP-WRK-001/002/007 and CAP-WTOP-004..009 in specs/capabilities/workers.md.
is_subprocess
Section titled “is_subprocess”is_subprocess: boolTrue when this worker is a runtime-spawned subprocess (CAP-WTOP-004). Capability flag definitions, validation, and resolution — v1 spec.
See specs/capabilities/flags.md for the canonical rules (CAP-FLAG-*).
FlagDef
Section titled “FlagDef”FlagDef(name: str, description: str, default: bool = False)Author-declared flag from capability.yaml.
ResolvedFlag
Section titled “ResolvedFlag”ResolvedFlag( name: str, description: str, default: bool, effective: bool, source: Literal["default", "binding", "env", "cli"],)Effective flag state after merging the four-layer override stack.
evaluate_when
Section titled “evaluate_when”evaluate_when( when: list[str] | None, resolved: list[ResolvedFlag]) -> boolEvaluate a when predicate against resolved flag state.
Returns True if the component should be loaded (CAP-FLAG-011).
flag_to_env_name
Section titled “flag_to_env_name”flag_to_env_name( capability_name: str, flag_name: str) -> strConvention env var injected into MCP subprocesses and tool imports (CAP-FLAG-021).
override_env_name
Section titled “override_env_name”override_env_name( capability_name: str, flag_name: str) -> strUser-facing override env var (CAP-FLAG-032).
parse_cli_flags
Section titled “parse_cli_flags”parse_cli_flags( raw: list[str] | None,) -> dict[str, dict[str, bool]]Parse --capability-flag capability.flag=true|false values (CAP-FLAG-033).
read_env_overrides
Section titled “read_env_overrides”read_env_overrides( capability_name: str, flag_defs: list[FlagDef]) -> dict[str, bool]Read DREADNODE_CAPABILITY_FLAG__* overrides from os.environ (CAP-FLAG-032).
resolve_flags
Section titled “resolve_flags”resolve_flags( flag_defs: list[FlagDef], persisted: dict[str, bool] | None = None, env_overrides: dict[str, bool] | None = None, cli_overrides: dict[str, bool] | None = None,) -> list[ResolvedFlag]Resolve effective state for each declared flag via the four-layer stack.
validate_flags_block
Section titled “validate_flags_block”validate_flags_block( raw: dict[str, Any] | None, manifest_path: Path) -> list[FlagDef]Validate the top-level flags block and return parsed definitions.
Returns an empty list when raw is None or \{\}.
validate_when
Section titled “validate_when”validate_when( when: Any, declared_flags: set[str], component_name: str, manifest_path: Path, *, source: str = "inline", component_kind: str = "MCP server",) -> list[str] | NoneValidate a when predicate on a gate-eligible component (MCP server or worker).
Returns the validated flag-name list, or None for “always load”. Capability worker — long-running background component.
A Worker is constructed at module level in a capability’s workers/*.py file.
Decorator-based handlers register callables; the runtime dispatches them during
the worker’s lifetime.
Example::
from dreadnode.capabilities.worker import Worker, EventEnvelope, RuntimeClient
worker = Worker(name="bridge")
@worker.on_startupasync def connect(client: RuntimeClient) -> None: worker.state["ws"] = await open_websocket()
@worker.on_event("turn.completed")async def on_turn(event: EventEnvelope, client: RuntimeClient) -> None: await forward_result(worker.state["ws"], event.payload)
@worker.every(seconds=30)async def heartbeat(client: RuntimeClient) -> None: await worker.state["ws"].ping()ClientHandler
Section titled “ClientHandler”ClientHandler = Callable[["RuntimeClient"], Awaitable[None]]Signature for on_startup, on_shutdown, every, and task handlers.
EventHandler
Section titled “EventHandler”EventHandler = Callable[ ["RuntimeEventEnvelope", "RuntimeClient"], Awaitable[None],]Signature for on_event handlers.
RuntimeClient
Section titled “RuntimeClient”RuntimeClient( server_url: str | None = None, *, auth_token: str | None = None, transport: AsyncBaseTransport | None = None, default_notify_source: str | None = None, default_session_labels: dict[str, list[str]] | None = None, default_session_origin: str | None = None,)Client for interacting with a running Dreadnode runtime server.
Provides session management, chat streaming, event subscription,
and runtime discovery. Assumes the server is already running —
use :class:~dreadnode.app.client.managed_client.ManagedRuntimeClient
when you need to start or manage the server process.
is_started
Section titled “is_started”is_started: boolWhether the client has verified server connectivity.
browse_session_facets
Section titled “browse_session_facets”browse_session_facets( *, archived: Literal[ "active", "archived", "any" ] = "active", label: list[str] | None = None, user_id: str | None = None, project_id: list[str] | None = None, origin: list[str] | None = None, search: str | None = None, include_workload_sessions: bool = False,) -> models.SessionFacetsPer-key value counts for the sidebar facets on the table view.
Parallels :meth:browse_sessions — takes the same filter set
(minus pagination / sort) and returns a typed
:class:~dreadnode.app.client.models.SessionFacets envelope.
Keys with zero matches are omitted by the platform, so the result
only carries the keys the caller can act on. Honors the same
SES-LST-009 workload default as the list endpoint.
browse_sessions
Section titled “browse_sessions”browse_sessions( *, page: int = 1, limit: int = 20, sort_by: Literal[ "updated_at", "last_message_at", "created_at", "message_count", ] = "updated_at", sort_dir: Literal["asc", "desc"] = "desc", archived: Literal[ "active", "archived", "any" ] = "active", label: list[str] | None = None, user_id: str | None = None, project_id: list[str] | None = None, origin: list[str] | None = None, search: str | None = None, include_workload_sessions: bool = False,) -> models.SessionListResultPaginated browse of platform-persisted sessions for this workspace.
Pass-through for the platform’s GET /sessions query shape — the
runtime forwards every kwarg as a query param and returns the
platform’s paginated envelope verbatim. In-process sessions are
not merged on this path; the table view trusts that
_register_session_with_platform syncs new sessions within a
turn. Use :meth:list_sessions for live in-process state.
include_workload_sessions (SES-LST-009) defaults to False
so the table view hides eval (and future optimization / training
/ world) runs. Callers that want them — the agents page, analytics
— pass True.
cancel_session
Section titled “cancel_session”cancel_session(session_id: str) -> NoneCancel the active turn for a session.
close() -> NoneClose network resources (HTTP client and interactive transport).
compact_session
Section titled “compact_session”compact_session( session_id: str, *, guidance: str = "") -> dict[str, t.Any]Request manual compaction of a session.
create_session
Section titled “create_session”create_session( *, capability: str | None = None, agent: str | None = None, model: str | None = None, session_id: str | None = None, project: str | None = None, generate_params_extra: dict[str, Any] | None = None, policy: str | dict[str, Any] | None = None, labels: dict[str, list[str]] | None = None, origin: str | None = None,) -> models.SessionInfoCreate or resolve a session on the server.
If session_id is provided and a session with that ID already exists, the call is idempotent and returns the existing session (CAP-WCLI-003).
delete_session
Section titled “delete_session”delete_session(session_id: str) -> NoneDelete a server session.
execute_shell
Section titled “execute_shell”execute_shell( command: str, *, cwd: str | None = None, timeout: int = 30,) -> dict[str, t.Any]Execute a shell command on the server.
fetch_mcp_detail
Section titled “fetch_mcp_detail”fetch_mcp_detail( capability: str, server_name: str) -> dict[str, t.Any]Fetch full detail for an MCP server.
fetch_runtime_info
Section titled “fetch_runtime_info”fetch_runtime_info() -> models.RuntimeInfoFetch runtime metadata from the connected server.
fetch_session_messages
Section titled “fetch_session_messages”fetch_session_messages( session_id: str,) -> list[dict[str, t.Any]]Fetch conversation messages for a session.
fetch_skill_content
Section titled “fetch_skill_content”fetch_skill_content(name: str) -> strFetch rendered skill content by name.
fetch_skills
Section titled “fetch_skills”fetch_skills() -> list[models.SkillInfo]Fetch available skills from runtime.
fetch_tools
Section titled “fetch_tools”fetch_tools() -> list[models.ToolInfo]Fetch available tools from runtime.
fetch_worker_detail
Section titled “fetch_worker_detail”fetch_worker_detail( capability: str, worker_name: str) -> dict[str, t.Any]Fetch full detail for a capability worker.
list_files
Section titled “list_files”list_files( path: str | None = None, depth: int = 10) -> list[dict[str, t.Any]]List files in a directory on the server.
list_sessions
Section titled “list_sessions”list_sessions( *, include_platform: bool = False) -> list[models.SessionInfo]List in-process sessions from the connected server (the boot/swap fast path).
Returns only sessions the runtime knows about in memory. include_platform
is preserved for callers that don’t yet differentiate the two paths — when
true, the runtime falls back to delegating to browse_sessions(page=1, limit=100)
and returns the flat sessions list. New code wanting paginated platform
history should call :meth:browse_sessions directly so it gets the
envelope (total, page, etc.).
notify
Section titled “notify”notify( title: str, *, body: str | None = None, severity: Literal[ "info", "warning", "error", "success" ] = "info", source: str | None = None, session_id: str | None = None,) -> dict[str, t.Any]Publish a user-facing notification (CAP-WCLI-014, CAP-WEVT-004).
Notifications are runtime-scope unless session_id is provided.
source defaults to the client’s configured
default_notify_source — worker-hosted clients get
capability.<name>; standalone clients leave it empty unless
the caller supplies one.
publish
Section titled “publish”publish( kind: str, payload: dict[str, Any] | None = None, *, session_id: str | None = None,) -> dict[str, t.Any]Publish an event onto the runtime event bus (CAP-WCLI-013).
When session_id is provided the event is session-scoped; otherwise
it is runtime-scope. Subscribers matching the event’s kind receive
it regardless of scope (CAP-WEVT-002). Reserved-prefix kinds
(turn., prompt., session., transport.,
capabilities.) are rejected at the server per CAP-WEVT-003.
read_file
Section titled “read_file”read_file(path: str) -> strRead a file’s content from the server.
reconnect_mcp_server
Section titled “reconnect_mcp_server”reconnect_mcp_server( capability: str, server_name: str) -> dict[str, t.Any]Reconnect an MCP server and return updated detail.
reload_capabilities
Section titled “reload_capabilities”reload_capabilities() -> models.RuntimeInfoTell the server to re-discover capabilities and return updated runtime info.
reset_session
Section titled “reset_session”reset_session(session_id: str) -> NoneReset a server session.
restart_worker
Section titled “restart_worker”restart_worker( capability: str, worker_name: str) -> dict[str, t.Any]Restart a capability worker and return updated detail.
run_turn
Section titled “run_turn”run_turn( *, session_id: str, message: str, model: str | None = None, agent: str | None = None, reset: bool = False, generate_params_extra: dict[str, Any] | None = None,) -> dict[str, t.Any]Run a turn to completion and return the terminal turn.completed
payload (CAP-WEVT-007): response_text, tool_calls, usage,
duration_ms, turn_id.
Use this when you want the final result without iterating individual
agent events. For streaming UIs, use :meth:stream_chat instead.
Raises :class:TurnFailedError on turn.failed (carrying the
error_type, partial_response, and any attempted tool calls)
and :class:TurnCancelledError on turn.cancelled.
send_human_input_response
Section titled “send_human_input_response”send_human_input_response( session_id: str, response: HumanInputResponse) -> NoneSend a human input response back to the server via the interactive websocket.
send_permission_response
Section titled “send_permission_response”send_permission_response( session_id: str, request_id: str, decision: str) -> NoneSend a permission decision back to the server via the interactive websocket.
set_session_policy
Section titled “set_session_policy”set_session_policy( session_id: str, policy: str | dict[str, Any] | None) -> dict[str, t.Any]Swap a session’s active policy mid-run.
Returns the server response dict with policy_name,
policy_is_autonomous, and policy_display_label
populated from the resolved policy class.
set_session_title
Section titled “set_session_title”set_session_title(session_id: str, title: str) -> NonePersist a session title on the server.
start() -> NoneVerify the server is reachable.
Subclasses override this to add server lifecycle management (e.g., auto-starting an in-process or subprocess server).
stream_chat
Section titled “stream_chat”stream_chat( *, session_id: str, message: str, model: str | None = None, agent: str | None = None, reset: bool = False, generate_params_extra: dict[str, Any] | None = None,) -> t.AsyncIterator[dict[str, t.Any]]Stream websocket chat events for one session turn.
subscribe
Section titled “subscribe”subscribe( *kinds: str,) -> t.AsyncIterator[RuntimeEventEnvelope]Subscribe to runtime-bus events filtered by kinds (CAP-WCLI-018).
Returns an async iterator yielding :class:RuntimeEventEnvelope
values. kinds is variadic; passing none subscribes to every
event. Session- and runtime-scope envelopes both flow through —
consumers inspect session_id to distinguish (CAP-WEVT-002).
The iterator yields events until the caller closes it
(aclose() or breaking out of async for) or authentication
is rejected. History is not replayed (CAP-WCLI-020).
On transient transport loss the client reconnects with
exponential backoff, reinstates the original kinds filter,
and yields a synthetic transport.reconnected envelope before
resuming (CAP-WCLI-021). Events published while disconnected
are not replayed; subscribers that need durability own their
own resync.
Peer of :meth:subscribe_session (CAP-WCLI-011); independent
from the interactive transport, so standalone worker processes
can iterate the runtime bus without opening a session-control
channel.
subscribe_session
Section titled “subscribe_session”subscribe_session(session_id: str) -> NoneKeep a session subscribed on the interactive websocket.
unsubscribe_session
Section titled “unsubscribe_session”unsubscribe_session(session_id: str) -> NoneDrop a session subscription from the interactive websocket.
ScheduleSpec
Section titled “ScheduleSpec”ScheduleSpec( interval_seconds: float | None = None, cron_expr: str | None = None,)Parsed schedule for an @worker.every(...) handler.
TurnCancelledError
Section titled “TurnCancelledError”TurnCancelledError( reason: str, *, partial_response: str | None = None, turn_id: str | None = None,)Raised by :meth:RuntimeClient.run_turn on a turn.cancelled terminal.
Carries the synthesized turn trajectory (CAP-WEVT-009) so callers can
recover any partial_response the agent produced before cancellation.
TurnFailedError
Section titled “TurnFailedError”TurnFailedError( error_type: str, message: str, *, partial_response: str | None = None, tool_calls_attempted: list[dict[str, Any]] | None = None, turn_id: str | None = None,)Raised by :meth:RuntimeClient.run_turn on a turn.failed terminal.
Carries the synthesized turn trajectory (CAP-WEVT-008) so callers can
inspect error_type, partial_response, and any tool calls the
model attempted before the failure.
Worker
Section titled “Worker”Worker(name: str | None = None)Capability worker — long-running background component.
Constructed at module level in a capability’s workers/ directory.
Handler decorators register callables that the runtime dispatches during
the worker’s lifetime. Workers interact with the runtime exclusively
through a :class:RuntimeClient instance passed to each handler.
Construct a Worker (CAP-WAPI-001).
When loaded via a capability manifest, the manifest key is authoritative. If name is omitted, the loader assigns the key; if provided, it must match the key (mismatch is a validation error). Standalone workers (CAP-WTOP-002) must provide name.
arun() -> NoneAsync peer of :meth:run: install signal handlers, then drive the worker.
Factored from :meth:_run_until so tests can drive the lifecycle
without touching process-wide signal state.
every( *, seconds: float | None = None, minutes: float | None = None, cron: str | None = None,) -> t.Callable[[ClientHandler], ClientHandler]Register a recurring schedule handler (CAP-WAPI-006).
Exactly one of seconds, minutes, or cron must be provided.
Handler signature: async def handler(client) -> None.
on_event
Section titled “on_event”on_event( kind: str,) -> t.Callable[[EventHandler], EventHandler]Register an event handler (CAP-WAPI-005).
Returns a decorator. The decorated function is invoked for each
broker event whose kind field matches kind exactly.
Handler signature: async def handler(event, client) -> None.
on_shutdown
Section titled “on_shutdown”on_shutdown(fn: ClientHandler) -> ClientHandlerRegister a shutdown handler (CAP-WAPI-004).
Called once during worker stop, before the client is closed. Receives the runtime client as its first argument.
on_startup
Section titled “on_startup”on_startup(fn: ClientHandler) -> ClientHandlerRegister a startup handler (CAP-WAPI-003).
Called once when the worker starts, before any other handlers are active. Receives the runtime client as its first argument.
run() -> NoneLaunch this worker as a standalone process (CAP-WTOP-002).
Reads DREADNODE_RUNTIME_* env vars (CAP-WENV-001..003) via
:class:RuntimeClient, runs the worker until SIGTERM/SIGINT.
Intended use::
if __name__ == "__main__": worker.run()Use :meth:arun if you already have a running event loop.
task(fn: ClientHandler) -> ClientHandlerRegister a supervised long-running task (CAP-WAPI-007).
The decorated function runs for the worker’s lifetime. If it
returns or raises (except CancelledError), it is restarted
with exponential backoff.
Handler signature: async def handler(client) -> None.