Tool Harness
Every capability an agent can use — file editing, shell execution, plugins, MCP servers, browser control, memory, workers — enters through one tool harness. The harness decides which tools exist in a session, who may call them, what must be approved, and how the call is observed.
Execution pipeline
flowchart LR
A["Session prompt"] --> B["SessionEngine + Agent loop"]
B --> C["Tool list assembly"]
C --> D["Model selects a tool"]
D --> E["beforeToolCall hooks"]
E --> F["Permission guard + approval center"]
F -->|approved| G["Tool execute(arguments, signal, onUpdate)"]
G --> H["afterToolCall / result post-processing"]
H --> I["Session events + JSONL"]
F -->|denied| IThe runtime builds a tool list per session, streams model turns, executes tool calls one at a time or in parallel depending on the SDK tool mode, and emits ToolExecutionStart, ToolExecutionUpdate, and ToolExecutionEnd events. Every call carries a RunSignal; cancellation propagates through the shell executor and the tool itself, and cancelled runs are never retried automatically.
Tool catalog
core/runtime-api defines the catalog in BaseToolCatalog. Each tool has an id, group, tier, kind, risk, platform, and availability flag.
| Tier | Meaning |
|---|---|
CORE_LOCKED | Always enabled, cannot be turned off per bot: read, write, edit, ls, grep, find, bash, ask_user_question |
CONFIGURABLE | Users can toggle it per bot: web_search, web_fetch, todo_write, goal, job, timer, present, calendar (Android), system_shell (Android, requires the system shell) |
Groups are web, planning, delivery, and platform. Kinds are read, write, execute, network, planning, interaction, platform. Risks are safe, mutating, and privileged; the permission guard uses them to decide when a prompt is required.
Beside built-in tools, a session can contain:
- Plugin tools — returned by
contributionsFor(host, session)from.ddpplugins.DIRECTtools are resident;DEFERREDtools are searchable but not directly callable. - MCP tools — loaded from configured MCP servers and named
mcp__<server>__<tool>. - Deferred tools — MCP/plugin tools hidden from the resident list. The model calls
tool_searchto inspect parameters andtool_executeto run one by name. - Platform tools — screen control, mini-app tools, browser tools, and memory dispatch, enabled by their own per-bot settings.
Tool assembly lives in AppTools.kt (AppToolContext, appTools) and in the host/session wiring that adds built-in tools, plugin tools, deferred tools, and platform factories.
Tool contract
A tool is an SDK CodingTool (which is exposed to the agent as AgentTool) with:
| Field | Purpose |
|---|---|
name | Stable snake_case identifier |
description | What it does, when to use it, and its limits |
parameters | JSON Schema object passed to the model as-is |
label, promptSnippet, promptGuidelines | UI title and system-prompt hints |
execute | suspend function receiving the call id, parsed arguments, a RunSignal, and an optional partial-update callback |
Rules the runtime relies on:
- Arguments are validated against the schema before execution; a validation failure becomes an error result, not a crash.
onUpdatestreams partial progress to the UI (ToolExecutionUpdate); it never substitutes for the final result.- Cancellation must throw, not be swallowed. Shell tools stop the process; file tools stop at safe boundaries.
- Results are bounded.
bashkeeps the last 2000 lines or 50 KB, appends an[exit: N]marker, and can spill a full log for oversized output. - Long commands run in the background through the
jobtool, which returns a job id and log path;job(list/status/output/kill)inspects or stops them.
Approvals
Human authorization is centralized in ToolApprovalCenter, deliberately separate from QuestionCenter so permissions are never routed through ordinary question cards or delegated to another model.
| Concept | Values |
|---|---|
| Risk level | STANDARD, OUTSIDE_WORKSPACE (write outside the workspace root), DESTRUCTIVE |
| Reason | COMMAND_EXECUTION, OUTSIDE_WORKSPACE_WRITE, DESTRUCTIVE_COMMAND |
| Decision | ALLOW_ONCE, ALLOW_SESSION, DENY (a timeout also denies, with the elapsed time in the reason) |
- Each pending approval becomes a
PendingToolApproval(session id, optional worker id, tool call id, tool name, risk, reason, command/path, workspace root, detail) that the UI renders and resolves. - Session grants are persisted crash-safely; a
DESTRUCTIVEapproval is never satisfied by a session grant. - Interrupted approvals survive a restart and can be reviewed instead of silently failing.
- Workers have their own approval path (
worker.tool_approval/worker.approval), so a coordinator sees remote prompts without taking them over. - If the host UI is not connected, guarded calls fail with a readable explanation rather than auto-approving.
Permission modes
Desktop and Host sessions use four modes from ToolPermissionGuard.PermissionMode:
| Mode | Behavior |
|---|---|
read_only | Denies file mutations, shell/job execution, and other mutating tools; allows read-only browser actions and read-only timer/goal queries |
ask_commands | Allows in-workspace edits; prompts before shell execution and outside-workspace writes |
workspace_auto | Auto-runs in-workspace edits and normal commands; prompts for destructive commands and outside-workspace writes |
full_auto | Executes without interactive prompts (still subject to hard denials such as unreadable workspaces) |
The guard wraps only tools that can mutate state: write, edit, bash, job, timer, goal, memory_dispatch, browser, tool_execute, and every mcp__* tool. It also:
- resolves the workspace root with
toRealPath()and walks ancestors withNOFOLLOW_LINKS, so symlinks cannot escape the workspace; - classifies destructive commands with explicit patterns (
rm -rf /-style targets,sudo, force-push,git reset --hard,git clean -f, disk tools,dd if=, recursivechmod 777,curl | sh); - applies the mode per Bot on the Host, so a local session and its workers can run under different policies.
Hooks
Two hook layers can observe or transform a call:
- SDK hooks (
ToolCallHookson the agent):beforeToolCallandafterToolCallreceive the call context and result. The runtime bridges its ownRuntimeHooksinto them. - Plugin hooks (
PluginHooks.beforeToolCall,afterToolExecution): plugins can continue, block with a reason, rewrite arguments, or replace a result. Built-ins run first, then plugins in registration order.beforeToolCallis fail-closed: a timeout or exception blocks the call.afterToolExecutionkeeps the previous result on timeout or failure.
- Prompt/input/context transforms (
promptTransform,inputTransform,context) run on the same dispatch path.contextinjects retrieval or memory text into the system prompt; transforms run serially with short timeouts and must not block on network or human input. - Read-before-edit guard (
ReadBeforeEditDecorator):editrequires the file to have been read in the same session, and an overwritingwriterequires a prior read; stale files must be re-read.
A run freezes its hook set when it starts: enabling or disabling plugins mid-run takes effect on the next run, and a frozen plugin may still receive the remaining events of the current run.
Workers and subagents
Orch mode is a coordinator session plus persistent worker sessions. The coordinator calls a worker tool:
| Action | Effect |
|---|---|
list | Show local and remote workers, their target bot, status, and session |
start | Create a worker with a task, optional title/name/model/thinking level |
continue | Send a follow-up to a worker that is waiting |
steer | Inject guidance into a running worker |
inspect | Read the worker's recent steps and current status |
stop / delete | Stop a run or remove the worker record |
compact | Compact the worker's context |
set_model | Change the worker's provider/model/thinking level |
answer / dismiss | Resolve a question the worker asked |
Implementation split: LocalWorkerPool owns in-process workers with their own session engine and JSONL history; RemoteWorkerGateway proxies workers on paired devices over the Relay; SuperOrchestrator coordinates both, tracks stages, cards, and artifacts, and supports live host handover (mesh-v2). The same worker surface is exposed as worker.* and super.worker.* route methods so a phone can drive workers hosted by a desktop, and vice versa.
Shell modes and isolation boundaries
Shell execution is resolved per call by HostEnvironmentProvider / DynamicHostAccess in core/runtime, using the selected access tier:
| Tier | Execution | Notes |
|---|---|---|
LOCAL | Bundled Alpine Linux through proot in app user space | Default; no root, no real kernel isolation |
ADB | Shell daemon reached over wireless debugging | HMAC-SHA256 challenge-response with a per-restart key; two-way shell, UI automation, virtual display |
ROOT | Native chroot / root shell | Full device privileges; only for users who granted root |
Selection falls back explicitly: ADB unavailable drops to LOCAL; ROOT unavailable drops to ADB (or LOCAL) with a ROOT_UNAVAILABLE marker. The UI and the model are told which tier is actually in effect, and tools that require the system shell are unavailable without it.
Important boundaries:
prootis a convenience, not a security sandbox. It shares the app UID and cannot contain hostile code.ROOTmode is fully trusted local execution.- Plugins run in-process with the app UID;
.ddpsignatures prove integrity and publisher continuity, not isolation. See Security and the repositorySECURITY.md. - On the JVM Host, Linux shell backends are per-platform (
LinuxShellBackend, PTY sessions) and all sessions are scoped to a workspace root. Browser tools are gated by site policy and user take-over state, and never accept a model-supplied approval flag.
Provider and model layer
Models are resolved through ProviderCatalog / ProviderDirectory in core/runtime:
- 42 built-in providers come from the Kotlin SDK's model catalog (API key or OAuth), plus arbitrary OpenAI-compatible endpoints configured by the user.
ModelConfigcarriesproviderId,modelId, andthinkingLevel(off,low,medium,high,xhigh,max). The catalog resolves a requested config to a valid provider/model and falls back safely when a model disappears.- Credentials are read through a
CredentialStorebacked by the platform secret store (Android AES/GCM with an Android Keystore key; Host encrypted vault). OAuth flows are persisted separately from API keys. - The same layer serves memory consolidation and title naming with their own model routing, so auxiliary calls never block the main turn.
- Provider failures surface as retryable errors with backoff; abandoned calls abort cleanly and never leave a run marked as completed.
Writing a tool
- Declare precise JSON Schema, a short
description, and apromptSnippet; the resident tool list is prompt budget. - Return text plus optional structured details for cards; never dump secrets, tokens, or raw credentials into a result.
- Use
onUpdatefor progress and keep the final result concise and bounded. - Respect
signal: check it before expensive work, and letCancellationExceptionpropagate. - Prefer the deferred path for rarely used tools: declare
PluginToolExposure.DEFERREDso the model finds it withtool_searchand runs it withtool_execute. - Do not attempt to bypass approvals or path guards from inside a tool; the guard wraps the tool, not the other way around.
See Plugin Runtime API for plugin-side tools, hooks, and host services.
