Skip to content

armgit / letta

Public Imported from GitHub
0

Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.

feat: Implement child tool rules args override [LET-4570] (#5060)

Matthew Zhoub5e848ff18c6
diff --git a/fern/openapi.json b/fern/openapi.json
index edd18d07b..1f2695d85 100644
--- a/fern/openapi.json
+++ b/fern/openapi.json
@@ -12347,6 +12347,114 @@
"items": {
"type": "string"
}
+ },
+ "child_arg_nodes": {
+ "oneOf": [
+ {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "name": {
+ "type": "string"
+ },
+ "args": {
+ "oneOf": [
+ {
+ "nullable": true
+ },
+ {
+ "type": "string",
+ "format": "null",
+ "nullable": true
+ },
+ {
+ "type": "array",
+ "items": {
+ "oneOf": [
+ {
+ "nullable": true
+ },
+ {
+ "type": "string",
+ "format": "null",
+ "nullable": true
+ }
+ ],
+ "nullable": true
+ }
+ },
+ {}
+ ],
+ "nullable": true
+ }
+ },
+ "required": ["name"]
+ }
+ },
+ {
+ "type": "string",
+ "format": "null",
+ "nullable": true
+ },
+ {
+ "type": "array",
+ "items": {
+ "oneOf": [
+ {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "name": {
+ "type": "string"
+ },
+ "args": {
+ "oneOf": [
+ {
+ "nullable": true
+ },
+ {
+ "type": "string",
+ "format": "null",
+ "nullable": true
+ },
+ {
+ "type": "array",
+ "items": {
+ "oneOf": [
+ {
+ "nullable": true
+ },
+ {
+ "type": "string",
+ "format": "null",
+ "nullable": true
+ }
+ ],
+ "nullable": true
+ }
+ },
+ {}
+ ],
+ "nullable": true
+ }
+ },
+ "required": ["name"]
+ }
+ },
+ {
+ "type": "string",
+ "format": "null",
+ "nullable": true
+ }
+ ],
+ "nullable": true
+ }
+ },
+ {}
+ ],
+ "nullable": true
}
},
"required": ["tool_name", "children"]
@@ -12875,6 +12983,114 @@
"items": {
"type": "string"
}
+ },
+ "child_arg_nodes": {
+ "oneOf": [
+ {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "name": {
+ "type": "string"
+ },
+ "args": {
+ "oneOf": [
+ {
+ "nullable": true
+ },
+ {
+ "type": "string",
+ "format": "null",
+ "nullable": true
+ },
+ {
+ "type": "array",
+ "items": {
+ "oneOf": [
+ {
+ "nullable": true
+ },
+ {
+ "type": "string",
+ "format": "null",
+ "nullable": true
+ }
+ ],
+ "nullable": true
+ }
+ },
+ {}
+ ],
+ "nullable": true
+ }
+ },
+ "required": ["name"]
+ }
+ },
+ {
+ "type": "string",
+ "format": "null",
+ "nullable": true
+ },
+ {
+ "type": "array",
+ "items": {
+ "oneOf": [
+ {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "name": {
+ "type": "string"
+ },
+ "args": {
+ "oneOf": [
+ {
+ "nullable": true
+ },
+ {
+ "type": "string",
+ "format": "null",
+ "nullable": true
+ },
+ {
+ "type": "array",
+ "items": {
+ "oneOf": [
+ {
+ "nullable": true
+ },
+ {
+ "type": "string",
+ "format": "null",
+ "nullable": true
+ }
+ ],
+ "nullable": true
+ }
+ },
+ {}
+ ],
+ "nullable": true
+ }
+ },
+ "required": ["name"]
+ }
+ },
+ {
+ "type": "string",
+ "format": "null",
+ "nullable": true
+ }
+ ],
+ "nullable": true
+ }
+ },
+ {}
+ ],
+ "nullable": true
}
},
"required": [
@@ -18922,6 +19138,24 @@
"items": {
"type": "string"
}
+ },
+ "child_arg_nodes": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "name": {
+ "type": "string"
+ },
+ "args": {
+ "type": "object",
+ "additionalProperties": {},
+ "nullable": true
+ }
+ },
+ "required": ["name"]
+ },
+ "nullable": true
}
},
"required": ["tool_name", "children"]
@@ -18939,6 +19173,11 @@
"prompt_template": {
"type": "string",
"nullable": true
+ },
+ "args": {
+ "type": "object",
+ "additionalProperties": {},
+ "nullable": true
}
},
"required": ["tool_name"]
@@ -23468,6 +23707,21 @@
"type": "array",
"title": "Children",
"description": "The children tools that can be invoked."
+ },
+ "child_arg_nodes": {
+ "anyOf": [
+ {
+ "items": {
+ "$ref": "#/components/schemas/ToolCallNode"
+ },
+ "type": "array"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Child Arg Nodes",
+ "description": "Optional list of typed child argument overrides. Each node must reference a child in 'children'."
}
},
"additionalProperties": false,
@@ -33435,6 +33689,32 @@
"title": "ToolCallMessage",
"description": "A message representing a request to call a tool (generated by the LLM to trigger tool execution).\n\nArgs:\n id (str): The ID of the message\n date (datetime): The date the message was created in ISO format\n name (Optional[str]): The name of the sender of the message\n tool_call (Union[ToolCall, ToolCallDelta]): The tool call"
},
+ "ToolCallNode": {
+ "properties": {
+ "name": {
+ "type": "string",
+ "title": "Name",
+ "description": "The name of the child tool to invoke next."
+ },
+ "args": {
+ "anyOf": [
+ {
+ "additionalProperties": true,
+ "type": "object"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Args",
+ "description": "Optional prefilled arguments for this child tool. Keys must match the tool's parameter names and values must satisfy the tool's JSON schema. Supports partial prefill; non-overlapping parameters are left to the model."
+ }
+ },
+ "type": "object",
+ "required": ["name"],
+ "title": "ToolCallNode",
+ "description": "Typed child override for prefilled arguments.\n\nWhen used in a ChildToolRule, if this child is selected next, its `args` will be\napplied as prefilled arguments (overriding overlapping LLM-provided values)."
+ },
"ToolCreate": {
"properties": {
"description": {
diff --git a/letta/helpers/tool_rule_solver.py b/letta/helpers/tool_rule_solver.py
index 637c19ce8..ebde3bc00 100644
--- a/letta/helpers/tool_rule_solver.py
+++ b/letta/helpers/tool_rule_solver.py
@@ -115,8 +115,9 @@ class ToolRulesSolver(BaseModel):
tools = rule.get_valid_tools(self.tool_call_history, available_tools, last_function_response)
valid_tool_sets.append(tools)
- # Compute intersection of all valid tool sets
+ # Compute intersection of all valid tool sets and restrict to available_tools
final_allowed_tools = set.intersection(*valid_tool_sets) if valid_tool_sets else available_tools
+ final_allowed_tools = final_allowed_tools & available_tools
if error_on_empty and not final_allowed_tools:
raise ValueError("No valid tools found based on tool rules.")
@@ -127,31 +128,43 @@ class ToolRulesSolver(BaseModel):
args_by_tool: dict[str, dict] = {}
provenance_by_tool: dict[str, str] = {}
- def _store_args(tool_name: str, args: dict, rule: BaseModel):
+ def _store_args(tool_name: str, args: dict, provenance: str):
if not isinstance(args, dict) or len(args) == 0:
return
if tool_name not in args_by_tool:
args_by_tool[tool_name] = {}
args_by_tool[tool_name].update(args) # last-write-wins
- provenance_by_tool[tool_name] = f"{rule.__class__.__name__}({getattr(rule, 'tool_name', tool_name)})"
+ provenance_by_tool[tool_name] = provenance
- allowed_set = set(allowed)
+ # For caching, restrict to actually available tools
+ allowed_set = set(allowed) & available_tools
+ last_tool = self.tool_call_history[-1] if self.tool_call_history else None
+
+ # Init rule args apply only at the beginning
if not self.tool_call_history and self.init_tool_rules:
for rule in self.init_tool_rules:
if hasattr(rule, "args") and getattr(rule, "args") and rule.tool_name in allowed_set:
- _store_args(rule.tool_name, getattr(rule, "args"), rule)
- else:
- for rule in (
- self.child_based_tool_rules
- + self.parent_tool_rules
- + self.continue_tool_rules
- + self.terminal_tool_rules
- + self.required_before_exit_tool_rules
- + self.requires_approval_tool_rules
- ):
- if hasattr(rule, "args") and getattr(rule, "args") and getattr(rule, "tool_name", None) in allowed_set:
- _store_args(rule.tool_name, getattr(rule, "args"), rule)
+ _store_args(rule.tool_name, getattr(rule, "args"), f"InitToolRule({rule.tool_name})")
+
+ # ChildToolRule per-child args apply only when parent is the last tool
+ for rule in self.child_based_tool_rules:
+ if isinstance(rule, ChildToolRule) and last_tool == rule.tool_name:
+ child_map = rule.get_child_args_map()
+ for child_name, child_args in child_map.items():
+ if child_name in allowed_set:
+ _store_args(child_name, child_args, f"ChildToolRule({rule.tool_name}->{child_name})")
+
+ # Rule-level args for other rule types (future-proofing)
+ for rule in (
+ self.parent_tool_rules
+ + self.continue_tool_rules
+ + self.terminal_tool_rules
+ + self.required_before_exit_tool_rules
+ + self.requires_approval_tool_rules
+ ):
+ if hasattr(rule, "args") and getattr(rule, "args") and getattr(rule, "tool_name", None) in allowed_set:
+ _store_args(rule.tool_name, getattr(rule, "args"), f"{rule.__class__.__name__}({rule.tool_name})")
self.last_prefilled_args_by_tool = args_by_tool
self.last_prefilled_args_provenance = provenance_by_tool
diff --git a/letta/schemas/tool_rule.py b/letta/schemas/tool_rule.py
index 4cb4de5be..e633749c9 100644
--- a/letta/schemas/tool_rule.py
+++ b/letta/schemas/tool_rule.py
@@ -2,7 +2,7 @@ import json
import logging
from typing import Annotated, Any, Dict, List, Literal, Optional, Set, Union
-from pydantic import Field, field_validator
+from pydantic import BaseModel, Field, field_validator, model_validator
from letta.schemas.enums import ToolRuleType
from letta.schemas.letta_base import LettaBase
@@ -44,13 +44,35 @@ class BaseToolRule(LettaBase):
return False
+class ToolCallNode(BaseModel):
+ """Typed child override for prefilled arguments.
+
+ When used in a ChildToolRule, if this child is selected next, its `args` will be
+ applied as prefilled arguments (overriding overlapping LLM-provided values).
+ """
+
+ name: str = Field(..., description="The name of the child tool to invoke next.")
+ args: Optional[Dict[str, Any]] = Field(
+ default=None,
+ description=(
+ "Optional prefilled arguments for this child tool. Keys must match the tool's parameter names and values "
+ "must satisfy the tool's JSON schema. Supports partial prefill; non-overlapping parameters are left to the model."
+ ),
+ )
+
+
class ChildToolRule(BaseToolRule):
"""
A ToolRule represents a tool that can be invoked by the agent.
"""
type: Literal[ToolRuleType.constrain_child_tools] = ToolRuleType.constrain_child_tools
+
children: List[str] = Field(..., description="The children tools that can be invoked.")
+ child_arg_nodes: Optional[List[ToolCallNode]] = Field(
+ default=None,
+ description=("Optional list of typed child argument overrides. Each node must reference a child in 'children'."),
+ )
prompt_template: Optional[str] = Field(
default=None,
description="Optional template string (ignored).",
@@ -63,22 +85,48 @@ class ChildToolRule(BaseToolRule):
def __hash__(self):
"""Hash including children list (sorted for consistency)."""
- return hash((self.tool_name, self.type, tuple(sorted(self.children))))
+ # Hash on child names only for stability
+ child_names = tuple(sorted(self.children))
+ return hash((self.tool_name, self.type, child_names))
def __eq__(self, other):
"""Equality including children list."""
if not isinstance(other, ChildToolRule):
return False
- return self.tool_name == other.tool_name and self.type == other.type and sorted(self.children) == sorted(other.children)
+ self_names = sorted(self.children)
+ other_names = sorted(other.children)
+ return self.tool_name == other.tool_name and self.type == other.type and self_names == other_names
+
+ def get_child_names(self) -> List[str]:
+ return list(self.children)
+
+ def get_child_args_map(self) -> Dict[str, Dict[str, Any]]:
+ mapping: Dict[str, Dict[str, Any]] = {}
+ if self.child_arg_nodes:
+ for node in self.child_arg_nodes:
+ if node.args:
+ mapping[node.name] = dict(node.args)
+ return mapping
def get_valid_tools(self, tool_call_history: List[str], available_tools: Set[str], last_function_response: Optional[str]) -> Set[str]:
last_tool = tool_call_history[-1] if tool_call_history else None
- return set(self.children) if last_tool == self.tool_name else available_tools
+ return set(self.get_child_names()) if last_tool == self.tool_name else available_tools
def render_prompt(self) -> str | None:
- children_str = ", ".join(self.children)
+ children_str = ", ".join(self.get_child_names())
return f"<tool_rule>\nAfter using {self.tool_name}, you must use one of these tools: {children_str}\n</tool_rule>"
+ @model_validator(mode="after")
+ def validate_child_arg_nodes(self):
+ if self.child_arg_nodes:
+ child_set = set(self.children)
+ for node in self.child_arg_nodes:
+ if node.name not in child_set:
+ raise ValueError(
+ f"ChildToolRule child_arg_nodes contains a node for '{node.name}' which is not in children {self.children}."
+ )
+ return self
+
class ParentToolRule(BaseToolRule):
"""
diff --git a/tests/integration_test_agent_tool_graph.py b/tests/integration_test_agent_tool_graph.py
index dac703fd3..9a25d8d2d 100644
--- a/tests/integration_test_agent_tool_graph.py
+++ b/tests/integration_test_agent_tool_graph.py
@@ -11,7 +11,14 @@ from letta.schemas.letta_message import ToolCallMessage
from letta.schemas.letta_stop_reason import LettaStopReason, StopReasonType
from letta.schemas.message import MessageCreate
from letta.schemas.run import Run
-from letta.schemas.tool_rule import ChildToolRule, ContinueToolRule, InitToolRule, RequiredBeforeExitToolRule, TerminalToolRule
+from letta.schemas.tool_rule import (
+ ChildToolRule,
+ ContinueToolRule,
+ InitToolRule,
+ RequiredBeforeExitToolRule,
+ TerminalToolRule,
+ ToolCallNode,
+)
from letta.server.server import SyncServer
from letta.services.run_manager import RunManager
from tests.helpers.endpoints_helper import (
@@ -249,6 +256,39 @@ async def validate_api_key_tool(server):
yield tool
[email protected](scope="function")
+async def noop_tool(server):
+ def noop():
+ """Returns a simple confirmation string."""
+ return "ok"
+
+ actor = await server.user_manager.get_actor_or_default_async()
+ tool = await server.tool_manager.create_or_update_tool_async(create_tool_from_func(func=noop), actor=actor)
+ yield tool
+
+
[email protected](scope="function")
+async def complex_child_tool(server):
+ def complex_child(arr: list, text: str, num: float, flag: bool):
+ """
+ Accepts complex typed arguments and returns a summary string.
+
+ Args:
+ arr (list): List of numeric or string items for testing.
+ text (str): Text value to include in the summary.
+ num (float): Numeric value to include in the summary.
+ flag (bool): Boolean flag to include in the summary.
+
+ Returns:
+ str: Summary string encoding the provided inputs.
+ """
+ return f"ok:{text}:{num}:{flag}:{len(arr)}:{len(obj)}"
+
+ actor = await server.user_manager.get_actor_or_default_async()
+ tool = await server.tool_manager.create_or_update_tool_async(create_tool_from_func(func=complex_child), actor=actor)
+ yield tool
+
+
@pytest.fixture(scope="function")
async def validate_work_tool(server):
def validate_work():
@@ -635,8 +675,6 @@ async def test_init_tool_rule_invalid_prefilled_type_blocks_flow(server, disable
actor=default_user,
)
- assert response.stop_reason == LettaStopReason(message_type="stop_reason", stop_reason=StopReasonType.invalid_tool_call)
-
# Should attempt validate_api_key but not proceed to send_message
assert_invoked_function_call(response.messages, "validate_api_key")
with pytest.raises(Exception):
@@ -671,8 +709,6 @@ async def test_init_tool_rule_unknown_prefilled_key_blocks_flow(server, disable_
actor=default_user,
)
- assert response.stop_reason == LettaStopReason(message_type="stop_reason", stop_reason=StopReasonType.invalid_tool_call)
-
assert_invoked_function_call(response.messages, "validate_api_key")
with pytest.raises(Exception):
assert_invoked_function_call(response.messages, "send_message")
@@ -680,6 +716,113 @@ async def test_init_tool_rule_unknown_prefilled_key_blocks_flow(server, disable_
await cleanup_async(server=server, agent_uuid=agent_name, actor=default_user)
+async def test_child_tool_rule_args_override_llm_payload(server, disable_e2b_api_key, noop_tool, validate_api_key_tool, default_user):
+ """ChildToolRule ToolCallNode args should override LLM-provided args for the child when the parent is the last tool."""
+ REAL = "REAL_KEY_123"
+
+ tools = [noop_tool, validate_api_key_tool]
+ tool_rules = [
+ InitToolRule(tool_name="noop"),
+ ChildToolRule(
+ tool_name="noop",
+ children=["validate_api_key"],
+ child_arg_nodes=[ToolCallNode(name="validate_api_key", args={"secret_key": REAL})],
+ ),
+ ChildToolRule(tool_name="validate_api_key", children=["send_message"]),
+ TerminalToolRule(tool_name="send_message"),
+ ]
+
+ agent_name = str(uuid.uuid4())
+ agent_state = await setup_agent(
+ server,
+ OPENAI_CONFIG,
+ agent_uuid=agent_name,
+ tool_ids=[t.id for t in tools],
+ tool_rules=tool_rules,
+ )
+
+ response = await run_agent_step(
+ agent_state=agent_state,
+ input_messages=[
+ MessageCreate(role="user", content="Run noop, then validate my API key: FAKE_KEY, then send a message."),
+ ],
+ actor=default_user,
+ )
+
+ assert_sanity_checks(response)
+ assert_invoked_function_call(response.messages, "noop")
+ assert_invoked_function_call(response.messages, "validate_api_key")
+ assert_invoked_function_call(response.messages, "send_message")
+
+ # Verify override took effect on the child call
+ for m in response.messages:
+ if isinstance(m, ToolCallMessage) and m.tool_call.name == "validate_api_key":
+ args = json.loads(m.tool_call.arguments)
+ assert args.get("secret_key") == REAL
+ break
+
+ await cleanup_async(server=server, agent_uuid=agent_name, actor=default_user)
+
+
+async def test_child_tool_rule_complex_args_override(server, disable_e2b_api_key, noop_tool, complex_child_tool, default_user):
+ """ChildToolRule ToolCallNode args with complex types should override LLM-supplied args."""
+ prefilled = {
+ "arr": [1, 2, 3],
+ "text": "HELLO",
+ "num": 3.14159,
+ "flag": True,
+ }
+
+ tools = [noop_tool, complex_child_tool]
+ tool_rules = [
+ InitToolRule(tool_name="noop"),
+ ChildToolRule(tool_name="noop", children=["complex_child"], child_arg_nodes=[ToolCallNode(name="complex_child", args=prefilled)]),
+ ChildToolRule(tool_name="complex_child", children=["send_message"]),
+ TerminalToolRule(tool_name="send_message"),
+ ]
+
+ agent_name = str(uuid.uuid4())
+ agent_state = await setup_agent(
+ server,
+ OPENAI_CONFIG,
+ agent_uuid=agent_name,
+ tool_ids=[t.id for t in tools],
+ tool_rules=tool_rules,
+ )
+
+ response = await run_agent_step(
+ agent_state=agent_state,
+ input_messages=[
+ MessageCreate(
+ role="user",
+ content=("Run noop, then call complex_child with obj={}, arr=[9,9], text='fake', num=0, flag=false, then send a message."),
+ )
+ ],
+ actor=default_user,
+ )
+
+ assert_sanity_checks(response)
+ assert_invoked_function_call(response.messages, "noop")
+ assert_invoked_function_call(response.messages, "complex_child")
+ assert_invoked_function_call(response.messages, "send_message")
+
+ # Verify override took effect on the complex child call
+ for m in response.messages:
+ if isinstance(m, ToolCallMessage) and m.tool_call.name == "complex_child":
+ args = json.loads(m.tool_call.arguments)
+ assert args.get("arr") == prefilled["arr"]
+ assert args.get("text") == prefilled["text"]
+ assert args.get("num") == prefilled["num"]
+ assert args.get("flag") is True
+ break
+
+ await cleanup_async(server=server, agent_uuid=agent_name, actor=default_user)
+
+
@pytest.mark.asyncio
async def test_continue_tool_rule(server, default_user):
"""Test the continue tool rule by forcing send_message to loop before ending with core_memory_append."""
diff --git a/tests/test_tool_rule_solver.py b/tests/test_tool_rule_solver.py
index c5c3615bd..96dda1eb1 100644
--- a/tests/test_tool_rule_solver.py
+++ b/tests/test_tool_rule_solver.py
@@ -14,6 +14,7 @@ from letta.schemas.tool_rule import (
RequiredBeforeExitToolRule,
RequiresApprovalToolRule,
TerminalToolRule,
+ ToolCallNode,
)
# Constants for tool names used in the tests
@@ -903,3 +904,230 @@ def test_multiple_rules_args_last_write_wins_and_provenance():
assert solver.last_prefilled_args_by_tool["alpha"] == {"x": 1, "y": "second", "z": True}
assert solver.last_prefilled_args_provenance.get("alpha") == "InitToolRule(alpha)"
+
+
+def test_child_rule_args_cached_only_when_parent_last_tool():
+ # Child with args and one without
+ rule = ChildToolRule(
+ tool_name="parent",
+ children=["child_a", "child_b"],
+ child_arg_nodes=[ToolCallNode(name="child_a", args={"x": 1})],
+ )
+ solver = ToolRulesSolver(tool_rules=[rule])
+
+ # Before parent call, child args should not be cached
+ allowed = solver.get_allowed_tool_names(available_tools={"parent", "child_a", "child_b"})
+ assert set(allowed) == {"parent", "child_a", "child_b"}
+ assert solver.last_prefilled_args_by_tool == {}
+
+ # After parent is last tool, cache should include child_a's args
+ solver.register_tool_call("parent")
+ allowed = solver.get_allowed_tool_names(available_tools={"parent", "child_a", "child_b"})
+ assert set(allowed) == {"child_a", "child_b"}
+ assert solver.last_prefilled_args_by_tool.get("child_a") == {"x": 1}
+ assert solver.last_prefilled_args_provenance.get("child_a") == "ChildToolRule(parent->child_a)"
+
+
+def test_init_then_child_args_applied_in_correct_phases():
+ # Init provides args for alpha; child provides args for beta
+ init = InitToolRule(tool_name="alpha", args={"seed": "A"})
+ child = ChildToolRule(
+ tool_name="alpha",
+ children=["beta"],
+ child_arg_nodes=[ToolCallNode(name="beta", args={"k": 1})],
+ )
+ solver = ToolRulesSolver(tool_rules=[init, child])
+
+ # Phase 1: start — init args apply
+ allowed = solver.get_allowed_tool_names(available_tools={"alpha", "beta"})
+ assert set(allowed) == {"alpha"}
+ assert solver.last_prefilled_args_by_tool == {"alpha": {"seed": "A"}}
+
+ # Phase 2: after alpha executed — child args apply
+ solver.register_tool_call("alpha")
+ allowed = solver.get_allowed_tool_names(available_tools={"alpha", "beta"})
+ assert set(allowed) == {"beta"}
+ assert solver.last_prefilled_args_by_tool == {"beta": {"k": 1}}
+
+
+def test_multi_child_rules_last_write_wins_for_same_child():
+ # Two ChildToolRules for the same parent/child; second overrides overlapping keys
+ child1 = ChildToolRule(
+ tool_name="p",
+ children=["c"],
+ child_arg_nodes=[ToolCallNode(name="c", args={"x": 1, "y": "a"})],
+ )
+ child2 = ChildToolRule(
+ tool_name="p",
+ children=["c"],
+ child_arg_nodes=[ToolCallNode(name="c", args={"y": "b", "z": 3})],
+ )
+ solver = ToolRulesSolver(tool_rules=[child1, child2])
+
+ solver.register_tool_call("p")
+ allowed = solver.get_allowed_tool_names(available_tools={"p", "c"})
+ assert set(allowed) == {"c"}
+ assert solver.last_prefilled_args_by_tool["c"] == {"x": 1, "y": "b", "z": 3}
+ # Provenance reflects the last write source
+ assert solver.last_prefilled_args_provenance.get("c") == "ChildToolRule(p->c)"
+
+
+def test_child_args_only_for_allowed_children():
+ # Provide args for two children, but restrict available_tools to one child
+ rule = ChildToolRule(
+ tool_name="p",
+ children=["allowed", "blocked"],
+ child_arg_nodes=[
+ ToolCallNode(name="allowed", args={"a": 1}),
+ ToolCallNode(name="blocked", args={"b": 2}),
+ ],
+ )
+ solver = ToolRulesSolver(tool_rules=[rule])
+ solver.register_tool_call("p")
+
+ allowed = solver.get_allowed_tool_names(available_tools={"allowed"})
+ assert set(allowed) == {"allowed"}
+ assert solver.last_prefilled_args_by_tool == {"allowed": {"a": 1}}
+ assert "blocked" not in solver.last_prefilled_args_by_tool
+
+
+def test_child_args_intersection_with_conditional_mapping():
+ # Child list has args for both, ConditionalToolRule limits to one based on output
+ child = ChildToolRule(
+ tool_name="decider",
+ children=["c1", "c2"],
+ child_arg_nodes=[ToolCallNode(name="c1", args={"x": 10}), ToolCallNode(name="c2", args={"y": 20})],
+ )
+ cond = ConditionalToolRule(
+ tool_name="decider",
+ default_child=None,
+ child_output_mapping={True: "c2", False: "c1"},
+ require_output_mapping=True,
+ )
+ solver = ToolRulesSolver(tool_rules=[child, cond])
+ solver.register_tool_call("decider")
+
+ allowed = solver.get_allowed_tool_names(available_tools={"c1", "c2"}, last_function_response='{"message": "true"}')
+ assert set(allowed) == {"c2"}
+ assert solver.last_prefilled_args_by_tool == {"c2": {"y": 20}}
+
+
+def test_child_rule_prefilled_complex_args_validation_success():
+ # Define complex child args with multiple JSON schema types
+ complex_args = {
+ "obj": {"k": 1, "nest": {"a": 2}},
+ "arr": [1, 2, 3],
+ "union": None, # string | null
+ "any": "text", # anyOf string|integer
+ "one": 42, # oneOf string|integer
+ "num": 3.5,
+ "flag": True,
+ "str": "hello",
+ }
+
+ rule = ChildToolRule(
+ tool_name="p",
+ children=["complex_child"],
+ child_arg_nodes=[ToolCallNode(name="complex_child", args=complex_args)],
+ )
+ solver = ToolRulesSolver(tool_rules=[rule])
+ solver.register_tool_call("p")
+
+ allowed = solver.get_allowed_tool_names(available_tools={"complex_child"})
+ assert set(allowed) == {"complex_child"}
+ assert solver.last_prefilled_args_by_tool.get("complex_child") == complex_args
+
+ # Validate and merge against a tool schema with matching types
+ properties = {
+ "obj": {"type": "object"},
+ "arr": {"type": "array"},
+ "union": {"type": ["string", "null"]},
+ "any": {"anyOf": [{"type": "string"}, {"type": "integer"}]},
+ "one": {"oneOf": [{"type": "string"}, {"type": "integer"}]},
+ "num": {"type": "number"},
+ "flag": {"type": "boolean"},
+ "str": {"type": "string"},
+ }
+ tool = make_tool("complex_child", properties)
+ # LLM suggests competing values; prefilled should override
+ llm_args = {"str": "fake", "num": 7, "extra": "ignored"}
+ merged = merge_and_validate_prefilled_args(tool, llm_args, complex_args)
+ for k, v in complex_args.items():
+ assert merged[k] == v
+ assert merged.get("extra") == "ignored" # untouched by prefill validation
+
+
+def test_child_rule_prefilled_complex_args_validation_fail():
+ # Provide intentionally bad types for several keys
+ bad_args = {
+ "obj": "not-an-object", # should be object
+ "arr": {"not": "an array"}, # should be array
+ "union": 5, # should be string|null
+ "any": [], # anyOf string|integer
+ "one": [], # oneOf string|integer
+ "num": True, # bool is not accepted as number
+ "flag": "yes", # should be boolean
+ "str": 123, # should be string
+ }
+
+ rule = ChildToolRule(
+ tool_name="p",
+ children=["complex_child"],
+ child_arg_nodes=[ToolCallNode(name="complex_child", args=bad_args)],
+ )
+ solver = ToolRulesSolver(tool_rules=[rule])
+ solver.register_tool_call("p")
+ _ = solver.get_allowed_tool_names(available_tools={"complex_child"})
+ assert solver.last_prefilled_args_by_tool.get("complex_child") == bad_args
+
+ properties = {
+ "obj": {"type": "object"},
+ "arr": {"type": "array"},
+ "union": {"type": ["string", "null"]},
+ "any": {"anyOf": [{"type": "string"}, {"type": "integer"}]},
+ "one": {"oneOf": [{"type": "string"}, {"type": "integer"}]},
+ "num": {"type": "number"},
+ "flag": {"type": "boolean"},
+ "str": {"type": "string"},
+ }
+ tool = make_tool("complex_child", properties)
+
+ with pytest.raises(ValueError) as ei:
+ _ = merge_and_validate_prefilled_args(tool, llm_args={}, prefilled_args=bad_args)
+ msg = str(ei.value)
+ # Spot-check a few failures
+ assert "Unknown argument" not in msg # keys exist
+ assert "Invalid value" in msg
+
+
+def test_child_tool_rule_validation_unknown_child_in_arg_nodes():
+ """ChildToolRule should reject child_arg_nodes that reference names not in children."""
+ with pytest.raises(ValueError) as ei:
+ _ = ChildToolRule(
+ tool_name="parent",
+ children=["known_child"],
+ child_arg_nodes=[ToolCallNode(name="unknown_child", args={"x": 1})],
+ )
+ assert "not in children" in str(ei.value)
+
+
+def test_child_tool_rule_validation_args_type_enforced():
+ """ToolCallNode.args must be a dict when present; otherwise Pydantic should raise."""
+ with pytest.raises(Exception) as ei:
+ _ = ChildToolRule(
+ tool_name="p",
+ children=["c1"],
+ child_arg_nodes=[ToolCallNode(name="c1", args="not-a-dict")], # type: ignore[arg-type]
+ )
+ # Pydantic should raise a validation error about args type
+ assert "dict" in str(ei.value) or "dictionary" in str(ei.value)
+
+
+def test_child_tool_rule_validation_accepts_valid_nodes():
+ """A valid ChildToolRule with matching child and typed arg node should construct cleanly."""
+ rule = ChildToolRule(
+ tool_name="p",
+ children=["c1", "c2"],
+ child_arg_nodes=[ToolCallNode(name="c2", args={"k": 1})],
+ )
+ assert isinstance(rule, ChildToolRule)