# model-harness-framework **Repository Path**: twc_space/model-harness-framework ## Basic Information - **Project Name**: model-harness-framework - **Description**: java ai harness 框架 - **Primary Language**: Java - **License**: Apache-2.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2026-11-26 - **Last Updated**: 2026-11-26 ## Categories & Tags **Categories**: Uncategorized **Tags**: AI, Harness, Java, Agent ## README # model-harness-framework > A Java 21 model-driven agent harness: event-based I/O, built-in ReAct loop, flow orchestration graphs, pluggable providers, and a unified single-node / cluster runtime. `model-harness-framework` separates **how an agent runs** from **how a business integrates with it**. Agents only emit events; the orchestration layer handles routing, dispatching, persistence and resume; channel layers simply subscribe. The core modules have no Spring dependency and can be used as a plain Java library. Spring Boot applications can pull in a starter for auto-configuration. --- ## Features - **Event-driven** — `Agent#run` returns a `Flux`. Every action (text, tool call, question, sub-task, token usage, lifecycle) is emitted through `RunEventPublisher`; the orchestration layer subscribes and publishes each event to the `EventBus`. - **Built-in ReAct loop** — think → tool call → observe → think again, with streaming output, iteration limits, duplicate-tool detection and cooperative cancellation. - **Flow orchestration graphs** — directed graphs of `AGENT` / `ACTION` / `END` nodes with conditional edges, cycles, LLM routing, error policies, checkpoint resume and re-run from a node. - **Five provider SPIs** — Skill, Knowledge, Prompt, Vector and Cache can each be composed from `file / db / network / classpath / local / redis` sources in configured order. - **Multi-agent collaboration** — `sub_agent` dispatch (sync or async) with results injected back into the parent ReAct loop. - **Conversation memory** — recent-message injection plus LLM summary compression (`CompressService`), with pause / resume for follow-up questions. - **Skill accumulation** — save run experience as Skill / Knowledge and export `SKILL.md` / `EXPERTISE.md`. - **Single-node or cluster** — in-process event bus and local lock by default; add the cluster starter to switch to Redis pub/sub + Redisson locks without changing business code. - **Spring-free core** — `core`, `runtime` and `orchestration` do not depend on Spring. --- ## Modules ``` model-harness-framework/ ├── model-harness-core # Contracts: interfaces, events, domain records, SPIs ├── model-harness-runtime # Runtime: ReAct, flow execution, event bus, providers, sub-agents ├── model-harness-orchestration # Orchestration: routing, orchestrator, pending-input retry └── spring-boot-starter-model-harness-parent/ ├── spring-boot-starter-model-harness # Auto-configuration (default single-node) ├── spring-boot-starter-model-harness-anthropic # Spring AI / Anthropic model adapter └── spring-boot-starter-model-harness-cluster # Redis + Redisson cluster implementation ``` | Module | Maven coordinates | Responsibility | |--------|-------------------|----------------| | core | `io.model.harness:model-harness-core` | `Agent`, `AgentContext`, `AgentDescriptor`, events, `EventBus`, `LlmClient`, `FlowDefinition`, `ToolSpec`, Store / Provider SPIs | | runtime | `io.model.harness:model-harness-runtime` | `ReactAgent`, `AgentRunner`, `FlowExecutor` / `FlowRunner`, `DefaultEventBus`, file/network providers, `SubAgentDispatcher`, memory compression, metrics & persistence subscribers | | orchestration | `io.model.harness:model-harness-orchestration` | `AgentOrchestrator`, `Router` / `CompositeRouter`, `PendingInputRetrier` | | starter | `io.model.harness:spring-boot-starter-model-harness` | Wires all framework beans; provides single-node event bus / local lock / file providers / skill export | | anthropic | `io.model.harness:spring-boot-starter-model-harness-anthropic` | Adapts Spring AI `ChatModel` to `LlmClient` and bridges tool schemas | | cluster | `io.model.harness:spring-boot-starter-model-harness-cluster` | `ClusterEventBus`, `RedissonLock`, `ClusterRunCoordinator`; overrides single-node beans | --- ## Core concepts | Concept | Description | |---------|-------------| | `Agent` | Smallest runnable unit. `descriptor()` describes it; `run(ctx)` returns an event stream. | | `AgentDescriptor` | Metadata: name, `expertType`, description, Skill/Expertise/Tool allow-lists, prompt key, max iterations. | | `AgentContext` | Per-run context: session, trace, user, input, channel, model, memory summary, recent messages, cancellation flag. | | `RunEventPublisher` | Event outlet for one run, wrapping a `Sinks.Many`; shared by agents and flows. | | `EventBus` | Per-session, single-threaded FIFO dispatch. Subscribers persist, push, summarize or meter events. | | `LlmClient` | Model SPI (sync / streaming / tool execution), isolating the concrete model implementation. | | `Provider` | Read/write abstraction for Skill/Knowledge/Prompt/Vector/Cache; multiple sources compose. | | `FlowDefinition` | Graph definition: nodes + conditional edges, produced by a code DSL or page JSON. | ### Execution path ```mermaid sequenceDiagram participant C as Channel / Business participant EB as EventBus participant O as AgentOrchestrator participant R as AgentRunner participant A as Agent (ReAct) participant S as Subscribers C->>EB: publish ChannelReceivedEvent EB->>O: onChannelReceived O->>O: prepare session / resume check / route O->>R: run(ctx, agent) R->>A: run(ctx) A-->>R: Flux (streaming) R->>EB: publish each event EB->>S: persistence / SSE push / metrics C->>EB: publish AgentCancelRequestEvent (optional) EB->>R: cooperative cancellation ``` 1. An external channel wraps user input in a `ChannelReceivedEvent` and publishes it to the `EventBus`. 2. `AgentOrchestrator` persists the session, generates a title, checks for resumable state, routes the intent, and selects an Agent or Flow. 3. `AgentRunner` executes `Agent#run` on a worker pool and forwards every event to the `EventBus`. 4. Subscribers (persistence, SSE channel, metrics, logging) consume events. On failure, any non-`default` agent automatically falls back to the `default` agent. 5. `ask_user` pauses the run and stores a snapshot; the next user message resumes the same Agent / Flow. --- ## Requirements | Tool | Version | |------|---------| | JDK | 21+ | | Maven | 3.9+ | | Redis | 6+ (cluster mode only) | | Spring Boot | 4.2.x (starter modules only) | | Spring AI | 2.1.x (anthropic module only) | --- ## Build ```bash git clone https://gitee.com/twc_space/mode-harness.git cd model-harness-framework mvn clean install ``` After installation, applications can depend on `io.model.harness:*:1.0-SNAPSHOT`. > Non-Spring projects can depend on `model-harness-core` + `model-harness-runtime` + `model-harness-orchestration`, implement `LlmClient` and the stores, and wire the components manually. --- ## Quick start (Spring Boot) ### 1. Add dependencies ```xml io.model.harness spring-boot-starter-model-harness 1.0-SNAPSHOT io.model.harness spring-boot-starter-model-harness-anthropic 1.0-SNAPSHOT ``` ### 2. Implement the required stores The framework defines contracts only. Applications must provide these three beans, otherwise startup fails with `缺少 XxxStore 实现 Bean`: | Bean | Purpose | |------|---------| | `ConversationStore` | Conversations, messages, summaries, titles, metadata | | `TaskStateStore` | Pending tasks and paused state | | `FlowStateStore` | Flow checkpoints | ```java @Configuration public class HarnessStoreConfig { @Bean ConversationStore conversationStore(MyConversationMapper mapper) { return new DbConversationStore(mapper); } @Bean TaskStateStore taskStateStore(MyTaskStateMapper mapper) { return new DbTaskStateStore(mapper); } @Bean FlowStateStore flowStateStore(MyFlowStateMapper mapper) { return new DbFlowStateStore(mapper); } } ``` ### 3. Configuration ```yaml spring: ai: anthropic: api-key: ${LLM_API_KEY} base-url: ${LLM_BASE_URL} chat: options: model: deepseek-v4-flash max-tokens: 8192 agent-harness: eventbus: session-idle-seconds: 300 # Idle session executor reclaim time providers: skill: file,db # Comma-separated, composed in order knowledge: file,db prompt: classpath,db cache: local vector: local skill-file-dir: data/skills knowledge-file-dir: data/expertise prompt-file-dir: data/prompts skill-save: db # Accumulation target; defaults if omitted knowledge-save: db accumulate: enabled: true export-dir: export cluster: # Cluster mode only channel: harness:events key-prefix: "harness:" run-lock-ttl: 30s agent: sub-agent: timeout-seconds: 600 model-catalog: # Models selectable in the UI default-id: deepseek-v4-flash models: - id: deepseek-v4-flash label: DeepSeek V4 Flash model: deepseek-v4-flash prompt-per-1k: 0.00004 completion-per-1k: 0.008 ``` > `agent-harness.eventbus.type` is kept only for backward compatibility and no longer selects an implementation. Single-node vs cluster is determined by whether the cluster starter is on the classpath. ### 4. Define an agent **Option A: YAML** (place under `src/main/resources/agents/*.yaml`) ```yaml name: Requirements Analyst expertType: req-analyst description: Breaks user requirements into executable tasks example: Analyze this requirement for me prompt: | You are a senior requirements analyst. Clarify the goal first, then produce a task breakdown. skills: - req-analysis expertises: - accounting-domain tools: - get_weather ``` **Option B: a code bean** ```java @Component public class ReqAnalystAgent extends ReactAgent { public ReqAnalystAgent(LlmClient llm, ToolRegistry tools, SkillProvider skills, KnowledgeProvider knowledge, PromptProvider prompts) { super(AgentDescriptor.of( "Requirements Analyst", "req-analyst", "Breaks requirements into executable tasks", "Analyze this requirement for me", List.of("req-analysis"), List.of("accounting-domain"), List.of(), "req-analyst"), llm, tools, skills, knowledge, prompts); } } ``` `tools` in `AgentDescriptor` is an allow-list: only tools available from `ToolCatalog` **and** listed here are exposed to the model. ### 5. Add a business tool ```java public record WeatherArgs( @JsonPropertyDescription("City name, e.g. Hangzhou") String city) { } @Configuration public class ToolConfig { @Bean ToolCatalog toolCatalog() { ToolSpec weather = ToolSpec.typed( "get_weather", "Get the weather for a city", WeatherArgs.class, (WeatherArgs args) -> args.city() + ": sunny, 26°C"); return new ToolCatalog() { @Override public ToolSpec get(String name) { return "get_weather".equals(name) ? weather : null; } @Override public List names() { return List.of("get_weather"); } }; } } ``` ### 6. Trigger a conversation A channel only needs to publish `ChannelReceivedEvent` and subscribe to reply / message events: ```java @Service public class ChatGateway { private final EventBus eventBus; public ChatGateway(EventBus eventBus) { this.eventBus = eventBus; // Final answer eventBus.subscribe(AgentMessageEvent.class, e -> { if (e.kind() == AgentMessageEvent.MessageKind.FULL) { System.out.println("[assistant] " + e.text()); } }); // Follow-up question / notice eventBus.subscribe(ChannelReplyEvent.class, e -> System.out.println("[reply] " + e.text())); } public void chat(String sessionId, String userId, String input) { eventBus.publish(new ChannelReceivedEvent( sessionId, UUID.randomUUID().toString(), null, Instant.now(), "web", userId, input, null)); } public void cancel(String sessionId) { eventBus.publish(new AgentCancelRequestEvent( sessionId, UUID.randomUUID().toString(), null, Instant.now(), "user_cancel")); } } ``` Common events: | Event | Description | |-------|-------------| | `AgentMessageEvent` | `CHUNK` streaming delta / `FULL` final answer | | `AgentToolCallEvent` / `AgentToolResultEvent` | Tool invocation and result | | `AgentStepEvent` | Step progress (running / done) | | `AgentAskUserEvent` | Follow-up question and structured questions | | `AgentLifecycleEvent` | `STARTED` / `COMPLETED` / `PAUSED` / `FAILED` / `CANCELLED` | | `AgentTokenUsageEvent` | Token usage of a single LLM call | | `ChannelReplyEvent` | Text sent back to the channel by the orchestrator | | `FlowNodeEvent` / `FlowEdgeEvent` | Flow node and edge progress | --- ## Flow orchestration A flow describes a process with nodes and edges. `AGENT` nodes invoke registered agents, `ACTION` nodes execute Java actions, and `END` nodes terminate. ### Code DSL ```java @Configuration public class FlowConfig { @Bean FlowDefinitionProvider triageFlow() { return new FlowDefinitionProvider() { @Override public String source() { return "code"; } @Override public int order() { return 0; // Lower loads first; same expertType is overridden later } @Override public List load() { FlowGraphBuilder graph = FlowDefinition.graph("triage", "Issue triage"); graph.maxSteps(50); graph.addAgentNode("classify", "Classify", "classifier"); graph.addActionNode("record", "Record ticket", "record.ticket"); graph.addAgentNode("answer", "Answer directly", "assistant"); graph.addEndNode("end", "End"); graph.setStartPoint("classify"); // Condition variables: input / constraint / channel / user / // var. / node..output / visit. / input.length graph.addEdge("classify", "record") .when(Rules.contains("node.classify.output", "bug")); graph.addEdge("classify", "answer"); // Unconditional edge = default branch graph.addEdge("record", "end"); graph.addEdge("answer", "end"); return List.of(graph.build()); } }; } } ``` An `ACTION` node maps to a `FlowAction` bean: ```java @Component public class RecordTicketAction implements FlowAction { @Override public String key() { return "record.ticket"; } @Override public String label() { return "Record ticket"; } @Override public FlowNodeResult execute(FlowActionContext ctx) { // Business logic; return FlowNodeResult.pause(...) when user input is needed return FlowNodeResult.ok("Ticket created"); } } ``` ### Edge conditions | Form | Semantics | |------|-----------| | `addEdge(from, to)` | Default edge, taken when no other outgoing edge matches | | `.when(Rules.var("key", "value"))` | Taken when the variable matches | | `.when(Rules.contains("node.x.output", "text"))` | Taken when a node output contains text | | `.llm(prompt)` | The model selects among candidate outgoing edges | | `.priority(n)` | Lower numbers are evaluated first; default 100 | ### Page / JSON definitions `FlowDefinition` can be serialized to the page-canvas JSON via `FlowDefinitionJson`. Implement `FlowDefinitionProvider` (`source = "database"`, `order = 100`) to let database definitions override code definitions for the same `expertType`. --- ## Extension points | SPI | Purpose | Required | |-----|---------|----------| | `ConversationStore` | Conversation and message persistence | ✅ | | `TaskStateStore` | Pending task / paused state | ✅ | | `FlowStateStore` | Flow checkpoints | ✅ | | `ToolCatalog` | Business tool catalog | Optional | | `AgentLoader` | Additional agent sources (DB, etc.) | Optional | | `Router` | Intent routing; multiple routers form a chain ordered by `order()` | Optional | | `FlowDefinitionProvider` | Code / database flow definitions | Optional | | `FlowAction` | Logic for `ACTION` nodes | Optional | | `FlowInputBuilder` | Dynamic input for `AGENT` nodes | Optional | | `FlowRouteDecider` | Edge routing decisions | Optional | | `SkillProvider` / `KnowledgeProvider` / `PromptProvider` / `VectorProvider` / `CacheProvider` | Capability sources | Optional | | `SkillExporter` | Accumulation export | Optional (provided by default modules) | | `LlmClient` | Model access | Provided by the anthropic starter | All extension points are picked up as Spring beans. The framework supplies core fallbacks; business beans take precedence. Agent sources load in the order code → YAML → DB, with later sources overriding earlier ones. --- ## Single-node vs cluster | Capability | Single-node (default starter) | Cluster (+ cluster starter) | |------------|-------------------------------|-----------------------------| | Event bus | `DefaultEventBus` (in-process) | `ClusterEventBus` (Redis pub/sub) | | Distributed lock | `DefaultLock` (local) | `RedissonLock` | | Run coordination | `DefaultRunCoordinator` | `ClusterRunCoordinator` (run lock) | | Skill export | `FileSkillExporter` | `NoopSkillExporter` (DB is the only store) | | Provider chain | Composed from config | Mutable data forced to DB (`prompt=db,classpath`; `cache`/`vector` kept from config) | Cluster-specific configuration: ```yaml agent-harness: cluster: instance-id: node-a # Defaults to a startup UUID channel: harness:events key-prefix: "harness:" run-lock-ttl: 30s max-payload-bytes: 262144 ``` > Cluster mode requires working Redis connection configuration (`spring.data.redis.*` or `redis.primary.*`). --- ## Project layout ``` model-harness-core/src/main/java/io/model/harness/core/ ├── Agent.java / AgentContext.java / AgentDescriptor.java ├── ConversationManager.java / ConversationStore.java / ResumeState.java ├── accumulate/ # Skill export ├── config/ # AgentHarnessProperties ├── eventbus/ # Event definitions, EventBus, filters, subscriptions ├── flow/ # FlowDefinition, nodes, edges, DSL, Store SPI ├── gateway/ # Channel ├── llm/ # LlmClient, messages, options, model catalog ├── load/ # AgentConfig, AgentLoader ├── lock/ # Lock SPI ├── orchestration/ # RunCoordinator, TaskStateManager ├── provider/ # Skill / Knowledge / Prompt / Vector / Cache SPI ├── subtask/ # SubTaskInbox └── tool/ # AgentTool, ToolSpec, ToolCatalog ``` --- ## Testing ```bash mvn test ``` Coverage focus: - `model-harness-core` — context derivation, resume snapshots, locks, run coordination - `model-harness-runtime` — ReAct loop, flow execution and resume, event bus, provider composition, tool registry - `model-harness-orchestration` — routing, dispatch, cancellation, fallback, sub-agent progress - `spring-boot-starter-*` — auto-configuration contracts, cluster codec / lock / event bus --- ## Contributing 1. Fork the repository 2. Create a `Feat_xxx` branch 3. Commit your changes with tests 4. Open a Pull Request --- ## License [Apache License 2.0](./LICENSE)