Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

feat(chat): Auto mode router + new chat tools (ask_user, web_fetch, etc.)

Bingxi Zhao (Frank)7bdb10b700f2
diff --git a/deeptutor/agents/auto/auto_pipeline.py b/deeptutor/agents/auto/auto_pipeline.py
index c7c6abdb8..887684496 100644
--- a/deeptutor/agents/auto/auto_pipeline.py
+++ b/deeptutor/agents/auto/auto_pipeline.py
@@ -72,11 +72,13 @@ from deeptutor.agents.auto.schemas import (
is_delegate_tool,
)
from deeptutor.capabilities._answer_now import extract_answer_now_context
+from deeptutor.capabilities._shared import emit_capability_result
from deeptutor.capabilities.request_contracts import (
AutoRequestConfig,
validate_auto_request_config,
validate_capability_config,
)
+from deeptutor.core.agentic.usage import UsageTracker
from deeptutor.core.context import UnifiedContext
from deeptutor.core.stream_bus import StreamBus
from deeptutor.core.trace import build_trace_metadata, new_call_id
@@ -141,6 +143,7 @@ class AutoPipeline:
self.extra_headers = getattr(self.llm_config, "extra_headers", None) or {}
self.cap_registry = get_capability_registry()
self.tool_registry = get_tool_registry()
+ self.usage = UsageTracker(model=self.model)
# ====================================================================== #
# Entry point #
@@ -472,6 +475,7 @@ class AutoPipeline:
tools=tool_schemas or None,
tool_choice="auto" if tool_schemas else None,
stream=True,
+ stream_options={"include_usage": True},
**self._completion_kwargs(ROUTER_MAX_TOKENS),
)
@@ -479,6 +483,12 @@ class AutoPipeline:
tool_calls_accum: dict[int, dict[str, str]] = {}
async for chunk in api_stream:
+ usage_frame = getattr(chunk, "usage", None)
+ if usage_frame:
+ try:
+ self.usage.add_from_response(usage_frame)
+ except Exception:
+ logger.debug("auto router usage recording failed", exc_info=True)
choices = getattr(chunk, "choices", None)
if not choices:
continue
@@ -499,9 +509,7 @@ class AutoPipeline:
delta_tool_calls = getattr(delta, "tool_calls", None) or []
for tc in delta_tool_calls:
idx = getattr(tc, "index", 0) or 0
- bucket = tool_calls_accum.setdefault(
- idx, {"id": "", "name": "", "arguments": ""}
- )
+ bucket = tool_calls_accum.setdefault(idx, {"id": "", "name": "", "arguments": ""})
if getattr(tc, "id", None):
bucket["id"] = tc.id
func = getattr(tc, "function", None)
@@ -608,7 +616,9 @@ class AutoPipeline:
# Args validation: NOT counted against per_delegation_retries; the
# router sees the error and self-corrects.
- config_payload = call.args.get("config") if isinstance(call.args.get("config"), dict) else {}
+ config_payload = (
+ call.args.get("config") if isinstance(call.args.get("config"), dict) else {}
+ )
try:
validated_config = validate_capability_config(cap_name, config_payload)
except ValueError as exc:
@@ -622,8 +632,7 @@ class AutoPipeline:
},
)
payload = (
- f"Invalid args for {cap_name}: {exc}. "
- "Re-issue the call with corrected arguments."
+ f"Invalid args for {cap_name}: {exc}. Re-issue the call with corrected arguments."
)
return {"role": "tool", "tool_call_id": call.id, "name": call.name, "content": payload}
@@ -687,12 +696,14 @@ class AutoPipeline:
stage="synthesizing",
metadata={"call_kind": "llm_final_response"},
)
- await stream.result(
+ await emit_capability_result(
+ stream,
{
"response": fail_text,
"auto_summary": _build_auto_summary(state),
},
source="auto",
+ usage=self.usage,
)
return
@@ -724,23 +735,26 @@ class AutoPipeline:
stage="synthesizing",
metadata={"call_kind": "llm_final_response"},
)
- await stream.result(
+ await emit_capability_result(
+ stream,
{
"response": text,
"auto_summary": _build_auto_summary(state),
},
source="auto",
+ usage=self.usage,
)
def _terminal_failure_text(self, reason: str) -> str:
- if self.language == "zh":
- return (
+ return self._t(
+ en=(
+ "Auto routing failed after exhausting retries. "
+ "Switch to Manual mode and pick a capability, or try the message again."
+ ),
+ zh=(
"Auto 路由失败,已经多次重试仍未恢复。"
"建议切到 Manual 模式手动选择 capability,或重试当前消息。"
- )
- return (
- "Auto routing failed after exhausting retries. "
- "Switch to Manual mode and pick a capability, or try the message again."
+ ),
)
def _fallback_text(self, state: _LoopState) -> str:
@@ -794,7 +808,8 @@ class AutoPipeline:
stage="synthesizing",
metadata={"call_kind": "llm_final_response", "answer_now": True},
)
- await stream.result(
+ await emit_capability_result(
+ stream,
{
"response": text,
"metadata": {"answer_now": True},
@@ -807,6 +822,7 @@ class AutoPipeline:
},
},
source="auto",
+ usage=self.usage,
)
def _answer_now_text(self, *, original: str, partial: str) -> str:
@@ -818,14 +834,15 @@ class AutoPipeline:
),
zh=f"已根据当前进度生成回答:{partial}",
)
- if self.language == "zh":
- return (
+ return self._t(
+ en=(
+ "Auto routing was interrupted before any result was produced. Switch to Manual "
+ "and pick a capability, or resend the message for a fresh attempt."
+ ),
+ zh=(
"已停止 Auto 路由。请切到 Manual 模式直接选择 capability "
"或重新发送消息以获得更完整的结果。"
- )
- return (
- "Auto routing was interrupted before any result was produced. Switch to Manual "
- "and pick a capability, or resend the message for a fresh attempt."
+ ),
)
# ====================================================================== #
@@ -847,10 +864,17 @@ class AutoPipeline:
model=self.model,
messages=messages,
stream=True,
+ stream_options={"include_usage": True},
**self._completion_kwargs(max_tokens),
)
chunks: list[str] = []
async for chunk in api_stream:
+ usage_frame = getattr(chunk, "usage", None)
+ if usage_frame:
+ try:
+ self.usage.add_from_response(usage_frame)
+ except Exception:
+ logger.debug("auto _call_llm_text usage recording failed", exc_info=True)
choices = getattr(chunk, "choices", None)
if not choices:
continue
diff --git a/deeptutor/agents/auto/schemas.py b/deeptutor/agents/auto/schemas.py
index 7f18bb020..f5da813f2 100644
--- a/deeptutor/agents/auto/schemas.py
+++ b/deeptutor/agents/auto/schemas.py
@@ -107,9 +107,11 @@ def build_atomic_tool_schemas(
(minus ``EXCLUDED_ATOMIC_TOOLS``) are. The RAG schema has ``kb_name``
stripped because that's a server-side / trusted UI value, not an LLM arg.
"""
- candidate_names: list[str] = list(enabled_tools) if enabled_tools else [
- name for name in tool_registry.list_tools() if name not in EXCLUDED_ATOMIC_TOOLS
- ]
+ candidate_names: list[str] = (
+ list(enabled_tools)
+ if enabled_tools
+ else [name for name in tool_registry.list_tools() if name not in EXCLUDED_ATOMIC_TOOLS]
+ )
candidate_names = [n for n in candidate_names if n not in EXCLUDED_ATOMIC_TOOLS]
schemas = tool_registry.build_openai_schemas(candidate_names)
for schema in schemas:
@@ -145,7 +147,7 @@ def build_all_tool_schemas(
def extract_capability_name(tool_name: str) -> str | None:
"""Reverse of ``_capability_tool_name``; returns None if not a delegate tool."""
if tool_name.startswith(_DELEGATE_PREFIX):
- return tool_name[len(_DELEGATE_PREFIX):] or None
+ return tool_name[len(_DELEGATE_PREFIX) :] or None
return None
diff --git a/deeptutor/agents/chat/agentic_pipeline.py b/deeptutor/agents/chat/agentic_pipeline.py
index f74e2fcbb..9d75d04ac 100644
--- a/deeptutor/agents/chat/agentic_pipeline.py
+++ b/deeptutor/agents/chat/agentic_pipeline.py
@@ -1,21 +1,28 @@
"""Single-loop agentic chat pipeline.
-The chat capability used to run four sequential LLM calls (thinking → acting
-→ observing → responding) regardless of question complexity. Simple questions
-paid for three unnecessary calls; complex questions couldn't iterate because
-``acting`` was a single-shot tool call.
-
-This module replaces that with one iterative LLM loop. Each iteration:
-
-* Streams an LLM call (with native tool schemas attached when applicable).
-* If the model emitted tool calls, dispatches them, appends the tool
- messages, and continues to the next iteration.
-* Otherwise the iteration's text is the final answer and the loop exits.
-
-The chat-only ``read_source`` tool is auto-included whenever the turn has a
-non-empty ``source_manifest`` (the manifest itself is appended to the
-system prompt by :py:meth:`_build_system_prompt`). The per-turn
-``{source_id: full_text}`` map flows in via ``context.metadata['source_index']``.
+The chat capability runs as one iterative LLM loop. Each iteration is a
+single streaming LLM call followed by, depending on the model's first-line
+protocol label:
+
+* ``FINISH`` → the post-label text IS the final user-facing answer; loop exits.
+* ``TOOL`` → native tool_calls run in parallel; their results feed the next
+ iteration. Tools may pause (``ask_user``) or terminate the turn.
+* ``THINK`` → intermediate reasoning; loop continues so the next call can
+ build on it.
+* ``PAUSE`` → semantically a ``THINK`` whose prose is shown to the user.
+ Same loop behavior as ``THINK`` (intermediate, no tools, loop continues),
+ but the post-label text streams into the chat bubble like ``FINISH`` so
+ the user sees the reasoning when it's worth showing.
+
+This module is the *capability-specific* assembly layer. The generic engine
+lives in :mod:`deeptutor.core.agentic`: label parsing, single-call streaming,
+parallel tool dispatch, and the loop scheduler. Chat plugs in its own:
+
+* tool composition + per-turn KB / source / notebook enums,
+* system-prompt + message assembly (memory, skills, manifests, attachments),
+* server-side tool-kwarg augmentation,
+* context-window guard, force-finalize, answer-now fast path,
+* protocol-violation copy (YAML-loaded, language-aware).
History compression (branch-safe) is handled upstream by
``ContextBuilder.build`` so it does not appear here.
@@ -23,14 +30,35 @@ History compression (branch-safe) is handled upstream by
from __future__ import annotations
-import asyncio
-import json
import logging
+import re
from typing import Any
-import httpx
-from openai import AsyncAzureOpenAI, AsyncOpenAI
-
+from deeptutor.agents._shared.tool_composition import (
+ ToolMountFlags,
+ compose_enabled_tools,
+ default_optional_tools,
+ user_has_memory,
+ user_has_notebooks,
+)
+from deeptutor.capabilities._shared import emit_capability_result
+from deeptutor.core.agentic import (
+ LABEL_PROBE_MAX_CHARS,
+ LABEL_UNKNOWN,
+ DispatchOutcome,
+ LabeledStepResult,
+ LabelProtocol,
+ LLMClientConfig,
+ UsageTracker,
+ build_completion_kwargs,
+ build_openai_client,
+ can_use_native_tool_calling,
+ dispatch_tool_calls,
+ run_agentic_loop,
+ run_labeled_step,
+)
+from deeptutor.core.agentic.labels import find_inline_labels, strip_label_probe_prefix
+from deeptutor.core.agentic.tool_dispatch import MAX_PARALLEL_TOOL_CALLS
from deeptutor.core.context import UnifiedContext
from deeptutor.core.stream_bus import StreamBus
from deeptutor.core.trace import (
@@ -40,13 +68,13 @@ from deeptutor.core.trace import (
new_call_id,
)
from deeptutor.runtime.registry.tool_registry import get_tool_registry
-from deeptutor.services.config import get_chat_params, load_system_settings
+from deeptutor.services.config import get_chat_params, load_system_settings # noqa: F401
from deeptutor.services.llm import (
clean_thinking_tags,
get_llm_config,
- get_token_limit_kwargs,
+ get_token_limit_kwargs, # noqa: F401 (re-exported for tests)
prepare_multimodal_messages,
- supports_tools,
+ supports_tools, # noqa: F401 (re-exported for tests)
)
from deeptutor.services.llm import (
stream as llm_stream,
@@ -54,26 +82,24 @@ from deeptutor.services.llm import (
from deeptutor.services.llm.context_window import resolve_effective_context_window
from deeptutor.services.prompt import get_prompt_manager
from deeptutor.services.prompt.language import append_language_directive
-from deeptutor.tools.builtin import BUILTIN_TOOL_NAMES
-from deeptutor.utils.json_parser import parse_json_response
logger = logging.getLogger(__name__)
-CHAT_EXCLUDED_TOOLS = {"geogebra_analysis"}
-# Optional tools the user can toggle from the composer. ``read_source`` is
-# intentionally excluded — it is auto-enabled by the pipeline when sources
-# are attached and is invisible in the frontend tool list.
-CHAT_OPTIONAL_TOOLS = [
- name
- for name in BUILTIN_TOOL_NAMES
- if name not in CHAT_EXCLUDED_TOOLS and name != "read_source"
-]
-MAX_PARALLEL_TOOL_CALLS = 8
-MAX_TOOL_RESULT_CHARS = 4000
-# Tool-iteration ceiling: small enough to prevent runaway loops, large
-# enough for genuinely multi-step retrieval. The default mirrors common
-# agent-framework defaults and is overridable via capabilities.chat.max_iterations.
-DEFAULT_MAX_ITERATIONS = 8
+
+# ---------------------------------------------------------------------------
+# Module-level configuration
+# ---------------------------------------------------------------------------
+
+CHAT_EXCLUDED_TOOLS: set[str] = set()
+# User-toggleable tools — the composer / settings UI surface. Computed once
+# at import time via the shared tool-composition policy so chat and quiz
+# pipelines can't disagree about which tools the user controls.
+CHAT_OPTIONAL_TOOLS = default_optional_tools(excluded=CHAT_EXCLUDED_TOOLS)
+
+# Tool-iteration ceiling: high enough for multi-step chat loops with
+# ask_user/tool repair, still bounded to prevent runaway loops. Overridable
+# via ``capabilities.chat.max_iterations``.
+DEFAULT_MAX_ITERATIONS = 20
# When messages exceed this fraction of the model's effective context
# window, the in-turn guard replaces the largest stale tool-result with a
# snip marker. Keeps headroom for the next LLM call without aborting.
@@ -82,51 +108,204 @@ TOOL_RESULT_SNIP_MARKER = (
"[earlier tool result snipped to stay within context window — "
"call the same tool again if the content is still needed]"
)
+FINALIZATION_REPAIR_ATTEMPTS = 3
-# Output protocol labels. The system prompt instructs the model to emit
-# exactly one of these as the FIRST line of every reply, wrapped in two
-# backticks each side, e.g. ``FINISH``. The pipeline parses this label
-# upfront and routes the rest of the stream accordingly:
-# FINISH → content events go straight to the answer body (llm_final_response)
-# TOOL → reply will use native tool_calls; prose goes to a reasoning sub-trace
-# THINK → intermediate reasoning only, no tools; loop continues; prose goes to a sub-trace
-# UNKNOWN is the parser's fallback when no valid label is detected within
-# LABEL_PROBE_MAX_CHARS — the pipeline then uses the legacy absorb-into-final
-# mechanism based on whether tool_calls came in.
+# Chat-only label strings (chat's protocol vocabulary). Kept as named
+# constants for legibility in the chat YAML/copy code that references them.
LABEL_FINISH = "FINISH"
LABEL_TOOL = "TOOL"
LABEL_THINK = "THINK"
-LABEL_UNKNOWN = "UNKNOWN"
-LABEL_OPTIONS: tuple[str, ...] = (LABEL_FINISH, LABEL_TOOL, LABEL_THINK)
-LABEL_PROBE_MAX_CHARS = 64
+# ``PAUSE`` is chat-specific: semantically it's ``THINK`` made visible —
+# same intermediate / no-tools / loop-continues behavior, but the
+# post-label text is streamed into the user-facing chat bubble (so it
+# lives in both ``intermediate`` AND ``final``). The LLM picks ``PAUSE``
+# over ``THINK`` only when the reasoning itself is worth showing to the
+# user.
+LABEL_PAUSE = "PAUSE"
+
+# Chat's label protocol, fed into the generic loop primitive.
+_CHAT_PROTOCOL = LabelProtocol(
+ allowed=(LABEL_FINISH, LABEL_TOOL, LABEL_THINK, LABEL_PAUSE),
+ terminal=frozenset({LABEL_FINISH}),
+ intermediate=frozenset({LABEL_THINK, LABEL_PAUSE}),
+ final=frozenset({LABEL_FINISH, LABEL_PAUSE}),
+ tool_label=LABEL_TOOL,
+)
+
+# ---------------------------------------------------------------------------
+# Answer-now lenient label parsing
+# ---------------------------------------------------------------------------
+# The main loop owns the canonical protocol and now tolerates common wrapper
+# variants at the core parser level. Answer-now is still more permissive — it
+# is a terminal, tool-less fast-path, so the safest UI behavior is to strip
+# common spellings rather than render them as a literal label.
-def _classify_label(buffer: str) -> tuple[str, str] | None:
- r"""Inspect a content buffer for a protocol label at the start.
+_ANSWER_NOW_WRAPPED_LABEL_RE = re.compile(
+ r"^`+\s*(FINISH|TOOL|THINK|PAUSE)\s*`+(?P<after>.*)$",
+ re.DOTALL,
+)
+_ANSWER_NOW_UNTERMINATED_WRAPPED_LABEL_RE = re.compile(
+ r"^`+\s*(FINISH|TOOL|THINK|PAUSE)\s*$",
+ re.DOTALL,
+)
+_LABEL_SEPARATOR_CHARS = "\n\r \t::-–—"
+_ANSWER_NOW_ALLOWED_LABELS: tuple[str, ...] = (
+ LABEL_FINISH,
+ LABEL_TOOL,
+ LABEL_THINK,
+ LABEL_PAUSE,
+)
- Returns ``(label, after_text)`` once a valid ``\`\`FINISH\`\```/
- ``\`\`TOOL\`\```/``\`\`THINK\`\``` prefix is detected (after any leading
- whitespace) — caller routes ``after_text`` and all subsequent chunks
- accordingly.
- Returns ``None`` while the buffer is too short or still a partial prefix
- match. Caller keeps buffering and tries again on the next chunk. The
- caller is responsible for falling back to ``LABEL_UNKNOWN`` once
- ``len(buffer) > LABEL_PROBE_MAX_CHARS``.
+# Re-export for tests that still import this name. New code constructs the
+# canonical ``DispatchOutcome`` directly.
+_DispatchOutcome = DispatchOutcome
+
+
+def _could_be_wrapped_answer_now_label(stripped: str) -> bool:
+ """Whether a backtick-prefixed buffer may still become a label."""
+ probe = stripped.lstrip("`").lstrip()
+ if not probe:
+ return True
+ for label in _ANSWER_NOW_ALLOWED_LABELS:
+ if label.startswith(probe):
+ return True
+ if probe.startswith(label):
+ after = probe[len(label) :]
+ if not after.strip("` \t\r\n"):
+ return True
+ return False
+
+
+def _classify_answer_now_label(
+ buffer: str,
+ *,
+ final: bool = False,
+) -> tuple[str, str] | None:
+ """Lenient label stripper used by :meth:`AgenticChatPipeline._run_answer_now`.
+
+ Accepts the canonical double-backtick wrapping as well as common
+ looser variants (single-backtick wrappers, unwrapped labels followed
+ by a separator). Returns ``None`` when the buffer still looks like a
+ partial label match — caller keeps buffering.
"""
- stripped = buffer.lstrip()
- for label in LABEL_OPTIONS:
- prefix = f"``{label}``"
- if stripped.startswith(prefix):
- after = stripped[len(prefix):]
- # Eat the single separating newline / spaces after the label so
- # the answer body / reasoning text doesn't start with stray
- # blank lines.
- return label, after.lstrip("\n\r ")
- # Could still match — return None to keep buffering.
+ from deeptutor.core.agentic.labels import classify_label
+
+ parsed = classify_label(buffer, allowed_labels=_ANSWER_NOW_ALLOWED_LABELS)
+ if parsed is not None:
+ return parsed
+
+ stripped = strip_label_probe_prefix(buffer)
+ wrapped = _ANSWER_NOW_WRAPPED_LABEL_RE.match(stripped)
+ if wrapped:
+ return wrapped.group(1), wrapped.group("after").lstrip(_LABEL_SEPARATOR_CHARS)
+ unterminated = _ANSWER_NOW_UNTERMINATED_WRAPPED_LABEL_RE.match(stripped)
+ if final and unterminated:
+ return unterminated.group(1), ""
+
+ for label in _ANSWER_NOW_ALLOWED_LABELS:
+ for prefix in (f"`{label}`", label):
+ if stripped.startswith(prefix):
+ after = stripped[len(prefix) :]
+ if after:
+ if after[0] in _LABEL_SEPARATOR_CHARS:
+ return label, after.lstrip(_LABEL_SEPARATOR_CHARS)
+ continue
+ if final:
+ return label, ""
+ if prefix.startswith(stripped):
+ return None
+ if stripped.startswith("`") and _could_be_wrapped_answer_now_label(stripped):
+ return None
return None
+def _normalise_user_reply(
+ raw: Any,
+) -> tuple[str, list[dict[str, str]] | None]:
+ """Normalise a waiter() reply into ``(text, answers)``.
+
+ Accepts either a plain string (legacy / direct injection in tests)
+ or a dict ``{"text": str, "answers": list | None}`` (runtime path
+ that supports the v2 multi-question schema).
+ """
+ if isinstance(raw, str):
+ return raw, None
+ if isinstance(raw, dict):
+ text = str(raw.get("text") or "")
+ answers_raw = raw.get("answers")
+ if isinstance(answers_raw, list) and answers_raw:
+ answers: list[dict[str, str]] = []
+ for entry in answers_raw:
+ if not isinstance(entry, dict):
+ continue
+ qid = str(entry.get("questionId") or entry.get("id") or "").strip()
+ if not qid:
+ continue
+ answers.append({"questionId": qid, "text": str(entry.get("text") or "")})
+ return text, answers or None
+ return text, None
+ return str(raw or ""), None
+
+
+def _format_user_reply_body(
+ text: str,
+ answers: list[dict[str, str]] | None,
+ ask_user_payload: dict[str, Any],
+) -> str:
+ """Render the ``User answered:`` body the model sees on resume.
+
+ Multi-question replies are rendered as one ``- <prompt>\n → <answer>``
+ line per question so the model has the original question text in
+ context. Skipped or empty answers come through as ``(skipped)``.
+ """
+ if answers:
+ prompts_by_id: dict[str, str] = {}
+ for q in ask_user_payload.get("questions") or []:
+ if isinstance(q, dict):
+ qid = str(q.get("id") or "")
+ prompts_by_id[qid] = str(q.get("prompt") or qid)
+ lines = ["User answered:"]
+ for entry in answers:
+ qid = entry.get("questionId", "")
+ prompt = prompts_by_id.get(qid) or qid or "(question)"
+ value = (entry.get("text") or "").strip() or "(skipped)"
+ lines.append(f"- {prompt}\n → {value}")
+ return "\n".join(lines)
+ flat = (text or "").strip() or "(empty reply)"
+ return f"User answered: {flat}"
+
+
+def _flatten_ask_user_summary(ask_user_payload: dict[str, Any]) -> str:
+ """One-line summary for fallback terminator emit when no waiter wired."""
+ questions = ask_user_payload.get("questions") or []
+ if isinstance(questions, list) and questions:
+ prompts = [str(q.get("prompt") or "") for q in questions if isinstance(q, dict)]
+ prompts = [p for p in prompts if p]
+ if prompts:
+ return " | ".join(prompts)
+ # Legacy single-question payload shape (pre-v2).
+ return str(ask_user_payload.get("question") or "")
+
+
+def _read_int(cfg: Any, *, key: str, default: int) -> int:
+ """Pull an integer from a nested YAML dict, falling back to ``default``."""
+ if isinstance(cfg, dict):
+ value = cfg.get(key, default)
+ else:
+ value = default
+ try:
+ return int(value)
+ except (TypeError, ValueError):
+ return default
+
+
+# ---------------------------------------------------------------------------
+# Pipeline
+# ---------------------------------------------------------------------------
+
+
class AgenticChatPipeline:
"""Run chat as a single iterative LLM loop with native tool calling."""
@@ -140,7 +319,7 @@ class AgenticChatPipeline:
self.api_version = getattr(self.llm_config, "api_version", None)
self.extra_headers = getattr(self.llm_config, "extra_headers", None) or {}
self.registry = get_tool_registry()
- self._usage = {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0, "calls": 0}
+ self._usage = UsageTracker(model=self.model)
try:
chat_cfg = get_chat_params()
@@ -177,6 +356,15 @@ class AgenticChatPipeline:
logger.warning("Failed to load agentic_chat prompts: %s", exc)
self._prompts = {}
+ self._client_config = LLMClientConfig(
+ binding=self.binding,
+ model=self.model,
+ api_key=self.api_key,
+ base_url=self.base_url,
+ api_version=self.api_version,
+ extra_headers=self.extra_headers or None,
+ )
+
# ------------------------------------------------------------------
# Public entry point
# ------------------------------------------------------------------
@@ -189,9 +377,7 @@ class AgenticChatPipeline:
enabled_tools = self._compose_enabled_tools(context)
use_native_tools = bool(enabled_tools) and self._can_use_native_tool_calling()
tool_schemas = (
- self._build_llm_tool_schemas(enabled_tools, context)
- if use_native_tools
- else None
+ self._build_llm_tool_schemas(enabled_tools, context) if use_native_tools else None
)
system_prompt = self._build_system_prompt(enabled_tools, context)
@@ -218,366 +404,449 @@ class AgenticChatPipeline:
metadata={"trace_kind": "warning"},
)
- aggregated_sources: list[dict[str, Any]] = []
- final_text = ""
- max_iter = max(1, self._max_iterations)
- completed = False
- iteration = 0
+ # Build the per-turn OpenAI client via ``_build_openai_client`` so
+ # tests can monkey-patch that method post-instantiation to inject a
+ # scripted client.
+ client = self._build_openai_client()
+ host = _ChatLoopHost(
+ pipeline=self,
+ context=context,
+ stream=stream,
+ client=client,
+ )
# Outer ``stage("responding")`` only drives the frontend's
# ``currentStage`` indicator ("DeepTutor responding…"). It carries no
# call_id so it does NOT spawn its own sub-trace; each LLM iteration
# and each tool call below allocate their own call_id and surface as
# individual sub-traces in CallTracePanel.
async with stream.stage("responding", source="chat"):
- for iteration in range(max_iter):
- await self._guard_context_window(messages, stream)
-
- # Per-iter sub-trace identity. Created up front but ONLY
- # opened by ``_stream_one_iteration`` when the resolved
- # label is THINK / TOOL / UNKNOWN. A FINISH iter never
- # opens it, so no empty sub-trace appears in the trace box.
- iter_call_id = new_call_id(f"chat-iter-{iteration}")
- iter_meta = build_trace_metadata(
- call_id=iter_call_id,
- phase="responding",
- label=self._t("labels.reasoning", default="Reasoning"),
- call_kind="llm_reasoning",
- trace_id=iter_call_id,
- trace_role="thought",
- trace_group="stage",
- )
- # Fresh final-response trace id per iter — FINISH path uses
- # it to scope the body content events; intermediate iters
- # never touch it.
- final_call_id = new_call_id("chat-final-response")
- final_meta = build_trace_metadata(
- call_id=final_call_id,
- phase="responding",
- label=self._t("labels.final_response", default="Final response"),
- call_kind="llm_final_response",
- trace_id=final_call_id,
- trace_role="response",
- trace_group="stage",
- )
-
- label, iteration_text, tool_calls = await self._stream_one_iteration(
- messages=messages,
- tool_schemas=tool_schemas,
- stream=stream,
- iter_meta=iter_meta,
- final_meta=final_meta,
- )
-
- # Reconcile contradictions between the declared label and
- # actual stream signals, then dispatch on the resolved
- # action.
- if label == LABEL_TOOL and not tool_calls:
- # Model said TOOL but never emitted calls — fall back
- # to a THINK iteration (the prose was reasoning).
- label = LABEL_THINK
- if label == LABEL_FINISH and tool_calls:
- # Model said FINISH but still emitted tool_calls. Trust
- # the tool intent — those calls happened mid-stream and
- # the body already received the prose chunks before the
- # calls appeared. Promote to TOOL so we dispatch.
- label = LABEL_TOOL
-
- if label == LABEL_FINISH:
- # Content already streamed live to the answer body via
- # the ``stream.content(call_kind=llm_final_response)``
- # path inside ``_stream_one_iteration``. Nothing more
- # to do — just record and exit.
- final_text += iteration_text
- completed = True
- break
-
- if label == LABEL_TOOL:
- messages.append(
- self._assistant_message_with_tool_calls(
- content=iteration_text,
- tool_calls=tool_calls,
- )
- )
- iter_sources, tool_messages = await self._dispatch_tool_calls(
- tool_calls=tool_calls,
- context=context,
- stream=stream,
- iteration_index=iteration,
- )
- aggregated_sources.extend(iter_sources)
- messages.extend(tool_messages)
- continue
-
- if label == LABEL_THINK:
- # Intermediate reasoning — no tools, no answer yet.
- # Persist the prose into the conversation so the next
- # iteration's LLM call can build on it.
- if iteration_text:
- messages.append(
- {"role": "assistant", "content": iteration_text}
- )
- continue
-
- # LABEL_UNKNOWN — protocol violation fallback. Behave like
- # the legacy "absorb-into-final" logic: if tool_calls came,
- # treat as TOOL; otherwise treat as FINISH by emitting one
- # synthetic content event and marking the existing sub-trace
- # as absorbed so it doesn't visually duplicate the answer.
- if tool_calls:
- messages.append(
- self._assistant_message_with_tool_calls(
- content=iteration_text,
- tool_calls=tool_calls,
- )
- )
- iter_sources, tool_messages = await self._dispatch_tool_calls(
- tool_calls=tool_calls,
- context=context,
- stream=stream,
- iteration_index=iteration,
- )
- aggregated_sources.extend(iter_sources)
- messages.extend(tool_messages)
- continue
-
- # No tool_calls + no valid label → treat as FINISH-fallback.
- # The sub-trace was already opened during streaming; mark it
- # absorbed so the frontend hides it, then emit the answer
- # body content.
- await stream.progress(
- "",
- source="chat",
- stage="responding",
- metadata=merge_trace_metadata(
- iter_meta,
- {
- "trace_kind": "call_status",
- "call_state": "complete",
- "absorbed_into_final": True,
- },
- ),
- )
- await stream.content(
- iteration_text,
- source="chat",
- stage="responding",
- metadata=merge_trace_metadata(
- final_meta, {"trace_kind": "llm_output"}
- ),
- )
- final_text += iteration_text
- completed = True
- break
- else:
- # Loop exhausted without a clean final response. Emit a
- # one-off warning event (no call_id — not a sub-trace).
- await stream.progress(
- self._t("notices.max_iterations_reached"),
- source="chat",
- stage="responding",
- metadata={"trace_kind": "warning"},
- )
+ outcome = await run_agentic_loop(
+ initial_messages=messages,
+ protocol=_CHAT_PROTOCOL,
+ client=client,
+ model=self.model,
+ completion_kwargs=self._completion_kwargs(max_tokens=self._responding_max_tokens),
+ binding=self.binding,
+ tool_schemas=tool_schemas,
+ stream=stream,
+ source="chat",
+ stage="responding",
+ max_iterations=max(1, self._max_iterations),
+ host=host,
+ usage=self._usage,
+ # Reasoning models that natively emit ``<think>...</think>``
+ # without parroting back ``\`\`THINK\`\``` are gracefully
+ # accepted as a THINK iteration rather than treated as a
+ # protocol violation (which would burn budget on repair
+ # retries that the model can't actually satisfy).
+ implicit_think_label=LABEL_THINK,
+ )
- if aggregated_sources:
+ if outcome.sources:
await stream.sources(
- aggregated_sources,
+ outcome.sources,
source="chat",
stage="responding",
metadata={"trace_kind": "sources"},
)
result_payload: dict[str, Any] = {
- "response": final_text,
- "iterations": iteration + 1,
- "completed": completed,
+ "response": outcome.final_text,
+ "iterations": outcome.iterations,
+ "completed": outcome.completed,
}
- cs = self._get_cost_summary()
- if cs:
- result_payload["metadata"] = {"cost_summary": cs}
- await stream.result(result_payload, source="chat")
+ await emit_capability_result(stream, result_payload, source="chat", usage=self._usage)
+
+ # ------------------------------------------------------------------
+ # Iteration trace metadata
+ # ------------------------------------------------------------------
+ def _build_iteration_trace_metadata(
+ self, iteration: int
+ ) -> tuple[dict[str, Any], dict[str, Any]]:
+ """Allocate trace metadata for one model iteration.
+
+ ``iter_meta`` scopes the reasoning sub-trace that THINK/TOOL/UNKNOWN
+ paths open; FINISH never opens it so the row stays empty in those
+ cases. ``final_meta`` is the per-iter id for body content events on
+ the FINISH path.
+ """
+ iter_call_id = new_call_id(f"chat-iter-{iteration}")
+ iter_meta = build_trace_metadata(
+ call_id=iter_call_id,
+ phase="responding",
+ label=self._t("labels.reasoning", default="Reasoning"),
+ call_kind="llm_reasoning",
+ trace_id=iter_call_id,
+ trace_role="thought",
+ trace_group="stage",
+ )
+ final_call_id = new_call_id("chat-final-response")
+ final_meta = build_trace_metadata(
+ call_id=final_call_id,
+ phase="responding",
+ label=self._t("labels.final_response", default="Final response"),
+ call_kind="llm_final_response",
+ trace_id=final_call_id,
+ trace_role="response",
+ trace_group="stage",
+ )
+ return iter_meta, final_meta
+
+ # ------------------------------------------------------------------
+ # Protocol copy (delegated to YAML; loop host calls these)
+ # ------------------------------------------------------------------
+ def _protocol_retry_notice(self) -> str:
+ return self._t(
+ "notices.protocol_retry",
+ default="The model violated the action-label protocol; retrying this iteration.",
+ )
+
+ def _protocol_repair_message(self, violation: str) -> str:
+ if self.language == "zh":
+ reason = {
+ "missing_label": "你上一轮回复没有以必需的协议标签开头",
+ "multiple_labels": "你上一轮回复在同一次输出里出现了多个协议标签",
+ "tool_without_calls": "你上一轮选择了 ``TOOL``,但没有发起真实 tool_calls",
+ "think_with_tools": "你上一轮选择了 ``THINK``,但同时发起了工具调用",
+ "finish_with_tools": "你上一轮选择了 ``FINISH``,但同时发起了工具调用",
+ "pause_with_tools": "你上一轮选择了 ``PAUSE``,但同时发起了工具调用",
+ }.get(violation, "你上一轮回复不符合协议")
+ default = (
+ f"协议修正:{reason},所以本轮还不能结束。下一次回复必须"
+ "只选择一个动作标签,并且只在第一行写一次:``FINISH``、"
+ "``TOOL``、``THINK`` 或 ``PAUSE``。标签正文里不要再出现"
+ "第二个协议标签。如果内容本来就是最终答案,用 ``FINISH``;"
+ "如果需要工具,用 ``TOOL`` 并在同一次回复里发起真实 "
+ "tool_calls;如果只是中间思考、用户不需要看到,用 ``THINK``"
+ " 且不要调用工具;如果这段思考让用户看到比藏着更有价值,"
+ "用 ``PAUSE``(等于可见的 ``THINK``)且不要调用工具。"
+ )
+ else:
+ reason = {
+ "missing_label": "your previous reply did not begin with a protocol label",
+ "multiple_labels": "your previous reply contained multiple protocol labels",
+ "tool_without_calls": "you chose ``TOOL`` but emitted no real tool_calls",
+ "think_with_tools": "you chose ``THINK`` while also emitting tool_calls",
+ "finish_with_tools": "you chose ``FINISH`` while also emitting tool_calls",
+ "pause_with_tools": "you chose ``PAUSE`` while also emitting tool_calls",
+ }.get(violation, "your previous reply violated the protocol")
+ default = (
+ f"Protocol correction: {reason}, so the turn is not complete. "
+ "Your next reply must choose exactly one action label, written "
+ "once on the first line only: ``FINISH``, ``TOOL``, ``THINK``, "
+ "or ``PAUSE``. Do not include a second protocol label anywhere "
+ "in the body. If the draft was the final answer, use "
+ "``FINISH``. If tools are needed, use ``TOOL`` and emit real "
+ "tool_calls in that same reply. If this is private intermediate "
+ "reasoning the user doesn't need to see, use ``THINK`` and "
+ "do not call tools. If your reasoning is worth showing to the "
+ "user, use ``PAUSE`` (same as ``THINK`` plus visibility) and "
+ "do not call tools."
+ )
+ return self._t(f"protocol.{violation}", default=default)
+
+ def _force_finish_message(self) -> str:
+ if self.language == "zh":
+ default = (
+ "迭代预算已用完。现在必须给出面向用户的最终答复:第一行必须是 "
+ "``FINISH``,不要再调用工具,也不要再用 ``THINK`` 或 ``PAUSE``。"
+ "如果信息仍不完整,请简短说明不确定性,但仍给出当前最有用的答案。"
+ )
+ else:
+ default = (
+ "The iteration budget is exhausted. You must now produce the "
+ "user-facing final answer: the first line must be ``FINISH``. "
+ "Do not call tools and do not use ``THINK`` or ``PAUSE``. If "
+ "information is still incomplete, state the uncertainty briefly "
+ "while giving the most useful answer possible."
+ )
+ return self._t("protocol.force_finish", default=default)
+
+ def _force_finish_repair_message(self, violation: str) -> str:
+ if self.language == "zh":
+ reason = "没有使用 ``FINISH``"
+ if violation == "multiple_labels":
+ reason = "在最终化回复里混用了多个标签"
+ elif violation == "tool_without_calls":
+ reason = "仍然选择了 ``TOOL``"
+ elif violation == "think_with_tools":
+ reason = "用 ``THINK`` 的同时调用了工具"
+ elif violation == "finish_with_tools":
+ reason = "用 ``FINISH`` 的同时调用了工具"
+ elif violation == "pause_with_tools":
+ reason = "用 ``PAUSE`` 的同时调用了工具"
+ default = (
+ f"最终化协议修正:上一轮{reason}。现在只能输出一个最终答案:"
+ "第一行写 ``FINISH``,后面直接给用户答案。不要写 ``THINK``、"
+ "``PAUSE``,不要写 ``TOOL``,不要调用任何工具,也不要在正文里"
+ "再次出现协议标签。"
+ )
+ else:
+ reason = "did not use ``FINISH``"
+ if violation == "multiple_labels":
+ reason = "mixed multiple labels in the finalization reply"
+ elif violation == "tool_without_calls":
+ reason = "still chose ``TOOL``"
+ elif violation == "think_with_tools":
+ reason = "used ``THINK`` while calling tools"
+ elif violation == "finish_with_tools":
+ reason = "used ``FINISH`` while calling tools"
+ elif violation == "pause_with_tools":
+ reason = "used ``PAUSE`` while calling tools"
+ default = (
+ f"Finalization protocol correction: the previous reply {reason}. "
+ "Now output only a final answer: first line ``FINISH``, then the "
+ "user-facing answer. Do not write ``THINK``, ``PAUSE``, or "
+ "``TOOL``, do not call tools, and do not include another "
+ "protocol label in the body."
+ )
+ return self._t("protocol.force_finish_repair", default=default)
+
+ def _protocol_fallback_final_text(self) -> str:
+ if self.language == "zh":
+ default = (
+ "我已经达到本轮迭代上限,但模型没有按 ``FINISH`` 协议产出合格的"
+ "最终回答。请重试一次,或把问题范围收窄;我会从已有上下文继续。"
+ )
+ else:
+ default = (
+ "I reached the iteration limit, but the model did not produce "
+ "a valid ``FINISH`` response. Please retry or narrow the request; "
+ "I can continue from the existing context."
+ )
+ return self._t("protocol.fallback_final", default=default)
# ------------------------------------------------------------------
- # Iteration core: one streaming LLM call with tools
+ # Forced finalization (host hook for max-iter exhaustion)
# ------------------------------------------------------------------
- async def _stream_one_iteration(
+ async def _run_forced_finish(
self,
*,
+ client: Any,
messages: list[dict[str, Any]],
- tool_schemas: list[dict[str, Any]] | None,
stream: StreamBus,
- iter_meta: dict[str, Any],
- final_meta: dict[str, Any],
- ) -> tuple[str, str, list[dict[str, Any]]]:
- r"""Run one LLM streaming call. Parses the protocol label
- (``\`\`FINISH\`\``` / ``\`\`TOOL\`\``` / ``\`\`THINK\`\```) from the FIRST chunks of
- the content stream, then routes subsequent chunks accordingly:
-
- * ``FINISH``: post-label chunks stream **directly to the answer body**
- via ``stream.content(call_kind="llm_final_response")``. No iteration
- sub-trace is ever opened — there's nothing intermediate to show.
- * ``TOOL`` / ``THINK``: post-label chunks stream as ``stream.thinking``
- events scoped to ``iter_meta.call_id`` so they fill a single
- "Reasoning" sub-trace in CallTracePanel.
-
- ``UNKNOWN`` is returned if the buffer exceeds ``LABEL_PROBE_MAX_CHARS``
- without a valid label — the caller falls back to the legacy
- absorb-into-final mechanism.
-
- Returns ``(label, accumulated_post_label_text, parsed_tool_calls)``.
- For ``FINISH`` the text reflects only what was streamed to the body;
- for ``TOOL``/``THINK`` it's the reasoning prose that the next
- iteration will see as the assistant's previous message.
- """
- client = self._build_openai_client()
- kwargs: dict[str, Any] = {
- "model": self.model,
- "messages": messages,
- "stream": True,
- **self._completion_kwargs(max_tokens=self._responding_max_tokens),
- }
- if tool_schemas:
- kwargs["tools"] = tool_schemas
- kwargs["tool_choice"] = "auto"
-
- label: str | None = None
- label_buf = ""
- sub_trace_opened = False
- content_acc: list[str] = []
- tc_acc: dict[int, dict[str, Any]] = {}
- usage_seen: Any = None
-
- async def _open_sub_trace() -> None:
- nonlocal sub_trace_opened
- if sub_trace_opened:
- return
- await stream.progress(
- iter_meta["label"],
+ start_iteration: int,
+ ) -> tuple[str, bool, int]:
+ """Ask the model for one tool-less ``FINISH`` reply, retrying on
+ protocol violations. Returns ``(final_text, completed, calls)``."""
+ calls = 0
+ messages.append({"role": "user", "content": self._force_finish_message()})
+ await stream.progress(
+ self._t("notices.max_iterations_reached"),
+ source="chat",
+ stage="responding",
+ metadata={"trace_kind": "warning"},
+ )
+ for attempt in range(FINALIZATION_REPAIR_ATTEMPTS):
+ await self._guard_context_window(messages, stream)
+ iter_meta, final_meta = self._build_iteration_trace_metadata(start_iteration + attempt)
+ step = await run_labeled_step(
+ client=client,
+ model=self.model,
+ messages=messages,
+ completion_kwargs=self._completion_kwargs(max_tokens=self._responding_max_tokens),
+ tool_schemas=None,
+ allowed_labels=(LABEL_FINISH,),
+ final_labels=frozenset({LABEL_FINISH}),
+ tool_label=None,
+ stream=stream,
source="chat",
stage="responding",
- metadata=merge_trace_metadata(
- iter_meta,
- {"trace_kind": "call_status", "call_state": "running"},
- ),
+ iter_meta=iter_meta,
+ binding=self.binding,
+ usage=self._usage,
)
- sub_trace_opened = True
-
- async def _emit_text(text: str) -> None:
- """Route a post-label text fragment to body or sub-trace."""
- if not text:
- return
- content_acc.append(text)
- if label == LABEL_FINISH:
- await stream.content(
- text,
- source="chat",
- stage="responding",
- metadata=merge_trace_metadata(final_meta, {"trace_kind": "llm_chunk"}),
- )
- else:
- # THINK / TOOL / UNKNOWN — all surface as reasoning sub-trace.
- await _open_sub_trace()
- await stream.thinking(
- text,
- source="chat",
- stage="responding",
- metadata=merge_trace_metadata(iter_meta, {"trace_kind": "llm_chunk"}),
- )
+ calls += 1
- response_stream = await client.chat.completions.create(**kwargs)
- try:
- async for chunk in response_stream:
- if getattr(chunk, "usage", None):
- usage_seen = chunk.usage
- if not chunk.choices:
- continue
- delta = chunk.choices[0].delta
- if delta is None:
- continue
+ violation = _classify_forced_finish_violation(step)
+ if step.label == LABEL_FINISH and not violation:
+ await self._emit_final_text(stream, step.text, final_meta)
+ return step.text, True, calls
- if delta.content:
- text = delta.content
- if label is None:
- label_buf += text
- parsed = _classify_label(label_buf)
- if parsed is not None:
- label, after_label = parsed
- label_buf = ""
- await _emit_text(after_label)
- elif len(label_buf) > LABEL_PROBE_MAX_CHARS:
- # Model didn't follow the protocol. Fall back —
- # stream what we've buffered as reasoning and
- # let the caller decide based on tool_calls.
- label = LABEL_UNKNOWN
- flushed = label_buf
- label_buf = ""
- await _emit_text(flushed)
- else:
- await _emit_text(text)
-
- for tc_delta in getattr(delta, "tool_calls", None) or []:
- # Tool-call delta is authoritative for the TOOL path.
- # If we're still buffering a label, force-resolve as TOOL
- # so the buffered prose flushes into the reasoning sub-
- # trace and subsequent prose continues there.
- if label is None:
- label = LABEL_TOOL
- flushed = label_buf
- label_buf = ""
- if flushed:
- await _emit_text(flushed)
- idx = getattr(tc_delta, "index", 0)
- entry = tc_acc.setdefault(
- idx, {"id": "", "name": "", "arguments": ""}
- )
- if getattr(tc_delta, "id", None):
- entry["id"] = tc_delta.id
- fn = getattr(tc_delta, "function", None)
- if fn is not None:
- if getattr(fn, "name", None):
- entry["name"] = entry["name"] + fn.name
- if getattr(fn, "arguments", None):
- entry["arguments"] = entry["arguments"] + fn.arguments
- finally:
- close = getattr(response_stream, "close", None)
- if callable(close):
- with self._suppress_close_errors():
- await close()
-
- if usage_seen is not None:
- self._accumulate_usage(_UsageShim(usage_seen))
-
- # Stream ended while still buffering a label (very short reply that
- # never reached LABEL_PROBE_MAX_CHARS and never matched). Flush as
- # UNKNOWN — the caller will decide based on tool_calls.
- if label is None:
- label = LABEL_UNKNOWN
- if label_buf:
- await _emit_text(label_buf)
- label_buf = ""
-
- # Close the sub-trace if it was opened (THINK / TOOL / UNKNOWN
- # paths). FINISH never opened one — its content went straight to
- # the body.
- if sub_trace_opened:
+ final_violation = violation or "final_missing_finish"
await stream.progress(
- "",
+ self._t(
+ "notices.final_protocol_failed",
+ default=(
+ "The model still did not produce a valid FINISH reply "
+ "after the finalization prompt."
+ ),
+ ),
source="chat",
stage="responding",
- metadata=merge_trace_metadata(
- iter_meta,
- {"trace_kind": "call_status", "call_state": "complete"},
- ),
+ metadata={
+ "trace_kind": "warning",
+ "protocol_violation": final_violation,
+ "finalization_attempt": attempt + 1,
+ },
+ )
+ self._append_assistant_context(messages, step.text)
+ messages.append(
+ {
+ "role": "user",
+ "content": self._force_finish_repair_message(final_violation),
+ }
)
- text = clean_thinking_tags("".join(content_acc), self.binding, self.model)
- ordered_tool_calls = [tc_acc[k] for k in sorted(tc_acc.keys())]
- # Filter out empty / malformed deltas that some providers emit.
- ordered_tool_calls = [tc for tc in ordered_tool_calls if tc.get("name")]
- return label, text, ordered_tool_calls
+ fallback = self._protocol_fallback_final_text()
+ await self._emit_protocol_fallback_final_response(stream, fallback)
+ return fallback, False, calls
+
+ @staticmethod
+ def _append_assistant_context(
+ messages: list[dict[str, Any]],
+ text: str,
+ ) -> None:
+ clipped = str(text or "").strip()
+ if not clipped:
+ return
+ if len(clipped) > 500:
+ clipped = clipped[:500].rstrip() + "\n...[truncated]"
+ messages.append({"role": "assistant", "content": clipped})
+
+ # ------------------------------------------------------------------
+ # Emit helpers (host hooks)
+ # ------------------------------------------------------------------
+ async def _emit_final_text(
+ self,
+ stream: StreamBus,
+ text: str,
+ final_meta: dict[str, Any],
+ ) -> None:
+ if not text:
+ return
+ await stream.content(
+ text,
+ source="chat",
+ stage="responding",
+ metadata=merge_trace_metadata(final_meta, {"trace_kind": "llm_output"}),
+ )
+
+ async def _emit_terminator_final_response(
+ self,
+ stream: StreamBus,
+ payload: dict[str, Any] | None,
+ ) -> None:
+ """Emit a ``content(call_kind=llm_final_response)`` event with the
+ terminating tool's content + its UI metadata.
+
+ Generic enough to support any future ``terminate_turn`` tool: the
+ tool's own ``ToolResult.metadata`` rides along on the
+ ``tool_metadata`` slot so the frontend can dispatch on it (e.g.
+ render option chips for ``ask_user`` via ``tool_metadata.ask_user``).
+ """
+ if not payload:
+ return
+ content = str(payload.get("content") or "").strip()
+ tool_metadata = payload.get("metadata") or {}
+ if not content:
+ return
+ final_call_id = new_call_id("chat-final-response")
+ final_meta = build_trace_metadata(
+ call_id=final_call_id,
+ phase="responding",
+ label=self._t("labels.final_response", default="Final response"),
+ call_kind="llm_final_response",
+ trace_id=final_call_id,
+ trace_role="response",
+ trace_group="stage",
+ terminator_tool=str(payload.get("tool_name") or ""),
+ )
+ merged_metadata: dict[str, Any] = {"trace_kind": "llm_output"}
+ if isinstance(tool_metadata, dict) and tool_metadata:
+ merged_metadata["tool_metadata"] = dict(tool_metadata)
+ await stream.content(
+ content,
+ source="chat",
+ stage="responding",
+ metadata=merge_trace_metadata(final_meta, merged_metadata),
+ )
+
+ async def _emit_protocol_fallback_final_response(
+ self,
+ stream: StreamBus,
+ content: str,
+ ) -> None:
+ final_meta = build_trace_metadata(
+ call_id=new_call_id("chat-final-response"),
+ phase="responding",
+ label=self._t("labels.final_response", default="Final response"),
+ call_kind="llm_final_response",
+ trace_id="chat-final-response",
+ trace_role="response",
+ trace_group="stage",
+ protocol_fallback=True,
+ )
+ await stream.content(
+ content,
+ source="chat",
+ stage="responding",
+ metadata=merge_trace_metadata(final_meta, {"trace_kind": "llm_output"}),
+ )
+
+ @staticmethod
+ def _assistant_message_with_tool_calls(
+ content: str,
+ tool_calls: list[dict[str, Any]],
+ ) -> dict[str, Any]:
+ return {
+ "role": "assistant",
+ "content": content or None,
+ "tool_calls": [
+ {
+ "id": tc["id"],
+ "type": "function",
+ "function": {
+ "name": tc["name"],
+ "arguments": tc.get("arguments") or "{}",
+ },
+ }
+ for tc in tool_calls
+ ],
+ }
# ------------------------------------------------------------------
- # Tool dispatch
+ # Tool dispatch (thin wrappers around the primitives — preserved for tests)
# ------------------------------------------------------------------
+ async def _execute_tool_call(
+ self,
+ tool_name: str,
+ tool_args: dict[str, Any],
+ *,
+ stream: StreamBus | None = None,
+ retrieve_meta: dict[str, Any] | None = None,
+ ) -> dict[str, Any]:
+ """Run a single tool with chat-flavored retrieve-progress events.
+
+ Direct callers (notably test code) use this to drive one tool
+ without going through the parallel dispatcher.
+ """
+ from deeptutor.core.agentic import execute_tool_call
+
+ if stream is None:
+ # No stream means no retrieve trace either; fall through with a
+ # dummy bus so the primitive's stream calls become no-ops.
+ stream = StreamBus()
+ return await execute_tool_call(
+ registry=self.registry,
+ tool_name=tool_name,
+ tool_args=tool_args,
+ stream=stream,
+ source="chat",
+ stage="acting",
+ retrieve_meta=retrieve_meta,
+ empty_tool_result_message=self._t("notices.empty_tool_result"),
+ start_retrieval_message=self._t(
+ "notices.start_retrieval", default="Starting retrieval"
+ ),
+ retrieve_label=self._t("labels.retrieve", default="Retrieve"),
+ unknown_error_message_factory=lambda tn: self._t(
+ "notices.tool_unknown_error",
+ tool=tn,
+ default=f"An unknown error occurred while executing {tn}.",
+ ),
+ )
+
async def _dispatch_tool_calls(
self,
*,
@@ -585,129 +854,131 @@ class AgenticChatPipeline:
context: UnifiedContext,
stream: StreamBus,
iteration_index: int,
- ) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
- """Execute one iteration's tool calls in parallel.
-
- Each individual tool call is given its own trace ``call_id`` so
- ``CallTracePanel`` renders each as a separate sub-trace row
- (e.g. "Tool call · code_execution" + "Retrieve" + …) — matching the
- user's "one LLM call or one tool call = one sub-trace" expectation.
-
- Returns ``(aggregated_sources, tool_role_messages)``. Tool messages
- are formatted for the OpenAI ``role=tool`` protocol so the next
- iteration's LLM call sees them.
- """
+ ) -> DispatchOutcome:
+ """Dispatch this iteration's tool calls under chat-specific labels,
+ kwarg-augmenter, and retrieve-trace metadata."""
+ too_many = None
if len(tool_calls) > MAX_PARALLEL_TOOL_CALLS:
- # Capped truncation notice carries no call_id — it's a one-off
- # warning, not a sub-trace.
- await stream.progress(
- self._t(
- "notices.too_many_tool_calls",
- requested=len(tool_calls),
- limit=MAX_PARALLEL_TOOL_CALLS,
- ),
- source="chat",
- stage="acting",
- metadata={"trace_kind": "warning"},
+ too_many = self._t(
+ "notices.too_many_tool_calls",
+ requested=len(tool_calls),
+ limit=MAX_PARALLEL_TOOL_CALLS,
)
- tool_calls = tool_calls[:MAX_PARALLEL_TOOL_CALLS]
-
- prepared: list[tuple[str, str, dict[str, Any], dict[str, Any]]] = []
- for tc in tool_calls:
- tool_name = str(tc.get("name") or "").strip()
- tool_call_id = str(tc.get("id") or "").strip()
- tool_args = parse_json_response(
- tc.get("arguments") or "{}",
- logger_instance=logger,
- fallback={},
- )
- if not isinstance(tool_args, dict):
- tool_args = {}
- execution_args = self._augment_tool_kwargs(tool_name, tool_args, context)
- prepared.append((tool_call_id, tool_name, dict(execution_args), execution_args))
-
- # Allocate a fresh trace call_id per tool call so each shows as its
- # own sub-trace in CallTracePanel. The OpenAI ``tool_call_id`` (used
- # for the role=tool message protocol) is separate from this trace id.
- per_tool_trace_meta: list[dict[str, Any]] = []
- for tool_index, (tool_call_id, tool_name, _display, _exec_args) in enumerate(prepared):
- trace_call_id = new_call_id(f"chat-iter-{iteration_index}-tool-{tool_index}")
- base_meta = build_trace_metadata(
- call_id=trace_call_id,
- phase="acting",
- label=self._t("labels.tool_call", default="Tool call"),
- call_kind="tool_planning",
- trace_id=trace_call_id,
- trace_role="tool",
- trace_group="tool_call",
+ return await dispatch_tool_calls(
+ tool_calls=tool_calls,
+ context=context,
+ stream=stream,
+ source="chat",
+ stage="acting",
+ iteration_index=iteration_index,
+ registry=self.registry,
+ kwarg_augmenter=self._augment_tool_kwargs,
+ retrieve_meta_factory=lambda meta, tn, ta: self._retrieve_trace_metadata(
+ meta, context=context, tool_name=tn, tool_args=ta
+ ),
+ tool_call_label=self._t("labels.tool_call", default="Tool call"),
+ retrieve_label=self._t("labels.retrieve", default="Retrieve"),
+ empty_tool_result_message=self._t("notices.empty_tool_result"),
+ start_retrieval_message=self._t(
+ "notices.start_retrieval", default="Starting retrieval"
+ ),
+ too_many_tool_calls_message=too_many,
+ unknown_error_message_factory=lambda tn: self._t(
+ "notices.tool_unknown_error",
+ tool=tn,
+ default=f"An unknown error occurred while executing {tn}.",
+ ),
+ trace_id_prefix="chat-iter",
+ )
+
+ # ------------------------------------------------------------------
+ # ``ask_user`` pause / resume
+ # ------------------------------------------------------------------
+ async def _await_user_reply_and_resolve(
+ self,
+ *,
+ context: UnifiedContext,
+ stream: StreamBus,
+ dispatch: DispatchOutcome,
+ ) -> bool:
+ """Pause the loop on an ``ask_user`` call and wait for the reply.
+
+ Returns ``True`` once the user's reply has been substituted into the
+ matching ``role=tool`` message and the loop can resume. Returns
+ ``False`` if the runtime did not wire a reply queue (in which case
+ the pipeline falls back to emitting a terminator final-response,
+ mirroring the legacy behaviour so direct unit tests of the pipeline
+ still work).
+
+ ``asyncio.CancelledError`` propagates up from ``waiter()`` when the
+ runtime cancels the turn task — caught by the runtime's own
+ cancellation handler which emits the right ERROR + DONE events. We
+ intentionally do NOT catch it here.
+ """
+ ask_user = (dispatch.pause_payload or {}).get("ask_user") or {}
+ waiter = context.metadata.get("wait_for_user_reply")
+ if not callable(waiter):
+ logger.warning(
+ "ask_user paused the loop but no wait_for_user_reply "
+ "callable is wired on the context; emitting terminator."
)
- per_tool_trace_meta.append(
- merge_trace_metadata(
- base_meta,
- {
- "tool_call_id": tool_call_id,
- "tool_name": tool_name,
- "tool_index": tool_index,
- "iteration_index": iteration_index,
- "session_id": context.session_id,
- "turn_id": str(context.metadata.get("turn_id", "")),
- },
- )
+ await self._emit_terminator_final_response(
+ stream,
+ {
+ "tool_name": (dispatch.pause_payload or {}).get("tool_name", "ask_user"),
+ "content": _flatten_ask_user_summary(ask_user),
+ "metadata": {"ask_user": ask_user},
+ },
)
+ return False
- for tool_index, (tool_call_id, tool_name, display_args, _exec_args) in enumerate(prepared):
- tool_meta = per_tool_trace_meta[tool_index]
- await stream.tool_call(
- tool_name=tool_name,
- args=display_args,
- source="chat",
- stage="acting",
- metadata=merge_trace_metadata(tool_meta, {"trace_kind": "tool_call"}),
- )
+ raw_reply = await waiter()
+ if raw_reply is None:
+ return False
- results = await asyncio.gather(
- *[
- self._execute_tool_call(
- tool_name,
- exec_args,
- stream=stream,
- retrieve_meta=self._retrieve_trace_metadata(
- per_tool_trace_meta[tool_index],
- context=context,
- tool_name=tool_name,
- tool_args=exec_args,
- ),
- )
- for tool_index, (_tool_call_id, tool_name, _display, exec_args) in enumerate(
- prepared
- )
- ]
+ # Normalise: callers may pass either a plain string (older tests
+ # / direct injections) or a structured dict (runtime / v2 path).
+ reply_text, answers = _normalise_user_reply(raw_reply)
+ body_text = _format_user_reply_body(reply_text, answers, ask_user)
+
+ # Mutate the paused tool's matching ``role=tool`` message in place.
+ # ``dispatch.tool_messages`` shares object identity with entries we
+ # already extended onto ``messages``, so this change is visible to
+ # the next LLM call without re-walking the list.
+ #
+ # The body is deliberately directive: a bare "User answered: X" was
+ # being misread by some models as the end of the turn. Spelling out
+ # "you must continue / do not stop after a one-liner ack" at the
+ # exact point in the conversation where the model is deciding what
+ # to do next keeps the loop alive across ask_user.
+ resumption_directive = (
+ f"{body_text}\n\n"
+ "[ask_user resolved. The turn is NOT over. Use these answers "
+ "to address the user's ORIGINAL request — call more tools "
+ "if you need them, then close with a substantive ``FINISH`` "
+ "reply. A short acknowledgment of the answer is NOT an "
+ "acceptable final response.]"
)
+ for tm in dispatch.tool_messages:
+ if tm.get("tool_call_id") == dispatch.pause_tool_call_id:
+ tm["content"] = resumption_directive
+ break
- aggregated_sources: list[dict[str, Any]] = []
- tool_messages: list[dict[str, Any]] = []
- for tool_index, ((tool_call_id, tool_name, display_args, _exec_args), result) in enumerate(
- zip(prepared, results, strict=False)
- ):
- result_text = str(result["result_text"])
- tool_meta = per_tool_trace_meta[tool_index]
- await stream.tool_result(
- tool_name=tool_name,
- result=result_text,
- source="chat",
- stage="acting",
- metadata=merge_trace_metadata(tool_meta, {"trace_kind": "tool_result"}),
- )
- aggregated_sources.extend(result.get("sources") or [])
- tool_messages.append(
- {
- "role": "tool",
- "tool_call_id": tool_call_id,
- "name": tool_name,
- "content": result_text,
- }
- )
- return aggregated_sources, tool_messages
+ progress_meta: dict[str, Any] = {
+ "trace_kind": "user_reply",
+ "ask_user_resolved": True,
+ "ask_user_tool_call_id": dispatch.pause_tool_call_id,
+ "reply_preview": (reply_text or "")[:200],
+ }
+ if answers:
+ progress_meta["answers"] = list(answers)
+ await stream.progress(
+ "",
+ source="chat",
+ stage="responding",
+ metadata=progress_meta,
+ )
+ return True
# ------------------------------------------------------------------
# Answer-now: cancel mid-stream and produce a final answer from what's
@@ -758,18 +1029,50 @@ class AgenticChatPipeline:
)
chunks: list[str] = []
- async for chunk in self._stream_messages(
- messages, max_tokens=self._answer_now_max_tokens
- ):
- if not chunk:
- continue
- chunks.append(chunk)
+ label_buf = ""
+ label_resolved = False
+
+ async def _emit_answer_chunk(text: str) -> None:
+ if not text:
+ return
+ chunks.append(text)
await stream.content(
- chunk,
+ text,
source="chat",
stage="responding",
metadata=merge_trace_metadata(trace_meta, {"trace_kind": "llm_chunk"}),
)
+
+ async for chunk in self._stream_messages(
+ messages, max_tokens=self._answer_now_max_tokens
+ ):
+ if not chunk:
+ continue
+ if not label_resolved:
+ label_buf += chunk
+ parsed = _classify_answer_now_label(label_buf)
+ if parsed is not None:
+ # Answer-now reuses the normal chat system prompt, so
+ # many models correctly start with ``FINISH``. Strip
+ # that protocol label before it reaches the UI.
+ _label, after_label = parsed
+ label_resolved = True
+ label_buf = ""
+ await _emit_answer_chunk(after_label)
+ elif len(label_buf) > LABEL_PROBE_MAX_CHARS:
+ label_resolved = True
+ buffered = label_buf
+ label_buf = ""
+ await _emit_answer_chunk(buffered)
+ continue
+ await _emit_answer_chunk(chunk)
+ if not label_resolved and label_buf:
+ parsed = _classify_answer_now_label(label_buf, final=True)
+ if parsed is not None:
+ _label, after_label = parsed
+ await _emit_answer_chunk(after_label)
+ else:
+ await _emit_answer_chunk(label_buf)
await stream.progress(
"",
source="chat",
@@ -785,10 +1088,42 @@ class AgenticChatPipeline:
"answer_now": True,
"source_trace": trace_meta.get("label", "Answer now"),
}
- cs = self._get_cost_summary()
- if cs:
- result_payload["metadata"] = {"cost_summary": cs}
- await stream.result(result_payload, source="chat")
+ await emit_capability_result(stream, result_payload, source="chat", usage=self._usage)
+
+ # ------------------------------------------------------------------
+ # Per-iteration marker (tells the model where it is in the budget)
+ # ------------------------------------------------------------------
+ def _append_iteration_marker(
+ self,
+ *,
+ messages: list[dict[str, Any]],
+ iteration: int,
+ max_iterations: int,
+ ) -> None:
+ """Append a ``role=user`` system-style note announcing the current
+ iteration so the LLM can pace itself.
+
+ Copy is YAML-driven (``iteration_marker``). Iteration is 0-indexed
+ internally; the marker shows ``current = iteration + 1`` to match
+ human counting. Markers from earlier iterations are kept in the
+ history so the model can also see how it has been spending its
+ budget across the turn.
+ """
+ current = iteration + 1
+ marker = self._t(
+ "iteration_marker",
+ default=(
+ f"[System note] You are at iteration {current}/{max_iterations} "
+ "of this turn. Once the maximum is reached, the next reply is "
+ "forced to be ``FINISH``."
+ ),
+ current=current,
+ max=max_iterations,
+ )
+ marker = (marker or "").strip()
+ if not marker:
+ return
+ messages.append({"role": "user", "content": marker})
# ------------------------------------------------------------------
# In-turn context-window guard
@@ -798,11 +1133,11 @@ class AgenticChatPipeline:
messages: list[dict[str, Any]],
stream: StreamBus,
) -> None:
- """Replace oldest tool-result contents with a snip marker until total
- token count fits under ``CONTEXT_WINDOW_GUARD_RATIO`` of the model's
- effective window. Never touches the system message or the original
- user message — only ``role == 'tool'`` payloads. Cross-turn history
- compression is handled separately by ``ContextBuilder``.
+ """Replace oldest tool-result contents with a snip marker until the
+ total token count fits under ``CONTEXT_WINDOW_GUARD_RATIO`` of the
+ model's effective window. Never touches the system message or the
+ original user message — only ``role == 'tool'`` payloads. Cross-turn
+ history compression is handled separately by ``ContextBuilder``.
"""
try:
window = resolve_effective_context_window(
@@ -829,7 +1164,6 @@ class AgenticChatPipeline:
if self._estimate_messages_tokens(messages) <= budget:
break
if snipped:
- # Warning is not a sub-trace — emit without a call_id.
await stream.progress(
self._t("notices.context_window_guard"),
source="chat",
@@ -839,9 +1173,9 @@ class AgenticChatPipeline:
@staticmethod
def _estimate_messages_tokens(messages: list[dict[str, Any]]) -> int:
- # Local import to break the agents.chat ↔ services.session
- # import cycle (context_builder pulls in agents.base_agent which
- # re-enters this module during package init).
+ # Local import to break the agents.chat ↔ services.session import
+ # cycle (context_builder pulls in agents.base_agent which re-enters
+ # this module during package init).
from deeptutor.services.session.context_builder import count_tokens
total = 0
@@ -863,11 +1197,11 @@ class AgenticChatPipeline:
enabled_tools: list[str],
context: UnifiedContext,
) -> str:
- # ``list_with_usage`` renders one bullet per tool including the tool's
- # ``when_to_use`` and ``input_format`` — pulled from per-tool YAML
- # under ``deeptutor/tools/prompting/hints/{lang}/{tool}.yaml``. This
- # is the only place per-tool guidance enters the chat persona prompt:
- # disabled tools contribute nothing, so the model never sees
+ # ``list_with_usage`` renders one bullet per tool including the
+ # tool's ``when_to_use`` and ``input_format`` — pulled from per-tool
+ # YAML under ``deeptutor/tools/prompting/hints/{lang}/{tool}.yaml``.
+ # This is the only place per-tool guidance enters the chat persona
+ # prompt: disabled tools contribute nothing, so the model never sees
# instructions for tools it cannot call.
tool_list = self.registry.build_prompt_text(
enabled_tools,
@@ -890,10 +1224,10 @@ class AgenticChatPipeline:
) -> list[dict[str, Any]]:
"""Assemble ``[system] + history + user``.
- ``memory_context``, ``skills_context``, and ``source_manifest`` are
- appended as separate ``---``-delimited sections after the main
- system prompt so prompt caching stays effective when only the
- manifest tail changes between turns.
+ ``memory_context``, ``skills_context``, ``source_manifest``, and
+ the notebook manifest are appended as separate ``---``-delimited
+ sections after the main system prompt so prompt caching stays
+ effective when only the manifest tail changes between turns.
"""
system_parts = [system_prompt]
if context.memory_context:
@@ -902,6 +1236,9 @@ class AgenticChatPipeline:
system_parts.append(context.skills_context)
if context.source_manifest:
system_parts.append(context.source_manifest)
+ notebook_manifest = self._build_notebook_manifest()
+ if notebook_manifest:
+ system_parts.append(notebook_manifest)
messages: list[dict[str, Any]] = [
{"role": "system", "content": "\n\n---\n\n".join(system_parts)}
]
@@ -930,26 +1267,27 @@ class AgenticChatPipeline:
# Tool selection + scheme construction
# ------------------------------------------------------------------
def _compose_enabled_tools(self, context: UnifiedContext) -> list[str]:
- """Resolve the tool set for this turn.
-
- - User-toggled tools come from ``context.enabled_tools``, filtered
- by ``CHAT_OPTIONAL_TOOLS`` (so ``geogebra_analysis`` and
- ``read_source`` are never user-toggleable here).
- - ``rag`` is auto-included iff the user attached any KB.
- - ``read_source`` is auto-included iff the turn has a non-empty
- source index (notebook / book / history / question / attachment).
+ """Resolve the tool set for this turn via the shared composition policy.
+
+ Auto-mount flags are resolved against chat's own context:
+
+ - ``has_kb`` — iff the user attached any KB.
+ - ``has_sources`` — iff the turn has a non-empty source index
+ (notebook / book / history / question / attachment).
+ - ``has_memory`` — iff the active user has memory content.
+ - ``has_notebooks`` — iff the active user has at least one notebook.
"""
- requested = [tool for tool in (context.enabled_tools or []) if tool != "rag"]
- normalized = [
- tool.name
- for tool in self.registry.get_enabled(requested)
- if tool.name in CHAT_OPTIONAL_TOOLS
- ]
- if self._selected_kbs(context):
- normalized.append("rag")
- if self._source_index(context):
- normalized.append("read_source")
- return normalized
+ return compose_enabled_tools(
+ registry=self.registry,
+ requested_tools=context.enabled_tools,
+ optional_whitelist=CHAT_OPTIONAL_TOOLS,
+ mount_flags=ToolMountFlags(
+ has_kb=bool(self._selected_kbs(context)),
+ has_sources=bool(self._source_index(context)),
+ has_memory=user_has_memory(),
+ has_notebooks=user_has_notebooks(),
+ ),
+ )
def _build_llm_tool_schemas(
self,
@@ -962,10 +1300,15 @@ class AgenticChatPipeline:
- ``read_source.source_id`` is restricted to the attached source
ids as an enum (this makes the LLM less likely to hallucinate
ids and lets the OpenAI SDK validate the call client-side).
+ - ``save_to_notebook.notebook_id`` is restricted to the active
+ user's actual notebook ids — mirrors the dropdown a human sees
+ in the Save-to-Notebook dialog so the model literally cannot
+ save into a notebook the user doesn't have.
"""
schemas = self.registry.build_openai_schemas(enabled_tools)
kb_choices = self._selected_kbs(context)
source_ids = sorted((self._source_index(context) or {}).keys())
+ notebook_choices = self._notebook_choices()
for schema in schemas:
function = schema.get("function") if isinstance(schema, dict) else None
if not isinstance(function, dict):
@@ -985,9 +1328,110 @@ class AgenticChatPipeline:
sid_schema = properties.get("source_id")
if isinstance(sid_schema, dict) and source_ids:
sid_schema["enum"] = source_ids
+ if function.get("name") == "geogebra_analysis" and isinstance(properties, dict):
+ # ``image_base64`` is server-side injected from the turn's
+ # image attachment; hide it from the LLM-visible schema so
+ # the model doesn't try to fabricate a value.
+ properties.pop("image_base64", None)
+ required = parameters.get("required")
+ if isinstance(required, list):
+ parameters["required"] = [name for name in required if name != "image_base64"]
+ if (
+ function.get("name") in {"list_notebook", "write_note"}
+ and isinstance(properties, dict)
+ and notebook_choices
+ ):
+ nb_schema = properties.get("notebook_id")
+ if isinstance(nb_schema, dict):
+ nb_schema["enum"] = [choice["id"] for choice in notebook_choices]
+ nb_choices_render = "; ".join(
+ f"{c['id']} = {c['name']}" for c in notebook_choices
+ )
+ nb_schema["description"] = (
+ f"{nb_schema.get('description', '').rstrip(' .')}. "
+ f"Available: {nb_choices_render}."
+ )
parameters["additionalProperties"] = False
return schemas
+ def _build_notebook_manifest(self) -> str:
+ """Render the user's notebooks as a system-prompt index block.
+
+ Always-on (when the user has notebooks): keeps the LLM grounded in
+ the real notebook names + ids + record counts so it never invents
+ notebook names when asking the user where to save. The block is
+ tiny (one line per notebook), capped at ~30 entries to protect the
+ context window. Heavy listing belongs to the ``list_notebook`` tool
+ — this is the "always visible at a glance" affordance only.
+ """
+ choices = self._notebook_choices_full()
+ if not choices:
+ return ""
+ capped = choices[:30]
+ if self.language == "zh":
+ lines = ["[用户的笔记本列表]"]
+ else:
+ lines = ["[User's notebooks]"]
+ for entry in capped:
+ nid = entry.get("id", "")
+ name = entry.get("name", nid)
+ count = entry.get("record_count", 0)
+ lines.append(f"- `{nid}` — {name} ({count} records)")
+ if len(choices) > len(capped):
+ lines.append(
+ f"… (+{len(choices) - len(capped)} more — call `list_notebook` to see the rest)"
+ )
+ if self.language == "zh":
+ lines.append(
+ "(要列出某笔记本里的具体记录,用 `list_notebook(notebook_id=...)`;要新增或编辑记录,用 `write_note`。)"
+ )
+ else:
+ lines.append(
+ "(Use `list_notebook(notebook_id=...)` to drill into one; use `write_note` to append / edit records.)"
+ )
+ return "\n".join(lines)
+
+ @staticmethod
+ def _notebook_choices_full() -> list[dict[str, Any]]:
+ try:
+ from deeptutor.services.notebook import get_notebook_manager
+
+ notebooks = get_notebook_manager().list_notebooks() or []
+ except Exception:
+ return []
+ rows: list[dict[str, Any]] = []
+ for nb in notebooks:
+ nid = str(nb.get("id") or "").strip()
+ if not nid:
+ continue
+ name = str(nb.get("name") or nb.get("title") or nid).strip() or nid
+ count = nb.get("record_count")
+ if not isinstance(count, int):
+ try:
+ count = int(count or 0)
+ except (TypeError, ValueError):
+ count = 0
+ rows.append({"id": nid, "name": name, "record_count": count})
+ return rows
+
+ @staticmethod
+ def _notebook_choices() -> list[dict[str, str]]:
+ """List the active user's notebooks as ``[{id, name}]`` rows."""
+ try:
+ from deeptutor.services.notebook import get_notebook_manager
+
+ notebooks = get_notebook_manager().list_notebooks() or []
+ except Exception:
+ return []
+ choices: list[dict[str, str]] = []
+ for nb in notebooks:
+ nid = str(nb.get("id") or "").strip()
+ if not nid:
+ continue
+ name = str(nb.get("name") or nb.get("title") or nid).strip() or nid
+ choices.append({"id": nid, "name": name})
+ return choices
+
@staticmethod
def _extract_answer_now_context(context: UnifiedContext) -> dict[str, Any] | None:
from deeptutor.capabilities._answer_now import extract_answer_now_context
@@ -995,90 +1439,8 @@ class AgenticChatPipeline:
return extract_answer_now_context(context)
# ------------------------------------------------------------------
- # Tool execution
+ # Tool kwarg augmentation
# ------------------------------------------------------------------
- async def _execute_tool_call(
- self,
- tool_name: str,
- tool_args: dict[str, Any],
- *,
- stream: StreamBus | None = None,
- retrieve_meta: dict[str, Any] | None = None,
- ) -> dict[str, Any]:
- async def _event_sink(
- event_type: str,
- message: str = "",
- metadata: dict[str, Any] | None = None,
- ) -> None:
- if stream is None or retrieve_meta is None or not message:
- return
- await stream.progress(
- message,
- source="chat",
- stage="acting",
- metadata=derive_trace_metadata(
- retrieve_meta,
- trace_kind=str(event_type or "tool_log"),
- **(metadata or {}),
- ),
- )
-
- if stream is not None and retrieve_meta is not None:
- query = str(retrieve_meta.get("query") or tool_args.get("query") or "").strip()
- await stream.progress(
- f"Query: {query}" if query else self._t("notices.start_retrieval"),
- source="chat",
- stage="acting",
- metadata=derive_trace_metadata(
- retrieve_meta,
- trace_kind="call_status",
- call_state="running",
- ),
- )
- try:
- result = await self.registry.execute(
- tool_name,
- event_sink=_event_sink if retrieve_meta is not None else None,
- **tool_args,
- )
- if stream is not None and retrieve_meta is not None:
- await stream.progress(
- f"Retrieve complete ({len(result.content)} chars)",
- source="chat",
- stage="acting",
- metadata=derive_trace_metadata(
- retrieve_meta,
- trace_kind="call_status",
- call_state="complete",
- ),
- )
- return {
- "result_text": result.content or self._t("notices.empty_tool_result"),
- "success": result.success,
- "sources": result.sources,
- "metadata": result.metadata,
- }
- except Exception as exc:
- logger.error("Tool %s failed", tool_name, exc_info=True)
- if stream is not None and retrieve_meta is not None:
- await stream.error(
- f"Retrieve failed: {exc}",
- source="chat",
- stage="acting",
- metadata=derive_trace_metadata(
- retrieve_meta,
- trace_kind="call_status",
- call_state="error",
- error=str(exc),
- ),
- )
- return {
- "result_text": f"Error executing {tool_name}: {exc}",
- "success": False,
- "sources": [],
- "metadata": {"error": str(exc)},
- }
-
def _augment_tool_kwargs(
self,
tool_name: str,
@@ -1116,6 +1478,45 @@ class AgenticChatPipeline:
# ReadSourceTool reads from this per-turn map rather than from
# any shared state, so each turn's sources stay isolated.
kwargs["source_index"] = self._source_index(context)
+ elif tool_name == "write_note":
+ # The tool assembles the transcript body itself from the
+ # conversation history (so the saved record is real Q&A, not
+ # an LLM-authored summary). Inject the history snapshot +
+ # current user message; the LLM never sees these as arguments
+ # — they're stripped from the JSON schema and populated
+ # server-side.
+ kwargs["conversation_history"] = list(context.conversation_history or [])
+ kwargs["current_user_message"] = context.user_message or ""
+ elif tool_name == "geogebra_analysis":
+ # The LLM never has access to the raw image bytes — we
+ # unconditionally inject the first image attachment's base64
+ # here (overwriting any value the LLM may have hallucinated
+ # into the kwarg). Without this, the underlying
+ # VisionSolverAgent would fail fast with "No image provided."
+ first_image = next(
+ (
+ att
+ for att in (context.attachments or [])
+ if getattr(att, "type", "") == "image" and getattr(att, "base64", "")
+ ),
+ None,
+ )
+ if first_image is not None:
+ # Attachment.base64 is the raw base64 payload (no data-URI
+ # prefix), but VisionSolverAgent feeds the value straight into
+ # an OpenAI ``image_url.url`` field which requires the data
+ # URI form. Wrap it here so the vision LLM accepts the image
+ # instead of silently failing all four pipeline stages.
+ raw_b64 = first_image.base64
+ if raw_b64.startswith("data:"):
+ kwargs["image_base64"] = raw_b64
+ else:
+ mime = getattr(first_image, "mime_type", "") or "image/png"
+ kwargs["image_base64"] = f"data:{mime};base64,{raw_b64}"
+ # Force the session language; this tool does not expose ``language``
+ # as an LLM-visible parameter, so an override here would only come
+ # from a hallucinated kwarg.
+ kwargs["language"] = context.language or "zh"
return kwargs
# ------------------------------------------------------------------
@@ -1129,18 +1530,19 @@ class AgenticChatPipeline:
tool_name: str,
tool_args: dict[str, Any],
) -> dict[str, Any] | None:
- """Build the retrieve-flavoured metadata for ``rag`` progress events.
-
- Each RAG call already has its own ``tool_meta`` (with its own
- ``call_id``) allocated by :py:meth:`_dispatch_tool_calls`; we
- derive a "retrieve" variant of it so the in-tool progress events
- (provider selection, chunk retrieval, etc.) stay attached to the
- same sub-trace but show as ``trace_role=retrieve`` for the
- chevron icon. For non-rag tools we return ``None`` so the
- executor skips the retrieve-progress surface.
+ """Retrieve-flavoured metadata for ``rag`` progress events.
+
+ Each rag call already has its own ``tool_meta`` (with its own
+ ``call_id``); we derive a "retrieve" variant of it so the in-tool
+ progress events (provider selection, chunk retrieval, etc.) stay
+ attached to the same sub-trace but show as
+ ``trace_role=retrieve`` for the chevron icon. For non-rag tools
+ we return ``None`` so the executor skips the retrieve-progress
+ surface.
"""
if tool_name != "rag":
return None
+ _ = context # context unused for now; kept for parity with solve's variant
return derive_trace_metadata(
tool_meta,
label=self._t("labels.retrieve", default="Retrieve"),
@@ -1179,27 +1581,6 @@ class AgenticChatPipeline:
# ------------------------------------------------------------------
# LLM call helpers
# ------------------------------------------------------------------
- @staticmethod
- def _assistant_message_with_tool_calls(
- content: str,
- tool_calls: list[dict[str, Any]],
- ) -> dict[str, Any]:
- return {
- "role": "assistant",
- "content": content or None,
- "tool_calls": [
- {
- "id": tc["id"],
- "type": "function",
- "function": {
- "name": tc["name"],
- "arguments": tc.get("arguments") or "{}",
- },
- }
- for tc in tool_calls
- ],
- }
-
async def _stream_messages(
self,
messages: list[dict[str, Any]],
@@ -1222,87 +1603,37 @@ class AgenticChatPipeline:
output_chars += len(chunk)
yield chunk
input_chars = sum(len(str(m.get("content", ""))) for m in messages)
- est_input = int(input_chars / 3.5)
- est_output = int(output_chars / 3.5)
- self._usage["prompt_tokens"] += est_input
- self._usage["completion_tokens"] += est_output
- self._usage["total_tokens"] += est_input + est_output
- self._usage["calls"] += 1
+ self._usage.add_estimated(input_chars=input_chars, output_chars=output_chars)
def _build_openai_client(self):
- http_client = None
- if load_system_settings()["disable_ssl_verify"]:
- http_client = httpx.AsyncClient(verify=False) # nosec B501
- default_headers = self.extra_headers or None
- if self.binding == "azure_openai" or (self.binding == "openai" and self.api_version):
- return AsyncAzureOpenAI(
- api_key=self.api_key or "sk-no-key-required",
- azure_endpoint=self.base_url,
- api_version=self.api_version,
- http_client=http_client,
- default_headers=default_headers,
- )
- return AsyncOpenAI(
- api_key=self.api_key or "sk-no-key-required",
- base_url=self.base_url or None,
- http_client=http_client,
- default_headers=default_headers,
- )
+ """Build an OpenAI/Azure async client from the pipeline's LLM config.
+
+ Kept as a method (rather than always reusing ``self._client``) so any
+ downstream test or future caller that wants a fresh client per call
+ can still get one without poking at module-level state.
+ """
+ return build_openai_client(self._client_config)
def _completion_kwargs(self, max_tokens: int) -> dict[str, Any]:
- kwargs: dict[str, Any] = {"temperature": self._chat_temperature}
- if self.model:
- kwargs.update(get_token_limit_kwargs(self.model, max_tokens))
- return kwargs
+ return build_completion_kwargs(
+ temperature=self._chat_temperature,
+ model=self.model,
+ max_tokens=max_tokens,
+ )
def _can_use_native_tool_calling(self) -> bool:
- # Same gating as before: providers we know reliably support OpenAI
- # function-calling. For other bindings the loop still runs but
- # without tool schemas — the model just chats.
- if not supports_tools(self.binding, self.model):
- return False
- return self.binding not in {
- "anthropic",
- "claude",
- "ollama",
- "lm_studio",
- "vllm",
- "llama_cpp",
- }
-
- # ------------------------------------------------------------------
- # Usage tracking
- # ------------------------------------------------------------------
- def _accumulate_usage(self, response: Any) -> None:
- usage = getattr(response, "usage", None) or response
- prompt = getattr(usage, "prompt_tokens", 0) or 0
- completion = getattr(usage, "completion_tokens", 0) or 0
- total = getattr(usage, "total_tokens", prompt + completion) or 0
- if prompt or completion or total:
- self._usage["prompt_tokens"] += int(prompt)
- self._usage["completion_tokens"] += int(completion)
- self._usage["total_tokens"] += int(total)
- self._usage["calls"] += 1
-
- def _get_cost_summary(self) -> dict[str, Any] | None:
- if self._usage["calls"] == 0:
- return None
- return {
- "total_cost_usd": 0,
- "total_tokens": self._usage["total_tokens"],
- "total_calls": self._usage["calls"],
- "prompt_tokens": self._usage["prompt_tokens"],
- "completion_tokens": self._usage["completion_tokens"],
- }
+ return can_use_native_tool_calling(binding=self.binding, model=self.model)
# ------------------------------------------------------------------
# YAML prompt lookup
# ------------------------------------------------------------------
def _t(self, key: str, default: str = "", **kwargs: Any) -> str:
- """Look up a YAML-loaded prompt by dotted key. Returns ``default``
- when missing. Renders via ``str.format`` when ``kwargs`` are
- provided; missing placeholders leave the template unrendered
- instead of crashing the pipeline."""
+ """Look up a YAML-loaded prompt by dotted key.
+
+ Returns ``default`` when missing. Renders via ``str.format`` when
+ ``kwargs`` are provided; missing placeholders leave the template
+ unrendered instead of crashing the pipeline.
+ """
value: Any = self._prompts
for part in key.split("."):
if not isinstance(value, dict) or part not in value:
@@ -1317,31 +1648,125 @@ class AgenticChatPipeline:
return value
return value
- # ------------------------------------------------------------------
- # Misc small helpers
- # ------------------------------------------------------------------
- @staticmethod
- def _suppress_close_errors():
- from contextlib import suppress
- return suppress(Exception)
+# ---------------------------------------------------------------------------
+# Loop host adapter
+# ---------------------------------------------------------------------------
-class _UsageShim:
- """Adapt OpenAI streaming ``CompletionUsage`` into the shape
- ``_accumulate_usage`` expects (it walks ``response.usage`` fields)."""
+class _ChatLoopHost:
+ """Bind the chat pipeline + current turn's context/stream into a single
+ object the generic loop primitive can call back into.
- def __init__(self, raw: Any) -> None:
- self.usage = raw
+ All chat-specific behavior — trace metadata, tool dispatch, pause/terminate,
+ final emission, force-finalize — lives as methods on
+ :class:`AgenticChatPipeline`; this adapter just routes the
+ :class:`~deeptutor.core.agentic.LoopHost` protocol calls to them.
+ """
+ def __init__(
+ self,
+ *,
+ pipeline: AgenticChatPipeline,
+ context: UnifiedContext,
+ stream: StreamBus,
+ client: Any,
+ ) -> None:
+ self._pipeline = pipeline
+ self._context = context
+ self._stream = stream
+ self._client = client
-def _read_int(cfg: Any, *, key: str, default: int) -> int:
- """Pull an integer from a nested YAML dict, falling back to ``default``."""
- if isinstance(cfg, dict):
- value = cfg.get(key, default)
- else:
- value = default
- try:
- return int(value)
- except (TypeError, ValueError):
- return default
+ async def guard_context_window(self, messages: list[dict[str, Any]]) -> None:
+ await self._pipeline._guard_context_window(messages, self._stream)
+
+ async def before_iteration(
+ self,
+ *,
+ messages: list[dict[str, Any]],
+ iteration: int,
+ max_iterations: int,
+ ) -> None:
+ """Inject the per-iteration counter so the model can pace itself."""
+ self._pipeline._append_iteration_marker(
+ messages=messages,
+ iteration=iteration,
+ max_iterations=max_iterations,
+ )
+
+ def build_iteration_trace_meta(self, iteration: int) -> tuple[dict[str, Any], dict[str, Any]]:
+ return self._pipeline._build_iteration_trace_metadata(iteration)
+
+ async def dispatch_tools(
+ self,
+ *,
+ iteration: int,
+ tool_calls: list[dict[str, Any]],
+ ) -> DispatchOutcome:
+ return await self._pipeline._dispatch_tool_calls(
+ tool_calls=tool_calls,
+ context=self._context,
+ stream=self._stream,
+ iteration_index=iteration,
+ )
+
+ async def resolve_pause(self, dispatch: DispatchOutcome) -> bool:
+ return await self._pipeline._await_user_reply_and_resolve(
+ context=self._context,
+ stream=self._stream,
+ dispatch=dispatch,
+ )
+
+ async def emit_terminator(self, payload: dict[str, Any] | None) -> None:
+ await self._pipeline._emit_terminator_final_response(self._stream, payload)
+
+ async def emit_final(self, text: str, final_meta: dict[str, Any]) -> None:
+ await self._pipeline._emit_final_text(self._stream, text, final_meta)
+
+ def assistant_message_with_tool_calls(
+ self,
+ *,
+ content: str,
+ tool_calls: list[dict[str, Any]],
+ ) -> dict[str, Any]:
+ return self._pipeline._assistant_message_with_tool_calls(content, tool_calls)
+
+ def protocol_retry_notice(self) -> str:
+ return self._pipeline._protocol_retry_notice()
+
+ def protocol_repair_message(self, violation: str) -> str:
+ return self._pipeline._protocol_repair_message(violation)
+
+ async def force_finalize(
+ self,
+ *,
+ messages: list[dict[str, Any]],
+ start_iteration: int,
+ ) -> tuple[str, bool, int]:
+ return await self._pipeline._run_forced_finish(
+ client=self._client,
+ messages=messages,
+ stream=self._stream,
+ start_iteration=start_iteration,
+ )
+
+
+# ---------------------------------------------------------------------------
+# Forced-finish protocol validation (chat-local because the violation key
+# vocabulary mirrors chat's repair-copy keys).
+# ---------------------------------------------------------------------------
+
+
+def _classify_forced_finish_violation(step: LabeledStepResult) -> str | None:
+ """Lightweight violation classifier for the FINISH-only finalization
+ loop. With ``allowed_labels=(FINISH,)`` and ``tool_schemas=None``, the
+ only possible violations are missing label / inline duplicate label.
+ """
+ if step.label == LABEL_UNKNOWN:
+ return "missing_label"
+ if find_inline_labels(
+ step.text,
+ allowed_labels=(LABEL_FINISH, LABEL_TOOL, LABEL_THINK, LABEL_PAUSE),
+ ):
+ return "multiple_labels"
+ return None
diff --git a/deeptutor/agents/chat/prompts/en/agentic_chat.yaml b/deeptutor/agents/chat/prompts/en/agentic_chat.yaml
index 02bdf4d6c..1b11e9376 100644
--- a/deeptutor/agents/chat/prompts/en/agentic_chat.yaml
+++ b/deeptutor/agents/chat/prompts/en/agentic_chat.yaml
@@ -35,16 +35,21 @@ system: |-
# Output protocol (mandatory — every reply must comply)
- Every reply MUST begin with exactly one of these three labels on the very first line, all-caps, wrapped with two backticks on each side:
+ Every reply MUST begin with exactly one of these four labels on the very first line, all-caps, wrapped with two backticks on each side:
- ``FINISH`` → This reply IS the final user-facing answer. No tools. Whatever follows the label is the answer.
+ ``FINISH`` → This reply IS the final user-facing answer. No tools. Whatever follows the label is the answer; the turn ends here.
``TOOL`` → This reply will use tools. After the label you may write one short sentence of intent, then emit native tool_calls.
- ``THINK`` → This reply is intermediate reasoning — **no tools, and not the final answer either**. You're writing your thoughts to push toward the next iteration. The next iteration will continue from here and eventually finish with ``FINISH``.
+ ``THINK`` → This reply is intermediate reasoning — **no tools, and not the final answer either**. The text is your private scratchpad; the user does NOT see it. The next iteration will continue from here and eventually finish with ``FINISH``.
+ ``PAUSE`` → Same as ``THINK`` (intermediate reasoning, no tools, not the final answer), except the user sees this text. Pick ``PAUSE`` over ``THINK`` only when you'd otherwise reach for ``THINK`` AND the reasoning itself is worth showing to the user — the thought process is part of the value, not just the conclusion.
+
+ The runtime treats **only** ``FINISH`` as terminal. ``THINK``, ``TOOL``, ``PAUSE``, tool results, user replies gathered through tools, and unlabeled text are never the end of the turn.
+ One LLM reply may choose **exactly one** action label. After the first line, do not write any other protocol label anywhere in the body. ``THINK``, ``FINISH``, and ``PAUSE`` must not emit tool_calls. ``TOOL`` must emit real native tool_calls in the same reply.
Pick one per reply based on current context:
- Simple question / enough info → ``FINISH``.
- Need external info / computation / retrieval → ``TOOL``.
- Complex problem that benefits from multi-step reasoning before acting → ``THINK`` (loop a few rounds; always close with ``FINISH``).
+ - You'd otherwise pick ``THINK`` AND showing this reasoning step would actually help the user follow along → ``PAUSE``.
Examples:
``FINISH``
@@ -57,16 +62,20 @@ system: |-
``THINK``
This problem has three steps: X, then Y, then Z. Next iteration I'll tackle X first…
+ ``PAUSE``
+ The data is in two different units (miles vs. kilometers) — I'll convert everything to kilometers first so the comparison is apples-to-apples.
+
Never:
- Put anything before the label (no leading prose, quotes, or stray characters).
- Use single backticks, brackets, or any alternate wrapper.
- - Emit more than one label in a single reply.
+ - Emit more than one label in a single reply, such as thinking first and then writing ``TOOL`` or ``FINISH`` in the same message.
+ - Use ``PAUSE`` for every reasoning step. Default to ``THINK``; only switch to ``PAUSE`` when the user genuinely benefits from seeing that specific piece of reasoning.
# Per-turn reasoning
1. Read the user's request. If you already have enough information for a reliable answer, answer directly with ``FINISH``. When unsure, lean on enabled tools rather than guessing — never fabricate precise values, external facts, or citations.
- 2. In a ``TOOL`` reply, multiple complementary tools may run in the same iteration. In a ``THINK`` reply, write your reasoning only — no tools. In a ``FINISH`` reply, deliver the answer and stop.
- 3. Once enough material is gathered, close with ``FINISH``.
+ 2. In a ``TOOL`` reply, multiple complementary tools may run in the same iteration. In a ``THINK`` or ``PAUSE`` reply, write reasoning only — no tools. In a ``FINISH`` reply, deliver the answer and stop.
+ 3. After any tool result (including a tool result that starts with "User answered:"), continue working on the user's original request. Once enough material is gathered, close with a substantive ``FINISH``.
Hard rules for tool calls:
- Tool names, parameter names, source ids, and KB names must be copied verbatim from the "Enabled tools" and "Knowledge bases / sources" blocks below. Never invent.
@@ -97,6 +106,34 @@ answer_now:
user: |-
Stop using tools and produce the user-facing answer now based on what you have already produced and any tool evidence you've gathered. Do not mention internal stages or planning. If something is still uncertain, say so briefly while giving the most useful answer you can.
+protocol:
+ missing_label: |-
+ Protocol correction: your previous reply did not begin with a protocol label, so the turn is not complete. Your next reply must choose exactly one action label, written once on the first line only: ``FINISH``, ``TOOL``, ``THINK``, or ``PAUSE``. Do not include a second protocol label anywhere in the body. If the draft was the final answer, use ``FINISH``. If tools are needed, use ``TOOL`` and emit real tool_calls in that same reply. If this is private intermediate reasoning the user doesn't need to see, use ``THINK`` and do not call tools. If your reasoning is worth showing to the user, use ``PAUSE`` (same as ``THINK`` plus visibility) and do not call tools.
+ multiple_labels: |-
+ Protocol correction: your previous reply contained multiple protocol labels, so the turn is not complete. Your next reply must choose exactly one action label, written once on the first line only: ``FINISH``, ``TOOL``, ``THINK``, or ``PAUSE``. Do not include a second protocol label anywhere in the body.
+ tool_without_calls: |-
+ Protocol correction: you chose ``TOOL`` but emitted no real tool_calls. Your next reply must choose exactly one action label. Use ``TOOL`` only if you emit native tool_calls in that same reply; otherwise use ``THINK``, ``PAUSE``, or ``FINISH``.
+ think_with_tools: |-
+ Protocol correction: you chose ``THINK`` while also emitting tool_calls. Your next reply must choose exactly one action label. Use ``THINK`` with no tools, or use ``TOOL`` with native tool_calls.
+ finish_with_tools: |-
+ Protocol correction: you chose ``FINISH`` while also emitting tool_calls. Your next reply must choose exactly one action label. Use ``FINISH`` with no tools, or use ``TOOL`` with native tool_calls.
+ pause_with_tools: |-
+ Protocol correction: you chose ``PAUSE`` while also emitting tool_calls. ``PAUSE`` is just ``THINK`` made visible to the user — reasoning only, no tools. Your next reply must choose exactly one action label. Use ``PAUSE`` with no tools (call tools in the following iteration if needed), or switch to ``TOOL`` and emit native tool_calls now.
+ force_finish: |-
+ The iteration budget is exhausted. You must now produce the user-facing final answer: the first line must be ``FINISH``. Do not call tools and do not use ``THINK`` or ``PAUSE``. If information is still incomplete, state the uncertainty briefly while giving the most useful answer possible.
+ force_finish_repair: |-
+ Finalization protocol correction: the previous reply did not produce a valid ``FINISH``. Now output only a final answer: first line ``FINISH``, then the user-facing answer. Do not write ``THINK``, ``PAUSE``, or ``TOOL``, do not call tools, and do not include another protocol label in the body.
+ fallback_final: |-
+ I reached the iteration limit, but the model did not produce a valid ``FINISH`` response. Please retry or narrow the request; I can continue from the existing context.
+
+# ---------------------------------------------------------------------------
+# Per-iteration system reminder
+# ---------------------------------------------------------------------------
+# Injected as a ``role=user`` message right before each LLM call so the
+# model can pace itself across the turn. ``{current}`` is 1-indexed.
+iteration_marker: |-
+ [System note] You are at iteration {current}/{max} of this turn. Once {max} is reached, the next reply is forced to be ``FINISH``.
+
# ---------------------------------------------------------------------------
# Progress notices and short copy
# ---------------------------------------------------------------------------
@@ -109,6 +146,8 @@ notices:
empty_tool_result: "The tool completed without returning text output."
images_stripped: "The current model `{model}` does not support image input, so image attachments were ignored."
max_iterations_reached: "Reached the maximum number of tool iterations for this turn. Producing the best answer I can with what I have."
+ protocol_retry: "The model violated the action-label protocol; retrying this iteration."
+ final_protocol_failed: "The model still did not produce a valid FINISH reply after the finalization prompt."
context_window_guard: "Trimmed older tool results to keep this turn within the model's context window."
# ---------------------------------------------------------------------------
diff --git a/deeptutor/agents/chat/prompts/zh/agentic_chat.yaml b/deeptutor/agents/chat/prompts/zh/agentic_chat.yaml
index b9e53105c..a97c508a7 100644
--- a/deeptutor/agents/chat/prompts/zh/agentic_chat.yaml
+++ b/deeptutor/agents/chat/prompts/zh/agentic_chat.yaml
@@ -29,27 +29,33 @@ system: |-
# 输出协议(强制,每一轮回复都必须遵守)
- 你的回复**必须以下面三个标签之一作为最开头**,整体顶格写、独占一行、全大写、左右各用两个反引号包裹:
+ 你的回复**必须以下面四个标签之一作为最开头**,整体顶格写、独占一行、全大写、左右各用两个反引号包裹:
- ``FINISH`` → 本轮就是面向用户的最终回答,不调用任何工具,标签后面的全部内容就是答案正文。
+ ``FINISH`` → 本轮就是面向用户的最终回答,不调用任何工具,标签后面的全部内容就是答案正文,本轮到此结束。
``TOOL`` → 本轮要调用工具。标签后可以用一句话简述要做什么,然后通过原生 tool_calls 发起工具调用。
- ``THINK`` → 本轮是中间推理,**不调用工具,但也不是最终答案**——你只是在边想边写、为下一轮做准备。下一轮你会继续基于这一轮的思路推进,最终会以 ``FINISH`` 收尾。
+ ``THINK`` → 本轮是中间推理,**不调用工具,但也不是最终答案**——你只是在边想边写、为下一轮做准备。这段文字是你的私有草稿,**用户看不到**。下一轮你会继续基于这一轮的思路推进,最终会以 ``FINISH`` 收尾。
+ ``PAUSE`` → 和 ``THINK`` 完全一样(中间推理、不调工具、也不是最终答案),区别只是这段文字**用户能看到**。只有当你本来就准备用 ``THINK`` 思考、并且这段思考让用户看到比藏着更有价值时,才使用 ``PAUSE``。
- 你自己根据当前问题难度、已有信息和工具情况自主选择三者之一:
+ runtime 只把 ``FINISH`` 当作终止信号。``THINK``、``TOOL``、``PAUSE``、工具结果、通过工具拿到的用户回复,以及没有标签的文本,都不是本轮结束。
+ 一次 LLM 回复只能选择**一个**动作标签。第一行之后,正文里不要再写任何协议标签。``THINK``、``FINISH`` 和 ``PAUSE`` 都不能同时发起 tool_calls;``TOOL`` 必须在同一次回复里发起真实原生 tool_calls。
+
+ 你自己根据当前问题难度、已有信息和工具情况选择:
- 简单问题、信息已足 → 直接 ``FINISH``。
- 需要外部信息 / 计算 / 检索 → ``TOOL``。
- 问题很复杂、需要把推理拆成多步先想清楚再回答 → ``THINK``(最多迭代几轮,每轮一个 ``THINK``,最后一定要 ``FINISH``)。
+ - 本来就要用 ``THINK``、并且这段思考让用户看到对他真的有帮助 → ``PAUSE``。
绝对不要:
- 在标签前面加任何字符(空格、引号、换行除外)。
- 用单反引号、方括号或别的格式代替双反引号包裹。
- - 在同一轮里输出多个标签。
+ - 在同一轮里输出多个标签,例如先思考又在同一条消息里写 ``TOOL`` 或 ``FINISH``。
+ - 每一轮思考都用 ``PAUSE``——默认用 ``THINK``,只有当这段思考让用户看到真的对用户有帮助时,才换成 ``PAUSE``。
# 每一轮的处理思路
1. 仔细读用户的问题。判断现有信息是否已足以给出可靠回答;不确定时倾向使用已启用工具,不要凭脑补给精确数值或外部事实。
- 2. ``TOOL`` 轮里可以并行调用多个互补工具;``THINK`` 轮里不调工具,而是深入的思考可以用的思路;``FINISH`` 轮里给最终答案、不再调工具。
- 3. 一旦素材足够,用 ``FINISH`` 结尾。
+ 2. ``TOOL`` 轮里可以并行调用多个互补工具;``THINK`` 和 ``PAUSE`` 轮里都只写推理、不调工具;``FINISH`` 轮里给最终答案、不再调工具。
+ 3. 看到任何工具结果后(包括以 "User answered:" 开头的工具结果),都要继续处理用户最初的请求;一旦素材足够,用有实质内容的 ``FINISH`` 结尾。
调用工具时的硬规则:
- 工具名、参数名、source id、知识库名只能从下方"启用工具"和"知识库 / 来源"中复制,不要凭空发明。
@@ -79,6 +85,34 @@ answer_now:
user: |-
请基于你已经产出的内容和已收集到的工具证据,立刻给出面向用户的最终答复,不要再调工具。不要提到内部阶段或规划。如果仍有不确定,请简短说明,但仍然给出当前最有用的回答。
+protocol:
+ missing_label: |-
+ 协议修正:你上一轮回复没有以协议标签开头,所以本轮还不能结束。下一次回复必须只选择一个动作标签,并且只在第一行写一次:``FINISH``、``TOOL``、``THINK`` 或 ``PAUSE``。标签正文里不要再出现第二个协议标签。如果内容本来就是最终答案,用 ``FINISH``;如果需要工具,用 ``TOOL`` 并在同一次回复里发起真实 tool_calls;如果只是中间思考、用户不需要看到,用 ``THINK`` 且不要调用工具;如果这段思考让用户看到比藏着更有价值,用 ``PAUSE``(等于可见的 ``THINK``)且不要调用工具。
+ multiple_labels: |-
+ 协议修正:你上一轮回复在同一次输出里出现了多个协议标签,所以本轮还不能结束。下一次回复必须只选择一个动作标签,并且只在第一行写一次:``FINISH``、``TOOL``、``THINK`` 或 ``PAUSE``。正文里不要再出现第二个协议标签。
+ tool_without_calls: |-
+ 协议修正:你上一轮选择了 ``TOOL``,但没有发起真实 tool_calls。下一次回复必须只选择一个动作标签;只有会在同一次回复里发起原生 tool_calls 时才用 ``TOOL``,否则用 ``THINK``、``PAUSE`` 或 ``FINISH``。
+ think_with_tools: |-
+ 协议修正:你上一轮选择了 ``THINK``,但同时发起了工具调用。下一次回复必须只选择一个动作标签;``THINK`` 不调用工具,或改用 ``TOOL`` 并发起原生 tool_calls。
+ finish_with_tools: |-
+ 协议修正:你上一轮选择了 ``FINISH``,但同时发起了工具调用。下一次回复必须只选择一个动作标签;``FINISH`` 不调用工具,或改用 ``TOOL`` 并发起原生 tool_calls。
+ pause_with_tools: |-
+ 协议修正:你上一轮选择了 ``PAUSE``,但同时发起了工具调用。``PAUSE`` 等同于带可见性的 ``THINK``——只写推理、不调任何工具。下一次回复必须只选择一个动作标签:要么用 ``PAUSE`` 但不调任何工具(需要工具就放到下一轮再用 ``TOOL``),要么直接改用 ``TOOL`` 并发起原生 tool_calls。
+ force_finish: |-
+ 迭代预算已用完。现在必须给出面向用户的最终答复:第一行必须是 ``FINISH``,不要再调用工具,也不要再用 ``THINK`` 或 ``PAUSE``。如果信息仍不完整,请简短说明不确定性,但仍给出当前最有用的答案。
+ force_finish_repair: |-
+ 最终化协议修正:上一轮没有产出合格的 ``FINISH``。现在只能输出一个最终答案:第一行写 ``FINISH``,后面直接给用户答案。不要写 ``THINK``、``PAUSE``,不要写 ``TOOL``,不要调用任何工具,也不要在正文里再次出现协议标签。
+ fallback_final: |-
+ 我已经达到本轮迭代上限,但模型没有按 ``FINISH`` 协议产出合格的最终回答。请重试一次,或把问题范围收窄;我会从已有上下文继续。
+
+# ---------------------------------------------------------------------------
+# 每轮系统提示
+# ---------------------------------------------------------------------------
+# 每次调用 LLM 之前以 ``role=user`` 的形式注入,告诉模型当前在第几轮,
+# 便于自己掌控节奏。{current} 从 1 开始计数。
+iteration_marker: |-
+ [系统提示] 当前是本轮第 {current}/{max} 次推理。到达 {max} 后下一轮会被强制要求以 ``FINISH`` 收尾。
+
# ---------------------------------------------------------------------------
# 进度提示与短文案
# ---------------------------------------------------------------------------
@@ -91,6 +125,8 @@ notices:
empty_tool_result: "工具执行完成,但没有返回文本内容。"
images_stripped: "当前模型 `{model}` 不支持图像输入,本轮图片附件已被忽略。"
max_iterations_reached: "已达到本轮工具迭代上限,将基于当前材料给出最佳回答。"
+ protocol_retry: "模型违反了动作标签协议,正在重试本次迭代。"
+ final_protocol_failed: "最终化提示后,模型仍未产出合格的 FINISH 回复。"
context_window_guard: "已裁剪较旧的工具结果,以确保本轮在模型上下文窗口内。"
# ---------------------------------------------------------------------------
diff --git a/deeptutor/core/stream.py b/deeptutor/core/stream.py
index 6569b49a0..dfd1d59ce 100644
--- a/deeptutor/core/stream.py
+++ b/deeptutor/core/stream.py
@@ -29,6 +29,7 @@ class StreamEventType(str, Enum):
RESULT = "result"
ERROR = "error"
SESSION = "session"
+ SESSION_META = "session_meta"
DONE = "done"
diff --git a/deeptutor/core/tool_protocol.py b/deeptutor/core/tool_protocol.py
index 16f618ffe..612b28239 100644
--- a/deeptutor/core/tool_protocol.py
+++ b/deeptutor/core/tool_protocol.py
@@ -15,7 +15,16 @@ from typing import Any, Protocol
@dataclass
class ToolParameter:
- """One parameter in a tool's function-calling schema."""
+ """One parameter in a tool's function-calling schema.
+
+ Attributes:
+ items: Inner JSON Schema for ``type="array"`` parameters. **Required
+ by strict providers (Gemini, Anthropic)** even though OpenAI
+ silently tolerates its absence — leaving it out causes a 400
+ on Gemini. When ``type="array"`` and ``items`` is None we fall
+ back to ``{"type": "string"}`` so callers that just declare
+ ``ToolParameter(type="array")`` still emit a valid schema.
+ """
name: str
type: str # "string" | "integer" | "boolean" | "number" | "array" | "object"
@@ -23,12 +32,15 @@ class ToolParameter:
required: bool = True
default: Any = None
enum: list[str] | None = None
+ items: dict[str, Any] | None = None
def to_schema(self) -> dict[str, Any]:
"""Convert to JSON Schema property dict."""
schema: dict[str, Any] = {"type": self.type, "description": self.description}
if self.enum:
schema["enum"] = self.enum
+ if self.type == "array":
+ schema["items"] = self.items if self.items is not None else {"type": "string"}
return schema
@@ -90,12 +102,37 @@ class ToolPromptHints:
@dataclass
class ToolResult:
- """Standardised return value from a tool execution."""
+ """Standardised return value from a tool execution.
+
+ Attributes:
+ content: Text returned to the LLM as the ``role=tool`` message body.
+ sources: Citation rows surfaced through ``stream.sources``.
+ metadata: Free-form payload — also used by the chat pipeline as a
+ channel for structured UI hints (e.g. ``ask_user.options``
+ for chip rendering).
+ success: ``False`` marks an explicit failure path; the LLM is
+ still allowed to read ``content`` (often an error message).
+ terminate_turn: When ``True`` the agentic chat loop must stop
+ iterating after dispatching this tool, treating the tool's
+ output as the assistant's final turn artefact. Reserved for
+ tools that genuinely end the turn (no future planned use —
+ ``ask_user`` now uses ``pause_for_user`` instead).
+ pause_for_user: When set, the chat loop **pauses** after this
+ tool call, emits a ``pending_user_input`` event with this
+ payload, awaits the user's reply via the runtime's reply
+ queue, then resumes the same loop iteration with the
+ reply substituted into the tool message body. Used by
+ ``ask_user`` to keep the turn alive across the user's
+ answer instead of ending and starting a new turn.
+ Shape mirrors ``AskUserPayload.to_dict()``.
+ """
content: str = ""
sources: list[dict[str, Any]] = field(default_factory=list)
metadata: dict[str, Any] = field(default_factory=dict)
success: bool = True
+ terminate_turn: bool = False
+ pause_for_user: dict[str, Any] | None = None
def __str__(self) -> str:
return self.content
diff --git a/deeptutor/tools/ask_user.py b/deeptutor/tools/ask_user.py
new file mode 100644
index 000000000..b1e2bd005
--- /dev/null
+++ b/deeptutor/tools/ask_user.py
@@ -0,0 +1,208 @@
+"""Build the payload for the ``ask_user`` tool.
+
+The tool packages one-to-three structured questions into a payload that
+the chat pipeline interprets as a "pause this same turn until the user
+answers" signal (``ToolResult.pause_for_user``). The frontend reads the
+same payload off ``tool_result.metadata.ask_user`` and renders a card
+that lets the user move between questions and submit answers in one
+batch.
+
+The schema is intentionally a list-of-questions even for the common
+single-question case — every call wraps a list so the frontend has one
+code path. The legacy ``{question, options}`` argument shape is still
+accepted at the LLM-facing boundary (``build_ask_user_payload``) and is
+normalised to a single-element list internally.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Any
+
+MAX_QUESTIONS = 3
+MAX_OPTIONS = 8
+MAX_OPTION_CHARS = 120
+MAX_QUESTION_CHARS = 800
+MAX_INTRO_CHARS = 400
+MAX_PLACEHOLDER_CHARS = 120
+
+
+@dataclass(frozen=True)
+class AskUserQuestion:
+ """A single question rendered as one tab on the ask_user card."""
+
+ id: str
+ prompt: str
+ options: tuple[str, ...] = ()
+ allow_free_text: bool = True
+ placeholder: str | None = None
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "id": self.id,
+ "prompt": self.prompt,
+ "options": list(self.options),
+ "allow_free_text": self.allow_free_text,
+ "placeholder": self.placeholder,
+ }
+
+
+@dataclass(frozen=True)
+class AskUserPayload:
+ """Structured payload that travels alongside the tool result.
+
+ Mirrored on the frontend by ``AskUserOptions.tsx`` which reads the
+ same field names off ``tool_result.metadata.ask_user``.
+ """
+
+ questions: tuple[AskUserQuestion, ...]
+ intro: str | None = None
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "intro": self.intro,
+ "questions": [q.to_dict() for q in self.questions],
+ }
+
+ @property
+ def question_ids(self) -> tuple[str, ...]:
+ return tuple(q.id for q in self.questions)
+
+
+def build_ask_user_payload(
+ *,
+ questions: Any = None,
+ intro: Any = None,
+ # Legacy single-question shape — auto-normalised into ``questions``.
+ question: Any = None,
+ options: Any = None,
+) -> tuple[AskUserPayload | None, str | None]:
+ """Validate + normalise the LLM-provided arguments.
+
+ Accepts either the v2 ``{questions: [...], intro?}`` shape or the
+ legacy ``{question, options?}`` shape (which is wrapped into a
+ one-element list). Returns ``(payload, None)`` on success, or
+ ``(None, error_message)`` if arguments cannot be honoured — errors
+ propagate back to the LLM as a tool failure rather than raising.
+ """
+ raw_questions = _coerce_questions(questions, question, options)
+ if isinstance(raw_questions, str):
+ return None, raw_questions
+ if not raw_questions:
+ return None, "`questions` must contain at least one question."
+ if len(raw_questions) > MAX_QUESTIONS:
+ raw_questions = raw_questions[:MAX_QUESTIONS]
+
+ normalised: list[AskUserQuestion] = []
+ used_ids: set[str] = set()
+ for idx, raw in enumerate(raw_questions):
+ q_or_err = _build_question(raw, idx, used_ids)
+ if isinstance(q_or_err, str):
+ return None, q_or_err
+ normalised.append(q_or_err)
+ used_ids.add(q_or_err.id)
+
+ intro_text: str | None = None
+ if intro is not None:
+ intro_text = _coerce_string(intro).strip() or None
+ if intro_text and len(intro_text) > MAX_INTRO_CHARS:
+ intro_text = intro_text[:MAX_INTRO_CHARS].rstrip() + "…"
+
+ return AskUserPayload(questions=tuple(normalised), intro=intro_text), None
+
+
+def _coerce_questions(questions: Any, question: Any, options: Any) -> list[Any] | str:
+ if questions is not None:
+ if not isinstance(questions, (list, tuple)):
+ return "`questions` must be an array."
+ return list(questions)
+ if question is not None:
+ # Legacy single-question shape.
+ return [{"prompt": question, "options": options}]
+ return []
+
+
+def _build_question(
+ raw: Any, idx: int, used_ids: set[str]
+) -> AskUserQuestion | str:
+ if not isinstance(raw, dict):
+ return f"Question #{idx + 1} must be an object."
+
+ # ``prompt`` is the canonical field; accept ``question`` as alias
+ # for forgiveness toward older LLM prompts.
+ prompt_raw = raw.get("prompt")
+ if prompt_raw is None:
+ prompt_raw = raw.get("question")
+ prompt = _coerce_string(prompt_raw).strip()
+ if not prompt:
+ return f"Question #{idx + 1}: `prompt` must be a non-empty string."
+ if len(prompt) > MAX_QUESTION_CHARS:
+ prompt = prompt[:MAX_QUESTION_CHARS].rstrip() + "…"
+
+ options_raw = raw.get("options")
+ options: tuple[str, ...] = ()
+ if options_raw is not None:
+ if not isinstance(options_raw, (list, tuple)):
+ return f"Question #{idx + 1}: `options` must be an array of strings."
+ cleaned: list[str] = []
+ for opt in options_raw:
+ text = _coerce_string(opt).strip()
+ if not text:
+ continue
+ if len(text) > MAX_OPTION_CHARS:
+ text = text[:MAX_OPTION_CHARS].rstrip() + "…"
+ if text in cleaned:
+ continue
+ cleaned.append(text)
+ if len(cleaned) >= MAX_OPTIONS:
+ break
+ options = tuple(cleaned)
+
+ allow_free_text = raw.get("allow_free_text")
+ allow_free_text = True if allow_free_text is None else bool(allow_free_text)
+
+ placeholder_raw = raw.get("placeholder")
+ placeholder: str | None = None
+ if placeholder_raw is not None:
+ placeholder = _coerce_string(placeholder_raw).strip() or None
+ if placeholder and len(placeholder) > MAX_PLACEHOLDER_CHARS:
+ placeholder = placeholder[:MAX_PLACEHOLDER_CHARS].rstrip() + "…"
+
+ qid = _coerce_string(raw.get("id")).strip()
+ if not qid:
+ qid = f"q{idx + 1}"
+ # Disambiguate duplicate ids deterministically rather than rejecting.
+ if qid in used_ids:
+ suffix = 2
+ while f"{qid}_{suffix}" in used_ids:
+ suffix += 1
+ qid = f"{qid}_{suffix}"
+
+ return AskUserQuestion(
+ id=qid,
+ prompt=prompt,
+ options=options,
+ allow_free_text=allow_free_text,
+ placeholder=placeholder,
+ )
+
+
+def _coerce_string(value: Any) -> str:
+ if value is None:
+ return ""
+ if isinstance(value, str):
+ return value
+ return str(value)
+
+
+__all__ = [
+ "AskUserPayload",
+ "AskUserQuestion",
+ "MAX_INTRO_CHARS",
+ "MAX_OPTION_CHARS",
+ "MAX_OPTIONS",
+ "MAX_PLACEHOLDER_CHARS",
+ "MAX_QUESTION_CHARS",
+ "MAX_QUESTIONS",
+ "build_ask_user_payload",
+]
diff --git a/deeptutor/tools/builtin/__init__.py b/deeptutor/tools/builtin/__init__.py
index 33656a176..d00006d74 100644
--- a/deeptutor/tools/builtin/__init__.py
+++ b/deeptutor/tools/builtin/__init__.py
@@ -414,14 +414,6 @@ class GeoGebraAnalysisTool(_PromptHintsMixin, BaseTool):
required=False,
default="",
),
- ToolParameter(
- name="language",
- type="string",
- description="Output language: 'zh' or 'en'.",
- required=False,
- default="zh",
- enum=["zh", "en"],
- ),
],
)
@@ -431,7 +423,9 @@ class GeoGebraAnalysisTool(_PromptHintsMixin, BaseTool):
question = kwargs.get("question", "")
image_base64 = kwargs.get("image_base64", "")
- language = kwargs.get("language", "zh")
+ # language is server-injected from the user's session setting by the
+ # chat pipeline; never accept an LLM-provided override.
+ language = kwargs.get("language") or "zh"
if not image_base64:
return ToolResult(
@@ -439,6 +433,13 @@ class GeoGebraAnalysisTool(_PromptHintsMixin, BaseTool):
success=False,
)
+ # VisionSolverAgent expects a fully-qualified ``data:image/<fmt>;base64,…``
+ # URI for the OpenAI image_url shape. The chat pipeline injects this
+ # form already, but defensively normalize for any other caller (or a
+ # hallucinated kwarg) so we don't silently fall through 4 empty stages.
+ if not image_base64.startswith("data:"):
+ image_base64 = f"data:image/png;base64,{image_base64}"
+
llm_config = get_llm_config()
agent = VisionSolverAgent(
api_key=llm_config.api_key,
@@ -547,9 +548,7 @@ class ReadSourceTool(_PromptHintsMixin, BaseTool):
source_index = kwargs.get("source_index")
if not isinstance(source_index, dict) or not source_index:
return ToolResult(
- content=(
- "Error: no attached sources are available for this turn."
- ),
+ content=("Error: no attached sources are available for this turn."),
success=False,
)
full_text = source_index.get(source_id)
@@ -568,6 +567,545 @@ class ReadSourceTool(_PromptHintsMixin, BaseTool):
)
+class ReadMemoryTool(_PromptHintsMixin, BaseTool):
+ """Read the current user's L3 cross-surface Memory.
+
+ Returns the concatenation of the four L3 markdown documents
+ (recent / profile / scope / preferences). Multi-user-safe: paths
+ resolve to the active user via the runtime's ContextVars.
+ """
+
+ def get_definition(self) -> ToolDefinition:
+ return ToolDefinition(
+ name="read_memory",
+ description=(
+ "Read the user's persistent memory: recent learning summary, "
+ "user profile, knowledge scope, and explicit preferences. "
+ "Use to personalise tone, depth, and examples — not on "
+ "every turn, not for purely factual questions."
+ ),
+ parameters=[],
+ )
+
+ async def execute(self, **kwargs: Any) -> ToolResult:
+ from deeptutor.services.memory import get_memory_store
+
+ text = get_memory_store().read_l3_concat()
+ return ToolResult(
+ content=text,
+ metadata={"char_count": len(text)},
+ )
+
+
+class WriteMemoryTool(_PromptHintsMixin, BaseTool):
+ """Persist an explicit user preference into the L3 ``preferences.md``.
+
+ The only chat-mode write into memory. Other memory docs are updated
+ through the Memory workbench by the user manually. This tool is for
+ moments when the user *explicitly* states a preference — speak it
+ back to them only if natural, then call this with the substance.
+ """
+
+ def get_definition(self) -> ToolDefinition:
+ return ToolDefinition(
+ name="write_memory",
+ description=(
+ "Save an explicit user preference (writing style, language "
+ "choice, depth, format) to long-term memory. Call ONLY when "
+ "the user clearly states a preference — never speculate."
+ ),
+ parameters=[
+ ToolParameter(
+ name="op",
+ type="string",
+ description="`add` for a new preference, `edit` to revise an existing one.",
+ enum=["add", "edit"],
+ required=True,
+ ),
+ ToolParameter(
+ name="text",
+ type="string",
+ description="The preference, in the user's own words where possible. ≤ 240 chars.",
+ required=True,
+ ),
+ ToolParameter(
+ name="target_id",
+ type="string",
+ description="Existing entry id (form `m_xxx`). Required for `edit`.",
+ required=False,
+ ),
+ ToolParameter(
+ name="reason",
+ type="string",
+ description="Optional one-line note shown in the Memory workbench.",
+ required=False,
+ ),
+ ],
+ )
+
+ async def execute(self, **kwargs: Any) -> ToolResult:
+ from deeptutor.services.memory import get_memory_store
+ from deeptutor.services.memory.trace import TraceEvent
+
+ op = str(kwargs.get("op") or "").strip().lower()
+ text = str(kwargs.get("text") or "").strip()
+ target_id = kwargs.get("target_id")
+ reason = kwargs.get("reason")
+
+ if op not in {"add", "edit"}:
+ return ToolResult(
+ content=f"Error: op must be 'add' or 'edit', got {op!r}.", success=False
+ )
+ if not text:
+ return ToolResult(
+ content="Error: text is required and must be non-empty.", success=False
+ )
+
+ store = get_memory_store()
+ # Emit an L1 trace so the preference's footnote points at a real event.
+ event = TraceEvent.new(
+ "chat",
+ "preference_stated",
+ {"op": op, "text": text, "target_id": target_id, "reason": reason},
+ )
+ await store.emit(event)
+
+ report = await store.write_preference(
+ op=op, # type: ignore[arg-type]
+ text=text,
+ target_id=str(target_id).strip() if target_id else None,
+ reason=str(reason).strip() if reason else None,
+ trace_id=event.id,
+ )
+ if not report.accepted:
+ return ToolResult(
+ content=f"write_memory rejected: {report.reason}",
+ success=False,
+ metadata={"op": op},
+ )
+ entry_id = report.results[0].entry_id if report.results else None
+ return ToolResult(
+ content=f"preference {op}ed (entry={entry_id or target_id}).",
+ metadata={"op": op, "entry_id": entry_id or target_id},
+ )
+
+
+class WebFetchTool(_PromptHintsMixin, BaseTool):
+ """Fetch a specific URL and return readable markdown.
+
+ The actual fetch / extract / safety logic lives in
+ ``deeptutor.tools.web_fetch`` so this wrapper stays free of network
+ code — easier to unit-test the BaseTool boilerplate without spinning
+ up an httpx mock.
+ """
+
+ def get_definition(self) -> ToolDefinition:
+ return ToolDefinition(
+ name="web_fetch",
+ description=(
+ "Fetch a specific URL and extract readable content as "
+ "markdown. Use this when the user shares a specific link; "
+ "use `web_search` for general topic searches."
+ ),
+ parameters=[
+ ToolParameter(
+ name="url",
+ type="string",
+ description="Full http:// or https:// URL.",
+ ),
+ ToolParameter(
+ name="max_chars",
+ type="integer",
+ description="Cap on the extracted text length; defaults to 50000.",
+ required=False,
+ ),
+ ],
+ )
+
+ async def execute(self, **kwargs: Any) -> ToolResult:
+ from deeptutor.tools.web_fetch import (
+ DEFAULT_MAX_CHARS,
+ fetch_url_as_markdown,
+ )
+
+ url = str(kwargs.get("url") or "").strip()
+ if not url:
+ return ToolResult(content="Error: url is required.", success=False)
+ try:
+ max_chars = int(kwargs.get("max_chars") or DEFAULT_MAX_CHARS)
+ except (TypeError, ValueError):
+ max_chars = DEFAULT_MAX_CHARS
+ outcome = await fetch_url_as_markdown(url, max_chars=max_chars)
+ if not outcome.ok:
+ return ToolResult(
+ content=outcome.error or "Fetch failed.",
+ success=False,
+ metadata={"url": url},
+ )
+ return ToolResult(
+ content=outcome.markdown,
+ sources=[{"type": "web", "url": outcome.url, "title": outcome.title}],
+ metadata={
+ "url": outcome.url,
+ "title": outcome.title,
+ "char_count": len(outcome.markdown),
+ "truncated": outcome.truncated,
+ },
+ )
+
+
+class ListNotebookTool(_PromptHintsMixin, BaseTool):
+ """List the user's notebooks, or list the records inside one notebook.
+
+ Two-mode discovery tool. Auto-mounted by the chat pipeline iff the
+ user has at least one notebook. The tool itself is stateless; the
+ chat pipeline supplies no extra context — list calls go straight
+ against the per-user notebook manager.
+ """
+
+ def get_definition(self) -> ToolDefinition:
+ return ToolDefinition(
+ name="list_notebook",
+ description=(
+ "Discover the user's notebooks and the records inside "
+ "them. Call with no arguments to list every notebook "
+ "the user owns (id + name + record count). Call with a "
+ "specific `notebook_id` to drill in and list its "
+ "records (record_id + title + summary + timestamp). "
+ "Use this BEFORE `write_note` in edit mode so you have "
+ "valid record ids."
+ ),
+ parameters=[
+ ToolParameter(
+ name="notebook_id",
+ type="string",
+ description=(
+ "Optional. When omitted, returns the notebook "
+ "index. When supplied, returns the records in "
+ "that notebook. Must be a valid id from the "
+ "notebook index — do not invent ids."
+ ),
+ required=False,
+ ),
+ ],
+ )
+
+ async def execute(self, **kwargs: Any) -> ToolResult:
+ from deeptutor.tools.list_notebook import list_notebooks_or_records
+
+ outcome = list_notebooks_or_records(
+ notebook_id=str(kwargs.get("notebook_id") or ""),
+ )
+ if not outcome.ok:
+ return ToolResult(content=outcome.error, success=False)
+ return ToolResult(
+ content=outcome.text,
+ metadata=outcome.summary or {},
+ )
+
+
+class WriteNoteTool(_PromptHintsMixin, BaseTool):
+ """Create OR edit a notebook record from the chat agent.
+
+ Two modes mirror what a human sees in the notebook UI:
+
+ * ``append`` — create a new record in a notebook (the model picks
+ a title; the body defaults to the actual chat transcript built
+ from injected conversation history, or to an agent-authored
+ markdown body if ``content`` is explicitly provided).
+ * ``edit`` — patch an existing record's title / body / summary.
+ Requires a known ``record_id`` (obtained via ``list_notebook``).
+
+ Auto-mounted only when the user has at least one notebook. The
+ pipeline injects ``conversation_history`` + ``current_user_message``
+ so the model never has to fabricate the saved chat.
+ """
+
+ def get_definition(self) -> ToolDefinition:
+ return ToolDefinition(
+ name="write_note",
+ description=(
+ "Save or edit a notebook record. mode='append' creates "
+ "a NEW record (default body = the actual recent chat "
+ "transcript built by the tool; pass `content` instead "
+ "to save an agent-authored markdown body). "
+ "mode='edit' patches an existing record's title / body "
+ "/ summary — `record_id` is required (call `list_notebook` "
+ "first to discover valid ids)."
+ ),
+ parameters=[
+ ToolParameter(
+ name="mode",
+ type="string",
+ description="'append' (new record) or 'edit' (patch existing).",
+ enum=["append", "edit"],
+ ),
+ ToolParameter(
+ name="notebook_id",
+ type="string",
+ description=(
+ "Id of the target notebook from the schema enum (do not invent ids)."
+ ),
+ ),
+ ToolParameter(
+ name="record_id",
+ type="string",
+ description=("Required for mode='edit'. Discover with `list_notebook` first."),
+ required=False,
+ ),
+ ToolParameter(
+ name="title",
+ type="string",
+ description=(
+ "For append: required, short descriptive title. "
+ "For edit: optional new title (leave empty to "
+ "keep the existing one)."
+ ),
+ required=False,
+ ),
+ ToolParameter(
+ name="content",
+ type="string",
+ description=(
+ "For append: optional agent-authored markdown body "
+ "(when omitted the tool inserts the real Q&A "
+ "transcript itself, the recommended default). "
+ "For edit: replacement body (leave empty to keep "
+ "the existing body)."
+ ),
+ required=False,
+ ),
+ ToolParameter(
+ name="turns_to_include",
+ type="string",
+ description=(
+ "Append mode only. Number of recent user+assistant "
+ "turns to render into the transcript body. Pass an "
+ "integer as a string (e.g. '3') or 'all' to include "
+ "every turn currently in scope. Ignored when "
+ "`content` is provided. Default '3'."
+ ),
+ required=False,
+ ),
+ ToolParameter(
+ name="note",
+ type="string",
+ description=(
+ "Optional one-paragraph commentary. In append "
+ "mode it's prepended above the transcript; in "
+ "edit mode it replaces the record's summary."
+ ),
+ required=False,
+ ),
+ ],
+ )
+
+ async def execute(self, **kwargs: Any) -> ToolResult:
+ from deeptutor.tools.write_note import write_note
+
+ outcome = write_note(
+ mode=str(kwargs.get("mode") or ""),
+ notebook_id=str(kwargs.get("notebook_id") or ""),
+ record_id=str(kwargs.get("record_id") or ""),
+ title=str(kwargs.get("title") or ""),
+ content=str(kwargs.get("content") or ""),
+ turns_to_include=kwargs.get("turns_to_include") or 3,
+ note=str(kwargs.get("note") or ""),
+ conversation_history=kwargs.get("conversation_history") or [],
+ current_user_message=str(kwargs.get("current_user_message") or ""),
+ )
+ if not outcome.ok:
+ return ToolResult(content=outcome.error, success=False)
+ action = "Saved new record" if outcome.mode == "append" else "Updated record"
+ return ToolResult(
+ content=(
+ f"{action} in notebook {outcome.notebook_name!r} (record id: {outcome.record_id})."
+ ),
+ metadata={
+ "mode": outcome.mode,
+ "record_id": outcome.record_id,
+ "notebook_id": outcome.notebook_id,
+ "notebook_name": outcome.notebook_name,
+ },
+ )
+
+
+class GithubTool(_PromptHintsMixin, BaseTool):
+ """Read-only GitHub queries via `gh`. Always auto-mounted; the
+ underlying call gracefully reports "gh unavailable" when the CLI
+ isn't installed on the server."""
+
+ _ALLOWED_QUERY_TYPES = ("pr", "issue", "run", "repo", "api")
+
+ def get_definition(self) -> ToolDefinition:
+ return ToolDefinition(
+ name="github",
+ description=(
+ "Read-only queries against GitHub PRs / issues / repos / "
+ "CI runs via the gh CLI. This tool cannot write — no "
+ "comments, no closes, no merges."
+ ),
+ parameters=[
+ ToolParameter(
+ name="query_type",
+ type="string",
+ description=("One of 'pr', 'issue', 'run', 'repo', 'api'."),
+ enum=list(_ALLOWED_QUERY_TYPES := ("pr", "issue", "run", "repo", "api")),
+ ),
+ ToolParameter(
+ name="target",
+ type="string",
+ description=(
+ "owner/repo[#number] or full URL for pr/issue; "
+ "owner/repo for run/repo; gh-api relative path "
+ "for api."
+ ),
+ ),
+ ],
+ )
+
+ async def execute(self, **kwargs: Any) -> ToolResult:
+ from deeptutor.tools.github_query import run_github_query
+
+ outcome = await run_github_query(
+ query_type=str(kwargs.get("query_type") or ""),
+ target=str(kwargs.get("target") or ""),
+ )
+ if not outcome.ok:
+ return ToolResult(
+ content=outcome.error,
+ success=False,
+ metadata={"query_type": outcome.query_type, "target": outcome.target},
+ )
+ return ToolResult(
+ content=outcome.output,
+ sources=[
+ {
+ "type": "github",
+ "query_type": outcome.query_type,
+ "target": outcome.target,
+ }
+ ],
+ metadata={
+ "query_type": outcome.query_type,
+ "target": outcome.target,
+ },
+ )
+
+
+class AskUserTool(_PromptHintsMixin, BaseTool):
+ """Pause the turn mid-loop to ask the user a clarifying question.
+
+ Returns ``pause_for_user`` carrying the structured question payload.
+ The chat pipeline halts the agentic loop after this call, surfaces
+ the question + options as a card in the chat UI, and **waits for
+ the user's reply on the same turn**. When the reply arrives the
+ loop resumes with the user's answer substituted into this tool's
+ result body — so subsequent iterations see "User answered: <text>"
+ as the matching ``role=tool`` content and can act on it. The user
+ can also abort the wait at any time via the composer's stop button
+ (which cancels the whole turn).
+ """
+
+ def get_definition(self) -> ToolDefinition:
+ return ToolDefinition(
+ name="ask_user",
+ description=(
+ "Pause the conversation to ask the user 1-3 clarifying "
+ "questions in one batch. The frontend renders all "
+ "questions on a single card with tabs the user can "
+ "switch between; the user answers each, then submits "
+ "once. The turn does NOT end — when the answers arrive "
+ "the agentic loop resumes with them as this tool's "
+ "result. Use sparingly: only when intent is genuinely "
+ "ambiguous and progress without clarification is unsafe."
+ ),
+ parameters=[
+ ToolParameter(
+ name="questions",
+ type="array",
+ description=(
+ "1-3 questions to ask in one card. Each item: "
+ "{prompt: 'question text', options?: ['A','B'], "
+ "id?: 'stable-id', allow_free_text?: true, "
+ "placeholder?: 'hint for free input'}. Each "
+ "question may have its own option chips; the "
+ "user can also type freely."
+ ),
+ required=False,
+ items={
+ "type": "object",
+ "properties": {
+ "prompt": {"type": "string"},
+ "options": {"type": "array", "items": {"type": "string"}},
+ "id": {"type": "string"},
+ "allow_free_text": {"type": "boolean"},
+ "placeholder": {"type": "string"},
+ },
+ },
+ ),
+ ToolParameter(
+ name="intro",
+ type="string",
+ description=(
+ "Optional one-line lead-in shown above the "
+ "questions (e.g. 'To tailor the research, please "
+ "answer:')."
+ ),
+ required=False,
+ ),
+ # Legacy single-question shape — still accepted; the tool
+ # auto-wraps it into a one-element ``questions`` list so
+ # older prompts keep working unchanged.
+ ToolParameter(
+ name="question",
+ type="string",
+ description=(
+ "Legacy single-question shorthand. Prefer "
+ "``questions``. If supplied alone, wrapped into "
+ "one question with ``options``."
+ ),
+ required=False,
+ ),
+ ToolParameter(
+ name="options",
+ type="array",
+ description=(
+ "Legacy option list paired with ``question``. "
+ "Ignored when ``questions`` is provided."
+ ),
+ required=False,
+ items={"type": "string"},
+ ),
+ ],
+ )
+
+ async def execute(self, **kwargs: Any) -> ToolResult:
+ from deeptutor.tools.ask_user import build_ask_user_payload
+
+ payload, err = build_ask_user_payload(
+ questions=kwargs.get("questions"),
+ intro=kwargs.get("intro"),
+ question=kwargs.get("question"),
+ options=kwargs.get("options"),
+ )
+ if payload is None:
+ return ToolResult(content=err or "Invalid ask_user arguments.", success=False)
+
+ payload_dict = payload.to_dict()
+ prompts = ", ".join(q.prompt for q in payload.questions)
+ return ToolResult(
+ # The placeholder content is overwritten by the pipeline
+ # once the user's reply arrives; the model never sees this
+ # literal string on a normal flow. It only surfaces if the
+ # runtime crashes mid-pause (in which case the LLM at least
+ # gets a coherent log entry).
+ content=f"[awaiting user reply to: {prompts}]",
+ metadata={"ask_user": payload_dict},
+ pause_for_user=payload_dict,
+ )
+
+
BUILTIN_TOOL_TYPES: tuple[type[BaseTool], ...] = (
BrainstormTool,
RAGTool,
@@ -575,12 +1113,42 @@ BUILTIN_TOOL_TYPES: tuple[type[BaseTool], ...] = (
CodeExecutionTool,
ReasonTool,
PaperSearchToolWrapper,
- GeoGebraAnalysisTool,
ReadSourceTool,
+ ReadMemoryTool,
+ WriteMemoryTool,
+ WebFetchTool,
+ ListNotebookTool,
+ WriteNoteTool,
+ GithubTool,
+ AskUserTool,
)
+# Tools whose implementation is parked while we redesign them. NOT loaded
+# into the runtime registry — the chat agent cannot invoke these — but the
+# settings page surfaces them with a "Coming soon" badge so users see the
+# capability is on the roadmap. Re-add to ``BUILTIN_TOOL_TYPES`` when ready
+# to ship.
+COMING_SOON_TOOL_TYPES: tuple[type[BaseTool], ...] = (GeoGebraAnalysisTool,)
+
BUILTIN_TOOL_NAMES: tuple[str, ...] = tuple(tool_type().name for tool_type in BUILTIN_TOOL_TYPES)
+COMING_SOON_TOOL_NAMES: tuple[str, ...] = tuple(
+ tool_type().name for tool_type in COMING_SOON_TOOL_TYPES
+)
+
+# Tools the user can switch on/off from /settings/tools ("体验增强" /
+# Experience Enhancement). Everything else in BUILTIN_TOOL_NAMES is mounted
+# automatically by the chat pipeline under per-tool context gates and is
+# locked-on from the user's perspective. Ordering here is the canonical
+# display order for the settings page.
+USER_TOGGLEABLE_TOOL_NAMES: tuple[str, ...] = (
+ "brainstorm",
+ "web_search",
+ "paper_search",
+ "code_execution",
+ "reason",
+)
+
TOOL_ALIASES: dict[str, tuple[str, dict[str, Any]]] = {
"rag_hybrid": ("rag", {"mode": "hybrid"}),
"rag_naive": ("rag", {"mode": "naive"}),
@@ -592,13 +1160,23 @@ TOOL_ALIASES: dict[str, tuple[str, dict[str, Any]]] = {
__all__ = [
"BUILTIN_TOOL_NAMES",
"BUILTIN_TOOL_TYPES",
+ "COMING_SOON_TOOL_NAMES",
+ "COMING_SOON_TOOL_TYPES",
"TOOL_ALIASES",
+ "USER_TOGGLEABLE_TOOL_NAMES",
+ "AskUserTool",
"BrainstormTool",
"CodeExecutionTool",
"GeoGebraAnalysisTool",
+ "GithubTool",
+ "ListNotebookTool",
"PaperSearchToolWrapper",
"RAGTool",
+ "ReadMemoryTool",
"ReadSourceTool",
"ReasonTool",
+ "WebFetchTool",
"WebSearchTool",
+ "WriteMemoryTool",
+ "WriteNoteTool",
]
diff --git a/deeptutor/tools/github_query.py b/deeptutor/tools/github_query.py
new file mode 100644
index 000000000..d6ec8fc4c
--- /dev/null
+++ b/deeptutor/tools/github_query.py
@@ -0,0 +1,223 @@
+"""Read-only GitHub queries via the ``gh`` CLI.
+
+Pure-function shape on top of an injectable ``run_command`` callback so
+tests don't need to mock ``asyncio.subprocess``. The tool exposes a
+restricted set of operations:
+
+* ``pr`` — view a pull request (title, state, checks, reviews)
+* ``issue`` — view an issue (title, state, body, comments)
+* ``run`` — list recent workflow runs for a repo
+* ``repo`` — show repo metadata
+* ``api`` — generic ``gh api`` GET (read-only fallback for things not
+ covered by the four shortcuts above)
+
+**Read-only by construction**: the command vocabulary below contains
+*only* ``view`` / ``list`` and the ``api`` action is always invoked as a
+GET. The tool does not expose mutation verbs (``close``, ``merge``,
+``comment``, ``edit`` …) — the model can't get them through this
+interface even by trying to be creative with ``target``.
+
+If ``gh`` is not installed (which is the common case on most deploys)
+:py:func:`run_github_query` returns a friendly ``ok=False`` outcome
+instead of raising, so the LLM gets a clear "tool unavailable on this
+system" message that it can relay to the user.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import shutil
+from dataclasses import dataclass
+from typing import Any, Awaitable, Callable
+
+logger = logging.getLogger(__name__)
+
+DEFAULT_TIMEOUT_S = 20.0
+MAX_OUTPUT_CHARS = 16_000
+
+QueryType = str # "pr" | "issue" | "run" | "repo" | "api"
+
+# Mapping from (query_type, target) → argv. Each is a strict *read-only*
+# template — no mutation verbs.
+_PR_FIELDS = "title,state,statusCheckRollup,reviews,url,author,createdAt,body"
+_ISSUE_FIELDS = "title,state,body,comments,url,author,createdAt,labels"
+_REPO_FIELDS = (
+ "description,defaultBranchRef,stargazerCount,forkCount,visibility,url"
+)
+_RUN_FIELDS = "name,status,conclusion,workflowName,event,createdAt,url"
+
+
+@dataclass(frozen=True)
+class GithubOutcome:
+ """Result of one ``gh`` invocation."""
+
+ ok: bool
+ output: str = ""
+ error: str = ""
+ query_type: str = ""
+ target: str = ""
+
+
+# A "command runner" — given an argv list and a timeout, returns
+# (returncode, stdout, stderr). Injectable so the tool stays unit-
+# testable without spawning real subprocesses.
+CommandRunner = Callable[[list[str], float], Awaitable[tuple[int, str, str]]]
+
+
+async def run_github_query(
+ *,
+ query_type: str,
+ target: str,
+ timeout_s: float = DEFAULT_TIMEOUT_S,
+ command_runner: CommandRunner | None = None,
+ gh_available: Callable[[], bool] | None = None,
+) -> GithubOutcome:
+ """Run one read-only ``gh`` command and return its output.
+
+ Arguments
+ ---------
+ query_type : "pr" | "issue" | "run" | "repo" | "api"
+ Determines which read-only template to use.
+ target : str
+ ``owner/repo[#number]`` or full URL for ``pr`` / ``issue``;
+ ``owner/repo`` for ``run`` and ``repo``; raw ``gh api`` path
+ (e.g. ``users/octocat``) for ``api``.
+ """
+ q = (query_type or "").strip().lower()
+ t = (target or "").strip()
+ if not q:
+ return GithubOutcome(ok=False, error="query_type is required.")
+ if not t:
+ return GithubOutcome(
+ ok=False, query_type=q, error="target is required."
+ )
+
+ is_available = gh_available or _default_gh_available
+ if not is_available():
+ return GithubOutcome(
+ ok=False,
+ query_type=q,
+ target=t,
+ error=(
+ "The `gh` CLI is not installed on this server, so GitHub "
+ "queries can't run here. Tell the user; they may need to "
+ "ask their admin to install it."
+ ),
+ )
+
+ argv = _build_argv(q, t)
+ if argv is None:
+ return GithubOutcome(
+ ok=False,
+ query_type=q,
+ target=t,
+ error=(
+ f"Unsupported query_type {q!r}. "
+ "Choose one of: pr, issue, run, repo, api."
+ ),
+ )
+
+ runner = command_runner or _default_command_runner
+ try:
+ rc, stdout, stderr = await runner(argv, timeout_s)
+ except asyncio.TimeoutError:
+ return GithubOutcome(
+ ok=False,
+ query_type=q,
+ target=t,
+ error=f"`gh` timed out after {timeout_s:g}s.",
+ )
+ except Exception as exc: # pragma: no cover — defensive
+ return GithubOutcome(
+ ok=False,
+ query_type=q,
+ target=t,
+ error=f"`gh` invocation failed: {exc}",
+ )
+
+ if rc != 0:
+ err_line = (stderr or stdout).strip().splitlines()[:3]
+ return GithubOutcome(
+ ok=False,
+ query_type=q,
+ target=t,
+ error=" / ".join(err_line) or f"gh exited with code {rc}.",
+ )
+
+ out = stdout.strip()
+ if len(out) > MAX_OUTPUT_CHARS:
+ out = out[:MAX_OUTPUT_CHARS].rstrip() + "\n…[truncated]"
+ return GithubOutcome(ok=True, output=out, query_type=q, target=t)
+
+
+# ---------------------------------------------------------------------------
+# Internals
+# ---------------------------------------------------------------------------
+
+
+def _build_argv(query_type: str, target: str) -> list[str] | None:
+ if query_type == "pr":
+ return [
+ "gh", "pr", "view", target,
+ "--json", _PR_FIELDS,
+ ]
+ if query_type == "issue":
+ return [
+ "gh", "issue", "view", target,
+ "--json", _ISSUE_FIELDS,
+ ]
+ if query_type == "run":
+ return [
+ "gh", "run", "list",
+ "--repo", target,
+ "--limit", "10",
+ "--json", _RUN_FIELDS,
+ ]
+ if query_type == "repo":
+ return [
+ "gh", "repo", "view", target,
+ "--json", _REPO_FIELDS,
+ ]
+ if query_type == "api":
+ # ``gh api`` defaults to GET; we never pass ``--method`` so even
+ # a creative ``target`` like ``-X POST repos/...`` can't sneak
+ # through because the shell isn't invoked.
+ return ["gh", "api", "-H", "Accept: application/vnd.github+json", target]
+ return None
+
+
+def _default_gh_available() -> bool:
+ return shutil.which("gh") is not None
+
+
+async def _default_command_runner(
+ argv: list[str], timeout_s: float
+) -> tuple[int, str, str]:
+ """Run ``argv`` as a subprocess, time-bounded, capturing stdout+stderr."""
+ proc = await asyncio.create_subprocess_exec(
+ *argv,
+ stdout=asyncio.subprocess.PIPE,
+ stderr=asyncio.subprocess.PIPE,
+ )
+ try:
+ stdout_b, stderr_b = await asyncio.wait_for(
+ proc.communicate(), timeout=timeout_s
+ )
+ except asyncio.TimeoutError:
+ proc.kill()
+ await proc.wait()
+ raise
+ return (
+ proc.returncode if proc.returncode is not None else -1,
+ stdout_b.decode("utf-8", errors="replace") if stdout_b else "",
+ stderr_b.decode("utf-8", errors="replace") if stderr_b else "",
+ )
+
+
+__all__ = [
+ "DEFAULT_TIMEOUT_S",
+ "GithubOutcome",
+ "QueryType",
+ "run_github_query",
+]
diff --git a/deeptutor/tools/list_notebook.py b/deeptutor/tools/list_notebook.py
new file mode 100644
index 000000000..7d3a3fcb3
--- /dev/null
+++ b/deeptutor/tools/list_notebook.py
@@ -0,0 +1,222 @@
+"""List the user's notebooks or the records inside a single notebook.
+
+Two modes, picked by whether ``notebook_id`` is supplied:
+
+* **Index mode** (``notebook_id`` empty): list every notebook the
+ active user owns — id, name, description, record count, last-updated.
+ Equivalent to the sidebar view a human sees.
+* **Drill-down mode** (``notebook_id`` supplied): list every record
+ inside one notebook — record id, title, type, summary, created_at.
+ Equivalent to opening a notebook and skimming entries.
+
+The tool itself is stateless and synchronous; the chat pipeline auto-
+mounts it only when the active user actually has notebooks, so empty
+runs are impossible by construction. Output is markdown so the LLM can
+quote the rendered list back to the user without reformatting.
+"""
+
+from __future__ import annotations
+
+import datetime as _dt
+import logging
+from dataclasses import dataclass
+from typing import Any
+
+logger = logging.getLogger(__name__)
+
+# Defensive ceilings so a freak case (user with thousands of notebooks
+# or a notebook with thousands of records) can't blow up the LLM's
+# context window. The cap is recorded in the rendered output so the
+# model knows truncation happened.
+MAX_NOTEBOOKS_RENDERED = 50
+MAX_RECORDS_RENDERED = 80
+MAX_TITLE_PREVIEW = 100
+MAX_SUMMARY_PREVIEW = 240
+
+
+@dataclass(frozen=True)
+class ListOutcome:
+ """Result of one ``list_notebook`` invocation."""
+
+ ok: bool
+ text: str = ""
+ error: str = ""
+ # Structured echo for the frontend / downstream tools. Kept tiny:
+ # callers needing the full dump should call the manager directly.
+ summary: dict[str, Any] | None = None
+
+
+def list_notebooks_or_records(
+ *,
+ notebook_id: str = "",
+ notebook_manager: Any = None,
+) -> ListOutcome:
+ """Run the list operation. Empty ``notebook_id`` → index mode.
+
+ Errors out cleanly as ``ListOutcome(ok=False, error=...)`` instead
+ of raising — the chat loop converts errors back into LLM-visible
+ tool results, not exceptions.
+ """
+ manager = notebook_manager
+ if manager is None:
+ from deeptutor.services.notebook import get_notebook_manager
+
+ manager = get_notebook_manager()
+
+ nid = (notebook_id or "").strip()
+ if not nid:
+ return _render_index(manager)
+ return _render_records(manager, nid)
+
+
+def _render_index(manager: Any) -> ListOutcome:
+ notebooks = manager.list_notebooks() or []
+ if not isinstance(notebooks, list) or not notebooks:
+ return ListOutcome(
+ ok=True,
+ text="The user has no notebooks yet.",
+ summary={"mode": "index", "count": 0},
+ )
+ total = len(notebooks)
+ sliced = notebooks[:MAX_NOTEBOOKS_RENDERED]
+ lines: list[str] = ["**User notebooks**"]
+ for nb in sliced:
+ nb_id = str(nb.get("id") or "").strip()
+ name = str(nb.get("name") or nb.get("title") or "").strip() or nb_id
+ description = _clip(str(nb.get("description") or "").strip(), 200)
+ count = nb.get("record_count")
+ if not isinstance(count, int):
+ try:
+ count = int(count or 0)
+ except (TypeError, ValueError):
+ count = 0
+ updated = _format_timestamp(nb.get("updated_at"))
+ bullet = f"- `{nb_id}` — **{name}** ({count} records"
+ if updated:
+ bullet += f", updated {updated}"
+ bullet += ")"
+ if description:
+ bullet += f"\n {description}"
+ lines.append(bullet)
+ if total > len(sliced):
+ lines.append(
+ f"\n_(showing {len(sliced)} of {total} notebooks — call with "
+ "a specific notebook_id to drill in.)_"
+ )
+ return ListOutcome(
+ ok=True,
+ text="\n".join(lines),
+ summary={"mode": "index", "count": total},
+ )
+
+
+def _render_records(manager: Any, notebook_id: str) -> ListOutcome:
+ # Validate the id against the user's actual notebooks first so the
+ # error message can tell the model the right ids to choose from.
+ notebooks = manager.list_notebooks() or []
+ matched = next(
+ (
+ nb
+ for nb in notebooks
+ if str(nb.get("id") or "").strip() == notebook_id
+ ),
+ None,
+ )
+ if matched is None:
+ valid_ids = ", ".join(
+ f"`{nb.get('id')}`" for nb in notebooks if nb.get("id")
+ )
+ return ListOutcome(
+ ok=False,
+ error=(
+ f"Unknown notebook_id {notebook_id!r}. "
+ f"Valid ids: {valid_ids or '(none)'}."
+ ),
+ )
+
+ try:
+ records = manager.get_records(notebook_id) or []
+ except Exception as exc: # pragma: no cover — defensive
+ logger.warning("list_notebook: get_records failed", exc_info=True)
+ return ListOutcome(ok=False, error=f"Failed to load records: {exc}")
+
+ notebook_name = str(matched.get("name") or matched.get("title") or notebook_id)
+ if not records:
+ return ListOutcome(
+ ok=True,
+ text=f"Notebook **{notebook_name}** (`{notebook_id}`) has no records yet.",
+ summary={"mode": "records", "notebook_id": notebook_id, "count": 0},
+ )
+
+ total = len(records)
+ # Newest first — the most-recent record is typically the one the
+ # user wants to find or edit.
+ sorted_records = sorted(
+ records,
+ key=lambda r: r.get("created_at") or 0,
+ reverse=True,
+ )
+ sliced = sorted_records[:MAX_RECORDS_RENDERED]
+ lines: list[str] = [
+ f"**Records in notebook `{notebook_id}` — {notebook_name}**",
+ ]
+ for rec in sliced:
+ rid = str(rec.get("id") or "").strip()
+ title = _clip(str(rec.get("title") or "").strip(), MAX_TITLE_PREVIEW)
+ rtype = str(rec.get("type") or "").strip()
+ summary = _clip(
+ str(rec.get("summary") or "").strip(),
+ MAX_SUMMARY_PREVIEW,
+ )
+ created = _format_timestamp(rec.get("created_at"))
+ head = f"- `{rid}` — **{title or '(untitled)'}**"
+ if rtype:
+ head += f" [{rtype}]"
+ if created:
+ head += f" — {created}"
+ lines.append(head)
+ if summary:
+ lines.append(f" {summary}")
+ if total > len(sliced):
+ lines.append(
+ f"\n_(showing {len(sliced)} most-recent of {total} records.)_"
+ )
+ return ListOutcome(
+ ok=True,
+ text="\n".join(lines),
+ summary={"mode": "records", "notebook_id": notebook_id, "count": total},
+ )
+
+
+def _clip(text: str, limit: int) -> str:
+ if len(text) <= limit:
+ return text
+ return text[:limit].rstrip() + "…"
+
+
+def _format_timestamp(raw: Any) -> str:
+ """Render an epoch-seconds value as ``YYYY-MM-DD`` for at-a-glance scan.
+
+ Falls back to ``""`` on missing / unparseable inputs so the caller
+ can omit the field cleanly.
+ """
+ if raw is None:
+ return ""
+ try:
+ ts = float(raw)
+ except (TypeError, ValueError):
+ return ""
+ if ts <= 0:
+ return ""
+ try:
+ return _dt.datetime.fromtimestamp(ts).strftime("%Y-%m-%d")
+ except (OverflowError, OSError, ValueError):
+ return ""
+
+
+__all__ = [
+ "MAX_NOTEBOOKS_RENDERED",
+ "MAX_RECORDS_RENDERED",
+ "ListOutcome",
+ "list_notebooks_or_records",
+]
diff --git a/deeptutor/tools/prompting/hints/en/ask_user.yaml b/deeptutor/tools/prompting/hints/en/ask_user.yaml
new file mode 100644
index 000000000..4f84fb30f
--- /dev/null
+++ b/deeptutor/tools/prompting/hints/en/ask_user.yaml
@@ -0,0 +1,13 @@
+short_description: "Pause the loop and ask the user 1-3 clarifying questions on one card; each question can have its own option chips and free-form input."
+when_to_use: "Only when missing information genuinely blocks a reliable answer: user level / grade is unclear and would change the depth, the question's referent is ambiguous, or several reasonable paths need user input. **Do not call this every turn** and do not call it when the user has already been clear. **At most one `ask_user` per assistant message**: bundle every clarification into the `questions` list of that single call (up to 3 questions); never emit multiple parallel `ask_user` tool_calls in one `tool_calls` field — duplicate cards are a bug, not redundancy."
+input_format: |
+ Preferred:
+ {"intro": "optional one-line lead-in", "questions": [
+ {"id": "scope", "prompt": "Q1 text", "options": ["A","B","C"]},
+ {"id": "depth", "prompt": "Q2 text", "options": ["A","B"]}
+ ]}
+ Each question allows up to 8 short option chips; the user can also type free-form text. 1-3 questions per call; group related clarifications in one call rather than calling the tool multiple times in a row.
+ Legacy shorthand (still accepted, auto-wrapped): {"question": "...", "options": [...]}.
+guideline: "After this call the loop **PAUSES** until the user answers, then **RESUMES on the SAME turn**. The user's reply appears as the matching tool result with content beginning ``User answered:`` followed by one ``- <prompt>\\n → <answer>`` line per question. When you see that, you MUST continue addressing the user's original request — call more tools if needed, then end with a substantive ``FINISH``. **Do NOT** treat ask_user as the end of the turn — a single-line acknowledgment is not an acceptable final answer."
+note: "Skipped questions arrive as ``(skipped)``. The user can also cancel the pause via the stop button (cancels the whole turn)."
+phase: "exploration"
diff --git a/deeptutor/tools/prompting/hints/en/geogebra_analysis.yaml b/deeptutor/tools/prompting/hints/en/geogebra_analysis.yaml
index e2325422e..a4da8c1d3 100644
--- a/deeptutor/tools/prompting/hints/en/geogebra_analysis.yaml
+++ b/deeptutor/tools/prompting/hints/en/geogebra_analysis.yaml
@@ -1,6 +1,6 @@
short_description: "Analyze a math problem image and generate validated GeoGebra commands for geometric visualization."
when_to_use: "Use when the user uploads a geometry or math diagram and wants to reconstruct, visualize, or interact with the figure in GeoGebra."
input_format: "The math problem text (question). The image is injected automatically from attachments."
-guideline: "Only invoke this tool when an image attachment is present and the problem involves geometric figures. The tool runs a full 4-stage pipeline (detection → analysis → scripting → reflection) and returns ready-to-render GeoGebra commands."
+guideline: "Only invoke this tool when an image attachment is present and the problem involves geometric figures. The tool runs a full 4-stage pipeline (detection → analysis → scripting → reflection) and returns ready-to-render GeoGebra commands. When the tool result contains a ```ggbscript[…]``` fenced block, copy that entire block verbatim into your final answer so the chat surface can render the interactive figure."
note: "The pipeline requires a vision-capable LLM. Processing may take 15-30 seconds due to four sequential LLM calls."
phase: "exploration"
diff --git a/deeptutor/tools/prompting/hints/en/github.yaml b/deeptutor/tools/prompting/hints/en/github.yaml
new file mode 100644
index 000000000..1c1b1d19b
--- /dev/null
+++ b/deeptutor/tools/prompting/hints/en/github.yaml
@@ -0,0 +1,6 @@
+short_description: "Read-only queries against GitHub PRs / issues / repos / CI runs via the `gh` CLI."
+when_to_use: "When the user asks about a specific GitHub resource: 'is this PR's CI passing', 'what are the recent issues on owner/repo', 'show this release's changelog'. **Do not use it for general code-concept questions** — answer those from training knowledge or via ``web_search``."
+input_format: "{\"query_type\": \"pr|issue|run|repo|api\", \"target\": \"owner/repo[#number] or full URL; relative gh api path when query_type is api\"}."
+guideline: "Read-only by construction — this tool cannot comment, close, or merge. Tell the user to act on GitHub directly for write operations. Output is JSON; extract the relevant fields for your reply rather than dumping it raw."
+note: "If the server has no `gh` CLI installed the tool returns a clear error — relay that honestly rather than fabricating a GitHub state."
+phase: "exploration"
diff --git a/deeptutor/tools/prompting/hints/en/list_notebook.yaml b/deeptutor/tools/prompting/hints/en/list_notebook.yaml
new file mode 100644
index 000000000..1052ed972
--- /dev/null
+++ b/deeptutor/tools/prompting/hints/en/list_notebook.yaml
@@ -0,0 +1,6 @@
+short_description: "Discover the user's notebooks (no args → index) or the records inside one notebook (notebook_id → drill-down)."
+when_to_use: "Call BEFORE `write_note` in edit mode so you have valid record ids. Also useful when the user references a notebook by description but you need its exact id, or when planning a multi-step save."
+input_format: "{} for the index, or {\"notebook_id\": \"id from the system-prompt notebook list / from a prior index call\"} to list records in one notebook."
+guideline: "Index mode shows id + name + record_count; drill-down shows record id + title + summary + date (newest first, capped at ~80). Don't call list_notebook just to confirm notebook names already visible in the system-prompt manifest — only call it when you genuinely need fresh info (e.g. to discover record ids for an edit, or after the user adds notebooks)."
+note: "Auto-mounted only when the user has at least one notebook. Output is markdown so you can paste/quote chunks back to the user."
+phase: "exploration"
diff --git a/deeptutor/tools/prompting/hints/en/paper_search.yaml b/deeptutor/tools/prompting/hints/en/paper_search.yaml
index a6eb2d330..7fde7888e 100644
--- a/deeptutor/tools/prompting/hints/en/paper_search.yaml
+++ b/deeptutor/tools/prompting/hints/en/paper_search.yaml
@@ -1,6 +1,6 @@
-short_description: "Search arXiv papers for academic background and recent methods."
-when_to_use: "Use when the task needs research literature, state-of-the-art methods, or scholarly references."
-input_format: "A concise keyword query, usually in English."
-guideline: "Use paper search for research-oriented questions, not standard textbook knowledge."
-note: "Paper search is strongest for academic topics and current research trends."
+short_description: "Search arXiv preprints for academic background and recent methods."
+when_to_use: "Use when the task needs research papers, state-of-the-art methods, or scholarly references. Skip for standard textbook questions."
+input_format: "**At most 3 English words** (e.g. `agent harness`, `LLM benchmark`). No full sentences, no 4-word-or-longer queries, no stacked noun phrases."
+guideline: "paper_search only covers arXiv; on zero results, do not keep rewriting the query — switch to web_search or FINISH."
+note: "arXiv-only; industrial-only terms may have no hits."
phase: "expansion"
diff --git a/deeptutor/tools/prompting/hints/en/read_memory.yaml b/deeptutor/tools/prompting/hints/en/read_memory.yaml
new file mode 100644
index 000000000..4b5682834
--- /dev/null
+++ b/deeptutor/tools/prompting/hints/en/read_memory.yaml
@@ -0,0 +1,6 @@
+short_description: "Read the user's persistent memory: recent learning summary, profile, knowledge scope, and explicit preferences."
+when_to_use: "When the answer's tone, depth, examples, or recommendations can be meaningfully personalised to THIS user. Skip for pure factual / computational / translation questions."
+input_format: "No parameters. Returns all four L3 documents concatenated."
+guideline: "Call at most once per turn. Use memory to shape HOW you explain — examples, depth, follow-ups. Do NOT quote memory back at the user as factual content."
+note: "When the user hasn't built up memory yet, returns a `(No memory available...)` notice — treat as a generic question."
+phase: "exploration"
diff --git a/deeptutor/tools/prompting/hints/en/web_fetch.yaml b/deeptutor/tools/prompting/hints/en/web_fetch.yaml
new file mode 100644
index 000000000..e0c202b0d
--- /dev/null
+++ b/deeptutor/tools/prompting/hints/en/web_fetch.yaml
@@ -0,0 +1,6 @@
+short_description: "Fetch a specific URL and extract readable content as markdown."
+when_to_use: "When the user's message contains a specific URL and reading that page is needed: shared blog / textbook / paper links with a question about them, or an explicit 'read this page' request. Use ``web_search`` for general topic searches."
+input_format: "{\"url\": \"full http(s):// URL\", \"max_chars\": 50000}. ``max_chars`` is optional (default 50000) and content beyond it is truncated."
+guideline: "Login-walled, anti-bot, or JS-only pages may return little useful content — say so honestly, don't fabricate around an empty result. The returned text already has scripts and sidebars stripped (first line is `# Title` when available)."
+note: "Refuses file:// / localhost / private IP addresses. Fetches one URL per call; issue separate calls for multiple URLs."
+phase: "exploration"
diff --git a/deeptutor/tools/prompting/hints/en/write_memory.yaml b/deeptutor/tools/prompting/hints/en/write_memory.yaml
new file mode 100644
index 000000000..ab502e789
--- /dev/null
+++ b/deeptutor/tools/prompting/hints/en/write_memory.yaml
@@ -0,0 +1,6 @@
+short_description: "Save an explicit user preference to long-term memory. Only fires when the user *clearly* states a preference."
+when_to_use: "The user explicitly told you a preference — style, language, format, depth, follow-up cadence, anything they want carried forward. Do NOT speculate; do NOT infer from a single comment that could be situational."
+input_format: "{\"op\": \"add\"|\"edit\", \"text\": \"≤240 chars in the user's words\", \"target_id\"?: \"m_xxx for edit\", \"reason\"?: \"optional note\"}"
+guideline: "Echo the preference briefly in your reply ('Got it — concise from now on'), then call this. Prefer quoting the user 「verbatim」 when natural. One call per preference; don't bundle unrelated preferences in one text."
+note: "Writes to the L3 preferences document. Other memory layers (recent, profile, scope, per-surface summaries) are consolidated by the user manually in the Memory workbench — do not try to write there."
+phase: "execution"
diff --git a/deeptutor/tools/prompting/hints/en/write_note.yaml b/deeptutor/tools/prompting/hints/en/write_note.yaml
new file mode 100644
index 000000000..5cc2853dc
--- /dev/null
+++ b/deeptutor/tools/prompting/hints/en/write_note.yaml
@@ -0,0 +1,6 @@
+short_description: "Save a new notebook record OR edit an existing one. mode='append' (new) or 'edit' (patch existing)."
+when_to_use: "append: user explicitly asked to save, or the turn produced a self-contained walkthrough worth keeping. edit: user asked to revise / extend / correct a record they previously saved. For edit, always run `list_notebook` first so you have the right record_id."
+input_format: "append: {\"mode\": \"append\", \"notebook_id\": \"...\", \"title\": \"...\", \"turns_to_include\": \"3\" | \"all\", \"note\": \"optional\"}. edit: {\"mode\": \"edit\", \"notebook_id\": \"...\", \"record_id\": \"...\", \"title\": optional, \"content\": optional, \"note\": optional}. In append mode you do NOT write the body — the tool inserts the real chat transcript itself; only pass `content` when you intentionally want to save an agent-authored summary."
+guideline: "Default `turns_to_include` is 3. Use 'all' when the user says 'save this whole conversation'. Never invent notebook ids or record ids — the schema enum lists valid notebook_ids, and `list_notebook` gives you record ids. The optional `note` is short commentary ('why this matters', 'context to remember'), not the body."
+note: "Auto-mounted only when the user has at least one notebook. On success the result includes the destination notebook name + record id — surface those to the user as confirmation. For edits the result confirms which field(s) changed."
+phase: "synthesis"
diff --git a/deeptutor/tools/prompting/hints/zh/ask_user.yaml b/deeptutor/tools/prompting/hints/zh/ask_user.yaml
new file mode 100644
index 000000000..48f3cd746
--- /dev/null
+++ b/deeptutor/tools/prompting/hints/zh/ask_user.yaml
@@ -0,0 +1,13 @@
+short_description: "暂停 loop 向用户提 1-5 个澄清问题,所有问题在同一张卡片上展示并可切换;每题可有自己的选项按钮+自由输入。"
+when_to_use: "仅在缺少关键信息无法可靠回答时使用:用户水平/年级不明会影响讲解深度、问题指代不清、有多种合理推进路径需要用户选。**不要每轮都问**;用户已经说清楚的场合不要调用。**同一次回复里最多调用一次 `ask_user`**:把所有要澄清的问题打包进同一次调用的 `questions` 列表(最多 3 个),**绝不要**在一个 `tool_calls` 字段里并行发起多个 `ask_user`——重复的卡片是错误,不是冗余。"
+input_format: |
+ 推荐形式:
+ {"intro": "可选的一行导语", "questions": [
+ {"id": "scope", "prompt": "问题1正文", "options": ["A","B","C"]},
+ {"id": "depth", "prompt": "问题2正文", "options": ["A","B"]}
+ ]}
+ 每题最多 8 个短选项;用户也可不点而自由输入。一次调用 1-3 个问题;尽量把相关澄清放在同一次调用里,而不是连续多次调用。
+ 兼容旧形式:{"question": "...", "options": [...]}(系统会自动包装成单元素 questions)。
+guideline: "调用后 loop **暂停**等用户回复,然后在**同一轮**自动 resume——你会在下一次迭代看到一条以 `User answered:` 开头的工具结果,下方按 `- <prompt>\\n → <answer>` 每行一条列出。看到它后,**必须**继续处理用户最初的请求:需要的话再调更多工具,最后用一个有实质内容的 ``FINISH`` 结尾。**绝不**把 ask_user 当作本轮的终点——一句简单的『好的我知道了』不算合格的最终答案。"
+note: "用户跳过的问题会以 `(skipped)` 回传。用户也可以点 stop 按钮取消等待(会取消整轮)。"
+phase: "exploration"
diff --git a/deeptutor/tools/prompting/hints/zh/geogebra_analysis.yaml b/deeptutor/tools/prompting/hints/zh/geogebra_analysis.yaml
index 4a4509c23..2a1417d76 100644
--- a/deeptutor/tools/prompting/hints/zh/geogebra_analysis.yaml
+++ b/deeptutor/tools/prompting/hints/zh/geogebra_analysis.yaml
@@ -1,6 +1,6 @@
short_description: "分析数学题目图片,生成经过验证的 GeoGebra 命令用于几何可视化。"
when_to_use: "当用户上传了几何或数学配图,并希望在 GeoGebra 中重建、可视化或交互操作图形时使用。"
input_format: "数学题目文本(question)。图片由附件自动注入。"
-guideline: "仅当有图片附件且题目涉及几何图形时调用此工具。工具内部运行完整的 4 阶段流水线(检测→分析→脚本生成→反思验证),返回可直接渲染的 GeoGebra 命令。"
+guideline: "仅当有图片附件且题目涉及几何图形时调用此工具。工具内部运行完整的 4 阶段流水线(检测→分析→脚本生成→反思验证),返回可直接渲染的 GeoGebra 命令。当工具返回的结果中包含 ```ggbscript[…]``` 围栏代码块时,必须在最终回答中原样复制该完整代码块,前端才能据此渲染可交互的几何图形。"
note: "流水线需要支持视觉的 LLM。由于包含四次连续 LLM 调用,处理时间约 15-30 秒。"
phase: "exploration"
diff --git a/deeptutor/tools/prompting/hints/zh/github.yaml b/deeptutor/tools/prompting/hints/zh/github.yaml
new file mode 100644
index 000000000..5ab388b65
--- /dev/null
+++ b/deeptutor/tools/prompting/hints/zh/github.yaml
@@ -0,0 +1,6 @@
+short_description: "通过 `gh` CLI 只读地查询 GitHub 上的 PR / issue / repo / CI 运行状态。"
+when_to_use: "用户问到具体 GitHub 资源时使用:'看看这个 PR 的 CI 通过了吗'、'某 repo 最近有什么 issue'、'这个 release 的 changelog'。**普通代码概念解释不要调它**,用通识或 web_search。"
+input_format: "{\"query_type\": \"pr|issue|run|repo|api\", \"target\": \"owner/repo[#number] 或完整 URL;api 类型时是 gh api 的相对路径\"}。"
+guideline: "本工具**只能读**,不会代用户评论、关 issue、合 PR——需要修改 GitHub 状态时让用户自己操作。返回的是 JSON,自己提取关键字段汇报给用户即可。"
+note: "服务端没装 `gh` CLI 时工具会返回一个明确错误,请如实告诉用户;不要凭空编造 GitHub 上的状态。"
+phase: "exploration"
diff --git a/deeptutor/tools/prompting/hints/zh/list_notebook.yaml b/deeptutor/tools/prompting/hints/zh/list_notebook.yaml
new file mode 100644
index 000000000..5d56062e5
--- /dev/null
+++ b/deeptutor/tools/prompting/hints/zh/list_notebook.yaml
@@ -0,0 +1,6 @@
+short_description: "查看用户的笔记本(不传参数 → 列出全部)或某个笔记本内的所有记录(传 notebook_id → 列出 records)。"
+when_to_use: "在调用 `write_note` 的 edit 模式之前先调用此工具拿到 record_id。用户用描述引用某本笔记本但你需要它的精确 id 时也用此工具。"
+input_format: "{} 列总览;{\"notebook_id\": \"system prompt 列出的或先前 index 返回的 id\"} 钻取单本笔记本的记录。"
+guideline: "Index 模式返回 id + name + 记录数;钻取模式返回 record id + 标题 + summary + 日期(按时间倒序,最多 80 条)。如果 system prompt 的 notebook 索引已经能回答你的问题(笔记本名字 / id),就不要再调用此工具——只在确实需要新信息(例如发现 record_id 以便 edit,或用户中途新建了笔记本)时调用。"
+note: "用户没有任何笔记本时此工具不会出现。输出是 markdown,可以直接引用片段回复用户。"
+phase: "exploration"
diff --git a/deeptutor/tools/prompting/hints/zh/paper_search.yaml b/deeptutor/tools/prompting/hints/zh/paper_search.yaml
index 0703c9e7b..bd8cf0612 100644
--- a/deeptutor/tools/prompting/hints/zh/paper_search.yaml
+++ b/deeptutor/tools/prompting/hints/zh/paper_search.yaml
@@ -1,6 +1,6 @@
-short_description: "搜索 arXiv 论文,用于补充学术背景和近期方法。"
-when_to_use: "当任务需要研究文献、前沿方法或学术引用时使用。"
-input_format: "简洁关键词查询,通常建议用英文。"
-guideline: "paper_search 适合研究型问题,不适合普通教材型知识。"
-note: "它更适合学术主题和前沿研究趋势。"
+short_description: "搜索 arXiv 预印本,用于学术背景和前沿方法。"
+when_to_use: "需要研究论文、最新学术方法或可引用学术来源时使用;普通教材型问题不要用。"
+input_format: "**最多 3 个英文单词**(如 `agent harness`、`LLM benchmark`)。禁止整句、禁止 4 词及以上、禁止把多个名词短语堆在一起。"
+guideline: "paper_search 仅覆盖 arXiv;零结果时不要反复改写查询,改用 web_search 或直接 FINISH。"
+note: "只覆盖 arXiv 预印本,工业界术语可能没有命中。"
phase: "expansion"
diff --git a/deeptutor/tools/prompting/hints/zh/read_memory.yaml b/deeptutor/tools/prompting/hints/zh/read_memory.yaml
new file mode 100644
index 000000000..6952269cf
--- /dev/null
+++ b/deeptutor/tools/prompting/hints/zh/read_memory.yaml
@@ -0,0 +1,6 @@
+short_description: "读取该用户的持久化记忆:近期学习总结、用户画像、知识 scope、显式偏好。"
+when_to_use: "当回答的语气、深度、举例或推荐可以**针对该用户**调整时调用。纯事实/计算/翻译类问题不调。"
+input_format: "无参数。返回拼接后的四份 L3 文档。"
+guideline: "每个 turn 最多调一次。读完用记忆来影响**怎么解释**、**举什么例子**、**问什么后续问题**——不要把记忆原文当事实抄给用户。"
+note: "用户还没建立记忆时返回 `(No memory available...)` 提示,按通用问题处理。"
+phase: "exploration"
diff --git a/deeptutor/tools/prompting/hints/zh/web_fetch.yaml b/deeptutor/tools/prompting/hints/zh/web_fetch.yaml
new file mode 100644
index 000000000..d737b9cd3
--- /dev/null
+++ b/deeptutor/tools/prompting/hints/zh/web_fetch.yaml
@@ -0,0 +1,6 @@
+short_description: "抓取一个具体 URL 的网页内容并提取为 markdown 文本。"
+when_to_use: "用户消息里出现具体 URL 且需要读那个页面时使用:分享了博客 / 教材 / 论文链接并问相关问题,或者用户明确说\"帮我读这个页面\"。普通主题搜索请用 web_search。"
+input_format: "{\"url\": \"完整 http(s):// URL\", \"max_chars\": 50000}。max_chars 可选,默认 50000,超出会截断。"
+guideline: "对于需要登录、有反爬虫、或纯前端 JS 渲染的页面会失败——失败时如实告知用户,不要凭空补内容。返回结果是已经去掉脚本/侧边栏的纯文本(首行 `# 标题`)。"
+note: "拒绝 file:// / localhost / 内网 IP 等地址。一次只抓一个 URL;要抓多个分多次调用。"
+phase: "exploration"
diff --git a/deeptutor/tools/prompting/hints/zh/write_memory.yaml b/deeptutor/tools/prompting/hints/zh/write_memory.yaml
new file mode 100644
index 000000000..5b1393079
--- /dev/null
+++ b/deeptutor/tools/prompting/hints/zh/write_memory.yaml
@@ -0,0 +1,6 @@
+short_description: "把用户显式表达的偏好写入长期记忆。仅当用户**明确表达**偏好时才调用。"
+when_to_use: "用户明确告诉你一个偏好——风格、语言、格式、深度、跟进节奏,任何他们希望长期沿用的东西。不要猜,不要根据一句可能只是当时情境的话推断长期偏好。"
+input_format: "{\"op\": \"add\"|\"edit\", \"text\": \"≤240 字,尽量用用户原话\", \"target_id\"?: \"edit 时必填 m_xxx\", \"reason\"?: \"可选备注\"}"
+guideline: "在回复里简短复述偏好(例如「好的,之后用简短回答」),然后调用本工具。自然时优先用户原话引述。一次调用记一条偏好,不要塞多个无关偏好到同一 text。"
+note: "只能写 L3 偏好文档。其他记忆层(近期总结、画像、scope、各 surface 小结)由用户在 Memory 工作台手动凝练——不要尝试写。"
+phase: "execution"
diff --git a/deeptutor/tools/prompting/hints/zh/write_note.yaml b/deeptutor/tools/prompting/hints/zh/write_note.yaml
new file mode 100644
index 000000000..29a94ebfc
--- /dev/null
+++ b/deeptutor/tools/prompting/hints/zh/write_note.yaml
@@ -0,0 +1,6 @@
+short_description: "新增笔记本记录(mode='append')或修改已有记录(mode='edit')。"
+when_to_use: "append:用户明确要求保存,或本轮产生了自包含的解题过程 / 新概念整理 / 错题分析。edit:用户要求修改、扩展或更正之前保存的记录——edit 之前一定要先用 `list_notebook` 拿到正确的 record_id。"
+input_format: "append: {\"mode\": \"append\", \"notebook_id\": \"...\", \"title\": \"...\", \"turns_to_include\": \"3\" 或 \"all\", \"note\": \"可选\"}。edit: {\"mode\": \"edit\", \"notebook_id\": \"...\", \"record_id\": \"...\", \"title\": 可选, \"content\": 可选, \"note\": 可选}。append 模式下你不需要写 body——工具会自己读真实对话历史拼好;只有在确实想保存你自己撰写的总结时才主动传 `content`。"
+guideline: "`turns_to_include` 默认 3。用户说『把整段对话存下来』时用 'all'。永远不要凭空发明笔记本 id 或 record id——schema 枚举列出了合法 notebook_id,record_id 通过 `list_notebook` 拿到。`note` 是简短评注(『为什么值得保存』『以后看这条要记得的背景』),不是正文。"
+note: "用户没有任何笔记本时此工具不会出现。append 成功后返回 notebook_name + record_id;edit 成功后会确认改了哪些字段,告诉用户即可。"
+phase: "synthesis"
diff --git a/deeptutor/tools/web_fetch.py b/deeptutor/tools/web_fetch.py
new file mode 100644
index 000000000..3dc6e1ad5
--- /dev/null
+++ b/deeptutor/tools/web_fetch.py
@@ -0,0 +1,264 @@
+"""HTTP fetch + readable-content extraction for the chat ``web_fetch`` tool.
+
+Kept deliberately self-contained: a single async entrypoint
+:py:func:`fetch_url_as_markdown` that takes a URL and returns either the
+extracted text (with a ``url`` field for citation) or a structured error.
+The chat pipeline calls it via the thin ``WebFetchTool`` wrapper in
+``deeptutor/tools/builtin/__init__.py``; no internal global state, no
+hidden side-effects — easy to test by passing a mock httpx client.
+
+Security stance (kept tight on purpose because the model decides
+arguments, not a human):
+
+* Only ``http://`` / ``https://`` schemes accepted.
+* IP literals and hostnames resolving to **private / loopback / link-local**
+ ranges are rejected up front. The strict-host check happens both
+ pre-flight (against the parsed URL) and post-redirect (against the
+ final resolved URL) so a redirect to ``127.0.0.1`` can't slip past.
+* Response size is hard-capped at ``MAX_RESPONSE_BYTES``; we stop reading
+ once the body grows past this even before the server finishes.
+* Extracted text is truncated to ``max_chars`` (default 50 000 chars,
+ caller-overridable) with a ``…[truncated]`` marker.
+"""
+
+from __future__ import annotations
+
+import ipaddress
+import logging
+import re
+import socket
+from dataclasses import dataclass
+from typing import Any
+from urllib.parse import urlparse
+
+import httpx
+
+logger = logging.getLogger(__name__)
+
+DEFAULT_MAX_CHARS = 50_000
+MAX_RESPONSE_BYTES = 4 * 1024 * 1024 # 4 MB — safety cap on raw download
+DEFAULT_TIMEOUT_S = 15.0
+DEFAULT_USER_AGENT = "DeepTutor/1.0 (+https://hkuds.dev/deeptutor)"
+ALLOWED_SCHEMES = {"http", "https"}
+
+# Cheap inline HTML → text. Good enough for blog / docs / arxiv abstract
+# pages. For JS-heavy SPAs the tool will return the bare HTML scaffold —
+# the docstring tells the model it may fail in that case, so it won't
+# fabricate around an empty result.
+_SCRIPT_STYLE_RE = re.compile(r"<(script|style)[^>]*>.*?</\1>", re.DOTALL | re.IGNORECASE)
+_TAG_RE = re.compile(r"<[^>]+>")
+_WHITESPACE_RE = re.compile(r"[ \t]+")
+_BLANK_LINE_RE = re.compile(r"\n{3,}")
+_TITLE_RE = re.compile(r"<title[^>]*>(.*?)</title>", re.DOTALL | re.IGNORECASE)
+
+
+@dataclass(frozen=True)
+class FetchOutcome:
+ """Result of a single ``web_fetch`` invocation.
+
+ ``ok=True`` paths populate ``markdown`` and ``url`` (the final
+ resolved URL after redirects). ``ok=False`` paths populate ``error``
+ with a one-line description suitable to surface back to the model.
+ """
+
+ ok: bool
+ markdown: str = ""
+ url: str = ""
+ title: str = ""
+ truncated: bool = False
+ error: str = ""
+
+
+async def fetch_url_as_markdown(
+ url: str,
+ *,
+ max_chars: int = DEFAULT_MAX_CHARS,
+ timeout_s: float = DEFAULT_TIMEOUT_S,
+ user_agent: str = DEFAULT_USER_AGENT,
+ client_factory: Any = None,
+ host_validator: Any = None,
+) -> FetchOutcome:
+ """Fetch ``url`` and extract readable text.
+
+ ``client_factory`` accepts a no-arg callable returning an
+ ``httpx.AsyncClient``-compatible context manager. ``host_validator``
+ is a ``(host: str) -> bool`` that returns ``True`` iff the host
+ should be **rejected** as private/loopback — defaults to
+ :py:func:`_is_disallowed_host`. Both default to real production
+ behaviour; tests inject stubs to bypass DNS or network I/O.
+ """
+ url_clean = (url or "").strip().strip("`\"'")
+ parsed = urlparse(url_clean)
+ if parsed.scheme.lower() not in ALLOWED_SCHEMES:
+ return FetchOutcome(
+ ok=False,
+ error=f"Unsupported URL scheme: {parsed.scheme or '(empty)'}. Use http:// or https://.",
+ )
+ host = (parsed.hostname or "").strip()
+ if not host:
+ return FetchOutcome(ok=False, error="URL is missing a host.")
+ validator = host_validator or _is_disallowed_host
+ if validator(host):
+ return FetchOutcome(
+ ok=False,
+ error=f"Refusing to fetch private/loopback host: {host}.",
+ )
+
+ factory = client_factory or _default_client_factory
+ try:
+ async with factory(timeout=timeout_s, user_agent=user_agent) as client:
+ try:
+ async with client.stream(
+ "GET",
+ url_clean,
+ headers={"User-Agent": user_agent, "Accept": "text/html,*/*;q=0.5"},
+ follow_redirects=True,
+ ) as response:
+ final_url = str(response.url)
+ final_host = (urlparse(final_url).hostname or "").strip()
+ if final_host and validator(final_host):
+ return FetchOutcome(
+ ok=False,
+ error=f"Redirect to private/loopback host blocked: {final_host}.",
+ )
+ if response.status_code >= 400:
+ return FetchOutcome(
+ ok=False,
+ url=final_url,
+ error=f"HTTP {response.status_code} from {final_url}.",
+ )
+ raw = await _bounded_read(response, MAX_RESPONSE_BYTES)
+ except httpx.HTTPError as exc:
+ return FetchOutcome(ok=False, error=f"Network error: {exc}")
+ except Exception as exc: # pragma: no cover — defensive
+ return FetchOutcome(ok=False, error=f"Unexpected fetch failure: {exc}")
+
+ title, body = _extract_readable(raw)
+ truncated = False
+ if len(body) > max_chars:
+ body = body[:max_chars].rstrip() + "\n…[truncated]"
+ truncated = True
+ return FetchOutcome(
+ ok=True, markdown=body, url=final_url, title=title, truncated=truncated
+ )
+
+
+# ---------------------------------------------------------------------------
+# Internals
+# ---------------------------------------------------------------------------
+
+
+def _default_client_factory(*, timeout: float, user_agent: str) -> httpx.AsyncClient:
+ return httpx.AsyncClient(
+ timeout=timeout,
+ headers={"User-Agent": user_agent},
+ max_redirects=5,
+ )
+
+
+def _is_disallowed_host(host: str) -> bool:
+ """Block hosts that resolve to private / loopback / link-local IPs.
+
+ Handles both raw IP literals (``127.0.0.1`` / ``[::1]``) and DNS
+ names (resolves them once via ``socket.getaddrinfo`` and checks ALL
+ returned addresses). DNS failures are treated as disallowed to fail
+ closed when in doubt.
+ """
+ candidate = host.strip("[]")
+ # Direct IP literal check
+ try:
+ ip = ipaddress.ip_address(candidate)
+ return _is_disallowed_ip(ip)
+ except ValueError:
+ pass
+ # Common loopback / metadata hostnames before DNS even tries.
+ lower = candidate.lower()
+ if lower in {"localhost", "ip6-localhost", "ip6-loopback"}:
+ return True
+ if lower.endswith(".local"):
+ return True
+ # Resolve once; treat resolution failure as "disallowed" so a typo
+ # plus an unlucky stub doesn't accidentally hit a private network.
+ try:
+ infos = socket.getaddrinfo(candidate, None)
+ except OSError:
+ return True
+ for info in infos:
+ addr = info[4][0]
+ try:
+ if _is_disallowed_ip(ipaddress.ip_address(addr)):
+ return True
+ except ValueError:
+ continue
+ return False
+
+
+def _is_disallowed_ip(ip: ipaddress.IPv4Address | ipaddress.IPv6Address) -> bool:
+ return (
+ ip.is_private
+ or ip.is_loopback
+ or ip.is_link_local
+ or ip.is_multicast
+ or ip.is_reserved
+ or ip.is_unspecified
+ )
+
+
+async def _bounded_read(response: httpx.Response, limit: int) -> str:
+ """Stream-read at most ``limit`` bytes from ``response`` then stop.
+
+ Avoids holding hundreds of MB if a server (or an LLM-supplied URL)
+ points at a huge resource. Encoding falls back from response.encoding
+ → utf-8 with replacement.
+ """
+ buf = bytearray()
+ async for chunk in response.aiter_bytes():
+ buf.extend(chunk)
+ if len(buf) >= limit:
+ break
+ encoding = response.encoding or "utf-8"
+ try:
+ return buf.decode(encoding, errors="replace")
+ except (LookupError, TypeError):
+ return buf.decode("utf-8", errors="replace")
+
+
+def _extract_readable(html_or_text: str) -> tuple[str, str]:
+ """Return ``(title, body_text)`` extracted from an HTML string.
+
+ For non-HTML payloads (plain text, JSON dumps) just normalises
+ whitespace and returns the input as-is — the model still gets
+ something usable.
+ """
+ title = ""
+ if "<" in html_or_text and ">" in html_or_text:
+ title_match = _TITLE_RE.search(html_or_text)
+ if title_match:
+ title = re.sub(r"\s+", " ", title_match.group(1)).strip()
+ stripped = _SCRIPT_STYLE_RE.sub(" ", html_or_text)
+ stripped = _TAG_RE.sub(" ", stripped)
+ # Decode common entities cheaply (full entity table is overkill).
+ stripped = (
+ stripped.replace("&nbsp;", " ")
+ .replace("&amp;", "&")
+ .replace("&lt;", "<")
+ .replace("&gt;", ">")
+ .replace("&quot;", '"')
+ .replace("&#39;", "'")
+ )
+ body = stripped
+ else:
+ body = html_or_text
+ body = _WHITESPACE_RE.sub(" ", body)
+ body = "\n".join(line.strip() for line in body.splitlines())
+ body = _BLANK_LINE_RE.sub("\n\n", body).strip()
+ if title:
+ body = f"# {title}\n\n{body}"
+ return title, body
+
+
+__all__ = [
+ "DEFAULT_MAX_CHARS",
+ "FetchOutcome",
+ "fetch_url_as_markdown",
+]
diff --git a/deeptutor/tools/write_note.py b/deeptutor/tools/write_note.py
new file mode 100644
index 000000000..c03e6beb5
--- /dev/null
+++ b/deeptutor/tools/write_note.py
@@ -0,0 +1,479 @@
+"""Create or edit a single notebook record from the chat agent.
+
+Replaces the older ``save_to_notebook`` tool. Two modes:
+
+* **append**: create a NEW record in the target notebook. The body is
+ either an auto-rendered transcript (when ``content`` is empty — the
+ default; mirrors a human clicking 'Save to notebook' on the recent
+ chat) or an agent-authored markdown body (when ``content`` is
+ provided — for the 'write a summary into the notebook' use case).
+* **edit**: update an EXISTING record's title and/or body and/or
+ summary. The agent must know the ``record_id`` (typically obtained
+ via the ``list_notebook`` tool).
+
+The append mode preserves the actual conversation by default; the
+agent does not author the body unless it explicitly chooses to. This
+matches the user's expectation that the saved record reflect what was
+actually said, not a summary the LLM invented.
+
+Dependency-injected for tests (``notebook_manager``,
+``conversation_history``, ``current_user_message``); the chat pipeline
+wires in the live values via ``_augment_tool_kwargs``.
+"""
+
+from __future__ import annotations
+
+import logging
+from dataclasses import dataclass
+from typing import Any, Iterable
+
+logger = logging.getLogger(__name__)
+
+# Length sanity caps. Generous because the tool now legitimately needs
+# to support saving arbitrarily long transcripts (the user requested
+# "保存任意长度的对话记录"). The 200k cap below corresponds to roughly
+# 50k tokens of conversation — well beyond any reasonable single chat
+# session — and still leaves headroom in the notebook UI.
+MAX_TITLE_CHARS = 200
+MAX_NOTE_CHARS = 4_000
+MAX_CONTENT_CHARS = 200_000
+# Append-mode ``turns_to_include`` accepts integers 1..N OR the
+# literal string "all" to capture every turn currently in scope. Tests
+# pin the default to 3 (= a sensible "couple of recent turns" slice).
+DEFAULT_TURNS_TO_INCLUDE = 3
+ALL_TURNS_SENTINEL = "all"
+
+VALID_MODES = ("append", "edit")
+
+
+@dataclass(frozen=True)
+class WriteOutcome:
+ """Result of a single ``write_note`` invocation."""
+
+ ok: bool
+ mode: str = ""
+ record_id: str = ""
+ notebook_id: str = ""
+ notebook_name: str = ""
+ error: str = ""
+
+
+def write_note(
+ *,
+ mode: str,
+ notebook_id: str,
+ record_id: str = "",
+ title: str = "",
+ content: str = "",
+ turns_to_include: Any = DEFAULT_TURNS_TO_INCLUDE,
+ note: str = "",
+ conversation_history: Iterable[dict[str, Any]] | None = None,
+ current_user_message: str = "",
+ notebook_manager: Any = None,
+) -> WriteOutcome:
+ """Dispatch on ``mode`` and forward to the append / edit helpers.
+
+ Errors are returned as ``WriteOutcome(ok=False, error=...)`` rather
+ than raising — the chat loop converts the result back into an
+ LLM-visible tool result.
+ """
+ cleaned_mode = (mode or "").strip().lower()
+ if cleaned_mode not in VALID_MODES:
+ return WriteOutcome(
+ ok=False,
+ error=(
+ f"Unknown mode {mode!r}. Use one of: "
+ + ", ".join(repr(m) for m in VALID_MODES)
+ + "."
+ ),
+ )
+
+ nid = (notebook_id or "").strip()
+ if not nid:
+ return WriteOutcome(ok=False, mode=cleaned_mode, error="notebook_id is required.")
+
+ manager = notebook_manager
+ if manager is None:
+ from deeptutor.services.notebook import get_notebook_manager
+
+ manager = get_notebook_manager()
+
+ notebooks = manager.list_notebooks()
+ if not isinstance(notebooks, list) or not notebooks:
+ return WriteOutcome(
+ ok=False,
+ mode=cleaned_mode,
+ error="No notebooks are available for this user.",
+ )
+ matched = next(
+ (nb for nb in notebooks if str(nb.get("id") or "").strip() == nid),
+ None,
+ )
+ if matched is None:
+ valid_ids = ", ".join(
+ f"`{nb.get('id')}`" for nb in notebooks if nb.get("id")
+ )
+ return WriteOutcome(
+ ok=False,
+ mode=cleaned_mode,
+ error=(
+ f"Unknown notebook_id {nid!r}. "
+ f"Valid ids: {valid_ids or '(none)'}."
+ ),
+ )
+
+ notebook_name = str(matched.get("name") or matched.get("title") or nid)
+
+ if cleaned_mode == "append":
+ return _do_append(
+ manager=manager,
+ notebook_id=nid,
+ notebook_name=notebook_name,
+ title=title,
+ content=content,
+ turns_to_include=turns_to_include,
+ note=note,
+ conversation_history=list(conversation_history or []),
+ current_user_message=str(current_user_message or "").strip(),
+ )
+ return _do_edit(
+ manager=manager,
+ notebook_id=nid,
+ notebook_name=notebook_name,
+ record_id=record_id,
+ title=title,
+ content=content,
+ note=note,
+ )
+
+
+# ---------------------------------------------------------------------------
+# Append mode
+# ---------------------------------------------------------------------------
+
+
+def _do_append(
+ *,
+ manager: Any,
+ notebook_id: str,
+ notebook_name: str,
+ title: str,
+ content: str,
+ turns_to_include: Any,
+ note: str,
+ conversation_history: list[dict[str, Any]],
+ current_user_message: str,
+) -> WriteOutcome:
+ cleaned_title = (title or "").strip()
+ if not cleaned_title:
+ return WriteOutcome(
+ ok=False,
+ mode="append",
+ notebook_id=notebook_id,
+ notebook_name=notebook_name,
+ error="title must not be empty in append mode.",
+ )
+ if len(cleaned_title) > MAX_TITLE_CHARS:
+ cleaned_title = cleaned_title[:MAX_TITLE_CHARS].rstrip() + "…"
+ cleaned_note = (note or "").strip()
+ if len(cleaned_note) > MAX_NOTE_CHARS:
+ cleaned_note = cleaned_note[:MAX_NOTE_CHARS].rstrip() + "…"
+
+ explicit_content = (content or "").strip()
+ if explicit_content:
+ # Agent-authored body: trust it. This is for the
+ # "save a summary into the notebook" use case.
+ transcript = explicit_content
+ else:
+ # Default: render the real conversation. Agent does not author.
+ transcript = _format_transcript(
+ conversation_history=conversation_history,
+ current_user_message=current_user_message,
+ turns_to_include=_coerce_turns(turns_to_include),
+ )
+
+ if not transcript.strip():
+ return WriteOutcome(
+ ok=False,
+ mode="append",
+ notebook_id=notebook_id,
+ notebook_name=notebook_name,
+ error=(
+ "Nothing to save: the chat history is empty and no "
+ "explicit content was provided. Either wait until "
+ "there's a user+assistant exchange, or pass `content` "
+ "directly."
+ ),
+ )
+
+ body_parts: list[str] = []
+ if cleaned_note:
+ body_parts.append(f"**Note:** {cleaned_note}")
+ body_parts.append(transcript)
+ cleaned_content = "\n\n---\n\n".join(body_parts).strip()
+ if len(cleaned_content) > MAX_CONTENT_CHARS:
+ cleaned_content = (
+ cleaned_content[:MAX_CONTENT_CHARS].rstrip() + "\n…[truncated]"
+ )
+
+ from deeptutor.services.notebook.service import RecordType
+
+ user_query_for_record = current_user_message or _last_user_message(
+ conversation_history
+ )
+
+ try:
+ outcome = manager.add_record(
+ notebook_ids=[notebook_id],
+ record_type=RecordType.CHAT,
+ title=cleaned_title,
+ user_query=user_query_for_record,
+ output=cleaned_content,
+ summary=cleaned_note or _summary_from_transcript(transcript),
+ metadata={
+ "source": "write_note_tool",
+ "mode": "append",
+ "note_provided": bool(cleaned_note),
+ "explicit_content": bool(explicit_content),
+ },
+ )
+ except Exception as exc:
+ logger.warning("write_note(append): add_record failed", exc_info=True)
+ return WriteOutcome(
+ ok=False,
+ mode="append",
+ notebook_id=notebook_id,
+ notebook_name=notebook_name,
+ error=f"Save failed: {exc}",
+ )
+
+ record = (outcome or {}).get("record") if isinstance(outcome, dict) else None
+ record_id = str((record or {}).get("id") or "")
+ if not record_id:
+ return WriteOutcome(
+ ok=False,
+ mode="append",
+ notebook_id=notebook_id,
+ notebook_name=notebook_name,
+ error="Notebook service did not return a record id.",
+ )
+ return WriteOutcome(
+ ok=True,
+ mode="append",
+ record_id=record_id,
+ notebook_id=notebook_id,
+ notebook_name=notebook_name,
+ )
+
+
+def _coerce_turns(raw: Any) -> int | None:
+ """Return a positive integer or ``None`` meaning 'all turns'."""
+ if isinstance(raw, str) and raw.strip().lower() == ALL_TURNS_SENTINEL:
+ return None
+ try:
+ value = int(raw)
+ except (TypeError, ValueError):
+ return DEFAULT_TURNS_TO_INCLUDE
+ return max(1, value)
+
+
+# ---------------------------------------------------------------------------
+# Edit mode
+# ---------------------------------------------------------------------------
+
+
+def _do_edit(
+ *,
+ manager: Any,
+ notebook_id: str,
+ notebook_name: str,
+ record_id: str,
+ title: str,
+ content: str,
+ note: str,
+) -> WriteOutcome:
+ rid = (record_id or "").strip()
+ if not rid:
+ return WriteOutcome(
+ ok=False,
+ mode="edit",
+ notebook_id=notebook_id,
+ notebook_name=notebook_name,
+ error="record_id is required in edit mode.",
+ )
+
+ existing = manager.get_record(notebook_id, rid) if hasattr(manager, "get_record") else None
+ if existing is None:
+ return WriteOutcome(
+ ok=False,
+ mode="edit",
+ notebook_id=notebook_id,
+ notebook_name=notebook_name,
+ error=(
+ f"Record {rid!r} not found in notebook {notebook_id!r}. "
+ "Call `list_notebook` with this notebook_id first to "
+ "discover valid record ids."
+ ),
+ )
+
+ cleaned_title = (title or "").strip()
+ if cleaned_title and len(cleaned_title) > MAX_TITLE_CHARS:
+ cleaned_title = cleaned_title[:MAX_TITLE_CHARS].rstrip() + "…"
+ cleaned_content = (content or "").strip()
+ if cleaned_content and len(cleaned_content) > MAX_CONTENT_CHARS:
+ cleaned_content = (
+ cleaned_content[:MAX_CONTENT_CHARS].rstrip() + "\n…[truncated]"
+ )
+ cleaned_note = (note or "").strip()
+ if cleaned_note and len(cleaned_note) > MAX_NOTE_CHARS:
+ cleaned_note = cleaned_note[:MAX_NOTE_CHARS].rstrip() + "…"
+
+ if not (cleaned_title or cleaned_content or cleaned_note):
+ return WriteOutcome(
+ ok=False,
+ mode="edit",
+ notebook_id=notebook_id,
+ notebook_name=notebook_name,
+ error=(
+ "edit mode requires at least one of `title`, `content`, "
+ "or `note` to change."
+ ),
+ )
+
+ update_kwargs: dict[str, Any] = {}
+ if cleaned_title:
+ update_kwargs["title"] = cleaned_title
+ if cleaned_content:
+ update_kwargs["output"] = cleaned_content
+ if cleaned_note:
+ update_kwargs["summary"] = cleaned_note
+
+ try:
+ updated = manager.update_record(notebook_id, rid, **update_kwargs)
+ except Exception as exc:
+ logger.warning("write_note(edit): update_record failed", exc_info=True)
+ return WriteOutcome(
+ ok=False,
+ mode="edit",
+ notebook_id=notebook_id,
+ notebook_name=notebook_name,
+ error=f"Edit failed: {exc}",
+ )
+ if updated is None:
+ return WriteOutcome(
+ ok=False,
+ mode="edit",
+ notebook_id=notebook_id,
+ notebook_name=notebook_name,
+ error="Notebook service rejected the update (record vanished?).",
+ )
+
+ return WriteOutcome(
+ ok=True,
+ mode="edit",
+ record_id=rid,
+ notebook_id=notebook_id,
+ notebook_name=notebook_name,
+ )
+
+
+# ---------------------------------------------------------------------------
+# Shared helpers
+# ---------------------------------------------------------------------------
+
+
+def _format_transcript(
+ *,
+ conversation_history: list[dict[str, Any]],
+ current_user_message: str,
+ turns_to_include: int | None,
+) -> str:
+ """Render a slice of the chat as a markdown Q&A block.
+
+ ``turns_to_include=None`` means "every turn currently in scope" —
+ used when the agent passes ``turns_to_include='all'``. Otherwise
+ we slice the most-recent N user+assistant pairs.
+
+ The "current turn" (the one this tool is being called from)
+ appears LAST: the user's latest message + a placeholder marker
+ because the assistant's response isn't finalised yet.
+ """
+ pairs: list[tuple[str, str]] = []
+ pending_user: str | None = None
+ for entry in conversation_history:
+ role = str(entry.get("role") or "").strip().lower()
+ content = entry.get("content")
+ text = _coerce_text(content)
+ if not text:
+ continue
+ if role == "user":
+ if pending_user is not None:
+ pairs.append((pending_user, ""))
+ pending_user = text
+ continue
+ if role == "assistant":
+ pairs.append((pending_user or "", text))
+ pending_user = None
+ continue
+ if pending_user is not None:
+ pairs.append((pending_user, ""))
+ if current_user_message:
+ pairs.append((current_user_message, ""))
+
+ if turns_to_include is None:
+ selected = pairs
+ else:
+ selected = pairs[-turns_to_include:] if pairs else []
+
+ blocks: list[str] = []
+ for user_text, assistant_text in selected:
+ if user_text:
+ blocks.append(f"### User\n\n{user_text}")
+ if assistant_text:
+ blocks.append(f"### Assistant\n\n{assistant_text}")
+ elif user_text:
+ blocks.append("### Assistant\n\n_(assistant response in progress)_")
+ return "\n\n---\n\n".join(blocks)
+
+
+def _coerce_text(content: Any) -> str:
+ if isinstance(content, list):
+ return "\n".join(
+ str(part.get("text") or "")
+ for part in content
+ if isinstance(part, dict) and part.get("type") == "text"
+ ).strip()
+ return str(content or "").strip()
+
+
+def _last_user_message(conversation_history: list[dict[str, Any]]) -> str:
+ """Return the most-recent non-empty user message text, or ``""``."""
+ for entry in reversed(conversation_history):
+ if str(entry.get("role") or "").lower() != "user":
+ continue
+ text = _coerce_text(entry.get("content"))
+ if text:
+ return text
+ return ""
+
+
+def _summary_from_transcript(transcript: str, *, limit: int = 240) -> str:
+ """Pick a first non-heading, non-blank line to use as the summary."""
+ for line in transcript.splitlines():
+ line = line.strip()
+ if not line or line.startswith("#") or line == "---":
+ continue
+ return line[:limit].rstrip() + ("…" if len(line) > limit else "")
+ return ""
+
+
+__all__ = [
+ "ALL_TURNS_SENTINEL",
+ "DEFAULT_TURNS_TO_INCLUDE",
+ "MAX_CONTENT_CHARS",
+ "MAX_NOTE_CHARS",
+ "MAX_TITLE_CHARS",
+ "VALID_MODES",
+ "WriteOutcome",
+ "write_note",
+]
diff --git a/tests/agents/auto/test_delegation.py b/tests/agents/auto/test_delegation.py
index 7835c2b52..0ec6c2d37 100644
--- a/tests/agents/auto/test_delegation.py
+++ b/tests/agents/auto/test_delegation.py
@@ -173,9 +173,7 @@ async def test_delegate_happy_path_forwards_events_with_metadata():
_evt(StreamEventType.RESULT, metadata={"response": "ok"}),
],
)
- with patch(
- "deeptutor.agents.auto.delegation.get_capability_registry"
- ) as mock_get_reg:
+ with patch("deeptutor.agents.auto.delegation.get_capability_registry") as mock_get_reg:
mock_get_reg.return_value.get.return_value = fake
result = await delegate_to_capability(
@@ -217,9 +215,7 @@ async def test_delegate_injects_call_id_into_content_without_one():
),
],
)
- with patch(
- "deeptutor.agents.auto.delegation.get_capability_registry"
- ) as mock_get_reg:
+ with patch("deeptutor.agents.auto.delegation.get_capability_registry") as mock_get_reg:
mock_get_reg.return_value.get.return_value = fake
result = await delegate_to_capability(
cap_name="deep_solve",
@@ -242,9 +238,7 @@ async def test_delegate_injects_call_id_into_content_without_one():
async def test_delegate_captures_raise_as_failure():
parent_bus = StreamBus()
fake = _FakeCapability(name="boom", raise_exc=RuntimeError("kaboom"))
- with patch(
- "deeptutor.agents.auto.delegation.get_capability_registry"
- ) as mock_get_reg:
+ with patch("deeptutor.agents.auto.delegation.get_capability_registry") as mock_get_reg:
mock_get_reg.return_value.get.return_value = fake
result = await delegate_to_capability(
cap_name="boom",
@@ -265,9 +259,7 @@ async def test_delegate_marks_failure_on_error_event():
name="errorful",
events=[_evt(StreamEventType.ERROR, content="problem")],
)
- with patch(
- "deeptutor.agents.auto.delegation.get_capability_registry"
- ) as mock_get_reg:
+ with patch("deeptutor.agents.auto.delegation.get_capability_registry") as mock_get_reg:
mock_get_reg.return_value.get.return_value = fake
result = await delegate_to_capability(
cap_name="errorful",
@@ -283,9 +275,7 @@ async def test_delegate_marks_failure_on_error_event():
@pytest.mark.asyncio
async def test_delegate_unknown_capability_returns_failure():
parent_bus = StreamBus()
- with patch(
- "deeptutor.agents.auto.delegation.get_capability_registry"
- ) as mock_get_reg:
+ with patch("deeptutor.agents.auto.delegation.get_capability_registry") as mock_get_reg:
mock_get_reg.return_value.get.return_value = None
result = await delegate_to_capability(
cap_name="nonexistent",
diff --git a/tests/agents/chat/test_agentic_parallel_tools.py b/tests/agents/chat/test_agentic_parallel_tools.py
index 2021e332f..ff70fb8c8 100644
--- a/tests/agents/chat/test_agentic_parallel_tools.py
+++ b/tests/agents/chat/test_agentic_parallel_tools.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import asyncio
+import json
from types import SimpleNamespace
from typing import Any
@@ -25,6 +26,59 @@ async def _collect_bus_events(bus: StreamBus) -> tuple[list[StreamEvent], asynci
await asyncio.sleep(0)
return events, consumer # type: ignore[return-value]
+
+def _llm_chunk(
+ *,
+ content: str | None = None,
+ tool_calls: list[dict[str, Any]] | None = None,
+) -> SimpleNamespace:
+ delta_fields: dict[str, Any] = {"content": content}
+ if tool_calls is not None:
+ delta_fields["tool_calls"] = [
+ SimpleNamespace(
+ index=tc.get("index", i),
+ id=tc.get("id"),
+ function=SimpleNamespace(
+ name=tc.get("name"),
+ arguments=tc.get("arguments"),
+ ),
+ )
+ for i, tc in enumerate(tool_calls)
+ ]
+ else:
+ delta_fields["tool_calls"] = None
+ return SimpleNamespace(choices=[SimpleNamespace(delta=SimpleNamespace(**delta_fields))])
+
+
+async def _async_llm_stream(chunks: list[SimpleNamespace]):
+ for chunk in chunks:
+ yield chunk
+
+
+class _ScriptedChatClient:
+ def __init__(self, scripted: list[list[SimpleNamespace]]) -> None:
+ self._script = list(scripted)
+ self.call_count = 0
+ self.calls: list[dict[str, Any]] = []
+
+ class _Completions:
+ def __init__(self, parent: _ScriptedChatClient) -> None:
+ self.parent = parent
+
+ async def create(self, **kwargs):
+ self.parent.call_count += 1
+ self.parent.calls.append({**kwargs, "messages": list(kwargs.get("messages") or [])})
+ if not self.parent._script:
+ raise RuntimeError("Scripted client exhausted")
+ return _async_llm_stream(self.parent._script.pop(0))
+
+ class _Chat:
+ def __init__(self, parent: _ScriptedChatClient) -> None:
+ self.completions = _Completions(parent)
+
+ self.chat = _Chat(self)
+
+
@pytest.mark.asyncio
async def test_execute_tool_call_streams_retrieve_progress_for_rag(
monkeypatch: pytest.MonkeyPatch,
@@ -113,7 +167,28 @@ async def test_execute_tool_call_streams_retrieve_progress_for_rag(
]
-def test_compose_enabled_tools_injects_rag_when_kb_selected() -> None:
+_ALWAYS_ON_TOOLS = ["write_memory", "web_fetch", "github", "ask_user"]
+
+
+def _stub_optional_services(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Pin auto-mount gates to ``False`` so tests see ONLY the tools each
+ case explicitly asserts on. Without this the dev workspace's real
+ memory / notebook contents could non-deterministically inject extra
+ tools and flake the assertions."""
+ monkeypatch.setattr(
+ "deeptutor.services.memory.get_memory_store",
+ lambda: SimpleNamespace(read_raw=lambda *_args, **_kwargs: ""),
+ )
+ monkeypatch.setattr(
+ "deeptutor.services.notebook.get_notebook_manager",
+ lambda: SimpleNamespace(list_notebooks=lambda: []),
+ )
+
+
+def test_compose_enabled_tools_injects_rag_when_kb_selected(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ _stub_optional_services(monkeypatch)
pipeline = AgenticChatPipeline.__new__(AgenticChatPipeline)
pipeline.registry = SimpleNamespace(
get_enabled=lambda selected: [SimpleNamespace(name=n) for n in selected]
@@ -123,21 +198,144 @@ def test_compose_enabled_tools_injects_rag_when_kb_selected() -> None:
enabled_tools=["web_search"],
knowledge_bases=["kb-a"],
)
- assert pipeline._compose_enabled_tools(context) == ["web_search", "rag"]
+ assert pipeline._compose_enabled_tools(context) == [
+ "web_search",
+ "rag",
+ *_ALWAYS_ON_TOOLS,
+ ]
-def test_compose_enabled_tools_omits_rag_when_no_kb() -> None:
+def test_compose_enabled_tools_omits_rag_when_no_kb(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ _stub_optional_services(monkeypatch)
pipeline = AgenticChatPipeline.__new__(AgenticChatPipeline)
pipeline.registry = SimpleNamespace(
get_enabled=lambda selected: [SimpleNamespace(name=n) for n in selected]
)
- # Legacy callers may still send "rag" in enabled_tools — it gets stripped.
+ # ``rag`` is not user-toggleable — even if a caller passes it in
+ # ``enabled_tools``, the ``CHAT_OPTIONAL_TOOLS`` filter drops it, and
+ # without an attached KB it does not get auto-mounted either.
context = UnifiedContext(
user_message="hi",
enabled_tools=["rag", "web_search"],
knowledge_bases=[],
)
- assert pipeline._compose_enabled_tools(context) == ["web_search"]
+ assert pipeline._compose_enabled_tools(context) == [
+ "web_search",
+ *_ALWAYS_ON_TOOLS,
+ ]
+
+
+def test_compose_enabled_tools_auto_mounts_read_memory(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """``read_memory`` joins the tool set iff the active user has memory."""
+ monkeypatch.setattr(
+ "deeptutor.services.memory.get_memory_store",
+ lambda: SimpleNamespace(read_raw=lambda *_args, **_kwargs: "some content"),
+ )
+ monkeypatch.setattr(
+ "deeptutor.services.notebook.get_notebook_manager",
+ lambda: SimpleNamespace(list_notebooks=lambda: []),
+ )
+ pipeline = AgenticChatPipeline.__new__(AgenticChatPipeline)
+ pipeline.registry = SimpleNamespace(
+ get_enabled=lambda selected: [SimpleNamespace(name=n) for n in selected]
+ )
+ context = UnifiedContext(
+ user_message="hi",
+ enabled_tools=[],
+ knowledge_bases=[],
+ )
+ assert pipeline._compose_enabled_tools(context) == [
+ "read_memory",
+ *_ALWAYS_ON_TOOLS,
+ ]
+
+
+def test_compose_enabled_tools_auto_mounts_notebook_pair(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """``list_notebook`` + ``write_note`` mount together iff user has notebooks."""
+ monkeypatch.setattr(
+ "deeptutor.services.memory.get_memory_store",
+ lambda: SimpleNamespace(read_raw=lambda *_args, **_kwargs: ""),
+ )
+ monkeypatch.setattr(
+ "deeptutor.services.notebook.get_notebook_manager",
+ lambda: SimpleNamespace(list_notebooks=lambda: [{"id": "nb-1", "name": "Math"}]),
+ )
+ pipeline = AgenticChatPipeline.__new__(AgenticChatPipeline)
+ pipeline.registry = SimpleNamespace(
+ get_enabled=lambda selected: [SimpleNamespace(name=n) for n in selected]
+ )
+ context = UnifiedContext(user_message="hi", enabled_tools=[], knowledge_bases=[])
+ assert pipeline._compose_enabled_tools(context) == [
+ "list_notebook",
+ "write_note",
+ *_ALWAYS_ON_TOOLS,
+ ]
+
+
+def test_augment_tool_kwargs_injects_geogebra_image(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """``geogebra_analysis`` is server-side wired: the LLM never sees the
+ raw image bytes, so the pipeline must inject the first image
+ attachment's base64 into the kwargs (overwriting any value the LLM
+ may have hallucinated) before the tool runs. Without this, the
+ underlying VisionSolverAgent fails fast with 'No image provided.'.
+ """
+ from deeptutor.core.context import Attachment
+
+ pipeline = AgenticChatPipeline.__new__(AgenticChatPipeline)
+ pipeline.language = "zh"
+ context = UnifiedContext(
+ user_message="solve this triangle",
+ attachments=[
+ Attachment(
+ type="image",
+ base64="REAL_IMG_BYTES",
+ filename="problem.png",
+ mime_type="image/png",
+ ),
+ ],
+ language="zh",
+ )
+
+ # LLM-provided kwargs may include a hallucinated image_base64; we
+ # must overwrite it from the attachment AND wrap it as a data URI so
+ # the vision LLM accepts the image (otherwise all 4 pipeline stages
+ # silently fail with a malformed image_url).
+ augmented = pipeline._augment_tool_kwargs(
+ "geogebra_analysis",
+ {"image_base64": "HALLUCINATED", "question": "stale question"},
+ context,
+ )
+
+ assert augmented["image_base64"] == "data:image/png;base64,REAL_IMG_BYTES"
+ assert augmented["language"] == "zh"
+
+
+def test_augment_tool_kwargs_geogebra_no_image_passes_through(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """When the user toggled geogebra_analysis on but uploaded no image,
+ the pipeline leaves ``image_base64`` empty; the tool itself reports
+ the friendly 'No image provided.' error rather than the pipeline
+ silently hiding the tool. This keeps the contract observable in
+ chat history."""
+ pipeline = AgenticChatPipeline.__new__(AgenticChatPipeline)
+ pipeline.language = "en"
+ context = UnifiedContext(
+ user_message="describe figure",
+ attachments=[],
+ language="en",
+ )
+ augmented = pipeline._augment_tool_kwargs("geogebra_analysis", {}, context)
+ assert "image_base64" not in augmented or augmented["image_base64"] == ""
+ assert augmented["language"] == "en"
def test_kb_note_lists_attached_knowledge_bases() -> None:
@@ -153,6 +351,729 @@ def test_kb_note_lists_attached_knowledge_bases() -> None:
assert "kb_name must" in note
+async def test_dispatch_records_pause_when_tool_emits_pause_for_user(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """``ask_user``-style pause requests surface on ``_DispatchOutcome``.
+
+ The dispatch step must (a) preserve the paused tool's ``tool_call_id``
+ so the pipeline can later overwrite the right ``role=tool`` message
+ content, and (b) carry the structured ``ask_user`` payload through to
+ the loop for the pending-user-input UI hint. Terminate/pause are
+ mutually exclusive — pause does NOT set the terminate flag.
+ """
+ monkeypatch.setattr(
+ "deeptutor.agents.chat.agentic_pipeline.get_llm_config",
+ lambda: SimpleNamespace(
+ binding="openai", model="gpt-test", api_key="k", base_url="u", api_version=None
+ ),
+ )
+
+ class _PausingRegistry:
+ def get_enabled(self, selected):
+ return [SimpleNamespace(name=name) for name in selected]
+
+ async def execute(self, name: str, **kwargs):
+ assert name == "ask_user"
+ ask_user = {"question": "Lecture or exam?", "options": ["Lecture", "Exam"]}
+ return ToolResult(
+ content="[awaiting user reply]",
+ metadata={"ask_user": ask_user},
+ pause_for_user=ask_user,
+ )
+
+ pipeline = AgenticChatPipeline(language="en")
+ pipeline.registry = _PausingRegistry()
+
+ context = UnifiedContext(
+ session_id="s1",
+ user_message="help me",
+ metadata={"turn_id": "t1"},
+ )
+ bus = StreamBus()
+ events, consumer = await _collect_bus_events(bus)
+
+ outcome = await pipeline._dispatch_tool_calls(
+ tool_calls=[
+ {"id": "call-1", "name": "ask_user", "arguments": "{}"},
+ ],
+ context=context,
+ stream=bus,
+ iteration_index=0,
+ )
+ await asyncio.sleep(0)
+ await bus.close()
+ await consumer
+
+ assert outcome.pause is True
+ assert outcome.terminate is False
+ assert outcome.pause_tool_call_id == "call-1"
+ assert outcome.pause_payload is not None
+ assert outcome.pause_payload["tool_name"] == "ask_user"
+ assert outcome.pause_payload["ask_user"]["question"] == "Lecture or exam?"
+ # The placeholder content still lands in the role=tool message; the
+ # pipeline (not _dispatch_tool_calls) is responsible for overwriting
+ # it with the user's reply once it arrives.
+ assert outcome.tool_messages[0]["content"].startswith("[awaiting user reply")
+
+
+async def test_dispatch_collapses_duplicate_parallel_tool_calls(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Identical parallel tool_calls execute once; later duplicates get a stub.
+
+ Guards against the LLM emitting two ``ask_user`` calls with the same
+ args in a single assistant message (which would otherwise render two
+ cards and only resolve the first one). The protocol-level
+ tool_call/tool_message pairing is preserved internally — one
+ ``role=tool`` message per emitted ``tool_call_id`` — but duplicate
+ ``ask_user`` calls are hidden from the user-facing trace stream.
+ """
+ monkeypatch.setattr(
+ "deeptutor.agents.chat.agentic_pipeline.get_llm_config",
+ lambda: SimpleNamespace(
+ binding="openai", model="gpt-test", api_key="k", base_url="u", api_version=None
+ ),
+ )
+
+ exec_count = 0
+
+ class _PausingRegistry:
+ def get_enabled(self, selected):
+ return [SimpleNamespace(name=name) for name in selected]
+
+ async def execute(self, name: str, **kwargs):
+ nonlocal exec_count
+ exec_count += 1
+ assert name == "ask_user"
+ ask_user = {"question": "Lecture or exam?", "options": ["Lecture", "Exam"]}
+ return ToolResult(
+ content="[awaiting user reply]",
+ metadata={"ask_user": ask_user},
+ pause_for_user=ask_user,
+ )
+
+ pipeline = AgenticChatPipeline(language="en")
+ pipeline.registry = _PausingRegistry()
+
+ context = UnifiedContext(
+ session_id="s1",
+ user_message="help me",
+ metadata={"turn_id": "t1"},
+ )
+ bus = StreamBus()
+ events, consumer = await _collect_bus_events(bus)
+
+ outcome = await pipeline._dispatch_tool_calls(
+ tool_calls=[
+ {"id": "call-1", "name": "ask_user", "arguments": "{}"},
+ {"id": "call-2", "name": "ask_user", "arguments": "{}"},
+ ],
+ context=context,
+ stream=bus,
+ iteration_index=0,
+ )
+ await asyncio.sleep(0)
+ await bus.close()
+ await consumer
+
+ # Tool was only run for the primary; duplicate short-circuited.
+ assert exec_count == 1
+ # Pause is tracked on the primary; the duplicate does not produce a
+ # second pause payload.
+ assert outcome.pause is True
+ assert outcome.pause_tool_call_id == "call-1"
+ # Both tool_call_ids get a role=tool message so the next OpenAI call
+ # has matched pairs, but only one carries the awaiting placeholder.
+ assert len(outcome.tool_messages) == 2
+ assert outcome.tool_messages[0]["tool_call_id"] == "call-1"
+ assert outcome.tool_messages[0]["content"].startswith("[awaiting user reply")
+ assert outcome.tool_messages[1]["tool_call_id"] == "call-2"
+ assert "duplicate parallel ask_user" in outcome.tool_messages[1]["content"]
+ assert "call-1" in outcome.tool_messages[1]["content"]
+ # Only the primary ask_user call is visible in the trace stream; the
+ # duplicate stub stays internal so the frontend renders one trace row
+ # and one card.
+ ask_user_tool_calls = [e for e in events if e.type == "tool_call" and e.content == "ask_user"]
+ assert len(ask_user_tool_calls) == 1
+ tool_results_with_ask_user = [
+ e
+ for e in events
+ if e.type == "tool_result"
+ and isinstance(e.metadata.get("tool_metadata"), dict)
+ and "ask_user" in e.metadata["tool_metadata"]
+ ]
+ assert len(tool_results_with_ask_user) == 1
+
+
+async def test_dispatch_allows_only_one_parallel_ask_user_even_with_different_args(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Any second ask_user in the same tool batch is suppressed.
+
+ The LLM is instructed to bundle multiple questions into one
+ ``questions`` array. If it instead emits multiple ask_user tool_calls
+ with different args, the first call is the only one that pauses and
+ the only one visible to the frontend; later calls get internal stub
+ tool messages to preserve API protocol pairing.
+ """
+ monkeypatch.setattr(
+ "deeptutor.agents.chat.agentic_pipeline.get_llm_config",
+ lambda: SimpleNamespace(
+ binding="openai", model="gpt-test", api_key="k", base_url="u", api_version=None
+ ),
+ )
+
+ executed: list[dict[str, object]] = []
+
+ class _PausingRegistry:
+ def get_enabled(self, selected):
+ return [SimpleNamespace(name=name) for name in selected]
+
+ async def execute(self, name: str, **kwargs):
+ executed.append({"name": name, "kwargs": kwargs})
+ assert name == "ask_user"
+ ask_user = {
+ "questions": [
+ {
+ "id": "q",
+ "prompt": str(kwargs.get("question") or "Question?"),
+ "options": [],
+ }
+ ]
+ }
+ return ToolResult(
+ content="[awaiting user reply]",
+ metadata={"ask_user": ask_user},
+ pause_for_user=ask_user,
+ )
+
+ pipeline = AgenticChatPipeline(language="en")
+ pipeline.registry = _PausingRegistry()
+ context = UnifiedContext(
+ session_id="s1",
+ user_message="help me",
+ metadata={"turn_id": "t1"},
+ )
+ bus = StreamBus()
+ events, consumer = await _collect_bus_events(bus)
+
+ outcome = await pipeline._dispatch_tool_calls(
+ tool_calls=[
+ {"id": "call-1", "name": "ask_user", "arguments": '{"question":"First?"}'},
+ {"id": "call-2", "name": "ask_user", "arguments": '{"question":"Second?"}'},
+ ],
+ context=context,
+ stream=bus,
+ iteration_index=0,
+ )
+ await asyncio.sleep(0)
+ await bus.close()
+ await consumer
+
+ assert len(executed) == 1
+ assert outcome.pause is True
+ assert outcome.pause_tool_call_id == "call-1"
+ assert len(outcome.tool_messages) == 2
+ assert outcome.tool_messages[0]["content"].startswith("[awaiting user reply")
+ assert "duplicate parallel ask_user" in outcome.tool_messages[1]["content"]
+ assert "call-1" in outcome.tool_messages[1]["content"]
+ ask_user_tool_calls = [e for e in events if e.type == "tool_call" and e.content == "ask_user"]
+ assert len(ask_user_tool_calls) == 1
+ ask_user_results = [
+ e
+ for e in events
+ if e.type == "tool_result"
+ and isinstance(e.metadata.get("tool_metadata"), dict)
+ and "ask_user" in e.metadata["tool_metadata"]
+ ]
+ assert len(ask_user_results) == 1
+
+
+async def test_await_user_reply_overwrites_matching_tool_message(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The waiter result must land in the *paused* tool message, not the
+ sibling ones — matched by ``tool_call_id``."""
+ monkeypatch.setattr(
+ "deeptutor.agents.chat.agentic_pipeline.get_llm_config",
+ lambda: SimpleNamespace(
+ binding="openai", model="gpt-test", api_key="k", base_url="u", api_version=None
+ ),
+ )
+ pipeline = AgenticChatPipeline(language="en")
+
+ from deeptutor.agents.chat.agentic_pipeline import _DispatchOutcome
+
+ paused_msg = {
+ "role": "tool",
+ "tool_call_id": "call-pause",
+ "name": "ask_user",
+ "content": "[awaiting user reply]",
+ }
+ sibling_msg = {
+ "role": "tool",
+ "tool_call_id": "call-other",
+ "name": "rag",
+ "content": "rag answer",
+ }
+ dispatch = _DispatchOutcome(
+ sources=[],
+ tool_messages=[paused_msg, sibling_msg],
+ pause=True,
+ pause_payload={
+ "tool_name": "ask_user",
+ "ask_user": {"question": "?", "options": []},
+ },
+ pause_tool_call_id="call-pause",
+ )
+
+ async def _waiter() -> str:
+ return "Lecture"
+
+ context = UnifiedContext(
+ session_id="s1",
+ user_message="m",
+ metadata={"turn_id": "t1", "wait_for_user_reply": _waiter},
+ )
+ bus = StreamBus()
+ _events, consumer = await _collect_bus_events(bus)
+
+ resumed = await pipeline._await_user_reply_and_resolve(
+ context=context, stream=bus, dispatch=dispatch
+ )
+ await asyncio.sleep(0)
+ await bus.close()
+ await consumer
+
+ assert resumed is True
+ # The paused tool's content is overwritten with a directive body
+ # that (a) preserves the user's literal answer and (b) instructs
+ # the model to continue addressing the original request rather
+ # than ending the turn with a one-line acknowledgment.
+ assert paused_msg["content"].startswith("User answered: Lecture")
+ assert "NOT over" in paused_msg["content"]
+ assert "FINISH" in paused_msg["content"]
+ # Sibling untouched — only the paused tool_call_id gets resolved.
+ assert sibling_msg["content"] == "rag answer"
+
+
+async def test_await_user_reply_handles_structured_v2_answers(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """v2 multi-question payload from the runtime is rendered as one
+ ``- <prompt>\\n → <answer>`` line per question and skipped answers
+ surface as ``(skipped)``."""
+ monkeypatch.setattr(
+ "deeptutor.agents.chat.agentic_pipeline.get_llm_config",
+ lambda: SimpleNamespace(
+ binding="openai", model="gpt-test", api_key="k", base_url="u", api_version=None
+ ),
+ )
+ pipeline = AgenticChatPipeline(language="en")
+ from deeptutor.agents.chat.agentic_pipeline import _DispatchOutcome
+
+ paused_msg = {
+ "role": "tool",
+ "tool_call_id": "call-pause",
+ "name": "ask_user",
+ "content": "[awaiting user reply]",
+ }
+ dispatch = _DispatchOutcome(
+ sources=[],
+ tool_messages=[paused_msg],
+ pause=True,
+ pause_payload={
+ "tool_name": "ask_user",
+ "ask_user": {
+ "intro": None,
+ "questions": [
+ {"id": "scope", "prompt": "Which direction?", "options": []},
+ {"id": "depth", "prompt": "How deep?", "options": []},
+ {"id": "format", "prompt": "What format?", "options": []},
+ ],
+ },
+ },
+ pause_tool_call_id="call-pause",
+ )
+
+ async def _waiter() -> dict:
+ return {
+ "text": "",
+ "answers": [
+ {"questionId": "scope", "text": "applications"},
+ {"questionId": "depth", "text": ""},
+ {"questionId": "format", "text": "learning path"},
+ ],
+ }
+
+ context = UnifiedContext(
+ session_id="s1",
+ user_message="m",
+ metadata={"turn_id": "t1", "wait_for_user_reply": _waiter},
+ )
+ bus = StreamBus()
+ events, consumer = await _collect_bus_events(bus)
+
+ resumed = await pipeline._await_user_reply_and_resolve(
+ context=context, stream=bus, dispatch=dispatch
+ )
+ await asyncio.sleep(0)
+ await bus.close()
+ await consumer
+
+ assert resumed is True
+ body = paused_msg["content"]
+ assert body.startswith("User answered:")
+ assert "Which direction?" in body
+ assert "→ applications" in body
+ assert "How deep?" in body
+ assert "→ (skipped)" in body
+ assert "What format?" in body
+ assert "→ learning path" in body
+ assert "NOT over" in body
+
+ resolved_events = [
+ e
+ for e in events
+ if e.type == StreamEventType.PROGRESS and e.metadata.get("ask_user_resolved") is True
+ ]
+ assert resolved_events
+ assert resolved_events[-1].metadata.get("answers") == [
+ {"questionId": "scope", "text": "applications"},
+ {"questionId": "depth", "text": ""},
+ {"questionId": "format", "text": "learning path"},
+ ]
+
+
+async def test_await_user_reply_falls_back_to_terminator_without_waiter(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Direct unit-test invocation has no runtime → emit terminator fallback."""
+ monkeypatch.setattr(
+ "deeptutor.agents.chat.agentic_pipeline.get_llm_config",
+ lambda: SimpleNamespace(
+ binding="openai", model="gpt-test", api_key="k", base_url="u", api_version=None
+ ),
+ )
+ pipeline = AgenticChatPipeline(language="en")
+ from deeptutor.agents.chat.agentic_pipeline import _DispatchOutcome
+
+ dispatch = _DispatchOutcome(
+ sources=[],
+ tool_messages=[{"role": "tool", "tool_call_id": "p", "name": "ask_user", "content": "?"}],
+ pause=True,
+ pause_payload={
+ "tool_name": "ask_user",
+ "ask_user": {"question": "Lecture or exam?", "options": []},
+ },
+ pause_tool_call_id="p",
+ )
+ context = UnifiedContext(session_id="s1", user_message="m", metadata={})
+ bus = StreamBus()
+ events, consumer = await _collect_bus_events(bus)
+
+ resumed = await pipeline._await_user_reply_and_resolve(
+ context=context, stream=bus, dispatch=dispatch
+ )
+ await asyncio.sleep(0)
+ await bus.close()
+ await consumer
+
+ assert resumed is False
+ # Should have emitted a content event carrying the ask_user payload
+ # so the frontend can still surface the question as a terminal turn.
+ content_events = [e for e in events if e.type == StreamEventType.CONTENT]
+ assert content_events, "expected fallback to emit a content event"
+ assert "Lecture or exam?" in content_events[0].content
+
+
+async def test_run_does_not_finish_on_unlabeled_reply_after_ask_user(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """After ask_user resumes, plain unlabeled text is a protocol violation,
+ not a final answer. The loop must repair and keep going until FINISH."""
+ monkeypatch.setattr(
+ "deeptutor.agents.chat.agentic_pipeline.get_llm_config",
+ lambda: SimpleNamespace(
+ binding="openai", model="gpt-test", api_key="k", base_url="u", api_version=None
+ ),
+ )
+
+ ask_user_payload = {"question": "Lecture or exam?", "options": ["Lecture", "Exam"]}
+
+ class _AskUserOnlyRegistry:
+ def build_prompt_text(self, *_args, **_kwargs):
+ return "- ask_user: ask a clarifying question"
+
+ def build_openai_schemas(self, _enabled_tools):
+ return [
+ {
+ "type": "function",
+ "function": {
+ "name": "ask_user",
+ "description": "Ask user",
+ "parameters": {
+ "type": "object",
+ "properties": {"question": {"type": "string"}},
+ "required": ["question"],
+ },
+ },
+ }
+ ]
+
+ async def execute(self, name: str, **_kwargs):
+ assert name == "ask_user"
+ return ToolResult(
+ content="[awaiting user reply]",
+ metadata={"ask_user": ask_user_payload},
+ pause_for_user=ask_user_payload,
+ )
+
+ client = _ScriptedChatClient(
+ [
+ [
+ _llm_chunk(content="``TOOL``\nI need to clarify."),
+ _llm_chunk(
+ tool_calls=[
+ {
+ "id": "call-ask",
+ "name": "ask_user",
+ "arguments": json.dumps(
+ {
+ "question": ask_user_payload["question"],
+ "options": ask_user_payload["options"],
+ }
+ ),
+ }
+ ]
+ ),
+ ],
+ [_llm_chunk(content="Okay, lecture mode.")],
+ [_llm_chunk(content="``FINISH``\nHere is the lecture-focused answer.")],
+ ]
+ )
+
+ async def _waiter() -> str:
+ return "Lecture"
+
+ pipeline = AgenticChatPipeline(language="en")
+ pipeline.registry = _AskUserOnlyRegistry()
+ monkeypatch.setattr(
+ pipeline,
+ "_compose_enabled_tools",
+ lambda _context: ["ask_user"],
+ )
+ monkeypatch.setattr(pipeline, "_build_openai_client", lambda: client)
+
+ context = UnifiedContext(
+ session_id="s1",
+ user_message="Help me prepare",
+ language="en",
+ metadata={"turn_id": "t1", "wait_for_user_reply": _waiter},
+ )
+ bus = StreamBus()
+ events, consumer = await _collect_bus_events(bus)
+
+ await pipeline.run(context, bus)
+ await asyncio.sleep(0)
+ await bus.close()
+ await consumer
+
+ assert client.call_count == 3
+ result_events = [e for e in events if e.type == StreamEventType.RESULT]
+ assert result_events
+ assert result_events[-1].content == ""
+ assert result_events[-1].source == "chat"
+ result_payload = result_events[-1]
+ assert result_payload.metadata["completed"] is True
+ assert result_payload.metadata["response"] == "Here is the lecture-focused answer."
+ assert result_payload.metadata["iterations"] == 3
+
+ protocol_warnings = [
+ e
+ for e in events
+ if e.type == StreamEventType.PROGRESS
+ and e.metadata.get("protocol_violation") == "missing_label"
+ ]
+ assert protocol_warnings
+ assert any(
+ "Protocol correction" in (m.get("content") or "") for m in client.calls[2]["messages"]
+ )
+
+
+async def test_run_forces_finish_after_iteration_budget_ends_on_think(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The loop must not end on a THINK trace when max_iterations is hit."""
+ monkeypatch.setattr(
+ "deeptutor.agents.chat.agentic_pipeline.get_llm_config",
+ lambda: SimpleNamespace(
+ binding="openai", model="gpt-test", api_key="k", base_url="u", api_version=None
+ ),
+ )
+ client = _ScriptedChatClient(
+ [
+ [_llm_chunk(content="``THINK``\nI still need to organize the answer.")],
+ [_llm_chunk(content="``THINK``\nI am still thinking.")],
+ [_llm_chunk(content="``FINISH``\nFinal answer after forced finish.")],
+ ]
+ )
+
+ pipeline = AgenticChatPipeline(language="en")
+ pipeline.registry = SimpleNamespace(build_prompt_text=lambda *_args, **_kwargs: "- none")
+ pipeline._max_iterations = 1
+ monkeypatch.setattr(pipeline, "_compose_enabled_tools", lambda _context: [])
+ monkeypatch.setattr(pipeline, "_build_openai_client", lambda: client)
+
+ bus = StreamBus()
+ events, consumer = await _collect_bus_events(bus)
+ await pipeline.run(UnifiedContext(session_id="s1", user_message="Explain X"), bus)
+ await asyncio.sleep(0)
+ await bus.close()
+ await consumer
+
+ assert client.call_count == 3
+ result = [e for e in events if e.type == StreamEventType.RESULT][-1]
+ assert result.metadata["completed"] is True
+ assert result.metadata["iterations"] == 3
+ assert result.metadata["response"] == "Final answer after forced finish."
+ assert client.calls[1].get("tools") is None
+ assert "first line must be ``FINISH``" in client.calls[1]["messages"][-1]["content"]
+
+
+async def test_run_repairs_multiple_labels_in_one_llm_reply(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A single LLM call may not say THINK and then TOOL/FINISH in the body."""
+ monkeypatch.setattr(
+ "deeptutor.agents.chat.agentic_pipeline.get_llm_config",
+ lambda: SimpleNamespace(
+ binding="openai", model="gpt-test", api_key="k", base_url="u", api_version=None
+ ),
+ )
+ client = _ScriptedChatClient(
+ [
+ [_llm_chunk(content="``THINK``\nFirst thought.\n``TOOL``\nMaybe search.")],
+ [_llm_chunk(content="``FINISH``\nClean final.")],
+ ]
+ )
+
+ pipeline = AgenticChatPipeline(language="en")
+ pipeline.registry = SimpleNamespace(build_prompt_text=lambda *_args, **_kwargs: "- none")
+ monkeypatch.setattr(pipeline, "_compose_enabled_tools", lambda _context: [])
+ monkeypatch.setattr(pipeline, "_build_openai_client", lambda: client)
+
+ bus = StreamBus()
+ events, consumer = await _collect_bus_events(bus)
+ await pipeline.run(UnifiedContext(session_id="s1", user_message="Help"), bus)
+ await asyncio.sleep(0)
+ await bus.close()
+ await consumer
+
+ result = [e for e in events if e.type == StreamEventType.RESULT][-1]
+ assert result.metadata["completed"] is True
+ assert result.metadata["response"] == "Clean final."
+ protocol_warnings = [
+ e
+ for e in events
+ if e.type == StreamEventType.PROGRESS
+ and e.metadata.get("protocol_violation") == "multiple_labels"
+ ]
+ assert protocol_warnings
+ assert any(
+ "multiple protocol labels" in (m.get("content") or "") for m in client.calls[1]["messages"]
+ )
+
+
+async def test_invalid_finish_body_is_not_streamed_before_protocol_repair(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A FINISH reply containing another label is rejected before answer streaming."""
+ monkeypatch.setattr(
+ "deeptutor.agents.chat.agentic_pipeline.get_llm_config",
+ lambda: SimpleNamespace(
+ binding="openai", model="gpt-test", api_key="k", base_url="u", api_version=None
+ ),
+ )
+ client = _ScriptedChatClient(
+ [
+ [_llm_chunk(content="``FINISH``\nPremature answer.\n``THINK``\nActually...")],
+ [_llm_chunk(content="``FINISH``\nClean final.")],
+ ]
+ )
+
+ pipeline = AgenticChatPipeline(language="en")
+ pipeline.registry = SimpleNamespace(build_prompt_text=lambda *_args, **_kwargs: "- none")
+ monkeypatch.setattr(pipeline, "_compose_enabled_tools", lambda _context: [])
+ monkeypatch.setattr(pipeline, "_build_openai_client", lambda: client)
+
+ bus = StreamBus()
+ events, consumer = await _collect_bus_events(bus)
+ await pipeline.run(UnifiedContext(session_id="s1", user_message="Help"), bus)
+ await asyncio.sleep(0)
+ await bus.close()
+ await consumer
+
+ content_events = [e for e in events if e.type == StreamEventType.CONTENT]
+ assert [e.content for e in content_events] == ["Clean final."]
+ result = [e for e in events if e.type == StreamEventType.RESULT][-1]
+ assert result.metadata["completed"] is True
+ assert result.metadata["response"] == "Clean final."
+
+
+async def test_run_emits_final_fallback_if_forced_finish_never_complies(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Even pathological non-compliance should not leave THINK as the last UI artefact."""
+ monkeypatch.setattr(
+ "deeptutor.agents.chat.agentic_pipeline.get_llm_config",
+ lambda: SimpleNamespace(
+ binding="openai", model="gpt-test", api_key="k", base_url="u", api_version=None
+ ),
+ )
+ client = _ScriptedChatClient(
+ [
+ [_llm_chunk(content="``THINK``\nInitial thought.")],
+ [_llm_chunk(content="``THINK``\nStill thinking 1.")],
+ [_llm_chunk(content="``THINK``\nStill thinking 2.")],
+ [_llm_chunk(content="``THINK``\nStill thinking 3.")],
+ ]
+ )
+
+ pipeline = AgenticChatPipeline(language="en")
+ pipeline.registry = SimpleNamespace(build_prompt_text=lambda *_args, **_kwargs: "- none")
+ pipeline._max_iterations = 1
+ monkeypatch.setattr(pipeline, "_compose_enabled_tools", lambda _context: [])
+ monkeypatch.setattr(pipeline, "_build_openai_client", lambda: client)
+
+ bus = StreamBus()
+ events, consumer = await _collect_bus_events(bus)
+ await pipeline.run(UnifiedContext(session_id="s1", user_message="Explain X"), bus)
+ await asyncio.sleep(0)
+ await bus.close()
+ await consumer
+
+ result = [e for e in events if e.type == StreamEventType.RESULT][-1]
+ assert result.metadata["completed"] is False
+ assert "valid ``FINISH`` response" in result.metadata["response"]
+ content_events = [e for e in events if e.type == StreamEventType.CONTENT]
+ assert content_events
+ assert content_events[-1].metadata.get("protocol_fallback") is True
+ assert "valid ``FINISH`` response" in content_events[-1].content
+
+
def test_build_llm_tool_schemas_kb_name_enum_matches_attached() -> None:
pipeline = AgenticChatPipeline.__new__(AgenticChatPipeline)
@@ -188,4 +1109,3 @@ def test_build_llm_tool_schemas_kb_name_enum_matches_attached() -> None:
assert parameters["properties"]["query"].get("minLength") == 1
assert parameters["required"] == ["query", "kb_name"]
assert parameters["additionalProperties"] is False
-
diff --git a/tests/capabilities/test_auto_capability.py b/tests/capabilities/test_auto_capability.py
index c7890c416..226cad16d 100644
--- a/tests/capabilities/test_auto_capability.py
+++ b/tests/capabilities/test_auto_capability.py
@@ -68,9 +68,7 @@ def _chunk(
]
else:
delta_fields["tool_calls"] = None
- return SimpleNamespace(
- choices=[SimpleNamespace(delta=SimpleNamespace(**delta_fields))]
- )
+ return SimpleNamespace(choices=[SimpleNamespace(delta=SimpleNamespace(**delta_fields))])
async def _async_iter(chunks: list[SimpleNamespace]):
@@ -185,7 +183,9 @@ class _StubSubCapability(BaseCapability):
if self.run_count in self._raise_on:
raise RuntimeError(f"{self.name} fail attempt {self.run_count}")
await stream.thinking("sub-thinking", source=self.name, stage="go")
- await stream.content(f"{self.response_text} (run {self.run_count})", source=self.name, stage="go")
+ await stream.content(
+ f"{self.response_text} (run {self.run_count})", source=self.name, stage="go"
+ )
await stream.result(
{"response": f"{self.response_text} (run {self.run_count})"},
source=self.name,
@@ -360,7 +360,9 @@ async def test_single_delegation_happy_path(fake_registry, mock_llm):
assert len(final_events) == 1
assert final_events[0].content == "Generated your quiz."
- result_events = [ev for ev in events if ev.type == StreamEventType.RESULT and ev.source == "auto"]
+ result_events = [
+ ev for ev in events if ev.type == StreamEventType.RESULT and ev.source == "auto"
+ ]
summary = result_events[0].metadata.get("auto_summary")
assert summary["delegations"][0]["capability"] == "deep_question"
assert summary["delegations"][0]["succeeded"] is True
@@ -400,7 +402,9 @@ async def test_router_text_response_no_delegation(fake_registry, mock_llm):
sub_events = [ev for ev in events if ev.metadata.get("delegated_from") == "auto"]
assert sub_events == []
- result_events = [ev for ev in events if ev.type == StreamEventType.RESULT and ev.source == "auto"]
+ result_events = [
+ ev for ev in events if ev.type == StreamEventType.RESULT and ev.source == "auto"
+ ]
assert result_events[0].metadata["auto_summary"]["final_path"] == "text_response"
@@ -433,7 +437,9 @@ async def test_enabled_capabilities_filter_visible_to_router(fake_registry, mock
# The scripted client recorded last_kwargs of the LAST call (synthesizer is
# not invoked because router gave text). The last call IS the router.
tools = client.last_kwargs["tools"]
- cap_tools = [t["function"]["name"] for t in tools if t["function"]["name"].startswith("delegate_to_")]
+ cap_tools = [
+ t["function"]["name"] for t in tools if t["function"]["name"].startswith("delegate_to_")
+ ]
assert cap_tools == ["delegate_to_visualize"]
@@ -455,7 +461,7 @@ async def test_router_api_error_retry_then_success(fake_registry, mock_llm):
client = _ScriptedClient(
[
_stream_for_text("ack"), # analyzer
- transient, # router iter 1 fails
+ transient, # router iter 1 fails
_stream_for_text("Hi!"), # router iter 1 retry succeeds (text)
]
)
@@ -495,9 +501,9 @@ async def test_router_api_error_max_retries_terminates(fake_registry, mock_llm):
client = _ScriptedClient(
[
_stream_for_text("ack"), # analyzer
- _transient_error(), # router fail 1
- _transient_error(), # router fail 2
- _transient_error(), # router fail 3 -> terminal
+ _transient_error(), # router fail 1
+ _transient_error(), # router fail 2
+ _transient_error(), # router fail 3 -> terminal
]
)
with (
@@ -561,8 +567,7 @@ async def test_subcap_raises_then_succeeds_on_retry(fake_registry, mock_llm):
retry_events = [
ev
for ev in events
- if ev.type == StreamEventType.ERROR
- and ev.metadata.get("trace_kind") == "delegation_retry"
+ if ev.type == StreamEventType.ERROR and ev.metadata.get("trace_kind") == "delegation_retry"
]
assert len(retry_events) >= 1
diff --git a/tests/services/session/test_turn_runtime_subscribe.py b/tests/services/session/test_turn_runtime_subscribe.py
new file mode 100644
index 000000000..1a38e0943
--- /dev/null
+++ b/tests/services/session/test_turn_runtime_subscribe.py
@@ -0,0 +1,46 @@
+from __future__ import annotations
+
+import asyncio
+
+import pytest
+
+from deeptutor.services.session.sqlite_store import SQLiteSessionStore
+from deeptutor.services.session.turn_runtime import TurnRuntimeManager, _TurnExecution
+
+
+async def test_subscribe_turn_does_not_synthesize_done_for_running_turn(tmp_path) -> None:
+ """A paused/replaced subscription must not make the UI think the turn ended."""
+
+ store = SQLiteSessionStore(tmp_path / "chat_history.db")
+ runtime = TurnRuntimeManager(store)
+ session = await store.ensure_session(None)
+ turn = await store.create_turn(session["id"], capability="chat")
+ execution = _TurnExecution(
+ turn_id=turn["id"],
+ session_id=session["id"],
+ capability="chat",
+ payload={},
+ )
+ runtime._executions[turn["id"]] = execution
+
+ events: list[dict] = []
+
+ async def _collect() -> None:
+ async for event in runtime.subscribe_turn(turn["id"], after_seq=0):
+ events.append(event)
+
+ task = asyncio.create_task(_collect())
+ for _ in range(20):
+ if execution.subscribers:
+ break
+ await asyncio.sleep(0)
+
+ assert execution.subscribers
+ await execution.subscribers[0].queue.put(None)
+ await asyncio.wait_for(task, timeout=1)
+
+ assert events == []
+ persisted = await store.get_turn(turn["id"])
+ assert persisted is not None
+ assert persisted["status"] == "running"
diff --git a/tests/services/session/test_turn_runtime_title.py b/tests/services/session/test_turn_runtime_title.py
new file mode 100644
index 000000000..9c8caac5a
--- /dev/null
+++ b/tests/services/session/test_turn_runtime_title.py
@@ -0,0 +1,15 @@
+from __future__ import annotations
+
+from deeptutor.services.session.turn_runtime import _sanitize_session_title
+
+
+def test_sanitize_session_title_removes_reasoning_block() -> None:
+ raw = "<think>\nNeed a concise title.\n</think>\n标题:AgenticRAG 定义"
+
+ assert _sanitize_session_title(raw) == "AgenticRAG 定义"
+
+
+def test_sanitize_session_title_falls_back_when_only_reasoning_remains() -> None:
+ raw = "<think>\nStill deciding on the title."
+
+ assert _sanitize_session_title(raw) == ""
diff --git a/tests/tools/test_ask_user.py b/tests/tools/test_ask_user.py
new file mode 100644
index 000000000..3d0c78a13
--- /dev/null
+++ b/tests/tools/test_ask_user.py
@@ -0,0 +1,236 @@
+"""Unit tests for ``ask_user`` payload building.
+
+Covers both the v2 multi-question schema and the legacy single-question
+shorthand which auto-wraps into a one-element list.
+"""
+
+from __future__ import annotations
+
+from deeptutor.tools.ask_user import (
+ MAX_OPTION_CHARS,
+ MAX_OPTIONS,
+ MAX_QUESTION_CHARS,
+ MAX_QUESTIONS,
+ build_ask_user_payload,
+)
+
+
+# ----------------------------- legacy shape -----------------------------
+
+
+def test_legacy_rejects_empty_question() -> None:
+ payload, err = build_ask_user_payload(question=" ")
+ assert payload is None
+ assert err and "prompt" in err
+
+
+def test_legacy_question_only_wraps_to_single() -> None:
+ payload, err = build_ask_user_payload(question="What's your level?")
+ assert err is None
+ assert payload is not None
+ assert len(payload.questions) == 1
+ only = payload.questions[0]
+ assert only.id == "q1"
+ assert only.prompt == "What's your level?"
+ assert only.options == ()
+ assert only.allow_free_text is True
+
+
+def test_legacy_options_strip_and_dedupe() -> None:
+ payload, err = build_ask_user_payload(
+ question="Pick",
+ options=[" A ", "B", "A", "", "C"],
+ )
+ assert err is None
+ assert payload is not None
+ assert payload.questions[0].options == ("A", "B", "C")
+
+
+def test_legacy_caps_option_count() -> None:
+ payload, _ = build_ask_user_payload(
+ question="Pick",
+ options=[f"opt-{i}" for i in range(MAX_OPTIONS + 5)],
+ )
+ assert payload is not None
+ assert len(payload.questions[0].options) == MAX_OPTIONS
+
+
+def test_legacy_clips_oversized_question() -> None:
+ payload, _ = build_ask_user_payload(question="q" * (MAX_QUESTION_CHARS + 50))
+ assert payload is not None
+ prompt = payload.questions[0].prompt
+ assert prompt.endswith("…")
+ assert len(prompt) <= MAX_QUESTION_CHARS + 1
+
+
+def test_legacy_clips_oversized_option() -> None:
+ payload, _ = build_ask_user_payload(
+ question="q",
+ options=["x" * (MAX_OPTION_CHARS + 100)],
+ )
+ assert payload is not None
+ assert payload.questions[0].options[0].endswith("…")
+
+
+def test_legacy_rejects_non_list_options() -> None:
+ payload, err = build_ask_user_payload(question="q", options="not-a-list")
+ assert payload is None
+ assert err and "array" in err
+
+
+# ------------------------------- v2 shape -------------------------------
+
+
+def test_v2_multiple_questions_assigned_default_ids() -> None:
+ payload, err = build_ask_user_payload(
+ questions=[
+ {"prompt": "scope?"},
+ {"prompt": "depth?"},
+ {"prompt": "format?"},
+ ]
+ )
+ assert err is None
+ assert payload is not None
+ assert payload.question_ids == ("q1", "q2", "q3")
+
+
+def test_v2_respects_explicit_ids() -> None:
+ payload, _ = build_ask_user_payload(
+ questions=[
+ {"id": "scope", "prompt": "A"},
+ {"id": "depth", "prompt": "B"},
+ ]
+ )
+ assert payload is not None
+ assert payload.question_ids == ("scope", "depth")
+
+
+def test_v2_disambiguates_duplicate_ids() -> None:
+ payload, _ = build_ask_user_payload(
+ questions=[
+ {"id": "x", "prompt": "A"},
+ {"id": "x", "prompt": "B"},
+ ]
+ )
+ assert payload is not None
+ assert payload.question_ids == ("x", "x_2")
+
+
+def test_v2_caps_question_count() -> None:
+ payload, _ = build_ask_user_payload(
+ questions=[{"prompt": f"q{i}"} for i in range(MAX_QUESTIONS + 4)]
+ )
+ assert payload is not None
+ assert len(payload.questions) == MAX_QUESTIONS
+
+
+def test_v2_intro_included_and_clipped() -> None:
+ payload, _ = build_ask_user_payload(
+ questions=[{"prompt": "hi"}],
+ intro="To tailor the research:",
+ )
+ assert payload is not None
+ assert payload.intro == "To tailor the research:"
+
+
+def test_v2_empty_intro_becomes_none() -> None:
+ payload, _ = build_ask_user_payload(
+ questions=[{"prompt": "hi"}],
+ intro=" ",
+ )
+ assert payload is not None
+ assert payload.intro is None
+
+
+def test_v2_rejects_non_object_question() -> None:
+ payload, err = build_ask_user_payload(questions=["bare string"])
+ assert payload is None
+ assert err and "object" in err
+
+
+def test_v2_rejects_empty_questions_list() -> None:
+ payload, err = build_ask_user_payload(questions=[])
+ assert payload is None
+ assert err and "at least one" in err
+
+
+def test_v2_rejects_non_array_questions() -> None:
+ payload, err = build_ask_user_payload(questions={"prompt": "x"})
+ assert payload is None
+ assert err and "array" in err
+
+
+def test_v2_accepts_question_alias_for_prompt() -> None:
+ """LLMs sometimes use ``question`` instead of ``prompt`` inside a v2 item."""
+ payload, err = build_ask_user_payload(
+ questions=[{"question": "what?", "options": ["a", "b"]}]
+ )
+ assert err is None
+ assert payload is not None
+ assert payload.questions[0].prompt == "what?"
+ assert payload.questions[0].options == ("a", "b")
+
+
+def test_v2_allow_free_text_default_true() -> None:
+ payload, _ = build_ask_user_payload(questions=[{"prompt": "x"}])
+ assert payload is not None
+ assert payload.questions[0].allow_free_text is True
+
+
+def test_v2_allow_free_text_can_be_disabled() -> None:
+ payload, _ = build_ask_user_payload(
+ questions=[{"prompt": "x", "options": ["a"], "allow_free_text": False}]
+ )
+ assert payload is not None
+ assert payload.questions[0].allow_free_text is False
+
+
+def test_v2_placeholder_stored() -> None:
+ payload, _ = build_ask_user_payload(
+ questions=[{"prompt": "x", "placeholder": "type here"}]
+ )
+ assert payload is not None
+ assert payload.questions[0].placeholder == "type here"
+
+
+# ------------------------- frontend contract shape ------------------------
+
+
+def test_to_dict_shape_is_v2_for_frontend() -> None:
+ payload, _ = build_ask_user_payload(
+ questions=[
+ {"id": "scope", "prompt": "Q1", "options": ["a"]},
+ {"id": "depth", "prompt": "Q2"},
+ ],
+ intro="hi",
+ )
+ assert payload is not None
+ assert payload.to_dict() == {
+ "intro": "hi",
+ "questions": [
+ {
+ "id": "scope",
+ "prompt": "Q1",
+ "options": ["a"],
+ "allow_free_text": True,
+ "placeholder": None,
+ },
+ {
+ "id": "depth",
+ "prompt": "Q2",
+ "options": [],
+ "allow_free_text": True,
+ "placeholder": None,
+ },
+ ],
+ }
+
+
+def test_to_dict_legacy_path_also_emits_v2() -> None:
+ payload, _ = build_ask_user_payload(question="hi", options=["a", "b"])
+ assert payload is not None
+ d = payload.to_dict()
+ assert d["intro"] is None
+ assert len(d["questions"]) == 1
+ assert d["questions"][0]["prompt"] == "hi"
+ assert d["questions"][0]["options"] == ["a", "b"]
diff --git a/tests/tools/test_github_query.py b/tests/tools/test_github_query.py
new file mode 100644
index 000000000..28342a2b8
--- /dev/null
+++ b/tests/tools/test_github_query.py
@@ -0,0 +1,179 @@
+"""Unit tests for the ``github_query`` tool's pure logic.
+
+We never spawn ``gh`` for real — every test injects its own
+``command_runner`` so we can pin returncode / stdout / stderr.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from typing import Any
+
+import pytest
+
+from deeptutor.tools.github_query import (
+ GithubOutcome,
+ MAX_OUTPUT_CHARS,
+ run_github_query,
+)
+
+
+def _runner(
+ *,
+ returncode: int = 0,
+ stdout: str = "",
+ stderr: str = "",
+ record: list[list[str]] | None = None,
+):
+ async def _run(argv, timeout_s):
+ if record is not None:
+ record.append(list(argv))
+ return returncode, stdout, stderr
+
+ return _run
+
+
+# ---------------------------------------------------------------------------
+# Argument validation
+# ---------------------------------------------------------------------------
+
+
+async def test_rejects_missing_query_type() -> None:
+ outcome = await run_github_query(
+ query_type="",
+ target="owner/repo",
+ gh_available=lambda: True,
+ command_runner=_runner(),
+ )
+ assert outcome.ok is False
+ assert "query_type" in outcome.error
+
+
+async def test_rejects_missing_target() -> None:
+ outcome = await run_github_query(
+ query_type="pr",
+ target="",
+ gh_available=lambda: True,
+ command_runner=_runner(),
+ )
+ assert outcome.ok is False
+ assert "target" in outcome.error
+
+
+async def test_rejects_unsupported_query_type() -> None:
+ outcome = await run_github_query(
+ query_type="merge", # explicitly write-flavoured, not in the whitelist
+ target="owner/repo#1",
+ gh_available=lambda: True,
+ command_runner=_runner(),
+ )
+ assert outcome.ok is False
+ assert "Unsupported query_type" in outcome.error
+
+
+# ---------------------------------------------------------------------------
+# gh CLI availability
+# ---------------------------------------------------------------------------
+
+
+async def test_reports_gh_missing_gracefully() -> None:
+ outcome = await run_github_query(
+ query_type="pr",
+ target="owner/repo#1",
+ gh_available=lambda: False,
+ command_runner=_runner(), # should never be invoked
+ )
+ assert outcome.ok is False
+ assert "`gh`" in outcome.error or "gh" in outcome.error.lower()
+
+
+# ---------------------------------------------------------------------------
+# argv shape — confirms each query_type stays read-only
+# ---------------------------------------------------------------------------
+
+
+async def test_pr_argv_is_view_only() -> None:
+ record: list[list[str]] = []
+ await run_github_query(
+ query_type="pr",
+ target="owner/repo#42",
+ gh_available=lambda: True,
+ command_runner=_runner(stdout='{"title":"x"}', record=record),
+ )
+ assert record == [["gh", "pr", "view", "owner/repo#42", "--json",
+ "title,state,statusCheckRollup,reviews,url,author,createdAt,body"]]
+
+
+async def test_issue_argv_is_view_only() -> None:
+ record: list[list[str]] = []
+ await run_github_query(
+ query_type="issue",
+ target="owner/repo#7",
+ gh_available=lambda: True,
+ command_runner=_runner(stdout='{"title":"x"}', record=record),
+ )
+ assert record[0][:4] == ["gh", "issue", "view", "owner/repo#7"]
+
+
+async def test_run_argv_uses_list_subcommand() -> None:
+ record: list[list[str]] = []
+ await run_github_query(
+ query_type="run",
+ target="owner/repo",
+ gh_available=lambda: True,
+ command_runner=_runner(stdout='[]', record=record),
+ )
+ assert record[0][:5] == ["gh", "run", "list", "--repo", "owner/repo"]
+
+
+async def test_api_argv_does_not_set_method() -> None:
+ """`gh api` defaults to GET; we never pass --method so the tool
+ can't be coerced into a mutating call by creative ``target``s."""
+ record: list[list[str]] = []
+ await run_github_query(
+ query_type="api",
+ target="repos/owner/repo/issues",
+ gh_available=lambda: True,
+ command_runner=_runner(stdout='[]', record=record),
+ )
+ assert "--method" not in record[0]
+ assert "-X" not in record[0]
+ assert record[0][0:2] == ["gh", "api"]
+
+
+# ---------------------------------------------------------------------------
+# Output handling
+# ---------------------------------------------------------------------------
+
+
+async def test_truncates_oversized_output() -> None:
+ huge = "y" * (MAX_OUTPUT_CHARS + 500)
+ outcome = await run_github_query(
+ query_type="pr",
+ target="o/r#1",
+ gh_available=lambda: True,
+ command_runner=_runner(stdout=huge),
+ )
+ assert outcome.ok is True
+ assert outcome.output.endswith("[truncated]")
+
+
+async def test_surfaces_nonzero_exit_as_failure() -> None:
+ outcome = await run_github_query(
+ query_type="pr",
+ target="o/r#1",
+ gh_available=lambda: True,
+ command_runner=_runner(returncode=1, stderr="not found"),
+ )
+ assert outcome.ok is False
+ assert "not found" in outcome.error
diff --git a/tests/tools/test_list_notebook.py b/tests/tools/test_list_notebook.py
new file mode 100644
index 000000000..810880480
--- /dev/null
+++ b/tests/tools/test_list_notebook.py
@@ -0,0 +1,149 @@
+"""Unit tests for the ``list_notebook`` tool's pure rendering logic."""
+
+from __future__ import annotations
+
+from deeptutor.tools.list_notebook import (
+ MAX_NOTEBOOKS_RENDERED,
+ MAX_RECORDS_RENDERED,
+ list_notebooks_or_records,
+)
+
+
+class _FakeManager:
+ """Minimal NotebookManager stand-in for unit tests."""
+
+ def __init__(self, notebooks=(), records_by_nb=None):
+ self._notebooks = list(notebooks)
+ self._records = dict(records_by_nb or {})
+
+ def list_notebooks(self):
+ return list(self._notebooks)
+
+ def get_records(self, notebook_id):
+ return list(self._records.get(notebook_id, []))
+
+
+# ---------------------------------------------------------------------------
+# Index mode (no notebook_id)
+# ---------------------------------------------------------------------------
+
+
+def test_index_returns_empty_message_when_user_has_no_notebooks() -> None:
+ outcome = list_notebooks_or_records(notebook_manager=_FakeManager())
+ assert outcome.ok is True
+ assert "no notebooks" in outcome.text.lower()
+ assert outcome.summary == {"mode": "index", "count": 0}
+
+
+def test_index_renders_id_name_count_for_each_notebook() -> None:
+ manager = _FakeManager(
+ notebooks=[
+ {
+ "id": "nb-1",
+ "name": "Math",
+ "description": "Calculus + linear algebra",
+ "record_count": 12,
+ "updated_at": 1_700_000_000.0,
+ },
+ {
+ "id": "nb-2",
+ "name": "Physics",
+ "record_count": 3,
+ "updated_at": 1_700_000_010.0,
+ },
+ ],
+ )
+ outcome = list_notebooks_or_records(notebook_manager=manager)
+ assert outcome.ok is True
+ assert "`nb-1`" in outcome.text
+ assert "**Math**" in outcome.text
+ assert "12 records" in outcome.text
+ assert "Calculus + linear algebra" in outcome.text
+ assert "`nb-2`" in outcome.text
+ assert "Physics" in outcome.text
+ assert outcome.summary == {"mode": "index", "count": 2}
+
+
+def test_index_caps_huge_notebook_lists() -> None:
+ manager = _FakeManager(
+ notebooks=[
+ {"id": f"nb-{i}", "name": f"NB {i}", "record_count": i}
+ for i in range(MAX_NOTEBOOKS_RENDERED + 10)
+ ],
+ )
+ outcome = list_notebooks_or_records(notebook_manager=manager)
+ assert outcome.ok is True
+ assert "showing" in outcome.text.lower()
+ assert outcome.summary["count"] == MAX_NOTEBOOKS_RENDERED + 10
+
+
+# ---------------------------------------------------------------------------
+# Drill-down mode (notebook_id given)
+# ---------------------------------------------------------------------------
+
+
+def test_drilldown_rejects_unknown_notebook_id() -> None:
+ manager = _FakeManager(
+ notebooks=[{"id": "nb-1", "name": "Math"}],
+ )
+ outcome = list_notebooks_or_records(
+ notebook_id="bogus", notebook_manager=manager
+ )
+ assert outcome.ok is False
+ assert "Unknown notebook_id" in outcome.error
+ assert "`nb-1`" in outcome.error # tells the LLM the right id to use
+
+
+def test_drilldown_empty_records() -> None:
+ manager = _FakeManager(
+ notebooks=[{"id": "nb-1", "name": "Math"}],
+ records_by_nb={"nb-1": []},
+ )
+ outcome = list_notebooks_or_records(notebook_id="nb-1", notebook_manager=manager)
+ assert outcome.ok is True
+ assert "no records" in outcome.text.lower()
+ assert outcome.summary == {"mode": "records", "notebook_id": "nb-1", "count": 0}
+
+
+def test_drilldown_renders_records_newest_first() -> None:
+ manager = _FakeManager(
+ notebooks=[{"id": "nb-1", "name": "Math"}],
+ records_by_nb={
+ "nb-1": [
+ {
+ "id": "r-old",
+ "title": "Old",
+ "summary": "old summary",
+ "type": "chat",
+ "created_at": 1_700_000_000.0,
+ },
+ {
+ "id": "r-new",
+ "title": "New",
+ "summary": "new summary",
+ "type": "chat",
+ "created_at": 1_700_001_000.0,
+ },
+ ]
+ },
+ )
+ outcome = list_notebooks_or_records(notebook_id="nb-1", notebook_manager=manager)
+ assert outcome.ok is True
+ # Newest first — "r-new" appears before "r-old" in the rendered text.
+ assert outcome.text.index("`r-new`") < outcome.text.index("`r-old`")
+ assert "new summary" in outcome.text
+
+
+def test_drilldown_caps_huge_record_lists() -> None:
+ big_records = [
+ {"id": f"r-{i}", "title": f"R{i}", "summary": "", "created_at": float(i)}
+ for i in range(MAX_RECORDS_RENDERED + 20)
+ ]
+ manager = _FakeManager(
+ notebooks=[{"id": "nb-1", "name": "Math"}],
+ records_by_nb={"nb-1": big_records},
+ )
+ outcome = list_notebooks_or_records(notebook_id="nb-1", notebook_manager=manager)
+ assert outcome.ok is True
+ assert "showing" in outcome.text.lower()
+ assert outcome.summary["count"] == MAX_RECORDS_RENDERED + 20
diff --git a/tests/tools/test_web_fetch.py b/tests/tools/test_web_fetch.py
new file mode 100644
index 000000000..1d2c5553c
--- /dev/null
+++ b/tests/tools/test_web_fetch.py
@@ -0,0 +1,180 @@
+"""Unit tests for the ``web_fetch`` tool's pure helpers."""
+
+from __future__ import annotations
+
+import pytest
+
+from deeptutor.tools.web_fetch import (
+ DEFAULT_MAX_CHARS,
+ FetchOutcome,
+ _extract_readable,
+ _is_disallowed_host,
+ fetch_url_as_markdown,
+)
+
+
+# ---------------------------------------------------------------------------
+# Host validation
+# ---------------------------------------------------------------------------
+
+
+ "host",
+ [
+ "127.0.0.1", "localhost", "10.0.0.1", "192.168.1.1",
+ "169.254.1.1", "::1", "[::1]", "metadata.local",
+ ],
+)
+def test_is_disallowed_host_blocks_private_addresses(host: str) -> None:
+ assert _is_disallowed_host(host) is True, f"{host!r} should be disallowed"
+
+
+def test_is_disallowed_host_allows_public_hostname() -> None:
+ # The DNS-dependent positive test is environment-fragile (CI sandboxes
+ # often block outbound DNS). The negative coverage above plus the
+ # injectable ``host_validator`` (used in fetch tests) makes a fully-
+ # offline public-host assertion unnecessary.
+ pytest.skip("public DNS check skipped; relies on injectable validator in tests")
+
+
+# ---------------------------------------------------------------------------
+# HTML readability extraction
+# ---------------------------------------------------------------------------
+
+
+def test_extract_readable_strips_scripts_and_styles() -> None:
+ html = """
+ <html><head><title>Hello</title><style>body {color:red;}</style></head>
+ <body><p>Visible.</p><script>alert('no');</script></body></html>
+ """
+ title, body = _extract_readable(html)
+ assert title == "Hello"
+ assert "Visible." in body
+ assert "alert" not in body
+ assert "color:red" not in body
+ # Title is prepended as h1 markdown
+ assert body.startswith("# Hello")
+
+
+def test_extract_readable_passes_through_plain_text() -> None:
+ title, body = _extract_readable("Plain text payload\nwith two lines.")
+ assert title == ""
+ assert "Plain text payload" in body
+ assert "with two lines" in body
+
+
+# ---------------------------------------------------------------------------
+# Top-level fetch — uses injected client_factory so no real network I/O.
+# ---------------------------------------------------------------------------
+
+
+class _StubResponse:
+ def __init__(
+ self,
+ *,
+ body: bytes = b"<html><title>T</title><body><p>x</p></body></html>",
+ status: int = 200,
+ url: str = "https://example.com/p",
+ encoding: str = "utf-8",
+ ) -> None:
+ self._body = body
+ self.status_code = status
+ self.url = url
+ self.encoding = encoding
+ self.headers = {"content-type": "text/html; charset=utf-8"}
+
+ async def aiter_bytes(self):
+ yield self._body
+
+ def raise_for_status(self) -> None:
+ if self.status_code >= 400:
+ raise RuntimeError(f"HTTP {self.status_code}")
+
+
+class _StubAsyncClient:
+ def __init__(self, response: _StubResponse) -> None:
+ self._response = response
+
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, exc_type, exc, tb):
+ return False
+
+ def stream(self, _method, _url, **_kwargs):
+ outer = self
+
+ class _Ctx:
+ async def __aenter__(self):
+ return outer._response
+
+ async def __aexit__(self, exc_type, exc, tb):
+ return False
+
+ return _Ctx()
+
+
+def _factory_returning(response: _StubResponse):
+ def _factory(*, timeout: float, user_agent: str):
+ return _StubAsyncClient(response)
+
+ return _factory
+
+
+async def test_fetch_rejects_unsupported_scheme() -> None:
+ outcome = await fetch_url_as_markdown("ftp://example.com/x")
+ assert outcome.ok is False
+ assert "scheme" in outcome.error.lower()
+
+
+async def test_fetch_rejects_private_host() -> None:
+ outcome = await fetch_url_as_markdown("http://127.0.0.1/x")
+ assert outcome.ok is False
+ assert "private" in outcome.error.lower() or "loopback" in outcome.error.lower()
+
+
+# Bypass DNS in every stubbed-network test — the validator is treated as
+# trusted here because ``client_factory`` already pins the response.
+_ALLOW_ALL = lambda host: False # noqa: E731 — single-use stub
+
+
+async def test_fetch_extracts_html_via_stubbed_client() -> None:
+ outcome = await fetch_url_as_markdown(
+ "https://example.com/p",
+ client_factory=_factory_returning(_StubResponse()),
+ host_validator=_ALLOW_ALL,
+ )
+ assert outcome.ok is True
+ assert outcome.title == "T"
+ assert "x" in outcome.markdown
+
+
+async def test_fetch_truncates_at_max_chars() -> None:
+ big_body = b"<html><body>" + (b"a" * 5000) + b"</body></html>"
+ outcome = await fetch_url_as_markdown(
+ "https://example.com/big",
+ max_chars=200,
+ client_factory=_factory_returning(_StubResponse(body=big_body)),
+ host_validator=_ALLOW_ALL,
+ )
+ assert outcome.ok is True
+ assert outcome.truncated is True
+ assert outcome.markdown.endswith("…[truncated]")
+ assert len(outcome.markdown) <= 220 # cap + marker headroom
+
+
+async def test_fetch_propagates_http_error_as_outcome_not_exception() -> None:
+ outcome = await fetch_url_as_markdown(
+ "https://example.com/missing",
+ client_factory=_factory_returning(
+ _StubResponse(status=404, body=b"<p>missing</p>")
+ ),
+ host_validator=_ALLOW_ALL,
+ )
+ assert outcome.ok is False
+ assert "404" in outcome.error
diff --git a/tests/tools/test_write_note.py b/tests/tools/test_write_note.py
new file mode 100644
index 000000000..9bf08918c
--- /dev/null
+++ b/tests/tools/test_write_note.py
@@ -0,0 +1,320 @@
+"""Unit tests for the ``write_note`` tool (append + edit modes)."""
+
+from __future__ import annotations
+
+from deeptutor.tools.write_note import (
+ ALL_TURNS_SENTINEL,
+ DEFAULT_TURNS_TO_INCLUDE,
+ MAX_NOTE_CHARS,
+ MAX_TITLE_CHARS,
+ write_note,
+)
+
+
+class _FakeManager:
+ """Notebook manager stand-in. Tracks last add / update for assertions."""
+
+ def __init__(
+ self,
+ notebooks=(),
+ records_by_nb=None,
+ raise_on_add: bool = False,
+ raise_on_update: bool = False,
+ ):
+ self._notebooks = list(notebooks)
+ self._records = dict(records_by_nb or {})
+ self._raise_on_add = raise_on_add
+ self._raise_on_update = raise_on_update
+ self.last_add = None
+ self.last_update = None
+
+ def list_notebooks(self):
+ return list(self._notebooks)
+
+ def get_record(self, notebook_id, record_id):
+ for rec in self._records.get(notebook_id, []):
+ if str(rec.get("id")) == record_id:
+ return rec
+ return None
+
+ def add_record(self, **kwargs):
+ if self._raise_on_add:
+ raise RuntimeError("disk full")
+ self.last_add = kwargs
+ return {"record": {"id": "rec-123"}, "added_to_notebooks": kwargs["notebook_ids"]}
+
+ def update_record(self, notebook_id, record_id, **kwargs):
+ if self._raise_on_update:
+ raise RuntimeError("io error")
+ target = self.get_record(notebook_id, record_id)
+ if target is None:
+ return None
+ target.update(kwargs)
+ self.last_update = {"notebook_id": notebook_id, "record_id": record_id, **kwargs}
+ return target
+
+
+_SAMPLE_HISTORY = [
+ {"role": "user", "content": "What is a vector?"},
+ {"role": "assistant", "content": "A vector is..."},
+ {"role": "user", "content": "And a tensor?"},
+ {"role": "assistant", "content": "A tensor generalises..."},
+]
+
+
+# ---------------------------------------------------------------------------
+# Mode validation + shared error paths
+# ---------------------------------------------------------------------------
+
+
+def test_rejects_unknown_mode() -> None:
+ outcome = write_note(
+ mode="rewrite",
+ notebook_id="nb-1",
+ notebook_manager=_FakeManager(notebooks=[{"id": "nb-1", "name": "N"}]),
+ )
+ assert outcome.ok is False
+ assert "Unknown mode" in outcome.error
+
+
+def test_rejects_unknown_notebook() -> None:
+ outcome = write_note(
+ mode="append",
+ notebook_id="bogus",
+ title="t",
+ conversation_history=_SAMPLE_HISTORY,
+ notebook_manager=_FakeManager(notebooks=[{"id": "nb-1", "name": "N"}]),
+ )
+ assert outcome.ok is False
+ assert "Unknown notebook_id" in outcome.error
+
+
+# ---------------------------------------------------------------------------
+# Append mode
+# ---------------------------------------------------------------------------
+
+
+def test_append_writes_real_transcript_by_default() -> None:
+ manager = _FakeManager(notebooks=[{"id": "nb-1", "name": "Math"}])
+ outcome = write_note(
+ mode="append",
+ notebook_id="nb-1",
+ title="Vectors",
+ turns_to_include=2,
+ note="Bookmark for review.",
+ conversation_history=_SAMPLE_HISTORY,
+ current_user_message="",
+ notebook_manager=manager,
+ )
+ assert outcome.ok is True
+ assert outcome.mode == "append"
+ body = manager.last_add["output"]
+ assert "### User" in body and "### Assistant" in body
+ assert "What is a vector?" in body
+ assert "A tensor generalises..." in body
+ # Note prefix appears above the transcript.
+ assert "Bookmark for review." in body
+ assert body.index("Bookmark") < body.index("### User")
+ assert manager.last_add["metadata"]["mode"] == "append"
+ assert manager.last_add["metadata"]["explicit_content"] is False
+
+
+def test_append_with_explicit_content_skips_auto_transcript() -> None:
+ """When the agent passes `content`, it's saved verbatim — supports
+ the 'save an agent-authored summary' use case."""
+ manager = _FakeManager(notebooks=[{"id": "nb-1", "name": "N"}])
+ outcome = write_note(
+ mode="append",
+ notebook_id="nb-1",
+ title="Summary",
+ content="### My summary\n\nThings to remember.",
+ conversation_history=_SAMPLE_HISTORY,
+ notebook_manager=manager,
+ )
+ assert outcome.ok is True
+ body = manager.last_add["output"]
+ assert "Things to remember." in body
+ # The default Q&A transcript headings should NOT appear when
+ # explicit content was provided.
+ assert "### User" not in body
+ assert manager.last_add["metadata"]["explicit_content"] is True
+
+
+def test_append_accepts_all_sentinel_for_turns() -> None:
+ manager = _FakeManager(notebooks=[{"id": "nb-1", "name": "N"}])
+ outcome = write_note(
+ mode="append",
+ notebook_id="nb-1",
+ title="Everything",
+ turns_to_include=ALL_TURNS_SENTINEL,
+ conversation_history=_SAMPLE_HISTORY,
+ current_user_message="latest question",
+ notebook_manager=manager,
+ )
+ assert outcome.ok is True
+ body = manager.last_add["output"]
+ # All four history pairs + the current question should be in the body.
+ assert "What is a vector?" in body
+ assert "And a tensor?" in body
+ assert "latest question" in body
+
+
+def test_append_requires_title() -> None:
+ manager = _FakeManager(notebooks=[{"id": "nb-1", "name": "N"}])
+ outcome = write_note(
+ mode="append",
+ notebook_id="nb-1",
+ title=" ",
+ conversation_history=_SAMPLE_HISTORY,
+ notebook_manager=manager,
+ )
+ assert outcome.ok is False
+ assert "title" in outcome.error.lower()
+
+
+def test_append_refuses_empty_history_without_content() -> None:
+ manager = _FakeManager(notebooks=[{"id": "nb-1", "name": "N"}])
+ outcome = write_note(
+ mode="append",
+ notebook_id="nb-1",
+ title="t",
+ conversation_history=[],
+ current_user_message="",
+ notebook_manager=manager,
+ )
+ assert outcome.ok is False
+ assert "nothing to save" in outcome.error.lower()
+
+
+def test_append_surfaces_manager_errors_as_outcome() -> None:
+ manager = _FakeManager(
+ notebooks=[{"id": "nb-1", "name": "N"}], raise_on_add=True
+ )
+ outcome = write_note(
+ mode="append",
+ notebook_id="nb-1",
+ title="t",
+ conversation_history=_SAMPLE_HISTORY,
+ notebook_manager=manager,
+ )
+ assert outcome.ok is False
+ assert "Save failed" in outcome.error
+
+
+# ---------------------------------------------------------------------------
+# Edit mode
+# ---------------------------------------------------------------------------
+
+
+def test_edit_requires_record_id() -> None:
+ manager = _FakeManager(
+ notebooks=[{"id": "nb-1", "name": "N"}],
+ records_by_nb={"nb-1": [{"id": "r1", "title": "old"}]},
+ )
+ outcome = write_note(
+ mode="edit",
+ notebook_id="nb-1",
+ title="new",
+ notebook_manager=manager,
+ )
+ assert outcome.ok is False
+ assert "record_id" in outcome.error.lower()
+
+
+def test_edit_rejects_unknown_record() -> None:
+ manager = _FakeManager(
+ notebooks=[{"id": "nb-1", "name": "N"}],
+ records_by_nb={"nb-1": [{"id": "r1", "title": "old"}]},
+ )
+ outcome = write_note(
+ mode="edit",
+ notebook_id="nb-1",
+ record_id="r-missing",
+ title="new",
+ notebook_manager=manager,
+ )
+ assert outcome.ok is False
+ assert "not found" in outcome.error.lower()
+ assert "list_notebook" in outcome.error # tells the LLM where to discover ids
+
+
+def test_edit_requires_at_least_one_field_changed() -> None:
+ manager = _FakeManager(
+ notebooks=[{"id": "nb-1", "name": "N"}],
+ records_by_nb={"nb-1": [{"id": "r1", "title": "old"}]},
+ )
+ outcome = write_note(
+ mode="edit",
+ notebook_id="nb-1",
+ record_id="r1",
+ notebook_manager=manager,
+ )
+ assert outcome.ok is False
+ assert "at least one" in outcome.error.lower()
+
+
+def test_edit_patches_title_and_content() -> None:
+ manager = _FakeManager(
+ notebooks=[{"id": "nb-1", "name": "N"}],
+ records_by_nb={"nb-1": [{"id": "r1", "title": "old", "output": "old body"}]},
+ )
+ outcome = write_note(
+ mode="edit",
+ notebook_id="nb-1",
+ record_id="r1",
+ title="new title",
+ content="new body",
+ notebook_manager=manager,
+ )
+ assert outcome.ok is True
+ assert outcome.mode == "edit"
+ assert outcome.record_id == "r1"
+ assert manager.last_update == {
+ "notebook_id": "nb-1",
+ "record_id": "r1",
+ "title": "new title",
+ "output": "new body",
+ }
+
+
+def test_edit_surfaces_manager_errors_as_outcome() -> None:
+ manager = _FakeManager(
+ notebooks=[{"id": "nb-1", "name": "N"}],
+ records_by_nb={"nb-1": [{"id": "r1", "title": "old"}]},
+ raise_on_update=True,
+ )
+ outcome = write_note(
+ mode="edit",
+ notebook_id="nb-1",
+ record_id="r1",
+ title="new",
+ notebook_manager=manager,
+ )
+ assert outcome.ok is False
+ assert "Edit failed" in outcome.error
+
+
+# ---------------------------------------------------------------------------
+# Constants / defaults
+# ---------------------------------------------------------------------------
+
+
+def test_default_turns_to_include_is_three() -> None:
+ assert DEFAULT_TURNS_TO_INCLUDE == 3
+
+
+def test_clips_oversized_title_and_note() -> None:
+ manager = _FakeManager(notebooks=[{"id": "nb-1", "name": "N"}])
+ outcome = write_note(
+ mode="append",
+ notebook_id="nb-1",
+ title="x" * (MAX_TITLE_CHARS + 50),
+ note="y" * (MAX_NOTE_CHARS + 100),
+ conversation_history=_SAMPLE_HISTORY,
+ notebook_manager=manager,
+ )
+ assert outcome.ok is True
+ assert manager.last_add["title"].endswith("…")
+ assert len(manager.last_add["title"]) <= MAX_TITLE_CHARS + 1
+ # The clipped note appears in the body with an ellipsis.
+ assert "…" in manager.last_add["output"]
diff --git a/web/components/chat/home/AskUserOptions.tsx b/web/components/chat/home/AskUserOptions.tsx
new file mode 100644
index 000000000..b0e9f2a70
--- /dev/null
+++ b/web/components/chat/home/AskUserOptions.tsx
@@ -0,0 +1,793 @@
+"use client";
+
+import { ChevronDown, ChevronLeft, ChevronRight } from "lucide-react";
+import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+
+import { shouldAppendEventContent } from "@/lib/stream";
+import type { StreamEvent } from "@/lib/unified-ws";
+
+/**
+ * v2 ``ask_user`` payload. Mirrors ``deeptutor.tools.ask_user.AskUserPayload``.
+ *
+ * Every question is rendered as one tab on the card; the user can
+ * switch between tabs freely, answer each (or skip), and submit once
+ * via the footer "Submit answers" button. The frontend always carries
+ * the v2 shape internally — legacy single-question payloads are
+ * normalised at extraction time.
+ */
+export interface AskUserQuestion {
+ id: string;
+ prompt: string;
+ options: string[];
+ allow_free_text: boolean;
+ placeholder: string | null;
+}
+
+export interface AskUserPayload {
+ intro: string | null;
+ questions: AskUserQuestion[];
+}
+
+export interface AskUserAnswer {
+ questionId: string;
+ /** Empty string = skipped / no answer. */
+ text: string;
+}
+
+/**
+ * Bundled data the chat surface reads from an assistant message's
+ * event stream. Always returned together so the card can render in
+ * either ``interactive`` (still waiting on user) or ``resolved``
+ * (read-only Q&A summary) mode without losing its place in chat
+ * history. Returns ``null`` only when the message has no ``ask_user``
+ * tool result at all.
+ */
+export interface AskUserCardData {
+ payload: AskUserPayload;
+ /** Present when the user has submitted; ``null`` while still pending. */
+ answers: AskUserAnswer[] | null;
+ resolved: boolean;
+}
+
+/**
+ * Read the ``ask_user`` card data from an assistant message's events.
+ *
+ * Walks the events forward (oldest first) so multiple ``ask_user``
+ * calls within one turn render as separate Q&A summaries in order.
+ * Today only the *latest* unresolved card is interactive; older ones
+ * are forced into resolved mode by the corresponding ``progress``
+ * event carrying ``ask_user_resolved=true`` (and ideally
+ * ``ask_user_tool_call_id``, used to match resolutions to the right
+ * question card).
+ *
+ * Returns the most-recent card so the caller renders one. (Past turns
+ * with multiple ask_user calls collapse to the last one — surfacing
+ * every one would clutter chat history; the rest are visible in the
+ * underlying tool-trace view anyway.)
+ */
+export function extractAskUserPayload(
+ events: StreamEvent[] | undefined,
+): AskUserCardData | null {
+ if (!events || events.length === 0) return null;
+
+ let latest: {
+ payload: AskUserPayload;
+ toolCallId: string | null;
+ } | null = null;
+ let resolution: {
+ toolCallId: string | null;
+ answers: AskUserAnswer[];
+ text: string;
+ } | null = null;
+
+ for (const event of events) {
+ const meta = (event.metadata ?? {}) as Record<string, unknown>;
+ if (event.type === "tool_result") {
+ const toolMetadata = meta.tool_metadata;
+ if (!toolMetadata || typeof toolMetadata !== "object") continue;
+ const askUser = (toolMetadata as Record<string, unknown>).ask_user;
+ const normalised = normaliseAskUserPayload(askUser);
+ if (!normalised) continue;
+ latest = {
+ payload: normalised,
+ toolCallId:
+ (event as { tool_call_id?: string }).tool_call_id ??
+ (typeof meta.tool_call_id === "string" ? meta.tool_call_id : null),
+ };
+ resolution = null;
+ continue;
+ }
+ if (event.type === "progress" && meta.ask_user_resolved) {
+ const answersRaw = Array.isArray(meta.answers) ? (meta.answers as unknown[]) : [];
+ resolution = {
+ toolCallId:
+ typeof meta.ask_user_tool_call_id === "string"
+ ? meta.ask_user_tool_call_id
+ : null,
+ answers: answersRaw
+ .map((entry) => {
+ if (!entry || typeof entry !== "object") return null;
+ const obj = entry as Record<string, unknown>;
+ const qid = String(obj.questionId || obj.id || "").trim();
+ if (!qid) return null;
+ return { questionId: qid, text: String(obj.text || "") };
+ })
+ .filter((a): a is AskUserAnswer => a !== null),
+ text:
+ typeof meta.reply_preview === "string" ? (meta.reply_preview as string) : "",
+ };
+ }
+ }
+
+ if (!latest) return null;
+
+ if (resolution && (resolution.toolCallId === latest.toolCallId || latest.toolCallId === null)) {
+ const answers =
+ resolution.answers.length > 0
+ ? resolution.answers
+ : // Legacy flat-text resolution: backfill as a single synthetic
+ // answer attached to the (first) question so the resolved view
+ // still has something to display.
+ latest.payload.questions.length > 0
+ ? [
+ {
+ questionId: latest.payload.questions[0].id,
+ text: resolution.text || "",
+ },
+ ]
+ : [];
+ return { payload: latest.payload, answers, resolved: true };
+ }
+
+ return { payload: latest.payload, answers: null, resolved: false };
+}
+
+/**
+ * Interleaved message body. Walks the event stream forward and emits a
+ * sequence of segments in the order they were produced, so that text
+ * generated before an ``ask_user`` tool result renders ABOVE the card
+ * and text generated by the resumed iteration renders BELOW it. The
+ * default chat surface uses this instead of pairing a flat
+ * ``msg.content`` blob with a card stuck at the bottom.
+ *
+ * Each ``ask_user`` tool result becomes its own segment with its own
+ * resolution state — multiple ask_user calls in one turn render as
+ * separate cards in stream order. Only the latest unresolved card is
+ * interactive; resolved cards show their Q&A summary.
+ */
+export type MessageSegment =
+ | { kind: "text"; text: string; key: string }
+ | { kind: "ask_user"; data: AskUserCardData; toolCallId: string | null; key: string };
+
+export function extractMessageSegments(
+ events: StreamEvent[] | undefined,
+): MessageSegment[] {
+ if (!events || events.length === 0) return [];
+
+ const segments: MessageSegment[] = [];
+ // Index of each ask_user segment by tool_call_id so a later
+ // ``progress`` event carrying ``ask_user_resolved`` can flip the
+ // matching card to resolved mode without a second pass.
+ const byToolCall = new Map<string, number>();
+ const seenAskUserCards = new Set<string>();
+ let pendingTextIdx: number | null = null;
+ let seq = 0;
+
+ const ensureTextSegment = () => {
+ if (pendingTextIdx === null) {
+ pendingTextIdx = segments.length;
+ segments.push({ kind: "text", text: "", key: `t${seq++}` });
+ }
+ return pendingTextIdx;
+ };
+
+ for (const event of events) {
+ if (shouldAppendEventContent(event)) {
+ const idx = ensureTextSegment();
+ const seg = segments[idx];
+ if (seg.kind === "text") {
+ segments[idx] = { ...seg, text: seg.text + event.content };
+ }
+ continue;
+ }
+ const meta = (event.metadata ?? {}) as Record<string, unknown>;
+ if (event.type === "tool_result") {
+ const toolMetadata = meta.tool_metadata;
+ if (!toolMetadata || typeof toolMetadata !== "object") continue;
+ const askUser = (toolMetadata as Record<string, unknown>).ask_user;
+ const normalised = normaliseAskUserPayload(askUser);
+ if (!normalised) continue;
+ const toolCallId =
+ (event as { tool_call_id?: string }).tool_call_id ??
+ (typeof meta.tool_call_id === "string" ? meta.tool_call_id : null);
+ const cardKey = toolCallId
+ ? `call:${toolCallId}`
+ : `payload:${JSON.stringify(normalised)}`;
+ if (seenAskUserCards.has(cardKey)) continue;
+ seenAskUserCards.add(cardKey);
+ // Close the current text run so the next text chunk starts a new
+ // segment after this card.
+ pendingTextIdx = null;
+ const idx = segments.length;
+ segments.push({
+ kind: "ask_user",
+ data: { payload: normalised, answers: null, resolved: false },
+ toolCallId,
+ key: `a${seq++}`,
+ });
+ if (toolCallId) byToolCall.set(toolCallId, idx);
+ continue;
+ }
+ if (event.type === "progress" && meta.ask_user_resolved) {
+ const replyToolCallId =
+ typeof meta.ask_user_tool_call_id === "string"
+ ? meta.ask_user_tool_call_id
+ : null;
+ // Match by tool_call_id; fall back to the most recent unresolved
+ // ask_user segment if the resolver did not echo the id back.
+ let targetIdx =
+ replyToolCallId !== null ? byToolCall.get(replyToolCallId) ?? -1 : -1;
+ if (targetIdx < 0) {
+ for (let i = segments.length - 1; i >= 0; i--) {
+ const s = segments[i];
+ if (s.kind === "ask_user" && !s.data.resolved) {
+ targetIdx = i;
+ break;
+ }
+ }
+ }
+ if (targetIdx < 0) continue;
+ const target = segments[targetIdx];
+ if (target.kind !== "ask_user") continue;
+ const answersRaw = Array.isArray(meta.answers) ? (meta.answers as unknown[]) : [];
+ const answers: AskUserAnswer[] = answersRaw
+ .map((entry) => {
+ if (!entry || typeof entry !== "object") return null;
+ const obj = entry as Record<string, unknown>;
+ const qid = String(obj.questionId || obj.id || "").trim();
+ if (!qid) return null;
+ return { questionId: qid, text: String(obj.text || "") };
+ })
+ .filter((a): a is AskUserAnswer => a !== null);
+ const replyText =
+ typeof meta.reply_preview === "string" ? (meta.reply_preview as string) : "";
+ const finalAnswers =
+ answers.length > 0
+ ? answers
+ : target.data.payload.questions.length > 0
+ ? [
+ {
+ questionId: target.data.payload.questions[0].id,
+ text: replyText || "",
+ },
+ ]
+ : [];
+ segments[targetIdx] = {
+ ...target,
+ data: { payload: target.data.payload, answers: finalAnswers, resolved: true },
+ };
+ }
+ }
+
+ // Drop empty trailing/leading text segments so the renderer doesn't
+ // emit blank ``<AssistantResponse>`` nodes.
+ return segments.filter((s) => s.kind !== "text" || s.text.length > 0);
+}
+
+function normaliseAskUserPayload(raw: unknown): AskUserPayload | null {
+ if (!raw || typeof raw !== "object") return null;
+ const obj = raw as Record<string, unknown>;
+
+ // v2 shape: ``{intro?, questions: [...]}``
+ if (Array.isArray(obj.questions)) {
+ const questions: AskUserQuestion[] = [];
+ for (const item of obj.questions) {
+ if (!item || typeof item !== "object") continue;
+ const q = item as Record<string, unknown>;
+ const prompt = String(q.prompt ?? q.question ?? "").trim();
+ if (!prompt) continue;
+ const optionsRaw = Array.isArray(q.options) ? q.options : [];
+ questions.push({
+ id: String(q.id || `q${questions.length + 1}`),
+ prompt,
+ options: optionsRaw
+ .map((o) => String(o ?? "").trim())
+ .filter((o) => o.length > 0),
+ allow_free_text: q.allow_free_text === false ? false : true,
+ placeholder:
+ typeof q.placeholder === "string" && q.placeholder.trim()
+ ? (q.placeholder as string).trim()
+ : null,
+ });
+ }
+ if (questions.length === 0) return null;
+ return {
+ intro:
+ typeof obj.intro === "string" && obj.intro.trim()
+ ? (obj.intro as string).trim()
+ : null,
+ questions,
+ };
+ }
+
+ // Legacy single-question shape from before the multi-question refactor.
+ const prompt = String(obj.question ?? "").trim();
+ if (!prompt) return null;
+ const optionsRaw = Array.isArray(obj.options) ? obj.options : [];
+ return {
+ intro: null,
+ questions: [
+ {
+ id: "q1",
+ prompt,
+ options: optionsRaw
+ .map((o) => String(o ?? "").trim())
+ .filter((o) => o.length > 0),
+ allow_free_text: true,
+ placeholder: null,
+ },
+ ],
+ };
+}
+
+const LETTERS = "ABCDEFGH"; // matches MAX_OPTIONS=8
+
+/**
+ * Render the ``ask_user`` card.
+ *
+ * Two visual modes share the same outer container so the card stays
+ * in place in the message stream — never unmounts. Switches from
+ * ``interactive`` (the agent is still paused) to ``resolved`` (the
+ * user has submitted) once a ``progress`` event with
+ * ``ask_user_resolved=true`` arrives in the message events.
+ */
+export const AskUserOptions = memo(function AskUserOptions({
+ data,
+ onSubmit,
+ collapsible = false,
+ defaultCollapsed = false,
+}: {
+ data: AskUserCardData;
+ onSubmit: (payload: {
+ text?: string;
+ answers?: Array<{ questionId: string; text: string }>;
+ }) => void;
+ /** When true, the resolved Q&A card renders with an inline toggle so
+ * the user can hide / show the question + answer summary. Used by the
+ * research flow once the research phase has started — the historical
+ * Q&A stays addressable but doesn't dominate the bubble. */
+ collapsible?: boolean;
+ /** Only honoured when ``collapsible`` is true. */
+ defaultCollapsed?: boolean;
+}) {
+ if (data.resolved) {
+ return (
+ <ResolvedAskUserCard
+ payload={data.payload}
+ answers={data.answers ?? []}
+ collapsible={collapsible}
+ defaultCollapsed={defaultCollapsed}
+ />
+ );
+ }
+ return <InteractiveAskUserCard payload={data.payload} onSubmit={onSubmit} />;
+});
+AskUserOptions.displayName = "AskUserOptions";
+
+// ---------- interactive mode ----------
+
+const InteractiveAskUserCard = memo(function InteractiveAskUserCard({
+ payload,
+ onSubmit,
+}: {
+ payload: AskUserPayload;
+ onSubmit: (payload: {
+ text?: string;
+ answers?: Array<{ questionId: string; text: string }>;
+ }) => void;
+}) {
+ const { t } = useTranslation();
+ const totalQuestions = payload.questions.length;
+
+ // Committed answer per question. Mirrors whichever input is currently
+ // selected (an option text or the free-text draft) — what gets sent.
+ const [answers, setAnswers] = useState<Record<string, string>>({});
+ // Sticky free-text draft per question. Preserved across option picks
+ // and tab switches so the user never loses what they typed.
+ const [customText, setCustomText] = useState<Record<string, string>>({});
+ // Whether the free-text input is the active choice for a question.
+ // Drives both textarea visibility and the "picked" visual state.
+ const [customSelected, setCustomSelected] = useState<Record<string, boolean>>({});
+ const [activeIdx, setActiveIdx] = useState(0);
+ const [submitted, setSubmitted] = useState(false);
+
+ const activeQuestion = payload.questions[activeIdx] ?? payload.questions[0];
+
+ const allAnswered = useMemo(
+ () => payload.questions.every((q) => (answers[q.id] ?? "").trim().length > 0),
+ [payload.questions, answers],
+ );
+
+ const handleSubmit = useCallback(() => {
+ if (submitted) return;
+ setSubmitted(true);
+ const list: Array<{ questionId: string; text: string }> = payload.questions.map(
+ (q) => ({ questionId: q.id, text: (answers[q.id] ?? "").trim() }),
+ );
+ // Always include a flat ``text`` synopsis for back-compat with any
+ // older server path that only looks at ``text``.
+ const flat = list
+ .map(({ text }) => text || "(skipped)")
+ .filter((s) => s !== "(skipped)")
+ .join(" | ");
+ onSubmit({ text: flat, answers: list });
+ }, [submitted, payload.questions, answers, onSubmit]);
+
+ const pickOption = useCallback((qid: string, text: string) => {
+ setAnswers((prev) => ({ ...prev, [qid]: text }));
+ setCustomSelected((prev) => ({ ...prev, [qid]: false }));
+ }, []);
+
+ const selectCustom = useCallback(
+ (qid: string) => {
+ const draft = (customText[qid] ?? "").trim();
+ setCustomSelected((prev) => ({ ...prev, [qid]: true }));
+ setAnswers((prev) => ({ ...prev, [qid]: draft }));
+ },
+ [customText],
+ );
+
+ const updateCustomText = useCallback((qid: string, text: string) => {
+ setCustomText((prev) => ({ ...prev, [qid]: text }));
+ setCustomSelected((prev) => ({ ...prev, [qid]: true }));
+ setAnswers((prev) => ({ ...prev, [qid]: text.trim() }));
+ }, []);
+
+ return (
+ <div className="mt-3 rounded-2xl border border-[var(--border)] bg-[var(--card)] p-4 shadow-[0_1px_2px_rgba(0,0,0,0.04),0_4px_14px_rgba(0,0,0,0.04)]">
+ <div className="flex items-start gap-3">
+ <div className="flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-[color-mix(in_srgb,var(--foreground)_8%,transparent)] text-[12px] font-semibold text-[var(--foreground)]/70">
+ ?
+ </div>
+ <div className="flex-1">
+ <div className="text-[13px] font-medium leading-snug text-[var(--foreground)]">
+ {payload.intro || t("Please answer to continue.")}
+ </div>
+ <div className="mt-0.5 text-[11px] text-[var(--muted-foreground)]">
+ {submitted
+ ? t("Sending your answers…")
+ : totalQuestions > 1
+ ? t("{{count}} questions — tap a tab to switch.", { count: totalQuestions })
+ : t("Pick an option or type your own to continue.")}
+ </div>
+ </div>
+ </div>
+
+ {totalQuestions > 1 ? (
+ <div className="mt-3 flex flex-wrap gap-1.5">
+ {payload.questions.map((q, idx) => {
+ const isActive = idx === activeIdx;
+ const answered = (answers[q.id] ?? "").trim().length > 0;
+ return (
+ <button
+ key={q.id}
+ type="button"
+ onClick={() => setActiveIdx(idx)}
+ disabled={submitted}
+ className={
+ "flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-[11.5px] font-medium transition-all " +
+ (isActive
+ ? "border-[var(--foreground)]/35 bg-[color-mix(in_srgb,var(--foreground)_5%,transparent)] text-[var(--foreground)]"
+ : "border-[var(--border)] bg-transparent text-[var(--muted-foreground)] hover:border-[var(--foreground)]/25 hover:text-[var(--foreground)]") +
+ " disabled:cursor-not-allowed disabled:opacity-60"
+ }
+ >
+ <span
+ className={
+ "flex h-4 w-4 shrink-0 items-center justify-center rounded-full text-[10px] " +
+ (answered
+ ? "bg-[var(--primary)] text-[var(--primary-foreground)]"
+ : "bg-[var(--muted)]/60 text-[var(--muted-foreground)]")
+ }
+ >
+ {answered ? "✓" : idx + 1}
+ </span>
+ <span className="max-w-[160px] truncate">{q.prompt}</span>
+ </button>
+ );
+ })}
+ </div>
+ ) : null}
+
+ <QuestionBody
+ key={activeQuestion.id}
+ question={activeQuestion}
+ currentAnswer={answers[activeQuestion.id] ?? ""}
+ customDraft={customText[activeQuestion.id] ?? ""}
+ customSelected={!!customSelected[activeQuestion.id]}
+ locked={submitted}
+ onPickOption={(text) => pickOption(activeQuestion.id, text)}
+ onSelectCustom={() => selectCustom(activeQuestion.id)}
+ onCustomTextChange={(text) => updateCustomText(activeQuestion.id, text)}
+ />
+
+ <div className="mt-3 flex items-center justify-between gap-2 border-t border-[var(--border)]/60 pt-3">
+ <div className="flex min-w-0 flex-1 items-center">
+ {totalQuestions > 1 && activeIdx > 0 ? (
+ <button
+ type="button"
+ onClick={() => setActiveIdx((idx) => Math.max(0, idx - 1))}
+ disabled={submitted}
+ className="inline-flex items-center gap-1 rounded-md border border-[var(--border)] bg-transparent px-2.5 py-1.5 text-[12px] font-medium text-[var(--foreground)] transition-colors hover:border-[var(--foreground)]/30 hover:bg-[color-mix(in_srgb,var(--foreground)_4%,transparent)] disabled:cursor-not-allowed disabled:opacity-40"
+ >
+ <ChevronLeft size={14} strokeWidth={2} />
+ <span>{t("Previous question")}</span>
+ </button>
+ ) : (
+ <div className="text-[11.5px] text-[var(--muted-foreground)]">
+ {allAnswered
+ ? t("All questions answered.")
+ : t("Unanswered questions will be submitted as skipped.")}
+ </div>
+ )}
+ </div>
+ {totalQuestions > 1 && activeIdx < totalQuestions - 1 ? (
+ <button
+ type="button"
+ onClick={() =>
+ setActiveIdx((idx) => Math.min(totalQuestions - 1, idx + 1))
+ }
+ disabled={submitted}
+ className="inline-flex items-center gap-1 rounded-md bg-[var(--primary)] px-3 py-1.5 text-[12px] font-medium text-[var(--primary-foreground)] hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-40"
+ >
+ <span>{t("Next question")}</span>
+ <ChevronRight size={14} strokeWidth={2} />
+ </button>
+ ) : (
+ <button
+ type="button"
+ onClick={handleSubmit}
+ disabled={submitted}
+ className="rounded-md bg-[var(--primary)] px-3 py-1.5 text-[12px] font-medium text-[var(--primary-foreground)] hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-40"
+ >
+ {totalQuestions > 1 ? t("Submit answers") : t("Submit")}
+ </button>
+ )}
+ </div>
+ </div>
+ );
+});
+InteractiveAskUserCard.displayName = "InteractiveAskUserCard";
+
+const QuestionBody = memo(function QuestionBody({
+ question,
+ currentAnswer,
+ customDraft,
+ customSelected,
+ locked,
+ onPickOption,
+ onSelectCustom,
+ onCustomTextChange,
+}: {
+ question: AskUserQuestion;
+ currentAnswer: string;
+ customDraft: string;
+ customSelected: boolean;
+ locked: boolean;
+ onPickOption: (text: string) => void;
+ onSelectCustom: () => void;
+ onCustomTextChange: (text: string) => void;
+}) {
+ const { t } = useTranslation();
+ const textareaRef = useRef<HTMLTextAreaElement>(null);
+
+ useEffect(() => {
+ if (customSelected) {
+ textareaRef.current?.focus();
+ }
+ }, [customSelected]);
+
+ return (
+ <>
+ <div className="mt-3 text-[14px] font-medium leading-snug text-[var(--foreground)]">
+ {question.prompt}
+ </div>
+
+ {question.options.length > 0 ? (
+ <div className="mt-2 flex flex-col gap-1.5">
+ {question.options.map((option, idx) => {
+ const letter = LETTERS[idx] ?? String(idx + 1);
+ const isPicked =
+ !customSelected && currentAnswer.trim() === option.trim();
+ return (
+ <button
+ key={`${letter}-${option}`}
+ type="button"
+ onClick={() => !locked && onPickOption(option)}
+ disabled={locked}
+ className={
+ "group flex w-full items-center gap-3 rounded-xl border px-3 py-2 text-left transition-all " +
+ (isPicked
+ ? "border-[var(--primary)]/70 bg-[color-mix(in_srgb,var(--primary)_7%,var(--card))] text-[var(--foreground)]"
+ : "border-[var(--border)] bg-[var(--card)] text-[var(--foreground)] hover:border-[var(--foreground)]/30 hover:bg-[color-mix(in_srgb,var(--foreground)_3%,var(--card))]") +
+ " disabled:cursor-not-allowed disabled:opacity-60"
+ }
+ >
+ <span
+ className={
+ "flex h-6 w-6 shrink-0 items-center justify-center rounded-md text-[12px] font-semibold transition-colors " +
+ (isPicked
+ ? "bg-[var(--primary)] text-[var(--primary-foreground)]"
+ : "bg-[var(--muted)]/70 text-[var(--muted-foreground)] group-hover:bg-[color-mix(in_srgb,var(--foreground)_10%,transparent)] group-hover:text-[var(--foreground)]")
+ }
+ >
+ {letter}
+ </span>
+ <span className="text-[13.5px] leading-snug">{option}</span>
+ </button>
+ );
+ })}
+ </div>
+ ) : null}
+
+ {question.allow_free_text ? (
+ <div className="mt-1.5">
+ {customSelected ? (
+ <div
+ className={
+ "flex items-start gap-3 rounded-xl border px-3 py-2 transition-colors " +
+ "border-[var(--primary)]/70 bg-[color-mix(in_srgb,var(--primary)_5%,var(--card))]"
+ }
+ >
+ <span className="mt-0.5 flex h-6 w-6 shrink-0 items-center justify-center rounded-md bg-[var(--primary)] text-[12px] font-semibold text-[var(--primary-foreground)]">
+ {LETTERS[question.options.length] ?? "+"}
+ </span>
+ <textarea
+ ref={textareaRef}
+ value={customDraft}
+ onChange={(event) => onCustomTextChange(event.target.value)}
+ placeholder={question.placeholder ?? t("Type your reply…")}
+ rows={3}
+ disabled={locked}
+ className="min-h-[2.25rem] w-full resize-y bg-transparent text-[13.5px] leading-snug text-[var(--foreground)] outline-none placeholder:text-[var(--muted-foreground)]/80 disabled:opacity-60"
+ />
+ </div>
+ ) : (
+ <button
+ type="button"
+ onClick={() => !locked && onSelectCustom()}
+ disabled={locked}
+ className="flex w-full items-center gap-3 rounded-xl border border-dashed border-[var(--border)] bg-transparent px-3 py-2 text-left text-[13px] text-[var(--muted-foreground)] transition-colors hover:border-[var(--foreground)]/30 hover:bg-[color-mix(in_srgb,var(--foreground)_3%,transparent)] hover:text-[var(--foreground)] disabled:cursor-not-allowed disabled:opacity-60"
+ >
+ <span className="flex h-6 w-6 shrink-0 items-center justify-center rounded-md bg-[var(--muted)]/70 text-[12px] font-semibold text-[var(--muted-foreground)]">
+ {LETTERS[question.options.length] ?? "+"}
+ </span>
+ <span className="truncate">
+ {customDraft.trim()
+ ? t("Other: {{text}}", { text: customDraft.trim() })
+ : t("Other — write your own reply…")}
+ </span>
+ </button>
+ )}
+ </div>
+ ) : null}
+ </>
+ );
+});
+QuestionBody.displayName = "QuestionBody";
+
+// ---------- resolved (read-only) mode ----------
+
+const ResolvedAskUserCard = memo(function ResolvedAskUserCard({
+ payload,
+ answers,
+ collapsible,
+ defaultCollapsed,
+}: {
+ payload: AskUserPayload;
+ answers: AskUserAnswer[];
+ collapsible: boolean;
+ defaultCollapsed: boolean;
+}) {
+ const { t } = useTranslation();
+ const [collapsed, setCollapsed] = useState(defaultCollapsed && collapsible);
+ // Once the user manually toggles, their choice wins — don't keep
+ // slamming the card closed when ``defaultCollapsed`` re-emits true on
+ // every research-progress re-render.
+ const userToggledRef = useRef(false);
+ const lastIntentRef = useRef(defaultCollapsed);
+ useEffect(() => {
+ if (!collapsible) return;
+ if (userToggledRef.current) return;
+ if (lastIntentRef.current !== defaultCollapsed) {
+ lastIntentRef.current = defaultCollapsed;
+ setCollapsed(defaultCollapsed);
+ }
+ }, [collapsible, defaultCollapsed]);
+
+ const toggleCollapsed = useCallback(() => {
+ userToggledRef.current = true;
+ setCollapsed((c) => !c);
+ }, []);
+
+ const byId = useMemo(() => {
+ const map = new Map<string, string>();
+ for (const a of answers) map.set(a.questionId, a.text);
+ return map;
+ }, [answers]);
+
+ const answeredCount = useMemo(() => {
+ let n = 0;
+ for (const q of payload.questions) {
+ if ((byId.get(q.id) ?? "").trim().length > 0) n += 1;
+ }
+ return n;
+ }, [payload.questions, byId]);
+
+ // Match the look-and-feel of ``ResearchOutlineEditor`` so the two
+ // collapsible cards stack consistently in the merged research bubble.
+ return (
+ <div className="my-2 rounded-lg border border-[var(--border)]/30 bg-[var(--background)] shadow-sm">
+ <button
+ type="button"
+ disabled={!collapsible}
+ onClick={collapsible ? toggleCollapsed : undefined}
+ className={`block w-full text-left ${collapsed ? "" : "border-b border-[var(--border)]/20"} px-4 py-2 ${
+ collapsible
+ ? "cursor-pointer transition-colors hover:bg-[var(--muted-foreground)]/[0.025]"
+ : "cursor-default"
+ }`}
+ >
+ <div className="flex items-center gap-1.5">
+ {collapsible && (
+ <ChevronDown
+ size={12}
+ className={`shrink-0 text-[var(--muted-foreground)]/50 transition-transform ${
+ collapsed ? "-rotate-90" : ""
+ }`}
+ />
+ )}
+ <h3 className="text-[13px] font-semibold text-[var(--foreground)]">
+ {t("Your answers")}
+ </h3>
+ {collapsible && collapsed && (
+ <span className="text-[11px] text-[var(--muted-foreground)]/45">
+ · {answeredCount}/{payload.questions.length} {t("answered")}
+ </span>
+ )}
+ </div>
+ </button>
+ {!collapsed && (
+ <div className="space-y-0 divide-y divide-[var(--border)]/15">
+ {payload.questions.map((q, index) => {
+ const value = (byId.get(q.id) ?? "").trim();
+ return (
+ <div
+ key={q.id}
+ className="flex items-start gap-2 px-3 py-1.5"
+ >
+ <span className="mt-[3px] w-4 shrink-0 text-center text-[11px] font-medium tabular-nums leading-tight text-[var(--muted-foreground)]/30">
+ {index + 1}
+ </span>
+ <div className="min-w-0 flex-1 space-y-0.5">
+ <div className="text-[12px] font-medium leading-snug text-[var(--foreground)]">
+ {q.prompt}
+ </div>
+ <div className="text-[11px] leading-snug text-[var(--muted-foreground)]/70">
+ {value ? (
+ value
+ ) : (
+ <span className="italic">{t("(skipped)")}</span>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ )}
+ </div>
+ );
+});
+ResolvedAskUserCard.displayName = "ResolvedAskUserCard";
diff --git a/web/components/chat/home/AutoErrorBlock.tsx b/web/components/chat/home/AutoErrorBlock.tsx
deleted file mode 100644
index ecbf29cdd..000000000
--- a/web/components/chat/home/AutoErrorBlock.tsx
+++ /dev/null
@@ -1,109 +0,0 @@
-"use client";
-
-import { AlertTriangle, RefreshCcw, SlidersHorizontal } from "lucide-react";
-import { memo } from "react";
-import { useTranslation } from "react-i18next";
-
-interface AutoErrorBlockProps {
- reason: string;
- failureMessage?: string;
- iteration?: number;
- routerRetries?: number;
- onRetry?: () => void;
- onSwitchToManual?: () => void;
-}
-
-/**
- * Prominent terminal-error block for auto-mode turns.
- *
- * Shown when the auto pipeline gave up after exhausting all retries. It
- * surfaces:
- * - the failure reason (router LLM exhausted, terminal error, etc.)
- * - the failure location (iteration, retry counts)
- * - two recovery actions: switch to manual mode, or retry the message
- *
- * Partial successes (capability calls that completed before the failure) are
- * still rendered in the regular ``AutoModeAssistantMessage`` blocks above this
- * one — we deliberately do not duplicate them here.
- */
-const AutoErrorBlock = memo(function AutoErrorBlock({
- reason,
- failureMessage,
- iteration,
- routerRetries,
- onRetry,
- onSwitchToManual,
-}: AutoErrorBlockProps) {
- const { t } = useTranslation();
- const headline = (() => {
- if (reason === "router_llm_exhausted") {
- return t("Auto routing failed: router LLM exhausted retries.");
- }
- return t("Auto routing failed: {{reason}}", { reason });
- })();
-
- const subtitle = (() => {
- const parts: string[] = [];
- if (iteration != null) {
- parts.push(t("at iteration {{n}}", { n: iteration }));
- }
- if (routerRetries != null) {
- parts.push(t("after {{n}} router retries", { n: routerRetries }));
- }
- return parts.join(" · ");
- })();
-
- return (
- <div className="mt-3 overflow-hidden rounded-xl border-2 border-red-300/70 bg-red-50/60 text-[13px] shadow-sm dark:border-red-500/40 dark:bg-red-950/30">
- <div className="flex items-start gap-2.5 px-4 pt-3">
- <AlertTriangle
- size={16}
- strokeWidth={2}
- className="mt-0.5 shrink-0 text-red-600 dark:text-red-400"
- />
- <div className="min-w-0 flex-1">
- <div className="font-semibold text-red-700 dark:text-red-300">
- {headline}
- </div>
- {subtitle ? (
- <div className="mt-0.5 text-[11px] text-red-700/80 dark:text-red-300/80">
- {subtitle}
- </div>
- ) : null}
- {failureMessage ? (
- <div className="mt-2 whitespace-pre-wrap text-[12px] text-red-900/85 dark:text-red-200/85">
- {failureMessage}
- </div>
- ) : null}
- </div>
- </div>
-
- <div className="mt-3 flex flex-wrap items-center gap-2 border-t border-red-200/60 bg-red-100/40 px-4 py-2 dark:border-red-500/25 dark:bg-red-900/20">
- {onSwitchToManual ? (
- <button
- type="button"
- onClick={onSwitchToManual}
- className="inline-flex items-center gap-1.5 rounded-md border border-red-300/60 bg-white px-2.5 py-1 text-[12px] font-medium text-red-700 transition-colors hover:bg-red-50 dark:border-red-500/40 dark:bg-red-950/40 dark:text-red-200 dark:hover:bg-red-900/40"
- >
- <SlidersHorizontal size={12} strokeWidth={1.8} />
- {t("Switch to Manual")}
- </button>
- ) : null}
- {onRetry ? (
- <button
- type="button"
- onClick={onRetry}
- className="inline-flex items-center gap-1.5 rounded-md border border-red-300/60 bg-white px-2.5 py-1 text-[12px] font-medium text-red-700 transition-colors hover:bg-red-50 dark:border-red-500/40 dark:bg-red-950/40 dark:text-red-200 dark:hover:bg-red-900/40"
- >
- <RefreshCcw size={12} strokeWidth={1.8} />
- {t("Try Again")}
- </button>
- ) : null}
- </div>
- </div>
- );
-});
-
-AutoErrorBlock.displayName = "AutoErrorBlock";
-
-export default AutoErrorBlock;
diff --git a/web/components/chat/home/AutoModeAssistantMessage.tsx b/web/components/chat/home/AutoModeAssistantMessage.tsx
deleted file mode 100644
index c455cf796..000000000
--- a/web/components/chat/home/AutoModeAssistantMessage.tsx
+++ /dev/null
@@ -1,468 +0,0 @@
-"use client";
-
-import dynamic from "next/dynamic";
-import { memo, useMemo } from "react";
-import {
- ChevronRight,
- CircleCheck,
- CircleX,
- Loader2,
- RotateCcw,
- type LucideIcon,
-} from "lucide-react";
-import { useTranslation } from "react-i18next";
-import AssistantResponse from "@/components/common/AssistantResponse";
-import { extractMathAnimatorResult } from "@/lib/math-animator-types";
-import { extractQuizQuestions } from "@/lib/quiz-types";
-import type { StreamEvent } from "@/lib/unified-ws";
-import { extractVisualizeResult } from "@/lib/visualize-types";
-import AutoErrorBlock from "./AutoErrorBlock";
-import { CallTracePanel } from "./TracePanels";
-
-const MathAnimatorViewer = dynamic(
- () => import("@/components/math-animator/MathAnimatorViewer"),
- { ssr: false },
-);
-const QuizViewer = dynamic(() => import("@/components/quiz/QuizViewer"), {
- ssr: false,
-});
-const VisualizationViewer = dynamic(
- () => import("@/components/visualize/VisualizationViewer"),
- { ssr: false },
-);
-
-/* -------------------------------------------------------------------------- */
-/* Event partitioning */
-/* -------------------------------------------------------------------------- */
-
-/**
- * Layout block as it appears in the rendered message, top to bottom.
- *
- * Auto turns interleave three streams of events on the wire:
- * - Top-level THINKING (router reasoning before/between/after delegations)
- * - Sub-capability events (everything with a ``parent_call_id`` from the
- * delegation forwarder)
- * - Auto's final CONTENT and RESULT (no ``parent_call_id``)
- *
- * The frontend renders them as:
- * - Inline ``thought`` blocks between collapsible delegation cards
- * - Collapsible ``delegation`` cards (one per sub-capability invocation)
- * - A prominent final synthesis block at the bottom
- * - An ``AutoErrorBlock`` if the turn ended in a terminal failure
- */
-
-type Block =
- | { kind: "thought"; text: string }
- | {
- kind: "delegation";
- callId: string;
- capability: string;
- events: StreamEvent[];
- }
- | { kind: "final"; text: string };
-
-/**
- * ``trace_kind``s we treat as internal retry / pivot markers, NOT as
- * user-visible errors. Anything else surfaces in the error list so a
- * silent backend failure (orchestrator-level exception, etc.) can't leave
- * the chat stuck on an empty user bubble.
- */
-const TRANSIENT_ERROR_TRACE_KINDS = new Set([
- "router_api_error",
- "router_format_error",
- "delegation_retry",
- "same_cap_exhausted",
- "validation_error",
- "atomic_tool_error",
-]);
-
-interface PartitionResult {
- blocks: Block[];
- terminalError: {
- failureReason: string;
- failureMessage: string;
- iteration?: number;
- routerRetries?: number;
- } | null;
- /** Non-terminal top-level error messages (e.g. an uncaught capability
- * exception bubbled up by the orchestrator). Always rendered. */
- surfacedErrors: string[];
- /** True while events for a delegation are still arriving. */
- hasOpenDelegation: boolean;
-}
-
-function partitionEvents(events: StreamEvent[]): PartitionResult {
- const blocks: Block[] = [];
- let terminalError: PartitionResult["terminalError"] = null;
- const surfacedErrors: string[] = [];
- let routerRetries = 0;
- const knownDelegations = new Map<string, Block & { kind: "delegation" }>();
- let openDelegationId: string | null = null;
- let thoughtBuffer: string[] = [];
-
- const flushThought = () => {
- if (thoughtBuffer.length === 0) return;
- const text = thoughtBuffer.join("").trim();
- thoughtBuffer = [];
- if (text) blocks.push({ kind: "thought", text });
- };
-
- for (const event of events) {
- const meta = event.metadata ?? {};
- const parentCallId = meta.parent_call_id as string | undefined;
-
- // Sub-capability event: route into its delegation card.
- if (parentCallId) {
- flushThought();
- let card = knownDelegations.get(parentCallId);
- if (!card) {
- const capName = (meta.delegated_capability as string | undefined) ?? "";
- card = {
- kind: "delegation",
- callId: parentCallId,
- capability: capName,
- events: [],
- };
- knownDelegations.set(parentCallId, card);
- blocks.push(card);
- openDelegationId = parentCallId;
- }
- card.events.push(event);
- // A RESULT event signals the delegation finished.
- if (event.type === "result") {
- openDelegationId = null;
- }
- continue;
- }
-
- // Top-level event.
- if (event.type === "error" && meta.terminal === true) {
- terminalError = {
- failureReason: String(meta.failure_reason ?? "unknown"),
- failureMessage: event.content || "",
- iteration: meta.iteration as number | undefined,
- routerRetries,
- };
- continue;
- }
-
- if (event.type === "error") {
- // Router retry counters live in error metadata on transient failures.
- if (
- typeof meta.retry_count === "number" &&
- meta.trace_kind === "router_api_error"
- ) {
- routerRetries = Math.max(routerRetries, meta.retry_count as number);
- }
- // Any error that is NOT an expected internal retry/pivot marker must be
- // surfaced — otherwise an uncaught backend exception (or a misconfigured
- // LLM) leaves the user staring at a silent chat bubble forever.
- const traceKind = typeof meta.trace_kind === "string" ? meta.trace_kind : "";
- if (!traceKind || !TRANSIENT_ERROR_TRACE_KINDS.has(traceKind)) {
- const msg = (event.content || "").trim();
- if (msg) surfacedErrors.push(msg);
- }
- continue;
- }
-
- // Auto's final synthesis CONTENT (with call_kind="llm_final_response").
- if (
- event.type === "content" &&
- meta.call_kind === "llm_final_response"
- ) {
- flushThought();
- const text = event.content || "";
- if (text) blocks.push({ kind: "final", text });
- continue;
- }
-
- // Inline thinking / observation text that should appear between blocks.
- // We deliberately skip ``stage === "synthesizing"`` events: the
- // synthesizer streams its chunks as THINKING for live-progress UX, but
- // the same text is then emitted as the prominent final CONTENT block
- // immediately after. Without this skip the user sees the synthesis twice
- // (once muted/italic, once prominent).
- if (event.type === "thinking" || event.type === "observation") {
- if (event.stage === "synthesizing") continue;
- const text = event.content || "";
- if (text) thoughtBuffer.push(text);
- continue;
- }
- // Other top-level event types (progress, stage markers) are silent for the
- // user-facing layout but still useful for CallTracePanel debugging — we
- // don't render them here.
- }
- flushThought();
-
- if (terminalError) {
- terminalError.routerRetries = routerRetries;
- }
-
- return {
- blocks,
- terminalError,
- surfacedErrors,
- hasOpenDelegation: openDelegationId !== null,
- };
-}
-
-/* -------------------------------------------------------------------------- */
-/* Delegation card */
-/* -------------------------------------------------------------------------- */
-
-interface DelegationCardProps {
- capability: string;
- events: StreamEvent[];
- isStreaming?: boolean;
- sessionId?: string | null;
- language?: string;
-}
-
-function delegationStatus(events: StreamEvent[]): {
- label: "running" | "success" | "failed" | "retried";
- icon: LucideIcon;
- className: string;
-} {
- const hasError = events.some((e) => e.type === "error");
- const hasResult = events.some((e) => e.type === "result");
- const hasRetry = events.some(
- (e) => e.metadata?.trace_kind === "delegation_retry",
- );
- if (!hasResult && !hasError) {
- return { label: "running", icon: Loader2, className: "text-amber-500 animate-spin" };
- }
- if (hasResult && !hasError) {
- return { label: "success", icon: CircleCheck, className: "text-emerald-500" };
- }
- if (hasResult && hasRetry) {
- return { label: "retried", icon: RotateCcw, className: "text-amber-500" };
- }
- return { label: "failed", icon: CircleX, className: "text-red-500" };
-}
-
-const DelegationCard = memo(function DelegationCard({
- capability,
- events,
- isStreaming,
- sessionId,
- language,
-}: DelegationCardProps) {
- const { t } = useTranslation();
- const status = delegationStatus(events);
- const StatusIcon = status.icon;
-
- // The final RESULT event holds the rich payload we feed the per-capability
- // viewer. We render the typed viewer (QuizViewer / MathAnimatorViewer / ...)
- // inside the collapsed panel so the user can inspect the actual output.
- const resultEvent = useMemo(
- () => events.find((e) => e.type === "result") ?? null,
- [events],
- );
-
- const quizQuestions = useMemo(() => {
- if (capability !== "deep_question" || !resultEvent) return null;
- return extractQuizQuestions(resultEvent.metadata);
- }, [capability, resultEvent]);
- const mathAnimatorResult = useMemo(() => {
- if (capability !== "math_animator" || !resultEvent) return null;
- return extractMathAnimatorResult(resultEvent.metadata);
- }, [capability, resultEvent]);
- const visualizeResult = useMemo(() => {
- if (capability !== "visualize" || !resultEvent) return null;
- return extractVisualizeResult(resultEvent.metadata);
- }, [capability, resultEvent]);
-
- // Markdown content from sub-capabilities that ship a final ``response``
- // string (deep_solve, deep_research) is rendered as plain assistant text.
- const markdownContent = useMemo(() => {
- if (!resultEvent) return "";
- if (quizQuestions || mathAnimatorResult || visualizeResult) return "";
- const meta = resultEvent.metadata as Record<string, unknown> | undefined;
- const response = meta?.response;
- return typeof response === "string" ? response : "";
- }, [resultEvent, quizQuestions, mathAnimatorResult, visualizeResult]);
-
- // Only the sub-capability's *internal* progress/thinking events belong in
- // the trace panel. CONTENT and RESULT are the user-facing payload — they
- // already render via the dedicated viewer / markdown below. Including them
- // would cause big code blocks to appear twice (once in the trace card, once
- // in the viewer).
- const traceableEvents = useMemo(
- () =>
- events.filter(
- (e) => e.type !== "content" && e.type !== "result",
- ),
- [events],
- );
- const hasNestedTrace = useMemo(
- () => traceableEvents.some((e) => Boolean(e.metadata?.call_id)),
- [traceableEvents],
- );
-
- return (
- <details
- // ``open`` defaults to false (collapsed). User clicks the summary to
- // expand. We do NOT auto-open while streaming so the chat stays compact.
- className="group mt-2 rounded-lg border border-[var(--border)]/55 bg-[var(--muted)]/30 transition-colors"
- >
- <summary className="flex cursor-pointer items-center gap-2 px-3 py-2 text-[12px] text-[var(--foreground)] outline-none [&::-webkit-details-marker]:hidden">
- <ChevronRight
- size={12}
- strokeWidth={2}
- className="shrink-0 text-[var(--muted-foreground)] transition-transform group-open:rotate-90"
- />
- <StatusIcon size={13} strokeWidth={1.8} className={status.className} />
- <span className="font-medium">{capability || t("(unknown)")}</span>
- <span className="text-[11px] text-[var(--muted-foreground)]">
- {status.label === "running"
- ? t("running…")
- : status.label === "retried"
- ? t("retried")
- : status.label === "failed"
- ? t("failed")
- : t("done")}
- </span>
- </summary>
- <div className="space-y-2 border-t border-[var(--border)]/40 px-3 py-3">
- {/* Sub-capability's internal trace (planning / reasoning / writing /
- tool calls / etc.). Rendered with ``nested`` so it doesn't clash
- with the parent shell. This is where the user can drill into the
- sub-capability's progress instead of seeing it scattered at the
- top of the auto turn. */}
- {hasNestedTrace ? (
- <CallTracePanel
- events={traceableEvents}
- isStreaming={isStreaming}
- nested
- />
- ) : null}
-
- {/* The sub-capability's final user-facing output. Typed viewer when
- we recognize the result shape, otherwise plain markdown. */}
- {quizQuestions && quizQuestions.length > 0 ? (
- <QuizViewer
- questions={quizQuestions}
- sessionId={sessionId}
- language={language}
- />
- ) : mathAnimatorResult ? (
- <MathAnimatorViewer result={mathAnimatorResult} />
- ) : visualizeResult ? (
- <VisualizationViewer result={visualizeResult} />
- ) : markdownContent ? (
- <AssistantResponse content={markdownContent} />
- ) : isStreaming ? (
- <div className="text-[12px] text-[var(--muted-foreground)]">
- {t("Working…")}
- </div>
- ) : null}
- </div>
- </details>
- );
-});
-
-DelegationCard.displayName = "DelegationCard";
-
-/* -------------------------------------------------------------------------- */
-/* AutoModeAssistantMessage */
-/* -------------------------------------------------------------------------- */
-
-interface AutoModeAssistantMessageProps {
- msg: { content: string; capability?: string; events?: StreamEvent[] };
- isStreaming?: boolean;
- sessionId?: string | null;
- language?: string;
- onRetry?: () => void;
- onSwitchToManual?: () => void;
-}
-
-const AutoModeAssistantMessage = memo(function AutoModeAssistantMessage({
- msg,
- isStreaming,
- sessionId,
- language,
- onRetry,
- onSwitchToManual,
-}: AutoModeAssistantMessageProps) {
- const { t } = useTranslation();
- const events = useMemo(() => msg.events ?? [], [msg.events]);
- const partition = useMemo(() => partitionEvents(events), [events]);
-
- return (
- <div className="space-y-1.5">
- {partition.blocks.map((block, idx) => {
- if (block.kind === "thought") {
- // Inline reasoning between delegations. Use a subtle left accent
- // instead of a boxed/italic treatment so it reads as prose, not
- // as a trace-metadata chunk.
- return (
- <div
- key={`t-${idx}`}
- className="whitespace-pre-wrap border-l-2 border-[var(--primary)]/25 pl-3 py-0.5 text-[13px] leading-relaxed text-[var(--muted-foreground)]"
- >
- {block.text}
- </div>
- );
- }
- if (block.kind === "delegation") {
- return (
- <DelegationCard
- key={block.callId}
- capability={block.capability}
- events={block.events}
- isStreaming={isStreaming && partition.hasOpenDelegation}
- sessionId={sessionId}
- language={language}
- />
- );
- }
- // Final synthesis — rendered prominently as the canonical reply.
- return <AssistantResponse key={`f-${idx}`} content={block.text} />;
- })}
-
- {/* Non-terminal but user-visible errors (typically an uncaught
- orchestrator exception). Don't suppress these — without them the
- user sees nothing when the backend fails silently. */}
- {partition.surfacedErrors.length > 0 ? (
- <div className="space-y-1.5">
- {partition.surfacedErrors.map((msg, idx) => (
- <div
- key={`err-${idx}`}
- className="whitespace-pre-wrap rounded-md border border-red-300/60 bg-red-50/60 px-3 py-2 text-[12.5px] text-red-700 dark:border-red-500/40 dark:bg-red-950/30 dark:text-red-200"
- >
- ✗ {msg}
- </div>
- ))}
- </div>
- ) : null}
-
- {/* Streaming placeholder: while the turn is in flight but the backend
- has not emitted anything user-visible yet, render a subtle
- "thinking" dot so the message bubble doesn't look frozen. */}
- {isStreaming &&
- partition.blocks.length === 0 &&
- partition.surfacedErrors.length === 0 &&
- !partition.terminalError ? (
- <div className="flex items-center gap-2 px-3 py-2 text-[12.5px] text-[var(--muted-foreground)]">
- <span className="inline-flex h-2 w-2 animate-pulse rounded-full bg-[var(--primary)]/60" />
- <span>{t("Thinking…")}</span>
- </div>
- ) : null}
-
- {partition.terminalError ? (
- <AutoErrorBlock
- reason={partition.terminalError.failureReason}
- failureMessage={partition.terminalError.failureMessage}
- iteration={partition.terminalError.iteration}
- routerRetries={partition.terminalError.routerRetries}
- onRetry={onRetry}
- onSwitchToManual={onSwitchToManual}
- />
- ) : null}
- </div>
- );
-});
-
-AutoModeAssistantMessage.displayName = "AutoModeAssistantMessage";
-
-export default AutoModeAssistantMessage;
diff --git a/web/lib/ask-user-state.ts b/web/lib/ask-user-state.ts
new file mode 100644
index 000000000..108652649
--- /dev/null
+++ b/web/lib/ask-user-state.ts
@@ -0,0 +1,71 @@
+import type { StreamEvent } from "./unified-ws";
+
+type MessageWithEvents = {
+ events?: StreamEvent[];
+};
+
+function asRecord(value: unknown): Record<string, unknown> | null {
+ return value && typeof value === "object" && !Array.isArray(value)
+ ? (value as Record<string, unknown>)
+ : null;
+}
+
+function eventBelongsToTurn(event: StreamEvent, turnId?: string | null): boolean {
+ if (!turnId) return true;
+ return !event.turn_id || event.turn_id === turnId;
+}
+
+function askUserPayloadFrom(event: StreamEvent): Record<string, unknown> | null {
+ const meta = asRecord(event.metadata);
+ const toolMetadata = asRecord(meta?.tool_metadata);
+ return asRecord(toolMetadata?.ask_user) ?? asRecord(meta?.ask_user);
+}
+
+function askUserToolCallId(event: StreamEvent): string {
+ const meta = asRecord(event.metadata);
+ return typeof meta?.tool_call_id === "string" ? meta.tool_call_id.trim() : "";
+}
+
+/**
+ * Returns true when a stream contains an ask_user card that has not yet
+ * emitted the matching ask_user_resolved progress event.
+ */
+export function hasPendingAskUser(
+ events: StreamEvent[] | undefined,
+ turnId?: string | null,
+): boolean {
+ const pending = new Set<string>();
+ let anonymousCount = 0;
+
+ for (const event of events ?? []) {
+ if (!eventBelongsToTurn(event, turnId)) continue;
+ const meta = asRecord(event.metadata);
+
+ if (event.type === "tool_result" && askUserPayloadFrom(event)) {
+ const toolCallId = askUserToolCallId(event);
+ pending.add(toolCallId ? `id:${toolCallId}` : `anon:${anonymousCount++}`);
+ continue;
+ }
+
+ if (event.type === "progress" && meta?.ask_user_resolved === true) {
+ const resolvedId =
+ typeof meta.ask_user_tool_call_id === "string"
+ ? meta.ask_user_tool_call_id.trim()
+ : "";
+ if (resolvedId) {
+ pending.delete(`id:${resolvedId}`);
+ } else {
+ pending.clear();
+ }
+ }
+ }
+
+ return pending.size > 0;
+}
+
+export function hasPendingAskUserInMessages(
+ messages: MessageWithEvents[],
+ turnId?: string | null,
+): boolean {
+ return messages.some((message) => hasPendingAskUser(message.events, turnId));
+}
diff --git a/web/tests/ask-user-state.test.ts b/web/tests/ask-user-state.test.ts
new file mode 100644
index 000000000..7492372f7
--- /dev/null
+++ b/web/tests/ask-user-state.test.ts
@@ -0,0 +1,71 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { hasPendingAskUser, hasPendingAskUserInMessages } from "../lib/ask-user-state";
+import type { StreamEvent } from "../lib/unified-ws";
+
+function event(
+ type: StreamEvent["type"],
+ metadata: Record<string, unknown>,
+ turnId = "turn-1",
+): StreamEvent {
+ return {
+ type,
+ source: "test",
+ stage: "rephrasing",
+ content: "",
+ metadata,
+ session_id: "session-1",
+ turn_id: turnId,
+ seq: 1,
+ timestamp: 0,
+ };
+}
+
+test("hasPendingAskUser detects unresolved ask_user tool results", () => {
+ const events = [
+ event("tool_result", {
+ tool_call_id: "call-1",
+ tool_metadata: {
+ ask_user: {
+ questions: [{ id: "scope", prompt: "What scope?" }],
+ },
+ },
+ }),
+ ];
+
+ assert.equal(hasPendingAskUser(events, "turn-1"), true);
+});
+
+test("hasPendingAskUser clears the matching card after ask_user_resolved", () => {
+ const events = [
+ event("tool_result", {
+ tool_call_id: "call-1",
+ tool_metadata: { ask_user: { questions: [{ id: "scope", prompt: "Scope?" }] } },
+ }),
+ event("progress", {
+ ask_user_resolved: true,
+ ask_user_tool_call_id: "call-1",
+ }),
+ ];
+
+ assert.equal(hasPendingAskUser(events, "turn-1"), false);
+});
+
+test("hasPendingAskUserInMessages ignores ask_user cards from other turns", () => {
+ const messages = [
+ {
+ events: [
+ event(
+ "tool_result",
+ {
+ tool_call_id: "call-old",
+ tool_metadata: { ask_user: { questions: [{ id: "q", prompt: "Old?" }] } },
+ },
+ "turn-old",
+ ),
+ ],
+ },
+ ];
+
+ assert.equal(hasPendingAskUserInMessages(messages, "turn-1"), false);
+});