posoco

    LLM Agent framework with hexagonal (ports-and-adapters) architecture. Defines 9 traits + Agent loop. Depends on moonbitlang/async.

    llm
    agent
    framework
    ports-and-adapters
    ai-runtime
    Download zip
    Author
    Version
    0.4.4
    License
    Apache-2.0
    Last updated
    4 months ago
    Downloads
    7K

    #colmugx/posoco

    Posoco 是一个使用 ports-and-adapters 架构的 MoonBit LLM Agent 框架。核心依赖 moonbitlang/async,由 9 个开放 trait、共享领域类型和一个 Agent::run_turn 编排循环组成;模型、工具、session、observer 等运行时能力由调用方注入。

    #当前公开结构

    Port职责
    ModelPort普通或流式模型调用
    ToolProvider工具发现与执行
    SessionStoresession 加载与保存
    Observer只读 turn event 观察
    Compressor每轮模型调用前返回压缩指令
    PipelineHook修改、延迟或中止 pipeline stage
    MemoryPort长期记忆存储与检索
    Lifecycleasync 资源清理
    CommandPort用户侧命令枚举与调用

    Agent 持有 &Trait 引用,没有泛型参数。公开签名的生成事实源是 src/pkg.generated.mbti,源文件布局与开发规则见 AGENTS.md。

    #最小组合

    下面的构造方式由 src/quickstart_fixture_test.mbt 作为黑盒测试编译验证:

    let agent = @posoco.Agent::new(
    model,
    tools=[],
    hooks=[],
    memory=[],
    compressors=[@posoco.NoopCompressor::{ }],
    observers=[],
    sessions=[store],
    lifecycle=None,
    config={
    max_tool_rounds: 10,
    temperature: None,
    max_output_tokens: None,
    tool_choice: None,
    reasoning_effort: None,
    model_context_window: None,
    },
    )
    let result = agent.run_turn(input, "session_1")

    完整可运行的 port 实现和验证命令见 docs/01-quickstart.md。外部 workspace 的本地 core 解析仍由 M0-T02 门禁跟踪;该问题完成前,文档不会把可能退回 registry 旧版本的 配置写成已验证安装方式。

    #关键运行语义

    • Agent::new 在两个 provider 声明同名工具时立即 raise CompositionError::ToolCollision;不存在 last-wins 路由或事后查询 warning。
    • ToolCallResult 的错误状态只从对应 ToolResult.is_error 派生。
    • provider raise 的 RuntimeError 会转换成同一个 error ToolResult,作为工具级 非致命 outcome 返回给模型;模型、session、hook 中止和工具循环超限会终止 turn。
    • 加载出的未知 session metadata 会原样保留;NewThread 的 parent_session_id lineage 由框架拥有并保存。
    • 已发布 TurnStarted 的 turn 恰好发布一个 terminal event:成功为 TurnCompleted,失败为 TurnFailed。After/Error hook 的 secondary failure 通过 Custom(source="posoco.core", label="secondary_failure", ...) 可观察, 且不覆盖 primary outcome。
    • malformed 或不完整的 streamed tool call 会 raise ModelError::ResponseParse,不会退回空参数继续执行。
    • Agent::shutdown 不吞 lifecycle failure;清理失败直接向调用方暴露。

    #分层

    Layer 3 — Agent / composition Agent::new + Agent::run_turn Layer 2 — Runtime adapters 调用方提供 ModelPort、ToolProvider、SessionStore 等具体实现 Layer 1 — Effect interfaces and shared types 9 个 pub(open) trait + Message / ToolCall / Session / TurnEvent 等

    压缩器在每一轮模型调用前执行,而不是每个 turn 只执行一次。Observer 返回 Unit、不控制流程;PipelineHook 返回 typed Result,可以改变控制流。

    #验证

    主门禁是 native target,所有 check/test 命令都输出 JSON:

    rtk moon check --target native --output-json rtk moon test --target native --output-json rtk moon fmt rtk moon info

    测试数量、其他 target 的实际能力和 extension 分类见 docs/TESTING.md 与 docs/support-matrix.md。不要把 default/wasm 只执行的 同步测试描述成完整 async 测试集。

    #扩展与设计文档

    #License

    Apache-2.0

    CommandPort

    pub(open) trait CommandPort {
    fn commands(Self) -> Array[CommandDef]
    async fn invoke(Self, id : String, args : Json) -> CommandOutcome raise CommandError
    }

    User-initiated, enumerable, side-effecting commands. Distinct from ToolProvider (LLM-initiated, results re-enter session). Both panel TUIs and slash command lines consume this without knowing command semantics. pub(open) so any ext can declare commands.

    Compressor

    pub(open) trait Compressor {
    fn compress(Self, messages : Array[Message], ctx : CompressContext) -> CompressAction
    }

    Compressor: pure function that decides how to shrink the message context. Returns instructions (None/Replace/NewThread) — never saves sessions or emits events directly; the Agent and Observer handle side effects.

    Lifecycle

    pub(open) trait Lifecycle {
    async fn on_shutdown(Self) -> Unit
    }

    Lifecycle: resource cleanup hook. Called once on agent shutdown to release connections, flush buffers, etc. async to allow IO during cleanup.

    MemoryPort

    pub(open) trait MemoryPort {
    fn store(Self, entry : MemoryEntry) -> String raise MemoryError
    fn search(Self, query : MemoryQuery) -> Array[MemoryEntry] raise MemoryError
    fn delete(Self, id : String) -> Unit raise MemoryError
    }

    MemoryPort: durable cross-session memory store/search/delete. Distinct from SessionStore (conversation history) — memory holds durable decisions/knowledge (e.g. brain.md integration).

    ModelPort

    pub(open) trait ModelPort {
    async fn chat(Self, messages : Array[Message], tools : Array[ToolDef], options : ChatOptions) -> ModelResponse raise ModelError
    async fn chat_streaming(Self, messages : Array[Message], tools : Array[ToolDef], options : ChatOptions, on_chunk : (StreamChunk) -> Unit) -> ModelResponse raise ModelError = _
    }

    ModelPort: the LLM calling interface. Every ext-deepseek / ext-openai / ext-anthropic implements this. chat is the primary call; chat_streaming has a default that ignores on_chunk and falls back to chat().

    Observer

    pub(open) trait Observer {
    fn on_event(Self, event : TurnEvent) -> Unit
    }

    Observer: read-only event listener. Never blocks or mutates — use PipelineHook for interception/abortion. Receives TurnEvent for every significant turn lifecycle event.

    PipelineHook

    pub(open) trait PipelineHook {
    async fn on_stage(Self, stage : Stage) -> Result[Stage, HookError]
    }

    Pipeline hook: observe or mutate stages before/after each phase. Before* stages may rewrite or abort; After*/*Error stages run under finally semantics (always invoked) in reverse hook order.

    SessionStore

    pub(open) trait SessionStore {
    async fn load(Self, id : String) -> Result[Session, SessionError]
    async fn save(Self, id : String, session : Session) -> Result[Unit, SessionError]
    }

    SessionStore: persist and load conversation sessions by id.

    Methods are async so that backing stores can use async I/O (e.g. node:fs/promises-style APIs on the JS target, @async/fs on native). Implementations that only touch in-memory state simply return synchronously inside the async body — no await keyword is required (MoonBit auto-awaits async trait methods when called from an async context).

    ToolProvider

    pub(open) trait ToolProvider {
    fn list_tools(Self) -> Array[ToolDef]
    async fn execute(Self, name : String, call : ToolCall) -> ToolResult raise RuntimeError
    }

    Unified tool interface: declare tools via list_tools(), execute via execute().

    AgentError

    pub(all) suberror AgentError {
    Model(String)
    Session(SessionError)
    Runtime(RuntimeError)
    ToolLoopExceeded
    HookAborted(String)
    } derive(
    Debug
    )

    impl Show for AgentError

    CatalogCompositionError

    pub(all) suberror CatalogCompositionError {
    InvalidToolName(detail~ : String)
    NameCollision(visible_name~ : String, first_provenance~ : String, conflicting_provenance~ : String)
    DuplicateProvenance(visible_name~ : String, provenance~ : String)
    UnsupportedSchemaKeyword(visible_name~ : String, keyword~ : String)
    MalformedSchema(visible_name~ : String, detail~ : String)
    InvalidExecutionPolicy(visible_name~ : String, detail~ : String)
    Empty
    }

    Why catalog composition failed. Each variant is a composition hard failure: the catalog was not built, no Run was started, no model/tool effect was declared.

    CommandError

    pub(all) suberror CommandError {
    NotFound(String)
    InvalidArgs(reason~ : String)
    ExecutionFailed(String)
    } derive(
    Debug
    )

    Errors raised by CommandPort.invoke: unknown command id, invalid args, or execution failure.

    CompositionError

    pub(all) suberror CompositionError {
    ToolCollision(String, String)
    EmptyPort(String)
    } derive(
    Debug
    )

    Composition errors raised during Agent::new (tool collisions, empty required ports).

    KernelError

    pub(all) suberror KernelError {
    ConstructorInvariant(category~ : InvariantCategory)
    ReducerInvariant(run_id~ : RunId, phase~ : String, category~ : InvariantCategory)
    IllegalTransition(run_id~ : RunId, phase~ : String, input_kind~ : String, detail~ : String)
    }

    Unified error type raised by Kernel constructors (RunState::*) and the reducer. The compatibility facade translates this to the legacy AgentError family.

    Variant ReducerInvariant is the only one that terminates a Run; the other variants are raised synchronously from constructors before the Run starts.
    impl Show for KernelError

    KernelFacadeError

    pub(all) suberror KernelFacadeError {
    SessionLoad(detail~ : String)
    SessionSave(detail~ : String)
    CatalogComposition(failure~ : CatalogCompositionError)
    ConversionFailed(detail~ : String)
    UntranslatedInvariant(category~ : InvariantCategory)
    DriverLoopExceeded(iterations~ : Int)
    KernelFailed(reason~ : FailureReason)
    KernelCancelled(reason~ : CancelReason)
    }

    MemoryError

    pub(all) suberror MemoryError {
    Store(String)
    Search(String)
    Delete(String)
    } derive(
    Debug
    )

    impl Show for MemoryError

    ModelError

    pub(all) suberror ModelError {
    RequestBuild(String)
    Transport(String)
    ResponseParse(String)
    } derive(
    Debug
    )

    impl Show for ModelError

    RuntimeError

    pub(all) suberror RuntimeError {
    UnknownTool(String)
    InvocationFailed(String)
    Transport(String)
    } derive(
    Debug
    )

    SchedulingError

    pub(all) suberror SchedulingError {
    DuplicateCallId(call_id~ : CallId)
    UnknownToolReachedScheduler(call_id~ : CallId, name~ : ToolName)
    StaleSnapshotVersion(expected~ : CatalogVersion, actual~ : CatalogVersion)
    }

    Why scheduling failed. Each variant is a kernel-invariant failure — the scheduler MUST NOT silently downgrade these to ordinary tool errors (ADR §2.4, §2.8).

    SessionError

    pub(all) suberror SessionError {
    Load(String)
    Save(String)
    } derive(
    Debug
    )

    Agent

    pub(all) struct Agent {
    model_port : &ModelPort
    tool_routing : ToolRouting
    pipeline_hook : &PipelineHook?
    compressors : Array[&Compressor]
    observers : Array[&Observer]
    memories : Array[&MemoryPort]
    sessions : Array[&SessionStore]
    lifecycle : &Lifecycle?
    config : AgentConfig
    }

    Agent — array-based composition: tools routed by name, hooks chained, observers fan-out, compressors first-wins, sessions write-all/read-first.

    Agent::new

    fn Agent::new(model_port : &ModelPort, tools~ : Array[&ToolProvider], hooks~ : Array[&PipelineHook], memory~ : Array[&MemoryPort], compressors~ : Array[&Compressor], observers~ : Array[&Observer], sessions~ : Array[&SessionStore], lifecycle~ : &Lifecycle?, config~ : AgentConfig) -> Agent raise CompositionError

    Construct an Agent with array-based composition.

    • tools: routed by tool name; a name collision RAISES CompositionError::ToolCollision (fail-fast, not last-wins)
    • hooks: chained in order (first runs first)
    • memory: fan-out store/search
    • compressors: first non-None wins
    • observers: all receive every event
    • sessions: write-all, read-first

    Agent::run_turn

    async fn Agent::run_turn(self : Agent, input : Message, session_id : String) -> TurnResult raise AgentError

    Run one full agent turn. Tool calls execute in parallel via @async.all.

    Agent::run_turn_via_kernel

    async fn Agent::run_turn_via_kernel(self : Agent, input : Message, session_id : String) -> TurnResult raise KernelFacadeError

    Drive a single turn through the M1 Functional Kernel. Returns a legacy TurnResult for compatibility with M0 callers.

    Known limitations vs M0 run_turn:
    • No PipelineHook / Compressor / streaming chunk support.
    • No MemoryPort / Lifecycle / CommandPort integration.
    • Tool execution is sequential via the scripted driver (not parallel).
    • Observer events are kernel-shaped (RunStarted/RunCompleted), not the full M0 TurnEvent set (see ADR §7 Q6.5 for the legacy-event question).

    Agent::shutdown

    async fn Agent::shutdown(self : Agent) -> Unit

    AgentConfig

    pub(all) struct AgentConfig {
    max_tool_rounds : Int
    temperature : Double?
    max_output_tokens : Int?
    tool_choice : ToolChoice?
    reasoning_effort : ReasoningEffort?
    model_context_window : Int?
    }

    AgentConfig::to_chat_options

    fn AgentConfig::to_chat_options(self : AgentConfig) -> ChatOptions

    AssistantCompletion

    pub(all) struct AssistantCompletion {
    message : AssistantMessagePayload
    usage : CanonicalUsage?
    } derive(Eq,
    Debug
    )

    A completed assistant step. The message field is the canonical assistant message that the reducer appends to the transcript; tool calls and reasoning live there (single source of truth, ADR §2.11). The usage field reports token consumption observed for this step, which the reducer may aggregate into the Run budget.

    Construction note: do NOT build this by hand in production code. The from_assistant_message constructor enforces the invariant that the message payload is consistent (assistant role, no ToolMessage shape, etc.).

    AssistantCompletion::finish_reason

    Returns the finish reason. Length is preserved as a distinct variant so the reducer can refuse to emit ExecuteTool effects for a truncated completion (ADR §2.7, M0 StreamAccumulator::to_response behaviour).

    AssistantCompletion::has_tool_calls

    fn AssistantCompletion::has_tool_calls(self : AssistantCompletion) -> Bool

    Convenience: does this completion request any tool calls?

    AssistantCompletion::new

    fn AssistantCompletion::new(content~ : Array[CanonicalContent], tool_calls~ : Array[CanonicalToolCall], reasoning~ : Reasoning?, finish_reason~ : AssistantFinishReason, usage~ : CanonicalUsage?) -> AssistantCompletion

    Build an AssistantCompletion from its parts. The reducer constructs this from a ModelCompleted input after parsing the model adapter's wire representation.

    AssistantCompletion::tool_calls

    Returns the tool calls in source order (already a copy of the internal array).

    AssistantFinishReason

    pub(all) enum AssistantFinishReason {
    Stop
    Length
    ToolCalls
    Other(String)
    } derive(Eq,
    Debug
    )

    Why the assistant finished a step. This is the canonical mirror of the M0 FinishReason, but it is owned by the assistant message (per ADR §2.11: single source of truth) rather than living on a separate ModelResponse field.

    Length is preserved as a distinct variant because the reducer must NOT emit ExecuteTool effects after a length-truncated completion, even if the provider tried to stream partial tool calls.

    AssistantMessagePayload

    pub(all) struct AssistantMessagePayload {
    content : Array[CanonicalContent]
    tool_calls : Array[CanonicalToolCall]
    reasoning : Reasoning?
    finish_reason : AssistantFinishReason
    } derive(Eq,
    Debug
    )

    Re-flattened assistant payload used inside AssistantCompletion. We cannot reuse CanonicalMessage::AssistantMessage directly because that variant already carries finish_reason; the completion's message field is the transcript entry, while the usage lives at the completion level. This struct mirrors only the fields that travel together as the assistant's contribution to a single step.

    Budget

    pub(all) struct Budget {
    max_model_steps : Int?
    max_tool_rounds : Int?
    max_tool_calls : Int?
    max_total_tokens : Int?
    } derive(Eq,
    Debug
    )

    Budget dimensions tracked per Run (ADR §2.9). Each dimension is Int?: None means "unbounded" (the host did not configure that limit). The reducer increments the consumed counters as it declares effects.

    Token accounting is a special case: total_tokens_observed only increases when the model reports usage via CanonicalUsage. Unknown usage is never reported as 0; the reducer refuses to terminate on a token budget whose consumed amount is unknown.

    Budget::bounded

    fn Budget::bounded(max_model_steps~ : Int, max_tool_rounds~ : Int, max_tool_calls~ : Int, max_total_tokens~ : Int) -> Budget

    Build a fully-bounded budget.

    Budget::default_run

    fn Budget::default_run() -> Budget

    Default budget: only max_tool_rounds is bounded (to a conservative 32 by default — the legacy AgentConfig.max_tool_rounds was caller-supplied but every existing caller set it). All other dimensions unbounded. Override via Budget::bounded.

    Budget::from_legacy_rounds

    fn Budget::from_legacy_rounds(max_tool_rounds : Int) -> Budget

    Build a budget that mirrors the legacy AgentConfig. The legacy config had no token / step / call limits, so those dimensions stay unbounded.

    BudgetConsumed

    pub(all) struct BudgetConsumed {
    model_steps : Int
    tool_rounds : Int
    tool_calls : Int
    observed_total_tokens : Int
    any_usage_verified : Bool
    } derive(Eq,
    Debug
    )

    Per-Run consumed counters. The reducer increments these as it declares effects. Each counter is Int (never optional) because "nothing consumed yet" is just 0.

    BudgetConsumed::exceeded

    fn BudgetConsumed::exceeded(self : BudgetConsumed, limit : Budget) -> BudgetState

    Returns the dimension that is now exceeded (if any) after this consumption. Returns None if every dimension still has headroom. If a token budget exists but no usage has ever been verified, the token dimension is reported as BudgetState::UnknownUsage and the reducer must NOT terminate on it.

    BudgetConsumed::zero

    BudgetDimension

    pub(all) enum BudgetDimension {
    ModelSteps
    ToolRounds
    ToolCalls
    TotalTokens
    } derive(Eq,
    Debug
    )

    BudgetExhaustedPayload

    pub(all) struct BudgetExhaustedPayload {
    dimension : BudgetDimension
    consumed : Int
    limit : Int
    } derive(Eq,
    Debug
    )

    External observation that a budget dimension was crossed. M1 fakes use this for token tracking; rounds/steps/calls are tracked internally by the reducer.

    BudgetState

    pub enum BudgetState {
    WithinBudget
    Exceeded(BudgetDimension)
    UnknownUsage(BudgetDimension)
    } derive(Eq,
    Debug
    )

    impl Show for BudgetState

    CallId

    pub(all) struct CallId {
    value : String
    } derive(Eq, Hash,
    Debug
    )

    Stable identifier for a single tool call requested by the assistant. The reducer and scheduler only ever compare/store this string; it is opaque to the Kernel and is produced by the model adapter or by the host.

    CallId::new

    fn CallId::new(value : String) -> Result[CallId, String]

    Construct a CallId. Empty strings are rejected — an empty id would make correlation ambiguous. The Kernel invariant treats a missing/empty call id in a streamed completion as ModelParseFailure, not as a usable call.

    CallId::to_string

    fn CallId::to_string(self : CallId) -> String

    CallId::unchecked

    fn CallId::unchecked(value : String) -> CallId

    Internal constructor used by Kernel tests and by the facade adapter when the caller has already validated the string. Production callers should prefer CallId::new and handle the typed rejection.

    CallModelPayload

    pub(all) struct CallModelPayload {
    model_step_id : ModelStepId
    messages : Array[CanonicalMessage]
    catalog_version : CatalogVersion
    call_options : Json
    } derive(Eq,
    Debug
    )

    Payload for Effect::CallModel. The executor uses catalog_version to re-derive the same definitions the model was prompted against; a stale version returned by the executor would be a kernel invariant failure detected at completion correlation.

    CancelDisposition

    pub(all) enum CancelDisposition {
    Propagated
    NotPropagated
    Unknown
    } derive(Eq,
    Debug
    )

    What the scripted executor recorded about a CancelOutstanding effect. Real adapter propagation is M3; in M1 the executor always reports Propagated against the in-memory scripted fakes and NotPropagated only when the bound adapter declares it cannot cancel (used by adapter-hardening tests). The reducer never blocks on this — termination is decided by inputs.

    CancelOutstandingPayload

    pub(all) struct CancelOutstandingPayload {
    effect_ids : Array[EffectId]
    reason : CancelReason
    } derive(Eq,
    Debug
    )

    Payload for Effect::CancelOutstanding. Lists the effect ids the reducer wants the executor to stop; the executor records a CancelDisposition per id (M1 fakes report Propagated; real adapters in M3 may report NotPropagated).

    CancelReason

    pub(all) enum CancelReason {
    HostRequested(detail~ : String?)
    DeadlineReached
    } derive(Eq,
    Debug
    )

    Why a Run was cancelled. Carried by the terminal Cancelled outcome.

    CancelRequestedPayload

    pub(all) struct CancelRequestedPayload {
    detail : String?
    } derive(Eq,
    Debug
    )

    Host or adapter requested cancellation. The reducer applies ADR §2.5 race rules: if the cancel arrives strictly before a queued completion, the cancel wins; otherwise the completion wins and the cancel becomes a post-terminal rejection.

    CanonicalContent

    pub(all) enum CanonicalContent {
    Text(String)
    Image(media_type~ : String, data~ : String)
    } derive(Eq,
    Debug
    )

    Canonical content block. Text is the common case; Image carries a stable media-type identifier plus opaque payload data (base64, URL, or an adapter-managed handle — the Kernel does not interpret it).

    CanonicalMessage

    pub(all) enum CanonicalMessage {
    SystemMessage(content~ : Array[CanonicalContent])
    UserMessage(content~ : Array[CanonicalContent])
    AssistantMessage(content~ : Array[CanonicalContent], tool_calls~ : Array[CanonicalToolCall], reasoning~ : Reasoning?, finish_reason~ : AssistantFinishReason)
    ToolMessage(call_id~ : CallId, tool_name~ : ToolName, outcome~ : ToolOutcome)
    } derive(Eq,
    Debug
    )

    Canonical conversation message. The role determines which payload is legal — illegal combinations are unrepresentable at the type level, unlike the legacy Message struct which carries every optional field on every message.

    Invariants:
    • SystemMessage / UserMessage never carry tool calls.
    • AssistantMessage is the ONLY variant that carries tool calls and the ONLY variant that carries reasoning.
    • ToolMessage is the ONLY variant that carries a call_id correlation and a ToolOutcome. It never carries tool calls.

    CanonicalToolCall

    pub(all) struct CanonicalToolCall {
    call_id : CallId
    name : ToolName
    arguments : Json
    } derive(Eq,
    Debug
    )

    Tool arguments as parsed JSON. This is the post-parsing representation: if the model stream produced malformed JSON, the reducer has already terminated the Run with ModelParseFailure before this type is constructed. Therefore any CanonicalToolCall reaching the scheduler has well-formed arguments, but the arguments may still fail the catalog schema (handled separately as NotExecuted(SchemaMismatch)).

    CanonicalToolDef

    pub(all) struct CanonicalToolDef {
    name : ToolName
    description : String
    input_schema : Json
    owner : OwnerId
    policy : ExecutionPolicy
    provenance : String?
    } derive(Eq,
    Debug
    )

    A single tool's definition as the model and the executor see it. Owned by the catalog snapshot (T05), not by individual providers.

    CanonicalToolDef::new

    fn CanonicalToolDef::new(name~ : ToolName, description~ : String, input_schema~ : Json, owner~ : OwnerId, policy~ : ExecutionPolicy, provenance~ : String?) -> CanonicalToolDef

    Internal builder used by the catalog. Most fields are required; provenance is optional. The catalog builder (T05) validates the schema and policy before constructing this, so by the time a CanonicalToolDef reaches the reducer, it has already passed composition.

    CanonicalTranscript

    pub(all) struct CanonicalTranscript {
    messages : Array[CanonicalMessage]
    } derive(Eq,
    Debug
    )

    Canonical conversation transcript. Every transition produces a fresh array (the reducer never mutates caller-owned arrays, ADR §2.10). The reducer is the only writer.

    CanonicalTranscript::append

    Returns a new transcript with message appended. The original transcript is not mutated (ADR §2.10).

    CanonicalTranscript::append_all

    Returns a new transcript with messages appended in order.

    CanonicalTranscript::empty

    CanonicalTranscript::from_array

    CanonicalTranscript::length

    fn CanonicalTranscript::length(self : CanonicalTranscript) -> Int

    Returns the number of messages.

    CanonicalTranscript::messages_snapshot

    Read-only snapshot of the message array. Returns a copy so callers cannot mutate the reducer-owned transcript.

    CanonicalUsage

    pub(all) struct CanonicalUsage {
    input_tokens : Int?
    output_tokens : Int?
    total_tokens : Int?
    } derive(Eq,
    Debug
    )

    Token usage reported by the model for a single step. The Kernel only counts what is actually reported; absent dimensions are None, never silently coerced to 0 (ADR §2.9 — unknown usage is never reported as 0).

    CatalogEntry

    pub(all) struct CatalogEntry {
    position : Int
    definition : CanonicalToolDef
    } derive(Eq,
    Debug
    )

    Internal entry: bundles a CanonicalToolDef with its position in the catalog (for stable enumeration). The snapshot exposes read-only accessors; callers cannot mutate entries.

    CatalogVersion

    pub(all) struct CatalogVersion {
    value : Int
    } derive(Eq,
    Debug
    )

    Catalog version — bumped every time a snapshot is built. The reducer and executor correlate CallModel and ExecuteTool effects back to the exact snapshot version the model was prompted against; a mismatch is a kernel invariant failure (InvariantViolation::StaleSnapshot).

    CatalogVersion::new

    fn CatalogVersion::new(value : Int) -> CatalogVersion

    CatalogVersion::to_int

    fn CatalogVersion::to_int(self : CatalogVersion) -> Int

    ChatOptions

    pub(all) struct ChatOptions {
    temperature : Double?
    max_output_tokens : Int?
    tool_choice : ToolChoice?
    reasoning_effort : ReasoningEffort?
    } derive(Eq,
    Debug
    )

    CommandDef

    pub(all) struct CommandDef {
    id : String
    label : String
    description : String
    category : String
    ctype : CommandType
    params : Array[CommandParam]
    aliases : Array[String]
    shortcut : String?
    icon : String?
    visible : Bool
    metadata : Json?
    } derive(Eq,
    Debug
    )

    Command declaration. params is the source of truth for argument rendering (panel form) and parsing (slash). Redundant fields (aliases/shortcut/icon/ visible/metadata) are deliberate "escape hatches" for ext authors to use without changing the trait — meta does not define their semantics.

    CommandOutcome

    pub(all) enum CommandOutcome {
    Success(feedback~ : String, structured~ : Json?, ui_hint~ : UiHint?)
    Failure(reason~ : String)
    NeedsInput(prompt~ : String)
    } derive(Eq,
    Debug
    )

    Outcome of invoking a command. feedback is for slash (print directly); structured + ui_hint are for panel (deep render + UI action). NeedsInput supports multi-step commands.

    CommandParam

    pub(all) struct CommandParam {
    name : String
    label : String
    description : String
    ptype : ParamType
    required : Bool
    default : Json?
    choices : Array[String]?
    positional : Bool
    } derive(Eq,
    Debug
    )

    A single command parameter. Explicit and human-facing, in contrast to ToolDef.input_schema (which is JSON Schema for LLM consumption).

    CommandType

    pub(all) enum CommandType {
    Action
    Toggle
    Select
    Input
    MultiStep
    } derive(Eq,
    Debug
    )

    Semantic command type. Determines how a panel renders the control (button / toggle / dropdown / input / multi-step form) and how a slash parser expects arguments.

    CompositeToolProvider

    pub(all) struct CompositeToolProvider {
    providers : Array[&ToolProvider]
    }

    Internal: merges multiple providers' tool lists. Agent routes via ToolRouting instead.

    CompressAction

    pub(all) enum CompressAction {
    None
    Replace(Array[Message])
    NewThread(messages~ : Array[Message], new_session_id~ : String, messages_before~ : Int, messages_after~ : Int)
    } derive(Eq,
    Debug
    )

    Action returned by a Compressor. None = no compression; Replace = substitute the message list; NewThread = start a fresh session with a summary carried over.

    CompressContext

    pub(all) struct CompressContext {
    session_id : String
    model_context_window : Int?
    } derive(Eq,
    Debug
    )

    Context passed to Compressor::compress.

    Content

    pub(all) enum Content {
    Text(String)
    Image(String, String)
    } derive(Eq,
    Debug
    )

    DeadlineReachedPayload

    pub(all) struct DeadlineReachedPayload {
    detail : String
    } derive(Eq,
    Debug
    )

    Deadline reached. Always wins against queued completions for the same reducer tick (ADR §2.5 rule 2).

    DriverStep

    pub(all) struct DriverStep {
    effect_id : EffectId
    effect_kind : String
    input_kind : String
    } derive(Eq,
    Debug
    )

    Single step in the driver's mechanical execution log. Used by T09 goldens to assert ordering and content without exposing payloads.
    impl Show for DriverStep

    DriverTrace

    pub(all) struct DriverTrace {
    steps : Array[DriverStep]
    events : Array[KernelEvent]
    final_state : RunState
    } derive(
    Debug
    )

    DriverTrace::events

    fn DriverTrace::events(self : DriverTrace) -> Array[KernelEvent]

    DriverTrace::final_state

    fn DriverTrace::final_state(self : DriverTrace) -> RunState

    DriverTrace::steps

    fn DriverTrace::steps(self : DriverTrace) -> Array[DriverStep]

    Effect

    pub(all) enum Effect {
    CallModel(effect_id~ : EffectId, payload~ : CallModelPayload)
    ExecuteTool(effect_id~ : EffectId, payload~ : ExecuteToolPayload)
    CancelOutstanding(effect_id~ : EffectId, payload~ : CancelOutstandingPayload)
    } derive(Eq,
    Debug
    )

    A single declared Effect. Each variant carries its own id and the model_step_id it belongs to. The executor consumes exactly one Effect at a time and returns exactly one completion Input (ADR §2.5).

    effect_id is unique per Run and allocated by the reducer.
    impl Show for Effect

    Effect::effect_id

    fn Effect::effect_id(self : Effect) -> EffectId

    Effect::model_step_id

    fn Effect::model_step_id(self : Effect) -> ModelStepId?

    EffectId

    pub(all) struct EffectId {
    value : Int
    } derive(Eq, Hash,
    Debug
    )

    Identifier for a single declared Effect. Monotonic per Run. Each completion input must correlate to a pending effect with this id; a mismatch is InvariantViolation::StaleCorrelation.
    impl Show for EffectId

    EffectId::first

    fn EffectId::first() -> EffectId

    EffectId::next

    fn EffectId::next(self : EffectId) -> EffectId

    EffectId::to_int

    fn EffectId::to_int(self : EffectId) -> Int

    EventSequence

    pub(all) struct EventSequence {
    value : Int
    } derive(Eq,
    Debug
    )

    Monotonic sequence counter for KernelEvents. The reducer allocates these. EventEnvelopes (built by the Harness/Interpreter outside the reducer) carry the sequence plus a wall-clock timestamp from an injected clock.

    EventSequence::initial

    fn EventSequence::initial() -> EventSequence

    EventSequence::next

    EventSequence::to_int

    fn EventSequence::to_int(self : EventSequence) -> Int

    ExecuteToolPayload

    pub(all) struct ExecuteToolPayload {
    model_step_id : ModelStepId
    call_id : CallId
    tool_name : ToolName
    arguments : Json
    owner : OwnerId
    catalog_version : CatalogVersion
    } derive(Eq,
    Debug
    )

    Payload for Effect::ExecuteTool. The executor looks up catalog_version+owner in the runtime registry; if either is missing, the executor returns a typed ToolFailed input carrying an InvariantCategory::MissingOwner/StaleSnapshot (ADR §2.5).

    ExecutionPlan

    pub(all) struct ExecutionPlan {
    waves : Array[ExecutionWave]
    } derive(Eq,
    Debug
    )

    Result of scheduling. The waves are in execution order: wave 0 runs first, then wave 1, etc. Each wave MAY run its calls in parallel.

    ExecutionPlan::total_calls

    fn ExecutionPlan::total_calls(self : ExecutionPlan) -> Int

    Total number of calls across all waves.

    ExecutionPlan::trace

    fn ExecutionPlan::trace(self : ExecutionPlan) -> String

    Single-line trace of the plan, suitable for logs and conformance golden output. Includes call ids, names and policies; NEVER includes arguments or schema payloads (ADR §2.7 — safe diagnostics).

    ExecutionPlan::wave_count

    fn ExecutionPlan::wave_count(self : ExecutionPlan) -> Int

    ExecutionPlan::waves

    ExecutionPolicy

    pub(all) enum ExecutionPolicy {
    Sequential
    Parallel
    Exclusive
    } derive(Eq,
    Debug
    )

    How a tool may be batched with other tools in the same model completion.

    • Sequential: occupies a single-element wave. Safe default; file/shell side effects never race.
    • Parallel: may share a wave with adjacent Parallel calls.
    • Exclusive: forms a barrier before and after; never shares a wave.

    ADR §2.8 freezes the safe default as Sequential. The compatibility facade (M1-T10) pins every legacy tool to Parallel to preserve M0's async.all-every-batch behaviour byte-for-byte.

    ExecutionWave

    pub(all) struct ExecutionWave {
    calls : Array[CanonicalToolCall]
    policies : Array[ExecutionPolicy]
    } derive(Eq,
    Debug
    )

    A single wave of tool calls that MAY execute in parallel. Wave membership is determined by the execution policies of adjacent calls; the executor is free to execute the wave's calls in any order or in parallel, but the reducer (T03) places the outcomes back into the transcript in source order regardless of completion order (ADR §2.8).

    FailureReason

    pub(all) enum FailureReason {
    ModelParseFailure(detail~ : String)
    ModelTransport(detail~ : String)
    ModelRuntime(detail~ : String)
    InvariantViolation(category~ : InvariantCategory)
    BudgetExhausted(dimension~ : BudgetDimension)
    DeadlineReached
    } derive(Eq,
    Debug
    )

    Why a Run terminated with Failed. Mirrors ADR §2.4 taxonomy: model parse / transport / runtime, kernel invariant, budget, deadline.

    Cancelled is a separate outcome (RunOutcome::Cancelled) and uses CancelReason, never FailureReason.

    FinishReason

    pub(all) enum FinishReason {
    Stop
    Length
    ToolCalls
    Other(String)
    } derive(Eq,
    Debug
    )

    HookChain

    pub(all) struct HookChain {
    hooks : Array[&PipelineHook]
    }

    Internal: chains multiple hooks in sequence.

    HookError

    pub(all) enum HookError {
    Aborted(String)
    Deferred(reason~ : String)
    } derive(Eq,
    Debug
    )

    impl Show for HookError

    HookRecord

    pub(all) struct HookRecord {
    stage_in : Stage
    outcome : RecordedHookOutcome
    }

    A recorded hook invocation: the stage received and its exact decision.

    InvariantCategory

    pub(all) enum InvariantCategory {
    DuplicateCompletion(effect_id~ : EffectId)
    StaleCorrelation(effect_id~ : EffectId)
    MissingOwner(owner~ : OwnerId)
    StaleSnapshot(expected~ : CatalogVersion, actual~ : CatalogVersion)
    DuplicateCallId(call_id~ : CallId)
    IllegalPhase(phase~ : String, detail~ : String)
    IllegalInputForPhase(input_kind~ : String, phase~ : String)
    PostTerminal(input_kind~ : String)
    } derive(Eq,
    Debug
    )

    Why the reducer (or constructor) declared a kernel invariant failure. Each variant carries enough context (phase, effect id, call id) to diagnose the violation without leaking raw prompt/tool payloads.

    KernelEvent

    pub(all) enum KernelEvent {
    RunStarted(details~ : StartedDetails)
    ModelStepStarted(model_step_id~ : ModelStepId, effect_id~ : EffectId)
    ModelStepCompleted(model_step_id~ : ModelStepId, completion_summary~ : String)
    ToolBatchStarted(model_step_id~ : ModelStepId, call_ids~ : Array[CallId])
    ToolCompleted(call_id~ : CallId, outcome~ : ToolOutcome)
    RunSuspended(requirement~ : SuspensionRequirement, model_step_id~ : ModelStepId)
    RunResumed(model_step_id~ : ModelStepId)
    CancelRequested(effect_ids~ : Array[EffectId], reason~ : CancelReason)
    BudgetExhausted(dimension~ : BudgetDimension, consumed~ : Int, limit~ : Int)
    InputRejected(input_kind~ : String, reason~ : String)
    RunCompleted(final_message_summary~ : String, model_steps~ : Int, tool_calls~ : Int)
    RunFailed(reason~ : FailureReason)
    RunCancelled(reason~ : CancelReason)
    } derive(Eq,
    Debug
    )

    A single domain event declared by the reducer. EventEnvelopes are built by the Harness/Interpreter outside the reducer.
    impl Show for KernelEvent

    KernelEvent::is_terminal

    fn KernelEvent::is_terminal(self : KernelEvent) -> Bool

    Whether this event is terminal (one of RunCompleted/RunFailed/RunCancelled). Used by conformance tests to assert exactly-once terminal semantics.

    MemoryEntry

    pub(all) struct MemoryEntry {
    id : String
    content : String
    metadata : Map[String, Json]
    score : Double?
    } derive(Eq,
    Debug
    )

    MemoryQuery

    pub(all) struct MemoryQuery {
    query : String
    top_k : Int
    threshold : Double?
    filter : Map[String, Json]
    } derive(Eq,
    Debug
    )

    Message

    pub(all) struct Message {
    role : Role
    content : Array[Content]
    tool_calls : Array[ToolCall]
    tool_call_id : String?
    name : String?
    reasoning_content : String?
    } derive(Eq,
    Debug
    )

    A conversation message. reasoning_content carries provider reasoning (e.g. DeepSeek deepseek-reasoner思维链, OpenAI o-series reasoning content). Providers that don't produce reasoning leave it None. Wire encoders decide whether to resend it in subsequent turns (DeepSeek: must resend for turns with tool_calls; optional otherwise).

    ModelCompletedPayload

    pub(all) struct ModelCompletedPayload {
    effect_id : EffectId
    model_step_id : ModelStepId
    completion : AssistantCompletion
    } derive(Eq,
    Debug
    )

    A successful model step completion. The reducer correlates this to the pending CallModel effect via effect_id and to the model step via model_step_id. Both must match.

    ModelFailedPayload

    pub(all) struct ModelFailedPayload {
    effect_id : EffectId
    model_step_id : ModelStepId
    failure : ModelFailure
    } derive(Eq,
    Debug
    )

    A failed model step. The reducer transitions to Terminal(Failed) with the matching FailureReason variant.

    ModelFailure

    pub(all) enum ModelFailure {
    RequestBuild(reason~ : String)
    Transport(reason~ : String)
    Runtime(reason~ : String)
    Parse(reason~ : String)
    } derive(Eq,
    Debug
    )

    Categorises why a model step failed (ADR §2.4). The reducer maps this to a FailureReason::Model* variant. Each variant carries a safe bounded label, never a raw provider payload.

    ModelId

    pub(all) struct ModelId {
    value : String
    } derive(Eq, Hash,
    Debug
    )

    Identifier for a model binding. M1 supports a single model per Run (host-supplied); M2 may add multi-model routing. The Kernel reducer never references this; it only sees the model step id.

    ModelId::new

    fn ModelId::new(value : String) -> Result[ModelId, String]

    ModelId::to_string

    fn ModelId::to_string(self : ModelId) -> String

    ModelId::unchecked

    fn ModelId::unchecked(value : String) -> ModelId

    ModelResponse

    pub(all) struct ModelResponse {
    message : Message
    tool_calls : Array[ToolCall]
    finish_reason : FinishReason
    usage : Usage?
    reasoning_content : String?
    } derive(Eq,
    Debug
    )

    ModelStepId

    pub(all) struct ModelStepId {
    value : Int
    } derive(Eq,
    Debug
    )

    Identifier for a single model step within a Run. Monotonic per Run; the reducer allocates these (the reducer is allowed to do arithmetic, just not IO/time). Each CallModel effect carries the model-step id it belongs to.
    impl Show for ModelStepId

    ModelStepId::first

    fn ModelStepId::first() -> ModelStepId

    ModelStepId::next

    fn ModelStepId::next(self : ModelStepId) -> ModelStepId

    ModelStepId::to_int

    fn ModelStepId::to_int(self : ModelStepId) -> Int

    NoopCommandPort

    pub(all) struct NoopCommandPort {
    }

    No-op CommandPort: declares no commands, invoke always raises NotFound. Useful as a default or for testing.

    NoopCompressor

    pub(all) struct NoopCompressor {
    }

    NoopHook

    pub(all) struct NoopHook {
    }

    NoopLifecycle

    pub(all) struct NoopLifecycle {
    }

    NoopMemoryPort

    pub(all) struct NoopMemoryPort {
    }

    NotExecutedReason

    pub(all) enum NotExecutedReason {
    UnknownTool
    SchemaMismatch(json_path~ : String, expected~ : String, actual~ : String)
    } derive(Eq,
    Debug
    )

    Discriminator for the reason a tool call was NOT executed even though the model requested it (ADR §2.7).

    • UnknownTool: the requested tool name is not present in the catalog snapshot that was handed to the CallModel effect.
    • SchemaMismatch: the model's arguments parsed successfully but failed validation against the tool's input schema. The diagnostic carries a safe JSON path and type expectation; it never includes the raw argument payload.

    Malformed-argument cases never reach this variant — they are ModelParseFailure at the reducer boundary (ADR §2.4).

    OwnerId

    pub(all) struct OwnerId {
    value : String
    } derive(Eq, Hash,
    Debug
    )

    Stable identifier for the provider that owns a tool. The Kernel uses this only for owner lookup in the runtime registry; it does not call into the owner through this type.

    OwnerId::new

    fn OwnerId::new(value : String) -> Result[OwnerId, String]

    OwnerId::to_string

    fn OwnerId::to_string(self : OwnerId) -> String

    OwnerId::unchecked

    fn OwnerId::unchecked(value : String) -> OwnerId

    ParamType

    pub(all) enum ParamType {
    Str
    Int
    Bool
    Strs
    } derive(Eq,
    Debug
    )

    Value type of a command parameter. Human-friendly (unlike JSON Schema which targets LLMs). Panel/slash consumers render and parse directly from this.

    Phase

    pub(all) enum Phase {
    Initializing
    ReadyForModel
    AwaitingModel
    AwaitingTools
    Suspended
    Terminal
    } derive(Eq,
    Debug
    )

    impl Show for Phase

    Reasoning

    pub(all) struct Reasoning {
    content : String
    } derive(Eq,
    Debug
    )

    Reasoning trace produced by the assistant (e.g. DeepSeek deepseek-reasoner chain-of-thought, OpenAI o-series reasoning content). The Kernel never interprets the content; it stores and replays it. None means the assistant produced no reasoning for this step.
    impl Show for Reasoning

    ReasoningEffort

    pub(all) enum ReasoningEffort {
    Off
    Minimal
    Low
    Medium
    High
    Maximum
    } derive(Eq,
    Debug
    )

    Reasoning effort requested of the model. Provider-agnostic: each ext maps these to its own effort tiers (e.g. DeepSeek collapses to on/off via model choice; OpenAI/Anthropic have explicit tiers). Maximum means the provider's absolute top tier (Claude ultra, DeepSeek Max, OpenAI high).

    RecordedHookOutcome

    pub(all) enum RecordedHookOutcome {
    Returned(Stage)
    AbortedWith(String)
    DeferredWith(String)
    }

    The exact decision made by a RecordingHook invocation.

    RecordingHook

    pub(all) struct RecordingHook {
    records : Array[HookRecord]
    abort_on : Map[String, String]
    defer_on : Map[String, String]
    }

    PipelineHook fake with configurable per-stage behavior. By default it is a pass-through (returns the stage unchanged). Records every call.

    RecordingHook::abort_when

    fn RecordingHook::abort_when(self : RecordingHook, trigger : String, msg : String) -> Unit

    Configure the hook to abort (HookError::Aborted) when it sees a stage whose debug string contains trigger.

    RecordingHook::defer_when

    fn RecordingHook::defer_when(self : RecordingHook, trigger : String, reason : String) -> Unit

    Configure the hook to defer when it sees a stage whose label contains trigger.

    RecordingHook::new

    RecordingHook::records

    RecordingObserver

    pub(all) struct RecordingObserver {
    events : Array[TurnEvent]
    }

    Observer fake that records every TurnEvent in arrival order. Unlike a counter, it keeps the full sequence for trace assertions.

    RecordingObserver::events

    Snapshot of all recorded events in order.

    RecordingObserver::new

    RecordingSessionStore

    pub(all) struct RecordingSessionStore {
    store : Map[String, Session]
    load_failures : Map[String, SessionError]
    save_failures : Array[String]
    ops : Array[SessionOp]
    }

    SessionStore fake that keeps an in-memory map and records every load/save with the metadata snapshot at save time. Load/save failures are configurable per id.

    RecordingSessionStore::fail_load

    fn RecordingSessionStore::fail_load(self : RecordingSessionStore, id : String, err : SessionError) -> Unit

    Configure load to fail for a given id.

    RecordingSessionStore::fail_save

    fn RecordingSessionStore::fail_save(self : RecordingSessionStore, id : String) -> Unit

    Configure save to fail for a given id (all subsequent saves to that id).

    RecordingSessionStore::new

    RecordingSessionStore::ops

    Recorded operations in order.

    RecordingSessionStore::save_snapshots

    fn RecordingSessionStore::save_snapshots(self : RecordingSessionStore) -> Array[(String, Map[String, Json])]

    All save operations, in order, as (id, metadata_snapshot) pairs.

    RecordingSessionStore::seed

    fn RecordingSessionStore::seed(self : RecordingSessionStore, id : String, session : Session) -> Unit

    Seed a session id with an existing session (including metadata).

    RecordingToolProvider

    pub(all) struct RecordingToolProvider {
    tool_defs : Array[ToolDef]
    outcomes : Map[String, ScriptedToolOutcome]
    list_calls : Int
    exec_records : Array[ToolExecRecord]
    ops : Array[ToolProviderOp]
    }

    ToolProvider fake that declares a fixed tool list and routes execute() by tool name through a configurable outcome map. Unknown tools raise RuntimeError::UnknownTool. Every execute is recorded with its call id.

    RecordingToolProvider::exec_records

    Snapshot of recorded executions (call id, tool name, outcome).

    RecordingToolProvider::execute_direct

    async fn RecordingToolProvider::execute_direct(self : RecordingToolProvider, name : String, call : ToolCall) -> ToolResult raise RuntimeError

    Direct (non-trait) execute entry point for testkit self-tests.

    RecordingToolProvider::list_call_count

    fn RecordingToolProvider::list_call_count(self : RecordingToolProvider) -> Int

    Number of times list_tools was called.

    RecordingToolProvider::new

    fn RecordingToolProvider::new(tool_defs : Array[ToolDef], outcomes : Map[String, ScriptedToolOutcome]) -> RecordingToolProvider

    RecordingToolProvider::ops

    Snapshot of list/execute operations in their exact observed order.

    ReduceOutput

    pub(all) struct ReduceOutput {
    next_state : RunState
    effects : Array[Effect]
    events : Array[KernelEvent]
    } derive(Eq,
    Debug
    )

    Result of a single reduce(state, input) call.

    • next_state: the new RunState (phase may be unchanged if the input was a typed rejection — see InputRejected event).
    • effects: zero or more Effects the executor should run. These are correlated back to the reducer via EffectId; completions arrive as future inputs.
    • events: zero or more KernelEvents the interpreter should publish. Terminal events (RunCompleted/RunFailed/RunCancelled) appear at most once per Run.

    The reducer never returns errors through MoonBit's raise mechanism — every invariant violation becomes a typed transition to Terminal(Failed) with FailureReason::InvariantViolation(...). The only raise paths are KernelError::ConstructorInvariant from RunState constructors, which surface programming errors (not runtime facts).

    ReduceOutput::effects

    fn ReduceOutput::effects(self : ReduceOutput) -> Array[Effect]

    ReduceOutput::events

    ReduceOutput::next_state

    fn ReduceOutput::next_state(self : ReduceOutput) -> RunState

    ResumePayload

    pub(all) struct ResumePayload {
    payload : Json
    } derive(Eq,
    Debug
    )

    Resume. Only legal from Suspended. The reducer emits RunResumed and transitions back to ReadyForModel to re-issue the model step.

    Role

    pub(all) enum Role {
    System
    User
    Assistant
    Tool
    } derive(Eq,
    Debug
    )

    RunContext

    pub(all) struct RunContext {
    run_id : RunId
    session_id : SessionId
    budget : Budget
    } derive(Eq,
    Debug
    )

    Immutable runtime context for a single Run (ADR §2.9). Carried by RunState but never mutated. The reducer reads from this for budget/limit checks; it does NOT read a clock.

    Product layers (TUI, session backend, MCP, extension host) MUST NOT appear here — Kernel boundary.

    RunContext::new

    fn RunContext::new(run_id~ : RunId, session_id~ : SessionId, budget~ : Budget) -> RunContext

    RunId

    pub(all) struct RunId {
    value : String
    } derive(Eq, Hash,
    Debug
    )

    Stable identifier for a single Run. The Kernel never constructs this; it is supplied by the host in the Start input and carried through every state.
    impl Show for RunId

    RunId::new

    fn RunId::new(value : String) -> Result[RunId, String]

    RunId::to_string

    fn RunId::to_string(self : RunId) -> String

    RunId::unchecked

    fn RunId::unchecked(value : String) -> RunId

    RunInput

    pub(all) enum RunInput {
    Start(payload~ : StartPayload)
    ModelCompleted(payload~ : ModelCompletedPayload)
    ModelFailed(payload~ : ModelFailedPayload)
    ToolCompleted(payload~ : ToolCompletedPayload)
    ToolFailed(payload~ : ToolFailedPayload)
    CancelRequested(payload~ : CancelRequestedPayload)
    DeadlineReached(payload~ : DeadlineReachedPayload)
    BudgetExhausted(payload~ : BudgetExhaustedPayload)
    SuspendRequested(payload~ : SuspendRequestedPayload)
    Resume(payload~ : ResumePayload)
    } derive(Eq,
    Debug
    )

    Discriminator for RunInput variants. The reducer pattern-matches on this in reduce(state, input).
    impl Show for RunInput

    RunInput::kind

    fn RunInput::kind(self : RunInput) -> String

    Stable string label for the input kind. Used by InputRejected events and by debug/conformance output. The string form is part of the contract (replay-equal), so it must not drift.

    RunOutcome

    pub(all) enum RunOutcome {
    Completed(final_message~ : CanonicalMessage, tool_results~ : Array[ToolOutcome])
    Failed(reason~ : FailureReason)
    Cancelled(reason~ : CancelReason)
    } derive(Eq,
    Debug
    )

    Terminal outcome of a Run (ADR §2.3). Exactly one per Run; carried by the Terminal phase.
    impl Show for RunOutcome

    RunState

    pub struct RunState {
    run_id : RunId
    session_id : SessionId
    budget : Budget
    phase : Phase
    transcript : CanonicalTranscript
    pending_effects : Array[Effect]
    next_event_sequence : EventSequence
    next_effect_id : EffectId
    current_model_step_id : ModelStepId
    catalog_version : CatalogVersion
    budget_consumed : BudgetConsumed
    outcome : RunOutcome?
    suspension_requirement : SuspensionRequirement?
    } derive(Eq,
    Debug
    )

    The Run's full state. Field visibility is priv (no pub(all) on the struct itself) so callers cannot construct illegal combinations; the constructors below enforce invariants.

    Note: MoonBit struct fields default to package-private, so within src/ tests can still read them via accessors. The constructors are the only sanctioned way to produce a legal state.
    impl Show for RunState

    RunState::budget

    fn RunState::budget(self : RunState) -> Budget

    RunState::budget_consumed

    fn RunState::budget_consumed(self : RunState) -> BudgetConsumed

    RunState::catalog_version

    fn RunState::catalog_version(self : RunState) -> CatalogVersion

    RunState::current_model_step_id

    fn RunState::current_model_step_id(self : RunState) -> ModelStepId

    RunState::initial

    fn RunState::initial(run_id~ : RunId, session_id~ : SessionId, budget~ : Budget) -> RunState raise KernelError

    Construct the initial Initializing state. The reducer accepts exactly one input against this state: Start. Any other input is a typed rejection.

    RunState::next_effect_id

    fn RunState::next_effect_id(self : RunState) -> EffectId

    RunState::next_event_sequence

    fn RunState::next_event_sequence(self : RunState) -> EventSequence

    RunState::outcome

    fn RunState::outcome(self : RunState) -> RunOutcome?

    RunState::pending_effects

    fn RunState::pending_effects(self : RunState) -> Array[Effect]

    RunState::phase

    fn RunState::phase(self : RunState) -> Phase

    RunState::run_id

    fn RunState::run_id(self : RunState) -> RunId

    RunState::session_id

    fn RunState::session_id(self : RunState) -> SessionId

    RunState::suspension_requirement

    fn RunState::suspension_requirement(self : RunState) -> SuspensionRequirement?

    RunState::transcript

    fn RunState::transcript(self : RunState) -> CanonicalTranscript

    RunState::transition

    fn RunState::transition(self : RunState, phase~ : Phase, transcript~ : CanonicalTranscript, pending_effects~ : Array[Effect], next_event_sequence~ : EventSequence, next_effect_id~ : EffectId, current_model_step_id~ : ModelStepId, catalog_version~ : CatalogVersion?, budget_consumed~ : BudgetConsumed, outcome~ : RunOutcome?, suspension_requirement~ : SuspensionRequirement?) -> RunState raise KernelError

    Internal: produce the next state from raw fields, running invariants. Exposed at package level so the reducer (in kernel_reducer.mbt) can use it without re-implementing validation.

    RuntimeRegistry

    pub struct RuntimeRegistry {
    model_port : &ModelPort
    model_id : ModelId
    tool_providers : Map[String, &ToolProvider]
    }

    Maps OwnerId -> &ToolProvider and ModelId -> &ModelPort. Built by the host from the same providers that built the catalog snapshot.

    Missing owner / stale snapshot version returned from the registry is a typed ToolFailed Input carrying InvariantCategory::MissingOwner / StaleSnapshot (ADR §2.4). The executor does NOT silently fall back.

    RuntimeRegistry::find_tool_provider

    fn RuntimeRegistry::find_tool_provider(self : RuntimeRegistry, owner : OwnerId) -> &ToolProvider?

    Look up a ToolProvider by owner id. Missing owner returns None; the caller (executor) is responsible for raising the typed invariant failure via a ToolFailed Input.

    RuntimeRegistry::model_id

    fn RuntimeRegistry::model_id(self : RuntimeRegistry) -> ModelId

    RuntimeRegistry::model_port

    fn RuntimeRegistry::model_port(self : RuntimeRegistry) -> &ModelPort

    RuntimeRegistry::new

    fn RuntimeRegistry::new(model_port : &ModelPort, model_id~ : ModelId, tool_bindings : Array[(OwnerId, &ToolProvider)]) -> RuntimeRegistry

    SchemaDiagnostic

    pub(all) struct SchemaDiagnostic {
    json_path : String
    expected : String
    actual : String
    } derive(Eq,
    Debug
    )

    Result of validating parsed tool arguments against a CanonicalToolDef's input schema. The validator (T05) returns this; the reducer (T03) maps Err into a ToolOutcome::NotExecuted(SchemaMismatch) carrying the original call id.

    The diagnostic deliberately excludes the raw argument payload; it reports only a JSON path and a type expectation, so that prompts and tool arguments never leak into logs.

    ScriptedExecutor

    pub struct ScriptedExecutor {
    outcomes : Map[String, ScriptedOutcome]
    }

    A fake executor: returns scripted outcomes by effect id. Used by T09 golden tests so they don't need a real ModelPort / ToolProvider.

    ScriptedExecutor::lookup

    fn ScriptedExecutor::lookup(self : ScriptedExecutor, effect_id : EffectId) -> ScriptedOutcome

    Look up the scripted outcome for an effect. Returns the configured outcome or a default invariant failure if not configured (so tests fail loudly rather than silently passing).

    ScriptedExecutor::new

    ScriptedExecutor::on

    Configure the outcome for a specific effect id (string form). The scripted driver looks up by effect_id.to_string().

    ScriptedModel

    pub(all) struct ScriptedModel {
    steps : Array[ScriptedModelStep]
    index : Int
    calls : Int
    received_messages : Array[Array[Message]]
    received_tools : Array[Array[ToolDef]]
    received_options : Array[ChatOptions]
    received_chunks : Array[StreamChunk]
    }

    ModelPort fake that plays a fixed script. Each chat call consumes one step in order. When the script is exhausted the next call fails with ModelError::Transport("scripted_model_exhausted at call <N>") — it never silently repeats the last response.

    ScriptedModel::call_count

    fn ScriptedModel::call_count(self : ScriptedModel) -> Int

    Number of chat/chat_streaming calls observed so far.

    ScriptedModel::chat_direct

    async fn ScriptedModel::chat_direct(self : ScriptedModel, messages : Array[Message], tools : Array[ToolDef], options : ChatOptions) -> ModelResponse raise ModelError

    Direct (non-trait) chat entry point for testkit self-tests. Trait methods on concrete types must be dispatched through a &ModelPort reference; this wrapper lets tests call chat without an Agent.

    ScriptedModel::chat_streaming_direct

    async fn ScriptedModel::chat_streaming_direct(self : ScriptedModel, messages : Array[Message], tools : Array[ToolDef], options : ChatOptions, on_chunk : (StreamChunk) -> Unit) -> ModelResponse raise ModelError

    Direct streaming entry point for testkit self-tests.

    ScriptedModel::new

    ScriptedModel::options_received

    fn ScriptedModel::options_received(self : ScriptedModel) -> Array[ChatOptions]

    Snapshot of all chat options received, in call order.

    ScriptedModelStep

    pub(all) enum ScriptedModelStep {
    Respond(ModelResponse)
    Stream(chunks~ : Array[StreamChunk], response~ : ModelResponse)
    Fail(ModelError)
    }

    A single scripted model interaction: a response, an exact stream transcript, or a typed error. Stream never synthesizes chunks from the final response.

    ScriptedOutcome

    pub(all) enum ScriptedOutcome {
    ScriptedModelCompleted(AssistantCompletion)
    ScriptedModelFailed(ModelFailure)
    ScriptedToolCompleted(ToolOutcome)
    ScriptedToolRuntime(ModelFailure)
    ScriptedToolInvariant(InvariantCategory)
    }

    What the scripted executor returns for a given effect id.

    ScriptedToolOutcome

    pub(all) enum ScriptedToolOutcome {
    OutcomeOk(ToolResult)
    OutcomeErr(RuntimeError)
    }

    Configurable outcome for a tool call: success result, or raised runtime error. Constructors are prefixed with Outcome to avoid ambiguity with Result::Ok/Result::Err at unqualified call sites.

    Session

    pub(all) struct Session {
    messages : Array[Message]
    metadata : Map[String, Json]
    } derive(Eq,
    Debug
    )

    SessionId

    pub(all) struct SessionId {
    value : String
    } derive(Eq, Hash,
    Debug
    )

    Stable identifier for a session. Maps directly to the legacy SessionStore::load/save id; the Kernel never opens the session itself, it only carries the id for the executor/facade to use.

    SessionId::new

    fn SessionId::new(value : String) -> Result[SessionId, String]

    SessionId::to_string

    fn SessionId::to_string(self : SessionId) -> String

    SessionId::unchecked

    fn SessionId::unchecked(value : String) -> SessionId

    SessionOp

    pub(all) enum SessionOp {
    OpLoad(id~ : String, result~ : Result[Session, SessionError])
    OpSave(id~ : String, metadata~ : Map[String, Json], result~ : Result[Unit, SessionError])
    }

    A recorded session operation. Constructors are prefixed with Op to avoid ambiguity with SessionError::Load/SessionError::Save.

    Stage

    pub(all) enum Stage {
    BeforeTurn
    BeforeModel(Array[Message])
    AfterModel(ModelResponse)
    ModelError(String)
    BeforeTool(ToolCall)
    AfterTool(ToolCall, ToolResult)
    ToolError(ToolCall, RuntimeError)
    AfterTurn(TurnResult)
    TurnError(AgentError)
    } derive(
    Debug
    )

    Pipeline hook stages. The Before* variants run hooks in forward order (short-circuit on error); the After*/*Error variants run in reverse order (onion semantics) without short-circuiting (finally semantics).

    StartPayload

    pub(all) struct StartPayload {
    initial_messages : Array[CanonicalMessage]
    catalog_version : CatalogVersion
    } derive(Eq,
    Debug
    )

    The initial input that drives a Run out of Initializing. Carries the initial transcript seed (system prompt, user message, etc.) and the catalog version to use.

    StartedDetails

    pub(all) struct StartedDetails {
    run_id : RunId
    session_id : SessionId
    } derive(Eq,
    Debug
    )

    Emitted when the reducer first transitions out of Initializing (the Start input). The RunStarted event is non-terminal.

    Note: this is the new Kernel name (open question Q6.4 — ADR recommended scheme). The legacy TurnStarted continues to be emitted by the compatibility facade alongside this event.

    StreamAccumulator

    pub(all) struct StreamAccumulator {
    text : String
    reasoning : String
    tool_calls : Array[ToolCallBuilder]
    finish_reason : FinishReason
    usage : Usage?
    } derive(
    Debug
    )

    Accumulates StreamChunk events into a ModelResponse.

    StreamAccumulator::new

    StreamAccumulator::push

    fn StreamAccumulator::push(self : StreamAccumulator, chunk : StreamChunk) -> Unit

    StreamAccumulator::to_response

    Assemble accumulated stream chunks into a ModelResponse.

    T07 error-transparency: malformed tool-call argument JSON raises ModelError::ResponseParse instead of silently becoming {}. This prevents a corrupted stream from masquerading as a valid empty-args call.

    StreamChunk

    pub(all) enum StreamChunk {
    TextDelta(token~ : String)
    ReasoningDelta(token~ : String)
    ToolCallDelta(index~ : Int, id~ : String?, name~ : String?, arguments_delta~ : String?)
    Usage(Usage)
    Finish(reason~ : FinishReason)
    } derive(Eq,
    Debug
    )

    SuspendRequestedPayload

    pub(all) struct SuspendRequestedPayload {
    requirement : SuspensionRequirement
    } derive(Eq,
    Debug
    )

    Suspend requested. Only legal from AwaitingModel with the single CallModel effect pending (ADR §2.6). The reducer drops the pending effect (emitting a CancelOutstanding for it), emits RunSuspended, and enters Suspended with zero pending effects.

    SuspensionRequirement

    pub(all) struct SuspensionRequirement {
    kind : String
    payload : Json
    } derive(Eq,
    Debug
    )

    Suspension requirement — what the host must satisfy before sending Resume. M1 only exercises in-process resume; cross-process durability is M5. The Kernel never interprets the payload.

    ToolCall

    pub(all) struct ToolCall {
    id : String
    name : String
    arguments : Json
    } derive(Eq,
    Debug
    )

    ToolCallBuilder

    pub(all) struct ToolCallBuilder {
    id : String
    name : String
    arguments_json : String
    } derive(
    Debug
    )

    ToolCallBuilder::new

    ToolCatalogBuilder

    pub struct ToolCatalogBuilder {
    entries : Array[CatalogEntry]
    by_name : Map[String, CatalogEntry]
    finished : Bool
    }

    Incremental builder for ToolCatalogSnapshot. Validates each insertion atomically: any composition failure aborts the build and the builder cannot be reused.

    Typical use:
    let snapshot = ToolCatalogBuilder::new()
    .add(def1)
    .add(def2)
    .finish(version=CatalogVersion::new(1))

    ToolCatalogBuilder::add

    Add a tool definition. Validates:
    • non-empty name (already enforced by CanonicalToolDef, but double-check)
    • no name collision
    • no duplicate provenance+name
    • supported schema keywords only
    • well-formed schema (object or boolean at top level)

    Returns the builder for chaining. Raises CatalogCompositionError on any composition hard failure.

    ToolCatalogBuilder::finish

    Seal the builder and produce an immutable snapshot. The builder is marked sealed; further add calls raise.

    ToolCatalogBuilder::new

    ToolCatalogSnapshot

    pub struct ToolCatalogSnapshot {
    version : CatalogVersion
    entries : Array[CatalogEntry]
    by_name : Map[String, CatalogEntry]
    } derive(Eq,
    Debug
    )

    Immutable, versioned catalog. Built by ToolCatalogBuilder; consumed read-only by the reducer and executor.

    ToolCatalogSnapshot::contains

    fn ToolCatalogSnapshot::contains(self : ToolCatalogSnapshot, name : ToolName) -> Bool

    Convenience: does the catalog contain a tool with this call-visible name?

    ToolCatalogSnapshot::definitions

    Returns just the tool definitions in source order — what the model adapter should be prompted with.

    ToolCatalogSnapshot::entries

    Returns all entries in declaration (source) order. The result is a copy; callers cannot mutate the snapshot.

    ToolCatalogSnapshot::find

    Look up an entry by call-visible name. Returns None if not present.

    ToolCatalogSnapshot::size

    Number of tools in the catalog.

    ToolCatalogSnapshot::validate_arguments

    fn ToolCatalogSnapshot::validate_arguments(self : ToolCatalogSnapshot, name : ToolName, arguments : Json) -> Result[Unit, SchemaDiagnostic]

    Validate parsed arguments against the named tool's input schema. Used by the reducer (T03) when folding ModelCompleted. Returns:
    • Ok(()) if the args conform
    • Err(SchemaDiagnostic) if the args are well-formed JSON but fail the schema

    Unknown tool name returns Err with a diagnostic that the reducer maps to ToolOutcome::NotExecuted(UnknownTool).

    ToolCatalogSnapshot::version

    ToolChoice

    pub(all) enum ToolChoice {
    Auto
    NoTool
    Required
    NamedTool(String)
    } derive(Eq,
    Debug
    )

    ToolCompletedPayload

    pub(all) struct ToolCompletedPayload {
    effect_id : EffectId
    call_id : CallId
    outcome : ToolOutcome
    } derive(Eq,
    Debug
    )

    A successful or business-failed tool outcome. Runtime failures arrive as ToolFailed instead. The reducer correlates this to the pending ExecuteTool effect via effect_id; the call_id must also match the effect's payload.

    ToolDef

    pub(all) struct ToolDef {
    name : String
    description : String
    input_schema : Json
    metadata : Json?
    source : String?
    } derive(Eq,
    Debug
    )

    ToolExecRecord

    pub(all) struct ToolExecRecord {
    requested_name : String
    call_id : String
    tool_name : String
    arguments : Json
    outcome : ScriptedToolOutcome
    }

    A recorded tool execution: call id, tool name, and outcome category.

    ToolFailedPayload

    pub(all) struct ToolFailedPayload {
    effect_id : EffectId
    call_id : CallId
    runtime : ModelFailure?
    invariant_failure : InvariantCategory?
    } derive(Eq,
    Debug
    )

    The adapter could not produce a ToolOutcome (e.g. provider raised a RuntimeError). The reducer converts this into a canonical ToolOutcome::RuntimeFailure and continues the Run — non-terminal.

    Kernel-invariant failures (MissingOwner, StaleSnapshot) also arrive through this variant, carrying the matching InvariantCategory; the reducer then transitions to Terminal(Failed) (ADR §2.4). This is the single channel by which executor-side invariants reach the reducer.

    ToolName

    pub(all) struct ToolName {
    value : String
    } derive(Eq, Hash,
    Debug
    )

    A tool name as it appears in the catalog (call-visible name). The Kernel uses this only for lookup in the catalog snapshot; it never re-parses or re-normalizes it.

    ToolName::new

    fn ToolName::new(value : String) -> Result[ToolName, String]

    ToolName::to_string

    fn ToolName::to_string(self : ToolName) -> String

    ToolName::unchecked

    fn ToolName::unchecked(value : String) -> ToolName

    ToolOutcome

    pub(all) enum ToolOutcome {
    Success(content~ : String, structured~ : Json?)
    ToolReportedError(content~ : String, structured~ : Json?)
    RuntimeFailure(error_category~ : String, message~ : String)
    NotExecuted(reason~ : NotExecutedReason, original_call_id~ : CallId)
    } derive(Eq,
    Debug
    )

    Outcome of a single tool invocation (ADR §2.4, §2.11).

    Variants:
    • Success: tool ran and returned structured data. structured is the model-facing JSON payload; content is the human-readable mirror used by the transcript.
    • ToolReportedError: tool ran and reported a business-level failure (equivalent to legacy ToolResult.is_error = true). The Run continues; the failure is fed back to the model as a normal tool message.
    • RuntimeFailure: tool did not run to completion — adapter raised a RuntimeError. Still non-terminal for the Run.
    • NotExecuted: model requested a tool that was not executed (unknown name or parseable-but-schema-invalid args). The original call id is preserved so the model can correlate the feedback.

    There is deliberately no boolean is_error field here. The variant tag IS the error status.
    impl Show for ToolOutcome

    ToolOutcome::is_failure

    fn ToolOutcome::is_failure(self : ToolOutcome) -> Bool

    Whether the outcome represents a non-success path (any variant other than Success). Used by the facade when translating to the legacy ToolResult.is_error boolean — but the canonical Kernel never needs this helper because pattern-matching is exhaustive.

    ToolOutcome::summary

    fn ToolOutcome::summary(self : ToolOutcome) -> String

    Single-line summary that excludes raw payloads. Used by Show and by any debug/log surface, so that prompts and tool arguments never leak.

    ToolProviderOp

    pub(all) enum ToolProviderOp {
    ListTools
    ExecuteTool(requested_name~ : String, call~ : ToolCall)
    }

    Unified provider operation trace, preserving list/execute interleaving.

    ToolRegistry

    pub(all) struct ToolRegistry {
    tools : Map[String, ToolDef]
    executors : Map[String, (ToolCall) -> ToolResult]
    }

    Dynamic runtime tool registration. Implements ToolProvider.

    ToolRegistry::new

    ToolRegistry::register

    fn ToolRegistry::register(self : ToolRegistry, tool : ToolDef, executor : (ToolCall) -> ToolResult) -> Unit

    ToolRegistry::unregister

    fn ToolRegistry::unregister(self : ToolRegistry, name : String) -> Unit

    ToolResult

    pub(all) struct ToolResult {
    content : String
    structured : Json?
    is_error : Bool
    } derive(Eq,
    Debug
    )

    ToolRouting

    type ToolRouting

    Internal routing table: tool name → owning provider. Built during Agent::new.

    TurnEvent

    pub(all) enum TurnEvent {
    TurnStarted
    ToolCallPending(ToolCall)
    ToolCallResult(call~ : ToolCall, result~ : ToolResult, is_error~ : Bool)
    ModelResponseReceived(message~ : Message, usage~ : Usage?, reasoning_content~ : String?)
    SessionRedirect(from~ : String, to~ : String, messages_before~ : Int, messages_after~ : Int)
    TurnCompleted
    TurnFailed(String)
    ToolCallDeferred(call~ : ToolCall, reason~ : String)
    StreamChunkReceived(chunk~ : StreamChunk)
    Custom(source~ : String, label~ : String, data~ : Json)
    } derive(Eq,
    Debug
    )

    impl Show for TurnEvent

    TurnResult

    pub(all) struct TurnResult {
    message : Message
    tool_results : Array[ToolResult]
    final_session_id : String
    } derive(Eq,
    Debug
    )

    UiHint

    pub(all) enum UiHint {
    RefreshModelList
    RefreshSettings
    ClosePanel
    Toast
    None
    } derive(Eq,
    Debug
    )

    Hint to a panel consumer about what UI action to take after invoke. Slash consumers ignore this. Fixed enum + None fallback; ext long-tail needs go through CommandDef.metadata.

    Usage

    pub(all) struct Usage {
    input_tokens : Int?
    output_tokens : Int?
    total_tokens : Int?
    } derive(Eq,
    Debug
    )

    assert_events_contain

    fn assert_events_contain(haystack : Array[TurnEvent], needle : Array[TurnEvent]) -> Unit

    Assert the recorded events contain a sub-sequence matching needle, in order. Reports the first needle event that could not be matched.

    assert_events_eq

    fn assert_events_eq(expected : Array[TurnEvent], actual : Array[TurnEvent]) -> Unit

    Assert two event traces are equal, reporting the first differing index, the expected and actual event, when they diverge.

    build_error_message

    fn build_error_message(call : ToolCall, error : RuntimeError) -> Message

    build_tool_result_message

    fn build_tool_result_message(call : ToolCall, result : ToolResult) -> Message

    canonical_to_legacy_message

    fn canonical_to_legacy_message(cm : CanonicalMessage) -> Message

    Convert a canonical message back to the legacy Message type the ModelPort expects. Inverse of legacy_to_completion for assistant payloads; for system/user/tool messages we project the canonical content.

    check_schema_supported

    fn check_schema_supported(schema : Json) -> Result[Unit, String]

    Pre-check a tool's input schema at composition time. Returns Ok(()) if the schema only uses supported keywords; returns Err with the first offending keyword otherwise. This is what the catalog builder (T05) invokes BEFORE attempting any runtime validation — composition hard failure (ADR §2.7).

    event_trace_mismatch

    fn event_trace_mismatch(expected : Array[TurnEvent], actual : Array[TurnEvent]) -> String?

    Return the first structural trace mismatch. Kept pure so conformance tests can prove missing, duplicate, and out-of-order detection without catching an assertion panic.

    execute_one

    async fn execute_one(effect : Effect, registry : RuntimeRegistry, on_chunk : (StreamChunk) -> Unit) -> RunInput

    Execute ONE Effect and return ONE structured RunInput. The executor holds no state; every call is independent. The result is fed straight back to reduce.

    Categorisation:
    • CallModel → calls ModelPort.chat_streaming, folds streaming chunks via the M0 StreamAccumulator, returns ModelCompleted on success or ModelFailed on ModelError.
    • ExecuteTool → looks up the owner in the registry. Missing owner or stale snapshot version returns ToolFailed carrying the typed invariant category. Otherwise calls ToolProvider.execute and returns ToolCompleted (mapping legacy ToolResult.is_error to ToolReportedError / Success) or ToolFailed (mapping RuntimeError).
    • CancelOutstanding → records the cancel disposition and returns a no-op acknowledgment as a typed input (M1: always returns CancelAcked via ToolFailed with no invariant; the reducer treats it as already terminal). Real adapter propagation hardening is M3.

    legacy_to_completion

    fn legacy_to_completion(response : ModelResponse) -> AssistantCompletion

    Convert legacy ModelResponse → canonical AssistantCompletion. This is the inverse of the legacy duplication: we read tool_calls/reasoning from the inner Message (the single source of truth in canonical form) and ignore the duplicated top-level fields.

    outcome_to_legacy

    fn outcome_to_legacy(outcome : ToolOutcome) -> (String, Bool)

    Convert canonical ToolOutcome → (legacy content, legacy is_error). Used by the facade when feeding outcomes back to legacy observers.

    parse_slash_args

    fn parse_slash_args(text : String, params : Array[CommandParam]) -> Result[Json, String]

    Parse a slash argument string into a JSON object according to CommandParam definitions. Positional params fill in declaration order; non-positional params expect key=value form. Applies defaults for missing optional params. Returns Err with a reason string on type conversion failure or missing required params. Pure function (no IO).

    reduce

    fn reduce(state : RunState, catalog : ToolCatalogSnapshot, input : RunInput) -> ReduceOutput raise KernelError

    The reducer. Pure: same (state, input) → same (next_state, effects, events).

    The catalog is passed separately because the RunState does not own it (the snapshot may outlive any single Run; M2 may refresh it). The reducer only reads from the snapshot, never writes.

    run_model_step

    fn run_model_step(state : RunState, catalog : ToolCatalogSnapshot, call_options : Json) -> ReduceOutput raise KernelError

    Issue a CallModel effect. This is the reducer entry point that the scripted driver / facade uses when it decides the run should advance to the next model step. The reducer:
    • allocates a fresh EffectId and ModelStepId
    • builds the CallModelPayload from the current transcript + catalog
    • transitions to AwaitingModel

    Note: this function is NOT called via reduce(state, catalog, input). It is a separate entry point because "request the next model step" is a host decision, not a fact the reducer observed. We expose it this way so that the reducer remains the single writer of state, but the triggering decision stays outside (M1 §6: "Reducer 不调用 trait、不读 时钟"). The host/driver calls this after reducer-declared effects have completed AND the host has decided more work is needed.

    schedule

    fn schedule(snapshot : ToolCatalogSnapshot, expected_version : CatalogVersion, calls : Array[CanonicalToolCall]) -> ExecutionPlan raise SchedulingError

    Schedule calls (already validated for unknown name and schema) into execution waves according to each tool's ExecutionPolicy.

    The caller passes the catalog snapshot AND the expected_version it built the model prompt against; a mismatch is StaleSnapshotVersion.

    Raises SchedulingError on:
    • duplicate call_id within the batch
    • unknown tool reaching the scheduler (upstream invariant broken)
    • stale snapshot version

    scripted_driver_run

    fn scripted_driver_run(initial_state : RunState, catalog : ToolCatalogSnapshot, scripted : ScriptedExecutor, start : StartPayload, max_iterations : Int) -> DriverTrace raise KernelError

    Drive a Run mechanically using the scripted executor. The driver:
    1. Calls reduce(state, catalog, Start) to seed the run.
    2. Repeats until state is Terminal OR no further model step is requested: a. If state is ReadyForModel, call run_model_step to declare a CallModel effect. b. For each declared effect, look up the scripted outcome and feed the resulting Input back to reduce.
    3. Returns a DriverTrace with steps, events and the final state.

    max_iterations is a safety guard: if the run does not terminate, the driver aborts by returning the last state.

    tk_config

    fn tk_config() -> AgentConfig

    Build a default AgentConfig for scripted tests.

    tk_error_result

    fn tk_error_result(content : String) -> ToolResult

    Build a business-error ToolResult (provider returns Ok but is_error=true).

    tk_ok_result

    fn tk_ok_result(content : String) -> ToolResult

    Build a successful ToolResult.

    tk_stop_response

    fn tk_stop_response(text : String) -> ModelResponse

    Build a minimal stop response (no tool calls) for scripted tests.

    tk_tool_call_response

    fn tk_tool_call_response(tool_name : String, call_id : String, args : Json) -> ModelResponse

    Build a response that requests a single tool call.

    tk_tool_def

    fn tk_tool_def(name : String, description : String) -> ToolDef

    Build a ToolDef with an empty object schema.

    tk_user_msg

    fn tk_user_msg(text : String) -> Message

    Build a user message.

    validate_args

    fn validate_args(def : CommandDef, args : Json) -> Result[Json, String]

    Validate a JSON object of args against a CommandDef's params. Checks required presence; optional params with no value and no default are omitted (not an error). Returns the (possibly defaulted) args on Ok. Pure function (no IO).

    validate_arguments

    fn validate_arguments(schema : Json, instance : Json) -> Result[Unit, SchemaDiagnostic]

    Validate instance against schema. Returns Ok(()) on success, or Err(SchemaDiagnostic) carrying a safe JSON path + expected/actual pair.

    The diagnostic never includes the raw instance payload — only a JSON path and a type expectation. This is the function the reducer (T03) calls when folding a ModelCompleted completion whose tool calls have already parsed.