Broker implementation¶
Current reference. System ownership · Domain glossary · Tool policy.
Agent autonomy and trust boundary¶
The immutable profile catalog in RuAgent.Protocol is the single semantic
source for the effective-policy prompt projection and Broker fallback:
| Preset | Canonical behavior |
|---|---|
plan |
Workspace read and Web are automatic; terminal and mutation are denied outright (read-only, no per-change asks); external structured access asks like Standard. |
standard |
Workspace reads, Web, workspace mutations and executable/shell launches from a workspace cwd are automatic; external structured access and external terminal cwd ask. Explicit rules and long foreground approval still apply. |
full_access |
The skip-all mode: external structured files, arbitrary terminal, and structured protected paths (harness key/database files, runtime descriptors and Ru hook and MCP configuration files, user plugins and their consent record, plus user-added RU_PROTECTED_PATHS entries) are automatic; hard-invalid requests remain denied. |
These are preset defaults. Explicit deny and ask rules still take precedence, including for external files covered by a session folder grant or Full Access. Hard invariants, including Plan's read-only gate, remain ahead of ask rules.
Preset selection is session-scoped. Workspace trust is a separate explicit
decision, once per canonical WorkspaceIdentity; the GUI presents a guarded
confirmation and CLI run/chat require --trust-workspace. A moved or
recreated identity must be trusted again. Full Access requires the GUI gate or
CLI --confirm-full-access, and neither implies workspace trust.
On Windows, trust resolution requires a real directory, its native final path,
volume serial and file ID. Query-only handles avoid requiring directory listing
access. An unverifiable native identity fails with workspace_identity_unverified
inside the resolver; a path hash never substitutes for Windows trust identity.
A native model step may contain optional narration and one or more ordered tool calls. If any call asks, the complete non-denied batch is retained durably and resumes by re-evaluation without a new model proposal. Read-only executions may overlap up to eight at a time while mutation/terminal barriers and receipt order remain intact.
ToolArgumentsCodec owns the durable tool-call envelope serialization and
interpretation. Retained input and approval recovery share exact identity and
argument matching; HTTP approval binding keeps its existing client-audience
and legacy compatibility checks. Codec sharing does not move policy decisions
or tool execution out of their existing owners.
Terminal children in standard and full_access run as the current Windows
user and may access files outside the workspace and network resources available
to that user; there
is no OS filesystem or network sandbox (ADR-0015). Standard authorizes the canonical launch directory rather than command syntax
(ADR-0017); Full Access also permits external launch directories. The terminal tool schema rejects obsolete sandbox arguments. Hard
timeout, output cap, cancellation, redaction, and process-tree cleanup remain
active. Structured file tools independently retain canonical/symlink/junction/
hard-link containment, and the protected-path denial holds in plan and
standard (full_access is literally full). API keys remain in credential
storage and diagnostics redact secrets.
The current managed process flow (Phase 2 cutover) is:
RuApp / RuAgent.Cli --start-or-attach via RuAgent.Client--> ASP.NET Core Public Host 127.0.0.1:<ephemeral>
(RuBackend.exe --managed-runtime, one process, no managed child)
|-- direct business, persistence, and durable Harness (Core + SQLite agent_harness.db + encrypted payloads)
|-- in-process typed model step (ModelStepService behind IModelStepRunner, one-step AssistantStep)
| `-- bounded provider adapters (OpenAI-compatible Chat Completions, OpenAI Responses, Anthropic Messages) via exact protocol dispatch
`-- in-process execution authority (BrokerExecutionRuntime behind IToolGatewayFactory)
|-- policy, approvals, and local action adapters (structured files)
`-- current-user terminal/git children, bounded by Job Object and policy
The public Agent path uses the in-process typed model runner. Durable policy/file-tool work is complete, with headless terminal and reconciliation surfaces from Phase 3:
- In-process model runner: one typed
ModelGenerationRequest→ one provider generation →AssistantStep(text, tool_calls, finish_reason). A provider may return optional narration plus one or more ordered native calls; a complete call written out as text to an advertised tool is salvaged into an ordinary call. Provider errors map to bounded stable codes without provider/model fallback. The runner composes one system message with composer2.0.0from seven ordered blocks: persona, execution contract, environment, profile/effective policy, instruction blocks, capabilities, and runtime context. It returns a receipt whose version, block ids/order, and per-instruction digests Core validates before completion or tool dispatch. What that receipt attests is bounded: theinstruction.*digests bind the exact instruction bytes in the context, while the other block digests are checked for shape and the caller does not receive the rendered prompt text. The typed step result carries text, tool calls, finish reason, and the prompt receipt, plus optional boundedusageandreasoning_text. - Capability listings summarize the first sentence; complete descriptions, schemas and argument examples travel in native declarations for Chat Completions, Responses and Anthropic. The environment date is converted to the advertised local timezone. Native runtime references omit only tool outputs already present in retained native history; unmatched references and paging notices remain available. Protocol schemas may carry string-valued
descriptionannotations, included in their canonical digests; Broker treats these as guidance metadata and retains required/type/enum/bounds/additional-property checks and rejection of unsupported validation keywords. An annotation never grants execution authority. - Agent API/SSE:
- 28
/agent/v1/*routes plus durableHarnessEventSSE (id:<sequence>,Last-Event-ID/after_sequencecursors, reconnect replay, transient non-durable deltas) with bearer auth, idempotency 409,workspace_busy409,preset_mismatch409, typed command dispatch (/compact,/help,/skills,/skill,/tasks [kill <execution_id>]) without history insertion, activeGET/POST/DELETE /agent/v1/policies(global requiresX-Interactive-Confirmed: true, versioned JSON, encrypted matcher values) plus the stored session-preset read (GET /agent/v1/sessions/{sessionId}/preset, 404 when the session has no stored selection), workspace concurrency/activity/changes reads and policy update, continuously renewed workspace membership while a run is driven, encrypted external-change journal entries, andPOST /agent/v1/runs/{runId}/approvals/{approvalId}. - The approval route accepts exactly
allow_once,allow_session_directoryfor external folders only,allow_alwayswhich additionally saves the durable matcher the Broker built for that approval as a project rule (Remembered Approval), ordeny. - An allow of a rememberable call also remembers the approved intent for the Agent session in an in-process, expiring ledger that the runtime loop materializes into the session's later policy snapshots — the durable pattern when one was saved, the exact intent otherwise, and external-directory approvals keep the Broker folder grant and write no entry — so a matching call — including later in the same run — evaluates as allowed without another prompt.
- Approvals use first-writer-wins
approval_stale, matcher preview, 30-min expiry, old-snapshot execution ordering, and explicit rules deny before ask before allow. reconcileis active on the Agent v2 headless path (Phase 3).- Different sessions always share a workspace;
- a run waiting on the user (an approval or an
ask_useranswer) retains its session ownership until it is answered, without blocking other sessions; there is no Continue gate (ADR 0048), and startup recovery fails a run an older build parked for Continue with its park code. - Exact consecutive tool calls terminate as
repeated_tool_callbefore another Broker dispatch. - Ordinary assistant prose immediately following any failed or unverified tool receipt is
suppressed from conversation outbox, recorded internally for audit as an
InternalOnlypayload, and answered with a bounded durable[HARNESS RECOVERY]note in the model context so the run can redo, reroute, or report the blocker; - a final report explicitly prefixed
[BLOCKED]is stored as visible assistant history with the marker removed and ends the run as failed, preserving the receipt error code (ormodel_reported_blockerwhen no failed receipt exists), without another recovery note; - terminal outbox delivery does not recreate runtime or transition the run to success.
- Otherwise, after the case budget (3 unverified notes, shared by tool-failure and verification holds) or the
window cap (24 notes within the recovery window (the last 512 durable events, about fifty steps)) is spent, a tool failure fails the run with its error code, and a
verification failure completes the run with state
unverified(completion policy). - An empty or whitespace-only final step is answered the same way up to 3 notes before failing as
empty_model_reply; - a
Lengthfinish suppresses the whole incomplete step before tool dispatch and gets up to 3 consecutive same-model notes requesting smaller output beforemodel_output_truncated; ContentFilterandErrorfinishes fail immediately asmodel_content_filteredandmodel_reply_error;- a model step the runner rejects with a repairable tool-call/selection code
(
model_tool_call_invalid,model_tool_call_unavailable,invalid_selection) is answered the same way up to 4 notes before failing with the original code, while a provider-transient code whose bounded retries were spent (provider_rate_limited,provider_timeout,provider_server_error,provider_transport_error) fails the run with that provider code, and the remaining provider/prompt/history/image codes still fail immediately. - Subsequent different recovery tool calls remain allowed.
- Broker v2:
- immutable
PolicySnapshotandBrokerRunLeasebind the run, session, canonical workspace identity, profile version, preset, and SHA-256 snapshot before capabilities are advertised. PolicySnapshotEvaluatorapplies hard invariants, ordered explicit rules, then the canonicalAgentPolicyProfileCatalog;- repository cleanliness and prompt text are never fallback inputs.
- Standard external structured access uses session-scoped
CanonicalDirectoryIdentitygrants or, when the user clicked "always", a durable project allow rule whose canonical path pattern (<folder>\**) the evaluator honors for external targets (external_directory_rule_allow). An allow rule without a path pattern is a workspace rule and never grants an external target; deny and ask still outrank it and the plan read-only gate still applies. - Full Access selects an ephemeral per-call external root and never creates a reusable folder grant.
- Structured
CanonicalPathResolver/ProtectedPathCatalogand adapter hard-link checks apply to structured file tools; - catalog protection is the preset guard that
planandstandarddeny andfull_accessis literally full about. - Canonical fallback ask reasons are
external_directory_required,terminal_external_cwd_requires_approval,terminal_protected_path_requires_approvalandterminal_timeout_requires_approval; rule_asksidentifies explicit ask rules.- Legacy reason codes remain readable in retained activity;
- timeout above the protocol hard maximum is denied.
- Pending approvals and exact single-use authorization tokens bind to the active lease/snapshot (version and canonical SHA-256, since session approval memory can derive a repeated version) and cannot be replayed.
- Tool Definition ownership:
RuAgent.Protocolderives immutable ID/version/schema/scope/description declarations and run-pinned coding profiles from one explicit row per model-visible tool inAgentToolDescriptorTable(ADR 0038).AgentModelToolContractCatalogprojects that catalog; the Host selects the pinned profile for both prompt capabilities and nativemodel_tools. Broker manifests are derived from the same rows and retain risk/approval/timeout/output policy; each manifest's schema digest must match Protocol.ask_userremains Host-intercepted and has no Broker binding.RuAgentBrokeris the only tool execution authority. Supported tool surfaces are described under Pinned coding tool profiles. - File tools:
readreturns one file's UTF-8 content withoffset/limitand no discriminator, defaults to a 1 MiB source window and accepts up to 4 MiB, fitting serialized output into 4 MiB before Broker normalization;- a
.pdffile returns bounded extracted text (PdfPig parses in process; nothing is rendered): withoutpagesa short document is read whole or its first ten pages, andpagesselects a 1-based range of at most twenty pages (ADR 0050); - Office Open XML and OpenDocument files (
FileOfficeTextExtractor, BCL ZIP/XML only, DTDs prohibited) returnkind: "document"text by part (paragraph, spreadsheet row or slide) withpagesas a part range and the same 60,000-character cap; legacy binary Office and iWork files fail asdocument_unsupported, other binary files asbinary_file_unsupportedand non-UTF-8 text asinvalid_utf8, each with a hint naming what the bytes are and the command that opens them (FileReadFailureHints; the hint travels in the exception's data so codes and types stay stable);outside_workspacesays how to attach the file, andread_fileon an image, PDF or document fails asread_file_text_only(ADR 0053); - clipped Unicode or escaped text carries source-byte continuation metadata;
listenumerates one directory (streaming enumeration, ordinal relative paths, hidden/binary/protected skip with counts, result/byte/time caps, boundedtruncatedmetadata, junction/symlink containment, no unbounded allocation).helpsearches the five bundled offline documentation resources, is workspace-independent and never reads workspace files.grep(regex content search withfile_glob/case_sensitive/is_regexfilters and bounded results) andglob(ordinal path-pattern results with traversal caps) remain standalone tools, alongside hash-guardedwrite_file/edit_fileand recoverablefile_delete/file_restore(preimage hashes are captured internally, never supplied in model proposal JSON; the encrypted recovery copy remains bounded, opaque, one-time, and never in diagnostics).- Model-facing definitions require preservation of user-supplied absolute paths inside a session-granted directory;
- Broker canonicalization and containment remain authoritative.
edit_fileuses exact replacements against the original file;grepuses canonicalis_regex, bounded concurrent reads, cancellation, and ordinal output ordering;- recovery caps are configurable below a 4 MiB hard maximum.
apply_patchexposes a workspace-scoped unified diff through the existing patch adapter, with all-target policy checks, internal preimage hashes and preparation before mutation.- Ru has no Git tool.
gitis an ordinary terminal command under Broker policy; automatic terminal Git reads pincore.fsmonitor=false, disable external diff and textconv, and override repository-local clean/smudge/process filters (an unreadable filter table fails closed withgit_filters_unreadable); Git writes keep the repository's filters. Subagent worktree setup is the only Git the Broker runs itself, throughStreamingGitCli. - See the pinned coding profiles below.
- Model surface: the Protocol tool definitions are projected into the prompt and native
model_tools; the Broker alone decides and executes each request, except Host-interceptedask_userwhich never dispatches. Plan, Standard, and Full Access use the matrix above. Managed Web remains bounded, redirect-validated, sanitized, and untrusted; Plan Web is automatic. Terminal children run as the current Windows user and have no OS filesystem/network confinement. Timeout, output cap, cancellation, and process-tree cleanup remain enforced. Themcptool connects to user-declared stdio or Streamable HTTP servers through the Broker under ADR 0025; workspace files cannot declare servers, and subagents cannot use it. The opt-incomputertool (ADR 0031) captures monitors and sends pointer and keyboard input throughComputerUseServicebehind the same execution authority;plandenies it,standardgrants apps per session, protected apps and Ru's terminal hosts are never targets, and Ctrl+Alt+Backspace (or Ctrl+Alt+Pause) cancels the controlling run. Mail/calendar/task connectors are not advertised Agent tools. - Terminal authority: ADR 0017 replaces
command-form approval with canonical launch-directory permission.
runpreserves literal argv;shellexplicitly selects PowerShell syntax. Both are automatic from a workspace cwd in Standard. External cwd and long foreground calls ask; explicit deny/ask rules precede automatic policy. Network and analyzer metadata are not permission gates. User-installed tools resolve through sanitized absolute PATH directories without an install-directory allowlist. The real executable, argv, cwd, timeout and classified metadata are rebound before consuming each authorization token. Dispatch receives that resolved intent directly and does not repeat PATH or cwd selection after authorization. Existing bare-name policy rules retain their request-label matching; remembered exact approvals use canonical paths. Deny/ask rules also match the original executable alias, so resolution cannot bypass an existing restriction. Unresolvable executables fail before approval. No OS confinement is claimed. The structured protected-path denial holds inplanandstandard, and credential storage/redaction are unchanged. Terminal children retain the trusted parent'sPSModulePathfor PowerShell module discovery; model input cannot supply or override environment entries. Secret variables remain stripped and seeded into output redaction. The redactor withholds only a trailing run that could still become a seed, so the live stream is not batched until the command exits when the environment carries a credential. Glob traversal also checks its elapsed request budget directly, so delayed cancellation timers cannot turn an expired scan into a successful receipt. Tool execution has one entry point,ExecuteAuthenticatedV2Async, reached only afterBrokerExecutionRuntimeconsumes the authorization token; any other envelope is refused astool_execute_v2_requiredbefore an adapter runs. The terminal adapter likewise refuses a launch without Broker authorization, whatever its analyzer class (terminal_command_not_allowed,terminal_shell_approval_invalid). Concurrent provider generation is unbounded unlessRU_MAX_CONCURRENT_MODEL_STEPSsets a cap (for example 1 for a local single-slot runtime). - Managed Web:
web_searchresolves the configured engine against a fixed set of public HTML engines and returns the first usable result after an accent-insensitive query-term and explicitsite:sanity check, rather than substituting a second tool or a second provider. It is the one documented exception to the no-substitution invariant, and every request still passesWebPolicy, so it cannot widen the network boundary or bypass a denial. Managed Web disables environment/system proxies and connects directly to a public address validated by the connection policy. - Structured reads bind content and SHA-256 to one opened, authorized file
handle. Windows final-path and hard-link checks inspect that handle before
reading. Full-file hashing observes caller cancellation and a five-second
deadline (
read_hash_timeout); mutation preimage hashes remain Host/Broker owned and cannot be supplied by the model. Byte-paged and line-paged reads verify the opened handle's final path before reading, so an ancestor junction swap after resolution cannot widen the target. On-demand skill bodies also use handle-based final-path and hard-link checks. Image reads additionally enforce byte signatures and bounded dimensions/size; only a pinned model that accepts image input receives an encrypted image result. - Cancellation binds tool registrations to the current run-lease lifetime. Revocation cancels existing registrations and makes late registrations already canceled; reopening a run creates a separate lifetime. Cancellation callbacks run outside registry locks. Session folder-grant revocation cancels active tools while leaving the run able to request fresh authority.
- Existing-file mutation: canonical ancestor handles are retained; one validated target handle excludes competing writes and rename-over through hash validation and update/delete. Updates retain at most 32 MiB of rollback bytes (
file_too_largeabove the cap), write in place and flush; ordinary write failures attempt restoration, but power-loss crash atomicity is not claimed. Missing-file creation stays staged with no overwrite. Patch rollback restores only still-matching applied output, preserving intervening editor changes. - Client attachments accept images and text/code files only. GUI picker, paste and drop share the same type checks; CLI attachment loading refuses unsupported formats. DOCX/XLSX/PPTX are not extracted or inlined. Document processing uses workspace files through ordinary terminal tools and optional skills with user-provided dependencies; it has no built-in converter or separate execution authority.
- Bundled help path:
help(help@1.0.0) is a model-visiblesystem.readtool backed by five explicitly embedded Markdown resources. It is offline, workspace-independent, approval-free, and bounded; it returns stable document IDs and excerpts only. It never reads workspace files or live process/device state, and its reference text cannot override higher-priority instructions. - Interactive and headless CLI:
RuAgent.Clidelegates start/attach toRuAgent.Clientand all run execution to HTTP/SSE. Its Terminal.Gui TUI owns terminal presentation, command navigation, attachment submission and run-following interaction; it also exposes headless commands and safe event envelopes. Model execution and execution policy remain Harness/Broker owned. Commands includeagent approve/deny, policy management, and run/chat preset selection.runandchatrequire--trust-workspacefor an untrusted canonical identity and--confirm-full-accessforfull_access;--jsonis accepted only with the explicit trust/full-access flags and cannot confirm an approval. The canonical Plan profile does not synthesizeweb_approval_required; an explicit ask rule may still surface that compatibility reason. Presentation, layout and turn-ownership details live in TUI terminal presentation.
The Harness tool pipeline uses one proposal-batch implementation for classification, input/approval pause selection, execution and abort cleanup. Initial proposal persistence remains interleaved with evaluation. Retained approval/input entrypoints validate their distinct identities before common re-evaluation and preparation; approval refresh retains its waiting state and never executes the batch.
The current Agent flow is:
RuApp -> ASP.NET Core public contract -> in-process typed model step -> bounded provider adapters
ASP.NET Core public contract -> IToolGateway -> BrokerExecutionRuntime (tool execution; current-user terminal bounded by policy and Job Object)
The in-process typed model step is the active Agent generation path; the typed worker protocol v2 and the worker executable were retired with it (ADR-0012), and the device v1 protocol was removed with the media surfaces. The shipped OpenCode-style system-prompt composer does not introduce a second conversation transport: text, coding, and tool-selection steps all use the same Agent run and model-step path.
Privacy boundary¶
Only data needed for a requested operation crosses a private boundary. Visible assistant text may enter Agent generation and approved persistence, but private markers and model-control metadata must not enter history, reviewed examples, cleanup manifests, or logs.
Automated checks may record statuses, timings, counts, event types, and cleanup state; they never record credentials, bearer tokens, request bodies, session identifiers, transcripts, or private marker metadata.
Agent Session¶
Definition: Agent Session (glossary).
RuAgentBroker¶
Definition: RuAgentBroker (glossary).
It no longer runs as a child process: the Host composes
BrokerExecutionRuntime behind IToolGatewayFactory (ADR-0014).
In-process, neither the Broker session nor a run lease expires on a clock: both are bounded by the Host process and by explicit release (run teardown closes the lease, session close and Host disposal close the rest). A finite lease lifetime used to deny every tool call of a run that worked for more than an hour.
Execution Authority¶
Definition: Execution Authority (glossary).
BrokerExecutionRuntime is reached through the IToolGateway seam created by
IToolGatewayFactory inside the Host process. The Host keeps orchestration and
the ask_user interception only; no second copy of tool semantics, policy, or
adapters may exist.
Tool Manifest¶
Definition: Tool Manifest (glossary).
The Broker policy declaration of a tool's identity, adapter, risk class, scopes,
execution schemas, timeout, output limit, and trust class. Its ID/version and
proposal schema digest must match the immutable definition in
RuAgent.Protocol; it does not itself make a tool model-visible.
Manifests are derived from AgentToolDescriptorTable rather than hand-written. ToolCatalog builds one manifest per Broker-bound row (27 of the 29 rows; ask_user and advisor have none) and requires executors and manifests to match in both directions. The trusted adapter allowlist in ToolRegistry comes from the AgentToolAdapter enum, with the Host-intercepted member excluded. Risk and adapter values map through explicit arms that throw when unmapped. A session grant adds each advertised tool's manifest scopes. The access class (ReadOnly, Mutation or Terminal) comes from the row through ToolAccessClassification, which the Broker gateway and the hook gateway both call. See ADR 0038.
Computer drag and scroll resolve and authorize the target immediately before each injected move, button-down or wheel event, with a final native root-window check before sending. A drag may cross separately granted apps; an ungranted, protected or replaced target stops further movement. Cancellation or denial releases a held button without moving the pointer toward the denied destination.
Tool Definition¶
Definition: Tool Definition (glossary).
The immutable Protocol-owned declaration of a tool's ID/version, model-facing
description, canonical scope, strict proposal schema, example,
and stable ordering. The Host runtime projection selects the pinned profile's
available definitions for both the prompt and the model-step model_tools.
Tool results carry a bounded notice string when an outcome would otherwise be
empty or self-explanatory, such as a grep scan that completed with zero
matches. A notice never replaces the fields that describe coverage:
scan_incomplete, excluded_by_size, truncated and next_offset stay
authoritative, so a partial scan states its coverage rather than claiming there
were no matches.
Pinned coding tool profiles¶
ADR 0027 introduced run-pinned
profiles. ADR 0029 retires its legacy
compatibility, and ADR 0043 folds the
experiments into one default: only coding_v3 (default) and coding_v2 remain supported.
The profile is pinned alongside the provider selection and removed from request
options before provider transport. Missing pins fail as tool_profile_required;
retired or unknown pins fail as tool_profile_invalid, without provider access
or substitution. Run queries return null for unsupported historical labels.
The catalog has 29 definitions and the Broker 27 bindings (ask_user and advisor are Host-only).
There are no public write, edit or bash bindings. Internal operation tags
still let saved policy-family deny/ask rules constrain the corresponding modern
tools; they cannot dispatch a retired tool. Shared file/terminal adapters remain
behind the same execution authority.
ADR 0028 introduced run_code,
now part of the default coding_v3 profile. run_code is a Broker orchestration barrier over the
existing tool authority. Jint runs pure synchronous computation, yields on each
uncached SDK call or read-only batch and replays saved JSON results in a fresh interpreter. Nested
calls re-enter normal evaluate/execute with the same run lease. Children cannot
invoke programs, and approval-required nested calls stop for a direct proposal.
No execution adapter or execution policy moves into the Host.
HarnessPayloadStore supplies an encrypted insert-once journal without changing
the root run's optimistic version. Prepared intent precedes the dispatch marker;
receipt follows it. Only prepared-only work may resume; a dispatch marker without
a receipt never authorizes replay. Up to eight read-only calls may overlap in
tools.parallel; ordered, indexed receipts and atomic batch reservations retain
the shared 32-call program limit. The existing root/family budget pool
counts nested calls; a program activates that pool even without child agents.
Source/SDK/policy binding changes fail closed. All authoritative nested receipts
feed verification and workstate projection; provider output strips the trace
regardless of size. This adds no OS process/filesystem/network confinement.
The modern surface separates file creation/deletion/restoration and Windows
terminal launch/read/stop operations. edit_file performs exact, non-overlapping
replacements against one original file and commits once. apply_patch checks
every path and hunk before writing, retaining bounded conflict-safe rollback.
Patch approval is one-time; outside-workspace patches are rejected. A rename
(differing ---/+++ paths, or git rename from/rename to lines; a pure
rename carries no hunks and moves the exact bytes) is a delete of its source plus
a create of its target: policy evaluates both paths, the target must not exist,
both steps are journaled for rollback, and the result reports both as files
rows. Case-only renames are refused (patch_rename_case_only), because canonical
paths compare case-insensitively. Git mode and similarity header lines are ignored.
read_file pages whole UTF-8 lines with start_line/line_count and next_line,
a 4 MiB snapshot scan cap and 32 KiB serialized output cap. read retains byte
paging, image input and current PDF page-range extraction. A line too large for the output budget returns
read_line_too_long rather than an advancing cursor that skips unseen text.
Skill guidance¶
The shared Skills module owns bounded YAML metadata discovery, canonical IDs,
local preferences, cache validation and checked on-demand body reads. The Host
uses the same catalog for prompt descriptors, explicit invocation and client
listing. skill returns a resource base and exact body digest; reading references
or executing scripts still requires the normal tools and Broker policy.
Grouped discovery and explicit pinned GitHub installation share the catalog. The
installer stages and verifies managed packages in the Broker; it is a user API,
not a model tool. There is no executable SkillManifest or skill.json workflow runtime.
See skill operations and ADR 0032.
Session Grant¶
Definition: Session Grant (glossary).
Capability Profile¶
Definition: Capability Profile (glossary).
The session-scoped Agent preset (plan, standard, opt-in full_access) mapped
to the immutable AgentPolicyProfileCatalog in RuAgent.Protocol. The catalog,
not prompt text or a client switch, is the canonical source used by both the
effective-policy prompt projector and Broker fallback evaluation. plan is a
read-only preset: workspace reads and Web are automatic, terminal and mutation
are denied outright (no per-change asks), and external structured files ask like
Standard. Profile version 2 defines standard by the canonical launch directory:
workspace reads, Web, structured workspace mutations, and executable/shell launches
from a workspace cwd are automatic. External structured files and terminal launch
directories outside the workspace ask; an approved external folder can be
remembered as a durable project-scope path pattern (or kept as a session-scoped
Broker grant), and remembered ask decisions store a bounded reviewed pattern
(see Approval Token). There is no language, command-form,
argv-path, network-declaration or executable-install-location approval list.
full_access also permits external structured files, arbitrary terminal
launches, and the structured protected paths (harness key/database files,
runtime descriptors and Ru hook and MCP configuration files, user plugins and their consent record, plus user-added
RU_PROTECTED_PATHS entries)
automatically; hard-invalid requests remain denied.
Explicit deny/ask rules, exact single-use authorization, hard-invalid requests
and process lifetime/output bounds remain enforced.
The Standard foreground ask threshold equals the 30-minute hard maximum, so a
foreground launch Standard allows never asks for its duration; background
launches use their bounded lifetime instead. Every running terminal task reserves
a session slot at launch, retained when foreground moves to background. The
Broker's RU_MAX_BACKGROUND_TERMINAL_TASKS setting defaults to 8 (range 1–64);
invalid explicit values fail initialization. A full session refuses new launches
as background_task_limit_reached without cancelling existing tasks.
API keys remain in credential storage
and diagnostics redact secrets. See ADR 0017.
Hard-invalid requests remain denied; structured protected paths stay denied in
plan and standard. Standard is the
default; full_access requires a GUI confirmation or CLI
--confirm-full-access. The model-visible tool list remains the runtime projection of
Protocol definitions, one purpose per tool: read (offset/limit, pages for PDF),
list (max_entries), grep, glob, help (five bundled offline documents),
todo_write, write_file, edit_file, file_delete, file_restore,
powershell, run_process, terminal_read, terminal_stop, skill,
standalone web_search/web_fetch, and Host-intercepted ask_user (it parks
the run on a user question and never reaches the Broker). There is no provider,
model, protocol, tool, or workspace-cleanliness substitution: a failure is a
bounded, named
code, never a retry on a different backend. Bounded self-correction is not
substitution: a [HARNESS RECOVERY] note is durable feedback returned to the
same model, provider, and tool, and spent bounds fall back to the original
fail-closed code; an exhausted transient provider fails the run with the
provider's code. The explicit account-limit code, provider_quota_exhausted, fails
without automatic retries; the operator restores credits or limits and sends a new
message. HTTP 429 without
an explicit quota code remains a transient throttle. The substitution exception is that
web_search races its configured engine against a fixed set of public HTML
engines inside the same tool decision, every request still passing WebPolicy.
Approval Token¶
Definition: Approval Token (glossary).
A short-lived, single-use value bound to the exact request, canonical arguments,
lease, and policy snapshot for an ask decision. Approval proposals are retained
in memory while live and reconstructed from durable events and encrypted
argument payloads after restart; resume re-evaluates the complete batch and
never asks the model to reissue it. A repeated identical deny still terminates
the run, and there is no provider/model/protocol/tool fallback. Bounded
auto-recovery never applies to approval decisions or reconciliation: those
paths keep their exact fail-closed rules and no recovery note can soften them.
A repeated policy_denied tool receipt is not an approval decision: it follows
the Recovery Note bound above, and when that bound is spent the run terminates
with the denial code. An allow decision on a rememberable call remembers the approved intent for
the Agent session — materialized into the session's later policy
snapshots, so a later matching call authorizes without a
new prompt; the memory is in-process and dies with the session or a host
restart, and a session allow still passes every protected-path denial (in
plan and standard) and Broker evaluation. The explicit allow_always decision additionally saves the durable matcher the Broker built for
that approval (Remembered Approval): for a terminal launch, the resolved
executable, at most two leading non-flag argv tokens and the exact launch directory, with flag-first
and shell-mode invocations kept exact; for an outside file target, the target's own folder as a
subtree pattern that survives restarts and later sessions of the workspace. rule_asks and
terminal_protected_path_requires_approval keep only the session matcher, so no durable rule is
saved and the approval degrades to allow_once; allow_once and session directory grants create no
durable rule.
Remembered Approval¶
Definition: Remembered Approval (glossary).
The Broker decides what an approval may remember. When approval.respond consumes a pending approval,
the same call returns the authorization token and an ApprovalRememberPlan, built by
ApprovalRememberPolicy from that approval's own PolicyContext and ask reason. The plan has a session
matcher, remembered for the Agent session on any allow, and a durable matcher, saved as a project allow
rule only for allow_always. A null matcher means that scope remembers nothing. The Host copies the
matchers it receives and derives none (Host approval flow).
- Allowlist by advertised tool id. File targets (
read,list,grep,glob,read_file,write_file,edit_file,file_delete) bind the canonical path, or the workspace-relative path inside the workspace. Terminal launches (run_process,powershell) bind the resolved executable, argv and canonical cwd.mcplist_toolsandcallbind the server (mcp:<server>) and its argv (list_tools, orcallwith the tool name).computerrequest_accessandfocusbind the exact app list or app. Every other id is not rememberable, includingapply_patch,file_restore,run_code,terminal_read,terminal_stop, the subagent tools,web_search,web_fetch,skill,help,todo_writeand unknown ids. - A matcher that cannot bind its identity is not made. That covers an empty argv (an argument-less terminal launch), a missing identity field such as the workspace root, which has no relative path, a wildcard in a path or cwd, and any value beyond the Host matcher limits.
- Terminal argv: the durable matcher keeps at most two leading non-flag tokens, so
git statuscoversgit status -s. A flag-first argv, a shell-mode invocation or apowershellscript stays exact in both scopes. The session matcher always keeps the full argv. The executable is the resolved full path, not the name the model typed. - Asks:
rule_asksandterminal_protected_path_requires_approvalkeep only the session matcher. - Outside folders: no session matcher, because the Broker's session directory grant already covers the
later calls. The durable matcher is the subtree pattern of the approved path's own folder (the
path itself when it is a folder, otherwise its parent, only when that folder exists), for file
targets only; it never climbs to a further ancestor. A missing folder or a drive, volume or share root yields no pattern, and such an
approval is downgraded to
allow_once, which registers no folder grant. Every allow of an outside-folder approval is bridged asallow_session_directory, so a one-time allow still registers the session folder grant. - Evaluator guard:
PolicyRuleMatcher.Matchesignores an allow rule formcplist_toolsorcall,computerrequest_accessorfocusunless the rule names both a resolved executable and a non-empty argv. Deny and ask rules keep wildcard semantics. Rules carry no provenance, so an identity-less allow written by a user for these tools is ignored too. - Probe:
ApprovalProbeAsyncreads a pending approval without consuming it or issuing a token.Knownis true only while the Broker holds the approval pending for the run and before its expiry.Rememberableis the tool-class check. It does not predict whether a particular target yields a matcher, so a root folder can be rememberable and still degrade. - Open limits: a durable external-folder rule is path-only and does not bind the approved operation. A
session matcher for a non-shell, non-flag-first terminal launch is
compared as a prefix, so a later call that appends arguments also matches it. Argv glob matching
compares case-insensitively and treats
\and/alike.
Session Approval Memory¶
Definition: Session Approval Memory (glossary).
The Host-side, in-process ledger that remembers the approved intent of
every allow decision on a rememberable call for the lifetime of one Agent Session — the bounded
pattern when allow_always saved one, the exact canonical intent otherwise.
The runtime loop
materializes its entries as run-scope allow rules on top of each run's durable
PolicySnapshot, so a later matching call evaluates as allowed
without a new prompt; protected-path denials and Broker evaluation still decide
every call. It creates no durable rule, never outlives its session or a host
restart, is bounded by a 24-hour entry lifetime (the approval lifetime) and a per-session cap, and is
cleared when the session is deleted. External-directory approvals keep the
Broker session directory grant (plus the durable project rule when
allow_always saved one) and write no entry. The fields the exact intent binds depend on the tool
class (Remembered Approval).
Shell policy contexts and Host approval bindings carry the same selected runtime
and literal invocation prefix/script. Executable resolution stays in execution.
Nonempty shell argv allow matchers compare the whole invocation literally and
with case sensitivity; script wildcards cannot widen permission. Deny/ask rules
retain pattern matching.
Policy Snapshot¶
Definition: Policy Snapshot (glossary).
The immutable, versioned, SHA-256-canonical binding of preset, trusted
workspace identity, and ordered PolicyRule/PolicyMatcher list that Broker v2
validates before advertising capabilities; creation time stays metadata on the
wire and is deliberately excluded from the hash, so a snapshot re-loaded after a
restart still matches its durable hash. A new
snapshot N+1 invalidates other pending N decisions after the
authorizing call completes.
Policy Rule¶
Definition: Policy Rule (glossary).
The Global|Project|Run|Once scoped record with stable ID, decision
Allow|Ask|Deny, matcher (tool ID/version, canonical path pattern,
resolved executable, argv/cwd/operation/network intent), creation order,
and optional expiry; matcher values with paths/argv/cwd are encrypted at
rest and only the active decrypted snapshot contains them.
Workspace Trust¶
Definition: Workspace Trust (glossary).
An explicit decision, with source explicit, binding one canonical root to its
Windows volume serial, root-file identity, and display hash
(WorkspaceIdentity ws_* + DisplayIdentityHash). Trust is requested once per canonical identity and validated by final-path resolution. The GUI requires an explicit confirmation; CLI run and
chat require --trust-workspace. A moved or recreated identity is untrusted
again, and the GUI presents that re-approval as a one-click "trust again" prompt
naming the identity change; --trust-workspace re-approves the same way for
automation.
Workspace Terminal¶
Definition: Workspace Terminal (glossary).
While a foreground command is attached, the in-process gateway publishes bounded, redacted stdout and stderr chunks in sequence. The Broker retains the spool independently for background tasks and later output reads.
The terminal adapter runs under execution-authority policy with bounded output,
hard timeout, cancellation, redaction, and process-tree cleanup. plan denies
terminal authority. standard automatically permits executable and shell
launches from a workspace cwd; external cwd and explicit ask rules prompt.
full_access also permits external cwd automatically. Both launch child processes as the current Windows user, without OS
filesystem or network confinement, including outside the workspace. The terminal tool schema has no sandbox selector
and rejects obsolete sandbox arguments. Structured protected-path denial does
not confine terminal commands, and clean/dirty repository state does not change
a decision. An ambiguous mutation outcome reaches the model as a failed result
with sideEffectsPossible, which it inspects before acting again. API keys remain in credential storage and are redacted from
diagnostics.
Shell launches run powershell.exe -NoProfile -NonInteractive -Command <script>.
CommandIntentResolver prepends one statement to the script that sets
[Console]::OutputEncoding to UTF-8 without BOM (inside try/catch). Windows
PowerShell otherwise writes redirected output in the system code page while the
runner decodes UTF-8, so accented text such as Vietnamese reached the model as ? or
U+FFFD. The prelude is part of the executed intent's argv and hash. Policy context,
approval bindings, previews and remembered rules keep the model's own script exactly as
before; the prelude is a fixed Host transform of it. Scripts whose first statement, after any leading comments, is using or param, or that begin with #Requires, are left
unchanged because those statements must come first. Programs launched with
run_process keep their own output encoding.
Declared terminal checks (purpose=verification and purpose=expected_failure) are advisory evidence
that never grants or denies execution (ADR 0039). The Broker
emits no verification repair families or repair hints and does not emit verification_repair_identity
or verification_invocation_invalid. The retired supersedes argument is no longer in the
launch schemas, so a call that still sends it fails schema validation before any process starts.
Receipts that still carry removed fields parse, and the fields are ignored.