colmugx/posoco/kernel does not have a README file

    HostChunkCallback

    type HostChunkCallback = (Json) -> Unit

    Streaming chunk callback shape. The host delivers raw provider chunks to the observer/telemetry surface without interpretation — the Kernel does not define a canonical chunk type because streaming is a host/telemetry concern, not a transcript fact (ADR §2.11).

    HostRuntime

    pub(open) trait HostRuntime {
    async fn call_model(Self, messages : Array[CanonicalMessage], tool_definitions : Array[CanonicalToolDef], call_options : Json, on_chunk : (Json) -> Unit) -> Result[AssistantCompletion, ModelFailure]
    async fn execute_tool(Self, owner_id : OwnerId, call_id : CallId, tool_name : ToolName, arguments : Json) -> ToolOutcome
    async fn cancel_effects(Self, effect_ids : Array[EffectId], reason : CancelReason) -> Array[(EffectId, CancelDisposition)]
    }

    Host runtime contract. Implementations live outside the Kernel package (root compatibility facade or M3 provider packages).

    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.

    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

    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).

    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

    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.

    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.

    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.

    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

    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

    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

    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.

    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?
    tool_results : Array[(CallId, ToolOutcome)]
    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.

    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().

    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.

    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

    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.

    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.

    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

    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.

    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.

    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).

    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.

    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.