Anda Engine Architecture

June 20, 2026 ยท View on GitHub

This document describes the current anda_engine runtime architecture from the source code. It replaces the older deployment-first narrative that treated ICP, TEE, and IC-TEE as mandatory runtime blocks.

In the current engine, those integrations are optional backing capabilities. The practical center of the system is the Engine runtime: it validates callers, creates scoped contexts, dispatches agents and tools, routes model calls, handles tool-call loops, and exposes selected local or remote functions.

Preview note: use markdown-viewer/markdown-viewer-extension to preview this document with the embedded HTML architecture diagram and PlantUML sequence diagram rendered.

Source map:

  • engine.rs: top-level Engine, EngineBuilder, exported APIs, management checks, hooks, challenge signing.
  • context/agent.rs: AgentCtx, local/remote/subagent routing, CompletionRunner, CompletionStream.
  • context/base.rs: BaseCtx, scoped state, cache, store, keys, HTTP, signed RPC, cancellation.
  • context/tool.rs: built-in discovery agents: tools_groups, tools_search, and tools_select.
  • model.rs: Models label router, provider adapters, retry and streaming helpers.
  • subagent.rs: reusable subagents, background sessions, compaction and handoff.
  • memory.rs: conversation/resource storage and KIP/Cognitive Nexus tools.
  • extension: built-in tool libraries such as filesystem, shell, fetch, skills, notes, todos, and memory.

Runtime View

Anda Engine Runtime Architecture
Current source-level view: agents, tools, contexts, models, memory, and optional external capabilities.
Entrypoints
Host apps
CLI, HTTP server, bot runtime, or embedded Rust application call the engine API.
Public API
agent_runtool_callinformationchallenge
Remote peers
Other engines can discover exported functions and call them through signed RPC.
Engine Boundary
EngineOwns runtime state, default agent, export lists, hooks, management policy.
EngineBuilderRegisters tools, agents, models, store, remote engines, subagents, and hooks.
EngineCardPublishes exported agent/tool definitions for remote discovery.
Access Control and Observation
ManagementPrivate, protected, or public visibility; controller and manager principals.
Hookson_agent_start/end and on_tool_start/end can reject, observe, or transform outputs.
CancellationRoot and child cancellation tokens propagate through contexts and runners.
Callable Registries
AgentSetLocal agents, including built-in `tools_groups`, `tools_search`, `tools_select`, and `subagents_manager`.
ToolSet / ToolProviderSetStatic tools and runtime-discovered providers with function definitions, resource tags, and capability groups.
RemoteEnginesRemote function metadata routed with `RA_` and `RT_` prefixes.
AgentCtx and CompletionRunner
AgentCtxCombines BaseCtx with models, tools, agents, subagents, and routing helpers.
CompletionRunnerIterates model turns, executes tool calls, accumulates usage/artifacts, and returns final output.
SubAgent sessions`SA_` workers support blocking calls or background sessions with progress/final hooks.
BaseCtx Capability Surface
Scoped stateCaller, request meta, elapsed time, typed state extensions, and depth-limited children.
Store and cacheContext-path namespaces isolate agent and tool data in object store and cache.
External callsHTTP, signed RPC, key derivation/signing, and canister calls through a configured Web3SDK.
Model Routing and Provider Adapters
ModelsLabel map plus primary model. Labels such as `pro`, `flash`, or `lite` choose provider entries.
AdaptersOpenAI-compatible, Anthropic, Gemini, and custom `CompletionFeaturesDyn` providers.
ReliabilityRequest defaults, SSE/NDJSON parsing, one short retry, and retryable `ModelError` signals.
Optional Extensions and Persistence
Built-in toolsfetch, filesystem, shell, note, skill, todo, and memory tools register like any other tool.
MemoryConversation/resource records in AndaDB; KIP commands backed by Cognitive Nexus.
ObjectStoreIn-memory by default; local, cloud, or IC-COSE-compatible backends can be supplied.
External Capabilities
Model providers
Completion APIs are reached only through registered model adapters.
Web3SDK
Can be a TEE client, a Web3 client, or a not-implemented placeholder.
HTTP resources
Fetch and remote-engine calls use the context HTTP/signed-RPC traits.
Databases
AndaDB and Cognitive Nexus are used when memory tools are registered.
Key point: the engine does not require a blockchain, TEE, or specific storage backend to schedule agents. Those are replaceable integrations behind `Web3SDK`, `Store`, model providers, or memory extensions.

Request Sequence

@startuml
title Anda Engine agent_run and completion loop
skinparam backgroundColor #FFFFFF
skinparam sequenceArrowColor #334155
skinparam sequenceLifeLineBorderColor #CBD5E1
skinparam sequenceParticipantBorderColor #CBD5E1
skinparam sequenceParticipantBackgroundColor #F8FAFC
skinparam sequenceGroupBorderColor #94A3B8
skinparam sequenceGroupBackgroundColor #F8FAFC
skinparam noteBackgroundColor #FFF7ED
skinparam noteBorderColor #FDBA74
actor Caller
participant "Host API\n(server / CLI / app)" as Host
participant "Engine" as Engine
participant "Management\n+ Hooks" as Guard
participant "AgentCtx\n+ BaseCtx" as Ctx
participant "Agent" as Agent
participant "CompletionRunner" as Runner
participant "Models\nlabel router" as Models
participant "Model adapter\nOpenAI / Anthropic / Gemini" as Model
participant "Tool / Agent\nregistries" as Registry
participant "Local Tool\nor Agent" as Local
participant "Remote Engine" as Remote
participant "SubAgent\nsession runner" as SubSession
Caller -> Host : submit AgentInput
Host -> Engine : agent_run(caller, input)
Engine -> Engine : validate RequestMeta\nnormalize default agent
Engine -> Guard : check_visibility(caller)
Guard --> Engine : visibility accepted
Engine -> Ctx : ctx_with(caller, agent, label, meta)
Engine -> Guard : on_agent_start(ctx, agent)
Engine -> Agent : run(ctx, prompt, resources)
Agent -> Ctx : completion(req, resources)
Ctx -> Runner : completion_iter(req, resources)
loop until final output, failure, or cancellation
Runner -> Models : resolve(req.model or ctx.label)
Models --> Runner : Model
Runner -> Model : completion(CompletionRequest)
Model --> Runner : AgentOutput\ncontent, usage, raw_history, tool_calls
alt model returned tool_calls
Runner -> Registry : resolve each tool_call name\nlocal, RA_, RT_, or SA_
par each resolved call
alt local tool
Runner -> Ctx : child_base(tool)
Ctx -> Local : Tool::call(BaseCtx, args, selected resources)
Local --> Runner : ToolOutput
else local agent or subagent without session
Runner -> Ctx : child(agent)
Ctx -> Local : Agent::run(AgentCtx, prompt, resources)
Local --> Runner : AgentOutput as ToolOutput
else remote callable
Runner -> Ctx : remote_tool_call or remote_agent_run
Ctx -> Remote : https_signed_rpc(tool_call / agent_run)
Remote --> Runner : ToolOutput or AgentOutput
else subagent session mode
Runner -> Local : SubAgent::run(session args)
Local -> SubSession : claim session and spawn background runner
Local --> Runner : ack with session id
SubSession -> Guard : on_background_start
SubSession -> Runner : unbound completion loop
SubSession -> Guard : on_background_progress / on_background_end
end
end
Runner -> Runner : accumulate usage, artifacts, tools_usage\nappend tool outputs to next request
else no tool calls
Runner -> Runner : final_output()
end
opt steering or follow-up queued
Runner -> Runner : insert user content at safe boundary\nprune unanswered tool raw history if needed
end
end
Runner --> Agent : AgentOutput
Agent --> Engine : AgentOutput
Engine -> Guard : on_agent_end(ctx, agent, output)
Guard --> Engine : transformed output
Engine -> Engine : clear provider raw_history
Engine --> Host : AgentOutput
Host --> Caller : response
@enduml

Component Notes

  • Engine is the public runtime boundary. It enforces exported agent/tool lists for non-manager callers and always exports the default agent.
  • EngineBuilder starts with in-memory storage, no implemented Web3 client, no external model, and built-in discovery/subagent control agents.
  • AgentCtx is the main scheduling surface. It exposes local tools, dynamic tool providers, local agents, subagents, registered remote engines, and dynamic remote engines from cache.
  • CompletionRunner is iterative. A model turn can return tool calls; the runner executes them and feeds tool outputs into the next model turn. Long-running runners can compact oversized history into a continuation handoff and resume from that summary.
  • tools_groups, tools_search, and tools_select are agents, not side channels. tools_groups returns a compact directory of visible capability bundles; tools_select can expand one group into schemas, and discovered schemas stay in tool-output context while repeated payloads are compacted from conversation context.
  • BaseCtx creates namespace-scoped child contexts. Agent paths use a_<agent>, tool paths use t_<tool>, and all store/cache operations are resolved under that path.
  • Models routes by label first and then falls back to the primary/default model. Provider-specific names stay inside adapter configuration.
  • SubAgentManager turns persisted or temporary SubAgent definitions into callable SA_<name> agents. Long-running subagent sessions use hooks to push progress and final output.
  • Memory is an extension layer. Conversation/resource storage uses AndaDB collections, and persistent knowledge operations are exposed as KIP tools backed by Cognitive Nexus.
  • Web3, TEE, ICP, and IC-COSE integrations are implementation choices behind Web3SDK, HttpFeatures, KeysFeatures, CanisterCaller, or ObjectStore. They are not mandatory architecture layers for the engine itself.