LLM Agent framework with hexagonal (ports-and-adapters) architecture. Defines 9 traits + Agent loop. Depends on moonbitlang/async.
| Port | 职责 |
|---|---|
| ModelPort | 普通或流式模型调用 |
| ToolProvider | 工具发现与执行 |
| SessionStore | session 加载与保存 |
| Observer | 只读 turn event 观察 |
| Compressor | 每轮模型调用前返回压缩指令 |
| PipelineHook | 修改、延迟或中止 pipeline stage |
| MemoryPort | 长期记忆存储与检索 |
| Lifecycle | async 资源清理 |
| CommandPort | 用户侧命令枚举与调用 |
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")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 等rtk moon check --target native --output-json
rtk moon test --target native --output-json
rtk moon fmt
rtk moon infopub(open) trait CommandPort {
fn commands(Self) -> Array[CommandDef]
async fn invoke(Self, id : String, args : Json) -> CommandOutcome raise CommandError
}pub(open) trait Compressor {
fn compress(Self, messages : Array[Message], ctx : CompressContext) -> CompressAction
}pub(open) trait Lifecycle {
async fn on_shutdown(Self) -> Unit
}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
}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 = _
}pub(open) trait SessionStore {
async fn load(Self, id : String) -> Result[Session, SessionError]
async fn save(Self, id : String, session : Session) -> Result[Unit, SessionError]
}pub(open) trait ToolProvider {
fn list_tools(Self) -> Array[ToolDef]
async fn execute(Self, name : String, call : ToolCall) -> ToolResult raise RuntimeError
}pub(all) suberror AgentError {
Model(String)
Session(SessionError)
Runtime(RuntimeError)
ToolLoopExceeded
HookAborted(String)
} derive(Debug)impl Show for AgentErrorpub(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
}impl Show for CatalogCompositionErrorpub(all) suberror CommandError {
NotFound(String)
InvalidArgs(reason~ : String)
ExecutionFailed(String)
} derive(Debug)impl Show for CommandErrorimpl Show for CompositionErrorpub(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)
}impl Show for KernelErrorpub(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)
}impl Show for KernelFacadeErrorpub(all) suberror ModelError {
RequestBuild(String)
Transport(String)
ResponseParse(String)
} derive(Debug)impl Show for ModelErrorpub(all) suberror RuntimeError {
UnknownTool(String)
InvocationFailed(String)
Transport(String)
} derive(Debug)impl Show for RuntimeErrorpub(all) suberror SchedulingError {
DuplicateCallId(call_id~ : CallId)
UnknownToolReachedScheduler(call_id~ : CallId, name~ : ToolName)
StaleSnapshotVersion(expected~ : CatalogVersion, actual~ : CatalogVersion)
}impl Show for SchedulingErrorpub(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
}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 CompositionErrorasync fn Agent::run_turn(self : Agent, input : Message, session_id : String) -> TurnResult raise AgentErrorasync fn Agent::run_turn_via_kernel(self : Agent, input : Message, session_id : String) -> TurnResult raise KernelFacadeErrorpub(all) struct AgentConfig {
max_tool_rounds : Int
temperature : Double?
max_output_tokens : Int?
tool_choice : ToolChoice?
reasoning_effort : ReasoningEffort?
model_context_window : Int?
}pub(all) struct AssistantCompletion {
message : AssistantMessagePayload
usage : CanonicalUsage?
} derive(Eq, Debug)fn AssistantCompletion::new(content~ : Array[CanonicalContent], tool_calls~ : Array[CanonicalToolCall], reasoning~ : Reasoning?, finish_reason~ : AssistantFinishReason, usage~ : CanonicalUsage?) -> AssistantCompletionimpl Show for AssistantFinishReasonpub(all) struct AssistantMessagePayload {
content : Array[CanonicalContent]
tool_calls : Array[CanonicalToolCall]
reasoning : Reasoning?
finish_reason : AssistantFinishReason
} derive(Eq, Debug)impl Show for BudgetDimensionpub(all) struct BudgetExhaustedPayload {
dimension : BudgetDimension
consumed : Int
limit : Int
} derive(Eq, Debug)pub enum BudgetState {
WithinBudget
Exceeded(BudgetDimension)
UnknownUsage(BudgetDimension)
} derive(Eq, Debug)impl Show for BudgetStatepub(all) struct CallModelPayload {
model_step_id : ModelStepId
messages : Array[CanonicalMessage]
catalog_version : CatalogVersion
call_options : Json
} derive(Eq, Debug)impl Show for CancelDispositionpub(all) struct CancelOutstandingPayload {
effect_ids : Array[EffectId]
reason : CancelReason
} derive(Eq, Debug)impl Show for CancelReasonimpl Show for CanonicalContentpub(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)impl Show for CanonicalToolCallimpl Show for CanonicalToolDeffn CanonicalToolDef::new(name~ : ToolName, description~ : String, input_schema~ : Json, owner~ : OwnerId, policy~ : ExecutionPolicy, provenance~ : String?) -> CanonicalToolDeffn CanonicalTranscript::append(self : CanonicalTranscript, message : CanonicalMessage) -> CanonicalTranscriptfn CanonicalTranscript::append_all(self : CanonicalTranscript, messages : Array[CanonicalMessage]) -> CanonicalTranscriptimpl Show for CanonicalUsageimpl Show for CatalogVersionpub(all) struct ChatOptions {
temperature : Double?
max_output_tokens : Int?
tool_choice : ToolChoice?
reasoning_effort : ReasoningEffort?
} derive(Eq, Debug)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)impl ToolProvider for CompositeToolProviderasync fn execute(_self : CompositeToolProvider, name : String, _call : ToolCall) -> ToolResult raise RuntimeErrorimpl Show for DriverSteppub(all) struct DriverTrace {
steps : Array[DriverStep]
events : Array[KernelEvent]
final_state : RunState
} derive(Debug)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)pub(all) struct ExecuteToolPayload {
model_step_id : ModelStepId
call_id : CallId
tool_name : ToolName
arguments : Json
owner : OwnerId
catalog_version : CatalogVersion
} derive(Eq, Debug)impl Show for ExecutionPlanimpl Show for ExecutionPolicypub(all) struct ExecutionWave {
calls : Array[CanonicalToolCall]
policies : Array[ExecutionPolicy]
} derive(Eq, Debug)impl Show for ExecutionWavepub(all) enum FailureReason {
ModelParseFailure(detail~ : String)
ModelTransport(detail~ : String)
ModelRuntime(detail~ : String)
InvariantViolation(category~ : InvariantCategory)
BudgetExhausted(dimension~ : BudgetDimension)
DeadlineReached
} derive(Eq, Debug)impl Show for FailureReasonpub(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)impl Show for InvariantCategorypub(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)impl Show for KernelEventpub(all) struct ModelCompletedPayload {
effect_id : EffectId
model_step_id : ModelStepId
completion : AssistantCompletion
} derive(Eq, Debug)pub(all) struct ModelFailedPayload {
effect_id : EffectId
model_step_id : ModelStepId
failure : ModelFailure
} derive(Eq, Debug)impl Show for ModelFailureimpl Show for ModelStepIdpub(all) struct NoopCommandPort {
}impl CommandPort for NoopCommandPortasync fn invoke(_self : NoopCommandPort, id : String, _args : Json) -> CommandOutcome raise CommandErrorpub(all) struct NoopCompressor {
}impl Compressor for NoopCompressorfn compress(_self : NoopCompressor, _messages : Array[Message], _ctx : CompressContext) -> CompressActionpub(all) struct NoopHook {
}impl Show for NotExecutedReasonpub(all) struct RecordingHook {
records : Array[HookRecord]
abort_on : Map[String, String]
defer_on : Map[String, String]
}impl PipelineHook for RecordingHookimpl Observer for RecordingObserverimpl SessionStore for RecordingSessionStoreasync fn save(self : RecordingSessionStore, id : String, session : Session) -> Result[Unit, SessionError]fn RecordingSessionStore::fail_load(self : RecordingSessionStore, id : String, err : SessionError) -> Unitfn RecordingSessionStore::save_snapshots(self : RecordingSessionStore) -> Array[(String, Map[String, Json])]fn RecordingSessionStore::seed(self : RecordingSessionStore, id : String, session : Session) -> Unitpub(all) struct RecordingToolProvider {
tool_defs : Array[ToolDef]
outcomes : Map[String, ScriptedToolOutcome]
list_calls : Int
exec_records : Array[ToolExecRecord]
ops : Array[ToolProviderOp]
}impl ToolProvider for RecordingToolProviderasync fn execute(self : RecordingToolProvider, name : String, call : ToolCall) -> ToolResult raise RuntimeErrorasync fn RecordingToolProvider::execute_direct(self : RecordingToolProvider, name : String, call : ToolCall) -> ToolResult raise RuntimeErrorfn RecordingToolProvider::new(tool_defs : Array[ToolDef], outcomes : Map[String, ScriptedToolOutcome]) -> RecordingToolProviderimpl Show for ReduceOutputpub(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)pub(all) enum RunOutcome {
Completed(final_message~ : CanonicalMessage, tool_results~ : Array[ToolOutcome])
Failed(reason~ : FailureReason)
Cancelled(reason~ : CancelReason)
} derive(Eq, Debug)impl Show for RunOutcomepub 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)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 KernelErrorpub struct RuntimeRegistry {
model_port : &ModelPort
model_id : ModelId
tool_providers : Map[String, &ToolProvider]
}fn RuntimeRegistry::new(model_port : &ModelPort, model_id~ : ModelId, tool_bindings : Array[(OwnerId, &ToolProvider)]) -> RuntimeRegistryimpl Show for SchemaDiagnosticfn ScriptedExecutor::on(self : ScriptedExecutor, effect_id : EffectId, outcome : ScriptedOutcome) -> ScriptedExecutorpub(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]
}impl ModelPort for ScriptedModelasync fn chat(self : ScriptedModel, messages : Array[Message], tools : Array[ToolDef], options : ChatOptions) -> ModelResponse raise ModelErrorasync fn chat_streaming(self : ScriptedModel, messages : Array[Message], tools : Array[ToolDef], options : ChatOptions, on_chunk : (StreamChunk) -> Unit) -> ModelResponse raise ModelErrorasync fn ScriptedModel::chat_direct(self : ScriptedModel, messages : Array[Message], tools : Array[ToolDef], options : ChatOptions) -> ModelResponse raise ModelErrorasync fn ScriptedModel::chat_streaming_direct(self : ScriptedModel, messages : Array[Message], tools : Array[ToolDef], options : ChatOptions, on_chunk : (StreamChunk) -> Unit) -> ModelResponse raise ModelErrorpub(all) enum ScriptedModelStep {
Respond(ModelResponse)
Stream(chunks~ : Array[StreamChunk], response~ : ModelResponse)
Fail(ModelError)
}pub(all) enum ScriptedOutcome {
ScriptedModelCompleted(AssistantCompletion)
ScriptedModelFailed(ModelFailure)
ScriptedToolCompleted(ToolOutcome)
ScriptedToolRuntime(ModelFailure)
ScriptedToolInvariant(InvariantCategory)
}pub(all) enum SessionOp {
OpLoad(id~ : String, result~ : Result[Session, SessionError])
OpSave(id~ : String, metadata~ : Map[String, Json], result~ : Result[Unit, SessionError])
}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)pub(all) struct StartPayload {
initial_messages : Array[CanonicalMessage]
catalog_version : CatalogVersion
} derive(Eq, Debug)pub(all) struct StreamAccumulator {
text : String
reasoning : String
tool_calls : Array[ToolCallBuilder]
finish_reason : FinishReason
usage : Usage?
} derive(Debug)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)pub struct ToolCatalogBuilder {
entries : Array[CatalogEntry]
by_name : Map[String, CatalogEntry]
finished : Bool
}let snapshot = ToolCatalogBuilder::new()
.add(def1)
.add(def2)
.finish(version=CatalogVersion::new(1))fn ToolCatalogBuilder::add(self : ToolCatalogBuilder, def : CanonicalToolDef) -> ToolCatalogBuilder raise CatalogCompositionErrorfn ToolCatalogBuilder::finish(self : ToolCatalogBuilder, version~ : CatalogVersion) -> ToolCatalogSnapshot raise CatalogCompositionErrorpub struct ToolCatalogSnapshot {
version : CatalogVersion
entries : Array[CatalogEntry]
by_name : Map[String, CatalogEntry]
} derive(Eq, Debug)fn ToolCatalogSnapshot::validate_arguments(self : ToolCatalogSnapshot, name : ToolName, arguments : Json) -> Result[Unit, SchemaDiagnostic]pub(all) struct ToolCompletedPayload {
effect_id : EffectId
call_id : CallId
outcome : ToolOutcome
} derive(Eq, Debug)pub(all) struct ToolExecRecord {
requested_name : String
call_id : String
tool_name : String
arguments : Json
outcome : ScriptedToolOutcome
}pub(all) struct ToolFailedPayload {
effect_id : EffectId
call_id : CallId
runtime : ModelFailure?
invariant_failure : InvariantCategory?
} derive(Eq, Debug)impl Show for ToolOutcomepub(all) struct ToolRegistry {
tools : Map[String, ToolDef]
executors : Map[String, (ToolCall) -> ToolResult]
}impl ToolProvider for ToolRegistryasync fn execute(self : ToolRegistry, name : String, call : ToolCall) -> ToolResult raise RuntimeErrorfn ToolRegistry::register(self : ToolRegistry, tool : ToolDef, executor : (ToolCall) -> ToolResult) -> Unittype ToolRoutingpub(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)pub(all) struct TurnResult {
message : Message
tool_results : Array[ToolResult]
final_session_id : String
} derive(Eq, Debug)async fn execute_one(effect : Effect, registry : RuntimeRegistry, on_chunk : (StreamChunk) -> Unit) -> RunInputfn reduce(state : RunState, catalog : ToolCatalogSnapshot, input : RunInput) -> ReduceOutput raise KernelErrorfn run_model_step(state : RunState, catalog : ToolCatalogSnapshot, call_options : Json) -> ReduceOutput raise KernelErrorfn schedule(snapshot : ToolCatalogSnapshot, expected_version : CatalogVersion, calls : Array[CanonicalToolCall]) -> ExecutionPlan raise SchedulingErrorfn scripted_driver_run(initial_state : RunState, catalog : ToolCatalogSnapshot, scripted : ScriptedExecutor, start : StartPayload, max_iterations : Int) -> DriverTrace raise KernelErrorInstall
Download zipLLM Agent framework with hexagonal (ports-and-adapters) architecture. Defines 9 traits + Agent loop. Depends on moonbitlang/async.