Agent Runtimedoc/{zh,en}/design/runtime/agent-runtime.md

Agent Runtime Overall Design

Status: 2026-11-13. Built: the builtin runtime plugin plugins/agent, a Turn of model Steps with tool calls, permission rules, approvals, askuser, todo, loadskill, context items, co

Status: 2026-11-13. Built: the builtin runtime plugin plugins/agent, a Turn of model Steps with tool calls, permission rules, approvals, ask_user, todo, load_skill, context items, completion checks, limits, streamed progress, and resumption from checkpoints (stages A0–A1 plus the skill, MCP, and context-item parts of A2). Proposed: everything in section 9, each in a v2 form. Linux and Windows have not been run natively.

1. Position and Goals

The Agent Runtime is Orquelo's own agent. It is the builtin plugin plugins/agent (plugin.yaml: name: agent, roles: [runtime], resumable: true, requires: [model]). It implements the runtime role:

go
type Runtime interface {
    Execute(ctx context.Context, in RunInput, host RuntimeHost) (Result, error)
}

One Execute call is one run, which is one turn of the agent. Everything outside the agent's own loop (models, tools, skills, reference material, guards, questions, storage) is reached through RuntimeHost (pkg/plugin/roles.go). Claude Code, Codex, a slash command, or a workflow would be other plugins with the runtime role at the same boundary; none exists yet.

GoalWhat it meansEvidence today
GeneralThe agent names no channel, vendor, site, or domain tool. Core tools come from a tool plugin (plugins/localenv).The same agent serves Feishu, the console, and the HTTP API (plugins/feishu, plugins/console, plugins/httpapi).
ExtensibleModels, tools, skills, reference material, and policies are plugins in the agent instance's uses.M6 zero-change acceptance (record).
DurableA Host restart repeats no committed model response or tool effect.TestAgentApprovalSurvivesRestart, TestLongToolIsPolledAcrossARestart (internal/host/engine), TestResumeSettlesOnlyMissingResults (plugins/agent).
Channel-neutralThe agent returns text and artifacts; Presentation and Delivery plugins format and send them.RuntimeHost has no channel types except Target.
GovernedThe Host fills CallContext; identity never comes from payloads; every call is limited by uses, scope, approvals, and policy.internal/host/engine/caller.go, toolcall.go.
SmallThe Runtime stays small; shared or domain concerns go to shared packages or plugins.plugins/agent is about 765 lines of Go.

Non-goals: the agent is not a workflow engine, a Memory store, a channel formatter, or a vendor SDK. It claims no ranking against other systems.

2. Design Principles

  1. Small fixed loop. The agent owns one loop: build the request, call the model, settle the tool calls, decide. Everything else is a role reached through RuntimeHost.
  2. The checkpoint is the truth. The agent's state (plugins/agent/state.go) is saved with RuntimeHost.Checkpoint after every settled model response and every tool result. A resumed run continues from it.
  3. Three planes stay apart. Instructions (the system prompt), reference material (history, context items, attachments), and tools (the pinned tool list) are built separately and meet only in the ChatRequest. Reference material is marked as information, never as instructions.
  4. A stable prompt prefix. The system prompt is built from the agent configuration, the run's trusted context, the tool and skill lists, and the run's start time, so it is identical for every Step of a run and provider prompt caches stay warm. It is never stored in the checkpoint.
  5. Intent before effect; never replay. Every tool call carries a stable key. The Host records the call before it runs it; a repeated key returns the recorded result, and an interrupted call is reported as "outcome unknown", never re-sent.
  6. Policies only tighten. The agent's deny/ask rules, guards, approvals, and operator policy can each refuse; none can relax another.
  7. People are durable participants. Questions and approvals are Host questions that survive restarts and can be answered from another conversation of the approver.
  8. Output is channel-neutral. The agent emits progress text, a final text, and artifact references. The Host and the connection's Presentation and Delivery plugins do the rest.

3. Plugin, Instance, and Connection

The agent is configured as an instance and wired into a connection:

yaml
plugins:
  - id: feishu
    plugin: feishu
    config: {app_id: "${FEISHU_APP_ID}", app_secret: "${FEISHU_APP_SECRET}"}
  - {id: chat, plugin: chat}
  - id: kimi
    plugin: openai
    config: {base_url: "https://api.kimi.com/coding/v1", api_key: "${KIMI_API_KEY}", model: kimi-for-coding}
  - {id: localenv, plugin: localenv}
  - {id: rail, plugin: rail-12306}
  - id: agent
    plugin: agent
    uses: [kimi, localenv, rail]       # the only instances it may call
    targets: [self]                    # questions and sends may go to the requester's direct chat
    config: {model: kimi, timezone: Asia/Shanghai, ask: ["rail__*"], deny: ["bash"]}
connections:
  - {id: feishu, transport: feishu, trigger: chat, runtime: agent, presentation: feishu, delivery: feishu}

What a run may do is the intersection of the roles each plugin declares, the agent instance's uses, each used instance's scope checked against the run's principal and conversation, the approval rules, the operator policy, and the current instance state. See Plugin design, section 4.

4. One Run End to End

mermaid
sequenceDiagram
    participant T as Transport
    participant H as Host
    participant G as Trigger
    participant A as Agent (plugins/agent)
    participant M as Model plugin
    participant X as Tool plugin
    T->>H: Submit(event)
    H->>G: Match(TriggerInput)
    G-->>H: Decision start
    H->>H: Create the run (queued); start it when the conversation is idle
    H->>A: Execute(RunInput, RuntimeHost)
    A->>H: ContextItems, Skills, Tools (pinned for the run)
    loop Steps
        A->>H: Chat(model, ChatRequest, onDelta)
        H->>M: Chat (uses, scope, limits, image parts)
        M-->>A: settled ChatResponse
        A->>H: Checkpoint
        A->>H: CallTool(name, args, key)
        H->>X: guards, approval, ledger, Invoke
        X-->>A: ToolResult
        A->>H: Checkpoint
    end
    A-->>H: Result{Text, Artifacts}
    H->>H: Finish the run and queue its deliveries in one transaction

The loop repeats until the model gives a final answer that the completion checks accept, or a limit, failure, cancellation, or timeout ends the run. The loop and its commit points are in the execution kernel; the inputs and outputs are in the I/O contract.

5. The Agent Definition

The Agent definition is the agent instance's config, validated against config_schema in plugins/agent/plugin.yaml. It is data: it grants nothing.

FieldDefaultMeaningStatus
modelrequiredThe model instance to call; it must be in uses (x-instance: model)Built
nameOrqueloHow the assistant names itself in the system promptBuilt
instructionsnoneOperator instructions appended to the system promptBuilt
timezoneUTCIANA zone for the current time in the system promptBuilt
max_steps100Model calls per run before the final no-tools callBuilt
max_tool_calls400Tool calls per runBuilt
max_output_tokensmodel defaultChatRequest.MaxTokensBuilt
allow, ask, denynoneTool name patterns (path.Match): deny wins over ask, ask over allow; unlisted tools are allowedBuilt
fallback_modelsnoneModel instances tried in order when the main model failsProposed (P4)
context_window, compact_at, compact_tail_tokens, compact_model, compact_output_tokens128,000, 0.8, 20,000, model, 8,192When and with which model to compact old messages (compaction)Built (P5)
subagentsnoneChild agent definitions for the delegate tool: name, description, instructions, tools (patterns within the parent's tools, used as written and offered directly, without tool search; empty means the parent's tools but stay_silent, goal and merge, the core ones offered directly and the rest found with tool_search), skills (patterns within the parent's skills that the child is told of and may load; default none), model, max_steps (default 20), timeoutBuilt (P8, config-defined)
instructions_fromnoneInstances whose instructions join the system promptProposed (P9)
require_toolsnoneTool names the agent cannot work withoutProposed (P10)

Delegation (plugins/agent/subagent.go): delegate is offered only when subagents is set. The child starts with its own instructions, a subset of the parent's tools and one message: the skills its definition names, the tools tool_search finds for it, the run's facts (with its own worktree's path and branch when it works in one, isolation: worktree), then the task text (context refactor slice 8). It cannot delegate or call ask_user, does not take the run's reminders, and its streamed text does not reach the reply. Its requests use their own prompt cache key (<session>/sub:<call key>), apart from its parent's and its siblings'. Its call keys are prefixed with the delegate call's key, its state is saved inside the parent's checkpoint, so a restart continues it without repeating its tool calls; its answer and artifacts become the delegate result and its usage joins the parent's. Plugin-provided definitions (AgentSource) are not built; they wait for a separate sub-agent design.

A change to the configuration takes effect for new runs after a reload; a started run keeps the generation it started in (internal/host/engine/generation.go).

6. What the Agent Uses from RuntimeHost

MethodWhat the Host doesUsed by plugins/agent
ToolsLists the tools of the instances in uses whose scope applies, minus exclude and policy.deny_tools; pins them per run (internal/host/broker/pin.go, table run_tools)Once per attempt
CallToolLedger lookup by key, pin check, call-chain check, guards, approval (reviewer, then person), invoke, polling of long tools, result guardsEvery non-builtin tool call
ChatChecks uses and scope, fills or replaces image parts, checks token limits, meters usage, logs model.calledEvery Step
AskOpens a durable question per (run, key), delivers it, waits; the run is waiting meanwhileask_user and ask rules
Skills, LoadSkillSkill cards and documents from the skill instances in usesSystem prompt, load_skill, invoked skills
ContextItemsReference items from the context instances in uses; a failing provider is left outOnce at Turn start
CheckCompletionFeedback from completion guards (including stop command hooks)On each final answer, at most twice
ProgressReplaces the run's ephemeral progress text; the Host sends it at most once a secondStreamed text, tool lines, todo list
CheckpointStores the agent's state on the runAfter every commit point
SendDurably sends text and artifacts to another target allowed by the instance's targetsNot used
Embed, PutArtifact, secrets, LinkStart, LinkFinish, ContextSee pkg/plugin/roles.goNot used

7. Subsystems

Model calls. The agent sends the whole message list with the system prompt first to Caller.Chat with the configured model. Streamed text goes to progress through onDelta. Only a settled ChatResponse comes back; a broken stream is an error with no tool calls. Stop reasons are normalized (end_turn, tool_calls, max_output_tokens, content_filter, other). Assistant Reasoning is kept in the checkpoint and sent back; the model plugin decides whether the vendor needs it. Today the values live in pkg/plugin and the vendor logic in plugins/openai; the owner decided they move to a shared package pkg/llm that every module can call (P3). See LLM layer.

Tools and where they run. The model sees the agent's three builtin tools (ask_user, todo, load_skill, the last only when skills exist) and the Host's tools, minus denied ones; a Host tool cannot shadow a builtin name. The six core tools read, write, edit, bash, grep, glob and artifact come from the localenv tool plugin, with powershell instead of bash on Windows and a workspace per conversation by default. Where tools run is which tool instance is in the agent's uses: a cloud environment is another tool plugin offering the same tool names, and two instances offering one name are refused. See Tools.

Skills and MCP. Skill cards appear in the system prompt; load_skill loads a body or a file. Skills the user names with $ (RunInput.Skills, P84) put their instructions before the input. MCP servers are declared in manifest plugins and become tools named <instance>__<tool> (internal/mcp, internal/bundle); the agent sees them as ordinary tools. See Skills.

Context and Memory. History arrives as RunInput.History (the last history_turns succeeded runs of the conversation, as text). Context items from context instances are placed before the input as reference material. A run that nears the window is compacted (P5, compaction). Memory is a plugin, not part of the Runtime: it uses the context role to recall, tools to write on request, an observer to learn from finished runs, and its data directory (P12). See Context and Memory.

Questions and approvals. ask_user calls Ask with kind ask. Its files are workspace paths that go out with the first question, each published through the workspace's artifact tool, so that tool's path rules and size limit apply; a file that cannot be attached refuses the call, and nothing is asked. replace makes the first question take the place of the previous one (Question.replaces). A tool matching an ask rule is approved by the requester before the call (kind approval). A tool whose ToolSpec.Approval is set (by its plugin, a manifest approval list, or the tool instance's approval) is approved inside CallTool: granted reviewer instances decide first, and a person is asked when they escalate. Both paths use the key approve:<call key>, so one tool call asks at most once.

Guards, reviewers, and hooks. Guards in the uses of every instance in the call chain apply: Check may deny a tool call, CheckInput may refuse the run's input before the agent runs, CheckResult may withhold a result or add a note, and CheckCompletion may ask for more work on a final answer. Manifest command hooks (pre_tool, post_tool, user_input, stop) are guards speaking Claude Code's JSON protocol. No guard runs before a continuing Step yet (P7).

Observability. The Host logs run.*, model.called, tool.called, question.*, and delivery.*; the agent logs agent.step, agent.step_limit, agent.completion_retry, agent.output_cutoff, and agent.content_filtered (Logging). Observers receive run.finished only (P11).

8. Extending the Agent

To addThe plugin suppliesHost or agent change
A model vendorA model plugin; the agent's model names its instanceNone
A domain toolA tool plugin, or an MCP server in a manifest plugin, in the agent's usesNone
A cloud workspaceA tool plugin offering the core tool names, replacing localenv in usesNone
A skill packA manifest plugin with skillsNone
Reference material or Memory recallA context pluginNone
A safety policyA guard plugin or a manifest command hookNone
Automatic approvalsA reviewer plugin with grants: [review]None
Telemetry on finished runsAn observer pluginNone
A specialist sub-agentsubagents config (P8)Configuration only

9. Proposed Mechanisms

The proposals live in one register, Agent Runtime proposals: P1–P16 as first listed here, and P17–P47 from the research review of 2026-11-14. Each row gives the v2 form, whether the Host contract changes (and so needs an ADR), and the design document that specifies it. The register also lists the changes that need no proposal and the order of the ADR batches.

Not carried over from the earlier design, because v2 does not need them: a separate session object (one run is one turn; history comes as RunInput.History), an agent-owned journal store and event lanes (the checkpoint and the Host's delivery queue cover them), and per-point plan resolution (roles are the extension points).

10. Go Packages

PartWhereRole
Definition and permission rules, Execute, restoreplugins/agent/agent.goComposition entry: init() registers the manifest with plugin.Register; New decodes the configuration
The Turn loopplugins/agent/loop.goOrchestrator: Step order, stop reasons, limits, commit points
Builtin toolsplugins/agent/builtin.goask_user, todo, load_skill
System promptplugins/agent/prompt.goBuilt per Step from the definition and trusted context
Stateplugins/agent/state.goThe checkpointed state and the initial messages
Progressplugins/agent/progress.goComposes the ephemeral progress text
Texts for peopleplugins/agent/locales/*.jsonzh-CN and en-US message keys

The provider ports are the RuntimeHost methods; the state owner is the run's checkpoint, stored by the Host. New behavior goes into new files of this package, and into a new package only when a second consumer exists, such as pkg/llm (P3). Model-facing text is English.

11. Stages

StageScopeStatus
A0Input in, one model call, message out; system prompt; checkpointBuilt
A1Tool loop, core tools through localenv, permission rules, approvals, ask_user, limits, recoveryBuilt
A2Skills, MCP, context items, completion checksBuilt
A2Compaction (P5), Memory plugin (P12), plugin instructions (P9)Proposed
A3Steering (P6), step guard (P7), delegation (P8), fallback (P4), evaluation events (P11)Proposed

12. Acceptance

  • ◆Built parts: the tests in plugins/agent/agent_test.go and internal/host/engine listed in the execution kernel, section 10, pass on macOS; Linux and Windows still need native runs.
  • ◆Each proposal lands with its own tests, including a restart in the middle of the new behavior, and records whether the Host changed.
  • ◆A fixed task set with recorded success rate, tokens, and cache reads is measured before any comparison with other agents is claimed.