The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(prompts): delegate tool dialect rendering
Steven Enamakel07fd67c32cc5
diff --git a/crates/openhuman-core/src/agent/prompts/render_helpers/subagent.rs b/crates/openhuman-core/src/agent/prompts/render_helpers/subagent.rsindex d24faadf3b..44769ca5f3 100644--- a/crates/openhuman-core/src/agent/prompts/render_helpers/subagent.rs+++ b/crates/openhuman-core/src/agent/prompts/render_helpers/subagent.rs@@ -12,6 +12,9 @@ use super::workspace_files::{};use std::fmt::Write;use std::path::Path;+use tinytools_agent::dialect::{+ CodeDialect, NativeDialect, PFormatDialect, ToolDialect, XmlDialect,+};// ─────────────────────────────────────────────────────────────────────────────// Sub-agent prompt renderer@@ -81,8 +84,8 @@ pub fn render_subagent_system_prompt(/// Inner renderer that accepts an explicit [`ToolCallFormat`] so callers/// that know the active dispatcher format can thread it through. The-/// public [`render_subagent_system_prompt`] defaults to PFormat for-/// backwards compatibility.+/// public [`render_subagent_system_prompt`] uses the preferred Python dialect+/// by default.////// `agents_md_global` / `agents_md_local` are the pre-loaded AGENTS.md layers/// (see [`crate::agent::prompts::agents_md::load_agents_md_layers`]); `None`/`None` (the value@@ -167,143 +170,32 @@ pub fn render_subagent_system_prompt_with_format(// section order. Skipped entirely when both layers are `None`.write_agents_md_blocks(&mut out, agents_md_global, agents_md_local);- // 2. Filtered tool catalogue. Indices are taken in ascending order- // from `allowed_indices`, which itself preserves `parent_tools`- // order, so the rendering is deterministic. We use `.get(i)`- // defensively even though the current caller (subagent host)- // only produces in-range indices — a future caller that derives- // indices from a different source must not be able to panic this- // renderer with a stale index.- //- // Rendering uses the caller-specified `tool_call_format` so- // sub-agents and the main dispatcher stay in lockstep.- // Tool catalogue rendering is dispatcher-format-aware:- //- // - **Native**: The provider receives full tool schemas through- // the request body's `tools` field (via `filtered_specs` in the- // sub-agent runner) and emits structured `tool_calls`. Listing- // the same tools again as prose in the system prompt is pure- // duplication — for a integrations_agent spawn with 62 dynamic gmail- // tools, that duplication added ~54k tokens and blew past the- // model's context window. We skip the prose `## Tools` section- // entirely in this mode.- //- // - **PFormat / Json**: Both are prompt-driven formats — the- // model discovers tools by reading the prose `## Tools` section- // and emits text-wrapped tool calls (`<tool_call>name[a|b]</tool_call>`- // for PFormat, `<tool_call>{"name":...}</tool_call>` for Json).- // Neither uses the native `tools` request field, so we MUST- // list each tool in prose — including dynamically-registered- // `extra_tools` — or the model has no way to know they exist.- if !matches!(tool_call_format, ToolCallFormat::Native) {- out.push_str("## Tools\n\n");- let render_one = |out: &mut String, tool: &dyn tinytools::Tool| match tool_call_format {- ToolCallFormat::PFormat => {- let sig = render_pformat_signature_for_box_tool(tool);- let _ = writeln!(- out,- "- **{}**: {}\n Call as: `{}`",- tool.name(),- tool.description(),- sig- );- }- ToolCallFormat::Json => {- let _ = writeln!(- out,- "- **{}**: {}\n Parameters: `{}`",- tool.name(),- tool.description(),- tool.parameters_schema()- );- }- ToolCallFormat::Python | ToolCallFormat::TypeScript => {- let Some(style) = tool_call_format.code_style() else {- return;- };- let spec = tinytools::ToolSpec {- name: tool.name().to_string(),- description: tool.description().to_string(),- parameters: tool.parameters_schema(),- };- // Reuse the canonical renderer, minus its heading — the- // heading was written once above for the whole list.- let rendered = tinytools_agent::render::render_code_catalogue(&[spec], style);- out.push_str(- rendered- .strip_prefix(tinytools_agent::render::CATALOGUE_HEADING)- .unwrap_or(&rendered),- );- }- ToolCallFormat::Native => {- // Unreachable — outer guard skips Native entirely.- }- };- for &i in allowed_indices {- let Some(tool) = parent_tools.get(i) else {- tracing::warn!(- index = i,- tool_count = parent_tools.len(),- "[context::prompt] dropping out-of-range tool index in subagent render"- );- continue;- };- render_one(&mut out, tool.as_ref());- }- for tool in extra_tools {- render_one(&mut out, tool.as_ref());- }- }-- // 3. Sub-agent calling-convention preamble — format-aware.- // Sub-agents need the same call format the main dispatcher expects- // so their output parses correctly.- out.push('\n');- match tool_call_format {- ToolCallFormat::PFormat => {- out.push_str(- "## Tool Use Protocol\n\n\- Tool calls use **P-Format**: compact, positional, pipe-delimited syntax \- wrapped in `<tool_call>` tags.\n\n\- ```\n<tool_call>\ntool_name[arg1|arg2]\n</tool_call>\n```\n\n\- Arguments are positional — match the order shown in each tool's `Call as:` \- signature above (alphabetical by parameter name). \- Escape `|` as `\\|`, `]` as `\\]` inside values. \- You may emit multiple `<tool_call>` blocks per response.\n\n\- Use the provided tools to accomplish the task. Reply with a concise, dense \- final answer when you have one — the parent agent will weave it back into the \- user-visible response.\n\n",- );- }- ToolCallFormat::Json => {- out.push_str(- "## Tool Use Protocol\n\n\- To use a tool, wrap a JSON object in `<tool_call></tool_call>` tags:\n\n\- ```\n<tool_call>\n{\"name\": \"tool_name\", \"arguments\": {\"param\": \"value\"}}\n</tool_call>\n```\n\n\- You may emit multiple `<tool_call>` blocks in a single response.\n\n\- Use the provided tools to accomplish the task. Reply with a concise, dense \- final answer when you have one — the parent agent will weave it back into the \- user-visible response.\n\n",+ // 2. TinyTools owns both the catalogue and calling protocol. Collect the+ // filtered surface in deterministic order, then delegate its rendering to+ // the same dialect that parses the model response.+ let mut tool_specs = Vec::new();+ for &i in allowed_indices {+ let Some(tool) = parent_tools.get(i) else {+ tracing::warn!(+ index = i,+ tool_count = parent_tools.len(),+ "[context::prompt] dropping out-of-range tool index in subagent render");- }- ToolCallFormat::Python | ToolCallFormat::TypeScript => {- if let Some(style) = tool_call_format.code_style() {- out.push_str(&tinytools_agent::dialect::CodeDialect::instructions(style));- }- out.push_str(- "Use the provided tools to accomplish the task. Reply with a concise, dense \- final answer when you have one — the parent agent will weave it back into the \- user-visible response.\n\n",- );- }- ToolCallFormat::Native => {- out.push_str(- "Use the provided tools via the model's native tool-calling output. \- Reply with a concise, dense final answer when you have one — the parent \- agent will weave it back into the user-visible response.\n\n",- );- }+ continue;+ };+ tool_specs.push(tinytools::ToolSpec {+ name: tool.name().to_string(),+ description: tool.description().to_string(),+ parameters: tool.parameters_schema(),+ });}+ tool_specs.extend(extra_tools.iter().map(|tool| tinytools::ToolSpec {+ name: tool.name().to_string(),+ description: tool.description().to_string(),+ parameters: tool.parameters_schema(),+ }));+ out.push_str(&render_tool_dialect_prompt(tool_call_format, &tool_specs));+ out.push_str("\nUse the provided tools to accomplish the task. Reply with a concise, dense final answer when you have one — the parent agent will weave it back into the user-visible response.\n\n");// 3b. Optional safety preamble. Definitions that do work with real// side-effects (code_executor, tool_maker, integrations_agent) set@@ -349,20 +241,31 @@ pub fn render_subagent_system_prompt_with_format(out}-/// Build a P-Format signature line (`name[a|b|c]`) from a `&dyn Tool`.-/// Used by `render_subagent_system_prompt` which operates on `Box<dyn Tool>`-/// directly (no intermediate `PromptTool`). Mirrors the `PromptTool` variant-/// below — both BTreeMap-iterate the schema's `properties` in the same order.-fn render_pformat_signature_for_box_tool(tool: &dyn tinytools::Tool) -> String {- let schema = tool.parameters_schema();- let names: Vec<String> = schema- .get("properties")- .and_then(|p| p.as_object())- .map(|m| m.keys().cloned().collect())- .unwrap_or_default();- if names.is_empty() {- format!("{}[]", tool.name())- } else {- format!("{}[{}]", tool.name(), names.join("|"))+/// Ask TinyTools to produce the exact catalogue and protocol that its+/// corresponding dialect accepts. OpenHuman deliberately owns no syntax here.+fn render_tool_dialect_prompt(format: ToolCallFormat, tools: &[tinytools::ToolSpec]) -> String {+ match format {+ ToolCallFormat::Native => NativeDialect.prompt_instructions(tools),+ ToolCallFormat::Json => XmlDialect.prompt_instructions(tools),+ ToolCallFormat::PFormat => {+ let registry = tinytools_agent::build_registry(+ tools+ .iter()+ .map(|tool| (tool.name.as_str(), &tool.parameters)),+ );+ format!(+ "{}\n{}",+ tinytools_agent::dialect::render_pformat_catalogue(tools),+ PFormatDialect::new(registry).prompt_instructions(tools)+ )+ }+ ToolCallFormat::Python | ToolCallFormat::TypeScript => {+ let style = format.code_style().expect("code format has a code style");+ format!(+ "{}\n{}",+ tinytools_agent::render::render_code_catalogue(tools, style),+ CodeDialect::instructions(style)+ )+ }}}diff --git a/crates/openhuman-core/src/agent/prompts/sections.rs b/crates/openhuman-core/src/agent/prompts/sections.rsindex 9cdf145ec3..9f360a5992 100644--- a/crates/openhuman-core/src/agent/prompts/sections.rs+++ b/crates/openhuman-core/src/agent/prompts/sections.rs@@ -372,11 +372,11 @@ impl PromptSection for ToolsSection {}return Ok(ctx.dispatcher_instructions.to_string());}- // Render P-Format signatures from the parser's schemas and argument order. For- // `Native` dispatchers the provider already has the full JSON schema in- // the API request (handled above); for `Json` / `PFormat` text- // dispatchers the dispatcher's own `prompt_instructions` block- // (appended below) carries whatever schema detail the wire format needs.+ // TinyTools renders the compact catalogue from the same schemas and+ // argument order that its parser consumes. For `Native` dispatchers+ // the provider already has the full JSON schema in the API request+ // (handled above); text dispatchers receive their protocol through+ // the dialect's `prompt_instructions` block appended below.let has_filter = !ctx.visible_tool_names.is_empty();let visible: Vec<ToolSpec> = ctx.tools@@ -407,7 +407,7 @@ impl PromptSection for ToolsSection {// The JSON dialect's protocol block embeds its own full-schema// catalogue (`XmlDialect::embeds_tool_catalogue`), so rendering the// signature catalogue as well listed every tool twice — 13 KB of- // P-Format signatures on top of 28 KB of schemas for the orchestrator.+ // compact signatures on top of 28 KB of schemas for the orchestrator.let mut out = match ctx.tool_call_format {ToolCallFormat::Json if !ctx.dispatcher_instructions.trim().is_empty() => String::new(),format => match format.code_style() {diff --git a/crates/openhuman-core/src/agent/prompts/types.rs b/crates/openhuman-core/src/agent/prompts/types.rsindex 66a6901d24..7c1b15750a 100644--- a/crates/openhuman-core/src/agent/prompts/types.rs+++ b/crates/openhuman-core/src/agent/prompts/types.rs@@ -280,13 +280,13 @@ impl<'a> PromptTool<'a> {}}-/// How the tool catalogue should render each tool entry. Driven by the-/// dispatcher choice on the agent — JSON-schema rendering is the-/// historic format; P-Format is the new default text protocol.-#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]+/// How TinyTools should render and parse an agent's tool calls.+///+/// The prompt layer carries this only to select the TinyTools dialect; it does+/// not define a tool-call protocol of its own.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum ToolCallFormat {- /// `tool_name[arg1|arg2|...]` — compact, positional. Default.- #[default]+ /// Compact positional legacy dialect.PFormat,/// Legacy JSON-in-tag rendering with full schemas.Json,@@ -299,6 +299,12 @@ pub enum ToolCallFormat {TypeScript,}+impl Default for ToolCallFormat {+ fn default() -> Self {+ Self::Python+ }+}+impl ToolCallFormat {/// The harness policy that speaks this format.///diff --git a/crates/openhuman-core/src/agent/subagent_host/mod.rs b/crates/openhuman-core/src/agent/subagent_host/mod.rsindex 4ed5f0090c..bdefb04b74 100644--- a/crates/openhuman-core/src/agent/subagent_host/mod.rs+++ b/crates/openhuman-core/src/agent/subagent_host/mod.rs@@ -68,10 +68,6 @@ pub use types::{SubagentRunStatus, SubagentUsage,};-// Crate-internal re-exports: `agent::debug` calls the text-mode protocol-// renderer. The other `tool_prep` helpers are used only inside this module.-pub(crate) use tool_prep::build_text_mode_tool_instructions;-// Progressive-disclosure handoff: the tinyagents `HandoffMiddleware` intercepts// oversized sub-agent tool results via `apply_handoff`, sharing the per-spawn// `ResultHandoffCache` with the `extract_from_result` tool.diff --git a/crates/openhuman-core/src/agent/subagent_host/ops/runner.rs b/crates/openhuman-core/src/agent/subagent_host/ops/runner.rsindex dd48440930..10714ab74c 100644--- a/crates/openhuman-core/src/agent/subagent_host/ops/runner.rs+++ b/crates/openhuman-core/src/agent/subagent_host/ops/runner.rs@@ -33,9 +33,9 @@ use crate::agent::subagent_host::extract_tool::ExtractFromResultTool;use crate::agent::subagent_host::handoff::ResultHandoffCache;use crate::agent::subagent_host::subagent_iter_cap_with_autonomous_lift;use crate::agent::subagent_host::tool_prep::{- build_text_mode_tool_instructions, filter_tool_indices, is_subagent_spawn_tool,- load_prompt_source, select_actions_with_essentials, strip_spawn_tools_from_dynamic,- subagent_prompt_protocol, top_k_for_toolkit,+ filter_tool_indices, is_subagent_spawn_tool, load_prompt_source,+ select_actions_with_essentials, strip_spawn_tools_from_dynamic, subagent_prompt_protocol,+ top_k_for_toolkit,};use crate::agent::subagent_host::types::{SubagentMode, SubagentRunError, SubagentRunOptions, SubagentRunOutcome, SubagentRunStatus,@@ -1384,8 +1384,11 @@ async fn run_typed_mode(.collect();let visible_tool_names: std::collections::HashSet<String> =prompt_tools.iter().map(|t| t.name.to_string()).collect();- let (prompt_tool_call_format, dispatcher_instructions) =- subagent_prompt_protocol(parent.tool_call_format, is_integrations_agent_with_toolkit);+ let (prompt_tool_call_format, dispatcher_instructions) = subagent_prompt_protocol(+ parent.tool_call_format,+ is_integrations_agent_with_toolkit,+ &filtered_specs,+ );// Load AGENTS.md instruction layers once, at prompt-build time, when the// config gate is on. The global layer comes from the workspace dir; the// project layer comes from the sub-agent's `worktree_action_dir` override@@ -1515,15 +1518,11 @@ async fn run_typed_mode(// rejected). Wrapping the provider clears `native_tool_calling`, which makes// the model adapter skip native advertisement and fall back to XML parsing.if is_integrations_agent_with_toolkit {- if let Some(sys) = history.iter_mut().find(|m| m.role == "system") {- sys.content.push_str("\n\n");- sys.content.push_str(&build_text_mode_tool_instructions());- }tracing::info!(agent_id = %definition.id,task_id = %task_id,tool_count = filtered_specs.len(),- "[subagent_host:text-mode] omitting native tool schemas; injected XML tool protocol into system prompt"+ "[subagent_host:text-mode] omitting native tool schemas; TinyTools JSON dialect owns the prompt protocol");subagent_source = subagent_source.with_text_mode();}diff --git a/crates/openhuman-core/src/agent/subagent_host/tool_prep.rs b/crates/openhuman-core/src/agent/subagent_host/tool_prep.rsindex fc0768552e..c7abaef2bd 100644--- a/crates/openhuman-core/src/agent/subagent_host/tool_prep.rs+++ b/crates/openhuman-core/src/agent/subagent_host/tool_prep.rs@@ -163,90 +163,43 @@ pub(super) fn select_actions_with_essentials(selected}-// ── Text-mode protocol block ────────────────────────────────────────────+// ── Text-mode dialect selection ─────────────────────────────────────────-/// Format the tool-use protocol block appended to the system prompt in text-/// mode. Teaches **P-Format** first (the same protocol-/// [`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-/// signatures for every tool, so teaching JSON here contradicted the-/// catalogue and threw away the p-format token savings.+/// Select the TinyTools-owned tool-use protocol for text-mode sub-agents.///-/// Per-parameter rendering is intentionally **compact**: name, type, a-/// "required" marker, and a short one-line description if present. We-/// do **not** serialise the full JSON schema. Composio/Fireworks action-/// schemas for toolkits like Gmail or Notion run multiple KB each —-/// embedding them verbatim blows up the prompt past the model's-/// context window (282k+ tokens for 26 Gmail tools vs a 196k cap).-/// The compact listing keeps the model informed enough to call tools-/// correctly while staying within budget. If the model needs deeper-/// schema detail it can surface the error and the orchestrator will-/// clarify on the next turn.-pub(crate) fn build_text_mode_tool_instructions() -> String {- // The tool catalog is already rendered in the prompt's `## Tools`- // section (see `prompts::ToolsSection::build`) with full- // `Call as: NAME[arg|arg]` signatures. We previously also emitted- // an `### Available Tools` subsection here with a different- // formatting (`Parameters: name:type, ...`), which doubled the- // tool list bytes for text-mode agents — especially expensive for- // the integrations_agent toolkit-scoped spawns (~50 actions ×- // 2 listings). Keep only the protocol explanation; the tool- // catalog itself comes from the prompt template.- let mut out = String::new();- out.push_str("## Tool Use Protocol\n\n");- out.push_str(- "Tool calls use **P-Format** (Parameter-Format): compact, positional, \- pipe-delimited syntax wrapped in `<tool_call>` tags.\n\n",- );- out.push_str("```\n<tool_call>\nGMAIL_FETCH_EMAILS[ca_123||10]\n</tool_call>\n```\n\n");- out.push_str(- "**Rules:**\n\- - Form: `name[arg1|arg2|...|argN]`. Arguments are positional and must match the \- order shown in each tool's `Call as:` signature in the `## Tools` section \- (alphabetical by parameter name). Leave a slot empty to omit that argument.\n\- - Empty calls: `name[]` for zero-arg tools.\n\- - Escapes inside argument values: `\\|` for a literal `|`, `\\]` for `]`, `\\\\` for `\\`.\n\- - Do not nest tags. Emit one tag per call; you can emit multiple tags in the same \- response to run calls in parallel.\n\- - When an argument needs a nested object or array that p-format cannot express, \- fall back to the JSON form in the same tags: \- `<tool_call>{\"name\": \"tool_name\", \"arguments\": {\"param\": \"value\"}}</tool_call>`. \- Prefer p-format for everything else.\n",- );- out-}-+/// Tool syntax and tool catalogue rendering live in TinyTools. Keeping only+/// dialect selection here prevents OpenHuman prompt text from drifting from+/// the parser that consumes the response./// The tool-call format a sub-agent's prompt is rendered for, and the/// dispatcher protocol block that goes with it.////// Normally both follow the parent. A text-mode child (the toolkit-scoped/// `integrations_agent`) is sent no native `tools`, so it must render its own-/// catalogue as text whatever the parent uses: under a native-tool parent,-/// `ToolsSection` would otherwise emit no catalogue and the native JSON protocol,-/// and the child would be told how to call tools but never which ones exist.-/// Its protocol block is empty because the runner appends-/// [`build_text_mode_tool_instructions`] itself.+/// catalogue as text whatever the parent uses. Text-mode children use the+/// TinyTools JSON dialect, which can faithfully carry nested tool arguments.pub(crate) fn subagent_prompt_protocol(parent_format: crate::agent::prompts::ToolCallFormat,text_mode: bool,+ tools: &[tinytools::ToolSpec],) -> (crate::agent::prompts::ToolCallFormat, String) {use crate::agent::prompts::ToolCallFormat;use tinytools_agent::dialect::{CodeDialect, CodeStyle, NativeDialect, PFormatDialect, ToolDialect, XmlDialect,};- use tinytools_agent::PFormatRegistry;if text_mode {- return (ToolCallFormat::PFormat, String::new());+ return (ToolCallFormat::Json, XmlDialect.prompt_instructions(tools));}- let empty_tools = Vec::new();let instructions = match parent_format {ToolCallFormat::PFormat => {- PFormatDialect::new(PFormatRegistry::new()).prompt_instructions(&empty_tools)+ let registry = tinytools_agent::build_registry(+ tools+ .iter()+ .map(|tool| (tool.name.as_str(), &tool.parameters)),+ );+ PFormatDialect::new(registry).prompt_instructions(tools)}- ToolCallFormat::Native => NativeDialect.prompt_instructions(&empty_tools),- ToolCallFormat::Json => XmlDialect.prompt_instructions(&empty_tools),+ ToolCallFormat::Native => NativeDialect.prompt_instructions(tools),+ ToolCallFormat::Json => XmlDialect.prompt_instructions(tools),ToolCallFormat::Python => CodeDialect::instructions(CodeStyle::Python),ToolCallFormat::TypeScript => CodeDialect::instructions(CodeStyle::TypeScript),};diff --git a/crates/openhuman-core/src/agent/subagent_host/tool_prep_tests.rs b/crates/openhuman-core/src/agent/subagent_host/tool_prep_tests.rsindex aaf3a7f0aa..6f908052ad 100644--- a/crates/openhuman-core/src/agent/subagent_host/tool_prep_tests.rs+++ b/crates/openhuman-core/src/agent/subagent_host/tool_prep_tests.rs@@ -455,11 +455,19 @@ fn render_tools_at(format: crate::agent::prompts::ToolCallFormat, instructions:fn text_mode_child_of_a_native_parent_renders_its_tool_catalogue() {use crate::agent::prompts::ToolCallFormat;- let (format, instructions) = subagent_prompt_protocol(ToolCallFormat::Native, true);- assert_eq!(format, ToolCallFormat::PFormat);+ let specs = [tinytools::ToolSpec {+ name: "composio_execute".into(),+ description: "Run one Composio action.".into(),+ parameters: serde_json::json!({+ "type": "object",+ "properties": {"action": {"type": "string"}}+ }),+ }];+ let (format, instructions) = subagent_prompt_protocol(ToolCallFormat::Native, true, &specs);+ assert_eq!(format, ToolCallFormat::Json);assert!(- instructions.is_empty(),- "the runner appends the text-mode protocol itself; a second block conflicts: {instructions}"+ !instructions.is_empty(),+ "TinyTools must supply the text-mode protocol: {instructions}");let rendered = render_tools_at(format, &instructions);assert!(@@ -483,7 +491,7 @@ fn native_child_keeps_the_parents_protocol() {ToolCallFormat::PFormat,ToolCallFormat::Json,] {- let (format, _) = subagent_prompt_protocol(parent, false);+ let (format, _) = subagent_prompt_protocol(parent, false, &[]);assert_eq!(format, parent);}}