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.5.1
    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 解析已由 external/moon.work + scripts/check-local-resolution.sh 验证到当前 checkout 的 colmugx/posoco@0.5.0;extension manifests 仍声明旧的 @0.4.4, 所以版本声明清理仍是 open risk,不能把 workspace 解析证据扩展成发布安装保证。

    Canonical M1/M2 code is owned by the separate colmugx/posoco/kernel and colmugx/posoco/puppetry packages. The root Agent::run_turn remains the default legacy entry point; Kernel/Harness facades are opt-in.

    #关键运行语义

    • 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

    AgentError

    ChatOptions

    CommandDef

    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.

    CommandParam

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

    CommandPort

    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.

    CompositionError

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

    Compressor

    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.

    Content

    Lifecycle

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

    MemoryPort

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

    Message

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

    ModelError

    ModelPort

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

    ModelResponse

    Observer

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

    PipelineHook

    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.

    ReasoningEffort

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

    Role

    RuntimeError

    Session

    SessionError

    SessionStore

    SessionStore: persist and load conversation sessions by id.

    Stage

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

    StreamChunk

    ToolCall

    ToolChoice

    ToolDef

    ToolProvider

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

    ToolResult

    TurnEvent

    TurnResult

    HarnessFacadeError

    pub(all) suberror HarnessFacadeError {
    SessionLoad(detail~ : String)
    SessionSave(detail~ : String)
    CatalogComposition(failure~ :
    CatalogCompositionError
    )
    HarnessRejected(error~ :
    HarnessError
    )
    UnsupportedSuspension(run_id~ :
    RunId
    , suspension_id~ : String)
    NonCompletedTerminal(outcome~ :
    RunOutcome
    )
    ConversionFailed(detail~ : String)
    }

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

    Agent

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

    Agent::new

    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

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

    Agent::run_turn_via_harness

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

    Drive a single turn through the M2 Harness. Returns a legacy TurnResult for compatibility with M0 callers.

    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 @types.TurnResult for compatibility with M0 callers.

    Known limitations vs M0 run_turn:
    • No @port.PipelineHook / @port.Compressor / streaming chunk support.
    • No @port.MemoryPort / @port.Lifecycle / @port.CommandPort integration.
    • Tool execution is sequential via the scripted driver (not parallel).
    • @port.Observer events are kernel-shaped (@kernel.RunStarted/@kernel.RunCompleted), not the full M0 @types.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

    CompositeToolProvider

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

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

    HookChain

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

    Internal: chains multiple hooks in sequence.

    HookRecord

    pub(all) struct HookRecord {
    stage_in :
    Stage

    outcome : RecordedHookOutcome
    }

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

    LegacyHostRuntime

    pub(all) struct LegacyHostRuntime {
    model_port : &
    ModelPort

    tool_providers : Map[String, &
    ToolProvider
    ]
    }

    Host-runtime implementation backed by legacy @port.ModelPort + @port.ToolProviders. Constructed from an Agent's bound providers; the lifetime of every reference is tied to the Agent.

    LegacyHostRuntime::from_agent

    fn LegacyHostRuntime::from_agent(agent : Agent) -> LegacyHostRuntime

    Build a LegacyHostRuntime from an Agent. Owner ids are derived from each tool's source field (falling back to "legacy_provider"), matching how build_agent_catalog assigns owners — so the owner a reducer sees in an ExecuteTool effect resolves back to the same provider here.

    LegacyHostRuntime::new

    Direct constructor (used by tests that assemble an Agent without going through Agent::new).

    NoopCommandPort

    pub(all) struct NoopCommandPort {
    }

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

    NoopHook

    pub(all) struct NoopHook {
    }

    NoopLifecycle

    pub(all) struct NoopLifecycle {
    }

    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

    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

    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

    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

    RecordingToolProvider::ops

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

    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

    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

    Direct streaming entry point for testkit self-tests.

    ScriptedModel::new

    ScriptedModel::options_received

    Snapshot of all chat options received, in call order.

    ScriptedModelStep

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

    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.

    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.

    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.

    ToolProviderOp

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

    Unified provider operation trace, preserving list/execute interleaving.

    ToolRegistry

    Dynamic runtime tool registration. Implements ToolProvider.

    ToolRegistry::new

    ToolRegistry::unregister

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

    ToolRouting

    type ToolRouting

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

    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

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

    canonical_to_legacy_message

    Convert a canonical message to the legacy @types.Message the @port.ModelPort expects. Inverse of legacy_to_completion for assistant payloads.

    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.

    legacy_to_completion

    Convert legacy @types.ModelResponse → canonical @kernel.AssistantCompletion. Tool calls and reasoning are read from the inner Message (the single source of truth in canonical form); the duplicated top-level fields are ignored.

    model_error_to_failure

    Convert legacy @error.ModelError → canonical @kernel.ModelFailure. No error is collapsed to a default; each variant preserves its category.

    outcome_to_legacy

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

    Convert canonical @kernel.ToolOutcome → (legacy content, legacy is_error). Used when feeding outcomes back to legacy observers/session save.

    outcome_to_legacy_tool_result

    Convert a canonical @kernel.ToolOutcome → legacy @types.ToolResult. The is_error boolean is derived from the outcome variant — never hardcoded (REPAIR M0-T06-A single-source rule).

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

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