feat(brain): keep how each answer was made (records, tools, plan, thinking, tool calls)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
javis-bot
2026-11-16 03:00:10 +09:00
parent 2a140d8490
commit a20ebe4eae
8 changed files with 265 additions and 8 deletions

View File

@@ -27,6 +27,7 @@ from .enrichment import (
digest_tool_result_for_query,
digest_loop_for_max_turns,
)
from . import turn_state as _turn_state
from .prompt_dump import dump_reply_turn, is_enabled as _prompt_dump_enabled, new_session_id
from .prompts import ModelSize, detect_model_size, get_system_prompts
from .compound_query import split_compound_query
@@ -61,6 +62,22 @@ if TYPE_CHECKING:
# ── Helpers ─────────────────────────────────────────────────────────────────
# How much of a tool result and of the model's thinking a trace keeps (history.spec.md, "Traces").
TRACE_RESULT_CHARS = 2000
TRACE_THINKING_CHARS = 8000
def _clip(text: str, limit: int) -> str:
return text if len(text) <= limit else text[:limit] + "…"
def _trace_tool(name: str, args, result) -> None:
"""One executed tool call in the turn's trace: name, arguments, outcome and the start of its result."""
text = result.reply_text or result.error_message or ""
_turn_state.trace("tool", name=name, args=args or {}, ok=bool(result.success),
result=_clip(str(text), TRACE_RESULT_CHARS))
def _indent_text(text: str, prefix: str = " ") -> str:
return f"\n{prefix}".join(text.splitlines())
@@ -1419,6 +1436,7 @@ def run_reply_engine(db: "Database", cfg, tts: Optional[Any],
routed_tools = [t for t in routed_tools if t != "webSearch"]
debug_log("screen-share: site named — dropping webSearch so controlBrowser wins", "tools")
_turn_state.trace("tools", names=list(routed_tools))
_planner_schema = generate_tools_json_schema(routed_tools, mcp_tools)
_planner_tool_catalog = planner_tool_catalog(_planner_schema or [])
@@ -1438,6 +1456,7 @@ def run_reply_engine(db: "Database", cfg, tts: Optional[Any],
debug_log(f"planner step failed (non-fatal): {_plan_exc}", "planning")
action_plan = []
if action_plan:
_turn_state.trace("plan", steps=list(action_plan))
_plan_preview = " | ".join(s[:50] for s in action_plan)
print(
f" 🗺️ Plan: {len(action_plan)} step(s) — {_plan_preview}",
@@ -2389,6 +2408,7 @@ def run_reply_engine(db: "Database", cfg, tts: Optional[Any],
max_retries=1,
language=language,
)
_trace_tool(_name, _args, _plan_result)
if _plan_result.reply_text:
_plan_text = _maybe_digest_tool_result(
cfg=cfg,
@@ -2602,6 +2622,7 @@ def run_reply_engine(db: "Database", cfg, tts: Optional[Any],
# Always show thinking if present, regardless of content
if thinking:
_turn_state.trace("think", text=_clip(str(thinking), TRACE_THINKING_CHARS))
debug_log(f" 💭 LLM thinking: '{thinking[:300]}{'...' if len(thinking) > 300 else ''}'", "planning")
# Extract tool call if present
@@ -2647,6 +2668,7 @@ def run_reply_engine(db: "Database", cfg, tts: Optional[Any],
# Check if tool is not allowed - respond with tool error
if tool_name not in allowed_tools:
debug_log(f" ⚠️ tool not allowed: {tool_name}", "planning")
_turn_state.trace("tool", name=tool_name, args=tool_args or {}, ok=False, skipped="not_allowed")
print(f" ⚠️ Tool '{tool_name}' not in allow-list", flush=True)
# Use tool response instead of system message to maintain native tool calling compatibility
messages.append({
@@ -2694,6 +2716,7 @@ def run_reply_engine(db: "Database", cfg, tts: Optional[Any],
if signature in recent_tool_signatures:
debug_log(f" ⚠️ Duplicate {tool_name} call - returning cached guidance", "planning")
_turn_state.trace("tool", name=tool_name, args=tool_args or {}, ok=False, skipped="duplicate")
if use_text_tools:
messages.append({"role": "user", "content": f"[Tool: {tool_name}] You already called this tool with these arguments. Use the results from the previous tool call to answer the user."})
else:
@@ -2713,6 +2736,7 @@ def run_reply_engine(db: "Database", cfg, tts: Optional[Any],
)
if duplicate_tool_count >= 2:
debug_log(f" ⚠️ Too many {tool_name} calls ({duplicate_tool_count}) - returning guidance", "planning")
_turn_state.trace("tool", name=tool_name, args=tool_args or {}, ok=False, skipped="duplicate")
if use_text_tools:
messages.append({"role": "user", "content": f"[Tool: {tool_name}] You have already called this tool {duplicate_tool_count} times. Use the results from those calls to answer the user's question."})
else:
@@ -2731,6 +2755,7 @@ def run_reply_engine(db: "Database", cfg, tts: Optional[Any],
max_retries=1,
language=language,
)
_trace_tool(tool_name, tool_args, result)
# Handle stop tool - end conversation without response
if result.reply_text == STOP_SIGNAL: