Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

refactor: remove tool dialect facade

Steven Enamakeldb41d45ea0d2
diff --git a/crates/openhuman-core/src/agent/README.md b/crates/openhuman-core/src/agent/README.md
index b9106a23a7..bab73f357e 100644
--- a/crates/openhuman-core/src/agent/README.md
+++ b/crates/openhuman-core/src/agent/README.md
@@ -8,7 +8,7 @@ Multi-agent orchestration domain. Owns the LLM tool-calling loop, sub-agent disp
- `pub fn run_subagent` / `pub struct SubagentRunOptions` / `pub enum SubagentRunError` — `harness/subagent_runner/` — execute a hierarchical sub-agent from a parent tool loop.
- `pub struct AgentDefinition` / `pub struct AgentDefinitionRegistry` / `pub enum SandboxMode` / `pub enum ToolScope` — `harness/definition/` (`agent_definition.rs`, `registry.rs`, `source.rs`, `tier.rs`, `execution_spec.rs`, `prompt_source.rs`, `subagents.rs`) — sub-agent archetypes loaded from built-ins + workspace TOML.
- `pub mod harness::fork_context` — task-local parent context for KV-cache reuse.
-- `pub trait ToolDispatcher` / `pub struct ParsedToolCall` / `pub struct ToolExecutionResult` — `tool_dialect.rs` — host conversion for persisted tool-call formats; parsing and rendering come directly from `tinytools_agent`.
+- `tinytools_agent::dialect::ToolDialect` / `tinytools_agent::ParsedToolCall` / `tinytools_agent::dialect::ToolOutcome` — canonical tool-call vocabulary; `message_convert.rs` performs only concrete durable/provider conversions.
- `pub mod triage` (`run_triage`, `apply_decision`, `TriggerEnvelope`, `TriageDecision`, `TriageAction`) — `triage/mod.rs` — classify external triggers, escalate to sub-agents.
- `pub mod prompts::SystemPromptBuilder` — `prompts/` — system-prompt section composer.
- `pub struct ChatMessage` / `pub enum ConversationMessage` / `pub struct ToolResultMessage` — `messages.rs` — transcript wire types; `inference/provider/types.rs::ChatRequest` borrows `&[ChatMessage]` from here.
@@ -43,7 +43,7 @@ Multi-agent orchestration domain. Owns the LLM tool-calling loop, sub-agent disp
| `tools/` | Agent-loop control tools (`ask_clarification`, `delegate`, `delegate_to_personality`, `plan_exit`, `remember_preference`, `save_preference`, `run_workflow`, `todo`, `update_task`), re-exported through `crate::tools` |
| `triage/` | Classifies external `TriggerEnvelope`s and escalates to sub-agents ([README](triage/README.md)) |
-Flat files: `bus.rs` (`agent.run_turn` native request handler), `cost.rs` (`pub(crate)`, per-turn token/cost accounting), `tool_dialect.rs` (host conversion around canonical tool-call parsing/rendering), `error.rs` (typed retryable/permanent loop errors), `hooks.rs` (post-turn self-learning hooks), `host_runtime.rs` (native shell execution backend), `message_convert.rs` (`pub(crate)`, transcript ↔ TinyAgents `Message` conversion), `messages.rs` (transcript types), `multimodal.rs` (attachment handling), `platform_shell.rs` (cross-platform shell selection shared with `host_runtime` and `sandbox::ops`), `progress.rs` (`AgentProgress` channel), `progress_sink.rs` (task-local progress sink for in-process embedders), `stop_hooks.rs` (mid-turn policy halts), `task_board.rs` (per-thread task board over `tinyagents_graph::todos`), `task_session.rs` (`pub(crate)`, task-board runs as conversation threads), `tool_policy.rs` (pre-execution tool-call policy hook), `turn_origin.rs` (task-local trust/routing label read by the approval gate), `turn_workspace.rs` (task-local per-turn filesystem root).
+Flat files: `bus.rs` (`agent.run_turn` native request handler), `cost.rs` (`pub(crate)`, per-turn token/cost accounting), `error.rs` (typed retryable/permanent loop errors), `hooks.rs` (post-turn self-learning hooks), `host_runtime.rs` (native shell execution backend), `message_convert.rs` (`pub(crate)`, transcript/provider conversion), `messages.rs` (transcript types), `multimodal.rs` (attachment handling), `platform_shell.rs` (cross-platform shell selection shared with `host_runtime` and `sandbox::ops`), `progress.rs` (`AgentProgress` channel), `progress_sink.rs` (task-local progress sink for in-process embedders), `stop_hooks.rs` (mid-turn policy halts), `task_board.rs` (per-thread task board over `tinyagents_graph::todos`), `task_session.rs` (`pub(crate)`, task-board runs as conversation threads), `tool_policy.rs` (pre-execution tool-call policy hook), `turn_origin.rs` (task-local trust/routing label read by the approval gate), `turn_workspace.rs` (task-local per-turn filesystem root).
## RPC namespaces owned by this tree
@@ -76,7 +76,7 @@ Flat files: `bus.rs` (`agent.run_turn` native request handler), `cost.rs` (`pub(
## Tests
-- Unit: `agent_tests.rs`, `multimodal_tests.rs`, `dispatcher_tests.rs` (loaded by `tool_dialect.rs`), plus `*_tests.rs` files colocated with `bus.rs`, `cost.rs`, `error.rs`, `hooks.rs`, `host_runtime.rs`, `message_convert.rs`, `platform_shell.rs`, `progress_sink.rs`, `schemas.rs`, `stop_hooks.rs`, `task_board.rs`, `task_session.rs`, `tool_policy.rs`, `turn_origin.rs`, `turn_workspace.rs`, and under `harness/`, `harness/session/`, `triage/`.
+- Unit: `agent_tests.rs`, `multimodal_tests.rs`, and direct TinyTools Agent dialect coverage in `pformat_tests.rs`, plus `*_tests.rs` files colocated with `bus.rs`, `cost.rs`, `error.rs`, `hooks.rs`, `host_runtime.rs`, `message_convert.rs`, `platform_shell.rs`, `progress_sink.rs`, `schemas.rs`, `stop_hooks.rs`, `task_board.rs`, `task_session.rs`, `tool_policy.rs`, `turn_origin.rs`, `turn_workspace.rs`, and under `harness/`, `harness/session/`, `triage/`.
- Integration: `tests/agent_builder_public.rs`, `tests/agent_harness_public.rs`, `tests/agent_harness_e2e.rs`, `tests/agent_multimodal_public.rs`, `tests/agent_turn_overrides_e2e.rs`, `tests/agent_approval_memory_coverage_e2e.rs`.
- Schema regression: `schemas_tests.rs` (`controller_schema_inventory_is_stable`).
diff --git a/crates/openhuman-core/src/agent/agent_dispatch_format_tests.rs b/crates/openhuman-core/src/agent/agent_dispatch_format_tests.rs
deleted file mode 100644
index 4b7f75049d..0000000000
--- a/crates/openhuman-core/src/agent/agent_dispatch_format_tests.rs
+++ /dev/null
@@ -1,523 +0,0 @@
-use super::*;
-
-#[tokio::test]
-async fn system_prompt_not_duplicated_on_second_turn() {
- let provider = Arc::new(ScriptedProvider::new(vec![
- text_response("first"),
- text_response("second"),
- ]));
- let (mut agent, _tmp) = build_agent_with(
- provider,
- vec![Box::new(EchoTool)],
- Box::new(NativeToolDispatcher),
- );
-
- let _ = agent.turn("hi").await.unwrap();
- let _ = agent.turn("hello again").await.unwrap();
-
- let system_count = agent
- .history()
- .iter()
- .filter(|msg| matches!(msg, ConversationMessage::Chat(c) if c.role == "system"))
- .count();
- assert_eq!(system_count, 1, "System prompt should appear exactly once");
-}
-
-// ═══════════════════════════════════════════════════════════════════════════
-// 15. Conversation history fidelity
-// ═══════════════════════════════════════════════════════════════════════════
-
-#[tokio::test]
-async fn history_contains_all_expected_entries_after_tool_loop() {
- let provider = Arc::new(ScriptedProvider::new(vec![
- tool_response(vec![ToolCall {
- id: "tc1".into(),
- name: "echo".into(),
- arguments: r#"{"message": "tool-out"}"#.into(),
- extra_content: None,
- }]),
- text_response("final answer"),
- ]));
-
- let (mut agent, _tmp) = build_agent_with(
- provider,
- vec![Box::new(EchoTool)],
- Box::new(NativeToolDispatcher),
- );
-
- let _ = agent.turn("test").await.unwrap();
-
- // Expected history entries:
- // 0: system prompt
- // 1: user message "test"
- // 2: AssistantToolCalls
- // 3: ToolResults
- // 4: assistant "final answer"
- let history = agent.history();
- assert!(
- history.len() >= 5,
- "Expected at least 5 history entries, got {}",
- history.len()
- );
-
- assert!(matches!(&history[0], ConversationMessage::Chat(c) if c.role == "system"));
- assert!(matches!(&history[1], ConversationMessage::Chat(c) if c.role == "user"));
- assert!(matches!(
- &history[2],
- ConversationMessage::AssistantToolCalls { .. }
- ));
- assert!(matches!(&history[3], ConversationMessage::ToolResults(_)));
- assert!(
- matches!(&history[4], ConversationMessage::Chat(c) if c.role == "assistant" && c.content == "final answer")
- );
-}
-
-// ═══════════════════════════════════════════════════════════════════════════
-// 16. Builder validation
-// ═══════════════════════════════════════════════════════════════════════════
-
-#[tokio::test]
-async fn builder_fails_without_provider() {
- let (mem, _tmp) = make_memory();
- let result = Agent::builder()
- .tools(vec![])
- .memory(mem)
- .tool_dispatcher(Box::new(NativeToolDispatcher))
- .workspace_dir(_tmp.path().to_path_buf())
- .build();
-
- assert!(result.is_err(), "Building without provider should fail");
-}
-
-// ═══════════════════════════════════════════════════════════════════════════
-// 17. Multi-turn conversation maintains context
-// ═══════════════════════════════════════════════════════════════════════════
-
-#[tokio::test]
-async fn multi_turn_maintains_growing_history() {
- let provider = Arc::new(ScriptedProvider::new(vec![
- text_response("response 1"),
- text_response("response 2"),
- text_response("response 3"),
- ]));
-
- let (mut agent, _tmp) = build_agent_with(provider, vec![], Box::new(NativeToolDispatcher));
-
- let r1 = agent.turn("msg 1").await.unwrap();
- let len_after_1 = agent.history().len();
-
- let r2 = agent.turn("msg 2").await.unwrap();
- let len_after_2 = agent.history().len();
-
- let r3 = agent.turn("msg 3").await.unwrap();
- let len_after_3 = agent.history().len();
-
- assert_eq!(r1, "response 1");
- assert_eq!(r2, "response 2");
- assert_eq!(r3, "response 3");
-
- // History should grow with each turn (user + assistant per turn)
- assert!(
- len_after_2 > len_after_1,
- "History should grow after turn 2"
- );
- assert!(
- len_after_3 > len_after_2,
- "History should grow after turn 3"
- );
-}
-
-// ═══════════════════════════════════════════════════════════════════════════
-// 18. Tool call with stringified JSON arguments (common LLM pattern)
-// ═══════════════════════════════════════════════════════════════════════════
-
-#[tokio::test]
-async fn native_dispatcher_handles_stringified_arguments() {
- let dispatcher = NativeToolDispatcher;
- let response = ChatResponse {
- text: Some(String::new()),
- tool_calls: vec![ToolCall {
- id: "tc1".into(),
- name: "echo".into(),
- arguments: r#"{"message": "hello"}"#.into(),
- extra_content: None,
- }],
- usage: None,
- reasoning_content: None,
- };
-
- let (_, calls) = dispatcher.parse_response(&response);
- assert_eq!(calls.len(), 1);
- assert_eq!(calls[0].name, "echo");
- assert_eq!(
- calls[0].arguments.get("message").unwrap().as_str().unwrap(),
- "hello"
- );
-}
-
-// ═══════════════════════════════════════════════════════════════════════════
-// 19. XML dispatcher edge cases
-// ═══════════════════════════════════════════════════════════════════════════
-
-#[test]
-fn xml_dispatcher_handles_nested_json() {
- let response = ChatResponse {
- text: Some(
- r#"<tool_call>
-{"name": "file_write", "arguments": {"path": "test.json", "content": "{\"key\": \"value\"}"}}
-</tool_call>"#
- .into(),
- ),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- };
-
- let dispatcher = XmlToolDispatcher;
- let (_, calls) = dispatcher.parse_response(&response);
- assert_eq!(calls.len(), 1);
- assert_eq!(calls[0].name, "file_write");
- assert_eq!(
- calls[0].arguments.get("path").unwrap().as_str().unwrap(),
- "test.json"
- );
-}
-
-#[test]
-fn xml_dispatcher_handles_empty_tool_call_tag() {
- let response = ChatResponse {
- text: Some("<tool_call>\n</tool_call>\nSome text".into()),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- };
-
- let dispatcher = XmlToolDispatcher;
- let (text, calls) = dispatcher.parse_response(&response);
- assert!(calls.is_empty());
- assert!(text.contains("Some text"));
-}
-
-#[test]
-fn xml_dispatcher_handles_unclosed_tool_call() {
- let response = ChatResponse {
- text: Some("Before\n<tool_call>\n{\"name\": \"shell\"}".into()),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- };
-
- let dispatcher = XmlToolDispatcher;
- let (text, calls) = dispatcher.parse_response(&response);
- // Should not panic; robust parser recovers the JSON tool call.
- assert_eq!(calls.len(), 1);
- assert_eq!(calls[0].name, "shell");
- assert!(text.contains("Before"));
-}
-
-// ═══════════════════════════════════════════════════════════════════════════
-// 20. ConversationMessage serialization round-trip
-// ═══════════════════════════════════════════════════════════════════════════
-
-#[test]
-fn conversation_message_serialization_roundtrip() {
- let messages = vec![
- ConversationMessage::Chat(ChatMessage::system("system")),
- ConversationMessage::Chat(ChatMessage::user("hello")),
- ConversationMessage::AssistantToolCalls {
- text: Some("checking".into()),
- tool_calls: vec![ToolCall {
- id: "tc1".into(),
- name: "shell".into(),
- arguments: "{}".into(),
- extra_content: None,
- }],
- reasoning_content: Some("thinking".into()),
- extra_metadata: Some(serde_json::json!({ "source": "unit-test" })),
- },
- ConversationMessage::ToolResults(vec![ToolResultMessage {
- tool_call_id: "tc1".into(),
- content: "ok".into(),
- }]),
- ConversationMessage::Chat(ChatMessage::assistant("done")),
- ];
-
- for msg in &messages {
- let json = serde_json::to_string(msg).unwrap();
- let parsed: ConversationMessage = serde_json::from_str(&json).unwrap();
-
- // Verify the variant type matches
- match (msg, &parsed) {
- (ConversationMessage::Chat(a), ConversationMessage::Chat(b)) => {
- assert_eq!(a.role, b.role);
- assert_eq!(a.content, b.content);
- }
- (
- ConversationMessage::AssistantToolCalls {
- text: a_text,
- tool_calls: a_calls,
- reasoning_content: a_reasoning,
- extra_metadata: a_extra,
- },
- ConversationMessage::AssistantToolCalls {
- text: b_text,
- tool_calls: b_calls,
- reasoning_content: b_reasoning,
- extra_metadata: b_extra,
- },
- ) => {
- assert_eq!(a_text, b_text);
- assert_eq!(a_calls.len(), b_calls.len());
- assert_eq!(a_reasoning, b_reasoning);
- assert_eq!(a_extra, b_extra);
- }
- (ConversationMessage::ToolResults(a), ConversationMessage::ToolResults(b)) => {
- assert_eq!(a.len(), b.len());
- }
- _ => panic!("Variant mismatch after serialization"),
- }
- }
-}
-
-// ═══════════════════════════════════════════════════════════════════════════
-// 21. Tool dispatcher format_results
-// ═══════════════════════════════════════════════════════════════════════════
-
-#[test]
-fn xml_format_results_includes_status_and_output() {
- let dispatcher = XmlToolDispatcher;
- let results = vec![
- ToolExecutionResult {
- name: "shell".into(),
- output: "file1.txt\nfile2.txt".into(),
- success: true,
- tool_call_id: None,
- },
- ToolExecutionResult {
- name: "file_read".into(),
- output: "Error: file not found".into(),
- success: false,
- tool_call_id: None,
- },
- ];
-
- let msg = dispatcher.format_results(&results);
- let content = match msg {
- ConversationMessage::Chat(c) => c.content,
- _ => panic!("Expected Chat variant"),
- };
-
- assert!(content.contains("shell"));
- assert!(content.contains("file1.txt"));
- assert!(content.contains("ok"));
- assert!(content.contains("file_read"));
- assert!(content.contains("error"));
-}
-
-#[test]
-fn native_format_results_maps_tool_call_ids() {
- let dispatcher = NativeToolDispatcher;
- let results = vec![
- ToolExecutionResult {
- name: "a".into(),
- output: "out1".into(),
- success: true,
- tool_call_id: Some("tc-001".into()),
- },
- ToolExecutionResult {
- name: "b".into(),
- output: "out2".into(),
- success: true,
- tool_call_id: Some("tc-002".into()),
- },
- ];
-
- let msg = dispatcher.format_results(&results);
- match msg {
- ConversationMessage::ToolResults(r) => {
- assert_eq!(r.len(), 2);
- assert_eq!(r[0].tool_call_id, "tc-001");
- assert_eq!(r[0].content, "out1");
- assert_eq!(r[1].tool_call_id, "tc-002");
- assert_eq!(r[1].content, "out2");
- }
- _ => panic!("Expected ToolResults"),
- }
-}
-
-// ═══════════════════════════════════════════════════════════════════════════
-// 22. to_provider_messages conversion
-// ═══════════════════════════════════════════════════════════════════════════
-
-#[test]
-fn xml_dispatcher_converts_history_to_provider_messages() {
- let dispatcher = XmlToolDispatcher;
- let history = vec![
- ConversationMessage::Chat(ChatMessage::system("sys")),
- ConversationMessage::Chat(ChatMessage::user("hi")),
- ConversationMessage::AssistantToolCalls {
- text: Some("checking".into()),
- tool_calls: vec![ToolCall {
- id: "tc1".into(),
- name: "shell".into(),
- arguments: "{}".into(),
- extra_content: None,
- }],
- reasoning_content: None,
- extra_metadata: None,
- },
- ConversationMessage::ToolResults(vec![ToolResultMessage {
- tool_call_id: "tc1".into(),
- content: "ok".into(),
- }]),
- ConversationMessage::Chat(ChatMessage::assistant("done")),
- ];
-
- let messages = dispatcher.to_provider_messages(&history);
-
- // Should have: system, user, assistant (from tool calls), user (tool results), assistant
- assert!(messages.len() >= 4);
- assert_eq!(messages[0].role, "system");
- assert_eq!(messages[1].role, "user");
-}
-
-#[test]
-fn native_dispatcher_converts_tool_results_to_tool_messages() {
- // TAURI-RUST-7: `to_provider_messages` now drops orphan `ToolResults`
- // that aren't preceded by an emitted `AssistantToolCalls`, since the
- // OpenAI chat-completions contract rejects a `tool` message that does
- // not follow a `tool_calls` opener. Feed a properly paired cycle so
- // this test continues to verify the serialisation shape of ToolResults
- // (one `tool` ChatMessage per result) rather than the orphan path.
- let dispatcher = NativeToolDispatcher;
- let history = vec![
- ConversationMessage::AssistantToolCalls {
- text: None,
- tool_calls: vec![
- ToolCall {
- id: "tc1".into(),
- name: "shell".into(),
- arguments: "{}".into(),
- extra_content: None,
- },
- ToolCall {
- id: "tc2".into(),
- name: "shell".into(),
- arguments: "{}".into(),
- extra_content: None,
- },
- ],
- reasoning_content: None,
- extra_metadata: None,
- },
- ConversationMessage::ToolResults(vec![
- ToolResultMessage {
- tool_call_id: "tc1".into(),
- content: "output1".into(),
- },
- ToolResultMessage {
- tool_call_id: "tc2".into(),
- content: "output2".into(),
- },
- ]),
- ];
-
- let messages = dispatcher.to_provider_messages(&history);
- // assistant tool_calls opener + one `tool` message per tool_call_id.
- assert_eq!(messages.len(), 3);
- assert_eq!(messages[0].role, "assistant");
- assert_eq!(messages[1].role, "tool");
- assert_eq!(messages[2].role, "tool");
-}
-
-#[test]
-fn native_dispatcher_drops_standalone_orphan_tool_results() {
- // TAURI-RUST-7 regression: a `ToolResults` without a preceding
- // `AssistantToolCalls` is an invalid wire shape (the provider rejects
- // a `tool` message that doesn't follow a `tool_calls` opener). The
- // dispatcher must drop it before serialising.
- let dispatcher = NativeToolDispatcher;
- let history = vec![ConversationMessage::ToolResults(vec![ToolResultMessage {
- tool_call_id: "tc-orphan".into(),
- content: "stranded".into(),
- }])];
-
- let messages = dispatcher.to_provider_messages(&history);
- assert!(
- messages.is_empty(),
- "standalone ToolResults must be dropped, got {} message(s)",
- messages.len()
- );
-}
-
-// ═══════════════════════════════════════════════════════════════════════════
-// 23. XML tool instructions generation
-// ═══════════════════════════════════════════════════════════════════════════
-
-#[test]
-fn xml_dispatcher_generates_tool_instructions() {
- let tools: Vec<Box<dyn Tool>> = vec![Box::new(EchoTool)];
- let dispatcher = XmlToolDispatcher;
- let instructions = dispatcher.prompt_instructions(&tools);
-
- assert!(instructions.contains("## Tool Use Protocol"));
- assert!(instructions.contains("<tool_call>"));
- assert!(instructions.contains("echo"));
- assert!(instructions.contains("Echoes the input"));
-}
-
-#[test]
-fn native_dispatcher_prompt_instructions_are_protocol_only_not_tool_catalog() {
- let tools: Vec<Box<dyn Tool>> = vec![Box::new(EchoTool)];
- let dispatcher = NativeToolDispatcher;
- let instructions = dispatcher.prompt_instructions(&tools);
- assert!(instructions.contains("## Tool Use Protocol"));
- assert!(instructions.contains("native tool-calling"));
- assert!(
- !instructions.contains("echo"),
- "native dispatcher does not inline tool names/schemas; provider sends tool specs when should_send_tool_specs is true"
- );
-}
-
-// ═══════════════════════════════════════════════════════════════════════════
-// 24. Clear history
-// ═══════════════════════════════════════════════════════════════════════════
-
-#[tokio::test]
-async fn clear_history_resets_conversation() {
- let provider = Arc::new(ScriptedProvider::new(vec![
- text_response("first"),
- text_response("second"),
- ]));
-
- let (mut agent, _tmp) = build_agent_with(provider, vec![], Box::new(NativeToolDispatcher));
-
- let _ = agent.turn("hi").await.unwrap();
- assert!(!agent.history().is_empty());
-
- agent.clear_history();
- assert!(agent.history().is_empty());
-
- // Next turn should re-inject system prompt
- let _ = agent.turn("hello again").await.unwrap();
- assert!(matches!(
- &agent.history()[0],
- ConversationMessage::Chat(c) if c.role == "system"
- ));
-}
-
-// ═══════════════════════════════════════════════════════════════════════════
-// 25. run_single delegates to turn
-// ═══════════════════════════════════════════════════════════════════════════
-
-#[tokio::test]
-async fn run_single_delegates_to_turn() {
- let provider = Arc::new(ScriptedProvider::new(vec![text_response("via run_single")]));
- let (mut agent, _tmp) = build_agent_with(provider, vec![], Box::new(NativeToolDispatcher));
-
- let response = agent.run_single("test").await.unwrap();
- assert!(
- !response.is_empty(),
- "Expected non-empty response from run_single"
- );
-}
diff --git a/crates/openhuman-core/src/agent/agent_tests.rs b/crates/openhuman-core/src/agent/agent_tests.rs
index a232a4ce1e..596454a7f0 100644
--- a/crates/openhuman-core/src/agent/agent_tests.rs
+++ b/crates/openhuman-core/src/agent/agent_tests.rs
@@ -26,9 +26,6 @@
use crate::agent::harness::session::Agent;
use crate::agent::messages::{ChatMessage, ConversationMessage, ToolResultMessage};
-use crate::agent::tool_dialect::{
- NativeToolDispatcher, ToolDispatcher, ToolExecutionResult, XmlToolDispatcher,
-};
use crate::config::AgentConfig;
use crate::inference::provider::{ChatResponse, ToolCall};
use crate::memory::Memory;
@@ -37,6 +34,7 @@ use async_trait::async_trait;
use std::sync::{Arc, Mutex};
use tinyinference_llm::model::{ChatModel, ModelProfile, ModelRequest, ModelResponse};
use tinytools::{Tool, ToolResult};
+use tinytools_agent::dialect::{NativeDialect, ToolDialect, ToolOutcome, XmlDialect};
// ═══════════════════════════════════════════════════════════════════════════
// Test Helpers — Mock Provider, Mock Tool, Mock Memory
@@ -250,7 +248,7 @@ fn make_retaining_memory() -> (Arc<dyn Memory>, tempfile::TempDir) {
fn build_agent_with(
provider: Arc<dyn ChatModel<()>>,
tools: Vec<Box<dyn Tool>>,
- dispatcher: Box<dyn ToolDispatcher>,
+ dispatcher: Box<dyn ToolDialect>,
) -> (Agent, tempfile::TempDir) {
let (mem, tmp) = make_memory();
let agent = Agent::builder()
@@ -275,7 +273,7 @@ fn build_agent_with_memory(
.chat_model(provider)
.tools(tools)
.memory(mem)
- .tool_dispatcher(Box::new(NativeToolDispatcher))
+ .tool_dispatcher(Box::new(NativeDialect))
.workspace_dir(tmp.path().to_path_buf())
.auto_save(auto_save)
.build()
@@ -293,7 +291,7 @@ fn build_agent_with_config(
.chat_model(provider)
.tools(tools)
.memory(mem)
- .tool_dispatcher(Box::new(NativeToolDispatcher))
+ .tool_dispatcher(Box::new(NativeDialect))
.workspace_dir(tmp.path().to_path_buf())
.config(config)
.build()
@@ -333,11 +331,11 @@ fn xml_tool_response(name: &str, args: &str) -> ChatResponse {
}
}
-#[path = "agent_dispatch_format_tests.rs"]
-mod agent_dispatch_format_tests;
#[path = "agent_memory_attribution_tests.rs"]
mod agent_memory_attribution_tests;
#[path = "agent_turn_loop_packed_tool_tests.rs"]
mod agent_turn_loop_packed_tool_tests;
#[path = "agent_turn_loop_tests.rs"]
mod agent_turn_loop_tests;
+#[path = "pformat_tests.rs"]
+mod pformat_tests;
diff --git a/crates/openhuman-core/src/agent/agent_turn_loop_packed_tool_tests.rs b/crates/openhuman-core/src/agent/agent_turn_loop_packed_tool_tests.rs
index cc4a2dd70d..674d920586 100644
--- a/crates/openhuman-core/src/agent/agent_turn_loop_packed_tool_tests.rs
+++ b/crates/openhuman-core/src/agent/agent_turn_loop_packed_tool_tests.rs
@@ -48,7 +48,7 @@ async fn turn_routes_a_bare_packed_tool_call_through_use_skill() {
let mut tools: Vec<Box<dyn Tool>> = vec![Box::new(RecordingPackedTool(ran.clone()))];
crate::tools::toolpacks::append_pack_tools(&mut tools);
- let (mut agent, _tmp) = build_agent_with(provider, tools, Box::new(NativeToolDispatcher));
+ let (mut agent, _tmp) = build_agent_with(provider, tools, Box::new(NativeDialect));
assert!(
!agent
.visible_tool_names_for_test()
diff --git a/crates/openhuman-core/src/agent/agent_turn_loop_tests.rs b/crates/openhuman-core/src/agent/agent_turn_loop_tests.rs
index 3c2024ef11..0e80fdf1aa 100644
--- a/crates/openhuman-core/src/agent/agent_turn_loop_tests.rs
+++ b/crates/openhuman-core/src/agent/agent_turn_loop_tests.rs
@@ -7,11 +7,8 @@ use super::*;
#[tokio::test]
async fn turn_returns_text_when_no_tools_called() {
let provider = Arc::new(ScriptedProvider::new(vec![text_response("Hello world")]));
- let (mut agent, _tmp) = build_agent_with(
- provider,
- vec![Box::new(EchoTool)],
- Box::new(NativeToolDispatcher),
- );
+ let (mut agent, _tmp) =
+ build_agent_with(provider, vec![Box::new(EchoTool)], Box::new(NativeDialect));
let response = agent.turn("hi").await.unwrap();
assert!(
@@ -36,11 +33,8 @@ async fn turn_executes_single_tool_then_returns() {
text_response("I ran the tool"),
]));
- let (mut agent, _tmp) = build_agent_with(
- provider,
- vec![Box::new(EchoTool)],
- Box::new(NativeToolDispatcher),
- );
+ let (mut agent, _tmp) =
+ build_agent_with(provider, vec![Box::new(EchoTool)], Box::new(NativeDialect));
let response = agent.turn("run echo").await.unwrap();
assert!(
@@ -82,7 +76,7 @@ async fn turn_handles_multi_step_tool_chain() {
let (mut agent, _tmp) = build_agent_with(
provider,
vec![Box::new(counting_tool)],
- Box::new(NativeToolDispatcher),
+ Box::new(NativeDialect),
);
let response = agent.turn("count 3 times").await.unwrap();
@@ -166,11 +160,8 @@ async fn turn_handles_unknown_tool_gracefully() {
text_response("I couldn't find that tool"),
]));
- let (mut agent, _tmp) = build_agent_with(
- provider,
- vec![Box::new(EchoTool)],
- Box::new(NativeToolDispatcher),
- );
+ let (mut agent, _tmp) =
+ build_agent_with(provider, vec![Box::new(EchoTool)], Box::new(NativeDialect));
let response = agent.turn("use nonexistent").await.unwrap();
assert!(
@@ -213,7 +204,7 @@ async fn turn_recovers_from_tool_failure() {
let (mut agent, _tmp) = build_agent_with(
provider,
vec![Box::new(FailingTool)],
- Box::new(NativeToolDispatcher),
+ Box::new(NativeDialect),
);
let response = agent.turn("try failing tool").await.unwrap();
@@ -238,7 +229,7 @@ async fn turn_recovers_from_tool_error() {
let (mut agent, _tmp) = build_agent_with(
provider,
vec![Box::new(PanickingTool)],
- Box::new(NativeToolDispatcher),
+ Box::new(NativeDialect),
);
let response = agent.turn("try panicking").await.unwrap();
@@ -254,11 +245,8 @@ async fn turn_recovers_from_tool_error() {
#[tokio::test]
async fn turn_propagates_provider_error() {
- let (mut agent, _tmp) = build_agent_with(
- Arc::new(FailingProvider),
- vec![],
- Box::new(NativeToolDispatcher),
- );
+ let (mut agent, _tmp) =
+ build_agent_with(Arc::new(FailingProvider), vec![], Box::new(NativeDialect));
let result = agent.turn("hello").await;
assert!(result.is_err(), "Expected provider error to propagate");
@@ -383,11 +371,8 @@ async fn xml_dispatcher_parses_and_loops() {
text_response("XML tool completed"),
]));
- let (mut agent, _tmp) = build_agent_with(
- provider,
- vec![Box::new(EchoTool)],
- Box::new(XmlToolDispatcher),
- );
+ let (mut agent, _tmp) =
+ build_agent_with(provider, vec![Box::new(EchoTool)], Box::new(XmlDialect));
let response = agent.turn("test xml").await.unwrap();
assert!(
@@ -399,22 +384,19 @@ async fn xml_dispatcher_parses_and_loops() {
#[tokio::test]
async fn native_dispatcher_sends_tool_specs() {
let provider = Arc::new(ScriptedProvider::new(vec![text_response("ok")]));
- let (mut agent, _tmp) = build_agent_with(
- provider,
- vec![Box::new(EchoTool)],
- Box::new(NativeToolDispatcher),
- );
+ let (mut agent, _tmp) =
+ build_agent_with(provider, vec![Box::new(EchoTool)], Box::new(NativeDialect));
let _ = agent.turn("hi").await.unwrap();
- // NativeToolDispatcher.should_send_tool_specs() returns true
- let dispatcher = NativeToolDispatcher;
+ // NativeDialect.should_send_tool_specs() returns true
+ let dispatcher = NativeDialect;
assert!(dispatcher.should_send_tool_specs());
}
#[tokio::test]
async fn xml_dispatcher_does_not_send_tool_specs() {
- let dispatcher = XmlToolDispatcher;
+ let dispatcher = XmlDialect;
assert!(!dispatcher.should_send_tool_specs());
}
@@ -435,7 +417,7 @@ async fn turn_errors_on_empty_text_response() {
reasoning_content: None,
}]));
- let (mut agent, _tmp) = build_agent_with(provider, vec![], Box::new(NativeToolDispatcher));
+ let (mut agent, _tmp) = build_agent_with(provider, vec![], Box::new(NativeDialect));
let err = agent
.turn("hi")
@@ -456,7 +438,7 @@ async fn turn_errors_on_none_text_response() {
reasoning_content: None,
}]));
- let (mut agent, _tmp) = build_agent_with(provider, vec![], Box::new(NativeToolDispatcher));
+ let (mut agent, _tmp) = build_agent_with(provider, vec![], Box::new(NativeDialect));
let err = agent
.turn("hi")
@@ -489,11 +471,8 @@ async fn turn_preserves_text_alongside_tool_calls() {
text_response("Here are the results"),
]));
- let (mut agent, _tmp) = build_agent_with(
- provider,
- vec![Box::new(EchoTool)],
- Box::new(NativeToolDispatcher),
- );
+ let (mut agent, _tmp) =
+ build_agent_with(provider, vec![Box::new(EchoTool)], Box::new(NativeDialect));
let response = agent.turn("check something").await.unwrap();
assert!(
@@ -550,7 +529,7 @@ async fn turn_handles_multiple_tools_in_one_response() {
let (mut agent, _tmp) = build_agent_with(
provider,
vec![Box::new(counting_tool)],
- Box::new(NativeToolDispatcher),
+ Box::new(NativeDialect),
);
let response = agent.turn("batch").await.unwrap();
@@ -580,11 +559,8 @@ async fn e2e_native_loop_executes_text_fallback_tool_calls_and_persists_history(
text_response("Completed via tool"),
]));
- let (mut agent, _tmp) = build_agent_with(
- provider,
- vec![Box::new(EchoTool)],
- Box::new(NativeToolDispatcher),
- );
+ let (mut agent, _tmp) =
+ build_agent_with(provider, vec![Box::new(EchoTool)], Box::new(NativeDialect));
let response = agent.turn("please use a tool").await.unwrap();
assert_eq!(response, "Completed via tool");
@@ -627,11 +603,8 @@ async fn e2e_native_loop_executes_text_fallback_tool_calls_and_persists_history(
#[tokio::test]
async fn system_prompt_injected_on_first_turn() {
let provider = Arc::new(ScriptedProvider::new(vec![text_response("ok")]));
- let (mut agent, _tmp) = build_agent_with(
- provider,
- vec![Box::new(EchoTool)],
- Box::new(NativeToolDispatcher),
- );
+ let (mut agent, _tmp) =
+ build_agent_with(provider, vec![Box::new(EchoTool)], Box::new(NativeDialect));
assert!(agent.history().is_empty(), "History should start empty");
diff --git a/crates/openhuman-core/src/agent/context/README.md b/crates/openhuman-core/src/agent/context/README.md
index 4d15738581..c54cba3c03 100644
--- a/crates/openhuman-core/src/agent/context/README.md
+++ b/crates/openhuman-core/src/agent/context/README.md
@@ -81,7 +81,7 @@ The durable substrate session-memory targets is the workspace `MEMORY.md` file,
- **`agent::tinyagents`** — `harness_assembly.rs` reads `CLEARED_PLACEHOLDER` when configuring `MicrocompactMiddleware`; `payload_summarizer.rs` and `host/context_composer.rs` build `PromptContext`s through `agent::prompts`.
- **`agent::registry::agents/*/prompt.rs`**, `flows/agents/*/prompt.rs`, `memory/agent/agent/prompt.rs`, `skills/*/agent/*/prompt.rs` — archetype prompt modules pull prompt sections/builder through `agent::prompts`.
- **`channels`** — `channels/system_prompt.rs` (`ChannelSystemPrompt`, used by `channels/runtime/startup/start_channels.rs`) calls `channels_prompt::build_system_prompt_with_identity`; `channels/mod.rs` re-exports `build_system_prompt`; the `channels/tests/*` prompt/identity tests call it directly.
-- **`agent::tool_dialect`, `agent::triage`, `agent::debug`, `agent::orchestration::tools` (spawn_subagent and friends), `agent::learning::prompt_sections`, `agent::profiles::prompt_section`, `memory::tool_memory::prompt`, `tools::orchestrator_tools`, `integrations::composio`** — consume prompt types (`PromptContext`, `PromptSection`, `ToolCallFormat`, `ConnectedIntegration`, …) via `agent::prompts`.
+- **`agent::triage`, `agent::debug`, `agent::orchestration::tools` (spawn_subagent and friends), `agent::learning::prompt_sections`, `agent::profiles::prompt_section`, `memory::tool_memory::prompt`, `tools::orchestrator_tools`, `integrations::composio`** — consume prompt types (`PromptContext`, `PromptSection`, `ToolCallFormat`, `ConnectedIntegration`, …) via `agent::prompts`.
- **`config::schema`** — `context.rs` embeds `SessionMemoryConfig`.
## Notes / gotchas
diff --git a/crates/openhuman-core/src/agent/dispatcher_tests.rs b/crates/openhuman-core/src/agent/dispatcher_tests.rs
deleted file mode 100644
index abdf6064cb..0000000000
--- a/crates/openhuman-core/src/agent/dispatcher_tests.rs
+++ /dev/null
@@ -1,687 +0,0 @@
-use super::*;
-use tinytools_agent::PFormatToolParams;
-
-#[test]
-fn xml_dispatcher_parses_tool_calls() {
- let response = ChatResponse {
- text: Some(
- "Checking\n<tool_call>{\"name\":\"shell\",\"arguments\":{\"command\":\"ls\"}}</tool_call>"
- .into(),
- ),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- };
- let dispatcher = XmlToolDispatcher;
- let (_, calls) = dispatcher.parse_response(&response);
- assert_eq!(calls.len(), 1);
- assert_eq!(calls[0].name, "shell");
-}
-
-#[test]
-fn native_dispatcher_roundtrip() {
- let response = ChatResponse {
- text: Some("ok".into()),
- tool_calls: vec![crate::inference::provider::ToolCall {
- id: "tc1".into(),
- name: "file_read".into(),
- arguments: "{\"path\":\"a.txt\"}".into(),
- extra_content: None,
- }],
- usage: None,
- reasoning_content: None,
- };
- let dispatcher = NativeToolDispatcher;
- let (_, calls) = dispatcher.parse_response(&response);
- assert_eq!(calls.len(), 1);
- assert_eq!(calls[0].tool_call_id.as_deref(), Some("tc1"));
-
- let msg = dispatcher.format_results(&[ToolExecutionResult {
- name: "file_read".into(),
- output: "hello".into(),
- success: true,
- tool_call_id: Some("tc1".into()),
- }]);
- match msg {
- ConversationMessage::ToolResults(results) => {
- assert_eq!(results.len(), 1);
- assert_eq!(results[0].tool_call_id, "tc1");
- }
- _ => panic!("expected tool results"),
- }
-}
-
-#[test]
-fn native_dispatcher_falls_back_to_xml_tool_calls() {
- let response = ChatResponse {
- text: Some(
- "Checking files...\n<tool_call>{\"name\":\"shell\",\"arguments\":{\"command\":\"ls\"}}</tool_call>"
- .into(),
- ),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- };
- let dispatcher = NativeToolDispatcher;
- let (text, calls) = dispatcher.parse_response(&response);
- assert_eq!(text, "Checking files...");
- assert_eq!(calls.len(), 1);
- assert_eq!(calls[0].name, "shell");
- assert_eq!(calls[0].tool_call_id, None);
-}
-
-#[test]
-fn native_dispatcher_falls_back_to_invoke_tag() {
- let response = ChatResponse {
- text: Some(
- "Let me run this.\n<invoke>{\"name\":\"shell\",\"arguments\":{\"command\":\"pwd\"}}</invoke>".into(),
- ),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- };
- let dispatcher = NativeToolDispatcher;
- let (text, calls) = dispatcher.parse_response(&response);
- assert_eq!(text, "Let me run this.");
- assert_eq!(calls.len(), 1);
- assert_eq!(calls[0].name, "shell");
-}
-
-#[test]
-fn xml_format_results_contains_tool_result_tags() {
- let dispatcher = XmlToolDispatcher;
- let msg = dispatcher.format_results(&[ToolExecutionResult {
- name: "shell".into(),
- output: "ok".into(),
- success: true,
- tool_call_id: None,
- }]);
- let rendered = match msg {
- ConversationMessage::Chat(chat) => chat.content,
- _ => String::new(),
- };
- assert!(rendered.contains("<tool_result"));
- assert!(rendered.contains("shell"));
-}
-
-fn pformat_registry_for(name: &str, props: serde_json::Value) -> PFormatRegistry {
- let schema = serde_json::json!({
- "type": "object",
- "properties": props
- });
- let mut reg = PFormatRegistry::new();
- reg.insert(name.to_string(), PFormatToolParams::from_schema(&schema));
- reg
-}
-
-#[test]
-fn pformat_dispatcher_parses_tool_call_tag() {
- // The model emits a p-format call inside a `<tool_call>` tag.
- // The dispatcher should pull it out, look up the tool's
- // parameter ordering, and produce named JSON args.
- let registry = pformat_registry_for(
- "get_weather",
- serde_json::json!({
- "location": { "type": "string" },
- "unit": { "type": "string" }
- }),
- );
- let dispatcher = PFormatToolDispatcher::new(registry);
- let response = ChatResponse {
- text: Some(
- "Let me check the weather.\n<tool_call>get_weather[0|London|1|metric]</tool_call>"
- .into(),
- ),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- };
- let (text, calls) = dispatcher.parse_response(&response);
- assert_eq!(text, "Let me check the weather.");
- assert_eq!(calls.len(), 1);
- assert_eq!(calls[0].name, "get_weather");
- assert_eq!(
- calls[0].arguments,
- serde_json::json!({"location": "London", "unit": "metric"})
- );
-}
-
-#[test]
-fn pformat_dispatcher_falls_back_to_json_in_tag() {
- // A model that ignored the p-format protocol and emitted a
- // JSON tool call should still be parsed correctly — the
- // dispatcher's whole point is to be a strict superset of the
- // legacy XML behaviour.
- let registry = pformat_registry_for(
- "shell",
- serde_json::json!({ "command": { "type": "string" } }),
- );
- let dispatcher = PFormatToolDispatcher::new(registry);
- let response = ChatResponse {
- text: Some(
- "Running it now.\n<tool_call>{\"name\":\"shell\",\"arguments\":{\"command\":\"ls\"}}</tool_call>"
- .into(),
- ),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- };
- let (text, calls) = dispatcher.parse_response(&response);
- assert_eq!(text, "Running it now.");
- assert_eq!(calls.len(), 1);
- assert_eq!(calls[0].name, "shell");
- assert_eq!(calls[0].arguments, serde_json::json!({"command": "ls"}));
-}
-
-#[test]
-fn pformat_dispatcher_handles_multiple_tags() {
- let registry = pformat_registry_for(
- "shell",
- serde_json::json!({ "command": { "type": "string" } }),
- );
- let dispatcher = PFormatToolDispatcher::new(registry);
- let response = ChatResponse {
- text: Some(
- "Step 1.\n<tool_call>shell[0|ls]</tool_call>\nStep 2.\n<tool_call>shell[0|pwd]</tool_call>"
- .into(),
- ),
- tool_calls: vec![],
- usage: None,
- reasoning_content: None,
- };
- let (_text, calls) = dispatcher.parse_response(&response);
- assert_eq!(calls.len(), 2);
- assert_eq!(calls[0].arguments, serde_json::json!({"command": "ls"}));
- assert_eq!(calls[1].arguments, serde_json::json!({"command": "pwd"}));
-}
-
-#[test]
-fn pformat_dispatcher_reports_pformat_tool_call_format() {
- let dispatcher = PFormatToolDispatcher::new(PFormatRegistry::new());
- assert_eq!(dispatcher.tool_call_format(), ToolCallFormat::PFormat);
-}
-
-#[test]
-fn pformat_dispatcher_instructions_are_protocol_only() {
- // The dispatcher's prompt_instructions should NOT re-render
- // the tool catalogue — that's `ToolsSection`'s job. Otherwise
- // every tool gets emitted twice and the prompt double-pays.
- let dispatcher = PFormatToolDispatcher::new(PFormatRegistry::new());
- // Pass in a tool to make sure the dispatcher ignores it.
- struct DummyTool;
- #[async_trait::async_trait]
- impl Tool for DummyTool {
- fn name(&self) -> &str {
- "should_not_appear"
- }
- fn description(&self) -> &str {
- "this string must not show up in the dispatcher instructions"
- }
- fn parameters_schema(&self) -> serde_json::Value {
- serde_json::json!({})
- }
- async fn execute(&self, _args: serde_json::Value) -> anyhow::Result<tinytools::ToolResult> {
- Ok(tinytools::ToolResult::success("ok"))
- }
- }
- let tools: Vec<Box<dyn Tool>> = vec![Box::new(DummyTool)];
- let instructions = dispatcher.prompt_instructions(&tools);
- assert!(instructions.contains("Tool Use Protocol"));
- assert!(
- !instructions.contains("should_not_appear"),
- "dispatcher instructions must not duplicate the tool catalogue, got:\n{instructions}"
- );
-}
-
-#[test]
-fn native_format_results_keeps_tool_call_id() {
- let dispatcher = NativeToolDispatcher;
- let msg = dispatcher.format_results(&[ToolExecutionResult {
- name: "shell".into(),
- output: "ok".into(),
- success: true,
- tool_call_id: Some("tc-1".into()),
- }]);
-
- match msg {
- ConversationMessage::ToolResults(results) => {
- assert_eq!(results.len(), 1);
- assert_eq!(results[0].tool_call_id, "tc-1");
- }
- _ => panic!("expected ToolResults variant"),
- }
-}
-
-// ── TAURI-RUST-7 regression: tool_calls / ToolResults pairing ──────────
-//
-// Providers reject any assistant `tool_calls` message that isn't immediately
-// followed by `tool` messages responding to every `tool_call_id`. Cached
-// transcript restores and mid-turn aborts can produce bisected pairs. The
-// fix in `to_provider_messages` drops unpaired AssistantToolCalls and orphan
-// ToolResults so the wire payload is always well-formed.
-
-fn assistant_tool_calls(id: &str) -> ConversationMessage {
- ConversationMessage::AssistantToolCalls {
- text: Some("calling tool".into()),
- tool_calls: vec![crate::inference::provider::ToolCall {
- id: id.into(),
- name: "shell".into(),
- arguments: "{}".into(),
- extra_content: None,
- }],
- reasoning_content: None,
- extra_metadata: None,
- }
-}
-
-fn tool_results(id: &str) -> ConversationMessage {
- use crate::agent::messages::ToolResultMessage;
- ConversationMessage::ToolResults(vec![ToolResultMessage {
- tool_call_id: id.into(),
- content: "ok".into(),
- }])
-}
-
-fn user_chat(text: &str) -> ConversationMessage {
- ConversationMessage::Chat(crate::agent::messages::ChatMessage::user(text))
-}
-
-fn assistant_chat(text: &str) -> ConversationMessage {
- ConversationMessage::Chat(crate::agent::messages::ChatMessage::assistant(text))
-}
-
-#[test]
-fn to_provider_messages_keeps_paired_tool_cycle() {
- let dispatcher = NativeToolDispatcher;
- let history = vec![
- user_chat("hi"),
- assistant_tool_calls("tc-1"),
- tool_results("tc-1"),
- assistant_chat("done"),
- ];
- let out = dispatcher.to_provider_messages(&history);
- let roles: Vec<&str> = out.iter().map(|m| m.role.as_str()).collect();
- assert_eq!(roles, vec!["user", "assistant", "tool", "assistant"]);
-}
-
-#[test]
-fn to_provider_messages_drops_trailing_unpaired_tool_calls() {
- // The assistant emitted tool_calls but the run was aborted before the
- // ToolResults were persisted. The trailing tool_calls must not reach
- // the wire.
- let dispatcher = NativeToolDispatcher;
- let history = vec![
- user_chat("hi"),
- assistant_chat("ok"),
- user_chat("again"),
- assistant_tool_calls("tc-2"),
- ];
- let out = dispatcher.to_provider_messages(&history);
- let roles: Vec<&str> = out.iter().map(|m| m.role.as_str()).collect();
- assert_eq!(
- roles,
- vec!["user", "assistant", "user"],
- "trailing unpaired AssistantToolCalls must be stripped"
- );
-}
-
-#[test]
-fn to_provider_messages_drops_mid_history_unpaired_tool_calls() {
- // History with a bisected pair in the middle: tool_calls followed
- // directly by a Chat (not ToolResults). Drop the tool_calls; keep
- // everything else.
- let dispatcher = NativeToolDispatcher;
- let history = vec![
- user_chat("hi"),
- assistant_tool_calls("tc-3"), // bisected — no following ToolResults
- user_chat("nevermind"),
- assistant_chat("ok"),
- ];
- let out = dispatcher.to_provider_messages(&history);
- let roles: Vec<&str> = out.iter().map(|m| m.role.as_str()).collect();
- assert_eq!(roles, vec!["user", "user", "assistant"]);
-}
-
-#[test]
-fn to_provider_messages_drops_orphan_tool_results() {
- // Symmetric drop: ToolResults whose preceding AssistantToolCalls was
- // never emitted (either never persisted or already dropped above)
- // must not appear in the wire payload.
- let dispatcher = NativeToolDispatcher;
- let history = vec![
- user_chat("hi"),
- tool_results("tc-4"), // orphan — no preceding AssistantToolCalls
- assistant_chat("ok"),
- ];
- let out = dispatcher.to_provider_messages(&history);
- let roles: Vec<&str> = out.iter().map(|m| m.role.as_str()).collect();
- assert_eq!(roles, vec!["user", "assistant"]);
-}
-
-#[test]
-fn to_provider_messages_handles_multiple_tool_cycles() {
- // Two paired cycles in a row — both must survive.
- let dispatcher = NativeToolDispatcher;
- let history = vec![
- user_chat("a"),
- assistant_tool_calls("tc-5"),
- tool_results("tc-5"),
- assistant_tool_calls("tc-6"),
- tool_results("tc-6"),
- assistant_chat("final"),
- ];
- let out = dispatcher.to_provider_messages(&history);
- let roles: Vec<&str> = out.iter().map(|m| m.role.as_str()).collect();
- assert_eq!(
- roles,
- vec![
- "user",
- "assistant",
- "tool",
- "assistant",
- "tool",
- "assistant"
- ]
- );
-}
-
-// ── tool_call_id set-pairing (CodeRabbit follow-up) ─────────────────────
-
-fn assistant_tool_calls_multi(ids: &[&str]) -> ConversationMessage {
- ConversationMessage::AssistantToolCalls {
- text: Some("calling tools".into()),
- tool_calls: ids
- .iter()
- .map(|id| crate::inference::provider::ToolCall {
- id: (*id).into(),
- name: "shell".into(),
- arguments: "{}".into(),
- extra_content: None,
- })
- .collect(),
- reasoning_content: None,
- extra_metadata: None,
- }
-}
-
-#[test]
-fn native_dispatcher_serializes_reasoning_content_for_tool_call_turns() {
- let dispatcher = NativeToolDispatcher;
- let history = vec![
- ConversationMessage::AssistantToolCalls {
- text: Some("calling tools".into()),
- tool_calls: vec![crate::inference::provider::ToolCall {
- id: "tc-1".into(),
- name: "shell".into(),
- arguments: "{}".into(),
- extra_content: None,
- }],
- reasoning_content: Some("chain-of-thought replay blob".into()),
- extra_metadata: None,
- },
- tool_results("tc-1"),
- ];
-
- let out = dispatcher.to_provider_messages(&history);
- assert_eq!(out.len(), 2);
- assert_eq!(out[0].role, "assistant");
-
- let payload: serde_json::Value =
- serde_json::from_str(&out[0].content).expect("assistant payload should be valid JSON");
- assert_eq!(
- payload
- .get("reasoning_content")
- .and_then(serde_json::Value::as_str),
- Some("chain-of-thought replay blob")
- );
-}
-
-#[test]
-fn native_dispatcher_omits_reasoning_content_when_absent() {
- let dispatcher = NativeToolDispatcher;
- let history = vec![assistant_tool_calls("tc-1"), tool_results("tc-1")];
-
- let out = dispatcher.to_provider_messages(&history);
- assert_eq!(out.len(), 2);
- assert_eq!(out[0].role, "assistant");
-
- let payload: serde_json::Value =
- serde_json::from_str(&out[0].content).expect("assistant payload should be valid JSON");
- assert!(
- payload.get("reasoning_content").is_none(),
- "reasoning_content should be omitted when absent"
- );
-}
-
-fn tool_results_multi(ids: &[&str]) -> ConversationMessage {
- use crate::agent::messages::ToolResultMessage;
- ConversationMessage::ToolResults(
- ids.iter()
- .map(|id| ToolResultMessage {
- tool_call_id: (*id).into(),
- content: "ok".into(),
- })
- .collect(),
- )
-}
-
-#[test]
-fn to_provider_messages_drops_pair_when_tool_call_ids_mismatch() {
- // Opener requests `tc-1`, but the only ToolResults entry answers `tc-x`.
- // Backend would 400 with "insufficient tool messages following tool_calls"
- // — drop both.
- let dispatcher = NativeToolDispatcher;
- let history = vec![
- user_chat("hi"),
- assistant_tool_calls_multi(&["tc-1"]),
- tool_results_multi(&["tc-x"]),
- assistant_chat("done"),
- ];
- let out = dispatcher.to_provider_messages(&history);
- let roles: Vec<&str> = out.iter().map(|m| m.role.as_str()).collect();
- assert_eq!(
- roles,
- vec!["user", "assistant"],
- "id-set mismatch must drop the bisected pair entirely, kept: {roles:?}"
- );
-}
-
-#[test]
-fn to_provider_messages_drops_pair_when_results_are_partial() {
- // Opener requests two tool_call_ids, results answer only one. Backend
- // rejects with "insufficient tool messages". Strict set equality drops
- // the pair.
- let dispatcher = NativeToolDispatcher;
- let history = vec![
- user_chat("hi"),
- assistant_tool_calls_multi(&["tc-1", "tc-2"]),
- tool_results_multi(&["tc-1"]),
- assistant_chat("done"),
- ];
- let out = dispatcher.to_provider_messages(&history);
- let roles: Vec<&str> = out.iter().map(|m| m.role.as_str()).collect();
- assert_eq!(
- roles,
- vec!["user", "assistant"],
- "partial tool-result coverage must drop the pair, kept: {roles:?}"
- );
-}
-
-#[test]
-fn to_provider_messages_keeps_pair_with_full_id_coverage() {
- // Strict set equality: opener has {tc-1, tc-2}, results cover both,
- // even if listed in a different order. Both messages must be emitted.
- let dispatcher = NativeToolDispatcher;
- let history = vec![
- user_chat("hi"),
- assistant_tool_calls_multi(&["tc-1", "tc-2"]),
- tool_results_multi(&["tc-2", "tc-1"]),
- assistant_chat("done"),
- ];
- let out = dispatcher.to_provider_messages(&history);
- let roles: Vec<&str> = out.iter().map(|m| m.role.as_str()).collect();
- assert_eq!(
- roles,
- vec!["user", "assistant", "tool", "tool", "assistant"]
- );
-}
-
-#[test]
-fn to_provider_messages_drops_pair_with_extra_unsolicited_results() {
- // Opener requests `tc-1`; results answer `tc-1` *and* an unsolicited
- // `tc-extra`. The id sets differ, so the pair is dropped.
- let dispatcher = NativeToolDispatcher;
- let history = vec![
- user_chat("hi"),
- assistant_tool_calls_multi(&["tc-1"]),
- tool_results_multi(&["tc-1", "tc-extra"]),
- assistant_chat("done"),
- ];
- let out = dispatcher.to_provider_messages(&history);
- let roles: Vec<&str> = out.iter().map(|m| m.role.as_str()).collect();
- assert_eq!(
- roles,
- vec!["user", "assistant"],
- "extra unsolicited tool_call_ids must invalidate the pair, kept: {roles:?}"
- );
-}
-
-// `ChatMessage.role` is a free-form `String` in the durable transcript record,
-// but `to_dialect_message`/`from_dialect_message` route it through the
-// crate's closed `DialectRole` (system/user/assistant/tool) — the same four
-// roles every dispatcher already spoke before this seam existed. A role
-// outside that vocabulary (nothing in this codebase produces one today; see
-// the doc comment on `to_dialect_message`) is treated as a `user` turn on the
-// way out, matching how every provider already treats an unrecognized role.
-// This pins that intentional behaviour so it does not silently drift.
-#[test]
-fn to_provider_messages_treats_unrecognized_role_as_user() {
- let dispatcher = XmlToolDispatcher;
- let mut developer_message = crate::agent::messages::ChatMessage::user("hi");
- developer_message.role = "developer".to_string();
- let history = vec![ConversationMessage::Chat(developer_message)];
-
- let out = dispatcher.to_provider_messages(&history);
-
- assert_eq!(out.len(), 1);
- assert_eq!(
- out[0].role, "user",
- "an unrecognized role must fall back to `user`, not be dropped or panic"
- );
- assert_eq!(out[0].content, "hi");
-}
-
-// ── KV-cache prefix stability ────────────────────────────────────────────────
-//
-// Every turn of a session replays the whole history, and a prefix cache reuses
-// only a *byte-identical* prefix. So the serialization of turn N must survive
-// as the opening of turn N+1 unchanged: a message that renders differently on
-// its second outing does not merely cost its own tokens, it invalidates
-// everything after it for the rest of the thread — including the system prompt,
-// which `Agent::turn` goes to considerable lengths to freeze.
-//
-// `to_provider_messages` is the one place that can violate this without any
-// caller doing anything wrong, because `pair_tool_cycles` *drops* entries. The
-// verdict it reaches for an entry must depend only on that entry and its
-// immediate neighbour — never on anything appended later — or an earlier
-// message's presence flips retroactively and the prefix moves under the cache.
-
-/// Every proper prefix of a history must serialize to a prefix of the whole
-/// history's serialization.
-///
-/// Written as a sweep over every split point rather than one hand-picked pair:
-/// the interesting splits are exactly the ones that land inside a tool cycle,
-/// and enumerating them is how the awkward case gets covered without someone
-/// having to notice it.
-fn assert_serialization_is_append_only(history: &[ConversationMessage]) {
- let dispatcher = NativeToolDispatcher;
- let full = dispatcher.to_provider_messages(history);
- for split in 0..=history.len() {
- let partial = dispatcher.to_provider_messages(&history[..split]);
- assert!(
- partial.len() <= full.len(),
- "history[..{split}] serialized to {} messages, longer than the full \
- history's {} — a later turn cannot un-send what an earlier one sent",
- partial.len(),
- full.len()
- );
- for (index, message) in partial.iter().enumerate() {
- assert_eq!(
- (message.role.as_str(), message.content.as_str()),
- (full[index].role.as_str(), full[index].content.as_str()),
- "history[..{split}] diverges from the full history at message \
- {index}: appending a later turn rewrote an earlier message, so \
- every provider prefix cache re-prefills from here on"
- );
- }
- }
-}
-
-#[test]
-fn appending_a_turn_never_rewrites_an_earlier_message() {
- assert_serialization_is_append_only(&[
- user_chat("hi"),
- assistant_chat("hello"),
- user_chat("run something"),
- assistant_tool_calls("tc-1"),
- tool_results("tc-1"),
- assistant_chat("done"),
- user_chat("and again"),
- assistant_tool_calls("tc-2"),
- tool_results("tc-2"),
- assistant_chat("done again"),
- ]);
-}
-
-#[test]
-fn completing_an_aborted_tool_cycle_only_appends() {
- // The turn that matters most: a run capped mid-cycle persists the opener
- // with no results, so that turn's request drops it. When the results
- // arrive, the opener becomes sendable — and must appear *after* everything
- // already sent, never before it. (A dropped entry that later reappears
- // in place would be the retroactive rewrite this whole property forbids.)
- let history = vec![
- user_chat("hi"),
- assistant_chat("hello"),
- assistant_tool_calls("tc-1"),
- tool_results("tc-1"),
- assistant_chat("done"),
- ];
- let dispatcher = NativeToolDispatcher;
-
- // Turn N: the opener at index 2 has no results yet, so it is withheld.
- let aborted = dispatcher.to_provider_messages(&history[..3]);
- assert_eq!(
- aborted.iter().map(|m| m.role.as_str()).collect::<Vec<_>>(),
- vec!["user", "assistant"],
- "an unpaired opener must not reach the wire"
- );
-
- // Turn N+1: with the results persisted the cycle is sendable, and the two
- // messages already sent are still the first two, unchanged.
- assert_serialization_is_append_only(&history);
-}
-
-#[test]
-fn serializing_the_same_history_twice_is_byte_identical() {
- // Guards against a serializer that folds in anything ambient — a
- // timestamp, an iteration counter, a HashMap iteration order. Such a thing
- // would cost the whole cached prefix on every turn while every other test
- // here still passed.
- let history = vec![
- user_chat("hi"),
- assistant_tool_calls("tc-1"),
- tool_results("tc-1"),
- assistant_chat("done"),
- ];
- let dispatcher = NativeToolDispatcher;
- let first = dispatcher.to_provider_messages(&history);
- let second = dispatcher.to_provider_messages(&history);
- let render = |messages: &[crate::agent::messages::ChatMessage]| {
- messages
- .iter()
- .map(|m| format!("{}:{}", m.role, m.content))
- .collect::<Vec<_>>()
- };
- assert_eq!(render(&first), render(&second));
-}
diff --git a/crates/openhuman-core/src/agent/harness/graph.rs b/crates/openhuman-core/src/agent/harness/graph.rs
index 3db76815f1..5447876b59 100644
--- a/crates/openhuman-core/src/agent/harness/graph.rs
+++ b/crates/openhuman-core/src/agent/harness/graph.rs
@@ -165,14 +165,19 @@ pub(crate) async fn run_channel_turn_via_graph(
// Using `outcome.conversation` (the typed messages-since-last-user) avoids
// indexing into a post-trim `outcome.history` with the pre-trim `prior_len`,
// which could drop current-turn messages when compaction reshaped the run.
- use crate::agent::tool_dialect::ToolDispatcher;
let suffix = if native_tools {
- crate::agent::tool_dialect::NativeToolDispatcher.to_provider_messages(&outcome.conversation)
+ crate::agent::message_convert::provider_messages_from_conversation(
+ &tinytools_agent::dialect::NativeDialect,
+ &outcome.conversation,
+ )
} else {
// History serialization is format-independent for prompt-guided providers
// (tool calls already ride the visible assistant text); the XML dispatcher
// renders the flat `[Tool results]` shape.
- crate::agent::tool_dialect::XmlToolDispatcher.to_provider_messages(&outcome.conversation)
+ crate::agent::message_convert::provider_messages_from_conversation(
+ &tinytools_agent::dialect::XmlDialect,
+ &outcome.conversation,
+ )
};
history.extend(suffix);
if outcome.early_exit_tool.is_some() {
diff --git a/crates/openhuman-core/src/agent/harness/harness_tool_call_parsing_tests.rs b/crates/openhuman-core/src/agent/harness/harness_tool_call_parsing_tests.rs
index c5e13932d8..6fe4744fb6 100644
--- a/crates/openhuman-core/src/agent/harness/harness_tool_call_parsing_tests.rs
+++ b/crates/openhuman-core/src/agent/harness/harness_tool_call_parsing_tests.rs
@@ -332,7 +332,7 @@ fn build_tool_instructions_includes_all_tools() {
std::path::Path::new("/tmp"),
std::path::Path::new("/tmp"),
));
- let tools = tools::default_tools(security);
+ let tools = tools::ops::default_tools(security);
let instructions = build_tool_instructions(&tools);
assert!(instructions.contains("## Tool Use Protocol"));
@@ -350,7 +350,7 @@ fn tools_to_openai_format_produces_valid_schema() {
std::path::Path::new("/tmp"),
std::path::Path::new("/tmp"),
));
- let tools = tools::default_tools(security);
+ let tools = tools::ops::default_tools(security);
let formatted = tools_to_openai_format(&tools);
assert!(!formatted.is_empty());
diff --git a/crates/openhuman-core/src/agent/harness/session/builder/builder_tests_tool_spec_views_tests.rs b/crates/openhuman-core/src/agent/harness/session/builder/builder_tests_tool_spec_views_tests.rs
index c994bf6908..3686d7cb85 100644
--- a/crates/openhuman-core/src/agent/harness/session/builder/builder_tests_tool_spec_views_tests.rs
+++ b/crates/openhuman-core/src/agent/harness/session/builder/builder_tests_tool_spec_views_tests.rs
@@ -130,7 +130,7 @@ fn spec_views_stay_consistent_for_a_tool_less_agent() {
.chat_model(model)
.tools(Vec::new())
.memory(crate::memory::test_support::noop_memory())
- .tool_dispatcher(Box::new(crate::agent::tool_dialect::XmlToolDispatcher))
+ .tool_dispatcher(Box::new(tinytools_agent::dialect::XmlDialect))
.build()
.expect("a tool-less agent is a legal build");
diff --git a/crates/openhuman-core/src/agent/harness/session/builder/factory.rs b/crates/openhuman-core/src/agent/harness/session/builder/factory.rs
index 6e5a003ea3..d3550f4f23 100644
--- a/crates/openhuman-core/src/agent/harness/session/builder/factory.rs
+++ b/crates/openhuman-core/src/agent/harness/session/builder/factory.rs
@@ -8,7 +8,6 @@ use crate::agent::harness::definition::{AgentDefinitionRegistry, PromptSource, T
use crate::agent::harness::session::types::Agent;
use crate::agent::host_runtime;
use crate::agent::prompts::SystemPromptBuilder;
-use crate::agent::tool_dialect::{NativeToolDispatcher, PFormatToolDispatcher, XmlToolDispatcher};
use crate::config::Config;
use crate::inference::provider;
use crate::memory::tool_memory::capture::ToolMemoryCaptureHook;
@@ -18,6 +17,7 @@ use crate::tools;
use anyhow::Result;
use std::sync::Arc;
use tinytools::{PermissionLevel, Tool};
+use tinytools_agent::dialect::{NativeDialect, PFormatDialect, ToolDialect, XmlDialect};
impl Agent {
/// Constructs an `Agent` instance from a global system configuration.
@@ -1062,14 +1062,11 @@ impl Agent {
);
let dispatcher_kind =
resolve_dispatcher_kind(&dispatcher_choice, supports_native, agent_id);
- let tool_dispatcher: Box<dyn crate::agent::tool_dialect::ToolDispatcher> =
- match dispatcher_kind {
- DispatcherKind::Native => Box::new(NativeToolDispatcher),
- DispatcherKind::Xml => Box::new(XmlToolDispatcher),
- DispatcherKind::PFormat => {
- Box::new(PFormatToolDispatcher::new(pformat_registry.clone()))
- }
- };
+ let tool_dispatcher: Box<dyn ToolDialect> = match dispatcher_kind {
+ DispatcherKind::Native => Box::new(NativeDialect),
+ DispatcherKind::Xml => Box::new(XmlDialect),
+ DispatcherKind::PFormat => Box::new(PFormatDialect::new(pformat_registry.clone())),
+ };
log::debug!(
"[agent] tool dispatcher selected: choice={dispatcher_choice} agent_id={agent_id} \
diff --git a/crates/openhuman-core/src/agent/harness/session/builder/setters.rs b/crates/openhuman-core/src/agent/harness/session/builder/setters.rs
index a34ea34127..8d1537a37e 100644
--- a/crates/openhuman-core/src/agent/harness/session/builder/setters.rs
+++ b/crates/openhuman-core/src/agent/harness/session/builder/setters.rs
@@ -143,10 +143,10 @@ impl AgentBuilder {
self
}
- /// Sets the tool dispatcher for the agent.
+ /// Sets the canonical tool dialect for the agent.
pub fn tool_dispatcher(
mut self,
- tool_dispatcher: Box<dyn crate::agent::tool_dialect::ToolDispatcher>,
+ tool_dispatcher: Box<dyn tinytools_agent::dialect::ToolDialect>,
) -> Self {
self.tool_dispatcher = Some(tool_dispatcher);
self
diff --git a/crates/openhuman-core/src/agent/harness/session/runtime/turn_helpers.rs b/crates/openhuman-core/src/agent/harness/session/runtime/turn_helpers.rs
index 3f1139a8c9..70662469ee 100644
--- a/crates/openhuman-core/src/agent/harness/session/runtime/turn_helpers.rs
+++ b/crates/openhuman-core/src/agent/harness/session/runtime/turn_helpers.rs
@@ -4,9 +4,9 @@
use super::super::types::Agent;
use crate::agent::error::AgentError;
use crate::agent::messages::ConversationMessage;
-use crate::agent::tool_dialect::ParsedToolCall;
use crate::inference::provider::ToolCall;
use crate::util::truncate_with_ellipsis;
+use tinytools_agent::ParsedToolCall;
impl Agent {
const EVENT_ERROR_MAX_CHARS: usize = 256;
@@ -100,8 +100,8 @@ impl Agent {
iteration: usize,
) -> Vec<ParsedToolCall> {
for (idx, call) in parsed_calls.iter_mut().enumerate() {
- if call.tool_call_id.is_none() {
- call.tool_call_id = Some(format!("parsed-{}-{}", iteration + 1, idx + 1));
+ if call.id.is_none() {
+ call.id = Some(format!("parsed-{}-{}", iteration + 1, idx + 1));
}
}
parsed_calls
@@ -125,7 +125,7 @@ impl Agent {
.enumerate()
.map(|(idx, call)| ToolCall {
id: call
- .tool_call_id
+ .id
.clone()
.unwrap_or_else(|| format!("parsed-{}-{}", iteration + 1, idx + 1)),
name: call.name.clone(),
diff --git a/crates/openhuman-core/src/agent/harness/session/runtime_tests.rs b/crates/openhuman-core/src/agent/harness/session/runtime_tests.rs
index 8b9461c8a7..456ff8a5cb 100644
--- a/crates/openhuman-core/src/agent/harness/session/runtime_tests.rs
+++ b/crates/openhuman-core/src/agent/harness/session/runtime_tests.rs
@@ -2,7 +2,6 @@ use super::super::types::Agent;
use crate::agent::error::AgentError;
use crate::agent::messages::ChatMessage;
use crate::agent::messages::ConversationMessage;
-use crate::agent::tool_dialect::XmlToolDispatcher;
use crate::core::events::DomainEvent;
use crate::inference::provider::{ChatResponse, UsageInfo};
use crate::memory::Memory;
@@ -13,6 +12,7 @@ use std::sync::Arc;
use tinyinference_llm::model::{
ChatModel, ModelRequest, ModelResponse, ModelStream, ModelStreamItem,
};
+use tinytools_agent::dialect::XmlDialect;
use tokio::sync::Mutex as AsyncMutex;
use tokio::time::{sleep, Duration};
@@ -120,7 +120,7 @@ fn make_agent(model: Arc<dyn ChatModel<()>>) -> Agent {
.chat_model(model)
.tools(vec![])
.memory(mem)
- .tool_dispatcher(Box::new(XmlToolDispatcher))
+ .tool_dispatcher(Box::new(XmlDialect))
.workspace_dir(workspace_path)
.event_context("runtime-test-session", "runtime-test-channel")
.build()
@@ -168,20 +168,20 @@ fn sanitizers_and_tool_call_helpers_cover_fallback_paths() {
assert!(!sanitized.contains('\t'));
let calls = vec![
- crate::agent::tool_dialect::ParsedToolCall {
+ tinytools_agent::ParsedToolCall {
name: "a".into(),
arguments: serde_json::json!({}),
- tool_call_id: None,
+ id: None,
},
- crate::agent::tool_dialect::ParsedToolCall {
+ tinytools_agent::ParsedToolCall {
name: "b".into(),
arguments: serde_json::json!({"x":1}),
- tool_call_id: Some("keep".into()),
+ id: Some("keep".into()),
},
];
let calls = Agent::with_fallback_tool_call_ids(calls, 2);
- assert_eq!(calls[0].tool_call_id.as_deref(), Some("parsed-3-1"));
- assert_eq!(calls[1].tool_call_id.as_deref(), Some("keep"));
+ assert_eq!(calls[0].id.as_deref(), Some("parsed-3-1"));
+ assert_eq!(calls[1].id.as_deref(), Some("keep"));
let response = crate::inference::provider::ChatResponse {
text: Some(String::new()),
diff --git a/crates/openhuman-core/src/agent/harness/session/session_builder_and_listener_tests.rs b/crates/openhuman-core/src/agent/harness/session/session_builder_and_listener_tests.rs
index e06208ca7a..3eb9ff94b5 100644
--- a/crates/openhuman-core/src/agent/harness/session/session_builder_and_listener_tests.rs
+++ b/crates/openhuman-core/src/agent/harness/session/session_builder_and_listener_tests.rs
@@ -338,7 +338,7 @@ fn refresh_workflows_picks_up_skill_installed_on_disk() {
.chat_model(provider)
.tools(vec![Box::new(MockTool)])
.memory(mem)
- .tool_dispatcher(Box::new(NativeToolDispatcher))
+ .tool_dispatcher(Box::new(NativeDialect))
.workspace_dir(wsp.clone())
.build()
.expect("agent build should succeed");
@@ -409,7 +409,7 @@ fn refresh_workflows_retracts_skill_removed_from_disk() {
.chat_model(provider)
.tools(vec![Box::new(MockTool)])
.memory(mem)
- .tool_dispatcher(Box::new(NativeToolDispatcher))
+ .tool_dispatcher(Box::new(NativeDialect))
.workspace_dir(wsp.clone())
.build()
.expect("agent build should succeed");
@@ -507,7 +507,7 @@ async fn turn_without_tools_returns_text() {
.chat_model(provider)
.tools(vec![Box::new(MockTool)])
.memory(mem)
- .tool_dispatcher(Box::new(XmlToolDispatcher))
+ .tool_dispatcher(Box::new(XmlDialect))
.workspace_dir(workspace_path)
.build()
.unwrap();
@@ -553,7 +553,7 @@ async fn last_turn_usage_is_public_and_non_draining() {
.chat_model(provider)
.tools(vec![Box::new(MockTool)])
.memory(mem)
- .tool_dispatcher(Box::new(XmlToolDispatcher))
+ .tool_dispatcher(Box::new(XmlDialect))
.workspace_dir(workspace_path)
.build()
.unwrap();
diff --git a/crates/openhuman-core/src/agent/harness/session/session_dispatch_and_resume_tests.rs b/crates/openhuman-core/src/agent/harness/session/session_dispatch_and_resume_tests.rs
index f4c24d387e..f33312ce2b 100644
--- a/crates/openhuman-core/src/agent/harness/session/session_dispatch_and_resume_tests.rs
+++ b/crates/openhuman-core/src/agent/harness/session/session_dispatch_and_resume_tests.rs
@@ -39,7 +39,7 @@ async fn turn_with_native_dispatcher_handles_tool_results_variant() {
.chat_model(provider)
.tools(vec![Box::new(MockTool)])
.memory(mem)
- .tool_dispatcher(Box::new(NativeToolDispatcher))
+ .tool_dispatcher(Box::new(NativeDialect))
.workspace_dir(workspace_path)
.build()
.unwrap();
@@ -89,7 +89,7 @@ async fn turn_with_native_dispatcher_persists_fallback_tool_calls() {
.chat_model(provider)
.tools(vec![Box::new(MockTool)])
.memory(mem)
- .tool_dispatcher(Box::new(NativeToolDispatcher))
+ .tool_dispatcher(Box::new(NativeDialect))
.workspace_dir(workspace_path)
.build()
.unwrap();
@@ -215,7 +215,7 @@ async fn system_prompt_and_model_are_byte_stable_across_turns() {
.chat_model(provider.clone() as Arc<dyn ChatModel<()>>)
.tools(vec![])
.memory(mem)
- .tool_dispatcher(Box::new(NativeToolDispatcher))
+ .tool_dispatcher(Box::new(NativeDialect))
.workspace_dir(workspace_path)
// Learning flag is explicitly enabled to prove that the
// former "rebuild system prompt on subsequent turns" branch
diff --git a/crates/openhuman-core/src/agent/harness/session/session_resume_request_id_tests.rs b/crates/openhuman-core/src/agent/harness/session/session_resume_request_id_tests.rs
index b9b4d5ddd7..8cd5fcc76b 100644
--- a/crates/openhuman-core/src/agent/harness/session/session_resume_request_id_tests.rs
+++ b/crates/openhuman-core/src/agent/harness/session/session_resume_request_id_tests.rs
@@ -251,7 +251,7 @@ fn a_resumed_request_less_transcript_is_not_restamped_with_the_resuming_request(
}))
.tools(vec![Box::new(MockTool)])
.memory(mem)
- .tool_dispatcher(Box::new(NativeToolDispatcher))
+ .tool_dispatcher(Box::new(NativeDialect))
.workspace_dir(wsp.clone())
.build()
.expect("agent build should succeed");
diff --git a/crates/openhuman-core/src/agent/harness/session/session_tests.rs b/crates/openhuman-core/src/agent/harness/session/session_tests.rs
index 0124afe5b0..fbd57f1616 100644
--- a/crates/openhuman-core/src/agent/harness/session/session_tests.rs
+++ b/crates/openhuman-core/src/agent/harness/session/session_tests.rs
@@ -7,7 +7,6 @@
use super::types::{Agent, AgentBuilder};
use crate::agent::messages::ConversationMessage;
-use crate::agent::tool_dialect::{NativeToolDispatcher, XmlToolDispatcher};
use crate::core::events::DomainEvent;
use crate::inference::provider::ChatResponse;
use crate::memory::Memory;
@@ -20,6 +19,7 @@ use tinyinference_llm::model::{
ChatModel, ModelProfile, ModelRequest, ModelResponse, ModelStream, ModelStreamItem,
};
use tinytools::Tool;
+use tinytools_agent::dialect::{NativeDialect, XmlDialect};
struct MockProvider {
responses: Mutex<Vec<ChatResponse>>,
@@ -195,7 +195,7 @@ fn build_minimal_agent_with_tool_sets(
.tools(tools)
.synthesized_tools(synthesized_tools)
.memory(mem)
- .tool_dispatcher(Box::new(NativeToolDispatcher))
+ .tool_dispatcher(Box::new(NativeDialect))
.workspace_dir(workspace_path);
if let Some(name) = definition_name {
@@ -372,7 +372,7 @@ async fn turn_dispatches_spawn_subagent_through_full_path_inner() {
.chat_model(provider)
.tools(tools)
.memory(mem)
- .tool_dispatcher(Box::new(NativeToolDispatcher))
+ .tool_dispatcher(Box::new(NativeDialect))
.workspace_dir(workspace_path)
.build()
.unwrap();
@@ -542,7 +542,7 @@ fn agent_with_fake_locator(
}))
.tools(vec![Box::new(MockTool)])
.memory(mem)
- .tool_dispatcher(Box::new(NativeToolDispatcher))
+ .tool_dispatcher(Box::new(NativeDialect))
.agent_definition_name("faker")
.workspace_dir(workspace.to_path_buf())
.with_session_history_locator(Arc::new(FakeLocator {
diff --git a/crates/openhuman-core/src/agent/harness/session/session_thread_resume_tests.rs b/crates/openhuman-core/src/agent/harness/session/session_thread_resume_tests.rs
index e4a0bdd2fa..68bfdba64e 100644
--- a/crates/openhuman-core/src/agent/harness/session/session_thread_resume_tests.rs
+++ b/crates/openhuman-core/src/agent/harness/session/session_thread_resume_tests.rs
@@ -89,7 +89,7 @@ fn seed_resume_from_thread_transcript_preserves_tool_calls_and_reasoning() {
}))
.tools(vec![Box::new(MockTool)])
.memory(mem)
- .tool_dispatcher(Box::new(NativeToolDispatcher))
+ .tool_dispatcher(Box::new(NativeDialect))
.agent_definition_name("some_other_agent_name")
.workspace_dir(wsp.clone())
.build()
diff --git a/crates/openhuman-core/src/agent/harness/session/transcript_history_tests.rs b/crates/openhuman-core/src/agent/harness/session/transcript_history_tests.rs
index 38d1d7c9bd..23b4a86a73 100644
--- a/crates/openhuman-core/src/agent/harness/session/transcript_history_tests.rs
+++ b/crates/openhuman-core/src/agent/harness/session/transcript_history_tests.rs
@@ -448,7 +448,7 @@ fn native_tool_round() -> Vec<ChatMessage> {
serde_json::json!({
"content": "calling get_weather",
// The flat `{id, name, arguments}` shape
- // `NativeToolDispatcher::to_provider_messages` persists — the
+ // `NativeDialect::to_provider_messages` persists — the
// one `parse_native_assistant_envelope` accepts.
"tool_calls": [{
"id": "call-1",
diff --git a/crates/openhuman-core/src/agent/harness/session/turn/context.rs b/crates/openhuman-core/src/agent/harness/session/turn/context.rs
index b2208cad96..992774045e 100644
--- a/crates/openhuman-core/src/agent/harness/session/turn/context.rs
+++ b/crates/openhuman-core/src/agent/harness/session/turn/context.rs
@@ -4,7 +4,9 @@ use super::super::turn_checkpoint::assistant_message_has_tool_calls;
use super::super::types::Agent;
use super::{collect_tree_root_summaries, sanitize_learned_entry};
use crate::agent::messages::{ChatMessage, ConversationMessage};
-use crate::agent::prompts::{LearnedContextData, PromptContext, PromptTool};
+use crate::agent::prompts::{
+ tool_call_format_from_dialect, LearnedContextData, PromptContext, PromptTool,
+};
use crate::memory::MemoryCategory;
use crate::tools::agent_policy::render_tool_policy_boundary;
use tinytools::Tool;
@@ -280,13 +282,8 @@ impl Agent {
/// Builds the system prompt for the current turn, including tool
/// instructions and learned context.
pub fn build_system_prompt(&self, learned: LearnedContextData) -> Result<String> {
- let tools_slice: &[Box<dyn Tool>] = self.tools.as_slice();
- // `visible_tool_specs` holds shared `Arc<ToolSpec>` leaves (they are the
- // same schema objects the durable and full views point at), while the
- // `ToolDispatcher` trait — which embedders implement — takes an owned
- // `&[ToolSpec]`. Materialise a borrow-slice for the call: this is one
- // transient copy per system-prompt build, not a per-agent resident one,
- // and keeping it here is what lets the trait stay source-compatible.
+ // `visible_tool_specs` holds shared `Arc<ToolSpec>` leaves. Materialise
+ // the canonical dialect input for this prompt build.
let visible_specs_owned: Vec<tinytools::ToolSpec> = self
.visible_tool_specs
.iter()
@@ -294,8 +291,7 @@ impl Agent {
.collect();
let instructions = self
.tool_dispatcher
- .prompt_instructions_for_specs(&visible_specs_owned)
- .unwrap_or_else(|| self.tool_dispatcher.prompt_instructions(tools_slice));
+ .prompt_instructions(&visible_specs_owned);
// Adapt the agent's whole callable surface into the shared PromptTool
// shape that every prompt-building call-site uses. Temporary vec
// borrows from the two tool `Arc`s and lives for the duration of the
@@ -326,7 +322,9 @@ impl Agent {
dispatcher_instructions: &instructions,
learned,
visible_tool_names: &prompt_visible_tool_names,
- tool_call_format: self.tool_dispatcher.tool_call_format(),
+ tool_call_format: tool_call_format_from_dialect(
+ self.tool_dispatcher.tool_call_format(),
+ ),
connected_integrations: &self.connected_integrations,
connected_identities_md: crate::agent::prompts::render_connected_identities(),
include_profile: !self.omit_profile,
diff --git a/crates/openhuman-core/src/agent/harness/session/turn/core/failed_turn.rs b/crates/openhuman-core/src/agent/harness/session/turn/core/failed_turn.rs
index 8d7ef651d3..bd773f4ebf 100644
--- a/crates/openhuman-core/src/agent/harness/session/turn/core/failed_turn.rs
+++ b/crates/openhuman-core/src/agent/harness/session/turn/core/failed_turn.rs
@@ -111,7 +111,10 @@ impl Agent {
output,
cached,
);
- let persisted = self.tool_dispatcher.to_provider_messages(&self.history);
+ let persisted = crate::agent::message_convert::provider_messages_from_conversation(
+ self.tool_dispatcher.as_ref(),
+ &self.history,
+ );
let turn_usage = TurnUsage {
provider: self.event_channel().to_string(),
model: effective_model.to_string(),
diff --git a/crates/openhuman-core/src/agent/harness/session/turn/core/grounded_close.rs b/crates/openhuman-core/src/agent/harness/session/turn/core/grounded_close.rs
index e83496f0fd..d9af71fc3d 100644
--- a/crates/openhuman-core/src/agent/harness/session/turn/core/grounded_close.rs
+++ b/crates/openhuman-core/src/agent/harness/session/turn/core/grounded_close.rs
@@ -61,7 +61,10 @@ impl Agent {
turn_checkpoint::render_tool_results(&results, turn_checkpoint::GROUNDING_TOTAL_CHARS);
let iteration = outcome.model_calls as u32 + 1;
- let base = self.tool_dispatcher.to_provider_messages(&self.history);
+ let base = crate::agent::message_convert::provider_messages_from_conversation(
+ self.tool_dispatcher.as_ref(),
+ &self.history,
+ );
let (candidate, candidate_usage) = self
.summarize_turn_wrapup(
&base,
diff --git a/crates/openhuman-core/src/agent/harness/session/turn/core/harness_turn.rs b/crates/openhuman-core/src/agent/harness/session/turn/core/harness_turn.rs
index c94b4f0805..46a28705ce 100644
--- a/crates/openhuman-core/src/agent/harness/session/turn/core/harness_turn.rs
+++ b/crates/openhuman-core/src/agent/harness/session/turn/core/harness_turn.rs
@@ -54,7 +54,10 @@ impl Agent {
// again. A resumed session's replayed prefix is folded into that same
// history first (see below), so there is exactly one sequence to read.
self.absorb_resumed_transcript_prefix();
- let mut messages = self.tool_dispatcher.to_provider_messages(&self.history);
+ let mut messages = crate::agent::message_convert::provider_messages_from_conversation(
+ self.tool_dispatcher.as_ref(),
+ &self.history,
+ );
// Multimodal prep (parity with the legacy engine): rehydrate image
// placeholders for vision-capable providers, then expand `[IMAGE:…]` /
@@ -286,7 +289,10 @@ impl Agent {
if self.history.last().is_some_and(is_empty_assistant_chat) {
self.history.pop();
}
- let base = self.tool_dispatcher.to_provider_messages(&self.history);
+ let base = crate::agent::message_convert::provider_messages_from_conversation(
+ self.tool_dispatcher.as_ref(),
+ &self.history,
+ );
let (summary, summary_usage) = self
.summarize_turn_wrapup(
&base,
@@ -474,7 +480,10 @@ impl Agent {
subagents: subagent_usage_entries,
});
- let mut persisted = self.tool_dispatcher.to_provider_messages(&self.history);
+ let mut persisted = crate::agent::message_convert::provider_messages_from_conversation(
+ self.tool_dispatcher.as_ref(),
+ &self.history,
+ );
// Re-attach per-call failure outcomes (dropped when the engine folded
// each tool result into a `role:"tool"` message) so the derived
// transcript view renders failed tools as errors, not successes.
diff --git a/crates/openhuman-core/src/agent/harness/session/turn/mod.rs b/crates/openhuman-core/src/agent/harness/session/turn/mod.rs
index 3b629f41c2..6e77f66d98 100644
--- a/crates/openhuman-core/src/agent/harness/session/turn/mod.rs
+++ b/crates/openhuman-core/src/agent/harness/session/turn/mod.rs
@@ -8,7 +8,7 @@ mod recall_lanes;
mod session_io;
mod tools;
-use crate::agent::tool_dialect::ParsedToolCall;
+use tinytools_agent::ParsedToolCall;
use std::borrow::Cow;
@@ -59,7 +59,7 @@ pub(super) fn normalize_tool_call<'a>(call: &'a ParsedToolCall) -> Cow<'a, Parse
Cow::Owned(ParsedToolCall {
name: skill_id.to_string(),
arguments: serde_json::Value::Object(inputs.clone()),
- tool_call_id: call.tool_call_id.clone(),
+ id: call.id.clone(),
})
}
diff --git a/crates/openhuman-core/src/agent/harness/session/turn/session_io/wrapup.rs b/crates/openhuman-core/src/agent/harness/session/turn/session_io/wrapup.rs
index 4a8a624a3c..fe95de6fa2 100644
--- a/crates/openhuman-core/src/agent/harness/session/turn/session_io/wrapup.rs
+++ b/crates/openhuman-core/src/agent/harness/session/turn/session_io/wrapup.rs
@@ -107,10 +107,12 @@ impl Agent {
// some providers only preserve one of those representations.
let parsed_call_count = |candidate: &str| {
self.tool_dispatcher
- .parse_response(&ChatResponse {
- text: Some(candidate.to_string()),
- ..ChatResponse::default()
- })
+ .parse_response(
+ &crate::agent::message_convert::dialect_response_from_provider(&ChatResponse {
+ text: Some(candidate.to_string()),
+ ..ChatResponse::default()
+ }),
+ )
.1
.len()
};
@@ -244,7 +246,10 @@ impl Agent {
// model sees exactly what it left out. Run silently: we validate the
// result before deciding whether/what to show, so a malformed attempt is
// never streamed to the client.
- let mut base = self.tool_dispatcher.to_provider_messages(&self.history);
+ let mut base = crate::agent::message_convert::provider_messages_from_conversation(
+ self.tool_dispatcher.as_ref(),
+ &self.history,
+ );
base.push(ChatMessage::user(ro::repair_instruction(contract)));
let (repair_text, usage) = self
.silent_completion(&base, effective_model, "required-output re-prompt")
diff --git a/crates/openhuman-core/src/agent/harness/session/turn/tools.rs b/crates/openhuman-core/src/agent/harness/session/turn/tools.rs
index d1e43b5167..5ae23b0872 100644
--- a/crates/openhuman-core/src/agent/harness/session/turn/tools.rs
+++ b/crates/openhuman-core/src/agent/harness/session/turn/tools.rs
@@ -90,7 +90,9 @@ impl Agent {
session_id: self.event_session_id().to_string(),
channel: self.event_channel().to_string(),
connected_integrations: self.connected_integrations.clone(),
- tool_call_format: self.tool_dispatcher.tool_call_format(),
+ tool_call_format: crate::agent::prompts::tool_call_format_from_dialect(
+ self.tool_dispatcher.tool_call_format(),
+ ),
session_key: self.session_key.clone(),
session_parent_prefix: self.session_parent_prefix.clone(),
on_progress: self.on_progress.clone(),
diff --git a/crates/openhuman-core/src/agent/harness/session/turn_auto_recall_tests.rs b/crates/openhuman-core/src/agent/harness/session/turn_auto_recall_tests.rs
index b2c0b38030..e1ddce4a7b 100644
--- a/crates/openhuman-core/src/agent/harness/session/turn_auto_recall_tests.rs
+++ b/crates/openhuman-core/src/agent/harness/session/turn_auto_recall_tests.rs
@@ -122,7 +122,7 @@ fn make_agent_with_auto_recall(
.tools(vec![])
.memory(mem)
.auto_recall(auto_recall)
- .tool_dispatcher(Box::new(XmlToolDispatcher))
+ .tool_dispatcher(Box::new(XmlDialect))
.config(crate::config::AgentConfig::default())
.context_config(crate::config::ContextConfig::default())
.workspace_dir(workspace_path)
diff --git a/crates/openhuman-core/src/agent/harness/session/turn_checkpoint.rs b/crates/openhuman-core/src/agent/harness/session/turn_checkpoint.rs
index 55efea85e8..734a26bfec 100644
--- a/crates/openhuman-core/src/agent/harness/session/turn_checkpoint.rs
+++ b/crates/openhuman-core/src/agent/harness/session/turn_checkpoint.rs
@@ -10,7 +10,7 @@ pub(crate) fn assistant_message_has_tool_calls(msg: &ChatMessage) -> bool {
// CodeRabbit follow-up: only treat this as the native tool_calls envelope
// when the full expected shape is present:
// - top-level JSON object
- // - `content` key present (the envelope `tool_dialect.rs` emits — see
+ // - `content` key present (the canonical native dialect emits — see
// `to_provider_messages`)
// - non-empty `tool_calls` array whose every element carries an `id`
// string, a `name` string, and an `arguments` field
diff --git a/crates/openhuman-core/src/agent/harness/session/turn_checkpoint_and_wrapup_tests.rs b/crates/openhuman-core/src/agent/harness/session/turn_checkpoint_and_wrapup_tests.rs
index 5fa3541918..12bce45fce 100644
--- a/crates/openhuman-core/src/agent/harness/session/turn_checkpoint_and_wrapup_tests.rs
+++ b/crates/openhuman-core/src/agent/harness/session/turn_checkpoint_and_wrapup_tests.rs
@@ -231,7 +231,7 @@ async fn turn_checkpoint_rejects_pformat_wrapup_without_streaming_it() {
..crate::config::AgentConfig::default()
},
crate::config::ContextConfig::default(),
- Box::new(PFormatToolDispatcher::new(registry)),
+ Box::new(PFormatDialect::new(registry)),
);
let (progress_tx, mut progress_rx) = tokio::sync::mpsc::channel(16);
agent.set_on_progress(Some(progress_tx));
@@ -559,7 +559,7 @@ async fn dedicated_profile_experience_recall_merges_shared_legacy_store() {
.tools(vec![])
.memory(dedicated)
.shared_experience_memory(Some(shared))
- .tool_dispatcher(Box::new(XmlToolDispatcher))
+ .tool_dispatcher(Box::new(XmlDialect))
.workspace_dir(tmp.path().to_path_buf())
.event_context("profile-experience-test", "web_chat")
.active_profile_id(Some("alice".into()))
diff --git a/crates/openhuman-core/src/agent/harness/session/turn_history_and_context_tests.rs b/crates/openhuman-core/src/agent/harness/session/turn_history_and_context_tests.rs
index d8a5be7c27..6a3865a2c6 100644
--- a/crates/openhuman-core/src/agent/harness/session/turn_history_and_context_tests.rs
+++ b/crates/openhuman-core/src/agent/harness/session/turn_history_and_context_tests.rs
@@ -533,7 +533,7 @@ async fn turn_triggers_configured_memory_agent_before_parent_prompt() {
.chat_model(provider)
.tools(vec![Box::new(EchoTool)])
.memory(mem)
- .tool_dispatcher(Box::new(XmlToolDispatcher))
+ .tool_dispatcher(Box::new(XmlDialect))
.config(crate::config::AgentConfig {
max_tool_iterations: 3,
max_history_messages: 10,
diff --git a/crates/openhuman-core/src/agent/harness/session/turn_learned_context_and_announcements_tests.rs b/crates/openhuman-core/src/agent/harness/session/turn_learned_context_and_announcements_tests.rs
index bc8e578876..a9ad695209 100644
--- a/crates/openhuman-core/src/agent/harness/session/turn_learned_context_and_announcements_tests.rs
+++ b/crates/openhuman-core/src/agent/harness/session/turn_learned_context_and_announcements_tests.rs
@@ -163,7 +163,7 @@ fn assistant_message_has_tool_calls_rejects_plain_text_reply() {
#[test]
fn assistant_message_has_tool_calls_rejects_envelope_without_content_field() {
// A bare `{"tool_calls": [...]}` JSON in the content (no `content` field)
- // is not the envelope `tool_dialect.rs` emits.
+ // is not the envelope the canonical native dialect emits.
let body = serde_json::json!({
"tool_calls": [{ "id": "tc-1", "name": "shell", "arguments": "{}" }]
})
@@ -505,7 +505,7 @@ fn make_agent_over_driver(
.chat_model(provider)
.tools(vec![])
.memory(mem)
- .tool_dispatcher(Box::new(XmlToolDispatcher))
+ .tool_dispatcher(Box::new(XmlDialect))
.config(crate::config::AgentConfig::default())
.context_config(crate::config::ContextConfig::default())
.workspace_dir(workspace_path)
diff --git a/crates/openhuman-core/src/agent/harness/session/turn_required_output_tests.rs b/crates/openhuman-core/src/agent/harness/session/turn_required_output_tests.rs
index d5c2ab72f1..6f3b951199 100644
--- a/crates/openhuman-core/src/agent/harness/session/turn_required_output_tests.rs
+++ b/crates/openhuman-core/src/agent/harness/session/turn_required_output_tests.rs
@@ -90,7 +90,7 @@ async fn turn_override_suppress_memory_agent_skips_memory_trigger() {
.chat_model(provider)
.tools(vec![Box::new(EchoTool)])
.memory(mem)
- .tool_dispatcher(Box::new(XmlToolDispatcher))
+ .tool_dispatcher(Box::new(XmlDialect))
.config(crate::config::AgentConfig {
max_tool_iterations: 3,
max_history_messages: 10,
diff --git a/crates/openhuman-core/src/agent/harness/session/turn_tests.rs b/crates/openhuman-core/src/agent/harness/session/turn_tests.rs
index 1c016e55c3..4cece550a3 100644
--- a/crates/openhuman-core/src/agent/harness/session/turn_tests.rs
+++ b/crates/openhuman-core/src/agent/harness/session/turn_tests.rs
@@ -4,7 +4,6 @@ use crate::agent::experience::{
};
use crate::agent::hooks::{PostTurnHook, TurnContext};
use crate::agent::messages::{ChatMessage, ConversationMessage};
-use crate::agent::tool_dialect::{PFormatToolDispatcher, ToolDispatcher, XmlToolDispatcher};
use crate::agent::tool_policy::{
GeneratedToolRuntimeContext, GeneratedToolRuntimeRisk, ToolPolicy, ToolPolicyDecision,
ToolPolicyRequest,
@@ -21,6 +20,7 @@ use tinyinference_llm::model::{
};
use tinytools::ToolResult;
use tinytools::{PermissionLevel, Tool};
+use tinytools_agent::dialect::{PFormatDialect, ToolDialect, XmlDialect};
use tokio::sync::Mutex as AsyncMutex;
use tokio::sync::Notify;
use tokio::time::{timeout, Duration};
@@ -410,7 +410,7 @@ fn make_agent_with_tool_sets(
.tools(tools)
.synthesized_tools(synthesized_tools)
.memory(mem)
- .tool_dispatcher(Box::new(XmlToolDispatcher))
+ .tool_dispatcher(Box::new(XmlDialect))
.workspace_dir(workspace_path)
.event_context("turn-test-session", "turn-test-channel")
.config(crate::config::AgentConfig {
@@ -438,7 +438,7 @@ fn make_agent_with_builder(
post_turn_hooks,
config,
context_config,
- Box::new(XmlToolDispatcher),
+ Box::new(XmlDialect),
)
}
@@ -448,7 +448,7 @@ fn make_agent_with_builder_and_dispatcher(
post_turn_hooks: Vec<Arc<dyn PostTurnHook>>,
config: crate::config::AgentConfig,
context_config: crate::config::ContextConfig,
- tool_dispatcher: Box<dyn ToolDispatcher>,
+ tool_dispatcher: Box<dyn ToolDialect>,
) -> Agent {
let workspace = tempfile::TempDir::new().expect("temp workspace");
let workspace_path = workspace.path().to_path_buf();
@@ -501,7 +501,7 @@ fn make_agent_with_memory(
.chat_model(Arc::new(DummyProvider))
.tools(vec![])
.memory(memory)
- .tool_dispatcher(Box::new(XmlToolDispatcher))
+ .tool_dispatcher(Box::new(XmlDialect))
.workspace_dir(workspace_dir)
.event_context("pref-test-session", "pref-test-channel")
.learning_enabled(learning_enabled)
diff --git a/crates/openhuman-core/src/agent/harness/session/types.rs b/crates/openhuman-core/src/agent/harness/session/types.rs
index dc0704bf06..f9f5f80bbc 100644
--- a/crates/openhuman-core/src/agent/harness/session/types.rs
+++ b/crates/openhuman-core/src/agent/harness/session/types.rs
@@ -14,13 +14,13 @@ use crate::agent::messages::{ChatMessage, ConversationMessage};
use crate::agent::progress::AgentProgress;
use crate::agent::prompts::SystemPromptBuilder;
use crate::agent::tinyagents::TurnModelSource;
-use crate::agent::tool_dialect::ToolDispatcher;
use crate::agent::tool_policy::ToolPolicy;
use crate::memory::Memory;
use crate::tools::agent_policy::ToolPolicySession;
use std::path::PathBuf;
use std::sync::Arc;
use tinytools::{Tool, ToolSpec};
+use tinytools_agent::dialect::ToolDialect;
/// Per-turn behaviour overrides applied to a **single** [`Agent::turn`] call.
///
@@ -161,7 +161,7 @@ pub struct Agent {
pub(super) auto_recall: Option<Arc<crate::memory::auto_recall::AutoRecall>>,
// `Arc` (not `Box`) so the tinyagents turn path can hold a cheap clone of
// the dispatcher without borrowing the `Agent` while session state mutates.
- pub(super) tool_dispatcher: Arc<dyn ToolDispatcher>,
+ pub(super) tool_dispatcher: Arc<dyn ToolDialect>,
pub(super) config: crate::config::AgentConfig,
pub(super) model_name: String,
/// User-configured vision capability for [`Self::model_name`], evaluated at
@@ -534,7 +534,7 @@ pub struct AgentBuilder {
/// Forwarded to [`Agent::auto_recall`] at build time. Defaults to `None`.
pub(super) auto_recall: Option<Arc<crate::memory::auto_recall::AutoRecall>>,
pub(super) prompt_builder: Option<SystemPromptBuilder>,
- pub(super) tool_dispatcher: Option<Box<dyn ToolDispatcher>>,
+ pub(super) tool_dispatcher: Option<Box<dyn ToolDialect>>,
pub(super) config: Option<crate::config::AgentConfig>,
/// Optional [`ContextConfig`] override threaded through from
/// `Agent::from_config`. When unset the builder falls back to
diff --git a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph/dispatch.rs b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph/dispatch.rs
index 7309d9b848..e0c76cde89 100644
--- a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph/dispatch.rs
+++ b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph/dispatch.rs
@@ -396,11 +396,16 @@ pub(in super::super) async fn run_subagent_via_graph(
// the typed `outcome.conversation` (messages-since-last-user) also avoids
// indexing a post-trim `outcome.history` with the pre-trim length, and the
// durable `[IMAGE:…]` markers stay put since the prior user turns are untouched.
- use crate::agent::tool_dialect::ToolDispatcher;
let suffix = if native_tools {
- crate::agent::tool_dialect::NativeToolDispatcher.to_provider_messages(&outcome.conversation)
+ crate::agent::message_convert::provider_messages_from_conversation(
+ &tinytools_agent::dialect::NativeDialect,
+ &outcome.conversation,
+ )
} else {
- crate::agent::tool_dialect::XmlToolDispatcher.to_provider_messages(&outcome.conversation)
+ crate::agent::message_convert::provider_messages_from_conversation(
+ &tinytools_agent::dialect::XmlDialect,
+ &outcome.conversation,
+ )
};
history.extend(suffix);
diff --git a/crates/openhuman-core/src/agent/harness/subagent_runner/tool_prep.rs b/crates/openhuman-core/src/agent/harness/subagent_runner/tool_prep.rs
index 1781d17f8c..64c71e941c 100644
--- a/crates/openhuman-core/src/agent/harness/subagent_runner/tool_prep.rs
+++ b/crates/openhuman-core/src/agent/harness/subagent_runner/tool_prep.rs
@@ -167,7 +167,7 @@ pub(super) fn select_actions_with_essentials(
/// Format the tool-use protocol block appended to the system prompt in text
/// mode. Teaches **P-Format** first (the same protocol
-/// [`crate::agent::tool_dialect::PFormatToolDispatcher`] renders and
+/// [`tinytools_agent::dialect::PFormatDialect`] renders and
/// the tinyagents adapter parses via `parse_tool_calls_with_pformat`), with
/// the legacy JSON-in-tag form as the documented fallback for nested
/// arguments. The `## Tools` catalogue already renders `Call as:` p-format
@@ -233,20 +233,18 @@ pub(crate) fn subagent_prompt_protocol(
text_mode: bool,
) -> (crate::agent::prompts::ToolCallFormat, String) {
use crate::agent::prompts::ToolCallFormat;
- use crate::agent::tool_dialect::{
- NativeToolDispatcher, PFormatToolDispatcher, ToolDispatcher, XmlToolDispatcher,
- };
+ use tinytools_agent::dialect::{NativeDialect, PFormatDialect, ToolDialect, XmlDialect};
use tinytools_agent::PFormatRegistry;
if text_mode {
return (ToolCallFormat::PFormat, String::new());
}
- let empty_tools: Vec<Box<dyn Tool>> = Vec::new();
+ let empty_tools = Vec::new();
let instructions = match parent_format {
ToolCallFormat::PFormat => {
- PFormatToolDispatcher::new(PFormatRegistry::new()).prompt_instructions(&empty_tools)
+ PFormatDialect::new(PFormatRegistry::new()).prompt_instructions(&empty_tools)
}
- ToolCallFormat::Native => NativeToolDispatcher.prompt_instructions(&empty_tools),
- ToolCallFormat::Json => XmlToolDispatcher.prompt_instructions(&empty_tools),
+ ToolCallFormat::Native => NativeDialect.prompt_instructions(&empty_tools),
+ ToolCallFormat::Json => XmlDialect.prompt_instructions(&empty_tools),
};
(parent_format, instructions)
}
diff --git a/crates/openhuman-core/src/agent/harness/tool_result_artifacts/mod.rs b/crates/openhuman-core/src/agent/harness/tool_result_artifacts/mod.rs
index ab0e34b7e1..3d4a385036 100644
--- a/crates/openhuman-core/src/agent/harness/tool_result_artifacts/mod.rs
+++ b/crates/openhuman-core/src/agent/harness/tool_result_artifacts/mod.rs
@@ -9,11 +9,11 @@
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
-use crate::agent::tool_dialect::ToolExecutionResult;
use crate::memory::safety::{sanitize_text, SanitizationReport, Sanitized};
use async_trait::async_trait;
use serde_json::Value;
use tinyagents_harness::store::Store;
+use tinytools_agent::dialect::ToolOutcome;
const ARTIFACT_ROOT: &str = "artifacts/tool-results";
@@ -507,7 +507,7 @@ pub(crate) async fn apply_per_result_persistence(
}
pub(crate) async fn spill_aggregate_tool_results(
- results: &mut [ToolExecutionResult],
+ results: &mut [ToolOutcome],
store: Option<&ToolResultArtifactStore>,
budget_bytes: usize,
) {
diff --git a/crates/openhuman-core/src/agent/harness/tool_result_artifacts/mod_tests.rs b/crates/openhuman-core/src/agent/harness/tool_result_artifacts/mod_tests.rs
index 3c13b2bd6a..afa8a4a78d 100644
--- a/crates/openhuman-core/src/agent/harness/tool_result_artifacts/mod_tests.rs
+++ b/crates/openhuman-core/src/agent/harness/tool_result_artifacts/mod_tests.rs
@@ -83,19 +83,19 @@ async fn aggregate_spills_largest_until_under_budget() {
let tmp = tempfile::tempdir().unwrap();
let store = ToolResultArtifactStore::new(tmp.path().to_path_buf(), "session");
let mut results = vec![
- ToolExecutionResult {
+ ToolOutcome {
name: "small".into(),
output: "a".repeat(100),
success: true,
tool_call_id: Some("small".into()),
},
- ToolExecutionResult {
+ ToolOutcome {
name: "largest".into(),
output: "b".repeat(2000),
success: true,
tool_call_id: Some("largest".into()),
},
- ToolExecutionResult {
+ ToolOutcome {
name: "medium".into(),
output: "c".repeat(900),
success: true,
@@ -120,19 +120,19 @@ async fn aggregate_forces_budget_when_envelope_has_no_savings() {
let tmp = tempfile::tempdir().unwrap();
let store = ToolResultArtifactStore::new(tmp.path().to_path_buf(), "session");
let mut results = vec![
- ToolExecutionResult {
+ ToolOutcome {
name: "one".into(),
output: "a".repeat(350),
success: true,
tool_call_id: Some("one".into()),
},
- ToolExecutionResult {
+ ToolOutcome {
name: "two".into(),
output: "b".repeat(350),
success: true,
tool_call_id: Some("two".into()),
},
- ToolExecutionResult {
+ ToolOutcome {
name: "three".into(),
output: "c".repeat(350),
success: true,
diff --git a/crates/openhuman-core/src/agent/message_convert.rs b/crates/openhuman-core/src/agent/message_convert.rs
index dcb49485ce..911f113f08 100644
--- a/crates/openhuman-core/src/agent/message_convert.rs
+++ b/crates/openhuman-core/src/agent/message_convert.rs
@@ -18,8 +18,103 @@ use tinyinference_llm::message::{
AssistantMessage, ContentBlock, ImageRef, Message, SystemMessage, ToolMessage, UserMessage,
};
use tinyinference_llm::tool::ToolCall as TaToolCall;
+use tinytools_agent::dialect::{
+ DialectMessage, DialectResponse, DialectRole, NativeToolCall, ToolDialect, ToolResultEntry,
+ TranscriptEntry,
+};
use crate::agent::messages::{ChatMessage, ConversationMessage, ToolResultMessage};
+use crate::inference::provider::{ChatResponse, ToolCall};
+
+/// Convert the host provider response at its boundary into the canonical
+/// dialect input. The dialect crate owns all parsing after this field-wise map.
+pub(crate) fn dialect_response_from_provider(response: &ChatResponse) -> DialectResponse {
+ DialectResponse {
+ text: response.text.clone(),
+ tool_calls: response
+ .tool_calls
+ .iter()
+ .map(|call| NativeToolCall {
+ id: call.id.clone(),
+ name: call.name.clone(),
+ arguments: call.arguments.clone(),
+ extra_content: call.extra_content.clone(),
+ })
+ .collect(),
+ }
+}
+
+/// Replay durable OpenHuman conversation records through a canonical dialect
+/// and return the provider's host message shape.
+pub(crate) fn provider_messages_from_conversation(
+ dialect: &dyn ToolDialect,
+ history: &[ConversationMessage],
+) -> Vec<ChatMessage> {
+ dialect
+ .to_provider_messages(
+ &history
+ .iter()
+ .map(conversation_to_transcript_entry)
+ .collect::<Vec<_>>(),
+ )
+ .into_iter()
+ .map(dialect_message_to_chat_message)
+ .collect()
+}
+
+fn conversation_to_transcript_entry(message: &ConversationMessage) -> TranscriptEntry {
+ match message {
+ ConversationMessage::Chat(chat) => TranscriptEntry::Chat(DialectMessage {
+ role: match chat.role.as_str() {
+ "system" => DialectRole::System,
+ "assistant" => DialectRole::Assistant,
+ "tool" => DialectRole::Tool,
+ _ => DialectRole::User,
+ },
+ content: chat.content.clone(),
+ extra_metadata: chat.extra_metadata.clone(),
+ }),
+ ConversationMessage::AssistantToolCalls {
+ text,
+ tool_calls,
+ reasoning_content,
+ extra_metadata,
+ } => TranscriptEntry::AssistantToolCalls {
+ text: text.clone(),
+ tool_calls: tool_calls
+ .iter()
+ .map(|call| NativeToolCall {
+ id: call.id.clone(),
+ name: call.name.clone(),
+ arguments: call.arguments.clone(),
+ extra_content: call.extra_content.clone(),
+ })
+ .collect(),
+ reasoning_content: reasoning_content.clone(),
+ extra_metadata: extra_metadata.clone(),
+ },
+ ConversationMessage::ToolResults(results) => TranscriptEntry::ToolResults(
+ results
+ .iter()
+ .map(|result| ToolResultEntry {
+ tool_call_id: result.tool_call_id.clone(),
+ content: result.content.clone(),
+ trusted_verbatim: false,
+ })
+ .collect(),
+ ),
+ }
+}
+
+fn dialect_message_to_chat_message(message: DialectMessage) -> ChatMessage {
+ ChatMessage {
+ id: None,
+ role: message.role.as_str().to_string(),
+ content: message.content,
+ extra_metadata: message.extra_metadata,
+ cache_breakpoints: Vec::new(),
+ }
+}
/// Key under which a thinking model's `reasoning_content` is echoed through
/// openhuman [`ChatMessage::extra_metadata`]. New harness transcripts carry
@@ -62,7 +157,7 @@ fn reasoning_extra_metadata(content: &[ContentBlock]) -> Option<serde_json::Valu
/// Convert one openhuman [`ChatMessage`] into a harness [`Message`].
///
/// Role strings map onto the typed arms. A seeded **native** tool round is
-/// serialized by [`NativeToolDispatcher::to_provider_messages`] as a
+/// serialized by [`NativeDialect::to_provider_messages`] as a
/// `{ "content", "tool_calls" }` assistant envelope followed by
/// `{ "tool_call_id", "content" }` tool envelopes; we unwrap those back into the
/// structured [`AssistantMessage::tool_calls`] / [`ToolMessage::tool_call_id`]
@@ -226,7 +321,7 @@ fn data_uri_mime(reference: &str) -> Option<String> {
}
/// Parse a native assistant tool-call envelope (`{ "content", "tool_calls" }`, as
-/// [`NativeToolDispatcher::to_provider_messages`] emits) back into its inner
+/// [`NativeDialect::to_provider_messages`] emits) back into its inner
/// visible text and structured [`TaToolCall`]s. Returns `None` when `text` is not
/// such an envelope (plain assistant prose), so the caller can fall back to text.
fn parse_native_assistant_envelope(text: &str) -> Option<(String, Vec<TaToolCall>)> {
diff --git a/crates/openhuman-core/src/agent/mod.rs b/crates/openhuman-core/src/agent/mod.rs
index 45ed9fb06b..046a5db05e 100644
--- a/crates/openhuman-core/src/agent/mod.rs
+++ b/crates/openhuman-core/src/agent/mod.rs
@@ -13,8 +13,8 @@
//! specialized agents (Orchestrator, Code Executor, Researcher, etc.).
//! - **[`triage`]**: A high-performance pipeline for classifying and responding
//! to external triggers (webhooks, cron jobs) using small local models.
-//! - **[`dispatcher`]**: Pluggable strategies for how tool calls are formatted
-//! in prompts and parsed from responses (XML, JSON, P-Format).
+//! - **`tinytools_agent::dialect`**: Canonical strategies for formatting and
+//! parsing tool calls (XML, JSON, P-Format).
//! - **[`harness::subagent_runner`]**: Logic for spawning "sub-agents" from
//! within a parent agent's tool loop, enabling hierarchical delegation.
pub mod artifacts;
@@ -66,7 +66,6 @@ pub mod task_dispatcher;
pub(crate) mod task_session;
pub mod tinyagents;
pub mod todos;
-pub mod tool_dialect;
pub mod tool_policy;
pub mod tools;
pub mod triage;
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/spawn_parallel_agents_tests.rs b/crates/openhuman-core/src/agent/orchestration/tools/spawn_parallel_agents_tests.rs
index 2ccd75ad19..ee33be98d6 100644
--- a/crates/openhuman-core/src/agent/orchestration/tools/spawn_parallel_agents_tests.rs
+++ b/crates/openhuman-core/src/agent/orchestration/tools/spawn_parallel_agents_tests.rs
@@ -10,7 +10,6 @@ use crate::agent::orchestration::spawn_parallel_graph::{
WorkerDispatchMode,
};
use crate::agent::prompts::ToolCallFormat;
-use crate::agent::tool_dialect::NativeToolDispatcher;
use crate::agent::Agent;
use crate::config::AgentConfig;
use crate::memory::{Memory, MemoryCategory, MemoryEntry, NamespaceSummary, RecallOpts};
@@ -27,6 +26,7 @@ use tinyinference_llm::model::{ChatModel, ModelProfile, ModelRequest, ModelRespo
use tinyinference_llm::tool::ToolCall;
use tinytools::ToolTimeout;
use tinytools::{PermissionLevel, Tool, ToolResult};
+use tinytools_agent::dialect::NativeDialect;
use tokio::time::{sleep, timeout, Duration};
const PARENT_PROMPT_CANARY: &str = "parallel-fanout-e2e-canary";
@@ -517,7 +517,7 @@ async fn agent_turn_runs_long_parallel_subagent_flow_with_many_nested_tool_calls
.chat_model(Arc::new(provider.clone()))
.tools(tools)
.memory(mem)
- .tool_dispatcher(Box::new(NativeToolDispatcher))
+ .tool_dispatcher(Box::new(NativeDialect))
.workspace_dir(workspace_path)
.build()
.unwrap();
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent.rs b/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent.rs
index 97cdb3a66c..bc8334b777 100644
--- a/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent.rs
+++ b/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent.rs
@@ -30,7 +30,7 @@ use tinytools::{PermissionLevel, Tool, ToolCallOptions, ToolResult};
/// Spawns a sub-agent of the requested type to handle a delegated task.
///
/// Registered into the parent agent's tool list by
-/// [`crate::tools::all_tools_with_runtime`]. The orchestrator
+/// [`crate::tools::ops::all_tools_with_runtime`]. The orchestrator
/// archetype's tool whitelist already includes `spawn_subagent`, so
/// orchestrated runs see it; non-orchestrator parents see it too unless
/// explicitly removed.
diff --git a/crates/openhuman-core/src/agent/prompts/mod_tests_user_files_reflections_tests.rs b/crates/openhuman-core/src/agent/prompts/mod_tests_user_files_reflections_tests.rs
index f07f94d447..20387d6a2c 100644
--- a/crates/openhuman-core/src/agent/prompts/mod_tests_user_files_reflections_tests.rs
+++ b/crates/openhuman-core/src/agent/prompts/mod_tests_user_files_reflections_tests.rs
@@ -541,7 +541,7 @@ fn tools_section_nonempty_for_pformat() {
#[test]
fn tools_section_native_with_dispatcher_instructions_returns_instructions() {
// Native mode must still include non-empty dispatcher_instructions
- // (e.g. the "## Tool Use Protocol" block from NativeToolDispatcher) so
+ // (e.g. the "## Tool Use Protocol" block from NativeDialect) so
// the model receives behavioural guidance even though the tool catalogue
// itself is omitted.
let tools: Vec<Box<dyn Tool>> = vec![Box::new(TestTool)];
diff --git a/crates/openhuman-core/src/agent/prompts/sections.rs b/crates/openhuman-core/src/agent/prompts/sections.rs
index e4b08cd372..70663e5e95 100644
--- a/crates/openhuman-core/src/agent/prompts/sections.rs
+++ b/crates/openhuman-core/src/agent/prompts/sections.rs
@@ -368,7 +368,7 @@ impl PromptSection for ToolsSection {
// schemas in the API request — no need to repeat the tool catalogue
// in the system prompt (pure token bloat). However, any non-empty
// `dispatcher_instructions` (e.g. the "## Tool Use Protocol" block
- // from NativeToolDispatcher) must still be included so the model
+ // from NativeDialect) must still be included so the model
// receives its behavioural guidance.
if ctx.tool_call_format == ToolCallFormat::Native {
if ctx.dispatcher_instructions.trim().is_empty() {
diff --git a/crates/openhuman-core/src/agent/prompts/types.rs b/crates/openhuman-core/src/agent/prompts/types.rs
index 04d5558c08..240db19866 100644
--- a/crates/openhuman-core/src/agent/prompts/types.rs
+++ b/crates/openhuman-core/src/agent/prompts/types.rs
@@ -295,6 +295,18 @@ pub enum ToolCallFormat {
Native,
}
+/// Map the canonical dialect's catalogue spelling onto the host prompt wire
+/// vocabulary at the prompt boundary.
+pub(crate) fn tool_call_format_from_dialect(
+ format: tinytools_agent::dialect::ToolCallFormat,
+) -> ToolCallFormat {
+ match format {
+ tinytools_agent::dialect::ToolCallFormat::PFormat => ToolCallFormat::PFormat,
+ tinytools_agent::dialect::ToolCallFormat::Json => ToolCallFormat::Json,
+ tinytools_agent::dialect::ToolCallFormat::Native => ToolCallFormat::Native,
+ }
+}
+
// ─────────────────────────────────────────────────────────────────────────────
// Authenticated user identity
// ─────────────────────────────────────────────────────────────────────────────
diff --git a/crates/openhuman-core/src/agent/schemas.rs b/crates/openhuman-core/src/agent/schemas.rs
index 3bd8ea0f76..d0421f1a4f 100644
--- a/crates/openhuman-core/src/agent/schemas.rs
+++ b/crates/openhuman-core/src/agent/schemas.rs
@@ -493,8 +493,8 @@ fn handle_graph_topologies(_params: Map<String, Value>) -> ControllerFuture {
/// * **Model** — the static cost catalog projection
/// (`cost::catalog::tinyagents_catalog_snapshot`); carries model id, aliases,
/// provider/mode tags.
-/// * **Tool** — the baseline tool registry (`tools::default_tools`); names +
-/// descriptions. NOTE: the *full* per-agent tool surface (`tools::all_tools`)
+/// * **Tool** — the baseline tool registry (`tools::ops::default_tools`); names +
+/// descriptions. NOTE: the *full* per-agent tool surface (`tools::ops::all_tools`)
/// needs config/memory/audit/action-dir wiring that only exists inside a turn,
/// so only the baseline set is projected here. Deferred — see `deferred` in
/// the response and the migration follow-up.
diff --git a/crates/openhuman-core/src/agent/tool_dialect.rs b/crates/openhuman-core/src/agent/tool_dialect.rs
deleted file mode 100644
index 7e1d93cdd7..0000000000
--- a/crates/openhuman-core/src/agent/tool_dialect.rs
+++ /dev/null
@@ -1,456 +0,0 @@
-//! Tool dialects — OpenHuman's adapter over
-//! [`tinytools_agent::dialect`].
-//!
-//! The dialects themselves moved to the crate: how a model is told to ask for a
-//! tool, how it is parsed when it does, how results are rendered back, and how
-//! a transcript is replayed onto the provider wire so the next iteration is
-//! well-formed. None of that is OpenHuman-specific, and keeping a second copy
-//! of it here is how a catalogue and its parser drift apart.
-//!
-//! # What stayed
-//!
-//! Two things, both of them vocabulary.
-//!
-//! First, the **types**. [`ParsedToolCall`] and [`ToolExecutionResult`] are
-//! named and shaped for ~190 call sites across the harness, and
-//! [`ConversationMessage`] is the durable JSONL record existing installations
-//! already have on disk. The crate speaks its own thin
-//! [`TranscriptEntry`](tinytools_agent::dialect::TranscriptEntry)
-//! instead, so the conversions below are the seam — a handful of field-wise
-//! maps that keep the wire bytes identical while the logic lives upstream.
-//!
-//! Second, the **[`Tool`] trait object**. The crate takes shared
-//! [`ToolSpec`] values, never a host's concrete tool type, for the reason the
-//! parse seam already documents: a crate that depended on OpenHuman's `Tool`
-//! could not be used by a second host. So
-//! [`ToolDispatcher::prompt_instructions`] reads names and schemas off the
-//! slice and hands the crate exactly what it needs.
-//!
-//! # What did not move, and will not
-//!
-//! Executing a tool. The security policy, the approval gate, the sandbox, the
-//! per-call timeout, the progress events — those are OpenHuman's, and a dialect
-//! never decides what is *allowed to happen*, only what the model reads and
-//! writes. That line is what keeps the policy auditable in one place.
-
-use crate::agent::messages::{ChatMessage, ConversationMessage, ToolResultMessage};
-use crate::agent::prompts::ToolCallFormat;
-use crate::inference::provider::{ChatResponse, ToolCall};
-use serde_json::Value;
-use tinytools::{Tool, ToolSpec};
-use tinytools_agent::dialect::{
- DialectMessage, DialectResponse, DialectRole, NativeDialect, NativeToolCall, PFormatDialect,
- ToolDialect, ToolOutcome, ToolResultEntry, TranscriptEntry, XmlDialect,
-};
-use tinytools_agent::PFormatRegistry;
-
-/// A parsed tool call representation after being extracted from an LLM response.
-#[derive(Debug, Clone)]
-pub struct ParsedToolCall {
- /// The name of the tool to be invoked.
- pub name: String,
- /// The arguments passed to the tool, as a JSON object.
- pub arguments: Value,
- /// An optional unique identifier for the tool call, provided by native APIs.
- pub tool_call_id: Option<String>,
-}
-
-/// The result of executing a tool call, formatted for the LLM.
-#[derive(Debug, Clone)]
-pub struct ToolExecutionResult {
- /// The name of the tool that was executed.
- pub name: String,
- /// The output of the tool execution as a string.
- pub output: String,
- /// Whether the tool execution was successful.
- pub success: bool,
- /// The tool call ID that generated this result.
- pub tool_call_id: Option<String>,
-}
-
-/// Trait defining how an agent interacts with an LLM for tool use.
-///
-/// Different LLMs have different "dialects" for calling tools. The dispatcher
-/// abstracts these differences, allowing the agent loop to remain agnostic of
-/// the specific formatting required by the provider.
-///
-/// Each implementation below is a thin projection of one
-/// [`ToolDialect`] into OpenHuman's own vocabulary.
-pub trait ToolDispatcher: Send + Sync {
- /// Parse the LLM response to extract narrative text and any tool calls.
- fn parse_response(&self, response: &ChatResponse) -> (String, Vec<ParsedToolCall>);
-
- /// Format tool execution results into a message suitable for the next LLM turn.
- fn format_results(&self, results: &[ToolExecutionResult]) -> ConversationMessage;
-
- /// Provide instructions for the system prompt on how the model should call tools.
- fn prompt_instructions(&self, tools: &[Box<dyn Tool>]) -> String;
-
- /// Provide instructions from already-filtered tool specs when a dispatcher
- /// embeds the tool catalogue in its prompt protocol.
- fn prompt_instructions_for_specs(&self, _specs: &[ToolSpec]) -> Option<String> {
- None
- }
-
- /// Convert internal conversation history into provider-specific messages.
- fn to_provider_messages(&self, history: &[ConversationMessage]) -> Vec<ChatMessage>;
-
- /// Whether the dispatcher requires tool specifications to be sent in the API request.
- fn should_send_tool_specs(&self) -> bool;
-
- /// Tell the prompt builder how to render each tool entry in the
- /// `## Tools` section. Defaults to [`ToolCallFormat::Json`] for
- /// dispatchers that haven't opted in.
- fn tool_call_format(&self) -> ToolCallFormat {
- ToolCallFormat::Json
- }
-}
-
-// ─────────────────────────────────────────────────────────────────────────────
-// The seam: OpenHuman vocabulary ↔ crate vocabulary
-//
-// Every function here is field-wise and lossless in the direction it is used.
-// If one of them ever needs a judgement call, that judgement belongs in the
-// crate — a conversion that decides something is a second implementation
-// wearing a disguise.
-// ─────────────────────────────────────────────────────────────────────────────
-
-/// Project a provider response into the shape a dialect reads.
-fn to_dialect_response(response: &ChatResponse) -> DialectResponse {
- DialectResponse {
- text: response.text.clone(),
- tool_calls: response.tool_calls.iter().map(to_native_call).collect(),
- }
-}
-
-fn to_native_call(call: &ToolCall) -> NativeToolCall {
- NativeToolCall {
- id: call.id.clone(),
- name: call.name.clone(),
- arguments: call.arguments.clone(),
- extra_content: call.extra_content.clone(),
- }
-}
-
-fn from_native_call(call: &NativeToolCall) -> ToolCall {
- ToolCall {
- id: call.id.clone(),
- name: call.name.clone(),
- arguments: call.arguments.clone(),
- extra_content: call.extra_content.clone(),
- }
-}
-
-fn from_parsed_calls(calls: Vec<tinytools_agent::ParsedToolCall>) -> Vec<ParsedToolCall> {
- calls
- .into_iter()
- .map(|call| ParsedToolCall {
- name: call.name,
- arguments: call.arguments,
- tool_call_id: call.id,
- })
- .collect()
-}
-
-fn to_outcomes(results: &[ToolExecutionResult]) -> Vec<ToolOutcome> {
- results
- .iter()
- .map(|result| ToolOutcome {
- name: result.name.clone(),
- output: result.output.clone(),
- success: result.success,
- tool_call_id: result.tool_call_id.clone(),
- trusted_verbatim: false,
- })
- .collect()
-}
-
-/// Project one durable OpenHuman record onto the crate's transcript entry.
-fn to_transcript_entry(message: &ConversationMessage) -> TranscriptEntry {
- match message {
- ConversationMessage::Chat(chat) => TranscriptEntry::Chat(to_dialect_message(chat)),
- ConversationMessage::AssistantToolCalls {
- text,
- tool_calls,
- reasoning_content,
- extra_metadata,
- } => TranscriptEntry::AssistantToolCalls {
- text: text.clone(),
- tool_calls: tool_calls.iter().map(to_native_call).collect(),
- reasoning_content: reasoning_content.clone(),
- extra_metadata: extra_metadata.clone(),
- },
- ConversationMessage::ToolResults(results) => TranscriptEntry::ToolResults(
- results
- .iter()
- .map(|result| ToolResultEntry {
- tool_call_id: result.tool_call_id.clone(),
- content: result.content.clone(),
- trusted_verbatim: false,
- })
- .collect(),
- ),
- }
-}
-
-fn to_transcript(history: &[ConversationMessage]) -> Vec<TranscriptEntry> {
- history.iter().map(to_transcript_entry).collect()
-}
-
-fn from_transcript_entry(entry: TranscriptEntry) -> ConversationMessage {
- match entry {
- TranscriptEntry::Chat(message) => ConversationMessage::Chat(from_dialect_message(message)),
- TranscriptEntry::AssistantToolCalls {
- text,
- tool_calls,
- reasoning_content,
- extra_metadata,
- } => ConversationMessage::AssistantToolCalls {
- text,
- tool_calls: tool_calls.iter().map(from_native_call).collect(),
- reasoning_content,
- extra_metadata,
- },
- TranscriptEntry::ToolResults(results) => ConversationMessage::ToolResults(
- results
- .into_iter()
- .map(|result| ToolResultMessage {
- tool_call_id: result.tool_call_id,
- content: result.content,
- })
- .collect(),
- ),
- }
-}
-
-fn to_dialect_message(message: &ChatMessage) -> DialectMessage {
- // `role` is a free-form string in the durable record; anything the crate
- // does not model is a `user` turn, which is what every provider treats an
- // unrecognized role as anyway.
- let role = match message.role.as_str() {
- "system" => DialectRole::System,
- "assistant" => DialectRole::Assistant,
- "tool" => DialectRole::Tool,
- _ => DialectRole::User,
- };
- DialectMessage {
- role,
- content: message.content.clone(),
- extra_metadata: message.extra_metadata.clone(),
- }
-}
-
-fn from_dialect_message(message: DialectMessage) -> ChatMessage {
- ChatMessage {
- id: None,
- role: message.role.as_str().to_string(),
- content: message.content,
- extra_metadata: message.extra_metadata,
- cache_breakpoints: Vec::new(),
- }
-}
-
-fn specs_from_tools(tools: &[Box<dyn Tool>]) -> Vec<ToolSpec> {
- tools.iter().map(|tool| tool.spec()).collect()
-}
-
-fn from_format(format: tinytools_agent::dialect::ToolCallFormat) -> ToolCallFormat {
- use tinytools_agent::dialect::ToolCallFormat as Crate;
- match format {
- Crate::PFormat => ToolCallFormat::PFormat,
- Crate::Json => ToolCallFormat::Json,
- Crate::Native => ToolCallFormat::Native,
- }
-}
-
-/// Shared body of every `ToolDispatcher` impl below: convert in, delegate,
-/// convert out. Written once as functions rather than repeated per dispatcher
-/// so a new dialect is a `impl ToolDispatcher` of five one-line forwards.
-fn dispatch_parse(
- dialect: &dyn ToolDialect,
- response: &ChatResponse,
-) -> (String, Vec<ParsedToolCall>) {
- let (text, calls) = dialect.parse_response(&to_dialect_response(response));
- (text, from_parsed_calls(calls))
-}
-
-fn dispatch_format_results(
- dialect: &dyn ToolDialect,
- results: &[ToolExecutionResult],
-) -> ConversationMessage {
- let entries = dialect.format_results(&to_outcomes(results));
- debug_assert_eq!(
- entries.len(),
- 1,
- "OpenHuman tool results must remain a single conversation message"
- );
- from_transcript_entry(
- entries
- .into_iter()
- .next()
- .expect("tool result formatting must produce a message"),
- )
-}
-
-fn dispatch_provider_messages(
- dialect: &dyn ToolDialect,
- history: &[ConversationMessage],
-) -> Vec<ChatMessage> {
- dialect
- .to_provider_messages(&to_transcript(history))
- .into_iter()
- .map(from_dialect_message)
- .collect()
-}
-
-// ─────────────────────────────────────────────────────────────────────────────
-// The three dispatchers
-// ─────────────────────────────────────────────────────────────────────────────
-
-/// Legacy dispatcher using XML-style tags (`<tool_call>`) with JSON bodies.
-///
-/// This is robust and works well with models that aren't natively trained for
-/// tool calling but can follow instructions in a system prompt.
-#[derive(Default)]
-pub struct XmlToolDispatcher;
-
-impl XmlToolDispatcher {
- /// Extract serializable specs for all tools in the registry.
- pub fn tool_specs(tools: &[Box<dyn Tool>]) -> Vec<ToolSpec> {
- tools.iter().map(|tool| tool.spec()).collect()
- }
-
- /// Render the protocol block plus the full-schema catalogue.
- pub fn prompt_instructions_from_specs(specs: &[ToolSpec]) -> String {
- XmlDialect::instructions(specs)
- }
-
- /// Internal helper to extract tool calls from a raw text string.
- #[cfg(test)]
- pub(crate) fn parse_tool_calls_from_text(response: &str) -> (String, Vec<ParsedToolCall>) {
- let (text, calls) = XmlDialect::parse_text(response);
- (text, from_parsed_calls(calls))
- }
-}
-
-impl ToolDispatcher for XmlToolDispatcher {
- fn parse_response(&self, response: &ChatResponse) -> (String, Vec<ParsedToolCall>) {
- dispatch_parse(&XmlDialect, response)
- }
-
- fn format_results(&self, results: &[ToolExecutionResult]) -> ConversationMessage {
- dispatch_format_results(&XmlDialect, results)
- }
-
- fn prompt_instructions(&self, tools: &[Box<dyn Tool>]) -> String {
- XmlDialect::instructions(&specs_from_tools(tools))
- }
-
- fn prompt_instructions_for_specs(&self, specs: &[ToolSpec]) -> Option<String> {
- Some(Self::prompt_instructions_from_specs(specs))
- }
-
- fn to_provider_messages(&self, history: &[ConversationMessage]) -> Vec<ChatMessage> {
- dispatch_provider_messages(&XmlDialect, history)
- }
-
- fn should_send_tool_specs(&self) -> bool {
- XmlDialect.should_send_tool_specs()
- }
-
- fn tool_call_format(&self) -> ToolCallFormat {
- from_format(XmlDialect.tool_call_format())
- }
-}
-
-/// Text-based dispatcher that emits and parses **P-Format** ("Parameter
-/// Format") tool calls — the compact `tool_name[arg1|arg2|...]` syntax.
-///
-/// P-format is designed to significantly reduce token usage compared to JSON.
-/// It uses positional arguments based on an alphabetical sort of the tool's
-/// parameters, and falls back to the JSON-in-tag parser per tag so a model that
-/// mixes the two forms is still understood.
-pub struct PFormatToolDispatcher {
- dialect: PFormatDialect,
-}
-
-impl PFormatToolDispatcher {
- /// Create a new P-Format dispatcher with the given tool registry.
- pub fn new(registry: PFormatRegistry) -> Self {
- Self {
- dialect: PFormatDialect::new(registry),
- }
- }
-}
-
-impl ToolDispatcher for PFormatToolDispatcher {
- fn parse_response(&self, response: &ChatResponse) -> (String, Vec<ParsedToolCall>) {
- dispatch_parse(&self.dialect, response)
- }
-
- fn format_results(&self, results: &[ToolExecutionResult]) -> ConversationMessage {
- dispatch_format_results(&self.dialect, results)
- }
-
- fn prompt_instructions(&self, _tools: &[Box<dyn Tool>]) -> String {
- // Protocol description ONLY — the catalogue is rendered by the upstream
- // `ToolsSection`, from the same schemas this dialect parses against.
- PFormatDialect::instructions()
- }
-
- fn to_provider_messages(&self, history: &[ConversationMessage]) -> Vec<ChatMessage> {
- dispatch_provider_messages(&self.dialect, history)
- }
-
- fn should_send_tool_specs(&self) -> bool {
- self.dialect.should_send_tool_specs()
- }
-
- fn tool_call_format(&self) -> ToolCallFormat {
- from_format(self.dialect.tool_call_format())
- }
-}
-
-/// Dispatcher for models with native, structured tool-calling support (e.g., OpenAI, Anthropic).
-///
-/// This dispatcher leverages the provider's built-in APIs for identifying and
-/// reporting tool calls, which is generally more reliable than text-based
-/// parsing. It still supports a text-based fallback for robustness against
-/// models that might "forget" to use the structured API, and drops half-finished
-/// tool cycles while serializing so a bisected transcript cannot trip the
-/// provider's 400 (TAURI-RUST-7) — see
-/// [`pair_tool_cycles`](tinytools_agent::dialect::pair_tool_cycles).
-pub struct NativeToolDispatcher;
-
-impl ToolDispatcher for NativeToolDispatcher {
- fn parse_response(&self, response: &ChatResponse) -> (String, Vec<ParsedToolCall>) {
- dispatch_parse(&NativeDialect, response)
- }
-
- fn format_results(&self, results: &[ToolExecutionResult]) -> ConversationMessage {
- dispatch_format_results(&NativeDialect, results)
- }
-
- fn prompt_instructions(&self, _tools: &[Box<dyn Tool>]) -> String {
- NativeDialect.prompt_instructions(&[])
- }
-
- fn to_provider_messages(&self, history: &[ConversationMessage]) -> Vec<ChatMessage> {
- dispatch_provider_messages(&NativeDialect, history)
- }
-
- fn should_send_tool_specs(&self) -> bool {
- NativeDialect.should_send_tool_specs()
- }
-
- fn tool_call_format(&self) -> ToolCallFormat {
- from_format(NativeDialect.tool_call_format())
- }
-}
-
-#[cfg(test)]
-#[path = "pformat_tests.rs"]
-mod pformat_tests;
-#[cfg(test)]
-#[path = "dispatcher_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/bin/rss_bench.rs b/crates/openhuman-core/src/bin/rss_bench.rs
index dd38e7cc9d..c2f8c82aea 100644
--- a/crates/openhuman-core/src/bin/rss_bench.rs
+++ b/crates/openhuman-core/src/bin/rss_bench.rs
@@ -26,13 +26,13 @@
use anyhow::{Context, Result};
use async_trait::async_trait;
-use openhuman_core::agent::tool_dialect::NativeToolDispatcher;
use openhuman_core::agent::Agent;
use openhuman_core::memory::{Memory, MemoryCategory, MemoryEntry, NamespaceSummary, RecallOpts};
use openhuman_core::platform::proc_metrics::{
self, BenchReport, ProcSample, RosterResult, REPORT_SCHEMA_VERSION, RSS_BUDGET_KIB,
RSS_HARD_CAP_KIB,
};
+use openhuman_core::tinytools_agent::dialect::NativeDialect;
use tinytools::{Tool, ToolResult};
use std::path::PathBuf;
@@ -172,7 +172,7 @@ fn build_roster(n: usize) -> Result<Roster> {
.chat_model(Arc::new(MockModel))
.tools(vec![Box::new(EchoTool)])
.memory(memory)
- .tool_dispatcher(Box::new(NativeToolDispatcher))
+ .tool_dispatcher(Box::new(NativeDialect))
.model_name("bench-mock".into())
.agent_definition_name(format!("bench-{i}"))
.workspace_dir(path.clone())
diff --git a/crates/openhuman-core/src/channels/runtime/startup/start_channels.rs b/crates/openhuman-core/src/channels/runtime/startup/start_channels.rs
index f48b2d0aa9..491c44d32c 100644
--- a/crates/openhuman-core/src/channels/runtime/startup/start_channels.rs
+++ b/crates/openhuman-core/src/channels/runtime/startup/start_channels.rs
@@ -199,7 +199,7 @@ async fn start_channels_inner(mut config: Config) -> Result<()> {
let temperature = config.default_temperature;
// Build system prompt from workspace identity files + skills
let workspace = config.workspace_dir.clone();
- let tools_registry = Arc::new(tools::all_tools_with_runtime(
+ let tools_registry = Arc::new(tools::ops::all_tools_with_runtime(
Arc::new(config.clone()),
&security,
runtime,
diff --git a/crates/openhuman-core/src/runtime/node/ops.rs b/crates/openhuman-core/src/runtime/node/ops.rs
index f4da1b7618..2c52550265 100644
--- a/crates/openhuman-core/src/runtime/node/ops.rs
+++ b/crates/openhuman-core/src/runtime/node/ops.rs
@@ -93,7 +93,7 @@ pub fn build_runtime_tools(config: &Config) -> Result<Vec<Box<dyn Tool>>, String
)
.map_err(|e| e.to_string())?;
let runtime: Arc<dyn RuntimeAdapter> = Arc::new(NativeRuntime::new());
- trace!("[runtime_node::ops] build_runtime_tools: tools::all_tools_with_runtime");
+ trace!("[runtime_node::ops] build_runtime_tools: tools::ops::all_tools_with_runtime");
let built = tools::ops::all_tools_with_runtime(
Arc::new(config.clone()),
&security,
diff --git a/docs/specs/agent-runtime-upstream-boundary.md b/docs/specs/agent-runtime-upstream-boundary.md
index fcb3b5a519..e4259103ab 100644
--- a/docs/specs/agent-runtime-upstream-boundary.md
+++ b/docs/specs/agent-runtime-upstream-boundary.md
@@ -129,7 +129,7 @@ the labels remain useful for review and completion tracking:
| Package | Required result |
| --- | --- |
-| **A — direct imports and facade purge** | Import `tinytools-agent` directly; replace `dispatcher.rs` with the host-only `tool_dialect.rs` conversion seam, delete `pformat.rs`, production `harness/parse.rs` re-exports, `harness/instructions.rs`, `harness/tool_filter.rs`, `context/prompt.rs`, `registry/tools.rs`, the handoff wrapper, and behavior-free graph re-exports. |
+| **A — direct imports and facade purge** | Import `tinytools-agent` directly; delete `dispatcher.rs`, `pformat.rs`, `tool_dialect.rs`, production `harness/parse.rs` re-exports, `harness/instructions.rs`, `harness/tool_filter.rs`, `context/prompt.rs`, `registry/tools.rs`, the handoff wrapper, and behavior-free graph re-exports. |
| **B — TinyInference ownership** | Move max-token/default/profile decorators, route identity, typed usage/provider metadata, call correlation, and abort-on-drop stream behavior to `tinyinference-llm`. |
| **C — canonical tool vocabulary** | Use `tinytools::Tool`/`ToolResult` end to end; make the harness bridge canonical tool context into its loop; delete OpenHuman tool adapters and conversions. |
| **D — live host invocation** | Give `AgentHarness` a real `HostCapabilities`-driven entry point, wire all ten OpenHuman adapters, and replace correctness-sensitive task-locals with explicit recursively inherited `RunContext` data. |
@@ -160,9 +160,8 @@ All users import parsing APIs from `tinytools_agent::{...}` or
`tinytools_agent::dialect::{...}`. Delete
`tinyagents_harness::tool_calling`, the former OpenHuman `agent::dispatcher`
and `agent::pformat` facades, and any forwarding definitions. The retained
-`agent::tool_dialect` module is a host-owned conversion layer for OpenHuman's
-persisted transcript and provider types; it imports its protocol primitives
-directly from `tinytools_agent`.
+OpenHuman's persisted transcript and provider types are converted only at their
+concrete I/O boundaries; they do not define a dialect facade.
The same direct-import rule applies between TinyAgents crates. A harness,
registry, or graph module must not preserve a former path by publicly
@@ -271,7 +270,7 @@ all consumers import the owner directly, not that behavior is dropped.
| `triage/` | Keep | OpenHuman trigger business domain and RPC. It invokes the host-driven harness. |
| `bus.rs` | Keep | Process-wide OpenHuman bus registration. |
| `cost.rs` | Keep/Split | Keep pricing/tier accounting; model-call usage carrier and aggregation primitives move to inference/harness. |
-| `tool_dialect.rs` | Keep/Shrink | Retain only OpenHuman persisted-transcript/provider conversion; import `tinytools-agent::dialect` directly. |
+| `tool_dialect.rs` | Delete | Import `tinytools-agent::dialect` directly; keep only concrete I/O conversions. |
| `error.rs` | Keep/Shrink | Product-facing errors and RPC mapping only; loop/model/tool errors originate upstream. |
| `hooks.rs`, `stop_hooks.rs` | Keep adapter | Product hook policy; generic callback/control machinery is harness-owned and values are explicit in context. |
| `host_runtime.rs`, `platform_shell.rs` | Keep | Host execution/shell policy shared with sandbox. |
diff --git a/gitbooks/developing/architecture/agent-harness.md b/gitbooks/developing/architecture/agent-harness.md
index 30788d7cd0..c35a861e5e 100644
--- a/gitbooks/developing/architecture/agent-harness.md
+++ b/gitbooks/developing/architecture/agent-harness.md
@@ -229,7 +229,7 @@ Every iteration emits a real-time `AgentProgress` event so the UI can render tok
Live turns speak **native tool calling**: the tinyagents harness sends structured tool specs through the `ChatModel` adapter and gets structured tool calls back, for every provider (Claude, GPT, Gemini, local Ollama alike).
-The host `ToolDispatcher` trait (`crates/openhuman-core/src/agent/tool_dialect.rs`) remains as a **transcript-compatibility layer**, not a live routing choice; it calls canonical `tinytools_agent` parsers and renderers directly:
+Canonical `tinytools_agent::dialect::ToolDialect` implementations provide transcript-compatible parsing and rendering directly; OpenHuman converts durable/provider records only at those I/O boundaries:
- **Native** - structured tool-call fields, the shape live turns produce today.
- **XML** - `<tool_call>{...}</tool_call>` tags in assistant text, produced by older sessions.
@@ -516,7 +516,7 @@ The harness shell lives under `crates/openhuman-core/src/agent/`, with the tinya
| `harness/subagent_runner/ops/runner.rs` | Integration-tool ranking uses canonical `tinyagents_harness::tool` APIs. |
| `../tinyagents/payload_summarizer.rs` | Oversized-tool-result detour. |
| `harness/session/tool_progress.rs` | Surviving OpenHuman seam: `TurnProgress`. |
-| `tool_dialect.rs` | Persisted-transcript conversion around canonical tool-call dialect APIs. |
+| `message_convert.rs` | Concrete durable/provider conversion around canonical tool-call dialect APIs. |
| `triage/` | External-trigger classification + escalation. |
| `registry/agents/` | Built-in archetypes - one subdirectory per agent. |
| `hooks.rs` / `stop_hooks.rs` | Post-turn and mid-turn hook surfaces. |
diff --git a/scripts/ci/agent-runtime-boundary-baseline.json b/scripts/ci/agent-runtime-boundary-baseline.json
index b72e02450d..9b582af659 100644
--- a/scripts/ci/agent-runtime-boundary-baseline.json
+++ b/scripts/ci/agent-runtime-boundary-baseline.json
@@ -555,7 +555,7 @@
{
"rule": "openhuman-task-local",
"path": "crates/openhuman-core/src/agent/harness/session/builder/factory.rs",
- "line": 1517,
+ "line": 1514,
"text": "let root = crate::agent::turn_workspace::current()?;",
"occurrence": 1
},
@@ -632,14 +632,14 @@
{
"rule": "openhuman-task-local",
"path": "crates/openhuman-core/src/agent/harness/session/turn/core/harness_turn.rs",
- "line": 173,
+ "line": 176,
"text": "crate::agent::harness::turn_subagent_usage::with_turn_collector(",
"occurrence": 1
},
{
"rule": "openhuman-task-local",
"path": "crates/openhuman-core/src/agent/harness/session/turn/core/harness_turn.rs",
- "line": 210,
+ "line": 213,
"text": "crate::agent::harness::turn_dispatch_guard::with_dispatch_guard(",
"occurrence": 1
},
@@ -2375,7 +2375,7 @@
{
"rule": "tinyagents-moved-symbol-alias",
"path": "vendor/tinyagents/crates/tinyagents-harness/src/tool/mod.rs",
- "line": 95,
+ "line": 97,
"text": "pub struct ToolRegistry<State: Send + Sync, Ctx: Send + Sync> {",
"occurrence": 1
},
@@ -2445,192 +2445,178 @@
{
"rule": "tinyagents-openhuman-domain-name",
"path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/input_builder_tests.rs",
- "line": 132,
+ "line": 145,
"text": "&[ChatMessage::user(",
"occurrence": 1
},
{
"rule": "tinyagents-openhuman-domain-name",
"path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/input_builder_tests.rs",
- "line": 151,
+ "line": 164,
"text": "&[ChatMessage::user(\"read [IMAGE:/etc/hostname]\")],",
"occurrence": 1
},
{
"rule": "tinyagents-openhuman-domain-name",
"path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/input_builder_tests.rs",
- "line": 162,
+ "line": 175,
"text": "ChatMessage::user(\"earlier [OH_IMAGE:data:image/png;base64,QUJD]\"),",
"occurrence": 1
},
{
"rule": "tinyagents-openhuman-domain-name",
"path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/input_builder_tests.rs",
- "line": 163,
+ "line": 176,
"text": "ChatMessage::assistant(\"old answer\"),",
"occurrence": 1
},
{
"rule": "tinyagents-openhuman-domain-name",
"path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/input_builder_tests.rs",
- "line": 164,
+ "line": 177,
"text": "ChatMessage::user(\"latest\"),",
"occurrence": 1
},
{
"rule": "tinyagents-openhuman-domain-name",
"path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/input_builder_tests.rs",
- "line": 181,
+ "line": 194,
"text": "ChatMessage::user(\"first steering\"),",
"occurrence": 1
},
{
"rule": "tinyagents-openhuman-domain-name",
"path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/input_builder_tests.rs",
- "line": 182,
+ "line": 195,
"text": "ChatMessage::user(\"second steering\"),",
"occurrence": 1
},
{
"rule": "tinyagents-openhuman-domain-name",
"path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/input_builder_tests.rs",
- "line": 183,
+ "line": 196,
"text": "ChatMessage::assistant(\"answer\"),",
"occurrence": 1
},
{
"rule": "tinyagents-openhuman-domain-name",
"path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/input_builder_tests.rs",
- "line": 184,
+ "line": 197,
"text": "ChatMessage::user(\"latest\"),",
"occurrence": 1
},
{
"rule": "tinyagents-openhuman-domain-name",
"path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/input_builder_tests.rs",
- "line": 194,
+ "line": 207,
"text": "&[ChatMessage::user(",
"occurrence": 1
},
{
"rule": "tinyagents-openhuman-domain-name",
"path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/input_builder_tests.rs",
- "line": 209,
+ "line": 222,
"text": "&[ChatMessage::user(",
"occurrence": 1
},
{
"rule": "tinyagents-openhuman-domain-name",
"path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/input_builder.rs",
- "line": 14,
+ "line": 15,
"text": "use super::bridge::ChatMessage;",
"occurrence": 1
},
{
"rule": "tinyagents-openhuman-domain-name",
"path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/input_builder.rs",
- "line": 22,
+ "line": 23,
"text": "pub fn build_stdin(messages: &[ChatMessage], is_new_session: bool) -> Vec<u8> {",
"occurrence": 1
},
{
"rule": "tinyagents-openhuman-domain-name",
"path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/input_builder.rs",
- "line": 32,
+ "line": 33,
"text": "let non_system: Vec<&ChatMessage> = messages.iter().filter(|m| m.role != \"system\").collect();",
"occurrence": 1
},
{
"rule": "tinyagents-openhuman-domain-name",
"path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/input_builder.rs",
- "line": 95,
- "text": "fn prior_conversation_preamble(non_system: &[&ChatMessage], end: usize) -> Option<String> {",
- "occurrence": 1
- },
- {
- "rule": "tinyagents-openhuman-domain-name",
- "path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/mod_tests.rs",
- "line": 26,
- "text": "let a = vec![ChatMessage::user(\"hello world\")];",
+ "line": 91,
+ "text": "fn pending_user_content(non_system: &[&ChatMessage]) -> Option<String> {",
"occurrence": 1
},
{
"rule": "tinyagents-openhuman-domain-name",
- "path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/mod_tests.rs",
- "line": 28,
- "text": "ChatMessage::user(\"hello world\"),",
+ "path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/input_builder.rs",
+ "line": 114,
+ "text": "fn prior_conversation_preamble(non_system: &[&ChatMessage], end: usize) -> Option<String> {",
"occurrence": 1
},
{
"rule": "tinyagents-openhuman-domain-name",
"path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/mod_tests.rs",
- "line": 29,
- "text": "ChatMessage::assistant(\"hi\"),",
+ "line": 49,
+ "text": "ChatMessage::system(\"base\"),",
"occurrence": 1
},
{
"rule": "tinyagents-openhuman-domain-name",
"path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/mod_tests.rs",
- "line": 36,
- "text": "let a = vec![ChatMessage::user(\"alpha\")];",
+ "line": 50,
+ "text": "ChatMessage::user(\"question\"),",
"occurrence": 1
},
{
"rule": "tinyagents-openhuman-domain-name",
"path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/mod_tests.rs",
- "line": 37,
- "text": "let b = vec![ChatMessage::user(\"beta\")];",
+ "line": 51,
+ "text": "ChatMessage::system(\"middleware addition\"),",
"occurrence": 1
},
{
"rule": "tinyagents-openhuman-domain-name",
"path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/mod.rs",
- "line": 19,
+ "line": 23,
"text": "use bridge::{ChatMessage, ChatResponse, ProviderDelta};",
"occurrence": 1
},
{
"rule": "tinyagents-openhuman-domain-name",
"path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/mod.rs",
- "line": 164,
+ "line": 175,
"text": "messages: &[ChatMessage],",
"occurrence": 1
},
{
"rule": "tinyagents-openhuman-domain-name",
"path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/mod.rs",
- "line": 195,
- "text": "fn request_messages(request: &ModelRequest) -> Vec<ChatMessage> {",
+ "line": 238,
+ "text": "fn coalesce_system_prompt(messages: &[ChatMessage]) -> Option<String> {",
"occurrence": 1
},
{
"rule": "tinyagents-openhuman-domain-name",
"path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/mod.rs",
- "line": 212,
- "text": "ChatMessage::new(role, content)",
+ "line": 277,
+ "text": "fn request_messages(request: &ModelRequest) -> Vec<ChatMessage> {",
"occurrence": 1
},
{
"rule": "tinyagents-openhuman-domain-name",
"path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_code/mod.rs",
- "line": 345,
- "text": "fn thread_key_from_messages(messages: &[ChatMessage]) -> String {",
+ "line": 300,
+ "text": "ChatMessage::new(role, content)",
"occurrence": 1
},
{
"rule": "tinyagents-tool-calling-facade",
"path": "vendor/tinyagents/crates/tinyagents-harness/src/agent_loop/run_loop.rs",
- "line": 906,
+ "line": 922,
"text": "use tinytools_agent::dialect::{DialectResponse, ToolDialect, XmlDialect};",
"occurrence": 1
},
- {
- "rule": "tinyagents-tool-calling-facade",
- "path": "vendor/tinyagents/crates/tinyagents-harness/src/providers/claude_agent_sdk/mod.rs",
- "line": 12,
- "text": "use tinytools_agent::dialect::{ToolDialect, XmlDialect};",
- "occurrence": 1
- },
{
"rule": "tinyagents-upstream-reexport",
"path": "vendor/tinyagents/crates/tinyagents-graph/src/lib.rs",
diff --git a/tests/agent_builder_public.rs b/tests/agent_builder_public.rs
index 1b76b057c2..cce6a0bfad 100644
--- a/tests/agent_builder_public.rs
+++ b/tests/agent_builder_public.rs
@@ -1,7 +1,7 @@
use anyhow::Result;
use async_trait::async_trait;
use openhuman_core::agent::prompts::SystemPromptBuilder;
-use openhuman_core::agent::tool_dialect::XmlToolDispatcher;
+use openhuman_core::tinytools_agent::dialect::XmlDialect;
use openhuman_core::agent::Agent;
use openhuman_core::memory::{Memory, MemoryCategory, MemoryEntry};
use tinytools::{Tool, ToolResult};
@@ -115,7 +115,7 @@ fn base_builder() -> openhuman_core::agent::AgentBuilder {
Box::new(StubTool("beta")),
])
.memory(Arc::new(StubMemory))
- .tool_dispatcher(Box::new(XmlToolDispatcher))
+ .tool_dispatcher(Box::new(XmlDialect))
}
#[test]
diff --git a/tests/agent_harness_e2e.rs b/tests/agent_harness_e2e.rs
index 5ea555f9ed..4e0624fad9 100644
--- a/tests/agent_harness_e2e.rs
+++ b/tests/agent_harness_e2e.rs
@@ -2359,7 +2359,7 @@ async fn multi_hop_delegation_chain_inner() {
mod streaming_support {
use async_trait::async_trait;
- use openhuman_core::agent::tool_dialect::NativeToolDispatcher;
+ use openhuman_core::tinytools_agent::dialect::NativeDialect;
use openhuman_core::agent::Agent;
use openhuman_core::config::{AgentConfig, ContextConfig};
use openhuman_core::memory::Memory;
@@ -2552,7 +2552,7 @@ mod streaming_support {
.chat_model(provider)
.tools(tools)
.memory(memory_for_workspace_s(&workspace_path))
- .tool_dispatcher(Box::new(NativeToolDispatcher))
+ .tool_dispatcher(Box::new(NativeDialect))
.workspace_dir(workspace_path)
.event_context("stream-accum-session", "stream-accum-channel")
.agent_definition_name("round17/orchestrator")
@@ -4149,7 +4149,7 @@ mod tool_policy_boundary_placement {
use anyhow::Result;
use async_trait::async_trait;
use openhuman_core::agent::prompts::LearnedContextData;
- use openhuman_core::agent::tool_dialect::NativeToolDispatcher;
+ use openhuman_core::tinytools_agent::dialect::NativeDialect;
use openhuman_core::agent::Agent;
use openhuman_core::config::AgentConfig;
use openhuman_core::memory::{
@@ -4266,7 +4266,7 @@ mod tool_policy_boundary_placement {
}),
])
.memory(Arc::new(StubMemory))
- .tool_dispatcher(Box::new(NativeToolDispatcher))
+ .tool_dispatcher(Box::new(NativeDialect))
.workspace_dir(workspace.path().to_path_buf())
.event_context("boundary-session", "boundary-channel")
.config(config)
diff --git a/tests/agent_turn_overrides_e2e.rs b/tests/agent_turn_overrides_e2e.rs
index 0e1b6671a0..1865a23160 100644
--- a/tests/agent_turn_overrides_e2e.rs
+++ b/tests/agent_turn_overrides_e2e.rs
@@ -37,7 +37,7 @@ use tempfile::TempDir;
use openhuman_core::agent::goals::{runtime as goal_runtime, store as goal_store};
use openhuman_core::agent::harness::session::TurnOverrides;
use openhuman_core::agent::tinyagents::thread_context::with_thread_id;
-use openhuman_core::agent::tool_dialect::{NativeToolDispatcher, XmlToolDispatcher};
+use tinytools_agent::dialect::{NativeDialect, XmlDialect};
use openhuman_core::agent::Agent;
use openhuman_core::config::{AgentConfig, ContextConfig};
use tinyinference_llm::message::Message;
@@ -232,7 +232,7 @@ fn agent_with(
model: Arc<dyn ChatModel<()>>,
tools: Vec<Box<dyn Tool>>,
workspace_path: PathBuf,
- dispatcher: Box<dyn openhuman_core::agent::tool_dialect::ToolDispatcher>,
+ dispatcher: Box<dyn openhuman_core::tinytools_agent::dialect::ToolDialect>,
) -> Agent {
Agent::builder()
.chat_model(model)
@@ -303,7 +303,7 @@ async fn suppress_active_goal_keeps_the_thread_goal_out_of_the_prompt_inner() {
control_model.clone(),
Vec::new(),
control_workspace.clone(),
- Box::new(XmlToolDispatcher),
+ Box::new(XmlDialect),
);
control
.turn("where are we on the task?")
@@ -327,7 +327,7 @@ async fn suppress_active_goal_keeps_the_thread_goal_out_of_the_prompt_inner() {
model.clone(),
Vec::new(),
workspace_path.clone(),
- Box::new(XmlToolDispatcher),
+ Box::new(XmlDialect),
);
agent.set_next_turn_overrides(TurnOverrides {
suppress_active_goal: true,
@@ -393,7 +393,7 @@ async fn suppress_transcript_autoload_does_not_replay_a_prior_threads_transcript
first_model.clone(),
Vec::new(),
workspace_path.clone(),
- Box::new(XmlToolDispatcher),
+ Box::new(XmlDialect),
);
first
.turn(PRIOR_MARKER)
@@ -411,7 +411,7 @@ async fn suppress_transcript_autoload_does_not_replay_a_prior_threads_transcript
control_model.clone(),
Vec::new(),
workspace_path.clone(),
- Box::new(XmlToolDispatcher),
+ Box::new(XmlDialect),
);
control
.turn("an unrelated question")
@@ -430,7 +430,7 @@ async fn suppress_transcript_autoload_does_not_replay_a_prior_threads_transcript
model.clone(),
Vec::new(),
workspace_path.clone(),
- Box::new(XmlToolDispatcher),
+ Box::new(XmlDialect),
);
agent.set_next_turn_overrides(TurnOverrides {
suppress_transcript_autoload: true,
@@ -477,7 +477,7 @@ async fn turn_overrides_apply_to_exactly_one_turn_and_then_reset_inner() {
model.clone(),
vec![Box::new(EchoTool)],
workspace_path.clone(),
- Box::new(NativeToolDispatcher),
+ Box::new(NativeDialect),
);
agent.set_next_turn_overrides(TurnOverrides {
@@ -550,7 +550,7 @@ async fn thread_goal_complete_and_clear_stop_the_goal_reaching_later_turns_inner
control_model.clone(),
Vec::new(),
control_workspace.clone(),
- Box::new(XmlToolDispatcher),
+ Box::new(XmlDialect),
);
control.turn("status?").await.expect("pre-completion turn");
assert!(
@@ -583,7 +583,7 @@ async fn thread_goal_complete_and_clear_stop_the_goal_reaching_later_turns_inner
model.clone(),
Vec::new(),
workspace_path.clone(),
- Box::new(XmlToolDispatcher),
+ Box::new(XmlDialect),
);
agent
.turn("something unrelated")
@@ -637,7 +637,7 @@ async fn thread_goal_complete_and_clear_stop_the_goal_reaching_later_turns_inner
post_clear_model.clone(),
Vec::new(),
workspace_path.clone(),
- Box::new(XmlToolDispatcher),
+ Box::new(XmlDialect),
);
post_clear
.turn("something else entirely")
diff --git a/tests/calendar_grounding_e2e.rs b/tests/calendar_grounding_e2e.rs
index 09937ab092..ab7174b3c1 100644
--- a/tests/calendar_grounding_e2e.rs
+++ b/tests/calendar_grounding_e2e.rs
@@ -1,6 +1,6 @@
use anyhow::Result;
use async_trait::async_trait;
-use openhuman_core::agent::tool_dialect::NativeToolDispatcher;
+use openhuman_core::tinytools_agent::dialect::NativeDialect;
use openhuman_core::agent::Agent;
use tinytools::{PermissionLevel, Tool, ToolResult};
@@ -111,7 +111,7 @@ async fn test_orchestrator_has_current_date_context() -> Result<()> {
let mut agent = Agent::builder()
.chat_model(model)
.tools(vec![Box::new(MockCalendarTool)])
- .tool_dispatcher(Box::new(NativeToolDispatcher))
+ .tool_dispatcher(Box::new(NativeDialect))
.memory(Arc::new(StubMemory))
.workspace_dir(std::env::temp_dir())
.build()?;
diff --git a/tests/raw_coverage/agent_harness_leftovers_raw_coverage_e2e.rs b/tests/raw_coverage/agent_harness_leftovers_raw_coverage_e2e.rs
index 1bd1992ae3..b6996d4643 100644
--- a/tests/raw_coverage/agent_harness_leftovers_raw_coverage_e2e.rs
+++ b/tests/raw_coverage/agent_harness_leftovers_raw_coverage_e2e.rs
@@ -6,7 +6,7 @@ use openhuman_core::agent::prompts::{
PersonalityRosterEntry, PromptContext, PromptTool, SubagentRenderOptions, SystemPromptBuilder,
ToolCallFormat, UserIdentity,
};
-use openhuman_core::agent::tool_dialect::NativeToolDispatcher;
+use openhuman_core::tinytools_agent::dialect::NativeDialect;
use openhuman_core::agent::harness::definition::AgentTier;
use openhuman_core::agent::harness::session::Agent;
use openhuman_core::agent::harness::{
@@ -270,7 +270,7 @@ fn build_agent(
.chat_model(provider)
.tools(tools)
.memory(Arc::new(StubMemory::default()))
- .tool_dispatcher(Box::new(NativeToolDispatcher))
+ .tool_dispatcher(Box::new(NativeDialect))
.config(agent_config(3))
.model_name("round19-model".to_string())
.temperature(0.0)
diff --git a/tests/raw_coverage/agent_harness_raw_coverage_e2e.rs b/tests/raw_coverage/agent_harness_raw_coverage_e2e.rs
index bd2635318d..183ab34376 100644
--- a/tests/raw_coverage/agent_harness_raw_coverage_e2e.rs
+++ b/tests/raw_coverage/agent_harness_raw_coverage_e2e.rs
@@ -1,6 +1,6 @@
use anyhow::Result;
use async_trait::async_trait;
-use openhuman_core::agent::tool_dialect::NativeToolDispatcher;
+use openhuman_core::tinytools_agent::dialect::NativeDialect;
use openhuman_core::agent::harness::definition::AgentDefinitionRegistry;
use openhuman_core::agent::harness::session::Agent;
use openhuman_core::agent::harness::{
@@ -244,7 +244,7 @@ fn build_agent_with_tools(
.chat_model(provider)
.tools(tools)
.memory(Arc::new(StubMemory))
- .tool_dispatcher(Box::new(NativeToolDispatcher))
+ .tool_dispatcher(Box::new(NativeDialect))
.config(agent_config())
.model_name("coverage-model".to_string())
.temperature(0.0)
diff --git a/tests/raw_coverage/agent_prompts_subagent_raw_coverage_e2e.rs b/tests/raw_coverage/agent_prompts_subagent_raw_coverage_e2e.rs
index 1ca1aedd8c..42e91010f3 100644
--- a/tests/raw_coverage/agent_prompts_subagent_raw_coverage_e2e.rs
+++ b/tests/raw_coverage/agent_prompts_subagent_raw_coverage_e2e.rs
@@ -1,6 +1,6 @@
use anyhow::Result;
use async_trait::async_trait;
-use openhuman_core::agent::tool_dialect::NativeToolDispatcher;
+use openhuman_core::tinytools_agent::dialect::NativeDialect;
use openhuman_core::agent::harness::session::Agent;
use openhuman_core::agent::harness::{
run_subagent, with_parent_context, AgentDefinition, DefinitionSource, ModelSpec,
@@ -516,7 +516,7 @@ fn agent_builder_validation_reports_each_required_component() {
.tools(vec![tool("echo"), tool("echo")])
.chat_model(ScriptedModel::new(vec![]))
.memory(Arc::new(StubMemory))
- .tool_dispatcher(Box::new(NativeToolDispatcher))
+ .tool_dispatcher(Box::new(NativeDialect))
.visible_tool_names(HashSet::from(["echo".to_string()]))
.agent_definition_name("round18/custom name")
.build()
diff --git a/tests/raw_coverage/agent_round26_raw_coverage_e2e.rs b/tests/raw_coverage/agent_round26_raw_coverage_e2e.rs
index 93d169b747..3a04e990cf 100644
--- a/tests/raw_coverage/agent_round26_raw_coverage_e2e.rs
+++ b/tests/raw_coverage/agent_round26_raw_coverage_e2e.rs
@@ -9,7 +9,7 @@ use openhuman_core::agent::prompts::{
UserIdentity,
};
use openhuman_core::agent::debug::{dump_agent_prompt, DumpPromptOptions};
-use openhuman_core::agent::tool_dialect::NativeToolDispatcher;
+use openhuman_core::tinytools_agent::dialect::NativeDialect;
use openhuman_core::agent::Agent;
use openhuman_core::config::AgentConfig;
use openhuman_core::memory::{
@@ -389,7 +389,7 @@ async fn builder_dedupes_visible_native_tools_and_seed_resume_bounds_history() -
.tools(tools)
.visible_tool_names(visible)
.memory(Arc::new(StubMemory))
- .tool_dispatcher(Box::new(NativeToolDispatcher))
+ .tool_dispatcher(Box::new(NativeDialect))
.workspace_dir(workspace.path().to_path_buf())
.event_context("round26-session", "round26-channel")
.agent_definition_name("round26/orchestrator")
diff --git a/tests/raw_coverage/agent_session_round24_raw_coverage_e2e.rs b/tests/raw_coverage/agent_session_round24_raw_coverage_e2e.rs
index ce12438906..bc6e8ad911 100644
--- a/tests/raw_coverage/agent_session_round24_raw_coverage_e2e.rs
+++ b/tests/raw_coverage/agent_session_round24_raw_coverage_e2e.rs
@@ -1,6 +1,6 @@
use anyhow::Result;
use async_trait::async_trait;
-use openhuman_core::agent::tool_dialect::XmlToolDispatcher;
+use openhuman_core::tinytools_agent::dialect::XmlDialect;
use openhuman_core::agent::hooks::{PostTurnHook, TurnContext};
use openhuman_core::agent::Agent;
use openhuman_core::config::{AgentConfig, ContextConfig};
@@ -429,7 +429,7 @@ async fn max_iteration_checkpoint_uses_deterministic_fallback_and_hooks() {
calls: calls.clone(),
})])
.memory(RecordingMemory::new())
- .tool_dispatcher(Box::new(XmlToolDispatcher))
+ .tool_dispatcher(Box::new(XmlDialect))
.workspace_dir(workspace_path.clone())
.event_context("round24-session", "round24-channel")
.agent_definition_name("round24/orchestrator")
@@ -514,7 +514,7 @@ async fn builder_validation_and_system_prompt_cover_defaults_and_learning() {
.chat_model(provider.clone())
.tools(vec![Box::new(Round24Tool { calls })])
.memory(memory)
- .tool_dispatcher(Box::new(XmlToolDispatcher))
+ .tool_dispatcher(Box::new(XmlDialect))
.workspace_dir(workspace_path)
.event_context("round24-prompt-session", "round24-prompt-channel")
.agent_definition_name("round24 prompt/name")
diff --git a/tests/raw_coverage/agent_session_turn_raw_coverage_e2e.rs b/tests/raw_coverage/agent_session_turn_raw_coverage_e2e.rs
index 413814cd49..d9cf79ba9b 100644
--- a/tests/raw_coverage/agent_session_turn_raw_coverage_e2e.rs
+++ b/tests/raw_coverage/agent_session_turn_raw_coverage_e2e.rs
@@ -2,7 +2,7 @@
mod noop_memory;
use async_trait::async_trait;
-use openhuman_core::agent::tool_dialect::{NativeToolDispatcher, XmlToolDispatcher};
+use tinytools_agent::dialect::{NativeDialect, XmlDialect};
use openhuman_core::agent::harness::definition::AgentTier;
use openhuman_core::agent::harness::subagent_runner::run_subagent;
use openhuman_core::agent::harness::{
@@ -617,7 +617,7 @@ fn agent_with(
model: Arc<dyn ChatModel<()>>,
tools: Vec<Box<dyn Tool>>,
workspace_path: PathBuf,
- dispatcher: Box<dyn openhuman_core::agent::tool_dialect::ToolDispatcher>,
+ dispatcher: Box<dyn openhuman_core::tinytools_agent::dialect::ToolDialect>,
config: AgentConfig,
context_config: ContextConfig,
) -> Agent {
@@ -693,7 +693,7 @@ async fn turn_native_tool_progress_reasoning_usage_and_resume_seed_paths_inner()
calls.clone(),
)],
workspace_path,
- Box::new(NativeToolDispatcher),
+ Box::new(NativeDialect),
AgentConfig {
max_tool_iterations: 4,
max_history_messages: 12,
@@ -766,7 +766,7 @@ async fn turn_native_tool_progress_reasoning_usage_and_resume_seed_paths_inner()
Arc::new(AtomicUsize::new(0)),
)],
seeded_workspace,
- Box::new(XmlToolDispatcher),
+ Box::new(XmlDialect),
AgentConfig {
max_history_messages: 3,
..AgentConfig::default()
@@ -839,7 +839,7 @@ async fn turn_citation_task_replaces_previous_handle_and_joins_successfully_inne
]))
.tools(Vec::new())
.memory(memory)
- .tool_dispatcher(Box::new(XmlToolDispatcher))
+ .tool_dispatcher(Box::new(XmlDialect))
.workspace_dir(workspace_path)
.event_context("round17-session", "round17-channel")
.agent_definition_name("round17/orchestrator")
@@ -950,7 +950,7 @@ async fn turn_xml_failures_checkpoint_policy_visibility_and_hooks_are_publicly_e
release_recall: None,
recall_cancelled: None,
}))
- .tool_dispatcher(Box::new(XmlToolDispatcher))
+ .tool_dispatcher(Box::new(XmlDialect))
.workspace_dir(workspace_path)
.event_context("round17-session", "round17-channel")
.agent_definition_name("round17/orchestrator")
@@ -1046,7 +1046,7 @@ async fn turn_xml_failures_checkpoint_policy_visibility_and_hooks_are_publicly_e
provider_error,
vec![],
failing_workspace,
- Box::new(XmlToolDispatcher),
+ Box::new(XmlDialect),
AgentConfig::default(),
ContextConfig::default(),
);
diff --git a/tests/raw_coverage/agent_tool_loop_raw_coverage_e2e.rs b/tests/raw_coverage/agent_tool_loop_raw_coverage_e2e.rs
index 71338c19a1..b9c32fec79 100644
--- a/tests/raw_coverage/agent_tool_loop_raw_coverage_e2e.rs
+++ b/tests/raw_coverage/agent_tool_loop_raw_coverage_e2e.rs
@@ -4,7 +4,7 @@ use openhuman_core::agent::bus::{
register_agent_handlers, AgentTurnRequest, AgentTurnResponse, AGENT_RUN_TURN_METHOD,
};
use openhuman_core::agent::debug::{dump_agent_prompt, DumpPromptOptions};
-use openhuman_core::agent::tool_dialect::XmlToolDispatcher;
+use openhuman_core::tinytools_agent::dialect::XmlDialect;
use openhuman_core::agent::{Agent, AgentBuilder};
use openhuman_core::config::{AgentConfig, MultimodalConfig, MultimodalFileConfig};
use openhuman_core::agent::prompts::LearnedContextData;
@@ -586,7 +586,7 @@ async fn agent_builder_prompt_and_debug_dump_cover_public_session_paths() {
.chat_model(provider)
.tools(vec![StaticTool::ok("echo", "ok")])
.memory(Arc::new(NoopMemory::default()))
- .tool_dispatcher(Box::new(XmlToolDispatcher))
+ .tool_dispatcher(Box::new(XmlDialect))
.config(config)
.workspace_dir(workspace.clone())
.agent_definition_name("round15/orchestrator")
@@ -627,7 +627,7 @@ async fn agent_turn_blank_final_response_is_typed_error() {
.chat_model(provider)
.tools(vec![])
.memory(Arc::new(NoopMemory::default()))
- .tool_dispatcher(Box::new(XmlToolDispatcher))
+ .tool_dispatcher(Box::new(XmlDialect))
.config(AgentConfig {
max_tool_iterations: 1,
..AgentConfig::default()
diff --git a/tests/raw_coverage/agent_turn_builder_leftovers_raw_coverage_e2e.rs b/tests/raw_coverage/agent_turn_builder_leftovers_raw_coverage_e2e.rs
index cd153ac0ed..024663e263 100644
--- a/tests/raw_coverage/agent_turn_builder_leftovers_raw_coverage_e2e.rs
+++ b/tests/raw_coverage/agent_turn_builder_leftovers_raw_coverage_e2e.rs
@@ -1,6 +1,6 @@
use anyhow::Result;
use async_trait::async_trait;
-use openhuman_core::agent::tool_dialect::{NativeToolDispatcher, XmlToolDispatcher};
+use tinytools_agent::dialect::{NativeDialect, XmlDialect};
use openhuman_core::agent::hooks::{PostTurnHook, TurnContext};
use openhuman_core::agent::Agent;
use openhuman_core::config::{AgentConfig, ContextConfig};
@@ -365,7 +365,7 @@ async fn native_turn_dedups_duplicate_tool_specs_and_executes_empty_arguments()
])
.visible_tool_names(["round20_dup".to_string()].into_iter().collect())
.memory(RecordingMemory::new())
- .tool_dispatcher(Box::new(NativeToolDispatcher))
+ .tool_dispatcher(Box::new(NativeDialect))
.workspace_dir(workspace_path)
.event_context("round20-native-session", "round20-native-channel")
.agent_definition_name("round20/native")
@@ -421,7 +421,7 @@ async fn xml_turn_persists_tool_cycle_and_fires_failure_hook_context() {
true,
)])
.memory(RecordingMemory::new())
- .tool_dispatcher(Box::new(XmlToolDispatcher))
+ .tool_dispatcher(Box::new(XmlDialect))
.workspace_dir(workspace_path.clone())
.event_context("round20-hook-session", "round20-hook-channel")
.agent_definition_name("round20/xml")
@@ -494,7 +494,7 @@ async fn session_memory_threshold_path_runs_only_after_successful_turn() {
false,
)])
.memory(RecordingMemory::new())
- .tool_dispatcher(Box::new(XmlToolDispatcher))
+ .tool_dispatcher(Box::new(XmlDialect))
.workspace_dir(workspace_path)
.event_context("round20-flush-session", "round20-flush-channel")
.agent_definition_name("round20/flush")
@@ -535,7 +535,7 @@ async fn session_memory_threshold_path_runs_only_after_successful_turn() {
.chat_model(empty_provider)
.tools(Vec::new())
.memory(RecordingMemory::new())
- .tool_dispatcher(Box::new(XmlToolDispatcher))
+ .tool_dispatcher(Box::new(XmlDialect))
.workspace_dir(empty_workspace)
.event_context("round20-empty-session", "round20-empty-channel")
.agent_definition_name("round20/empty")
diff --git a/tests/raw_coverage/inference_agent_raw_coverage_e2e.rs b/tests/raw_coverage/inference_agent_raw_coverage_e2e.rs
index a319733cfe..a85ce0f3f1 100644
--- a/tests/raw_coverage/inference_agent_raw_coverage_e2e.rs
+++ b/tests/raw_coverage/inference_agent_raw_coverage_e2e.rs
@@ -28,9 +28,9 @@ use openhuman_core::agent::bus::{
use openhuman_core::agent::debug::{
write_prompt_dumps, DumpPromptOptions, DumpedPrompt,
};
-use openhuman_core::agent::tool_dialect::{
- NativeToolDispatcher, PFormatToolDispatcher, ToolDispatcher, ToolExecutionResult,
- XmlToolDispatcher,
+use tinytools_agent::dialect::{
+ NativeDialect, PFormatDialect, ToolDialect, ToolOutcome,
+ XmlDialect,
};
use openhuman_core::agent::error::{
is_context_limit_error, is_max_iterations_error, AgentError, MAX_ITERATIONS_ERROR_PREFIX,
@@ -801,7 +801,7 @@ fn base_agent_builder() -> openhuman_core::agent::AgentBuilder {
Box::new(StubTool("beta")),
])
.memory(Arc::new(RecordingMemory::default()))
- .tool_dispatcher(Box::new(XmlToolDispatcher))
+ .tool_dispatcher(Box::new(XmlDialect))
}
#[tokio::test]
@@ -3229,13 +3229,13 @@ fn agent_dispatchers_and_host_runtime_cover_public_edge_paths() {
}),
};
- let xml = XmlToolDispatcher;
+ let xml = XmlDialect;
let xml_instructions = xml
.prompt_instructions_for_specs(&[spec.clone()])
.expect("xml specs");
assert!(xml_instructions.contains("search_docs"));
assert!(!xml.should_send_tool_specs());
- let xml_result = xml.format_results(&[ToolExecutionResult {
+ let xml_result = xml.format_results(&[ToolOutcome {
name: "search_docs".into(),
output: "found docs".into(),
success: true,
@@ -3251,7 +3251,7 @@ fn agent_dispatchers_and_host_runtime_cover_public_edge_paths() {
types: vec![PFormatParamType::String],
},
);
- let pformat = PFormatToolDispatcher::new(registry);
+ let pformat = PFormatDialect::new(registry);
let mixed = ChatResponse {
text: Some(
"first\n<tool_call>search_docs[0|coverage gaps]</tool_call>\n\
@@ -3283,7 +3283,7 @@ fn agent_dispatchers_and_host_runtime_cover_public_edge_paths() {
assert_eq!(pformat.tool_call_format(), ToolCallFormat::PFormat);
assert!(pformat.prompt_instructions(&[]).contains("P-Format"));
- let native = NativeToolDispatcher;
+ let native = NativeDialect;
let structured = ChatResponse {
text: Some("using a tool".into()),
tool_calls: vec![
diff --git a/tests/raw_coverage/tools_agent_credentials_state_raw_coverage_e2e.rs b/tests/raw_coverage/tools_agent_credentials_state_raw_coverage_e2e.rs
index 2d63f65035..0f71a73262 100644
--- a/tests/raw_coverage/tools_agent_credentials_state_raw_coverage_e2e.rs
+++ b/tests/raw_coverage/tools_agent_credentials_state_raw_coverage_e2e.rs
@@ -16,7 +16,7 @@ use axum::response::IntoResponse;
use axum::routing::post;
use axum::{Json, Router};
use chrono::{Duration as ChronoDuration, Utc};
-use openhuman_core::agent::tool_dialect::NativeToolDispatcher;
+use openhuman_core::tinytools_agent::dialect::NativeDialect;
use openhuman_core::agent::harness::session::Agent;
use openhuman_core::agent::harness::{
run_subagent, with_parent_context, AgentDefinition, ParentExecutionContext, PromptSource,
@@ -742,7 +742,7 @@ async fn round16_agent_builder_turn_uses_public_harness_paths() {
.chat_model(provider)
.tools(vec![Box::new(EchoTool)])
.memory(Arc::new(StubMemory))
- .tool_dispatcher(Box::new(NativeToolDispatcher))
+ .tool_dispatcher(Box::new(NativeDialect))
.config(openhuman_core::config::AgentConfig {
max_tool_iterations: 3,
..Default::default()